Thanasoft-Hytha/gestion/lib/Service/InvoicePdfService.php
2025-04-14 16:01:19 +03:00

336 lines
14 KiB
PHP

<?php
declare(strict_types=1);
/**
* Calendar App
*
* @copyright 2021 Anna Larch <anna.larch@gmx.net>
*
* @author Anna Larch <anna.larch@gmx.net>
* @author Richard Steinmetz <richard@steinmetz.cloud>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Gestion\Service;
use DateTime;
use OCA\Gestion\Constants\BddConstant;
use OCA\Gestion\Constants\ClientTemplateTypeConstant;
use OCA\Gestion\Constants\DevisMentionConstant;
use OCA\Gestion\Constants\FactureTypeConstant;
use OCA\Gestion\Constants\MultipleFactureTypeConstant;
use OCA\Gestion\Db\Bdd;
use OCA\Gestion\Helpers\DateHelpers;
use OCA\Gestion\Service\InvoiceGroupPdfHandler\InvoiceFunecapPdfHandler;
use OCA\Gestion\Service\InvoiceGroupPdfHandler\InvoiceGroupPdfHandler;
use OCA\Gestion\Service\InvoiceGroupPdfHandler\InvoiceOgfPdfHandler;
use OCA\Gestion\Service\InvoiceRecap\InvoiceRecapService;
use OCP\DB\Exception;
use OCP\Files\IRootFolder;
class InvoicePdfService {
/** @var Bdd */
private $gestionBdd;
/** @var IRootFolder */
private $rootFolder;
/** @var InvoiceRecapService */
private $invoiceRecapService;
private const DEFAULT_NEXTCLOUD_ADMIN = "admin";
public function __construct(
Bdd $gestionBdd,
IRootFolder $rootFolder,
InvoiceRecapService $invoiceRecapService) {
$this->gestionBdd = $gestionBdd;
$this->rootFolder = $rootFolder;
$this->invoiceRecapService = $invoiceRecapService;
}
private function getLogo(){
$storage = $this->rootFolder->getUserFolder(self::DEFAULT_NEXTCLOUD_ADMIN);
try{
try {
if(isset($storage)){
$file = $storage->get('/.gestion/logo.png');
}else{
return "nothing";
}
} catch(\OCP\Files\NotFoundException $e) {
$file = $storage->get('/.gestion/logo.jpeg');
}
}
catch(\OCP\Files\NotFoundException $e) {
return "nothing";
}
return base64_encode($file->getContent());
}
private function generateFactureSinglePdfByFactureId($factureId,$idNextCloud){
$storage = $this->rootFolder->getUserFolder($idNextCloud);
$configs = json_decode($this->gestionBdd->getConfiguration(self::DEFAULT_NEXTCLOUD_ADMIN));
$currentConfig = $configs[0];
$logo = $this->getLogo();
$invoicePdfData = $this->gestionBdd->getInvoicePdfData($factureId,$currentConfig);
if($invoicePdfData == null){
return null;
}
$clean_folder = html_entity_decode(string: $currentConfig->path).'/';
$factureFolders = $this->getFacturesFolder($invoicePdfData,$clean_folder);
$pdf = new InvoicePdfHandler();
$pdf->AddFont('ComicSans','','Comic Sans MS.php');
$pdf->AddFont('ComicSans','B','comic-sans-bold.php');
$pdf->InvoicePdfFactory($invoicePdfData,$logo);
$pdf->SetFactureContent();
$pdfContent = $pdf->Output('','S');
$pdfFilename = $pdf->GetInvoiceFilename();
$prefixPdf = "FACTURE";
if($invoicePdfData['is_negative']){
$prefixPdf = "AVOIR";
}
$pdfFilename = $prefixPdf."_".$pdfFilename;
$filenames = [];
foreach($factureFolders as $folder){
try {
$storage->newFolder($folder);
}
catch(\OCP\Files\NotPermittedException $e) {
}
$ff_pdf = $folder.$pdfFilename.'.pdf';
$storage->newFile($ff_pdf);
$file_pdf = $storage->get($ff_pdf);
$file_pdf->putContent($pdfContent);
$filenames[] = $ff_pdf;
}
$this->gestionBdd->setFactureGeneratedDate($factureId);
return [
"content" => $pdfContent,
"filenames" => $filenames
];
}
public function generateFacturePdfByFactureId($factureId,$idNextCloud){
$factureType = $this->gestionBdd->getFactureTypeByFactureId($factureId);
if($factureType == FactureTypeConstant::TYPE_SINGLE){
return $this->generateFactureSinglePdfByFactureId($factureId,$idNextCloud);
}
else{
return $this->generateFactureGroupPdfByFactureId($factureId,$idNextCloud);
}
}
private function getGroupFactureFolder(array $factureData,$racinePath){
$clientRacineFolder = $racinePath.'CLIENTS/'.mb_strtoupper($factureData["group_name"],'UTF-8').'/';
$factureDate = $factureData['date_paiement'];
$factureDatetime = new DateTime($factureDate);
$factureDateYear = $factureDatetime->format('Y');
$factureMonth = DateHelpers::GetDateWithFormatDayAndMonthPlainString($factureData['date_paiement']);
$factureByYearFolder = $clientRacineFolder."$factureDateYear".'/'.$factureMonth.'/'.'FACTURES'.'/';
return [
$factureByYearFolder
];
}
private function getFacturesFolder(array $factureData,$racinePath){
$clientRacineFolder = $racinePath.'CLIENTS/'.mb_strtoupper($factureData["client_nom"],'UTF-8').'/';
$defuntsFolder = $clientRacineFolder.'DEFUNTS/'.mb_strtoupper($factureData['defunt_nom'],'UTF-8').'/'.'FACTURES'.'/';
$devisDate = $factureData['devis_date'];
$devisDatetime = new DateTime($devisDate);
$devisDateYear = $devisDatetime->format('Y');
$devisMonth = DateHelpers::GetDateWithFormatDayAndMonthPlainString($factureData['devis_date']);
$factureByYearFolder = $clientRacineFolder."$devisDateYear".'/'.$devisMonth.'/'.'FACTURES'.'/';
return [
$defuntsFolder,
$factureByYearFolder
];
}
private function generateFactureGroupPdfByFactureId($factureId,$idNextCloud){
$storage = $this->rootFolder->getUserFolder($idNextCloud);
$configs = json_decode($this->gestionBdd->getConfiguration(self::DEFAULT_NEXTCLOUD_ADMIN));
$currentConfig = $configs[0];
$logo = $this->getLogo();
$invoicePdfData = $this->gestionBdd->getInvoiceGroupPdfData($factureId,$currentConfig);
if($invoicePdfData == null){
return "";
}
$templateType = $invoicePdfData['template_type_key'];
$clean_folder = html_entity_decode(string: $currentConfig->path).'/';
$factureFolders = $this->getGroupFactureFolder($invoicePdfData,$clean_folder);
//For testing
// $templateType = ClientTemplateTypeConstant::OGF;
switch ($templateType) {
case ClientTemplateTypeConstant::FUNECAP:
$pdf = new InvoiceFunecapPdfHandler();
break;
case ClientTemplateTypeConstant::OGF:
$pdf = new InvoiceOgfPdfHandler();
break;
default:
$pdf = new InvoiceGroupPdfHandler();
break;
}
$pdf->AddFont('ComicSans','','Comic Sans MS.php');
$pdf->AddFont('ComicSans','B','comic-sans-bold.php');
$pdf->InvoicePdfFactory($invoicePdfData,$logo);
$pdf->SetFactureContent();
$pdfContent = $pdf->Output('','S');
$pdfFilename = $pdf->GetInvoiceFilename();
$filenames = [];
foreach($factureFolders as $folder){
try {
$storage->newFolder($folder);
}
catch(\OCP\Files\NotPermittedException $e) {
}
$ff_pdf = $folder.$pdfFilename.'.pdf';
$storage->newFile($ff_pdf);
$file_pdf = $storage->get($ff_pdf);
$file_pdf->putContent($pdfContent);
$filenames[] = $ff_pdf;
}
$this->gestionBdd->setFactureGeneratedDate($factureId);
return [
"content" => $pdfContent,
"filenames" => $filenames
];
}
public function generateFacturePdfByFactureIds(array $factureIds,$idNextCloud){
foreach( $factureIds as $factureId ){
$this->generateFacturePdfByFactureId($factureId,$idNextCloud);
}
}
public function generateMultipleInvoicePdfByClientAndMonthYear($filter,$month,$year,$idNextCloud,$filterType){
$storage = $this->rootFolder->getUserFolder($idNextCloud);
$configs = json_decode($this->gestionBdd->getConfiguration(self::DEFAULT_NEXTCLOUD_ADMIN));
$currentConfig = $configs[0];
$logo = $this->getLogo();
$invoiceData = $this->gestionBdd->getInvoicePdfDataByClientAndMonthYear($filter,$month,$year,$currentConfig,$filterType);
if(empty($invoiceData)){
return null;
}
$pdf = new InvoicePdfHandler();
$pdf->AddFont('ComicSans','','Comic Sans MS.php');
$pdf->AddFont('ComicSans','B','comic-sans-bold.php');
$pdf->MutlipleInvoicePdfFactory($invoiceData,$logo);
$pdf->SetMultipleFactureContent();
$racinePath = html_entity_decode(string: $currentConfig->path).'/';
$clientNameInFolder = $invoiceData[0]["client_nom"];
if($invoiceData[0]['facture_type'] == MultipleFactureTypeConstant::GROUP_FILTER_TYPE){
if($invoiceData[0]["group_name"] != null && $invoiceData[0]["group_name"] != ""){
$clientNameInFolder = $invoiceData[0]["group_name"];
}
}
$clientRacineFolder = $racinePath.'CLIENTS/'.mb_strtoupper($clientNameInFolder,'UTF-8').'/';
$filename = "FACTURE".'_'.$pdf->GetMultipleInvoiceFilename($month,$year);
$filenamePath = $clientRacineFolder.$filename.'.pdf';
$pdfContent = $pdf->Output('','S');
try {
$storage->newFolder($clientRacineFolder);
}
catch(\OCP\Files\NotPermittedException $e) {
}
$storage->newFile($filenamePath);
$file_pdf = $storage->get($filenamePath);
$file_pdf->putContent($pdfContent);
return $filenamePath;
}
public function generateInvoiceRecap($filter,$filterType,$date,$idNextCloud){
$this->invoiceRecapService->generateInvoiceRecap($filter,$filterType,$date,$idNextCloud);
}
public function exportGroupOfDevisIntoFacture($clientId,$clientType,$month,$year,$facturationDate,$idNextcloud = BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD){
try{
$datetime = new Datetime();
$month = $month ?? $datetime->format('m');
$year = $year ?? $datetime->format('Y');
$factureId = null;
$fkClientId = null;
$fkClientGroupFacturationId = null;
$devisMentionFiltersToBeInvoiced = [
DevisMentionConstant::NEW,
DevisMentionConstant::MENTION
];
// Recuperer les devis non facturés du client avant la date de facturation du mois
//Si il a devis qui n est pas encore facturés
//Cree un facture, atttaché l ID du facture au devis et generer le pdf
if($clientType == MultipleFactureTypeConstant::CLIENT_FILTER_TYPE){
$devisIds = $this->gestionBdd->getDevisIdsByClientIdAndDate($clientId,$facturationDate,$devisMentionFiltersToBeInvoiced);
$fkClientId = $clientId;
$factureId = $this->gestionBdd->getFactureIdByClientIdAndDate($clientId,$facturationDate);
}else{
$devisIds = $this->gestionBdd->getDevisIdsByClientGroupFacturationIdAnDate($clientId , $facturationDate , $devisMentionFiltersToBeInvoiced );
$fkClientGroupFacturationId = $clientId;
$factureId = $this->gestionBdd->getFactureIdByClientGroupFacturationIdAndDate($clientId,$facturationDate);
}
// if($clientType == MultipleFactureTypeConstant::CLIENT_FILTER_TYPE){
// $devisIds = $this->gestionBdd->getDevisIdsByClientIdAndMonthYear($clientId,$month,$year,$devisMentionFiltersToBeInvoiced);
// $fkClientId = $clientId;
// }
// else{
// $factureId = $this->gestionBdd->getFactureIdByClientGroupFacturationIdAndMonthYear($clientId,$month,$year);
// $devisIds = $this->gestionBdd->getDevisIdsByClientGroupFacturationIdAndMonthYear($clientId,$month,$year);
// $fkClientGroupFacturationId = $clientId;
// }
// $clientIsAlreadyFacturedForThisMonthAndYear = $factureId != null && $factureId != 0;
// if($clientIsAlreadyFacturedForThisMonthAndYear == false){
// $factureId = $this->gestionBdd->createFactureAndReturnFactureId(
// $facturationDate,
// FactureTypeConstant::TYPE_GROUP,
// $month,
// $year,
// $fkClientId,
// $fkClientGroupFacturationId);
// }
if (!empty($devisIds)) {
//Get facture by date and client
$clientIsAlreadyFacturedForThisDate = $factureId != null && $factureId != 0;
if (!$clientIsAlreadyFacturedForThisDate) {
$factureId = $this->gestionBdd->createFactureAndReturnFactureId(
$facturationDate,
FactureTypeConstant::TYPE_GROUP,
$month,
$year,
$fkClientId,
$fkClientGroupFacturationId
);
}
$this->gestionBdd->invoiceListOfDevisIds($devisIds , $factureId);
$factureGeneratedResponse = $this->generateFactureGroupPdfByFactureId($factureId,$idNextcloud);
return $factureGeneratedResponse["filenames"];
}
return null;
}
catch(Exception){
return null;
}
}
}