api_stockmovements.class.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. * @param string $properties Restrict the data returned to theses properties. Ignored if empty. Comma separated list of properties names
  82. * @return array Array of warehouse objects
  83. *
  84. * @throws RestException
  85. */
  86. public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
  87. {
  88. global $conf;
  89. $obj_ret = array();
  90. if (!DolibarrApiAccess::$user->rights->stock->lire) {
  91. throw new RestException(401);
  92. }
  93. $sql = "SELECT t.rowid";
  94. $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
  95. //$sql.= ' WHERE t.entity IN ('.getEntity('stock').')';
  96. $sql .= ' WHERE 1 = 1';
  97. // Add sql filters
  98. if ($sqlfilters) {
  99. $errormessage = '';
  100. $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
  101. if ($errormessage) {
  102. throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
  103. }
  104. }
  105. $sql .= $this->db->order($sortfield, $sortorder);
  106. if ($limit) {
  107. if ($page < 0) {
  108. $page = 0;
  109. }
  110. $offset = $limit * $page;
  111. $sql .= $this->db->plimit($limit + 1, $offset);
  112. }
  113. $result = $this->db->query($sql);
  114. if ($result) {
  115. $i = 0;
  116. $num = $this->db->num_rows($result);
  117. $min = min($num, ($limit <= 0 ? $num : $limit));
  118. while ($i < $min) {
  119. $obj = $this->db->fetch_object($result);
  120. $stockmovement_static = new MouvementStock($this->db);
  121. if ($stockmovement_static->fetch($obj->rowid)) {
  122. $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($stockmovement_static), $properties);
  123. }
  124. $i++;
  125. }
  126. } else {
  127. throw new RestException(503, 'Error when retrieve stock movement list : '.$this->db->lasterror());
  128. }
  129. return $obj_ret;
  130. }
  131. /**
  132. * Create stock movement object.
  133. * You can use the following message to test this RES API:
  134. * { "product_id": 1, "warehouse_id": 1, "qty": 1, "lot": "", "movementcode": "INV123", "movementlabel": "Inventory 123", "price": 0 }
  135. * $price Can be set to update AWP (Average Weighted Price) when you make a stock increase
  136. * $dlc Eat-by date. Will be used if lot does not exists yet and will be created.
  137. * $dluo Sell-by date. Will be used if lot does not exists yet and will be created.
  138. *
  139. * @param int $product_id Id product id {@min 1} {@from body} {@required true}
  140. * @param int $warehouse_id Id warehouse {@min 1} {@from body} {@required true}
  141. * @param float $qty Qty to add (Use negative value for a stock decrease) {@from body} {@required true}
  142. * @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}
  143. * @param string $lot Lot {@from body}
  144. * @param string $movementcode Movement code {@from body}
  145. * @param string $movementlabel Movement label {@from body}
  146. * @param string $price To update AWP (Average Weighted Price) when you make a stock increase (qty must be higher then 0). {@from body}
  147. * @param string $datem Date of movement {@from body} {@type date}
  148. * @param string $dlc Eat-by date. {@from body} {@type date}
  149. * @param string $dluo Sell-by date. {@from body} {@type date}
  150. * @param string $origin_type Origin type (Element of source object, like 'project', 'inventory', ...)
  151. * @param int $origin_id Origin id (Id of source object)
  152. *
  153. * @return int ID of stock movement
  154. * @throws RestException
  155. */
  156. public function post($product_id, $warehouse_id, $qty, $type = 2, $lot = '', $movementcode = '', $movementlabel = '', $price = '', $datem = '', $dlc = '', $dluo = '', $origin_type = '', $origin_id = 0)
  157. {
  158. if (!DolibarrApiAccess::$user->rights->stock->creer) {
  159. throw new RestException(401);
  160. }
  161. if ($qty == 0) {
  162. throw new RestException(503, "Making a stock movement with a quantity of 0 is not possible");
  163. }
  164. // Type increase or decrease
  165. if ($type == 1 && $qty >= 0) {
  166. $type = 0;
  167. }
  168. if ($type == 2 && $qty >= 0) {
  169. $type = 3;
  170. }
  171. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  172. $eatBy = empty($dluo) ? '' : dol_stringtotime($dluo);
  173. $sellBy = empty($dlc) ? '' : dol_stringtotime($dlc);
  174. $dateMvt = empty($datem) ? '' : dol_stringtotime($datem);
  175. $this->stockmovement->setOrigin($origin_type, $origin_id);
  176. if ($this->stockmovement->_create(DolibarrApiAccess::$user, $product_id, $warehouse_id, $qty, $type, $price, $movementlabel, $movementcode, $dateMvt, $eatBy, $sellBy, $lot) <= 0) {
  177. $errormessage = $this->stockmovement->error;
  178. if (empty($errormessage)) {
  179. $errormessage = join(',', $this->stockmovement->errors);
  180. }
  181. throw new RestException(503, 'Error when create stock movement : '.$errormessage);
  182. }
  183. return $this->stockmovement->id;
  184. }
  185. /**
  186. * Update stock movement
  187. *
  188. * @param int $id Id of warehouse to update
  189. * @param array $request_data Datas
  190. * @return int
  191. */
  192. /*
  193. public function put($id, $request_data = null)
  194. {
  195. if(! DolibarrApiAccess::$user->rights->stock->creer) {
  196. throw new RestException(401);
  197. }
  198. $result = $this->stockmovement->fetch($id);
  199. if( ! $result ) {
  200. throw new RestException(404, 'stock movement not found');
  201. }
  202. if( ! DolibarrApi::_checkAccessToResource('stock',$this->stockmovement->id)) {
  203. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  204. }
  205. foreach($request_data as $field => $value) {
  206. if ($field == 'id') continue;
  207. $this->stockmovement->$field = $value;
  208. }
  209. if($this->stockmovement->update($id, DolibarrApiAccess::$user))
  210. return $this->get ($id);
  211. return false;
  212. }*/
  213. /**
  214. * Delete stock movement
  215. *
  216. * @param int $id Stock movement ID
  217. * @return array
  218. */
  219. /*
  220. public function delete($id)
  221. {
  222. if(! DolibarrApiAccess::$user->rights->stock->supprimer) {
  223. throw new RestException(401);
  224. }
  225. $result = $this->stockmovement->fetch($id);
  226. if( ! $result ) {
  227. throw new RestException(404, 'stock movement not found');
  228. }
  229. if( ! DolibarrApi::_checkAccessToResource('stock',$this->stockmovement->id)) {
  230. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  231. }
  232. if (! $this->stockmovement->delete(DolibarrApiAccess::$user)) {
  233. throw new RestException(401,'error when delete stock movement');
  234. }
  235. return array(
  236. 'success' => array(
  237. 'code' => 200,
  238. 'message' => 'Warehouse deleted'
  239. )
  240. );
  241. }*/
  242. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  243. /**
  244. * Clean sensible object datas
  245. *
  246. * @param MouvementStock $object Object to clean
  247. * @return Object Object with cleaned properties
  248. */
  249. protected function _cleanObjectDatas($object)
  250. {
  251. // phpcs:enable
  252. $object = parent::_cleanObjectDatas($object);
  253. // Remove useless data
  254. unset($object->civility_id);
  255. unset($object->firstname);
  256. unset($object->lastname);
  257. unset($object->name);
  258. unset($object->location_incoterms);
  259. unset($object->label_incoterms);
  260. unset($object->fk_incoterms);
  261. unset($object->lines);
  262. unset($object->total_ht);
  263. unset($object->total_ttc);
  264. unset($object->total_tva);
  265. unset($object->total_localtax1);
  266. unset($object->total_localtax2);
  267. unset($object->note);
  268. unset($object->note_private);
  269. unset($object->note_public);
  270. unset($object->shipping_method_id);
  271. unset($object->fk_account);
  272. unset($object->model_pdf);
  273. unset($object->fk_delivery_address);
  274. unset($object->cond_reglement);
  275. unset($object->cond_reglement_id);
  276. unset($object->mode_reglement_id);
  277. unset($object->barcode_type_coder);
  278. unset($object->barcode_type_label);
  279. unset($object->barcode_type_code);
  280. unset($object->barcode_type);
  281. unset($object->country_code);
  282. unset($object->country_id);
  283. unset($object->country);
  284. unset($object->thirdparty);
  285. unset($object->contact);
  286. unset($object->contact_id);
  287. unset($object->user);
  288. unset($object->fk_project);
  289. unset($object->project);
  290. unset($object->canvas);
  291. //unset($object->eatby); Filled correctly in read mode
  292. //unset($object->sellby); Filled correctly in read mode
  293. return $object;
  294. }
  295. /**
  296. * Validate fields before create or update object
  297. *
  298. * @param array|null $data Data to validate
  299. * @return array
  300. *
  301. * @throws RestException
  302. */
  303. private function _validate($data)
  304. {
  305. $stockmovement = array();
  306. foreach (self::$FIELDS as $field) {
  307. if (!isset($data[$field])) {
  308. throw new RestException(400, "$field field missing");
  309. }
  310. $stockmovement[$field] = $data[$field];
  311. }
  312. return $stockmovement;
  313. }
  314. }