<?php
namespace App\Controller\APIIctus;
use DateTime;
use App\Entity\User;
use App\Services\Util;
use App\Entity\Ordonnance;
use App\Entity\IctusCommande;
use App\Entity\IctusPharmacie;
use App\Entity\Stockpharmacie;
use App\Services\MailerServices;
use App\Entity\IctusCommandeLine;
use App\Services\IctocoinService;
use App\Entity\IctusPanierPatient;
use App\Entity\IctusPanierSpecial;
use App\Repository\UserRepository;
use App\Services\api\PanierService;
use App\Services\NotificationService;
use App\Services\FacturePatientService;
use App\Repository\OrdonnanceRepository;
use App\Services\VanillaPaiementSercice;
use Doctrine\ORM\EntityManagerInterface;
use App\Services\CodeRecuperationService;
use App\Repository\TypepaiementRepository;
use App\Repository\IctusCommandeRepository;
use App\Repository\IctusPharmacieRepository;
use App\Repository\StockpharmacieRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\HttpFoundation\Response;
use App\Repository\IctusEtatPaiementRepository;
use App\Repository\IctusTypePaiementRepository;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\IctusPanierPatientRepository;
use App\Repository\IctusTypeLivraisonRepository;
use App\Repository\IctusMobileAppareilRepository;
use App\Services\VanillaPayInternationnalService;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
#[Route('/api/ictus-shop/panier', name: 'app_api_ictus_shop_panier_')]
class APIIctPanierController extends AbstractController
{
private $em;
private $mailerint;
private $mailTechnicien = "zoanja.rabehaja@sopharmad.mg";
private $util;
private $montantTotalPaiementEnLigne = 0;
private $listeCommandePaiementEnLigne = array();
private $notifUrl;
private $redirectUrl;
public function __construct(EntityManagerInterface $em, MailerInterface $mailerint, Util $util, UrlGeneratorInterface $urlGenerator)
{
$this->em = $em;
$this->mailerint = $mailerint;
$this->util = $util;
$this->notifUrl = $_ENV["VANILLA_INT_URL_NOTIF"];
$this->redirectUrl = $_ENV["VANILLA_INT_URL_REDIRECT"];
}
#[Route('/non-authentifier', name: 'non_auth', methods: ['GET'])]
public function panierNonAuth(Request $request, StockpharmacieRepository $stockpharmacieRepository, PanierService $panierService): Response
{
$produitPcie = $request->query->all('produitPcie');
$produitPcie = array_map('intval', $produitPcie);
$panierCart = $panierService->getFull($stockpharmacieRepository, null,$produitPcie);
$responseData = [
'error' => true,
];
if (count($panierService->groupByIdPcie($panierCart)) > 0) {
$responseData = $panierService->groupByIdPcie($panierCart);
return $this->json($responseData);
}
return $this->json($responseData, 500, [], []);
}
/******************Ajouter panier dans MySQL************** */
//Enregistrement panier direct dans DB MysQl par l'user connectee dans meilleur vente
#[Route('/ajout-auth-mysql', name: 'app_panier_add_auth', methods: ['POST'])]
public function ajoutPanierAuthBestSeller(Request $request, IctusPanierPatientRepository $panierRepo, UserRepository $userRepository, StockpharmacieRepository $stockPcieRepo): Response
{
// Récupérer les données du corps de la requête
$data = json_decode($request->getContent(), true);
// Vérifier si userId est bien envoyé
if (!isset($data['userId'])) {
return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
}
// Vérifier si les produits sont bien envoyés
if (!isset($data['produit'])) {
return $this->json(['error' => 'Aucun produit fourni'], JsonResponse::HTTP_BAD_REQUEST);
}
// Récupérer l'utilisateur depuis l'ID envoyé
$user = $userRepository->find($data['userId']);
if (!$user) {
return $this->json(['error' => 'Utilisateur non trouvé'], JsonResponse::HTTP_NOT_FOUND);
}
if (!isset($data['produit'], $data['quantite'])) {
return $this->json(['error' => 'Informations du produit manquantes'], JsonResponse::HTTP_BAD_REQUEST);
}
// Récupérer le produit en base de données
$produit = $stockPcieRepo->find($data['produit']);
if (!$produit) {
return $this->json(['error' => 'Produit non trouvé'], JsonResponse::HTTP_NOT_FOUND);
}
// produit exit panier ou non
$existPanier = $panierRepo->findOneBy(['user' => $user, 'produit_stock_pcie' => $produit]);
$quantite = $data['quantite'];
$tva = $produit->getTva();
if (!is_null($existPanier)) {
$quantite = $existPanier->getQuantite() + $data['quantite'];
}
$panier = (!is_null($existPanier)) ? $existPanier : new IctusPanierPatient();
// Calculer le prix total
$prix_unitaire = (!is_null($tva)) ? ($produit->getPrixunitforme() + ($produit->getPrixunitforme() * $tva) / 100) : $produit->getPrixunitforme();
// Créer une nouvelle entrée dans le panier
$panier->setProduitStockPcie($produit)
->setUser($user)
->setQuantite($quantite)
->setPrixUnitaire($prix_unitaire)
->setTotal($quantite * $prix_unitaire);
// Persister dans la base de données
$this->em->persist($panier);
$this->em->flush();
return $this->json(['message' => 'Panier enregistré avec succès'], JsonResponse::HTTP_CREATED);
}
//Enregistrement panier SQLite dans DB MysQl apres login
#[Route('/ajout-sqlit-mysql', name: 'app_panier_add_sqlite_to_mysql_apre_login', methods: ['POST'])]
public function enregistrementPanierDB(
Request $request,
StockpharmacieRepository $stockPcieRepo,
UserRepository $userRepo,
IctusPanierPatientRepository $panierRepo,
EntityManagerInterface $em
): JsonResponse {
// Récupérer les données du corps de la requête
$data = json_decode($request->getContent(), true);
// Vérifier si userId est bien envoyé
if (!isset($data['userId'])) {
return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
}
// Vérifier si les produits sont bien envoyés
if (!isset($data['produits']) || !is_array($data['produits'])) {
return $this->json(['error' => 'Aucun produit fourni'], JsonResponse::HTTP_BAD_REQUEST);
}
$user = $userRepo->findOneById($data['userId']);
if (!$user) {
return $this->json(['error' => 'Utilisateur: '.$data['userId'].' non trouvé'], JsonResponse::HTTP_NOT_FOUND);
}
$paniers = $data['produits'];
$prixTotal = 0;
foreach ($paniers as $panierSession) {
// Vérifier les informations du produit
if (!isset($panierSession['idProduit'], $panierSession['quantite'])) {
return $this->json(['error' => 'Informations du produit manquantes'], JsonResponse::HTTP_BAD_REQUEST);
}
// Récupérer le produit en base de données
$produit = $stockPcieRepo->find($panierSession['idProduit']);
if (!$produit) {
return $this->json(['error' => 'Produit non trouvé'], JsonResponse::HTTP_NOT_FOUND);
}
$existPanier = $panierRepo->findOneBy(['user' => $user, 'produit_stock_pcie' => $produit]);
$quantite = $panierSession['quantite'];
$tva = $produit->getTva();
if (!is_null($existPanier)) {
$quantite = $existPanier->getQuantite() + $panierSession['quantite'];
}
$panier = (!is_null($existPanier)) ? $existPanier : new IctusPanierPatient();
$prix_unitaire = (!is_null($tva)) ? ($produit->getPrixunitforme() + ($produit->getPrixunitforme() * $tva) / 100) : $produit->getPrixunitforme();
$prixTotal += $quantite * $prix_unitaire;
// Créer une nouvelle entrée dans le panier
$panier->setProduitStockPcie($produit)
->setUser($user)
->setQuantite($quantite)
->setPrixUnitaire($prix_unitaire)
->setTotal($quantite * $prix_unitaire);
// Essayer de persister chaque entrée
try {
$em->persist($panier);
} catch (\Exception $e) {
// Logger l'erreur avec plus de détails
return $this->json(['erreur' => 'Erreur lors de l\'ajout au panier: ' . $e->getMessage()], JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
}
}
// Enregistrer tous les paniers en une seule transaction
try {
$em->flush();
} catch (\Exception $e) {
return $this->json(['erreur' => 'Erreur lors de l\'enregistrement des paniers: ' . $e->getMessage()], JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
}
return $this->json(['message' => 'Panier ajouté avec succès', 'total' => $prixTotal], JsonResponse::HTTP_CREATED);
}
#[Route('/count-mysql', name: 'app_panier_count_mysql', methods: ['POST'])]
public function getCountProduitParUser(Request $request, UserRepository $userRepo, IctusPanierPatientRepository $panierRepo)
{
$data = json_decode($request->getContent(), true);
if (!isset($data['userId'])) {
return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
}
$user = $userRepo->find($data['userId']);
if (!$user) {
return $this->json(['error' => 'Utilisateur non trouvé'], JsonResponse::HTTP_NOT_FOUND);
}
$countPanier = $panierRepo->findCountpanierByUser($user);
return $this->json(["countPanier" => $countPanier]);
}
//Liste produit dans panier MySQL pour l'utilisateur connecte
#[Route('/mysql-user-connecte', name: 'mysql_user_connecte', methods: ['POST'])]
public function panierMySQLUserConnectee(
Request $request,
StockpharmacieRepository $stockpharmacieRepository,
PanierService $panierService,
IctusPanierPatientRepository $panierRepo,
UserRepository $userRepo
): Response {
$data = json_decode($request->getContent(), true);
if (!isset($data['userId'])) {
return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
}
$user = $userRepo->find($data['userId']);
$produitPcie = $panierRepo->findAllByUser($user);
$coupleIdQuantite = [];
if (count($produitPcie) > 0) {
foreach ($produitPcie as $panier) {
$idStockPcie = $panier->getProduitStockPcie()->getId();
$quantite = $panier->getQuantite();
$coupleIdQuantite[$idStockPcie] = $quantite;
}
}
$panierCart = $panierService->getFull($stockpharmacieRepository, $user, $coupleIdQuantite);
$responseData = [
'error' => true,
];
if (count($panierService->groupByIdPcie($panierCart)) > 0) {
$responseData = $panierService->groupByIdPcie($panierCart);
return $this->json($responseData, JsonResponse::HTTP_OK);
}
return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
}
#[Route('/mysql-user-connecte-update-quantite', name: 'mysql_user_connecte_update_quantite', methods: ['POST'])]
public function updateQuantiteProduitPanier(
Request $request,
StockpharmacieRepository $stockpharmacieRepository,
IctusPanierPatientRepository $panierRepo,
UserRepository $userRepo
): Response {
$data = json_decode($request->getContent(), true);
$panier = null;
$stockpcie = null;
if (!isset($data['userId'])) {
return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
}
$user = $userRepo->find($data['userId']);
if (is_null($user)) {
return $this->json(['error' => 'User non trouve'], JsonResponse::HTTP_NOT_FOUND);
}
if (!isset($data['produit'])) {
return $this->json(['error' => 'ID Produit manquant'], JsonResponse::HTTP_BAD_REQUEST);
}
$stockpcie = $stockpharmacieRepository->findOneById($data['produit']);
if (is_null($stockpcie)) {
return $this->json(['error' => 'Produit non trouve'], JsonResponse::HTTP_NOT_FOUND);
}
$panier = $panierRepo->findOneBy(['produit_stock_pcie' => $stockpcie, 'user' => $user]);
/******* */
$tva = $stockpcie->getTva();
$prix_unitaire = (!is_null($tva)) ? ($stockpcie->getPrixunitforme() + ($stockpcie->getPrixunitforme() * $tva) / 100) : $stockpcie->getPrixunitforme();
$pixTotal = $prix_unitaire * $data['quantite'];
/************ */
if (!is_null($panier)) {
$panier->setQuantite($data['quantite'])
->setTotal($pixTotal)
->setPrixUnitaire($prix_unitaire);
$this->em->flush();
$newData = [
'userId' => $data['userId'],
'produit' => $data['produit'],
'quantite' => $data['quantite'],
'prix_unitaire' => $prix_unitaire,
'total' => $pixTotal
];
return $this->json($newData, JsonResponse::HTTP_OK);
}
return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
}
#[Route('/mysql-user-connecte-delete', name: 'mysql_user_connecte_delete', methods: ['POST'])]
public function deleteProduitPanierMySQL(
Request $request,
StockpharmacieRepository $stockpharmacieRepository,
IctusPanierPatientRepository $panierRepo,
UserRepository $userRepo
): Response {
$data = json_decode($request->getContent(), true);
$panier = null;
$stockpcie = null;
if (!isset($data['userId'])) {
return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
}
$user = $userRepo->find($data['userId']);
if (is_null($user)) {
return $this->json(['error' => 'User non trouve'], JsonResponse::HTTP_NOT_FOUND);
}
if (!isset($data['produit'])) {
return $this->json(['error' => 'ID Produit manquant'], JsonResponse::HTTP_BAD_REQUEST);
}
$stockpcie = $stockpharmacieRepository->findOneById($data['produit']);
if (is_null($stockpcie)) {
return $this->json(['error' => 'Produit non trouve'], JsonResponse::HTTP_NOT_FOUND);
}
$panier = $panierRepo->findOneBy(['produit_stock_pcie' => $stockpcie, 'user' => $user]);
/************ */
if (!is_null($panier)) {
$this->em->remove($panier);
$this->em->flush();
return $this->json("DATA DELETED OK", JsonResponse::HTTP_OK);
}
return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
}
//Ajouter ordonnace dans un produit panier
#[Route('/create/ordonnance', name: 'create_ordonnance', methods: ['POST'])]
public function createOrdonnancePanier(
Request $request,
OrdonnanceRepository $ordonaceRepo,
PanierService $panierService,
StockpharmacieRepository $stockpharmacieRepository,
IctusPanierPatientRepository $panierRepo,
UserRepository $userRepo
): Response {
//$data = json_decode($request->getContent(), true);
$panierData = $panierService->handleDataPanier($userRepo, $stockpharmacieRepository, $panierRepo, $request);
if (isset($panierData['error'])) {
return $this->json($panierData, JsonResponse::HTTP_BAD_REQUEST);
}
// Si tout est correct, vous pouvez procéder à la création de l'ordonnance
$user = $panierData['user'];
if ($user instanceof User) {
$panier = $panierData['panier'];
if (!is_null($panier) && $panier instanceof IctusPanierPatient) {
$panier->setOrdonnance($ordonaceRepo->createOrdonnance($panierData['file'], $panierData['titre'], $panierData['user']));
$this->em->flush();
} else {
$ordonaceRepo->createOrdonnance($panierData['file'], $panierData['titre'], $panierData['user']);
}
return $this->json(['CREATED' => "DATA CREATE OK"], JsonResponse::HTTP_CREATED);
}
return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
}
//allOrdonneByIdUser()
#[Route('/ordonnance/{id}', name: 'get_ordonnance', methods: ['GET'])]
public function recupOrdonnanceByUser(User $user, OrdonnanceRepository $ordonaceRepo): Response
{
$dataOrdonnances = [];
if (!is_null($user)) {
$ordonnances = $ordonaceRepo->findAllOrdonnanceByIdUser($user->getId());
if (count($ordonnances)) {
foreach ($ordonnances as $ordo) {
$dataOrd = [
'id' => $ordo->getId(),
'userId' => $ordo->getPropriertaire()->getId(),
'titre' => $ordo->getTitre(),
'file' => $ordo->getFichier()
];
array_push($dataOrdonnances, $dataOrd);
}
return $this->json($dataOrdonnances, JsonResponse::HTTP_OK);
}
}
return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
}
//Update PanierOrdonnace
#[Route('/update/ordonnance', name: 'update_ordonnance', methods: ['POST'])]
public function updateOrdonnancePanier(
Request $request,
OrdonnanceRepository $ordonaceRepo,
StockpharmacieRepository $stockpharmacieRepository,
IctusPanierPatientRepository $panierRepo,
UserRepository $userRepo
): Response {
$data = json_decode($request->getContent(), true);
if (!isset($data['produitId'])) {
return $this->json(['error' => 'Produit manquant'], JsonResponse::HTTP_BAD_REQUEST);
}
$stockpcie = $stockpharmacieRepository->findOneById($data['produitId']);
if (!isset($data['userId'])) {
return $this->json(['error' => 'ID utilisateur manquant'], JsonResponse::HTTP_BAD_REQUEST);
}
$user = $userRepo->find($data['userId']);
$panier = $panierRepo->findOneBy(['produit_stock_pcie' => $stockpcie, 'user' => $user]);
if (!isset($data['ordonnanceId'])) {
return $this->json(['error' => 'Id ordonnance manquant'], JsonResponse::HTTP_BAD_REQUEST);
}
$ordonnance = $ordonaceRepo->findOneById($data['ordonnanceId']);
if ($user instanceof User && $ordonnance instanceof Ordonnance && $panier instanceof IctusPanierPatient) {
$panier->setOrdonnance($ordonnance);
$this->em->flush();
return $this->json(['UPDATED' => "DATA UPDATED OK"], JsonResponse::HTTP_OK);
}
return $this->json(['error' => 'Empty Data'], JsonResponse::HTTP_NOT_FOUND);
}
/* url = {base_url}/api/ictus-shop/panier/panier/sendcommande/{userId}/{typeLivraisonId}/{typePaiementId}
method : GET
*/
#[Route('/sendcommande/{userId}/{typeLivraisonId}/{typePaiementId}', name: 'panier_sendcommande', methods: ['GET'])]
public function panierSendcommande(Request $request, FacturePatientService $facturePatientService, IctusMobileAppareilRepository $mobileAppareilRepo, NotificationService $notificationService, MailerServices $mail, IctocoinService $ictocoinService, VanillaPayInternationnalService $vanillaPayInternationnalService, UserRepository $userRepo, IctusPanierPatientRepository $ictusPanierPatientRepo, IctusTypeLivraisonRepository $ictusTypeLivraisonRepo, IctusTypePaiementRepository $ictusTypePaiementRepo, IctusPharmacieRepository $ictusPharmacieRepo, IctusEtatPaiementRepository $etatPaiementRepo, IctusCommandeRepository $ictusCommandeRepo, CodeRecuperationService $codeRecuperationService, $userId, $typeLivraisonId, $typePaiementId)
{
if ($request->isMethod('GET')) {
$urlPaiement = null;
if ($typeLivraisonId != null && $typePaiementId != null && $userId != null) {
$user = $userRepo->find($userId);
$token = (new \DateTime())->format('YmdiHs') . $user->getId();
$typeLivraison = $ictusTypeLivraisonRepo->find($typeLivraisonId);
$typePaiement = $ictusTypePaiementRepo->find($typePaiementId);
$paniers = $ictusPanierPatientRepo->findBy(['user' => $user]);
if (count($paniers) > 0) {
$nbCommandes = $this->sendCommande($paniers, $typePaiement, $typeLivraison, $user, $ictusPanierPatientRepo, $ictusPharmacieRepo, $etatPaiementRepo, $token, $ictusCommandeRepo, $codeRecuperationService, $ictusTypePaiementRepo, $facturePatientService, $ictocoinService, $mail, $notificationService, $mobileAppareilRepo);
$ictusPanierPatientRepo->removeProduit($user->getId());
if ($nbCommandes > 0) {
/* Paiement si necessaire */
if (count($this->listeCommandePaiementEnLigne) > 0 and $this->montantTotalPaiementEnLigne > 0) {
$liste = json_encode($this->listeCommandePaiementEnLigne);
$reference = (new DateTime())->format('YmdHis') . $user->getId();
if ($typePaiement->getId() == 4) {
$vanilla = new VanillaPaiementSercice($this->util);
$nomUser = $user->getNomComplet();
$adresseip = $this->getUserIpAddr();
$urlPaiement = $vanilla->payer($liste, $this->montantWithFrai($this->montantTotalPaiementEnLigne), $nomUser, $reference, $adresseip);
if ($urlPaiement != null) {
$urlPaiement = $urlPaiement->getTargetUrl();
}
} else if ($typePaiement->getId() == 5) {
$urlPaiement = $vanillaPayInternationnalService->payer($liste, $this->montantTotalPaiementEnLigne, $reference, $this->notifUrl, $this->redirectUrl);
if ($urlPaiement != null) {
$urlPaiement = $urlPaiement->getTargetUrl();
}
}
}
return $this->json(['success' => 'Success', 'message' => 'Commandes envoyées avec succès', 'nbCommandes' => $nbCommandes, 'urlPaiement' => $urlPaiement], JsonResponse::HTTP_OK);
}
return $this->json(['error' => 'Error', 'message' => 'Aucun commande envoyée', 'nbCommandes' => $nbCommandes, 'urlPaiement' => $urlPaiement], JsonResponse::HTTP_OK);
}
return $this->json(['error' => 'Error', 'message' => 'Panier vide', 'nbCommandes' => 0, 'urlPaiement' => $urlPaiement], JsonResponse::HTTP_OK);
} else {
return $this->json(['error' => 'Error', 'message' => 'Parametre manquant', 'nbCommandes' => 0, 'urlPaiement' => $urlPaiement], JsonResponse::HTTP_BAD_REQUEST);
}
}
}
private function sendCommande(
$paniers,
$typePaiement,
$typeLivraison,
$user,
$ictusPanierPatientRepo,
$ictusPharmacieRepo,
$etatPaiementRepo,
$token,
$ictusCommandeRepo,
$codeRecuperationService,
$ictusTypePaiementRepo,
$facturePatientService,
$ictocoinService,
$mail,
$notificationService,
$mobileAppareilRepo
) {
$etatPaiementDefault = $etatPaiementRepo->findOneById(1);
$pharmacies = $ictusPanierPatientRepo->getPcieDistinctByPatientAndTypePaiement($user, $typePaiement);
$nbCommande = 0;
foreach ($pharmacies as $pharmacie) {
$paiement = null;
if ($pharmacie["idTypePaiement"] != null) {
$paiement = $typePaiement;
} else {
$paiement = $ictusTypePaiementRepo->findOneById(1);
}
$maxReference = $ictusCommandeRepo->findMaxReference($pharmacie["idpharmacie"])[0]["maxReference"];
if ($maxReference == null) {
$maxReference = 0;
}
$maxReference = (int)$maxReference + 1;
$createdAt = new DateTime();
$createdAt->modify('+2 hours');
$commande = new IctusCommande();
$codeComplet = $codeRecuperationService->generateCommande();
$commande->setPharmacie($ictusPharmacieRepo->findOneById(intval($pharmacie["idpharmacie"])))
->setTypeLivraison($typeLivraison)
->setTypePaiement($paiement)
->setUser($user)
->setToken($token)
->setReference($maxReference)
->setEtatpaiement($etatPaiementDefault)
->setCreatedAt($createdAt)
->setIsRecuperer(false)
->setIsValide($pharmacie["isValideAutomatique"])
->setIsValide($pharmacie["isValideAutomatique"])
->setCode($codeComplet['code'])
->setCodeSecret($codeComplet['secret']);
$this->em->persist($commande);
$montantTotal = 0;
foreach ($paniers as $panier) {
if ($pharmacie["idpharmacie"] == $panier->getProduitStockPcie()->getIctuspharmacie()->getId()) {
$commandeLine = new IctusCommandeLine();
$commandeLine->setQuantite($panier->getQuantite())
->setDesignation($panier->getProduitStockPcie()->getNomproduit())
->setCip7($panier->getProduitStockPcie()->getCip7())
->setCip13($panier->getProduitStockPcie()->getCip13())
->setPrixunitaire($panier->getPrixUnitaire() ?? 0)
->setRemise($panier->getProduitStockPcie()->getRemise())
->setOrdonnance($panier->getOrdonnance())
->setCommande($commande)
->setIsValide($pharmacie["isValideAutomatique"]);
$this->em->persist($commandeLine);
$montantTotal += $panier->getPrixUnitaire() * $panier->getQuantite();
}
}
$this->em->flush();
$nbCommande++;
//Creation facture et ictocoin au cas ou
if ($pharmacie["isValideAutomatique"] != null) {
$this->montantTotalPaiementEnLigne += $montantTotal;
array_push($this->listeCommandePaiementEnLigne, "CMD-" . $commande->getId());
$facturePatientService->editPatient($commande);
$raison = 'Frais de gestion sur la commande du ' . date("d M Y") . ', Référence :/cmd {{' . $commande->getId() . '}}';
$montantDebit = $ictocoinService->montantIctocoin($pharmacie["idpharmacie"], $montantTotal);
$debitage = $ictocoinService->debiter($pharmacie["idpharmacie"], $montantDebit, $raison);
if ($debitage != true) {
$templateMail = 'emails/erreurIctocoin.html.twig';
$paramsMail = [
'type' => "Débit",
'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>"
];
$objectMail = "Erreur mouvement Ictocoin";
$mail->sendMail($this->mailerint, $this->mailTechnicien, "noreply@ictuspharma.com", $objectMail, $templateMail, $paramsMail);
}
}
//Notification pharmacie par mail et mobile
$user_pcie = $ictusPharmacieRepo->findOneById(intval($pharmacie["idpharmacie"]))->getUsers()[0];
$mobileAppareils = $mobileAppareilRepo->findAllToArray($user_pcie);
$array_cfm_token = array_unique((array_column($mobileAppareils, "cfm_tokem")));
if (count($array_cfm_token) > 0) {
$data = [
'id_commande' => intval($commande->getId()),
'id_pharmacie' => intval($pharmacie["idpharmacie"]),
'reference' => $commande->getReference()
];
foreach ($array_cfm_token as $tk) {
$textNotif = 'Référence commande ICTCMD_MG_' . intval($pharmacie["idpharmacie"]) . '_' . $commande->getReference();
$notificationService->sendNotification($tk, 'Nouvelle Commande', $textNotif, $data);
}
}
$templateMail = 'emails/commandePatient.html.twig';
$paramsMail = [
'nomPatient' => $user->getLastname(),
'prenomPatient' => $user->getFirstname(),
'mailPatient' => $user->getEmail(),
'refCommande' => "ICT_CMD_" . $commande->getId(),
'linkCommande' => 'https://www.pharmadexi.com/ictus/commande/patient/detail/' . $commande->getId()
];
$objectMail = "Commande Ictuspharma : ICT_CMD_" . $commande->getId();
$mail->sendMail($this->mailerint, $pharmacie["mail"], "commande@ictuspharma.com", $objectMail, $templateMail, $paramsMail);
//Notification patient
$templateMail = 'emails/confirmationCommandePatient.html.twig';
$paramsMail = [
'nomPatient' => $user->getLastname(),
'pharmacie' => $pharmacie,
'listes' => $paniers,
'refCommande' => "ICT_CMD_" . $commande->getId()
];
$objectMail = "Commande Ictuspharma : ICT_CMD_" . $commande->getId();
$mail->sendMail($this->mailerint, $user->getEmail(), "commande@ictuspharma.com", $objectMail, $templateMail, $paramsMail);
}
return $nbCommande;
}
//$paiementRepository->findAll()
#[Route('/type-paiement', name: 'api_patient_ictus_panier_paiement', methods: ['GET'])]
public function recupTypePaiement(IctusTypePaiementRepository $typePaiementRepo): Response
{
$typePaiements = $typePaiementRepo->findAll();
if ($typePaiements) {
$dataTypePaiements = [];
if (count($typePaiements) > 0) {
foreach ($typePaiements as $tp) {
$dataTypePaiements[] = [
'paiementId' => $tp->getId(),
'designation' => $tp->getDesignation()
];
}
return new JsonResponse([
'success' => 'Informations recuperées avec succès',
'dataTypePaiements' => $dataTypePaiements
], Response::HTTP_OK);
}
return new JsonResponse(['error' => 'Accun type paiement trouvé'], Response::HTTP_NOT_FOUND);
}
return new JsonResponse(['error' => 'Type paiement non trouvé'], Response::HTTP_NOT_FOUND);
}
#[Route('/paiements-pcie/{id}', name: 'api_patient_ictus_panier_paiemens_pcie', methods: ['GET'])]
public function recuptypePaiementPcie(IctusPharmacie $ictusPcie): Response
{
if ($ictusPcie != null) {
$paimentsPcies = $ictusPcie->getIctusPaiementPharmacies();
if (count($paimentsPcies) > 0) {
$dataPaiements = [];
foreach ($paimentsPcies as $paiement) {
$dataPaiements[] = [
'paiementID' => $paiement->getIctusTypePaiement()->getId(),
'designation' => $paiement->getIctusTypePaiement()->getDesignation()
];
}
return new JsonResponse([
'success' => 'Informations recuperées avec succès',
'dataTypePaiements' => $dataPaiements
], Response::HTTP_OK);
}
}
return new JsonResponse(['error' => 'Pharmacie non trouvé'], Response::HTTP_NOT_FOUND);
}
#[Route('/somme-total/{id}', name: 'api_patient_ictus_panier_somme_total', methods: ['GET'])]
public function sommeTotal(User $user, IctusPanierPatientRepository $panierRepo): Response
{
if ($user != null) {
$monPaniers = $panierRepo->findBy(['user' => $user]);
if (count($monPaniers) > 0) {
$sommePanier = 0.0;
foreach ($monPaniers as $p) {
$sommePanier += ($p->getTotal());
}
return new JsonResponse([
'success' => 'Informations recuperées avec succès',
'sommePanier' => $sommePanier
], Response::HTTP_OK);
}
}
return new JsonResponse(['error' => 'Utilisateur non trouvé'], Response::HTTP_NOT_FOUND);
}
function getUserIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
// IP address from shared internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// IP address passed from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
// Regular IP address
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
public function montantWithFrai($val)
{
$pourcentage = 0;
switch (true) {
case ($val > 0 && $val <= 10000):
$pourcentage = 2;
break;
case ($val > 10000 && $val <= 20000):
$pourcentage = 1.75;
break;
case ($val > 20000 && $val <= 30000):
$pourcentage = 1.25;
break;
case ($val > 30000 && $val <= 50000):
$pourcentage = 1.5;
break;
case ($val > 50000 && $val <= 80000):
$pourcentage = 1.75;
break;
case ($val > 80000 && $val <= 120000):
$pourcentage = 1.5;
break;
case ($val > 120000 && $val <= 170000):
$pourcentage = 1.40;
break;
case ($val > 170000):
$pourcentage = 1.30;
break;
default:
$pourcentage = 0;
break;
}
return $val + ($val * $pourcentage / 100);
}
}