src/Controller/HomeController.php line 769

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Service\EdenAiHelperMethods;
  4. use Doctrine\ORM\EntityRepository;
  5. use App\Entity\Achat;
  6. use App\Entity\Vente;
  7. use App\Entity\Client;
  8. use App\Entity\TmpOcr;
  9. use App\Entity\Galerie;
  10. use App\Entity\Lot;
  11. use App\Entity\Pret;
  12. use App\Entity\EmailDocumentPreview;
  13. use App\Form\AchatType;
  14. use App\Form\FournisseursType;
  15. use App\Form\ChantierType;
  16. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  17. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  18. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  19. use Symfony\Component\HttpFoundation\JsonResponse;
  20. use Symfony\Component\Routing\Generator\UrlGenerator;
  21. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  22. use Symfony\Component\Config\Definition\Exception\Exception;
  23. use Symfony\Component\HttpFoundation\Request;
  24. use Symfony\Component\HttpFoundation\Response;
  25. use Symfony\Component\Routing\Annotation\Route;
  26. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  27. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  28. use Symfony\Component\HttpFoundation\Session\Session;
  29. use App\Entity\Fournisseurs;
  30. use App\Entity\Chantier;
  31. use App\Entity\Entreprise;
  32. use App\Entity\Tva;
  33. use App\Entity\Devise;
  34. use App\Repository\ChantierRepository;
  35. use App\Repository\HoraireRepository;
  36. use App\Repository\PaieRepository;
  37. use App\Repository\FournisseursRepository;
  38. use App\Repository\UtilisateurRepository;
  39. use App\Repository\VenteRepository;
  40. use App\Repository\AchatRepository;
  41. use App\Repository\EntrepriseRepository;
  42. use App\Repository\GalerieRepository;
  43. use Pagerfanta\Adapter\ArrayAdapter;
  44. use App\Service\GlobalService;
  45. use Carbon\Carbon;
  46. use Pagerfanta\Pagerfanta;
  47. use Symfony\Component\Mailer\MailerInterface;
  48. use Symfony\Component\Mime\Email;
  49. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  50. use App\Repository\MetaConfigRepository;
  51. // On utilise Algoria
  52. use Algolia\AlgoliaSearch\SearchClient;
  53. use Aws\S3\S3Client;
  54. use Aws\Exception\AwsException;
  55. use Ilovepdf\Ilovepdf;
  56. use Ilovepdf\CompressTask;
  57. // Imports the Google Cloud client library
  58. use Google\ApiCore;
  59. use Google\Auth;
  60. use \ConvertApi\ConvertApi;
  61. use ZipArchive;
  62. use setasign\Fpdi\Fpdi;
  63. use Spipu\Html2Pdf\Html2Pdf;
  64. use Spipu\Html2Pdf\Exception\Html2PdfException;
  65. use App\Controller\PretController;
  66. use App\Entity\OcrField;
  67. use App\Entity\TmpExpense;
  68. use App\Repository\TmpOcrRepository;
  69. use App\Service\ArticleExtractService;
  70. use App\Service\FactureService;
  71. use App\Service\FindNumBLService;
  72. use App\Service\GoogleHelperMethods;
  73. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  74. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  75. class HomeController extends Controller
  76. {
  77.     private $global_s;
  78.     private $chantierRepository;
  79.     private $achatRepository;
  80.     private $entrepriseRepository;
  81.     private $fournisseurRepository;
  82.     private $venteRepository;
  83.     private $galerieRepository;
  84.     private $utilisateurRepository;
  85.     private $PaieRepository;
  86.     private $horaireRepository;
  87.     private $session;
  88.     private $pretController;
  89.     public $edenAi;
  90.     public $articleExtractService;
  91.     public $googleHelperMethods;
  92.     public $params;
  93.     private $tmpOcrRepository;
  94.     private $findNumBLService;
  95.     public function __construct(FindNumBLService $findNumBLServiceTmpOcrRepository $tmpOcrRepositoryParameterBagInterface $paramsGoogleHelperMethods $googleHelperMethodsArticleExtractService $articleExtractServiceEdenAiHelperMethods $edenAiGlobalService $global_sGalerieRepository $galerieRepositoryChantierRepository $chantierRepositoryAchatRepository $achatRepositoryEntrepriseRepository $entrepriseRepositoryFournisseursRepository $fournisseurRepositoryPaieRepository $paieRepositoryVenteRepository $venteRepositoryHoraireRepository $horaireRepositoryUtilisateurRepository $utilisateurRepositorySessionInterface $sessionPretController $pretControllerMetaConfigRepository $metaConfigRepository)
  96.     {
  97.         $this->global_s $global_s;
  98.         $this->chantierRepository $chantierRepository;
  99.         $this->galerieRepository $galerieRepository;
  100.         $this->venteRepository $venteRepository;
  101.         $this->utilisateurRepository $utilisateurRepository;
  102.         $this->fournisseurRepository $fournisseurRepository;
  103.         $this->achatRepository $achatRepository;
  104.         $this->entrepriseRepository $entrepriseRepository;
  105.         $this->paieRepository $paieRepository;
  106.         $this->horaireRepository $horaireRepository;
  107.         $this->pretController $pretController;
  108.         $this->metaConfigRepository $metaConfigRepository;
  109.         $this->session $session;
  110.         $this->edenAi $edenAi;
  111.         $this->articleExtractService $articleExtractService;
  112.         $this->googleHelperMethods $googleHelperMethods;
  113.         $this->params $params;
  114.         $this->tmpOcrRepository $tmpOcrRepository;
  115.         $this->findNumBLService $findNumBLService;
  116.     }
  117.     public function getBaseUrl()
  118.     {
  119.         $baseUrl $this->generateUrl('home', [], UrlGenerator::ABSOLUTE_URL);
  120.         return new Response($baseUrl);
  121.     }
  122.     /**
  123.      * @Route("/merge", name="page_merge")
  124.      */
  125.     public function mergeImage()
  126.     {
  127.         // $ilovepdf = new Ilovepdf('project_public_931609e2e0edbf50c10eaeb858e470f3_fsjDZdb3b9cdf88dab190f9056c68e18de17a','secret_key_2b723a927cff7ba74a71d1fdfad73a9e_wF2qzfa225b5b9be2dbcc23bc29ba9b4c0722');
  128.         // $filename = "20220108110103_00161d96b2f6c9d3.jpg";
  129.         //     $myTask = $ilovepdf->newTask('imagepdf');
  130.         //     $file1 = $myTask->addFile($this->get('kernel')->getProjectDir() . "/public/uploads/achats/facturation/".$filename);
  131.         //     $myTask->execute();
  132.         //     $myTask->setOutputFilename("test.pdf");
  133.         //     $myTask->download($this->get('kernel')->getProjectDir() . "/public/uploads/achats/facturation/");
  134.         //     dd($file1);
  135.         return new Response('d');
  136.     }
  137.     /**
  138.      * @Route("/503/{type}", name="page_503")
  139.      */
  140.     public function page503(Request $request$type false)
  141.     {
  142.         $this->global_s->cronOcrIa(null$type);
  143.         dd('sds');
  144.         return $this->render('error/503.html.twig');
  145.     }
  146.     /**
  147.      * @Route("/ocr", name="lancer_ocr")
  148.      */
  149.     public function ocr(Request $request)
  150.     {
  151.         if (is_null($this->getUser()))
  152.             $this->generateUrl("security_login", [], UrlGenerator::ABSOLUTE_URL);
  153.         $this->global_s->cronOcrImportDocument();
  154.         //$this->global_s->cronOcrIa();
  155.         dd('Opération terminée');
  156.     }
  157.     /**
  158.      * @Route("/import", name="page_import")
  159.      */
  160.     public function import(Request $request)
  161.     {
  162.         $this->global_s->cronOcrImportDocument();
  163.         dd("import");
  164.     }
  165.     /**
  166.      * @Route("/get-adresse", name="page_import")
  167.      */
  168.     public function getAdresseApi(Request $request)
  169.     {
  170.         $chaine "Mme Pascale HUWART 42 Rue gambetta 62000 ARRAS";
  171.         $url 'https://api-adresse.data.gouv.fr/search/?q='.str_replace(' ','+'$chaine);
  172.         $curlHandle curl_init();
  173.         curl_setopt($curlHandleCURLOPT_URL$url);
  174.         curl_setopt($curlHandleCURLOPT_RETURNTRANSFERTRUE);
  175.         $response curl_exec($curlHandle);
  176.         $httpCode curl_getinfo($curlHandleCURLINFO_HTTP_CODE);
  177.         if($httpCode == 200){
  178.             $resultat json_decode($response);
  179.             if(count($resultat->features)){
  180.                 $resultat $resultat->features[0];
  181.                 $resultat $resultat->properties;
  182.                 if($resultat){
  183.                     return[
  184.                         'adresse' => $resultat->name,
  185.                         'cp' => $resultat->postcode,
  186.                         'ville' => $resultat->city
  187.                     ];
  188.                 }
  189.             }
  190.         }
  191.     }
  192.     /**
  193.      * @Route("/split-pdf", name="pdf_split")
  194.      */
  195.     public function testPDFSplit(){
  196.         $outputDir $this->get('kernel')->getProjectDir(). "/public/uploads/factures/";
  197.         $fileToSplit base64_encode(file_get_contents($outputDir."test_to_split.pdf"));
  198.         $filename "test_to_split.pdf";
  199.         //$this->googleHelperMethods->simpleSplitPDF($filename, $fileToSplit, $outputDir);
  200.         //Mergin
  201.         $filename1 "test_to_split-1.pdf";
  202.         $filename2 "test_to_split-2.pdf";
  203.         $fileToSplit1 base64_encode(file_get_contents($outputDir."test_to_split-1.pdf"));
  204.         $fileToSplit2 base64_encode(file_get_contents($outputDir."test_to_split-2.pdf"));
  205.         $fileDatas = [];
  206.         $fileDatas[] = [
  207.             'Name' => $filename1,
  208.             'Data' => $fileToSplit1,
  209.         ];
  210.         $fileDatas[] = [
  211.             'Name' => $filename2,
  212.             'Data' => $fileToSplit2,
  213.         ];
  214.         $fileNameBase "test_to_split.pdf";
  215.         dd($this->googleHelperMethods->simpleMergePDF($fileDatas$outputDir$fileNameBase"1-2"));
  216.     }
  217.     public function rotateIfPaysage($dir$file$angle)
  218.     {
  219.         try {
  220.             if (file_exists($file)) {
  221.                 $ilovepdf = new Ilovepdf('project_public_931609e2e0edbf50c10eaeb858e470f3_fsjDZdb3b9cdf88dab190f9056c68e18de17a''secret_key_2b723a927cff7ba74a71d1fdfad73a9e_wF2qzfa225b5b9be2dbcc23bc29ba9b4c0722');
  222.                 // $pdf = new Fpdi();
  223.                 // $pdf->setSourceFile($file);
  224.                 for ($i 1$i <= 1$i++) {
  225.                     // $tpl = $pdf->importPage($i); 
  226.                     // $size = $pdf->getTemplateSize($tpl); 
  227.                     // $pdf->addPage(); 
  228.                     // $pdf->useTemplate($tpl); 
  229.                     $myTask $ilovepdf->newTask('rotate');
  230.                     $file1 $myTask->addFile($file);
  231.                     $file1->setRotation($angle);
  232.                     $myTask->execute();
  233.                     $myTask->setOutputFilename("test");
  234.                     $myTask->download($dir);
  235.                 }
  236.             }
  237.         } catch (\Exception $e) {
  238.             throw new \Exception($e->getMessage(), 1);
  239.         }
  240.     }
  241.     /**
  242.      * @param EmailDocumentPreview $docId // chemin vers le fichier
  243.      * @param mixed $debug  // mode
  244.      * @return mixed   // tableau contenant la réponse
  245.      * @Route("/get_articles_item_scan/{docId}/load/{debug}", name="get_articles_item_scan")
  246.      */
  247.     public function extractArticleItem(EmailDocumentPreview $docId$debug 0){
  248.         $datas $this->articleExtractService->extractArticle($docId);
  249.         if($debug){
  250.             dd($datas);
  251.         }
  252.         return new Response(json_encode($datas));
  253.     }
  254.     /**
  255.      * @return mixed   // tableau contenant la réponse
  256.      * @Route("/google_response_debug/{docID}", name="get_google_articles")
  257.      */
  258.     public function extractArticleItemFromGoogle(EmailDocumentPreview $docID){
  259.         $filenamePDF $docID->getDocument();
  260.         $filenamePDF $this->googleHelperMethods->getDirDosssier($docID->getDossier(), $this->params) . $filenamePDF;
  261.         $resultat $this->googleHelperMethods->extractFromGoogle(null$filenamePDF$this->paramsnulltrue);
  262.         dd(['Fichier PDF' => $filenamePDF'Scan Google' => $resultat]);
  263.         return new Response(json_encode($resultat));
  264.     }
  265.     /**
  266.      * @Route("/document-rotation", name="document_rotation")
  267.      */
  268.     public function documentRotation(Request $request)
  269.     {
  270.         $pdfDir $request->query->get('pdf');
  271.         $rotation = (int)$request->query->get('rotation');
  272.         $dossier $request->query->get('dossier');
  273.         $arr explode('/'$pdfDir);
  274.         $pdf array_pop($arr);
  275.         $dir $this->get('kernel')->getProjectDir() . "/public" implode('/'$arr);
  276.         $pdfDir $dir '/' $pdf;
  277.         try {
  278.             $this->rotateIfPaysage($dir$pdfDir$rotation);
  279.         } catch (\Exception $e) {
  280.             return new Response(json_encode([
  281.                 'status' => 400,
  282.                 'message' => $e->getMessage()
  283.             ]));
  284.         }
  285.         $docPreview =  $this->getDoctrine()->getRepository(EmailDocumentPreview::class)->findOneBy(['dossier' => $dossier'document' => $pdf]);
  286.         if (!is_null($docPreview)) {
  287.             $docPreview->setIsConvert(false);
  288.             $docPreview->setExecute(false);
  289.         }
  290.         $em $this->getDoctrine()->getManager();
  291.         $imagename strtolower($pdf);
  292.         $imagename str_replace(".pdf"'.jpg'$imagename);
  293.         $em->getRepository(TmpOcr::class)->removesAll($dossier$imagename);
  294.         $em->flush();
  295.         $urlRedirect "";
  296.         switch ($dossier) {
  297.             case 'facturation':
  298.                 $urlRedirect "facturation_import_document";
  299.                 break;
  300.             case 'bon_livraison':
  301.                 $urlRedirect "bon_livraison_import_document";
  302.                 break;
  303.             case 'devis_pro':
  304.                 $urlRedirect "devis_pro_import_document";
  305.                 break;
  306.             case 'facture_client':
  307.                 $urlRedirect "facture_client_import_document";
  308.                 break;
  309.             case 'devis_client':
  310.                 $urlRedirect "devis_client_import_document";
  311.                 break;
  312.             case 'paie':
  313.                 $urlRedirect "paie_import_document";
  314.                 break;
  315.         }
  316.         if ($urlRedirect != "") {
  317.             return new Response(json_encode([
  318.                 'status' => 200,
  319.                 "datas" => [
  320.                     'redirect' => $this->generateUrl($urlRedirect, ['scan' => 1], UrlGenerator::ABSOLUTE_URL)
  321.                 ]
  322.             ]));
  323.         }
  324.     }
  325.     /**
  326.      * @Route("/testPdf", name="home_test_pdf")
  327.      */
  328.     public function testPdf()
  329.     {
  330.         $products = [];
  331.         for ($i 0$i 9$i++) {
  332.             $products[] =
  333.                 array(
  334.                     'number' => '',
  335.                     'title' => 'Devis n°687 du 22/09/2021',
  336.                     'description' => 'Annule et remplace le devis 668 changement de modeconstructif',
  337.                     'qte' => '1.0000',
  338.                     'u' => 'U',
  339.                     'pu' => '350,00 €',
  340.                     'rem' => '',
  341.                     'total' => '350,00 €',
  342.                     'tva' => '20,00'
  343.                 );
  344.         }
  345.         if (count($products) <= 6)
  346.             $nbPage 1;
  347.         else
  348.             $nbPage ceil((count($products) - 6) / 19) + 1;
  349.         $html $this->renderView('home/testPdfGenerate.html.twig', [
  350.             'products' => $products,
  351.             'nbPage' => $nbPage
  352.         ]);
  353.         $html2pdf = new Html2Pdf('P''A4''fr'true'UTF-8', array(0000));
  354.         $html2pdf->addFont('helveticab'''realpath($_SERVER["DOCUMENT_ROOT"]) . '/fonts/helveticaBoldItalic/helveticab.php');
  355.         $html2pdf->addFont('helveticaob'''realpath($_SERVER["DOCUMENT_ROOT"]) . '/fonts/helveticaOblique/helveticaob.php');
  356.         $html2pdf->addFont('helveticabold'''realpath($_SERVER["DOCUMENT_ROOT"]) . '/fonts/helveticabold/helveticabold.php');
  357.         $html2pdf->addFont('helveticabl'''realpath($_SERVER["DOCUMENT_ROOT"]) . '/fonts/helveticaligth/helveticabl.php');
  358.         $html2pdf->writeHTML($html);
  359.         $html2pdf->output('credit.pdf');
  360.         return $html2pdf->stream("pdf_filename.pdf", array("Attachment" => false));
  361.     }
  362.     public function getAmmortissements($annee)
  363.     {
  364.         $prets $this->getDoctrine()->getRepository(Pret::class)->findBy(['entreprise' => $this->session->get('entreprise_session_id')]);
  365.         $amortissementsArr = [];
  366.         foreach ($prets as $pret) {
  367.             $dateDebut $pret->getDateDeblocage();
  368.             $debutPrelevementInteret $pret->getDebutPrelevementInteret();
  369.             $montantEcheance1 = (float)$pret->getMontantEcheance1();
  370.             $montantEcheance1 = (float)$pret->getMontantEcheance1();
  371.             $interet1 = (float)$pret->getInteret1();
  372.             $remboursement1 = (float)$pret->getRemboursement1();
  373.             $datePremiereEcheance $pret->getDatePremiereEcheance();
  374.             $montantPret = (float)$pret->getCapital();
  375.             $duree = (int)$pret->getDuree();
  376.             $taux = (float)$pret->getTaux();
  377.             $tauxAssurance = (float)$pret->getTauxAssurance();
  378.             $typeDiffere = (int)$pret->getDiffere();
  379.             $dureeDiffere = (int)$pret->getDureeDiffere();
  380.             $amortissements $this->pretController->calculAmortissement($pret$dateDebut$montantPret$duree$taux$tauxAssurance$typeDiffere$dureeDiffere$debutPrelevementInteret$montantEcheance1$datePremiereEcheance$interet1$remboursement1$annee)['amortissements'];
  381.             foreach ($amortissements as $value) {
  382.                 if (($value['date'])->format('Y') == $annee) {
  383.                     $amortissementsArr[($value['date'])->format('Y-m')][] = ['pret' => $pret->getId(), 'date' => ($value['date'])->format('Y-m-d'), 'mensualite_avec_assurance' => $value['mensualite_avec_assurance']];
  384.                 }
  385.             }
  386.         }
  387.         $amortissementsArr array_map(function ($amortissement) {
  388.             return [
  389.                 'date' => $amortissement[0]['date'],
  390.                 'mensualite_avec_assurance' => array_reduce(
  391.                     $amortissement,
  392.                     function ($sum$item) {
  393.                         return $sum $item['mensualite_avec_assurance'];
  394.                     }
  395.                 )
  396.             ];
  397.         }, $amortissementsArr);
  398.         return $amortissementsArr;
  399.     }
  400.     /**
  401.      * @Route("/", name="home")
  402.      */
  403.     public function index(Request $requestSession $session)
  404.     {
  405.         $form $request->request->get('form'null);
  406.         $fournisseurId $chantierId $clientId =  null;
  407.         $moisList array_flip($this->global_s->getMois());
  408.         if ($form) {
  409.             $mois null;
  410.             $monthText = !is_null($mois) ? $moisList[$mois] : "";
  411.             $annee = (!(int)$form['annee']) ? null : (int)$form['annee'];
  412.             $session->set('home_mois_bl'$mois);
  413.             $session->set('home_annee_bl'$annee);
  414.             $session->set('home_chantier_bl'$chantierId);
  415.         } else {
  416.             $day explode('-', (new \DateTime())->format('Y-m-d'));
  417.             $mois =  $session->get('home_mois_bl') ?? null;
  418.             $monthText $mois $moisList[$mois] : "";
  419.             $annee $session->get('home_annee_bl') ?? $day[0];
  420.             $chantierId $session->get('home_chantier_bl') ?? null;
  421.         }
  422.         $form $this->createFormBuilder(array(
  423.             'annee' => $annee,
  424.         ))
  425.             ->add('annee'ChoiceType::class, array(
  426.                 'label' => "Année",
  427.                 'choices' => $this->global_s->getAnnee(),
  428.                 'attr' => array(
  429.                     'class' => 'form-control'
  430.                 )
  431.             ))->getForm();
  432.         $entityManager $this->getDoctrine()->getManager();
  433.         $montant $entityManager->getRepository(Achat::class)->countMontantByfacturedGroupDate($mois$annee'bon_livraison'$chantierId$fournisseurId);
  434.         $montantNonRelie $entityManager->getRepository(Achat::class)->countMontantByfacturedGroupDate($mois$annee'bon_livraison'$chantierId$fournisseurIdnullfalse);
  435.         $montantPayeFact $entityManager->getRepository(Achat::class)->countMontantByfacturedPayeDate($mois$annee'facturation'$chantierId$fournisseurId);
  436.         $montantFact $entityManager->getRepository(Achat::class)->countMontantByfacturedGroupDate($mois$annee'facturation'$chantierId$fournisseurId);
  437.         $montantFactClient $entityManager->getRepository(Vente::class)->countMontantByVenteGroupDate($mois$annee'facture'$chantierId$clientId);
  438.         $coutGlobals $this->paieRepository->getCoutGlobalGroupDate($monthText$annee);
  439.         $em $this->getDoctrine()->getManager();
  440.         $montantFactApayer $entityManager->getRepository(Vente::class)->countMontantByVenteGroupDate($mois$annee'devis_client'$chantierId$clientId);
  441.         $valChartAmortMensAssurance = [""""""""""""""""""""""""];
  442.         $sumMontantAmortMensAssurance = ['mensualite_avec_assurance' => 0];
  443.         $gestionFinancements $this->metaConfigRepository->findOneBy(['mkey' => 'gestion_financement''entreprise' => $this->session->get('entreprise_session_id')]);
  444.         $isgestionFinancements 0;
  445.         if (!is_null($gestionFinancements) && !is_null($gestionFinancements->getValue())) {
  446.             $amortissements $this->getAmmortissements($annee);
  447.             foreach ($amortissements as $key => $value) {
  448.                 $valChartAmortMensAssurance[(int)(new \DateTime($value['date']))->format('m') - 1] = number_format($value['mensualite_avec_assurance'], 2'.''');
  449.                 $sumMontantAmortMensAssurance['mensualite_avec_assurance'] =  $sumMontantAmortMensAssurance['mensualite_avec_assurance'] + $value['mensualite_avec_assurance'];
  450.             }
  451.             $isgestionFinancements 1;
  452.         }
  453.         $ventesArr = [];
  454.         $valChartFactApayer = [""""""""""""""""""""""""];
  455.         $sumFactApayer = ['facture_a_payer' => 0];
  456.         foreach ($montantFactApayer as $value) {
  457.             $valChartFactClient[(int)$value['mois'] - 1] = number_format($value['sum_ht'], 2'.''');
  458.             $listIdDevis explode(','$value['list_id']);
  459.             $sumFacutreAssocieDevis 0;
  460.             foreach ($listIdDevis as $val) {
  461.                 $sumFacutreAssocieDevis += $this->venteRepository->getSumMontantByDevis($val)['sum_ht'];
  462.             }
  463.             $currentFacture_a_payer $value['sum_ht'] - $sumFacutreAssocieDevis;
  464.             $sumFactApayer['facture_a_payer'] +=  $currentFacture_a_payer;
  465.             $valChartFactApayer[(int)$value['mois'] - 1] = number_format($currentFacture_a_payer2'.''');
  466.         }
  467.         $valChartFact = [""""""""""""""""""""""""];
  468.         $sumMontantFact = ['prixttc' => 0'sum_ht' => 0];
  469.         foreach ($montantFact as $value) {
  470.             $valChartFact[(int)$value['mois'] - 1] = number_format($value['sum_ht'], 2'.''');
  471.             $sumMontantFact['prixttc'] =  $sumMontantFact['prixttc'] + $value['prixttc'];
  472.             $sumMontantFact['sum_ht'] =  $sumMontantFact['sum_ht'] + $value['sum_ht'];
  473.         }
  474.         $valChart = [""""""""""""""""""""""""];
  475.         $sumMontant = ['prixttc' => 0'sum_ht' => 0];
  476.         foreach ($montant as $value) {
  477.             $valChart[(int)$value['mois'] - 1] = number_format($value['sum_ht'], 2'.''');
  478.             $sumMontant['prixttc'] =  $sumMontant['prixttc'] + $value['prixttc'];
  479.             $sumMontant['sum_ht'] =  $sumMontant['sum_ht'] + $value['sum_ht'];
  480.         }
  481.         $valChartNonLie = [""""""""""""""""""""""""];
  482.         $sumMontantNonLie = ['prixttc' => 0'sum_ht' => 0];
  483.         foreach ($montantNonRelie as $value) {
  484.             $valChartNonLie[(int)$value['mois'] - 1] = number_format($value['sum_ht'], 2'.''');
  485.             $sumMontantNonLie['prixttc'] =  $sumMontantNonLie['prixttc'] + $value['prixttc'];
  486.             $sumMontantNonLie['sum_ht'] =  $sumMontantNonLie['sum_ht'] + $value['sum_ht'];
  487.         }
  488.         $valChartFactClient = [""""""""""""""""""""""""];
  489.         $sumMontantFactClient = ['prixttc' => 0'sum_ht' => 0];
  490.         $tabMois = [];
  491.         for ($i 1$i <= 12$i++) {
  492.             $tabMois[] = $i;
  493.         }
  494.         foreach ($montantFactClient as $value) {
  495.             $valChartFactClient[(int)$value['mois'] - 1] = number_format($value['sum_ht'], 2'.''');
  496.             $sumMontantFactClient['prixttc'] =  $sumMontantFactClient['prixttc'] + $value['prixttc'];
  497.             $sumMontantFactClient['sum_ht'] =  $sumMontantFactClient['sum_ht'] + $value['sum_ht'];
  498.         }
  499.         $valChartCoutGb = [""""""""""""""""""""""""];
  500.         $sumCoutGb 0;
  501.         $getMois $this->global_s->getMois();
  502.         $tabMoisWithPaid = [];
  503.         foreach ($coutGlobals as $value) {
  504.             $currentMois $getMois[ucfirst(explode(" "$value['datePaie'])[0])];
  505.             $valChartCoutGb[(int)$currentMois 1] = number_format($value['cout_global'], 2'.''');
  506.             $sumCoutGb += $value['cout_global'];
  507.             $tabMoisWithPaid[] = (int)$currentMois;
  508.         }
  509.         $tabMois array_diff($tabMois$tabMoisWithPaid);
  510.         // tableau pour completer la valeur des coup des mois sans fiche par les horaire
  511.         foreach ($tabMois as $value) {
  512.             if (is_null($mois) || (!is_null($mois) && (int)$mois == $value)) {
  513.                 $totaleGroup $this->calculCoutGlobalWithoutPaidOnMonth($chantierId$value$annee);
  514.                 $cout_global $totaleGroup['tx_moyen'] * $totaleGroup['heure'];
  515.                 $valChartCoutGb[$value 1] = number_format(((float)$valChartCoutGb[$value 1] + $cout_global), 2'.''');
  516.                 $sumCoutGb += $cout_global;
  517.             }
  518.         }
  519.         /* pour le mois en cour cour sans fiche, calculer sur les tx_moyen des horaires */
  520.         $lastPaie $this->paieRepository->findBy([], ["id" => "DESC"], 1);
  521.         if (count($lastPaie) && strtolower($lastPaie[0]->getDatePaie()) == strtolower((new \DateTime())->format('m Y'))) {
  522.             $currenDateMonthYear ucfirst(Carbon::parse((new \DateTime())->format('Y-m-d'))->locale('fr')->isoFormat('MMMM YYYY'));
  523.             $currentMois $getMois[ucfirst(explode(" "$currenDateMonthYear)[0])];
  524.             $totaleGroup $this->calculCoutGlobalWithoutPaidOnMonth($chantierId);
  525.             $lastVal $totaleGroup['tx_moyen'] * $totaleGroup['heure'];
  526.             $sumCoutGb += $lastVal;
  527.             $valChartCoutGb[(int)$currentMois 1] = number_format(((float)$valChartCoutGb[(int)$currentMois 1] + $lastVal), 2'.''');
  528.         }
  529.         $chartMarge = [""""""""""""""""""""""""];
  530.         $tauxMargin = [000000000000];
  531.         $chartColor = ["green""green""green""green""green""green""green""green""green""green""green""green"];
  532.         $sumMarge 0;
  533.         $sumMarge_1 0;
  534.         $moisToday = (int)(new \DateTime())->format('m');
  535.         $tauxMarginCumulle 0;
  536.         $countMonth 0;
  537.         for ($i 0$i count($chartMarge); $i++) {
  538.             $chartMarge[$i] = round(((float)$valChartFactClient[$i] - (float)$valChartFact[$i] - (float)$valChartCoutGb[$i] - (float)$valChartNonLie[$i]), 2);
  539.             $sumMarge += (float)$chartMarge[$i];
  540.             if ($i < ($moisToday 1)) {
  541.                 $sumMarge_1 += (float)$chartMarge[$i];
  542.             }
  543.             if ($chartMarge[$i] < 0) {
  544.                 $chartColor[$i] = "red";
  545.             }
  546.             if ($valChartFactClient[$i] != 0) {
  547.                 $currentTaux = ((float)$chartMarge[$i] / $valChartFactClient[$i])  * 100;
  548.                 $tauxMargin[$i] = number_format($currentTaux2'.''');
  549.             }
  550.         }
  551.         if ($sumMontantFactClient && $sumMontantFactClient['sum_ht'] != 0) {
  552.             $tauxMarginCumulle = ($sumMarge $sumMontantFactClient['sum_ht']) * 100;
  553.         }
  554.         // $galeries = $this->loadGalerie(0);
  555.         // $tabFileDim = [];
  556.         // foreach ($galeries as $value) {
  557.         //     $tabFileDim[$value->getId()] = ['width'=>0, 'height'=>0];
  558.         //     try {
  559.         //         $dir = $this->get('kernel')->getProjectDir()."/public/galerie/";
  560.         //         $file = $dir.$value->getEntreprise()->getId() . "/" . $value->getCreatedAt()->format('Y-m-d') . "/" . $value->getNom();
  561.         //         if(is_file($file)){
  562.         //             list($orig_width, $orig_height) = getimagesize($file);
  563.         //             $width = $orig_width;
  564.         //             $height = $orig_height;
  565.         //             $tabFileDim[$value->getId()] = ['width'=>$width, 'height'=>$height];
  566.         //         }
  567.         //     } catch (Exception $e) {
  568.         //     }            
  569.         // }
  570.         $full_month $annee;
  571.         if ($mois && !empty($mois) && $annee)
  572.             $full_month Carbon::parse("$annee-$mois-01")->locale('fr')->isoFormat('MMMM YYYY');
  573.         if ($request->query->get('test')) {
  574.             $galeries = [];
  575.         }
  576.         $galleryUser $this->galerieRepository->getGalleryGroupByUser();
  577.         usort($galleryUser, function ($a$b) {
  578.             return $b['nbr_gallery'] - $a['nbr_gallery'];
  579.         });
  580.         $maxPhotoVal = (count($galleryUser) > 0) ? $galleryUser[0]['nbr_gallery'] : 0;
  581.         $utilisateurs $this->utilisateurRepository->getUserByEntreprise(true);
  582.         $countDocumentAttente $entityManager->getRepository(EmailDocumentPreview::class)->countGroupByDossier();
  583.         $dossiers = [];
  584.         foreach ($countDocumentAttente as $value) {
  585.             switch ($value['dossier']) {
  586.                 case "facturation":
  587.                     $dossiers[] = [
  588.                         'dossier' => "Facture Fournisseur",
  589.                         'entity' => $value
  590.                     ];
  591.                     break;
  592.                 case "bon_livraison":
  593.                     $dossiers[] = [
  594.                         'entity' => $value,
  595.                         'dossier' => "Bon de Livraison"
  596.                     ];
  597.                     break;
  598.                 case "facture_client":
  599.                     $dossiers[] = [
  600.                         'entity' => $value,
  601.                         'dossier' => "Facture Client"
  602.                     ];
  603.                     break;
  604.                 case "devis_client":
  605.                     $dossiers[] = [
  606.                         'entity' => $value,
  607.                         'dossier' => "Devis Client"
  608.                     ];
  609.                     break;
  610.                 case "devis_pro":
  611.                     $dossiers[] = [
  612.                         'entity' => $value,
  613.                         'dossier' => "Devis Fournisseur"
  614.                     ];
  615.                     break;
  616.                 case "paie":
  617.                     $dossiers[] = [
  618.                         'entity' => $value,
  619.                         'dossier' => "Fiche de Paie"
  620.                     ];
  621.                     break;
  622.                 default:
  623.                     # code...
  624.                     break;
  625.             }
  626.         }
  627.         return $this->render('home/index.html.twig', [
  628.             'full_month' => $full_month,
  629.             'valChart' => $valChart,
  630.             'valChartNonLie' => $valChartNonLie,
  631.             'valChartFact' => $valChartFact,
  632.             'valChartFactClient' => $valChartFactClient,
  633.             'valChartCoutGb' => $valChartCoutGb,
  634.             'chartMarge' => $chartMarge,
  635.             'tauxMargin' => $tauxMargin,
  636.             'tauxMarginCumulle' => $tauxMarginCumulle,
  637.             'valChartFactApayer' => $valChartFactApayer,
  638.             'valChartAmortMensAssurance' => $valChartAmortMensAssurance,
  639.             'mois' => $mois,
  640.             'annee' => $annee,
  641.             'form' => $form->createView(),
  642.             'montant' => $sumMontant,
  643.             'montantBlNonRelie' => $sumMontantNonLie,
  644.             'montantFact' => $sumMontantFact,
  645.             'montantFactClient' => $sumMontantFactClient,
  646.             'montantPayeFact' => $montantPayeFact,
  647.             'sumMontantAmortMensAssurance' => $sumMontantAmortMensAssurance,
  648.             'isgestionFinancements' => $isgestionFinancements,
  649.             'sumCoutGb' => $sumCoutGb,
  650.             'sumMarge' => $sumMarge,
  651.             'sumMarge_1' => $sumMarge_1,
  652.             'sumFactApayer' => $sumFactApayer,
  653.             'chartColor' => $chartColor,
  654.             'galleryUser' => $galleryUser,
  655.             'maxPhotoVal' => $maxPhotoVal,
  656.             'countDocumentAttente' => $dossiers,
  657.             'utilisateurs' => $this->global_s->getUserByMiniature($utilisateurs),
  658.             'ouvriers' => $utilisateurs,
  659.             'currentMonth' => Carbon::parse((new \DateTime())->format('Y-m-d'))->locale('fr')->isoFormat('MMMM YYYY')
  660.         ]);
  661.     }
  662.     /**
  663.      * @Route("/load-galerie-xhr", name="load_galerie_xhr", methods={"GET"})
  664.      */
  665.     public function loadGalerieXhr(Request $request)
  666.     {
  667.         $page $request->query->get('page');
  668.         $offset $page 36;
  669.         $galeries $this->loadGalerie($offset);
  670.         $tabFileDim = [];
  671.         foreach ($galeries as $value) {
  672.             $tabFileDim[$value->getId()] = ['width' => 0'height' => 0];
  673.             try {
  674.                 $dir $this->get('kernel')->getProjectDir() . "/public/galerie/";
  675.                 $file $dir $value->getEntreprise()->getId() . "/" $value->getCreatedAt()->format('Y-m-d') . "/" $value->getNom();
  676.                 if (is_file($file)) {
  677.                     list($orig_width$orig_height) = getimagesize($file);
  678.                     $width $orig_width;
  679.                     $height $orig_height;
  680.                     $tabFileDim[$value->getId()] = ['width' => $width'height' => $height];
  681.                 }
  682.             } catch (Exception $e) {
  683.             }
  684.         }
  685.         $datas = ['status' => 200"message" => ""];
  686.         if (count($galeries) == 0) {
  687.             $datas['status'] = 300;
  688.         }
  689.         $datas['preview'] = $this->renderView('home/galerie.html.twig', [
  690.             'galeries' => $galeries,
  691.             'page' => $page,
  692.             'tabFileDim' => $tabFileDim
  693.         ]);
  694.         $response = new Response(json_encode($datas));
  695.         return $response;
  696.     }
  697.     public function loadGalerie($offset 0)
  698.     {
  699.         $galeries $this->galerieRepository->findBy(['entreprise' => $this->session->get('entreprise_session_id')], ['id' => 'DESC'], 36$offset);
  700.         // $galeries = $entityManager->createQueryBuilder()
  701.         //     ->select('g')
  702.         //     ->from('App\Entity\Galerie', 'g')
  703.         //     ->andWhere('g.entreprise = :entreprise')
  704.         //     ->setParameter('entreprise', $this->session->get('entreprise_session_id'))
  705.         //     ->orderBy('g.id', 'DESC')
  706.         //     ->setMaxResults(36)
  707.         //     ->getQuery()
  708.         //     ->getResult();
  709.         return $galeries;
  710.     }
  711.     public function calculCoutGlobalWithoutPaidOnMonth($chantierId null$mois null$annee null)
  712.     {
  713.         $currentMonth = !is_null($mois) ? $mois : (new \DateTime())->format('m');
  714.         $currentYear = !is_null($annee) ? $annee : (new \DateTime())->format('Y');
  715.         $horaires $this->horaireRepository->findByParams($chantierIdnullnull$currentMonth$currentYearnullnull);
  716.         $absences = [
  717.             => "Congés Payés",
  718.             => "En arrêt",
  719.             => "Chômage Partiel",
  720.             => "Absence",
  721.             => "Formation",
  722.             => "RTT",
  723.             => "Férié"
  724.         ];
  725.         $horairesArr = [];
  726.         $txMoyen 0;
  727.         $totaux = ['heure' => 0'fictif' => 0'tx_moyen' => 0];
  728.         if (count($horaires)) {
  729.             $tabUserId = [];
  730.             foreach ($horaires as $value) {
  731.                 $paie $this->paieRepository->getLastPaieWithTx($value['user_id']);
  732.                 $value['tx_moyen'] = $paie $paie['tx_moyen'] : 0;
  733.                 $totaux['heure'] +=  $value['time'];
  734.                 if (!array_key_exists($value['absence'], $absences))
  735.                     $totaux['fictif'] +=  $value['fictif'];
  736.                 elseif ($value['absence'] == 5) {
  737.                     $totaux['fictif'] +=  7;
  738.                 }
  739.                 //nous avons juste besoins d'une seule valuer par user
  740.                 if (!in_array($value['user_id'], $tabUserId)) {
  741.                     if ($value['tx_moyen'] > 0) {
  742.                         $txMoyen += $value['tx_moyen'];
  743.                         $tabUserId[] = $value['user_id'];
  744.                     }
  745.                 }
  746.             }
  747.             if (count($tabUserId))
  748.                 $txMoyen $txMoyen count($tabUserId);
  749.         }
  750.         $totaux['tx_moyen'] = $txMoyen;
  751.         return $totaux;
  752.     }
  753.     /**
  754.      * @Route("/split-pdf-bill/{doc}", name="split_pdf_bill", requirements={"doc"=".+"})
  755.      */
  756.     public function splitPDF(Request $request$doc nullParameterBagInterface $params)
  757.     {
  758.         $outputDir $params->get('kernel.project_dir') . "/public/test-google";
  759.         if (!is_dir($outputDir)) {
  760.             mkdir($outputDir0777true);
  761.         }
  762.         if ($doc) {
  763.             $fileToSend $doc;
  764.         } else {
  765.             $fileToSend  $params->get('kernel.project_dir') . "/public/test-google/bulletin-fulling.pdf";
  766.         }
  767.         try {
  768.             $ilovepdf = new Ilovepdf('project_public_931609e2e0edbf50c10eaeb858e470f3_fsjDZdb3b9cdf88dab190f9056c68e18de17a''secret_key_2b723a927cff7ba74a71d1fdfad73a9e_wF2qzfa225b5b9be2dbcc23bc29ba9b4c0722');
  769.         } catch (\Exception $e) {
  770.             throw new \Exception("Erreur de connexion à l'API de conversion de pdf"1);
  771.         }
  772.         $nbrePages $this->countPage($fileToSend);
  773.         // Create a new task
  774.         $myTaskSplit $ilovepdf->newTask('split');
  775.         // Add files to task for upload
  776.         $file1 $myTaskSplit->addFile($fileToSend); // PDF filename
  777.         // Set your tool options
  778.         //$myTaskSplit->setRanges('2-4,6-8');
  779.         // Execute the task
  780.         $myTaskSplit->execute();
  781.         // Download the package files
  782.         $myTaskSplit->download($outputDir);
  783.         // UNZIP FILE
  784.         if (file_exists($outputDir '/output.zip')) {
  785.             $zip = new ZipArchive();
  786.             $res $zip->open($outputDir '/output.zip');
  787.             if ($res === TRUE) {
  788.                 $zip->extractTo($outputDir);
  789.                 $zip->close();
  790.             }
  791.             unlink($outputDir '/output.zip');
  792.         }
  793.         //Lecture des fichiers correspondants
  794.         $docSplit = [];
  795.         for ($i 1$i <= $nbrePages$i++) {
  796.             $docSplit[] = substr($fileToSend0, -4) . '-' $i '.pdf';
  797.         }
  798.         natsort($docSplit);
  799.         $dataForDoc = [];
  800.         foreach ($docSplit as $doc) {
  801.             if ($doc == '.' || $doc == '..') {
  802.                 continue;
  803.             }
  804.             //$newName = $outputDir.'/'.$this->arrangeName($doc);
  805.             //rename($outputDir.'/'.$doc, $newName);
  806.             $dataForDoc[] = $this->extractFromGoogle($doc$params);
  807.         }
  808.         //dd($dataForDoc);
  809.         $splitRange '';
  810.         $numPage 1;
  811.         foreach ($dataForDoc as $item) {
  812.             if (isset($item['nom'])) {
  813.                 $username $item['nom'];
  814.                 $docRange $this->SearchSimilar($username$dataForDoc);
  815.                 if ($docRange != '') {
  816.                     if ($splitRange != '')
  817.                         $splitRange .= ',';
  818.                     $splitRange .= $docRange;
  819.                 }
  820.             } else {
  821.                 if ($splitRange != '')
  822.                     $splitRange .= ',';
  823.                 $splitRange .= $numPage;
  824.             }
  825.             $numPage++;
  826.         }
  827.         $splitRange explode(','$splitRange);
  828.         $splitRange array_unique($splitRange);
  829.         $listeDocRetour = [];
  830.         foreach ($splitRange as $elt) {
  831.             $toMerge_array explode('-'$elt);
  832.             if (count($toMerge_array) == 2) {
  833.                 $merged $this->mergeSimilarfile($fileToSend$toMerge_array$ilovepdf$outputDir);
  834.                 $listeDocRetour[] = $this->extractPath($merged$outputDir);
  835.             } else {
  836.                 $listeDocRetour[] = $this->extractPath(substr($fileToSend0, -4) . '-' $toMerge_array[0] . '.pdf'$outputDir);
  837.             }
  838.         }
  839.         try {
  840.             unlink($fileToSend);
  841.         } catch (\Throwable $th) {
  842.             //throw $th;
  843.         }
  844.         $splitRange implode(','$splitRange);
  845.         print_r($listeDocRetour);
  846.         return new Response("Traitement terminé. Nouveau découpage: $splitRange");
  847.     }
  848.     public function extractPath($nameWithPath$path)
  849.     {
  850.         $nameWithPath str_replace($path'',  $nameWithPath);
  851.         $nameWithPath str_replace('/''',  $nameWithPath);
  852.         return $nameWithPath;
  853.     }
  854.     public function mergeSimilarfile($fileToSend$tabList$ilovepdf$savePath)
  855.     {
  856.         $myTaskMerge $ilovepdf->newTask('merge');
  857.         for ($i = (int)$tabList[0]; $i <= (int)$tabList[1]; $i++) {
  858.             $myTaskMerge->addFile(substr($fileToSend0, -4) . '-' $i '.pdf');
  859.         }
  860.         $myTaskMerge->execute();
  861.         $myTaskMerge->download($savePath);
  862.         rename($savePath '/merged.pdf'substr($fileToSend0, -4) . '-' $tabList[0] . '-' $tabList[1] . '.pdf');
  863.         for ($i = (int)$tabList[0]; $i <= (int)$tabList[1]; $i++) {
  864.             try {
  865.                 unlink(substr($fileToSend0, -4) . '-' $i '.pdf');
  866.             } catch (\Throwable $th) {
  867.                 //throw $th;
  868.             }
  869.         }
  870.         return substr($fileToSend0, -4) . '-' $tabList[0] . '-' $tabList[1] . '.pdf';
  871.     }
  872.     public function countPage($path)
  873.     {
  874.         $pdf file_get_contents($path);
  875.         $number preg_match_all("/\/Page\W/"$pdf$dummy);
  876.         return $number;
  877.     }
  878.     public function SearchSimilar($value$tableau)
  879.     {
  880.         $index 1;
  881.         $otherPages = [];
  882.         foreach ($tableau as $item) {
  883.             if (isset($item['nom']) && ($item['nom'] == $value)) {
  884.                 $otherPages[] = $index;
  885.             }
  886.             $index++;
  887.         }
  888.         $nbreResult count($otherPages);
  889.         if ($otherPages[0] == $otherPages[$nbreResult 1])
  890.             return $otherPages[0] . '';
  891.         return $nbreResult $otherPages[0] . '-' $otherPages[$nbreResult 1] : '';
  892.     }
  893.     public function arrangeName($string)
  894.     {
  895.         $table = array(
  896.             '-1.pdf' => '-01.pdf',
  897.             '-2.pdf' => '-02.pdf',
  898.             '-3.pdf' => '-03.pdf',
  899.             '-4.pdf' => '-04.pdf',
  900.             '-5.pdf' => '-05.pdf',
  901.             '-6.pdf' => '-06.pdf',
  902.             '-7.pdf' => '-07.pdf',
  903.             '-8.pdf' => '-08.pdf',
  904.             '-9.pdf' => '-09.pdf',
  905.         );
  906.         return strtr($string$table);
  907.     }
  908.     public function extractFromGoogle($doc$params)
  909.     {
  910.         if ($doc) {
  911.             $b64Doc base64_encode(file_get_contents($doc));
  912.         } else {
  913.             $fileToSend  $params->get('kernel.project_dir') . "/public/test-google/bulletin-2.pdf";
  914.             $b64Doc base64_encode(file_get_contents($fileToSend));
  915.         }
  916.         $token file_get_contents($params->get('kernel.project_dir') . "/public/google-token.txt");
  917.         $token substr($token0, -1);
  918.         $postParameter = [
  919.             "skipHumanReview" => true,
  920.             "inlineDocument" => [
  921.                 "mimeType" => "Application/pdf",
  922.                 "content" => $b64Doc
  923.             ]
  924.         ];
  925.         $requeteJSON json_encode($postParameter);
  926.         $curlHandle curl_init('https://eu-documentai.googleapis.com/v1/projects/673985886308/locations/eu/processors/cd248572704a7ad7/processorVersions/663d22d0d2354323:process');
  927.         curl_setopt($curlHandleCURLOPT_HTTPHEADER, [
  928.             'Authorization: Bearer ' $token,
  929.             'Content-Type: application/json; charset=utf-8'
  930.         ]);
  931.         curl_setopt($curlHandleCURLOPT_POSTFIELDS$requeteJSON);
  932.         curl_setopt($curlHandleCURLOPT_RETURNTRANSFERtrue);
  933.         $curlResponse curl_exec($curlHandle);
  934.         //Gestion de la réponse
  935.         $http_status curl_getinfo($curlHandleCURLINFO_HTTP_CODE);
  936.         if ($http_status == 200) {
  937.             $dataReturn json_decode($curlResponse);
  938.             $entities $dataReturn->document->entities;
  939.             return array_column($entities'mentionText''type');
  940.         }
  941.         return null;
  942.     }
  943.     /**
  944.      * @Route("/testons", name="testons")
  945.      */
  946.     public function checkDatas(Request $requestParameterBagInterface $params)
  947.     {
  948.         $path $params->get('kernel.project_dir') . "/public/test-google/";
  949.         //$doc  = $params->get('kernel.project_dir') . "/public/test-google/BL.pdf";
  950.         $doc "https://dockeo.fr/uploads/achats/facturation/BL_87699229_20230725_13512764bfb7a0b2e3864bfb8e4298f1.pdf";
  951.         $filenameImg "Astu";
  952.         if(!$this->convertFromPDFToJPG($doc$filenameImg$path)){
  953.             dd("Problème lors de la conversion de ".$doc);
  954.         }
  955.         $documentPath $path.$filenameImg.".jpg";
  956.         $fp_image fopen($documentPath'r');
  957.         $image fread($fp_imagefilesize($documentPath));
  958.         fclose($fp_image);
  959.         
  960.         try {
  961.             $client = new \Aws\Textract\TextractClient([
  962.                 'region' => 'us-east-1',
  963.                 'version'  => 'latest',
  964.                 'credentials' => array(
  965.                     'key' => "AKIA4WXTGEBWCTPMQAXL",
  966.                     'secret'  => "0Fn7gH+h9S/LQg6ZHJJIOaQPkTEVmq1U45rw8bAp",
  967.                   )
  968.             ]);
  969.         } catch (\Exception $e) {
  970.             throw new \Exception("Erreur de connexion à l'API OCR"1);   
  971.         }
  972.         $resultSummaryFields $client->analyzeExpense ([
  973.             'Document' => [ // REQUIRED
  974.                 'Bytes' => $image,
  975.             ],
  976.         ]); 
  977.         dd($resultSummaryFields);
  978.         
  979.         return new Response();
  980.     }
  981.     public function convertFromPDFToJPG(string  $urlFile$filenameImg$path): string{
  982.         $image  "";
  983.         $postParameter = [
  984.             "Parameters" => [
  985.                 [
  986.                     "Name" => "File",
  987.                     "FileValue" => [
  988.                         "Name" => "Mon_PDF.pdf",
  989.                         "Data" => base64_encode(file_get_contents($urlFile)) // base64 encode file_content
  990.                     ]
  991.                 ],
  992.                 [
  993.                     "Name" => "StoreFile",
  994.                     "Value" => true
  995.                 ]
  996.             ]
  997.         ];
  998.         $curlHandle curl_init('https://v2.convertapi.com/convert/pdf/to/jpg?Secret=u2NOZjqsk0X6oKDw');
  999.         curl_setopt($curlHandleCURLOPT_HTTPHEADER, [
  1000.             'Content-Type: application/json'
  1001.         ]);
  1002.         curl_setopt($curlHandleCURLOPT_POSTFIELDSjson_encode($postParameter));
  1003.         curl_setopt($curlHandleCURLOPT_RETURNTRANSFERtrue);
  1004.         $curlResponse json_decode(curl_exec($curlHandle));
  1005.         //Gestion de la réponse
  1006.         $http_status curl_getinfo($curlHandleCURLINFO_HTTP_CODE);
  1007.         if($http_status == 200){
  1008.             $resultats =  $curlResponse->Files;   
  1009.             $i 1;     
  1010.             if(count($resultats)){
  1011.                 //Creation du dossier de sauvegarde
  1012.                 $dirTmp $path.$filenameImg."/";
  1013.                 try {
  1014.                     if (!is_dir($dirTmp)) {
  1015.                         mkdir($dirTmp0777true);
  1016.                     }
  1017.                 } catch (FileException $e) {}
  1018.                 
  1019.                 foreach($resultats as $result){     
  1020.                     $resultat =  $result->Url;   
  1021.                     $context stream_context_create(array('http'=>array('protocol_version'=>'1.1')));
  1022.                     $returnImg file_get_contents($resultatfalse$context);
  1023.                     file_put_contents($dirTmp.$filenameImg.$i++.".jpg"$returnImg); 
  1024.                 }
  1025.                 return $this->mergeJpgFiles($dirTmp$path$filenameImg.".jpg");
  1026.             }
  1027.             
  1028.         }else{
  1029.             print_r("Problème lors de la conversion en JPG de ".$path.$filenameImg);
  1030.         }
  1031.         return $image;
  1032.     }
  1033.     public function mergeJpgFiles(string $tmpdirstring $saveDirstring $filename): string{
  1034.         $files = [];
  1035.         if(is_dir($tmpdir))
  1036.             $files array_diff(scandir($tmpdir), array('.''..'));
  1037.         
  1038.         //MERGE LES FICHIERS IMAGES EN UNE SEULE POUR ENVOYER à AWS OCR
  1039.         if(count($files)){
  1040.             $nbrPageMax count($files) > 12 12 count($files);
  1041.             list($imgWidth$imgHeight) = getimagesize($tmpdir.array_values($files)[0]);
  1042.             $calque imagecreatetruecolor($imgWidth, ($imgHeight*$nbrPageMax));
  1043.             $i 0;
  1044.             foreach ($files as $value) {
  1045.                 if($i $nbrPageMax)
  1046.                     break;
  1047.                 imagecopy($calqueimagecreatefromjpeg($tmpdir.$value), 0$imgHeight*$i00$imgWidth$imgHeight);
  1048.                 
  1049.                 $i++;
  1050.             }
  1051.             $dirSave $saveDir.$filename;
  1052.             
  1053.             try {
  1054.                 imagejpeg($calque$dirSave);            
  1055.             } catch (\Exception $e) {
  1056.                 return false;
  1057.                 //dd(["ERROR:".$e->getMessage() ,$dirSave, $calque]);
  1058.             }
  1059.         }
  1060.         return $dirSave;
  1061.     }
  1062.     function base64ToImage($base64_string$output_file) {
  1063.         $file fopen($output_file"wb");
  1064.     
  1065.         $data explode(','$base64_string);
  1066.     
  1067.         fwrite($filebase64_decode($data[1]));
  1068.         fclose($file);
  1069.     
  1070.         return $output_file;
  1071.     }
  1072.     public function findAllChantierInTmpOcr($entityName null$filename$dossier$entrepriseId){
  1073.         $em $this->getDoctrine()->getManager();
  1074.         $entityName str_replace("'"""$entityName);
  1075.         $retourArr = [];
  1076.         if (!$entityName) {
  1077.             $chantiers $em->getRepository(Chantier::class)->getByEntrepriseOdreByBl($entrepriseId);
  1078.             foreach ($chantiers as $value) {
  1079.                 if (strtolower($value['nom']) == 'a definir' || strtolower($value['nom']) == 'fmda construction')
  1080.                     continue;
  1081.                 $newValue str_replace("'"" "$value['nom']);
  1082.                 $entityfound $em->getRepository(OcrField::class)->findChantierBrute($dossier$entrepriseId$filename$newValue);
  1083.                 /* autre tentative avec recherche sur les deux premiers mots */
  1084.                 if ($entityfound == false) {
  1085.                     $fournisseurName str_replace("-"' '$value['nom']);
  1086.                     $fournisseurName str_replace("  "' '$fournisseurName);
  1087.                     $fournisseurNameArr explode(' '$fournisseurName);
  1088.                     if (count($fournisseurNameArr) >= 2) {
  1089.                         //$fournisseurName = $fournisseurNameArr[0].' '.$fournisseurNameArr[1];
  1090.                         foreach ($fournisseurNameArr as $fourni) {
  1091.                             if (strlen($fourni) >= 4) {
  1092.                                 $result $this->findAllChantierInTmpOcr($fourni$filename$dossier$entrepriseId);
  1093.                                 if ($result)
  1094.                                     $retourArr[] = $result;
  1095.                             }
  1096.                         }
  1097.                     }
  1098.                 }else{
  1099.                     $retourArr[] = $entityfound;
  1100.                     break;
  1101.                 }
  1102.             }
  1103.         }else{
  1104.             $entityfound $em->getRepository(OcrField::class)->findChantierBrute($dossier$entrepriseId$filename$entityName);
  1105.             if ($entityfound != false) {
  1106.                 return $entityfound;
  1107.             }
  1108.         }
  1109.         return $retourArr;
  1110.     }
  1111.     public function dataLookLike($elt$checker)
  1112.     {
  1113.         return $elt == $checker;
  1114.     }
  1115.     public function removeDoublon($fournisseurArr){
  1116.         $retour = [];
  1117.         foreach($fournisseurArr as $item){
  1118.             if(!in_array($item['name'], array_column($retour'name')))
  1119.                 $retour [] = $item;
  1120.         }
  1121.         return $retour;
  1122.     }
  1123.     /**
  1124.      * @Route("/eden_ai_debug/{doc}", name="eden_ai_debug", requirements={"doc"=".+"})
  1125.      */
  1126.     public function edenAiDebug(Request $request$doc nullParameterBagInterface $params)
  1127.     {
  1128.         if(!$doc){
  1129.             $doc  "https://dockeo.fr/test-google/facture.pdf";
  1130.         }
  1131.         
  1132.         $edenAiResult $this->edenAi->scanWithEdenAi($doc);
  1133.         //dd($_SERVER['SERVER_NAME']);
  1134.         //$edenAiResult = $edenAiResult->google->extracted_data;
  1135.         //$edenAiResult = $edenAiResult[0];
  1136.         dd($this->edenAi->getDatasFromEdenAi($edenAiResult'google'));
  1137.         return $this->render('error/503.html.twig');
  1138.     }
  1139.     /**
  1140.      * @Route("/find_best_num_bl/{previewDoc}/{type}", name="find_best_num_bl")
  1141.      */
  1142.     public function findBestMatchTextRefNumBL(EmailDocumentPreview $previewDoc null$type "bl")
  1143.     {
  1144.         dd($this->findNumBLService->findCustumNumBL($previewDoc));
  1145.         $listNumBL $this->findNumBLService->findBestMatchTextRefNum($previewDoc$type);
  1146.         $AR = (array_key_exists('AR'$listNumBL) && $listNumBL['AR']) ? true false;
  1147.         $PF = (array_key_exists('PF'$listNumBL) && $listNumBL['PF']) ? true false;
  1148.         dd($this->findNumBLService->extractNumfromChaine($listNumBL['num_BL_found'], $listNumBL['good_text_Ref'], $PF$AR));
  1149.         return $this->render('error/503.html.twig');
  1150.     }
  1151.     /**
  1152.      * @Route("/get_email_doc/{previewDoc}", name="get_email")
  1153.      */
  1154.     public function getEmailFromTmpExpense(EmailDocumentPreview $previewDoc)
  1155.     {
  1156.         if(str_contains($previewDoc->getDocument(), '.pdf')){
  1157.             $filename str_replace('.pdf''.jpg'$previewDoc->getDocument());
  1158.         }else{
  1159.             $filename str_replace('.PDF''.jpg'$previewDoc->getDocument());
  1160.         }
  1161.         $listEmail $this->getDoctrine()->getRepository(TmpExpense::class)->findEmailInTmpExpense($previewDoc->getDossier(), $filename);
  1162.         dd($listEmail);
  1163.         return $this->render('error/503.html.twig');
  1164.     }
  1165.     /**
  1166.      * @Route("/file-delete/{dossier}/{filename}", name="file_delete")
  1167.      */
  1168.     public function deleteFileAPI(Request $requestParameterBagInterface $paramsstring $dossier ""string $filename "")
  1169.     {
  1170.         if($dossier && $filename){
  1171.             $file $params->get('kernel.project_dir') . "/public/".$this->getDirFiles($dossier)."/".$filename;
  1172.             if(file_exists($file)){
  1173.                 unlink($file);
  1174.             }
  1175.         }
  1176.         return new JsonResponse(true);
  1177.     }
  1178.     public function getDirFiles(string $dossier){
  1179.         switch ($dossier) {
  1180.             case 'facturation':
  1181.                 return "uploads/achats/facturation/";
  1182.             case 'bon_livraison':
  1183.                 return "uploads/factures/";
  1184.             case 'devis_pro':
  1185.                 return "uploads/devis/";
  1186.             case 'facture_client':
  1187.                 return "uploads/clients/factures/";
  1188.             case 'devis_client':
  1189.                 return "uploads/devis/";
  1190.             case 'paie':
  1191.                 return "uploads/paies/";
  1192.             case 'cheque':
  1193.                 return "uploads/banque/";
  1194.             case 'lcr':
  1195.                 return "uploads/lcr/";
  1196.             case 'outillage':
  1197.                 return "uploads/image_outillage/";
  1198.             case 'vehicule':
  1199.                 return "uploads/vehicule/document/";
  1200.             default:
  1201.                 return "inconu";
  1202.         }
  1203.     }
  1204.     /**
  1205.      * @Route("/google_ai_debug/{doc}", name="google_ai_debug", requirements={"doc"=".+"})
  1206.      */
  1207.     public function googleAiDebug(Request $request$doc nullParameterBagInterface $params)
  1208.     {
  1209.         if ($doc) {
  1210.             $b64Doc base64_encode(file_get_contents($doc));
  1211.         } else {
  1212.             $fileToSend  $params->get('kernel.project_dir') . "/public/test-google/bulletin-debug.pdf";
  1213.             $b64Doc base64_encode(file_get_contents($fileToSend));
  1214.         }
  1215.         $token file_get_contents($params->get('kernel.project_dir') . "/public/google-token.txt");
  1216.         $token substr($token0, -1);
  1217.         $postParameter = [
  1218.             "skipHumanReview" => true,
  1219.             "inlineDocument" => [
  1220.                 "mimeType" => "Application/pdf",
  1221.                 "content" => $b64Doc
  1222.             ]
  1223.         ];
  1224.         $requeteJSON json_encode($postParameter);
  1225.         $curlHandle curl_init('https://eu-documentai.googleapis.com/v1/projects/673985886308/locations/eu/processors/cd248572704a7ad7/processorVersions/4b2bc30d3fbe3865:process');
  1226.         curl_setopt($curlHandleCURLOPT_HTTPHEADER, [
  1227.             'Authorization: Bearer ' $token,
  1228.             'Content-Type: application/json; charset=utf-8'
  1229.         ]);
  1230.         curl_setopt($curlHandleCURLOPT_POSTFIELDS$requeteJSON);
  1231.         curl_setopt($curlHandleCURLOPT_RETURNTRANSFERtrue);
  1232.         $curlResponse curl_exec($curlHandle);
  1233.         //Gestion de la réponse
  1234.         $http_status curl_getinfo($curlHandleCURLINFO_HTTP_CODE);
  1235.         if ($http_status == 200) {
  1236.             echo 'TRAITEMENT AVEC SUCCES';
  1237.             $dataReturn json_decode($curlResponse);
  1238.             $entities $dataReturn->document->entities;
  1239.             echo '<br><br>LE DOCUMENT RETOURNE EN ENTIER';
  1240.             dd($entities);
  1241.         } else {
  1242.             print_r('ECHEC DE TRAITEMENT');
  1243.             dd(json_decode($curlResponse));
  1244.         }
  1245.         curl_close($curlHandle);
  1246.         return $this->render('error/503.html.twig');
  1247.     }
  1248.     /**
  1249.      * @Route("/date-debug", name="debug-date")
  1250.      */
  1251.     public function debugDate(Request $request)
  1252.     {
  1253.         $dateO  0;
  1254.         if ($dateO) {
  1255.             print_r(date_format($dateO'd-m-Y'));
  1256.         } else {
  1257.             print_r("La date n'a pas pu être formaté");
  1258.         }
  1259.         return $this->render('error/503.html.twig');
  1260.     }
  1261.     
  1262. }