<?php
namespace App\Controller\APIIctus;
use App\Entity\User;
use Psr\Log\LoggerInterface;
use App\Entity\IctusCommande;
use App\Services\FactureService;
use App\Services\MailerServices;
use App\Entity\IctusCommandeLine;
use App\Entity\IctusTypePaiement;
use App\Services\IctocoinService;
use App\Repository\UserRepository;
use App\Service\NotificationsService;
use App\Services\NotificationService;
use App\Entity\IctusHistoriquePaiement;
use Doctrine\ORM\EntityManagerInterface;
use App\Repository\TypepaiementRepository;
use App\Repository\IctusCommandeRepository;
use App\Repository\IctusPharmacieRepository;
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\IctusMobileAppareilRepository;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Services\api\NotificationTwoPackagesService;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/**
* @Route("/api_ictus/commande/patient/", name="api_ictus_commande_patient_")
*/
class ApiIctusCommandeController extends AbstractController
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* @Route("liste/cmd/{user}", name="liste_cmd", methods={"GET"})
*/
public function cmdListe(IctusCommandeRepository $commandeRepository, User $user): Response
{
$response = [
"error" => true,
"message" => "Erreur lors de la recuperation des commandes"
];
if ($user) {
$commandes = $commandeRepository->findBy(['user' => $user], ['createdAt' => 'DESC']);
$dataCmd = [];
$allDataCommandes = [];
foreach ($commandes as $cmd) {
$paiementOnline = null;
$fraisPaiement = null;
if ($cmd->getTypePaiement()->getId() != 1) {
$fraisPaiement = 0;
if ($cmd->getTypePaiement()->getId() == 4) {
$fraisPaiement = $this->pourcentageVanillaPay($cmd->getTotalCommande());
}
$paiementOnline = [
'fraisVannilaPay' => $fraisPaiement,
'montantPaiement' => $cmd->getTotalCommande() + $fraisPaiement,
'apiUrlPaiement' => $this->generateUrl('api_ictus_paiement_payer_commande', ['commande' => $cmd->getId()], UrlGeneratorInterface::ABSOLUTE_URL)
];
}
$adresse = $cmd->getPharmacie()->getAdresse() . ", " . $cmd->getPharmacie()->getQuartier()->getName() . ", " . $cmd->getPharmacie()->getQuartier()->getVille()->getName();
$pharmacie = [
'id' => $cmd->getPharmacie()->getId(),
'designation' => $cmd->getPharmacie()->getDesignation(),
'adresse' => $adresse
];
$dataCmd = [
'id' => $cmd->getId(),
'reference' => "ICTCMD_MG_" . $cmd->getPharmacie()->getId() . "_" . $cmd->getReference(),
'date' => $cmd->getCreatedAt()->format('Y-m-d'),
'paiement' => $cmd->getTypePaiement()->getDesignation(),
'livraison' => $cmd->getTypeLivraison()->getDesignation(),
'some_total' => $cmd->getTotalCommande(),
'total_produit'=> $cmd->getTotalProduit(),
'isValid' => $cmd->isIsValide(),
'etat_recuperation'=> $cmd->isIsRecuperer()
];
$allDataCommandes[] = [
'commande' => $dataCmd,
'paiement' => $paiementOnline,
'pharmacie'=> $pharmacie
];
}
$response = [
"success" => "Success",
"allDataCommandes" => $allDataCommandes
];
}
return new JsonResponse($response);
}
private function pourcentageVanillaPay($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 * (($pourcentage / 100) / (1 - ($pourcentage / 100)));
}
/**
* @Route("entente/{id}", name="listes", methods={"GET"})
*/
public function cmdEntante(IctusCommandeRepository $commandeRepository, User $user): Response
{
$commandes = $commandeRepository->findByMultipleIsValide(false, $user->getIctusPharmacie());
$dataCmd = [];
foreach ($commandes as $cmd) {
$dataCmd[] = [
'id' => $cmd->getId(),
'reference' => "ICTCMD_MG_" . $cmd->getPharmacie()->getId() . "_" . $cmd->getReference(),
'date' => $cmd->getCreatedAt()->format('d-m-Y'),
'paiement' => $cmd->getTypePaiement()->getDesignation(),
'livraison' => $cmd->getTypeLivraison()->getDesignation(),
'montant' => $cmd->getTotalCommande(),
'totalProduit' => $cmd->getTotalProduit(),
'isValid' => $cmd->isIsValide(),
'idPcie' => $cmd->getPharmacie()->getId()
];
}
return new JsonResponse($dataCmd);
}
/**
* @Route("valid/{id}", name="listes_valide", methods={"GET"})
*/
public function cmdvalid(IctusCommandeRepository $commandeRepository, User $user): Response
{
$commandes = $commandeRepository->findByMultipleIsValide(true, $user->getIctusPharmacie());
$dataCmd = [];
foreach ($commandes as $cmd) {
$dataCmd[] = [
'id' => $cmd->getId(),
'reference' => "ICTCMD_MG_" . $cmd->getPharmacie()->getId() . "_" . $cmd->getReference(),
'date' => $cmd->getCreatedAt()->format('d-m-Y'),
'paiement' => $cmd->getTypePaiement()->getDesignation(),
'livraison' => $cmd->getTypeLivraison()->getDesignation(),
'montant' => $cmd->getTotalCommande(),
'totalProduit' => $cmd->getTotalProduit(),
'isValid' => $cmd->isIsValide(),
'idPcie' => $cmd->getPharmacie()->getId()
];
}
return new JsonResponse($dataCmd);
}
/**
* @Route("detail/{id}", name="detail", methods={"GET"})
*/
public function detail(IctusCommande $commande): Response
{
$dataCmd_produit = [];
$patient = $commande->getUser();
$dataCmd_patient = [
'patientId' => $patient->getId(),
'nomComplet' => $patient->getNomComplet(),
'telephone' => $patient->getPhone(),
'mail' => $patient->getEmail()
];
$dataCmd = [];
foreach ($commande->getIctusCommandeLines() as $line) {
$total = $line->getPrixunitaire() * $line->getQuantite();
$temp = [
'id' => $line->getId(),
'designation' => $line->getDesignation(),
'pu' => $line->getPrixunitaire(),
'quantite' => $line->getQuantite(),
'total' => $total,
'isValid' => $line->isIsValide()
];
array_push($dataCmd_produit, $temp);
}
$dataCmd = [
'id' => $commande->getId(),
'reference' => "ICTCMD_MG_" . $commande->getPharmacie()->getId() . "_" . $commande->getReference(),
'date' => $commande->getCreatedAt()->format('d-m-Y'),
'paiement' => $commande->getTypePaiement()->getDesignation(),
'livraison' => $commande->getTypeLivraison()->getDesignation(),
'montant' => $commande->getTotalCommande(),
'totalProduit' => $commande->getTotalProduit(),
'isValid' => $commande->isIsValide(),
'isLivre' => $commande->isIsLivrer(),
'etatpaiement' => $commande->getEtatpaiement()->getId(),
'designationPaiement' => $commande->getEtatpaiement()->getDesignation(),
'typepepaiement' => $commande->getTypePaiement()->getId(),
'designationtypepaiement' => $commande->getTypePaiement()->getDesignation(),
'detailCmd' => $dataCmd_produit,
'patient' => $dataCmd_patient
];
return new JsonResponse($dataCmd);
}
/**
* @Route("validation/{id}", name="validation_cmd", methods={"GET"})
*/
public function editValidCmd(
IctusCommande $commande,
IctocoinService $ictocoinService,
MailerServices $mailerServices,
MailerInterface $mi,
FactureService $factureService,
NotificationTwoPackagesService $notificationPatientService,
IctusMobileAppareilRepository $mobileAppareilRepo
): Response
{
$response = [
"error" => true,
"message" => "Erreur de la modification"
];
if (!is_null($commande)) {
if ($commande->isIsValide() == false || $commande->isIsValide() == null) {
$commande->setIsValide(true);
//Itcoin et send email
$factureService->editPatient($commande);
$raison = 'Profit Ictuspharma sur la commande du ' . date("d M Y") . ', Référence :/cmd {{' . $commande->getId() . '}}';
$ictocoinService->debiter($commande->getPharmacie(), $commande->getTotalCommande(), $raison);
$to = $commande->getUser()->getEmail();
$from = "siteweb@ictuspharma.com";
$subject = "VALIDATION COMMANDE";
$templateMail = 'emails/validationCommande.html.twig';
$paramsMail = [
'link' => "https://ictuspharm.com/commande/historique/non-payer",
'numeroCommande' => "ICT_CMD_" . $commande->getId(),
'pharmacy' => $commande->getPharmacie()->getDesignation()
];
$mailerServices->send($mi, $to, $from, $subject, $templateMail, $paramsMail);
//FIn
$response = [
"error" => false,
"message" => "La commande a été validée avec succès."
];
$notificationPatientService->pushNotification($commande, $mobileAppareilRepo, $subject);
} else {
$commande->setIsValide(false);
$response = [
"error" => false,
"message" => "Commande non valide"
];
$notificationPatientService->pushNotification($commande, $mobileAppareilRepo, "Commande non valide");
}
$this->em->flush();
}
return new JsonResponse($response);
}
/**
* @Route("livrer/{id}", name="livrer_cmd", methods={"GET"})
*/
public function validationLivraison(IctusCommande $commande): Response
{
$response = [
"error" => true,
"message" => "Erreur de la modification"
];
if (!is_null($commande)) {
if ($commande->isIsLivrer() == false || $commande->isIsLivrer() == null) {
$commande->setIsLivrer(true);
$response = [
"error" => false,
"message" => "La commande a été livrée avec succès."
];
} else {
$commande->setIsLivrer(false);
$response = [
"error" => false,
"message" => "Commande non livrée"
];
}
$this->em->flush();
}
return new JsonResponse($response);
}
/**
* @Route("etat-paiement", name="list_paiements", methods={"GET"})
*/
public function recupEtatPaiement(IctusEtatPaiementRepository $ictusEtatPaiementRepository): Response
{
$etats = $ictusEtatPaiementRepository->findAllAsc();
$dataEtats = [];
foreach ($etats as $etat) {
$dataEtats[] = [
'id' => $etat->getId(),
'designation' => $etat->getDesignation()
];
}
return $this->json($dataEtats);
}
/**
* @Route("type-paiement", name="list_type_paiements", methods={"GET"})
*/
public function recupTypePaiement(IctusTypePaiementRepository $ictusTypePaiementRepository): Response
{
$etats = $ictusTypePaiementRepository->findAllAsc();
$dataEtats = [];
foreach ($etats as $etat) {
$dataEtats[] = [
'id' => $etat->getId(),
'designation' => $etat->getDesignation()
];
}
return $this->json($dataEtats);
}
/**
* @Route("edit-paiement/{id}", name="edit_paiement_cmd", methods={"POST"})
*/
public function editEtatpaiement(IctusCommande $commande, Request $request, IctusEtatPaiementRepository $etatPaiementrepo, IctusTypePaiementRepository $tpRepo): Response
{
$response = [
"error" => true,
"message" => "Erreur de la modification"
];
if (!is_null($commande)) {
if ($request->get("etatpaiement") != null) {
$etatPaiement = $etatPaiementrepo->findOneById($request->get("etatpaiement"));
//Creation historique
$typePaiement = $tpRepo->findOneById($request->get('typepepaiement'));
$historique = new IctusHistoriquePaiement();
$historique->setMontant($request->get('montant'))->setCommande($commande);
if ($typePaiement instanceof IctusTypePaiement) {
$historique->setIctusTypePaiement($typePaiement);
}
$this->em->persist($historique);
//Fin creation historique
if (!is_null($etatPaiement)) {
$commande->setEtatpaiement($etatPaiement);
$response = [
"error" => false,
"message" => "Etat paiement a été modifiée avec succès."
];
} else {
$response = [
"error" => false,
"message" => "Etat paiement non trouvé"
];
}
$this->em->flush();
} else {
$response = [
"error" => false,
"message" => "Etat paiement null"
];
}
}
return new JsonResponse($response);
}
/**
* @Route("detail-qrCode/{code}/{codeSecret}/{idUser}", name="detail_qr_code", methods={"GET"})
*/
public function detailQrCode(IctusCommandeRepository $ictusCommandeRepository, UserRepository $userRepository, $code, $codeSecret, $idUser): Response
{
$user = $userRepository->findOneById($idUser);
$pharmacie = null;
if (!is_null($user)) {
$pharmacie = $user->getIctusPharmacie();
}
if (!is_null($pharmacie)) {
$pharmacie = $pharmacie->getId();
}
$commande = $ictusCommandeRepository->findOneBy([
'code' => $code,
'codeSecret' => $codeSecret,
'pharmacie' => $pharmacie
]);
$dataCmd_produit = [];
$dataCmd = [];
$patient = $commande->getUser();
$dataCmd_patient = [
'patientId' => $patient->getId(),
'nomComplet' => $patient->getNomComplet(),
'nomComplet' => $patient->getNomComplet(),
'telephone' => $patient->getPhone(),
'mail' => $patient->getEmail()
];
foreach ($commande->getIctusCommandeLines() as $line) {
$total = $line->getPrixunitaire() * $line->getQuantite();
$temp = [
'id' => $line->getId(),
'designation' => $line->getDesignation(),
'pu' => $line->getPrixunitaire(),
'quantite' => $line->getQuantite(),
'total' => $total
];
array_push($dataCmd_produit, $temp);
}
$dataCmd = [
'id' => $commande->getId(),
'reference' => "ICTCMD_MG_" . $commande->getPharmacie()->getId() . "_" . $commande->getReference(),
'date' => $commande->getCreatedAt()->format('d-m-Y'),
'paiement' => $commande->getTypePaiement()->getDesignation(),
'livraison' => $commande->getTypeLivraison()->getDesignation(),
'montant' => $commande->getTotalCommande(),
'totalProduit' => $commande->getTotalProduit(),
'isValid' => $commande->isIsValide(),
'isLivre' => $commande->isIsLivrer(),
'etatpaiement' => $commande->getEtatpaiement()->getId(),
'designationPaiement' => $commande->getEtatpaiement()->getDesignation(),
'typepepaiement' => $commande->getTypePaiement()->getId(),
'designationtypepaiement' => $commande->getTypePaiement()->getDesignation(),
'detailCmd' => $dataCmd_produit,
'patient' => $dataCmd_patient
];
return new JsonResponse($dataCmd);
}
/**
* @Route("edit-comandeproduit/{id}", methods={"POST"})
*/
public function editCommadeProduit(IctusCommandeLine $commandeLile, Request $request)
{
$response = [
"error" => true,
"message" => "Erreur de la modification"
];
if (!is_null($commandeLile)) {
if (!is_null($request->get('quantite'))) {
$commandeLile->setQuantite($request->get('quantite'));
}
if (!is_null($request->get('pu'))) {
$commandeLile->setPrixunitaire($request->get('pu'));
}
if (!is_null($request->get('isValid'))) {
if ($commandeLile->isIsValide() == false || $commandeLile->isIsValide() == null) {
$commandeLile->setIsValide(true);
} else {
$commandeLile->setIsValide(false);
}
}
$response = [
"error" => false,
"message" => "Modification avec succees"
];
$this->em->flush();
} else {
$response = [
"error" => false,
"message" => "Produit non trouvé"
];
}
return new JsonResponse($response);
}
/**
* @Route("envoie-notification-cmdnonvalid", methods={"GET"})
*/
public function sendNotificationCmdNonValide(IctusCommandeRepository $ictusCommandeRepository, NotificationService $notificationService, IctusMobileAppareilRepository $mobileAppareilRepo)
{
$response = [
"error" => true,
"message" => "Erreur de la modification"
];
$commandes = $ictusCommandeRepository->findAllNonValide();
if (!is_null($commandes)) {
//Envoie notification dans dans android Pcie
foreach ($commandes as $cmd) {
$user_pcie = $cmd->getPharmacie()->getUsers()[0];
$mobileAppareils = $mobileAppareilRepo->findAllToArray($user_pcie);
$array_cfm_token = array_unique((array_column($mobileAppareils, "cfm_tokem"))); //array_column trasform tableau associative en array simple
//$fcmToken = $user_pcie->getFcmToken();
if (count($array_cfm_token) > 0) {
$data = [
'id_commande' => intval($cmd->getId()),
'id_pharmacie' => intval($cmd->getPharmacie()->getId()),
'reference' => $cmd->getReference()
];
foreach ($array_cfm_token as $token) {
if ($token != "")
$notificationService->sendNotification($token, 'Commande pas encore validée', 'Référence commande ICTCMD_MG_' . intval($cmd->getPharmacie()->getId()) . '_' . $cmd->getReference(), $data);
}
}
}
//Fin envoie notification
$response = [
"error" => false,
"message" => "OKOK"
];
}
return new JsonResponse($response);
}
//*******************************************************
//************************COMPTE PATIENT******************
//* *****************************************************
/**
* @Route("detail-cmd-patient/{id}", name="detail_commade_patient", methods={"GET"})
*/
public function detailCommande(IctusCommande $commande): Response
{
$response = [
"error" => true,
"message" => "Erreur de la modification"
];
$allDataCommandes = [];
if ($commande) {
//COMMANDE
$dataCommande = [
'id' => $commande->getId(),
'reference' => "ICTCMD_MG_".$commande->getPharmacie()->getId()."_". $commande->getReference(),
'date_livraison' => $commande->getDateLivraison() ? $commande->getDateLivraison()->format("d-m-Y"):"null",
'date_creation' => $commande->getCreatedAt()->format('d-M-Y H:i'),
'etat_paiement' => $commande->getEtatpaiement()->getDesignation(),
'etat_commande' => $commande->isIsValide(),
'etat_livraison' => $commande->isIsRecuperer(),
'code_recuperation' => $commande->getCode().$commande->getCodeSecret(),
'some_total' => $commande->getTotalCommande(),
'total_produit' => $commande->getTotalProduit(),
'type_paiement' => $commande->getTypePaiement()->getDesignation()
];
//FIN
//PCIE
$pcie = $commande->getPharmacie();
$dataPcie = [];
if($pcie){
$dataPcie[] = [
'id' => $pcie->getId(),
'designation' => $pcie->getDesignation(),
'logo' => $pcie->getLogo(),
'adresse' => $pcie->getAdresse(),
'ville' => $pcie->getQuartier()->getVille()->getName(),
'quartier' => $pcie->getQuartier()->getName()
];
}
//FIN PCIE
//LIVRAISON
$livraison = $commande->getTypeLivraison();
$dataTypeLivraison = [];
if($livraison){
$dataTypeLivraison = [];
if($livraison){
$dataTypeLivraison[] = [
'id' => $livraison->getId(),
'designation' => $livraison->getDesignation()
];
}
}
//Fin livraison
//PAIEMENT
$paiement = $commande->getTypePaiement();
$dataPaiement = [];
if($paiement){
$dataPaiement = [];
if($paiement){
$dataPaiement[] = [
'id' => $paiement->getId(),
'designation' => $paiement->getDesignation()
];
}
}
//FIN
//Produit
$produits = $commande->getIctusCommandeLines();
$dataProduit = [];
if(count($produits) > 0){
foreach ($produits as $produit) {
$dataProduit[]= [
'stockid' => $produit->getId(),
'isOrdonnance' => $produit->getOrdonnance() ? true : false,
'nomproduit' => $produit->getDesignation(),
'prixunitforme' => $produit->getPrixunitaire(),
'quantity_panier' => $produit->getQuantite(),
'prixTotal' => $produit->getQuantite() * $produit->getPrixunitaire()
];
}
}
//Fin Produit
$allDataCommandes = [
'commande' => $dataCommande,
'pharmacie'=> $dataPcie,
'paiement' => $dataPaiement,
'livraison'=> $dataTypeLivraison,
'produit' => $dataProduit
];
$response = [
"success" => "Success",
"allDataCommandes" => $allDataCommandes
];
}
return new JsonResponse($response);
}
/**
* @Route("recuperee/{id}", name="recuperee", methods={"POST"})
*/
public function recupererCommande(IctusCommande $commande):Response
{
$response = [
"error" => true,
"message" => "Erreur de la modification"
];
if($commande){
$commande->setIsRecuperer(true);
$this->em->flush();
$response = [
"success" => "Success",
"message" => "Commande récupérée avec succès"
];
}
return new JsonResponse($response);
}
}