dolibarr 21.0.0-beta
api_supplier_orders.class.php
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use Luracast\Restler\RestException;
20
21require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
22
30{
35 public static $FIELDS = array(
36 'socid'
37 );
38
42 public $order;
43
47 public function __construct()
48 {
49 global $db, $conf;
50 $this->db = $db;
51 $this->order = new CommandeFournisseur($this->db);
52 }
53
64 public function get($id)
65 {
66 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
67 throw new RestException(403);
68 }
69
70 $result = $this->order->fetch($id);
71 if (!$result) {
72 throw new RestException(404, 'Supplier order not found');
73 }
74
75 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
76 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
77 }
78
79 $this->order->fetchObjectLinked();
80 return $this->_cleanObjectDatas($this->order);
81 }
82
103 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $product_ids = '', $status = '', $sqlfilters = '', $sqlfilterlines = '', $properties = '', $pagination_data = false)
104 {
105 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
106 throw new RestException(403);
107 }
108
109 $obj_ret = array();
110
111 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
112 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
113
114 // If the internal user must only see his customers, force searching by him
115 $search_sale = 0;
116 if (!DolibarrApiAccess::$user->hasRight("societe", "client", "voir") && !empty($socids)) {
117 $search_sale = DolibarrApiAccess::$user->id;
118 }
119
120 $sql = "SELECT t.rowid";
121 $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur AS t";
122 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseur_extrafields AS ef ON (ef.fk_object = t.rowid)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call, so we will be able to filter on extrafields
123 if (!empty($product_ids)) {
124 $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; // We need this table joined to the select in order to filter by product
125 }
126 $sql .= ' WHERE t.entity IN ('.getEntity('supplier_order').')';
127 if (!empty($product_ids)) {
128 $sql .= " AND cd.fk_commande = t.rowid AND cd.fk_product IN (".$this->db->sanitize($product_ids).")";
129 }
130 if ($socids) {
131 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
132 }
133 // Filter by status
134 if ($status == 'draft') {
135 $sql .= " AND t.fk_statut IN (0)";
136 }
137 if ($status == 'validated') {
138 $sql .= " AND t.fk_statut IN (1)";
139 }
140 if ($status == 'approved') {
141 $sql .= " AND t.fk_statut IN (2)";
142 }
143 if ($status == 'running') {
144 $sql .= " AND t.fk_statut IN (3)";
145 }
146 if ($status == 'received_start') {
147 $sql .= " AND t.fk_statut IN (4)";
148 }
149 if ($status == 'received_end') {
150 $sql .= " AND t.fk_statut IN (5)";
151 }
152 if ($status == 'cancelled') {
153 $sql .= " AND t.fk_statut IN (6,7)";
154 }
155 if ($status == 'refused') {
156 $sql .= " AND t.fk_statut IN (9)";
157 }
158 // Search on sale representative
159 if ($search_sale && $search_sale != '-1') {
160 if ($search_sale == -2) {
161 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
162 } elseif ($search_sale > 0) {
163 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
164 }
165 }
166 // Add sql filters
167 if ($sqlfilters) {
168 $errormessage = '';
169 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
170 if ($errormessage) {
171 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
172 }
173 }
174 // Add sql filters for lines
175 if ($sqlfilterlines) {
176 $errormessage = '';
177 $sql .= " AND EXISTS (SELECT tl.rowid FROM ".MAIN_DB_PREFIX."commande_fournisseurdet AS tl WHERE tl.fk_commande = t.rowid";
178 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilterlines, $errormessage);
179 $sql .= ")";
180 if ($errormessage) {
181 throw new RestException(400, 'Error when validating parameter sqlfilterlines -> '.$errormessage);
182 }
183 }
184
185 //this query will return total supplier orders with the filters given
186 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
187
188 $sql .= $this->db->order($sortfield, $sortorder);
189 if ($limit) {
190 if ($page < 0) {
191 $page = 0;
192 }
193 $offset = $limit * $page;
194
195 $sql .= $this->db->plimit($limit + 1, $offset);
196 }
197
198 $result = $this->db->query($sql);
199 if ($result) {
200 $i = 0;
201 $num = $this->db->num_rows($result);
202 $min = min($num, ($limit <= 0 ? $num : $limit));
203 while ($i < $min) {
204 $obj = $this->db->fetch_object($result);
205 $order_static = new CommandeFournisseur($this->db);
206 if ($order_static->fetch($obj->rowid)) {
207 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($order_static), $properties);
208 }
209 $i++;
210 }
211 } else {
212 throw new RestException(503, 'Error when retrieve supplier order list : '.$this->db->lasterror());
213 }
214
215 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
216 if ($pagination_data) {
217 $totalsResult = $this->db->query($sqlTotals);
218 $total = $this->db->fetch_object($totalsResult)->total;
219
220 $tmp = $obj_ret;
221 $obj_ret = [];
222
223 $obj_ret['data'] = $tmp;
224 $obj_ret['pagination'] = [
225 'total' => (int) $total,
226 'page' => $page, //count starts from 0
227 'page_count' => ceil((int) $total / $limit),
228 'limit' => $limit
229 ];
230 }
231
232 return $obj_ret;
233 }
234
243 public function post($request_data = null)
244 {
245 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
246 throw new RestException(403, "Insuffisant rights");
247 }
248 // Check mandatory fields
249 $result = $this->_validate($request_data);
250
251 foreach ($request_data as $field => $value) {
252 if ($field === 'caller') {
253 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
254 $this->order->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
255 continue;
256 }
257
258 $this->order->$field = $this->_checkValForAPI($field, $value, $this->order);
259 }
260 if (!array_keys($request_data, 'date')) {
261 $this->order->date = dol_now();
262 }
263 /* We keep lines as an array
264 if (isset($request_data["lines"])) {
265 $lines = array();
266 foreach ($request_data["lines"] as $line) {
267 array_push($lines, (object) $line);
268 }
269 $this->order->lines = $lines;
270 }*/
271
272 if ($this->order->create(DolibarrApiAccess::$user) < 0) {
273 throw new RestException(500, "Error creating order", array_merge(array($this->order->error), $this->order->errors));
274 }
275 return $this->order->id;
276 }
277
285 public function put($id, $request_data = null)
286 {
287 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
288 throw new RestException(403);
289 }
290
291 $result = $this->order->fetch($id);
292 if (!$result) {
293 throw new RestException(404, 'Supplier order not found');
294 }
295
296 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
297 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
298 }
299
300 foreach ($request_data as $field => $value) {
301 if ($field == 'id') {
302 continue;
303 }
304 if ($field === 'caller') {
305 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
306 $this->order->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
307 continue;
308 }
309 if ($field == 'array_options' && is_array($value)) {
310 foreach ($value as $index => $val) {
311 $this->order->array_options[$index] = $this->_checkValForAPI($field, $val, $this->order);
312 }
313 continue;
314 }
315 $this->order->$field = $this->_checkValForAPI($field, $value, $this->order);
316 }
317
318 if ($this->order->update(DolibarrApiAccess::$user)) {
319 return $this->get($id);
320 }
321
322 return false;
323 }
324
339 public function getContacts($id, $source, $type = '')
340 {
341 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
342 throw new RestException(403);
343 }
344
345 $result = $this->order->fetch($id);
346 if (!$result) {
347 throw new RestException(404, 'Supplier order not found');
348 }
349
350 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
351 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
352 }
353 $contacts = array();
354
355 if ($source == 'all' || $source == 'external') {
356 $tmpContacts = $this->order->liste_contact(-1, 'external', 0, $type);
357 $contacts = array_merge($contacts, $tmpContacts);
358 }
359
360 if ($source == 'all' || $source == 'internal') {
361 $tmpContacts = $this->order->liste_contact(-1, 'internal', 0, $type);
362 $contacts = array_merge($contacts, $tmpContacts);
363 }
364
365 return $this->_cleanObjectDatas($contacts);
366 }
367
382 public function postContact($id, $contactid, $type, $source)
383 {
384 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
385 throw new RestException(403);
386 }
387
388 $result = $this->order->fetch($id);
389 if (!$result) {
390 throw new RestException(404, 'Supplier order not found');
391 }
392
393 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
394 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
395 }
396
397 $result = $this->order->add_contact($contactid, $type, $source);
398
399 if ($result < 0) {
400 throw new RestException(500, 'Error when added the contact');
401 }
402
403 if ($result == 0) {
404 throw new RestException(304, 'contact already added');
405 }
406
407 return array(
408 'success' => array(
409 'code' => 200,
410 'message' => 'Contact linked to the order'
411 )
412 );
413 }
414
431 public function deleteContact($id, $contactid, $type, $source)
432 {
433 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
434 throw new RestException(403);
435 }
436
437 $result = $this->order->fetch($id);
438 if (!$result) {
439 throw new RestException(404, 'Supplier order not found');
440 }
441
442 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
443 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
444 }
445
446 $contacts = $this->order->liste_contact(-1, $source, 0, $type);
447
448 $contactToUnlink = 0;
449 foreach ($contacts as $contact) {
450 if ($contact['id'] == $contactid && $contact['code'] == $type) {
451 $contactToUnlink = $contact['rowid'];
452 break;
453 }
454 }
455
456 if ($contactToUnlink == 0) {
457 throw new RestException(404, 'Linked contact not found');
458 }
459
460 $result = $this->order->delete_contact($contact['rowid']);
461
462 if (!$result) {
463 throw new RestException(500, 'Error when deleted the contact');
464 }
465
466 return array(
467 'success' => array(
468 'code' => 200,
469 'message' => 'Contact unlinked from supplier order'
470 )
471 );
472 }
473
480 public function delete($id)
481 {
482 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "supprimer")) {
483 throw new RestException(403);
484 }
485 $result = $this->order->fetch($id);
486 if (!$result) {
487 throw new RestException(404, 'Supplier order not found');
488 }
489
490 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
491 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
492 }
493
494 if ($this->order->delete(DolibarrApiAccess::$user) < 0) {
495 throw new RestException(500, 'Error when deleting order');
496 }
497
498 return array(
499 'success' => array(
500 'code' => 200,
501 'message' => 'Supplier order deleted'
502 )
503 );
504 }
505
506
525 public function validate($id, $idwarehouse = 0, $notrigger = 0)
526 {
527 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
528 throw new RestException(403);
529 }
530 $result = $this->order->fetch($id);
531 if (!$result) {
532 throw new RestException(404, 'Order not found');
533 }
534
535 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
536 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
537 }
538
539 $result = $this->order->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger);
540 if ($result == 0) {
541 throw new RestException(304, 'Error nothing done. May be object is already validated');
542 }
543 if ($result < 0) {
544 throw new RestException(500, 'Error when validating Order: '.$this->order->error);
545 }
546
547 return array(
548 'success' => array(
549 'code' => 200,
550 'message' => 'Order validated (Ref='.$this->order->ref.')'
551 )
552 );
553 }
554
573 public function approve($id, $idwarehouse = 0, $secondlevel = 0)
574 {
575 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
576 throw new RestException(403);
577 }
578 $result = $this->order->fetch($id);
579 if (!$result) {
580 throw new RestException(404, 'Order not found');
581 }
582
583 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
584 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
585 }
586
587 $result = $this->order->approve(DolibarrApiAccess::$user, $idwarehouse, $secondlevel);
588 if ($result == 0) {
589 throw new RestException(304, 'Error nothing done. May be object is already approved');
590 }
591 if ($result < 0) {
592 throw new RestException(500, 'Error when approve Order: '.$this->order->error);
593 }
594
595 return array(
596 'success' => array(
597 'code' => 200,
598 'message' => 'Order approved (Ref='.$this->order->ref.')'
599 )
600 );
601 }
602
603
624 public function makeOrder($id, $date, $method, $comment = '')
625 {
626 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
627 throw new RestException(403);
628 }
629 $result = $this->order->fetch($id);
630 if (!$result) {
631 throw new RestException(404, 'Order not found');
632 }
633
634 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
635 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
636 }
637
638 $result = $this->order->commande(DolibarrApiAccess::$user, $date, $method, $comment);
639 if ($result == 0) {
640 throw new RestException(304, 'Error nothing done. May be object is already sent');
641 }
642 if ($result < 0) {
643 throw new RestException(500, 'Error when sending Order: '.$this->order->error);
644 }
645
646 return array(
647 'success' => array(
648 'code' => 200,
649 'message' => 'Order sent (Ref='.$this->order->ref.')'
650 )
651 );
652 }
653
687 public function receiveOrder($id, $closeopenorder, $comment, $lines)
688 {
689 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
690 throw new RestException(403);
691 }
692 $result = $this->order->fetch($id);
693 if (!$result) {
694 throw new RestException(404, 'Order not found');
695 }
696
697 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
698 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
699 }
700
701 foreach ($lines as $line) {
702 $lineObj =(object) $line;
703
704 $result=$this->order->dispatchProduct(
705 DolibarrApiAccess::$user,
706 $lineObj->fk_product,
707 $lineObj->qty,
708 $lineObj->warehouse,
709 $lineObj->price,
710 $lineObj->comment,
711 $lineObj->eatby,
712 $lineObj->sellby,
713 $lineObj->batch,
714 $lineObj->id,
715 $lineObj->notrigger
716 );
717
718 if ($result < 0) {
719 throw new RestException(500, 'Error dispatch order line '.$line->id.': '.$this->order->error);
720 }
721 }
722
723 $result = $this->order->calcAndSetStatusDispatch(DolibarrApiAccess::$user, $closeopenorder, $comment);
724
725 if ($result == 0) {
726 throw new RestException(304, 'Error nothing done. May be object is already dispatched');
727 }
728 if ($result < 0) {
729 throw new RestException(500, 'Error when receivce order: '.$this->order->error);
730 }
731
732 return array(
733 'success' => array(
734 'code' => 200,
735 'message' => 'Order received (Ref='.$this->order->ref.')'
736 )
737 );
738 }
739
740 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
747 protected function _cleanObjectDatas($object)
748 {
749 // phpcs:enable
750 $object = parent::_cleanObjectDatas($object);
751
752 unset($object->rowid);
753 unset($object->barcode_type);
754 unset($object->barcode_type_code);
755 unset($object->barcode_type_label);
756 unset($object->barcode_type_coder);
757
758 return $object;
759 }
760
769 private function _validate($data)
770 {
771 $order = array();
772 foreach (SupplierOrders::$FIELDS as $field) {
773 if (!isset($data[$field])) {
774 throw new RestException(400, "$field field missing");
775 }
776 $order[$field] = $data[$field];
777 }
778 return $order;
779 }
780}
$id
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
Class to manage predefined suppliers products.
Class for API REST v1.
Definition api.class.php:30
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:82
validate($id, $idwarehouse=0, $notrigger=0)
Validate an order.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $product_ids='', $status='', $sqlfilters='', $sqlfilterlines='', $properties='', $pagination_data=false)
List orders.
put($id, $request_data=null)
Update supplier order.
post($request_data=null)
Create supplier order object.
_cleanObjectDatas($object)
Clean sensible object datas.
deleteContact($id, $contactid, $type, $source)
Unlink a contact type of given supplier order.
makeOrder($id, $date, $method, $comment='')
Sends an order to the vendor.
postContact($id, $contactid, $type, $source)
Add a contact type of given supplier order.
getContacts($id, $source, $type='')
Get contacts of given supplier order.
_validate($data)
Validate fields before create or update object.
approve($id, $idwarehouse=0, $secondlevel=0)
Approve an order.
receiveOrder($id, $closeopenorder, $comment, $lines)
Receives the order, dispatches products.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79