3fe0f676f6
Auto Tag Develop / tag (push) Successful in 11s
Ticket Lesstime #139 (M3 — Répertoire prestataires, position 1.9). DoD back avant le front : suite PHPUnit consolidée sur la matrice § 8.1 + captures JSON réelles dans la spec § 4.0.bis. ## Contenu - **Fix réfs comptables** : `provider:read:accounting` ajouté sur `TvaMode`/`PaymentDelay`/`PaymentType`/`Bank` — sans ça elles sortaient en IRI nu dans le détail prestataire (réplique du fix ERP-92 du M2, piège #1 § 4.0.bis). - **`ProviderSerializationContractTest`** (13 tests) : gating RIB/scalaires par omission, réfs compta en objet `{id,code,label}`, `isArchived`, embed categories/sites liste+détail, sous-collections, enveloppe AP4 ; `testDodReferenceJsonShape` dumpe le JSON réel (`PROVIDER_DOD_DUMP=1`). - **`ProviderAuditTest`** (5 tests) : create/update/archive (`technique.Provider`), iban/bic dans le diff (`technique.ProviderRib`, pas dAuditIgnore), trace M2M `sites`. - **`ProviderListTest`** étendu : `?pagination=false`, anti-N+1, filtre `?typeCode=PRESTATAIRE`. - **`ProviderRbacGatingTest`** étendu : restauration en conflit de nom → 409 (RG-3.14). - **`ProviderFixtures`** (§ 8.4) : démo idempotente (complet VIREMENT+banque+RIB, LCR+RIB, CHEQUE multi-cat, minimal, archivé) répartie sur sites 86/17/82 ; skip en env `test`. - Helper `seedCompleteProvider` ; spec § 4.0.bis : gabarits remplacés par les captures réelles (liste + détail avec/sans accounting.view). ## Vérifications - `make php-cs-fixer-allow-risky` → 0 fichier - `make test` → OK, 677 tests, 3328 assertions (garde-fous globaux verts) ## Notes - MR stackée sur ERP-138 (base = sa branche). - Fixtures démo exercées en dev via `make fixtures` (autowiring vérifié). --------- Co-authored-by: Matthieu <contact@malio.fr> Reviewed-on: #100
224 lines
9.0 KiB
PHP
224 lines
9.0 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Module\Technique\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\Technique\Domain\Entity\Provider;
|
|
use App\Module\Technique\Domain\Repository\ProviderRepositoryInterface;
|
|
use App\Module\Technique\Infrastructure\Security\ProviderSiteScopeChecker;
|
|
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator;
|
|
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
|
|
|
/**
|
|
* Provider du repertoire prestataires (M3). Cf. spec-back M3 § 4.1 / § 4.2 +
|
|
* RG-3.16 / RG-3.17. Jumeau du SupplierProvider (M2), augmente du cloisonnement
|
|
* par site pilote par l'utilisateur (§ 2.13).
|
|
*
|
|
* Collection (GET /api/providers) :
|
|
* - exclut par defaut les archives (is_archived = true) ET les soft-deletes
|
|
* (deleted_at IS NOT NULL) — RG-3.16 ;
|
|
* - ?includeArchived=true reintegre les archives (les soft-deletes restent
|
|
* exclus au M3) — RG-3.16 ;
|
|
* - tri par defaut companyName ASC — RG-3.16 ;
|
|
* - filtres ?search=... (fuzzy companyName + contacts lies : firstName /
|
|
* lastName / email), ?categoryCode=<code> (prestataires ayant >= 1 categorie
|
|
* de ce code, repetable) et ?siteId=<id> (prestataires rattaches a ce site
|
|
* via la relation DIRECTE provider.sites, repetable) ;
|
|
* - pagination obligatoire (regle ABSOLUE n°13) : Paginator ORM ; echappatoire
|
|
* ?pagination=false pour alimenter un <select> sans pagination.
|
|
*
|
|
* Cloisonnement par site (RG-3.17, § 2.13) — applique ICI (le QueryBuilder du
|
|
* repository ne connait pas l'user courant) :
|
|
* - si l'user N'A PAS `sites.bypass_scope` ET que CurrentSiteProvider::get()
|
|
* retourne un site -> la liste est restreinte aux prestataires dont
|
|
* provider.sites contient le currentSite (repository::applySiteScope), AVANT
|
|
* pagination : totalItems reflete le perimetre de l'user ;
|
|
* - le DETAIL (Get / provider de PATCH) d'un prestataire hors perimetre renvoie
|
|
* 404 (null) — ne pas reveler l'existence d'une ligne hors site ;
|
|
* - user `bypass_scope` (Admin auto, profils consolidation) -> aucun filtre ;
|
|
* - currentSite = null (module Sites off / user sans site) -> no-op lecture
|
|
* (aligne site-aware.md § 5).
|
|
*
|
|
* Item (GET /api/providers/{id} + provider de PATCH) :
|
|
* - 404 si introuvable OU soft-delete (deleted_at non null, jamais expose au
|
|
* M3) ; les archives restent consultables/restaurables en detail ;
|
|
* - 404 si hors perimetre site (cloisonnement, cf. ci-dessus).
|
|
*
|
|
* Le filtrage des champs comptables en lecture (groupe provider:read:accounting)
|
|
* n'est PAS fait ici mais dans ProviderReadGroupContextBuilder : un Provider
|
|
* retourne des donnees mais ne peut pas influencer les groupes de serialisation.
|
|
*
|
|
* @implements ProviderInterface<Provider>
|
|
*/
|
|
final class ProviderProvider implements ProviderInterface
|
|
{
|
|
public function __construct(
|
|
#[Autowire(service: 'App\Module\Technique\Infrastructure\Doctrine\DoctrineProviderRepository')]
|
|
private readonly ProviderRepositoryInterface $repository,
|
|
private readonly Pagination $pagination,
|
|
// Decision de cloisonnement par site centralisee (site-aware.md § 6.2) :
|
|
// source UNIQUE partagee avec le provider decore des sous-ressources
|
|
// (ProviderSubResourceItemProvider) et les processors d'ecriture, pour
|
|
// eviter tout drift entre ces points d'application.
|
|
private readonly ProviderSiteScopeChecker $scopeChecker,
|
|
) {}
|
|
|
|
public function provide(Operation $operation, array $uriVariables = [], array $context = []): iterable|Paginator|Provider|null
|
|
{
|
|
if ($operation instanceof CollectionOperationInterface) {
|
|
return $this->provideCollection($operation, $context);
|
|
}
|
|
|
|
return $this->provideItem($uriVariables);
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $context
|
|
*
|
|
* @return list<Provider>|Paginator<Provider>
|
|
*/
|
|
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=NETTOYAGE, selects)
|
|
// 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,
|
|
);
|
|
|
|
// Cloisonnement par site (RG-3.17) AVANT pagination : ajoute une clause
|
|
// restreignant au currentSite pour un user non-bypass. S'intersecte avec
|
|
// un eventuel filtre ?siteId du client (deux sous-requetes ANDees).
|
|
$scopeSite = $this->scopeChecker->siteScopeOrNull();
|
|
if (null !== $scopeSite) {
|
|
$this->repository->applySiteScope($qb, (int) $scopeSite->getId());
|
|
}
|
|
|
|
// Echappatoire ?pagination=false : collection complete sans Paginator
|
|
// (regle n°13 — utile pour un <select> cote front).
|
|
if (!$this->pagination->isEnabled($operation, $context)) {
|
|
/** @var list<Provider> $providers */
|
|
$providers = $qb->getQuery()->getResult();
|
|
// Hydratation batchee des collections affichees (§ 2.12) : evite le
|
|
// N+1 si la serialisation touche categories/sites, sans cartesien.
|
|
$this->repository->hydrateListCollections($providers);
|
|
|
|
return $providers;
|
|
}
|
|
|
|
$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 pas de fetch-join to-many (§ 2.12) : 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): ?Provider
|
|
{
|
|
$id = $uriVariables['id'] ?? null;
|
|
if (!is_int($id) && !(is_string($id) && ctype_digit($id))) {
|
|
return null;
|
|
}
|
|
|
|
$provider = $this->repository->findById((int) $id);
|
|
if (null === $provider) {
|
|
return null;
|
|
}
|
|
|
|
// Soft-delete : jamais expose au M3 (HP-M4) — 404 via retour null.
|
|
// Les archives restent visibles en detail (consultation + restauration).
|
|
if (null !== $provider->getDeletedAt()) {
|
|
return null;
|
|
}
|
|
|
|
// Cloisonnement par site (RG-3.17) : un prestataire hors du perimetre de
|
|
// l'user -> 404 (ne pas reveler son existence). No-op pour bypass_scope ou
|
|
// currentSite null (delegue au ProviderSiteScopeChecker).
|
|
if (!$this->scopeChecker->isInScope($provider)) {
|
|
return null;
|
|
}
|
|
|
|
return $provider;
|
|
}
|
|
|
|
/**
|
|
* 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;
|
|
}
|
|
}
|