<?php
namespace App\Controller\GestionComerciale;
use App\Entity\Articles\Article;
use App\Entity\GestionComerciale\ArticleCommande;
use App\Entity\GestionComerciale\Commande;
use App\Entity\GestionComerciale\StatutCommande;
use App\Model\GestionCommerciale\TypeDocumentCommercial;
use App\Form\GestionComerciale\CommandeType;
use App\Library\Datatable\Util\Datatable;
use App\Library\Uploader\Services\FileUploader;
use App\Security\Voter\EntityVoter;
use App\Service\Articles\ArticleService;
use App\Service\GestionComerciale\EmailService;
use App\Service\GestionComerciale\PanierService;
use App\Service\GestionComerciale\CommandeService;
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\Form\Devis\DevisVersPanierType;
class DevisController extends AbstractController
{
/**
* @Route("/compte/devis", name="dtc_devis_liste")
*/
public function listerAction(Request $request, EntityManagerInterface $em,CommandeService $commandeService, Datatable $datatable, TranslatorInterface $translator, ColonneTableauService $serviceColonneTableau)
{
$user = $this->getUser();
//if(is_object($user->getClient())) $commandeService->importDocumentsErp($user->getClient()->getId(),["devis"],["log"=>false]);
$tableau_class_cellule = array();
$tableau_class_cellule[] = ["className" => "visible_export colonne_id text-center", "targets" => [0], "visible" => false, "orderable" => true];
$tableau_class_cellule[] = ["className" => "visible_export colonne_id text-center", "targets" => [1],"title"=>'<i style="font-size:1.5em;" class="fa fa-clipboard">', "visible" => true, "orderable" => false];
$tableau_class_cellule[] = ["className" => "visible_export colonne_id text-left", "targets" => [2], "visible" => true, "orderable" => false];
$tableau_class_cellule[] = ["className" => "visible_export colonne_id text-right", "targets" => [3],"title"=>'<i style="font-size:1.5em;" class="fa fa-calendar"> <b>/</b> <i style="" class="fa fa-euro"> ', "visible" => true, "orderable" => false];
$tableau_class_cellule[] = ["className" => "visible_export colonne_id text-center", "targets" => [4],"title"=>'<i style="font-size:1.5em;" class="fa fa-gear">', "visible" => true, "orderable" => false];
// $this->commandeService->importDocumentsErp($client_tab["id"],["devis"]);
$response = new Response();
$this->datatable($request, $em, $datatable, $translator, $response);
$param = $request->query->all();
return $this->render('GestionComerciale/Devis/lister.html.twig',
[
'tableauClassColonne' => $tableau_class_cellule,
'parametres'=> $param,
]
,$response);
}
/**
* set datatable configs
*
* @return \App\Library\Datatable\Util\Datatable
*/
private function datatable(Request $request, EntityManagerInterface $em, Datatable $datatable, TranslatorInterface $translator)
{
$user = $this->getUser();
$param = $request->query->all();
$datatable
->setDatatableId('liste_commande')
->setEntity(Commande::class, "x")
->setFields(
[
$translator->trans("ID") => 'x.id',
'date' => 'x.date',
$translator->trans("RÉFÉRENCE") => 'x.reference',
$translator->trans("Total HT") => 'x.total',
$translator->trans("Actions") => 'x.id',
"_identifier_" => 'x.id',
]
)
//->addJoin('x.transporteur', 't', \Doctrine\ORM\Query\Expr\Join::LEFT_JOIN)
->addJoin('x.utilisateur', 'u', \Doctrine\ORM\Query\Expr\Join::LEFT_JOIN)
->setRenderers(
[
1 => [
'view' => 'FO/DataTable/type_document_vente.html.twig',
],
2 => [
'view' => 'FO/DataTable/reference_document_commercail.html.twig',
],
/*
2 => [
'view' => 'FO/DataTable/avec_lien_edit_route.html.twig',
'params' => [
'edit_route' => 'dtc_commande_liste',
],
],
*/
3 => [
'view' => 'FO/DataTable/prix_commande_heure.html.twig',
],
4 => [
'view' => 'FO/DataTable/actions.html.twig',
'params' => [
'edit_route' => 'dtc_devis_liste',
'objet' => Commande::class,
'deplier' => false,
'table' => "liste_commande",
],
],
]
)
->setMultiple([])
->setOrder("x.date", "desc")
->setSearch(true)
->setSearchFields([]);
$client_id = 10000000000000;
if($user->getClient()) $client_id = $user->getClient()->getId();
$where = "x.typeDocumentCommercial = :typeDocumentCommercial and x.client = :client and x.visible = :visible";
$parameters = ['typeDocumentCommercial' => TypeDocumentCommercial::DEVIS,'client'=>$client_id,'visible'=>1];
if (array_key_exists('parametres', $param)) {
$response = new Response();
if (array_key_exists('client', $param["parametres"]) and $param["parametres"]["client"] > 0) {
//$datatable->addJoin('x.client', 'client', \Doctrine\ORM\Query\Expr\Join::LEFT_JOIN);
$parameters["client"] = $param["parametres"]["client"];
if ($where != "") {
$where .= " AND ";
}
$where .= "c.id = :client";
}
if (array_key_exists('date_debut', $param["parametres"]) and $param["parametres"]["date_debut"] != "") {
$param["parametres"]["date_debut"] = \DateTime::createFromFormat('d/m/Y', $param["parametres"]["date_debut"]);
$param["parametres"]["date_debut"]->setTime(00, 00, 00);
$parameters["date_debut"] = $param["parametres"]["date_debut"];
if ($where != "") {
$where .= " AND ";
}
$where .= "x.date >= :date_debut";
}
if (array_key_exists('transporteur', $param["parametres"]) and $param["parametres"]["transporteur"] > 0) {
//$datatable->addJoin('x.client', 'client', \Doctrine\ORM\Query\Expr\Join::LEFT_JOIN);
$parameters["transporteur"] = $param["parametres"]["transporteur"];
if ($where != "") {
$where .= " AND ";
}
$where .= "t.id = :transporteur";
}
if (array_key_exists('date_fin', $param["parametres"]) and $param["parametres"]["date_fin"] != "") {
$param["parametres"]["date_fin"] = \DateTime::createFromFormat('d/m/Y', $param["parametres"]["date_fin"]);
$param["parametres"]["date_fin"]->setTime(23, 59, 59);
$parameters["date_fin"] = $param["parametres"]["date_fin"];
if ($where != "") {
$where .= " AND ";
}
$where .= "x.date <= :date_fin";
}
}
if ($where != '') {
$datatable->setWhere($where, $parameters);
$qb = $datatable->getQueryBuilder()->getDoctrineQueryBuilder();
}
return $datatable;
}
/**
* @Route("/compte/devis/grid", name="dtc_devis_liste_grid")
*/
public function gridAction(Request $request, EntityManagerInterface $em, Datatable $datatable, TranslatorInterface $translator)
{
return $this->datatable($request, $em, $datatable, $translator)->execute();
}
/**
* @Route("/compte/devis/transformer/{id}", name="dtc_devis_transformer_panier", requirements={"id"="\d+"})
*/
public function tranformerEnPanierAction(Request $request,Commande $devis, EntityManagerInterface $em,PanierService $panierService,ArticleService $articleService)
{
$action = $request->query->get('action');
$titre_modal = "Passer votre devis en commande";
if($action=="editer") $titre_modal = "Éditer votre devis";
if($action=="dupliquer") $titre_modal = "Commander à nouveau";
$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]);
$errors = [];
$form = $this->createForm(DevisVersPanierType::class);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if($form->isValid()) {
$articleRepo = $em->getRepository(Article::class);
$data = $form->getData();
$actionPanier = $data['action_panier'];
// Votre logique métier ici
if ($actionPanier === 'vider') {
$panierService->viderPanier($user);
}
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);
}
$panier->setReferenceClient($devis->getReferenceClient());
foreach($devis->getArticleCommande() as $ac)
{
$article = $ac->getArticle();
$quantite = $ac->getQuantite();
$prixVente = $article->getPrixVente();
$prixRemise = $article->getPrixVente();
$remise = 0;
$remise_supplementaire = 0;
$articleCommande = $panier->getArticleCommande()->filter(fn($a) => $a->getArticle()->getId() === $article->getId())->first();
if ($articleCommande) {
$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
{
$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();
}
}
$panierService->majPanier($panier);
$em->flush();
$url = $this->generateUrl('dtc_checkout_v2',['cible'=>'commande']);
if($action=="editer") $url = $this->generateUrl('dtc_checkout_v2',['cible'=>'devis']);
return new Response(json_encode(['rendu' => '', 'valide' => '1', 'url' => $url, 'type' => '']),200,['Content-Type' => 'application/json']);
}
else {
foreach ($form->getErrors(true) as $error) {
$fieldName = $error->getOrigin() ? $error->getOrigin()->getName() : 'form';
$errors[] = [
'field' => $fieldName,
'message' => $error->getMessage()
];
}
}
}
$rendu = $this->renderView('GestionComerciale/Devis/devis_vers_panier_modal.html.twig',['form' => $form->createView(),'errors' => $errors,'panier'=>$panier,'devis'=>$devis,'action'=>$action]);
return new JsonResponse(['rendu' => $rendu, 'valide' => '0', 'url' => '', 'titre' => $titre_modal]);
}
}