dolibarr 23.0.4
api_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) 2024-2025 Frédéric France <frederic.france@free.fr>
5 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21use Luracast\Restler\RestException;
22
23require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
24
31class Orders extends DolibarrApi
32{
36 public static $FIELDS = array(
37 'socid',
38 'date'
39 );
40
44 public $commande;
45
49 public function __construct()
50 {
51 global $db;
52
53 $this->db = $db;
54 $this->commande = new Commande($this->db);
55 }
56
68 public function get($id, $contact_list = -1)
69 {
70 return $this->_fetch($id, '', '', $contact_list);
71 }
72
86 public function getByRef($ref, $contact_list = -1)
87 {
88 return $this->_fetch(0, $ref, '', $contact_list);
89 }
90
104 public function getByRefExt($ref_ext, $contact_list = -1)
105 {
106 return $this->_fetch(0, '', $ref_ext, $contact_list);
107 }
108
122 private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = -1)
123 {
124 if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
125 throw new RestException(403);
126 }
127 if (empty($id) && empty($ref) && empty($ref_ext)) {
128 throw new RestException(400, 'No ID or Ref provided');
129 }
130 $result = $this->commande->fetch($id, $ref, $ref_ext);
131 if (!$result) {
132 throw new RestException(404, 'Order not found');
133 }
134
135 if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
136 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
137 }
138
139 if ($contact_list > -1) {
140 // Add external contacts ids
141 $tmparray = $this->commande->liste_contact(-1, 'external', $contact_list);
142 if (is_array($tmparray)) {
143 $this->commande->contacts_ids = $tmparray;
144 }
145 $tmparray = $this->commande->liste_contact(-1, 'internal', $contact_list);
146 if (is_array($tmparray)) {
147 $this->commande->contacts_ids_internal = $tmparray;
148 }
149 }
150
151 $this->commande->fetchObjectLinked();
152
153 // Add online_payment_url, cf #20477
154 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
155 $this->commande->online_payment_url = getOnlinePaymentUrl(0, 'order', $this->commande->ref);
156
157 return $this->_cleanObjectDatas($this->commande);
158 }
159
182 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '', $sqlfilterlines = '', $properties = '', $pagination_data = false, $loadlinkedobjects = 0)
183 {
184 global $hookmanager;
185
186 if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
187 throw new RestException(403);
188 }
189
190 $obj_ret = array();
191
192 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
193 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
194
195 // If the internal user must only see his customers, force searching by him
196 $search_sale = 0;
197 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
198 $search_sale = DolibarrApiAccess::$user->id;
199 }
200
201 $sql = "SELECT t.rowid";
202 $sql .= " FROM ".MAIN_DB_PREFIX."commande AS t";
203 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe AS s ON (s.rowid = t.fk_soc)";
204 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_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
205 $sql .= ' WHERE t.entity IN ('.getEntity('commande').')';
206 if ($socids) {
207 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
208 }
209 // Search on sale representative
210 if ($search_sale && $search_sale != '-1') {
211 if ($search_sale == -2) {
212 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
213 } elseif ($search_sale > 0) {
214 $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).")";
215 }
216 }
217 $parameters = array();
218 $hookmanager->executeHooks('printFieldListWhere', $parameters, $this->commande); // Note that $action and $object may have been modified by hook
219 $sql .= $hookmanager->resPrint;
220 // Add sql filters
221 if ($sqlfilters) {
222 $errormessage = '';
223 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
224 if ($errormessage) {
225 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
226 }
227 }
228 // Add sql filters for lines
229 if ($sqlfilterlines) {
230 $errormessage = '';
231 $sql .= " AND EXISTS (SELECT tl.rowid FROM ".MAIN_DB_PREFIX."commandedet AS tl WHERE tl.fk_commande = t.rowid";
232 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilterlines, $errormessage);
233 $sql .= ")";
234 if ($errormessage) {
235 throw new RestException(400, 'Error when validating parameter sqlfilterlines -> '.$errormessage);
236 }
237 }
238
239 //this query will return total orders with the filters given
240 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
241
242 $sql .= $this->db->order($sortfield, $sortorder);
243 if ($limit) {
244 if ($page < 0) {
245 $page = 0;
246 }
247 $offset = $limit * $page;
248
249 $sql .= $this->db->plimit($limit + 1, $offset);
250 }
251
252 dol_syslog("API Rest request");
253 $result = $this->db->query($sql);
254
255 if ($result) {
256 $num = $this->db->num_rows($result);
257 $min = min($num, ($limit <= 0 ? $num : $limit));
258 $i = 0;
259 while ($i < $min) {
260 $obj = $this->db->fetch_object($result);
261 $commande_static = new Commande($this->db);
262 if ($commande_static->fetch($obj->rowid) > 0) {
263 // Add external contacts ids
264 $tmparray = $commande_static->liste_contact(-1, 'external', 1);
265 if (is_array($tmparray)) {
266 $commande_static->contacts_ids = $tmparray;
267 }
268
269 if ($loadlinkedobjects) {
270 // retrieve linked objects
271 $commande_static->fetchObjectLinked();
272 }
273
274 // Add online_payment_url, cf #20477
275 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
276 $commande_static->online_payment_url = getOnlinePaymentUrl(0, 'order', $commande_static->ref);
277
278 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($commande_static), $properties);
279 }
280 $i++;
281 }
282 } else {
283 throw new RestException(503, 'Error when retrieve commande list : '.$this->db->lasterror());
284 }
285
286 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
287 if ($pagination_data) {
288 $totalsResult = $this->db->query($sqlTotals);
289 $total = $this->db->fetch_object($totalsResult)->total;
290
291 $tmp = $obj_ret;
292 $obj_ret = [];
293
294 $obj_ret['data'] = $tmp;
295 $obj_ret['pagination'] = [
296 'total' => (int) $total,
297 'page' => $page, //count starts from 0
298 'page_count' => ceil((int) $total / $limit),
299 'limit' => $limit
300 ];
301 }
302
303 return $obj_ret;
304 }
305
316 public function post($request_data = null)
317 {
318 global $conf;
319 if (!DolibarrApiAccess::$user->hasRight('commande', 'creer')) {
320 throw new RestException(403, "Insufficiant rights");
321 }
322
323 // Check mandatory fields
324 $this->_validate($request_data);
325
326 // Check thirdparty validity
327 $socid = (int) $request_data['socid'];
328 $thirdpartytmp = new Societe($this->db);
329 $thirdparty_result = $thirdpartytmp->fetch($socid);
330 if ($thirdparty_result < 1) {
331 throw new RestException(404, 'Thirdparty with id='.$socid.' not found or not allowed');
332 }
333 if (!DolibarrApi::_checkAccessToResource('societe', $thirdpartytmp->id)) {
334 throw new RestException(404, 'Thirdparty with id='.$thirdpartytmp->id.' not found or not allowed');
335 }
336
337 foreach ($request_data as $field => $value) {
338 if ($field === 'caller') {
339 // 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
340 $this->commande->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
341 continue;
342 }
343 if ($field == 'id') {
344 throw new RestException(400, 'Creating with id field is forbidden');
345 }
346 if ($field == 'entity' && ((int) $value) != ((int) $conf->entity)) {
347 throw new RestException(403, 'Creating with entity='.((int) $value).' MUST be the same entity='.((int) $conf->entity).' as your API user/key belongs to');
348 }
349
350 $this->commande->$field = $this->_checkValForAPI($field, $value, $this->commande);
351 }
352 /*if (isset($request_data["lines"])) {
353 $lines = array();
354 foreach ($request_data["lines"] as $line) {
355 array_push($lines, (object) $line);
356 }
357 $this->commande->lines = $lines;
358 }*/
359
360 if ($this->commande->create(DolibarrApiAccess::$user) < 0) {
361 throw new RestException(500, "Error creating order", array_merge(array($this->commande->error), $this->commande->errors));
362 }
363
364 return ((int) $this->commande->id);
365 }
366
378 public function getLines($id)
379 {
380 if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
381 throw new RestException(403);
382 }
383
384 $result = $this->commande->fetch($id);
385 if (!$result) {
386 throw new RestException(404, 'Order not found');
387 }
388
389 if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
390 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
391 }
392 $this->commande->getLinesArray();
393 $result = array();
394 foreach ($this->commande->lines as $line) {
395 array_push($result, $this->_cleanObjectDatas($line));
396 }
397 return $result;
398 }
399
411 public function getLine($id, $lineid, $properties = '')
412 {
413 if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
414 throw new RestException(403);
415 }
416
417 $result = $this->commande->fetch($id);
418 if (!$result) {
419 throw new RestException(404, 'Order not found');
420 }
421
422 if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
423 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
424 }
425
426 $this->commande->fetch_lines();
427 foreach ($this->commande->lines as $line) {
428 if ($line->id == $lineid) {
429 return $this->_filterObjectProperties($this->_cleanObjectDatas($line), $properties);
430 }
431 }
432 throw new RestException(404, 'Line not found');
433 }
434
447 public function postLine($id, $request_data = null)
448 {
449 if (!DolibarrApiAccess::$user->hasRight('commande', 'creer')) {
450 throw new RestException(403);
451 }
452
453 $result = $this->commande->fetch($id);
454 if (!$result) {
455 throw new RestException(404, 'Order not found');
456 }
457
458 if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
459 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
460 }
461
462 $request_data = (object) $request_data;
463
464 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
465 $request_data->label = sanitizeVal($request_data->label);
466
467 $updateRes = $this->commande->addline(
468 $request_data->desc,
469 $request_data->subprice,
470 $request_data->qty,
471 $request_data->tva_tx,
472 $request_data->localtax1_tx,
473 $request_data->localtax2_tx,
474 $request_data->fk_product,
475 $request_data->remise_percent,
476 $request_data->info_bits,
477 $request_data->fk_remise_except,
478 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
479 $request_data->subprice,
480 $request_data->date_start,
481 $request_data->date_end,
482 $request_data->product_type,
483 $request_data->rang,
484 $request_data->special_code,
485 $request_data->fk_parent_line,
486 $request_data->fk_fournprice,
487 $request_data->pa_ht,
488 $request_data->label,
489 $request_data->array_options,
490 $request_data->fk_unit,
491 $request_data->origin,
492 $request_data->origin_id,
493 $request_data->multicurrency_subprice,
494 $request_data->ref_ext
495 );
496
497 if ($updateRes > 0) {
498 return $updateRes;
499 } else {
500 throw new RestException(400, $this->commande->error);
501 }
502 }
503
516 public function putLine($id, $lineid, $request_data = null)
517 {
518 if (!DolibarrApiAccess::$user->hasRight('commande', 'creer')) {
519 throw new RestException(403);
520 }
521
522 $result = $this->commande->fetch($id);
523 if (!$result) {
524 throw new RestException(404, 'Order not found');
525 }
526
527 if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
528 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
529 }
530
531 $request_data = (object) $request_data;
532
533 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
534 $request_data->label = sanitizeVal($request_data->label);
535
536 $orderline = new OrderLine($this->db);
537 $result = $orderline->fetch($lineid);
538 if (!$result) {
539 throw new RestException(404, 'Order line not found');
540 }
541
542 if ($orderline->fk_commande != $id) {
543 throw new RestException(403, 'Line does not belong to this order');
544 }
545
546 $updateRes = $this->commande->updateline(
547 $lineid,
548 $request_data->desc,
549 $request_data->subprice,
550 $request_data->qty,
551 $request_data->remise_percent,
552 $request_data->tva_tx,
553 $request_data->localtax1_tx,
554 $request_data->localtax2_tx,
555 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
556 $request_data->info_bits,
557 $request_data->date_start,
558 $request_data->date_end,
559 $request_data->product_type,
560 $request_data->fk_parent_line,
561 0,
562 $request_data->fk_fournprice,
563 $request_data->pa_ht,
564 $request_data->label,
565 $request_data->special_code,
566 $request_data->array_options,
567 $request_data->fk_unit,
568 $request_data->multicurrency_subprice,
569 0,
570 $request_data->ref_ext,
571 $request_data->rang
572 );
573
574 if ($updateRes > 0) {
575 $result = $this->get($id);
576 unset($result->line);
577 return $this->_cleanObjectDatas($result);
578 }
579 return false;
580 }
581
594 public function deleteLine($id, $lineid)
595 {
596 if (!DolibarrApiAccess::$user->hasRight('commande', 'creer')) {
597 throw new RestException(403);
598 }
599
600 $result = $this->commande->fetch($id);
601 if (!$result) {
602 throw new RestException(404, 'Order not found');
603 }
604
605 if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
606 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
607 }
608
609 $updateRes = $this->commande->deleteLine(DolibarrApiAccess::$user, $lineid, $id);
610 if ($updateRes > 0) {
611 return $this->get($id);
612 } else {
613 throw new RestException(405, $this->commande->error);
614 }
615 }
616
630 public function getContacts($id, $type = '')
631 {
632 if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
633 throw new RestException(403);
634 }
635
636 $result = $this->commande->fetch($id);
637 if (!$result) {
638 throw new RestException(404, 'Order not found');
639 }
640
641 if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
642 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
643 }
644
645 $contacts = $this->commande->liste_contact(-1, 'external', 0, $type);
646 $socpeoples = $this->commande->liste_contact(-1, 'internal', 0, $type);
647
648 $contacts = array_merge($contacts, $socpeoples);
649
650 return $contacts;
651 }
652
672 public function postContact($id, $contactid, $type, $source = "external", $notrigger = 0)
673 {
674 if (!DolibarrApiAccess::$user->hasRight('commande', 'creer')) {
675 throw new RestException(403);
676 }
677
678 // test source
679 if (empty($source)) {
680 throw new RestException(400, 'Source can not be empty');
681 }
682 $sql_distinct_source = "SELECT DISTINCT source";
683 $sql_distinct_source .= " FROM ".MAIN_DB_PREFIX."c_type_contact";
684 $sql_distinct_source .= " WHERE element LIKE 'commande'";
685 $sql_distinct_source .= " AND source is NOT NULL";
686 $sql_distinct_source .= " AND active != 0";
687 $source_result = $this->db->query($sql_distinct_source);
688 $source_array = array();
689
690 if ($source_result) {
691 $num = $this->db->num_rows($source_result);
692 $i = 0;
693 while ($i < $num) {
694 $obj = $this->db->fetch_object($source_result);
695 $source_kind = (string) $obj->source;
696 array_push($source_array, $source_kind);
697 dol_syslog("source_kind=".$source_kind);
698 $i++;
699 }
700 } else {
701 throw new RestException(503, 'Error when retrieving a list of order contact sources: '.$this->db->lasterror());
702 }
703 if (!in_array($source, (array) $source_array, true)) {
704 throw new RestException(400, 'Combo of Source='.$source.' and Type='.$type.' not found in dictionary with active order contact types');
705 }
706
707 // test type
708 if (empty($type)) {
709 throw new RestException(400, 'type can not be empty');
710 }
711 // variable called type here, but code in dictionary and database
712 $sql_distinct_type = "SELECT DISTINCT code";
713 $sql_distinct_type .= " FROM ".MAIN_DB_PREFIX."c_type_contact";
714 $sql_distinct_type .= " WHERE element LIKE 'commande'";
715 $sql_distinct_type .= " AND source='".$this->db->escape($source)."'";
716 $sql_distinct_type .= " AND code is NOT NULL";
717 $sql_distinct_type .= " AND active != 0";
718 $type_result = $this->db->query($sql_distinct_type);
719 $type_array = array();
720
721 if ($type_result) {
722 $num = $this->db->num_rows($type_result);
723 $i = 0;
724 while ($i < $num) {
725 $obj = $this->db->fetch_object($type_result);
726 // variable called type here, but code in dictionary and database
727 $type_kind = (string) $obj->code;
728 array_push($type_array, $type_kind);
729 dol_syslog("type_kind=".$type_kind);
730 $i++;
731 }
732 } else {
733 throw new RestException(503, 'Error when retrieving a list of order contact types: '.$this->db->lasterror());
734 }
735 if (!in_array($type, (array) $type_array, true)) {
736 throw new RestException(400, 'Combo of Type='.$type.' and Source='.$source.' not found in dictionary with active order contact types');
737 }
738
739 // tests done, let's get it
740 $result = $this->commande->fetch($id);
741 if (!$result) {
742 throw new RestException(404, 'Order not found');
743 }
744 if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
745 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
746 }
747
748 $result = $this->commande->add_contact($contactid, $type, $source, $notrigger);
749
750 if ($result == 0) {
751 throw new RestException(400, 'Already exists: Contact='.$contactid.' is already linked to the order='.$id.' as source='.$source.' and type='.$type);
752 } elseif ($result == -1) {
753 throw new RestException(400, 'Wrong contact='.$contactid);
754 } elseif ($result == -2) {
755 throw new RestException(400, 'Wrong type='.$type);
756 } elseif ($result == -3) {
757 throw new RestException(400, 'Not allowed contacts');
758 } elseif ($result == -4) {
759 throw new RestException(400, 'ErrorCommercialNotAllowedForThirdparty');
760 } elseif ($result == -5) {
761 throw new RestException(400, 'Trigger failed');
762 } elseif ($result == -6) {
763 throw new RestException(400, 'DB_ERROR_RECORD_ALREADY_EXISTS');
764 } elseif ($result == -7) {
765 throw new RestException(400, 'Some other error');
766 }
767
768 return array(
769 'success' => array(
770 'code' => 200,
771 'message' => 'Contact='.$contactid.' linked to the order='.$id.' as '.$source.' '.$type
772 )
773 );
774 }
775
793 public function deleteContact($id, $contactid, $type)
794 {
795 if (!DolibarrApiAccess::$user->hasRight('commande', 'creer')) {
796 throw new RestException(403);
797 }
798
799 $result = $this->commande->fetch($id);
800 if (!$result) {
801 throw new RestException(404, 'Order not found');
802 }
803
804 if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
805 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
806 }
807
808 foreach (array('internal', 'external') as $source) {
809 $contacts = $this->commande->liste_contact(-1, $source);
810 foreach ($contacts as $contact) {
811 if ($contact['id'] == $contactid && $contact['code'] == $type) {
812 $result = $this->commande->delete_contact($contact['rowid']);
813
814 if (!$result) {
815 throw new RestException(500, 'Error when deleting the contact '.$contact['rowid']);
816 }
817 }
818 }
819 }
820
821 return array(
822 'success' => array(
823 'code' => 200,
824 'message' => 'Contact unlinked from order'
825 )
826 );
827 }
828
838 public function put($id, $request_data = null)
839 {
840 if (!DolibarrApiAccess::$user->hasRight('commande', 'creer')) {
841 throw new RestException(403);
842 }
843 if ($id == 0) {
844 throw new RestException(400, 'No order with id=0 can exist');
845 }
846 $result = $this->commande->fetch($id);
847 if (!$result) {
848 throw new RestException(404, 'Order not found');
849 }
850
851 if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
852 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
853 }
854 foreach ($request_data as $field => $value) {
855 if ($field == 'id') {
856 continue;
857 }
858 if ($field === 'caller') {
859 // 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
860 $this->commande->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
861 continue;
862 }
863 if ($field == 'array_options' && is_array($value)) {
864 foreach ($value as $index => $val) {
865 $this->commande->array_options[$index] = $this->_checkValForAPI($field, $val, $this->commande);
866 }
867 continue;
868 }
869
870 $this->commande->$field = $this->_checkValForAPI($field, $value, $this->commande);
871 }
872
873 // Update availability
874 if (!empty($this->commande->availability_id)) {
875 if ($this->commande->availability($this->commande->availability_id) < 0) {
876 throw new RestException(400, 'Error while updating availability');
877 }
878 }
879
880 if ($this->commande->update(DolibarrApiAccess::$user) > 0) {
881 return $this->get($id);
882 } else {
883 throw new RestException(500, $this->commande->error);
884 }
885 }
886
895 public function delete($id)
896 {
897 if (!DolibarrApiAccess::$user->hasRight('commande', 'supprimer')) {
898 throw new RestException(403);
899 }
900 if ($id == 0) {
901 throw new RestException(400, 'No order with id=0 can exist');
902 }
903 $result = $this->commande->fetch($id);
904 if (!$result) {
905 throw new RestException(404, 'Order not found');
906 }
907
908 if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
909 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
910 }
911
912 if ($this->commande->delete(DolibarrApiAccess::$user) <= 0) {
913 throw new RestException(500, 'Error when deleting order : '.$this->commande->error);
914 }
915
916 return array(
917 'success' => array(
918 'code' => 200,
919 'message' => 'Order deleted'
920 )
921 );
922 }
923
945 public function validate($id, $idwarehouse = 0, $notrigger = 0)
946 {
947 if (!DolibarrApiAccess::$user->hasRight('commande', 'creer')) {
948 throw new RestException(403);
949 }
950 $result = $this->commande->fetch($id);
951 if (!$result) {
952 throw new RestException(404, 'Order not found');
953 }
954
955 $result = $this->commande->fetch_thirdparty(); // do not check result, as failure is not fatal (used only for mail notification substitutes)
956
957 if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
958 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
959 }
960
961 $result = $this->commande->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger);
962 if ($result == 0) {
963 throw new RestException(304, 'Error nothing done. May be object is already validated');
964 }
965 if ($result < 0) {
966 throw new RestException(500, 'Error when validating Order: '.$this->commande->error);
967 }
968 $result = $this->commande->fetch($id);
969
970 $this->commande->fetchObjectLinked();
971
972 //fix #20477 : add online_payment_url
973 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
974 $this->commande->online_payment_url = getOnlinePaymentUrl(0, 'order', $this->commande->ref);
975
976 return $this->_cleanObjectDatas($this->commande);
977 }
978
996 public function reopen($id)
997 {
998 if (!DolibarrApiAccess::$user->hasRight('commande', 'creer')) {
999 throw new RestException(403);
1000 }
1001 if (empty($id)) {
1002 throw new RestException(400, 'Order ID is mandatory');
1003 }
1004 $result = $this->commande->fetch($id);
1005 if (!$result) {
1006 throw new RestException(404, 'Order not found');
1007 }
1008
1009 $result = $this->commande->set_reopen(DolibarrApiAccess::$user);
1010 if ($result < 0) {
1011 throw new RestException(405, $this->commande->error);
1012 } elseif ($result == 0) {
1013 throw new RestException(304);
1014 }
1015
1016 return $result;
1017 }
1018
1032 public function setinvoiced($id)
1033 {
1034 if (!DolibarrApiAccess::$user->hasRight('commande', 'creer')) {
1035 throw new RestException(403);
1036 }
1037 if (empty($id)) {
1038 throw new RestException(400, 'Order ID is mandatory');
1039 }
1040 $result = $this->commande->fetch($id);
1041 if (!$result) {
1042 throw new RestException(404, 'Order not found');
1043 }
1044
1045 $result = $this->commande->classifyBilled(DolibarrApiAccess::$user);
1046 if ($result < 0) {
1047 throw new RestException(400, $this->commande->error);
1048 }
1049
1050 $result = $this->commande->fetch($id);
1051 if (!$result) {
1052 throw new RestException(404, 'Order not found');
1053 }
1054
1055 if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
1056 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1057 }
1058
1059 $this->commande->fetchObjectLinked();
1060
1061 return $this->_cleanObjectDatas($this->commande);
1062 }
1063
1073 public function close($id, $notrigger = 0)
1074 {
1075 if (!DolibarrApiAccess::$user->hasRight('commande', 'creer')) {
1076 throw new RestException(403);
1077 }
1078 $result = $this->commande->fetch($id);
1079 if (!$result) {
1080 throw new RestException(404, 'Order not found');
1081 }
1082
1083 if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
1084 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1085 }
1086
1087 $result = $this->commande->cloture(DolibarrApiAccess::$user, $notrigger);
1088 if ($result == 0) {
1089 throw new RestException(304, 'Error nothing done. May be object is already closed');
1090 }
1091 if ($result < 0) {
1092 throw new RestException(500, 'Error when closing Order: '.$this->commande->error);
1093 }
1094
1095 $result = $this->commande->fetch($id);
1096 if (!$result) {
1097 throw new RestException(404, 'Order not found');
1098 }
1099
1100 // test already done
1101 // if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
1102 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1103 // }
1104
1105 $this->commande->fetchObjectLinked();
1106
1107 return $this->_cleanObjectDatas($this->commande);
1108 }
1109
1119 public function settodraft($id, $idwarehouse = -1)
1120 {
1121 if (!DolibarrApiAccess::$user->hasRight('commande', 'creer')) {
1122 throw new RestException(403);
1123 }
1124 $result = $this->commande->fetch($id);
1125 if (!$result) {
1126 throw new RestException(404, 'Order not found');
1127 }
1128
1129 if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
1130 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1131 }
1132
1133 $result = $this->commande->setDraft(DolibarrApiAccess::$user, $idwarehouse);
1134 if ($result == 0) {
1135 throw new RestException(304, 'Nothing done. May be object is already closed');
1136 }
1137 if ($result < 0) {
1138 throw new RestException(500, 'Error when closing Order: '.$this->commande->error);
1139 }
1140
1141 $result = $this->commande->fetch($id);
1142 if (!$result) {
1143 throw new RestException(404, 'Order not found');
1144 }
1145
1146 // test already done
1147 // if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
1148 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1149 // }
1150
1151 $this->commande->fetchObjectLinked();
1152
1153 return $this->_cleanObjectDatas($this->commande);
1154 }
1155
1156
1170 public function createOrderFromProposal($proposalid)
1171 {
1172 require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
1173
1174 if (!DolibarrApiAccess::$user->hasRight('propal', 'lire')) {
1175 throw new RestException(403);
1176 }
1177 if (!DolibarrApiAccess::$user->hasRight('commande', 'creer')) {
1178 throw new RestException(403);
1179 }
1180 if (empty($proposalid)) {
1181 throw new RestException(400, 'Proposal ID is mandatory');
1182 }
1183
1184 $propal = new Propal($this->db);
1185 $result = $propal->fetch($proposalid);
1186 if (!$result) {
1187 throw new RestException(404, 'Proposal not found');
1188 }
1189
1190 $result = $this->commande->createFromProposal($propal, DolibarrApiAccess::$user);
1191 if ($result < 0) {
1192 throw new RestException(405, $this->commande->error);
1193 }
1194 $this->commande->fetchObjectLinked();
1195
1196 return $this->_cleanObjectDatas($this->commande);
1197 }
1198
1214 public function getOrderShipments($id)
1215 {
1216 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1217 if (!DolibarrApiAccess::$user->hasRight('expedition', 'lire')) {
1218 throw new RestException(403);
1219 }
1220 if (!DolibarrApi::_checkAccessToResource('commande', $id)) {
1221 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1222 }
1223 $obj_ret = array();
1224 $sql = "SELECT e.rowid";
1225 $sql .= " FROM ".MAIN_DB_PREFIX."expedition as e";
1226 $sql .= " JOIN ".MAIN_DB_PREFIX."expeditiondet as edet";
1227 $sql .= " ON e.rowid = edet.fk_expedition";
1228 $sql .= " JOIN ".MAIN_DB_PREFIX."commandedet as cdet";
1229 $sql .= " ON edet.fk_elementdet = cdet.rowid";
1230 $sql .= " JOIN ".MAIN_DB_PREFIX."commande as c";
1231 $sql .= " ON cdet.fk_commande = c.rowid";
1232 $sql .= " WHERE c.rowid = ".((int) $id);
1233 $sql .= " GROUP BY e.rowid";
1234 $sql .= $this->db->order("e.rowid", "ASC");
1235
1236 dol_syslog("API Rest request");
1237 $result = $this->db->query($sql);
1238
1239 if ($result) {
1240 $i = 0;
1241 $num = $this->db->num_rows($result);
1242 if ($num <= 0) {
1243 throw new RestException(404, 'Shipments not found ');
1244 }
1245 //$min = min($num, ($limit <= 0 ? $num : $limit));
1246 $min = $num;
1247 while ($i < $min) {
1248 $obj = $this->db->fetch_object($result);
1249 $shipment_static = new Expedition($this->db);
1250 if ($shipment_static->fetch($obj->rowid)) {
1251 $obj_ret[] = $this->_cleanObjectDatas($shipment_static);
1252 }
1253 $i++;
1254 }
1255 } else {
1256 throw new RestException(500, 'Error when retrieve shipment list : '.$this->db->lasterror());
1257 }
1258 return $obj_ret;
1259 }
1260
1275 public function createOrderShipment($id, $warehouse_id)
1276 {
1277 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1278 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
1279 throw new RestException(403);
1280 }
1281 if ($warehouse_id <= 0) {
1282 throw new RestException(404, 'Warehouse not found');
1283 }
1284 $result = $this->commande->fetch($id);
1285 if (!$result) {
1286 throw new RestException(404, 'Order not found');
1287 }
1288 if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
1289 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1290 }
1291 $shipment = new Expedition($this->db);
1292 $shipment->socid = $this->commande->socid;
1293 $shipment->origin_id = $this->commande->id;
1294 $shipment->origin = $this->commande->element;
1295 $result = $shipment->create(DolibarrApiAccess::$user);
1296 if ($result <= 0) {
1297 throw new RestException(500, 'Error on creating expedition :'.$this->db->lasterror());
1298 }
1299 foreach ($this->commande->lines as $line) {
1300 $result = $shipment->create_line($warehouse_id, $line->id, $line->qty);
1301 if ($result <= 0) {
1302 throw new RestException(500, 'Error on creating expedition lines:'.$this->db->lasterror());
1303 }
1304 }
1305 return $shipment->id;
1306 }
1307
1308 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1318 protected function _cleanObjectDatas($object)
1319 {
1320 // phpcs:enable
1321 $object = parent::_cleanObjectDatas($object);
1322
1323 unset($object->note);
1324 unset($object->address);
1325 unset($object->barcode_type);
1326 unset($object->barcode_type_code);
1327 unset($object->barcode_type_label);
1328 unset($object->barcode_type_coder);
1329
1330 return $object;
1331 }
1332
1340 private function _validate($data)
1341 {
1342 if ($data === null) {
1343 $data = array();
1344 }
1345 $commande = array();
1346 foreach (Orders::$FIELDS as $field) {
1347 if (!isset($data[$field])) {
1348 throw new RestException(400, $field." field missing");
1349 }
1350 $commande[$field] = $data[$field];
1351 }
1352 return $commande;
1353 }
1354}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
Class to manage customers orders.
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
Class to manage order lines.
deleteContact($id, $contactid, $type)
Unlink a contact type of given order.
__construct()
Constructor.
_validate($data)
Validate fields before create or update object.
deleteLine($id, $lineid)
Delete a line of a given order.
getByRef($ref, $contact_list=-1)
Get properties of an order object by ref.
close($id, $notrigger=0)
Close an order (Classify it as "Delivered")
postContact($id, $contactid, $type, $source="external", $notrigger=0)
Add a contact type of given order.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $sqlfilters='', $sqlfilterlines='', $properties='', $pagination_data=false, $loadlinkedobjects=0)
List orders.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
_fetch($id, $ref='', $ref_ext='', $contact_list=-1)
Get properties of an order object.
put($id, $request_data=null)
Update order general fields (won't touch lines of order)
getLines($id)
Get lines of an order.
reopen($id)
Tag the order as validated (opened)
setinvoiced($id)
Classify the order as invoiced.
getContacts($id, $type='')
Get contacts of a given order.
getLine($id, $lineid, $properties='')
Get properties of a line of an order object by id.
postLine($id, $request_data=null)
Add a line to given order.
post($request_data=null)
Create a sale order.
validate($id, $idwarehouse=0, $notrigger=0)
Validate an order.
createOrderFromProposal($proposalid)
Create an order using an existing proposal.
putLine($id, $lineid, $request_data=null)
Update a line to given order.
getOrderShipments($id)
Get the shipments of an order.
settodraft($id, $idwarehouse=-1)
Set an order to draft.
createOrderShipment($id, $warehouse_id)
Create the shipment of an order.
getByRefExt($ref_ext, $contact_list=-1)
Get properties of an order object by ref_ext.
Class to manage proposals.
Class to manage third parties objects (customers, suppliers, prospects...)
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.