api_contracts.class.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. <?php
  2. /* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  3. * Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2018-2020 Frédéric France <frederic.france@netlogic.fr>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. use Luracast\Restler\RestException;
  20. require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
  21. /**
  22. * API class for contracts
  23. *
  24. * @access protected
  25. * @class DolibarrApiAccess {@requires user,external}
  26. */
  27. class Contracts extends DolibarrApi
  28. {
  29. /**
  30. * @var array $FIELDS Mandatory fields, checked when create and update object
  31. */
  32. static $FIELDS = array(
  33. 'socid',
  34. 'date_contrat',
  35. 'commercial_signature_id',
  36. 'commercial_suivi_id'
  37. );
  38. /**
  39. * @var Contrat $contract {@type Contrat}
  40. */
  41. public $contract;
  42. /**
  43. * Constructor
  44. */
  45. public function __construct()
  46. {
  47. global $db, $conf;
  48. $this->db = $db;
  49. $this->contract = new Contrat($this->db);
  50. }
  51. /**
  52. * Get properties of a contract object
  53. *
  54. * Return an array with contract informations
  55. *
  56. * @param int $id ID of contract
  57. * @return Object Object with cleaned properties
  58. * @throws RestException
  59. */
  60. public function get($id)
  61. {
  62. if (!DolibarrApiAccess::$user->rights->contrat->lire) {
  63. throw new RestException(401);
  64. }
  65. $result = $this->contract->fetch($id);
  66. if (!$result) {
  67. throw new RestException(404, 'Contract not found');
  68. }
  69. if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
  70. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  71. }
  72. $this->contract->fetchObjectLinked();
  73. return $this->_cleanObjectDatas($this->contract);
  74. }
  75. /**
  76. * List contracts
  77. *
  78. * Get a list of contracts
  79. *
  80. * @param string $sortfield Sort field
  81. * @param string $sortorder Sort order
  82. * @param int $limit Limit for list
  83. * @param int $page Page number
  84. * @param string $thirdparty_ids Thirdparty ids to filter contracts of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
  85. * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  86. * @return array Array of contract objects
  87. *
  88. * @throws RestException 404 Not found
  89. * @throws RestException 503 Error
  90. */
  91. public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '')
  92. {
  93. global $db, $conf;
  94. if (!DolibarrApiAccess::$user->rights->contrat->lire) {
  95. throw new RestException(401);
  96. }
  97. $obj_ret = array();
  98. // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
  99. $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
  100. // If the internal user must only see his customers, force searching by him
  101. $search_sale = 0;
  102. if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
  103. $search_sale = DolibarrApiAccess::$user->id;
  104. }
  105. $sql = "SELECT t.rowid";
  106. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  107. $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)
  108. }
  109. $sql .= " FROM ".MAIN_DB_PREFIX."contrat AS t LEFT JOIN ".MAIN_DB_PREFIX."contrat_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
  110. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  111. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
  112. }
  113. $sql .= ' WHERE t.entity IN ('.getEntity('contrat').')';
  114. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  115. $sql .= " AND t.fk_soc = sc.fk_soc";
  116. }
  117. if ($socids) {
  118. $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
  119. }
  120. if ($search_sale > 0) {
  121. $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
  122. }
  123. // Insert sale filter
  124. if ($search_sale > 0) {
  125. $sql .= " AND sc.fk_user = ".((int) $search_sale);
  126. }
  127. // Add sql filters
  128. if ($sqlfilters) {
  129. $errormessage = '';
  130. $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
  131. if ($errormessage) {
  132. throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
  133. }
  134. }
  135. $sql .= $this->db->order($sortfield, $sortorder);
  136. if ($limit) {
  137. if ($page < 0) {
  138. $page = 0;
  139. }
  140. $offset = $limit * $page;
  141. $sql .= $this->db->plimit($limit + 1, $offset);
  142. }
  143. dol_syslog("API Rest request");
  144. $result = $this->db->query($sql);
  145. if ($result) {
  146. $num = $this->db->num_rows($result);
  147. $min = min($num, ($limit <= 0 ? $num : $limit));
  148. $i = 0;
  149. while ($i < $min) {
  150. $obj = $this->db->fetch_object($result);
  151. $contrat_static = new Contrat($this->db);
  152. if ($contrat_static->fetch($obj->rowid)) {
  153. $obj_ret[] = $this->_cleanObjectDatas($contrat_static);
  154. }
  155. $i++;
  156. }
  157. } else {
  158. throw new RestException(503, 'Error when retrieve contrat list : '.$this->db->lasterror());
  159. }
  160. if (!count($obj_ret)) {
  161. throw new RestException(404, 'No contract found');
  162. }
  163. return $obj_ret;
  164. }
  165. /**
  166. * Create contract object
  167. *
  168. * @param array $request_data Request data
  169. * @return int ID of contrat
  170. */
  171. public function post($request_data = null)
  172. {
  173. if (!DolibarrApiAccess::$user->rights->contrat->creer) {
  174. throw new RestException(401, "Insufficient rights");
  175. }
  176. // Check mandatory fields
  177. $result = $this->_validate($request_data);
  178. foreach ($request_data as $field => $value) {
  179. $this->contract->$field = $value;
  180. }
  181. /*if (isset($request_data["lines"])) {
  182. $lines = array();
  183. foreach ($request_data["lines"] as $line) {
  184. array_push($lines, (object) $line);
  185. }
  186. $this->contract->lines = $lines;
  187. }*/
  188. if ($this->contract->create(DolibarrApiAccess::$user) < 0) {
  189. throw new RestException(500, "Error creating contract", array_merge(array($this->contract->error), $this->contract->errors));
  190. }
  191. return $this->contract->id;
  192. }
  193. /**
  194. * Get lines of a contract
  195. *
  196. * @param int $id Id of contract
  197. *
  198. * @url GET {id}/lines
  199. *
  200. * @return array
  201. */
  202. public function getLines($id)
  203. {
  204. if (!DolibarrApiAccess::$user->rights->contrat->lire) {
  205. throw new RestException(401);
  206. }
  207. $result = $this->contract->fetch($id);
  208. if (!$result) {
  209. throw new RestException(404, 'Contract not found');
  210. }
  211. if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
  212. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  213. }
  214. $this->contract->getLinesArray();
  215. $result = array();
  216. foreach ($this->contract->lines as $line) {
  217. array_push($result, $this->_cleanObjectDatas($line));
  218. }
  219. return $result;
  220. }
  221. /**
  222. * Add a line to given contract
  223. *
  224. * @param int $id Id of contrat to update
  225. * @param array $request_data Contractline data
  226. *
  227. * @url POST {id}/lines
  228. *
  229. * @return int|bool
  230. */
  231. public function postLine($id, $request_data = null)
  232. {
  233. if (!DolibarrApiAccess::$user->rights->contrat->creer) {
  234. throw new RestException(401);
  235. }
  236. $result = $this->contract->fetch($id);
  237. if (!$result) {
  238. throw new RestException(404, 'Contract not found');
  239. }
  240. if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
  241. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  242. }
  243. $request_data = (object) $request_data;
  244. $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
  245. $request_data->price_base_type = sanitizeVal($request_data->price_base_type);
  246. $updateRes = $this->contract->addline(
  247. $request_data->desc,
  248. $request_data->subprice,
  249. $request_data->qty,
  250. $request_data->tva_tx,
  251. $request_data->localtax1_tx,
  252. $request_data->localtax2_tx,
  253. $request_data->fk_product,
  254. $request_data->remise_percent,
  255. $request_data->date_start,
  256. $request_data->date_end,
  257. $request_data->price_base_type ? $request_data->price_base_type : 'HT',
  258. $request_data->subprice_excl_tax,
  259. $request_data->info_bits,
  260. $request_data->fk_fournprice,
  261. $request_data->pa_ht,
  262. $request_data->array_options,
  263. $request_data->fk_unit,
  264. $request_data->rang
  265. );
  266. if ($updateRes > 0) {
  267. return $updateRes;
  268. }
  269. return false;
  270. }
  271. /**
  272. * Update a line to given contract
  273. *
  274. * @param int $id Id of contrat to update
  275. * @param int $lineid Id of line to update
  276. * @param array $request_data Contractline data
  277. *
  278. * @url PUT {id}/lines/{lineid}
  279. *
  280. * @return Object|bool
  281. */
  282. public function putLine($id, $lineid, $request_data = null)
  283. {
  284. if (!DolibarrApiAccess::$user->rights->contrat->creer) {
  285. throw new RestException(401);
  286. }
  287. $result = $this->contract->fetch($id);
  288. if (!$result) {
  289. throw new RestException(404, 'Contrat not found');
  290. }
  291. if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
  292. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  293. }
  294. $request_data = (object) $request_data;
  295. $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
  296. $request_data->price_base_type = sanitizeVal($request_data->price_base_type);
  297. $updateRes = $this->contract->updateline(
  298. $lineid,
  299. $request_data->desc,
  300. $request_data->subprice,
  301. $request_data->qty,
  302. $request_data->remise_percent,
  303. $request_data->date_start,
  304. $request_data->date_end,
  305. $request_data->tva_tx,
  306. $request_data->localtax1_tx,
  307. $request_data->localtax2_tx,
  308. $request_data->date_start_real,
  309. $request_data->date_end_real,
  310. $request_data->price_base_type ? $request_data->price_base_type : 'HT',
  311. $request_data->info_bits,
  312. $request_data->fk_fourn_price,
  313. $request_data->pa_ht,
  314. $request_data->array_options,
  315. $request_data->fk_unit
  316. );
  317. if ($updateRes > 0) {
  318. $result = $this->get($id);
  319. unset($result->line);
  320. return $this->_cleanObjectDatas($result);
  321. }
  322. return false;
  323. }
  324. /**
  325. * Activate a service line of a given contract
  326. *
  327. * @param int $id Id of contract to activate
  328. * @param int $lineid Id of line to activate
  329. * @param string $datestart {@from body} Date start {@type timestamp}
  330. * @param string $dateend {@from body} Date end {@type timestamp}
  331. * @param string $comment {@from body} Comment
  332. *
  333. * @url PUT {id}/lines/{lineid}/activate
  334. *
  335. * @return Object|bool
  336. */
  337. public function activateLine($id, $lineid, $datestart, $dateend = null, $comment = null)
  338. {
  339. if (!DolibarrApiAccess::$user->rights->contrat->creer) {
  340. throw new RestException(401);
  341. }
  342. $result = $this->contract->fetch($id);
  343. if (!$result) {
  344. throw new RestException(404, 'Contrat not found');
  345. }
  346. if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
  347. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  348. }
  349. $updateRes = $this->contract->active_line(DolibarrApiAccess::$user, $lineid, $datestart, $dateend, $comment);
  350. if ($updateRes > 0) {
  351. $result = $this->get($id);
  352. unset($result->line);
  353. return $this->_cleanObjectDatas($result);
  354. }
  355. return false;
  356. }
  357. /**
  358. * Unactivate a service line of a given contract
  359. *
  360. * @param int $id Id of contract to activate
  361. * @param int $lineid Id of line to activate
  362. * @param string $datestart {@from body} Date start {@type timestamp}
  363. * @param string $comment {@from body} Comment
  364. *
  365. * @url PUT {id}/lines/{lineid}/unactivate
  366. *
  367. * @return Object|bool
  368. */
  369. public function unactivateLine($id, $lineid, $datestart, $comment = null)
  370. {
  371. if (!DolibarrApiAccess::$user->rights->contrat->creer) {
  372. throw new RestException(401);
  373. }
  374. $result = $this->contract->fetch($id);
  375. if (!$result) {
  376. throw new RestException(404, 'Contrat not found');
  377. }
  378. if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
  379. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  380. }
  381. $updateRes = $this->contract->close_line(DolibarrApiAccess::$user, $lineid, $datestart, $comment);
  382. if ($updateRes > 0) {
  383. $result = $this->get($id);
  384. unset($result->line);
  385. return $this->_cleanObjectDatas($result);
  386. }
  387. return false;
  388. }
  389. /**
  390. * Delete a line to given contract
  391. *
  392. *
  393. * @param int $id Id of contract to update
  394. * @param int $lineid Id of line to delete
  395. *
  396. * @url DELETE {id}/lines/{lineid}
  397. *
  398. * @return array|mixed
  399. *
  400. * @throws RestException 401
  401. * @throws RestException 404
  402. */
  403. public function deleteLine($id, $lineid)
  404. {
  405. if (!DolibarrApiAccess::$user->rights->contrat->creer) {
  406. throw new RestException(401);
  407. }
  408. $result = $this->contract->fetch($id);
  409. if (!$result) {
  410. throw new RestException(404, 'Contrat not found');
  411. }
  412. if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
  413. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  414. }
  415. // TODO Check the lineid $lineid is a line of object
  416. $updateRes = $this->contract->deleteline($lineid, DolibarrApiAccess::$user);
  417. if ($updateRes > 0) {
  418. return $this->get($id);
  419. } else {
  420. throw new RestException(405, $this->contract->error);
  421. }
  422. }
  423. /**
  424. * Update contract general fields (won't touch lines of contract)
  425. *
  426. * @param int $id Id of contract to update
  427. * @param array $request_data Datas
  428. *
  429. * @return array|mixed
  430. */
  431. public function put($id, $request_data = null)
  432. {
  433. if (!DolibarrApiAccess::$user->rights->contrat->creer) {
  434. throw new RestException(401);
  435. }
  436. $result = $this->contract->fetch($id);
  437. if (!$result) {
  438. throw new RestException(404, 'Contrat not found');
  439. }
  440. if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
  441. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  442. }
  443. foreach ($request_data as $field => $value) {
  444. if ($field == 'id') {
  445. continue;
  446. }
  447. $this->contract->$field = $value;
  448. }
  449. if ($this->contract->update(DolibarrApiAccess::$user) > 0) {
  450. return $this->get($id);
  451. } else {
  452. throw new RestException(500, $this->contract->error);
  453. }
  454. }
  455. /**
  456. * Delete contract
  457. *
  458. * @param int $id Contract ID
  459. *
  460. * @return array
  461. */
  462. public function delete($id)
  463. {
  464. if (!DolibarrApiAccess::$user->rights->contrat->supprimer) {
  465. throw new RestException(401);
  466. }
  467. $result = $this->contract->fetch($id);
  468. if (!$result) {
  469. throw new RestException(404, 'Contract not found');
  470. }
  471. if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
  472. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  473. }
  474. if (!$this->contract->delete(DolibarrApiAccess::$user)) {
  475. throw new RestException(500, 'Error when delete contract : '.$this->contract->error);
  476. }
  477. return array(
  478. 'success' => array(
  479. 'code' => 200,
  480. 'message' => 'Contract deleted'
  481. )
  482. );
  483. }
  484. /**
  485. * Validate a contract
  486. *
  487. * @param int $id Contract ID
  488. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  489. *
  490. * @url POST {id}/validate
  491. *
  492. * @return array
  493. * FIXME An error 403 is returned if the request has an empty body.
  494. * Error message: "Forbidden: Content type `text/plain` is not supported."
  495. * Workaround: send this in the body
  496. * {
  497. * "notrigger": 0
  498. * }
  499. */
  500. public function validate($id, $notrigger = 0)
  501. {
  502. if (!DolibarrApiAccess::$user->rights->contrat->creer) {
  503. throw new RestException(401);
  504. }
  505. $result = $this->contract->fetch($id);
  506. if (!$result) {
  507. throw new RestException(404, 'Contract not found');
  508. }
  509. if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
  510. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  511. }
  512. $result = $this->contract->validate(DolibarrApiAccess::$user, '', $notrigger);
  513. if ($result == 0) {
  514. throw new RestException(304, 'Error nothing done. May be object is already validated');
  515. }
  516. if ($result < 0) {
  517. throw new RestException(500, 'Error when validating Contract: '.$this->contract->error);
  518. }
  519. return array(
  520. 'success' => array(
  521. 'code' => 200,
  522. 'message' => 'Contract validated (Ref='.$this->contract->ref.')'
  523. )
  524. );
  525. }
  526. /**
  527. * Close all services of a contract
  528. *
  529. * @param int $id Contract ID
  530. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  531. *
  532. * @url POST {id}/close
  533. *
  534. * @return array
  535. * FIXME An error 403 is returned if the request has an empty body.
  536. * Error message: "Forbidden: Content type `text/plain` is not supported."
  537. * Workaround: send this in the body
  538. * {
  539. * "notrigger": 0
  540. * }
  541. */
  542. public function close($id, $notrigger = 0)
  543. {
  544. if (!DolibarrApiAccess::$user->rights->contrat->creer) {
  545. throw new RestException(401);
  546. }
  547. $result = $this->contract->fetch($id);
  548. if (!$result) {
  549. throw new RestException(404, 'Contract not found');
  550. }
  551. if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
  552. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  553. }
  554. $result = $this->contract->closeAll(DolibarrApiAccess::$user, $notrigger);
  555. if ($result == 0) {
  556. throw new RestException(304, 'Error nothing done. May be object is already close');
  557. }
  558. if ($result < 0) {
  559. throw new RestException(500, 'Error when closing Contract: '.$this->contract->error);
  560. }
  561. return array(
  562. 'success' => array(
  563. 'code' => 200,
  564. 'message' => 'Contract closed (Ref='.$this->contract->ref.'). All services were closed.'
  565. )
  566. );
  567. }
  568. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  569. /**
  570. * Clean sensible object datas
  571. *
  572. * @param Object $object Object to clean
  573. * @return Object Object with cleaned properties
  574. */
  575. protected function _cleanObjectDatas($object)
  576. {
  577. // phpcs:enable
  578. $object = parent::_cleanObjectDatas($object);
  579. unset($object->address);
  580. unset($object->civility_id);
  581. return $object;
  582. }
  583. /**
  584. * Validate fields before create or update object
  585. *
  586. * @param array $data Array with data to verify
  587. * @return array
  588. * @throws RestException
  589. */
  590. private function _validate($data)
  591. {
  592. $contrat = array();
  593. foreach (Contracts::$FIELDS as $field) {
  594. if (!isset($data[$field])) {
  595. throw new RestException(400, "$field field missing");
  596. }
  597. $contrat[$field] = $data[$field];
  598. }
  599. return $contrat;
  600. }
  601. }