IndexController.php 27.2 KB
Newer Older
Julien Jorry committed
1 2 3 4 5 6 7 8 9 10
<?php

namespace App\Controller;

use App\Entity\AccountComptoir;
use App\Entity\AccountGroupe;
use App\Entity\AccountPrestataire;
use App\Entity\AccountSiege;
use App\Entity\Comptoir;
use App\Entity\Geoloc;
11
use App\Entity\GeolocPrestataire;
Julien Jorry committed
12 13 14
use App\Entity\GlobalParameter;
use App\Entity\Groupe;
use App\Entity\Prestataire;
15
use App\Entity\SelfEvalPrestaQuiz;
Julien Jorry committed
16 17 18 19
use App\Entity\Siege;
use App\Entity\User;
use App\Entity\Usergroup;
use App\Enum\CurrencyEnum;
20 21
use App\Form\Type\DistributorSelfEvalPrestaQuizType;
use App\Form\Type\InfosPrestaQuizType;
Julien Jorry committed
22
use App\Form\Type\InstallFormType;
23
use App\Form\Type\ProducerSelfEvalPrestaQuizType;
Julien Jorry committed
24
use App\Security\LoginAuthenticator;
25
use Doctrine\Common\Collections\ArrayCollection;
Julien Jorry committed
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Model\UserManagerInterface;
use Geocoder\Provider\Nominatim\Nominatim;
use Geocoder\Query\GeocodeQuery;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
42
use Symfony\Component\Routing\RouterInterface;
Julien Jorry committed
43
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
44
use Symfony\Component\Security\Core\Security;
Julien Jorry committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
use Symfony\Component\Security\Core\Security as Secur;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
use Symfony\Component\Security\Guard\Token\PostAuthenticationGuardToken;

class IndexController extends AbstractController
{
    private $eventDispatcher;
    private $em;
    private $userManager;
    private $tokenManager;
    private $guard;
    private $authenticator;
    private $session;
    private $tokenStorage;
60
    private $router;
61
    private $security;
62
    private $mailer;
Julien Jorry committed
63

64 65 66 67 68 69 70 71 72 73
    public function __construct(
        EventDispatcherInterface $eventDispatcher,
        EntityManagerInterface $em,
        UserManagerInterface $userManager,
        CsrfTokenManagerInterface $tokenManager = null,
        GuardAuthenticatorHandler $guard,
        SessionInterface $session,
        LoginAuthenticator $authenticator,
        TokenStorageInterface $tokenStorage,
        RouterInterface $router,
74 75
        Security $security,
        \Swift_Mailer $mailer
76
    ) {
Julien Jorry committed
77 78 79 80 81 82 83 84
        $this->eventDispatcher = $eventDispatcher;
        $this->em = $em;
        $this->userManager = $userManager;
        $this->tokenManager = $tokenManager;
        $this->guard = $guard;
        $this->authenticator = $authenticator;
        $this->session = $session;
        $this->tokenStorage = $tokenStorage;
85
        $this->router = $router;
86
        $this->security = $security;
87
        $this->mailer = $mailer;
88
    }
Julien Jorry committed
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

    /**
     * @Route("/", name="index")
     */
    public function index(Request $request)
    {
        /* Pour la première installation */
        $siege = $this->em->getRepository(Siege::class)->findAll();
        if (null == $siege || empty($siege)) {
            return $this->redirectToRoute('installation');
        }
        /* Pour la modale de login => SecurityController loginAction */
        $session = $request->getSession();
        $lastUsernameKey = Secur::LAST_USERNAME;
        // last username entered by the user
        $lastUsername = (null === $session) ? '' : $session->get($lastUsernameKey);
        $csrfToken = $this->tokenManager
            ? $this->tokenManager->getToken('authenticate')->getValue()
            : null;

        $isWordpress = 'false' != $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::USE_WORDPRESS);

        $template = 'index.html.twig';
        if ($isWordpress) {
            $template = 'index_wordpress.html.twig';
        }

116
        if (
117 118
            isset($_GET['upswd'])
            && 'success' == $_GET['upswd']
119
            && $this->security->isGranted('ROLE_ADHERENT')
120
            && true == $this->getParameter('tav_env')
121 122 123 124 125 126
        ) {
            $this->addFlash(
                'warning',
                'Suite à la modification de votre mot de passe, pensez à mettre à jour votre code de paiment pour pouvoir effectuer des achats.'
            );
        }
127 128 129 130
        list($redirRoute,$presta) = $this->getAndDispatchPrestataire('index');
        if ($redirRoute) {
            return $this->redirectToRoute($redirRoute);
        }
131

Julien Jorry committed
132 133 134 135 136 137 138
        return $this->render('@kohinos/' . $template, [
            'news' => [],
            'last_username' => $lastUsername,
            'csrf_token' => $csrfToken,
        ]);
    }

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 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
    private function getAndDispatchPrestataire($origin)
    {
        if (!$this->getParameter('presta_self_init_and_eval')
            || !$this->security->isGranted('ROLE_ADHERENT')) { //not sure ROLE_ADHERENT is the proper check here
            $destination = 'index';
            return $destination !== $origin ? [$destination, null] : [null, null];
        }

        /* @var ArrayCollection $prestas */
        if ($this->em->getFilters()->isEnabled('enabled_filter')) {
            $this->em->getFilters()->disable('enabled_filter');
        }
        $prestas = $this->em->getRepository(Prestataire::class)->findByData(['user' => $this->security->getUser()]);
        if (!$this->em->getFilters()->isEnabled('enabled_filter')) {
            $this->em->getFilters()->enable('enabled_filter');
        }

        if (!$prestas) {
            $destination = 'index';
            return $destination !== $origin ? [$destination, null] : [null, null];
        }

        /* @var Prestataire $presta */
        $presta = $prestas[0];

        if ($presta->isEnabled()) {
            $destination = 'index';
            return $destination !== $origin ? [$destination, $presta] : [null, $presta];
        }

        if ($presta->getSelfEvalPrestaQuiz()) {
            $destination = 'prestaquiz-sent';
            return $destination !== $origin ? [$destination, $presta] : [null, $presta];
        }

        if ($presta->getMarketChannelFunction()) {
            $destination = 'prestaquiz-selfeval';
            return $destination !== $origin ? [$destination, $presta] : [null, $presta];
        }

        $destination = 'prestaquiz-infos';
        return $destination !== $origin ? [$destination, $presta] : [null, $presta];
    }

    /**
     * @Route("/prestaquiz-sent", name="prestaquiz-sent")
     */
    public function prestaQuizSent(Request $request): Response
    {
        list($redirRoute,$presta) = $this->getAndDispatchPrestataire('prestaquiz-sent');
        if ($redirRoute) {
            return $this->redirectToRoute($redirRoute);
        }

193
        return $this->render('@kohinos/tav/prestaquiz_sent.html.twig');
194 195
    }

Julien Jorry committed
196 197 198 199 200 201 202 203
    /**
     * @Route("/manifest.json", name="manifest")
     */
    public function manifest(Request $request)
    {
        return new JsonResponse(json_decode($this->renderView('@kohinos/common/manifest.json.twig')));
    }

Julien Jorry committed
204 205 206 207 208 209 210 211
    /**
     * @Route("/cotisation/invalid", name="cotisation_invalid")
     */
    public function cotisationInvalidAction(Request $request)
    {
        return $this->render('@kohinos/index_cotisation_invalid.html.twig', []);
    }

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    /**
     * @Route("/prestaquiz-infos", name="prestaquiz-infos")
     */
    public function prestaQuizInfosAction(Request $request): Response
    {
        list($redirRoute,$presta) = $this->getAndDispatchPrestataire('prestaquiz-infos');
        if ($redirRoute) {
            return $this->redirectToRoute($redirRoute);
        }

        /* @var Prestataire $presta */

        if(!$presta->getGeolocs() || $presta->getGeolocs()->isEmpty()) {
            $address = new GeolocPrestataire();
            $presta->addGeoloc($address);
        }
        $form = $this->createForm(InfosPrestaQuizType::class, $presta);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->security->getUser()->setFirstName($form->get('userFirstName')->getData());
            $this->security->getUser()->setLastName($form->get('userLastName')->getData());
            $this->em->flush();
            list($redirRoute,$presta) = $this->getAndDispatchPrestataire('prestaquiz-infos');
            if ($redirRoute) {
                return $this->redirectToRoute($redirRoute);
            }
        }

        return $this->render('@kohinos/tav/infos_prestaquiz.html.twig', [
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/prestaquiz-selfeval", name="prestaquiz-selfeval")
     */
    public function prestaQuizSelfEvalAction(Request $request): Response
    {
        list($redirRoute,$presta) = $this->getAndDispatchPrestataire('prestaquiz-selfeval');
        if ($redirRoute) {
            return $this->redirectToRoute($redirRoute);
        }

        /* @var Prestataire $presta */

        $formClass = Prestataire::DISTRIBUTOR === $presta->getMarketChannelFunction() ?
            DistributorSelfEvalPrestaQuizType::class : ProducerSelfEvalPrestaQuizType::class;

        $quiz = new SelfEvalPrestaQuiz();

        $form = $this->createForm($formClass, $quiz);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $presta->setSelfEvalPrestaQuiz($quiz);
            $this->em->persist($quiz);
            $this->em->flush();

271 272 273
            //Send email !
            $this->notifyGestionnaireAfterPrestaquizSent($presta);

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
            list($redirRoute,$presta) = $this->getAndDispatchPrestataire('prestaquiz-selfeval');
            if ($redirRoute) {
                return $this->redirectToRoute($redirRoute);
            }
        }

        $tmpl = Prestataire::DISTRIBUTOR === $presta->getMarketChannelFunction() ?
            '@kohinos/tav/distributor_selfeval_prestaquiz.html.twig'
            : '@kohinos/tav/producer_selfeval_prestaquiz.html.twig';

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

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    private function notifyGestionnaireAfterPrestaquizSent(Prestataire $presta)
    {
        $user = $this->security->getUser();
        $gestionnaires = $presta->getGroupe()->getGestionnaires();
        if(!$gestionnaires || $gestionnaires->isEmpty() || !$gestionnaires->first()->getEmail()) {
            $to = $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_CONTACT_EMAIL);
        } else {
            $to = $gestionnaires->first()->getEmail();
        }

        $subject = $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_NAME_SMALL)
            . ' : Réception questionnaire point de vente';

        $mail = (new \Swift_Message($subject))
            ->setFrom($this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_NOTIF_EMAIL)) //using $from here sometimes fails with 550 5.7.1 Sender mismatch
            ->setTo($to)
            ->setBody("L'utilisateur " . $user->getUsername()
                .  " vient de soumettre un questionnaire pour le point de vente " . $presta->getRaison() . "."
            );
        $this->mailer->send($mail);
    }

Julien Jorry committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    /**
     * @Route("/installation", name="installation")
     */
    public function installationAction(Request $request)
    {
        $siege = $this->em->getRepository(Siege::class)->findAll();
        if (!empty($siege) && count($siege) > 0) {
            // Installation déjà effectuée !
            return $this->redirectToRoute('index');
        }
        $repogroup = $this->em->getRepository(Usergroup::class);
        $group = $repogroup->findOneBy(['name' => 'Super Admin']);
        if (empty($group)) {
            return new Response('ERREUR !<br><br>Avant de pouvoir installer le kohinos, il faut charger les fixtures : <br>Soit charger les fixtures standards :<br><em>php bin/console hautelook:fixtures:load --purge-with-truncate</em><br/><br/>Soit charger les fixtures de dev (pour tester le kohinos avec des données/comptes factices):<br/><em>php bin/console hautelook:fixtures:load --purge-with-truncate --env=test</em>', 200);
        }
        $user = $this->userManager->createUser();
        $user->setEnabled(true);
        $user->addPossiblegroup($group);
        $user->addGroup($group);
        $form = $this->createForm(InstallFormType::class, ['user' => $user]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $siege = $form['siege']->getData();
            $user = $form['user']->getData();
            $groupe = $form['groupe']->getData();
            $configs = $form['config']->getData();
            $iban = $form['iban']->getData();
            $website = $form['website']->getData();
            $groupe->setSiege($siege);

            //Création du prestataire recevant les cotisations
            $presta = new Prestataire();
            $presta->setMlc(true);
            $presta->setRaison('Monnaie locale');
            $presta->setDescription('Association gérant la monnaie locale et recevant les cotisations');
            $presta->setEnabled(true);
            $presta->setIban($iban);
            if (!empty($website)) {
                $presta->setWeb($website);
            }
            $presta->setSiret(' ');
            $groupePresta = $repogroup->findOneBy(['name' => 'Prestataire']);
            $user->addPossiblegroup($groupePresta);
            $presta->addUser($user);
            $presta->setGroupe($groupe);

            $this->em->persist($siege);

            if (null == $siege->getAccountWithCurrency(CurrencyEnum::CURRENCY_EMLC)) {
                $account = new AccountSiege();
                $account
                    ->setBalance($siege->getEcompteNantie())
                    ->setCurrency(CurrencyEnum::CURRENCY_EMLC) // compte de monnaie numérique nantie
                ;
                $siege->addAccount($account);
                $this->em->persist($account);
            }
            if (null == $siege->getAccountWithCurrency(CurrencyEnum::CURRENCY_MLC)) {
                $accountMLC = new AccountSiege();
                $accountMLC
                    ->setBalance($siege->getCompte())
                    ->setCurrency(CurrencyEnum::CURRENCY_MLC) // compte de monnaie papier au siege non nantie
                ;
                $siege->addAccount($accountMLC);
                $this->em->persist($accountMLC);
            }
            // if ($siege->getAccountWithCurrency(CurrencyEnum::CURRENCY_EURO) == null) {
            //     $accountEuro = new AccountSiege();
            //     $accountEuro
            //         ->setCurrency(CurrencyEnum::CURRENCY_EURO) // compte réel de nantissement // @TODO : offrir la possibilité de voir les opérations du compte euro du fond de garanti ? Ou plutôt de suivre les euros à récupérés aux comptoirs
            //     ;
            //     $siege->addAccount($accountEuro);
            //     $this->em->persist($accountEuro);
            // }
            if (null == $siege->getAccountWithCurrency(CurrencyEnum::CURRENCY_MLC_NANTIE)) {
                $accountMlcNantie = new AccountSiege();
                $accountMlcNantie
                    ->setBalance($siege->getCompteNantie())
                    ->setCurrency(CurrencyEnum::CURRENCY_MLC_NANTIE) // compte de monnaie papier nantie
                ;
                $siege->addAccount($accountMlcNantie);
                $this->em->persist($accountMlcNantie);
                $this->em->persist($siege);
            }

            $this->em->persist($groupe);
            if (null == $groupe->getAccountWithCurrency(CurrencyEnum::CURRENCY_MLC)) {
                $account = new AccountGroupe();
                $account
                    ->setBalance($groupe->getCompte())
                    ->setCurrency(CurrencyEnum::CURRENCY_MLC)
                ;
                $groupe->addAccount($account);
                $this->em->persist($account);
                $this->em->persist($groupe);
            }
408 409 410 411 412 413 414 415 416 417
            $comptoirData = $form['comptoir']->getData();
            $comptoirName = $comptoirData['name'];
            $comptoirCompte = $comptoirData['compte'];
            $comptoirGeoloc = $comptoirData['geoloc'];
            if (!empty($comptoir)) {
                $comptoir = new Comptoir();
                $comptoir->setName($comptoirName);
                $comptoir->setEnabled(true);
                $comptoir->setGeoloc($comptoirGeoloc);
                $comptoir->setGroupe($groupe);
Julien Jorry committed
418
                $this->em->persist($comptoir);
419 420 421 422 423 424 425 426 427 428
                if (null == $comptoir->getAccountWithCurrency(CurrencyEnum::CURRENCY_MLC)) {
                    $account = new AccountComptoir();
                    $account
                        ->setBalance(empty($comptoirCompte) ? $comptoirCompte : 0)
                        ->setCurrency(CurrencyEnum::CURRENCY_MLC)
                    ;
                    $comptoir->addAccount($account);
                    $this->em->persist($account);
                    $this->em->persist($comptoir);
                }
Julien Jorry committed
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
            }
            $this->userManager->updateUser($user);
            $this->em->persist($presta);
            if (null == $presta->getAccountWithCurrency(CurrencyEnum::CURRENCY_EMLC)) {
                $account = new AccountPrestataire();
                $account
                    ->setBalance($presta->getEcompte())
                    ->setCurrency(CurrencyEnum::CURRENCY_EMLC)
                ;
                $presta->addAccount($account);
                $this->em->persist($account);
            }
            if ($presta->isMlc() && null == $presta->getAccountWithCurrency(CurrencyEnum::CURRENCY_EURO)) {
                // Ajout du compte de fonctionnement euro pour le prestataire MLC
                $accountEuro = new AccountPrestataire();
                $accountEuro
                        ->setCurrency(CurrencyEnum::CURRENCY_EURO)
                    ;
                $presta->addAccount($accountEuro);
                $this->em->persist($accountEuro);
            }
            $this->em->persist($presta);
            foreach ($configs as $config) {
                $this->em->persist($config);
            }
            $this->em->flush();
            // Création de l'utilisateur avec ROLE_API pour le plugin Wordpress ou les applis tierces !
            $userAPI = $this->userManager->createUser();
            $userAPI->setEnabled(true);
            $userAPI->setUsername('userapi');
            $userAPI->setPassword(md5(random_bytes(10)));
            $userAPI->setEmail('userapi@kohinos.fr');
            $userAPI->addRole('ROLE_API');
            $this->userManager->updateUser($userAPI);

            $this->em->flush();
            $this->addFlash(
                'success',
                "BRAVO ! Vous venez de configurer le Kohinos. Vous pouvez maintenant accéder à l'interface d'administration."
            );

            $url = $this->generateUrl('fos_user_registration_confirmed');
            $response = new RedirectResponse($url);

            // @TODO : send mail with this event catch !
            $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

            return new RedirectResponse($this->generateUrl('sonata_admin_dashboard'));
        }

        return $this->render('@kohinos/installation.html.twig', [
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/geoloc", name="geolocAdresse")
     */
    public function geoLocAction(Request $request)
    {
        $referer = $request->headers->get('referer');
        if ($referer && !$request->isXmlHttpRequest()) {
            return $this->redirect($referer);
        } elseif (!$request->isXmlHttpRequest()) {
            return new Response('', Response::HTTP_BAD_REQUEST);
        }
        $status = 'success';
        $return = null;
        if (!empty($request->get('cpostal')) && !empty($request->get('ville'))) {
            try {
                // GEOCODING ADDRESS :
                $httpClient = new \Http\Adapter\Guzzle6\Client();
                $provider = Nominatim::withOpenStreetMapServer($httpClient, 'Mozilla/5.0');
                $geocoder = new \Geocoder\StatefulGeocoder($provider, 'fr');
                // Query geocoding from complete address
                $result = $geocoder->geocodeQuery(GeocodeQuery::create($request->get('adresse') . ' ' . $request->get('cpostal') . ' ' . $request->get('ville')));
                if (count($result) > 0) {
                    $coords = $result->first()->getCoordinates();
                    $return = ['lat' => $coords->getLatitude(), 'lon' => $coords->getLongitude()];
                } else {
                    $result = $geocoder->geocodeQuery(GeocodeQuery::create($request->get('cpostal') . ' ' . $request->get('ville')));
                    if (count($result) > 0) {
                        $coords = $result->first()->getCoordinates();
                        $return = ['lat' => $coords->getLatitude(), 'lon' => $coords->getLongitude()];
                    }
                }
            } catch (\Exception $e) {
                $status = 'error';
            }
        } else {
            $status = 'error';
        }

        return new JsonResponse(['status' => $status, 'data' => $return]);
    }

    /**
     * Choix du groupe local géré.
     *
     * @Route("/login/groupe/choice/{usergrpid}/{grpid}", name="groupe_choice")
     * @ParamConverter("group", class="App:Usergroup", options={"mapping": {"usergrpid": "id"}})
     * @ParamConverter("groupe", class="App:Groupe", options={"mapping": {"grpid": "id"}})
     * @IsGranted("ROLE_USER")
     */
    public function groupeChoiceAction(Usergroup $group, Groupe $groupe, Request $request)
    {
        $this->em->refresh($this->getUser());
        if (!($this->getUser()->getPossiblegroups()->exists(function ($key, $value) {
            return in_array('ROLE_GESTION_GROUPE', $value->getRoles()) || in_array('ROLE_CONTACT', $value->getRoles()) || in_array('ROLE_TRESORIER', $value->getRoles());
        }) and $this->getUser()->getGroupesgeres()->contains($groupe))) {
            $this->addFlash(
                'error',
                'Accès impossible !'
            );

            return $this->redirectToRoute('index');
        }
        $this->removeOldSessionParams();
        // On enregistre le groupe local choisit en session
        $this->session->set('_groupegere', $groupe);
        $this->reloadUserTokenFromGroup($group, $request);

551
        if (true == $this->getParameter('tav_env')) {
552 553 554 555
            return $this->redirectToRoute('index');
        } else {
            return $this->redirectToRoute('sonata_admin_dashboard');
        }
Julien Jorry committed
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
    }

    /**
     * Choix du comptoir géré.
     *
     * @Route("/login/comptoir/choice/{usergrpid}/{cptid}", name="comptoir_choice")
     * @ParamConverter("group", class="App:Usergroup", options={"mapping": {"usergrpid": "id"}})
     * @ParamConverter("comptoir", class="App:Comptoir", options={"mapping": {"cptid": "id"}})
     * @IsGranted("ROLE_USER")
     */
    public function comptoirChoiceAction(Usergroup $group, Comptoir $comptoir, Request $request)
    {
        $this->em->refresh($this->getUser());
        if (!($this->getUser()->getPossiblegroups()->exists(function ($key, $value) {
            return in_array('ROLE_COMPTOIR', $value->getRoles());
        }) and $this->getUser()->getComptoirsgeres()->contains($comptoir))) {
            $this->addFlash(
                'error',
                'Accès impossible !'
            );

            return $this->redirectToRoute('index');
        }
        $this->removeOldSessionParams();
        // On enregistre le comptoir choisit en session
        $this->session->set('_comptoirgere', $comptoir);
        $this->reloadUserTokenFromGroup($group, $request);

584
        if (true == $this->getParameter('tav_env')) {
585 586 587 588
            return $this->redirectToRoute('index');
        } else {
            return $this->redirectToRoute('sonata_admin_dashboard');
        }
Julien Jorry committed
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
    }

    /**
     * Choix du presta géré.
     *
     * @Route("/login/presta/choice/{usergrpid}/{prestaid}", name="presta_choice")
     * @ParamConverter("group", class="App:Usergroup", options={"mapping": {"usergrpid": "id"}})
     * @ParamConverter("prestataire", class="App:Prestataire", options={"mapping": {"prestaid": "id"}})
     * @IsGranted("ROLE_USER")
     */
    public function prestaChoiceAction(Usergroup $group, Prestataire $prestataire, Request $request)
    {
        $this->em->refresh($this->getUser());
        if (!(($this->getUser()->getPossiblegroups()->exists(function ($key, $value) {
            return in_array('ROLE_PRESTATAIRE', $value->getRoles());
        }) and $this->getUser()->getPrestataires()->contains($prestataire)) || (($this->getUser()->getPossiblegroups()->exists(function ($key, $value) {
            return in_array('ROLE_CAISSIER', $value->getRoles());
        }) and $this->getUser()->getCaissiers()->contains($prestataire))))
        ) {
            $this->addFlash(
                'error',
                'Accès impossible !'
            );

            return $this->redirectToRoute('index');
        }
        $this->removeOldSessionParams();
        // On enregistre le presta choisit en session
        $this->session->set('_prestagere', $prestataire);
        $this->reloadUserTokenFromGroup($group, $request);

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

    /**
     * @Route("/login/group/choice/{id}", name="usergroup_choice")
     * @IsGranted("ROLE_USER")
     */
    public function groupChoiceAction(Usergroup $group, Request $request)
    {
        if (!$this->getUser()->getPossiblegroups()->contains($group)) {
            $this->addFlash(
                'error',
                'Accès impossible !'
            );

            return $this->redirectToRoute('index');
        }
        $this->removeOldSessionParams();
        $this->reloadUserTokenFromGroup($group, $request);

640 641 642
        if (in_array('ROLE_SUPER_ADMIN', $this->getUser()->getRoles(), true)) {
            // c'est un administrateur
            return new RedirectResponse($this->router->generate('sonata_admin_dashboard'));
Julien Jorry committed
643
        }
644 645

        return new RedirectResponse($this->router->generate('index'));
Julien Jorry committed
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
    }

    private function removeOldSessionParams()
    {
        $this->session->remove('_choixGroup');
        $this->session->remove('_groupId');
        $this->session->remove('_groupegere');
        $this->session->remove('_comptoirgere');
        $this->session->remove('_prestagere');
    }

    private function reloadUserTokenFromGroup($group, $request)
    {
        $groups = [$group];
        if ($this->getUser()->getGroups() !== $groups) {
            $this->getUser()->setGroups($groups);
            $this->em->persist($this->getUser());
            $this->em->flush();
        }
        $token = new PostAuthenticationGuardToken(
            $this->getUser(),
            'main',
            $this->getUser()->getRoles()
        );
        $this->tokenStorage->setToken($token);
        $this->guard->authenticateUserAndHandleSuccess(
            $this->getUser(),
            $request,
            $this->authenticator,
            'main'
        );
        $this->session->set('_security_main', serialize($token));
    }
}