dolibarr 25.0.0-alpha
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-2026 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2025 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2026 William Mead <william@m34d.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22use Luracast\Restler\RestException;
23
24require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
25require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
26
36{
40 public static $FIELDS = array(
41 'socid'
42 );
43
47 public $order;
48
52 public function __construct()
53 {
54 global $db, $conf;
55 $this->db = $db;
56 $this->order = new CommandeFournisseur($this->db);
57 }
58
71 public function get($id)
72 {
73 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
74 throw new RestException(403);
75 }
76
77 $result = $this->order->fetch($id);
78 if (!$result) {
79 throw new RestException(404, 'Supplier order not found');
80 }
81
82 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
83 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
84 }
85
86 $this->order->fetchObjectLinked();
87 return $this->_cleanObjectDatas($this->order);
88 }
89
117 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $product_ids = '', $status = '', $sqlfilters = '', $sqlfilterlines = '', $properties = '', $pagination_data = false)
118 {
119 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
120 throw new RestException(403);
121 }
122
123 $obj_ret = array();
124
125 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
126 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
127
128 // If the internal user must only see his customers, force searching by him
129 $search_sale = 0;
130 if (!DolibarrApiAccess::$user->hasRight("societe", "client", "voir") && !empty($socids)) {
131 $search_sale = DolibarrApiAccess::$user->id;
132 }
133
134 $sql = "SELECT t.rowid";
135 $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur AS t";
136 $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
137 if (!empty($product_ids)) {
138 $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; // We need this table joined to the select in order to filter by product
139 }
140 $sql .= ' WHERE t.entity IN ('.getEntity('supplier_order').')';
141 if (!empty($product_ids)) {
142 $sql .= " AND cd.fk_commande = t.rowid AND cd.fk_product IN (".$this->db->sanitize($product_ids).")";
143 }
144 if ($socids) {
145 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
146 }
147 // An unknown value used to be ignored, so the whole list came back as if it were the filtered one
148 if ((string) $status !== '' && !in_array($status, array('draft', 'validated', 'approved', 'running', 'received_start', 'received_end', 'cancelled', 'refused'), true)) {
149 throw new RestException(400, "Bad value for parameter status. Expected one of: draft, validated, approved, running, received_start, received_end, cancelled, refused");
150 }
151 // Filter by status
152 if ($status == 'draft') {
153 $sql .= " AND t.fk_statut IN (0)";
154 }
155 if ($status == 'validated') {
156 $sql .= " AND t.fk_statut IN (1)";
157 }
158 if ($status == 'approved') {
159 $sql .= " AND t.fk_statut IN (2)";
160 }
161 if ($status == 'running') {
162 $sql .= " AND t.fk_statut IN (3)";
163 }
164 if ($status == 'received_start') {
165 $sql .= " AND t.fk_statut IN (4)";
166 }
167 if ($status == 'received_end') {
168 $sql .= " AND t.fk_statut IN (5)";
169 }
170 if ($status == 'cancelled') {
171 $sql .= " AND t.fk_statut IN (6,7)";
172 }
173 if ($status == 'refused') {
174 $sql .= " AND t.fk_statut IN (9)";
175 }
176 // Search on sale representative
177 if ($search_sale && $search_sale != '-1') {
178 if ($search_sale == -2) {
179 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', 0, 1);
180 } elseif ($search_sale > 0) {
181 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', (int) $search_sale);
182 }
183 }
184 // Add sql filters
185 if ($sqlfilters) {
186 $errormessage = '';
187 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
188 if ($errormessage) {
189 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
190 }
191 }
192 // Add sql filters for lines
193 if ($sqlfilterlines) {
194 $errormessage = '';
195 $sql .= " AND EXISTS (SELECT tl.rowid FROM ".MAIN_DB_PREFIX."commande_fournisseurdet AS tl WHERE tl.fk_commande = t.rowid";
196 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilterlines, $errormessage);
197 $sql .= ")";
198 if ($errormessage) {
199 throw new RestException(400, 'Error when validating parameter sqlfilterlines -> '.$errormessage);
200 }
201 }
202
203 //this query will return total supplier orders with the filters given
204 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
205
206 $sql .= $this->db->order($sortfield, $sortorder);
207 if ($limit) {
208 if ($page < 0) {
209 $page = 0;
210 }
211 $offset = $limit * $page;
212
213 $sql .= $this->db->plimit($limit + 1, $offset);
214 }
215
216 $result = $this->db->query($sql);
217 if ($result) {
218 $i = 0;
219 $num = $this->db->num_rows($result);
220 $min = min($num, ($limit <= 0 ? $num : $limit));
221 while ($i < $min) {
222 $obj = $this->db->fetch_object($result);
223 $order_static = new CommandeFournisseur($this->db);
224 if ($order_static->fetch($obj->rowid)) {
225 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($order_static), $properties);
226 }
227 $i++;
228 }
229 } else {
230 throw new RestException(503, 'Error when retrieve supplier order list : '.$this->db->lasterror());
231 }
232
233 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
234 if ($pagination_data) {
235 $totalsResult = $this->db->query($sqlTotals);
236 $total = $this->db->fetch_object($totalsResult)->total;
237
238 $tmp = $obj_ret;
239 $obj_ret = [];
240
241 $obj_ret['data'] = $tmp;
242 $obj_ret['pagination'] = [
243 'total' => (int) $total,
244 'page' => $page, //count starts from 0
245 'page_count' => (int) ceil((int) $total / $limit),
246 'limit' => $limit
247 ];
248 }
249
250 return $obj_ret;
251 }
252
265 public function post($request_data = null)
266 {
267 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
268 throw new RestException(403, "Insufficiant rights");
269 }
270
271 if (!is_array($request_data)) {
272 $request_data = array();
273 }
274
275 // Check mandatory fields (not using output, only possible exception is important)
276 $this->_validate($request_data);
277
278 foreach ($request_data as $field => $value) {
279 if ($field === 'caller') {
280 // 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
281 $this->order->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
282 continue;
283 }
284
285 $this->order->$field = $this->_checkValForAPI($field, $value, $this->order);
286 }
287 if (!array_keys($request_data, 'date')) {
288 $this->order->date = dol_now();
289 }
290 /* We keep lines as an array
291 if (isset($request_data["lines"])) {
292 $lines = array();
293 foreach ($request_data["lines"] as $line) {
294 array_push($lines, (object) $line);
295 }
296 $this->order->lines = $lines;
297 }*/
298
299 if ($this->order->create(DolibarrApiAccess::$user) < 0) {
300 throw new RestException(500, "Error creating order", array_merge(array($this->order->error), $this->order->errors));
301 }
302 return $this->order->id;
303 }
304
316 public function put($id, $request_data = null)
317 {
318 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
319 throw new RestException(403);
320 }
321
322 $result = $this->order->fetch($id);
323 if (!$result) {
324 throw new RestException(404, 'Supplier order not found');
325 }
326
327 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
328 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
329 }
330
331 foreach ($request_data as $field => $value) {
332 if ($field == 'id') {
333 continue;
334 }
335 if ($field === 'caller') {
336 // 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
337 $this->order->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
338 continue;
339 }
340 if ($field == 'array_options' && is_array($value)) {
341 foreach ($value as $index => $val) {
342 $this->order->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->order);
343 }
344 continue;
345 }
346
347 $this->order->$field = $this->_checkValForAPI($field, $value, $this->order);
348 }
349
350 if ($this->order->update(DolibarrApiAccess::$user)) {
351 return $this->get($id);
352 }
353
354 return false;
355 }
356
371 public function postLine($id, $request_data = null)
372 {
373 if (!DolibarrApiAccess::$user->hasRight('fournisseur', 'commande', 'creer')) {
374 throw new RestException(403);
375 }
376
377 $result = $this->order->fetch($id);
378 if (!$result) {
379 throw new RestException(404, 'Supplier order not found');
380 }
381
382 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
383 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
384 }
385
386 $request_data = (object) $request_data;
387
388 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
389
390 $updateRes = $this->order->addline(
391 $request_data->desc,
392 $request_data->subprice,
393 $request_data->qty,
394 $request_data->tva_tx,
395 $request_data->localtax1_tx,
396 $request_data->localtax2_tx,
397 $request_data->fk_product,
398 $request_data->fk_prod_fourn_price,
399 $request_data->ref_fourn,
400 $request_data->remise_percent,
401 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
402 $request_data->pu_ttc,
403 $request_data->product_type,
404 $request_data->info_bits,
405 $request_data->notrigger,
406 $request_data->date_start,
407 $request_data->date_end,
408 $request_data->array_options,
409 $request_data->fk_unit,
410 $request_data->multicurrency_subprice,
411 $request_data->origin,
412 $request_data->origin_id,
413 $request_data->rang,
414 $request_data->special_code
415 );
416
417 if ($updateRes > 0) {
418 return $updateRes;
419 } else {
420 throw new RestException(400, $this->order->errorsToString());
421 }
422 }
423
434 public function getLine($id, $lineid)
435 {
436 $line = clone $this->loadLineForOperation($id, $lineid);
437 $this->_cleanObjectDatas($line);
438 return $line;
439 }
440
457 public function putLine($id, $lineid, $request_data = null)
458 {
459 if (!DolibarrApiAccess::$user->hasRight('fournisseur', 'commande', 'creer')) {
460 throw new RestException(403, 'Write permission is required');
461 }
462 $line = $this->loadLineForOperation($id, $lineid);
463 if ((int) $this->order->status !== CommandeFournisseur::STATUS_DRAFT) {
464 throw new RestException(409, 'Only draft supplier orders accept line changes');
465 }
466 $line = $this->prepareLineUpdate($line, $request_data);
467 $includingtax = isset($request_data['subprice_ttc']) || (!isset($request_data['subprice']) && $line->wasEnteredIncludingTax());
468 if (isset($request_data['multicurrency_subprice'])) {
469 $line->subprice = 0;
470 $includingtax = false;
471 } elseif ($includingtax || isset($request_data['subprice'])) {
472 $line->multicurrency_subprice = 0;
473 }
474 $vatrate = $line->tva_tx;
475 if (!isset($request_data['tva_tx']) && !empty($line->vat_src_code)) {
476 $vatrate .= ' ('.$line->vat_src_code.')';
477 }
478 if ($this->order->fetch_thirdparty() <= 0) {
479 throw new RestException(500, 'Unable to load supplier for tax calculations');
480 }
481 $result = $this->order->updateline(
482 $lineid, $line->desc, $includingtax ? $line->subprice_ttc : $line->subprice,
483 $line->qty, $line->remise_percent, $vatrate, $line->localtax1_tx, $line->localtax2_tx,
484 $includingtax ? 'TTC' : 'HT', $line->info_bits, $line->product_type, 0,
485 (int) $line->date_start, (int) $line->date_end, $line->array_options, $line->fk_unit,
486 $line->multicurrency_subprice, $line->ref_supplier
487 );
488 if ($result <= 0) {
489 throw new RestException(400, $this->order->errorsToString());
490 }
491
492 $line = new CommandeFournisseurLigne($this->db);
493 if ($line->fetch($lineid) <= 0) {
494 throw new RestException(500, 'Failed to reload the updated line');
495 }
496
497 $this->_cleanObjectDatas($line);
498 return $line;
499 }
500
521 public function deleteLine($id, $lineid)
522 {
523 if (empty($lineid)) {
524 throw new RestException(400, 'Line ID is mandatory');
525 }
526
527 if (!DolibarrApiAccess::$user->hasRight('fournisseur', 'commande', 'creer')) {
528 throw new RestException(403);
529 }
530
531 // Checks read permission and access to the order, and that the line belongs to it
532 $this->loadLineForOperation($id, $lineid);
533
534 if ((int) $this->order->status !== CommandeFournisseur::STATUS_DRAFT) {
535 throw new RestException(405, 'Supplier order must be in draft status to delete lines');
536 }
537
538 $updateRes = $this->order->deleteLine((int) $lineid);
539 if ($updateRes > 0) {
540 return array(
541 'success' => array(
542 'code' => 200,
543 'message' => 'line '.$lineid.' deleted'
544 )
545 );
546 } else {
547 throw new RestException(405, $this->order->errorsToString());
548 }
549 }
550
558 protected function prepareLineUpdate($line, $request_data)
559 {
560 if (!is_array($request_data) || empty($request_data)) {
561 throw new RestException(400, 'A non-empty object of line changes is required');
562 }
563 $pricefields = array_intersect(array_keys($request_data), array('subprice', 'subprice_ttc', 'multicurrency_subprice'));
564 if (count($pricefields) > 1) {
565 throw new RestException(400, 'Give only one unit price: subprice, subprice_ttc or multicurrency_subprice');
566 }
567 $line = clone $line;
568 $allowed = array('desc', 'subprice', 'subprice_ttc', 'qty', 'remise_percent', 'tva_tx', 'localtax1_tx', 'localtax2_tx', 'date_start', 'date_end', 'array_options', 'fk_unit', 'multicurrency_subprice', 'ref_supplier');
569 foreach ($request_data as $field => $value) {
570 if (!in_array($field, $allowed, true)) {
571 throw new RestException(400, 'Unsupported line field: '.$field);
572 }
573 if ($field === 'array_options') {
574 if (!is_array($value)) {
575 throw new RestException(400, 'array_options must be an object');
576 }
577 foreach ($value as $key => $optional) {
578 $line->array_options[$key] = $this->_checkValExtrafieldsForAPI($key, $optional, $line);
579 }
580 } elseif (in_array($field, array('date_start', 'date_end', 'fk_unit'), true)) {
581 if ($value !== null && (!is_numeric($value) || (int) $value != $value || $value < ($field === 'fk_unit' ? 1 : 0))) {
582 throw new RestException(400, 'Expected a valid integer or null for '.$field);
583 }
584 $line->$field = $value === null ? null : (int) $value;
585 } elseif (in_array($field, array('desc', 'ref_supplier'), true)) {
586 if (!is_string($value)) {
587 throw new RestException(400, 'Expected a string for '.$field);
588 }
589 $line->$field = $this->_checkValForAPI($field, $value, $line);
590 } elseif (!is_numeric($value) || !is_finite((float) $value)) {
591 throw new RestException(400, 'Expected a finite numeric value for '.$field);
592 } else {
593 $line->$field = $value;
594 }
595 }
596 if ((float) $line->qty == 0) {
597 throw new RestException(400, 'Quantity must not be zero');
598 }
599 if ($line->date_start && $line->date_end && $line->date_start > $line->date_end) {
600 throw new RestException(400, 'Start date must not be later than end date');
601 }
602 return $line;
603 }
604
611 protected function loadOrderForOperation($id)
612 {
613 if (!DolibarrApiAccess::$user->hasRight('fournisseur', 'commande', 'lire')) {
614 throw new RestException(403, 'Read permission is required');
615 }
616 if ($this->order->fetch($id) <= 0) {
617 throw new RestException(404, 'Supplier order not found');
618 }
619 if (!static::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
620 throw new RestException(403, 'Access denied to supplier order');
621 }
622 }
623
631 protected function loadLineForOperation($id, $lineid)
632 {
634 foreach ($this->order->lines as $line) {
635 if ((int) $line->id === (int) $lineid) {
636 return $line;
637 }
638 }
639 throw new RestException(404, 'Line not found in this supplier order');
640 }
641
658 public function getContacts($id, $source, $type = '')
659 {
660 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
661 throw new RestException(403);
662 }
663
664 $result = $this->order->fetch($id);
665 if (!$result) {
666 throw new RestException(404, 'Supplier order not found');
667 }
668
669 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
670 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
671 }
672 $contacts = array();
673
674 if ($source == 'all' || $source == 'external') {
675 $tmpContacts = $this->order->liste_contact(-1, 'external', 0, $type);
676 $contacts = array_merge($contacts, $tmpContacts);
677 }
678
679 if ($source == 'all' || $source == 'internal') {
680 $tmpContacts = $this->order->liste_contact(-1, 'internal', 0, $type);
681 $contacts = array_merge($contacts, $tmpContacts);
682 }
683
684 return $contacts;
685 }
686
705 public function postContact($id, $contactid, $type, $source)
706 {
707 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
708 throw new RestException(403);
709 }
710
711 $result = $this->order->fetch($id);
712 if (!$result) {
713 throw new RestException(404, 'Supplier order not found');
714 }
715
716 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
717 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
718 }
719
720 $result = $this->order->add_contact($contactid, $type, $source);
721
722 if ($result < 0) {
723 throw new RestException(500, 'Error when added the contact');
724 }
725
726 if ($result == 0) {
727 throw new RestException(304, 'contact already added');
728 }
729
730 return array(
731 'success' => array(
732 'code' => 200,
733 'message' => 'Contact linked to the order'
734 )
735 );
736 }
737
758 public function deleteContact($id, $contactid, $type, $source)
759 {
760 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
761 throw new RestException(403);
762 }
763
764 $result = $this->order->fetch($id);
765 if (!$result) {
766 throw new RestException(404, 'Supplier order not found');
767 }
768
769 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
770 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
771 }
772
773 $contacts = $this->order->liste_contact(-1, $source, 0, $type);
774
775 $contactToUnlink = 0;
776 foreach ($contacts as $contact) {
777 if ($contact['id'] == $contactid && $contact['code'] == $type) {
778 $contactToUnlink = $contact['rowid'];
779 break;
780 }
781 }
782
783 if ($contactToUnlink == 0) {
784 throw new RestException(404, 'Linked contact not found');
785 }
786
787 $result = $this->order->delete_contact($contactToUnlink);
788
789 if (!$result) {
790 throw new RestException(500, 'Error when deleting the contact');
791 }
792
793 return array(
794 'success' => array(
795 'code' => 200,
796 'message' => 'Contact unlinked from supplier order'
797 )
798 );
799 }
800
811 public function delete($id)
812 {
813 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "supprimer")) {
814 throw new RestException(403);
815 }
816 $result = $this->order->fetch($id);
817 if (!$result) {
818 throw new RestException(404, 'Supplier order not found');
819 }
820
821 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
822 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
823 }
824
825 if ($this->order->delete(DolibarrApiAccess::$user) < 0) {
826 throw new RestException(500, 'Error when deleting order');
827 }
828
829 return array(
830 'success' => array(
831 'code' => 200,
832 'message' => 'Supplier order deleted'
833 )
834 );
835 }
836
837
861 public function validate($id, $idwarehouse = 0, $notrigger = 0)
862 {
863 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
864 throw new RestException(403);
865 }
866 $result = $this->order->fetch($id);
867 if (!$result) {
868 throw new RestException(404, 'Order not found');
869 }
870
871 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
872 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
873 }
874
875 $result = $this->order->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger);
876 if ($result == 0) {
877 throw new RestException(304, 'Error nothing done. May be object is already validated');
878 }
879 if ($result < 0) {
880 throw new RestException(500, 'Error when validating Order: '.$this->order->errorsToString());
881 }
882
883 return array(
884 'success' => array(
885 'code' => 200,
886 'message' => 'Order validated (Ref='.$this->order->ref.')'
887 )
888 );
889 }
890
909 public function settodraft($id)
910 {
911 // Same right as checked by the supplier order card before calling CommandeFournisseur::setReopen()
912 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
913 throw new RestException(403);
914 }
915 $result = $this->order->fetch($id);
916 if (!$result) {
917 throw new RestException(404, 'Order not found');
918 }
919
920 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
921 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
922 }
923
924 // Other statuses are reopened one step back by CommandeFournisseur::setReopen(), not set to draft
925 $status = (int) $this->order->status;
927 throw new RestException(405, 'Only validated or approved supplier orders can be set back to draft');
928 }
929
930 // Same rights as the ones showing the "Modify" (validated) and "Disapprove" (approved) buttons on the supplier order card
932 $allowed = DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "commander");
933 } else {
934 $allowed = (DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "approuver")
935 && (!getDolGlobalString('SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY') || DolibarrApiAccess::$user->id == $this->order->user_approve_id))
936 || (DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "approve2") && getDolGlobalString('SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED')
937 && (!getDolGlobalString('SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY') || DolibarrApiAccess::$user->id == $this->order->user_approve_id2));
938 }
939 if (!$allowed) {
940 throw new RestException(403, 'Not allowed to set this supplier order back to draft');
941 }
942
943 $result = $this->order->setReopen(DolibarrApiAccess::$user);
944 if ($result <= 0) {
945 throw new RestException(500, 'Error when setting Order to draft: '.$this->order->errorsToString());
946 }
947
948 return array(
949 'success' => array(
950 'code' => 200,
951 'message' => 'Order set to draft (Ref='.$this->order->ref.')'
952 )
953 );
954 }
955
979 public function approve($id, $idwarehouse = 0, $secondlevel = 0)
980 {
981 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
982 throw new RestException(403);
983 }
984 $result = $this->order->fetch($id);
985 if (!$result) {
986 throw new RestException(404, 'Order not found');
987 }
988
989 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
990 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
991 }
992
993 $result = $this->order->approve(DolibarrApiAccess::$user, $idwarehouse, $secondlevel);
994 if ($result == 0) {
995 throw new RestException(304, 'Error nothing done. May be object is already approved');
996 }
997 if ($result < 0) {
998 throw new RestException(500, 'Error when approve Order: '.$this->order->errorsToString());
999 }
1000
1001 return array(
1002 'success' => array(
1003 'code' => 200,
1004 'message' => 'Order approved (Ref='.$this->order->ref.')'
1005 )
1006 );
1007 }
1008
1035 public function refuse($id, $comment = '')
1036 {
1037 // Same right as checked by CommandeFournisseur::refuse(), which otherwise does nothing and returns 0
1038 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "approuver")) {
1039 throw new RestException(403);
1040 }
1041 $result = $this->order->fetch($id);
1042 if (!$result) {
1043 throw new RestException(404, 'Order not found');
1044 }
1045
1046 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
1047 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1048 }
1049
1050 if ((int) $this->order->status !== CommandeFournisseur::STATUS_VALIDATED) {
1051 throw new RestException(405, 'Only validated supplier orders waiting for approval can be refused');
1052 }
1053
1054 if ((string) $comment !== '') {
1055 $this->order->refuse_note = $comment;
1056 }
1057
1058 $result = $this->order->refuse(DolibarrApiAccess::$user);
1059 if ($result < 0) {
1060 throw new RestException(500, 'Error when refusing Order: '.$this->order->errorsToString());
1061 }
1062
1063 return array(
1064 'success' => array(
1065 'code' => 200,
1066 'message' => 'Order refused (Ref='.$this->order->ref.')'
1067 )
1068 );
1069 }
1070
1071
1097 public function makeOrder($id, $date, $method, $comment = '')
1098 {
1099 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
1100 throw new RestException(403);
1101 }
1102 $result = $this->order->fetch($id);
1103 if (!$result) {
1104 throw new RestException(404, 'Order not found');
1105 }
1106
1107 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
1108 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1109 }
1110
1111 $result = $this->order->commande(DolibarrApiAccess::$user, $date, $method, $comment);
1112 if ($result == 0) {
1113 throw new RestException(304, 'Error nothing done. May be object is already sent');
1114 }
1115 if ($result < 0) {
1116 throw new RestException(500, 'Error when sending Order: '.$this->order->errorsToString());
1117 }
1118
1119 return array(
1120 'success' => array(
1121 'code' => 200,
1122 'message' => 'Order sent (Ref='.$this->order->ref.')'
1123 )
1124 );
1125 }
1126
1153 public function cancel($id, $comment = '')
1154 {
1155 // Same right as checked by CommandeFournisseur::cancel(), which otherwise returns -1 without error message
1156 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "commander")) {
1157 throw new RestException(403);
1158 }
1159 $result = $this->order->fetch($id);
1160 if (!$result) {
1161 throw new RestException(404, 'Order not found');
1162 }
1163
1164 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
1165 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1166 }
1167
1168 // Same status as the one allowing the cancel button on the supplier order card
1169 if ((int) $this->order->status !== CommandeFournisseur::STATUS_ACCEPTED) {
1170 throw new RestException(405, 'Only approved supplier orders can be canceled');
1171 }
1172
1173 if ((string) $comment !== '') {
1174 $this->order->cancel_note = $comment;
1175 }
1176
1177 $result = $this->order->cancel(DolibarrApiAccess::$user);
1178 if ($result < 0) {
1179 throw new RestException(500, 'Error when canceling Order: '.$this->order->errorsToString());
1180 }
1181
1182 return array(
1183 'success' => array(
1184 'code' => 200,
1185 'message' => 'Order canceled (Ref='.$this->order->ref.')'
1186 )
1187 );
1188 }
1189
1229 public function receiveOrder($id, $closeopenorder, $comment, $lines)
1230 {
1231 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
1232 throw new RestException(403);
1233 }
1234 $result = $this->order->fetch($id);
1235 if (!$result) {
1236 throw new RestException(404, 'Order not found');
1237 }
1238
1239 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
1240 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1241 }
1242
1243 foreach ($lines as $line) {
1244 $lineObj = (object) $line;
1245
1246 $result = $this->order->dispatchProduct(
1247 DolibarrApiAccess::$user,
1248 $lineObj->fk_product,
1249 $lineObj->qty,
1250 $lineObj->warehouse,
1251 $lineObj->price,
1252 $lineObj->comment,
1253 $lineObj->eatby,
1254 $lineObj->sellby,
1255 $lineObj->batch,
1256 (int) $lineObj->id,
1257 $lineObj->notrigger
1258 );
1259
1260 if ($result < 0) {
1261 throw new RestException(500, 'Error dispatch order line '.$lineObj->id.': '.$this->order->errorsToString());
1262 }
1263 }
1264
1265 $result = $this->order->calcAndSetStatusDispatch(DolibarrApiAccess::$user, $closeopenorder, $comment);
1266
1267 if ($result == 0) {
1268 throw new RestException(304, 'Error nothing done. May be object is already dispatched');
1269 }
1270 if ($result < 0) {
1271 throw new RestException(500, 'Error when receivce order: '.$this->order->errorsToString());
1272 }
1273
1274 return array(
1275 'success' => array(
1276 'code' => 200,
1277 'message' => 'Order received (Ref='.$this->order->ref.')'
1278 )
1279 );
1280 }
1281
1282 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1292 protected function _cleanObjectDatas($object)
1293 {
1294 // phpcs:enable
1295 $object = parent::_cleanObjectDatas($object);
1296
1297 unset($object->rowid);
1298 unset($object->barcode_type);
1299 unset($object->barcode_type_code);
1300 unset($object->barcode_type_label);
1301 unset($object->barcode_type_coder);
1302
1303 return $object;
1304 }
1305
1314 private function _validate($data)
1315 {
1316 if ($data === null) {
1317 $data = array();
1318 }
1319 $order = array();
1320 foreach (SupplierOrders::$FIELDS as $field) {
1321 if (!isset($data[$field])) {
1322 throw new RestException(400, "$field field missing");
1323 }
1324 $order[$field] = $data[$field];
1325 }
1326 return $order;
1327 }
1328}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage predefined suppliers products.
const STATUS_VALIDATED
Validated status.
Class to manage line orders.
Class for API REST v1.
Definition api.class.php:35
_checkValExtrafieldsForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $parenttableforentity='')
Check access by user to a given resource.
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.
putLine($id, $lineid, $request_data=null)
Update selected fields of a draft supplier order line.
loadOrderForOperation($id)
Load an authorised order without sanitising its live database handle.
deleteLine($id, $lineid)
Deletes a line of a given draft supplier order.
put($id, $request_data=null)
Update supplier order.
settodraft($id)
Set a validated or approved order back to draft.
loadLineForOperation($id, $lineid)
Load the complete line after checking its parent and ownership.
post($request_data=null)
Create supplier order object.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
postLine($id, $request_data=null)
Add a line to a given supplier order.
prepareLineUpdate($line, $request_data)
Prepare a partial update without changing the original line or writing data.
deleteContact($id, $contactid, $type, $source)
Unlink a contact type of given supplier order.
makeOrder($id, $date, $method, $comment='')
Sends an order to the vendor.
refuse($id, $comment='')
Refuse a validated order that is waiting for approval.
postContact($id, $contactid, $type, $source)
Add a contact type of given supplier order.
getLine($id, $lineid)
Get one supplier order line after checking access to its parent.
cancel($id, $comment='')
Cancel an approved order that has not been sent to the vendor yet.
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.
dol_now($mode='gmt')
Return date for now.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.