dolibarr 24.0.0-beta
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
292 public function delete($id)
293 {
294 if (!DolibarrApiAccess::$user->hasRight('bom', 'delete')) {
295 throw new RestException(403);
296 }
297 $result = $this->bom->fetch($id);
298 if (!$result) {
299 throw new RestException(404, 'BOM not found');
300 }
301
302 if (!DolibarrApi::_checkAccessToResource('bom', $this->bom->id, 'bom_bom')) {
303 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
304 }
305
306 if (!$this->bom->delete(DolibarrApiAccess::$user)) {
307 throw new RestException(500, 'Error when deleting BOM : '.$this->bom->error);
308 }
309
310 return array(
311 'success' => array(
312 'code' => 200,
313 'message' => 'BOM deleted'
314 )
315 );
316 }
317
332 public function getLines($id)
333 {
334 if (!DolibarrApiAccess::$user->hasRight('bom', 'read')) {
335 throw new RestException(403);
336 }
337
338 $result = $this->bom->fetch($id);
339 if (!$result) {
340 throw new RestException(404, 'BOM not found');
341 }
342
343 if (!DolibarrApi::_checkAccessToResource('bom_bom', $this->bom->id)) {
344 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
345 }
346 $this->bom->getLinesArray();
347 $result = array();
348 foreach ($this->bom->lines as $line) {
349 array_push($result, $this->_cleanObjectDatas($line));
350 }
351 return $result;
352 }
353
370 public function postLine($id, $request_data = null)
371 {
372 if (!DolibarrApiAccess::$user->hasRight('bom', 'write')) {
373 throw new RestException(403);
374 }
375
376 $result = $this->bom->fetch($id);
377 if (!$result) {
378 throw new RestException(404, 'BOM not found');
379 }
380
381 if (!DolibarrApi::_checkAccessToResource('bom_bom', $this->bom->id)) {
382 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
383 }
384
385 $request_data = (object) $request_data;
386
387 $updateRes = $this->bom->addLine(
388 $request_data->fk_product,
389 $request_data->qty,
390 $request_data->qty_frozen,
391 $request_data->disable_stock_change,
392 $request_data->efficiency,
393 $request_data->position,
394 $request_data->fk_bom_child,
395 $request_data->import_key,
396 $request_data->fk_unit,
397 $request_data->array_options,
398 $request_data->fk_default_workstation
399 );
400
401 if ($updateRes > 0) {
402 return $updateRes;
403 } else {
404 throw new RestException(500, $this->bom->error);
405 }
406 }
407
424 public function putLine($id, $lineid, $request_data = null)
425 {
426 if (!DolibarrApiAccess::$user->hasRight('bom', 'write')) {
427 throw new RestException(403);
428 }
429
430 $result = $this->bom->fetch($id);
431 if (!$result) {
432 throw new RestException(404, 'BOM not found');
433 }
434
435 if (!DolibarrApi::_checkAccessToResource('bom_bom', $this->bom->id)) {
436 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
437 }
438
439 $request_data = (object) $request_data;
440
441 $updateRes = $this->bom->updateLine(
442 $lineid,
443 $request_data->qty,
444 $request_data->qty_frozen,
445 $request_data->disable_stock_change,
446 $request_data->efficiency,
447 $request_data->position,
448 $request_data->import_key,
449 $request_data->fk_unit,
450 $request_data->array_options,
451 $request_data->fk_default_workstation
452 );
453
454 if ($updateRes > 0) {
455 $result = $this->get($id);
456 unset($result->line);
457 return $this->_cleanObjectDatas($result);
458 }
459 return false;
460 }
461
479 public function deleteLine($id, $lineid)
480 {
481 if (!DolibarrApiAccess::$user->hasRight('bom', 'write')) {
482 throw new RestException(403);
483 }
484
485 $result = $this->bom->fetch($id);
486 if (!$result) {
487 throw new RestException(404, 'BOM not found');
488 }
489
490 if (!DolibarrApi::_checkAccessToResource('bom_bom', $this->bom->id)) {
491 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
492 }
493
494 //Check the rowid is a line of current bom object
495 $lineIdIsFromObject = false;
496 foreach ($this->bom->lines as $bl) {
497 if ($bl->id == $lineid) {
498 $lineIdIsFromObject = true;
499 break;
500 }
501 }
502 if (!$lineIdIsFromObject) {
503 throw new RestException(500, 'Line to delete (rowid: '.$lineid.') is not a line of BOM (id: '.$this->bom->id.')');
504 }
505
506 $updateRes = $this->bom->deleteLine(DolibarrApiAccess::$user, $lineid);
507 if ($updateRes > 0) {
508 return array(
509 'success' => array(
510 'code' => 200,
511 'message' => 'line ' .$lineid. ' deleted'
512 )
513 );
514 } else {
515 throw new RestException(500, $this->bom->error);
516 }
517 }
518
519 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
529 protected function _cleanObjectDatas($object)
530 {
531 // phpcs:enable
532 $object = parent::_cleanObjectDatas($object);
533
534 unset($object->rowid);
535 unset($object->canvas);
536
537 unset($object->name);
538 unset($object->lastname);
539 unset($object->firstname);
540 unset($object->civility_id);
541 unset($object->statut);
542 unset($object->state);
543 unset($object->state_id);
544 unset($object->state_code);
545 unset($object->region);
546 unset($object->region_code);
547 unset($object->country);
548 unset($object->country_id);
549 unset($object->country_code);
550 unset($object->barcode_type);
551 unset($object->barcode_type_code);
552 unset($object->barcode_type_label);
553 unset($object->barcode_type_coder);
554 unset($object->total_ht);
555 unset($object->total_tva);
556 unset($object->total_localtax1);
557 unset($object->total_localtax2);
558 unset($object->total_ttc);
559 unset($object->fk_account);
560 unset($object->comments);
561 unset($object->note);
562 unset($object->mode_reglement_id);
563 unset($object->cond_reglement_id);
564 unset($object->cond_reglement);
565 unset($object->shipping_method_id);
566 unset($object->fk_incoterms);
567 unset($object->label_incoterms);
568 unset($object->location_incoterms);
569 unset($object->multicurrency_code);
570 unset($object->multicurrency_tx);
571 unset($object->multicurrency_total_ht);
572 unset($object->multicurrency_total_ttc);
573 unset($object->multicurrency_total_tva);
574 unset($object->multicurrency_total_localtax1);
575 unset($object->multicurrency_total_localtax2);
576
577
578 // If object has lines, remove $db property
579 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
580 $nboflines = count($object->lines);
581 for ($i = 0; $i < $nboflines; $i++) {
582 $this->_cleanObjectDatas($object->lines[$i]);
583
584 unset($object->lines[$i]->lines);
585 unset($object->lines[$i]->note);
586 }
587 }
588
589 return $object;
590 }
591
600 private function _validate($data)
601 {
602 if ($data === null) {
603 $data = array();
604 }
605 $myobject = array();
606 foreach ($this->bom->fields as $field => $propfield) {
607 if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || empty($propfield['notnull']) || $propfield['notnull'] != 1) {
608 continue; // Not a mandatory field
609 }
610 if (!isset($data[$field])) {
611 throw new RestException(400, "$field field missing");
612 }
613 $myobject[$field] = $data[$field];
614 }
615 return $myobject;
616 }
617
623 private function checkRefNumbering()
624 {
625 $ref = substr($this->bom->ref, 1, 4);
626 if ($this->bom->status > BOM::STATUS_DRAFT && $ref == 'PROV') {
627 throw new RestException(400, "Wrong naming scheme '(PROV%)' is only allowed on 'DRAFT' status. For automatic increment use 'auto' on the 'ref' field.");
628 }
629
630 if (strtolower($this->bom->ref) == 'auto') {
631 if (empty($this->bom->id) && $this->bom->status == BOM::STATUS_DRAFT) {
632 $this->bom->ref = ''; // 'ref' will auto incremented with '(PROV' + newID + ')'
633 } else {
634 $res = $this->bom->fetch_product();
635 if ($res > 0 && $this->bom->product instanceof Product) {
636 $numref = $this->bom->getNextNumRef($this->bom->product); // @phan-suppress-current-line PhanTypeMismatchArgumentNullable
637 $this->bom->ref = $numref;
638 } else {
639 throw new RestException(400, "Error when generating automatic increment on the 'ref' field.");
640 }
641 }
642 }
643 }
644}
$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
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.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.