Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b580bb6576 | |||
| 3548224298 | |||
| 3838473876 |
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Application\Service;
|
||||
|
||||
/**
|
||||
* Normalisation serveur des champs texte d'un Supplier / SupplierContact,
|
||||
* appliquee par le SupplierProcessor (et les processors de sous-ressources,
|
||||
* ERP-88) AVANT persistance. Cf. spec-back M2 § 2.11 + RG-2.12. Jumeau de
|
||||
* ClientFieldNormalizer (M1) — duplique volontairement (isolation Client /
|
||||
* Fournisseur, decision § 2.1).
|
||||
*
|
||||
* - companyName : UPPERCASE integral (RG-2.12)
|
||||
* - firstName / lastName (personnes, sur SupplierContact) : Title Case (RG-2.12)
|
||||
* - phone* : chiffres uniquement, ex "06.12.34.56.78" -> "0612345678" (RG-2.12).
|
||||
* Le formatage d'affichage "XX XX XX XX XX" est de la responsabilite du front.
|
||||
* - email : lowercase integral (RG-2.12)
|
||||
*
|
||||
* Toutes les methodes sont null-safe et trim-ent l'entree ; une chaine vide
|
||||
* apres trim devient null (evite de persister "" dans des colonnes nullable).
|
||||
*/
|
||||
final class SupplierFieldNormalizer
|
||||
{
|
||||
/**
|
||||
* Nom de societe en majuscules (RG-2.12). Conserve null tel quel ; une
|
||||
* chaine non vide est trim + upper. Une chaine vide reste "" (champ
|
||||
* obligatoire : c'est l'Assert\NotBlank qui rejette, pas le normalizer).
|
||||
*/
|
||||
public function normalizeCompanyName(?string $value): ?string
|
||||
{
|
||||
if (null === $value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return mb_strtoupper(trim($value), 'UTF-8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Nom/prenom de personne en Title Case (RG-2.12) : "JEAN dupont" ->
|
||||
* "Jean Dupont". Une chaine vide apres trim devient null.
|
||||
*/
|
||||
public function normalizePersonName(?string $value): ?string
|
||||
{
|
||||
if (null === $value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$value = trim($value);
|
||||
|
||||
return '' === $value ? null : mb_convert_case($value, MB_CASE_TITLE, 'UTF-8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Email en minuscules (RG-2.12). Une chaine vide apres trim devient null.
|
||||
*/
|
||||
public function normalizeEmail(?string $value): ?string
|
||||
{
|
||||
if (null === $value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$value = trim($value);
|
||||
|
||||
return '' === $value ? null : mb_strtolower($value, 'UTF-8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Telephone reduit aux chiffres (RG-2.12) : "06.12.34.56.78" ->
|
||||
* "0612345678". Une valeur sans aucun chiffre devient null.
|
||||
*/
|
||||
public function normalizePhone(?string $value): ?string
|
||||
{
|
||||
if (null === $value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$digits = preg_replace('/\D+/', '', $value) ?? '';
|
||||
|
||||
return '' === $digits ? null : $digits;
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Application\Validator;
|
||||
|
||||
use ApiPlatform\Validator\Exception\ValidationException;
|
||||
use App\Module\Commercial\Domain\Entity\Supplier;
|
||||
use Symfony\Component\Validator\ConstraintViolation;
|
||||
use Symfony\Component\Validator\ConstraintViolationList;
|
||||
|
||||
/**
|
||||
* Validator metier RG-2.03 (jumeau du ClientInformationCompletenessValidator M1) :
|
||||
* pour un utilisateur portant le role metier Commerciale, TOUS les champs de
|
||||
* l'onglet Information sont obligatoires sur POST comme sur tout PATCH,
|
||||
* independamment des champs reellement envoyes.
|
||||
*
|
||||
* Invoque par le SupplierProcessor des que l'utilisateur courant porte le role
|
||||
* Commerciale (detection du role cote back). Pour les autres roles, ces champs
|
||||
* restent optionnels — le validator n'est pas appele.
|
||||
*
|
||||
* NEW vs Client : ajoute le champ `volumeForecast` (volume previsionnel),
|
||||
* specifique fournisseur.
|
||||
*
|
||||
* Leve une ValidationException (HTTP 422) listant chaque champ manquant, chaque
|
||||
* violation portant son propertyPath (consommable par extractApiViolations,
|
||||
* ERP-101), par coherence avec les violations Symfony rendues par API Platform.
|
||||
*/
|
||||
final class SupplierInformationCompletenessValidator
|
||||
{
|
||||
public function validate(Supplier $supplier): void
|
||||
{
|
||||
// Map champ -> valeur courante de l'onglet Information.
|
||||
$fields = [
|
||||
'description' => $supplier->getDescription(),
|
||||
'competitors' => $supplier->getCompetitors(),
|
||||
'foundedAt' => $supplier->getFoundedAt(),
|
||||
'employeesCount' => $supplier->getEmployeesCount(),
|
||||
'revenueAmount' => $supplier->getRevenueAmount(),
|
||||
'directorName' => $supplier->getDirectorName(),
|
||||
'profitAmount' => $supplier->getProfitAmount(),
|
||||
'volumeForecast' => $supplier->getVolumeForecast(),
|
||||
];
|
||||
|
||||
$violations = new ConstraintViolationList();
|
||||
|
||||
foreach ($fields as $property => $value) {
|
||||
if ($this->isMissing($value)) {
|
||||
$violations->add(new ConstraintViolation(
|
||||
sprintf('Ce champ est obligatoire pour le rôle Commerciale (champ "%s").', $property),
|
||||
null,
|
||||
[],
|
||||
$supplier,
|
||||
$property,
|
||||
$value,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (count($violations) > 0) {
|
||||
throw new ValidationException($violations);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Une valeur est manquante si null ou, pour une chaine, vide apres trim. Les
|
||||
* zeros numeriques (employeesCount = 0, profitAmount = "0.00",
|
||||
* volumeForecast = 0) sont des valeurs valides : on ne les considere pas
|
||||
* manquants.
|
||||
*/
|
||||
private function isMissing(mixed $value): bool
|
||||
{
|
||||
if (null === $value) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return is_string($value) && '' === trim($value);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,13 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Domain\Entity;
|
||||
|
||||
use ApiPlatform\Metadata\ApiResource;
|
||||
use ApiPlatform\Metadata\Get;
|
||||
use ApiPlatform\Metadata\GetCollection;
|
||||
use ApiPlatform\Metadata\Patch;
|
||||
use ApiPlatform\Metadata\Post;
|
||||
use App\Module\Commercial\Infrastructure\ApiPlatform\State\Processor\SupplierProcessor;
|
||||
use App\Module\Commercial\Infrastructure\ApiPlatform\State\Provider\SupplierProvider;
|
||||
use App\Module\Commercial\Infrastructure\Doctrine\DoctrineSupplierRepository;
|
||||
use App\Shared\Domain\Attribute\Auditable;
|
||||
use App\Shared\Domain\Contract\BlamableInterface;
|
||||
@@ -18,6 +25,7 @@ use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
use Symfony\Component\Serializer\Attribute\SerializedName;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
|
||||
/**
|
||||
* Fournisseur (M2 Commercial) — entite racine du repertoire fournisseurs,
|
||||
@@ -44,10 +52,73 @@ use Symfony\Component\Validator\Constraints as Assert;
|
||||
* CategoryInterface + resolve_target_entities (regle n°1, pas d'import direct).
|
||||
*
|
||||
* Contrat de serialisation (RETEX M1, 3 maillons — spec § 4.0) : les read-groups
|
||||
* sont poses ICI (source unique). L'#[ApiResource] et le SupplierProvider /
|
||||
* SupplierProcessor (gating accounting, archivage, mode strict) sont branches au
|
||||
* ticket suivant (ERP-87).
|
||||
* sont poses ICI (source unique). L'#[ApiResource] (operations + contextes), le
|
||||
* SupplierProvider (liste paginee, exclusion archives, item 404 soft-delete), le
|
||||
* SupplierProcessor (normalisation, archivage, gating accounting/manage en mode
|
||||
* strict, 409 doublon) et le SupplierReadGroupContextBuilder (ajout conditionnel
|
||||
* du groupe supplier:read:accounting selon accounting.view) sont branches ICI
|
||||
* (ERP-87).
|
||||
*/
|
||||
#[ApiResource(
|
||||
operations: [
|
||||
new GetCollection(
|
||||
security: "is_granted('commercial.suppliers.view')",
|
||||
// La liste embarque les categories (avec leur code/name, groupe
|
||||
// category:read) et les sites agreges des adresses (groupe
|
||||
// site:read) pour alimenter les colonnes « Catégories » et
|
||||
// « Site(s) » du Repertoire (cohérence M1/ERP-62, § 2.12). Cf.
|
||||
// getSites(). Fetch-joins/hydratation deleguee au repository (N+1).
|
||||
normalizationContext: ['groups' => ['supplier:read', 'default:read', 'category:read', 'site:read']],
|
||||
provider: SupplierProvider::class,
|
||||
),
|
||||
new Get(
|
||||
security: "is_granted('commercial.suppliers.view')",
|
||||
// Detail : fournisseur + sous-collections embarquees (contacts /
|
||||
// adresses + leurs sites/categories/contacts).
|
||||
// - supplier:read:accounting est ajoute par SupplierReadGroupContextBuilder
|
||||
// selon la permission (gate les scalaires comptables ET les RIB
|
||||
// embarques), donc volontairement ABSENT ici (parade bug #4 M1).
|
||||
// - category:read / site:read indispensables pour embarquer le
|
||||
// code/name des categories et le name/postalCode des sites (sinon
|
||||
// stub IRI nu — bugs #1/#2 M1).
|
||||
normalizationContext: ['groups' => [
|
||||
'supplier:read',
|
||||
'supplier:item:read',
|
||||
'category:read',
|
||||
'site:read',
|
||||
'default:read',
|
||||
]],
|
||||
provider: SupplierProvider::class,
|
||||
),
|
||||
new Post(
|
||||
security: "is_granted('commercial.suppliers.manage')",
|
||||
normalizationContext: ['groups' => ['supplier:read', 'default:read', 'category:read', 'site:read']],
|
||||
denormalizationContext: ['groups' => ['supplier:write:main']],
|
||||
processor: SupplierProcessor::class,
|
||||
),
|
||||
new Patch(
|
||||
// Security elargie : `manage` OU `accounting.manage`. Le role Compta
|
||||
// n'a pas `manage` mais doit pouvoir editer l'onglet Comptabilite
|
||||
// d'un fournisseur existant (§ 2.9). Le SupplierProcessor re-gate
|
||||
// ensuite onglet par onglet (mode strict RG-2.16) :
|
||||
// - champs accounting -> accounting.manage (guardAccounting) ;
|
||||
// - champs main/information -> manage (guardManage : empeche Compta
|
||||
// d'editer les autres onglets) ;
|
||||
// - isArchived -> archive (guardArchive, RG-2.14).
|
||||
security: "is_granted('commercial.suppliers.manage') or is_granted('commercial.suppliers.accounting.manage')",
|
||||
normalizationContext: ['groups' => ['supplier:read', 'default:read', 'category:read', 'site:read']],
|
||||
denormalizationContext: ['groups' => [
|
||||
'supplier:write:main',
|
||||
'supplier:write:information',
|
||||
'supplier:write:accounting',
|
||||
'supplier:write:archive',
|
||||
]],
|
||||
provider: SupplierProvider::class,
|
||||
processor: SupplierProcessor::class,
|
||||
),
|
||||
// Pas de Delete au M2 (HP-M3-1). Archivage via PATCH { isArchived: true }.
|
||||
],
|
||||
)]
|
||||
#[ORM\Entity(repositoryClass: DoctrineSupplierRepository::class)]
|
||||
#[ORM\Table(name: 'supplier')]
|
||||
// Index nommes pour matcher la migration (Version20260605130000). L'index unique
|
||||
@@ -63,6 +134,20 @@ class Supplier implements TimestampableInterface, BlamableInterface
|
||||
{
|
||||
use TimestampableBlamableTrait;
|
||||
|
||||
/**
|
||||
* RG-2.10 : seules les categories de ce type sont autorisees sur le
|
||||
* fournisseur (entite principale). Miroir de SupplierAddress (ERP-88).
|
||||
* S'appuie sur CategoryInterface::getCategoryTypeCode() (pas d'import du
|
||||
* module Catalog — regle ABSOLUE n°1).
|
||||
*/
|
||||
private const string REQUIRED_CATEGORY_TYPE_CODE = 'FOURNISSEUR';
|
||||
|
||||
/** RG-2.07 : code du type de reglement imposant une banque. */
|
||||
private const string PAYMENT_TYPE_VIREMENT = 'VIREMENT';
|
||||
|
||||
/** RG-2.08 : code du type de reglement imposant au moins un RIB. */
|
||||
private const string PAYMENT_TYPE_LCR = 'LCR';
|
||||
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column]
|
||||
@@ -130,7 +215,8 @@ class Supplier implements TimestampableInterface, BlamableInterface
|
||||
|
||||
// === Onglet Comptabilite ===
|
||||
// Lecture conditionnee via le groupe `supplier:read:accounting` (ajoute au
|
||||
// contexte par le SupplierProvider si l'user a accounting.view, ERP-87).
|
||||
// contexte par le SupplierReadGroupContextBuilder si l'user a accounting.view,
|
||||
// ERP-87 — un Provider ne peut pas influencer les groupes de serialisation).
|
||||
// Ecriture via `supplier:write:accounting` (le Processor exige accounting.manage).
|
||||
#[ORM\Column(length: 20, nullable: true)]
|
||||
#[Assert\Length(max: 20, maxMessage: 'Le SIREN ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
@@ -209,6 +295,65 @@ class Supplier implements TimestampableInterface, BlamableInterface
|
||||
$this->ribs = new ArrayCollection();
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-2.10 : toute categorie posee sur le fournisseur doit etre de type
|
||||
* FOURNISSEUR -> sinon 422 avec violation sur le champ `categories`
|
||||
* (propertyPath aligne ERP-101, message FR ERP-107). Miroir de
|
||||
* SupplierAddress::validateCategoryType (ERP-88). S'appuie sur
|
||||
* CategoryInterface::getCategoryTypeCode() (pas d'import du module Catalog —
|
||||
* regle ABSOLUE n°1). Joue avant la base via la validation API Platform, sur
|
||||
* POST (categories ∈ supplier:write:main) comme sur PATCH.
|
||||
*/
|
||||
#[Assert\Callback]
|
||||
public function validateCategoryType(ExecutionContextInterface $context): void
|
||||
{
|
||||
foreach ($this->categories as $category) {
|
||||
if ($category instanceof CategoryInterface
|
||||
&& self::REQUIRED_CATEGORY_TYPE_CODE !== $category->getCategoryTypeCode()) {
|
||||
$context->buildViolation('Type de catégorie non autorisé (FOURNISSEUR attendu).')
|
||||
->atPath('categories')
|
||||
->addViolation()
|
||||
;
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-2.07 / RG-2.08 : coherence du type de reglement comptable. Decision
|
||||
* figee ERP-89 : ces RG inter-champs passent par une contrainte d'entite
|
||||
* (Assert\Callback + ->atPath()) et NON par le SupplierProcessor, afin que
|
||||
* chaque 422 porte un propertyPath exploitable par extractApiViolations
|
||||
* (mapping inline sous le champ, pas un toast — convention ERP-101).
|
||||
* - RG-2.07 : paymentType = VIREMENT impose une banque -> violation sur `bank`.
|
||||
* - RG-2.08 : paymentType = LCR impose au moins un RIB -> violation sur `ribs`
|
||||
* (le 409 sur DELETE du dernier RIB en LCR est porte par ERP-88).
|
||||
*
|
||||
* Ces champs vivant dans le groupe d'ecriture comptable (absent du POST, qui
|
||||
* n'expose que supplier:write:main), la contrainte ne mord en pratique que
|
||||
* sur le PATCH de l'onglet Comptabilite.
|
||||
*/
|
||||
#[Assert\Callback]
|
||||
public function validatePaymentTypeConsistency(ExecutionContextInterface $context): void
|
||||
{
|
||||
$paymentCode = $this->paymentType?->getCode();
|
||||
|
||||
if (self::PAYMENT_TYPE_VIREMENT === $paymentCode && null === $this->bank) {
|
||||
$context->buildViolation('La banque est obligatoire pour le type de règlement Virement.')
|
||||
->atPath('bank')
|
||||
->addViolation()
|
||||
;
|
||||
}
|
||||
|
||||
if (self::PAYMENT_TYPE_LCR === $paymentCode && $this->ribs->isEmpty()) {
|
||||
$context->buildViolation('Au moins un RIB est obligatoire pour le type de règlement LCR.')
|
||||
->atPath('ribs')
|
||||
->addViolation()
|
||||
;
|
||||
}
|
||||
}
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
@@ -510,7 +655,7 @@ class Supplier implements TimestampableInterface, BlamableInterface
|
||||
|
||||
// Embed gate sur le groupe COMPTABLE (et non supplier:item:read comme contacts/
|
||||
// adresses) : supplier:read:accounting n'est ajoute au contexte que si l'user a
|
||||
// accounting.view (SupplierProvider, ERP-87). Resultat : la cle `ribs` est
|
||||
// accounting.view (SupplierReadGroupContextBuilder, ERP-87). Resultat : la cle `ribs` est
|
||||
// TOTALEMENT ABSENTE du detail pour un user sans accounting.view (ex. Commerciale),
|
||||
// au meme titre que les scalaires comptables — evite la fuite IBAN/BIC (piege n°4 M1).
|
||||
/** @return Collection<int, SupplierRib> */
|
||||
|
||||
@@ -4,6 +4,13 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Domain\Entity;
|
||||
|
||||
use ApiPlatform\Metadata\ApiResource;
|
||||
use ApiPlatform\Metadata\Delete;
|
||||
use ApiPlatform\Metadata\Get;
|
||||
use ApiPlatform\Metadata\Link;
|
||||
use ApiPlatform\Metadata\Patch;
|
||||
use ApiPlatform\Metadata\Post;
|
||||
use App\Module\Commercial\Infrastructure\ApiPlatform\State\Processor\SupplierAddressProcessor;
|
||||
use App\Module\Commercial\Infrastructure\Doctrine\DoctrineSupplierAddressRepository;
|
||||
use App\Shared\Domain\Attribute\Auditable;
|
||||
use App\Shared\Domain\Contract\BlamableInterface;
|
||||
@@ -17,6 +24,7 @@ use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
use Symfony\Component\Serializer\Attribute\SerializedName;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
|
||||
/**
|
||||
* Adresse d'un fournisseur (1:n) — onglet Adresse. Le type d'adresse est un enum
|
||||
@@ -30,14 +38,60 @@ use Symfony\Component\Validator\Constraints as Assert;
|
||||
* un site obligatoire (RG-2.06, Assert\Count). Site n'a pas de `code`.
|
||||
* - contacts : SupplierContact (meme module).
|
||||
* - categories : CategoryInterface (module Catalog) via resolve_target_entities —
|
||||
* type FOURNISSEUR attendu (RG-2.10, controle au Processor/Validator ERP-89).
|
||||
* type FOURNISSEUR attendu (RG-2.10, Assert\Callback validateCategoryType).
|
||||
*
|
||||
* Embarquee sous `supplier.addresses` au detail (groupe supplier:item:read,
|
||||
* maillon (a)). Edition via la sous-ressource (POST /api/suppliers/{id}/addresses,
|
||||
* PATCH/DELETE /api/supplier_addresses/{id}), branchee a ERP-88.
|
||||
* maillon (a)).
|
||||
*
|
||||
* Sous-ressource API (ERP-88, spec § 4.5) :
|
||||
* - POST /api/suppliers/{supplierId}/addresses : creation rattachee au
|
||||
* fournisseur parent (Link toProperty 'supplier'), security
|
||||
* commercial.suppliers.manage.
|
||||
* - PATCH / DELETE /api/supplier_addresses/{id} : security
|
||||
* commercial.suppliers.manage.
|
||||
* - GET /api/supplier_addresses/{id} : lecture unitaire (security view) — la
|
||||
* lecture courante reste via le parent. Pas de GET collection autonome.
|
||||
* Tout passe par le SupplierAddressProcessor (rattachement parent). Les regles
|
||||
* RG-2.05/2.06/2.09/2.10 sont portees par les contraintes de l'entite (jouees
|
||||
* avant le processor).
|
||||
*
|
||||
* Audite (#[Auditable]) + Timestampable / Blamable.
|
||||
*/
|
||||
#[ApiResource(
|
||||
operations: [
|
||||
new Get(
|
||||
security: "is_granted('commercial.suppliers.view')",
|
||||
// site:read + category:read : embarquent les Site / Category lies
|
||||
// (maillon (c)) plutot que des IRI nus dans le retour.
|
||||
normalizationContext: ['groups' => ['supplier:item:read', 'site:read', 'category:read', 'default:read']],
|
||||
),
|
||||
new Post(
|
||||
uriTemplate: '/suppliers/{supplierId}/addresses',
|
||||
uriVariables: [
|
||||
'supplierId' => new Link(fromClass: Supplier::class, toProperty: 'supplier'),
|
||||
],
|
||||
// read:false : pas de stade lecture du parent. Le Link toProperty
|
||||
// resoudrait l'enfant (SELECT SupplierAddress ... WHERE supplier = :id)
|
||||
// et casse en NonUniqueResult des >= 2 enfants. Le parent est rattache
|
||||
// manuellement par SupplierAddressProcessor::linkParent (404 si absent).
|
||||
read: false,
|
||||
security: "is_granted('commercial.suppliers.manage')",
|
||||
normalizationContext: ['groups' => ['supplier:item:read', 'site:read', 'category:read', 'default:read']],
|
||||
denormalizationContext: ['groups' => ['supplier:write:addresses']],
|
||||
processor: SupplierAddressProcessor::class,
|
||||
),
|
||||
new Patch(
|
||||
security: "is_granted('commercial.suppliers.manage')",
|
||||
normalizationContext: ['groups' => ['supplier:item:read', 'site:read', 'category:read', 'default:read']],
|
||||
denormalizationContext: ['groups' => ['supplier:write:addresses']],
|
||||
processor: SupplierAddressProcessor::class,
|
||||
),
|
||||
new Delete(
|
||||
security: "is_granted('commercial.suppliers.manage')",
|
||||
processor: SupplierAddressProcessor::class,
|
||||
),
|
||||
],
|
||||
)]
|
||||
#[ORM\Entity(repositoryClass: DoctrineSupplierAddressRepository::class)]
|
||||
#[ORM\Table(name: 'supplier_address')]
|
||||
#[ORM\Index(name: 'idx_supplier_address_supplier', columns: ['supplier_id'])]
|
||||
@@ -53,6 +107,13 @@ class SupplierAddress implements TimestampableInterface, BlamableInterface
|
||||
*/
|
||||
public const array ADDRESS_TYPES = ['PROSPECT', 'DEPART', 'RENDU'];
|
||||
|
||||
/**
|
||||
* RG-2.10 : seules les categories de ce type sont autorisees sur une adresse
|
||||
* fournisseur. S'appuie sur CategoryInterface::getCategoryTypeCode() (pas
|
||||
* d'import du module Catalog — regle ABSOLUE n°1).
|
||||
*/
|
||||
private const string REQUIRED_CATEGORY_TYPE_CODE = 'FOURNISSEUR';
|
||||
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column]
|
||||
@@ -154,6 +215,29 @@ class SupplierAddress implements TimestampableInterface, BlamableInterface
|
||||
$this->categories = new ArrayCollection();
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-2.10 : toute categorie posee sur une adresse fournisseur doit etre de
|
||||
* type FOURNISSEUR -> sinon 422 avec violation sur le champ `categories`
|
||||
* (propertyPath aligne ERP-101, message FR ERP-107). S'appuie sur
|
||||
* CategoryInterface::getCategoryTypeCode() (pas d'import du module Catalog —
|
||||
* regle ABSOLUE n°1). Joue avant la base via la validation API Platform.
|
||||
*/
|
||||
#[Assert\Callback]
|
||||
public function validateCategoryType(ExecutionContextInterface $context): void
|
||||
{
|
||||
foreach ($this->categories as $category) {
|
||||
if ($category instanceof CategoryInterface
|
||||
&& self::REQUIRED_CATEGORY_TYPE_CODE !== $category->getCategoryTypeCode()) {
|
||||
$context->buildViolation('Type de catégorie non autorisé (FOURNISSEUR attendu).')
|
||||
->atPath('categories')
|
||||
->addViolation()
|
||||
;
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
|
||||
@@ -4,6 +4,13 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Domain\Entity;
|
||||
|
||||
use ApiPlatform\Metadata\ApiResource;
|
||||
use ApiPlatform\Metadata\Delete;
|
||||
use ApiPlatform\Metadata\Get;
|
||||
use ApiPlatform\Metadata\Link;
|
||||
use ApiPlatform\Metadata\Patch;
|
||||
use ApiPlatform\Metadata\Post;
|
||||
use App\Module\Commercial\Infrastructure\ApiPlatform\State\Processor\SupplierContactProcessor;
|
||||
use App\Module\Commercial\Infrastructure\Doctrine\DoctrineSupplierContactRepository;
|
||||
use App\Shared\Domain\Attribute\Auditable;
|
||||
use App\Shared\Domain\Contract\BlamableInterface;
|
||||
@@ -20,12 +27,56 @@ use Symfony\Component\Validator\Constraints as Assert;
|
||||
* permissive (les deux champs sont nullable).
|
||||
*
|
||||
* Embarque sous `supplier.contacts` au detail (groupe supplier:item:read,
|
||||
* maillon (a) du contrat de serialisation). Edition via la sous-ressource
|
||||
* (POST /api/suppliers/{id}/contacts, PATCH/DELETE /api/supplier_contacts/{id}),
|
||||
* branchee a ERP-88 (l'#[ApiResource] sera ajoute alors).
|
||||
* maillon (a) du contrat de serialisation).
|
||||
*
|
||||
* Sous-ressource API (ERP-88, spec § 4.5) :
|
||||
* - POST /api/suppliers/{supplierId}/contacts : creation rattachee au
|
||||
* fournisseur parent (Link toProperty 'supplier'), security
|
||||
* commercial.suppliers.manage.
|
||||
* - PATCH / DELETE /api/supplier_contacts/{id} : security
|
||||
* commercial.suppliers.manage. Le DELETE est physique et libre (pas de garde
|
||||
* « dernier contact » au M2 — RG-2.13 front-driven, la collection peut rester
|
||||
* vide cote back).
|
||||
* - GET /api/supplier_contacts/{id} : lecture unitaire (security view) — la
|
||||
* lecture courante reste via le parent (le fournisseur embarque ses contacts).
|
||||
* Pas de GET collection autonome.
|
||||
* Tout passe par le SupplierContactProcessor (normalisation RG-2.12, RG-2.04).
|
||||
*
|
||||
* Audite (#[Auditable]) + Timestampable / Blamable (pattern Shared standard).
|
||||
*/
|
||||
#[ApiResource(
|
||||
operations: [
|
||||
new Get(
|
||||
security: "is_granted('commercial.suppliers.view')",
|
||||
normalizationContext: ['groups' => ['supplier:item:read']],
|
||||
),
|
||||
new Post(
|
||||
uriTemplate: '/suppliers/{supplierId}/contacts',
|
||||
uriVariables: [
|
||||
'supplierId' => new Link(fromClass: Supplier::class, toProperty: 'supplier'),
|
||||
],
|
||||
// read:false : pas de stade lecture du parent. Le Link toProperty
|
||||
// resoudrait l'enfant (SELECT SupplierContact ... WHERE supplier = :id)
|
||||
// et casse en NonUniqueResult des >= 2 enfants. Le parent est rattache
|
||||
// manuellement par SupplierContactProcessor::linkParent (404 si absent).
|
||||
read: false,
|
||||
security: "is_granted('commercial.suppliers.manage')",
|
||||
normalizationContext: ['groups' => ['supplier:item:read']],
|
||||
denormalizationContext: ['groups' => ['supplier:write:contacts']],
|
||||
processor: SupplierContactProcessor::class,
|
||||
),
|
||||
new Patch(
|
||||
security: "is_granted('commercial.suppliers.manage')",
|
||||
normalizationContext: ['groups' => ['supplier:item:read']],
|
||||
denormalizationContext: ['groups' => ['supplier:write:contacts']],
|
||||
processor: SupplierContactProcessor::class,
|
||||
),
|
||||
new Delete(
|
||||
security: "is_granted('commercial.suppliers.manage')",
|
||||
processor: SupplierContactProcessor::class,
|
||||
),
|
||||
],
|
||||
)]
|
||||
#[ORM\Entity(repositoryClass: DoctrineSupplierContactRepository::class)]
|
||||
#[ORM\Table(name: 'supplier_contact')]
|
||||
#[ORM\Index(name: 'idx_supplier_contact_supplier', columns: ['supplier_id'])]
|
||||
|
||||
@@ -4,6 +4,13 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Domain\Entity;
|
||||
|
||||
use ApiPlatform\Metadata\ApiResource;
|
||||
use ApiPlatform\Metadata\Delete;
|
||||
use ApiPlatform\Metadata\Get;
|
||||
use ApiPlatform\Metadata\Link;
|
||||
use ApiPlatform\Metadata\Patch;
|
||||
use ApiPlatform\Metadata\Post;
|
||||
use App\Module\Commercial\Infrastructure\ApiPlatform\State\Processor\SupplierRibProcessor;
|
||||
use App\Module\Commercial\Infrastructure\Doctrine\DoctrineSupplierRibRepository;
|
||||
use App\Shared\Domain\Attribute\Auditable;
|
||||
use App\Shared\Domain\Contract\BlamableInterface;
|
||||
@@ -24,9 +31,54 @@ use Symfony\Component\Validator\Constraints as Assert;
|
||||
* piege n°4 du M1). Aucun #[AuditIgnore] sur iban/bic : l'audit etant admin-only,
|
||||
* la tracabilite RIB est conservee (decision M1 reportee, § 2.7).
|
||||
*
|
||||
* Sous-ressource API (ERP-88, spec § 4.5) — gating comptable renforce :
|
||||
* - POST /api/suppliers/{supplierId}/ribs : creation rattachee au fournisseur
|
||||
* parent (Link toProperty 'supplier'), security
|
||||
* commercial.suppliers.accounting.manage.
|
||||
* - PATCH / DELETE /api/supplier_ribs/{id} : security
|
||||
* commercial.suppliers.accounting.manage. Le DELETE refuse la suppression du
|
||||
* dernier RIB sous LCR (RG-2.08, 409).
|
||||
* - GET /api/supplier_ribs/{id} : lecture unitaire, security
|
||||
* commercial.suppliers.accounting.view (donnees bancaires sensibles). Pas de
|
||||
* GET collection autonome.
|
||||
* Tout passe par le SupplierRibProcessor (RG-2.08 sur DELETE).
|
||||
*
|
||||
* Validation IBAN/BIC : Assert\Iban + Assert\Bic standard Symfony (pas de controle
|
||||
* banque reelle). Audite (#[Auditable]) + Timestampable / Blamable.
|
||||
*/
|
||||
#[ApiResource(
|
||||
operations: [
|
||||
new Get(
|
||||
security: "is_granted('commercial.suppliers.accounting.view')",
|
||||
normalizationContext: ['groups' => ['supplier:read:accounting']],
|
||||
),
|
||||
new Post(
|
||||
uriTemplate: '/suppliers/{supplierId}/ribs',
|
||||
uriVariables: [
|
||||
'supplierId' => new Link(fromClass: Supplier::class, toProperty: 'supplier'),
|
||||
],
|
||||
// read:false : pas de stade lecture du parent. Le Link toProperty
|
||||
// resoudrait l'enfant (SELECT SupplierRib ... WHERE supplier = :id) et
|
||||
// casse en NonUniqueResult des >= 2 enfants. Le parent est rattache
|
||||
// manuellement par SupplierRibProcessor::linkParent (404 si absent).
|
||||
read: false,
|
||||
security: "is_granted('commercial.suppliers.accounting.manage')",
|
||||
normalizationContext: ['groups' => ['supplier:read:accounting']],
|
||||
denormalizationContext: ['groups' => ['supplier:write:accounting']],
|
||||
processor: SupplierRibProcessor::class,
|
||||
),
|
||||
new Patch(
|
||||
security: "is_granted('commercial.suppliers.accounting.manage')",
|
||||
normalizationContext: ['groups' => ['supplier:read:accounting']],
|
||||
denormalizationContext: ['groups' => ['supplier:write:accounting']],
|
||||
processor: SupplierRibProcessor::class,
|
||||
),
|
||||
new Delete(
|
||||
security: "is_granted('commercial.suppliers.accounting.manage')",
|
||||
processor: SupplierRibProcessor::class,
|
||||
),
|
||||
],
|
||||
)]
|
||||
#[ORM\Entity(repositoryClass: DoctrineSupplierRibRepository::class)]
|
||||
#[ORM\Table(name: 'supplier_rib')]
|
||||
#[ORM\Index(name: 'idx_supplier_rib_supplier', columns: ['supplier_id'])]
|
||||
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Infrastructure\ApiPlatform\Serializer;
|
||||
|
||||
use ApiPlatform\State\SerializerContextBuilderInterface;
|
||||
use App\Module\Commercial\Domain\Entity\Supplier;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
|
||||
use Symfony\Component\DependencyInjection\Attribute\AutowireDecorated;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
|
||||
/**
|
||||
* Decore le context builder de serialisation d'API Platform pour ajouter
|
||||
* DYNAMIQUEMENT le groupe de lecture `supplier:read:accounting` sur les
|
||||
* ressources Supplier, uniquement si l'utilisateur courant a la permission
|
||||
* `commercial.suppliers.accounting.view` (cf. spec-back M2 § 2.9 / § 4.1 /
|
||||
* § 4.2). Jumeau de ClientReadGroupContextBuilder (M1).
|
||||
*
|
||||
* Pourquoi un context builder et pas le Provider : un Provider retourne des
|
||||
* donnees mais ne peut pas influencer les groupes de serialisation. Le contexte
|
||||
* de normalisation est construit ici, en amont du serializer — c'est le point
|
||||
* d'extension idiomatique d'API Platform pour conditionner un groupe selon
|
||||
* l'utilisateur. Realise l'intention « gating du groupe accounting » de la spec
|
||||
* (le groupe n'est jamais pose par defaut sur l'operation : il est AJOUTE ici si
|
||||
* la permission est presente — resultat identique au « retrait » decrit en spec).
|
||||
*
|
||||
* S'applique aux operations de LECTURE (normalization) sur Supplier : liste ET
|
||||
* detail. Sans la permission, les champs comptables (siren, accountNumber,
|
||||
* tvaMode, nTva, paymentDelay, paymentType, bank) ET les RIB embarques (groupe
|
||||
* supplier:read:accounting porte par getRibs()) ne sont jamais serialises — la
|
||||
* cle est totalement absente du JSON (gating par omission, parade bug #4 M1).
|
||||
*
|
||||
* Priorite de decoration -10 : on s'empile APRES ClientReadGroupContextBuilder
|
||||
* (priorite par defaut 0) sur le meme service `api_platform.serializer.context_builder`.
|
||||
* Les deux decorateurs passent la main pour toute ressource autre que la leur :
|
||||
* l'ordre de chainage n'a donc aucun effet fonctionnel, la priorite explicite ne
|
||||
* sert qu'a lever l'ambiguite de deux decorateurs sur un meme service.
|
||||
*/
|
||||
#[AsDecorator(decorates: 'api_platform.serializer.context_builder', priority: -10)]
|
||||
final readonly class SupplierReadGroupContextBuilder implements SerializerContextBuilderInterface
|
||||
{
|
||||
public function __construct(
|
||||
#[AutowireDecorated]
|
||||
private SerializerContextBuilderInterface $decorated,
|
||||
private Security $security,
|
||||
) {}
|
||||
|
||||
public function createFromRequest(Request $request, bool $normalization, ?array $extractedAttributes = null): array
|
||||
{
|
||||
$context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);
|
||||
|
||||
// Uniquement en lecture, sur la ressource Supplier, avec la permission.
|
||||
if (!$normalization) {
|
||||
return $context;
|
||||
}
|
||||
|
||||
if (Supplier::class !== ($context['resource_class'] ?? null)) {
|
||||
return $context;
|
||||
}
|
||||
|
||||
if (!$this->security->isGranted('commercial.suppliers.accounting.view')) {
|
||||
return $context;
|
||||
}
|
||||
|
||||
$groups = $context['groups'] ?? [];
|
||||
if (!in_array('supplier:read:accounting', $groups, true)) {
|
||||
$groups[] = 'supplier:read:accounting';
|
||||
}
|
||||
$context['groups'] = $groups;
|
||||
|
||||
return $context;
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Infrastructure\ApiPlatform\State\Processor;
|
||||
|
||||
use ApiPlatform\Metadata\DeleteOperationInterface;
|
||||
use ApiPlatform\Metadata\Operation;
|
||||
use ApiPlatform\State\ProcessorInterface;
|
||||
use App\Module\Commercial\Domain\Entity\Supplier;
|
||||
use App\Module\Commercial\Domain\Entity\SupplierAddress;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
/**
|
||||
* Processor d'ecriture de la sous-ressource Adresse d'un fournisseur (M2,
|
||||
* spec-back § 4.5). Jumeau du ClientAddressProcessor (M1), recentre sur le
|
||||
* perimetre ERP-88.
|
||||
*
|
||||
* Sequence :
|
||||
* - POST / PATCH : rattachement au fournisseur parent. Aucune normalisation
|
||||
* specifique (pas d'email de facturation au M2). Les regles de l'onglet
|
||||
* Adresse sont garanties en amont par des contraintes sur l'entite, jouees
|
||||
* par API Platform avant ce processor : RG-2.05 (code postal, Assert\Regex),
|
||||
* RG-2.06 (>= 1 site, Assert\Count), RG-2.09 (type d'adresse, Assert\Choice +
|
||||
* CHECK BDD), RG-2.10 (categorie de type FOURNISSEUR, Assert\Callback
|
||||
* SupplierAddress::validateCategoryType).
|
||||
* - DELETE : aucune regle metier specifique (suppression physique directe).
|
||||
*
|
||||
* La security de l'operation (commercial.suppliers.manage) est appliquee par API
|
||||
* Platform en amont, de meme que la validation Symfony des contraintes d'attribut.
|
||||
*
|
||||
* @implements ProcessorInterface<SupplierAddress, null|SupplierAddress>
|
||||
*/
|
||||
final class SupplierAddressProcessor implements ProcessorInterface
|
||||
{
|
||||
public function __construct(
|
||||
#[Autowire(service: 'api_platform.doctrine.orm.state.persist_processor')]
|
||||
private readonly ProcessorInterface $persistProcessor,
|
||||
#[Autowire(service: 'api_platform.doctrine.orm.state.remove_processor')]
|
||||
private readonly ProcessorInterface $removeProcessor,
|
||||
private readonly EntityManagerInterface $em,
|
||||
) {}
|
||||
|
||||
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
|
||||
{
|
||||
if (!$data instanceof SupplierAddress) {
|
||||
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
|
||||
}
|
||||
|
||||
if ($operation instanceof DeleteOperationInterface) {
|
||||
return $this->removeProcessor->process($data, $operation, $uriVariables, $context);
|
||||
}
|
||||
|
||||
$this->linkParent($data, $uriVariables);
|
||||
|
||||
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rattache l'adresse au fournisseur parent de la sous-ressource POST
|
||||
* (/suppliers/{supplierId}/addresses) : la relation n'est pas peuplee
|
||||
* automatiquement par le Link sur une ecriture. Sur PATCH, no-op.
|
||||
*/
|
||||
private function linkParent(SupplierAddress $address, array $uriVariables): void
|
||||
{
|
||||
if (null !== $address->getSupplier()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$supplierId = $uriVariables['supplierId'] ?? null;
|
||||
if (null === $supplierId) {
|
||||
return;
|
||||
}
|
||||
|
||||
$supplier = $supplierId instanceof Supplier
|
||||
? $supplierId
|
||||
: $this->em->getRepository(Supplier::class)->find($supplierId);
|
||||
|
||||
// read:false sur le POST : sans stade lecture, un parent introuvable n'est
|
||||
// plus intercepte en amont -> 404 explicite (sinon 500 au persist sur la
|
||||
// contrainte supplier_id NOT NULL).
|
||||
if (!$supplier instanceof Supplier) {
|
||||
throw new NotFoundHttpException('Fournisseur introuvable.');
|
||||
}
|
||||
|
||||
$address->setSupplier($supplier);
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Infrastructure\ApiPlatform\State\Processor;
|
||||
|
||||
use ApiPlatform\Metadata\DeleteOperationInterface;
|
||||
use ApiPlatform\Metadata\Operation;
|
||||
use ApiPlatform\State\ProcessorInterface;
|
||||
use ApiPlatform\Validator\Exception\ValidationException;
|
||||
use App\Module\Commercial\Application\Service\SupplierFieldNormalizer;
|
||||
use App\Module\Commercial\Domain\Entity\Supplier;
|
||||
use App\Module\Commercial\Domain\Entity\SupplierContact;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Symfony\Component\Validator\ConstraintViolation;
|
||||
use Symfony\Component\Validator\ConstraintViolationList;
|
||||
|
||||
/**
|
||||
* Processor d'ecriture de la sous-ressource Contact d'un fournisseur (M2,
|
||||
* spec-back § 4.5). Jumeau du ClientContactProcessor (M1), recentre sur le
|
||||
* perimetre ERP-88.
|
||||
*
|
||||
* Sequence :
|
||||
* - POST / PATCH : rattachement au fournisseur parent, normalisation serveur
|
||||
* (RG-2.12 : prenom/nom Title Case, telephones reduits aux chiffres, email
|
||||
* lowercase) via le SupplierFieldNormalizer partage, puis validation RG-2.04
|
||||
* (au moins prenom OU nom) avant persistance.
|
||||
* - DELETE : aucune garde « dernier contact » au M2 — contrairement au M1, la
|
||||
* collection peut rester vide cote back (RG-2.13 front-driven, spec § 4.5).
|
||||
* Suppression physique directe.
|
||||
*
|
||||
* La security de l'operation (commercial.suppliers.manage) est appliquee par API
|
||||
* Platform en amont, de meme que la validation Symfony des contraintes d'attribut
|
||||
* (Assert\Email, Assert\Length...).
|
||||
*
|
||||
* @implements ProcessorInterface<SupplierContact, null|SupplierContact>
|
||||
*/
|
||||
final class SupplierContactProcessor implements ProcessorInterface
|
||||
{
|
||||
public function __construct(
|
||||
#[Autowire(service: 'api_platform.doctrine.orm.state.persist_processor')]
|
||||
private readonly ProcessorInterface $persistProcessor,
|
||||
#[Autowire(service: 'api_platform.doctrine.orm.state.remove_processor')]
|
||||
private readonly ProcessorInterface $removeProcessor,
|
||||
private readonly SupplierFieldNormalizer $normalizer,
|
||||
private readonly EntityManagerInterface $em,
|
||||
) {}
|
||||
|
||||
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
|
||||
{
|
||||
if (!$data instanceof SupplierContact) {
|
||||
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
|
||||
}
|
||||
|
||||
if ($operation instanceof DeleteOperationInterface) {
|
||||
return $this->removeProcessor->process($data, $operation, $uriVariables, $context);
|
||||
}
|
||||
|
||||
$this->linkParent($data, $uriVariables);
|
||||
$this->normalize($data);
|
||||
$this->validateName($data);
|
||||
|
||||
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rattache le contact au fournisseur parent de la sous-ressource POST
|
||||
* (/suppliers/{supplierId}/contacts). La relation n'est pas peuplee
|
||||
* automatiquement par le Link sur une operation d'ecriture : on resout le
|
||||
* parent depuis l'uri variable. Sur PATCH (entite existante), le fournisseur
|
||||
* est deja present -> no-op.
|
||||
*/
|
||||
private function linkParent(SupplierContact $contact, array $uriVariables): void
|
||||
{
|
||||
if (null !== $contact->getSupplier()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$supplierId = $uriVariables['supplierId'] ?? null;
|
||||
if (null === $supplierId) {
|
||||
return;
|
||||
}
|
||||
|
||||
$supplier = $supplierId instanceof Supplier
|
||||
? $supplierId
|
||||
: $this->em->getRepository(Supplier::class)->find($supplierId);
|
||||
|
||||
// read:false sur le POST : sans stade lecture, un parent introuvable n'est
|
||||
// plus intercepte en amont -> 404 explicite (sinon 500 au persist sur la
|
||||
// contrainte supplier_id NOT NULL).
|
||||
if (!$supplier instanceof Supplier) {
|
||||
throw new NotFoundHttpException('Fournisseur introuvable.');
|
||||
}
|
||||
|
||||
$contact->setSupplier($supplier);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalisation serveur (RG-2.12). Toutes les methodes du normalizer sont
|
||||
* null-safe : une chaine vide apres trim devient null.
|
||||
*/
|
||||
private function normalize(SupplierContact $contact): void
|
||||
{
|
||||
$contact->setFirstName($this->normalizer->normalizePersonName($contact->getFirstName()));
|
||||
$contact->setLastName($this->normalizer->normalizePersonName($contact->getLastName()));
|
||||
$contact->setPhonePrimary($this->normalizer->normalizePhone($contact->getPhonePrimary()));
|
||||
$contact->setPhoneSecondary($this->normalizer->normalizePhone($contact->getPhoneSecondary()));
|
||||
$contact->setEmail($this->normalizer->normalizeEmail($contact->getEmail()));
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-2.04 : au moins le prenom OU le nom est obligatoire (double garde avec le
|
||||
* CHECK BDD chk_supplier_contact_name — leve une 422 propre rattachee au champ
|
||||
* `firstName` plutot qu'une 500 SQL). Joue apres normalisation, donc les
|
||||
* chaines vides sont deja ramenees a null.
|
||||
*/
|
||||
private function validateName(SupplierContact $contact): void
|
||||
{
|
||||
if (null === $contact->getFirstName() && null === $contact->getLastName()) {
|
||||
$violations = new ConstraintViolationList();
|
||||
$violations->add(new ConstraintViolation(
|
||||
'Le prénom ou le nom du contact est obligatoire.',
|
||||
null,
|
||||
[],
|
||||
$contact,
|
||||
'firstName',
|
||||
null,
|
||||
));
|
||||
|
||||
throw new ValidationException($violations);
|
||||
}
|
||||
}
|
||||
}
|
||||
+527
@@ -0,0 +1,527 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Infrastructure\ApiPlatform\State\Processor;
|
||||
|
||||
use ApiPlatform\Metadata\Operation;
|
||||
use ApiPlatform\State\ProcessorInterface;
|
||||
use App\Module\Commercial\Application\Service\SupplierFieldNormalizer;
|
||||
use App\Module\Commercial\Application\Validator\SupplierInformationCompletenessValidator;
|
||||
use App\Module\Commercial\Domain\Entity\Supplier;
|
||||
use App\Shared\Domain\Contract\BusinessRoleAwareInterface;
|
||||
use App\Shared\Domain\Security\BusinessRoles;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Doctrine\ORM\PersistentCollection;
|
||||
use JsonException;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Component\HttpFoundation\RequestStack;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
|
||||
/**
|
||||
* Processor d'ecriture du repertoire fournisseurs (M2). Cf. spec-back M2 § 4.3 /
|
||||
* § 4.4 + RG-2.11 / RG-2.12 / RG-2.14 / RG-2.15 / RG-2.16. Jumeau du
|
||||
* ClientProcessor (M1), recentre sur le perimetre ERP-87.
|
||||
*
|
||||
* Sequence (POST / PATCH) :
|
||||
* 1. Autorisation additionnelle par groupe d'onglet (mode strict RG-2.16). La
|
||||
* security d'operation du PATCH est elargie a `manage` OU `accounting.manage`
|
||||
* pour laisser entrer le role Compta ; ce processor re-gate alors finement :
|
||||
* - champ comptable modifie dans le payload -> exige accounting.manage (403) ;
|
||||
* - champ main/information modifie -> exige manage (guardManage, 403) :
|
||||
* empeche Compta d'editer un autre onglet que la Comptabilite (§ 2.9) ;
|
||||
* - champ isArchived dans le payload -> exige archive (RG-2.14, 403) et
|
||||
* interdit toute autre modification dans la meme requete (RG-2.14, 422).
|
||||
* 2. Normalisation serveur (RG-2.12) via SupplierFieldNormalizer.
|
||||
* 3. Pose / retrait de archivedAt (RG-2.14 true=now, RG-2.15 false=null).
|
||||
* 4. Persistance via le persist_processor Doctrine, avec traduction des
|
||||
* collisions d'unicite en 409 (RG-2.11 doublon de nom ; RG-2.15 conflit de
|
||||
* restauration).
|
||||
*
|
||||
* Validators metier (ERP-89). Decision figee : ce processor ne porte QUE
|
||||
* RG-2.03 (completude Information exigee pour le role Commerciale — detection du
|
||||
* role cote back, non exprimable en contrainte d'entite). Les RG inter-champs
|
||||
* RG-2.07 (Virement -> banque), RG-2.08 (LCR -> >= 1 RIB) et RG-2.10 (categorie
|
||||
* de type FOURNISSEUR) sont portees par des Assert\Callback + ->atPath() sur
|
||||
* l'entite Supplier (jouees par API Platform AVANT ce processor), pour que
|
||||
* chaque 422 porte un propertyPath consommable par extractApiViolations
|
||||
* (mapping inline, pas un toast — convention ERP-101).
|
||||
*
|
||||
* Note : la validation Symfony (Assert\NotBlank, Assert\Count sur categories,
|
||||
* les Callback RG-2.07/2.08/2.10...) est jouee par API Platform AVANT ce
|
||||
* processor ; on n'y traite donc que les regles non exprimables en simples
|
||||
* contraintes d'entite (RG-2.03, qui depend du role de l'utilisateur courant).
|
||||
*
|
||||
* @implements ProcessorInterface<Supplier, Supplier>
|
||||
*/
|
||||
final class SupplierProcessor implements ProcessorInterface
|
||||
{
|
||||
/** Champs de l'onglet principal (groupe supplier:write:main). */
|
||||
private const array MAIN_FIELDS = [
|
||||
'companyName', 'categories',
|
||||
];
|
||||
|
||||
/** Champs de l'onglet Information (groupe supplier:write:information). */
|
||||
private const array INFORMATION_FIELDS = [
|
||||
'description', 'competitors', 'foundedAt', 'employeesCount',
|
||||
'revenueAmount', 'directorName', 'profitAmount', 'volumeForecast',
|
||||
];
|
||||
|
||||
/** Champs de l'onglet Comptabilite (groupe supplier:write:accounting). */
|
||||
private const array ACCOUNTING_FIELDS = [
|
||||
'siren', 'accountNumber', 'tvaMode', 'nTva', 'paymentDelay',
|
||||
'paymentType', 'bank',
|
||||
];
|
||||
|
||||
/** Champ d'archivage (groupe supplier:write:archive). */
|
||||
private const string ARCHIVE_FIELD = 'isArchived';
|
||||
|
||||
private const string PERM_MANAGE = 'commercial.suppliers.manage';
|
||||
private const string PERM_ACCOUNTING_MANAGE = 'commercial.suppliers.accounting.manage';
|
||||
private const string PERM_ARCHIVE = 'commercial.suppliers.archive';
|
||||
|
||||
/**
|
||||
* Memoisation du dernier corps de requete decode, clos par le contenu brut.
|
||||
* payloadKeys() est appele plusieurs fois par requete (writablePayloadKeys,
|
||||
* categoriesChanged...) : on evite de rejouer json_decode a chaque appel. La
|
||||
* cle etant le contenu lui-meme et le calcul une fonction pure de ce contenu,
|
||||
* aucune fuite n'est possible entre requetes sur ce service partage (un meme
|
||||
* corps redonne les memes cles).
|
||||
*/
|
||||
private ?string $decodedContent = null;
|
||||
|
||||
/** @var list<string> Cles de premier niveau correspondant au corps memoise. */
|
||||
private array $decodedPayloadKeys = [];
|
||||
|
||||
public function __construct(
|
||||
#[Autowire(service: 'api_platform.doctrine.orm.state.persist_processor')]
|
||||
private readonly ProcessorInterface $persistProcessor,
|
||||
private readonly SupplierFieldNormalizer $normalizer,
|
||||
private readonly SupplierInformationCompletenessValidator $informationValidator,
|
||||
private readonly Security $security,
|
||||
private readonly RequestStack $requestStack,
|
||||
private readonly EntityManagerInterface $em,
|
||||
) {}
|
||||
|
||||
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
|
||||
{
|
||||
if (!$data instanceof Supplier) {
|
||||
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
|
||||
}
|
||||
|
||||
$writableKeys = $this->writablePayloadKeys();
|
||||
|
||||
$isArchiveRequest = $this->guardArchive($data, $writableKeys);
|
||||
$this->guardAccounting($data);
|
||||
|
||||
$this->normalize($data);
|
||||
|
||||
// guardManage apres normalize : la comparaison « change vs etat
|
||||
// persiste » des champs texte (companyName...) se fait sur des valeurs
|
||||
// normalisees des deux cotes (l'etat persiste l'a deja ete).
|
||||
$this->guardManage($data);
|
||||
|
||||
$this->validateInformationCompleteness($data);
|
||||
|
||||
try {
|
||||
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
|
||||
} catch (UniqueConstraintViolationException $e) {
|
||||
// Le seul index unique partiel est uq_supplier_company_name_active
|
||||
// (LOWER(company_name) parmi non-archives/non-deletes — § 2.6).
|
||||
if ($isArchiveRequest && false === $data->isArchived()) {
|
||||
// RG-2.15 : restauration en conflit avec un homonyme actif.
|
||||
throw new ConflictHttpException(
|
||||
'Restauration impossible : un autre fournisseur a pris le nom entre-temps.',
|
||||
$e,
|
||||
);
|
||||
}
|
||||
|
||||
// RG-2.11 : doublon de nom de societe.
|
||||
throw new ConflictHttpException(
|
||||
sprintf('Un fournisseur nommé "%s" existe déjà.', (string) $data->getCompanyName()),
|
||||
$e,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-2.14 / RG-2.15 : si le payload bascule reellement isArchived, exige la
|
||||
* permission archive (403), interdit toute autre modification (422) et
|
||||
* pose/retire archivedAt. Retourne true si la requete est une requete
|
||||
* d'archivage.
|
||||
*
|
||||
* Le gating est restreint a la mise a jour d'un fournisseur existant ET au
|
||||
* seul cas ou isArchived change vraiment : un POST (entite non encore geree
|
||||
* par l'ORM) ou un PATCH « representation complete » renvoyant isArchived
|
||||
* inchange ne doit declencher ni 403 ni 422 parasite.
|
||||
*
|
||||
* @param list<string> $writableKeys cles ecrivables du payload (hors @* et champs inconnus)
|
||||
*/
|
||||
private function guardArchive(Supplier $data, array $writableKeys): bool
|
||||
{
|
||||
// POST / entite non geree : l'archivage est une action de mise a jour.
|
||||
if (!$this->em->contains($data)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// isArchived inchange par rapport a l'etat persiste : pas une requete
|
||||
// d'archivage (cas du PATCH representation complete).
|
||||
if (!$this->fieldChanged($data, 'isArchived', $data->isArchived())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$this->security->isGranted(self::PERM_ARCHIVE)) {
|
||||
throw new AccessDeniedHttpException(sprintf(
|
||||
'Le champ "%s" requiert la permission "%s".',
|
||||
self::ARCHIVE_FIELD,
|
||||
self::PERM_ARCHIVE,
|
||||
));
|
||||
}
|
||||
|
||||
// RG-2.14 : une requete d'archivage ne modifie aucun autre champ ecrivable.
|
||||
if ([] !== array_diff($writableKeys, [self::ARCHIVE_FIELD])) {
|
||||
throw new UnprocessableEntityHttpException(
|
||||
'Une requête d\'archivage ne peut modifier aucun autre champ que "isArchived".',
|
||||
);
|
||||
}
|
||||
|
||||
// RG-2.14 (true -> now) / RG-2.15 (false -> null).
|
||||
$data->setArchivedAt($data->isArchived() ? new DateTimeImmutable() : null);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-2.16 : la modification effective d'un champ comptable exige
|
||||
* accounting.manage, sinon 403 sur l'ensemble du payload (mode strict, pas
|
||||
* de filtrage silencieux). On ne gate que si un champ change reellement par
|
||||
* rapport a l'etat persiste : un POST/PATCH renvoyant des champs comptables
|
||||
* inchanges (ou null en creation) ne declenche pas de 403 parasite. Le
|
||||
* message precise le premier champ fautif.
|
||||
*/
|
||||
private function guardAccounting(Supplier $data): void
|
||||
{
|
||||
$changed = $this->changedAccountingFields($data);
|
||||
|
||||
if ([] === $changed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!$this->security->isGranted(self::PERM_ACCOUNTING_MANAGE)) {
|
||||
throw new AccessDeniedHttpException(sprintf(
|
||||
'Le champ "%s" requiert la permission "%s".',
|
||||
$changed[0],
|
||||
self::PERM_ACCOUNTING_MANAGE,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* § 2.9 / RG-2.16 : la modification effective d'un champ « metier » (onglets
|
||||
* principal ou Information) exige `commercial.suppliers.manage`. Sans cette
|
||||
* permission -> 403 sur l'ensemble du payload (mode strict, miroir de
|
||||
* guardAccounting). C'est ce qui empeche le role Compta — qui entre dans le
|
||||
* PATCH via `accounting.manage` (security d'operation elargie) — d'editer
|
||||
* autre chose que l'onglet Comptabilite.
|
||||
*
|
||||
* Ne s'applique qu'aux mises a jour (entite geree) : la creation (POST) est
|
||||
* deja gardee par la security d'operation `manage`, donc inutile de la
|
||||
* re-gater ici (et un POST par un porteur de `manage` passerait de toute
|
||||
* facon).
|
||||
*/
|
||||
private function guardManage(Supplier $data): void
|
||||
{
|
||||
if (!$this->em->contains($data)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$changed = $this->changedBusinessFields($data);
|
||||
|
||||
if ([] === $changed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!$this->security->isGranted(self::PERM_MANAGE)) {
|
||||
throw new AccessDeniedHttpException(sprintf(
|
||||
'Le champ "%s" requiert la permission "%s".',
|
||||
$changed[0],
|
||||
self::PERM_MANAGE,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-2.03 : si l'utilisateur porte le role metier Commerciale, TOUS les
|
||||
* champs de l'onglet Information sont obligatoires sur POST comme sur TOUT
|
||||
* PATCH — independamment des champs reellement envoyes. Garantit qu'un
|
||||
* fournisseur cree/edite par une Commerciale ne reste jamais avec un onglet
|
||||
* Information incomplet. Pour les autres roles, ces champs restent optionnels.
|
||||
*
|
||||
* Consequence (cf. spec § 7, miroir RG-1.04) : le POST n'exposant que
|
||||
* supplier:write:main, une Commerciale obtient 422 sur tout POST tant que
|
||||
* l'Information n'est pas complete -> la completude se fait via les PATCH
|
||||
* supplier:write:information.
|
||||
*/
|
||||
private function validateInformationCompleteness(Supplier $data): void
|
||||
{
|
||||
if ($this->currentUserIsCommerciale()) {
|
||||
$this->informationValidator->validate($data);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Detection du role metier Commerciale cote back (jamais front), via le
|
||||
* contrat BusinessRoleAwareInterface (pas d'import de User — regle ABSOLUE
|
||||
* n°1). Identique au ClientProcessor (M1).
|
||||
*/
|
||||
private function currentUserIsCommerciale(): bool
|
||||
{
|
||||
$user = $this->security->getUser();
|
||||
|
||||
return $user instanceof BusinessRoleAwareInterface
|
||||
&& $user->hasBusinessRole(BusinessRoles::COMMERCIALE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Champs « metier » (onglets principal + Information, hors comptabilite et
|
||||
* archivage) dont la valeur courante differe de l'etat persiste. Memes
|
||||
* regles de comparaison que changedAccountingFields (scalaires par valeur).
|
||||
*
|
||||
* Cas particulier `categories` (M2M) : non trace par getOriginalEntityData,
|
||||
* compare par valeur via le snapshot de la PersistentCollection (cf.
|
||||
* categoriesChanged) — la simple presence dans le payload ne suffit pas, sous
|
||||
* peine de 403 parasite sur un PATCH representation complete reincluant des
|
||||
* categories inchangees.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private function changedBusinessFields(Supplier $data): array
|
||||
{
|
||||
$newValues = [
|
||||
'companyName' => $data->getCompanyName(),
|
||||
'description' => $data->getDescription(),
|
||||
'competitors' => $data->getCompetitors(),
|
||||
'foundedAt' => $data->getFoundedAt(),
|
||||
'employeesCount' => $data->getEmployeesCount(),
|
||||
'revenueAmount' => $data->getRevenueAmount(),
|
||||
'directorName' => $data->getDirectorName(),
|
||||
'profitAmount' => $data->getProfitAmount(),
|
||||
'volumeForecast' => $data->getVolumeForecast(),
|
||||
];
|
||||
|
||||
$changed = [];
|
||||
foreach ($newValues as $field => $newValue) {
|
||||
if ($this->fieldChanged($data, $field, $newValue)) {
|
||||
$changed[] = $field;
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->categoriesChanged($data)) {
|
||||
$changed[] = 'categories';
|
||||
}
|
||||
|
||||
return $changed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si l'ensemble des categories (M2M) differe reellement de l'etat
|
||||
* persiste. La collection n'etant pas tracee par getOriginalEntityData, on
|
||||
* compare par identifiants (independamment de l'ordre) le snapshot de la
|
||||
* PersistentCollection (etat charge depuis la base) a l'etat courant (apres
|
||||
* application du payload). Symetrique de changedAccountingFields : seul un
|
||||
* changement effectif compte, pas la simple presence dans le payload.
|
||||
*
|
||||
* - POST / entite non geree : fournir des categories est un acte metier
|
||||
* (branche defensive, guardManage ne s'execute de toute facon que sur
|
||||
* entite geree).
|
||||
* - categories absent du payload (PATCH partiel) : aucun changement.
|
||||
*/
|
||||
private function categoriesChanged(Supplier $data): bool
|
||||
{
|
||||
if (!$this->em->contains($data)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!in_array('categories', $this->payloadKeys(), true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$collection = $data->getCategories();
|
||||
|
||||
// Hors PersistentCollection (cas limite hors flux PATCH reel) : faute
|
||||
// d'etat persiste comparable, on se rabat sur la presence payload.
|
||||
if (!$collection instanceof PersistentCollection) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->categoryIdSet($collection->toArray())
|
||||
!== $this->categoryIdSet($collection->getSnapshot());
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensemble trie des identifiants d'une liste de categories — pour une
|
||||
* comparaison par valeur independante de l'ordre.
|
||||
*
|
||||
* @param array<int, object> $categories
|
||||
*
|
||||
* @return list<mixed>
|
||||
*/
|
||||
private function categoryIdSet(array $categories): array
|
||||
{
|
||||
$ids = array_map(
|
||||
static fn (object $category): mixed => method_exists($category, 'getId')
|
||||
? $category->getId()
|
||||
: spl_object_id($category),
|
||||
array_values($categories),
|
||||
);
|
||||
sort($ids);
|
||||
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Champs comptables dont la valeur courante differe de l'etat persiste. Les
|
||||
* relations (tvaMode, paymentDelay, paymentType, bank) sont comparees par
|
||||
* identite d'objet : l'identity map Doctrine renvoie la meme instance tant
|
||||
* que la reference est inchangee.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private function changedAccountingFields(Supplier $data): array
|
||||
{
|
||||
$changed = [];
|
||||
|
||||
foreach (self::ACCOUNTING_FIELDS as $field) {
|
||||
$newValue = match ($field) {
|
||||
'siren' => $data->getSiren(),
|
||||
'accountNumber' => $data->getAccountNumber(),
|
||||
'tvaMode' => $data->getTvaMode(),
|
||||
'nTva' => $data->getNTva(),
|
||||
'paymentDelay' => $data->getPaymentDelay(),
|
||||
'paymentType' => $data->getPaymentType(),
|
||||
'bank' => $data->getBank(),
|
||||
};
|
||||
|
||||
if ($this->fieldChanged($data, $field, $newValue)) {
|
||||
$changed[] = $field;
|
||||
}
|
||||
}
|
||||
|
||||
return $changed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si la valeur courante d'un champ differe de l'etat persiste. Pour une
|
||||
* entite non geree (creation/POST), l'etat persiste est vide : toute valeur
|
||||
* non-null est alors un changement.
|
||||
*/
|
||||
private function fieldChanged(Supplier $data, string $field, mixed $newValue): bool
|
||||
{
|
||||
$original = $this->originalData($data);
|
||||
|
||||
return $newValue !== ($original[$field] ?? null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Snapshot des valeurs persistees de l'entite (telles que chargees, avant
|
||||
* application du payload). Vide pour une entite non geree (POST).
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function originalData(Supplier $data): array
|
||||
{
|
||||
if (!$this->em->contains($data)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->em->getUnitOfWork()->getOriginalEntityData($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalisation serveur du formulaire principal (RG-2.12). Seul companyName
|
||||
* subsiste cote Supplier (le contact inline a ete retire en V1 — les champs
|
||||
* de contact sont normalises par SupplierContactProcessor, ERP-88). Le setter
|
||||
* non-nullable n'est touche que si une valeur est presente, pour ne jamais
|
||||
* ecraser l'existant lors d'un PATCH partiel.
|
||||
*/
|
||||
private function normalize(Supplier $data): void
|
||||
{
|
||||
if (null !== $data->getCompanyName()) {
|
||||
$data->setCompanyName((string) $this->normalizer->normalizeCompanyName($data->getCompanyName()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cles ecrivables effectivement presentes dans le payload : on retire les
|
||||
* cles JSON-LD (@id, @context, @var...) et tout champ non rattache a un
|
||||
* groupe d'ecriture connu. C'est la base du 422 d'archivage (RG-2.14) —
|
||||
* sans elles, un PATCH « representation complete » porteur de @id ferait
|
||||
* croire a une modification multi-onglets.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private function writablePayloadKeys(): array
|
||||
{
|
||||
$writable = array_merge(
|
||||
self::MAIN_FIELDS,
|
||||
self::INFORMATION_FIELDS,
|
||||
self::ACCOUNTING_FIELDS,
|
||||
[self::ARCHIVE_FIELD],
|
||||
);
|
||||
|
||||
return array_values(array_intersect($this->payloadKeys(), $writable));
|
||||
}
|
||||
|
||||
/**
|
||||
* Cles de premier niveau effectivement envoyees par le client (payload JSON
|
||||
* brut), filtrage compris. Pour un PATCH merge-patch+json, ce sont les seuls
|
||||
* champs modifies.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private function payloadKeys(): array
|
||||
{
|
||||
$request = $this->requestStack->getCurrentRequest();
|
||||
if (null === $request) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$content = $request->getContent();
|
||||
|
||||
// Cache hit : meme corps brut que le dernier decodage -> memes cles.
|
||||
if ($content === $this->decodedContent) {
|
||||
return $this->decodedPayloadKeys;
|
||||
}
|
||||
|
||||
$this->decodedContent = $content;
|
||||
$this->decodedPayloadKeys = $this->extractPayloadKeys($content);
|
||||
|
||||
return $this->decodedPayloadKeys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode le corps brut et en extrait les cles de premier niveau (chaines).
|
||||
* Corps vide ou JSON invalide -> aucune cle.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private function extractPayloadKeys(string $content): array
|
||||
{
|
||||
if ('' === $content) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
$decoded = json_decode($content, true, 512, JSON_THROW_ON_ERROR);
|
||||
} catch (JsonException) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return is_array($decoded) ? array_values(array_filter(array_keys($decoded), 'is_string')) : [];
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Infrastructure\ApiPlatform\State\Processor;
|
||||
|
||||
use ApiPlatform\Metadata\DeleteOperationInterface;
|
||||
use ApiPlatform\Metadata\Operation;
|
||||
use ApiPlatform\State\ProcessorInterface;
|
||||
use App\Module\Commercial\Domain\Entity\Supplier;
|
||||
use App\Module\Commercial\Domain\Entity\SupplierRib;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
/**
|
||||
* Processor d'ecriture de la sous-ressource RIB d'un fournisseur (M2, spec-back
|
||||
* § 4.5). Jumeau du ClientRibProcessor (M1), recentre sur le perimetre ERP-88.
|
||||
*
|
||||
* Sequence :
|
||||
* - POST / PATCH : rattachement au fournisseur parent. Aucune normalisation
|
||||
* specifique ; la validite de l'IBAN et du BIC est garantie par Assert\Iban /
|
||||
* Assert\Bic sur l'entite (jouees en amont par API Platform). Aucun
|
||||
* #[AuditIgnore] sur iban/bic : la tracabilite comptable est volontaire
|
||||
* (decision M1 reportee, spec § 2.7).
|
||||
* - DELETE : RG-2.08 — si le fournisseur est en reglement LCR, la suppression de
|
||||
* son DERNIER RIB est refusee (409), car LCR exige au moins un RIB.
|
||||
*
|
||||
* La security de l'operation (commercial.suppliers.accounting.manage) est
|
||||
* appliquee par API Platform en amont : un utilisateur sans cette permission
|
||||
* recoit 403 sur POST/PATCH/DELETE avant d'atteindre ce processor — c'est le
|
||||
* niveau de gating renforce des donnees bancaires (distinct de manage, spec
|
||||
* § 4.5).
|
||||
*
|
||||
* @implements ProcessorInterface<SupplierRib, null|SupplierRib>
|
||||
*/
|
||||
final class SupplierRibProcessor implements ProcessorInterface
|
||||
{
|
||||
public function __construct(
|
||||
#[Autowire(service: 'api_platform.doctrine.orm.state.persist_processor')]
|
||||
private readonly ProcessorInterface $persistProcessor,
|
||||
#[Autowire(service: 'api_platform.doctrine.orm.state.remove_processor')]
|
||||
private readonly ProcessorInterface $removeProcessor,
|
||||
private readonly EntityManagerInterface $em,
|
||||
) {}
|
||||
|
||||
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
|
||||
{
|
||||
if (!$data instanceof SupplierRib) {
|
||||
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
|
||||
}
|
||||
|
||||
if ($operation instanceof DeleteOperationInterface) {
|
||||
$this->guardLastRibDeletionUnderLcr($data);
|
||||
|
||||
return $this->removeProcessor->process($data, $operation, $uriVariables, $context);
|
||||
}
|
||||
|
||||
$this->linkParent($data, $uriVariables);
|
||||
|
||||
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rattache le RIB au fournisseur parent de la sous-ressource POST
|
||||
* (/suppliers/{supplierId}/ribs) : la relation n'est pas peuplee
|
||||
* automatiquement par le Link sur une ecriture. Sur PATCH, no-op.
|
||||
*/
|
||||
private function linkParent(SupplierRib $rib, array $uriVariables): void
|
||||
{
|
||||
if (null !== $rib->getSupplier()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$supplierId = $uriVariables['supplierId'] ?? null;
|
||||
if (null === $supplierId) {
|
||||
return;
|
||||
}
|
||||
|
||||
$supplier = $supplierId instanceof Supplier
|
||||
? $supplierId
|
||||
: $this->em->getRepository(Supplier::class)->find($supplierId);
|
||||
|
||||
// read:false sur le POST : sans stade lecture, un parent introuvable n'est
|
||||
// plus intercepte en amont -> 404 explicite (sinon 500 au persist sur la
|
||||
// contrainte supplier_id NOT NULL).
|
||||
if (!$supplier instanceof Supplier) {
|
||||
throw new NotFoundHttpException('Fournisseur introuvable.');
|
||||
}
|
||||
|
||||
$rib->setSupplier($supplier);
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-2.08 : un fournisseur dont le type de reglement est LCR doit conserver au
|
||||
* moins un RIB. La collection inclut le RIB en cours de suppression : un
|
||||
* effectif <= 1 signifie qu'il ne resterait aucun RIB -> 409. Pour tout autre
|
||||
* type de reglement, les RIBs sont optionnels (suppression libre).
|
||||
*/
|
||||
private function guardLastRibDeletionUnderLcr(SupplierRib $rib): void
|
||||
{
|
||||
$supplier = $rib->getSupplier();
|
||||
if (null === $supplier) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ('LCR' === $supplier->getPaymentType()?->getCode() && $supplier->getRibs()->count() <= 1) {
|
||||
throw new ConflictHttpException(
|
||||
'Impossible de supprimer le dernier RIB : le type de règlement LCR exige au moins un RIB.',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
<?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\Supplier;
|
||||
use App\Module\Commercial\Domain\Repository\SupplierRepositoryInterface;
|
||||
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
|
||||
/**
|
||||
* Provider du repertoire fournisseurs (M2). Cf. spec-back M2 § 4.1 / § 4.2 +
|
||||
* RG-2.17. Jumeau du ClientProvider (M1).
|
||||
*
|
||||
* Collection (GET /api/suppliers) :
|
||||
* - exclut par defaut les archives (is_archived = true) ET les soft-deletes
|
||||
* (deleted_at IS NOT NULL) — RG-2.17 ;
|
||||
* - ?includeArchived=true reintegre les archives (les soft-deletes restent
|
||||
* exclus au M2) — RG-2.17 ;
|
||||
* - tri par defaut companyName ASC — RG-2.17 ;
|
||||
* - filtres ?search=... (fuzzy companyName + contacts lies : firstName /
|
||||
* lastName / email — D1 refonte-contact), ?categoryCode=<code> (fournisseurs
|
||||
* ayant >= 1 categorie de ce code, repetable) et ?siteId=<id> (fournisseurs
|
||||
* ayant >= 1 adresse rattachee a ce site, repetable) ;
|
||||
* - pagination obligatoire (regle ABSOLUE n°13) : Paginator ORM ; echappatoire
|
||||
* ?pagination=false pour alimenter un <select> sans pagination.
|
||||
*
|
||||
* Item (GET /api/suppliers/{id} + provider de PATCH) :
|
||||
* - 404 si introuvable OU soft-delete (deleted_at non null, jamais expose au
|
||||
* M2) ; les archives restent consultables/restaurables en detail.
|
||||
*
|
||||
* Le filtrage des champs comptables en lecture (groupe supplier:read:accounting)
|
||||
* n'est PAS fait ici mais dans SupplierReadGroupContextBuilder : un Provider
|
||||
* retourne des donnees mais ne peut pas influencer les groupes de serialisation.
|
||||
* Le contexte de normalisation est construit par le SerializerContextBuilder, en
|
||||
* amont du serializer — c'est le point d'extension idiomatique d'API Platform
|
||||
* pour conditionner le groupe accounting selon la permission de l'utilisateur.
|
||||
*
|
||||
* @implements ProviderInterface<Supplier>
|
||||
*/
|
||||
final class SupplierProvider implements ProviderInterface
|
||||
{
|
||||
public function __construct(
|
||||
#[Autowire(service: 'App\Module\Commercial\Infrastructure\Doctrine\DoctrineSupplierRepository')]
|
||||
private readonly SupplierRepositoryInterface $repository,
|
||||
private readonly Pagination $pagination,
|
||||
) {}
|
||||
|
||||
public function provide(Operation $operation, array $uriVariables = [], array $context = []): iterable|Paginator|Supplier|null
|
||||
{
|
||||
if ($operation instanceof CollectionOperationInterface) {
|
||||
return $this->provideCollection($operation, $context);
|
||||
}
|
||||
|
||||
return $this->provideItem($uriVariables);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $context
|
||||
*
|
||||
* @return list<Supplier>|Paginator<Supplier>
|
||||
*/
|
||||
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=NEGOCIANT, 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,
|
||||
);
|
||||
|
||||
// Echappatoire ?pagination=false : collection complete sans Paginator
|
||||
// (regle n°13 — utile pour un <select> cote front).
|
||||
if (!$this->pagination->isEnabled($operation, $context)) {
|
||||
/** @var list<Supplier> $suppliers */
|
||||
$suppliers = $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($suppliers);
|
||||
|
||||
return $suppliers;
|
||||
}
|
||||
|
||||
$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): ?Supplier
|
||||
{
|
||||
$id = $uriVariables['id'] ?? null;
|
||||
if (!is_int($id) && !(is_string($id) && ctype_digit($id))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$supplier = $this->repository->findById((int) $id);
|
||||
if (null === $supplier) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Soft-delete : jamais expose au M2 (HP-M3-1) — 404 via retour null.
|
||||
// Les archives restent visibles en detail (consultation + restauration).
|
||||
if (null !== $supplier->getDeletedAt()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $supplier;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Module\Commercial\Domain\Entity;
|
||||
|
||||
use App\Module\Commercial\Domain\Entity\Bank;
|
||||
use App\Module\Commercial\Domain\Entity\PaymentType;
|
||||
use App\Module\Commercial\Domain\Entity\Supplier;
|
||||
use App\Module\Commercial\Domain\Entity\SupplierRib;
|
||||
use App\Shared\Domain\Contract\CategoryInterface;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Component\Validator\Validation;
|
||||
use Symfony\Component\Validator\Validator\ValidatorInterface;
|
||||
|
||||
/**
|
||||
* Tests des contraintes inter-champs de l'entite Supplier portees par
|
||||
* Assert\Callback (decision figee ERP-89) : RG-2.10 (categorie de type
|
||||
* FOURNISSEUR), RG-2.07 (Virement -> banque), RG-2.08 (LCR -> >= 1 RIB).
|
||||
*
|
||||
* On valide l'entite avec le validator Symfony (mapping par attributs) et on
|
||||
* assert le propertyPath exact de chaque violation (contrat ERP-101 :
|
||||
* exploitable par extractApiViolations). Pas de base : les Callback ne touchent
|
||||
* que des champs en memoire (categories via un double CategoryInterface).
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class SupplierValidationTest extends TestCase
|
||||
{
|
||||
private ValidatorInterface $validator;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->validator = Validation::createValidatorBuilder()
|
||||
->enableAttributeMapping()
|
||||
->getValidator()
|
||||
;
|
||||
}
|
||||
|
||||
// === RG-2.10 : categories de type FOURNISSEUR ===
|
||||
|
||||
public function testFournisseurCategoryIsAccepted(): void
|
||||
{
|
||||
$supplier = $this->validSupplier();
|
||||
|
||||
self::assertSame([], $this->violationPaths($supplier));
|
||||
}
|
||||
|
||||
public function testNonFournisseurCategoryIsRejectedOnCategoriesPath(): void
|
||||
{
|
||||
$supplier = new Supplier();
|
||||
$supplier->setCompanyName('Recycla SAS');
|
||||
$supplier->addCategory($this->category('CLIENT'));
|
||||
|
||||
self::assertContains('categories', $this->violationPaths($supplier));
|
||||
}
|
||||
|
||||
// === RG-2.07 : Virement impose une banque ===
|
||||
|
||||
public function testVirementWithoutBankIsRejectedOnBankPath(): void
|
||||
{
|
||||
$supplier = $this->validSupplier();
|
||||
$supplier->setPaymentType($this->paymentType('VIREMENT'));
|
||||
|
||||
self::assertContains('bank', $this->violationPaths($supplier));
|
||||
}
|
||||
|
||||
public function testVirementWithBankPasses(): void
|
||||
{
|
||||
$supplier = $this->validSupplier();
|
||||
$supplier->setPaymentType($this->paymentType('VIREMENT'));
|
||||
$supplier->setBank(new Bank());
|
||||
|
||||
self::assertNotContains('bank', $this->violationPaths($supplier));
|
||||
}
|
||||
|
||||
// === RG-2.08 : LCR impose au moins un RIB ===
|
||||
|
||||
public function testLcrWithoutRibIsRejectedOnRibsPath(): void
|
||||
{
|
||||
$supplier = $this->validSupplier();
|
||||
$supplier->setPaymentType($this->paymentType('LCR'));
|
||||
|
||||
self::assertContains('ribs', $this->violationPaths($supplier));
|
||||
}
|
||||
|
||||
public function testLcrWithRibPasses(): void
|
||||
{
|
||||
$supplier = $this->validSupplier();
|
||||
$supplier->setPaymentType($this->paymentType('LCR'));
|
||||
$supplier->addRib(new SupplierRib());
|
||||
|
||||
self::assertNotContains('ribs', $this->violationPaths($supplier));
|
||||
}
|
||||
|
||||
public function testNeutralPaymentTypeRequiresNeitherBankNorRib(): void
|
||||
{
|
||||
// Un type de reglement neutre (ni VIREMENT ni LCR) n'exige ni banque ni RIB.
|
||||
$supplier = $this->validSupplier();
|
||||
$supplier->setPaymentType($this->paymentType('CHEQUE'));
|
||||
|
||||
$paths = $this->violationPaths($supplier);
|
||||
self::assertNotContains('bank', $paths);
|
||||
self::assertNotContains('ribs', $paths);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fournisseur valide (nom + 1 categorie FOURNISSEUR), sans onglet
|
||||
* Comptabilite renseigne : sert de base aux tests RG-2.07/2.08.
|
||||
*/
|
||||
private function validSupplier(): Supplier
|
||||
{
|
||||
$supplier = new Supplier();
|
||||
$supplier->setCompanyName('Recycla SAS');
|
||||
$supplier->addCategory($this->category('FOURNISSEUR'));
|
||||
|
||||
return $supplier;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string> propertyPaths des violations levees par le validator
|
||||
*/
|
||||
private function violationPaths(Supplier $supplier): array
|
||||
{
|
||||
$paths = [];
|
||||
foreach ($this->validator->validate($supplier) as $violation) {
|
||||
$paths[] = $violation->getPropertyPath();
|
||||
}
|
||||
|
||||
return $paths;
|
||||
}
|
||||
|
||||
/**
|
||||
* Double minimal de CategoryInterface (pas d'acces base) renvoyant le code de
|
||||
* type de categorie voulu — seul element regarde par validateCategoryType.
|
||||
*/
|
||||
private function category(string $typeCode): CategoryInterface
|
||||
{
|
||||
return new class($typeCode) implements CategoryInterface {
|
||||
public function __construct(private readonly string $typeCode) {}
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public function getName(): ?string
|
||||
{
|
||||
return 'Categorie test';
|
||||
}
|
||||
|
||||
public function getCode(): ?string
|
||||
{
|
||||
return 'TEST';
|
||||
}
|
||||
|
||||
public function getCategoryTypeCode(): ?string
|
||||
{
|
||||
return $this->typeCode;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private function paymentType(string $code): PaymentType
|
||||
{
|
||||
$type = new PaymentType();
|
||||
$type->setCode($code);
|
||||
$type->setLabel($code);
|
||||
|
||||
return $type;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Module\Commercial\Unit;
|
||||
|
||||
use ApiPlatform\Validator\Exception\ValidationException;
|
||||
use App\Module\Commercial\Application\Validator\SupplierInformationCompletenessValidator;
|
||||
use App\Module\Commercial\Domain\Entity\Supplier;
|
||||
use DateTimeImmutable;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Tests unitaires du SupplierInformationCompletenessValidator (RG-2.03) : pour le
|
||||
* role Commerciale, TOUS les champs de l'onglet Information sont obligatoires.
|
||||
* Chaque champ manquant produit une violation portant son propertyPath (ERP-101).
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class SupplierInformationCompletenessValidatorTest extends TestCase
|
||||
{
|
||||
public function testCompleteInformationPasses(): void
|
||||
{
|
||||
$supplier = $this->completeSupplier();
|
||||
|
||||
$this->validator()->validate($supplier);
|
||||
|
||||
// Aucune exception levee : la completude est satisfaite.
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
public function testEmptyInformationListsEveryMissingField(): void
|
||||
{
|
||||
$supplier = new Supplier();
|
||||
$supplier->setCompanyName('Recycla SAS'); // onglet principal, hors Information
|
||||
|
||||
try {
|
||||
$this->validator()->validate($supplier);
|
||||
self::fail('Une ValidationException etait attendue (onglet Information vide).');
|
||||
} catch (ValidationException $e) {
|
||||
$paths = [];
|
||||
foreach ($e->getConstraintViolationList() as $violation) {
|
||||
$paths[] = $violation->getPropertyPath();
|
||||
}
|
||||
|
||||
// Les 8 champs Information (dont volumeForecast, NEW vs Client) sont
|
||||
// tous signales d'un coup, chacun sous son propre propertyPath.
|
||||
sort($paths);
|
||||
self::assertSame([
|
||||
'competitors',
|
||||
'description',
|
||||
'directorName',
|
||||
'employeesCount',
|
||||
'foundedAt',
|
||||
'profitAmount',
|
||||
'revenueAmount',
|
||||
'volumeForecast',
|
||||
], $paths);
|
||||
}
|
||||
}
|
||||
|
||||
public function testPartialInformationReportsOnlyMissingFields(): void
|
||||
{
|
||||
$supplier = $this->completeSupplier();
|
||||
$supplier->setDirectorName(null);
|
||||
$supplier->setVolumeForecast(null);
|
||||
|
||||
try {
|
||||
$this->validator()->validate($supplier);
|
||||
self::fail('Une ValidationException etait attendue (2 champs manquants).');
|
||||
} catch (ValidationException $e) {
|
||||
$paths = [];
|
||||
foreach ($e->getConstraintViolationList() as $violation) {
|
||||
$paths[] = $violation->getPropertyPath();
|
||||
}
|
||||
|
||||
sort($paths);
|
||||
self::assertSame(['directorName', 'volumeForecast'], $paths);
|
||||
}
|
||||
}
|
||||
|
||||
public function testZeroNumericValuesAreNotMissing(): void
|
||||
{
|
||||
// employeesCount = 0, profitAmount = "0.00", volumeForecast = 0 sont des
|
||||
// valeurs valides (un zero n'est pas une absence) -> pas de violation.
|
||||
$supplier = $this->completeSupplier();
|
||||
$supplier->setEmployeesCount(0);
|
||||
$supplier->setProfitAmount('0.00');
|
||||
$supplier->setVolumeForecast(0);
|
||||
|
||||
$this->validator()->validate($supplier);
|
||||
|
||||
$this->addToAssertionCount(1);
|
||||
}
|
||||
|
||||
public function testBlankStringIsMissing(): void
|
||||
{
|
||||
// Une chaine vide apres trim compte comme manquante.
|
||||
$supplier = $this->completeSupplier();
|
||||
$supplier->setDescription(' ');
|
||||
|
||||
$this->expectException(ValidationException::class);
|
||||
$this->validator()->validate($supplier);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fournisseur dont l'onglet Information est entierement renseigne.
|
||||
*/
|
||||
private function completeSupplier(): Supplier
|
||||
{
|
||||
$supplier = new Supplier();
|
||||
$supplier->setCompanyName('Recycla SAS');
|
||||
$supplier->setDescription('Specialiste du recyclage');
|
||||
$supplier->setCompetitors('Concurrent A, Concurrent B');
|
||||
$supplier->setFoundedAt(new DateTimeImmutable('2010-01-01'));
|
||||
$supplier->setEmployeesCount(42);
|
||||
$supplier->setRevenueAmount('1000000.00');
|
||||
$supplier->setDirectorName('Marie Durand');
|
||||
$supplier->setProfitAmount('150000.00');
|
||||
$supplier->setVolumeForecast(5000);
|
||||
|
||||
return $supplier;
|
||||
}
|
||||
|
||||
private function validator(): SupplierInformationCompletenessValidator
|
||||
{
|
||||
return new SupplierInformationCompletenessValidator();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Module\Commercial\Unit;
|
||||
|
||||
use ApiPlatform\Metadata\Operation;
|
||||
use ApiPlatform\State\ProcessorInterface;
|
||||
use ApiPlatform\Validator\Exception\ValidationException;
|
||||
use App\Module\Commercial\Application\Service\SupplierFieldNormalizer;
|
||||
use App\Module\Commercial\Application\Validator\SupplierInformationCompletenessValidator;
|
||||
use App\Module\Commercial\Domain\Entity\Supplier;
|
||||
use App\Module\Commercial\Infrastructure\ApiPlatform\State\Processor\SupplierProcessor;
|
||||
use App\Shared\Domain\Contract\BusinessRoleAwareInterface;
|
||||
use App\Shared\Domain\Security\BusinessRoles;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Doctrine\ORM\UnitOfWork;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\RequestStack;
|
||||
use Symfony\Component\Security\Core\User\UserInterface;
|
||||
|
||||
/**
|
||||
* Tests unitaires du SupplierProcessor — perimetre ERP-89 : detection du role
|
||||
* Commerciale cote back (RG-2.03). Les autres responsabilites du processor
|
||||
* (gating accounting / archive / mode strict) sont heritees d'ERP-87 et testees
|
||||
* a leur niveau ; les RG inter-champs (RG-2.07/2.08/2.10) sont des contraintes
|
||||
* d'entite (cf. SupplierValidationTest), non portees ici.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class SupplierProcessorTest extends TestCase
|
||||
{
|
||||
public function testCommercialeIncompleteInformationIsUnprocessable(): void
|
||||
{
|
||||
// RG-2.03 : role Commerciale + onglet Information incomplet -> 422, meme
|
||||
// sur un POST (les champs Information n'y sont pas renseignables).
|
||||
$supplier = $this->minimalSupplier();
|
||||
$supplier->setDescription('Une description'); // les autres champs Information restent null
|
||||
|
||||
$processor = $this->makeProcessor(
|
||||
payload: ['description' => 'Une description'],
|
||||
user: $this->commercialeUser(),
|
||||
);
|
||||
|
||||
$this->expectException(ValidationException::class);
|
||||
$processor->process($supplier, $this->operation());
|
||||
}
|
||||
|
||||
public function testCommercialeIncompleteInformationOnMainOnlyPatchIsUnprocessable(): void
|
||||
{
|
||||
// RG-2.03 : pour une Commerciale, la completude Information est exigee
|
||||
// meme quand le payload ne touche PAS l'onglet Information (ici
|
||||
// companyName seul) -> 422.
|
||||
$supplier = $this->minimalSupplier();
|
||||
$supplier->setCompanyName('Renamed Co');
|
||||
|
||||
$processor = $this->makeProcessor(
|
||||
granted: ['commercial.suppliers.manage'],
|
||||
payload: ['companyName' => 'Renamed Co'],
|
||||
user: $this->commercialeUser(),
|
||||
managed: true,
|
||||
originalData: [
|
||||
'companyName' => 'TEST CO',
|
||||
'isArchived' => false,
|
||||
],
|
||||
);
|
||||
|
||||
$this->expectException(ValidationException::class);
|
||||
$processor->process($supplier, $this->operation());
|
||||
}
|
||||
|
||||
public function testCommercialeCompleteInformationPasses(): void
|
||||
{
|
||||
// RG-2.03 satisfaite : tous les champs Information renseignes -> 200.
|
||||
$supplier = $this->completeInformationSupplier();
|
||||
|
||||
$processor = $this->makeProcessor(
|
||||
granted: ['commercial.suppliers.manage'],
|
||||
payload: ['description' => 'desc'],
|
||||
user: $this->commercialeUser(),
|
||||
);
|
||||
|
||||
self::assertInstanceOf(Supplier::class, $processor->process($supplier, $this->operation()));
|
||||
}
|
||||
|
||||
public function testNonCommercialeSkipsInformationCompleteness(): void
|
||||
{
|
||||
// Meme onglet Information incomplet, mais user non-Commerciale -> aucun
|
||||
// blocage (la completude est specifique a la Commerciale).
|
||||
$supplier = $this->minimalSupplier();
|
||||
$supplier->setDescription('Une description');
|
||||
|
||||
$processor = $this->makeProcessor(
|
||||
payload: ['description' => 'Une description'],
|
||||
user: null,
|
||||
);
|
||||
|
||||
self::assertInstanceOf(Supplier::class, $processor->process($supplier, $this->operation()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $granted Permissions accordees a l'utilisateur courant
|
||||
* @param array<string, mixed> $payload Corps JSON simule de la requete
|
||||
* @param bool $managed true = entite geree par l'ORM (PATCH), false = creation (POST)
|
||||
* @param array<string, mixed> $originalData Etat persiste simule (getOriginalEntityData)
|
||||
*/
|
||||
private function makeProcessor(
|
||||
array $granted = [],
|
||||
array $payload = [],
|
||||
?UserInterface $user = null,
|
||||
bool $managed = false,
|
||||
array $originalData = [],
|
||||
): SupplierProcessor {
|
||||
$persist = new class implements ProcessorInterface {
|
||||
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
};
|
||||
|
||||
$security = $this->createStub(Security::class);
|
||||
$security->method('isGranted')->willReturnCallback(
|
||||
static fn (mixed $attribute): bool => is_string($attribute) && in_array($attribute, $granted, true),
|
||||
);
|
||||
$security->method('getUser')->willReturn($user);
|
||||
|
||||
$requestStack = new RequestStack();
|
||||
$requestStack->push(new Request([], [], [], [], [], [], json_encode($payload, JSON_THROW_ON_ERROR)));
|
||||
|
||||
$uow = $this->createMock(UnitOfWork::class);
|
||||
$uow->method('getOriginalEntityData')->willReturn($originalData);
|
||||
|
||||
$em = $this->createMock(EntityManagerInterface::class);
|
||||
$em->method('contains')->willReturn($managed);
|
||||
$em->method('getUnitOfWork')->willReturn($uow);
|
||||
|
||||
return new SupplierProcessor(
|
||||
$persist,
|
||||
new SupplierFieldNormalizer(),
|
||||
new SupplierInformationCompletenessValidator(),
|
||||
$security,
|
||||
$requestStack,
|
||||
$em,
|
||||
);
|
||||
}
|
||||
|
||||
private function minimalSupplier(): Supplier
|
||||
{
|
||||
$supplier = new Supplier();
|
||||
$supplier->setCompanyName('Test Co');
|
||||
|
||||
return $supplier;
|
||||
}
|
||||
|
||||
private function completeInformationSupplier(): Supplier
|
||||
{
|
||||
$supplier = $this->minimalSupplier();
|
||||
$supplier->setDescription('desc');
|
||||
$supplier->setCompetitors('concurrents');
|
||||
$supplier->setFoundedAt(new DateTimeImmutable('2010-01-01'));
|
||||
$supplier->setEmployeesCount(10);
|
||||
$supplier->setRevenueAmount('1000.00');
|
||||
$supplier->setDirectorName('Marie Durand');
|
||||
$supplier->setProfitAmount('100.00');
|
||||
$supplier->setVolumeForecast(500);
|
||||
|
||||
return $supplier;
|
||||
}
|
||||
|
||||
private function operation(): Operation
|
||||
{
|
||||
return $this->createStub(Operation::class);
|
||||
}
|
||||
|
||||
private function commercialeUser(): UserInterface
|
||||
{
|
||||
return new class implements UserInterface, BusinessRoleAwareInterface {
|
||||
public function hasBusinessRole(string $roleCode): bool
|
||||
{
|
||||
return BusinessRoles::COMMERCIALE === $roleCode;
|
||||
}
|
||||
|
||||
public function getRoles(): array
|
||||
{
|
||||
return ['ROLE_USER'];
|
||||
}
|
||||
|
||||
public function eraseCredentials(): void {}
|
||||
|
||||
public function getUserIdentifier(): string
|
||||
{
|
||||
return 'commerciale-test';
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user