dolibarr 21.0.0-beta
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 if ($field == 'array_options' && is_array($value)) {
487 foreach ($value as $index => $val) {
488 $this->shipment->array_options[$index] = $this->_checkValForAPI($field, $val, $this->shipment);
489 }
490 continue;
491 }
492 $this->shipment->$field = $this->_checkValForAPI($field, $value, $this->shipment);
493 }
494
495 if ($this->shipment->update(DolibarrApiAccess::$user) > 0) {
496 return $this->get($id);
497 } else {
498 throw new RestException(500, $this->shipment->error);
499 }
500 }
501
509 public function delete($id)
510 {
511 if (!DolibarrApiAccess::$user->hasRight('expedition', 'supprimer')) {
512 throw new RestException(403);
513 }
514 $result = $this->shipment->fetch($id);
515 if (!$result) {
516 throw new RestException(404, 'Shipment not found');
517 }
518
519 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
520 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
521 }
522
523 if (!$this->shipment->delete(DolibarrApiAccess::$user)) {
524 throw new RestException(500, 'Error when deleting shipment : '.$this->shipment->error);
525 }
526
527 return array(
528 'success' => array(
529 'code' => 200,
530 'message' => 'Shipment deleted'
531 )
532 );
533 }
534
554 public function validate($id, $notrigger = 0)
555 {
556 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
557 throw new RestException(403);
558 }
559 $result = $this->shipment->fetch($id);
560 if (!$result) {
561 throw new RestException(404, 'Shipment not found');
562 }
563
564 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
565 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
566 }
567
568 $result = $this->shipment->valid(DolibarrApiAccess::$user, $notrigger);
569 if ($result == 0) {
570 throw new RestException(304, 'Error nothing done. May be object is already validated');
571 }
572 if ($result < 0) {
573 throw new RestException(500, 'Error when validating Shipment: '.$this->shipment->error);
574 }
575
576 // Reload shipment
577 $result = $this->shipment->fetch($id);
578
579 $this->shipment->fetchObjectLinked();
580 return $this->_cleanObjectDatas($this->shipment);
581 }
582
583
584 // /**
585 // * Classify the shipment as invoiced
586 // *
587 // * @param int $id Id of the shipment
588 // *
589 // * @url POST {id}/setinvoiced
590 // *
591 // * @return int
592 // *
593 // * @throws RestException 400
594 // * @throws RestException 401
595 // * @throws RestException 404
596 // * @throws RestException 405
597 // */
598 /*
599 public function setinvoiced($id)
600 {
601
602 if(! DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
603 throw new RestException(403);
604 }
605 if(empty($id)) {
606 throw new RestException(400, 'Shipment ID is mandatory');
607 }
608 $result = $this->shipment->fetch($id);
609 if( ! $result ) {
610 throw new RestException(404, 'Shipment not found');
611 }
612
613 $result = $this->shipment->classifyBilled(DolibarrApiAccess::$user);
614 if( $result < 0) {
615 throw new RestException(400, $this->shipment->error);
616 }
617 return $result;
618 }
619 */
620
621
622 // /**
623 // * Create a shipment using an existing order.
624 // *
625 // * @param int $orderid Id of the order
626 // *
627 // * @url POST /createfromorder/{orderid}
628 // *
629 // * @return int
630 // * @throws RestException 400
631 // * @throws RestException 401
632 // * @throws RestException 404
633 // * @throws RestException 405
634 // */
635 /*
636 public function createShipmentFromOrder($orderid)
637 {
638
639 require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
640
641 if(! DolibarrApiAccess::$user->hasRight('expedition', 'lire')) {
642 throw new RestException(403);
643 }
644 if(! DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
645 throw new RestException(403);
646 }
647 if(empty($proposalid)) {
648 throw new RestException(400, 'Order ID is mandatory');
649 }
650
651 $order = new Commande($this->db);
652 $result = $order->fetch($proposalid);
653 if( ! $result ) {
654 throw new RestException(404, 'Order not found');
655 }
656
657 $result = $this->shipment->createFromOrder($order, DolibarrApiAccess::$user);
658 if( $result < 0) {
659 throw new RestException(405, $this->shipment->error);
660 }
661 $this->shipment->fetchObjectLinked();
662 return $this->_cleanObjectDatas($this->shipment);
663 }
664 */
665
676 public function close($id, $notrigger = 0)
677 {
678 if (!DolibarrApiAccess::$user->hasRight('expedition', 'creer')) {
679 throw new RestException(403);
680 }
681
682 $result = $this->shipment->fetch($id);
683 if (!$result) {
684 throw new RestException(404, 'Shipment not found');
685 }
686
687 if (!DolibarrApi::_checkAccessToResource('expedition', $this->shipment->id)) {
688 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
689 }
690
691 $result = $this->shipment->setClosed();
692 if ($result == 0) {
693 throw new RestException(304, 'Error nothing done. May be object is already closed');
694 }
695 if ($result < 0) {
696 throw new RestException(500, 'Error when closing Order: '.$this->shipment->error);
697 }
698
699 // Reload shipment
700 $result = $this->shipment->fetch($id);
701
702 $this->shipment->fetchObjectLinked();
703
704 return $this->_cleanObjectDatas($this->shipment);
705 }
706
707 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
714 protected function _cleanObjectDatas($object)
715 {
716 // phpcs:enable
717 $object = parent::_cleanObjectDatas($object);
718
719 unset($object->canvas);
720
721 unset($object->thirdparty); // id already returned
722
723 unset($object->note);
724 unset($object->address);
725 unset($object->barcode_type);
726 unset($object->barcode_type_code);
727 unset($object->barcode_type_label);
728 unset($object->barcode_type_coder);
729
730 if (!empty($object->lines) && is_array($object->lines)) {
731 foreach ($object->lines as $line) {
732 if (is_array($line->detail_batch)) {
733 foreach ($line->detail_batch as $keytmp2 => $valtmp2) {
734 unset($line->detail_batch[$keytmp2]->db);
735 }
736 }
737 unset($line->canvas);
738
739 unset($line->tva_tx);
740 unset($line->vat_src_code);
741 unset($line->total_ht);
742 unset($line->total_ttc);
743 unset($line->total_tva);
744 unset($line->total_localtax1);
745 unset($line->total_localtax2);
746 unset($line->remise_percent);
747 }
748 }
749
750 return $object;
751 }
752
760 private function _validate($data)
761 {
762 $shipment = array();
763 foreach (Shipments::$FIELDS as $field) {
764 if (!isset($data[$field])) {
765 throw new RestException(400, "$field field missing");
766 }
767 $shipment[$field] = $data[$field];
768 }
769 return $shipment;
770 }
771}
$id
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79