dolibarr 25.0.0-alpha
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 * Copyright (C) 2025 Charlene Benke <charlene@patas-monkey.com>
6 * Copyright (C) 2025 Frédéric France <frederic.france@free.fr>
7 * Copyright (C) 2025 Nick Fragoulis
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
23use Luracast\Restler\RestException;
24
25require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
26require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
27
35{
39 public static $FIELDS = array(
40 'socid',
41 'origin_id',
42 'origin_type',
43 );
44
48 public $shipment;
49
53 public function __construct()
54 {
55 global $db;
56 $this->db = $db;
57 $this->shipment = new Expedition($this->db);
58 }
59
70 public function get($id)
71 {
72 if (!DolibarrApiAccess::$user->hasRight('expedition', 'lire')) {
73 throw new RestException(403);
74 }
75
76 $result = $this->shipment->fetch($id);
77 if (!$result) {
78 throw new RestException(404, 'Shipment not found');
79 }
80
81 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
82 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
83 }
84
85 $this->shipment->fetchObjectLinked();
86 return $this->_cleanObjectDatas($this->shipment);
87 }
88
89
90
110 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
111 {
112 if (!DolibarrApiAccess::$user->hasRight('expedition', 'lire')) {
113 throw new RestException(403);
114 }
115
116 global $hookmanager;
117
118 $obj_ret = array();
119
120 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
121 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
122
123 // If the internal user must only see his customers, force searching by him
124 $search_sale = 0;
125 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
126 $search_sale = DolibarrApiAccess::$user->id;
127 }
128
129 $sql = "SELECT t.rowid";
130 $sql .= " FROM ".MAIN_DB_PREFIX."expedition AS t";
131 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe AS s ON (s.rowid = t.fk_soc)";
132 $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
133 $sql .= ' WHERE t.entity IN ('.getEntity('expedition').')';
134 if ($socids) {
135 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
136 }
137 // Search on sale representative
138 if ($search_sale && $search_sale != '-1') {
139 if ($search_sale == -2) {
140 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', 0, 1);
141 } elseif ($search_sale > 0) {
142 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', (int) $search_sale);
143 }
144 }
145 // Add sql filters
146 if ($sqlfilters) {
147 $parameters = array('sqlfilters' => $sqlfilters, 'apiroute' => 'shipments', 'apimethod' => 'index');
148 $object = new stdClass();
149 $action = 'list';
150 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
151 if ($reshook > 0) {
152 $sql = $hookmanager->resPrint;
153 } elseif ($reshook == 0) {
154 $sql .= $hookmanager->resPrint;
155 }
156 $errormessage = '';
157 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
158 if ($errormessage) {
159 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
160 }
161 }
162
163 //this query will return total shipments with the filters given
164 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
165
166 $sql .= $this->db->order($sortfield, $sortorder);
167 if ($limit) {
168 if ($page < 0) {
169 $page = 0;
170 }
171 $offset = $limit * $page;
172
173 $sql .= $this->db->plimit($limit + 1, $offset);
174 }
175
176 dol_syslog("API Rest request");
177 $result = $this->db->query($sql);
178
179 if ($result) {
180 $num = $this->db->num_rows($result);
181 $min = min($num, ($limit <= 0 ? $num : $limit));
182 $i = 0;
183 while ($i < $min) {
184 $obj = $this->db->fetch_object($result);
185 $shipment_static = new Expedition($this->db);
186 if ($shipment_static->fetch($obj->rowid)) {
187 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($shipment_static), $properties);
188 }
189 $i++;
190 }
191 } else {
192 throw new RestException(503, 'Error when retrieving shipments list : '.$this->db->lasterror());
193 }
194
195 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
196 if ($pagination_data) {
197 $totalsResult = $this->db->query($sqlTotals);
198 $total = $this->db->fetch_object($totalsResult)->total;
199
200 $tmp = $obj_ret;
201 $obj_ret = [];
202
203 $obj_ret['data'] = $tmp;
204 $obj_ret['pagination'] = [
205 'total' => (int) $total,
206 'page' => $page, //count starts from 0
207 'page_count' => ceil((int) $total / $limit),
208 'limit' => $limit
209 ];
210 }
211
212 return $obj_ret;
213 }
214
223 public function post($request_data = null)
224 {
225 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
226 throw new RestException(403, "Insufficiant rights");
227 }
228 // Check mandatory fields
229 $result = $this->_validate($request_data);
230
231 foreach ($request_data as $field => $value) {
232 if ($field === 'caller') {
233 // 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
234 $this->shipment->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
235 continue;
236 }
237
238 $this->shipment->$field = $this->_checkValForAPI($field, $value, $this->shipment);
239 }
240
241 // A standalone shipment has no source order line to point to: its lines are free
242 // lines, recorded with addlinefree() exactly as the shipment card records them.
243 if (getDolGlobalString('SHIPMENT_STANDALONE') && !isset($request_data['origin_id']) && !isset($request_data['origin_type'])) {
244 return $this->createStandalone($request_data['lines'] ?? array());
245 }
246
247 if (isset($request_data["lines"])) {
248 $lines = array();
249 foreach ($request_data["lines"] as $line) {
250 $shipmentline = new ExpeditionLigne($this->db);
251
252 $shipmentline->entrepot_id = (int) $line['entrepot_id'];
253 $shipmentline->fk_element = (int) ($line['fk_element'] ?? $line['origin_id']); // example: order id. this->origin is 'commande'
254 $shipmentline->origin_line_id = (int) ($line['fk_elementdet'] ?? $line['origin_line_id']); // example: order id
255 $shipmentline->fk_elementdet = (int) ($line['fk_elementdet'] ?? $line['origin_line_id']); // example: order line id
256 $shipmentline->origin_type = $line['element_type'] ?? $line['origin_type']; // example 'commande' or 'order'
257 $shipmentline->element_type = $line['element_type'] ?? $line['origin_type']; // example 'commande' or 'order'
258 $shipmentline->qty = (float) $line['qty'];
259 $shipmentline->rang = (int) $line['rang'];
260 $array_options = $line['array_options'];
261 if (is_array($array_options)) {
262 $shipmentline->array_options = $array_options;
263 }
264 $detail_batch = $line['detail_batch'];
265 if (is_array($detail_batch) || is_object($detail_batch)) {
266 $shipmentline->detail_batch = $detail_batch;
267 }
268 $lines[] = $shipmentline;
269 }
270 $this->shipment->lines = $lines;
271 }
272
273 if ($this->shipment->create(DolibarrApiAccess::$user) < 0) {
274 throw new RestException(500, "Error creating shipment", array_merge(array($this->shipment->error), $this->shipment->errors));
275 }
276
277 return $this->shipment->id;
278 }
279
287 private function createStandalone($lines)
288 {
289 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
290
291 if (!is_array($lines)) {
292 throw new RestException(400, 'Field lines must be an array');
293 }
294 $this->shipment->lines = array();
295
296 $this->db->begin();
297
298 if ($this->shipment->create(DolibarrApiAccess::$user) < 0) {
299 $this->db->rollback();
300 throw new RestException(500, "Error creating shipment", array_merge(array($this->shipment->error), $this->shipment->errors));
301 }
302
303 foreach ($lines as $line) {
304 if (!is_array($line)) {
305 $this->db->rollback();
306 throw new RestException(400, 'Each line must be an object');
307 }
308 $fk_product = (int) ($line['fk_product'] ?? 0);
309 $description = sanitizeVal((string) ($line['description'] ?? ($line['desc'] ?? '')), 'restricthtml');
310 $qty = (float) price2num($line['qty'] ?? '', 'MS');
311 $fk_unit = isset($line['fk_unit']) ? (int) $line['fk_unit'] : null;
312
313 $error = '';
314 if (!isset($line['qty']) || $line['qty'] === '') {
315 $error = 'Field qty is mandatory';
316 } elseif ($qty < 0) {
317 $error = 'Field qty cannot be negative';
318 } elseif ($fk_product <= 0 && getDolGlobalString('MAIN_DISABLE_FREE_LINES')) {
319 $error = 'Field fk_product is mandatory (MAIN_DISABLE_FREE_LINES is on)';
320 } elseif ($fk_product <= 0 && $description === '') {
321 $error = 'A line needs a fk_product or a description';
322 } elseif ($fk_product > 0) {
323 $product = new Product($this->db);
324 if ($product->fetch($fk_product) <= 0) {
325 $error = 'Product '.$fk_product.' not found';
326 } elseif ($fk_unit === null) {
327 $fk_unit = $product->fk_unit;
328 }
329 }
330 if ($error !== '') {
331 $this->db->rollback();
332 throw new RestException(400, $error);
333 }
334
335 $array_options = (isset($line['array_options']) && is_array($line['array_options'])) ? $line['array_options'] : array();
336 $rang = (int) ($line['rang'] ?? 0);
337
338 if ($this->shipment->addlinefree($qty, 'shipping', $fk_product, $fk_unit, $rang > 0 ? $rang : -1, $description, 0, $array_options) <= 0) {
339 $this->db->rollback();
340 throw new RestException(500, "Error creating shipment line", array_merge(array($this->shipment->error), $this->shipment->errors));
341 }
342 }
343
344 $this->db->commit();
345
346 return $this->shipment->id;
347 }
348
360 public function getLines($id)
361 {
362 if (!DolibarrApiAccess::$user->hasRight('expedition', 'lire')) {
363 throw new RestException(403);
364 }
365
366 $result = $this->shipment->fetch($id);
367 if (!$result) {
368 throw new RestException(404, 'Shipment not found');
369 }
370
371 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
372 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
373 }
374 $this->shipment->getLinesArray();
375 $result = array();
376 foreach ($this->shipment->lines as $line) {
377 array_push($result, $this->_cleanObjectDatas($line));
378 }
379 return $result;
380 }
381
410 public function postLine($id, $fk_origin_line = 0, $qty = 0, $warehouse_id = 0, $fk_product = 0, $description = '')
411 {
412 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
413 throw new RestException(403);
414 }
415
416 $result = $this->shipment->fetch($id);
417 if (!$result) {
418 throw new RestException(404, 'Shipment not found');
419 }
420
421 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
422 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
423 }
424
425 // A line can only be added while the shipment is a draft (no stock movement yet).
426 if ((int) $this->shipment->status != Expedition::STATUS_DRAFT) {
427 throw new RestException(405, 'Lines can only be added to a draft shipment');
428 }
429
430 $fk_origin_line = (int) $fk_origin_line;
431
432 // A shipment without order has no order line to point to: add a free line, as the shipment card does.
433 if ($fk_origin_line <= 0 && empty($this->shipment->origin_id) && getDolGlobalString('SHIPMENT_STANDALONE')) {
434 $qty = (float) $qty;
435 $fk_product = (int) $fk_product;
436 $description = sanitizeVal((string) $description, 'restricthtml');
437 $fk_unit = null;
438
439 if ($qty <= 0) {
440 throw new RestException(400, 'Field qty is mandatory and must be greater than 0');
441 }
442 if ($fk_product > 0) {
443 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
444 $product = new Product($this->db);
445 if ($product->fetch($fk_product) <= 0) {
446 throw new RestException(400, 'Product '.$fk_product.' not found');
447 }
448 $fk_unit = $product->fk_unit;
449 } elseif (getDolGlobalString('MAIN_DISABLE_FREE_LINES')) {
450 throw new RestException(400, 'Field fk_product is mandatory (MAIN_DISABLE_FREE_LINES is on)');
451 } elseif ($description === '') {
452 throw new RestException(400, 'A line needs a fk_product or a description');
453 }
454
455 $lineId = $this->shipment->addlinefree($qty, 'shipping', $fk_product, $fk_unit, -1, $description, 0, array(), (int) $warehouse_id);
456 if ($lineId <= 0) {
457 $msg = $this->shipment->errorsToString() ? $this->shipment->errorsToString() : 'Error while adding shipment line';
458 // -1 missing warehouse, -3 not enough stock, -4 batch product: bad request from the caller.
459 throw new RestException(in_array($lineId, array(-1, -3, -4), true) ? 400 : 500, $msg);
460 }
461
462 return $lineId;
463 }
464
465 if ($fk_origin_line <= 0) {
466 throw new RestException(400, 'Field fk_origin_line is mandatory');
467 }
468
469 $qty = (float) $qty;
470 if ($qty <= 0) {
471 throw new RestException(400, 'Field qty is mandatory and must be greater than 0');
472 }
473
474 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
475 $orderline = new OrderLine($this->db);
476 $resorderline = $orderline->fetch($fk_origin_line);
477 if ($resorderline <= 0) {
478 throw new RestException(404, 'Origin order line '.$fk_origin_line.' not found');
479 }
480 if (isModEnabled('productbatch') && !empty($orderline->product_tobatch)) {
481 throw new RestException(405, 'Adding a batch/lot managed shipment line is not supported through this endpoint. Use the dedicated dispatch flow instead.');
482 }
483
484 // addline() stacks the line in memory and runs native validation
485 // (warehouse requirement, stock availability, batch rejection).
486 $addResult = $this->shipment->addline((int) $warehouse_id, $fk_origin_line, $qty, array(), (int) $fk_product);
487 if ($addResult <= 0) {
488 $msg = $this->shipment->errorsToString() ? $this->shipment->errorsToString() : 'Error while adding shipment line';
489 // -1 missing warehouse, -3 not enough stock, -4 batch product: bad request from the caller.
490 if (in_array((int) $addResult, array(-1, -3, -4), true)) {
491 throw new RestException(400, $msg);
492 }
493 throw new RestException(500, $msg);
494 }
495
496 // addline() only fills $this->shipment->lines; persist the line just stacked.
497 $line = end($this->shipment->lines);
498 $line->fk_expedition = $this->shipment->id;
499
500 $insertRes = $line->insert(DolibarrApiAccess::$user);
501 if ($insertRes > 0) {
502 return $insertRes;
503 }
504
505 throw new RestException(500, $line->errorsToString());
506 }
507
532 public function putLine($id, $lineid, $qty = 0, $warehouse_id = 0)
533 {
534 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
535 throw new RestException(403);
536 }
537
538 $result = $this->shipment->fetch($id);
539 if (!$result) {
540 throw new RestException(404, 'Shipment not found');
541 }
542
543 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
544 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
545 }
546
547 // A line can only be edited while the shipment is a draft (no stock movement yet).
548 if ((int) $this->shipment->status != Expedition::STATUS_DRAFT) {
549 throw new RestException(405, 'Only draft shipment lines can be updated');
550 }
551
552 $qty = (float) $qty;
553 if ($qty <= 0) {
554 throw new RestException(400, 'Field qty is mandatory and must be greater than 0');
555 }
556
557 $line = new ExpeditionLigne($this->db);
558 $resline = $line->fetch($lineid);
559 if ($resline <= 0) {
560 throw new RestException(404, 'Shipment line not found');
561 }
562 if ((int) $line->fk_expedition != (int) $this->shipment->id) {
563 throw new RestException(404, 'Line '.((int) $lineid).' is not a line of shipment '.((int) $id));
564 }
565
566 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionlinebatch.class.php';
567 $linebatch = new ExpeditionLineBatch($this->db);
568 $lots = $linebatch->fetchAll($line->id);
569 if (is_array($lots) && count($lots) > 0) {
570 throw new RestException(405, 'Update of a batch/lot managed shipment line is not supported. Delete and recreate the line instead.');
571 }
572
573 $line->qty = $qty;
574 if ($warehouse_id > 0) {
575 $line->entrepot_id = (int) $warehouse_id;
576 }
577
578 $updateRes = $line->update(DolibarrApiAccess::$user);
579 if ($updateRes > 0) {
580 return $this->get($id);
581 }
582
583 throw new RestException(500, $line->errorsToString() ? $line->errorsToString() : $this->shipment->errorsToString());
584 }
585
605 public function deleteLine($id, $lineid)
606 {
607 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
608 throw new RestException(403);
609 }
610
611 $result = $this->shipment->fetch($id);
612 if (!$result) {
613 throw new RestException(404, 'Shipment not found');
614 }
615
616 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
617 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
618 }
619
620 // A line can only be deleted while the shipment is a draft (no stock movement yet).
621 if ((int) $this->shipment->status != Expedition::STATUS_DRAFT) {
622 throw new RestException(405, 'Only draft shipment lines can be deleted');
623 }
624
625 $line = new ExpeditionLigne($this->db);
626 $resline = $line->fetch($lineid);
627 if ($resline <= 0) {
628 throw new RestException(404, 'Shipment line not found');
629 }
630 if ((int) $line->fk_expedition != (int) $this->shipment->id) {
631 throw new RestException(404, 'Line '.((int) $lineid).' is not a line of shipment '.((int) $id));
632 }
633
634 $deleteRes = $this->shipment->deleteLine(DolibarrApiAccess::$user, $lineid);
635 if ($deleteRes > 0) {
636 return $this->get($id);
637 }
638
639 throw new RestException(500, $this->shipment->errorsToString() ? $this->shipment->errorsToString() : 'Error while deleting shipment line');
640 }
641
651 public function put($id, $request_data = null)
652 {
653 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
654 throw new RestException(403);
655 }
656
657 $result = $this->shipment->fetch($id);
658 if (!$result) {
659 throw new RestException(404, 'Shipment not found');
660 }
661
662 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
663 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
664 }
665 foreach ($request_data as $field => $value) {
666 if ($field == 'id') {
667 continue;
668 }
669 if ($field === 'caller') {
670 // 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
671 $this->shipment->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
672 continue;
673 }
674
675 if ($field == 'array_options' && is_array($value)) {
676 foreach ($value as $index => $val) {
677 $this->shipment->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->shipment);
678 }
679 continue;
680 }
681 $this->shipment->$field = $this->_checkValForAPI($field, $value, $this->shipment);
682 }
683
684 if ($this->shipment->update(DolibarrApiAccess::$user) > 0) {
685 return $this->get($id);
686 } else {
687 throw new RestException(500, $this->shipment->errorsToString());
688 }
689 }
690
700 public function delete($id)
701 {
702 if (!DolibarrApiAccess::$user->hasRight('expedition', 'supprimer')) {
703 throw new RestException(403);
704 }
705 $result = $this->shipment->fetch($id);
706 if (!$result) {
707 throw new RestException(404, 'Shipment not found');
708 }
709
710 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
711 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
712 }
713
714 if (!$this->shipment->delete(DolibarrApiAccess::$user)) {
715 throw new RestException(500, 'Error when deleting shipment : '.$this->shipment->errorsToString());
716 }
717
718 return array(
719 'success' => array(
720 'code' => 200,
721 'message' => 'Shipment deleted'
722 )
723 );
724 }
725
745 public function validate($id, $notrigger = 0)
746 {
747 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
748 throw new RestException(403);
749 }
750 $result = $this->shipment->fetch($id);
751 if (!$result) {
752 throw new RestException(404, 'Shipment not found');
753 }
754
755 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
756 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
757 }
758
759 $result = $this->shipment->valid(DolibarrApiAccess::$user, $notrigger);
760 if ($result == 0) {
761 throw new RestException(304, 'Error nothing done. May be object is already validated');
762 }
763 if ($result < 0) {
764 throw new RestException(500, 'Error when validating Shipment: '.$this->shipment->errorsToString());
765 }
766
767 // Reload shipment
768 $result = $this->shipment->fetch($id);
769
770 $this->shipment->fetchObjectLinked();
771 return $this->_cleanObjectDatas($this->shipment);
772 }
773
774
775 // /**
776 // * Classify the shipment as invoiced
777 // *
778 // * @param int $id Id of the shipment
779 // *
780 // * @url POST {id}/setinvoiced
781 // *
782 // * @return int
783 // *
784 // * @throws RestException 400
785 // * @throws RestException 401
786 // * @throws RestException 404
787 // * @throws RestException 405
788 // */
789 /*
790 public function setinvoiced($id)
791 {
792
793 if(! DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
794 throw new RestException(403);
795 }
796 if(empty($id)) {
797 throw new RestException(400, 'Shipment ID is mandatory');
798 }
799 $result = $this->shipment->fetch($id);
800 if( ! $result ) {
801 throw new RestException(404, 'Shipment not found');
802 }
803
804 $result = $this->shipment->classifyBilled(DolibarrApiAccess::$user);
805 if( $result < 0) {
806 throw new RestException(400, $this->shipment->errorsToString());
807 }
808 return $result;
809 }
810 */
811
812
813 // /**
814 // * Create a shipment using an existing order.
815 // *
816 // * @param int $orderid Id of the order
817 // *
818 // * @url POST /createfromorder/{orderid}
819 // *
820 // * @return int
821 // * @throws RestException 400
822 // * @throws RestException 401
823 // * @throws RestException 404
824 // * @throws RestException 405
825 // */
826 /*
827 public function createShipmentFromOrder($orderid)
828 {
829
830 require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
831
832 if(! DolibarrApiAccess::$user->hasRight('expedition', 'lire')) {
833 throw new RestException(403);
834 }
835 if(! DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
836 throw new RestException(403);
837 }
838 if(empty($proposalid)) {
839 throw new RestException(400, 'Order ID is mandatory');
840 }
841
842 $order = new Commande($this->db);
843 $result = $order->fetch($proposalid);
844 if( ! $result ) {
845 throw new RestException(404, 'Order not found');
846 }
847
848 $result = $this->shipment->createFromOrder($order, DolibarrApiAccess::$user);
849 if( $result < 0) {
850 throw new RestException(405, $this->shipment->errorsToString());
851 }
852 $this->shipment->fetchObjectLinked();
853 return $this->_cleanObjectDatas($this->shipment);
854 }
855 */
856
867 public function close($id, $notrigger = 0)
868 {
869 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
870 throw new RestException(403);
871 }
872
873 $result = $this->shipment->fetch($id);
874 if (!$result) {
875 throw new RestException(404, 'Shipment not found');
876 }
877
878 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
879 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
880 }
881
882 $result = $this->shipment->setClosed();
883 if ($result == 0) {
884 throw new RestException(304, 'Error nothing done. May be object is already closed');
885 }
886 if ($result < 0) {
887 throw new RestException(500, 'Error when closing Order: '.$this->shipment->errorsToString());
888 }
889
890 // Reload shipment
891 $result = $this->shipment->fetch($id);
892
893 $this->shipment->fetchObjectLinked();
894
895 return $this->_cleanObjectDatas($this->shipment);
896 }
897
915 public function setToDraft($id)
916 {
917 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
918 throw new RestException(403);
919 }
920
921 $result = $this->shipment->fetch($id);
922 if (!$result) {
923 throw new RestException(404, 'Shipment not found');
924 }
925
926 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
927 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
928 }
929
930 $result = $this->shipment->setDraft(DolibarrApiAccess::$user);
931 if ($result == 0) {
932 throw new RestException(304, 'Error nothing done. May be object is already draft');
933 }
934 if ($result < 0) {
935 throw new RestException(500, 'Error when setting shipment back to draft: '.$this->shipment->errorsToString());
936 }
937
938 // Reload shipment
939 $result = $this->shipment->fetch($id);
940
941 $this->shipment->fetchObjectLinked();
942
943 return $this->_cleanObjectDatas($this->shipment);
944 }
945
946 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
956 protected function _cleanObjectDatas($object)
957 {
958 // phpcs:enable
959 $object = parent::_cleanObjectDatas($object);
960
961 unset($object->canvas);
962
963 unset($object->thirdparty); // id already returned
964
965 unset($object->note);
966 unset($object->address);
967 unset($object->barcode_type);
968 unset($object->barcode_type_code);
969 unset($object->barcode_type_label);
970 unset($object->barcode_type_coder);
971
972 if (!empty($object->lines) && is_array($object->lines)) {
973 foreach ($object->lines as $line) {
974 if (is_array($line->detail_batch)) {
975 foreach ($line->detail_batch as $keytmp2 => $valtmp2) {
976 unset($line->detail_batch[$keytmp2]->db);
977 }
978 }
979 unset($line->canvas);
980
981 unset($line->tva_tx);
982 unset($line->vat_src_code);
983 unset($line->total_ht);
984 unset($line->total_ttc);
985 unset($line->total_tva);
986 unset($line->total_localtax1);
987 unset($line->total_localtax2);
988 unset($line->remise_percent);
989 }
990 }
991
992 return $object;
993 }
994
1002 private function _validate($data)
1003 {
1004 if ($data === null) {
1005 $data = array();
1006 }
1007 $shipment = array();
1008 // A standalone shipment carries no source document, exactly as the card
1009 // allows when SHIPMENT_STANDALONE is enabled: do not demand an origin the
1010 // user is entitled to omit.
1011 $mandatory = Shipments::$FIELDS;
1012 if (getDolGlobalString('SHIPMENT_STANDALONE') && !isset($data['origin_id']) && !isset($data['origin_type'])) {
1013 $mandatory = array_values(array_diff($mandatory, array('origin_id', 'origin_type')));
1014 }
1015 foreach ($mandatory as $field) {
1016 if (!isset($data[$field])) {
1017 throw new RestException(400, "$field field missing");
1018 }
1019 $shipment[$field] = $data[$field];
1020 }
1021 return $shipment;
1022 }
1023}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
Class for API REST v1.
Definition api.class.php:35
_checkValExtrafieldsForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $parenttableforentity='')
Check access by user to a given resource.
const STATUS_DRAFT
Draft status.
Class to manage lines of shipment.
CRUD class for batch number management within shipment.
Class to manage order lines.
Class to manage products or services.
close($id, $notrigger=0)
Classify the shipment as invoiced.
_validate($data)
Validate fields before create or update object.
postLine($id, $fk_origin_line=0, $qty=0, $warehouse_id=0, $fk_product=0, $description='')
Add a line to a given shipment.
setToDraft($id)
Set a shipment back to draft status.
createStandalone($lines)
Create a standalone shipment (no source order) and its free lines.
put($id, $request_data=null)
Update shipment general fields (won't touch lines of shipment)
putLine($id, $lineid, $qty=0, $warehouse_id=0)
Update a line of a given 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.
getLines($id)
Get lines of a shipment.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
deleteLine($id, $lineid)
Delete a line of a given shipment.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.