dolibarr 23.0.4
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-2025 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 return $this->_cleanObjectDatas($this->productlot);
90 }
91
115 public function index($sortfield = "pl.batch", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
116 {
117 global $conf;
118
119 $obj_ret = [];
120
121 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
122 throw new RestException(403, "Insufficient rights to view your products lots");
123 }
124
125 $sortorder = (strtoupper($sortorder) === 'DESC') ? 'DESC' : 'ASC';
126
127 $sql = "SELECT pl.rowid";
128 $sql .= " FROM ".MAIN_DB_PREFIX."product_lot AS pl";
129 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot_extrafields AS ple ON ple.fk_object = pl.rowid";
130 // Productlot sets ismultientitymanaged = 1, so the list must be restricted to the entities the
131 // caller may see, as productlot_list.php does. Without it the API returns the lots of every entity.
132 $sql .= " WHERE pl.entity IN (".getEntity('productlot').")";
133
134 // Filtres universels
135 if ($sqlfilters) {
136 $errormessage = '';
137 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
138 if ($errormessage) {
139 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
140 }
141 }
142
143 // Clone pour total (avant ORDER/LIMIT)
144 $sqlTotals = preg_replace('/^\s*SELECT\s+pl\.rowid/i', 'SELECT COUNT(pl.rowid) AS total', $sql);
145
146 // ORDER BY
147 $sql .= $this->db->order($sortfield, $sortorder);
148
149 // LIMIT/OFFSET
150 if ($limit) {
151 $page = max(0, (int) $page);
152 $offset = $limit * $page;
153 $sql .= $this->db->plimit($limit + 1, $offset);
154 }
155
156 $res = $this->db->query($sql);
157 if (!$res) {
158 throw new RestException(503, 'Error when retrieving product lot list: '.$this->db->lasterror());
159 }
160
161 $i = 0;
162 $num = $this->db->num_rows($res);
163 $max = ($limit > 0) ? min($num, $limit) : $num;
164
165 while ($i < $max) {
166 $obj = $this->db->fetch_object($res);
167 if (!$obj) break;
168
169 $pl = new Productlot($this->db);
170 if ($pl->fetch((int) $obj->rowid) > 0) {
171 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($pl), $properties);
172 }
173 $i++;
174 }
175
176 // Pagination enrichie
177 if ($pagination_data) {
178 $total = 0;
179 $totRes = $this->db->query($sqlTotals);
180 if ($totRes) {
181 $row = $this->db->fetch_object($totRes);
182 if ($row && isset($row->total)) $total = (int) $row->total;
183 }
184
185 // Evite division par zéro
186 $safeLimit = ($limit > 0) ? (int) $limit : max(1, count($obj_ret));
187 $pageCount = (int) ceil($total / $safeLimit);
188
189 $data = $obj_ret;
190 $obj_ret = [
191 'data' => $data,
192 'pagination' => [
193 'total' => $total,
194 'page' => (int) $page,
195 'page_count' => $pageCount,
196 'limit' => $safeLimit
197 ]
198 ];
199 }
200
201 return $obj_ret;
202 }
203
204
218 public function post($request_data = null)
219 {
220 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
221 throw new RestException(403, "Insufficient rights to create your product lot");
222 }
223
224 // Check mandatory fields
225 $result = $this->_validate($request_data);
226
227 foreach ($request_data as $field => $value) {
228 if ($field === 'caller') {
229 // 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
230 $this->productlot->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
231 continue;
232 }
233
234 $this->productlot->$field = $this->_checkValForAPI($field, $value, $this->productlot);
235 }
236 /*if (isset($request_data["lines"])) {
237 $lines = array();
238 foreach ($request_data["lines"] as $line) {
239 array_push($lines, (object) $line);
240 }
241 $this->expensereport->lines = $lines;
242 }*/
243
244 if ($this->productlot->create(DolibarrApiAccess::$user) < 0) {
245 throw new RestException(500, "Error creating event", array_merge(array($this->productlot->error), $this->productlot->errors));
246 }
247
248 return $this->productlot->id;
249 }
250
251
265 public function put($id, $request_data = null)
266 {
267 if (!DolibarrApiAccess::$user->hasRight('produit', 'creer')) {
268 throw new RestException(403, "Insufficient rights to create your Product lot");
269 }
270
271 $result = $this->productlot->fetch($id);
272 if ($result) {
273 $this->productlot->fetch_optionals();
274 $this->productlot->oldcopy = clone $this->productlot; // @phan-suppress-current-line PhanTypeMismatchProperty
275 }
276 if (!$result) {
277 throw new RestException(404, 'productlot not found');
278 }
279
280 if (!DolibarrApi::_checkAccessToResource('productlot', $this->productlot->id, 'product_lot', '', 'fk_soc', 'rowid')) {
281 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
282 }
283 foreach ($request_data as $field => $value) {
284 if ($field == 'id') {
285 continue;
286 }
287 if ($field === 'caller') {
288 // 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
289 $this->productlot->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
290 continue;
291 }
292
293 if ($field == 'array_options' && is_array($value)) {
294 foreach ($value as $index => $val) {
295 $this->productlot->array_options[$index] = $this->_checkValForAPI($field, $val, $this->productlot);
296 }
297 continue;
298 }
299 $this->productlot->$field = $this->_checkValForAPI($field, $value, $this->productlot);
300 }
301
302 if ($this->productlot->update(DolibarrApiAccess::$user) > 0) {
303 return $this->get($id);
304 }
305
306 return false;
307 }
308
322 public function delete($id)
323 {
324 if (!DolibarrApiAccess::$user->hasRight('produit', 'supprimer')) {
325 throw new RestException(403, "Insufficient rights to delete your product lot");
326 }
327
328 $result = $this->productlot->fetch($id);
329 if ($result) {
330 $this->productlot->fetch_optionals();
331 $this->productlot->oldcopy = clone $this->productlot; // @phan-suppress-current-line PhanTypeMismatchProperty
332 }
333
334 if (!$result) {
335 throw new RestException(404, 'Product lot not found');
336 }
337
338 if (!DolibarrApi::_checkAccessToResource('productlot', $this->productlot->id, 'product_lot', '', 'fk_soc', 'rowid')) {
339 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
340 }
341
342 if ($this->productlot->delete(DolibarrApiAccess::$user) < 0) {
343 throw new RestException(500, 'Error when delete Product lot : '.implode(',', $this->productlot->errors));
344 }
345
346 return array(
347 'success' => array(
348 'code' => 200,
349 'message' => 'Product lot deleted'
350 )
351 );
352 }
353
361 private function _validate($data)
362 {
363 if ($data === null) {
364 $data = array();
365 }
366
367 $lot = array();
368
369 foreach (self::$FIELDS as $field) {
370 if (!isset($data[$field]) || $data[$field] === '') {
371 throw new RestException(400, "$field field missing");
372 }
373 $lot[$field] = $data[$field];
374 }
375
376 return $lot;
377 }
378
379
380 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
390 protected function _cleanObjectDatas($object)
391 {
392 // phpcs:enable
393 $object = parent::_cleanObjectDatas($object);
394
395 unset($object->note); // already in note_private or note_public
396 unset($object->usermod);
397 unset($object->libelle);
398 unset($object->context);
399 unset($object->canvas);
400 unset($object->contact);
401 unset($object->contact_id);
402 unset($object->thirdparty);
403 unset($object->user);
404 unset($object->origin);
405 unset($object->origin_id);
406 unset($object->ref_ext);
407 unset($object->statut);
408 unset($object->state_code);
409 unset($object->state_id);
410 unset($object->state);
411 unset($object->region);
412 unset($object->region_code);
413 unset($object->country);
414 unset($object->country_id);
415 unset($object->country_code);
416 unset($object->barcode_type);
417 unset($object->barcode_type_code);
418 unset($object->barcode_type_label);
419 unset($object->barcode_type_coder);
420 unset($object->mode_reglement_id);
421 unset($object->cond_reglement_id);
422 unset($object->cond_reglement);
423 unset($object->fk_delivery_address);
424 unset($object->shipping_method_id);
425 unset($object->fk_account);
426 unset($object->total_ht);
427 unset($object->total_tva);
428 unset($object->total_localtax1);
429 unset($object->total_localtax2);
430 unset($object->total_ttc);
431 unset($object->fk_incoterms);
432 unset($object->label_incoterms);
433 unset($object->location_incoterms);
434 unset($object->name);
435 unset($object->lastname);
436 unset($object->firstname);
437 unset($object->civility_id);
438 unset($object->contact);
439 unset($object->societe);
440 unset($object->demand_reason_id);
441 unset($object->transport_mode_id);
442 unset($object->region_id);
443 unset($object->actions);
444 unset($object->lines);
445
446 return $object;
447 }
448}
$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:33
_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:98
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.
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.