src/Controller/AccueilController.php line 327

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