FluxController.php 17.3 KB
Newer Older
Julien Jorry committed
1 2 3 4
<?php

namespace App\Controller;

5
use AndrewSvirin\Ebics\Builders\CustomerCreditTransfer\CustomerCreditTransferBuilder;
Julien Jorry committed
6
use App\Entity\Adherent;
7
use App\Entity\Don;
Julien Jorry committed
8
use App\Entity\Flux;
9
use App\Entity\GlobalParameter;
Julien Jorry committed
10 11
use App\Entity\Groupe;
use App\Entity\Prestataire;
12
use App\Entity\Reconversion;
Julien Jorry committed
13 14 15 16 17
use App\Entity\User;
use App\Enum\CurrencyEnum;
use App\Flux\FluxInterface;
use App\Utils\CustomEntityManager;
use App\Utils\OperationUtils;
18
use App\Utils\TAVCotisationUtils;
Julien Jorry committed
19
use FOS\UserBundle\Model\UserManagerInterface;
20
use FOS\UserBundle\Util\TokenGeneratorInterface;
21
use Gamez\Symfony\Component\Serializer\Normalizer\UuidNormalizer;
22
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
Julien Jorry committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36
use Sonata\Exporter\Handler;
use Sonata\Exporter\Source\DoctrineORMQuerySourceIterator;
use Sonata\Exporter\Writer\CsvWriter;
use Sonata\Exporter\Writer\JsonWriter;
use Sonata\Exporter\Writer\XlsWriter;
use Sonata\Exporter\Writer\XmlWriter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Annotation\Route;
37
use Symfony\Component\Routing\RouterInterface;
Julien Jorry committed
38
use Symfony\Component\Security\Core\Security;
39
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
40 41 42
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
Julien Jorry committed
43
use Symfony\Component\Translation\TranslatorInterface;
44
use Symfony\Component\Validator\Validator\ValidatorInterface;
Julien Jorry committed
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
use Twig\Environment;

/**
 * Types de transfert : (Les transferts dans la structure sont les flux de billets détenus par les opérateurs.).
 *
 *  - SIEGE             =>     GROUPES LOCAUX           (Transfert du siège au groupe)
 *  - GROUPE            =>     SIEGE                    (Transfert du groupe au siège)
 *  - GROUPES LOCAUX    =>     COMPTOIRS                (Transfert du groupe au comptoir)
 *  - COMPTOIRS         =>     GROUPES LOCAUX           (Transfert du comptoir au groupe)
 *  - COMPTOIRS         =>     ADHERENTS                (Diffusion de monnaie papier auprès des adhérents)
 *  - COMPTOIRS         =>     PRESTATAIRES             (Diffusion de monnaie papier auprès des prestataires)
 *  - PRESTATAIRES      =>     COMPTOIRS                (Reconversion)
 *
 * Types de transaction :
 *
 *   - PRESTATAIRES     =>    ADHERENTS         (Virement vers un adherent)
 *   - PRESTATAIRES     =>    PRESTATAIRES      (Virement entre prestataires)
 *   - ADHERENTS        =>    PRESTATAIRES      (Paiement numérique)
 *   - SIEGE            =>    ADHERENTS         (Achat de monnaie numérique par CB d'un adhérent)
 *   - SIEGE            =>    PRESTATAIRES      (Achat de monnaie numérique par CB d'un prestataire)
 *   - COMPTOIR         =>    ADHERENTS         (Vente de monnaie numérique à un adhérent)
 *   - COMPTOIR         =>    PRESTATAIRES      (Vente de monnaie numérique à un prestataire)
 *   Changes :
 *   - COMPTOIR         =>    ADHERENTS         (Retrait de monnaie numérique en échange de billets MLC à un adhérent)
 *   - COMPTOIR         =>    PRESTATAIRES      (Retrait de monnaie numérique en échange de billets MLC à un prestataire)
 */
class FluxController extends AbstractController
{
    protected $em;
    protected $security;
    protected $translator;
    protected $eventDispatcher;
    protected $session;
    protected $templating;
    protected $operationUtils;
80 81
    protected $tokenGenerator;
    protected $validator;
82
    protected $userManager;
83
    protected $router;
Julien Jorry committed
84 85 86 87 88 89 90 91

    public function __construct(
        Security $security,
        CustomEntityManager $em,
        TranslatorInterface $translator,
        EventDispatcherInterface $eventDispatcher,
        SessionInterface $session,
        Environment $templating,
92
        OperationUtils $operationUtils,
93
        TAVCotisationUtils $tavCotisationsUtils,
94
        TokenGeneratorInterface $tokenGenerator,
95
        ValidatorInterface $validator,
96
        CsrfTokenManagerInterface $tokenManager,
97 98
        UserManagerInterface $userManager,
        RouterInterface $router
Julien Jorry committed
99 100 101 102 103 104 105 106
    ) {
        $this->security = $security;
        $this->em = $em;
        $this->translator = $translator;
        $this->eventDispatcher = $eventDispatcher;
        $this->session = $session;
        $this->templating = $templating;
        $this->operationUtils = $operationUtils;
107 108
        $this->tokenGenerator = $tokenGenerator;
        $this->validator = $validator;
109
        $this->tokenManager = $tokenManager;
110
        $this->tavCotisationsUtils = $tavCotisationsUtils;
111
        $this->userManager = $userManager;
112
        $this->router = $router;
Julien Jorry committed
113 114 115 116 117 118 119 120 121 122
    }

    protected function manageFluxForm(Request $request, Form $form, $template = '@kohinos/flux/transaction.html.twig', $params = [])
    {
        // @TODO : better error management !! => show error on form instead of exception !
        if (null == $this->security->getUser()) {
            throw new \Exception('[FLUX] Opération impossible ! Utilisateur déconnecté !');
            // return new Response('Opération impossible ! Vous êtes déconnecté !', Response::HTTP_BAD_REQUEST);
        }
        // if (!$request->isXmlHttpRequest()) {
123
        //     return new Response('', Response::HTTP_BAD_REQUEST);
Julien Jorry committed
124 125
        // }
        $form->handleRequest($request);
126
        if ($form->isSubmitted() && !$this->tokenManager->isTokenValid($this->tokenManager->getToken('flux_form'))) {
127 128 129 130
            $referer = $request->headers->get('referer');

            return $this->redirect($referer);
        }
Julien Jorry committed
131
        if ($form->isSubmitted() && $form->isValid()) {
132
            $this->tokenManager->refreshToken('flux_form');
Julien Jorry committed
133
            $flux = $form->getData();
134 135 136 137 138 139 140 141 142 143 144 145 146 147
            try {
                if ($this->operationUtils->executeOperations($flux)) {
                    // Redirect to confirmation page
                    return $this->fluxSuccessRedirection($request, $flux);
                }
            } catch (\Exception $e) {
                $this->addFlash(
                    'error',
                    $this->translator->trans($flux->getType() . '_title', [], 'flux') . ' : ' . $e->getMessage()
                );
                $referer = $request->headers->get('referer');
                if ($referer) {
                    return $this->redirect($referer);
                }
Julien Jorry committed
148 149 150 151 152 153 154 155 156 157 158 159
            }
        }

        return $this->render($template, array_merge([
            'form' => $form->createView(),
        ], $params));
    }

    private function fluxSuccessRedirection(Request $request, FluxInterface $flux)
    {
        $referer = $request->headers->get('referer');
        $template = null;
160 161 162 163
        if ($this->templating->getLoader()->exists('@kohinos/flux/confirmationPage/' . $flux->getParentType() . '.html.twig')) {
            $template = '@kohinos/flux/confirmationPage/' . $flux->getParentType() . '.html.twig';
            if ($this->templating->getLoader()->exists('@kohinos/flux/confirmationPage/' . $flux->getParentType() . '-' . $flux->getType() . '.html.twig')) {
                $template = '@kohinos/flux/confirmationPage/' . $flux->getParentType() . '-' . $flux->getType() . '.html.twig';
Julien Jorry committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
            }
        }
        // Redirect to previous page in no confirmation page exist
        if (null === $template && $referer) {
            $this->addFlash(
                'success',
                $this->translator->trans($flux->getType() . '_title', [], 'flux') . ' : ' . $this->translator->trans('operation_success', [], 'flux')
            );

            return $this->redirect($referer);
        }

        return $this->render($template, [
            'flux' => $flux,
        ]);
    }

181 182 183 184 185 186 187 188
    /**
     * @param Request $request
     * @Route("/credit-transfer-file", name="credit_transfer_file")
     * @IsGranted({"ROLE_TRESORIER", "ROLE_SUPER_ADMIN"})
     * @return Response
     */
    public function creditTransferFileAction(Request $request)
    {
189 190
        //raison, bic and iban from debitor are fetched in global parameters
        $globalParametersRepository = $this->em->getRepository(GlobalParameter::class);
191 192 193
        $raison = $globalParametersRepository->val(GlobalParameter::VIREMENT_RECONVERSION_RAISON_GESTIONNAIRE);
        $bic = $globalParametersRepository->val(GlobalParameter::VIREMENT_RECONVERSION_BIC_GESTIONNAIRE);
        $iban = $globalParametersRepository->val(GlobalParameter::VIREMENT_RECONVERSION_IBAN_GESTIONNAIRE);
194

195 196 197

        //make sure raison, bic and iban are not empty
        if(!$raison || !$bic || !$iban) {
198 199
            $this->addFlash(
                'sonata_flash_error',
200
                "Opération annulée car la raison, l'IBAN ou le BIC du gestionnaire pour les virements de reconversions est vide."
201 202 203 204 205 206 207 208 209
            );
            return $this->redirect($this->router->generate('index') . 'admin/app/reconversion/list');
        }

        //SEPA
        $builder = new CustomerCreditTransferBuilder();

        $customerCreditTransfer = $builder
            ->createInstance(
210 211 212
                $bic,
                $iban,
                $raison
213 214
            );

215
        $reconversions = $this->em->getRepository(Reconversion::class)->findBy(["reconverti" => false, "reconversionCcas" => false]);
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 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 257 258 259 260 261 262 263
        if(!$reconversions) {
            $this->addFlash(
                'sonata_flash_error',
                "Aucune reconversion à traiter."
            );
            return $this->redirect($this->router->generate('index') . 'admin/app/reconversion/list');
        }
        foreach($reconversions as $r) {
            /* @var Reconversion $r */
            /* @var Prestataire $presta */
            $presta = $r->getExpediteur();
            if(!$presta || !$presta->isEnabled()) {
                //fail ; do not flush : we don't want to toggle reconverti when file can't be generated
                $this->addFlash(
                    'sonata_flash_error',
                    "Opération annulée car le prestataire " . $presta->getRaison() . " est désactivé ou introuvable."
                );
                return $this->redirect($this->router->generate('index') . 'admin/app/reconversion/list');
            }
            if(!$presta->getIban() || !$presta->getBic()) {
                //fail ; do not flush : we don't want to toggle reconverti when file can't be generated
                $this->addFlash(
                    'sonata_flash_error',
                    "Opération annulée car l'IBAN ou le BIC du prestataire " . $presta->getRaison() . " est vide."
                );
                return $this->redirect($this->router->generate('index') . 'admin/app/reconversion/list');
            }
            $customerCreditTransfer
                ->addTransaction(
                    $presta->getBic(),
                    $presta->getIban(),
                    $presta->getRaison(),
                    $r->getMontant(),
                    'EUR',
                    'Reconversion MonA vers EUR'
                );
            $r->setReconverti(true);
        }

        $filename = sprintf(
            'credit_transfer_file_%s.%s',
            date('Y_m_d_H_i_s', strtotime('now')),
            'xml'
        );

        //projectDir is composer.json
        $dir = $this->getParameter('kernel.project_dir') . "/reconversions";
        if (!is_dir($dir)) {
264
            mkdir($dir, 0755, true);
265 266 267 268 269 270 271 272 273 274 275
        }

        $path = $dir . "/" . $filename;

        $customerCreditTransfer->popInstance()->save($path);

        $this->em->flush();

        return $this->file($path);
    }

Julien Jorry committed
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    /**
     * Export all operations for a user role.
     *
     * @param Request $request Request
     * @param string  $format  Format of export ('json', 'xml', 'csv', 'xls')
     * @Route("/operation/export/{format}/{currency}", name="exportUserOperation", defaults={"format": "csv", "currency" : "emlc"})
     */
    public function exportUserOperationAction(Request $request, $format = 'csv', string $currency = CurrencyEnum::CURRENCY_EMLC)
    {
        $query = $this->operationUtils->getUserOperationsByCurrency($request, $currency);

        if (null != $query) {
            // Prepare the data source
            $fields = [
                'Date' => 'createdAt',
291 292
                'Expediteur' => 'flux.expediteur',
                'Destinataire' => 'flux.destinataire',
Julien Jorry committed
293 294 295 296
                'Montant' => 'montant',
                'Type parent' => 'flux.parenttype',
                'Type' => 'flux.type',
                'Moyen' => 'flux.moyen',
297
                'Référence' => 'flux.reference',
Julien Jorry committed
298 299 300 301 302 303 304 305 306
            ];
            $source = new DoctrineORMQuerySourceIterator($query, $fields);

            $filename = sprintf(
                'export_operations_%s.%s',
                date('Y_m_d_H_i_s', strtotime('now')),
                $format
            );

307 308 309 310
            foreach ($source as $data) {
                $data['Date'] = (new \Datetime($data['Date']))->format('d/m/Y H:i:s');
                $data['Type'] = $this->translator->trans($data['Type'], [], 'flux');
                $data['Montant'] = number_format($data['Montant'], 2, '.', '');
Julien Jorry committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
            }

            return $this->getResponse(
                $format,
                $filename,
                $source
            );
        } else {
            $this->addFlash(
                'error',
                $this->translator->trans('Export des opérations impossible.')
            );

            return $this->redirectToRoute('index');
        }
    }

    /**
     * Export all transferts / transactions for a user role.
     *
     * @param Request $request Request
     * @param string  $format  Format of export ('json', 'xml', 'csv', 'xls')
     * @Route("/flux/export/{format}/", name="exportUserFlux", defaults={"format": "csv"})
     */
    public function exportFluxAction(Request $request, $format = 'csv')
    {
        //Prepare query depending on user role
        $query = null;
        $user = $this->security->getUser();
        if (null != $this->session->get('_prestagere') && $user->isGranted('ROLE_PRESTATAIRE')) {
            $query = $this->em->getRepository(Flux::class)->getQueryByPrestataire($this->session->get('_prestagere'));
        } elseif (null != $user->getAdherent() && $user->isGranted('ROLE_ADHERENT')) {
            $query = $this->em->getRepository(Flux::class)->getQueryByAdherent($user->getAdherent());
        } elseif (null != $this->session->get('_comptoirgere') && $user->isGranted('ROLE_COMPTOIR')) {
            $query = $this->em->getRepository(Flux::class)->getQueryByComptoir($this->session->get('_comptoirgere'));
        } elseif (null != $this->session->get('_groupegere') && $user->isGranted('ROLE_GESTION_GROUPE')) {
            $query = $this->em->getRepository(Flux::class)->getQueryByGroupe($this->session->get('_groupegere'));
        }

        if (null != $query) {
            // Prepare the data source
            $fields = [
                'Date' => 'createdAt',
                'Expediteur' => 'expediteur',
                'Destinataire' => 'destinataire',
                'Type' => 'type',
                'Montant' => 'montant',
                'Moyen' => 'moyen',
                'Opérateur' => 'operateur',
                'Référence' => 'reference',
            ];
            $source = new DoctrineORMQuerySourceIterator($query, $fields);

            $filename = sprintf(
                'export_flux_%s.%s',
                date('Y_m_d_H_i_s', strtotime('now')),
                $format
            );

370 371 372 373
            foreach ($source as $data) {
                $data['Date'] = (new \Datetime($data['Date']))->format('d/m/Y H:i:s');
                $data['Type'] = $this->translator->trans($data['Type'], [], 'flux');
                $data['Montant'] = number_format($data['Montant'], 2, '.', '');
Julien Jorry committed
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
            }

            return $this->getResponse(
                $format,
                $filename,
                $source
            );
        } else {
            $this->addFlash(
                'error',
                $this->translator->trans('Export impossible.')
            );

            return $this->redirectToRoute('index');
        }
    }

    private function getResponse($format, $filename, $source)
    {
        switch ($format) {
            case 'xls':
                $writer = new XlsWriter('php://output');
                $contentType = 'application/vnd.ms-excel';

                break;
            case 'xml':
                $writer = new XmlWriter('php://output');
                $contentType = 'text/xml';

                break;
            case 'json':
                $writer = new JsonWriter('php://output');
                $contentType = 'application/json';

                break;
            case 'csv':
                $writer = new CsvWriter('php://output', ',', '"', '\\', true, true);
                $contentType = 'text/csv';

                break;
            default:
                throw new \RuntimeException('Invalid format');
        }

        $callback = static function () use ($source, $writer) {
            $handler = Handler::create($source, $writer);
            $handler->export();
        };

        return new StreamedResponse($callback, 200, [
            'Content-Type' => $contentType,
            'Content-Disposition' => sprintf('attachment; filename="%s"', $filename),
        ]);
    }
}