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

namespace App\Controller;

use App\Entity\Adherent;
6
use App\Entity\Don;
Julien Jorry committed
7 8 9 10 11 12 13 14
use App\Entity\Flux;
use App\Entity\Groupe;
use App\Entity\Prestataire;
use App\Entity\User;
use App\Enum\CurrencyEnum;
use App\Flux\FluxInterface;
use App\Utils\CustomEntityManager;
use App\Utils\OperationUtils;
15
use App\Utils\TAVCotisationUtils;
Julien Jorry committed
16
use FOS\UserBundle\Model\UserManagerInterface;
17
use FOS\UserBundle\Util\TokenGeneratorInterface;
18
use Gamez\Symfony\Component\Serializer\Normalizer\UuidNormalizer;
Julien Jorry committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
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;
use Symfony\Component\Security\Core\Security;
34
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
35 36 37
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
Julien Jorry committed
38
use Symfony\Component\Translation\TranslatorInterface;
39
use Symfony\Component\Validator\Validator\ValidatorInterface;
Julien Jorry committed
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
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;
75 76
    protected $tokenGenerator;
    protected $validator;
77
    protected $userManager;
Julien Jorry committed
78 79 80 81 82 83 84 85

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

    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()) {
115
        //     return new Response('', Response::HTTP_BAD_REQUEST);
Julien Jorry committed
116 117
        // }
        $form->handleRequest($request);
118
        if ($form->isSubmitted() && !$this->tokenManager->isTokenValid($this->tokenManager->getToken('flux_form'))) {
119 120 121 122
            $referer = $request->headers->get('referer');

            return $this->redirect($referer);
        }
Julien Jorry committed
123
        if ($form->isSubmitted() && $form->isValid()) {
124
            $this->tokenManager->refreshToken('flux_form');
Julien Jorry committed
125
            $flux = $form->getData();
126 127 128 129 130 131 132 133 134 135 136 137 138 139
            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
140 141 142 143 144 145 146 147 148 149 150 151
            }
        }

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

    private function fluxSuccessRedirection(Request $request, FluxInterface $flux)
    {
        $referer = $request->headers->get('referer');
        $template = null;
152 153 154 155
        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
156 157 158 159 160 161 162 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
            }
        }
        // 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,
        ]);
    }

    /**
     * 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',
188 189
                'Expediteur' => 'flux.expediteur',
                'Destinataire' => 'flux.destinataire',
Julien Jorry committed
190 191 192 193
                'Montant' => 'montant',
                'Type parent' => 'flux.parenttype',
                'Type' => 'flux.type',
                'Moyen' => 'flux.moyen',
194
                'Référence' => 'flux.reference',
Julien Jorry committed
195 196 197 198 199 200 201 202 203
            ];
            $source = new DoctrineORMQuerySourceIterator($query, $fields);

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

204 205 206 207
            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
208 209 210 211 212 213 214 215 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 264 265 266
            }

            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
            );

267 268 269 270
            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
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
            }

            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),
        ]);
    }
}