feat : export Excel et stats par tranche d'âge sur l'inventaire bovin
Some checks failed
Auto Tag Develop / tag (push) Has been cancelled
Some checks failed
Auto Tag Develop / tag (push) Has been cancelled
- Dépendance phpoffice/phpspreadsheet - Endpoint GET /bovines/inventory-export : XLSX coloré, header figé, auto-filter, tri birthDate ASC - Endpoint GET /bovines/inventory-stats : comptes par tranche d'âge (>=24, 22-24, 20-22) - Bouton Excel à gauche du titre (style icône-only, même design que le bouton impression) - Légende visuelle avec cartes bordées coloriées - Ajustement seuils couleurs des lignes en -300 (base) / -400 (hover) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
32
src/ApiResource/BovineInventoryExport.php
Normal file
32
src/ApiResource/BovineInventoryExport.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\ApiResource;
|
||||
|
||||
use ApiPlatform\Metadata\ApiProperty;
|
||||
use ApiPlatform\Metadata\ApiResource;
|
||||
use ApiPlatform\Metadata\Get;
|
||||
use ApiPlatform\OpenApi\Model\Operation as OpenApiOperation;
|
||||
use App\State\Bovin\BovineInventoryExportProvider;
|
||||
|
||||
#[ApiResource(
|
||||
operations: [
|
||||
new Get(
|
||||
uriTemplate: '/bovines/inventory-export',
|
||||
openapi: new OpenApiOperation(
|
||||
summary: "Export Excel de l'inventaire bovin actuel.",
|
||||
description: "Retourne un fichier XLSX listant tous les bovins actifs (exitedAt IS NULL) triés par date de naissance croissante, avec colorisation des lignes selon l'âge.",
|
||||
tags: ['Bovines'],
|
||||
),
|
||||
security: "is_granted('ROLE_USER')",
|
||||
output: false,
|
||||
provider: BovineInventoryExportProvider::class,
|
||||
),
|
||||
]
|
||||
)]
|
||||
final class BovineInventoryExport
|
||||
{
|
||||
#[ApiProperty(identifier: true)]
|
||||
public string $id = 'current';
|
||||
}
|
||||
39
src/ApiResource/BovineInventoryStats.php
Normal file
39
src/ApiResource/BovineInventoryStats.php
Normal file
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\ApiResource;
|
||||
|
||||
use ApiPlatform\Metadata\ApiProperty;
|
||||
use ApiPlatform\Metadata\ApiResource;
|
||||
use ApiPlatform\Metadata\Get;
|
||||
use ApiPlatform\OpenApi\Model\Operation as OpenApiOperation;
|
||||
use App\State\Bovin\BovineInventoryStatsProvider;
|
||||
|
||||
#[ApiResource(
|
||||
operations: [
|
||||
new Get(
|
||||
uriTemplate: '/bovines/inventory-stats',
|
||||
openapi: new OpenApiOperation(
|
||||
summary: "Compteurs de l'inventaire bovin par tranche d'âge.",
|
||||
description: "Renvoie le nombre total de bovins actifs et la répartition par tranche d'âge (>= 24 mois, 22-24, 20-22).",
|
||||
tags: ['Bovines'],
|
||||
),
|
||||
security: "is_granted('ROLE_USER')",
|
||||
provider: BovineInventoryStatsProvider::class,
|
||||
),
|
||||
]
|
||||
)]
|
||||
final class BovineInventoryStats
|
||||
{
|
||||
#[ApiProperty(identifier: true)]
|
||||
public string $id = 'current';
|
||||
|
||||
public int $total = 0;
|
||||
|
||||
public int $over24 = 0;
|
||||
|
||||
public int $between22And24 = 0;
|
||||
|
||||
public int $between20And22 = 0;
|
||||
}
|
||||
206
src/State/Bovin/BovineInventoryExportProvider.php
Normal file
206
src/State/Bovin/BovineInventoryExportProvider.php
Normal file
@@ -0,0 +1,206 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\State\Bovin;
|
||||
|
||||
use ApiPlatform\Metadata\Operation;
|
||||
use ApiPlatform\State\ProviderInterface;
|
||||
use App\Entity\Bovine;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
|
||||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Alignment;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Border;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Fill;
|
||||
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* @implements ProviderInterface<Response>
|
||||
*/
|
||||
final class BovineInventoryExportProvider implements ProviderInterface
|
||||
{
|
||||
private const HEADER_FILL = 'FFF1F5F9';
|
||||
|
||||
private const COLOR_VIOLET = 'FFC4B5FD';
|
||||
|
||||
private const COLOR_RED = 'FFFCA5A5';
|
||||
|
||||
private const COLOR_ORANGE = 'FFFDBA74';
|
||||
|
||||
private const HEADERS = [
|
||||
'N° National',
|
||||
'N° Travail',
|
||||
'Sexe',
|
||||
'Né le',
|
||||
'Age (mois)',
|
||||
'Race',
|
||||
'Bâtiment',
|
||||
'Case',
|
||||
'Entrée le',
|
||||
];
|
||||
|
||||
private const COLUMN_WIDTHS = [18, 12, 10, 12, 12, 12, 30, 8, 12];
|
||||
|
||||
public function __construct(
|
||||
private EntityManagerInterface $em,
|
||||
) {}
|
||||
|
||||
public function provide(Operation $operation, array $uriVariables = [], array $context = []): Response
|
||||
{
|
||||
$bovines = $this->em->createQueryBuilder()
|
||||
->select('b')
|
||||
->from(Bovine::class, 'b')
|
||||
->where('b.exitedAt IS NULL')
|
||||
->orderBy('b.birthDate', 'ASC')
|
||||
->getQuery()
|
||||
->getResult()
|
||||
;
|
||||
|
||||
$spreadsheet = $this->buildSpreadsheet($bovines);
|
||||
$body = $this->renderXlsx($spreadsheet);
|
||||
$filename = sprintf('inventaire_bovins_%s.xlsx', new DateTimeImmutable()->format('Y-m-d'));
|
||||
|
||||
$response = new Response($body);
|
||||
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
||||
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
|
||||
$response->headers->set('Content-Length', (string) strlen($body));
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<Bovine> $bovines
|
||||
*/
|
||||
private function buildSpreadsheet(array $bovines): Spreadsheet
|
||||
{
|
||||
$spreadsheet = new Spreadsheet();
|
||||
$sheet = $spreadsheet->getActiveSheet();
|
||||
$sheet->setTitle('Inventaire');
|
||||
|
||||
// Header row
|
||||
foreach (self::HEADERS as $index => $label) {
|
||||
$sheet->setCellValue([$index + 1, 1], $label);
|
||||
}
|
||||
|
||||
$lastColumn = $sheet->getHighestColumn();
|
||||
$headerRange = sprintf('A1:%s1', $lastColumn);
|
||||
$sheet->getStyle($headerRange)->applyFromArray([
|
||||
'font' => ['bold' => true],
|
||||
'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
|
||||
'fill' => [
|
||||
'fillType' => Fill::FILL_SOLID,
|
||||
'startColor' => ['argb' => self::HEADER_FILL],
|
||||
],
|
||||
'borders' => [
|
||||
'allBorders' => ['borderStyle' => Border::BORDER_THIN],
|
||||
],
|
||||
]);
|
||||
|
||||
// Column widths
|
||||
foreach (self::COLUMN_WIDTHS as $index => $width) {
|
||||
$sheet->getColumnDimension(Coordinate::stringFromColumnIndex($index + 1))->setWidth($width);
|
||||
}
|
||||
|
||||
// N° National et N° Travail : valeurs numériques mais conservées en string
|
||||
// (leading zeros, format métier) — on force le format texte pour éviter
|
||||
// l'avertissement Excel "nombre stocké sous forme de texte".
|
||||
$sheet->getStyle('A')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
|
||||
$sheet->getStyle('B')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
|
||||
|
||||
// Data rows
|
||||
$rowNumber = 2;
|
||||
foreach ($bovines as $bovine) {
|
||||
$values = $this->formatRow($bovine);
|
||||
foreach ($values as $colIndex => $value) {
|
||||
$sheet->setCellValue([$colIndex + 1, $rowNumber], $value);
|
||||
}
|
||||
|
||||
$color = $this->ageColor($bovine->getAgeMonths());
|
||||
if (null !== $color) {
|
||||
$rowRange = sprintf('A%d:%s%d', $rowNumber, $lastColumn, $rowNumber);
|
||||
$sheet->getStyle($rowRange)->applyFromArray([
|
||||
'fill' => [
|
||||
'fillType' => Fill::FILL_SOLID,
|
||||
'startColor' => ['argb' => $color],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
++$rowNumber;
|
||||
}
|
||||
|
||||
// Freeze header row + auto-filter
|
||||
$sheet->freezePane('A2');
|
||||
if ($rowNumber > 2) {
|
||||
$sheet->setAutoFilter(sprintf('%s:%s%d', 'A1', $lastColumn, $rowNumber - 1));
|
||||
} else {
|
||||
$sheet->setAutoFilter($headerRange);
|
||||
}
|
||||
|
||||
return $spreadsheet;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<null|int|string>
|
||||
*/
|
||||
private function formatRow(Bovine $bovine): array
|
||||
{
|
||||
return [
|
||||
$bovine->getNationalNumber(),
|
||||
$bovine->getWorkNumber(),
|
||||
$this->formatSex($bovine->getSex()),
|
||||
$this->formatDate($bovine->getBirthDate()),
|
||||
$bovine->getAgeMonths(),
|
||||
$bovine->getBreedCode(),
|
||||
$bovine->getBuildingCase()?->getIdBuilding()?->getLabel(),
|
||||
$bovine->getBuildingCase()?->getCaseNumber(),
|
||||
$this->formatDate($bovine->getArrivalDate()),
|
||||
];
|
||||
}
|
||||
|
||||
private function formatSex(?string $sex): ?string
|
||||
{
|
||||
return match ($sex) {
|
||||
'M' => 'Mâle',
|
||||
'F' => 'Femelle',
|
||||
default => $sex,
|
||||
};
|
||||
}
|
||||
|
||||
private function formatDate(?DateTimeImmutable $date): ?string
|
||||
{
|
||||
return $date?->format('d/m/Y');
|
||||
}
|
||||
|
||||
private function ageColor(?int $ageMonths): ?string
|
||||
{
|
||||
if (null === $ageMonths) {
|
||||
return null;
|
||||
}
|
||||
if ($ageMonths >= 24) {
|
||||
return self::COLOR_VIOLET;
|
||||
}
|
||||
if ($ageMonths >= 22) {
|
||||
return self::COLOR_RED;
|
||||
}
|
||||
if ($ageMonths >= 20) {
|
||||
return self::COLOR_ORANGE;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function renderXlsx(Spreadsheet $spreadsheet): string
|
||||
{
|
||||
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
|
||||
ob_start();
|
||||
$writer->save('php://output');
|
||||
$body = ob_get_clean();
|
||||
|
||||
return false !== $body ? $body : '';
|
||||
}
|
||||
}
|
||||
41
src/State/Bovin/BovineInventoryStatsProvider.php
Normal file
41
src/State/Bovin/BovineInventoryStatsProvider.php
Normal file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\State\Bovin;
|
||||
|
||||
use ApiPlatform\Metadata\Operation;
|
||||
use ApiPlatform\State\ProviderInterface;
|
||||
use App\ApiResource\BovineInventoryStats;
|
||||
use Doctrine\DBAL\Connection;
|
||||
|
||||
/**
|
||||
* @implements ProviderInterface<BovineInventoryStats>
|
||||
*/
|
||||
final class BovineInventoryStatsProvider implements ProviderInterface
|
||||
{
|
||||
public function __construct(
|
||||
private Connection $connection,
|
||||
) {}
|
||||
|
||||
public function provide(Operation $operation, array $uriVariables = [], array $context = []): BovineInventoryStats
|
||||
{
|
||||
$row = $this->connection->fetchAssociative(<<<'SQL'
|
||||
SELECT
|
||||
COUNT(*) AS total,
|
||||
COUNT(*) FILTER (WHERE age_months >= 24) AS over_24,
|
||||
COUNT(*) FILTER (WHERE age_months >= 22 AND age_months < 24) AS between_22_and_24,
|
||||
COUNT(*) FILTER (WHERE age_months >= 20 AND age_months < 22) AS between_20_and_22
|
||||
FROM bovine
|
||||
WHERE exited_at IS NULL
|
||||
SQL);
|
||||
|
||||
$stats = new BovineInventoryStats();
|
||||
$stats->total = (int) ($row['total'] ?? 0);
|
||||
$stats->over24 = (int) ($row['over_24'] ?? 0);
|
||||
$stats->between22And24 = (int) ($row['between_22_and_24'] ?? 0);
|
||||
$stats->between20And22 = (int) ($row['between_20_and_22'] ?? 0);
|
||||
|
||||
return $stats;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user