<?php
namespace App\Controller\GestionComerciale;
use App\Entity\Transporteurs\Transporteur;
use App\Entity\Adresses\Adresse;
use App\Entity\Articles\Article;
use App\Entity\Articles\ArticleComplementOption;
use App\Entity\GestionComerciale\Commande;
use App\Entity\GestionComerciale\ArticleCommande;
use App\Entity\GestionComerciale\StatutCommande;
use App\Form\GestionComerciale\CommandeType;
use App\Library\Uploader\Services\FileUploader;
use App\Security\Voter\EntityVoter;
use App\Service\GestionComerciale\EmailService;
use App\Service\GestionComerciale\PanierService;
use App\Service\Articles\ArticleService;
use App\Service\Taxes\TaxeService;
use App\Service\Utilisateur\ColonneTableauService;
use Doctrine\ORM\EntityManagerInterface;
use JMS\Serializer\SerializerBuilder;
use Knp\Component\Pager\PaginatorInterface;
use Knp\Snappy\Pdf;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use App\Model\GestionCommerciale\TypeDocumentCommercial;
/**
* @Route("/panier")
*/
class PanierController extends AbstractController
{
/**
* @Route("/ajouter/{id}", name="ajouter", methods={"POST"})
*/
public function ajouter( int $id,Request $request,EntityManagerInterface $em,PanierService $panierService,ArticleService $articleService): JsonResponse
{
$articleRepo = $em->getRepository(Article::class);
$commandeRepo = $em->getRepository(Commande::class);
$user = $this->getUser();
$article = $articleRepo->find($id);
if (!$articleRepo) {
return $this->json(['success' => false, 'message' => 'Produit inexistant']);
}
$data = json_decode($request->getContent(), true);
$quantite = isset($data['quantite']) && $data['quantite'] > 0 ? (int)$data['quantite'] : 1;
$statutPanier = $em->getRepository(StatutCommande::class)->findOneBy(["documentCommercial" => TypeDocumentCommercial::PANIER, "ordre" => "1"] );
// Récupérer ou créer le panier
$panier = $commandeRepo->findOneBy([
'statutCommande' => $statutPanier,
'utilisateur' => $user,
'typeDocumentCommercial' => TypeDocumentCommercial::PANIER
]);
if (!$panier) {
$panier = new Commande();
if($user) $panier->setClient($user->getClient());
$panier->setStatutCommande($statutPanier);
$panier->setUtilisateur($user);
$panier->setTypeDocumentCommercial(TypeDocumentCommercial::PANIER);
$panier->setTotal(0);
$panier->setAvecTaxe(0);
$panier->setTotalTvaFraisPort(0);
$panier->setTotalTva(0);
$panier->setTauxTvaFraisPort(0);
$panier->setTotalFraisPort(0);
$panier->setTotalTtc(0);
$panier->setTotalFraisPortTtc(0);
$panier->setTotalPoids(0);
$panier->setTotalHtAvecFraisPort(0);
$em->persist($panier);
}
$prixVente = $article->getPrixVente();
$prixRemise = $article->getPrixVente();
$remise = 0;
$remise_supplementaire = 0;
$lignePanier = "";
$articleCommande = $panier->getArticleCommande()->filter(fn($a) => $a->getArticle()->getId() === $article->getId())->first();
if ($articleCommande) {
if($user) {
$remise_calcule = $articleService->getRemisesPossibleArticleClient(['article'=>$article],$user->getClient());
if($remise_calcule["remiseId"]>0) {
$remise = $remise_calcule["valeur"];
$prixRemise = $remise_calcule["prixRemise"];
}
}
$articleCommande->setRemise($remise);
$articleCommande->setQuantite($articleCommande->getQuantite() + $quantite);
$articleCommande->setTotalTtcDevise($prixRemise*($articleCommande->getQuantite()));
$articleCommande->setTotalHt($prixRemise*($articleCommande->getQuantite()));
$articleCommande->setTotalWithTax($prixRemise*($articleCommande->getQuantite()));
$em->persist($articleCommande);
} else {
if($user) {
$remise_calcule = $articleService->getRemisesPossibleArticleClient(['article'=>$article],$user->getClient());
if($remise_calcule["remiseId"]>0) {
$remise = $remise_calcule["valeur"];
$prixRemise = $remise_calcule["prixRemise"];
}
}
$articleCommande = new ArticleCommande();
$articleCommande->setLibelle($article->getLibelle());
$articleCommande->setLibelleSecondaire($article->getLibelleSecondaire());
$articleCommande->setReference($article->getReference());
$articleCommande->setCommande($panier);
$articleCommande->setArticle($article);
$articleCommande->setLargeur($article->getLargeur());
$articleCommande->setProfondeur($article->getProfondeur());
$articleCommande->setHauteur($article->getHauteur());
$articleCommande->setPoids($article->getPoids());
$articleCommande->setQuantite($quantite);
$articleCommande->setPrixBase($prixVente);
$articleCommande->setPrixAvecRemise($prixRemise);
$articleCommande->setPrixUnitaireTtc($prixVente);
$articleCommande->setTvaVente(0);
$articleCommande->setTva(0);
$articleCommande->setRal($quantite);
$articleCommande->setRemise($remise);
$articleCommande->setRemiseSupplementaire($remise_supplementaire);
$articleCommande->setTotalTtcDevise($prixRemise*$quantite);
$articleCommande->setTotalHt($prixRemise*$quantite);
$articleCommande->setTotalWithTax($prixRemise*$quantite);
$em->persist($articleCommande);
$panier->addArticleCommande($articleCommande);
$em->flush();
$lignePanier = $this->renderView('GestionComerciale/Panier/ligne_panier_v2.html.twig', ["p"=>$articleCommande]);
}
$panierService->majPanier($panier);
$em->flush();
$topListeArticlePanier = $this->renderView('GestionComerciale/Panier/liste_article_panier_top.html.twig', []);
return $this->json([
'success' => true,
'articleCommandeId' => $articleCommande->getId(),
'totalArticles' => count($panier->getArticleCommande()),
'totalPrix' => $panier->getTotal(),
'topListeArticlePanier' => $topListeArticlePanier,
'lignePanier' => $lignePanier,
'totalPrixArticle' => $prixRemise * $articleCommande->getQuantite(),
'quantite' => $articleCommande->getQuantite(),
]);
}
/**
* @Route("/supprimer/{id}", name="dtc_panier_supprimer", methods={"POST"})
*/
public function supprimerArticle( int $id,EntityManagerInterface $em, Request $request,PanierService $panierService): JsonResponse
{
$commandeRepo = $em->getRepository(Commande::class);
$articleCommandeRepo = $em->getRepository(ArticleCommande::class);
$user = $this->getUser();
$statutPanier = $em->getRepository(StatutCommande::class)->findOneBy(["documentCommercial" => TypeDocumentCommercial::PANIER, "ordre" => "1"] );
$panier = $commandeRepo->findOneBy([
'statutCommande' => $statutPanier,
'utilisateur' => $user,
'typeDocumentCommercial' => TypeDocumentCommercial::PANIER
]);
if (!$panier) {
return $this->json(['success' => false, 'message' => 'Panier introuvable']);
}
$articleCommande = $articleCommandeRepo->find($id);
if (!$articleCommande) {
return $this->json(['success' => false, 'message' => 'Article introuvable dans le panier']);
}
$em->remove($articleCommande);
$em->flush();
$panierService->majPanier($panier);
$panierDissocie = $panierService->dissocierPanierStock($panier);
$totalEnStock = 0;
if(count($panierDissocie["stock"]->getArticleCommande())>0) {
foreach($panierDissocie["stock"]->getArticleCommande() as $ac) {
$totalEnStock += $ac->getQuantite();
}
}
$totalArticles = 0;
if(count($panier->getArticleCommande())>0) {
foreach($panier->getArticleCommande() as $ac) {
$totalArticles += $ac->getQuantite();
}
}
return $this->json([
'success' => true,
'totalArticles' => $totalArticles,
'totalPrix' => $panier->getTotal(),
'totalPoids' => $panier->getTotalPoids(),
'totalEnStock' => $totalEnStock,
]);
}
/**
* @Route("/modifier-quantite/{id}", name="dtc_panier_modifier_quantite", methods={"POST"})
*/
public function modifierQuantite(int $id, Request $request, EntityManagerInterface $em,PanierService $panierService,ArticleService $articleService): JsonResponse
{
$commandeRepo = $em->getRepository(Commande::class);
$articleCommandeRepo = $em->getRepository(ArticleCommande::class);
$user = $this->getUser();
$statutPanier = $em->getRepository(StatutCommande::class)->findOneBy(["documentCommercial" => TypeDocumentCommercial::PANIER, "ordre" => "1"] );
$panier = $commandeRepo->findOneBy([
'statutCommande' => $statutPanier,
'utilisateur' => $user,
'typeDocumentCommercial' => TypeDocumentCommercial::PANIER
]);
if (!$panier) {
return $this->json(['success' => false, 'message' => 'Panier introuvable']);
}
$articleCommande = $panier->getArticleCommande()->filter(fn($a) => $a->getId() === $id)->first();
if (!$articleCommande) {
return $this->json(['success' => false, 'message' => 'Article introuvable dans le panier']);
}
$data = json_decode($request->getContent(), true);
$quantite = isset($data['quantite']) && $data['quantite'] > 0 ? (int)$data['quantite'] : 1;
$prixVente = $articleCommande->getArticle()->getPrixVente();
$prixRemise = $articleCommande->getArticle()->getPrixVente();
$remise = 0;
$articleCommande->setQuantite($quantite);
$remise_calcule = $articleService->getRemisesPossibleArticleClient(['article'=>$articleCommande->getArticle()],$user->getClient());
if($remise_calcule["remiseId"]>0) {
$remise = $remise_calcule["valeur"];
$prixRemise = $remise_calcule["prixRemise"];
}
$articleCommande->setRemise($remise);
$articleCommande->setTotalTtcDevise($prixRemise*($articleCommande->getQuantite()));
$articleCommande->setTotalHt($prixRemise*($articleCommande->getQuantite()));
$articleCommande->setTotalWithTax($prixRemise*($articleCommande->getQuantite()));
$em->persist($articleCommande);
$panierService->majPanier($panier);
$panierDissocie = $panierService->dissocierPanierStock($panier);
$totalEnStock = 0;
if(count($panierDissocie["stock"]->getArticleCommande())>0) {
foreach($panierDissocie["stock"]->getArticleCommande() as $ac) {
$totalEnStock += $ac->getQuantite();
}
}
$totalArticles = 0;
if(count($panier->getArticleCommande())>0) {
foreach($panier->getArticleCommande() as $ac) {
$totalArticles += $ac->getQuantite();
}
}
//$articleCommande
$lignePanier = $this->renderView('GestionComerciale/Panier/ligne_panier_v2.html.twig', ["p"=>$articleCommande]);
return $this->json([
'ligne' => $lignePanier,
'success' => true,
'totalArticles' => $totalArticles,
'totalPrix' => $panier->getTotal(),
'totalPrixArticle' => $prixRemise * $articleCommande->getQuantite(),
'articlePrix' => $articleCommande->getPrixBase() * $articleCommande->getQuantite(),
'totalPoids' => $panier->getTotalPoids(),
'totalEnStock' => $totalEnStock,
]);
}
/**
* @Route("/", name="dtc_panier_afficher")
*/
public function listerAction(Request $request, EntityManagerInterface $em, TranslatorInterface $translator,PanierService $panierService)
{
$user = $this->getUser();
if(!$user or !$user->getClient()) return $this->redirectToRoute('dtc_infos_manquantes');
$param = [];
$cat_produit_home = $this->getParameter('cat_produit_home');
$commandeRepo = $em->getRepository(Commande::class);
$user = $this->getUser();
$statutPanier = $em->getRepository(StatutCommande::class)->findOneBy(["documentCommercial" => TypeDocumentCommercial::PANIER, "ordre" => "1"] );
$panier = $commandeRepo->findOneBy([
'statutCommande' => $statutPanier,
'utilisateur' => $user,
'typeDocumentCommercial' => TypeDocumentCommercial::PANIER
]);
if (!$panier) {
$panier = new Commande();
$panier->setClient($user->getClient());
$panier->setStatutCommande($statutPanier);
$panier->setUtilisateur($user);
$panier->setTypeDocumentCommercial(TypeDocumentCommercial::PANIER);
$panier->setTotal(0);
$panier->setAvecTaxe(0);
$panier->setTotalTvaFraisPort(0);
$panier->setTotalTva(0);
$panier->setTauxTvaFraisPort(0);
$panier->setTotalFraisPort(0);
$panier->setTotalTtc(0);
$panier->setTotalFraisPortTtc(0);
$panier->setTotalPoids(0);
$panier->setTotalHtAvecFraisPort(0);
$em->persist($panier);
$em->flush();
}
if ($panier->getArticleCommande()->isEmpty()) {
$this->addFlash('warning', 'Votre panier est vide.');
}
$panierDissocie = $panierService->dissocierPanierStock($panier);
return $this->render(
'GestionComerciale/Panier/afficher.html.twig',
[
'parametres'=> $param,
'panierDissocie' => $panierDissocie,
"cat_produit_home" => $cat_produit_home,
]
);
}
/**
* @Route("/tva/calcul/", name="dtc_panier_calcul_tva")
*/
public function tvaCalculAction(Request $request, EntityManagerInterface $em, TranslatorInterface $translator,ArticleService $articleService,PanierService $panierService)
{
$totaux=[];
$commandeRepo = $em->getRepository(Commande::class);
$transporteurRepo = $em->getRepository(Transporteur::class);
$user = $this->getUser();
$statutPanier = $em->getRepository(StatutCommande::class)->findOneBy(["documentCommercial" => TypeDocumentCommercial::PANIER, "ordre" => "1"] );
$panier = $commandeRepo->findOneBy([
'statutCommande' => $statutPanier,
'utilisateur' => $user,
'typeDocumentCommercial' => TypeDocumentCommercial::PANIER
]);
if (!$user->getClient()) {
return new JsonResponse(['message' => "client introuvable"]);
}
else if (!$panier) {
return new JsonResponse(['message' => "panier introuvable"]);
}
else {
$data = json_decode($request->getContent(), true);
if(empty($data["id_adresse"])) {
return new JsonResponse(['message' => "adresse introuvable"]);
}
else {
$transporteur_obj = $transporteurRepo->find($data["id_transporteur"]);
$panier->setTransporteur($transporteur_obj);
$rep_adresse = $em->getRepository(Adresse::class);
$adresseFacturation = NULL;
$adresseLivraison = NULL;
if(is_object($user->getClient())) $adresseFacturation = $rep_adresse->findOneBy(["client" =>$user->getClient(), "facturationDefaut" => "1"] );
$adresseLivraison = $rep_adresse->find($data["id_adresse"]);
$panier->setAdresseLivraison($adresseLivraison);
$totalTva = 0;
foreach($panier->getArticleCommande() as $ac) {
$articleService->getTva2($ac);
$taxeDefautObj = $articleService->getTaxeClientAdresses($ac->getArticle()->getRegleTaxe(), $user->getClient(), $adresseLivraison, $adresseFacturation);
if($taxeDefautObj) {
$ac->setTaxe($taxeDefautObj);
$ac->setTva($taxeDefautObj->getTaux());
$tvaVente = ($ac->getPrixAvecRemise()*$ac->getQuantite())*$taxeDefautObj->getTaux()/100;
$ac->setTvaVente($tvaVente);
$ac->setTotalTtcDevise($ac->getTotalHt()+$tvaVente);
$ac->setTotalWithTax($ac->getTotalHt()+$tvaVente);
$ac->setPrixUnitaireTtc($ac->getPrixAvecRemise()+($ac->getPrixAvecRemise()*$taxeDefautObj->getTaux()/100));
$em->persist($ac);
}
}
$panierService->majPanier($panier);
$totaux["total"]=$panier->getTotal();
$totaux["totalTva"]=$panier->getTotalTva();
$totaux["totalFraisPort"]=$panier->getTotalFraisPort();
$totaux["totalTvaFraisPort"]=$panier->getTotalTvaFraisPort();
$totaux["totalTtc"]=$panier->getTotalTtc();
}
return new JsonResponse(['id_transporteur' => $data["id_transporteur"],'totaux'=>$totaux]);
}
}
}