dolibarr 19.0.4
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(401);
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(401, '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(401);
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 if ((!DolibarrApiAccess::$user->hasRight("societe", "client", "voir")) || $search_sale > 0) {
121 $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
122 }
123 $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur AS t 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
124
125 if ((!DolibarrApiAccess::$user->hasRight("societe", "client", "voir")) || $search_sale > 0) {
126 $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
127 }
128
129 if (!empty($product_ids)) {
130 $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; // We need this table joined to the select in order to filter by product
131 }
132
133 $sql .= ' WHERE t.entity IN ('.getEntity('supplier_order').')';
134 if ((!DolibarrApiAccess::$user->hasRight("societe", "client", "voir")) || $search_sale > 0) {
135 $sql .= " AND t.fk_soc = sc.fk_soc";
136 }
137 if (!empty($product_ids)) {
138 $sql .= " AND cd.fk_commande = t.rowid AND cd.fk_product IN (".$this->db->sanitize($product_ids).")";
139 }
140 if ($socids) {
141 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
142 }
143
144 // Filter by status
145 if ($status == 'draft') {
146 $sql .= " AND t.fk_statut IN (0)";
147 }
148 if ($status == 'validated') {
149 $sql .= " AND t.fk_statut IN (1)";
150 }
151 if ($status == 'approved') {
152 $sql .= " AND t.fk_statut IN (2)";
153 }
154 if ($status == 'running') {
155 $sql .= " AND t.fk_statut IN (3)";
156 }
157 if ($status == 'received_start') {
158 $sql .= " AND t.fk_statut IN (4)";
159 }
160 if ($status == 'received_end') {
161 $sql .= " AND t.fk_statut IN (5)";
162 }
163 if ($status == 'cancelled') {
164 $sql .= " AND t.fk_statut IN (6,7)";
165 }
166 if ($status == 'refused') {
167 $sql .= " AND t.fk_statut IN (9)";
168 }
169 // Insert sale filter
170 if ($search_sale > 0) {
171 $sql .= " AND sc.fk_user = ".((int) $search_sale);
172 }
173 // Add sql filters
174 if ($sqlfilters) {
175 $errormessage = '';
176 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
177 if ($errormessage) {
178 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
179 }
180 }
181 // Add sql filters for lines
182 if ($sqlfilterlines) {
183 $errormessage = '';
184 $sql .= " AND EXISTS (SELECT tl.rowid FROM ".MAIN_DB_PREFIX."commande_fournisseurdet AS tl WHERE tl.fk_commande = t.rowid";
185 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilterlines, $errormessage);
186 $sql .= ")";
187 if ($errormessage) {
188 throw new RestException(400, 'Error when validating parameter sqlfilterlines -> '.$errormessage);
189 }
190 }
191
192 $sql .= $this->db->order($sortfield, $sortorder);
193 if ($limit) {
194 if ($page < 0) {
195 $page = 0;
196 }
197 $offset = $limit * $page;
198
199 $sql .= $this->db->plimit($limit + 1, $offset);
200 }
201
202 $result = $this->db->query($sql);
203 if ($result) {
204 $i = 0;
205 $num = $this->db->num_rows($result);
206 $min = min($num, ($limit <= 0 ? $num : $limit));
207 while ($i < $min) {
208 $obj = $this->db->fetch_object($result);
209 $order_static = new CommandeFournisseur($this->db);
210 if ($order_static->fetch($obj->rowid)) {
211 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($order_static), $properties);
212 }
213 $i++;
214 }
215 } else {
216 throw new RestException(503, 'Error when retrieve supplier order list : '.$this->db->lasterror());
217 }
218
219 return $obj_ret;
220 }
221
230 public function post($request_data = null)
231 {
232 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
233 throw new RestException(401, "Insuffisant rights");
234 }
235 // Check mandatory fields
236 $result = $this->_validate($request_data);
237
238 foreach ($request_data as $field => $value) {
239 if ($field === 'caller') {
240 // 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 whith the caller
241 $this->order->context['caller'] = $request_data['caller'];
242 continue;
243 }
244
245 $this->order->$field = $this->_checkValForAPI($field, $value, $this->order);
246 }
247 if (!array_keys($request_data, 'date')) {
248 $this->order->date = dol_now();
249 }
250 /* We keep lines as an array
251 if (isset($request_data["lines"])) {
252 $lines = array();
253 foreach ($request_data["lines"] as $line) {
254 array_push($lines, (object) $line);
255 }
256 $this->order->lines = $lines;
257 }*/
258
259 if ($this->order->create(DolibarrApiAccess::$user) < 0) {
260 throw new RestException(500, "Error creating order", array_merge(array($this->order->error), $this->order->errors));
261 }
262 return $this->order->id;
263 }
264
272 public function put($id, $request_data = null)
273 {
274 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
275 throw new RestException(401);
276 }
277
278 $result = $this->order->fetch($id);
279 if (!$result) {
280 throw new RestException(404, 'Supplier order not found');
281 }
282
283 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
284 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
285 }
286
287 foreach ($request_data as $field => $value) {
288 if ($field == 'id') {
289 continue;
290 }
291 if ($field === 'caller') {
292 // 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 whith the caller
293 $this->order->context['caller'] = $request_data['caller'];
294 continue;
295 }
296
297 $this->order->$field = $this->_checkValForAPI($field, $value, $this->order);
298 }
299
300 if ($this->order->update(DolibarrApiAccess::$user)) {
301 return $this->get($id);
302 }
303
304 return false;
305 }
306
321 public function getContacts($id, $source, $type = '')
322 {
323 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
324 throw new RestException(401);
325 }
326
327 $result = $this->order->fetch($id);
328 if (!$result) {
329 throw new RestException(404, 'Supplier order not found');
330 }
331
332 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
333 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
334 }
335 $contacts = array();
336
337 if ($source == 'all' || $source == 'external') {
338 $tmpContacts = $this->order->liste_contact(-1, 'external', 0, $type);
339 $contacts = array_merge($contacts, $tmpContacts);
340 }
341
342 if ($source == 'all' || $source == 'internal') {
343 $tmpContacts = $this->order->liste_contact(-1, 'internal', 0, $type);
344 $contacts = array_merge($contacts, $tmpContacts);
345 }
346
347 return $this->_cleanObjectDatas($contacts);
348 }
349
364 public function postContact($id, $contactid, $type, $source)
365 {
366 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
367 throw new RestException(401);
368 }
369
370 $result = $this->order->fetch($id);
371 if (!$result) {
372 throw new RestException(404, 'Supplier order not found');
373 }
374
375 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
376 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
377 }
378
379 $result = $this->order->add_contact($contactid, $type, $source);
380
381 if ($result < 0) {
382 throw new RestException(500, 'Error when added the contact');
383 }
384
385 if ($result == 0) {
386 throw new RestException(304, 'contact already added');
387 }
388
389 return array(
390 'success' => array(
391 'code' => 200,
392 'message' => 'Contact linked to the order'
393 )
394 );
395 }
396
413 public function deleteContact($id, $contactid, $type, $source)
414 {
415 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
416 throw new RestException(401);
417 }
418
419 $result = $this->order->fetch($id);
420 if (!$result) {
421 throw new RestException(404, 'Supplier order not found');
422 }
423
424 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
425 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
426 }
427
428 $contacts = $this->order->liste_contact(-1, $source, 0, $type);
429
430 $contactToUnlink = 0;
431 foreach ($contacts as $contact) {
432 if ($contact['id'] == $contactid && $contact['code'] == $type) {
433 $contactToUnlink = $contact['rowid'];
434 break;
435 }
436 }
437
438 if ($contactToUnlink == 0) {
439 throw new RestException(404, 'Linked contact not found');
440 }
441
442 $result = $this->order->delete_contact($contact['rowid']);
443
444 if (!$result) {
445 throw new RestException(500, 'Error when deleted the contact');
446 }
447
448 return array(
449 'success' => array(
450 'code' => 200,
451 'message' => 'Contact unlinked from supplier order'
452 )
453 );
454 }
455
462 public function delete($id)
463 {
464 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "supprimer")) {
465 throw new RestException(401);
466 }
467 $result = $this->order->fetch($id);
468 if (!$result) {
469 throw new RestException(404, 'Supplier order not found');
470 }
471
472 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
473 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
474 }
475
476 if ($this->order->delete(DolibarrApiAccess::$user) < 0) {
477 throw new RestException(500, 'Error when deleting order');
478 }
479
480 return array(
481 'success' => array(
482 'code' => 200,
483 'message' => 'Supplier order deleted'
484 )
485 );
486 }
487
488
507 public function validate($id, $idwarehouse = 0, $notrigger = 0)
508 {
509 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
510 throw new RestException(401);
511 }
512 $result = $this->order->fetch($id);
513 if (!$result) {
514 throw new RestException(404, 'Order not found');
515 }
516
517 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
518 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
519 }
520
521 $result = $this->order->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger);
522 if ($result == 0) {
523 throw new RestException(304, 'Error nothing done. May be object is already validated');
524 }
525 if ($result < 0) {
526 throw new RestException(500, 'Error when validating Order: '.$this->order->error);
527 }
528
529 return array(
530 'success' => array(
531 'code' => 200,
532 'message' => 'Order validated (Ref='.$this->order->ref.')'
533 )
534 );
535 }
536
555 public function approve($id, $idwarehouse = 0, $secondlevel = 0)
556 {
557 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
558 throw new RestException(401);
559 }
560 $result = $this->order->fetch($id);
561 if (!$result) {
562 throw new RestException(404, 'Order not found');
563 }
564
565 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
566 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
567 }
568
569 $result = $this->order->approve(DolibarrApiAccess::$user, $idwarehouse, $secondlevel);
570 if ($result == 0) {
571 throw new RestException(304, 'Error nothing done. May be object is already approved');
572 }
573 if ($result < 0) {
574 throw new RestException(500, 'Error when approve Order: '.$this->order->error);
575 }
576
577 return array(
578 'success' => array(
579 'code' => 200,
580 'message' => 'Order approved (Ref='.$this->order->ref.')'
581 )
582 );
583 }
584
585
606 public function makeOrder($id, $date, $method, $comment = '')
607 {
608 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
609 throw new RestException(401);
610 }
611 $result = $this->order->fetch($id);
612 if (!$result) {
613 throw new RestException(404, 'Order not found');
614 }
615
616 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
617 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
618 }
619
620 $result = $this->order->commande(DolibarrApiAccess::$user, $date, $method, $comment);
621 if ($result == 0) {
622 throw new RestException(304, 'Error nothing done. May be object is already sent');
623 }
624 if ($result < 0) {
625 throw new RestException(500, 'Error when sending Order: '.$this->order->error);
626 }
627
628 return array(
629 'success' => array(
630 'code' => 200,
631 'message' => 'Order sent (Ref='.$this->order->ref.')'
632 )
633 );
634 }
635
669 public function receiveOrder($id, $closeopenorder, $comment, $lines)
670 {
671 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
672 throw new RestException(401);
673 }
674 $result = $this->order->fetch($id);
675 if (!$result) {
676 throw new RestException(404, 'Order not found');
677 }
678
679 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
680 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
681 }
682
683 foreach ($lines as $line) {
684 $lineObj =(object) $line;
685
686 $result=$this->order->dispatchProduct(
687 DolibarrApiAccess::$user,
688 $lineObj->fk_product,
689 $lineObj->qty,
690 $lineObj->warehouse,
691 $lineObj->price,
692 $lineObj->comment,
693 $lineObj->eatby,
694 $lineObj->sellby,
695 $lineObj->batch,
696 $lineObj->id,
697 $lineObj->notrigger
698 );
699
700 if ($result < 0) {
701 throw new RestException(500, 'Error dispatch order line '.$line->id.': '.$this->order->error);
702 }
703 }
704
705 $result = $this->order->calcAndSetStatusDispatch(DolibarrApiAccess::$user, $closeopenorder, $comment);
706
707 if ($result == 0) {
708 throw new RestException(304, 'Error nothing done. May be object is already dispatched');
709 }
710 if ($result < 0) {
711 throw new RestException(500, 'Error when receivce order: '.$this->order->error);
712 }
713
714 return array(
715 'success' => array(
716 'code' => 200,
717 'message' => 'Order received (Ref='.$this->order->ref.')'
718 )
719 );
720 }
721
722 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
729 protected function _cleanObjectDatas($object)
730 {
731 // phpcs:enable
732 $object = parent::_cleanObjectDatas($object);
733
734 unset($object->rowid);
735 unset($object->barcode_type);
736 unset($object->barcode_type_code);
737 unset($object->barcode_type_label);
738 unset($object->barcode_type_coder);
739
740 return $object;
741 }
742
751 private function _validate($data)
752 {
753 $order = array();
754 foreach (SupplierOrders::$FIELDS as $field) {
755 if (!isset($data[$field])) {
756 throw new RestException(400, "$field field missing");
757 }
758 $order[$field] = $data[$field];
759 }
760 return $order;
761 }
762}
Class to manage predefined suppliers products.
Class for API REST v1.
Definition api.class.php:31
_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:85
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.