Compare commits
29 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e598a92f94 | |||
| b8dc3cb696 | |||
| 843e4b0a0c | |||
| a9c14704b7 | |||
| 43b2251ef1 | |||
| 9cda225bdf | |||
| f031c70393 | |||
| e050a7b910 | |||
| b35deed8fe | |||
| 6f9bb68170 | |||
| 97459e798f | |||
| 58cbfe4437 | |||
| 54091be60e | |||
| e265a008bc | |||
| 145d4362db | |||
| cd36c45b67 | |||
| e77c6378d3 | |||
| 3e138e1c17 | |||
| 6a01067746 | |||
| cd98817b0a | |||
| 1a29bcf76c | |||
| da343464c6 | |||
| 0b33bcb0f2 | |||
| 786638a02f | |||
| fcacde2a34 | |||
| fea325e10f | |||
| e139d234a9 | |||
| c437bc52a2 | |||
| 597101262d |
+19
-131
@@ -6,6 +6,13 @@
|
||||
- PHP CS Fixer : regles Symfony + PSR-12 + strict types (commande : `make php-cs-fixer-allow-risky`)
|
||||
- Commentaires (docblock, inline, bloc) **en francais** ; code (classes, methodes, variables) en anglais
|
||||
|
||||
## Messages de validation (obligatoire)
|
||||
|
||||
Toute contrainte `#[Assert\*]` d'une entite metier : **message FR explicite**, et `Assert\Length.max` = `length` de la colonne ORM (coherence 3 niveaux nullable DB <-> NotBlank back <-> required front, ERP-101). RG inter-champs via `#[Assert\Callback]->atPath('<champ>')` (mapping inline front, pas toast). Exceptions miroir Length (Bic/Iban/Regex borne) : whitelist `EntityConstraintsHaveFrenchMessageTest::EXCLUDED_LENGTH_MIRROR`.
|
||||
|
||||
Garde-fou : `tests/Architecture/EntityConstraintsHaveFrenchMessageTest` (casse `make test`).
|
||||
→ patterns code + exemples + justification complete : skill `backend-entity-conventions`.
|
||||
|
||||
## API Platform (pas de controllers)
|
||||
|
||||
- Toujours utiliser `#[ApiResource]` + Providers + Processors — pas de controllers Symfony classiques
|
||||
@@ -15,61 +22,10 @@
|
||||
|
||||
## Pagination (obligatoire)
|
||||
|
||||
**Regle** : toute collection API DOIT etre paginee. Aucun retour de collection complete cote serveur.
|
||||
Toute collection API est paginee (defaut 10, max 50 ; `?pagination=false` = echappatoire selects, `?itemsPerPage=25` borne par le max). Standard global dans `config/packages/api_platform.yaml`. Jamais `paginationEnabled: false` hors whitelist `CollectionsArePaginatedTest::EXCLUDED`. Provider custom : ne jamais retourner un `array` brut sur une `CollectionOperationInterface` (court-circuite Hydra) — wrapper un Paginator (ORM : `ApiPlatform\Doctrine\Orm\Paginator` ; DBAL : `DbalPaginator`) et gerer `?pagination=false` via `$this->pagination->isEnabled(...)`.
|
||||
|
||||
### Standard global
|
||||
|
||||
Pose dans `config/packages/api_platform.yaml` (section `defaults:`) et heritee par toutes les ressources :
|
||||
|
||||
| Cle | Valeur | Effet |
|
||||
|---|---|---|
|
||||
| `pagination_enabled` | `true` | Pagination Hydra active par defaut. |
|
||||
| `pagination_items_per_page` | `10` | Taille de page par defaut, aligne sur l'UI `MalioDataTable`. |
|
||||
| `pagination_maximum_items_per_page` | `50` | Borne dure : `?itemsPerPage=999` → ramene a 50. Anti deep-fetch. |
|
||||
| `pagination_client_items_per_page` | `true` | Le client peut envoyer `?itemsPerPage=25` (bornee par le max). |
|
||||
| `pagination_client_enabled` | `true` | Le client peut envoyer `?pagination=false` pour TOUT recuperer (echappatoire selects). |
|
||||
|
||||
### Override par ressource (rare)
|
||||
|
||||
Si une ressource a besoin d'un autre defaut (ex: payload lourd), utiliser les attributs sur l'operation. **JAMAIS `paginationEnabled: false`** sans whitelist explicite dans `tests/Architecture/CollectionsArePaginatedTest::EXCLUDED`.
|
||||
|
||||
```php
|
||||
new GetCollection(
|
||||
paginationItemsPerPage: 5, // override taille par defaut
|
||||
paginationMaximumItemsPerPage: 20, // override borne max
|
||||
)
|
||||
```
|
||||
|
||||
### Selects et autocompletions
|
||||
|
||||
Pour alimenter un `<select>` ou un drawer RBAC (Role, Permission, Site, CategoryType), le front passe :
|
||||
|
||||
```ts
|
||||
useApi().get('/api/roles?pagination=false')
|
||||
```
|
||||
|
||||
Le serveur retourne toute la collection, sans `view`. C'est l'echappatoire prevue par `pagination_client_enabled: true`. Sur les ressources a forte volumetrie, preferer une saisie assistee (recherche serveur via `?q=`) — a planifier dans un ticket dedie.
|
||||
|
||||
Les tests fonctionnels qui exercent ce comportement doivent egalement passer `?pagination=false` (cf. `CategoryListTest`, `PermissionApiTest`).
|
||||
|
||||
### Providers customs et pagination
|
||||
|
||||
Un provider custom qui retourne un `array` brut sur une `CollectionOperationInterface` **court-circuite la pagination Hydra** (pas de `totalItems`, pas de `view`). Patterns supportes :
|
||||
|
||||
- **ORM** : injecter `ApiPlatform\State\Pagination\Pagination`, wrap un `Doctrine\ORM\Tools\Pagination\Paginator` dans `ApiPlatform\Doctrine\Orm\Paginator`. Exemple : `CategoryProvider`.
|
||||
- **DBAL** : implementer un paginator local conforme a `PaginatorInterface`. Exemple : `DbalPaginator` (Core) + `AuditLogProvider`.
|
||||
|
||||
Gerer l'echappatoire `?pagination=false` :
|
||||
|
||||
```php
|
||||
if (!$this->pagination->isEnabled($operation, $context)) {
|
||||
return $qb->getQuery()->getResult(); // tout retourner
|
||||
}
|
||||
```
|
||||
|
||||
### Garde-fou architecture
|
||||
|
||||
`tests/Architecture/CollectionsArePaginatedTest` scanne reflexivement toutes les classes `#[ApiResource]` sous `src/` et echoue si une `GetCollection` pose `paginationEnabled: false` hors whitelist `EXCLUDED`. Ajouter une entree a la whitelist requiert une justification courte + un ticket Lesstime ouvert.
|
||||
Garde-fou : `tests/Architecture/CollectionsArePaginatedTest` (casse `make test`).
|
||||
→ tableau des cles `pagination_*` + selects + providers ORM/DBAL detailles : skill `backend-entity-conventions`.
|
||||
|
||||
## Repositories
|
||||
|
||||
@@ -100,42 +56,17 @@ Format obligatoire : `module.resource[.subresource].action` en snake_case.
|
||||
|
||||
### Libelle i18n du type d'entite (obligatoire avec `#[Auditable]`)
|
||||
|
||||
**Toute entite `#[Auditable]` doit avoir son libelle FR dans le bloc `audit.entity` de `frontend/i18n/locales/fr.json`.** C'est la contrepartie i18n de l'attribut : sans elle, le filtre « Type d'entite » de l'audit-log affiche le type technique brut (ex: `commercial.Client`) au lieu d'un libelle lisible.
|
||||
Toute entite `#[Auditable]` doit avoir sa cle `audit.entity.<module>_<entity>` dans `frontend/i18n/locales/fr.json` (cle = `strtolower(module)` + `_` + `strtolower(Entity)`, decision ERP-99). Sans elle, le filtre « Type d'entite » de l'audit-log retombe silencieusement sur le type technique brut (ex: `commercial.Client`). Fait partie de la definition de fini d'une entite auditee.
|
||||
|
||||
Pourquoi : le filtre est dynamique (`GET /audit-log-entity-types` renvoie les `entity_type` distincts presents en base) ; des qu'un module audite une entite, son type y apparait. Le front (`formatEntityType`, `audit-log.vue`) construit la cle `audit.entity.<module>_<entity>` et, faute de traduction, **retombe silencieusement** sur le type brut.
|
||||
|
||||
Derivation de la cle (emplacement centralise + schema flat — decision ERP-99) :
|
||||
|
||||
| FQCN entite | `entity_type` (back) | Cle i18n (flat) |
|
||||
|---|---|---|
|
||||
| `App\Module\Commercial\Domain\Entity\Client` | `commercial.Client` | `commercial_client` |
|
||||
| `App\Module\Commercial\Domain\Entity\ClientAddress` | `commercial.ClientAddress` | `commercial_clientaddress` |
|
||||
| `App\Module\Catalog\Domain\Entity\Category` | `catalog.Category` | `catalog_category` |
|
||||
|
||||
Regle : `strtolower(module)` + `_` + `strtolower(Entity)`. Ajouter sa cle de libelle audit fait partie de la **definition de fini** d'une entite metier auditee.
|
||||
|
||||
**Garde-fou** : `tests/Architecture/AuditableEntitiesHaveI18nLabelTest` scanne les entites `#[Auditable]` et echoue si une seule n'a pas sa cle `audit.entity.*`. Conclusion : creer une entite `#[Auditable]` sans son libelle i18n casse `make test`.
|
||||
Garde-fou : `tests/Architecture/AuditableEntitiesHaveI18nLabelTest` (casse `make test`).
|
||||
→ derivation detaillee + exemples : skill `backend-entity-conventions`.
|
||||
|
||||
## Timestampable + Blamable (obligatoire pour entites metier)
|
||||
|
||||
Toute **nouvelle** entite metier sous `src/Module/*/Domain/Entity/` doit porter les 4 colonnes `created_at` / `updated_at` / `created_by` / `updated_by`, remplies automatiquement. Trois lignes a ajouter a l'entite :
|
||||
Toute **nouvelle** entite metier sous `src/Module/*/Domain/Entity/` : `implements TimestampableInterface, BlamableInterface` + `use TimestampableBlamableTrait` (porte les 4 colonnes `created_at` / `updated_at` / `created_by` / `updated_by`, remplies par `TimestampableBlamableSubscriber` au prePersist/preUpdate). La migration cree les 4 colonnes (`created_at`/`updated_at` NOT NULL, `created_by`/`updated_by` nullable `ON DELETE SET NULL`). Referentiel statique justifie : whitelist `EntitiesAreTimestampableBlamableTest::EXCLUDED`.
|
||||
|
||||
```php
|
||||
use App\Shared\Domain\Contract\BlamableInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
|
||||
class MyEntity implements TimestampableInterface, BlamableInterface
|
||||
{
|
||||
use TimestampableBlamableTrait; // porte les 4 props + getters/setters
|
||||
// ... reste metier
|
||||
}
|
||||
```
|
||||
|
||||
- Le `TimestampableBlamableSubscriber` (`Shared/Infrastructure/Doctrine/`) remplit les colonnes au `prePersist` / `preUpdate`. Hors contexte HTTP (CLI, cron, migration), le blame reste `null` (libelle « Systeme » cote front).
|
||||
- La migration de l'entite doit creer les 4 colonnes (`created_at` / `updated_at` NOT NULL, `created_by` / `updated_by` nullable `ON DELETE SET NULL`).
|
||||
- **Garde-fou CI** : `tests/Architecture/EntitiesAreTimestampableBlamableTest` echoue si une entite oublie le pattern. Un referentiel statique justifie (ex: `CategoryType`) doit etre explicitement whiteliste dans la constante `EXCLUDED` avec un commentaire.
|
||||
- Spec complete : @docs/specs/M0-categories/spec-back.md § 2.8 + § 2.8.bis
|
||||
Garde-fou : `tests/Architecture/EntitiesAreTimestampableBlamableTest` (casse `make test`).
|
||||
→ snippet complet : skill `backend-entity-conventions` ; spec : @docs/specs/M0-categories/spec-back.md § 2.8 + § 2.8.bis.
|
||||
|
||||
## Serialization
|
||||
|
||||
@@ -153,50 +84,7 @@ Exemple : pour qu'`User.profile` soit embarque au lieu d'un lien IRI sous le gro
|
||||
|
||||
## Migrations Doctrine
|
||||
|
||||
### Documentation SQL obligatoire (`COMMENT ON COLUMN`)
|
||||
Toute migration creant/modifiant une colonne d'une table metier pose un `COMMENT ON COLUMN` (FR, ≤ 200 caracteres, semantique + contrainte/RG, cible pour les FK). Les 4 colonnes Timestampable/Blamable recoivent leur description via le helper centralise `addStandardTimestampableBlamableComments($schema, 'table')`. Bonus : `COMMENT ON TABLE` pour decrire la table.
|
||||
|
||||
**Toute migration qui cree ou modifie une colonne d'une table metier doit poser un `COMMENT ON COLUMN` decrivant le champ.** La description est stockee dans `pg_description` et visible dans tous les outils d'admin BDD (DBeaver, DataGrip, pgAdmin), sans avoir a lire les annotations PHP.
|
||||
|
||||
**Format de la description** :
|
||||
- En francais
|
||||
- ≤ 200 caracteres
|
||||
- Semantique du champ — contraintes / lien RG si pertinent
|
||||
- Pour les colonnes d'identifiant ou FK, mentionner la cible
|
||||
|
||||
Exemples :
|
||||
|
||||
```php
|
||||
// Migration : creation d'une colonne avec son commentaire dans la meme migration
|
||||
$this->addSql("ALTER TABLE client ADD COLUMN siren VARCHAR(9) DEFAULT NULL");
|
||||
$this->addSql("COMMENT ON COLUMN client.siren IS 'SIREN (9 chiffres) — identifiant legal entreprise. Unique parmi non-archives (RG-1.15).'");
|
||||
|
||||
// Cas FK : preciser la cible
|
||||
$this->addSql("COMMENT ON COLUMN client.legal_form_id IS 'Reference forme juridique (SARL, SAS, SA...) — FK -> legal_form.id, ON DELETE RESTRICT.'");
|
||||
|
||||
// Cas booleen : preciser le sens et la valeur par defaut
|
||||
$this->addSql("COMMENT ON COLUMN user.is_admin IS 'Drapeau super-administrateur — bypass complet RBAC. Faux par defaut.'");
|
||||
|
||||
// Bonus : decrire la table elle-meme
|
||||
$this->addSql("COMMENT ON TABLE client IS 'Repertoire clients (M1 Commercial) — entites archivables.'");
|
||||
```
|
||||
|
||||
### Helper Timestampable/Blamable
|
||||
|
||||
Les 4 colonnes `created_at`, `updated_at`, `created_by`, `updated_by` ajoutees par `TimestampableBlamableTrait` recoivent une description **standardisee** via le helper centralise pour eviter la duplication. Helper a creer ou appeler :
|
||||
|
||||
```php
|
||||
// Dans la migration, apres avoir ajoute les 4 colonnes :
|
||||
$this->addStandardTimestampableBlamableComments($schema, 'client');
|
||||
```
|
||||
|
||||
L'implementation du helper applique :
|
||||
- `created_at` : « Horodatage de creation de la ligne (UTC, rempli automatiquement par TimestampableBlamableSubscriber). »
|
||||
- `updated_at` : « Horodatage de derniere modification de la ligne (UTC, rempli automatiquement par TimestampableBlamableSubscriber). »
|
||||
- `created_by` : « ID de l'utilisateur ayant cree la ligne — null pour les creations hors HTTP (CLI, migration, fixture). FK -> user.id, ON DELETE SET NULL. »
|
||||
- `updated_by` : « ID de l'utilisateur ayant modifie la ligne en dernier — null pour les modifications hors HTTP. FK -> user.id, ON DELETE SET NULL. »
|
||||
|
||||
### Garde-fou architecture
|
||||
|
||||
`tests/Architecture/ColumnsHaveSqlCommentTest` parcourt `information_schema.columns` filtre sur le schema `public` et echoue si **une seule colonne** n'a pas de `col_description`. Seules les tables system (`doctrine_migration_versions`) et la whitelist `EXCLUDED_TABLES` explicite (commentaire de justification + ticket Lesstime ouvert pour le retrofit) sont tolerees.
|
||||
|
||||
Conclusion : si tu crees une colonne sans poser son `COMMENT ON COLUMN`, `make test` casse en CI.
|
||||
Garde-fou : `tests/Architecture/ColumnsHaveSqlCommentTest` parcourt `information_schema.columns` (schema `public`) ; une seule colonne sans `col_description` casse `make test` (hors `EXCLUDED_TABLES`).
|
||||
→ exemples SQL + textes du helper : skill `backend-entity-conventions`.
|
||||
|
||||
@@ -44,6 +44,10 @@ Tout champ de formulaire / filtre doit utiliser les composants `Malio*` plutot q
|
||||
|
||||
Toute autre exception requiert validation avant merge.
|
||||
|
||||
## Standard ecran formulaire — reference : ecran Client
|
||||
|
||||
**Tout nouvel ecran de formulaire doit ressembler au premier ecran Client** (`frontend/modules/commercial/pages/clients/new.vue` + `[id]/edit.vue`) : meme structure (bloc principal puis onglets), memes marges/espacements, memes blocs de collection (ajout/suppression inline), meme validation inline 422 par champ. C'est la reference visuelle et fonctionnelle des formulaires du projet — s'en inspirer avant d'en creer un nouveau.
|
||||
|
||||
## Validation des formulaires — useFormErrors obligatoire (erreur par champ)
|
||||
|
||||
**Tout formulaire qui soumet a une API DOIT afficher les erreurs de validation 422 sous le champ concerne, via `useFormErrors`** (`frontend/shared/composables/useFormErrors.ts`). C'est le pendant front de « le back renvoie TOUTES les violations d'une 422 d'un coup » : un seul aller-retour, chaque erreur affichee inline sous son champ (prop `:error` des `Malio*`), pas un toast fourre-tout.
|
||||
@@ -142,6 +146,18 @@ A NE PAS faire :
|
||||
- Seuls les deep links "de navigation metier" (ex: ouvrir un detail precis `/users/42`) sont dans l'URL
|
||||
- Exceptions autorisees **sur demande explicite** de l'utilisateur
|
||||
|
||||
## Validation des formulaires (standard ERP-101)
|
||||
|
||||
Regle transverse a TOUS les formulaires front (et a rappeler a l'ecriture de chaque ticket back/front portant un formulaire). Decidee en ERP-101 (declencheur : ecran « Ajouter un client » ERP-63).
|
||||
|
||||
- **Champs obligatoires** : prop `required` du composant `Malio*` + etoile (asterisque) rouge dans le label. Ne JAMAIS griser le bouton « Valider » sans feedback : bouton toujours actif + erreurs affichees sous les champs.
|
||||
- **Couche de validation autoritaire = le back** : les RG sont re-validees serveur (mode strict). Au `422`, mapper `violations[].propertyPath` vers la prop `error` du champ via `extractApiViolations` (deja utilise par `useCategoryForm`). Zero duplication de RG, zero drift.
|
||||
- **Feedback instantane au blur** : uniquement requis / min / max / format (pas de re-implementation des RG metier cote front).
|
||||
- **Regles front-only** : celles sans equivalent back (ex. FK nullable cote back mais obligatoire selon un choix UI) sont validees et affichees cote front.
|
||||
- **Email — PAS de masque** : un email n'a pas de structure fixe. Normalisation via la prop `lowercase` de `MalioInputEmail` (trim + suppression des espaces + lowercase, coherent avec la normalisation serveur RG-1.21). Le format est valide par la prop `error` (violations serveur ou check au blur), jamais par un masque. Retirer tout shaping email ad hoc des ecrans.
|
||||
- **Contrat back attendu** : tout `422` issu d'un Processor/Validator doit porter `violations[].propertyPath` aligne sur les noms de champs du formulaire, pour etre consommable par `extractApiViolations`.
|
||||
- **Dependance** : le branchement des props `required` suppose `@malio/layer-ui` a jour (props `required` + etoile — MUI-41 / ERP-101).
|
||||
|
||||
## Interdits
|
||||
|
||||
- `modules-loader.ts`, `.module.ts` — le scan des layers est automatique
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
---
|
||||
name: backend-entity-conventions
|
||||
description: Conventions détaillées des entités métier Starseed (back PHP/Symfony/API Platform) — messages de validation FR sur les contraintes, pagination API Platform et providers ORM/DBAL, libellé i18n du type d'entité auditée, Timestampable/Blamable, COMMENT ON COLUMN des migrations. Charger dès qu'on crée ou modifie une entité Domain, un ApiResource, un Provider/Processor, une contrainte de validation, ou une migration Doctrine. Le résumé court de chaque règle (+ nom du test garde-fou) reste dans .claude/rules/backend.md ; ce skill porte les patterns, tableaux et exemples complets.
|
||||
---
|
||||
|
||||
# Conventions entités métier — détail
|
||||
|
||||
Ce skill contient le détail (patterns code, tableaux, dérivations) des 5 règles back qui ont chacune
|
||||
un test Architecture déterministe. L'énoncé court de chaque règle vit dans `.claude/rules/backend.md`
|
||||
(chargé à chaque session) ; ici on trouve le « comment » complet.
|
||||
|
||||
> Règle d'or : le **test Architecture reste le juge** (il casse `make test`). Ce skill aide à écrire
|
||||
> le code juste du premier coup, il ne remplace pas le garde-fou.
|
||||
|
||||
---
|
||||
|
||||
## 1. Messages de validation (Garde-fou : `EntityConstraintsHaveFrenchMessageTest`)
|
||||
|
||||
**Toute contrainte `#[Assert\*]` portée par une entité métier doit avoir un message FR explicite**, et
|
||||
**`Assert\Length.max` doit refléter le `length` de la colonne ORM**. C'est le pendant back du mapping
|
||||
d'erreur par champ côté front (ERP-101 : `useFormErrors` / `mapViolationsToRecord` affiche sous chaque
|
||||
champ le `message` renvoyé par le back).
|
||||
|
||||
Pourquoi :
|
||||
- Sans `message:` explicite, Symfony renvoie le défaut **anglais** (« This value is not a valid email
|
||||
address. »). La locale FR globale (`default_locale: fr` dans `framework.yaml`) sert de FILET via
|
||||
`validators.fr.xlf`, mais les contraintes métier portent en plus leur message FR pour un contrôle total.
|
||||
- Une colonne string bornée **sans `Assert\Length`** échoue au niveau Postgres (500 générique, non
|
||||
rattachée au champ) au lieu d'une 422 propre. Le `max` doit égaler le `length` ORM (anti-dérive).
|
||||
|
||||
Pattern par champ scalaire :
|
||||
|
||||
```php
|
||||
// Email métier
|
||||
#[Assert\Email(message: 'L\'adresse email n\'est pas valide.')]
|
||||
|
||||
// Longueur calée sur la colonne (VARCHAR(120))
|
||||
#[ORM\Column(length: 120)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le nom ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
|
||||
// Obligatoire (aligner nullable DB / NotBlank back / required front)
|
||||
#[Assert\NotBlank(message: 'Le téléphone est obligatoire.', normalizer: 'trim')]
|
||||
```
|
||||
|
||||
Cohérence à 3 niveaux pour un champ obligatoire : colonne `nullable` (DB) <-> `Assert\NotBlank` (back)
|
||||
<-> `:required` + astérisque (front ERP-101). Les trois doivent s'accorder.
|
||||
|
||||
Exceptions au miroir `Length` : un format déjà borné par `Assert\Bic` / `Assert\Iban` (longueur
|
||||
garantie) ou par un `Assert\Regex` borné (ex. code postal `{4,5}`, couleur hex `#RRGGBB`) — whitelister
|
||||
alors la propriété dans `EntityConstraintsHaveFrenchMessageTest::EXCLUDED_LENGTH_MIRROR` avec justification.
|
||||
|
||||
Les règles inter-champs (RG métier : exclusivité distributor/broker RG-1.03, billingEmail RG-1.11, etc.)
|
||||
passent par un `#[Assert\Callback]` qui construit la violation avec `->atPath('<champ>')` — indispensable
|
||||
pour que le front la mappe en inline plutôt qu'en toast.
|
||||
|
||||
### Garde-fou architecture
|
||||
|
||||
`tests/Architecture/EntityConstraintsHaveFrenchMessageTest` scanne réflexivement les entités sous
|
||||
`src/Module/*/Domain/Entity/` et échoue si :
|
||||
1. une contrainte connue n'a pas de message FR explicite (comparé au défaut Symfony) ;
|
||||
2. une colonne string bornée writable n'a pas de `Assert\Length(max == ORM length)` (hors whitelist).
|
||||
|
||||
Une contrainte non gérée par le mapping du test le fait échouer : il faut l'ajouter explicitement
|
||||
(anti faux positif vert).
|
||||
|
||||
---
|
||||
|
||||
## 2. Pagination (Garde-fou : `CollectionsArePaginatedTest`)
|
||||
|
||||
**Règle** : toute collection API DOIT être paginée. Aucun retour de collection complète côté serveur.
|
||||
|
||||
### Standard global
|
||||
|
||||
Posé dans `config/packages/api_platform.yaml` (section `defaults:`) et hérité par toutes les ressources :
|
||||
|
||||
| Clé | Valeur | Effet |
|
||||
|---|---|---|
|
||||
| `pagination_enabled` | `true` | Pagination Hydra active par défaut. |
|
||||
| `pagination_items_per_page` | `10` | Taille de page par défaut, alignée sur l'UI `MalioDataTable`. |
|
||||
| `pagination_maximum_items_per_page` | `50` | Borne dure : `?itemsPerPage=999` → ramené à 50. Anti deep-fetch. |
|
||||
| `pagination_client_items_per_page` | `true` | Le client peut envoyer `?itemsPerPage=25` (bornée par le max). |
|
||||
| `pagination_client_enabled` | `true` | Le client peut envoyer `?pagination=false` pour TOUT récupérer (échappatoire selects). |
|
||||
|
||||
### Override par ressource (rare)
|
||||
|
||||
Si une ressource a besoin d'un autre défaut (ex: payload lourd), utiliser les attributs sur l'opération.
|
||||
**JAMAIS `paginationEnabled: false`** sans whitelist explicite dans
|
||||
`tests/Architecture/CollectionsArePaginatedTest::EXCLUDED`.
|
||||
|
||||
```php
|
||||
new GetCollection(
|
||||
paginationItemsPerPage: 5, // override taille par défaut
|
||||
paginationMaximumItemsPerPage: 20, // override borne max
|
||||
)
|
||||
```
|
||||
|
||||
### Selects et autocomplétions
|
||||
|
||||
Pour alimenter un `<select>` ou un drawer RBAC (Role, Permission, Site, CategoryType), le front passe :
|
||||
|
||||
```ts
|
||||
useApi().get('/api/roles?pagination=false')
|
||||
```
|
||||
|
||||
Le serveur retourne toute la collection, sans `view`. C'est l'échappatoire prévue par
|
||||
`pagination_client_enabled: true`. Sur les ressources à forte volumétrie, préférer une saisie assistée
|
||||
(recherche serveur via `?q=`) — à planifier dans un ticket dédié.
|
||||
|
||||
Les tests fonctionnels qui exercent ce comportement doivent également passer `?pagination=false`
|
||||
(cf. `CategoryListTest`, `PermissionApiTest`).
|
||||
|
||||
### Providers customs et pagination
|
||||
|
||||
Un provider custom qui retourne un `array` brut sur une `CollectionOperationInterface`
|
||||
**court-circuite la pagination Hydra** (pas de `totalItems`, pas de `view`). Patterns supportés :
|
||||
|
||||
- **ORM** : injecter `ApiPlatform\State\Pagination\Pagination`, wrap un
|
||||
`Doctrine\ORM\Tools\Pagination\Paginator` dans `ApiPlatform\Doctrine\Orm\Paginator`. Exemple : `CategoryProvider`.
|
||||
- **DBAL** : implémenter un paginator local conforme à `PaginatorInterface`. Exemple : `DbalPaginator`
|
||||
(Core) + `AuditLogProvider`.
|
||||
|
||||
Gérer l'échappatoire `?pagination=false` :
|
||||
|
||||
```php
|
||||
if (!$this->pagination->isEnabled($operation, $context)) {
|
||||
return $qb->getQuery()->getResult(); // tout retourner
|
||||
}
|
||||
```
|
||||
|
||||
### Garde-fou architecture
|
||||
|
||||
`tests/Architecture/CollectionsArePaginatedTest` scanne réflexivement toutes les classes
|
||||
`#[ApiResource]` sous `src/` et échoue si une `GetCollection` pose `paginationEnabled: false` hors
|
||||
whitelist `EXCLUDED`. Ajouter une entrée à la whitelist requiert une justification courte + un ticket
|
||||
Lesstime ouvert.
|
||||
|
||||
---
|
||||
|
||||
## 3. Libellé i18n du type d'entité auditée (Garde-fou : `AuditableEntitiesHaveI18nLabelTest`)
|
||||
|
||||
**Toute entité `#[Auditable]` doit avoir son libellé FR dans le bloc `audit.entity` de
|
||||
`frontend/i18n/locales/fr.json`.** C'est la contrepartie i18n de l'attribut : sans elle, le filtre
|
||||
« Type d'entité » de l'audit-log affiche le type technique brut (ex: `commercial.Client`) au lieu d'un
|
||||
libellé lisible.
|
||||
|
||||
Pourquoi : le filtre est dynamique (`GET /audit-log-entity-types` renvoie les `entity_type` distincts
|
||||
présents en base) ; dès qu'un module audite une entité, son type y apparaît. Le front
|
||||
(`formatEntityType`, `audit-log.vue`) construit la clé `audit.entity.<module>_<entity>` et, faute de
|
||||
traduction, **retombe silencieusement** sur le type brut.
|
||||
|
||||
Dérivation de la clé (emplacement centralisé + schéma flat — décision ERP-99) :
|
||||
|
||||
| FQCN entité | `entity_type` (back) | Clé i18n (flat) |
|
||||
|---|---|---|
|
||||
| `App\Module\Commercial\Domain\Entity\Client` | `commercial.Client` | `commercial_client` |
|
||||
| `App\Module\Commercial\Domain\Entity\ClientAddress` | `commercial.ClientAddress` | `commercial_clientaddress` |
|
||||
| `App\Module\Catalog\Domain\Entity\Category` | `catalog.Category` | `catalog_category` |
|
||||
|
||||
Règle : `strtolower(module)` + `_` + `strtolower(Entity)`. Ajouter sa clé de libellé audit fait partie
|
||||
de la **définition de fini** d'une entité métier auditée.
|
||||
|
||||
**Garde-fou** : `tests/Architecture/AuditableEntitiesHaveI18nLabelTest` scanne les entités `#[Auditable]`
|
||||
et échoue si une seule n'a pas sa clé `audit.entity.*`. Conclusion : créer une entité `#[Auditable]`
|
||||
sans son libellé i18n casse `make test`.
|
||||
|
||||
---
|
||||
|
||||
## 4. Timestampable + Blamable (Garde-fou : `EntitiesAreTimestampableBlamableTest`)
|
||||
|
||||
Toute **nouvelle** entité métier sous `src/Module/*/Domain/Entity/` doit porter les 4 colonnes
|
||||
`created_at` / `updated_at` / `created_by` / `updated_by`, remplies automatiquement. Trois lignes à
|
||||
ajouter à l'entité :
|
||||
|
||||
```php
|
||||
use App\Shared\Domain\Contract\BlamableInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
|
||||
class MyEntity implements TimestampableInterface, BlamableInterface
|
||||
{
|
||||
use TimestampableBlamableTrait; // porte les 4 props + getters/setters
|
||||
// ... reste métier
|
||||
}
|
||||
```
|
||||
|
||||
- Le `TimestampableBlamableSubscriber` (`Shared/Infrastructure/Doctrine/`) remplit les colonnes au
|
||||
`prePersist` / `preUpdate`. Hors contexte HTTP (CLI, cron, migration), le blame reste `null`
|
||||
(libellé « Système » côté front).
|
||||
- La migration de l'entité doit créer les 4 colonnes (`created_at` / `updated_at` NOT NULL,
|
||||
`created_by` / `updated_by` nullable `ON DELETE SET NULL`).
|
||||
- **Garde-fou CI** : `tests/Architecture/EntitiesAreTimestampableBlamableTest` échoue si une entité
|
||||
oublie le pattern. Un référentiel statique justifié (ex: `CategoryType`) doit être explicitement
|
||||
whitelisté dans la constante `EXCLUDED` avec un commentaire.
|
||||
- Spec complète : @docs/specs/M0-categories/spec-back.md § 2.8 + § 2.8.bis
|
||||
|
||||
---
|
||||
|
||||
## 5. Migrations Doctrine — COMMENT ON COLUMN (Garde-fou : `ColumnsHaveSqlCommentTest`)
|
||||
|
||||
**Toute migration qui crée ou modifie une colonne d'une table métier doit poser un `COMMENT ON COLUMN`
|
||||
décrivant le champ.** La description est stockée dans `pg_description` et visible dans tous les outils
|
||||
d'admin BDD (DBeaver, DataGrip, pgAdmin), sans avoir à lire les annotations PHP.
|
||||
|
||||
**Format de la description** :
|
||||
- En français
|
||||
- ≤ 200 caractères
|
||||
- Sémantique du champ — contraintes / lien RG si pertinent
|
||||
- Pour les colonnes d'identifiant ou FK, mentionner la cible
|
||||
|
||||
Exemples :
|
||||
|
||||
```php
|
||||
// Migration : création d'une colonne avec son commentaire dans la même migration
|
||||
$this->addSql("ALTER TABLE client ADD COLUMN siren VARCHAR(9) DEFAULT NULL");
|
||||
$this->addSql("COMMENT ON COLUMN client.siren IS 'SIREN (9 chiffres) — identifiant legal entreprise. Unique parmi non-archives (RG-1.15).'");
|
||||
|
||||
// Cas FK : préciser la cible
|
||||
$this->addSql("COMMENT ON COLUMN client.legal_form_id IS 'Reference forme juridique (SARL, SAS, SA...) — FK -> legal_form.id, ON DELETE RESTRICT.'");
|
||||
|
||||
// Cas booléen : préciser le sens et la valeur par défaut
|
||||
$this->addSql("COMMENT ON COLUMN user.is_admin IS 'Drapeau super-administrateur — bypass complet RBAC. Faux par defaut.'");
|
||||
|
||||
// Bonus : décrire la table elle-même
|
||||
$this->addSql("COMMENT ON TABLE client IS 'Repertoire clients (M1 Commercial) — entites archivables.'");
|
||||
```
|
||||
|
||||
### Helper Timestampable/Blamable
|
||||
|
||||
Les 4 colonnes `created_at`, `updated_at`, `created_by`, `updated_by` ajoutées par
|
||||
`TimestampableBlamableTrait` reçoivent une description **standardisée** via le helper centralisé pour
|
||||
éviter la duplication. Helper à créer ou appeler :
|
||||
|
||||
```php
|
||||
// Dans la migration, après avoir ajouté les 4 colonnes :
|
||||
$this->addStandardTimestampableBlamableComments($schema, 'client');
|
||||
```
|
||||
|
||||
L'implémentation du helper applique :
|
||||
- `created_at` : « Horodatage de creation de la ligne (UTC, rempli automatiquement par TimestampableBlamableSubscriber). »
|
||||
- `updated_at` : « Horodatage de derniere modification de la ligne (UTC, rempli automatiquement par TimestampableBlamableSubscriber). »
|
||||
- `created_by` : « ID de l'utilisateur ayant cree la ligne — null pour les creations hors HTTP (CLI, migration, fixture). FK -> user.id, ON DELETE SET NULL. »
|
||||
- `updated_by` : « ID de l'utilisateur ayant modifie la ligne en dernier — null pour les modifications hors HTTP. FK -> user.id, ON DELETE SET NULL. »
|
||||
|
||||
### Garde-fou architecture
|
||||
|
||||
`tests/Architecture/ColumnsHaveSqlCommentTest` parcourt `information_schema.columns` filtré sur le
|
||||
schéma `public` et échoue si **une seule colonne** n'a pas de `col_description`. Seules les tables
|
||||
système (`doctrine_migration_versions`) et la whitelist `EXCLUDED_TABLES` explicite (commentaire de
|
||||
justification + ticket Lesstime ouvert pour le retrofit) sont tolérées.
|
||||
|
||||
Conclusion : si tu crées une colonne sans poser son `COMMENT ON COLUMN`, `make test` casse en CI.
|
||||
@@ -75,7 +75,7 @@ jobs:
|
||||
- name: Bootstrap test database
|
||||
# Aligne sur la cible `test-db-setup` du makefile : apres
|
||||
# `schema:update --force`, on RECREE manuellement l'index unique
|
||||
# partiel `uq_category_name_type_active` car Doctrine ORM ne sait
|
||||
# partiel `uq_category_name_active` car Doctrine ORM ne sait
|
||||
# pas exprimer les index fonctionnels partiels (LOWER(name) + WHERE
|
||||
# deleted_at IS NULL) et `schema:update` les considere comme
|
||||
# orphelins et les DROP — collisions non detectees, tests d'unicite
|
||||
@@ -89,7 +89,7 @@ jobs:
|
||||
php bin/console app:apply-column-comments --env=test --no-interaction
|
||||
php bin/console doctrine:fixtures:load --env=test --no-interaction
|
||||
php bin/console app:sync-permissions --env=test --no-interaction
|
||||
php bin/console --env=test dbal:run-sql "CREATE UNIQUE INDEX IF NOT EXISTS uq_category_name_type_active ON category (LOWER(name), category_type_id) WHERE deleted_at IS NULL"
|
||||
php bin/console --env=test dbal:run-sql "CREATE UNIQUE INDEX IF NOT EXISTS uq_category_name_active ON category (LOWER(name)) WHERE deleted_at IS NULL"
|
||||
|
||||
- name: Run PHPUnit
|
||||
run: php -d memory_limit=512M vendor/bin/phpunit
|
||||
|
||||
@@ -141,7 +141,7 @@ Disponibles uniquement après `make db-reset` / `make fixtures` (état « avec s
|
||||
| `bob` | `bob` | ROLE_USER | — |
|
||||
| `bureau` | `demo` | ROLE_USER | clients : view + manage |
|
||||
| `compta` | `demo` | ROLE_USER | clients : view + accounting.view / manage |
|
||||
| `commerciale` | `demo` | ROLE_USER | clients : view + manage (Information obligatoire — RG-1.04) |
|
||||
| `commerciale` | `demo` | ROLE_USER | clients : view + manage |
|
||||
| `usine` | `demo` | ROLE_USER | aucun accès clients |
|
||||
|
||||
---
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
"symfony/runtime": "8.0.*",
|
||||
"symfony/security-bundle": "8.0.*",
|
||||
"symfony/serializer": "8.0.*",
|
||||
"symfony/translation": "8.0.*",
|
||||
"symfony/twig-bundle": "8.0.*",
|
||||
"symfony/uid": "8.0.*",
|
||||
"symfony/validator": "8.0.*",
|
||||
|
||||
Generated
+94
-1
@@ -4,7 +4,7 @@
|
||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"content-hash": "aada2e60fd7563f1498b5505b37e3f4b",
|
||||
"content-hash": "2dc5db01e7f5d6aecd5956749b21a092",
|
||||
"packages": [
|
||||
{
|
||||
"name": "api-platform/doctrine-common",
|
||||
@@ -7657,6 +7657,99 @@
|
||||
],
|
||||
"time": "2026-03-30T15:14:47+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/translation",
|
||||
"version": "v8.0.10",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/translation.git",
|
||||
"reference": "f63e9342e12646a57c91ef8a366a4f9d8e557b67"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/translation/zipball/f63e9342e12646a57c91ef8a366a4f9d8e557b67",
|
||||
"reference": "f63e9342e12646a57c91ef8a366a4f9d8e557b67",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=8.4",
|
||||
"symfony/polyfill-mbstring": "^1.0",
|
||||
"symfony/translation-contracts": "^3.6.1"
|
||||
},
|
||||
"conflict": {
|
||||
"nikic/php-parser": "<5.0",
|
||||
"symfony/http-client-contracts": "<2.5",
|
||||
"symfony/service-contracts": "<2.5"
|
||||
},
|
||||
"provide": {
|
||||
"symfony/translation-implementation": "2.3|3.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"nikic/php-parser": "^5.0",
|
||||
"psr/log": "^1|^2|^3",
|
||||
"symfony/config": "^7.4|^8.0",
|
||||
"symfony/console": "^7.4|^8.0",
|
||||
"symfony/dependency-injection": "^7.4|^8.0",
|
||||
"symfony/finder": "^7.4|^8.0",
|
||||
"symfony/http-client-contracts": "^2.5|^3.0",
|
||||
"symfony/http-kernel": "^7.4|^8.0",
|
||||
"symfony/intl": "^7.4|^8.0",
|
||||
"symfony/polyfill-intl-icu": "^1.21",
|
||||
"symfony/routing": "^7.4|^8.0",
|
||||
"symfony/service-contracts": "^2.5|^3",
|
||||
"symfony/yaml": "^7.4|^8.0"
|
||||
},
|
||||
"type": "library",
|
||||
"autoload": {
|
||||
"files": [
|
||||
"Resources/functions.php"
|
||||
],
|
||||
"psr-4": {
|
||||
"Symfony\\Component\\Translation\\": ""
|
||||
},
|
||||
"exclude-from-classmap": [
|
||||
"/Tests/"
|
||||
]
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Fabien Potencier",
|
||||
"email": "fabien@symfony.com"
|
||||
},
|
||||
{
|
||||
"name": "Symfony Community",
|
||||
"homepage": "https://symfony.com/contributors"
|
||||
}
|
||||
],
|
||||
"description": "Provides tools to internationalize your application",
|
||||
"homepage": "https://symfony.com",
|
||||
"support": {
|
||||
"source": "https://github.com/symfony/translation/tree/v8.0.10"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
"url": "https://symfony.com/sponsor",
|
||||
"type": "custom"
|
||||
},
|
||||
{
|
||||
"url": "https://github.com/fabpot",
|
||||
"type": "github"
|
||||
},
|
||||
{
|
||||
"url": "https://github.com/nicolas-grekas",
|
||||
"type": "github"
|
||||
},
|
||||
{
|
||||
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2026-05-06T11:30:54+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/translation-contracts",
|
||||
"version": "v3.6.1",
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
doctrine:
|
||||
dbal:
|
||||
connections:
|
||||
# Force le profiling DBAL en environnement de test independamment de
|
||||
# APP_DEBUG. Sans cela, la CI tourne en APP_DEBUG=0 (prod-like) et le
|
||||
# service `doctrine.debug_data_holder` n'est pas enregistre : le test
|
||||
# anti-N+1 (SupplierListTest::testListQueryCountDoesNotGrowWithRowCount)
|
||||
# qui compte les requetes via ce holder echoue alors en CI alors qu'il
|
||||
# passe en local (APP_DEBUG=1). Activer le profiling ici garde le test
|
||||
# actif precisement la ou il compte (CI), sans impacter la prod.
|
||||
default:
|
||||
profiling: true
|
||||
@@ -0,0 +1,12 @@
|
||||
framework:
|
||||
# Locale par defaut FR (ERP-107) : les messages natifs des contraintes
|
||||
# Symfony (Email, NotBlank, Length, Iban, Bic...) sont alors servis en
|
||||
# francais via validators.fr.xlf. C'est le FILET ; les contraintes metier
|
||||
# portent en plus un `message:` FR explicite, teste par
|
||||
# tests/Architecture/EntityConstraintsHaveFrenchMessageTest.
|
||||
default_locale: fr
|
||||
translator:
|
||||
default_path: '%kernel.project_dir%/translations'
|
||||
fallbacks:
|
||||
- fr
|
||||
providers:
|
||||
+5
-4
@@ -53,10 +53,11 @@ return [
|
||||
'permission' => 'commercial.clients.view',
|
||||
],
|
||||
[
|
||||
'label' => 'sidebar.commercial.suppliers',
|
||||
'to' => '/suppliers',
|
||||
'icon' => 'mdi:account-arrow-left-outline',
|
||||
'module' => 'commercial',
|
||||
'label' => 'sidebar.commercial.suppliers',
|
||||
'to' => '/suppliers',
|
||||
'icon' => 'mdi:account-arrow-left-outline',
|
||||
'module' => 'commercial',
|
||||
'permission' => 'commercial.suppliers.view',
|
||||
],
|
||||
],
|
||||
],
|
||||
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
parameters:
|
||||
app.version: '0.1.80'
|
||||
app.version: '0.1.97'
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
# Validation « tous les blocs » sur les onglets à blocs dynamiques (Client M1)
|
||||
|
||||
> Date : 2026-06-04 · Module : Commercial (M1 Clients) · Tickets liés : ERP-101 / ERP-107
|
||||
> Écrans : `clients/new.vue`, `clients/[id]/edit.vue` · Onglets concernés : Contacts, Adresses, RIB
|
||||
|
||||
## 1. Problème
|
||||
|
||||
À la soumission des onglets à **blocs d'ajout dynamiques** (Contacts / Adresses / RIB), la validation
|
||||
par champ ne s'affiche pas correctement. Deux causes **distinctes et cumulées** :
|
||||
|
||||
### Cause A — 500 back qui court-circuite la validation (cause racine)
|
||||
|
||||
Les opérations `Post` des sous-ressources sont déclarées ainsi :
|
||||
|
||||
```php
|
||||
new Post(
|
||||
uriTemplate: '/clients/{clientId}/contacts',
|
||||
uriVariables: ['clientId' => new Link(fromClass: Client::class, toProperty: 'client')],
|
||||
processor: ClientContactProcessor::class,
|
||||
)
|
||||
```
|
||||
|
||||
Au stade « read » du POST, API Platform résout `clientId` via `LinksHandlerTrait` (branche `toProperty`,
|
||||
`vendor/api-platform/doctrine-orm/State/LinksHandlerTrait.php:134-141`). La requête générée porte sur
|
||||
l'entité **enfant** :
|
||||
|
||||
```sql
|
||||
SELECT o FROM ClientContact o INNER JOIN o.client c WHERE c.id = :clientId
|
||||
```
|
||||
|
||||
exécutée via `ItemProvider::provide` → `getOneOrNullResult()`
|
||||
(`vendor/api-platform/doctrine-orm/State/ItemProvider.php:89`). Donc :
|
||||
|
||||
| Nb d'enfants du client | Lignes retournées | Résultat |
|
||||
|---|---|---|
|
||||
| 0 | 0 | `null` → OK (cas du test CI actuel) |
|
||||
| 1 | 1 | OK |
|
||||
| **≥ 2** | **≥ 2** | **`NonUniqueResultException` → HTTP 500** |
|
||||
|
||||
Conséquence : un client à ≥2 contacts (resp. adresses, RIB) ne peut plus en recevoir un nouveau.
|
||||
La 500 survient **avant** la déserialisation/validation → aucune 422 n'est produite → `mapRowError`
|
||||
(qui ne mappe que les 422) retombe sur un toast générique.
|
||||
|
||||
Les **3** sous-ressources ont strictement la même config → même bug latent (contacts est juste le
|
||||
premier à sauter car les clients de démo ont 3 contacts).
|
||||
|
||||
### Cause B — la boucle front s'arrête au premier bloc en erreur
|
||||
|
||||
`submitContacts` / `submitAddresses` / boucle RIB de `submitAccounting` (dans `new.vue` ET `edit.vue`)
|
||||
font `return` dans le `catch` du premier bloc en échec :
|
||||
|
||||
```js
|
||||
catch (error) {
|
||||
if (!mapRowError(error, contactErrors, index)) { toast(...) }
|
||||
return // ← stoppe : les blocs suivants ne sont jamais validés ni affichés
|
||||
}
|
||||
```
|
||||
|
||||
→ même une fois le 500 corrigé, seules les erreurs du **premier** bloc fautif s'afficheraient.
|
||||
|
||||
## 2. Objectif
|
||||
|
||||
À la validation d'un onglet collection, **tenter tous les blocs** et **afficher l'erreur inline sous
|
||||
chaque champ fautif, pour chaque bloc**, en un seul aller-retour de soumission. Pas de toast récapitulatif
|
||||
(décision : inline seul, cohérent ERP-101). Pas de toast succès tant qu'au moins un bloc reste en erreur.
|
||||
|
||||
Hors périmètre : le workflow incrémental (créer le client, puis débloquer les onglets) reste inchangé ;
|
||||
les onglets scalaires (Principal / Information / Comptabilité-scalaires) fonctionnent déjà et ne sont pas
|
||||
touchés.
|
||||
|
||||
## 3. Conception
|
||||
|
||||
### 3.1 Back — supprimer le read cassé du POST (cause racine)
|
||||
|
||||
Sur les opérations `Post` de `ClientContact`, `ClientAddress`, `ClientRib` :
|
||||
|
||||
- Ajouter **`read: false`**. Le stade « read » est inutile : le `*Processor::linkParent` rattache déjà le
|
||||
parent manuellement via `$em->getRepository(Client::class)->find($clientId)`. Pattern déjà employé dans
|
||||
le projet (`Sites/.../CurrentSiteResource.php`).
|
||||
- Durcir les 3 `linkParent` : si `find($clientId)` renvoie `null`, lever
|
||||
`Symfony\Component\HttpKernel\Exception\NotFoundHttpException` (préserve le **404** sur parent
|
||||
inexistant — sans le read, on régresserait sinon en 500 au persist sur `client_id NOT NULL`).
|
||||
|
||||
Effet : plus de `getOneOrNullResult` foireux → déserialisation + validation Symfony s'exécutent → **422
|
||||
propre par champ** avec `violations[].propertyPath` (déjà garanti par ERP-107 : messages FR explicites).
|
||||
|
||||
Aucune autre modification (security, normalizationContext, processor restant) n'est nécessaire.
|
||||
|
||||
### 3.2 Front — collecter les erreurs de tous les blocs
|
||||
|
||||
Dans `submitContacts`, `submitAddresses`, et la boucle RIB de `submitAccounting`, **dans `new.vue` ET
|
||||
`edit.vue`** :
|
||||
|
||||
- Conserver la réinitialisation du tableau d'erreurs en début de submit (`xxxErrors.value = []`).
|
||||
- Introduire un drapeau local `hasError`. Dans le `catch`, remplacer `return` par
|
||||
`hasError = true; continue` → la boucle tente/valide **tous** les blocs ; chaque 422 se mappe sur
|
||||
`xxxErrors[index]` via `mapRowError` (mécanique existante, inchangée).
|
||||
- Après la boucle : si `hasError` → **ne pas** appeler `completeTab(...)`, **pas** de toast succès. Sinon
|
||||
→ comportement actuel (`completeTab` + toast succès).
|
||||
- Les blocs déjà créés (id non-null) repassent en `PATCH` au resubmit → idempotent, pas de doublon.
|
||||
- Awaits **séquentiels** conservés (volume faible, ordre des blocs préservé, pas de course).
|
||||
|
||||
Le binding inline est déjà en place côté template (`:errors="contactErrors[index]"` /
|
||||
`:error="ribErrors[index]?.iban"` …). Aucun changement de composant `Malio*` requis.
|
||||
|
||||
### 3.3 Réutilisation / isolation
|
||||
|
||||
Le bloc « boucle de soumission d'une collection avec collecte d'erreurs par index » est dupliqué 3× × 2
|
||||
pages. Pour rester testable et DRY, extraire un helper de soumission de collection (ex.
|
||||
`submitCollection(rows, { buildBody, post, patch, errors })` retournant `{ hasError }`) consommé par les
|
||||
6 sites d'appel. À acter dans le plan d'implémentation (option : garder inline si l'extraction dégrade la
|
||||
lisibilité — décision lors du plan).
|
||||
|
||||
## 4. Tests
|
||||
|
||||
### Back (TDD — échouent d'abord)
|
||||
|
||||
Dans `tests/Module/Commercial/Api/ClientSubResourceApiTest` :
|
||||
|
||||
- `testPostContactToClientWithTwoExistingContactsReturns201` : seed un client + 2 contacts, POST un 3ᵉ →
|
||||
attendu **201** (rouge aujourd'hui : 500).
|
||||
- `testPostContactInvalidEmailOnClientWithExistingContactsReturns422` : même seed, POST email invalide →
|
||||
**422** avec `propertyPath=email` et message FR (vérifie que la validation est bien atteinte).
|
||||
- Variantes germes pour adresses et RIB (au moins une chacune) pour verrouiller les 3 sous-ressources.
|
||||
|
||||
Pré-requis : helper de seed de contacts/adresses/RIB dans `AbstractCommercialApiTestCase` (ajouter si
|
||||
absent).
|
||||
|
||||
### Front (Vitest)
|
||||
|
||||
- Si helper `submitCollection` extrait : test unitaire « 3 blocs, le 2ᵉ renvoie 422 → les erreurs du 2ᵉ
|
||||
sont mappées, les blocs 1 et 3 sont tentés, `hasError = true`, tab non complété ».
|
||||
- Sinon : test de composant sur `ClientContactBlock` + page, vérifiant l'affichage inline multi-blocs.
|
||||
|
||||
### Vérifications finales
|
||||
|
||||
`make test` + `make php-cs-fixer-allow-risky` (back), `make nuxt-test` (front). Golden path manuel :
|
||||
client à 3 contacts, ajouter un 4ᵉ avec email invalide → 422 inline sous l'email du bon bloc, pas de 500.
|
||||
|
||||
## 5. Impact / risques
|
||||
|
||||
- API contract : POST sous-ressource passe de 500→201/422 (correction) ; 404 préservé sur parent
|
||||
inexistant. Pas de changement de payload ni de réponse de succès.
|
||||
- Le test fonctionnel CI actuel (POST sur client à 0 contact) reste vert.
|
||||
- Régression possible si un consommateur dépendait du read implicite du parent au POST : aucun identifié
|
||||
(les 3 processors gèrent déjà le rattachement manuellement).
|
||||
@@ -0,0 +1,633 @@
|
||||
# Validation « tous les blocs » — onglets à blocs dynamiques (Client M1) — Plan d'implémentation
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Permettre la validation 422 par champ sur TOUS les blocs des onglets Contacts / Adresses / RIB d'un client (création + édition), en supprimant la 500 `NonUniqueResultException` qui les bloque dès ≥2 enfants et en ne stoppant plus la boucle front au premier bloc en erreur.
|
||||
|
||||
**Architecture:** Côté back, on retire le stade « read » inutile du POST des 3 sous-ressources (`read: false`) — le parent est déjà rattaché manuellement par le processor — et on durcit ce rattachement (404 si parent absent). Côté front, on factorise la boucle de soumission de collection dans `useClientFormErrors().submitRows(...)` qui tente tous les blocs et collecte les erreurs par index, puis on branche les 6 sites d'appel (`new.vue` + `edit.vue` × contacts/adresses/RIB).
|
||||
|
||||
**Tech Stack:** Symfony 8 / API Platform 4 (PHP 8.4, PHPUnit) ; Nuxt 4 / Vue 3 / TypeScript / Vitest.
|
||||
|
||||
**Spec de référence :** `docs/superpowers/specs/2026-06-04-client-collection-blocks-validation-design.md`
|
||||
|
||||
**Pré-vol :** `make start` (containers up), branche de travail = celle de la MR (`feat/erp-107-validation-messages-fr`) ou une branche dédiée selon décision utilisateur.
|
||||
|
||||
---
|
||||
|
||||
## Structure des fichiers
|
||||
|
||||
**Back — modifiés :**
|
||||
- `src/Module/Commercial/Domain/Entity/ClientContact.php` — `read: false` sur `Post`
|
||||
- `src/Module/Commercial/Domain/Entity/ClientAddress.php` — `read: false` sur `Post`
|
||||
- `src/Module/Commercial/Domain/Entity/ClientRib.php` — `read: false` sur `Post`
|
||||
- `src/Module/Commercial/Infrastructure/ApiPlatform/State/Processor/ClientContactProcessor.php` — `linkParent` → 404
|
||||
- `.../Processor/ClientAddressProcessor.php` — idem
|
||||
- `.../Processor/ClientRibProcessor.php` — idem
|
||||
- `tests/Module/Commercial/Api/AbstractCommercialApiTestCase.php` — helper `seedContact()`
|
||||
- `tests/Module/Commercial/Api/ClientSubResourceApiTest.php` — tests de non-régression
|
||||
|
||||
**Front — modifiés :**
|
||||
- `frontend/modules/commercial/composables/useClientFormErrors.ts` — méthode `submitRows()`
|
||||
- `frontend/modules/commercial/composables/__tests__/useClientFormErrors.spec.ts` — créé (test unitaire)
|
||||
- `frontend/modules/commercial/pages/clients/new.vue` — branchements (3 submits)
|
||||
- `frontend/modules/commercial/pages/clients/[id]/edit.vue` — branchements (3 submits)
|
||||
|
||||
---
|
||||
|
||||
## Task 1 : Back — test rouge (POST sur client à ≥2 enfants)
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/Module/Commercial/Api/AbstractCommercialApiTestCase.php`
|
||||
- Test: `tests/Module/Commercial/Api/ClientSubResourceApiTest.php`
|
||||
|
||||
- [ ] **Step 1 : Ajouter un helper de seed de contact à la base de test**
|
||||
|
||||
Dans `AbstractCommercialApiTestCase.php`, ajouter (sous `seedClient`, avant `cleanupCommercialTestData`) :
|
||||
|
||||
```php
|
||||
/**
|
||||
* Seede directement un ClientContact en base (sans passer par l'API), pour
|
||||
* preparer un client deja dote de N contacts. Au moins le prenom est pose
|
||||
* (RG-1.05 / CHECK chk_client_contact_name).
|
||||
*/
|
||||
protected function seedContact(ClientEntity $client, string $firstName): \App\Module\Commercial\Domain\Entity\ClientContact
|
||||
{
|
||||
$em = $this->getEm();
|
||||
$contact = new \App\Module\Commercial\Domain\Entity\ClientContact();
|
||||
$contact->setClient($client);
|
||||
$contact->setFirstName($firstName);
|
||||
$em->persist($contact);
|
||||
$em->flush();
|
||||
|
||||
return $contact;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2 : Écrire les tests rouges**
|
||||
|
||||
Dans `ClientSubResourceApiTest.php`, ajouter dans la section `// === Contacts ===` :
|
||||
|
||||
```php
|
||||
/**
|
||||
* Regression ERP (bug subresource Link toProperty) : POST d'un contact sur un
|
||||
* client qui en a DEJA >= 2 ne doit pas exploser en 500
|
||||
* (NonUniqueResultException sur la resolution du parent), mais creer (201).
|
||||
*/
|
||||
public function testPostContactOnClientWithTwoExistingContactsReturns201(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedClient('Contact Multi');
|
||||
$this->seedContact($seed, 'Alpha');
|
||||
$this->seedContact($seed, 'Beta');
|
||||
|
||||
$client->request('POST', '/api/clients/'.$seed->getId().'/contacts', [
|
||||
'headers' => ['Content-Type' => self::LD, 'Accept' => self::LD],
|
||||
'json' => ['firstName' => 'Gamma'],
|
||||
]);
|
||||
|
||||
self::assertResponseStatusCodeSame(201);
|
||||
}
|
||||
|
||||
/**
|
||||
* Meme contexte (>= 2 contacts existants) : un email invalide doit produire
|
||||
* une 422 par champ (la validation est bien atteinte), pas une 500.
|
||||
*/
|
||||
public function testPostInvalidContactOnPopulatedClientReturns422OnField(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedClient('Contact Multi Bad');
|
||||
$this->seedContact($seed, 'Alpha');
|
||||
$this->seedContact($seed, 'Beta');
|
||||
|
||||
$response = $client->request('POST', '/api/clients/'.$seed->getId().'/contacts', [
|
||||
'headers' => ['Content-Type' => self::LD, 'Accept' => self::LD],
|
||||
'json' => ['firstName' => 'Gamma', 'email' => 'pas-un-email'],
|
||||
]);
|
||||
|
||||
self::assertResponseStatusCodeSame(422);
|
||||
$byPath = [];
|
||||
foreach ($response->toArray(false)['violations'] ?? [] as $v) {
|
||||
$byPath[$v['propertyPath']] = $v['message'];
|
||||
}
|
||||
self::assertArrayHasKey('email', $byPath);
|
||||
self::assertSame('L\'adresse email n\'est pas valide.', $byPath['email']);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3 : Lancer les tests, vérifier qu'ils échouent (500 au lieu de 201/422)**
|
||||
|
||||
Run : `make test` (ou ciblé dans le container : `docker exec php-starseed-fpm php bin/phpunit --filter ClientSubResourceApiTest`)
|
||||
Expected : les 2 nouveaux tests ÉCHOUENT (HTTP 500 `NonUniqueResultException`). `testPostContactOnClient...` reçoit 500, pas 201.
|
||||
|
||||
- [ ] **Step 4 : Commit (test rouge)**
|
||||
|
||||
```bash
|
||||
git add tests/Module/Commercial/Api/AbstractCommercialApiTestCase.php tests/Module/Commercial/Api/ClientSubResourceApiTest.php
|
||||
git commit -m "test(commercial) : reproduit la 500 NonUniqueResult au POST contact sur client peuple (ERP-107)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2 : Back — fix (read:false + linkParent durci) → tests verts
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/Module/Commercial/Domain/Entity/ClientContact.php:48-57`
|
||||
- Modify: `src/Module/Commercial/Domain/Entity/ClientAddress.php:61-70`
|
||||
- Modify: `src/Module/Commercial/Domain/Entity/ClientRib.php:52-61`
|
||||
- Modify: `.../State/Processor/ClientContactProcessor.php:76-94`
|
||||
- Modify: `.../State/Processor/ClientAddressProcessor.php:63-81`
|
||||
- Modify: `.../State/Processor/ClientRibProcessor.php:65-83`
|
||||
|
||||
- [ ] **Step 1 : `read: false` sur les 3 opérations `Post`**
|
||||
|
||||
`ClientContact.php`, opération `Post` — ajouter la ligne `read: false,` :
|
||||
|
||||
```php
|
||||
new Post(
|
||||
uriTemplate: '/clients/{clientId}/contacts',
|
||||
uriVariables: [
|
||||
'clientId' => new Link(fromClass: Client::class, toProperty: 'client'),
|
||||
],
|
||||
// read:false : pas de stade lecture du parent (le Link toProperty
|
||||
// resoudrait l'enfant et casse en NonUniqueResult des >= 2 enfants).
|
||||
// Le parent est rattache par ClientContactProcessor::linkParent.
|
||||
read: false,
|
||||
security: "is_granted('commercial.clients.manage')",
|
||||
normalizationContext: ['groups' => ['client_contact:read']],
|
||||
denormalizationContext: ['groups' => ['client_contact:write']],
|
||||
processor: ClientContactProcessor::class,
|
||||
),
|
||||
```
|
||||
|
||||
`ClientAddress.php` — idem dans son `Post` (`security: commercial.clients.manage`, processor `ClientAddressProcessor`), commentaire pointant `ClientAddressProcessor::linkParent`.
|
||||
|
||||
`ClientRib.php` — idem dans son `Post` (`security: commercial.clients.accounting.manage`, processor `ClientRibProcessor`), commentaire pointant `ClientRibProcessor::linkParent`.
|
||||
|
||||
- [ ] **Step 2 : Durcir les 3 `linkParent` (404 si parent absent)**
|
||||
|
||||
Dans chaque processor, ajouter l'import en tête de fichier :
|
||||
|
||||
```php
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
```
|
||||
|
||||
`ClientContactProcessor::linkParent` — remplacer le bloc final par :
|
||||
|
||||
```php
|
||||
if (null === $clientId) {
|
||||
return;
|
||||
}
|
||||
|
||||
$client = $clientId instanceof Client
|
||||
? $clientId
|
||||
: $this->em->getRepository(Client::class)->find($clientId);
|
||||
|
||||
// read:false sur le POST : sans stade lecture, un parent introuvable
|
||||
// n'est plus intercepte en amont -> 404 explicite (sinon 500 au persist
|
||||
// sur client_id NOT NULL).
|
||||
if (!$client instanceof Client) {
|
||||
throw new NotFoundHttpException('Client introuvable.');
|
||||
}
|
||||
|
||||
$contact->setClient($client);
|
||||
```
|
||||
|
||||
`ClientAddressProcessor::linkParent` — idem avec `$address->setClient($client);`.
|
||||
`ClientRibProcessor::linkParent` — idem avec `$rib->setClient($client);`.
|
||||
|
||||
- [ ] **Step 3 : Lancer les tests, vérifier qu'ils passent**
|
||||
|
||||
Run : `make test`
|
||||
Expected : les 2 tests de Task 1 PASSENT (201 + 422 `propertyPath=email`). Aucun test existant cassé (notamment `testPostContactInvalidEmailReturns422WithFrenchMessageOnField` et les tests d'archi ERP-107 restent verts).
|
||||
|
||||
- [ ] **Step 4 : Lint PHP**
|
||||
|
||||
Run : `make php-cs-fixer-allow-risky`
|
||||
Expected : 0 fichier à corriger (ou corrections appliquées et re-vérifiées).
|
||||
|
||||
- [ ] **Step 5 : Commit (fix back)**
|
||||
|
||||
```bash
|
||||
git add src/Module/Commercial/Domain/Entity/ClientContact.php src/Module/Commercial/Domain/Entity/ClientAddress.php src/Module/Commercial/Domain/Entity/ClientRib.php src/Module/Commercial/Infrastructure/ApiPlatform/State/Processor/ClientContactProcessor.php src/Module/Commercial/Infrastructure/ApiPlatform/State/Processor/ClientAddressProcessor.php src/Module/Commercial/Infrastructure/ApiPlatform/State/Processor/ClientRibProcessor.php
|
||||
git commit -m "fix(commercial) : POST sous-ressource client en read:false + parent 404 (corrige 500 NonUniqueResult, ERP-107)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3 : Back — germes adresses + RIB (verrouille les 3 sous-ressources)
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/Module/Commercial/Api/AbstractCommercialApiTestCase.php` (helpers `seedAddress`, `seedRib`)
|
||||
- Test: `tests/Module/Commercial/Api/ClientSubResourceApiTest.php`
|
||||
|
||||
- [ ] **Step 1 : Helpers de seed adresse + RIB**
|
||||
|
||||
Dans `AbstractCommercialApiTestCase.php`, ajouter :
|
||||
|
||||
```php
|
||||
/** Seede une adresse minimale valide (RG : CP/ville/rue requis). */
|
||||
protected function seedAddress(ClientEntity $client, string $city): \App\Module\Commercial\Domain\Entity\ClientAddress
|
||||
{
|
||||
$em = $this->getEm();
|
||||
$address = new \App\Module\Commercial\Domain\Entity\ClientAddress();
|
||||
$address->setClient($client);
|
||||
$address->setPostalCode('33000');
|
||||
$address->setCity($city);
|
||||
$address->setStreet('1 rue du Test');
|
||||
$em->persist($address);
|
||||
$em->flush();
|
||||
|
||||
return $address;
|
||||
}
|
||||
|
||||
/** Seede un RIB valide (BIC/IBAN conformes). */
|
||||
protected function seedRib(ClientEntity $client, string $label): \App\Module\Commercial\Domain\Entity\ClientRib
|
||||
{
|
||||
$em = $this->getEm();
|
||||
$rib = new \App\Module\Commercial\Domain\Entity\ClientRib();
|
||||
$rib->setClient($client);
|
||||
$rib->setLabel($label);
|
||||
$rib->setBic('BNPAFRPPXXX');
|
||||
$rib->setIban('FR1420041010050500013M02606');
|
||||
$em->persist($rib);
|
||||
$em->flush();
|
||||
|
||||
return $rib;
|
||||
}
|
||||
```
|
||||
|
||||
> Note : si une propriété est non-nullable et absente ci-dessus (ex. `position`, flags d'adresse), poser les setters correspondants avec une valeur par défaut neutre — vérifier les entités `ClientAddress` / `ClientRib` au moment de l'écriture.
|
||||
|
||||
- [ ] **Step 2 : Tests de non-régression adresses + RIB**
|
||||
|
||||
Dans `ClientSubResourceApiTest.php`, section adresses puis RIB :
|
||||
|
||||
```php
|
||||
public function testPostAddressOnClientWithTwoExistingAddressesReturns201(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedClient('Addr Multi');
|
||||
$this->seedAddress($seed, 'Bordeaux');
|
||||
$this->seedAddress($seed, 'Lyon');
|
||||
|
||||
$client->request('POST', '/api/clients/'.$seed->getId().'/addresses', [
|
||||
'headers' => ['Content-Type' => self::LD, 'Accept' => self::LD],
|
||||
'json' => ['postalCode' => '75001', 'city' => 'Paris', 'street' => '2 rue Neuve'],
|
||||
]);
|
||||
|
||||
self::assertResponseStatusCodeSame(201);
|
||||
}
|
||||
|
||||
public function testPostRibOnClientWithTwoExistingRibsReturns201(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedClient('Rib Multi');
|
||||
$this->seedRib($seed, 'Compte 1');
|
||||
$this->seedRib($seed, 'Compte 2');
|
||||
|
||||
$client->request('POST', '/api/clients/'.$seed->getId().'/ribs', [
|
||||
'headers' => ['Content-Type' => self::LD, 'Accept' => self::LD],
|
||||
'json' => ['label' => 'Compte 3', 'bic' => self::VALID_BIC, 'iban' => self::VALID_IBAN],
|
||||
]);
|
||||
|
||||
self::assertResponseStatusCodeSame(201);
|
||||
}
|
||||
```
|
||||
|
||||
> Le POST RIB exige `commercial.clients.accounting.manage` — `admin` (ROLE_ADMIN) l'a. Si une 403 apparaît, vérifier le compte de test.
|
||||
|
||||
- [ ] **Step 3 : Lancer, vérifier vert**
|
||||
|
||||
Run : `make test`
|
||||
Expected : PASS (les 2 nouveaux tests verts grâce au fix de Task 2).
|
||||
|
||||
- [ ] **Step 4 : Commit**
|
||||
|
||||
```bash
|
||||
git add tests/Module/Commercial/Api/AbstractCommercialApiTestCase.php tests/Module/Commercial/Api/ClientSubResourceApiTest.php
|
||||
git commit -m "test(commercial) : verrouille POST adresses/RIB sur client peuple (ERP-107)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4 : Front — helper `submitRows` + test unitaire
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/modules/commercial/composables/useClientFormErrors.ts`
|
||||
- Create: `frontend/modules/commercial/composables/__tests__/useClientFormErrors.spec.ts`
|
||||
|
||||
- [ ] **Step 1 : Écrire le test rouge**
|
||||
|
||||
Créer `useClientFormErrors.spec.ts` :
|
||||
|
||||
```ts
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { useClientFormErrors } from '../useClientFormErrors'
|
||||
|
||||
// Construit une erreur facon useApi : 422 avec violations Hydra.
|
||||
function http422(path: string, message: string) {
|
||||
return { response: { status: 422, _data: { violations: [{ propertyPath: path, message }] } } }
|
||||
}
|
||||
|
||||
describe('useClientFormErrors.submitRows', () => {
|
||||
it('tente TOUS les blocs et mappe les erreurs par index, sans stopper au premier echec', async () => {
|
||||
const { contactErrors, submitRows } = useClientFormErrors()
|
||||
const seen: number[] = []
|
||||
const onUnmapped = vi.fn()
|
||||
|
||||
const saveRow = async (_row: unknown, index: number) => {
|
||||
seen.push(index)
|
||||
if (index === 1) throw http422('email', 'Email invalide')
|
||||
}
|
||||
|
||||
const hasError = await submitRows(
|
||||
[{ a: 0 }, { a: 1 }, { a: 2 }],
|
||||
contactErrors,
|
||||
saveRow,
|
||||
onUnmapped,
|
||||
)
|
||||
|
||||
expect(seen).toEqual([0, 1, 2]) // tous les blocs tentes
|
||||
expect(hasError).toBe(true)
|
||||
expect(contactErrors.value[1]).toEqual({ email: 'Email invalide' })
|
||||
expect(contactErrors.value[0]).toBeUndefined()
|
||||
expect(onUnmapped).not.toHaveBeenCalled() // 422 mappee, pas de fallback
|
||||
})
|
||||
|
||||
it('saute les lignes filtrees par shouldSkip et renvoie false si tout passe', async () => {
|
||||
const { contactErrors, submitRows } = useClientFormErrors()
|
||||
const saved: number[] = []
|
||||
|
||||
const hasError = await submitRows(
|
||||
[{ skip: true }, { skip: false }],
|
||||
contactErrors,
|
||||
async (_row, index) => { saved.push(index) },
|
||||
vi.fn(),
|
||||
(row: { skip: boolean }) => row.skip,
|
||||
)
|
||||
|
||||
expect(saved).toEqual([1])
|
||||
expect(hasError).toBe(false)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 2 : Lancer, vérifier l'échec**
|
||||
|
||||
Run : `make nuxt-test` (ou ciblé : `docker exec <node> npx vitest run useClientFormErrors`)
|
||||
Expected : FAIL — `submitRows` n'existe pas encore.
|
||||
|
||||
- [ ] **Step 3 : Implémenter `submitRows`**
|
||||
|
||||
Dans `useClientFormErrors.ts`, ajouter la méthode (dans la fonction, après `mapRowError`) et l'exposer dans le `return` :
|
||||
|
||||
```ts
|
||||
/**
|
||||
* Soumet TOUS les blocs d'une collection (contacts/adresses/RIB) en collectant
|
||||
* les erreurs par index : on n'arrete PAS au premier bloc en echec (ERP-101).
|
||||
* Reinitialise le tableau d'erreurs cible, tente chaque ligne via `saveRow`,
|
||||
* mappe les 422 inline (mapRowError) ou delegue le fallback a `onUnmappedError`.
|
||||
* Retourne true si au moins un bloc a echoue (le caller ne valide alors pas l'onglet).
|
||||
*/
|
||||
async function submitRows<T>(
|
||||
rows: T[],
|
||||
target: Ref<Record<string, string>[]>,
|
||||
saveRow: (row: T, index: number) => Promise<void>,
|
||||
onUnmappedError: (error: unknown, index: number) => void,
|
||||
shouldSkip?: (row: T, index: number) => boolean,
|
||||
): Promise<boolean> {
|
||||
target.value = []
|
||||
let hasError = false
|
||||
for (let index = 0; index < rows.length; index++) {
|
||||
if (shouldSkip?.(rows[index], index)) {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
await saveRow(rows[index], index)
|
||||
}
|
||||
catch (error) {
|
||||
if (!mapRowError(error, target, index)) {
|
||||
onUnmappedError(error, index)
|
||||
}
|
||||
hasError = true
|
||||
}
|
||||
}
|
||||
|
||||
return hasError
|
||||
}
|
||||
```
|
||||
|
||||
Ajouter `submitRows` à l'objet retourné par `useClientFormErrors`.
|
||||
|
||||
- [ ] **Step 4 : Lancer, vérifier vert**
|
||||
|
||||
Run : `make nuxt-test`
|
||||
Expected : PASS (les 2 cas verts).
|
||||
|
||||
- [ ] **Step 5 : Commit**
|
||||
|
||||
```bash
|
||||
git add frontend/modules/commercial/composables/useClientFormErrors.ts frontend/modules/commercial/composables/__tests__/useClientFormErrors.spec.ts
|
||||
git commit -m "feat(commercial) : submitRows collecte les erreurs de tous les blocs de collection (ERP-101)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5 : Front — brancher `submitRows` dans new.vue + edit.vue
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/modules/commercial/pages/clients/new.vue` (`submitContacts`, `submitAddresses`, boucle RIB de `submitAccounting`)
|
||||
- Modify: `frontend/modules/commercial/pages/clients/[id]/edit.vue` (les 3 équivalents)
|
||||
|
||||
- [ ] **Step 1 : Récupérer `submitRows` du composable**
|
||||
|
||||
Dans `new.vue` ET `edit.vue`, ajouter `submitRows` à la déstructuration de `useClientFormErrors()` :
|
||||
|
||||
```ts
|
||||
const {
|
||||
mainErrors,
|
||||
informationErrors,
|
||||
accountingErrors,
|
||||
contactErrors,
|
||||
addressErrors,
|
||||
ribErrors,
|
||||
mapRowError,
|
||||
submitRows,
|
||||
} = useClientFormErrors()
|
||||
```
|
||||
|
||||
- [ ] **Step 2 : Réécrire `submitContacts` (new.vue)**
|
||||
|
||||
Remplacer le corps de la boucle par un appel à `submitRows` :
|
||||
|
||||
```ts
|
||||
async function submitContacts(): Promise<void> {
|
||||
if (clientId.value === null || !canValidateContacts.value || tabSubmitting.value) return
|
||||
tabSubmitting.value = true
|
||||
try {
|
||||
const hasError = await submitRows(
|
||||
contacts.value,
|
||||
contactErrors,
|
||||
async (contact) => {
|
||||
const body = {
|
||||
firstName: contact.firstName || null,
|
||||
lastName: contact.lastName || null,
|
||||
jobTitle: contact.jobTitle || null,
|
||||
phonePrimary: contact.phonePrimary || null,
|
||||
phoneSecondary: contact.hasSecondaryPhone ? (contact.phoneSecondary || null) : null,
|
||||
email: contact.email || null,
|
||||
}
|
||||
if (contact.id === null) {
|
||||
const created = await api.post<ContactResponse>(
|
||||
`/clients/${clientId.value}/contacts`,
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
contact.id = created.id
|
||||
contact.iri = created['@id'] ?? null
|
||||
}
|
||||
else {
|
||||
await api.patch(`/client_contacts/${contact.id}`, body, { toast: false })
|
||||
}
|
||||
},
|
||||
(error) => toast.error({ title: t('commercial.clients.toast.error'), message: apiErrorMessage(error) }),
|
||||
(contact) => !isContactNamed(contact),
|
||||
)
|
||||
if (hasError) return
|
||||
completeTab('contact')
|
||||
toast.success({ title: t('commercial.clients.toast.updateSuccess') })
|
||||
}
|
||||
finally {
|
||||
tabSubmitting.value = false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3 : Réécrire `submitAddresses` (new.vue)**
|
||||
|
||||
```ts
|
||||
async function submitAddresses(): Promise<void> {
|
||||
if (clientId.value === null || !canValidateAddresses.value || tabSubmitting.value) return
|
||||
tabSubmitting.value = true
|
||||
try {
|
||||
const hasError = await submitRows(
|
||||
addresses.value,
|
||||
addressErrors,
|
||||
async (address) => {
|
||||
const body = {
|
||||
isProspect: address.isProspect,
|
||||
isDelivery: address.isDelivery,
|
||||
isBilling: address.isBilling,
|
||||
country: address.country,
|
||||
postalCode: address.postalCode || null,
|
||||
city: address.city || null,
|
||||
street: address.street || null,
|
||||
streetComplement: address.streetComplement || null,
|
||||
categories: address.categoryIris,
|
||||
sites: address.siteIris,
|
||||
contacts: address.contactIris,
|
||||
billingEmail: isBillingEmailRequired(address) ? (address.billingEmail || null) : null,
|
||||
}
|
||||
if (address.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/clients/${clientId.value}/addresses`,
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
address.id = created.id
|
||||
}
|
||||
else {
|
||||
await api.patch(`/client_addresses/${address.id}`, body, { toast: false })
|
||||
}
|
||||
},
|
||||
(error) => toast.error({ title: t('commercial.clients.toast.error'), message: apiErrorMessage(error) }),
|
||||
)
|
||||
if (hasError) return
|
||||
completeTab('address')
|
||||
toast.success({ title: t('commercial.clients.toast.updateSuccess') })
|
||||
}
|
||||
finally {
|
||||
tabSubmitting.value = false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4 : Réécrire la boucle RIB de `submitAccounting` (new.vue)**
|
||||
|
||||
Garder le PATCH scalaire inchangé (1) ; remplacer la boucle (2) :
|
||||
|
||||
```ts
|
||||
// 2) POST/PATCH des RIB (erreurs inline par ligne, tous les blocs).
|
||||
const ribHasError = await submitRows(
|
||||
ribs.value,
|
||||
ribErrors,
|
||||
async (rib) => {
|
||||
const body = { label: rib.label, bic: rib.bic, iban: rib.iban }
|
||||
if (rib.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/clients/${clientId.value}/ribs`,
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
rib.id = created.id
|
||||
}
|
||||
else {
|
||||
await api.patch(`/client_ribs/${rib.id}`, body, { toast: false })
|
||||
}
|
||||
},
|
||||
(error) => toast.error({ title: t('commercial.clients.toast.error'), message: apiErrorMessage(error) }),
|
||||
(rib) => !ribIsComplete(rib),
|
||||
)
|
||||
if (ribHasError) return
|
||||
|
||||
completeTab('accounting')
|
||||
toast.success({ title: t('commercial.clients.toast.updateSuccess') })
|
||||
```
|
||||
|
||||
> Retirer le `ribErrors.value = []` désormais fait par `submitRows`. Le `accountingErrors.clearErrors()` du PATCH scalaire reste.
|
||||
|
||||
- [ ] **Step 5 : Mirror dans edit.vue**
|
||||
|
||||
Appliquer les mêmes réécritures aux `submitContacts` / `submitAddresses` / boucle RIB de `submitAccounting` d'`edit.vue`. Conserver le **fallback d'erreur propre à edit.vue** (si edit.vue utilise `showError(...)` au lieu de `toast.error(...)`, passer ce fallback comme `onUnmappedError`). Vérifier les noms des refs (`clientId` peut y être l'id de route).
|
||||
|
||||
- [ ] **Step 6 : Vérifier le typecheck + tests front**
|
||||
|
||||
Run : `make nuxt-test`
|
||||
Expected : PASS. Aucune régression des specs existantes (`ClientContactBlock.spec.ts`, etc.).
|
||||
|
||||
- [ ] **Step 7 : Commit**
|
||||
|
||||
```bash
|
||||
git add frontend/modules/commercial/pages/clients/new.vue "frontend/modules/commercial/pages/clients/[id]/edit.vue"
|
||||
git commit -m "feat(commercial) : valide tous les blocs contacts/adresses/RIB et affiche les erreurs par bloc (ERP-101)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6 : Vérification finale + golden path manuel
|
||||
|
||||
- [ ] **Step 1 : Suite complète back**
|
||||
|
||||
Run : `make test` puis `make php-cs-fixer-allow-risky`
|
||||
Expected : tout vert, 0 fichier à corriger.
|
||||
|
||||
- [ ] **Step 2 : Suite complète front**
|
||||
|
||||
Run : `make nuxt-test`
|
||||
Expected : tout vert.
|
||||
|
||||
- [ ] **Step 3 : Golden path manuel (`make dev-nuxt`, port 3004)**
|
||||
|
||||
Scénario : ouvrir un client à 3 contacts (compte `admin`), onglet Contacts, ajouter un bloc avec email invalide + un autre bloc avec prénom/nom vides → Valider.
|
||||
Attendu : **pas de 500** ; « L'adresse email n'est pas valide. » sous l'email du bon bloc ET « Le prénom ou le nom du contact est obligatoire. » sous le prénom de l'autre bloc, **affichés simultanément**. L'onglet ne se valide pas tant qu'une erreur subsiste. Idem à vérifier rapidement sur Adresses et RIB.
|
||||
|
||||
- [ ] **Step 4 : Si une vérif échoue ou ne peut être lancée, le dire explicitement** (ne pas annoncer « fini »).
|
||||
|
||||
---
|
||||
|
||||
## Self-review (auteur du plan)
|
||||
|
||||
- **Couverture spec §3.1 (back)** : Task 2 (read:false + linkParent 404) ✓ ; §3.2 (front collect-all) : Tasks 4-5 ✓ ; §3.3 (helper réutilisable) : Task 4 `submitRows` ✓ ; §4 tests : Tasks 1, 3 (back), 4 (front) + Task 6 golden path ✓.
|
||||
- **Périmètre 3 sous-ressources** : contacts (Task 1-2), adresses + RIB (Task 3 + branchements Task 5) ✓.
|
||||
- **Décision « inline seul »** : aucun toast succès si `hasError` ; pas de toast récap ✓.
|
||||
- **Pas de placeholder** : le seul point ouvert est la note Task 3 Step 1 (setters non-nullables éventuels d'adresse/RIB à compléter en lisant les entités) — à lever à l'écriture. Cohérence des noms : `submitRows` utilisé identiquement en Task 4 et Task 5.
|
||||
@@ -10,8 +10,8 @@ trous, zéro duplication »).
|
||||
|
||||
ERP-60 n'écrit QUE les tests des RG non déjà couvertes par la stack, et mappe ici
|
||||
l'intégralité des RG (existantes + nouvelles + déléguées). Les tests dépendants
|
||||
des **rôles métier** (matrice RBAC bureau/compta/commerciale/usine + RG-1.04
|
||||
fonctionnel) sont **délégués à ERP-74 (#493)** : ces rôles n'existent qu'après le
|
||||
des **rôles métier** (matrice RBAC bureau/compta/commerciale/usine) sont
|
||||
**délégués à ERP-74 (#493)** : ces rôles n'existent qu'après le
|
||||
merge de la stack.
|
||||
|
||||
## Mapping RG → test
|
||||
@@ -21,7 +21,7 @@ merge de la stack.
|
||||
| ~~RG-1.01~~ | _(supprimée V1 — refonte-contact)_ contact inline retiré du Client ; complétude couverte par RG-1.05 / RG-1.14 (`ClientContact`) | — | refonte-contact |
|
||||
| ~~RG-1.02~~ | _(supprimée du Client V1)_ téléphones inline retirés du Client (testés sur `ClientContact`) | — | refonte-contact |
|
||||
| RG-1.03 | distributor/broker exclusifs + type catégorie | `ClientApiTest::testPostWithDistributorAndBrokerReturns422` ; `::testPostDistributorReferencingNonDistributorReturns422` ; `::testPostValidDistributorReturns201` ; `ClientProcessorTest` (unit) | ERP-55 |
|
||||
| RG-1.04 | Onglet Information obligatoire pour rôle Commerciale | `ClientProcessorTest::testCommercialeIncompleteInformationIsUnprocessable` ; `::testNonCommercialeSkipsInformationCompleteness` (unit, dormant). **Test fonctionnel + durcissement → ERP-74** | ERP-55 / **ERP-74** |
|
||||
| ~~RG-1.04~~ | _(SUPPRIMÉE)_ Onglet Information désormais facultatif pour tous les rôles (validation de complétude retirée) | — | ERP-55 / ERP-74 |
|
||||
| RG-1.05 | Contact : prénom OU nom → 422 (CHECK) | `ClientSubResourceApiTest::testPostContactWithoutNameReturns422` | ERP-57 |
|
||||
| RG-1.06/07/08 | Adresse prospect exclusive de livraison/facturation → 422 (Assert\Callback + CHECK filet) | `ClientAddressTest::testProspectAddressCannotBeDelivery` ; `::testProspectAddressCannotBeBilling` | ERP-60 / **ERP-76** |
|
||||
| RG-1.09 | Code postal `^[0-9]{4,5}$` → 422 | `ClientSubResourceApiTest::testPostAddressWithInvalidPostalCodeReturns422` | ERP-57 |
|
||||
@@ -60,8 +60,7 @@ merge de la stack.
|
||||
|
||||
- **Matrice RBAC différenciée** par rôle métier (Bureau / Compta / Commerciale /
|
||||
Usine) : 200/403 par verbe et par onglet selon le rôle.
|
||||
- **RG-1.04 fonctionnel** : PATCH onglet Information par une Commerciale avec
|
||||
champs incomplets → 422 ; même PATCH par Admin → 200 (+ durcissement code/spec).
|
||||
- ~~**RG-1.04 fonctionnel**~~ : _(SUPPRIMÉE)_ l'onglet Information est désormais facultatif pour tous les rôles.
|
||||
- Raison : ces rôles métier ne sont seedés qu'après le merge de la stack M1.
|
||||
|
||||
## Gaps & suivi
|
||||
|
||||
@@ -310,7 +310,7 @@ CREATE TABLE client (
|
||||
distributor_id INT REFERENCES client(id) ON DELETE SET NULL,
|
||||
broker_id INT REFERENCES client(id) ON DELETE SET NULL,
|
||||
triage_service BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
-- Onglet Information (Commerciale obligatoire — RG-1.04 — null sinon)
|
||||
-- Onglet Information (facultatif pour tous — RG-1.04 supprimée)
|
||||
description TEXT,
|
||||
competitors VARCHAR(255),
|
||||
founded_at DATE,
|
||||
@@ -864,8 +864,7 @@ Cf. § 2.6. Pattern Shared standard.
|
||||
|
||||
### Onglet Information
|
||||
|
||||
- **RG-1.04** _(durcie — ERP-74)_ : Pour un utilisateur portant le rôle métier **Commerciale**, **tous** les champs de l'onglet Information (`description`, `competitors`, `foundedAt`, `employeesCount`, `revenueAmount`, `directorName`, `profitAmount`) sont obligatoires sur **POST et sur tout PATCH**, **indépendamment des champs réellement envoyés** (la condition d'intersection avec `client:write:information` a été retirée). Pour les autres rôles, ces champs restent optionnels. Implémenté via un validator custom `ClientInformationCompletenessValidator` invoqué systématiquement par le `ClientProcessor` quand le user porte le rôle Commerciale.
|
||||
- **Conséquence** : le POST n'exposant que le groupe `client:write:main`, l'onglet Information n'y est pas renseignable → une Commerciale obtient **422** sur tout POST (cf. § 8.1). La complétude se fait donc via les PATCH `client:write:information` ultérieurs. Un Admin (non gaté) crée normalement (201).
|
||||
- ~~**RG-1.04**~~ _(SUPPRIMÉE)_ : l'onglet Information est désormais **facultatif pour tous les rôles**, y compris Commerciale. Les champs `description`, `competitors`, `foundedAt`, `employeesCount`, `revenueAmount`, `directorName`, `profitAmount` restent optionnels (colonnes nullable, aucune validation de complétude). Le validator `ClientInformationCompletenessValidator` et le gating par rôle métier dans le `ClientProcessor` ont été retirés.
|
||||
|
||||
### Onglet Contact
|
||||
|
||||
@@ -883,6 +882,7 @@ Cf. § 2.6. Pattern Shared standard.
|
||||
|
||||
### Onglet Comptabilité
|
||||
|
||||
- **RG-1.30** _(ajoutée — correctif incohérence spec-front/spec-back)_ : à la **validation complète de l'onglet Comptabilité**, les six champs scalaires `siren`, `accountNumber`, `tvaMode`, `nTva`, `paymentDelay`, `paymentType` sont **obligatoires** (alignement sur spec-front § Onglet Comptabilité). Colonnes `nullable` en base (l'onglet est rempli dans un second temps, et l'onglet principal ne les envoie pas) + validateur contextuel `ClientAccountingCompletenessValidator` invoqué par le `ClientProcessor` (parti pris : nullable + validateur d'onglet plutôt qu'un `Assert\NotBlank` sur l'entité). Déclenchement : uniquement quand **les six champs sont présents dans le payload** (le front les envoie toujours ensemble via « Valider ») ; un PATCH ciblant un sous-ensemble de champs comptables (édition ponctuelle) n'est pas soumis à la complétude. Chaque champ manquant → 422 sur son `propertyPath` (mapping inline front, ERP-101). `bank` reste hors complétude (conditionnel RG-1.12).
|
||||
- **RG-1.12** : Le champ `bank` est visible et obligatoire **uniquement** si `paymentType.code = 'VIREMENT'`. Validation server-side dans le `ClientProcessor` : si `payment_type.code = VIREMENT` et `bank IS NULL` → 422.
|
||||
- **RG-1.13** : Les champs RIB (`label`, `bic`, `iban`) sont obligatoires si **au moins un bloc RIB est présent ET** `paymentType.code = 'LCR'`. C'est-à-dire :
|
||||
- Si `paymentType.code = LCR` ET `client.ribs.count() = 0` → 422 « Au moins un RIB est obligatoire pour le type LCR ».
|
||||
@@ -937,7 +937,7 @@ Cf. § 2.6. Pattern Shared standard.
|
||||
- [ ] ~~RG-1.02~~ _(supprimée du Client V1)_ : plus de téléphones inline sur le Client (téléphones testés sur `ClientContact`)
|
||||
- [ ] **RG-1.03** : POST avec distributor ET broker → 422 ; POST distributor seul → 201
|
||||
- [ ] **RG-1.03** : POST distributor référençant un client SANS catégorie de code DISTRIBUTEUR → 422 (validation custom `ClientProcessor::hasCategoryCode`)
|
||||
- [ ] **RG-1.04** : PATCH onglet Information par un user Commerciale avec champs incomplets → 422 ; même PATCH par Admin → 200
|
||||
- [x] ~~**RG-1.04**~~ _(SUPPRIMÉE)_ : onglet Information facultatif pour tous les rôles (plus de validation de complétude)
|
||||
- [ ] **RG-1.05** : POST contact sans firstName ni lastName → 422 (BDD CHECK lève une exception)
|
||||
- [ ] **RG-1.06/07/08** : POST adresse avec isProspect=true ET isDelivery=true → 422 / CHECK
|
||||
- [ ] **RG-1.09** : POST adresse avec postalCode invalide (3 chiffres) → 422 ; CP/ville incohérents → 200 (pas de validation stricte côté serveur)
|
||||
|
||||
@@ -13,7 +13,7 @@ date_redaction: 2026-05-28
|
||||
|
||||
# === LIENS ===
|
||||
maquette_figma: "https://www.figma.com/design/jRYgT0T9c03VsEbjGhCwwS/Composants---Design-System?node-id=1132-31898"
|
||||
regles_metier: [RG-1.01, RG-1.02, RG-1.03, RG-1.04, RG-1.05, RG-1.06, RG-1.07, RG-1.08, RG-1.09, RG-1.10, RG-1.11, RG-1.12, RG-1.13, RG-1.14, RG-1.15, RG-1.16, RG-1.17, RG-1.18, RG-1.19, RG-1.20, RG-1.21, RG-1.22, RG-1.23, RG-1.24, RG-1.25, RG-1.26, RG-1.27, RG-1.28, RG-1.29]
|
||||
regles_metier: [RG-1.01, RG-1.02, RG-1.03, RG-1.05, RG-1.06, RG-1.07, RG-1.08, RG-1.09, RG-1.10, RG-1.11, RG-1.12, RG-1.13, RG-1.14, RG-1.15, RG-1.16, RG-1.17, RG-1.18, RG-1.19, RG-1.20, RG-1.21, RG-1.22, RG-1.23, RG-1.24, RG-1.25, RG-1.26, RG-1.27, RG-1.28, RG-1.29]
|
||||
roles: [Admin, Bureau, Compta, Commerciale, Usine]
|
||||
lien_spec_back: ./spec-back.md
|
||||
|
||||
@@ -105,13 +105,13 @@ Saisir les informations de l'entreprise.
|
||||
|
||||
| Champ | Type | Obligatoire | Règle |
|
||||
|---|---|---|---|
|
||||
| **Description** | `<MalioInputTextArea>` | Conditionnel | RG-1.04 (obligatoire pour rôle Commerciale) |
|
||||
| **Concurrents** | `<MalioInputText>` | Conditionnel | RG-1.04 |
|
||||
| **Date de création** (de l'entreprise) | `<input type="date">` (exception Malio — pas de composant date couvert) | Conditionnel | RG-1.04 |
|
||||
| **Nombre de salariés** | `<MalioInputNumber>` | Conditionnel | RG-1.04 |
|
||||
| **CA €** | `<MalioInputAmount>` | Conditionnel | RG-1.04 |
|
||||
| **Dirigeant** | `<MalioInputText>` | Conditionnel | RG-1.04 |
|
||||
| **Résultat €** | `<MalioInputAmount>` | Conditionnel | RG-1.04 |
|
||||
| **Description** | `<MalioInputTextArea>` | Non | — _(onglet facultatif, RG-1.04 supprimée)_ |
|
||||
| **Concurrents** | `<MalioInputText>` | Non | — |
|
||||
| **Date de création** (de l'entreprise) | `<input type="date">` (exception Malio — pas de composant date couvert) | Non | — |
|
||||
| **Nombre de salariés** | `<MalioInputNumber>` | Non | — |
|
||||
| **CA €** | `<MalioInputAmount>` | Non | — |
|
||||
| **Dirigeant** | `<MalioInputText>` | Non | — |
|
||||
| **Résultat €** | `<MalioInputAmount>` | Non | — |
|
||||
|
||||
**Action** : « Valider » → PATCH partiel `/api/clients/{id}` (groupe `client:write:information`).
|
||||
|
||||
|
||||
@@ -126,7 +126,7 @@ Toutes les entités métier nouvelles implémentent `TimestampableInterface` + `
|
||||
|
||||
Notes (miroir M1) :
|
||||
- **Compta édite uniquement l'onglet Comptabilité** (`accounting.manage`) d'un fournisseur existant. Compta ne peut pas **créer** un fournisseur (pas de `manage` global).
|
||||
- **Commerciale** a `view` + `manage` mais **pas** `accounting.view` → l'onglet Comptabilité est masqué (front) et filtré (back, 2 niveaux : `security` API Platform + `SupplierProvider`).
|
||||
- **Commerciale** a `view` + `manage` mais **pas** `accounting.view` → l'onglet Comptabilité est masqué (front) et filtré (back). Mécanisme réel (le code fait foi) : le groupe de lecture `supplier:read:accounting` n'est **pas** dans le contexte de sérialisation par défaut ; le `SupplierReadGroupContextBuilder` ne l'**ajoute** dynamiquement que si l'utilisateur porte `commercial.suppliers.accounting.view` (gating **par ajout** de groupe, jamais par retrait). Sans la permission, les champs comptables (et les RIB) ne sont donc jamais sérialisés. La colonne SIREN de l'export XLSX suit la même règle (`accounting.view`).
|
||||
- **Bureau** : `view` + `manage` (tout sauf Comptabilité).
|
||||
- **Usine** : aucune permission → item sidebar invisible, accès direct 403.
|
||||
|
||||
@@ -159,9 +159,11 @@ final class SupplierFieldNormalizer
|
||||
|
||||
Le formatage `XX XX XX XX XX` est fait à l'affichage côté front. Le back stocke `0612345678` (chiffres seuls).
|
||||
|
||||
### 2.12 Liste : embed catégories + sites + fetch-joins (cohérence M1/ERP-62)
|
||||
### 2.12 Liste : embed catégories + sites + hydratation anti-N+1 (cohérence M1/ERP-62)
|
||||
|
||||
Décision d'alignement (02/06/2026) : la **liste** `GET /api/suppliers` **embarque** les `categories[]` (avec `code`/`name`) et les `sites[]` (avec `name`/`postalCode` — pas de `code`), comme la liste Clients après ERP-62 — et **non** des champs dérivés aplatis. Conséquence performance : le `DoctrineSupplierRepository` **DOIT** poser des **fetch-joins** (`leftJoin`+`addSelect`) sur `categories` et `addresses.sites` dans la requête de liste pour éviter le N+1. Les `sites` de la liste sont agrégés/dédoublonnés via `Supplier::getSites()` (cf. § 3.3). Le contrat de sérialisation (groupes `category:read` / `site:read` dans le contexte) est posé **une seule fois** sur l'entité — source de vérité unique, le front ne le redéfinit pas.
|
||||
Décision d'alignement (02/06/2026) : la **liste** `GET /api/suppliers` **embarque** les `categories[]` (avec `code`/`name`) et les `sites[]` (avec `name`/`postalCode` — pas de `code`), comme la liste Clients après ERP-62 — et **non** des champs dérivés aplatis.
|
||||
|
||||
Conséquence performance — **implémentation réelle (le code fait foi)** : le `DoctrineSupplierRepository` **ne fetch-joine PAS** les to-many dans la requête de sélection (`createListQueryBuilder` ne fait que filtres + tri). L'anti-N+1 passe par `hydrateListCollections()` (puis `hydrateContacts()`) : une fois le jeu de fournisseurs borné (page ou export), des requêtes **`IN` bornées séparées** remplissent `categories`, puis `addresses.sites`, puis `contacts` sur les **mêmes** instances `Supplier` (identity map). Ce découpage évite le **produit cartésien** qu'un fetch-join combiné `categories × addresses.sites` imposerait aux chemins non paginés (export, `?pagination=false`). Les `sites` de la liste sont agrégés/dédoublonnés via `Supplier::getSites()` (cf. § 3.3). Le contrat de sérialisation (groupes `category:read` / `site:read` dans le contexte) est posé **une seule fois** sur l'entité — source de vérité unique, le front ne le redéfinit pas.
|
||||
|
||||
> Dépendance confirmée sur le JSON réel (#82 mergé) : `Category` expose `code`/`name` sous `category:read` ; `Site` expose `name`/`postalCode`/`city`/`color` sous `site:read` (**pas de `code`**). L'embed est pleinement matérialisé.
|
||||
|
||||
@@ -213,6 +215,8 @@ Namespace : **`DoctrineMigrations` (racine `migrations/`)** — fichier `migrati
|
||||
|
||||
> **Rappel règle ABSOLUE n°12** : chaque colonne créée ci-dessous DOIT recevoir son `COMMENT ON COLUMN`. Les 4 colonnes Timestampable/Blamable passent par le helper `addStandardTimestampableBlamableComments($schema, '<table>')`. Le SQL ci-dessous montre la structure ; les `COMMENT ON COLUMN` (un par colonne métier) sont à écrire dans la migration (exemples §3.2.bis).
|
||||
|
||||
> **Types réels de la migration (le code fait foi)** : le SQL ci-dessous est *illustratif*. La migration mergée (`Version20260605130000`) utilise le **style aligné M1** : clés primaires en `INT GENERATED BY DEFAULT AS IDENTITY` (et **non** `SERIAL`) et horodatages en `TIMESTAMP(0) WITHOUT TIME ZONE` (et **non** `TIMESTAMPTZ`, car le `TimestampableBlamableTrait` mappe `datetime_immutable`). Garantit que `schema:update` reste un no-op une fois les entités mappées.
|
||||
|
||||
```sql
|
||||
-- =====================================================================
|
||||
-- Seed taxonomie : nouveau type FOURNISSEUR (référentiels comptables = M1, non recréés)
|
||||
@@ -422,8 +426,10 @@ use Symfony\Component\Validator\Constraints as Assert;
|
||||
// Cohérence M1/ERP-62 : la LISTE embarque catégories + sites (pas de
|
||||
// champ dérivé aplati). Maillon (c) : category:read + site:read dans
|
||||
// le contexte pour exposer Category(code/name) + Site(name/postalCode).
|
||||
// ⚠ Le SupplierRepository DOIT fetch-join categories + addresses.sites
|
||||
// pour éviter le N+1 sur la liste (cf. § 2.12).
|
||||
// ⚠ Anti-N+1 : pas de fetch-join dans la requête de liste — le
|
||||
// SupplierRepository hydrate categories/sites/contacts via des requêtes
|
||||
// IN bornées séparées (hydrateListCollections), pour éviter le produit
|
||||
// cartésien sur les chemins non paginés (export) — cf. § 2.12.
|
||||
normalizationContext: ['groups' => [
|
||||
'supplier:read',
|
||||
'category:read',
|
||||
@@ -442,13 +448,14 @@ use Symfony\Component\Validator\Constraints as Assert;
|
||||
normalizationContext: ['groups' => [
|
||||
'supplier:read',
|
||||
'supplier:item:read', // embed contacts / addresses
|
||||
'supplier:read:accounting', // scalaires compta + embed ribs (filtré par le Provider selon accounting.view)
|
||||
// ⚠ supplier:read:accounting est volontairement ABSENT ici : il est
|
||||
// AJOUTÉ dynamiquement par le SupplierReadGroupContextBuilder quand
|
||||
// l'user porte accounting.view (gating par ajout, pas par retrait —
|
||||
// parade bug #4 M1). Il porte les scalaires compta + l'embed ribs.
|
||||
'category:read', // embed des Category (id/code/name) — relation imbriquée
|
||||
'site:read', // embed des Site (id/name/postalCode/city/color, pas de code) — relation imbriquée
|
||||
'default:read',
|
||||
]],
|
||||
// Le Provider RETIRE supplier:read:accounting du contexte si l'user
|
||||
// n'a pas is_granted('commercial.suppliers.accounting.view').
|
||||
provider: SupplierProvider::class,
|
||||
),
|
||||
new Post(
|
||||
@@ -458,10 +465,13 @@ use Symfony\Component\Validator\Constraints as Assert;
|
||||
processor: SupplierProcessor::class,
|
||||
),
|
||||
new Patch(
|
||||
security: "is_granted('commercial.suppliers.manage')",
|
||||
// Le SupplierProcessor inspecte les groupes envoyés pour autoriser
|
||||
// onglet par onglet (cf. § 2.10 + § 5). Patch des champs comptables
|
||||
// exige is_granted('commercial.suppliers.accounting.manage') ;
|
||||
// Security élargie : `manage` OU `accounting.manage` — le rôle Compta
|
||||
// n'a pas `manage` mais doit pouvoir éditer l'onglet Comptabilité d'un
|
||||
// fournisseur existant (§ 2.9). Le SupplierProcessor re-gate ensuite
|
||||
// onglet par onglet (mode strict RG-2.16) :
|
||||
security: "is_granted('commercial.suppliers.manage') or is_granted('commercial.suppliers.accounting.manage')",
|
||||
// Patch des champs comptables exige accounting.manage (guardAccounting) ;
|
||||
// champs main/information exigent manage (guardManage) ;
|
||||
// patch isArchived exige is_granted('commercial.suppliers.archive').
|
||||
normalizationContext: ['groups' => ['supplier:read', 'default:read']],
|
||||
denormalizationContext: ['groups' => [
|
||||
@@ -711,91 +721,108 @@ Même pattern que les jumelles `Client*` (`#[Auditable]`, `TimestampableBlamable
|
||||
| Scalaires Comptabilité (siren, refs…) | `supplier:read:accounting` | ✅ (gated) | refs (`tvaMode`…) id+label ∈ `supplier:read:accounting` |
|
||||
| `ribs[]` (label/bic/iban) | `ribs` ∈ `supplier:read:accounting` | ✅ (gated) | — |
|
||||
|
||||
### 4.0.bis Réponses JSON de référence (DoD — à confirmer sur l'API réelle)
|
||||
### 4.0.bis Réponses JSON de référence (DoD — RÉELLES, capturées ERP-92)
|
||||
|
||||
> **Definition of Done de cette spec back (RETEX M1 §3)** : avant d'écrire les tickets front, créer un fournisseur de test et **coller ici les réponses RÉELLES** de `GET /api/suppliers` et `GET /api/suppliers/{id}`. Les containers n'étant pas lancés au moment de la rédaction, le JSON ci-dessous est le **contrat CIBLE** — à valider/remplacer par la réponse réelle (`make start` puis `curl`). Toute donnée affichée par le front DOIT apparaître dans ce JSON.
|
||||
> **Definition of Done CLÔTURÉE (ERP-92, 2026-06-05)** : les réponses ci-dessous sont **réelles**, capturées sur l'API de test via PHPUnit (`SupplierSerializationContractTest`, fournisseur complet seedé). Les `id`/timestamps sont illustratifs (run de test). Toute donnée affichée par le front DOIT apparaître dans ce JSON. Front #93→#96 peuvent démarrer.
|
||||
>
|
||||
> **2 constats validés à la capture** (cf. § 4.0.ter) :
|
||||
> 1. 🔧 **Fix ERP-92** : les réfs comptables (`tvaMode`/`paymentDelay`/`paymentType`/`bank`) sortaient en **IRI nu** (les entités partagées ne portaient que `client:read:accounting`, pas `supplier:read:accounting`). Corrigé → objet `{id, code, label}` embarqué (le front consultation/édition affiche le libellé sans fetch).
|
||||
> 2. ℹ️ **Liste « riche »** : le groupe `supplier:read` étant partagé liste+détail, la **collection embarque tout le bloc Information** (et, pour un user `accounting.view`, les scalaires compta + `ribs[]`). Comportement identique au M1 (groupe `client:read` partagé) — la datatable n'affiche que Nom/Catégories/Site(s)/MAJ, mais le payload est complet. Le gating `accounting` reste effectif (Commerciale ne voit ni compta ni `ribs` en liste comme en détail).
|
||||
|
||||
> **Forme d'enveloppe confirmée sur le M1 réel** (API Platform 4.2) : JSON-LD **sans préfixe `hydra:`** → clés `member` / `totalItems` / `view`, avec `@type: "Collection"` et `view.@type: "PartialCollectionView"`. `Content-Type: application/ld+json; charset=utf-8`. Pagination défaut 10 confirmée. Login réel = `POST /api/login_check` (nginx réécrit vers `/login_check`), réponse `204` + cookie HttpOnly `BEARER`.
|
||||
|
||||
`GET /api/suppliers` (liste, ADMIN) :
|
||||
`GET /api/suppliers?search=…` (liste, ADMIN — un membre) :
|
||||
```json
|
||||
{
|
||||
"@context": "/api/contexts/Supplier",
|
||||
"@id": "/api/suppliers",
|
||||
"@type": "Collection",
|
||||
"totalItems": 13,
|
||||
"totalItems": 1,
|
||||
"member": [
|
||||
{
|
||||
"@id": "/api/suppliers/1",
|
||||
"@id": "/api/suppliers/85",
|
||||
"@type": "Supplier",
|
||||
"id": 1,
|
||||
"companyName": "RECYCLA SAS",
|
||||
"id": 85,
|
||||
"companyName": "DOD59393F 862875",
|
||||
"categories": [
|
||||
{"@id": "/api/categories/12", "id": 12, "code": "NEGOCIANT", "name": "Négociant"}
|
||||
{"@type": "Category", "@id": "/api/categories/2279", "id": 2279, "name": "test_cli_cat_fr_negociant", "code": "NEGOCIANT",
|
||||
"categoryType": {"@id": "/api/category_types/602", "@type": "CategoryType", "id": 602, "code": "FOURNISSEUR", "label": "Fournisseur"},
|
||||
"createdAt": "…", "updatedAt": "…"}
|
||||
],
|
||||
"description": "Fournisseur de test complet.",
|
||||
"competitors": "Concurrent A, Concurrent B",
|
||||
"foundedAt": "2008-04-01T00:00:00+02:00",
|
||||
"employeesCount": 42,
|
||||
"revenueAmount": "1500000.00",
|
||||
"directorName": "Jean Dupont",
|
||||
"profitAmount": "120000.00",
|
||||
"volumeForecast": 8000,
|
||||
"siren": "123456789",
|
||||
"accountNumber": "F0001",
|
||||
"tvaMode": {"@id": "/api/tva_modes/30", "@type": "TvaMode", "id": 30, "code": "FRANCE_VENTES", "label": "France (ventes)"},
|
||||
"nTva": "FR00123456789",
|
||||
"paymentDelay": {"@id": "/api/payment_delays/11", "@type": "PaymentDelay", "id": 11, "code": "J30", "label": "30 jours"},
|
||||
"paymentType": {"@id": "/api/payment_types/14", "@type": "PaymentType", "id": 14, "code": "LCR", "label": "LCR"},
|
||||
"ribs": [
|
||||
{"@id": "/api/supplier_ribs/27", "@type": "SupplierRib", "id": 27, "label": "Compte principal", "bic": "BNPAFRPPXXX", "iban": "FR1420041010050500013M02606", "createdAt": "…", "updatedAt": "…"}
|
||||
],
|
||||
"createdAt": "…", "updatedAt": "…",
|
||||
"sites": [
|
||||
{"@id": "/api/sites/1", "id": 1, "name": "Chatellerault", "postalCode": "86100", "city": "Châtellerault", "color": "#056CF2"},
|
||||
{"@id": "/api/sites/2", "id": 2, "name": "Saint-Jean", "postalCode": "17400", "city": "Fontenet", "color": "#…"}
|
||||
{"@type": "Site", "@id": "/api/sites/87", "id": 87, "name": "Chatellerault", "street": "14 All. d'Argenson", "postalCode": "86100", "city": "Châtellerault", "color": "#056CF2", "fullAddress": "14 All. d'Argenson\n86100 Châtellerault"},
|
||||
{"@type": "Site", "@id": "/api/sites/88", "id": 88, "name": "Saint-Jean", "street": "Z i", "postalCode": "17400", "city": "Fontenet", "color": "#F3CB00", "fullAddress": "Z i\n17400 Fontenet"}
|
||||
],
|
||||
"updatedAt": "2026-02-17T09:30:00+00:00",
|
||||
"isArchived": false
|
||||
}
|
||||
],
|
||||
"view": {
|
||||
"@id": "/api/suppliers?page=1",
|
||||
"@type": "PartialCollectionView",
|
||||
"first": "/api/suppliers?page=1",
|
||||
"last": "/api/suppliers?page=2",
|
||||
"next": "/api/suppliers?page=2"
|
||||
}
|
||||
"view": {"@id": "/api/suppliers?search=…", "@type": "PartialCollectionView"}
|
||||
}
|
||||
```
|
||||
|
||||
> Les fournisseurs archivés sont **exclus** du `totalItems` (sur le M1, 14 clients en base → `totalItems: 13` car 1 archivé filtré par le Provider). `categories[]` (avec `code`/`name`) et `sites[]` (avec `name`/`postalCode` — **pas de `code`**) sont **embarqués** (cohérence M1/ERP-62, § 2.12) ; `sites` est l'agrégat dédoublonné des adresses via `Supplier::getSites()`. Fetch-joins repository obligatoires (anti N+1).
|
||||
> Les fournisseurs archivés sont **exclus** du `totalItems` (RG-2.17 — filtré par le Provider). `categories[]` (avec `code`/`name`) et `sites[]` (avec `name`/`postalCode` — **pas de `code`**) sont **embarqués** (cohérence M1/ERP-62, § 2.12) ; `sites` est l'agrégat dédoublonné des adresses via `Supplier::getSites()`. Fetch-joins repository (anti N+1) **vérifiés par test** (`SupplierListTest::testListQueryCountDoesNotGrowWithRowCount` : nombre de requêtes constant entre 2 et 4 fournisseurs). ⚠️ Le membre embarque aussi l'**Information complète** et — pour un user `accounting.view` (ici admin) — les **scalaires compta + `ribs[]`** (groupe `supplier:read` partagé liste/détail). Pour la **Commerciale** (sans `accounting.view`), `siren`/`tvaMode`/`paymentType`/`ribs`… **disparaissent** de chaque membre.
|
||||
|
||||
`GET /api/suppliers/1` (détail — user avec `accounting.view`) :
|
||||
`GET /api/suppliers/85` (détail — user avec `accounting.view`) :
|
||||
```json
|
||||
{
|
||||
"@id": "/api/suppliers/1",
|
||||
"@context": "/api/contexts/Supplier",
|
||||
"@id": "/api/suppliers/85",
|
||||
"@type": "Supplier",
|
||||
"id": 1,
|
||||
"companyName": "RECYCLA SAS",
|
||||
"id": 85,
|
||||
"companyName": "DOD59393F 862875",
|
||||
"categories": [
|
||||
{"@id": "/api/categories/12", "id": 12, "code": "NEGOCIANT", "name": "Négociant"}
|
||||
{"@type": "Category", "@id": "/api/categories/2279", "id": 2279, "name": "test_cli_cat_fr_negociant", "code": "NEGOCIANT",
|
||||
"categoryType": {"@id": "/api/category_types/602", "@type": "CategoryType", "id": 602, "code": "FOURNISSEUR", "label": "Fournisseur"}}
|
||||
],
|
||||
"description": "…", "competitors": "…", "foundedAt": "2008-04-01",
|
||||
"employeesCount": 42, "revenueAmount": "1500000.00", "directorName": "…",
|
||||
"profitAmount": "120000.00", "volumeForecast": 8000,
|
||||
"description": "Fournisseur de test complet.", "competitors": "Concurrent A, Concurrent B",
|
||||
"foundedAt": "2008-04-01T00:00:00+02:00", "employeesCount": 42, "revenueAmount": "1500000.00",
|
||||
"directorName": "Jean Dupont", "profitAmount": "120000.00", "volumeForecast": 8000,
|
||||
"siren": "123456789", "accountNumber": "F0001",
|
||||
"tvaMode": {"@id": "/api/tva_modes/30", "@type": "TvaMode", "id": 30, "code": "FRANCE_VENTES", "label": "France (ventes)"},
|
||||
"nTva": "FR00123456789",
|
||||
"paymentDelay": {"@id": "/api/payment_delays/11", "@type": "PaymentDelay", "id": 11, "code": "J30", "label": "30 jours"},
|
||||
"paymentType": {"@id": "/api/payment_types/14", "@type": "PaymentType", "id": 14, "code": "LCR", "label": "LCR"},
|
||||
"contacts": [
|
||||
{"@id": "/api/supplier_contacts/1", "id": 1, "firstName": "Marie", "lastName": "Martin",
|
||||
"jobTitle": "Responsable achats", "phonePrimary": "0612345678", "phoneSecondary": null,
|
||||
"email": "marie.martin@recycla.fr"}
|
||||
{"@id": "/api/supplier_contacts/39", "@type": "SupplierContact", "id": 39, "firstName": "Marie", "lastName": "Martin",
|
||||
"jobTitle": "Responsable achats", "phonePrimary": "0612345678", "email": "marie.martin@seed.test"}
|
||||
],
|
||||
"addresses": [
|
||||
{"@id": "/api/supplier_addresses/1", "id": 1, "addressType": "DEPART",
|
||||
"country": "France", "postalCode": "86000", "city": "Poitiers",
|
||||
"street": "12 rue des Acacias", "streetComplement": null,
|
||||
{"@id": "/api/supplier_addresses/33", "@type": "SupplierAddress", "id": 33, "addressType": "DEPART",
|
||||
"country": "France", "postalCode": "86000", "city": "Poitiers", "street": "12 rue des Acacias",
|
||||
"bennes": 3, "triageProvider": true,
|
||||
"sites": [{"@id": "/api/sites/1", "id": 1, "name": "Chatellerault", "postalCode": "86100", "city": "Châtellerault", "color": "#056CF2"}],
|
||||
"categories": [{"@id": "/api/categories/12", "id": 12, "code": "NEGOCIANT", "name": "Négociant"}],
|
||||
"contacts": [{"@id": "/api/supplier_contacts/1", "id": 1, "firstName": "Marie", "lastName": "Martin"}]}
|
||||
"sites": [
|
||||
{"@type": "Site", "@id": "/api/sites/87", "id": 87, "name": "Chatellerault", "postalCode": "86100", "city": "Châtellerault", "color": "#056CF2"},
|
||||
{"@type": "Site", "@id": "/api/sites/88", "id": 88, "name": "Saint-Jean", "postalCode": "17400", "city": "Fontenet", "color": "#F3CB00"}
|
||||
],
|
||||
"contacts": [{"@id": "/api/supplier_contacts/39", "@type": "SupplierContact", "id": 39, "firstName": "Marie", "lastName": "Martin"}],
|
||||
"categories": [{"@type": "Category", "@id": "/api/categories/2279", "id": 2279, "name": "test_cli_cat_fr_negociant", "code": "NEGOCIANT"}]}
|
||||
],
|
||||
"siren": "123456789", "accountNumber": "F0001",
|
||||
"tvaMode": {"@id": "/api/tva_modes/1", "id": 1, "label": "France (ventes)"},
|
||||
"nTva": "FR00123456789",
|
||||
"paymentDelay": {"@id": "/api/payment_delays/2", "id": 2, "label": "30 jours"},
|
||||
"paymentType": {"@id": "/api/payment_types/2", "id": 2, "code": "LCR", "label": "LCR"},
|
||||
"bank": null,
|
||||
"ribs": [
|
||||
{"@id": "/api/supplier_ribs/1", "id": 1, "label": "Compte principal",
|
||||
"bic": "SOGEFRPP", "iban": "FR7630003035400005000000123"}
|
||||
{"@id": "/api/supplier_ribs/27", "@type": "SupplierRib", "id": 27, "label": "Compte principal", "bic": "BNPAFRPPXXX", "iban": "FR1420041010050500013M02606"}
|
||||
],
|
||||
"isArchived": false, "archivedAt": null,
|
||||
"updatedAt": "2026-02-17T09:30:00+00:00"
|
||||
"isArchived": false
|
||||
}
|
||||
```
|
||||
|
||||
> Pour un user **sans** `accounting.view` (ex. Commerciale) : les clés `siren`, `accountNumber`, `tvaMode`, `nTva`, `paymentDelay`, `paymentType`, `bank`, `ribs` **sont absentes** (pas `null` — réellement non sérialisées car le Provider retire le groupe). Le gating par **omission de clé** est confirmé confortable côté front. Le blame `updatedBy` est sérialisé en **IRI** (`"/api/me"` quand c'est l'user courant) — en tenir compte côté front.
|
||||
> Pour un user **sans** `accounting.view` (ex. Commerciale) : les clés `siren`, `accountNumber`, `tvaMode`, `nTva`, `paymentDelay`, `paymentType`, `bank`, `ribs` **sont absentes** (pas `null` — réellement non sérialisées : le `SupplierReadGroupContextBuilder` n'ajoute pas le groupe). Gating par **omission de clé** confirmé sur le JSON réel (`SupplierSerializationContractTest::testRibsAbsentForCommercialeWithoutAccountingView` + `testAccountingScalarsGatedByOmission`). `bennes`/`triageProvider`/`addressType`/`addresses[].contacts` restent visibles (onglet Adresse non gaté). NB : ici `bank` est absent (paymentType=LCR sans banque) ; avec un VIREMENT, `bank` est embarqué `{id, code, label}` (fix ERP-92).
|
||||
|
||||
### 4.0.ter Pièges de sérialisation CONSTATÉS sur le M1 réel → parade M2 (OBLIGATOIRE)
|
||||
|
||||
@@ -1046,7 +1073,7 @@ Le M1 a subi un aller-retour (ERP-68) faute de fixtures alignées. Pour le M2, p
|
||||
|
||||
- [x] 3 maillons de sérialisation documentés pour chaque champ liste + détail (§ 4.0)
|
||||
- [x] Décision embed vs GetCollection explicite et câblée (embed détail + sous-ressources write — § 3.3 / § 3.4 / § 4.5), **pas de POST-only**
|
||||
- [ ] **Réponses JSON RÉELLES** collées (§ 4.0.bis) — *en attente de `make start` + curl (DoD avant tickets front)*
|
||||
- [x] **Réponses JSON RÉELLES** collées (§ 4.0.bis) — capturées via PHPUnit (ERP-92, 2026-06-05) ; fix réfs compta IRI→{id,label} inclus
|
||||
- [x] Matrice RBAC rôle × onglet + mode strict PATCH (§ 2.9 / RG-2.16)
|
||||
- [x] Pagination (n°13), COMMENT ON COLUMN (n°12), Timestampable/Blamable, Audit, routes à plat : rappelés
|
||||
- [x] Réutilisations M1 identifiées (référentiels compta partagés, taxonomie code/type, `usePaginatedList`, blocs, archive, normalisation)
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
Valeurs en dur issues de la maquette Figma (design Starseed) :
|
||||
- sidebar depliee : 232px (w-[232px], repli laisse par defaut 72px)
|
||||
- marge horizontale du contenu sur desktop : 170px (xl:px-[170px])
|
||||
- bande blanche sticky sous la navbar : 47px (h-[47px])
|
||||
La marge haute du contenu (44px) vit desormais DANS l'entete (PageHeader,
|
||||
pt-11) et non sur le <main> : sinon, l'entete etant sticky, ce padding
|
||||
laissait un trou blanc entre le SiteSelector et l'entete.
|
||||
A faire evoluer uniquement avec une mise a jour de maquette.
|
||||
-->
|
||||
<template>
|
||||
@@ -25,9 +27,6 @@
|
||||
<SiteSelector v-if="showSiteSelector"/>
|
||||
<main
|
||||
class="flex flex-1 flex-col overflow-y-auto overflow-x-hidden bg-white px-4 pb-10 sm:px-6 lg:px-12 xl:px-11">
|
||||
<div
|
||||
aria-hidden="true"
|
||||
class="pointer-events-none sticky top-0 z-30 h-11 flex-shrink-0 bg-white"/>
|
||||
<slot/>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -168,13 +168,18 @@
|
||||
"prospect": "Prospect",
|
||||
"delivery": "Adresse de livraison",
|
||||
"billing": "Facturation",
|
||||
"addressType": "Type d'adresse",
|
||||
"addressTypeProspect": "Prospect",
|
||||
"addressTypeDelivery": "Livraison",
|
||||
"addressTypeBilling": "Facturation",
|
||||
"addressTypeDeliveryBilling": "Adresse + Facturation",
|
||||
"categories": "Catégorie",
|
||||
"country": "Pays",
|
||||
"postalCode": "Code postal",
|
||||
"city": "Ville",
|
||||
"street": "Adresse",
|
||||
"streetComplement": "Adresse complémentaire",
|
||||
"sites": "Sites Starseed",
|
||||
"sites": "Sites",
|
||||
"contacts": "Contact(s) rattaché(s)",
|
||||
"billingEmail": "Email de facturation",
|
||||
"remove": "Supprimer l'adresse",
|
||||
@@ -254,7 +259,11 @@
|
||||
"commercial_client": "Client",
|
||||
"commercial_clientaddress": "Adresse client",
|
||||
"commercial_clientcontact": "Contact client",
|
||||
"commercial_clientrib": "RIB client"
|
||||
"commercial_clientrib": "RIB client",
|
||||
"commercial_supplier": "Fournisseur",
|
||||
"commercial_supplieraddress": "Adresse fournisseur",
|
||||
"commercial_suppliercontact": "Contact fournisseur",
|
||||
"commercial_supplierrib": "RIB fournisseur"
|
||||
},
|
||||
"empty": "Aucune activité enregistrée",
|
||||
"no_results": "Aucun résultat pour ces filtres",
|
||||
@@ -411,17 +420,24 @@
|
||||
"noCategories": "Aucune catégorie pour l'instant.",
|
||||
"table": {
|
||||
"name": "Nom",
|
||||
"type": "Type"
|
||||
"types": "Types"
|
||||
},
|
||||
"filters": {
|
||||
"title": "Filtres",
|
||||
"search": "Recherche",
|
||||
"types": "Types de catégorie",
|
||||
"apply": "Voir les résultats",
|
||||
"reset": "Réinitialiser"
|
||||
},
|
||||
"form": {
|
||||
"name": "Nom",
|
||||
"type": "Type de catégorie",
|
||||
"typePlaceholder": "Sélectionner un type"
|
||||
"types": "Types de catégorie",
|
||||
"typesPlaceholder": "Sélectionner un ou plusieurs types"
|
||||
},
|
||||
"validation": {
|
||||
"nameRequired": "Le nom est obligatoire.",
|
||||
"nameLength": "Le nom doit faire entre 2 et 120 caractères.",
|
||||
"typeRequired": "Le type de catégorie est obligatoire."
|
||||
"typesRequired": "Sélectionnez au moins un type de catégorie."
|
||||
},
|
||||
"delete": {
|
||||
"title": "Supprimer la catégorie",
|
||||
@@ -431,7 +447,7 @@
|
||||
"created": "Catégorie créée avec succès",
|
||||
"updated": "Catégorie mise à jour avec succès",
|
||||
"deleted": "Catégorie supprimée avec succès",
|
||||
"duplicate": "Une catégorie nommée « {name} » existe déjà pour ce type.",
|
||||
"duplicate": "Une catégorie nommée « {name} » existe déjà.",
|
||||
"typesLoadFailed": "Impossible de charger les types de catégorie. Réessayez."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,16 +24,18 @@
|
||||
required
|
||||
/>
|
||||
|
||||
<!-- Type (RG-1.05 obligatoire). MalioSelect porte la valeur en
|
||||
number (categoryType id) ; conversion en IRI au moment du save
|
||||
par le composable useCategoryForm. -->
|
||||
<MalioSelect
|
||||
v-model="form.categoryTypeId.value"
|
||||
<!-- Types (RG-1.05 : au moins un obligatoire). MalioSelectCheckbox
|
||||
porte un tableau d'ids (categoryType id) ; conversion en tableau
|
||||
d'IRI au moment du save par le composable useCategoryForm. -->
|
||||
<MalioSelectCheckbox
|
||||
v-model="form.categoryTypeIds.value"
|
||||
:options="typeOptions"
|
||||
:label="t('admin.categories.form.type')"
|
||||
:empty-option-label="t('admin.categories.form.typePlaceholder')"
|
||||
:error="form.errors.categoryType"
|
||||
:label="t('admin.categories.form.types')"
|
||||
:empty-option-label="t('admin.categories.form.typesPlaceholder')"
|
||||
:error="form.errors.categoryTypes"
|
||||
:display-tag="true"
|
||||
:disabled="loadingTypes"
|
||||
required
|
||||
/>
|
||||
</form>
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ const TYPE_ACHAT: CategoryType = { id: 2, code: 'ACHAT', label: 'Achat' }
|
||||
const CAT: Category = {
|
||||
id: 42,
|
||||
name: 'Vis',
|
||||
categoryType: TYPE_VENTE,
|
||||
categoryTypes: [TYPE_VENTE],
|
||||
deletedAt: null,
|
||||
createdAt: '2026-01-01T10:00:00+00:00',
|
||||
updatedAt: '2026-01-01T10:00:00+00:00',
|
||||
@@ -58,25 +58,25 @@ describe('useCategoryForm', () => {
|
||||
})
|
||||
|
||||
describe('loadFrom', () => {
|
||||
it('pre-remplit le formulaire depuis une categorie existante', () => {
|
||||
it('pre-remplit le formulaire depuis une categorie existante (multi-types)', () => {
|
||||
const form = useCategoryForm()
|
||||
|
||||
form.loadFrom(CAT)
|
||||
form.loadFrom({ ...CAT, categoryTypes: [TYPE_VENTE, TYPE_ACHAT] })
|
||||
|
||||
expect(form.name.value).toBe('Vis')
|
||||
expect(form.categoryTypeId.value).toBe(1)
|
||||
expect(form.categoryTypeIds.value).toEqual([1, 2])
|
||||
expect(form.errors).toEqual({})
|
||||
})
|
||||
|
||||
it('vide le formulaire en mode creation (null)', () => {
|
||||
const form = useCategoryForm()
|
||||
form.name.value = 'old'
|
||||
form.categoryTypeId.value = 99
|
||||
form.categoryTypeIds.value = [99]
|
||||
|
||||
form.loadFrom(null)
|
||||
|
||||
expect(form.name.value).toBe('')
|
||||
expect(form.categoryTypeId.value).toBeNull()
|
||||
expect(form.categoryTypeIds.value).toEqual([])
|
||||
})
|
||||
|
||||
it('reinitialise le snapshot initial → isDirty=false juste apres', () => {
|
||||
@@ -98,13 +98,32 @@ describe('useCategoryForm', () => {
|
||||
|
||||
expect(form.isDirty.value).toBe(true)
|
||||
})
|
||||
|
||||
it('passe a true quand on ajoute un type (selection multi)', () => {
|
||||
const form = useCategoryForm()
|
||||
form.loadFrom(CAT)
|
||||
expect(form.isDirty.value).toBe(false)
|
||||
|
||||
form.categoryTypeIds.value = [1, 2]
|
||||
|
||||
expect(form.isDirty.value).toBe(true)
|
||||
})
|
||||
|
||||
it('reste false si la selection est identique dans un autre ordre', () => {
|
||||
const form = useCategoryForm()
|
||||
form.loadFrom({ ...CAT, categoryTypes: [TYPE_VENTE, TYPE_ACHAT] })
|
||||
|
||||
form.categoryTypeIds.value = [2, 1]
|
||||
|
||||
expect(form.isDirty.value).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('validate', () => {
|
||||
it('signale une erreur si name est vide (RG-1.02)', () => {
|
||||
const form = useCategoryForm()
|
||||
form.name.value = ''
|
||||
form.categoryTypeId.value = 1
|
||||
form.categoryTypeIds.value = [1]
|
||||
|
||||
const ok = form.validate()
|
||||
|
||||
@@ -115,7 +134,7 @@ describe('useCategoryForm', () => {
|
||||
it('signale erreur si name est whitespace-only (trim → vide)', () => {
|
||||
const form = useCategoryForm()
|
||||
form.name.value = ' '
|
||||
form.categoryTypeId.value = 1
|
||||
form.categoryTypeIds.value = [1]
|
||||
|
||||
const ok = form.validate()
|
||||
|
||||
@@ -126,7 +145,7 @@ describe('useCategoryForm', () => {
|
||||
it('signale erreur si name fait 1 caractere (< 2, RG-1.04)', () => {
|
||||
const form = useCategoryForm()
|
||||
form.name.value = 'A'
|
||||
form.categoryTypeId.value = 1
|
||||
form.categoryTypeIds.value = [1]
|
||||
|
||||
const ok = form.validate()
|
||||
|
||||
@@ -137,7 +156,7 @@ describe('useCategoryForm', () => {
|
||||
it('signale erreur si name fait 121 caracteres (> 120, RG-1.04)', () => {
|
||||
const form = useCategoryForm()
|
||||
form.name.value = 'A'.repeat(121)
|
||||
form.categoryTypeId.value = 1
|
||||
form.categoryTypeIds.value = [1]
|
||||
|
||||
const ok = form.validate()
|
||||
|
||||
@@ -145,21 +164,21 @@ describe('useCategoryForm', () => {
|
||||
expect(form.errors.name).toBe('admin.categories.validation.nameLength')
|
||||
})
|
||||
|
||||
it('signale erreur si categoryTypeId est null (RG-1.05)', () => {
|
||||
it('signale erreur si aucun type selectionne (RG-1.05)', () => {
|
||||
const form = useCategoryForm()
|
||||
form.name.value = 'Vis'
|
||||
form.categoryTypeId.value = null
|
||||
form.categoryTypeIds.value = []
|
||||
|
||||
const ok = form.validate()
|
||||
|
||||
expect(ok).toBe(false)
|
||||
expect(form.errors.categoryType).toBe('admin.categories.validation.typeRequired')
|
||||
expect(form.errors.categoryTypes).toBe('admin.categories.validation.typesRequired')
|
||||
})
|
||||
|
||||
it('passe quand name et categoryType sont valides', () => {
|
||||
it('passe quand name et au moins un type sont valides', () => {
|
||||
const form = useCategoryForm()
|
||||
form.name.value = 'Vis'
|
||||
form.categoryTypeId.value = 1
|
||||
form.categoryTypeIds.value = [1, 2]
|
||||
|
||||
const ok = form.validate()
|
||||
|
||||
@@ -171,7 +190,7 @@ describe('useCategoryForm', () => {
|
||||
const form = useCategoryForm()
|
||||
// Erreur prealable : une validation en echec peuple errors.name.
|
||||
form.name.value = ''
|
||||
form.categoryTypeId.value = 1
|
||||
form.categoryTypeIds.value = [1]
|
||||
form.validate()
|
||||
expect(form.errors.name).toBeTruthy()
|
||||
|
||||
@@ -184,17 +203,17 @@ describe('useCategoryForm', () => {
|
||||
})
|
||||
|
||||
describe('submitCreate', () => {
|
||||
it('appelle POST /categories avec body { name trimme, categoryType en IRI }', async () => {
|
||||
it('appelle POST /categories avec body { name trimme, categoryTypes en IRI[] }', async () => {
|
||||
mockPost.mockResolvedValueOnce(CAT)
|
||||
const form = useCategoryForm()
|
||||
form.name.value = ' Vis '
|
||||
form.categoryTypeId.value = 1
|
||||
form.categoryTypeIds.value = [1, 2]
|
||||
|
||||
const result = await form.submitCreate()
|
||||
|
||||
expect(mockPost).toHaveBeenCalledWith(
|
||||
'/categories',
|
||||
{ name: 'Vis', categoryType: '/api/category_types/1' },
|
||||
{ name: 'Vis', categoryTypes: ['/api/category_types/1', '/api/category_types/2'] },
|
||||
{ toast: false },
|
||||
)
|
||||
expect(result).toEqual(CAT)
|
||||
@@ -203,7 +222,7 @@ describe('useCategoryForm', () => {
|
||||
it('ne declenche aucun appel API si la validation client echoue', async () => {
|
||||
const form = useCategoryForm()
|
||||
form.name.value = ''
|
||||
form.categoryTypeId.value = 1
|
||||
form.categoryTypeIds.value = [1]
|
||||
|
||||
const result = await form.submitCreate()
|
||||
|
||||
@@ -215,7 +234,7 @@ describe('useCategoryForm', () => {
|
||||
mockPost.mockResolvedValueOnce(CAT)
|
||||
const form = useCategoryForm()
|
||||
form.name.value = 'Vis'
|
||||
form.categoryTypeId.value = 1
|
||||
form.categoryTypeIds.value = [1]
|
||||
|
||||
await form.submitCreate()
|
||||
|
||||
@@ -231,7 +250,7 @@ describe('useCategoryForm', () => {
|
||||
})
|
||||
const form = useCategoryForm()
|
||||
form.name.value = 'Vis'
|
||||
form.categoryTypeId.value = 1
|
||||
form.categoryTypeIds.value = [1]
|
||||
|
||||
const result = await form.submitCreate()
|
||||
|
||||
@@ -258,7 +277,7 @@ describe('useCategoryForm', () => {
|
||||
})
|
||||
const form = useCategoryForm()
|
||||
form.name.value = 'Vis'
|
||||
form.categoryTypeId.value = 1
|
||||
form.categoryTypeIds.value = [1]
|
||||
|
||||
const result = await form.submitCreate()
|
||||
|
||||
@@ -269,24 +288,24 @@ describe('useCategoryForm', () => {
|
||||
expect(mockToastError).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('mappe aussi hydra:violations (negociation de format alternative)', async () => {
|
||||
it('mappe une violation sur categoryTypes (hydra:violations alternative)', async () => {
|
||||
mockPost.mockRejectedValueOnce({
|
||||
response: {
|
||||
status: 422,
|
||||
_data: {
|
||||
'hydra:violations': [
|
||||
{ propertyPath: 'categoryType', message: 'Type invalide.' },
|
||||
{ propertyPath: 'categoryTypes', message: 'Sélectionnez au moins un type de catégorie.' },
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
const form = useCategoryForm()
|
||||
form.name.value = 'Vis'
|
||||
form.categoryTypeId.value = 1
|
||||
form.categoryTypeIds.value = [1]
|
||||
|
||||
await form.submitCreate()
|
||||
|
||||
expect(form.errors.categoryType).toBe('Type invalide.')
|
||||
expect(form.errors.categoryTypes).toBe('Sélectionnez au moins un type de catégorie.')
|
||||
})
|
||||
|
||||
it('fallback en toast generique si le status n est ni 409 ni 422', async () => {
|
||||
@@ -295,7 +314,7 @@ describe('useCategoryForm', () => {
|
||||
})
|
||||
const form = useCategoryForm()
|
||||
form.name.value = 'Vis'
|
||||
form.categoryTypeId.value = 1
|
||||
form.categoryTypeIds.value = [1]
|
||||
|
||||
await form.submitCreate()
|
||||
|
||||
@@ -314,7 +333,7 @@ describe('useCategoryForm', () => {
|
||||
)
|
||||
const form = useCategoryForm()
|
||||
form.name.value = 'Vis'
|
||||
form.categoryTypeId.value = 1
|
||||
form.categoryTypeIds.value = [1]
|
||||
|
||||
const pending = form.submitCreate()
|
||||
expect(form.submitting.value).toBe(true)
|
||||
@@ -331,28 +350,28 @@ describe('useCategoryForm', () => {
|
||||
mockPatch.mockResolvedValueOnce({ ...CAT, name: 'Vis V2' })
|
||||
const form = useCategoryForm()
|
||||
form.loadFrom(CAT)
|
||||
form.name.value = 'Vis V2' // categoryTypeId inchange
|
||||
form.name.value = 'Vis V2' // types inchanges
|
||||
|
||||
await form.submitUpdate(42)
|
||||
|
||||
expect(mockPatch).toHaveBeenCalledWith(
|
||||
'/categories/42',
|
||||
{ name: 'Vis V2' }, // pas de categoryType car non modifie
|
||||
{ name: 'Vis V2' }, // pas de categoryTypes car non modifies
|
||||
{ toast: false },
|
||||
)
|
||||
})
|
||||
|
||||
it('envoie categoryType en IRI quand seul le type a change', async () => {
|
||||
mockPatch.mockResolvedValueOnce({ ...CAT, categoryType: TYPE_ACHAT })
|
||||
it('envoie categoryTypes en IRI[] quand on ajoute un type', async () => {
|
||||
mockPatch.mockResolvedValueOnce({ ...CAT, categoryTypes: [TYPE_VENTE, TYPE_ACHAT] })
|
||||
const form = useCategoryForm()
|
||||
form.loadFrom(CAT)
|
||||
form.categoryTypeId.value = 2
|
||||
form.categoryTypeIds.value = [1, 2]
|
||||
|
||||
await form.submitUpdate(42)
|
||||
|
||||
expect(mockPatch).toHaveBeenCalledWith(
|
||||
'/categories/42',
|
||||
{ categoryType: '/api/category_types/2' },
|
||||
{ categoryTypes: ['/api/category_types/1', '/api/category_types/2'] },
|
||||
{ toast: false },
|
||||
)
|
||||
})
|
||||
@@ -438,7 +457,7 @@ describe('useCategoryForm', () => {
|
||||
form.reset()
|
||||
|
||||
expect(form.name.value).toBe('')
|
||||
expect(form.categoryTypeId.value).toBeNull()
|
||||
expect(form.categoryTypeIds.value).toEqual([])
|
||||
expect(form.errors).toEqual({})
|
||||
expect(form.submitting.value).toBe(false)
|
||||
})
|
||||
|
||||
@@ -13,9 +13,10 @@
|
||||
* revalide toujours (defense en profondeur).
|
||||
*
|
||||
* Erreurs par champ : delegue a `useFormErrors` (convention ERP-101). Les
|
||||
* violations 422 sont mappees par `propertyPath` (`name`, `categoryType`) ;
|
||||
* violations 422 sont mappees par `propertyPath` (`name`, `categoryTypes`) ;
|
||||
* l'erreur globale (status != 422 exploitable) part en toast. Le 409 (doublon
|
||||
* RG-1.07) reste un cas metier specifique : erreur inline sur `name` + toast.
|
||||
* de nom GLOBAL, RG-1.07) reste un cas metier specifique : erreur inline sur
|
||||
* `name` + toast.
|
||||
*/
|
||||
import { computed, ref } from 'vue'
|
||||
import type { Category } from '~/modules/catalog/types/category'
|
||||
@@ -42,20 +43,29 @@ export function useCategoryForm() {
|
||||
// State local du formulaire — pas singleton, chaque appel a useCategoryForm
|
||||
// cree son propre state (cohérent avec le pattern « un drawer = un form »).
|
||||
const name = ref('')
|
||||
const categoryTypeId = ref<number | null>(null)
|
||||
const categoryTypeIds = ref<number[]>([])
|
||||
|
||||
// Snapshot des valeurs initiales : sert a calculer `isDirty` pour le
|
||||
// pattern view → edit du drawer (le bouton Enregistrer reste masque tant
|
||||
// que rien n'a change en mode consultation).
|
||||
const initialName = ref('')
|
||||
const initialCategoryTypeId = ref<number | null>(null)
|
||||
const initialCategoryTypeIds = ref<number[]>([])
|
||||
|
||||
const submitting = ref(false)
|
||||
|
||||
// Compare deux listes d'ids sans tenir compte de l'ordre (la selection
|
||||
// multi-types n'est pas ordonnee).
|
||||
function sameIds(a: number[], b: number[]): boolean {
|
||||
if (a.length !== b.length) return false
|
||||
const sortedA = [...a].sort((x, y) => x - y)
|
||||
const sortedB = [...b].sort((x, y) => x - y)
|
||||
return sortedA.every((v, i) => v === sortedB[i])
|
||||
}
|
||||
|
||||
const isDirty = computed(
|
||||
() =>
|
||||
name.value !== initialName.value
|
||||
|| categoryTypeId.value !== initialCategoryTypeId.value,
|
||||
|| !sameIds(categoryTypeIds.value, initialCategoryTypeIds.value),
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -66,15 +76,16 @@ export function useCategoryForm() {
|
||||
function loadFrom(category: Category | null): void {
|
||||
formErrors.clearErrors()
|
||||
if (category) {
|
||||
const ids = category.categoryTypes.map(t => t.id)
|
||||
name.value = category.name
|
||||
categoryTypeId.value = category.categoryType.id
|
||||
categoryTypeIds.value = [...ids]
|
||||
initialName.value = category.name
|
||||
initialCategoryTypeId.value = category.categoryType.id
|
||||
initialCategoryTypeIds.value = [...ids]
|
||||
} else {
|
||||
name.value = ''
|
||||
categoryTypeId.value = null
|
||||
categoryTypeIds.value = []
|
||||
initialName.value = ''
|
||||
initialCategoryTypeId.value = null
|
||||
initialCategoryTypeIds.value = []
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,23 +106,23 @@ export function useCategoryForm() {
|
||||
formErrors.setError('name', t('admin.categories.validation.nameLength'))
|
||||
}
|
||||
|
||||
// RG-1.05 — categoryType obligatoire.
|
||||
if (categoryTypeId.value === null) {
|
||||
formErrors.setError('categoryType', t('admin.categories.validation.typeRequired'))
|
||||
// RG-1.05 — au moins un type obligatoire.
|
||||
if (categoryTypeIds.value.length === 0) {
|
||||
formErrors.setError('categoryTypes', t('admin.categories.validation.typesRequired'))
|
||||
}
|
||||
|
||||
return !formErrors.errors.name && !formErrors.errors.categoryType
|
||||
return !formErrors.errors.name && !formErrors.errors.categoryTypes
|
||||
}
|
||||
|
||||
/**
|
||||
* Construit le payload POST a partir du state. Le `categoryType` est
|
||||
* envoye en IRI Hydra (`/api/category_types/{id}`) — convention API
|
||||
* Platform pour referencer une ressource liee.
|
||||
* Construit le payload POST a partir du state. Les `categoryTypes` sont
|
||||
* envoyes en tableau d'IRI Hydra (`/api/category_types/{id}`) — convention
|
||||
* API Platform pour referencer une collection de ressources liees.
|
||||
*/
|
||||
function buildCreatePayload(): Record<string, unknown> {
|
||||
return {
|
||||
name: name.value.trim(),
|
||||
categoryType: `/api/category_types/${categoryTypeId.value}`,
|
||||
categoryTypes: categoryTypeIds.value.map(id => `/api/category_types/${id}`),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,8 +185,8 @@ export function useCategoryForm() {
|
||||
if (name.value !== initialName.value) {
|
||||
payload.name = name.value.trim()
|
||||
}
|
||||
if (categoryTypeId.value !== initialCategoryTypeId.value) {
|
||||
payload.categoryType = `/api/category_types/${categoryTypeId.value}`
|
||||
if (!sameIds(categoryTypeIds.value, initialCategoryTypeIds.value)) {
|
||||
payload.categoryTypes = categoryTypeIds.value.map(id => `/api/category_types/${id}`)
|
||||
}
|
||||
// Garde-fou : un PATCH sans changement ne sert a rien. Theoriquement
|
||||
// empeche par le drawer (bouton Enregistrer masque si !isDirty) mais
|
||||
@@ -233,9 +244,9 @@ export function useCategoryForm() {
|
||||
*/
|
||||
function reset(): void {
|
||||
name.value = ''
|
||||
categoryTypeId.value = null
|
||||
categoryTypeIds.value = []
|
||||
initialName.value = ''
|
||||
initialCategoryTypeId.value = null
|
||||
initialCategoryTypeIds.value = []
|
||||
formErrors.clearErrors()
|
||||
submitting.value = false
|
||||
}
|
||||
@@ -243,7 +254,7 @@ export function useCategoryForm() {
|
||||
return {
|
||||
// State
|
||||
name,
|
||||
categoryTypeId,
|
||||
categoryTypeIds,
|
||||
errors: formErrors.errors,
|
||||
submitting,
|
||||
isDirty,
|
||||
|
||||
@@ -3,13 +3,28 @@
|
||||
<PageHeader>
|
||||
{{ t('admin.categories.title') }}
|
||||
<template #actions>
|
||||
<MalioButton
|
||||
v-if="canManage"
|
||||
:label="t('admin.categories.newCategory')"
|
||||
icon-name="mdi:add-bold"
|
||||
icon-position="left"
|
||||
@click="openCreateDrawer"
|
||||
/>
|
||||
<!-- gap-12 = 48px d'espacement entre Ajouter et Filtres (meme
|
||||
design que le Repertoire Clients). -->
|
||||
<div class="flex items-center gap-12">
|
||||
<MalioButton
|
||||
v-if="canManage"
|
||||
:label="t('admin.categories.newCategory')"
|
||||
icon-name="mdi:add-bold"
|
||||
icon-position="left"
|
||||
@click="openCreateDrawer"
|
||||
/>
|
||||
<!-- Bouton Filtres a DROITE d'Ajouter. Le compteur reflete
|
||||
les filtres actifs. -->
|
||||
<MalioButton
|
||||
variant="tertiary"
|
||||
:label="filterButtonLabel"
|
||||
icon-name="mdi:tune"
|
||||
icon-position="left"
|
||||
icon-size="24"
|
||||
button-class="w-[184px] justify-start gap-4 text-black"
|
||||
@click="openFilters"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
@@ -47,6 +62,60 @@
|
||||
:loading="deleting"
|
||||
@confirm="handleDelete"
|
||||
/>
|
||||
|
||||
<!-- Drawer de filtres : etat BROUILLON, applique uniquement au clic sur
|
||||
« Appliquer ». Meme pattern que le Repertoire Clients. Etat 100 %
|
||||
local, jamais dans l'URL (regle ABSOLUE n°6). -->
|
||||
<MalioDrawer
|
||||
v-model="filterDrawerOpen"
|
||||
drawer-class="max-w-[450px]"
|
||||
body-class="p-0"
|
||||
footer-class="justify-between border-t border-black p-6"
|
||||
>
|
||||
<template #header>
|
||||
<h2 class="text-[24px] font-bold uppercase">{{ t('admin.categories.filters.title') }}</h2>
|
||||
</template>
|
||||
|
||||
<MalioAccordion>
|
||||
<!-- Recherche par nom (param `name`, partiel insensible a la casse). -->
|
||||
<MalioAccordionItem :title="t('admin.categories.filters.search')" value="search">
|
||||
<MalioInputText
|
||||
v-model="draftSearch"
|
||||
icon-name="mdi:magnify"
|
||||
/>
|
||||
</MalioAccordionItem>
|
||||
|
||||
<!-- Type(s) : cases a cocher (multi). Une categorie remonte si
|
||||
elle porte AU MOINS UN des types coches (OR cote back). -->
|
||||
<MalioAccordionItem :title="t('admin.categories.filters.types')" value="types">
|
||||
<div class="flex flex-col">
|
||||
<MalioCheckbox
|
||||
v-for="opt in typeFilterOptions"
|
||||
:id="`filter-type-${opt.value}`"
|
||||
:key="opt.value"
|
||||
:label="opt.label"
|
||||
:model-value="draftTypeIds.includes(opt.value)"
|
||||
@update:model-value="(val: boolean) => toggleType(opt.value, val)"
|
||||
/>
|
||||
</div>
|
||||
</MalioAccordionItem>
|
||||
</MalioAccordion>
|
||||
|
||||
<template #footer>
|
||||
<MalioButton
|
||||
variant="tertiary"
|
||||
:label="t('admin.categories.filters.reset')"
|
||||
button-class="w-m-btn-action"
|
||||
@click="resetFilters"
|
||||
/>
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('admin.categories.filters.apply')"
|
||||
button-class="w-[170px]"
|
||||
@click="applyFilters"
|
||||
/>
|
||||
</template>
|
||||
</MalioDrawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -55,7 +124,7 @@ import type { Category } from '~/modules/catalog/types/category'
|
||||
|
||||
const { t } = useI18n()
|
||||
const { can } = usePermissions()
|
||||
const { fetchTypes } = useCategoriesAdmin()
|
||||
const { types, fetchTypes } = useCategoriesAdmin()
|
||||
const { submitDelete } = useCategoryForm()
|
||||
|
||||
useHead({ title: t('admin.categories.title') })
|
||||
@@ -74,6 +143,7 @@ const {
|
||||
fetch: fetchCategories,
|
||||
goToPage,
|
||||
setItemsPerPage,
|
||||
setFilters,
|
||||
} = usePaginatedList<Category>({ url: '/categories' })
|
||||
|
||||
const drawerOpen = ref(false)
|
||||
@@ -82,21 +152,96 @@ const deleteModalOpen = ref(false)
|
||||
const categoryToDelete = ref<Category | null>(null)
|
||||
const deleting = ref(false)
|
||||
|
||||
// Colonnes du datatable. Le type est embarque cote API (cf. spec-back § 3.4) —
|
||||
// on aplatit en label lisible pour l'affichage.
|
||||
// Colonnes du datatable. Les types sont embarques cote API (ManyToMany) — on
|
||||
// aplatit en libelles joints par une virgule pour l'affichage.
|
||||
const columns = [
|
||||
{ key: 'name', label: t('admin.categories.table.name') },
|
||||
{ key: 'typeLabel', label: t('admin.categories.table.type') },
|
||||
{ key: 'typesLabel', label: t('admin.categories.table.types') },
|
||||
]
|
||||
|
||||
const categoryItems = computed(() =>
|
||||
categories.value.map(cat => ({
|
||||
id: cat.id,
|
||||
name: cat.name,
|
||||
typeLabel: cat.categoryType?.label ?? '',
|
||||
typesLabel: (cat.categoryTypes ?? []).map(ct => ct.label).join(', '),
|
||||
})),
|
||||
)
|
||||
|
||||
// ── Filtres (drawer) ────────────────────────────────────────────────────────
|
||||
// Deux niveaux d'etat (pattern Repertoire Clients) :
|
||||
// - APPLIED : pilote la liste + le compteur du bouton. Modifie uniquement au
|
||||
// clic « Appliquer » / « Réinitialiser ».
|
||||
// - DRAFT : edite librement dans le drawer ; recopie vers applied a la validation.
|
||||
const filterDrawerOpen = ref(false)
|
||||
|
||||
const draftSearch = ref('')
|
||||
const draftTypeIds = ref<number[]>([])
|
||||
|
||||
const appliedSearch = ref('')
|
||||
const appliedTypeIds = ref<number[]>([])
|
||||
|
||||
// Options du filtre Type(s), derivees du referentiel deja charge (fetchTypes).
|
||||
const typeFilterOptions = computed(() =>
|
||||
types.value.map(ct => ({ value: ct.id, label: ct.label })),
|
||||
)
|
||||
|
||||
const activeFilterCount = computed(() => {
|
||||
let count = 0
|
||||
if (appliedSearch.value.trim() !== '') count++
|
||||
if (appliedTypeIds.value.length > 0) count++
|
||||
return count
|
||||
})
|
||||
|
||||
const filterButtonLabel = computed(() => {
|
||||
const base = t('admin.categories.filters.title')
|
||||
return activeFilterCount.value > 0 ? `${base} (${activeFilterCount.value})` : base
|
||||
})
|
||||
|
||||
// Recopie l'etat applique vers le brouillon puis ouvre le drawer.
|
||||
function openFilters(): void {
|
||||
draftSearch.value = appliedSearch.value
|
||||
draftTypeIds.value = [...appliedTypeIds.value]
|
||||
filterDrawerOpen.value = true
|
||||
}
|
||||
|
||||
function toggleType(id: number, selected: boolean): void {
|
||||
draftTypeIds.value = selected
|
||||
? [...draftTypeIds.value, id]
|
||||
: draftTypeIds.value.filter(t => t !== id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Construit le payload de filtres serveur a partir de l'etat applique. Cle
|
||||
* `typeId[]` pour que PHP la parse en tableau (OR cote back). Filtres vides omis.
|
||||
*/
|
||||
function buildFilterPayload(): Record<string, string | string[]> {
|
||||
const payload: Record<string, string | string[]> = {}
|
||||
if (appliedSearch.value.trim() !== '') payload.name = appliedSearch.value.trim()
|
||||
if (appliedTypeIds.value.length > 0) payload['typeId[]'] = appliedTypeIds.value.map(String)
|
||||
return payload
|
||||
}
|
||||
|
||||
// « Appliquer » : recopie brouillon → applied, pousse les filtres (retombe en
|
||||
// page 1 via usePaginatedList) et ferme le drawer.
|
||||
function applyFilters(): void {
|
||||
appliedSearch.value = draftSearch.value.trim()
|
||||
appliedTypeIds.value = [...draftTypeIds.value]
|
||||
|
||||
setFilters(buildFilterPayload(), { replace: true })
|
||||
filterDrawerOpen.value = false
|
||||
}
|
||||
|
||||
// « Réinitialiser » : vide brouillon ET applied, recharge la liste complete.
|
||||
// Le drawer reste ouvert pour montrer le formulaire vide.
|
||||
function resetFilters(): void {
|
||||
draftSearch.value = ''
|
||||
draftTypeIds.value = []
|
||||
appliedSearch.value = ''
|
||||
appliedTypeIds.value = []
|
||||
|
||||
setFilters({}, { replace: true })
|
||||
}
|
||||
|
||||
function getCategoryById(id: number): Category | undefined {
|
||||
return categories.value.find(c => c.id === id)
|
||||
}
|
||||
|
||||
@@ -4,15 +4,15 @@
|
||||
* Contrats API consommes :
|
||||
* - GET /api/categories → HydraCollection<Category>
|
||||
* - GET /api/categories/{id} → Category
|
||||
* - POST /api/categories → body { name, categoryType: IRI }
|
||||
* - PATCH /api/categories/{id} → body partiel { name?, categoryType?: IRI }
|
||||
* - POST /api/categories → body { name, categoryTypes: IRI[] }
|
||||
* - PATCH /api/categories/{id} → body partiel { name?, categoryTypes?: IRI[] }
|
||||
* - DELETE /api/categories/{id} → 204 (soft delete via CategoryProcessor)
|
||||
* - GET /api/category_types → HydraCollection<CategoryType>
|
||||
*
|
||||
* Notes :
|
||||
* - Les IRI sont envoyes en POST/PATCH (ex. "/api/category_types/3").
|
||||
* - `categoryType` est embarque (groupe Serializer `category:read` sur les
|
||||
* proprietes de CategoryType, cf. spec-back § 3.4).
|
||||
* - Les IRI sont envoyes en POST/PATCH (ex. ["/api/category_types/3"]).
|
||||
* - `categoryTypes` est embarque (groupe Serializer `category:read` sur les
|
||||
* proprietes de CategoryType) : tableau d'objets type en lecture.
|
||||
* - `createdBy` / `updatedBy` peuvent etre `null` (hors contexte HTTP,
|
||||
* ON DELETE SET NULL en BDD). Affichage : libelle "Systeme" si null.
|
||||
*/
|
||||
@@ -43,7 +43,8 @@ export interface CategoryType {
|
||||
export interface Category {
|
||||
id: number
|
||||
name: string
|
||||
categoryType: CategoryType
|
||||
/** Types de la categorie (>= 1, ManyToMany embarque en lecture). */
|
||||
categoryTypes: CategoryType[]
|
||||
/** Soft delete : null = active, valeur = supprimee logiquement le {date}. */
|
||||
deletedAt: string | null
|
||||
createdAt: string
|
||||
@@ -53,12 +54,12 @@ export interface Category {
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload accepte en POST /api/categories. `categoryType` est envoye en
|
||||
* IRI Hydra (ex. `/api/category_types/3`).
|
||||
* Payload accepte en POST /api/categories. `categoryTypes` est un tableau
|
||||
* d'IRI Hydra (ex. `['/api/category_types/3', '/api/category_types/5']`).
|
||||
*/
|
||||
export interface CategoryCreateInput {
|
||||
name: string
|
||||
categoryType: string
|
||||
categoryTypes: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -67,5 +68,5 @@ export interface CategoryCreateInput {
|
||||
*/
|
||||
export interface CategoryUpdateInput {
|
||||
name?: string
|
||||
categoryType?: string
|
||||
categoryTypes?: string[]
|
||||
}
|
||||
|
||||
@@ -10,34 +10,53 @@
|
||||
@click="$emit('remove')"
|
||||
/>
|
||||
|
||||
<!-- Usage de l'adresse : Prospect exclusif de Livraison/Facturation
|
||||
(RG-1.06/07/08). L'exclusivite est appliquee au toggle (cocher l'un
|
||||
decoche l'autre) plutot qu'en masquant les options. -->
|
||||
<MalioCheckbox
|
||||
:model-value="model.isProspect"
|
||||
:label="t('commercial.clients.form.address.prospect')"
|
||||
group-class="self-center"
|
||||
<!-- Usage de l'adresse : Select unique (plus simple pour l'utilisateur)
|
||||
remplacant les 3 cases. Les options encodent les combinaisons valides
|
||||
(exclusivite Prospect, RG-1.06/07/08) ; le back recoit toujours les
|
||||
drapeaux isProspect / isDelivery / isBilling (aucune RG modifiee). -->
|
||||
<MalioSelect
|
||||
:model-value="addressType"
|
||||
:options="addressTypeOptions"
|
||||
:label="t('commercial.clients.form.address.addressType')"
|
||||
:readonly="readonly"
|
||||
@update:model-value="(v: boolean) => toggleFlag('isProspect', v)"
|
||||
/>
|
||||
<MalioCheckbox
|
||||
:model-value="model.isDelivery"
|
||||
:label="t('commercial.clients.form.address.delivery')"
|
||||
group-class="self-center"
|
||||
:readonly="readonly"
|
||||
@update:model-value="(v: boolean) => toggleFlag('isDelivery', v)"
|
||||
/>
|
||||
<MalioCheckbox
|
||||
:model-value="model.isBilling"
|
||||
:label="t('commercial.clients.form.address.billing')"
|
||||
group-class="self-center"
|
||||
:readonly="readonly"
|
||||
@update:model-value="(v: boolean) => toggleFlag('isBilling', v)"
|
||||
:required="true"
|
||||
@update:model-value="onAddressTypeChange"
|
||||
/>
|
||||
|
||||
<!-- Cellule vide : laisse un trou en position 4 (ligne 1) pour que
|
||||
Categorie reparte au debut de la ligne suivante. -->
|
||||
<div aria-hidden="true" />
|
||||
<!-- Sites Starseed : multiselect a tags (>= 1 obligatoire, RG-1.10). -->
|
||||
<MalioSelectCheckbox
|
||||
:model-value="model.siteIris"
|
||||
:options="siteOptions"
|
||||
:label="t('commercial.clients.form.address.sites')"
|
||||
:display-tag="true"
|
||||
:readonly="readonly"
|
||||
:required="true"
|
||||
@update:model-value="(v: (string | number)[]) => update('siteIris', v.map(String))"
|
||||
/>
|
||||
|
||||
<MalioSelectCheckbox
|
||||
:model-value="model.contactIris"
|
||||
:options="contactOptions"
|
||||
:label="t('commercial.clients.form.address.contacts')"
|
||||
:display-tag="true"
|
||||
:readonly="readonly"
|
||||
@update:model-value="(v: (string | number)[]) => update('contactIris', v.map(String))"
|
||||
/>
|
||||
|
||||
<!-- Email de facturation : ligne 1 colonne 4, visible/obligatoire
|
||||
seulement si Facturation (RG-1.11). Sinon un filler comble la
|
||||
colonne pour que Categorie reparte au debut de la ligne 2. -->
|
||||
<MalioInputEmail
|
||||
v-if="isBillingEmailRequired(model)"
|
||||
:model-value="model.billingEmail"
|
||||
:label="t('commercial.clients.form.address.billingEmail')"
|
||||
:required="true"
|
||||
:readonly="readonly"
|
||||
:lowercase="true"
|
||||
:error="errors?.billingEmail"
|
||||
@update:model-value="(v: string) => update('billingEmail', v)"
|
||||
/>
|
||||
<div v-else aria-hidden="true" />
|
||||
|
||||
<MalioSelectCheckbox
|
||||
:model-value="model.categoryIris"
|
||||
@@ -68,8 +87,9 @@
|
||||
@update:model-value="onPostalCodeChange"
|
||||
/>
|
||||
|
||||
<!-- Ville : MalioSelect alimente par le code postal (BAN). En mode
|
||||
degrade (service indisponible), bascule en saisie libre. -->
|
||||
<!-- Ville : MalioSelect alimente par le code postal (BAN). Si la BAN est
|
||||
indisponible, bascule en saisie libre — recuperable : re-saisir le
|
||||
code postal relance la recherche et repasse en select au succes. -->
|
||||
<MalioSelect
|
||||
v-if="!degraded"
|
||||
:model-value="model.city"
|
||||
@@ -96,11 +116,14 @@
|
||||
sur l'input interne, pas sur la cellule de grille. Le wrapper porte
|
||||
le col-span-2, le champ le remplit (w-full). -->
|
||||
<div class="col-span-2">
|
||||
<!-- Adresse : saisie assistee (BAN) en edition ; champ texte simple en
|
||||
mode degrade OU en lecture seule (MalioInputAutocomplete ne reaffiche
|
||||
pas sa valeur liee, il n'afficherait rien en readonly). -->
|
||||
<!-- Adresse : saisie assistee (BAN) en edition ; champ texte simple
|
||||
seulement en lecture seule (MalioInputAutocomplete ne reaffiche pas
|
||||
sa valeur liee, il n'afficherait rien en readonly). Une erreur BAN
|
||||
ne bascule PAS en saisie libre : l'autocompletion reste montee et
|
||||
chaque frappe relance la recherche (l'utilisateur peut aussi taper
|
||||
une rue librement). -->
|
||||
<MalioInputAutocomplete
|
||||
v-if="!degraded && !readonly"
|
||||
v-if="!readonly"
|
||||
:model-value="model.street"
|
||||
:options="addressOptions"
|
||||
:loading="addressLoading"
|
||||
@@ -134,47 +157,15 @@
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Sites Starseed : cases a cocher inline (>= 1 obligatoire, RG-1.10). -->
|
||||
<div class="flex justify-between">
|
||||
<MalioCheckbox
|
||||
v-for="site in siteOptions"
|
||||
:key="site.value"
|
||||
:model-value="model.siteIris.includes(site.value)"
|
||||
:label="site.label"
|
||||
group-class="w-auto self-center"
|
||||
:readonly="readonly"
|
||||
@update:model-value="(v: boolean) => toggleSite(site.value, v)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<MalioSelectCheckbox
|
||||
:model-value="model.contactIris"
|
||||
:options="contactOptions"
|
||||
:label="t('commercial.clients.form.address.contacts')"
|
||||
:display-tag="true"
|
||||
:readonly="readonly"
|
||||
@update:model-value="(v: (string | number)[]) => update('contactIris', v.map(String))"
|
||||
/>
|
||||
|
||||
<!-- Email de facturation : visible/obligatoire seulement si Facturation
|
||||
est coche (RG-1.11). -->
|
||||
<MalioInputText
|
||||
v-if="isBillingEmailRequired(model)"
|
||||
:model-value="model.billingEmail"
|
||||
:label="t('commercial.clients.form.address.billingEmail')"
|
||||
:required="true"
|
||||
:readonly="readonly"
|
||||
:error="errors?.billingEmail"
|
||||
@update:model-value="(v: string) => update('billingEmail', v)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
applyProspectExclusivity,
|
||||
addressFlagsFromType,
|
||||
addressTypeFromFlags,
|
||||
isBillingEmailRequired,
|
||||
type AddressFlagsDraft,
|
||||
type AddressType,
|
||||
} from '~/modules/commercial/utils/clientFormRules'
|
||||
import { useAddressAutocomplete, type AddressSuggestion } from '~/shared/composables/useAddressAutocomplete'
|
||||
import type { CategoryOption, RefOption } from '~/modules/commercial/composables/useClientReferentials'
|
||||
@@ -213,8 +204,29 @@ const autocomplete = useAddressAutocomplete()
|
||||
|
||||
const model = computed(() => props.modelValue)
|
||||
|
||||
// Mode degrade : service BAN indisponible → Ville/Adresse en saisie libre.
|
||||
// Type d'adresse (Select unique) derive des drapeaux back. null tant qu'aucun
|
||||
// drapeau n'est pose -> champ vide + bouton « Valider » bloque (cf. parent).
|
||||
const addressType = computed<AddressType | null>(() => addressTypeFromFlags(model.value))
|
||||
|
||||
const addressTypeOptions = computed<RefOption[]>(() => [
|
||||
{ value: 'prospect', label: t('commercial.clients.form.address.addressTypeProspect') },
|
||||
{ value: 'delivery', label: t('commercial.clients.form.address.addressTypeDelivery') },
|
||||
{ value: 'billing', label: t('commercial.clients.form.address.addressTypeBilling') },
|
||||
{ value: 'delivery_billing', label: t('commercial.clients.form.address.addressTypeDeliveryBilling') },
|
||||
])
|
||||
|
||||
/** Applique le type choisi en repercutant les 3 drapeaux back (immutabilite). */
|
||||
function onAddressTypeChange(value: string | number | null): void {
|
||||
if (value === null) return
|
||||
emit('update:modelValue', { ...props.modelValue, ...addressFlagsFromType(value as AddressType) })
|
||||
}
|
||||
|
||||
// Repli saisie libre de la VILLE quand la BAN est indisponible (recuperable :
|
||||
// remis a false des qu'une recherche de ville aboutit). N'affecte plus le champ
|
||||
// Adresse, qui reste en autocompletion et reessaie a chaque frappe.
|
||||
const degraded = ref(false)
|
||||
// Avertissement « service indisponible » envoye au parent une seule fois.
|
||||
let unavailableNotified = false
|
||||
// Villes proposees par la BAN (alimentees a la saisie du code postal).
|
||||
const banCityOptions = ref<RefOption[]>([])
|
||||
// Adresses proposees par la BAN (alimentees a la saisie d'adresse).
|
||||
@@ -254,29 +266,10 @@ function update<K extends keyof AddressFormDraft>(field: K, value: AddressFormDr
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: value })
|
||||
}
|
||||
|
||||
/** Coche/decoche un site Starseed rattache a l'adresse (M2M par IRI, RG-1.10). */
|
||||
function toggleSite(siteIri: string, selected: boolean): void {
|
||||
const current = props.modelValue.siteIris
|
||||
const next = selected
|
||||
? [...current, siteIri]
|
||||
: current.filter(iri => iri !== siteIri)
|
||||
update('siteIris', next)
|
||||
}
|
||||
|
||||
/** Applique l'exclusivite Prospect / (Livraison|Facturation) au changement. */
|
||||
function toggleFlag(field: keyof AddressFlagsDraft, value: boolean): void {
|
||||
const flags = applyProspectExclusivity(
|
||||
{ isProspect: model.value.isProspect, isDelivery: model.value.isDelivery, isBilling: model.value.isBilling },
|
||||
field,
|
||||
value,
|
||||
)
|
||||
emit('update:modelValue', { ...props.modelValue, ...flags })
|
||||
}
|
||||
|
||||
/** Bascule définitivement en mode degrade et previent le parent (toast unique). */
|
||||
function enterDegraded(): void {
|
||||
if (!degraded.value) {
|
||||
degraded.value = true
|
||||
/** Previent le parent (toast unique) que l'autocompletion est indisponible. */
|
||||
function notifyUnavailable(): void {
|
||||
if (!unavailableNotified) {
|
||||
unavailableNotified = true
|
||||
emit('degraded')
|
||||
}
|
||||
}
|
||||
@@ -285,9 +278,6 @@ function enterDegraded(): void {
|
||||
async function onPostalCodeChange(value: string): Promise<void> {
|
||||
update('postalCode', value)
|
||||
|
||||
if (degraded.value) {
|
||||
return
|
||||
}
|
||||
const digits = (value ?? '').replace(/\D/g, '')
|
||||
if (digits.length < 5) {
|
||||
return
|
||||
@@ -295,15 +285,22 @@ async function onPostalCodeChange(value: string): Promise<void> {
|
||||
try {
|
||||
const suggestions = await autocomplete.searchCity(digits)
|
||||
banCityOptions.value = suggestions.map(s => ({ value: s.city, label: s.city }))
|
||||
// Service repondu : on (re)passe la Ville en select assiste.
|
||||
degraded.value = false
|
||||
}
|
||||
catch {
|
||||
enterDegraded()
|
||||
// BAN indispo : Ville en saisie libre (recuperable au prochain essai).
|
||||
degraded.value = true
|
||||
notifyUnavailable()
|
||||
}
|
||||
}
|
||||
|
||||
/** Recherche d'adresse assistee (event de MalioInputAutocomplete). */
|
||||
async function onAddressSearch(query: string): Promise<void> {
|
||||
if (degraded.value) {
|
||||
// La BAN exige au moins 3 caracteres : on n'envoie rien en deca (evite un 400)
|
||||
// et on vide les suggestions devenues obsoletes.
|
||||
if (query.trim().length < 3) {
|
||||
banAddressOptions.value = []
|
||||
return
|
||||
}
|
||||
addressLoading.value = true
|
||||
@@ -314,7 +311,10 @@ async function onAddressSearch(query: string): Promise<void> {
|
||||
banAddressOptions.value = suggestions.map(s => ({ value: s.street, label: s.label }))
|
||||
}
|
||||
catch {
|
||||
enterDegraded()
|
||||
// Erreur transitoire : on vide les suggestions, la prochaine frappe reessaie
|
||||
// (pas de bascule definitive — c'etait le bug). Avertissement une seule fois.
|
||||
banAddressOptions.value = []
|
||||
notifyUnavailable()
|
||||
}
|
||||
finally {
|
||||
addressLoading.value = false
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
:model-value="model.email"
|
||||
:label="t('commercial.clients.form.contact.email')"
|
||||
:readonly="readonly"
|
||||
:lowercase="true"
|
||||
:error="errors?.email"
|
||||
@update:model-value="(v: string) => update('email', v)"
|
||||
/>
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { mount, flushPromises } from '@vue/test-utils'
|
||||
import { defineComponent, h, ref, computed } from 'vue'
|
||||
import { emptyAddress } from '~/modules/commercial/types/clientForm'
|
||||
import ClientAddressBlock from '../ClientAddressBlock.vue'
|
||||
|
||||
// Le composable BAN est mocke : aucun appel reseau, aucune suggestion chargee.
|
||||
// On reproduit ainsi l'etat « adresse persistee, mais liste de suggestions
|
||||
// vide » (remontage apres validation / edition d'une adresse existante).
|
||||
// Mocks controlables du composable BAN (hoisted) : chaque test configure le
|
||||
// comportement de searchCity / searchAddress (succes, rejet, rejet-puis-succes).
|
||||
// Par defaut ils renvoient undefined (aucune suggestion) — etat « adresse
|
||||
// persistee mais liste vide » couvert par les tests d'affichage.
|
||||
const { searchCityMock, searchAddressMock } = vi.hoisted(() => ({
|
||||
searchCityMock: vi.fn(),
|
||||
searchAddressMock: vi.fn(),
|
||||
}))
|
||||
vi.mock('~/shared/composables/useAddressAutocomplete', () => ({
|
||||
useAddressAutocomplete: () => ({
|
||||
searchCity: vi.fn(),
|
||||
searchAddress: vi.fn(),
|
||||
searchCity: searchCityMock,
|
||||
searchAddress: searchAddressMock,
|
||||
}),
|
||||
}))
|
||||
|
||||
@@ -130,3 +135,57 @@ describe('ClientAddressBlock — mapping erreur par champ (ERP-101)', () => {
|
||||
expect(field?.attributes('data-error')).toBe('Code postal invalide.')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ClientAddressBlock — recherche adresse robuste (erreur BAN)', () => {
|
||||
beforeEach(() => {
|
||||
searchAddressMock.mockReset()
|
||||
})
|
||||
|
||||
it('n\'appelle pas la BAN en deca de 3 caracteres', async () => {
|
||||
const wrapper = mountBlock(null)
|
||||
const auto = wrapper.findComponent(MalioInputAutocompleteStub)
|
||||
|
||||
auto.vm.$emit('search', 'ab')
|
||||
await flushPromises()
|
||||
|
||||
expect(searchAddressMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('relance la recherche apres une erreur (pas de bascule definitive)', async () => {
|
||||
searchAddressMock
|
||||
.mockRejectedValueOnce(new Error('BAN indisponible'))
|
||||
.mockResolvedValueOnce([
|
||||
{ label: '8 Boulevard du Port, Paris', street: '8 Boulevard du Port', postalCode: '75001', city: 'Paris' },
|
||||
])
|
||||
|
||||
const wrapper = mountBlock(null)
|
||||
const auto = wrapper.findComponent(MalioInputAutocompleteStub)
|
||||
|
||||
// 1er essai -> erreur BAN.
|
||||
auto.vm.$emit('search', 'boulevard du port')
|
||||
await flushPromises()
|
||||
expect(searchAddressMock).toHaveBeenCalledTimes(1)
|
||||
|
||||
// 2e essai -> DOIT relancer l'appel (c'etait le bug : plus aucune recherche).
|
||||
auto.vm.$emit('search', 'boulevard du porte')
|
||||
await flushPromises()
|
||||
expect(searchAddressMock).toHaveBeenCalledTimes(2)
|
||||
|
||||
// L'autocompletion reste montee (aucune bascule en saisie libre).
|
||||
expect(wrapper.find('[data-testid="addr-autocomplete"]').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('emet « degraded » une seule fois malgre plusieurs erreurs', async () => {
|
||||
searchAddressMock.mockRejectedValue(new Error('BAN indisponible'))
|
||||
|
||||
const wrapper = mountBlock(null)
|
||||
const auto = wrapper.findComponent(MalioInputAutocompleteStub)
|
||||
|
||||
auto.vm.$emit('search', 'rue de la paix')
|
||||
await flushPromises()
|
||||
auto.vm.$emit('search', 'rue de la paixx')
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.emitted('degraded')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -52,3 +52,71 @@ describe('useClientFormErrors', () => {
|
||||
expect(f.addressErrors.value[0]).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
// Construit une erreur facon useApi : 422 avec violations Hydra.
|
||||
function http422(path: string, message: string) {
|
||||
return { response: { status: 422, _data: { violations: [{ propertyPath: path, message }] } } }
|
||||
}
|
||||
|
||||
/**
|
||||
* `submitRows` factorise la soumission d'une collection de blocs (contacts /
|
||||
* adresses / RIB) : on tente TOUS les blocs et on collecte les erreurs par index
|
||||
* sans stopper au premier echec (ERP-110 / ERP-101).
|
||||
*/
|
||||
describe('useClientFormErrors.submitRows', () => {
|
||||
it('tente TOUS les blocs et mappe les erreurs par index, sans stopper au premier echec', async () => {
|
||||
const { contactErrors, submitRows } = useClientFormErrors()
|
||||
const seen: number[] = []
|
||||
const onUnmapped = vi.fn()
|
||||
|
||||
const saveRow = async (_row: unknown, index: number) => {
|
||||
seen.push(index)
|
||||
if (index === 1) throw http422('email', 'Email invalide')
|
||||
}
|
||||
|
||||
const hasError = await submitRows(
|
||||
[{ a: 0 }, { a: 1 }, { a: 2 }],
|
||||
contactErrors,
|
||||
saveRow,
|
||||
onUnmapped,
|
||||
)
|
||||
|
||||
expect(seen).toEqual([0, 1, 2]) // tous les blocs tentes
|
||||
expect(hasError).toBe(true)
|
||||
expect(contactErrors.value[1]).toEqual({ email: 'Email invalide' })
|
||||
expect(contactErrors.value[0]).toBeUndefined()
|
||||
expect(onUnmapped).not.toHaveBeenCalled() // 422 mappee, pas de fallback
|
||||
})
|
||||
|
||||
it('delegue le fallback onUnmappedError pour une erreur non mappable et marque hasError', async () => {
|
||||
const { ribErrors, submitRows } = useClientFormErrors()
|
||||
const onUnmapped = vi.fn()
|
||||
|
||||
const hasError = await submitRows(
|
||||
[{ a: 0 }],
|
||||
ribErrors,
|
||||
async () => { throw { response: { status: 500, _data: {} } } },
|
||||
onUnmapped,
|
||||
)
|
||||
|
||||
expect(hasError).toBe(true)
|
||||
expect(onUnmapped).toHaveBeenCalledTimes(1)
|
||||
expect(ribErrors.value[0]).toBeUndefined()
|
||||
})
|
||||
|
||||
it('saute les lignes filtrees par shouldSkip et renvoie false si tout passe', async () => {
|
||||
const { contactErrors, submitRows } = useClientFormErrors()
|
||||
const saved: number[] = []
|
||||
|
||||
const hasError = await submitRows(
|
||||
[{ skip: true }, { skip: false }],
|
||||
contactErrors,
|
||||
async (_row, index) => { saved.push(index) },
|
||||
vi.fn(),
|
||||
(row: { skip: boolean }) => row.skip,
|
||||
)
|
||||
|
||||
expect(saved).toEqual([1])
|
||||
expect(hasError).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -43,6 +43,44 @@ export function useClientFormErrors() {
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Soumet TOUS les blocs d'une collection (contacts / adresses / RIB) en
|
||||
* collectant les erreurs par index : on n'arrete PAS au premier bloc en echec
|
||||
* (decision ERP-110 / ERP-101). Reinitialise le tableau d'erreurs cible, tente
|
||||
* chaque ligne via `saveRow`, mappe les 422 inline (mapRowError) ou delegue le
|
||||
* fallback a `onUnmappedError`. `shouldSkip` permet d'ignorer les blocs vides
|
||||
* (non remplis). Retourne true si au moins un bloc a echoue (le caller ne valide
|
||||
* alors pas l'onglet et n'affiche pas de toast succes).
|
||||
*/
|
||||
async function submitRows<T>(
|
||||
rows: T[],
|
||||
target: Ref<Record<string, string>[]>,
|
||||
saveRow: (row: T, index: number) => Promise<void>,
|
||||
onUnmappedError: (error: unknown, index: number) => void,
|
||||
shouldSkip?: (row: T, index: number) => boolean,
|
||||
): Promise<boolean> {
|
||||
target.value = []
|
||||
let hasError = false
|
||||
for (let index = 0; index < rows.length; index++) {
|
||||
// L'index reste borne par rows.length : la ligne existe forcement.
|
||||
const row = rows[index] as T
|
||||
if (shouldSkip?.(row, index)) {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
await saveRow(row, index)
|
||||
}
|
||||
catch (error) {
|
||||
if (!mapRowError(error, target, index)) {
|
||||
onUnmappedError(error, index)
|
||||
}
|
||||
hasError = true
|
||||
}
|
||||
}
|
||||
|
||||
return hasError
|
||||
}
|
||||
|
||||
return {
|
||||
mainErrors,
|
||||
informationErrors,
|
||||
@@ -51,5 +89,6 @@ export function useClientFormErrors() {
|
||||
addressErrors,
|
||||
ribErrors,
|
||||
mapRowError,
|
||||
submitRows,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,7 +99,9 @@ export function useClientReferentials() {
|
||||
*/
|
||||
async function loadCommon(): Promise<void> {
|
||||
await Promise.allSettled([
|
||||
fetchAll<CategoryMember>('/categories')
|
||||
// Taxonomie multi-types (ERP-84) : un client ne porte que des categories
|
||||
// de type CLIENT (pas FOURNISSEUR) -> on filtre la collection cote API.
|
||||
fetchAll<CategoryMember>('/categories', { typeCode: 'CLIENT' })
|
||||
.then((cats) => { categories.value = cats.map(c => ({ value: c['@id'], label: c.name, code: c.code })) }),
|
||||
fetchAll<SiteMember>('/sites')
|
||||
// Libelle = numero de departement (2 premiers chiffres du code
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div>
|
||||
<!-- En-tete : retour repertoire + nom du client. -->
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="flex items-center gap-3 pt-11">
|
||||
<MalioButtonIcon
|
||||
icon="mdi:arrow-left-bold"
|
||||
icon-size="24"
|
||||
@@ -9,7 +9,7 @@
|
||||
v-bind="{ ariaLabel: t('commercial.clients.edit.back') }"
|
||||
@click="goBack"
|
||||
/>
|
||||
<h1 class="text-[32px] font-bold text-m-primary">{{ headerTitle }}</h1>
|
||||
<h1 class="text-[30px] font-semibold text-m-primary">{{ headerTitle }}</h1>
|
||||
</div>
|
||||
|
||||
<!-- Etats de chargement / introuvable. -->
|
||||
@@ -41,6 +41,7 @@
|
||||
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
|
||||
/>
|
||||
<MalioSelect
|
||||
v-if="showRelationAndTriage"
|
||||
:model-value="main.relationType"
|
||||
:options="relationOptions"
|
||||
:label="t('commercial.clients.form.main.relation')"
|
||||
@@ -49,7 +50,7 @@
|
||||
@update:model-value="onRelationChange"
|
||||
/>
|
||||
<MalioSelect
|
||||
v-if="main.relationType === 'courtier'"
|
||||
v-if="showRelationAndTriage && main.relationType === 'courtier'"
|
||||
:model-value="main.brokerIri"
|
||||
:options="brokerOptions"
|
||||
:label="t('commercial.clients.form.main.brokerName')"
|
||||
@@ -59,7 +60,7 @@
|
||||
@update:model-value="(v: string | number | null) => main.brokerIri = v === null ? null : String(v)"
|
||||
/>
|
||||
<MalioSelect
|
||||
v-if="main.relationType === 'distributeur'"
|
||||
v-if="showRelationAndTriage && main.relationType === 'distributeur'"
|
||||
:model-value="main.distributorIri"
|
||||
:options="distributorOptions"
|
||||
:label="t('commercial.clients.form.main.distributorName')"
|
||||
@@ -69,6 +70,7 @@
|
||||
@update:model-value="(v: string | number | null) => main.distributorIri = v === null ? null : String(v)"
|
||||
/>
|
||||
<MalioCheckbox
|
||||
v-if="showRelationAndTriage"
|
||||
v-model="main.triageService"
|
||||
:label="t('commercial.clients.form.main.triageService')"
|
||||
group-class="self-center"
|
||||
@@ -90,11 +92,14 @@
|
||||
<!-- Onglet Information -->
|
||||
<template #information>
|
||||
<div class="mt-12 grid grid-cols-4 gap-x-[44px] gap-y-4 bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
|
||||
<!-- pt-1/pb-1 alignent le textarea (h-full) en haut ET en bas
|
||||
sur les inputs (champ 40px centre dans un h-12 -> ~4px de
|
||||
coussin de chaque cote). -->
|
||||
<MalioInputTextArea
|
||||
v-model="information.description"
|
||||
:label="t('commercial.clients.form.information.description')"
|
||||
resize="none"
|
||||
group-class="row-span-2 pt-1"
|
||||
group-class="row-span-2 pt-1 pb-1"
|
||||
text-input="h-full text-lg"
|
||||
:readonly="businessReadonly"
|
||||
:error="informationErrors.errors.description"
|
||||
@@ -205,6 +210,7 @@
|
||||
icon-name="mdi:add-bold"
|
||||
icon-position="left"
|
||||
:label="t('commercial.clients.form.address.add')"
|
||||
:disabled="!canAddAddress"
|
||||
@click="addAddress"
|
||||
/>
|
||||
<MalioButton
|
||||
@@ -289,9 +295,9 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Blocs RIB (0..n) — obligatoires si type de reglement = LCR (RG-1.13). -->
|
||||
<!-- Blocs RIB — affiches uniquement si type de reglement = LCR (RG-1.13). -->
|
||||
<div
|
||||
v-for="(rib, index) in ribs"
|
||||
v-for="(rib, index) in visibleRibs"
|
||||
:key="rib.id ?? `new-${index}`"
|
||||
class="relative bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]"
|
||||
>
|
||||
@@ -330,10 +336,12 @@
|
||||
|
||||
<div v-if="!accountingReadonly" class="flex justify-center gap-6">
|
||||
<MalioButton
|
||||
v-if="isRibRequired"
|
||||
variant="secondary"
|
||||
icon-name="mdi:add-bold"
|
||||
icon-position="left"
|
||||
:label="t('commercial.clients.form.accounting.addRib')"
|
||||
:disabled="!canAddRib"
|
||||
@click="addRib"
|
||||
/>
|
||||
<MalioButton
|
||||
@@ -379,7 +387,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { useClient } from '~/modules/commercial/composables/useClient'
|
||||
import { useClientReferentials, type CategoryOption, type RefOption } from '~/modules/commercial/composables/useClientReferentials'
|
||||
import { useClientFormErrors } from '~/modules/commercial/composables/useClientFormErrors'
|
||||
@@ -411,11 +419,17 @@ import {
|
||||
} from '~/modules/commercial/utils/clientEdit'
|
||||
import {
|
||||
buildClientFormTabKeys,
|
||||
hasAllRequiredAccountingFields,
|
||||
hasAtLeastOneValidContact,
|
||||
isAddressValid,
|
||||
isBankRequiredForPaymentType,
|
||||
isBillingEmailRequired,
|
||||
isContactBlank,
|
||||
isContactNamed,
|
||||
isRibBlank,
|
||||
isRibComplete,
|
||||
isRibRequiredForPaymentType,
|
||||
showsRelationAndTriageFields,
|
||||
} from '~/modules/commercial/utils/clientFormRules'
|
||||
import {
|
||||
emptyAddress,
|
||||
@@ -426,6 +440,7 @@ import {
|
||||
type RibFormDraft,
|
||||
} from '~/modules/commercial/types/clientForm'
|
||||
import { extractApiErrorMessage } from '~/shared/utils/api'
|
||||
import { readHistoryTab } from '~/shared/utils/historyTab'
|
||||
|
||||
// Masques de saisie (la normalisation finale reste serveur).
|
||||
const SIREN_MASK = '#########'
|
||||
@@ -496,7 +511,9 @@ function hydrate(detail: ClientDetail): void {
|
||||
// un bloc vierge (non persiste tant qu'incomplet — cf. submit*/canValidate*).
|
||||
if (contacts.value.length === 0) contacts.value.push(emptyContact())
|
||||
if (addresses.value.length === 0) addresses.value.push(emptyAddress())
|
||||
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||
// RIB : amorce un bloc vide seulement si le type de reglement est une LCR
|
||||
// (sinon la section reste masquee — RG-1.13).
|
||||
if (isRibRequired.value && ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||
// Charge les listes distributeur / courtier si une relation est deja posee.
|
||||
if (main.relationType === 'distributeur') referentials.loadDistributors().catch(() => {})
|
||||
if (main.relationType === 'courtier') referentials.loadBrokers().catch(() => {})
|
||||
@@ -547,6 +564,28 @@ const relationOptions = computed<RefOption[]>(() => [
|
||||
{ value: 'courtier', label: t('commercial.clients.form.main.relationBroker') },
|
||||
])
|
||||
|
||||
// Codes des categories selectionnees (resolus depuis l'union referentiel + embed).
|
||||
const selectedCategoryCodes = computed(() =>
|
||||
main.categoryIris
|
||||
.map(iri => mainCategoryOptions.value.find(c => c.value === iri)?.code)
|
||||
.filter((code): code is string => code !== undefined),
|
||||
)
|
||||
|
||||
// « Relation » + « Prestation de triage » masques par defaut, reveles des qu'une
|
||||
// categorie ordinaire (autre que Distributeur/Courtier) est selectionnee.
|
||||
const showRelationAndTriage = computed(() => showsRelationAndTriageFields(selectedCategoryCodes.value))
|
||||
|
||||
// Masquer ces champs reinitialise leurs valeurs : pas de relation/triage fantome
|
||||
// soumis pour un client Distributeur/Courtier.
|
||||
watch(showRelationAndTriage, (visible) => {
|
||||
if (!visible) {
|
||||
main.relationType = null
|
||||
main.distributorIri = null
|
||||
main.brokerIri = null
|
||||
main.triageService = false
|
||||
}
|
||||
})
|
||||
|
||||
// Distributeur / courtier : referentiel charge a la demande UNION valeur courante.
|
||||
const currentDistributorOption = computed<RefOption[]>(() => {
|
||||
const d = client.value?.distributor
|
||||
@@ -588,11 +627,13 @@ const tabs = computed(() => tabKeys.value.map(key => ({
|
||||
icon: TAB_ICONS[key],
|
||||
})))
|
||||
|
||||
const activeTab = ref('information')
|
||||
// Onglet initial : repris de la consultation (history.state), sinon Information.
|
||||
const activeTab = ref(readHistoryTab(tabKeys.value) ?? 'information')
|
||||
|
||||
// ── Navigation ──────────────────────────────────────────────────────────────
|
||||
/** Retour consultation en conservant l'onglet courant (via history.state). */
|
||||
function goBack(): void {
|
||||
router.push(`/clients/${clientId}`)
|
||||
router.push({ path: `/clients/${clientId}`, state: { tab: activeTab.value } })
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -628,7 +669,7 @@ const {
|
||||
contactErrors,
|
||||
addressErrors,
|
||||
ribErrors,
|
||||
mapRowError,
|
||||
submitRows,
|
||||
} = useClientFormErrors()
|
||||
|
||||
// ── Bloc principal ───────────────────────────────────────────────────────────
|
||||
@@ -742,11 +783,14 @@ async function submitContacts(): Promise<void> {
|
||||
}
|
||||
removedContactIds.value = []
|
||||
|
||||
for (let index = 0; index < contacts.value.length; index++) {
|
||||
const contact = contacts.value[index]
|
||||
if (!isContactNamed(contact)) continue
|
||||
const body = buildContactPayload(contact)
|
||||
try {
|
||||
// On tente TOUS les blocs (collecte des erreurs par index, ERP-110). Seuls
|
||||
// les blocs TOTALEMENT vides sont ignores : un bloc partiellement rempli
|
||||
// sans nom (email seul) est soumis -> 422 RG-1.05 inline sous le bloc.
|
||||
const hasError = await submitRows(
|
||||
contacts.value,
|
||||
contactErrors,
|
||||
async (contact) => {
|
||||
const body = buildContactPayload(contact)
|
||||
if (contact.id === null) {
|
||||
const created = await api.post<{ '@id'?: string, id: number }>(
|
||||
`/clients/${clientId}/contacts`,
|
||||
@@ -759,15 +803,15 @@ async function submitContacts(): Promise<void> {
|
||||
else {
|
||||
await api.patch(`/client_contacts/${contact.id}`, body, { toast: false })
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
// 422 → erreurs inline sous les champs de CETTE ligne ; on stoppe.
|
||||
if (!mapRowError(error, contactErrors, index)) {
|
||||
showError(error)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
},
|
||||
error => showError(error),
|
||||
// On ne saute QUE les amorces neuves (id null) totalement vides. Un
|
||||
// bloc existant vide est soumis -> 422 RG-1.05 inline (sinon la modif
|
||||
// serait perdue en silence avec un faux toast de succes).
|
||||
contact => contact.id === null && isContactBlank(contact),
|
||||
)
|
||||
// Tant qu'un bloc reste en erreur : pas de toast succes.
|
||||
if (hasError) return
|
||||
toast.success({ title: t('commercial.clients.toast.updateSuccess') })
|
||||
}
|
||||
catch (e) {
|
||||
@@ -780,17 +824,17 @@ async function submitContacts(): Promise<void> {
|
||||
|
||||
// ── Onglet Adresse ───────────────────────────────────────────────────────────
|
||||
const canValidateAddresses = computed(() =>
|
||||
addresses.value.length > 0
|
||||
&& addresses.value.every((a) => {
|
||||
const filledBillingEmail = a.billingEmail !== null && a.billingEmail.trim() !== ''
|
||||
return a.siteIris.length >= 1
|
||||
&& a.categoryIris.length >= 1
|
||||
&& (!isBillingEmailRequired(a) || filledBillingEmail)
|
||||
}),
|
||||
addresses.value.length > 0 && addresses.value.every(isAddressValid),
|
||||
)
|
||||
|
||||
// « + Adresse » desactive tant que la derniere adresse n'est pas valide.
|
||||
const canAddAddress = computed(() => {
|
||||
const last = addresses.value[addresses.value.length - 1]
|
||||
return last !== undefined && isAddressValid(last)
|
||||
})
|
||||
|
||||
function addAddress(): void {
|
||||
addresses.value.push(emptyAddress())
|
||||
if (canAddAddress.value) addresses.value.push(emptyAddress())
|
||||
}
|
||||
|
||||
function askRemoveAddress(index: number): void {
|
||||
@@ -824,10 +868,12 @@ async function submitAddresses(): Promise<void> {
|
||||
}
|
||||
removedAddressIds.value = []
|
||||
|
||||
for (let index = 0; index < addresses.value.length; index++) {
|
||||
const address = addresses.value[index]
|
||||
const body = buildAddressPayload(address, isBillingEmailRequired(address))
|
||||
try {
|
||||
// On tente TOUS les blocs d'adresse (collecte des erreurs par index, ERP-110).
|
||||
const hasError = await submitRows(
|
||||
addresses.value,
|
||||
addressErrors,
|
||||
async (address) => {
|
||||
const body = buildAddressPayload(address, isBillingEmailRequired(address))
|
||||
if (address.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/clients/${clientId}/addresses`,
|
||||
@@ -839,14 +885,10 @@ async function submitAddresses(): Promise<void> {
|
||||
else {
|
||||
await api.patch(`/client_addresses/${address.id}`, body, { toast: false })
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
if (!mapRowError(error, addressErrors, index)) {
|
||||
showError(error)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
},
|
||||
error => showError(error),
|
||||
)
|
||||
if (hasError) return
|
||||
toast.success({ title: t('commercial.clients.toast.updateSuccess') })
|
||||
}
|
||||
catch (e) {
|
||||
@@ -864,24 +906,42 @@ const selectedPaymentTypeCode = computed(() =>
|
||||
const isBankRequired = computed(() => isBankRequiredForPaymentType(selectedPaymentTypeCode.value))
|
||||
const isRibRequired = computed(() => isRibRequiredForPaymentType(selectedPaymentTypeCode.value))
|
||||
|
||||
// Les blocs RIB ne sont affiches que pour une LCR (RG-1.13).
|
||||
const visibleRibs = computed(() => isRibRequired.value ? ribs.value : [])
|
||||
|
||||
function onPaymentTypeChange(value: string | number | null): void {
|
||||
accounting.paymentTypeIri = value === null ? null : String(value)
|
||||
if (!isBankRequired.value) accounting.bankIri = null
|
||||
}
|
||||
|
||||
function ribIsComplete(rib: { label: string | null, bic: string | null, iban: string | null }): boolean {
|
||||
const filled = (v: string | null) => v !== null && v.trim() !== ''
|
||||
return filled(rib.label) && filled(rib.bic) && filled(rib.iban)
|
||||
// Les RIB n'ont de sens que pour une LCR (RG-1.13) : on amorce un bloc vide
|
||||
// quand LCR est choisi, sinon on vide la liste — les RIB deja persistes sont
|
||||
// marques pour suppression serveur au prochain enregistrement.
|
||||
if (isRibRequired.value) {
|
||||
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||
}
|
||||
else {
|
||||
for (const rib of ribs.value) {
|
||||
if (rib.id != null) removedRibIds.value.push(rib.id)
|
||||
}
|
||||
ribs.value = []
|
||||
ribErrors.value = []
|
||||
}
|
||||
}
|
||||
|
||||
const canValidateAccounting = computed(() => {
|
||||
if (!hasAllRequiredAccountingFields(accounting)) return false
|
||||
if (isBankRequired.value && accounting.bankIri === null) return false
|
||||
if (isRibRequired.value && !ribs.value.some(ribIsComplete)) return false
|
||||
if (isRibRequired.value && !ribs.value.some(isRibComplete)) return false
|
||||
return true
|
||||
})
|
||||
|
||||
// « + RIB » desactive tant que le dernier bloc RIB n'est pas complet.
|
||||
const canAddRib = computed(() => {
|
||||
const last = ribs.value[ribs.value.length - 1]
|
||||
return last !== undefined && isRibComplete(last)
|
||||
})
|
||||
|
||||
function addRib(): void {
|
||||
ribs.value.push(emptyRib())
|
||||
if (canAddRib.value) ribs.value.push(emptyRib())
|
||||
}
|
||||
|
||||
function askRemoveRib(index: number): void {
|
||||
@@ -905,6 +965,9 @@ async function submitAccounting(): Promise<void> {
|
||||
if (accountingReadonly.value || !canValidateAccounting.value || tabSubmitting.value) return
|
||||
tabSubmitting.value = true
|
||||
accountingErrors.clearErrors()
|
||||
// Reset des erreurs RIB des le debut : l'etape 1 (PATCH scalaires) peut
|
||||
// echouer et `return` avant submitRows (qui porte sinon le reset), laissant
|
||||
// des erreurs de RIB obsoletes affichees sous les blocs.
|
||||
ribErrors.value = []
|
||||
try {
|
||||
// 1) PATCH des scalaires comptables (erreurs inline sur leurs champs).
|
||||
@@ -921,12 +984,14 @@ async function submitAccounting(): Promise<void> {
|
||||
}
|
||||
removedRibIds.value = []
|
||||
|
||||
// 2) POST/PATCH des RIB (erreurs inline par ligne).
|
||||
for (let index = 0; index < ribs.value.length; index++) {
|
||||
const rib = ribs.value[index]
|
||||
if (!ribIsComplete(rib)) continue
|
||||
const body = buildRibPayload(rib)
|
||||
try {
|
||||
// 2) POST/PATCH des RIB (erreurs inline par ligne, tous les blocs tentes).
|
||||
// Seuls les blocs RIB TOTALEMENT vides sont ignores : un RIB partiel (ex.
|
||||
// IBAN seul) est soumis -> 422 NotBlank (label / bic / iban) inline.
|
||||
const ribHasError = await submitRows(
|
||||
ribs.value,
|
||||
ribErrors,
|
||||
async (rib) => {
|
||||
const body = buildRibPayload(rib)
|
||||
if (rib.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/clients/${clientId}/ribs`,
|
||||
@@ -938,14 +1003,14 @@ async function submitAccounting(): Promise<void> {
|
||||
else {
|
||||
await api.patch(`/client_ribs/${rib.id}`, body, { toast: false })
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
if (!mapRowError(error, ribErrors, index)) {
|
||||
showError(error)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
},
|
||||
error => showError(error),
|
||||
// On ne saute QUE les amorces neuves (id null) totalement vides. Un
|
||||
// RIB existant vide est soumis -> 422 NotBlank inline (sinon la modif
|
||||
// serait perdue en silence avec un faux toast de succes).
|
||||
rib => rib.id === null && isRibBlank(rib),
|
||||
)
|
||||
if (ribHasError) return
|
||||
toast.success({ title: t('commercial.clients.toast.updateSuccess') })
|
||||
}
|
||||
catch (e) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div>
|
||||
<!-- En-tete : retour repertoire + nom du client + actions (Modifier / Archiver|Restaurer). -->
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="flex items-center gap-3 pt-11">
|
||||
<MalioButtonIcon
|
||||
icon="mdi:arrow-left-bold"
|
||||
icon-size="24"
|
||||
@@ -9,7 +9,7 @@
|
||||
v-bind="{ ariaLabel: t('commercial.clients.consultation.back') }"
|
||||
@click="goBack"
|
||||
/>
|
||||
<h1 class="text-[32px] font-bold text-m-primary">{{ headerTitle }}</h1>
|
||||
<h1 class="text-[30px] font-semibold text-m-primary">{{ headerTitle }}</h1>
|
||||
|
||||
<!-- gap-12 = 48px : meme espacement que Ajouter / Filtres du repertoire. -->
|
||||
<div class="ml-auto flex items-center gap-12">
|
||||
@@ -88,11 +88,14 @@
|
||||
<!-- Onglet Information -->
|
||||
<template #information>
|
||||
<div class="mt-12 grid grid-cols-4 gap-x-[44px] gap-y-4 bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
|
||||
<!-- pt-1/pb-1 alignent le textarea (h-full) en haut ET en bas
|
||||
sur les inputs (champ 40px centre dans un h-12 -> ~4px de
|
||||
coussin de chaque cote). -->
|
||||
<MalioInputTextArea
|
||||
:model-value="information.description"
|
||||
:label="t('commercial.clients.form.information.description')"
|
||||
resize="none"
|
||||
group-class="row-span-2 pt-1"
|
||||
group-class="row-span-2 pt-1 pb-1"
|
||||
text-input="h-full text-lg"
|
||||
readonly
|
||||
/>
|
||||
@@ -278,6 +281,7 @@
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useClient } from '~/modules/commercial/composables/useClient'
|
||||
import { buildClientFormTabKeys } from '~/modules/commercial/utils/clientFormRules'
|
||||
import { readHistoryTab } from '~/shared/utils/historyTab'
|
||||
import {
|
||||
canEditClient,
|
||||
categoryOptionsOf,
|
||||
@@ -293,7 +297,7 @@ import {
|
||||
type ClientDetail,
|
||||
type SelectOption,
|
||||
} from '~/modules/commercial/utils/clientConsultation'
|
||||
import { emptyAddress, emptyContact, emptyRib } from '~/modules/commercial/types/clientForm'
|
||||
import { emptyAddress, emptyContact } from '~/modules/commercial/types/clientForm'
|
||||
|
||||
// Masque d'affichage (purement visuel, la donnee reste celle du serveur).
|
||||
const SIREN_MASK = '#########'
|
||||
@@ -350,10 +354,10 @@ const addressViews = computed(() => {
|
||||
const views = (client.value?.addresses ?? []).map(mapAddressView)
|
||||
return views.length ? views : [{ draft: emptyAddress(), siteOptions: [], categoryOptions: [] }]
|
||||
})
|
||||
const ribs = computed(() => {
|
||||
const list = (client.value?.ribs ?? []).map(mapRibToDraft)
|
||||
return list.length ? list : [emptyRib()]
|
||||
})
|
||||
// Exception au placeholder ci-dessus : on n'affiche AUCUN bloc RIB quand le
|
||||
// client n'en a pas (un RIB n'existe que pour un reglement LCR — RG-1.13). Pas
|
||||
// de bloc vierge fantome en consultation.
|
||||
const ribs = computed(() => (client.value?.ribs ?? []).map(mapRibToDraft))
|
||||
// Draft comptable (tout null si l'utilisateur n'a pas accounting.view).
|
||||
const accounting = computed(() => mapAccountingDraft(client.value ?? ({} as ClientDetail)))
|
||||
|
||||
@@ -413,15 +417,17 @@ const tabs = computed(() => tabKeys.value.map(key => ({
|
||||
icon: TAB_ICONS[key],
|
||||
})))
|
||||
|
||||
const activeTab = ref('information')
|
||||
// Onglet initial : repris de l'edition au retour (history.state), sinon Information.
|
||||
const activeTab = ref(readHistoryTab(tabKeys.value) ?? 'information')
|
||||
|
||||
// ── Navigation ─────────────────────────────────────────────────────────────
|
||||
function goBack(): void {
|
||||
router.push('/clients')
|
||||
}
|
||||
|
||||
/** Bascule en edition en conservant l'onglet courant (via history.state). */
|
||||
function goEdit(): void {
|
||||
router.push(`/clients/${clientId}/edit`)
|
||||
router.push({ path: `/clients/${clientId}/edit`, state: { tab: activeTab.value } })
|
||||
}
|
||||
|
||||
// ── Archivage / Restauration ────────────────────────────────────────────────
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
{{ t('commercial.clients.title') }}
|
||||
<template #actions>
|
||||
<!-- gap-12 = 48px d'espacement entre Ajouter et Filtres. -->
|
||||
<div class="flex items-center gap-12">
|
||||
<div class="flex items-center gap-8">
|
||||
<MalioButton
|
||||
v-if="canManage"
|
||||
variant="secondary"
|
||||
@@ -21,8 +21,8 @@
|
||||
:label="filterButtonLabel"
|
||||
icon-name="mdi:tune"
|
||||
icon-position="left"
|
||||
icon-size="24"
|
||||
button-class="w-[184px] justify-start gap-4 text-black"
|
||||
icon-size="20"
|
||||
button-class="w-[180px] justify-start gap-4 text-black"
|
||||
@click="openFilters"
|
||||
/>
|
||||
</div>
|
||||
@@ -39,7 +39,7 @@
|
||||
:per-page="itemsPerPage"
|
||||
:per-page-options="itemsPerPageOptions"
|
||||
row-clickable
|
||||
table-class="table-fixed"
|
||||
table-class="table-fixed clients-table"
|
||||
:empty-message="t('commercial.clients.empty')"
|
||||
@row-click="onRowClick"
|
||||
@update:page="goToPage"
|
||||
@@ -56,7 +56,7 @@
|
||||
<span
|
||||
v-for="site in (item.sites as ClientSite[])"
|
||||
:key="site.id"
|
||||
class="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium text-white"
|
||||
class="inline-flex items-center rounded-full px-2 py-0.5 font-medium text-white"
|
||||
:style="{ backgroundColor: site.color }"
|
||||
>
|
||||
{{ site.name }}
|
||||
@@ -70,7 +70,7 @@
|
||||
</template>
|
||||
</MalioDataTable>
|
||||
|
||||
<div class="flex justify-center mt-6">
|
||||
<div class="flex justify-center mt-4">
|
||||
<MalioButton
|
||||
v-if="canView"
|
||||
variant="primary"
|
||||
@@ -350,7 +350,9 @@ async function loadFilterOptions(): Promise<void> {
|
||||
const [cats, sites] = await Promise.all([
|
||||
api.get<{ member?: Array<{ code: string, name: string }> }>(
|
||||
'/categories',
|
||||
{ pagination: 'false' },
|
||||
// Taxonomie multi-types (ERP-84) : le filtre du repertoire client ne
|
||||
// propose que les categories de type CLIENT (pas les FOURNISSEUR).
|
||||
{ pagination: 'false', typeCode: 'CLIENT' },
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
),
|
||||
api.get<{ member?: Array<{ id: number, name: string }> }>(
|
||||
@@ -419,3 +421,16 @@ onMounted(() => {
|
||||
})
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/*
|
||||
* Colonne Sites uniquement (3e colonne : companyName, categories, SITES,
|
||||
* lastActivity) : ses badges rendent la cellule trop haute. On reduit le padding
|
||||
* vertical de SON td (16px Malio -> 8px) sans toucher les autres colonnes ni les
|
||||
* couleurs/tailles (qui restent sur les defauts Malio).
|
||||
*/
|
||||
:deep(.clients-table tbody td:nth-child(3)) {
|
||||
padding-top: 8px;
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div>
|
||||
<!-- En-tete : retour vers le repertoire + titre. -->
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="flex items-center gap-3 pt-11">
|
||||
<MalioButtonIcon
|
||||
icon="mdi:arrow-left-bold"
|
||||
icon-size="24"
|
||||
@@ -9,7 +9,7 @@
|
||||
v-bind="{ ariaLabel: t('commercial.clients.form.back') }"
|
||||
@click="goBack"
|
||||
/>
|
||||
<h1 class="text-[32px] font-bold text-m-primary">{{ t('commercial.clients.form.title') }}</h1>
|
||||
<h1 class="text-[30px] font-semibold text-m-primary">{{ t('commercial.clients.form.title') }}</h1>
|
||||
</div>
|
||||
|
||||
<!-- ── Formulaire principal (pre-onglets) ─────────────────────────────
|
||||
@@ -35,6 +35,7 @@
|
||||
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
|
||||
/>
|
||||
<MalioSelect
|
||||
v-if="showRelationAndTriage"
|
||||
:model-value="main.relationType"
|
||||
:options="relationOptions"
|
||||
:label="t('commercial.clients.form.main.relation')"
|
||||
@@ -43,7 +44,7 @@
|
||||
@update:model-value="onRelationChange"
|
||||
/>
|
||||
<MalioSelect
|
||||
v-if="main.relationType === 'courtier'"
|
||||
v-if="showRelationAndTriage && main.relationType === 'courtier'"
|
||||
:model-value="main.brokerIri"
|
||||
:options="referentials.brokers.value"
|
||||
:label="t('commercial.clients.form.main.brokerName')"
|
||||
@@ -53,7 +54,7 @@
|
||||
@update:model-value="(v: string | number | null) => main.brokerIri = v === null ? null : String(v)"
|
||||
/>
|
||||
<MalioSelect
|
||||
v-if="main.relationType === 'distributeur'"
|
||||
v-if="showRelationAndTriage && main.relationType === 'distributeur'"
|
||||
:model-value="main.distributorIri"
|
||||
:options="referentials.distributors.value"
|
||||
:label="t('commercial.clients.form.main.distributorName')"
|
||||
@@ -63,6 +64,7 @@
|
||||
@update:model-value="(v: string | number | null) => main.distributorIri = v === null ? null : String(v)"
|
||||
/>
|
||||
<MalioCheckbox
|
||||
v-if="showRelationAndTriage"
|
||||
v-model="main.triageService"
|
||||
:label="t('commercial.clients.form.main.triageService')"
|
||||
group-class="self-center"
|
||||
@@ -84,13 +86,15 @@
|
||||
<!-- Onglet Information -->
|
||||
<template #information>
|
||||
<div class="mt-12 grid grid-cols-4 gap-x-[44px] gap-y-4 bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
|
||||
<!-- pt-1 : aligne le bord superieur du textarea sur celui des
|
||||
inputs (centres dans un conteneur h-12, soit ~4px de retrait haut). -->
|
||||
<!-- pt-1/pb-1 alignent le textarea (h-full) sur les inputs, dont
|
||||
le champ de 40px est centre dans un conteneur h-12 (~4px de
|
||||
coussin en HAUT et en BAS). Sans pb-1, le textarea descend ~4px
|
||||
plus bas que les champs voisins. -->
|
||||
<MalioInputTextArea
|
||||
v-model="information.description"
|
||||
:label="t('commercial.clients.form.information.description')"
|
||||
resize="none"
|
||||
group-class="row-span-2 pt-1"
|
||||
group-class="row-span-2 pt-1 pb-1"
|
||||
text-input="h-full text-lg"
|
||||
:readonly="isValidated('information')"
|
||||
:error="informationErrors.errors.description"
|
||||
@@ -134,13 +138,15 @@
|
||||
/>
|
||||
</div>
|
||||
<div v-if="!isValidated('information')" class="mt-12 flex justify-center">
|
||||
<!-- Desactive tant que le client n'est pas cree : evite un PATCH
|
||||
avant le POST si l'utilisateur clique trop tot (le panneau
|
||||
Information est l'onglet actif par defaut). -->
|
||||
<!-- Desactive tant que le client n'est pas cree (evite un PATCH
|
||||
avant le POST si clic trop tot, Information etant l'onglet
|
||||
actif par defaut) OU si aucun champ n'est rempli : onglet
|
||||
facultatif, mais pas de validation a vide (on passe alors
|
||||
directement a Contact). -->
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('commercial.clients.form.submit')"
|
||||
:disabled="tabSubmitting || clientId === null"
|
||||
:disabled="tabSubmitting || clientId === null || !canValidateInformation"
|
||||
@click="submitInformation"
|
||||
/>
|
||||
</div>
|
||||
@@ -204,6 +210,7 @@
|
||||
icon-name="mdi:add-bold"
|
||||
icon-position="left"
|
||||
:label="t('commercial.clients.form.address.add')"
|
||||
:disabled="!canAddAddress"
|
||||
@click="addAddress"
|
||||
/>
|
||||
<MalioButton
|
||||
@@ -287,9 +294,9 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Blocs RIB (0..n) — obligatoires si type de reglement = LCR. -->
|
||||
<!-- Blocs RIB — affiches uniquement si type de reglement = LCR (RG-1.13). -->
|
||||
<div
|
||||
v-for="(rib, index) in ribs"
|
||||
v-for="(rib, index) in visibleRibs"
|
||||
:key="index"
|
||||
class="relative bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]"
|
||||
>
|
||||
@@ -329,10 +336,12 @@
|
||||
|
||||
<div v-if="!accountingReadonly" class="flex justify-center gap-6">
|
||||
<MalioButton
|
||||
v-if="isRibRequired"
|
||||
variant="secondary"
|
||||
icon-name="mdi:add-bold"
|
||||
icon-position="left"
|
||||
:label="t('commercial.clients.form.accounting.addRib')"
|
||||
:disabled="!canAddRib"
|
||||
@click="addRib"
|
||||
/>
|
||||
<MalioButton
|
||||
@@ -382,11 +391,18 @@ import { useClientFormErrors } from '~/modules/commercial/composables/useClientF
|
||||
import {
|
||||
buildClientFormTabKeys,
|
||||
CLIENT_FORM_PLACEHOLDER_TABS,
|
||||
hasAllRequiredAccountingFields,
|
||||
hasAtLeastOneInformationField,
|
||||
hasAtLeastOneValidContact,
|
||||
isAddressValid,
|
||||
isBankRequiredForPaymentType,
|
||||
isBillingEmailRequired,
|
||||
isContactBlank,
|
||||
isContactNamed,
|
||||
isRibBlank,
|
||||
isRibComplete,
|
||||
isRibRequiredForPaymentType,
|
||||
showsRelationAndTriageFields,
|
||||
} from '~/modules/commercial/utils/clientFormRules'
|
||||
import {
|
||||
emptyAddress,
|
||||
@@ -441,7 +457,7 @@ const {
|
||||
contactErrors,
|
||||
addressErrors,
|
||||
ribErrors,
|
||||
mapRowError,
|
||||
submitRows,
|
||||
} = useClientFormErrors()
|
||||
|
||||
useHead({ title: t('commercial.clients.form.title') })
|
||||
@@ -479,6 +495,28 @@ const relationOptions = computed<RefOption[]>(() => [
|
||||
{ value: 'courtier', label: t('commercial.clients.form.main.relationBroker') },
|
||||
])
|
||||
|
||||
// Codes des categories selectionnees (resolus depuis les IRI du brouillon).
|
||||
const selectedCategoryCodes = computed(() =>
|
||||
main.categoryIris
|
||||
.map(iri => referentials.categories.value.find(c => c.value === iri)?.code)
|
||||
.filter((code): code is string => code !== undefined),
|
||||
)
|
||||
|
||||
// « Relation » + « Prestation de triage » masques par defaut, reveles des qu'une
|
||||
// categorie ordinaire (autre que Distributeur/Courtier) est selectionnee.
|
||||
const showRelationAndTriage = computed(() => showsRelationAndTriageFields(selectedCategoryCodes.value))
|
||||
|
||||
// Masquer ces champs reinitialise leurs valeurs : pas de relation/triage fantome
|
||||
// soumis pour un client Distributeur/Courtier.
|
||||
watch(showRelationAndTriage, (visible) => {
|
||||
if (!visible) {
|
||||
main.relationType = null
|
||||
main.distributorIri = null
|
||||
main.brokerIri = null
|
||||
main.triageService = false
|
||||
}
|
||||
})
|
||||
|
||||
// Validation du formulaire principal (gate le bouton « Valider ») :
|
||||
// - companyName / >= 1 categorie obligatoires ;
|
||||
// - relation Distributeur/Courtier optionnelle, mais le nom correspondant
|
||||
@@ -534,7 +572,9 @@ async function submitMain(): Promise<void> {
|
||||
main.companyName = created.companyName ?? main.companyName
|
||||
|
||||
mainLocked.value = true
|
||||
unlockedIndex.value = 0
|
||||
// Information est facultatif : on deverrouille jusqu'a Contact (index 1)
|
||||
// pour que l'utilisateur puisse y aller directement sans valider Information.
|
||||
unlockedIndex.value = tabIndex('contact')
|
||||
activeTab.value = 'information'
|
||||
toast.success({ title: t('commercial.clients.toast.createSuccess') })
|
||||
}
|
||||
@@ -621,9 +661,12 @@ const information = reactive({
|
||||
directorName: null as string | null,
|
||||
})
|
||||
|
||||
// Onglet facultatif, mais pas de validation « a vide » : au moins un champ rempli.
|
||||
const canValidateInformation = computed(() => hasAtLeastOneInformationField(information))
|
||||
|
||||
/** PATCH /clients/{id} — mode strict : uniquement les champs du groupe information. */
|
||||
async function submitInformation(): Promise<void> {
|
||||
if (clientId.value === null || tabSubmitting.value) return
|
||||
if (clientId.value === null || tabSubmitting.value || !canValidateInformation.value) return
|
||||
tabSubmitting.value = true
|
||||
informationErrors.clearErrors()
|
||||
try {
|
||||
@@ -676,23 +719,22 @@ function askRemoveContact(index: number): void {
|
||||
async function submitContacts(): Promise<void> {
|
||||
if (clientId.value === null || !canValidateContacts.value || tabSubmitting.value) return
|
||||
tabSubmitting.value = true
|
||||
contactErrors.value = []
|
||||
try {
|
||||
for (let index = 0; index < contacts.value.length; index++) {
|
||||
const contact = contacts.value[index]
|
||||
// On ignore les blocs totalement vides (ni nom ni prenom).
|
||||
if (!isContactNamed(contact)) continue
|
||||
|
||||
const body = {
|
||||
firstName: contact.firstName || null,
|
||||
lastName: contact.lastName || null,
|
||||
jobTitle: contact.jobTitle || null,
|
||||
phonePrimary: contact.phonePrimary || null,
|
||||
phoneSecondary: contact.hasSecondaryPhone ? (contact.phoneSecondary || null) : null,
|
||||
email: contact.email || null,
|
||||
}
|
||||
|
||||
try {
|
||||
// On tente TOUS les blocs (collecte des erreurs par index, ERP-110). Seuls
|
||||
// les blocs TOTALEMENT vides sont ignores : un bloc partiellement rempli
|
||||
// sans nom (email seul) est soumis -> 422 RG-1.05 inline sous le bloc.
|
||||
const hasError = await submitRows(
|
||||
contacts.value,
|
||||
contactErrors,
|
||||
async (contact) => {
|
||||
const body = {
|
||||
firstName: contact.firstName || null,
|
||||
lastName: contact.lastName || null,
|
||||
jobTitle: contact.jobTitle || null,
|
||||
phonePrimary: contact.phonePrimary || null,
|
||||
phoneSecondary: contact.hasSecondaryPhone ? (contact.phoneSecondary || null) : null,
|
||||
email: contact.email || null,
|
||||
}
|
||||
if (contact.id === null) {
|
||||
const created = await api.post<ContactResponse>(
|
||||
`/clients/${clientId.value}/contacts`,
|
||||
@@ -705,16 +747,15 @@ async function submitContacts(): Promise<void> {
|
||||
else {
|
||||
await api.patch(`/client_contacts/${contact.id}`, body, { toast: false })
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
// 422 → erreurs inline sous les champs de CETTE ligne ; on stoppe
|
||||
// a la premiere ligne en echec (les suivantes ne sont pas tentees).
|
||||
if (!mapRowError(error, contactErrors, index)) {
|
||||
toast.error({ title: t('commercial.clients.toast.error'), message: apiErrorMessage(error) })
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
},
|
||||
error => toast.error({ title: t('commercial.clients.toast.error'), message: apiErrorMessage(error) }),
|
||||
// On ne saute QUE les amorces neuves (id null) totalement vides. Un
|
||||
// bloc existant vide est soumis -> 422 RG-1.05 inline (sinon la modif
|
||||
// serait perdue en silence avec un faux toast de succes).
|
||||
contact => contact.id === null && isContactBlank(contact),
|
||||
)
|
||||
// Tant qu'un bloc reste en erreur : pas de validation d'onglet ni de toast succes.
|
||||
if (hasError) return
|
||||
completeTab('contact')
|
||||
toast.success({ title: t('commercial.clients.toast.updateSuccess') })
|
||||
}
|
||||
@@ -748,19 +789,20 @@ const countryOptions: RefOption[] = [
|
||||
{ value: 'Espagne', label: 'Espagne' },
|
||||
]
|
||||
|
||||
// RG-1.10 (>= 1 site) + RG-1.11 (email facturation si Facturation) sur chaque adresse.
|
||||
// Type d'adresse (Select) obligatoire + RG-1.10 (>= 1 site) + RG-1.11 (email
|
||||
// facturation si Facturation) sur chaque adresse.
|
||||
const canValidateAddresses = computed(() =>
|
||||
addresses.value.length > 0
|
||||
&& addresses.value.every((a) => {
|
||||
const filledBillingEmail = a.billingEmail !== null && a.billingEmail.trim() !== ''
|
||||
return a.siteIris.length >= 1
|
||||
&& a.categoryIris.length >= 1
|
||||
&& (!isBillingEmailRequired(a) || filledBillingEmail)
|
||||
}),
|
||||
addresses.value.length > 0 && addresses.value.every(isAddressValid),
|
||||
)
|
||||
|
||||
// « + Adresse » desactive tant que la derniere adresse n'est pas valide.
|
||||
const canAddAddress = computed(() => {
|
||||
const last = addresses.value[addresses.value.length - 1]
|
||||
return last !== undefined && isAddressValid(last)
|
||||
})
|
||||
|
||||
function addAddress(): void {
|
||||
addresses.value.push(emptyAddress())
|
||||
if (canAddAddress.value) addresses.value.push(emptyAddress())
|
||||
}
|
||||
|
||||
function askRemoveAddress(index: number): void {
|
||||
@@ -784,26 +826,26 @@ function onAddressDegraded(): void {
|
||||
async function submitAddresses(): Promise<void> {
|
||||
if (clientId.value === null || !canValidateAddresses.value || tabSubmitting.value) return
|
||||
tabSubmitting.value = true
|
||||
addressErrors.value = []
|
||||
try {
|
||||
for (let index = 0; index < addresses.value.length; index++) {
|
||||
const address = addresses.value[index]
|
||||
const body = {
|
||||
isProspect: address.isProspect,
|
||||
isDelivery: address.isDelivery,
|
||||
isBilling: address.isBilling,
|
||||
country: address.country,
|
||||
postalCode: address.postalCode || null,
|
||||
city: address.city || null,
|
||||
street: address.street || null,
|
||||
streetComplement: address.streetComplement || null,
|
||||
categories: address.categoryIris,
|
||||
sites: address.siteIris,
|
||||
contacts: address.contactIris,
|
||||
billingEmail: isBillingEmailRequired(address) ? (address.billingEmail || null) : null,
|
||||
}
|
||||
|
||||
try {
|
||||
// On tente TOUS les blocs d'adresse (collecte des erreurs par index, ERP-110).
|
||||
const hasError = await submitRows(
|
||||
addresses.value,
|
||||
addressErrors,
|
||||
async (address) => {
|
||||
const body = {
|
||||
isProspect: address.isProspect,
|
||||
isDelivery: address.isDelivery,
|
||||
isBilling: address.isBilling,
|
||||
country: address.country,
|
||||
postalCode: address.postalCode || null,
|
||||
city: address.city || null,
|
||||
street: address.street || null,
|
||||
streetComplement: address.streetComplement || null,
|
||||
categories: address.categoryIris,
|
||||
sites: address.siteIris,
|
||||
contacts: address.contactIris,
|
||||
billingEmail: isBillingEmailRequired(address) ? (address.billingEmail || null) : null,
|
||||
}
|
||||
if (address.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/clients/${clientId.value}/addresses`,
|
||||
@@ -815,14 +857,10 @@ async function submitAddresses(): Promise<void> {
|
||||
else {
|
||||
await api.patch(`/client_addresses/${address.id}`, body, { toast: false })
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
if (!mapRowError(error, addressErrors, index)) {
|
||||
toast.error({ title: t('commercial.clients.toast.error'), message: apiErrorMessage(error) })
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
},
|
||||
error => toast.error({ title: t('commercial.clients.toast.error'), message: apiErrorMessage(error) }),
|
||||
)
|
||||
if (hasError) return
|
||||
completeTab('address')
|
||||
toast.success({ title: t('commercial.clients.toast.updateSuccess') })
|
||||
}
|
||||
@@ -853,26 +891,42 @@ const selectedPaymentTypeCode = computed(() =>
|
||||
const isBankRequired = computed(() => isBankRequiredForPaymentType(selectedPaymentTypeCode.value))
|
||||
const isRibRequired = computed(() => isRibRequiredForPaymentType(selectedPaymentTypeCode.value))
|
||||
|
||||
// Les blocs RIB ne sont affiches que pour une LCR (RG-1.13).
|
||||
const visibleRibs = computed(() => isRibRequired.value ? ribs.value : [])
|
||||
|
||||
function onPaymentTypeChange(value: string | number | null): void {
|
||||
accounting.paymentTypeIri = value === null ? null : String(value)
|
||||
// La banque n'a de sens que pour un virement : on la vide sinon (RG-1.12).
|
||||
if (!isBankRequired.value) accounting.bankIri = null
|
||||
// Les RIB n'ont de sens que pour une LCR (RG-1.13) : on amorce un bloc vide
|
||||
// quand LCR est choisi, on vide la liste sinon (pas de RIB fantome soumis).
|
||||
if (isRibRequired.value) {
|
||||
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||
}
|
||||
else {
|
||||
ribs.value = []
|
||||
ribErrors.value = []
|
||||
}
|
||||
}
|
||||
|
||||
function ribIsComplete(rib: RibFormDraft): boolean {
|
||||
const filled = (v: string | null) => v !== null && v.trim() !== ''
|
||||
return filled(rib.label) && filled(rib.bic) && filled(rib.iban)
|
||||
}
|
||||
|
||||
// RG-1.30 : les 6 champs scalaires obligatoires (comme les onglets Contact /
|
||||
// Adresse, le bouton reste desactive tant que l'onglet n'est pas complet).
|
||||
// RG-1.12 : banque requise si VIREMENT. RG-1.13 : >= 1 RIB complet si LCR.
|
||||
const canValidateAccounting = computed(() => {
|
||||
if (!hasAllRequiredAccountingFields(accounting)) return false
|
||||
if (isBankRequired.value && (accounting.bankIri === null)) return false
|
||||
if (isRibRequired.value && !ribs.value.some(ribIsComplete)) return false
|
||||
if (isRibRequired.value && !ribs.value.some(isRibComplete)) return false
|
||||
return true
|
||||
})
|
||||
|
||||
// « + RIB » desactive tant que le dernier bloc RIB n'est pas complet.
|
||||
const canAddRib = computed(() => {
|
||||
const last = ribs.value[ribs.value.length - 1]
|
||||
return last !== undefined && isRibComplete(last)
|
||||
})
|
||||
|
||||
function addRib(): void {
|
||||
ribs.value.push(emptyRib())
|
||||
if (canAddRib.value) ribs.value.push(emptyRib())
|
||||
}
|
||||
|
||||
function askRemoveRib(index: number): void {
|
||||
@@ -893,6 +947,9 @@ async function submitAccounting(): Promise<void> {
|
||||
if (clientId.value === null || !canValidateAccounting.value || tabSubmitting.value) return
|
||||
tabSubmitting.value = true
|
||||
accountingErrors.clearErrors()
|
||||
// Reset des erreurs RIB des le debut : l'etape 1 (PATCH scalaires) peut
|
||||
// echouer et `return` avant submitRows (qui porte sinon le reset), laissant
|
||||
// des erreurs de RIB obsoletes affichees sous les blocs.
|
||||
ribErrors.value = []
|
||||
try {
|
||||
// 1) PATCH des scalaires comptables (erreurs inline sur leurs champs).
|
||||
@@ -912,30 +969,33 @@ async function submitAccounting(): Promise<void> {
|
||||
return
|
||||
}
|
||||
|
||||
// 2) POST/PATCH des RIB (erreurs inline par ligne).
|
||||
for (let index = 0; index < ribs.value.length; index++) {
|
||||
const rib = ribs.value[index]
|
||||
if (!ribIsComplete(rib)) continue
|
||||
try {
|
||||
// 2) POST/PATCH des RIB (erreurs inline par ligne, tous les blocs tentes).
|
||||
// Seuls les blocs RIB TOTALEMENT vides sont ignores : un RIB partiel (ex.
|
||||
// IBAN seul) est soumis -> 422 NotBlank (label / bic / iban) inline.
|
||||
const ribHasError = await submitRows(
|
||||
ribs.value,
|
||||
ribErrors,
|
||||
async (rib) => {
|
||||
const body = { label: rib.label, bic: rib.bic, iban: rib.iban }
|
||||
if (rib.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/clients/${clientId.value}/ribs`,
|
||||
{ label: rib.label, bic: rib.bic, iban: rib.iban },
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
rib.id = created.id
|
||||
}
|
||||
else {
|
||||
await api.patch(`/client_ribs/${rib.id}`, { label: rib.label, bic: rib.bic, iban: rib.iban }, { toast: false })
|
||||
await api.patch(`/client_ribs/${rib.id}`, body, { toast: false })
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
if (!mapRowError(error, ribErrors, index)) {
|
||||
toast.error({ title: t('commercial.clients.toast.error'), message: apiErrorMessage(error) })
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
},
|
||||
error => toast.error({ title: t('commercial.clients.toast.error'), message: apiErrorMessage(error) }),
|
||||
// On ne saute QUE les amorces neuves (id null) totalement vides. Un
|
||||
// RIB existant vide est soumis -> 422 NotBlank inline (sinon la modif
|
||||
// serait perdue en silence avec un faux toast de succes).
|
||||
rib => rib.id === null && isRibBlank(rib),
|
||||
)
|
||||
if (ribHasError) return
|
||||
|
||||
completeTab('accounting')
|
||||
toast.success({ title: t('commercial.clients.toast.updateSuccess') })
|
||||
@@ -978,8 +1038,7 @@ interface ContactResponse {
|
||||
onMounted(() => {
|
||||
// Echec du chargement des referentiels non bloquant : les selects restent vides.
|
||||
referentials.loadCommon().catch(() => {})
|
||||
// Au moins un bloc RIB toujours visible en creation : on amorce un bloc vide
|
||||
// (non persiste tant qu'incomplet — RG-1.13).
|
||||
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||
// Pas d'amorce de RIB ici : un bloc vide n'apparait que si LCR est choisi
|
||||
// (cf. onPaymentTypeChange).
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -1,17 +1,41 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
addressFlagsFromType,
|
||||
addressTypeFromFlags,
|
||||
applyProspectExclusivity,
|
||||
buildClientFormTabKeys,
|
||||
canSelectDeliveryOrBilling,
|
||||
canSelectProspect,
|
||||
hasAllRequiredAccountingFields,
|
||||
hasAtLeastOneInformationField,
|
||||
hasAtLeastOneValidContact,
|
||||
isAddressValid,
|
||||
isBankRequiredForPaymentType,
|
||||
isBillingEmailRequired,
|
||||
isBlankRow,
|
||||
isContactBlank,
|
||||
isContactNamed,
|
||||
isRibBlank,
|
||||
isRibComplete,
|
||||
isRibRequiredForPaymentType,
|
||||
showsRelationAndTriageFields,
|
||||
type AddressValidityDraft,
|
||||
type ContactDraft,
|
||||
type ContactFillableDraft,
|
||||
} from '../clientFormRules'
|
||||
|
||||
/** Bloc contact totalement vide (amorce par defaut). */
|
||||
function blankContact(): ContactFillableDraft {
|
||||
return {
|
||||
firstName: null,
|
||||
lastName: null,
|
||||
jobTitle: null,
|
||||
phonePrimary: null,
|
||||
phoneSecondary: null,
|
||||
email: null,
|
||||
}
|
||||
}
|
||||
|
||||
describe('buildClientFormTabKeys (gating onglet Comptabilite + onglets edit-only)', () => {
|
||||
it('inclut l onglet accounting si l utilisateur a accounting.view', () => {
|
||||
expect(buildClientFormTabKeys(true)).toContain('accounting')
|
||||
@@ -59,6 +83,49 @@ describe('isContactNamed (RG-1.05)', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('isBlankRow (primitive : toutes les valeurs vides)', () => {
|
||||
it('vrai si toutes les valeurs sont nulles / vides / espaces', () => {
|
||||
expect(isBlankRow([null, undefined, '', ' '])).toBe(true)
|
||||
expect(isBlankRow([])).toBe(true)
|
||||
})
|
||||
|
||||
it('faux des qu une valeur porte un caractere non-espace', () => {
|
||||
expect(isBlankRow([null, 'x', ''])).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isRibBlank (bloc RIB totalement vide vs partiellement rempli)', () => {
|
||||
it('vrai si label / bic / iban sont tous vides', () => {
|
||||
expect(isRibBlank({ label: null, bic: null, iban: null })).toBe(true)
|
||||
expect(isRibBlank({ label: ' ', bic: '', iban: null })).toBe(true)
|
||||
})
|
||||
|
||||
it('faux si un IBAN seul est saisi (bloc a soumettre -> 422 NotBlank inline)', () => {
|
||||
expect(isRibBlank({ label: null, bic: null, iban: 'FR1420041010050500013M02606' })).toBe(false)
|
||||
})
|
||||
|
||||
it('faux si seul le libelle est saisi', () => {
|
||||
expect(isRibBlank({ label: 'Compte courant', bic: null, iban: null })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isContactBlank (bloc totalement vide vs partiellement rempli)', () => {
|
||||
it('vrai si aucun champ saisissable n est rempli', () => {
|
||||
expect(isContactBlank(blankContact())).toBe(true)
|
||||
expect(isContactBlank({ ...blankContact(), firstName: ' ', email: '' })).toBe(true)
|
||||
})
|
||||
|
||||
it('faux si un email seul est saisi (bloc a soumettre -> 422 RG-1.05 inline)', () => {
|
||||
expect(isContactBlank({ ...blankContact(), email: 'jean@acme.fr' })).toBe(false)
|
||||
})
|
||||
|
||||
it('faux si seul un telephone, une fonction ou un nom est saisi', () => {
|
||||
expect(isContactBlank({ ...blankContact(), phonePrimary: '0612345678' })).toBe(false)
|
||||
expect(isContactBlank({ ...blankContact(), jobTitle: 'Directeur' })).toBe(false)
|
||||
expect(isContactBlank({ ...blankContact(), firstName: 'Alice' })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasAtLeastOneValidContact (RG-1.14)', () => {
|
||||
it('faux sur une liste vide', () => {
|
||||
expect(hasAtLeastOneValidContact([])).toBe(false)
|
||||
@@ -137,6 +204,32 @@ describe('isBillingEmailRequired (RG-1.11)', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('type d\'adresse (Select front) <-> drapeaux back', () => {
|
||||
it('addressFlagsFromType mappe chaque type vers les bons drapeaux', () => {
|
||||
expect(addressFlagsFromType('prospect')).toEqual({ isProspect: true, isDelivery: false, isBilling: false })
|
||||
expect(addressFlagsFromType('delivery')).toEqual({ isProspect: false, isDelivery: true, isBilling: false })
|
||||
expect(addressFlagsFromType('billing')).toEqual({ isProspect: false, isDelivery: false, isBilling: true })
|
||||
expect(addressFlagsFromType('delivery_billing')).toEqual({ isProspect: false, isDelivery: true, isBilling: true })
|
||||
})
|
||||
|
||||
it('addressTypeFromFlags reconstruit le type (Prospect prioritaire, livraison+facturation groupes)', () => {
|
||||
expect(addressTypeFromFlags({ isProspect: true, isDelivery: false, isBilling: false })).toBe('prospect')
|
||||
expect(addressTypeFromFlags({ isProspect: false, isDelivery: true, isBilling: false })).toBe('delivery')
|
||||
expect(addressTypeFromFlags({ isProspect: false, isDelivery: false, isBilling: true })).toBe('billing')
|
||||
expect(addressTypeFromFlags({ isProspect: false, isDelivery: true, isBilling: true })).toBe('delivery_billing')
|
||||
})
|
||||
|
||||
it('addressTypeFromFlags retourne null quand aucun drapeau (amorce vierge -> bouton bloque)', () => {
|
||||
expect(addressTypeFromFlags({ isProspect: false, isDelivery: false, isBilling: false })).toBeNull()
|
||||
})
|
||||
|
||||
it('aller-retour type -> drapeaux -> type stable pour les 4 types', () => {
|
||||
for (const type of ['prospect', 'delivery', 'billing', 'delivery_billing'] as const) {
|
||||
expect(addressTypeFromFlags(addressFlagsFromType(type))).toBe(type)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('regles type de reglement (RG-1.12 / RG-1.13)', () => {
|
||||
it('banque obligatoire si VIREMENT', () => {
|
||||
expect(isBankRequiredForPaymentType('VIREMENT')).toBe(true)
|
||||
@@ -150,3 +243,129 @@ describe('regles type de reglement (RG-1.12 / RG-1.13)', () => {
|
||||
expect(isRibRequiredForPaymentType(null)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasAllRequiredAccountingFields (RG-1.30)', () => {
|
||||
const complete = {
|
||||
siren: '123456789',
|
||||
accountNumber: '00012345678',
|
||||
nTva: 'FR12345678901',
|
||||
tvaModeIri: '/api/tva_modes/1',
|
||||
paymentDelayIri: '/api/payment_delays/1',
|
||||
paymentTypeIri: '/api/payment_types/1',
|
||||
}
|
||||
|
||||
it('vrai quand les six champs obligatoires sont remplis', () => {
|
||||
expect(hasAllRequiredAccountingFields(complete)).toBe(true)
|
||||
})
|
||||
|
||||
it('faux si un champ est manquant (null ou vide apres trim)', () => {
|
||||
expect(hasAllRequiredAccountingFields({ ...complete, siren: null })).toBe(false)
|
||||
expect(hasAllRequiredAccountingFields({ ...complete, accountNumber: ' ' })).toBe(false)
|
||||
expect(hasAllRequiredAccountingFields({ ...complete, tvaModeIri: null })).toBe(false)
|
||||
expect(hasAllRequiredAccountingFields({ ...complete, paymentTypeIri: null })).toBe(false)
|
||||
})
|
||||
|
||||
it('faux quand tout est vide (onglet non rempli)', () => {
|
||||
expect(hasAllRequiredAccountingFields({
|
||||
siren: null,
|
||||
accountNumber: null,
|
||||
nTva: null,
|
||||
tvaModeIri: null,
|
||||
paymentDelayIri: null,
|
||||
paymentTypeIri: null,
|
||||
})).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('showsRelationAndTriageFields (affichage Relation + Triage selon categorie)', () => {
|
||||
it('faux par defaut (aucune categorie selectionnee)', () => {
|
||||
expect(showsRelationAndTriageFields([])).toBe(false)
|
||||
})
|
||||
|
||||
it('faux si seules des categories Distributeur / Courtier sont selectionnees', () => {
|
||||
expect(showsRelationAndTriageFields(['DISTRIBUTEUR'])).toBe(false)
|
||||
expect(showsRelationAndTriageFields(['COURTIER'])).toBe(false)
|
||||
expect(showsRelationAndTriageFields(['DISTRIBUTEUR', 'COURTIER'])).toBe(false)
|
||||
})
|
||||
|
||||
it('vrai des qu\'une categorie ordinaire est selectionnee', () => {
|
||||
expect(showsRelationAndTriageFields(['CLIENT'])).toBe(true)
|
||||
expect(showsRelationAndTriageFields(['DISTRIBUTEUR', 'CLIENT'])).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasAtLeastOneInformationField (pas de validation a vide a la creation)', () => {
|
||||
const blank = {
|
||||
description: null,
|
||||
competitors: null,
|
||||
foundedAt: null,
|
||||
employeesCount: null,
|
||||
revenueAmount: null,
|
||||
profitAmount: null,
|
||||
directorName: null,
|
||||
}
|
||||
|
||||
it('faux quand aucun champ n\'est rempli (onglet vierge)', () => {
|
||||
expect(hasAtLeastOneInformationField(blank)).toBe(false)
|
||||
expect(hasAtLeastOneInformationField({ ...blank, description: ' ' })).toBe(false)
|
||||
})
|
||||
|
||||
it('vrai des qu\'un champ porte une valeur', () => {
|
||||
expect(hasAtLeastOneInformationField({ ...blank, description: 'Acteur majeur' })).toBe(true)
|
||||
expect(hasAtLeastOneInformationField({ ...blank, employeesCount: '42' })).toBe(true)
|
||||
expect(hasAtLeastOneInformationField({ ...blank, foundedAt: '2020-01-01' })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isAddressValid (gating « + Adresse » + validation onglet)', () => {
|
||||
/** Adresse de livraison valide (type + site + categorie ; pas de facturation). */
|
||||
function validDelivery(): AddressValidityDraft {
|
||||
return {
|
||||
isProspect: false,
|
||||
isDelivery: true,
|
||||
isBilling: false,
|
||||
categoryIris: ['/api/client_categories/1'],
|
||||
siteIris: ['/api/sites/1'],
|
||||
billingEmail: null,
|
||||
}
|
||||
}
|
||||
|
||||
it('vrai quand type + >= 1 site + >= 1 categorie (sans facturation)', () => {
|
||||
expect(isAddressValid(validDelivery())).toBe(true)
|
||||
})
|
||||
|
||||
it('faux si aucun drapeau (type d\'adresse non renseigne, amorce vierge)', () => {
|
||||
expect(isAddressValid({ ...validDelivery(), isDelivery: false })).toBe(false)
|
||||
})
|
||||
|
||||
it('faux si aucun site (RG-1.10)', () => {
|
||||
expect(isAddressValid({ ...validDelivery(), siteIris: [] })).toBe(false)
|
||||
})
|
||||
|
||||
it('faux si aucune categorie', () => {
|
||||
expect(isAddressValid({ ...validDelivery(), categoryIris: [] })).toBe(false)
|
||||
})
|
||||
|
||||
it('RG-1.11 : email de facturation obligatoire quand l\'adresse est de facturation', () => {
|
||||
const billing: AddressValidityDraft = { ...validDelivery(), isBilling: true }
|
||||
expect(isAddressValid({ ...billing, billingEmail: null })).toBe(false)
|
||||
expect(isAddressValid({ ...billing, billingEmail: ' ' })).toBe(false)
|
||||
expect(isAddressValid({ ...billing, billingEmail: 'facture@acme.fr' })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isRibComplete (gating « + RIB » + RG-1.13)', () => {
|
||||
it('vrai quand label + BIC + IBAN sont remplis', () => {
|
||||
expect(isRibComplete({ label: 'Compte courant', bic: 'BNPAFRPP', iban: 'FR1420041010050500013M02606' })).toBe(true)
|
||||
})
|
||||
|
||||
it('faux si un champ manque (null ou vide apres trim)', () => {
|
||||
expect(isRibComplete({ label: null, bic: 'BNPAFRPP', iban: 'FR14...' })).toBe(false)
|
||||
expect(isRibComplete({ label: 'Compte', bic: ' ', iban: 'FR14...' })).toBe(false)
|
||||
expect(isRibComplete({ label: 'Compte', bic: 'BNPAFRPP', iban: null })).toBe(false)
|
||||
})
|
||||
|
||||
it('faux pour un bloc totalement vide (amorce)', () => {
|
||||
expect(isRibComplete({ label: null, bic: null, iban: null })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -12,10 +12,8 @@
|
||||
*
|
||||
* Ces helpers ne touchent ni a l'API ni a l'etat reactif.
|
||||
*
|
||||
* NOTE RG-1.04 (Information obligatoire pour la Commerciale) : volontairement NON
|
||||
* miroitee cote front (cf. clientFormRules.ts) — /api/me n'expose pas le code de
|
||||
* role et Bureau partage les permissions de Commerciale. Le back l'applique de
|
||||
* maniere fiable (422) ; on laisse remonter ce 422 en toast.
|
||||
* NOTE : l'onglet Information est facultatif pour tous les roles (RG-1.04
|
||||
* « Information obligatoire pour la Commerciale » retiree cote back).
|
||||
*/
|
||||
|
||||
import {
|
||||
|
||||
@@ -9,12 +9,9 @@
|
||||
* Le back reste la source de verite (les RG sont re-validees serveur) ; ces
|
||||
* regles ne servent qu'au feedback UI immediat (gating de boutons, visibilite).
|
||||
*
|
||||
* NOTE RG-1.04 (Information obligatoire pour la Commerciale) : volontairement
|
||||
* NON miroite cote front pour l'instant. Le payload /api/me ne porte pas le code
|
||||
* de role (roles = IRIs opaques) et Bureau partage les memes permissions que
|
||||
* Commerciale : aucun signal fiable pour distinguer le role cote front. Le back
|
||||
* (ClientProcessor, via BusinessRoleAware) applique la regle de maniere fiable ;
|
||||
* a rebrancher ici des qu'un code de role sera expose dans /api/me.
|
||||
* NOTE : l'onglet Information est facultatif pour tous les roles. L'ancienne
|
||||
* RG-1.04 (« Information obligatoire pour la Commerciale ») a ete retiree cote
|
||||
* back — rien a miroiter ici.
|
||||
*/
|
||||
|
||||
/**
|
||||
@@ -53,6 +50,26 @@ export function buildClientFormTabKeys(
|
||||
return keys
|
||||
}
|
||||
|
||||
/**
|
||||
* Codes de categorie « intermediaire » : un client dont la categorie est
|
||||
* Distributeur ou Courtier n'a ni relation amont (il EST le distributeur /
|
||||
* courtier) ni prestation de triage. Sert a conditionner l'affichage des champs
|
||||
* « Relation » et « Prestation de triage » du formulaire principal.
|
||||
*/
|
||||
export const DISTRIBUTOR_BROKER_CATEGORY_CODES = ['DISTRIBUTEUR', 'COURTIER'] as const
|
||||
|
||||
/**
|
||||
* Vrai des qu'au moins une categorie « ordinaire » (autre que Distributeur /
|
||||
* Courtier) est selectionnee. Les champs « Relation » (depend du distributeur /
|
||||
* courtier) et « Prestation de triage » du formulaire principal sont masques par
|
||||
* defaut et reveles uniquement dans ce cas.
|
||||
*/
|
||||
export function showsRelationAndTriageFields(selectedCategoryCodes: string[]): boolean {
|
||||
return selectedCategoryCodes.some(
|
||||
code => !(DISTRIBUTOR_BROKER_CATEGORY_CODES as readonly string[]).includes(code),
|
||||
)
|
||||
}
|
||||
|
||||
/** Sous-ensemble d'un contact necessaire aux regles de nommage (RG-1.05/1.14). */
|
||||
export interface ContactDraft {
|
||||
firstName: string | null
|
||||
@@ -86,6 +103,68 @@ export function hasAtLeastOneValidContact(contacts: ContactDraft[]): boolean {
|
||||
return contacts.some(isContactNamed)
|
||||
}
|
||||
|
||||
/**
|
||||
* Primitive reutilisable : vrai si TOUTES les valeurs fournies sont vides (null /
|
||||
* undefined / espaces uniquement). Sert a detecter un bloc de collection
|
||||
* totalement vide (amorce non remplie). Un bloc qui porte la moindre donnee
|
||||
* n'est PAS « blank » : il doit etre soumis pour declencher sa 422 inline plutot
|
||||
* que d'etre saute silencieusement.
|
||||
*/
|
||||
export function isBlankRow(values: (string | null | undefined)[]): boolean {
|
||||
return values.every(value => !isFilled(value))
|
||||
}
|
||||
|
||||
/** Champs saisissables d'un bloc contact (pour detecter un bloc totalement vide). */
|
||||
export interface ContactFillableDraft extends ContactDraft {
|
||||
jobTitle: string | null
|
||||
phonePrimary: string | null
|
||||
phoneSecondary: string | null
|
||||
email: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si AUCUN champ saisissable du bloc contact n'est rempli. Distingue un bloc
|
||||
* d'amorce vide (a ignorer au submit) d'un bloc partiellement rempli sans nom
|
||||
* (email / telephone / fonction seul) : ce dernier doit etre soumis pour
|
||||
* declencher la 422 RG-1.05 (« prenom ou nom obligatoire ») affichee inline.
|
||||
*/
|
||||
export function isContactBlank(contact: ContactFillableDraft): boolean {
|
||||
return isBlankRow([
|
||||
contact.firstName,
|
||||
contact.lastName,
|
||||
contact.jobTitle,
|
||||
contact.phonePrimary,
|
||||
contact.phoneSecondary,
|
||||
contact.email,
|
||||
])
|
||||
}
|
||||
|
||||
/** Champs saisissables d'un bloc RIB (pour detecter un bloc totalement vide). */
|
||||
export interface RibFillableDraft {
|
||||
label: string | null
|
||||
bic: string | null
|
||||
iban: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si AUCUN champ du bloc RIB n'est rempli. Un RIB partiellement rempli (ex.
|
||||
* IBAN seul) n'est PAS « blank » : il doit etre soumis pour declencher les 422
|
||||
* NotBlank (label / bic / iban) inline plutot que d'etre saute silencieusement.
|
||||
*/
|
||||
export function isRibBlank(rib: RibFillableDraft): boolean {
|
||||
return isBlankRow([rib.label, rib.bic, rib.iban])
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-1.13 : un RIB est complet quand ses trois champs sont remplis (label, BIC,
|
||||
* IBAN). Predicat par-bloc partage entre le gating du bouton « + RIB » (le
|
||||
* dernier bloc doit etre complet avant d'en ajouter un autre) et la validation
|
||||
* de l'onglet (au moins un RIB complet si reglement LCR).
|
||||
*/
|
||||
export function isRibComplete(rib: RibFillableDraft): boolean {
|
||||
return isFilled(rib.label) && isFilled(rib.bic) && isFilled(rib.iban)
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-1.06/07/08 : une adresse de prospection est exclusive d'une adresse de
|
||||
* livraison/facturation. Prospect n'est selectionnable que si ni Livraison ni
|
||||
@@ -135,6 +214,70 @@ export function isBillingEmailRequired(flags: AddressFlagsDraft): boolean {
|
||||
return flags.isBilling
|
||||
}
|
||||
|
||||
/**
|
||||
* Type d'adresse expose a l'utilisateur (Select unique remplacant les trois
|
||||
* cases a cocher). Sucre purement front : le back continue de recevoir les
|
||||
* drapeaux isProspect / isDelivery / isBilling (aucune RG modifiee). Les seules
|
||||
* combinaisons proposees respectent l'exclusivite Prospect (RG-1.06/07/08).
|
||||
*/
|
||||
export type AddressType = 'prospect' | 'delivery' | 'billing' | 'delivery_billing'
|
||||
|
||||
/**
|
||||
* Mappe le type d'adresse choisi vers les trois drapeaux back.
|
||||
* « Adresse + Facturation » = livraison ET facturation sur la meme adresse.
|
||||
*/
|
||||
export function addressFlagsFromType(type: AddressType): AddressFlagsDraft {
|
||||
switch (type) {
|
||||
case 'prospect':
|
||||
return { isProspect: true, isDelivery: false, isBilling: false }
|
||||
case 'delivery':
|
||||
return { isProspect: false, isDelivery: true, isBilling: false }
|
||||
case 'billing':
|
||||
return { isProspect: false, isDelivery: false, isBilling: true }
|
||||
case 'delivery_billing':
|
||||
return { isProspect: false, isDelivery: true, isBilling: true }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconstruit le type d'adresse a partir des drapeaux (consultation / edition
|
||||
* d'une adresse persistee, ou amorce vierge). Retourne null si aucun drapeau
|
||||
* n'est positionne — le Select reste alors a saisir (et bloque la validation).
|
||||
*/
|
||||
export function addressTypeFromFlags(flags: AddressFlagsDraft): AddressType | null {
|
||||
if (flags.isProspect) return 'prospect'
|
||||
if (flags.isDelivery && flags.isBilling) return 'delivery_billing'
|
||||
if (flags.isDelivery) return 'delivery'
|
||||
if (flags.isBilling) return 'billing'
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Sous-ensemble d'une adresse necessaire a sa validite par-bloc : drapeaux
|
||||
* d'usage (pour le type + l'email de facturation conditionnel), sites et
|
||||
* categories rattaches, email de facturation.
|
||||
*/
|
||||
export interface AddressValidityDraft extends AddressFlagsDraft {
|
||||
categoryIris: string[]
|
||||
siteIris: string[]
|
||||
billingEmail: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Validite par-bloc d'une adresse : type renseigne (RG-1.06/07/08), >= 1 site
|
||||
* (RG-1.10), >= 1 categorie, et email de facturation rempli si l'adresse est de
|
||||
* facturation (RG-1.11). Predicat partage entre le gating du bouton « + Adresse »
|
||||
* (le dernier bloc doit etre valide avant d'en ajouter un autre) et la
|
||||
* validation de l'onglet (toutes les adresses valides).
|
||||
*/
|
||||
export function isAddressValid(address: AddressValidityDraft): boolean {
|
||||
return addressTypeFromFlags(address) !== null
|
||||
&& address.siteIris.length >= 1
|
||||
&& address.categoryIris.length >= 1
|
||||
&& (!isBillingEmailRequired(address) || isFilled(address.billingEmail))
|
||||
}
|
||||
|
||||
/** Code stable du type de reglement « virement » (cf. PaymentType.code, RG-1.12). */
|
||||
const PAYMENT_TYPE_TRANSFER = 'VIREMENT'
|
||||
|
||||
@@ -156,3 +299,62 @@ export function isBankRequiredForPaymentType(code: string | null | undefined): b
|
||||
export function isRibRequiredForPaymentType(code: string | null | undefined): boolean {
|
||||
return code === PAYMENT_TYPE_LCR
|
||||
}
|
||||
|
||||
/** Champs saisissables de l'onglet Information (tous facultatifs). */
|
||||
export interface InformationFieldsDraft {
|
||||
description: string | null
|
||||
competitors: string | null
|
||||
foundedAt: string | null
|
||||
employeesCount: string | null
|
||||
revenueAmount: string | null
|
||||
profitAmount: string | null
|
||||
directorName: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si au moins un champ de l'onglet Information est rempli. L'onglet est
|
||||
* facultatif (aucun champ obligatoire), mais on n'autorise pas une validation
|
||||
* « a vide » a la creation : sans donnee, rien a enregistrer, l'utilisateur
|
||||
* passe directement a l'onglet Contact. (En edition, vider tous les champs reste
|
||||
* une action legitime : ce gate n'y est pas applique.)
|
||||
*/
|
||||
export function hasAtLeastOneInformationField(information: InformationFieldsDraft): boolean {
|
||||
return !isBlankRow([
|
||||
information.description,
|
||||
information.competitors,
|
||||
information.foundedAt,
|
||||
information.employeesCount,
|
||||
information.revenueAmount,
|
||||
information.profitAmount,
|
||||
information.directorName,
|
||||
])
|
||||
}
|
||||
|
||||
/** Sous-ensemble du brouillon comptable portant les six champs obligatoires. */
|
||||
export interface AccountingRequiredDraft {
|
||||
siren: string | null
|
||||
accountNumber: string | null
|
||||
nTva: string | null
|
||||
tvaModeIri: string | null
|
||||
paymentDelayIri: string | null
|
||||
paymentTypeIri: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-1.30 : les six champs scalaires de l'onglet Comptabilite sont obligatoires
|
||||
* pour valider l'onglet (SIREN, N de compte, Mode de TVA, N de TVA, Delai de
|
||||
* reglement, Type de reglement). bank / RIB restent conditionnels (RG-1.12 /
|
||||
* RG-1.13) et sont evalues a part. Miroir front du
|
||||
* ClientAccountingCompletenessValidator : meme gate que les onglets Contact /
|
||||
* Adresse (bouton « Valider » desactive tant que l'onglet n'est pas complet).
|
||||
*/
|
||||
export function hasAllRequiredAccountingFields(accounting: AccountingRequiredDraft): boolean {
|
||||
const filled = (v: string | null): boolean => v !== null && v.trim() !== ''
|
||||
|
||||
return filled(accounting.siren)
|
||||
&& filled(accounting.accountNumber)
|
||||
&& filled(accounting.nTva)
|
||||
&& filled(accounting.tvaModeIri)
|
||||
&& filled(accounting.paymentDelayIri)
|
||||
&& filled(accounting.paymentTypeIri)
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
>
|
||||
<template #cell-action="{ item }">
|
||||
<span
|
||||
class="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium"
|
||||
class="inline-flex items-center rounded-full px-2 py-0.5 font-medium"
|
||||
:class="actionBadgeClass(item.action as string)"
|
||||
>
|
||||
{{ t(`audit.action.${item.action}`) }}
|
||||
@@ -38,15 +38,14 @@
|
||||
</template>
|
||||
<template #cell-entityType="{ item }">
|
||||
<span
|
||||
class="text-xs"
|
||||
:title="item.entityType as string"
|
||||
>{{ formatEntityType(item.entityType as string) }}</span>
|
||||
</template>
|
||||
<template #cell-entityId="{ item }">
|
||||
<span class="font-mono text-xs">{{ item.entityId }}</span>
|
||||
<span>{{ item.entityId }}</span>
|
||||
</template>
|
||||
<template #cell-summary="{ item }">
|
||||
<span class="text-xs text-gray-600">{{ item.summary }}</span>
|
||||
<span class="text-gray-600">{{ item.summary }}</span>
|
||||
</template>
|
||||
</MalioDataTable>
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
@update:per-page="setItemsPerPage"
|
||||
>
|
||||
<template #cell-code="{ item }">
|
||||
<span class="font-mono text-xs">{{ item.code }}</span>
|
||||
<span>{{ item.code }}</span>
|
||||
</template>
|
||||
<template #cell-permissions="{ item }">
|
||||
{{ item.permissions }}
|
||||
@@ -36,7 +36,7 @@
|
||||
<template #cell-system="{ item }">
|
||||
<span
|
||||
v-if="item.isSystem"
|
||||
class="inline-flex items-center rounded-full bg-blue-100 px-2.5 py-0.5 text-xs font-medium text-blue-800"
|
||||
class="inline-flex items-center rounded-full bg-blue-100 px-2.5 py-0.5 font-medium text-blue-800"
|
||||
>
|
||||
{{ t('admin.roles.table.system') }}
|
||||
</span>
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
<template #cell-admin="{ item }">
|
||||
<span
|
||||
v-if="item.admin"
|
||||
class="inline-flex items-center rounded-full bg-purple-100 px-2.5 py-0.5 text-xs font-medium text-purple-800"
|
||||
class="inline-flex items-center rounded-full bg-purple-100 px-2.5 py-0.5 font-medium text-purple-800"
|
||||
>
|
||||
{{ t('admin.users.table.admin') }}
|
||||
</span>
|
||||
|
||||
@@ -62,7 +62,7 @@
|
||||
<MalioInputText
|
||||
v-model="form.color"
|
||||
placeholder="#RRGGBB"
|
||||
input-class="w-full font-mono"
|
||||
input-class="w-full"
|
||||
required
|
||||
/>
|
||||
<!-- pb-4 sur le wrapper : simule le slot message du
|
||||
|
||||
@@ -33,11 +33,11 @@
|
||||
:style="{ backgroundColor: item.color }"
|
||||
class="inline-block size-5 rounded-full border border-neutral-200"
|
||||
/>
|
||||
<span class="font-mono text-xs">{{ item.color }}</span>
|
||||
<span>{{ item.color }}</span>
|
||||
</span>
|
||||
</template>
|
||||
<template #cell-fullAddress="{ item }">
|
||||
<span class="line-clamp-2 text-xs text-neutral-600">
|
||||
<span class="line-clamp-2 text-neutral-600">
|
||||
{{ item.fullAddress }}
|
||||
</span>
|
||||
</template>
|
||||
|
||||
Generated
+14
-14
@@ -7,7 +7,7 @@
|
||||
"name": "starseed-frontend",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@malio/layer-ui": "^1.7.4",
|
||||
"@malio/layer-ui": "^1.7.7",
|
||||
"@nuxt/icon": "^2.2.1",
|
||||
"@nuxtjs/i18n": "^10.2.3",
|
||||
"@nuxtjs/tailwindcss": "^6.14.0",
|
||||
@@ -583,20 +583,20 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@emnapi/core": {
|
||||
"version": "1.10.0",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
|
||||
"integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==",
|
||||
"version": "1.11.0",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.0.tgz",
|
||||
"integrity": "sha512-l9Oo58x0HOP5znGzVhYW9U3e5wVuA4LAZU2AGezTmkhO1CgQRFDhDg4nneHsu/t3WniXg9QrG2nIXL/ZS8ln8Q==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@emnapi/wasi-threads": "1.2.1",
|
||||
"@emnapi/wasi-threads": "1.2.2",
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/runtime": {
|
||||
"version": "1.10.0",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz",
|
||||
"integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==",
|
||||
"version": "1.11.0",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.0.tgz",
|
||||
"integrity": "sha512-55coeOFKHv1ywEcUXJtWU5f+Jr/W5tZDvZig8DLKSwUN1JpROQ4rk/SNOQiFWmaR/VKF4zuFyW1B8JduOSv6Pg==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
@@ -604,9 +604,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/wasi-threads": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",
|
||||
"integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==",
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz",
|
||||
"integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
@@ -1866,9 +1866,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@malio/layer-ui": {
|
||||
"version": "1.7.4",
|
||||
"resolved": "https://gitea.malio.fr/api/packages/MALIO-DEV/npm/%40malio%2Flayer-ui/-/1.7.4/layer-ui-1.7.4.tgz",
|
||||
"integrity": "sha512-JNXwBelj5UQ35Qv5VmnassXKt8niX9jDXjM1vUSukJQiyeUXRxAiZr16QumVgBN9P9YGDyjXVKrwCHltTXvPtQ==",
|
||||
"version": "1.7.7",
|
||||
"resolved": "https://gitea.malio.fr/api/packages/MALIO-DEV/npm/%40malio%2Flayer-ui/-/1.7.7/layer-ui-1.7.7.tgz",
|
||||
"integrity": "sha512-MLHDtOzUxcCwIBGWj4FcUMLQTExtGD29uLvpU+IA6qr7gCj9kZ9fGZDu76LXxuJJdfBwzZmenuZioE7Z1qQUUw==",
|
||||
"dependencies": {
|
||||
"@nuxt/icon": "^2.2.1",
|
||||
"@nuxtjs/tailwindcss": "^6.14.0",
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
"test:e2e:ui": "playwright test --ui"
|
||||
},
|
||||
"dependencies": {
|
||||
"@malio/layer-ui": "^1.7.4",
|
||||
"@malio/layer-ui": "^1.7.7",
|
||||
"@nuxt/icon": "^2.2.1",
|
||||
"@nuxtjs/i18n": "^10.2.3",
|
||||
"@nuxtjs/tailwindcss": "^6.14.0",
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="(diff, field) in updateDiff" :key="field" class="border-t border-gray-200">
|
||||
<td class="px-2 py-1 font-mono">{{ field }}</td>
|
||||
<td class="px-2 py-1">{{ field }}</td>
|
||||
<td class="px-2 py-1 text-red-700">{{ formatValue(diff.old) }}</td>
|
||||
<td class="px-2 py-1 text-green-700">{{ formatValue(diff.new) }}</td>
|
||||
</tr>
|
||||
@@ -31,7 +31,7 @@
|
||||
{ added: [ids], removed: [ids] } → affiche + et - sur
|
||||
la meme ligne pour garder une colonne field unique. -->
|
||||
<tr v-for="(diff, field) in collectionDiff" :key="`col-${field}`" class="border-t border-gray-200">
|
||||
<td class="px-2 py-1 font-mono">{{ field }}</td>
|
||||
<td class="px-2 py-1">{{ field }}</td>
|
||||
<td class="px-2 py-1 text-red-700">
|
||||
<span v-if="diff.removed.length">− {{ diff.removed.join(', ') }}</span>
|
||||
<span v-else class="text-gray-400">∅</span>
|
||||
@@ -47,7 +47,7 @@
|
||||
|
||||
<div v-else class="space-y-1">
|
||||
<div v-for="(value, key) in entry.changes" :key="key" class="flex gap-2">
|
||||
<span class="font-mono text-xs text-gray-600">{{ key }}:</span>
|
||||
<span class="text-xs text-gray-600">{{ key }}:</span>
|
||||
<span class="text-xs">{{ formatValue(value) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
<template>
|
||||
<!-- Entete de page standard : source unique du style des titres.
|
||||
Slot par defaut = texte du titre, slot #actions = boutons a droite. -->
|
||||
<div class="mb-[44px] flex items-center justify-between gap-4">
|
||||
<h1 class="text-[32px] font-semibold text-primary-500">
|
||||
Slot par defaut = texte du titre, slot #actions = boutons a droite.
|
||||
Sticky en haut du <main> scrollable : reste visible au scroll. Fond blanc
|
||||
+ pt-11/pb-[34px] (au lieu de marges) pour que le contenu defilant soit
|
||||
masque sous l'entete (espaces haut ET bas compris) et que l'entete soit
|
||||
collee sous le SiteSelector sans trou. pt-11 = 44px, la marge haute
|
||||
d'origine. z-20 < drawers/modales. -->
|
||||
<div class="sticky top-0 z-20 flex items-center justify-between gap-4 bg-white pt-11 pb-[34px]">
|
||||
<h1 class="text-[30px] font-semibold text-primary-500">
|
||||
<slot/>
|
||||
</h1>
|
||||
<div v-if="$slots.actions" class="shrink-0">
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest'
|
||||
import { readHistoryTab } from '../historyTab'
|
||||
|
||||
const KEYS = ['information', 'contact', 'address', 'accounting']
|
||||
|
||||
describe('readHistoryTab', () => {
|
||||
afterEach(() => {
|
||||
window.history.replaceState(null, '')
|
||||
})
|
||||
|
||||
it('retourne la cle d\'onglet quand elle est presente et valide', () => {
|
||||
window.history.replaceState({ tab: 'address' }, '')
|
||||
expect(readHistoryTab(KEYS)).toBe('address')
|
||||
})
|
||||
|
||||
it('retourne null quand l\'onglet n\'est pas dans les cles valides (ex: role sans Comptabilite)', () => {
|
||||
window.history.replaceState({ tab: 'accounting' }, '')
|
||||
expect(readHistoryTab(['information', 'contact', 'address'])).toBeNull()
|
||||
})
|
||||
|
||||
it('retourne null sans onglet dans l\'etat d\'historique (navigation directe / refresh)', () => {
|
||||
window.history.replaceState(null, '')
|
||||
expect(readHistoryTab(KEYS)).toBeNull()
|
||||
|
||||
window.history.replaceState({ foo: 'bar' }, '')
|
||||
expect(readHistoryTab(KEYS)).toBeNull()
|
||||
})
|
||||
|
||||
it('retourne null quand la valeur n\'est pas une chaine', () => {
|
||||
window.history.replaceState({ tab: 42 }, '')
|
||||
expect(readHistoryTab(KEYS)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Onglet actif transmis d'une page a l'autre via l'etat d'historique
|
||||
* (`history.state`), SANS le mettre dans l'URL. Sert a preserver l'onglet courant
|
||||
* au passage consultation <-> edition d'un client (dans les deux sens).
|
||||
*
|
||||
* On reste donc fidele a la regle « etat d'UI local, pas dans l'URL » : l'onglet
|
||||
* voyage dans l'entree d'historique de la navigation, l'URL ne change pas.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Lit la cle d'onglet posee par la page precedente (`history.state.tab`) si elle
|
||||
* fait partie des onglets valides pour l'utilisateur. Retourne `null` sinon :
|
||||
* navigation directe / deep link, rechargement de page, ou onglet inexistant
|
||||
* pour ce role (ex: Comptabilite sans la permission).
|
||||
*/
|
||||
export function readHistoryTab(validKeys: string[]): string | null {
|
||||
if (typeof window === 'undefined') {
|
||||
return null
|
||||
}
|
||||
const tab = (window.history.state as Record<string, unknown> | null)?.tab
|
||||
return typeof tab === 'string' && validKeys.includes(tab) ? tab : null
|
||||
}
|
||||
@@ -75,6 +75,15 @@ export const personas: Record<PersonaKey, Persona> = {
|
||||
'commercial.clients.accounting.view',
|
||||
'commercial.clients.accounting.manage',
|
||||
'commercial.clients.archive',
|
||||
// Commercial — Repertoire fournisseurs (M2, ERP-90). Meme logique que
|
||||
// les clients : mappe sur le persona "tout", pas de nouveau persona
|
||||
// (regle ABSOLUE n°7). commercial.suppliers.view n'ajoute pas de lien
|
||||
// dans la section Administration, donc expectedAdminLinks reste inchange.
|
||||
'commercial.suppliers.view',
|
||||
'commercial.suppliers.manage',
|
||||
'commercial.suppliers.accounting.view',
|
||||
'commercial.suppliers.accounting.manage',
|
||||
'commercial.suppliers.archive',
|
||||
],
|
||||
expectedAdminLinks: ['users', 'roles', 'sites', 'categories', 'audit-log'],
|
||||
},
|
||||
|
||||
@@ -207,7 +207,8 @@ migration-migrate:
|
||||
# orphelins du mapping ORM. Les index partiels (LOWER + WHERE) ne sont pas
|
||||
# exprimables via les attributs Doctrine ORM (fonctionnel + partiel), donc
|
||||
# ils disparaissent apres schema:update. On les recree par dbal:run-sql :
|
||||
# - `uq_category_name_type_active` (M0 Catalog) : tests RG-1.07.
|
||||
# - `uq_category_name_active` (M0 Catalog) : unicite GLOBALE du nom parmi
|
||||
# les actifs (M:N categorie<->type), tests RG-1.07.
|
||||
# - `uq_category_code` (Catalog ERP-78) : unicite du code categorie parmi
|
||||
# les actifs (slug du nom), pilote RG-1.03/1.29.
|
||||
# - `uq_client_company_name_active` (M1 Commercial) : unicite nom societe
|
||||
@@ -226,9 +227,10 @@ test-db-setup:
|
||||
$(SYMFONY_CONSOLE) --env=test --no-interaction doctrine:fixtures:load
|
||||
$(SYMFONY_CONSOLE) --env=test --no-interaction app:sync-permissions
|
||||
$(SYMFONY_CONSOLE) --env=test --no-interaction app:seed-rbac
|
||||
$(SYMFONY_CONSOLE) --env=test dbal:run-sql "CREATE UNIQUE INDEX IF NOT EXISTS uq_category_name_type_active ON category (LOWER(name), category_type_id) WHERE deleted_at IS NULL"
|
||||
$(SYMFONY_CONSOLE) --env=test dbal:run-sql "CREATE UNIQUE INDEX IF NOT EXISTS uq_category_name_active ON category (LOWER(name)) WHERE deleted_at IS NULL"
|
||||
$(SYMFONY_CONSOLE) --env=test dbal:run-sql "CREATE UNIQUE INDEX IF NOT EXISTS uq_category_code ON category (code) WHERE deleted_at IS NULL"
|
||||
$(SYMFONY_CONSOLE) --env=test dbal:run-sql "CREATE UNIQUE INDEX IF NOT EXISTS uq_client_company_name_active ON client (LOWER(company_name)) WHERE is_archived = FALSE AND deleted_at IS NULL"
|
||||
$(SYMFONY_CONSOLE) --env=test dbal:run-sql "CREATE UNIQUE INDEX IF NOT EXISTS uq_supplier_company_name_active ON supplier (LOWER(company_name)) WHERE is_archived = FALSE AND deleted_at IS NULL"
|
||||
|
||||
fixtures:
|
||||
$(SYMFONY_CONSOLE) --no-interaction doctrine:fixtures:load
|
||||
|
||||
@@ -256,13 +256,13 @@ final class Version20260601000000 extends AbstractMigration
|
||||
$this->comment('client', 'distributor_id', 'FK auto-referente vers un client porteur de la categorie DISTRIBUTEUR — exclusive avec broker_id (RG-1.03, chk_client_distrib_or_broker). FK -> client.id, ON DELETE SET NULL.');
|
||||
$this->comment('client', 'broker_id', 'FK auto-referente vers un client porteur de la categorie COURTIER — exclusive avec distributor_id (RG-1.03). FK -> client.id, ON DELETE SET NULL.');
|
||||
$this->comment('client', 'triage_service', 'Drapeau service triage active pour le client. Faux par defaut.');
|
||||
$this->comment('client', 'description', 'Onglet Information : description libre. Obligatoire pour le role Commerciale (RG-1.04), optionnel sinon.');
|
||||
$this->comment('client', 'competitors', 'Onglet Information : concurrents identifies (texte libre ≤ 255). Obligatoire role Commerciale (RG-1.04).');
|
||||
$this->comment('client', 'founded_at', 'Onglet Information : date de creation de l entreprise. Obligatoire role Commerciale (RG-1.04).');
|
||||
$this->comment('client', 'employees_count', 'Onglet Information : effectif (entier >= 0). Obligatoire role Commerciale (RG-1.04).');
|
||||
$this->comment('client', 'revenue_amount', 'Onglet Information : chiffre d affaires (NUMERIC 15,2). Obligatoire role Commerciale (RG-1.04).');
|
||||
$this->comment('client', 'director_name', 'Onglet Information : nom du dirigeant. Obligatoire role Commerciale (RG-1.04).');
|
||||
$this->comment('client', 'profit_amount', 'Onglet Information : resultat / benefice (NUMERIC 15,2). Obligatoire role Commerciale (RG-1.04).');
|
||||
$this->comment('client', 'description', 'Onglet Information : description libre. Facultatif.');
|
||||
$this->comment('client', 'competitors', 'Onglet Information : concurrents identifies (texte libre ≤ 255). Facultatif.');
|
||||
$this->comment('client', 'founded_at', 'Onglet Information : date de creation de l entreprise. Facultatif.');
|
||||
$this->comment('client', 'employees_count', 'Onglet Information : effectif (entier >= 0). Facultatif.');
|
||||
$this->comment('client', 'revenue_amount', 'Onglet Information : chiffre d affaires (NUMERIC 15,2). Facultatif.');
|
||||
$this->comment('client', 'director_name', 'Onglet Information : nom du dirigeant. Facultatif.');
|
||||
$this->comment('client', 'profit_amount', 'Onglet Information : resultat / benefice (NUMERIC 15,2). Facultatif.');
|
||||
$this->comment('client', 'siren', 'Onglet Comptabilite : SIREN (9 chiffres attendus). NON unique — peut etre partage entre etablissements (RG-1.15 supprimee, Q4).');
|
||||
$this->comment('client', 'account_number', 'Onglet Comptabilite : numero de compte comptable du client.');
|
||||
$this->comment('client', 'tva_mode_id', 'Onglet Comptabilite : mode de TVA applique — FK -> tva_mode.id, ON DELETE RESTRICT.');
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* ERP-84 — Taxonomie FOURNISSEUR (module Catalog, prerequis M2).
|
||||
*
|
||||
* Contexte : ERP-78 (Version20260602100000) a unifie la taxonomie sur un type
|
||||
* unique CLIENT. Le M2 (fournisseurs) a besoin d'une taxonomie distincte : les
|
||||
* categories clients (Agro-alimentaire...) ne sont pas valides pour un
|
||||
* fournisseur (Negociant, Cooperative...). Decision Matthieu (02/06) : types
|
||||
* distincts CLIENT / FOURNISSEUR (PRESTA a venir), chacun avec sa taxonomie.
|
||||
*
|
||||
* Cette migration :
|
||||
* 1. recree le `category_type` FOURNISSEUR (code FOURNISSEUR, label « Fournisseur ») ;
|
||||
* 2. seede quelques `Category` de demonstration rattachees a ce type.
|
||||
*
|
||||
* Aucune colonne creee/modifiee -> pas de `COMMENT ON COLUMN` (regle ABSOLUE n°12).
|
||||
*
|
||||
* Namespace racine `DoctrineMigrations` (regle ABSOLUE n°11) et NON modulaire
|
||||
* Catalog : avec plusieurs migrations_paths, Doctrine Migrations 3.x trie par
|
||||
* FQCN alphabetique -> une migration `App\Module\Catalog\...` passerait avant les
|
||||
* `DoctrineMigrations\...` sur base vide, donc avant la creation de la table
|
||||
* `category_type`. Le namespace racine garantit l'ordre par timestamp.
|
||||
*
|
||||
* Idempotence : `INSERT ... ON CONFLICT (code) DO NOTHING` pour le type,
|
||||
* `INSERT ... SELECT ... WHERE NOT EXISTS` pour chaque categorie (aligne sur le
|
||||
* pattern ERP-78 etape 4). En prod la table `category` est vide (aucune fixture
|
||||
* metier). En dev/test, le purger Doctrine vide `category`/`category_type` avant
|
||||
* les fixtures qui reproduisent le meme etat final (CategoryTypeFixtures /
|
||||
* CategoryFixtures etendus a FOURNISSEUR).
|
||||
*/
|
||||
final class Version20260605120000 extends AbstractMigration
|
||||
{
|
||||
/**
|
||||
* Categories de demonstration du type FOURNISSEUR : nom => code stable. Le
|
||||
* code est la cle metier (slug MAJUSCULE du nom, miroir du
|
||||
* CategoryCodeGenerator) et reste unique parmi les actifs (uq_category_code,
|
||||
* partage avec les codes CLIENT — aucune collision ici).
|
||||
*/
|
||||
private const array SUPPLIER_CATEGORIES = [
|
||||
'Négociant' => 'NEGOCIANT',
|
||||
'Coopérative' => 'COOPERATIVE',
|
||||
'Producteur' => 'PRODUCTEUR',
|
||||
'Grossiste' => 'GROSSISTE',
|
||||
'Importateur' => 'IMPORTATEUR',
|
||||
];
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'ERP-84 : recree le CategoryType FOURNISSEUR + seed des categories fournisseurs (Negociant, Cooperative...).';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
// 1. Type FOURNISSEUR (idempotent via l'index unique uq_category_type_code).
|
||||
$this->addSql(<<<'SQL'
|
||||
INSERT INTO category_type (code, label) VALUES ('FOURNISSEUR', 'Fournisseur')
|
||||
ON CONFLICT (code) DO NOTHING
|
||||
SQL);
|
||||
|
||||
// 2. Categories de demonstration sous FOURNISSEUR (si le code est libre
|
||||
// parmi les actifs). created_at/updated_at NOT NULL -> NOW() ; le blame
|
||||
// reste null (seed hors contexte HTTP, libelle « Systeme » cote front).
|
||||
foreach (self::SUPPLIER_CATEGORIES as $name => $code) {
|
||||
$this->addSql(<<<'SQL'
|
||||
INSERT INTO category (name, code, category_type_id, created_at, updated_at)
|
||||
SELECT :name, :code, ct.id, NOW(), NOW()
|
||||
FROM category_type ct
|
||||
WHERE ct.code = 'FOURNISSEUR'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM category c WHERE c.code = :code AND c.deleted_at IS NULL
|
||||
)
|
||||
SQL, ['name' => $name, 'code' => $code]);
|
||||
}
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
// Best-effort : on retire d'abord les categories seedees (par code), puis
|
||||
// le type s'il n'est plus reference (guard NOT EXISTS sur la FK RESTRICT).
|
||||
$this->addSql(
|
||||
'DELETE FROM category WHERE code IN (:codes) '
|
||||
."AND category_type_id = (SELECT id FROM category_type WHERE code = 'FOURNISSEUR')",
|
||||
['codes' => array_values(self::SUPPLIER_CATEGORIES)],
|
||||
['codes' => \Doctrine\DBAL\ArrayParameterType::STRING],
|
||||
);
|
||||
|
||||
$this->addSql(<<<'SQL'
|
||||
DELETE FROM category_type
|
||||
WHERE code = 'FOURNISSEUR'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM category c WHERE c.category_type_id = category_type.id
|
||||
)
|
||||
SQL);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use App\Shared\Infrastructure\Database\ColumnCommentsCatalog;
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* M2 — Repertoire fournisseurs (ERP-85) : creation de toute la structure BDD
|
||||
* des fournisseurs sous le module Commercial (jumeau du M1 client).
|
||||
*
|
||||
* Tables creees :
|
||||
* - Table principale : supplier (formulaire principal + Information +
|
||||
* Comptabilite + archive + soft-delete + Timestampable/Blamable).
|
||||
* - Sous-collections : supplier_category (M2M), supplier_contact (1:n),
|
||||
* supplier_address (1:n), supplier_rib (1:n).
|
||||
* - Jointures de supplier_address : supplier_address_site,
|
||||
* supplier_address_contact, supplier_address_category.
|
||||
*
|
||||
* Differences vs le M1 `client` (cf. spec M2 § 2.4 / § 3.1) :
|
||||
* - PAS de contact inline sur supplier (first_name / last_name / phone_* /
|
||||
* email retires en V0.2, refonte-contact ERP-106). Les contacts vivent
|
||||
* uniquement dans supplier_contact (onglet Contacts).
|
||||
* - PAS d'auto-reference distributor_id / broker_id (pas de CHECK associe).
|
||||
* - Ajout du champ Information volume_forecast (entier).
|
||||
* - supplier_address remplace les 3 booleens M1 (is_prospect / is_delivery /
|
||||
* is_billing + billing_email) par un seul enum address_type
|
||||
* (PROSPECT | DEPART | RENDU, radio exclusif, CHECK chk_supplier_address_type)
|
||||
* et ajoute bennes (int nullable) + triage_provider (bool).
|
||||
*
|
||||
* Referentiels comptables NON recrees : tva_mode / payment_delay / payment_type
|
||||
* / bank sont ceux du M1 (FK partagees, zero duplication — spec § 2.3).
|
||||
*
|
||||
* CategoryType FOURNISSEUR NON re-seede : il est cree par ERP-84
|
||||
* (Version20260605120000) avec ses categories de demonstration. Le M2M
|
||||
* supplier_category / supplier_address_category s'appuie sur ce type existant.
|
||||
*
|
||||
* Namespace racine `DoctrineMigrations` (regle ABSOLUE Starseed n°11) et NON
|
||||
* `App\Module\Commercial\...` : la migration cree un schema avec FK cross-module
|
||||
* (user, category, site, et les referentiels comptables M1). Avec plusieurs
|
||||
* migrations_paths, Doctrine Migrations 3.x trie par FQCN alphabetique — un
|
||||
* namespace modulaire s'executerait avant la creation de user/category/site sur
|
||||
* base vide -> echec des FK. Le namespace racine garantit l'ordre par timestamp.
|
||||
*
|
||||
* Style DDL aligne sur le M1 (Version20260601000000) : `INT GENERATED BY DEFAULT
|
||||
* AS IDENTITY` (et non SERIAL), `TIMESTAMP(0) WITHOUT TIME ZONE` (et non
|
||||
* TIMESTAMPTZ, car le TimestampableBlamableTrait mappe `datetime_immutable`).
|
||||
* Garantit que `schema:update` restera un no-op quand les entites arriveront
|
||||
* (ticket ERP-86).
|
||||
*
|
||||
* Decision unicite (Matthieu 02/06, alignee Q4 du M1) : unicite metier sur le
|
||||
* NOM DE SOCIETE uniquement (uq_supplier_company_name_active, partiel). Pas
|
||||
* d'index unique sur siren ni email.
|
||||
*
|
||||
* Chaque colonne porte un `COMMENT ON COLUMN` (regle ABSOLUE n°12, garde-fou
|
||||
* ColumnsHaveSqlCommentTest). Les tables n'etant pas encore mappees par l'ORM
|
||||
* (entites a ERP-86), ces commentaires survivent au `schema:update --force` du
|
||||
* setup de test (additif, ne drop pas les tables non mappees).
|
||||
*/
|
||||
final class Version20260605130000 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'ERP-85 (M2) : tables supplier + sous-collections + jointures M2M (referentiels comptables et CategoryType FOURNISSEUR reutilises).';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->createSupplierTable();
|
||||
$this->createSupplierCategory();
|
||||
$this->createSupplierContact();
|
||||
$this->createSupplierAddress();
|
||||
$this->createSupplierAddressJoinTables();
|
||||
$this->createSupplierRib();
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
// Ordre inverse des dependances FK : jointures et sous-collections
|
||||
// d'abord, puis supplier. Les referentiels comptables et le
|
||||
// CategoryType FOURNISSEUR ne sont pas touches (crees ailleurs).
|
||||
$this->addSql('DROP TABLE IF EXISTS supplier_address_category');
|
||||
$this->addSql('DROP TABLE IF EXISTS supplier_address_contact');
|
||||
$this->addSql('DROP TABLE IF EXISTS supplier_address_site');
|
||||
$this->addSql('DROP TABLE IF EXISTS supplier_rib');
|
||||
$this->addSql('DROP TABLE IF EXISTS supplier_address');
|
||||
$this->addSql('DROP TABLE IF EXISTS supplier_contact');
|
||||
$this->addSql('DROP TABLE IF EXISTS supplier_category');
|
||||
$this->addSql('DROP TABLE IF EXISTS supplier');
|
||||
}
|
||||
|
||||
// =================================================================
|
||||
// Table principale `supplier`
|
||||
// =================================================================
|
||||
|
||||
private function createSupplierTable(): void
|
||||
{
|
||||
$this->addSql(<<<'SQL'
|
||||
CREATE TABLE supplier (
|
||||
id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
|
||||
company_name VARCHAR(180) NOT NULL,
|
||||
description TEXT DEFAULT NULL,
|
||||
competitors VARCHAR(255) DEFAULT NULL,
|
||||
founded_at DATE DEFAULT NULL,
|
||||
employees_count INT DEFAULT NULL,
|
||||
revenue_amount NUMERIC(15, 2) DEFAULT NULL,
|
||||
director_name VARCHAR(120) DEFAULT NULL,
|
||||
profit_amount NUMERIC(15, 2) DEFAULT NULL,
|
||||
volume_forecast INT DEFAULT NULL,
|
||||
siren VARCHAR(20) DEFAULT NULL,
|
||||
account_number VARCHAR(40) DEFAULT NULL,
|
||||
tva_mode_id INT DEFAULT NULL,
|
||||
n_tva VARCHAR(40) DEFAULT NULL,
|
||||
payment_delay_id INT DEFAULT NULL,
|
||||
payment_type_id INT DEFAULT NULL,
|
||||
bank_id INT DEFAULT NULL,
|
||||
is_archived BOOLEAN DEFAULT FALSE NOT NULL,
|
||||
archived_at TIMESTAMP(0) WITHOUT TIME ZONE DEFAULT NULL,
|
||||
deleted_at TIMESTAMP(0) WITHOUT TIME ZONE DEFAULT NULL,
|
||||
created_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL,
|
||||
updated_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL,
|
||||
created_by INT DEFAULT NULL,
|
||||
updated_by INT DEFAULT NULL,
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT fk_supplier_tva_mode
|
||||
FOREIGN KEY (tva_mode_id) REFERENCES tva_mode (id) ON DELETE RESTRICT,
|
||||
CONSTRAINT fk_supplier_payment_delay
|
||||
FOREIGN KEY (payment_delay_id) REFERENCES payment_delay (id) ON DELETE RESTRICT,
|
||||
CONSTRAINT fk_supplier_payment_type
|
||||
FOREIGN KEY (payment_type_id) REFERENCES payment_type (id) ON DELETE RESTRICT,
|
||||
CONSTRAINT fk_supplier_bank
|
||||
FOREIGN KEY (bank_id) REFERENCES bank (id) ON DELETE RESTRICT,
|
||||
CONSTRAINT fk_supplier_created_by
|
||||
FOREIGN KEY (created_by) REFERENCES "user" (id) ON DELETE SET NULL,
|
||||
CONSTRAINT fk_supplier_updated_by
|
||||
FOREIGN KEY (updated_by) REFERENCES "user" (id) ON DELETE SET NULL
|
||||
)
|
||||
SQL);
|
||||
|
||||
$this->addSql('CREATE INDEX idx_supplier_is_archived ON supplier (is_archived)');
|
||||
$this->addSql('CREATE INDEX idx_supplier_deleted_at ON supplier (deleted_at)');
|
||||
$this->addSql('CREATE INDEX idx_supplier_created_by ON supplier (created_by)');
|
||||
$this->addSql('CREATE INDEX idx_supplier_updated_by ON supplier (updated_by)');
|
||||
|
||||
// Index sur les FK des referentiels comptables (Postgres n'indexe pas
|
||||
// automatiquement les colonnes portant une FOREIGN KEY).
|
||||
$this->addSql('CREATE INDEX idx_supplier_tva_mode_id ON supplier (tva_mode_id)');
|
||||
$this->addSql('CREATE INDEX idx_supplier_payment_delay_id ON supplier (payment_delay_id)');
|
||||
$this->addSql('CREATE INDEX idx_supplier_payment_type_id ON supplier (payment_type_id)');
|
||||
$this->addSql('CREATE INDEX idx_supplier_bank_id ON supplier (bank_id)');
|
||||
|
||||
// Unicite metier partielle : nom de societe insensible a la casse, parmi
|
||||
// les non-archives ET non soft-deletes uniquement (spec § 2.6). Pas
|
||||
// d'index unique sur siren ni email.
|
||||
$this->addSql(<<<'SQL'
|
||||
CREATE UNIQUE INDEX uq_supplier_company_name_active
|
||||
ON supplier (LOWER(company_name))
|
||||
WHERE is_archived = FALSE AND deleted_at IS NULL
|
||||
SQL);
|
||||
|
||||
$this->comment('supplier', '_table', 'Repertoire fournisseurs (M2 Commercial) — entites archivables (is_archived) et soft-deletables (deleted_at, HP M3).');
|
||||
$this->comment('supplier', 'id', 'Identifiant interne auto-incremente.');
|
||||
$this->comment('supplier', 'company_name', 'Raison sociale du fournisseur (stockee en MAJUSCULES). Unique case-insensitive parmi les actifs non archives/non supprimes (uq_supplier_company_name_active, § 2.6).');
|
||||
$this->comment('supplier', 'description', 'Onglet Information : description libre. Obligatoire pour le role Commerciale (RG-2.03), optionnel sinon.');
|
||||
$this->comment('supplier', 'competitors', 'Onglet Information : concurrents identifies (texte libre ≤ 255). Obligatoire role Commerciale (RG-2.03).');
|
||||
$this->comment('supplier', 'founded_at', 'Onglet Information : date de creation de l entreprise. Obligatoire role Commerciale (RG-2.03).');
|
||||
$this->comment('supplier', 'employees_count', 'Onglet Information : effectif (entier >= 0). Obligatoire role Commerciale (RG-2.03).');
|
||||
$this->comment('supplier', 'revenue_amount', 'Onglet Information : chiffre d affaires (NUMERIC 15,2). Obligatoire role Commerciale (RG-2.03).');
|
||||
$this->comment('supplier', 'director_name', 'Onglet Information : nom du dirigeant. Obligatoire role Commerciale (RG-2.03).');
|
||||
$this->comment('supplier', 'profit_amount', 'Onglet Information : resultat / benefice (NUMERIC 15,2). Obligatoire role Commerciale (RG-2.03).');
|
||||
$this->comment('supplier', 'volume_forecast', 'Onglet Information : volume previsionnel (entier >= 0) — specifique fournisseur. Obligatoire role Commerciale (RG-2.03).');
|
||||
$this->comment('supplier', 'siren', 'Onglet Comptabilite : SIREN (9 chiffres attendus). NON unique — peut etre partage entre etablissements (§ 2.6).');
|
||||
$this->comment('supplier', 'account_number', 'Onglet Comptabilite : numero de compte comptable du fournisseur.');
|
||||
$this->comment('supplier', 'tva_mode_id', 'Onglet Comptabilite : mode de TVA applique — FK -> tva_mode.id (referentiel partage M1), ON DELETE RESTRICT.');
|
||||
$this->comment('supplier', 'n_tva', 'Onglet Comptabilite : numero de TVA intracommunautaire.');
|
||||
$this->comment('supplier', 'payment_delay_id', 'Onglet Comptabilite : delai de reglement — FK -> payment_delay.id (M1), ON DELETE RESTRICT.');
|
||||
$this->comment('supplier', 'payment_type_id', 'Onglet Comptabilite : type de reglement — FK -> payment_type.id (M1), ON DELETE RESTRICT. Pilote RG-2.07 (Banque si VIREMENT) et RG-2.08 (RIB).');
|
||||
$this->comment('supplier', 'bank_id', 'Onglet Comptabilite : banque — FK -> bank.id (M1), ON DELETE RESTRICT. Obligatoire ssi payment_type = VIREMENT (RG-2.07), null sinon.');
|
||||
$this->comment('supplier', 'is_archived', 'Drapeau fonctionnel d archivage — masque par defaut dans la liste. Bascule via permission commercial.suppliers.archive.');
|
||||
$this->comment('supplier', 'archived_at', 'Horodatage de l archivage — pose quand is_archived passe a vrai, remis a null a la restauration.');
|
||||
$this->comment('supplier', 'deleted_at', 'Horodatage du soft-delete technique (HP M3) — non expose par l API au M2. Null = ligne active.');
|
||||
$this->addTimestampableBlamableComments('supplier');
|
||||
}
|
||||
|
||||
// =================================================================
|
||||
// M2M supplier <-> category (type FOURNISSEUR — RG-2.10)
|
||||
// =================================================================
|
||||
|
||||
private function createSupplierCategory(): void
|
||||
{
|
||||
$this->addSql(<<<'SQL'
|
||||
CREATE TABLE supplier_category (
|
||||
supplier_id INT NOT NULL,
|
||||
category_id INT NOT NULL,
|
||||
PRIMARY KEY (supplier_id, category_id),
|
||||
CONSTRAINT fk_supplier_category_supplier
|
||||
FOREIGN KEY (supplier_id) REFERENCES supplier (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_supplier_category_category
|
||||
FOREIGN KEY (category_id) REFERENCES category (id) ON DELETE RESTRICT
|
||||
)
|
||||
SQL);
|
||||
$this->addSql('CREATE INDEX idx_supplier_category_category ON supplier_category (category_id)');
|
||||
|
||||
$this->comment('supplier_category', '_table', 'Jointure M2M supplier <-> category (Catalog) — categories de type FOURNISSEUR du fournisseur, au moins une obligatoire (RG-2.10).');
|
||||
$this->comment('supplier_category', 'supplier_id', 'FK -> supplier.id, ON DELETE CASCADE — fournisseur porteur de la categorie.');
|
||||
$this->comment('supplier_category', 'category_id', 'FK -> category.id, ON DELETE RESTRICT — categorie de type FOURNISSEUR rattachee au fournisseur (RG-2.10).');
|
||||
}
|
||||
|
||||
// =================================================================
|
||||
// Sous-collection : contacts (1:n)
|
||||
// =================================================================
|
||||
|
||||
private function createSupplierContact(): void
|
||||
{
|
||||
$this->addSql(<<<'SQL'
|
||||
CREATE TABLE supplier_contact (
|
||||
id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
|
||||
supplier_id INT NOT NULL,
|
||||
first_name VARCHAR(120) DEFAULT NULL,
|
||||
last_name VARCHAR(120) DEFAULT NULL,
|
||||
job_title VARCHAR(120) DEFAULT NULL,
|
||||
phone_primary VARCHAR(20) DEFAULT NULL,
|
||||
phone_secondary VARCHAR(20) DEFAULT NULL,
|
||||
email VARCHAR(180) DEFAULT NULL,
|
||||
position INT DEFAULT 0 NOT NULL,
|
||||
created_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL,
|
||||
updated_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL,
|
||||
created_by INT DEFAULT NULL,
|
||||
updated_by INT DEFAULT NULL,
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT chk_supplier_contact_name
|
||||
CHECK (first_name IS NOT NULL OR last_name IS NOT NULL),
|
||||
CONSTRAINT fk_supplier_contact_supplier
|
||||
FOREIGN KEY (supplier_id) REFERENCES supplier (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_supplier_contact_created_by
|
||||
FOREIGN KEY (created_by) REFERENCES "user" (id) ON DELETE SET NULL,
|
||||
CONSTRAINT fk_supplier_contact_updated_by
|
||||
FOREIGN KEY (updated_by) REFERENCES "user" (id) ON DELETE SET NULL
|
||||
)
|
||||
SQL);
|
||||
$this->addSql('CREATE INDEX idx_supplier_contact_supplier ON supplier_contact (supplier_id)');
|
||||
|
||||
$this->comment('supplier_contact', '_table', 'Contacts d un fournisseur (1:n) — au moins firstName OU lastName par contact (RG-2.04).');
|
||||
$this->comment('supplier_contact', 'id', 'Identifiant interne auto-incremente.');
|
||||
$this->comment('supplier_contact', 'supplier_id', 'FK -> supplier.id, ON DELETE CASCADE — fournisseur proprietaire du contact.');
|
||||
$this->comment('supplier_contact', 'first_name', 'Prenom du contact (capitalise serveur). first_name OU last_name obligatoire (RG-2.04, chk_supplier_contact_name).');
|
||||
$this->comment('supplier_contact', 'last_name', 'Nom du contact (capitalise serveur). first_name OU last_name obligatoire (RG-2.04, chk_supplier_contact_name).');
|
||||
$this->comment('supplier_contact', 'job_title', 'Fonction / intitule de poste du contact (≤ 120 caracteres).');
|
||||
$this->comment('supplier_contact', 'phone_primary', 'Telephone principal du contact — chiffres uniquement (normalisation serveur).');
|
||||
$this->comment('supplier_contact', 'phone_secondary', 'Telephone secondaire du contact — chiffres uniquement (normalisation serveur).');
|
||||
$this->comment('supplier_contact', 'email', 'Email du contact (lowercase serveur).');
|
||||
$this->comment('supplier_contact', 'position', 'Ordre d affichage du contact dans la liste du fournisseur (croissant).');
|
||||
$this->addTimestampableBlamableComments('supplier_contact');
|
||||
}
|
||||
|
||||
// =================================================================
|
||||
// Sous-collection : adresses (1:n)
|
||||
// =================================================================
|
||||
|
||||
private function createSupplierAddress(): void
|
||||
{
|
||||
$this->addSql(<<<'SQL'
|
||||
CREATE TABLE supplier_address (
|
||||
id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
|
||||
supplier_id INT NOT NULL,
|
||||
address_type VARCHAR(20) NOT NULL,
|
||||
country VARCHAR(80) DEFAULT 'France' NOT NULL,
|
||||
postal_code VARCHAR(20) NOT NULL,
|
||||
city VARCHAR(120) NOT NULL,
|
||||
street VARCHAR(255) NOT NULL,
|
||||
street_complement VARCHAR(255) DEFAULT NULL,
|
||||
bennes INT DEFAULT NULL,
|
||||
triage_provider BOOLEAN DEFAULT FALSE NOT NULL,
|
||||
position INT DEFAULT 0 NOT NULL,
|
||||
created_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL,
|
||||
updated_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL,
|
||||
created_by INT DEFAULT NULL,
|
||||
updated_by INT DEFAULT NULL,
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT chk_supplier_address_type
|
||||
CHECK (address_type IN ('PROSPECT', 'DEPART', 'RENDU')),
|
||||
CONSTRAINT fk_supplier_address_supplier
|
||||
FOREIGN KEY (supplier_id) REFERENCES supplier (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_supplier_address_created_by
|
||||
FOREIGN KEY (created_by) REFERENCES "user" (id) ON DELETE SET NULL,
|
||||
CONSTRAINT fk_supplier_address_updated_by
|
||||
FOREIGN KEY (updated_by) REFERENCES "user" (id) ON DELETE SET NULL
|
||||
)
|
||||
SQL);
|
||||
$this->addSql('CREATE INDEX idx_supplier_address_supplier ON supplier_address (supplier_id)');
|
||||
|
||||
$this->comment('supplier_address', '_table', 'Adresses d un fournisseur (1:n) — type PROSPECT/DEPART/RENDU exclusif (RG-2.09), >= 1 site rattache (RG-2.06).');
|
||||
$this->comment('supplier_address', 'id', 'Identifiant interne auto-incremente.');
|
||||
$this->comment('supplier_address', 'supplier_id', 'FK -> supplier.id, ON DELETE CASCADE — fournisseur proprietaire de l adresse.');
|
||||
$this->comment('supplier_address', 'address_type', 'Type d adresse : PROSPECT | DEPART | RENDU (radio exclusif par construction — RG-2.09, chk_supplier_address_type).');
|
||||
$this->comment('supplier_address', 'country', 'Pays de l adresse — defaut France.');
|
||||
$this->comment('supplier_address', 'postal_code', 'Code postal (4-5 chiffres attendus).');
|
||||
$this->comment('supplier_address', 'city', 'Ville — preremplie depuis le code postal via API BAN cote front.');
|
||||
$this->comment('supplier_address', 'street', 'Numero et voie de l adresse.');
|
||||
$this->comment('supplier_address', 'street_complement', 'Complement d adresse (etage, batiment...) — optionnel.');
|
||||
$this->comment('supplier_address', 'bennes', 'Nombre de bennes sur le site fournisseur (entier nullable) — specifique fournisseur.');
|
||||
$this->comment('supplier_address', 'triage_provider', 'Le fournisseur est prestataire de triage sur cette adresse. Faux par defaut.');
|
||||
$this->comment('supplier_address', 'position', 'Ordre d affichage de l adresse dans la liste du fournisseur (croissant).');
|
||||
$this->addTimestampableBlamableComments('supplier_address');
|
||||
}
|
||||
|
||||
// =================================================================
|
||||
// Jointures de supplier_address (M2M)
|
||||
// =================================================================
|
||||
|
||||
private function createSupplierAddressJoinTables(): void
|
||||
{
|
||||
$this->addSql(<<<'SQL'
|
||||
CREATE TABLE supplier_address_site (
|
||||
supplier_address_id INT NOT NULL,
|
||||
site_id INT NOT NULL,
|
||||
PRIMARY KEY (supplier_address_id, site_id),
|
||||
CONSTRAINT fk_supplier_address_site_address
|
||||
FOREIGN KEY (supplier_address_id) REFERENCES supplier_address (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_supplier_address_site_site
|
||||
FOREIGN KEY (site_id) REFERENCES site (id) ON DELETE RESTRICT
|
||||
)
|
||||
SQL);
|
||||
$this->comment('supplier_address_site', '_table', 'Jointure M2M supplier_address <-> site (Sites) — sites rattaches a l adresse (>= 1 obligatoire, RG-2.06).');
|
||||
$this->comment('supplier_address_site', 'supplier_address_id', 'FK -> supplier_address.id, ON DELETE CASCADE — adresse concernee.');
|
||||
$this->comment('supplier_address_site', 'site_id', 'FK -> site.id, ON DELETE RESTRICT — site rattache a l adresse.');
|
||||
|
||||
$this->addSql(<<<'SQL'
|
||||
CREATE TABLE supplier_address_contact (
|
||||
supplier_address_id INT NOT NULL,
|
||||
supplier_contact_id INT NOT NULL,
|
||||
PRIMARY KEY (supplier_address_id, supplier_contact_id),
|
||||
CONSTRAINT fk_supplier_address_contact_address
|
||||
FOREIGN KEY (supplier_address_id) REFERENCES supplier_address (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_supplier_address_contact_contact
|
||||
FOREIGN KEY (supplier_contact_id) REFERENCES supplier_contact (id) ON DELETE CASCADE
|
||||
)
|
||||
SQL);
|
||||
$this->comment('supplier_address_contact', '_table', 'Jointure M2M supplier_address <-> supplier_contact — contacts associes a une adresse.');
|
||||
$this->comment('supplier_address_contact', 'supplier_address_id', 'FK -> supplier_address.id, ON DELETE CASCADE — adresse concernee.');
|
||||
$this->comment('supplier_address_contact', 'supplier_contact_id', 'FK -> supplier_contact.id, ON DELETE CASCADE — contact associe a l adresse.');
|
||||
|
||||
$this->addSql(<<<'SQL'
|
||||
CREATE TABLE supplier_address_category (
|
||||
supplier_address_id INT NOT NULL,
|
||||
category_id INT NOT NULL,
|
||||
PRIMARY KEY (supplier_address_id, category_id),
|
||||
CONSTRAINT fk_supplier_address_category_address
|
||||
FOREIGN KEY (supplier_address_id) REFERENCES supplier_address (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_supplier_address_category_category
|
||||
FOREIGN KEY (category_id) REFERENCES category (id) ON DELETE RESTRICT
|
||||
)
|
||||
SQL);
|
||||
$this->comment('supplier_address_category', '_table', 'Jointure M2M supplier_address <-> category — categories d adresse de type FOURNISSEUR (RG-2.10).');
|
||||
$this->comment('supplier_address_category', 'supplier_address_id', 'FK -> supplier_address.id, ON DELETE CASCADE — adresse concernee.');
|
||||
$this->comment('supplier_address_category', 'category_id', 'FK -> category.id, ON DELETE RESTRICT — categorie d adresse de type FOURNISSEUR (RG-2.10).');
|
||||
}
|
||||
|
||||
// =================================================================
|
||||
// Sous-collection : RIB (1:n)
|
||||
// =================================================================
|
||||
|
||||
private function createSupplierRib(): void
|
||||
{
|
||||
$this->addSql(<<<'SQL'
|
||||
CREATE TABLE supplier_rib (
|
||||
id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
|
||||
supplier_id INT NOT NULL,
|
||||
label VARCHAR(120) NOT NULL,
|
||||
bic VARCHAR(20) NOT NULL,
|
||||
iban VARCHAR(34) NOT NULL,
|
||||
position INT DEFAULT 0 NOT NULL,
|
||||
created_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL,
|
||||
updated_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL,
|
||||
created_by INT DEFAULT NULL,
|
||||
updated_by INT DEFAULT NULL,
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT fk_supplier_rib_supplier
|
||||
FOREIGN KEY (supplier_id) REFERENCES supplier (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_supplier_rib_created_by
|
||||
FOREIGN KEY (created_by) REFERENCES "user" (id) ON DELETE SET NULL,
|
||||
CONSTRAINT fk_supplier_rib_updated_by
|
||||
FOREIGN KEY (updated_by) REFERENCES "user" (id) ON DELETE SET NULL
|
||||
)
|
||||
SQL);
|
||||
$this->addSql('CREATE INDEX idx_supplier_rib_supplier ON supplier_rib (supplier_id)');
|
||||
|
||||
$this->comment('supplier_rib', '_table', 'Coordonnees bancaires d un fournisseur (1:n) — >= 1 RIB attendu selon le type de reglement (RG-2.08). Tous les champs audites (pas d AuditIgnore).');
|
||||
$this->comment('supplier_rib', 'id', 'Identifiant interne auto-incremente.');
|
||||
$this->comment('supplier_rib', 'supplier_id', 'FK -> supplier.id, ON DELETE CASCADE — fournisseur proprietaire du RIB.');
|
||||
$this->comment('supplier_rib', 'label', 'Libelle du RIB (ex: compte principal).');
|
||||
$this->comment('supplier_rib', 'bic', 'Code BIC/SWIFT de la banque (8 ou 11 caracteres).');
|
||||
$this->comment('supplier_rib', 'iban', 'IBAN du compte (≤ 34 caracteres).');
|
||||
$this->comment('supplier_rib', 'position', 'Ordre d affichage du RIB dans la liste du fournisseur (croissant).');
|
||||
$this->addTimestampableBlamableComments('supplier_rib');
|
||||
}
|
||||
|
||||
// =================================================================
|
||||
// Helpers
|
||||
// =================================================================
|
||||
|
||||
/**
|
||||
* Pose les 4 commentaires standardises Timestampable/Blamable sur une table,
|
||||
* en reutilisant le catalogue partage (source unique, cf. ERP-67).
|
||||
*/
|
||||
private function addTimestampableBlamableComments(string $table): void
|
||||
{
|
||||
foreach (ColumnCommentsCatalog::timestampableBlamableComments() as $column => $description) {
|
||||
$this->comment($table, $column, $description);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Emet un `COMMENT ON TABLE` (colonne speciale `_table`) ou
|
||||
* `COMMENT ON COLUMN` en dollar-quoting Postgres ($_$...$_$) pour eviter
|
||||
* tout echappement d apostrophe.
|
||||
*/
|
||||
private function comment(string $table, string $column, string $description): void
|
||||
{
|
||||
$quotedTable = '"'.str_replace('"', '""', $table).'"';
|
||||
|
||||
if ('_table' === $column) {
|
||||
$this->addSql(sprintf('COMMENT ON TABLE %s IS $_$%s$_$', $quotedTable, $description));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->addSql(sprintf(
|
||||
'COMMENT ON COLUMN %s.%s IS $_$%s$_$',
|
||||
$quotedTable,
|
||||
'"'.str_replace('"', '""', $column).'"',
|
||||
$description,
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* Catalog — Category multi-types : passage de la relation Category -> CategoryType
|
||||
* de ManyToOne a ManyToMany.
|
||||
*
|
||||
* Ordre critique :
|
||||
* 1. Creation de la table de jonction `category_category_type` (FK category ON
|
||||
* DELETE CASCADE, FK category_type ON DELETE RESTRICT — conserve le garde-fou
|
||||
* « on ne supprime pas un type encore reference »).
|
||||
* 2. Backfill : chaque categorie existante recoit une ligne de jonction vers son
|
||||
* ancien `category_type_id` (avant de dropper la colonne).
|
||||
* 3. Drop de l'index unique (LOWER(name), category_type_id), de l'index FK et de
|
||||
* la colonne `category.category_type_id` (Postgres drope la FK dependante).
|
||||
* 4. Nouvel index unique GLOBAL sur le nom : LOWER(name) WHERE deleted_at IS NULL
|
||||
* (l'unicite n'est plus liee au type — RG-1.07 reformulee).
|
||||
*
|
||||
* Sur base fraiche, les categories seedees CLIENT (Distributeur/Courtier/Secteur/
|
||||
* Autre) et FOURNISSEUR (Negociant/Cooperative/...) n'ont aucun nom en collision
|
||||
* -> l'index unique global passe sans conflit.
|
||||
*
|
||||
* Migration placee au namespace racine `DoctrineMigrations` (regle ABSOLUE n°11) :
|
||||
* Doctrine Migrations 3.x trie par FQCN puis version ; le namespace racine garantit
|
||||
* l'ordre par timestamp apres les migrations d'init des tables.
|
||||
*/
|
||||
final class Version20260608120000 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Catalog : Category <-> CategoryType en ManyToMany (jonction category_category_type), unicite du nom globalisee.';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
// 1. Table de jonction.
|
||||
$this->addSql(<<<'SQL'
|
||||
CREATE TABLE category_category_type (
|
||||
category_id INT NOT NULL,
|
||||
category_type_id INT NOT NULL,
|
||||
PRIMARY KEY (category_id, category_type_id),
|
||||
CONSTRAINT fk_category_category_type_category
|
||||
FOREIGN KEY (category_id) REFERENCES category (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_category_category_type_type
|
||||
FOREIGN KEY (category_type_id) REFERENCES category_type (id) ON DELETE RESTRICT
|
||||
)
|
||||
SQL);
|
||||
$this->addSql('CREATE INDEX idx_cat_cat_type_type ON category_category_type (category_type_id)');
|
||||
|
||||
$this->comment('category_category_type', '_table', 'Jointure M2M category <-> category_type (Catalog) — types portes par la categorie, au moins un obligatoire (RG-1.05).');
|
||||
$this->comment('category_category_type', 'category_id', 'FK -> category.id, ON DELETE CASCADE — categorie portant le type.');
|
||||
$this->comment('category_category_type', 'category_type_id', 'FK -> category_type.id, ON DELETE RESTRICT — type rattache (un type ne peut etre supprime tant qu il reste reference).');
|
||||
|
||||
// 2. Backfill depuis l'ancienne colonne ManyToOne (chaque categorie -> 1 type).
|
||||
$this->addSql(<<<'SQL'
|
||||
INSERT INTO category_category_type (category_id, category_type_id)
|
||||
SELECT id, category_type_id FROM category
|
||||
SQL);
|
||||
|
||||
// 3. Suppression de l'ancien modele : index unique par type, index FK, colonne.
|
||||
$this->addSql('DROP INDEX uq_category_name_type_active');
|
||||
$this->addSql('DROP INDEX idx_category_type_id');
|
||||
// DROP COLUMN drope automatiquement la FK fk_category_type qui en depend.
|
||||
$this->addSql('ALTER TABLE category DROP COLUMN category_type_id');
|
||||
|
||||
// 4. Unicite du nom desormais GLOBALE parmi les actifs (RG-1.07 reformulee).
|
||||
$this->addSql(<<<'SQL'
|
||||
CREATE UNIQUE INDEX uq_category_name_active
|
||||
ON category (LOWER(name))
|
||||
WHERE deleted_at IS NULL
|
||||
SQL);
|
||||
|
||||
// Realignement de la doc SQL de `category` (le type n'est plus une colonne).
|
||||
$this->comment('category', '_table', 'Categories — referentiel multi-types via la jonction category_category_type, soft-delete via deleted_at, unicite LOWER(name) GLOBALE parmi les actifs (uq_category_name_active).');
|
||||
$this->comment('category', 'name', 'Libelle de la categorie (≤ 120 caracteres) — unique GLOBALEMENT parmi les actifs (RG-1.07, uq_category_name_active).');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
// Restauration best-effort de l'ancien modele ManyToOne (1 type par categorie).
|
||||
$this->addSql('DROP INDEX IF EXISTS uq_category_name_active');
|
||||
|
||||
$this->addSql('ALTER TABLE category ADD COLUMN category_type_id INT DEFAULT NULL');
|
||||
|
||||
// Reprend le premier type de chaque categorie (l'ordre des types perdus
|
||||
// au-dela du premier est best-effort : le modele cible n'en gardait qu'un).
|
||||
$this->addSql(<<<'SQL'
|
||||
UPDATE category c
|
||||
SET category_type_id = (
|
||||
SELECT cct.category_type_id
|
||||
FROM category_category_type cct
|
||||
WHERE cct.category_id = c.id
|
||||
ORDER BY cct.category_type_id ASC
|
||||
LIMIT 1
|
||||
)
|
||||
SQL);
|
||||
|
||||
// Categories sans aucun type (theorique) : on les rattache a defaut au
|
||||
// premier type existant pour pouvoir reposer le NOT NULL.
|
||||
$this->addSql(<<<'SQL'
|
||||
UPDATE category
|
||||
SET category_type_id = (SELECT id FROM category_type ORDER BY id ASC LIMIT 1)
|
||||
WHERE category_type_id IS NULL
|
||||
SQL);
|
||||
|
||||
$this->addSql('ALTER TABLE category ALTER COLUMN category_type_id SET NOT NULL');
|
||||
$this->addSql(<<<'SQL'
|
||||
ALTER TABLE category
|
||||
ADD CONSTRAINT fk_category_type
|
||||
FOREIGN KEY (category_type_id) REFERENCES category_type (id) ON DELETE RESTRICT
|
||||
SQL);
|
||||
$this->addSql('CREATE INDEX idx_category_type_id ON category (category_type_id)');
|
||||
$this->addSql(<<<'SQL'
|
||||
CREATE UNIQUE INDEX uq_category_name_type_active
|
||||
ON category (LOWER(name), category_type_id)
|
||||
WHERE deleted_at IS NULL
|
||||
SQL);
|
||||
|
||||
$this->addSql('DROP TABLE category_category_type');
|
||||
}
|
||||
|
||||
/**
|
||||
* Emet un `COMMENT ON TABLE` (colonne speciale `_table`) ou `COMMENT ON COLUMN`
|
||||
* en dollar-quoting Postgres ($_$...$_$) pour eviter tout echappement.
|
||||
*/
|
||||
private function comment(string $table, string $column, string $description): void
|
||||
{
|
||||
$quotedTable = '"'.str_replace('"', '""', $table).'"';
|
||||
|
||||
if ('_table' === $column) {
|
||||
$this->addSql(sprintf('COMMENT ON TABLE %s IS $_$%s$_$', $quotedTable, $description));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->addSql(sprintf(
|
||||
'COMMENT ON COLUMN %s.%s IS $_$%s$_$',
|
||||
$quotedTable,
|
||||
'"'.str_replace('"', '""', $column).'"',
|
||||
$description,
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -19,14 +19,18 @@ use App\Shared\Domain\Contract\CategoryInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
|
||||
/**
|
||||
* Categorie : referentiel metier classifiant les futurs tiers (clients,
|
||||
* fournisseurs, prestataires). Porte un `name` libre et un `categoryType`
|
||||
* (FK vers le referentiel statique CategoryType).
|
||||
* fournisseurs, prestataires). Porte un `name` libre et un ou plusieurs
|
||||
* `categoryTypes` (ManyToMany vers le referentiel statique CategoryType,
|
||||
* table de jonction `category_category_type`). Une categorie peut appartenir
|
||||
* a plusieurs types simultanement (>= 1 obligatoire, RG-1.05).
|
||||
*
|
||||
* - Soft delete via `deletedAt` (pas de hard delete) : la liste exclut par
|
||||
* defaut les categories supprimees (cf. CategoryProvider, ticket 0.3).
|
||||
@@ -81,12 +85,11 @@ use Symfony\Component\Validator\Constraints as Assert;
|
||||
#[ORM\Entity(repositoryClass: DoctrineCategoryRepository::class)]
|
||||
#[ORM\Table(name: 'category')]
|
||||
// Index nommes pour matcher la migration (cf. Role/Permission/Site). Les index
|
||||
// uniques partiels `uq_category_name_type_active` (LOWER(name), category_type_id
|
||||
// WHERE deleted_at IS NULL) et `uq_category_code` (code WHERE deleted_at IS NULL)
|
||||
// restent possedes par la seule migration : Doctrine ORM ne sait pas exprimer un
|
||||
// index partiel via attribut.
|
||||
// uniques partiels `uq_category_name_active` (LOWER(name) WHERE deleted_at IS
|
||||
// NULL — unicite GLOBALE du nom parmi les actifs) et `uq_category_code` (code
|
||||
// WHERE deleted_at IS NULL) restent possedes par la seule migration : Doctrine
|
||||
// ORM ne sait pas exprimer un index partiel via attribut.
|
||||
#[ORM\Index(name: 'idx_category_deleted_at', columns: ['deleted_at'])]
|
||||
#[ORM\Index(name: 'idx_category_type_id', columns: ['category_type_id'])]
|
||||
#[ORM\Index(name: 'idx_category_created_by', columns: ['created_by'])]
|
||||
#[ORM\Index(name: 'idx_category_updated_by', columns: ['updated_by'])]
|
||||
#[Auditable]
|
||||
@@ -112,7 +115,7 @@ class Category implements TimestampableInterface, BlamableInterface, CategoryInt
|
||||
// persiste, sans contradiction entre l'ordre Validate / Process.
|
||||
#[ORM\Column(length: 120)]
|
||||
#[Assert\NotBlank(message: 'Le nom est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(min: 2, max: 120, normalizer: 'trim')]
|
||||
#[Assert\Length(min: 2, max: 120, minMessage: 'Le nom doit comporter au moins {{ limit }} caractères.', maxMessage: 'Le nom ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['category:read', 'category:write'])]
|
||||
private ?string $name = null;
|
||||
|
||||
@@ -126,11 +129,21 @@ class Category implements TimestampableInterface, BlamableInterface, CategoryInt
|
||||
#[Groups(['category:read'])]
|
||||
private ?string $code = null;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: CategoryType::class)]
|
||||
#[ORM\JoinColumn(name: 'category_type_id', referencedColumnName: 'id', nullable: false, onDelete: 'RESTRICT')]
|
||||
#[Assert\NotNull(message: 'Type de catégorie obligatoire.')]
|
||||
/**
|
||||
* Types de la categorie (>= 1 obligatoire, RG-1.05). ManyToMany vers le
|
||||
* referentiel statique CategoryType via la jonction `category_category_type`.
|
||||
* Cote inverse (category_type) en ON DELETE RESTRICT : un type ne peut etre
|
||||
* supprime tant qu'il reste reference par une categorie.
|
||||
*
|
||||
* @var Collection<int, CategoryType>
|
||||
*/
|
||||
#[ORM\ManyToMany(targetEntity: CategoryType::class)]
|
||||
#[ORM\JoinTable(name: 'category_category_type')]
|
||||
#[ORM\JoinColumn(name: 'category_id', referencedColumnName: 'id', onDelete: 'CASCADE')]
|
||||
#[ORM\InverseJoinColumn(name: 'category_type_id', referencedColumnName: 'id', onDelete: 'RESTRICT')]
|
||||
#[Assert\Count(min: 1, minMessage: 'Sélectionnez au moins un type de catégorie.')]
|
||||
#[Groups(['category:read', 'category:write'])]
|
||||
private ?CategoryType $categoryType = null;
|
||||
private Collection $categoryTypes;
|
||||
|
||||
/**
|
||||
* Soft delete : null = active, valeur = supprimee logiquement le {date}.
|
||||
@@ -141,6 +154,11 @@ class Category implements TimestampableInterface, BlamableInterface, CategoryInt
|
||||
#[Groups(['category:read'])]
|
||||
private ?DateTimeImmutable $deletedAt = null;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->categoryTypes = new ArrayCollection();
|
||||
}
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
@@ -173,26 +191,42 @@ class Category implements TimestampableInterface, BlamableInterface, CategoryInt
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getCategoryType(): ?CategoryType
|
||||
/**
|
||||
* @return Collection<int, CategoryType>
|
||||
*/
|
||||
public function getCategoryTypes(): Collection
|
||||
{
|
||||
return $this->categoryType;
|
||||
return $this->categoryTypes;
|
||||
}
|
||||
|
||||
public function setCategoryType(?CategoryType $categoryType): static
|
||||
public function addCategoryType(CategoryType $categoryType): static
|
||||
{
|
||||
$this->categoryType = $categoryType;
|
||||
if (!$this->categoryTypes->contains($categoryType)) {
|
||||
$this->categoryTypes->add($categoryType);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function removeCategoryType(CategoryType $categoryType): static
|
||||
{
|
||||
$this->categoryTypes->removeElement($categoryType);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implemente CategoryInterface : code du type rattache (ou null). Permet
|
||||
* aux modules tiers de filtrer/valider par type metier sans dependre de
|
||||
* Catalog.
|
||||
* Implemente CategoryInterface : liste des codes de types rattaches a la
|
||||
* categorie. Permet aux modules tiers de filtrer/valider par type metier
|
||||
* (ex: RG-2.10 « contient FOURNISSEUR ») sans dependre de Catalog.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function getCategoryTypeCode(): ?string
|
||||
public function getCategoryTypeCodes(): array
|
||||
{
|
||||
return $this->categoryType?->getCode();
|
||||
return array_values(array_filter(
|
||||
$this->categoryTypes->map(static fn (CategoryType $t): ?string => $t->getCode())->toArray(),
|
||||
));
|
||||
}
|
||||
|
||||
public function getDeletedAt(): ?DateTimeImmutable
|
||||
|
||||
@@ -23,7 +23,26 @@ interface CategoryRepositoryInterface
|
||||
/**
|
||||
* Construit un QueryBuilder de liste avec filtre soft-delete et tri par defaut.
|
||||
* - $includeDeleted = false : exclut les categories soft-deleted (RG-1.08)
|
||||
* - $typeCode non null : ne garde que les categories PORTANT ce code de type
|
||||
* (filtre `?typeCode=`, ex. FOURNISSEUR / CLIENT). Sert au multi-select
|
||||
* Categorie du fournisseur (M2, RG-2.10).
|
||||
* - $nameSearch non null : recherche partielle case-insensitive sur le nom
|
||||
* (filtre `?name=` de la liste admin).
|
||||
* - $typeIds non vide : ne garde que les categories portant AU MOINS UN des
|
||||
* types (OR, filtre `?typeId[]=` de la liste admin).
|
||||
* - Tri : name ASC (RG-1.10).
|
||||
*
|
||||
* Les categories etant en ManyToMany avec leurs types, la collection
|
||||
* `categoryTypes` est eager-loadee (addSelect) pour eviter un N+1 a la
|
||||
* serialisation, et `distinct` est applique des qu'un filtre type joint la
|
||||
* table de jonction (evite les lignes dupliquees).
|
||||
*
|
||||
* @param list<int> $typeIds
|
||||
*/
|
||||
public function createListQueryBuilder(bool $includeDeleted = false): QueryBuilder;
|
||||
public function createListQueryBuilder(
|
||||
bool $includeDeleted = false,
|
||||
?string $typeCode = null,
|
||||
?string $nameSearch = null,
|
||||
array $typeIds = [],
|
||||
): QueryBuilder;
|
||||
}
|
||||
|
||||
@@ -22,8 +22,8 @@ use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
* via CategoryCodeGenerator ; puis delegation au persist_processor Doctrine
|
||||
* ORM. Le code est FIGE a la creation (jamais recalcule sur PATCH). Toute
|
||||
* UniqueConstraintViolationException remontee par Postgres (collision sur
|
||||
* l'index partiel uq_category_name_type_active) est traduite en HTTP 409 avec
|
||||
* le message attendu par la spec (RG-1.07).
|
||||
* l'index partiel uq_category_name_active — unicite GLOBALE du nom parmi les
|
||||
* actifs) est traduite en HTTP 409 avec le message attendu par la spec (RG-1.07).
|
||||
* - DELETE : soft delete (RG-1.12). On NE delegue PAS au remove_processor ;
|
||||
* on pose deletedAt = now() puis on delegue au persist_processor pour que
|
||||
* le UPDATE Doctrine parte et que le TimestampableBlamableSubscriber mette
|
||||
@@ -78,10 +78,12 @@ final class CategoryProcessor implements ProcessorInterface
|
||||
try {
|
||||
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
|
||||
} catch (UniqueConstraintViolationException $e) {
|
||||
// RG-1.07 : doublon (LOWER(name), category_type_id) parmi les non-soft-deleted.
|
||||
// RG-1.07 : doublon de nom GLOBAL (LOWER(name)) parmi les non-soft-deleted
|
||||
// (uq_category_name_active). L'unicite n'est plus liee au type depuis le
|
||||
// passage en ManyToMany.
|
||||
throw new HttpException(
|
||||
409,
|
||||
sprintf('Une catégorie nommée "%s" existe déjà pour ce type.', $data->getName() ?? ''),
|
||||
sprintf('Une catégorie nommée "%s" existe déjà.', $data->getName() ?? ''),
|
||||
$e,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -40,7 +40,12 @@ final class CategoryProvider implements ProviderInterface
|
||||
$includeDeleted = $this->readIncludeDeleted($context);
|
||||
|
||||
if ($operation instanceof CollectionOperationInterface) {
|
||||
$qb = $this->repository->createListQueryBuilder($includeDeleted);
|
||||
$qb = $this->repository->createListQueryBuilder(
|
||||
$includeDeleted,
|
||||
$this->readTypeCode($context),
|
||||
$this->readNameSearch($context),
|
||||
$this->readTypeIds($context),
|
||||
);
|
||||
|
||||
// Echappatoire ?pagination=false : retourne la collection complete sans Paginator.
|
||||
// Utile pour les drawers Role/Permission/Site/CategoryType qui alimentent un <select>.
|
||||
@@ -97,4 +102,66 @@ final class CategoryProvider implements ProviderInterface
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lit le filtre `?typeCode=` depuis les filtres API Platform. Renvoie le code
|
||||
* normalise (trim) ou null si absent / vide. Ne contraint pas la casse : la
|
||||
* comparaison SQL se fait sur le code exact stocke (ex. FOURNISSEUR, CLIENT).
|
||||
*/
|
||||
private function readTypeCode(array $context): ?string
|
||||
{
|
||||
$raw = $context['filters']['typeCode'] ?? null;
|
||||
|
||||
if (!is_string($raw)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$raw = trim($raw);
|
||||
|
||||
return '' === $raw ? null : $raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lit le filtre `?name=` (recherche partielle sur le nom, liste admin).
|
||||
* Renvoie la valeur trimmee ou null si absente / vide.
|
||||
*/
|
||||
private function readNameSearch(array $context): ?string
|
||||
{
|
||||
$raw = $context['filters']['name'] ?? null;
|
||||
|
||||
if (!is_string($raw)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$raw = trim($raw);
|
||||
|
||||
return '' === $raw ? null : $raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lit le filtre `?typeId[]=` (liste admin) : ids des types coches (OR).
|
||||
* Tolere une valeur scalaire unique (`?typeId=3`) ou un tableau. Ignore
|
||||
* les entrees non numeriques.
|
||||
*
|
||||
* @return list<int>
|
||||
*/
|
||||
private function readTypeIds(array $context): array
|
||||
{
|
||||
$raw = $context['filters']['typeId'] ?? null;
|
||||
|
||||
if (null === $raw) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$values = is_array($raw) ? $raw : [$raw];
|
||||
|
||||
$ids = [];
|
||||
foreach ($values as $value) {
|
||||
if (is_int($value) || (is_string($value) && ctype_digit($value))) {
|
||||
$ids[] = (int) $value;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique($ids));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,14 +14,16 @@ use RuntimeException;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
|
||||
/**
|
||||
* Fixtures dev/test du module Catalog : ~11 categories de demonstration, toutes
|
||||
* rattachees au type unique CLIENT (refonte taxonomie ERP-78). Chaque categorie
|
||||
* porte un `code` stable. Alimente le repertoire clients (ClientFixtures, module
|
||||
* Commercial) avec des donnees realistes couvrant RG-1.03 (codes DISTRIBUTEUR /
|
||||
* COURTIER) et RG-1.29 (codes interdits sur adresse).
|
||||
* Fixtures dev/test du module Catalog : categories de demonstration rattachees
|
||||
* a leur CategoryType. Le type CLIENT porte ~11 categories clients (refonte
|
||||
* taxonomie ERP-78) ; le type FOURNISSEUR porte les categories fournisseurs
|
||||
* (ERP-84 : Negociant, Cooperative...). Chaque categorie porte un `code` stable.
|
||||
* Alimente le repertoire clients (ClientFixtures, module Commercial) avec des
|
||||
* donnees realistes couvrant RG-1.03 (codes DISTRIBUTEUR / COURTIER) et RG-1.29
|
||||
* (codes interdits sur adresse), et le multi-select Categorie fournisseur (M2).
|
||||
*
|
||||
* Depend de CategoryTypeFixtures : le type CLIENT doit etre seede avant de
|
||||
* pouvoir y rattacher des Category.
|
||||
* Depend de CategoryTypeFixtures : les types CLIENT et FOURNISSEUR doivent etre
|
||||
* seedes avant de pouvoir y rattacher des Category.
|
||||
*
|
||||
* Idempotence : lookup par `code` parmi les categories non supprimees (deletedAt
|
||||
* null), coherent avec l'index unique partiel uq_category_code (code WHERE
|
||||
@@ -39,28 +41,36 @@ use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
*/
|
||||
class CategoryFixtures extends Fixture implements DependentFixtureInterface
|
||||
{
|
||||
/** Code du type unique (cf. CategoryTypeFixtures, migration ERP-78). */
|
||||
private const string CLIENT_TYPE_CODE = 'CLIENT';
|
||||
|
||||
/**
|
||||
* Source unique des categories de demonstration : nom => code stable. Les 4
|
||||
* premieres (Distributeur / Courtier / Secteur / Autre) sont les categories
|
||||
* Categories de demonstration par code de type. Les 4 premieres categories
|
||||
* CLIENT (Distributeur / Courtier / Secteur / Autre) sont les categories
|
||||
* « systeme » reportees des anciens types ; leurs codes pilotent les RG.
|
||||
* Les categories FOURNISSEUR (ERP-84) miroir de la migration
|
||||
* Version20260605120000. Chaque valeur : nom => code stable.
|
||||
*
|
||||
* @var array<string, string>
|
||||
* @var array<string, array<string, string>>
|
||||
*/
|
||||
private const CATEGORIES = [
|
||||
'Distributeur' => 'DISTRIBUTEUR',
|
||||
'Courtier' => 'COURTIER',
|
||||
'Secteur' => 'SECTEUR',
|
||||
'Autre' => 'AUTRE',
|
||||
'BTP' => 'BTP',
|
||||
'Industrie' => 'INDUSTRIE',
|
||||
'Agro-alimentaire' => 'AGRO_ALIMENTAIRE',
|
||||
'Transport/Logistique' => 'TRANSPORT_LOGISTIQUE',
|
||||
'Services' => 'SERVICES',
|
||||
'Association' => 'ASSOCIATION',
|
||||
'Indépendant' => 'INDEPENDANT',
|
||||
private const CATEGORIES_BY_TYPE = [
|
||||
'CLIENT' => [
|
||||
'Distributeur' => 'DISTRIBUTEUR',
|
||||
'Courtier' => 'COURTIER',
|
||||
'Secteur' => 'SECTEUR',
|
||||
'Autre' => 'AUTRE',
|
||||
'BTP' => 'BTP',
|
||||
'Industrie' => 'INDUSTRIE',
|
||||
'Agro-alimentaire' => 'AGRO_ALIMENTAIRE',
|
||||
'Transport/Logistique' => 'TRANSPORT_LOGISTIQUE',
|
||||
'Services' => 'SERVICES',
|
||||
'Association' => 'ASSOCIATION',
|
||||
'Indépendant' => 'INDEPENDANT',
|
||||
],
|
||||
'FOURNISSEUR' => [
|
||||
'Négociant' => 'NEGOCIANT',
|
||||
'Coopérative' => 'COOPERATIVE',
|
||||
'Producteur' => 'PRODUCTEUR',
|
||||
'Grossiste' => 'GROSSISTE',
|
||||
'Importateur' => 'IMPORTATEUR',
|
||||
],
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
@@ -84,31 +94,33 @@ class CategoryFixtures extends Fixture implements DependentFixtureInterface
|
||||
return;
|
||||
}
|
||||
|
||||
$clientType = null;
|
||||
// Index des types presents par code, pour rattacher chaque categorie.
|
||||
$typesByCode = [];
|
||||
foreach ($this->categoryTypeRepository->findAllOrderedByLabel() as $type) {
|
||||
if (self::CLIENT_TYPE_CODE === $type->getCode()) {
|
||||
$clientType = $type;
|
||||
$typesByCode[$type->getCode()] = $type;
|
||||
}
|
||||
|
||||
break;
|
||||
foreach (self::CATEGORIES_BY_TYPE as $typeCode => $categories) {
|
||||
$type = $typesByCode[$typeCode] ?? null;
|
||||
|
||||
if (!$type instanceof CategoryType) {
|
||||
// Misconfiguration : CategoryTypeFixtures n'a pas seede ce type.
|
||||
throw new RuntimeException(sprintf(
|
||||
'CategoryTypeFixtures doit avoir seede le type "%s" avant CategoryFixtures.',
|
||||
$typeCode,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (!$clientType instanceof CategoryType) {
|
||||
// Misconfiguration : CategoryTypeFixtures n'a pas tourne avant.
|
||||
throw new RuntimeException(
|
||||
'CategoryTypeFixtures doit avoir seede le type "CLIENT" avant CategoryFixtures.',
|
||||
);
|
||||
}
|
||||
|
||||
foreach (self::CATEGORIES as $name => $code) {
|
||||
$this->ensureCategory($manager, $name, $code, $clientType);
|
||||
foreach ($categories as $name => $code) {
|
||||
$this->ensureCategory($manager, $name, $code, $type);
|
||||
}
|
||||
}
|
||||
|
||||
$manager->flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Cree la categorie (name, code) sous le type CLIENT si son code n'existe pas
|
||||
* Cree la categorie (name, code) sous le type fourni si son code n'existe pas
|
||||
* encore parmi les categories actives, sinon la laisse en place. Lookup
|
||||
* aligne sur l'index unique partiel uq_category_code.
|
||||
*/
|
||||
@@ -126,7 +138,7 @@ class CategoryFixtures extends Fixture implements DependentFixtureInterface
|
||||
$category = new Category();
|
||||
$category->setName($name);
|
||||
$category->setCode($code);
|
||||
$category->setCategoryType($type);
|
||||
$category->addCategoryType($type);
|
||||
$manager->persist($category);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,10 +12,14 @@ use Doctrine\Persistence\ObjectManager;
|
||||
/**
|
||||
* Fixtures du module Catalog : seed du type de categorie (M1).
|
||||
*
|
||||
* Refonte taxonomie ERP-78 : le modele n'a plus qu'UN SEUL `category_type`,
|
||||
* CLIENT (code CLIENT, label « Client »). Distributeur / Courtier / Secteur /
|
||||
* Autre (et les categories metier fines) sont desormais des `Category` codees
|
||||
* rattachees a ce type (cf. CategoryFixtures + migration Version20260602100000).
|
||||
* Refonte taxonomie ERP-78 : le type CLIENT (code CLIENT, label « Client »)
|
||||
* porte les categories clients ; Distributeur / Courtier / Secteur / Autre (et
|
||||
* les categories metier fines) sont des `Category` codees rattachees a ce type
|
||||
* (cf. CategoryFixtures + migration Version20260602100000).
|
||||
*
|
||||
* ERP-84 : ajout du type FOURNISSEUR (code FOURNISSEUR, label « Fournisseur »),
|
||||
* taxonomie distincte des fournisseurs (Negociant, Cooperative...). Mirroir de
|
||||
* la migration Version20260605120000.
|
||||
*
|
||||
* Pourquoi une fixture EN PLUS du seed de la migration : `category_type` est une
|
||||
* entite managee par l ORM, donc le purger Doctrine la vide avant chaque
|
||||
@@ -31,11 +35,13 @@ use Doctrine\Persistence\ObjectManager;
|
||||
class CategoryTypeFixtures extends Fixture
|
||||
{
|
||||
/**
|
||||
* Source unique du type : code technique => libelle FR. Doit rester aligne
|
||||
* sur le seed de la migration Version20260602100000 (type unique CLIENT).
|
||||
* Source unique des types : code technique => libelle FR. Doit rester aligne
|
||||
* sur le seed des migrations Version20260602100000 (CLIENT) et
|
||||
* Version20260605120000 (FOURNISSEUR).
|
||||
*/
|
||||
private const TYPES = [
|
||||
'CLIENT' => 'Client',
|
||||
'CLIENT' => 'Client',
|
||||
'FOURNISSEUR' => 'Fournisseur',
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
|
||||
@@ -48,9 +48,19 @@ class DoctrineCategoryRepository extends ServiceEntityRepository implements Cate
|
||||
return [] !== $qb->getQuery()->getResult();
|
||||
}
|
||||
|
||||
public function createListQueryBuilder(bool $includeDeleted = false): QueryBuilder
|
||||
{
|
||||
public function createListQueryBuilder(
|
||||
bool $includeDeleted = false,
|
||||
?string $typeCode = null,
|
||||
?string $nameSearch = null,
|
||||
array $typeIds = [],
|
||||
): QueryBuilder {
|
||||
// Eager-load de la collection categoryTypes (ManyToMany) : embarquee a la
|
||||
// serialisation -> on la fetch-joine pour eviter un N+1 par categorie. Le
|
||||
// provider enveloppe la requete dans un Paginator(fetchJoinCollection: true),
|
||||
// compatible avec ce fetch-join to-many.
|
||||
$qb = $this->createQueryBuilder('c')
|
||||
->leftJoin('c.categoryTypes', 'cte')
|
||||
->addSelect('cte')
|
||||
->orderBy('c.name', 'ASC')
|
||||
;
|
||||
|
||||
@@ -58,6 +68,45 @@ class DoctrineCategoryRepository extends ServiceEntityRepository implements Cate
|
||||
$qb->andWhere('c.deletedAt IS NULL');
|
||||
}
|
||||
|
||||
// Filtre `?typeCode=` : la categorie doit PORTER ce code de type (RG-2.10,
|
||||
// multi-select fournisseur). Sous-requete EXISTS correlee pour ne PAS
|
||||
// restreindre la collection eager-loadee `cte` (sinon les autres types de
|
||||
// la categorie disparaitraient du JSON) et eviter les lignes dupliquees.
|
||||
if (null !== $typeCode) {
|
||||
$sub = $this->getEntityManager()->createQueryBuilder()
|
||||
->select('1')
|
||||
->from(Category::class, 'c_tc')
|
||||
->join('c_tc.categoryTypes', 'ct_tc')
|
||||
->where('c_tc = c')
|
||||
->andWhere('ct_tc.code = :typeCode')
|
||||
;
|
||||
$qb->andWhere($qb->expr()->exists($sub->getDQL()))
|
||||
->setParameter('typeCode', $typeCode)
|
||||
;
|
||||
}
|
||||
|
||||
// Filtre `?typeId[]=` (liste admin) : la categorie porte AU MOINS UN des
|
||||
// types coches (OR). Meme strategie EXISTS correlee que `typeCode`.
|
||||
if ([] !== $typeIds) {
|
||||
$sub = $this->getEntityManager()->createQueryBuilder()
|
||||
->select('1')
|
||||
->from(Category::class, 'c_ti')
|
||||
->join('c_ti.categoryTypes', 'ct_ti')
|
||||
->where('c_ti = c')
|
||||
->andWhere('ct_ti.id IN (:typeIds)')
|
||||
;
|
||||
$qb->andWhere($qb->expr()->exists($sub->getDQL()))
|
||||
->setParameter('typeIds', $typeIds)
|
||||
;
|
||||
}
|
||||
|
||||
// Filtre `?name=` (liste admin) : recherche partielle case-insensitive.
|
||||
if (null !== $nameSearch && '' !== $nameSearch) {
|
||||
$qb->andWhere('LOWER(c.name) LIKE :nameSearch')
|
||||
->setParameter('nameSearch', '%'.mb_strtolower($nameSearch).'%')
|
||||
;
|
||||
}
|
||||
|
||||
return $qb;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Application\Validator;
|
||||
|
||||
use ApiPlatform\Validator\Exception\ValidationException;
|
||||
use App\Module\Commercial\Domain\Entity\Client;
|
||||
use Symfony\Component\Validator\ConstraintViolation;
|
||||
use Symfony\Component\Validator\ConstraintViolationList;
|
||||
|
||||
/**
|
||||
* Validator metier (spec-front § Onglet Comptabilite) : a la soumission complete
|
||||
* de l'onglet Comptabilite, les six champs scalaires obligatoires doivent etre
|
||||
* renseignes (SIREN, Numero de compte, Mode de TVA, N de TVA, Delai de reglement,
|
||||
* Type de reglement). La banque reste conditionnelle (RG-1.12) et les RIB aussi
|
||||
* (RG-1.13) : ils ne sont pas couverts ici.
|
||||
*
|
||||
* Parti pris : colonnes nullable en base + validateur contextuel, plutot qu'un
|
||||
* Assert\NotBlank sur l'entite (qui casserait le POST de l'onglet principal,
|
||||
* lequel n'envoie aucun champ comptable).
|
||||
*
|
||||
* Invoque par le ClientProcessor uniquement quand le payload porte les six champs
|
||||
* (= une validation d'onglet), jamais sur un PATCH ciblant un seul champ comptable.
|
||||
*
|
||||
* Leve une ValidationException (HTTP 422) listant chaque champ manquant, par
|
||||
* coherence avec les violations Symfony rendues par API Platform (mapping inline
|
||||
* front via useFormErrors, ERP-101).
|
||||
*/
|
||||
final class ClientAccountingCompletenessValidator
|
||||
{
|
||||
public function validate(Client $client): void
|
||||
{
|
||||
// Map champ -> valeur courante des champs obligatoires de l'onglet.
|
||||
$fields = [
|
||||
'siren' => $client->getSiren(),
|
||||
'accountNumber' => $client->getAccountNumber(),
|
||||
'tvaMode' => $client->getTvaMode(),
|
||||
'nTva' => $client->getNTva(),
|
||||
'paymentDelay' => $client->getPaymentDelay(),
|
||||
'paymentType' => $client->getPaymentType(),
|
||||
];
|
||||
|
||||
$violations = new ConstraintViolationList();
|
||||
|
||||
foreach ($fields as $property => $value) {
|
||||
if ($this->isMissing($value)) {
|
||||
$violations->add(new ConstraintViolation(
|
||||
'Ce champ est obligatoire.',
|
||||
null,
|
||||
[],
|
||||
$client,
|
||||
$property,
|
||||
$value,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if (count($violations) > 0) {
|
||||
throw new ValidationException($violations);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Une valeur est manquante si null ou, pour une chaine, vide apres trim. Les
|
||||
* references (TvaMode / PaymentDelay / PaymentType) ne sont manquantes que
|
||||
* lorsqu'elles valent null.
|
||||
*/
|
||||
private function isMissing(mixed $value): bool
|
||||
{
|
||||
if (null === $value) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return is_string($value) && '' === trim($value);
|
||||
}
|
||||
}
|
||||
-74
@@ -1,74 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Application\Validator;
|
||||
|
||||
use ApiPlatform\Validator\Exception\ValidationException;
|
||||
use App\Module\Commercial\Domain\Entity\Client;
|
||||
use Symfony\Component\Validator\ConstraintViolation;
|
||||
use Symfony\Component\Validator\ConstraintViolationList;
|
||||
|
||||
/**
|
||||
* Validator metier RG-1.04 (durcie ERP-74) : 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 ClientProcessor des que l'utilisateur courant porte le role
|
||||
* Commerciale (plus de condition d'intersection avec l'onglet Information).
|
||||
* Pour les autres roles, ces champs restent optionnels — le validator n'est
|
||||
* pas appele.
|
||||
*
|
||||
* Leve une ValidationException (HTTP 422) listant chaque champ manquant, par
|
||||
* coherence avec les violations Symfony rendues par API Platform.
|
||||
*/
|
||||
final class ClientInformationCompletenessValidator
|
||||
{
|
||||
public function validate(Client $client): void
|
||||
{
|
||||
// Map champ -> valeur courante de l'onglet Information.
|
||||
$fields = [
|
||||
'description' => $client->getDescription(),
|
||||
'competitors' => $client->getCompetitors(),
|
||||
'foundedAt' => $client->getFoundedAt(),
|
||||
'employeesCount' => $client->getEmployeesCount(),
|
||||
'revenueAmount' => $client->getRevenueAmount(),
|
||||
'directorName' => $client->getDirectorName(),
|
||||
'profitAmount' => $client->getProfitAmount(),
|
||||
];
|
||||
|
||||
$violations = new ConstraintViolationList();
|
||||
|
||||
foreach ($fields as $property => $value) {
|
||||
if ($this->isMissing($value)) {
|
||||
$violations->add(new ConstraintViolation(
|
||||
sprintf('Ce champ est obligatoire pour le role Commerciale (champ "%s").', $property),
|
||||
null,
|
||||
[],
|
||||
$client,
|
||||
$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") 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);
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
<?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 (completude Information cote fournisseur) :
|
||||
* 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(
|
||||
// Pas de nom de champ technique dans le message : la violation est
|
||||
// deja rattachee au bon champ via son propertyPath (mappe inline
|
||||
// cote front par useFormErrors).
|
||||
'Ce champ est obligatoire pour le rôle Commerciale.',
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,11 @@ final class CommercialModule
|
||||
['code' => 'commercial.clients.accounting.view', 'label' => 'Voir l\'onglet Comptabilité d\'un client'],
|
||||
['code' => 'commercial.clients.accounting.manage', 'label' => 'Modifier l\'onglet Comptabilité d\'un client'],
|
||||
['code' => 'commercial.clients.archive', 'label' => 'Archiver / restaurer un client'],
|
||||
['code' => 'commercial.suppliers.view', 'label' => 'Voir les fournisseurs'],
|
||||
['code' => 'commercial.suppliers.manage', 'label' => 'Créer / modifier les fournisseurs (hors onglet Comptabilité)'],
|
||||
['code' => 'commercial.suppliers.accounting.view', 'label' => 'Voir l\'onglet Comptabilité d\'un fournisseur'],
|
||||
['code' => 'commercial.suppliers.accounting.manage', 'label' => 'Modifier l\'onglet Comptabilité d\'un fournisseur'],
|
||||
['code' => 'commercial.suppliers.archive', 'label' => 'Archiver / restaurer un fournisseur'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,12 +20,13 @@ use Symfony\Component\Serializer\Attribute\Groups;
|
||||
* permission commercial.clients.view ; POST/PATCH/DELETE -> 405. Pas de
|
||||
* Timestampable/Blamable (referentiel statique whiteliste dans
|
||||
* EntitiesAreTimestampableBlamableTest::EXCLUDED). Le groupe
|
||||
* `client:read:accounting` permet l'embarquement dans la reponse Client.
|
||||
* `client:read:accounting` permet l'embarquement dans la reponse Client ;
|
||||
* `supplier:read:accounting` dans la reponse Fournisseur (M2, ERP-92 — § 4.0).
|
||||
*/
|
||||
#[ApiResource(
|
||||
operations: [
|
||||
new GetCollection(
|
||||
security: "is_granted('commercial.clients.view')",
|
||||
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||
normalizationContext: ['groups' => ['bank:read']],
|
||||
// Tri par defaut spec M1 § 4.7 : position ASC puis label ASC.
|
||||
order: ['position' => 'ASC', 'label' => 'ASC'],
|
||||
@@ -33,11 +34,11 @@ use Symfony\Component\Serializer\Attribute\Groups;
|
||||
paginationClientEnabled: true,
|
||||
),
|
||||
new Get(
|
||||
security: "is_granted('commercial.clients.view')",
|
||||
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||
normalizationContext: ['groups' => ['bank:read']],
|
||||
),
|
||||
],
|
||||
security: "is_granted('commercial.clients.view')",
|
||||
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||
)]
|
||||
#[ORM\Entity(repositoryClass: DoctrineBankRepository::class)]
|
||||
#[ORM\Table(name: 'bank')]
|
||||
@@ -47,15 +48,15 @@ class Bank
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column]
|
||||
#[Groups(['bank:read', 'client:read:accounting'])]
|
||||
#[Groups(['bank:read', 'client:read:accounting', 'supplier:read:accounting'])]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(length: 30)]
|
||||
#[Groups(['bank:read', 'client:read:accounting'])]
|
||||
#[Groups(['bank:read', 'client:read:accounting', 'supplier:read:accounting'])]
|
||||
private ?string $code = null;
|
||||
|
||||
#[ORM\Column(length: 120)]
|
||||
#[Groups(['bank:read', 'client:read:accounting'])]
|
||||
#[Groups(['bank:read', 'client:read:accounting', 'supplier:read:accounting'])]
|
||||
private ?string $label = null;
|
||||
|
||||
#[ORM\Column(options: ['default' => 0])]
|
||||
|
||||
@@ -147,7 +147,7 @@ class Client implements TimestampableInterface, BlamableInterface
|
||||
// === Formulaire principal ===
|
||||
#[ORM\Column(length: 180)]
|
||||
#[Assert\NotBlank(message: 'Le nom de l\'entreprise est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(min: 2, max: 180, normalizer: 'trim')]
|
||||
#[Assert\Length(min: 2, max: 180, minMessage: 'Le nom de l\'entreprise doit comporter au moins {{ limit }} caractères.', maxMessage: 'Le nom de l\'entreprise ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client:read', 'client:write:main'])]
|
||||
private ?string $companyName = null;
|
||||
|
||||
@@ -188,6 +188,7 @@ class Client implements TimestampableInterface, BlamableInterface
|
||||
private ?string $description = null;
|
||||
|
||||
#[ORM\Column(length: 255, nullable: true)]
|
||||
#[Assert\Length(max: 255, maxMessage: 'La liste des concurrents ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client:read', 'client:write:information'])]
|
||||
private ?string $competitors = null;
|
||||
|
||||
@@ -196,7 +197,7 @@ class Client implements TimestampableInterface, BlamableInterface
|
||||
private ?DateTimeImmutable $foundedAt = null;
|
||||
|
||||
#[ORM\Column(nullable: true)]
|
||||
#[Assert\PositiveOrZero]
|
||||
#[Assert\PositiveOrZero(message: 'L\'effectif doit être un nombre positif ou nul.')]
|
||||
#[Groups(['client:read', 'client:write:information'])]
|
||||
private ?int $employeesCount = null;
|
||||
|
||||
@@ -205,6 +206,7 @@ class Client implements TimestampableInterface, BlamableInterface
|
||||
private ?string $revenueAmount = null;
|
||||
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le nom du dirigeant ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client:read', 'client:write:information'])]
|
||||
private ?string $directorName = null;
|
||||
|
||||
@@ -217,10 +219,12 @@ class Client implements TimestampableInterface, BlamableInterface
|
||||
// futur Provider si l'user a la permission accounting.view). Ecriture via
|
||||
// `client:write:accounting` (le futur 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')]
|
||||
#[Groups(['client:read:accounting', 'client:write:accounting'])]
|
||||
private ?string $siren = null;
|
||||
|
||||
#[ORM\Column(length: 40, nullable: true)]
|
||||
#[Assert\Length(max: 40, maxMessage: 'Le numéro de compte ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client:read:accounting', 'client:write:accounting'])]
|
||||
private ?string $accountNumber = null;
|
||||
|
||||
@@ -230,6 +234,7 @@ class Client implements TimestampableInterface, BlamableInterface
|
||||
private ?TvaMode $tvaMode = null;
|
||||
|
||||
#[ORM\Column(length: 40, nullable: true)]
|
||||
#[Assert\Length(max: 40, maxMessage: 'Le numéro de TVA ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client:read:accounting', 'client:write:accounting'])]
|
||||
private ?string $nTva = null;
|
||||
|
||||
|
||||
@@ -63,6 +63,11 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
uriVariables: [
|
||||
'clientId' => new Link(fromClass: Client::class, toProperty: 'client'),
|
||||
],
|
||||
// read:false : pas de stade lecture du parent. Le Link toProperty
|
||||
// resoudrait l'enfant (SELECT ClientAddress ... WHERE client = :id) et
|
||||
// casse en NonUniqueResult des >= 2 enfants. Le parent est rattache
|
||||
// manuellement par ClientAddressProcessor::linkParent (404 si absent).
|
||||
read: false,
|
||||
security: "is_granted('commercial.clients.manage')",
|
||||
normalizationContext: ['groups' => ['client_address:read']],
|
||||
denormalizationContext: ['groups' => ['client_address:write']],
|
||||
@@ -125,33 +130,39 @@ class ClientAddress implements TimestampableInterface, BlamableInterface
|
||||
private bool $isBilling = false;
|
||||
|
||||
#[ORM\Column(length: 80, options: ['default' => 'France'])]
|
||||
#[Assert\Length(max: 80, maxMessage: 'Le pays ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client_address:read', 'client_address:write'])]
|
||||
private string $country = 'France';
|
||||
|
||||
// RG-1.09 : code postal a 4 ou 5 chiffres (pas de controle CP/ville serveur).
|
||||
// Le Regex borne deja la longueur (≤ 5) : pas de Length redondant.
|
||||
#[ORM\Column(length: 20)]
|
||||
#[Assert\NotBlank]
|
||||
#[Assert\NotBlank(message: 'Le code postal est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: '/^[0-9]{4,5}$/', message: 'Le code postal doit comporter 4 ou 5 chiffres.')]
|
||||
#[Groups(['client_address:read', 'client_address:write'])]
|
||||
private ?string $postalCode = null;
|
||||
|
||||
#[ORM\Column(length: 120)]
|
||||
#[Assert\NotBlank]
|
||||
#[Assert\NotBlank(message: 'La ville est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(max: 120, maxMessage: 'La ville ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client_address:read', 'client_address:write'])]
|
||||
private ?string $city = null;
|
||||
|
||||
#[ORM\Column(length: 255)]
|
||||
#[Assert\NotBlank]
|
||||
#[Assert\NotBlank(message: 'La rue est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(max: 255, maxMessage: 'La rue ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client_address:read', 'client_address:write'])]
|
||||
private ?string $street = null;
|
||||
|
||||
#[ORM\Column(length: 255, nullable: true)]
|
||||
#[Assert\Length(max: 255, maxMessage: 'Le complément d\'adresse ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client_address:read', 'client_address:write'])]
|
||||
private ?string $streetComplement = null;
|
||||
|
||||
// RG-1.11 : obligatoire ssi isBilling (validateBillingEmailPresence + CHECK BDD).
|
||||
#[ORM\Column(length: 180, nullable: true)]
|
||||
#[Assert\Email]
|
||||
#[Assert\Email(message: 'L\'email de facturation n\'est pas valide.')]
|
||||
#[Assert\Length(max: 180, maxMessage: 'L\'email de facturation ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client_address:read', 'client_address:write'])]
|
||||
private ?string $billingEmail = null;
|
||||
|
||||
|
||||
@@ -50,6 +50,11 @@ use Symfony\Component\Validator\Constraints as Assert;
|
||||
uriVariables: [
|
||||
'clientId' => new Link(fromClass: Client::class, toProperty: 'client'),
|
||||
],
|
||||
// read:false : pas de stade lecture du parent. Le Link toProperty
|
||||
// resoudrait l'enfant (SELECT ClientContact ... WHERE client = :id) et
|
||||
// casse en NonUniqueResult des >= 2 enfants. Le parent est rattache
|
||||
// manuellement par ClientContactProcessor::linkParent (404 si absent).
|
||||
read: false,
|
||||
security: "is_granted('commercial.clients.manage')",
|
||||
normalizationContext: ['groups' => ['client_contact:read']],
|
||||
denormalizationContext: ['groups' => ['client_contact:write']],
|
||||
@@ -88,30 +93,36 @@ class ClientContact implements TimestampableInterface, BlamableInterface
|
||||
// RG-1.05 : firstName OU lastName obligatoire (CHECK BDD + Processor). Les
|
||||
// deux restent nullable au niveau ORM.
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, normalizer: 'trim')]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le prénom ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client_contact:read', 'client_contact:write'])]
|
||||
private ?string $firstName = null;
|
||||
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, normalizer: 'trim')]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le nom ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client_contact:read', 'client_contact:write'])]
|
||||
private ?string $lastName = null;
|
||||
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, normalizer: 'trim')]
|
||||
#[Assert\Length(max: 120, maxMessage: 'La fonction ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client_contact:read', 'client_contact:write'])]
|
||||
private ?string $jobTitle = null;
|
||||
|
||||
// RG : pas de validation de format telephone (saisie libre), mais une
|
||||
// Assert\Length calee sur la colonne VARCHAR(20) evite l'erreur Postgres
|
||||
// (500 non rattachee au champ) au profit d'une 422 propre (ERP-107).
|
||||
#[ORM\Column(length: 20, nullable: true)]
|
||||
#[Assert\Length(max: 20, maxMessage: 'Le téléphone ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client_contact:read', 'client_contact:write'])]
|
||||
private ?string $phonePrimary = null;
|
||||
|
||||
#[ORM\Column(length: 20, nullable: true)]
|
||||
#[Assert\Length(max: 20, maxMessage: 'Le téléphone secondaire ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client_contact:read', 'client_contact:write'])]
|
||||
private ?string $phoneSecondary = null;
|
||||
|
||||
#[ORM\Column(length: 180, nullable: true)]
|
||||
#[Assert\Email]
|
||||
#[Assert\Email(message: 'L\'adresse email n\'est pas valide.')]
|
||||
#[Assert\Length(max: 180, maxMessage: 'L\'email ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client_contact:read', 'client_contact:write'])]
|
||||
private ?string $email = null;
|
||||
|
||||
|
||||
@@ -54,6 +54,11 @@ use Symfony\Component\Validator\Constraints as Assert;
|
||||
uriVariables: [
|
||||
'clientId' => new Link(fromClass: Client::class, toProperty: 'client'),
|
||||
],
|
||||
// read:false : pas de stade lecture du parent. Le Link toProperty
|
||||
// resoudrait l'enfant (SELECT ClientRib ... WHERE client = :id) et
|
||||
// casse en NonUniqueResult des >= 2 enfants. Le parent est rattache
|
||||
// manuellement par ClientRibProcessor::linkParent (404 si absent).
|
||||
read: false,
|
||||
security: "is_granted('commercial.clients.accounting.manage')",
|
||||
normalizationContext: ['groups' => ['client_rib:read']],
|
||||
denormalizationContext: ['groups' => ['client_rib:write']],
|
||||
@@ -97,20 +102,22 @@ class ClientRib implements TimestampableInterface, BlamableInterface
|
||||
private ?Client $client = null;
|
||||
|
||||
#[ORM\Column(length: 120)]
|
||||
#[Assert\NotBlank]
|
||||
#[Assert\Length(max: 120, normalizer: 'trim')]
|
||||
#[Assert\NotBlank(message: 'Le libellé du RIB est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le libellé ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['client_rib:read', 'client:read:accounting', 'client_rib:write'])]
|
||||
private ?string $label = null;
|
||||
|
||||
// Bic/Iban bornent deja le format (et donc la longueur) : pas de Length
|
||||
// redondant calee sur la colonne (whitelist du garde-fou ERP-107).
|
||||
#[ORM\Column(length: 20)]
|
||||
#[Assert\NotBlank]
|
||||
#[Assert\Bic]
|
||||
#[Assert\NotBlank(message: 'Le BIC est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Bic(message: 'Le BIC n\'est pas valide.')]
|
||||
#[Groups(['client_rib:read', 'client:read:accounting', 'client_rib:write'])]
|
||||
private ?string $bic = null;
|
||||
|
||||
#[ORM\Column(length: 34)]
|
||||
#[Assert\NotBlank]
|
||||
#[Assert\Iban]
|
||||
#[Assert\NotBlank(message: 'L\'IBAN est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Iban(message: 'L\'IBAN n\'est pas valide.')]
|
||||
#[Groups(['client_rib:read', 'client:read:accounting', 'client_rib:write'])]
|
||||
private ?string $iban = null;
|
||||
|
||||
|
||||
@@ -20,12 +20,13 @@ use Symfony\Component\Serializer\Attribute\Groups;
|
||||
* permission commercial.clients.view ; POST/PATCH/DELETE -> 405. Pas de
|
||||
* Timestampable/Blamable (referentiel statique whiteliste dans
|
||||
* EntitiesAreTimestampableBlamableTest::EXCLUDED). Le groupe
|
||||
* `client:read:accounting` permet l'embarquement dans la reponse Client.
|
||||
* `client:read:accounting` permet l'embarquement dans la reponse Client ;
|
||||
* `supplier:read:accounting` dans la reponse Fournisseur (M2, ERP-92 — § 4.0).
|
||||
*/
|
||||
#[ApiResource(
|
||||
operations: [
|
||||
new GetCollection(
|
||||
security: "is_granted('commercial.clients.view')",
|
||||
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||
normalizationContext: ['groups' => ['payment_delay:read']],
|
||||
// Tri par defaut spec M1 § 4.7 : position ASC puis label ASC.
|
||||
order: ['position' => 'ASC', 'label' => 'ASC'],
|
||||
@@ -33,11 +34,11 @@ use Symfony\Component\Serializer\Attribute\Groups;
|
||||
paginationClientEnabled: true,
|
||||
),
|
||||
new Get(
|
||||
security: "is_granted('commercial.clients.view')",
|
||||
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||
normalizationContext: ['groups' => ['payment_delay:read']],
|
||||
),
|
||||
],
|
||||
security: "is_granted('commercial.clients.view')",
|
||||
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||
)]
|
||||
#[ORM\Entity(repositoryClass: DoctrinePaymentDelayRepository::class)]
|
||||
#[ORM\Table(name: 'payment_delay')]
|
||||
@@ -47,15 +48,15 @@ class PaymentDelay
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column]
|
||||
#[Groups(['payment_delay:read', 'client:read:accounting'])]
|
||||
#[Groups(['payment_delay:read', 'client:read:accounting', 'supplier:read:accounting'])]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(length: 30)]
|
||||
#[Groups(['payment_delay:read', 'client:read:accounting'])]
|
||||
#[Groups(['payment_delay:read', 'client:read:accounting', 'supplier:read:accounting'])]
|
||||
private ?string $code = null;
|
||||
|
||||
#[ORM\Column(length: 120)]
|
||||
#[Groups(['payment_delay:read', 'client:read:accounting'])]
|
||||
#[Groups(['payment_delay:read', 'client:read:accounting', 'supplier:read:accounting'])]
|
||||
private ?string $label = null;
|
||||
|
||||
#[ORM\Column(options: ['default' => 0])]
|
||||
|
||||
@@ -23,12 +23,13 @@ use Symfony\Component\Serializer\Attribute\Groups;
|
||||
* permission commercial.clients.view ; POST/PATCH/DELETE -> 405. Pas de
|
||||
* Timestampable/Blamable (referentiel statique whiteliste dans
|
||||
* EntitiesAreTimestampableBlamableTest::EXCLUDED). Le groupe
|
||||
* `client:read:accounting` permet l'embarquement dans la reponse Client.
|
||||
* `client:read:accounting` permet l'embarquement dans la reponse Client ;
|
||||
* `supplier:read:accounting` dans la reponse Fournisseur (M2, ERP-92 — § 4.0).
|
||||
*/
|
||||
#[ApiResource(
|
||||
operations: [
|
||||
new GetCollection(
|
||||
security: "is_granted('commercial.clients.view')",
|
||||
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||
normalizationContext: ['groups' => ['payment_type:read']],
|
||||
// Tri par defaut spec M1 § 4.7 : position ASC puis label ASC.
|
||||
order: ['position' => 'ASC', 'label' => 'ASC'],
|
||||
@@ -36,11 +37,11 @@ use Symfony\Component\Serializer\Attribute\Groups;
|
||||
paginationClientEnabled: true,
|
||||
),
|
||||
new Get(
|
||||
security: "is_granted('commercial.clients.view')",
|
||||
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||
normalizationContext: ['groups' => ['payment_type:read']],
|
||||
),
|
||||
],
|
||||
security: "is_granted('commercial.clients.view')",
|
||||
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||
)]
|
||||
#[ORM\Entity(repositoryClass: DoctrinePaymentTypeRepository::class)]
|
||||
#[ORM\Table(name: 'payment_type')]
|
||||
@@ -50,15 +51,15 @@ class PaymentType
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column]
|
||||
#[Groups(['payment_type:read', 'client:read:accounting'])]
|
||||
#[Groups(['payment_type:read', 'client:read:accounting', 'supplier:read:accounting'])]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(length: 30)]
|
||||
#[Groups(['payment_type:read', 'client:read:accounting'])]
|
||||
#[Groups(['payment_type:read', 'client:read:accounting', 'supplier:read:accounting'])]
|
||||
private ?string $code = null;
|
||||
|
||||
#[ORM\Column(length: 120)]
|
||||
#[Groups(['payment_type:read', 'client:read:accounting'])]
|
||||
#[Groups(['payment_type:read', 'client:read:accounting', 'supplier:read:accounting'])]
|
||||
private ?string $label = null;
|
||||
|
||||
#[ORM\Column(options: ['default' => 0])]
|
||||
|
||||
@@ -0,0 +1,728 @@
|
||||
<?php
|
||||
|
||||
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;
|
||||
use App\Shared\Domain\Contract\CategoryInterface;
|
||||
use App\Shared\Domain\Contract\SiteInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
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,
|
||||
* jumelle du Client (M1). Porte le formulaire principal, l'onglet Information,
|
||||
* l'onglet Comptabilite, le mecanisme d'archivage (is_archived / archived_at) et
|
||||
* le soft-delete technique prepare mais non expose au M2 (deleted_at, HP M3).
|
||||
*
|
||||
* Decisions structurantes (cf. spec M2 § 2 / § 3.3) :
|
||||
* - Contact inline RETIRE (V0.2, refonte-contact ERP-106) : firstName / lastName
|
||||
* / phonePrimary / phoneSecondary / email ne sont plus portes par le
|
||||
* fournisseur — ils vivent uniquement dans SupplierContact (onglet Contacts).
|
||||
* La garantie « au moins un contact nomme » est portee par RG-2.04 + RG-2.13.
|
||||
* - PAS d'auto-reference distributor / broker (contrairement au Client).
|
||||
* - Ajout du champ Information volumeForecast (volume previsionnel, entier),
|
||||
* specifique fournisseur.
|
||||
* - Audit complet (#[Auditable]) sur tous les champs (M2M categories audite
|
||||
* automatiquement). Timestampable / Blamable via le trait Shared.
|
||||
* - PAS de #[ORM\UniqueConstraint] : l'unicite du nom de societe (RG-2.11) est
|
||||
* portee par l'index partiel fonctionnel uq_supplier_company_name_active
|
||||
* (LOWER(company_name) WHERE is_archived = FALSE AND deleted_at IS NULL),
|
||||
* inexprimable en attribut ORM, donc possede par la seule migration. SIREN et
|
||||
* email NE SONT PAS uniques (§ 2.6).
|
||||
* - categories : M2M vers Category (module Catalog) via le contrat
|
||||
* 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] (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
|
||||
// partiel uq_supplier_company_name_active reste possede par la migration :
|
||||
// Doctrine ORM ne sait pas exprimer un index fonctionnel (LOWER) + partiel
|
||||
// (WHERE) via attribut. Pas de #[ORM\UniqueConstraint] (§ 2.6).
|
||||
#[ORM\Index(name: 'idx_supplier_is_archived', columns: ['is_archived'])]
|
||||
#[ORM\Index(name: 'idx_supplier_deleted_at', columns: ['deleted_at'])]
|
||||
#[ORM\Index(name: 'idx_supplier_created_by', columns: ['created_by'])]
|
||||
#[ORM\Index(name: 'idx_supplier_updated_by', columns: ['updated_by'])]
|
||||
#[Auditable]
|
||||
class Supplier implements TimestampableInterface, BlamableInterface
|
||||
{
|
||||
use TimestampableBlamableTrait;
|
||||
|
||||
/**
|
||||
* RG-2.10 : seules les categories PORTANT ce type sont autorisees sur le
|
||||
* fournisseur (entite principale). Miroir de SupplierAddress (ERP-88).
|
||||
* S'appuie sur CategoryInterface::getCategoryTypeCodes() (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]
|
||||
#[Groups(['supplier:read'])]
|
||||
private ?int $id = null;
|
||||
|
||||
// === Formulaire principal ===
|
||||
#[ORM\Column(length: 180)]
|
||||
#[Assert\NotBlank(message: 'Le nom du fournisseur est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(min: 2, max: 180, minMessage: 'Le nom du fournisseur doit comporter au moins {{ limit }} caractères.', maxMessage: 'Le nom du fournisseur ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['supplier:read', 'supplier:write:main'])]
|
||||
private ?string $companyName = null;
|
||||
|
||||
// RG : au moins une categorie (Count min 1), de type FOURNISSEUR (RG-2.10,
|
||||
// verifiee au Processor/Validator a ERP-89). M2M vers Category via le contrat
|
||||
// CategoryInterface (resolve_target_entities -> Category). Embarquee en LISTE
|
||||
// ET DETAIL (coherence M1/ERP-62) ; maillon (c) : le contexte inclut
|
||||
// 'category:read' pour exposer id/code/name.
|
||||
/** @var Collection<int, CategoryInterface> */
|
||||
#[ORM\ManyToMany(targetEntity: CategoryInterface::class)]
|
||||
#[ORM\JoinTable(name: 'supplier_category')]
|
||||
#[ORM\JoinColumn(name: 'supplier_id', referencedColumnName: 'id', onDelete: 'CASCADE')]
|
||||
#[ORM\InverseJoinColumn(name: 'category_id', referencedColumnName: 'id', onDelete: 'RESTRICT')]
|
||||
#[Assert\Count(min: 1, minMessage: 'Au moins une catégorie est obligatoire.')]
|
||||
#[Groups(['supplier:read', 'supplier:write:main'])]
|
||||
private Collection $categories;
|
||||
|
||||
// === Onglet Information ===
|
||||
#[ORM\Column(type: 'text', nullable: true)]
|
||||
#[Groups(['supplier:read', 'supplier:write:information'])]
|
||||
private ?string $description = null;
|
||||
|
||||
#[ORM\Column(length: 255, nullable: true)]
|
||||
#[Assert\Length(max: 255, maxMessage: 'La liste des concurrents ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['supplier:read', 'supplier:write:information'])]
|
||||
private ?string $competitors = null;
|
||||
|
||||
#[ORM\Column(type: 'date_immutable', nullable: true)]
|
||||
#[Groups(['supplier:read', 'supplier:write:information'])]
|
||||
private ?DateTimeImmutable $foundedAt = null;
|
||||
|
||||
#[ORM\Column(nullable: true)]
|
||||
#[Assert\PositiveOrZero(message: 'L\'effectif doit être un nombre positif ou nul.')]
|
||||
#[Groups(['supplier:read', 'supplier:write:information'])]
|
||||
private ?int $employeesCount = null;
|
||||
|
||||
#[ORM\Column(type: 'decimal', precision: 15, scale: 2, nullable: true)]
|
||||
#[Groups(['supplier:read', 'supplier:write:information'])]
|
||||
private ?string $revenueAmount = null;
|
||||
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le nom du dirigeant ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['supplier:read', 'supplier:write:information'])]
|
||||
private ?string $directorName = null;
|
||||
|
||||
#[ORM\Column(type: 'decimal', precision: 15, scale: 2, nullable: true)]
|
||||
#[Groups(['supplier:read', 'supplier:write:information'])]
|
||||
private ?string $profitAmount = null;
|
||||
|
||||
// NEW vs Client : Volume previsionnel (entier).
|
||||
#[ORM\Column(nullable: true)]
|
||||
#[Assert\PositiveOrZero(message: 'Le volume prévisionnel doit être un nombre positif ou nul.')]
|
||||
#[Groups(['supplier:read', 'supplier:write:information'])]
|
||||
private ?int $volumeForecast = null;
|
||||
|
||||
// === Onglet Comptabilite ===
|
||||
// Lecture conditionnee via le groupe `supplier:read:accounting` (ajoute au
|
||||
// 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')]
|
||||
#[Groups(['supplier:read:accounting', 'supplier:write:accounting'])]
|
||||
private ?string $siren = null;
|
||||
|
||||
#[ORM\Column(length: 40, nullable: true)]
|
||||
#[Assert\Length(max: 40, maxMessage: 'Le numéro de compte ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['supplier:read:accounting', 'supplier:write:accounting'])]
|
||||
private ?string $accountNumber = null;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: TvaMode::class)]
|
||||
#[ORM\JoinColumn(name: 'tva_mode_id', referencedColumnName: 'id', nullable: true, onDelete: 'RESTRICT')]
|
||||
#[Groups(['supplier:read:accounting', 'supplier:write:accounting'])]
|
||||
private ?TvaMode $tvaMode = null;
|
||||
|
||||
#[ORM\Column(length: 40, nullable: true)]
|
||||
#[Assert\Length(max: 40, maxMessage: 'Le numéro de TVA ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['supplier:read:accounting', 'supplier:write:accounting'])]
|
||||
private ?string $nTva = null;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: PaymentDelay::class)]
|
||||
#[ORM\JoinColumn(name: 'payment_delay_id', referencedColumnName: 'id', nullable: true, onDelete: 'RESTRICT')]
|
||||
#[Groups(['supplier:read:accounting', 'supplier:write:accounting'])]
|
||||
private ?PaymentDelay $paymentDelay = null;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: PaymentType::class)]
|
||||
#[ORM\JoinColumn(name: 'payment_type_id', referencedColumnName: 'id', nullable: true, onDelete: 'RESTRICT')]
|
||||
#[Groups(['supplier:read:accounting', 'supplier:write:accounting'])]
|
||||
private ?PaymentType $paymentType = null;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: Bank::class)]
|
||||
#[ORM\JoinColumn(name: 'bank_id', referencedColumnName: 'id', nullable: true, onDelete: 'RESTRICT')]
|
||||
#[Groups(['supplier:read:accounting', 'supplier:write:accounting'])]
|
||||
private ?Bank $bank = null;
|
||||
|
||||
// === Sous-collections — EMBARQUEES dans le DETAIL (RETEX M1 §2) ===
|
||||
// Maillon (a) : le read-group est porte par le GETTER (getContacts / getAddresses
|
||||
// / getRibs) — sans #[Groups], jamais serialisees. Edition via sous-ressources
|
||||
// POST/PATCH/DELETE (ERP-88).
|
||||
/** @var Collection<int, SupplierContact> */
|
||||
#[ORM\OneToMany(mappedBy: 'supplier', targetEntity: SupplierContact::class, cascade: ['persist', 'remove'], orphanRemoval: true)]
|
||||
private Collection $contacts;
|
||||
|
||||
/** @var Collection<int, SupplierAddress> */
|
||||
#[ORM\OneToMany(mappedBy: 'supplier', targetEntity: SupplierAddress::class, cascade: ['persist', 'remove'], orphanRemoval: true)]
|
||||
private Collection $addresses;
|
||||
|
||||
/** @var Collection<int, SupplierRib> */
|
||||
#[ORM\OneToMany(mappedBy: 'supplier', targetEntity: SupplierRib::class, cascade: ['persist', 'remove'], orphanRemoval: true)]
|
||||
private Collection $ribs;
|
||||
|
||||
// === Archive / Soft delete ===
|
||||
// Groupe d'ECRITURE uniquement sur la propriete (denormalisation PATCH archive).
|
||||
// Le groupe de LECTURE est declare sur le getter isArchived() avec
|
||||
// SerializedName('isArchived') : sans cela, Symfony strip le prefixe "is" et
|
||||
// exposerait la cle JSON "archived" — en pratique la cle est totalement
|
||||
// DROPPEE (piege n°3 du M1). Pattern corrige : Groups + SerializedName sur le getter.
|
||||
#[ORM\Column(name: 'is_archived', options: ['default' => false])]
|
||||
#[Groups(['supplier:write:archive'])]
|
||||
private bool $isArchived = false;
|
||||
|
||||
#[ORM\Column(type: 'datetime_immutable', nullable: true)]
|
||||
#[Groups(['supplier:read'])]
|
||||
private ?DateTimeImmutable $archivedAt = null;
|
||||
|
||||
// Soft delete technique (HP M3) : non expose en lecture/ecriture au M2.
|
||||
#[ORM\Column(type: 'datetime_immutable', nullable: true)]
|
||||
private ?DateTimeImmutable $deletedAt = null;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->categories = new ArrayCollection();
|
||||
$this->contacts = new ArrayCollection();
|
||||
$this->addresses = new ArrayCollection();
|
||||
$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::getCategoryTypeCodes() (multi-type — la categorie est
|
||||
* acceptee des qu'elle PORTE le type FOURNISSEUR ; 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
|
||||
&& !in_array(self::REQUIRED_CATEGORY_TYPE_CODE, $category->getCategoryTypeCodes(), true)) {
|
||||
$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;
|
||||
}
|
||||
|
||||
public function getCompanyName(): ?string
|
||||
{
|
||||
return $this->companyName;
|
||||
}
|
||||
|
||||
public function setCompanyName(string $companyName): static
|
||||
{
|
||||
$this->companyName = $companyName;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/** @return Collection<int, CategoryInterface> */
|
||||
public function getCategories(): Collection
|
||||
{
|
||||
return $this->categories;
|
||||
}
|
||||
|
||||
public function addCategory(CategoryInterface $category): static
|
||||
{
|
||||
if (!$this->categories->contains($category)) {
|
||||
$this->categories->add($category);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function removeCategory(CategoryInterface $category): static
|
||||
{
|
||||
$this->categories->removeElement($category);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getDescription(): ?string
|
||||
{
|
||||
return $this->description;
|
||||
}
|
||||
|
||||
public function setDescription(?string $description): static
|
||||
{
|
||||
$this->description = $description;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getCompetitors(): ?string
|
||||
{
|
||||
return $this->competitors;
|
||||
}
|
||||
|
||||
public function setCompetitors(?string $competitors): static
|
||||
{
|
||||
$this->competitors = $competitors;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getFoundedAt(): ?DateTimeImmutable
|
||||
{
|
||||
return $this->foundedAt;
|
||||
}
|
||||
|
||||
public function setFoundedAt(?DateTimeImmutable $foundedAt): static
|
||||
{
|
||||
$this->foundedAt = $foundedAt;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getEmployeesCount(): ?int
|
||||
{
|
||||
return $this->employeesCount;
|
||||
}
|
||||
|
||||
public function setEmployeesCount(?int $employeesCount): static
|
||||
{
|
||||
$this->employeesCount = $employeesCount;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getRevenueAmount(): ?string
|
||||
{
|
||||
return $this->revenueAmount;
|
||||
}
|
||||
|
||||
public function setRevenueAmount(?string $revenueAmount): static
|
||||
{
|
||||
$this->revenueAmount = $revenueAmount;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getDirectorName(): ?string
|
||||
{
|
||||
return $this->directorName;
|
||||
}
|
||||
|
||||
public function setDirectorName(?string $directorName): static
|
||||
{
|
||||
$this->directorName = $directorName;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getProfitAmount(): ?string
|
||||
{
|
||||
return $this->profitAmount;
|
||||
}
|
||||
|
||||
public function setProfitAmount(?string $profitAmount): static
|
||||
{
|
||||
$this->profitAmount = $profitAmount;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getVolumeForecast(): ?int
|
||||
{
|
||||
return $this->volumeForecast;
|
||||
}
|
||||
|
||||
public function setVolumeForecast(?int $volumeForecast): static
|
||||
{
|
||||
$this->volumeForecast = $volumeForecast;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getSiren(): ?string
|
||||
{
|
||||
return $this->siren;
|
||||
}
|
||||
|
||||
public function setSiren(?string $siren): static
|
||||
{
|
||||
$this->siren = $siren;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getAccountNumber(): ?string
|
||||
{
|
||||
return $this->accountNumber;
|
||||
}
|
||||
|
||||
public function setAccountNumber(?string $accountNumber): static
|
||||
{
|
||||
$this->accountNumber = $accountNumber;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getTvaMode(): ?TvaMode
|
||||
{
|
||||
return $this->tvaMode;
|
||||
}
|
||||
|
||||
public function setTvaMode(?TvaMode $tvaMode): static
|
||||
{
|
||||
$this->tvaMode = $tvaMode;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getNTva(): ?string
|
||||
{
|
||||
return $this->nTva;
|
||||
}
|
||||
|
||||
public function setNTva(?string $nTva): static
|
||||
{
|
||||
$this->nTva = $nTva;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPaymentDelay(): ?PaymentDelay
|
||||
{
|
||||
return $this->paymentDelay;
|
||||
}
|
||||
|
||||
public function setPaymentDelay(?PaymentDelay $paymentDelay): static
|
||||
{
|
||||
$this->paymentDelay = $paymentDelay;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPaymentType(): ?PaymentType
|
||||
{
|
||||
return $this->paymentType;
|
||||
}
|
||||
|
||||
public function setPaymentType(?PaymentType $paymentType): static
|
||||
{
|
||||
$this->paymentType = $paymentType;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getBank(): ?Bank
|
||||
{
|
||||
return $this->bank;
|
||||
}
|
||||
|
||||
public function setBank(?Bank $bank): static
|
||||
{
|
||||
$this->bank = $bank;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/** @return Collection<int, SupplierContact> */
|
||||
#[Groups(['supplier:item:read'])]
|
||||
public function getContacts(): Collection
|
||||
{
|
||||
return $this->contacts;
|
||||
}
|
||||
|
||||
public function addContact(SupplierContact $contact): static
|
||||
{
|
||||
if (!$this->contacts->contains($contact)) {
|
||||
$this->contacts->add($contact);
|
||||
$contact->setSupplier($this);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function removeContact(SupplierContact $contact): static
|
||||
{
|
||||
if ($this->contacts->removeElement($contact) && $contact->getSupplier() === $this) {
|
||||
$contact->setSupplier(null);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/** @return Collection<int, SupplierAddress> */
|
||||
#[Groups(['supplier:item:read'])]
|
||||
public function getAddresses(): Collection
|
||||
{
|
||||
return $this->addresses;
|
||||
}
|
||||
|
||||
public function addAddress(SupplierAddress $address): static
|
||||
{
|
||||
if (!$this->addresses->contains($address)) {
|
||||
$this->addresses->add($address);
|
||||
$address->setSupplier($this);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function removeAddress(SupplierAddress $address): static
|
||||
{
|
||||
if ($this->addresses->removeElement($address) && $address->getSupplier() === $this) {
|
||||
$address->setSupplier(null);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sites distincts rattaches a au moins une adresse du fournisseur (RG-2.06).
|
||||
* Le fournisseur ne porte pas de sites en propre : ils vivent sur les
|
||||
* adresses. Agrege en lecture seule pour la colonne « Site(s) » du Repertoire
|
||||
* (badges colores) — expose en LISTE via le groupe supplier:read (les adresses
|
||||
* completes restent reservees au detail, supplier:item:read). Site n'a pas de
|
||||
* champ `code` : libelle = `name`, prefixe = `postalCode` (§ 2.4 / § 4.0.ter).
|
||||
*
|
||||
* Fetch-join obligatoire (addresses.sites) cote repository pour eviter le N+1
|
||||
* a la serialisation de la liste (cf. DoctrineSupplierRepository, § 2.12).
|
||||
*
|
||||
* @return list<SiteInterface>
|
||||
*/
|
||||
#[Groups(['supplier:read'])]
|
||||
public function getSites(): array
|
||||
{
|
||||
$sites = [];
|
||||
foreach ($this->addresses as $address) {
|
||||
foreach ($address->getSites() as $site) {
|
||||
// Deduplication par identite d'objet : un meme site peut etre
|
||||
// rattache a plusieurs adresses du fournisseur.
|
||||
$sites[spl_object_id($site)] = $site;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($sites);
|
||||
}
|
||||
|
||||
// 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 (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> */
|
||||
#[Groups(['supplier:read:accounting'])]
|
||||
public function getRibs(): Collection
|
||||
{
|
||||
return $this->ribs;
|
||||
}
|
||||
|
||||
public function addRib(SupplierRib $rib): static
|
||||
{
|
||||
if (!$this->ribs->contains($rib)) {
|
||||
$this->ribs->add($rib);
|
||||
$rib->setSupplier($this);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function removeRib(SupplierRib $rib): static
|
||||
{
|
||||
if ($this->ribs->removeElement($rib) && $rib->getSupplier() === $this) {
|
||||
$rib->setSupplier(null);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
// Groupe de lecture + nom serialise explicite : sans SerializedName, Symfony
|
||||
// exposerait la cle "archived" (strip du prefixe "is" sur les getters) et
|
||||
// droppait silencieusement la cle du JSON (piege n°3 du M1).
|
||||
#[Groups(['supplier:read'])]
|
||||
#[SerializedName('isArchived')]
|
||||
public function isArchived(): bool
|
||||
{
|
||||
return $this->isArchived;
|
||||
}
|
||||
|
||||
public function setIsArchived(bool $isArchived): static
|
||||
{
|
||||
$this->isArchived = $isArchived;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getArchivedAt(): ?DateTimeImmutable
|
||||
{
|
||||
return $this->archivedAt;
|
||||
}
|
||||
|
||||
public function setArchivedAt(?DateTimeImmutable $archivedAt): static
|
||||
{
|
||||
$this->archivedAt = $archivedAt;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getDeletedAt(): ?DateTimeImmutable
|
||||
{
|
||||
return $this->deletedAt;
|
||||
}
|
||||
|
||||
public function setDeletedAt(?DateTimeImmutable $deletedAt): static
|
||||
{
|
||||
$this->deletedAt = $deletedAt;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
<?php
|
||||
|
||||
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;
|
||||
use App\Shared\Domain\Contract\CategoryInterface;
|
||||
use App\Shared\Domain\Contract\SiteInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
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
|
||||
* exclusif PROSPECT | DEPART | RENDU (radio cote front — RG-2.09), qui remplace
|
||||
* les 3 booleens prospect/livraison/facturation du Client (M1) ; pas d'email de
|
||||
* facturation au M2. Ajoute deux champs specifiques fournisseur : `bennes`
|
||||
* (entier nullable) et `triageProvider` (prestataire de triage, booleen).
|
||||
*
|
||||
* Relations M2M :
|
||||
* - sites : SiteInterface (module Sites) via resolve_target_entities — au moins
|
||||
* 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, Assert\Callback validateCategoryType).
|
||||
*
|
||||
* Embarquee sous `supplier.addresses` au detail (groupe supplier:item:read,
|
||||
* 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'])]
|
||||
#[Auditable]
|
||||
class SupplierAddress implements TimestampableInterface, BlamableInterface
|
||||
{
|
||||
use TimestampableBlamableTrait;
|
||||
|
||||
/**
|
||||
* Valeurs autorisees de address_type (RG-2.09). Miroir applicatif du CHECK BDD
|
||||
* chk_supplier_address_type : alimente l'Assert\Choice (422 propre rattachee
|
||||
* au champ avant la base) et reste la source des options cote front.
|
||||
*/
|
||||
public const array ADDRESS_TYPES = ['PROSPECT', 'DEPART', 'RENDU'];
|
||||
|
||||
/**
|
||||
* RG-2.10 : seules les categories PORTANT ce type sont autorisees sur une
|
||||
* adresse fournisseur. S'appuie sur CategoryInterface::getCategoryTypeCodes()
|
||||
* (pas d'import du module Catalog — regle ABSOLUE n°1).
|
||||
*/
|
||||
private const string REQUIRED_CATEGORY_TYPE_CODE = 'FOURNISSEUR';
|
||||
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column]
|
||||
#[Groups(['supplier:item:read'])]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: Supplier::class, inversedBy: 'addresses')]
|
||||
#[ORM\JoinColumn(name: 'supplier_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
|
||||
private ?Supplier $supplier = null;
|
||||
|
||||
// RG-2.09 : enum exclusif. La valeur est bornee par Assert\Choice (longueur de
|
||||
// fait <= 8), d'ou la whitelist du miroir Assert\Length == ORM length (ERP-107,
|
||||
// EntityConstraintsHaveFrenchMessageTest::EXCLUDED_LENGTH_MIRROR).
|
||||
#[ORM\Column(length: 20)]
|
||||
#[Assert\NotBlank(message: 'Le type d\'adresse est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Choice(choices: self::ADDRESS_TYPES, message: 'Le type d\'adresse doit être Prospect, Départ ou Rendu.')]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:addresses'])]
|
||||
private ?string $addressType = null;
|
||||
|
||||
#[ORM\Column(length: 80, options: ['default' => 'France'])]
|
||||
#[Assert\Length(max: 80, maxMessage: 'Le pays ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:addresses'])]
|
||||
private string $country = 'France';
|
||||
|
||||
// RG-2.05 : code postal a 4 ou 5 chiffres (pas de controle CP/ville serveur).
|
||||
// Le Regex borne deja la longueur (<= 5) : pas de Length redondant (whitelist).
|
||||
#[ORM\Column(length: 20)]
|
||||
#[Assert\NotBlank(message: 'Le code postal est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: '/^[0-9]{4,5}$/', message: 'Le code postal doit comporter 4 ou 5 chiffres.')]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:addresses'])]
|
||||
private ?string $postalCode = null;
|
||||
|
||||
#[ORM\Column(length: 120)]
|
||||
#[Assert\NotBlank(message: 'La ville est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(max: 120, maxMessage: 'La ville ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:addresses'])]
|
||||
private ?string $city = null;
|
||||
|
||||
#[ORM\Column(length: 255)]
|
||||
#[Assert\NotBlank(message: 'La rue est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(max: 255, maxMessage: 'La rue ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:addresses'])]
|
||||
private ?string $street = null;
|
||||
|
||||
#[ORM\Column(length: 255, nullable: true)]
|
||||
#[Assert\Length(max: 255, maxMessage: 'Le complément d\'adresse ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:addresses'])]
|
||||
private ?string $streetComplement = null;
|
||||
|
||||
// Specifique fournisseur : nombre de bennes sur le site.
|
||||
#[ORM\Column(nullable: true)]
|
||||
#[Assert\PositiveOrZero(message: 'Le nombre de bennes doit être un nombre positif ou nul.')]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:addresses'])]
|
||||
private ?int $bennes = null;
|
||||
|
||||
// Specifique fournisseur : prestataire de triage sur cette adresse. Groupe
|
||||
// d'ECRITURE uniquement sur la propriete ; le groupe de LECTURE est porte par
|
||||
// le getter isTriageProvider() avec SerializedName('triageProvider') — sinon
|
||||
// Symfony strip le prefixe "is" et droppe la cle (piege n°3 du M1).
|
||||
#[ORM\Column(name: 'triage_provider', options: ['default' => false])]
|
||||
#[Groups(['supplier:write:addresses'])]
|
||||
private bool $triageProvider = false;
|
||||
|
||||
// Ordre d'affichage de l'adresse (gere serveur, non expose au M2).
|
||||
#[ORM\Column(options: ['default' => 0])]
|
||||
private int $position = 0;
|
||||
|
||||
// RG-2.06 : au moins un site rattache a chaque adresse.
|
||||
/** @var Collection<int, SiteInterface> */
|
||||
#[ORM\ManyToMany(targetEntity: SiteInterface::class)]
|
||||
#[ORM\JoinTable(name: 'supplier_address_site')]
|
||||
#[ORM\JoinColumn(name: 'supplier_address_id', referencedColumnName: 'id', onDelete: 'CASCADE')]
|
||||
#[ORM\InverseJoinColumn(name: 'site_id', referencedColumnName: 'id', onDelete: 'RESTRICT')]
|
||||
#[Assert\Count(min: 1, minMessage: 'Au moins un site est obligatoire.')]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:addresses'])]
|
||||
private Collection $sites;
|
||||
|
||||
/** @var Collection<int, SupplierContact> */
|
||||
#[ORM\ManyToMany(targetEntity: SupplierContact::class)]
|
||||
#[ORM\JoinTable(name: 'supplier_address_contact')]
|
||||
#[ORM\JoinColumn(name: 'supplier_address_id', referencedColumnName: 'id', onDelete: 'CASCADE')]
|
||||
#[ORM\InverseJoinColumn(name: 'supplier_contact_id', referencedColumnName: 'id', onDelete: 'CASCADE')]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:addresses'])]
|
||||
private Collection $contacts;
|
||||
|
||||
// RG-2.10 : categories d'adresse de type FOURNISSEUR (controle au Processor).
|
||||
/** @var Collection<int, CategoryInterface> */
|
||||
#[ORM\ManyToMany(targetEntity: CategoryInterface::class)]
|
||||
#[ORM\JoinTable(name: 'supplier_address_category')]
|
||||
#[ORM\JoinColumn(name: 'supplier_address_id', referencedColumnName: 'id', onDelete: 'CASCADE')]
|
||||
#[ORM\InverseJoinColumn(name: 'category_id', referencedColumnName: 'id', onDelete: 'RESTRICT')]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:addresses'])]
|
||||
private Collection $categories;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->sites = new ArrayCollection();
|
||||
$this->contacts = new ArrayCollection();
|
||||
$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::getCategoryTypeCodes() (multi-type — la categorie est
|
||||
* acceptee des qu'elle PORTE le type FOURNISSEUR ; 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
|
||||
&& !in_array(self::REQUIRED_CATEGORY_TYPE_CODE, $category->getCategoryTypeCodes(), true)) {
|
||||
$context->buildViolation('Type de catégorie non autorisé (FOURNISSEUR attendu).')
|
||||
->atPath('categories')
|
||||
->addViolation()
|
||||
;
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getSupplier(): ?Supplier
|
||||
{
|
||||
return $this->supplier;
|
||||
}
|
||||
|
||||
public function setSupplier(?Supplier $supplier): static
|
||||
{
|
||||
$this->supplier = $supplier;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getAddressType(): ?string
|
||||
{
|
||||
return $this->addressType;
|
||||
}
|
||||
|
||||
public function setAddressType(?string $addressType): static
|
||||
{
|
||||
$this->addressType = $addressType;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getCountry(): string
|
||||
{
|
||||
return $this->country;
|
||||
}
|
||||
|
||||
public function setCountry(string $country): static
|
||||
{
|
||||
$this->country = $country;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPostalCode(): ?string
|
||||
{
|
||||
return $this->postalCode;
|
||||
}
|
||||
|
||||
public function setPostalCode(?string $postalCode): static
|
||||
{
|
||||
$this->postalCode = $postalCode;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getCity(): ?string
|
||||
{
|
||||
return $this->city;
|
||||
}
|
||||
|
||||
public function setCity(?string $city): static
|
||||
{
|
||||
$this->city = $city;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getStreet(): ?string
|
||||
{
|
||||
return $this->street;
|
||||
}
|
||||
|
||||
public function setStreet(?string $street): static
|
||||
{
|
||||
$this->street = $street;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getStreetComplement(): ?string
|
||||
{
|
||||
return $this->streetComplement;
|
||||
}
|
||||
|
||||
public function setStreetComplement(?string $streetComplement): static
|
||||
{
|
||||
$this->streetComplement = $streetComplement;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getBennes(): ?int
|
||||
{
|
||||
return $this->bennes;
|
||||
}
|
||||
|
||||
public function setBennes(?int $bennes): static
|
||||
{
|
||||
$this->bennes = $bennes;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
// Groupe de lecture + nom serialise explicite (cf. note sur la propriete) :
|
||||
// sans SerializedName, Symfony exposerait la cle "triage" (strip du prefixe
|
||||
// "is") et, le groupe etant sur la propriete `triageProvider`, droppait
|
||||
// silencieusement la cle du JSON.
|
||||
#[Groups(['supplier:item:read'])]
|
||||
#[SerializedName('triageProvider')]
|
||||
public function isTriageProvider(): bool
|
||||
{
|
||||
return $this->triageProvider;
|
||||
}
|
||||
|
||||
public function setTriageProvider(bool $triageProvider): static
|
||||
{
|
||||
$this->triageProvider = $triageProvider;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPosition(): int
|
||||
{
|
||||
return $this->position;
|
||||
}
|
||||
|
||||
public function setPosition(int $position): static
|
||||
{
|
||||
$this->position = $position;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/** @return Collection<int, SiteInterface> */
|
||||
public function getSites(): Collection
|
||||
{
|
||||
return $this->sites;
|
||||
}
|
||||
|
||||
public function addSite(SiteInterface $site): static
|
||||
{
|
||||
if (!$this->sites->contains($site)) {
|
||||
$this->sites->add($site);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function removeSite(SiteInterface $site): static
|
||||
{
|
||||
$this->sites->removeElement($site);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/** @return Collection<int, SupplierContact> */
|
||||
public function getContacts(): Collection
|
||||
{
|
||||
return $this->contacts;
|
||||
}
|
||||
|
||||
public function addContact(SupplierContact $contact): static
|
||||
{
|
||||
if (!$this->contacts->contains($contact)) {
|
||||
$this->contacts->add($contact);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function removeContact(SupplierContact $contact): static
|
||||
{
|
||||
$this->contacts->removeElement($contact);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/** @return Collection<int, CategoryInterface> */
|
||||
public function getCategories(): Collection
|
||||
{
|
||||
return $this->categories;
|
||||
}
|
||||
|
||||
public function addCategory(CategoryInterface $category): static
|
||||
{
|
||||
if (!$this->categories->contains($category)) {
|
||||
$this->categories->add($category);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function removeCategory(CategoryInterface $category): static
|
||||
{
|
||||
$this->categories->removeElement($category);
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
<?php
|
||||
|
||||
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;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
|
||||
/**
|
||||
* Contact d'un fournisseur (1:n) — onglet Contacts. Au moins firstName OU
|
||||
* lastName doit etre renseigne (RG-2.04) : contrainte portee par un CHECK BDD
|
||||
* (chk_supplier_contact_name) et validee au Processor (ERP-88) ; l'entite reste
|
||||
* permissive (les deux champs sont nullable).
|
||||
*
|
||||
* Embarque sous `supplier.contacts` au detail (groupe supplier:item:read,
|
||||
* 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'])]
|
||||
#[Auditable]
|
||||
class SupplierContact implements TimestampableInterface, BlamableInterface
|
||||
{
|
||||
use TimestampableBlamableTrait;
|
||||
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column]
|
||||
#[Groups(['supplier:item:read'])]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: Supplier::class, inversedBy: 'contacts')]
|
||||
#[ORM\JoinColumn(name: 'supplier_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
|
||||
private ?Supplier $supplier = null;
|
||||
|
||||
// RG-2.04 : firstName OU lastName obligatoire (CHECK BDD + Processor). Les
|
||||
// deux restent nullable au niveau ORM.
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le prénom ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:contacts'])]
|
||||
private ?string $firstName = null;
|
||||
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le nom ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:contacts'])]
|
||||
private ?string $lastName = null;
|
||||
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'La fonction ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:contacts'])]
|
||||
private ?string $jobTitle = null;
|
||||
|
||||
// RG : pas de validation de format telephone (saisie libre), mais une
|
||||
// Assert\Length calee sur la colonne VARCHAR(20) evite l'erreur Postgres
|
||||
// (500 non rattachee au champ) au profit d'une 422 propre (ERP-107).
|
||||
#[ORM\Column(length: 20, nullable: true)]
|
||||
#[Assert\Length(max: 20, maxMessage: 'Le téléphone ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:contacts'])]
|
||||
private ?string $phonePrimary = null;
|
||||
|
||||
#[ORM\Column(length: 20, nullable: true)]
|
||||
#[Assert\Length(max: 20, maxMessage: 'Le téléphone secondaire ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:contacts'])]
|
||||
private ?string $phoneSecondary = null;
|
||||
|
||||
#[ORM\Column(length: 180, nullable: true)]
|
||||
#[Assert\Email(message: 'L\'adresse email n\'est pas valide.')]
|
||||
#[Assert\Length(max: 180, maxMessage: 'L\'email ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:contacts'])]
|
||||
private ?string $email = null;
|
||||
|
||||
// Ordre d'affichage du contact (gere serveur, non expose au M2).
|
||||
#[ORM\Column(options: ['default' => 0])]
|
||||
private int $position = 0;
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getSupplier(): ?Supplier
|
||||
{
|
||||
return $this->supplier;
|
||||
}
|
||||
|
||||
public function setSupplier(?Supplier $supplier): static
|
||||
{
|
||||
$this->supplier = $supplier;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getFirstName(): ?string
|
||||
{
|
||||
return $this->firstName;
|
||||
}
|
||||
|
||||
public function setFirstName(?string $firstName): static
|
||||
{
|
||||
$this->firstName = $firstName;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getLastName(): ?string
|
||||
{
|
||||
return $this->lastName;
|
||||
}
|
||||
|
||||
public function setLastName(?string $lastName): static
|
||||
{
|
||||
$this->lastName = $lastName;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getJobTitle(): ?string
|
||||
{
|
||||
return $this->jobTitle;
|
||||
}
|
||||
|
||||
public function setJobTitle(?string $jobTitle): static
|
||||
{
|
||||
$this->jobTitle = $jobTitle;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPhonePrimary(): ?string
|
||||
{
|
||||
return $this->phonePrimary;
|
||||
}
|
||||
|
||||
public function setPhonePrimary(?string $phonePrimary): static
|
||||
{
|
||||
$this->phonePrimary = $phonePrimary;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPhoneSecondary(): ?string
|
||||
{
|
||||
return $this->phoneSecondary;
|
||||
}
|
||||
|
||||
public function setPhoneSecondary(?string $phoneSecondary): static
|
||||
{
|
||||
$this->phoneSecondary = $phoneSecondary;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getEmail(): ?string
|
||||
{
|
||||
return $this->email;
|
||||
}
|
||||
|
||||
public function setEmail(?string $email): static
|
||||
{
|
||||
$this->email = $email;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPosition(): int
|
||||
{
|
||||
return $this->position;
|
||||
}
|
||||
|
||||
public function setPosition(int $position): static
|
||||
{
|
||||
$this->position = $position;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
<?php
|
||||
|
||||
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;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
|
||||
/**
|
||||
* Coordonnees bancaires d'un fournisseur (1:n) — onglet Comptabilite. Au moins un
|
||||
* RIB est obligatoire si le type de reglement est LCR (RG-2.08, verifie au
|
||||
* Processor : refus du DELETE du dernier RIB sous LCR, ERP-88).
|
||||
*
|
||||
* Embarque sous `supplier.ribs` UNIQUEMENT si l'user a accounting.view : le
|
||||
* read-group est `supplier:read:accounting`, retire du contexte par le
|
||||
* SupplierProvider sinon (gating par omission de cle — evite la fuite IBAN/BIC,
|
||||
* 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'])]
|
||||
#[Auditable]
|
||||
class SupplierRib implements TimestampableInterface, BlamableInterface
|
||||
{
|
||||
use TimestampableBlamableTrait;
|
||||
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column]
|
||||
#[Groups(['supplier:read:accounting'])]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: Supplier::class, inversedBy: 'ribs')]
|
||||
#[ORM\JoinColumn(name: 'supplier_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
|
||||
private ?Supplier $supplier = null;
|
||||
|
||||
#[ORM\Column(length: 120)]
|
||||
#[Assert\NotBlank(message: 'Le libellé du RIB est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le libellé ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Groups(['supplier:read:accounting', 'supplier:write:accounting'])]
|
||||
private ?string $label = null;
|
||||
|
||||
// Bic/Iban bornent deja le format (et donc la longueur) : pas de Length
|
||||
// redondant calee sur la colonne (auto-exempte du miroir ERP-107).
|
||||
#[ORM\Column(length: 20)]
|
||||
#[Assert\NotBlank(message: 'Le BIC est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Bic(message: 'Le BIC n\'est pas valide.')]
|
||||
#[Groups(['supplier:read:accounting', 'supplier:write:accounting'])]
|
||||
private ?string $bic = null;
|
||||
|
||||
#[ORM\Column(length: 34)]
|
||||
#[Assert\NotBlank(message: 'L\'IBAN est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Iban(message: 'L\'IBAN n\'est pas valide.')]
|
||||
#[Groups(['supplier:read:accounting', 'supplier:write:accounting'])]
|
||||
private ?string $iban = null;
|
||||
|
||||
// Ordre d'affichage du RIB (gere serveur, non expose au M2).
|
||||
#[ORM\Column(options: ['default' => 0])]
|
||||
private int $position = 0;
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getSupplier(): ?Supplier
|
||||
{
|
||||
return $this->supplier;
|
||||
}
|
||||
|
||||
public function setSupplier(?Supplier $supplier): static
|
||||
{
|
||||
$this->supplier = $supplier;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getLabel(): ?string
|
||||
{
|
||||
return $this->label;
|
||||
}
|
||||
|
||||
public function setLabel(string $label): static
|
||||
{
|
||||
$this->label = $label;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getBic(): ?string
|
||||
{
|
||||
return $this->bic;
|
||||
}
|
||||
|
||||
public function setBic(string $bic): static
|
||||
{
|
||||
$this->bic = $bic;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getIban(): ?string
|
||||
{
|
||||
return $this->iban;
|
||||
}
|
||||
|
||||
public function setIban(string $iban): static
|
||||
{
|
||||
$this->iban = $iban;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPosition(): int
|
||||
{
|
||||
return $this->position;
|
||||
}
|
||||
|
||||
public function setPosition(int $position): static
|
||||
{
|
||||
$this->position = $position;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -17,18 +17,20 @@ use Symfony\Component\Serializer\Attribute\Groups;
|
||||
* re-seede en dev/test par CommercialReferentialFixtures.
|
||||
*
|
||||
* Lecture seule au M1 (HP-M2-2) : seules GetCollection et Get sont exposees
|
||||
* (ERP-56), sous la permission commercial.clients.view ; aucune ecriture
|
||||
* (ERP-56), sous la permission commercial.clients.view (elargie aux roles
|
||||
* fournisseurs au M2 via commercial.suppliers.view, ERP-90) ; aucune ecriture
|
||||
* declaree -> POST/PATCH/DELETE renvoient 405.
|
||||
*
|
||||
* Referentiel statique : pas de Timestampable/Blamable (whiteliste dans
|
||||
* EntitiesAreTimestampableBlamableTest::EXCLUDED, comme CategoryType). Le
|
||||
* groupe `client:read:accounting` permet d'embarquer le mode dans la reponse
|
||||
* d'un Client (onglet Comptabilite) au lieu d'un IRI.
|
||||
* d'un Client (onglet Comptabilite) au lieu d'un IRI ; `supplier:read:accounting`
|
||||
* fait de meme dans la reponse Fournisseur (M2, ERP-92 — sinon IRI nu, § 4.0).
|
||||
*/
|
||||
#[ApiResource(
|
||||
operations: [
|
||||
new GetCollection(
|
||||
security: "is_granted('commercial.clients.view')",
|
||||
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||
normalizationContext: ['groups' => ['tva_mode:read']],
|
||||
// Tri par defaut spec M1 § 4.7 : position ASC puis label ASC
|
||||
// (ordre des selecteurs comptables) — provider Doctrine par defaut.
|
||||
@@ -39,11 +41,11 @@ use Symfony\Component\Serializer\Attribute\Groups;
|
||||
paginationClientEnabled: true,
|
||||
),
|
||||
new Get(
|
||||
security: "is_granted('commercial.clients.view')",
|
||||
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||
normalizationContext: ['groups' => ['tva_mode:read']],
|
||||
),
|
||||
],
|
||||
security: "is_granted('commercial.clients.view')",
|
||||
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||
)]
|
||||
#[ORM\Entity(repositoryClass: DoctrineTvaModeRepository::class)]
|
||||
#[ORM\Table(name: 'tva_mode')]
|
||||
@@ -53,15 +55,15 @@ class TvaMode
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column]
|
||||
#[Groups(['tva_mode:read', 'client:read:accounting'])]
|
||||
#[Groups(['tva_mode:read', 'client:read:accounting', 'supplier:read:accounting'])]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(length: 30)]
|
||||
#[Groups(['tva_mode:read', 'client:read:accounting'])]
|
||||
#[Groups(['tva_mode:read', 'client:read:accounting', 'supplier:read:accounting'])]
|
||||
private ?string $code = null;
|
||||
|
||||
#[ORM\Column(length: 120)]
|
||||
#[Groups(['tva_mode:read', 'client:read:accounting'])]
|
||||
#[Groups(['tva_mode:read', 'client:read:accounting', 'supplier:read:accounting'])]
|
||||
private ?string $label = null;
|
||||
|
||||
#[ORM\Column(options: ['default' => 0])]
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Domain\Repository;
|
||||
|
||||
use App\Module\Commercial\Domain\Entity\SupplierAddress;
|
||||
|
||||
interface SupplierAddressRepositoryInterface
|
||||
{
|
||||
public function findById(int $id): ?SupplierAddress;
|
||||
|
||||
public function save(SupplierAddress $address): void;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Domain\Repository;
|
||||
|
||||
use App\Module\Commercial\Domain\Entity\SupplierContact;
|
||||
|
||||
interface SupplierContactRepositoryInterface
|
||||
{
|
||||
public function findById(int $id): ?SupplierContact;
|
||||
|
||||
public function save(SupplierContact $contact): void;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Domain\Repository;
|
||||
|
||||
use App\Module\Commercial\Domain\Entity\Supplier;
|
||||
use Doctrine\ORM\QueryBuilder;
|
||||
|
||||
interface SupplierRepositoryInterface
|
||||
{
|
||||
public function findById(int $id): ?Supplier;
|
||||
|
||||
public function save(Supplier $supplier): void;
|
||||
|
||||
/**
|
||||
* Construit un QueryBuilder de liste pour le repertoire fournisseurs.
|
||||
* - Exclut toujours les fournisseurs soft-deletes (deleted_at IS NOT NULL, RG-2.17).
|
||||
* - Archivage (RG-2.17) :
|
||||
* - $archivedOnly = true -> uniquement les archives (is_archived = true) ;
|
||||
* - sinon $includeArchived = true -> actifs + archives (echappatoire) ;
|
||||
* - sinon (defaut) -> uniquement les actifs (is_archived = false).
|
||||
* $archivedOnly a la priorite sur $includeArchived.
|
||||
* - Tri par defaut : companyName ASC (RG-2.17).
|
||||
* - $search : recherche fuzzy insensible a la casse sur companyName + les
|
||||
* contacts lies (firstName / lastName / email) via sous-requete (D1,
|
||||
* refonte-contact §4.1). Metacaracteres LIKE echappes. Ignore si null/vide.
|
||||
* - $categoryCodes : restreint aux fournisseurs possedant au moins une
|
||||
* categorie dont le code est dans la liste (OR). Liste vide = pas de filtre.
|
||||
* - $siteIds : restreint aux fournisseurs ayant au moins une adresse rattachee
|
||||
* a l'un des sites donnes (OR — RG-2.06). Liste vide = pas de filtre.
|
||||
*
|
||||
* Filtrage centralise ICI (et non dans le provider/controller) pour que la
|
||||
* liste paginee (SupplierProvider) et l'export (SupplierExportController)
|
||||
* partagent strictement la meme logique de selection.
|
||||
*
|
||||
* Contrat = SELECTION uniquement (filtres + tri). Aucun fetch-join to-many :
|
||||
* l'hydratation des collections affichees est deleguee a
|
||||
* {@see self::hydrateListCollections()} pour ne pas imposer le cout d'un
|
||||
* produit cartesien aux chemins non pagines (cf. M1/ERP-100).
|
||||
*
|
||||
* @param list<string> $categoryCodes
|
||||
* @param list<int> $siteIds
|
||||
*/
|
||||
public function createListQueryBuilder(
|
||||
bool $includeArchived = false,
|
||||
?string $search = null,
|
||||
array $categoryCodes = [],
|
||||
array $siteIds = [],
|
||||
bool $archivedOnly = false,
|
||||
): QueryBuilder;
|
||||
|
||||
/**
|
||||
* Hydrate en lot les collections affichees par le repertoire (categories,
|
||||
* adresses et leurs sites) sur un jeu de fournisseurs DEJA charges, via
|
||||
* l'identity map Doctrine (memes instances). A appeler apres une selection
|
||||
* bornee (page courante ou jeu d'export) pour eviter le N+1 a la
|
||||
* serialisation, sans imposer de fetch-join au QueryBuilder de selection
|
||||
* (anti N+1, § 2.12).
|
||||
*
|
||||
* Charge les categories et les adresses/sites en DEUX requetes distinctes
|
||||
* (et non un triple fetch-join) pour ne pas multiplier categories x adresses
|
||||
* x sites en un seul produit cartesien.
|
||||
*
|
||||
* @param list<Supplier> $suppliers
|
||||
*/
|
||||
public function hydrateListCollections(array $suppliers): void;
|
||||
|
||||
/**
|
||||
* Hydrate en lot la collection `contacts` sur un jeu de fournisseurs DEJA
|
||||
* charges (memes instances via l'identity map). Reservee a l'export XLSX
|
||||
* (§ 4.6) qui a besoin du contact principal : la LISTE paginee n'embarque
|
||||
* pas les contacts (§ 2.12), d'ou une methode dediee plutot qu'une passe
|
||||
* supplementaire dans {@see self::hydrateListCollections()} — on n'impose pas
|
||||
* le cout du chargement des contacts au chemin liste.
|
||||
*
|
||||
* @param list<Supplier> $suppliers
|
||||
*/
|
||||
public function hydrateContacts(array $suppliers): void;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Domain\Repository;
|
||||
|
||||
use App\Module\Commercial\Domain\Entity\SupplierRib;
|
||||
|
||||
interface SupplierRibRepositoryInterface
|
||||
{
|
||||
public function findById(int $id): ?SupplierRib;
|
||||
|
||||
public function save(SupplierRib $rib): void;
|
||||
}
|
||||
+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;
|
||||
}
|
||||
}
|
||||
+8
-2
@@ -12,6 +12,7 @@ use App\Module\Commercial\Domain\Entity\Client;
|
||||
use App\Module\Commercial\Domain\Entity\ClientAddress;
|
||||
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 client (M1, § 4.5).
|
||||
@@ -75,9 +76,14 @@ final class ClientAddressProcessor implements ProcessorInterface
|
||||
? $clientId
|
||||
: $this->em->getRepository(Client::class)->find($clientId);
|
||||
|
||||
if ($client instanceof Client) {
|
||||
$address->setClient($client);
|
||||
// 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 client_id NOT NULL).
|
||||
if (!$client instanceof Client) {
|
||||
throw new NotFoundHttpException('Client introuvable.');
|
||||
}
|
||||
|
||||
$address->setClient($client);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+8
-2
@@ -14,6 +14,7 @@ use App\Module\Commercial\Domain\Entity\ClientContact;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Symfony\Component\Validator\ConstraintViolation;
|
||||
use Symfony\Component\Validator\ConstraintViolationList;
|
||||
|
||||
@@ -88,9 +89,14 @@ final class ClientContactProcessor implements ProcessorInterface
|
||||
? $clientId
|
||||
: $this->em->getRepository(Client::class)->find($clientId);
|
||||
|
||||
if ($client instanceof Client) {
|
||||
$contact->setClient($client);
|
||||
// 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 client_id NOT NULL).
|
||||
if (!$client instanceof Client) {
|
||||
throw new NotFoundHttpException('Client introuvable.');
|
||||
}
|
||||
|
||||
$contact->setClient($client);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+39
-28
@@ -8,11 +8,9 @@ use ApiPlatform\Metadata\Operation;
|
||||
use ApiPlatform\State\ProcessorInterface;
|
||||
use ApiPlatform\Validator\Exception\ValidationException;
|
||||
use App\Module\Commercial\Application\Service\ClientFieldNormalizer;
|
||||
use App\Module\Commercial\Application\Validator\ClientInformationCompletenessValidator;
|
||||
use App\Module\Commercial\Application\Validator\ClientAccountingCompletenessValidator;
|
||||
use App\Module\Commercial\Domain\Entity\Client;
|
||||
use App\Shared\Domain\Contract\BusinessRoleAwareInterface;
|
||||
use App\Shared\Domain\Contract\CategoryInterface;
|
||||
use App\Shared\Domain\Security\BusinessRoles;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
@@ -43,8 +41,8 @@ use Symfony\Component\Validator\ConstraintViolationList;
|
||||
* 2. Normalisation serveur (RG-1.18 a 1.21) via ClientFieldNormalizer.
|
||||
* 3. Regles metier : RG-1.03 (distributor/broker
|
||||
* exclusifs + type de categorie), RG-1.12 (Virement -> banque),
|
||||
* RG-1.13 (LCR -> >= 1 RIB), RG-1.04 (completude Information exigee sur POST
|
||||
* et tout PATCH pour le role Commerciale).
|
||||
* RG-1.13 (LCR -> >= 1 RIB). L'onglet Information est entierement facultatif
|
||||
* (RG-1.04 retiree : plus d'obligation, y compris pour le role Commerciale).
|
||||
* 4. Pose / retrait de archivedAt (RG-1.22 true=now, RG-1.23 false=null).
|
||||
* 5. Persistance via le persist_processor Doctrine, avec traduction des
|
||||
* collisions d'unicite en 409 (RG-1.16 doublon de nom ; RG-1.23 conflit de
|
||||
@@ -75,6 +73,14 @@ final class ClientProcessor implements ProcessorInterface
|
||||
'paymentType', 'bank',
|
||||
];
|
||||
|
||||
/**
|
||||
* Champs comptables obligatoires a la validation complete de l'onglet
|
||||
* (spec-front § Onglet Comptabilite). bank est exclu : conditionnel (RG-1.12).
|
||||
*/
|
||||
private const array ACCOUNTING_REQUIRED_FIELDS = [
|
||||
'siren', 'accountNumber', 'tvaMode', 'nTva', 'paymentDelay', 'paymentType',
|
||||
];
|
||||
|
||||
/** Champ d'archivage (groupe client:write:archive). */
|
||||
private const string ARCHIVE_FIELD = 'isArchived';
|
||||
|
||||
@@ -99,7 +105,7 @@ final class ClientProcessor implements ProcessorInterface
|
||||
#[Autowire(service: 'api_platform.doctrine.orm.state.persist_processor')]
|
||||
private readonly ProcessorInterface $persistProcessor,
|
||||
private readonly ClientFieldNormalizer $normalizer,
|
||||
private readonly ClientInformationCompletenessValidator $informationValidator,
|
||||
private readonly ClientAccountingCompletenessValidator $accountingValidator,
|
||||
private readonly Security $security,
|
||||
private readonly RequestStack $requestStack,
|
||||
private readonly EntityManagerInterface $em,
|
||||
@@ -111,6 +117,12 @@ final class ClientProcessor implements ProcessorInterface
|
||||
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
|
||||
}
|
||||
|
||||
// Reinitialisation de la memoisation du payload en debut de traitement :
|
||||
// le service est partage (stateful), on repart du corps de LA requete
|
||||
// courante et on n'herite jamais des cles decodees d'une requete passee.
|
||||
$this->decodedContent = null;
|
||||
$this->decodedPayloadKeys = [];
|
||||
|
||||
$writableKeys = $this->writablePayloadKeys();
|
||||
|
||||
$isArchiveRequest = $this->guardArchive($data, $writableKeys);
|
||||
@@ -125,7 +137,7 @@ final class ClientProcessor implements ProcessorInterface
|
||||
|
||||
$this->validateDistributorBroker($data);
|
||||
$this->validateAccountingConsistency($data);
|
||||
$this->validateInformationCompleteness($data);
|
||||
$this->validateAccountingCompleteness($data);
|
||||
|
||||
try {
|
||||
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
|
||||
@@ -487,18 +499,26 @@ final class ClientProcessor implements ProcessorInterface
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-1.04 (durcie ERP-74) : 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
|
||||
* (plus de condition d'intersection avec INFORMATION_FIELDS). Garantit qu'un
|
||||
* client cree/edite par une Commerciale ne reste jamais avec un onglet
|
||||
* Information incomplet.
|
||||
* spec-front § Onglet Comptabilite : a la validation COMPLETE de l'onglet
|
||||
* (les six champs obligatoires presents dans le payload — le front les envoie
|
||||
* toujours ensemble), chacun doit etre renseigne, sinon 422 par champ. On ne
|
||||
* declenche pas sur un PATCH ciblant un sous-ensemble de champs comptables :
|
||||
* ce n'est pas une validation d'onglet (edition ponctuelle preservee). bank /
|
||||
* RIB restent geres par validateAccountingConsistency (RG-1.12 / RG-1.13).
|
||||
*
|
||||
* Colonnes nullable en base + validateur contextuel : un Assert\NotBlank sur
|
||||
* l'entite casserait le POST de l'onglet principal, qui n'envoie aucun champ
|
||||
* comptable.
|
||||
*/
|
||||
private function validateInformationCompleteness(Client $data): void
|
||||
private function validateAccountingCompleteness(Client $data): void
|
||||
{
|
||||
if ($this->currentUserIsCommerciale()) {
|
||||
$this->informationValidator->validate($data);
|
||||
// Declenche uniquement si TOUS les champs requis sont presents dans le
|
||||
// payload (= soumission d'onglet, pas un PATCH partiel cible).
|
||||
if ([] !== array_diff(self::ACCOUNTING_REQUIRED_FIELDS, $this->payloadKeys())) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->accountingValidator->validate($data);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -516,21 +536,12 @@ final class ClientProcessor implements ProcessorInterface
|
||||
return false;
|
||||
}
|
||||
|
||||
private function currentUserIsCommerciale(): bool
|
||||
{
|
||||
$user = $this->security->getUser();
|
||||
|
||||
return $user instanceof BusinessRoleAwareInterface
|
||||
&& $user->hasBusinessRole(BusinessRoles::COMMERCIALE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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-1.22) et du
|
||||
* declenchement conditionnel de RG-1.04 — sans elles, un PATCH
|
||||
* « representation complete » porteur de @id ferait croire a une
|
||||
* modification multi-onglets.
|
||||
* groupe d'ecriture connu. C'est la base du 422 d'archivage (RG-1.22) —
|
||||
* sans elles, un PATCH « representation complete » porteur de @id ferait
|
||||
* croire a une modification multi-onglets.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
|
||||
+8
-2
@@ -12,6 +12,7 @@ use App\Module\Commercial\Domain\Entity\ClientRib;
|
||||
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 client (M1, § 4.5).
|
||||
@@ -77,9 +78,14 @@ final class ClientRibProcessor implements ProcessorInterface
|
||||
? $clientId
|
||||
: $this->em->getRepository(Client::class)->find($clientId);
|
||||
|
||||
if ($client instanceof Client) {
|
||||
$rib->setClient($client);
|
||||
// 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 client_id NOT NULL).
|
||||
if (!$client instanceof Client) {
|
||||
throw new NotFoundHttpException('Client introuvable.');
|
||||
}
|
||||
|
||||
$rib->setClient($client);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+533
@@ -0,0 +1,533 @@
|
||||
<?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);
|
||||
}
|
||||
|
||||
// Reinitialisation de la memoisation du payload en debut de traitement :
|
||||
// le service est partage (stateful), on repart du corps de LA requete
|
||||
// courante et on n'herite jamais des cles decodees d'une requete passee.
|
||||
$this->decodedContent = null;
|
||||
$this->decodedPayloadKeys = [];
|
||||
|
||||
$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,296 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Infrastructure\Controller;
|
||||
|
||||
use App\Module\Commercial\Domain\Entity\Supplier;
|
||||
use App\Module\Commercial\Domain\Entity\SupplierContact;
|
||||
use App\Module\Commercial\Domain\Repository\SupplierRepositoryInterface;
|
||||
use App\Shared\Domain\Contract\CategoryInterface;
|
||||
use App\Shared\Domain\Contract\SiteInterface;
|
||||
use App\Shared\Domain\Contract\SpreadsheetExporterInterface;
|
||||
use DateTimeImmutable;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Attribute\AsController;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
||||
|
||||
/**
|
||||
* Export XLSX du repertoire fournisseurs (M2, spec-back § 4.6). Jumeau du
|
||||
* {@see ClientExportController} (M1).
|
||||
*
|
||||
* Controller Symfony custom (et non operation API Platform) car il produit un
|
||||
* binaire de fichier, pas une representation Hydra. `priority: 1` est
|
||||
* OBLIGATOIRE sur la route : sans cela API Platform capterait
|
||||
* `/api/suppliers/export.xlsx` comme l'item `GET /api/suppliers/{id}.{_format}`
|
||||
* (id="export", _format="xlsx") — cf. CLAUDE.md « controller custom sous /api ».
|
||||
*
|
||||
* Separation des responsabilites :
|
||||
* - le COMMENT (generation du fichier) est delegue au service Shared
|
||||
* {@see SpreadsheetExporterInterface} — generique, reutilisable, sans metier ;
|
||||
* - le QUOI vit ICI : selection des fournisseurs (memes filtres que
|
||||
* `GET /api/suppliers`, via {@see SupplierRepositoryInterface::createListQueryBuilder()})
|
||||
* et mapping metier des colonnes.
|
||||
*
|
||||
* Colonnes de contact : depuis la suppression du contact inline (ERP-106), elles
|
||||
* sont alimentees par le CONTACT PRINCIPAL du fournisseur — le SupplierContact de
|
||||
* plus petit `position` (decision D2, spec § 4.6).
|
||||
*
|
||||
* La colonne SIREN n'est ajoutee que si l'utilisateur a la permission
|
||||
* `commercial.suppliers.accounting.view` (gating identique a la lecture).
|
||||
*/
|
||||
#[AsController]
|
||||
final class SupplierExportController
|
||||
{
|
||||
public function __construct(
|
||||
#[Autowire(service: 'App\Module\Commercial\Infrastructure\Doctrine\DoctrineSupplierRepository')]
|
||||
private readonly SupplierRepositoryInterface $repository,
|
||||
private readonly SpreadsheetExporterInterface $exporter,
|
||||
private readonly Security $security,
|
||||
) {}
|
||||
|
||||
#[Route('/api/suppliers/export.xlsx', name: 'commercial_suppliers_export_xlsx', methods: ['GET'], priority: 1)]
|
||||
#[IsGranted('commercial.suppliers.view')]
|
||||
public function __invoke(Request $request): Response
|
||||
{
|
||||
// Memes filtres d'archivage que la vue liste (SupplierProvider) pour que
|
||||
// l'export reflete exactement ce que l'utilisateur voit a l'ecran :
|
||||
// - includeArchived : inclut les archives en plus des actifs ;
|
||||
// - archivedOnly : restreint aux seules archives (prioritaire, cf.
|
||||
// createListQueryBuilder).
|
||||
$includeArchived = $this->readBool($request->query->get('includeArchived'));
|
||||
$archivedOnly = $this->readBool($request->query->get('archivedOnly'));
|
||||
$search = $request->query->getString('search') ?: null;
|
||||
|
||||
// Memes filtres que la vue liste : categoryCode/siteId tolerent une valeur
|
||||
// unique ou une liste (?categoryCode[]=A&siteId[]=1). On lit via all() pour
|
||||
// ne pas lever d'exception sur une valeur scalaire.
|
||||
$query = $request->query->all();
|
||||
$categoryCodes = $this->readStringList($query['categoryCode'] ?? []);
|
||||
$siteIds = $this->readIntList($query['siteId'] ?? []);
|
||||
|
||||
/** @var list<Supplier> $suppliers */
|
||||
$suppliers = $this->repository
|
||||
->createListQueryBuilder($includeArchived, $search, $categoryCodes, $siteIds, $archivedOnly)
|
||||
->getQuery()
|
||||
->getResult()
|
||||
;
|
||||
|
||||
// Hydratation batchee des collections affichees (§ 2.12) : le QB de
|
||||
// selection ne fetch-join pas les to-many. On remplit categories + sites en
|
||||
// lot (colonnes « Catégories » / « Sites »), puis les contacts (colonnes du
|
||||
// contact principal) — chacune en requetes IN bornees, anti N+1.
|
||||
$this->repository->hydrateListCollections($suppliers);
|
||||
$this->repository->hydrateContacts($suppliers);
|
||||
|
||||
$withSiren = $this->security->isGranted('commercial.suppliers.accounting.view');
|
||||
|
||||
$binary = $this->exporter->export(
|
||||
'Répertoire fournisseurs',
|
||||
$this->buildHeaders($withSiren),
|
||||
$this->buildRows($suppliers, $withSiren),
|
||||
);
|
||||
|
||||
return $this->buildResponse($binary);
|
||||
}
|
||||
|
||||
/**
|
||||
* Colonnes de l'export (spec § 4.6). SIREN inseree avant la date de creation,
|
||||
* uniquement si l'utilisateur a accounting.view.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private function buildHeaders(bool $withSiren): array
|
||||
{
|
||||
$headers = [
|
||||
'Nom fournisseur',
|
||||
'Contact principal',
|
||||
'Téléphone principal',
|
||||
'Téléphone secondaire',
|
||||
'Email',
|
||||
'Catégories',
|
||||
'Sites',
|
||||
];
|
||||
|
||||
if ($withSiren) {
|
||||
$headers[] = 'SIREN';
|
||||
}
|
||||
|
||||
$headers[] = 'Date de création';
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<Supplier> $suppliers
|
||||
*
|
||||
* @return iterable<list<null|scalar>>
|
||||
*/
|
||||
private function buildRows(array $suppliers, bool $withSiren): iterable
|
||||
{
|
||||
foreach ($suppliers as $supplier) {
|
||||
$contact = $this->principalContact($supplier);
|
||||
|
||||
$row = [
|
||||
$supplier->getCompanyName(),
|
||||
null !== $contact ? $this->formatContactName($contact) : '',
|
||||
$contact?->getPhonePrimary() ?? '',
|
||||
$contact?->getPhoneSecondary() ?? '',
|
||||
$contact?->getEmail() ?? '',
|
||||
$this->formatCategories($supplier),
|
||||
$this->formatSites($supplier),
|
||||
];
|
||||
|
||||
if ($withSiren) {
|
||||
$row[] = $supplier->getSiren();
|
||||
}
|
||||
|
||||
$row[] = $supplier->getCreatedAt()?->format('d/m/Y');
|
||||
|
||||
yield $row;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Contact principal du fournisseur : le SupplierContact de plus petit
|
||||
* `position` (decision D2, spec § 4.6). Null si le fournisseur n'a aucun
|
||||
* contact (les colonnes contact restent vides).
|
||||
*/
|
||||
private function principalContact(Supplier $supplier): ?SupplierContact
|
||||
{
|
||||
$contacts = $supplier->getContacts()->toArray();
|
||||
if ([] === $contacts) {
|
||||
return null;
|
||||
}
|
||||
|
||||
usort(
|
||||
$contacts,
|
||||
static fn (SupplierContact $a, SupplierContact $b): int => $a->getPosition() <=> $b->getPosition(),
|
||||
);
|
||||
|
||||
return $contacts[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Libelle du contact principal « Nom Prénom » (spec § 4.6). Les deux parties
|
||||
* sont optionnelles (RG-2.04 : au moins l'une des deux), d'ou le trim final.
|
||||
*/
|
||||
private function formatContactName(SupplierContact $contact): string
|
||||
{
|
||||
return trim(sprintf('%s %s', $contact->getLastName() ?? '', $contact->getFirstName() ?? ''));
|
||||
}
|
||||
|
||||
/**
|
||||
* Libelles des categories du fournisseur, dedupliques, tries, joints par
|
||||
* virgule.
|
||||
*/
|
||||
private function formatCategories(Supplier $supplier): string
|
||||
{
|
||||
$names = [];
|
||||
foreach ($supplier->getCategories() as $category) {
|
||||
// @var CategoryInterface $category
|
||||
$name = $category->getName();
|
||||
if (null !== $name && '' !== $name) {
|
||||
$names[$name] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->joinSorted($names);
|
||||
}
|
||||
|
||||
/**
|
||||
* Le fournisseur ne porte pas de sites en propre : ils sont rattaches aux
|
||||
* adresses (RG-2.06). La colonne « Sites » agrege donc l'union distincte des
|
||||
* sites de toutes les adresses du fournisseur.
|
||||
*/
|
||||
private function formatSites(Supplier $supplier): string
|
||||
{
|
||||
$names = [];
|
||||
foreach ($supplier->getAddresses() as $address) {
|
||||
foreach ($address->getSites() as $site) {
|
||||
// @var SiteInterface $site
|
||||
$name = $site->getName();
|
||||
if (null !== $name && '' !== $name) {
|
||||
$names[$name] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $this->joinSorted($names);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, true> $names ensemble de libelles (cles)
|
||||
*/
|
||||
private function joinSorted(array $names): string
|
||||
{
|
||||
$list = array_keys($names);
|
||||
sort($list);
|
||||
|
||||
return implode(', ', $list);
|
||||
}
|
||||
|
||||
private function buildResponse(string $binary): Response
|
||||
{
|
||||
$filename = sprintf('repertoire-fournisseurs-%s.xlsx', new DateTimeImmutable()->format('Ymd'));
|
||||
|
||||
$response = new Response($binary);
|
||||
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
||||
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lit un flag booleen issu des query params. Accepte true / "true" / "1".
|
||||
* Aligne sur SupplierProvider pour un comportement identique a la liste.
|
||||
*/
|
||||
private function readBool(mixed $raw): bool
|
||||
{
|
||||
return is_string($raw) && in_array(strtolower($raw), ['true', '1'], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise un filtre en liste de chaines (valeur unique ou liste).
|
||||
* Aligne sur SupplierProvider pour un comportement identique a la liste.
|
||||
*
|
||||
* @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 (valeur unique
|
||||
* ou liste). Aligne sur SupplierProvider.
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
@@ -234,7 +234,7 @@ class ClientFixtures extends Fixture implements DependentFixtureInterface
|
||||
$this->addAddress($services, ['Chatellerault'], '86100', 'Châtellerault', '15 rue du Conseil', isDelivery: true);
|
||||
}
|
||||
|
||||
// === Onglet Information complet (RG-1.04) ===
|
||||
// === Onglet Information complet (exemple de fiche renseignee) ===
|
||||
[$holding, $isNew] = $this->ensureClient(
|
||||
$manager,
|
||||
companyName: 'Holding Premium Invest',
|
||||
|
||||
@@ -0,0 +1,525 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Infrastructure\DataFixtures;
|
||||
|
||||
use App\Module\Catalog\Infrastructure\DataFixtures\CategoryFixtures;
|
||||
use App\Module\Commercial\Application\Service\SupplierFieldNormalizer;
|
||||
use App\Module\Commercial\Domain\Entity\Bank;
|
||||
use App\Module\Commercial\Domain\Entity\PaymentDelay;
|
||||
use App\Module\Commercial\Domain\Entity\PaymentType;
|
||||
use App\Module\Commercial\Domain\Entity\Supplier;
|
||||
use App\Module\Commercial\Domain\Entity\SupplierAddress;
|
||||
use App\Module\Commercial\Domain\Entity\SupplierContact;
|
||||
use App\Module\Commercial\Domain\Entity\SupplierRib;
|
||||
use App\Module\Commercial\Domain\Entity\TvaMode;
|
||||
use App\Module\Sites\Infrastructure\DataFixtures\SitesFixtures;
|
||||
use App\Shared\Domain\Contract\CategoryInterface;
|
||||
use App\Shared\Domain\Contract\SiteInterface;
|
||||
use App\Shared\Domain\Contract\SiteProviderInterface;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\Bundle\FixturesBundle\Fixture;
|
||||
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
|
||||
use Doctrine\Persistence\ObjectManager;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
|
||||
/**
|
||||
* Fixtures dev/test du module Commercial : ~13 fournisseurs de demonstration
|
||||
* couvrant l'ensemble des cas metier RG-2.xx du repertoire fournisseurs (M2),
|
||||
* jumelles des fixtures Client (ERP-68). Theme metier : negoce / recyclage de
|
||||
* metaux (d'ou les champs `bennes` et `triageProvider` sur les adresses).
|
||||
*
|
||||
* Cas pivots couverts (criteres d'acceptation ERP-112) :
|
||||
* - reglement VIREMENT avec banque renseignee (RG-2.07) ;
|
||||
* - reglement LCR avec 1 puis 2 RIB (RG-2.08) ; CHEQUE et NON_SOUMISE sans RIB ;
|
||||
* - adresses multi-types PROSPECT / DEPART / RENDU (RG-2.09) et multi-sites
|
||||
* (86 / 17 / 82, RG-2.06) ; bennes + prestataire de triage ;
|
||||
* - 1 a 3 contacts dont un avec telephone secondaire et un nomme par le seul
|
||||
* nom (RG-2.04) ;
|
||||
* - 2 fournisseurs archives (isArchived + archivedAt) pour l'exclusion de la
|
||||
* liste (RG-2.17) ;
|
||||
* - mono et multi-categories de type FOURNISSEUR (RG-2.10) ;
|
||||
* - onglet Information complet (dont volumeForecast, specifique fournisseur).
|
||||
*
|
||||
* Resolution inter-modules conforme a la regle n°1 (pas d'import direct) :
|
||||
* - categories resolues via le contrat Shared CategoryInterface
|
||||
* (resolve_target_entities -> Category) ;
|
||||
* - sites resolus via le contrat Shared SiteProviderInterface.
|
||||
*
|
||||
* Normalisation : les valeurs sont fournies BRUTES (casse libre, telephones
|
||||
* formates) et normalisees par SupplierFieldNormalizer avant persist, exactement
|
||||
* comme le ferait le SupplierProcessor via l'API (companyName UPPERCASE,
|
||||
* first/last Capitalize, telephones chiffres seuls, emails lowercase).
|
||||
*
|
||||
* Coherence gating comptable (RG-2.16) : les scalaires comptables (siren,
|
||||
* tvaMode, paymentType, bank...) et les RIB ne sont visibles qu'avec
|
||||
* accounting.view. Les donnees sont posees pour que les roles SANS cette
|
||||
* permission (ex. Commerciale) ne voient pas de compta — support des tests
|
||||
* ERP-92 et du golden path front.
|
||||
*
|
||||
* Idempotence : lookup par companyName normalise (coherent avec l'index unique
|
||||
* partiel uq_supplier_company_name_active). Un fournisseur deja present n'est pas
|
||||
* reconstruit (ses sous-collections ne sont pas redupliquees). Rejouable sans
|
||||
* doublon meme si le purger Doctrine est desactive.
|
||||
*
|
||||
* Audit / Blamable : persist hors contexte HTTP -> created_by / updated_by
|
||||
* restent null (« Systeme » cote front), c'est attendu. Les donnees respectent
|
||||
* les CHECK BDD (chk_supplier_contact_name : firstName OU lastName ;
|
||||
* chk_supplier_address_type : PROSPECT | DEPART | RENDU) ET la coherence des
|
||||
* validators d'entite (RG-2.07/2.08 : VIREMENT => banque, LCR => >= 1 RIB).
|
||||
*
|
||||
* Depend de CategoryFixtures (categories FOURNISSEUR), SitesFixtures (sites) et
|
||||
* CommercialReferentialFixtures (referentiels comptables — REUTILISES de M1,
|
||||
* aucune nouvelle table).
|
||||
*
|
||||
* Portee : DONNEES DE DEMONSTRATION (dev uniquement). En environnement `test`,
|
||||
* la fixture ne charge rien : les tests seedent et nettoient leurs propres
|
||||
* fournisseurs et comptent sur une table `supplier` vierge — y injecter 13
|
||||
* fournisseurs de demo casserait les comptages de liste et les cleanups. Meme
|
||||
* garde-fou que ClientFixtures / CategoryFixtures.
|
||||
*/
|
||||
class SupplierFixtures extends Fixture implements DependentFixtureInterface
|
||||
{
|
||||
/**
|
||||
* Type de categorie exige pour un fournisseur et ses adresses (RG-2.10).
|
||||
* Miroir de Supplier::REQUIRED_CATEGORY_TYPE_CODE (non importable — regle n°1).
|
||||
*/
|
||||
private const string SUPPLIER_CATEGORY_TYPE_CODE = 'FOURNISSEUR';
|
||||
|
||||
/** Cache des categories resolues par nom (evite des requetes repetees). */
|
||||
private array $categoryCache = [];
|
||||
|
||||
/** Cache des sites resolus par nom. */
|
||||
private array $siteCache = [];
|
||||
|
||||
/** ObjectManager courant, capture en debut de load (resolution categories). */
|
||||
private ObjectManager $manager;
|
||||
|
||||
public function __construct(
|
||||
private readonly SupplierFieldNormalizer $normalizer,
|
||||
private readonly SiteProviderInterface $siteProvider,
|
||||
#[Autowire('%kernel.environment%')]
|
||||
private readonly string $environment,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array<int, class-string>
|
||||
*/
|
||||
public function getDependencies(): array
|
||||
{
|
||||
return [
|
||||
CategoryFixtures::class,
|
||||
SitesFixtures::class,
|
||||
CommercialReferentialFixtures::class,
|
||||
];
|
||||
}
|
||||
|
||||
public function load(ObjectManager $manager): void
|
||||
{
|
||||
// Donnees de demo : dev uniquement. En test, on laisse la table vierge.
|
||||
if ('test' === $this->environment) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->manager = $manager;
|
||||
|
||||
// === Fournisseur basique — VIREMENT + banque (RG-2.07), compta complete ===
|
||||
[$negoce, $isNew] = $this->ensureSupplier($manager, 'Négoce Métaux Atlantique', ['Négociant']);
|
||||
if ($isNew) {
|
||||
$negoce->setSiren('841611054');
|
||||
$negoce->setAccountNumber('F0001');
|
||||
$negoce->setTvaMode($this->tvaMode($manager, 'FRANCE_VENTES'));
|
||||
$negoce->setNTva('FR12841611054');
|
||||
$negoce->setPaymentDelay($this->paymentDelay($manager, 'J30'));
|
||||
$negoce->setPaymentType($this->paymentType($manager, 'VIREMENT'));
|
||||
$negoce->setBank($this->bank($manager, 'SG'));
|
||||
$this->addContact($negoce, 'Jean', 'Dubois', 'Responsable achats', '05 49 00 00 01', null, 'jean.dubois@negoce-metaux.fr');
|
||||
$this->addAddress($negoce, 'DEPART', ['Chatellerault'], '86100', 'Châtellerault', '12 rue de la Ferraille', bennes: 4, triageProvider: true, categoryNames: ['Négociant']);
|
||||
}
|
||||
|
||||
// === LCR avec 1 RIB (RG-2.08) + 2 contacts ===
|
||||
[$coop, $isNew] = $this->ensureSupplier($manager, 'Coopérative Agricole du Sud-Ouest', ['Coopérative']);
|
||||
if ($isNew) {
|
||||
$coop->setSiren('775680459');
|
||||
$coop->setTvaMode($this->tvaMode($manager, 'FRANCE_VENTES'));
|
||||
$coop->setPaymentDelay($this->paymentDelay($manager, 'J15'));
|
||||
$coop->setPaymentType($this->paymentType($manager, 'LCR'));
|
||||
$this->addContact($coop, 'Sophie', 'Marchand', 'Directrice', '05 56 10 20 30', '06 11 22 33 44', 'sophie.marchand@coop-so.fr', 0);
|
||||
$this->addContact($coop, 'Marc', 'Girard', 'Acheteur', '05 56 10 20 31', null, 'marc.girard@coop-so.fr', 1);
|
||||
$this->addAddress($coop, 'RENDU', ['Pommevic'], '82400', 'Pommevic', '8 route des Cooperateurs', bennes: 2);
|
||||
$this->addRib($coop, 'Compte principal', 'BNPAFRPPXXX', 'FR1420041010050500013M02606', 0);
|
||||
}
|
||||
|
||||
// === Prospect seul (adresse PROSPECT), compta minimale ===
|
||||
[$producteur, $isNew] = $this->ensureSupplier($manager, 'Producteur Bio Charente', ['Producteur']);
|
||||
if ($isNew) {
|
||||
$this->addContact($producteur, 'Claire', 'Moreau', 'Gérante', '05 49 21 22 23', null, 'claire.moreau@bio-charente.fr');
|
||||
$this->addAddress($producteur, 'PROSPECT', ['Saint-Jean'], '17400', 'Fontenet', '1 chemin des Producteurs');
|
||||
}
|
||||
|
||||
// === Multi-categories M2M + LCR avec 2 RIB + 3 contacts ===
|
||||
[$grossiste, $isNew] = $this->ensureSupplier($manager, 'Grossiste Multi-Métaux', ['Grossiste', 'Négociant']);
|
||||
if ($isNew) {
|
||||
$grossiste->setSiren('552081317');
|
||||
$grossiste->setAccountNumber('F0004');
|
||||
$grossiste->setTvaMode($this->tvaMode($manager, 'FRANCE_VENTES'));
|
||||
$grossiste->setNTva('FR45552081317');
|
||||
$grossiste->setPaymentDelay($this->paymentDelay($manager, 'J30'));
|
||||
$grossiste->setPaymentType($this->paymentType($manager, 'LCR'));
|
||||
$this->addContact($grossiste, 'Thomas', 'Petit', 'Directeur des achats', '05 56 31 32 33', '06 01 02 03 04', 'thomas.petit@grossiste-mm.fr', 0);
|
||||
$this->addContact($grossiste, 'Julie', 'Roux', 'Assistante commerciale', '05 56 31 32 34', null, 'julie.roux@grossiste-mm.fr', 1);
|
||||
$this->addContact($grossiste, 'Hélène', 'Faure', 'Logistique', '05 56 31 32 35', null, 'helene.faure@grossiste-mm.fr', 2);
|
||||
$this->addAddress($grossiste, 'DEPART', ['Chatellerault'], '86100', 'Châtellerault', '20 zone des Activités', streetComplement: 'Bâtiment C', bennes: 6, triageProvider: true, categoryNames: ['Grossiste', 'Négociant']);
|
||||
$this->addRib($grossiste, 'Compte principal', 'BNPAFRPPXXX', 'FR7630006000011234567890189', 0);
|
||||
$this->addRib($grossiste, 'Compte secondaire', 'SOGEFRPPXXX', 'FR7630001007941234567890185', 1);
|
||||
}
|
||||
|
||||
// === VIREMENT + banque, TVA intracom (importateur), multi-sites sur l'adresse ===
|
||||
[$import, $isNew] = $this->ensureSupplier($manager, 'Import Recyclage International', ['Importateur']);
|
||||
if ($isNew) {
|
||||
$import->setSiren('409512012');
|
||||
$import->setTvaMode($this->tvaMode($manager, 'INTRACOM_VENTES'));
|
||||
$import->setNTva('FR90409512012');
|
||||
$import->setPaymentDelay($this->paymentDelay($manager, 'J30'));
|
||||
$import->setPaymentType($this->paymentType($manager, 'VIREMENT'));
|
||||
$import->setBank($this->bank($manager, 'CIC'));
|
||||
$this->addContact($import, 'Paul', 'Garnier', 'Import manager', '05 56 44 55 66', null, 'paul.garnier@import-recyclage.fr', 0);
|
||||
$this->addContact($import, null, 'Bernard', 'Douanes', '05 56 44 55 67', null, 'douanes@import-recyclage.fr', 1);
|
||||
$this->addAddress($import, 'RENDU', ['Pommevic', 'Saint-Jean'], '82400', 'Pommevic', '3 quai des Importateurs', bennes: 8);
|
||||
}
|
||||
|
||||
// === Multi-adresses PROSPECT / DEPART / RENDU (RG-2.09) + VIREMENT/banque ===
|
||||
[$ferrailleur, $isNew] = $this->ensureSupplier($manager, 'Ferrailleur Grand Ouest', ['Négociant']);
|
||||
if ($isNew) {
|
||||
$ferrailleur->setSiren('732829320');
|
||||
$ferrailleur->setTvaMode($this->tvaMode($manager, 'FRANCE_VENTES'));
|
||||
$ferrailleur->setPaymentDelay($this->paymentDelay($manager, 'A_RECEPTION'));
|
||||
$ferrailleur->setPaymentType($this->paymentType($manager, 'VIREMENT'));
|
||||
$ferrailleur->setBank($this->bank($manager, 'CA'));
|
||||
$this->addContact($ferrailleur, 'Olivier', 'Renard', 'Responsable site', '05 49 61 62 63', null, 'olivier.renard@ferrailleur-go.fr', 0);
|
||||
$this->addContact($ferrailleur, 'Nadia', 'Benali', 'Pesée', '05 49 61 62 64', null, 'nadia.benali@ferrailleur-go.fr', 1);
|
||||
// Prospect (site en cours de demarchage).
|
||||
$this->addAddress($ferrailleur, 'PROSPECT', ['Chatellerault'], '86100', 'Châtellerault', '5 avenue de la Prospection', position: 0);
|
||||
// Depart (collecte) multi-sites avec bennes + triage.
|
||||
$this->addAddress($ferrailleur, 'DEPART', ['Saint-Jean', 'Pommevic'], '17400', 'Fontenet', '4 rue de la Collecte', bennes: 5, triageProvider: true, categoryNames: ['Négociant'], position: 1);
|
||||
// Rendu (livraison).
|
||||
$this->addAddress($ferrailleur, 'RENDU', ['Pommevic'], '82400', 'Pommevic', '7 boulevard du Rendu', bennes: 3, position: 2);
|
||||
}
|
||||
|
||||
// === Onglet Information complet (dont volumeForecast) + VIREMENT/banque ===
|
||||
[$holding, $isNew] = $this->ensureSupplier($manager, 'Holding Recyclage Premium', ['Importateur']);
|
||||
if ($isNew) {
|
||||
$holding->setDescription('Holding de recyclage diversifiée, présente sur le Grand Sud-Ouest.');
|
||||
$holding->setCompetitors('Groupe Atlantique Recyclage, Sud Métaux');
|
||||
$holding->setFoundedAt(new DateTimeImmutable('2008-09-01'));
|
||||
$holding->setEmployeesCount(180);
|
||||
$holding->setRevenueAmount('24500000.00');
|
||||
$holding->setDirectorName('Antoine Lefèvre');
|
||||
$holding->setProfitAmount('1850000.00');
|
||||
$holding->setVolumeForecast(120000);
|
||||
$holding->setSiren('318471925');
|
||||
$holding->setAccountNumber('F0007');
|
||||
$holding->setTvaMode($this->tvaMode($manager, 'FRANCE_VENTES'));
|
||||
$holding->setNTva('FR33318471925');
|
||||
$holding->setPaymentDelay($this->paymentDelay($manager, 'J30'));
|
||||
$holding->setPaymentType($this->paymentType($manager, 'VIREMENT'));
|
||||
$holding->setBank($this->bank($manager, 'SG'));
|
||||
$this->addContact($holding, 'Antoine', 'Lefèvre', 'PDG', '05 56 51 52 53', null, 'antoine.lefevre@holding-recyclage.fr');
|
||||
$this->addAddress($holding, 'DEPART', ['Chatellerault'], '86100', 'Châtellerault', '1 allée des Investisseurs', bennes: 5, triageProvider: true, categoryNames: ['Importateur']);
|
||||
}
|
||||
|
||||
// === Coop minimale — contact par le seul nom (RG-2.04), sans compta ===
|
||||
[$coopMin, $isNew] = $this->ensureSupplier($manager, 'Coop Métaux Réunis', ['Coopérative']);
|
||||
if ($isNew) {
|
||||
$this->addContact($coopMin, null, 'Caron', 'Président', '05 49 81 82 83', null, 'president@coop-metaux-reunis.fr');
|
||||
$this->addAddress($coopMin, 'DEPART', ['Saint-Jean'], '17400', 'Fontenet', '6 chemin du Village');
|
||||
}
|
||||
|
||||
// === Reglement CHEQUE (sans banque ni RIB requis) ===
|
||||
[$petit, $isNew] = $this->ensureSupplier($manager, 'Petit Négoce Local', ['Négociant']);
|
||||
if ($isNew) {
|
||||
$petit->setTvaMode($this->tvaMode($manager, 'FRANCE_VENTES'));
|
||||
$petit->setPaymentDelay($this->paymentDelay($manager, 'A_RECEPTION'));
|
||||
$petit->setPaymentType($this->paymentType($manager, 'CHEQUE'));
|
||||
$this->addContact($petit, 'Luc', 'Martin', 'Gérant', '05 56 71 72 73', null, 'luc.martin@petit-negoce.fr');
|
||||
$this->addAddress($petit, 'RENDU', ['Chatellerault'], '86100', 'Châtellerault', '15 rue du Commerce');
|
||||
}
|
||||
|
||||
// === Reglement NON_SOUMISE + adresse multi-sites avec triage ===
|
||||
[$recup, $isNew] = $this->ensureSupplier($manager, 'Récupération Métaux Express', ['Grossiste']);
|
||||
if ($isNew) {
|
||||
$recup->setSiren('490212019');
|
||||
$recup->setTvaMode($this->tvaMode($manager, 'FRANCE_VENTES'));
|
||||
$recup->setPaymentDelay($this->paymentDelay($manager, 'J15'));
|
||||
$recup->setPaymentType($this->paymentType($manager, 'NON_SOUMISE'));
|
||||
$this->addContact($recup, 'Marie', 'Lemoine', 'Responsable', '05 49 77 88 99', null, 'marie.lemoine@recup-express.fr', 0);
|
||||
$this->addContact($recup, 'Pierre', 'Durand', 'Chauffeur', '05 49 77 88 98', null, 'pierre.durand@recup-express.fr', 1);
|
||||
$this->addAddress($recup, 'DEPART', ['Saint-Jean', 'Chatellerault'], '17400', 'Fontenet', '10 zone industrielle', bennes: 7, triageProvider: true, categoryNames: ['Grossiste']);
|
||||
}
|
||||
|
||||
// === Centre de tri — focus bennes/triage + multi-categories ===
|
||||
[$centre, $isNew] = $this->ensureSupplier($manager, 'Centre de Tri Sud', ['Producteur', 'Coopérative']);
|
||||
if ($isNew) {
|
||||
$centre->setPaymentDelay($this->paymentDelay($manager, 'A_RECEPTION'));
|
||||
$this->addContact($centre, 'Camille', 'Faure', 'Chef de centre', '05 56 91 92 93', null, 'camille.faure@centre-tri-sud.fr');
|
||||
$this->addAddress($centre, 'DEPART', ['Pommevic'], '82400', 'Pommevic', '2 route du Tri', bennes: 12, triageProvider: true, categoryNames: ['Producteur']);
|
||||
}
|
||||
|
||||
// === Fournisseur archive #1 (RG-2.17) ===
|
||||
[$ancien, $isNew] = $this->ensureSupplier($manager, 'Ancien Fournisseur Fermé', ['Producteur'], isArchived: true);
|
||||
if ($isNew) {
|
||||
$this->addContact($ancien, null, 'Lambert', 'Ancien contact', '05 49 99 99 99', null, 'contact@ancien-fournisseur.fr');
|
||||
$this->addAddress($ancien, 'DEPART', ['Chatellerault'], '86100', 'Châtellerault', '99 rue Fermée');
|
||||
}
|
||||
|
||||
// === Fournisseur archive #2 (RG-2.17) ===
|
||||
[$disparu, $isNew] = $this->ensureSupplier($manager, 'Négoce Disparu', ['Grossiste'], isArchived: true);
|
||||
if ($isNew) {
|
||||
$this->addContact($disparu, 'Gérard', 'Blanc', 'Ex-gérant', '05 56 00 00 00', null, 'gerard.blanc@negoce-disparu.fr');
|
||||
$this->addAddress($disparu, 'RENDU', ['Saint-Jean'], '17400', 'Fontenet', '0 impasse Oubliée');
|
||||
}
|
||||
|
||||
$manager->flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Cree un fournisseur (base normalisee + categories de type FOURNISSEUR)
|
||||
* s'il n'existe pas encore, sinon retourne l'existant. Retourne
|
||||
* [Supplier, isNew] : isNew=false bloque la reconstruction des
|
||||
* sous-collections (idempotence sans doublon).
|
||||
*
|
||||
* @param list<string> $categoryNames categories de type FOURNISSEUR (RG-2.10)
|
||||
*
|
||||
* @return array{0: Supplier, 1: bool}
|
||||
*/
|
||||
private function ensureSupplier(
|
||||
ObjectManager $manager,
|
||||
string $companyName,
|
||||
array $categoryNames,
|
||||
bool $isArchived = false,
|
||||
): array {
|
||||
$normalizedName = (string) $this->normalizer->normalizeCompanyName($companyName);
|
||||
|
||||
$existing = $manager->getRepository(Supplier::class)->findOneBy(['companyName' => $normalizedName]);
|
||||
if ($existing instanceof Supplier) {
|
||||
return [$existing, false];
|
||||
}
|
||||
|
||||
$supplier = new Supplier();
|
||||
$supplier->setCompanyName($normalizedName);
|
||||
|
||||
foreach ($categoryNames as $categoryName) {
|
||||
$supplier->addCategory($this->category($manager, $categoryName));
|
||||
}
|
||||
|
||||
if ($isArchived) {
|
||||
$supplier->setIsArchived(true);
|
||||
$supplier->setArchivedAt(new DateTimeImmutable());
|
||||
}
|
||||
|
||||
$manager->persist($supplier);
|
||||
|
||||
return [$supplier, true];
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajoute un contact normalise au fournisseur (cascade persist via
|
||||
* Supplier.contacts). Au moins firstName OU lastName est toujours fourni
|
||||
* (RG-2.04, chk_supplier_contact_name).
|
||||
*/
|
||||
private function addContact(
|
||||
Supplier $supplier,
|
||||
?string $firstName,
|
||||
?string $lastName,
|
||||
?string $jobTitle,
|
||||
?string $phonePrimary,
|
||||
?string $phoneSecondary,
|
||||
?string $email,
|
||||
int $position = 0,
|
||||
): void {
|
||||
$contact = new SupplierContact();
|
||||
$contact->setFirstName($this->normalizer->normalizePersonName($firstName));
|
||||
$contact->setLastName($this->normalizer->normalizePersonName($lastName));
|
||||
$contact->setJobTitle($jobTitle);
|
||||
$contact->setPhonePrimary($this->normalizer->normalizePhone($phonePrimary));
|
||||
$contact->setPhoneSecondary($this->normalizer->normalizePhone($phoneSecondary));
|
||||
$contact->setEmail($this->normalizer->normalizeEmail($email));
|
||||
$contact->setPosition($position);
|
||||
|
||||
$supplier->addContact($contact);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajoute une adresse au fournisseur (cascade persist via Supplier.addresses).
|
||||
* Le type d'adresse est exclusif (PROSPECT | DEPART | RENDU — RG-2.09,
|
||||
* chk_supplier_address_type) ; au moins un site est rattache (RG-2.06) ; les
|
||||
* categories d'adresse sont de type FOURNISSEUR (RG-2.10).
|
||||
*
|
||||
* @param list<string> $siteNames au moins un site (RG-2.06)
|
||||
* @param list<string> $categoryNames categories de type FOURNISSEUR (RG-2.10)
|
||||
*/
|
||||
private function addAddress(
|
||||
Supplier $supplier,
|
||||
string $addressType,
|
||||
array $siteNames,
|
||||
string $postalCode,
|
||||
string $city,
|
||||
string $street,
|
||||
?string $streetComplement = null,
|
||||
?int $bennes = null,
|
||||
bool $triageProvider = false,
|
||||
array $categoryNames = [],
|
||||
int $position = 0,
|
||||
): void {
|
||||
$address = new SupplierAddress();
|
||||
$address->setAddressType($addressType);
|
||||
$address->setPostalCode($postalCode);
|
||||
$address->setCity($city);
|
||||
$address->setStreet($street);
|
||||
$address->setStreetComplement($streetComplement);
|
||||
$address->setBennes($bennes);
|
||||
$address->setTriageProvider($triageProvider);
|
||||
$address->setPosition($position);
|
||||
|
||||
foreach ($siteNames as $siteName) {
|
||||
$address->addSite($this->site($siteName));
|
||||
}
|
||||
|
||||
foreach ($categoryNames as $categoryName) {
|
||||
$address->addCategory($this->category($this->manager, $categoryName));
|
||||
}
|
||||
|
||||
$supplier->addAddress($address);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajoute un RIB au fournisseur (cascade persist via Supplier.ribs). IBAN/BIC
|
||||
* valides (Assert\Iban/Bic non rejouee sur persist direct mais donnees
|
||||
* coherentes pour le golden path / les tests).
|
||||
*/
|
||||
private function addRib(Supplier $supplier, string $label, string $bic, string $iban, int $position = 0): void
|
||||
{
|
||||
$rib = new SupplierRib();
|
||||
$rib->setLabel($label);
|
||||
$rib->setBic($bic);
|
||||
$rib->setIban($iban);
|
||||
$rib->setPosition($position);
|
||||
|
||||
$supplier->addRib($rib);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resout une categorie par son nom via le contrat Shared CategoryInterface
|
||||
* (resolve_target_entities -> Category), sans importer le module Catalog
|
||||
* (regle n°1). Mise en cache par nom.
|
||||
*/
|
||||
private function category(ObjectManager $manager, string $name): CategoryInterface
|
||||
{
|
||||
if (isset($this->categoryCache[$name])) {
|
||||
return $this->categoryCache[$name];
|
||||
}
|
||||
|
||||
// RG-2.10 : on garde la categorie des qu'elle PORTE le type FOURNISSEUR
|
||||
// (multi-type depuis le passage en ManyToMany). Le nom etant desormais
|
||||
// unique GLOBALEMENT parmi les actifs, le lookup par `name` renvoie au
|
||||
// plus une categorie, mais on conserve la verification du type pour
|
||||
// ecarter un homonyme qui ne porterait pas FOURNISSEUR. Le filtre type
|
||||
// est porte cote PHP (findBy ne sait pas filtrer la collection categoryTypes).
|
||||
$candidates = $manager->getRepository(CategoryInterface::class)->findBy([
|
||||
'name' => $name,
|
||||
'deletedAt' => null,
|
||||
]);
|
||||
|
||||
foreach ($candidates as $candidate) {
|
||||
if ($candidate instanceof CategoryInterface
|
||||
&& in_array(self::SUPPLIER_CATEGORY_TYPE_CODE, $candidate->getCategoryTypeCodes(), true)) {
|
||||
return $this->categoryCache[$name] = $candidate;
|
||||
}
|
||||
}
|
||||
|
||||
throw new RuntimeException(sprintf(
|
||||
'Categorie FOURNISSEUR "%s" introuvable : CategoryFixtures doit tourner avant SupplierFixtures.',
|
||||
$name,
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Resout un site par son nom via le contrat Shared SiteProviderInterface,
|
||||
* sans importer le module Sites (regle n°1). Mise en cache par nom.
|
||||
*/
|
||||
private function site(string $name): SiteInterface
|
||||
{
|
||||
if (isset($this->siteCache[$name])) {
|
||||
return $this->siteCache[$name];
|
||||
}
|
||||
|
||||
$site = $this->siteProvider->findByName($name);
|
||||
|
||||
if (!$site instanceof SiteInterface) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'Site "%s" introuvable : SitesFixtures doit tourner avant SupplierFixtures.',
|
||||
$name,
|
||||
));
|
||||
}
|
||||
|
||||
return $this->siteCache[$name] = $site;
|
||||
}
|
||||
|
||||
private function tvaMode(ObjectManager $manager, string $code): TvaMode
|
||||
{
|
||||
$mode = $manager->getRepository(TvaMode::class)->findOneBy(['code' => $code]);
|
||||
|
||||
if (!$mode instanceof TvaMode) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'TvaMode "%s" introuvable : CommercialReferentialFixtures doit tourner avant SupplierFixtures.',
|
||||
$code,
|
||||
));
|
||||
}
|
||||
|
||||
return $mode;
|
||||
}
|
||||
|
||||
private function paymentDelay(ObjectManager $manager, string $code): PaymentDelay
|
||||
{
|
||||
$delay = $manager->getRepository(PaymentDelay::class)->findOneBy(['code' => $code]);
|
||||
|
||||
if (!$delay instanceof PaymentDelay) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'PaymentDelay "%s" introuvable : CommercialReferentialFixtures doit tourner avant SupplierFixtures.',
|
||||
$code,
|
||||
));
|
||||
}
|
||||
|
||||
return $delay;
|
||||
}
|
||||
|
||||
private function paymentType(ObjectManager $manager, string $code): PaymentType
|
||||
{
|
||||
$type = $manager->getRepository(PaymentType::class)->findOneBy(['code' => $code]);
|
||||
|
||||
if (!$type instanceof PaymentType) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'PaymentType "%s" introuvable : CommercialReferentialFixtures doit tourner avant SupplierFixtures.',
|
||||
$code,
|
||||
));
|
||||
}
|
||||
|
||||
return $type;
|
||||
}
|
||||
|
||||
private function bank(ObjectManager $manager, string $code): Bank
|
||||
{
|
||||
$bank = $manager->getRepository(Bank::class)->findOneBy(['code' => $code]);
|
||||
|
||||
if (!$bank instanceof Bank) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'Bank "%s" introuvable : CommercialReferentialFixtures doit tourner avant SupplierFixtures.',
|
||||
$code,
|
||||
));
|
||||
}
|
||||
|
||||
return $bank;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Infrastructure\Doctrine;
|
||||
|
||||
use App\Module\Commercial\Domain\Entity\SupplierAddress;
|
||||
use App\Module\Commercial\Domain\Repository\SupplierAddressRepositoryInterface;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/**
|
||||
* @extends ServiceEntityRepository<SupplierAddress>
|
||||
*/
|
||||
class DoctrineSupplierAddressRepository extends ServiceEntityRepository implements SupplierAddressRepositoryInterface
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, SupplierAddress::class);
|
||||
}
|
||||
|
||||
public function findById(int $id): ?SupplierAddress
|
||||
{
|
||||
return $this->find($id);
|
||||
}
|
||||
|
||||
public function save(SupplierAddress $address): void
|
||||
{
|
||||
$this->getEntityManager()->persist($address);
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Infrastructure\Doctrine;
|
||||
|
||||
use App\Module\Commercial\Domain\Entity\SupplierContact;
|
||||
use App\Module\Commercial\Domain\Repository\SupplierContactRepositoryInterface;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/**
|
||||
* @extends ServiceEntityRepository<SupplierContact>
|
||||
*/
|
||||
class DoctrineSupplierContactRepository extends ServiceEntityRepository implements SupplierContactRepositoryInterface
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, SupplierContact::class);
|
||||
}
|
||||
|
||||
public function findById(int $id): ?SupplierContact
|
||||
{
|
||||
return $this->find($id);
|
||||
}
|
||||
|
||||
public function save(SupplierContact $contact): void
|
||||
{
|
||||
$this->getEntityManager()->persist($contact);
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Infrastructure\Doctrine;
|
||||
|
||||
use App\Module\Commercial\Domain\Entity\Supplier;
|
||||
use App\Module\Commercial\Domain\Repository\SupplierRepositoryInterface;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\ORM\QueryBuilder;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/**
|
||||
* @extends ServiceEntityRepository<Supplier>
|
||||
*/
|
||||
class DoctrineSupplierRepository extends ServiceEntityRepository implements SupplierRepositoryInterface
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, Supplier::class);
|
||||
}
|
||||
|
||||
public function findById(int $id): ?Supplier
|
||||
{
|
||||
return $this->find($id);
|
||||
}
|
||||
|
||||
public function save(Supplier $supplier): void
|
||||
{
|
||||
$this->getEntityManager()->persist($supplier);
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
|
||||
public function createListQueryBuilder(
|
||||
bool $includeArchived = false,
|
||||
?string $search = null,
|
||||
array $categoryCodes = [],
|
||||
array $siteIds = [],
|
||||
bool $archivedOnly = false,
|
||||
): QueryBuilder {
|
||||
// SELECTION uniquement (filtres + tri) : pas de fetch-join to-many ici.
|
||||
// L'hydratation des collections affichees (Catégories / Site(s)) est
|
||||
// deleguee a hydrateListCollections() une fois le jeu borne, pour ne pas
|
||||
// imposer un produit cartesien aux chemins non pagines (export,
|
||||
// ?pagination=false) — § 2.12 (cf. M1/ERP-100).
|
||||
$qb = $this->createQueryBuilder('s')
|
||||
->andWhere('s.deletedAt IS NULL')
|
||||
->orderBy('s.companyName', 'ASC')
|
||||
;
|
||||
|
||||
// Perimetre d'archivage : archivedOnly prioritaire sur includeArchived.
|
||||
if ($archivedOnly) {
|
||||
$qb->andWhere('s.isArchived = true');
|
||||
} elseif (!$includeArchived) {
|
||||
$qb->andWhere('s.isArchived = false');
|
||||
}
|
||||
|
||||
$this->applySearch($qb, $search);
|
||||
$this->applyCategoryCodes($qb, $categoryCodes);
|
||||
$this->applySiteIds($qb, $siteIds);
|
||||
|
||||
return $qb;
|
||||
}
|
||||
|
||||
public function hydrateListCollections(array $suppliers): void
|
||||
{
|
||||
if ([] === $suppliers) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Ids des fournisseurs deja charges (entites managees). Les requetes
|
||||
// ci-dessous renvoient les MEMES instances Supplier (identity map), dont
|
||||
// les collections sont alors remplies — anti N+1 a la serialisation.
|
||||
$ids = [];
|
||||
foreach ($suppliers as $supplier) {
|
||||
$id = $supplier->getId();
|
||||
if (null !== $id) {
|
||||
$ids[] = $id;
|
||||
}
|
||||
}
|
||||
if ([] === $ids) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 1re passe : categories (colonne « Catégories »). Produit s x cat seul.
|
||||
$this->createQueryBuilder('s')
|
||||
->leftJoin('s.categories', 'cat')->addSelect('cat')
|
||||
->where('s.id IN (:ids)')->setParameter('ids', $ids)
|
||||
->getQuery()
|
||||
->getResult()
|
||||
;
|
||||
|
||||
// 2e passe : adresses + sites (colonne « Site(s) », sites portes par les
|
||||
// adresses — RG-2.06). Le join addr -> site reste imbrique mais n'est plus
|
||||
// multiplie par les categories : le cartesien global est casse.
|
||||
$this->createQueryBuilder('s')
|
||||
->leftJoin('s.addresses', 'addr')->addSelect('addr')
|
||||
->leftJoin('addr.sites', 'site')->addSelect('site')
|
||||
->where('s.id IN (:ids)')->setParameter('ids', $ids)
|
||||
->getQuery()
|
||||
->getResult()
|
||||
;
|
||||
}
|
||||
|
||||
public function hydrateContacts(array $suppliers): void
|
||||
{
|
||||
$ids = [];
|
||||
foreach ($suppliers as $supplier) {
|
||||
$id = $supplier->getId();
|
||||
if (null !== $id) {
|
||||
$ids[] = $id;
|
||||
}
|
||||
}
|
||||
if ([] === $ids) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Une seule requete IN bornee : remplit la collection `contacts` des MEMES
|
||||
// instances Supplier (identity map). Tri par position pour que le « contact
|
||||
// principal » (plus petit position) soit deterministe a l'export (§ 4.6).
|
||||
$this->createQueryBuilder('s')
|
||||
->leftJoin('s.contacts', 'sc')->addSelect('sc')
|
||||
->where('s.id IN (:ids)')->setParameter('ids', $ids)
|
||||
->orderBy('sc.position', 'ASC')
|
||||
->getQuery()
|
||||
->getResult()
|
||||
;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recherche fuzzy insensible a la casse sur companyName ET sur les contacts
|
||||
* lies (firstName / lastName / email) — decision D1, refonte-contact (§ 4.1).
|
||||
* Les deux criteres sont unis par OR : un fournisseur matche si son nom de
|
||||
* societe OU l'un de ses contacts matche. Le critere contact passe par une
|
||||
* sous-requete IN (plutot qu'un JOIN sur la collection) pour ne pas perturber
|
||||
* le DISTINCT / ORDER BY / pagination principal. Les metacaracteres LIKE
|
||||
* (%, _, \) saisis sont echappes pour rester litteraux.
|
||||
*/
|
||||
private function applySearch(QueryBuilder $qb, ?string $search): void
|
||||
{
|
||||
if (null === $search || '' === trim($search)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$escaped = str_replace(['\\', '%', '_'], ['\\\\', '\%', '\_'], trim($search));
|
||||
$pattern = '%'.mb_strtolower($escaped, 'UTF-8').'%';
|
||||
|
||||
$contactSub = $this->getEntityManager()->createQueryBuilder()
|
||||
->select('s2.id')
|
||||
->from(Supplier::class, 's2')
|
||||
->join('s2.contacts', 'sc2')
|
||||
->where('LOWER(sc2.firstName) LIKE :search')
|
||||
->orWhere('LOWER(sc2.lastName) LIKE :search')
|
||||
->orWhere('LOWER(sc2.email) LIKE :search')
|
||||
;
|
||||
|
||||
$qb->andWhere(
|
||||
$qb->expr()->orX(
|
||||
'LOWER(s.companyName) LIKE :search',
|
||||
$qb->expr()->in('s.id', $contactSub->getDQL()),
|
||||
),
|
||||
)->setParameter('search', $pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* Restreint aux fournisseurs possedant au moins une categorie dont le code
|
||||
* figure dans la liste (OR). Alimente le filtre « Catégories » du drawer.
|
||||
* Sous-requete IN (plutot qu'un JOIN sur la collection M2M) pour ne pas
|
||||
* perturber le DISTINCT / ORDER BY principal.
|
||||
*
|
||||
* @param list<string> $categoryCodes
|
||||
*/
|
||||
private function applyCategoryCodes(QueryBuilder $qb, array $categoryCodes): void
|
||||
{
|
||||
$codes = $this->normalizeStringList($categoryCodes);
|
||||
if ([] === $codes) {
|
||||
return;
|
||||
}
|
||||
|
||||
$sub = $this->getEntityManager()->createQueryBuilder()
|
||||
->select('s3.id')
|
||||
->from(Supplier::class, 's3')
|
||||
->join('s3.categories', 'cat3')
|
||||
->where('cat3.code IN (:categoryCodes)')
|
||||
;
|
||||
|
||||
$qb->andWhere($qb->expr()->in('s.id', $sub->getDQL()))
|
||||
->setParameter('categoryCodes', $codes)
|
||||
;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restreint aux fournisseurs ayant au moins une adresse rattachee a l'un des
|
||||
* sites donnes (OR — RG-2.06 : les sites vivent sur les adresses). Sous-requete
|
||||
* IN pour ne pas perturber le tri/pagination principal.
|
||||
*
|
||||
* @param list<int> $siteIds
|
||||
*/
|
||||
private function applySiteIds(QueryBuilder $qb, array $siteIds): void
|
||||
{
|
||||
$ids = $this->normalizeIntList($siteIds);
|
||||
if ([] === $ids) {
|
||||
return;
|
||||
}
|
||||
|
||||
$sub = $this->getEntityManager()->createQueryBuilder()
|
||||
->select('s4.id')
|
||||
->from(Supplier::class, 's4')
|
||||
->join('s4.addresses', 'addr4')
|
||||
->join('addr4.sites', 'site4')
|
||||
->where('site4.id IN (:siteIds)')
|
||||
;
|
||||
|
||||
$qb->andWhere($qb->expr()->in('s.id', $sub->getDQL()))
|
||||
->setParameter('siteIds', $ids)
|
||||
;
|
||||
}
|
||||
|
||||
/**
|
||||
* Nettoie une liste de chaines : trim, retrait des vides, reindexation.
|
||||
* Defensive : tolere des elements scalaires non-string (cast) et ignore le
|
||||
* reste sans lever de TypeError, le contrat etant de normaliser une entree
|
||||
* potentiellement brute (query params).
|
||||
*
|
||||
* @param array<mixed> $values
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private function normalizeStringList(array $values): array
|
||||
{
|
||||
$out = [];
|
||||
foreach ($values as $value) {
|
||||
if (is_string($value) || is_int($value) || is_float($value)) {
|
||||
$trimmed = trim((string) $value);
|
||||
if ('' !== $trimmed) {
|
||||
$out[] = $trimmed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Nettoie une liste d'identifiants : cast int, retrait des <= 0, reindexation.
|
||||
* Defensive (cf. normalizeStringList) : accepte des entiers ou des chaines
|
||||
* numeriques ('1', '2') sans TypeError, ignore le reste.
|
||||
*
|
||||
* @param array<mixed> $values
|
||||
*
|
||||
* @return list<int>
|
||||
*/
|
||||
private function normalizeIntList(array $values): array
|
||||
{
|
||||
$out = [];
|
||||
foreach ($values as $value) {
|
||||
if (is_numeric($value) && (int) $value > 0) {
|
||||
$out[] = (int) $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Infrastructure\Doctrine;
|
||||
|
||||
use App\Module\Commercial\Domain\Entity\SupplierRib;
|
||||
use App\Module\Commercial\Domain\Repository\SupplierRibRepositoryInterface;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/**
|
||||
* @extends ServiceEntityRepository<SupplierRib>
|
||||
*/
|
||||
class DoctrineSupplierRibRepository extends ServiceEntityRepository implements SupplierRibRepositoryInterface
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, SupplierRib::class);
|
||||
}
|
||||
|
||||
public function findById(int $id): ?SupplierRib
|
||||
{
|
||||
return $this->find($id);
|
||||
}
|
||||
|
||||
public function save(SupplierRib $rib): void
|
||||
{
|
||||
$this->getEntityManager()->persist($rib);
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
@@ -36,8 +36,8 @@ final class RbacSeeder
|
||||
{
|
||||
/**
|
||||
* Codes des roles metier (snake_case, regex Role respectee). `commerciale`
|
||||
* reference la constante Shared deja consommee par le ClientProcessor
|
||||
* (RG-1.04) pour eviter tout drift : un seul litteral pour ce code.
|
||||
* reference la constante Shared pour eviter tout drift : un seul litteral
|
||||
* pour ce code.
|
||||
*/
|
||||
public const string ROLE_BUREAU = 'bureau';
|
||||
public const string ROLE_COMPTA = 'compta';
|
||||
@@ -51,8 +51,9 @@ final class RbacSeeder
|
||||
* Definition unique des 4 roles + matrice § 2.7. La cle est le code du role,
|
||||
* `label` le libelle FR affichable, `permissions` la liste des codes RBAC a
|
||||
* attacher (vide pour usine : aucun acces ; admin n'apparait pas car il
|
||||
* bypass tout via isAdmin ; `commercial.clients.archive` n'est attache a
|
||||
* aucun role metier — admin seul).
|
||||
* bypass tout via isAdmin ; `commercial.clients.archive` et
|
||||
* `commercial.suppliers.archive` ne sont attaches a aucun role metier —
|
||||
* admin seul).
|
||||
*
|
||||
* @var array<string, array{label: string, permissions: list<string>}>
|
||||
*/
|
||||
@@ -62,6 +63,9 @@ final class RbacSeeder
|
||||
'permissions' => [
|
||||
'commercial.clients.view',
|
||||
'commercial.clients.manage',
|
||||
// Fournisseurs (M2 § 2.9, ERP-90) : view + manage (hors Comptabilite).
|
||||
'commercial.suppliers.view',
|
||||
'commercial.suppliers.manage',
|
||||
// Lecture des referentiels transverses pour les selects client (ERP-102).
|
||||
'catalog.categories.read_ref',
|
||||
'sites.read_ref',
|
||||
@@ -73,6 +77,11 @@ final class RbacSeeder
|
||||
'commercial.clients.view',
|
||||
'commercial.clients.accounting.view',
|
||||
'commercial.clients.accounting.manage',
|
||||
// Fournisseurs (M2 § 2.9, ERP-90) : view + onglet Comptabilite uniquement
|
||||
// (pas de manage global -> ne peut pas creer un fournisseur).
|
||||
'commercial.suppliers.view',
|
||||
'commercial.suppliers.accounting.view',
|
||||
'commercial.suppliers.accounting.manage',
|
||||
// Lecture des referentiels transverses pour les selects client (ERP-102).
|
||||
'catalog.categories.read_ref',
|
||||
'sites.read_ref',
|
||||
@@ -83,6 +92,10 @@ final class RbacSeeder
|
||||
'permissions' => [
|
||||
'commercial.clients.view',
|
||||
'commercial.clients.manage',
|
||||
// Fournisseurs (M2 § 2.9, ERP-90) : view + manage, sans accounting
|
||||
// (onglet Comptabilite masque/filtre pour la Commerciale).
|
||||
'commercial.suppliers.view',
|
||||
'commercial.suppliers.manage',
|
||||
// Lecture des referentiels transverses pour les selects client (ERP-102).
|
||||
'catalog.categories.read_ref',
|
||||
'sites.read_ref',
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user