36e947fd8e
Auto Tag Develop / tag (push) Successful in 8s
## ERP-187 (1.7) — Tests PHPUnit RG-5.01→5.10 + capture contrat JSON
Couvre les règles de gestion du M5 (tickets de pesée) par des tests PHPUnit et capture la **réponse JSON réelle** (DoD § 4.0.bis) collée dans `spec-back.md` avant les écrans front.
### Tests unitaires (Processor / Normalizer / Callback — sans BDD ni HTTP)
- **NetWeightTest** (RG-5.05) : net = plein − vide, `null` si une pesée manque, recalcul au PATCH.
- **CounterpartyValidationTest** (RG-5.03) : présence du champ requis par branche (propertyPath `client`/`supplier`/`otherLabel`) + exclusivité (null-ification hors-branche).
- **ImmatriculationNormalizationTest** (RG-5.01/5.10) : masque `XX-000-XX`, « Tout format », mapping 422 sur `immatriculation`.
### Tests fonctionnels (API réelle)
- **WeighingTicketNumberingTest** (RG-5.02/5.09) : format `{siteCode}-TP-{NNNN}`, séquence par site, isolation inter-sites, immuabilité numéro/site au PATCH.
- **WeighingTicketSerializationContractTest** (DoD § 4.0.bis) : 4 pièges verts (client embarqué, `plateFreeFormat` présent, `number` formaté, `netWeight` = full − empty) + dump JSON via `WEIGHING_TICKET_DOD_DUMP`.
- **WeighingTicketRBACMatrixTest** (§ 5.2) : admin/bureau/usine OK, compta/commerciale 403, anonyme 401.
> DSD / stub pont bascule / endpoint pesée déjà couverts (ERP-184/185).
### DoD
- `spec-back.md § 4.0.bis` : **JSON réel** (liste + détail) collé, 4 pièges marqués ✅ — feu vert front.
### Vérifications
- `make test` complet **vert** : 848 tests, 6302 assertions (0 échec ; deprecations/notices PHPUnit seuls).
- `make php-cs-fixer-allow-risky` : 0 correction.
Empilée sur ERP-186 (stack M5).
---------
Co-authored-by: Matthieu <contact@malio.fr>
Reviewed-on: #137
188 lines
7.1 KiB
PHP
188 lines
7.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Module\Logistique\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\Logistique\Domain\Entity\WeighingTicket;
|
|
use App\Module\Logistique\Domain\Repository\WeighingTicketRepositoryInterface;
|
|
use App\Module\Sites\Application\Service\CurrentSiteProviderInterface;
|
|
use App\Module\Sites\Domain\Entity\Site;
|
|
use Doctrine\ORM\QueryBuilder;
|
|
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator;
|
|
use Symfony\Bundle\SecurityBundle\Security;
|
|
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
|
|
|
/**
|
|
* Provider de lecture des tickets de pesee (M5). Cf. spec-back M5 § 4.0 / § 4.1 +
|
|
* RG-5.09. Jumeau du SupplierProvider (M2), augmente du cloisonnement par site.
|
|
*
|
|
* Collection (GET /api/weighing_tickets) :
|
|
* - exclut les soft-deletes (deleted_at IS NOT NULL, prepares mais non exposes au
|
|
* M5 — § 2.13), via le repository ;
|
|
* - filtre ?search=... (fuzzy sur number, nom client/fournisseur, other_label,
|
|
* immatriculation — § 4.1) ;
|
|
* - tri ?order[displayDate]=asc|desc (date du ticket = COALESCE full/empty),
|
|
* defaut number DESC (plus recents en tete) ;
|
|
* - pagination obligatoire (regle ABSOLUE n°13) : Paginator ORM ; echappatoire
|
|
* ?pagination=false ;
|
|
* - fetch-join client / supplier / site (ManyToOne surs) pour eviter le N+1 a la
|
|
* serialisation (§ 4.0).
|
|
*
|
|
* Cloisonnement par site (§ 2.3 / RG-5.09) — applique ICI : un provider custom
|
|
* REMPLACE le provider Doctrine, donc le SiteScopedQueryExtension ne s'execute pas
|
|
* automatiquement (il n'agit que dans le provider ORM standard). On replique sa
|
|
* logique a l'identique :
|
|
* - user `sites.bypass_scope` (Admin auto, consolidation) -> aucun filtre ;
|
|
* - site courant null (module Sites off / user sans site) -> no-op (l'user voit
|
|
* tout, decision site-aware.md § 5) ;
|
|
* - sinon -> liste restreinte aux tickets du site courant, AVANT pagination
|
|
* (totalItems reflete le perimetre).
|
|
*
|
|
* Item (GET /api/weighing_tickets/{id} + provider de PATCH) :
|
|
* - 404 si introuvable OU soft-delete (deleted_at non null) ;
|
|
* - 404 si hors perimetre site (ne pas reveler l'existence d'une ligne d'un autre
|
|
* site — anti-enumeration).
|
|
*
|
|
* @implements ProviderInterface<WeighingTicket>
|
|
*/
|
|
final class WeighingTicketProvider implements ProviderInterface
|
|
{
|
|
public function __construct(
|
|
#[Autowire(service: 'App\Module\Logistique\Infrastructure\Doctrine\DoctrineWeighingTicketRepository')]
|
|
private readonly WeighingTicketRepositoryInterface $repository,
|
|
private readonly Pagination $pagination,
|
|
private readonly CurrentSiteProviderInterface $currentSiteProvider,
|
|
private readonly Security $security,
|
|
) {}
|
|
|
|
public function provide(Operation $operation, array $uriVariables = [], array $context = []): iterable|Paginator|WeighingTicket|null
|
|
{
|
|
if ($operation instanceof CollectionOperationInterface) {
|
|
return $this->provideCollection($operation, $context);
|
|
}
|
|
|
|
return $this->provideItem($uriVariables);
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $context
|
|
*
|
|
* @return list<WeighingTicket>|Paginator<WeighingTicket>
|
|
*/
|
|
private function provideCollection(Operation $operation, array $context): array|Paginator
|
|
{
|
|
$filters = $context['filters'] ?? [];
|
|
$search = $filters['search'] ?? null;
|
|
|
|
$qb = $this->repository->createListQueryBuilder(is_string($search) ? $search : null);
|
|
|
|
$this->applyDisplayDateOrder($qb, $filters);
|
|
$this->applySiteScope($qb);
|
|
|
|
// Echappatoire ?pagination=false : collection complete sans Paginator
|
|
// (regle n°13 — utile pour alimenter un <select> cote front).
|
|
if (!$this->pagination->isEnabled($operation, $context)) {
|
|
// @var list<WeighingTicket> $tickets
|
|
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);
|
|
|
|
// Les fetch-joins du repository sont tous ManyToOne (client/supplier/site) :
|
|
// pas de demultiplication de lignes -> fetchJoinCollection: false (COUNT
|
|
// simple, page correcte).
|
|
return new Paginator(new DoctrinePaginator($qb->getQuery(), fetchJoinCollection: false));
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $uriVariables
|
|
*/
|
|
private function provideItem(array $uriVariables): ?WeighingTicket
|
|
{
|
|
$id = $uriVariables['id'] ?? null;
|
|
if (!is_int($id) && !(is_string($id) && ctype_digit($id))) {
|
|
return null;
|
|
}
|
|
|
|
$ticket = $this->repository->findById((int) $id);
|
|
if (null === $ticket) {
|
|
return null;
|
|
}
|
|
|
|
// Soft-delete : jamais expose au M5 (§ 2.13) -> 404 via retour null.
|
|
if (null !== $ticket->getDeletedAt()) {
|
|
return null;
|
|
}
|
|
|
|
// Cloisonnement par site : un ticket hors perimetre -> 404 (anti-enumeration).
|
|
$scopeSite = $this->currentScopeSite();
|
|
if (null !== $scopeSite && $ticket->getSite()?->getId() !== $scopeSite->getId()) {
|
|
return null;
|
|
}
|
|
|
|
return $ticket;
|
|
}
|
|
|
|
/**
|
|
* Tri par date du ticket (§ 4.1) : displayDate = full_date ?? empty_date, donc
|
|
* un getter calcule (pas une colonne) -> on trie sur l'expression DQL
|
|
* COALESCE(full_date, empty_date). Absent du payload -> on garde le tri par
|
|
* defaut du repository (number DESC).
|
|
*
|
|
* @param array<string, mixed> $filters
|
|
*/
|
|
private function applyDisplayDateOrder(QueryBuilder $qb, array $filters): void
|
|
{
|
|
$order = $filters['order'] ?? null;
|
|
if (!is_array($order) || !isset($order['displayDate'])) {
|
|
return;
|
|
}
|
|
|
|
$direction = 'asc' === strtolower((string) $order['displayDate']) ? 'ASC' : 'DESC';
|
|
$rootAlias = $qb->getRootAliases()[0];
|
|
|
|
$qb->orderBy(sprintf('COALESCE(%1$s.fullDate, %1$s.emptyDate)', $rootAlias), $direction);
|
|
}
|
|
|
|
/**
|
|
* Restreint la liste au site courant si l'user n'a pas le bypass et qu'un site
|
|
* est selectionne (cf. docblock de classe). No-op sinon.
|
|
*/
|
|
private function applySiteScope(QueryBuilder $qb): void
|
|
{
|
|
$scopeSite = $this->currentScopeSite();
|
|
if (null === $scopeSite) {
|
|
return;
|
|
}
|
|
|
|
$rootAlias = $qb->getRootAliases()[0];
|
|
$qb->andWhere(sprintf('%s.site = :scopeSite', $rootAlias))
|
|
->setParameter('scopeSite', $scopeSite)
|
|
;
|
|
}
|
|
|
|
/**
|
|
* Site servant a cloisonner, ou null si aucun cloisonnement ne s'applique
|
|
* (bypass_scope, ou pas de site courant). Replique les conditions de
|
|
* SiteScopedQueryExtension.
|
|
*/
|
|
private function currentScopeSite(): ?Site
|
|
{
|
|
if ($this->security->isGranted('sites.bypass_scope')) {
|
|
return null;
|
|
}
|
|
|
|
return $this->currentSiteProvider->get();
|
|
}
|
|
}
|