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

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

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

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

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

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

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

Yvon committed
246 247 248 249 250

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

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

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

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

        $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
315 316
    }

317
    /**
318 319
     * Payment terminal page.
     * 
320
     * @Route("/encaissement", name="encaissement")
321
     * @IsGranted({"ROLE_CAISSIER", "ROLE_PRESTATAIRE"})
322
     */
323
    public function encaissementAction(Request $request)
324
    {
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
        // 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');
            }
        }

342
        $form = $this->createForm(EncaissementFormType::class, null, []);
343
        $form->handleRequest($request);
344
        $validation = false;  // validation = user enters its code
345
        $insufficientBalance = null;  // if not null, will indicate for the template an insufficient founds situation 
346 347 348

        if ($form->isSubmitted()) {
            $data = $form->getData();
Damien Moulard committed
349
            
350
            if ($form->isValid()) {
351 352
                $adherent = $data["adherent"];
                $adherent_code = $adherent->getPaymentCode();
353
                $input_code = $data["payment_code"];
Damien Moulard committed
354

355 356 357 358 359 360 361 362
                // 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é.')
                        );
363

364 365
                        goto end;
                    }
366

367 368
                    // if adherent doesn't have a validation code
                    if (is_null($adherent_code)) {
369 370
                        $this->addFlash(
                            'error',
371
                            $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.')
372
                        );
Damien Moulard committed
373

374 375
                        goto end;
                    }
Damien Moulard committed
376

377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
                    // 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;
395 396 397

                    // First step validated (set user & amount) -> go to validation
                    goto end;
398 399 400 401
                } else {
                    // We're in the validation process
                    $validation = true;
                }
402

403
                // Check validation code
404
                // NOTE as we use password salt, the user must change his payment code if his password changes
405 406
                $encoded_input = crypt($input_code, $adherent->getUser()->getSalt());
                if (!hash_equals($adherent_code, $encoded_input)) {
407 408 409 410
                    $this->addFlash(
                        'error',
                        $this->translator->trans('Code incorrect')
                    );
Damien Moulard committed
411

412 413 414
                    goto end;
                }

415 416 417 418 419
                // Check adherent has enough funds
                $balance = $adherent->getEmlcAccount()->getBalance();
                $transaction_amount = floatval($data["montant"]);
                if ($balance < $transaction_amount) {
                    // Send mail for insufficient funds
420
                    $subject = $this->translator->trans('[MONNAIE ALIMENTAIRE COMMUNE] – Solde insuffisant');
421 422 423 424 425 426 427
                    $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',
                                [
428
                                    'subject' => $subject
429 430 431 432 433 434 435 436
                                ]
                            ),
                            'text/html'
                        );
                    $this->mailer->send($mail);

                    $this->addFlash(
                        'error',
437
                        $this->translator->trans('Solde de l\'habitant·e insuffisant')
438 439
                    );

440 441
                    $insufficientBalance = $balance;

442
                    goto end;
443
                }
444

445
                // No error at this point: save transaction
446 447 448
                $flux = new TransactionAdherentPrestataire();
                $flux->setExpediteur($adherent);

449 450 451 452
                if (!isset($presta)) {
                    $presta = $this->session->get('_prestagere');
                    $presta = $this->em->getRepository(Prestataire::class)->findOneById($presta->getId());
                }
453 454 455 456 457 458 459 460 461 462 463 464
                $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);

                $this->em->persist($flux);
                $this->operationUtils->executeOperations($flux);
                $this->em->flush();
Damien Moulard committed
465

466 467 468 469 470 471 472 473 474
                $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);
475 476 477 478 479 480 481 482
            } else {
                $this->addFlash(
                    'error',
                    $this->translator->trans('Problème avec l\'encaissement !') . ' ' . $form->getErrors()
                );
            }
        }

Damien Moulard committed
483
        end:
484
        $templateData = [
Damien Moulard committed
485
            'form' => $form->createView(),
486 487
            'validation' => $validation,
            'insufficientBalance' => $insufficientBalance
488 489 490 491 492 493 494
        ];

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

        return $this->render('@kohinos/tav/encaissement_page.html.twig', $templateData);
495
    }
496 497 498 499 500 501 502

    /**
     * @Route("/encaissement/succes", name="encaissementSuccess")
     * @IsGranted({"ROLE_CAISSIER", "ROLE_PRESTATAIRE"})
     */
    public function encaissementSuccessAction(Request $request)
    {
503 504 505 506 507 508 509 510
        $templateData = [];

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

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