dolibarr 23.0.3
api_stockmovements.class.php
1<?php
2/* Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
4 * Copyright (C) 2025 William Mead <william@m34d.com>
5 * Copyright (C) 2025 Frédéric France <frederic.france@free.fr>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21use Luracast\Restler\RestException;
22
23require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
24
25
35{
39 public static $FIELDS = array(
40 'product_id',
41 'warehouse_id',
42 'qty'
43 );
44
48 public $stockmovement;
49
53 public function __construct()
54 {
55 global $db;
56 $this->db = $db;
57 $this->stockmovement = new MouvementStock($this->db);
58 }
59
77 public function get($id)
78 {
79 if (!DolibarrApiAccess::$user->hasRight('stock', 'mouvement', 'lire')) {
80 throw new RestException(403);
81 }
82 if ($id == 0) {
83 throw new RestException(400, 'No stock movement with id 0 can exist');
84 }
85 $result = $this->stockmovement->fetch($id);
86 if (!$result ) {
87 throw new RestException(404, 'stock movement not found');
88 }
89
90 return $this->_cleanObjectDatas($this->stockmovement);
91 }
92
111 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
112 {
113 $obj_ret = array();
114
115 if (!DolibarrApiAccess::$user->hasRight('stock', 'lire')) {
116 throw new RestException(403);
117 }
118
119 $sql = "SELECT t.rowid";
120 $sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement AS t LEFT JOIN ".MAIN_DB_PREFIX."stock_mouvement_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
121
122 //$sql.= ' WHERE t.entity IN ('.getEntity('stock').')';
123 $sql .= ' WHERE 1 = 1';
124 // Add sql filters
125 if ($sqlfilters) {
126 $errormessage = '';
127 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
128 if ($errormessage) {
129 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
130 }
131 }
132
133 // this query will return total stock movements with the filters given
134 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
135
136 $sql .= $this->db->order($sortfield, $sortorder);
137 if ($limit) {
138 if ($page < 0) {
139 $page = 0;
140 }
141 $offset = $limit * $page;
142
143 $sql .= $this->db->plimit($limit + 1, $offset);
144 }
145
146 $result = $this->db->query($sql);
147 if ($result) {
148 $i = 0;
149 $num = $this->db->num_rows($result);
150 $min = min($num, ($limit <= 0 ? $num : $limit));
151 while ($i < $min) {
152 $obj = $this->db->fetch_object($result);
153 $stockmovement_static = new MouvementStock($this->db);
154 if ($stockmovement_static->fetch($obj->rowid)) {
155 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($stockmovement_static), $properties);
156 }
157 $i++;
158 }
159 } else {
160 throw new RestException(503, 'Error when retrieve stock movement list : '.$this->db->lasterror());
161 }
162
163 // if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
164 if ($pagination_data) {
165 $totalsResult = $this->db->query($sqlTotals);
166 $total = $this->db->fetch_object($totalsResult)->total;
167
168 $tmp = $obj_ret;
169 $obj_ret = [];
170
171 $obj_ret['data'] = $tmp;
172 $obj_ret['pagination'] = [
173 'total' => (int) $total,
174 'page' => $page, //count starts from 0
175 'page_count' => ceil((int) $total / $limit),
176 'limit' => $limit
177 ];
178 }
179
180 return $obj_ret;
181 }
182
212 public function post($product_id, $warehouse_id, $qty, $type = 2, $batch = '', $movementcode = '', $label = '', $price = '', $datem = '', $sellBy = '', $eatBy = '', $origin_type = '', $origin_id = 0)
213 {
214 if (!DolibarrApiAccess::$user->hasRight('stock', 'creer')) {
215 throw new RestException(403);
216 }
217
218 if ($qty == 0) {
219 throw new RestException(503, "Making a stock movement with a quantity of 0 is not possible");
220 }
221
222 // Type increase or decrease
223 if ($type == 1 && $qty >= 0) {
224 $type = 0;
225 }
226 if ($type == 2 && $qty >= 0) {
227 $type = 3;
228 }
229
230 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
231 $dluo = empty($eatBy) ? '' : dol_stringtotime($eatBy);
232 $dlc = empty($sellBy) ? '' : dol_stringtotime($sellBy);
233 $dateMvt = empty($datem) ? '' : dol_stringtotime($datem);
234
235 $this->stockmovement->setOrigin($origin_type, $origin_id);
236 if ($this->stockmovement->_create(DolibarrApiAccess::$user, $product_id, $warehouse_id, $qty, $type, (float) $price, $label, $movementcode, $dateMvt, $dluo, $dlc, $batch) <= 0) {
237 $errormessage = $this->stockmovement->error;
238 if (empty($errormessage)) {
239 $errormessage = implode(',', $this->stockmovement->errors);
240 }
241 throw new RestException(503, 'Error when create stock movement : '.$errormessage);
242 }
243
244 return $this->stockmovement->id;
245 }
246
254 /*
255 public function put($id, $request_data = null)
256 {
257 if(! DolibarrApiAccess::$user->hasRight('stock', 'creer')) {
258 throw new RestException(403);
259 }
260
261 $result = $this->stockmovement->fetch($id);
262 if( ! $result ) {
263 throw new RestException(404, 'stock movement not found');
264 }
265
266 if( ! DolibarrApi::_checkAccessToResource('stock',$this->stockmovement->id)) {
267 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
268 }
269
270 foreach($request_data as $field => $value) {
271 if ($field == 'id') continue;
272 $this->stockmovement->$field = $value;
273 }
274
275 if($this->stockmovement->update($id, DolibarrApiAccess::$user))
276 return $this->get ($id);
277
278 return false;
279 }*/
280
287 /*
288 public function delete($id)
289 {
290 if (! DolibarrApiAccess::$user->hasRight('stock', 'supprimer')) {
291 throw new RestException(403);
292 }
293 $result = $this->stockmovement->fetch($id);
294 if (! $result ) {
295 throw new RestException(404, 'stock movement not found');
296 }
297
298 if (! DolibarrApi::_checkAccessToResource('stock',$this->stockmovement->id)) {
299 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
300 }
301
302 if (! $this->stockmovement->delete(DolibarrApiAccess::$user)) {
303 throw new RestException(403,'error when delete stock movement');
304 }
305
306 return array(
307 'success' => array(
308 'code' => 200,
309 'message' => 'Warehouse deleted'
310 )
311 );
312 }*/
313
314
315
316 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
326 protected function _cleanObjectDatas($object)
327 {
328 // phpcs:enable
329 $object = parent::_cleanObjectDatas($object);
330
331 // Remove useless data
332 unset($object->civility_id);
333 unset($object->firstname);
334 unset($object->lastname);
335 unset($object->name);
336 unset($object->location_incoterms);
337 unset($object->label_incoterms);
338 unset($object->fk_incoterms);
339 unset($object->lines);
340 unset($object->total_ht);
341 unset($object->total_ttc);
342 unset($object->total_tva);
343 unset($object->total_localtax1);
344 unset($object->total_localtax2);
345 unset($object->note);
346 unset($object->note_private);
347 unset($object->note_public);
348 unset($object->shipping_method_id);
349 unset($object->fk_account);
350 unset($object->model_pdf);
351 unset($object->fk_delivery_address);
352 unset($object->cond_reglement);
353 unset($object->cond_reglement_id);
354 unset($object->mode_reglement_id);
355 unset($object->barcode_type_coder);
356 unset($object->barcode_type_label);
357 unset($object->barcode_type_code);
358 unset($object->barcode_type);
359 unset($object->country_code);
360 unset($object->country_id);
361 unset($object->country);
362 unset($object->thirdparty);
363 unset($object->contact);
364 unset($object->contact_id);
365 unset($object->user);
366 unset($object->fk_project);
367 unset($object->project);
368 unset($object->canvas);
369
370 //unset($object->eatby); Filled correctly in read mode
371 //unset($object->sellby); Filled correctly in read mode
372
373 return $object;
374 }
375
384 private function _validate($data) // @phpstan-ignore-line
385 {
386 if ($data === null) {
387 $data = array();
388 }
389 $stockmovement = array();
390 foreach (self::$FIELDS as $field) {
391 if (!isset($data[$field])) {
392 throw new RestException(400, "$field field missing");
393 }
394 $stockmovement[$field] = $data[$field];
395 }
396 return $stockmovement;
397 }
398}
$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.
Class to manage stock movements.
_validate($data)
Validate fields before create or update object.
post($product_id, $warehouse_id, $qty, $type=2, $batch='', $movementcode='', $label='', $price='', $datem='', $sellBy='', $eatBy='', $origin_type='', $origin_id=0)
Create a stock movement.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $sqlfilters='', $properties='', $pagination_data=false)
Get a list of stock movements.
_cleanObjectDatas($object)
Update stock movement.
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:434
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria