api_multicurrencies.class.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. <?php
  2. /* Copyright (C) 2022 J-F Bouculat <jfbouculat@gmail.com>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. use Luracast\Restler\RestException;
  18. //require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
  19. require_once DOL_DOCUMENT_ROOT.'/core/lib/multicurrency.lib.php';
  20. /**
  21. * API class for MultiCurrency
  22. *
  23. * @access protected
  24. * @class DolibarrApiAccess {@requires user,external}
  25. */
  26. class MultiCurrencies extends DolibarrApi
  27. {
  28. /**
  29. * Constructor
  30. */
  31. public function __construct()
  32. {
  33. global $db;
  34. $this->db = $db;
  35. }
  36. /**
  37. * List Currencies
  38. *
  39. * Get a list of Currencies
  40. *
  41. * @param string $sortfield Sort field
  42. * @param string $sortorder Sort order
  43. * @param int $limit Limit for list
  44. * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.product_id:=:1) and (t.date_creation:<:'20160101')"
  45. * @return array Array of warehouse objects
  46. *
  47. * @throws RestException
  48. */
  49. public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $sqlfilters = '')
  50. {
  51. global $db;
  52. $obj_ret = array();
  53. $sql = "SELECT t.rowid";
  54. $sql .= " FROM ".$this->db->prefix()."multicurrency as t";
  55. $sql .= ' WHERE 1 = 1';
  56. // Add sql filters
  57. if ($sqlfilters) {
  58. $errormessage = '';
  59. if (!DolibarrApi::_checkFilters($sqlfilters, $errormessage)) {
  60. throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
  61. }
  62. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  63. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
  64. }
  65. $sql .= $this->db->order($sortfield, $sortorder);
  66. if ($limit) {
  67. if ($page < 0) {
  68. $page = 0;
  69. }
  70. $offset = $limit * $page;
  71. $sql .= $this->db->plimit($limit + 1, $offset);
  72. }
  73. $result = $this->db->query($sql);
  74. if ($result) {
  75. $i = 0;
  76. $num = $this->db->num_rows($result);
  77. $min = min($num, ($limit <= 0 ? $num : $limit));
  78. while ($i < $min) {
  79. $obj = $this->db->fetch_object($result);
  80. $multicurrency_static = new MultiCurrency($this->db);
  81. if ($multicurrency_static->fetch($obj->rowid)) {
  82. $obj_ret[] = $this->_cleanObjectDatas($multicurrency_static);
  83. }
  84. $i++;
  85. }
  86. } else {
  87. throw new RestException(503, 'Error when retrieve currencies list : '.$this->db->lasterror());
  88. }
  89. if (!count($obj_ret)) {
  90. throw new RestException(404, 'No currencies found');
  91. }
  92. return $obj_ret;
  93. }
  94. /**
  95. * Get properties of a Currency object
  96. *
  97. * Return an array with Currency informations
  98. *
  99. * @param int $id ID of Currency
  100. * @return Object Object with cleaned properties
  101. *
  102. * @throws RestException
  103. */
  104. public function get($id)
  105. {
  106. $multicurrency = new MultiCurrency($this->db);
  107. if (!$multicurrency->fetch($id)) {
  108. throw new RestException(404, 'Currency not found');
  109. }
  110. if (!DolibarrApiAccess::$user->rights->multicurrency->currency->read) {
  111. throw new RestException(401, "Insufficient rights to read currency");
  112. }
  113. return $this->_cleanObjectDatas($multicurrency);
  114. }
  115. /**
  116. * Get properties of a Currency object by code
  117. *
  118. * Return an array with Currency informations
  119. * @url GET /bycode/{code}
  120. *
  121. * @param string $code Code of Currency (ex: EUR)
  122. * @return array|mixed Data without useless information
  123. *
  124. * @throws RestException
  125. */
  126. public function getByCode($code)
  127. {
  128. $multicurrency = new MultiCurrency($this->db);
  129. if (!$multicurrency->fetch('', $code)) {
  130. throw new RestException(404, 'Currency not found');
  131. }
  132. if (!DolibarrApiAccess::$user->rights->multicurrency->currency->read) {
  133. throw new RestException(401, "Insufficient rights to read currency");
  134. }
  135. return $this->_cleanObjectDatas($multicurrency);
  136. }
  137. /**
  138. * List Currency rates
  139. *
  140. * Get a list of Currency rates
  141. *
  142. * @url GET {id}/rates
  143. * @param int $id ID of Currency
  144. * @return array|mixed Data without useless information
  145. *
  146. * @throws RestException
  147. */
  148. public function getRates($id)
  149. {
  150. $multicurrency = new MultiCurrency($this->db);
  151. if (!$multicurrency->fetch($id)) {
  152. throw new RestException(404, 'Currency not found');
  153. }
  154. if (!DolibarrApiAccess::$user->rights->multicurrency->currency->read) {
  155. throw new RestException(401, "Insufficient rights to read currency rates");
  156. }
  157. if ($multicurrency->fetchAllCurrencyRate() < 0) {
  158. throw new RestException(500, "Error when fetching currency rates");
  159. }
  160. // Clean object datas
  161. foreach ($multicurrency->rates as $key => $obj) {
  162. $multicurrency->rates[$key] = $this->_cleanObjectDatasRate($obj);
  163. }
  164. return $multicurrency->rates;
  165. }
  166. /**
  167. * Create Currency object
  168. *
  169. * @param array $request_data Request data
  170. * @return int ID of Currency
  171. *
  172. * @throws RestException
  173. */
  174. public function post($request_data = null)
  175. {
  176. if (!DolibarrApiAccess::$user->rights->multicurrency->currency->create) {
  177. throw new RestException(401, "Insufficient rights to create currency");
  178. }
  179. // Check parameters
  180. if (!isset($request_data['code'])) {
  181. throw new RestException(400, "code field missing");
  182. }
  183. if (!isset($request_data['name'])) {
  184. throw new RestException(400, "name field missing");
  185. }
  186. $multicurrency = new MultiCurrency($this->db);
  187. $multicurrency->code = $request_data['code'];
  188. $multicurrency->name = $request_data['name'];
  189. // Create Currency
  190. if ($multicurrency->create(DolibarrApiAccess::$user) < 0) {
  191. throw new RestException(500, "Error creating currency", array_merge(array($multicurrency->error), $multicurrency->errors));
  192. }
  193. // Add default rate if defined
  194. if (isset($request_data['rate']) && $request_data['rate'] > 0) {
  195. if ($multicurrency->addRate($request_data['rate']) < 0) {
  196. throw new RestException(500, "Error adding currency rate", array_merge(array($multicurrency->error), $multicurrency->errors));
  197. }
  198. return $multicurrency->id;
  199. }
  200. return $multicurrency->id;
  201. }
  202. /**
  203. * Update Currency
  204. *
  205. * @param int $id Id of Currency to update
  206. * @param array $request_data Datas
  207. * @return array The updated Currency
  208. *
  209. * @throws RestException
  210. */
  211. public function put($id, $request_data = null)
  212. {
  213. if (!DolibarrApiAccess::$user->rights->multicurrency->currency->create) {
  214. throw new RestException(401, "Insufficient rights to update currency");
  215. }
  216. $multicurrency = new MultiCurrency($this->db);
  217. if (!$multicurrency->fetch($id)) {
  218. throw new RestException(404, 'Currency not found');
  219. }
  220. foreach ($request_data as $field => $value) {
  221. if ($field == 'id') {
  222. continue;
  223. }
  224. $multicurrency->$field = $value;
  225. }
  226. if ($multicurrency->update(DolibarrApiAccess::$user) < 0) {
  227. throw new RestException(500, "Error updating currency", array_merge(array($multicurrency->error), $multicurrency->errors));
  228. }
  229. return $this->get($id);
  230. }
  231. /**
  232. * Delete Currency
  233. *
  234. * @param int $id Currency ID
  235. * @return array
  236. *
  237. * @throws RestException
  238. */
  239. public function delete($id)
  240. {
  241. if (!DolibarrApiAccess::$user->rights->multicurrency->currency->delete) {
  242. throw new RestException(401, "Insufficient rights to delete currency");
  243. }
  244. $multicurrency = new MultiCurrency($this->db);
  245. if (!$multicurrency->fetch($id)) {
  246. throw new RestException(404, 'Currency not found');
  247. }
  248. if (!$multicurrency->delete(DolibarrApiAccess::$user)) {
  249. throw new RestException(500, "Error deleting currency", array_merge(array($multicurrency->error), $multicurrency->errors));
  250. }
  251. return array(
  252. 'success' => array(
  253. 'code' => 200,
  254. 'message' => 'Currency deleted'
  255. )
  256. );
  257. }
  258. /**
  259. * Update Currency rate
  260. * @url PUT {id}/rates
  261. *
  262. * @param int $id Currency ID
  263. * @param array $request_data Request data
  264. * @return Object|false Object with cleaned properties
  265. *
  266. * @throws RestException
  267. */
  268. public function updateRate($id, $request_data = null)
  269. {
  270. if (!DolibarrApiAccess::$user->rights->multicurrency->currency->create) {
  271. throw new RestException(401, "Insufficient rights to update currency rate");
  272. }
  273. // Check parameters
  274. if (!isset($request_data['rate'])) {
  275. throw new RestException(400, "rate field missing");
  276. }
  277. $multicurrency = new MultiCurrency($this->db);
  278. if (!$multicurrency->fetch($id)) {
  279. throw new RestException(404, 'Currency not found');
  280. }
  281. // Add rate
  282. if ($multicurrency->addRate($request_data['rate']) < 0) {
  283. throw new RestException(500, "Error updating currency rate", array_merge(array($multicurrency->error), $multicurrency->errors));
  284. }
  285. return $this->_cleanObjectDatas($multicurrency);
  286. }
  287. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  288. /**
  289. * Clean sensible object datas
  290. *
  291. * @param MultiCurrency $object Object to clean
  292. * @return Object Object with cleaned properties
  293. */
  294. protected function _cleanObjectDatas($object)
  295. {
  296. // phpcs:enable
  297. $object = parent::_cleanObjectDatas($object);
  298. // Clear all fields out of interrest
  299. foreach ($object as $key => $value) {
  300. if ($key == "rate") {
  301. $object->$key = $this->_cleanObjectDatasRate($object->$key);
  302. }
  303. if ($key == "id" || $key == "code" || $key == "rate" || $key == "name") {
  304. continue;
  305. }
  306. unset($object->$key);
  307. }
  308. return $object;
  309. }
  310. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  311. /**
  312. * Clean sensible MultiCurrencyRate object datas
  313. *
  314. * @param MultiCurrency $object Object to clean
  315. * @return Object Object with cleaned properties
  316. */
  317. protected function _cleanObjectDatasRate($object)
  318. {
  319. // phpcs:enable
  320. $object = parent::_cleanObjectDatas($object);
  321. // Clear all fields out of interrest
  322. foreach ($object as $key => $value) {
  323. if ($key == "id" || $key == "rate" || $key == "date_sync")
  324. continue;
  325. unset($object->$key);
  326. }
  327. return $object;
  328. }
  329. }