api_stockmovements.class.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. <?php
  2. /* Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. use Luracast\Restler\RestException;
  18. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  19. /**
  20. * API class for stock movements
  21. *
  22. * @access protected
  23. * @class DolibarrApiAccess {@requires user,external}
  24. */
  25. class StockMovements extends DolibarrApi
  26. {
  27. /**
  28. * @var array $FIELDS Mandatory fields, checked when create and update object
  29. */
  30. public static $FIELDS = array(
  31. 'product_id',
  32. 'warehouse_id',
  33. 'qty'
  34. );
  35. /**
  36. * @var MouvementStock $stockmovement {@type MouvementStock}
  37. */
  38. public $stockmovement;
  39. /**
  40. * Constructor
  41. */
  42. public function __construct()
  43. {
  44. global $db, $conf;
  45. $this->db = $db;
  46. $this->stockmovement = new MouvementStock($this->db);
  47. }
  48. /**
  49. * Get properties of a stock movement object
  50. *
  51. * Return an array with stock movement informations
  52. *
  53. * @param int $id ID of movement
  54. * @return Object Object with cleaned properties
  55. *
  56. * @throws RestException
  57. */
  58. /*
  59. public function get($id)
  60. {
  61. if(! DolibarrApiAccess::$user->rights->stock->lire) {
  62. throw new RestException(401);
  63. }
  64. $result = $this->stockmovement->fetch($id);
  65. if( ! $result ) {
  66. throw new RestException(404, 'warehouse not found');
  67. }
  68. if( ! DolibarrApi::_checkAccessToResource('warehouse',$this->stockmovement->id)) {
  69. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  70. }
  71. return $this->_cleanObjectDatas($this->stockmovement);
  72. }*/
  73. /**
  74. * Get a list of stock movement
  75. *
  76. * @param string $sortfield Sort field
  77. * @param string $sortorder Sort order
  78. * @param int $limit Limit for list
  79. * @param int $page Page number
  80. * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.product_id:=:1) and (t.date_creation:<:'20160101')"
  81. * @return array Array of warehouse objects
  82. *
  83. * @throws RestException
  84. */
  85. public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '')
  86. {
  87. global $conf;
  88. $obj_ret = array();
  89. if (!DolibarrApiAccess::$user->rights->stock->lire) {
  90. throw new RestException(401);
  91. }
  92. $sql = "SELECT t.rowid";
  93. $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
  94. //$sql.= ' WHERE t.entity IN ('.getEntity('stock').')';
  95. $sql .= ' WHERE 1 = 1';
  96. // Add sql filters
  97. if ($sqlfilters) {
  98. $errormessage = '';
  99. $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
  100. if ($errormessage) {
  101. throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
  102. }
  103. }
  104. $sql .= $this->db->order($sortfield, $sortorder);
  105. if ($limit) {
  106. if ($page < 0) {
  107. $page = 0;
  108. }
  109. $offset = $limit * $page;
  110. $sql .= $this->db->plimit($limit + 1, $offset);
  111. }
  112. $result = $this->db->query($sql);
  113. if ($result) {
  114. $i = 0;
  115. $num = $this->db->num_rows($result);
  116. $min = min($num, ($limit <= 0 ? $num : $limit));
  117. while ($i < $min) {
  118. $obj = $this->db->fetch_object($result);
  119. $stockmovement_static = new MouvementStock($this->db);
  120. if ($stockmovement_static->fetch($obj->rowid)) {
  121. $obj_ret[] = $this->_cleanObjectDatas($stockmovement_static);
  122. }
  123. $i++;
  124. }
  125. } else {
  126. throw new RestException(503, 'Error when retrieve stock movement list : '.$this->db->lasterror());
  127. }
  128. if (!count($obj_ret)) {
  129. throw new RestException(404, 'No stock movement found');
  130. }
  131. return $obj_ret;
  132. }
  133. /**
  134. * Create stock movement object.
  135. * You can use the following message to test this RES API:
  136. * { "product_id": 1, "warehouse_id": 1, "qty": 1, "lot": "", "movementcode": "INV123", "movementlabel": "Inventory 123", "price": 0 }
  137. * $price Can be set to update AWP (Average Weighted Price) when you make a stock increase
  138. * $dlc Eat-by date. Will be used if lot does not exists yet and will be created.
  139. * $dluo Sell-by date. Will be used if lot does not exists yet and will be created.
  140. *
  141. * @param int $product_id Id product id {@min 1} {@from body} {@required true}
  142. * @param int $warehouse_id Id warehouse {@min 1} {@from body} {@required true}
  143. * @param float $qty Qty to add (Use negative value for a stock decrease) {@from body} {@required true}
  144. * @param int $type Optionally specify the type of movement. 0=input (stock increase by a stock transfer), 1=output (stock decrease by a stock transfer), 2=output (stock decrease), 3=input (stock increase). {@from body} {@type int}
  145. * @param string $lot Lot {@from body}
  146. * @param string $movementcode Movement code {@from body}
  147. * @param string $movementlabel Movement label {@from body}
  148. * @param string $price To update AWP (Average Weighted Price) when you make a stock increase (qty must be higher then 0). {@from body}
  149. * @param string $datem Date of movement {@from body} {@type date}
  150. * @param string $dlc Eat-by date. {@from body} {@type date}
  151. * @param string $dluo Sell-by date. {@from body} {@type date}
  152. * @param string $origin_type Origin type (Element of source object, like 'project', 'inventory', ...)
  153. * @param string $origin_id Origin id (Id of source object)
  154. *
  155. * @return int ID of stock movement
  156. * @throws RestException
  157. */
  158. public function post($product_id, $warehouse_id, $qty, $type = 2, $lot = '', $movementcode = '', $movementlabel = '', $price = '', $datem = '', $dlc = '', $dluo = '', $origin_type = '', $origin_id = 0)
  159. {
  160. if (!DolibarrApiAccess::$user->rights->stock->creer) {
  161. throw new RestException(401);
  162. }
  163. if ($qty == 0) {
  164. throw new RestException(503, "Making a stock movement with a quantity of 0 is not possible");
  165. }
  166. // Type increase or decrease
  167. if ($type == 1 && $qty >= 0) {
  168. $type = 0;
  169. }
  170. if ($type == 2 && $qty >= 0) {
  171. $type = 3;
  172. }
  173. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  174. $eatBy = empty($dluo) ? '' : dol_stringtotime($dluo);
  175. $sellBy = empty($dlc) ? '' : dol_stringtotime($dlc);
  176. $dateMvt = empty($datem) ? '' : dol_stringtotime($datem);
  177. $this->stockmovement->setOrigin($origin_type, $origin_id);
  178. if ($this->stockmovement->_create(DolibarrApiAccess::$user, $product_id, $warehouse_id, $qty, $type, $price, $movementlabel, $movementcode, $dateMvt, $eatBy, $sellBy, $lot) <= 0) {
  179. $errormessage = $this->stockmovement->error;
  180. if (empty($errormessage)) {
  181. $errormessage = join(',', $this->stockmovement->errors);
  182. }
  183. throw new RestException(503, 'Error when create stock movement : '.$errormessage);
  184. }
  185. return $this->stockmovement->id;
  186. }
  187. /**
  188. * Update stock movement
  189. *
  190. * @param int $id Id of warehouse to update
  191. * @param array $request_data Datas
  192. * @return int
  193. */
  194. /*
  195. public function put($id, $request_data = null)
  196. {
  197. if(! DolibarrApiAccess::$user->rights->stock->creer) {
  198. throw new RestException(401);
  199. }
  200. $result = $this->stockmovement->fetch($id);
  201. if( ! $result ) {
  202. throw new RestException(404, 'stock movement not found');
  203. }
  204. if( ! DolibarrApi::_checkAccessToResource('stock',$this->stockmovement->id)) {
  205. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  206. }
  207. foreach($request_data as $field => $value) {
  208. if ($field == 'id') continue;
  209. $this->stockmovement->$field = $value;
  210. }
  211. if($this->stockmovement->update($id, DolibarrApiAccess::$user))
  212. return $this->get ($id);
  213. return false;
  214. }*/
  215. /**
  216. * Delete stock movement
  217. *
  218. * @param int $id Stock movement ID
  219. * @return array
  220. */
  221. /*
  222. public function delete($id)
  223. {
  224. if(! DolibarrApiAccess::$user->rights->stock->supprimer) {
  225. throw new RestException(401);
  226. }
  227. $result = $this->stockmovement->fetch($id);
  228. if( ! $result ) {
  229. throw new RestException(404, 'stock movement not found');
  230. }
  231. if( ! DolibarrApi::_checkAccessToResource('stock',$this->stockmovement->id)) {
  232. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  233. }
  234. if (! $this->stockmovement->delete(DolibarrApiAccess::$user)) {
  235. throw new RestException(401,'error when delete stock movement');
  236. }
  237. return array(
  238. 'success' => array(
  239. 'code' => 200,
  240. 'message' => 'Warehouse deleted'
  241. )
  242. );
  243. }*/
  244. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  245. /**
  246. * Clean sensible object datas
  247. *
  248. * @param MouvementStock $object Object to clean
  249. * @return Object Object with cleaned properties
  250. */
  251. protected function _cleanObjectDatas($object)
  252. {
  253. // phpcs:enable
  254. $object = parent::_cleanObjectDatas($object);
  255. // Remove useless data
  256. unset($object->civility_id);
  257. unset($object->firstname);
  258. unset($object->lastname);
  259. unset($object->name);
  260. unset($object->location_incoterms);
  261. unset($object->label_incoterms);
  262. unset($object->fk_incoterms);
  263. unset($object->lines);
  264. unset($object->total_ht);
  265. unset($object->total_ttc);
  266. unset($object->total_tva);
  267. unset($object->total_localtax1);
  268. unset($object->total_localtax2);
  269. unset($object->note);
  270. unset($object->note_private);
  271. unset($object->note_public);
  272. unset($object->shipping_method_id);
  273. unset($object->fk_account);
  274. unset($object->model_pdf);
  275. unset($object->fk_delivery_address);
  276. unset($object->cond_reglement);
  277. unset($object->cond_reglement_id);
  278. unset($object->mode_reglement_id);
  279. unset($object->barcode_type_coder);
  280. unset($object->barcode_type_label);
  281. unset($object->barcode_type_code);
  282. unset($object->barcode_type);
  283. unset($object->country_code);
  284. unset($object->country_id);
  285. unset($object->country);
  286. unset($object->thirdparty);
  287. unset($object->contact);
  288. unset($object->contact_id);
  289. unset($object->user);
  290. unset($object->fk_project);
  291. unset($object->project);
  292. unset($object->canvas);
  293. //unset($object->eatby); Filled correctly in read mode
  294. //unset($object->sellby); Filled correctly in read mode
  295. return $object;
  296. }
  297. /**
  298. * Validate fields before create or update object
  299. *
  300. * @param array|null $data Data to validate
  301. * @return array
  302. *
  303. * @throws RestException
  304. */
  305. private function _validate($data)
  306. {
  307. $stockmovement = array();
  308. foreach (self::$FIELDS as $field) {
  309. if (!isset($data[$field])) {
  310. throw new RestException(400, "$field field missing");
  311. }
  312. $stockmovement[$field] = $data[$field];
  313. }
  314. return $stockmovement;
  315. }
  316. }