dolibarr 21.0.0-alpha
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 *
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
19use Luracast\Restler\RestException;
20
21require_once DOL_DOCUMENT_ROOT.'/reception/class/reception.class.php';
22require_once DOL_DOCUMENT_ROOT.'/reception/class/receptionlinebatch.class.php';
23
31{
35 public static $FIELDS = array(
36 'socid',
37 'origin_id',
38 'origin_type',
39 );
40
44 public $reception;
45
49 public function __construct()
50 {
51 global $db, $conf;
52 $this->db = $db;
53 $this->reception = new Reception($this->db);
54 }
55
65 public function get($id)
66 {
67 if (!DolibarrApiAccess::$user->hasRight('reception', 'lire')) {
68 throw new RestException(403);
69 }
70
71 $result = $this->reception->fetch($id);
72 if (!$result) {
73 throw new RestException(404, 'Reception not found');
74 }
75
76 if (!DolibarrApi::_checkAccessToResource('reception', $this->reception->id)) {
77 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
78 }
79
80 $this->reception->fetchObjectLinked();
81 return $this->_cleanObjectDatas($this->reception);
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('reception', '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."reception AS t";
122 $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
123 $sql .= ' WHERE t.entity IN ('.getEntity('reception').')';
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 receptions 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 $reception_static = new Reception($this->db);
167 if ($reception_static->fetch($obj->rowid)) {
168 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($reception_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('reception', '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->reception->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
214 continue;
215 }
216
217 $this->reception->$field = $this->_checkValForAPI($field, $value, $this->reception);
218 }
219 if (isset($request_data["lines"])) {
220 $lines = array();
221 foreach ($request_data["lines"] as $line) {
222 $receptionline = new ReceptionLineBatch($this->db);
223
224 $receptionline->fk_product = $line['fk_product'];
225 $receptionline->fk_entrepot = $line['fk_entrepot'];
226 $receptionline->fk_element = $line['fk_element'] ?? $line['origin_id']; // example: purchase order id. this->origin is 'supplier_order'
227 $receptionline->origin_line_id = $line['fk_elementdet'] ?? $line['origin_line_id']; // example: purchase order id
228 $receptionline->fk_elementdet = $line['fk_elementdet'] ?? $line['origin_line_id']; // example: purchase order line id
229 $receptionline->origin_type = $line['element_type'] ?? $line['origin_type']; // example 'supplier_order'
230 $receptionline->element_type = $line['element_type'] ?? $line['origin_type']; // example 'supplier_order'
231 $receptionline->qty = $line['qty'];
232 //$receptionline->rang = $line['rang'];
233 $receptionline->array_options = $line['array_options'];
234 $receptionline->batch = $line['batch'];
235 $receptionline->eatby = $line['eatby'];
236 $receptionline->sellby = $line['sellby'];
237 $receptionline->cost_price = $line['cost_price'];
238 $receptionline->status = $line['status'];
239
240 $lines[] = $receptionline;
241 }
242 $this->reception->lines = $lines;
243 }
244
245 if ($this->reception->create(DolibarrApiAccess::$user) < 0) {
246 throw new RestException(500, "Error creating reception", array_merge(array($this->reception->error), $this->reception->errors));
247 }
248
249 return $this->reception->id;
250 }
251
252 // /**
253 // * Get lines of an reception
254 // *
255 // * @param int $id Id of reception
256 // *
257 // * @url GET {id}/lines
258 // *
259 // * @return int
260 // */
261 /*
262 public function getLines($id)
263 {
264 if (!DolibarrApiAccess::$user->hasRight('reception', 'lire')) {
265 throw new RestException(403);
266 }
267
268 $result = $this->reception->fetch($id);
269 if (! $result) {
270 throw new RestException(404, 'Reception not found');
271 }
272
273 if (!DolibarrApi::_checkAccessToResource('reception',$this->reception->id)) {
274 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
275 }
276 $this->reception->getLinesArray();
277 $result = array();
278 foreach ($this->reception->lines as $line) {
279 array_push($result,$this->_cleanObjectDatas($line));
280 }
281 return $result;
282 }
283 */
284
285 // /**
286 // * Add a line to given reception
287 // *
288 // * @param int $id Id of reception to update
289 // * @param array $request_data ShipmentLine data
290 // *
291 // * @url POST {id}/lines
292 // *
293 // * @return int
294 // */
295 /*
296 public function postLine($id, $request_data = null)
297 {
298 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
299 throw new RestException(403);
300 }
301
302 $result = $this->reception->fetch($id);
303 if (! $result) {
304 throw new RestException(404, 'Reception not found');
305 }
306
307 if (!DolibarrApi::_checkAccessToResource('reception',$this->reception->id)) {
308 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
309 }
310
311 $request_data = (object) $request_data;
312
313 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
314 $request_data->label = sanitizeVal($request_data->label);
315
316 $updateRes = $this->reception->addline(
317 $request_data->desc,
318 $request_data->subprice,
319 $request_data->qty,
320 $request_data->tva_tx,
321 $request_data->localtax1_tx,
322 $request_data->localtax2_tx,
323 $request_data->fk_product,
324 $request_data->remise_percent,
325 $request_data->info_bits,
326 $request_data->fk_remise_except,
327 'HT',
328 0,
329 $request_data->date_start,
330 $request_data->date_end,
331 $request_data->product_type,
332 $request_data->rang,
333 $request_data->special_code,
334 $fk_parent_line,
335 $request_data->fk_fournprice,
336 $request_data->pa_ht,
337 $request_data->label,
338 $request_data->array_options,
339 $request_data->fk_unit,
340 $request_data->origin,
341 $request_data->origin_id,
342 $request_data->multicurrency_subprice
343 );
344
345 if ($updateRes > 0) {
346 return $updateRes;
347
348 }
349 return false;
350 }*/
351
352 // /**
353 // * Update a line to given reception
354 // *
355 // * @param int $id Id of reception to update
356 // * @param int $lineid Id of line to update
357 // * @param array $request_data ShipmentLine data
358 // *
359 // * @url PUT {id}/lines/{lineid}
360 // *
361 // * @return object
362 // */
363 /*
364 public function putLine($id, $lineid, $request_data = null)
365 {
366 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
367 throw new RestException(403);
368 }
369
370 $result = $this->reception->fetch($id);
371 if (! $result) {
372 throw new RestException(404, 'Reception not found');
373 }
374
375 if (!DolibarrApi::_checkAccessToResource('reception',$this->reception->id)) {
376 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
377 }
378
379 $request_data = (object) $request_data;
380
381 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
382 $request_data->label = sanitizeVal($request_data->label);
383
384 $updateRes = $this->reception->updateline(
385 $lineid,
386 $request_data->desc,
387 $request_data->subprice,
388 $request_data->qty,
389 $request_data->remise_percent,
390 $request_data->tva_tx,
391 $request_data->localtax1_tx,
392 $request_data->localtax2_tx,
393 'HT',
394 $request_data->info_bits,
395 $request_data->date_start,
396 $request_data->date_end,
397 $request_data->product_type,
398 $request_data->fk_parent_line,
399 0,
400 $request_data->fk_fournprice,
401 $request_data->pa_ht,
402 $request_data->label,
403 $request_data->special_code,
404 $request_data->array_options,
405 $request_data->fk_unit,
406 $request_data->multicurrency_subprice
407 );
408
409 if ($updateRes > 0) {
410 $result = $this->get($id);
411 unset($result->line);
412 return $this->_cleanObjectDatas($result);
413 }
414 return false;
415 }*/
416
429 public function deleteLine($id, $lineid)
430 {
431 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
432 throw new RestException(403);
433 }
434
435 $result = $this->reception->fetch($id);
436 if (!$result) {
437 throw new RestException(404, 'Reception not found');
438 }
439
440 if (!DolibarrApi::_checkAccessToResource('reception', $this->reception->id)) {
441 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
442 }
443
444 // TODO Check the lineid $lineid is a line of object
445
446 $updateRes = $this->reception->deleteLine(DolibarrApiAccess::$user, $lineid);
447 if ($updateRes < 0) {
448 throw new RestException(405, $this->reception->error);
449 }
450
451 return array(
452 'success' => array(
453 'code' => 200,
454 'message' => 'Line deleted'
455 )
456 );
457 }
458
466 public function put($id, $request_data = null)
467 {
468 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
469 throw new RestException(403);
470 }
471
472 $result = $this->reception->fetch($id);
473 if (!$result) {
474 throw new RestException(404, 'Reception not found');
475 }
476
477 if (!DolibarrApi::_checkAccessToResource('reception', $this->reception->id)) {
478 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
479 }
480 foreach ($request_data as $field => $value) {
481 if ($field == 'id') {
482 continue;
483 }
484 if ($field === 'caller') {
485 // 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
486 $this->reception->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
487 continue;
488 }
489
490 $this->reception->$field = $this->_checkValForAPI($field, $value, $this->reception);
491 }
492
493 if ($this->reception->update(DolibarrApiAccess::$user) > 0) {
494 return $this->get($id);
495 } else {
496 throw new RestException(500, $this->reception->error);
497 }
498 }
499
506 public function delete($id)
507 {
508 if (!DolibarrApiAccess::$user->hasRight('reception', 'supprimer')) {
509 throw new RestException(403);
510 }
511 $result = $this->reception->fetch($id);
512 if (!$result) {
513 throw new RestException(404, 'Reception not found');
514 }
515
516 if (!DolibarrApi::_checkAccessToResource('reception', $this->reception->id)) {
517 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
518 }
519
520 if (!$this->reception->delete(DolibarrApiAccess::$user)) {
521 throw new RestException(500, 'Error when deleting reception : '.$this->reception->error);
522 }
523
524 return array(
525 'success' => array(
526 'code' => 200,
527 'message' => 'Reception deleted'
528 )
529 );
530 }
531
551 public function validate($id, $notrigger = 0)
552 {
553 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
554 throw new RestException(403);
555 }
556 $result = $this->reception->fetch($id);
557 if (!$result) {
558 throw new RestException(404, 'Reception not found');
559 }
560
561 if (!DolibarrApi::_checkAccessToResource('reception', $this->reception->id)) {
562 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
563 }
564
565 $result = $this->reception->valid(DolibarrApiAccess::$user, $notrigger);
566 if ($result == 0) {
567 throw new RestException(304, 'Error nothing done. May be object is already validated');
568 }
569 if ($result < 0) {
570 throw new RestException(500, 'Error when validating Reception: '.$this->reception->error);
571 }
572
573 // Reload reception
574 $result = $this->reception->fetch($id);
575
576 $this->reception->fetchObjectLinked();
577 return $this->_cleanObjectDatas($this->reception);
578 }
579
580
581 // /**
582 // * Classify the reception as invoiced
583 // *
584 // * @param int $id Id of the reception
585 // *
586 // * @url POST {id}/setinvoiced
587 // *
588 // * @return int
589 // *
590 // * @throws RestException 400
591 // * @throws RestException 401
592 // * @throws RestException 404
593 // * @throws RestException 405
594 // */
595 /*
596 public function setinvoiced($id)
597 {
598
599 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
600 throw new RestException(403);
601 }
602 if (empty($id)) {
603 throw new RestException(400, 'Reception ID is mandatory');
604 }
605 $result = $this->reception->fetch($id);
606 if (!$result) {
607 throw new RestException(404, 'Reception not found');
608 }
609
610 $result = $this->reception->classifyBilled(DolibarrApiAccess::$user);
611 if ($result < 0) {
612 throw new RestException(400, $this->reception->error);
613 }
614 return $result;
615 }
616 */
617
618
619 // /**
620 // * Create a reception using an existing order.
621 // *
622 // * @param int $orderid Id of the order
623 // *
624 // * @url POST /createfromorder/{orderid}
625 // *
626 // * @return int
627 // * @throws RestException 400
628 // * @throws RestException 401
629 // * @throws RestException 404
630 // * @throws RestException 405
631 // */
632 /*
633 public function createShipmentFromOrder($orderid)
634 {
635
636 require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
637
638 if (!DolibarrApiAccess::$user->hasRight('reception', 'lire')) {
639 throw new RestException(403);
640 }
641 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
642 throw new RestException(403);
643 }
644 if (empty($proposalid)) {
645 throw new RestException(400, 'Order ID is mandatory');
646 }
647
648 $order = new Commande($this->db);
649 $result = $order->fetch($proposalid);
650 if (!$result) {
651 throw new RestException(404, 'Order not found');
652 }
653
654 $result = $this->reception->createFromOrder($order, DolibarrApiAccess::$user);
655 if( $result < 0) {
656 throw new RestException(405, $this->reception->error);
657 }
658 $this->reception->fetchObjectLinked();
659 return $this->_cleanObjectDatas($this->reception);
660 }
661 */
662
673 public function close($id, $notrigger = 0)
674 {
675 if (!DolibarrApiAccess::$user->hasRight('reception', 'creer')) {
676 throw new RestException(403);
677 }
678
679 $result = $this->reception->fetch($id);
680 if (!$result) {
681 throw new RestException(404, 'Reception not found');
682 }
683
684 if (!DolibarrApi::_checkAccessToResource('reception', $this->reception->id)) {
685 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
686 }
687
688 $result = $this->reception->setClosed();
689 if ($result == 0) {
690 throw new RestException(304, 'Error nothing done. May be object is already closed');
691 }
692 if ($result < 0) {
693 throw new RestException(500, 'Error when closing Reception: '.$this->reception->error);
694 }
695
696 // Reload reception
697 $result = $this->reception->fetch($id);
698
699 $this->reception->fetchObjectLinked();
700
701 return $this->_cleanObjectDatas($this->reception);
702 }
703
704 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
711 protected function _cleanObjectDatas($object)
712 {
713 // phpcs:enable
714 $object = parent::_cleanObjectDatas($object);
715
716 unset($object->thirdparty); // id already returned
717
718 unset($object->note);
719 unset($object->address);
720 unset($object->barcode_type);
721 unset($object->barcode_type_code);
722 unset($object->barcode_type_label);
723 unset($object->barcode_type_coder);
724
725 if (!empty($object->lines) && is_array($object->lines)) {
726 foreach ($object->lines as $line) {
727 unset($line->canvas);
728
729 unset($line->tva_tx);
730 unset($line->vat_src_code);
731 unset($line->total_ht);
732 unset($line->total_ttc);
733 unset($line->total_tva);
734 unset($line->total_localtax1);
735 unset($line->total_localtax2);
736 unset($line->remise_percent);
737 }
738 }
739
740 return $object;
741 }
742
750 private function _validate($data)
751 {
752 $reception = array();
753 foreach (Receptions::$FIELDS as $field) {
754 if (!isset($data[$field])) {
755 throw new RestException(400, "$field field missing");
756 }
757 $reception[$field] = $data[$field];
758 }
759 return $reception;
760 }
761}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
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.