api_multicurrencies.class.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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, $conf;
  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 string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.product_id:=:1) and (t.date_creation:<:'20160101')"
  44. * @return array Array of warehouse objects
  45. *
  46. * @throws RestException
  47. */
  48. public function index($sortfield = "t.rowid", $sortorder = 'ASC', $sqlfilters = '')
  49. {
  50. global $db, $conf;
  51. $obj_ret = array();
  52. $sql = "SELECT t.rowid";
  53. $sql .= " FROM ".$this->db->prefix()."multicurrency as t";
  54. $sql .= ' WHERE 1 = 1';
  55. // Add sql filters
  56. if ($sqlfilters) {
  57. $errormessage = '';
  58. if (!DolibarrApi::_checkFilters($sqlfilters, $errormessage)) {
  59. throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
  60. }
  61. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  62. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
  63. }
  64. $sql .= $this->db->order($sortfield, $sortorder);
  65. if ($limit) {
  66. if ($page < 0) {
  67. $page = 0;
  68. }
  69. $offset = $limit * $page;
  70. $sql .= $this->db->plimit($limit + 1, $offset);
  71. }
  72. $result = $this->db->query($sql);
  73. if ($result) {
  74. $i = 0;
  75. $num = $this->db->num_rows($result);
  76. $min = min($num, ($limit <= 0 ? $num : $limit));
  77. while ($i < $min) {
  78. $obj = $this->db->fetch_object($result);
  79. $multicurrency_static = new MultiCurrency($this->db);
  80. if ($multicurrency_static->fetch($obj->rowid)) {
  81. $obj_ret[] = $this->_cleanObjectDatas($multicurrency_static);
  82. }
  83. $i++;
  84. }
  85. } else {
  86. throw new RestException(503, 'Error when retrieve currencies list : '.$this->db->lasterror());
  87. }
  88. if (!count($obj_ret)) {
  89. throw new RestException(404, 'No currencies found');
  90. }
  91. return $obj_ret;
  92. }
  93. /**
  94. * Get properties of a Currency object
  95. *
  96. * Return an array with Currency informations
  97. *
  98. * @param int $id ID of Currency
  99. * @return array|mixed Data without useless information
  100. *
  101. * @throws RestException
  102. */
  103. public function get($id)
  104. {
  105. $multicurrency = new MultiCurrency($this->db);
  106. if (!$multicurrency->fetch($id)) {
  107. throw new RestException(404, 'Currency not found');
  108. }
  109. if (!DolibarrApiAccess::$user->rights->multicurrency->currency->read) {
  110. throw new RestException(401, "Insufficient rights to read currency");
  111. }
  112. return $this->_cleanObjectDatas($multicurrency);
  113. }
  114. /**
  115. * Get properties of a Currency object by code
  116. *
  117. * Return an array with Currency informations
  118. * @url GET /bycode/{code}
  119. *
  120. * @param string $code Code of Currency (ex: EUR)
  121. * @return array|mixed Data without useless information
  122. *
  123. * @throws RestException
  124. */
  125. public function getByCode($code)
  126. {
  127. $multicurrency = new MultiCurrency($this->db);
  128. if (!$multicurrency->fetch('', $code)) {
  129. throw new RestException(404, 'Currency not found');
  130. }
  131. if (!DolibarrApiAccess::$user->rights->multicurrency->currency->read) {
  132. throw new RestException(401, "Insufficient rights to read currency");
  133. }
  134. return $this->_cleanObjectDatas($multicurrency);
  135. }
  136. /**
  137. * List Currency rates
  138. *
  139. * Get a list of Currency rates
  140. *
  141. * @url GET {id}/rates
  142. * @param int $id ID of Currency
  143. * @return array|mixed Data without useless information
  144. *
  145. * @throws RestException
  146. */
  147. public function getRates($id)
  148. {
  149. $multicurrency = new MultiCurrency($this->db);
  150. if (!$multicurrency->fetch($id)) {
  151. throw new RestException(404, 'Currency not found');
  152. }
  153. if (!DolibarrApiAccess::$user->rights->multicurrency->currency->read) {
  154. throw new RestException(401, "Insufficient rights to read currency rates");
  155. }
  156. if ($multicurrency->fetchAllCurrencyRate() < 0) {
  157. throw new RestException(500, "Error when fetching currency rates");
  158. }
  159. // Clean object datas
  160. foreach ($multicurrency->rates as $key => $obj) {
  161. $multicurrency->rates[$key] = $this->_cleanObjectDatasRate($obj);
  162. }
  163. return $multicurrency->rates;
  164. }
  165. /**
  166. * Create Currency object
  167. *
  168. * @param array $request_data Request data
  169. * @return int ID of Currency
  170. *
  171. * @throws RestException
  172. */
  173. public function post($request_data = null)
  174. {
  175. if (!DolibarrApiAccess::$user->rights->multicurrency->currency->create) {
  176. throw new RestException(401, "Insufficient rights to create currency");
  177. }
  178. // Check parameters
  179. if (!isset($request_data['code'])) {
  180. throw new RestException(400, "code field missing");
  181. }
  182. if (!isset($request_data['name'])) {
  183. throw new RestException(400, "name field missing");
  184. }
  185. $multicurrency = new MultiCurrency($this->db);
  186. $multicurrency->code = $request_data['code'];
  187. $multicurrency->name = $request_data['name'];
  188. // Create Currency
  189. if ($multicurrency->create(DolibarrApiAccess::$user) < 0) {
  190. throw new RestException(500, "Error creating currency", array_merge(array($multicurrency->error), $multicurrency->errors));
  191. }
  192. // Add default rate if defined
  193. if (isset($request_data['rate']) && $request_data['rate'] > 0) {
  194. if ($multicurrency->addRate(DolibarrApiAccess::$user, $request_data['rate']) < 0) {
  195. throw new RestException(500, "Error adding currency rate", array_merge(array($multicurrency->error), $multicurrency->errors));
  196. }
  197. return $multicurrency->id;
  198. }
  199. return $multicurrency->id;
  200. }
  201. /**
  202. * Update Currency
  203. *
  204. * @param int $id Id of Currency to update
  205. * @param array $request_data Datas
  206. * @return array The updated Currency
  207. *
  208. * @throws RestException
  209. */
  210. public function put($id, $request_data = null)
  211. {
  212. if (!DolibarrApiAccess::$user->rights->multicurrency->currency->create) {
  213. throw new RestException(401, "Insufficient rights to update currency");
  214. }
  215. $multicurrency = new MultiCurrency($this->db);
  216. if (!$multicurrency->fetch($id)) {
  217. throw new RestException(404, 'Currency not found');
  218. }
  219. foreach ($request_data as $field => $value) {
  220. if ($field == 'id') {
  221. continue;
  222. }
  223. $multicurrency->$field = $value;
  224. }
  225. if ($multicurrency->update(DolibarrApiAccess::$user) < 0) {
  226. throw new RestException(500, "Error updating currency", array_merge(array($multicurrency->error), $multicurrency->errors));
  227. }
  228. return $this->get($id);
  229. }
  230. /**
  231. * Delete Currency
  232. *
  233. * @param int $id Currency ID
  234. * @return array
  235. *
  236. * @throws RestException
  237. */
  238. public function delete($id)
  239. {
  240. if (!DolibarrApiAccess::$user->rights->multicurrency->currency->delete) {
  241. throw new RestException(401, "Insufficient rights to delete currency");
  242. }
  243. $multicurrency = new MultiCurrency($this->db);
  244. if (!$multicurrency->fetch($id)) {
  245. throw new RestException(404, 'Currency not found');
  246. }
  247. if (!$multicurrency->delete(DolibarrApiAccess::$user)) {
  248. throw new RestException(500, "Error deleting currency", array_merge(array($multicurrency->error), $multicurrency->errors));
  249. }
  250. return array(
  251. 'success' => array(
  252. 'code' => 200,
  253. 'message' => 'Currency deleted'
  254. )
  255. );
  256. }
  257. /**
  258. * Update Currency rate
  259. * @url PUT {id}/rates
  260. *
  261. * @param int $id Currency ID
  262. * @param array $request_data Request data
  263. * @return array The currency with the new rate
  264. *
  265. * @throws RestException
  266. */
  267. public function updateRate($id, $request_data = null)
  268. {
  269. if (!DolibarrApiAccess::$user->rights->multicurrency->currency->create) {
  270. throw new RestException(401, "Insufficient rights to update currency rate");
  271. }
  272. // Check parameters
  273. if (!isset($request_data['rate'])) {
  274. throw new RestException(400, "rate field missing");
  275. }
  276. $multicurrency = new MultiCurrency($this->db);
  277. if (!$multicurrency->fetch($id)) {
  278. throw new RestException(404, 'Currency not found');
  279. }
  280. // Add rate
  281. if ($multicurrency->addRate($request_data['rate']) < 0) {
  282. throw new RestException(500, "Error updating currency rate", array_merge(array($multicurrency->error), $multicurrency->errors));
  283. }
  284. return $this->_cleanObjectDatas($multicurrency);
  285. }
  286. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  287. /**
  288. * Clean sensible object datas
  289. *
  290. * @param MultiCurrency $object Object to clean
  291. * @return Object Object with cleaned properties
  292. */
  293. protected function _cleanObjectDatas($object)
  294. {
  295. // phpcs:enable
  296. $object = parent::_cleanObjectDatas($object);
  297. // Clear all fields out of interrest
  298. foreach ($object as $key => $value) {
  299. if ($key == "rate") $object->$key = $this->_cleanObjectDatasRate($object->$key);
  300. if ($key == "id" || $key == "code" || $key == "rate" || $key == "name")
  301. continue;
  302. unset($object->$key);
  303. }
  304. return $object;
  305. }
  306. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  307. /**
  308. * Clean sensible MultiCurrencyRate object datas
  309. *
  310. * @param MultiCurrencyRate $object Object to clean
  311. * @return Object Object with cleaned properties
  312. */
  313. protected function _cleanObjectDatasRate($object)
  314. {
  315. // phpcs:enable
  316. $object = parent::_cleanObjectDatas($object);
  317. // Clear all fields out of interrest
  318. foreach ($object as $key => $value) {
  319. if ($key == "id" || $key == "rate" || $key == "date_sync")
  320. continue;
  321. unset($object->$key);
  322. }
  323. return $object;
  324. }
  325. }