src/Controller/AccueilController.php line 330

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Response; 
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\Routing\Annotation\Route;
  8. use Doctrine\Persistence\ManagerRegistry; 
  9. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  10. use Doctrine\DBAL\Connection;
  11. use App\Entity\Commande;  
  12. use App\Entity\User;  
  13. use App\Entity\Client; 
  14. use App\Entity\Commercial; 
  15. use App\Entity\Bordereau; 
  16. use App\Entity\Parametrage;   
  17. use App\Entity\Fournisseur; 
  18. use App\Entity\Lignecommande; 
  19. use App\Entity\Lignetypecommande; 
  20. use App\Entity\Livraison; 
  21. use App\Entity\Produit;   
  22. use App\Entity\Magasin;
  23. use App\Entity\ArriereClient;
  24. use App\EventSubscriber\LocaleSubscriber;
  25. use App\Service\LandingRouteResolver;
  26. use App\Service\LogActionService;
  27. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  28. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  29. use App\Security\TokenAuthenticator; 
  30. use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;  
  31. class AccueilController extends AbstractController
  32. {
  33.     
  34.     
  35.     private $connection;
  36.     private $session;
  37.     private $idproduit;
  38.     private $nomproduit;
  39.     private $produit;
  40.     public function __construct(ManagerRegistry $doctrine,Connection $connection,SessionInterface $session)
  41.     {
  42.         $em =  $doctrine->getManager();
  43.         $this->connection = $connection;
  44.         $this->session = $session;
  45.         if($this->session->get('getsessionproduit')=="" || $this->session->get('getsessionproduit')==null){
  46.                 
  47.             $arrays = array();
  48.             $arrays['datesuppressionproduit'] = null;
  49.             
  50.             $oneprod = $em->getRepository(Produit::class)->findOneBy($arrays);
  51.             if($oneprod!=null){
  52.                 $this->session->set('getsessionproduit',$oneprod->getId());
  53.                 $this->session->set('getsessionnomproduit',$oneprod->getNomproduit());
  54.             }
  55.         }
  56.         $this->idproduit = $this->session->get('getsessionproduit');
  57.         $this->nomproduit = $this->session->get('getsessionnomproduit');
  58.         $this->produit = $em->getRepository(Produit::class)->findOneBy(['id'=>$this->session->get('getsessionproduit')]);
  59.     }
  60.     
  61.     
  62.     public $keypass = "@Dmin1494";
  63.     
  64.     /**
  65.      * @Route("/sidebar", name="sidebar")
  66.      */
  67.     public function sidebar(ManagerRegistry $doctrine,Request $request): Response
  68.     {
  69.      
  70.         $em = $this->getDoctrine()->getManager();
  71.         $conn  =  $this->connection; 
  72.             
  73.         $parametrage = $em->getRepository(Parametrage::class)->findOneBy([], ['id' => 'ASC']); 
  74.         if($parametrage==null){
  75.             $parametrage = new Parametrage();
  76.             $em->persist($parametrage);
  77.             $em->flush();
  78.         }
  79.              
  80.  
  81.         $commande = $em->getRepository(Commande::class)->findOneBy(['produitid'=>$this->idproduit,'id'=>0,'produitid'=>$this->idproduit]);
  82.       
  83.                         
  84.         $commandes = $conn->fetchAllAssociative("
  85.         SELECT COUNT(*) AS nombre, m.nommagasin , m.id
  86.         FROM stockboutique sb , typeciment tc , magasin m
  87.         WHERE sb.typecimentid = tc.id AND tc.datesuppressiontypeciment IS NULL
  88.         AND m.id = sb.magasinid 
  89.         AND sb.qtestock < tc.qteinitiale
  90.         AND tc.produitid = $this->idproduit
  91.         GROUP BY m.id ORDER BY nombre DESC");
  92.         return $this->render('partials/rsidehead.html.twig',[
  93.             'COMMANDE'=>$commande,
  94.             'NOTIFICATIONS'=>$commandes,
  95.             'PARAMETRAGE'=>$parametrage,
  96.             'BORDEREAUX'=>[],
  97.             'PRODUITS'=>[],
  98.             'CT'=>[],
  99.             'CJ'=>[],
  100.             ]);
  101.     
  102.     }     
  103.     
  104.     
  105.     
  106.   /**
  107.      * @Route("/sidebarmagasin", name="sidebarmagasin")
  108.      */
  109.     public function sidebarmagasin(ManagerRegistry $doctrine,Request $request): Response
  110.     {
  111.      
  112.         $user = $this->getUser(); 
  113.         $em = $this->getDoctrine()->getManager();
  114.         $conn  =  $this->connection; 
  115.             
  116.         $parametrage = $em->getRepository(Parametrage::class)->findOneBy([], ['id' => 'ASC']); 
  117.         if($parametrage==null){
  118.             $parametrage = new Parametrage();
  119.             $em->persist($parametrage);
  120.             $em->flush();
  121.         }
  122.              
  123.  
  124.         $commande = $em->getRepository(Commande::class)->findOneBy(['produitid'=>$this->idproduit,'id'=>0,'produitid'=>$this->idproduit]);
  125.       
  126.         $arrays = array();
  127.         $arrays['datesuppressionproduit'] = null;
  128.         if(!$this->isGranted('ROLE_SUPER_ADMIN')){
  129.             $arrays['id'] = $user->getProduitslist()??[];
  130.         }
  131.         
  132.         $produits = $em->getRepository(Produit::class)->findBy($arrays); 
  133.       
  134.         $defaut = 0;
  135.         if(sizeof($produits)>0){
  136.             $defaut = $produits[0]->getId(); 
  137.         }
  138.                         
  139.         $commandes = $conn->fetchAllAssociative("
  140.         SELECT COUNT(*) AS nombre, m.nommagasin , m.id
  141.         FROM stockboutique sb , typeciment tc , magasin m
  142.         WHERE sb.typecimentid = tc.id AND tc.datesuppressiontypeciment IS NULL
  143.         AND m.id = sb.magasinid 
  144.         AND sb.qtestock < tc.qteinitiale
  145.         AND tc.produitid = $this->idproduit
  146.         GROUP BY m.id ORDER BY nombre DESC");
  147.         return $this->render('partials/rsideheadmagasin.html.twig',[
  148.             'PRODUITES'=>$produits,
  149.             'COMMANDE'=>$commande,
  150.             'NOTIFICATIONS'=>$commandes,
  151.             'PARAMETRAGE'=>$parametrage,
  152.             'BORDEREAUX'=>[],
  153.             'PRODUITS'=>[],
  154.             'CT'=>[],
  155.             'CJ'=>[],
  156.             ]);
  157.     
  158.     }
  159.     
  160.     
  161.     
  162.     /**
  163.      * @Route("/side", name="side")
  164.      */
  165.     public function side(SessionInterface $sessions,ManagerRegistry $doctrine,Request $request): Response
  166.     {
  167.      
  168.         $user = $this->getUser();
  169.         $em =  $doctrine->getManager();
  170.         $parametres = $this->container;
  171.         $conn  =  $this->connection;
  172.         $modification = true;
  173.         $message = "";
  174.         $statut = 0; 
  175.         $color = "red";   
  176.         if((sizeof($user->getProduitslist()??[])==1)){
  177.             
  178.             $arrays = array();
  179.             $arrays['datesuppressionproduit'] = null;
  180.             if(!$this->isGranted('ROLE_SUPER_ADMIN')){
  181.                 $arrays['id'] = $user->getProduitslist()??[];
  182.             }
  183.             $produits = $em->getRepository(Produit::class)->findOneBy($arrays);  
  184.             $defaut = 1;
  185.             $defautname = "Ciment";
  186.             if($produits!=null){
  187.                 $defaut = $produits->getId(); 
  188.                 $defautname = $produits->getNomproduit(); 
  189.             }  
  190.             $sessions->set('getsessionproduit',$defaut);
  191.             $sessions->set('getsessionnomproduit',$defautname);  
  192.         }
  193.          
  194.             
  195.         $parametrage = $em->getRepository(Parametrage::class)->findOneBy([], ['id' => 'ASC']); 
  196.         if($parametrage==null){
  197.             $parametrage = new Parametrage();
  198.             $em->persist($parametrage);
  199.             $em->flush();
  200.         }
  201.  
  202.         
  203.          
  204.         $commande = $em->getRepository(Commande::class)->findOneBy(['produitid'=>$this->idproduit,'id'=>0]);
  205.  
  206.         //$bordereau = $em->getRepository(Bordereau::class)->findBy(['produitid'=>$this->idproduit,'datesuppressionbordereau'=>null],['datebordereau'=>'DESC'],200);
  207.         
  208.         
  209.         $lastcommande = $em->getRepository(Commande::class)->findOneBy(['produitid'=>$this->idproduit,],['numcommande'=>'DESC']);
  210.         
  211.         $lastcomm = 1 ;
  212.         
  213.         if($lastcommande!=null){
  214.             $lastcomm = $lastcommande->getNumcommande()+1;
  215.         }
  216.         
  217.         $formatted_num = sprintf('%03d', $lastcomm);
  218.         
  219.         if($commande==null){
  220.             $commande = new Commande();
  221.         }
  222.         $arrays = array();
  223.         $arrays['datesuppressionproduit'] = null;
  224.         if(!$this->isGranted('ROLE_SUPER_ADMIN')){
  225.             $arrays['id'] = $user->getProduitslist()??[];
  226.         }
  227.         
  228.         $produits = $em->getRepository(Produit::class)->findBy($arrays); 
  229.       
  230.         $defaut = 0;
  231.         if(sizeof($produits)>0){
  232.             $defaut = $produits[0]->getId(); 
  233.         }
  234.         $session = $sessions->get('getsessionproduit')??$defaut; 
  235.                 
  236.         // Le menu latéral se rend sur CHAQUE page : un COUNT suffit pour le
  237.         // badge — l'ancien SELECT * ramenait toutes les colonnes de tout
  238.         // l'historique des commandes à chaque affichage.
  239.         $nbCommandesEnCours = (int) $conn->fetchOne("SELECT COUNT(*)
  240.         FROM commande c, bordereau b
  241.         where c.datesuppressioncommande is null AND c.produitid = $this->idproduit AND c.bordereauid = b.id
  242.         AND
  243.         IFNULL((SELECT SUM(l.quantite) FROM lignetypecommande l where l.commandeid = c.id AND l.datesuppressionlignetypecommande is NULL),0)>
  244.         IFNULL((SELECT SUM(l.tonne) FROM livraison l where l.commandeid = c.id AND l.datesuppressionlivraison is NULL AND l.vehiculeid IS NOT NULL),0)");
  245.             // Créer un QueryBuilder pour Bordereau
  246.             $qb = $em->createQueryBuilder();
  247.             // Construire la requête
  248.             $qb->select('b')
  249.                 ->from(Bordereau::class, 'b')
  250.                 ->where('b.produitid = :idProduit')
  251.                 ->andWhere('b.datesuppressionbordereau IS NULL')
  252.                 ->andWhere($qb->expr()->notIn(
  253.                     'b.id',
  254.                     $em->createQueryBuilder()
  255.                         ->select('IDENTITY(c.bordereauid)')
  256.                         ->from(Commande::class, 'c')
  257.                         ->where('c.datesuppressioncommande IS NULL')
  258.                         ->getDQL()
  259.                 ))
  260.                 ->orderBy('b.datebordereau', 'DESC')
  261.                 ->setMaxResults(200)
  262.                 ->setParameter('idProduit', $this->idproduit);
  263.             // Exécuter la requête
  264.             $bordereau =  $qb->getQuery()->getResult();
  265.         
  266.         return $this->render('partials/side.html.twig',[
  267.             'SESSIONS'=>$session,
  268.             'PRODUITES'=>$produits,
  269.             'PARAMETRAGE'=>$parametrage,
  270.             'COMMANDE'=>$commande,
  271.             'BORDEREAUX'=>$bordereau,
  272.             'lastcommande'=>$formatted_num,
  273.             'COMMS'=>$nbCommandesEnCours,
  274.             'CT'=>[],
  275.             'CJ'=>[],
  276.             ]);
  277.     
  278.     }     
  279.   
  280.     
  281.     /**
  282.      * @Route("/", name="home")
  283.      */
  284.     public function index(Request $request, LandingRouteResolver $landingResolver): Response
  285.     {
  286.         // Chaque profil atterrit sur le premier écran que ses droits autorisent
  287.         // (un commercial terrain n'a pas « voir-tableaudebord »).
  288.         return $this->redirectToRoute($landingResolver->resolve($this->getUser()));
  289.     }
  290.     /**
  291.      * @Route("/admin", name="homer")
  292.      */
  293.     public function indexer(Request $request, LandingRouteResolver $landingResolver): Response
  294.     {
  295.         return $this->redirectToRoute($landingResolver->resolve($this->getUser()));
  296.     }
  297.          
  298.     /**
  299.      * @Route("/404", name="404")
  300.      */
  301.     public function erreur(Request $request): Response
  302.     {
  303.         $ajaxs = false;
  304.         $em = $this->getDoctrine()->getManager();
  305.  
  306.       
  307.         return $this->render('accueil/404.html.twig');
  308.     
  309.     }
  310.     
  311.               
  312.     /**
  313.      * @Route("/setsession", name="setsession")
  314.      */
  315.     public function setsession(SessionInterface $sessions,Request $request): Response
  316.     {
  317.      
  318.         $em = $this->getDoctrine()->getManager(); 
  319.         $produits = $em->getRepository(Produit::class)->findOneBy(['datesuppressionproduit'=>null,'id'=>$request->get('setsession')]);
  320.         // Périmètre produit du compte (audit 02/09/2026) : la session ne
  321.         // porte jamais un type de produit hors produitslist — c'est elle
  322.         // qui borne les écrans commande. Hors périmètre : on retombe sur
  323.         // le premier type autorisé du compte.
  324.         $utilisateur = $this->getUser();
  325.         if ($produits !== null && $utilisateur !== null && !$this->isGranted('ROLE_SUPER_ADMIN')) {
  326.             $autorises = array_values(array_filter(array_map('intval', $utilisateur->getProduitslist() ?? [])));
  327.             if ($autorises !== [] && !in_array((int) $produits->getId(), $autorises, true)) {
  328.                 $produits = $em->getRepository(Produit::class)->findOneBy([
  329.                     'datesuppressionproduit' => null,
  330.                     'id'                     => $autorises[0],
  331.                 ]);
  332.             }
  333.         }
  334.         $defaut = 1;
  335.         $defautname = "Ciment";
  336.         if($produits!=null){
  337.             $defaut = $produits->getId();
  338.             $defautname = $produits->getNomproduit();
  339.         }
  340.         $sessions->set('getsessionproduit',$defaut);
  341.         $sessions->set('getsessionnomproduit',$defautname); 
  342.         
  343.         return new JsonResponse(['OK']); 
  344.     }
  345.     
  346.      
  347.     /**
  348.      * @Route("/admin/rapportsolde", name="rapportsolde")
  349.      */
  350.     public function rapportsolde(ManagerRegistry $doctrine,SessionInterface $sessions,Connection $conn,Request $request,LogActionService $logger): Response
  351.     {
  352.         $u = $this->getUser();
  353.         $logger->createLog(
  354.             'rapport_consultation',
  355.             "Consultation du rapport « solde »",
  356.             $u ? $u->getId() : null,
  357.             null,
  358.             null,
  359.             ['old' => null, 'new' => ['rapport' => 'solde', 'filtres' => $request->query->all()]]
  360.         );
  361.         return new JsonResponse(['html'=>$this->rapportventetotalmagasin( $doctrine, $request)]);
  362.     }
  363.     
  364.     
  365.  
  366.     public function rapportventetotalmagasin(ManagerRegistry $doctrine,Request $request)
  367.     { 
  368.         $user = $this->getUser();
  369.         $em =  $doctrine->getManager();
  370.         $parametres = $this->container;
  371.         $conn  =  $this->connection;
  372.         $modification = true;
  373.         $message = "";
  374.         $statut = 0; 
  375.         $color = "red";    
  376.          
  377.         $datedebut = $request->get('datedebut');
  378.         $datefin   = $request->get('datefin')." 23:59:59";
  379.         
  380.         if(strlen($datedebut)<8){
  381.             
  382.             $timestampDebutLundi = strtotime('monday this week');
  383.             $datedebut = date('Y-m-d', $timestampDebutLundi);
  384.             $datefin = date('Y-m-d 23:59:59');
  385.         }
  386.  
  387.         $AllData = array();
  388.         $idmagasin = 0;
  389.  
  390.         if($user!=null && $user->getMagasinid()!=null){  
  391.                         
  392.             $arrays = array();
  393.             $idmagasin = $user->getMagasinid()->getId();
  394.     
  395.             $arrays['datesuppressionproduit'] = null;
  396.             if(!$this->isGranted('ROLE_SUPER_ADMIN')){
  397.                 $arrays['id'] = $user->getProduitslist()??[];
  398.             }
  399.     
  400.             
  401.             $produits = $em->getRepository(Produit::class)->findBy($arrays); 
  402.             
  403.              
  404.             foreach($produits as $produit){
  405.              
  406.                 $ventedata = $em->createQueryBuilder()
  407.                     ->select('SUM(p.totalvente) AS totalVente', 'SUM(p.totalpaye) AS totalPaye', 'SUM(p.remisevente) AS totalRemise', 'SUM(p.totalvente-p.totalpaye) AS totalReste')
  408.                     ->from('App\Entity\Vente', 'p') 
  409.                     ->where('p.datesuppressionvente IS null')  
  410.                     ->andWhere('p.produitid = :idprod ')->setParameter('idprod', $produit->getId())
  411.                     ->andWhere('p.magasinid = :idmag ')->setParameter('idmag',$idmagasin)
  412.                     ->andWhere("p.datevente >= :datedebut ")->setParameter('datedebut', $datedebut)
  413.                     ->andWhere("p.datevente <= :datefin")->setParameter('datefin', $datefin)
  414.                     ->getQuery()->getResult();
  415.                     
  416.                 $AllData[] = [
  417.                     "Produit"=>$produit,
  418.                     "Data"=>$ventedata
  419.                     ] ;
  420.         
  421.             }
  422.         }  
  423.         
  424.              
  425.                 $depense = $em->createQueryBuilder()
  426.                     ->select('SUM(p.montantdepense) AS totalDepense')
  427.                     ->from('App\Entity\Depense', 'p') 
  428.                     ->where('p.datesuppressiondepense IS null')  
  429.                     ->andWhere('p.magasinid = :idmag ')->setParameter('idmag',$idmagasin)
  430.                     ->andWhere("p.datedepense >= :datedebut ")->setParameter('datedebut', $datedebut)
  431.                     ->andWhere("p.datedepense <= :datefin")->setParameter('datefin', $datefin)
  432.                     ->getQuery()->getResult();
  433.           
  434.         return $this->renderView('ventemobile/totalgestion.html.twig', [
  435.             "ALLDATA"=>$AllData,
  436.             "ALLDEPENSE"=>$depense
  437.         ]);
  438.      
  439.     
  440.     }  
  441.     
  442.          
  443.     
  444.     /**
  445.      * @Route("/admin/tdb", name="accueil")
  446.      */
  447.     public function admin(ManagerRegistry $doctrine,SessionInterface $sessions,Connection $conn,Request $request): Response
  448.     {
  449.         $ajaxs = false;
  450.         $user = $this->getUser();
  451.         $em = $this->getDoctrine()->getManager(); 
  452.         $parametres = $this->container;    
  453.         $sql = "";
  454.         $arrayprod = array();
  455.         $arrayprod[] = "Ciment";
  456.         $arrayprod[] = "Fer à Béton"; 
  457.         $data = array();
  458.         $idmagasin = 1;
  459.         if($user!=null && $user->getMagasinid()!=null){
  460.             
  461.             $arrays = array();
  462.             $idmagasin = $user->getMagasinid()->getId();
  463.     
  464.             $arrays['datesuppressionproduit'] = null;
  465.             if(!$this->isGranted('ROLE_SUPER_ADMIN')){
  466.                 $arrays['id'] = $user->getProduitslist()??[];
  467.             }
  468.     
  469.             
  470.             $produits = $em->getRepository(Produit::class)->findBy($arrays); 
  471.             
  472.             
  473.             $listeciment = array();
  474.             $listeciment2 = array();
  475.             foreach($produits as $produit){
  476.                 $idprod = $produit->getId();
  477.          
  478.                 
  479.                 $typeciments = $conn->fetchAllAssociative("
  480.                 SELECT * , sm.qtestock AS stockactuel , tc.id , (tc.prixtypeciment/tc.barretonne) AS prixtypeciment,
  481.                 (IFNULL((SELECT nomfournisseur FROM fournisseur WHERE id = tc.fournisseurid),'')) AS nomfournisseur
  482.                 FROM  typeciment tc , stockboutique sm
  483.                 WHERE tc.id = sm.typecimentid
  484.                 AND tc.produitid = $idprod
  485.                 AND sm.magasinid = $idmagasin
  486.                 AND tc.datesuppressiontypeciment IS NULL
  487.                 AND sm.datesuppressionstockboutique IS NULL
  488.                 AND sm.qtestock > 0 
  489.                 ORDER BY LENGTH(tc.nomtypeciment) ASC ,  tc.nomtypeciment ASC");  
  490.                 
  491.                 $typeciments2 = $conn->fetchAllAssociative("
  492.                 SELECT * , sm.qtestock AS stockactuel , tc.id , (tc.prixtypeciment/tc.barretonne) AS prixtypeciment,
  493.                 (IFNULL((SELECT nomfournisseur FROM fournisseur WHERE id = tc.fournisseurid),'')) AS nomfournisseur
  494.                 FROM  typeciment tc , stockboutique sm
  495.                 WHERE tc.id = sm.typecimentid
  496.                 AND tc.produitid = $idprod
  497.                 AND sm.magasinid = $idmagasin
  498.                 AND tc.datesuppressiontypeciment IS NULL
  499.                 AND sm.datesuppressionstockboutique IS NULL 
  500.                 ORDER BY LENGTH(tc.nomtypeciment) ASC ,  tc.nomtypeciment ASC");  
  501.                 
  502.                 //$result = array_merge($typeciments, $typeciments2);
  503.                 
  504.                 $listeciment[$idprod] = $typeciments;
  505.                 $listeciment2[$idprod] = $typeciments2;
  506.             }
  507.             
  508.             
  509.             $timestampLundi = null;
  510.             if((new DroitController())->estautoriser($this,'lister-vente-jour',true)){
  511.                $timestampLundi =  date('Y-m-d');
  512.             }
  513.             
  514.             if((new DroitController())->estautoriser($this,'lister-vente-semaine',true)){
  515.                 $timestampLundi = strtotime('monday this week');
  516.                 $timestampLundi = date('Y-m-d', $timestampLundi);
  517.             }
  518.             
  519.             if((new DroitController())->estautoriser($this,'lister-vente-mois',true)){
  520.                $timestampLundi =  date('Y-m').'-01';
  521.             }
  522.             
  523.             if((new DroitController())->estautoriser($this,'lister-vente-annee',true)){
  524.                $timestampLundi =  date('Y').'-01-01';
  525.             }
  526.             
  527.             $clients = $em->getRepository(Client::class)->findBy(['datesuppressionclient'=>null],['nom'=>'ASC','prenom'=>'ASC']); 
  528.             $commercials = $em->getRepository(Commercial::class)->findBy(['datesuppressioncommercial'=>null],['nom'=>'ASC','prenom'=>'ASC']); 
  529.             
  530.             
  531.             $timestampDebutLundi = strtotime('monday this week');
  532.             $timestampDebutLundi = date('Y-m-d', $timestampDebutLundi);
  533.             
  534.             return $this->render('ventemobile/index.html.twig',[ 
  535.             'CLIENTS'=>$clients,
  536.             'COMMERCIALS'=>$commercials,
  537.             'PRODUITES'=>$produits,
  538.             'TYPECIMENT'=>$listeciment,
  539.             'TYPECIMENT2'=>$listeciment2,
  540.             'LIGNEUNIQUE'=>null,
  541.             'MINDATE'=>$timestampLundi ,
  542.             'DEBUTDATE'=>$timestampDebutLundi,
  543.             'TEMPLATE'=> $this->rapportventetotalmagasin( $doctrine, $request)
  544.             ]); 
  545.         } 
  546.         foreach($arrayprod as $arraypr){
  547.             $prod = $em->getRepository(Produit::class)->findOneBy(['nomproduit'=>$arraypr]);
  548.             if($prod==null){
  549.                 $prod = new Produit();
  550.                 $prod->setNomproduit($arraypr);
  551.                 $prod->setJournalproduit("Création du produit $arraypr");
  552.                 $prod->setDatecreationproduit(new \DateTime());
  553.                 $em->persist($prod);
  554.                 $em->flush();
  555.             }
  556.         }
  557.         if($sessions->get('getsessionproduit')==null || strlen($sessions->get('getsessionproduit'))==0){
  558.             
  559.             $arrays = array();
  560.             $arrays['datesuppressionproduit'] = null;
  561.             if(!$this->isGranted('ROLE_SUPER_ADMIN')){
  562.                 $arrays['id'] = $user->getProduitslist()??[];
  563.             }
  564.             $produits = $em->getRepository(Produit::class)->findOneBy($arrays);  
  565.             $defaut = 1;
  566.             $defautname = "Ciment";
  567.             if($produits!=null){
  568.                 $defaut = $produits->getId(); 
  569.                 $defautname = $produits->getNomproduit(); 
  570.             }  
  571.             $sessions->set('getsessionproduit',$defaut);
  572.             $sessions->set('getsessionnomproduit',$defautname);  
  573.         }
  574.         
  575.             
  576.         if ((new DroitController())->estautoriser($this,'voir-tableaudebord',1) == true){
  577.  
  578.         $localite = $conn->fetchAllAssociative("SELECT * FROM localite l where l.datesuppressionlocalite is null ORDER BY nomlocalite ASC LIMIT 6");
  579.         
  580.         $option = 1;
  581.         $dated = "";
  582.         $datef = "";
  583.         if ($request->getMethod() == 'PUT') {
  584.              
  585.              $option = $request->get('periode');
  586.              $dated = $request->get('dated');
  587.              $datef = $request->get('datef');
  588.            
  589.            
  590.         }
  591.  
  592.         if($option==10){ 
  593.             $dates = $this->recupererDates($option,$dated,$datef);
  594.         }else{
  595.             $dates = $this->recupererDates($option);
  596.         }
  597.          
  598.         
  599.         $datedebut = $dates['datedebut'];
  600.         $datefin = $dates['datefin'];
  601.         $graphe = $dates['graphe'];
  602.         $grapheval = $dates['grapheval'];
  603.         $dat = [];
  604.         $sommecommandetermine = [];
  605.         $sommecommandeencours = [];
  606.         $sommecommandeannule = [];
  607.         
  608.         foreach($graphe as $f){
  609.             $dat[] = strlen($f);
  610.         }
  611.  
  612.         $sommebordereau = $conn->fetchAllAssociative("
  613.         SELECT IFNULL(SUM(montantversement),0) AS TT , COUNT(*) AS NT FROM bordereau where datebordereau BETWEEN 
  614.         '$datedebut' AND '$datefin' AND datesuppressionbordereau IS NULL AND produitid = $this->idproduit ;");
  615.  
  616.         $sommecommande = $conn->fetchAllAssociative("
  617.         SELECT  COUNT(*) AS NT ,
  618.         IFNULL((SELECT SUM(m.apayer) FROM livraison m WHERE m.datesuppressionlivraison is null AND m.produitid = $this->idproduit AND m.commandeid = c.id  ),0) AS TG,
  619.         IFNULL((SELECT SUM(m.total) FROM lignetypecommande m WHERE m.datesuppressionlignetypecommande is null AND m.produitid = $this->idproduit AND m.commandeid = c.id  ),0) AS TT
  620.         FROM  commande c 
  621.         where c.datecommande BETWEEN '$datedebut' AND '$datefin' 
  622.         AND c.produitid = $this->idproduit  
  623.         AND c.datesuppressioncommande IS NULL  ;");
  624.   
  625.  
  626.         $sommecommande2 = $conn->fetchAllAssociative("SELECT IFNULL(SUM(tc.total),0) AS TT , IFNULL(SUM(lc.prixunitairelignecommande*lc.total),0) AS TG , COUNT(*) AS NT 
  627.         FROM dangote c , lignedangote lc , lignetypecommande tc
  628.         where c.datecommande BETWEEN '$datedebut' AND '$datefin' 
  629.         AND c.produitid = $this->idproduit
  630.         AND c.id = lc.commandeid AND c.id = tc.commandeid
  631.         AND c.datesuppressioncommande IS NULL  AND lc.datesuppressionlignecommande IS NULL ;");
  632.  
  633.         $grapheDatas = [];
  634.  
  635.         $tab01 = [];
  636.         $tab02 = [];
  637.         $tab03 = [];
  638.  
  639.         foreach($grapheval as $el){
  640.  
  641.             $datedebut = $el['dd'];
  642.             $datefin = $el['df'];
  643.              
  644.             $sommecommandetermine = $conn->fetchAllAssociative("
  645.             SELECT  COUNT(*) AS NT ,
  646.             IFNULL((SELECT SUM(m.apayer) FROM livraison m WHERE m.datesuppressionlivraison is null AND m.produitid = $this->idproduit AND m.commandeid = c.id  ),0) AS TG,
  647.             IFNULL((SELECT SUM(m.total) FROM lignetypecommande m WHERE m.datesuppressionlignetypecommande is null AND m.produitid = $this->idproduit AND m.commandeid = c.id  ),0) AS TT
  648.             FROM  commande c 
  649.             where c.datecommande BETWEEN '$datedebut' AND '$datefin' 
  650.             AND c.produitid = $this->idproduit  
  651.             AND c.datevalidationcommande IS NOT NULL
  652.             AND c.datesuppressioncommande IS NULL  ;");
  653.             
  654.             $sommecommandeencours = $conn->fetchAllAssociative("
  655.             SELECT  COUNT(*) AS NT ,
  656.             IFNULL((SELECT SUM(m.apayer) FROM livraison m WHERE m.datesuppressionlivraison is null AND m.produitid = $this->idproduit AND m.commandeid = c.id  ),0) AS TG,
  657.             IFNULL((SELECT SUM(m.total) FROM lignetypecommande m WHERE m.datesuppressionlignetypecommande is null AND m.produitid = $this->idproduit AND m.commandeid = c.id  ),0) AS TT
  658.             FROM  commande c 
  659.             where c.datecommande BETWEEN '$datedebut' AND '$datefin' 
  660.             AND c.produitid = $this->idproduit  
  661.             AND c.datevalidationcommande IS NULL
  662.             AND c.datesuppressioncommande IS NULL  ;");
  663.       
  664.             
  665.             $sommecommandeannule = $conn->fetchAllAssociative("
  666.             SELECT  COUNT(*) AS NT ,
  667.             IFNULL((SELECT SUM(m.apayer) FROM livraison m WHERE m.datesuppressionlivraison is null AND m.produitid = $this->idproduit AND m.commandeid = c.id  ),0) AS TG,
  668.             IFNULL((SELECT SUM(m.total) FROM lignetypecommande m WHERE m.datesuppressionlignetypecommande is null AND m.produitid = $this->idproduit AND m.commandeid = c.id  ),0) AS TT
  669.             FROM  commande c 
  670.             where c.datecommande BETWEEN '$datedebut' AND '$datefin' 
  671.             AND c.produitid = $this->idproduit  
  672.             AND c.datevalidationcommande IS NULL
  673.             AND c.datesuppressioncommande IS NOT NULL  ;");
  674.       
  675.              
  676.             
  677.             
  678.             $tab01[] = sizeof($sommecommandetermine)>0 ? $sommecommandetermine[0]['TT'] : 0;
  679.             $tab02[] = sizeof($sommecommandeannule)>0 ? $sommecommandeannule[0]['TT'] : 0;
  680.             $tab03[] = sizeof($sommecommandeencours)>0 ? $sommecommandeencours[0]['TT'] : 0;
  681.              
  682.         }
  683.         $grapheDatas[] = [['name'=>'Terminé','data'=>$tab01],['name'=>'Annulé','data'=>$tab02],['name'=>'En cours','data'=>$tab03]];
  684.         
  685.         $commandes = $conn->fetchAllAssociative("SELECT * , c.id AS idc , b.id AS idb , 
  686.         IFNULL((SELECT SUM(l.tonne*l.quantite) FROM lignecommande l where l.commandeid = c.id AND l.datesuppressionlignecommande is NULL),0) AS totaltonne
  687.         FROM commande c, bordereau b 
  688.         where c.datesuppressioncommande is null 
  689.         AND c.produitid = $this->idproduit
  690.         AND c.bordereauid = b.id AND c.datevalidationcommande is NULL AND c.dateannulationcommande IS NULL
  691.         ORDER BY c.numcommande DESC LIMIT 10");
  692.         
  693.         
  694.         $commandes2 = $conn->fetchAllAssociative("SELECT * , c.id AS idc,
  695.         IFNULL((SELECT SUM(l.tonne*l.quantite) FROM lignedangote l where l.commandeid = c.id AND l.datesuppressionlignecommande is NULL),0) AS totaltonne
  696.         FROM dangote c , typeciment tc
  697.         where c.datesuppressioncommande is null AND tc.id = c.typecimentid AND  c.datevalidationcommande is NULL AND c.dateannulationcommande IS NULL
  698.         ORDER BY c.numcommande DESC LIMIT 10");
  699.         
  700.         
  701.         // ── 1. DÉPENSES sur la même période que le filtre ──────────────────────────
  702.         $depenses_tdb = $conn->fetchAllAssociative("
  703.             SELECT
  704.                 IFNULL(SUM(d.montantdepense), 0)          AS total,
  705.                 COUNT(d.id)                                AS nb,
  706.                 SUM(CASE WHEN f.id IS NULL THEN 1 ELSE 0 END) AS sans_justif,
  707.                 c.nom                                      AS categorie_nom,
  708.                 c.couleur                                  AS categorie_couleur,
  709.                 IFNULL(c.nom, 'Non catégorisé')            AS cat_label
  710.             FROM depense d
  711.             LEFT JOIN depense_categorie c ON c.id = d.categorieid
  712.             LEFT JOIN (
  713.                 SELECT depenseid, MIN(id) AS id
  714.                 FROM depense_fichier
  715.                 WHERE datesuppression IS NULL
  716.                 GROUP BY depenseid
  717.             ) f ON f.depenseid = d.id
  718.             WHERE d.datesuppressiondepense IS NULL
  719.             AND d.produitid = $this->idproduit
  720.             AND d.datedepense BETWEEN '$datedebut' AND '$datefin'
  721.             GROUP BY d.categorieid
  722.             ORDER BY total DESC
  723.             LIMIT 8
  724.         ");
  725.         // Totaux dépenses pour les KPI cards
  726.         $depenses_totaux = $conn->fetchAssociative("
  727.             SELECT
  728.                 IFNULL(SUM(montantdepense), 0) AS total,
  729.                 COUNT(id) AS nb,
  730.                 SUM(CASE WHEN (
  731.                     SELECT COUNT(*) FROM depense_fichier
  732.                     WHERE depenseid = d.id AND datesuppression IS NULL
  733.                 ) = 0 THEN 1 ELSE 0 END) AS sans_justif
  734.             FROM depense d
  735.             WHERE datesuppressiondepense IS NULL
  736.             AND produitid = $this->idproduit
  737.             AND datedepense BETWEEN '$datedebut' AND '$datefin'
  738.         ") ?: ['total'=>0,'nb'=>0,'sans_justif'=>0];
  739.         // ── 2. STOCK disponible par type de ciment ─────────────────────────────────
  740.         $stock_tdb = $conn->fetchAllAssociative("
  741.             SELECT
  742.                 tc.nomtypeciment,
  743.                 tc.prixtypeciment / tc.barretonne AS prix_unitaire,
  744.                 sm.qtestock,
  745.                 sm.qtestock * (tc.prixtypeciment / tc.barretonne) AS valeur_stock,
  746.                 IFNULL((SELECT nomfournisseur FROM fournisseur WHERE id = tc.fournisseurid), '—') AS fournisseur
  747.             FROM typeciment tc
  748.             INNER JOIN stockboutique sm ON sm.typecimentid = tc.id
  749.             WHERE tc.produitid = $this->idproduit
  750.             AND sm.magasinid = $idmagasin
  751.             AND tc.datesuppressiontypeciment IS NULL
  752.             AND sm.datesuppressionstockboutique IS NULL
  753.             AND sm.qtestock > 0
  754.             ORDER BY LENGTH(tc.nomtypeciment), tc.nomtypeciment
  755.         ");
  756.         $stock_total_valeur = array_sum(array_column($stock_tdb, 'valeur_stock'));
  757.         $stock_total_qte    = array_sum(array_column($stock_tdb, 'qtestock'));
  758.         // ── 3. TOP CLIENTS ──────────────────────────────────────────────────────────
  759.         $top_clients = $conn->fetchAllAssociative("
  760.             SELECT
  761.                 CONCAT(IFNULL(cl.nom,''), ' ', IFNULL(cl.prenom,'')) AS nom_client,
  762.                 IFNULL(SUM(v.totalvente), 0)  AS total_vente,
  763.                 IFNULL(SUM(v.totalpaye), 0)   AS total_paye,
  764.                 IFNULL(SUM(v.totalvente - v.totalpaye), 0) AS reste,
  765.                 COUNT(v.id)                   AS nb_ventes
  766.             FROM vente v
  767.             INNER JOIN client cl ON cl.id = v.clientid
  768.             WHERE v.datesuppressionvente IS NULL
  769.             AND v.produitid = $this->idproduit
  770.             AND v.magasinid = $idmagasin
  771.             AND v.datevente BETWEEN '$datedebut' AND '$datefin'
  772.             GROUP BY v.clientid
  773.             ORDER BY total_vente DESC
  774.             LIMIT 8
  775.         ");
  776.         // ── 4. VENTES MAGASIN (résumé rapportventetotalmagasin) ────────────────────
  777.         $ventes_magasin = $conn->fetchAllAssociative("
  778.             SELECT
  779.                 IFNULL(SUM(v.totalvente), 0)  AS totalVente,
  780.                 IFNULL(SUM(v.totalpaye), 0)   AS totalPaye,
  781.                 IFNULL(SUM(v.remisevente), 0) AS totalRemise,
  782.                 IFNULL(SUM(v.totalvente - v.totalpaye), 0) AS totalReste,
  783.                 COUNT(v.id)                   AS nbVentes,
  784.                 p.nomproduit
  785.             FROM vente v
  786.             INNER JOIN produit p ON p.id = v.produitid
  787.             WHERE v.datesuppressionvente IS NULL
  788.             AND v.produitid = $this->idproduit
  789.             AND v.magasinid = $idmagasin
  790.             AND v.datevente BETWEEN '$datedebut' AND '$datefin'
  791.             GROUP BY v.produitid
  792.         ") ?: [];
  793.         $ventes_magasin_resume = $ventes_magasin[0] ?? ['totalVente'=>0,'totalPaye'=>0,'totalRemise'=>0,'totalReste'=>0,'nbVentes'=>0];
  794.         // ── Ajouter au tableau $data (insérer dans les clés existantes) ─────────────
  795.         // Dans votre $data = [...], ajoutez ces lignes :
  796.         //   'DEPENSES_TDB'       => $depenses_tdb,
  797.         //   'DEPENSES_TOTAUX'    => $depenses_totaux,
  798.         //   'STOCK_TDB'          => $stock_tdb,
  799.         //   'STOCK_TOTAL_VALEUR' => $stock_total_valeur,
  800.         //   'STOCK_TOTAL_QTE'    => $stock_total_qte,
  801.         //   'TOP_CLIENTS'        => $top_clients,
  802.         //   'VENTES_MAGASIN'     => $ventes_magasin_resume,
  803.         //   'idmagasin'          => $idmagasin,
  804.         $data = [ 
  805.                 'dd'=>$datedebut,
  806.                 'df'=>$datefin,
  807.                 'LOCALITES'=>$localite,
  808.                 'COMMANDES'=>$commandes,
  809.                 'COMMANDES2'=>$commandes2,
  810.                 'RESTAURANTS'=>[],
  811.                 'PRODUITS'=>[],
  812.                 'TB'=>$sommebordereau,
  813.                 'TC'=>$sommecommande,
  814.                 'TC2'=>$sommecommande2,
  815.                 'CV'=>sizeof($sommecommandetermine)>0 ? $sommecommandetermine[0] : ['TT'=>0],
  816.                 'CEC'=>sizeof($sommecommandeencours)>0 ? $sommecommandeencours[0] : ['TT'=>0],
  817.                 'CA'=>sizeof($sommecommandeannule)>0 ? $sommecommandeannule[0] : ['TT'=>0], 
  818.                 'G'=>$graphe,
  819.                 'D'=>$dat,
  820.                 'V'=>$grapheval,
  821.                 'GD'=>$grapheDatas
  822.                 ];
  823.  
  824.         if ($request->getMethod() == 'PUT') {
  825.             return new JsonResponse(["vu"=>$this->renderView('accueil/include1.html.twig',$data),'data'=>$data]);
  826.         }
  827.         
  828.         
  829.         return $this->render('accueil/index.html.twig',$data);
  830.         }else{
  831.             return $this->render('accueil/noindex.html.twig');
  832.         }
  833.     
  834.     }
  835.     
  836.     
  837.     
  838.     
  839.     
  840.     
  841.     
  842.     
  843.     /**
  844.      * @Route("/admin/rapport", name="rapport")
  845.      */
  846.     public function rapport(ManagerRegistry $doctrine,SessionInterface $sessions,Connection $conn,Request $request,LogActionService $logger,\App\Service\MagasinCatalogueFilterService $magasinFilter): Response
  847.     {
  848.         $ajaxs = false;
  849.         $user = $this->getUser();
  850.         $em = $this->getDoctrine()->getManager();
  851.         $parametres = $this->container;
  852.         $sql = "";
  853.         $logger->createLog(
  854.             'rapport_consultation',
  855.             "Consultation du rapport général",
  856.             $user ? $user->getId() : null,
  857.             null,
  858.             null,
  859.             ['old' => null, 'new' => ['rapport' => 'general', 'filtres' => $request->query->all()]]
  860.         );
  861.         $arrayprod = array();
  862.         $arrayprod[] = "Ciment";
  863.         $arrayprod[] = "Fer à Béton"; 
  864.         $data = array();
  865.  
  866.         $timestampLundi = strtotime('monday this week');
  867.         $timestampLundi = date('Y-m-d', $timestampLundi);
  868.    
  869.         $fournisseurs = $em->getRepository(Fournisseur::class)->findBy(['produitid'=>$this->idproduit,'datesuppressionfournisseur'=>null],['nomfournisseur'=>'ASC']);
  870.       
  871.    
  872.         $commerciaux = $em->getRepository(Commercial::class)->findBy(['datesuppressioncommercial'=>null],['nom'=>'ASC']);
  873.       
  874.             $arrays = array();
  875.             $idmagasin = 0;
  876.     
  877.             $arrays['datesuppressionproduit'] = null;
  878.             if(!$this->isGranted('ROLE_SUPER_ADMIN')){
  879.                 $arrays['id'] = $user->getProduitslist()??[];
  880.             }
  881.     
  882.             
  883.             $produits = $em->getRepository(Produit::class)->findBy($arrays); 
  884.             
  885.             
  886.             $typeciments2 = $conn->fetchAllAssociative("
  887.             SELECT * ,   tc.id , (tc.prixtypeciment/tc.barretonne) AS prixtypeciment,
  888.             (IFNULL((SELECT nomfournisseur FROM fournisseur WHERE id = tc.fournisseurid),'')) AS nomfournisseur
  889.             FROM  typeciment tc 
  890.             WHERE tc.produitid = $this->idproduit 
  891.             AND tc.datesuppressiontypeciment IS NULL 
  892.             ORDER BY LENGTH(tc.nomtypeciment) ASC ,  tc.nomtypeciment ASC");  
  893.             
  894.             
  895.     
  896.             $timestampDebutLundi = strtotime('monday this week');
  897.             $timestampDebutLundi = date('Y-m-d', $timestampDebutLundi);
  898.             
  899.             
  900.             $clients = $em->getRepository(Client::class)->findBy(['datesuppressionclient'=>null],['nom'=>'ASC','prenom'=>'ASC']); 
  901.             $commercials = $em->getRepository(Commercial::class)->findBy(['datesuppressioncommercial'=>null],['nom'=>'ASC','prenom'=>'ASC']); 
  902.       
  903.             // Ne lister que les magasins qui gèrent le produit actif, au sens du
  904.             // catalogue (stockboutique.catalogue_actif = 1) — la même règle que
  905.             // Vente, Dépense, Ajustement et Situation magasin, via
  906.             // MagasinCatalogueFilterService. La colonne héritée magasin.produitid
  907.             // ne porte qu'un seul produit et ne reflète plus la réalité : elle
  908.             // masquait des magasins qui vendent bel et bien le produit actif.
  909.             // Sans produit actif — ou si le catalogue ne répond rien — on retombe
  910.             // sur tous les magasins ouverts : mieux vaut une liste complète qu'un
  911.             // filtre vide.
  912.             $magasins = $magasinFilter->magasinsPourProduit($this->idproduit);
  913.             if (empty($magasins)) {
  914.                 $magasins = $em->getRepository(Magasin::class)->findBy(
  915.                     ['datesuppressionmagasin' => null],
  916.                     ['nommagasin' => 'ASC']
  917.                 );
  918.             }
  919.             $arriereStats = $em->getRepository(ArriereClient::class)->statsRapport($this->idproduit);
  920.             $data = ["VIEW"=>0,'idproduit'=>$this->idproduit,'FOURNISSEURS'=>$fournisseurs,'DATEDEBUT'=>$timestampLundi,'CLIENTS'=>$clients,
  921.             'COMMERCIALS'=>$commercials,  'TYPECIMENT'=>$typeciments2,   'MINDATE'=>$timestampLundi, 'DEBUTDATE'=>$timestampDebutLundi , 'MAGASINS'=>$magasins,'COMMERCIAUX'=>$commerciaux,
  922.             'TEMPLATE'=> $this->rapportventetotalmagasin( $doctrine, $request),
  923.             'ARRIERES_STATS' => $arriereStats];
  924.  
  925.        
  926.         
  927.         
  928.         
  929.         return $this->render('rapport/index.html.twig',$data);
  930.   
  931.     
  932.     }
  933.     
  934.     
  935.     
  936.     /**
  937.      * @Route("/admin/rapportventemagasin", name="rapportventemagasin")
  938.      */
  939.     public function rapportventemagasin(ManagerRegistry $doctrine,Request $request,LogActionService $logger): Response
  940.     {
  941.         $user = $this->getUser();
  942.         $em =  $doctrine->getManager();
  943.         $parametres = $this->container;
  944.         $conn  =  $this->connection;
  945.         $modification = true;
  946.         $message = "";
  947.         $statut = 0;
  948.         $color = "red";
  949.         $logger->createLog(
  950.             'rapport_consultation',
  951.             "Consultation du rapport « ventes par magasin »",
  952.             $user ? $user->getId() : null,
  953.             null,
  954.             null,
  955.             ['old' => null, 'new' => ['rapport' => 'ventes_par_magasin', 'filtres' => $request->query->all()]]
  956.         );
  957.         $idproduitelement = $request->get('idproduitelement');
  958.         $filtredetail = $request->get('filtredetail');
  959.         $id = $request->get('idproduit');
  960.         $statutvente = $request->get('statutvente')??1;
  961.         $datedebut = $request->get('datedebut');
  962.         $datefin   = $request->get('datefin');
  963.         $client   = $request->get('client')??0;
  964.         $commercial   = $request->get('commercial')??0;
  965.         $idmagasin = $request->get('magasinid');
  966.         
  967.             
  968.         $ventes = $em->createQueryBuilder()
  969.                     ->select('lv','p')
  970.                     ->from('App\Entity\Lignetypevente', 'lv')
  971.                     ->join('lv.venteid', 'p')
  972.                     ->where('p.datesuppressionvente IS null') 
  973.                     ->andWhere('p.datevalidationvente IS NOT null') 
  974.                     ->andWhere('lv.datesuppressionlignetypevente IS null') 
  975.                     ->andWhere('p.produitid = :idprod ') 
  976.                     ->setParameter('idprod', $id);  
  977.                     
  978.             
  979.         $ventedata = $em->createQueryBuilder()
  980.                     ->select('SUM(p.totalvente) AS totalVente', 'SUM(p.totalpaye) AS totalPaye', 'SUM(p.remisevente) AS totalRemise', 'SUM(p.totalvente-p.totalpaye) AS totalReste')
  981.                     ->from('App\Entity\Vente', 'p') 
  982.                     ->where('p.datesuppressionvente IS null') 
  983.                     ->andWhere('p.datevalidationvente IS NOT null') 
  984.                     ->andWhere('p.produitid = :idprod ') 
  985.                     ->setParameter('idprod', $id);  
  986.                     
  987.         if($idmagasin>0){
  988.             $ventes = $ventes->andWhere('p.magasinid = :idmag ')->setParameter('idmag',$idmagasin);
  989.             $ventedata = $ventedata->andWhere('p.magasinid = :idmag ')->setParameter('idmag',$idmagasin);
  990.         }
  991.         if ($idproduitelement == -1) {
  992.             $ventes = $ventes
  993.                 ->join('lv.typecimentid', 'tc')
  994.                 ->select('tc.nomtypeciment AS nomtypeciment','IDENTITY(lv.typecimentid) AS typeciment', 'SUM(lv.quantite) AS quantiteTotal', 'SUM(lv.total) AS totalVente')
  995.                 ->groupBy('lv.typecimentid'); 
  996.         } 
  997.         
  998.             
  999.         if($idproduitelement>0){
  1000.             $ventes = $ventes->andWhere("lv.typecimentid = :idproduitelement ")->setParameter('idproduitelement', $idproduitelement);
  1001.             //$ventedata = $ventedata->andWhere("lv.typecimentid = :idproduitelement ")->setParameter('idproduitelement', $idproduitelement);
  1002.         }
  1003.                     
  1004.         if(strlen($datedebut)>7){
  1005.           $ventes = $ventes->andWhere("p.datevente >= :datedebut ")->setParameter('datedebut', $datedebut);  
  1006.           $ventedata = $ventedata->andWhere("p.datevente >= :datedebut ")->setParameter('datedebut', $datedebut);  
  1007.         }           
  1008.         if(strlen($datedebut)>7){
  1009.           $ventes = $ventes->andWhere("p.datevente <= :datefin")->setParameter('datefin', $datefin);  
  1010.           $ventedata = $ventedata->andWhere("p.datevente <= :datefin")->setParameter('datefin', $datefin);  
  1011.         }
  1012.         if((new DroitController())->estautoriser($this,'voir-mes-vente',true)){
  1013.            //$ventes = $ventes->andWhere("p.venteajoutepar = :venteajoutepar")->setParameter('venteajoutepar', $user->getId()); 
  1014.         }
  1015.         
  1016.         if($client>0){
  1017.             $ventes = $ventes->andWhere("p.clientid = $client");
  1018.             $ventedata = $ventedata->andWhere("p.clientid = $client");
  1019.         }
  1020.         
  1021.         if($commercial>0){
  1022.             $ventes = $ventes->andWhere("p.commercialid = $commercial");
  1023.             $ventedata = $ventedata->andWhere("p.commercialid = $commercial");
  1024.         }
  1025.         
  1026.         if($statutvente==2){ // En attente
  1027.             $ventes = $ventes->andWhere("p.datevalidationvente IS NULL");
  1028.             $ventedata = $ventedata->andWhere("p.datevalidationvente IS NULL");
  1029.         }
  1030.            
  1031.         if($statutvente==3){ // Aucun paiement
  1032.             $ventes = $ventes->andWhere("p.totalvente>0 AND p.totalpaye = 0");
  1033.             $ventedata = $ventedata->andWhere("p.totalvente>0 AND p.totalpaye = 0");
  1034.         }
  1035.           
  1036.            
  1037.         if($statutvente==4){ // Paiement partiel
  1038.             $ventes = $ventes->andWhere("p.totalvente > p.totalpaye AND p.totalpaye>0");
  1039.             $ventedata = $ventedata->andWhere("p.totalvente > p.totalpaye AND p.totalpaye>0");
  1040.         }
  1041.           
  1042.            
  1043.         if($statutvente==5){ // Soldé
  1044.             $ventes = $ventes->andWhere("p.totalvente>0 AND p.totalvente <= p.totalpaye");
  1045.             $ventedata = $ventedata->andWhere("p.totalvente>0 AND p.totalvente <= p.totalpaye");
  1046.         }
  1047.         
  1048.       
  1049.           if ($idproduitelement == -1) {
  1050.             $ventes = $ventes->orderBy('totalVente', 'DESC')->getQuery()->getResult(); 
  1051.             $ventedata = $ventedata->orderBy('totalVente', 'DESC')->getQuery()->getResult();  
  1052.           }else{
  1053.             $ventes = $ventes->orderBy('p.id', 'ASC')->getQuery()->getResult(); 
  1054.             $ventedata = $ventedata->orderBy('p.id', 'ASC')->getQuery()->getResult(); 
  1055.           }
  1056.             
  1057.           
  1058.         
  1059.         
  1060.         $total = 0;
  1061.         $totalpaye = 0;
  1062.         $qte = 0;
  1063.         $nombre = 0;
  1064.         $lignevente = array();
  1065.         foreach($ventes as $vente){
  1066.         
  1067.                 if ($idproduitelement == -1) {
  1068.                     $qte += $vente['quantiteTotal'];
  1069.                     $total += $vente['totalVente'];
  1070.            
  1071.                 }else{
  1072.                     $total = $total + $vente->getTotal();
  1073.                     $qte = $qte + $vente->getQuantite();  
  1074.                 }
  1075.                 $nombre++;
  1076.                 $totalpaye = 0;  
  1077.             
  1078.         }
  1079.         
  1080.         
  1081.         
  1082.    
  1083.         
  1084.           
  1085.         return $this->render('rapport/rapportventemagasin.html.twig', [
  1086.             'VENTE'=>$ventedata,
  1087.             'TOTAL'=>$total,
  1088.             'TOTALPAYE'=>$totalpaye,
  1089.             'VENTES' => $ventes, 
  1090.             'NOMBRE'=> $nombre,
  1091.             'idproduitelement'=> $idproduitelement,
  1092.             'QTE'=> $qte
  1093.         ]);
  1094.      
  1095.     
  1096.     }  
  1097.     
  1098.  
  1099.  
  1100.     
  1101.     
  1102.     /**
  1103.      * @Route("/admin/rapportventeclient", name="rapportventeclient")
  1104.      */
  1105.     public function rapportventeclient(ManagerRegistry $doctrine,Request $request,LogActionService $logger): Response
  1106.     {
  1107.         $user = $this->getUser();
  1108.         $em =  $doctrine->getManager();
  1109.         $parametres = $this->container;
  1110.         $conn  =  $this->connection;
  1111.         $modification = true;
  1112.         $message = "";
  1113.         $statut = 0;
  1114.         $color = "red";
  1115.         $logger->createLog(
  1116.             'rapport_consultation',
  1117.             "Consultation du rapport « ventes par client »",
  1118.             $user ? $user->getId() : null,
  1119.             null,
  1120.             null,
  1121.             ['old' => null, 'new' => ['rapport' => 'ventes_par_client', 'filtres' => $request->query->all()]]
  1122.         );
  1123.         $idproduitelement = $request->get('idproduitelement');
  1124.         $filtredetail = $request->get('filtredetail');
  1125.         $id = $request->get('idproduit');
  1126.         $statutvente = $request->get('statutvente')??1;
  1127.         $datedebut = $request->get('datedebut');
  1128.         $datefin   = $request->get('datefin');
  1129.         $client   = $request->get('client')??0;
  1130.         $commercial   = $request->get('commercial')??0;
  1131.         $idmagasin = $request->get('magasinid');
  1132.            
  1133.             
  1134.         $ventedata = $em->createQueryBuilder()
  1135.                     ->select('SUM(ltv.total) AS totalVente', 'SUM(ltv.total) AS totalPaye', 'SUM(ltv.total) AS totalRemise', 'SUM(ltv.total) AS totalReste')
  1136.                     ->from('App\Entity\Lignetypecommande', 'ltv') 
  1137.                     ->join('ltv.commandeid', 'p')
  1138.                     ->where('p.datesuppressioncommande IS null') 
  1139.                     //->andWhere('p.datevalidationcommande IS NOT null') 
  1140.                     ->andWhere('p.produitid = :idprod ') 
  1141.                     ->setParameter('idprod', $id);  
  1142.                     
  1143.         $sql = ""; 
  1144.                     
  1145.         if($idmagasin>0){
  1146.             //$ventes = $ventes->andWhere('p.magasinid = :idmag ')->setParameter('idmag',$idmagasin);
  1147.             //$ventedata = $ventedata->andWhere('p.magasinid = :idmag ')->setParameter('idmag',$idmagasin);
  1148.         }
  1149.         if ($idproduitelement == -1) {
  1150.           /*  $ventes = $ventes
  1151.                 ->join('ltv.typecimentid', 'tc')
  1152.                 ->select('tc.nomtypeciment AS nomtypeciment','IDENTITY(ltv.typecimentid) AS typeciment', 'SUM(ltv.quantite) AS quantiteTotal', 'SUM(ltv.total) AS totalVente')
  1153.                 ->groupBy('ltv.typecimentid');  */
  1154.         } 
  1155.         
  1156.             
  1157.         if($idproduitelement>0){
  1158.             $sql .= " AND tc.id = $idproduitelement "; 
  1159.         }
  1160.                     
  1161.         if(strlen($datedebut)>7){  
  1162.           $sql .= " AND lc.datecreationlignecommande >= '$datedebut 00:00:00' ";
  1163.         }           
  1164.         if(strlen($datefin)>7){ 
  1165.           $sql .= " AND lc.datecreationlignecommande <= '$datefin 23:59:59' ";
  1166.         } 
  1167.         
  1168.         if($client>0){ 
  1169.             $sql .= " AND lc.clientid = $client ";
  1170.         }
  1171.         
  1172.         if($commercial>0){ 
  1173.             $sql .= " AND l.commercialid = $commercial ";
  1174.         }
  1175.        
  1176.         if($statutvente==2){ // En attente
  1177.             
  1178.         }
  1179.            
  1180.         if($statutvente==3){ // Aucun paiement
  1181.              
  1182.             $sql .= " AND l.totalpaye = 0 ";
  1183.         }
  1184.           
  1185.            
  1186.         if($statutvente==4){ // Paiement partiel
  1187.            
  1188.             $sql .= " AND l.totalpaye > 0 AND l.totalpaye < l.apayer ";
  1189.         }
  1190.           
  1191.            
  1192.         if($statutvente==5){ // Soldé
  1193.             $sql .= " AND l.totalpaye >= l.apayer ";
  1194.         }
  1195.         
  1196.       
  1197.           if ($idproduitelement == -1) {
  1198.                 $ventes = $conn->fetchAllAssociative("
  1199.                     SELECT tc.* , SUM(l.tonne) AS tonne , SUM(l.apayer) AS apayer , SUM(l.totalpaye) AS totalpaye FROM
  1200.                     typeciment tc , commande c , lignetypecommande ltc , lignecommande lc , livraison l
  1201.                     WHERE tc.id = ltc.typecimentid AND c.id = ltc.commandeid AND ltc.id = lc.lignetypecommandeid AND  lc.id = l.lignecommandeid 
  1202.                     AND c.datesuppressioncommande IS NULL AND ltc.datesuppressionlignetypecommande IS NULL AND lc.datesuppressionlignecommande IS NULL AND l.datesuppressionlivraison IS NULL
  1203.                     AND (lc.clientid IS NOT NULL OR lc.localiteid IS NOT NULL) AND tc.produitid = $id  $sql GROUP BY tc.id");  
  1204.           }else{
  1205.                 $ventes = $conn->fetchAllAssociative("
  1206.                     SELECT * , 
  1207.                     IFNULL((SELECT CONCAT(client.nom,' ',client.prenom,' ',client.telephone) FROM client WHERE client.id = lc.clientid),
  1208.                     IFNULL((SELECT nomlocalite FROM localite WHERE localite.id = lc.localiteid),'-')) AS MYCLIENT,
  1209.                     IFNULL((SELECT CONCAT(commercial.nom,' ',commercial.prenom,' ',commercial.telephone) FROM commercial WHERE commercial.id = l.commercialid),'-') AS MYCOMMERCIAL
  1210.                     FROM
  1211.                     typeciment tc , commande c , lignetypecommande ltc , lignecommande lc , livraison l
  1212.                     WHERE tc.id = ltc.typecimentid AND c.id = ltc.commandeid AND ltc.id = lc.lignetypecommandeid AND  lc.id = l.lignecommandeid 
  1213.                     AND c.datesuppressioncommande IS NULL AND ltc.datesuppressionlignetypecommande IS NULL AND lc.datesuppressionlignecommande IS NULL AND l.datesuppressionlivraison IS NULL
  1214.                     AND (lc.clientid IS NOT NULL OR lc.localiteid IS NOT NULL) AND tc.produitid = $id  $sql "); 
  1215.           }
  1216.             
  1217.           
  1218.        
  1219.         
  1220.         $total = 0;
  1221.         $totalpaye = 0;
  1222.         $qte = 0;
  1223.         $nombre = 0;
  1224.         $lignevente = array();
  1225.         foreach($ventes as $vente){
  1226.         
  1227.                 $total += $vente['apayer'];
  1228.                 $totalpaye += $vente['totalpaye'];
  1229.                 $qte += intval($vente['tonne']);
  1230.                 $nombre++; 
  1231.             
  1232.         }
  1233.         
  1234.         
  1235.         
  1236.    
  1237.         
  1238.           
  1239.         return $this->render('rapport/rapportventeclient.html.twig', [
  1240.             'VENTE'=>$ventedata,
  1241.             'TOTAL'=>$total,
  1242.             'TOTALPAYE'=>$totalpaye,
  1243.             'COMMANDES' => $ventes, 
  1244.             'NOMBRE'=> $nombre,
  1245.             'idproduitelement'=> $idproduitelement,
  1246.             'QTE'=> $qte
  1247.         ]);
  1248.      
  1249.     
  1250.     }  
  1251.     
  1252.  
  1253.     
  1254.     /**
  1255.      * @Route("/admin/rapportcommandetotal", name="rapportcommandetotal")
  1256.      */
  1257.     public function rapportcommandetotal(ManagerRegistry $doctrine,Request $request,LogActionService $logger): Response
  1258.     {
  1259.         $user = $this->getUser();
  1260.         $em =  $doctrine->getManager();
  1261.         $parametres = $this->container;
  1262.         $conn  =  $this->connection;
  1263.         $modification = true;
  1264.         $message = "";
  1265.         $statut = 0;
  1266.         $color = "red";
  1267.         $logger->createLog(
  1268.             'rapport_consultation',
  1269.             "Consultation du rapport « commandes total »",
  1270.             $user ? $user->getId() : null,
  1271.             null,
  1272.             null,
  1273.             ['old' => null, 'new' => ['rapport' => 'commandes_total', 'filtres' => $request->query->all()]]
  1274.         );
  1275.         $idproduitelement = $request->get('idproduitelement');
  1276.         $filtredetail = $request->get('filtredetail');
  1277.         $id = $request->get('idproduit');
  1278.         $statutvente = $request->get('statutvente')??1;
  1279.         $datedebut = $request->get('datedebut');
  1280.         $datefin   = $request->get('datefin');
  1281.         $client   = $request->get('client')??0;
  1282.         $commercial   = $request->get('commercial')??0;
  1283.         $idmagasin = $request->get('magasinid'); 
  1284.         $fournisseurid = $request->get('fournisseurid');
  1285.              
  1286.                     
  1287.         $sql = ""; 
  1288.                     
  1289.         if($fournisseurid>0){
  1290.           $sql .= " AND b.fournisseurid = $fournisseurid ";
  1291.         }
  1292.  
  1293.             
  1294.         if($idproduitelement>0){
  1295.             $sql .= " AND tc.id = $idproduitelement "; 
  1296.         }
  1297.                     
  1298.         if(strlen($datedebut)>7){  
  1299.           $sql .= " AND c.datecommande >= '$datedebut' ";
  1300.         }           
  1301.         if(strlen($datefin)>7){ 
  1302.           $sql .= " AND c.datecommande <= '$datefin' ";
  1303.         } 
  1304.         
  1305.         if($client>0){ 
  1306.             //$sql .= " AND lc.clientid = $client ";
  1307.         }
  1308.         
  1309.         if($commercial>0){ 
  1310.             //$sql .= " AND l.commercialid = $commercial ";
  1311.         }
  1312.        
  1313.         if($statutvente==2){ // En attente
  1314.             
  1315.         }
  1316.            
  1317.         if($statutvente==3){ // Aucun paiement
  1318.              
  1319.             //$sql .= " AND l.totalpaye = 0 ";
  1320.         }
  1321.           
  1322.            
  1323.         if($statutvente==4){ // Paiement partiel
  1324.            
  1325.             //$sql .= " AND l.totalpaye > 0 AND l.totalpaye < l.apayer ";
  1326.         }
  1327.           
  1328.            
  1329.         if($statutvente==5){ // Soldé
  1330.             //$sql .= " AND l.totalpaye >= l.apayer ";
  1331.         }
  1332.         
  1333.       
  1334.           if ($idproduitelement == -1) {
  1335.                 $ventes = $conn->fetchAllAssociative("
  1336.                     SELECT tc.* , SUM(ltc.total) AS total ,  SUM(ltc.quantite) AS quantite
  1337.                     FROM fournisseur f, bordereau b , typeciment tc , commande c , lignetypecommande ltc 
  1338.                     WHERE f.id = b.fournisseurid AND tc.id = ltc.typecimentid AND b.id = c.bordereauid AND c.id = ltc.commandeid 
  1339.                     AND c.datesuppressioncommande IS NULL AND ltc.datesuppressionlignetypecommande IS NULL AND tc.produitid = $id  $sql GROUP BY tc.id");  
  1340.           }else{
  1341.                 $ventes = $conn->fetchAllAssociative("
  1342.                     SELECT * FROM fournisseur f, bordereau b , typeciment tc , commande c , lignetypecommande ltc 
  1343.                     WHERE f.id = b.fournisseurid AND tc.id = ltc.typecimentid AND c.id = ltc.commandeid AND b.id = c.bordereauid 
  1344.                     AND c.datesuppressioncommande IS NULL AND ltc.datesuppressionlignetypecommande IS NULL AND tc.produitid = $id  $sql "); 
  1345.           }
  1346.             
  1347.           
  1348.        
  1349.         
  1350.         $total = 0;
  1351.         $totalpaye = 0;
  1352.         $prixunitairelignetypecommande = 0;
  1353.         $qte = 0;
  1354.         $nombre = 0;
  1355.         $lignevente = array();
  1356.         foreach($ventes as $vente){
  1357.         
  1358.                 
  1359.                 if ($idproduitelement == -1) {
  1360.                     $total += $vente['barretonne']*$vente['quantite'];
  1361.                     $totalpaye += $vente['prixtypeciment']*intval($vente['quantite']);
  1362.                     $prixunitairelignetypecommande += $vente['total'];
  1363.                     $qte += intval($vente['quantite']);
  1364.                 }else{
  1365.                     $total += $vente['barretonne']*$vente['quantite'];
  1366.                     $totalpaye += $vente['total'];
  1367.                     $prixunitairelignetypecommande += $vente['prixunitairelignetypecommande']*intval($vente['quantite']);
  1368.                     $qte += intval($vente['quantite']);            
  1369.                 }
  1370.                 $nombre++; 
  1371.             
  1372.         }
  1373.         
  1374.         
  1375.         
  1376.    
  1377.         
  1378.           
  1379.         return $this->render('rapport/rapportcommande.html.twig', [ 
  1380.             'TOTAL'=>$total,
  1381.             'TOTALPAYE'=>$totalpaye,
  1382.             'COMMANDES' => $ventes, 
  1383.             'NOMBRE'=> $nombre,
  1384.             'MONTANTTOTAL'=> $prixunitairelignetypecommande,
  1385.             'idproduitelement'=> $idproduitelement,
  1386.             'QTE'=> $qte
  1387.         ]);
  1388.      
  1389.     
  1390.     }  
  1391.     
  1392.          
  1393.     
  1394.     
  1395.     /**
  1396.      * @Route("/admin/rapportcommandevalorisation", name="rapportcommandevalorisation")
  1397.      */
  1398.     public function rapportcommandevalorisation(ManagerRegistry $doctrine, Request $request, LogActionService $logger): Response
  1399.     {
  1400.         $user = $this->getUser();
  1401.         $conn = $this->connection;
  1402.         $logger->createLog(
  1403.             'rapport_consultation',
  1404.             "Consultation du rapport « valorisation commandes »",
  1405.             $user ? $user->getId() : null,
  1406.             null, null,
  1407.             ['old' => null, 'new' => ['rapport' => 'commande_valorisation', 'filtres' => $request->query->all()]]
  1408.         );
  1409.         // Filtres
  1410.         $f_fournisseur = (int) ($request->get('fournisseurid') ?? 0);
  1411.         $f_livraison   = (string) ($request->get('livraison') ?? '');
  1412.         $f_statut      = (string) ($request->get('statutcommande') ?? '');
  1413.         $datedebut     = $request->get('datedebut');
  1414.         $datefin       = $request->get('datefin');
  1415.         $sql = "";
  1416.         if ($f_fournisseur > 0)   $sql .= " AND b.fournisseurid = $f_fournisseur";
  1417.         if (strlen($datedebut) > 7) $sql .= " AND c.datecommande >= '$datedebut'";
  1418.         if (strlen($datefin)   > 7) $sql .= " AND c.datecommande <= '$datefin'";
  1419.         if ($f_statut === 'attente') $sql .= " AND c.datevalidationcommande IS NULL AND c.dateannulationcommande IS NULL";
  1420.         elseif ($f_statut === 'validee') $sql .= " AND c.datevalidationcommande IS NOT NULL AND c.dateannulationcommande IS NULL";
  1421.         elseif ($f_statut === 'annulee') $sql .= " AND c.dateannulationcommande IS NOT NULL";
  1422.         $having = "";
  1423.         if ($f_livraison === 'aucune')         $having = " HAVING totaltonne <= 0 AND lignetotaltonne > 0";
  1424.         elseif ($f_livraison === 'partielle')  $having = " HAVING totaltonne > 0 AND totaltonne < lignetotaltonne";
  1425.         elseif ($f_livraison === 'complete')   $having = " HAVING lignetotaltonne > 0 AND totaltonne >= lignetotaltonne";
  1426.         elseif ($f_livraison === 'restant')    $having = " HAVING lignetotaltonne > 0 AND totaltonne < lignetotaltonne";
  1427.         // Détection colonnes prix
  1428.         $colsLtc = array_column($conn->fetchAllAssociative("SHOW COLUMNS FROM lignetypecommande"), 'Field');
  1429.         $colsLc  = array_column($conn->fetchAllAssociative("SHOW COLUMNS FROM lignecommande"), 'Field');
  1430.         $hasPrixLtc = in_array('prixunitairelignetypecommande', $colsLtc, true);
  1431.         $hasPrixLc  = in_array('prixunitairelignecommande', $colsLc, true);
  1432.         $sqlValCmd  = $hasPrixLtc
  1433.             ? "IFNULL((SELECT SUM(l.quantite * l.prixunitairelignetypecommande) FROM lignetypecommande l WHERE l.commandeid = c.id AND l.datesuppressionlignetypecommande IS NULL AND l.produitid = $this->idproduit),0)"
  1434.             : "0";
  1435.         $sqlValRep  = $hasPrixLc
  1436.             ? "IFNULL((SELECT SUM(l.tonne*l.quantite*l.prixunitairelignecommande) FROM lignecommande l WHERE l.commandeid = c.id AND l.datesuppressionlignecommande IS NULL AND l.produitid = $this->idproduit),0)"
  1437.             : "0";
  1438.         $commandes = $conn->fetchAllAssociative("SELECT c.id AS idc, c.numcommande, c.datecommande, c.datevalidationcommande, c.dateannulationcommande,
  1439.             b.id AS idb, b.numbordereau,
  1440.             IFNULL((SELECT f.nomfournisseur FROM fournisseur f WHERE f.id = b.fournisseurid),'-') AS nomfournisseur,
  1441.             IFNULL((SELECT SUM(l.quantite) FROM lignetypecommande l WHERE l.commandeid = c.id AND l.datesuppressionlignetypecommande IS NULL AND l.produitid = $this->idproduit),0) AS lignetotaltonne,
  1442.             $sqlValCmd AS valeur_commandee,
  1443.             IFNULL((SELECT SUM(l.tonne*l.quantite) FROM lignecommande l WHERE l.commandeid = c.id AND l.datesuppressionlignecommande IS NULL AND l.produitid = $this->idproduit),0) AS totaltonne,
  1444.             $sqlValRep AS valeur_repartie,
  1445.             IFNULL((SELECT SUM(l.tonne) FROM livraison l, lignecommande ls WHERE ls.id = l.lignecommandeid AND ls.datesuppressionlignecommande IS NULL AND l.commandeid = c.id AND l.datesuppressionlivraison IS NULL AND TRIM(l.numlivraison) <> '' AND l.produitid = $this->idproduit),0) AS totallivraisontonne
  1446.             FROM commande c, bordereau b
  1447.             WHERE c.datesuppressioncommande IS NULL AND c.produitid = $this->idproduit AND c.bordereauid = b.id $sql
  1448.             $having
  1449.             ORDER BY c.datecommande DESC, c.numcommande DESC");
  1450.         // Totaux pour KPI
  1451.         $tot_cmd_qte = 0; $tot_rep_qte = 0; $tot_livr_qte = 0;
  1452.         $tot_cmd_val = 0; $tot_rep_val = 0;
  1453.         foreach ($commandes as $r) {
  1454.             $tot_cmd_qte  += (float)$r['lignetotaltonne'];
  1455.             $tot_rep_qte  += (float)$r['totaltonne'];
  1456.             $tot_livr_qte += (float)$r['totallivraisontonne'];
  1457.             $tot_cmd_val  += (float)$r['valeur_commandee'];
  1458.             $tot_rep_val  += (float)$r['valeur_repartie'];
  1459.         }
  1460.         return $this->render('rapport/rapportcommandevalorisation.html.twig', [
  1461.             'COMMANDES'  => $commandes,
  1462.             'NOMBRE'     => count($commandes),
  1463.             'TOT_CMD_QTE'=> $tot_cmd_qte,
  1464.             'TOT_REP_QTE'=> $tot_rep_qte,
  1465.             'TOT_LIVR_QTE' => $tot_livr_qte,
  1466.             'TOT_CMD_VAL'=> $tot_cmd_val,
  1467.             'TOT_REP_VAL'=> $tot_rep_val,
  1468.             'TOT_RESTE_VAL' => $tot_cmd_val - $tot_rep_val,
  1469.             'TOT_RESTE_QTE' => $tot_cmd_qte - $tot_rep_qte,
  1470.             'F_LIVRAISON'=> $f_livraison,
  1471.             'F_STATUT'   => $f_statut,
  1472.             'F_FOURNISSEUR' => $f_fournisseur,
  1473.         ]);
  1474.     }
  1475.     /**
  1476.      * @Route("/admin/rapportstockagemagasin", name="rapportstockagemagasin")
  1477.      */
  1478.     public function rapportstockagemagasin(ManagerRegistry $doctrine,Request $request,LogActionService $logger): Response
  1479.     {
  1480.         $user = $this->getUser();
  1481.         $em =  $doctrine->getManager();
  1482.         $parametres = $this->container;
  1483.         $conn  =  $this->connection;
  1484.         $modification = true;
  1485.         $message = "";
  1486.         $statut = 0;
  1487.         $color = "red";
  1488.         $logger->createLog(
  1489.             'rapport_consultation',
  1490.             "Consultation du rapport « stockage magasin »",
  1491.             $user ? $user->getId() : null,
  1492.             null,
  1493.             null,
  1494.             ['old' => null, 'new' => ['rapport' => 'stockage_magasin', 'filtres' => $request->query->all()]]
  1495.         );
  1496.         
  1497.         $idproduitelement = $request->get('idproduitelement');
  1498.         $filtredetail = $request->get('filtredetail');
  1499.         $id = $request->get('idproduit');
  1500.         $statutvente = $request->get('statutvente')??1;
  1501.         $datedebut = $request->get('datedebut');
  1502.         $datefin   = $request->get('datefin');
  1503.         $client   = $request->get('client')??0;
  1504.         $commercial   = $request->get('commercial')??0;
  1505.         $idmagasin = $request->get('magasinid');
  1506.            
  1507.              
  1508.                     
  1509.         $sql = ""; 
  1510.                     
  1511.         if($idmagasin>0){
  1512.           $sql .= " AND lc.magasinid = $idmagasin ";
  1513.         }
  1514.  
  1515.             
  1516.         if($idproduitelement>0){
  1517.             $sql .= " AND tc.id = $idproduitelement "; 
  1518.         }
  1519.                     
  1520.         if(strlen($datedebut)>7){  
  1521.           $sql .= " AND c.datecommande >= '$datedebut' ";
  1522.         }           
  1523.         if(strlen($datefin)>7){ 
  1524.           $sql .= " AND c.datecommande <= '$datefin' ";
  1525.         } 
  1526.         
  1527.         if($client>0){ 
  1528.             $sql .= " AND lc.clientid = $client ";
  1529.         }
  1530.         
  1531.         if($commercial>0){ 
  1532.             $sql .= " AND l.commercialid = $commercial ";
  1533.         }
  1534.        
  1535.         if($statutvente==2){ // En attente
  1536.             
  1537.         }
  1538.            
  1539.         if($statutvente==3){ // Aucun paiement
  1540.              
  1541.             $sql .= " AND l.totalpaye = 0 ";
  1542.         }
  1543.           
  1544.            
  1545.         if($statutvente==4){ // Paiement partiel
  1546.            
  1547.             $sql .= " AND l.totalpaye > 0 AND l.totalpaye < l.apayer ";
  1548.         }
  1549.           
  1550.            
  1551.         if($statutvente==5){ // Soldé
  1552.             $sql .= " AND l.totalpaye >= l.apayer ";
  1553.         }
  1554.         
  1555.       
  1556.           if ($idproduitelement == -1) {
  1557.                 $ventes = $conn->fetchAllAssociative("
  1558.                     SELECT tc.* , SUM(l.tonne*ltc.prixunitairelignetypecommande) AS prixunitairelignetypecommandetotal ,  SUM(l.tonne) AS tonne , SUM(l.tonne*tc.barretonne) AS barretonnetotal , SUM(l.apayer) AS apayer , SUM(l.totalpaye) AS totalpaye FROM
  1559.                     typeciment tc , commande c , lignetypecommande ltc , lignecommande lc , livraison l
  1560.                     WHERE tc.id = ltc.typecimentid AND c.id = ltc.commandeid AND ltc.id = lc.lignetypecommandeid AND  lc.id = l.lignecommandeid 
  1561.                     AND c.datesuppressioncommande IS NULL AND ltc.datesuppressionlignetypecommande IS NULL AND lc.datesuppressionlignecommande IS NULL AND l.datesuppressionlivraison IS NULL
  1562.                     AND lc.clientid IS NULL AND lc.localiteid IS NULL AND lc.magasinid IS NOT NULL AND tc.produitid = $id  $sql GROUP BY tc.id");  
  1563.           }else{
  1564.                 $ventes = $conn->fetchAllAssociative("
  1565.                     SELECT * , 
  1566.                     IFNULL((SELECT CONCAT(client.nom,' ',client.prenom,' ',client.telephone) FROM client WHERE client.id = lc.clientid), 
  1567.                     IFNULL((SELECT nommagasin FROM magasin WHERE magasin.id = lc.magasinid),'-')) AS MYMAGASIN 
  1568.                     FROM
  1569.                     typeciment tc , commande c , lignetypecommande ltc , lignecommande lc , livraison l
  1570.                     WHERE tc.id = ltc.typecimentid AND c.id = ltc.commandeid AND ltc.id = lc.lignetypecommandeid AND  lc.id = l.lignecommandeid 
  1571.                     AND c.datesuppressioncommande IS NULL AND ltc.datesuppressionlignetypecommande IS NULL AND lc.datesuppressionlignecommande IS NULL AND l.datesuppressionlivraison IS NULL
  1572.                     AND lc.clientid IS NULL AND lc.localiteid IS NULL AND lc.magasinid IS NOT NULL AND tc.produitid = $id  $sql "); 
  1573.           }
  1574.             
  1575.           
  1576.        
  1577.         
  1578.         $total = 0;
  1579.         $totalpaye = 0;
  1580.         $prixunitairelignetypecommande = 0;
  1581.         $qte = 0;
  1582.         $nombre = 0;
  1583.         $lignevente = array();
  1584.         foreach($ventes as $vente){
  1585.         
  1586.                 
  1587.                 if ($idproduitelement == -1) {
  1588.                     $total += $vente['barretonnetotal'];
  1589.                     $totalpaye += $vente['prixtypeciment']*intval($vente['tonne']);
  1590.                     $prixunitairelignetypecommande += $vente['prixunitairelignetypecommandetotal'];
  1591.                     $qte += intval($vente['tonne']);
  1592.                 }else{
  1593.                     $total += $vente['barretonne']*$vente['tonne'];
  1594.                     $totalpaye += $vente['totalpaye'];
  1595.                     $prixunitairelignetypecommande += $vente['prixunitairelignetypecommande']*intval($vente['tonne']);
  1596.                     $qte += intval($vente['tonne']);            
  1597.                 }
  1598.                 $nombre++; 
  1599.             
  1600.         }
  1601.         
  1602.         
  1603.         
  1604.    
  1605.         
  1606.           
  1607.         return $this->render('rapport/rapportstockagemagasin.html.twig', [ 
  1608.             'TOTAL'=>$total,
  1609.             'TOTALPAYE'=>$totalpaye,
  1610.             'COMMANDES' => $ventes, 
  1611.             'NOMBRE'=> $nombre,
  1612.             'MONTANTTOTAL'=> $prixunitairelignetypecommande,
  1613.             'idproduitelement'=> $idproduitelement,
  1614.             'QTE'=> $qte
  1615.         ]);
  1616.      
  1617.     
  1618.     }  
  1619.     
  1620.  
  1621.  
  1622.     
  1623.     
  1624.     /**
  1625.      * @Route("/admin/rapportprofitperte", name="rapportprofitperte")
  1626.      */
  1627.     public function rapportprofitperte(ManagerRegistry $doctrine,Request $request,LogActionService $logger): Response
  1628.     {
  1629.         $user = $this->getUser();
  1630.         $em =  $doctrine->getManager();
  1631.         $parametres = $this->container;
  1632.         $conn  =  $this->connection;
  1633.         $modification = true;
  1634.         $message = "";
  1635.         $statut = 0;
  1636.         $color = "red";
  1637.         $logger->createLog(
  1638.             'rapport_consultation',
  1639.             "Consultation du rapport « profit / perte »",
  1640.             $user ? $user->getId() : null,
  1641.             null,
  1642.             null,
  1643.             ['old' => null, 'new' => ['rapport' => 'profit_perte', 'filtres' => $request->query->all()]]
  1644.         );
  1645.         $idproduitelement = $request->get('idproduitelement');
  1646.         $filtredetail = $request->get('filtredetail');
  1647.         $id = $request->get('idproduit');
  1648.         $statutvente = $request->get('statutvente')??1;
  1649.         $datedebut = $request->get('datedebut');
  1650.         $datefin   = $request->get('datefin');
  1651.         $client   = $request->get('client')??0;
  1652.         $commercial   = $request->get('commercial')??0;
  1653.         $idmagasin = $request->get('magasinid');
  1654.            
  1655.              
  1656.         $sql = "";  
  1657.         $sql2 = "";
  1658.         if(strlen($datedebut)>7){  
  1659.           $sql .= " AND datebordereau >= '$datedebut' ";
  1660.           $sql2 .= " AND datedepense >= '$datedebut' ";
  1661.         }           
  1662.         if(strlen($datefin)>7){ 
  1663.           $sql .= " AND datebordereau <= '$datefin' ";
  1664.           $sql2 .= " AND datedepense <= '$datefin 23:59:59' ";
  1665.         }  
  1666.         $montantversement = $conn->fetchAllAssociative("SELECT IFNULL(SUM(montantversement),0) AS MONTANT FROM bordereau WHERE datesuppressionbordereau IS NULL AND produitid = $this->idproduit $sql");  
  1667.      
  1668.         
  1669.            
  1670.              
  1671.         $sql = "";  
  1672.         if(strlen($datedebut)>7){  
  1673.           $sql .= " AND datepaiement >= '$datedebut' ";
  1674.         }           
  1675.         if(strlen($datefin)>7){ 
  1676.           $sql .= " AND datepaiement <= '$datefin' ";
  1677.         }  
  1678.         $montantpaiement = $conn->fetchAllAssociative("SELECT IFNULL(SUM(montantpaiement),0) AS MONTANT FROM paiement WHERE datesuppressionpaiement IS NULL AND produitid = $this->idproduit $sql");  
  1679.              
  1680.               
  1681.              
  1682.         $sql = "";  
  1683.         if(strlen($datedebut)>7){  
  1684.           $sql .= " AND datepaiementvente >= '$datedebut' ";
  1685.         }           
  1686.         if(strlen($datefin)>7){ 
  1687.           $sql .= " AND datepaiementvente <= '$datefin' ";
  1688.         }  
  1689.         $montantpaiementvente = $conn->fetchAllAssociative("SELECT IFNULL(SUM(montantpaiementvente),0) AS MONTANT 
  1690.         FROM paiementvente , vente
  1691.         WHERE datesuppressionpaiementvente IS NULL 
  1692.         AND paiementvente.venteid = vente.id 
  1693.         AND vente.datesuppressionvente IS NULL
  1694.         AND vente.dateannulationvente IS NULL
  1695.         AND paiementvente.produitid = $this->idproduit $sql");  
  1696.         
  1697.         $sql2 = $sql2." AND produitid = ".$this->idproduit;
  1698.              
  1699.    
  1700.         $montantdepense = $conn->fetchAllAssociative("SELECT IFNULL(SUM(montantdepense),0) AS MONTANT 
  1701.         FROM depense
  1702.         WHERE datesuppressiondepense IS NULL  $sql2");  
  1703.              
  1704.    
  1705.         
  1706.           
  1707.         return $this->render('rapport/rapportprofitperte.html.twig', [ 
  1708.             'BORDEREAU'=>$montantversement,
  1709.             'VENTEDIRECT'=>$montantpaiement,
  1710.             'VENTEMAGASIN'=>$montantpaiementvente,
  1711.             'DEPENSEMONTANT'=>$montantdepense,
  1712.         ]);
  1713.      
  1714.     
  1715.     }  
  1716.     
  1717.  
  1718.   
  1719.  
  1720.     
  1721.     
  1722.     /**
  1723.      * @Route("/admin/rapportcommercial", name="rapportcommercial")
  1724.      */
  1725.     public function rapportcommercial(ManagerRegistry $doctrine,Request $request,LogActionService $logger): Response
  1726.     {
  1727.         $user = $this->getUser();
  1728.         $em =  $doctrine->getManager();
  1729.         $parametres = $this->container;
  1730.         $conn  =  $this->connection;
  1731.         $modification = true;
  1732.         $message = "";
  1733.         $statut = 0;
  1734.         $color = "red";
  1735.         $logger->createLog(
  1736.             'rapport_consultation',
  1737.             "Consultation du rapport « commerciaux »",
  1738.             $user ? $user->getId() : null,
  1739.             null,
  1740.             null,
  1741.             ['old' => null, 'new' => ['rapport' => 'commercial', 'filtres' => $request->query->all()]]
  1742.         );
  1743.         $idproduitelement = $request->get('idproduitelement');
  1744.         $filtredetail = $request->get('filtredetail');
  1745.         $id = $request->get('idproduit');
  1746.         $statutvente = $request->get('statutvente')??1;
  1747.         $datedebut = $request->get('datedebut');
  1748.         $datefin   = $request->get('datefin');
  1749.         $client   = $request->get('client')??0;
  1750.         $commercialid   = $request->get('commercialid')??0;
  1751.         $idmagasin = $request->get('magasinid');
  1752.         $etatvente = $request->get('etatvente');
  1753.  
  1754.              
  1755.         $sql = ""; 
  1756.         $sql2 = "";  
  1757.         $sql3 = "";  
  1758.         if(strlen($datedebut)>7){  
  1759.             $sql .= " AND datebordereau >= '$datedebut' ";
  1760.             $sql2 = $sql2." AND l.datecreationlivraison >= '$datedebut'";
  1761.             $sql3 = $sql3." AND v.datevente >= '$datedebut'";
  1762.         }           
  1763.         if(strlen($datefin)>7){ 
  1764.             $sql .= " AND datebordereau <= '$datefin' ";
  1765.             $dr = date('Y-m-d', strtotime($datefin . ' +1 day'));
  1766.             $sql2 = $sql2." AND l.datecreationlivraison <= '$dr'";
  1767.             $sql3 = $sql3." AND v.datevente <= '$dr'";
  1768.         }  
  1769.         $montantversement = $conn->fetchAllAssociative("SELECT IFNULL(SUM(montantversement),0) AS MONTANT FROM bordereau WHERE datesuppressionbordereau IS NULL AND produitid = $this->idproduit $sql");  
  1770.      
  1771.         
  1772.            
  1773.              
  1774.         $sql = "";  
  1775.         if(strlen($datedebut)>7){  
  1776.           $sql .= " AND datepaiement >= '$datedebut' ";
  1777.         }           
  1778.         if(strlen($datefin)>7){ 
  1779.           $sql .= " AND datepaiement <= '$datefin' ";
  1780.         }  
  1781.         $montantpaiement = $conn->fetchAllAssociative("SELECT IFNULL(SUM(montantpaiement),0) AS MONTANT FROM paiement WHERE datesuppressionpaiement IS NULL AND produitid = $this->idproduit $sql");  
  1782.              
  1783.               
  1784.              
  1785.         $sql = "";  
  1786.         if(strlen($datedebut)>7){  
  1787.           $sql .= " AND datepaiementvente >= '$datedebut' ";
  1788.         }           
  1789.         if(strlen($datefin)>7){ 
  1790.           $sql .= " AND datepaiementvente <= '$datefin' ";
  1791.         }  
  1792.         
  1793.         if($commercialid>0){
  1794.             $sql2 .= " AND l.commercialid = $commercialid ";
  1795.             $sql3 .= " AND v.commercialid = $commercialid ";
  1796.         }
  1797.         
  1798.         if($etatvente == 1){
  1799.             $sql2 .= " AND l.apayer > 0 AND  l.totalpaye = 0 ";
  1800.             $sql3 .= " AND v.totalvente > 0 AND  v.totalpaye = 0 ";
  1801.         }
  1802.         
  1803.         if($etatvente == 2){
  1804.             $sql2 .= " AND l.apayer > 0 AND  l.totalpaye < l.apayer ";
  1805.             $sql3 .= " AND v.totalvente > 0 AND  v.totalpaye < v.totalvente ";
  1806.         }
  1807.         
  1808.         if($etatvente == 3){
  1809.             $sql2 .= " AND l.apayer > 0 AND  l.totalpaye >= l.apayer ";
  1810.             $sql3 .= " AND v.totalvente > 0 AND  v.totalpaye >= v.totalvente ";
  1811.         }
  1812.         
  1813.         $montantpaiementvente = $conn->fetchAllAssociative("SELECT IFNULL(SUM(montantpaiementvente),0) AS MONTANT 
  1814.         FROM paiementvente , vente
  1815.         WHERE datesuppressionpaiementvente IS NULL 
  1816.         AND paiementvente.venteid = vente.id 
  1817.         AND vente.datesuppressionvente IS NULL
  1818.         AND vente.dateannulationvente IS NULL
  1819.         AND paiementvente.produitid = $this->idproduit $sql");  
  1820.              
  1821.     
  1822.         $requete1 = "SELECT 
  1823.         SUM(l.apayer) AS TOTALAPAYER , SUM(l.totalpaye) AS TOTALPAYER , SUM(l.apayer - l.totalpaye) AS RESTEAPAYER , c.id , c.nom , c.prenom , COUNT(*) AS nombrelivraison
  1824.         FROM livraison l , commercial c , commande co , lignecommande lc
  1825.         WHERE 
  1826.         co.produitid = $this->idproduit AND
  1827.         lc.id = l.lignecommandeid AND c.id = l.commercialid AND  l.datesuppressionlivraison is NULL
  1828.         AND  co.id = l.commandeid AND co.datesuppressioncommande IS NULL $sql2 ";
  1829.         
  1830.         $inventairesAll = $conn->fetchAllAssociative($requete1."   ORDER BY TOTALAPAYER DESC");
  1831.         $inventaires = $conn->fetchAllAssociative($requete1." GROUP BY c.id , c.nom , c.prenom   ORDER BY TOTALAPAYER DESC;");
  1832.         
  1833.         
  1834.     
  1835.         $requete2 = "SELECT 
  1836.         SUM(v.totalvente) AS TOTALAPAYER , SUM(v.totalpaye) AS TOTALPAYER , SUM(v.totalvente - v.totalpaye) AS RESTEAPAYER , c.id , c.nom , c.prenom , COUNT(*) AS nombrelivraison
  1837.         FROM vente v , commercial c 
  1838.         WHERE 
  1839.         v.produitid = $this->idproduit AND
  1840.         v.commercialid = c.id AND  v.datesuppressionvente is NULL  $sql3 ";
  1841.         
  1842.           
  1843.         $inventairesAll2 = $conn->fetchAllAssociative($requete2."  ORDER BY TOTALAPAYER DESC");
  1844.         $inventaires2 = $conn->fetchAllAssociative($requete2." GROUP BY c.id , c.nom , c.prenom   ORDER BY TOTALAPAYER DESC;");
  1845.         
  1846.         return $this->render('rapport/rapportcommercial.html.twig', [ 
  1847.             'INVENTAIRES' => $inventaires,
  1848.             'ALLINVENTAIRES' => $inventairesAll,
  1849.             'INVENTAIRES2' => $inventaires2,
  1850.             'ALLINVENTAIRES2' => $inventairesAll2,
  1851.             'BORDEREAU'=>$montantversement,
  1852.             'VENTEDIRECT'=>$montantpaiement,
  1853.             'VENTEMAGASIN'=>$montantpaiementvente,
  1854.         ]);
  1855.      
  1856.     
  1857.     }  
  1858.     
  1859.  
  1860.  
  1861.  
  1862.             
  1863.     /**
  1864.      * @Route("/admin/rapportbordereau", name="rapportbordereau")
  1865.      */
  1866.     public function rapportbordereau(SessionInterface $sessions,Connection $conn,Request $request,LogActionService $logger): Response
  1867.     {
  1868.         $ajaxs = false;
  1869.         $user = $this->getUser();
  1870.         $em = $this->getDoctrine()->getManager();
  1871.         $parametres = $this->container;
  1872.         $sql = "";
  1873.         $logger->createLog(
  1874.             'rapport_consultation',
  1875.             "Consultation du rapport « bordereaux »",
  1876.             $user ? $user->getId() : null,
  1877.             null,
  1878.             null,
  1879.             ['old' => null, 'new' => ['rapport' => 'bordereaux', 'filtres' => $request->query->all()]]
  1880.         );
  1881.         $arrayprod = array();
  1882.         $arrayprod[] = "Ciment";
  1883.         $arrayprod[] = "Fer à Béton"; 
  1884.         $data = array();
  1885.  
  1886.         $datedebut = $request->get('datedebut');
  1887.         $datefin = $request->get('datefin');
  1888.         $etat = $request->get('etat');
  1889.         
  1890.         if(strlen($datefin)<8){
  1891.             $datefin = date('Y-m-d')." 23:59:59";
  1892.         }
  1893.         
  1894.         $fournisseurid = $request->get('fournisseurid');
  1895.         $sql = "";
  1896.         if(strlen($fournisseurid)>0){
  1897.            $sql .= " AND f.id = $fournisseurid "; 
  1898.         }
  1899.         
  1900.         if($etat==1){
  1901.             $sql .= " AND b.id IN (SELECT c.bordereauid FROM commande c WHERE c.datevalidationcommande IS NULL AND c.produitid = $this->idproduit AND c.datesuppressioncommande IS NULL ) "; 
  1902.         }
  1903.         
  1904.         if($etat==2){
  1905.             $sql .= " AND b.id IN (SELECT c.bordereauid FROM commande c WHERE c.datevalidationcommande IS NOT NULL AND c.produitid = $this->idproduit AND c.datesuppressioncommande IS NULL ) "; 
  1906.         }
  1907.         
  1908.         
  1909.         $sommebordereau = $conn->fetchAllAssociative("
  1910.         SELECT IFNULL(SUM(montantversement),0) AS TT , COUNT(*) AS NT FROM fournisseur f , bordereau  b where datebordereau BETWEEN 
  1911.         '$datedebut' AND '$datefin' AND f.id = b.fournisseurid AND datesuppressionbordereau IS NULL AND b.produitid = $this->idproduit $sql ;");
  1912.  
  1913.         $bordereaus = $conn->fetchAllAssociative("SELECT * ,
  1914.         IFNULL((SELECT SUM(l.tonne*l.quantite) FROM lignecommande l , commande c where l.commandeid = c.id AND c.bordereauid = b.id AND l.datesuppressionlignecommande is NULL AND c.datesuppressioncommande is NULL),0) AS totaltonne,
  1915.         IFNULL((SELECT SUM(l.quantite) FROM lignetypecommande l , commande c where l.commandeid = c.id AND c.bordereauid = b.id AND l.datesuppressionlignetypecommande is NULL AND c.datesuppressioncommande is NULL),0) AS totalcommande,
  1916.         IFNULL((SELECT COUNT(*) FROM  commande c where   c.bordereauid = b.id AND c.datesuppressioncommande is NULL AND dateannulationcommande is NULL),0) AS nombrebon, 
  1917.         IFNULL((SELECT SUM(l.tonne*l.quantite) FROM livraison ll , lignecommande l , commande c  where ll.numlivraison <>'' AND ll.lignecommandeid = l.id AND ll.datesuppressionlivraison IS NULL AND l.commandeid = c.id AND c.bordereauid = b.id AND l.datesuppressionlignecommande is NULL AND c.datesuppressioncommande is NULL),0) AS nombrelivrer
  1918.         FROM   fournisseur f , bordereau b 
  1919.         where datebordereau BETWEEN '$datedebut' AND '$datefin' AND b.datesuppressionbordereau is null AND b.produitid = $this->idproduit
  1920.         AND f.id = b.fournisseurid  $sql
  1921.         ORDER BY b.id DESC");
  1922.    
  1923.         $fournisseurs = $em->getRepository(Fournisseur::class)->findBy(['produitid'=>$this->idproduit,'datesuppressionfournisseur'=>null],['nomfournisseur'=>'ASC']);
  1924.         $data = [ 
  1925.             'BORDEREAUS' => $bordereaus,
  1926.             'FOURNISSEURS'=>$fournisseurs,
  1927.             'BORDEREAU'=>$sommebordereau
  1928.                 ];
  1929.  
  1930.        
  1931.         
  1932.         
  1933.         
  1934.         return $this->render('rapport/rapportbordereau.html.twig',$data);
  1935.   
  1936.     
  1937.     }
  1938.     
  1939.     
  1940. function recupererDates($option,$ddd="",$ddf="") {
  1941.     $datedebut = '2000-01-01';
  1942.     $datefin = date('Y-m-d');
  1943.     $tab = [];
  1944.     $tabval = [];
  1945.     switch ($option) {
  1946.         case 1: // Aujourd'hui
  1947.             $datedebut = date('Y-m-d');
  1948.             $datefin = date('Y-m-d');
  1949.             $tab[] = $datefin;
  1950.             $tabval[] = ['dd'=>$datedebut,'df'=>$datefin];
  1951.             break;
  1952.         case 2: // Hier
  1953.             $datedebut = date('Y-m-d', strtotime('yesterday'));
  1954.             $datefin = $datedebut;
  1955.             $tab[] = $datefin;
  1956.             $tabval[] = ['dd'=>$datedebut,'df'=>$datefin];
  1957.             break;
  1958.         case 3: // Cette semaine
  1959.             $datedebut = date('Y-m-d', strtotime('monday this week'));
  1960.             $datefin = date('Y-m-d');
  1961.             
  1962.             $currentDate = strtotime($datedebut);
  1963.             $endDate = strtotime($datefin);
  1964.             
  1965.             while ($currentDate <= $endDate) {
  1966.                 $c = date('Y-m-d', $currentDate);
  1967.                 $tab[] =  $c;
  1968.                 $currentDate = strtotime('+1 day', $currentDate); 
  1969.                 $tabval[] = ['dd'=>$c,'df'=>date('Y-m-d', $currentDate)];
  1970.             }
  1971.             
  1972.             break;
  1973.         case 4: // Semaine dernière
  1974.             $datedebut = date('Y-m-d', strtotime('monday last week'));
  1975.             $datefin = date('Y-m-d', strtotime('sunday last week'));
  1976.             
  1977.             $currentDate = strtotime($datedebut);
  1978.             $endDate = strtotime($datefin);
  1979.             
  1980.             while ($currentDate <= $endDate) {
  1981.                 $c = date('Y-m-d', $currentDate);
  1982.                 $tab[] =  $c;
  1983.                 $currentDate = strtotime('+1 day', $currentDate); 
  1984.                 $tabval[] = ['dd'=>$c,'df'=>date('Y-m-d', $currentDate)];
  1985.             }
  1986.             
  1987.             break;
  1988.         case 5: // Ce mois
  1989.             $datedebut = date('Y-m-01');
  1990.             $datefin = date('Y-m-t');
  1991.             $tab = [date('M')];
  1992.             break;
  1993.         case 6: // Mois dernier
  1994.             $datedebut = date('Y-m-01');
  1995.             $datefin = date('Y-m-t');
  1996.             //$tab = ['Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Juin', 'Jul', 'Août', 'Sep', 'Oct', 'Nov', 'Déc'];
  1997.             
  1998.             for ($i = 0; $i < 12; $i++) {
  1999.                 $tab[] = date('M', strtotime("-".($i-11)." month"));
  2000.                 $dateDebut = date('Y-m-01', strtotime("-".($i-11)." month"));
  2001.                 $dateFin = date('Y-m-t', strtotime("-".($i-11)." month")); 
  2002.                 $tabval[] = array('dd' => $dateDebut, 'df' => $dateFin);
  2003.             }
  2004.             
  2005.             break;
  2006.         case 7: // Cette année
  2007.             $datedebut = date('Y-01-01');
  2008.             $datefin = date('Y-12-31');
  2009.             $tab = [date('Y')];
  2010.             $tabval[] = array('dd' => $datedebut, 'df' => $datefin);
  2011.             break;
  2012.         case 8: // Année dernière
  2013.             $datedebut = date('Y-01-01', strtotime('last year'));
  2014.             $datefin = date('Y-12-31', strtotime('last year'));
  2015.             for($i = 0; $i<12; $i++){
  2016.                 $a = intval(date('Y'))-11+$i;
  2017.                 
  2018.                 $tab[] = $a;
  2019.                 
  2020.                 $dateDebut = date($a.'-01-01');
  2021.                 $dateFin = date($a.'-12-t'); 
  2022.                 $tabval[] = array('dd' => $dateDebut, 'df' => $dateFin);
  2023.             }
  2024.             break;
  2025.         case 9: // Depuis le début
  2026.             // Vous devez spécifier votre propre date de début ici
  2027.             // Par exemple, si votre application a commencé le 1er janvier 2020 :
  2028.             // $datedebut = '2020-01-01';
  2029.             // $datefin = date('Y-m-d');
  2030.             for($i = 0; $i<12 ; $i++){
  2031.                 $a = intval(date('Y'))-11+$i;
  2032.                 
  2033.                 $tab[] = $a;
  2034.                 
  2035.                 $dateDebut = date($a.'-01-01');
  2036.                 $dateFin = date($a.'-12-t'); 
  2037.                 $tabval[] = array('dd' => $dateDebut, 'df' => $dateFin);
  2038.             }
  2039.             break;
  2040.             case 10: // Date pre
  2041.                 $datedebut = $ddd;
  2042.                 $datefin = $ddf;
  2043.                 
  2044.                 $currentDate = strtotime($datedebut);
  2045.                 $endDate = strtotime($datefin);
  2046.                 $cv = date('Y', $currentDate);
  2047.                 $ce = date('Y', $endDate);
  2048.                 $cv2 = date('Y-m', $currentDate);
  2049.                 $ce2 = date('Y-m', $endDate);
  2050.                 if($cv!=$ce){
  2051.                     for($i = 0; $i<=(intval($ce)-intval($cv)) ; $i++){
  2052.                         $a = intval($cv)+$i;
  2053.                         
  2054.                         $tab[] = $a;
  2055.                         
  2056.                         $dateDebut = date($a.'-01-01');
  2057.                         $dateFin = date($a.'-12-t'); 
  2058.                         $tabval[] = array('dd' => $dateDebut, 'df' => $dateFin);
  2059.                     }  
  2060.                 }elseif($cv2!=$ce2){
  2061.             
  2062.                     for ($i = 0; $i < 12; $i++) {
  2063.                         $tab[] = date('M', strtotime("-".($i-11)." month"));
  2064.                         $dateDebut = date('Y-m-01', strtotime("-".($i-11)." month"));
  2065.                         $dateFin = date('Y-m-t', strtotime("-".($i-11)." month")); 
  2066.                         $tabval[] = array('dd' => $dateDebut, 'df' => $dateFin);
  2067.                     }
  2068.                     
  2069.                 }elseif($cv2==$ce2){
  2070.             
  2071.                     while ($currentDate <= $endDate) {
  2072.                         $c = date('Y-m-d', $currentDate);
  2073.                         $tab[] =  $c;
  2074.                         $currentDate = strtotime('+1 day', $currentDate); 
  2075.                         $tabval[] = ['dd'=>$c,'df'=>date('Y-m-d', $currentDate)];
  2076.                     }
  2077.                     
  2078.                 }
  2079.                 break;
  2080.         default:
  2081.             // Gérer les options invalides ou non définies ici
  2082.             for($i = 0; $i<12 ; $i++){
  2083.                 $tab[] = intval(date('Y'))-11+$i;
  2084.             }
  2085.             break;
  2086.     }
  2087.     return array('datedebut' => $datedebut, 'datefin' => $datefin,'graphe'=>$tab,'grapheval'=>$tabval);
  2088. }
  2089.     
  2090.     
  2091.     
  2092.  
  2093.     /**
  2094.      * @Route("/auth/restaurants/popularrestaurant", name="popularrestaurant")
  2095.      */
  2096.     public function popularRestaurant(Connection $conn,Request $request): Response
  2097.     {
  2098.         $ajaxs = false;
  2099.         $em = $this->getDoctrine()->getManager(); 
  2100.         
  2101.  
  2102.         $restaurants = $conn->fetchAllAssociative("SELECT * FROM restaurant where datesuppressionrestaurant is null LIMIT 20");
  2103.       
  2104.         shuffle($restaurants);
  2105.         
  2106.         return new JsonResponse($restaurants);
  2107.     
  2108.     }
  2109.         
  2110.  
  2111.     /**
  2112.      * @Route("/auth/categorie", name="categorieliste")
  2113.      */
  2114.     public function categorieList(Connection $conn,Request $request): Response
  2115.     {
  2116.         $ajaxs = false;
  2117.         $em = $this->getDoctrine()->getManager(); 
  2118.         
  2119.         $sql = "";
  2120.         
  2121.         $data = json_decode($request->getContent(), true);
  2122.          
  2123.         $boutiqueid = isset($data['boutiqueid']) ? $data['boutiqueid'] : null;
  2124.         
  2125.         $boutiqueid == null ? $sql = " " : $sql = " OR boutiqueid = $boutiqueid";
  2126.         
  2127.  
  2128.         $categories = $conn->fetchAllAssociative("SELECT * FROM categorie where datesuppressioncategorie is null AND (boutiqueid is null $sql) ORDER BY boutiqueid DESC , nomcategorie ASC;");
  2129.       
  2130.         if($boutiqueid==null){
  2131.           shuffle($categories);
  2132.         }
  2133.         
  2134.         
  2135.         return new JsonResponse($categories);
  2136.     
  2137.     }
  2138.     
  2139.    
  2140.  
  2141.     /**
  2142.      * @Route("/auth/restaurantscategorie", name="categorieid")
  2143.      */
  2144.     public function restaurantscategorie(Connection $conn,Request $request): Response
  2145.     {
  2146.         $ajaxs = false;
  2147.         $em = $this->getDoctrine()->getManager(); 
  2148.         
  2149.         
  2150.         
  2151.         $data = $_GET;  
  2152.          
  2153.         $categorieid = isset($data['categorieid']) && strlen($data['categorieid'])>0 ? $data['categorieid'] : '';
  2154.         $page = isset($data['page']) && strlen($data['page'])>0 ? $data['page'] : 1;
  2155.         $pagesize = isset($data['pagesize']) && strlen($data['pagesize'])>0 ? $data['pagesize'] : 1;
  2156.         
  2157.         $offset = intval($pagesize) * (intval($page) - 1);
  2158.         
  2159.         $sql = "";
  2160.         
  2161.         if(strlen($categorieid)>0){
  2162.             $sql = " AND id IN (SELECT p.restaurant_id FROM produit p , categorie c WHERE p.categorie_id = c.id AND c.nomcategorie LIKE '$categorieid' )"; 
  2163.         } 
  2164.          
  2165.  
  2166.         $restaurants = $conn->fetchAllAssociative("SELECT * FROM restaurant  WHERE datesuppressionrestaurant is null $sql LIMIT $pagesize OFFSET $offset");
  2167.         $categor = $conn->fetchAllAssociative("SELECT * FROM categorie  where datesuppressioncategorie is null ORDER BY boutiqueid ASC , nomcategorie ASC;");
  2168.       
  2169.         shuffle($restaurants);
  2170.         $r = array();
  2171.         $categories = array();
  2172.         
  2173.         $categories[] = ""; 
  2174.         $cats = array(); 
  2175.         foreach($categor as $rr){  
  2176.             $categories[] = $rr['nomcategorie']; 
  2177.             
  2178.             $cat = array(); 
  2179.             $cat['title'] = $rr['nomcategorie'];
  2180.             $cats[] = $cat;
  2181.         }
  2182.         foreach($restaurants as $rr){ 
  2183.             $cat = array(); 
  2184.             $cat['title'] = $rr['name'];
  2185.             $rr['categories'] = [];
  2186.             $r[] = $rr;
  2187.         }
  2188.         $restaurants = $r;
  2189.         
  2190.         $restaurant = null;
  2191.         if(sizeof($restaurants)>0){
  2192.             $restaurant = $restaurants[0];
  2193.             //$restaurants = array_merge($restaurants, $restaurants); 
  2194.             $restaurant['data'] = $restaurants;
  2195.         }
  2196.         
  2197.         
  2198.         return new JsonResponse(['status'=>200,'data'=>['restaurants'=>$restaurant,'categories'=>$categories]]);
  2199.     
  2200.     }
  2201.                 
  2202.  
  2203.     /**
  2204.      * @Route("/auth/restaurants/{id}", name="restaurants")
  2205.      */
  2206.     public function restaurants(Connection $conn,Request $request,$id=0): Response
  2207.     {
  2208.         $ajaxs = false;
  2209.         $em = $this->getDoctrine()->getManager(); 
  2210.         $sql = "";
  2211.         $sql2 = "";
  2212.         if($id>0){
  2213.             $sql = " AND  id = $id";
  2214.             $sql2 = " AND restaurant_id = $id";
  2215.         }
  2216.         
  2217.  
  2218.         $restaurants = $conn->fetchAllAssociative("SELECT * FROM restaurant WHERE 1=1  $sql AND datesuppressionrestaurant is null  LIMIT 1");
  2219.         $products = $conn->fetchAllAssociative("SELECT produit.* , restaurant.name AS restaurant ,  restaurant.logo AS logoresto FROM produit , restaurant WHERE  restaurant.id = produit.restaurant_id  $sql2   LIMIT 20");
  2220.         
  2221.         $restau = [];
  2222.         
  2223.         foreach($restaurants as $r){ 
  2224.             $r['product'] = $products;
  2225.             $json_data = $r['horairevendeur'];
  2226.             $data = json_decode($json_data, true);
  2227.             setlocale(LC_TIME, 'fr_FR.utf8'); 
  2228.             $jour_actuel = ucfirst(strftime('%A'));
  2229.             if (array_key_exists($jour_actuel, $data)) { 
  2230.                 $message_du_jour = $data[$jour_actuel]['message'];
  2231.                 $r['aujourdhui'] = $message_du_jour;
  2232.             }else{
  2233.                 $r['aujourdhui'] = "Toute la journée";
  2234.             } 
  2235.             $restau [] = $r;
  2236.         }
  2237.         
  2238.       
  2239.         return new JsonResponse(['data'=>$restau]);
  2240.     
  2241.     }
  2242.     
  2243.     
  2244.     
  2245.  
  2246.     /**
  2247.      * @Route("/auth/products/popularproduct", name="popularproduct")
  2248.      */
  2249.     public function popularproduct(Connection $conn,Request $request): Response
  2250.     {
  2251.         $ajaxs = false;
  2252.         $em = $this->getDoctrine()->getManager(); 
  2253.         
  2254.  
  2255.         $produits = $conn->fetchAllAssociative("SELECT produit.* , restaurant.name AS restaurant , restaurant.logo AS logoresto  FROM produit , restaurant WHERE restaurant.id = produit.restaurant_id  LIMIT 20");
  2256.         shuffle($produits);
  2257.         return new JsonResponse($produits);
  2258.     
  2259.     }
  2260.     
  2261.         
  2262.     
  2263.  
  2264.     /**
  2265.      * @Route("/auth/products", name="products")
  2266.      */
  2267.     public function products(Connection $conn,Request $request): Response
  2268.     {
  2269.         $ajaxs = false; 
  2270.         $em = $this->getDoctrine()->getManager(); 
  2271.         
  2272.         $data = json_decode($request->getContent(), true);  
  2273.          
  2274.         $categorieid = isset($data['categorieid']) && strlen($data['categorieid'])>0 ? $data['categorieid'] : '';
  2275.         $restaurantid = isset($data['restaurantid']) && strlen($data['restaurantid'])>0 ? $data['restaurantid'] : '';
  2276.         $page = isset($data['page']) && strlen($data['page'])>0 ? $data['page'] : 1;
  2277.         $pagesize = isset($data['pagesize']) && strlen($data['pagesize'])>0 ? $data['pagesize'] : 1;
  2278.         
  2279.         $offset = intval($pagesize) * (intval($page) - 1);
  2280.         
  2281.         $sql = "";
  2282.         
  2283.         if(strlen($categorieid)>0){
  2284.             $sql .= " AND categorie_id = $categorieid";
  2285.         }
  2286.         
  2287.         if(strlen($restaurantid)>0){
  2288.             $sql .= " AND restaurant_id = $restaurantid";
  2289.         }
  2290.         
  2291.  
  2292.         $produits = $conn->fetchAllAssociative("SELECT produit.* , restaurant.name  AS restaurant , restaurant.logo AS logoresto 
  2293.         FROM produit ,restaurant  where datesuppressionproduit is null and restaurant.id = produit.restaurant_id and datevalidationproduit is not null $sql LIMIT $pagesize OFFSET $offset;");
  2294.       
  2295.         return new JsonResponse($produits);
  2296.     
  2297.     }
  2298.         
  2299.  
  2300.     /**
  2301.      * @Route("/auth/products/{id}/reviews", name="productsreviews")
  2302.      */
  2303.     public function productsreviews(Connection $conn,Request $request,$id=0): Response
  2304.     {
  2305.         $ajaxs = false;
  2306.         $em = $this->getDoctrine()->getManager(); 
  2307.         
  2308.         $data = json_decode($request->getContent(), true);
  2309.          
  2310.         $rate = isset($data['rate']) ? $data['rate'] : 4;
  2311.  
  2312.         $avis = $conn->fetchAllAssociative("SELECT *  FROM avis WHERE rating_for_id = $id AND rate = $rate AND deleted_at is NULL  ORDER BY id DESC LIMIT 30");
  2313.       
  2314.         $a = array();
  2315.         
  2316.         
  2317.         
  2318.         foreach($avis as $av){   
  2319.             $user = $conn->fetchAllAssociative("SELECT * FROM user where id = ".$av['user_id']); 
  2320.             $av['user'] = isset($user[0])?$user[0]:null; 
  2321.             $a[] = $av;
  2322.         }
  2323.         return new JsonResponse($a);
  2324.     
  2325.     }
  2326.     
  2327.             
  2328.          
  2329.  
  2330.     /**
  2331.      * @Route("/auth/products/{id}/review", name="productsreview")
  2332.      */
  2333.     public function productsreview(Connection $conn,Request $request,$id=0): Response
  2334.     {
  2335.         $ajaxs = false;
  2336.         $em = $this->getDoctrine()->getManager(); 
  2337.         
  2338.         $data = json_decode($request->getContent(), true);
  2339.         $user = isset($data['user']) ? $data['user'] : 0;
  2340.         $rate = isset($data['rate']) ? $data['rate'] : 4;
  2341.         $feedback = isset($data['feedback']) ? $data['feedback'] : ""; 
  2342.         
  2343.         if(strlen(trim($feedback))>0){
  2344.             $client = $em->getRepository(User::class)->findOneBy(['produitid'=>$this->idproduit,"id"=>$user]);
  2345.             $avis = new Avis();
  2346.             $avis->setUserId($client);
  2347.             $avis->setRatingForId($id);
  2348.             $avis->setRate($rate);
  2349.             $avis->setFeedback($feedback);
  2350.             $avis->setCreatedAt(new \DateTime());
  2351.             $avis->setUpdatedAt(new \DateTime());
  2352.             $em->persist($avis);
  2353.             $em->flush();
  2354.         }
  2355.         
  2356.  
  2357.         $avis = $conn->fetchAllAssociative("SELECT *  FROM avis WHERE rating_for_id = $id AND deleted_at is NULL  ORDER BY id DESC LIMIT 20");
  2358.         
  2359.         $conn->executeUpdate("UPDATE  produit p set p.numrating = (select count(*) FROM avis where avis.rating_for_id = p.id) , p.rating = (select AVG(avis.rate) FROM avis where avis.rating_for_id = p.id) WHERE p.id = $id;");
  2360.       
  2361.         return new JsonResponse($avis);
  2362.     
  2363.     }
  2364.     
  2365.                 
  2366.     
  2367.  
  2368.     /**
  2369.      * @Route("/auth/categories", name="categories")
  2370.      */
  2371.     public function categories(Connection $conn,Request $request): Response
  2372.     {
  2373.         $ajaxs = false;
  2374.         $em = $this->getDoctrine()->getManager(); 
  2375.         
  2376.  
  2377.         $restaurants = $conn->fetchAllAssociative("SELECT * FROM restaurant where datesuppressionrestaurant is null");
  2378.       
  2379.         return new JsonResponse($restaurants);
  2380.     
  2381.     }
  2382.     
  2383.             
  2384.         
  2385.     
  2386.  
  2387.     /**
  2388.      * @Route("/auth/search", name="search")
  2389.      */
  2390.     public function search(Connection $conn,Request $request): Response
  2391.     {
  2392.         $ajaxs = false;
  2393.         $em = $this->getDoctrine()->getManager(); 
  2394.         
  2395.         $data = strtolower($_GET['search_query']);
  2396.  
  2397.         $produits = $conn->fetchAllAssociative("SELECT produit.* ,  restaurant.name from AS restaurant , restaurant.logo AS logoresto  FROM produit , restaurant  where    restaurant.id = produit.restaurant_id AND  LOWER(produit.name) LIKE '%$data%' ");
  2398.       
  2399.         return new JsonResponse(['Data'=>$_GET,'Products'=>$produits]);
  2400.     
  2401.     }
  2402.            
  2403.  
  2404.     /**
  2405.      * @Route("/auth/filter", name="filter")
  2406.      */
  2407.     public function filter(Connection $conn,Request $request): Response
  2408.     {
  2409.         $ajaxs = false;
  2410.         $em = $this->getDoctrine()->getManager(); 
  2411.          //{category: BFC, idrestaurant: 3, price: 40506, pricemin: 40506, rating: 4}
  2412.          
  2413.          
  2414.         $data = json_decode($request->getContent(), true);
  2415.         $category = $data['category'];
  2416.         $idrestaurant = $data['idrestaurant'];
  2417.         $idcategorie = $data['idcategorie'];
  2418.         $price = $data['price'];
  2419.         $pricemin = $data['pricemin'];
  2420.         $rating = $data['rating'];
  2421.         
  2422.         $sql = "";
  2423.         if(intval($idrestaurant)>0){
  2424.             $sql .= " AND restaurant_id = $idrestaurant ";
  2425.         }
  2426.         if(intval($idcategorie)>0){
  2427.             $sql .= " AND categorie_id = $idcategorie ";
  2428.         }
  2429.         if(intval($rating)>0){
  2430.             $sql .= " AND produit.rating =  $rating ";
  2431.         }
  2432.  
  2433.         $produits = $conn->fetchAllAssociative("SELECT produit.* , restaurant.name  AS restaurant , logo AS logoresto  FROM produit , restaurant where   restaurant.id = produit.restaurant_id AND price BETWEEN $pricemin AND $price $sql ORDER BY produit.name ASC LIMIT 50;");
  2434.       
  2435.         return new JsonResponse($produits);
  2436.     
  2437.     }
  2438.                 
  2439.         
  2440.     
  2441.  
  2442.     /**
  2443.      * @Route("/auth/resto", name="resto")
  2444.      */
  2445.     public function resto(Connection $conn,Request $request): Response
  2446.     {
  2447.         $ajaxs = false;
  2448.         $em = $this->getDoctrine()->getManager(); 
  2449.         
  2450.         $data = strtolower($_GET['search_query']);
  2451.  
  2452.         $restaurants = $conn->fetchAllAssociative("SELECT *   FROM restaurant where LOWER(name) LIKE '%$data%' ");
  2453.       
  2454.         return new JsonResponse(['Data'=>$_GET,'Restaurant'=>$restaurants]);
  2455.     
  2456.     }
  2457.     
  2458.     
  2459.     /**
  2460.      * @Route("/auth/discounts", name="discounts")
  2461.      */
  2462.     public function discounts(Connection $conn,Request $request): Response
  2463.     {
  2464.         $ajaxs = false;
  2465.         $em = $this->getDoctrine()->getManager(); 
  2466.         $promos = array();
  2467.         
  2468.         $data = $_GET;  
  2469.         
  2470.         $date = date('Y-m-d', strtotime(' -1 days'));
  2471.         $date2 = date('Y-m-d', strtotime(' -0 days'));
  2472.           
  2473.         $page = isset($data['page']) && strlen($data['page'])>0 ? $data['page'] : 1;
  2474.         $pagesize = isset($data['pagesize']) && strlen($data['pagesize'])>0 ? $data['pagesize'] : 1;
  2475.         
  2476.         $offset = intval($pagesize) * (intval($page) - 1);
  2477.         
  2478.         
  2479.         for($i=1;$i<3;$i++){
  2480.             $promotion = $conn->fetchAllAssociative("SELECT * FROM promotion where typer = $i AND datesuppressionpromotion IS NULL
  2481.             AND datecreationpromotion <= '$date' AND deadline >= '$date2' LIMIT $pagesize OFFSET $offset"); 
  2482.             $promo = array();
  2483.             foreach($promotion as $pro){ 
  2484.                 $prod = $conn->fetchAllAssociative("SELECT produit.* ,  restaurant.name  AS restaurant , logo AS logoresto  FROM produit ,restaurant  where   restaurant.id = produit.restaurant_id AND produit.id = ".$pro['product_id']);
  2485.                 if(sizeof($prod)>0){
  2486.                     $pro["product"] = $prod[0];
  2487.                     $promo[] = $pro;
  2488.                 } 
  2489.             }
  2490.             shuffle($promo);
  2491.             $promos["P$i"] = $promo; 
  2492.         }
  2493.       
  2494.         return new JsonResponse($promos);
  2495.     
  2496.         $data = json_decode($request->getContent(), true);
  2497.     }
  2498.     
  2499.      
  2500.  
  2501.     /**
  2502.      * @Route("/auth/user/addtocart", name="addtocart")
  2503.      */
  2504.     public function addtocart(Connection $conn,Request $request): Response
  2505.     {
  2506.         $ajaxs = false;
  2507.         $em = $this->getDoctrine()->getManager(); 
  2508.         
  2509.         $data = json_decode($request->getContent(), true);
  2510.         $quantity = $data['quantity'];
  2511.         $product_id = $data['product_id'];
  2512.         $token = $data['token'];
  2513.  
  2514.         //$produit = $conn->fetchAllAssociative("SELECT * FROM produit where id = $product_id;");
  2515.         
  2516.         $p = 0;
  2517.         $produit = $em->getRepository(Produit::class)->findOneBy(["id"=>$product_id]);
  2518.         $panier = $em->getRepository(Panier::class)->findOneBy(['produitid'=>$this->idproduit,"product_id"=>$product_id,'token'=>$token]);
  2519.         if($produit!=null && $panier==null){ 
  2520.             $panier = new Panier();
  2521.             $panier->setOrderId(0);
  2522.             $panier->setName($produit->getName());
  2523.             $panier->setImage($produit->getImage());
  2524.             $panier->setQuantity($quantity);
  2525.             $panier->setUnitprice($produit->getPrice());
  2526.             $panier->setPrice(intval($quantity)*intval($produit->getPrice()));
  2527.             $panier->setToken($token);
  2528.             $panier->setProductId($produit);
  2529.             $panier->setDateajout(new \DateTime());
  2530.             
  2531.             $em->persist($panier);
  2532.             $em->flush();
  2533.             
  2534.             $p = $panier->getId();
  2535.         }else if($panier!=null){
  2536.             $panier->setQuantity($quantity);
  2537.             $panier->setUnitprice($produit->getPrice());
  2538.             $panier->setPrice(intval($quantity)*intval($produit->getPrice()));
  2539.             $panier->setDateajout(new \DateTime());
  2540.             $em->persist($panier);
  2541.             $em->flush();
  2542.             $p = $panier->getId();
  2543.         }
  2544.         
  2545.         $panier = $conn->fetchAllAssociative("SELECT * , IFNULL((select r.name FROM restaurant r , produit p where p.restaurant_id = r.id AND panier.product_id = p.id),'-') AS restaurant FROM panier where id = $p;");
  2546.       
  2547.         return new JsonResponse($panier);
  2548.     
  2549.     }  
  2550.      
  2551.  
  2552.     /**
  2553.      * @Route("/auth/user/deletefromcart/{id}/{token}", name="deletefromcart")
  2554.      */
  2555.     public function deletefromcart(Connection $conn,Request $request,$id=0,$token=""): Response
  2556.     {
  2557.         $ajaxs = false;
  2558.         $em = $this->getDoctrine()->getManager(); 
  2559.         
  2560.         $data = json_decode($request->getContent(), true); 
  2561.   
  2562.         $panier = $em->getRepository(Panier::class)->findOneBy(['produitid'=>$this->idproduit,"id"=>$id,'token'=>$token]);
  2563.         
  2564.         if($panier!=null){ 
  2565.             $em->remove($panier);
  2566.             $em->flush();
  2567.         }
  2568.     
  2569.         
  2570.         $panier = $conn->fetchAllAssociative("SELECT * FROM panier where id = $p;");
  2571.       
  2572.         return new JsonResponse($panier);
  2573.     
  2574.     }  
  2575.          
  2576.  
  2577.     /**
  2578.      * @Route("/auth/user/deletefromcartresto/{id}/{token}", name="deletefromcartresto")
  2579.      */
  2580.     public function deletefromcartresto(Connection $conn,Request $request,$id=0,$token=""): Response
  2581.     {
  2582.         $ajaxs = false;
  2583.         $em = $this->getDoctrine()->getManager(); 
  2584.         
  2585.         $data = json_decode($request->getContent(), true); 
  2586.   
  2587.         $panier = $em->getRepository(Panier::class)->findOneBy(['produitid'=>$this->idproduit,"id"=>$id,'token'=>$token]);
  2588.         
  2589.         if($panier!=null){ 
  2590.             $em->remove($panier);
  2591.             $em->flush();
  2592.         }
  2593.     
  2594.         
  2595.         $panier = $conn->fetchAllAssociative("SELECT * FROM panier where id = $p;");
  2596.       
  2597.         return new JsonResponse($panier);
  2598.     
  2599.     }  
  2600.     
  2601.     
  2602.     
  2603.     
  2604.      
  2605.  
  2606.     /**
  2607.      * @Route("/auth/user/checkout", name="checkout")
  2608.      */
  2609.     public function checkout(Connection $conn,Request $request): Response
  2610.     {
  2611.         
  2612.             $em = $this->getDoctrine()->getManager(); 
  2613.         
  2614.             $data = json_decode($request->getContent(), true);
  2615.          
  2616.             $panier = isset($data['panier']) ? $data['panier'] : []; 
  2617.             $token = isset($data['token']) ? $data['token'] : ''; 
  2618.             $adresse = isset($data['adresse']) ? $data['adresse'] : ''; 
  2619.             $user = isset($data['user']) ? intval($data['user']) : 1; 
  2620.             
  2621.             $lastcmd = $em->getRepository(Commande::class)->findOneBy(['produitid'=>$this->idproduit,],['id'=>'DESC']);
  2622.             
  2623.             $codecommande = $lastcmd == null ? 1 : $lastcmd->getId()+1;
  2624.             $idcmd = 0;
  2625.             if(sizeof($panier)>0){
  2626.                 $commande = new Commande();
  2627.                 
  2628.                 $commande->setDatecommande(new \DateTime());
  2629.                 $commande->setAdresselivraison($adresse);
  2630.                 $commande->setUserid($em->getRepository(User::class)->findOneBy(['produitid'=>$this->idproduit,"id"=>$user]));
  2631.                 $commande->setCodecommande("COM-BR-".$codecommande);
  2632.                 
  2633.                 $em->persist($commande);
  2634.                 $em->flush();
  2635.                 $total = 0 ;
  2636.                 $boutik = null;
  2637.                 foreach($panier as $element){
  2638.                     $lignecommande = new Lignecommande();
  2639.                     
  2640.                     $lignecommande->setQuantite($element['quantity']);
  2641.                     $lignecommande->setPu($element['unitprice']);
  2642.                     $lignecommande->setPrixtotal($element['quantity']*$element['unitprice']);
  2643.                     $lignecommande->setIdcommande($commande);
  2644.                     $prd = $em->getRepository(Produit::class)->findOneBy(["id"=>$element['product_id']]);
  2645.                     $lignecommande->setIdproduit($prd);
  2646.                     
  2647.                     if($prd!=null){
  2648.                        $boutik = $prd->getRestaurantId();
  2649.                     }
  2650.                      
  2651.                     $em->persist($lignecommande);
  2652.                     $em->flush();
  2653.                     $total = $total + ($element['quantity']*$element['unitprice']);
  2654.                     
  2655.                 }
  2656.                 $commande->setRestaurantId($boutik);
  2657.                 $commande->setTotalcommande(intval($total));
  2658.                 $commande->setFraislivraison(0);
  2659.                 $em->persist($commande);
  2660.                 $em->flush();
  2661.                  
  2662.             } 
  2663.  
  2664.         //$commande = $conn->fetchAllAssociative("SELECT * , (select CONCAT(r.logo,'||||',r.name) FROM restaurant r , commande c , produit p , lignecommande lc where r.id = p.restaurant_id AND c.id = commande.id AND c.id = lc.idcommande AND p.id = lc.idproduit LIMIT 1) AS logorestaurant FROM commande  WHERE userid = $user ORDER BY id DESC LIMIT 60;");
  2665.         
  2666.         $commande = $conn->fetchAllAssociative("SELECT * FROM commande c WHERE userid = $user ORDER BY id DESC LIMIT 60;");
  2667.         
  2668.         $c = array();
  2669.         foreach($commande as $com){
  2670.             $datacommande = $conn->fetchAllAssociative("SELECT r.name AS restaurant , r.logo , p.name AS produit , p.image , l.* FROM lignecommande l , produit p , restaurant r 
  2671.             where r.id = p.restaurant_id AND p.id = l.idproduit AND l.idcommande = ".$com['id']);
  2672.             $com['produits'] = $datacommande;
  2673.             $c[] = $com;
  2674.         }
  2675.         
  2676.       
  2677.         return new JsonResponse($c);
  2678.     
  2679.     }      
  2680.     
  2681.     
  2682.   
  2683.     /**
  2684.      * @Route("/auth/user/orders", name="orders")
  2685.      */
  2686.     public function orders(Connection $conn,Request $request): Response
  2687.     {
  2688.         
  2689.         $em = $this->getDoctrine()->getManager(); 
  2690.     
  2691.         $data = json_decode($request->getContent(), true); 
  2692.         $token = isset($data['token']) ? $data['token'] : '';  
  2693.         $user = isset($data['user']) ? $data['user'] : 0; 
  2694.    
  2695.  
  2696.         $commande = $conn->fetchAllAssociative("SELECT * FROM commande c WHERE userid = $user ORDER BY id DESC LIMIT 60;");
  2697.         
  2698.         $c = array();
  2699.         foreach($commande as $com){
  2700.             $datacommande = $conn->fetchAllAssociative("SELECT r.name AS restaurant , r.logo , p.name AS produit , p.image , l.* FROM lignecommande l , produit p , restaurant r 
  2701.             where r.id = p.restaurant_id AND p.id = l.idproduit AND l.idcommande = ".$com['id']);
  2702.             $com['produits'] = $datacommande;
  2703.             $c[] = $com;
  2704.         }
  2705.         
  2706.       
  2707.         return new JsonResponse($c);
  2708.     
  2709.     }      
  2710.         
  2711.     
  2712.     
  2713.   
  2714.     /**
  2715.      * Legacy : ancienne route notifications héritée (table `notification` du projet
  2716.      * resto/food). Redirige vers le nouveau système app_notification.
  2717.      *
  2718.      * @Route("/auth/user/notifications", name="notifications")
  2719.      */
  2720.     public function notifications(Connection $conn,Request $request): Response
  2721.     {
  2722.         return $this->redirectToRoute('app_notifications');
  2723.         // ⬇️ Code legacy conservé pour mémoire (table `notification` supprimée). ⬇️
  2724.         $em = $this->getDoctrine()->getManager();
  2725.         $data = json_decode($request->getContent(), true);
  2726.         $token = isset($data['token']) ? $data['token'] : '';
  2727.         $user = isset($data['user']) ? $data['user'] : 0;
  2728.         $dernier = isset($data['dernier']) ? $data['dernier'] : 0;
  2729.         $date = date('Y-m-d', strtotime(' -7 days'));
  2730.         $commande = $conn->fetchAllAssociative("
  2731.         SELECT *
  2732.         ,IFNULL((select name from restaurant where id = notification.restaurantid),'') AS restaurant
  2733.         ,IFNULL((select name from produit where id = notification.platid),'') AS plat
  2734.         ,IFNULL((select codecommande from commande where id = notification.commandeid),'') AS commande
  2735.         FROM notification
  2736.         WHERE (userid = $user OR userid is NULL)
  2737.         AND datesuppressionnotification IS NULL
  2738.         AND datenotification > '$date'
  2739.         AND id > $dernier
  2740.         ORDER BY id DESC LIMIT 10;");
  2741.         
  2742.         $dam = array();
  2743.         foreach($commande as $c){
  2744.             $el = array();
  2745.             
  2746.             $el['notif'] = $c;
  2747.             $el['data']  = null;
  2748.             if($c['platid']!=null){
  2749.                 $da = $conn->fetchAllAssociative("SELECT produit.* , restaurant.name AS restaurant , logo AS logoresto FROM produit , restaurant WHERE restaurant.id = produit.restaurant_id AND produit.id  = ".$c['platid']);
  2750.                 $el['data']  = sizeof($da)>0 ? $da[0] : null;
  2751.             }
  2752.             if($c['restaurantid']!=null){
  2753.                 $da = $conn->fetchAllAssociative("SELECT * FROM restaurant WHERE id  = ".$c['restaurantid']);
  2754.                 $el['data']  = sizeof($da)>0 ? $da[0] : null;
  2755.             }
  2756.             if($c['commandeid']!=null){
  2757.                 $da = $conn->fetchAllAssociative("SELECT * FROM commande WHERE id  = ".$c['commandeid']);
  2758.                 $el['data']  = sizeof($da)>0 ? $da[0] : null;
  2759.             }
  2760.             
  2761.             $dam[] = $el;
  2762.         }
  2763.  
  2764.       
  2765.         return new JsonResponse($dam);
  2766.         return new JsonResponse($commande);
  2767.     
  2768.     }      
  2769.         
  2770.     
  2771.     
  2772.     
  2773.     
  2774.     /**
  2775.      * @Route("/auth/connexion", name="connexion")
  2776.      */
  2777.     public function connexion(Connection $conn,Request $request): Response
  2778.     {
  2779.         $ajaxs = false;
  2780.         $em = $this->getDoctrine()->getManager();
  2781.  
  2782.         $data = json_decode($request->getContent(), true);
  2783.         $type = isset($data['type']) ? $data['type'] : '';
  2784.         $dataauth = isset($data['data']) ? $data['data'] : '';
  2785.         $email = isset($data['email']) ? $data['email'] : '';
  2786.         $password = isset($data['password']) ? $data['password'] : ''; 
  2787.         $token = md5(date('Ymdhis')."stephaneogou@gmail.com");
  2788.  
  2789.         //$email = "stephaneogou@gmail.com";
  2790.         
  2791.         $data = array();
  2792.         $data['access_token'] = $token;
  2793.         $data['token_type'] = 'https';
  2794.         $data['expires_in'] = 2;
  2795.         
  2796.         $user = $em->getRepository(User::class)->findOneBy(['produitid'=>$this->idproduit,"email"=>$email]);
  2797.         if($user!=null){
  2798.             
  2799.             if($type=="gmail"){
  2800.                 //User(displayName: Ogou Stephane, email: stephaneogou@gmail.com, isEmailVerified: true, isAnonymous: false, metadata: UserMetadata(creationTime: 2024-03-16 04:46:01.365Z, lastSignInTime: 2024-03-16 05:20:19.986Z), phoneNumber: null, photoURL: https://lh3.googleusercontent.com/a/ACg8ocJuZTJ5og1YAhYtqcymKer9i8vo7ByyP69S8vrrIXRK2zg=s96-c, providerData, [UserInfo(displayName: Ogou Stephane, email: stephaneogou@gmail.com, phoneNumber: null, photoURL: https://lh3.googleusercontent.com/a/ACg8ocJuZTJ5og1YAhYtqcymKer9i8vo7ByyP69S8vrrIXRK2zg=s96-c, providerId: google.com, uid: 101736167964474266692)], refreshToken: null, tenantId: null, uid: QZO4IHQfN7RD97e2Z0xjuiM0hD13)
  2801.                 $user->setIdgmail($dataauth);
  2802.             }
  2803.             
  2804.             $user->setTypecon($type);
  2805.             $user->setToken($token);
  2806.             $user->setLastLogin(new \DateTime());
  2807.             $em->persist($user);
  2808.             $em->flush();
  2809.         }
  2810.       
  2811.         
  2812.         $user = $conn->fetchAllAssociative("SELECT * FROM user where email = '$email';");
  2813.         
  2814.         $data['user'] = isset($user[0])?$user[0]:null;
  2815.         
  2816.         return new JsonResponse($data);
  2817.     
  2818.     } 
  2819.     
  2820.         
  2821.     
  2822.     /**
  2823.      * @Route("/auth/register", name="authregister")
  2824.      */
  2825.     public function authregister(Connection $conn,Request $request,TokenAuthenticator $authenticator, GuardAuthenticatorHandler $guardHandler,AuthenticationUtils $authenticationUtils, UserPasswordHasherInterface $userPasswordHasher): Response
  2826.     {
  2827.         $ajaxs = false;
  2828.         $em = $this->getDoctrine()->getManager();
  2829.  
  2830.         $data = json_decode($request->getContent(), true);
  2831.         $type = isset($data['type']) ? $data['type'] : '';
  2832.         $dataauth = isset($data['data']) ? $data['data'] : '';
  2833.         $email = isset($data['email']) ? $data['email'] : '';
  2834.         $password = isset($data['password']) ? $data['password'] : ''; 
  2835.         $name = isset($data['name']) ? $data['name'] : ''; 
  2836.         $token = md5(date('Ymdhis')."stephaneogou@gmail.com");
  2837.  
  2838.         //$email = "stephaneogou@gmail.com";
  2839.         
  2840.         $data = array();
  2841.         $data['access_token'] = $token;
  2842.         $data['token_type'] = 'https';
  2843.         $data['expires_in'] = 2;
  2844.         
  2845.         
  2846.         $user = $em->getRepository(User::class)->findOneBy(['produitid'=>$this->idproduit,"email"=>$email]);
  2847.         if($email!="" && $user==null){
  2848.             $utilisateur = new User();
  2849.  
  2850.             $utilisateur->setEmail($email); 
  2851.             $utilisateur->setPseudo($email); 
  2852.             $utilisateur->setName($name); 
  2853.             $utilisateur->setPhonenumber(""); 
  2854.             $utilisateur->setRoles(["ROLE_CLIENT"]);   
  2855.             $utilisateur->setRestaurantid(null);
  2856.             $utilisateur->setDatecreationuser(new \DateTime());  
  2857.             $utilisateur->setMdp($password);
  2858.             $utilisateur->setPassword($userPasswordHasher->hashPassword($utilisateur,$password)); 
  2859.             $utilisateur->setIsverified(true);
  2860.             
  2861.             $em->persist($utilisateur);
  2862.             $em->flush();             
  2863.                 
  2864.         }
  2865.         
  2866.         
  2867.         
  2868.         $user = $em->getRepository(User::class)->findOneBy(['produitid'=>$this->idproduit,"email"=>$email]);
  2869.         if($user!=null){
  2870.             
  2871.             if($type=="gmail"){
  2872.                 //User(displayName: Ogou Stephane, email: stephaneogou@gmail.com, isEmailVerified: true, isAnonymous: false, metadata: UserMetadata(creationTime: 2024-03-16 04:46:01.365Z, lastSignInTime: 2024-03-16 05:20:19.986Z), phoneNumber: null, photoURL: https://lh3.googleusercontent.com/a/ACg8ocJuZTJ5og1YAhYtqcymKer9i8vo7ByyP69S8vrrIXRK2zg=s96-c, providerData, [UserInfo(displayName: Ogou Stephane, email: stephaneogou@gmail.com, phoneNumber: null, photoURL: https://lh3.googleusercontent.com/a/ACg8ocJuZTJ5og1YAhYtqcymKer9i8vo7ByyP69S8vrrIXRK2zg=s96-c, providerId: google.com, uid: 101736167964474266692)], refreshToken: null, tenantId: null, uid: QZO4IHQfN7RD97e2Z0xjuiM0hD13)
  2873.                 $user->setIdgmail($dataauth);
  2874.             }
  2875.             
  2876.             $user->setTypecon($type);
  2877.             $user->setToken($token);
  2878.             $user->setLastLogin(new \DateTime());
  2879.             $em->persist($user);
  2880.             $em->flush();
  2881.         }
  2882.       
  2883.         
  2884.         $user = null; //$conn->fetchAllAssociative("SELECT * FROM user where email = '$email';");
  2885.         
  2886.         $data['user'] = isset($user[0])?$user[0]:null;
  2887.         
  2888.         return new JsonResponse($data);
  2889.     
  2890.     } 
  2891.     
  2892.     
  2893.     
  2894.     
  2895.         
  2896.     
  2897.     /**
  2898.      * @Route("/auth/logout/{iduser}", name="logout")
  2899.      */
  2900.     public function logout(Connection $conn,Request $request,$iduser=0): Response
  2901.     {
  2902.         $ajaxs = false;
  2903.         $em = $this->getDoctrine()->getManager();
  2904.   
  2905.         $user = $conn->fetchAllAssociative("SELECT * FROM user where id = $iduser;");
  2906.         
  2907.         $data['user'] = isset($user[0])?$user[0]:null;
  2908.         
  2909.         $user = $em->getRepository(User::class)->findOneBy(['produitid'=>$this->idproduit,"id"=>$iduser]);
  2910.         if($user!=null){
  2911.             $user->setToken("");
  2912.             $user->setLastLogout(new \DateTime());
  2913.             $em->persist($user);
  2914.             $em->flush();
  2915.         }
  2916.       
  2917.         return new JsonResponse($data);
  2918.     
  2919.     } 
  2920.      
  2921.         
  2922.     
  2923.     /**
  2924.      * @Route("/mon-profil", name="mon_profil")
  2925.      */
  2926.     public function monProfil(
  2927.         Request $request,
  2928.         UserPasswordHasherInterface $userPasswordHasher,
  2929.         \App\Service\DeuxFacteursService $deuxFacteurs
  2930.     ): Response {
  2931.         $user = $this->getUser();
  2932.         if ($user === null) {
  2933.             return $this->redirectToRoute('login');
  2934.         }
  2935.         $em      = $this->getDoctrine()->getManager();
  2936.         $message = '';
  2937.         $etat    = '';
  2938.         if ($request->getMethod() === 'POST') {
  2939.             $action = $request->request->get('action', 'profil');
  2940.             if ($action === 'profil') {
  2941.                 $name  = trim((string) $request->request->get('name', ''));
  2942.                 $phone = trim((string) $request->request->get('phone', ''));
  2943.                 $user->setName($name !== '' ? $name : null);
  2944.                 $user->setPhoneNumber($phone !== '' ? $phone : null);
  2945.                 $image = $request->files->get('image');
  2946.                 if ($image) {
  2947.                     $profil = $this->fichierAction($image, '/images/client');
  2948.                     $user->setImage($profil);
  2949.                 }
  2950.                 $em->persist($user);
  2951.                 $em->flush();
  2952.                 $message = 'Profil mis à jour avec succès.';
  2953.                 $etat    = 'success';
  2954.             } elseif ($action === 'motdepasse') {
  2955.                 $actuel  = (string) $request->request->get('motdepasseactuel', '');
  2956.                 $nouveau = (string) $request->request->get('nouveaumotdepasse', '');
  2957.                 $confirm = (string) $request->request->get('confirmermotdepasse', '');
  2958.                 if ($actuel !== $user->getMdp()) {
  2959.                     $message = 'Votre mot de passe actuel est incorrect.';
  2960.                     $etat    = 'danger';
  2961.                 } elseif (strlen($nouveau) < 4) {
  2962.                     $message = 'Le nouveau mot de passe doit contenir au moins 4 caractères.';
  2963.                     $etat    = 'warning';
  2964.                 } elseif ($nouveau !== $confirm) {
  2965.                     $message = 'Le nouveau mot de passe et sa confirmation ne correspondent pas.';
  2966.                     $etat    = 'warning';
  2967.                 } else {
  2968.                     $passnew = $userPasswordHasher->hashPassword($user, $nouveau);
  2969.                     $user->setMdp($nouveau);
  2970.                     $user->setPassword($passnew);
  2971.                     $em->persist($user);
  2972.                     $em->flush();
  2973.                     $message = 'Mot de passe modifié avec succès.';
  2974.                     $etat    = 'success';
  2975.                 }
  2976.             }
  2977.         }
  2978.         return $this->render('profil/index.html.twig', [
  2979.             'USER'    => $user,
  2980.             'message' => $message,
  2981.             'etat'    => $etat,
  2982.             // Double authentification : état affiché dans la section dédiée.
  2983.             'codes_secours_restants'  => $user->isTotpActif()
  2984.                 ? $deuxFacteurs->codesSecoursRestants($user)
  2985.                 : 0,
  2986.             'appareils_de_confiance'  => $user->isTotpActif()
  2987.                 ? $deuxFacteurs->appareils($user)
  2988.                 : [],
  2989.         ]);
  2990.     }
  2991.     /**
  2992.      * @Route("/auth/user/updateprofile", name="updateprofile")
  2993.      */
  2994.     public function updateprofile(Connection $conn,Request $request): Response
  2995.     {
  2996.         $ajaxs = false;
  2997.         $em = $this->getDoctrine()->getManager();
  2998.    
  2999.        
  3000.         // Récupérer les données de la requête
  3001.    /*     $data = json_decode($request->getContent(), true);
  3002.         $image = isset($data['image']) ? $data['image'] : false;
  3003.         $name = isset($data['name']) ? $data['name'] : '';
  3004.         $phone = isset($data['phone']) ? $data['phone'] : '';
  3005.         $token = isset($data['token']) ? $data['token'] : '';
  3006.         $userId = isset($data['user']) ? $data['user'] : 0;*/
  3007.         
  3008.         $image = $request->files->get('image');
  3009.         $name = $request->request->get('name');
  3010.         $phone = $request->request->get('phone');
  3011.         $token = $request->request->get('token');
  3012.         $userId = $request->request->get('user');
  3013.         
  3014.         $user = $em->getRepository(User::class)->findOneBy(['produitid'=>$this->idproduit,"id"=>$userId]);
  3015.         if($user!=null){
  3016.             
  3017.             if ($image) {
  3018.                 $profil = $this->fichierAction($image,'/images/client');
  3019.                 $user->setImage($profil); 
  3020.             } 
  3021.             
  3022.             $user->setToken($token); 
  3023.             $user->setName($name); 
  3024.             $user->setPhonenumber($phone); 
  3025.             $em->persist($user);
  3026.             $em->flush();
  3027.         }
  3028.         
  3029.         
  3030.         $user = $conn->fetchAllAssociative("SELECT * FROM user where id = $userId;");
  3031.         
  3032.         $data['data'] = isset($user[0])?$user[0]:null;
  3033.       
  3034.         return new JsonResponse($data);
  3035.     
  3036.     } 
  3037.     
  3038.          
  3039.     
  3040.     /**
  3041.      * @Route("/privacy", name="privacy")
  3042.      */
  3043.     public function privacy(Request $request): Response
  3044.     {
  3045.         $ajaxs = false;
  3046.         $em = $this->getDoctrine()->getManager();
  3047.  
  3048.       
  3049.         return $this->render('accueil/privacy.html.twig');
  3050.     
  3051.     } 
  3052.     
  3053.     function decrypt($data) {
  3054.         $keyBytes = utf8_encode($this->keypass);
  3055.         $inputBytes = base64_decode($data);
  3056.     
  3057.         // Extract the original input bytes (excluding the HMAC digest)
  3058.         $originalInputBytes = substr($inputBytes, 0, -32);
  3059.     
  3060.         // Extract the HMAC digest from the end of the input bytes
  3061.         $hmacDigest = substr($inputBytes, -32);
  3062.     
  3063.         $data = json_decode($request->getContent(), true);
  3064.         // Recalculate the HMAC digest using the provided secret key
  3065.         $calculatedDigest = hash_hmac('sha256', $originalInputBytes, $keyBytes, true);
  3066.         $return = "";
  3067.         // Compare the calculated digest with the extracted digest
  3068.         if (hash_equals($calculatedDigest, $hmacDigest)) {
  3069.             $return =  utf8_decode($originalInputBytes);
  3070.         } else {
  3071.             $return =  "NOEXISTNUMBER"; // HMAC verification failed
  3072.         }
  3073.         
  3074.         return $return;
  3075.     }
  3076.     
  3077.  
  3078.     
  3079.     /**
  3080.      * @Route("/mobile/addmessage", name="addmessage")
  3081.      */
  3082.     public function addmessage(Connection $conn,Request $request): Response
  3083.     {
  3084.         $em = $this->getDoctrine()->getManager();
  3085.         $data = json_decode($request->getContent(), true);
  3086.         // Utilisez les données comme nécessaire
  3087.         $msg = "Aucun";
  3088.         if($request->getMethod() == 'POST' && isset($data['message'])){
  3089.             $msg =  $data['message'];
  3090.             $receveur = $this->decrypt($data['receveur']);  
  3091.             $envoyeur = $this->decrypt($data['envoyeur']);  
  3092.             $datecreation = $data['datecreation']; 
  3093.             $declenche = $data['declenche'];  
  3094.             $keymessage = $this->decrypt($data['keymessage']);  
  3095.             
  3096.             
  3097.             $messages = $conn->fetchAllAssociative("SELECT * FROM message 
  3098.             where ((RIGHT(envoyeur,8) = RIGHT($envoyeur,8) AND RIGHT(receveur,8) = RIGHT($receveur,8)) 
  3099.             OR    (RIGHT(receveur,8) = RIGHT($envoyeur,8) AND RIGHT(envoyeur,8) = RIGHT($receveur,8))) AND keymessage = '$keymessage'
  3100.             LIMIT 1");
  3101.             
  3102.             $declenche = 0;
  3103.             //$key = md5($datecreation);
  3104.             
  3105.             if((sizeof($messages)>0 && $messages[0]['envoyeur']==$envoyeur)|| sizeof($messages) == 0){
  3106.                 $declenche = 1;
  3107.             }
  3108.             
  3109.             $message = new Message();
  3110.             $message->setReceveur($receveur);
  3111.             $message->setEnvoyeur($envoyeur);
  3112.             $message->setMessage($msg);
  3113.             $message->setDatecreation(new \DateTime()); 
  3114.             $message->setLu(0);
  3115.             $message->setDeclenche($declenche);
  3116.             $message->setKeymessage($keymessage);
  3117.             
  3118.             $em->persist($message);
  3119.             $em->flush(); 
  3120.         }
  3121.         // ... faites quelque chose avec les données ...
  3122.         return new Response('Données reçues avec succès : '.$msg.' | '.$request->getMethod().' | '.$request->getContent(), 200);
  3123.     }
  3124.     
  3125.     
  3126.  
  3127.     
  3128.     /**
  3129.      * @Route("/mobile/getmessage", name="getmessage")
  3130.      */
  3131.     public function getmessage(Connection $conn,Request $request): Response
  3132.     {
  3133.         $em = $this->getDoctrine()->getManager();
  3134.         $data = json_decode($request->getContent(), true);
  3135.         // Utilisez les données comme nécessaire
  3136.         $msg = "fail";
  3137.         $messages = null;
  3138.         if($request->getMethod() == 'POST' && isset($data['telephone'])){
  3139.             
  3140.             //$messages = $em->getRepository(Message::class)->findBy(['produitid'=>$this->idproduit,"envoyeur"=>$data['telephone']]);
  3141.             
  3142.             $numero = $this->decrypt($data['telephone']);
  3143.             $dernierID = $data['dernierID'];
  3144.             
  3145.             $str = " envoyeur LIKE '%$numero' OR receveur LIKE '%$numero' ";
  3146.             
  3147.             $table = []; 
  3148.             
  3149.             for($i=1; $i<5;$i++){   
  3150.                 if(strlen($numero)>$i){
  3151.                     $table[] = substr($numero,$i,strlen($numero));
  3152.                 }
  3153.             }
  3154.             
  3155.             foreach($table as $t){
  3156.                 $str = $str." OR envoyeur LIKE '%$t' OR receveur LIKE '%$t' ";
  3157.             }
  3158.             
  3159.             $messages = $conn->fetchAllAssociative("SELECT * FROM message where id > $dernierID  AND datesuppression is null AND ($str) LIMIT 20");
  3160.             
  3161.             $msg = "success";
  3162.         }
  3163.         // ... faites quelque chose avec les données ...
  3164.  
  3165.         return new JsonResponse(['msg'=>$msg,'messages'=>$messages]);
  3166.     }
  3167.     
  3168.         
  3169.    
  3170.     
  3171.       public function trueData($datatable){
  3172.       
  3173.         $serializer = $this->container->get('serializer');
  3174.         $reports = $serializer->serialize($datatable, 'json');  
  3175.          
  3176.         
  3177.         return $reports;
  3178.     }  
  3179.     
  3180.     
  3181.     
  3182.         
  3183.     public function fichierAction($file,$chemin='/images/client'){
  3184.           
  3185.              
  3186.             $nomfichier = date('YmdHis')."-".str_replace(" ","-",$file->getClientOriginalName());    
  3187.             $fileSize = $file->getMaxFilesize();
  3188.             $extension = $file->getClientOriginalExtension();
  3189.             $minetype = $file->getClientMimeType();
  3190.            
  3191.             
  3192.            $i = 1;
  3193.            $newnomfichier = str_replace(".".$extension,"",$nomfichier);
  3194.            $defutnomfichier = str_replace(".".$extension,"",$nomfichier);
  3195.            
  3196.            $status = array('status' => "success","fileUploaded" => false);
  3197.            if(!is_null($file)){
  3198.               $path = $this->getParameter('kernel.project_dir')."/public".$chemin;
  3199.               $file->move($path,$nomfichier); // move the file to a path
  3200.               $status = array('status' => "success","fileUploaded" => true);
  3201.            }
  3202.        return $nomfichier;
  3203.     }
  3204.     /**
  3205.      * @Route("/preferences/theme", name="user_theme_update", methods={"POST"})
  3206.      */
  3207.     public function updateUserTheme(Request $request): JsonResponse
  3208.     {
  3209.         $user = $this->getUser();
  3210.         if (!$user instanceof User) {
  3211.             return new JsonResponse(['status' => 'error', 'message' => 'Non authentifie'], 401);
  3212.         }
  3213.         $theme = $request->request->get('theme');
  3214.         if (!in_array($theme, ['light', 'dark'], true)) {
  3215.             return new JsonResponse(['status' => 'error', 'message' => 'Theme invalide'], 400);
  3216.         }
  3217.         $em = $this->getDoctrine()->getManager();
  3218.         $user->setTheme($theme);
  3219.         $em->persist($user);
  3220.         $em->flush();
  3221.         return new JsonResponse(['status' => 'success', 'theme' => $theme]);
  3222.     }
  3223.     /**
  3224.      * I18N-01 — Changement de la langue d'interface par l'utilisateur.
  3225.      *
  3226.      * Deux écritures indissociables : le compte (pour retrouver sa langue à
  3227.      * la prochaine connexion, sur n'importe quel appareil) et la session
  3228.      * (pour que la page rechargée juste après soit déjà dans la bonne
  3229.      * langue). Écrire l'un sans l'autre donne un changement qui « ne prend
  3230.      * pas », ou qui s'oublie au matin.
  3231.      *
  3232.      * @Route("/preferences/langue", name="user_locale_update", methods={"POST"})
  3233.      */
  3234.     public function updateUserLocale(Request $request, LogActionService $journal): JsonResponse
  3235.     {
  3236.         $user = $this->getUser();
  3237.         if (!$user instanceof User) {
  3238.             return new JsonResponse(['status' => 'error', 'message' => 'Non authentifie'], 401);
  3239.         }
  3240.         $locale = $request->request->get('locale');
  3241.         if (!is_string($locale) || !in_array($locale, User::LOCALES_SUPPORTEES, true)) {
  3242.             return new JsonResponse(['status' => 'error', 'message' => 'Langue non prise en charge'], 400);
  3243.         }
  3244.         $avant = $user->getLocale();
  3245.         if ($avant === $locale) {
  3246.             // Rien à écrire : on ne pollue pas le journal d'actions avec des
  3247.             // clics qui ne changent rien.
  3248.             return new JsonResponse(['status' => 'success', 'locale' => $locale]);
  3249.         }
  3250.         $em = $this->getDoctrine()->getManager();
  3251.         $user->setLocale($locale);
  3252.         $em->persist($user);
  3253.         $em->flush();
  3254.         $request->getSession()->set(LocaleSubscriber::CLE_SESSION, $locale);
  3255.         $journal->audit(
  3256.             'PREFERENCE_LANGUE',
  3257.             $user,
  3258.             ['locale' => $avant],
  3259.             ['locale' => $locale],
  3260.             sprintf('Langue d\'interface changee de %s a %s', $avant, $locale)
  3261.         );
  3262.         return new JsonResponse(['status' => 'success', 'locale' => $locale]);
  3263.     }
  3264. }