Files
Starseed/src/Module/Commercial/Infrastructure/ApiPlatform/State/Provider/ClientProvider.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

131 lines
4.8 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
* ?categoryType=<code> (clients ayant >= 1 categorie de ce type) ;
* - 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);
$search = $filters['search'] ?? null;
$categoryType = $filters['categoryType'] ?? null;
// Filtrage delegue au repository (logique partagee avec l'export XLSX).
$qb = $this->repository->createListQueryBuilder(
$includeArchived,
is_string($search) ? $search : null,
is_string($categoryType) ? $categoryType : null,
);
// 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> $result
return $qb->getQuery()->getResult();
}
$limit = $this->pagination->getLimit($operation, $context);
$page = max(1, $this->pagination->getPage($context));
$offset = ($page - 1) * $limit;
$qb->setFirstResult($offset)->setMaxResults($limit);
// fetchJoinCollection: true pour un COUNT correct des que des JOINs
// to-many seront ajoutes (sous-collections embarquees en detail).
return new Paginator(new DoctrinePaginator($qb->getQuery(), fetchJoinCollection: true));
}
/**
* @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);
}
}