OperationUtils.php 11.6 KB
Newer Older
Julien Jorry committed
1 2 3 4 5 6 7 8 9
<?php

namespace App\Utils;

use App\Entity\AccountAdherent;
use App\Entity\AccountComptoir;
use App\Entity\AccountGroupe;
use App\Entity\AccountPrestataire;
use App\Entity\AccountSiege;
10
use App\Entity\AchatMonnaie;
Julien Jorry committed
11 12
use App\Entity\Adherent;
use App\Entity\Comptoir;
13
use App\Entity\Flux;
Julien Jorry committed
14 15 16 17 18 19 20
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;
21
use App\Entity\Reconversion;
Julien Jorry committed
22
use App\Entity\Siege;
23
use App\Entity\Transaction;
24
use App\Entity\VenteEmlc;
Julien Jorry committed
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
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')
68
                ->setParameter('datemin', $request->get('formListOperations')['datemin'])  // Date only comparison: error in queries comparing datetimes with some MYSQL versions
Julien Jorry committed
69 70 71 72 73
            ;
        }
        if (!empty($request->get('formListOperations')['datemax'])) {
            $qb
                ->andWhere('a.createdAt <= :datemax')
74
                ->setParameter('datemax', $request->get('formListOperations')['datemax'])
Julien Jorry committed
75 76 77 78 79 80 81 82 83 84 85
            ;
        }
        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'])
            ;
        }
86 87 88 89 90 91 92
        if (!empty($request->get('formListOperations')['showMonAPurchaseOnly'])) {
            $qb
                ->andWhere('flux.type IN (:type_achat_monnaie_adherent, :type_vente_emlc_adherent)')
                ->setParameter('type_achat_monnaie_adherent', AchatMonnaie::TYPE_ACHAT_ADHERENT)
                ->setParameter('type_vente_emlc_adherent', VenteEmlc::TYPE_VENTE_EMLC_ADHERENT)
            ;
        }
Julien Jorry committed
93 94 95 96 97 98 99 100 101 102

        return $qb->getQuery();
    }

    public function executeOperations(FluxInterface $flux)
    {
        try {
            $em = $this->em;
            $callback = function () use ($em, $flux) {
                $operations = $flux->getAllOperations($em);
103 104
                // 0/ Merge operations on same account (for cotisation+don and achatmonnaie+don) to check if balance is enough
                $operationsToCheck = [];
Julien Jorry committed
105
                foreach ($operations as $operation) {
106 107 108 109 110 111 112 113 114 115
                    if (!empty($operationsToCheck) && isset($operationsToCheck[$operation->getAccount()->getId()->toString()])) {
                        $op = $operationsToCheck[$operation->getAccount()->getId()->toString()];
                        $op->setMontant($op->getMontant() + $operation->getMontant());
                        $operationsToCheck[$operation->getAccount()->getId()->toString()] = $op;
                    } else {
                        $operationsToCheck[$operation->getAccount()->getId()->toString()] = $operation;
                    }
                }
                // 1/ Check if all operations can be done without erros
                foreach ($operationsToCheck as $operation) {
Julien Jorry committed
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
                    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);
Yvon committed
148 149 150 151 152 153 154 155
                    /*
                     * Apply operations on account amounts.
                     * One flux between two acounts is composed of two operations.
                     * These operations are configured by getAllOperations methods.
                     * These operations can be positive or negative.
                     * For example, a flux of type Reconversion will decrease
                     * accounts of prestataire and siege (see Reconversion.php).
                     */
Julien Jorry committed
156
                    $account->addAmount($operation->getMontant());
Yvon committed
157
                    //Update special account "balance ccas" for some operations only
158 159 160 161 162 163
                    $updateBalanceCcas =
                        //only process isCcas or reconversionCcas $flux
                        ( $flux instanceof Transaction && $flux->getIsCcas() || $flux instanceof Reconversion && $flux->getReconversionCcas() )
                        //only process the prestataire side of the flux
                        && $account instanceof AccountPrestataire;
                    if ($updateBalanceCcas) {
164 165
                        $account->addAmountCcas($operation->getMontant());
                    }
Julien Jorry committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
                    $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');
194
        } elseif (null != $this->session->get('_groupegere') && ($user->isGranted('ROLE_GESTION_GROUPE') || $user->isGranted('ROLE_CONTACT'))) {
Julien Jorry committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
            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)
    {
210 211 212
        if ($this->em->getFilters()->isEnabled('enabled_filter')) {
            $this->em->getFilters()->disable('enabled_filter');
        }
Julien Jorry committed
213 214 215 216 217 218 219
        if (null == $this->security->getUser()) {
            return null;
        }
        $object = $this->getCurrentAccountable($this->security->getUser());
        $repo = null;
        $account = null;
        if ($object instanceof Prestataire) {
220 221 222 223 224
            if (null != $currency) {
                $account = $this->em->getRepository(AccountPrestataire::class)->findOneBy(['prestataire' => $object, 'currency' => $currency]);
            } else {
                $account = $this->em->getRepository(AccountPrestataire::class)->findOneBy(['prestataire' => $object, 'currency' => CurrencyEnum::CURRENCY_EMLC]);
            }
Julien Jorry committed
225 226
            $repo = $this->em->getRepository(OperationPrestataire::class);
        } elseif ($object instanceof Adherent) {
227 228 229 230 231
            if (null != $currency) {
                $account = $this->em->getRepository(AccountAdherent::class)->findOneBy(['adherent' => $object, 'currency' => $currency]);
            } else {
                $account = $this->em->getRepository(AccountAdherent::class)->findOneBy(['adherent' => $object, 'currency' => CurrencyEnum::CURRENCY_EMLC]);
            }
Julien Jorry committed
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
            $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);
    }
}