UserController.php 22.6 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;
Julien Jorry committed
15 16
use App\Enum\MoyenEnum;
use App\Form\Type\CotiserFormType;
17 18
use App\Form\Type\DonAdherentFormType;
use App\Form\Type\DonPrestataireFormType;
Julien Jorry committed
19
use App\Form\Type\UserInfosFormType;
20
use App\Form\Type\EncaissementFormType;
Damien Moulard committed
21
use App\Form\Type\EncaissementValidationFormType;
22
use App\Utils\CotisationUtils;
Julien Jorry committed
23 24 25 26
use App\Utils\OperationUtils;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
27
use Symfony\Component\HttpFoundation\JsonResponse;
Julien Jorry committed
28 29
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
30
use Symfony\Component\HttpFoundation\Session\SessionInterface;
Julien Jorry committed
31 32 33
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Translation\TranslatorInterface;
34
use Twig\Environment;
35
use App\Entity\Flux;
Julien Jorry committed
36 37 38 39 40 41 42

class UserController extends AbstractController
{
    private $em;
    private $translator;
    private $security;
    private $operationUtils;
43
    private $cotisationUtils;
44 45 46 47 48 49 50 51 52 53 54 55 56 57
    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
58 59 60 61
        $this->em = $em;
        $this->translator = $translator;
        $this->security = $security;
        $this->operationUtils = $operationUtils;
62
        $this->cotisationUtils = $cotisationUtils;
63 64 65
        $this->session = $session;
        $this->mailer = $mailer;
        $this->templating = $templating;
Julien Jorry committed
66 67 68
    }

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

        $form = $this->createForm(CotiserFormType::class, null, $options);
        $form->handleRequest($request);
89 90
        if ('nextyear' === $type) {
            $nextYear = new \DateTime('+1 year');
91 92 93
            $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');
94 95 96 97
        } else {
            $now = new \DateTime();
            $kohYear = (string) $now->format('Y');
        }
Julien Jorry committed
98 99 100 101

        if ($form->isSubmitted()) {
            $cotisation = $form->getData();
            if ($form->isValid()) {
102 103 104 105 106 107 108 109 110 111
                //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);
112
                    $cotisation->getCotisationInfos()->setAnnee((string) $endDate->format('Y'));
113
                }
Julien Jorry committed
114
                if (MoyenEnum::MOYEN_EMLC == $cotisation->getMoyen()) {
Julien Jorry committed
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
                    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');
131 132 133 134 135 136 137 138 139
                } 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
140
                    // Redirect to payment page
141
                    return $this->forward('App\Controller\PaymentController::preparePaymentAction', [
Julien Jorry committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155
                        '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(),
156
            'koh_year' => $kohYear,
Julien Jorry committed
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 188 189 190 191 192 193 194 195 196 197 198 199
        ]);
    }

    /**
     * @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', [
        ]);
    }

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    /**
     * @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
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
    /**
     * @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');
    }
247

Yvon committed
248 249 250 251 252

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

Yvon committed
261
        //Make sure current user is destinataire of transaction
262
        if(!in_array($this->getUser(),$presta->getUsers()->toArray())) {
Yvon committed
263 264 265 266 267 268
            $this->addFlash(
                'error',
                "Vous n'êtes pas autorisé à annuler cette transaction."
            );
            return $this->redirectToRoute('index');
        }
269 270 271 272 273 274 275 276 277
        //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
278
        // Check prestataire has enough funds
279
        $balance = $presta->getEmlcAccount()->getBalance();
Yvon committed
280
        //I think this is unlikely in real situation but we need to make sure prestataire has enough founds
281 282
        $montant = $transactionAdherentPrestataire->getMontant();
        if ($balance < $montant) {
Yvon committed
283 284 285 286 287 288 289
            $this->addFlash(
                'error',
                'Fonds insuffisants pour annuler cette transaction.'
            );
            return $this->redirectToRoute('index');
        }

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
        //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');
            }
323 324
        }

325 326 327 328 329 330 331 332 333
        //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);

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

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

        $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
357 358
    }

359
    /**
360 361
     * Payment terminal page.
     * 
362
     * @Route("/encaissement", name="encaissement")
363
     * @IsGranted({"ROLE_CAISSIER", "ROLE_PRESTATAIRE"})
364
     */
365
    public function encaissementAction(Request $request)
366
    {
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
        // 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');
            }
        }

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

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

397 398 399 400 401 402 403 404
                // 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é.')
                        );
405

406 407
                        goto end;
                    }
408

409 410
                    // if adherent doesn't have a validation code
                    if (is_null($adherent_code)) {
411 412
                        $this->addFlash(
                            'error',
413
                            $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.')
414
                        );
Damien Moulard committed
415

416 417
                        goto end;
                    }
Damien Moulard committed
418

419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
                    // 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;
437 438 439

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

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

454 455 456
                    goto end;
                }

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

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

482 483
                    $insufficientBalance = $balance;

484
                    goto end;
485
                }
486

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

491 492 493 494
                if (!isset($presta)) {
                    $presta = $this->session->get('_prestagere');
                    $presta = $this->em->getRepository(Prestataire::class)->findOneById($presta->getId());
                }
495 496 497 498 499 500 501 502 503
                $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);

504 505 506 507 508 509 510 511 512 513
                // 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);
                }

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

518 519 520 521 522 523 524 525 526
                $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);
527 528 529 530 531 532 533 534
            } else {
                $this->addFlash(
                    'error',
                    $this->translator->trans('Problème avec l\'encaissement !') . ' ' . $form->getErrors()
                );
            }
        }

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

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

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

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

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

        return $this->render('@kohinos/tav/payment_done_page.html.twig', $templateData);
563
    }
Julien Jorry committed
564
}