src/Controller/APIIctus/APIIctPanierController.php line 689

Open in your IDE?
  1. <?php
  2. namespace App\Controller\APIIctus;
  3. use DateTime;
  4. use App\Entity\User;
  5. use App\Services\Util;
  6. use App\Entity\Ordonnance;
  7. use App\Entity\IctusCommande;
  8. use App\Entity\IctusPharmacie;
  9. use App\Entity\Stockpharmacie;
  10. use App\Services\MailerServices;
  11. use App\Entity\IctusCommandeLine;
  12. use App\Services\IctocoinService;
  13. use App\Entity\IctusPanierPatient;
  14. use App\Entity\IctusPanierSpecial;
  15. use App\Repository\UserRepository;
  16. use App\Services\api\PanierService;
  17. use App\Services\NotificationService;
  18. use App\Services\FacturePatientService;
  19. use App\Repository\OrdonnanceRepository;
  20. use App\Services\VanillaPaiementSercice;
  21. use Doctrine\ORM\EntityManagerInterface;
  22. use App\Services\CodeRecuperationService;
  23. use App\Repository\TypepaiementRepository;
  24. use App\Repository\IctusCommandeRepository;
  25. use App\Repository\IctusPharmacieRepository;
  26. use App\Repository\StockpharmacieRepository;
  27. use Symfony\Component\HttpFoundation\Request;
  28. use Symfony\Component\Mailer\MailerInterface;
  29. use Symfony\Component\HttpFoundation\Response;
  30. use App\Repository\IctusEtatPaiementRepository;
  31. use App\Repository\IctusTypePaiementRepository;
  32. use Symfony\Component\Routing\Annotation\Route;
  33. use App\Repository\IctusPanierPatientRepository;
  34. use App\Repository\IctusTypeLivraisonRepository;
  35. use App\Repository\IctusMobileAppareilRepository;
  36. use App\Services\VanillaPayInternationnalService;
  37. use Symfony\Component\HttpFoundation\JsonResponse;
  38. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  39. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  40. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  41. #[Route('/api/ictus-shop/panier'name'app_api_ictus_shop_panier_')]
  42. class APIIctPanierController extends AbstractController
  43. {
  44.     private $em;
  45.     private $mailerint;
  46.     private $mailTechnicien "zoanja.rabehaja@sopharmad.mg";
  47.     private $util;
  48.     private $montantTotalPaiementEnLigne 0;
  49.     private $listeCommandePaiementEnLigne = array();
  50.     private $notifUrl;
  51.     private $redirectUrl;
  52.     public function __construct(EntityManagerInterface $emMailerInterface $mailerintUtil $utilUrlGeneratorInterface $urlGenerator)
  53.     {
  54.         $this->em $em;
  55.         $this->mailerint  $mailerint;
  56.         $this->util       $util;
  57.         $this->notifUrl   $_ENV["VANILLA_INT_URL_NOTIF"];
  58.         $this->redirectUrl $_ENV["VANILLA_INT_URL_REDIRECT"];
  59.     }
  60.     #[Route('/non-authentifier'name'non_auth'methods: ['GET'])]
  61.     public function panierNonAuth(Request $requestStockpharmacieRepository $stockpharmacieRepositoryPanierService $panierService): Response
  62.     {
  63.         $produitPcie $request->query->all('produitPcie');
  64.         $produitPcie array_map('intval'$produitPcie);
  65.         $panierCart  $panierService->getFull($stockpharmacieRepositorynull,$produitPcie);
  66.         $responseData   = [
  67.             'error' => true,
  68.         ];
  69.         if (count($panierService->groupByIdPcie($panierCart)) > 0) {
  70.             $responseData $panierService->groupByIdPcie($panierCart);
  71.             return $this->json($responseData);
  72.         }
  73.         return $this->json($responseData500, [], []);
  74.     }
  75.     /******************Ajouter panier dans MySQL************** */
  76.     //Enregistrement panier direct dans DB MysQl par l'user connectee dans meilleur vente
  77.     #[Route('/ajout-auth-mysql'name'app_panier_add_auth'methods: ['POST'])]
  78.     public function ajoutPanierAuthBestSeller(Request $requestIctusPanierPatientRepository $panierRepoUserRepository $userRepositoryStockpharmacieRepository $stockPcieRepo): Response
  79.     {
  80.         // Récupérer les données du corps de la requête
  81.         $data json_decode($request->getContent(), true);
  82.         // Vérifier si userId est bien envoyé
  83.         if (!isset($data['userId'])) {
  84.             return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
  85.         }
  86.         // Vérifier si les produits sont bien envoyés
  87.         if (!isset($data['produit'])) {
  88.             return $this->json(['error' => 'Aucun produit fourni'], JsonResponse::HTTP_BAD_REQUEST);
  89.         }
  90.         // Récupérer l'utilisateur depuis l'ID envoyé
  91.         $user $userRepository->find($data['userId']);
  92.         if (!$user) {
  93.             return $this->json(['error' => 'Utilisateur non trouvé'], JsonResponse::HTTP_NOT_FOUND);
  94.         }
  95.         if (!isset($data['produit'], $data['quantite'])) {
  96.             return $this->json(['error' => 'Informations du produit manquantes'], JsonResponse::HTTP_BAD_REQUEST);
  97.         }
  98.         // Récupérer le produit en base de données
  99.         $produit $stockPcieRepo->find($data['produit']);
  100.         if (!$produit) {
  101.             return $this->json(['error' => 'Produit non trouvé'], JsonResponse::HTTP_NOT_FOUND);
  102.         }
  103.         // produit exit panier ou non 
  104.         $existPanier   $panierRepo->findOneBy(['user' => $user'produit_stock_pcie' => $produit]);
  105.         $quantite      $data['quantite'];
  106.         $tva           $produit->getTva();
  107.         if (!is_null($existPanier)) {
  108.             $quantite $existPanier->getQuantite() + $data['quantite'];
  109.         }
  110.         $panier        = (!is_null($existPanier)) ? $existPanier : new IctusPanierPatient();
  111.         // Calculer le prix total
  112.         $prix_unitaire = (!is_null($tva)) ? ($produit->getPrixunitforme() + ($produit->getPrixunitforme() * $tva) / 100) : $produit->getPrixunitforme();
  113.         // Créer une nouvelle entrée dans le panier
  114.         $panier->setProduitStockPcie($produit)
  115.             ->setUser($user)
  116.             ->setQuantite($quantite)
  117.             ->setPrixUnitaire($prix_unitaire)
  118.             ->setTotal($quantite $prix_unitaire);
  119.         // Persister dans la base de données
  120.         $this->em->persist($panier);
  121.         $this->em->flush();
  122.         return $this->json(['message' => 'Panier enregistré avec succès'], JsonResponse::HTTP_CREATED);
  123.     }
  124.     //Enregistrement panier SQLite dans DB MysQl apres login
  125.     #[Route('/ajout-sqlit-mysql'name'app_panier_add_sqlite_to_mysql_apre_login'methods: ['POST'])]
  126.     public function enregistrementPanierDB(
  127.         Request $request,
  128.         StockpharmacieRepository $stockPcieRepo,
  129.         UserRepository $userRepo,
  130.         IctusPanierPatientRepository $panierRepo,
  131.         EntityManagerInterface $em
  132.     ): JsonResponse {
  133.         // Récupérer les données du corps de la requête
  134.         $data json_decode($request->getContent(), true);
  135.         // Vérifier si userId est bien envoyé
  136.         if (!isset($data['userId'])) {
  137.             return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
  138.         }
  139.         // Vérifier si les produits sont bien envoyés
  140.         if (!isset($data['produits']) || !is_array($data['produits'])) {
  141.             return $this->json(['error' => 'Aucun produit fourni'], JsonResponse::HTTP_BAD_REQUEST);
  142.         }
  143.         $user $userRepo->findOneById($data['userId']);
  144.         if (!$user) {
  145.             return $this->json(['error' => 'Utilisateur: '.$data['userId'].' non trouvé'], JsonResponse::HTTP_NOT_FOUND);
  146.         }
  147.         $paniers $data['produits'];
  148.         $prixTotal 0;
  149.         foreach ($paniers as $panierSession) {
  150.             // Vérifier les informations du produit
  151.             if (!isset($panierSession['idProduit'], $panierSession['quantite'])) {
  152.                 return $this->json(['error' => 'Informations du produit manquantes'], JsonResponse::HTTP_BAD_REQUEST);
  153.             }
  154.             // Récupérer le produit en base de données
  155.             $produit $stockPcieRepo->find($panierSession['idProduit']);
  156.             if (!$produit) {
  157.                 return $this->json(['error' => 'Produit non trouvé'], JsonResponse::HTTP_NOT_FOUND);
  158.             }
  159.             $existPanier   $panierRepo->findOneBy(['user' => $user'produit_stock_pcie' => $produit]);
  160.             $quantite      $panierSession['quantite'];
  161.             $tva           $produit->getTva();
  162.             if (!is_null($existPanier)) {
  163.                 $quantite  $existPanier->getQuantite() + $panierSession['quantite'];
  164.             }
  165.             $panier        = (!is_null($existPanier)) ? $existPanier : new IctusPanierPatient();
  166.             $prix_unitaire = (!is_null($tva)) ? ($produit->getPrixunitforme() + ($produit->getPrixunitforme() * $tva) / 100) : $produit->getPrixunitforme();
  167.             $prixTotal += $quantite $prix_unitaire;
  168.             // Créer une nouvelle entrée dans le panier
  169.             $panier->setProduitStockPcie($produit)
  170.                 ->setUser($user)
  171.                 ->setQuantite($quantite)
  172.                 ->setPrixUnitaire($prix_unitaire)
  173.                 ->setTotal($quantite $prix_unitaire);
  174.             // Essayer de persister chaque entrée
  175.             try {
  176.                 $em->persist($panier);
  177.             } catch (\Exception $e) {
  178.                 // Logger l'erreur avec plus de détails
  179.                 return $this->json(['erreur' => 'Erreur lors de l\'ajout au panier: ' $e->getMessage()], JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
  180.             }
  181.         }
  182.         // Enregistrer tous les paniers en une seule transaction
  183.         try {
  184.             $em->flush();
  185.         } catch (\Exception $e) {
  186.             return $this->json(['erreur' => 'Erreur lors de l\'enregistrement des paniers: ' $e->getMessage()], JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
  187.         }
  188.         return $this->json(['message' => 'Panier ajouté avec succès''total' => $prixTotal], JsonResponse::HTTP_CREATED);
  189.     }
  190.     #[Route('/count-mysql'name'app_panier_count_mysql'methods: ['POST'])]
  191.     public function getCountProduitParUser(Request $requestUserRepository $userRepoIctusPanierPatientRepository $panierRepo)
  192.     {
  193.         $data json_decode($request->getContent(), true);
  194.         if (!isset($data['userId'])) {
  195.             return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
  196.         }
  197.         $user $userRepo->find($data['userId']);
  198.         if (!$user) {
  199.             return $this->json(['error' => 'Utilisateur non trouvé'], JsonResponse::HTTP_NOT_FOUND);
  200.         }
  201.         $countPanier $panierRepo->findCountpanierByUser($user);
  202.         return $this->json(["countPanier" => $countPanier]);
  203.     }
  204.     //Liste produit dans panier MySQL pour l'utilisateur connecte
  205.     #[Route('/mysql-user-connecte'name'mysql_user_connecte'methods: ['POST'])]
  206.     public function panierMySQLUserConnectee(
  207.         Request $request,
  208.         StockpharmacieRepository $stockpharmacieRepository,
  209.         PanierService $panierService,
  210.         IctusPanierPatientRepository $panierRepo,
  211.         UserRepository $userRepo
  212.     ): Response {
  213.         $data json_decode($request->getContent(), true);
  214.         if (!isset($data['userId'])) {
  215.             return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
  216.         }
  217.         $user             $userRepo->find($data['userId']);
  218.         $produitPcie      $panierRepo->findAllByUser($user);
  219.         $coupleIdQuantite = [];
  220.         if (count($produitPcie) > 0) {
  221.             foreach ($produitPcie as $panier) {
  222.                 $idStockPcie                    $panier->getProduitStockPcie()->getId();
  223.                 $quantite                       $panier->getQuantite();
  224.                 $coupleIdQuantite[$idStockPcie] = $quantite;
  225.             }
  226.         }
  227.         $panierCart   $panierService->getFull($stockpharmacieRepository$user$coupleIdQuantite);
  228.         $responseData = [
  229.             'error' => true,
  230.         ];
  231.         if (count($panierService->groupByIdPcie($panierCart)) > 0) {
  232.             $responseData $panierService->groupByIdPcie($panierCart);
  233.             return $this->json($responseDataJsonResponse::HTTP_OK);
  234.         }
  235.         return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
  236.     }
  237.     #[Route('/mysql-user-connecte-update-quantite'name'mysql_user_connecte_update_quantite'methods: ['POST'])]
  238.     public function updateQuantiteProduitPanier(
  239.         Request $request,
  240.         StockpharmacieRepository $stockpharmacieRepository,
  241.         IctusPanierPatientRepository $panierRepo,
  242.         UserRepository $userRepo
  243.     ): Response {
  244.         $data      json_decode($request->getContent(), true);
  245.         $panier    null;
  246.         $stockpcie null;
  247.         if (!isset($data['userId'])) {
  248.             return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
  249.         }
  250.         $user $userRepo->find($data['userId']);
  251.         if (is_null($user)) {
  252.             return $this->json(['error' => 'User non trouve'], JsonResponse::HTTP_NOT_FOUND);
  253.         }
  254.         if (!isset($data['produit'])) {
  255.             return $this->json(['error' => 'ID Produit manquant'], JsonResponse::HTTP_BAD_REQUEST);
  256.         }
  257.         $stockpcie $stockpharmacieRepository->findOneById($data['produit']);
  258.         if (is_null($stockpcie)) {
  259.             return $this->json(['error' => 'Produit non trouve'], JsonResponse::HTTP_NOT_FOUND);
  260.         }
  261.         $panier $panierRepo->findOneBy(['produit_stock_pcie' => $stockpcie'user' => $user]);
  262.         /******* */
  263.         $tva           $stockpcie->getTva();
  264.         $prix_unitaire = (!is_null($tva)) ? ($stockpcie->getPrixunitforme() + ($stockpcie->getPrixunitforme() * $tva) / 100) : $stockpcie->getPrixunitforme();
  265.         $pixTotal      =  $prix_unitaire $data['quantite'];
  266.         /************ */
  267.         if (!is_null($panier)) {
  268.             $panier->setQuantite($data['quantite'])
  269.                 ->setTotal($pixTotal)
  270.                 ->setPrixUnitaire($prix_unitaire);
  271.             $this->em->flush();
  272.             $newData = [
  273.                 'userId'        => $data['userId'],
  274.                 'produit'       => $data['produit'],
  275.                 'quantite'      => $data['quantite'],
  276.                 'prix_unitaire' => $prix_unitaire,
  277.                 'total'         => $pixTotal
  278.             ];
  279.             return $this->json($newDataJsonResponse::HTTP_OK);
  280.         }
  281.         return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
  282.     }
  283.     #[Route('/mysql-user-connecte-delete'name'mysql_user_connecte_delete'methods: ['POST'])]
  284.     public function deleteProduitPanierMySQL(
  285.         Request $request,
  286.         StockpharmacieRepository $stockpharmacieRepository,
  287.         IctusPanierPatientRepository $panierRepo,
  288.         UserRepository $userRepo
  289.     ): Response {
  290.         $data      json_decode($request->getContent(), true);
  291.         $panier    null;
  292.         $stockpcie null;
  293.         if (!isset($data['userId'])) {
  294.             return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
  295.         }
  296.         $user $userRepo->find($data['userId']);
  297.         if (is_null($user)) {
  298.             return $this->json(['error' => 'User non trouve'], JsonResponse::HTTP_NOT_FOUND);
  299.         }
  300.         if (!isset($data['produit'])) {
  301.             return $this->json(['error' => 'ID Produit manquant'], JsonResponse::HTTP_BAD_REQUEST);
  302.         }
  303.         $stockpcie $stockpharmacieRepository->findOneById($data['produit']);
  304.         if (is_null($stockpcie)) {
  305.             return $this->json(['error' => 'Produit non trouve'], JsonResponse::HTTP_NOT_FOUND);
  306.         }
  307.         $panier $panierRepo->findOneBy(['produit_stock_pcie' => $stockpcie'user' => $user]);
  308.         /************ */
  309.         if (!is_null($panier)) {
  310.             $this->em->remove($panier);
  311.             $this->em->flush();
  312.             return $this->json("DATA DELETED OK"JsonResponse::HTTP_OK);
  313.         }
  314.         return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
  315.     }
  316.     //Ajouter ordonnace dans un produit panier
  317.     #[Route('/create/ordonnance'name'create_ordonnance'methods: ['POST'])]
  318.     public function createOrdonnancePanier(
  319.         Request $request,
  320.         OrdonnanceRepository $ordonaceRepo,
  321.         PanierService $panierService,
  322.         StockpharmacieRepository $stockpharmacieRepository,
  323.         IctusPanierPatientRepository $panierRepo,
  324.         UserRepository $userRepo
  325.     ): Response {
  326.         //$data = json_decode($request->getContent(), true);
  327.         $panierData $panierService->handleDataPanier($userRepo$stockpharmacieRepository$panierRepo$request);
  328.         if (isset($panierData['error'])) {
  329.             return $this->json($panierDataJsonResponse::HTTP_BAD_REQUEST);
  330.         }
  331.         // Si tout est correct, vous pouvez procéder à la création de l'ordonnance
  332.         $user $panierData['user'];
  333.         if ($user instanceof User) {
  334.             $panier $panierData['panier'];
  335.             if (!is_null($panier) && $panier instanceof IctusPanierPatient) {
  336.                 $panier->setOrdonnance($ordonaceRepo->createOrdonnance($panierData['file'], $panierData['titre'], $panierData['user']));
  337.                 $this->em->flush();
  338.             } else {
  339.                 $ordonaceRepo->createOrdonnance($panierData['file'], $panierData['titre'], $panierData['user']);
  340.             }
  341.             return $this->json(['CREATED' => "DATA CREATE OK"], JsonResponse::HTTP_CREATED);
  342.         }
  343.         return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
  344.     }
  345.     //allOrdonneByIdUser()
  346.     #[Route('/ordonnance/{id}'name'get_ordonnance'methods: ['GET'])]
  347.     public function recupOrdonnanceByUser(User $userOrdonnanceRepository $ordonaceRepo): Response
  348.     {
  349.         $dataOrdonnances = [];
  350.         if (!is_null($user)) {
  351.             $ordonnances $ordonaceRepo->findAllOrdonnanceByIdUser($user->getId());
  352.             if (count($ordonnances)) {
  353.                 foreach ($ordonnances as $ordo) {
  354.                     $dataOrd = [
  355.                         'id'     => $ordo->getId(),
  356.                         'userId' => $ordo->getPropriertaire()->getId(),
  357.                         'titre'  => $ordo->getTitre(),
  358.                         'file'   => $ordo->getFichier()
  359.                     ];
  360.                     array_push($dataOrdonnances$dataOrd);
  361.                 }
  362.                 return $this->json($dataOrdonnancesJsonResponse::HTTP_OK);
  363.             }
  364.         }
  365.         return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
  366.     }
  367.     //Update PanierOrdonnace
  368.     #[Route('/update/ordonnance'name'update_ordonnance'methods: ['POST'])]
  369.     public function updateOrdonnancePanier(
  370.         Request $request,
  371.         OrdonnanceRepository $ordonaceRepo,
  372.         StockpharmacieRepository $stockpharmacieRepository,
  373.         IctusPanierPatientRepository $panierRepo,
  374.         UserRepository $userRepo
  375.     ): Response {
  376.         $data json_decode($request->getContent(), true);
  377.         if (!isset($data['produitId'])) {
  378.             return $this->json(['error' => 'Produit manquant'], JsonResponse::HTTP_BAD_REQUEST);
  379.         }
  380.         $stockpcie $stockpharmacieRepository->findOneById($data['produitId']);
  381.         if (!isset($data['userId'])) {
  382.             return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
  383.         }
  384.         $user $userRepo->find($data['userId']);
  385.         $panier $panierRepo->findOneBy(['produit_stock_pcie' => $stockpcie'user' => $user]);
  386.         if (!isset($data['ordonnanceId'])) {
  387.             return $this->json(['error' => 'Id ordonnance manquant'], JsonResponse::HTTP_BAD_REQUEST);
  388.         }
  389.         $ordonnance $ordonaceRepo->findOneById($data['ordonnanceId']);
  390.         if ($user instanceof User && $ordonnance instanceof Ordonnance && $panier instanceof IctusPanierPatient) {
  391.             $panier->setOrdonnance($ordonnance);
  392.             $this->em->flush();
  393.             return $this->json(['UPDATED' => "DATA UPDATED OK"], JsonResponse::HTTP_OK);
  394.         }
  395.         return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
  396.     }
  397.     /*  url = {base_url}/api/ictus-shop/panier/panier/sendcommande/{userId}/{typeLivraisonId}/{typePaiementId}
  398.         method : GET
  399.      */
  400.     #[Route('/sendcommande/{userId}/{typeLivraisonId}/{typePaiementId}'name'panier_sendcommande'methods: ['GET'])]
  401.     public function panierSendcommande(Request $requestFacturePatientService $facturePatientServiceIctusMobileAppareilRepository $mobileAppareilRepoNotificationService $notificationServiceMailerServices $mailIctocoinService $ictocoinServiceVanillaPayInternationnalService $vanillaPayInternationnalServiceUserRepository $userRepoIctusPanierPatientRepository $ictusPanierPatientRepoIctusTypeLivraisonRepository $ictusTypeLivraisonRepoIctusTypePaiementRepository $ictusTypePaiementRepoIctusPharmacieRepository $ictusPharmacieRepoIctusEtatPaiementRepository $etatPaiementRepoIctusCommandeRepository $ictusCommandeRepoCodeRecuperationService $codeRecuperationService$userId$typeLivraisonId$typePaiementId)
  402.     {
  403.         if ($request->isMethod('GET')) {
  404.             $urlPaiement null;
  405.             if ($typeLivraisonId != null && $typePaiementId != null && $userId != null) {
  406.                 $user         $userRepo->find($userId);
  407.                 $token = (new \DateTime())->format('YmdiHs') . $user->getId();
  408.                 $typeLivraison $ictusTypeLivraisonRepo->find($typeLivraisonId);
  409.                 $typePaiement  $ictusTypePaiementRepo->find($typePaiementId);
  410.                 $paniers    $ictusPanierPatientRepo->findBy(['user' => $user]);
  411.                 if (count($paniers) > 0) {
  412.                     $nbCommandes $this->sendCommande($paniers$typePaiement$typeLivraison$user$ictusPanierPatientRepo$ictusPharmacieRepo$etatPaiementRepo$token$ictusCommandeRepo$codeRecuperationService$ictusTypePaiementRepo$facturePatientService$ictocoinService$mail$notificationService$mobileAppareilRepo);
  413.                     $ictusPanierPatientRepo->removeProduit($user->getId());
  414.                     if ($nbCommandes 0) {
  415.                         /* Paiement si necessaire */
  416.                         if (count($this->listeCommandePaiementEnLigne) > and $this->montantTotalPaiementEnLigne 0) {
  417.                             $liste json_encode($this->listeCommandePaiementEnLigne);
  418.                             $reference = (new DateTime())->format('YmdHis') . $user->getId();
  419.                             if ($typePaiement->getId() == 4) {
  420.                                 $vanilla   = new VanillaPaiementSercice($this->util);
  421.                                 $nomUser   $user->getNomComplet();
  422.                                 $adresseip $this->getUserIpAddr();
  423.                                 $urlPaiement $vanilla->payer($liste$this->montantWithFrai($this->montantTotalPaiementEnLigne), $nomUser$reference$adresseip);
  424.                                 if ($urlPaiement != null) {
  425.                                     $urlPaiement $urlPaiement->getTargetUrl();
  426.                                 }
  427.                             } else if ($typePaiement->getId() == 5) {
  428.                                 $urlPaiement $vanillaPayInternationnalService->payer($liste$this->montantTotalPaiementEnLigne$reference$this->notifUrl$this->redirectUrl);
  429.                                 if ($urlPaiement != null) {
  430.                                     $urlPaiement $urlPaiement->getTargetUrl();
  431.                                 }
  432.                             }
  433.                         }
  434.                         return $this->json(['success' => 'Success''message' => 'Commandes envoyées avec succès''nbCommandes' => $nbCommandes'urlPaiement' => $urlPaiement], JsonResponse::HTTP_OK);
  435.                     }
  436.                     return $this->json(['error' => 'Error''message' => 'Aucun commande envoyée''nbCommandes' => $nbCommandes'urlPaiement' => $urlPaiement], JsonResponse::HTTP_OK);
  437.                 }
  438.                 return $this->json(['error' => 'Error''message' => 'Panier vide''nbCommandes' => 0'urlPaiement' => $urlPaiement], JsonResponse::HTTP_OK);
  439.             } else {
  440.                 return $this->json(['error' => 'Error''message' => 'Parametre manquant''nbCommandes' => 0'urlPaiement' => $urlPaiement], JsonResponse::HTTP_BAD_REQUEST);
  441.             }
  442.         }
  443.     }
  444.     private function sendCommande(
  445.         $paniers,
  446.         $typePaiement,
  447.         $typeLivraison,
  448.         $user,
  449.         $ictusPanierPatientRepo,
  450.         $ictusPharmacieRepo,
  451.         $etatPaiementRepo,
  452.         $token,
  453.         $ictusCommandeRepo,
  454.         $codeRecuperationService,
  455.         $ictusTypePaiementRepo,
  456.         $facturePatientService,
  457.         $ictocoinService,
  458.         $mail,
  459.         $notificationService,
  460.         $mobileAppareilRepo
  461.     ) {
  462.         $etatPaiementDefault $etatPaiementRepo->findOneById(1);
  463.         $pharmacies $ictusPanierPatientRepo->getPcieDistinctByPatientAndTypePaiement($user$typePaiement);
  464.         $nbCommande 0;
  465.         foreach ($pharmacies as $pharmacie) {
  466.             $paiement null;
  467.             if ($pharmacie["idTypePaiement"] != null) {
  468.                 $paiement $typePaiement;
  469.             } else {
  470.                 $paiement $ictusTypePaiementRepo->findOneById(1);
  471.             }
  472.             $maxReference $ictusCommandeRepo->findMaxReference($pharmacie["idpharmacie"])[0]["maxReference"];
  473.             if ($maxReference == null) {
  474.                 $maxReference 0;
  475.             }
  476.             $maxReference = (int)$maxReference 1;
  477.             $createdAt = new DateTime();
  478.             $createdAt->modify('+2 hours');
  479.             $commande  = new IctusCommande();
  480.             $codeComplet $codeRecuperationService->generateCommande();
  481.             $commande->setPharmacie($ictusPharmacieRepo->findOneById(intval($pharmacie["idpharmacie"])))
  482.                 ->setTypeLivraison($typeLivraison)
  483.                 ->setTypePaiement($paiement)
  484.                 ->setUser($user)
  485.                 ->setToken($token)
  486.                 ->setReference($maxReference)
  487.                 ->setEtatpaiement($etatPaiementDefault)
  488.                 ->setCreatedAt($createdAt)
  489.                 ->setIsRecuperer(false)
  490.                 ->setIsValide($pharmacie["isValideAutomatique"])
  491.                 ->setIsValide($pharmacie["isValideAutomatique"])
  492.                 ->setCode($codeComplet['code'])
  493.                 ->setCodeSecret($codeComplet['secret']);
  494.             $this->em->persist($commande);
  495.             $montantTotal 0;
  496.             foreach ($paniers as $panier) {
  497.                 if ($pharmacie["idpharmacie"] == $panier->getProduitStockPcie()->getIctuspharmacie()->getId()) {
  498.                     $commandeLine = new IctusCommandeLine();
  499.                     $commandeLine->setQuantite($panier->getQuantite())
  500.                         ->setDesignation($panier->getProduitStockPcie()->getNomproduit())
  501.                         ->setCip7($panier->getProduitStockPcie()->getCip7())
  502.                         ->setCip13($panier->getProduitStockPcie()->getCip13())
  503.                         ->setPrixunitaire($panier->getPrixUnitaire() ?? 0)
  504.                         ->setRemise($panier->getProduitStockPcie()->getRemise())
  505.                         ->setOrdonnance($panier->getOrdonnance())
  506.                         ->setCommande($commande)
  507.                         ->setIsValide($pharmacie["isValideAutomatique"]);
  508.                     $this->em->persist($commandeLine);
  509.                     $montantTotal += $panier->getPrixUnitaire() * $panier->getQuantite();
  510.                 }
  511.             }
  512.             $this->em->flush();
  513.             $nbCommande++;
  514.             //Creation facture et ictocoin au cas ou
  515.             if ($pharmacie["isValideAutomatique"] != null) {
  516.                 $this->montantTotalPaiementEnLigne += $montantTotal;
  517.                 array_push($this->listeCommandePaiementEnLigne"CMD-" $commande->getId());
  518.                 $facturePatientService->editPatient($commande);
  519.                 $raison 'Frais de gestion sur la commande du ' date("d M Y") . ', Référence :/cmd {{' $commande->getId() . '}}';
  520.                 $montantDebit $ictocoinService->montantIctocoin($pharmacie["idpharmacie"], $montantTotal);
  521.                 $debitage $ictocoinService->debiter($pharmacie["idpharmacie"], $montantDebit$raison);
  522.                 if ($debitage != true) {
  523.                     $templateMail 'emails/erreurIctocoin.html.twig';
  524.                     $paramsMail = [
  525.                         'type'    => "Débit",
  526.                         'erreur' => "<p>Commande numéro : " $commande->getId() . "</p><p>Pharmacie id : " $pharmacie["idpharmacie"] . "</p><p>Montant : " $montantDebit "<sup style='margin-left:5px;'>ICTO</sup></p><p>Raison : " $raison "</p>"
  527.                     ];
  528.                     $objectMail "Erreur mouvement Ictocoin";
  529.                     $mail->sendMail($this->mailerint$this->mailTechnicien"noreply@ictuspharma.com"$objectMail$templateMail$paramsMail);
  530.                 }
  531.             }
  532.             //Notification pharmacie par mail et mobile
  533.             $user_pcie       $ictusPharmacieRepo->findOneById(intval($pharmacie["idpharmacie"]))->getUsers()[0];
  534.             $mobileAppareils $mobileAppareilRepo->findAllToArray($user_pcie);
  535.             $array_cfm_token array_unique((array_column($mobileAppareils"cfm_tokem")));
  536.             if (count($array_cfm_token) > 0) {
  537.                 $data = [
  538.                     'id_commande'  => intval($commande->getId()),
  539.                     'id_pharmacie' => intval($pharmacie["idpharmacie"]),
  540.                     'reference'    => $commande->getReference()
  541.                 ];
  542.                 foreach ($array_cfm_token as $tk) {
  543.                     $textNotif 'Référence commande ICTCMD_MG_' intval($pharmacie["idpharmacie"]) . '_' $commande->getReference();
  544.                     $notificationService->sendNotification($tk'Nouvelle Commande'$textNotif$data);
  545.                 }
  546.             }
  547.             $templateMail 'emails/commandePatient.html.twig';
  548.             $paramsMail = [
  549.                 'nomPatient'    => $user->getLastname(),
  550.                 'prenomPatient' => $user->getFirstname(),
  551.                 'mailPatient'   => $user->getEmail(),
  552.                 'refCommande'   => "ICT_CMD_" $commande->getId(),
  553.                 'linkCommande'  => 'https://www.pharmadexi.com/ictus/commande/patient/detail/' $commande->getId()
  554.             ];
  555.             $objectMail "Commande Ictuspharma : ICT_CMD_" $commande->getId();
  556.             $mail->sendMail($this->mailerint$pharmacie["mail"], "commande@ictuspharma.com"$objectMail$templateMail$paramsMail);
  557.             //Notification patient
  558.             $templateMail 'emails/confirmationCommandePatient.html.twig';
  559.             $paramsMail = [
  560.                 'nomPatient'    => $user->getLastname(),
  561.                 'pharmacie'    => $pharmacie,
  562.                 'listes' => $paniers,
  563.                 'refCommande'   => "ICT_CMD_" $commande->getId()
  564.             ];
  565.             $objectMail "Commande Ictuspharma : ICT_CMD_" $commande->getId();
  566.             $mail->sendMail($this->mailerint$user->getEmail(), "commande@ictuspharma.com"$objectMail$templateMail$paramsMail);
  567.         }
  568.         return $nbCommande;
  569.     }
  570.     //$paiementRepository->findAll()
  571.     #[Route('/type-paiement'name'api_patient_ictus_panier_paiement'methods: ['GET'])]
  572.     public function recupTypePaiement(IctusTypePaiementRepository $typePaiementRepo): Response
  573.     {
  574.         $typePaiements $typePaiementRepo->findAll();
  575.         if ($typePaiements) {
  576.             $dataTypePaiements = [];
  577.             if (count($typePaiements) > 0) {
  578.                 foreach ($typePaiements as $tp) {
  579.                     $dataTypePaiements[] = [
  580.                         'paiementId'   => $tp->getId(),
  581.                         'designation'  => $tp->getDesignation()
  582.                     ];
  583.                 }
  584.                 return new JsonResponse([
  585.                     'success'       => 'Informations recuperées avec succès',
  586.                     'dataTypePaiements' => $dataTypePaiements
  587.                 ], Response::HTTP_OK);
  588.             }
  589.             return new JsonResponse(['error' => 'Accun type paiement trouvé'], Response::HTTP_NOT_FOUND);
  590.         }
  591.         return new JsonResponse(['error' => 'Type paiement non trouvé'], Response::HTTP_NOT_FOUND);
  592.     }
  593.     #[Route('/paiements-pcie/{id}'name'api_patient_ictus_panier_paiemens_pcie'methods: ['GET'])]
  594.     public function recuptypePaiementPcie(IctusPharmacie $ictusPcie): Response
  595.     {
  596.         if ($ictusPcie != null) {
  597.             $paimentsPcies $ictusPcie->getIctusPaiementPharmacies();
  598.             if (count($paimentsPcies) > 0) {
  599.                 $dataPaiements = [];
  600.                 foreach ($paimentsPcies as $paiement) {
  601.                     $dataPaiements[] = [
  602.                         'paiementID'  => $paiement->getIctusTypePaiement()->getId(),
  603.                         'designation' => $paiement->getIctusTypePaiement()->getDesignation()
  604.                     ];
  605.                 }
  606.                 return new JsonResponse([
  607.                     'success'           => 'Informations recuperées avec succès',
  608.                     'dataTypePaiements' => $dataPaiements
  609.                 ], Response::HTTP_OK);
  610.             }
  611.         }
  612.         return new JsonResponse(['error' => 'Pharmacie non trouvé'], Response::HTTP_NOT_FOUND);
  613.     }
  614.     #[Route('/somme-total/{id}'name'api_patient_ictus_panier_somme_total'methods: ['GET'])]
  615.     public function sommeTotal(User $userIctusPanierPatientRepository $panierRepo): Response
  616.     {
  617.         if ($user != null) {
  618.             $monPaniers $panierRepo->findBy(['user' => $user]);
  619.             if (count($monPaniers) > 0) {
  620.                 $sommePanier 0.0;
  621.                 foreach ($monPaniers as $p) {
  622.                     $sommePanier += ($p->getTotal());
  623.                 }
  624.                 return new JsonResponse([
  625.                     'success'           => 'Informations recuperées avec succès',
  626.                     'sommePanier' => $sommePanier
  627.                 ], Response::HTTP_OK);
  628.             }
  629.         }
  630.         return new JsonResponse(['error' => 'Utilisateur non trouvé'], Response::HTTP_NOT_FOUND);
  631.     }
  632.     function getUserIpAddr()
  633.     {
  634.         if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
  635.             // IP address from shared internet
  636.             $ip $_SERVER['HTTP_CLIENT_IP'];
  637.         } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  638.             // IP address passed from proxy
  639.             $ip $_SERVER['HTTP_X_FORWARDED_FOR'];
  640.         } else {
  641.             // Regular IP address
  642.             $ip $_SERVER['REMOTE_ADDR'];
  643.         }
  644.         return $ip;
  645.     }
  646.     public function montantWithFrai($val)
  647.     {
  648.         $pourcentage 0;
  649.         switch (true) {
  650.             case ($val && $val <= 10000):
  651.                 $pourcentage 2;
  652.                 break;
  653.             case ($val 10000 && $val <= 20000):
  654.                 $pourcentage 1.75;
  655.                 break;
  656.             case ($val 20000 && $val <= 30000):
  657.                 $pourcentage 1.25;
  658.                 break;
  659.             case ($val 30000 && $val <= 50000):
  660.                 $pourcentage 1.5;
  661.                 break;
  662.             case ($val 50000 && $val <= 80000):
  663.                 $pourcentage 1.75;
  664.                 break;
  665.             case ($val 80000 && $val <= 120000):
  666.                 $pourcentage 1.5;
  667.                 break;
  668.             case ($val 120000 && $val <= 170000):
  669.                 $pourcentage 1.40;
  670.                 break;
  671.             case ($val 170000):
  672.                 $pourcentage 1.30;
  673.                 break;
  674.             default:
  675.                 $pourcentage 0;
  676.                 break;
  677.         }
  678.         return $val + ($val $pourcentage 100);
  679.     }
  680. }