dolibarr 21.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 *
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
19 use Luracast\Restler\RestException;
20
21 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
22
30{
34 public static $FIELDS = array(
35 'socid',
36 'origin_id',
37 'origin_type',
38 );
39
43 public $shipment;
44
48 public function __construct()
49 {
50 global $db, $conf;
51 $this->db = $db;
52 $this->shipment = new Expedition($this->db);
53 }
54
65 public function get($id)
66 {
67 if (!DolibarrApiAccess::$user->hasRight('expedition', 'lire')) {
68 throw new RestException(403);
69 }
70
71 $result = $this->shipment->fetch($id);
72 if (!$result) {
73 throw new RestException(404, 'Shipment not found');
74 }
75
76 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
77 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
78 }
79
80 $this->shipment->fetchObjectLinked();
81 return $this->_cleanObjectDatas($this->shipment);
82 }
83
84
85
103 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
104 {
105 if (!DolibarrApiAccess::$user->hasRight('expedition', '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') && !$socids) {
117 $search_sale = DolibarrApiAccess::$user->id;
118 }
119
120 $sql = "SELECT t.rowid";
121 $sql .= " FROM ".MAIN_DB_PREFIX."expedition AS t";
122 $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
123 $sql .= ' WHERE t.entity IN ('.getEntity('expedition').')';
124 if ($socids) {
125 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
126 }
127 // Search on sale representative
128 if ($search_sale && $search_sale != '-1') {
129 if ($search_sale == -2) {
130 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
131 } elseif ($search_sale > 0) {
132 $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).")";
133 }
134 }
135 // Add sql filters
136 if ($sqlfilters) {
137 $errormessage = '';
138 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
139 if ($errormessage) {
140 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
141 }
142 }
143
144 //this query will return total shipments with the filters given
145 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
146
147 $sql .= $this->db->order($sortfield, $sortorder);
148 if ($limit) {
149 if ($page < 0) {
150 $page = 0;
151 }
152 $offset = $limit * $page;
153
154 $sql .= $this->db->plimit($limit + 1, $offset);
155 }
156
157 dol_syslog("API Rest request");
158 $result = $this->db->query($sql);
159
160 if ($result) {
161 $num = $this->db->num_rows($result);
162 $min = min($num, ($limit <= 0 ? $num : $limit));
163 $i = 0;
164 while ($i < $min) {
165 $obj = $this->db->fetch_object($result);
166 $shipment_static = new Expedition($this->db);
167 if ($shipment_static->fetch($obj->rowid)) {
168 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($shipment_static), $properties);
169 }
170 $i++;
171 }
172 } else {
173 throw new RestException(503, 'Error when retrieve commande list : '.$this->db->lasterror());
174 }
175
176 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
177 if ($pagination_data) {
178 $totalsResult = $this->db->query($sqlTotals);
179 $total = $this->db->fetch_object($totalsResult)->total;
180
181 $tmp = $obj_ret;
182 $obj_ret = [];
183
184 $obj_ret['data'] = $tmp;
185 $obj_ret['pagination'] = [
186 'total' => (int) $total,
187 'page' => $page, //count starts from 0
188 'page_count' => ceil((int) $total / $limit),
189 'limit' => $limit
190 ];
191 }
192
193 return $obj_ret;
194 }
195
202 public function post($request_data = null)
203 {
204 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
205 throw new RestException(403, "Insuffisant rights");
206 }
207 // Check mandatory fields
208 $result = $this->_validate($request_data);
209
210 foreach ($request_data as $field => $value) {
211 if ($field === 'caller') {
212 // 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
213 $this->shipment->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
214 continue;
215 }
216
217 $this->shipment->$field = $this->_checkValForAPI($field, $value, $this->shipment);
218 }
219 if (isset($request_data["lines"])) {
220 $lines = array();
221 foreach ($request_data["lines"] as $line) {
222 $shipmentline = new ExpeditionLigne($this->db);
223
224 $shipmentline->entrepot_id = $line['entrepot_id'];
225 $shipmentline->fk_element = $line['fk_element'] ?? $line['origin_id']; // example: order id. this->origin is 'commande'
226 $shipmentline->origin_line_id = $line['fk_elementdet'] ?? $line['origin_line_id']; // example: order id
227 $shipmentline->fk_elementdet = $line['fk_elementdet'] ?? $line['origin_line_id']; // example: order line id
228 $shipmentline->origin_type = $line['element_type'] ?? $line['origin_type']; // example 'commande' or 'order'
229 $shipmentline->element_type = $line['element_type'] ?? $line['origin_type']; // example 'commande' or 'order'
230 $shipmentline->qty = $line['qty'];
231 $shipmentline->rang = $line['rang'];
232 $shipmentline->array_options = $line['array_options'];
233 $shipmentline->detail_batch = $line['detail_batch'];
234
235 $lines[] = $shipmentline;
236 }
237 $this->shipment->lines = $lines;
238 }
239
240 if ($this->shipment->create(DolibarrApiAccess::$user) < 0) {
241 throw new RestException(500, "Error creating shipment", array_merge(array($this->shipment->error), $this->shipment->errors));
242 }
243
244 return $this->shipment->id;
245 }
246
247 // /**
248 // * Get lines of an shipment
249 // *
250 // * @param int $id Id of shipment
251 // *
252 // * @url GET {id}/lines
253 // *
254 // * @return int
255 // */
256 /*
257 public function getLines($id)
258 {
259 if(! DolibarrApiAccess::$user->hasRight('expedition', 'lire')) {
260 throw new RestException(403);
261 }
262
263 $result = $this->shipment->fetch($id);
264 if( ! $result ) {
265 throw new RestException(404, 'Shipment not found');
266 }
267
268 if( ! DolibarrApi::_checkAccessToResource('expedition',$this->shipment->id)) {
269 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
270 }
271 $this->shipment->getLinesArray();
272 $result = array();
273 foreach ($this->shipment->lines as $line) {
274 array_push($result,$this->_cleanObjectDatas($line));
275 }
276 return $result;
277 }
278 */
279
280 // /**
281 // * Add a line to given shipment
282 // *
283 // * @param int $id Id of shipment to update
284 // * @param array $request_data ShipmentLine data
285 // *
286 // * @url POST {id}/lines
287 // *
288 // * @return int
289 // */
290 /*
291 public function postLine($id, $request_data = null)
292 {
293 if(! DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
294 throw new RestException(403);
295 }
296
297 $result = $this->shipment->fetch($id);
298 if ( ! $result ) {
299 throw new RestException(404, 'Shipment not found');
300 }
301
302 if( ! DolibarrApi::_checkAccessToResource('expedition',$this->shipment->id)) {
303 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
304 }
305
306 $request_data = (object) $request_data;
307
308 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
309 $request_data->label = sanitizeVal($request_data->label);
310
311 $updateRes = $this->shipment->addline(
312 $request_data->desc,
313 $request_data->subprice,
314 $request_data->qty,
315 $request_data->tva_tx,
316 $request_data->localtax1_tx,
317 $request_data->localtax2_tx,
318 $request_data->fk_product,
319 $request_data->remise_percent,
320 $request_data->info_bits,
321 $request_data->fk_remise_except,
322 'HT',
323 0,
324 $request_data->date_start,
325 $request_data->date_end,
326 $request_data->product_type,
327 $request_data->rang,
328 $request_data->special_code,
329 $fk_parent_line,
330 $request_data->fk_fournprice,
331 $request_data->pa_ht,
332 $request_data->label,
333 $request_data->array_options,
334 $request_data->fk_unit,
335 $request_data->origin,
336 $request_data->origin_id,
337 $request_data->multicurrency_subprice
338 );
339
340 if ($updateRes > 0) {
341 return $updateRes;
342
343 }
344 return false;
345 }*/
346
347 // /**
348 // * Update a line to given shipment
349 // *
350 // * @param int $id Id of shipment to update
351 // * @param int $lineid Id of line to update
352 // * @param array $request_data ShipmentLine data
353 // *
354 // * @url PUT {id}/lines/{lineid}
355 // *
356 // * @return object
357 // */
358 /*
359 public function putLine($id, $lineid, $request_data = null)
360 {
361 if (! DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
362 throw new RestException(403);
363 }
364
365 $result = $this->shipment->fetch($id);
366 if ( ! $result ) {
367 throw new RestException(404, 'Shipment not found');
368 }
369
370 if( ! DolibarrApi::_checkAccessToResource('expedition',$this->shipment->id)) {
371 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
372 }
373
374 $request_data = (object) $request_data;
375
376 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
377 $request_data->label = sanitizeVal($request_data->label);
378
379 $updateRes = $this->shipment->updateline(
380 $lineid,
381 $request_data->desc,
382 $request_data->subprice,
383 $request_data->qty,
384 $request_data->remise_percent,
385 $request_data->tva_tx,
386 $request_data->localtax1_tx,
387 $request_data->localtax2_tx,
388 'HT',
389 $request_data->info_bits,
390 $request_data->date_start,
391 $request_data->date_end,
392 $request_data->product_type,
393 $request_data->fk_parent_line,
394 0,
395 $request_data->fk_fournprice,
396 $request_data->pa_ht,
397 $request_data->label,
398 $request_data->special_code,
399 $request_data->array_options,
400 $request_data->fk_unit,
401 $request_data->multicurrency_subprice
402 );
403
404 if ($updateRes > 0) {
405 $result = $this->get($id);
406 unset($result->line);
407 return $this->_cleanObjectDatas($result);
408 }
409 return false;
410 }*/
411
426 public function deleteLine($id, $lineid)
427 {
428 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
429 throw new RestException(403);
430 }
431
432 $result = $this->shipment->fetch($id);
433 if (!$result) {
434 throw new RestException(404, 'Shipment not found');
435 }
436
437 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
438 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
439 }
440
441 // TODO Check the lineid $lineid is a line of object
442
443 $updateRes = $this->shipment->deleteLine(DolibarrApiAccess::$user, $lineid);
444 if ($updateRes > 0) {
445 return array(
446 'success' => array(
447 'code' => 200,
448 'message' => 'line ' .$lineid. ' deleted'
449 )
450 );
451 } else {
452 throw new RestException(405, $this->shipment->error);
453 }
454 }
455
463 public function put($id, $request_data = null)
464 {
465 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
466 throw new RestException(403);
467 }
468
469 $result = $this->shipment->fetch($id);
470 if (!$result) {
471 throw new RestException(404, 'Shipment not found');
472 }
473
474 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
475 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
476 }
477 foreach ($request_data as $field => $value) {
478 if ($field == 'id') {
479 continue;
480 }
481 if ($field === 'caller') {
482 // 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
483 $this->shipment->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
484 continue;
485 }
486
487 $this->shipment->$field = $this->_checkValForAPI($field, $value, $this->shipment);
488 }
489
490 if ($this->shipment->update(DolibarrApiAccess::$user) > 0) {
491 return $this->get($id);
492 } else {
493 throw new RestException(500, $this->shipment->error);
494 }
495 }
496
504 public function delete($id)
505 {
506 if (!DolibarrApiAccess::$user->hasRight('expedition', 'supprimer')) {
507 throw new RestException(403);
508 }
509 $result = $this->shipment->fetch($id);
510 if (!$result) {
511 throw new RestException(404, 'Shipment not found');
512 }
513
514 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
515 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
516 }
517
518 if (!$this->shipment->delete(DolibarrApiAccess::$user)) {
519 throw new RestException(500, 'Error when deleting shipment : '.$this->shipment->error);
520 }
521
522 return array(
523 'success' => array(
524 'code' => 200,
525 'message' => 'Shipment deleted'
526 )
527 );
528 }
529
549 public function validate($id, $notrigger = 0)
550 {
551 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
552 throw new RestException(403);
553 }
554 $result = $this->shipment->fetch($id);
555 if (!$result) {
556 throw new RestException(404, 'Shipment not found');
557 }
558
559 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
560 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
561 }
562
563 $result = $this->shipment->valid(DolibarrApiAccess::$user, $notrigger);
564 if ($result == 0) {
565 throw new RestException(304, 'Error nothing done. May be object is already validated');
566 }
567 if ($result < 0) {
568 throw new RestException(500, 'Error when validating Shipment: '.$this->shipment->error);
569 }
570
571 // Reload shipment
572 $result = $this->shipment->fetch($id);
573
574 $this->shipment->fetchObjectLinked();
575 return $this->_cleanObjectDatas($this->shipment);
576 }
577
578
579 // /**
580 // * Classify the shipment as invoiced
581 // *
582 // * @param int $id Id of the shipment
583 // *
584 // * @url POST {id}/setinvoiced
585 // *
586 // * @return int
587 // *
588 // * @throws RestException 400
589 // * @throws RestException 401
590 // * @throws RestException 404
591 // * @throws RestException 405
592 // */
593 /*
594 public function setinvoiced($id)
595 {
596
597 if(! DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
598 throw new RestException(403);
599 }
600 if(empty($id)) {
601 throw new RestException(400, 'Shipment ID is mandatory');
602 }
603 $result = $this->shipment->fetch($id);
604 if( ! $result ) {
605 throw new RestException(404, 'Shipment not found');
606 }
607
608 $result = $this->shipment->classifyBilled(DolibarrApiAccess::$user);
609 if( $result < 0) {
610 throw new RestException(400, $this->shipment->error);
611 }
612 return $result;
613 }
614 */
615
616
617 // /**
618 // * Create a shipment using an existing order.
619 // *
620 // * @param int $orderid Id of the order
621 // *
622 // * @url POST /createfromorder/{orderid}
623 // *
624 // * @return int
625 // * @throws RestException 400
626 // * @throws RestException 401
627 // * @throws RestException 404
628 // * @throws RestException 405
629 // */
630 /*
631 public function createShipmentFromOrder($orderid)
632 {
633
634 require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
635
636 if(! DolibarrApiAccess::$user->hasRight('expedition', 'lire')) {
637 throw new RestException(403);
638 }
639 if(! DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
640 throw new RestException(403);
641 }
642 if(empty($proposalid)) {
643 throw new RestException(400, 'Order ID is mandatory');
644 }
645
646 $order = new Commande($this->db);
647 $result = $order->fetch($proposalid);
648 if( ! $result ) {
649 throw new RestException(404, 'Order not found');
650 }
651
652 $result = $this->shipment->createFromOrder($order, DolibarrApiAccess::$user);
653 if( $result < 0) {
654 throw new RestException(405, $this->shipment->error);
655 }
656 $this->shipment->fetchObjectLinked();
657 return $this->_cleanObjectDatas($this->shipment);
658 }
659 */
660
671 public function close($id, $notrigger = 0)
672 {
673 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
674 throw new RestException(403);
675 }
676
677 $result = $this->shipment->fetch($id);
678 if (!$result) {
679 throw new RestException(404, 'Shipment not found');
680 }
681
682 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
683 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
684 }
685
686 $result = $this->shipment->setClosed();
687 if ($result == 0) {
688 throw new RestException(304, 'Error nothing done. May be object is already closed');
689 }
690 if ($result < 0) {
691 throw new RestException(500, 'Error when closing Order: '.$this->shipment->error);
692 }
693
694 // Reload shipment
695 $result = $this->shipment->fetch($id);
696
697 $this->shipment->fetchObjectLinked();
698
699 return $this->_cleanObjectDatas($this->shipment);
700 }
701
702 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
709 protected function _cleanObjectDatas($object)
710 {
711 // phpcs:enable
712 $object = parent::_cleanObjectDatas($object);
713
714 unset($object->canvas);
715
716 unset($object->thirdparty); // id already returned
717
718 unset($object->note);
719 unset($object->address);
720 unset($object->barcode_type);
721 unset($object->barcode_type_code);
722 unset($object->barcode_type_label);
723 unset($object->barcode_type_coder);
724
725 if (!empty($object->lines) && is_array($object->lines)) {
726 foreach ($object->lines as $line) {
727 if (is_array($line->detail_batch)) {
728 foreach ($line->detail_batch as $keytmp2 => $valtmp2) {
729 unset($line->detail_batch[$keytmp2]->db);
730 }
731 }
732 unset($line->canvas);
733
734 unset($line->tva_tx);
735 unset($line->vat_src_code);
736 unset($line->total_ht);
737 unset($line->total_ttc);
738 unset($line->total_tva);
739 unset($line->total_localtax1);
740 unset($line->total_localtax2);
741 unset($line->remise_percent);
742 }
743 }
744
745 return $object;
746 }
747
755 private function _validate($data)
756 {
757 $shipment = array();
758 foreach (Shipments::$FIELDS as $field) {
759 if (!isset($data[$field])) {
760 throw new RestException(400, "$field field missing");
761 }
762 $shipment[$field] = $data[$field];
763 }
764 return $shipment;
765 }
766}
$id
Definition account.php:39
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
Class for API REST v1.
Definition api.class.php:30
_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:82
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.