dolibarr 25.0.0-alpha
api_productlots.class.php
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2025 William Mead <william@m34d.com>
6 * Copyright (C) 2025 Frédéric France <frederic.france@free.fr>
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 . '/product/stock/class/productlot.class.php';
25
35{
39 public static $FIELDS = array(
40 'fk_product',
41 'batch'
42 );
43
47 public $productlot;
48
52 public function __construct()
53 {
54 global $db, $conf;
55 $this->db = $db;
56 $this->productlot = new Productlot($this->db);
57 }
58
71 public function get($id)
72 {
73 if (!DolibarrApiAccess::$user->hasRight('product', 'lire')) {
74 throw new RestException(403, "Insufficient rights to read an event");
75 }
76 if ($id === 0) {
77 $result = $this->productlot->initAsSpecimen();
78 } else {
79 $result = $this->productlot->fetch($id);
80 if ($result) {
81 $this->productlot->fetch_optionals();
82 $this->productlot->fetchObjectLinked();
83 }
84 }
85 if (!$result) {
86 throw new RestException(404, 'Product lots not found');
87 }
88
89 if ($id > 0 && !DolibarrApi::_checkAccessToResource('produit', $this->productlot->id, 'product_lot')) {
90 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
91 }
92
93 return $this->_cleanObjectDatas($this->productlot);
94 }
95
119 public function index($sortfield = "pl.batch", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
120 {
121 global $conf;
122
123 $obj_ret = [];
124
125 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
126 throw new RestException(403, "Insufficient rights to view your products lots");
127 }
128
129 $sortorder = (strtoupper($sortorder) === 'DESC') ? 'DESC' : 'ASC';
130
131 $sql = "SELECT pl.rowid";
132 $sql .= " FROM ".MAIN_DB_PREFIX."product_lot AS pl";
133 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot_extrafields AS ple ON ple.fk_object = pl.rowid";
134 // Productlot sets ismultientitymanaged = 1, so the list must be restricted to the entities the
135 // caller may see, as productlot_list.php does. Without it the API returns the lots of every entity.
136 $sql .= " WHERE pl.entity IN (".getEntity('productlot').")";
137
138 // Global 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 // Clone for total (before ORDER/LIMIT)
148 $sqlTotals = preg_replace('/^\s*SELECT\s+pl\.rowid/i', 'SELECT COUNT(pl.rowid) AS total', $sql);
149
150 // ORDER BY
151 $sql .= $this->db->order($sortfield, $sortorder);
152
153 // LIMIT/OFFSET
154 if ($limit) {
155 $page = max(0, (int) $page);
156 $offset = $limit * $page;
157 $sql .= $this->db->plimit($limit + 1, $offset);
158 }
159
160 $res = $this->db->query($sql);
161 if (!$res) {
162 throw new RestException(503, 'Error when retrieving product lot list: '.$this->db->lasterror());
163 }
164
165 $i = 0;
166 $num = $this->db->num_rows($res);
167 $max = ($limit > 0) ? min($num, $limit) : $num;
168
169 while ($i < $max) {
170 $obj = $this->db->fetch_object($res);
171 if (!$obj) break;
172
173 $pl = new Productlot($this->db);
174 if ($pl->fetch((int) $obj->rowid) > 0) {
175 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($pl), $properties);
176 }
177 $i++;
178 }
179
180 // Pagination enrichie
181 if ($pagination_data) {
182 $total = 0;
183 $totRes = $this->db->query($sqlTotals);
184 if ($totRes) {
185 $row = $this->db->fetch_object($totRes);
186 if ($row && isset($row->total)) $total = (int) $row->total;
187 }
188
189 // Avoid division by zero
190 $safeLimit = ($limit > 0) ? (int) $limit : max(1, count($obj_ret));
191 $pageCount = (int) ceil($total / $safeLimit);
192
193 $data = $obj_ret;
194 $obj_ret = [
195 'data' => $data,
196 'pagination' => [
197 'total' => $total,
198 'page' => (int) $page,
199 'page_count' => $pageCount,
200 'limit' => $safeLimit
201 ]
202 ];
203 }
204
205 return $obj_ret;
206 }
207
208
222 public function post($request_data = null)
223 {
224 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
225 throw new RestException(403, "Insufficient rights to create your product lot");
226 }
227
228 // Check mandatory fields
229 $result = $this->_validate($request_data);
230
231 foreach ($request_data as $field => $value) {
232 if ($field === 'caller') {
233 // 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
234 $this->productlot->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
235 continue;
236 }
237
238 $this->productlot->$field = $this->_checkValForAPI($field, $value, $this->productlot);
239 }
240 /*if (isset($request_data["lines"])) {
241 $lines = array();
242 foreach ($request_data["lines"] as $line) {
243 array_push($lines, (object) $line);
244 }
245 $this->expensereport->lines = $lines;
246 }*/
247
248 if ($this->productlot->create(DolibarrApiAccess::$user) < 0) {
249 throw new RestException(500, "Error creating event", array_merge(array($this->productlot->error), $this->productlot->errors));
250 }
251
252 return $this->productlot->id;
253 }
254
255
269 public function put($id, $request_data = null)
270 {
271 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
272 throw new RestException(403, "Insufficient rights to create your Product lot");
273 }
274
275 $result = $this->productlot->fetch($id);
276 if ($result) {
277 $this->productlot->fetch_optionals();
278 $this->productlot->oldcopy = clone $this->productlot; // @phan-suppress-current-line PhanTypeMismatchProperty
279 }
280 if (!$result) {
281 throw new RestException(404, 'productlot not found');
282 }
283
284 if (!DolibarrApi::_checkAccessToResource('produit', $this->productlot->id, 'product_lot')) {
285 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
286 }
287 foreach ($request_data as $field => $value) {
288 if ($field == 'id') {
289 continue;
290 }
291 if ($field === 'caller') {
292 // 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
293 $this->productlot->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
294 continue;
295 }
296
297 if ($field == 'array_options' && is_array($value)) {
298 foreach ($value as $index => $val) {
299 $this->productlot->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->productlot);
300 }
301 continue;
302 }
303 $this->productlot->$field = $this->_checkValForAPI($field, $value, $this->productlot);
304 }
305
306 if ($this->productlot->update(DolibarrApiAccess::$user) > 0) {
307 return $this->get($id);
308 }
309
310 return false;
311 }
312
326 public function delete($id)
327 {
328 if (!DolibarrApiAccess::$user->hasRight('produit', 'supprimer')) {
329 throw new RestException(403, "Insufficient rights to delete your product lot");
330 }
331
332 $result = $this->productlot->fetch($id);
333 if ($result) {
334 $this->productlot->fetch_optionals();
335 $this->productlot->oldcopy = clone $this->productlot; // @phan-suppress-current-line PhanTypeMismatchProperty
336 }
337
338 if (!$result) {
339 throw new RestException(404, 'Product lot not found');
340 }
341
342 if (!DolibarrApi::_checkAccessToResource('produit', $this->productlot->id, 'product_lot')) {
343 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
344 }
345
346 if ($this->productlot->delete(DolibarrApiAccess::$user) < 0) {
347 throw new RestException(500, 'Error when delete Product lot : '.implode(',', $this->productlot->errors));
348 }
349
350 return array(
351 'success' => array(
352 'code' => 200,
353 'message' => 'Product lot deleted'
354 )
355 );
356 }
357
365 private function _validate($data)
366 {
367 if ($data === null) {
368 $data = array();
369 }
370
371 $lot = array();
372
373 foreach (self::$FIELDS as $field) {
374 if (!isset($data[$field]) || $data[$field] === '') {
375 throw new RestException(400, "$field field missing");
376 }
377 $lot[$field] = $data[$field];
378 }
379
380 return $lot;
381 }
382
383
384 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
394 protected function _cleanObjectDatas($object)
395 {
396 // phpcs:enable
397 $object = parent::_cleanObjectDatas($object);
398
399 unset($object->note); // already in note_private or note_public
400 unset($object->usermod);
401 unset($object->libelle);
402 unset($object->context);
403 unset($object->canvas);
404 unset($object->contact);
405 unset($object->contact_id);
406 unset($object->thirdparty);
407 unset($object->user);
408 unset($object->origin);
409 unset($object->origin_id);
410 unset($object->ref_ext);
411 unset($object->statut);
412 unset($object->state_code);
413 unset($object->state_id);
414 unset($object->state);
415 unset($object->region);
416 unset($object->region_code);
417 unset($object->country);
418 unset($object->country_id);
419 unset($object->country_code);
420 unset($object->barcode_type);
421 unset($object->barcode_type_code);
422 unset($object->barcode_type_label);
423 unset($object->barcode_type_coder);
424 unset($object->mode_reglement_id);
425 unset($object->cond_reglement_id);
426 unset($object->cond_reglement);
427 unset($object->fk_delivery_address);
428 unset($object->shipping_method_id);
429 unset($object->fk_account);
430 unset($object->total_ht);
431 unset($object->total_tva);
432 unset($object->total_localtax1);
433 unset($object->total_localtax2);
434 unset($object->total_ttc);
435 unset($object->fk_incoterms);
436 unset($object->label_incoterms);
437 unset($object->location_incoterms);
438 unset($object->name);
439 unset($object->lastname);
440 unset($object->firstname);
441 unset($object->civility_id);
442 unset($object->contact);
443 unset($object->societe);
444 unset($object->demand_reason_id);
445 unset($object->transport_mode_id);
446 unset($object->region_id);
447 unset($object->actions);
448 unset($object->lines);
449
450 return $object;
451 }
452}
$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 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.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $parenttableforentity='')
Check access by user to a given resource.
Class with list of lots and properties.
index($sortfield="pl.batch", $sortorder='ASC', $limit=100, $page=0, $user_ids='', $sqlfilters='', $properties='', $pagination_data=false)
List of product lot.
_validate($data)
Validate fields before create or update object.
post($request_data=null)
Create an product lot.
put($id, $request_data=null)
Update an Product lot.
__construct()
Constructor.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.