dolibarr 25.0.0-alpha
api_boms.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2019 Maxime Kohlhaas <maxime@atm-consulting.fr>
4 * Copyright (C) 2020-2025 Frédéric France <frederic.france@free.fr>
5 * Copyright (C) 2022 Christian Humpel <christian.humpel@live.com>
6 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22use Luracast\Restler\RestException;
23
24require_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
25
26
39class Boms extends DolibarrApi
40{
44 public $bom;
45
49 public function __construct()
50 {
51 global $db;
52
53 $this->db = $db;
54 $this->bom = new BOM($this->db);
55 }
56
72 public function get($id)
73 {
74 if (!DolibarrApiAccess::$user->hasRight('bom', 'read')) {
75 throw new RestException(403);
76 }
77
78 $result = $this->bom->fetch($id);
79 if (!$result) {
80 throw new RestException(404, 'BOM not found');
81 }
82
83 if (!DolibarrApi::_checkAccessToResource('bom', $this->bom->id, 'bom_bom')) {
84 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
85 }
86
87 return $this->_cleanObjectDatas($this->bom);
88 }
89
90
110 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
111 {
112 if (!DolibarrApiAccess::$user->hasRight('bom', 'read')) {
113 throw new RestException(403);
114 }
115
116 $obj_ret = array();
117 $tmpobject = new BOM($this->db);
118
119 $socid = DolibarrApiAccess::$user->socid ?: '';
120
121 $restrictonsocid = 0; // Set to 1 if there is a field socid in table of object
122
123 // If the internal user must only see his customers, force searching by him
124 $search_sale = 0;
125 if ($restrictonsocid && !DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socid) {
126 $search_sale = DolibarrApiAccess::$user->id;
127 }
128
129 $sql = "SELECT t.rowid";
130 $sql .= " FROM ".MAIN_DB_PREFIX.$tmpobject->table_element." AS t";
131 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmpobject->table_element."_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
132 $sql .= " WHERE 1 = 1";
133 if ($tmpobject->ismultientitymanaged) {
134 $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')';
135 }
136 if ($restrictonsocid && $socid) {
137 $sql .= " AND t.fk_soc = ".((int) $socid);
138 }
139 // Search on sale representative
140 if ($search_sale && $search_sale != '-1') {
141 if ($search_sale == -2) {
142 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
143 } elseif ($search_sale > 0) {
144 $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).")";
145 }
146 }
147 if ($sqlfilters) {
148 $errormessage = '';
149 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
150 if ($errormessage) {
151 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
152 }
153 }
154
155 $sql .= $this->db->order($sortfield, $sortorder);
156 if ($limit) {
157 if ($page < 0) {
158 $page = 0;
159 }
160 $offset = $limit * $page;
161
162 $sql .= $this->db->plimit($limit + 1, $offset);
163 }
164
165 $result = $this->db->query($sql);
166 if ($result) {
167 $i = 0;
168 $num = $this->db->num_rows($result);
169 $min = min($num, ($limit <= 0 ? $num : $limit));
170 while ($i < $min) {
171 $obj = $this->db->fetch_object($result);
172 $bom_static = new BOM($this->db);
173 if ($bom_static->fetch($obj->rowid)) {
174 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($bom_static), $properties);
175 }
176 $i++;
177 }
178 } else {
179 throw new RestException(503, 'Error when retrieve bom list');
180 }
181
182 return $obj_ret;
183 }
184
196 public function post($request_data = null)
197 {
198 if (!DolibarrApiAccess::$user->hasRight('bom', 'write')) {
199 throw new RestException(403);
200 }
201 // Check mandatory fields
202 $result = $this->_validate($request_data);
203
204 foreach ($request_data as $field => $value) {
205 if ($field === 'caller') {
206 // 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
207 $this->bom->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
208 continue;
209 }
210
211 $this->bom->$field = $this->_checkValForAPI($field, $value, $this->bom);
212 }
213
214 $this->checkRefNumbering();
215
216 if (!$this->bom->create(DolibarrApiAccess::$user)) {
217 throw new RestException(500, "Error creating BOM", array_merge(array($this->bom->error), $this->bom->errors));
218 }
219 return $this->bom->id;
220 }
221
237 public function put($id, $request_data = null)
238 {
239 if (!DolibarrApiAccess::$user->hasRight('bom', 'write')) {
240 throw new RestException(403);
241 }
242
243 $result = $this->bom->fetch($id);
244 if (!$result) {
245 throw new RestException(404, 'BOM not found');
246 }
247
248 if (!DolibarrApi::_checkAccessToResource('bom', $this->bom->id, 'bom_bom')) {
249 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
250 }
251
252 foreach ($request_data as $field => $value) {
253 if ($field == 'id') {
254 continue;
255 }
256 if ($field === 'caller') {
257 // 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
258 $this->bom->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
259 continue;
260 }
261
262 if ($field == 'array_options' && is_array($value)) {
263 foreach ($value as $index => $val) {
264 $this->bom->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->bom);
265 }
266 continue;
267 }
268 $this->bom->$field = $this->_checkValForAPI($field, $value, $this->bom);
269 }
270
271 $this->checkRefNumbering();
272
273 if ($this->bom->update(DolibarrApiAccess::$user) > 0) {
274 return $this->get($id);
275 } else {
276 throw new RestException(500, $this->bom->error);
277 }
278 }
279
294 public function validate($id, $notrigger = 0)
295 {
296 if (!DolibarrApiAccess::$user->hasRight('bom', 'write')) {
297 throw new RestException(403);
298 }
299 $result = $this->bom->fetch($id);
300 if (!$result) {
301 throw new RestException(404, 'Bom not found');
302 }
303
304 $result = $this->bom->validate(DolibarrApiAccess::$user, $notrigger);
305 if ($result == 0) {
306 throw new RestException(304, 'Error nothing done. May be object is already validated');
307 }
308 if ($result < 0) {
309 throw new RestException(500, 'Error when validating BOM: '.$this->bom->error);
310 }
311 $result = $this->bom->fetch($id);
312
313 return $this->_cleanObjectDatas($this->bom);
314 }
315
328 public function delete($id)
329 {
330 if (!DolibarrApiAccess::$user->hasRight('bom', 'delete')) {
331 throw new RestException(403);
332 }
333 $result = $this->bom->fetch($id);
334 if (!$result) {
335 throw new RestException(404, 'BOM not found');
336 }
337
338 if (!DolibarrApi::_checkAccessToResource('bom', $this->bom->id, 'bom_bom')) {
339 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
340 }
341
342 if (!$this->bom->delete(DolibarrApiAccess::$user)) {
343 throw new RestException(500, 'Error when deleting BOM : '.$this->bom->error);
344 }
345
346 return array(
347 'success' => array(
348 'code' => 200,
349 'message' => 'BOM deleted'
350 )
351 );
352 }
353
368 public function getLines($id)
369 {
370 if (!DolibarrApiAccess::$user->hasRight('bom', 'read')) {
371 throw new RestException(403);
372 }
373
374 $result = $this->bom->fetch($id);
375 if (!$result) {
376 throw new RestException(404, 'BOM not found');
377 }
378
379 if (!DolibarrApi::_checkAccessToResource('bom_bom', $this->bom->id)) {
380 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
381 }
382 $this->bom->getLinesArray();
383 $result = array();
384 foreach ($this->bom->lines as $line) {
385 array_push($result, $this->_cleanObjectDatas($line));
386 }
387 return $result;
388 }
389
406 public function postLine($id, $request_data = null)
407 {
408 if (!DolibarrApiAccess::$user->hasRight('bom', 'write')) {
409 throw new RestException(403);
410 }
411
412 $result = $this->bom->fetch($id);
413 if (!$result) {
414 throw new RestException(404, 'BOM not found');
415 }
416
417 if (!DolibarrApi::_checkAccessToResource('bom_bom', $this->bom->id)) {
418 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
419 }
420
421 $request_data = (object) $request_data;
422
423 $updateRes = $this->bom->addLine(
424 $request_data->fk_product,
425 $request_data->qty,
426 $request_data->qty_frozen,
427 $request_data->disable_stock_change,
428 $request_data->efficiency,
429 $request_data->position,
430 $request_data->fk_bom_child,
431 $request_data->import_key,
432 $request_data->fk_unit,
433 $request_data->array_options,
434 $request_data->fk_default_workstation
435 );
436
437 if ($updateRes > 0) {
438 return $updateRes;
439 } else {
440 throw new RestException(500, $this->bom->error);
441 }
442 }
443
460 public function putLine($id, $lineid, $request_data = null)
461 {
462 if (!DolibarrApiAccess::$user->hasRight('bom', 'write')) {
463 throw new RestException(403);
464 }
465
466 $result = $this->bom->fetch($id);
467 if (!$result) {
468 throw new RestException(404, 'BOM not found');
469 }
470
471 if (!DolibarrApi::_checkAccessToResource('bom_bom', $this->bom->id)) {
472 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
473 }
474
475 $request_data = (object) $request_data;
476
477 $updateRes = $this->bom->updateLine(
478 $lineid,
479 $request_data->qty,
480 $request_data->qty_frozen,
481 $request_data->disable_stock_change,
482 $request_data->efficiency,
483 $request_data->position,
484 $request_data->import_key,
485 $request_data->fk_unit,
486 $request_data->array_options,
487 $request_data->fk_default_workstation
488 );
489
490 if ($updateRes > 0) {
491 $result = $this->get($id);
492 unset($result->line);
493 return $this->_cleanObjectDatas($result);
494 }
495 return false;
496 }
497
515 public function deleteLine($id, $lineid)
516 {
517 if (!DolibarrApiAccess::$user->hasRight('bom', 'write')) {
518 throw new RestException(403);
519 }
520
521 $result = $this->bom->fetch($id);
522 if (!$result) {
523 throw new RestException(404, 'BOM not found');
524 }
525
526 if (!DolibarrApi::_checkAccessToResource('bom_bom', $this->bom->id)) {
527 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
528 }
529
530 //Check the rowid is a line of current bom object
531 $lineIdIsFromObject = false;
532 foreach ($this->bom->lines as $bl) {
533 if ($bl->id == $lineid) {
534 $lineIdIsFromObject = true;
535 break;
536 }
537 }
538 if (!$lineIdIsFromObject) {
539 throw new RestException(500, 'Line to delete (rowid: '.$lineid.') is not a line of BOM (id: '.$this->bom->id.')');
540 }
541
542 $updateRes = $this->bom->deleteLine(DolibarrApiAccess::$user, $lineid);
543 if ($updateRes > 0) {
544 return array(
545 'success' => array(
546 'code' => 200,
547 'message' => 'line ' .$lineid. ' deleted'
548 )
549 );
550 } else {
551 throw new RestException(500, $this->bom->error);
552 }
553 }
554
555 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
565 protected function _cleanObjectDatas($object)
566 {
567 // phpcs:enable
568 $object = parent::_cleanObjectDatas($object);
569
570 unset($object->rowid);
571 unset($object->canvas);
572
573 unset($object->name);
574 unset($object->lastname);
575 unset($object->firstname);
576 unset($object->civility_id);
577 unset($object->statut);
578 unset($object->state);
579 unset($object->state_id);
580 unset($object->state_code);
581 unset($object->region);
582 unset($object->region_code);
583 unset($object->country);
584 unset($object->country_id);
585 unset($object->country_code);
586 unset($object->barcode_type);
587 unset($object->barcode_type_code);
588 unset($object->barcode_type_label);
589 unset($object->barcode_type_coder);
590 unset($object->total_ht);
591 unset($object->total_tva);
592 unset($object->total_localtax1);
593 unset($object->total_localtax2);
594 unset($object->total_ttc);
595 unset($object->fk_account);
596 unset($object->comments);
597 unset($object->note);
598 unset($object->mode_reglement_id);
599 unset($object->cond_reglement_id);
600 unset($object->cond_reglement);
601 unset($object->shipping_method_id);
602 unset($object->fk_incoterms);
603 unset($object->label_incoterms);
604 unset($object->location_incoterms);
605 unset($object->multicurrency_code);
606 unset($object->multicurrency_tx);
607 unset($object->multicurrency_total_ht);
608 unset($object->multicurrency_total_ttc);
609 unset($object->multicurrency_total_tva);
610 unset($object->multicurrency_total_localtax1);
611 unset($object->multicurrency_total_localtax2);
612
613
614 // If object has lines, remove $db property
615 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
616 $nboflines = count($object->lines);
617 for ($i = 0; $i < $nboflines; $i++) {
618 $this->_cleanObjectDatas($object->lines[$i]);
619
620 unset($object->lines[$i]->lines);
621 unset($object->lines[$i]->note);
622 }
623 }
624
625 return $object;
626 }
627
636 private function _validate($data)
637 {
638 if ($data === null) {
639 $data = array();
640 }
641 $myobject = array();
642 foreach ($this->bom->fields as $field => $propfield) {
643 if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || empty($propfield['notnull']) || $propfield['notnull'] != 1) {
644 continue; // Not a mandatory field
645 }
646 if (!isset($data[$field])) {
647 throw new RestException(400, "$field field missing");
648 }
649 $myobject[$field] = $data[$field];
650 }
651 return $myobject;
652 }
653
659 private function checkRefNumbering()
660 {
661 $ref = substr($this->bom->ref, 1, 4);
662 if ($this->bom->status > BOM::STATUS_DRAFT && $ref == 'PROV') {
663 throw new RestException(400, "Wrong naming scheme '(PROV%)' is only allowed on 'DRAFT' status. For automatic increment use 'auto' on the 'ref' field.");
664 }
665
666 if (strtolower($this->bom->ref) == 'auto') {
667 if (empty($this->bom->id) && $this->bom->status == BOM::STATUS_DRAFT) {
668 $this->bom->ref = ''; // 'ref' will auto incremented with '(PROV' + newID + ')'
669 } else {
670 $res = $this->bom->fetch_product();
671 if ($res > 0 && $this->bom->product instanceof Product) {
672 $numref = $this->bom->getNextNumRef($this->bom->product); // @phan-suppress-current-line PhanTypeMismatchArgumentNullable
673 $this->bom->ref = $numref;
674 } else {
675 throw new RestException(400, "Error when generating automatic increment on the 'ref' field.");
676 }
677 }
678 }
679 }
680}
$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 BOM.
Definition bom.class.php:42
validate($id, $notrigger=0)
Validate BOM.
checkRefNumbering()
Validate the ref field and get the next Number if it's necessary.
put($id, $request_data=null)
Update bom.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
putLine($id, $lineid, $request_data=null)
Update a line to given BOM.
post($request_data=null)
Create bom object.
getLines($id)
Get lines of an BOM.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $sqlfilters='', $properties='')
List boms.
__construct()
Constructor.
deleteLine($id, $lineid)
Delete a line to given BOM.
postLine($id, $request_data=null)
Add a line to given BOM.
_validate($data)
Validate fields before create or update object.
Class for API REST v1.
Definition api.class.php:35
_checkValExtrafieldsForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
_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.
Class to manage products or services.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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.