OperationUtils.php 8.67 KB
Newer Older
Julien Jorry committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
<?php

namespace App\Utils;

use App\Entity\AccountAdherent;
use App\Entity\AccountComptoir;
use App\Entity\AccountGroupe;
use App\Entity\AccountPrestataire;
use App\Entity\AccountSiege;
use App\Entity\Adherent;
use App\Entity\Comptoir;
use App\Entity\Groupe;
use App\Entity\OperationAdherent;
use App\Entity\OperationComptoir;
use App\Entity\OperationGroupe;
use App\Entity\OperationPrestataire;
use App\Entity\OperationSiege;
use App\Entity\Prestataire;
use App\Entity\Siege;
use App\Enum\CurrencyEnum;
use App\Enum\MoyenEnum;
use App\Events\FluxEvent;
use App\Events\MLCEvents;
use App\Flux\AccountInterface;
use App\Flux\FluxInterface;
use Doctrine\DBAL\LockMode;
use Doctrine\ORM\EntityRepository;
use FOS\UserBundle\Model\UserInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Security;

class OperationUtils
{
    private $em;
    private $session;
    private $security;
    private $eventDispatcher;

    public function __construct(CustomEntityManager $em, SessionInterface $session, Security $security, EventDispatcherInterface $eventDispatcher)
    {
        $this->em = $em;
        $this->session = $session;
        $this->security = $security;
        $this->eventDispatcher = $eventDispatcher;
    }

    private function getQueryOperations(EntityRepository $repo, AccountInterface $account, Request $request)
    {
        $qb = $repo
            ->createQueryBuilder('a')
            ->addSelect('flux')
            ->leftJoin('a.flux', 'flux')
            ->andWhere('a.account = :account')
            ->setParameter('account', $account->getId())
            ->orderBy('a.createdAt', 'DESC')
        ;

        if (!empty($request->get('formListOperations')['datemin'])) {
            $qb
                ->andWhere('a.createdAt >= :datemin')
                ->setParameter('datemin', $request->get('formListOperations')['datemin'] . ' 00:00:00')
            ;
        }
        if (!empty($request->get('formListOperations')['datemax'])) {
            $qb
                ->andWhere('a.createdAt <= :datemax')
                ->setParameter('datemax', $request->get('formListOperations')['datemax'] . ' 23:59:59')
            ;
        }
        if (!empty($request->get('formListOperations')['moyen'])) {
            if (!in_array(($request->get('formListOperations')['moyen']), MoyenEnum::getAvailableTypes())) {
                throw new \InvalidArgumentException('Moyen de paiement invalide !');
            }
            $qb
                ->andWhere('flux.moyen = :moyen')
                ->setParameter('moyen', $request->get('formListOperations')['moyen'])
            ;
        }

        return $qb->getQuery();
    }

    public function executeOperations(FluxInterface $flux)
    {
        try {
            $em = $this->em;
            $callback = function () use ($em, $flux) {
                $operations = $flux->getAllOperations($em);
                // 1/ Check if all operations can be donde without erros
                foreach ($operations as $operation) {
                    if (null == $operation->getAccount()) {
                        throw new \Exception('No account !!');
                    }
                    if ($operation->getAccount()->getCurrency() != $operation->getCurrency()) {
                        throw new \Exception("Account's currency different from operation !");
                    }

                    // Get repository inside callable to make sure EntityManager is valid
                    $class = $em->getClassMetadata(get_class($operation->getAccount()));
                    $accounts = $em->getRepository($class->getName());
                    // Fetch account with FOR UPDATE write lock
                    $account = $accounts->find(
                        $operation->getAccount()->getId(),
                        LockMode::PESSIMISTIC_WRITE
                    );

                    $newAccountBalance = $account->getBalance() + $operation->getMontant();
                    if ($newAccountBalance < 0) {
                        throw new \Exception('Operation impossible, montant supérieur au solde !');
                    }
                }
                // 2/ If all is ok, persist operations and new account's balance !
                foreach ($operations as $operation) {
                    // Get repository inside callable to make sure EntityManager is valid
                    $class = $em->getClassMetadata(get_class($operation->getAccount()));
                    $accounts = $em->getRepository($class->getName());
                    // Fetch account with FOR UPDATE write lock
                    $account = $accounts->find(
                        $operation->getAccount()->getId(),
                        LockMode::PESSIMISTIC_WRITE
                    );
                    // $account->addOperation($operation);
                    $account->addAmount($operation->getMontant());
                    $em->persist($operation);
                    $em->persist($account);
                }
                $em->persist($flux);
                $em->flush();
            };
            $this->em->transactional($callback);

            $this->eventDispatcher->dispatch(
                MLCEvents::FLUX,
                new FluxEvent($flux)
            );

            return true;
        } catch (\Exception $e) {
            // @TODO : tmp
            throw $e;
        }
    }

    public function getCurrentAccountable(UserInterface $user)
    {
        if (null != $this->session->get('_prestagere') && ($user->isGranted('ROLE_PRESTATAIRE') || $user->isGranted('ROLE_CAISSIER'))) {
            return $this->session->get('_prestagere');
        } elseif (null != $user->getAdherent() && $user->isGranted('ROLE_ADHERENT')) {
            return $user->getAdherent();
        } elseif (null != $this->session->get('_comptoirgere') && $user->isGranted('ROLE_COMPTOIR')) {
            return $this->session->get('_comptoirgere');
        } elseif (null != $this->session->get('_groupegere') && $user->isGranted('ROLE_GESTION_GROUPE')) {
            return $this->session->get('_groupegere');
        } elseif ($user->isGranted('ROLE_ADMIN_SIEGE')) {
            $siege = $this->em->getRepository(Siege::class)->getTheOne();

            return $siege;
        }

        return null;
    }

    /**
     * @return Account[] Returns an array of Account objects
     */
    public function getUserOperationsByCurrency(Request $request, string $currency = null)
    {
170 171 172
        if ($this->em->getFilters()->isEnabled('enabled_filter')) {
            $this->em->getFilters()->disable('enabled_filter');
        }
Julien Jorry committed
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        if (null == $this->security->getUser()) {
            return null;
        }
        $object = $this->getCurrentAccountable($this->security->getUser());
        $repo = null;
        $account = null;
        if ($object instanceof Prestataire) {
            $account = $this->em->getRepository(AccountPrestataire::class)->findOneBy(['prestataire' => $object, 'currency' => CurrencyEnum::CURRENCY_EMLC]);
            $repo = $this->em->getRepository(OperationPrestataire::class);
        } elseif ($object instanceof Adherent) {
            $account = $this->em->getRepository(AccountAdherent::class)->findOneBy(['adherent' => $object, 'currency' => CurrencyEnum::CURRENCY_EMLC]);
            $repo = $this->em->getRepository(OperationAdherent::class);
        } elseif ($object instanceof Groupe) {
            $account = $this->em->getRepository(AccountGroupe::class)->findOneBy(['groupe' => $object, 'currency' => CurrencyEnum::CURRENCY_MLC]);
            $repo = $this->em->getRepository(OperationGroupe::class);
        } elseif ($object instanceof Comptoir) {
            $account = $this->em->getRepository(AccountComptoir::class)->findOneBy(['comptoir' => $object, 'currency' => CurrencyEnum::CURRENCY_MLC]);
            $repo = $this->em->getRepository(OperationComptoir::class);
        } elseif ($object instanceof Siege) {
            if (null != $currency) {
                if (!in_array($currency, CurrencyEnum::getAvailableTypes())) {
                    throw new \Exception('Opération impossible ! Type de currency  ' . $currency . ' inexistant');
                }
                $account = $object->getAccountWithCurrency($currency);
            } else {
                $account = $this->em->getRepository(AccountSiege::class)->findOneBy(['siege' => $object, 'currency' => CurrencyEnum::CURRENCY_MLC]);
            }
            $repo = $this->em->getRepository(OperationSiege::class);
        }
        if (null == $repo || null == $account) {
            return null;
        }

        return $this->getQueryOperations($repo, $account, $request);
    }
}