30require_once DOL_DOCUMENT_ROOT.
'/core/class/commonobject.class.php';
31require_once DOL_DOCUMENT_ROOT.
'/multicurrency/class/currencyrate.class.php';
44 public $element =
'multicurrency';
49 public $table_element =
'multicurrency';
54 public $table_element_line =
"multicurrency_rate";
59 public $rates = array();
116 global $conf, $langs;
118 dol_syslog(
'MultiCurrency::create', LOG_DEBUG);
122 if (self::checkCodeAlreadyExists($this->code)) {
124 $this->errors[] = $langs->trans(
'multicurrency_code_already_added');
128 if (empty($this->entity) || $this->entity <= 0) {
129 $this->entity = $conf->entity;
134 $sql =
"INSERT INTO ".MAIN_DB_PREFIX.$this->table_element.
"(";
138 $sql .=
' date_create,';
140 $sql .=
') VALUES (';
141 $sql .=
" '".$this->db->escape($this->code).
"',";
142 $sql .=
" '".$this->db->escape($this->
name).
"',";
143 $sql .=
" ".((int) $this->entity).
",";
144 $sql .=
" '".$this->db->idate($now).
"',";
145 $sql .=
" ".((int) $user->id);
151 $resql = $this->db->query($sql);
154 $this->errors[] =
'Error '.$this->db->lasterror();
155 dol_syslog(
'MultiCurrency::create '.implode(
',', $this->errors), LOG_ERR);
159 $this->
id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
160 $this->date_create = $now;
161 $this->fk_user = $user->id;
163 if (empty($notrigger)) {
164 $result = $this->
call_trigger(
'CURRENCY_CREATE', $user);
172 $this->db->rollback();
189 public function fetch($id, $code =
null)
191 dol_syslog(
'MultiCurrency::fetch', LOG_DEBUG);
196 $sql .=
' c.rowid, c.name, c.code, c.entity, c.date_create, c.fk_user';
197 $sql .=
' FROM '.MAIN_DB_PREFIX.$this->table_element.
' AS c';
199 $sql .=
' WHERE c.code = \''.$this->db->escape($code).
'\' AND c.entity =
'.$conf->entity;
201 $sql .= ' WHERE c.rowid =
'.((int) $id);
204 dol_syslog(__METHOD__, LOG_DEBUG);
205 $resql = $this->db->query($sql);
208 $numrows = $this->db->num_rows($resql);
210 $obj = $this->db->fetch_object($resql);
212 $this->id = $obj->rowid;
213 $this->name = $obj->name;
214 $this->code = $obj->code;
215 $this->entity = $obj->entity;
216 $this->date_create = $obj->date_create;
217 $this->fk_user = $obj->fk_user;
219 $this->fetchAllCurrencyRate();
222 $this->db->free($resql);
230 $this->errors[] = 'Error
'.$this->db->lasterror();
242 public function fetchAllCurrencyRate()
244 $sql = "SELECT cr.rowid";
245 $sql .= ' FROM
'.MAIN_DB_PREFIX.$this->table_element_line.' as cr
';
246 $sql .= ' WHERE cr.fk_multicurrency =
'.((int) $this->id);
247 $sql .= ' ORDER BY cr.date_sync DESC
';
249 $this->rates = array();
251 dol_syslog(__METHOD__, LOG_DEBUG);
252 $resql = $this->db->query($sql);
254 $num = $this->db->num_rows($resql);
256 while ($obj = $this->db->fetch_object($resql)) {
257 $rate = new CurrencyRate($this->db);
258 $rate->fetch($obj->rowid);
260 $this->rates[] = $rate;
262 $this->db->free($resql);
266 $this->errors[] = 'Error
'.$this->db->lasterror();
280 public function update(User $user, $notrigger = 0)
287 $this->name = trim($this->name);
288 $this->code = trim($this->code);
291 if (empty($this->code)) {
299 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
300 $sql .= " name = '".$this->db->escape($this->name)."',";
301 $sql .= " code = '".$this->db->escape($this->code)."'";
302 $sql .= " WHERE rowid = ".((int) $this->id);
306 $resql = $this->db->query($sql);
309 $this->errors[] = 'Error
'.$this->db->lasterror();
313 if (!$error && empty($notrigger)) {
314 $result = $this->call_trigger('CURRENCY_MODIFY
', $user);
320 // Commit or rollback
322 $this->db->rollback();
339 public function delete(User $user, $notrigger = 0)
347 if (empty($notrigger)) {
348 $result = $this->call_trigger('CURRENCY_DELETE
', $user);
355 // Delete all rates before
356 if (!$this->deleteRates()) {
358 $this->errors[] = 'Error
'.$this->db->lasterror();
359 dol_syslog('Currency::delete
'.implode(',
', $this->errors), LOG_ERR);
362 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
363 $sql .= " WHERE rowid = ".((int) $this->id);
365 dol_syslog(__METHOD__, LOG_DEBUG);
366 $resql = $this->db->query($sql);
369 $this->errors[] = 'Error
'.$this->db->lasterror();
374 // Commit or rollback
376 $this->db->rollback();
391 public function deleteRates()
395 foreach ($this->rates as &$rate) {
396 if ($rate->delete($user) <= 0) {
410 public function addRate($rate)
414 $currencyRate = new CurrencyRate($this->db);
415 $currencyRate->rate = (float) price2num($rate);
417 if ($currencyRate->create($user, $this->id) > 0) {
418 $this->rate = $currencyRate;
422 $this->errors = $currencyRate->errors;
434 public function addRateFromDolibarr($code, $rate)
438 $currency = new MultiCurrency($this->db);
439 $currency->code = $code;
440 $currency->name = $code;
442 $sql = "SELECT label FROM ".MAIN_DB_PREFIX."c_currencies WHERE code_iso = '
".$this->db->escape($code)."'";
444 dol_syslog(__METHOD__, LOG_DEBUG);
445 $resql = $this->db->query($sql);
446 if ($resql && ($line = $this->db->fetch_object($resql))) {
447 $currency->name = $line->label;
450 if ($currency->create($user) > 0) {
451 $currency->addRate($rate);
469 public function updateRate($rate)
471 return $this->addRate($rate);
479 public function getRate()
481 $sql = "SELECT cr.rowid";
482 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element_line." as cr";
483 $sql .= " WHERE cr.fk_multicurrency = ".((int) $this->id);
484 $sql .= " AND cr.date_sync = (SELECT MAX(cr2.date_sync) FROM ".MAIN_DB_PREFIX.$this->table_element_line." AS cr2 WHERE cr2.fk_multicurrency = ".((int) $this->id).")";
486 dol_syslog(__METHOD__, LOG_DEBUG);
487 $resql = $this->db->query($sql);
488 if ($resql && ($obj = $this->db->fetch_object($resql))) {
489 $this->rate = new CurrencyRate($this->db);
490 return $this->rate->fetch($obj->rowid);
504 public static function getIdFromCode($dbs, $code)
508 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."multicurrency WHERE code = '
".$dbs->escape($code)."' AND entity = ".((int) $conf->entity);
510 dol_syslog(__METHOD__, LOG_DEBUG);
511 $resql = $dbs->query($sql);
512 if ($resql && $obj = $dbs->fetch_object($resql)) {
529 public static function getIdAndTxFromCode($dbs, $code, $date_document = '
')
533 $sql1 = "SELECT m.rowid, mc.rate FROM ".MAIN_DB_PREFIX."multicurrency m";
535 $sql1 .= ' LEFT JOIN
'.MAIN_DB_PREFIX.'multicurrency_rate mc ON (m.rowid = mc.fk_multicurrency)
';
536 $sql1 .= " WHERE m.code = '".$dbs->escape($code)."'";
537 $sql1 .= " AND m.entity IN (".getEntity('multicurrency
').")";
539 if (getDolGlobalString('MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE
') && !empty($date_document)) { // Use last known rate compared to document date
540 $tmparray = dol_getdate($date_document);
541 $sql2 .= " AND mc.date_sync <= '".$dbs->idate(dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], true))."'";
543 $sql3 = " ORDER BY mc.date_sync DESC LIMIT 1";
545 dol_syslog(__METHOD__, LOG_DEBUG);
546 $resql = $dbs->query($sql1.$sql2.$sql3);
548 if ($resql && $obj = $dbs->fetch_object($resql)) {
549 return array($obj->rowid, $obj->rate);
551 if (getDolGlobalString('MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE
')) {
552 $resql = $dbs->query($sql1.$sql3);
553 if ($resql && $obj = $dbs->fetch_object($resql)) {
554 return array($obj->rowid, $obj->rate);
572 public static function getAmountConversionFromInvoiceRate($fk_facture, $amount, $way = 'dolibarr
', $table = 'facture
', $invoice_rate = null)
574 if (!is_null($invoice_rate)) {
575 $multicurrency_tx = $invoice_rate;
577 $multicurrency_tx = self::getInvoiceRate($fk_facture, $table);
580 if ($multicurrency_tx) {
581 if ($way == 'dolibarr
') {
582 return (float) price2num($amount * $multicurrency_tx, 'MU
');
584 return (float) price2num($amount / $multicurrency_tx, 'MU
');
598 public static function getInvoiceRate($fk_facture, $table = 'facture
')
602 $sql = "SELECT multicurrency_tx FROM ".MAIN_DB_PREFIX.$table." WHERE rowid = ".((int) $fk_facture);
604 dol_syslog(__METHOD__, LOG_DEBUG);
605 $resql = $db->query($sql);
606 if ($resql && ($line = $db->fetch_object($resql))) {
607 return $line->multicurrency_tx;
620 public function recalculRates(&$TRate)
624 if ($conf->currency != getDolGlobalString('MULTICURRENCY_APP_SOURCE
')) {
625 $alternate_source = 'USD
'.$conf->currency;
626 if (!empty($TRate->$alternate_source)) {
627 $coef = 1 / $TRate->$alternate_source;
628 foreach ($TRate as $attr => &$rate) {
631 $TRate->USDUSD = $coef;
635 return -1; // Alternate source not found
638 return 0; // Nothing to do
649 public function syncRates($key, $addifnotfound = 0, $mode = "")
651 global $conf, $db, $langs;
653 if (getDolGlobalString('MULTICURRENCY_DISABLE_SYNC_CURRENCYLAYER
')) {
654 if ($mode == "cron") {
655 $this->output = $langs->trans('Use of API
for currency
update is
disabled by option MULTICURRENCY_DISABLE_SYNC_CURRENCYLAYER
');
657 setEventMessages($langs->trans('Use of API
for currency
update is
disabled by option MULTICURRENCY_DISABLE_SYNC_CURRENCYLAYER
'), null, 'errors
');
663 $key = getDolGlobalString("MULTICURRENCY_APP_ID");
666 include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php
';
668 $urlendpoint = 'http:
669 $urlendpoint .=
'&source=' . (!
getDolGlobalString(
'MULTICURRENCY_APP_SOURCE') ?
'USD' : $conf->global->MULTICURRENCY_APP_SOURCE);
671 dol_syslog(
"Call url endpoint ".$urlendpoint);
675 if ($resget[
'content']) {
676 $response = $resget[
'content'];
677 $response = json_decode($response);
679 if ($response->success) {
680 $TRate = $response->quotes;
684 foreach ($TRate as $currency_code => $rate) {
685 $code = substr($currency_code, 3, 3);
687 if ($obj->fetch(0, $code) > 0) {
688 $obj->updateRate($rate);
689 } elseif ($addifnotfound) {
695 if ($mode ==
"cron") {
700 dol_syslog(
"Failed to call endpoint ".$response->error->info, LOG_WARNING);
701 if ($mode ==
"cron") {
702 $this->output = $langs->trans(
'multicurrency_syncronize_error', $response->error->info);
704 setEventMessages($langs->trans(
'multicurrency_syncronize_error', $response->error->info),
null,
'errors');
722 if ($currencytmp->fetch(
'', $code) > 0) {
Parent class of all other business classes (invoices, contracts, proposals, orders,...
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage Dolibarr database access.
delete(User $user, $notrigger=0)
Delete object in database.
update(User $user, $notrigger=0)
Update object into database.
fetchAllCurrencyRate()
Load all rates in object from the database.
checkCodeAlreadyExists($code)
Check in database if the current code already exists.
__construct(DoliDB $db)
Constructor.
create(User $user, $notrigger=0)
Create object into database.
addRateFromDolibarr($code, $rate)
Try get label of code in llx_currency then add rate.
recalculRates(&$TRate)
With free account we can't set source then recalcul all rates to force another source.
fetch($id, $code=null)
Load object in memory from the database.
Class to manage Dolibarr users.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
dol_now($mode='auto')
Return date for now.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getURLContent($url, $postorget='GET', $param='', $followlocation=1, $addheaders=array(), $allowedschemes=array('http', 'https'), $localurl=0, $ssl_verifypeer=-1)
Function to get a content from an URL (use proxy if proxy defined).
$conf db name
Only used if Module[ID]Name translation string is not found.