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