dolibarr 21.0.3
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
103 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $product_ids = '', $status = '', $sqlfilters = '', $sqlfilterlines = '', $properties = '', $pagination_data = false)
104 {
105 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
106 throw new RestException(403);
107 }
108
109 $obj_ret = array();
110
111 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
112 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
113
114 // If the internal user must only see his customers, force searching by him
115 $search_sale = 0;
116 if (!DolibarrApiAccess::$user->hasRight("societe", "client", "voir") && !empty($socids)) {
117 $search_sale = DolibarrApiAccess::$user->id;
118 }
119
120 $sql = "SELECT t.rowid";
121 $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur AS t";
122 $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
123 if (!empty($product_ids)) {
124 $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; // We need this table joined to the select in order to filter by product
125 }
126 $sql .= ' WHERE t.entity IN ('.getEntity('supplier_order').')';
127 if (!empty($product_ids)) {
128 $sql .= " AND cd.fk_commande = t.rowid AND cd.fk_product IN (".$this->db->sanitize($product_ids).")";
129 }
130 if ($socids) {
131 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
132 }
133 // Filter by status
134 if ($status == 'draft') {
135 $sql .= " AND t.fk_statut IN (0)";
136 }
137 if ($status == 'validated') {
138 $sql .= " AND t.fk_statut IN (1)";
139 }
140 if ($status == 'approved') {
141 $sql .= " AND t.fk_statut IN (2)";
142 }
143 if ($status == 'running') {
144 $sql .= " AND t.fk_statut IN (3)";
145 }
146 if ($status == 'received_start') {
147 $sql .= " AND t.fk_statut IN (4)";
148 }
149 if ($status == 'received_end') {
150 $sql .= " AND t.fk_statut IN (5)";
151 }
152 if ($status == 'cancelled') {
153 $sql .= " AND t.fk_statut IN (6,7)";
154 }
155 if ($status == 'refused') {
156 $sql .= " AND t.fk_statut IN (9)";
157 }
158 // Search on sale representative
159 if ($search_sale && $search_sale != '-1') {
160 if ($search_sale == -2) {
161 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
162 } elseif ($search_sale > 0) {
163 $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).")";
164 }
165 }
166 // Add sql filters
167 if ($sqlfilters) {
168 $errormessage = '';
169 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
170 if ($errormessage) {
171 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
172 }
173 }
174 // Add sql filters for lines
175 if ($sqlfilterlines) {
176 $errormessage = '';
177 $sql .= " AND EXISTS (SELECT tl.rowid FROM ".MAIN_DB_PREFIX."commande_fournisseurdet AS tl WHERE tl.fk_commande = t.rowid";
178 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilterlines, $errormessage);
179 $sql .= ")";
180 if ($errormessage) {
181 throw new RestException(400, 'Error when validating parameter sqlfilterlines -> '.$errormessage);
182 }
183 }
184
185 //this query will return total supplier orders with the filters given
186 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
187
188 $sql .= $this->db->order($sortfield, $sortorder);
189 if ($limit) {
190 if ($page < 0) {
191 $page = 0;
192 }
193 $offset = $limit * $page;
194
195 $sql .= $this->db->plimit($limit + 1, $offset);
196 }
197
198 $result = $this->db->query($sql);
199 if ($result) {
200 $i = 0;
201 $num = $this->db->num_rows($result);
202 $min = min($num, ($limit <= 0 ? $num : $limit));
203 while ($i < $min) {
204 $obj = $this->db->fetch_object($result);
205 $order_static = new CommandeFournisseur($this->db);
206 if ($order_static->fetch($obj->rowid)) {
207 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($order_static), $properties);
208 }
209 $i++;
210 }
211 } else {
212 throw new RestException(503, 'Error when retrieve supplier order list : '.$this->db->lasterror());
213 }
214
215 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
216 if ($pagination_data) {
217 $totalsResult = $this->db->query($sqlTotals);
218 $total = $this->db->fetch_object($totalsResult)->total;
219
220 $tmp = $obj_ret;
221 $obj_ret = [];
222
223 $obj_ret['data'] = $tmp;
224 $obj_ret['pagination'] = [
225 'total' => (int) $total,
226 'page' => $page, //count starts from 0
227 'page_count' => ceil((int) $total / $limit),
228 'limit' => $limit
229 ];
230 }
231
232 return $obj_ret;
233 }
234
243 public function post($request_data = null)
244 {
245 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
246 throw new RestException(403, "Insuffisant rights");
247 }
248 // Check mandatory fields
249 $result = $this->_validate($request_data);
250
251 foreach ($request_data as $field => $value) {
252 if ($field === 'caller') {
253 // 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
254 $this->order->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
255 continue;
256 }
257
258 $this->order->$field = $this->_checkValForAPI($field, $value, $this->order);
259 }
260 if (!array_keys($request_data, 'date')) {
261 $this->order->date = dol_now();
262 }
263 /* We keep lines as an array
264 if (isset($request_data["lines"])) {
265 $lines = array();
266 foreach ($request_data["lines"] as $line) {
267 array_push($lines, (object) $line);
268 }
269 $this->order->lines = $lines;
270 }*/
271
272 if ($this->order->create(DolibarrApiAccess::$user) < 0) {
273 throw new RestException(500, "Error creating order", array_merge(array($this->order->error), $this->order->errors));
274 }
275 return $this->order->id;
276 }
277
285 public function put($id, $request_data = null)
286 {
287 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
288 throw new RestException(403);
289 }
290
291 $result = $this->order->fetch($id);
292 if (!$result) {
293 throw new RestException(404, 'Supplier order not found');
294 }
295
296 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
297 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
298 }
299
300 foreach ($request_data as $field => $value) {
301 if ($field == 'id') {
302 continue;
303 }
304 if ($field === 'caller') {
305 // 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
306 $this->order->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
307 continue;
308 }
309 if ($field == 'array_options' && is_array($value)) {
310 foreach ($value as $index => $val) {
311 $this->order->array_options[$index] = $this->_checkValForAPI($field, $val, $this->order);
312 }
313 continue;
314 }
315
316 $this->order->$field = $this->_checkValForAPI($field, $value, $this->order);
317 }
318
319 if ($this->order->update(DolibarrApiAccess::$user)) {
320 return $this->get($id);
321 }
322
323 return false;
324 }
325
340 public function getContacts($id, $source, $type = '')
341 {
342 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "lire")) {
343 throw new RestException(403);
344 }
345
346 $result = $this->order->fetch($id);
347 if (!$result) {
348 throw new RestException(404, 'Supplier order not found');
349 }
350
351 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
352 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
353 }
354 $contacts = array();
355
356 if ($source == 'all' || $source == 'external') {
357 $tmpContacts = $this->order->liste_contact(-1, 'external', 0, $type);
358 $contacts = array_merge($contacts, $tmpContacts);
359 }
360
361 if ($source == 'all' || $source == 'internal') {
362 $tmpContacts = $this->order->liste_contact(-1, 'internal', 0, $type);
363 $contacts = array_merge($contacts, $tmpContacts);
364 }
365
366 return $this->_cleanObjectDatas($contacts);
367 }
368
383 public function postContact($id, $contactid, $type, $source)
384 {
385 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
386 throw new RestException(403);
387 }
388
389 $result = $this->order->fetch($id);
390 if (!$result) {
391 throw new RestException(404, 'Supplier order not found');
392 }
393
394 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
395 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
396 }
397
398 $result = $this->order->add_contact($contactid, $type, $source);
399
400 if ($result < 0) {
401 throw new RestException(500, 'Error when added the contact');
402 }
403
404 if ($result == 0) {
405 throw new RestException(304, 'contact already added');
406 }
407
408 return array(
409 'success' => array(
410 'code' => 200,
411 'message' => 'Contact linked to the order'
412 )
413 );
414 }
415
432 public function deleteContact($id, $contactid, $type, $source)
433 {
434 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer")) {
435 throw new RestException(403);
436 }
437
438 $result = $this->order->fetch($id);
439 if (!$result) {
440 throw new RestException(404, 'Supplier order not found');
441 }
442
443 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
444 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
445 }
446
447 $contacts = $this->order->liste_contact(-1, $source, 0, $type);
448
449 $contactToUnlink = 0;
450 foreach ($contacts as $contact) {
451 if ($contact['id'] == $contactid && $contact['code'] == $type) {
452 $contactToUnlink = $contact['rowid'];
453 break;
454 }
455 }
456
457 if ($contactToUnlink == 0) {
458 throw new RestException(404, 'Linked contact not found');
459 }
460
461 $result = $this->order->delete_contact($contact['rowid']);
462
463 if (!$result) {
464 throw new RestException(500, 'Error when deleted the contact');
465 }
466
467 return array(
468 'success' => array(
469 'code' => 200,
470 'message' => 'Contact unlinked from supplier order'
471 )
472 );
473 }
474
481 public function delete($id)
482 {
483 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "supprimer")) {
484 throw new RestException(403);
485 }
486 $result = $this->order->fetch($id);
487 if (!$result) {
488 throw new RestException(404, 'Supplier order not found');
489 }
490
491 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
492 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
493 }
494
495 if ($this->order->delete(DolibarrApiAccess::$user) < 0) {
496 throw new RestException(500, 'Error when deleting order');
497 }
498
499 return array(
500 'success' => array(
501 'code' => 200,
502 'message' => 'Supplier order deleted'
503 )
504 );
505 }
506
507
526 public function validate($id, $idwarehouse = 0, $notrigger = 0)
527 {
528 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
529 throw new RestException(403);
530 }
531 $result = $this->order->fetch($id);
532 if (!$result) {
533 throw new RestException(404, 'Order not found');
534 }
535
536 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
537 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
538 }
539
540 $result = $this->order->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger);
541 if ($result == 0) {
542 throw new RestException(304, 'Error nothing done. May be object is already validated');
543 }
544 if ($result < 0) {
545 throw new RestException(500, 'Error when validating Order: '.$this->order->error);
546 }
547
548 return array(
549 'success' => array(
550 'code' => 200,
551 'message' => 'Order validated (Ref='.$this->order->ref.')'
552 )
553 );
554 }
555
574 public function approve($id, $idwarehouse = 0, $secondlevel = 0)
575 {
576 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
577 throw new RestException(403);
578 }
579 $result = $this->order->fetch($id);
580 if (!$result) {
581 throw new RestException(404, 'Order not found');
582 }
583
584 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
585 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
586 }
587
588 $result = $this->order->approve(DolibarrApiAccess::$user, $idwarehouse, $secondlevel);
589 if ($result == 0) {
590 throw new RestException(304, 'Error nothing done. May be object is already approved');
591 }
592 if ($result < 0) {
593 throw new RestException(500, 'Error when approve Order: '.$this->order->error);
594 }
595
596 return array(
597 'success' => array(
598 'code' => 200,
599 'message' => 'Order approved (Ref='.$this->order->ref.')'
600 )
601 );
602 }
603
604
625 public function makeOrder($id, $date, $method, $comment = '')
626 {
627 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
628 throw new RestException(403);
629 }
630 $result = $this->order->fetch($id);
631 if (!$result) {
632 throw new RestException(404, 'Order not found');
633 }
634
635 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
636 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
637 }
638
639 $result = $this->order->commande(DolibarrApiAccess::$user, $date, $method, $comment);
640 if ($result == 0) {
641 throw new RestException(304, 'Error nothing done. May be object is already sent');
642 }
643 if ($result < 0) {
644 throw new RestException(500, 'Error when sending Order: '.$this->order->error);
645 }
646
647 return array(
648 'success' => array(
649 'code' => 200,
650 'message' => 'Order sent (Ref='.$this->order->ref.')'
651 )
652 );
653 }
654
688 public function receiveOrder($id, $closeopenorder, $comment, $lines)
689 {
690 if (!DolibarrApiAccess::$user->hasRight("fournisseur", "commande", "creer") && !DolibarrApiAccess::$user->hasRight("supplier_order", "creer")) {
691 throw new RestException(403);
692 }
693 $result = $this->order->fetch($id);
694 if (!$result) {
695 throw new RestException(404, 'Order not found');
696 }
697
698 if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
699 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
700 }
701
702 foreach ($lines as $line) {
703 $lineObj =(object) $line;
704
705 $result=$this->order->dispatchProduct(
706 DolibarrApiAccess::$user,
707 $lineObj->fk_product,
708 $lineObj->qty,
709 $lineObj->warehouse,
710 $lineObj->price,
711 $lineObj->comment,
712 $lineObj->eatby,
713 $lineObj->sellby,
714 $lineObj->batch,
715 $lineObj->id,
716 $lineObj->notrigger
717 );
718
719 if ($result < 0) {
720 throw new RestException(500, 'Error dispatch order line '.$line->id.': '.$this->order->error);
721 }
722 }
723
724 $result = $this->order->calcAndSetStatusDispatch(DolibarrApiAccess::$user, $closeopenorder, $comment);
725
726 if ($result == 0) {
727 throw new RestException(304, 'Error nothing done. May be object is already dispatched');
728 }
729 if ($result < 0) {
730 throw new RestException(500, 'Error when receivce order: '.$this->order->error);
731 }
732
733 return array(
734 'success' => array(
735 'code' => 200,
736 'message' => 'Order received (Ref='.$this->order->ref.')'
737 )
738 );
739 }
740
741 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
748 protected function _cleanObjectDatas($object)
749 {
750 // phpcs:enable
751 $object = parent::_cleanObjectDatas($object);
752
753 unset($object->rowid);
754 unset($object->barcode_type);
755 unset($object->barcode_type_code);
756 unset($object->barcode_type_label);
757 unset($object->barcode_type_coder);
758
759 return $object;
760 }
761
770 private function _validate($data)
771 {
772 $order = array();
773 foreach (SupplierOrders::$FIELDS as $field) {
774 if (!isset($data[$field])) {
775 throw new RestException(400, "$field field missing");
776 }
777 $order[$field] = $data[$field];
778 }
779 return $order;
780 }
781}
$id
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
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:83
validate($id, $idwarehouse=0, $notrigger=0)
Validate an order.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $product_ids='', $status='', $sqlfilters='', $sqlfilterlines='', $properties='', $pagination_data=false)
List orders.
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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79