<?php
namespace App\Controller\Kernix\Api\v1;
use App\Entity\Voyage;
use App\Entity\VoyageCotation;
use App\Entity\VoyagePeriode;
use App\Entity\VoyagePeriodeCotation;
use App\Entity\VoyageService AS VoyService;
use App\Entity\Service;
use App\Service\VoyageService;
use App\Service\KernixApiService;
use App\Service\KernixService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Translation\TranslatorInterface;
use JMS\Serializer\SerializerBuilder;
use JMS\Serializer\SerializationContext;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
//use OpenApi\Annotations as OA;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use App\DTO\KernixReservationDTO;
use App\DTO\KernixParticipantDTO;
use App\DTO\KernixHebergementDTO;
use App\DTO\KernixActiviteDTO;
use App\DTO\KernixAjustementDTO;
use App\DTO\KernixPaiementDTO;
use App\DTO\KernixLigneSupplementaireDTO;
use App\DTO\KernixAjustementDataDTO;
use App\DTO\KernixAjustementDataParticipantDTO;
use App\DTO\DolibarrUserFacturationDTO;
use App\DTO\DolibarrUserLivraisonDTO;
/**
* @Route("/kernix/api/v1/reservations", name="kernix_api_v1_reservations_")
*/
class ReservationController extends AbstractController
{
/**
* @Route("/", name="get_reservations", methods={"GET"})
*/
public function getReservations(Request $request, KernixApiService $service, EntityManagerInterface $em, TranslatorInterface $translator)
{
// Gère un timestamp
$timestamp = $request->query->get('timestamp', null);
$params = array(
'timestamp' => $timestamp,
'conditions' => [
]
);
$data = $service->getDossiers($params);
return $this->json($data);
}
/**
* @Route("/new", name="new_reservation_kernix", methods={"POST"})
*/
public function newReservation(Request $request, ValidatorInterface $validator, KernixApiService $apiService, KernixService $service, EntityManagerInterface $em, TranslatorInterface $translator) {
$dto = new KernixReservationDTO();
$data = $request->request->all(); // fonctionne avec form-data
// Champs simples
$dto->code = $data['code' ] ?? '';
$dto->email = $data['email'] ?? '';
$dto->voyage_id = isset($data['voyage_id' ]) ? $data['voyage_id' ] : '';
$dto->formule_id = isset($data['formule_id']) ? $data['formule_id'] : '';
$dto->type = $data['type' ] ?? '';
$dto->statut = $data['statut' ] ?? '';
$dto->langue = $data['langue' ] ?? '';
$dto->date_depart = $data['date_depart'] ?? '';
$dto->date_retour = $data['date_retour'] ?? '';
$dto->emetteur = $data['emetteur'] ?? '';
if (isset($data['statut_paiement'])) {
$dto->statut_paiement = $data['statut_paiement'];
}
if (isset($data['mode_paiement'])) {
$dto->mode_paiement = $data['mode_paiement'];
}
if (isset($data['montant_total'])) {
$dto->montant_total = $data['montant_total' ];
}
if (isset($data['montant_base'])) {
$dto->montant_base = $data['montant_base' ];
}
if (isset($data['montant_paye'])) {
$dto->montant_paye = $data['montant_paye' ];
}
// data facturation
if ($request->request->has('facturation')) {
$facturationData = $request->request->get('facturation');
if (is_array($facturationData)) {
$facturation = new DolibarrUserFacturationDTO();
$facturation->lastname = $facturationData['nom' ] ?? '';
$facturation->firstname = $facturationData['prenom' ] ?? '';
$facturation->phone = $facturationData['telephone' ] ?? '';
$facturation->email = $facturationData['email' ] ?? '';
$facturation->address = $facturationData['adresse' ] ?? '';
$facturation->zip = $facturationData['code_postal'] ?? '';
$facturation->town = $facturationData['ville' ] ?? '';
$facturation->country = $facturationData['pays' ] ?? '';
$dto->facturation = $facturation;
}
}
// data livraison
if ($request->request->has('livraison')) {
$livraisonData = $request->request->get('livraison');
if (is_array($livraisonData)) {
$livraison = new DolibarrUserLivraisonDTO();
$livraison->lastname = $livraisonData['nom' ] ?? '';
$livraison->firstname = $livraisonData['prenom' ] ?? '';
$livraison->phone = $livraisonData['telephone' ] ?? '';
$livraison->email = $livraisonData['email' ] ?? '';
$livraison->address = $livraisonData['adresse' ] ?? '';
$livraison->zip = $livraisonData['code_postal' ] ?? '';
$livraison->town = $livraisonData['ville' ] ?? '';
$livraison->country = $livraisonData['pays' ] ?? '';
$livraison->mode_transport = $livraisonData['mode_transport'] ?? '';
$livraison->lieu_livraison = $livraisonData['lieu_livraison'] ?? '';
$livraison->societe = $livraisonData['societe' ] ?? '';
$dto->livraison = $livraison;
}
}
// Participants
if (isset($data['participants']) && is_array($data['participants'])) {
foreach ($data['participants'] as $participantData) {
$participant = new KernixParticipantDTO();
$participant->prenom = $participantData['prenom'] ?? null;
$participant->nom = $participantData['nom'] ?? null;
$participant->date_naissance = $participantData['date_naissance'] ?? '';
$participant->taille = isset($participantData['taille']) ? (float) $participantData['taille'] : null;
$participant->taille_pied = $participantData['taille_pied'] ?? null;
$participant->taille_pouce = $participantData['taille_pouce'] ?? null;
$participant->taille_pied_pouce = $participantData['taille_pied_pouce'] ?? null;
$participant->langue = $participantData['langue'] ?? null;
$participant->location_velo = $participantData['location_velo'] ?? null;
$participant->velo = $participantData['velo'] ?? null;
$participant->prix_velo = isset($participantData['prix_velo']) ? (float) $participantData['prix_velo'] : null;
$participant->souscription_assurance = $participantData['souscription_assurance'] ?? 0;
$participant->location_casque = $participantData['location_casque'] ?? 0;
$participant->supp_single = $participantData['supp_single'] ?? 0;
$dto->participants[] = $participant;
}
}
// Hebergement
if (isset($data['hebergements']) && is_array($data['hebergements'])) {
foreach ($data['hebergements'] as $hebergementData) {
$hebergement = new KernixHebergementDTO();
$hebergement->numero_chambre = $hebergementData['numero_chambre'] ?? '';
$hebergement->type = $hebergementData['type'] ?? null;
$hebergement->participants = $hebergementData['participants'] ?? null;
$dto->hebergements[] = $hebergement;
}
}
// Activités
if (isset($data['activites']) && is_array($data['activites'])) {
foreach ($data['activites'] as $activiteData) {
$activite = new KernixActiviteDTO();
$activite->id = $activiteData['id'] ?? null;
$activite->participants = $activiteData['participants'] ?? null;
$dto->activites[] = $activite;
}
}
// Ajustements
if (isset($data['ajustements']) && is_array($data['ajustements'])) {
foreach ($data['ajustements'] as $ajustementData) {
$ajustement = new KernixAjustementDTO();
$ajustement->id = $ajustementData['id'] ?? null;
$ajustement->animalNom = $ajustementData['animal_nom' ] ?? '' ;
$ajustement->animalRace = $ajustementData['animal_race' ] ?? '' ;
$ajustement->animalPoids = $ajustementData['animal_poids'] ?? '' ;
$ajustement->dates = $ajustementData['dates' ] ?? [] ;
if (is_array($ajustementData['data'])) {
foreach ($ajustementData['data'] as $ajustementDataData) {
$ajustementPart = new KernixAjustementDataDTO();
$ajustementPart->montant = $ajustementDataData['montant'] ?? null;
if (array_key_exists('participants', $ajustementDataData) && is_array($ajustementDataData['participants'])) {
foreach ($ajustementDataData['participants'] as $ajustementParticipantData) {
$ajustementParticipant = new KernixAjustementDataParticipantDTO();
$ajustementParticipant->tarifId = $ajustementParticipantData['tarif_id'] ?? '';
$ajustementParticipant->numero = $ajustementParticipantData['numero' ] ?? '';
$ajustementPart->participants[] = $ajustementParticipant;
}
}
$ajustement->data[] = $ajustementPart;
}
}
$dto->ajustements[] = $ajustement;
}
}
// Paiements
if (isset($data['paiements']) && is_array($data['paiements']) && count($data['paiements']) > 0) {
foreach ($data['paiements'] as $payData) {
$pay = new KernixPaiementDTO();
$pay->emetteur = $payData['emetteur'] ?? '';
$pay->code_reduction = $payData['code_reduction'] ?? '';
if (isset($payData['mode_paiement'])) {
$pay->mode_paiement = $payData['mode_paiement'];
}
if (isset($payData['montant'])) {
$pay->montant = $payData['montant'];
}
$dto->paiements[] = $pay;
}
}
// Suppléments
if (isset($data['supplements']) && is_array($data['supplements']) && count($data['supplements']) > 0) {
foreach ($data['supplements'] as $suppData) {
$supp = new KernixLigneSupplementaireDTO();
$supp->libelle = $suppData['libelle' ] ?? '';
$supp->quantite = $suppData['quantite'] ?? '';
$supp->code = $suppData['code' ] ?? '';
if (isset($suppData['montant'])) {
$supp->montant = $suppData['montant'];
}
$dto->ligneSupplementaires[] = $supp;
}
}
// Réductions
if (isset($data['reductions']) && is_array($data['reductions']) && count($data['reductions']) > 0) {
foreach ($data['reductions'] as $reducData) {
$reduc = new KernixLigneSupplementaireDTO();
$reduc->libelle = $reducData['libelle' ] ?? '';
$reduc->quantite = $reducData['quantite'] ?? '';
$reduc->code = $reducData['code' ] ?? '';
if (isset($reducData['montant'])) {
$reduc->montant = $reducData['montant'];
}
$dto->reductions[] = $reduc;
}
}
// Validation
$errors = $validator->validate($dto);
if (count($errors) > 0) {
$errorMessages = [];
foreach ($errors as $error) {
$errorMessages[] = sprintf('%s: %s', $error->getPropertyPath(), $error->getMessage());
}
return new JsonResponse([
'status' => 'error',
'message' => $errorMessages,
], JsonResponse::HTTP_BAD_REQUEST);
}
// Vérifie l'email
$user = $service->testUser($data['email']);
if (false === $user) {
return new JsonResponse([
'status' => 'error',
'message' => sprintf('User %s inconnu', $data['email'])], Response::HTTP_BAD_REQUEST);
}
// Vérifie les voyages
$voyage = $em->getRepository(Voyage::class)->findOneById($data['voyage_id' ]);
$formule = $em->getRepository(Voyage::class)->findOneById($data['formule_id']);
if (null === $voyage || null === $formule) {
return new JsonResponse([
'status' => 'error',
'message' => sprintf('Voyage %s introuvable', $data['voyage'])], Response::HTTP_BAD_REQUEST);
}
// Tout est OK on lance la création
$resa = $service->newReservation($data, $voyage, $user);
if (null !== $resa) {
if (is_array($resa)) {
return new JsonResponse($resa);
}
$data = $apiService->getDossiersById($resa->getDossier()->getId());
}
return $this->json($data);
}
/**
* @Route("/email/{email}", name="get_reservation_by_email", methods={"GET"}, defaults={ "id":null, "option":"email" })
*/
public function getReservationByEmail(Request $request, KernixApiService $service, $email=null) {
if (null === $email) {
return new JsonResponse(['status' => 'error', 'message' => 'Email est manquant'], Response::HTTP_BAD_REQUEST);
}
if (false === $service->verifierEmail($email)) { // email chelou
return new JsonResponse(['status' => 'error', 'message' => 'Email incorrect'], Response::HTTP_BAD_REQUEST);
}
if (false === $service->isPaxExists($email)) {
return new JsonResponse(['status' => 'error', 'message' => 'Utilisateur non trouvé'], Response::HTTP_NOT_FOUND);
}
// Gère un timestamp
$timestamp = $request->query->get('timestamp', null);
$data = $service->getDossiersByMail($email, $timestamp);
return new JsonResponse(['status' => 'success', 'data' => $data], Response::HTTP_OK);
}
/**
* @Route("/devis/{id}", name="get_reservation_devis", methods={"GET"})
*/
public function getReservationDevis(Request $request, KernixApiService $service, $id) {
$rowid = $id;
if (null === $rowid) {
return new JsonResponse(['status' => 'error', 'message' => sprintf('Identifiant invalide', $rowid)], Response::HTTP_BAD_REQUEST);
}
if (!preg_match('/^\d+$/', $rowid)) {
return new JsonResponse(['status' => 'error', 'message' => sprintf('Identifiant "%s" invalide', $rowid)], Response::HTTP_BAD_REQUEST);
}
$data = $service->getDossierDevis($rowid);
return $this->json($data);
}
/**
* @Route("/facture/{id}", name="get_reservation_facture", methods={"GET"})
*/
public function getReservationFacture(Request $request, KernixApiService $service, $id) {
$rowid = $id;
if (null === $rowid) {
return new JsonResponse(['status' => 'error', 'message' => sprintf('Identifiant invalide', $rowid)], Response::HTTP_BAD_REQUEST);
}
if (!preg_match('/^\d+$/', $rowid)) {
return new JsonResponse(['status' => 'error', 'message' => sprintf('Identifiant "%s" invalide', $rowid)], Response::HTTP_BAD_REQUEST);
}
$data = $service->getDossierFacture($rowid);
return $this->json($data);
}
/**
* @Route("/itineraire/{dossierId}", name="get_reservation_itineraire", methods={"GET"})
*/
public function getReservationItineraire(Request $request, KernixApiService $service, $dossierId) {
$rowid = $dossierId;
if (null === $rowid) {
return new JsonResponse(['status' => 'error', 'message' => sprintf('Identifiant dossier invalide', $rowid)], Response::HTTP_BAD_REQUEST);
}
if (!preg_match('/^\d+$/', $rowid)) {
return new JsonResponse(['status' => 'error', 'message' => sprintf('Identifiant dossier "%s" invalide', $rowid)], Response::HTTP_BAD_REQUEST);
}
$data = $service->getDossierDocumentItineraire($dossierId);
return $this->json($data);
}
/**
* @Route("/payment/{dossierId}", name="new_reservation_payment_kernix", methods={"GET","POST"})
*/
public function newPaiement(Request $request, ValidatorInterface $validator, KernixApiService $apiService, KernixService $service, EntityManagerInterface $em, TranslatorInterface $translator, $dossierId) {
$data = $request->request->all(); // fonctionne avec form-data
$toProcess = [];
$errorMessages = [];
// Paiements
if (isset($data['paiements']) && is_array($data['paiements']) && count($data['paiements']) > 0) {
foreach ($data['paiements'] as $payData) {
$pay = new KernixPaiementDTO();
$pay->emetteur = $payData['emetteur'] ?? '';
$pay->code_reduction = $payData['code_reduction'] ?? '';
if (isset($payData['mode_paiement'])) {
$pay->mode_paiement = $payData['mode_paiement'];
}
if (isset($payData['montant'])) {
$pay->montant = $payData['montant'];
}
// Validation
$errors = $validator->validate($pay);
if (count($errors) > 0) {
foreach ($errors as $error) {
$errorMessages[] = sprintf('%s: %s', $error->getPropertyPath(), $error->getMessage());
}
} else {
$toProcess[] = $payData;
}
}
if (count($errors) > 0) {
return new JsonResponse([
'status' => 'error',
'message' => $errorMessages,
], JsonResponse::HTTP_BAD_REQUEST);
}
$statut = $service->addPaiements($dossierId, $toProcess);
if (false !== $statut) {
return $this->json($statut);
}
else {
return new JsonResponse([
'status' => 'error',
'message' => ['Une erreur est survenue, veuillez contacter un admin'],
], JsonResponse::HTTP_BAD_REQUEST);
}
} else {
return new JsonResponse([
'status' => 'error',
'message' => ['Il manque les paiements'],
], JsonResponse::HTTP_BAD_REQUEST);
}
}
}