src/Controller/Kernix/Api/v1/ReservationController.php line 48

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Kernix\Api\v1;
  3. use App\Entity\Voyage;
  4. use App\Entity\VoyageCotation;
  5. use App\Entity\VoyagePeriode;
  6. use App\Entity\VoyagePeriodeCotation;
  7. use App\Entity\VoyageService AS VoyService;
  8. use App\Entity\Service;
  9. use App\Service\VoyageService;
  10. use App\Service\KernixApiService;
  11. use App\Service\KernixService;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Translation\TranslatorInterface;
  17. use JMS\Serializer\SerializerBuilder;
  18. use JMS\Serializer\SerializationContext;
  19. use Doctrine\ORM\EntityManagerInterface;
  20. use Symfony\Component\HttpFoundation\JsonResponse;
  21. //use OpenApi\Annotations as OA;
  22. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  23. use Symfony\Component\Validator\Validator\ValidatorInterface;
  24. use App\DTO\KernixReservationDTO;
  25. use App\DTO\KernixParticipantDTO;
  26. use App\DTO\KernixHebergementDTO;
  27. use App\DTO\KernixActiviteDTO;
  28. use App\DTO\KernixAjustementDTO;
  29. use App\DTO\KernixPaiementDTO;
  30. use App\DTO\KernixLigneSupplementaireDTO;
  31. use App\DTO\KernixAjustementDataDTO;
  32. use App\DTO\KernixAjustementDataParticipantDTO;
  33. use App\DTO\DolibarrUserFacturationDTO;
  34. use App\DTO\DolibarrUserLivraisonDTO;
  35. /**
  36.  * @Route("/kernix/api/v1/reservations", name="kernix_api_v1_reservations_")
  37.  */
  38. class ReservationController extends AbstractController
  39. {
  40.     /**
  41.      * @Route("/", name="get_reservations", methods={"GET"})
  42.      */
  43.     public function getReservations(Request $requestKernixApiService $serviceEntityManagerInterface $emTranslatorInterface $translator
  44.     {
  45.         // Gère un timestamp
  46.         $timestamp $request->query->get('timestamp'null);        
  47.         $params = array(
  48.             'timestamp' => $timestamp,
  49.             'conditions' => [
  50.             ]
  51.         );
  52.         $data $service->getDossiers($params);
  53.         return $this->json($data);
  54.     }
  55.     /**
  56.      * @Route("/new", name="new_reservation_kernix", methods={"POST"})
  57.      */
  58.     public function newReservation(Request $requestValidatorInterface $validatorKernixApiService $apiServiceKernixService $serviceEntityManagerInterface $emTranslatorInterface $translator) {
  59.     
  60.         $dto  = new KernixReservationDTO();
  61.         $data $request->request->all(); // fonctionne avec form-data
  62.     
  63.         // Champs simples
  64.         $dto->code            $data['code' ] ?? '';
  65.         $dto->email           $data['email'] ?? '';
  66.         $dto->voyage_id       = isset($data['voyage_id' ]) ? $data['voyage_id' ] : '';
  67.         $dto->formule_id      = isset($data['formule_id']) ? $data['formule_id'] : '';
  68.         $dto->type            $data['type'   ] ?? '';
  69.         $dto->statut          $data['statut' ] ?? '';
  70.         $dto->langue          $data['langue' ] ?? '';
  71.         $dto->date_depart     $data['date_depart'] ?? '';
  72.         $dto->date_retour     $data['date_retour'] ?? '';
  73.         $dto->emetteur        $data['emetteur'] ?? '';
  74.         if (isset($data['statut_paiement'])) {
  75.             $dto->statut_paiement $data['statut_paiement'];
  76.         }
  77.         if (isset($data['mode_paiement'])) {
  78.             $dto->mode_paiement $data['mode_paiement'];
  79.         }
  80.         if (isset($data['montant_total'])) {
  81.             $dto->montant_total $data['montant_total' ];
  82.         }
  83.         if (isset($data['montant_base'])) {
  84.             $dto->montant_base $data['montant_base' ];
  85.         }
  86.         if (isset($data['montant_paye'])) {
  87.             $dto->montant_paye $data['montant_paye' ];
  88.         }
  89.         // data facturation
  90.         if ($request->request->has('facturation')) {
  91.             $facturationData $request->request->get('facturation');
  92.             if (is_array($facturationData)) {
  93.                 $facturation = new DolibarrUserFacturationDTO();
  94.                 $facturation->lastname  $facturationData['nom'        ] ?? '';
  95.                 $facturation->firstname $facturationData['prenom'     ] ?? '';
  96.                 $facturation->phone     $facturationData['telephone'  ] ?? '';
  97.                 $facturation->email     $facturationData['email'      ] ?? '';
  98.                 $facturation->address   $facturationData['adresse'    ] ?? '';
  99.                 $facturation->zip       $facturationData['code_postal'] ?? '';
  100.                 $facturation->town      $facturationData['ville'      ] ?? '';
  101.                 $facturation->country   $facturationData['pays'       ] ?? '';
  102.                 $dto->facturation $facturation;
  103.             }
  104.         }
  105.         // data livraison
  106.         if ($request->request->has('livraison')) {
  107.             $livraisonData $request->request->get('livraison');
  108.             if (is_array($livraisonData)) {
  109.                 $livraison = new DolibarrUserLivraisonDTO();
  110.                 $livraison->lastname       $livraisonData['nom'           ] ?? '';
  111.                 $livraison->firstname      $livraisonData['prenom'        ] ?? '';
  112.                 $livraison->phone          $livraisonData['telephone'     ] ?? '';
  113.                 $livraison->email          $livraisonData['email'         ] ?? '';
  114.                 $livraison->address        $livraisonData['adresse'       ] ?? '';
  115.                 $livraison->zip            $livraisonData['code_postal'   ] ?? '';
  116.                 $livraison->town           $livraisonData['ville'         ] ?? '';
  117.                 $livraison->country        $livraisonData['pays'          ] ?? '';
  118.                 $livraison->mode_transport $livraisonData['mode_transport'] ?? '';
  119.                 $livraison->lieu_livraison $livraisonData['lieu_livraison'] ?? '';
  120.                 $livraison->societe        $livraisonData['societe'       ] ?? '';
  121.                 $dto->livraison $livraison;
  122.             }
  123.         }
  124.         // Participants
  125.         if (isset($data['participants']) && is_array($data['participants'])) {
  126.             foreach ($data['participants'] as $participantData) {
  127.                 $participant = new KernixParticipantDTO();
  128.                 $participant->prenom                 $participantData['prenom'] ?? null;
  129.                 $participant->nom                    $participantData['nom'] ?? null;
  130.                 $participant->date_naissance         $participantData['date_naissance'] ?? '';
  131.                 $participant->taille                 = isset($participantData['taille']) ? (float) $participantData['taille'] : null;
  132.                 $participant->taille_pied            $participantData['taille_pied'] ?? null;
  133.                 $participant->taille_pouce           $participantData['taille_pouce'] ?? null;
  134.                 $participant->taille_pied_pouce      $participantData['taille_pied_pouce'] ?? null;
  135.                 $participant->langue                 $participantData['langue'] ?? null;
  136.                 $participant->location_velo          $participantData['location_velo'] ?? null;
  137.                 $participant->velo                   $participantData['velo'] ?? null;
  138.                 $participant->prix_velo              = isset($participantData['prix_velo']) ? (float) $participantData['prix_velo'] : null;
  139.                 $participant->souscription_assurance $participantData['souscription_assurance'] ?? 0;
  140.                 $participant->location_casque        $participantData['location_casque'] ?? 0;
  141.                 $participant->supp_single            $participantData['supp_single'] ?? 0;
  142.     
  143.                 $dto->participants[] = $participant;
  144.             }
  145.         }
  146.         // Hebergement
  147.         if (isset($data['hebergements']) && is_array($data['hebergements'])) {
  148.             foreach ($data['hebergements'] as $hebergementData) {
  149.                 $hebergement = new KernixHebergementDTO();
  150.                 $hebergement->numero_chambre $hebergementData['numero_chambre'] ?? '';
  151.                 $hebergement->type           $hebergementData['type'] ?? null;
  152.                 $hebergement->participants   $hebergementData['participants'] ?? null;
  153.                 $dto->hebergements[] = $hebergement;
  154.             }
  155.         }
  156.         // Activités
  157.         if (isset($data['activites']) && is_array($data['activites'])) {
  158.             foreach ($data['activites'] as $activiteData) {
  159.                 $activite = new KernixActiviteDTO();
  160.                 $activite->id           $activiteData['id'] ?? null;
  161.                 $activite->participants $activiteData['participants'] ?? null;
  162.                 $dto->activites[] = $activite;
  163.             }
  164.         }
  165.         // Ajustements
  166.         if (isset($data['ajustements']) && is_array($data['ajustements'])) {
  167.             foreach ($data['ajustements'] as $ajustementData) {
  168.                 $ajustement = new KernixAjustementDTO();
  169.                 $ajustement->id           $ajustementData['id'] ?? null;
  170.                 $ajustement->animalNom    $ajustementData['animal_nom'  ] ?? ''  ;
  171.                 $ajustement->animalRace   $ajustementData['animal_race' ] ?? ''  ;
  172.                 $ajustement->animalPoids  $ajustementData['animal_poids'] ?? ''  ;
  173.                 $ajustement->dates        $ajustementData['dates'       ] ?? []  ;
  174.                 
  175.                 if (is_array($ajustementData['data'])) {
  176.                     foreach ($ajustementData['data'] as $ajustementDataData) {
  177.                         $ajustementPart = new KernixAjustementDataDTO();
  178.                         $ajustementPart->montant $ajustementDataData['montant'] ?? null;
  179.                         if (array_key_exists('participants'$ajustementDataData) && is_array($ajustementDataData['participants'])) {
  180.                             foreach ($ajustementDataData['participants'] as $ajustementParticipantData) {
  181.                                 $ajustementParticipant = new KernixAjustementDataParticipantDTO();
  182.                                 $ajustementParticipant->tarifId $ajustementParticipantData['tarif_id'] ?? '';
  183.                                 $ajustementParticipant->numero  $ajustementParticipantData['numero'  ] ?? '';
  184.                                 $ajustementPart->participants[] = $ajustementParticipant;
  185.                             }
  186.                         }
  187.                         $ajustement->data[] = $ajustementPart;
  188.                     }
  189.                 }
  190.                 $dto->ajustements[] = $ajustement;
  191.             }
  192.         }
  193.         // Paiements
  194.         if (isset($data['paiements']) && is_array($data['paiements']) && count($data['paiements']) > 0) {
  195.             foreach ($data['paiements'] as $payData) {
  196.                 $pay = new KernixPaiementDTO();
  197.                 $pay->emetteur       $payData['emetteur'] ?? '';
  198.                 $pay->code_reduction $payData['code_reduction'] ?? '';
  199.                 if (isset($payData['mode_paiement'])) {
  200.                     $pay->mode_paiement $payData['mode_paiement'];
  201.                 }
  202.                 if (isset($payData['montant'])) {
  203.                     $pay->montant $payData['montant'];
  204.                 }
  205.                 $dto->paiements[]  = $pay;
  206.             }
  207.         }
  208.         // Suppléments
  209.         if (isset($data['supplements']) && is_array($data['supplements']) && count($data['supplements']) > 0) {
  210.             foreach ($data['supplements'] as $suppData) {
  211.                 $supp = new KernixLigneSupplementaireDTO();
  212.                 $supp->libelle  $suppData['libelle' ] ?? '';
  213.                 $supp->quantite $suppData['quantite'] ?? '';
  214.                 $supp->code     $suppData['code'    ] ?? '';
  215.                 if (isset($suppData['montant'])) {
  216.                     $supp->montant $suppData['montant'];
  217.                 }
  218.                 $dto->ligneSupplementaires[] = $supp;
  219.             }
  220.         }
  221.         // Réductions
  222.         if (isset($data['reductions']) && is_array($data['reductions']) && count($data['reductions']) > 0) {
  223.             foreach ($data['reductions'] as $reducData) {
  224.                 $reduc = new KernixLigneSupplementaireDTO();
  225.                 $reduc->libelle  $reducData['libelle' ] ?? '';
  226.                 $reduc->quantite $reducData['quantite'] ?? '';
  227.                 $reduc->code     $reducData['code'    ] ?? '';
  228.                 if (isset($reducData['montant'])) {
  229.                     $reduc->montant $reducData['montant'];
  230.                 }
  231.                 $dto->reductions[] = $reduc;
  232.             }
  233.         }
  234.         // Validation
  235.         $errors $validator->validate($dto);
  236.         if (count($errors) > 0) {
  237.             $errorMessages = [];
  238.             foreach ($errors as $error) {
  239.                 $errorMessages[] = sprintf('%s: %s'$error->getPropertyPath(), $error->getMessage());
  240.             }
  241.             return new JsonResponse([
  242.                 'status' => 'error',
  243.                 'message' => $errorMessages,
  244.             ], JsonResponse::HTTP_BAD_REQUEST);
  245.         }
  246.         
  247.         // Vérifie l'email 
  248.         $user $service->testUser($data['email']);
  249.         
  250.         if (false === $user) {
  251.             return new JsonResponse([
  252.                 'status'  => 'error'
  253.                 'message' => sprintf('User %s inconnu'$data['email'])], Response::HTTP_BAD_REQUEST);
  254.         }
  255.         
  256.         // Vérifie les voyages
  257.         $voyage  $em->getRepository(Voyage::class)->findOneById($data['voyage_id' ]);
  258.         $formule $em->getRepository(Voyage::class)->findOneById($data['formule_id']);
  259.         
  260.         if (null === $voyage || null === $formule) {
  261.             return new JsonResponse([
  262.                 'status'  => 'error'
  263.                 'message' => sprintf('Voyage %s introuvable'$data['voyage'])], Response::HTTP_BAD_REQUEST);
  264.         }
  265.         
  266.         // Tout est OK on lance la création
  267.         $resa $service->newReservation($data$voyage$user);
  268.         if (null !== $resa) {
  269.             if (is_array($resa)) {
  270.                 return new JsonResponse($resa);
  271.             }
  272.             $data $apiService->getDossiersById($resa->getDossier()->getId());
  273.         }
  274.         return $this->json($data);
  275.     }
  276.     /**
  277.      * @Route("/email/{email}", name="get_reservation_by_email", methods={"GET"}, defaults={ "id":null, "option":"email" })
  278.      */
  279.     public function getReservationByEmail(Request $requestKernixApiService $service$email=null) {
  280.         if (null === $email) {
  281.             return new JsonResponse(['status'  => 'error''message' => 'Email est manquant'], Response::HTTP_BAD_REQUEST);
  282.         }      
  283.         if (false === $service->verifierEmail($email)) { // email chelou
  284.             return new JsonResponse(['status'  => 'error''message' => 'Email incorrect'], Response::HTTP_BAD_REQUEST);
  285.         }
  286.         if (false === $service->isPaxExists($email)) {
  287.             return new JsonResponse(['status' => 'error''message' => 'Utilisateur non trouvé'], Response::HTTP_NOT_FOUND);
  288.         }
  289.         // Gère un timestamp
  290.         $timestamp $request->query->get('timestamp'null);        
  291.         $data $service->getDossiersByMail($email$timestamp);
  292.         return new JsonResponse(['status' => 'success''data' => $data], Response::HTTP_OK);
  293.     }
  294.     /**
  295.      * @Route("/devis/{id}", name="get_reservation_devis", methods={"GET"})
  296.      */
  297.     public function getReservationDevis(Request $requestKernixApiService $service$id) {
  298.       $rowid $id;
  299.       if (null === $rowid) {
  300.           return new JsonResponse(['status'  => 'error''message' => sprintf('Identifiant invalide'$rowid)], Response::HTTP_BAD_REQUEST);
  301.       }
  302.       if (!preg_match('/^\d+$/'$rowid)) {
  303.           return new JsonResponse(['status'  => 'error''message' => sprintf('Identifiant "%s" invalide'$rowid)], Response::HTTP_BAD_REQUEST);
  304.       }
  305.       $data $service->getDossierDevis($rowid);
  306.       return $this->json($data);
  307.     }
  308.     /**
  309.      * @Route("/facture/{id}", name="get_reservation_facture", methods={"GET"})
  310.      */
  311.     public function getReservationFacture(Request $requestKernixApiService $service$id) {
  312.       $rowid $id;
  313.       if (null === $rowid) {
  314.           return new JsonResponse(['status'  => 'error''message' => sprintf('Identifiant invalide'$rowid)], Response::HTTP_BAD_REQUEST);
  315.       }
  316.       if (!preg_match('/^\d+$/'$rowid)) {
  317.           return new JsonResponse(['status'  => 'error''message' => sprintf('Identifiant "%s" invalide'$rowid)], Response::HTTP_BAD_REQUEST);
  318.       }
  319.       $data $service->getDossierFacture($rowid);
  320.       return $this->json($data);
  321.     }
  322.     /**
  323.      * @Route("/itineraire/{dossierId}", name="get_reservation_itineraire", methods={"GET"})
  324.      */
  325.     public function getReservationItineraire(Request $requestKernixApiService $service$dossierId) {
  326.       $rowid $dossierId;
  327.       if (null === $rowid) {
  328.           return new JsonResponse(['status'  => 'error''message' => sprintf('Identifiant dossier invalide'$rowid)], Response::HTTP_BAD_REQUEST);
  329.       }
  330.       if (!preg_match('/^\d+$/'$rowid)) {
  331.           return new JsonResponse(['status'  => 'error''message' => sprintf('Identifiant dossier "%s" invalide'$rowid)], Response::HTTP_BAD_REQUEST);
  332.       }
  333.       $data $service->getDossierDocumentItineraire($dossierId);
  334.       return $this->json($data);
  335.     }
  336.     /**
  337.      * @Route("/payment/{dossierId}", name="new_reservation_payment_kernix", methods={"GET","POST"})
  338.      */
  339.     public function newPaiement(Request $requestValidatorInterface $validatorKernixApiService $apiServiceKernixService $serviceEntityManagerInterface $emTranslatorInterface $translator$dossierId) {
  340.         $data $request->request->all(); // fonctionne avec form-data
  341.         $toProcess     = [];
  342.         $errorMessages = [];
  343.         // Paiements
  344.         if (isset($data['paiements']) && is_array($data['paiements']) && count($data['paiements']) > 0) {
  345.             foreach ($data['paiements'] as $payData) {
  346.                 $pay = new KernixPaiementDTO();
  347.                 $pay->emetteur       $payData['emetteur'] ?? '';
  348.                 $pay->code_reduction $payData['code_reduction'] ?? '';
  349.                 if (isset($payData['mode_paiement'])) {
  350.                     $pay->mode_paiement $payData['mode_paiement'];
  351.                 }
  352.                 if (isset($payData['montant'])) {
  353.                     $pay->montant $payData['montant'];
  354.                 }
  355.                 // Validation
  356.                 $errors $validator->validate($pay);
  357.                 if (count($errors) > 0) {
  358.                     foreach ($errors as $error) {
  359.                         $errorMessages[] = sprintf('%s: %s'$error->getPropertyPath(), $error->getMessage());
  360.                     }
  361.                 } else {
  362.                     $toProcess[] = $payData;
  363.                 }
  364.             }
  365.             if (count($errors) > 0) {
  366.                 return new JsonResponse([
  367.                     'status' => 'error',
  368.                     'message' => $errorMessages,
  369.                 ], JsonResponse::HTTP_BAD_REQUEST);
  370.             }
  371.             $statut $service->addPaiements($dossierId$toProcess);
  372.             if (false !== $statut) {
  373.                  return $this->json($statut);
  374.             }
  375.             else {
  376.                  return new JsonResponse([
  377.                      'status' => 'error',
  378.                      'message' => ['Une erreur est survenue, veuillez contacter un admin'],
  379.                  ], JsonResponse::HTTP_BAD_REQUEST);
  380.             }
  381.         } else {
  382.              return new JsonResponse([
  383.                  'status' => 'error',
  384.                  'message' => ['Il manque les paiements'],
  385.              ], JsonResponse::HTTP_BAD_REQUEST);
  386.         }
  387.     }
  388. }