api_orders.class.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  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.'/commande/class/commande.class.php';
  20. /**
  21. * API class for orders
  22. *
  23. * @access protected
  24. * @class DolibarrApiAccess {@requires user,external}
  25. */
  26. class Orders extends DolibarrApi
  27. {
  28. /**
  29. * @var array $FIELDS Mandatory fields, checked when create and update object
  30. */
  31. public static $FIELDS = array(
  32. 'socid',
  33. 'date'
  34. );
  35. /**
  36. * @var Commande $commande {@type Commande}
  37. */
  38. public $commande;
  39. /**
  40. * Constructor
  41. */
  42. public function __construct()
  43. {
  44. global $db, $conf;
  45. $this->db = $db;
  46. $this->commande = new Commande($this->db);
  47. }
  48. /**
  49. * Get properties of an order object by id
  50. *
  51. * Return an array with order informations
  52. *
  53. * @param int $id ID of order
  54. * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id
  55. * @return array|mixed data without useless information
  56. *
  57. * @throws RestException
  58. */
  59. public function get($id, $contact_list = 1)
  60. {
  61. return $this->_fetch($id, '', '', $contact_list);
  62. }
  63. /**
  64. * Get properties of an order object by ref
  65. *
  66. * Return an array with order informations
  67. *
  68. * @param string $ref Ref of object
  69. * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id
  70. * @return array|mixed data without useless information
  71. *
  72. * @url GET ref/{ref}
  73. *
  74. * @throws RestException
  75. */
  76. public function getByRef($ref, $contact_list = 1)
  77. {
  78. return $this->_fetch('', $ref, '', $contact_list);
  79. }
  80. /**
  81. * Get properties of an order object by ref_ext
  82. *
  83. * Return an array with order informations
  84. *
  85. * @param string $ref_ext External reference of object
  86. * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id
  87. * @return array|mixed data without useless information
  88. *
  89. * @url GET ref_ext/{ref_ext}
  90. *
  91. * @throws RestException
  92. */
  93. public function getByRefExt($ref_ext, $contact_list = 1)
  94. {
  95. return $this->_fetch('', '', $ref_ext, $contact_list);
  96. }
  97. /**
  98. * Get properties of an order object
  99. *
  100. * Return an array with order informations
  101. *
  102. * @param int $id ID of order
  103. * @param string $ref Ref of object
  104. * @param string $ref_ext External reference of object
  105. * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id
  106. * @return Object Object with cleaned properties
  107. *
  108. * @throws RestException
  109. */
  110. private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1)
  111. {
  112. if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
  113. throw new RestException(401);
  114. }
  115. $result = $this->commande->fetch($id, $ref, $ref_ext);
  116. if (!$result) {
  117. throw new RestException(404, 'Order not found');
  118. }
  119. if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
  120. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  121. }
  122. // Add external contacts ids
  123. $tmparray = $this->commande->liste_contact(-1, 'external', $contact_list);
  124. if (is_array($tmparray)) {
  125. $this->commande->contacts_ids = $tmparray;
  126. }
  127. $this->commande->fetchObjectLinked();
  128. // Add online_payment_url, cf #20477
  129. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  130. $this->commande->online_payment_url = getOnlinePaymentUrl(0, 'order', $this->commande->ref);
  131. return $this->_cleanObjectDatas($this->commande);
  132. }
  133. /**
  134. * List orders
  135. *
  136. * Get a list of orders
  137. *
  138. * @param string $sortfield Sort field
  139. * @param string $sortorder Sort order
  140. * @param int $limit Limit for list
  141. * @param int $page Page number
  142. * @param string $thirdparty_ids Thirdparty ids to filter orders of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
  143. * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  144. * @param string $sqlfilterlines Other criteria to filter answers separated by a comma. Syntax example "(tl.fk_product:=:'17') and (tl.price:<:'250')"
  145. * @param string $properties Restrict the data returned to theses properties. Ignored if empty. Comma separated list of properties names
  146. * @return array Array of order objects
  147. *
  148. * @throws RestException 404 Not found
  149. * @throws RestException 503 Error
  150. */
  151. public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '', $sqlfilterlines = '', $properties = '')
  152. {
  153. if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
  154. throw new RestException(401);
  155. }
  156. $obj_ret = array();
  157. // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
  158. $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
  159. // If the internal user must only see his customers, force searching by him
  160. $search_sale = 0;
  161. if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
  162. $search_sale = DolibarrApiAccess::$user->id;
  163. }
  164. $sql = "SELECT t.rowid";
  165. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  166. $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)
  167. }
  168. $sql .= " FROM ".MAIN_DB_PREFIX."commande AS t LEFT JOIN ".MAIN_DB_PREFIX."commande_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
  169. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  170. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
  171. }
  172. $sql .= ' WHERE t.entity IN ('.getEntity('commande').')';
  173. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  174. $sql .= " AND t.fk_soc = sc.fk_soc";
  175. }
  176. if ($socids) {
  177. $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
  178. }
  179. if ($search_sale > 0) {
  180. $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
  181. }
  182. // Insert sale filter
  183. if ($search_sale > 0) {
  184. $sql .= " AND sc.fk_user = ".((int) $search_sale);
  185. }
  186. // Add sql filters
  187. if ($sqlfilters) {
  188. $errormessage = '';
  189. $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
  190. if ($errormessage) {
  191. throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
  192. }
  193. }
  194. // Add sql filters for lines
  195. if ($sqlfilterlines) {
  196. $errormessage = '';
  197. $sql .= " AND EXISTS (SELECT tl.rowid FROM ".MAIN_DB_PREFIX."commandedet AS tl WHERE tl.fk_commande = t.rowid";
  198. $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilterlines, $errormessage);
  199. $sql .= ")";
  200. if ($errormessage) {
  201. throw new RestException(400, 'Error when validating parameter sqlfilterlines -> '.$errormessage);
  202. }
  203. }
  204. $sql .= $this->db->order($sortfield, $sortorder);
  205. if ($limit) {
  206. if ($page < 0) {
  207. $page = 0;
  208. }
  209. $offset = $limit * $page;
  210. $sql .= $this->db->plimit($limit + 1, $offset);
  211. }
  212. dol_syslog("API Rest request");
  213. $result = $this->db->query($sql);
  214. if ($result) {
  215. $num = $this->db->num_rows($result);
  216. $min = min($num, ($limit <= 0 ? $num : $limit));
  217. $i = 0;
  218. while ($i < $min) {
  219. $obj = $this->db->fetch_object($result);
  220. $commande_static = new Commande($this->db);
  221. if ($commande_static->fetch($obj->rowid)) {
  222. // Add external contacts ids
  223. $tmparray = $commande_static->liste_contact(-1, 'external', 1);
  224. if (is_array($tmparray)) {
  225. $commande_static->contacts_ids = $tmparray;
  226. }
  227. // Add online_payment_url, cf #20477
  228. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  229. $commande_static->online_payment_url = getOnlinePaymentUrl(0, 'order', $commande_static->ref);
  230. $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($commande_static), $properties);
  231. }
  232. $i++;
  233. }
  234. } else {
  235. throw new RestException(503, 'Error when retrieve commande list : '.$this->db->lasterror());
  236. }
  237. if (!count($obj_ret)) {
  238. throw new RestException(404, 'No order found');
  239. }
  240. return $obj_ret;
  241. }
  242. /**
  243. * Create a sale order
  244. *
  245. * Exemple: { "socid": 2, "date": 1595196000, "type": 0, "lines": [{ "fk_product": 2, "qty": 1 }] }
  246. *
  247. * @param array $request_data Request data
  248. * @return int ID of order
  249. */
  250. public function post($request_data = null)
  251. {
  252. if (!DolibarrApiAccess::$user->rights->commande->creer) {
  253. throw new RestException(401, "Insuffisant rights");
  254. }
  255. // Check mandatory fields
  256. $result = $this->_validate($request_data);
  257. foreach ($request_data as $field => $value) {
  258. $this->commande->$field = $value;
  259. }
  260. /*if (isset($request_data["lines"])) {
  261. $lines = array();
  262. foreach ($request_data["lines"] as $line) {
  263. array_push($lines, (object) $line);
  264. }
  265. $this->commande->lines = $lines;
  266. }*/
  267. if ($this->commande->create(DolibarrApiAccess::$user) < 0) {
  268. throw new RestException(500, "Error creating order", array_merge(array($this->commande->error), $this->commande->errors));
  269. }
  270. return $this->commande->id;
  271. }
  272. /**
  273. * Get lines of an order
  274. *
  275. * @param int $id Id of order
  276. *
  277. * @url GET {id}/lines
  278. *
  279. * @return array
  280. */
  281. public function getLines($id)
  282. {
  283. if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
  284. throw new RestException(401);
  285. }
  286. $result = $this->commande->fetch($id);
  287. if (!$result) {
  288. throw new RestException(404, 'Order not found');
  289. }
  290. if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
  291. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  292. }
  293. $this->commande->getLinesArray();
  294. $result = array();
  295. foreach ($this->commande->lines as $line) {
  296. array_push($result, $this->_cleanObjectDatas($line));
  297. }
  298. return $result;
  299. }
  300. /**
  301. * Add a line to given order
  302. *
  303. * @param int $id Id of order to update
  304. * @param array $request_data OrderLine data
  305. *
  306. * @url POST {id}/lines
  307. *
  308. * @return int
  309. */
  310. public function postLine($id, $request_data = null)
  311. {
  312. if (!DolibarrApiAccess::$user->rights->commande->creer) {
  313. throw new RestException(401);
  314. }
  315. $result = $this->commande->fetch($id);
  316. if (!$result) {
  317. throw new RestException(404, 'Order not found');
  318. }
  319. if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
  320. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  321. }
  322. $request_data = (object) $request_data;
  323. $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
  324. $request_data->label = sanitizeVal($request_data->label);
  325. $updateRes = $this->commande->addline(
  326. $request_data->desc,
  327. $request_data->subprice,
  328. $request_data->qty,
  329. $request_data->tva_tx,
  330. $request_data->localtax1_tx,
  331. $request_data->localtax2_tx,
  332. $request_data->fk_product,
  333. $request_data->remise_percent,
  334. $request_data->info_bits,
  335. $request_data->fk_remise_except,
  336. $request_data->price_base_type ? $request_data->price_base_type : 'HT',
  337. $request_data->subprice,
  338. $request_data->date_start,
  339. $request_data->date_end,
  340. $request_data->product_type,
  341. $request_data->rang,
  342. $request_data->special_code,
  343. $request_data->fk_parent_line,
  344. $request_data->fk_fournprice,
  345. $request_data->pa_ht,
  346. $request_data->label,
  347. $request_data->array_options,
  348. $request_data->fk_unit,
  349. $request_data->origin,
  350. $request_data->origin_id,
  351. $request_data->multicurrency_subprice,
  352. $request_data->ref_ext
  353. );
  354. if ($updateRes > 0) {
  355. return $updateRes;
  356. } else {
  357. throw new RestException(400, $this->commande->error);
  358. }
  359. }
  360. /**
  361. * Update a line to given order
  362. *
  363. * @param int $id Id of order to update
  364. * @param int $lineid Id of line to update
  365. * @param array $request_data OrderLine data
  366. * @return Object|false Object with cleaned properties
  367. *
  368. * @url PUT {id}/lines/{lineid}
  369. */
  370. public function putLine($id, $lineid, $request_data = null)
  371. {
  372. if (!DolibarrApiAccess::$user->rights->commande->creer) {
  373. throw new RestException(401);
  374. }
  375. $result = $this->commande->fetch($id);
  376. if (!$result) {
  377. throw new RestException(404, 'Order not found');
  378. }
  379. if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
  380. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  381. }
  382. $request_data = (object) $request_data;
  383. $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
  384. $request_data->label = sanitizeVal($request_data->label);
  385. $updateRes = $this->commande->updateline(
  386. $lineid,
  387. $request_data->desc,
  388. $request_data->subprice,
  389. $request_data->qty,
  390. $request_data->remise_percent,
  391. $request_data->tva_tx,
  392. $request_data->localtax1_tx,
  393. $request_data->localtax2_tx,
  394. $request_data->price_base_type ? $request_data->price_base_type : 'HT',
  395. $request_data->info_bits,
  396. $request_data->date_start,
  397. $request_data->date_end,
  398. $request_data->product_type,
  399. $request_data->fk_parent_line,
  400. 0,
  401. $request_data->fk_fournprice,
  402. $request_data->pa_ht,
  403. $request_data->label,
  404. $request_data->special_code,
  405. $request_data->array_options,
  406. $request_data->fk_unit,
  407. $request_data->multicurrency_subprice,
  408. 0,
  409. $request_data->ref_ext,
  410. $request_data->rang
  411. );
  412. if ($updateRes > 0) {
  413. $result = $this->get($id);
  414. unset($result->line);
  415. return $this->_cleanObjectDatas($result);
  416. }
  417. return false;
  418. }
  419. /**
  420. * Delete a line of a given order
  421. *
  422. * @param int $id Id of order to update
  423. * @param int $lineid Id of line to delete
  424. * @return Object Object with cleaned properties
  425. *
  426. * @url DELETE {id}/lines/{lineid}
  427. *
  428. * @throws RestException 401
  429. * @throws RestException 404
  430. */
  431. public function deleteLine($id, $lineid)
  432. {
  433. if (!DolibarrApiAccess::$user->rights->commande->creer) {
  434. throw new RestException(401);
  435. }
  436. $result = $this->commande->fetch($id);
  437. if (!$result) {
  438. throw new RestException(404, 'Order not found');
  439. }
  440. if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
  441. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  442. }
  443. $updateRes = $this->commande->deleteline(DolibarrApiAccess::$user, $lineid, $id);
  444. if ($updateRes > 0) {
  445. return $this->get($id);
  446. } else {
  447. throw new RestException(405, $this->commande->error);
  448. }
  449. }
  450. /**
  451. * Get contacts of given order
  452. *
  453. * Return an array with contact informations
  454. *
  455. * @param int $id ID of order
  456. * @param string $type Type of the contact (BILLING, SHIPPING, CUSTOMER)
  457. * @return Object Object with cleaned properties
  458. *
  459. * @url GET {id}/contacts
  460. *
  461. * @throws RestException
  462. */
  463. public function getContacts($id, $type = '')
  464. {
  465. if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
  466. throw new RestException(401);
  467. }
  468. $result = $this->commande->fetch($id);
  469. if (!$result) {
  470. throw new RestException(404, 'Order not found');
  471. }
  472. if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
  473. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  474. }
  475. $contacts = $this->commande->liste_contact(-1, 'external', 0, $type);
  476. return $this->_cleanObjectDatas($contacts);
  477. }
  478. /**
  479. * Add a contact type of given order
  480. *
  481. * @param int $id Id of order to update
  482. * @param int $contactid Id of contact to add
  483. * @param string $type Type of the contact (BILLING, SHIPPING, CUSTOMER)
  484. * @return array
  485. *
  486. * @url POST {id}/contact/{contactid}/{type}
  487. *
  488. * @throws RestException 401
  489. * @throws RestException 404
  490. */
  491. public function postContact($id, $contactid, $type)
  492. {
  493. if (!DolibarrApiAccess::$user->rights->commande->creer) {
  494. throw new RestException(401);
  495. }
  496. $result = $this->commande->fetch($id);
  497. if (!$result) {
  498. throw new RestException(404, 'Order not found');
  499. }
  500. if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
  501. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  502. }
  503. $result = $this->commande->add_contact($contactid, $type, 'external');
  504. if ($result < 0) {
  505. throw new RestException(500, 'Error when added the contact');
  506. }
  507. if ($result == 0) {
  508. throw new RestException(304, 'contact already added');
  509. }
  510. return array(
  511. 'success' => array(
  512. 'code' => 200,
  513. 'message' => 'Contact linked to the order'
  514. )
  515. );
  516. }
  517. /**
  518. * Unlink a contact type of given order
  519. *
  520. * @param int $id Id of order to update
  521. * @param int $contactid Id of contact
  522. * @param string $type Type of the contact (BILLING, SHIPPING, CUSTOMER).
  523. *
  524. * @url DELETE {id}/contact/{contactid}/{type}
  525. *
  526. * @return array
  527. *
  528. * @throws RestException 401
  529. * @throws RestException 404
  530. * @throws RestException 500 System error
  531. */
  532. public function deleteContact($id, $contactid, $type)
  533. {
  534. if (!DolibarrApiAccess::$user->rights->commande->creer) {
  535. throw new RestException(401);
  536. }
  537. $result = $this->commande->fetch($id);
  538. if (!$result) {
  539. throw new RestException(404, 'Order not found');
  540. }
  541. if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
  542. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  543. }
  544. $contacts = $this->commande->liste_contact();
  545. foreach ($contacts as $contact) {
  546. if ($contact['id'] == $contactid && $contact['code'] == $type) {
  547. $result = $this->commande->delete_contact($contact['rowid']);
  548. if (!$result) {
  549. throw new RestException(500, 'Error when deleted the contact');
  550. }
  551. }
  552. }
  553. return array(
  554. 'success' => array(
  555. 'code' => 200,
  556. 'message' => 'Contact unlinked from order'
  557. )
  558. );
  559. }
  560. /**
  561. * Update order general fields (won't touch lines of order)
  562. *
  563. * @param int $id Id of order to update
  564. * @param array $request_data Datas
  565. * @return Object Object with cleaned properties
  566. */
  567. public function put($id, $request_data = null)
  568. {
  569. if (!DolibarrApiAccess::$user->rights->commande->creer) {
  570. throw new RestException(401);
  571. }
  572. $result = $this->commande->fetch($id);
  573. if (!$result) {
  574. throw new RestException(404, 'Order not found');
  575. }
  576. if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
  577. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  578. }
  579. foreach ($request_data as $field => $value) {
  580. if ($field == 'id') {
  581. continue;
  582. }
  583. $this->commande->$field = $value;
  584. }
  585. // Update availability
  586. if (!empty($this->commande->availability_id)) {
  587. if ($this->commande->availability($this->commande->availability_id) < 0) {
  588. throw new RestException(400, 'Error while updating availability');
  589. }
  590. }
  591. if ($this->commande->update(DolibarrApiAccess::$user) > 0) {
  592. return $this->get($id);
  593. } else {
  594. throw new RestException(500, $this->commande->error);
  595. }
  596. }
  597. /**
  598. * Delete order
  599. *
  600. * @param int $id Order ID
  601. * @return array
  602. */
  603. public function delete($id)
  604. {
  605. if (!DolibarrApiAccess::$user->rights->commande->supprimer) {
  606. throw new RestException(401);
  607. }
  608. $result = $this->commande->fetch($id);
  609. if (!$result) {
  610. throw new RestException(404, 'Order not found');
  611. }
  612. if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
  613. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  614. }
  615. if (!$this->commande->delete(DolibarrApiAccess::$user)) {
  616. throw new RestException(500, 'Error when deleting order : '.$this->commande->error);
  617. }
  618. return array(
  619. 'success' => array(
  620. 'code' => 200,
  621. 'message' => 'Order deleted'
  622. )
  623. );
  624. }
  625. /**
  626. * Validate an order
  627. *
  628. * If you get a bad value for param notrigger check, provide this in body
  629. * {
  630. * "idwarehouse": 0,
  631. * "notrigger": 0
  632. * }
  633. *
  634. * @param int $id Order ID
  635. * @param int $idwarehouse Warehouse ID
  636. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  637. * @return Object Object with cleaned properties
  638. *
  639. * @url POST {id}/validate
  640. *
  641. * @throws RestException 304
  642. * @throws RestException 401
  643. * @throws RestException 404
  644. * @throws RestException 500 System error
  645. *
  646. */
  647. public function validate($id, $idwarehouse = 0, $notrigger = 0)
  648. {
  649. if (!DolibarrApiAccess::$user->rights->commande->creer) {
  650. throw new RestException(401);
  651. }
  652. $result = $this->commande->fetch($id);
  653. if (!$result) {
  654. throw new RestException(404, 'Order not found');
  655. }
  656. $result = $this->commande->fetch_thirdparty(); // do not check result, as failure is not fatal (used only for mail notification substitutes)
  657. if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
  658. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  659. }
  660. $result = $this->commande->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger);
  661. if ($result == 0) {
  662. throw new RestException(304, 'Error nothing done. May be object is already validated');
  663. }
  664. if ($result < 0) {
  665. throw new RestException(500, 'Error when validating Order: '.$this->commande->error);
  666. }
  667. $result = $this->commande->fetch($id);
  668. $this->commande->fetchObjectLinked();
  669. //fix #20477 : add online_payment_url
  670. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  671. $this->commande->online_payment_url = getOnlinePaymentUrl(0, 'order', $this->commande->ref);
  672. return $this->_cleanObjectDatas($this->commande);
  673. }
  674. /**
  675. * Tag the order as validated (opened)
  676. *
  677. * Function used when order is reopend after being closed.
  678. *
  679. * @param int $id Id of the order
  680. *
  681. * @url POST {id}/reopen
  682. *
  683. * @return int
  684. *
  685. * @throws RestException 304
  686. * @throws RestException 400
  687. * @throws RestException 401
  688. * @throws RestException 404
  689. * @throws RestException 405
  690. */
  691. public function reopen($id)
  692. {
  693. if (!DolibarrApiAccess::$user->rights->commande->creer) {
  694. throw new RestException(401);
  695. }
  696. if (empty($id)) {
  697. throw new RestException(400, 'Order ID is mandatory');
  698. }
  699. $result = $this->commande->fetch($id);
  700. if (!$result) {
  701. throw new RestException(404, 'Order not found');
  702. }
  703. $result = $this->commande->set_reopen(DolibarrApiAccess::$user);
  704. if ($result < 0) {
  705. throw new RestException(405, $this->commande->error);
  706. } elseif ($result == 0) {
  707. throw new RestException(304);
  708. }
  709. return $result;
  710. }
  711. /**
  712. * Classify the order as invoiced. Could be also called setbilled
  713. *
  714. * @param int $id Id of the order
  715. * @return Object Object with cleaned properties
  716. *
  717. * @url POST {id}/setinvoiced
  718. *
  719. * @throws RestException 400
  720. * @throws RestException 401
  721. * @throws RestException 404
  722. * @throws RestException 405
  723. */
  724. public function setinvoiced($id)
  725. {
  726. if (!DolibarrApiAccess::$user->rights->commande->creer) {
  727. throw new RestException(401);
  728. }
  729. if (empty($id)) {
  730. throw new RestException(400, 'Order ID is mandatory');
  731. }
  732. $result = $this->commande->fetch($id);
  733. if (!$result) {
  734. throw new RestException(404, 'Order not found');
  735. }
  736. $result = $this->commande->classifyBilled(DolibarrApiAccess::$user);
  737. if ($result < 0) {
  738. throw new RestException(400, $this->commande->error);
  739. }
  740. $result = $this->commande->fetch($id);
  741. if (!$result) {
  742. throw new RestException(404, 'Order not found');
  743. }
  744. if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
  745. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  746. }
  747. $this->commande->fetchObjectLinked();
  748. return $this->_cleanObjectDatas($this->commande);
  749. }
  750. /**
  751. * Close an order (Classify it as "Delivered")
  752. *
  753. * @param int $id Order ID
  754. * @param int $notrigger Disabled triggers
  755. * @return Object Object with cleaned properties
  756. *
  757. * @url POST {id}/close
  758. */
  759. public function close($id, $notrigger = 0)
  760. {
  761. if (!DolibarrApiAccess::$user->rights->commande->creer) {
  762. throw new RestException(401);
  763. }
  764. $result = $this->commande->fetch($id);
  765. if (!$result) {
  766. throw new RestException(404, 'Order not found');
  767. }
  768. if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
  769. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  770. }
  771. $result = $this->commande->cloture(DolibarrApiAccess::$user, $notrigger);
  772. if ($result == 0) {
  773. throw new RestException(304, 'Error nothing done. May be object is already closed');
  774. }
  775. if ($result < 0) {
  776. throw new RestException(500, 'Error when closing Order: '.$this->commande->error);
  777. }
  778. $result = $this->commande->fetch($id);
  779. if (!$result) {
  780. throw new RestException(404, 'Order not found');
  781. }
  782. if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
  783. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  784. }
  785. $this->commande->fetchObjectLinked();
  786. return $this->_cleanObjectDatas($this->commande);
  787. }
  788. /**
  789. * Set an order to draft
  790. *
  791. * @param int $id Order ID
  792. * @param int $idwarehouse Warehouse ID to use for stock change (Used only if option STOCK_CALCULATE_ON_VALIDATE_ORDER is on)
  793. * @return Object Object with cleaned properties
  794. *
  795. * @url POST {id}/settodraft
  796. */
  797. public function settodraft($id, $idwarehouse = -1)
  798. {
  799. if (!DolibarrApiAccess::$user->rights->commande->creer) {
  800. throw new RestException(401);
  801. }
  802. $result = $this->commande->fetch($id);
  803. if (!$result) {
  804. throw new RestException(404, 'Order not found');
  805. }
  806. if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
  807. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  808. }
  809. $result = $this->commande->setDraft(DolibarrApiAccess::$user, $idwarehouse);
  810. if ($result == 0) {
  811. throw new RestException(304, 'Nothing done. May be object is already closed');
  812. }
  813. if ($result < 0) {
  814. throw new RestException(500, 'Error when closing Order: '.$this->commande->error);
  815. }
  816. $result = $this->commande->fetch($id);
  817. if (!$result) {
  818. throw new RestException(404, 'Order not found');
  819. }
  820. if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) {
  821. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  822. }
  823. $this->commande->fetchObjectLinked();
  824. return $this->_cleanObjectDatas($this->commande);
  825. }
  826. /**
  827. * Create an order using an existing proposal.
  828. *
  829. * @param int $proposalid Id of the proposal
  830. * @return Object Object with cleaned properties
  831. *
  832. * @url POST /createfromproposal/{proposalid}
  833. *
  834. * @throws RestException 400
  835. * @throws RestException 401
  836. * @throws RestException 404
  837. * @throws RestException 405
  838. */
  839. public function createOrderFromProposal($proposalid)
  840. {
  841. require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  842. if (!DolibarrApiAccess::$user->hasRight('propal', 'lire')) {
  843. throw new RestException(401);
  844. }
  845. if (!DolibarrApiAccess::$user->rights->commande->creer) {
  846. throw new RestException(401);
  847. }
  848. if (empty($proposalid)) {
  849. throw new RestException(400, 'Proposal ID is mandatory');
  850. }
  851. $propal = new Propal($this->db);
  852. $result = $propal->fetch($proposalid);
  853. if (!$result) {
  854. throw new RestException(404, 'Proposal not found');
  855. }
  856. $result = $this->commande->createFromProposal($propal, DolibarrApiAccess::$user);
  857. if ($result < 0) {
  858. throw new RestException(405, $this->commande->error);
  859. }
  860. $this->commande->fetchObjectLinked();
  861. return $this->_cleanObjectDatas($this->commande);
  862. }
  863. /**
  864. * Get the shipments of an order
  865. *
  866. * @param int $id Id of the order
  867. *
  868. * @url GET {id}/shipment
  869. *
  870. * @return array
  871. *
  872. * @throws RestException 401
  873. * @throws RestException 404
  874. * @throws RestException 500 System error
  875. */
  876. public function getOrderShipments($id)
  877. {
  878. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
  879. if (!DolibarrApiAccess::$user->rights->expedition->lire) {
  880. throw new RestException(401);
  881. }
  882. $obj_ret = array();
  883. $sql = "SELECT e.rowid";
  884. $sql .= " FROM ".MAIN_DB_PREFIX."expedition as e";
  885. $sql .= " JOIN ".MAIN_DB_PREFIX."expeditiondet as edet";
  886. $sql .= " ON e.rowid = edet.fk_expedition";
  887. $sql .= " JOIN ".MAIN_DB_PREFIX."commandedet as cdet";
  888. $sql .= " ON edet.fk_origin_line = cdet.rowid";
  889. $sql .= " JOIN ".MAIN_DB_PREFIX."commande as c";
  890. $sql .= " ON cdet.fk_commande = c.rowid";
  891. $sql .= " WHERE c.rowid = ".((int) $id);
  892. $sql .= " GROUP BY e.rowid";
  893. $sql .= $this->db->order("e.rowid", "ASC");
  894. dol_syslog("API Rest request");
  895. $result = $this->db->query($sql);
  896. if ($result) {
  897. $num = $this->db->num_rows($result);
  898. if ($num <= 0) {
  899. throw new RestException(404, 'Shipments not found ');
  900. }
  901. $i = 0;
  902. while ($i < $num) {
  903. $obj = $this->db->fetch_object($result);
  904. $shipment_static = new Expedition($this->db);
  905. if ($shipment_static->fetch($obj->rowid)) {
  906. $obj_ret[] = $this->_cleanObjectDatas($shipment_static);
  907. }
  908. $i++;
  909. }
  910. } else {
  911. throw new RestException(500, 'Error when retrieve shipment list : '.$this->db->lasterror());
  912. }
  913. return $obj_ret;
  914. }
  915. /**
  916. * Create the shipment of an order
  917. *
  918. * @param int $id Id of the order
  919. * @param int $warehouse_id Id of a warehouse
  920. *
  921. * @url POST {id}/shipment/{warehouse_id}
  922. *
  923. * @return int
  924. *
  925. * @throws RestException 401
  926. * @throws RestException 404
  927. * @throws RestException 500 System error
  928. */
  929. public function createOrderShipment($id, $warehouse_id)
  930. {
  931. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
  932. if (!DolibarrApiAccess::$user->rights->expedition->creer) {
  933. throw new RestException(401);
  934. }
  935. if ($warehouse_id <= 0) {
  936. throw new RestException(404, 'Warehouse not found');
  937. }
  938. $result = $this->commande->fetch($id);
  939. if (!$result) {
  940. throw new RestException(404, 'Order not found');
  941. }
  942. $shipment = new Expedition($this->db);
  943. $shipment->socid = $this->commande->socid;
  944. $shipment->origin_id = $this->commande->id;
  945. $result = $shipment->create(DolibarrApiAccess::$user);
  946. if ($result <= 0) {
  947. throw new RestException(500, 'Error on creating expedition :'.$this->db->lasterror());
  948. }
  949. foreach ($this->commande->lines as $line) {
  950. $result = $shipment->create_line($warehouse_id, $line->id, $line->qty);
  951. if ($result <= 0) {
  952. throw new RestException(500, 'Error on creating expedition lines:'.$this->db->lasterror());
  953. }
  954. }
  955. return $shipment->id;
  956. }
  957. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  958. /**
  959. * Clean sensible object datas
  960. *
  961. * @param Object $object Object to clean
  962. * @return Object Object with cleaned properties
  963. */
  964. protected function _cleanObjectDatas($object)
  965. {
  966. // phpcs:enable
  967. $object = parent::_cleanObjectDatas($object);
  968. unset($object->note);
  969. unset($object->address);
  970. unset($object->barcode_type);
  971. unset($object->barcode_type_code);
  972. unset($object->barcode_type_label);
  973. unset($object->barcode_type_coder);
  974. return $object;
  975. }
  976. /**
  977. * Validate fields before create or update object
  978. *
  979. * @param array $data Array with data to verify
  980. * @return array
  981. * @throws RestException
  982. */
  983. private function _validate($data)
  984. {
  985. $commande = array();
  986. foreach (Orders::$FIELDS as $field) {
  987. if (!isset($data[$field])) {
  988. throw new RestException(400, $field." field missing");
  989. }
  990. $commande[$field] = $data[$field];
  991. }
  992. return $commande;
  993. }
  994. }