api_supplier_orders.class.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. <?php
  2. /* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  3. * Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use Luracast\Restler\RestException;
  19. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
  20. /**
  21. * API class for supplier orders
  22. *
  23. * @access protected
  24. * @class DolibarrApiAccess {@requires user,external}
  25. */
  26. class SupplierOrders extends DolibarrApi
  27. {
  28. /**
  29. *
  30. * @var array $FIELDS Mandatory fields, checked when create and update object
  31. */
  32. public static $FIELDS = array(
  33. 'socid'
  34. );
  35. /**
  36. * @var CommandeFournisseur $order {@type CommandeFournisseur}
  37. */
  38. public $order;
  39. /**
  40. * Constructor
  41. */
  42. public function __construct()
  43. {
  44. global $db, $conf;
  45. $this->db = $db;
  46. $this->order = new CommandeFournisseur($this->db);
  47. }
  48. /**
  49. * Get properties of a supplier order object
  50. *
  51. * Return an array with supplier order information
  52. *
  53. * @param int $id ID of supplier order
  54. * @return array|mixed data without useless information
  55. *
  56. * @throws RestException
  57. */
  58. public function get($id)
  59. {
  60. if (!DolibarrApiAccess::$user->rights->fournisseur->commande->lire) {
  61. throw new RestException(401);
  62. }
  63. $result = $this->order->fetch($id);
  64. if (!$result) {
  65. throw new RestException(404, 'Supplier order not found');
  66. }
  67. if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
  68. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  69. }
  70. $this->order->fetchObjectLinked();
  71. return $this->_cleanObjectDatas($this->order);
  72. }
  73. /**
  74. * List orders
  75. *
  76. * Get a list of supplier orders
  77. *
  78. * @param string $sortfield Sort field
  79. * @param string $sortorder Sort order
  80. * @param int $limit Limit for list
  81. * @param int $page Page number
  82. * @param string $thirdparty_ids Thirdparty ids to filter orders of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
  83. * @param string $product_ids Product ids to filter orders of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
  84. * @param string $status Filter by order status : draft | validated | approved | running | received_start | received_end | cancelled | refused
  85. * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.datec:<:'20160101')"
  86. * @return array Array of order objects
  87. *
  88. * @throws RestException
  89. */
  90. public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $product_ids = '', $status = '', $sqlfilters = '')
  91. {
  92. global $db, $conf;
  93. if (!DolibarrApiAccess::$user->rights->fournisseur->commande->lire) {
  94. throw new RestException(401);
  95. }
  96. $obj_ret = array();
  97. // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
  98. $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
  99. // If the internal user must only see his customers, force searching by him
  100. $search_sale = 0;
  101. if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
  102. $search_sale = DolibarrApiAccess::$user->id;
  103. }
  104. $sql = "SELECT t.rowid";
  105. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  106. $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
  107. }
  108. $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as t";
  109. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  110. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
  111. }
  112. if (!empty($product_ids)) {
  113. $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; // We need this table joined to the select in order to filter by product
  114. }
  115. $sql .= ' WHERE t.entity IN ('.getEntity('supplier_order').')';
  116. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  117. $sql .= " AND t.fk_soc = sc.fk_soc";
  118. }
  119. if (!empty($product_ids)) {
  120. $sql .= " AND cd.fk_commande = t.rowid AND cd.fk_product IN (".$this->db->sanitize($product_ids).")";
  121. }
  122. if ($socids) {
  123. $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
  124. }
  125. if ($search_sale > 0) {
  126. $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
  127. }
  128. // Filter by status
  129. if ($status == 'draft') {
  130. $sql .= " AND t.fk_statut IN (0)";
  131. }
  132. if ($status == 'validated') {
  133. $sql .= " AND t.fk_statut IN (1)";
  134. }
  135. if ($status == 'approved') {
  136. $sql .= " AND t.fk_statut IN (2)";
  137. }
  138. if ($status == 'running') {
  139. $sql .= " AND t.fk_statut IN (3)";
  140. }
  141. if ($status == 'received_start') {
  142. $sql .= " AND t.fk_statut IN (4)";
  143. }
  144. if ($status == 'received_end') {
  145. $sql .= " AND t.fk_statut IN (5)";
  146. }
  147. if ($status == 'cancelled') {
  148. $sql .= " AND t.fk_statut IN (6,7)";
  149. }
  150. if ($status == 'refused') {
  151. $sql .= " AND t.fk_statut IN (9)";
  152. }
  153. // Insert sale filter
  154. if ($search_sale > 0) {
  155. $sql .= " AND sc.fk_user = ".((int) $search_sale);
  156. }
  157. // Add sql filters
  158. if ($sqlfilters) {
  159. $errormessage = '';
  160. if (!DolibarrApi::_checkFilters($sqlfilters, $errormessage)) {
  161. throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
  162. }
  163. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  164. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
  165. }
  166. $sql .= $this->db->order($sortfield, $sortorder);
  167. if ($limit) {
  168. if ($page < 0) {
  169. $page = 0;
  170. }
  171. $offset = $limit * $page;
  172. $sql .= $this->db->plimit($limit + 1, $offset);
  173. }
  174. $result = $this->db->query($sql);
  175. if ($result) {
  176. $i = 0;
  177. $num = $this->db->num_rows($result);
  178. $min = min($num, ($limit <= 0 ? $num : $limit));
  179. while ($i < $min) {
  180. $obj = $this->db->fetch_object($result);
  181. $order_static = new CommandeFournisseur($this->db);
  182. if ($order_static->fetch($obj->rowid)) {
  183. $obj_ret[] = $this->_cleanObjectDatas($order_static);
  184. }
  185. $i++;
  186. }
  187. } else {
  188. throw new RestException(503, 'Error when retrieve supplier order list : '.$this->db->lasterror());
  189. }
  190. if (!count($obj_ret)) {
  191. throw new RestException(404, 'No supplier order found');
  192. }
  193. return $obj_ret;
  194. }
  195. /**
  196. * Create supplier order object
  197. *
  198. * Example: {"ref": "auto", "ref_supplier": "1234", "socid": "1", "multicurrency_code": "SEK", "multicurrency_tx": 1, "tva_tx": 25, "note": "Imported via the REST API"}
  199. *
  200. * @param array $request_data Request datas
  201. * @return int ID of supplier order
  202. */
  203. public function post($request_data = null)
  204. {
  205. if (empty(DolibarrApiAccess::$user->rights->fournisseur->commande->creer) && empty(DolibarrApiAccess::$user->rights->supplier_order->creer)) {
  206. throw new RestException(401, "Insuffisant rights");
  207. }
  208. // Check mandatory fields
  209. $result = $this->_validate($request_data);
  210. foreach ($request_data as $field => $value) {
  211. $this->order->$field = $value;
  212. }
  213. if (!array_keys($request_data, 'date')) {
  214. $this->order->date = dol_now();
  215. }
  216. /* We keep lines as an array
  217. if (isset($request_data["lines"])) {
  218. $lines = array();
  219. foreach ($request_data["lines"] as $line) {
  220. array_push($lines, (object) $line);
  221. }
  222. $this->order->lines = $lines;
  223. }*/
  224. if ($this->order->create(DolibarrApiAccess::$user) < 0) {
  225. throw new RestException(500, "Error creating order", array_merge(array($this->order->error), $this->order->errors));
  226. }
  227. return $this->order->id;
  228. }
  229. /**
  230. * Update supplier order
  231. *
  232. * @param int $id Id of supplier order to update
  233. * @param array $request_data Datas
  234. * @return int
  235. */
  236. public function put($id, $request_data = null)
  237. {
  238. if (empty(DolibarrApiAccess::$user->rights->fournisseur->commande->creer) && empty(DolibarrApiAccess::$user->rights->supplier_order->creer)) {
  239. throw new RestException(401);
  240. }
  241. $result = $this->order->fetch($id);
  242. if (!$result) {
  243. throw new RestException(404, 'Supplier order not found');
  244. }
  245. if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
  246. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  247. }
  248. foreach ($request_data as $field => $value) {
  249. if ($field == 'id') {
  250. continue;
  251. }
  252. $this->order->$field = $value;
  253. }
  254. if ($this->order->update(DolibarrApiAccess::$user)) {
  255. return $this->get($id);
  256. }
  257. return false;
  258. }
  259. /**
  260. * Delete supplier order
  261. *
  262. * @param int $id Supplier order ID
  263. * @return array Array of result
  264. */
  265. public function delete($id)
  266. {
  267. if (!DolibarrApiAccess::$user->rights->fournisseur->commande->supprimer) {
  268. throw new RestException(401);
  269. }
  270. $result = $this->order->fetch($id);
  271. if (!$result) {
  272. throw new RestException(404, 'Supplier order not found');
  273. }
  274. if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
  275. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  276. }
  277. if ($this->order->delete(DolibarrApiAccess::$user) < 0) {
  278. throw new RestException(500, 'Error when deleting order');
  279. }
  280. return array(
  281. 'success' => array(
  282. 'code' => 200,
  283. 'message' => 'Supplier order deleted'
  284. )
  285. );
  286. }
  287. /**
  288. * Validate an order
  289. *
  290. * @param int $id Order ID
  291. * @param int $idwarehouse Warehouse ID
  292. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  293. *
  294. * @url POST {id}/validate
  295. *
  296. * @return array
  297. * FIXME An error 403 is returned if the request has an empty body.
  298. * Error message: "Forbidden: Content type `text/plain` is not supported."
  299. * Workaround: send this in the body
  300. * {
  301. * "idwarehouse": 0,
  302. * "notrigger": 0
  303. * }
  304. */
  305. public function validate($id, $idwarehouse = 0, $notrigger = 0)
  306. {
  307. if (empty(DolibarrApiAccess::$user->rights->fournisseur->commande->creer) && empty(DolibarrApiAccess::$user->rights->supplier_order->creer)) {
  308. throw new RestException(401);
  309. }
  310. $result = $this->order->fetch($id);
  311. if (!$result) {
  312. throw new RestException(404, 'Order not found');
  313. }
  314. if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
  315. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  316. }
  317. $result = $this->order->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger);
  318. if ($result == 0) {
  319. throw new RestException(304, 'Error nothing done. May be object is already validated');
  320. }
  321. if ($result < 0) {
  322. throw new RestException(500, 'Error when validating Order: '.$this->order->error);
  323. }
  324. return array(
  325. 'success' => array(
  326. 'code' => 200,
  327. 'message' => 'Order validated (Ref='.$this->order->ref.')'
  328. )
  329. );
  330. }
  331. /**
  332. * Approve an order
  333. *
  334. * @param int $id Order ID
  335. * @param int $idwarehouse Warehouse ID
  336. * @param int $secondlevel 1=Does not execute triggers, 0= execute triggers
  337. *
  338. * @url POST {id}/approve
  339. *
  340. * @return array
  341. * FIXME An error 403 is returned if the request has an empty body.
  342. * Error message: "Forbidden: Content type `text/plain` is not supported."
  343. * Workaround: send this in the body
  344. * {
  345. * "idwarehouse": 0,
  346. * "secondlevel": 0
  347. * }
  348. */
  349. public function approve($id, $idwarehouse = 0, $secondlevel = 0)
  350. {
  351. if (empty(DolibarrApiAccess::$user->rights->fournisseur->commande->creer) && empty(DolibarrApiAccess::$user->rights->supplier_order->creer)) {
  352. throw new RestException(401);
  353. }
  354. $result = $this->order->fetch($id);
  355. if (!$result) {
  356. throw new RestException(404, 'Order not found');
  357. }
  358. if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
  359. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  360. }
  361. $result = $this->order->approve(DolibarrApiAccess::$user, $idwarehouse, $secondlevel);
  362. if ($result == 0) {
  363. throw new RestException(304, 'Error nothing done. May be object is already approved');
  364. }
  365. if ($result < 0) {
  366. throw new RestException(500, 'Error when approve Order: '.$this->order->error);
  367. }
  368. return array(
  369. 'success' => array(
  370. 'code' => 200,
  371. 'message' => 'Order approved (Ref='.$this->order->ref.')'
  372. )
  373. );
  374. }
  375. /**
  376. * Sends an order to the vendor
  377. *
  378. * @param int $id Order ID
  379. * @param integer $date Date (unix timestamp in sec)
  380. * @param int $method Method
  381. * @param string $comment Comment
  382. *
  383. * @url POST {id}/makeorder
  384. *
  385. * @return array
  386. * FIXME An error 403 is returned if the request has an empty body.
  387. * Error message: "Forbidden: Content type `text/plain` is not supported."
  388. * Workaround: send this in the body
  389. * {
  390. * "date": 0,
  391. * "method": 0,
  392. * "comment": ""
  393. * }
  394. */
  395. public function makeOrder($id, $date, $method, $comment = '')
  396. {
  397. if (empty(DolibarrApiAccess::$user->rights->fournisseur->commande->creer) && empty(DolibarrApiAccess::$user->rights->supplier_order->creer)) {
  398. throw new RestException(401);
  399. }
  400. $result = $this->order->fetch($id);
  401. if (!$result) {
  402. throw new RestException(404, 'Order not found');
  403. }
  404. if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
  405. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  406. }
  407. $result = $this->order->commande(DolibarrApiAccess::$user, $date, $method, $comment);
  408. if ($result == 0) {
  409. throw new RestException(304, 'Error nothing done. May be object is already sent');
  410. }
  411. if ($result < 0) {
  412. throw new RestException(500, 'Error when sending Order: '.$this->order->error);
  413. }
  414. return array(
  415. 'success' => array(
  416. 'code' => 200,
  417. 'message' => 'Order sent (Ref='.$this->order->ref.')'
  418. )
  419. );
  420. }
  421. /**
  422. * Receives the order, dispatches products.
  423. *
  424. * Example:
  425. * <code> {
  426. * "closeopenorder": 1,
  427. * "comment": "",
  428. * "lines": [{
  429. * "id": 14,
  430. * "fk_product": 112,
  431. * "qty": 18,
  432. * "warehouse": 1,
  433. * "price": 114,
  434. * "comment": "",
  435. * "eatby": 0,
  436. * "sellby": 0,
  437. * "batch": 0,
  438. * "notrigger": 0
  439. * }]
  440. * }</code>
  441. *
  442. * @param int $id Order ID
  443. * @param integer $closeopenorder Close order if everything is received {@required false}
  444. * @param string $comment Comment {@required false}
  445. * @param array $lines Array of product dispatches
  446. *
  447. * @url POST {id}/receive
  448. *
  449. * @return array
  450. * FIXME An error 403 is returned if the request has an empty body.
  451. * Error message: "Forbidden: Content type `text/plain` is not supported."
  452. *
  453. */
  454. public function receiveOrder($id, $closeopenorder, $comment, $lines)
  455. {
  456. if (empty(DolibarrApiAccess::$user->rights->fournisseur->commande->creer) && empty(DolibarrApiAccess::$user->rights->supplier_order->creer)) {
  457. throw new RestException(401);
  458. }
  459. $result = $this->order->fetch($id);
  460. if (!$result) {
  461. throw new RestException(404, 'Order not found');
  462. }
  463. if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
  464. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  465. }
  466. foreach ($lines as $line) {
  467. $lineObj =(object) $line;
  468. $result=$this->order->dispatchProduct(DolibarrApiAccess::$user,
  469. $lineObj->fk_product,
  470. $lineObj->qty,
  471. $lineObj->warehouse,
  472. $lineObj->price,
  473. $lineObj->comment,
  474. $lineObj->eatby,
  475. $lineObj->sellby,
  476. $lineObj->batch,
  477. $lineObj->id,
  478. $lineObj->notrigger);
  479. if ($result < 0) {
  480. throw new RestException(500, 'Error dispatch order line '.$line->id.': '.$this->order->error);
  481. }
  482. }
  483. $result = $this->order->calcAndSetStatusDispatch(DolibarrApiAccess::$user, $closeopenorder, $comment);
  484. if ($result == 0) {
  485. throw new RestException(304, 'Error nothing done. May be object is already dispatched');
  486. }
  487. if ($result < 0) {
  488. throw new RestException(500, 'Error when receivce order: '.$this->order->error);
  489. }
  490. return array(
  491. 'success' => array(
  492. 'code' => 200,
  493. 'message' => 'Order received (Ref='.$this->order->ref.')'
  494. )
  495. );
  496. }
  497. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  498. /**
  499. * Clean sensible object datas
  500. *
  501. * @param Object $object Object to clean
  502. * @return Object Object with cleaned properties
  503. */
  504. protected function _cleanObjectDatas($object)
  505. {
  506. // phpcs:enable
  507. $object = parent::_cleanObjectDatas($object);
  508. unset($object->rowid);
  509. unset($object->barcode_type);
  510. unset($object->barcode_type_code);
  511. unset($object->barcode_type_label);
  512. unset($object->barcode_type_coder);
  513. return $object;
  514. }
  515. /**
  516. * Validate fields before create or update object
  517. *
  518. * @param array $data Datas to validate
  519. * @return array
  520. *
  521. * @throws RestException
  522. */
  523. private function _validate($data)
  524. {
  525. $order = array();
  526. foreach (SupplierOrders::$FIELDS as $field) {
  527. if (!isset($data[$field])) {
  528. throw new RestException(400, "$field field missing");
  529. }
  530. $order[$field] = $data[$field];
  531. }
  532. return $order;
  533. }
  534. }