api_supplier_orders.class.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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. $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
  161. if ($errormessage) {
  162. throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
  163. }
  164. }
  165. $sql .= $this->db->order($sortfield, $sortorder);
  166. if ($limit) {
  167. if ($page < 0) {
  168. $page = 0;
  169. }
  170. $offset = $limit * $page;
  171. $sql .= $this->db->plimit($limit + 1, $offset);
  172. }
  173. $result = $this->db->query($sql);
  174. if ($result) {
  175. $i = 0;
  176. $num = $this->db->num_rows($result);
  177. $min = min($num, ($limit <= 0 ? $num : $limit));
  178. while ($i < $min) {
  179. $obj = $this->db->fetch_object($result);
  180. $order_static = new CommandeFournisseur($this->db);
  181. if ($order_static->fetch($obj->rowid)) {
  182. $obj_ret[] = $this->_cleanObjectDatas($order_static);
  183. }
  184. $i++;
  185. }
  186. } else {
  187. throw new RestException(503, 'Error when retrieve supplier order list : '.$this->db->lasterror());
  188. }
  189. if (!count($obj_ret)) {
  190. throw new RestException(404, 'No supplier order found');
  191. }
  192. return $obj_ret;
  193. }
  194. /**
  195. * Create supplier order object
  196. *
  197. * Example: {"ref": "auto", "ref_supplier": "1234", "socid": "1", "multicurrency_code": "SEK", "multicurrency_tx": 1, "tva_tx": 25, "note": "Imported via the REST API"}
  198. *
  199. * @param array $request_data Request datas
  200. * @return int ID of supplier order
  201. */
  202. public function post($request_data = null)
  203. {
  204. if (empty(DolibarrApiAccess::$user->rights->fournisseur->commande->creer) && empty(DolibarrApiAccess::$user->rights->supplier_order->creer)) {
  205. throw new RestException(401, "Insuffisant rights");
  206. }
  207. // Check mandatory fields
  208. $result = $this->_validate($request_data);
  209. foreach ($request_data as $field => $value) {
  210. $this->order->$field = $value;
  211. }
  212. if (!array_keys($request_data, 'date')) {
  213. $this->order->date = dol_now();
  214. }
  215. /* We keep lines as an array
  216. if (isset($request_data["lines"])) {
  217. $lines = array();
  218. foreach ($request_data["lines"] as $line) {
  219. array_push($lines, (object) $line);
  220. }
  221. $this->order->lines = $lines;
  222. }*/
  223. if ($this->order->create(DolibarrApiAccess::$user) < 0) {
  224. throw new RestException(500, "Error creating order", array_merge(array($this->order->error), $this->order->errors));
  225. }
  226. return $this->order->id;
  227. }
  228. /**
  229. * Update supplier order
  230. *
  231. * @param int $id Id of supplier order to update
  232. * @param array $request_data Datas
  233. * @return int
  234. */
  235. public function put($id, $request_data = null)
  236. {
  237. if (empty(DolibarrApiAccess::$user->rights->fournisseur->commande->creer) && empty(DolibarrApiAccess::$user->rights->supplier_order->creer)) {
  238. throw new RestException(401);
  239. }
  240. $result = $this->order->fetch($id);
  241. if (!$result) {
  242. throw new RestException(404, 'Supplier order not found');
  243. }
  244. if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
  245. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  246. }
  247. foreach ($request_data as $field => $value) {
  248. if ($field == 'id') {
  249. continue;
  250. }
  251. $this->order->$field = $value;
  252. }
  253. if ($this->order->update(DolibarrApiAccess::$user)) {
  254. return $this->get($id);
  255. }
  256. return false;
  257. }
  258. /**
  259. * Delete supplier order
  260. *
  261. * @param int $id Supplier order ID
  262. * @return array Array of result
  263. */
  264. public function delete($id)
  265. {
  266. if (!DolibarrApiAccess::$user->rights->fournisseur->commande->supprimer) {
  267. throw new RestException(401);
  268. }
  269. $result = $this->order->fetch($id);
  270. if (!$result) {
  271. throw new RestException(404, 'Supplier order not found');
  272. }
  273. if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
  274. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  275. }
  276. if ($this->order->delete(DolibarrApiAccess::$user) < 0) {
  277. throw new RestException(500, 'Error when deleting order');
  278. }
  279. return array(
  280. 'success' => array(
  281. 'code' => 200,
  282. 'message' => 'Supplier order deleted'
  283. )
  284. );
  285. }
  286. /**
  287. * Validate an order
  288. *
  289. * @param int $id Order ID
  290. * @param int $idwarehouse Warehouse ID
  291. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  292. *
  293. * @url POST {id}/validate
  294. *
  295. * @return array
  296. * FIXME An error 403 is returned if the request has an empty body.
  297. * Error message: "Forbidden: Content type `text/plain` is not supported."
  298. * Workaround: send this in the body
  299. * {
  300. * "idwarehouse": 0,
  301. * "notrigger": 0
  302. * }
  303. */
  304. public function validate($id, $idwarehouse = 0, $notrigger = 0)
  305. {
  306. if (empty(DolibarrApiAccess::$user->rights->fournisseur->commande->creer) && empty(DolibarrApiAccess::$user->rights->supplier_order->creer)) {
  307. throw new RestException(401);
  308. }
  309. $result = $this->order->fetch($id);
  310. if (!$result) {
  311. throw new RestException(404, 'Order not found');
  312. }
  313. if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
  314. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  315. }
  316. $result = $this->order->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger);
  317. if ($result == 0) {
  318. throw new RestException(304, 'Error nothing done. May be object is already validated');
  319. }
  320. if ($result < 0) {
  321. throw new RestException(500, 'Error when validating Order: '.$this->order->error);
  322. }
  323. return array(
  324. 'success' => array(
  325. 'code' => 200,
  326. 'message' => 'Order validated (Ref='.$this->order->ref.')'
  327. )
  328. );
  329. }
  330. /**
  331. * Approve an order
  332. *
  333. * @param int $id Order ID
  334. * @param int $idwarehouse Warehouse ID
  335. * @param int $secondlevel 1=Does not execute triggers, 0= execute triggers
  336. *
  337. * @url POST {id}/approve
  338. *
  339. * @return array
  340. * FIXME An error 403 is returned if the request has an empty body.
  341. * Error message: "Forbidden: Content type `text/plain` is not supported."
  342. * Workaround: send this in the body
  343. * {
  344. * "idwarehouse": 0,
  345. * "secondlevel": 0
  346. * }
  347. */
  348. public function approve($id, $idwarehouse = 0, $secondlevel = 0)
  349. {
  350. if (empty(DolibarrApiAccess::$user->rights->fournisseur->commande->creer) && empty(DolibarrApiAccess::$user->rights->supplier_order->creer)) {
  351. throw new RestException(401);
  352. }
  353. $result = $this->order->fetch($id);
  354. if (!$result) {
  355. throw new RestException(404, 'Order not found');
  356. }
  357. if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
  358. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  359. }
  360. $result = $this->order->approve(DolibarrApiAccess::$user, $idwarehouse, $secondlevel);
  361. if ($result == 0) {
  362. throw new RestException(304, 'Error nothing done. May be object is already approved');
  363. }
  364. if ($result < 0) {
  365. throw new RestException(500, 'Error when approve Order: '.$this->order->error);
  366. }
  367. return array(
  368. 'success' => array(
  369. 'code' => 200,
  370. 'message' => 'Order approved (Ref='.$this->order->ref.')'
  371. )
  372. );
  373. }
  374. /**
  375. * Sends an order to the vendor
  376. *
  377. * @param int $id Order ID
  378. * @param integer $date Date (unix timestamp in sec)
  379. * @param int $method Method
  380. * @param string $comment Comment
  381. *
  382. * @url POST {id}/makeorder
  383. *
  384. * @return array
  385. * FIXME An error 403 is returned if the request has an empty body.
  386. * Error message: "Forbidden: Content type `text/plain` is not supported."
  387. * Workaround: send this in the body
  388. * {
  389. * "date": 0,
  390. * "method": 0,
  391. * "comment": ""
  392. * }
  393. */
  394. public function makeOrder($id, $date, $method, $comment = '')
  395. {
  396. if (empty(DolibarrApiAccess::$user->rights->fournisseur->commande->creer) && empty(DolibarrApiAccess::$user->rights->supplier_order->creer)) {
  397. throw new RestException(401);
  398. }
  399. $result = $this->order->fetch($id);
  400. if (!$result) {
  401. throw new RestException(404, 'Order not found');
  402. }
  403. if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
  404. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  405. }
  406. $result = $this->order->commande(DolibarrApiAccess::$user, $date, $method, $comment);
  407. if ($result == 0) {
  408. throw new RestException(304, 'Error nothing done. May be object is already sent');
  409. }
  410. if ($result < 0) {
  411. throw new RestException(500, 'Error when sending Order: '.$this->order->error);
  412. }
  413. return array(
  414. 'success' => array(
  415. 'code' => 200,
  416. 'message' => 'Order sent (Ref='.$this->order->ref.')'
  417. )
  418. );
  419. }
  420. /**
  421. * Receives the order, dispatches products.
  422. *
  423. * Example:
  424. * <code> {
  425. * "closeopenorder": 1,
  426. * "comment": "",
  427. * "lines": [{
  428. * "id": 14,
  429. * "fk_product": 112,
  430. * "qty": 18,
  431. * "warehouse": 1,
  432. * "price": 114,
  433. * "comment": "",
  434. * "eatby": 0,
  435. * "sellby": 0,
  436. * "batch": 0,
  437. * "notrigger": 0
  438. * }]
  439. * }</code>
  440. *
  441. * @param int $id Order ID
  442. * @param integer $closeopenorder Close order if everything is received {@required false}
  443. * @param string $comment Comment {@required false}
  444. * @param array $lines Array of product dispatches
  445. *
  446. * @url POST {id}/receive
  447. *
  448. * @return array
  449. * FIXME An error 403 is returned if the request has an empty body.
  450. * Error message: "Forbidden: Content type `text/plain` is not supported."
  451. *
  452. */
  453. public function receiveOrder($id, $closeopenorder, $comment, $lines)
  454. {
  455. if (empty(DolibarrApiAccess::$user->rights->fournisseur->commande->creer) && empty(DolibarrApiAccess::$user->rights->supplier_order->creer)) {
  456. throw new RestException(401);
  457. }
  458. $result = $this->order->fetch($id);
  459. if (!$result) {
  460. throw new RestException(404, 'Order not found');
  461. }
  462. if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->order->id, 'commande_fournisseur', 'commande')) {
  463. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  464. }
  465. foreach ($lines as $line) {
  466. $lineObj =(object) $line;
  467. $result=$this->order->dispatchProduct(DolibarrApiAccess::$user,
  468. $lineObj->fk_product,
  469. $lineObj->qty,
  470. $lineObj->warehouse,
  471. $lineObj->price,
  472. $lineObj->comment,
  473. $lineObj->eatby,
  474. $lineObj->sellby,
  475. $lineObj->batch,
  476. $lineObj->id,
  477. $lineObj->notrigger);
  478. if ($result < 0) {
  479. throw new RestException(500, 'Error dispatch order line '.$line->id.': '.$this->order->error);
  480. }
  481. }
  482. $result = $this->order->calcAndSetStatusDispatch(DolibarrApiAccess::$user, $closeopenorder, $comment);
  483. if ($result == 0) {
  484. throw new RestException(304, 'Error nothing done. May be object is already dispatched');
  485. }
  486. if ($result < 0) {
  487. throw new RestException(500, 'Error when receivce order: '.$this->order->error);
  488. }
  489. return array(
  490. 'success' => array(
  491. 'code' => 200,
  492. 'message' => 'Order received (Ref='.$this->order->ref.')'
  493. )
  494. );
  495. }
  496. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  497. /**
  498. * Clean sensible object datas
  499. *
  500. * @param Object $object Object to clean
  501. * @return Object Object with cleaned properties
  502. */
  503. protected function _cleanObjectDatas($object)
  504. {
  505. // phpcs:enable
  506. $object = parent::_cleanObjectDatas($object);
  507. unset($object->rowid);
  508. unset($object->barcode_type);
  509. unset($object->barcode_type_code);
  510. unset($object->barcode_type_label);
  511. unset($object->barcode_type_coder);
  512. return $object;
  513. }
  514. /**
  515. * Validate fields before create or update object
  516. *
  517. * @param array $data Datas to validate
  518. * @return array
  519. *
  520. * @throws RestException
  521. */
  522. private function _validate($data)
  523. {
  524. $order = array();
  525. foreach (SupplierOrders::$FIELDS as $field) {
  526. if (!isset($data[$field])) {
  527. throw new RestException(400, "$field field missing");
  528. }
  529. $order[$field] = $data[$field];
  530. }
  531. return $order;
  532. }
  533. }