api_bankaccounts.class.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. <?php
  2. /*
  3. * Copyright (C) 2016 Xebax Christy <xebax@wanadoo.fr>
  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.'/compta/bank/class/account.class.php';
  20. /**
  21. * API class for accounts
  22. *
  23. * @property DoliDB $db
  24. * @access protected
  25. * @class DolibarrApiAccess {@requires user,external}
  26. */
  27. class BankAccounts extends DolibarrApi
  28. {
  29. /**
  30. * array $FIELDS Mandatory fields, checked when creating an object
  31. */
  32. public static $FIELDS = array(
  33. 'ref',
  34. 'label',
  35. 'type',
  36. 'currency_code',
  37. 'country_id'
  38. );
  39. /**
  40. * Constructor
  41. */
  42. public function __construct()
  43. {
  44. global $db;
  45. $this->db = $db;
  46. }
  47. /**
  48. * Get the list of accounts.
  49. *
  50. * @param string $sortfield Sort field
  51. * @param string $sortorder Sort order
  52. * @param int $limit Limit for list
  53. * @param int $page Page number
  54. * @param int $category Use this param to filter list by category
  55. * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.import_key:<:'20160101')"
  56. * @param string $properties Restrict the data returned to theses properties. Ignored if empty. Comma separated list of properties names
  57. * @return array List of account objects
  58. *
  59. * @throws RestException
  60. */
  61. public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $category = 0, $sqlfilters = '', $properties = '')
  62. {
  63. $list = array();
  64. if (!DolibarrApiAccess::$user->rights->banque->lire) {
  65. throw new RestException(401);
  66. }
  67. $sql = "SELECT t.rowid FROM ".MAIN_DB_PREFIX."bank_account AS t LEFT JOIN ".MAIN_DB_PREFIX."bank_account_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
  68. if ($category > 0) {
  69. $sql .= ", ".MAIN_DB_PREFIX."categorie_account as c";
  70. }
  71. $sql .= ' WHERE t.entity IN ('.getEntity('bank_account').')';
  72. // Select accounts of given category
  73. if ($category > 0) {
  74. $sql .= " AND c.fk_categorie = ".((int) $category)." AND c.fk_account = t.rowid";
  75. }
  76. // Add sql filters
  77. if ($sqlfilters) {
  78. $errormessage = '';
  79. $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
  80. if ($errormessage) {
  81. throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
  82. }
  83. }
  84. $sql .= $this->db->order($sortfield, $sortorder);
  85. if ($limit) {
  86. if ($page < 0) {
  87. $page = 0;
  88. }
  89. $offset = $limit * $page;
  90. $sql .= $this->db->plimit($limit + 1, $offset);
  91. }
  92. dol_syslog("API Rest request");
  93. $result = $this->db->query($sql);
  94. if ($result) {
  95. $num = $this->db->num_rows($result);
  96. $min = min($num, ($limit <= 0 ? $num : $limit));
  97. for ($i = 0; $i < $min; $i++) {
  98. $obj = $this->db->fetch_object($result);
  99. $account = new Account($this->db);
  100. if ($account->fetch($obj->rowid) > 0) {
  101. $list[] = $this->_filterObjectProperties($this->_cleanObjectDatas($account), $properties);
  102. }
  103. }
  104. } else {
  105. throw new RestException(503, 'Error when retrieving list of accounts: '.$this->db->lasterror());
  106. }
  107. return $list;
  108. }
  109. /**
  110. * Get account by ID.
  111. *
  112. * @param int $id ID of account
  113. * @return Object Object with cleaned properties
  114. *
  115. * @throws RestException
  116. */
  117. public function get($id)
  118. {
  119. if (!DolibarrApiAccess::$user->rights->banque->lire) {
  120. throw new RestException(401);
  121. }
  122. $account = new Account($this->db);
  123. $result = $account->fetch($id);
  124. if (!$result) {
  125. throw new RestException(404, 'account not found');
  126. }
  127. return $this->_cleanObjectDatas($account);
  128. }
  129. /**
  130. * Create account object
  131. *
  132. * @param array $request_data Request data
  133. * @return int ID of account
  134. */
  135. public function post($request_data = null)
  136. {
  137. if (!DolibarrApiAccess::$user->rights->banque->configurer) {
  138. throw new RestException(401);
  139. }
  140. // Check mandatory fields
  141. $result = $this->_validate($request_data);
  142. $account = new Account($this->db);
  143. foreach ($request_data as $field => $value) {
  144. $account->$field = $this->_checkValForAPI($field, $value, $account);
  145. }
  146. // Date of the initial balance (required to create an account).
  147. $account->date_solde = time();
  148. // courant and type are the same thing but the one used when
  149. // creating an account is courant
  150. $account->courant = $account->type;
  151. if ($account->create(DolibarrApiAccess::$user) < 0) {
  152. throw new RestException(500, 'Error creating bank account', array_merge(array($account->error), $account->errors));
  153. }
  154. return $account->id;
  155. }
  156. /**
  157. * Create an internal wire transfer between two bank accounts
  158. *
  159. * @param int $bankaccount_from_id BankAccount ID to use as the source of the internal wire transfer {@from body}{@required true}
  160. * @param int $bankaccount_to_id BankAccount ID to use as the destination of the internal wire transfer {@from body}{@required true}
  161. * @param string $date Date of the internal wire transfer (UNIX timestamp) {@from body}{@required true}{@type timestamp}
  162. * @param string $description Description of the internal wire transfer {@from body}{@required true}
  163. * @param float $amount Amount to transfer from the source to the destination BankAccount {@from body}{@required true}
  164. * @param float $amount_to Amount to transfer to the destination BankAccount (only when accounts does not share the same currency) {@from body}{@required false}
  165. *
  166. * @url POST /transfer
  167. *
  168. * @return array
  169. *
  170. * @status 201
  171. *
  172. * @throws RestException 401 Unauthorized: User does not have permission to configure bank accounts
  173. * @throws RestException 404 Not Found: Either the source or the destination bankaccount for the provided id does not exist
  174. * @throws RestException 422 Unprocessable Entity: Refer to detailed exception message for the cause
  175. * @throws RestException 500 Internal Server Error: Error(s) returned by the RDBMS
  176. */
  177. public function transfer($bankaccount_from_id = 0, $bankaccount_to_id = 0, $date = null, $description = "", $amount = 0.0, $amount_to = 0.0)
  178. {
  179. if (!DolibarrApiAccess::$user->rights->banque->configurer) {
  180. throw new RestException(401);
  181. }
  182. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  183. $accountfrom = new Account($this->db);
  184. $resultAccountFrom = $accountfrom->fetch($bankaccount_from_id);
  185. if ($resultAccountFrom === 0) {
  186. throw new RestException(404, 'The BankAccount for bankaccount_from_id provided does not exist.');
  187. }
  188. $accountto = new Account($this->db);
  189. $resultAccountTo = $accountto->fetch($bankaccount_to_id);
  190. if ($resultAccountTo === 0) {
  191. throw new RestException(404, 'The BankAccount for bankaccount_to_id provided does not exist.');
  192. }
  193. if ($accountto->currency_code == $accountfrom->currency_code) {
  194. $amount_to = $amount;
  195. } else {
  196. if (!$amount_to || empty($amount_to)) {
  197. throw new RestException(422, 'You must provide amount_to value since bankaccount_from and bankaccount_to does not share the same currency.');
  198. }
  199. }
  200. if ($amount_to < 0) {
  201. throw new RestException(422, 'You must provide a positive value for amount.');
  202. }
  203. if ($accountto->id == $accountfrom->id) {
  204. throw new RestException(422, 'bankaccount_from_id and bankaccount_to_id must be different !');
  205. }
  206. $this->db->begin();
  207. $error = 0;
  208. $bank_line_id_from = 0;
  209. $bank_line_id_to = 0;
  210. $result = 0;
  211. $user = DolibarrApiAccess::$user;
  212. // By default, electronic transfert from bank to bank
  213. $typefrom = 'PRE';
  214. $typeto = 'VIR';
  215. if ($accountto->courant == Account::TYPE_CASH || $accountfrom->courant == Account::TYPE_CASH) {
  216. // This is transfer of change
  217. $typefrom = 'LIQ';
  218. $typeto = 'LIQ';
  219. }
  220. // Clean data
  221. $description = sanitizeVal($description, 'alphanohtml');
  222. /**
  223. * Creating bank line records
  224. */
  225. if (!$error) {
  226. $bank_line_id_from = $accountfrom->addline($date, $typefrom, $description, -1 * price2num($amount), '', '', $user);
  227. }
  228. if (!($bank_line_id_from > 0)) {
  229. $error++;
  230. }
  231. if (!$error) {
  232. $bank_line_id_to = $accountto->addline($date, $typeto, $description, price2num($amount_to), '', '', $user);
  233. }
  234. if (!($bank_line_id_to > 0)) {
  235. $error++;
  236. }
  237. /**
  238. * Creating links between bank line record and its source
  239. */
  240. $url = DOL_URL_ROOT.'/compta/bank/line.php?rowid=';
  241. $label = '(banktransfert)';
  242. $type = 'banktransfert';
  243. if (!$error) {
  244. $result = $accountfrom->add_url_line($bank_line_id_from, $bank_line_id_to, $url, $label, $type);
  245. }
  246. if (!($result > 0)) {
  247. $error++;
  248. }
  249. if (!$error) {
  250. $result = $accountto->add_url_line($bank_line_id_to, $bank_line_id_from, $url, $label, $type);
  251. }
  252. if (!($result > 0)) {
  253. $error++;
  254. }
  255. if (!$error) {
  256. $this->db->commit();
  257. return array(
  258. 'success' => array(
  259. 'code' => 201,
  260. 'message' => 'Internal wire transfer created successfully.',
  261. 'bank_id_from' => $bank_line_id_from,
  262. 'bank_id_to' => $bank_line_id_to,
  263. )
  264. );
  265. } else {
  266. $this->db->rollback();
  267. throw new RestException(500, $accountfrom->error.' '.$accountto->error);
  268. }
  269. }
  270. /**
  271. * Update account
  272. *
  273. * @param int $id ID of account
  274. * @param array $request_data data
  275. * @return Object Object with cleaned properties
  276. */
  277. public function put($id, $request_data = null)
  278. {
  279. if (!DolibarrApiAccess::$user->rights->banque->configurer) {
  280. throw new RestException(401);
  281. }
  282. $account = new Account($this->db);
  283. $result = $account->fetch($id);
  284. if (!$result) {
  285. throw new RestException(404, 'account not found');
  286. }
  287. foreach ($request_data as $field => $value) {
  288. if ($field == 'id') {
  289. continue;
  290. }
  291. $account->$field = $this->_checkValForAPI($field, $value, $account);
  292. }
  293. if ($account->update(DolibarrApiAccess::$user) > 0) {
  294. return $this->get($id);
  295. } else {
  296. throw new RestException(500, $account->error);
  297. }
  298. }
  299. /**
  300. * Delete account
  301. *
  302. * @param int $id ID of account
  303. * @return array
  304. */
  305. public function delete($id)
  306. {
  307. if (!DolibarrApiAccess::$user->rights->banque->configurer) {
  308. throw new RestException(401);
  309. }
  310. $account = new Account($this->db);
  311. $result = $account->fetch($id);
  312. if (!$result) {
  313. throw new RestException(404, 'account not found');
  314. }
  315. if ($account->delete(DolibarrApiAccess::$user) < 0) {
  316. throw new RestException(401, 'error when deleting account');
  317. }
  318. return array(
  319. 'success' => array(
  320. 'code' => 200,
  321. 'message' => 'account deleted'
  322. )
  323. );
  324. }
  325. /**
  326. * Validate fields before creating an object
  327. *
  328. * @param array|null $data Data to validate
  329. * @return array
  330. *
  331. * @throws RestException
  332. */
  333. private function _validate($data)
  334. {
  335. $account = array();
  336. foreach (BankAccounts::$FIELDS as $field) {
  337. if (!isset($data[$field])) {
  338. throw new RestException(400, "$field field missing");
  339. }
  340. $account[$field] = $data[$field];
  341. }
  342. return $account;
  343. }
  344. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  345. /**
  346. * Clean sensible object datas
  347. *
  348. * @param Object $object Object to clean
  349. * @return Object Object with cleaned properties
  350. */
  351. protected function _cleanObjectDatas($object)
  352. {
  353. // phpcs:enable
  354. $object = parent::_cleanObjectDatas($object);
  355. unset($object->rowid);
  356. return $object;
  357. }
  358. /**
  359. * Get the list of lines of the account.
  360. *
  361. * @param int $id ID of account
  362. * @return array Array of AccountLine objects
  363. *
  364. * @throws RestException
  365. *
  366. * @url GET {id}/lines
  367. * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.import_key:<:'20160101')"
  368. */
  369. public function getLines($id, $sqlfilters = '')
  370. {
  371. $list = array();
  372. if (!DolibarrApiAccess::$user->rights->banque->lire) {
  373. throw new RestException(401);
  374. }
  375. $account = new Account($this->db);
  376. $result = $account->fetch($id);
  377. if (!$result) {
  378. throw new RestException(404, 'account not found');
  379. }
  380. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."bank ";
  381. $sql .= " WHERE fk_account = ".((int) $id);
  382. // Add sql filters
  383. if ($sqlfilters) {
  384. $errormessage = '';
  385. $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
  386. if ($errormessage) {
  387. throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
  388. }
  389. }
  390. $sql .= " ORDER BY rowid";
  391. $result = $this->db->query($sql);
  392. if ($result) {
  393. $num = $this->db->num_rows($result);
  394. for ($i = 0; $i < $num; $i++) {
  395. $obj = $this->db->fetch_object($result);
  396. $accountLine = new AccountLine($this->db);
  397. if ($accountLine->fetch($obj->rowid) > 0) {
  398. $list[] = $this->_cleanObjectDatas($accountLine);
  399. }
  400. }
  401. } else {
  402. throw new RestException(503, 'Error when retrieving list of account lines: '.$this->db->lasterror());
  403. }
  404. return $list;
  405. }
  406. /**
  407. * Add a line to an account
  408. *
  409. * @param int $id ID of account
  410. * @param string $date Payment date (timestamp) {@from body} {@type timestamp}
  411. * @param string $type Payment mode (TYP,VIR,PRE,LIQ,VAD,CB,CHQ...) {@from body}
  412. * @param string $label Label {@from body}
  413. * @param float $amount Amount (may be 0) {@from body}
  414. * @param int $category Category
  415. * @param string $cheque_number Cheque numero {@from body}
  416. * @param string $cheque_writer Name of cheque writer {@from body}
  417. * @param string $cheque_bank Bank of cheque writer {@from body}
  418. * @param string $accountancycode Accountancy code {@from body}
  419. * @param string $datev Payment date value (timestamp) {@from body} {@type timestamp}
  420. * @param string $num_releve Bank statement numero {@from body}
  421. * @return int ID of line
  422. *
  423. * @url POST {id}/lines
  424. */
  425. public function addLine($id, $date, $type, $label, $amount, $category = 0, $cheque_number = '', $cheque_writer = '', $cheque_bank = '', $accountancycode = '', $datev = null, $num_releve = '')
  426. {
  427. if (!DolibarrApiAccess::$user->rights->banque->modifier) {
  428. throw new RestException(401);
  429. }
  430. $account = new Account($this->db);
  431. $result = $account->fetch($id);
  432. if (!$result) {
  433. throw new RestException(404, 'account not found');
  434. }
  435. $type = sanitizeVal($type);
  436. $label = sanitizeVal($label);
  437. $cheque_number = sanitizeVal($cheque_number);
  438. $cheque_writer = sanitizeVal($cheque_writer);
  439. $cheque_bank = sanitizeVal($cheque_bank);
  440. $accountancycode = sanitizeVal($accountancycode);
  441. $num_releve = sanitizeVal($num_releve);
  442. $result = $account->addline(
  443. $date,
  444. $type,
  445. $label,
  446. $amount,
  447. $cheque_number,
  448. $category,
  449. DolibarrApiAccess::$user,
  450. $cheque_writer,
  451. $cheque_bank,
  452. $accountancycode,
  453. $datev,
  454. $num_releve
  455. );
  456. if ($result < 0) {
  457. throw new RestException(503, 'Error when adding line to account: '.$account->error);
  458. }
  459. return $result;
  460. }
  461. /**
  462. * Add a link to an account line
  463. *
  464. * @param int $id ID of account
  465. * @param int $line_id ID of account line
  466. * @param int $url_id ID to set in the URL {@from body}
  467. * @param string $url URL of the link {@from body}
  468. * @param string $label Label {@from body}
  469. * @param string $type Type of link ('payment', 'company', 'member', ...) {@from body}
  470. * @return int ID of link
  471. *
  472. * @url POST {id}/lines/{line_id}/links
  473. */
  474. public function addLink($id, $line_id, $url_id, $url, $label, $type)
  475. {
  476. if (!DolibarrApiAccess::$user->rights->banque->modifier) {
  477. throw new RestException(401);
  478. }
  479. $account = new Account($this->db);
  480. $result = $account->fetch($id);
  481. if (!$result) {
  482. throw new RestException(404, 'account not found');
  483. }
  484. $accountLine = new AccountLine($this->db);
  485. $result = $accountLine->fetch($line_id);
  486. if (!$result) {
  487. throw new RestException(404, 'account line not found');
  488. }
  489. $url = sanitizeVal($url);
  490. $label = sanitizeVal($label);
  491. $type = sanitizeVal($type);
  492. $result = $account->add_url_line($line_id, $url_id, $url, $label, $type);
  493. if ($result < 0) {
  494. throw new RestException(503, 'Error when adding link to account line: '.$account->error);
  495. }
  496. return $result;
  497. }
  498. }