db = $db; } /** * */ public function loadRateFromBank(string $currency): float { return (new MnbExchangeRate)->currencyExchangeRate($currency); } /** * */ public function updateRate(): bool { $success = true; $this->errors = []; $eur = 1/$this->loadRateFromBank(self::EUR); $this->loadEntities(); if (!empty($this->entities)) { foreach ($this->entities as $entity) { if ($this->updateEntity(self::EUR, $eur, $entity) === false) { $success = false; } } } return $success; } /** * */ private function updateEntity(string $currency, float $rate, DaoMulticompany $entity): bool { $result = false; $multiCurrencyId = $this->getIdFromCode($currency, $entity->id); $currencyRate = new CurrencyRate($this->db); $currencyRate->fk_multicurrency = $multiCurrencyId; $currencyRate->entity = $entity->id; $currencyRate->date_sync = date('Y-m-d H:i:s'); $currencyRate->rate = $rate; $result = $currencyRate->create(intval($multiCurrencyId)); if ($result > 0) { $result = true; } else { $this->errors[] = $currency.' entity: '.$entity->label.' ('.$entity->id.')'; dol_syslog("currencyRate:createRate", LOG_WARNING); } return $result; } /** * */ public function loadEntities(): void { $entityDao = (new DaoMulticompany($this->db)); $entityDao->getEntities(false, [], true); $this->entities = $entityDao->entities; } /** * Get id of currency from code * * @param string $code code value search * @param int $entity entity value search * * @return int 0 if not found, >0 if OK */ public function getIdFromCode($code, $entity): int { $id = 0; $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."multicurrency WHERE code = '".$this->db->escape($code)."' AND entity = ".$entity; dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql && $obj = $this->db->fetch_object($resql)) { $id = $obj->rowid; } return $id; } /** * */ public static function getExchangeRate(string $currency, int $entity): array { global $db; $result = []; $sql = " SELECT ROUND(1/cr.rate, 2) AS \"{$currency}\", cr.date_sync AS last_update FROM ".MAIN_DB_PREFIX."multicurrency AS c LEFT JOIN ".MAIN_DB_PREFIX."multicurrency_rate AS cr ON cr.fk_multicurrency=c.rowid WHERE c.code ILIKE '{$currency}' AND cr.entity={$entity} ORDER BY cr.date_sync DESC LIMIT 1 "; $row = $db->query($sql); if ($row) { $obj = $db->fetch_object($row); $result = (array)$obj; $result[$currency] = (float)$result[$currency]; } return $result; } }