src/Service/CurrencyService.php line 47

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use App\Config\ExchangeRateTypeEnum;
  4. use App\Entity\MarkupStrategy;
  5. use App\Repository\CurrencyExchangerateRepository;
  6. use App\Repository\MarkupStrategyExchangeRateRepository;
  7. use Exception;
  8. use Sherlockode\ConfigurationBundle\Manager\ParameterManagerInterface;
  9. use Symfony\Component\HttpFoundation\RequestStack;
  10. use Symfony\Component\Security\Core\User\UserInterface;
  11. class CurrencyService
  12. {
  13.     public function __construct(
  14.         private readonly CurrencyExchangerateRepository $currencyExchangerateRepository,
  15.         private readonly ParameterManagerInterface      $parameterManager,
  16.         private readonly ParameterService               $parameterService,
  17.         private readonly RequestStack                   $requestStack,
  18.         private readonly MarkupStrategyExchangeRateRepository $markupStrategyExchangeRateRepository
  19.     ){}
  20.     public function getCurrencies(): array
  21.     {
  22.         $currencies = [];
  23.         $parameters = $this->parameterManager->getAll();
  24.         foreach ($parameters as $key => $value) {
  25.             if (str_starts_with($key, 'Currency_')){
  26.                 $currencies [$value] = $value;
  27.             }
  28.         }
  29.         return $currencies;
  30.     }
  31.     /**
  32.      * Retourne la devise active de la session.
  33.      * Si la session ne contient rien, on retombe sur la devise de référence du projet.
  34.      */
  35.     public function getSessionCurrency() : string{
  36.         $session = $this->requestStack->getSession();
  37.         return $session->get('userCurrency') ?? $this->parameterService->getReferenceCurrency();
  38.     }
  39.     /**
  40.      * Retourne la locale active de la session.
  41.      * Cette valeur pilote l'affichage RTL/LTR et le formatage des montants.
  42.      */
  43.     public function getSessionLocale(): string
  44.     {
  45.         $session = $this->requestStack->getSession();
  46.         return $session->get('_locale') ?? 'fr';
  47.     }
  48.     /**
  49.      * Calcule le libellé affichable d'une devise en fonction de la locale.
  50.      * On tente d'utiliser Intl pour obtenir le symbole localisé, puis on revient au code ISO.
  51.      */
  52.     public function getCurrencyLabel(?string $currency, ?string $locale = null, ?string $fallbackCurrency = null): string
  53.     {
  54.         $resolvedCurrency = $currency ?? $fallbackCurrency;
  55.         if (empty($resolvedCurrency)) {
  56.             return '';
  57.         }
  58.         $normalizedCurrency = strtoupper((string) $resolvedCurrency);
  59.         $normalizedLocale = strtolower(str_replace('_', '-', $locale ?? $this->getSessionLocale()));
  60.         try {
  61.             $formatter = new \NumberFormatter($normalizedLocale, \NumberFormatter::CURRENCY);
  62.             $formatted = $formatter->formatCurrency(1, $normalizedCurrency);
  63.             if ($formatted !== false) {
  64.                 $symbol = preg_replace('/[\p{N}\p{Z}\p{P}]/u', '', $formatted);
  65.                 if (is_string($symbol) && trim($symbol) !== '') {
  66.                     return trim($symbol);
  67.                 }
  68.             }
  69.         } catch (\Throwable $throwable) {
  70.             // Fall back to the ISO code below.
  71.         }
  72.         return $normalizedCurrency;
  73.     }
  74.     /**
  75.      * Convertit un montant d'une devise source vers une devise cible.
  76.      * Le résultat est arrondi au supérieur pour conserver un montant exploitable côté métier.
  77.      * @throws Exception
  78.      */
  79.     public function convert($amount, $currencyFrom, $currencyTo, ExchangeRateTypeEnum $type) : ?float
  80.     {
  81.         $exchangeRate = $this->calculateExchangeRate($currencyFrom, $currencyTo, $type);
  82.         return ceil($amount * $exchangeRate);
  83.     }
  84.     /**
  85.      * Récupère le taux de change entre deux devises.
  86.      * Le type choisit le taux : 'buy' (exchangeRateBuy) pour les prix d'achat, 'sale' (exchangeRateSale) pour les prix de vente.
  87.      * Avec une stratégie de markup, le taux de vente défini par la stratégie pour la paire remplace le taux de vente par défaut.
  88.      * Si les devises sont identiques, on renvoie 1 pour éviter une requête inutile.
  89.      * @throws Exception
  90.      */
  91.     public function calculateExchangeRate($currencyFrom, $currencyTo, ExchangeRateTypeEnum $type, ?MarkupStrategy $markupStrategy = null) : float
  92.     {
  93.         if($currencyFrom == $currencyTo){
  94.             return 1.0;
  95.         }else
  96.         {
  97.             if ($type === ExchangeRateTypeEnum::sale && $markupStrategy?->getId() !== null) {
  98.                 $strategyExchange = $this->markupStrategyExchangeRateRepository->findOneByPair($markupStrategy, $currencyFrom, $currencyTo);
  99.                 if ($strategyExchange !== null) {
  100.                     return (float) $strategyExchange->getExchangeRateSale();
  101.                 }
  102.             }
  103.             $currencyExchange = $this->currencyExchangerateRepository->findOneBy(
  104.                 [
  105.                     'currencyFrom' => $currencyFrom,
  106.                     'currencyTo' => $currencyTo
  107.                 ]
  108.             );
  109.             if($currencyExchange!=null){
  110.                 return $currencyExchange->getExchangeRate($type);
  111.             }else{
  112.                 throw new Exception("Currency ExchangeRate Exception");
  113.                 return 1;
  114.             }
  115.         }
  116.     }
  117.     /**
  118.      * Retourne la liste des devises disponibles dans les taux d'échange configurés.
  119.      * Utile pour alimenter les sélecteurs de devise en front et en back.
  120.      */
  121.     public function  getCurrenciesFromExchange(): array
  122.     {
  123.         $exchangeCurrencies = $this->currencyExchangerateRepository->findAll();
  124.         $currenciesToValues = array_map(function($currency) {
  125.             return $currency->getCurrencyTo();
  126.         }, $exchangeCurrencies);
  127.         $currencyArrayWithValues = [];
  128.         foreach ($currenciesToValues as $currency) {
  129.             $currencyArrayWithValues[$currency] = $currency;
  130.         }
  131.         return $currencyArrayWithValues;
  132.     }
  133.     /**
  134.      * Détermine la devise de vente liée au user connecté.
  135.      * Si aucun customer n'est associé, on garde la devise de référence du projet.
  136.      */
  137.     public function getSaleCurrency(?UserInterface $user) : ?string
  138.     {
  139.         $customer = ($user?$user->getCustomer() : null);
  140.         if(is_null($user) || is_null($customer)){
  141. //            return $this->getSessionCurrency();
  142.             return $this->parameterService->getReferenceCurrency();
  143.         }
  144.         return $customer->getCurrency();
  145.     }
  146.     /**
  147.      * Retourne le code ISO4217 numérique de certaines devises utilisées par les passerelles de paiement.
  148.      */
  149.     public function getISO4217Code(?string $currency) : ?int // 3 characters
  150.     {
  151.         return match ($currency) {
  152.             'TND' => 788,
  153.             'EUR' => 200,
  154.             'USD' => 100,
  155.             default => null,
  156.         };
  157.     }
  158. }