<?php
namespace App\Controller;
use App\Service\EdenAiHelperMethods;
use Doctrine\ORM\EntityRepository;
use App\Entity\Achat;
use App\Entity\Vente;
use App\Entity\Client;
use App\Entity\TmpOcr;
use App\Entity\Galerie;
use App\Entity\Lot;
use App\Entity\Pret;
use App\Entity\EmailDocumentPreview;
use App\Form\AchatType;
use App\Form\FournisseursType;
use App\Form\ChantierType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use App\Entity\Fournisseurs;
use App\Entity\Chantier;
use App\Entity\Entreprise;
use App\Entity\Tva;
use App\Entity\Devise;
use App\Repository\ChantierRepository;
use App\Repository\HoraireRepository;
use App\Repository\PaieRepository;
use App\Repository\FournisseursRepository;
use App\Repository\UtilisateurRepository;
use App\Repository\VenteRepository;
use App\Repository\AchatRepository;
use App\Repository\EntrepriseRepository;
use App\Repository\GalerieRepository;
use Pagerfanta\Adapter\ArrayAdapter;
use App\Service\GlobalService;
use Carbon\Carbon;
use Pagerfanta\Pagerfanta;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\Repository\MetaConfigRepository;
// On utilise Algoria
use Algolia\AlgoliaSearch\SearchClient;
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
use Ilovepdf\Ilovepdf;
use Ilovepdf\CompressTask;
// Imports the Google Cloud client library
use Google\ApiCore;
use Google\Auth;
use \ConvertApi\ConvertApi;
use ZipArchive;
use setasign\Fpdi\Fpdi;
use Spipu\Html2Pdf\Html2Pdf;
use Spipu\Html2Pdf\Exception\Html2PdfException;
use App\Controller\PretController;
use App\Entity\OcrField;
use App\Entity\TmpExpense;
use App\Repository\TmpOcrRepository;
use App\Service\ArticleExtractService;
use App\Service\FactureService;
use App\Service\FindNumBLService;
use App\Service\GoogleHelperMethods;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
class HomeController extends Controller
{
private $global_s;
private $chantierRepository;
private $achatRepository;
private $entrepriseRepository;
private $fournisseurRepository;
private $venteRepository;
private $galerieRepository;
private $utilisateurRepository;
private $PaieRepository;
private $horaireRepository;
private $session;
private $pretController;
public $edenAi;
public $articleExtractService;
public $googleHelperMethods;
public $params;
private $tmpOcrRepository;
private $findNumBLService;
public function __construct(FindNumBLService $findNumBLService, TmpOcrRepository $tmpOcrRepository, ParameterBagInterface $params, GoogleHelperMethods $googleHelperMethods, ArticleExtractService $articleExtractService, EdenAiHelperMethods $edenAi, GlobalService $global_s, GalerieRepository $galerieRepository, ChantierRepository $chantierRepository, AchatRepository $achatRepository, EntrepriseRepository $entrepriseRepository, FournisseursRepository $fournisseurRepository, PaieRepository $paieRepository, VenteRepository $venteRepository, HoraireRepository $horaireRepository, UtilisateurRepository $utilisateurRepository, SessionInterface $session, PretController $pretController, MetaConfigRepository $metaConfigRepository)
{
$this->global_s = $global_s;
$this->chantierRepository = $chantierRepository;
$this->galerieRepository = $galerieRepository;
$this->venteRepository = $venteRepository;
$this->utilisateurRepository = $utilisateurRepository;
$this->fournisseurRepository = $fournisseurRepository;
$this->achatRepository = $achatRepository;
$this->entrepriseRepository = $entrepriseRepository;
$this->paieRepository = $paieRepository;
$this->horaireRepository = $horaireRepository;
$this->pretController = $pretController;
$this->metaConfigRepository = $metaConfigRepository;
$this->session = $session;
$this->edenAi = $edenAi;
$this->articleExtractService = $articleExtractService;
$this->googleHelperMethods = $googleHelperMethods;
$this->params = $params;
$this->tmpOcrRepository = $tmpOcrRepository;
$this->findNumBLService = $findNumBLService;
}
public function getBaseUrl()
{
$baseUrl = $this->generateUrl('home', [], UrlGenerator::ABSOLUTE_URL);
return new Response($baseUrl);
}
/**
* @Route("/merge", name="page_merge")
*/
public function mergeImage()
{
// $ilovepdf = new Ilovepdf('project_public_931609e2e0edbf50c10eaeb858e470f3_fsjDZdb3b9cdf88dab190f9056c68e18de17a','secret_key_2b723a927cff7ba74a71d1fdfad73a9e_wF2qzfa225b5b9be2dbcc23bc29ba9b4c0722');
// $filename = "20220108110103_00161d96b2f6c9d3.jpg";
// $myTask = $ilovepdf->newTask('imagepdf');
// $file1 = $myTask->addFile($this->get('kernel')->getProjectDir() . "/public/uploads/achats/facturation/".$filename);
// $myTask->execute();
// $myTask->setOutputFilename("test.pdf");
// $myTask->download($this->get('kernel')->getProjectDir() . "/public/uploads/achats/facturation/");
// dd($file1);
return new Response('d');
}
/**
* @Route("/503/{type}", name="page_503")
*/
public function page503(Request $request, $type = false)
{
$this->global_s->cronOcrIa(null, $type);
dd('sds');
return $this->render('error/503.html.twig');
}
/**
* @Route("/ocr", name="lancer_ocr")
*/
public function ocr(Request $request)
{
if (is_null($this->getUser()))
$this->generateUrl("security_login", [], UrlGenerator::ABSOLUTE_URL);
$this->global_s->cronOcrImportDocument();
//$this->global_s->cronOcrIa();
dd('Opération terminée');
}
/**
* @Route("/import", name="page_import")
*/
public function import(Request $request)
{
$this->global_s->cronOcrImportDocument();
dd("import");
}
/**
* @Route("/get-adresse", name="page_import")
*/
public function getAdresseApi(Request $request)
{
$chaine = "Mme Pascale HUWART 42 Rue gambetta 62000 ARRAS";
$url = 'https://api-adresse.data.gouv.fr/search/?q='.str_replace(' ','+', $chaine);
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($curlHandle);
$httpCode = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
if($httpCode == 200){
$resultat = json_decode($response);
if(count($resultat->features)){
$resultat = $resultat->features[0];
$resultat = $resultat->properties;
if($resultat){
return[
'adresse' => $resultat->name,
'cp' => $resultat->postcode,
'ville' => $resultat->city
];
}
}
}
}
/**
* @Route("/split-pdf", name="pdf_split")
*/
public function testPDFSplit(){
$outputDir = $this->get('kernel')->getProjectDir(). "/public/uploads/factures/";
$fileToSplit = base64_encode(file_get_contents($outputDir."test_to_split.pdf"));
$filename = "test_to_split.pdf";
//$this->googleHelperMethods->simpleSplitPDF($filename, $fileToSplit, $outputDir);
//Mergin
$filename1 = "test_to_split-1.pdf";
$filename2 = "test_to_split-2.pdf";
$fileToSplit1 = base64_encode(file_get_contents($outputDir."test_to_split-1.pdf"));
$fileToSplit2 = base64_encode(file_get_contents($outputDir."test_to_split-2.pdf"));
$fileDatas = [];
$fileDatas[] = [
'Name' => $filename1,
'Data' => $fileToSplit1,
];
$fileDatas[] = [
'Name' => $filename2,
'Data' => $fileToSplit2,
];
$fileNameBase = "test_to_split.pdf";
dd($this->googleHelperMethods->simpleMergePDF($fileDatas, $outputDir, $fileNameBase, "1-2"));
}
public function rotateIfPaysage($dir, $file, $angle)
{
try {
if (file_exists($file)) {
$ilovepdf = new Ilovepdf('project_public_931609e2e0edbf50c10eaeb858e470f3_fsjDZdb3b9cdf88dab190f9056c68e18de17a', 'secret_key_2b723a927cff7ba74a71d1fdfad73a9e_wF2qzfa225b5b9be2dbcc23bc29ba9b4c0722');
// $pdf = new Fpdi();
// $pdf->setSourceFile($file);
for ($i = 1; $i <= 1; $i++) {
// $tpl = $pdf->importPage($i);
// $size = $pdf->getTemplateSize($tpl);
// $pdf->addPage();
// $pdf->useTemplate($tpl);
$myTask = $ilovepdf->newTask('rotate');
$file1 = $myTask->addFile($file);
$file1->setRotation($angle);
$myTask->execute();
$myTask->setOutputFilename("test");
$myTask->download($dir);
}
}
} catch (\Exception $e) {
throw new \Exception($e->getMessage(), 1);
}
}
/**
* @param EmailDocumentPreview $docId // chemin vers le fichier
* @param mixed $debug // mode
* @return mixed // tableau contenant la réponse
* @Route("/get_articles_item_scan/{docId}/load/{debug}", name="get_articles_item_scan")
*/
public function extractArticleItem(EmailDocumentPreview $docId, $debug = 0){
$datas = $this->articleExtractService->extractArticle($docId);
if($debug){
dd($datas);
}
return new Response(json_encode($datas));
}
/**
* @return mixed // tableau contenant la réponse
* @Route("/google_response_debug/{docID}", name="get_google_articles")
*/
public function extractArticleItemFromGoogle(EmailDocumentPreview $docID){
$filenamePDF = $docID->getDocument();
$filenamePDF = $this->googleHelperMethods->getDirDosssier($docID->getDossier(), $this->params) . $filenamePDF;
$resultat = $this->googleHelperMethods->extractFromGoogle(null, $filenamePDF, $this->params, null, true);
dd(['Fichier PDF' => $filenamePDF, 'Scan Google' => $resultat]);
return new Response(json_encode($resultat));
}
/**
* @Route("/document-rotation", name="document_rotation")
*/
public function documentRotation(Request $request)
{
$pdfDir = $request->query->get('pdf');
$rotation = (int)$request->query->get('rotation');
$dossier = $request->query->get('dossier');
$arr = explode('/', $pdfDir);
$pdf = array_pop($arr);
$dir = $this->get('kernel')->getProjectDir() . "/public" . implode('/', $arr);
$pdfDir = $dir . '/' . $pdf;
try {
$this->rotateIfPaysage($dir, $pdfDir, $rotation);
} catch (\Exception $e) {
return new Response(json_encode([
'status' => 400,
'message' => $e->getMessage()
]));
}
$docPreview = $this->getDoctrine()->getRepository(EmailDocumentPreview::class)->findOneBy(['dossier' => $dossier, 'document' => $pdf]);
if (!is_null($docPreview)) {
$docPreview->setIsConvert(false);
$docPreview->setExecute(false);
}
$em = $this->getDoctrine()->getManager();
$imagename = strtolower($pdf);
$imagename = str_replace(".pdf", '.jpg', $imagename);
$em->getRepository(TmpOcr::class)->removesAll($dossier, $imagename);
$em->flush();
$urlRedirect = "";
switch ($dossier) {
case 'facturation':
$urlRedirect = "facturation_import_document";
break;
case 'bon_livraison':
$urlRedirect = "bon_livraison_import_document";
break;
case 'devis_pro':
$urlRedirect = "devis_pro_import_document";
break;
case 'facture_client':
$urlRedirect = "facture_client_import_document";
break;
case 'devis_client':
$urlRedirect = "devis_client_import_document";
break;
case 'paie':
$urlRedirect = "paie_import_document";
break;
}
if ($urlRedirect != "") {
return new Response(json_encode([
'status' => 200,
"datas" => [
'redirect' => $this->generateUrl($urlRedirect, ['scan' => 1], UrlGenerator::ABSOLUTE_URL)
]
]));
}
}
/**
* @Route("/testPdf", name="home_test_pdf")
*/
public function testPdf()
{
$products = [];
for ($i = 0; $i < 9; $i++) {
$products[] =
array(
'number' => '',
'title' => 'Devis n°687 du 22/09/2021',
'description' => 'Annule et remplace le devis 668 changement de modeconstructif',
'qte' => '1.0000',
'u' => 'U',
'pu' => '350,00 €',
'rem' => '',
'total' => '350,00 €',
'tva' => '20,00'
);
}
if (count($products) <= 6)
$nbPage = 1;
else
$nbPage = ceil((count($products) - 6) / 19) + 1;
$html = $this->renderView('home/testPdfGenerate.html.twig', [
'products' => $products,
'nbPage' => $nbPage
]);
$html2pdf = new Html2Pdf('P', 'A4', 'fr', true, 'UTF-8', array(0, 0, 0, 0));
$html2pdf->addFont('helveticab', '', realpath($_SERVER["DOCUMENT_ROOT"]) . '/fonts/helveticaBoldItalic/helveticab.php');
$html2pdf->addFont('helveticaob', '', realpath($_SERVER["DOCUMENT_ROOT"]) . '/fonts/helveticaOblique/helveticaob.php');
$html2pdf->addFont('helveticabold', '', realpath($_SERVER["DOCUMENT_ROOT"]) . '/fonts/helveticabold/helveticabold.php');
$html2pdf->addFont('helveticabl', '', realpath($_SERVER["DOCUMENT_ROOT"]) . '/fonts/helveticaligth/helveticabl.php');
$html2pdf->writeHTML($html);
$html2pdf->output('credit.pdf');
return $html2pdf->stream("pdf_filename.pdf", array("Attachment" => false));
}
public function getAmmortissements($annee)
{
$prets = $this->getDoctrine()->getRepository(Pret::class)->findBy(['entreprise' => $this->session->get('entreprise_session_id')]);
$amortissementsArr = [];
foreach ($prets as $pret) {
$dateDebut = $pret->getDateDeblocage();
$debutPrelevementInteret = $pret->getDebutPrelevementInteret();
$montantEcheance1 = (float)$pret->getMontantEcheance1();
$montantEcheance1 = (float)$pret->getMontantEcheance1();
$interet1 = (float)$pret->getInteret1();
$remboursement1 = (float)$pret->getRemboursement1();
$datePremiereEcheance = $pret->getDatePremiereEcheance();
$montantPret = (float)$pret->getCapital();
$duree = (int)$pret->getDuree();
$taux = (float)$pret->getTaux();
$tauxAssurance = (float)$pret->getTauxAssurance();
$typeDiffere = (int)$pret->getDiffere();
$dureeDiffere = (int)$pret->getDureeDiffere();
$amortissements = $this->pretController->calculAmortissement($pret, $dateDebut, $montantPret, $duree, $taux, $tauxAssurance, $typeDiffere, $dureeDiffere, $debutPrelevementInteret, $montantEcheance1, $datePremiereEcheance, $interet1, $remboursement1, $annee)['amortissements'];
foreach ($amortissements as $value) {
if (($value['date'])->format('Y') == $annee) {
$amortissementsArr[($value['date'])->format('Y-m')][] = ['pret' => $pret->getId(), 'date' => ($value['date'])->format('Y-m-d'), 'mensualite_avec_assurance' => $value['mensualite_avec_assurance']];
}
}
}
$amortissementsArr = array_map(function ($amortissement) {
return [
'date' => $amortissement[0]['date'],
'mensualite_avec_assurance' => array_reduce(
$amortissement,
function ($sum, $item) {
return $sum + $item['mensualite_avec_assurance'];
}
)
];
}, $amortissementsArr);
return $amortissementsArr;
}
/**
* @Route("/", name="home")
*/
public function index(Request $request, Session $session)
{
$form = $request->request->get('form', null);
$fournisseurId = $chantierId = $clientId = null;
$moisList = array_flip($this->global_s->getMois());
if ($form) {
$mois = null;
$monthText = !is_null($mois) ? $moisList[$mois] : "";
$annee = (!(int)$form['annee']) ? null : (int)$form['annee'];
$session->set('home_mois_bl', $mois);
$session->set('home_annee_bl', $annee);
$session->set('home_chantier_bl', $chantierId);
} else {
$day = explode('-', (new \DateTime())->format('Y-m-d'));
$mois = $session->get('home_mois_bl') ?? null;
$monthText = $mois ? $moisList[$mois] : "";
$annee = $session->get('home_annee_bl') ?? $day[0];
$chantierId = $session->get('home_chantier_bl') ?? null;
}
$form = $this->createFormBuilder(array(
'annee' => $annee,
))
->add('annee', ChoiceType::class, array(
'label' => "Année",
'choices' => $this->global_s->getAnnee(),
'attr' => array(
'class' => 'form-control'
)
))->getForm();
$entityManager = $this->getDoctrine()->getManager();
$montant = $entityManager->getRepository(Achat::class)->countMontantByfacturedGroupDate($mois, $annee, 'bon_livraison', $chantierId, $fournisseurId);
$montantNonRelie = $entityManager->getRepository(Achat::class)->countMontantByfacturedGroupDate($mois, $annee, 'bon_livraison', $chantierId, $fournisseurId, null, false);
$montantPayeFact = $entityManager->getRepository(Achat::class)->countMontantByfacturedPayeDate($mois, $annee, 'facturation', $chantierId, $fournisseurId);
$montantFact = $entityManager->getRepository(Achat::class)->countMontantByfacturedGroupDate($mois, $annee, 'facturation', $chantierId, $fournisseurId);
$montantFactClient = $entityManager->getRepository(Vente::class)->countMontantByVenteGroupDate($mois, $annee, 'facture', $chantierId, $clientId);
$coutGlobals = $this->paieRepository->getCoutGlobalGroupDate($monthText, $annee);
$em = $this->getDoctrine()->getManager();
$montantFactApayer = $entityManager->getRepository(Vente::class)->countMontantByVenteGroupDate($mois, $annee, 'devis_client', $chantierId, $clientId);
$valChartAmortMensAssurance = ["", "", "", "", "", "", "", "", "", "", "", ""];
$sumMontantAmortMensAssurance = ['mensualite_avec_assurance' => 0];
$gestionFinancements = $this->metaConfigRepository->findOneBy(['mkey' => 'gestion_financement', 'entreprise' => $this->session->get('entreprise_session_id')]);
$isgestionFinancements = 0;
if (!is_null($gestionFinancements) && !is_null($gestionFinancements->getValue())) {
$amortissements = $this->getAmmortissements($annee);
foreach ($amortissements as $key => $value) {
$valChartAmortMensAssurance[(int)(new \DateTime($value['date']))->format('m') - 1] = number_format($value['mensualite_avec_assurance'], 2, '.', '');
$sumMontantAmortMensAssurance['mensualite_avec_assurance'] = $sumMontantAmortMensAssurance['mensualite_avec_assurance'] + $value['mensualite_avec_assurance'];
}
$isgestionFinancements = 1;
}
$ventesArr = [];
$valChartFactApayer = ["", "", "", "", "", "", "", "", "", "", "", ""];
$sumFactApayer = ['facture_a_payer' => 0];
foreach ($montantFactApayer as $value) {
$valChartFactClient[(int)$value['mois'] - 1] = number_format($value['sum_ht'], 2, '.', '');
$listIdDevis = explode(',', $value['list_id']);
$sumFacutreAssocieDevis = 0;
foreach ($listIdDevis as $val) {
$sumFacutreAssocieDevis += $this->venteRepository->getSumMontantByDevis($val)['sum_ht'];
}
$currentFacture_a_payer = $value['sum_ht'] - $sumFacutreAssocieDevis;
$sumFactApayer['facture_a_payer'] += $currentFacture_a_payer;
$valChartFactApayer[(int)$value['mois'] - 1] = number_format($currentFacture_a_payer, 2, '.', '');
}
$valChartFact = ["", "", "", "", "", "", "", "", "", "", "", ""];
$sumMontantFact = ['prixttc' => 0, 'sum_ht' => 0];
foreach ($montantFact as $value) {
$valChartFact[(int)$value['mois'] - 1] = number_format($value['sum_ht'], 2, '.', '');
$sumMontantFact['prixttc'] = $sumMontantFact['prixttc'] + $value['prixttc'];
$sumMontantFact['sum_ht'] = $sumMontantFact['sum_ht'] + $value['sum_ht'];
}
$valChart = ["", "", "", "", "", "", "", "", "", "", "", ""];
$sumMontant = ['prixttc' => 0, 'sum_ht' => 0];
foreach ($montant as $value) {
$valChart[(int)$value['mois'] - 1] = number_format($value['sum_ht'], 2, '.', '');
$sumMontant['prixttc'] = $sumMontant['prixttc'] + $value['prixttc'];
$sumMontant['sum_ht'] = $sumMontant['sum_ht'] + $value['sum_ht'];
}
$valChartNonLie = ["", "", "", "", "", "", "", "", "", "", "", ""];
$sumMontantNonLie = ['prixttc' => 0, 'sum_ht' => 0];
foreach ($montantNonRelie as $value) {
$valChartNonLie[(int)$value['mois'] - 1] = number_format($value['sum_ht'], 2, '.', '');
$sumMontantNonLie['prixttc'] = $sumMontantNonLie['prixttc'] + $value['prixttc'];
$sumMontantNonLie['sum_ht'] = $sumMontantNonLie['sum_ht'] + $value['sum_ht'];
}
$valChartFactClient = ["", "", "", "", "", "", "", "", "", "", "", ""];
$sumMontantFactClient = ['prixttc' => 0, 'sum_ht' => 0];
$tabMois = [];
for ($i = 1; $i <= 12; $i++) {
$tabMois[] = $i;
}
foreach ($montantFactClient as $value) {
$valChartFactClient[(int)$value['mois'] - 1] = number_format($value['sum_ht'], 2, '.', '');
$sumMontantFactClient['prixttc'] = $sumMontantFactClient['prixttc'] + $value['prixttc'];
$sumMontantFactClient['sum_ht'] = $sumMontantFactClient['sum_ht'] + $value['sum_ht'];
}
$valChartCoutGb = ["", "", "", "", "", "", "", "", "", "", "", ""];
$sumCoutGb = 0;
$getMois = $this->global_s->getMois();
$tabMoisWithPaid = [];
foreach ($coutGlobals as $value) {
$currentMois = $getMois[ucfirst(explode(" ", $value['datePaie'])[0])];
$valChartCoutGb[(int)$currentMois - 1] = number_format($value['cout_global'], 2, '.', '');
$sumCoutGb += $value['cout_global'];
$tabMoisWithPaid[] = (int)$currentMois;
}
$tabMois = array_diff($tabMois, $tabMoisWithPaid);
// tableau pour completer la valeur des coup des mois sans fiche par les horaire
foreach ($tabMois as $value) {
if (is_null($mois) || (!is_null($mois) && (int)$mois == $value)) {
$totaleGroup = $this->calculCoutGlobalWithoutPaidOnMonth($chantierId, $value, $annee);
$cout_global = $totaleGroup['tx_moyen'] * $totaleGroup['heure'];
$valChartCoutGb[$value - 1] = number_format(((float)$valChartCoutGb[$value - 1] + $cout_global), 2, '.', '');
$sumCoutGb += $cout_global;
}
}
/* pour le mois en cour cour sans fiche, calculer sur les tx_moyen des horaires */
$lastPaie = $this->paieRepository->findBy([], ["id" => "DESC"], 1);
if (count($lastPaie) && strtolower($lastPaie[0]->getDatePaie()) == strtolower((new \DateTime())->format('m Y'))) {
$currenDateMonthYear = ucfirst(Carbon::parse((new \DateTime())->format('Y-m-d'))->locale('fr')->isoFormat('MMMM YYYY'));
$currentMois = $getMois[ucfirst(explode(" ", $currenDateMonthYear)[0])];
$totaleGroup = $this->calculCoutGlobalWithoutPaidOnMonth($chantierId);
$lastVal = $totaleGroup['tx_moyen'] * $totaleGroup['heure'];
$sumCoutGb += $lastVal;
$valChartCoutGb[(int)$currentMois - 1] = number_format(((float)$valChartCoutGb[(int)$currentMois - 1] + $lastVal), 2, '.', '');
}
$chartMarge = ["", "", "", "", "", "", "", "", "", "", "", ""];
$tauxMargin = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
$chartColor = ["green", "green", "green", "green", "green", "green", "green", "green", "green", "green", "green", "green"];
$sumMarge = 0;
$sumMarge_1 = 0;
$moisToday = (int)(new \DateTime())->format('m');
$tauxMarginCumulle = 0;
$countMonth = 0;
for ($i = 0; $i < count($chartMarge); $i++) {
$chartMarge[$i] = round(((float)$valChartFactClient[$i] - (float)$valChartFact[$i] - (float)$valChartCoutGb[$i] - (float)$valChartNonLie[$i]), 2);
$sumMarge += (float)$chartMarge[$i];
if ($i < ($moisToday - 1)) {
$sumMarge_1 += (float)$chartMarge[$i];
}
if ($chartMarge[$i] < 0) {
$chartColor[$i] = "red";
}
if ($valChartFactClient[$i] != 0) {
$currentTaux = ((float)$chartMarge[$i] / $valChartFactClient[$i]) * 100;
$tauxMargin[$i] = number_format($currentTaux, 2, '.', '');
}
}
if ($sumMontantFactClient && $sumMontantFactClient['sum_ht'] != 0) {
$tauxMarginCumulle = ($sumMarge / $sumMontantFactClient['sum_ht']) * 100;
}
// $galeries = $this->loadGalerie(0);
// $tabFileDim = [];
// foreach ($galeries as $value) {
// $tabFileDim[$value->getId()] = ['width'=>0, 'height'=>0];
// try {
// $dir = $this->get('kernel')->getProjectDir()."/public/galerie/";
// $file = $dir.$value->getEntreprise()->getId() . "/" . $value->getCreatedAt()->format('Y-m-d') . "/" . $value->getNom();
// if(is_file($file)){
// list($orig_width, $orig_height) = getimagesize($file);
// $width = $orig_width;
// $height = $orig_height;
// $tabFileDim[$value->getId()] = ['width'=>$width, 'height'=>$height];
// }
// } catch (Exception $e) {
// }
// }
$full_month = $annee;
if ($mois && !empty($mois) && $annee)
$full_month = Carbon::parse("$annee-$mois-01")->locale('fr')->isoFormat('MMMM YYYY');
if ($request->query->get('test')) {
$galeries = [];
}
$galleryUser = $this->galerieRepository->getGalleryGroupByUser();
usort($galleryUser, function ($a, $b) {
return $b['nbr_gallery'] - $a['nbr_gallery'];
});
$maxPhotoVal = (count($galleryUser) > 0) ? $galleryUser[0]['nbr_gallery'] : 0;
$utilisateurs = $this->utilisateurRepository->getUserByEntreprise(true);
$countDocumentAttente = $entityManager->getRepository(EmailDocumentPreview::class)->countGroupByDossier();
$dossiers = [];
foreach ($countDocumentAttente as $value) {
switch ($value['dossier']) {
case "facturation":
$dossiers[] = [
'dossier' => "Facture Fournisseur",
'entity' => $value
];
break;
case "bon_livraison":
$dossiers[] = [
'entity' => $value,
'dossier' => "Bon de Livraison"
];
break;
case "facture_client":
$dossiers[] = [
'entity' => $value,
'dossier' => "Facture Client"
];
break;
case "devis_client":
$dossiers[] = [
'entity' => $value,
'dossier' => "Devis Client"
];
break;
case "devis_pro":
$dossiers[] = [
'entity' => $value,
'dossier' => "Devis Fournisseur"
];
break;
case "paie":
$dossiers[] = [
'entity' => $value,
'dossier' => "Fiche de Paie"
];
break;
default:
# code...
break;
}
}
return $this->render('home/index.html.twig', [
'full_month' => $full_month,
'valChart' => $valChart,
'valChartNonLie' => $valChartNonLie,
'valChartFact' => $valChartFact,
'valChartFactClient' => $valChartFactClient,
'valChartCoutGb' => $valChartCoutGb,
'chartMarge' => $chartMarge,
'tauxMargin' => $tauxMargin,
'tauxMarginCumulle' => $tauxMarginCumulle,
'valChartFactApayer' => $valChartFactApayer,
'valChartAmortMensAssurance' => $valChartAmortMensAssurance,
'mois' => $mois,
'annee' => $annee,
'form' => $form->createView(),
'montant' => $sumMontant,
'montantBlNonRelie' => $sumMontantNonLie,
'montantFact' => $sumMontantFact,
'montantFactClient' => $sumMontantFactClient,
'montantPayeFact' => $montantPayeFact,
'sumMontantAmortMensAssurance' => $sumMontantAmortMensAssurance,
'isgestionFinancements' => $isgestionFinancements,
'sumCoutGb' => $sumCoutGb,
'sumMarge' => $sumMarge,
'sumMarge_1' => $sumMarge_1,
'sumFactApayer' => $sumFactApayer,
'chartColor' => $chartColor,
'galleryUser' => $galleryUser,
'maxPhotoVal' => $maxPhotoVal,
'countDocumentAttente' => $dossiers,
'utilisateurs' => $this->global_s->getUserByMiniature($utilisateurs),
'ouvriers' => $utilisateurs,
'currentMonth' => Carbon::parse((new \DateTime())->format('Y-m-d'))->locale('fr')->isoFormat('MMMM YYYY')
]);
}
/**
* @Route("/load-galerie-xhr", name="load_galerie_xhr", methods={"GET"})
*/
public function loadGalerieXhr(Request $request)
{
$page = $request->query->get('page');
$offset = $page * 36;
$galeries = $this->loadGalerie($offset);
$tabFileDim = [];
foreach ($galeries as $value) {
$tabFileDim[$value->getId()] = ['width' => 0, 'height' => 0];
try {
$dir = $this->get('kernel')->getProjectDir() . "/public/galerie/";
$file = $dir . $value->getEntreprise()->getId() . "/" . $value->getCreatedAt()->format('Y-m-d') . "/" . $value->getNom();
if (is_file($file)) {
list($orig_width, $orig_height) = getimagesize($file);
$width = $orig_width;
$height = $orig_height;
$tabFileDim[$value->getId()] = ['width' => $width, 'height' => $height];
}
} catch (Exception $e) {
}
}
$datas = ['status' => 200, "message" => ""];
if (count($galeries) == 0) {
$datas['status'] = 300;
}
$datas['preview'] = $this->renderView('home/galerie.html.twig', [
'galeries' => $galeries,
'page' => $page,
'tabFileDim' => $tabFileDim
]);
$response = new Response(json_encode($datas));
return $response;
}
public function loadGalerie($offset = 0)
{
$galeries = $this->galerieRepository->findBy(['entreprise' => $this->session->get('entreprise_session_id')], ['id' => 'DESC'], 36, $offset);
// $galeries = $entityManager->createQueryBuilder()
// ->select('g')
// ->from('App\Entity\Galerie', 'g')
// ->andWhere('g.entreprise = :entreprise')
// ->setParameter('entreprise', $this->session->get('entreprise_session_id'))
// ->orderBy('g.id', 'DESC')
// ->setMaxResults(36)
// ->getQuery()
// ->getResult();
return $galeries;
}
public function calculCoutGlobalWithoutPaidOnMonth($chantierId = null, $mois = null, $annee = null)
{
$currentMonth = !is_null($mois) ? $mois : (new \DateTime())->format('m');
$currentYear = !is_null($annee) ? $annee : (new \DateTime())->format('Y');
$horaires = $this->horaireRepository->findByParams($chantierId, null, null, $currentMonth, $currentYear, null, null);
$absences = [
1 => "Congés Payés",
2 => "En arrêt",
3 => "Chômage Partiel",
4 => "Absence",
5 => "Formation",
6 => "RTT",
7 => "Férié"
];
$horairesArr = [];
$txMoyen = 0;
$totaux = ['heure' => 0, 'fictif' => 0, 'tx_moyen' => 0];
if (count($horaires)) {
$tabUserId = [];
foreach ($horaires as $value) {
$paie = $this->paieRepository->getLastPaieWithTx($value['user_id']);
$value['tx_moyen'] = $paie ? $paie['tx_moyen'] : 0;
$totaux['heure'] += $value['time'];
if (!array_key_exists($value['absence'], $absences))
$totaux['fictif'] += $value['fictif'];
elseif ($value['absence'] == 5) {
$totaux['fictif'] += 7;
}
//nous avons juste besoins d'une seule valuer par user
if (!in_array($value['user_id'], $tabUserId)) {
if ($value['tx_moyen'] > 0) {
$txMoyen += $value['tx_moyen'];
$tabUserId[] = $value['user_id'];
}
}
}
if (count($tabUserId))
$txMoyen = $txMoyen / count($tabUserId);
}
$totaux['tx_moyen'] = $txMoyen;
return $totaux;
}
/**
* @Route("/split-pdf-bill/{doc}", name="split_pdf_bill", requirements={"doc"=".+"})
*/
public function splitPDF(Request $request, $doc = null, ParameterBagInterface $params)
{
$outputDir = $params->get('kernel.project_dir') . "/public/test-google";
if (!is_dir($outputDir)) {
mkdir($outputDir, 0777, true);
}
if ($doc) {
$fileToSend = $doc;
} else {
$fileToSend = $params->get('kernel.project_dir') . "/public/test-google/bulletin-fulling.pdf";
}
try {
$ilovepdf = new Ilovepdf('project_public_931609e2e0edbf50c10eaeb858e470f3_fsjDZdb3b9cdf88dab190f9056c68e18de17a', 'secret_key_2b723a927cff7ba74a71d1fdfad73a9e_wF2qzfa225b5b9be2dbcc23bc29ba9b4c0722');
} catch (\Exception $e) {
throw new \Exception("Erreur de connexion à l'API de conversion de pdf", 1);
}
$nbrePages = $this->countPage($fileToSend);
// Create a new task
$myTaskSplit = $ilovepdf->newTask('split');
// Add files to task for upload
$file1 = $myTaskSplit->addFile($fileToSend); // PDF filename
// Set your tool options
//$myTaskSplit->setRanges('2-4,6-8');
// Execute the task
$myTaskSplit->execute();
// Download the package files
$myTaskSplit->download($outputDir);
// UNZIP FILE
if (file_exists($outputDir . '/output.zip')) {
$zip = new ZipArchive();
$res = $zip->open($outputDir . '/output.zip');
if ($res === TRUE) {
$zip->extractTo($outputDir);
$zip->close();
}
unlink($outputDir . '/output.zip');
}
//Lecture des fichiers correspondants
$docSplit = [];
for ($i = 1; $i <= $nbrePages; $i++) {
$docSplit[] = substr($fileToSend, 0, -4) . '-' . $i . '.pdf';
}
natsort($docSplit);
$dataForDoc = [];
foreach ($docSplit as $doc) {
if ($doc == '.' || $doc == '..') {
continue;
}
//$newName = $outputDir.'/'.$this->arrangeName($doc);
//rename($outputDir.'/'.$doc, $newName);
$dataForDoc[] = $this->extractFromGoogle($doc, $params);
}
//dd($dataForDoc);
$splitRange = '';
$numPage = 1;
foreach ($dataForDoc as $item) {
if (isset($item['nom'])) {
$username = $item['nom'];
$docRange = $this->SearchSimilar($username, $dataForDoc);
if ($docRange != '') {
if ($splitRange != '')
$splitRange .= ',';
$splitRange .= $docRange;
}
} else {
if ($splitRange != '')
$splitRange .= ',';
$splitRange .= $numPage;
}
$numPage++;
}
$splitRange = explode(',', $splitRange);
$splitRange = array_unique($splitRange);
$listeDocRetour = [];
foreach ($splitRange as $elt) {
$toMerge_array = explode('-', $elt);
if (count($toMerge_array) == 2) {
$merged = $this->mergeSimilarfile($fileToSend, $toMerge_array, $ilovepdf, $outputDir);
$listeDocRetour[] = $this->extractPath($merged, $outputDir);
} else {
$listeDocRetour[] = $this->extractPath(substr($fileToSend, 0, -4) . '-' . $toMerge_array[0] . '.pdf', $outputDir);
}
}
try {
unlink($fileToSend);
} catch (\Throwable $th) {
//throw $th;
}
$splitRange = implode(',', $splitRange);
print_r($listeDocRetour);
return new Response("Traitement terminé. Nouveau découpage: $splitRange");
}
public function extractPath($nameWithPath, $path)
{
$nameWithPath = str_replace($path, '', $nameWithPath);
$nameWithPath = str_replace('/', '', $nameWithPath);
return $nameWithPath;
}
public function mergeSimilarfile($fileToSend, $tabList, $ilovepdf, $savePath)
{
$myTaskMerge = $ilovepdf->newTask('merge');
for ($i = (int)$tabList[0]; $i <= (int)$tabList[1]; $i++) {
$myTaskMerge->addFile(substr($fileToSend, 0, -4) . '-' . $i . '.pdf');
}
$myTaskMerge->execute();
$myTaskMerge->download($savePath);
rename($savePath . '/merged.pdf', substr($fileToSend, 0, -4) . '-' . $tabList[0] . '-' . $tabList[1] . '.pdf');
for ($i = (int)$tabList[0]; $i <= (int)$tabList[1]; $i++) {
try {
unlink(substr($fileToSend, 0, -4) . '-' . $i . '.pdf');
} catch (\Throwable $th) {
//throw $th;
}
}
return substr($fileToSend, 0, -4) . '-' . $tabList[0] . '-' . $tabList[1] . '.pdf';
}
public function countPage($path)
{
$pdf = file_get_contents($path);
$number = preg_match_all("/\/Page\W/", $pdf, $dummy);
return $number;
}
public function SearchSimilar($value, $tableau)
{
$index = 1;
$otherPages = [];
foreach ($tableau as $item) {
if (isset($item['nom']) && ($item['nom'] == $value)) {
$otherPages[] = $index;
}
$index++;
}
$nbreResult = count($otherPages);
if ($otherPages[0] == $otherPages[$nbreResult - 1])
return $otherPages[0] . '';
return $nbreResult > 0 ? $otherPages[0] . '-' . $otherPages[$nbreResult - 1] : '';
}
public function arrangeName($string)
{
$table = array(
'-1.pdf' => '-01.pdf',
'-2.pdf' => '-02.pdf',
'-3.pdf' => '-03.pdf',
'-4.pdf' => '-04.pdf',
'-5.pdf' => '-05.pdf',
'-6.pdf' => '-06.pdf',
'-7.pdf' => '-07.pdf',
'-8.pdf' => '-08.pdf',
'-9.pdf' => '-09.pdf',
);
return strtr($string, $table);
}
public function extractFromGoogle($doc, $params)
{
if ($doc) {
$b64Doc = base64_encode(file_get_contents($doc));
} else {
$fileToSend = $params->get('kernel.project_dir') . "/public/test-google/bulletin-2.pdf";
$b64Doc = base64_encode(file_get_contents($fileToSend));
}
$token = file_get_contents($params->get('kernel.project_dir') . "/public/google-token.txt");
$token = substr($token, 0, -1);
$postParameter = [
"skipHumanReview" => true,
"inlineDocument" => [
"mimeType" => "Application/pdf",
"content" => $b64Doc
]
];
$requeteJSON = json_encode($postParameter);
$curlHandle = curl_init('https://eu-documentai.googleapis.com/v1/projects/673985886308/locations/eu/processors/cd248572704a7ad7/processorVersions/663d22d0d2354323:process');
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $token,
'Content-Type: application/json; charset=utf-8'
]);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $requeteJSON);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
$curlResponse = curl_exec($curlHandle);
//Gestion de la réponse
$http_status = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
if ($http_status == 200) {
$dataReturn = json_decode($curlResponse);
$entities = $dataReturn->document->entities;
return array_column($entities, 'mentionText', 'type');
}
return null;
}
/**
* @Route("/testons", name="testons")
*/
public function checkDatas(Request $request, ParameterBagInterface $params)
{
$path = $params->get('kernel.project_dir') . "/public/test-google/";
//$doc = $params->get('kernel.project_dir') . "/public/test-google/BL.pdf";
$doc = "https://dockeo.fr/uploads/achats/facturation/BL_87699229_20230725_13512764bfb7a0b2e3864bfb8e4298f1.pdf";
$filenameImg = "Astu";
if(!$this->convertFromPDFToJPG($doc, $filenameImg, $path)){
dd("Problème lors de la conversion de ".$doc);
}
$documentPath = $path.$filenameImg.".jpg";
$fp_image = fopen($documentPath, 'r');
$image = fread($fp_image, filesize($documentPath));
fclose($fp_image);
try {
$client = new \Aws\Textract\TextractClient([
'region' => 'us-east-1',
'version' => 'latest',
'credentials' => array(
'key' => "AKIA4WXTGEBWCTPMQAXL",
'secret' => "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",
)
]);
} catch (\Exception $e) {
throw new \Exception("Erreur de connexion à l'API OCR", 1);
}
$resultSummaryFields = $client->analyzeExpense ([
'Document' => [ // REQUIRED
'Bytes' => $image,
],
]);
dd($resultSummaryFields);
return new Response();
}
public function convertFromPDFToJPG(string $urlFile, $filenameImg, $path): string{
$image = "";
$postParameter = [
"Parameters" => [
[
"Name" => "File",
"FileValue" => [
"Name" => "Mon_PDF.pdf",
"Data" => base64_encode(file_get_contents($urlFile)) // base64 encode file_content
]
],
[
"Name" => "StoreFile",
"Value" => true
]
]
];
$curlHandle = curl_init('https://v2.convertapi.com/convert/pdf/to/jpg?Secret=u2NOZjqsk0X6oKDw');
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, json_encode($postParameter));
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
$curlResponse = json_decode(curl_exec($curlHandle));
//Gestion de la réponse
$http_status = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
if($http_status == 200){
$resultats = $curlResponse->Files;
$i = 1;
if(count($resultats)){
//Creation du dossier de sauvegarde
$dirTmp = $path.$filenameImg."/";
try {
if (!is_dir($dirTmp)) {
mkdir($dirTmp, 0777, true);
}
} catch (FileException $e) {}
foreach($resultats as $result){
$resultat = $result->Url;
$context = stream_context_create(array('http'=>array('protocol_version'=>'1.1')));
$returnImg = file_get_contents($resultat, false, $context);
file_put_contents($dirTmp.$filenameImg.$i++.".jpg", $returnImg);
}
return $this->mergeJpgFiles($dirTmp, $path, $filenameImg.".jpg");
}
}else{
print_r("Problème lors de la conversion en JPG de ".$path.$filenameImg);
}
return $image;
}
public function mergeJpgFiles(string $tmpdir, string $saveDir, string $filename): string{
$files = [];
if(is_dir($tmpdir))
$files = array_diff(scandir($tmpdir), array('.', '..'));
//MERGE LES FICHIERS IMAGES EN UNE SEULE POUR ENVOYER à AWS OCR
if(count($files)){
$nbrPageMax = count($files) > 12 ? 12 : count($files);
list($imgWidth, $imgHeight) = getimagesize($tmpdir.array_values($files)[0]);
$calque = imagecreatetruecolor($imgWidth, ($imgHeight*$nbrPageMax));
$i = 0;
foreach ($files as $value) {
if($i > $nbrPageMax)
break;
imagecopy($calque, imagecreatefromjpeg($tmpdir.$value), 0, $imgHeight*$i, 0, 0, $imgWidth, $imgHeight);
$i++;
}
$dirSave = $saveDir.$filename;
try {
imagejpeg($calque, $dirSave);
} catch (\Exception $e) {
return false;
//dd(["ERROR:".$e->getMessage() ,$dirSave, $calque]);
}
}
return $dirSave;
}
function base64ToImage($base64_string, $output_file) {
$file = fopen($output_file, "wb");
$data = explode(',', $base64_string);
fwrite($file, base64_decode($data[1]));
fclose($file);
return $output_file;
}
public function findAllChantierInTmpOcr($entityName = null, $filename, $dossier, $entrepriseId){
$em = $this->getDoctrine()->getManager();
$entityName = str_replace("'", "", $entityName);
$retourArr = [];
if (!$entityName) {
$chantiers = $em->getRepository(Chantier::class)->getByEntrepriseOdreByBl($entrepriseId);
foreach ($chantiers as $value) {
if (strtolower($value['nom']) == 'a definir' || strtolower($value['nom']) == 'fmda construction')
continue;
$newValue = str_replace("'", " ", $value['nom']);
$entityfound = $em->getRepository(OcrField::class)->findChantierBrute($dossier, $entrepriseId, $filename, $newValue);
/* autre tentative avec recherche sur les deux premiers mots */
if ($entityfound == false) {
$fournisseurName = str_replace("-", ' ', $value['nom']);
$fournisseurName = str_replace(" ", ' ', $fournisseurName);
$fournisseurNameArr = explode(' ', $fournisseurName);
if (count($fournisseurNameArr) >= 2) {
//$fournisseurName = $fournisseurNameArr[0].' '.$fournisseurNameArr[1];
foreach ($fournisseurNameArr as $fourni) {
if (strlen($fourni) >= 4) {
$result = $this->findAllChantierInTmpOcr($fourni, $filename, $dossier, $entrepriseId);
if ($result)
$retourArr[] = $result;
}
}
}
}else{
$retourArr[] = $entityfound;
break;
}
}
}else{
$entityfound = $em->getRepository(OcrField::class)->findChantierBrute($dossier, $entrepriseId, $filename, $entityName);
if ($entityfound != false) {
return $entityfound;
}
}
return $retourArr;
}
public function dataLookLike($elt, $checker)
{
return $elt == $checker;
}
public function removeDoublon($fournisseurArr){
$retour = [];
foreach($fournisseurArr as $item){
if(!in_array($item['name'], array_column($retour, 'name')))
$retour [] = $item;
}
return $retour;
}
/**
* @Route("/eden_ai_debug/{doc}", name="eden_ai_debug", requirements={"doc"=".+"})
*/
public function edenAiDebug(Request $request, $doc = null, ParameterBagInterface $params)
{
if(!$doc){
$doc = "https://dockeo.fr/test-google/facture.pdf";
}
$edenAiResult = $this->edenAi->scanWithEdenAi($doc);
//dd($_SERVER['SERVER_NAME']);
//$edenAiResult = $edenAiResult->google->extracted_data;
//$edenAiResult = $edenAiResult[0];
dd($this->edenAi->getDatasFromEdenAi($edenAiResult, 'google'));
return $this->render('error/503.html.twig');
}
/**
* @Route("/find_best_num_bl/{previewDoc}/{type}", name="find_best_num_bl")
*/
public function findBestMatchTextRefNumBL(EmailDocumentPreview $previewDoc = null, $type = "bl")
{
dd($this->findNumBLService->findCustumNumBL($previewDoc));
$listNumBL = $this->findNumBLService->findBestMatchTextRefNum($previewDoc, $type);
$AR = (array_key_exists('AR', $listNumBL) && $listNumBL['AR']) ? true : false;
$PF = (array_key_exists('PF', $listNumBL) && $listNumBL['PF']) ? true : false;
dd($this->findNumBLService->extractNumfromChaine($listNumBL['num_BL_found'], $listNumBL['good_text_Ref'], $PF, $AR));
return $this->render('error/503.html.twig');
}
/**
* @Route("/get_email_doc/{previewDoc}", name="get_email")
*/
public function getEmailFromTmpExpense(EmailDocumentPreview $previewDoc)
{
if(str_contains($previewDoc->getDocument(), '.pdf')){
$filename = str_replace('.pdf', '.jpg', $previewDoc->getDocument());
}else{
$filename = str_replace('.PDF', '.jpg', $previewDoc->getDocument());
}
$listEmail = $this->getDoctrine()->getRepository(TmpExpense::class)->findEmailInTmpExpense($previewDoc->getDossier(), $filename);
dd($listEmail);
return $this->render('error/503.html.twig');
}
/**
* @Route("/file-delete/{dossier}/{filename}", name="file_delete")
*/
public function deleteFileAPI(Request $request, ParameterBagInterface $params, string $dossier = "", string $filename = "")
{
if($dossier && $filename){
$file = $params->get('kernel.project_dir') . "/public/".$this->getDirFiles($dossier)."/".$filename;
if(file_exists($file)){
unlink($file);
}
}
return new JsonResponse(true);
}
public function getDirFiles(string $dossier){
switch ($dossier) {
case 'facturation':
return "uploads/achats/facturation/";
case 'bon_livraison':
return "uploads/factures/";
case 'devis_pro':
return "uploads/devis/";
case 'facture_client':
return "uploads/clients/factures/";
case 'devis_client':
return "uploads/devis/";
case 'paie':
return "uploads/paies/";
case 'cheque':
return "uploads/banque/";
case 'lcr':
return "uploads/lcr/";
case 'outillage':
return "uploads/image_outillage/";
case 'vehicule':
return "uploads/vehicule/document/";
default:
return "inconu";
}
}
/**
* @Route("/google_ai_debug/{doc}", name="google_ai_debug", requirements={"doc"=".+"})
*/
public function googleAiDebug(Request $request, $doc = null, ParameterBagInterface $params)
{
if ($doc) {
$b64Doc = base64_encode(file_get_contents($doc));
} else {
$fileToSend = $params->get('kernel.project_dir') . "/public/test-google/bulletin-debug.pdf";
$b64Doc = base64_encode(file_get_contents($fileToSend));
}
$token = file_get_contents($params->get('kernel.project_dir') . "/public/google-token.txt");
$token = substr($token, 0, -1);
$postParameter = [
"skipHumanReview" => true,
"inlineDocument" => [
"mimeType" => "Application/pdf",
"content" => $b64Doc
]
];
$requeteJSON = json_encode($postParameter);
$curlHandle = curl_init('https://eu-documentai.googleapis.com/v1/projects/673985886308/locations/eu/processors/cd248572704a7ad7/processorVersions/4b2bc30d3fbe3865:process');
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $token,
'Content-Type: application/json; charset=utf-8'
]);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $requeteJSON);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
$curlResponse = curl_exec($curlHandle);
//Gestion de la réponse
$http_status = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
if ($http_status == 200) {
echo 'TRAITEMENT AVEC SUCCES';
$dataReturn = json_decode($curlResponse);
$entities = $dataReturn->document->entities;
echo '<br><br>LE DOCUMENT RETOURNE EN ENTIER';
dd($entities);
} else {
print_r('ECHEC DE TRAITEMENT');
dd(json_decode($curlResponse));
}
curl_close($curlHandle);
return $this->render('error/503.html.twig');
}
/**
* @Route("/date-debug", name="debug-date")
*/
public function debugDate(Request $request)
{
$dateO = 0;
if ($dateO) {
print_r(date_format($dateO, 'd-m-Y'));
} else {
print_r("La date n'a pas pu être formaté");
}
return $this->render('error/503.html.twig');
}
}