src/Controller/Participation/OdrController.php line 74

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Participation;
  3. use App\Controller\APIController;
  4. use App\Form\Participation\OdrParticipationType;
  5. use App\Form\User\UserRegisterType;
  6. use App\Manager\Participation\ParticipationOdrManager;
  7. use App\Manager\ParticipationManager;
  8. use App\Manager\User\UserManager;
  9. use App\Model\Operation\Odr;
  10. use App\Model\Participation\Odr as ParticipationOdr;
  11. use App\Model\State;
  12. use App\Model\User\Identity;
  13. use App\Model\User\User;
  14. use App\Security\Odr\OdrVoter;
  15. use Exception;
  16. use JMS\Serializer\DeserializationContext;
  17. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\Routing\Annotation\Route;
  21. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  22. use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
  23. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  24. use Symfony\Component\Serializer\Serializer;
  25. use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
  26. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  27. /**
  28.  * Class OdrController.
  29.  *
  30.  * @Route("/offre-de-remboursement")
  31.  */
  32. class OdrController extends APIController
  33. {
  34.     /**
  35.      * @Route("/inscription-au-club", name="kiwi_operation_odr_register_user")
  36.      */
  37.     public function registerOdrOffer(Request $request)
  38.     {
  39.         $user = new User();
  40.         $form $this->createForm(UserRegisterType::class, $user);
  41.         $user->setIdentity(
  42.             (new Identity())
  43.                 ->setFirstName('')
  44.                 ->setLastName('')
  45.         );
  46.         $form->handleRequest($request);
  47.         if ($form->isSubmitted() && $form->isValid()) {
  48.             $encoders = [new JsonEncoder()];
  49.             $normalizers = [new ObjectNormalizer()];
  50.             $serializer = new Serializer($normalizers$encoders);
  51.             $userRequest $request->request->get('user_register');
  52.             $json $serializer->serialize($form->getData(), 'json', [AbstractObjectNormalizer::SKIP_NULL_VALUES => true]);
  53.             $response $this->APIKiwi->register($json);
  54.             try {
  55.                 $user $this->serializer->deserialize($response->getContent(), User::class, 'json'DeserializationContext::create()->setGroups(['get_user']));
  56.                  $this->requestStack->getSession()->set('kiwi_register_odr_user_id'$user->getId());
  57.                  $this->requestStack->getSession()->set('kiwi_register_odr_email'$user->getEmail());
  58.                 $response $this->APIKiwi->postLoginAfterRegistration(['email' => $userRequest['email']['first'], 'password' => $userRequest['plainPassword']['first']]);
  59.                 $apiToken $this->decodeContent($response)['token'];
  60.                 $this->setTokenStorage($user$apiToken);
  61.                 return $this->redirectToRoute('kiwi_operation_odr_form_participation_user');
  62.             } catch (ClientExceptionInterface $e) {
  63.                 $this->catchRegisterError($response$e);
  64.             } catch (Exception $e) {
  65.                 $this->logger->error(sprintf('%s : %s'get_class($e), $e->getMessage()), $e->getTrace());
  66.                 $this->addFlash('warning'$this->translator->trans('api.validation.errors.generic', [], 'api'));
  67.             }
  68.         }
  69.         $odrResp $this->APIKiwi->getPublicKiwi('odr/'$this->requestStack->getSession()->get('kiwi_operation_odr_id'));
  70.         return $this->render('operation/odr/register_from_odr.html.twig', [
  71.             'form' => $form->createView(),
  72.             'odr' => $this->deserialize($odrResp->getContent(), Odr::class, 'get_odr'),
  73.         ]);
  74.     }
  75.     /**
  76.      * @Route("/formulaire-participation", name="kiwi_operation_odr_form_participation_user")
  77.      * @IsGranted("IS_AUTHENTICATED_FULLY")
  78.      * @throws Exception
  79.      * @throws TransportExceptionInterface
  80.      */
  81.     public function participationForm(Request $requestUserManager $userManagerParticipationOdrManager $participationOdrManagerParticipationManager $participationManager)
  82.     {
  83.         $userInterface $this->getUser();
  84.         $user $this->getUserData();
  85.         $odrId =  $this->requestStack->getSession()->get('kiwi_operation_odr_id');
  86.         $offerResp $participationOdrManager->getOdrInformation($odrId);
  87.         $odrWithRelations $this->deserialize($offerResp->getContent(), Odr::class, 'get_odrs');
  88.         $nbParticipationsUser $this->APIKiwi->getKiwi(['path' => '/participation-odrs/user/operation/'.$odrId.'?reparticipation=false''token' => $this->getUser()->getToken()])->getContent(); //Retourne le nombre de participation de l'utilisateur à une opération
  89.         $nbParticipations $this->APIKiwi->getPublicKiwi('get-nb-participation-odr/'.$odrId)->getContent(); //Retourne le nombre de participation totale d'une opération
  90.         if ($nbParticipations >= $odrWithRelations->getMaxParticipationPerMonth()) {
  91.             $this->flashBag->add('danger''Cette offre est épuisé');
  92.             return $this->redirectToRoute('kiwi_operation_odr_show', ['odrId' => $odrId]);
  93.         }
  94.         if ('MONTHLY' === $odrWithRelations->getPeriodicity()) {
  95.             if (intval($nbParticipationsUser) >= $odrWithRelations->getMaxPartByUser()) {
  96.                 $this->flashBag->add('danger''Vous avez atteint votre quotas mensuel de participation pour cette offre.');
  97.                 return $this->redirectToRoute('kiwi_operation_odr_show', ['odrId' => $odrId]);
  98.             }
  99.         } else {
  100.             if (intval($nbParticipationsUser) >= $odrWithRelations->getMaxPartByUser()) {
  101.                 $this->flashBag->add('danger''Vous avez atteint votre quotas global de participation pour cette offre.');
  102.                 return $this->redirectToRoute('kiwi_operation_odr_show', ['odrId' => $odrId]);
  103.             }
  104.         }
  105.         return $this->buildParticipationPage($request$userManager$participationOdrManager$participationManager$user$userInterface$odrWithRelations);
  106.     }
  107.     private function catchRegisterError($response$e)
  108.     {
  109.         $content json_decode($response->getContent(false), true);
  110.         if (isset($content['@type']) && 'ConstraintViolationList' === $content['@type'] && isset($content['violations'])) {
  111.             foreach ($content['violations'] as $violation) {
  112.                 $this->addFlash(
  113.                     'warning',
  114.                     sprintf(
  115.                         '%s : %s',
  116.                         $this->translator->trans(sprintf('api.validation.properties.%s'$violation['propertyPath']), [], 'api'),
  117.                         $this->translator->trans(sprintf('api.validation.codes.%s'$violation['code']), [], 'api')
  118.                     )
  119.                 );
  120.             }
  121.         } else {
  122.             $this->logger->error(sprintf('%s : %s''ClientException'$e->getMessage()), $e->getTrace());
  123.             $this->addFlash('warning'$this->translator->trans('api.validation.errors.generic', [], 'api'));
  124.         }
  125.     }
  126.     /**
  127.      * @Route("/recapitulatif", name="kiwi_participation_recap_participation_odr")
  128.      * @IsGranted("IS_AUTHENTICATED_FULLY")
  129.      * @throws Exception|TransportExceptionInterface
  130.      */
  131.     public function recap()
  132.     {
  133.          $this->requestStack->getSession()->set('kiwi_target_path''kiwi_participation_recap_participation_odr');
  134.         $iban =  $this->requestStack->getSession()->get('kiwi_participation_iban_bic');
  135.         $ibanStart substr($iban['accountNumber'], 04);
  136.         $ibanEnd substr($iban['accountNumber'], -4);
  137.         $odrResp $this->APIKiwi->getPublicKiwi('odr/'$this->requestStack->getSession()->get('kiwi_operation_odr_id'));
  138.         return $this->render('participation/odr/recap.html.twig', [
  139.             'user' => $this->APIKiwi->getUserData($this->getUser()),
  140.             'odr' => $this->deserialize($odrResp->getContent(), Odr::class, 'get_odr'),
  141.             'eans' =>  $this->requestStack->getSession()->get('kiwi_participation_eans'),
  142.             'medias' =>  $this->requestStack->getSession()->get('kiwi_participation_odr_medias'),
  143.             'iban' => str_pad($ibanStartstrlen($iban['accountNumber']) - 8'*').$ibanEnd,
  144.             'bic' => $iban['bic'],
  145.         ]);
  146.     }
  147.     /**
  148.      * @Route("/confirmation", name="kiwi_participation_confirm_participation_odr")
  149.      * @IsGranted("IS_AUTHENTICATED_FULLY")
  150.      */
  151.     public function confirmParticipation(ParticipationOdrManager $participationOdrManager)
  152.     {
  153.         $participationId =  $this->requestStack->getSession()->get('kiwi_participation_participation_id');
  154.         $user $this->getUser();
  155.         $stateResp $this->APIKiwi->getKiwi(['path' => '/states?label=participation_progress''token' => $user->getToken()]);
  156.         $state $this->batchDeserialize(json_decode($stateResp->getContent(), true)['hydra:member'], State::class, 'get_states')[0];
  157.         if ( $this->requestStack->getSession()->has('kiwi_participation_nct_id')) {
  158.             $participationOdrManager->confirmParticipation($user$participationId,  $this->requestStack->getSession()->get('kiwi_participation_nct_id'), $state->getId(), true,  $this->requestStack->getSession()->get('kiwi_participation_token'));
  159.         } else {
  160.             $participationOdrManager->confirmParticipation($user$participationIdnull$state->getId(), falsenull);
  161.         }
  162.         $odrResp $this->APIKiwi->getPublicKiwi('odr/'$this->requestStack->getSession()->get('kiwi_operation_odr_id'));
  163.         $odr $this->deserialize($odrResp->getContent(), Odr::class, 'get_odr');
  164.         $participationOdrManager->postParticipationSmp($user$participationId);
  165.         if ( $this->requestStack->getSession()->has('kiwi_register_odr_user_id')) {
  166.              $this->requestStack->getSession()->clear();
  167.             return $this->render('participation/odr/register_confirmation.html.twig', [
  168.                 'odr' => $this->deserialize($odrResp->getContent(), Odr::class, 'get_odr'),
  169.             ]);
  170.         }
  171.         //Passe l'ancienne participation NCT au status participation_edited
  172.         if ( $this->requestStack->getSession()->has('kiwi_participation_nct_id')) {
  173.             $participationNctId =  $this->requestStack->getSession()->get('kiwi_participation_nct_id');
  174.             $stateResp $this->APIKiwi->getKiwi(['path' => '/states?label=participation_edited''token' => $user->getToken()]);
  175.             $state $this->batchDeserialize(json_decode($stateResp->getContent(), true)['hydra:member'], State::class, 'get_states')[0];
  176.             $participationOdrManager->confirmParticipation($user$participationNctIdnull$state->getId(), falsenull);
  177.         }
  178.          $this->requestStack->getSession()->clear();
  179.         return $this->render('participation/odr/confirmation.html.twig', [
  180.             'odr' => $odr,
  181.         ]);
  182.     }
  183.     /**
  184.      * @Route("/participation", name="participation_odr")
  185.      * @IsGranted("IS_AUTHENTICATED_FULLY")
  186.      */
  187.     public function index(): Response
  188.     {
  189.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  190.         $userInterface $this->getUser();
  191.         $participations $this->APIKiwi->getKiwi(['path' => '/participation-odrs/user''token' => $userInterface->getToken()]);
  192.         $template = isset($_ENV['PROJECT_TYPE']) && 'step' === $_ENV['PROJECT_TYPE'] ? 'participation/odr/index_tabs.html.twig' 'participation/odr/index.html.twig';
  193.         return $this->render($template, [
  194.             'participations' => $this->batchDeserialize(json_decode($participations->getContent(), true)['hydra:member'], ParticipationOdr::class, 'get_participation_odrs'),
  195.         ]);
  196.     }
  197.     /**
  198.      * @Route("/participation/{participationId}/operation/{odrId}", name="kiwi_show_participation_id")
  199.      * @IsGranted("IS_AUTHENTICATED_FULLY")
  200.      */
  201.     public function show($participationId$odrIdParticipationOdrManager $participationOdrManager): Response
  202.     {
  203.          $this->requestStack->getSession()->set('_target_path''kiwi_show_participation_id');
  204.          $this->requestStack->getSession()->set('_target_path_params', ['participationId' => $participationId'odrId' => $odrId]);
  205.         $this->denyAccessUnlessGranted(OdrVoter::GET_ODR_DELIVERY);
  206.         $user $this->getUser();
  207.         $odrResp $this->APIKiwi->getPublicKiwi('operation-odr/'.$odrId);
  208.         $participationResp $participationOdrManager->getParticipationIdByUser($user$participationId);
  209.         $participation $this->deserialize($participationResp->getContent(), ParticipationOdr::class, 'get_participation_odr_by_id');
  210.          $this->requestStack->getSession()->set('kiwi_operation_odr_id'$odrId);
  211.         if (State::PARTICIPATION_UNCONFORMED_TEMP == $participation->getState()->getLabel()) {
  212.              $this->requestStack->getSession()->set('kiwi_participation_nct_id'$participationId);
  213.         }
  214.         return $this->render('participation/odr/detail_participation.html.twig', [
  215.             'user' => $this->APIKiwi->getUserData($this->getUser()),
  216.             'odr' => $this->deserialize($odrResp->getContent(), Odr::class, 'get_odr'),
  217.             'participation' => $participation,
  218.         ]);
  219.     }
  220.     /**
  221.      * @Route("/formulaire-reparticipation/{participationId}", name="kiwi_operation_odr_form_reparticipation_user")
  222.      * @IsGranted("IS_AUTHENTICATED_FULLY")
  223.      */
  224.     public function reparticipationForm(Request $requestUserManager $userManager$participationIdParticipationOdrManager $participationOdrManagerParticipationManager $participationManager)
  225.     {
  226.         $userInterface $this->getUser();
  227.         $user $this->getUserData();
  228.         $odrId =  $this->requestStack->getSession()->get('kiwi_operation_odr_id');
  229.         $offerResp $participationOdrManager->getOdrInformation($odrId);
  230.         $odrWithRelations $this->deserialize($offerResp->getContent(), Odr::class, 'get_odrs');
  231.         $participationResp $participationOdrManager->getReParticipationIdByUser($userInterface$participationId);
  232.         $participation $this->deserialize($participationResp->getContent(), ParticipationOdr::class, 'get_participation_odr_by_id');
  233.         return $this->buildParticipationPage($request$userManager$participationOdrManager$participationManager$user$userInterface$odrWithRelationstrue$participation);
  234.     }
  235.     private function buildParticipationPage(Request $requestUserManager $userManagerParticipationOdrManager $participationOdrManagerParticipationManager $participationManager$user$userInterface$odrWithRelations$edit false$participation null)
  236.     {
  237.         $form $this->createForm(OdrParticipationType::class, [
  238.             'user' => $user,
  239.             'eans' => $odrWithRelations->getDetailsOdr()->getEans(),
  240.             'edit' => $edit,
  241.             'participation' => $participation,
  242.         ]);
  243.         $form->handleRequest($request);
  244.         if ($form->isSubmitted() && $form->isValid()) {
  245.             $data $form->getData();
  246.             $address = [
  247.                 'street' => $data['street'],
  248.                 'complement' => $data['complement'],
  249.                 'postalCode' => $data['postalCode'],
  250.                 'city' => $data['city'],
  251.             ];
  252.             $eans $data['eans'];
  253.             $iban null;
  254.             if (!array_key_exists('editIban'$data)) {
  255.                 $iban $participationOdrManager->setIban($data['accountNumber'], $data['bic']);
  256.             } else {
  257.                 if ($data['editIban'] && !$edit) {
  258.                     $iban $participationOdrManager->setIban($data['accountNumber'], $data['bic']);
  259.                 }
  260.             }
  261.             if ($participation) {
  262.                 $iban $participationOdrManager->setIban($participation->getIban(), $participation->getBic());
  263.                  $this->requestStack->getSession()->set('kiwi_participation_token'$participation->getToken());
  264.             }
  265.              $this->requestStack->getSession()->set('kiwi_participation_eans'$eans);
  266.              $this->requestStack->getSession()->set('kiwi_target_path''kiwi_participation_recap_participation_odr');
  267.             if (!$iban) {
  268.                  $this->requestStack->getSession()->set('kiwi_participation_iban_bic'$participationOdrManager->setIban($user->getIbans()[0]->getHiddenAccountNumber(), $user->getIbans()[0]->getBic()));
  269.             } else {
  270.                  $this->requestStack->getSession()->set('kiwi_participation_iban_bic'$iban);
  271.             }
  272.             if ((empty($user->getSiret()) || empty($user->getCompanyName()) || empty($user->getIdentity()->getLastName()) || empty($user->getIdentity()->getFirstName())) || empty($user->getPhoneNumber())) {
  273.                 if (!array_key_exists('phoneNumber'$data)) {
  274.                     $data['phoneNumber'] = $user->getPhoneNumber();
  275.                 }
  276.                 $user->getIdentity()
  277.                     ->setLastName($data['lastName'])
  278.                     ->setFirstName($data['firstName']);
  279.                 $user
  280.                     ->setSiret($data['siret'])
  281.                     ->setCompanyName($data['companyName'])
  282.                     ->setPhoneNumber($data['phoneNumber']);
  283.                 $userManager->sendCreateOrUpdateDataCustomerToSalesforce($userInterface);
  284.                 $userManager->requestUser($userInterface'/users/' $userInterface->getId(), $user'put_user_general');
  285.             }
  286.             $data $participationOdrManager->setDeliveryInformation($data$address$user);
  287.             $data['user'] = '/api/users/'.$userInterface->getId();
  288.             $userManager->createOrUpdateDelivery($user$userInterface$data);
  289.             //Participation
  290.             $filesArray $participationManager->postFiles($userInterface$request->files->get('odr_participation')['file']);
  291.              $this->requestStack->getSession()->set('kiwi_participation_odr_medias'$filesArray);
  292.             $participation $participationOdrManager->postParticipation($userInterface$odrWithRelations->getId(), $eans$filesArray$iban);
  293.             $participationId substr($participation[0], (strrpos($participation[0], '/') + 1));
  294.              $this->requestStack->getSession()->set('kiwi_participation_participation_id'$participationId);
  295.             return $this->redirectToRoute('kiwi_participation_recap_participation_odr');
  296.         }
  297.         $odrResp $this->APIKiwi->getPublicKiwi('odr/'$this->requestStack->getSession()->get('kiwi_operation_odr_id'));
  298.         return $this->render('operation/odr/address_delivery.html.twig', [
  299.             'form' => $form->createView(),
  300.             'odr' => $this->deserialize($odrResp->getContent(), Odr::class, 'get_odr'),
  301.         ]);
  302.     }
  303. }