97301dcd6c
Auto Tag Develop / tag (push) Successful in 7s
## Contexte Issu de la review ERP-62 (#44). `DoctrineClientRepository::createListQueryBuilder()` portait 3 `leftJoin+addSelect` to-many imbriqués (`categories × addresses × addresses.sites`) **partagés** entre : - la **liste paginée** (`ClientProvider`) — bornée, OK ; - l'**export XLSX** et **`?pagination=false`** — `getResult()` sans pagination → hydratation du **produit cartésien sur tout le référentiel** (1 client à 5 cat × 4 adr × 3 sites = 60 lignes SQL, × N clients). Défaut d'altitude : un « QueryBuilder de liste » (contrat = filtres) imposait une stratégie d'hydratation à tout appelant. ## Changements - **`createListQueryBuilder()`** redevient **filtres + tri seuls** — conforme au contrat de l'interface. - Nouvelle méthode **`hydrateListCollections(array $clients)`** : recharge les collections en **2 requêtes `WHERE id IN(...)` séparées** (catégories d'un côté, adresses+sites de l'autre) via l'identity map Doctrine. Casse le triple cartésien en `cat + (addr × site)`. - **3 appelants** branchés sur cette stratégie unique : - liste paginée : `fetchJoinCollection: false` (COUNT simple) + hydratation de la page ; - `?pagination=false` : hydratation après `getResult()` ; - export XLSX : hydratation après `getResult()`. ## Tests - `make test` : **465 OK**. - Nouveau test `ClientExportControllerTest::testExportPopulatesCategoryAndSiteColumns` : garde-fou sur les valeurs Catégories/Sites de l'export (qu'un oubli d'hydratation rendrait silencieusement vides). - `php-cs-fixer` : 0 correction. ## Notes - Benchmark « 1000+ clients » non exécuté (pas de jeu de données à cette échelle en dev) ; le cartésien est supprimé structurellement. - `addr × site` reste un join imbriqué (inévitable pour agréger les sites par adresse), désormais non multiplié par les catégories. Closes ERP-100. --------- Co-authored-by: admin malio <malio@yuno.malio.fr> Co-authored-by: Matthieu <contact@malio.fr> Reviewed-on: #50 Co-authored-by: THOLOT DECHENE Matthieu <matthieu@yuno.malio.fr> Co-committed-by: THOLOT DECHENE Matthieu <matthieu@yuno.malio.fr>
186 lines
6.7 KiB
PHP
186 lines
6.7 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Module\Commercial\Infrastructure\ApiPlatform\State\Provider;
|
|
|
|
use ApiPlatform\Doctrine\Orm\Paginator;
|
|
use ApiPlatform\Metadata\CollectionOperationInterface;
|
|
use ApiPlatform\Metadata\Operation;
|
|
use ApiPlatform\State\Pagination\Pagination;
|
|
use ApiPlatform\State\ProviderInterface;
|
|
use App\Module\Commercial\Domain\Entity\Client;
|
|
use App\Module\Commercial\Domain\Repository\ClientRepositoryInterface;
|
|
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator;
|
|
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
|
|
|
/**
|
|
* Provider du repertoire clients (M1). Cf. spec-back M1 § 4.1 / § 4.2.
|
|
*
|
|
* Collection (GET /api/clients) :
|
|
* - exclut par defaut les archives (is_archived = true) ET les soft-deletes
|
|
* (deleted_at IS NOT NULL) — RG-1.24 ;
|
|
* - ?includeArchived=true reintegre les archives (les soft-deletes restent
|
|
* exclus au M1) — RG-1.25 ;
|
|
* - tri par defaut companyName ASC — RG-1.26 ;
|
|
* - filtres ?search=... (fuzzy companyName + lastName + email) et
|
|
* ?categoryCode=<code> (clients ayant >= 1 categorie de ce code — ERP-78) ;
|
|
* - pagination obligatoire (convention Starseed ERP-72) : Paginator ORM ;
|
|
* echappatoire ?pagination=false pour alimenter un <select> sans pagination.
|
|
*
|
|
* Item (GET /api/clients/{id} + provider de PATCH) :
|
|
* - 404 si introuvable OU soft-delete (deleted_at non null, jamais expose au
|
|
* M1) ; les archives restent consultables/restaurables en detail.
|
|
*
|
|
* Le filtrage des champs comptables en lecture (groupe client:read:accounting)
|
|
* n'est PAS fait ici mais dans ClientReadGroupContextBuilder (le provider ne
|
|
* peut pas influencer les groupes de serialisation).
|
|
*
|
|
* @implements ProviderInterface<Client>
|
|
*/
|
|
final class ClientProvider implements ProviderInterface
|
|
{
|
|
public function __construct(
|
|
#[Autowire(service: 'App\Module\Commercial\Infrastructure\Doctrine\DoctrineClientRepository')]
|
|
private readonly ClientRepositoryInterface $repository,
|
|
private readonly Pagination $pagination,
|
|
) {}
|
|
|
|
public function provide(Operation $operation, array $uriVariables = [], array $context = []): Client|iterable|Paginator|null
|
|
{
|
|
if ($operation instanceof CollectionOperationInterface) {
|
|
return $this->provideCollection($operation, $context);
|
|
}
|
|
|
|
return $this->provideItem($uriVariables);
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $context
|
|
*
|
|
* @return list<Client>|Paginator<Client>
|
|
*/
|
|
private function provideCollection(Operation $operation, array $context): array|Paginator
|
|
{
|
|
$filters = $context['filters'] ?? [];
|
|
$includeArchived = $this->readBool($filters['includeArchived'] ?? false);
|
|
$archivedOnly = $this->readBool($filters['archivedOnly'] ?? false);
|
|
$search = $filters['search'] ?? null;
|
|
// categoryCode accepte un code unique (?categoryCode=DISTRIBUTEUR, selects
|
|
// RG-1.03) OU une liste (?categoryCode[]=A&categoryCode[]=B, drawer multi).
|
|
$categoryCodes = $this->readStringList($filters['categoryCode'] ?? []);
|
|
$siteIds = $this->readIntList($filters['siteId'] ?? []);
|
|
|
|
// Filtrage delegue au repository (logique partagee avec l'export XLSX).
|
|
$qb = $this->repository->createListQueryBuilder(
|
|
$includeArchived,
|
|
is_string($search) ? $search : null,
|
|
$categoryCodes,
|
|
$siteIds,
|
|
$archivedOnly,
|
|
);
|
|
|
|
// Echappatoire ?pagination=false : collection complete sans Paginator
|
|
// (cf. convention ERP-72 — utile pour un <select> cote front).
|
|
if (!$this->pagination->isEnabled($operation, $context)) {
|
|
/** @var list<Client> $clients */
|
|
$clients = $qb->getQuery()->getResult();
|
|
// Hydratation batchee des collections affichees (cf. ERP-100) : evite
|
|
// le N+1 si la serialisation touche categories/sites, sans cartesien.
|
|
$this->repository->hydrateListCollections($clients);
|
|
|
|
return $clients;
|
|
}
|
|
|
|
$limit = $this->pagination->getLimit($operation, $context);
|
|
$page = max(1, $this->pagination->getPage($context));
|
|
$offset = ($page - 1) * $limit;
|
|
|
|
$qb->setFirstResult($offset)->setMaxResults($limit);
|
|
|
|
// Le QB de selection ne porte plus de fetch-join to-many (ERP-100) : le
|
|
// COUNT est simple, fetchJoinCollection inutile. On materialise la page
|
|
// puis on hydrate ses collections en lot (memes entites managees).
|
|
$paginator = new Paginator(new DoctrinePaginator($qb->getQuery(), fetchJoinCollection: false));
|
|
$this->repository->hydrateListCollections(iterator_to_array($paginator));
|
|
|
|
return $paginator;
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $uriVariables
|
|
*/
|
|
private function provideItem(array $uriVariables): ?Client
|
|
{
|
|
$id = $uriVariables['id'] ?? null;
|
|
if (!is_int($id) && !(is_string($id) && ctype_digit($id))) {
|
|
return null;
|
|
}
|
|
|
|
$client = $this->repository->findById((int) $id);
|
|
if (null === $client) {
|
|
return null;
|
|
}
|
|
|
|
// Soft-delete : jamais expose au M1 (HP-M2-1) — 404 via retour null.
|
|
// Les archives restent visibles en detail (consultation + restauration).
|
|
if (null !== $client->getDeletedAt()) {
|
|
return null;
|
|
}
|
|
|
|
return $client;
|
|
}
|
|
|
|
/**
|
|
* Lit un flag booleen issu des query params. Accepte true / "true" / "1".
|
|
*/
|
|
private function readBool(mixed $raw): bool
|
|
{
|
|
if (is_bool($raw)) {
|
|
return $raw;
|
|
}
|
|
|
|
return is_string($raw) && in_array(strtolower($raw), ['true', '1'], true);
|
|
}
|
|
|
|
/**
|
|
* Normalise un filtre en liste de chaines. Tolere un code unique (string)
|
|
* ou une liste (?key[]=a&key[]=b). Trim + retrait des vides.
|
|
*
|
|
* @return list<string>
|
|
*/
|
|
private function readStringList(mixed $raw): array
|
|
{
|
|
$values = is_array($raw) ? $raw : [$raw];
|
|
|
|
$out = [];
|
|
foreach ($values as $value) {
|
|
if (is_string($value) && '' !== trim($value)) {
|
|
$out[] = trim($value);
|
|
}
|
|
}
|
|
|
|
return $out;
|
|
}
|
|
|
|
/**
|
|
* Normalise un filtre en liste d'identifiants entiers positifs. Tolere une
|
|
* valeur unique ou une liste (?key[]=1&key[]=2).
|
|
*
|
|
* @return list<int>
|
|
*/
|
|
private function readIntList(mixed $raw): array
|
|
{
|
|
$values = is_array($raw) ? $raw : [$raw];
|
|
|
|
$out = [];
|
|
foreach ($values as $value) {
|
|
if ((is_int($value) || (is_string($value) && ctype_digit($value))) && (int) $value > 0) {
|
|
$out[] = (int) $value;
|
|
}
|
|
}
|
|
|
|
return $out;
|
|
}
|
|
}
|