<?php
namespace App\Controller;
use App\Entity\FactureAaf;
use App\Entity\Installateur;
use App\Entity\Docfacture;
use App\Form\FactureAafType;
use App\Repository\FactureAafRepository;
use App\Repository\DocfactureRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Service\FileUploader;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\String\Slugger\SluggerInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Datetime;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Repository\NotificationsRepository;
use App\Repository\InstallateurRepository;
use App\Repository\EquipeRepository;
use Symfony\Component\Process\Process;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Fill;
/**
* @Route("/facture")
*/
class FactureAafController extends AbstractController
{
/**
* @Route("/", name="app_facture_aaf_index", methods={"GET", "POST"})
*/
public function index(FactureAafRepository $factureAafRepository): Response
{
if ($this->isGranted('ROLE_INSTALLATEUR')){
$factureAaf=[];
foreach ($factureAafRepository->findAll() as $key => $aaf) {
foreach ($aaf->getDossier() as $key => $doss) {
if ($doss->getDeal()->getInstallateur()->getId() == $this->getUser()->getInstallateur()->getId() ) {
$factureAaf[]=$aaf;
}
}
}
}else{
$factureAaf= $factureAafRepository->findAll();
}
$tab=[];
$factureAafs=[];
// id,type as owner,client as name ,date,file ,batiment
foreach ($factureAaf as $value) {
$j = 0;
$dossi = "";
if ($value->getNumero() != null) {
$tab['id']=$value->getId();
//$tab['id_dossier']=$value->getDossier()->getId();
$tab['name']=$value->getNumero();
$tab['owner']=$value->getDepotaaf();
$tab['count']=count($value->getDossier());
foreach ($value->getDossier() as $key => $doss) {
if ($j==0) {
$dossi= $doss->getDeal()->getDealoblige()->getNom();
$j=$j+1;
}
}
$tab['industry_type']=$dossi;
$factureAafs[]=$tab;
}
}
//dd($factureAafs);
$clientjson = json_encode($factureAafs);
// var_dump(json_encode($clientjson ));
file_put_contents('assets/json/factureaaf-list.json', $clientjson);
return $this->render('facture_aaf/index.html.twig', [
'facture_aafs' => $factureAafRepository->findAll(),
]);
}
/**
* @Route("/new", name="app_facture_aaf_new", methods={"GET", "POST"})
*/
public function new(Request $request, EntityManagerInterface $entityManager): Response
{
$factureAaf = new FactureAaf();
$form = $this->createForm(FactureAafType::class, $factureAaf);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->persist($factureAaf);
$entityManager->flush();
return $this->redirectToRoute('app_facture_aaf_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('facture_aaf/new.html.twig', [
'facture_aaf' => $factureAaf,
'form' => $form,
]);
}
/**
* @Route("/{id}", name="app_facture_aaf_show", methods={"GET"})
*/
public function show(FactureAaf $factureAaf): Response
{
// $factureAaf= $factureAafRepository->findAll();
if ($this->isGranted('ROLE_INSTALLATEUR')){
$parameters = ['facture' => $factureAaf->getNumero()];
return $this->redirectToRoute('app_facture_aaf_installateur_show', ['id' => $this->getUser()->getInstallateur()->getId()]+$parameters, Response::HTTP_SEE_OTHER);
}
$tab=[];
$factureAafs=[];
$cumacTotal=0;
$installateur=[];
$instid=[];
$oblige ="";
foreach ($factureAaf->getDossier() as $value) {
if ($value->getNumero() != null) {
$tab['id']=$value->getDeal()->getInstallateur()->getId();
$tab['id_dossier']=$value->getId();
$tab['owner']=$value->getNumero();
$tab['name']=$value->getDeal()->getInstallateur()->getSociete();
if (!in_array($value->getDeal()->getInstallateur()->getId(), $instid)) {
$installateur[]=$value->getDeal()->getInstallateur();
$instid[]=$value->getDeal()->getInstallateur()->getId();
}
$tab['industry_type']=$value->getCumac();
$tab['location']=$factureAaf->getNumero();
$factureAafs[]=$tab;
$cumacTotal =$cumacTotal+$value->getCumac();
$oblige = $value->getDeal()->getDealoblige()->getNom();
}
}
//dd($installateur);
$clientjson = json_encode($factureAafs);
// var_dump(json_encode($clientjson ));
file_put_contents('assets/json/showaaf-list.json', $clientjson);
return $this->render('facture_aaf/show.html.twig', [
'facture_aaf' => $factureAaf,
'TotalCumac' => $cumacTotal,
'installateur' => $installateur,
'oblige' =>$oblige
]);
}
/**
* @Route("/installateur/{id}", name="app_facture_aaf_installateur_show", methods={"GET"})
*/
public function showinst(Request $request,Installateur $installateur,FactureAafRepository $factureAafRepository,DocfactureRepository $docfactureRepository): Response
{
// $factureAaf= $factureAafRepository->findAll();
$form = $request->request;
$factureAaf = $factureAafRepository->findOneBy(["numero" => $request->get("facture")]);
$tab=[];
$factureAafs=[];
$cumacTotal=0;
$oblige ="";
$taux =0;
$docfacture=[];
foreach ($factureAaf->getDossier() as $value) {
if ($value->getNumero() != null) {
if ($value->getDeal()->getInstallateur()->getId() == $installateur->getId()) {
$factureAafs[]=$value;
$cumacTotal =$cumacTotal+$value->getCumac();
$oblige = $value->getDeal()->getDealoblige()->getNom();
$taux =$value->getDeal()->getTaux();
}
}
}
foreach ($factureAaf->getDocfactures() as $key => $doc) {
if ($doc->getInstallateur()->getId() == $installateur->getId()) {
$docfacture= $doc;
}
}
// dd($factureAafs);
// $clientjson = json_encode($factureAafs);
// var_dump(json_encode($clientjson ));
// file_put_contents('assets/json/showaaf-list.json', $clientjson);
return $this->render('facture_aaf/showinst.html.twig', [
'installateur_aaf' => $installateur,
'TotalCumac' => $cumacTotal,
'oblige' =>$oblige,
'facture_aafs' => $factureAafs,
'factureAaf' => $factureAaf,
'taux' =>$taux,
'docfacture' => $docfacture
]);
}
/**
* @Route("/installateur/exportedepot/{id}", name="app_facture_aaf_installateur_exporte", methods={"GET"})
*/
public function exporte(Request $request,Installateur $installateur,FactureAafRepository $factureAafRepository,DocfactureRepository $docfactureRepository): Response
{
// $jsonFilePath = 'assets/json/dossier-list.json';
// Étape 1 : Récupérer le contenu JSON depuis le fichier
// $jsonContent = file_get_contents($jsonFilePath);
// Étape 2 : Décoder le contenu JSON en tableau PHP
$factureAaf = $factureAafRepository->findOneBy(["numero" => $request->get("facture")]);
$numeroaaf=$factureAaf->getNumero();
$tab=[];
$factureAafs=[];
$cumacTotal=0;
$oblige ="";
$taux =0;
$docfacture=[];
foreach ($factureAaf->getDossier() as $value) {
if ($value->getNumero() != null) {
if ($value->getDeal()->getInstallateur()->getId() == $installateur->getId()) {
$factureAafs[]=$value;
$cumacTotal =$cumacTotal+$value->getCumac();
$oblige = $value->getDeal()->getDealoblige()->getNom();
$taux =$value->getDeal()->getTaux();
}
}
}
foreach ($factureAaf->getDocfactures() as $key => $doc) {
if ($doc->getInstallateur()->getId() == $installateur->getId()) {
$docfacture= $doc;
}
}
$phpArray = $factureAafs;
// Créer un nouveau classeur Excel
$spreadsheet = new Spreadsheet();
// Obtenir la feuille active
$sheet = $spreadsheet->getActiveSheet();
// Écrire des données dans la feuille
$totalcumac = 0;
$taux = 0;
$sheet->setCellValue('A1', 'Numéro dossier');
$sheet->getStyle('A1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('BAE1FF');
$sheet->getStyle('A1')->getFont()->setBold(true);
$sheet->setCellValue('B1', 'Nom du Beneficiaire');
$sheet->getStyle('B1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('BAE1FF');
$sheet->getStyle('B1')->getFont()->setBold(true);
$sheet->setCellValue('C1', 'Deal associé');
$sheet->getStyle('C1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('BAE1FF');
$sheet->getStyle('C1')->getFont()->setBold(true);
$sheet->setCellValue('D1', 'KWh Cumac');
$sheet->getStyle('D1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('BAE1FF');
$sheet->getStyle('D1')->getFont()->setBold(true);
$sheet->setCellValue('E1', 'Taux');
$sheet->getStyle('E1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('BAE1FF');
$sheet->getStyle('E1')->getFont()->setBold(true);
$sheet->setCellValue('F1', 'Prime');
$sheet->getStyle('F1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('BAE1FF');
$sheet->getStyle('F1')->getFont()->setBold(true);
$sheet->getColumnDimension('A')->setWidth(15);
$sheet->getColumnDimension('B')->setWidth(18);
$sheet->getColumnDimension('C')->setWidth(15);
$sheet->getColumnDimension('D')->setWidth(15);
$sheet->getColumnDimension('E')->setWidth(15);
$sheet->getColumnDimension('F')->setWidth(15);
$i=2;
if ($phpArray === null) {
echo "Erreur Tableau vide: ";
} else {
// Utilisez le tableau PHP $phpArray comme bon vous semble
foreach ($phpArray as $dl) {
// $dl=$depotDossierRepository->findOneBy(["id"=>intval($value["id"])]);
$sheet->setCellValue('A'.$i, $dl->getNumero());
$sheet->setCellValue('B'.$i, $dl->getPrenomclient().' '.$dl->getNomclient() );
$sheet->setCellValue('C'.$i, $dl->getDeal()->getDealoblige()->getNom());
$sheet->setCellValue('D'.$i, $dl->getCumac());
$sheet->setCellValue('E'.$i, $dl->getDeal()->getTaux());
$sheet->setCellValue('F'.$i, $dl->getCumac() * ($dl->getDeal()->getTaux() / 1000));
$totalcumac = $totalcumac + $dl->getCumac();
$taux = $dl->getDeal()->getTaux() / 1000;
$i=$i+1;
}
}
$sheet->setCellValue('A'.$i+2, 'Total Cumac');
$sheet->getStyle('A'.$i+2)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('96CEB4');
$sheet->getStyle('A'.$i+2)->getFont()->setBold(true);
$sheet->setCellValue('B'.$i+2, $totalcumac);
$sheet->getStyle('B'.$i+2)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('96CEB4');
$sheet->getStyle('B'.$i+2)->getFont()->setBold(true);
$sheet->setCellValue('A'.$i+3, 'Total Prime');
$sheet->getStyle('A'.$i+3)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('96CEB4');
$sheet->getStyle('A'.$i+3)->getFont()->setBold(true);
$sheet->setCellValue('B'.$i+3, $totalcumac * $taux);
$sheet->getStyle('B'.$i+3)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('96CEB4');
$sheet->getStyle('B'.$i+3)->getFont()->setBold(true);
// Créer un objet Writer pour enregistrer le fichier
$writer = new Xlsx($spreadsheet);
// Enregistrer le fichier à un emplacement
$now = new DateTime();
$date = $now->format('d-m-Y H-i-s');
$nomexecel = "factureAAf-".$numeroaaf."-".$installateur->getSociete()."-".$date;
$cheminFichier =$this->getParameter('installateur_directory') . "/export/export".$nomexecel.".xlsx";
$writer->save($cheminFichier);
// $filtre->setExporte("export".$nomexecel.".xlsx");
// $filtreRepository->add($filtre, true);
// Renvoyer la réponse avec le fichier Excel en pièce jointe
return $this->file($cheminFichier);
}
/**
* @Route("/{id}/edit", name="app_facture_aaf_edit", methods={"GET", "POST"})
*/
public function edit(Request $request, FactureAaf $factureAaf, EntityManagerInterface $entityManager): Response
{
$form = $this->createForm(FactureAafType::class, $factureAaf);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->flush();
return $this->redirectToRoute('app_facture_aaf_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('facture_aaf/edit.html.twig', [
'facture_aaf' => $factureAaf,
'form' => $form,
]);
}
/**
* @Route("/{id}", name="app_facture_aaf_delete", methods={"POST"})
*/
public function delete(Request $request, FactureAaf $factureAaf, EntityManagerInterface $entityManager): Response
{
if ($this->isCsrfTokenValid('delete'.$factureAaf->getId(), $request->request->get('_token'))) {
$entityManager->remove($factureAaf);
$entityManager->flush();
}
return $this->redirectToRoute('app_facture_aaf_index', [], Response::HTTP_SEE_OTHER);
}
/**
* @Route("/upload/{id}", methods={"POST"})
*/
public function upload(Request $request ,FactureAaf $factureAaf,InstallateurRepository $installateurRepository,
FileUploader $uploader,EquipeRepository $equipeRepository,NotificationsRepository $notificationsRepository,DocfactureRepository $docfactureRepository): JsonResponse
{
if ($request->getMethod() == "POST") {
$file=$request->files->get('file');
if ($file) {
$installateur = $installateurRepository->findOneBy(["id" => $request->get("idinstallateur")]);
if ($request->get("iddocfacture")) {
$docfacture = $docfactureRepository->findOneBy(["id" => $request->get("iddocfacture")]);
}else{
$docfacture = new Docfacture();
$docfacture->setAaf($factureAaf);
$docfacture->setInstallateur($installateur);
}
$now = new DateTime();
$date = $now->format('d-m-Y');
$destination = $this->getParameter('installateur_directory');
$fileName = explode('.',$file->getClientOriginalName())[0].'.'.$file->getClientOriginalExtension();
$fileName = $request->get("donne")."-".$factureAaf->getNumero()."-".$installateur->getSociete().'-'.$date.'.'.$file->getClientOriginalExtension();
$file->move($destination, $fileName);
if ($request->get("donne")=='model') {
$docfacture->setModel($fileName);
}
if ($request->get("donne")=='facture') {
$docfacture->setFacture($fileName);
}
$docfactureRepository->add($docfacture, true);
// $activiteDeal = new ActiviteDeal();
if ($this->isGranted('ROLE_INSTALLATEUR')) {
$admins = $equipeRepository->findAll();
foreach ($admins as $key => $value) {
$listrole = $value->getRole();
if($listrole == "ROLE_MANAGER" || $listrole == "ROLE_ADMIN" ){
$notifications = new Notifications();
$notifications->setUserId($value->getUser());
$notifications->setAction("app_facture_aaf_show");
$notifications->setMessage($installateur->getSociete()."à ajoutés sa facture AAf : ".$factureAaf->getNumero());
$notifications->setActionId($factureAaf->getId());
$notifications->setSender($this->getUser());
$notifications->setStatuts("non lu");
$notifications->setDate(new DateTime());
$notificationsRepository->add($notifications, true);
}
}
// $admins = $equipeRepository->findAll();
// foreach ($admins as $key => $value) {
// $listPermissions = $value->getPermissions();
// foreach ($listPermissions as $v) {
// if($v == "NOTIFICATION" ){
// $notifications = new Notifications();
// $notifications->setUserId($value->getUser());
// $notifications->setAction("app_deal_edit");
// $notifications->setMessage("Des documents ont été ajoutés pour le deal ".$champsDeal->getNumero());
// $notifications->setActionId($champsDeal->getId());
// $notifications->setSender($this->getUser());
// $notifications->setStatuts("non lu");
// $notifications->setDate(new DateTime());
// $notificationsRepository->add($notifications, true);
// }
// }
// }
// $activiteDeal->setFonction('installateur');
// $activiteDeal->setInstallateur($this->getUser()->getInstallateur());
}else{
// $activiteDeal->setFonction('equipe');
// $activiteDeal->setEquipe($this->getUser()->getEquipe());
}
// $activiteDeal->setCommentaire("À déposé le document ".$champsDeal->getNom());
// $activiteDeal->setDate(new Datetime());
// $activiteDeal->setDeal($champsDeal->getDeal());
// $activiteDealRepository->add($activiteDeal, true);
// Historique
// $historiqueDeal = new HistoriqueDeal();
// $historiqueDeal->setUser($this->getUser());
// $historiqueDeal->setDeal($champsDeal->getDeal());
// $historiqueDeal->setDate(new DateTime());
// $historiqueDeal->setAction("Importation du document ".$champsDeal->getNom()." dans le Deal ".$champsDeal->getDeal()->getNumero());
// $historiqueDealRepository->add($historiqueDeal, true);
return $this->json(['success' => true, 'message' => 'Fichier téléchargé et ajouté en base de données avec succès']);
}
}
return $this->json(['success' => false, 'error' => 'Erreur lors du téléchargement du fichier']);
}
}