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

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

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

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

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

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

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

    /**
     * @Route("/encaissement", name="encaissement")
247
     * @IsGranted({"ROLE_CAISSIER", "ROLE_PRESTATAIRE"})
248
     */
249
    public function encaissementAction(Request $request)
250
    {
251
        $form = $this->createForm(EncaissementFormType::class, null, []);
252
        $form->handleRequest($request);
Damien Moulard committed
253
        $validation = false;
254 255 256

        if ($form->isSubmitted()) {
            $data = $form->getData();
Damien Moulard committed
257
            
258
            if ($form->isValid()) {
259
                $input_code = $data["payment_code"];
260
                $validation = true;  // As soon as the form is submitted & valid, we enter the validation process
Damien Moulard committed
261

262
                if (empty($input_code)) {
Damien Moulard committed
263 264 265 266
                    // First step validated (set user & amount) -> go to validation
                    goto end;
                } 

267 268
                $adherent = $data["adherent"];
                $adherent_code = $adherent->getPaymentCode();
Damien Moulard committed
269

270 271 272 273 274 275 276 277 278 279
                // 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é.')
                    );

                    goto end;
                }

Damien Moulard committed
280
                // if adherent doesn't have a validation code
281 282 283
                if (is_null($adherent_code)) {
                    $this->addFlash(
                        'error',
284
                        $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.')
285
                    );
Damien Moulard committed
286

287 288
                    goto end;
                }
Damien Moulard committed
289

290
                // Check validation code
291
                // NOTE as we use password salt, must change payment code if password changes
292 293
                $encoded_input = crypt($input_code, $adherent->getUser()->getSalt());
                if (!hash_equals($adherent_code, $encoded_input)) {
294 295 296 297
                    $this->addFlash(
                        'error',
                        $this->translator->trans('Code incorrect')
                    );
Damien Moulard committed
298

299 300 301
                    goto end;
                }

302 303 304 305 306
                // Check adherent has enough funds
                $balance = $adherent->getEmlcAccount()->getBalance();
                $transaction_amount = floatval($data["montant"]);
                if ($balance < $transaction_amount) {
                    // Send mail for insufficient funds
307
                    $subject = $this->translator->trans('[MONNAIE ALIMENTAIRE COMMUNE] – Solde insuffisant');
308 309 310 311 312 313 314
                    $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',
                                [
315
                                    'subject' => $subject
316 317 318 319 320 321 322 323
                                ]
                            ),
                            'text/html'
                        );
                    $this->mailer->send($mail);

                    $this->addFlash(
                        'error',
324
                        $this->translator->trans('Solde de l\'habitant·e insuffisant')
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
                    );

                    return $this->redirectToRoute('index');
                }
                
                // Save transaction
                $flux = new TransactionAdherentPrestataire();
                $flux->setExpediteur($adherent);

                $presta = $this->session->get('_prestagere');
                $presta = $this->em->getRepository(Prestataire::class)->findOneById($presta->getId());
                $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
348

349 350
                $this->addFlash(
                    'success',
351
                    $this->translator->trans('Transaction réussie !')
352
                );
353 354

                return $this->redirectToRoute('index');
355 356 357 358 359 360 361 362
            } else {
                $this->addFlash(
                    'error',
                    $this->translator->trans('Problème avec l\'encaissement !') . ' ' . $form->getErrors()
                );
            }
        }

Damien Moulard committed
363
        end:
364
        return $this->render('@kohinos/tav/encaissement_page.html.twig', [
Damien Moulard committed
365 366
            'form' => $form->createView(),
            'validation' => $validation
367 368
        ]);
    }
Julien Jorry committed
369
}