src/Controller/Client/ClientController.php line 213

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Client;
  3. use App\Entity\Adresses\Adresse;
  4. use App\Entity\Articles\Article;
  5. use App\Entity\FO\Cron;
  6. use App\Entity\Articles\Compta;
  7. use App\Entity\Clients\Categorie;
  8. use App\Entity\Clients\Client;
  9. use App\Entity\Clients\HistoriqueClient;
  10. use App\Entity\Clients\Type;
  11. use App\Entity\FO\TacheCron;
  12. use App\Entity\Ged\Fichier;
  13. use App\Entity\GestionComerciale\ArticleCommande;
  14. use App\Entity\GestionComerciale\Commande;
  15. use App\Entity\Localisation\Zone;
  16. use App\Entity\Notes\Note;
  17. use App\Entity\Remises\Remise;
  18. use App\Entity\Utilisateur\Utilisateur;
  19. use App\Entity\Vehicules\VehiculeClient;
  20. use App\Form\Clients\Client2Type;
  21. use App\Form\Clients\ClientType;
  22. use App\Form\Clients\SupprimerClientType;
  23. use App\Library\Datatable\Util\Datatable;
  24. use App\Model\GestionCommerciale\TypeDocumentCommercial;
  25. use App\Security\Voter\EntityVoter;
  26. use App\Service\Clients\ClientCategorieRemiseClientService;
  27. use App\Service\Clients\ClientCategorieService;
  28. use App\Service\Clients\ClientService;
  29. use App\Service\Clients\DocumentClient;
  30. use App\Service\FO\Logo;
  31. use App\Service\GestionComerciale\AcompteService;
  32. use App\Service\GestionComerciale\NumerotationDocumentService;
  33. use App\Service\Localisation\ZoneService;
  34. use App\Service\Utilisateur\ColonneTableauService;
  35. use Doctrine\ORM\EntityManagerInterface;
  36. use JMS\Serializer\SerializerBuilder;
  37. use Knp\Component\Pager\PaginatorInterface;
  38. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  39. use Symfony\Component\Form\FormError;
  40. use Symfony\Component\HttpFoundation\JsonResponse;
  41. use Symfony\Component\HttpFoundation\Request;
  42. use Symfony\Component\HttpFoundation\Response;
  43. use Symfony\Component\Routing\Annotation\Route;
  44. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  45. use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
  46. use Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer;
  47. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  48. use Symfony\Component\Serializer\Serializer;
  49. use Symfony\Component\Validator\Validator\ValidatorInterface;
  50. use Symfony\Contracts\Translation\TranslatorInterface;
  51. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  52. class ClientController extends AbstractController
  53. {
  54.     /**
  55.      * @Route("/client/recherche", name="dtc_client_recherche")
  56.      */
  57.     public function rechercheAction(Request $requestEntityManagerInterface $emPaginatorInterface $paginatorAcompteService $serviceAcompte)
  58.     {
  59.         $user $this->getUser();
  60.         if ($user->getType()->getId() != && $user->getType()->getId() != 3) {
  61.             throw new AccessDeniedException('Accès interdit à cette page.');
  62.         }
  63.         $q            $request->query->get('q');
  64.         $parent       $request->query->get('parent');
  65.         $repo         $em->getRepository(Client::class);
  66.         $repo_adresse $em->getRepository(Adresse::class);
  67.         $results      $repo->getRechercheClient(trim($q), $parent);
  68.         $tabClient    = [];
  69.         for ($i 0$i count($results); $i++) {
  70.             if (is_null($results[$i]["cmp_id"]) or $results[$i]["cmp_id"] == 0) {
  71.                 $c $repo->find($results[$i]["id"]);
  72.                 $montant $serviceAcompte->getSoldeClient($c);
  73.             } else {
  74.                 $montant 0;
  75.             }
  76.             $results[$i]["avoir"] = round($montant2);
  77.         }
  78.         $pagination $paginator->paginate(
  79.             $results,
  80.             $request->query->getInt('page'1),
  81.             10
  82.         );
  83.         $pagination_results $pagination->getItems();
  84.         if (count($pagination_results) > 0) {
  85.             for ($i 0$i count($pagination_results); $i++) {
  86.                 $client_obj $repo->find($pagination_results[$i]["id"]);
  87.                 $pagination_results[$i]["text"]=$pagination_results[$i]["libelle"];
  88.                 if (is_object($client_obj)) {
  89.                     $adresse         $repo_adresse->findOneBy(['client' => $client_obj'visible' => 1'facturationDefaut' => 1]);
  90.                     $libelle_adresse "";
  91.                     if (is_object($adresse)) {
  92.                         if (is_object($adresse->getCodePostal())) {
  93.                             $libelle_adresse .= " ".$adresse->getCodePostal()->getCodePostal();
  94.                         }
  95.                         if (is_object($adresse->getVille())) {
  96.                             $libelle_adresse .= " ".$adresse->getVille()->getTitre();
  97.                         }
  98.                     } else {
  99.                         $adresse $repo_adresse->findOneBy(['client' => $client_obj'visible' => 1]);
  100.                         if (is_object($adresse) && is_object($adresse->getCodePostal())) {
  101.                             $libelle_adresse .= " ".$adresse->getCodePostal()->getCodePostal();
  102.                         }
  103.                         if (is_object($adresse) && is_object($adresse->getVille())) {
  104.                             $libelle_adresse .= " ".$adresse->getVille()->getTitre();
  105.                         }
  106.                     }
  107.                     $pagination_results[$i]["libelle"] = trim($pagination_results[$i]["libelle"]." (".$pagination_results[$i]["reference"]." ".trim($libelle_adresse).")");
  108.                 }
  109.             }
  110.         }
  111.         $option_placeholde = ["libelle" => "Sélectionnez""id" => ""];
  112.         if ($request->query->getInt('page'1) == 1) {
  113.             array_unshift($pagination_results$option_placeholde);
  114.         }
  115.         $pagination->setItems($pagination_results);
  116.         $serializer SerializerBuilder::create()->build();
  117.         return JsonResponse::fromJsonString($serializer->serialize($pagination'json'));
  118.     }
  119.     /**
  120.      * @Route("/client/search/", name="dtc_client_search")
  121.      */
  122.     public function searchAction(Request $requestEntityManagerInterface $em)
  123.     {
  124.         $query   $request->query->get('q');
  125.         $results $em->getRepository(Client::class)->findByRefOrName($query);
  126.         $datas = [];
  127.         foreach ($results as $result) {
  128.             $datas[] = $result;
  129.         }
  130.         $response = new JsonResponse();
  131.         $response->setData([
  132.             'items' => $datas,
  133.         ]);
  134.         return $response;
  135.     }
  136.     /**
  137.      * @Route("/client/synchro-documents/{id}/{typeDocument}", name="dtc_client_synchro_documents")
  138.      */
  139.     public function renduSynchroDocuments(Request $request,EntityManagerInterface $emClient $client,$typeDocument): Response
  140.     {
  141.         $repo_cron$em->getRepository(Cron::class);
  142.         $cron $repo_cron->findOneBy(["client"=>$client,"tacheCron"=>97,"echec"=>0,"dateFin"=>null]);
  143.         $lancer_synchro false;
  144.         $now = new \DateTime();
  145.         if (
  146.             $client->getDateSynchroDocumentsErp() === null ||
  147.             $client->getDateSynchroDocumentsErp() < (clone $now)->modify('-12 hours')
  148.         ) {
  149.             $lancer_synchro true;
  150.         }
  151.         $lancer_synchro true;
  152.         return $this->render(
  153.             'Clients/Client/synchro_document.html.twig',
  154.             [
  155.                 'lancer_synchro'=>$lancer_synchro,
  156.                 'typeDocument'=>$typeDocument,
  157.                 'cronId' => $cron $cron->getId() : null
  158.             ]
  159.         );
  160.     }
  161.     /**
  162.      * @Route("/client/import-progress/{id}", name="import_progress")
  163.      */
  164.     public function progress($idEntityManagerInterface $em)
  165.     {
  166.         $cron $em->getRepository(Cron::class)->find($id);
  167.         $status "";
  168.         if(is_object($cron->getDateFin())) $status ="finished";
  169.         return $this->json([
  170.             'status' => $status,
  171.             'progress' => $cron->getProgression()
  172.         ]);
  173.     }
  174.     /**
  175.      * @Route("/client/import-documents/{id}/{typeDocument}", name="dtc_client_import_documents")
  176.      */
  177.     public function import(Client $client,$typeDocument=""EntityManagerInterface $em)
  178.     {
  179.         $repo_tache_cron $em->getRepository(TacheCron::class);
  180.         $repo_cron $em->getRepository(Cron::class);
  181.         $tache $repo_tache_cron->find(97);
  182.         $derniersCron $repo_cron->findBy(['tacheCron' => $tache,'client'=>$client], ['date' => 'DESC'], 10);
  183.         $creer_cron true;
  184.         $cron_id 0;
  185.         if (count($derniersCron) > 0) {
  186.             if (is_object($derniersCron[0]) && $derniersCron[0]->getDateFin() == null) {
  187.                 /*
  188.                 $pid = $derniersCron[0]->getPid();
  189.                 if (!file_exists("/proc/$pid")) {
  190.                     $derniersCron[0]->setDateFin($dateTmp);
  191.                     $derniersCron[0]->setEchec(true);
  192.                     $em->persist($derniersCron[0]);
  193.                     $em->flush();
  194.                 }
  195.                 */
  196.                 if (is_object($derniersCron[0]->getDateDebut()) && $derniersCron[0]->getDateDebut() < new \DateTime('-5 minutes')) {
  197.                     $derniersCron[0]->setDateFin(new \DateTime());
  198.                     $derniersCron[0]->setEchec(true);
  199.                     $em->persist($derniersCron[0]);
  200.                     $em->flush();
  201.                 }
  202.             }
  203.             if (is_object($derniersCron[0]) && $derniersCron[0]->getDateFin() == null) {
  204.                 $date = new \Datetime();
  205.                 $libelle_cron $derniersCron[0]->getLibelle()." Cron non terminé à ".$date->format("Y-m-d H:i:s");
  206.                 $libelle_cron substr($libelle_cronstrlen($libelle_cron) - 250);
  207.                 $derniersCron[0]->setLibelle($libelle_cron);
  208.                 $derniersCron[0]->setDescription($derniersCron[0]->getDescription()." Cron non terminé à ".$date->format("Y-m-d H:i:s"));
  209.                 $em->persist($derniersCron[0]);
  210.                 $em->flush();
  211.                 $creer_cron false;
  212.                 $cron_id $derniersCron[0]->getId();
  213.             }
  214.         }
  215.         if($creer_cron) {
  216.             $cron = new Cron();
  217.             $cron->setLibelle("Import des commandes depuis ERP DTC client_id:".$client->getId());
  218.             $cron->setClient($client);
  219.             $cron->setTacheCron($tache);
  220.             $cron->setEchec(false);
  221.             $cron->setProgression(rand(515));
  222.             $em->persist($cron);
  223.             $em->flush();
  224.             $em->refresh($cron);
  225.             $cron_id $cron->getId();
  226.             $cmd sprintf(
  227.                 'php %s/bin/console import:commandes %d %s %d > /dev/null 2>&1 &',
  228.                 $this->getParameter('kernel.project_dir'),
  229.                 $client->getId(),
  230.                 $typeDocument,
  231.                 $cron_id
  232.             );
  233.             exec($cmd$output);
  234.             $pid = isset($output[0]) ? (int)$output[0] : null;
  235.             $cron->setPid($pid);
  236.             $em->persist($cron);
  237.             $em->flush();
  238.         }
  239.         return $this->json(['cronId' => $cron_id]);
  240.     }
  241.     /**
  242.      * @Route("/client/export", name="export_client")
  243.      */
  244.     public function exportClient(EntityManagerInterface $em): Response
  245.     {
  246.         $user $this->getUser();
  247.         if ($user->getType()->getId() != 1) {
  248.             throw new AccessDeniedException('Accès interdit à cette page.');
  249.         }
  250.         $users $em->getRepository(Utilisateur::class)->findBy([
  251.             'type' => [4]
  252.         ]);
  253.         $handle fopen('php://temp''r+');
  254.         // BOM UTF-8 pour Excel
  255.         fwrite($handle"\xEF\xBB\xBF");
  256.         // Entêtes
  257.         fputcsv($handle, ['id''email''nom','prenom','ref_client','nom_client','actif','api'], ';');
  258.         // Données
  259.         foreach ($users as $u) {
  260.             $client "";
  261.             $ref_client "";
  262.             if($u->getClient()) {
  263.                 $client $u->getClient()->getNom();
  264.                 $ref_client $u->getClient()->getReference();
  265.                 $api $u->getClient()->isStatutApi();
  266.                 $actif 1;
  267.                 if(!is_null($u->getDateSuppression())) $actif=0;
  268.                 fputcsv($handle, [
  269.                     $u->getId(),
  270.                     $u->getEmail(),
  271.                     $u->getNom(),
  272.                     $u->getPrenom(),
  273.                     $ref_client,
  274.                     $client,
  275.                     $actif,
  276.                     $api,
  277.                 ], ';');
  278.             }
  279.         }
  280.         rewind($handle);
  281.         $csvContent stream_get_contents($handle);
  282.         fclose($handle);
  283.         $response = new Response($csvContent);
  284.         $filename 'clients_' date('Y-m-d_H-i-s') . '.csv';
  285.         $response->headers->set('Content-Type''text/csv; charset=UTF-8');
  286.         $response->headers->set(
  287.             'Content-Disposition',
  288.             'attachment; filename="' $filename '"'
  289.         );
  290.         $response->headers->set('Pragma''no-cache');
  291.         $response->headers->set('Expires''0');
  292.         return $response;
  293.     }
  294. }