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

namespace App\Controller;

use App\Entity\Adherent;
use App\Entity\CotisationAdherent;
use App\Entity\CotisationPrestataire;
8
use App\Entity\GlobalParameter;
Julien Jorry committed
9 10
use App\Entity\Payment;
use App\Entity\Prestataire;
11
use App\Entity\Reconversion;
12
use App\Entity\TransactionPrestataireAdherent;
Julien Jorry committed
13
use App\Entity\User;
14
use App\Entity\TransactionAdherentPrestataire;
15 16
use App\Entity\InformationPopup;
use App\Entity\InformationPopupUser;
Julien Jorry committed
17 18
use App\Enum\MoyenEnum;
use App\Form\Type\CotiserFormType;
19 20
use App\Form\Type\DonAdherentFormType;
use App\Form\Type\DonPrestataireFormType;
Julien Jorry committed
21
use App\Form\Type\UserInfosFormType;
22
use App\Form\Type\EncaissementFormType;
Damien Moulard committed
23
use App\Form\Type\EncaissementValidationFormType;
24
use App\Utils\CotisationUtils;
Julien Jorry committed
25 26 27 28
use App\Utils\OperationUtils;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
29
use Symfony\Component\HttpFoundation\JsonResponse;
Julien Jorry committed
30 31
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
32
use Symfony\Component\HttpFoundation\Session\SessionInterface;
Julien Jorry committed
33 34 35
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Translation\TranslatorInterface;
36
use Twig\Environment;
37
use App\Entity\Flux;
Julien Jorry committed
38 39 40 41 42 43 44

class UserController extends AbstractController
{
    private $em;
    private $translator;
    private $security;
    private $operationUtils;
45
    private $cotisationUtils;
46 47 48 49 50 51 52 53 54 55 56 57 58 59
    private $session;
    private $mailer;
    private $templating;

    public function __construct(
        EntityManagerInterface $em,
        TranslatorInterface $translator,
        Security $security,
        OperationUtils $operationUtils,
        CotisationUtils $cotisationUtils,
        SessionInterface $session,
        \Swift_Mailer $mailer,
        Environment $templating
    ) {
Julien Jorry committed
60 61 62 63
        $this->em = $em;
        $this->translator = $translator;
        $this->security = $security;
        $this->operationUtils = $operationUtils;
64
        $this->cotisationUtils = $cotisationUtils;
65 66 67
        $this->session = $session;
        $this->mailer = $mailer;
        $this->templating = $templating;
Julien Jorry committed
68 69 70
    }

    /**
71 72
     * @Route("/cotiser", name="cotiser", defaults={"type": "null"})
     * @Route("/cotiser/next", name="cotisernextyear", defaults={"type": "nextyear"})
Julien Jorry committed
73 74
     * @IsGranted("ROLE_USER")
     */
75
    public function cotiserAction($type, Request $request)
Julien Jorry committed
76 77 78
    {
        $options = [];
        $payment_type = '';
79
        if ($this->security->isGranted('ROLE_ADHERENT')) {
Julien Jorry committed
80
            $options['data_class'] = CotisationAdherent::class;
81
            $options['don_class'] = DonAdherentFormType::class;
Julien Jorry committed
82
            $payment_type = Payment::TYPE_COTISATION_ADHERENT;
83
        } elseif ($this->security->isGranted('ROLE_PRESTATAIRE')) {
Julien Jorry committed
84
            $options['data_class'] = CotisationPrestataire::class;
85
            $options['don_class'] = DonPrestataireFormType::class;
Julien Jorry committed
86 87 88 89 90
            $payment_type = Payment::TYPE_COTISATION_PRESTA;
        }

        $form = $this->createForm(CotiserFormType::class, null, $options);
        $form->handleRequest($request);
91 92
        if ('nextyear' === $type) {
            $nextYear = new \DateTime('+1 year');
93 94 95
            $startDate = $this->cotisationUtils->isCotisationValid($this->getUser());
            $endDate = new \DateTime(date('Y-m-d H:i:s', strtotime('+1 year', strtotime($startDate->format('Y-m-d H:i:s')))));
            $kohYear = (string) $endDate->format('Y');
96 97 98 99
        } else {
            $now = new \DateTime();
            $kohYear = (string) $now->format('Y');
        }
Julien Jorry committed
100 101 102 103

        if ($form->isSubmitted()) {
            $cotisation = $form->getData();
            if ($form->isValid()) {
104 105 106 107 108 109 110 111 112 113
                //Manage don if null => delete it !
                if ($cotisation->getDon() && 0 == $cotisation->getDon()->getMontant()) {
                    $cotisation->setDon(null);
                }
                if ('nextyear' === $type) {
                    // Cotiser pour l'année suivante
                    $startDate = $this->cotisationUtils->isCotisationValid($this->getUser());
                    $cotisation->getCotisationInfos()->setDebut($startDate);
                    $endDate = new \DateTime(date('Y-m-d H:i:s', strtotime('+1 year', strtotime($startDate->format('Y-m-d H:i:s')))));
                    $cotisation->getCotisationInfos()->setFin($endDate);
114
                    $cotisation->getCotisationInfos()->setAnnee((string) $endDate->format('Y'));
115
                }
Julien Jorry committed
116
                if (MoyenEnum::MOYEN_EMLC == $cotisation->getMoyen()) {
Julien Jorry committed
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
                    try {
                        $cotisation->setRecu(true);
                        $this->operationUtils->executeOperations($cotisation);
                        $this->addFlash(
                            'success',
                            // "Cotisation pour l'année {$cotisation->getCotisationInfos()->getAnnee()} bien reçue. Merci !"
                            $this->translator->trans('Cotisation bien reçue. Merci !')
                        );
                    } catch (\Exception $e) {
                        $this->addFlash(
                            'error',
                            $this->translator->trans('Problème avec la cotisation !') . ' ' . $e->getMessage()
                        );
                    }

                    return $this->redirectToRoute('index');
133 134 135 136 137 138 139 140 141
                } elseif (MoyenEnum::MOYEN_HELLOASSO == $cotisation->getMoyen()) {
                    if ($this->security->isGranted('ROLE_ADHERENT')) {
                        $url = $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::HELLOASSO_URL_COTISATION_ADHERENT);
                    } else {
                        $url = $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::HELLOASSO_URL_COTISATION_PRESTATAIRE);
                    }

                    return $this->redirect($url);
                } elseif (MoyenEnum::MOYEN_CB == $cotisation->getMoyen()) {
Julien Jorry committed
142
                    // Redirect to payment page
143
                    return $this->forward('App\Controller\PaymentController::preparePaymentAction', [
Julien Jorry committed
144 145 146 147 148 149 150 151 152 153 154 155 156 157
                        'form' => $form,
                        'type' => $payment_type,
                    ]);
                }
            } else {
                $this->addFlash(
                    'error',
                    $this->translator->trans('Problème avec la cotisation !') . ' ' . $form->getErrors()
                );
            }
        }

        return $this->render('@kohinos/cotiser.html.twig', [
            'form' => $form->createView(),
158
            'koh_year' => $kohYear,
Julien Jorry committed
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 188 189 190 191 192 193 194 195 196 197 198 199 200 201
        ]);
    }

    /**
     * @Route("/userinfos", name="user_infos")
     * @IsGranted("ROLE_USER")
     */
    public function userInfosAction(Request $request)
    {
        $form = $this->createForm(UserInfosFormType::class, $this->getUser());
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->em->persist($form->getData());
            $this->em->flush();
            $this->addFlash(
                'success',
                $this->translator->trans("Infos de l'utilisateur modifiée !")
            );
            $referer = $request->headers->get('referer');
            if ($referer && !$request->isXmlHttpRequest()) {
                return $this->redirect($referer);
            } elseif (!$request->isXmlHttpRequest()) {
                return new Response('', Response::HTTP_BAD_REQUEST);
            }
        }

        return $this->redirectToRoute('index');
        // return $this->render('@kohinos/presta/infos.html.twig', array(
        //     'form' => $form->createView()
        // ));
    }

    /**
     * @Route("/account/user", name="myaccount")
     * @IsGranted("ROLE_USER")
     */
    public function myaccountAction(Request $request)
    {
        return $this->render('@kohinos/common/myaccount.html.twig', [
        ]);
    }

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    /**
     * @Route("/search/adherent", methods="GET", name="searchadherent")
     * @IsGranted("ROLE_USER")
     */
    public function searchAdherentAction(Request $request)
    {
        $term = $request->get('term');
        $result = $this->em->getRepository(Adherent::class)->findsByData(['email' => $term, 'name' => $term]);
        $arrayData = [];
        foreach ($result as $adherent) {
            $arrayData[] = ['id' => $adherent->getId(), 'text' => $adherent->__toString()];
        }

        return new JsonResponse(['results' => $arrayData]);
    }

Julien Jorry committed
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
    /**
     * @Route("/user/achatMonnaieAConfirmer", name="achatMonnaieAConfirmer")
     * @IsGranted({"ROLE_ADHERENT", "ROLE_PRESTATAIRE"})
     */
    public function achatMonnaieAConfirmerAction(Request $request)
    {
        $obj = $this->operationUtils->getCurrentAccountable($this->security->getUser());
        if ($obj instanceof Prestataire) {
            return $this->redirectToRoute('achatMonnaieAConfirmerPrestataire');
        } elseif ($obj instanceof Adherent) {
            return $this->redirectToRoute('achatMonnaieAConfirmerAdherent');
        }

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

    /**
     * @Route("/user/listachatMonnaieAConfirmer", name="listachatMonnaieAConfirmer")
     * @IsGranted({"ROLE_ADHERENT", "ROLE_PRESTATAIRE"})
     */
    public function listachatMonnaieAConfirmerAction(Request $request)
    {
        $obj = $this->operationUtils->getCurrentAccountable($this->security->getUser());
        if ($obj instanceof Prestataire) {
            return $this->redirectToRoute('listachatMonnaieAConfirmerPrestataire');
        } elseif ($obj instanceof Adherent) {
            return $this->redirectToRoute('listachatMonnaieAConfirmerAdherent');
        }

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

Yvon committed
250 251 252 253 254

    /**
     * @param Request $request
     * @param TransactionAdherentPrestataire $transactionAdherentPrestataire
     * @return void
255
     * @IsGranted({"ROLE_CAISSIER", "ROLE_PRESTATAIRE"})
Yvon committed
256 257 258 259
     * @Route("/cancel-transaction-adherent-prestataire/{id}", name="cancel_transaction_adherent_prestataire")
     */
    public function cancelTransactionAdherentPrestataireAction(Request $request, TransactionAdherentPrestataire $transactionAdherentPrestataire)
    {
260 261 262
        $adherent = $transactionAdherentPrestataire->getExpediteur();
        $presta = $transactionAdherentPrestataire->getDestinataire();

Yvon committed
263
        //Make sure current user is destinataire of transaction
264
        if(!in_array($this->getUser(),$presta->getUsers()->toArray())) {
Yvon committed
265 266 267 268 269 270
            $this->addFlash(
                'error',
                "Vous n'êtes pas autorisé à annuler cette transaction."
            );
            return $this->redirectToRoute('index');
        }
271 272 273 274 275 276 277 278 279
        //Make sure flux has not been cancelled already
        if($transactionAdherentPrestataire->getCancellerFlux()) {
            $this->addFlash(
                'error',
                "Cette transaction a déjà été annulée."
            );
            return $this->redirectToRoute('index');
        }

Yvon committed
280
        // Check prestataire has enough funds
281
        $balance = $presta->getEmlcAccount()->getBalance();
Yvon committed
282
        //I think this is unlikely in real situation but we need to make sure prestataire has enough founds
283 284
        $montant = $transactionAdherentPrestataire->getMontant();
        if ($balance < $montant) {
Yvon committed
285 286 287 288 289 290 291
            $this->addFlash(
                'error',
                'Fonds insuffisants pour annuler cette transaction.'
            );
            return $this->redirectToRoute('index');
        }

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
        //Ccas transactions.
        if ($transactionAdherentPrestataire->getIsCcas()) {
            //Allowed if and only if transaction is from current month
            $now = new \DateTime();
            if (
                $transactionAdherentPrestataire->getCreatedAt()->format('m') !== $now->format('m')
                || $transactionAdherentPrestataire->getCreatedAt()->format('Y') !== $now->format('Y')
            ) {
                //display the same error message for CCAS or non CCAS as prestataire are not supposed to know if a transaction is CCAS or not
                $this->addFlash(
                    'error',
                    'Cette transaction ne plus être annulée car une reconversion a été demandée depuis.'
                );
                return $this->redirectToRoute('index');
            }
        }
        //Non ccas transactions,
        else {
            //we prevent cancelling transactions which happened before a reconversion (to avoid refunding money that's been reconverted)
            if (
                $this->em->getRepository(Flux::class)->getQueryByPrestataire(
                    $presta,
                    null,
                    Reconversion::TYPE_RECONVERSION_PRESTATAIRE,
                    $transactionAdherentPrestataire->getCreatedAt()->format("Y-m-d H:i:s")
                )->getResult()
            ) {
                $this->addFlash(
                    'error',
                    'Cette transaction ne plus être annulée car une reconversion a été demandée depuis.'
                );
                return $this->redirectToRoute('index');
            }
325 326
        }

327 328 329 330 331 332 333 334 335
        //Create new transaction in opposite direction
        $flux = new TransactionPrestataireAdherent();
        $flux->setExpediteur($presta);
        $flux->setDestinataire($adherent);

        $flux->setOperateur($this->security->getUser());
        $flux->setMontant($montant);
        $flux->setMoyen(MoyenEnum::MOYEN_EMLC);

336 337 338 339 340
        // The flux to cancel a ccas flux is also marked as ccas
        if ($this->getParameter('ccas_mode')) {
            $flux->setIsCcas($transactionAdherentPrestataire->getIsCcas());
        }

341 342
        $now = (new \Datetime('now'))->format('d/m/Y H:i:s');
        $flux->setReference(
343
            'Remboursement en Monnaie Solidaire du ' . $now . ' annule ' . $transactionAdherentPrestataire->getReference()
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
        );

        $this->em->persist($flux);
        $this->operationUtils->executeOperations($flux);

        //Mark original transaction as cancelled
        $transactionAdherentPrestataire->setCancellerFlux($flux);

        $this->em->flush();

        $this->addFlash(
            'success',
            'La transaction a bien été annulée.'
        );
        return $this->redirectToRoute('index');
Yvon committed
359 360
    }

361
    /**
362 363
     * Payment terminal page.
     * 
364
     * @Route("/encaissement", name="encaissement")
365
     * @IsGranted({"ROLE_CAISSIER", "ROLE_PRESTATAIRE"})
366
     */
367
    public function encaissementAction(Request $request)
368
    {
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
        // If conventionnement process is activated, prevent access to payment terminal if prestataire conventionnement is not set
        $conventionnementMode = $this->getParameter('presta_self_init_and_eval');
        if ($conventionnementMode == true) {
            $presta = $this->session->get('_prestagere');
            $presta = $this->em->getRepository(Prestataire::class)->findOneById($presta->getId());

            $conventionnement = $presta->getConventionnement();
            if ($conventionnement == null || $conventionnement == 0) {
                $this->addFlash(
                    'error',
                    $this->translator->trans("Impossible d'accéder au terminal de paiement tant que votre conventionnement n'a pas été établi par un·e gestionnaire.")
                );

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

386
        $form = $this->createForm(EncaissementFormType::class, null, []);
387
        $form->handleRequest($request);
388
        $validation = false;  // validation = user enters its code
389
        $insufficientBalance = null;  // if not null, will indicate for the template an insufficient founds situation 
390 391 392

        if ($form->isSubmitted()) {
            $data = $form->getData();
Damien Moulard committed
393
            
394
            if ($form->isValid()) {
395 396
                $adherent = $data["adherent"];
                $adherent_code = $adherent->getPaymentCode();
397
                $input_code = $data["payment_code"];
Damien Moulard committed
398

399 400 401 402 403 404 405 406
                // Perform first step checks
                if (empty($input_code)) {
                    // if adherent account isn't enabled
                    if (!$adherent->getUser()->isEnabled()) {
                        $this->addFlash(
                            'error',
                            $this->translator->trans('Le compte de l\'habitant·e est désactivé.')
                        );
407

408 409
                        goto end;
                    }
410

411 412
                    // if adherent doesn't have a validation code
                    if (is_null($adherent_code)) {
413 414
                        $this->addFlash(
                            'error',
415
                            $this->translator->trans('L\'habitant·e n\'a pas encore défini un code de validation de paiement sur son espace personnel, il·elle ne peut pas payer en Monnaie Solidaire pour l\'instant.')
416
                        );
Damien Moulard committed
417

418 419
                        goto end;
                    }
Damien Moulard committed
420

421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
                    // If entered amount is above maximum amount, depending on prestataire conventionnement
                    if ($conventionnementMode == true) {
                        $transaction_amount = floatval($data["montant"]);
                        $montantPanier = floatval($form['montantPanier']->getData());
                        $maxAmount = $montantPanier * floatval($conventionnement);

                        if ($transaction_amount > $maxAmount) {
                            $this->addFlash(
                                'error',
                                $this->translator->trans('Montant maximal en MonA dépassé. Veuillez modifier le montant en MonA.')
                            );
        
                            goto end;
                        }
                    }

                    // When the form is submitted & valid, and the user account checks passed, we enter the validation process
                    $validation = true;
439 440 441

                    // First step validated (set user & amount) -> go to validation
                    goto end;
442 443 444 445
                } else {
                    // We're in the validation process
                    $validation = true;
                }
446

447
                // Check validation code
448
                // NOTE as we use password salt, the user must change his payment code if his password changes
449 450
                $encoded_input = crypt($input_code, $adherent->getUser()->getSalt());
                if (!hash_equals($adherent_code, $encoded_input)) {
451 452 453 454
                    $this->addFlash(
                        'error',
                        $this->translator->trans('Code incorrect')
                    );
Damien Moulard committed
455

456 457 458
                    goto end;
                }

459 460 461 462 463
                // Check adherent has enough funds
                $balance = $adherent->getEmlcAccount()->getBalance();
                $transaction_amount = floatval($data["montant"]);
                if ($balance < $transaction_amount) {
                    // Send mail for insufficient funds
464
                    $subject = $this->translator->trans('[MONNAIE ALIMENTAIRE COMMUNE] – Solde insuffisant');
465 466 467 468 469 470 471
                    $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/tav/insufficient_funds.html.twig',
                                [
472
                                    'subject' => $subject
473 474 475 476 477 478 479 480
                                ]
                            ),
                            'text/html'
                        );
                    $this->mailer->send($mail);

                    $this->addFlash(
                        'error',
481
                        $this->translator->trans('Solde de l\'habitant·e insuffisant')
482 483
                    );

484 485
                    $insufficientBalance = $balance;

486
                    goto end;
487
                }
488

489
                // No error at this point: save transaction
490 491 492
                $flux = new TransactionAdherentPrestataire();
                $flux->setExpediteur($adherent);

493 494 495 496
                if (!isset($presta)) {
                    $presta = $this->session->get('_prestagere');
                    $presta = $this->em->getRepository(Prestataire::class)->findOneById($presta->getId());
                }
497 498 499 500 501 502 503 504 505
                $flux->setDestinataire($presta);

                $flux->setOperateur($this->security->getUser());
                $flux->setMontant($transaction_amount);
                $flux->setMoyen(MoyenEnum::MOYEN_EMLC);

                $now = (new \Datetime('now'))->format('d/m/Y H:i:s');
                $flux->setReference('Achat en Monnaie Solidaire du ' . $now);

506 507 508 509 510 511 512 513 514 515
                // Mark transaction as CCAS if at the time of the transation, both adherent & presta are CCAS complient
                if (
                    $this->getParameter('ccas_mode')
                    && $adherent->getCcasEligible() 
                    && $adherent->getCcasAccepted()
                    && $presta->getCcasOk()
                ) {
                    $flux->setIsCcas(true);
                }

516 517 518
                $this->em->persist($flux);
                $this->operationUtils->executeOperations($flux);
                $this->em->flush();
Damien Moulard committed
519

520 521 522 523 524 525 526 527 528
                $redirectParams = [];
                if ($form->has('montantPanier')) {
                    $transaction_amount = floatval($data["montant"]);
                    $montantPanier = floatval($form['montantPanier']->getData());

                    $redirectParams['remainingAmount'] = $montantPanier - $transaction_amount;
                }

                return $this->redirectToRoute('encaissementSuccess', $redirectParams);
529 530 531 532 533 534 535 536
            } else {
                $this->addFlash(
                    'error',
                    $this->translator->trans('Problème avec l\'encaissement !') . ' ' . $form->getErrors()
                );
            }
        }

Damien Moulard committed
537
        end:
538
        $templateData = [
Damien Moulard committed
539
            'form' => $form->createView(),
540 541
            'validation' => $validation,
            'insufficientBalance' => $insufficientBalance
542 543 544 545 546 547 548
        ];

        if ($conventionnementMode == true) {
            $templateData['conventionnement'] = $conventionnement;
        }

        return $this->render('@kohinos/tav/encaissement_page.html.twig', $templateData);
549
    }
550 551 552 553 554 555 556

    /**
     * @Route("/encaissement/succes", name="encaissementSuccess")
     * @IsGranted({"ROLE_CAISSIER", "ROLE_PRESTATAIRE"})
     */
    public function encaissementSuccessAction(Request $request)
    {
557 558 559 560 561 562 563 564
        $templateData = [];

        $remainingAmount = $request->query->get('remainingAmount');
        if ($remainingAmount != '') {
            $templateData['remainingAmount'] = $remainingAmount;
        }

        return $this->render('@kohinos/tav/payment_done_page.html.twig', $templateData);
565
    }
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592

    /**
     * Register that the connected user (currently only adherents) has clicked on the popup validation button,
     * So it's not shown to him/her again.
     * 
     * @Route("/user/setUserValidatedInformationPopup", name="set_user_validated_information_popup")
     * @IsGranted({"ROLE_ADHERENT"})
     */
    public function setUserValidatedInformationPopupAction(Request $request)
    {
        $user = $this->security->getUser();
        $activePopup = $this->em->getRepository(InformationPopup::class)->findOneBy(['enabled' => true]);
        $activePopupUser = $this->em->getRepository(InformationPopupUser::class)->findOneBy(['informationPopup' => $activePopup, 'user' => $user]);

        if (null === $activePopupUser) {
            $activePopupUser = new InformationPopupUser();
            $activePopupUser->setInformationPopup($activePopup);
            $activePopupUser->setUser($user);
        }

        $activePopupUser->setHasValidated(true);

        $this->em->persist($activePopupUser);
        $this->em->flush();

        return $this->redirectToRoute('index');
    }
Julien Jorry committed
593
}