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 if ($field == 'array_options' && is_array($value)) {
298 foreach ($value as $index => $val) {
299 $this->order->array_options[$index] = $this->_checkValForAPI($field, $val, $this->order);
300 }
301 continue;
302 }
303
304 $this->order->$field = $this->_checkValForAPI($field, $value, $this->order);
305 }
306
307 if ($this->order->update(DolibarrApiAccess::$user)) {
308 return $this->get($id);
309 }
310
311 return false;
312 }
313
328 public function getContacts($id, $source, $type = '')
329 {
330 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
331 throw new RestException(401);
332 }
333
334 $result = $this->order->fetch($id);
335 if (!$result) {
336 throw new RestException(404, 'Supplier order not found');
337 }
338
339 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
340 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
341 }
342 $contacts = array();
343
344 if ($source == 'all' || $source == 'external') {
345 $tmpContacts = $this->order->liste_contact(-1, 'external', 0, $type);
346 $contacts = array_merge($contacts, $tmpContacts);
347 }
348
349 if ($source == 'all' || $source == 'internal') {
350 $tmpContacts = $this->order->liste_contact(-1, 'internal', 0, $type);
351 $contacts = array_merge($contacts, $tmpContacts);
352 }
353
354 return $this->_cleanObjectDatas($contacts);
355 }
356
371 public function postContact($id, $contactid, $type, $source)
372 {
373 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
374 throw new RestException(401);
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(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
384 }
385
386 $result = $this->order->add_contact($contactid, $type, $source);
387
388 if ($result < 0) {
389 throw new RestException(500, 'Error when added the contact');
390 }
391
392 if ($result == 0) {
393 throw new RestException(304, 'contact already added');
394 }
395
396 return array(
397 'success' => array(
398 'code' => 200,
399 'message' => 'Contact linked to the order'
400 )
401 );
402 }
403
420 public function deleteContact($id, $contactid, $type, $source)
421 {
422 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
423 throw new RestException(401);
424 }
425
426 $result = $this->order->fetch($id);
427 if (!$result) {
428 throw new RestException(404, 'Supplier order not found');
429 }
430
431 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
432 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
433 }
434
435 $contacts = $this->order->liste_contact(-1, $source, 0, $type);
436
437 $contactToUnlink = 0;
438 foreach ($contacts as $contact) {
439 if ($contact['id'] == $contactid && $contact['code'] == $type) {
440 $contactToUnlink = $contact['rowid'];
441 break;
442 }
443 }
444
445 if ($contactToUnlink == 0) {
446 throw new RestException(404, 'Linked contact not found');
447 }
448
449 $result = $this->order->delete_contact($contact['rowid']);
450
451 if (!$result) {
452 throw new RestException(500, 'Error when deleted the contact');
453 }
454
455 return array(
456 'success' => array(
457 'code' => 200,
458 'message' => 'Contact unlinked from supplier order'
459 )
460 );
461 }
462
469 public function delete($id)
470 {
471 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "supprimer")) {
472 throw new RestException(401);
473 }
474 $result = $this->order->fetch($id);
475 if (!$result) {
476 throw new RestException(404, 'Supplier order not found');
477 }
478
479 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
480 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
481 }
482
483 if ($this->order->delete(DolibarrApiAccess::$user) < 0) {
484 throw new RestException(500, 'Error when deleting order');
485 }
486
487 return array(
488 'success' => array(
489 'code' => 200,
490 'message' => 'Supplier order deleted'
491 )
492 );
493 }
494
495
514 public function validate($id, $idwarehouse = 0, $notrigger = 0)
515 {
516 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
517 throw new RestException(401);
518 }
519 $result = $this->order->fetch($id);
520 if (!$result) {
521 throw new RestException(404, 'Order not found');
522 }
523
524 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
525 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
526 }
527
528 $result = $this->order->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger);
529 if ($result == 0) {
530 throw new RestException(304, 'Error nothing done. May be object is already validated');
531 }
532 if ($result < 0) {
533 throw new RestException(500, 'Error when validating Order: '.$this->order->error);
534 }
535
536 return array(
537 'success' => array(
538 'code' => 200,
539 'message' => 'Order validated (Ref='.$this->order->ref.')'
540 )
541 );
542 }
543
562 public function approve($id, $idwarehouse = 0, $secondlevel = 0)
563 {
564 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
565 throw new RestException(401);
566 }
567 $result = $this->order->fetch($id);
568 if (!$result) {
569 throw new RestException(404, 'Order not found');
570 }
571
572 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
573 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
574 }
575
576 $result = $this->order->approve(DolibarrApiAccess::$user, $idwarehouse, $secondlevel);
577 if ($result == 0) {
578 throw new RestException(304, 'Error nothing done. May be object is already approved');
579 }
580 if ($result < 0) {
581 throw new RestException(500, 'Error when approve Order: '.$this->order->error);
582 }
583
584 return array(
585 'success' => array(
586 'code' => 200,
587 'message' => 'Order approved (Ref='.$this->order->ref.')'
588 )
589 );
590 }
591
592
613 public function makeOrder($id, $date, $method, $comment = '')
614 {
615 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
616 throw new RestException(401);
617 }
618 $result = $this->order->fetch($id);
619 if (!$result) {
620 throw new RestException(404, 'Order not found');
621 }
622
623 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
624 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
625 }
626
627 $result = $this->order->commande(DolibarrApiAccess::$user, $date, $method, $comment);
628 if ($result == 0) {
629 throw new RestException(304, 'Error nothing done. May be object is already sent');
630 }
631 if ($result < 0) {
632 throw new RestException(500, 'Error when sending Order: '.$this->order->error);
633 }
634
635 return array(
636 'success' => array(
637 'code' => 200,
638 'message' => 'Order sent (Ref='.$this->order->ref.')'
639 )
640 );
641 }
642
676 public function receiveOrder($id, $closeopenorder, $comment, $lines)
677 {
678 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
679 throw new RestException(401);
680 }
681 $result = $this->order->fetch($id);
682 if (!$result) {
683 throw new RestException(404, 'Order not found');
684 }
685
686 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
687 throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
688 }
689
690 foreach ($lines as $line) {
691 $lineObj =(object) $line;
692
693 $result=$this->order->dispatchProduct(
694 DolibarrApiAccess::$user,
695 $lineObj->fk_product,
696 $lineObj->qty,
697 $lineObj->warehouse,
698 $lineObj->price,
699 $lineObj->comment,
700 $lineObj->eatby,
701 $lineObj->sellby,
702 $lineObj->batch,
703 $lineObj->id,
704 $lineObj->notrigger
705 );
706
707 if ($result < 0) {
708 throw new RestException(500, 'Error dispatch order line '.$line->id.': '.$this->order->error);
709 }
710 }
711
712 $result = $this->order->calcAndSetStatusDispatch(DolibarrApiAccess::$user, $closeopenorder, $comment);
713
714 if ($result == 0) {
715 throw new RestException(304, 'Error nothing done. May be object is already dispatched');
716 }
717 if ($result < 0) {
718 throw new RestException(500, 'Error when receivce order: '.$this->order->error);
719 }
720
721 return array(
722 'success' => array(
723 'code' => 200,
724 'message' => 'Order received (Ref='.$this->order->ref.')'
725 )
726 );
727 }
728
729 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
736 protected function _cleanObjectDatas($object)
737 {
738 // phpcs:enable
739 $object = parent::_cleanObjectDatas($object);
740
741 unset($object->rowid);
742 unset($object->barcode_type);
743 unset($object->barcode_type_code);
744 unset($object->barcode_type_label);
745 unset($object->barcode_type_coder);
746
747 return $object;
748 }
749
758 private function _validate($data)
759 {
760 $order = array();
761 foreach (SupplierOrders::$FIELDS as $field) {
762 if (!isset($data[$field])) {
763 throw new RestException(400, "$field field missing");
764 }
765 $order[$field] = $data[$field];
766 }
767 return $order;
768 }
769}
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.