snapshot of https://github.com/espocrm/espocrm.git (master, 2026-09-18; blobs > 131072B omitted)
Some checks failed
Test / Test on PHP 8.3 (push) Failing after 5s
Test / Test on PHP 8.4 (push) Failing after 4s
Test / Test on PHP 8.5 (push) Failing after 3s
TypeScript static analysis / TypeScript check (push) Failing after 14s
Test Integration on MySQL / Test on PHP 8.3 (push) Failing after 2s
Test Integration on MySQL / Test on PHP 8.5 (push) Failing after 0s
Test Integration on PostgreSQL / Test on PHP 8.4 fix (push) Failing after 1s
Test Integration on PostgreSQL / Test on PHP 8.4 master (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-18 04:19:15 +05:00
commit 7cc7e6b4f3
10077 changed files with 900756 additions and 0 deletions

View File

@@ -0,0 +1,52 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Currency\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Tools\Currency\RateService as Service;
/**
* Gets rates.
*/
class Get implements Action
{
public function __construct(private Service $service)
{}
public function process(Request $request): Response
{
$result = $this->service->get()->toAssoc();
return ResponseComposer::json($result);
}
}

View File

@@ -0,0 +1,57 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Currency\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Currency\Rates;
use Espo\Tools\Currency\RateService as Service;
/**
* Updates rates.
*/
class PutUpdate implements Action
{
public function __construct(private Service $service)
{}
public function process(Request $request): Response
{
$data = $request->getParsedBody();
$rates = Rates::fromAssoc(get_object_vars($data), '___');
$this->service->set($rates);
return ResponseComposer::json(true);
}
}

View File

@@ -0,0 +1,129 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Currency\Conversion;
use Espo\Core\Acl;
use Espo\Core\Acl\Table;
use Espo\Core\Currency\Converter;
use Espo\Core\Currency\Rates;
use Espo\Core\Field\Currency;
use Espo\Core\ORM\Entity as CoreEntity;
use Espo\Core\ORM\Type\FieldType;
use Espo\Core\Utils\Metadata;
use Espo\ORM\Entity;
use Espo\ORM\EntityManager;
use LogicException;
/**
* @implements EntityConverter<CoreEntity>
*/
class DefaultEntityConverter implements EntityConverter
{
public function __construct(
private Converter $converter,
private EntityManager $entityManager,
private Metadata $metadata,
private Acl $acl
) {}
/**
* @param CoreEntity $entity
*/
public function convert(Entity $entity, string $targetCurrency, Rates $rates): void
{
$entityDefs = $this->entityManager
->getDefs()
->getEntity($entity->getEntityType());
foreach ($this->getFieldList($entity->getEntityType()) as $field) {
$disabled = $entityDefs->getField($field)->getParam('conversionDisabled');
if ($disabled) {
continue;
}
$value = $entity->getValueObject($field);
if (!$value) {
continue;
}
if (!$value instanceof Currency) {
throw new LogicException();
}
if ($targetCurrency === $value->getCode()) {
continue;
}
$convertedValue = $this->converter->convertWithRates($value, $targetCurrency, $rates);
$entity->setValueObject($field, $convertedValue);
}
}
/**
* @return string[]
*/
private function getFieldList(string $entityType): array
{
$resultList = [];
/** @var string[] $requiredFieldList */
$requiredFieldList = $this->metadata->get(['scopes', $entityType, 'currencyConversionAccessRequiredFieldList']);
$allFields = $requiredFieldList !== null;
$fieldDefsList = $this->entityManager
->getDefs()
->getEntity($entityType)
->getFieldList();
foreach ($fieldDefsList as $fieldDefs) {
$field = $fieldDefs->getName();
$type = $fieldDefs->getType();
if ($type !== FieldType::CURRENCY) {
continue;
}
if (
!$allFields &&
!$this->acl->checkField($entityType, $field, Table::ACTION_EDIT)
) {
continue;
}
$resultList[] = $field;
}
return $resultList;
}
}

View File

@@ -0,0 +1,52 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Currency\Conversion;
use Espo\Core\Currency\Rates;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Conflict;
use Espo\Core\Exceptions\Forbidden;
use Espo\ORM\Entity;
/**
* Converts entity currency values. Is not supposed to save the entity.
*
* @template TEntity of Entity
*/
interface EntityConverter
{
/**
* @param TEntity $entity
* @throws Forbidden
* @throws BadRequest
* @throws Conflict
*/
public function convert(Entity $entity, string $targetCurrency, Rates $rates): void;
}

View File

@@ -0,0 +1,65 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Currency\Conversion;
use Espo\Core\Acl;
use Espo\Core\Binding\BindingContainerBuilder;
use Espo\Core\InjectableFactory;
use Espo\Core\Utils\Metadata;
use Espo\Entities\User;
use Espo\ORM\Entity;
class EntityConverterFactory
{
public function __construct(
private Metadata $metadata,
private InjectableFactory $injectableFactory,
private User $user,
private Acl $acl
) {}
/**
* @return EntityConverter<Entity>
*/
public function create(string $entityType): EntityConverter
{
/** @var class-string<EntityConverter<Entity>> $className */
$className = $this->metadata
->get(['app', 'currencyConversion', 'entityConverterClassNameMap', $entityType]) ??
DefaultEntityConverter::class;
$binding = BindingContainerBuilder::create()
->bindInstance(User::class, $this->user)
->bindInstance(Acl::class, $this->acl)
->build();
return $this->injectableFactory->createWithBinding($className, $binding);
}
}

View File

@@ -0,0 +1,49 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Currency\Events;
use Espo\Core\Utils\Event\CrossInstanceEvent;
use stdClass;
/**
* @since 10.1.0
*/
readonly class CurrencyRateUpdate implements CrossInstanceEvent
{
public function toPayload(): stdClass
{
return (object) [];
}
public static function fromPayload(stdClass $payload): self
{
return new self();
}
}

View File

@@ -0,0 +1,35 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Currency\Exceptions;
use Exception;
class NotEnabled extends Exception
{}

View File

@@ -0,0 +1,191 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Currency;
use Espo\Core\Currency\ConfigDataProvider;
use Espo\Core\Currency\InternalRateEntryProvider;
use Espo\Core\Field\Date;
use Espo\Core\Utils\DateTime;
use Espo\Core\Utils\Event\EventDispatcher;
use Espo\Entities\CurrencyRecord;
use Espo\Entities\CurrencyRecordRate;
use Espo\ORM\EntityManager;
use Espo\ORM\Query\Part\Order;
use Espo\Tools\Currency\Events\CurrencyRateUpdate;
use Espo\Tools\Currency\Exceptions\NotEnabled;
use WeakMap;
/**
* @since 9.3.0
*/
class RateEntryProvider
{
/** @var WeakMap<CurrencyRecord, ?CurrencyRecordRate> */
private WeakMap $map;
public function __construct(
private ConfigDataProvider $configDataProvider,
private EntityManager $entityManager,
private DateTime $dateTime,
private InternalRateEntryProvider $internalRateEntryProvider,
private EventDispatcher $eventDispatcher,
) {
$this->map = new WeakMap();
$this->eventDispatcher->subscribe(CurrencyRateUpdate::class, function () {
$this->map = new WeakMap();
});
}
public function getCurrentRateEntry(CurrencyRecord $record): ?CurrencyRecordRate
{
if (!$this->map->offsetExists($record)) {
$this->map[$record] = $this->entityManager
->getRDBRepositoryByClass(CurrencyRecordRate::class)
->where([
CurrencyRecordRate::ATTR_RECORD_ID => $record->getId(),
CurrencyRecordRate::FIELD_BASE_CODE => $this->configDataProvider->getBaseCurrency(),
CurrencyRecordRate::FIELD_DATE . '<=' => $this->dateTime->getToday()->toString(),
])
->order(CurrencyRecordRate::FIELD_DATE, Order::DESC)
->findOne();
}
return $this->map[$record];
}
/**
* @throws NotEnabled
*/
public function prepareNew(string $code, Date $date): CurrencyRecordRate
{
$record = $this->getRecordByCode($code);
$entry = $this->entityManager->getRDBRepositoryByClass(CurrencyRecordRate::class)->getNew();
$entry
->setRecord($record)
->setDate($date);
return $entry;
}
private function getRateEntryForRecord(CurrencyRecord $record, ?Date $date = null): ?CurrencyRecordRate
{
$date ??= $this->dateTime->getToday();
$base = $this->configDataProvider->getBaseCurrency();
return $this->internalRateEntryProvider->getRateEntryForRecord($record, $date, $base);
}
/**
* Get rate against the base currency by a record.
*
* @return ?numeric-string
*/
public function getRateForRecord(CurrencyRecord $record, ?Date $date = null): ?string
{
$rateEntry = $this->getRateEntryForRecord($record, $date);
return $rateEntry?->getRate();
}
/**
* Get rate against the base currency.
*
* @param string $code
* @return ?numeric-string
* @throws NotEnabled
*/
public function getRate(string $code): ?string
{
$record = $this->getRecordByCode($code);
return $this->getRateForRecord($record);
}
/**
* @throws NotEnabled
*/
public function getRateEntryOnDate(string $code, Date $date): ?CurrencyRecordRate
{
$record = $this->getRecordByCode($code);
return $this->entityManager
->getRDBRepositoryByClass(CurrencyRecordRate::class)
->where([
CurrencyRecordRate::ATTR_RECORD_ID => $record->getId(),
CurrencyRecordRate::FIELD_BASE_CODE => $this->configDataProvider->getBaseCurrency(),
CurrencyRecordRate::FIELD_DATE => $date->toString(),
])
->order(CurrencyRecordRate::FIELD_DATE, Order::DESC)
->findOne();
}
/**
* @since 9.3.0
* @throws NotEnabled
* @noinspection PhpUnused
*/
public function getRateEntryOnAsOfDate(string $code, Date $date): ?CurrencyRecordRate
{
$record = $this->getRecordByCode($code);
return $this->entityManager
->getRDBRepositoryByClass(CurrencyRecordRate::class)
->where([
CurrencyRecordRate::ATTR_RECORD_ID => $record->getId(),
CurrencyRecordRate::FIELD_BASE_CODE => $this->configDataProvider->getBaseCurrency(),
CurrencyRecordRate::FIELD_DATE . '<=' => $date->toString(),
])
->order(CurrencyRecordRate::FIELD_DATE, Order::DESC)
->findOne();
}
/**
* @throws NotEnabled
*/
private function getRecordByCode(string $code): CurrencyRecord
{
$record = $this->entityManager
->getRDBRepositoryByClass(CurrencyRecord::class)
->where([
CurrencyRecord::FIELD_CODE => $code,
CurrencyRecord::FIELD_STATUS => CurrencyRecord::STATUS_ACTIVE,
])
->findOne();
if (!$record) {
throw new NotEnabled("Currency $code is not enabled.");
}
return $record;
}
}

View File

@@ -0,0 +1,143 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Currency;
use Espo\Core\Acl\Table;
use Espo\Core\Currency\ConfigDataProvider;
use Espo\Core\Currency\Rates;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Acl;
use Espo\Core\Utils\Currency\DatabasePopulator;
use Espo\Core\Utils\DateTime;
use Espo\ORM\EntityManager;
use RuntimeException;
class RateService
{
private const string SCOPE = 'Currency';
public function __construct(
private Acl $acl,
private DatabasePopulator $databasePopulator,
private ConfigDataProvider $configDataProvider,
private SyncManager $syncManager,
private RateEntryProvider $rateEntryProvider,
private DateTime $dateTime,
private EntityManager $entityManager,
) {}
/**
* @throws Forbidden
*/
public function get(): Rates
{
$this->checkReadAccess();
$rates = Rates::create($this->configDataProvider->getBaseCurrency());
foreach ($this->configDataProvider->getCurrencyList() as $code) {
$rates = $rates->withRate($code, $this->configDataProvider->getCurrencyRate($code));
}
return $rates;
}
/**
* @throws BadRequest
* @throws Forbidden
*/
public function set(Rates $rates): void
{
$this->checkEditAccess();
$codeList = $this->configDataProvider->getCurrencyList();
$base = $this->configDataProvider->getBaseCurrency();
foreach ($rates->toAssoc() as $code => $value) {
if ($value < 0) {
throw new BadRequest("Bad value.");
}
if (!in_array($code, $codeList) || $code === $base) {
continue;
}
$this->writeOne($code, $value);
}
$this->syncManager->refreshCache();
$this->databasePopulator->process();
}
private function writeOne(string $code, float $value): void
{
$date = $this->dateTime->getToday();
try {
$rateEntry = $this->rateEntryProvider->getRateEntryOnDate($code, $date) ??
$this->rateEntryProvider->prepareNew($code, $date);
} catch (Exceptions\NotEnabled $e) {
throw new RuntimeException($e->getMessage(), previous: $e);
}
$rateEntry->setRate((string) $value);
$this->entityManager->saveEntity($rateEntry);
}
/**
* @throws Forbidden
*/
private function checkReadAccess(): void
{
if (!$this->acl->check(self::SCOPE)) {
throw new Forbidden();
}
if ($this->acl->getLevel(self::SCOPE, Table::ACTION_READ) !== Table::LEVEL_YES) {
throw new Forbidden();
}
}
/**
* @throws Forbidden
*/
private function checkEditAccess(): void
{
if (!$this->acl->check(self::SCOPE)) {
throw new Forbidden();
}
if ($this->acl->getLevel(self::SCOPE, Table::ACTION_EDIT) !== Table::LEVEL_YES) {
throw new Forbidden();
}
}
}

View File

@@ -0,0 +1,178 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Currency;
use Espo\Core\Currency\ConfigDataProvider;
use Espo\Core\Utils\Config\ConfigWriter;
use Espo\Core\Utils\Config\SystemConfig;
use Espo\Core\Utils\DataCache;
use Espo\Core\Utils\Event\EventDispatcher;
use Espo\Entities\CurrencyRecord;
use Espo\ORM\EntityManager;
use Espo\ORM\Name\Attribute;
use Espo\ORM\Query\UpdateBuilder;
use Espo\Tools\Currency\Events\CurrencyRateUpdate;
use Espo\Tools\Currency\Exceptions\NotEnabled;
/**
* @since 9.3.0
* @internal
*/
class SyncManager
{
private string $cacheKey = 'currencyRates';
public function __construct(
private ConfigDataProvider $configDataProvider,
private EntityManager $entityManager,
private ConfigWriter $configWriter,
private RateEntryProvider $rateEntryProvider,
private DataCache $dataCache,
private SystemConfig $systemConfig,
private EventDispatcher $eventDispatcher,
) {}
public function sync(): void
{
$this->entityManager->getTransactionManager()->run(function () {
$this->syncInTransaction();
});
$this->refreshCache();
}
private function syncInTransaction(): void
{
$this->lock();
foreach ($this->configDataProvider->getCurrencyList() as $code) {
$this->syncCode($code);
}
$this->deactivateNotListed();
}
private function syncCode(string $code): void
{
$record = $this->entityManager
->getRDBRepositoryByClass(CurrencyRecord::class)
->where([CurrencyRecord::FIELD_CODE => $code])
->findOne();
if (!$record) {
$record = $this->entityManager->getRDBRepositoryByClass(CurrencyRecord::class)->getNew();
$record->setCode($code);
}
$record->setStatus(CurrencyRecord::STATUS_ACTIVE);
$this->entityManager->saveEntity($record);
}
private function deactivateNotListed(): void
{
$list = $this->configDataProvider->getCurrencyList();
$updateQuery = UpdateBuilder::create()
->in(CurrencyRecord::ENTITY_TYPE)
->set([
CurrencyRecord::FIELD_STATUS => CurrencyRecord::STATUS_INACTIVE,
])
->where([
CurrencyRecord::FIELD_CODE . '!=' => $list,
])
->build();
$this->entityManager->getQueryExecutor()->execute($updateQuery);
}
private function lock(): void
{
$this->entityManager
->getRDBRepositoryByClass(CurrencyRecord::class)
->forUpdate()
->sth()
->select(Attribute::ID)
->find();
}
public function refreshCache(): void
{
$this->entityManager->getTransactionManager()->run(function () {
$this->syncToConfigInTransaction();
});
$this->dispatchUpdateEvent();
$this->clearCache();
}
private function syncToConfigInTransaction(): void
{
$this->lock();
$rates = $this->configDataProvider->getCurrencyRates()->toAssoc();
$this->configWriter->set('currencyRates', $rates);
$this->configWriter->save();
}
/**
* @throws NotEnabled
*/
public function updateCode(string $code): void
{
$rates = $this->configDataProvider->getCurrencyRates()->toAssoc();
$rate = $this->rateEntryProvider->getRate($code) ?? '1.0';
$rates[$code] = (float) $rate;
$this->configWriter->set('currencyRates', $rates);
$this->configWriter->save();
$this->dispatchUpdateEvent();
$this->clearCache();
}
private function clearCache(): void
{
if (!$this->systemConfig->useCache()) {
return;
}
$this->dataCache->clear($this->cacheKey);
}
private function dispatchUpdateEvent(): void
{
$this->eventDispatcher->dispatch(new CurrencyRateUpdate());
}
}