dolibarr 21.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 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 ? 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 // *
296 // * @url POST {id}/lines
297 // *
298 // * @return int
299 // */
300 /*
301 public function postLine($id, $request_data = null)
302 {
303 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
304 throw new RestException(403);
305 }
306
307 $result = $this->reception->fetch($id);
308 if (! $result) {
309 throw new RestException(404, 'Reception not found');
310 }
311
312 if (!DolibarrApi::_checkAccessToResource('reception',$this->reception->id)) {
313 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
314 }
315
316 $request_data = (object) $request_data;
317
318 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
319 $request_data->label = sanitizeVal($request_data->label);
320
321 $updateRes = $this->reception->addline(
322 $request_data->desc,
323 $request_data->subprice,
324 $request_data->qty,
325 $request_data->tva_tx,
326 $request_data->localtax1_tx,
327 $request_data->localtax2_tx,
328 $request_data->fk_product,
329 $request_data->remise_percent,
330 $request_data->info_bits,
331 $request_data->fk_remise_except,
332 'HT',
333 0,
334 $request_data->date_start,
335 $request_data->date_end,
336 $request_data->product_type,
337 $request_data->rang,
338 $request_data->special_code,
339 $fk_parent_line,
340 $request_data->fk_fournprice,
341 $request_data->pa_ht,
342 $request_data->label,
343 $request_data->array_options,
344 $request_data->fk_unit,
345 $request_data->origin,
346 $request_data->origin_id,
347 $request_data->multicurrency_subprice
348 );
349
350 if ($updateRes > 0) {
351 return $updateRes;
352
353 }
354 return false;
355 }*/
356
357 // /**
358 // * Update a line to given reception
359 // *
360 // * @param int $id Id of reception to update
361 // * @param int $lineid Id of line to update
362 // * @param array $request_data ShipmentLine data
363 // *
364 // * @url PUT {id}/lines/{lineid}
365 // *
366 // * @return object
367 // */
368 /*
369 public function putLine($id, $lineid, $request_data = null)
370 {
371 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
372 throw new RestException(403);
373 }
374
375 $result = $this->reception->fetch($id);
376 if (! $result) {
377 throw new RestException(404, 'Reception not found');
378 }
379
380 if (!DolibarrApi::_checkAccessToResource('reception',$this->reception->id)) {
381 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
382 }
383
384 $request_data = (object) $request_data;
385
386 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
387 $request_data->label = sanitizeVal($request_data->label);
388
389 $updateRes = $this->reception->updateline(
390 $lineid,
391 $request_data->desc,
392 $request_data->subprice,
393 $request_data->qty,
394 $request_data->remise_percent,
395 $request_data->tva_tx,
396 $request_data->localtax1_tx,
397 $request_data->localtax2_tx,
398 'HT',
399 $request_data->info_bits,
400 $request_data->date_start,
401 $request_data->date_end,
402 $request_data->product_type,
403 $request_data->fk_parent_line,
404 0,
405 $request_data->fk_fournprice,
406 $request_data->pa_ht,
407 $request_data->label,
408 $request_data->special_code,
409 $request_data->array_options,
410 $request_data->fk_unit,
411 $request_data->multicurrency_subprice
412 );
413
414 if ($updateRes > 0) {
415 $result = $this->get($id);
416 unset($result->line);
417 return $this->_cleanObjectDatas($result);
418 }
419 return false;
420 }*/
421
436 public function deleteLine($id, $lineid)
437 {
438 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
439 throw new RestException(403);
440 }
441
442 $result = $this->reception->fetch($id);
443 if (!$result) {
444 throw new RestException(404, 'Reception not found');
445 }
446
447 if (!DolibarrApi::_checkAccessToResource('reception', $this->reception->id)) {
448 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
449 }
450
451 // TODO Check the lineid $lineid is a line of object
452
453 $updateRes = $this->reception->deleteLine(DolibarrApiAccess::$user, $lineid);
454 if ($updateRes < 0) {
455 throw new RestException(405, $this->reception->error);
456 }
457
458 return array(
459 'success' => array(
460 'code' => 200,
461 'message' => 'Line deleted'
462 )
463 );
464 }
465
475 public function put($id, $request_data = null)
476 {
477 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
478 throw new RestException(403);
479 }
480
481 $result = $this->reception->fetch($id);
482 if (!$result) {
483 throw new RestException(404, 'Reception not found');
484 }
485
486 if (!DolibarrApi::_checkAccessToResource('reception', $this->reception->id)) {
487 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
488 }
489 foreach ($request_data as $field => $value) {
490 if ($field == 'id') {
491 continue;
492 }
493 if ($field === 'caller') {
494 // 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
495 $this->reception->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
496 continue;
497 }
498
499 if ($field == 'array_options' && is_array($value)) {
500 foreach ($value as $index => $val) {
501 $this->reception->array_options[$index] = $this->_checkValForAPI($field, $val, $this->reception);
502 }
503 continue;
504 }
505
506 $this->reception->$field = $this->_checkValForAPI($field, $value, $this->reception);
507 }
508
509 if ($this->reception->update(DolibarrApiAccess::$user) > 0) {
510 return $this->get($id);
511 } else {
512 throw new RestException(500, $this->reception->error);
513 }
514 }
515
524 public function delete($id)
525 {
526 if (!DolibarrApiAccess::$user->hasRight('reception', 'supprimer')) {
527 throw new RestException(403);
528 }
529 $result = $this->reception->fetch($id);
530 if (!$result) {
531 throw new RestException(404, 'Reception not found');
532 }
533
534 if (!DolibarrApi::_checkAccessToResource('reception', $this->reception->id)) {
535 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
536 }
537
538 if (!$this->reception->delete(DolibarrApiAccess::$user)) {
539 throw new RestException(500, 'Error when deleting reception : '.$this->reception->error);
540 }
541
542 return array(
543 'success' => array(
544 'code' => 200,
545 'message' => 'Reception deleted'
546 )
547 );
548 }
549
569 public function validate($id, $notrigger = 0)
570 {
571 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
572 throw new RestException(403);
573 }
574 $result = $this->reception->fetch($id);
575 if (!$result) {
576 throw new RestException(404, 'Reception not found');
577 }
578
579 if (!DolibarrApi::_checkAccessToResource('reception', $this->reception->id)) {
580 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
581 }
582
583 $result = $this->reception->valid(DolibarrApiAccess::$user, $notrigger);
584 if ($result == 0) {
585 throw new RestException(304, 'Error nothing done. May be object is already validated');
586 }
587 if ($result < 0) {
588 throw new RestException(500, 'Error when validating Reception: '.$this->reception->error);
589 }
590
591 // Reload reception
592 $result = $this->reception->fetch($id);
593
594 $this->reception->fetchObjectLinked();
595 return $this->_cleanObjectDatas($this->reception);
596 }
597
598
599 // /**
600 // * Classify the reception as invoiced
601 // *
602 // * @param int $id Id of the reception
603 // *
604 // * @url POST {id}/setinvoiced
605 // *
606 // * @return int
607 // *
608 // * @throws RestException 400
609 // * @throws RestException 401
610 // * @throws RestException 404
611 // * @throws RestException 405
612 // */
613 /*
614 public function setinvoiced($id)
615 {
616
617 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
618 throw new RestException(403);
619 }
620 if (empty($id)) {
621 throw new RestException(400, 'Reception ID is mandatory');
622 }
623 $result = $this->reception->fetch($id);
624 if (!$result) {
625 throw new RestException(404, 'Reception not found');
626 }
627
628 $result = $this->reception->classifyBilled(DolibarrApiAccess::$user);
629 if ($result < 0) {
630 throw new RestException(400, $this->reception->error);
631 }
632 return $result;
633 }
634 */
635
636
637 // /**
638 // * Create a reception using an existing order.
639 // *
640 // * @param int $orderid Id of the order
641 // *
642 // * @url POST /createfromorder/{orderid}
643 // *
644 // * @return int
645 // * @throws RestException 400
646 // * @throws RestException 401
647 // * @throws RestException 404
648 // * @throws RestException 405
649 // */
650 /*
651 public function createShipmentFromOrder($orderid)
652 {
653
654 require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
655
656 if (!DolibarrApiAccess::$user->hasRight('reception', 'lire')) {
657 throw new RestException(403);
658 }
659 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
660 throw new RestException(403);
661 }
662 if (empty($proposalid)) {
663 throw new RestException(400, 'Order ID is mandatory');
664 }
665
666 $order = new Commande($this->db);
667 $result = $order->fetch($proposalid);
668 if (!$result) {
669 throw new RestException(404, 'Order not found');
670 }
671
672 $result = $this->reception->createFromOrder($order, DolibarrApiAccess::$user);
673 if( $result < 0) {
674 throw new RestException(405, $this->reception->error);
675 }
676 $this->reception->fetchObjectLinked();
677 return $this->_cleanObjectDatas($this->reception);
678 }
679 */
680
691 public function close($id, $notrigger = 0)
692 {
693 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
694 throw new RestException(403);
695 }
696
697 $result = $this->reception->fetch($id);
698 if (!$result) {
699 throw new RestException(404, 'Reception not found');
700 }
701
702 if (!DolibarrApi::_checkAccessToResource('reception', $this->reception->id)) {
703 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
704 }
705
706 $result = $this->reception->setClosed();
707 if ($result == 0) {
708 throw new RestException(304, 'Error nothing done. May be object is already closed');
709 }
710 if ($result < 0) {
711 throw new RestException(500, 'Error when closing Reception: '.$this->reception->error);
712 }
713
714 // Reload reception
715 $result = $this->reception->fetch($id);
716
717 $this->reception->fetchObjectLinked();
718
719 return $this->_cleanObjectDatas($this->reception);
720 }
721
722 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
729 protected function _cleanObjectDatas($object)
730 {
731 // phpcs:enable
732 $object = parent::_cleanObjectDatas($object);
733
734 unset($object->thirdparty); // id already returned
735
736 unset($object->note);
737 unset($object->address);
738 unset($object->barcode_type);
739 unset($object->barcode_type_code);
740 unset($object->barcode_type_label);
741 unset($object->barcode_type_coder);
742
743 if (!empty($object->lines) && is_array($object->lines)) {
744 foreach ($object->lines as $line) {
745 unset($line->canvas);
746
747 unset($line->tva_tx);
748 unset($line->vat_src_code);
749 unset($line->total_ht);
750 unset($line->total_ttc);
751 unset($line->total_tva);
752 unset($line->total_localtax1);
753 unset($line->total_localtax2);
754 unset($line->remise_percent);
755 }
756 }
757
758 return $object;
759 }
760
768 private function _validate($data)
769 {
770 $reception = array();
771 foreach (Receptions::$FIELDS as $field) {
772 if (!isset($data[$field])) {
773 throw new RestException(400, "$field field missing");
774 }
775 $reception[$field] = $data[$field];
776 }
777 return $reception;
778 }
779}
$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:31
_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:83
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