dolibarr  21.0.0-alpha
api_multicurrencies.class.php
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 
18 use Luracast\Restler\RestException;
19 
20 //require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
21 require_once DOL_DOCUMENT_ROOT.'/core/lib/multicurrency.lib.php';
22 
30 {
34  public function __construct()
35  {
36  global $db;
37 
38  $this->db = $db;
39  }
40 
56  public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
57  {
58  global $db;
59 
60  if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
61  throw new RestException(403, "Insufficient rights to read currency");
62  }
63 
64  $obj_ret = array();
65 
66  $sql = "SELECT t.rowid";
67  $sql .= " FROM ".$this->db->prefix()."multicurrency as t";
68  $sql .= ' WHERE 1 = 1';
69  // Add sql filters
70  if ($sqlfilters) {
71  $errormessage = '';
72  if (!DolibarrApi::_checkFilters($sqlfilters, $errormessage)) {
73  throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
74  }
75  $regexstring = '\‍(([^:\'\‍(\‍)]+:[^:\'\‍(\‍)]+:[^\‍(\‍)]+)\‍)';
76  $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
77  }
78 
79  $sql .= $this->db->order($sortfield, $sortorder);
80  if ($limit) {
81  if ($page < 0) {
82  $page = 0;
83  }
84  $offset = $limit * $page;
85 
86  $sql .= $this->db->plimit($limit + 1, $offset);
87  }
88 
89  $result = $this->db->query($sql);
90  if ($result) {
91  $i = 0;
92  $num = $this->db->num_rows($result);
93  $min = min($num, ($limit <= 0 ? $num : $limit));
94  while ($i < $min) {
95  $obj = $this->db->fetch_object($result);
96  $multicurrency_static = new MultiCurrency($this->db);
97  if ($multicurrency_static->fetch($obj->rowid)) {
98  $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($multicurrency_static), $properties);
99  }
100  $i++;
101  }
102  } else {
103  throw new RestException(503, 'Error when retrieve currencies list : '.$this->db->lasterror());
104  }
105 
106  return $obj_ret;
107  }
108 
119  public function get($id)
120  {
121  $multicurrency = new MultiCurrency($this->db);
122  if (!$multicurrency->fetch($id)) {
123  throw new RestException(404, 'Currency not found');
124  }
125 
126  if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
127  throw new RestException(403, "Insufficient rights to read currency");
128  }
129 
130  return $this->_cleanObjectDatas($multicurrency);
131  }
132 
144  public function getByCode($code)
145  {
146  $multicurrency = new MultiCurrency($this->db);
147  if (!$multicurrency->fetch('', $code)) {
148  throw new RestException(404, 'Currency not found');
149  }
150 
151  if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
152  throw new RestException(403, "Insufficient rights to read currency");
153  }
154 
155  return $this->_cleanObjectDatas($multicurrency);
156  }
157 
169  public function getRates($id)
170  {
171  $multicurrency = new MultiCurrency($this->db);
172  if (!$multicurrency->fetch($id)) {
173  throw new RestException(404, 'Currency not found');
174  }
175 
176  if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'read')) {
177  throw new RestException(403, "Insufficient rights to read currency rates");
178  }
179 
180  if ($multicurrency->fetchAllCurrencyRate() < 0) {
181  throw new RestException(500, "Error when fetching currency rates");
182  }
183 
184  // Clean object datas
185  foreach ($multicurrency->rates as $key => $obj) {
186  $multicurrency->rates[$key] = $this->_cleanObjectDatasRate($obj);
187  }
188 
189  return $multicurrency->rates;
190  }
191 
200  public function post($request_data = null)
201  {
202 
203  // Check parameters
204  if (!isset($request_data['code'])) {
205  throw new RestException(400, "code field missing");
206  }
207  if (!isset($request_data['name'])) {
208  throw new RestException(400, "name field missing");
209  }
210 
211  if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'write')) {
212  throw new RestException(403, "Insufficient rights to create currency");
213  }
214 
215  $multicurrency = new MultiCurrency($this->db);
216 
217  foreach ($request_data as $field => $value) {
218  if ($field === 'caller') {
219  // 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
220  $multicurrency->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
221  continue;
222  }
223 
224  $multicurrency->$field = $this->_checkValForAPI($field, $value, $multicurrency);
225  }
226 
227  // Create Currency
228  if ($multicurrency->create(DolibarrApiAccess::$user) < 0) {
229  throw new RestException(500, "Error creating currency", array_merge(array($multicurrency->error), $multicurrency->errors));
230  }
231 
232  // Add default rate if defined
233  if (isset($request_data['rate']) && $request_data['rate'] > 0) {
234  if ($multicurrency->addRate($request_data['rate']) < 0) {
235  throw new RestException(500, "Error adding currency rate", array_merge(array($multicurrency->error), $multicurrency->errors));
236  }
237 
238  return $multicurrency->id;
239  }
240 
241  return $multicurrency->id;
242  }
243 
253  public function put($id, $request_data = null)
254  {
255  if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'write')) {
256  throw new RestException(403, "Insufficient rights to update currency");
257  }
258 
259  $multicurrency = new MultiCurrency($this->db);
260  if (!$multicurrency->fetch($id)) {
261  throw new RestException(404, 'Currency not found');
262  }
263 
264  foreach ($request_data as $field => $value) {
265  if ($field == 'id') {
266  continue;
267  }
268  if ($field === 'caller') {
269  // 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
270  $multicurrency->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
271  continue;
272  }
273 
274  $multicurrency->$field = $this->_checkValForAPI($field, $value, $multicurrency);
275  }
276 
277  if ($multicurrency->update(DolibarrApiAccess::$user) < 0) {
278  throw new RestException(500, "Error updating currency", array_merge(array($multicurrency->error), $multicurrency->errors));
279  }
280 
281  return $this->get($id);
282  }
283 
292  public function delete($id)
293  {
294  if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'delete')) {
295  throw new RestException(403, "Insufficient rights to delete currency");
296  }
297 
298  $multicurrency = new MultiCurrency($this->db);
299  if (!$multicurrency->fetch($id)) {
300  throw new RestException(404, 'Currency not found');
301  }
302 
303  if (!$multicurrency->delete(DolibarrApiAccess::$user)) {
304  throw new RestException(500, "Error deleting currency", array_merge(array($multicurrency->error), $multicurrency->errors));
305  }
306 
307  return array(
308  'success' => array(
309  'code' => 200,
310  'message' => 'Currency deleted'
311  )
312  );
313  }
314 
315 
326  public function updateRate($id, $request_data = null)
327  {
328  if (!DolibarrApiAccess::$user->hasRight('multicurrency', 'currency', 'write')) {
329  throw new RestException(403, "Insufficient rights to update currency rate");
330  }
331 
332  // Check parameters
333  if (!isset($request_data['rate'])) {
334  throw new RestException(400, "Rate field is missing");
335  }
336 
337  $multicurrency = new MultiCurrency($this->db);
338  if (!$multicurrency->fetch($id)) {
339  throw new RestException(404, 'Currency not found');
340  }
341 
342  // Add rate
343  if ($multicurrency->addRate($request_data['rate']) < 0) {
344  throw new RestException(500, "Error updating currency rate", array_merge(array($multicurrency->error), $multicurrency->errors));
345  }
346 
347  return $this->_cleanObjectDatas($multicurrency);
348  }
349 
350  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
357  protected function _cleanObjectDatas($object)
358  {
359  // phpcs:enable
360  $object = parent::_cleanObjectDatas($object);
361 
362  // Clear all fields out of interest
363  foreach ($object as $key => $value) {
364  if ($key == "rate") {
365  $object->$key = $this->_cleanObjectDatasRate($object->$key);
366  }
367  if ($key == "id" || $key == "code" || $key == "rate" || $key == "name") {
368  continue;
369  }
370  unset($object->$key);
371  }
372 
373  return $object;
374  }
375 
376  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
383  protected function _cleanObjectDatasRate($object)
384  {
385  // phpcs:enable
386  $object = parent::_cleanObjectDatas($object);
387 
388  // Clear all fields out of interest
389  foreach ($object as $key => $value) {
390  if ($key == "id" || $key == "rate" || $key == "date_sync") {
391  continue;
392  }
393  unset($object->$key);
394  }
395 
396  return $object;
397  }
398 }
if($user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition: card.php:58
Class for API REST v1.
Definition: api.class.php:30
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
Definition: api.class.php:136
_checkFilters($sqlfilters, &$error='')
Return if a $sqlfilters parameter is valid Function no more used.
Definition: api.class.php:397
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition: api.class.php:82
_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.
if(isModEnabled('invoice') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&!getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD') && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') && $user->hasRight('tax', 'charges', 'lire')) if(isModEnabled('invoice') &&isModEnabled('order') && $user->hasRight("commande", "lire") &&!getDolGlobalString('WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER')) $sql
Social contributions to pay.
Definition: index.php:751
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.