SolidoumeCommand.php 18.9 KB
Newer Older
Julien Jorry committed
1 2 3 4 5 6 7
<?php

declare(strict_types=1);

namespace App\Command;

use App\Entity\Adherent;
8
use App\Entity\Flux;
Julien Jorry committed
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
use App\Entity\GlobalParameter;
use App\Entity\Prestataire;
use App\Entity\SolidoumeItem;
use App\Entity\SolidoumeParameter;
use App\Entity\TransactionAdherentPrestataire;
use App\Entity\TransactionPrestataireAdherent;
use App\Entity\User;
use App\Enum\CurrencyEnum;
use App\Enum\MoyenEnum;
use App\Utils\CustomEntityManager;
use App\Utils\OperationUtils;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Twig\Environment;

/**
 * @SuppressWarnings(PHPMD.CyclomaticComplexity)
 */
class SolidoumeCommand extends Command
{
    protected static $defaultName = 'kohinos:solidoume:execute';

    protected $em;
    protected $logger;
    protected $mailer;
    protected $templating;
    protected $io;
    protected $param;
    protected $operationUtils;
    protected $isTest;
    protected $testExecute;
    protected $itemsTest;

    public function __construct(
        CustomEntityManager $em,
        LoggerInterface $cronLogger,
        \Swift_Mailer $mailer,
        Environment $templating,
        OperationUtils $operationUtils
    ) {
        $this->em = $em;
        $this->logger = $cronLogger;
        $this->mailer = $mailer;
        $this->templating = $templating;
        $this->operationUtils = $operationUtils;
        $this->isTest = false;
        $this->testExecute = false;
        $this->itemsTest = null;
        parent::__construct();
    }

    protected function configure()
    {
        $this
            ->setDescription('Sécurité sociale alimentaire : executer les opérations')
            ->setDefinition([
                new InputOption('test', null, InputOption::VALUE_NONE, 'For testing purpose : only print testresult of reminder email and taking money the right day'),
                new InputOption('execute', null, InputOption::VALUE_NONE, 'For testing purpose : execute program even if it\s not the correct date fo execution !'),
            ])
        ;
    }

    /**
76 77 78 79 80 81
     * Execute program Solidoume.
     *
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return int
Julien Jorry committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $this->io = new SymfonyStyle($input, $output);
        $this->param = $this->em->getRepository(SolidoumeParameter::class)->findTheOne();
        if (empty($this->param)) {
            $this->io->error('Sécurité sociale alimentaire non paramétrée !');

            return 0;
        }
        $this->em->getConnection()->getConfiguration()->setSQLLogger(null);
        $this->isTest = $input->getOption('test');
        $this->testExecute = $input->getOption('execute');

        $this->io->title('Start');
        $this->executeReminders();
98 99 100 101
        // Envoi d'un quizz uniquement pour les utilisateurs de Solidoume !
        if ($this->em->getRepository(SolidoumeParameter::class)->getValueOf('name') == 'Solidoume') {
            $this->executeQuizz();
        }
Julien Jorry committed
102 103 104 105 106 107 108 109 110 111 112
        $this->executeTaking();
        sleep(1);
        $this->executeProgram();
        $this->io->success('End');

        $memoryUsage = memory_get_usage(true) / 1024 / 1024;
        $this->io->text("Batch finished with memory: ${memoryUsage}M");

        return 0;
    }

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    /**
     * Execute quizz : send quizz to all participant who have participated since 3 months minimum
     */
    private function executeQuizz()
    {
        $this->io->title('START : Envoi du questionnaire');
        $items = $this->em->getRepository(SolidoumeItem::class)->findBy(['enabled' => true]);
        foreach ($items as $item) {
            if ($this->hasToSendQuizz($item)) {
                $item->setQuizzSended(true);
                if (!$this->isTest) {
                    $this->em->persist($item);
                    $this->em->flush();
                }
                $this->sendQuizz($item);
            }
        }
    }

Julien Jorry committed
132
    /**
133
     * Execute email reminder : If balance of account if not enough x days before date of paiement => send email.
Julien Jorry committed
134 135 136 137
     */
    private function executeReminders()
    {
        $this->io->title('START : Rappel par email');
138 139
        $items = $this->em->getRepository(SolidoumeItem::class)->findBy(['enabled' => true]);
        
Julien Jorry committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        foreach ($items as $item) {
            if ($this->hasToExecuteReminders($item)) {
                $amount = $item->getAmount();
                $accountEmlc = $item->getAdherent()->getAccountWithCurrency(CurrencyEnum::CURRENCY_EMLC);
                if (null != $accountEmlc) {
                    if ($accountEmlc->getBalance() < $amount) {
                        // L'adherent n'a pas assez d'argent sur son ecompte !
                        if ($this->isTest) {
                            $this->io->error('Balance : ' . $accountEmlc->getBalance() . ', montant : ' . $amount);
                        }
                        $this->sendReminder($item);
                    }
                } else {
                    $this->io->error("L'adherent " . $adherent->__toString() . " n'a pas de compte emlc !");
                }
            }
        }
    }

    /**
160 161 162
     * Send email reminder.
     *
     * @param SolidoumeItem $solidoumeItem
Julien Jorry committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
     */
    private function sendReminder(SolidoumeItem $solidoumeItem)
    {
        $adherent = $solidoumeItem->getAdherent();
        $this->io->success("Envoi de l'email de rappel à l'adhérent : " . $adherent->__toString());

        $subject = $this->em->getRepository(SolidoumeParameter::class)->getValueOf('name') . ' : Votre compte n\'a pas un solde suffisant !';
        $mail = (new \Swift_Message($subject))
            ->setFrom($this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_NOTIF_EMAIL))
            ->setTo($adherent->getUser()->getEmail())
            ->setBody(
                $this->templating->render(
                    '@kohinos/email/solidoume/reminder.html.twig',
                    [
                        'subject' => $subject,
                        'item' => $solidoumeItem,
                    ]
                ),
                'text/html'
            );
        if (!$this->isTest) {
            $this->mailer->send($mail);
        }
    }

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    /**
     * Send Quizz email.
     *
     * @param SolidoumeItem $solidoumeItem
     */
    private function sendQuizz(SolidoumeItem $solidoumeItem)
    {
        $adherent = $solidoumeItem->getAdherent();
        $this->io->success("Envoi du questionnaire à l'adhérent : " . $adherent->__toString());

        $subject = 'Vos retours sur ' . $this->em->getRepository(SolidoumeParameter::class)->getValueOf('name') . ' !';
        $mail = (new \Swift_Message($subject))
            ->setFrom($this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_NOTIF_EMAIL))
            ->setTo($adherent->getUser()->getEmail())
            ->setBody(
                $this->templating->render(
                    '@kohinos/email/solidoume/quizz.html.twig',
                    [
                        'subject' => $subject,
                        'item' => $solidoumeItem,
                    ]
                ),
                'text/html'
            );
        if (!$this->isTest) {
            $this->mailer->send($mail);
        }
    }

Julien Jorry committed
217
    /**
218
     * Take money of participant of solidoume if date of today is same as paiementDate.
Julien Jorry committed
219 220 221 222 223 224
     */
    private function executeTaking()
    {
        $this->io->title('START : prélèvement du jour');
        $nowDay = (new \DateTime('now', new \DateTimeZone('UTC')))->format('d');
        $nowMonth = intval((new \DateTime('now', new \DateTimeZone('UTC')))->format('Ym'));
225 226
        $items = $this->em->getRepository(SolidoumeItem::class)->findBy(['enabled' => true, 'paiementDate' => $nowDay]);

Julien Jorry committed
227 228 229 230 231 232 233 234 235 236 237 238 239 240
        try {
            $em = $this->em;
            $isTest = $this->isTest;
            $io = $this->io;
            $operationUtils = $this->operationUtils;
            $callback = function () use ($em, $items, $isTest, $io, $nowDay, $nowMonth, $operationUtils) {
                foreach ($items as $item) {
                    // Prélèvement des emlc sur chaque compte adhérent participant au programme
                    $amount = $item->getAmount();
                    $accountEmlc = $item->getAdherent()->getAccountWithCurrency(CurrencyEnum::CURRENCY_EMLC);
                    if (null != $accountEmlc
                        && $item->getPaiementDate() == $nowDay
                        && $item->getLastMonthPayed() != $nowMonth) {
                        if ($accountEmlc->getBalance() < $amount) {
241
                            $io->error($item->getAdherent()->__toString() . ' : Solde de l\'adherent inférieur au montant à prélever (Solde : ' . $accountEmlc->getBalance() . ' eMLC) !');
Julien Jorry committed
242 243 244 245 246 247 248 249 250 251
                            $item->setEnabled(false);
                            if (!$isTest) {
                                $em->persist($item);
                            }
                            // @TODO : alerter l'utilisateur ?
                        } else {
                            $flux = new TransactionAdherentPrestataire();
                            $flux->setExpediteur($item->getAdherent());
                            $flux->setDestinataire($em->getRepository(Prestataire::class)->getPrestataireSolidoume());
                            $flux->setMontant($amount);
252
                            $flux->setData($item->toArray());
Julien Jorry committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
                            $flux->setMoyen(MoyenEnum::MOYEN_EMLC);
                            $now = (new \Datetime('now'))->format('d/m/Y H:i:s');
                            $flux->setReference($em->getRepository(SolidoumeParameter::class)->getValueOf('name') . ' prélèvement en date du ' . $now);

                            $item->setLastMonthPayed($nowMonth);

                            if (!$isTest) {
                                $em->persist($flux);
                                $em->persist($item);
                                // Write operations for this flux !
                                $operationUtils->executeOperations($flux);
                                $em->flush();
                            } else {
                            }

                            $io->success("Prélèvement $amount\nFlux : " . $flux->__toString() . "\nItem : " . $item->__toString());
                        }
                    }
                }
            };
            $this->em->transactional($callback);
        } catch (\Exception $e) {
            // @TODO : tmp
            throw $e;
        }
    }

    /**
281
     * Execute solidoume repartition of money recolted if date of today is same as executionDate.
Julien Jorry committed
282 283 284 285
     */
    private function executeProgram()
    {
        $nowDay = (new \DateTime('now', new \DateTimeZone('UTC')))->format('d');
286

Julien Jorry committed
287 288 289 290
        if (!$this->testExecute && $nowDay != $this->param->getExecutionDate()) {
            $this->io->warning("Ce n'est pas le jour d'execution du programme (" . $this->param->getExecutionDate() . ')');
        } else {
            $this->io->title('START : Répartition de la somme récoltée');
291 292
            $items = $this->em->getRepository(SolidoumeItem::class)->findBy(['enabled' => true]);
            
Julien Jorry committed
293 294 295
            $total = 0;
            $countPerson = 0;
            $countParticipants = 0;
296
            $participants = [];
Julien Jorry committed
297
            foreach ($items as $item) {
298
                if ($this->isItemPayedThisMonth($item)) {
299
                    $datas = $this->em->getRepository(Flux::class)->getQueryByAdherentAndDestinataire($item->getAdherent(), $this->em->getRepository(Prestataire::class)->getPrestataireSolidoume(), 'adherent_prestataire');
300 301
                    $lastPrelevement = null;
                    foreach ($datas as $data) {
302 303 304
                        if ($data->getCreatedAt()->format('d') <= $this->param->getExecutionDate() && $data->getCreatedAt()->format('m') == ((new \DateTime('now', new \DateTimeZone('UTC')))->format('m'))) {
                            $lastPrelevement = $data;
                        } elseif ($data->getCreatedAt()->format('d') > $this->param->getExecutionDate() && $data->getCreatedAt()->format('m') == ((new \DateTime('now', new \DateTimeZone('UTC')))->format('m')-1)) {
305 306
                            $lastPrelevement = $data;
                        }
307
                    }
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
                    if ($lastPrelevement != null) {
                        $datas = $this->em->getRepository(Flux::class)->getQueryByAdherentAndDestinataire($item->getAdherent(), $this->em->getRepository(Prestataire::class)->getPrestataireSolidoume(), 'prestataire_adherent');
                        $lastPaiement = null;
                        foreach ($datas as $data) {
                            if ($data->getCreatedAt()->format('m') == ((new \DateTime('now', new \DateTimeZone('UTC')))->format('m'))) {
                                $lastPaiement = $data;
                            }
                        }
                        if ($lastPaiement == null) {
                            $total += $lastPrelevement->getMontant();
                            if (!$item->getIsDonation()) {
                                ++$countParticipants;
                            }
                            $participants[] = $item;
                            ++$countPerson;
323
                        }
Julien Jorry committed
324 325 326 327 328 329 330 331 332 333 334 335 336 337
                    }
                }
            }
            $totalByParticipant = round((($total / $countParticipants) * ((100 - $this->param->getCommission()) / 100)), 2, PHP_ROUND_HALF_DOWN);
            $this->io->success('Total de eMLC récolté : ' . $total . ' !');
            $this->io->success('Nombre de personnes : ' . $countPerson . ' !');
            $this->io->success('Nombre de participants au programme : ' . $countParticipants . ' !');
            $this->io->success('Total par participants (sans commission) : ' . ($total / $countParticipants) . ' !');
            $this->io->success('Total par participants (avec commission de ' . $this->param->getCommission() . '%) : ' . $totalByParticipant . ' !');
            try {
                $em = $this->em;
                $isTest = $this->isTest;
                $io = $this->io;
                $operationUtils = $this->operationUtils;
338 339
                $callback = function () use ($em, $participants, $isTest, $io, $totalByParticipant, $operationUtils) {
                    foreach ($participants as $item) {
340
                        if ($this->isItemPayedThisMonth($item) && !$item->getIsDonation()) {
Julien Jorry committed
341 342 343 344 345 346 347
                            // Envoi de l'emlc sur le compte de l'adherent
                            $flux = new TransactionPrestataireAdherent();
                            $flux->setExpediteur($em->getRepository(Prestataire::class)->getPrestataireSolidoume());
                            $flux->setDestinataire($item->getAdherent());
                            $flux->setMontant($totalByParticipant);
                            $flux->setMoyen(MoyenEnum::MOYEN_EMLC);
                            $now = (new \Datetime('now'))->format('d/m/Y H:i:s');
348
                            $flux->setReference('Correction ' . $em->getRepository(SolidoumeParameter::class)->getValueOf('name') . ' ' . $now);
Julien Jorry committed
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
                            if (!$isTest) {
                                $em->persist($flux);
                                // Write operations for this flux !
                                $operationUtils->executeOperations($flux);
                                $em->flush();
                            }
                            $io->success("Paiement solidoume\nFlux : " . $flux->__toString() . "\nItem : " . $item->__toString());
                        }
                        if (!$item->getIsRecurrent()) {
                            // Disabled all non recurrent paiement
                            $item->setEnabled(false);
                            if (!$isTest) {
                                $em->persist($item);
                            } else {
                                $io->text('Paiement non recurrent donc désactivé ! ' . $item->__toString());
                            }
                        }
                    }
                    if (!$isTest) {
                        $em->flush();
                        $em->clear();
                    }
                };
                $this->em->transactional($callback);
            } catch (\Exception $e) {
                $this->io->error($e->getMessage());
            }
        }

        return null;
    }

381 382 383 384 385 386
    private function isItemPayedThisMonth(SolidoumeItem $item): bool
    {
        $nowMonth = intval((new \DateTime('now', new \DateTimeZone('UTC')))->format('Ym'));
        $lastMonth = intval((new \DateTime('now -1month', new \DateTimeZone('UTC')))->format('Ym'));
        if ($item->isEnabled() && null != $item->getLastMonthPayed()) {
            if ($item->getPaiementDate() <= $this->param->getExecutionDate() && $item->getPaiementDate() >= 1) {
387
                if ($item->getLastMonthPayed() >= $nowMonth) {
388 389 390
                    return true;
                }
            } else {
391
                if ($item->getLastMonthPayed() >= $lastMonth) {
392 393 394 395 396 397 398 399
                    return true;
                }
            }
        }

        return false;
    }

400 401 402 403 404 405 406 407 408 409 410
    private function hasToSendQuizz(SolidoumeItem $item)
    {
        $datas = $this->em->getRepository(Flux::class)->getQueryByAdherentAndDestinataire($item->getAdherent(), $this->em->getRepository(Prestataire::class)->getPrestataireSolidoume(), 'adherent_prestataire');

        if (count($datas) >= 3 && !$item->isQuizzSended()) {
            return true;
        }

        return false;
    }

Julien Jorry committed
411
    /**
412 413 414 415 416
     * Has to execute reminder by email ? Check date of paiement choose by adherent and number of days before remind.
     *
     * @param SolidoumeItem $item
     *
     * @return bool
Julien Jorry committed
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
     */
    private function hasToExecuteReminders(SolidoumeItem $item)
    {
        $nowDay = intval((new \DateTime('now', new \DateTimeZone('UTC')))->format('d'));
        $reminderDays = $this->param->getReminderDays();
        $executionDate = intval($item->getPaiementDate());
        if ($nowDay > $executionDate) {
            $d = new \DateTime('now');
            $d->modify('first day of next month');
            $nextExecution = $d->format('Ym') . ($executionDate < 10 ? '0' . $executionDate : $executionDate);
            $reminingDate = (new \DateTime('+' . $reminderDays . ' days', new \DateTimeZone('UTC')))->format('Ymd');
            if ($reminingDate == $nextExecution) {
                return true;
            }
        } else {
            $nextExecution = (new \DateTime('now', new \DateTimeZone('UTC')))->format('Ym') . ($executionDate < 10 ? '0' . $executionDate : $executionDate);
            $reminingDate = (new \DateTime('+' . $reminderDays . ' days', new \DateTimeZone('UTC')))->format('Ymd');
            if ($reminingDate == $nextExecution) {
                return true;
            }
        }

        return false;
    }
}