Files
Starseed/src/Module/Commercial/Infrastructure/Controller/ClientExportController.php
T
matthieu 120058049c
Auto Tag Develop / tag (push) Successful in 7s
test(commercial) : cover RG-1.01..1.29 except role-gated (M1) + polish stack (#38)
Dernier wagon de la stack back M1. ERP-60 = polish stack + couverture de tests PHPUnit NON dépendante des rôles métier (cf. spec § 7 / § 8.1).

## Phase 0 — polish stack (déjà mergé dans les branches basses via rebase)
- ERP-59 : route sidebar `/clients` (au lieu de `/commercial/clients`), cohérente avec `/suppliers`.
- One-liner pagination Client abandonné : `pagination_client_enabled: true` est déjà le défaut global → `?pagination=false` marche déjà sur `/api/clients` (décision P7).

## Phase 1 — tests (combler les trous, zéro duplication)
8 nouvelles suites couvrant les RG non encore testées par ERP-55/56/57/58 :
- `ClientFormulaireMainTest` — RG-1.02 (téléphone secondaire, max 2).
- `ClientAddressTest` — RG-1.06/07/08 + RG-1.11 (CHECK BDD prospect/billing).
- `ClientUniquenessTest` — RG-1.15/1.17 (Q4 : SIREN/email NON uniques).
- `ClientArchiveTest` — **RG-1.23 : 409 restauration en conflit (gap P1)**.
- `ClientAuditTest` — RG-1.27 (created* figés / updatedBy modificateur) + iban/bic présents dans le diff audité.
- `ClientMigrationTest` — index partiel unique `uq_client_company_name_active` (1 seul) ; pas d'index siren/email.
- `ClientSecurityTest` — 401 anonyme + 403 sans `commercial.clients.view`.
- `ClientPatchStrictTest` — RG-1.28 (403 strict mix de groupes, fonctionnel).

Cahier de test complet (mapping de TOUTES les RG → test) : `docs/specs/M1-clients/cahier-test-back-M1.md`.

## Délégué à ERP-74 (#493)
Matrice RBAC différenciée (bureau/compta/commerciale/usine) + RG-1.04 fonctionnel — exigent les rôles métier seedés après le merge de la stack.

## Gaps documentés (cahier)
- RG-1.29 validation écriture (catégorie type sur adresse → 422) non implémentée back (hors § 8.1, ticket test-only).
- Violations CHECK adresse → rejet (≥400) sans mapping fin 422 (amélioration possible).

## Vérifs
`make db-reset && make php-cs-fixer-allow-risky && make test` → **421 tests OK, 1386 assertions, 0 risky**. Nouveaux tests : 17, 71 assertions.

---------

Co-authored-by: Matthieu <contact@malio.fr>
Reviewed-on: #38
Co-authored-by: THOLOT DECHENE Matthieu <matthieu@yuno.malio.fr>
Co-committed-by: THOLOT DECHENE Matthieu <matthieu@yuno.malio.fr>
2026-06-01 19:46:39 +00:00

202 lines
6.7 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Module\Commercial\Infrastructure\Controller;
use App\Module\Commercial\Domain\Entity\Client;
use App\Module\Commercial\Domain\Repository\ClientRepositoryInterface;
use App\Shared\Domain\Contract\CategoryInterface;
use App\Shared\Domain\Contract\SiteInterface;
use App\Shared\Domain\Contract\SpreadsheetExporterInterface;
use DateTimeImmutable;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* Export XLSX du repertoire clients (M1, spec-back § 4.6).
*
* Controller Symfony custom (et non operation API Platform) car il produit un
* binaire de fichier, pas une representation Hydra. `priority: 1` est
* OBLIGATOIRE sur la route : sans cela API Platform capterait
* `/api/clients/export.xlsx` comme l'item `GET /api/clients/{id}.{_format}`
* (id="export", _format="xlsx") — cf. CLAUDE.md « controller custom sous /api ».
*
* Separation des responsabilites :
* - le COMMENT (generation du fichier) est delegue au service Shared
* {@see SpreadsheetExporterInterface} — generique, reutilisable, sans metier ;
* - le QUOI vit ICI : selection des clients (memes filtres que
* `GET /api/clients`, via {@see ClientRepositoryInterface::createListQueryBuilder()})
* et mapping metier des colonnes.
*
* La colonne SIREN n'est ajoutee que si l'utilisateur a la permission
* `commercial.clients.accounting.view` (gating identique a la lecture).
*/
#[AsController]
final class ClientExportController
{
public function __construct(
#[Autowire(service: 'App\Module\Commercial\Infrastructure\Doctrine\DoctrineClientRepository')]
private readonly ClientRepositoryInterface $repository,
private readonly SpreadsheetExporterInterface $exporter,
private readonly Security $security,
) {}
#[Route('/api/clients/export.xlsx', name: 'commercial_clients_export_xlsx', methods: ['GET'], priority: 1)]
#[IsGranted('commercial.clients.view')]
public function __invoke(Request $request): Response
{
$includeArchived = $this->readBool($request->query->get('includeArchived'));
$search = $request->query->getString('search') ?: null;
$categoryType = $request->query->getString('categoryType') ?: null;
/** @var list<Client> $clients */
$clients = $this->repository
->createListQueryBuilder($includeArchived, $search, $categoryType)
->getQuery()
->getResult()
;
$withSiren = $this->security->isGranted('commercial.clients.accounting.view');
$binary = $this->exporter->export(
'Répertoire clients',
$this->buildHeaders($withSiren),
$this->buildRows($clients, $withSiren),
);
return $this->buildResponse($binary);
}
/**
* Colonnes dans l'ordre impose par la spec § 4.6. SIREN inseree avant la
* date de creation, uniquement si l'utilisateur a accounting.view.
*
* @return list<string>
*/
private function buildHeaders(bool $withSiren): array
{
$headers = [
'Nom entreprise',
'Nom contact principal',
'Prénom',
'Téléphone principal',
'Téléphone secondaire',
'Email',
'Catégories',
'Sites',
];
if ($withSiren) {
$headers[] = 'SIREN';
}
$headers[] = 'Date de création';
return $headers;
}
/**
* @param list<Client> $clients
*
* @return iterable<list<null|scalar>>
*/
private function buildRows(array $clients, bool $withSiren): iterable
{
foreach ($clients as $client) {
$row = [
$client->getCompanyName(),
$client->getLastName(),
$client->getFirstName(),
$client->getPhonePrimary(),
$client->getPhoneSecondary(),
$client->getEmail(),
$this->formatCategories($client),
$this->formatSites($client),
];
if ($withSiren) {
$row[] = $client->getSiren();
}
$row[] = $client->getCreatedAt()?->format('d/m/Y');
yield $row;
}
}
/**
* Libelles des categories du client, dedupliques, tries, joints par virgule.
*/
private function formatCategories(Client $client): string
{
$names = [];
foreach ($client->getCategories() as $category) {
// @var CategoryInterface $category
$name = $category->getName();
if (null !== $name && '' !== $name) {
$names[$name] = true;
}
}
return $this->joinSorted($names);
}
/**
* Le Client ne porte pas de sites en propre : ils sont rattaches aux
* adresses (RG-1.10). La colonne « Sites » agrege donc l'union distincte des
* sites de toutes les adresses du client (decision validee 01/06).
*/
private function formatSites(Client $client): string
{
$names = [];
foreach ($client->getAddresses() as $address) {
foreach ($address->getSites() as $site) {
// @var SiteInterface $site
$name = $site->getName();
if (null !== $name && '' !== $name) {
$names[$name] = true;
}
}
}
return $this->joinSorted($names);
}
/**
* @param array<string, true> $names ensemble de libelles (cles)
*/
private function joinSorted(array $names): string
{
$list = array_keys($names);
sort($list);
return implode(', ', $list);
}
private function buildResponse(string $binary): Response
{
$filename = sprintf('repertoire-clients-%s.xlsx', new DateTimeImmutable()->format('Ymd'));
$response = new Response($binary);
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
return $response;
}
/**
* Lit un flag booleen issu des query params. Accepte true / "true" / "1".
* Aligne sur ClientProvider pour un comportement identique a la liste.
*/
private function readBool(mixed $raw): bool
{
return is_string($raw) && in_array(strtolower($raw), ['true', '1'], true);
}
}