dolibarr 22.0.5
api_multicurrencies.class.php
1<?php
2/* Copyright (C) 2022 J-F Bouculat <jfbouculat@gmail.com>
3 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
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
19use Luracast\Restler\RestException;
20
21//require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
22require_once DOL_DOCUMENT_ROOT.'/core/lib/multicurrency.lib.php';
23
31{
35 public function __construct()
36 {
37 global $db;
38
39 $this->db = $db;
40 }
41
59 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
60 {
61 global $db;
62
63 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
64 throw new RestException(403, "Insufficient rights to read currency");
65 }
66
67 $obj_ret = array();
68
69 $sql = "SELECT t.rowid";
70 $sql .= " FROM ".$this->db->prefix()."multicurrency as t";
71 $sql .= " WHERE t.entity IN (".getEntity('multicurrency').")";
72 // Add sql filters
73 if ($sqlfilters) {
74 $errormessage = '';
75 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
76 if ($errormessage) {
77 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
78 }
79 }
80
81 $sql .= $this->db->order($sortfield, $sortorder);
82 if ($limit) {
83 if ($page < 0) {
84 $page = 0;
85 }
86 $offset = $limit * $page;
87
88 $sql .= $this->db->plimit($limit + 1, $offset);
89 }
90
91 $result = $this->db->query($sql);
92 if ($result) {
93 $i = 0;
94 $num = $this->db->num_rows($result);
95 $min = min($num, ($limit <= 0 ? $num : $limit));
96 while ($i < $min) {
97 $obj = $this->db->fetch_object($result);
98 $multicurrency_static = new MultiCurrency($this->db);
99 if ($multicurrency_static->fetch($obj->rowid)) {
100 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($multicurrency_static), $properties);
101 }
102 $i++;
103 }
104 } else {
105 throw new RestException(503, 'Error when retrieve currencies list : '.$this->db->lasterror());
106 }
107
108 return $obj_ret;
109 }
110
121 public function get($id)
122 {
123 $multicurrency = new MultiCurrency($this->db);
124 if (!$multicurrency->fetch($id)) {
125 throw new RestException(404, 'Currency not found');
126 }
127
128 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
129 throw new RestException(403, "Insufficient rights to read currency");
130 }
131
132 return $this->_cleanObjectDatas($multicurrency);
133 }
134
146 public function getByCode($code)
147 {
148 $multicurrency = new MultiCurrency($this->db);
149 if (!$multicurrency->fetch(0, $code)) {
150 throw new RestException(404, 'Currency not found');
151 }
152
153 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
154 throw new RestException(403, "Insufficient rights to read currency");
155 }
156
157 return $this->_cleanObjectDatas($multicurrency);
158 }
159
171 public function getRates($id)
172 {
173 $multicurrency = new MultiCurrency($this->db);
174 if (!$multicurrency->fetch($id)) {
175 throw new RestException(404, 'Currency not found');
176 }
177
178 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
179 throw new RestException(403, "Insufficient rights to read currency rates");
180 }
181
182 if ($multicurrency->fetchAllCurrencyRate() < 0) {
183 throw new RestException(500, "Error when fetching currency rates");
184 }
185
186 // Clean object datas
187 foreach ($multicurrency->rates as $key => $obj) {
188 $multicurrency->rates[$key] = $this->_cleanObjectDatasRate($obj);
189 }
190
191 return $multicurrency->rates;
192 }
193
204 public function post($request_data = null)
205 {
206
207 // Check parameters
208 if (!isset($request_data['code'])) {
209 throw new RestException(400, "code field missing");
210 }
211 if (!isset($request_data['name'])) {
212 throw new RestException(400, "name field missing");
213 }
214
215 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'write')) {
216 throw new RestException(403, "Insufficient rights to create currency");
217 }
218
219 $multicurrency = new MultiCurrency($this->db);
220
221 foreach ($request_data as $field => $value) {
222 if ($field === 'caller') {
223 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
224 $multicurrency->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
225 continue;
226 }
227
228 $multicurrency->$field = $this->_checkValForAPI($field, $value, $multicurrency);
229 }
230
231 // Create Currency
232 if ($multicurrency->create(DolibarrApiAccess::$user) < 0) {
233 throw new RestException(500, "Error creating currency", array_merge(array($multicurrency->error), $multicurrency->errors));
234 }
235
236 // Add default rate if defined
237 if (isset($request_data['rate']) && $request_data['rate'] > 0) {
238 if ($multicurrency->addRate((float) $request_data['rate']) < 0) {
239 throw new RestException(500, "Error adding currency rate", array_merge(array($multicurrency->error), $multicurrency->errors));
240 }
241
242 return $multicurrency->id;
243 }
244
245 return $multicurrency->id;
246 }
247
259 public function put($id, $request_data = null)
260 {
261 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'write')) {
262 throw new RestException(403, "Insufficient rights to update currency");
263 }
264
265 $multicurrency = new MultiCurrency($this->db);
266 if (!$multicurrency->fetch($id)) {
267 throw new RestException(404, 'Currency not found');
268 }
269
270 foreach ($request_data as $field => $value) {
271 if ($field == 'id') {
272 continue;
273 }
274 if ($field === 'caller') {
275 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
276 $multicurrency->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
277 continue;
278 }
279
280 $multicurrency->$field = $this->_checkValForAPI($field, $value, $multicurrency);
281 }
282
283 if ($multicurrency->update(DolibarrApiAccess::$user) < 0) {
284 throw new RestException(500, "Error updating currency", array_merge(array($multicurrency->error), $multicurrency->errors));
285 }
286
287 return $this->get($id);
288 }
289
300 public function delete($id)
301 {
302 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'delete')) {
303 throw new RestException(403, "Insufficient rights to delete currency");
304 }
305
306 $multicurrency = new MultiCurrency($this->db);
307 if (!$multicurrency->fetch($id)) {
308 throw new RestException(404, 'Currency not found');
309 }
310
311 if (!$multicurrency->delete(DolibarrApiAccess::$user)) {
312 throw new RestException(500, "Error deleting currency", array_merge(array($multicurrency->error), $multicurrency->errors));
313 }
314
315 return array(
316 'success' => array(
317 'code' => 200,
318 'message' => 'Currency deleted'
319 )
320 );
321 }
322
323
336 public function updateRate($id, $request_data = null)
337 {
338 if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'write')) {
339 throw new RestException(403, "Insufficient rights to update currency rate");
340 }
341
342 // Check parameters
343 if (!isset($request_data['rate'])) {
344 throw new RestException(400, "Rate field is missing");
345 }
346
347 $multicurrency = new MultiCurrency($this->db);
348 if (!$multicurrency->fetch($id)) {
349 throw new RestException(404, 'Currency not found');
350 }
351
352 // Add rate
353 if ($multicurrency->addRate((float) $request_data['rate']) < 0) {
354 throw new RestException(500, "Error updating currency rate", array_merge(array($multicurrency->error), $multicurrency->errors));
355 }
356
357 return $this->_cleanObjectDatas($multicurrency);
358 }
359
360 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
367 protected function _cleanObjectDatas($object)
368 {
369 // phpcs:enable
370 $object = parent::_cleanObjectDatas($object);
371
372 // Clear all fields out of interest
373 foreach ($object as $key => $value) {
374 if ($key == "rate") {
375 $object->$key = $this->_cleanObjectDatasRate($object->$key);
376 }
377 if ($key == "id" || $key == "code" || $key == "rate" || $key == "name") {
378 continue;
379 }
380 unset($object->$key);
381 }
382
383 return $object;
384 }
385
386 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
393 protected function _cleanObjectDatasRate($object)
394 {
395 // phpcs:enable
396 $object = parent::_cleanObjectDatas($object);
397
398 // Clear all fields out of interest
399 foreach ($object as $key => $value) {
400 if ($key == "id" || $key == "rate" || $key == "date_sync") {
401 continue;
402 }
403 unset($object->$key);
404 }
405
406 return $object;
407 }
408}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
Class for API REST v1.
Definition api.class.php:33
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:98
_cleanObjectDatasRate($object)
Clean sensible MultiCurrencyRate object datas.
getRates($id)
List Currency rates.
put($id, $request_data=null)
Update Currency.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $sqlfilters='', $properties='')
List Currencies.
updateRate($id, $request_data=null)
Update Currency rate @url PUT {id}/rates.
getByCode($code)
Get properties of a Currency object by code.
_cleanObjectDatas($object)
Clean sensible object datas.
post($request_data=null)
Create Currency object.
Class Currency.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.