dolibarr 20.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 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use Luracast\Restler\RestException;
20
21require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
22
30{
35 public static $FIELDS = array(
36 'socid'
37 );
38
42 public $order;
43
47 public function __construct()
48 {
49 global $db, $conf;
50 $this->db = $db;
51 $this->order = new CommandeFournisseur($this->db);
52 }
53
64 public function get($id)
65 {
66 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
67 throw new RestException(403);
68 }
69
70 $result = $this->order->fetch($id);
71 if (!$result) {
72 throw new RestException(404, 'Supplier order not found');
73 }
74
75 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
76 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
77 }
78
79 $this->order->fetchObjectLinked();
80 return $this->_cleanObjectDatas($this->order);
81 }
82
102 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $product_ids = '', $status = '', $sqlfilters = '', $sqlfilterlines = '', $properties = '')
103 {
104 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
105 throw new RestException(403);
106 }
107
108 $obj_ret = array();
109
110 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
111 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
112
113 // If the internal user must only see his customers, force searching by him
114 $search_sale = 0;
115 if (!DolibarrApiAccess::$user->hasRight("societe", "client", "voir") && !empty($socids)) {
116 $search_sale = DolibarrApiAccess::$user->id;
117 }
118
119 $sql = "SELECT t.rowid";
120 $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur AS t";
121 $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
122 if (!empty($product_ids)) {
123 $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; // We need this table joined to the select in order to filter by product
124 }
125 $sql .= ' WHERE t.entity IN ('.getEntity('supplier_order').')';
126 if (!empty($product_ids)) {
127 $sql .= " AND cd.fk_commande = t.rowid AND cd.fk_product IN (".$this->db->sanitize($product_ids).")";
128 }
129 if ($socids) {
130 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
131 }
132 // Filter by status
133 if ($status == 'draft') {
134 $sql .= " AND t.fk_statut IN (0)";
135 }
136 if ($status == 'validated') {
137 $sql .= " AND t.fk_statut IN (1)";
138 }
139 if ($status == 'approved') {
140 $sql .= " AND t.fk_statut IN (2)";
141 }
142 if ($status == 'running') {
143 $sql .= " AND t.fk_statut IN (3)";
144 }
145 if ($status == 'received_start') {
146 $sql .= " AND t.fk_statut IN (4)";
147 }
148 if ($status == 'received_end') {
149 $sql .= " AND t.fk_statut IN (5)";
150 }
151 if ($status == 'cancelled') {
152 $sql .= " AND t.fk_statut IN (6,7)";
153 }
154 if ($status == 'refused') {
155 $sql .= " AND t.fk_statut IN (9)";
156 }
157 // Search on sale representative
158 if ($search_sale && $search_sale != '-1') {
159 if ($search_sale == -2) {
160 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
161 } elseif ($search_sale > 0) {
162 $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).")";
163 }
164 }
165 // Add sql filters
166 if ($sqlfilters) {
167 $errormessage = '';
168 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
169 if ($errormessage) {
170 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
171 }
172 }
173 // Add sql filters for lines
174 if ($sqlfilterlines) {
175 $errormessage = '';
176 $sql .= " AND EXISTS (SELECT tl.rowid FROM ".MAIN_DB_PREFIX."commande_fournisseurdet AS tl WHERE tl.fk_commande = t.rowid";
177 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilterlines, $errormessage);
178 $sql .= ")";
179 if ($errormessage) {
180 throw new RestException(400, 'Error when validating parameter sqlfilterlines -> '.$errormessage);
181 }
182 }
183
184 $sql .= $this->db->order($sortfield, $sortorder);
185 if ($limit) {
186 if ($page < 0) {
187 $page = 0;
188 }
189 $offset = $limit * $page;
190
191 $sql .= $this->db->plimit($limit + 1, $offset);
192 }
193
194 $result = $this->db->query($sql);
195 if ($result) {
196 $i = 0;
197 $num = $this->db->num_rows($result);
198 $min = min($num, ($limit <= 0 ? $num : $limit));
199 while ($i < $min) {
200 $obj = $this->db->fetch_object($result);
201 $order_static = new CommandeFournisseur($this->db);
202 if ($order_static->fetch($obj->rowid)) {
203 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($order_static), $properties);
204 }
205 $i++;
206 }
207 } else {
208 throw new RestException(503, 'Error when retrieve supplier order list : '.$this->db->lasterror());
209 }
210
211 return $obj_ret;
212 }
213
222 public function post($request_data = null)
223 {
224 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
225 throw new RestException(403, "Insuffisant rights");
226 }
227 // Check mandatory fields
228 $result = $this->_validate($request_data);
229
230 foreach ($request_data as $field => $value) {
231 if ($field === 'caller') {
232 // 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
233 $this->order->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
234 continue;
235 }
236
237 $this->order->$field = $this->_checkValForAPI($field, $value, $this->order);
238 }
239 if (!array_keys($request_data, 'date')) {
240 $this->order->date = dol_now();
241 }
242 /* We keep lines as an array
243 if (isset($request_data["lines"])) {
244 $lines = array();
245 foreach ($request_data["lines"] as $line) {
246 array_push($lines, (object) $line);
247 }
248 $this->order->lines = $lines;
249 }*/
250
251 if ($this->order->create(DolibarrApiAccess::$user) < 0) {
252 throw new RestException(500, "Error creating order", array_merge(array($this->order->error), $this->order->errors));
253 }
254 return $this->order->id;
255 }
256
264 public function put($id, $request_data = null)
265 {
266 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
267 throw new RestException(403);
268 }
269
270 $result = $this->order->fetch($id);
271 if (!$result) {
272 throw new RestException(404, 'Supplier order not found');
273 }
274
275 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
276 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
277 }
278
279 foreach ($request_data as $field => $value) {
280 if ($field == 'id') {
281 continue;
282 }
283 if ($field === 'caller') {
284 // 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
285 $this->order->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
286 continue;
287 }
288 if ($field == 'array_options' && is_array($value)) {
289 foreach ($value as $index => $val) {
290 $this->order->array_options[$index] = $this->_checkValForAPI($field, $val, $this->order);
291 }
292 continue;
293 }
294
295 $this->order->$field = $this->_checkValForAPI($field, $value, $this->order);
296 }
297
298 if ($this->order->update(DolibarrApiAccess::$user)) {
299 return $this->get($id);
300 }
301
302 return false;
303 }
304
319 public function getContacts($id, $source, $type = '')
320 {
321 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
322 throw new RestException(403);
323 }
324
325 $result = $this->order->fetch($id);
326 if (!$result) {
327 throw new RestException(404, 'Supplier order not found');
328 }
329
330 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
331 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
332 }
333 $contacts = array();
334
335 if ($source == 'all' || $source == 'external') {
336 $tmpContacts = $this->order->liste_contact(-1, 'external', 0, $type);
337 $contacts = array_merge($contacts, $tmpContacts);
338 }
339
340 if ($source == 'all' || $source == 'internal') {
341 $tmpContacts = $this->order->liste_contact(-1, 'internal', 0, $type);
342 $contacts = array_merge($contacts, $tmpContacts);
343 }
344
345 return $this->_cleanObjectDatas($contacts);
346 }
347
362 public function postContact($id, $contactid, $type, $source)
363 {
364 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
365 throw new RestException(403);
366 }
367
368 $result = $this->order->fetch($id);
369 if (!$result) {
370 throw new RestException(404, 'Supplier order not found');
371 }
372
373 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
374 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
375 }
376
377 $result = $this->order->add_contact($contactid, $type, $source);
378
379 if ($result < 0) {
380 throw new RestException(500, 'Error when added the contact');
381 }
382
383 if ($result == 0) {
384 throw new RestException(304, 'contact already added');
385 }
386
387 return array(
388 'success' => array(
389 'code' => 200,
390 'message' => 'Contact linked to the order'
391 )
392 );
393 }
394
411 public function deleteContact($id, $contactid, $type, $source)
412 {
413 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
414 throw new RestException(403);
415 }
416
417 $result = $this->order->fetch($id);
418 if (!$result) {
419 throw new RestException(404, 'Supplier order not found');
420 }
421
422 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
423 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
424 }
425
426 $contacts = $this->order->liste_contact(-1, $source, 0, $type);
427
428 $contactToUnlink = 0;
429 foreach ($contacts as $contact) {
430 if ($contact['id'] == $contactid && $contact['code'] == $type) {
431 $contactToUnlink = $contact['rowid'];
432 break;
433 }
434 }
435
436 if ($contactToUnlink == 0) {
437 throw new RestException(404, 'Linked contact not found');
438 }
439
440 $result = $this->order->delete_contact($contact['rowid']);
441
442 if (!$result) {
443 throw new RestException(500, 'Error when deleted the contact');
444 }
445
446 return array(
447 'success' => array(
448 'code' => 200,
449 'message' => 'Contact unlinked from supplier order'
450 )
451 );
452 }
453
460 public function delete($id)
461 {
462 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "supprimer")) {
463 throw new RestException(403);
464 }
465 $result = $this->order->fetch($id);
466 if (!$result) {
467 throw new RestException(404, 'Supplier order not found');
468 }
469
470 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
471 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
472 }
473
474 if ($this->order->delete(DolibarrApiAccess::$user) < 0) {
475 throw new RestException(500, 'Error when deleting order');
476 }
477
478 return array(
479 'success' => array(
480 'code' => 200,
481 'message' => 'Supplier order deleted'
482 )
483 );
484 }
485
486
505 public function validate($id, $idwarehouse = 0, $notrigger = 0)
506 {
507 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
508 throw new RestException(403);
509 }
510 $result = $this->order->fetch($id);
511 if (!$result) {
512 throw new RestException(404, 'Order not found');
513 }
514
515 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
516 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
517 }
518
519 $result = $this->order->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger);
520 if ($result == 0) {
521 throw new RestException(304, 'Error nothing done. May be object is already validated');
522 }
523 if ($result < 0) {
524 throw new RestException(500, 'Error when validating Order: '.$this->order->error);
525 }
526
527 return array(
528 'success' => array(
529 'code' => 200,
530 'message' => 'Order validated (Ref='.$this->order->ref.')'
531 )
532 );
533 }
534
553 public function approve($id, $idwarehouse = 0, $secondlevel = 0)
554 {
555 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
556 throw new RestException(403);
557 }
558 $result = $this->order->fetch($id);
559 if (!$result) {
560 throw new RestException(404, 'Order not found');
561 }
562
563 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
564 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
565 }
566
567 $result = $this->order->approve(DolibarrApiAccess::$user, $idwarehouse, $secondlevel);
568 if ($result == 0) {
569 throw new RestException(304, 'Error nothing done. May be object is already approved');
570 }
571 if ($result < 0) {
572 throw new RestException(500, 'Error when approve Order: '.$this->order->error);
573 }
574
575 return array(
576 'success' => array(
577 'code' => 200,
578 'message' => 'Order approved (Ref='.$this->order->ref.')'
579 )
580 );
581 }
582
583
604 public function makeOrder($id, $date, $method, $comment = '')
605 {
606 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
607 throw new RestException(403);
608 }
609 $result = $this->order->fetch($id);
610 if (!$result) {
611 throw new RestException(404, 'Order not found');
612 }
613
614 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
615 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
616 }
617
618 $result = $this->order->commande(DolibarrApiAccess::$user, $date, $method, $comment);
619 if ($result == 0) {
620 throw new RestException(304, 'Error nothing done. May be object is already sent');
621 }
622 if ($result < 0) {
623 throw new RestException(500, 'Error when sending Order: '.$this->order->error);
624 }
625
626 return array(
627 'success' => array(
628 'code' => 200,
629 'message' => 'Order sent (Ref='.$this->order->ref.')'
630 )
631 );
632 }
633
667 public function receiveOrder($id, $closeopenorder, $comment, $lines)
668 {
669 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
670 throw new RestException(403);
671 }
672 $result = $this->order->fetch($id);
673 if (!$result) {
674 throw new RestException(404, 'Order not found');
675 }
676
677 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
678 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
679 }
680
681 foreach ($lines as $line) {
682 $lineObj =(object) $line;
683
684 $result=$this->order->dispatchProduct(
685 DolibarrApiAccess::$user,
686 $lineObj->fk_product,
687 $lineObj->qty,
688 $lineObj->warehouse,
689 $lineObj->price,
690 $lineObj->comment,
691 $lineObj->eatby,
692 $lineObj->sellby,
693 $lineObj->batch,
694 $lineObj->id,
695 $lineObj->notrigger
696 );
697
698 if ($result < 0) {
699 throw new RestException(500, 'Error dispatch order line '.$line->id.': '.$this->order->error);
700 }
701 }
702
703 $result = $this->order->calcAndSetStatusDispatch(DolibarrApiAccess::$user, $closeopenorder, $comment);
704
705 if ($result == 0) {
706 throw new RestException(304, 'Error nothing done. May be object is already dispatched');
707 }
708 if ($result < 0) {
709 throw new RestException(500, 'Error when receivce order: '.$this->order->error);
710 }
711
712 return array(
713 'success' => array(
714 'code' => 200,
715 'message' => 'Order received (Ref='.$this->order->ref.')'
716 )
717 );
718 }
719
720 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
727 protected function _cleanObjectDatas($object)
728 {
729 // phpcs:enable
730 $object = parent::_cleanObjectDatas($object);
731
732 unset($object->rowid);
733 unset($object->barcode_type);
734 unset($object->barcode_type_code);
735 unset($object->barcode_type_label);
736 unset($object->barcode_type_coder);
737
738 return $object;
739 }
740
749 private function _validate($data)
750 {
751 $order = array();
752 foreach (SupplierOrders::$FIELDS as $field) {
753 if (!isset($data[$field])) {
754 throw new RestException(400, "$field field missing");
755 }
756 $order[$field] = $data[$field];
757 }
758 return $order;
759 }
760}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
Class to manage predefined suppliers products.
Class for API REST v1.
Definition api.class.php:30
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:82
validate($id, $idwarehouse=0, $notrigger=0)
Validate an order.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $product_ids='', $status='', $sqlfilters='', $sqlfilterlines='', $properties='')
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.