dolibarr 22.0.5
api_shipments.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) 2025 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20use Luracast\Restler\RestException;
21
22require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
23
31{
35 public static $FIELDS = array(
36 'socid',
37 'origin_id',
38 'origin_type',
39 );
40
44 public $shipment;
45
49 public function __construct()
50 {
51 global $db, $conf;
52 $this->db = $db;
53 $this->shipment = new Expedition($this->db);
54 }
55
66 public function get($id)
67 {
68 if (!DolibarrApiAccess::$user->hasRight('expedition', 'lire')) {
69 throw new RestException(403);
70 }
71
72 $result = $this->shipment->fetch($id);
73 if (!$result) {
74 throw new RestException(404, 'Shipment not found');
75 }
76
77 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
78 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
79 }
80
81 $this->shipment->fetchObjectLinked();
82 return $this->_cleanObjectDatas($this->shipment);
83 }
84
85
86
106 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
107 {
108 if (!DolibarrApiAccess::$user->hasRight('expedition', 'lire')) {
109 throw new RestException(403);
110 }
111
112 $obj_ret = array();
113
114 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
115 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
116
117 // If the internal user must only see his customers, force searching by him
118 $search_sale = 0;
119 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
120 $search_sale = DolibarrApiAccess::$user->id;
121 }
122
123 $sql = "SELECT t.rowid";
124 $sql .= " FROM ".MAIN_DB_PREFIX."expedition AS t";
125 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."expedition_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
126 $sql .= ' WHERE t.entity IN ('.getEntity('expedition').')';
127 if ($socids) {
128 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
129 }
130 // Search on sale representative
131 if ($search_sale && $search_sale != '-1') {
132 if ($search_sale == -2) {
133 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
134 } elseif ($search_sale > 0) {
135 $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).")";
136 }
137 }
138 // Add sql filters
139 if ($sqlfilters) {
140 $errormessage = '';
141 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
142 if ($errormessage) {
143 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
144 }
145 }
146
147 //this query will return total shipments with the filters given
148 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
149
150 $sql .= $this->db->order($sortfield, $sortorder);
151 if ($limit) {
152 if ($page < 0) {
153 $page = 0;
154 }
155 $offset = $limit * $page;
156
157 $sql .= $this->db->plimit($limit + 1, $offset);
158 }
159
160 dol_syslog("API Rest request");
161 $result = $this->db->query($sql);
162
163 if ($result) {
164 $num = $this->db->num_rows($result);
165 $min = min($num, ($limit <= 0 ? $num : $limit));
166 $i = 0;
167 while ($i < $min) {
168 $obj = $this->db->fetch_object($result);
169 $shipment_static = new Expedition($this->db);
170 if ($shipment_static->fetch($obj->rowid)) {
171 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($shipment_static), $properties);
172 }
173 $i++;
174 }
175 } else {
176 throw new RestException(503, 'Error when retrieve commande list : '.$this->db->lasterror());
177 }
178
179 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
180 if ($pagination_data) {
181 $totalsResult = $this->db->query($sqlTotals);
182 $total = $this->db->fetch_object($totalsResult)->total;
183
184 $tmp = $obj_ret;
185 $obj_ret = [];
186
187 $obj_ret['data'] = $tmp;
188 $obj_ret['pagination'] = [
189 'total' => (int) $total,
190 'page' => $page, //count starts from 0
191 'page_count' => ceil((int) $total / $limit),
192 'limit' => $limit
193 ];
194 }
195
196 return $obj_ret;
197 }
198
207 public function post($request_data = null)
208 {
209 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
210 throw new RestException(403, "Insuffisant rights");
211 }
212 // Check mandatory fields
213 $result = $this->_validate($request_data);
214
215 foreach ($request_data as $field => $value) {
216 if ($field === 'caller') {
217 // 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
218 $this->shipment->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
219 continue;
220 }
221
222 $this->shipment->$field = $this->_checkValForAPI($field, $value, $this->shipment);
223 }
224 if (isset($request_data["lines"])) {
225 $lines = array();
226 foreach ($request_data["lines"] as $line) {
227 $shipmentline = new ExpeditionLigne($this->db);
228
229 $shipmentline->entrepot_id = (int) $line['entrepot_id'];
230 $shipmentline->fk_element = (int) ($line['fk_element'] ?? $line['origin_id']); // example: order id. this->origin is 'commande'
231 $shipmentline->origin_line_id = (int) ($line['fk_elementdet'] ?? $line['origin_line_id']); // example: order id
232 $shipmentline->fk_elementdet = (int) ($line['fk_elementdet'] ?? $line['origin_line_id']); // example: order line id
233 $shipmentline->origin_type = $line['element_type'] ?? $line['origin_type']; // example 'commande' or 'order'
234 $shipmentline->element_type = $line['element_type'] ?? $line['origin_type']; // example 'commande' or 'order'
235 $shipmentline->qty = (float) $line['qty'];
236 $shipmentline->rang = (int) $line['rang'];
237 $array_options = $line['array_options'];
238 if (is_array($array_options)) {
239 $shipmentline->array_options = $array_options;
240 }
241 $detail_batch = $line['detail_batch'];
242 if (is_array($detail_batch) || is_object($detail_batch)) {
243 $shipmentline->detail_batch = $detail_batch;
244 }
245 $lines[] = $shipmentline;
246 }
247 $this->shipment->lines = $lines;
248 }
249
250 if ($this->shipment->create(DolibarrApiAccess::$user) < 0) {
251 throw new RestException(500, "Error creating shipment", array_merge(array($this->shipment->error), $this->shipment->errors));
252 }
253
254 return $this->shipment->id;
255 }
256
257 // /**
258 // * Get lines of an shipment
259 // *
260 // * @param int $id Id of shipment
261 // *
262 // * @url GET {id}/lines
263 // *
264 // * @return int
265 // */
266 /*
267 public function getLines($id)
268 {
269 if(! DolibarrApiAccess::$user->hasRight('expedition', 'lire')) {
270 throw new RestException(403);
271 }
272
273 $result = $this->shipment->fetch($id);
274 if( ! $result ) {
275 throw new RestException(404, 'Shipment not found');
276 }
277
278 if( ! DolibarrApi::_checkAccessToResource('expedition',$this->shipment->id)) {
279 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
280 }
281 $this->shipment->getLinesArray();
282 $result = array();
283 foreach ($this->shipment->lines as $line) {
284 array_push($result,$this->_cleanObjectDatas($line));
285 }
286 return $result;
287 }
288 */
289
290 // /**
291 // * Add a line to given shipment
292 // *
293 // * @param int $id Id of shipment to update
294 // * @param array $request_data ShipmentLine data
295 // * @phan-param ?array<string,string> $request_data
296 // * @phpstan-param ?array<string,string> $request_data
297 // *
298 // * @url POST {id}/lines
299 // *
300 // * @return int
301 // */
302 /*
303 public function postLine($id, $request_data = null)
304 {
305 if(! DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
306 throw new RestException(403);
307 }
308
309 $result = $this->shipment->fetch($id);
310 if ( ! $result ) {
311 throw new RestException(404, 'Shipment not found');
312 }
313
314 if( ! DolibarrApi::_checkAccessToResource('expedition',$this->shipment->id)) {
315 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
316 }
317
318 $request_data = (object) $request_data;
319
320 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
321 $request_data->label = sanitizeVal($request_data->label);
322
323 $updateRes = $this->shipment->addline(
324 $request_data->desc,
325 $request_data->subprice,
326 $request_data->qty,
327 $request_data->tva_tx,
328 $request_data->localtax1_tx,
329 $request_data->localtax2_tx,
330 $request_data->fk_product,
331 $request_data->remise_percent,
332 $request_data->info_bits,
333 $request_data->fk_remise_except,
334 'HT',
335 0,
336 $request_data->date_start,
337 $request_data->date_end,
338 $request_data->product_type,
339 $request_data->rang,
340 $request_data->special_code,
341 $fk_parent_line,
342 $request_data->fk_fournprice,
343 $request_data->pa_ht,
344 $request_data->label,
345 $request_data->array_options,
346 $request_data->fk_unit,
347 $request_data->origin,
348 $request_data->origin_id,
349 $request_data->multicurrency_subprice
350 );
351
352 if ($updateRes > 0) {
353 return $updateRes;
354
355 }
356 return false;
357 }*/
358
359 // /**
360 // * Update a line to given shipment
361 // *
362 // * @param int $id Id of shipment to update
363 // * @param int $lineid Id of line to update
364 // * @param array $request_data ShipmentLine data
365 // *
366 // * @url PUT {id}/lines/{lineid}
367 // *
368 // * @return object
369 // */
370 /*
371 public function putLine($id, $lineid, $request_data = null)
372 {
373 if (! DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
374 throw new RestException(403);
375 }
376
377 $result = $this->shipment->fetch($id);
378 if ( ! $result ) {
379 throw new RestException(404, 'Shipment not found');
380 }
381
382 if( ! DolibarrApi::_checkAccessToResource('expedition',$this->shipment->id)) {
383 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
384 }
385
386 $request_data = (object) $request_data;
387
388 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
389 $request_data->label = sanitizeVal($request_data->label);
390
391 $updateRes = $this->shipment->updateline(
392 $lineid,
393 $request_data->desc,
394 $request_data->subprice,
395 $request_data->qty,
396 $request_data->remise_percent,
397 $request_data->tva_tx,
398 $request_data->localtax1_tx,
399 $request_data->localtax2_tx,
400 'HT',
401 $request_data->info_bits,
402 $request_data->date_start,
403 $request_data->date_end,
404 $request_data->product_type,
405 $request_data->fk_parent_line,
406 0,
407 $request_data->fk_fournprice,
408 $request_data->pa_ht,
409 $request_data->label,
410 $request_data->special_code,
411 $request_data->array_options,
412 $request_data->fk_unit,
413 $request_data->multicurrency_subprice
414 );
415
416 if ($updateRes > 0) {
417 $result = $this->get($id);
418 unset($result->line);
419 return $this->_cleanObjectDatas($result);
420 }
421 return false;
422 }*/
423
440 public function deleteLine($id, $lineid)
441 {
442 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
443 throw new RestException(403);
444 }
445
446 $result = $this->shipment->fetch($id);
447 if (!$result) {
448 throw new RestException(404, 'Shipment not found');
449 }
450
451 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
452 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
453 }
454
455 // TODO Check the lineid $lineid is a line of object
456
457 $updateRes = $this->shipment->deleteLine(DolibarrApiAccess::$user, $lineid);
458 if ($updateRes > 0) {
459 return array(
460 'success' => array(
461 'code' => 200,
462 'message' => 'line ' .$lineid. ' deleted'
463 )
464 );
465 } else {
466 throw new RestException(405, $this->shipment->error);
467 }
468 }
469
479 public function put($id, $request_data = null)
480 {
481 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
482 throw new RestException(403);
483 }
484
485 $result = $this->shipment->fetch($id);
486 if (!$result) {
487 throw new RestException(404, 'Shipment not found');
488 }
489
490 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
491 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
492 }
493 foreach ($request_data as $field => $value) {
494 if ($field == 'id') {
495 continue;
496 }
497 if ($field === 'caller') {
498 // 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
499 $this->shipment->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
500 continue;
501 }
502
503 if ($field == 'array_options' && is_array($value)) {
504 foreach ($value as $index => $val) {
505 $this->shipment->array_options[$index] = $this->_checkValForAPI($field, $val, $this->shipment);
506 }
507 continue;
508 }
509 $this->shipment->$field = $this->_checkValForAPI($field, $value, $this->shipment);
510 }
511
512 if ($this->shipment->update(DolibarrApiAccess::$user) > 0) {
513 return $this->get($id);
514 } else {
515 throw new RestException(500, $this->shipment->error);
516 }
517 }
518
528 public function delete($id)
529 {
530 if (!DolibarrApiAccess::$user->hasRight('expedition', 'supprimer')) {
531 throw new RestException(403);
532 }
533 $result = $this->shipment->fetch($id);
534 if (!$result) {
535 throw new RestException(404, 'Shipment not found');
536 }
537
538 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
539 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
540 }
541
542 if (!$this->shipment->delete(DolibarrApiAccess::$user)) {
543 throw new RestException(500, 'Error when deleting shipment : '.$this->shipment->error);
544 }
545
546 return array(
547 'success' => array(
548 'code' => 200,
549 'message' => 'Shipment deleted'
550 )
551 );
552 }
553
573 public function validate($id, $notrigger = 0)
574 {
575 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
576 throw new RestException(403);
577 }
578 $result = $this->shipment->fetch($id);
579 if (!$result) {
580 throw new RestException(404, 'Shipment not found');
581 }
582
583 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
584 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
585 }
586
587 $result = $this->shipment->valid(DolibarrApiAccess::$user, $notrigger);
588 if ($result == 0) {
589 throw new RestException(304, 'Error nothing done. May be object is already validated');
590 }
591 if ($result < 0) {
592 throw new RestException(500, 'Error when validating Shipment: '.$this->shipment->error);
593 }
594
595 // Reload shipment
596 $result = $this->shipment->fetch($id);
597
598 $this->shipment->fetchObjectLinked();
599 return $this->_cleanObjectDatas($this->shipment);
600 }
601
602
603 // /**
604 // * Classify the shipment as invoiced
605 // *
606 // * @param int $id Id of the shipment
607 // *
608 // * @url POST {id}/setinvoiced
609 // *
610 // * @return int
611 // *
612 // * @throws RestException 400
613 // * @throws RestException 401
614 // * @throws RestException 404
615 // * @throws RestException 405
616 // */
617 /*
618 public function setinvoiced($id)
619 {
620
621 if(! DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
622 throw new RestException(403);
623 }
624 if(empty($id)) {
625 throw new RestException(400, 'Shipment ID is mandatory');
626 }
627 $result = $this->shipment->fetch($id);
628 if( ! $result ) {
629 throw new RestException(404, 'Shipment not found');
630 }
631
632 $result = $this->shipment->classifyBilled(DolibarrApiAccess::$user);
633 if( $result < 0) {
634 throw new RestException(400, $this->shipment->error);
635 }
636 return $result;
637 }
638 */
639
640
641 // /**
642 // * Create a shipment using an existing order.
643 // *
644 // * @param int $orderid Id of the order
645 // *
646 // * @url POST /createfromorder/{orderid}
647 // *
648 // * @return int
649 // * @throws RestException 400
650 // * @throws RestException 401
651 // * @throws RestException 404
652 // * @throws RestException 405
653 // */
654 /*
655 public function createShipmentFromOrder($orderid)
656 {
657
658 require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
659
660 if(! DolibarrApiAccess::$user->hasRight('expedition', 'lire')) {
661 throw new RestException(403);
662 }
663 if(! DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
664 throw new RestException(403);
665 }
666 if(empty($proposalid)) {
667 throw new RestException(400, 'Order ID is mandatory');
668 }
669
670 $order = new Commande($this->db);
671 $result = $order->fetch($proposalid);
672 if( ! $result ) {
673 throw new RestException(404, 'Order not found');
674 }
675
676 $result = $this->shipment->createFromOrder($order, DolibarrApiAccess::$user);
677 if( $result < 0) {
678 throw new RestException(405, $this->shipment->error);
679 }
680 $this->shipment->fetchObjectLinked();
681 return $this->_cleanObjectDatas($this->shipment);
682 }
683 */
684
695 public function close($id, $notrigger = 0)
696 {
697 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
698 throw new RestException(403);
699 }
700
701 $result = $this->shipment->fetch($id);
702 if (!$result) {
703 throw new RestException(404, 'Shipment not found');
704 }
705
706 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
707 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
708 }
709
710 $result = $this->shipment->setClosed();
711 if ($result == 0) {
712 throw new RestException(304, 'Error nothing done. May be object is already closed');
713 }
714 if ($result < 0) {
715 throw new RestException(500, 'Error when closing Order: '.$this->shipment->error);
716 }
717
718 // Reload shipment
719 $result = $this->shipment->fetch($id);
720
721 $this->shipment->fetchObjectLinked();
722
723 return $this->_cleanObjectDatas($this->shipment);
724 }
725
726 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
733 protected function _cleanObjectDatas($object)
734 {
735 // phpcs:enable
736 $object = parent::_cleanObjectDatas($object);
737
738 unset($object->canvas);
739
740 unset($object->thirdparty); // id already returned
741
742 unset($object->note);
743 unset($object->address);
744 unset($object->barcode_type);
745 unset($object->barcode_type_code);
746 unset($object->barcode_type_label);
747 unset($object->barcode_type_coder);
748
749 if (!empty($object->lines) && is_array($object->lines)) {
750 foreach ($object->lines as $line) {
751 if (is_array($line->detail_batch)) {
752 foreach ($line->detail_batch as $keytmp2 => $valtmp2) {
753 unset($line->detail_batch[$keytmp2]->db);
754 }
755 }
756 unset($line->canvas);
757
758 unset($line->tva_tx);
759 unset($line->vat_src_code);
760 unset($line->total_ht);
761 unset($line->total_ttc);
762 unset($line->total_tva);
763 unset($line->total_localtax1);
764 unset($line->total_localtax2);
765 unset($line->remise_percent);
766 }
767 }
768
769 return $object;
770 }
771
779 private function _validate($data)
780 {
781 if ($data === null) {
782 $data = array();
783 }
784 $shipment = array();
785 foreach (Shipments::$FIELDS as $field) {
786 if (!isset($data[$field])) {
787 throw new RestException(400, "$field field missing");
788 }
789 $shipment[$field] = $data[$field];
790 }
791 return $shipment;
792 }
793}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
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 lines of shipment.
close($id, $notrigger=0)
Classify the shipment as invoiced.
_validate($data)
Validate fields before create or update object.
put($id, $request_data=null)
Update shipment general fields (won't touch lines of shipment)
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $sqlfilters='', $properties='', $pagination_data=false)
List shipments.
validate($id, $notrigger=0)
Validate a shipment.
__construct()
Constructor.
post($request_data=null)
Create shipment object.
_cleanObjectDatas($object)
Clean sensible object datas.
deleteLine($id, $lineid)
Get lines of an shipment.
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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79