dolibarr 25.0.0-alpha
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 if (! DolibarrApi::_checkAccessToResource('stockmovement', $this->stockmovement, 'stock_mouvement', '', '', 'rowid', 'fk_entrepot@entrepot')) {
91 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
92 }
93
94 return $this->_cleanObjectDatas($this->stockmovement);
95 }
96
115 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
116 {
117 $obj_ret = array();
118
119 if (!DolibarrApiAccess::$user->hasRight('stock', 'lire')) {
120 throw new RestException(403);
121 }
122
123 $sql = "SELECT t.rowid";
124 $sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement AS t";
125 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."entrepot as e ON t.fk_entrepot = e.rowid";
126 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."stock_mouvement_extrafields AS ef ON (ef.fk_object = t.rowid)";
127 $sql .= " WHERE e.entity IN (".getEntity('stock').")";
128
129 // Add sql filters
130 if ($sqlfilters) {
131 $errormessage = '';
132 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
133 if ($errormessage) {
134 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
135 }
136 }
137
138 // this query will return total stock movements with the filters given
139 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
140
141 $sql .= $this->db->order($sortfield, $sortorder);
142 if ($limit) {
143 if ($page < 0) {
144 $page = 0;
145 }
146 $offset = $limit * $page;
147
148 $sql .= $this->db->plimit($limit + 1, $offset);
149 }
150
151 $result = $this->db->query($sql);
152 if ($result) {
153 $i = 0;
154 $num = $this->db->num_rows($result);
155 $min = min($num, ($limit <= 0 ? $num : $limit));
156 while ($i < $min) {
157 $obj = $this->db->fetch_object($result);
158 $stockmovement_static = new MouvementStock($this->db);
159 if ($stockmovement_static->fetch($obj->rowid)) {
160 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($stockmovement_static), $properties);
161 }
162 $i++;
163 }
164 } else {
165 throw new RestException(503, 'Error when retrieve stock movement list : '.$this->db->lasterror());
166 }
167
168 // if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
169 if ($pagination_data) {
170 $totalsResult = $this->db->query($sqlTotals);
171 $total = $this->db->fetch_object($totalsResult)->total;
172
173 $tmp = $obj_ret;
174 $obj_ret = [];
175
176 $obj_ret['data'] = $tmp;
177 $obj_ret['pagination'] = [
178 'total' => (int) $total,
179 'page' => $page, //count starts from 0
180 'page_count' => ceil((int) $total / $limit),
181 'limit' => $limit
182 ];
183 }
184
185 return $obj_ret;
186 }
187
217 public function post($product_id, $warehouse_id, $qty, $type = 2, $batch = '', $movementcode = '', $label = '', $price = '', $datem = '', $sellBy = '', $eatBy = '', $origin_type = '', $origin_id = 0)
218 {
219 if (!DolibarrApiAccess::$user->hasRight('stock', 'creer')) {
220 throw new RestException(403);
221 }
222
223 if ($qty == 0) {
224 throw new RestException(503, "Making a stock movement with a quantity of 0 is not possible");
225 }
226
227 // Type increase or decrease
228 if ($type == 1 && $qty >= 0) {
229 $type = 0;
230 }
231 if ($type == 2 && $qty >= 0) {
232 $type = 3;
233 }
234
235 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
236 $dluo = empty($eatBy) ? '' : dol_stringtotime($eatBy);
237 $dlc = empty($sellBy) ? '' : dol_stringtotime($sellBy);
238 $dateMvt = empty($datem) ? '' : dol_stringtotime($datem);
239
240 $this->stockmovement->setOrigin($origin_type, $origin_id);
241 if ($this->stockmovement->_create(DolibarrApiAccess::$user, $product_id, $warehouse_id, $qty, $type, (float) $price, $label, $movementcode, $dateMvt, $dluo, $dlc, $batch) <= 0) {
242 $errormessage = $this->stockmovement->error;
243 if (empty($errormessage)) {
244 $errormessage = implode(',', $this->stockmovement->errors);
245 }
246 throw new RestException(503, 'Error when create stock movement : '.$errormessage);
247 }
248
249 return $this->stockmovement->id;
250 }
251
259 /*
260 public function put($id, $request_data = null)
261 {
262 if(! DolibarrApiAccess::$user->hasRight('stock', 'creer')) {
263 throw new RestException(403);
264 }
265
266 $result = $this->stockmovement->fetch($id);
267 if( ! $result ) {
268 throw new RestException(404, 'stock movement not found');
269 }
270
271 if( ! DolibarrApi::_checkAccessToResource('stock', $this->stockmovement)) {
272 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
273 }
274
275 foreach($request_data as $field => $value) {
276 if ($field == 'id') continue;
277 $this->stockmovement->$field = $this->_checkValForAPI($field, $value, $this->stockmovement);
278 }
279
280 if ($this->stockmovement->update($id, DolibarrApiAccess::$user)) {
281 return $this->get ($id);
282 }
283
284 return false;
285 }*/
286
293 /*
294 public function delete($id)
295 {
296 if (! DolibarrApiAccess::$user->hasRight('stock', 'supprimer')) {
297 throw new RestException(403);
298 }
299 $result = $this->stockmovement->fetch($id);
300 if (! $result ) {
301 throw new RestException(404, 'stock movement not found');
302 }
303
304 if (! DolibarrApi::_checkAccessToResource('stock', $this->stockmovement)) {
305 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
306 }
307
308 if (! $this->stockmovement->delete(DolibarrApiAccess::$user)) {
309 throw new RestException(403,'error when delete stock movement');
310 }
311
312 return array(
313 'success' => array(
314 'code' => 200,
315 'message' => 'Warehouse deleted'
316 )
317 );
318 }*/
319
320
321
322 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
332 protected function _cleanObjectDatas($object)
333 {
334 // phpcs:enable
335 $object = parent::_cleanObjectDatas($object);
336
337 // Remove useless data
338 unset($object->civility_id);
339 unset($object->firstname);
340 unset($object->lastname);
341 unset($object->name);
342 unset($object->location_incoterms);
343 unset($object->label_incoterms);
344 unset($object->fk_incoterms);
345 unset($object->lines);
346 unset($object->total_ht);
347 unset($object->total_ttc);
348 unset($object->total_tva);
349 unset($object->total_localtax1);
350 unset($object->total_localtax2);
351 unset($object->note);
352 unset($object->note_private);
353 unset($object->note_public);
354 unset($object->shipping_method_id);
355 unset($object->fk_account);
356 unset($object->model_pdf);
357 unset($object->fk_delivery_address);
358 unset($object->cond_reglement);
359 unset($object->cond_reglement_id);
360 unset($object->mode_reglement_id);
361 unset($object->barcode_type_coder);
362 unset($object->barcode_type_label);
363 unset($object->barcode_type_code);
364 unset($object->barcode_type);
365 unset($object->country_code);
366 unset($object->country_id);
367 unset($object->country);
368 unset($object->thirdparty);
369 unset($object->contact);
370 unset($object->contact_id);
371 unset($object->user);
372 unset($object->fk_project);
373 unset($object->project);
374 unset($object->canvas);
375
376 //unset($object->eatby); Filled correctly in read mode
377 //unset($object->sellby); Filled correctly in read mode
378
379 return $object;
380 }
381
390 private function _validate($data) // @phpstan-ignore-line
391 {
392 if ($data === null) {
393 $data = array();
394 }
395 $stockmovement = array();
396 foreach (self::$FIELDS as $field) {
397 if (!isset($data[$field])) {
398 throw new RestException(400, "$field field missing");
399 }
400 $stockmovement[$field] = $data[$field];
401 }
402 return $stockmovement;
403 }
404}
$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
_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', $parenttableforentity='')
Check access by user to a given resource.
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:436
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria