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