SendCcasTransactionsExportToPrestatairesCommand.php 9.79 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

declare(strict_types=1);

namespace App\Command;

use App\Entity\Flux;
use App\Entity\GlobalParameter;
use App\Entity\Prestataire;
Yvon committed
10
use App\Entity\User;
11 12
use App\Utils\CustomEntityManager;
use App\Utils\OperationUtils;
13
use IntlDateFormatter;
14 15 16 17 18 19 20 21 22 23 24 25 26
use NumberFormatter;
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 Symfony\Component\HttpKernel\KernelInterface;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;

/**
27 28 29 30 31 32
 * This command is part of the CCAS reconversion process.
 * It is used in conjonction with ReconversionCcasMonaPrestataires.
 * It has been separated from ReconversionCcasMonaPrestataires
 * so that we can replay it in case of mailing issue
 * without performing the "Demande de reconversion" again.
 *
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
 * @SuppressWarnings(PHPMD.CyclomaticComplexity)
 */
class SendCcasTransactionsExportToPrestatairesCommand extends Command
{

    protected static $defaultName = 'kohinos:ssa:export-ccas-transactions';

    protected $em;
    protected $mailer;
    protected $templating;
    protected $io;
    protected $param;
    protected $operationUtils;

    public function __construct(
        CustomEntityManager $em,
        \Swift_Mailer $mailer,
        Environment $templating,
        OperationUtils $operationUtils
    ) {
        $this->em = $em;
        $this->mailer = $mailer;
        $this->templating = $templating;
        $this->operationUtils = $operationUtils;
        parent::__construct();
    }

    /**
     * @param Prestataire $p
62
     * @param $monthYearStr
63 64 65 66 67 68 69
     * @param $montant
     * @param $path
     *
     * @throws LoaderError
     * @throws RuntimeError
     * @throws SyntaxError
     */
70
    public function prepareMail(Prestataire $p, $monthYearStr, $montant): \Swift_Message
71 72
    {
        $this->io->text('Envoi du mail pour le prestataire ' . $p->getRaison());
73
        $subject = "Expérimentation de Sécurité Sociale de l’Alimentation en Gironde – Facture CCAS $monthYearStr";
74
        $globalParamRepo = $this->em->getRepository(GlobalParameter::class);
Yvon committed
75 76 77 78 79 80 81
        //Send to prestataire
        //Send copy to tresoriers + gestionnaire de groupe (or default contact if linked gestionnaire de groupe does not exists)
        $copyTo = array();
        $users = $this->em->getRepository(User::class)->findByRole('ROLE_TRESORIER');
        foreach ($users as $userTresorier) {
            $copyTo[] = $userTresorier->getEmail();
        }
82 83 84
        foreach ($globalParamRepo->getMailOfGestionnaireDeGroupeAndDefaultContact($p) as $copyToEmail) {
            $copyTo[] = $copyToEmail;
        }
85 86
        $mail = (new \Swift_Message($subject))
            ->setFrom($globalParamRepo->val(GlobalParameter::MLC_NOTIF_EMAIL))
Yvon committed
87
            ->setTo($p->getGestionnairesEmailsArray())
Yvon committed
88
            ->setCc($copyTo)
89 90 91 92
            ->setBody(
                $this->templating->render(
                    '@kohinos/email/tav/ccas_transactions.html.twig',
                    [
93
                        'subject' => "Facture CCAS $monthYearStr",
94
                        'montant' => $montant,
95
                        'monthyear' => $monthYearStr
96 97 98 99 100 101 102
                    ]
                ),
                'text/html'
            );
        return $mail;
    }

103 104 105 106 107
    private function fputcsvSeparatedBySemicolon($file, $arr)
    {
        fputcsv($file, $arr, ";");
    }

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    /**
     * @param $year
     * @param int         $month
     * @param Prestataire $p
     * @param string      $dir
     * @param $data
     * @param NumberFormatter $nf
     *
     * @return array
     */
    public function createExportFile($year, int $month, Prestataire $p, string $dir, $data, NumberFormatter $nf): array
    {
        $filename = sprintf(
            'ssagir_ccastrans_%s_%s.%s',
            $year . '-' . $month,
            $p->getSlug(),
            'csv'
        );
        $path = $dir . '/' . $filename;

        $file = fopen($path, 'w');

        //Write header
131 132
        $this->fputcsvSeparatedBySemicolon($file, [
            "Numero d'anonymisation",
133 134 135 136 137 138 139 140 141 142 143 144 145 146
            'Montant (€)',
            'Montant en lettres',
            'Date',
        ]);

        //Init data used in loop to write intermediate totals
        $prestaTotal = 0;
        $clientTotal = 0;
        $previousAnonymousToken = $data[0]['anonymous_token'];

        //Write body
        foreach ($data as $row) {
            //Write intermediate total line before moving to next client
            if ($previousAnonymousToken !== $row['anonymous_token']) {
147
                $this->fputcsvSeparatedBySemicolon($file, [
148
                    'TOTAL ' . $previousAnonymousToken,
149 150 151 152 153
                    $clientTotal,
                    $nf->format($clientTotal),
                    '',
                ]);
                $clientTotal = 0;
154
                $previousAnonymousToken = $row['anonymous_token'];
155 156
            }
            //Write transaction line
157
            $this->fputcsvSeparatedBySemicolon($file, [
158 159 160 161 162 163 164 165 166
                $row['anonymous_token'],
                $row['montant'],
                $this->currencySpellout($nf, $row['montant']),
                $row['created_at'],
            ]);
            $clientTotal += $row['montant'];
            $prestaTotal += $row['montant'];
        }
        //Write last intermediate total line
167
        $this->fputcsvSeparatedBySemicolon($file, [
168 169 170 171 172 173
            'TOTAL ' . $row['anonymous_token'],
            number_format($clientTotal, 2),
            $this->currencySpellout($nf, $clientTotal),
            '',
        ]);
        //Write final total line
174
        $this->fputcsvSeparatedBySemicolon($file, [
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 209 210 211 212 213 214 215 216 217 218
            'TOTAL ' . $p->getRaison(),
            number_format($prestaTotal, 2),
            $this->currencySpellout($nf, $prestaTotal),
            '',
        ]);

        fclose($file);

        return [$path, $prestaTotal];
    }

    protected function configure()
    {
        $this
            ->setDescription('SSA : envoyer des mails avec export permettant aux prestataires de facturer le ccas')
            ->addOption(
                'prestaid',
                null,
                InputOption::VALUE_REQUIRED,
                "Effectuer l'action pour un seul prestataire."
            )
            ->addOption(
                'yearmonth',
                null,
                InputOption::VALUE_REQUIRED,
                "Effectuer l'action pour le mois YYYYMM."
            );
    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $this->io = new SymfonyStyle($input, $output);
        $prestaid = $input->hasOption('prestaid') ? $input->getOption('prestaid') : null;
        $yearmonth = $input->hasOption('yearmonth') ? $input->getOption('yearmonth') : null;

        $prestaRepo = $this->em->getRepository(Prestataire::class);
        $prestas = $prestaid ? [0 => $prestaRepo->find($prestaid)] : $prestaRepo->findAll();

219 220 221
        $dateFormatter = new IntlDateFormatter('fr_FR', IntlDateFormatter::NONE, IntlDateFormatter::NONE);
        $dateFormatter->setPattern("MMMM Y");
        $date = new \DateTime();
222 223 224
        if ($yearmonth) {
            $year = substr($yearmonth, 0, 4);
            $month = intval(substr($yearmonth, 4, 2));
225 226
            $date->setDate(intval($year),$month,1);
            $monthYearStr = $dateFormatter->format($date);
227
        } else {
228 229 230 231
            $date->modify('previous month');
            $year = $date->format('Y');
            $month = intval($date->format('m'));
            $monthYearStr = $dateFormatter->format($date);
232 233 234 235
        }

        $this->io->title(
            'START. Préparation des exports pour ' . count($prestas) . ' prestataires '
236
            . 'contenant les transactions CCAS pour ' . $monthYearStr
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
        );

        //projectDir is composer.json
        /** @var KernelInterface $kernel */
        $kernel = $this->getApplication()->getKernel();
        $rootDir = $kernel->getContainer()->getParameter('kernel.project_dir');
        $dir = $rootDir . '/ccastransactions';
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

        $nf = new NumberFormatter('fr', NumberFormatter::SPELLOUT);

        foreach ($prestas as $p) {
            /* @var Prestataire $p */
            $data = $this->em->getRepository(Flux::class)->getValidCcasTransactionsByPrestaAndMonth($p, $month, $year);
            //only create export file if there are data
            $path = null;
            $prestaTotal = 0;
            if ($data) {
                list($path, $prestaTotal) = $this->createExportFile($year, $month, $p, $dir, $data, $nf);
            }
            //Send mail as soon as there are data or prestataire is CCAS OK
            //If there is no data, just inform there is nothing to do
            if ($data || $p->getCcasOk()) {
262
                $mail = $this->prepareMail($p, $monthYearStr, $prestaTotal);
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
                if ($path) {
                    $mail->attach(\Swift_Attachment::fromPath($path));
                }
                $this->mailer->send($mail);
            }
        }

        $this->io->success('End');

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

        return 0;
    }

    private function currencySpellout($nf, $montant)
    {
        $amountInCents = round($montant * 100);
        $cents = round($amountInCents % 100, 2);
        $euros = ($amountInCents - $cents) / 100;
        $eurosText = $nf->format($euros) . ' euro' . ($euros > 1 ? 's' : '');
        $centsText = $cents ? ' et ' . $nf->format($cents) . ' centime' . ($cents > 0.01 ? 's' : '') : '';

        return $eurosText . $centsText;
    }
}