0ca1fb159a
Coeur API du repertoire prestataires (M3), jumeau du M2 fournisseurs : - ProviderProvider : liste paginee (Paginator ORM), filtres search/categoryCode/siteId/includeArchived, tri companyName ASC, exclusion archives + soft-deletes (RG-3.16). Cloisonnement par site pilote par l'utilisateur (RG-3.17 / § 2.13) : liste restreinte au currentSite avant pagination (totalItems = perimetre), detail hors perimetre -> 404, bypass via sites.bypass_scope. - ProviderProcessor : normalisation companyName (RG-3.11), POST formulaire principal (companyName + categories + sites), PATCH partiels par groupe en mode strict (RG-3.15, 403 sur tout le payload), archivage (RG-3.13/3.14), 409 doublon de nom (RG-3.10), garde d'ecriture cloisonnee des sites (RG-3.03/3.17, 422 sur sites pour les users sites.read_ref). - ProviderReadGroupContextBuilder : gating comptabilite par AJOUT du groupe provider:read:accounting si accounting.view (jamais par retrait). - ProviderFieldNormalizer : miroir SupplierFieldNormalizer. - ApiResource cable (provider + processor) sur l'entite Provider. Tests : ProviderApiTest, ProviderListTest, ProviderRbacGatingTest, ProviderSiteScopeTest (26 tests). Suite complete verte (612 tests).
257 lines
10 KiB
PHP
257 lines
10 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\Sites\Application\Service\CurrentSiteProviderInterface;
|
|
use App\Module\Technique\Domain\Entity\Provider;
|
|
use App\Module\Technique\Domain\Repository\ProviderRepositoryInterface;
|
|
use App\Shared\Domain\Contract\SiteInterface;
|
|
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator;
|
|
use Symfony\Bundle\SecurityBundle\Security;
|
|
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,
|
|
private readonly Security $security,
|
|
// Outillage site-aware sanctionne (site-aware.md § 6.2 : « injecter
|
|
// CurrentSiteProvider dans le service et ajouter la clause WHERE
|
|
// manuellement » pour les cas multi-site non couverts par
|
|
// SiteScopedQueryExtension). Type-hint sur l'interface pour le mock test.
|
|
private readonly CurrentSiteProviderInterface $currentSiteProvider,
|
|
) {}
|
|
|
|
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->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.
|
|
$scopeSite = $this->siteScopeOrNull();
|
|
if (null !== $scopeSite && !$this->providerHasSite($provider, (int) $scopeSite->getId())) {
|
|
return null;
|
|
}
|
|
|
|
return $provider;
|
|
}
|
|
|
|
/**
|
|
* Site de cloisonnement a appliquer en LECTURE, ou null si aucun cloisonnement
|
|
* (user `sites.bypass_scope`, ou pas de site courant resolu — module Sites off
|
|
* / user sans currentSite, aligne site-aware.md § 5).
|
|
*/
|
|
private function siteScopeOrNull(): ?SiteInterface
|
|
{
|
|
if ($this->security->isGranted('sites.bypass_scope')) {
|
|
return null;
|
|
}
|
|
|
|
return $this->currentSiteProvider->get();
|
|
}
|
|
|
|
/**
|
|
* Vrai si le prestataire est rattache (relation directe provider.sites) au
|
|
* site d'id donne. Comparaison en memoire sur l'entite deja chargee (detail).
|
|
*/
|
|
private function providerHasSite(Provider $provider, int $siteId): bool
|
|
{
|
|
foreach ($provider->getSites() as $site) {
|
|
if ($site instanceof SiteInterface && $site->getId() === $siteId) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* 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;
|
|
}
|
|
}
|