dolibarr 22.0.5
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 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20use Luracast\Restler\RestException;
21
22require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
23
31{
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
105 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $product_ids = '', $status = '', $sqlfilters = '', $sqlfilterlines = '', $properties = '', $pagination_data = false)
106 {
107 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
108 throw new RestException(403);
109 }
110
111 $obj_ret = array();
112
113 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
114 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
115
116 // If the internal user must only see his customers, force searching by him
117 $search_sale = 0;
118 if (!DolibarrApiAccess::$user->hasRight("societe", "client", "voir") && !empty($socids)) {
119 $search_sale = DolibarrApiAccess::$user->id;
120 }
121
122 $sql = "SELECT t.rowid";
123 $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur AS t";
124 $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
125 if (!empty($product_ids)) {
126 $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; // We need this table joined to the select in order to filter by product
127 }
128 $sql .= ' WHERE t.entity IN ('.getEntity('supplier_order').')';
129 if (!empty($product_ids)) {
130 $sql .= " AND cd.fk_commande = t.rowid AND cd.fk_product IN (".$this->db->sanitize($product_ids).")";
131 }
132 if ($socids) {
133 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
134 }
135 // Filter by status
136 if ($status == 'draft') {
137 $sql .= " AND t.fk_statut IN (0)";
138 }
139 if ($status == 'validated') {
140 $sql .= " AND t.fk_statut IN (1)";
141 }
142 if ($status == 'approved') {
143 $sql .= " AND t.fk_statut IN (2)";
144 }
145 if ($status == 'running') {
146 $sql .= " AND t.fk_statut IN (3)";
147 }
148 if ($status == 'received_start') {
149 $sql .= " AND t.fk_statut IN (4)";
150 }
151 if ($status == 'received_end') {
152 $sql .= " AND t.fk_statut IN (5)";
153 }
154 if ($status == 'cancelled') {
155 $sql .= " AND t.fk_statut IN (6,7)";
156 }
157 if ($status == 'refused') {
158 $sql .= " AND t.fk_statut IN (9)";
159 }
160 // Search on sale representative
161 if ($search_sale && $search_sale != '-1') {
162 if ($search_sale == -2) {
163 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
164 } elseif ($search_sale > 0) {
165 $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).")";
166 }
167 }
168 // Add sql filters
169 if ($sqlfilters) {
170 $errormessage = '';
171 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
172 if ($errormessage) {
173 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
174 }
175 }
176 // Add sql filters for lines
177 if ($sqlfilterlines) {
178 $errormessage = '';
179 $sql .= " AND EXISTS (SELECT tl.rowid FROM ".MAIN_DB_PREFIX."commande_fournisseurdet AS tl WHERE tl.fk_commande = t.rowid";
180 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilterlines, $errormessage);
181 $sql .= ")";
182 if ($errormessage) {
183 throw new RestException(400, 'Error when validating parameter sqlfilterlines -> '.$errormessage);
184 }
185 }
186
187 //this query will return total supplier orders with the filters given
188 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
189
190 $sql .= $this->db->order($sortfield, $sortorder);
191 if ($limit) {
192 if ($page < 0) {
193 $page = 0;
194 }
195 $offset = $limit * $page;
196
197 $sql .= $this->db->plimit($limit + 1, $offset);
198 }
199
200 $result = $this->db->query($sql);
201 if ($result) {
202 $i = 0;
203 $num = $this->db->num_rows($result);
204 $min = min($num, ($limit <= 0 ? $num : $limit));
205 while ($i < $min) {
206 $obj = $this->db->fetch_object($result);
207 $order_static = new CommandeFournisseur($this->db);
208 if ($order_static->fetch($obj->rowid)) {
209 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($order_static), $properties);
210 }
211 $i++;
212 }
213 } else {
214 throw new RestException(503, 'Error when retrieve supplier order list : '.$this->db->lasterror());
215 }
216
217 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
218 if ($pagination_data) {
219 $totalsResult = $this->db->query($sqlTotals);
220 $total = $this->db->fetch_object($totalsResult)->total;
221
222 $tmp = $obj_ret;
223 $obj_ret = [];
224
225 $obj_ret['data'] = $tmp;
226 $obj_ret['pagination'] = [
227 'total' => (int) $total,
228 'page' => $page, //count starts from 0
229 'page_count' => (int) ceil((int) $total / $limit),
230 'limit' => $limit
231 ];
232 }
233
234 return $obj_ret;
235 }
236
247 public function post($request_data = null)
248 {
249 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
250 throw new RestException(403, "Insuffisant rights");
251 }
252
253 if (!is_array($request_data)) {
254 $request_data = array();
255 }
256
257 // Check mandatory fields (not using output, only possible exception is important)
258 $this->_validate($request_data);
259
260 foreach ($request_data as $field => $value) {
261 if ($field === 'caller') {
262 // 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
263 $this->order->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
264 continue;
265 }
266
267 $this->order->$field = $this->_checkValForAPI($field, $value, $this->order);
268 }
269 if (!array_keys($request_data, 'date')) {
270 $this->order->date = dol_now();
271 }
272 /* We keep lines as an array
273 if (isset($request_data["lines"])) {
274 $lines = array();
275 foreach ($request_data["lines"] as $line) {
276 array_push($lines, (object) $line);
277 }
278 $this->order->lines = $lines;
279 }*/
280
281 if ($this->order->create(DolibarrApiAccess::$user) < 0) {
282 throw new RestException(500, "Error creating order", array_merge(array($this->order->error), $this->order->errors));
283 }
284 return $this->order->id;
285 }
286
296 public function put($id, $request_data = null)
297 {
298 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
299 throw new RestException(403);
300 }
301
302 $result = $this->order->fetch($id);
303 if (!$result) {
304 throw new RestException(404, 'Supplier order not found');
305 }
306
307 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
308 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
309 }
310
311 foreach ($request_data as $field => $value) {
312 if ($field == 'id') {
313 continue;
314 }
315 if ($field === 'caller') {
316 // 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
317 $this->order->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
318 continue;
319 }
320 if ($field == 'array_options' && is_array($value)) {
321 foreach ($value as $index => $val) {
322 $this->order->array_options[$index] = $this->_checkValForAPI($field, $val, $this->order);
323 }
324 continue;
325 }
326
327 $this->order->$field = $this->_checkValForAPI($field, $value, $this->order);
328 }
329
330 if ($this->order->update(DolibarrApiAccess::$user)) {
331 return $this->get($id);
332 }
333
334 return false;
335 }
336
351 public function getContacts($id, $source, $type = '')
352 {
353 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
354 throw new RestException(403);
355 }
356
357 $result = $this->order->fetch($id);
358 if (!$result) {
359 throw new RestException(404, 'Supplier order not found');
360 }
361
362 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
363 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
364 }
365 $contacts = array();
366
367 if ($source == 'all' || $source == 'external') {
368 $tmpContacts = $this->order->liste_contact(-1, 'external', 0, $type);
369 $contacts = array_merge($contacts, $tmpContacts);
370 }
371
372 if ($source == 'all' || $source == 'internal') {
373 $tmpContacts = $this->order->liste_contact(-1, 'internal', 0, $type);
374 $contacts = array_merge($contacts, $tmpContacts);
375 }
376
377 return $this->_cleanObjectDatas($contacts);
378 }
379
396 public function postContact($id, $contactid, $type, $source)
397 {
398 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
399 throw new RestException(403);
400 }
401
402 $result = $this->order->fetch($id);
403 if (!$result) {
404 throw new RestException(404, 'Supplier order not found');
405 }
406
407 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
408 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
409 }
410
411 $result = $this->order->add_contact($contactid, $type, $source);
412
413 if ($result < 0) {
414 throw new RestException(500, 'Error when added the contact');
415 }
416
417 if ($result == 0) {
418 throw new RestException(304, 'contact already added');
419 }
420
421 return array(
422 'success' => array(
423 'code' => 200,
424 'message' => 'Contact linked to the order'
425 )
426 );
427 }
428
447 public function deleteContact($id, $contactid, $type, $source)
448 {
449 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
450 throw new RestException(403);
451 }
452
453 $result = $this->order->fetch($id);
454 if (!$result) {
455 throw new RestException(404, 'Supplier order not found');
456 }
457
458 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
459 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
460 }
461
462 $contacts = $this->order->liste_contact(-1, $source, 0, $type);
463
464 $contactToUnlink = 0;
465 foreach ($contacts as $contact) {
466 if ($contact['id'] == $contactid && $contact['code'] == $type) {
467 $contactToUnlink = $contact['rowid'];
468 break;
469 }
470 }
471
472 if ($contactToUnlink == 0) {
473 throw new RestException(404, 'Linked contact not found');
474 }
475
476 $result = $this->order->delete_contact($contact['rowid']);
477
478 if (!$result) {
479 throw new RestException(500, 'Error when deleted the contact');
480 }
481
482 return array(
483 'success' => array(
484 'code' => 200,
485 'message' => 'Contact unlinked from supplier order'
486 )
487 );
488 }
489
498 public function delete($id)
499 {
500 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "supprimer")) {
501 throw new RestException(403);
502 }
503 $result = $this->order->fetch($id);
504 if (!$result) {
505 throw new RestException(404, 'Supplier order not found');
506 }
507
508 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
509 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
510 }
511
512 if ($this->order->delete(DolibarrApiAccess::$user) < 0) {
513 throw new RestException(500, 'Error when deleting order');
514 }
515
516 return array(
517 'success' => array(
518 'code' => 200,
519 'message' => 'Supplier order deleted'
520 )
521 );
522 }
523
524
546 public function validate($id, $idwarehouse = 0, $notrigger = 0)
547 {
548 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
549 throw new RestException(403);
550 }
551 $result = $this->order->fetch($id);
552 if (!$result) {
553 throw new RestException(404, 'Order not found');
554 }
555
556 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
557 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
558 }
559
560 $result = $this->order->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger);
561 if ($result == 0) {
562 throw new RestException(304, 'Error nothing done. May be object is already validated');
563 }
564 if ($result < 0) {
565 throw new RestException(500, 'Error when validating Order: '.$this->order->error);
566 }
567
568 return array(
569 'success' => array(
570 'code' => 200,
571 'message' => 'Order validated (Ref='.$this->order->ref.')'
572 )
573 );
574 }
575
597 public function approve($id, $idwarehouse = 0, $secondlevel = 0)
598 {
599 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
600 throw new RestException(403);
601 }
602 $result = $this->order->fetch($id);
603 if (!$result) {
604 throw new RestException(404, 'Order not found');
605 }
606
607 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
608 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
609 }
610
611 $result = $this->order->approve(DolibarrApiAccess::$user, $idwarehouse, $secondlevel);
612 if ($result == 0) {
613 throw new RestException(304, 'Error nothing done. May be object is already approved');
614 }
615 if ($result < 0) {
616 throw new RestException(500, 'Error when approve Order: '.$this->order->error);
617 }
618
619 return array(
620 'success' => array(
621 'code' => 200,
622 'message' => 'Order approved (Ref='.$this->order->ref.')'
623 )
624 );
625 }
626
627
651 public function makeOrder($id, $date, $method, $comment = '')
652 {
653 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
654 throw new RestException(403);
655 }
656 $result = $this->order->fetch($id);
657 if (!$result) {
658 throw new RestException(404, 'Order not found');
659 }
660
661 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
662 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
663 }
664
665 $result = $this->order->commande(DolibarrApiAccess::$user, $date, $method, $comment);
666 if ($result == 0) {
667 throw new RestException(304, 'Error nothing done. May be object is already sent');
668 }
669 if ($result < 0) {
670 throw new RestException(500, 'Error when sending Order: '.$this->order->error);
671 }
672
673 return array(
674 'success' => array(
675 'code' => 200,
676 'message' => 'Order sent (Ref='.$this->order->ref.')'
677 )
678 );
679 }
680
718 public function receiveOrder($id, $closeopenorder, $comment, $lines)
719 {
720 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
721 throw new RestException(403);
722 }
723 $result = $this->order->fetch($id);
724 if (!$result) {
725 throw new RestException(404, 'Order not found');
726 }
727
728 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
729 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
730 }
731
732 foreach ($lines as $line) {
733 $lineObj = (object) $line;
734
735 $result = $this->order->dispatchProduct(
736 DolibarrApiAccess::$user,
737 $lineObj->fk_product,
738 $lineObj->qty,
739 $lineObj->warehouse,
740 $lineObj->price,
741 $lineObj->comment,
742 $lineObj->eatby,
743 $lineObj->sellby,
744 $lineObj->batch,
745 (int) $lineObj->id,
746 $lineObj->notrigger
747 );
748
749 if ($result < 0) {
750 throw new RestException(500, 'Error dispatch order line '.$lineObj->id.': '.$this->order->error);
751 }
752 }
753
754 $result = $this->order->calcAndSetStatusDispatch(DolibarrApiAccess::$user, $closeopenorder, $comment);
755
756 if ($result == 0) {
757 throw new RestException(304, 'Error nothing done. May be object is already dispatched');
758 }
759 if ($result < 0) {
760 throw new RestException(500, 'Error when receivce order: '.$this->order->error);
761 }
762
763 return array(
764 'success' => array(
765 'code' => 200,
766 'message' => 'Order received (Ref='.$this->order->ref.')'
767 )
768 );
769 }
770
771 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
778 protected function _cleanObjectDatas($object)
779 {
780 // phpcs:enable
781 $object = parent::_cleanObjectDatas($object);
782
783 unset($object->rowid);
784 unset($object->barcode_type);
785 unset($object->barcode_type_code);
786 unset($object->barcode_type_label);
787 unset($object->barcode_type_coder);
788
789 return $object;
790 }
791
800 private function _validate($data)
801 {
802 if ($data === null) {
803 $data = array();
804 }
805 $order = array();
806 foreach (SupplierOrders::$FIELDS as $field) {
807 if (!isset($data[$field])) {
808 throw new RestException(400, "$field field missing");
809 }
810 $order[$field] = $data[$field];
811 }
812 return $order;
813 }
814}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
Class to manage predefined suppliers products.
Class for API REST v1.
Definition api.class.php:33
_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:98
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