Compare commits

...

8 Commits

Author SHA1 Message Date
d2bb1a9cc6 fix recap pdf 2025-12-16 09:07:49 +03:00
8cacac1efc fix recap devis multi product 2025-12-15 11:58:11 +03:00
a28b7f6ea6 fix erreur stats thanato 2025-11-20 09:45:34 +03:00
03784fd8e6 fix stats devis thanato 2025-11-19 12:01:51 +03:00
411cc2d5a8 fix statistique client calcul total HT 2025-11-17 17:27:40 +03:00
34717b772d fix statistique pas de filtre mentions 2025-11-17 13:23:47 +03:00
b6ea2550bc fix statistique not status 2025-11-17 13:10:37 +03:00
65d13d70f9 fix statistiques 2025-11-17 12:41:49 +03:00
8 changed files with 678 additions and 427 deletions

View File

@ -2615,7 +2615,7 @@ class Bdd
return $data; return $data;
} }
private function getThanatoDevisListByDate($thanatoId, $date) private function getThanatoDevisListByDateSave($thanatoId, $date)
{ {
$dateFormatted = $date->format('Y-m-d'); $dateFormatted = $date->format('Y-m-d');
$sql = "SELECT $sql = "SELECT
@ -2656,6 +2656,42 @@ class Bdd
return $devisList; return $devisList;
} }
private function getThanatoDevisListByDate($thanatoId, $date)
{
$dateFormatted = $date->format('Y-m-d');
$sql = "SELECT
devis.id,
devis.date,
devis.mentions,
devis.num as calendar_uuid,
devis.id_defunt as id_defunt,
devis.id_lieu as id_lieu,
devis.id_client as id_client,
devis.id_thanato as id_thanato,
thanato.nom as nom_thanato,
thanato.prenom as prenom_thanato,
defunt.nom as nom_defunt,
lieu.nom as nom_lieu,
lieu.latitude as lieu_latitude,
lieu.longitude as lieu_longitude,
client.nom as nom_client,
client.entreprise as client_entreprise,
client.adresse as client_adresse
FROM ".$this->tableprefix."devis as devis
LEFT JOIN ".$this->tableprefix."thanato as thanato on devis.id_thanato = thanato.id
LEFT JOIN ".$this->tableprefix."lieu as lieu on devis.id_lieu = lieu.id
LEFT JOIN ".$this->tableprefix."defunt as defunt on devis.id_defunt = defunt.id
LEFT JOIN ".$this->tableprefix."client as client on devis.id_client = client.id
WHERE devis.date = ? AND
devis.id_thanato = ?
ORDER BY devis.date ASC;";
$devisList = $this->execSQLNoJsonReturn(
$sql,
[$dateFormatted,$thanatoId]
);
return $devisList;
}
public function getThanatoById($thanatoId) public function getThanatoById($thanatoId)
{ {
$sql = "SELECT id, nom, prenom,fk_user_uuid FROM ".$this->tableprefix."thanato WHERE id = ? LIMIT 1;"; $sql = "SELECT id, nom, prenom,fk_user_uuid FROM ".$this->tableprefix."thanato WHERE id = ? LIMIT 1;";
@ -3153,7 +3189,7 @@ class Bdd
return 0; return 0;
} }
private function getClientFactureStatisticPerMonth($clientId, array $produitList) private function getClientFactureStatisticPerMonthSave($clientId, array $produitList)
{ {
$currentYear = date('Y'); $currentYear = date('Y');
$monthLists = range(1, 12); $monthLists = range(1, 12);
@ -3174,12 +3210,11 @@ class Bdd
LEFT JOIN ".$this->tableprefix."devis as devis on facture.id_devis = devis.id LEFT JOIN ".$this->tableprefix."devis as devis on facture.id_devis = devis.id
WHERE YEAR(facture.date_paiement) = ? AND WHERE YEAR(facture.date_paiement) = ? AND
MONTH(facture.date_paiement) = ? AND MONTH(facture.date_paiement) = ? AND
devis.id_client = ? AND devis.id_client = ?
(devis.mentions = ? OR devis.mentions = ?)
ORDER BY facture.date_paiement ASC;"; ORDER BY facture.date_paiement ASC;";
$factureList = $this->execSQLNoJsonReturn( $factureList = $this->execSQLNoJsonReturn(
$sql, $sql,
[$currentYear,$monthValue,$clientId,DevisMentionConstant::FACTURED,DevisMentionConstant::FACTURED_FORMATTED] [$currentYear,$monthValue,$clientId]
); );
$factureDevisIds = []; $factureDevisIds = [];
@ -3209,6 +3244,58 @@ class Bdd
return $data; return $data;
} }
private function getClientFactureStatisticPerMonth($clientId, array $produitList, $clientGroupId = null)
{
$currentYear = date('Y');
$monthLists = range(1, 12);
$data = [] ;
foreach($monthLists as $monthValue) {
if(!isset($data[$monthValue])) {
$data[$monthValue] = [];
}
$sql = "SELECT
devis.id as devis_id,
devis.id_client as devis_client_id,
devis.date as devis_date,
devis.mentions as devis_mention
FROM ".$this->tableprefix."devis as devis
WHERE YEAR(devis.date) = ? AND
MONTH(devis.date) = ? AND
devis.id_client = ?
ORDER BY devis.date ASC;";
$factureList = $this->execSQLNoJsonReturn(
$sql,
[$currentYear,$monthValue,$clientId]
);
$factureDevisIds = [];
foreach($factureList as $facture) {
$factureDevisIds[] = $facture['devis_id'];
}
$defuntCount = count($factureList);
$produitsPrice = 0;
$statisticForeachProductPerMonth = [];
foreach($produitList as $produit) {
if(!isset($statisticForeachProductPerMonth[$produit['id']])) {
$statisticForeachProductPerMonth[$produit['id']] = 0;
}
$productTotalCount = $this->getDevisProductsQuantityByDevisListAndProductId($factureDevisIds, $produit['id']);
$prixUnitaire = is_null($clientGroupId) ? $produit["prix_unitaire"] : $this->getProductPriceByClientGroupId($clientGroupId, $produit['id']);
$totalWithoutVat = $productTotalCount * $prixUnitaire;
$statisticForeachProductPerMonth[$produit['id']] += $productTotalCount;
$produitsPrice += $totalWithoutVat;
}
$data[$monthValue] = [
"defunt_count" => $defuntCount,
"total_price" => $produitsPrice,
"year" => $currentYear,
"products" => $statisticForeachProductPerMonth
];
}
return $data;
}
public function getExportClientStatData(array $clientIds) public function getExportClientStatData(array $clientIds)
{ {
$data = []; $data = [];
@ -3222,9 +3309,10 @@ class Bdd
$client = $this->getClientById($clientId); $client = $this->getClientById($clientId);
if($client != null) { if($client != null) {
$clientName = trim($client["client_nom"]) . '-' .trim($client['client_entreprise']); $clientName = trim($client["client_nom"]) . '-' .trim($client['client_entreprise']);
$clientGroupId = $client['fk_client_group_id'];
} }
$data[$clientId]["client_name"] = $clientName; $data[$clientId]["client_name"] = $clientName;
$data[$clientId]["client_data"] = $this->getClientFactureStatisticPerMonth($clientId, $produitList); $data[$clientId]["client_data"] = $this->getClientFactureStatisticPerMonth($clientId, $produitList, $clientGroupId);
} }
return $data; return $data;
} }

View File

@ -85,9 +85,9 @@ class DevisDataProcessor
} }
// Traitement identique aux factures // Traitement identique aux factures
$produitsReferenceArray = array_unique($produitsReferenceArray); // $produitsReferenceArray = array_unique($produitsReferenceArray);
$produitsReferenceAsString = implode("-", $produitsReferenceArray); $produitsReferenceAsString = implode("-", $produitsReferenceArray);
$devis_temp['article'] = !empty($produitsReferenceAsString) ? $produitsReferenceAsString : 'SOINS'; $devis_temp['article'] = !empty($produitsReferenceAsString) ? $produitsReferenceAsString : '';
$devis_temp['montant_tva'] = ($devis_temp['montant_htc'] * $devis_temp['tva']) / 100; $devis_temp['montant_tva'] = ($devis_temp['montant_htc'] * $devis_temp['tva']) / 100;
$devis_temp['montant_ttc'] = $devis_temp['montant_tva'] + $devis_temp['montant_htc']; $devis_temp['montant_ttc'] = $devis_temp['montant_tva'] + $devis_temp['montant_htc'];

View File

@ -81,16 +81,31 @@ class DevisPdfGenerator
private function calculatePagination($totalItems) private function calculatePagination($totalItems)
{ {
if ($totalItems <= 8) {
// Tout sur 1 page
return [
'nb_pages' => 1,
'items_per_page' => 15,
'current_index' => 0
];
}
// Réserver 8 items pour dernière page
$itemsAvantDernierePage = $totalItems - 8;
$nbPagesNormales = ceil($itemsAvantDernierePage / 15);
return [ return [
'nb_pages' => ceil($totalItems / 12), // RÉDUIRE à 12 par page 'nb_pages' => $nbPagesNormales + 1,
'items_per_page' => 12, 'items_per_page' => 15,
'current_index' => 0 'current_index' => 0
]; ];
} }
// VOICI LA FONCTION CORRIGÉE - 4 paramètres au lieu de 10
private function generateSinglePage(PageContext $context, $num_page, &$pagination, &$totals) private function generateSinglePage(PageContext $context, $num_page, &$pagination, &$totals)
{ {
$startIndex = $pagination['current_index'];
$remainingItems = count($context->dataDevis) - $startIndex;
$context->pdf->AddPage(); $context->pdf->AddPage();
$context->pdf->SetAutoPagebreak(false); $context->pdf->SetAutoPagebreak(false);
$context->pdf->SetMargins(0, 0, 10); $context->pdf->SetMargins(0, 0, 10);
@ -100,7 +115,17 @@ class DevisPdfGenerator
$this->layoutManager->addClientInfoSection($context->pdf, $context->clientInfo, $context->dataDevis[0]); $this->layoutManager->addClientInfoSection($context->pdf, $context->clientInfo, $context->dataDevis[0]);
$this->layoutManager->addDocumentTitle($context->pdf, $context->dataDevis[0], $context->year); $this->layoutManager->addDocumentTitle($context->pdf, $context->dataDevis[0], $context->year);
$itemsToProcess = min($pagination['items_per_page'], count($context->dataDevis) - $pagination['current_index']); // ✅ Calculer items
$isLastPage = ($num_page == $pagination['nb_pages']);
$hasAmounts = !$context->montant;
if ($isLastPage && $hasAmounts) {
// Dernière page avec totaux : max 8 items
$itemsToProcess = min(8, $remainingItems);
} else {
// Pages normales : 15 items
$itemsToProcess = min(15, $remainingItems);
}
$config = [ $config = [
'pagination' => $pagination, 'pagination' => $pagination,
@ -111,7 +136,7 @@ class DevisPdfGenerator
'sansMontant' => $context->montant 'sansMontant' => $context->montant
]; ];
$this->tableRenderer->createDevisTable( $finalY = $this->tableRenderer->createDevisTable(
$context->pdf, $context->pdf,
$context->dataDevis, $context->dataDevis,
$config $config

View File

@ -63,17 +63,18 @@ class DevisPdfLayoutManager
); );
} }
public function addLegalFooter($pdf, $config) public function addLegalFooter($pdf, $config, $tableEndY = 0)
{ {
$y0 = 260; $y0 = 280;
$pageWidth = $pdf->GetPageWidth(); $pageWidth = $pdf->GetPageWidth();
$pdf->SetFont('Arial', '', 6); $pdf->SetFont('Arial', '', 6);
$pdf->SetXY(1, $y0 + 4); $pdf->SetXY(1, $y0);
$pdf->Cell($pageWidth, 5, mb_convert_encoding(html_entity_decode($config->legal_one), 'ISO-8859-1', 'UTF-8'), 0, 0, 'C'); $pdf->Cell($pageWidth, 5, mb_convert_encoding(html_entity_decode($config->legal_one), 'ISO-8859-1', 'UTF-8'), 0, 0, 'C');
$pdf->SetXY(1, $y0 + 8); $pdf->SetXY(1, $y0 + 4);
$pdf->Cell($pageWidth, 5, mb_convert_encoding(html_entity_decode($config->legal_two), 'ISO-8859-1', 'UTF-8'), 0, 0, 'C'); $pdf->Cell($pageWidth, 5, mb_convert_encoding(html_entity_decode($config->legal_two), 'ISO-8859-1', 'UTF-8'), 0, 0, 'C');
$pdf->SetXY(1, $y0 + 12); $pdf->SetXY(1, $y0 + 8);
$pdf->Cell($pageWidth, 5, mb_convert_encoding(html_entity_decode($config->telephone), 'ISO-8859-1', 'UTF-8'), 0, 0, 'C'); $pdf->Cell($pageWidth, 5, mb_convert_encoding(html_entity_decode($config->telephone), 'ISO-8859-1', 'UTF-8'), 0, 0, 'C');
} }

View File

@ -13,40 +13,59 @@ class DevisPdfTableRenderer
$totals = &$config['totals']; $totals = &$config['totals'];
$sansMontant = $config['sansMontant'] ?? false; $sansMontant = $config['sansMontant'] ?? false;
// Système de pagination comme les factures
$maxItemsPerPage = 22; // Nombre maximum d'éléments par page
$startIndex = $pagination['current_index']; $startIndex = $pagination['current_index'];
$itemsThisPage = min($itemsToProcess, count($dataDevis) - $startIndex); $itemsThisPage = min($itemsToProcess, count($dataDevis) - $startIndex);
$this->drawTableStructure($pdf, $numPage, $nbPage, $sansMontant); $tableEndY = $this->drawTableStructure($pdf, $numPage, $nbPage, $sansMontant, $itemsThisPage);
$this->addTableHeaders($pdf, $sansMontant); $this->addTableHeaders($pdf, $sansMontant);
$this->populateTableData($pdf, $dataDevis, $startIndex, $itemsThisPage, $totals, $sansMontant); $this->populateTableData($pdf, $dataDevis, $startIndex, $itemsThisPage, $totals, $sansMontant);
// Totaux seulement sur la dernière page
if ($numPage == $nbPage && !$sansMontant) { if ($numPage == $nbPage && !$sansMontant) {
$this->addTableTotals($pdf, $totals); $finalY = $this->addTableTotals($pdf, $totals, $tableEndY);
} else {
$finalY = $tableEndY;
} }
return $finalY;
} }
private function drawTableStructure($pdf, $numPage, $nbPage, $sansMontant) private function drawTableStructure($pdf, $numPage, $nbPage, $sansMontant, $itemsOnPage)
{ {
$pdf->SetLineWidth(0.2); $pdf->SetLineWidth(0.2);
$pdf->Rect(5, 105, 200, 130, "D");
$headerHeight = 10;
$rowHeight = 10;
$tableHeight = $headerHeight + ($itemsOnPage * $rowHeight);
$endY = 105 + $tableHeight;
$isLastPage = ($numPage == $nbPage);
$hasAmounts = !$sansMontant;
if ($isLastPage && $hasAmounts) {
// Dessiner 3 côtés seulement (haut, gauche, droite)
$pdf->Line(5, 105, 205, 105); // Haut
$pdf->Line(5, 105, 5, $endY); // Gauche
$pdf->Line(205, 105, 205, $endY); // Droite
// Pas de ligne du bas - elle sera tracée dans addTableTotals
} else {
// Dessiner rectangle complet
$pdf->Rect(5, 105, 200, $tableHeight, "D");
}
$pdf->Line(5, 115, 205, 115); $pdf->Line(5, 115, 205, 115);
$endY = ($numPage == $nbPage && !$sansMontant) ? 225 : 235;
if (!$sansMontant) { if (!$sansMontant) {
// Ajout de la colonne Thanatopracteur entre Défunt et H.T.
$verticalLines = [24, 41, 58, 77, 102, 127, 147, 167, 178, 189]; $verticalLines = [24, 41, 58, 77, 102, 127, 147, 167, 178, 189];
} else { } else {
// Pour sans montant: ajout de Thanatopracteur à la fin
$verticalLines = [27, 47, 67, 85, 110, 135, 160]; $verticalLines = [27, 47, 67, 85, 110, 135, 160];
} }
foreach ($verticalLines as $x) { foreach ($verticalLines as $x) {
$pdf->Line($x, 105, $x, $endY); $pdf->Line($x, 105, $x, $endY);
} }
return $endY;
} }
private function addTableHeaders($pdf, $sansMontant) private function addTableHeaders($pdf, $sansMontant)
@ -176,43 +195,44 @@ class DevisPdfTableRenderer
} }
} }
private function addTableTotals($pdf, $totals) private function addTableTotals($pdf, $totals, $tableEndY)
{ {
$pdf->Line(5, 225, 205, 225); $totalEndY = $tableEndY + 8;
$pdf->SetLineWidth(0.2);
// Juste les lignes horizontales haut et bas
$pdf->Line(5, $tableEndY, 205, $tableEndY);
$pdf->Line(5, $totalEndY, 205, $totalEndY);
$pdf->Line(5, $tableEndY, 5, $totalEndY);
$pdf->Line(205, $tableEndY, 205, $totalEndY);
$pdf->SetFont('Arial', 'B', 8); $pdf->SetFont('Arial', 'B', 8);
// Alignement des totaux avec les colonnes HT, TVA, TTC avec espaces entre les valeurs $pdf->SetXY(5, $tableEndY);
$pdf->SetXY(5, 225);
$pdf->Cell(162, 8, 'TOTAL', 0, 0, 'C'); $pdf->Cell(162, 8, 'TOTAL', 0, 0, 'C');
// POSITIONS avec espaces entre les valeurs - plus d'espace entre HT et TVA $pdf->SetXY(167, $tableEndY);
$pdf->SetXY(167, 225);
$pdf->Cell(9, 8, number_format($totals['ht'], 2, '.', '') . chr(128), 0, 0, 'R'); $pdf->Cell(9, 8, number_format($totals['ht'], 2, '.', '') . chr(128), 0, 0, 'R');
$pdf->SetXY(181, 225); $pdf->SetXY(181, $tableEndY);
$pdf->Cell(9, 8, number_format($totals['tva'], 2, '.', '') . chr(128), 0, 0, 'R'); $pdf->Cell(9, 8, number_format($totals['tva'], 2, '.', '') . chr(128), 0, 0, 'R');
$pdf->SetXY(189, 225); $pdf->SetXY(189, $tableEndY);
$pdf->Cell(16, 8, number_format($totals['ttc'], 2, '.', '') . chr(128), 0, 0, 'R'); $pdf->Cell(16, 8, number_format($totals['ttc'], 2, '.', '') . chr(128), 0, 0, 'R');
// CADRE TOTAL TTC - Cadre encore plus agrandi $cadreY = $totalEndY + 3;
$pdf->SetXY(170, 241);
$pdf->SetXY(170, $cadreY + 1);
$pdf->Cell(19, 6, 'TOTAL TTC', 0, 0, 'C'); $pdf->Cell(19, 6, 'TOTAL TTC', 0, 0, 'C');
$pdf->SetXY(189, 241); $pdf->SetXY(189, $cadreY + 1);
$pdf->Cell(16, 6, number_format($totals['ttc'], 2, '.', '') . chr(128), 0, 0, 'C'); $pdf->Cell(16, 6, number_format($totals['ttc'], 2, '.', '') . chr(128), 0, 0, 'C');
// Cadre TOTAL TTC aligné avec la fin du tableau (205) $pdf->Rect(170, $cadreY, 35, 8, 'D');
$lines = [ $pdf->Line(189, $cadreY, 189, $cadreY + 8);
[170, 240, 170, 248], // Ligne verticale gauche (déplacée de 173 à 170 pour agrandir)
[189, 240, 189, 248], // Ligne de séparation (alignée avec colonne T.T.C)
[205, 240, 205, 248], // Ligne verticale droite (alignée avec fin du tableau)
[170, 240, 205, 240], // Ligne horizontale haute
[170, 248, 205, 248] // Ligne horizontale basse
];
foreach ($lines as $line) { return $cadreY + 8;
$pdf->Line($line[0], $line[1], $line[2], $line[3]);
}
} }
} }

View File

@ -30,94 +30,102 @@ use OCA\Gestion\Db\Bdd;
use OCA\Gestion\Helpers\FileExportHelpers; use OCA\Gestion\Helpers\FileExportHelpers;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
class ExportClientStatisticService { class ExportClientStatisticService
/** @var Bdd */ {
private $gestionBdd; /** @var Bdd */
private $gestionBdd;
/** @var LoggerInterface */ /** @var LoggerInterface */
private $logger; private $logger;
public function __construct( public function __construct(
Bdd $gestionBdd, Bdd $gestionBdd,
LoggerInterface $logger) { LoggerInterface $logger
$this->logger = $logger; ) {
$this->gestionBdd = $gestionBdd; $this->logger = $logger;
} $this->gestionBdd = $gestionBdd;
}
public function getFileName(array $clientIds){ public function getFileName(array $clientIds)
{
$filename = ""; $filename = "";
$clients = $this->gestionBdd->getClientsByClientsID($clientIds); $clients = $this->gestionBdd->getClientsByClientsID($clientIds);
foreach($clients as $client){ foreach($clients as $client) {
$filename .= $client['client_nom'] . '-' . $client['client_entreprise'] . '--'; $filename .= $client['client_nom'] . '-' . $client['client_entreprise'] . '--';
} }
$filename = rtrim($filename, '-'); $filename = rtrim($filename, '-');
$filename = str_replace(' ','-', $filename); $filename = str_replace(' ', '-', $filename);
$filename = str_replace('&nbsp;','-', $filename); $filename = str_replace('&nbsp;', '-', $filename);
return $filename; return $filename;
} }
public function getExportClientFileHeader(): string{ public function getExportClientFileHeader(): string
$fileHeader = {
'CLIENT'.';'. $fileHeader =
'CLIENT'.';'.
'MOIS'.';'. 'MOIS'.';'.
'ANNEE'.';'. 'ANNEE'.';'.
'NB DE DEFUNTS'.';'; 'NB DE DEFUNTS'.';';
$produitList = $this->gestionBdd->getProduitsListAsArray(); $produitList = $this->gestionBdd->getProduitsListAsArray();
foreach($produitList as $produit){ foreach($produitList as $produit) {
$fileHeader .= FileExportHelpers::FormatTextForExport($produit['reference']).';'; $fileHeader .= FileExportHelpers::FormatTextForExport($produit['reference']).';';
} }
$fileHeader .= 'TOTAL HT'.';'."\n"; $fileHeader .= 'TOTAL HT'.';'."\n";
return $fileHeader; return $fileHeader;
} }
public function populateExportDataIntoFileContent(array $exportData,string $fileContent): string{ public function populateExportDataIntoFileContent(array $exportData, string $fileContent): string
foreach($exportData as $clientId => $clientData){ {
$clientName = $clientData["client_name"]; foreach($exportData as $clientId => $clientData) {
$clientStatPerMonth = $clientData["client_data"]; $clientName = $clientData["client_name"];
$totalPrice = 0; $clientStatPerMonth = $clientData["client_data"];
if(!empty($clientStatPerMonth)){ $totalPrice = 0;
foreach($clientStatPerMonth as $month => $stat){ if(!empty($clientStatPerMonth)) {
$stat["client_name"] = $clientName; foreach($clientStatPerMonth as $month => $stat) {
$totalPrice+=$stat["total_price"]; $stat["client_name"] = $clientName;
$fileContent = $this->populateClientStatDataIntoFileContent($fileContent,$month,$stat); $totalPrice += $stat["total_price"];
} $fileContent = $this->populateClientStatDataIntoFileContent($fileContent, $month, $stat);
$fileContent = $this->populateTotalPriceIntoFileContent($fileContent,$totalPrice,count($stat["products"])); }
} $fileContent = $this->populateTotalPriceIntoFileContent($fileContent, $totalPrice, count($stat["products"]));
} }
return $fileContent; }
} return $fileContent;
}
private function populateTotalPriceIntoFileContent(string $fileContent,$totalPrice,$productsCount){ private function populateTotalPriceIntoFileContent(string $fileContent, $totalPrice, $productsCount)
$fileContent = $fileContent. {
''.';'. $fileContent = $fileContent.
''.';'. ''.';'.
''.';'. ''.';'.
''.';'; ''.';'.
while($productsCount > 0){ ''.';';
$fileContent .= ''.';'; while($productsCount > 0) {
$productsCount--; $fileContent .= ''.';';
} $productsCount--;
$fileContent .= "$totalPrice".";"."\n"; }
return $fileContent; $fileContent .= "$totalPrice".";"."\n";
} return $fileContent;
}
private function populateClientStatDataIntoFileContent(string $fileContent,$month,array $statPerMonth){ private function populateClientStatDataIntoFileContent(string $fileContent, $month, array $statPerMonth)
$yearValue = $statPerMonth["year"]; {
$defuntCount = $statPerMonth["defunt_count"]; $yearValue = $statPerMonth["year"];
$products = $statPerMonth["products"]; $defuntCount = $statPerMonth["defunt_count"];
$products = $statPerMonth["products"];
$fileContent = $fileContent. $priceTotal = $statPerMonth["total_price"];
FileExportHelpers::FormatTextForExport($statPerMonth['client_name']).';'.
"$month".';'.
"$yearValue".';'.
"$defuntCount".';';
foreach($products as $productCount){ $fileContent = $fileContent.
$fileContent .= "$productCount".";"; FileExportHelpers::FormatTextForExport($statPerMonth['client_name']).';'.
} "$month".';'.
$fileContent .= "\n"; "$yearValue".';'.
return $fileContent; "$defuntCount".';';
} foreach($products as $productCount) {
$fileContent .= "$productCount".";";
}
$fileContent .= "$priceTotal".';'."\n";
return $fileContent;
}
} }

View File

@ -34,149 +34,158 @@ use OCA\Gestion\Constants\BddConstant;
use OCA\Gestion\Helpers\FileExportHelpers; use OCA\Gestion\Helpers\FileExportHelpers;
use OCA\Gestion\Constants\AbsenceTypeConstant; use OCA\Gestion\Constants\AbsenceTypeConstant;
class ExportThanatoStatisticService { class ExportThanatoStatisticService
/** @var Bdd */ {
private $gestionBdd; /** @var Bdd */
private $gestionBdd;
/** @var LoggerInterface */ /** @var LoggerInterface */
private $logger; private $logger;
/** @var IRootFolder */ /** @var IRootFolder */
private $rootFolder; private $rootFolder;
private $geoService; private $geoService;
public function __construct( public function __construct(
Bdd $gestionBdd, Bdd $gestionBdd,
LoggerInterface $logger, LoggerInterface $logger,
IRootFolder $rootFolder, IRootFolder $rootFolder,
GeoService $geoService) { GeoService $geoService
$this->geoService = $geoService; ) {
$this->rootFolder = $rootFolder; $this->geoService = $geoService;
$this->logger = $logger; $this->rootFolder = $rootFolder;
$this->gestionBdd = $gestionBdd; $this->logger = $logger;
} $this->gestionBdd = $gestionBdd;
}
private function getFilename($thanatoName,$thanatoLastName,$month,$year){ private function getFilename($thanatoName, $thanatoLastName, $month, $year)
$filename = "$year-$month-"; {
$filename .= $thanatoName . '-' . $thanatoLastName; $filename = "$year-$month-";
$filename = str_replace(' ','-', $filename); $filename .= $thanatoName . '-' . $thanatoLastName;
$filename = str_replace('&nbsp;','-', $filename); $filename = str_replace(' ', '-', $filename);
$filename = str_replace('&nbsp;', '-', $filename);
return $filename; return $filename;
} }
private function exportThanatoStatistic($thanatoId,$month,$year,$idNextcloud){ private function exportThanatoStatistic($thanatoId, $month, $year, $idNextcloud)
$thanato = $this->gestionBdd->getThanatoById($thanatoId); {
if($thanato == null){ $thanato = $this->gestionBdd->getThanatoById($thanatoId);
return null; if($thanato == null) {
} return null;
$exportData = $this->gestionBdd->getExportThanatoStatisticData($thanatoId,$month,$year); }
if(empty($exportData)){ $exportData = $this->gestionBdd->getExportThanatoStatisticData($thanatoId, $month, $year);
return null; if(empty($exportData)) {
} return null;
$defaultConfig = json_decode($this->gestionBdd->getConfiguration(BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD)); }
$racineFolder = html_entity_decode($defaultConfig[0]->path).'/'; $defaultConfig = json_decode($this->gestionBdd->getConfiguration(BddConstant::DEFAULT_ADMIN_ID_NEXTCLOUD));
$thanatoFolder = $racineFolder.'STATISTIQUES/THANATOS/'; $racineFolder = html_entity_decode($defaultConfig[0]->path).'/';
$fileHeader = $this->getExportThanatoFileHeader(); $thanatoFolder = $racineFolder.'STATISTIQUES/THANATOS/';
$fileContent = $this->populateExportDataIntoFileContent($exportData,$fileHeader); $fileHeader = $this->getExportThanatoFileHeader();
$storage = $this->rootFolder->getUserFolder($idNextcloud); $fileContent = $this->populateExportDataIntoFileContent($exportData, $fileHeader);
try{ $storage = $this->rootFolder->getUserFolder($idNextcloud);
$storage->newFolder($thanatoFolder); try {
} $storage->newFolder($thanatoFolder);
catch(\OCP\Files\NotPermittedException $e) { } catch(\OCP\Files\NotPermittedException $e) {
}
$filename = $this->getFilename($thanato["nom"],$thanato["prenom"],$month,$year);
$fileNamePath = $thanatoFolder."STAT-THANATO-" . $filename . '.csv';
$storage->newFile($fileNamePath);
$file = $storage->get($fileNamePath);
$file->putContent($fileContent);
return $fileNamePath;
}
public function exportThanatosListStatistic(array $thanatoIds,$month,$year,$idNextcloud){ }
$filenames = []; $filename = $this->getFilename($thanato["nom"], $thanato["prenom"], $month, $year);
foreach($thanatoIds as $thanatoId){ $fileNamePath = $thanatoFolder."STAT-THANATO-" . $filename . '.csv';
$filename = $this->exportThanatoStatistic($thanatoId,$month,$year,$idNextcloud); $storage->newFile($fileNamePath);
if($filename != null){ $file = $storage->get($fileNamePath);
$filenames[] = $filename; $file->putContent($fileContent);
} return $fileNamePath;
} }
return $filenames;
}
public function getExportThanatoFileHeader(): string{ public function exportThanatosListStatistic(array $thanatoIds, $month, $year, $idNextcloud)
$fileHeader = {
'FACTURE'.';'. $filenames = [];
'THANATOPRACTEUR'.';'. foreach($thanatoIds as $thanatoId) {
'DATE'.';'. $filename = $this->exportThanatoStatistic($thanatoId, $month, $year, $idNextcloud);
'HEURE DE DEBUT'.';'. if($filename != null) {
'HEURE DE FIN'.';'. $filenames[] = $filename;
'SOINS'.';'. }
'JOUR/FERIE'.';'. }
'CONGE'.';'. return $filenames;
'REPOS'.';'. }
'MALADIE'.';'.
'NOM ET PRENOM'.';'.
'LIEU'.';'.
'POMPES FUNEBRES'.';'.
'ADRESSE'.';'.
'DISTANCE TOTALE KM'.';'.
'HEURES TOTAL DE SOIN'.';'.
'HEURES TOTAL DE CONGE'.';'.
'HEURES TOTAL DE REPOS'.';'.
'HEURES TOTAL DE MALADIE'.';'.
'HEURES TOTAL DE TRAVAIL'.';'.
'HEURES TOTAL DE PARCOURS ENTRE DEVIS'.';'.
'NOMBRE DE SOINS ET TOILETTES'.';'.
"\n";
return $fileHeader;
}
private function populateNoDevisDataInADay(string $fileContent,$leave){ public function getExportThanatoFileHeader(): string
$startTimeValue = ""; {
$endTimeValue = ""; $fileHeader =
$leaveValue = "Non"; 'DEVIS'.';'.
if($leave["onLeave"]){ 'THANATOPRACTEUR'.';'.
$startTimeValue = $leave["startTime"]; 'DATE'.';'.
$endTimeValue = $leave["endTime"]; 'HEURE DE DEBUT'.';'.
if($leave["absenceTypeKey"] == AbsenceTypeConstant::LEAVE){ 'HEURE DE FIN'.';'.
$leaveValue = "Oui"; 'SOINS'.';'.
} 'JOUR/FERIE'.';'.
if($leave["absenceTypeKey"] == AbsenceTypeConstant::DISEASE){ 'CONGE'.';'.
$diseaseValue = "Oui"; 'REPOS'.';'.
} 'MALADIE'.';'.
if($leave["absenceTypeKey"] == AbsenceTypeConstant::REST){ 'NOM ET PRENOM'.';'.
$restValue = "Oui"; 'LIEU'.';'.
} 'POMPES FUNEBRES'.';'.
} 'ADRESSE'.';'.
$fileContent = $fileContent. 'DISTANCE TOTALE KM'.';'.
''.';'. 'HEURES TOTAL DE SOIN'.';'.
FileExportHelpers::FormatTextForExport($leave['thanatoName']).';'. 'HEURES TOTAL DE CONGE'.';'.
$leave['date'].';'. 'HEURES TOTAL DE REPOS'.';'.
$startTimeValue.';'. 'HEURES TOTAL DE MALADIE'.';'.
$endTimeValue.';'. 'HEURES TOTAL DE TRAVAIL'.';'.
''.';'. 'HEURES TOTAL DE PARCOURS ENTRE DEVIS'.';'.
DateHelpers::getPublicHolidayText($leave['isPublicHoliday']).';'. 'NOMBRE DE SOINS ET TOILETTES'.';'.
$leaveValue.';'. "\n";
$restValue.';'. return $fileHeader;
$diseaseValue.';'. }
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'."\n";
return $fileContent;
}
public function populateExportDataIntoFileContent(array $exportData,string $fileContent): string{ private function populateNoDevisDataInADay(string $fileContent, $leave)
{
$startTimeValue = "";
$endTimeValue = "";
$leaveValue = "Non";
$restValue = "Non"; // AJOUTER CETTE LIGNE
$diseaseValue = "Non"; // AJOUTER CETTE LIGNE
if($leave["onLeave"]) {
$startTimeValue = $leave["startTime"];
$endTimeValue = $leave["endTime"];
if($leave["absenceTypeKey"] == AbsenceTypeConstant::LEAVE) {
$leaveValue = "Oui";
}
if($leave["absenceTypeKey"] == AbsenceTypeConstant::DISEASE) {
$diseaseValue = "Oui";
}
if($leave["absenceTypeKey"] == AbsenceTypeConstant::REST) {
$restValue = "Oui";
}
}
$fileContent = $fileContent.
''.';'.
FileExportHelpers::FormatTextForExport($leave['thanatoName']).';'.
$leave['date'].';'.
$startTimeValue.';'.
$endTimeValue.';'.
''.';'.
DateHelpers::getPublicHolidayText($leave['isPublicHoliday']).';'.
$leaveValue.';'.
$restValue.';'.
$diseaseValue.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'."\n";
return $fileContent;
}
public function populateExportDataIntoFileContent(array $exportData, string $fileContent): string
{
$g_totalDistance = 0; $g_totalDistance = 0;
$g_totalDevisHours = 0; $g_totalDevisHours = 0;
@ -185,81 +194,81 @@ class ExportThanatoStatisticService {
$g_totalTravelingHoursBetweenDevisLocation = 0; $g_totalTravelingHoursBetweenDevisLocation = 0;
$g_totalDiseaseHours = 0; $g_totalDiseaseHours = 0;
$g_totalRestHours = 0; $g_totalRestHours = 0;
$g_totalDevisCount = 0; $g_totalDevisCount = 0;
foreach($exportData as $devisDate => $devisData){ foreach($exportData as $devisDate => $devisData) {
$totalDevisHours = 0; $totalDevisHours = 0;
$totalWorkedHours = 8; $totalWorkedHours = 8;
$totalLeaveHours = 0; $totalLeaveHours = 0;
$totalDiseaseHours = 0; $totalDiseaseHours = 0;
$totalRestHours = 0; $totalRestHours = 0;
$totalDistance = 0; $totalDistance = 0;
$totalDevisCount = 0; $totalDevisCount = 0;
$totalTravelingHoursBetweenDevisLocation = 0; $totalTravelingHoursBetweenDevisLocation = 0;
$hasDevisInTheCurrentDate = $devisData['hasDevis']; $hasDevisInTheCurrentDate = $devisData['hasDevis'];
if($hasDevisInTheCurrentDate === false){ if($hasDevisInTheCurrentDate === false) {
$leaves = $devisData["leaves"]; $leaves = $devisData["leaves"];
foreach($leaves as $leave){ foreach($leaves as $leave) {
$fileContent = $this->populateNoDevisDataInADay($fileContent,$leave); $fileContent = $this->populateNoDevisDataInADay($fileContent, $leave);
if($leave["onLeave"]){ if($leave["onLeave"]) {
$totalLeaveHoursInsideWorkingHours = $leave["totalWorkedHours"]; $totalLeaveHoursInsideWorkingHours = $leave["totalWorkedHours"];
if($leave["absenceTypeKey"] == AbsenceTypeConstant::LEAVE ){ if($leave["absenceTypeKey"] == AbsenceTypeConstant::LEAVE) {
$totalLeaveHours += $totalLeaveHoursInsideWorkingHours; $totalLeaveHours += $totalLeaveHoursInsideWorkingHours;
} }
if($leave["absenceTypeKey"] == AbsenceTypeConstant::REST){ if($leave["absenceTypeKey"] == AbsenceTypeConstant::REST) {
$totalRestHours += $totalLeaveHoursInsideWorkingHours; $totalRestHours += $totalLeaveHoursInsideWorkingHours;
} }
if($leave["absenceTypeKey"] == AbsenceTypeConstant::DISEASE){ if($leave["absenceTypeKey"] == AbsenceTypeConstant::DISEASE) {
$totalDiseaseHours += $totalLeaveHoursInsideWorkingHours; $totalDiseaseHours += $totalLeaveHoursInsideWorkingHours;
} }
} }
} }
$totalAbsenceHours = $totalLeaveHours + $totalRestHours + $totalDiseaseHours; $totalAbsenceHours = $totalLeaveHours + $totalRestHours + $totalDiseaseHours;
$totalWorkedHours -= $totalAbsenceHours; $totalWorkedHours -= $totalAbsenceHours;
} } else {
else{ $totalDevisCount += count($devisData["devisId"]);
$totalDevisCount += count($devisData["devisId"]); $routeLines = $this->gestionBdd->getRouteLinesByDevisIdList($devisData["devisId"]);
$routeLines = $this->gestionBdd->getRouteLinesByDevisIdList($devisData["devisId"]); $totalDistanceAndTotalTravelingHoursBetweenDevis = $this->geoService->getTotalDistanceAndTotalTravelingHoursBetweenDevisLocationByRouteLines($routeLines);
$totalDistanceAndTotalTravelingHoursBetweenDevis = $this->geoService->getTotalDistanceAndTotalTravelingHoursBetweenDevisLocationByRouteLines($routeLines); $totalDistance = $totalDistanceAndTotalTravelingHoursBetweenDevis["totalDistance"];
$totalDistance = $totalDistanceAndTotalTravelingHoursBetweenDevis["totalDistance"]; $totalTravelingHoursBetweenDevisLocation = $totalDistanceAndTotalTravelingHoursBetweenDevis["totalTravelingHours"];
$totalTravelingHoursBetweenDevisLocation = $totalDistanceAndTotalTravelingHoursBetweenDevis["totalTravelingHours"]; $devisList = $devisData["devis"];
$devisList = $devisData["devis"]; $leaves = $devisData["leaves"];
$leaves = $devisData["leaves"]; if(!empty($devisList)) {
if(!empty($devisList)){ foreach($devisList as $devis) {
foreach($devisList as $devis){ $fileContent = $this->populateDevisDataIntoThanatoExportFileContent($fileContent, $devis);
$fileContent = $this->populateDevisDataIntoThanatoExportFileContent($fileContent,$devis); $totalDevisHours += $devis["totalHours"];
$totalDevisHours += $devis["totalHours"]; }
} }
} foreach($leaves as $leave) {
foreach($leaves as $leave){ $fileContent = $this->populateNoDevisDataInADay($fileContent, $leave);
$fileContent = $this->populateNoDevisDataInADay($fileContent,$leave); if($leave["onLeave"]) {
if($leave["onLeave"]){ $totalLeaveHoursInsideWorkingHours = $leave["totalWorkedHours"];
$totalLeaveHoursInsideWorkingHours = $leave["totalWorkedHours"]; if($leave["absenceTypeKey"] == AbsenceTypeConstant::LEAVE) {
if($leave["absenceTypeKey"] == AbsenceTypeConstant::LEAVE){ $totalLeaveHours += $totalLeaveHoursInsideWorkingHours;
$totalLeaveHours += $totalLeaveHoursInsideWorkingHours; }
} if($leave["absenceTypeKey"] == AbsenceTypeConstant::REST) {
if($leave["absenceTypeKey"] == AbsenceTypeConstant::REST){ $totalRestHours += $totalLeaveHoursInsideWorkingHours;
$totalRestHours += $totalLeaveHoursInsideWorkingHours; }
} if($leave["absenceTypeKey"] == AbsenceTypeConstant::DISEASE) {
if($leave["absenceTypeKey"] == AbsenceTypeConstant::DISEASE){ $totalDiseaseHours += $totalLeaveHoursInsideWorkingHours;
$totalDiseaseHours += $totalLeaveHoursInsideWorkingHours; }
} }
} }
} $totalAbsenceHours = $totalLeaveHours + $totalRestHours + $totalDiseaseHours;
$totalAbsenceHours = $totalLeaveHours + $totalRestHours + $totalDiseaseHours; $totalWorkedHours -= $totalAbsenceHours;
$totalWorkedHours -= $totalAbsenceHours; }
}
$fileContent = $this->populateLastRecapForTheLine( $fileContent = $this->populateLastRecapForTheLine(
$fileContent, $fileContent,
$totalDistance, $totalDistance,
$totalDevisHours, $totalDevisHours,
$totalWorkedHours, $totalWorkedHours,
$totalLeaveHours, $totalLeaveHours,
$totalTravelingHoursBetweenDevisLocation, $totalTravelingHoursBetweenDevisLocation,
$totalDiseaseHours, $totalDiseaseHours,
$totalRestHours,$totalDevisCount $totalRestHours,
); $totalDevisCount
);
$g_totalDistance += $totalDistance; $g_totalDistance += $totalDistance;
$g_totalDevisHours += $totalDevisHours; $g_totalDevisHours += $totalDevisHours;
@ -268,8 +277,8 @@ class ExportThanatoStatisticService {
$g_totalTravelingHoursBetweenDevisLocation += $totalTravelingHoursBetweenDevisLocation; $g_totalTravelingHoursBetweenDevisLocation += $totalTravelingHoursBetweenDevisLocation;
$g_totalDiseaseHours += $totalDiseaseHours; $g_totalDiseaseHours += $totalDiseaseHours;
$g_totalRestHours += $totalRestHours; $g_totalRestHours += $totalRestHours;
$g_totalDevisCount += $totalDevisCount; $g_totalDevisCount += $totalDevisCount;
} }
$fileContent = $this->populateLastRecapForTheLine( $fileContent = $this->populateLastRecapForTheLine(
$fileContent, $fileContent,
@ -279,77 +288,113 @@ class ExportThanatoStatisticService {
$g_totalLeaveHours, $g_totalLeaveHours,
$g_totalTravelingHoursBetweenDevisLocation, $g_totalTravelingHoursBetweenDevisLocation,
$g_totalDiseaseHours, $g_totalDiseaseHours,
$g_totalRestHours,$g_totalDevisCount $g_totalRestHours,
$g_totalDevisCount
); );
return $fileContent; return $fileContent;
} }
private function populateLastRecapForTheLine(string $fileContent,$distance,$totalDevisHours,$totalWorkedHours,$totalLeaveHours,$totalTravelingHours ,$totalDiseaseHours = 0,$totalRestHours = 0,$totalDevisCount = 0){ private function populateLastRecapForTheLine(string $fileContent, $distance, $totalDevisHours, $totalWorkedHours, $totalLeaveHours, $totalTravelingHours, $totalDiseaseHours = 0, $totalRestHours = 0, $totalDevisCount = 0)
$fileContent = $fileContent. {
''.';'. $fileContent = $fileContent.
''.';'. ''.';'.
''.';'. ''.';'.
''.';'. ''.';'.
''.';'. ''.';'.
''.';'. ''.';'.
''.';'. ''.';'.
''.';'. ''.';'.
''.';'. ''.';'.
''.';'. ''.';'.
''.';'. ''.';'.
''.';'. ''.';'.
''.';'. ''.';'.
''.';'. ''.';'.
"$distance".';'. ''.';'.
"$totalDevisHours".';'. "$distance".';'.
"$totalLeaveHours".';'. "$totalDevisHours".';'.
"$totalRestHours".';'. "$totalLeaveHours".';'.
"$totalDiseaseHours".';'. "$totalRestHours".';'.
"$totalWorkedHours".';'. "$totalDiseaseHours".';'.
"$totalTravelingHours".';'. "$totalWorkedHours".';'.
"$totalDevisCount"."\n"; "$totalTravelingHours".';'.
return $fileContent; "$totalDevisCount"."\n";
} return $fileContent;
}
private function getFormatDevisProduitsAsString($devisProduits){ private function getFormatDevisProduitsAsString($devisProduits)
$result = ''; {
foreach ($devisProduits as $produit) { $result = '';
$result .= $produit['produit_reference'] . '-' . $produit['produit_description'] . '--'; foreach ($devisProduits as $produit) {
} $result .= $produit['produit_reference'] . '-' . $produit['produit_description'] . '--';
// Remove the trailing "--" at the end }
$result = rtrim($result, '-'); // Remove the trailing "--" at the end
return $result; $result = rtrim($result, '-');
} return $result;
}
private function populateDevisDataIntoThanatoExportFileContent(string $fileContent,array $devis){ private function populateDevisDataIntoThanatoExportFileContentSave(string $fileContent, array $devis)
$produitAsString = $this->getFormatDevisProduitsAsString($devis["produits"]); {
$factureNum = $devis["facture_num"] ?? $devis["facture_on_group_num"] ?? ""; $produitAsString = $this->getFormatDevisProduitsAsString($devis["produits"]);
$fileContent = $fileContent. $factureNum = $devis["facture_num"] ?? $devis["facture_on_group_num"] ?? "";
FileExportHelpers::FormatTextForExport($factureNum).';'. $fileContent = $fileContent.
FileExportHelpers::FormatTextForExport($devis['nom_thanato'] . ' ' . $devis['prenom_thanatho']).';'. FileExportHelpers::FormatTextForExport($factureNum).';'.
FileExportHelpers::FormatTextForExport($devis["date"]).';'. FileExportHelpers::FormatTextForExport($devis['nom_thanato'] . ' ' . $devis['prenom_thanatho']).';'.
FileExportHelpers::FormatTextForExport($devis["startTime"]).';'. FileExportHelpers::FormatTextForExport($devis["date"]).';'.
FileExportHelpers::FormatTextForExport($devis["endTime"]).';'. FileExportHelpers::FormatTextForExport($devis["startTime"]).';'.
FileExportHelpers::FormatTextForExport($produitAsString).';'. FileExportHelpers::FormatTextForExport($devis["endTime"]).';'.
FileExportHelpers::FormatTextForExport($devis["dayType"]).';'. FileExportHelpers::FormatTextForExport($produitAsString).';'.
FileExportHelpers::FormatTextForExport('Non').';'. FileExportHelpers::FormatTextForExport($devis["dayType"]).';'.
''.';'. FileExportHelpers::FormatTextForExport('Non').';'.
''.';'. ''.';'.
FileExportHelpers::FormatTextForExport($devis["nom_defunt"]).';'. ''.';'.
FileExportHelpers::FormatTextForExport($devis["nom_lieu"] ?? "").';'. FileExportHelpers::FormatTextForExport($devis["nom_defunt"]).';'.
FileExportHelpers::FormatTextForExport($devis["nom_client"] ?? "").';'. FileExportHelpers::FormatTextForExport($devis["nom_lieu"] ?? "").';'.
FileExportHelpers::FormatTextForExport($devis["client_adresse"] ?? ""). FileExportHelpers::FormatTextForExport($devis["nom_client"] ?? "").';'.
''.';'. FileExportHelpers::FormatTextForExport($devis["client_adresse"] ?? "").
''.';'. ''.';'.
''.';'. ''.';'.
''.';'. ''.';'.
''.';'. ''.';'.
''.';'. ''.';'.
''.';'. ''.';'.
''.';'."\n"; ''.';'.
''.';'."\n";
return $fileContent;
} return $fileContent;
}
private function populateDevisDataIntoThanatoExportFileContent(string $fileContent, array $devis)
{
$produitAsString = $this->getFormatDevisProduitsAsString($devis["produits"]);
$devisNum = (string)($devis["calendar_uuid"] ?? "");
$fileContent = $fileContent.
FileExportHelpers::FormatTextForExport($devisNum).';'.
FileExportHelpers::FormatTextForExport(($devis['nom_thanato'] ?? '') . ' ' . ($devis['prenom_thanato'] ?? '')).';'.
FileExportHelpers::FormatTextForExport($devis["date"] ?? "").';'.
FileExportHelpers::FormatTextForExport($devis["startTime"] ?? "").';'.
FileExportHelpers::FormatTextForExport($devis["endTime"] ?? "").';'.
FileExportHelpers::FormatTextForExport($produitAsString).';'.
FileExportHelpers::FormatTextForExport($devis["dayType"] ?? "").';'.
'Non'.';'.
''.';'.
''.';'.
FileExportHelpers::FormatTextForExport($devis["nom_defunt"] ?? "").';'. // ICI
FileExportHelpers::FormatTextForExport($devis["nom_lieu"] ?? "").';'.
FileExportHelpers::FormatTextForExport($devis["nom_client"] ?? "").';'.
FileExportHelpers::FormatTextForExport($devis["client_adresse"] ?? "").';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'.
''.';'."\n";
return $fileContent;
}
} }

View File

@ -30,28 +30,31 @@ use Exception;
use OCA\Gestion\Constants\GeoConstant; use OCA\Gestion\Constants\GeoConstant;
use OCA\Gestion\Helpers\GeoHelpers; use OCA\Gestion\Helpers\GeoHelpers;
class GeoService { class GeoService
{
public function __construct() { public function __construct()
} {
}
/** /**
* Calcul la distance entre les deux points à vol d'oiseau * Calcul la distance entre les deux points à vol d'oiseau
*/ */
private function getDistanceInKmBetweenTwoPoints($lat1, $lon1, $lat2, $lon2) { private function getDistanceInKmBetweenTwoPoints($lat1, $lon1, $lat2, $lon2)
{
$R = 6371; // Rayon moyen de la Terre en kilomètres $R = 6371; // Rayon moyen de la Terre en kilomètres
$dLat = deg2rad($lat2 - $lat1); $dLat = deg2rad($lat2 - $lat1);
$dLon = deg2rad($lon2 - $lon1); $dLon = deg2rad($lon2 - $lon1);
$a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon/2) * sin($dLon/2); $a = sin($dLat / 2) * sin($dLat / 2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon / 2) * sin($dLon / 2);
$c = 2 * atan2(sqrt($a), sqrt(1-$a)); $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
$d = $R * $c; $d = $R * $c;
return round($d, 2); return round($d, 2);
} }
private function getTravelingHourBetweenTwoPoints(array $origin,array $destination,$mode = "driving"){ private function getTravelingHourBetweenTwoPoints(array $origin, array $destination, $mode = "driving")
{
$baseUrl = "https://api.geoapify.com/v1/routing"; $baseUrl = "https://api.geoapify.com/v1/routing";
$originPoints = GeoHelpers::getPointsTextFromLatitudeAndLongitude($origin["latitude"],$origin["longitude"]); $originPoints = GeoHelpers::getPointsTextFromLatitudeAndLongitude($origin["latitude"], $origin["longitude"]);
$destinationPoints = GeoHelpers::getPointsTextFromLatitudeAndLongitude($destination["latitude"],$destination["longitude"]); $destinationPoints = GeoHelpers::getPointsTextFromLatitudeAndLongitude($destination["latitude"], $destination["longitude"]);
$fullUrl = $baseUrl."?waypoints=$originPoints|$destinationPoints&mode=$mode&apiKey=9e23d93e7f454c988344f9171bf867aa"; $fullUrl = $baseUrl."?waypoints=$originPoints|$destinationPoints&mode=$mode&apiKey=9e23d93e7f454c988344f9171bf867aa";
$curl = curl_init(); $curl = curl_init();
@ -66,11 +69,11 @@ class GeoService {
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET', CURLOPT_CUSTOMREQUEST => 'GET',
)); ));
$response = curl_exec($curl); $response = curl_exec($curl);
curl_close($curl); curl_close($curl);
if ($response === false) { if ($response === false) {
return 0; return 0;
} else { } else {
@ -79,45 +82,45 @@ class GeoService {
$travelTimeHours = round($travelTimeHours, 2); $travelTimeHours = round($travelTimeHours, 2);
return $travelTimeHours; return $travelTimeHours;
} }
} } catch(Exception $e) {
catch(Exception $e){
return 0; return 0;
} }
} }
public function getTotalDistanceAndTotalTravelingHoursBetweenDevisLocationByRouteLines(array $routeLines){ public function getTotalDistanceAndTotalTravelingHoursBetweenDevisLocationByRouteLinesSave(array $routeLines)
{
$distanceCumul = 0; $distanceCumul = 0;
$totalTravelingHoursBetweenTwoDevisLocation = 0; $totalTravelingHoursBetweenTwoDevisLocation = 0;
$lastPoint = NULL; $lastPoint = null;
for ($i=0; $i < sizeof($routeLines); $i++) { for ($i = 0; $i < sizeof($routeLines); $i++) {
$currentDistance = 0; $currentDistance = 0;
if($routeLines[$i]['lieu_id'] != NULL){ if($routeLines[$i]['lieu_id'] != null) {
$lastPoint = $routeLines[$i]; $lastPoint = $routeLines[$i];
} }
if($lastPoint['lieu_id'] != NULL && $routeLines[$i+1]['lieu_id'] != NULL){ if($lastPoint['lieu_id'] != null && $routeLines[$i + 1]['lieu_id'] != null) {
$currentDistance = $this->getDistanceInKmBetweenTwoPoints( $currentDistance = $this->getDistanceInKmBetweenTwoPoints(
floatval(value: $lastPoint['latitude']), floatval(value: $lastPoint['latitude']),
floatval($lastPoint['longitude']), floatval($lastPoint['longitude']),
floatval($routeLines[$i+1]['latitude']), floatval($routeLines[$i + 1]['latitude']),
floatval($routeLines[$i+1]['longitude']) floatval($routeLines[$i + 1]['longitude'])
); );
$targetIsBetweenTwoDevisLocation = $lastPoint['source'] != "siege" && $routeLines[$i+1]["source"] != "siege"; $targetIsBetweenTwoDevisLocation = $lastPoint['source'] != "siege" && $routeLines[$i + 1]["source"] != "siege";
if($targetIsBetweenTwoDevisLocation){ if($targetIsBetweenTwoDevisLocation) {
$originPoints = [ $originPoints = [
"latitude" => $lastPoint["latitude"], "latitude" => $lastPoint["latitude"],
"longitude" => $lastPoint["longitude"] "longitude" => $lastPoint["longitude"]
]; ];
$destinationPoints = [ $destinationPoints = [
"latitude" => $routeLines[$i+1]["latitude"], "latitude" => $routeLines[$i + 1]["latitude"],
"longitude" => $routeLines[$i+1]["longitude"] "longitude" => $routeLines[$i + 1]["longitude"]
]; ];
$totalTravelingHoursBetweenTwoDevisLocation+= $this->getTravelingHourBetweenTwoPoints( $totalTravelingHoursBetweenTwoDevisLocation += $this->getTravelingHourBetweenTwoPoints(
$originPoints, $originPoints,
$destinationPoints, $destinationPoints,
GeoConstant::DRIVING_MODE GeoConstant::DRIVING_MODE
); );
} }
} }
$distanceCumul += $currentDistance; $distanceCumul += $currentDistance;
} }
return [ return [
@ -125,4 +128,65 @@ class GeoService {
"totalTravelingHours" => $totalTravelingHoursBetweenTwoDevisLocation "totalTravelingHours" => $totalTravelingHoursBetweenTwoDevisLocation
]; ];
} }
public function getTotalDistanceAndTotalTravelingHoursBetweenDevisLocationByRouteLines(array $routeLines)
{
$distanceCumul = 0;
$totalTravelingHoursBetweenTwoDevisLocation = 0;
$lastPoint = null;
for ($i = 0; $i < sizeof($routeLines); $i++) {
$currentDistance = 0;
// Vérifier que l'élément actuel existe
if(!isset($routeLines[$i])) {
continue;
}
if($routeLines[$i]['lieu_id'] != null) {
$lastPoint = $routeLines[$i];
}
// Vérifier que $i+1 existe ET que $lastPoint n'est pas null
if($lastPoint !== null &&
isset($routeLines[$i + 1]) &&
isset($lastPoint['lieu_id']) &&
isset($routeLines[$i + 1]['lieu_id']) &&
$lastPoint['lieu_id'] != null &&
$routeLines[$i + 1]['lieu_id'] != null) {
$currentDistance = $this->getDistanceInKmBetweenTwoPoints(
floatval($lastPoint['latitude']),
floatval($lastPoint['longitude']),
floatval($routeLines[$i + 1]['latitude']),
floatval($routeLines[$i + 1]['longitude'])
);
$targetIsBetweenTwoDevisLocation = $lastPoint['source'] != "siege" && $routeLines[$i + 1]["source"] != "siege";
if($targetIsBetweenTwoDevisLocation) {
$originPoints = [
"latitude" => $lastPoint["latitude"],
"longitude" => $lastPoint["longitude"]
];
$destinationPoints = [
"latitude" => $routeLines[$i + 1]["latitude"],
"longitude" => $routeLines[$i + 1]["longitude"]
];
$totalTravelingHoursBetweenTwoDevisLocation += $this->getTravelingHourBetweenTwoPoints(
$originPoints,
$destinationPoints,
GeoConstant::DRIVING_MODE
);
}
}
$distanceCumul += $currentDistance;
}
return [
"totalDistance" => round($distanceCumul, 2),
"totalTravelingHours" => round($totalTravelingHoursBetweenTwoDevisLocation, 2)
];
}
} }