src/Controller/HomeController.php line 99

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