src/Controller/APIIctus/ApiLivraisonController.php line 210

Open in your IDE?
  1. <?php
  2. namespace App\Controller\APIIctus;
  3. use App\Entity\User;
  4. use App\Repository\UserRepository;
  5. use App\Repository\ParcoursRepository;
  6. use App\Repository\LivraisonRepository;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use App\Repository\IctusCommandeRepository;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use App\Repository\SocieteLivraisonRepository;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Routing\Annotation\Route;
  13. use App\Repository\IctusMobileAppareilRepository;
  14. use Symfony\Component\HttpFoundation\JsonResponse;
  15. use App\Services\NotificationSocieteLivraisonService;
  16. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  17. /**
  18.  * @Route("/api_ictus/livraison", name="api_ictus_livraison_")
  19.  */
  20. class ApiLivraisonController extends AbstractController
  21. {
  22.     private $em;
  23.     public function __construct(EntityManagerInterface $em)
  24.     {
  25.         $this->em $em;
  26.     }
  27.     
  28.     /**
  29.      * @Route("/{id}", name="livraison_par_livraire", methods={"GET"})
  30.      */
  31.     public function livraisonParLivraire(User $userLivraisonRepository $livraisonRepository): JsonResponse
  32.     {
  33.         // Vérification explicite que l'utilisateur existe
  34.         if (!$user || !$user->getId()) {
  35.             return new JsonResponse([
  36.                 'error' => true,
  37.                 'message' => 'Utilisateur non trouvé'
  38.             ], 404);
  39.         }
  40.         $livraisons $livraisonRepository->findBy(
  41.             ['livreur' => $user],
  42.             ['createdAt' => 'DESC']  // Optionnel : trier par date
  43.         );
  44.         $data = [];
  45.         foreach ($livraisons as $livraison) {
  46.             $data[] = [
  47.                 'id'          => $livraison->getId(),
  48.                 'tarif'       => $livraison->getTarif(),
  49.                 'code'        => $livraison->getCode(),
  50.                 'codeSecret'  => $livraison->getCodeSecret(),
  51.                 // Tu peux ajouter d'autres champs utiles :
  52.                 // 'statut' => $livraison->getStatut(),
  53.                 'date'   => $livraison->getCreatedAt()?->format('d-M-Y H:i'),
  54.             ];
  55.         }
  56.         return new JsonResponse([
  57.             'error' => false,
  58.             'message' => 'Livraisons récupérées avec succès',
  59.             'dataLivraison' => $data,
  60.             'count' => count($data)   // Utile pour le frontend
  61.         ]);
  62.     }
  63.     
  64.    /**
  65.      * @Route("/parcours/{id}", name="parcours", methods={"GET"})
  66.      */
  67.     public function parcours($idParcoursRepository $parcoursRepo): JsonResponse
  68.     {
  69.         if (!$id) {
  70.             return new JsonResponse([
  71.                 'error' => true,
  72.                 'message' => 'ID de livraison manquant'
  73.             ], 400);
  74.         }
  75.         $allParcours $parcoursRepo->allParcoursByLivraison($id);
  76.         if (empty($allParcours)) {
  77.             return new JsonResponse([
  78.                 'error' => false,
  79.                 'message' => 'Aucun parcours trouvé',
  80.                 'clients' => [],
  81.                 'count' => 0
  82.             ]);
  83.         }
  84.         $clientsData = [];
  85.         $tarifTotalGlobal 0;
  86.         foreach ($allParcours as $parcour) {
  87.             $commande  $parcour->getIctusCommande();
  88.             $pharmacie $commande->getPharmacie();
  89.             $client    $commande->getUser();
  90.             $adressePatient $parcour->getAdresse();
  91.             if (!$client) continue;
  92.             $clientId $client->getId();
  93.             // Initialisation du client s'il n'existe pas encore
  94.             if (!isset($clientsData[$clientId])) {
  95.                 $clientsData[$clientId] = [
  96.                     'client_id'      => $clientId,
  97.                     'client_nom'     => $client->getNomComplet(),
  98.                     'client_adresse' => $adressePatient->getLot().", ".$adressePatient->getQuartier()->getName().", ".$adressePatient->getQuartier()->getVille()->getName(),//$client->getFullAdresse(),
  99.                     'client_contact' => $client->getPhone(),
  100.                     'tarifTotal'     => 0,                   
  101.                     'parcours'       => []                    // Liste des parcours du client
  102.                 ];
  103.             }
  104.             $tarif $parcour->getLivraison()->getTarif() ?? 0;
  105.             $clientsData[$clientId]['tarifTotal'] += $tarif;
  106.             $tarifTotalGlobal += $tarif;
  107.             // Ajout du parcours pour ce client
  108.             $clientsData[$clientId]['parcours'][] = [
  109.                 'pharmacie_id'              => $pharmacie->getId(),
  110.                 'designation'               => $pharmacie->getDesignation(),
  111.                 'adresse'                   => $pharmacie->getFullAdresse(),
  112.                 'nun_commande'              => $commande->getConcatRefCmd(),
  113.                 'code_recuperation_pcie'    => $commande->getCode() . $commande->getCodeSecret(),
  114.                 'tarif_recuperation'        => $tarif,
  115.                 'code_recuperation_livreur' => $parcour->getLivraison()->getCode(),
  116.                 'etat'                      => $parcour->getEtat(),
  117.                 'commande_etat'             => $commande->isIsLivrer(),
  118.                 'parcours_id'               => $parcour->getId()
  119.             ];
  120.         }
  121.         // Conversion en tableau indexé (pour le frontend)
  122.         $clientsArray array_values($clientsData);
  123.         return new JsonResponse([
  124.             'error'        => false,
  125.             'message'      => 'Parcours récupérés avec succès',
  126.             'clients'      => $clientsArray,           // Données groupées par client
  127.             'tarifTotalGlobal' => $tarifTotalGlobal,   // Total général (optionnel)
  128.             'count'        => count($allParcours)
  129.         ]);
  130.     }
  131.     /**
  132.      * @Route("/parcours/verifcode/{id}", name="verification_code", methods={"POST"})
  133.      */
  134.     public function verifCodeParcour(Request $requestParcoursRepository $parcourRepo$id): Response
  135.     {
  136.         $content $request->getContent();
  137.         $message "Erreur du traitement";
  138.         if (!empty($content)) {
  139.             $decoded json_decode($contenttrue);
  140.             if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
  141.                 $data $decoded;
  142.             }
  143.         }
  144.         
  145.         if (empty($data)) {
  146.             $data $request->query->all();
  147.         }
  148.         $code_secret $data['code_secret'] ?? $data['code_secret'] ?? null;
  149.         if (empty($code_secret) || !is_numeric($code_secret)) {
  150.             return new JsonResponse(
  151.                 ['error' => 'Paramètre code secret manquant ou invalide'],
  152.                 Response::HTTP_BAD_REQUEST
  153.             );
  154.         }
  155.         $parcour $parcourRepo->find($id);
  156.         if (!$parcour) {
  157.             return new JsonResponse(
  158.                 ['error' => 'Parcours non trouvé'],
  159.                 Response::HTTP_NOT_FOUND
  160.             );
  161.         }
  162.         
  163.         if ($parcour->getLivraison()->getCodeSecret() == $code_secret) {
  164.             $parcour->setEtat(1);
  165.             $commande $parcour->getIctusCommande();
  166.             $commande->setIsLivrer(1)->setIsRecuperer(1);
  167.             $this->em->persist($commande);
  168.             $this->em->persist($parcour);
  169.             $this->em->flush();
  170.             $message ="Colis marqué comme livré";
  171.         } else {
  172.             $message ="Code sécret erroné!";
  173.             return new JsonResponse([
  174.                 'error' => true,
  175.                 'message' => $message
  176.             ]);
  177.         }
  178.         return new JsonResponse([
  179.             'error' => false,
  180.             'message' => $message
  181.         ]);
  182.     }
  183.     /**
  184.      * @Route("/livreur-position/{id}", name="get_postion_livreur", methods={"POST"})
  185.      */
  186.     public function getPositionLivreur(User $userRequest $request)
  187.     {
  188.         $data = [];
  189.         $content $request->getContent();
  190.         if (!empty($content)) {
  191.             $decoded json_decode($contenttrue);
  192.             if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
  193.                 $data $decoded;
  194.             }
  195.         }
  196.         if (empty($data)) {
  197.             $data $request->query->all();
  198.         }
  199.         $longitude $data['longitude'] ?? null;
  200.         $latitude  $data['latitude'] ?? null;
  201.         if (!is_numeric($longitude) || !is_numeric($latitude)) {
  202.             return new JsonResponse(
  203.                 ['error' => 'Paramètre latitude ou longitude manquant ou invalide'],
  204.                 Response::HTTP_BAD_REQUEST
  205.             );
  206.         }
  207.         $user->setLogitude((float) $longitude)->setLatitude((float) $latitude);
  208.         $this->em->flush();
  209.         return new JsonResponse([
  210.             'error' => false,
  211.             'message' => 'Position mise à jour avec succès',
  212.         ]);
  213.     }
  214.     /**
  215.      * @Route("/livreur-proposition-refuser/{id}", name="proposition_refuser", methods={"POST"})
  216.      */
  217.     public function refuserPropositionLivraison($id,ParcoursRepository $parcourRepo,UserRepository $userRepoIctusCommandeRepository $ictusCommandeRepoIctusMobileAppareilRepository $mobileAppareilRepoNotificationSocieteLivraisonService $notificationSLService)
  218.     {
  219.         if (is_null($id)) {
  220.              return new JsonResponse(
  221.                 ['error' => 'Paramètre id commande manquant ou invalide'],
  222.                 Response::HTTP_BAD_REQUEST
  223.             );
  224.         }
  225.         $parcour $parcourRepo->find($id);
  226.         
  227.         $ictusCommande $parcour->getIctusCommande();//$ictusCommandeRepo->findById($id);
  228.         $ancienlivreur $parcour->getLivraison()->getLivreur();
  229.         $ancienlivreur->setIsDisponible(null);
  230.         $this->em->flush();
  231.         
  232.             $sl null;
  233.             $parcours $ictusCommande->getParcours();
  234.             if ($parcours != null) {
  235.                 $sl $parcours->getLivraison()->getSocieteLivraison();
  236.             }
  237.             //dd($sl2->getUsers()[0]);
  238.             //$sl = $ictusCommande->getSocieteLivraison();
  239.             //$pt = $ictusCommande->getUser();
  240.             $parmacie $ictusCommande->getPharmacie();
  241.             if ($sl) {
  242.                 $data = [
  243.                     'type'       => 'delivery_request',
  244.                     'status'     => 'validated_by_pharmacy',
  245.                     'click_action' => 'FLUTTER_NOTIFICATION_CLICK'// utile si tu as une app Flutter
  246.                 ];
  247.                 $user_sl  $sl->getUsers()[0];
  248.                 $mobileAppareils $mobileAppareilRepo->findAllToArray($user_sl);
  249.                 $array_cfm_token array_unique((array_column($mobileAppareils"cfm_tokem")));
  250.                 if ($sl->isIsAutomatique()) {
  251.                     //ici
  252.                     //Attribution automatique du livreur
  253.                     $livreur $userRepo->findNearestLivreur($parmacie->getLatitude(), $parmacie->getLogitude(), $sl$ancienlivreur->getId());
  254.                     $livraison $parcours->getLivraison();
  255.                     $livraison->setLivreur($livreur);
  256.                     $this->em->persist($livraison);
  257.                     if ($livreur) {
  258.                         //livreur set non disponible
  259.                         $livreur->setIsDisponible(null);
  260.                         $this->em->flush();
  261.                         //envoie notification au livreur attribué
  262.                         foreach ($livreur->getIctusMobileAppareils() as $appareil) {
  263.                             $notificationSLService->sendNotification(
  264.                                 $appareil->getCfmTokem(),
  265.                                 'Nouvelle mission de livraison',
  266.                                 'Demande validée par la pharmacie, vous avez été attribué pour cette livraison.',
  267.                                 $data
  268.                             );
  269.                         }
  270.                         //Envoie notification au responsable de la société de livraison
  271.                         foreach ($array_cfm_token as $token) {
  272.                             $notificationSLService->sendNotification(
  273.                                 $token,
  274.                                 'Nouvelle demande de livraison',
  275.                                 'Demande validée par la pharmacie, livreur attribué automatiquement à un livreur proche de la pharmacie',
  276.                                 $data
  277.                             );
  278.                         }
  279.                     } else {
  280.                         if (!empty($array_cfm_token)) {
  281.                             foreach ($array_cfm_token as $token) {
  282.                                 $notificationSLService->sendNotification(
  283.                                     $token,
  284.                                     'Nouvelle demande de livraison',
  285.                                     'Demande validée par la pharmacie, veuillez attribuer un livreur.',
  286.                                     $data
  287.                                 );
  288.                             }
  289.                         }
  290.                     }
  291.                     //fin
  292.                 } else {
  293.                     if (!empty($array_cfm_token)) {
  294.                         foreach ($array_cfm_token as $token) {
  295.                             $notificationSLService->sendNotification(
  296.                                 $token,
  297.                                 'Nouvelle demande de livraison',
  298.                                 'Demande validée par la pharmacie, veuillez attribuer un livreur.',
  299.                                 $data
  300.                             );
  301.                         }
  302.                     }
  303.                 }
  304.             }
  305.             return new JsonResponse([
  306.             'error' => false,
  307.             'message' => 'Refus livraison avec succès',
  308.         ]);
  309.     }
  310. }