dolibarr 21.0.0-beta
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 $this->reception->$field = $this->_checkValForAPI($field, $value, $this->reception);
500 }
501
502 if ($this->reception->update(DolibarrApiAccess::$user) > 0) {
503 return $this->get($id);
504 } else {
505 throw new RestException(500, $this->reception->error);
506 }
507 }
508
517 public function delete($id)
518 {
519 if (!DolibarrApiAccess::$user->hasRight('reception', 'supprimer')) {
520 throw new RestException(403);
521 }
522 $result = $this->reception->fetch($id);
523 if (!$result) {
524 throw new RestException(404, 'Reception not found');
525 }
526
527 if (!DolibarrApi::_checkAccessToResource('reception', $this->reception->id)) {
528 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
529 }
530
531 if (!$this->reception->delete(DolibarrApiAccess::$user)) {
532 throw new RestException(500, 'Error when deleting reception : '.$this->reception->error);
533 }
534
535 return array(
536 'success' => array(
537 'code' => 200,
538 'message' => 'Reception deleted'
539 )
540 );
541 }
542
562 public function validate($id, $notrigger = 0)
563 {
564 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
565 throw new RestException(403);
566 }
567 $result = $this->reception->fetch($id);
568 if (!$result) {
569 throw new RestException(404, 'Reception not found');
570 }
571
572 if (!DolibarrApi::_checkAccessToResource('reception', $this->reception->id)) {
573 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
574 }
575
576 $result = $this->reception->valid(DolibarrApiAccess::$user, $notrigger);
577 if ($result == 0) {
578 throw new RestException(304, 'Error nothing done. May be object is already validated');
579 }
580 if ($result < 0) {
581 throw new RestException(500, 'Error when validating Reception: '.$this->reception->error);
582 }
583
584 // Reload reception
585 $result = $this->reception->fetch($id);
586
587 $this->reception->fetchObjectLinked();
588 return $this->_cleanObjectDatas($this->reception);
589 }
590
591
592 // /**
593 // * Classify the reception as invoiced
594 // *
595 // * @param int $id Id of the reception
596 // *
597 // * @url POST {id}/setinvoiced
598 // *
599 // * @return int
600 // *
601 // * @throws RestException 400
602 // * @throws RestException 401
603 // * @throws RestException 404
604 // * @throws RestException 405
605 // */
606 /*
607 public function setinvoiced($id)
608 {
609
610 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
611 throw new RestException(403);
612 }
613 if (empty($id)) {
614 throw new RestException(400, 'Reception ID is mandatory');
615 }
616 $result = $this->reception->fetch($id);
617 if (!$result) {
618 throw new RestException(404, 'Reception not found');
619 }
620
621 $result = $this->reception->classifyBilled(DolibarrApiAccess::$user);
622 if ($result < 0) {
623 throw new RestException(400, $this->reception->error);
624 }
625 return $result;
626 }
627 */
628
629
630 // /**
631 // * Create a reception using an existing order.
632 // *
633 // * @param int $orderid Id of the order
634 // *
635 // * @url POST /createfromorder/{orderid}
636 // *
637 // * @return int
638 // * @throws RestException 400
639 // * @throws RestException 401
640 // * @throws RestException 404
641 // * @throws RestException 405
642 // */
643 /*
644 public function createShipmentFromOrder($orderid)
645 {
646
647 require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
648
649 if (!DolibarrApiAccess::$user->hasRight('reception', 'lire')) {
650 throw new RestException(403);
651 }
652 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
653 throw new RestException(403);
654 }
655 if (empty($proposalid)) {
656 throw new RestException(400, 'Order ID is mandatory');
657 }
658
659 $order = new Commande($this->db);
660 $result = $order->fetch($proposalid);
661 if (!$result) {
662 throw new RestException(404, 'Order not found');
663 }
664
665 $result = $this->reception->createFromOrder($order, DolibarrApiAccess::$user);
666 if( $result < 0) {
667 throw new RestException(405, $this->reception->error);
668 }
669 $this->reception->fetchObjectLinked();
670 return $this->_cleanObjectDatas($this->reception);
671 }
672 */
673
684 public function close($id, $notrigger = 0)
685 {
686 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
687 throw new RestException(403);
688 }
689
690 $result = $this->reception->fetch($id);
691 if (!$result) {
692 throw new RestException(404, 'Reception not found');
693 }
694
695 if (!DolibarrApi::_checkAccessToResource('reception', $this->reception->id)) {
696 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
697 }
698
699 $result = $this->reception->setClosed();
700 if ($result == 0) {
701 throw new RestException(304, 'Error nothing done. May be object is already closed');
702 }
703 if ($result < 0) {
704 throw new RestException(500, 'Error when closing Reception: '.$this->reception->error);
705 }
706
707 // Reload reception
708 $result = $this->reception->fetch($id);
709
710 $this->reception->fetchObjectLinked();
711
712 return $this->_cleanObjectDatas($this->reception);
713 }
714
715 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
722 protected function _cleanObjectDatas($object)
723 {
724 // phpcs:enable
725 $object = parent::_cleanObjectDatas($object);
726
727 unset($object->thirdparty); // id already returned
728
729 unset($object->note);
730 unset($object->address);
731 unset($object->barcode_type);
732 unset($object->barcode_type_code);
733 unset($object->barcode_type_label);
734 unset($object->barcode_type_coder);
735
736 if (!empty($object->lines) && is_array($object->lines)) {
737 foreach ($object->lines as $line) {
738 unset($line->canvas);
739
740 unset($line->tva_tx);
741 unset($line->vat_src_code);
742 unset($line->total_ht);
743 unset($line->total_ttc);
744 unset($line->total_tva);
745 unset($line->total_localtax1);
746 unset($line->total_localtax2);
747 unset($line->remise_percent);
748 }
749 }
750
751 return $object;
752 }
753
761 private function _validate($data)
762 {
763 $reception = array();
764 foreach (Receptions::$FIELDS as $field) {
765 if (!isset($data[$field])) {
766 throw new RestException(400, "$field field missing");
767 }
768 $reception[$field] = $data[$field];
769 }
770 return $reception;
771 }
772}
$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 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