Compare commits

...

80 Commits

Author SHA1 Message Date
tristan 06a7ef4f78 fix(front) : repertoires fournisseur et prestataire affichent le code des categories (MAJUSCULE) comme le client (ERP-193)
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Successful in 2m4s
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Successful in 3m37s
formatCategories mappe desormais c.code (slug MAJUSCULE) au lieu de c.name,
pour aligner l'affichage des categories sur le repertoire client.
2026-06-19 16:51:03 +02:00
tristan 3462510c15 fix(front) : pas d'etoile required sur les champs adresse en consultation (4 modules) (ERP-193)
Les *AddressBlock derivent desormais required de l'etat editable
(:required="!readonly && !disabled") : l'asterisque obligatoire reste en
creation/edition mais disparait en consultation (bloc disabled).
2026-06-19 15:45:49 +02:00
tristan ad7d201285 fix(front) : masque la barre d'onglets en consultation fournisseur quand aucun onglet visible + bump @malio/layer-ui 1.7.13 (ERP-193)
- consultation fournisseur : MalioTabList rendu sous v-if="visibleTabKeys.length"
  (aligne sur le client) pour ne plus afficher la bordure quand seul le formulaire
  principal est rempli
- mise a jour @malio/layer-ui ^1.7.12 -> ^1.7.13
2026-06-19 15:39:55 +02:00
tristan 4a2d7cddb0 Merge remote-tracking branch 'origin/fix/erp-193-retours-metier' into fix/erp-193-retours-metier
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Successful in 48s
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Successful in 2m17s
2026-06-19 15:24:59 +02:00
tristan 1e86d9745c fix(front) : toast de succes a la suppression d'un bloc (contact / adresse / RIB / prix) sur les 4 modules (ERP-193)
removeCollectionRow expose un callback onSuccess declenche uniquement apres une
suppression serveur confirmee (pas sur le retrait d'un brouillon local). Cable
sur Client / Fournisseur / Prestataire / Transporteur via notifyRemovalSuccess,
avec un message i18n generique success.deleted.
2026-06-19 15:24:38 +02:00
matthieu 1ef0560604 Merge branch 'develop' into fix/erp-193-retours-metier
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Has been cancelled
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Has been cancelled
2026-06-19 13:08:14 +00:00
tristan 0786e4f461 fix(front) : masque le Valider du premier onglet tant que le formulaire principal n'est pas valide (ERP-193)
Sur les ecrans d'ajout Client / Fournisseur / Prestataire, le Valider du
premier onglet (onglet actif par defaut) etait seulement desactive et
s'affichait a cote de celui du formulaire principal. On le masque desormais
tant que l'entite n'est pas creee (id null).
2026-06-19 15:01:21 +02:00
tristan 833d992ebb fix(transport) : onglet Contact transporteur non obligatoire + navigation onglets (ERP-193)
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Successful in 46s
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Successful in 3m24s
- retrait de la regle « prenom OU nom » sur le bloc Contact : garde
  CarrierContactProcessor::validateName supprimee, CHECK chk_carrier_contact_name
  droppe (migration Version20260619120000), commentaires SQL/catalogue alignes
- front : gating « + Nouveau contact » sur bloc non vide (au lieu de « nomme »),
  onglet Contact vide finalisable sans creer de contact
- Prix accessible des la validation des Adresses (Contacts optionnel ne bloque plus)
- consultation <-> edition : on retombe sur le meme onglet via ?tab=
2026-06-19 14:53:52 +02:00
tristan c11d7822ce refactor(front) : champs anti-parasites via masks maska (filtrage natif, focus/curseur OK) au lieu du sanitizer @update ; email sans masque (ERP-193)
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Has been cancelled
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Has been cancelled
2026-06-19 14:25:26 +02:00
tristan e66615d40b fix(transport) : immatriculations LIOT filtrées via mask maska (focus/curseur natifs, plus de hack) (ERP-193)
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Failing after 12m13s
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Has been cancelled
2026-06-19 14:10:49 +02:00
tristan 6d3122a0b8 fix(transport) : immatriculations LIOT — re-synchronise le champ après filtrage (:key) pour ne plus afficher les caractères interdits (ERP-193)
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Failing after 15m5s
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Failing after 15m7s
2026-06-19 12:02:56 +02:00
tristan fa00a2b6e1 fix(transport) : immatriculations LIOT sur 3 colonnes en consultation aussi (ERP-193)
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Has been cancelled
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Has been cancelled
2026-06-19 11:52:24 +02:00
tristan a98f58cb33 feat(transport) : immatriculations LIOT sur 3 colonnes + filtre saisie (lettres/chiffres/tiret/point-virgule) (ERP-193)
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Has been cancelled
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Has been cancelled
2026-06-19 11:50:05 +02:00
tristan ab33b09bc0 fix(transport) : tableau prix — bord droit Transport noir uniforme (couleur de bordure bas side-specific) (ERP-193)
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Has been cancelled
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Has been cancelled
2026-06-19 11:36:45 +02:00
tristan 023f70dd1d fix(transport) : tableau prix — trait fin entre lignes d'une même adresse, épais entre adresses (ERP-193)
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Has been cancelled
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Has been cancelled
2026-06-19 11:34:15 +02:00
tristan c243232799 fix(transport) : tableau prix — pas de trait entre les lignes d'une même adresse de livraison (ERP-193)
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Has been cancelled
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Has been cancelled
2026-06-19 11:29:29 +02:00
tristan cdd43960cd fix(transport) : tableau prix — regroupement et tri par adresse de livraison, contenant par ligne (ERP-193)
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Has been cancelled
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Has been cancelled
2026-06-19 11:17:47 +02:00
tristan 9a42c432f8 fix(transport) : tableau prix — colonnes séparées, ordre Adresse livraisons puis Adresse sites (ERP-193)
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Successful in 2m19s
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Successful in 3m36s
2026-06-19 11:10:17 +02:00
tristan 865e580b6e fix(transport) : tableau prix — colonne Fournisseurs/Clients, fusion adresses sites/livraisons, renomme Transport (ERP-193)
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Successful in 1m55s
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Successful in 3m19s
2026-06-19 10:50:25 +02:00
tristan 0ad4a739ca style : bouton Archiver en rouge (variant danger) sur les 4 consultations (ERP-193)
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Successful in 2m16s
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Successful in 3m39s
2026-06-19 10:13:52 +02:00
tristan cdcc7d1e75 feat : grise les champs en consultation et onglets validés (readonly → disabled) (ERP-193) 2026-06-19 09:48:49 +02:00
tristan 07f5a95a6b feat : bloque les caractères spéciaux dans les champs texte des 4 répertoires (ERP-193) 2026-06-19 09:46:23 +02:00
gitea-actions 6c938756cc chore: bump version to v0.1.146
Auto Tag Develop / tag (push) Successful in 6s
Build & Push Docker Image / build (push) Successful in 2m8s
2026-06-19 07:35:42 +00:00
matthieu ac1a51a7f4 fix(prod) : droits www-data sur le volume de logs (#138)
Auto Tag Develop / tag (push) Successful in 8s
## Problème

Le volume nommé `starseed_logs` est monté sur `/var/www/html/var/log` (docker-compose.prod.yml), mais ce dossier **n'existe pas dans l'image**. Au premier montage d'un volume vide, Docker crée le point de montage en `root:root`, ce qui empêche `www-data` (le worker php-fpm) d'écrire les logs → crash de l'application.

Même problème que celui rencontré et patché à la main sur Lesstime.

## Correctif

Ajout de `var/log` au `mkdir -p` du Dockerfile, avant le `chown -R www-data:www-data`. Ainsi tout volume de logs neuf hérite automatiquement des droits `www-data` — plus besoin de chown manuel.

## Déploiement

Nécessite un rebuild + push de l'image pour prendre effet en prod.

---------

Co-authored-by: Matthieu <contact@malio.fr>
Reviewed-on: #138
2026-06-19 07:35:34 +00:00
tristan 403dc4a870 feat(commercial) : interdit les dates de création futures sur client/fournisseur (ERP-193) 2026-06-18 16:53:07 +02:00
tristan 745b03083c feat(commercial) : plafonne le chiffre d'affaires client/fournisseur à 999 999 999 999,99 (ERP-193) 2026-06-18 16:34:12 +02:00
tristan 868141e324 fix(front) : masque les onglets vides en consultation des 4 repertoires (ERP-193) 2026-06-18 16:15:41 +02:00
tristan 86507486a4 fix(front) : renomme la colonne « Dernière activité » en « Dernière modification » (ERP-193) 2026-06-18 15:58:46 +02:00
tristan 29aa9b352d fix(front) : pagination par defaut a 25 sur les repertoires (ERP-193) 2026-06-18 15:53:25 +02:00
gitea-actions a9935fbf97 chore: bump version to v0.1.145
Auto Tag Develop / tag (push) Successful in 7s
Build & Push Docker Image / build (push) Successful in 24s
2026-06-18 13:33:48 +00:00
matthieu 36e947fd8e test(logistique) : tests PHPUnit RG-5.01→5.10 + capture contrat JSON (ERP-187) (#137)
Auto Tag Develop / tag (push) Successful in 8s
## ERP-187 (1.7) — Tests PHPUnit RG-5.01→5.10 + capture contrat JSON

Couvre les règles de gestion du M5 (tickets de pesée) par des tests PHPUnit et capture la **réponse JSON réelle** (DoD § 4.0.bis) collée dans `spec-back.md` avant les écrans front.

### Tests unitaires (Processor / Normalizer / Callback — sans BDD ni HTTP)
- **NetWeightTest** (RG-5.05) : net = plein − vide, `null` si une pesée manque, recalcul au PATCH.
- **CounterpartyValidationTest** (RG-5.03) : présence du champ requis par branche (propertyPath `client`/`supplier`/`otherLabel`) + exclusivité (null-ification hors-branche).
- **ImmatriculationNormalizationTest** (RG-5.01/5.10) : masque `XX-000-XX`, « Tout format », mapping 422 sur `immatriculation`.

### Tests fonctionnels (API réelle)
- **WeighingTicketNumberingTest** (RG-5.02/5.09) : format `{siteCode}-TP-{NNNN}`, séquence par site, isolation inter-sites, immuabilité numéro/site au PATCH.
- **WeighingTicketSerializationContractTest** (DoD § 4.0.bis) : 4 pièges verts (client embarqué, `plateFreeFormat` présent, `number` formaté, `netWeight` = full − empty) + dump JSON via `WEIGHING_TICKET_DOD_DUMP`.
- **WeighingTicketRBACMatrixTest** (§ 5.2) : admin/bureau/usine OK, compta/commerciale 403, anonyme 401.

> DSD / stub pont bascule / endpoint pesée déjà couverts (ERP-184/185).

### DoD
- `spec-back.md § 4.0.bis` : **JSON réel** (liste + détail) collé, 4 pièges marqués  — feu vert front.

### Vérifications
- `make test` complet **vert** : 848 tests, 6302 assertions (0 échec ; deprecations/notices PHPUnit seuls).
- `make php-cs-fixer-allow-risky` : 0 correction.

Empilée sur ERP-186 (stack M5).

---------

Co-authored-by: Matthieu <contact@malio.fr>
Reviewed-on: #137
2026-06-18 13:33:39 +00:00
gitea-actions b4e550b5de chore: bump version to v0.1.144
Auto Tag Develop / tag (push) Successful in 6s
Build & Push Docker Image / build (push) Successful in 20s
2026-06-18 12:51:24 +00:00
matthieu 10c113dbad Merge pull request 'feat(logistique) : export XLSX des tickets de pesée (ERP-186)' (#136) from feat/erp-186-export-xlsx-tickets-pesee into develop
Auto Tag Develop / tag (push) Successful in 8s
2026-06-18 12:47:16 +00:00
matthieu c0dadd79ff Merge pull request 'feat(logistique) : WeighingTicketProvider + Processor — numérotation, contrepartie, net, normalisation (ERP-185)' (#135) from feat/erp-185-provider-processor-weighingticket into develop
Auto Tag Develop / tag (push) Successful in 7s
2026-06-18 12:47:11 +00:00
matthieu 1ffa38282a Merge pull request 'feat(logistique) : pesée pont bascule stub + DSD + endpoint (ERP-184)' (#134) from feat/erp-184-pesee-pont-bascule into develop
Auto Tag Develop / tag (push) Successful in 6s
2026-06-18 12:47:06 +00:00
matthieu 036b075d5e Merge pull request 'feat(logistique) : entité WeighingTicket + dette site.code (ERP-183)' (#133) from feat/erp-183-entite-weighingticket into develop
Auto Tag Develop / tag (push) Successful in 7s
2026-06-18 12:47:04 +00:00
matthieu 25466b18d8 Merge pull request 'feat(logistique) : migration schéma M5 tickets de pesée (ERP-182)' (#132) from feat/erp-182-migration-m5 into develop
Auto Tag Develop / tag (push) Successful in 8s
2026-06-18 12:47:02 +00:00
matthieu 2fde5844e5 Merge pull request 'feat(logistique) : scaffold module + socle RBAC tickets de pesée (ERP-181)' (#131) from feat/erp-181-logistique-module into develop
Auto Tag Develop / tag (push) Successful in 8s
2026-06-18 12:46:58 +00:00
Matthieu 02a22597b3 feat(logistique) : export XLSX des tickets de pesée (ERP-186)
Endpoint GET /api/weighing_tickets/export.xlsx — controller custom (priority: 1)
calque sur les exports M2/M3/M4, delegue la generation au SpreadsheetExporter
partage. Rejoue la selection du WeighingTicketProvider (recherche ?search, tri
?order[displayDate], cloisonnement par site courant) SANS pagination : export
complet de la liste (§ 4.5).

Colonnes : Numero, Type contrepartie, Contrepartie (nom Client/Fournisseur/
Autre), Date, Immatriculation, Poids vide, Poids plein, Poids net, DSD vide,
DSD plein. Securite logistique.weighing_tickets.view.

Tests fonctionnels : 200 + en-tetes/Content-Disposition, mapping des colonnes
avec net = plein - vide (RG-5.05), cloisonnement par site (non-admin), 403, 401.
2026-06-18 14:37:16 +02:00
Matthieu 76e7a59ba7 feat(logistique) : WeighingTicketProvider + Processor — numérotation, contrepartie, net, normalisation (ERP-185)
Logique métier d'écriture et de lecture du ticket de pesée (M5).

Processor (POST/PATCH) :
- résolution du site courant (CurrentSiteProvider) + attribution du numéro
  {siteCode}-TP-{NNNN} à la création, immuables ensuite (RG-5.02 / RG-5.09) ;
- exclusivité de la contrepartie CLIENT/FOURNISSEUR/AUTRE — null-ification des
  champs hors-branche (RG-5.03, garde-fou CHECK Postgres) ;
- normalisation immatriculation trim/UPPER + masque XX-000-XX hors « Tout
  format », 422 inline sur le champ si invalide (RG-5.01 / RG-5.10) ;
- DSD autoritaire pour les pesées AUTO via DsdAllocator (verrou), MANUEL conservé
  (RG-5.04) ;
- poids net = plein − vide recalculé (RG-5.05).

Provider (GET) : liste paginée (Paginator ORM, règle n°13), recherche ?search=,
tri ?order[displayDate], cloisonnement par site courant appliqué dans le provider
(le SiteScopedQueryExtension ne traverse pas un provider custom), fetch-join
client/supplier/site anti-N+1, 404 hors périmètre / soft-delete.

Ajouts : WeighingTicketNumberAllocator (compteur weighing_ticket_counter,
SELECT FOR UPDATE), WeighingTicketFieldNormalizer, InvalidImmatriculationException
+ alias DI.

make test vert (811), Architecture vert (CollectionsArePaginatedTest).
2026-06-18 14:37:16 +02:00
Matthieu e88bb059e6 feat(logistique) : pesée pont bascule stub + allocateur DSD + endpoint (ERP-184)
- WeighbridgeReaderInterface (contrat) + RandomWeighbridgeReader (stub,
  poids aléatoire ∈ [10000,50000] kg, RG-5.06) + WeighbridgeUnavailableException
- DsdAllocator : compteur DSD par site (weighbridge_dsd_counter) incrémenté
  sous verrou ligne SELECT ... FOR UPDATE (RG-5.04, § 2.7)
- endpoint POST /api/weighbridge_readings : ressource virtuelle
  WeighbridgeReadingResource + WeighbridgeReadingProcessor (pas de controller)
  - AUTO -> {weight, dsd, mode} ; MANUAL -> {weight, dsd, manualNumber, mode}
  - WeighbridgeUnavailableException -> HTTP 503 explicite (RG-5.06)
  - site courant via CurrentSiteProviderInterface (contrat Sites)
  - is_granted('logistique.weighing_tickets.manage')
- dsd renvoyé prévisionnel : attribution autoritaire refaite à la création
  du ticket (ERP-185)
- tests : WeighbridgeReaderStubTest, DsdAllocatorTest, processor (503/400),
  WeighbridgeReadingApiTest (RBAC + AUTO/MANUAL + 422)
2026-06-18 14:37:16 +02:00
Matthieu 312c119c06 feat(logistique) : entité WeighingTicket + dette site.code (ERP-183)
Entité WeighingTicket
- Entité métier complète (#[Auditable], TimestampableBlamableTrait, relations
  ORM Client/Supplier/Site) + contrat de sérialisation à 3 maillons
  (weighing_ticket:read / :item:read + contextes par opération).
- Getters calculés displayDate et plateFreeFormat (#[SerializedName]),
  sécurité view/manage, pas de Delete/archive.
- Validation #[Assert\*] messages FR + #[Assert\Callback] RG-5.03 (->atPath()),
  libellé i18n audit.entity.logistique_weighingticket.
- Repository : interface Domain + DoctrineWeighingTicketRepository
  (recherche + tri number DESC, deletedAt IS NULL).

Dette site.code
- Site.code mappé VARCHAR(8) (groupes read/write), dérivation auto au
  PrePersist (2 premiers chiffres du CP), UniqueConstraint uq_site_code.
- Migration Version20260617160000 : ALTER COLUMN code SET NOT NULL + COMMENT.
- Fixtures (codes 86/17/82) et SiteApiTest ajustés.

Câblage
- doctrine.yaml : mapping ORM du module Logistique (absent du scaffold ERP-181).
- ColumnCommentsCatalog : site.code + table weighing_ticket.

Specs M5 versionnées (spec-back / spec-front / prompts).
2026-06-18 14:37:16 +02:00
Matthieu 8491f55072 feat(logistique) : migration schéma M5 tickets de pesée (ERP-182)
Crée le schéma BDD du module Logistique (M5) au namespace racine
DoctrineMigrations (FK cross-module user/client/supplier/site, règle n°11) :

- site.code VARCHAR(8) (préfixe de numérotation {siteCode}-TP, RG-5.02) +
  backfill depuis le code postal + index unique uq_site_code. Colonne NULLABLE
  à ce ticket (l'entité Site ne mappe pas encore code) ; mapping ORM,
  peuplement et SET NOT NULL portés par le ticket entité.
- weighing_ticket_counter / weighbridge_dsd_counter : compteurs par site
  (numéro RG-5.02 / DSD pont RG-5.04), gérés en DBAL brut FOR UPDATE, hors ORM
  → exclus du schema_filter (sinon schema:update les droppe) + catalogués.
- weighing_ticket : table principale (contrepartie Client/Fournisseur/Autre
  avec CHECK 3 branches RG-5.03, immatriculation partagée, pesées vide/plein
  en colonnes plates, net_weight dérivé, soft-delete + Timestampable/Blamable).
  Index unique (site_id, number) + index FK. ON DELETE site/client/supplier =
  RESTRICT, created_by/updated_by = SET NULL.

COMMENT ON COLUMN sur chaque colonne créée (règle n°12). make test +
ColumnsHaveSqlCommentTest verts, db-reset OK.
2026-06-18 14:36:05 +02:00
Matthieu c63a5f971f feat(logistique) : scaffold module + socle RBAC tickets de pesée (ERP-181)
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Successful in 3m12s
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Successful in 1m44s
Nouveau module Logistique (M5), sans entité ni migration (ticket 1.2) :
- LogistiqueModule (ID logistique, permissions weighing_tickets.view/manage)
  enregistré dans config/modules.php
- layer front frontend/modules/logistique (auto-détecté)
- sidebar : section Logistique + item /weighing-tickets (gate ...view)
  + clés i18n sidebar.logistique.*
- 3 miroirs RBAC alignés : sidebar.php, personas.ts (user-full),
  SeedE2ECommand (user-full)
- matrice métier RbacSeeder : Bureau + Usine = view/manage ;
  Compta + Commerciale = aucun accès (spec § 5.2)
2026-06-18 14:36:05 +02:00
gitea-actions 5f2aa5334b chore: bump version to v0.1.138
Auto Tag Develop / tag (push) Successful in 7s
Build & Push Docker Image / build (push) Successful in 50s
2026-06-18 08:51:36 +00:00
tristan 21b1c64a5f Merge pull request 'feat(transport) : upload décharge + i18n transporteur (ERP-171)' (#130) from feat/erp-171-carrier-upload-i18n into develop
Auto Tag Develop / tag (push) Successful in 9s
2026-06-18 08:50:13 +00:00
tristan fd89160c4b Merge pull request 'feat(transport) : consultation + modification transporteur (ERP-170)' (#129) from feat/erp-170-carrier-view-edit into develop
Auto Tag Develop / tag (push) Successful in 7s
2026-06-18 08:50:07 +00:00
tristan 8daf0ff5d4 Merge pull request 'feat(transport) : onglet prix transporteur (ERP-169)' (#128) from feat/erp-169-carrier-prices into develop
Auto Tag Develop / tag (push) Successful in 9s
2026-06-18 08:49:57 +00:00
tristan d304b74289 refactor(transport) : supprime les reliquats multi-adresses — colonne position, dead code front, docblocks 1:n (ERP-172)
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Successful in 3m20s
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Successful in 1m39s
2026-06-18 10:38:25 +02:00
tristan 80b3741f64 style(transport) : tableau prix consultation — colonne « Type de transport » à 170px (ERP-172)
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Successful in 3m3s
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Successful in 1m32s
2026-06-17 17:58:06 +02:00
tristan c468374b16 style(transport) : tableau prix consultation — « Type de transport » (colonne élargie, en-tête centré) (ERP-172)
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Has been cancelled
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Has been cancelled
2026-06-17 17:57:26 +02:00
tristan 7ddf495d7f style(transport) : tableau prix consultation — code du site (département) + en-têtes Forfait/Tonne (€) (ERP-172)
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Successful in 3m15s
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Successful in 1m31s
2026-06-17 17:46:58 +02:00
tristan 9fcf5c24f6 feat(transport) : retour au répertoire après validation du dernier onglet (création) (ERP-172)
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Has been cancelled
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Has been cancelled
2026-06-17 17:44:34 +02:00
tristan 76fb01c063 feat(transport) : modif — onglet Qualimat (actualisation) + certification éditable (déliage Qualimat) (ERP-172)
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Successful in 3m14s
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Has been cancelled
2026-06-17 17:40:05 +02:00
tristan e76bd1dd63 feat(transport) : adresse unique par transporteur (OneToOne back + un seul bloc front) (ERP-172) 2026-06-17 17:32:29 +02:00
tristan 498cef8cc0 fix(transport) : embarque le nom de la décharge dans le détail carrier (consultation/modif) (ERP-171)
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Successful in 3m15s
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Successful in 1m50s
2026-06-17 16:08:08 +02:00
tristan 7668d77c78 fix(transport) : upload décharge différé à l'enregistrement/validation (évite les orphelins) (ERP-171) 2026-06-17 16:08:08 +02:00
tristan 1d5110d000 feat(transport) : upload décharge (useUpload) + câblage MalioInputUpload + i18n erreur (ERP-171) 2026-06-17 16:08:08 +02:00
tristan b6b5bb06e8 fix(transport) : affiche le message 409 (homonyme) à la restauration + virgule décimale dans sanitizeDecimal (ERP-170)
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Successful in 3m7s
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Successful in 1m41s
2026-06-17 16:08:02 +02:00
tristan fb9c15c52a fix(transport) : pré-validation front du bloc prix — erreurs inline sous tous les champs requis (selects branche) (ERP-169)
Pull Request — Quality gate / Backend (PHP CS + PHPUnit) (pull_request) Successful in 3m4s
Pull Request — Quality gate / Frontend (lint + Vitest + build) (pull_request) Successful in 1m34s
2026-06-17 16:08:02 +02:00
tristan c371057c0b style(transport) : tableau prix — réduit Adresse sites au profit d'Adresse livraisons (ERP-170) 2026-06-17 16:08:02 +02:00
tristan e1712465f1 fix(transport) : bloc prix — radios sens/contenant/tarif horizontaux et centrés (h-12) en colonne 1 (ERP-169) 2026-06-17 16:08:02 +02:00
tristan 5125883e21 fix(transport) : tableau prix — corrige l'inversion Adresse sites / Adresse livraisons (ERP-170) 2026-06-17 16:08:02 +02:00
tristan 6ff5b13ce2 fix(transport) : bloc prix par défaut (CLIENT), sens seul en ligne 1, payload omet scalaires vides (422 inline au lieu de 400) (ERP-169) 2026-06-17 16:08:02 +02:00
tristan 5bbd4ddb47 style(transport) : tableau prix — libellés colonnes + élargit Transporteurs/Adresse livraisons, réduit Forfait/Tonne/Indexation/État (ERP-170) 2026-06-17 16:08:02 +02:00
tristan a26bb09ee1 fix(transport) : bloc prix — radios sans label de groupe, sens en colonne 1, défaut Benne/Forfait (ERP-169) 2026-06-17 16:08:02 +02:00
tristan 20296ac149 style(transport) : datatable qualimat table-fixed (radio étroit, colonnes égales) + icônes onglets prix/qualimat (ERP-170) 2026-06-17 16:08:02 +02:00
tristan 07e0bcbcce feat(transport) : onglet prix transporteur (ERP-169) 2026-06-17 16:08:02 +02:00
tristan fe1d012548 style(transport) : tableau prix consultation en table-fixed (colonnes à parts égales, contenant étroit) (ERP-170) 2026-06-17 16:08:02 +02:00
tristan d86dc69cf2 feat(transport) : consultation — contenant en radios lecture seule (aligné ajout/modif) (ERP-170) 2026-06-17 16:08:02 +02:00
tristan 07ed57f283 feat(transport) : contenant du formulaire principal en radios centrés (Benne par défaut) (ERP-170) 2026-06-17 16:08:02 +02:00
tristan b5749520bc fix(transport) : consultation — disposition du bloc principal alignée sur l'ajout (LIOT, décharge col 3, affréter col 4) (ERP-170) 2026-06-17 16:08:02 +02:00
tristan 02d2fde653 fix(transport) : indexation réellement plafonnée à 100 % — re-synchronise le champ amount contrôlé via :key (ERP-170) 2026-06-17 16:08:02 +02:00
tristan 0d284fe488 fix(transport) : volume m³ en champ texte décimal + indexation en montant % plafonné à 100 (ERP-170) 2026-06-17 16:08:02 +02:00
tristan 48ca963a9d fix(transport) : tableau prix — en-tête « Contenant » sur la colonne de groupe (ERP-170) 2026-06-17 16:08:02 +02:00
tristan b11968f5e5 fix(transport) : tableau prix — supprime la double bordure du bas + séparateur épais entre groupes Benne/Fond mouvant (ERP-170) 2026-06-17 16:08:02 +02:00
tristan 5109b5f57a fix(transport) : tableau prix consultation — police/bordures/radius alignés MalioDataTable, colonne groupe en épine (ERP-170) 2026-06-17 16:08:02 +02:00
tristan d5a01ac85f fix(transport) : name de radio unique par bloc prix (useId) — plus de groupe partagé entre blocs (ERP-170) 2026-06-17 16:08:02 +02:00
tristan 7adf3a511a fix(transport) : tableau prix consultation — cellule de groupe fusionnée (Fond Mouvant/Benne) + colonnes maquette (ERP-170) 2026-06-17 16:08:02 +02:00
tristan e612eae391 feat(transport) : consultation + modification transporteur (ERP-170) 2026-06-17 16:08:02 +02:00
147 changed files with 10805 additions and 950 deletions
+2
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
use App\Module\Catalog\CatalogModule;
use App\Module\Commercial\CommercialModule;
use App\Module\Core\CoreModule;
use App\Module\Logistique\LogistiqueModule;
use App\Module\Sites\SitesModule;
use App\Module\Technique\TechniqueModule;
use App\Module\Transport\TransportModule;
@@ -15,4 +16,5 @@ return [
CatalogModule::class,
TechniqueModule::class,
TransportModule::class,
LogistiqueModule::class,
];
+18 -2
View File
@@ -24,13 +24,18 @@ doctrine:
# is_active, TIMESTAMP(6)) -> schema:update reste un no-op.
# - `idtf_product` / `idtf_sync_log` : referentiel codes IDTF
# synchronise en DBAL brut par `app:idtf:sync`, hors ORM.
# - `weighing_ticket_counter` / `weighbridge_dsd_counter` : compteurs
# par site (numero de ticket de pesee RG-5.02 / DSD du pont RG-5.04,
# M5 Logistique), incrementes en DBAL brut sous verrou `FOR UPDATE`
# par l'allocateur — jamais mappes en ORM (cf. spec M5 § 2.5 / § 2.7).
# Sans ce filtre, schema:update les considere comme "orphelines" et
# genere un `DROP TABLE` qui casse la base de test apres chaque
# `make test-db-setup` (la migration les a creees, schema:update les
# supprime juste apres). Creation / suppression restent pilotees par
# les migrations (audit_log : Version20260420202749 ; qualimat :
# Version20260612150000 ; idtf : Version20260612160000).
schema_filter: '~^(?!(?:audit_log|qualimat_sync_log|idtf_product|idtf_sync_log)$).+~'
# Version20260612150000 ; idtf : Version20260612160000 ; compteurs M5 :
# Version20260617150000).
schema_filter: '~^(?!(?:audit_log|qualimat_sync_log|idtf_product|idtf_sync_log|weighing_ticket_counter|weighbridge_dsd_counter)$).+~'
audit:
url: '%env(resolve:DATABASE_URL)%'
orm:
@@ -133,6 +138,17 @@ doctrine:
dir: '%kernel.project_dir%/src/Module/Transport/Domain/Entity'
prefix: 'App\Module\Transport\Domain\Entity'
alias: Transport
# Mapping inconditionnel du module Logistique (meme logique que Transport) :
# la table weighing_ticket (tickets de pesee M5) creee par la migration
# Version20260617150000 doit etre connue de l'ORM, sinon schema:update la
# drope sur la base de test. L'activation fonctionnelle passe par
# config/modules.php.
Logistique:
type: attribute
is_bundle: false
dir: '%kernel.project_dir%/src/Module/Logistique/Domain/Entity'
prefix: 'App\Module\Logistique\Domain\Entity'
alias: Logistique
controller_resolver:
auto_mapping: false
+11
View File
@@ -33,3 +33,14 @@ services:
App\Module\Sites\Application\Service\CurrentSiteProviderInterface:
alias: App\Module\Sites\Application\Service\CurrentSiteProvider
# M5 Logistique — pesee pont bascule (ERP-184)
App\Module\Logistique\Domain\Contract\WeighbridgeReaderInterface:
alias: App\Module\Logistique\Infrastructure\Weighbridge\RandomWeighbridgeReader
App\Module\Logistique\Application\Service\DsdAllocatorInterface:
alias: App\Module\Logistique\Infrastructure\Service\DsdAllocator
# M5 Logistique — Provider/Processor ticket de pesee (ERP-185)
App\Module\Logistique\Application\Service\WeighingTicketNumberAllocatorInterface:
alias: App\Module\Logistique\Infrastructure\Service\WeighingTicketNumberAllocator
+19
View File
@@ -78,6 +78,25 @@ return [
],
],
],
// Section "Logistique" (M5, ERP-181) : nouveau pole "operations physiques sur
// site", distinct du repertoire Transport (M4, desormais rattache a la section
// Administration cote develop). Porte le ticket de pesee au pont bascule.
// L'item est gate par `logistique.weighing_tickets.view` ; la section disparait
// automatiquement (SidebarProvider) si le module `logistique` est desactive ou
// si l'user n'a pas la permission (Compta / Commerciale).
[
'label' => 'sidebar.logistique.section',
'icon' => 'mdi:scale',
'items' => [
[
'label' => 'sidebar.logistique.weighing_tickets',
'to' => '/weighing-tickets',
'icon' => 'mdi:scale',
'module' => 'logistique',
'permission' => 'logistique.weighing_tickets.view',
],
],
],
// Section "Administration" : regroupe toutes les pages de configuration
// applicative (RBAC, users, sites, audit log).
//
+1 -1
View File
@@ -1,2 +1,2 @@
parameters:
app.version: '0.1.131'
app.version: '0.1.146'
@@ -0,0 +1,38 @@
# Prompt d'implémentation — M5 · ERP-181 (1.1) — Scaffolder le module Logistique + RBAC
Projet **Starseed** (modular monolith DDD). Tâche **back**. Lis d'abord `CLAUDE.md` + `.claude/rules/architecture.md` + `.claude/rules/backend.md`, puis la spec : `docs/specs/M5-tickets-pesee/spec-back.md` (§ 2.1, § 5).
## Mission
Créer le **nouveau module `Logistique`** et poser son socle RBAC, **avant toute entité**. Aucun écran fonctionnel ici, juste le squelette + permissions + sidebar + 3 miroirs RBAC.
## Étapes
1. Scaffolder via le skill projet **`create-module`** : `src/Module/Logistique/` avec `Domain/ Application/ Infrastructure/` et `LogistiqueModule.php` :
- `const string ID = 'logistique'` ; `const string LABEL = 'Logistique'` ; `const bool REQUIRED = false`.
- `permissions()` retourne :
- `['code' => 'logistique.weighing_tickets.view', 'label' => 'Voir les tickets de pesée']`
- `['code' => 'logistique.weighing_tickets.manage', 'label' => 'Créer / modifier les tickets de pesée']`
2. Enregistrer `LogistiqueModule::class` dans `config/modules.php`.
3. Créer le layer front minimal `frontend/modules/logistique/nuxt.config.ts` (kebab-case, auto-détecté).
4. Ajouter à `config/sidebar.php` une section/item « Logistique » :
```php
['label' => 'sidebar.logistique.weighing_tickets', 'to' => '/weighing-tickets',
'icon' => 'mdi-scale', 'module' => 'logistique', 'permission' => 'logistique.weighing_tickets.view'],
```
+ la clé i18n `sidebar.logistique.*` dans `frontend/i18n/locales/fr.json`.
5. **Règle ABSOLUE n°8 — 3 miroirs RBAC alignés ensemble** :
- `config/sidebar.php` (item + permission ci-dessus),
- `frontend/tests/e2e/_fixtures/personas.ts` (persona **Usine** gagne `weighing_tickets.view` + `manage` et `expectedAdminLinks` ; **Compta/Commerciale** : aucun accès),
- `src/Module/Core/Infrastructure/Console/SeedE2ECommand.php` (miroir back du même persona).
6. `make shell` → `php bin/console app:sync-permissions`.
## Garde-fous (règles ABSOLUES)
- `declare(strict_types=1);` partout ; commentaires **en français**, code en anglais.
- Permission au format `module.resource.action` snake_case.
- Ne PAS créer d'entité ni de migration ici (ticket 1.2).
- Pas de hardcode sidebar côté front : elle vient de `/api/sidebar`.
## Vérification
- `make test` (les tests Architecture ne cassent pas).
- `make php-cs-fixer-allow-risky`.
- `GET /api/modules` retourne `logistique` ; `GET /api/sidebar` : item présent pour Admin/Bureau/Usine, **absent** pour Compta/Commerciale.
- Les 3 miroirs RBAC sont cohérents (sinon test E2E faux positif).
@@ -0,0 +1,28 @@
# Prompt d'implémentation — M5 · ERP-182 (1.2) — Migrer le schéma M5
Projet **Starseed**. Tâche **back / migration**. Lis `CLAUDE.md` (règles n°11 et n°12), `.claude/rules/backend.md` (§ Migrations) et la spec : `docs/specs/M5-tickets-pesee/spec-back.md` (§ 3.2, § 3.2.bis, § 2.5, § 2.7).
## Mission
Écrire **une** migration Doctrine au namespace racine `DoctrineMigrations` (`migrations/VersionYYYYMMDDHHMMSS.php`, postérieure aux existantes) qui crée tout le schéma M5.
## Étapes
1. **`site.code`** : `ALTER TABLE site ADD COLUMN code VARCHAR(8)` **NULLABLE** → backfill `UPDATE site SET code = LEFT(postal_code, 2) WHERE code IS NULL` → index unique `uq_site_code` (tolère les NULL multiples Postgres).
-**NE PAS poser `SET NOT NULL` ici.** Sur `make db-reset`, les fixtures `SitesFixtures` insèrent des sites via l'ORM, qui ne connaît `code` que si la propriété est mappée sur l'entité `Site.php` (fait en ERP-183) → sinon `INSERT` sans `code` → violation `NOT NULL` → db-reset plante. Le `NOT NULL` est posé en **ERP-183** (2ᵉ migration) une fois `Site::code` mappé + peuplé. Cf. spec § 2.5.
2. Table **`weighing_ticket_counter (site_id PK → site, last_value INT NOT NULL DEFAULT 0)`** (séquence numéro par site, RG-5.02).
3. Table **`weighbridge_dsd_counter (site_id PK → site, last_value INT NOT NULL DEFAULT 0)`** (compteur DSD par site, RG-5.04).
4. Table **`weighing_ticket`** : copier le DDL de la spec § 3.2 (colonnes `site_id`, `number`, contrepartie `counterparty_type`/`client_id`/`supplier_id`/`other_label`, `immatriculation`/`plate_free_format`, `empty_*`, `full_*`, `net_weight`, `deleted_at` + 4 colonnes Timestampable/Blamable).
- Convention `INT GENERATED BY DEFAULT AS IDENTITY`, `TIMESTAMP(0) WITHOUT TIME ZONE` (§ 2.2).
- CHECK : `counterparty_type`, `empty_mode`/`full_mode`, et les **3 branches contrepartie** (RG-5.03).
- Index unique `(site_id, number)` + index FK (`site`, `client`, `supplier`, `deleted_at`, `created_by`, `updated_by`).
5. **Règle ABSOLUE n°12** : `COMMENT ON COLUMN` (FR, ≤ 200 car., sémantique + RG) sur **chaque** colonne créée — cf. échantillon § 3.2.bis. Les 4 colonnes Timestampable/Blamable via `addStandardTimestampableBlamableComments($schema, 'weighing_ticket')`. Bonus `COMMENT ON TABLE`.
6. Écrire `down()` symétrique (drop tables + drop colonne `site.code`).
## Garde-fous
- Noms de colonnes **en minuscules** (Postgres).
- FK cross-module (`user`, `client`, `supplier`, `site`) → la migration **doit** vivre au namespace racine (règle n°11), sinon `make db-reset` casse l'ordre.
- `ON DELETE` : `site` = RESTRICT, `client`/`supplier` = RESTRICT, `created_by`/`updated_by` = SET NULL, compteurs = CASCADE.
## Vérification
- `make db-reset` puis `make migration-migrate` (BDD fraîche) → OK.
- `make test` : `ColumnsHaveSqlCommentTest` **vert** (aucune colonne `public` sans `col_description`).
- `make php-cs-fixer-allow-risky`.
@@ -0,0 +1,40 @@
# Prompt d'implémentation — M5 · ERP-183 (1.3) — Entité WeighingTicket + repository + contrat sérialisation
Projet **Starseed**. Tâche **back**. Lis `CLAUDE.md`, `.claude/rules/backend.md` (Audit, Timestampable/Blamable, Serialization) et la spec : `docs/specs/M5-tickets-pesee/spec-back.md` (§ 3.3, § 4.0, § 2.11). Prérequis : ERP-182 mergé.
## Mission
Créer l'entité Doctrine **`WeighingTicket`** + son `#[ApiResource]` (Get / GetCollection / Post / Patch) + le repository, avec le **contrat de sérialisation posé une seule fois** (read-groups sur chaque propriété affichée — RETEX M1→M4).
## ⚠ Finaliser `site.code` (dette laissée par ERP-182 — à faire EN PREMIER)
ERP-182 a créé `site.code` **nullable** (sinon `db-reset` cassait). Ici on le rend obligatoire, maintenant que l'ORM peut le remplir :
1. Mapper la propriété `code` sur l'entité `src/Module/Sites/Domain/Entity/Site.php` (colonne + getter/setter + groupes de sérialisation cohérents avec les autres champs `site:*`).
2. Peupler `code` (86 / 17 / 82) dans `SitesFixtures` **et** dans `SeedE2ECommand.php` (sites seedés).
3. Ajuster les tests Sites en collision d'unicité : ex. `SiteApiTest` qui crée un site CP `86000``code` 86 entre en collision avec la fixture Châtellerault (86) → adapter le CP/code du test.
4. **2ᵉ petite migration** (namespace racine) : `ALTER TABLE site ALTER COLUMN code SET NOT NULL;` (+ `COMMENT ON COLUMN` si pas déjà posé).
5. `make db-reset` + `make test` doivent rester verts.
## Étapes — WeighingTicket
1. `src/Module/Logistique/Domain/Entity/WeighingTicket.php` (squelette spec § 3.3) :
- `#[Auditable]`, `use TimestampableBlamableTrait`, `implements TimestampableInterface, BlamableInterface`.
- Relations ORM **partagées** (PAS d'import de logique) : `Client` (M1), `Supplier` (M2), `Site` (Sites) en ManyToOne.
- Propriétés : `number`, `site`, `counterpartyType`, `client`, `supplier`, `otherLabel`, `immatriculation`, `plateFreeFormat`, `empty*` (date/weight/dsd/mode/manualNumber), `full*` (idem), `netWeight`.
2. **Read-groups (3 maillons § 4.0)** :
- `weighing_ticket:read` = champs liste (`number`, `counterpartyType`, `client`, `supplier`, `otherLabel`, `displayDate`, `netWeight`, `plateFreeFormat`, timestamps).
- `weighing_ticket:item:read` = détail (`empty*`, `full*`, `site`, `immatriculation`).
- Contextes des opérations exactement comme § 3.3 (inclure `client:read`, `supplier:read`, `site:read`, `default:read`).
3. Getter calculé **`displayDate`** (= `fullDate ?? emptyDate`) annoté `weighing_ticket:read`.
4. Booléen **`plateFreeFormat`** : exposer via getter + `#[SerializedName('plateFreeFormat')]` (piège #3 M1 — la clé doit sortir dans le JSON).
5. Sécurité opérations : GET = `is_granted('logistique.weighing_tickets.view')` ; POST/PATCH = `...manage`. **Pas de Delete, pas d'archive.** Provider/Processor référencés (implémentés en ERP-184/185).
6. Contraintes `#[Assert\*]` avec **messages FR** ; `Assert\Length.max` aligné sur les colonnes ORM.
7. **Libellé i18n audit** : `audit.entity.logistique_weighingticket` dans `frontend/i18n/locales/fr.json`.
8. `src/Module/Logistique/Infrastructure/Doctrine/DoctrineWeighingTicketRepository.php`.
## Garde-fous
- `declare(strict_types=1);` ; commentaires FR.
- Ne JAMAIS importer une classe d'un autre **module** pour de la logique — seules les entités de référence (Client/Supplier/Site) sont consommées en relation ORM (toléré M1→M4).
- Pagination gérée par le Provider (ERP-185) — ne pas désactiver la pagination.
## Vérification
- `make test` : `EntitiesAreTimestampableBlamableTest`, `AuditableEntitiesHaveI18nLabelTest`, `EntityConstraintsHaveFrenchMessageTest` **verts**.
- `make php-cs-fixer-allow-risky`.
- (La capture JSON réelle du contrat est faite en ERP-187.)
@@ -0,0 +1,33 @@
# Prompt d'implémentation — M5 · ERP-184 (1.4) — Pesée pont bascule (stub + DSD + endpoint)
Projet **Starseed**. Tâche **back**. Lis `CLAUDE.md`, `.claude/rules/backend.md` et la spec : `docs/specs/M5-tickets-pesee/spec-back.md` (§ 2.6, § 2.7, § 4.2). Prérequis : ERP-182.
## Mission
Implémenter la pesée déclenchée par les boutons « Pesée bascule » / « Pesée manuelle » : **stub** (pas de liaison matérielle au M5) + allocateur DSD + endpoint API.
## Étapes
1. Contrat `Logistique\Domain\Contract\WeighbridgeReaderInterface` :
```php
public function read(SiteInterface $site): WeighbridgeReading; // {weight:int kg, dsd:int}
```
+ `WeighbridgeUnavailableException`.
2. Impl `Logistique\Infrastructure\Weighbridge\RandomWeighbridgeReader` : `weight = random_int(10000, 50000)` (RG-5.06), `dsd = DsdAllocator::next($site)`.
3. `DsdAllocator` (service) : compteur DSD **par site** sur `weighbridge_dsd_counter`, incrément avec **verrou ligne `SELECT ... FOR UPDATE`** dans une transaction.
- AUTO : incrémente et renvoie la nouvelle valeur.
- MANUAL : `dsd = dernier dsd du site + 1` (RG-5.04).
4. Endpoint **`POST /api/weighbridge_readings`** — ressource virtuelle (DTO `WeighbridgeReadingInput`/`Output`) + Processor dédié, **pas de controller Symfony** :
- `{ "mode": "AUTO" }` → `{ weight, dsd, mode }` (site courant via `CurrentSiteProviderInterface`).
- `{ "mode": "MANUAL", "weight": <int>, "manualNumber": "<str>" }` → `{ weight, dsd, manualNumber, mode }`.
- Erreur `WeighbridgeUnavailableException` → **HTTP 503** explicite « Pont bascule indisponible — passez en pesée manuelle » (RG-5.06).
- Sécurité `is_granted('logistique.weighing_tickets.manage')`.
5. Le `dsd` renvoyé est **prévisionnel** : noter en commentaire que l'attribution autoritaire est refaite à la création du ticket (ERP-185).
## Garde-fous
- `declare(strict_types=1);` ; commentaires FR.
- Consommer `CurrentSiteProviderInterface` (contrat Sites) — pas d'import de logique d'un autre module.
- Pas de controller sous `/api` (API Platform).
## Vérification
- `make test` : `WeighbridgeReaderStubTest` (poids ∈ [10000,50000] + chemin erreur → 503), `DsdAllocatorTest` (AUTO incrémente / MANUAL = dernier+1 / par site).
- `make php-cs-fixer-allow-risky`.
- Appel manuel `POST /api/weighbridge_readings {AUTO}` (token Usine) → poids + dsd cohérents.
@@ -0,0 +1,31 @@
# Prompt d'implémentation — M5 · ERP-185 (1.5) — Provider + Processor WeighingTicket
Projet **Starseed**. Tâche **back**. Lis `CLAUDE.md`, `.claude/rules/backend.md` (Pagination, RBAC, Validation) et la spec : `docs/specs/M5-tickets-pesee/spec-back.md` (§ 4.3, § 4.4, § 2.5, § 2.9, § 2.8, § 6, § 2.3). Prérequis : ERP-183, ERP-184.
## Mission
Implémenter la logique métier d'écriture (Processor) et de lecture (Provider) du ticket de pesée.
## Étapes — `WeighingTicketProcessor` (POST/PATCH)
1. **Site courant** : résoudre via `CurrentSiteProviderInterface``site_id` (à la création).
2. **Numéro `{siteCode}-TP-{NNNN}`** (RG-5.02) : à la création, incrémenter `weighing_ticket_counter` du site avec **`SELECT ... FOR UPDATE`**, formater `%04d`. Numéro **immuable** au PATCH (RG-5.09).
3. **DSD autoritaire** : (ré)attribuer `empty_dsd`/`full_dsd` via `DsdAllocator` (verrou) si pesée AUTO (RG-5.04).
4. **RG-5.03** (contrepartie) : `#[Assert\Callback]` sur l'entité → selon `counterpartyType`, exiger `client` / `supplier` / `otherLabel` et forcer les autres à `null` (messages FR, `->atPath()` sur le bon champ).
5. **RG-5.05** : `net_weight = full_weight - empty_weight` (plein vide) si les 2 poids présents, sinon `null`.
6. **RG-5.01 / RG-5.10** : `WeighingTicketFieldNormalizer` (service appelé avant validation) — `immatriculation` trim+UPPER ; si `!plateFreeFormat` reformate `XX-000-XX` et **rejette en 422** si invalide ; `otherLabel` trim.
7. `site` immuable au PATCH (RG-5.09).
## Étapes — `WeighingTicketProvider` (GET)
8. Liste **paginée** via `ApiPlatform\Doctrine\Orm\Paginator` (jamais d'array brut — règle n°13).
9. **Cloisonnement par site courant** (§ 2.3) : appliquer le `SiteScopedQueryExtension` existant (ou filtrer sur le site courant).
10. Query params : `?search=` (sur `number`, nom client/fournisseur, `other_label`, `immatriculation`), tri `displayDate` (défaut `number DESC`).
11. Anti-N+1 : fetch-join `client`/`supplier`/`site` (ManyToOne sûrs).
## Garde-fous
- `declare(strict_types=1);` ; commentaires FR ; messages de validation **FR**.
- Toutes les violations 422 portent un `propertyPath` aligné sur les noms de champs (consommé par le front `useFormErrors`).
- Pas de controller ; pas de `paginationEnabled: false`.
## Vérification
- `make test` (les tests dédiés sont écrits en ERP-187) : au minimum `CollectionsArePaginatedTest` **vert**.
- `make php-cs-fixer-allow-risky`.
- Smoke manuel : `POST /api/weighing_tickets` (Usine) → numéro `86-TP-0001` attribué, `net_weight` calculé ; second POST même site → `86-TP-0002`.
@@ -0,0 +1,23 @@
# Prompt d'implémentation — M5 · ERP-186 (1.6) — Export XLSX des tickets de pesée
Projet **Starseed**. Tâche **back**. Lis `CLAUDE.md`, `.claude/rules/backend.md` et la spec : `docs/specs/M5-tickets-pesee/spec-back.md` (§ 4.5). Prérequis : ERP-185.
## Mission
Endpoint d'export XLSX de **toute la liste** des tickets de pesée (bouton « Exporter »).
## Étapes
1. Endpoint **`GET /api/weighing_tickets/export.xlsx`** : opération API Platform dédiée avec provider renvoyant un binaire (`Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`, `Content-Disposition: attachment`).
2. Respecter le **site courant** + les filtres actifs (mêmes critères que la liste, mais **sans pagination** → export complet).
3. Colonnes : Numéro, Contrepartie (type + nom Client/Fournisseur/Autre), Date, Immatriculation, Poids vide, Poids plein, **Poids net**, DSD vide, DSD plein.
4. Sécurité `is_granted('logistique.weighing_tickets.view')`.
5. Whitelister cette opération dans `CollectionsArePaginatedTest::EXCLUDED` (export complet légitime).
## Garde-fous
- `declare(strict_types=1);` ; commentaires FR.
- Utiliser le helper XLSX standard du projet (cf. exports M1→M4) — ne pas réinventer.
- Pas de controller custom sous `/api` sans `priority: 1` (préférer une opération API Platform).
## Vérification
- `make test` : test de l'export (colonnes + filtrage site) + `CollectionsArePaginatedTest` vert.
- `make php-cs-fixer-allow-risky`.
- Téléchargement manuel → fichier ouvrable, colonnes correctes, poids net = plein vide.
@@ -0,0 +1,31 @@
# Prompt d'implémentation — M5 · ERP-187 (1.7) — Tests PHPUnit RG-5.01→5.10 + capture contrat JSON
Projet **Starseed**. Tâche **back / tests**. Lis `CLAUDE.md`, `.claude/rules/testing.md` et la spec : `docs/specs/M5-tickets-pesee/spec-back.md` (§ 8, § 4.0.bis). Prérequis : ERP-183 → ERP-186 mergés.
## Mission
Couvrir les RG du M5 par des tests PHPUnit et **capturer la réponse JSON réelle** (DoD) à coller dans la spec avant le démarrage front.
## Étapes
1. **`WeighingTicketSerializationContractTest`** : seeder un ticket complet (contrepartie Client, pesée vide + plein), capturer le JSON **liste** + **détail** (via une variable d'env de dump, cf. pattern M4 `CARRIER_DOD_DUMP`). Vérifier les **4 pièges** :
- `client` / `supplier` sortent en **objet embarqué**, pas en IRI nu ;
- `plateFreeFormat` présent dans le JSON ;
- `number` présent et formaté `{siteCode}-TP-{NNNN}` ;
- `netWeight` = `full - empty` (plein vide).
**Coller le JSON capturé dans `spec-back.md § 4.0.bis`** (feu vert front).
2. `WeighingTicketNumberingTest` : numéro par site, unicité, concurrence (`FOR UPDATE`), immuabilité au PATCH.
3. `DsdAllocatorTest` : AUTO incrémente / MANUAL = dernier+1 / compteur par site.
4. `WeighbridgeReaderStubTest` : poids ∈ [10000,50000] ; `WeighbridgeUnavailableException` → 503 (RG-5.06).
5. `NetWeightTest` : plein vide ; `null` si une pesée manque (RG-5.05).
6. `CounterpartyValidationTest` : RG-5.03 (chaque branche valide + rejets des incohérences).
7. `ImmatriculationNormalizationTest` : masque `XX-000-XX`, `plateFreeFormat`, 422 si invalide (RG-5.01).
8. **RBAC** : Admin/Bureau/Usine OK ; Compta/Commerciale → 403 ; anonyme → 401.
## Garde-fous
- `declare(strict_types=1);` ; fixtures dédiées sous `tests/Fixtures/`.
- **Pas de test E2E** (règle d'or) — PHPUnit uniquement.
- Ne pas casser les tests Architecture existants.
## Vérification
- `make test` **vert** (suite complète, dont Architecture).
- `spec-back.md § 4.0.bis` contient le JSON RÉEL avec les 4 pièges marqués verts.
- `make php-cs-fixer-allow-risky`.
+790
View File
@@ -0,0 +1,790 @@
---
# === IDENTITÉ ===
module: M5
nom: "Tickets de pesée"
ecran: tickets-pesee
owner_spec: Matthieu
backup_spec: Tristan
version: V0.1
date_redaction: 2026-06-17
# Historique :
# V0.1 (2026-06-17) — Spec back initiale. Restitution + précisions back du docx fonctionnel
# « M5-ticket-de-pesee-V02 » (V0.2, 15/06/2026, validation client en attente).
# Décisions Matthieu (17/06) :
# (1) NOUVEAU module `Logistique` (pas une greffe sur Transport).
# (2) Pont bascule = PAS de liaison matérielle au M5 → stub renvoyant un poids
# aléatoire ∈ [10000, 50000] kg. Driver réel = hors périmètre (ticket dédié).
# (3) DSD = compteur de pesée du pont (en manuel : dernier dsd + 1).
# (4) Poids net (non précisé par le docx) = poids plein poids vide, calculé serveur
# (CONFIRMÉ Matthieu 17/06 — § 2.8 / RG-5.05).
# Maquette Figma (node 1322-16774, board « Module 5 : Ticket de pesée ») intégrée le 17/06 :
# les DEUX blocs (vide + plein) portent « Pesée bascule » + « Pesée manuelle » ;
# DSD séquentiel +1 par pesée (16619 → 16620) ; contrepartie portée par le bloc vide.
# === LIENS ===
spec_front: ./spec-front.md
maquette_figma: "https://www.figma.com/design/jRYgT0T9c03VsEbjGhCwwS/Composants---Design-System?node-id=1322-16774&p=f&m=dev"
trace_fonctionnelle: "uploads/M5-ticket-de-pesee-V02.pdf (V0.2, 15/06/2026, validation client en attente)"
# === LIEN LESSTIME ===
lesstime_project_id: 6
lesstime_taskgroup_id: 33 # M5 — Tickets de pesée (ERP-181 → ERP-192)
statut_global: pret_a_dev
# === DÉPENDANCES AMONT ===
depend_de:
- Sites # SitesModule + sélecteur de site (CurrentSiteProviderInterface) + SiteScopedQueryExtension → numérotation + cloisonnement
- Commercial # Client (M1) + Supplier (M2) → contrepartie du ticket (Client / Fournisseur)
- Core # User, Role, Permission, Audit, JWT
- Shared # TimestampableBlamableTrait + Subscriber (ERP-52)
---
# Spec back — Module 5 : Tickets de pesée
## 1. Contexte
Cette spec **complète et précise** la [spec front V0.1](./spec-front.md) (docx `M5-ticket-de-pesee-V02`, V0.2 du 15/06/2026) avec tout ce qui touche au back : décisions d'archi, modèle de données, migration, API REST, RBAC, règles de gestion (RG-5.01 + précisions back RG-5.02 → RG-5.10), intégration pont bascule (stub), tests, hors-périmètre.
**Module cible** : **NOUVEAU module `Logistique`** (`src/Module/Logistique/`) — DÉCISION Matthieu (17/06). Le docx parle de « page d'entrée du Module *Logistique* » : on en fait un module à part entière (scaffolding via le skill `create-module`), distinct de `Transport` (M4). Son premier périmètre fonctionnel exposé est le **ticket de pesée** (entité `WeighingTicket`).
> **Distinction Transport (M4) vs Logistique (M5)** : `Transport` = référentiel des transporteurs (qui transporte). `Logistique` = opérations physiques sur site, à commencer par la **pesée au pont bascule**. Les deux peuvent à terme cohabiter dans une même section sidebar « Logistique » (cf. § 5.3), mais restent **deux modules** (activables/désactivables séparément).
> **RETEX obligatoire (M1→M4)** : ~80 % des frictions venaient du **contrat de sérialisation** (groupes / sous-ressources / embed), pas du métier. La section § 4.0 applique ce RETEX au M5. On réutilise aussi le pattern Provider/Processor + normalisation serveur + Timestampable/Blamable + audit i18n posé aux modules précédents.
**Dépendances déjà en place sur `develop`** :
- `Sites` → 3 sites Châtellerault (86) / Saint-Jean (17) / Pommevic (82) ; **sélecteur de site** exposé via `Sites\Application\Service\CurrentSiteProviderInterface` ; `SiteScopedQueryExtension` (filtrage par site courant) ; `SiteInterface` (contrat partagé).
- `Commercial``Client` (M1) + `Supplier` (M2).
- `Shared``TimestampableBlamableTrait` + `Subscriber` (ERP-52).
- `Core` → User, Role, Permission, Audit, JWT.
## 2. Décisions d'archi
### 2.1 Nouveau module `Logistique` + entité `WeighingTicket`
Création du module **`Logistique`** :
- `src/Module/Logistique/LogistiqueModule.php``ID = 'logistique'`, `LABEL = 'Logistique'`, `REQUIRED = false`, `permissions()` (§ 5.1).
- Ajout dans `config/modules.php` : `LogistiqueModule::class`.
- `Domain/`, `Application/`, `Infrastructure/` (arborescence DDD standard).
- Layer front `frontend/modules/logistique/` (kebab-case — règle naming).
Entité racine : **`WeighingTicket`** (ticket de pesée) sous `src/Module/Logistique/Domain/Entity/`, avec ses **deux pesées** (vide + plein) modélisées en colonnes plates (§ 2.4).
**Référentiels cross-module consommés en relation ORM partagée (PAS d'import de logique)** — exactement comme M2/M3/M4 : le ticket référence `Client` (M1), `Supplier` (M2) et `Site` (Sites) via des **relations ORM** (ManyToOne). Ce sont des **données de référence partagées**, pas de la logique inter-module (aucun service/repository d'un autre module appelé). La seule logique cross-module consommée est `CurrentSiteProviderInterface` (déjà un **contrat** exposé par Sites — autorisé par la règle ABSOLUE n°1).
### 2.2 IDs — convention `INT` (alignée Core/Commercial/Sites)
Le module `Logistique` est un **nouveau** module métier hors périmètre Transport : on s'aligne sur la convention **`INT GENERATED BY DEFAULT AS IDENTITY`** des modules historiques (Core / Commercial / Sites), et **non** sur le `BIGINT` du module Transport. Horodatages en `TIMESTAMP(0) WITHOUT TIME ZONE` (le `TimestampableBlamableTrait` mappe `datetime_immutable`).
### 2.3 Cloisonnement par site courant (DÉCISION par défaut — à confirmer)
> **Décision par défaut** : les tickets de pesée sont des **données opérationnelles rattachées à un site physique** (le pont bascule est sur site). On **cloisonne la liste par le site courant** (sélecteur de site en haut de l'app) via le `SiteScopedQueryExtension` **déjà existant** (Sites). Un utilisateur voit les tickets du site actif.
- Colonne `site_id` NOT NULL sur `weighing_ticket` (renseignée à la création depuis `CurrentSiteProviderInterface`).
- `GET /api/weighing_tickets` filtré sur le site courant (extension automatique).
- Le **numéro** du ticket encode déjà le site (RG-5.02) → cohérent avec le cloisonnement.
> **À confirmer client** : si le métier veut une **vue multi-sites** (tous sites confondus), retirer le cloisonnement et ajouter un filtre `?siteId=`. Tracé HP-M5-01 (§ 9).
### 2.4 Modélisation des deux pesées — colonnes plates (pas de sous-entité)
Un ticket porte **exactement deux pesées** : une **à vide** (tare) et une **à plein** (brut). Plutôt qu'une sous-collection `Weighing` (1:n), on modélise **deux jeux de colonnes plates** sur `weighing_ticket` :
| Groupe | Colonnes |
|---|---|
| Pesée à vide | `empty_date`, `empty_weight`, `empty_dsd`, `empty_mode` (AUTO/MANUAL), `empty_manual_number` |
| Pesée à plein | `full_date`, `full_weight`, `full_dsd`, `full_mode` (AUTO/MANUAL), `full_manual_number` |
Justification : cardinalité **fixe** (toujours 1 vide + 1 plein), pas de tri/ajout dynamique, requêtes/exports plus simples, audit lisible. (Alternative sous-entité `Weighing` documentée mais non retenue — over-engineering pour 2 lignes figées.)
> **Champs `*_manual_number`** : « numéro de pesée » saisi en **pesée manuelle** (référence d'un ticket papier / autre bascule — distinct du DSD, cf. RG-5.04). Nullable (rempli seulement si `mode = MANUAL`).
> **Maquette (17/06)** : les **deux** blocs (vide ET plein) portent les boutons « Pesée bascule » + « Pesée manuelle » — le modèle symétrique (`empty_*` ET `full_*` avec mode AUTO/MANUAL) est donc bien utilisé des deux côtés. (Le texte du docx V0.2 ne mentionnait la manuelle que sur le bloc vide ; la maquette fait foi.)
### 2.5 Numérotation `{siteCode}-TP-{NNNN}` (RG-5.02)
> **Décision** : chaque ticket reçoit un **numéro unique par site** au format `{siteCode}-TP-{NNNN}` (ex. `86-TP-0001`). La séquence est **propre à chaque site** → `86-TP-0001` et `17-TP-0001` coexistent (cf. docx).
- **`siteCode`** : le `Site` actuel n'a **pas** de colonne `code`. On **ajoute** `site.code` (VARCHAR court, ex. `86`/`17`/`82`) — backfill par défaut = 2 premiers chiffres du `postal_code`, valeur éditable ensuite côté admin Sites. Justification : un code explicite est plus robuste qu'une dérivation implicite du CP (collisions de département possibles). Petit débordement assumé sur le module Sites (1 colonne).
-**Cadencement en 2 temps (RETEX dev ERP-182, 17/06)** : `NOT NULL` ne peut PAS être posé dans la migration M5 seule. Sur base fraîche (`make db-reset`), les fixtures `SitesFixtures` font `new Site(...)` via l'ORM, qui ne connaît `code` que si la **propriété est mappée sur l'entité** `Site.php` (pas le cas avant ERP-183) → `INSERT` sans `code` → violation `NOT NULL`. Décision :
- **ERP-182 (migration)** : créer `site.code` **NULLABLE** + backfill + index unique (les `NULL` multiples sont tolérés par l'index unique Postgres). `make db-reset` passe, aucun test cassé.
- **ERP-183 (entité)** : mapper `Site::code` (propriété + getter/setter), le peupler dans `SitesFixtures` (86/17/82) + `SeedE2ECommand`, ajuster les tests Sites en collision d'unicité (ex. `SiteApiTest` créant un site CP `86000``code` 86 = collision avec Châtellerault), **puis** poser `NOT NULL` via une **2ᵉ petite migration**.
- **Séquence par site** : table dédiée `weighing_ticket_counter (site_id PK, last_value INT)`. À la création : `SELECT ... FOR UPDATE` sur la ligne du site (verrou ligne) → `last_value + 1`, formaté `%04d` (zéro-padding 4 chiffres, débordement naturel au-delà de 9999). Garantit l'unicité même en concurrence.
- Le numéro est **immuable** après création (pas modifiable à l'édition).
- Index unique `uq_weighing_ticket_number (site_id, number)`.
> **Alternative écartée** : séquence Postgres par site (création dynamique de séquences) — moins portable, plus lourde à seeder. La table compteur + `FOR UPDATE` est le pattern retenu.
### 2.6 Intégration pont bascule — stub au M5 (RG-5.06)
> **Décision Matthieu (17/06)** : **aucune liaison matérielle** au M5. Le « pont bascule » est **simulé** : il renvoie un **poids aléatoire ∈ [10000, 50000] kg**.
- Contrat : `Logistique\Domain\Contract\WeighbridgeReaderInterface`
```php
interface WeighbridgeReaderInterface
{
/** @throws WeighbridgeUnavailableException si la bascule ne répond pas (→ bascule manuelle). */
public function read(SiteInterface $site): WeighbridgeReading; // {weight: int (kg), dsd: int}
}
```
- Implémentation livrée au M5 : `Infrastructure\Weighbridge\RandomWeighbridgeReader` → `weight = random_int(10000, 50000)`, `dsd = nextDsd(site)` (RG-5.04).
- **Driver matériel réel** (protocole série/TCP de l'indicateur de pesage, parsing trame, reconnexion) = **hors périmètre M5**, tracé HP-M5-02 (§ 9). Le jour venu, on substitue l'implémentation derrière l'interface — **zéro impact** sur les écrans / l'API.
- **Gestion d'erreur** (RG-5.06) : si `read()` lève `WeighbridgeUnavailableException`, l'API renvoie un **422/503 explicite** « Pont bascule indisponible — passez en pesée manuelle ». Le front affiche le message dans la modal et propose la pesée manuelle (le stub ne lève jamais l'exception au M5, mais le chemin d'erreur est implémenté et testé).
### 2.7 DSD — compteur de pesée du pont (RG-5.04)
> **Décision Matthieu (17/06)** : le **DSD** est un **compteur de pesée** (index séquentiel des pesées du pont). Chaque pesée (vide OU plein) consomme **une** valeur DSD.
- Compteur **par site** (un pont par site) : table `weighbridge_dsd_counter (site_id PK, last_value INT)` (verrou ligne `FOR UPDATE`, même pattern que le compteur de numéro).
- **Pesée bascule (AUTO)** : la lecture incrémente le compteur du site et renvoie la nouvelle valeur (le stub fait pareil ; un vrai pont renverrait son propre index, qu'on persisterait).
- **Pesée manuelle** : `dsd = dernier dsd du site + 1` (le docx : « le dsd est automatiquement calculé en fonction du dernier dsd en base de données »).
- Un ticket complet (vide + plein en AUTO) consomme **2 incréments DSD** (`empty_dsd`, `full_dsd`).
### 2.8 Poids net — `plein vide`, calculé serveur (RG-5.05)
> **Le docx ne définit pas** le calcul du poids affiché en liste (colonne « Poids »). **CONFIRMÉ Matthieu (17/06)** : **poids net = poids plein poids vide**.
- Stocké en colonne dérivée `net_weight` (INT, kg), **recalculé serveur** par le `WeighingTicketProcessor` à chaque POST/PATCH dès que `empty_weight` ET `full_weight` sont renseignés (sinon `null`).
- La colonne **liste « Poids » = `net_weight`** (cf. § 4.0). Le détail/ticket affiche vide + plein + net.
- Exemple maquette : plein `14 300` vide `7 150` = **net `7 150` kg**.
### 2.9 Contrepartie CLIENT / FOURNISSEUR / AUTRE (RG-5.03)
Le formulaire principal porte un sélecteur **« Fournisseur / Client / Autre »** qui pilote des champs conditionnels (docx p.4). Le back **ne maintient pas de state machine** : il stocke et **valide la cohérence** au POST/PATCH.
| `counterparty_type` | Champs requis | Champs forcés nuls |
|---|---|---|
| `CLIENT` | `client_id` (FK Client) | `supplier_id`, `other_label` |
| `FOURNISSEUR` | `supplier_id` (FK Supplier) | `client_id`, `other_label` |
| `AUTRE` | `other_label` (texte libre) | `client_id`, `supplier_id` |
Validation via `#[Assert\Callback]` + CHECK Postgres (garde-fous miroir M4 § 3.2).
### 2.10 Masque immatriculation & « Tout format » (RG-5.01)
- `immatriculation` : par défaut **masque `XX-000-XX`** (plaque FR SIV). Si **`plate_free_format = true`** (« Tout format » coché), le masque est désactivé (saisie libre — anciennes plaques, étranger, engins).
- **Champs connectés entre les deux formulaires** (vide ⇄ plein) : `immatriculation` et `plate_free_format` sont **portés par le ticket** (une seule valeur, partagée par les 2 formulaires) — c'est le même véhicule. Pas de duplication.
- Normalisation serveur : `immatriculation` → trim + UPPER + (si masque) re-formatage `XX-000-XX` ; rejet 422 si format invalide et `plate_free_format = false`.
### 2.11 Audit & traces temporelles
Pattern Starseed standard (miroir M1→M4) :
- `#[Auditable]` sur `WeighingTicket`. Pas de champ sensible (password/token) → pas d'`#[AuditIgnore]`.
- Audit des FK (`client`, `supplier`, `site`) tracé automatiquement.
- `WeighingTicket implements TimestampableInterface, BlamableInterface` + `use TimestampableBlamableTrait` (4 colonnes standard).
- **Libellé i18n** (règle ABSOLUE backend — `AuditableEntitiesHaveI18nLabelTest`) : ajouter `audit.entity.logistique_weighingticket` dans `frontend/i18n/locales/fr.json` (clé = `strtolower(module)` + `_` + `strtolower(Entity)`).
### 2.12 Bon de pesée — PDF généré côté serveur via template Twig (RG-5.08)
> **DÉCISION Matthieu (17/06)** : le **bon de pesée est généré côté back** par un **template Twig → PDF** (et non un gabarit imprimé par le navigateur). **OWNER : Tristan** (ticket back dédié, cf. § 10). Cette spec en pose le contrat (endpoint, contenu, données).
Contrat attendu :
- **Endpoint** : `GET /api/weighing_tickets/{id}/print.pdf` (opération API Platform dédiée, **pas de controller** — provider renvoyant un binaire). Sécurité `is_granted('logistique.weighing_tickets.view')`. Réponse `Content-Type: application/pdf` (inline).
- **Rendu** : un template **Twig** (`templates/logistique/weighing_ticket_print.html.twig`) hydraté avec le ticket → converti en PDF via le générateur PDF du projet (ex. Dompdf / wkhtmltopdf / Gotenberg — s'aligner sur l'existant ; sinon proposer une lib et la cadrer avec Matthieu).
- **Contenu du bon** : numéro (`{siteCode}-TP-{NNNN}`), site, contrepartie (Client / Fournisseur / Autre + libellé), immatriculation, **pesée à vide** (date/poids/DSD), **pesée à plein** (date/poids/DSD), **poids net** (= plein vide), date d'édition. (En-tête / logo / mentions = à caler par Tristan.)
- **Données** : toutes déjà disponibles sur le ticket (mêmes champs que `GET /api/weighing_tickets/{id}` § 4.0) — aucun champ API supplémentaire requis.
- **Déclencheurs front** (RG-5.08) : à la **validation** (création), le front ouvre l'aperçu/PDF servi par cet endpoint ; en **modification**, le bouton **« Imprimer »** ouvre le même PDF (absent à l'ajout).
### 2.13 Pas d'archive ; soft delete préparé non exposé
Le docx M5 **ne prévoit pas** d'archivage (contrairement au M4). On **n'expose pas** d'archive. On prépare néanmoins une colonne `deleted_at` (soft delete technique) **non exposée** au M5 (`DELETE` non exposé → 404). Cohérent avec le pattern projet.
## 3. Modèle de données
### 3.1 Diagramme
```
+------------------+
| site (Sites) | + NOUVELLE colonne `code` (86/17/82)
+------------------+
^ ^ ^
site_id | | site_id| site_id
+---------------+ | +------------------------+
| | |
+-----------------------+ +--------------------------+ +--------------------------+
| weighing_ticket_counter| | weighbridge_dsd_counter | | weighing_ticket |
| site_id PK | | site_id PK | | id (PK) |
| last_value INT | | last_value INT | | number (UNIQUE / site) |
+-----------------------+ +--------------------------+ | site_id (FK) |
(séquence n° ticket) (compteur DSD pont) | counterparty_type |
| client_id (FK M1, null) |--> client (M1)
| supplier_id (FK M2, null)|--> supplier (M2)
| other_label (null) |
| immatriculation |
| plate_free_format |
| empty_* (date/weight/dsd/mode/manual_number) |
| full_* (date/weight/dsd/mode/manual_number) |
| net_weight (dérivé) |
| deleted_at (soft, non exposé) |
+--------------------------+
```
### 3.2 Migration Doctrine — SQL Postgres
Namespace : **`DoctrineMigrations` (racine `migrations/`)** — fichier `migrations/VersionYYYYMMDDHHMMSS.php` (à dater, postérieur aux migrations existantes).
> **Même justification qu'aux M1→M4** : la migration crée un schéma avec **FK cross-module** (`user`, `client`, `supplier`, `site`). Le namespace modulaire casserait l'ordre (`make db-reset`) — exception racine de la règle ABSOLUE n°11.
> **Rappel règle ABSOLUE n°12** : chaque colonne créée DOIT recevoir son `COMMENT ON COLUMN` (FR, ≤ 200 car., sémantique + contrainte/RG). Les 4 colonnes Timestampable/Blamable passent par le helper `addStandardTimestampableBlamableComments`. SQL ci-dessous *illustratif* (convention `INT GENERATED BY DEFAULT AS IDENTITY`, `TIMESTAMP(0)`).
```sql
-- =====================================================================
-- Ajout d'un code de site (préfixe de numérotation TP) — § 2.5
-- =====================================================================
-- ⚠ NULLABLE au M5 (ERP-182). Le SET NOT NULL est posé en ERP-183, une fois Site::code
-- mappé sur l'entité et peuplé dans les fixtures (sinon db-reset casse — cf. § 2.5).
ALTER TABLE site ADD COLUMN code VARCHAR(8);
-- Backfill : 2 premiers chiffres du code postal (dépt) par défaut, éditable ensuite.
UPDATE site SET code = LEFT(postal_code, 2) WHERE code IS NULL;
-- Index unique tolérant les NULL (Postgres : plusieurs NULL autorisés) — OK tant que code nullable.
CREATE UNIQUE INDEX uq_site_code ON site (code);
-- ERP-183 (2ᵉ migration) : ALTER TABLE site ALTER COLUMN code SET NOT NULL;
-- =====================================================================
-- Compteur de numéro de ticket (séquence par site) — RG-5.02
-- =====================================================================
CREATE TABLE weighing_ticket_counter (
site_id INT PRIMARY KEY REFERENCES site(id) ON DELETE CASCADE,
last_value INT NOT NULL DEFAULT 0
);
-- =====================================================================
-- Compteur DSD (pesée du pont, par site) — RG-5.04
-- =====================================================================
CREATE TABLE weighbridge_dsd_counter (
site_id INT PRIMARY KEY REFERENCES site(id) ON DELETE CASCADE,
last_value INT NOT NULL DEFAULT 0
);
-- =====================================================================
-- Table principale `weighing_ticket`
-- =====================================================================
CREATE TABLE weighing_ticket (
id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
site_id INT NOT NULL REFERENCES site(id) ON DELETE RESTRICT,
number VARCHAR(20) NOT NULL, -- {siteCode}-TP-{NNNN} (RG-5.02)
-- Contrepartie (RG-5.03)
counterparty_type VARCHAR(12) NOT NULL, -- CLIENT|FOURNISSEUR|AUTRE
client_id INT REFERENCES client(id) ON DELETE RESTRICT,
supplier_id INT REFERENCES supplier(id) ON DELETE RESTRICT,
other_label VARCHAR(255),
-- Véhicule (RG-5.01, partagé entre les 2 formulaires)
immatriculation VARCHAR(20) NOT NULL,
plate_free_format BOOLEAN NOT NULL DEFAULT FALSE,
-- Pesée à vide (§ 2.4)
empty_date TIMESTAMP(0) WITHOUT TIME ZONE,
empty_weight INT, -- kg
empty_dsd INT,
empty_mode VARCHAR(8), -- AUTO|MANUAL
empty_manual_number VARCHAR(50), -- numéro de pesée manuelle (RG-5.04)
-- Pesée à plein (§ 2.4)
full_date TIMESTAMP(0) WITHOUT TIME ZONE,
full_weight INT, -- kg
full_dsd INT,
full_mode VARCHAR(8), -- AUTO|MANUAL
full_manual_number VARCHAR(50),
-- Dérivé (RG-5.05)
net_weight INT, -- full_weight - empty_weight (RG-5.05)
-- Soft delete (préparé, non exposé au M5)
deleted_at TIMESTAMP(0) WITHOUT TIME ZONE,
-- Timestampable + Blamable
created_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL,
updated_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL,
created_by INT REFERENCES "user"(id) ON DELETE SET NULL,
updated_by INT REFERENCES "user"(id) ON DELETE SET NULL,
CONSTRAINT chk_wt_counterparty_type
CHECK (counterparty_type IN ('CLIENT','FOURNISSEUR','AUTRE')),
CONSTRAINT chk_wt_empty_mode CHECK (empty_mode IS NULL OR empty_mode IN ('AUTO','MANUAL')),
CONSTRAINT chk_wt_full_mode CHECK (full_mode IS NULL OR full_mode IN ('AUTO','MANUAL')),
-- RG-5.03 : cohérence contrepartie
CONSTRAINT chk_wt_client_branch CHECK (
counterparty_type <> 'CLIENT' OR (client_id IS NOT NULL AND supplier_id IS NULL AND other_label IS NULL)
),
CONSTRAINT chk_wt_supplier_branch CHECK (
counterparty_type <> 'FOURNISSEUR' OR (supplier_id IS NOT NULL AND client_id IS NULL AND other_label IS NULL)
),
CONSTRAINT chk_wt_other_branch CHECK (
counterparty_type <> 'AUTRE' OR (other_label IS NOT NULL AND client_id IS NULL AND supplier_id IS NULL)
)
);
CREATE UNIQUE INDEX uq_weighing_ticket_number ON weighing_ticket (site_id, number);
CREATE INDEX idx_wt_site ON weighing_ticket (site_id);
CREATE INDEX idx_wt_client ON weighing_ticket (client_id);
CREATE INDEX idx_wt_supplier ON weighing_ticket (supplier_id);
CREATE INDEX idx_wt_deleted_at ON weighing_ticket (deleted_at);
CREATE INDEX idx_wt_created_by ON weighing_ticket (created_by);
CREATE INDEX idx_wt_updated_by ON weighing_ticket (updated_by);
```
### 3.2.bis Commentaires SQL obligatoires (échantillon)
```php
$this->addSql("COMMENT ON TABLE weighing_ticket IS 'Tickets de pesée (M5 Logistique) — pesée à vide + à plein au pont bascule, contrepartie Client/Fournisseur/Autre.'");
$this->addSql("COMMENT ON COLUMN site.code IS 'Code court du site (ex. 86/17/82) — préfixe de numérotation des tickets de pesée (RG-5.02). Unique.'");
$this->addSql("COMMENT ON COLUMN weighing_ticket.number IS 'Numéro {siteCode}-TP-{NNNN}, unique par site, immuable. Séquence weighing_ticket_counter (RG-5.02).'");
$this->addSql("COMMENT ON COLUMN weighing_ticket.counterparty_type IS 'Contrepartie : CLIENT, FOURNISSEUR ou AUTRE (RG-5.03). Pilote l''obligation client_id / supplier_id / other_label.'");
$this->addSql("COMMENT ON COLUMN weighing_ticket.immatriculation IS 'Plaque du véhicule, partagée entre pesée vide et plein. Masque XX-000-XX sauf si plate_free_format (RG-5.01).'");
$this->addSql("COMMENT ON COLUMN weighing_ticket.plate_free_format IS '« Tout format » : désactive le masque XX-000-XX de l''immatriculation (RG-5.01). Partagé entre les 2 formulaires.'");
$this->addSql("COMMENT ON COLUMN weighing_ticket.empty_dsd IS 'Compteur DSD du pont à la pesée à vide. AUTO=valeur du pont ; MANUAL=dernier dsd du site +1 (RG-5.04).'");
$this->addSql("COMMENT ON COLUMN weighing_ticket.empty_manual_number IS 'Numéro de pesée saisi en pesée manuelle (distinct du DSD) — formulaire à vide (RG-5.04).'");
$this->addSql("COMMENT ON COLUMN weighing_ticket.net_weight IS 'Poids net = full_weight - empty_weight (kg), calculé serveur (RG-5.05). Colonne Poids de la liste.'");
$this->addSql("COMMENT ON COLUMN weighbridge_dsd_counter.last_value IS 'Dernière valeur DSD attribuée pour le site (pont bascule). Incrément verrouillé FOR UPDATE (RG-5.04).'");
$this->addSql("COMMENT ON COLUMN weighing_ticket_counter.last_value IS 'Dernier numéro de ticket attribué pour le site. Incrément verrouillé FOR UPDATE (RG-5.02).'");
// + COMMENT ON COLUMN sur TOUTES les autres colonnes métier (règle n°12)
$this->addStandardTimestampableBlamableComments($schema, 'weighing_ticket');
```
### 3.3 Entité `WeighingTicket` — squelette (extrait)
Pattern jumeau de `Carrier`/`Supplier` (`#[Auditable]`, `TimestampableBlamableTrait`). **Chaque propriété affichée porte un read-group** (RETEX M1).
```php
<?php
declare(strict_types=1);
namespace App\Module\Logistique\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\Domain\Entity\Client; // relation ORM partagée (§ 2.1)
use App\Module\Commercial\Domain\Entity\Supplier; // relation ORM partagée (§ 2.1)
use App\Module\Sites\Domain\Entity\Site; // relation ORM partagée (§ 2.1)
use App\Module\Logistique\Infrastructure\ApiPlatform\State\Processor\WeighingTicketProcessor;
use App\Module\Logistique\Infrastructure\ApiPlatform\State\Provider\WeighingTicketProvider;
use App\Module\Logistique\Infrastructure\Doctrine\DoctrineWeighingTicketRepository;
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\Serializer\Attribute\SerializedName;
use Symfony\Component\Validator\Constraints as Assert;
#[ApiResource(
operations: [
new GetCollection(
security: "is_granted('logistique.weighing_tickets.view')",
normalizationContext: ['groups' => ['weighing_ticket:read', 'client:read', 'supplier:read', 'site:read', 'default:read']],
provider: WeighingTicketProvider::class,
),
new Get(
security: "is_granted('logistique.weighing_tickets.view')",
normalizationContext: ['groups' => ['weighing_ticket:read', 'weighing_ticket:item:read', 'client:read', 'supplier:read', 'site:read', 'default:read']],
provider: WeighingTicketProvider::class,
),
new Post(
security: "is_granted('logistique.weighing_tickets.manage')",
normalizationContext: ['groups' => ['weighing_ticket:read', 'weighing_ticket:item:read', 'client:read', 'supplier:read', 'site:read', 'default:read']],
denormalizationContext: ['groups' => ['weighing_ticket:write']],
processor: WeighingTicketProcessor::class,
),
new Patch(
security: "is_granted('logistique.weighing_tickets.manage')",
normalizationContext: ['groups' => ['weighing_ticket:read', 'weighing_ticket:item:read', 'client:read', 'supplier:read', 'site:read', 'default:read']],
denormalizationContext: ['groups' => ['weighing_ticket:write']],
provider: WeighingTicketProvider::class,
processor: WeighingTicketProcessor::class,
),
// Pas de Delete au M5 (HP). Pas d'archive (hors docx).
],
)]
#[ORM\Entity(repositoryClass: DoctrineWeighingTicketRepository::class)]
#[ORM\Table(name: 'weighing_ticket')]
#[Auditable]
class WeighingTicket implements TimestampableInterface, BlamableInterface
{
use TimestampableBlamableTrait;
#[ORM\Id, ORM\GeneratedValue, ORM\Column]
#[Groups(['weighing_ticket:read'])]
private ?int $id = null;
/** Numéro {siteCode}-TP-{NNNN} — attribué serveur, lecture seule (RG-5.02). */
#[ORM\Column(length: 20)]
#[Groups(['weighing_ticket:read'])]
private ?string $number = null;
#[ORM\ManyToOne(targetEntity: Site::class)]
#[ORM\JoinColumn(name: 'site_id', nullable: false, onDelete: 'RESTRICT')]
#[Groups(['weighing_ticket:read'])] // renseigné serveur depuis le site courant (§ 2.3)
private ?Site $site = null;
#[ORM\Column(length: 12)]
#[Assert\Choice(choices: ['CLIENT', 'FOURNISSEUR', 'AUTRE'], message: 'Type de contrepartie invalide.')]
#[Assert\NotBlank(message: 'La contrepartie (Client / Fournisseur / Autre) est obligatoire.')]
#[Groups(['weighing_ticket:read', 'weighing_ticket:write'])]
private ?string $counterpartyType = null;
#[ORM\ManyToOne(targetEntity: Client::class)]
#[ORM\JoinColumn(name: 'client_id', nullable: true, onDelete: 'RESTRICT')]
#[Groups(['weighing_ticket:read', 'weighing_ticket:write'])]
private ?Client $client = null; // requis si counterpartyType=CLIENT (Callback RG-5.03)
#[ORM\ManyToOne(targetEntity: Supplier::class)]
#[ORM\JoinColumn(name: 'supplier_id', nullable: true, onDelete: 'RESTRICT')]
#[Groups(['weighing_ticket:read', 'weighing_ticket:write'])]
private ?Supplier $supplier = null; // requis si counterpartyType=FOURNISSEUR
#[ORM\Column(length: 255, nullable: true)]
#[Groups(['weighing_ticket:read', 'weighing_ticket:write'])]
private ?string $otherLabel = null; // requis si counterpartyType=AUTRE
#[ORM\Column(length: 20)]
#[Assert\NotBlank(message: 'L''immatriculation est obligatoire.')]
#[Groups(['weighing_ticket:read', 'weighing_ticket:write'])]
private ?string $immatriculation = null; // masque XX-000-XX sauf plateFreeFormat (RG-5.01)
#[ORM\Column(options: ['default' => false])]
#[Groups(['weighing_ticket:read', 'weighing_ticket:write'])]
private bool $plateFreeFormat = false;
// === Pesée à vide ===
#[ORM\Column(name: 'empty_date', type: 'datetime_immutable', nullable: true)]
#[Groups(['weighing_ticket:item:read', 'weighing_ticket:write'])]
private ?\DateTimeImmutable $emptyDate = null;
#[ORM\Column(name: 'empty_weight', nullable: true)]
#[Groups(['weighing_ticket:item:read', 'weighing_ticket:write'])]
private ?int $emptyWeight = null; // kg — readonly UI, rempli par la pesée (RG-5.07)
#[ORM\Column(name: 'empty_dsd', nullable: true)]
#[Groups(['weighing_ticket:item:read', 'weighing_ticket:write'])]
private ?int $emptyDsd = null;
#[ORM\Column(name: 'empty_mode', length: 8, nullable: true)]
#[Assert\Choice(choices: ['AUTO', 'MANUAL'], message: 'Mode de pesée invalide.')]
#[Groups(['weighing_ticket:item:read', 'weighing_ticket:write'])]
private ?string $emptyMode = null;
#[ORM\Column(name: 'empty_manual_number', length: 50, nullable: true)]
#[Groups(['weighing_ticket:item:read', 'weighing_ticket:write'])]
private ?string $emptyManualNumber = null;
// === Pesée à plein (mêmes colonnes, préfixe full*) ===
// fullDate / fullWeight / fullDsd / fullMode / fullManualNumber ...
/** Poids net dérivé — calculé serveur (RG-5.05). */
#[ORM\Column(name: 'net_weight', nullable: true)]
#[Groups(['weighing_ticket:read'])]
private ?int $netWeight = null;
// RG-5.03 (contrepartie) + RG-5.01 (immat) : cohérence via #[Assert\Callback] (§ 7).
// ... getters/setters ...
}
```
> ⚠ `Client` / `Supplier` / `Site` appartiennent à d'autres modules — on consomme leurs read-groups (`client:read`, `supplier:read`, `site:read`), **pas de logique inter-module** (§ 2.1).
## 4. API REST (API Platform)
### 4.0 Contrat de sérialisation (RETEX M1 — section critique)
> **Leçon M1→M4** : pour **chaque champ affiché** (liste OU détail), les **3 maillons** doivent être prouvés : (a) groupe sur la propriété, (b) groupe dans le `normalizationContext` de l'opération, (c) read-group de l'entité imbriquée présent dans le contexte parent.
**Contexte par opération** :
| Opération | `normalizationContext` (groupes) |
|---|---|
| `GetCollection` (liste) | `weighing_ticket:read` + `client:read` + `supplier:read` + `site:read` + `default:read` |
| `Get` / `Post` / `Patch` (détail) | + `weighing_ticket:item:read` |
**LISTE — colonne datatable → maillons** (docx p.3 : Numéro, Client, Fournisseur, Autre, Date, Poids) :
| Colonne affichée | Propriété (a) | Dans contexte liste (b) | Imbriqué (c) |
|---|---|---|---|
| Numéro | `number` ∈ `weighing_ticket:read` | ✅ | — |
| Client | `client` ∈ `weighing_ticket:read` (embed) | ✅ | `client:read` ✅ (RG-5.03) |
| Fournisseur | `supplier` ∈ `weighing_ticket:read` (embed) | ✅ | `supplier:read` ✅ |
| Autre | `otherLabel` ∈ `weighing_ticket:read` | ✅ | — |
| Date | `fullDate` ?? `emptyDate` (date du ticket) ∈ `weighing_ticket:read` | ✅ | — |
| Poids | `netWeight` ∈ `weighing_ticket:read` | ✅ | — |
> **Note « Date » liste** : on expose une propriété calculée `displayDate` (getter) = `fullDate ?? emptyDate`, dans `weighing_ticket:read` (les `empty/full*` détaillées restent en `:item:read`).
**DÉTAIL — maillons** : scalaires + `emptyDate/emptyWeight/emptyDsd/...` + `full*` ∈ `weighing_ticket:item:read` ; `client`/`supplier`/`site` embarqués (`client:read`/`supplier:read`/`site:read`).
### 4.0.bis Réponse JSON de référence (DoD — CAPTURÉE sur l'API réelle ✅)
> **Definition of Done** (miroir M2/M3/M4) : ✅ **FAIT (ERP-187)**. Le JSON ci-dessous est la réponse **RÉELLE** capturée par le test `WeighingTicketSerializationContractTest::testListAndDetailSerializationContract` (ticket créé via `POST /api/weighing_tickets` — numérotation serveur réelle — contrepartie Client, pesée vide + plein AUTO). Re-capturable : `WEIGHING_TICKET_DOD_DUMP=1` → `/tmp/weighing-ticket-dod-{list,detail}.json`. **Feu vert front.** Toute donnée affichée par le front DOIT apparaître dans ce JSON.
>
> **Pièges re-testés — tous VERTS** (assertions dans le test) :
> 1. ✅ `client` sort en **objet embarqué** (`client:read`), pas en IRI nu ; `supplier` **omis car null** (`skip_null_values` — jamais un IRI nu). Sur une contrepartie Fournisseur, `supplier` sortirait symétriquement en objet (`supplier:read`).
> 2. ✅ Booléen `plateFreeFormat` : **clé présente** (getter `isPlateFreeFormat()` + `SerializedName('plateFreeFormat')`).
> 3. ✅ `number` présent et formaté `{siteCode}-TP-{NNNN}` (ici `86-TP-0001`).
> 4. ✅ `netWeight` cohérent = `full - empty` = `14300 - 7150` = **`7150`** (RG-5.05).
>
> **Note `skip_null_values`** : les champs null sont **omis** du JSON (ex. `supplier`, `otherLabel`, `emptyManualNumber`, `fullManualNumber` absents quand null). Le front ne doit pas présumer leur présence — lire avec un défaut (`?? null`).
**`GET /api/weighing_tickets?search=86-TP-0001` (LISTE)** — enveloppe Hydra AP4 (`member`/`totalItems`/`view`), filtrée site courant (§ 2.3). Capture réelle :
```jsonc
{
"@context": "/api/contexts/WeighingTicket",
"@id": "/api/weighing_tickets",
"@type": "Collection",
"totalItems": 1,
"member": [
{
"@id": "/api/weighing_tickets/9",
"@type": "WeighingTicket",
"id": 9,
"number": "86-TP-0001",
"counterpartyType": "CLIENT",
"client": {
"@id": "/api/clients/629",
"@type": "Client",
"id": 629,
"companyName": "NÉGOCE MÉTAUX ATLANTIQUE",
"triageService": false,
"categories": [],
"createdAt": "2026-06-18T11:50:47+02:00",
"updatedAt": "2026-06-18T11:50:47+02:00",
"createdBy": "/api/me",
"updatedBy": "/api/me",
"sites": [],
"isArchived": false
},
"plateFreeFormat": false,
"netWeight": 7150,
"createdAt": "2026-06-18T11:50:48+02:00",
"updatedAt": "2026-06-18T11:50:48+02:00",
"createdBy": "/api/me",
"updatedBy": "/api/me",
"displayDate": "2026-06-17T09:12:00+02:00"
// supplier / otherLabel omis (null → skip_null_values)
}
],
"view": { "@id": "/api/weighing_tickets?search=86-TP-0001", "@type": "PartialCollectionView" }
}
```
**`GET /api/weighing_tickets/9` (DÉTAIL)** — ajoute le site embarqué (avec `code`), l'immatriculation et les deux pesées. Capture réelle :
```jsonc
{
"@context": "/api/contexts/WeighingTicket",
"@id": "/api/weighing_tickets/9",
"@type": "WeighingTicket",
"id": 9,
"number": "86-TP-0001",
"site": {
"@id": "/api/sites/1",
"@type": "Site",
"id": 1,
"name": "Chatellerault",
"code": "86",
"street": "14 All. d'Argenson",
"postalCode": "86100",
"city": "Châtellerault",
"color": "#056CF2",
"createdAt": "2026-06-17T17:07:47+02:00",
"updatedAt": "2026-06-17T17:07:47+02:00",
"fullAddress": "14 All. d'Argenson\n86100 Châtellerault"
},
"counterpartyType": "CLIENT",
"client": {
"@id": "/api/clients/629",
"@type": "Client",
"id": 629,
"companyName": "NÉGOCE MÉTAUX ATLANTIQUE",
"triageService": false,
"categories": [],
"createdAt": "2026-06-18T11:50:47+02:00",
"updatedAt": "2026-06-18T11:50:47+02:00",
"createdBy": "/api/me",
"updatedBy": "/api/me",
"sites": [],
"isArchived": false
},
"immatriculation": "AB-123-CD",
"plateFreeFormat": false,
"emptyDate": "2026-06-17T09:00:00+02:00",
"emptyWeight": 7150,
"emptyDsd": 1,
"emptyMode": "AUTO",
"fullDate": "2026-06-17T09:12:00+02:00",
"fullWeight": 14300,
"fullDsd": 2,
"fullMode": "AUTO",
"netWeight": 7150,
"createdAt": "2026-06-18T11:50:48+02:00",
"updatedAt": "2026-06-18T11:50:48+02:00",
"createdBy": "/api/me",
"updatedBy": "/api/me",
"displayDate": "2026-06-17T09:12:00+02:00"
// emptyManualNumber / fullManualNumber omis (null → skip_null_values)
}
```
### 4.1 Query params (LISTE)
| Param | Effet |
|---|---|
| `?page` / `?itemsPerPage` | pagination standard (10 / 25 / 50, défaut 10) |
| `?search=` | recherche sur `number`, nom client/fournisseur, `other_label`, `immatriculation` |
| `?order[displayDate]=desc` | tri par date (défaut : `number DESC` = plus récents en tête) |
| *(site courant)* | filtré automatiquement par `SiteScopedQueryExtension` (§ 2.3) |
Pagination obligatoire (règle ABSOLUE n°13) — provider ORM via `ApiPlatform\Doctrine\Orm\Paginator`, jamais d'array brut.
### 4.2 Endpoint pesée (pont bascule) — `POST /api/weighbridge_readings`
Action **autonome** (le ticket n'est pas encore créé quand on déclenche la pesée du formulaire principal).
- **Sécurité** : `is_granted('logistique.weighing_tickets.manage')`.
- **AUTO (pesée bascule)** — body `{ "mode": "AUTO" }` → le site courant est résolu serveur (`CurrentSiteProviderInterface`).
- Réponse `200` : `{ "weight": 23187, "dsd": 42, "mode": "AUTO" }` (stub : `weight = random_int(10000,50000)`, `dsd = nextDsd(site)`).
- Réponse `503` (RG-5.06) si `WeighbridgeUnavailableException` : `{ "title": "Pont bascule indisponible", "detail": "Passez en pesée manuelle." }`.
- **MANUAL (pesée manuelle)** — body `{ "mode": "MANUAL", "weight": 23187, "manualNumber": "PAP-555" }`.
- Réponse `200` : `{ "weight": 23187, "dsd": 43, "manualNumber": "PAP-555", "mode": "MANUAL" }` (`dsd = dernier dsd du site + 1`, RG-5.04).
> **Implémentation** : `#[ApiResource]` non-Doctrine (DTO `WeighbridgeReadingInput`/`Output`) + Processor dédié, OU une ressource `WeighbridgeReading` virtuelle. **Pas de controller** Symfony (règle backend). Le Processor appelle `WeighbridgeReaderInterface` + le `DsdAllocator` (verrou `FOR UPDATE`).
>
> **Concurrence DSD** : le `dsd` renvoyé ici est **prévisionnel**. L'attribution **autoritaire** du `dsd` (et du `number`) est refaite/verrouillée à la **création du ticket** (`POST /api/weighing_tickets`) pour éviter les collisions si deux postes pèsent en parallèle. Front : afficher le dsd renvoyé, mais c'est le ticket persisté qui fait foi.
### 4.3 `POST /api/weighing_tickets` (création)
- Le client envoie : `counterpartyType` (+ `client`/`supplier`/`otherLabel`), `immatriculation`, `plateFreeFormat`, et les pesées (`emptyDate/Weight/Dsd/Mode/ManualNumber`, `full*`).
- Le **Processor** :
1. Résout le **site courant** (`CurrentSiteProviderInterface`) → `site_id`.
2. Attribue le **numéro** `{siteCode}-TP-{NNNN}` (compteur verrouillé — RG-5.02).
3. (Re)attribue les `dsd` autoritaires si nécessaire (verrou — RG-5.04).
4. Normalise `immatriculation` (RG-5.01) ; valide la cohérence contrepartie (RG-5.03) et pesées.
5. Calcule `net_weight = full_weight - empty_weight` si les deux poids sont présents (RG-5.05).
- Réponse `201` avec le ticket complet → le front ouvre la **modal d'impression** (RG-5.08).
### 4.4 `PATCH /api/weighing_tickets/{id}` (modification)
- Mise à jour partielle (mêmes règles). Le **numéro et le site sont immuables** (ignorés s'ils sont envoyés). `net_weight` recalculé. Le bouton d'impression est disponible (RG-5.08).
### 4.5 Export — `GET /api/weighing_tickets/export.xlsx`
- Exporte **toute la liste** des tickets (docx : bouton « Exporter » → « Exporte toute la liste des tickets de pesée »), filtrée par le site courant + filtres actifs.
- Colonnes : Numéro, Contrepartie (Client/Fournisseur/Autre + nom), Date, Immatriculation, Poids vide, Poids plein, **Poids net**, DSD vide/plein.
- Génération via le helper XLSX standard projet (skill `xlsx`). Endpoint : provider dédié renvoyant un binaire (`Content-Type` xlsx) — whitelisté pagination (`EXCLUDED`) car export complet.
### 4.6 Impression — `GET /api/weighing_tickets/{id}/print.pdf` (bon de pesée, OWNER Tristan)
- Opération API Platform dédiée (provider renvoyant un binaire PDF, **pas de controller**). Sécurité `is_granted('logistique.weighing_tickets.view')`.
- Rendu d'un **template Twig** (`templates/logistique/weighing_ticket_print.html.twig`) → PDF (cf. § 2.12). `Content-Type: application/pdf`, inline.
- Contenu : cf. § 2.12. Données déjà portées par le ticket — aucun champ API supplémentaire.
## 5. RBAC, module & sidebar
### 5.1 `LogistiqueModule::permissions()`
```php
public static function permissions(): array
{
return [
['code' => 'logistique.weighing_tickets.view', 'label' => 'Voir les tickets de pesée'],
['code' => 'logistique.weighing_tickets.manage', 'label' => 'Créer / modifier les tickets de pesée'],
];
}
```
Synchronisation : `app:sync-permissions`.
### 5.2 Matrice rôle → permissions (docx p.3)
| Rôle | `…view` | `…manage` |
|---|:--:|:--:|
| **Admin** | ✅ | ✅ |
| **Bureau** | ✅ | ✅ |
| **Usine** | ✅ | ✅ |
| **Compta** | ❌ | ❌ |
| **Commerciale** | ❌ | ❌ |
> ⚠ **Changement vs M5 V0.1** : en V0.2 **Usine = Tout / Tout** (consultation + ajout/modif), alors que la V0.1 disait « Oui ». Compta et Commerciale = **aucun** accès (item sidebar masqué).
### 5.3 Sidebar (`config/sidebar.php`)
Nouvelle section **« Logistique »** (ou item rattaché à une section logistique mutualisée avec Transport — à confirmer). Item :
```php
[
'label' => 'sidebar.logistique.weighing_tickets',
'to' => '/weighing-tickets',
'icon' => 'mdi-scale',
'module' => 'logistique',
'permission' => 'logistique.weighing_tickets.view',
],
```
### 5.4 Règle ABSOLUE n°8 — 3 miroirs RBAC
Toute permission `logistique.*` doit être posée **simultanément** dans :
1. `config/sidebar.php` (item + permission ci-dessus),
2. `frontend/tests/e2e/_fixtures/personas.ts` (ajuster un persona existant : Usine gagne `weighing_tickets.view/manage` + `expectedAdminLinks`),
3. `src/Module/Core/Infrastructure/Console/SeedE2ECommand.php` (miroir back du même persona).
## 6. Normalisation serveur (RG-5.01 / RG-5.10)
`WeighingTicketFieldNormalizer` (miroir `CarrierFieldNormalizer`), appelé par le Processor avant validation :
```php
final class WeighingTicketFieldNormalizer
{
// RG-5.01 : trim + UPPER ; si !plateFreeFormat → reformate XX-000-XX (rejet 422 si invalide).
public function normalizeImmatriculation(?string $v, bool $freeFormat): ?string
public function normalizeOtherLabel(?string $v): ?string // trim
}
```
## 7. Règles de gestion (RG)
| RG | Source | Énoncé |
|---|---|---|
| **RG-5.01** | docx | Immatriculation : masque par défaut `XX-000-XX` ; « Tout format » coché → masque désactivé (saisie libre). Les champs `immatriculation` et `plateFreeFormat` sont **connectés entre les 2 formulaires** (une seule valeur portée par le ticket — § 2.10). |
| **RG-5.02** | back | Numéro `{siteCode}-TP-{NNNN}`, **unique par site**, attribué serveur à la création, immuable. Séquence verrouillée par site (§ 2.5). |
| **RG-5.03** | docx+back | Contrepartie `CLIENT`/`FOURNISSEUR`/`AUTRE` → champ associé obligatoire, les autres forcés nuls (§ 2.9). |
| **RG-5.04** | docx+back | DSD = compteur de pesée du pont, par site. AUTO = valeur du pont ; MANUAL = dernier dsd du site + 1. « Numéro de pesée » manuel = champ distinct (§ 2.7). |
| **RG-5.05** | back | Poids net = `poids plein poids vide`, calculé serveur, exposé en liste/détail (§ 2.8 — confirmé Matthieu 17/06). |
| **RG-5.06** | docx+back | Pesée bascule indisponible → erreur explicite + bascule en pesée manuelle. Au M5, le pont est un **stub** (poids aléatoire ∈ [10000,50000] kg, § 2.6). |
| **RG-5.07** | docx | Formulaire à vide : `Date` = date du jour par défaut ; `Poids` et `DSD` **readonly** (remplis par la pesée, pas saisis). |
| **RG-5.08** | docx | « Valider » (création) → enregistre + ouvre le **bon de pesée (PDF servi par le back)**. En modification : bouton « Valider » → « Enregistrer », bouton « Imprimer » disponible (absent à l'ajout) → ouvre le même PDF. Le bouton « Enregistré » du bloc pesée à vide disparaît en modification. **Bon de pesée = PDF généré back via template Twig, OWNER Tristan** (§ 2.12 / § 4.6). |
| **RG-5.09** | back | Site & numéro immuables après création ; liste cloisonnée par site courant (§ 2.3, à confirmer). |
| **RG-5.10** | back | Normalisation immatriculation (trim/UPPER/format) côté serveur (§ 6). |
Cohérence inter-champs (RG-5.03, RG-5.01) implémentée via `#[Assert\Callback]` portant des messages FR + CHECK Postgres en garde-fou (§ 3.2).
## 8. Tests (PHPUnit) — `make test`
- **`WeighingTicketSerializationContractTest`** : capture JSON liste + détail (DoD § 4.0.bis), 4 pièges verts.
- **`WeighingTicketNumberingTest`** : `{siteCode}-TP-{NNNN}`, séquence par site, unicité, concurrence (FOR UPDATE).
- **`DsdAllocatorTest`** : AUTO incrémente ; MANUAL = dernier + 1 ; par site.
- **`WeighbridgeReaderStubTest`** : poids ∈ [10000,50000] ; chemin d'erreur `WeighbridgeUnavailableException` → 503 (RG-5.06).
- **`NetWeightTest`** : `plein vide` ; null si une pesée manque (RG-5.05).
- **`CounterpartyValidationTest`** : RG-5.03 (chaque branche + rejets).
- **`ImmatriculationNormalizationTest`** : masque XX-000-XX, free format, 422 (RG-5.01).
- **RBAC** : Usine/Bureau/Admin OK ; Compta/Commerciale 403.
- **Architecture** (déjà en place, ne pas casser) : `ColumnsHaveSqlCommentTest`, `EntitiesAreTimestampableBlamableTest`, `AuditableEntitiesHaveI18nLabelTest`, `CollectionsArePaginatedTest`, `EntityConstraintsHaveFrenchMessageTest`.
## 9. Hors périmètre (HP)
| Réf | Sujet |
|---|---|
| HP-M5-01 | Vue multi-sites des tickets (retirer le cloisonnement + filtre `?siteId=`) si demandé (§ 2.3). |
| HP-M5-02 | Driver matériel réel du pont bascule (protocole série/TCP, parsing trame, reconnexion) derrière `WeighbridgeReaderInterface` (§ 2.6). |
| HP-M5-03 | Sens réception-expédition explicite + contrôle de signe du net (le net reste `plein vide`, § 2.8). |
| ~~HP-M5-04~~ | **Passé en périmètre** : bon de pesée = PDF serveur via template Twig → ticket back dédié (OWNER Tristan, § 2.12 / § 4.6). |
| HP-M5-05 | Archivage fonctionnel des tickets (non prévu au docx — § 2.13). |
## 10. Tickets Lesstime (à découper — back en tête)
| Ordre | Sujet | Tag |
|---|---|---|
| 0 | Scaffolding module `Logistique` (create-module) + `config/modules.php` + sidebar + 3 miroirs RBAC | Backend |
| 1 | Migration : `site.code` + compteurs + `weighing_ticket` (+ index + COMMENT) | Backend |
| 2 | Entité `WeighingTicket` + Repository + contrat sérialisation | Backend |
| 3 | `WeighbridgeReaderInterface` + `RandomWeighbridgeReader` + `DsdAllocator` + endpoint `weighbridge_readings` | Backend |
| 4 | `WeighingTicketProvider` + `WeighingTicketProcessor` (numérotation, RG-5.03/5.05, normalisation) | Backend |
| 5 | Export XLSX | Backend |
| 6 | Tests PHPUnit RG-5.01→5.10 + capture contrat JSON | Backend |
| 6.bis (ERP-192) | **Bon de pesée — PDF via template Twig** (`/print.pdf`, § 2.12 / § 4.6) | **Backend (OWNER Tristan)** |
| 7 | Page liste `/weighing-tickets` (usePaginatedList) + export | Frontend |
| 8 | Écran Ajouter (formulaires vide + plein, pesée bascule/manuelle, masque immat) + ouverture PDF à la validation | Frontend |
| 9 | Écran Modification + bouton « Imprimer » (ouvre le PDF back) | Frontend |
| 10 | i18n + libellé audit + branchement site courant | Frontend |
+246
View File
@@ -0,0 +1,246 @@
---
# === IDENTITÉ ===
module: M5
nom: "Tickets de pesée"
ecran: tickets-pesee
owner_spec: Matthieu
backup_spec: Tristan
version: V0.1
date_redaction: 2026-06-17
# Historique :
# V0.1 (2026-06-17) — Restitution Markdown du docx « M5-ticket-de-pesee-V02 » (V0.2, 15/06/2026,
# validation client en attente) + maquette Figma (node 1322-16774). Précisions techniques (back)
# dans spec-back.md. Réutilise le pattern et les composants M1/M2/M3/M4.
# Maquette : les 2 blocs (vide + plein) portent « Pesée bascule » + « Pesée manuelle » ;
# contrepartie portée par le bloc « Poids à vide » ; net = plein vide (confirmé Matthieu).
# === LIENS ===
maquette_figma: "https://www.figma.com/design/jRYgT0T9c03VsEbjGhCwwS/Composants---Design-System?node-id=1322-16774&p=f&m=dev"
regles_metier: [RG-5.01, RG-5.02, RG-5.03, RG-5.04, RG-5.05, RG-5.06, RG-5.07, RG-5.08, RG-5.09, RG-5.10]
roles: [Admin, Bureau, Compta, Commerciale, Usine]
lien_spec_back: ./spec-back.md
# === VALIDATION CLIENT ===
client_validation_1:
statut: validee
version: V0.2
date_doc: 2026-06-15
date_validation: 2026-06-17
valide_par: "Matthieu (CP MALIO)"
# === LIEN LESSTIME ===
lesstime_project_id: 6
lesstime_taskgroup_id: 33 # M5 — Tickets de pesée (ERP-181 → ERP-192)
statut_global: pret_a_dev
---
# Module 5 — Tickets de pesée (V0.1 front)
> **Origine** : spec fonctionnelle `M5-ticket-de-pesee-V02` (V0.2, 15/06/2026, **validation client en attente**) + maquette Figma (node 1322-16774). Restitution Markdown pour intégration au workflow MALIO. Toute décision technique (back) vit dans [`spec-back.md`](./spec-back.md). Le M5 réutilise le pattern et les composants posés aux [M1 clients](../M1-clients/spec-front.md) → [M4 transporteurs](../M4-transporteurs/spec-front.md).
> **Nouveau module `Logistique`** (DÉCISION Matthieu 17/06). La maquette montre une section sidebar **Logistique** plus large (Réception, Expédition, Validations, Triage, **Ticket de pesée**, Bons…) ; **le M5 ne livre que l'écran « Ticket de pesée »**. Les autres items sont hors périmètre (modules/écrans ultérieurs).
> **Décisions (17/06)** : (1) **pont bascule = stub** renvoyant un poids aléatoire ∈ [10000, 50000] kg (pas de liaison matérielle — [`spec-back.md § 2.6`](./spec-back.md)) ; (2) **DSD = compteur de pesée** par site, +1 par pesée ([`§ 2.7`](./spec-back.md)) ; (3) **net = plein vide** ([`§ 2.8`](./spec-back.md)) ; (4) numéro **`{siteCode}-TP-{NNNN}` par site** ([`§ 2.5`](./spec-back.md)).
## But
Lister les tickets de pesée et accéder à leur fiche : consultation, création (pesée à vide + pesée à plein au pont bascule), modification, impression. Chaque ticket porte un **numéro unique par site** (ex. `86-TP-0001`) et une **contrepartie** Client / Fournisseur / Autre.
## Accès
- **Depuis** : menu principal → section **Logistique** → item **« Ticket de pesée »** (route `/weighing-tickets`).
- **Site** : l'écran dépend du **site courant** (sélecteur de site en haut de l'app — onglets `CHÂTELLERAULT` / `SAINT-JEAN` / `POMMEVIC`). Le site pilote la numérotation et (par défaut) le cloisonnement de la liste ([`spec-back.md § 2.3 / § 2.5`](./spec-back.md)).
- **Rôles autorisés** (tableau « Rôles & permissions » du docx p.3, V0.2) :
| Rôle | Consultation | Ajout / Modification |
|---|---|---|
| **Admin** | ✅ Tout | ✅ Tout |
| **Bureau** | ✅ Tout | ✅ Tout |
| **Usine** | ✅ Tout | ✅ Tout |
| **Compta** | ❌ | ❌ |
| **Commerciale** | ❌ | ❌ |
> **Notes** :
> - RBAC transposée sur `logistique.weighing_tickets.view` / `.manage` ([`spec-back.md § 5`](./spec-back.md)).
> - ⚠ **Changement vs M5 V0.1** : en **V0.2, Usine = Tout / Tout**. **Compta** et **Commerciale** n'ont **aucun** accès (item sidebar masqué).
## Navigation
Page d'entrée de l'écran : **datatable** « Tickets de pesées ».
- **Clic sur une ligne** → écran **Modification d'un ticket de pesée** (le docx ne prévoit pas d'écran de consultation séparé — clic = édition).
- **Bouton « + Ajouter »** (haut droite, si `manage`) → écran **Ajouter un ticket de pesée**.
- **Bouton « Exporter »** (bas de liste, maquette) → télécharge un **XLSX** de **toute la liste** (filtres + site courant appliqués). Format dans [`spec-back.md § 4.5`](./spec-back.md).
## Datatable des tickets
Composant : `<MalioDataTable>` branché sur `usePaginatedList<WeighingTicket>({ url: '/weighing_tickets' })` *(URL API en `snake_case` ; la route Nuxt reste `/weighing-tickets`)* (règle frontend obligatoire — pagination Hydra, état 100 % local). Colonnes (docx p.3 + maquette) :
| Colonne | Source | Tri |
|---|---|---|
| **Numéro** | `ticket.number` (`{siteCode}-TP-{NNNN}`) | DESC par défaut (plus récents en tête) |
| **Client** | `ticket.client.companyName` (vide si contrepartie ≠ Client) | Non |
| **Fournisseur** | `ticket.supplier.companyName` (vide si ≠ Fournisseur) | Non |
| **Autre** | `ticket.otherLabel` (vide si ≠ Autre) | Non |
| **Date** | `ticket.displayDate` (`fullDate ?? emptyDate`, format `JJ-MM-AAAA`) | Oui |
| **Poids** | `ticket.netWeight` (kg, = plein vide — RG-5.05) | Oui |
> **Clic ligne** → écran Modification. **Pagination** : standard Starseed 10 / 25 / 50 (défaut 10). Liste **cloisonnée par site courant** par défaut ([`spec-back.md § 2.3`](./spec-back.md)).
## Écran « Ajouter un ticket de pesée »
**Accès** : bouton « + Ajouter ». **Rôles** : Admin, Bureau, Usine.
**Titre** : « ← Ticket de pesée » (flèche retour vers la liste).
L'écran (maquette) est composé de **deux blocs empilés****« Poids à vide »** puis **« Poids à plein »** — et d'un bouton **« Valider »** en bas.
### Bloc « Poids à vide »
Boutons en haut à droite du bloc : **« Pesée bascule »** (`<MalioButton>` secondaire) + **« Pesée manuelle »** (`<MalioButton>` primaire).
**Champs** :
| Champ | Type composant | Obligatoire | Règle |
|---|---|---|---|
| **Fournisseur / Client / Autre** | `<MalioSelect>` (3 valeurs) | Oui | RG-5.03 — pilote le champ suivant |
| **Nom du fournisseur** | `<MalioSelect>` (liste fournisseurs M2) | Conditionnel | RG-5.03 — visible + obligatoire si « Fournisseur » |
| **Nom du client** | `<MalioSelect>` (liste clients M1) | Conditionnel | RG-5.03 — visible + obligatoire si « Client » |
| **Autre** | `<MalioInputText>` | Conditionnel | RG-5.03 — visible + obligatoire si « Autre » |
| **Date** | `<MalioInputText>` type `date` *(cf. note)* | Oui | RG-5.07 — **date du jour par défaut** |
| **Poids** | `<MalioInputNumber>` (suffixe « Kg ») | Oui | RG-5.07 — **readonly**, rempli par la pesée |
| **DSD** | `<MalioInputNumber>` | Oui | RG-5.04 / RG-5.07 — **readonly**, rempli par la pesée |
| **Immatriculation** | `<MalioInputText>` (masque `XX-000-XX`) | Oui | RG-5.01 |
| **Tout format** | `<MalioCheckbox>` | Non | RG-5.01 — désactive le masque |
> **La contrepartie (Fournisseur/Client/Autre) + son champ associé est portée par le bloc « Poids à vide » uniquement** (maquette) — c'est une donnée du ticket, pas répétée sur le bloc plein. Côté back : champs `counterpartyType` / `client` / `supplier` / `otherLabel` du ticket ([`spec-back.md § 2.9`](./spec-back.md)).
**Action « Enregistrer »** (sous le bloc, maquette) : POST `/api/weighing_tickets` (création initiale du ticket avec la pesée à vide) — [`spec-back.md § 4.3`](./spec-back.md). Le numéro `{siteCode}-TP-{NNNN}` est attribué serveur.
### Bloc « Poids à plein »
Mêmes boutons **« Pesée bascule »** + **« Pesée manuelle »**. **Champs** : Date (date du jour par défaut), Poids (readonly, Kg), DSD (readonly), Immatriculation (`XX-000-XX`), « Tout format ».
> **Immatriculation + « Tout format » connectés entre les 2 blocs** (RG-5.01) : une seule valeur partagée — modifier l'un met à jour l'autre (même véhicule). Géré dans `useWeighingTicketForm()` (état partagé).
### Boutons de pesée — comportement
| Bouton | Déclencheur | Comportement |
|---|---|---|
| **Pesée bascule** | clic | Ouvre une **modal de confirmation** « Êtes-vous sûr de vouloir déclencher une pesée ? » (`<MalioButton>` « Valider »). Si confirmé → `POST /api/weighbridge_readings { mode: 'AUTO' }` ([`spec-back.md § 4.2`](./spec-back.md)) → remplit **Poids** et **DSD** du bloc, ferme la modal. **En cas d'erreur** (RG-5.06) : le message d'erreur s'affiche **dans la modal** et invite à passer en **pesée manuelle**. *(Au M5, le stub renvoie toujours un poids ∈ [10000,50000] — le chemin d'erreur est néanmoins géré.)* |
| **Pesée manuelle** | clic | Ouvre une **modal « Pesée manuelle »** avec **Poids** et **Numéro de pesée** à saisir (`<MalioInputNumber>` + `<MalioInputText>`), bouton « Enregistrer ». Une fois validé → le **Poids** du bloc est rempli ; le **DSD** est **calculé automatiquement** = dernier dsd du site + 1 (`POST /api/weighbridge_readings { mode: 'MANUAL', weight, manualNumber }` — RG-5.04). |
### Action « Valider » (bas d'écran)
`<MalioButton>` « Valider » → finalise le ticket (PATCH `/api/weighing_tickets/{id}` avec la pesée à plein + recalcul du net — [`spec-back.md § 4.4`](./spec-back.md)) puis **ouvre la modal d'impression** du ticket (RG-5.08 — **bon d'impression réalisé par Tristan**, cf. § Modales).
## Écran « Modification d'un ticket de pesée »
**But** : modifier un ticket existant et/ou **imprimer** le ticket.
**Accès** : clic sur une ligne de la liste. **Rôles** : Admin, Bureau, Usine.
**Identique à l'écran d'ajout** — mêmes 2 blocs, mêmes règles (RG-5.01 → RG-5.10) — **sauf** (docx + maquette) :
- Les champs sont **pré-remplis** avec les valeurs actuelles.
- Le **bouton « Enregistrer » du bloc « Poids à vide » disparaît** (RG-5.08) — on enregistre via le bas d'écran.
- En bas : **« Enregistrer »** (remplace « Valider ») + **« Imprimer »** (bouton d'impression **absent à l'ajout**, RG-5.08).
- Le numéro et le site sont **immuables** (lecture seule).
## Modales
| Modale | Contenu | Source |
|---|---|---|
| **Confirmation pesée bascule** | « Êtes-vous sûr de vouloir déclencher une pesée ? » + bouton « Valider ». Erreur affichée inline → invite pesée manuelle (RG-5.06). | docx p.5 + maquette |
| **Pesée manuelle** | Champs « Poids » + « Numéro de pesée » + bouton « Enregistrer ». DSD auto = dernier +1 (RG-5.04). | docx p.5 + maquette |
| **Impression du ticket / bon de pesée** | Aperçu imprimable du ticket (numéro, contrepartie, immat, pesée vide/plein, net, DSD, date). **Réalisé par Tristan** (voir encadré ci-dessous). | docx p.5 / RG-5.08 ; [`spec-back.md § 2.12`](./spec-back.md) |
> **⚠ Bon d'impression = Tristan.** La conception et la réalisation du **bon d'impression** (gabarit du ticket de pesée, mise en page, déclenchement) sont **prises en charge par Tristan lui-même**, hors de la découpe front standard du M5. Le reste de l'écran (modale de confirmation, modale pesée manuelle, formulaires) reste dans la découpe M5.
> - **Déclencheur attendu** : modale d'impression à la **validation** (création) ; bouton **« Imprimer »** en **modification** (absent à l'ajout — RG-5.08).
> - **Données disponibles** : toute la réponse `GET /api/weighing_tickets/{id}` (numéro, site, contrepartie, immat, pesées vide/plein, net, DSD, dates) — [`spec-back.md § 2.12 / § 4.0`](./spec-back.md).
> - **Modales** : réutiliser le wrapper de modal partagé `frontend/shared/` (comme M1→M4).
## Composants UI à utiliser (`@malio/layer-ui`)
- **Datatable** : `<MalioDataTable>` (+ `usePaginatedList`)
- **Select** : `<MalioSelect>` (contrepartie, nom client, nom fournisseur)
- **Input texte** : `<MalioInputText>` (Autre, Immatriculation, Numéro de pesée)
- **Input nombre** : `<MalioInputNumber>` (Poids, DSD)
- **Checkbox** : `<MalioCheckbox>` (« Tout format »)
- **Bouton** : `<MalioButton>`, `<MalioButtonIcon>` (Pesée bascule, Pesée manuelle, Valider, Enregistrer, Imprimer, + Ajouter, Exporter)
- **Validation par champ** : `useFormErrors` (mapping 422 inline — règle frontend obligatoire)
- **Toasts** : standards via `useApi()`
**Exceptions autorisées** (commenter `// TODO migrer quand Malio couvre`) :
- **Date** : `<MalioInput>` ne couvrant pas `date` nativement, utiliser un `<input type="date">` encapsulé OU `MalioDate` si dispo (cf. exceptions @.claude/rules/frontend.md — type `date` explicitement listé comme exception tolérée).
- **Masque immatriculation `XX-000-XX`** : si non couvert par `<MalioInputText>`, masque local (directive) + `// TODO`. La validation de format reste **autoritaire côté serveur** (RG-5.01 / RG-5.10).
- **Modales** : wrapper partagé `frontend/shared/`.
## Composables & appels API
- `usePaginatedList<WeighingTicket>({ url: '/weighing_tickets' })` — liste paginée (obligatoire). Consomme `number`, `client`/`supplier`/`otherLabel`, `displayDate`, `netWeight` ([`spec-back.md § 4.0`](./spec-back.md)).
- `useWeighingTicket(id)` — charge le détail via `GET /api/weighing_tickets/{id}` (pesées vide + plein embarquées, client/supplier/site imbriqués). **DoD avant intégration** : vérifier le JSON réel ([`spec-back.md § 4.0.bis`](./spec-back.md)).
- `useWeighingTicketForm()` — workflow 2 blocs (POST à l'« Enregistrer » du bloc vide, PATCH au « Valider ») + **état partagé** immatriculation/« Tout format » entre les 2 blocs (RG-5.01) + gestion des champs conditionnels de contrepartie (RG-5.03).
- `useWeighbridge()` — déclenche la pesée : `POST /api/weighbridge_readings` (AUTO ou MANUAL), gère la modal de confirmation et le chemin d'erreur → pesée manuelle (RG-5.06).
- `useClientOptions()` / `useSupplierOptions()` — alimentent les selects (référentiels M1/M2 via `?pagination=false` — échappatoire selects).
- `useCurrentSite()` — site courant (sélecteur) — déjà exposé côté front (Sites). Le back lit le site courant pour la numérotation ; le front n'a pas à l'envoyer.
- `usePermissions()` — masque l'item sidebar et les boutons selon `logistique.weighing_tickets.view/manage`.
- Tous les appels passent par `useApi()` (jamais `$fetch` direct — règle ABSOLUE n°4).
## Règles de formatage et normalisation
Le serveur normalise systématiquement ([`spec-back.md § 6`](./spec-back.md)) :
| Champ | Normalisation serveur | Affichage front |
|---|---|---|
| Immatriculation | trim + UPPER ; format `XX-000-XX` sauf « Tout format » (RG-5.01) | UPPER, masqué |
| Autre (`otherLabel`) | trim | identique |
| Poids / DSD | entiers (kg) | « 7 150 Kg », DSD brut |
| Numéro de ticket | `{siteCode}-TP-{NNNN}` (serveur) | affiché tel quel |
> Le front **ne normalise pas** : il envoie la valeur saisie, le serveur normalise et renvoie la valeur que l'UI affiche.
## Différences notables avec les modules précédents
| Zone | M1→M4 | M5 tickets de pesée |
|---|---|---|
| Module | Commercial / Transport… | **Logistique** (nouveau, ERP à venir) |
| Saisie poids | — | **Pesée au pont bascule** (stub random) + pesée manuelle |
| Cloisonnement par site | M3 oui / M4 non | **Oui** (site courant) + numéro par site |
| Numérotation métier | id technique | **`{siteCode}-TP-{NNNN}`** par site (RG-5.02) |
| Onglets | présents | **Aucun onglet** : 2 blocs empilés (vide + plein) |
| Impression | aucune | **Modal d'impression** du ticket (RG-5.08) |
| Contrepartie | — | **Client / Fournisseur / Autre** (conditionnel, RG-5.03) |
## Points résolus côté back
| # | Zone d'ombre | Résolution (cf. `spec-back.md`) |
|---|---|---|
| 1 | Module | **Nouveau module `Logistique`** (§ 2.1) |
| 2 | Pont bascule | **Stub** poids aléatoire ∈ [10000,50000], interface réutilisable, driver réel HP (§ 2.6) |
| 3 | DSD | **Compteur de pesée par site**, +1 par pesée ; manuel = dernier +1 (§ 2.7) |
| 4 | Poids net | **plein vide**, calculé serveur (§ 2.8) |
| 5 | Numérotation | **`{siteCode}-TP-{NNNN}`** par site, séquence verrouillée (§ 2.5) ; ajout `site.code` |
| 6 | Contrepartie | `counterpartyType` + FK Client/Supplier ou `otherLabel` (RG-5.03, § 2.9) |
| 7 | Deux pesées | Colonnes plates `empty_*` / `full_*` ; les 2 blocs supportent bascule + manuelle (§ 2.4) |
| 8 | Impression | Modal d'impression front ; bouton dispo en modif seulement (RG-5.08, § 2.12) |
| 9 | Masque immat | `XX-000-XX` + « Tout format », connectés entre blocs (RG-5.01, § 2.10) |
| 10 | RBAC | `logistique.weighing_tickets.view/manage` ; Usine = Tout ; Compta + Commerciale sans accès (§ 5.2) |
---
## 📦 Tickets Lesstime générés
**TaskGroup Lesstime** : **#33 — M5 — Tickets de pesée** (projet `ERP / Starseed`, projectId=6) — créé le 17/06/2026, 12 tickets au statut « Prêt à dev ».
| # | ERP | Ticket | Effort | Tag |
|---|---|---|---|---|
| 1.1 | ERP-181 | Scaffolder le module Logistique + RBAC | M | Backend |
| 1.2 | ERP-182 | Migrer le schéma M5 (site.code, compteurs, weighing_ticket) | M | Backend |
| 1.3 | ERP-183 | Créer l'entité WeighingTicket + repository + contrat sérialisation | M | Backend |
| 1.4 | ERP-184 | Implémenter la pesée pont bascule (stub + DSD + endpoint) | M | Backend |
| 1.5 | ERP-185 | Créer Provider + Processor (numérotation, RG, normalisation) | L | Backend |
| 1.6 | ERP-186 | Implémenter l'export XLSX | S | Backend |
| 1.7 | ERP-187 | Tests PHPUnit RG-5.01→5.10 + capture contrat JSON | M | Backend |
| 1.8 | ERP-188 | Créer la page liste `/weighing-tickets` + export | M | Frontend |
| 1.9 | ERP-189 | Implémenter l'écran Ajouter (blocs vide+plein, pesée, masque immat) | L | Frontend |
| 1.10 | ERP-190 | Implémenter l'écran Modification + déclenchement impression | M | Frontend |
| 1.11 | ERP-191 | i18n + libellés + branchement site courant | S | Frontend |
| 1.12 | ERP-192 | **Bon d'impression du ticket de pesée — OWNER Tristan** | — | Frontend |
+105 -23
View File
@@ -39,6 +39,10 @@
"section": "Transport",
"carriers": "Répertoire transporteurs"
},
"logistique": {
"section": "Logistique",
"weighing_tickets": "Tickets de pesée"
},
"core": {
"roles": "Gestion des rôles",
"users": "Utilisateurs",
@@ -67,7 +71,7 @@
"companyName": "Nom",
"categories": "Catégories",
"sites": "Site",
"lastActivity": "Dernière activité"
"lastActivity": "Dernière modification"
},
"filters": {
"title": "Filtres",
@@ -211,7 +215,7 @@
"companyName": "Nom",
"categories": "Catégories",
"sites": "Site",
"lastActivity": "Dernière activité"
"lastActivity": "Dernière modification"
},
"filters": {
"title": "Filtres",
@@ -381,7 +385,7 @@
"companyName": "Nom",
"categories": "Catégories",
"sites": "Site",
"lastActivity": "Dernière activité"
"lastActivity": "Dernière modification"
},
"filters": {
"title": "Filtres",
@@ -505,7 +509,7 @@
"name": "Nom",
"certification": "Certification",
"validityDate": "Date de validité",
"lastActivity": "Dernière activité"
"lastActivity": "Dernière modification"
},
"certification": {
"QUALIMAT": "QUALIMAT",
@@ -529,7 +533,49 @@
"createSuccess": "Transporteur créé avec succès",
"integrateSuccess": "Transporteur QUALIMAT intégré",
"addressSaved": "Adresse enregistrée",
"contactSaved": "Contact enregistré"
"contactSaved": "Contact enregistré",
"priceSaved": "Prix enregistré",
"updateSuccess": "Transporteur mis à jour avec succès",
"archiveSuccess": "Transporteur archivé avec succès",
"restoreSuccess": "Transporteur restauré avec succès"
},
"action": {
"edit": "Modifier",
"archive": "Archiver",
"restore": "Restaurer"
},
"consultation": {
"title": "Consultation transporteur",
"back": "Retour au répertoire",
"loading": "Chargement du transporteur…",
"notFound": "Transporteur introuvable.",
"confirmArchive": {
"title": "Archiver le transporteur",
"message": "Ce transporteur n'apparaîtra plus dans le répertoire actif. Confirmer l'archivage ?"
},
"confirmRestore": {
"title": "Restaurer le transporteur",
"message": "Ce transporteur réapparaîtra dans le répertoire actif. Confirmer la restauration ?"
},
"price": {
"group": "Transport",
"carrier": "Fournisseurs / Clients",
"aproOrSite": "Adresse sites",
"delivery": "Adresse livraisons",
"forfait": "Forfait (€)",
"tonne": "Tonne (€)",
"indexation": "Indexation",
"state": "État du prix",
"export": "Exporter",
"empty": "Aucun prix pour ce transporteur."
}
},
"edit": {
"title": "Modifier le transporteur",
"back": "Retour à la consultation",
"loading": "Chargement du transporteur…",
"notFound": "Transporteur introuvable.",
"save": "Enregistrer"
},
"containerType": {
"BENNE": "Benne",
@@ -579,7 +625,8 @@
"dischargeRequired": "La décharge est obligatoire pour une certification « Autre ».",
"indexationRequired": "Le taux d'indexation est obligatoire pour un transporteur affrété.",
"containerTypeRequired": "Le type de contenant est obligatoire pour un transporteur affrété.",
"volumeRequired": "Le volume est obligatoire pour un transporteur affrété."
"volumeRequired": "Le volume est obligatoire pour un transporteur affrété.",
"uploadFailed": "Le téléversement de la décharge a échoué."
},
"address": {
"country": "Pays",
@@ -588,8 +635,6 @@
"street": "Adresse",
"streetComplement": "Adresse complémentaire",
"streetNotFound": "Adresse introuvable ? Saisissez-la directement.",
"add": "Nouvelle adresse",
"remove": "Supprimer l'adresse",
"degraded": "Service d'adresse indisponible : saisie de la ville et de l'adresse en mode libre."
},
"contact": {
@@ -608,6 +653,41 @@
"message": "Cette suppression est définitive. Confirmer ?",
"cancel": "Annuler",
"confirm": "Supprimer"
},
"price": {
"direction": "Sens",
"directionClient": "Client",
"directionSupplier": "Fournisseur",
"client": "Client",
"clientDeliveryAddress": "Adresse de livraison",
"departureSite": "Adresse de départ",
"supplier": "Fournisseur",
"supplierSupplyAddress": "Adresse d'approvisionnement",
"deliverySite": "Adresse de livraison",
"containerType": "Benne / Fond mouvant",
"pricingUnit": "Forfait / Tonne",
"pricingForfait": "Forfait",
"pricingTonne": "Tonne",
"price": "Prix",
"priceState": "État du prix",
"stateEnCours": "En cours",
"stateValide": "Validé",
"stateNonValide": "Non validé",
"add": "Nouveau prix",
"remove": "Supprimer le prix",
"errors": {
"direction": "Le sens du prix est obligatoire.",
"client": "Le client est obligatoire pour un prix client.",
"clientDeliveryAddress": "L'adresse de livraison du client est obligatoire pour un prix client.",
"departureSite": "Le site de départ est obligatoire pour un prix client.",
"supplier": "Le fournisseur est obligatoire pour un prix fournisseur.",
"supplierSupplyAddress": "L'adresse d'approvisionnement est obligatoire pour un prix fournisseur.",
"deliverySite": "Le site de livraison est obligatoire pour un prix fournisseur.",
"containerType": "Le type de contenant est obligatoire.",
"pricingUnit": "L'unité de tarification est obligatoire.",
"price": "Le prix est obligatoire.",
"priceState": "L'état du prix est obligatoire."
}
}
}
}
@@ -654,27 +734,28 @@
"delete": "Suppression"
},
"entity": {
"core_user": "Utilisateur",
"core_role": "Rôle",
"core_permission": "Permission",
"sites_site": "Site",
"catalog_category": "Catégorie",
"commercial_client": "Client",
"core_user": "Utilisateur",
"core_role": "Rôle",
"core_permission": "Permission",
"sites_site": "Site",
"catalog_category": "Catégorie",
"commercial_client": "Client",
"commercial_clientaddress": "Adresse client",
"commercial_clientcontact": "Contact client",
"commercial_clientrib": "RIB client",
"commercial_supplier": "Fournisseur",
"commercial_clientrib": "RIB client",
"commercial_supplier": "Fournisseur",
"commercial_supplieraddress": "Adresse fournisseur",
"commercial_suppliercontact": "Contact fournisseur",
"commercial_supplierrib": "RIB fournisseur",
"technique_provider": "Prestataire",
"technique_provider": "Prestataire",
"technique_provideraddress": "Adresse prestataire",
"technique_providercontact": "Contact prestataire",
"technique_providerrib": "RIB prestataire",
"transport_carrier": "Transporteur",
"transport_carrieraddress": "Adresse transporteur",
"transport_carriercontact": "Contact transporteur",
"transport_carrierprice": "Prix transporteur"
"technique_providerrib": "RIB prestataire",
"transport_carrier": "Transporteur",
"transport_carrieraddress": "Adresse transporteur",
"transport_carriercontact": "Contact transporteur",
"transport_carrierprice": "Prix transporteur",
"logistique_weighingticket": "Ticket de pesée"
},
"empty": "Aucune activité enregistrée",
"no_results": "Aucun résultat pour ces filtres",
@@ -709,7 +790,8 @@
"auth": {
"logout": "Deconnexion reussie"
},
"title": "Succès"
"title": "Succès",
"deleted": "Suppression effectuée"
},
"admin": {
"roles": {
@@ -2,7 +2,7 @@
<div class="relative 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)]">
<!-- ariaLabel via v-bind objet (prop camelCase ; aria-* serait un attribut HTML). -->
<MalioButtonIcon
v-if="removable && !readonly"
v-if="removable && !readonly && !disabled"
icon="mdi:delete-outline"
variant="ghost"
button-class="absolute top-3 right-3"
@@ -21,7 +21,8 @@
:options="addressTypeOptions"
:label="t('commercial.clients.form.address.addressType')"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.isProspect"
@update:model-value="onAddressTypeChange"
/>
@@ -33,7 +34,8 @@
:label="t('commercial.clients.form.address.sites')"
:display-tag="true"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.sites"
@update:model-value="(v: (string | number)[]) => update('siteIris', v.map(String))"
/>
@@ -44,6 +46,7 @@
:label="t('commercial.clients.form.address.contacts')"
:display-tag="true"
:readonly="readonly"
:disabled="disabled"
@update:model-value="(v: (string | number)[]) => update('contactIris', v.map(String))"
/>
@@ -55,8 +58,9 @@
v-if="isBillingEmailRequired(model)"
:model-value="model.billingEmail"
:label="t('commercial.clients.form.address.billingEmail')"
:required="true"
:required="!readonly && !disabled"
:readonly="readonly"
:disabled="disabled"
:lowercase="true"
:error="errors?.billingEmail"
:addable="!model.hasSecondaryBillingEmail && !readonly"
@@ -71,6 +75,7 @@
:model-value="model.billingEmailSecondary"
:label="t('commercial.clients.form.address.billingEmailSecondary')"
:readonly="readonly"
:disabled="disabled"
:lowercase="true"
:error="errors?.billingEmailSecondary"
@update:model-value="(v: string) => update('billingEmailSecondary', v)"
@@ -82,7 +87,8 @@
:label="t('commercial.clients.form.address.categories')"
:display-tag="true"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.categories"
@update:model-value="(v: (string | number)[]) => update('categoryIris', v.map(String))"
/>
@@ -92,7 +98,8 @@
:options="countryOptions"
:label="t('commercial.clients.form.address.country')"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
@update:model-value="(v: string | number | null) => update('country', String(v ?? 'France'))"
/>
@@ -101,7 +108,8 @@
:label="t('commercial.clients.form.address.postalCode')"
:mask="POSTAL_CODE_MASK"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.postalCode"
@update:model-value="onPostalCodeChange"
/>
@@ -115,8 +123,9 @@
:options="cityOptions"
:label="t('commercial.clients.form.address.city')"
:readonly="readonly"
:disabled="disabled"
empty-option-label=""
:required="true"
:required="!readonly && !disabled"
:error="errors?.city"
@update:model-value="(v: string | number | null) => update('city', v === null ? null : String(v))"
/>
@@ -124,8 +133,10 @@
v-else
:model-value="model.city"
:label="t('commercial.clients.form.address.city')"
:mask="ADDRESS_MASK"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.city"
@update:model-value="(v: string) => update('city', v)"
/>
@@ -142,14 +153,15 @@
blur/Entree (saisie manuelle) — sinon il serait efface. La ville reste
pilotee par le code postal ; choisir une suggestion remplit rue+ville+CP. -->
<MalioInputAutocomplete
v-if="!readonly"
v-if="!readonly && !disabled"
:model-value="model.street"
:options="addressOptions"
:loading="addressLoading"
:min-search-length="3"
:label="t('commercial.clients.form.address.street')"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.street"
:allow-create="true"
:no-results-text="t('commercial.clients.form.address.streetNotFound')"
@@ -162,7 +174,8 @@
:model-value="model.street"
:label="t('commercial.clients.form.address.street')"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.street"
@update:model-value="(v: string) => update('street', v)"
/>
@@ -172,7 +185,9 @@
<MalioInputText
:model-value="model.streetComplement"
:label="t('commercial.clients.form.address.streetComplement')"
:mask="ADDRESS_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.streetComplement"
@update:model-value="(v: string) => update('streetComplement', v)"
/>
@@ -191,6 +206,7 @@ import {
import { useAddressAutocomplete, type AddressSuggestion } from '~/shared/composables/useAddressAutocomplete'
import type { CategoryOption, RefOption } from '~/modules/commercial/composables/useClientReferentials'
import type { AddressFormDraft } from '~/modules/commercial/types/clientForm'
import { ADDRESS_MASK } from '~/shared/utils/textSanitize'
// Masque code postal FR : 5 chiffres.
const POSTAL_CODE_MASK = '#####'
@@ -209,6 +225,8 @@ const props = defineProps<{
countryOptions: RefOption[]
removable?: boolean
readonly?: boolean
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
disabled?: boolean
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
errors?: Record<string, string>
}>()
@@ -284,6 +302,11 @@ const addressLoading = ref(false)
// Conserve les suggestions d'adresse pour retrouver ville/CP au moment du select.
let lastAddressSuggestions: AddressSuggestion[] = []
// Filtrage des caracteres parasites : porte par le mask ADDRESS_MASK (maska) sur
// les champs texte editables (complement, ville en mode degrade). La voie en
// autocomplete (BAN) et la ville en select ne sont pas masquees (le back valide
// via Assert\Regex) ; les emails de facturation valident leur format (Assert\Email).
/** Emet un nouveau brouillon avec le champ modifie (immutabilite). */
function update<K extends keyof AddressFormDraft>(field: K, value: AddressFormDraft[K]): void {
emit('update:modelValue', { ...props.modelValue, [field]: value })
@@ -4,7 +4,7 @@
non supprimable (1er bloc obligatoire RG-1.14) ou en lecture seule.
ariaLabel via v-bind objet (prop camelCase ; aria-* serait un attribut HTML). -->
<MalioButtonIcon
v-if="removable && !readonly"
v-if="removable && !readonly && !disabled"
icon="mdi:delete-outline"
variant="ghost"
button-class="absolute top-3 right-3"
@@ -15,14 +15,18 @@
<MalioInputText
:model-value="model.lastName"
:label="t('commercial.clients.form.contact.lastName')"
:mask="PERSON_NAME_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.lastName"
@update:model-value="(v: string) => update('lastName', v)"
/>
<MalioInputText
:model-value="model.firstName"
:label="t('commercial.clients.form.contact.firstName')"
:mask="PERSON_NAME_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.firstName"
@update:model-value="(v: string) => update('firstName', v)"
/>
@@ -33,7 +37,9 @@
<MalioInputText
:model-value="model.jobTitle"
:label="t('commercial.clients.form.contact.jobTitle')"
:mask="FREE_TEXT_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.jobTitle"
@update:model-value="(v: string) => update('jobTitle', v)"
/>
@@ -42,6 +48,7 @@
:model-value="model.email"
:label="t('commercial.clients.form.contact.email')"
:readonly="readonly"
:disabled="disabled"
:lowercase="true"
:error="errors?.email"
@update:model-value="(v: string) => update('email', v)"
@@ -51,6 +58,7 @@
:label="t('commercial.clients.form.contact.phonePrimary')"
:mask="PHONE_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.phonePrimary"
:addable="!model.hasSecondaryPhone && !readonly"
:add-button-label="t('commercial.clients.form.contact.addPhone')"
@@ -63,6 +71,7 @@
:label="t('commercial.clients.form.contact.phoneSecondary')"
:mask="PHONE_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.phoneSecondary"
@update:model-value="(v: string) => update('phoneSecondary', v)"
/>
@@ -71,6 +80,7 @@
<script setup lang="ts">
import type { ContactFormDraft } from '~/modules/commercial/types/clientForm'
import { FREE_TEXT_MASK, PERSON_NAME_MASK } from '~/shared/utils/textSanitize'
// Masque telephone FR : 5 groupes de 2 chiffres (la normalisation finale reste
// serveur, cf. formatPhoneFR re-applique a la valeur renvoyee).
@@ -85,6 +95,8 @@ const props = defineProps<{
removable?: boolean
/** Bloc en lecture seule (onglet valide). */
readonly?: boolean
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
disabled?: boolean
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
errors?: Record<string, string>
}>()
@@ -99,6 +111,10 @@ const { t } = useI18n()
// Alias local pour la lisibilite du template.
const model = computed(() => props.modelValue)
// Filtrage des caracteres parasites : porte par les masks maska sur les champs
// (PERSON_NAME_MASK / FREE_TEXT_MASK), filtrage natif au focus/curseur. L'email n'a
// pas de mask (ERP-101 : validation de format via Assert\Email + erreur inline).
/** Emet un nouveau brouillon avec le champ modifie (immutabilite). */
function update<K extends keyof ContactFormDraft>(field: K, value: ContactFormDraft[K]): void {
emit('update:modelValue', { ...props.modelValue, [field]: value })
@@ -2,7 +2,7 @@
<div class="relative 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)]">
<!-- Suppression : modal de confirmation cote parent. -->
<MalioButtonIcon
v-if="removable && !readonly"
v-if="removable && !readonly && !disabled"
icon="mdi:delete-outline"
variant="ghost"
button-class="absolute top-3 right-3"
@@ -18,8 +18,9 @@
:options="addressTypeOptions"
:label="t('commercial.suppliers.form.address.addressType')"
:readonly="readonly"
:disabled="disabled"
empty-option-label=""
:required="true"
:required="!readonly && !disabled"
:error="errors?.addressType"
@update:model-value="(v: string | number | null) => update('addressType', v === null ? null : (v as SupplierAddressType))"
/>
@@ -31,7 +32,8 @@
:label="t('commercial.suppliers.form.address.sites')"
:display-tag="true"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.sites"
@update:model-value="(v: (string | number)[]) => update('siteIris', v.map(String))"
/>
@@ -43,6 +45,7 @@
:label="t('commercial.suppliers.form.address.contacts')"
:display-tag="true"
:readonly="readonly"
:disabled="disabled"
@update:model-value="(v: (string | number)[]) => update('contactIris', v.map(String))"
/>
@@ -57,7 +60,8 @@
:label="t('commercial.suppliers.form.address.categories')"
:display-tag="true"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.categories"
@update:model-value="(v: (string | number)[]) => update('categoryIris', v.map(String))"
/>
@@ -67,7 +71,8 @@
:options="countryOptions"
:label="t('commercial.suppliers.form.address.country')"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
@update:model-value="(v: string | number | null) => update('country', String(v ?? 'France'))"
/>
@@ -76,7 +81,8 @@
:label="t('commercial.suppliers.form.address.postalCode')"
:mask="POSTAL_CODE_MASK"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.postalCode"
@update:model-value="onPostalCodeChange"
/>
@@ -88,8 +94,9 @@
:options="cityOptions"
:label="t('commercial.suppliers.form.address.city')"
:readonly="readonly"
:disabled="disabled"
empty-option-label=""
:required="true"
:required="!readonly && !disabled"
:error="errors?.city"
@update:model-value="(v: string | number | null) => update('city', v === null ? null : String(v))"
/>
@@ -97,8 +104,10 @@
v-else
:model-value="model.city"
:label="t('commercial.suppliers.form.address.city')"
:mask="ADDRESS_MASK"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.city"
@update:model-value="(v: string) => update('city', v)"
/>
@@ -107,14 +116,15 @@
texte saisi est conserve si la BAN ne propose rien (saisie manuelle). -->
<div class="col-span-2">
<MalioInputAutocomplete
v-if="!readonly"
v-if="!readonly && !disabled"
:model-value="model.street"
:options="addressOptions"
:loading="addressLoading"
:min-search-length="3"
:label="t('commercial.suppliers.form.address.street')"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.street"
:allow-create="true"
:no-results-text="t('commercial.suppliers.form.address.streetNotFound')"
@@ -126,8 +136,10 @@
v-else
:model-value="model.street"
:label="t('commercial.suppliers.form.address.street')"
:mask="ADDRESS_MASK"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.street"
@update:model-value="(v: string) => update('street', v)"
/>
@@ -137,7 +149,9 @@
<MalioInputText
:model-value="model.streetComplement"
:label="t('commercial.suppliers.form.address.streetComplement')"
:mask="ADDRESS_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.streetComplement"
@update:model-value="(v: string) => update('streetComplement', v)"
/>
@@ -149,6 +163,7 @@
:label="t('commercial.suppliers.form.address.bennes')"
:min="0"
:readonly="readonly"
:disabled="disabled"
:error="errors?.bennes"
@update:model-value="(v: string) => update('bennes', v)"
/>
@@ -160,6 +175,7 @@
:model-value="model.triageProvider"
group-class="self-center"
:readonly="readonly"
:disabled="disabled"
@update:model-value="(v: boolean) => update('triageProvider', v)"
/>
</div>
@@ -169,6 +185,7 @@
import { useAddressAutocomplete, type AddressSuggestion } from '~/shared/composables/useAddressAutocomplete'
import type { CategoryOption, RefOption } from '~/modules/commercial/composables/useSupplierReferentials'
import type { SupplierAddressFormDraft, SupplierAddressType } from '~/modules/commercial/types/supplierForm'
import { ADDRESS_MASK } from '~/shared/utils/textSanitize'
// Masque code postal FR : 5 chiffres.
const POSTAL_CODE_MASK = '#####'
@@ -187,6 +204,8 @@ const props = defineProps<{
countryOptions: RefOption[]
removable?: boolean
readonly?: boolean
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
disabled?: boolean
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
errors?: Record<string, string>
}>()
@@ -238,6 +257,11 @@ const addressLoading = ref(false)
// Conserve les suggestions d'adresse pour retrouver ville/CP au moment du select.
let lastAddressSuggestions: AddressSuggestion[] = []
// Filtrage des caracteres parasites : porte par le mask ADDRESS_MASK (maska) sur
// les champs texte editables (complement, ville en mode degrade, voie en repli). La
// voie en autocomplete (BAN) et la ville en select ne sont pas masquees (le back
// valide via Assert\Regex).
/** Emet un nouveau brouillon avec le champ modifie (immutabilite). */
function update<K extends keyof SupplierAddressFormDraft>(field: K, value: SupplierAddressFormDraft[K]): void {
emit('update:modelValue', { ...props.modelValue, [field]: value })
@@ -3,7 +3,7 @@
<!-- Suppression : ouvre une modal de confirmation cote parent. Masquee si
non supprimable (1er bloc, RG-2.13) ou en lecture seule. -->
<MalioButtonIcon
v-if="removable && !readonly"
v-if="removable && !readonly && !disabled"
icon="mdi:delete-outline"
variant="ghost"
button-class="absolute top-3 right-3"
@@ -14,14 +14,18 @@
<MalioInputText
:model-value="model.lastName"
:label="t('commercial.suppliers.form.contact.lastName')"
:mask="PERSON_NAME_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.lastName"
@update:model-value="(v: string) => update('lastName', v)"
/>
<MalioInputText
:model-value="model.firstName"
:label="t('commercial.suppliers.form.contact.firstName')"
:mask="PERSON_NAME_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.firstName"
@update:model-value="(v: string) => update('firstName', v)"
/>
@@ -32,7 +36,9 @@
<MalioInputText
:model-value="model.jobTitle"
:label="t('commercial.suppliers.form.contact.jobTitle')"
:mask="FREE_TEXT_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.jobTitle"
@update:model-value="(v: string) => update('jobTitle', v)"
/>
@@ -41,6 +47,7 @@
:model-value="model.email"
:label="t('commercial.suppliers.form.contact.email')"
:readonly="readonly"
:disabled="disabled"
:lowercase="true"
:error="errors?.email"
@update:model-value="(v: string) => update('email', v)"
@@ -50,6 +57,7 @@
:label="t('commercial.suppliers.form.contact.phonePrimary')"
:mask="PHONE_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.phonePrimary"
:addable="!model.hasSecondaryPhone && !readonly"
:add-button-label="t('commercial.suppliers.form.contact.addPhone')"
@@ -62,6 +70,7 @@
:label="t('commercial.suppliers.form.contact.phoneSecondary')"
:mask="PHONE_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.phoneSecondary"
@update:model-value="(v: string) => update('phoneSecondary', v)"
/>
@@ -70,6 +79,7 @@
<script setup lang="ts">
import type { SupplierContactFormDraft } from '~/modules/commercial/types/supplierForm'
import { FREE_TEXT_MASK, PERSON_NAME_MASK } from '~/shared/utils/textSanitize'
// Masque telephone FR : 5 groupes de 2 chiffres (la normalisation finale reste serveur).
const PHONE_MASK = '## ## ## ## ##'
@@ -83,6 +93,8 @@ const props = defineProps<{
removable?: boolean
/** Bloc en lecture seule (onglet valide). */
readonly?: boolean
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
disabled?: boolean
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
errors?: Record<string, string>
}>()
@@ -97,6 +109,10 @@ const { t } = useI18n()
// Alias local pour la lisibilite du template.
const model = computed(() => props.modelValue)
// Filtrage des caracteres parasites : porte par les masks maska sur les champs
// (PERSON_NAME_MASK / FREE_TEXT_MASK), filtrage natif au focus/curseur. L'email n'a
// pas de mask (ERP-101 : validation de format via Assert\Email + erreur inline).
/** Emet un nouveau brouillon avec le champ modifie (immutabilite). */
function update<K extends keyof SupplierContactFormDraft>(field: K, value: SupplierContactFormDraft[K]): void {
emit('update:modelValue', { ...props.modelValue, [field]: value })
@@ -25,8 +25,8 @@ function makeHydra(total: number): HydraCollection<Client> {
describe('useClientsRepository', () => {
beforeEach(() => {
mockGet.mockReset()
// 25 items → 3 pages a 10/page : permet de tester la navigation page 2.
mockGet.mockResolvedValue(makeHydra(25))
// 60 items → 3 pages a 25/page : permet de tester la navigation page 2.
mockGet.mockResolvedValue(makeHydra(60))
})
it('cible la ressource /clients en page 1 par defaut', async () => {
@@ -35,7 +35,7 @@ describe('useClientsRepository', () => {
expect(mockGet).toHaveBeenLastCalledWith(
'/clients',
{ page: 1, itemsPerPage: 10 },
{ page: 1, itemsPerPage: 25 },
expect.objectContaining({ toast: false }),
)
})
@@ -65,7 +65,7 @@ describe('useClientsRepository', () => {
'siteId[]': ['1', '2'],
archivedOnly: true,
page: 1,
itemsPerPage: 10,
itemsPerPage: 25,
},
expect.objectContaining({ toast: false }),
)
@@ -78,7 +78,7 @@ describe('useClientsRepository', () => {
expect(mockGet).toHaveBeenLastCalledWith(
'/clients',
{ page: 1, itemsPerPage: 10 },
{ page: 1, itemsPerPage: 25 },
expect.objectContaining({ toast: false }),
)
})
@@ -25,8 +25,8 @@ function makeHydra(total: number): HydraCollection<Supplier> {
describe('useSuppliersRepository', () => {
beforeEach(() => {
mockGet.mockReset()
// 25 items → 3 pages a 10/page : permet de tester la navigation page 2.
mockGet.mockResolvedValue(makeHydra(25))
// 60 items → 3 pages a 25/page : permet de tester la navigation page 2.
mockGet.mockResolvedValue(makeHydra(60))
})
it('cible la ressource /suppliers en page 1 par defaut', async () => {
@@ -35,7 +35,7 @@ describe('useSuppliersRepository', () => {
expect(mockGet).toHaveBeenLastCalledWith(
'/suppliers',
{ page: 1, itemsPerPage: 10 },
{ page: 1, itemsPerPage: 25 },
expect.objectContaining({ toast: false }),
)
})
@@ -65,7 +65,7 @@ describe('useSuppliersRepository', () => {
'siteId[]': ['86', '17'],
archivedOnly: true,
page: 1,
itemsPerPage: 10,
itemsPerPage: 25,
},
expect.objectContaining({ toast: false }),
)
@@ -78,7 +78,7 @@ describe('useSuppliersRepository', () => {
expect(mockGet).toHaveBeenLastCalledWith(
'/suppliers',
{ page: 1, itemsPerPage: 10 },
{ page: 1, itemsPerPage: 25 },
expect.objectContaining({ toast: false }),
)
})
@@ -49,5 +49,6 @@ export interface Client {
* gerer.
*/
export function useClientsRepository() {
return usePaginatedList<Client>({ url: '/clients' })
// Pagination par defaut a 25 sur le repertoire (retour metier ERP-193).
return usePaginatedList<Client>({ url: '/clients', defaultItemsPerPage: 25 })
}
@@ -51,5 +51,6 @@ export interface Supplier {
* `usePaginatedList`. Aucun reset au logout a gerer.
*/
export function useSuppliersRepository() {
return usePaginatedList<Supplier>({ url: '/suppliers' })
// Pagination par defaut a 25 sur le repertoire (retour metier ERP-193).
return usePaginatedList<Supplier>({ url: '/suppliers', defaultItemsPerPage: 25 })
}
@@ -25,9 +25,10 @@
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
<MalioInputText
v-model="main.companyName"
:mask="FREE_TEXT_MASK"
:label="t('commercial.clients.form.main.companyName')"
:required="true"
:readonly="businessReadonly"
:disabled="businessReadonly"
:error="mainErrors.errors.companyName"
/>
<MalioSelectCheckbox
@@ -35,7 +36,7 @@
:options="mainCategoryOptions"
:label="t('commercial.clients.form.main.categories')"
:display-tag="true"
:readonly="businessReadonly"
:disabled="businessReadonly"
:required="true"
:error="mainErrors.errors.categories"
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
@@ -46,7 +47,7 @@
:options="relationOptions"
:label="t('commercial.clients.form.main.relation')"
:empty-option-label="t('commercial.clients.form.main.relationNone')"
:readonly="businessReadonly"
:disabled="businessReadonly"
@update:model-value="onRelationChange"
/>
<MalioSelect
@@ -54,7 +55,7 @@
:model-value="main.brokerIri"
:options="brokerOptions"
:label="t('commercial.clients.form.main.brokerName')"
:readonly="businessReadonly"
:disabled="businessReadonly"
:required="true"
:error="mainErrors.errors.broker"
@update:model-value="(v: string | number | null) => main.brokerIri = v === null ? null : String(v)"
@@ -64,7 +65,7 @@
:model-value="main.distributorIri"
:options="distributorOptions"
:label="t('commercial.clients.form.main.distributorName')"
:readonly="businessReadonly"
:disabled="businessReadonly"
:required="true"
:error="mainErrors.errors.distributor"
@update:model-value="(v: string | number | null) => main.distributorIri = v === null ? null : String(v)"
@@ -74,7 +75,7 @@
v-model="main.triageService"
:label="t('commercial.clients.form.main.triageService')"
group-class="self-center"
:readonly="businessReadonly"
:disabled="businessReadonly"
/>
</div>
@@ -101,20 +102,24 @@
resize="none"
group-class="row-span-2 pt-1 pb-1"
text-input="h-full text-lg"
:readonly="businessReadonly"
:disabled="businessReadonly"
:error="informationErrors.errors.description"
/>
<MalioInputText
v-model="information.competitors"
:mask="FREE_TEXT_MASK"
:label="t('commercial.clients.form.information.competitors')"
:readonly="businessReadonly"
:disabled="businessReadonly"
:error="informationErrors.errors.competitors"
/>
<!-- Date de creation jamais dans le futur (ERP-193) : :max plafonne
le calendrier a aujourd'hui et invalide une saisie future. -->
<MalioDate
v-model="information.foundedAt"
:label="t('commercial.clients.form.information.foundedAt')"
:readonly="businessReadonly"
:disabled="businessReadonly"
:editable="true"
:max="maxFoundedAt"
:error="informationErrors.errors.foundedAt"
@update:raw-value="(v: string) => information.foundedAtRaw = v"
/>
@@ -122,25 +127,30 @@
v-model="information.employeesCount"
:label="t('commercial.clients.form.information.employeesCount')"
:mask="EMPLOYEES_MASK"
:readonly="businessReadonly"
:disabled="businessReadonly"
:error="informationErrors.errors.employeesCount"
/>
<!-- CA plafonne a 999 999 999 999,99 (ERP-193) : clamp a la saisie,
:key force le re-affichage quand on plafonne (modelValue inchange). -->
<MalioInputAmount
v-model="information.revenueAmount"
:key="revenueAmountKey"
:model-value="information.revenueAmount"
:label="t('commercial.clients.form.information.revenueAmount')"
:readonly="businessReadonly"
:disabled="businessReadonly"
:error="informationErrors.errors.revenueAmount"
@update:model-value="onRevenueAmountInput"
/>
<MalioInputText
v-model="information.directorName"
:mask="PERSON_NAME_MASK"
:label="t('commercial.clients.form.information.directorName')"
:readonly="businessReadonly"
:disabled="businessReadonly"
:error="informationErrors.errors.directorName"
/>
<MalioInputAmount
v-model="information.profitAmount"
:label="t('commercial.clients.form.information.profitAmount')"
:readonly="businessReadonly"
:disabled="businessReadonly"
:error="informationErrors.errors.profitAmount"
/>
</div>
@@ -167,7 +177,7 @@
:model-value="contact"
:title="t('commercial.clients.form.contact.title', { n: index + 1 })"
:removable="isRowRemovable(contacts, index)"
:readonly="businessReadonly"
:disabled="businessReadonly"
:errors="contactErrors[index]"
@update:model-value="(v) => contacts[index] = v"
@remove="askRemoveContact(index)"
@@ -204,7 +214,7 @@
:contact-options="contactOptions"
:country-options="countryOptions"
:removable="isRowRemovable(addresses, index)"
:readonly="businessReadonly"
:disabled="businessReadonly"
:errors="addressErrors[index]"
@update:model-value="(v) => addresses[index] = v"
@remove="askRemoveAddress(index)"
@@ -239,14 +249,15 @@
v-model="accounting.siren"
:label="t('commercial.clients.form.accounting.siren')"
:mask="SIREN_MASK"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.siren"
/>
<MalioInputText
v-model="accounting.accountNumber"
:mask="CODE_ALNUM_MASK"
:label="t('commercial.clients.form.accounting.accountNumber')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.accountNumber"
/>
@@ -254,7 +265,7 @@
:model-value="accounting.tvaModeIri"
:options="tvaModeOptions"
:label="t('commercial.clients.form.accounting.tvaMode')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.tvaMode"
@@ -262,8 +273,9 @@
/>
<MalioInputText
v-model="accounting.nTva"
:mask="CODE_ALNUM_MASK"
:label="t('commercial.clients.form.accounting.nTva')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.nTva"
/>
@@ -271,7 +283,7 @@
:model-value="accounting.paymentDelayIri"
:options="paymentDelayOptions"
:label="t('commercial.clients.form.accounting.paymentDelay')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.paymentDelay"
@@ -281,7 +293,7 @@
:model-value="accounting.paymentTypeIri"
:options="paymentTypeOptions"
:label="t('commercial.clients.form.accounting.paymentType')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.paymentType"
@@ -292,7 +304,7 @@
:model-value="accounting.bankIri"
:options="bankOptions"
:label="t('commercial.clients.form.accounting.bank')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.bank"
@@ -319,21 +331,23 @@
<MalioInputText
v-model="rib.label"
:label="t('commercial.clients.form.accounting.ribLabel')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="isRibRequired"
:error="ribErrors[index]?.label"
/>
<MalioInputText
v-model="rib.bic"
:mask="CODE_ALNUM_MASK"
:label="t('commercial.clients.form.accounting.ribBic')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="isRibRequired"
:error="ribErrors[index]?.bic"
/>
<MalioInputText
v-model="rib.iban"
:mask="CODE_ALNUM_MASK"
:label="t('commercial.clients.form.accounting.ribIban')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="isRibRequired"
:error="ribErrors[index]?.iban"
/>
@@ -423,6 +437,9 @@ import {
type InformationFormDraft,
type MainFormDraft,
} from '~/modules/commercial/utils/forms/clientEdit'
import { clampRevenueAmount } from '~/modules/commercial/utils/forms/amountInput'
import { todayIso } from '~/shared/utils/date'
import { CODE_ALNUM_MASK, FREE_TEXT_MASK, PERSON_NAME_MASK } from '~/shared/utils/textSanitize'
import {
buildClientFormTabKeys,
isAddressValid,
@@ -491,6 +508,22 @@ const headerTitle = computed(() => client.value?.companyName ?? t('commercial.cl
const main = reactive<MainFormDraft>(mapMainDraft({} as ClientDetail))
const information = reactive<InformationFormDraft>(mapInformationDraft({} as ClientDetail))
const accounting = reactive<AccountingFormDraft>(mapAccountingFormDraft({} as ClientDetail))
// Borne haute de la date de creation : aujourd'hui (ERP-193, pas de date future).
const maxFoundedAt = todayIso()
// CA plafonne a 999 999 999 999,99 (ERP-193). La :key force le re-affichage du
// champ controle quand le plafonnement laisse le modelValue inchange.
const revenueAmountKey = ref(0)
/** Saisie du CA : plafonne au maximum metier et re-synchronise le champ si plafonne. */
function onRevenueAmountInput(value: string | null): void {
const clamped = clampRevenueAmount(value)
information.revenueAmount = clamped ?? null
if (clamped !== value) {
revenueAmountKey.value += 1
}
}
const contacts = ref<ContactFormDraft[]>([])
const addresses = ref<AddressFormDraft[]>([])
const ribs = ref<RibFormDraft[]>([])
@@ -668,6 +701,11 @@ function showError(e: unknown, opts: { duplicateCompany?: boolean } = {}): void
})
}
/** Toast de succès après suppression serveur confirmée d'un bloc (contact / adresse / RIB). */
function notifyRemovalSuccess(): void {
toast.success({ title: t('success.title'), message: t('success.deleted') })
}
// ── Erreurs de validation par champ (ERP-101) ───────────────────────────────
// Etat d'erreurs factorise avec l'ecran de creation (cf. useClientFormErrors) :
// un `useFormErrors` par groupe scalaire + un tableau d'erreurs par ligne pour
@@ -767,6 +805,7 @@ function askRemoveContact(index: number): void {
deleteRow: url => api.delete(url, {}, { toast: false }),
makeEmpty: emptyContact,
onError: showError,
onSuccess: notifyRemovalSuccess,
}))
}
@@ -844,6 +883,7 @@ function askRemoveAddress(index: number): void {
deleteRow: url => api.delete(url, {}, { toast: false }),
makeEmpty: emptyAddress,
onError: showError,
onSuccess: notifyRemovalSuccess,
}))
}
@@ -944,6 +984,7 @@ function askRemoveRib(index: number): void {
deleteRow: url => api.delete(url, {}, { toast: false }),
makeEmpty: emptyRib,
onError: showError,
onSuccess: notifyRemovalSuccess,
}))
}
@@ -23,7 +23,7 @@
/>
<MalioButton
v-if="showArchive"
variant="secondary"
variant="danger"
icon-name="mdi:archive-arrow-down-outline"
icon-position="left"
:label="t('commercial.clients.action.archive')"
@@ -50,14 +50,14 @@
<MalioInputText
:model-value="client.companyName"
:label="t('commercial.clients.form.main.companyName')"
readonly
disabled
/>
<MalioSelectCheckbox
:model-value="categoryIris"
:options="mainCategoryOptions"
:label="t('commercial.clients.form.main.categories')"
:display-tag="true"
readonly
disabled
/>
<!-- Relation toujours affichee (vide = « Aucun »), comme en edition. -->
<MalioSelect
@@ -65,7 +65,7 @@
:options="relationOptions"
:label="t('commercial.clients.form.main.relation')"
:empty-option-label="t('commercial.clients.form.main.relationNone')"
readonly
disabled
/>
<!-- Nom du distributeur/courtier : conditionnel (libelle type-dependant,
aucune valeur sans relation meme comportement qu'en edition). -->
@@ -73,18 +73,20 @@
v-if="relation.type"
:model-value="relation.name"
:label="relation.type === 'distributeur' ? t('commercial.clients.form.main.distributorName') : t('commercial.clients.form.main.brokerName')"
readonly
disabled
/>
<MalioCheckbox
:model-value="client.triageService === true"
:label="t('commercial.clients.form.main.triageService')"
group-class="self-center"
readonly
disabled
/>
</div>
<!-- ── Onglets (navigation libre, tout en lecture seule) ─────────── -->
<MalioTabList v-model="activeTab" :tabs="tabs" :max-visible-tabs="5" :max-width="1100" class="mt-[60px]">
<!-- ERP-193 : on n'affiche la barre que s'il reste au moins un onglet
non vide (sinon seul le bloc principal est visible). -->
<MalioTabList v-if="visibleTabKeys.length" v-model="activeTab" :tabs="tabs" :max-visible-tabs="5" :max-width="1100" class="mt-[60px]">
<!-- 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)]">
@@ -97,37 +99,37 @@
resize="none"
group-class="row-span-2 pt-1 pb-1"
text-input="h-full text-lg"
readonly
disabled
/>
<MalioInputText
:model-value="information.competitors"
:label="t('commercial.clients.form.information.competitors')"
readonly
disabled
/>
<MalioDate
:model-value="information.foundedAt"
:label="t('commercial.clients.form.information.foundedAt')"
readonly
disabled
/>
<MalioInputText
:model-value="information.employeesCount"
:label="t('commercial.clients.form.information.employeesCount')"
readonly
disabled
/>
<MalioInputAmount
:model-value="information.revenueAmount"
:label="t('commercial.clients.form.information.revenueAmount')"
readonly
disabled
/>
<MalioInputText
:model-value="information.directorName"
:label="t('commercial.clients.form.information.directorName')"
readonly
disabled
/>
<MalioInputAmount
:model-value="information.profitAmount"
:label="t('commercial.clients.form.information.profitAmount')"
readonly
disabled
/>
</div>
</template>
@@ -140,7 +142,7 @@
:key="contact.id ?? index"
:model-value="contact"
:title="t('commercial.clients.form.contact.title', { n: index + 1 })"
readonly
disabled
/>
</div>
</template>
@@ -157,7 +159,7 @@
:site-options="allSiteOptions"
:contact-options="contactOptions"
:country-options="countryOptions"
readonly
disabled
/>
</div>
</template>
@@ -171,38 +173,38 @@
:model-value="accounting.siren"
:label="t('commercial.clients.form.accounting.siren')"
:mask="SIREN_MASK"
readonly
disabled
/>
<MalioInputText
:model-value="accounting.accountNumber"
:label="t('commercial.clients.form.accounting.accountNumber')"
readonly
disabled
/>
<MalioSelect
:model-value="accounting.tvaModeIri"
:options="tvaModeOptions"
:label="t('commercial.clients.form.accounting.tvaMode')"
empty-option-label=""
readonly
disabled
/>
<MalioInputText
:model-value="accounting.nTva"
:label="t('commercial.clients.form.accounting.nTva')"
readonly
disabled
/>
<MalioSelect
:model-value="accounting.paymentDelayIri"
:options="paymentDelayOptions"
:label="t('commercial.clients.form.accounting.paymentDelay')"
empty-option-label=""
readonly
disabled
/>
<MalioSelect
:model-value="accounting.paymentTypeIri"
:options="paymentTypeOptions"
:label="t('commercial.clients.form.accounting.paymentType')"
empty-option-label=""
readonly
disabled
/>
<MalioSelect
v-if="accounting.bankIri"
@@ -210,7 +212,7 @@
:options="bankOptions"
:label="t('commercial.clients.form.accounting.bank')"
empty-option-label=""
readonly
disabled
/>
</div>
</div>
@@ -225,28 +227,25 @@
<MalioInputText
:model-value="rib.label"
:label="t('commercial.clients.form.accounting.ribLabel')"
readonly
disabled
/>
<MalioInputText
:model-value="rib.bic"
:label="t('commercial.clients.form.accounting.ribBic')"
readonly
disabled
/>
<MalioInputText
:model-value="rib.iban"
:label="t('commercial.clients.form.accounting.ribIban')"
readonly
disabled
/>
</div>
</div>
</div>
</template>
<!-- Onglets non encore implementes : frame vide (navigation libre). -->
<template #transport><ComingSoonPlaceholder /></template>
<template #statistics><ComingSoonPlaceholder /></template>
<template #reports><ComingSoonPlaceholder /></template>
<template #exchanges><ComingSoonPlaceholder /></template>
<!-- ERP-193 : les onglets « a venir » (Transport / Statistiques /
Rapports / Echanges) ne sont plus rendus en consultation
(masquage des onglets vides) — slots supprimes. -->
</MalioTabList>
</template>
@@ -278,13 +277,14 @@
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { computed, onMounted, ref, watch } from 'vue'
import { useClient } from '~/modules/commercial/composables/useClient'
import { buildClientFormTabKeys, isRibRequiredForPaymentType } from '~/modules/commercial/utils/forms/clientFormRules'
import { isRibRequiredForPaymentType } from '~/modules/commercial/utils/forms/clientFormRules'
import { readHistoryTab } from '~/shared/utils/historyTab'
import {
canEditClient,
categoryOptionsOf,
clientConsultationVisibleTabs,
contactOptionsOf,
mapAccountingDraft,
mapAddressView,
@@ -412,9 +412,11 @@ const paymentTypeOptions = computed(() => referentialOptionOf(client.value?.paym
const bankOptions = computed(() => referentialOptionOf(client.value?.bank))
// ── Onglets : navigation LIBRE (pas de sequence forcee en consultation) ────
// 4 onglets actifs (Information, Contact, Adresse, + Comptabilite si droit) et
// 4 coquilles (Transport, Statistiques, Rapports, Echanges).
const tabKeys = computed(() => buildClientFormTabKeys(canAccountingView.value, { includeEditOnlyTabs: true }))
// ERP-193 (retour metier) : on masque les coquilles non implementees ET tout
// onglet de donnees vide. La liste depend donc du payload charge.
const visibleTabKeys = computed(() => clientConsultationVisibleTabs(client.value, {
canAccountingView: canAccountingView.value,
}))
const TAB_ICONS: Record<string, string> = {
information: 'mdi:account-outline',
@@ -427,14 +429,26 @@ const TAB_ICONS: Record<string, string> = {
exchanges: 'mdi:account-group-outline',
}
const tabs = computed(() => tabKeys.value.map(key => ({
const tabs = computed(() => visibleTabKeys.value.map(key => ({
key,
label: t(`commercial.clients.tab.${key}`),
icon: TAB_ICONS[key],
})))
// Onglet initial : repris de l'edition au retour (history.state), sinon Information.
const activeTab = ref(readHistoryTab(tabKeys.value) ?? 'information')
// Onglet initial : vide tant que le client n'est pas charge. Des que la liste
// des onglets visibles est connue, on cale sur l'onglet repris de l'edition
// (history.state) s'il est encore visible, sinon le premier onglet visible.
// Un watcher recale aussi si l'onglet courant disparait (ex: changement de droit).
const activeTab = ref('')
watch(visibleTabKeys, (keys) => {
if (keys.length === 0) {
activeTab.value = ''
return
}
if (!keys.includes(activeTab.value)) {
activeTab.value = readHistoryTab(keys) ?? keys[0]
}
}, { immediate: true })
// ── Navigation ─────────────────────────────────────────────────────────────
function goBack(): void {
@@ -19,9 +19,10 @@
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
<MalioInputText
v-model="main.companyName"
:mask="FREE_TEXT_MASK"
:label="t('commercial.clients.form.main.companyName')"
:required="true"
:readonly="mainLocked"
:disabled="mainLocked"
:error="mainErrors.errors.companyName"
/>
<MalioSelectCheckbox
@@ -29,7 +30,7 @@
:options="referentials.categories.value"
:label="t('commercial.clients.form.main.categories')"
:display-tag="true"
:readonly="mainLocked"
:disabled="mainLocked"
:required="true"
:error="mainErrors.errors.categories"
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
@@ -40,7 +41,7 @@
:options="relationOptions"
:label="t('commercial.clients.form.main.relation')"
:empty-option-label="t('commercial.clients.form.main.relationNone')"
:readonly="mainLocked"
:disabled="mainLocked"
@update:model-value="onRelationChange"
/>
<MalioSelect
@@ -48,7 +49,7 @@
:model-value="main.brokerIri"
:options="referentials.brokers.value"
:label="t('commercial.clients.form.main.brokerName')"
:readonly="mainLocked"
:disabled="mainLocked"
:required="true"
:error="mainErrors.errors.broker"
@update:model-value="(v: string | number | null) => main.brokerIri = v === null ? null : String(v)"
@@ -58,7 +59,7 @@
:model-value="main.distributorIri"
:options="referentials.distributors.value"
:label="t('commercial.clients.form.main.distributorName')"
:readonly="mainLocked"
:disabled="mainLocked"
:required="true"
:error="mainErrors.errors.distributor"
@update:model-value="(v: string | number | null) => main.distributorIri = v === null ? null : String(v)"
@@ -68,7 +69,7 @@
v-model="main.triageService"
:label="t('commercial.clients.form.main.triageService')"
group-class="self-center"
:readonly="mainLocked"
:disabled="mainLocked"
/>
</div>
@@ -96,20 +97,24 @@
resize="none"
group-class="row-span-2 pt-1 pb-1"
text-input="h-full text-lg"
:readonly="isValidated('information')"
:disabled="isValidated('information')"
:error="informationErrors.errors.description"
/>
<MalioInputText
v-model="information.competitors"
:mask="FREE_TEXT_MASK"
:label="t('commercial.clients.form.information.competitors')"
:readonly="isValidated('information')"
:disabled="isValidated('information')"
:error="informationErrors.errors.competitors"
/>
<!-- Date de creation jamais dans le futur (ERP-193) : :max plafonne
le calendrier a aujourd'hui et invalide une saisie future. -->
<MalioDate
v-model="information.foundedAt"
:label="t('commercial.clients.form.information.foundedAt')"
:readonly="isValidated('information')"
:disabled="isValidated('information')"
:editable="true"
:max="maxFoundedAt"
:error="informationErrors.errors.foundedAt"
@update:raw-value="(v: string) => information.foundedAtRaw = v"
/>
@@ -117,37 +122,42 @@
v-model="information.employeesCount"
:label="t('commercial.clients.form.information.employeesCount')"
:mask="EMPLOYEES_MASK"
:readonly="isValidated('information')"
:disabled="isValidated('information')"
:error="informationErrors.errors.employeesCount"
/>
<!-- CA plafonne a 999 999 999 999,99 (ERP-193) : clamp a la saisie,
:key force le re-affichage quand on plafonne (modelValue inchange). -->
<MalioInputAmount
v-model="information.revenueAmount"
:key="revenueAmountKey"
:model-value="information.revenueAmount"
:label="t('commercial.clients.form.information.revenueAmount')"
:readonly="isValidated('information')"
:disabled="isValidated('information')"
:error="informationErrors.errors.revenueAmount"
@update:model-value="onRevenueAmountInput"
/>
<MalioInputText
v-model="information.directorName"
:mask="PERSON_NAME_MASK"
:label="t('commercial.clients.form.information.directorName')"
:readonly="isValidated('information')"
:disabled="isValidated('information')"
:error="informationErrors.errors.directorName"
/>
<MalioInputAmount
v-model="information.profitAmount"
:label="t('commercial.clients.form.information.profitAmount')"
:readonly="isValidated('information')"
:disabled="isValidated('information')"
:error="informationErrors.errors.profitAmount"
/>
</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 clic trop tot, Information etant l'onglet
actif par defaut). Onglet facultatif : un enregistrement a
vide reste possible, c'est le back qui valide. -->
<!-- Masque tant que le client n'est pas cree : Information etant
l'onglet actif par defaut, son Valider ne doit pas apparaitre a
cote de celui du formulaire principal (ERP-193). Onglet facultatif :
un enregistrement a vide reste possible, c'est le back qui valide. -->
<div v-if="!isValidated('information') && clientId !== null" class="mt-12 flex justify-center">
<MalioButton
variant="primary"
:label="t('commercial.clients.form.submit')"
:disabled="tabSubmitting || clientId === null"
:disabled="tabSubmitting"
@click="submitInformation"
/>
</div>
@@ -166,7 +176,7 @@
:model-value="contact"
:title="t('commercial.clients.form.contact.title', { n: index + 1 })"
:removable="isRowRemovable(contacts, index)"
:readonly="isValidated('contact')"
:disabled="isValidated('contact')"
:errors="contactErrors[index]"
@update:model-value="(v) => contacts[index] = v"
@remove="askRemoveContact(index)"
@@ -203,7 +213,7 @@
:contact-options="contactOptions"
:country-options="countryOptions"
:removable="isRowRemovable(addresses, index)"
:readonly="isValidated('address')"
:disabled="isValidated('address')"
:errors="addressErrors[index]"
@update:model-value="(v) => addresses[index] = v"
@remove="askRemoveAddress(index)"
@@ -237,14 +247,15 @@
v-model="accounting.siren"
:label="t('commercial.clients.form.accounting.siren')"
:mask="SIREN_MASK"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.siren"
/>
<MalioInputText
v-model="accounting.accountNumber"
:mask="CODE_ALNUM_MASK"
:label="t('commercial.clients.form.accounting.accountNumber')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.accountNumber"
/>
@@ -252,7 +263,7 @@
:model-value="accounting.tvaModeIri"
:options="referentials.tvaModes.value"
:label="t('commercial.clients.form.accounting.tvaMode')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.tvaMode"
@@ -260,8 +271,9 @@
/>
<MalioInputText
v-model="accounting.nTva"
:mask="CODE_ALNUM_MASK"
:label="t('commercial.clients.form.accounting.nTva')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.nTva"
/>
@@ -269,7 +281,7 @@
:model-value="accounting.paymentDelayIri"
:options="referentials.paymentDelays.value"
:label="t('commercial.clients.form.accounting.paymentDelay')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.paymentDelay"
@@ -279,7 +291,7 @@
:model-value="accounting.paymentTypeIri"
:options="referentials.paymentTypes.value"
:label="t('commercial.clients.form.accounting.paymentType')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.paymentType"
@@ -290,7 +302,7 @@
:model-value="accounting.bankIri"
:options="referentials.banks.value"
:label="t('commercial.clients.form.accounting.bank')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.bank"
@@ -318,21 +330,23 @@
<MalioInputText
v-model="rib.label"
:label="t('commercial.clients.form.accounting.ribLabel')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="isRibRequired"
:error="ribErrors[index]?.label"
/>
<MalioInputText
v-model="rib.bic"
:mask="CODE_ALNUM_MASK"
:label="t('commercial.clients.form.accounting.ribBic')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="isRibRequired"
:error="ribErrors[index]?.bic"
/>
<MalioInputText
v-model="rib.iban"
:mask="CODE_ALNUM_MASK"
:label="t('commercial.clients.form.accounting.ribIban')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="isRibRequired"
:error="ribErrors[index]?.iban"
/>
@@ -407,6 +421,9 @@ import {
lastFillableTabKey,
showsRelationAndTriageFields,
} from '~/modules/commercial/utils/forms/clientFormRules'
import { clampRevenueAmount } from '~/modules/commercial/utils/forms/amountInput'
import { todayIso } from '~/shared/utils/date'
import { CODE_ALNUM_MASK, FREE_TEXT_MASK, PERSON_NAME_MASK } from '~/shared/utils/textSanitize'
import {
buildAddressPayload,
buildMainPayload,
@@ -665,6 +682,22 @@ const information = reactive({
directorName: null as string | null,
})
// Borne haute de la date de creation : aujourd'hui (ERP-193, pas de date future).
const maxFoundedAt = todayIso()
// CA plafonne a 999 999 999 999,99 (ERP-193). La :key force le re-affichage du
// champ controle quand le plafonnement laisse le modelValue inchange.
const revenueAmountKey = ref(0)
/** Saisie du CA : plafonne au maximum metier et re-synchronise le champ si plafonne. */
function onRevenueAmountInput(value: string | null): void {
const clamped = clampRevenueAmount(value)
information.revenueAmount = clamped ?? null
if (clamped !== value) {
revenueAmountKey.value += 1
}
}
/** PATCH /clients/{id} — mode strict : uniquement les champs du groupe information. */
async function submitInformation(): Promise<void> {
if (clientId.value === null || tabSubmitting.value) return
@@ -26,15 +26,16 @@
v-model="main.companyName"
:label="t('commercial.suppliers.form.main.companyName')"
:required="true"
:readonly="businessReadonly"
:disabled="businessReadonly"
:error="mainErrors.errors.companyName"
:mask="FREE_TEXT_MASK"
/>
<MalioSelectCheckbox
:model-value="main.categoryIris"
:options="mainCategoryOptions"
:label="t('commercial.suppliers.form.main.categories')"
:display-tag="true"
:readonly="businessReadonly"
:disabled="businessReadonly"
:required="true"
:error="mainErrors.errors.categories"
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
@@ -62,20 +63,24 @@
resize="none"
group-class="row-span-2 pt-1 pb-1"
text-input="h-full text-lg"
:readonly="businessReadonly"
:disabled="businessReadonly"
:error="informationErrors.errors.description"
/>
<MalioInputText
v-model="information.competitors"
:label="t('commercial.suppliers.form.information.competitors')"
:readonly="businessReadonly"
:disabled="businessReadonly"
:error="informationErrors.errors.competitors"
:mask="FREE_TEXT_MASK"
/>
<!-- Date de creation jamais dans le futur (ERP-193) : :max plafonne
le calendrier a aujourd'hui et invalide une saisie future. -->
<MalioDate
v-model="information.foundedAt"
:label="t('commercial.suppliers.form.information.foundedAt')"
:readonly="businessReadonly"
:disabled="businessReadonly"
:editable="true"
:max="maxFoundedAt"
:error="informationErrors.errors.foundedAt"
@update:raw-value="(v: string) => information.foundedAtRaw = v"
/>
@@ -83,25 +88,30 @@
v-model="information.employeesCount"
:label="t('commercial.suppliers.form.information.employeesCount')"
:mask="EMPLOYEES_MASK"
:readonly="businessReadonly"
:disabled="businessReadonly"
:error="informationErrors.errors.employeesCount"
/>
<!-- CA plafonne a 999 999 999 999,99 (ERP-193) : clamp a la saisie,
:key force le re-affichage quand on plafonne (modelValue inchange). -->
<MalioInputAmount
v-model="information.revenueAmount"
:key="revenueAmountKey"
:model-value="information.revenueAmount"
:label="t('commercial.suppliers.form.information.revenueAmount')"
:readonly="businessReadonly"
:disabled="businessReadonly"
:error="informationErrors.errors.revenueAmount"
@update:model-value="onRevenueAmountInput"
/>
<MalioInputText
v-model="information.directorName"
:label="t('commercial.suppliers.form.information.directorName')"
:readonly="businessReadonly"
:disabled="businessReadonly"
:error="informationErrors.errors.directorName"
:mask="PERSON_NAME_MASK"
/>
<MalioInputAmount
v-model="information.profitAmount"
:label="t('commercial.suppliers.form.information.profitAmount')"
:readonly="businessReadonly"
:disabled="businessReadonly"
:error="informationErrors.errors.profitAmount"
/>
<!-- Volume previsionnel : specifique fournisseur (entier). -->
@@ -109,7 +119,7 @@
v-model="information.volumeForecast"
:label="t('commercial.suppliers.form.information.volumeForecast')"
:mask="VOLUME_FORECAST_MASK"
:readonly="businessReadonly"
:disabled="businessReadonly"
:error="informationErrors.errors.volumeForecast"
/>
</div>
@@ -136,7 +146,7 @@
:model-value="contact"
:title="t('commercial.suppliers.form.contact.title', { n: index + 1 })"
:removable="isRowRemovable(contacts, index)"
:readonly="businessReadonly"
:disabled="businessReadonly"
:errors="contactErrors[index]"
@update:model-value="(v) => contacts[index] = v"
@remove="askRemoveContact(index)"
@@ -173,7 +183,7 @@
:contact-options="contactOptions"
:country-options="countryOptions"
:removable="isRowRemovable(addresses, index)"
:readonly="businessReadonly"
:disabled="businessReadonly"
:errors="addressErrors[index]"
@update:model-value="(v) => addresses[index] = v"
@remove="askRemoveAddress(index)"
@@ -208,22 +218,23 @@
v-model="accounting.siren"
:label="t('commercial.suppliers.form.accounting.siren')"
:mask="SIREN_MASK"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.siren"
/>
<MalioInputText
v-model="accounting.accountNumber"
:label="t('commercial.suppliers.form.accounting.accountNumber')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.accountNumber"
:mask="CODE_ALNUM_MASK"
/>
<MalioSelect
:model-value="accounting.tvaModeIri"
:options="tvaModeOptions"
:label="t('commercial.suppliers.form.accounting.tvaMode')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.tvaMode"
@@ -232,15 +243,16 @@
<MalioInputText
v-model="accounting.nTva"
:label="t('commercial.suppliers.form.accounting.nTva')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.nTva"
:mask="CODE_ALNUM_MASK"
/>
<MalioSelect
:model-value="accounting.paymentDelayIri"
:options="paymentDelayOptions"
:label="t('commercial.suppliers.form.accounting.paymentDelay')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.paymentDelay"
@@ -250,7 +262,7 @@
:model-value="accounting.paymentTypeIri"
:options="paymentTypeOptions"
:label="t('commercial.suppliers.form.accounting.paymentType')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.paymentType"
@@ -261,7 +273,7 @@
:model-value="accounting.bankIri"
:options="bankOptions"
:label="t('commercial.suppliers.form.accounting.bank')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.bank"
@@ -288,23 +300,25 @@
<MalioInputText
v-model="rib.label"
:label="t('commercial.suppliers.form.accounting.ribLabel')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="isRibRequired"
:error="ribErrors[index]?.label"
/>
<MalioInputText
v-model="rib.bic"
:label="t('commercial.suppliers.form.accounting.ribBic')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="isRibRequired"
:error="ribErrors[index]?.bic"
:mask="CODE_ALNUM_MASK"
/>
<MalioInputText
v-model="rib.iban"
:label="t('commercial.suppliers.form.accounting.ribIban')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="isRibRequired"
:error="ribErrors[index]?.iban"
:mask="CODE_ALNUM_MASK"
/>
</div>
</div>
@@ -392,6 +406,8 @@ import {
type MainFormDraft,
type SupplierEditAbilities,
} from '~/modules/commercial/utils/forms/supplierEdit'
import { clampRevenueAmount } from '~/modules/commercial/utils/forms/amountInput'
import { todayIso } from '~/shared/utils/date'
import {
buildSupplierFormTabKeys,
isAddressValid,
@@ -412,6 +428,7 @@ import {
} from '~/modules/commercial/types/supplierForm'
import { extractApiErrorMessage } from '~/shared/utils/api'
import { isRowRemovable, removeCollectionRow } from '~/shared/utils/collectionRow'
import { CODE_ALNUM_MASK, FREE_TEXT_MASK, PERSON_NAME_MASK } from '~/shared/utils/textSanitize'
import { readHistoryTab } from '~/shared/utils/historyTab'
// Masques de saisie (la normalisation finale reste serveur).
@@ -457,6 +474,22 @@ const headerTitle = computed(() => supplier.value?.companyName ?? t('commercial.
const main = reactive<MainFormDraft>(mapMainDraft({} as SupplierDetail))
const information = reactive<InformationFormDraft>(mapInformationDraft({} as SupplierDetail))
const accounting = reactive<AccountingFormDraft>(mapAccountingFormDraft({} as SupplierDetail))
// Borne haute de la date de creation : aujourd'hui (ERP-193, pas de date future).
const maxFoundedAt = todayIso()
// CA plafonne a 999 999 999 999,99 (ERP-193). La :key force le re-affichage du
// champ controle quand le plafonnement laisse le modelValue inchange.
const revenueAmountKey = ref(0)
/** Saisie du CA : plafonne au maximum metier et re-synchronise le champ si plafonne. */
function onRevenueAmountInput(value: string | null): void {
const clamped = clampRevenueAmount(value)
information.revenueAmount = clamped ?? null
if (clamped !== value) {
revenueAmountKey.value += 1
}
}
const contacts = ref<SupplierContactFormDraft[]>([])
const addresses = ref<SupplierAddressFormDraft[]>([])
const ribs = ref<SupplierRibFormDraft[]>([])
@@ -583,6 +616,11 @@ function showError(e: unknown): void {
toast.error({ title: t('commercial.suppliers.toast.error'), message: apiErrorMessage(e) })
}
/** Toast de succès après suppression serveur confirmée d'un bloc (contact / adresse / RIB). */
function notifyRemovalSuccess(): void {
toast.success({ title: t('success.title'), message: t('success.deleted') })
}
// ── Erreurs de validation par champ (ERP-101) ───────────────────────────────
const {
mainErrors,
@@ -666,6 +704,7 @@ function askRemoveContact(index: number): void {
deleteRow: url => api.delete(url, {}, { toast: false }),
makeEmpty: emptyContact,
onError: showError,
onSuccess: notifyRemovalSuccess,
}))
}
@@ -734,6 +773,7 @@ function askRemoveAddress(index: number): void {
deleteRow: url => api.delete(url, {}, { toast: false }),
makeEmpty: emptyAddress,
onError: showError,
onSuccess: notifyRemovalSuccess,
}))
}
@@ -833,6 +873,7 @@ function askRemoveRib(index: number): void {
deleteRow: url => api.delete(url, {}, { toast: false }),
makeEmpty: emptyRib,
onError: showError,
onSuccess: notifyRemovalSuccess,
}))
}
@@ -23,7 +23,7 @@
/>
<MalioButton
v-if="showArchive"
variant="secondary"
variant="danger"
icon-name="mdi:archive-arrow-down-outline"
icon-position="left"
:label="t('commercial.suppliers.action.archive')"
@@ -50,19 +50,22 @@
<MalioInputText
:model-value="supplier.companyName"
:label="t('commercial.suppliers.form.main.companyName')"
readonly
disabled
/>
<MalioSelectCheckbox
:model-value="categoryIris"
:options="mainCategoryOptions"
:label="t('commercial.suppliers.form.main.categories')"
:display-tag="true"
readonly
disabled
/>
</div>
<!-- Onglets (navigation libre, tout en lecture seule) -->
<MalioTabList v-model="activeTab" :tabs="tabs" :max-visible-tabs="5" :max-width="1100" class="mt-[60px]">
<!-- Masque la barre d'onglets (et sa bordure) quand aucun onglet n'est
visible : seul le formulaire principal est rempli (aligné sur le
client). -->
<MalioTabList v-if="visibleTabKeys.length" v-model="activeTab" :tabs="tabs" :max-visible-tabs="5" :max-width="1100" class="mt-[60px]">
<!-- 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)]">
@@ -74,43 +77,43 @@
resize="none"
group-class="row-span-2 pt-1 pb-1"
text-input="h-full text-lg"
readonly
disabled
/>
<MalioInputText
:model-value="information.competitors"
:label="t('commercial.suppliers.form.information.competitors')"
readonly
disabled
/>
<MalioDate
:model-value="information.foundedAt"
:label="t('commercial.suppliers.form.information.foundedAt')"
readonly
disabled
/>
<MalioInputText
:model-value="information.employeesCount"
:label="t('commercial.suppliers.form.information.employeesCount')"
readonly
disabled
/>
<MalioInputAmount
:model-value="information.revenueAmount"
:label="t('commercial.suppliers.form.information.revenueAmount')"
readonly
disabled
/>
<MalioInputText
:model-value="information.directorName"
:label="t('commercial.suppliers.form.information.directorName')"
readonly
disabled
/>
<MalioInputAmount
:model-value="information.profitAmount"
:label="t('commercial.suppliers.form.information.profitAmount')"
readonly
disabled
/>
<!-- Volume previsionnel : specifique fournisseur (entier). -->
<MalioInputText
:model-value="information.volumeForecast"
:label="t('commercial.suppliers.form.information.volumeForecast')"
readonly
disabled
/>
</div>
</template>
@@ -123,7 +126,7 @@
:key="contact.id ?? index"
:model-value="contact"
:title="t('commercial.suppliers.form.contact.title', { n: index + 1 })"
readonly
disabled
/>
</div>
</template>
@@ -140,7 +143,7 @@
:site-options="allSiteOptions"
:contact-options="contactOptions"
:country-options="countryOptions"
readonly
disabled
/>
</div>
</template>
@@ -154,38 +157,38 @@
:model-value="accounting.siren"
:label="t('commercial.suppliers.form.accounting.siren')"
:mask="SIREN_MASK"
readonly
disabled
/>
<MalioInputText
:model-value="accounting.accountNumber"
:label="t('commercial.suppliers.form.accounting.accountNumber')"
readonly
disabled
/>
<MalioSelect
:model-value="accounting.tvaModeIri"
:options="tvaModeOptions"
:label="t('commercial.suppliers.form.accounting.tvaMode')"
empty-option-label=""
readonly
disabled
/>
<MalioInputText
:model-value="accounting.nTva"
:label="t('commercial.suppliers.form.accounting.nTva')"
readonly
disabled
/>
<MalioSelect
:model-value="accounting.paymentDelayIri"
:options="paymentDelayOptions"
:label="t('commercial.suppliers.form.accounting.paymentDelay')"
empty-option-label=""
readonly
disabled
/>
<MalioSelect
:model-value="accounting.paymentTypeIri"
:options="paymentTypeOptions"
:label="t('commercial.suppliers.form.accounting.paymentType')"
empty-option-label=""
readonly
disabled
/>
<MalioSelect
v-if="accounting.bankIri"
@@ -193,7 +196,7 @@
:options="bankOptions"
:label="t('commercial.suppliers.form.accounting.bank')"
empty-option-label=""
readonly
disabled
/>
</div>
</div>
@@ -208,28 +211,25 @@
<MalioInputText
:model-value="rib.label"
:label="t('commercial.suppliers.form.accounting.ribLabel')"
readonly
disabled
/>
<MalioInputText
:model-value="rib.bic"
:label="t('commercial.suppliers.form.accounting.ribBic')"
readonly
disabled
/>
<MalioInputText
:model-value="rib.iban"
:label="t('commercial.suppliers.form.accounting.ribIban')"
readonly
disabled
/>
</div>
</div>
</div>
</template>
<!-- Onglets non encore implementes : frame vide (navigation libre). -->
<template #transport><ComingSoonPlaceholder /></template>
<template #statistics><ComingSoonPlaceholder /></template>
<template #reports><ComingSoonPlaceholder /></template>
<template #exchanges><ComingSoonPlaceholder /></template>
<!-- ERP-193 : les onglets « a venir » (Transport / Statistiques /
Rapports / Echanges) ne sont plus rendus en consultation
(masquage des onglets vides) slots supprimes. -->
</MalioTabList>
</template>
@@ -261,9 +261,9 @@
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { computed, onMounted, ref, watch } from 'vue'
import { useSupplier } from '~/modules/commercial/composables/useSupplier'
import { buildSupplierFormTabKeys, isRibRequiredForPaymentType } from '~/modules/commercial/utils/forms/supplierFormRules'
import { isRibRequiredForPaymentType } from '~/modules/commercial/utils/forms/supplierFormRules'
import { readHistoryTab } from '~/shared/utils/historyTab'
import {
canEditSupplier,
@@ -278,6 +278,7 @@ import {
referentialOptionOf,
showArchiveAction,
showRestoreAction,
supplierConsultationVisibleTabs,
type SelectOption,
type SupplierDetail,
} from '~/modules/commercial/utils/forms/supplierConsultation'
@@ -387,9 +388,11 @@ const paymentTypeOptions = computed(() => referentialOptionOf(supplier.value?.pa
const bankOptions = computed(() => referentialOptionOf(supplier.value?.bank))
// ── Onglets : navigation LIBRE (pas de sequence forcee en consultation) ────
// 3 onglets actifs (Information, Contacts, Adresses, + Comptabilite si droit) et
// 4 coquilles (Transport, Statistiques, Rapports, Echanges).
const tabKeys = computed(() => buildSupplierFormTabKeys(canAccountingView.value, { includeEditOnlyTabs: true }))
// ERP-193 (retour metier) : on masque les coquilles non implementees ET tout
// onglet de donnees vide. La liste depend donc du payload charge.
const visibleTabKeys = computed(() => supplierConsultationVisibleTabs(supplier.value, {
canAccountingView: canAccountingView.value,
}))
const TAB_ICONS: Record<string, string> = {
information: 'mdi:account-outline',
@@ -402,14 +405,25 @@ const TAB_ICONS: Record<string, string> = {
exchanges: 'mdi:account-group-outline',
}
const tabs = computed(() => tabKeys.value.map(key => ({
const tabs = computed(() => visibleTabKeys.value.map(key => ({
key,
label: t(`commercial.suppliers.tab.${key}`),
icon: TAB_ICONS[key],
})))
// Onglet initial : repris de l'edition au retour (history.state), sinon Information.
const activeTab = ref(readHistoryTab(tabKeys.value) ?? 'information')
// Onglet initial : vide tant que le fournisseur n'est pas charge. Des que la
// liste des onglets visibles est connue, on cale sur l'onglet repris de
// l'edition (history.state) s'il est encore visible, sinon le premier visible.
const activeTab = ref('')
watch(visibleTabKeys, (keys) => {
if (keys.length === 0) {
activeTab.value = ''
return
}
if (!keys.includes(activeTab.value)) {
activeTab.value = readHistoryTab(keys) ?? keys[0]
}
}, { immediate: true })
// ── Navigation ─────────────────────────────────────────────────────────────
function goBack(): void {
@@ -43,7 +43,7 @@
@update:page="goToPage"
@update:per-page="setItemsPerPage"
>
<!-- Categories : libelles (name) separes par une virgule (spec M2). -->
<!-- Categories : codes stables (MAJUSCULE) separes par une virgule, aligne sur le client (ERP-193). -->
<template #cell-categories="{ item }">
{{ formatCategories(item) }}
</template>
@@ -209,10 +209,10 @@ const columns = [
{ key: 'lastActivity', label: t('commercial.suppliers.column.lastActivity') },
]
/** Libelles des categories du fournisseur, separes par une virgule (spec M2 : name). */
/** Codes (MAJUSCULE) des categories du fournisseur, separes par une virgule (aligne sur le client, ERP-193). */
function formatCategories(item: Record<string, unknown>): string {
const categories = (item.categories as Supplier['categories']) ?? []
return categories.map(c => c.name).join(', ')
return categories.map(c => c.code).join(', ')
}
/**
@@ -21,15 +21,16 @@
v-model="main.companyName"
:label="t('commercial.suppliers.form.main.companyName')"
:required="true"
:readonly="mainLocked"
:disabled="mainLocked"
:error="mainErrors.errors.companyName"
:mask="FREE_TEXT_MASK"
/>
<MalioSelectCheckbox
:model-value="main.categoryIris"
:options="referentials.categories.value"
:label="t('commercial.suppliers.form.main.categories')"
:display-tag="true"
:readonly="mainLocked"
:disabled="mainLocked"
:required="true"
:error="mainErrors.errors.categories"
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
@@ -56,20 +57,24 @@
resize="none"
group-class="row-span-2 pt-1 pb-1"
text-input="h-full text-lg"
:readonly="isValidated('information')"
:disabled="isValidated('information')"
:error="informationErrors.errors.description"
/>
<MalioInputText
v-model="information.competitors"
:label="t('commercial.suppliers.form.information.competitors')"
:readonly="isValidated('information')"
:disabled="isValidated('information')"
:error="informationErrors.errors.competitors"
:mask="FREE_TEXT_MASK"
/>
<!-- Date de creation jamais dans le futur (ERP-193) : :max plafonne
le calendrier a aujourd'hui et invalide une saisie future. -->
<MalioDate
v-model="information.foundedAt"
:label="t('commercial.suppliers.form.information.foundedAt')"
:readonly="isValidated('information')"
:disabled="isValidated('information')"
:editable="true"
:max="maxFoundedAt"
:error="informationErrors.errors.foundedAt"
@update:raw-value="(v: string) => information.foundedAtRaw = v"
/>
@@ -77,25 +82,30 @@
v-model="information.employeesCount"
:label="t('commercial.suppliers.form.information.employeesCount')"
:mask="EMPLOYEES_MASK"
:readonly="isValidated('information')"
:disabled="isValidated('information')"
:error="informationErrors.errors.employeesCount"
/>
<!-- CA plafonne a 999 999 999 999,99 (ERP-193) : clamp a la saisie,
:key force le re-affichage quand on plafonne (modelValue inchange). -->
<MalioInputAmount
v-model="information.revenueAmount"
:key="revenueAmountKey"
:model-value="information.revenueAmount"
:label="t('commercial.suppliers.form.information.revenueAmount')"
:readonly="isValidated('information')"
:disabled="isValidated('information')"
:error="informationErrors.errors.revenueAmount"
@update:model-value="onRevenueAmountInput"
/>
<MalioInputText
v-model="information.directorName"
:label="t('commercial.suppliers.form.information.directorName')"
:readonly="isValidated('information')"
:disabled="isValidated('information')"
:error="informationErrors.errors.directorName"
:mask="PERSON_NAME_MASK"
/>
<MalioInputAmount
v-model="information.profitAmount"
:label="t('commercial.suppliers.form.information.profitAmount')"
:readonly="isValidated('information')"
:disabled="isValidated('information')"
:error="informationErrors.errors.profitAmount"
/>
<!-- Volume previsionnel : specifique fournisseur. Champ texte
@@ -104,15 +114,18 @@
v-model="information.volumeForecast"
:label="t('commercial.suppliers.form.information.volumeForecast')"
:mask="VOLUME_FORECAST_MASK"
:readonly="isValidated('information')"
:disabled="isValidated('information')"
:error="informationErrors.errors.volumeForecast"
/>
</div>
<div v-if="!isValidated('information')" class="mt-12 flex justify-center">
<!-- Masque tant que le fournisseur n'est pas cree : Information etant
l'onglet actif par defaut, son Valider ne doit pas apparaitre a cote
de celui du formulaire principal (ERP-193). -->
<div v-if="!isValidated('information') && supplierId !== null" class="mt-12 flex justify-center">
<MalioButton
variant="primary"
:label="t('commercial.suppliers.form.submit')"
:disabled="tabSubmitting || supplierId === null"
:disabled="tabSubmitting"
@click="submitInformation"
/>
</div>
@@ -131,7 +144,7 @@
:model-value="contact"
:title="t('commercial.suppliers.form.contact.title', { n: index + 1 })"
:removable="isRowRemovable(contacts, index)"
:readonly="isValidated('contacts')"
:disabled="isValidated('contacts')"
:errors="contactErrors[index]"
@update:model-value="(v) => contacts[index] = v"
@remove="askRemoveContact(index)"
@@ -168,7 +181,7 @@
:contact-options="contactOptions"
:country-options="countryOptions"
:removable="isRowRemovable(addresses, index)"
:readonly="isValidated('addresses')"
:disabled="isValidated('addresses')"
:errors="addressErrors[index]"
@update:model-value="(v) => addresses[index] = v"
@remove="askRemoveAddress(index)"
@@ -202,22 +215,23 @@
v-model="accounting.siren"
:label="t('commercial.suppliers.form.accounting.siren')"
:mask="SIREN_MASK"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.siren"
/>
<MalioInputText
v-model="accounting.accountNumber"
:label="t('commercial.suppliers.form.accounting.accountNumber')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.accountNumber"
:mask="CODE_ALNUM_MASK"
/>
<MalioSelect
:model-value="accounting.tvaModeIri"
:options="referentials.tvaModes.value"
:label="t('commercial.suppliers.form.accounting.tvaMode')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.tvaMode"
@@ -226,15 +240,16 @@
<MalioInputText
v-model="accounting.nTva"
:label="t('commercial.suppliers.form.accounting.nTva')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.nTva"
:mask="CODE_ALNUM_MASK"
/>
<MalioSelect
:model-value="accounting.paymentDelayIri"
:options="referentials.paymentDelays.value"
:label="t('commercial.suppliers.form.accounting.paymentDelay')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.paymentDelay"
@@ -244,7 +259,7 @@
:model-value="accounting.paymentTypeIri"
:options="referentials.paymentTypes.value"
:label="t('commercial.suppliers.form.accounting.paymentType')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.paymentType"
@@ -255,7 +270,7 @@
:model-value="accounting.bankIri"
:options="referentials.banks.value"
:label="t('commercial.suppliers.form.accounting.bank')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.bank"
@@ -282,23 +297,25 @@
<MalioInputText
v-model="rib.label"
:label="t('commercial.suppliers.form.accounting.ribLabel')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="isRibRequired"
:error="ribErrors[index]?.label"
/>
<MalioInputText
v-model="rib.bic"
:label="t('commercial.suppliers.form.accounting.ribBic')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="isRibRequired"
:error="ribErrors[index]?.bic"
:mask="CODE_ALNUM_MASK"
/>
<MalioInputText
v-model="rib.iban"
:label="t('commercial.suppliers.form.accounting.ribIban')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="isRibRequired"
:error="ribErrors[index]?.iban"
:mask="CODE_ALNUM_MASK"
/>
</div>
</div>
@@ -375,6 +392,8 @@ import {
buildMainPayload,
buildRibPayload,
} from '~/modules/commercial/utils/forms/supplierEdit'
import { clampRevenueAmount } from '~/modules/commercial/utils/forms/amountInput'
import { todayIso } from '~/shared/utils/date'
import {
emptyAddress,
emptyContact,
@@ -385,6 +404,7 @@ import {
} from '~/modules/commercial/types/supplierForm'
import { extractApiErrorMessage } from '~/shared/utils/api'
import { isRowRemovable } from '~/shared/utils/collectionRow'
import { CODE_ALNUM_MASK, FREE_TEXT_MASK, PERSON_NAME_MASK } from '~/shared/utils/textSanitize'
// Masques de saisie (la normalisation finale reste serveur).
const SIREN_MASK = '#########'
@@ -564,6 +584,22 @@ const information = reactive({
volumeForecast: null as string | null,
})
// Borne haute de la date de creation : aujourd'hui (ERP-193, pas de date future).
const maxFoundedAt = todayIso()
// CA plafonne a 999 999 999 999,99 (ERP-193). La :key force le re-affichage du
// champ controle quand le plafonnement laisse le modelValue inchange.
const revenueAmountKey = ref(0)
/** Saisie du CA : plafonne au maximum metier et re-synchronise le champ si plafonne. */
function onRevenueAmountInput(value: string | null): void {
const clamped = clampRevenueAmount(value)
information.revenueAmount = clamped ?? null
if (clamped !== value) {
revenueAmountKey.value += 1
}
}
/** PATCH /suppliers/{id} — mode strict : uniquement les champs du groupe information. */
async function submitInformation(): Promise<void> {
if (supplierId.value === null || tabSubmitting.value) return
@@ -0,0 +1,33 @@
import { describe, expect, it } from 'vitest'
import { clampRevenueAmount, REVENUE_AMOUNT_MAX } from '../amountInput'
describe('clampRevenueAmount', () => {
it('laisse les valeurs vides / nulles telles quelles', () => {
expect(clampRevenueAmount(null)).toBeNull()
expect(clampRevenueAmount(undefined)).toBeUndefined()
expect(clampRevenueAmount('')).toBe('')
})
it('laisse une valeur sous le plafond inchangee', () => {
expect(clampRevenueAmount('1000.50')).toBe('1000.50')
expect(clampRevenueAmount('999999999999.99')).toBe('999999999999.99')
})
it('plafonne une valeur au-dessus du maximum', () => {
expect(clampRevenueAmount('1000000000000')).toBe('999999999999.99')
expect(clampRevenueAmount('999999999999999.99')).toBe('999999999999.99')
})
it('tolere une saisie a virgule / avec espaces (securite)', () => {
expect(clampRevenueAmount('1 000 000 000 000,00')).toBe('999999999999.99')
expect(clampRevenueAmount('12,5')).toBe('12,5')
})
it('ne touche pas une saisie non numerique', () => {
expect(clampRevenueAmount('abc')).toBe('abc')
})
it('expose le plafond metier', () => {
expect(REVENUE_AMOUNT_MAX).toBe(999_999_999_999.99)
})
})
@@ -2,7 +2,10 @@ import { describe, expect, it } from 'vitest'
import {
canEditClient,
categoryOptionsOf,
clientConsultationVisibleTabs,
contactOptionsOf,
hasAccountingData,
hasInformationData,
iriOf,
mapAccountingDraft,
mapAddressToDraft,
@@ -248,3 +251,73 @@ describe('paymentTypeCodeOf (ERP-121 : RIB masques hors-LCR en consultation)', (
expect(paymentTypeCodeOf(undefined)).toBeNull()
})
})
describe('hasInformationData', () => {
it('faux si tous les champs Information sont vides/absents', () => {
expect(hasInformationData({ '@id': '/api/clients/1', id: 1 })).toBe(false)
expect(hasInformationData({ '@id': '/api/clients/1', id: 1, description: ' ' })).toBe(false)
})
it('vrai des qu\'un champ Information porte une donnee', () => {
expect(hasInformationData({ '@id': '/api/clients/1', id: 1, directorName: 'Dupont' })).toBe(true)
expect(hasInformationData({ '@id': '/api/clients/1', id: 1, employeesCount: 0 })).toBe(true)
})
})
describe('hasAccountingData', () => {
it('faux sans champ comptable ni RIB', () => {
expect(hasAccountingData({ '@id': '/api/clients/1', id: 1 })).toBe(false)
})
it('vrai avec un champ comptable scalaire', () => {
expect(hasAccountingData({ '@id': '/api/clients/1', id: 1, siren: '123456789' })).toBe(true)
})
it('vrai avec une relation comptable embarquee (paymentType)', () => {
expect(hasAccountingData({
'@id': '/api/clients/1', id: 1,
paymentType: { '@id': '/api/payment_types/1', code: 'LCR' },
})).toBe(true)
})
it('vrai avec au moins un RIB', () => {
expect(hasAccountingData({
'@id': '/api/clients/1', id: 1,
ribs: [{ '@id': '/api/ribs/1', id: 1, iban: 'FR76...' }],
})).toBe(true)
})
})
describe('clientConsultationVisibleTabs', () => {
it('retourne [] tant que le client n\'est pas charge', () => {
expect(clientConsultationVisibleTabs(null, { canAccountingView: true })).toEqual([])
expect(clientConsultationVisibleTabs(undefined, { canAccountingView: true })).toEqual([])
})
it('masque les coquilles et les onglets vides (client minimal)', () => {
const client: ClientDetail = { '@id': '/api/clients/1', id: 1, companyName: 'ACME' }
expect(clientConsultationVisibleTabs(client, { canAccountingView: true })).toEqual([])
})
it('affiche les onglets non vides dans l\'ordre information/contact/address/accounting', () => {
const client: ClientDetail = {
'@id': '/api/clients/1', id: 1,
directorName: 'Dupont',
contacts: [{ '@id': '/api/client_contacts/1', id: 1 }],
addresses: [{ '@id': '/api/client_addresses/1', id: 1 }],
siren: '123456789',
}
expect(clientConsultationVisibleTabs(client, { canAccountingView: true }))
.toEqual(['information', 'contact', 'address', 'accounting'])
})
it('masque Comptabilite sans le droit accounting.view meme si des donnees existent', () => {
const client: ClientDetail = {
'@id': '/api/clients/1', id: 1,
contacts: [{ '@id': '/api/client_contacts/1', id: 1 }],
siren: '123456789',
}
expect(clientConsultationVisibleTabs(client, { canAccountingView: false }))
.toEqual(['contact'])
})
})
@@ -3,6 +3,8 @@ import {
canEditSupplier,
categoryOptionsOf,
contactOptionsOf,
hasAccountingData,
hasInformationData,
iriOf,
mapAccountingDraft,
mapAddressToDraft,
@@ -14,6 +16,7 @@ import {
showArchiveAction,
showRestoreAction,
siteOptionsOf,
supplierConsultationVisibleTabs,
type SupplierDetail,
} from '../supplierConsultation'
@@ -237,3 +240,60 @@ describe('paymentTypeCodeOf (ERP-121 : RIB masques hors-LCR en consultation)', (
expect(paymentTypeCodeOf(undefined)).toBeNull()
})
})
describe('hasInformationData (fournisseur)', () => {
it('faux si tous les champs Information (volume previsionnel inclus) sont vides', () => {
expect(hasInformationData({ '@id': '/api/suppliers/1', id: 1 })).toBe(false)
})
it('vrai des qu\'un champ Information porte une donnee', () => {
expect(hasInformationData({ '@id': '/api/suppliers/1', id: 1, directorName: 'Martin' })).toBe(true)
expect(hasInformationData({ '@id': '/api/suppliers/1', id: 1, volumeForecast: 1200 })).toBe(true)
})
})
describe('hasAccountingData (fournisseur)', () => {
it('faux sans champ comptable ni RIB', () => {
expect(hasAccountingData({ '@id': '/api/suppliers/1', id: 1 })).toBe(false)
})
it('vrai avec un champ comptable ou un RIB', () => {
expect(hasAccountingData({ '@id': '/api/suppliers/1', id: 1, siren: '123456789' })).toBe(true)
expect(hasAccountingData({
'@id': '/api/suppliers/1', id: 1,
ribs: [{ '@id': '/api/supplier_ribs/1', id: 1, iban: 'FR76...' }],
})).toBe(true)
})
})
describe('supplierConsultationVisibleTabs', () => {
it('retourne [] tant que le fournisseur n\'est pas charge', () => {
expect(supplierConsultationVisibleTabs(null, { canAccountingView: true })).toEqual([])
})
it('masque les coquilles et les onglets vides (fournisseur minimal)', () => {
expect(supplierConsultationVisibleTabs(
{ '@id': '/api/suppliers/1', id: 1, companyName: 'ACME' },
{ canAccountingView: true },
)).toEqual([])
})
it('affiche information/contacts/addresses/accounting (cles plurielles) dans l\'ordre', () => {
const supplier: SupplierDetail = {
'@id': '/api/suppliers/1', id: 1,
volumeForecast: 1000,
contacts: [{ '@id': '/api/supplier_contacts/1', id: 1 }],
addresses: [{ '@id': '/api/supplier_addresses/1', id: 1 }],
siren: '123456789',
}
expect(supplierConsultationVisibleTabs(supplier, { canAccountingView: true }))
.toEqual(['information', 'contacts', 'addresses', 'accounting'])
})
it('masque Comptabilite sans le droit accounting.view', () => {
expect(supplierConsultationVisibleTabs(
{ '@id': '/api/suppliers/1', id: 1, siren: '123456789' },
{ canAccountingView: false },
)).toEqual([])
})
})
@@ -0,0 +1,29 @@
/**
* Helpers de saisie des montants des formulaires Client / Fournisseur (commercial).
* Purs / testables. Pendant FRONT de la contrainte back `LessThanOrEqual` posee sur
* `revenueAmount` (Client/Supplier) — retour metier ERP-193 : le chiffre d'affaires
* est plafonne a 999 999 999 999,99.
*/
/** Plafond metier du chiffre d'affaires (CA) : 999 999 999 999,99. */
export const REVENUE_AMOUNT_MAX = 999_999_999_999.99
/** Valeur « modele » (decimale a point, sans separateur) renvoyee quand on plafonne. */
const REVENUE_AMOUNT_MAX_MODEL = '999999999999.99'
/**
* Plafonne le CA au maximum metier. Recoit le modele emis par `MalioInputAmount`
* (chaine propre a decimale `.`, sans espaces) ; tolere malgre tout une virgule /
* des espaces par securite. Renvoie la valeur telle quelle si elle est vide, non
* numerique ou sous le plafond ; sinon la valeur plafonnee.
*/
export function clampRevenueAmount(value: string | null | undefined): string | null | undefined {
if (value === null || value === undefined || value === '') {
return value
}
const n = Number(String(value).replace(/\s/g, '').replace(',', '.'))
if (Number.isNaN(n)) {
return value
}
return n > REVENUE_AMOUNT_MAX ? REVENUE_AMOUNT_MAX_MODEL : value
}
@@ -317,6 +317,77 @@ export function mapAddressView(address: AddressRead): AddressView {
}
}
/**
* Vrai si une valeur scalaire porte une donnee affichable (non null/undefined,
* et non chaine vide apres trim). Sert aux predicats « onglet vide » ci-dessous.
*/
function hasValue(value: unknown): boolean {
if (value === null || value === undefined) {
return false
}
if (typeof value === 'string') {
return value.trim() !== ''
}
return true
}
/**
* Vrai si l'onglet Information porte au moins une donnee. ERP-193 : en
* consultation on masque les onglets vides ; Information n'echappe pas a la
* regle malgre son statut d'onglet d'atterrissage par defaut.
*/
export function hasInformationData(client: ClientDetail): boolean {
return [
client.description,
client.competitors,
client.foundedAt,
client.employeesCount,
client.revenueAmount,
client.profitAmount,
client.directorName,
].some(hasValue)
}
/**
* Vrai si l'onglet Comptabilite porte au moins un champ comptable OU un RIB.
* (Le gating permission `accounting.view` reste applique en amont par l'appelant.)
*/
export function hasAccountingData(client: ClientDetail): boolean {
const draft = mapAccountingDraft(client)
const hasField = Object.values(draft).some(hasValue)
const hasRib = (client.ribs ?? []).length > 0
return hasField || hasRib
}
/**
* Onglets visibles en consultation (ERP-193, retour metier) : on masque les
* coquilles non implementees (Transport / Statistiques / Rapports / Echanges)
* ET tout onglet de donnees vide. L'ordre reproduit `buildClientFormTabKeys`.
* Retourne `[]` tant que le client n'est pas charge.
*/
export function clientConsultationVisibleTabs(
client: ClientDetail | null | undefined,
options: { canAccountingView: boolean },
): string[] {
if (!client) {
return []
}
const visible: string[] = []
if (hasInformationData(client)) {
visible.push('information')
}
if ((client.contacts ?? []).length > 0) {
visible.push('contact')
}
if ((client.addresses ?? []).length > 0) {
visible.push('address')
}
if (options.canAccountingView && hasAccountingData(client)) {
visible.push('accounting')
}
return visible
}
/**
* Bouton « Modifier » : visible si l'utilisateur peut editer au moins un onglet
* — `manage` (formulaire/onglets metier) OU `accounting.manage` (le role Compta
@@ -292,6 +292,78 @@ export function mapAddressView(address: AddressRead): AddressView {
}
}
/**
* Vrai si une valeur scalaire porte une donnee affichable (non null/undefined,
* et non chaine vide apres trim). Sert aux predicats « onglet vide » ci-dessous.
*/
function hasValue(value: unknown): boolean {
if (value === null || value === undefined) {
return false
}
if (typeof value === 'string') {
return value.trim() !== ''
}
return true
}
/**
* Vrai si l'onglet Information porte au moins une donnee (volume previsionnel
* inclus, specifique fournisseur). ERP-193 : en consultation on masque les
* onglets vides, Information comprise.
*/
export function hasInformationData(supplier: SupplierDetail): boolean {
return [
supplier.description,
supplier.competitors,
supplier.foundedAt,
supplier.employeesCount,
supplier.revenueAmount,
supplier.profitAmount,
supplier.directorName,
supplier.volumeForecast,
].some(hasValue)
}
/**
* Vrai si l'onglet Comptabilite porte au moins un champ comptable OU un RIB.
* (Le gating permission `accounting.view` reste applique en amont par l'appelant.)
*/
export function hasAccountingData(supplier: SupplierDetail): boolean {
const draft = mapAccountingDraft(supplier)
const hasField = Object.values(draft).some(hasValue)
const hasRib = (supplier.ribs ?? []).length > 0
return hasField || hasRib
}
/**
* Onglets visibles en consultation (ERP-193, retour metier) : on masque les
* coquilles non implementees (Transport / Statistiques / Rapports / Echanges)
* ET tout onglet de donnees vide. L'ordre reproduit `buildSupplierFormTabKeys`.
* Retourne `[]` tant que le fournisseur n'est pas charge.
*/
export function supplierConsultationVisibleTabs(
supplier: SupplierDetail | null | undefined,
options: { canAccountingView: boolean },
): string[] {
if (!supplier) {
return []
}
const visible: string[] = []
if (hasInformationData(supplier)) {
visible.push('information')
}
if ((supplier.contacts ?? []).length > 0) {
visible.push('contacts')
}
if ((supplier.addresses ?? []).length > 0) {
visible.push('addresses')
}
if (options.canAccountingView && hasAccountingData(supplier)) {
visible.push('accounting')
}
return visible
}
/**
* Bouton « Modifier » : visible si l'utilisateur peut editer au moins un onglet
* — `manage` (formulaire/onglets metier) OU `accounting.manage` (le role Compta
@@ -0,0 +1 @@
export default defineNuxtConfig({})
@@ -2,7 +2,7 @@
<div class="relative 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)]">
<!-- Suppression : modal de confirmation cote parent. -->
<MalioButtonIcon
v-if="removable && !readonly"
v-if="removable && !readonly && !disabled"
icon="mdi:delete-outline"
variant="ghost"
button-class="absolute top-3 right-3"
@@ -17,7 +17,8 @@
:label="t('technique.providers.form.address.sites')"
:display-tag="true"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.sites"
@update:model-value="(v: (string | number)[]) => update('siteIris', v.map(String))"
/>
@@ -29,7 +30,8 @@
:label="t('technique.providers.form.address.categories')"
:display-tag="true"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.categories"
@update:model-value="(v: (string | number)[]) => update('categoryIris', v.map(String))"
/>
@@ -41,6 +43,7 @@
:label="t('technique.providers.form.address.contacts')"
:display-tag="true"
:readonly="readonly"
:disabled="disabled"
@update:model-value="(v: (string | number)[]) => update('contactIris', v.map(String))"
/>
@@ -49,7 +52,8 @@
:options="countryOptions"
:label="t('technique.providers.form.address.country')"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
@update:model-value="(v: string | number | null) => update('country', String(v ?? 'France'))"
/>
@@ -58,7 +62,8 @@
:label="t('technique.providers.form.address.postalCode')"
:mask="POSTAL_CODE_MASK"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.postalCode"
@update:model-value="onPostalCodeChange"
/>
@@ -70,8 +75,9 @@
:options="cityOptions"
:label="t('technique.providers.form.address.city')"
:readonly="readonly"
:disabled="disabled"
empty-option-label=""
:required="true"
:required="!readonly && !disabled"
:error="errors?.city"
@update:model-value="(v: string | number | null) => update('city', v === null ? null : String(v))"
/>
@@ -79,8 +85,10 @@
v-else
:model-value="model.city"
:label="t('technique.providers.form.address.city')"
:mask="ADDRESS_MASK"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.city"
@update:model-value="(v: string) => update('city', v)"
/>
@@ -89,14 +97,15 @@
texte saisi est conserve si la BAN ne propose rien (saisie manuelle). -->
<div class="col-span-2">
<MalioInputAutocomplete
v-if="!readonly"
v-if="!readonly && !disabled"
:model-value="model.street"
:options="addressOptions"
:loading="addressLoading"
:min-search-length="3"
:label="t('technique.providers.form.address.street')"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.street"
:allow-create="true"
:no-results-text="t('technique.providers.form.address.streetNotFound')"
@@ -109,7 +118,8 @@
:model-value="model.street"
:label="t('technique.providers.form.address.street')"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.street"
@update:model-value="(v: string) => update('street', v)"
/>
@@ -119,7 +129,9 @@
<MalioInputText
:model-value="model.streetComplement"
:label="t('technique.providers.form.address.streetComplement')"
:mask="ADDRESS_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.streetComplement"
@update:model-value="(v: string) => update('streetComplement', v)"
/>
@@ -131,6 +143,7 @@
import { useAddressAutocomplete, type AddressSuggestion } from '~/shared/composables/useAddressAutocomplete'
import type { RefOption } from '~/modules/technique/composables/useProviderReferentials'
import type { ProviderAddressFormDraft } from '~/modules/technique/types/providerForm'
import { ADDRESS_MASK } from '~/shared/utils/textSanitize'
// Masque code postal FR : 5 chiffres.
const POSTAL_CODE_MASK = '#####'
@@ -148,6 +161,8 @@ const props = defineProps<{
countryOptions: RefOption[]
removable?: boolean
readonly?: boolean
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
disabled?: boolean
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
errors?: Record<string, string>
}>()
@@ -193,6 +208,11 @@ const addressLoading = ref(false)
// Conserve les suggestions d'adresse pour retrouver ville/CP au moment du select.
let lastAddressSuggestions: AddressSuggestion[] = []
// Filtrage des caracteres parasites : porte par le mask ADDRESS_MASK (maska) sur
// les champs texte editables (complement, ville en mode degrade). La voie en
// autocomplete (BAN) et la ville en select ne sont pas masquees (le back valide
// via Assert\Regex).
/** Emet un nouveau brouillon avec le champ modifie (immutabilite). */
function update<K extends keyof ProviderAddressFormDraft>(field: K, value: ProviderAddressFormDraft[K]): void {
emit('update:modelValue', { ...props.modelValue, [field]: value })
@@ -3,7 +3,7 @@
<!-- Suppression : ouvre une modal de confirmation cote parent. Masquee si
non supprimable (1er bloc) ou en lecture seule. -->
<MalioButtonIcon
v-if="removable && !readonly"
v-if="removable && !readonly && !disabled"
icon="mdi:delete-outline"
variant="ghost"
button-class="absolute top-3 right-3"
@@ -14,14 +14,18 @@
<MalioInputText
:model-value="model.lastName"
:label="t('technique.providers.form.contact.lastName')"
:mask="PERSON_NAME_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.lastName"
@update:model-value="(v: string) => update('lastName', v)"
/>
<MalioInputText
:model-value="model.firstName"
:label="t('technique.providers.form.contact.firstName')"
:mask="PERSON_NAME_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.firstName"
@update:model-value="(v: string) => update('firstName', v)"
/>
@@ -32,7 +36,9 @@
<MalioInputText
:model-value="model.jobTitle"
:label="t('technique.providers.form.contact.jobTitle')"
:mask="FREE_TEXT_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.jobTitle"
@update:model-value="(v: string) => update('jobTitle', v)"
/>
@@ -41,6 +47,7 @@
:model-value="model.email"
:label="t('technique.providers.form.contact.email')"
:readonly="readonly"
:disabled="disabled"
:lowercase="true"
:error="errors?.email"
@update:model-value="(v: string) => update('email', v)"
@@ -50,6 +57,7 @@
:label="t('technique.providers.form.contact.phonePrimary')"
:mask="PHONE_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.phonePrimary"
:addable="!model.hasSecondaryPhone && !readonly"
:add-button-label="t('technique.providers.form.contact.addPhone')"
@@ -63,6 +71,7 @@
:label="t('technique.providers.form.contact.phoneSecondary')"
:mask="PHONE_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.phoneSecondary"
@update:model-value="(v: string) => update('phoneSecondary', v)"
/>
@@ -71,6 +80,7 @@
<script setup lang="ts">
import type { ProviderContactFormDraft } from '~/modules/technique/types/providerForm'
import { FREE_TEXT_MASK, PERSON_NAME_MASK } from '~/shared/utils/textSanitize'
// Masque telephone FR : 5 groupes de 2 chiffres (la normalisation finale reste serveur).
const PHONE_MASK = '## ## ## ## ##'
@@ -82,6 +92,8 @@ const props = defineProps<{
removable?: boolean
/** Bloc en lecture seule (onglet valide). */
readonly?: boolean
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
disabled?: boolean
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
errors?: Record<string, string>
}>()
@@ -96,6 +108,10 @@ const { t } = useI18n()
// Alias local pour la lisibilite du template.
const model = computed(() => props.modelValue)
// Filtrage des caracteres parasites : porte par les masks maska sur les champs
// (PERSON_NAME_MASK / FREE_TEXT_MASK), filtrage natif au focus/curseur. L'email n'a
// pas de mask (ERP-101 : validation de format via Assert\Email + erreur inline).
/** Emet un nouveau brouillon avec le champ modifie (immutabilite). */
function update<K extends keyof ProviderContactFormDraft>(field: K, value: ProviderContactFormDraft[K]): void {
emit('update:modelValue', { ...props.modelValue, [field]: value })
@@ -44,7 +44,7 @@ describe('useProvidersRepository', () => {
expect(mockApiGet).toHaveBeenCalledTimes(1)
const [url, query, opts] = mockApiGet.mock.calls[0]
expect(url).toBe('/providers')
expect(query).toMatchObject({ page: 1, itemsPerPage: 10 })
expect(query).toMatchObject({ page: 1, itemsPerPage: 25 })
expect(opts).toMatchObject({
toast: false,
headers: { Accept: 'application/ld+json' },
@@ -84,6 +84,11 @@ export function useProviderForm() {
})
}
/** Toast de succès après suppression serveur confirmée d'une sous-ressource. */
function notifyRemovalSuccess(): void {
toast.success({ title: t('success.title'), message: t('success.deleted') })
}
// ── Etat du prestataire cree ────────────────────────────────────────────
const providerId = ref<number | null>(null)
const mainLocked = ref(false)
@@ -339,6 +344,7 @@ export function useProviderForm() {
deleteRow: url => api.delete(url, {}, { toast: false }),
makeEmpty: emptyProviderContact,
onError: notifyRemovalError,
onSuccess: notifyRemovalSuccess,
})
}
@@ -417,6 +423,7 @@ export function useProviderForm() {
deleteRow: url => api.delete(url, {}, { toast: false }),
makeEmpty: emptyProviderAddress,
onError: notifyRemovalError,
onSuccess: notifyRemovalSuccess,
})
}
@@ -518,6 +525,7 @@ export function useProviderForm() {
deleteRow: url => api.delete(url, {}, { toast: false }),
makeEmpty: emptyProviderRib,
onError: notifyRemovalError,
onSuccess: notifyRemovalSuccess,
})
}
@@ -59,5 +59,6 @@ export interface Provider {
* `usePaginatedList`. Aucun reset au logout a gerer.
*/
export function useProvidersRepository() {
return usePaginatedList<Provider>({ url: '/providers' })
// Pagination par defaut a 25 sur le repertoire (retour metier ERP-193).
return usePaginatedList<Provider>({ url: '/providers', defaultItemsPerPage: 25 })
}
@@ -22,8 +22,9 @@
<MalioInputText
v-model="main.companyName"
:label="t('technique.providers.form.main.companyName')"
:mask="FREE_TEXT_MASK"
:required="true"
:readonly="businessReadonly"
:disabled="businessReadonly"
:error="mainErrors.errors.companyName"
/>
<MalioSelectCheckbox
@@ -31,7 +32,7 @@
:options="referentials.categories.value"
:label="t('technique.providers.form.main.categories')"
:display-tag="true"
:readonly="businessReadonly"
:disabled="businessReadonly"
:required="true"
:error="mainErrors.errors.categories"
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
@@ -41,7 +42,7 @@
:options="referentials.sites.value"
:label="t('technique.providers.form.main.sites')"
:display-tag="true"
:readonly="businessReadonly"
:disabled="businessReadonly"
:required="true"
:error="mainErrors.errors.sites"
@update:model-value="(v: (string | number)[]) => main.siteIris = v.map(String)"
@@ -71,7 +72,7 @@
:key="index"
:model-value="contact"
:removable="isRowRemovable(contacts, index)"
:readonly="businessReadonly"
:disabled="businessReadonly"
:errors="contactErrors[index]"
@update:model-value="(v) => contacts[index] = v"
@remove="askRemoveContact(index)"
@@ -107,7 +108,7 @@
:contact-options="contactOptions"
:country-options="countryOptions"
:removable="isRowRemovable(addresses, index)"
:readonly="businessReadonly"
:disabled="businessReadonly"
:errors="addressErrors[index]"
@update:model-value="(v) => addresses[index] = v"
@remove="askRemoveAddress(index)"
@@ -141,14 +142,15 @@
v-model="accounting.siren"
:label="t('technique.providers.form.accounting.siren')"
:mask="SIREN_MASK"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.siren"
/>
<MalioInputText
v-model="accounting.accountNumber"
:label="t('technique.providers.form.accounting.accountNumber')"
:readonly="accountingReadonly"
:mask="CODE_ALNUM_MASK"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.accountNumber"
/>
@@ -156,7 +158,7 @@
:model-value="accounting.tvaModeIri"
:options="referentials.tvaModes.value"
:label="t('technique.providers.form.accounting.tvaMode')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.tvaMode"
@@ -165,7 +167,8 @@
<MalioInputText
v-model="accounting.nTva"
:label="t('technique.providers.form.accounting.nTva')"
:readonly="accountingReadonly"
:mask="CODE_ALNUM_MASK"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.nTva"
/>
@@ -173,7 +176,7 @@
:model-value="accounting.paymentDelayIri"
:options="referentials.paymentDelays.value"
:label="t('technique.providers.form.accounting.paymentDelay')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.paymentDelay"
@@ -183,7 +186,7 @@
:model-value="accounting.paymentTypeIri"
:options="referentials.paymentTypes.value"
:label="t('technique.providers.form.accounting.paymentType')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.paymentType"
@@ -194,7 +197,7 @@
:model-value="accounting.bankIri"
:options="referentials.banks.value"
:label="t('technique.providers.form.accounting.bank')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.bank"
@@ -221,21 +224,23 @@
<MalioInputText
v-model="rib.label"
:label="t('technique.providers.form.accounting.ribLabel')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="true"
:error="ribErrors[index]?.label"
/>
<MalioInputText
v-model="rib.bic"
:label="t('technique.providers.form.accounting.ribBic')"
:readonly="accountingReadonly"
:mask="CODE_ALNUM_MASK"
:disabled="accountingReadonly"
:required="true"
:error="ribErrors[index]?.bic"
/>
<MalioInputText
v-model="rib.iban"
:label="t('technique.providers.form.accounting.ribIban')"
:readonly="accountingReadonly"
:mask="CODE_ALNUM_MASK"
:disabled="accountingReadonly"
:required="true"
:error="ribErrors[index]?.iban"
/>
@@ -313,6 +318,7 @@ import {
} from '~/modules/technique/types/providerForm'
import { extractApiErrorMessage } from '~/shared/utils/api'
import { isRowRemovable } from '~/shared/utils/collectionRow'
import { CODE_ALNUM_MASK, FREE_TEXT_MASK } from '~/shared/utils/textSanitize'
// Masque SIREN : 9 chiffres (la normalisation finale reste serveur).
const SIREN_MASK = '#########'
@@ -22,7 +22,7 @@
/>
<MalioButton
v-if="showArchive"
variant="secondary"
variant="danger"
icon-name="mdi:archive-arrow-down-outline"
icon-position="left"
:label="t('technique.providers.action.archive')"
@@ -49,26 +49,27 @@
<MalioInputText
:model-value="provider.companyName"
:label="t('technique.providers.form.main.companyName')"
readonly
disabled
/>
<MalioSelectCheckbox
:model-value="mainCategoryIris"
:options="mainCategoryOptions"
:label="t('technique.providers.form.main.categories')"
:display-tag="true"
readonly
disabled
/>
<MalioSelectCheckbox
:model-value="mainSiteIris"
:options="mainSiteOptions"
:label="t('technique.providers.form.main.sites')"
:display-tag="true"
readonly
disabled
/>
</div>
<!-- Onglets (navigation libre, tout en lecture seule) -->
<MalioTabList v-model="activeTab" :tabs="tabs" :max-visible-tabs="5" :max-width="1100" class="mt-[60px]">
<!-- ERP-193 : barre masquee s'il ne reste aucun onglet non vide. -->
<MalioTabList v-if="visibleTabKeys.length" v-model="activeTab" :tabs="tabs" :max-visible-tabs="5" :max-width="1100" class="mt-[60px]">
<!-- Onglet Contacts -->
<template #contacts>
<div class="mt-12 flex flex-col gap-6">
@@ -76,7 +77,7 @@
v-for="(contact, index) in contacts"
:key="index"
:model-value="contact"
readonly
disabled
/>
</div>
</template>
@@ -92,27 +93,25 @@
:site-options="view.siteOptions"
:contact-options="contactOptions"
:country-options="countryOptionsFor(view.draft.country)"
readonly
disabled
/>
</div>
</template>
<!-- Onglets placeholder « A venir » (comme les autres modules). -->
<template #reports><ComingSoonPlaceholder /></template>
<template #exchanges><ComingSoonPlaceholder /></template>
<!-- ERP-193 : les onglets « a venir » (Rapports / Echanges) ne sont
plus rendus en consultation (masquage des onglets vides). -->
<!-- Onglet Comptabilite (present uniquement si accounting.view). -->
<template v-if="canAccountingView" #accounting>
<div class="mt-12 flex flex-col gap-6">
<div class="bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
<div class="grid grid-cols-4 gap-x-[44px] gap-y-4">
<MalioInputText :model-value="accounting.siren" :label="t('technique.providers.form.accounting.siren')" readonly />
<MalioInputText :model-value="accounting.accountNumber" :label="t('technique.providers.form.accounting.accountNumber')" readonly />
<MalioSelect :model-value="accounting.tvaModeIri" :options="tvaModeOptions" :label="t('technique.providers.form.accounting.tvaMode')" readonly empty-option-label="" />
<MalioInputText :model-value="accounting.nTva" :label="t('technique.providers.form.accounting.nTva')" readonly />
<MalioSelect :model-value="accounting.paymentDelayIri" :options="paymentDelayOptions" :label="t('technique.providers.form.accounting.paymentDelay')" readonly empty-option-label="" />
<MalioSelect :model-value="accounting.paymentTypeIri" :options="paymentTypeOptions" :label="t('technique.providers.form.accounting.paymentType')" readonly empty-option-label="" />
<MalioSelect v-if="isBankRequired" :model-value="accounting.bankIri" :options="bankOptions" :label="t('technique.providers.form.accounting.bank')" readonly empty-option-label="" />
<MalioInputText :model-value="accounting.siren" :label="t('technique.providers.form.accounting.siren')" disabled />
<MalioInputText :model-value="accounting.accountNumber" :label="t('technique.providers.form.accounting.accountNumber')" disabled />
<MalioSelect :model-value="accounting.tvaModeIri" :options="tvaModeOptions" :label="t('technique.providers.form.accounting.tvaMode')" disabled empty-option-label="" />
<MalioInputText :model-value="accounting.nTva" :label="t('technique.providers.form.accounting.nTva')" disabled />
<MalioSelect :model-value="accounting.paymentDelayIri" :options="paymentDelayOptions" :label="t('technique.providers.form.accounting.paymentDelay')" disabled empty-option-label="" />
<MalioSelect :model-value="accounting.paymentTypeIri" :options="paymentTypeOptions" :label="t('technique.providers.form.accounting.paymentType')" disabled empty-option-label="" />
<MalioSelect v-if="isBankRequired" :model-value="accounting.bankIri" :options="bankOptions" :label="t('technique.providers.form.accounting.bank')" disabled empty-option-label="" />
</div>
</div>
@@ -123,9 +122,9 @@
class="bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]"
>
<div class="grid grid-cols-4 gap-x-[44px] gap-y-4">
<MalioInputText :model-value="rib.label" :label="t('technique.providers.form.accounting.ribLabel')" readonly />
<MalioInputText :model-value="rib.bic" :label="t('technique.providers.form.accounting.ribBic')" readonly />
<MalioInputText :model-value="rib.iban" :label="t('technique.providers.form.accounting.ribIban')" readonly />
<MalioInputText :model-value="rib.label" :label="t('technique.providers.form.accounting.ribLabel')" disabled />
<MalioInputText :model-value="rib.bic" :label="t('technique.providers.form.accounting.ribBic')" disabled />
<MalioInputText :model-value="rib.iban" :label="t('technique.providers.form.accounting.ribIban')" disabled />
</div>
</div>
</div>
@@ -158,7 +157,7 @@
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useProvider } from '~/modules/technique/composables/useProvider'
import {
canEditProvider,
@@ -170,6 +169,7 @@ import {
mapContactToDraft,
mapRibToDraft,
paymentTypeCodeOf,
providerConsultationVisibleTabs,
referentialOptionOf,
showArchiveAction,
showRestoreAction,
@@ -197,7 +197,6 @@ const headerTitle = computed(() => provider.value?.companyName || t('technique.p
useHead({ title: t('technique.providers.consultation.title') })
// ── Onglets (ordre spec : Contacts · Adresse · Rapports · Échanges · Comptabilité) ──
const activeTab = ref('contacts')
const TAB_ICONS: Record<string, string> = {
contacts: 'mdi:account-box-plus-outline',
address: 'mdi:map-marker-outline',
@@ -205,11 +204,27 @@ const TAB_ICONS: Record<string, string> = {
exchanges: 'mdi:swap-horizontal',
accounting: 'mdi:bank-circle-outline',
}
const tabs = computed(() => {
const keys = ['contacts', 'address', 'reports', 'exchanges']
if (canAccountingView.value) keys.push('accounting')
return keys.map(key => ({ key, label: t(`technique.providers.tab.${key}`), icon: TAB_ICONS[key] }))
})
// ERP-193 (retour metier) : on masque les coquilles (Rapports / Echanges) ET
// tout onglet de donnees vide. La liste depend donc du payload charge.
const visibleTabKeys = computed(() => providerConsultationVisibleTabs(provider.value, {
canAccountingView: canAccountingView.value,
}))
const tabs = computed(() => visibleTabKeys.value.map(
key => ({ key, label: t(`technique.providers.tab.${key}`), icon: TAB_ICONS[key] }),
))
// Onglet initial : vide tant que le prestataire n'est pas charge, puis premier
// onglet visible. Un watcher recale si l'onglet courant disparait.
const activeTab = ref('')
watch(visibleTabKeys, (keys) => {
if (keys.length === 0) {
activeTab.value = ''
return
}
if (!keys.includes(activeTab.value)) {
activeTab.value = keys[0]
}
}, { immediate: true })
// ── Donnees mappees depuis la SEULE reponse detail ─────────────────────────────
const mainCategoryIris = computed(() => irisOf(provider.value?.categories))
@@ -44,7 +44,7 @@
@update:page="goToPage"
@update:per-page="setItemsPerPage"
>
<!-- Categories : libelles (name) separes par une virgule. -->
<!-- Categories : codes stables (MAJUSCULE) separes par une virgule, aligne sur le client (ERP-193). -->
<template #cell-categories="{ item }">
{{ formatCategories(item) }}
</template>
@@ -210,10 +210,10 @@ const columns = [
{ key: 'lastActivity', label: t('technique.providers.column.lastActivity') },
]
/** Libelles des categories du prestataire, separes par une virgule (name). */
/** Codes (MAJUSCULE) des categories du prestataire, separes par une virgule (aligne sur le client, ERP-193). */
function formatCategories(item: Record<string, unknown>): string {
const categories = (item.categories as Provider['categories']) ?? []
return categories.map(c => c.name).join(', ')
return categories.map(c => c.code).join(', ')
}
/**
@@ -21,8 +21,9 @@
<MalioInputText
v-model="main.companyName"
:label="t('technique.providers.form.main.companyName')"
:mask="FREE_TEXT_MASK"
:required="true"
:readonly="mainLocked"
:disabled="mainLocked"
:error="mainErrors.errors.companyName"
/>
<MalioSelectCheckbox
@@ -30,7 +31,7 @@
:options="referentials.categories.value"
:label="t('technique.providers.form.main.categories')"
:display-tag="true"
:readonly="mainLocked"
:disabled="mainLocked"
:required="true"
:error="mainErrors.errors.categories"
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
@@ -40,7 +41,7 @@
:options="referentials.sites.value"
:label="t('technique.providers.form.main.sites')"
:display-tag="true"
:readonly="mainLocked"
:disabled="mainLocked"
:required="true"
:error="mainErrors.errors.sites"
@update:model-value="(v: (string | number)[]) => main.siteIris = v.map(String)"
@@ -72,12 +73,16 @@
:key="index"
:model-value="contact"
:removable="isRowRemovable(contacts, index)"
:readonly="isValidated('contact')"
:disabled="isValidated('contact')"
:errors="contactErrors[index]"
@update:model-value="(v) => contacts[index] = v"
@remove="askRemoveContact(index)"
/>
<div v-if="!isValidated('contact')" class="flex justify-center gap-6">
<!-- Masque tant que le prestataire n'est pas cree : Contact etant
l'onglet actif par defaut, ses actions (Ajouter / Valider) ne
doivent pas apparaitre a cote du Valider du formulaire principal
(ERP-193). -->
<div v-if="!isValidated('contact') && providerId !== null" class="flex justify-center gap-6">
<MalioButton
variant="secondary"
icon-name="mdi:add-bold"
@@ -89,7 +94,7 @@
<MalioButton
variant="primary"
:label="t('technique.providers.form.submit')"
:disabled="tabSubmitting || providerId === null"
:disabled="tabSubmitting"
@click="onSubmitContacts"
/>
</div>
@@ -107,7 +112,7 @@
:contact-options="contactOptions"
:country-options="countryOptions"
:removable="isRowRemovable(addresses, index)"
:readonly="isValidated('address')"
:disabled="isValidated('address')"
:errors="addressErrors[index]"
@update:model-value="(v) => addresses[index] = v"
@remove="askRemoveAddress(index)"
@@ -140,14 +145,15 @@
v-model="accounting.siren"
:label="t('technique.providers.form.accounting.siren')"
:mask="SIREN_MASK"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.siren"
/>
<MalioInputText
v-model="accounting.accountNumber"
:label="t('technique.providers.form.accounting.accountNumber')"
:readonly="accountingReadonly"
:mask="CODE_ALNUM_MASK"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.accountNumber"
/>
@@ -155,7 +161,7 @@
:model-value="accounting.tvaModeIri"
:options="referentials.tvaModes.value"
:label="t('technique.providers.form.accounting.tvaMode')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.tvaMode"
@@ -164,7 +170,8 @@
<MalioInputText
v-model="accounting.nTva"
:label="t('technique.providers.form.accounting.nTva')"
:readonly="accountingReadonly"
:mask="CODE_ALNUM_MASK"
:disabled="accountingReadonly"
:required="true"
:error="accountingErrors.errors.nTva"
/>
@@ -172,7 +179,7 @@
:model-value="accounting.paymentDelayIri"
:options="referentials.paymentDelays.value"
:label="t('technique.providers.form.accounting.paymentDelay')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.paymentDelay"
@@ -182,7 +189,7 @@
:model-value="accounting.paymentTypeIri"
:options="referentials.paymentTypes.value"
:label="t('technique.providers.form.accounting.paymentType')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.paymentType"
@@ -194,7 +201,7 @@
:model-value="accounting.bankIri"
:options="referentials.banks.value"
:label="t('technique.providers.form.accounting.bank')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
empty-option-label=""
:required="true"
:error="accountingErrors.errors.bank"
@@ -221,21 +228,23 @@
<MalioInputText
v-model="rib.label"
:label="t('technique.providers.form.accounting.ribLabel')"
:readonly="accountingReadonly"
:disabled="accountingReadonly"
:required="true"
:error="ribErrors[index]?.label"
/>
<MalioInputText
v-model="rib.bic"
:label="t('technique.providers.form.accounting.ribBic')"
:readonly="accountingReadonly"
:mask="CODE_ALNUM_MASK"
:disabled="accountingReadonly"
:required="true"
:error="ribErrors[index]?.bic"
/>
<MalioInputText
v-model="rib.iban"
:label="t('technique.providers.form.accounting.ribIban')"
:readonly="accountingReadonly"
:mask="CODE_ALNUM_MASK"
:disabled="accountingReadonly"
:required="true"
:error="ribErrors[index]?.iban"
/>
@@ -297,6 +306,7 @@ import {
} from '~/modules/technique/utils/forms/providerAccounting'
import { extractApiErrorMessage } from '~/shared/utils/api'
import { isRowRemovable } from '~/shared/utils/collectionRow'
import { CODE_ALNUM_MASK, FREE_TEXT_MASK } from '~/shared/utils/textSanitize'
// Masque SIREN : 9 chiffres (la normalisation finale reste serveur).
const SIREN_MASK = '#########'
@@ -10,6 +10,7 @@ const {
canEditProvider,
categoryOptionsOf,
contactOptionsOf,
hasAccountingData,
iriOf,
irisOf,
mapAccountingDraft,
@@ -17,6 +18,7 @@ const {
mapContactToDraft,
mapRibToDraft,
paymentTypeCodeOf,
providerConsultationVisibleTabs,
referentialOptionOf,
showArchiveAction,
showRestoreAction,
@@ -165,3 +167,48 @@ describe('providerDetail helpers', () => {
})
})
})
describe('hasAccountingData (prestataire)', () => {
it('faux sans champ comptable ni RIB', () => {
expect(hasAccountingData({ '@id': '/api/providers/1', id: 1 })).toBe(false)
})
it('vrai avec un champ comptable ou un RIB', () => {
expect(hasAccountingData({ '@id': '/api/providers/1', id: 1, siren: '123456789' })).toBe(true)
expect(hasAccountingData({
'@id': '/api/providers/1', id: 1,
ribs: [{ '@id': '/api/provider_ribs/1', id: 1, iban: 'FR76...' }],
})).toBe(true)
})
})
describe('providerConsultationVisibleTabs', () => {
it('retourne [] tant que le prestataire n\'est pas charge', () => {
expect(providerConsultationVisibleTabs(null, { canAccountingView: true })).toEqual([])
})
it('masque les coquilles (reports/exchanges) et les onglets vides', () => {
expect(providerConsultationVisibleTabs(
{ '@id': '/api/providers/1', id: 1, companyName: 'ACME' },
{ canAccountingView: true },
)).toEqual([])
})
it('affiche contacts/address/accounting dans l\'ordre (pas d\'onglet information)', () => {
const provider = {
'@id': '/api/providers/1', id: 1,
contacts: [{ '@id': '/api/provider_contacts/1', id: 1 }],
addresses: [{ '@id': '/api/provider_addresses/1', id: 1 }],
siren: '123456789',
}
expect(providerConsultationVisibleTabs(provider, { canAccountingView: true }))
.toEqual(['contacts', 'address', 'accounting'])
})
it('masque Comptabilite sans le droit accounting.view', () => {
expect(providerConsultationVisibleTabs(
{ '@id': '/api/providers/1', id: 1, siren: '123456789' },
{ canAccountingView: false },
)).toEqual([])
})
})
@@ -224,6 +224,58 @@ export function paymentTypeCodeOf(relation: Relation): string | null {
return (relation.code as string | undefined) ?? null
}
/**
* Vrai si une valeur scalaire porte une donnee affichable (non null/undefined,
* et non chaine vide apres trim). Sert au predicat « onglet vide » ci-dessous.
*/
function hasValue(value: unknown): boolean {
if (value === null || value === undefined) {
return false
}
if (typeof value === 'string') {
return value.trim() !== ''
}
return true
}
/**
* Vrai si l'onglet Comptabilite porte au moins un champ comptable OU un RIB.
* (Le gating permission `accounting.view` reste applique en amont par l'appelant.)
*/
export function hasAccountingData(provider: ProviderDetail): boolean {
const draft = mapAccountingDraft(provider)
const hasField = Object.values(draft).some(hasValue)
const hasRib = (provider.ribs ?? []).length > 0
return hasField || hasRib
}
/**
* Onglets visibles en consultation (ERP-193, retour metier) : on masque les
* coquilles non implementees (Rapports / Echanges) ET tout onglet de donnees
* vide. Le prestataire n'a pas d'onglet Information (bloc principal au-dessus
* des onglets). Ordre : Contacts · Adresse · Comptabilite. Retourne `[]` tant
* que le prestataire n'est pas charge.
*/
export function providerConsultationVisibleTabs(
provider: ProviderDetail | null | undefined,
options: { canAccountingView: boolean },
): string[] {
if (!provider) {
return []
}
const visible: string[] = []
if ((provider.contacts ?? []).length > 0) {
visible.push('contacts')
}
if ((provider.addresses ?? []).length > 0) {
visible.push('address')
}
if (options.canAccountingView && hasAccountingData(provider)) {
visible.push('accounting')
}
return visible
}
/**
* Bouton « Modifier » : visible si l'utilisateur peut editer au moins un onglet
* `manage` (onglets metier) OU `accounting.manage` (le role Compta doit pouvoir
@@ -1,22 +1,14 @@
<template>
<!-- Adresse UNIQUE par transporteur (ERP-172) : un seul bloc, jamais supprimable. -->
<div class="relative 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)]">
<!-- Suppression : modal de confirmation cote parent. -->
<MalioButtonIcon
v-if="removable && !readonly"
icon="mdi:delete-outline"
variant="ghost"
button-class="absolute top-3 right-3"
v-bind="{ ariaLabel: t('transport.carriers.form.address.remove') }"
@click="$emit('remove')"
/>
<!-- Pays : prerempli « France » (RG-4.05). -->
<MalioSelect
:model-value="model.country"
:options="countryOptions"
:label="t('transport.carriers.form.address.country')"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.country"
@update:model-value="(v: string | number | null) => update('country', String(v ?? 'France'))"
/>
@@ -27,7 +19,8 @@
:label="t('transport.carriers.form.address.postalCode')"
:mask="POSTAL_CODE_MASK"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.postalCode"
@update:model-value="onPostalCodeChange"
/>
@@ -39,8 +32,9 @@
:options="cityOptions"
:label="t('transport.carriers.form.address.city')"
:readonly="readonly"
:disabled="disabled"
empty-option-label=""
:required="true"
:required="!readonly && !disabled"
:error="errors?.city"
@update:model-value="(v: string | number | null) => update('city', v === null ? null : String(v))"
/>
@@ -48,8 +42,10 @@
v-else
:model-value="model.city"
:label="t('transport.carriers.form.address.city')"
:mask="ADDRESS_MASK"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.city"
@update:model-value="(v: string) => update('city', v)"
/>
@@ -61,14 +57,15 @@
texte saisi est conserve si la BAN ne propose rien (saisie manuelle). -->
<div class="col-span-2">
<MalioInputAutocomplete
v-if="!readonly"
v-if="!readonly && !disabled"
:model-value="model.street"
:options="addressOptions"
:loading="addressLoading"
:min-search-length="3"
:label="t('transport.carriers.form.address.street')"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.street"
:allow-create="true"
:no-results-text="t('transport.carriers.form.address.streetNotFound')"
@@ -81,7 +78,8 @@
:model-value="model.street"
:label="t('transport.carriers.form.address.street')"
:readonly="readonly"
:required="true"
:disabled="disabled"
:required="!readonly && !disabled"
:error="errors?.street"
@update:model-value="(v: string) => update('street', v)"
/>
@@ -90,7 +88,9 @@
<MalioInputText
:model-value="model.streetComplement"
:label="t('transport.carriers.form.address.streetComplement')"
:mask="ADDRESS_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.streetComplement"
@update:model-value="(v: string) => update('streetComplement', v)"
/>
@@ -100,6 +100,7 @@
<script setup lang="ts">
import { useAddressAutocomplete, type AddressSuggestion } from '~/shared/composables/useAddressAutocomplete'
import type { CarrierAddressFormDraft } from '~/modules/transport/types/carrierForm'
import { ADDRESS_MASK } from '~/shared/utils/textSanitize'
interface RefOption {
value: string
@@ -114,15 +115,15 @@ const props = defineProps<{
modelValue: CarrierAddressFormDraft
/** Pays disponibles (France par defaut). */
countryOptions: RefOption[]
removable?: boolean
readonly?: boolean
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
disabled?: boolean
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
errors?: Record<string, string>
}>()
const emit = defineEmits<{
'update:modelValue': [value: CarrierAddressFormDraft]
'remove': []
/** Emis une fois quand le service d'autocompletion bascule en indisponible. */
'degraded': []
}>()
@@ -161,6 +162,10 @@ const addressLoading = ref(false)
// Conserve les suggestions d'adresse pour retrouver ville/CP au moment du select.
let lastAddressSuggestions: AddressSuggestion[] = []
// Filtrage des caracteres parasites : porte par le mask ADDRESS_MASK (maska) sur les
// champs texte editables (complement, ville en mode degrade). La voie en autocomplete
// (BAN) et la ville en select ne sont pas masquees (le back valide via Assert\Regex).
/** Emet un nouveau brouillon avec le champ modifie (immutabilite). */
function update<K extends keyof CarrierAddressFormDraft>(field: K, value: CarrierAddressFormDraft[K]): void {
emit('update:modelValue', { ...props.modelValue, [field]: value })
@@ -3,7 +3,7 @@
<!-- Suppression : ouvre une modal de confirmation côté parent. Masquée si
non supprimable (1er bloc) ou en lecture seule. -->
<MalioButtonIcon
v-if="removable && !readonly"
v-if="removable && !readonly && !disabled"
icon="mdi:delete-outline"
variant="ghost"
button-class="absolute top-3 right-3"
@@ -14,14 +14,18 @@
<MalioInputText
:model-value="model.lastName"
:label="t('transport.carriers.form.contact.lastName')"
:mask="PERSON_NAME_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.lastName"
@update:model-value="(v: string) => update('lastName', v)"
/>
<MalioInputText
:model-value="model.firstName"
:label="t('transport.carriers.form.contact.firstName')"
:mask="PERSON_NAME_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.firstName"
@update:model-value="(v: string) => update('firstName', v)"
/>
@@ -31,7 +35,9 @@
<MalioInputText
:model-value="model.jobTitle"
:label="t('transport.carriers.form.contact.jobTitle')"
:mask="FREE_TEXT_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.jobTitle"
@update:model-value="(v: string) => update('jobTitle', v)"
/>
@@ -40,6 +46,7 @@
:model-value="model.email"
:label="t('transport.carriers.form.contact.email')"
:readonly="readonly"
:disabled="disabled"
:lowercase="true"
:error="errors?.email"
@update:model-value="(v: string) => update('email', v)"
@@ -50,6 +57,7 @@
:label="t('transport.carriers.form.contact.phonePrimary')"
:mask="PHONE_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.phonePrimary"
:addable="!model.hasSecondaryPhone && !readonly"
:add-button-label="t('transport.carriers.form.contact.addPhone')"
@@ -63,6 +71,7 @@
:label="t('transport.carriers.form.contact.phoneSecondary')"
:mask="PHONE_MASK"
:readonly="readonly"
:disabled="disabled"
:error="errors?.phoneSecondary"
@update:model-value="(v: string) => update('phoneSecondary', v)"
/>
@@ -71,6 +80,7 @@
<script setup lang="ts">
import type { CarrierContactFormDraft } from '~/modules/transport/types/carrierForm'
import { FREE_TEXT_MASK, PERSON_NAME_MASK } from '~/shared/utils/textSanitize'
// Masque téléphone FR : 5 groupes de 2 chiffres (la normalisation finale reste serveur).
const PHONE_MASK = '## ## ## ## ##'
@@ -82,6 +92,8 @@ const props = defineProps<{
removable?: boolean
/** Bloc en lecture seule (onglet validé). */
readonly?: boolean
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
disabled?: boolean
/** Erreurs serveur 422 de cette ligne, indexées par champ (ERP-101). */
errors?: Record<string, string>
}>()
@@ -96,6 +108,10 @@ const { t } = useI18n()
// Alias local pour la lisibilité du template.
const model = computed(() => props.modelValue)
// Filtrage des caractères parasites : porté par les masks maska sur les champs
// (PERSON_NAME_MASK / FREE_TEXT_MASK), filtrage natif au focus/curseur. L'email n'a
// pas de mask (ERP-101 : validation de format via Assert\Email + erreur inline).
/** Émet un nouveau brouillon avec le champ modifié (immutabilité). */
function update<K extends keyof CarrierContactFormDraft>(field: K, value: CarrierContactFormDraft[K]): void {
emit('update:modelValue', { ...props.modelValue, [field]: value })
@@ -0,0 +1,317 @@
<template>
<div class="relative 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)]">
<!-- Suppression : modal de confirmation côté parent. -->
<MalioButtonIcon
v-if="removable && !readonly && !disabled"
icon="mdi:delete-outline"
variant="ghost"
button-class="absolute top-3 right-3"
v-bind="{ ariaLabel: t('transport.carriers.form.price.remove') }"
@click="$emit('remove')"
/>
<!-- RG-4.09 : sens du prix (CLIENT / FOURNISSEUR) en colonne 1 / ligne 1, radios
EN LIGNE (horizontaux), centrés sur la hauteur de champ (h-12) comme la
case « Affréter ». Pas de label de groupe. -->
<div>
<div class="flex h-12 items-center gap-6">
<MalioRadioButton
:model-value="model.direction"
:name="`price-direction-${uid}`"
value="CLIENT"
:label="t('transport.carriers.form.price.directionClient')"
:disabled="readonly || disabled"
group-class="mt-0"
@update:model-value="onDirectionChange"
/>
<MalioRadioButton
:model-value="model.direction"
:name="`price-direction-${uid}`"
value="FOURNISSEUR"
:label="t('transport.carriers.form.price.directionSupplier')"
:disabled="readonly || disabled"
group-class="mt-0"
@update:model-value="onDirectionChange"
/>
</div>
<p v-if="errors?.direction" class="ml-[2px] text-xs text-m-danger">{{ errors.direction }}</p>
</div>
<!-- Branche CLIENT (RG-4.10). -->
<template v-if="model.direction === 'CLIENT'">
<MalioSelect
:model-value="model.clientIri"
:options="clientOptions"
:label="t('transport.carriers.form.price.client')"
empty-option-label=""
:required="true"
:readonly="readonly"
:disabled="disabled"
:error="errors?.client"
@update:model-value="onClientChange"
/>
<MalioSelect
:model-value="model.clientDeliveryAddressIri"
:options="clientAddressOptions"
:label="t('transport.carriers.form.price.clientDeliveryAddress')"
empty-option-label=""
:required="true"
:readonly="readonly"
:disabled="disabled"
:error="errors?.clientDeliveryAddress"
@update:model-value="(v: string | number | null) => update('clientDeliveryAddressIri', v === null ? null : String(v))"
/>
<MalioSelect
:model-value="model.departureSiteIri"
:options="siteOptions"
:label="t('transport.carriers.form.price.departureSite')"
empty-option-label=""
:required="true"
:readonly="readonly"
:disabled="disabled"
:error="errors?.departureSite"
@update:model-value="(v: string | number | null) => update('departureSiteIri', v === null ? null : String(v))"
/>
</template>
<!-- Branche FOURNISSEUR (RG-4.11). -->
<template v-else-if="model.direction === 'FOURNISSEUR'">
<MalioSelect
:model-value="model.supplierIri"
:options="supplierOptions"
:label="t('transport.carriers.form.price.supplier')"
empty-option-label=""
:required="true"
:readonly="readonly"
:disabled="disabled"
:error="errors?.supplier"
@update:model-value="onSupplierChange"
/>
<MalioSelect
:model-value="model.supplierSupplyAddressIri"
:options="supplierAddressOptions"
:label="t('transport.carriers.form.price.supplierSupplyAddress')"
empty-option-label=""
:required="true"
:readonly="readonly"
:disabled="disabled"
:error="errors?.supplierSupplyAddress"
@update:model-value="(v: string | number | null) => update('supplierSupplyAddressIri', v === null ? null : String(v))"
/>
<MalioSelect
:model-value="model.deliverySiteIri"
:options="siteOptions"
:label="t('transport.carriers.form.price.deliverySite')"
empty-option-label=""
:required="true"
:readonly="readonly"
:disabled="disabled"
:error="errors?.deliverySite"
@update:model-value="(v: string | number | null) => update('deliverySiteIri', v === null ? null : String(v))"
/>
</template>
<!-- Communs (visibles dès qu'un sens est choisi). -->
<template v-if="model.direction !== null">
<!-- Contenant : Benne / Fond mouvant (radios centrés h-12, pas de label). -->
<div>
<div class="flex h-12 items-center gap-4">
<MalioRadioButton
:model-value="model.containerType"
:name="`price-container-${uid}`"
value="BENNE"
:label="t('transport.carriers.containerType.BENNE')"
:disabled="readonly || disabled"
group-class="mt-0"
@update:model-value="(v: string | number | boolean | null) => update('containerType', v === null ? null : String(v))"
/>
<MalioRadioButton
:model-value="model.containerType"
:name="`price-container-${uid}`"
value="FOND_MOUVANT"
:label="t('transport.carriers.containerType.FOND_MOUVANT')"
:disabled="readonly || disabled"
group-class="mt-0"
@update:model-value="(v: string | number | boolean | null) => update('containerType', v === null ? null : String(v))"
/>
</div>
<p v-if="errors?.containerType" class="ml-[2px] text-xs text-m-danger">{{ errors.containerType }}</p>
</div>
<!-- Tarification : Forfait / Tonne (radios centrés h-12, pas de label). -->
<div>
<div class="flex h-12 items-center gap-4">
<MalioRadioButton
:model-value="model.pricingUnit"
:name="`price-unit-${uid}`"
value="FORFAIT"
:label="t('transport.carriers.form.price.pricingForfait')"
:disabled="readonly || disabled"
group-class="mt-0"
@update:model-value="(v: string | number | boolean | null) => update('pricingUnit', v === null ? null : String(v))"
/>
<MalioRadioButton
:model-value="model.pricingUnit"
:name="`price-unit-${uid}`"
value="TONNE"
:label="t('transport.carriers.form.price.pricingTonne')"
:disabled="readonly || disabled"
group-class="mt-0"
@update:model-value="(v: string | number | boolean | null) => update('pricingUnit', v === null ? null : String(v))"
/>
</div>
<p v-if="errors?.pricingUnit" class="ml-[2px] text-xs text-m-danger">{{ errors.pricingUnit }}</p>
</div>
<MalioInputAmount
:model-value="model.price"
:label="t('transport.carriers.form.price.price')"
:required="true"
:readonly="readonly"
:disabled="disabled"
:error="errors?.price"
@update:model-value="(v: string) => update('price', v)"
/>
<MalioSelect
:model-value="model.priceState"
:options="priceStateOptions"
:label="t('transport.carriers.form.price.priceState')"
empty-option-label=""
:required="true"
:readonly="readonly"
:disabled="disabled"
:error="errors?.priceState"
@update:model-value="(v: string | number | null) => update('priceState', v === null ? null : String(v))"
/>
</template>
</div>
</template>
<script setup lang="ts">
import { computed, ref, useId, watch } from 'vue'
import type { CarrierPriceFormDraft } from '~/modules/transport/types/carrierForm'
interface SelectOption {
value: string
label: string
}
const props = defineProps<{
/** Brouillon du prix (v-model). */
modelValue: CarrierPriceFormDraft
/** Clients disponibles (IRI en value). */
clientOptions: SelectOption[]
/** Fournisseurs disponibles (IRI en value). */
supplierOptions: SelectOption[]
/** Sites Starseed (3 sites — IRI en value). */
siteOptions: SelectOption[]
removable?: boolean
readonly?: boolean
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
disabled?: boolean
/** Erreurs serveur 422 de cette ligne, indexées par champ (ERP-101). */
errors?: Record<string, string>
}>()
const emit = defineEmits<{
'update:modelValue': [value: CarrierPriceFormDraft]
'remove': []
}>()
const { t } = useI18n()
const api = useApi()
// Identifiant unique par instance : les groupes de radios (sens / contenant / tarif)
// doivent avoir un `name` PROPRE à chaque bloc prix, sinon plusieurs blocs partagent
// le même groupe HTML et leurs radios se désélectionnent mutuellement.
const uid = useId()
const model = computed(() => props.modelValue)
const priceStateOptions = computed<SelectOption[]>(() => [
{ value: 'EN_COURS', label: t('transport.carriers.form.price.stateEnCours') },
{ value: 'VALIDE', label: t('transport.carriers.form.price.stateValide') },
{ value: 'NON_VALIDE', label: t('transport.carriers.form.price.stateNonValide') },
])
// Adresses chargées à la volée pour le client / fournisseur sélectionné (par bloc).
const clientAddressOptions = ref<SelectOption[]>([])
const supplierAddressOptions = ref<SelectOption[]>([])
/** Émet un nouveau brouillon avec le champ modifié (immutabilité). */
function update<K extends keyof CarrierPriceFormDraft>(field: K, value: CarrierPriceFormDraft[K]): void {
emit('update:modelValue', { ...props.modelValue, [field]: value })
}
/** Changement de sens : réinitialise les DEUX branches (cohérence CHECK BDD). */
function onDirectionChange(value: string | number | boolean | null): void {
const direction = value === 'CLIENT' || value === 'FOURNISSEUR' ? value : null
emit('update:modelValue', {
...props.modelValue,
direction,
clientIri: null,
clientDeliveryAddressIri: null,
departureSiteIri: null,
supplierIri: null,
supplierSupplyAddressIri: null,
deliverySiteIri: null,
})
}
/** Sélection d'un client → maj IRI + reset de l'adresse de livraison (autre client). */
function onClientChange(value: string | number | null): void {
emit('update:modelValue', {
...props.modelValue,
clientIri: value === null ? null : String(value),
clientDeliveryAddressIri: null,
})
}
/** Sélection d'un fournisseur → maj IRI + reset de l'adresse d'appro. */
function onSupplierChange(value: string | number | null): void {
emit('update:modelValue', {
...props.modelValue,
supplierIri: value === null ? null : String(value),
supplierSupplyAddressIri: null,
})
}
/** Réponse détail (client / fournisseur) embarquant ses adresses. */
interface ParentWithAddresses {
addresses?: { '@id': string, street?: string | null, postalCode?: string | null, city?: string | null }[]
}
/** Mappe les adresses embarquées en options (IRI en value, voie · CP · ville en label). */
function toAddressOptions(parent: ParentWithAddresses): SelectOption[] {
return (parent.addresses ?? []).map(a => ({
value: a['@id'],
label: [a.street, a.postalCode, a.city].filter(Boolean).join(' · ') || a['@id'],
}))
}
/**
* Charge les adresses d'un parent (client/fournisseur) à la volée via son détail
* (GET de l'IRI, qui embarque `addresses`). Échec liste vide (non bloquant).
*/
async function loadAddresses(iri: string | null, target: typeof clientAddressOptions): Promise<void> {
if (!iri) {
target.value = []
return
}
try {
// L'IRI est absolue (/api/clients/5) ; useApi préfixe déjà /api on le retire.
const path = iri.replace(/^\/api/, '')
const data = await api.get<ParentWithAddresses>(path, {}, { headers: { Accept: 'application/ld+json' }, toast: false })
target.value = toAddressOptions(data)
}
catch {
target.value = []
}
}
// Recharge les adresses quand le client / fournisseur change (immediate pour le
// pré-remplissage en édition).
watch(() => props.modelValue.clientIri, iri => loadAddresses(iri, clientAddressOptions), { immediate: true })
watch(() => props.modelValue.supplierIri, iri => loadAddresses(iri, supplierAddressOptions), { immediate: true })
</script>
@@ -0,0 +1,201 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { debounce } from '~/shared/utils/debounce'
import { useQualimatSearch, type QualimatCarrierRow } from '~/modules/transport/composables/useQualimatSearch'
/**
* Onglet « Qualimat » saisie assistée par recherche dans le référentiel QUALIMAT
* (RG-4.01 / RG-4.04). Datatable paginé filtré par le NOM (`searchName`), sélection
* d'une ligne → modal de confirmation → `integrate`. Mutualisé entre l'écran
* d'AJOUT (ERP-166) et l'écran de MODIFICATION (ERP-172, « actualiser le
* transporteur »). La persistance (copie nom / certification / FK) est portée par
* le parent via `useCarrierForm.applyQualimatSelection`.
*/
const props = defineProps<{
/** Terme de recherche (nom du transporteur saisi dans le formulaire principal). */
searchName: string
/** IRI QUALIMAT actuellement lié (coche le radio de la ligne correspondante). */
selectedIri: string | null
}>()
const emit = defineEmits<{
(event: 'integrate', row: QualimatCarrierRow): void
}>()
const { t } = useI18n()
const {
items: qualimatItems,
totalItems: qualimatTotal,
currentPage: qualimatPage,
itemsPerPage: qualimatPerPage,
itemsPerPageOptions: qualimatPerPageOptions,
goToPage: qualimatGoToPage,
setItemsPerPage: qualimatSetPerPage,
setFilters: qualimatSetFilters,
} = useQualimatSearch()
// Colonnes du datatable de sélection QUALIMAT (radio / Nom / Adresse / Validité).
const qualimatColumns = [
{ key: 'select', label: '' },
{ key: 'name', label: t('transport.carriers.form.qualimat.columns.name') },
{ key: 'address', label: t('transport.carriers.form.qualimat.columns.address') },
{ key: 'validityDate', label: t('transport.carriers.form.qualimat.columns.validityDate') },
]
// Le datatable n'affiche QUE des résultats de recherche : vide tant que le Nom n'est
// pas saisi (pas de liste complète par défaut).
const hasQualimatSearch = computed(() => props.searchName.trim() !== '')
const qualimatRows = computed(() => {
if (!hasQualimatSearch.value) {
return []
}
return qualimatItems.value.map(row => ({
id: row.id,
iri: row['@id'],
name: row.name,
address: formatQualimatAddress(row),
validityDate: row.validityDate,
}))
})
const qualimatTotalDisplay = computed(() => (hasQualimatSearch.value ? qualimatTotal.value : 0))
const qualimatEmptyMessage = computed(() => hasQualimatSearch.value
? t('transport.carriers.form.qualimat.empty')
: t('transport.carriers.form.qualimat.searchHint'))
// Re-filtrage debouncé sur le nom ; aucune recherche tant que le Nom est vide.
const filterQualimatByName = debounce((term: string) => {
if (term.trim() === '') {
return
}
void qualimatSetFilters({ search: term })
}, 300)
watch(() => props.searchName, term => filterQualimatByName(term), { immediate: true })
/** Adresse QUALIMAT condensée pour la colonne « Adresse » (voie · CP · ville). */
function formatQualimatAddress(row: QualimatCarrierRow): string {
return [row.address, row.postalCode, row.city].filter(Boolean).join(' · ')
}
/** RG-4.04 : un agrément est périmé si sa date de validité est < aujourd'hui. */
function isExpired(value: string): boolean {
const date = new Date(value)
if (Number.isNaN(date.getTime())) {
return false
}
const today = new Date()
today.setHours(0, 0, 0, 0)
date.setHours(0, 0, 0, 0)
return date.getTime() < today.getTime()
}
/** Format court français JJ-MM-AAAA (chaîne vide si date absente / invalide). */
function formatDateFr(value: string | null | undefined): string {
if (!value) {
return ''
}
const date = new Date(value)
if (Number.isNaN(date.getTime())) {
return ''
}
const day = String(date.getDate()).padStart(2, '0')
const month = String(date.getMonth() + 1).padStart(2, '0')
return `${day}-${month}-${date.getFullYear()}`
}
// Confirmation d'intégration
const confirmOpen = ref(false)
const pendingRow = ref<QualimatCarrierRow | null>(null)
/** Clic sur une ligne → retrouve la ligne QUALIMAT source + ouvre la modal. */
function onQualimatRowClick(item: Record<string, unknown>): void {
const row = qualimatItems.value.find(r => r.id === item.id)
if (row) {
pendingRow.value = row
confirmOpen.value = true
}
}
/** Confirme l'intégration : délègue la persistance au parent via `integrate`. */
function confirmIntegrate(): void {
const row = pendingRow.value
confirmOpen.value = false
if (row !== null) {
emit('integrate', row)
}
}
</script>
<template>
<div class="mt-12 flex flex-col gap-6">
<!-- table-fixed : 1re colonne (radio) étroite, les 3 autres à parts égales. -->
<MalioDataTable
class="qualimat-table"
table-class="table-fixed"
:columns="qualimatColumns"
:items="qualimatRows"
:total-items="qualimatTotalDisplay"
:page="qualimatPage"
:per-page="qualimatPerPage"
:per-page-options="qualimatPerPageOptions"
row-clickable
:empty-message="qualimatEmptyMessage"
@row-click="onQualimatRowClick"
@update:page="qualimatGoToPage"
@update:per-page="qualimatSetPerPage"
>
<!-- Radio reflétant la ligne QUALIMAT intégrée (lecture). -->
<template #cell-select="{ item }">
<MalioRadioButton
:model-value="selectedIri"
name="qualimat-row"
:value="item.iri"
group-class="mt-0"
/>
</template>
<!-- Date de validité : fond rouge si périmée (RG-4.04). -->
<template #cell-validityDate="{ item }">
<span
v-if="item.validityDate"
:class="isExpired(item.validityDate as string) ? 'inline-block rounded px-2 py-0.5 bg-m-danger text-white' : ''"
>
{{ formatDateFr(item.validityDate as string) }}
</span>
</template>
</MalioDataTable>
<!-- Modal de confirmation d'intégration QUALIMAT. -->
<MalioModal v-model="confirmOpen" modal-class="max-w-md">
<template #header>
<h2 class="text-[24px] font-bold">{{ t('transport.carriers.form.qualimat.confirm.title') }}</h2>
</template>
<p>{{ t('transport.carriers.form.qualimat.confirm.message') }}</p>
<template #footer>
<MalioButton
variant="secondary"
button-class="flex-1"
:label="t('transport.carriers.form.qualimat.confirm.cancel')"
@click="confirmOpen = false"
/>
<MalioButton
variant="primary"
button-class="flex-1"
:label="t('transport.carriers.form.qualimat.confirm.confirm')"
@click="confirmIntegrate"
/>
</template>
</MalioModal>
</div>
</template>
<style scoped>
/* Datatable QUALIMAT en table-fixed : la colonne radio (1re) reste étroite,
les 3 autres (nom / adresse / validité) se partagent l'espace à parts égales. */
.qualimat-table :deep(th:first-child),
.qualimat-table :deep(td:first-child) {
width: 56px;
}
</style>
@@ -37,8 +37,9 @@ vi.stubGlobal('useToast', () => ({
}))
const { useCarrierForm, CARRIER_TAB_KEYS } = await import('../useCarrierForm')
const { buildCarrierContactPayload, isCarrierContactBlank, isCarrierContactNamed } = await import('../../utils/forms/carrierContact')
const { emptyCarrierContact } = await import('../../types/carrierForm')
const { buildCarrierContactPayload, isCarrierContactBlank } = await import('../../utils/forms/carrierContact')
const { buildCarrierPricePayload, isCarrierPriceValid } = await import('../../utils/forms/carrierPrice')
const { emptyCarrierContact, emptyCarrierPrice } = await import('../../types/carrierForm')
describe('useCarrierForm', () => {
beforeEach(() => {
@@ -110,6 +111,8 @@ describe('useCarrierForm', () => {
form.main.name = 'Acme'
form.main.certificationType = 'GMP_PLUS'
form.main.isChartered = true
// Annule le défaut « BENNE » pour vérifier la garde « contenant obligatoire ».
form.main.containerType = null
const created = await form.submitMain()
@@ -322,16 +325,18 @@ describe('useCarrierForm — champs conditionnels (ERP-166)', () => {
})
})
it('RG-4.03 affrété mais champs vides : omis du payload (422 NotBlank back)', () => {
it('RG-4.03 affrété, indexation/volume vides : omis du payload (containerType garde son défaut BENNE)', () => {
const form = useCarrierForm()
form.main.name = 'Acme'
form.main.certificationType = 'GMP_PLUS'
form.main.isChartered = true
// indexation / volume vides → omis (422 NotBlank back) ; containerType défaut « BENNE » envoyé.
expect(form.buildMainPayload()).toEqual({
name: 'Acme',
certificationType: 'GMP_PLUS',
isChartered: true,
containerType: 'BENNE',
})
})
@@ -345,6 +350,52 @@ describe('useCarrierForm — champs conditionnels (ERP-166)', () => {
form.main.dischargeDocumentIri = '/api/uploaded_documents/7'
expect(form.buildMainPayload()).toMatchObject({ dischargeDocument: '/api/uploaded_documents/7' })
})
it('RG-4.02 upload différé : selectDischarge ne POST pas ; submitMain upload PUIS crée', async () => {
mockPost.mockReset()
// 1er POST = /uploaded_documents (renvoie l'IRI) ; 2e = /carriers (création).
mockPost
.mockResolvedValueOnce({ '@id': '/api/uploaded_documents/7' })
.mockResolvedValueOnce({ id: 12, name: 'ACME', certificationType: 'AUTRE' })
const form = useCarrierForm()
form.main.name = 'Acme'
form.main.certificationType = 'AUTRE'
// Sélection du fichier : aucun appel réseau (upload différé à l'enregistrement).
form.selectDischarge(new File(['x'], 'decharge.pdf', { type: 'application/pdf' }))
expect(mockPost).not.toHaveBeenCalled()
// La validation est satisfaite par le fichier en attente (pas encore d'IRI).
expect(form.mainErrors.errors.dischargeDocument).toBeUndefined()
const created = await form.submitMain()
expect(created).toBe(true)
// 1er appel : upload multipart ; 2e : création carrier avec l'IRI résolu.
expect(mockPost.mock.calls[0][0]).toBe('/uploaded_documents')
expect(mockPost.mock.calls[1][0]).toBe('/carriers')
expect(mockPost.mock.calls[1][1]).toMatchObject({ dischargeDocument: '/api/uploaded_documents/7' })
})
it('RG-4.02 upload différé : un 422 MIME bloque la création (message inline, pas de POST /carriers)', async () => {
mockPost.mockReset()
// Le POST /uploaded_documents échoue (MIME hors whitelist) → 422.
mockPost.mockRejectedValueOnce(Object.assign(new Error('422'), {
data: { 'hydra:description': 'Type de fichier non autorisé.' },
}))
const form = useCarrierForm()
form.main.name = 'Acme'
form.main.certificationType = 'AUTRE'
form.selectDischarge(new File(['x'], 'malware.exe', { type: 'application/x-msdownload' }))
const created = await form.submitMain()
expect(created).toBe(false)
// Message back affiché inline sous le champ ; aucune création de carrier.
expect(form.mainErrors.errors.dischargeDocument).toBe('Type de fichier non autorisé.')
expect(mockPost).toHaveBeenCalledTimes(1)
expect(mockPost.mock.calls[0][0]).toBe('/uploaded_documents')
})
})
describe('useCarrierForm — copie QUALIMAT (ERP-166)', () => {
@@ -435,14 +486,13 @@ describe('useCarrierForm — copie QUALIMAT (ERP-166)', () => {
})
})
it('applyQualimatSelection pré-remplit le 1er bloc d\'adresse (RG-4.05)', async () => {
it('applyQualimatSelection pré-remplit l\'adresse unique à la création (RG-4.05)', async () => {
const form = useCarrierForm()
form.main.name = 'Acme'
await form.applyQualimatSelection(QUALIMAT_ROW)
expect(form.addresses.value).toHaveLength(1)
expect(form.addresses.value[0]).toEqual({
expect(form.address.value).toEqual({
id: null,
country: 'France',
postalCode: '86000',
@@ -453,53 +503,38 @@ describe('useCarrierForm — copie QUALIMAT (ERP-166)', () => {
})
})
describe('useCarrierForm — onglet Adresses (ERP-167)', () => {
describe('useCarrierForm — onglet Adresse (ERP-167 / ERP-172 : adresse unique)', () => {
beforeEach(() => {
mockPost.mockReset()
mockPatch.mockReset()
mockDelete.mockReset()
})
/** Transporteur créé, onglet Adresses accessible. */
/** Transporteur créé, onglet Adresse accessible. */
function createdForm() {
const form = useCarrierForm()
form.carrierId.value = 7
return form
}
/** Remplit un bloc adresse complet (CP + ville + rue). */
function fillAddress(form: ReturnType<typeof useCarrierForm>, index = 0): void {
const a = form.addresses.value[index]
if (a) {
a.postalCode = '86100'
a.city = 'Châtellerault'
a.street = '1 rue du Test'
}
/** Remplit l'unique bloc adresse (CP + ville + rue). */
function fillAddress(form: ReturnType<typeof useCarrierForm>): void {
const a = form.address.value
a.postalCode = '86100'
a.city = 'Châtellerault'
a.street = '1 rue du Test'
}
it('canAddAddress : désactivé tant que la dernière adresse est incomplète', () => {
const form = createdForm()
expect(form.canAddAddress.value).toBe(false)
form.addAddress()
expect(form.addresses.value).toHaveLength(1) // no-op tant qu'incomplète
fillAddress(form)
expect(form.canAddAddress.value).toBe(true)
form.addAddress()
expect(form.addresses.value).toHaveLength(2)
})
it('submitAddresses : POST des nouvelles adresses, capture l\'id, finalise l\'onglet', async () => {
it('submitAddress : POST sur /carriers/{id}/address, capture l\'id, finalise l\'onglet', async () => {
mockPost.mockResolvedValueOnce({ id: 88 })
const form = createdForm()
fillAddress(form)
const ok = await form.submitAddresses(vi.fn())
const ok = await form.submitAddress(vi.fn())
expect(ok).toBe(true)
const [url, body, opts] = mockPost.mock.calls[0] ?? []
expect(url).toBe('/carriers/7/addresses')
expect(url).toBe('/carriers/7/address')
expect(body).toEqual({
country: 'France',
postalCode: '86100',
@@ -508,24 +543,26 @@ describe('useCarrierForm — onglet Adresses (ERP-167)', () => {
streetComplement: null,
})
expect(opts).toMatchObject({ toast: false, headers: { Accept: 'application/ld+json' } })
expect(form.addresses.value[0]?.id).toBe(88)
expect(form.address.value.id).toBe(88)
expect(form.isValidated('addresses')).toBe(true)
// ERP-193 : Contact optionnel → valider Adresses déverrouille jusqu'à Prix
// (dernier onglet), sans étape bloquante par Contacts.
expect(form.unlockedIndex.value).toBe(CARRIER_TAB_KEYS.length - 1)
})
it('submitAddresses : PATCH des adresses existantes sur /carrier_addresses/{id}', async () => {
it('submitAddress : PATCH de l\'adresse existante sur /carrier_addresses/{id}', async () => {
mockPatch.mockResolvedValueOnce({})
const form = createdForm()
fillAddress(form)
const first = form.addresses.value[0]
if (first) first.id = 88
form.address.value.id = 88
await form.submitAddresses(vi.fn())
await form.submitAddress(vi.fn())
expect(mockPost).not.toHaveBeenCalled()
expect(mockPatch).toHaveBeenCalledWith('/carrier_addresses/88', expect.objectContaining({ city: 'Châtellerault' }), { toast: false })
})
it('submitAddresses : mappe les 422 PAR LIGNE et ne finalise pas l\'onglet (RG-4.05)', async () => {
it('submitAddress : mappe les 422 inline par champ et ne finalise pas l\'onglet (RG-4.05)', async () => {
mockPost.mockRejectedValueOnce({
response: {
status: 422,
@@ -535,30 +572,15 @@ describe('useCarrierForm — onglet Adresses (ERP-167)', () => {
const form = createdForm()
fillAddress(form)
const ok = await form.submitAddresses(vi.fn())
const ok = await form.submitAddress(vi.fn())
expect(ok).toBe(false)
expect(form.addressErrors.value[0]?.city).toBe('La ville est obligatoire pour un transporteur affrété.')
expect(form.addressErrors.value.city).toBe('La ville est obligatoire pour un transporteur affrété.')
expect(form.isValidated('addresses')).toBe(false)
})
it('removeAddress : DELETE /carrier_addresses/{id} puis retrait du bloc', async () => {
mockDelete.mockResolvedValueOnce({})
const form = createdForm()
fillAddress(form)
const first = form.addresses.value[0]
if (first) first.id = 88
form.addAddress()
fillAddress(form, 1)
await form.removeAddress(0)
expect(mockDelete).toHaveBeenCalledWith('/carrier_addresses/88', {}, { toast: false })
expect(form.addresses.value).toHaveLength(1)
})
})
describe('carrierContact (util) — validité alignée M1/M2/M3 + max 2 téléphones', () => {
describe('carrierContact (util) — bloc optionnel (ERP-193) + max 2 téléphones', () => {
it('isCarrierContactBlank : vrai si vide, faux dès un champ comptant rempli (phoneSecondary exclu)', () => {
expect(isCarrierContactBlank(emptyCarrierContact())).toBe(true)
expect(isCarrierContactBlank({ ...emptyCarrierContact(), jobTitle: 'Acheteur' })).toBe(false)
@@ -567,15 +589,6 @@ describe('carrierContact (util) — validité alignée M1/M2/M3 + max 2 téléph
expect(isCarrierContactBlank({ ...emptyCarrierContact(), phoneSecondary: '0605040302', hasSecondaryPhone: true })).toBe(true)
})
it('isCarrierContactNamed : nommé seulement avec un prénom OU un nom', () => {
expect(isCarrierContactNamed(emptyCarrierContact())).toBe(false)
expect(isCarrierContactNamed({ ...emptyCarrierContact(), firstName: 'Jean' })).toBe(true)
expect(isCarrierContactNamed({ ...emptyCarrierContact(), lastName: 'Doe' })).toBe(true)
// Fonction / téléphone / email seuls ne « nomment » pas (≠ RG-4.08 large).
expect(isCarrierContactNamed({ ...emptyCarrierContact(), jobTitle: 'Acheteur' })).toBe(false)
expect(isCarrierContactNamed({ ...emptyCarrierContact(), email: 'a@b.fr' })).toBe(false)
})
it('buildCarrierContactPayload : phones = 1 numéro sans secondaire', () => {
const body = buildCarrierContactPayload({ ...emptyCarrierContact(), phonePrimary: '0102030405' })
expect(body.phones).toEqual(['0102030405'])
@@ -616,23 +629,18 @@ describe('useCarrierForm — onglet Contacts (ERP-168)', () => {
return form
}
it('« + Nouveau contact » désactivé tant que le bloc n\'est pas nommé (prénom OU nom, aligné M1/M2/M3)', () => {
it('ERP-193 : « + Nouveau contact » désactivé tant que le bloc est VIDE (plus de règle prénom/nom)', () => {
const form = createdForm()
expect(form.canAddContact.value).toBe(false)
// addContact est un no-op tant que le bloc n'est pas nommé.
// addContact est un no-op tant que le bloc est totalement vide.
form.addContact()
expect(form.contacts.value).toHaveLength(1)
// Fonction seule ne suffit PAS à ajouter un nouveau bloc (≠ RG-4.08 large).
// ERP-193 : un seul champ rempli (ici la fonction, sans prénom ni nom) suffit
// désormais à débloquer l'ajout — la règle « prénom OU nom » est retirée.
const first = form.contacts.value[0]
if (first) first.jobTitle = 'Acheteur'
expect(form.canAddContact.value).toBe(false)
form.addContact()
expect(form.contacts.value).toHaveLength(1)
// Un nom (ou prénom) débloque l'ajout.
if (first) first.lastName = 'Doe'
expect(form.canAddContact.value).toBe(true)
form.addContact()
expect(form.contacts.value).toHaveLength(2)
@@ -667,21 +675,15 @@ describe('useCarrierForm — onglet Contacts (ERP-168)', () => {
expect(mockPatch).toHaveBeenCalledWith('/carrier_contacts/55', expect.objectContaining({ lastName: 'Doe' }), { toast: false })
})
it('RG-4.08 : onglet vide → soumet l\'amorce pour déclencher la 422 inline', async () => {
mockPost.mockRejectedValueOnce({
response: {
status: 422,
_data: { violations: [{ propertyPath: 'firstName', message: 'Au moins un champ du contact est obligatoire.' }] },
},
})
it('ERP-193 : onglet Contact vide → aucun POST, onglet finalisé (bloc optionnel)', async () => {
const form = createdForm()
// Bloc vide → rien n'est soumis, l'onglet se finalise et déverrouille Prix.
const ok = await form.submitContacts(vi.fn())
expect(ok).toBe(false)
expect(mockPost).toHaveBeenCalledTimes(1)
expect(form.contactErrors.value[0]?.firstName).toBe('Au moins un champ du contact est obligatoire.')
expect(form.isValidated('contacts')).toBe(false)
expect(ok).toBe(true)
expect(mockPost).not.toHaveBeenCalled()
expect(form.isValidated('contacts')).toBe(true)
})
it('removeContact : DELETE /carrier_contacts/{id} puis retrait du bloc', async () => {
@@ -699,3 +701,330 @@ describe('useCarrierForm — onglet Contacts (ERP-168)', () => {
expect(form.contacts.value).toHaveLength(1)
})
})
describe('carrierPrice (util) — bascule CLIENT/FOURNISSEUR + champs requis par branche', () => {
const CLIENT = '/api/clients/3'
const CLIENT_ADDR = '/api/client_addresses/8'
const SUPPLIER = '/api/suppliers/5'
const SUPPLIER_ADDR = '/api/supplier_addresses/9'
const SITE = '/api/sites/1'
it('buildCarrierPricePayload CLIENT : branche client envoyée, branche fournisseur à null', () => {
const body = buildCarrierPricePayload({
...emptyCarrierPrice(),
direction: 'CLIENT',
clientIri: CLIENT,
clientDeliveryAddressIri: CLIENT_ADDR,
departureSiteIri: SITE,
containerType: 'BENNE',
pricingUnit: 'FORFAIT',
price: '120.00',
priceState: 'EN_COURS',
})
expect(body).toMatchObject({
direction: 'CLIENT',
client: CLIENT,
clientDeliveryAddress: CLIENT_ADDR,
departureSite: SITE,
supplier: null,
supplierSupplyAddress: null,
deliverySite: null,
containerType: 'BENNE',
pricingUnit: 'FORFAIT',
price: '120.00',
priceState: 'EN_COURS',
})
})
it('buildCarrierPricePayload FOURNISSEUR : branche fournisseur envoyée, branche client à null', () => {
const body = buildCarrierPricePayload({
...emptyCarrierPrice(),
direction: 'FOURNISSEUR',
supplierIri: SUPPLIER,
supplierSupplyAddressIri: SUPPLIER_ADDR,
deliverySiteIri: SITE,
containerType: 'FOND_MOUVANT',
pricingUnit: 'TONNE',
price: '45',
priceState: 'VALIDE',
})
expect(body).toMatchObject({
direction: 'FOURNISSEUR',
supplier: SUPPLIER,
supplierSupplyAddress: SUPPLIER_ADDR,
deliverySite: SITE,
client: null,
clientDeliveryAddress: null,
departureSite: null,
})
})
it('isCarrierPriceValid : faux si branche incomplète, vrai si branche complète + communs', () => {
const base = { ...emptyCarrierPrice(), containerType: 'BENNE', pricingUnit: 'FORFAIT', price: '10', priceState: 'EN_COURS' }
// Direction non choisie → invalide.
expect(isCarrierPriceValid({ ...base, direction: null })).toBe(false)
// Sens CLIENT par défaut mais branche incomplète → invalide.
expect(isCarrierPriceValid(base)).toBe(false)
// CLIENT sans adresse/site → invalide.
expect(isCarrierPriceValid({ ...base, direction: 'CLIENT', clientIri: CLIENT })).toBe(false)
// CLIENT complet → valide.
expect(isCarrierPriceValid({ ...base, direction: 'CLIENT', clientIri: CLIENT, clientDeliveryAddressIri: CLIENT_ADDR, departureSiteIri: SITE })).toBe(true)
// FOURNISSEUR complet → valide.
expect(isCarrierPriceValid({ ...base, direction: 'FOURNISSEUR', supplierIri: SUPPLIER, supplierSupplyAddressIri: SUPPLIER_ADDR, deliverySiteIri: SITE })).toBe(true)
// Prix manquant → invalide même branche complète.
expect(isCarrierPriceValid({ ...emptyCarrierPrice(), direction: 'CLIENT', clientIri: CLIENT, clientDeliveryAddressIri: CLIENT_ADDR, departureSiteIri: SITE, containerType: 'BENNE', pricingUnit: 'FORFAIT', priceState: 'EN_COURS' })).toBe(false)
})
})
describe('useCarrierForm — onglet Prix (ERP-169)', () => {
beforeEach(() => {
mockPost.mockReset()
mockPatch.mockReset()
mockDelete.mockReset()
})
function createdForm() {
const form = useCarrierForm()
form.carrierId.value = 7
return form
}
it('démarre avec un bloc CLIENT par défaut ; « + Nouveau prix » bloqué tant qu\'il est incomplet', () => {
const form = createdForm()
// Un bloc présent d'office, sens CLIENT pré-sélectionné.
expect(form.prices.value).toHaveLength(1)
expect(form.prices.value[0]?.direction).toBe('CLIENT')
// Bloc incomplet → on ne peut pas en ajouter un autre.
expect(form.canAddPrice.value).toBe(false)
form.addPrice()
expect(form.prices.value).toHaveLength(1)
// Une fois le bloc complété, l'ajout est autorisé.
const p = form.prices.value[0]
if (p) {
p.clientIri = '/api/clients/3'
p.clientDeliveryAddressIri = '/api/client_addresses/8'
p.departureSiteIri = '/api/sites/1'
p.price = '120'
p.priceState = 'EN_COURS'
}
expect(form.canAddPrice.value).toBe(true)
form.addPrice()
expect(form.prices.value).toHaveLength(2)
})
it('submitPrices : POST des nouveaux prix (branche CLIENT), capture l\'id, finalise', async () => {
mockPost.mockResolvedValueOnce({ id: 50 })
const form = createdForm()
form.addPrice()
const p = form.prices.value[0]
if (p) {
p.direction = 'CLIENT'
p.clientIri = '/api/clients/3'
p.clientDeliveryAddressIri = '/api/client_addresses/8'
p.departureSiteIri = '/api/sites/1'
p.containerType = 'BENNE'
p.pricingUnit = 'FORFAIT'
p.price = '120'
p.priceState = 'EN_COURS'
}
const ok = await form.submitPrices(vi.fn())
expect(ok).toBe(true)
const [url, body, opts] = mockPost.mock.calls[0] ?? []
expect(url).toBe('/carriers/7/prices')
expect(body).toMatchObject({ direction: 'CLIENT', client: '/api/clients/3', supplier: null })
expect(opts).toMatchObject({ toast: false, headers: { Accept: 'application/ld+json' } })
expect(form.prices.value[0]?.id).toBe(50)
expect(form.isValidated('prices')).toBe(true)
})
it('submitPrices : PATCH des prix existants sur /carrier_prices/{id}', async () => {
mockPatch.mockResolvedValueOnce({})
const form = createdForm()
const p = form.prices.value[0]
if (p) {
p.id = 50
p.direction = 'FOURNISSEUR'
p.supplierIri = '/api/suppliers/5'
p.supplierSupplyAddressIri = '/api/supplier_addresses/9'
p.deliverySiteIri = '/api/sites/1'
p.price = '10'
p.priceState = 'VALIDE'
}
await form.submitPrices(vi.fn())
expect(mockPost).not.toHaveBeenCalled()
expect(mockPatch).toHaveBeenCalledWith('/carrier_prices/50', expect.objectContaining({ direction: 'FOURNISSEUR' }), { toast: false })
})
it('front : bloc prix incomplet → erreurs inline sous chaque champ requis, pas d\'appel back', async () => {
const form = createdForm()
// Bloc CLIENT par défaut, rien d'autre rempli.
const ok = await form.submitPrices(vi.fn())
expect(ok).toBe(false)
expect(mockPost).not.toHaveBeenCalled()
const errs = form.priceErrors.value[0]
expect(errs?.client).toBeTruthy()
expect(errs?.clientDeliveryAddress).toBeTruthy()
expect(errs?.departureSite).toBeTruthy()
expect(errs?.price).toBeTruthy()
expect(errs?.priceState).toBeTruthy()
})
it('submitPrices : mappe les 422 back par ligne (appartenance adresse) et ne finalise pas', async () => {
mockPost.mockRejectedValueOnce({
response: { status: 422, _data: { violations: [{ propertyPath: 'clientDeliveryAddress', message: 'L\'adresse de livraison doit appartenir au client selectionne.' }] } },
})
const form = createdForm()
// Tous les champs requis remplis (le pré-check front passe) ; le back 422 sur
// une RG qu'il est seul à connaître (appartenance de l'adresse au client).
const p = form.prices.value[0]
if (p) {
p.direction = 'CLIENT'
p.clientIri = '/api/clients/3'
p.clientDeliveryAddressIri = '/api/client_addresses/8'
p.departureSiteIri = '/api/sites/1'
p.price = '10'
p.priceState = 'EN_COURS'
}
const ok = await form.submitPrices(vi.fn())
expect(ok).toBe(false)
expect(form.priceErrors.value[0]?.clientDeliveryAddress).toBe('L\'adresse de livraison doit appartenir au client selectionne.')
expect(form.isValidated('prices')).toBe(false)
})
it('removePrice : DELETE /carrier_prices/{id} puis retrait du bloc', async () => {
mockDelete.mockResolvedValueOnce({})
const form = createdForm()
form.addPrice()
const p = form.prices.value[0]
if (p) { p.id = 77; p.direction = 'CLIENT'; p.clientIri = '/api/clients/3'; p.clientDeliveryAddressIri = '/api/client_addresses/8'; p.departureSiteIri = '/api/sites/1'; p.containerType = 'BENNE'; p.pricingUnit = 'FORFAIT'; p.price = '10'; p.priceState = 'EN_COURS' }
form.addPrice()
await form.removePrice(0)
expect(mockDelete).toHaveBeenCalledWith('/carrier_prices/77', {}, { toast: false })
expect(form.prices.value).toHaveLength(1)
})
})
describe('useCarrierForm — édition (ERP-170)', () => {
beforeEach(() => {
mockPost.mockReset()
mockPatch.mockReset()
})
it('prefillFrom : peuple carrierId + principal + sous-collections, passe en editMode', () => {
const form = useCarrierForm()
form.prefillFrom({
'@id': '/api/carriers/7',
id: 7,
name: 'TRANSPORTS ACME',
certificationType: 'GMP_PLUS',
address: { '@id': '/api/carrier_addresses/3', id: 3, city: 'Poitiers' },
contacts: [{ '@id': '/api/carrier_contacts/9', id: 9, lastName: 'Doe', phonePrimary: '0102030405' }],
prices: [{ '@id': '/api/carrier_prices/5', id: 5, direction: 'CLIENT', client: { '@id': '/api/clients/3' }, containerType: 'BENNE', pricingUnit: 'FORFAIT', price: '120', priceState: 'EN_COURS' }],
})
expect(form.carrierId.value).toBe(7)
expect(form.editMode.value).toBe(true)
expect(form.main.name).toBe('TRANSPORTS ACME')
expect(form.main.certificationType).toBe('GMP_PLUS')
expect(form.address.value.id).toBe(3)
expect(form.contacts.value[0]?.id).toBe(9)
expect(form.prices.value[0]?.clientIri).toBe('/api/clients/3')
})
it('updateMain : PATCH /carriers/{id} (pas de POST), réaffiche le nom normalisé', async () => {
mockPatch.mockResolvedValueOnce({ id: 7, name: 'TRANSPORTS ACME', certificationType: 'GMP_PLUS' })
const form = useCarrierForm()
form.prefillFrom({ '@id': '/api/carriers/7', id: 7, name: 'Transports Acme', certificationType: 'GMP_PLUS' })
const ok = await form.updateMain()
expect(ok).toBe(true)
expect(mockPost).not.toHaveBeenCalled()
expect(mockPatch).toHaveBeenCalledWith(
'/carriers/7',
expect.objectContaining({ name: 'Transports Acme', certificationType: 'GMP_PLUS' }),
{ toast: false },
)
expect(form.main.name).toBe('TRANSPORTS ACME')
})
})
describe('useCarrierForm — modification : Qualimat + certification (ERP-172)', () => {
const QUALIMAT_ROW = {
'@id': '/api/qualimat_carriers/42',
id: '42',
name: 'TRANSPORTS QUALIMAT',
address: '1 rue du Port',
postalCode: '86000',
city: 'Poitiers',
validityDate: '2027-01-15',
status: 'VALIDE',
}
beforeEach(() => {
mockPost.mockReset()
mockPatch.mockReset()
})
it('setCertification : quitter QUALIMAT délie la FK qualimatCarrier', () => {
const form = useCarrierForm()
form.main.qualimatCarrierIri = '/api/qualimat_carriers/42'
form.main.certificationType = 'QUALIMAT'
form.setCertification('GMP_PLUS')
expect(form.main.certificationType).toBe('GMP_PLUS')
expect(form.main.qualimatCarrierIri).toBeNull()
})
it('certificationReadonly : éditable en modification même pour un QUALIMAT', () => {
const form = useCarrierForm()
form.prefillFrom({
'@id': '/api/carriers/7', id: 7, name: 'ACME', certificationType: 'QUALIMAT',
qualimatCarrier: { '@id': '/api/qualimat_carriers/42' },
})
expect(form.isQualimat.value).toBe(true)
expect(form.certificationReadonly.value).toBe(false)
})
it('buildMainPayload : en modification, délie le Qualimat (qualimatCarrier: null) sans lien', () => {
const form = useCarrierForm()
form.prefillFrom({
'@id': '/api/carriers/7', id: 7, name: 'ACME', certificationType: 'QUALIMAT',
qualimatCarrier: { '@id': '/api/qualimat_carriers/42' },
})
form.setCertification('GMP_PLUS')
expect(form.buildMainPayload()).toMatchObject({ certificationType: 'GMP_PLUS', qualimatCarrier: null })
})
it('applyQualimatSelection : en modification, conserve l\'adresse existante (PATCH nom/certif/FK)', async () => {
mockPatch.mockResolvedValueOnce({})
const form = useCarrierForm()
form.prefillFrom({
'@id': '/api/carriers/7', id: 7, name: 'OLD', certificationType: 'GMP_PLUS',
address: { '@id': '/api/carrier_addresses/3', id: 3, city: 'Poitiers', street: 'rue A' },
})
const addressBefore = { ...form.address.value }
const ok = await form.applyQualimatSelection(QUALIMAT_ROW)
expect(ok).toBe(true)
// Décision « conserver » (ERP-172) : l'adresse n'est pas réécrite en modification.
expect(form.address.value).toEqual(addressBefore)
// Nom + certification + FK actualisés via PATCH.
expect(form.main.name).toBe('TRANSPORTS QUALIMAT')
expect(form.main.certificationType).toBe('QUALIMAT')
expect(form.main.qualimatCarrierIri).toBe('/api/qualimat_carriers/42')
})
})
@@ -50,7 +50,7 @@ describe('useCarriersRepository', () => {
expect(mockApiGet).toHaveBeenCalledTimes(1)
const [url, query, opts] = mockApiGet.mock.calls[0]
expect(url).toBe('/carriers')
expect(query).toMatchObject({ page: 1, itemsPerPage: 10 })
expect(query).toMatchObject({ page: 1, itemsPerPage: 25 })
expect(opts).toMatchObject({
toast: false,
headers: { Accept: 'application/ld+json' },
@@ -0,0 +1,68 @@
import { ref } from 'vue'
import type { CarrierDetail } from '~/modules/transport/utils/forms/carrierMappers'
/**
* Chargement et actions d'archivage d'un transporteur unique (écrans Consultation /
* Modification, ERP-170). Miroir de `useProvider` (M3) / `useSupplier` (M2). Lit le
* détail embarqué via `GET /api/carriers/{id}` (qualimatCarrier + addresses /
* contacts / prices sous `carrier:item:read`, relations cross-module via leurs
* read-groups) une SEULE requête peuple les deux écrans (embed borné, pas de N+1).
*
* L'en-tête `Accept: application/ld+json` est imposé pour obtenir le payload Hydra
* complet (avec les `@id` des relations embarquées, indispensables au préremplissage).
*
* État 100 % local à l'instance (refs). Les erreurs d'archivage / restauration
* (notamment le 409 d'homonyme actif à la restauration) sont PROPAGÉES à l'appelant.
*/
export function useCarrier(id: number | string) {
const api = useApi()
const carrier = ref<CarrierDetail | null>(null)
const loading = ref(false)
const error = ref(false)
/** Récupère le détail complet (embed qualimatCarrier + addresses / contacts / prices). */
function fetchDetail(): Promise<CarrierDetail> {
return api.get<CarrierDetail>(
`/carriers/${id}`,
{},
{ headers: { Accept: 'application/ld+json' }, toast: false },
)
}
/** Charge le détail du transporteur. En cas d'échec : `error = true`, `carrier = null`. */
async function load(): Promise<void> {
loading.value = true
error.value = false
try {
carrier.value = await fetchDetail()
}
catch {
error.value = true
carrier.value = null
}
finally {
loading.value = false
}
}
/**
* Bascule l'archivage (PATCH `isArchived` SEUL groupe carrier:write:archive ;
* tout autre champ 422, security archive = Admin seul), puis RECHARGE le détail
* complet (la réponse du PATCH ne porte pas l'embed des sous-collections). Toute
* erreur est propagée à l'appelant AVANT le rechargement.
*/
async function setArchived(isArchived: boolean): Promise<void> {
await api.patch(`/carriers/${id}`, { isArchived }, { toast: false })
carrier.value = await fetchDetail()
}
return {
carrier,
loading,
error,
load,
archive: () => setArchived(true),
restore: () => setArchived(false),
}
}
@@ -1,5 +1,6 @@
import { computed, reactive, ref, type Ref } from 'vue'
import { useFormErrors } from '~/shared/composables/useFormErrors'
import { useUpload } from '~/shared/composables/useUpload'
import { extractApiErrorMessage, mapViolationsToRecord } from '~/shared/utils/api'
import { removeCollectionRow } from '~/shared/utils/collectionRow'
import {
@@ -7,14 +8,24 @@ import {
emptyCarrierAddressCopy,
emptyCarrierContact,
emptyCarrierMain,
emptyCarrierPrice,
type CarrierAddressCopy,
type CarrierAddressFormDraft,
type CarrierContactFormDraft,
type CarrierMainDraft,
type CarrierMainResponse,
type CarrierPriceFormDraft,
} from '~/modules/transport/types/carrierForm'
import { buildCarrierAddressPayload, isCarrierAddressValid } from '~/modules/transport/utils/forms/carrierAddress'
import { buildCarrierContactPayload, isCarrierContactBlank, isCarrierContactNamed } from '~/modules/transport/utils/forms/carrierContact'
import { buildCarrierAddressPayload } from '~/modules/transport/utils/forms/carrierAddress'
import { buildCarrierContactPayload, isCarrierContactBlank } from '~/modules/transport/utils/forms/carrierContact'
import { buildCarrierPricePayload, isCarrierPriceValid } from '~/modules/transport/utils/forms/carrierPrice'
import {
mapAddressToDraft,
mapContactToDraft,
mapMainToDraft,
mapPriceToDraft,
type CarrierDetail,
} from '~/modules/transport/utils/forms/carrierMappers'
import type { QualimatCarrierRow } from '~/modules/transport/composables/useQualimatSearch'
/** Nom du cas spécial « compte-propre » LIOT (comparaison insensible à la casse, RG-4.01). */
@@ -56,6 +67,11 @@ export function useCarrierForm() {
// Erreurs de validation par champ (ERP-101) du formulaire principal.
const mainErrors = useFormErrors()
// Upload de la décharge (RG-4.02) — infra partagée /api/uploaded_documents.
// L'upload est DIFFÉRÉ : le fichier choisi attend ici jusqu'à l'enregistrement.
const { uploading: dischargeUploading, upload: uploadFile } = useUpload()
const pendingDischargeFile = ref<File | null>(null)
// ── État du transporteur créé ─────────────────────────────────────────────
const carrierId = ref<number | null>(null)
const mainLocked = ref(false)
@@ -75,8 +91,10 @@ export function useCarrierForm() {
// Transporteur QUALIMAT : la FK est posée → certification figée à « QUALIMAT ».
const isQualimat = computed(() => main.qualimatCarrierIri !== null)
// Certification masquée en cas LIOT ; lecture seule si QUALIMAT (ou bloc verrouillé).
// En MODIFICATION (ERP-172) : éditable même pour un QUALIMAT (le métier doit pouvoir
// changer la certification) — la sortie de QUALIMAT délie le référentiel.
const showCertification = computed(() => !isLiot.value)
const certificationReadonly = computed(() => isQualimat.value || mainLocked.value)
const certificationReadonly = computed(() => (isQualimat.value && !editMode.value) || mainLocked.value)
// RG-4.03 : champs d'affrètement (indexation / contenant / volume) visibles et
// obligatoires si « Affréter » coché — masqués en cas LIOT.
const showCharteredFields = computed(() => main.isChartered && !isLiot.value)
@@ -130,8 +148,9 @@ export function useCarrierForm() {
valid = false
}
// RG-4.02 : décharge obligatoire si certification AUTRE.
if (main.certificationType === 'AUTRE' && !main.dischargeDocumentIri) {
// RG-4.02 : décharge obligatoire si certification AUTRE — satisfaite par un
// IRI déjà posé OU un fichier en attente d'upload (différé à l'enregistrement).
if (main.certificationType === 'AUTRE' && !main.dischargeDocumentIri && !pendingDischargeFile.value) {
mainErrors.setError('dischargeDocument', t('transport.carriers.form.errors.dischargeRequired'))
valid = false
}
@@ -155,6 +174,58 @@ export function useCarrierForm() {
return valid
}
/**
* Sélection de la décharge (RG-4.02) via `@file-selected` : le fichier est mis
* EN ATTENTE, l'upload réel est DIFFÉRÉ à l'enregistrement (`submitMain` /
* `updateMain`). Évite les binaires orphelins si l'utilisateur abandonne le
* formulaire après avoir choisi un fichier.
*/
function selectDischarge(file: File): void {
mainErrors.clearError('dischargeDocument')
pendingDischargeFile.value = file
}
/** Annulation du choix de décharge : oublie le fichier en attente et l'IRI. */
function clearDischarge(): void {
pendingDischargeFile.value = null
main.dischargeDocumentIri = null
}
/**
* Résout l'upload différé au moment de l'enregistrement : s'il y a un fichier
* en attente, l'envoie (POST /uploaded_documents) et pose l'IRI sur le
* brouillon. Retourne false au 422 (MIME / taille message inline) pour
* interrompre la sauvegarde du transporteur. Pas de fichier en attente no-op.
*/
async function resolveDischargeUpload(): Promise<boolean> {
if (!pendingDischargeFile.value) {
return true
}
try {
main.dischargeDocumentIri = await uploadFile(pendingDischargeFile.value)
pendingDischargeFile.value = null
return true
} catch (error) {
const message = extractApiErrorMessage((error as { data?: unknown })?.data)
|| t('transport.carriers.form.errors.uploadFailed')
mainErrors.setError('dischargeDocument', message)
return false
}
}
/**
* Change la certification (sélecteur). Quitter « QUALIMAT » délie le référentiel
* (FK qualimatCarrier vidée ERP-172) : un transporteur n'est QUALIMAT que tant
* que sa certification l'est. La FK null est propagée au back par buildMainPayload
* (en modification uniquement).
*/
function setCertification(value: string | null): void {
main.certificationType = value
if (value !== 'QUALIMAT') {
main.qualimatCarrierIri = null
}
}
/**
* Payload du POST principal (groupe `carrier:write:main`). `name` et
* `certificationType` sont omis s'ils sont vides afin que la 422 porte la
@@ -180,9 +251,14 @@ export function useCarrierForm() {
payload.certificationType = main.certificationType
}
// FK QUALIMAT (saisie assistée, § 2.5) envoyée si une ligne a été intégrée.
// En MODIFICATION, on délie explicitement (null) si plus de lien — ex: la
// certification a changé de QUALIMAT vers autre chose (ERP-172).
if (main.qualimatCarrierIri) {
payload.qualimatCarrier = main.qualimatCarrierIri
}
else if (editMode.value) {
payload.qualimatCarrier = null
}
// RG-4.02 : décharge envoyée seulement en certification AUTRE ; omise quand
// absente pour que la 422 « obligatoire » porte sur le champ.
if (main.certificationType === 'AUTRE' && main.dischargeDocumentIri) {
@@ -217,6 +293,9 @@ export function useCarrierForm() {
mainSubmitting.value = true
try {
// Upload différé de la décharge : envoyé seulement maintenant (au Valider).
if (!(await resolveDischargeUpload())) return false
const created = await api.post<CarrierMainResponse>('/carriers', buildMainPayload(), {
headers: { Accept: 'application/ld+json' },
toast: false,
@@ -254,6 +333,71 @@ export function useCarrierForm() {
}
}
/**
* MODIFICATION du formulaire principal (ERP-170) : PATCH /api/carriers/{id} sur le
* groupe carrier:write:main (PAS de re-POST). Pré-check front + 409 doublon / 422
* inline comme `submitMain`. Ne verrouille rien et ne bascule pas d'onglet (édition
* = navigation libre). Retourne true si le PATCH a réussi.
*/
async function updateMain(): Promise<boolean> {
if (carrierId.value === null || mainSubmitting.value) return false
mainErrors.clearErrors()
if (!validateMainFront()) return false
mainSubmitting.value = true
try {
// Upload différé de la décharge : envoyé seulement maintenant (à l'Enregistrer).
if (!(await resolveDischargeUpload())) return false
const updated = await api.patch<CarrierMainResponse>(
`/carriers/${carrierId.value}`,
buildMainPayload(),
{ toast: false },
)
main.name = updated.name ?? main.name
main.certificationType = updated.certificationType ?? main.certificationType
return true
}
catch (error) {
const status = (error as { response?: { status?: number } })?.response?.status
if (status === 409) {
const message = t('transport.carriers.form.duplicateName')
mainErrors.setError('name', message)
toast.error({ title: t('transport.carriers.toast.error'), message })
}
else {
mainErrors.handleApiError(error, { fallbackMessage: t('transport.carriers.toast.error') })
}
return false
}
finally {
mainSubmitting.value = false
}
}
/**
* Pré-remplit le formulaire depuis le détail `GET /api/carriers/{id}` (écran
* Modification) : peuple carrierId + principal + adresses / contacts / prix via les
* mappers, passe en `editMode` (navigation libre, tous onglets accessibles, bloc
* principal éditable). Au moins un bloc Adresse / Contact affiché même sans donnée.
*/
function prefillFrom(detail: CarrierDetail): void {
carrierId.value = detail.id
editMode.value = true
mainLocked.value = false
unlockedIndex.value = tabKeys.value.length - 1
Object.assign(main, mapMainToDraft(detail))
// Adresse UNIQUE (ERP-172) : objet `address` (ou null) au lieu d'une liste.
address.value = detail.address ? mapAddressToDraft(detail.address) : emptyCarrierAddress()
const mappedContacts = (detail.contacts ?? []).map(mapContactToDraft)
contacts.value = mappedContacts.length > 0 ? mappedContacts : [emptyCarrierContact()]
prices.value = (detail.prices ?? []).map(mapPriceToDraft)
}
/**
* PATCH partiel du transporteur (mode strict : un seul groupe de sérialisation
* par appel spec-back § 2.9). Servira les onglets à champs scalaires des
@@ -272,6 +416,11 @@ export function useCarrierForm() {
})
}
/** Toast de succès après suppression serveur confirmée d'une sous-ressource. */
function notifyRemovalSuccess(): void {
toast.success({ title: t('success.title'), message: t('success.deleted') })
}
/**
* Soumet TOUS les blocs d'une collection en collectant les erreurs PAR INDEX :
* on n'arrête pas au premier bloc en échec (décision ERP-101). Réinitialise la
@@ -311,75 +460,56 @@ export function useCarrierForm() {
return hasError
}
// ── Onglet Adresses (ERP-167) ─────────────────────────────────────────────
const addresses = ref<CarrierAddressFormDraft[]>([emptyCarrierAddress()])
// Erreurs 422 par ligne (alignées sur l'index du v-for), peuplées par submitRows.
const addressErrors = ref<Record<string, string>[]>([])
// « + Nouvelle adresse » désactivé tant que la dernière adresse n'est pas
// complète (CP + ville + rue — RG-4.05, gate d'ajout).
const canAddAddress = computed(() => {
const last = addresses.value[addresses.value.length - 1]
return last !== undefined && isCarrierAddressValid(last)
})
function addAddress(): void {
if (canAddAddress.value) {
addresses.value.push(emptyCarrierAddress())
}
}
/** Suppression immédiate d'une adresse existante (DELETE /carrier_addresses/{id}). */
async function removeAddress(index: number): Promise<void> {
await removeCollectionRow({
rows: addresses.value,
errors: addressErrors.value,
index,
endpoint: '/carrier_addresses',
deleteRow: url => api.delete(url, {}, { toast: false }),
makeEmpty: emptyCarrierAddress,
onError: notifyRemovalError,
})
}
// ── Onglet Adresse (ERP-167 / ERP-172 : adresse UNIQUE) ───────────────────
// Un transporteur a au plus UNE adresse (décision métier ERP-172) : un seul
// bloc, pas d'ajout/suppression. `id` null tant que l'adresse n'est pas créée.
const address = ref<CarrierAddressFormDraft>(emptyCarrierAddress())
// Erreurs 422 du bloc adresse (mapping inline par champ, ERP-101).
const addressErrors = ref<Record<string, string>>({})
/**
* Valide l'onglet Adresses : POST des nouvelles adresses sur
* /carriers/{id}/addresses, PATCH des existantes sur /carrier_addresses/{id}
* (groupe carrier:write:addresses). Erreurs 422 collectées par ligne (RG-4.05
* « obligatoire si affrété » re-validée back). Retourne true si l'onglet a é
* validé (avancé/terminé).
* Valide l'onglet Adresse : POST sur /carriers/{id}/address (création) ou PATCH
* sur /carrier_addresses/{id} (mise à jour), groupe carrier:write:addresses.
* Erreurs 422 mappées inline par champ (RG-4.05 « obligatoire si affrété »
* re-validée back). Retourne true si l'onglet a é validé.
*/
async function submitAddresses(onError: (error: unknown) => void): Promise<boolean> {
async function submitAddress(onError: (error: unknown) => void): Promise<boolean> {
if (carrierId.value === null || tabSubmitting.value) {
return false
}
tabSubmitting.value = true
addressErrors.value = {}
try {
const hasError = await submitRows(
addresses.value,
addressErrors,
async (address) => {
const body = buildCarrierAddressPayload(address)
if (address.id === null) {
const created = await api.post<{ id: number }>(
`/carriers/${carrierId.value}/addresses`,
body,
{ headers: { Accept: 'application/ld+json' }, toast: false },
)
address.id = created.id
}
else {
await api.patch(`/carrier_addresses/${address.id}`, body, { toast: false })
}
},
onError,
)
if (hasError) {
return false
const body = buildCarrierAddressPayload(address.value)
if (address.value.id === null) {
const created = await api.post<{ id: number }>(
`/carriers/${carrierId.value}/address`,
body,
{ headers: { Accept: 'application/ld+json' }, toast: false },
)
address.value.id = created.id
}
else {
await api.patch(`/carrier_addresses/${address.value.id}`, body, { toast: false })
}
completeTab('addresses')
// ERP-193 : l'onglet Contact est OPTIONNEL — il ne doit pas verrouiller
// l'accès à Prix. Dès les Adresses validées, on déverrouille jusqu'à Prix
// (Contacts reste accessible mais n'est plus une étape bloquante).
unlockedIndex.value = tabKeys.value.length - 1
return true
}
catch (error) {
const response = (error as { response?: { status?: number, _data?: unknown } })?.response
const mapped = response?.status === 422 ? mapViolationsToRecord(response._data) : {}
if (Object.keys(mapped).length > 0) {
addressErrors.value = mapped
}
else {
onError(error)
}
return false
}
finally {
tabSubmitting.value = false
}
@@ -390,12 +520,13 @@ export function useCarrierForm() {
// Erreurs 422 par ligne (alignées sur l'index du v-for), peuplées par submitRows.
const contactErrors = ref<Record<string, string>[]>([])
// « + Nouveau contact » désactivé tant que le DERNIER bloc n'est pas « nommé »
// (prénom OU nom) — aligné sur M1/M2/M3 (fonction / téléphone / email seuls ne
// suffisent pas à ajouter un nouveau bloc).
// « + Nouveau contact » désactivé tant que le DERNIER bloc est VIDE. ERP-193 :
// l'onglet Contact n'est plus obligatoire — on ne réclame plus prénom OU nom,
// un seul champ rempli (fonction / téléphone / email) suffit pour empiler un
// bloc suivant (et évite d'accumuler des blocs totalement vides).
const canAddContact = computed(() => {
const last = contacts.value[contacts.value.length - 1]
return last !== undefined && isCarrierContactNamed(last)
return last !== undefined && !isCarrierContactBlank(last)
})
function addContact(): void {
@@ -414,16 +545,18 @@ export function useCarrierForm() {
deleteRow: url => api.delete(url, {}, { toast: false }),
makeEmpty: emptyCarrierContact,
onError: notifyRemovalError,
onSuccess: notifyRemovalSuccess,
})
}
/**
* Valide l'onglet Contacts : POST des nouveaux contacts sur
* /carriers/{id}/contacts, PATCH des existants sur /carrier_contacts/{id}
* (groupe carrier:write:contacts). RG-4.08 ( 1 champ rempli, max 2 téléphones)
* re-validée back 422 par ligne. Si l'onglet ne contient QUE des amorces
* vides, on soumet la 1re pour déclencher la 422 RG-4.08 inline plutôt que de
* finaliser un onglet vide. Retourne true si l'onglet a é validé.
* (groupe carrier:write:contacts). Max 2 téléphones re-validé back 422 par
* ligne. ERP-193 : l'onglet Contact est OPTIONNEL les amorces vides neuves
* sont systématiquement ignorées (pas de contact vide créé) et un onglet sans
* aucun bloc rempli est simplement finalisé, déverrouillant l'onglet Prix.
* Retourne true si l'onglet a é validé.
*/
async function submitContacts(onError: (error: unknown) => void): Promise<boolean> {
if (carrierId.value === null || tabSubmitting.value) {
@@ -431,7 +564,6 @@ export function useCarrierForm() {
}
tabSubmitting.value = true
try {
const hasSubmittable = contacts.value.some(c => c.id !== null || !isCarrierContactBlank(c))
const hasError = await submitRows(
contacts.value,
contactErrors,
@@ -450,9 +582,9 @@ export function useCarrierForm() {
}
},
onError,
// Amorce vide neuve ignorée s'il reste un autre bloc soumettable ;
// sinon on la soumet pour déclencher la 422 RG-4.08 (sur firstName).
contact => hasSubmittable && contact.id === null && isCarrierContactBlank(contact),
// Amorce vide neuve toujours ignorée (bloc Contact optionnel, ERP-193) :
// un onglet sans aucun bloc rempli se finalise sans rien créer.
contact => contact.id === null && isCarrierContactBlank(contact),
)
if (hasError) {
return false
@@ -465,6 +597,124 @@ export function useCarrierForm() {
}
}
// ── Onglet Prix (ERP-169) ─────────────────────────────────────────────────
// Un bloc présent par défaut (sens CLIENT pré-sélectionné). L'utilisateur ajoute
// les suivants via « + Nouveau prix ».
const prices = ref<CarrierPriceFormDraft[]>([emptyCarrierPrice()])
// Erreurs 422 par ligne (alignées sur l'index du v-for), peuplées par submitRows.
const priceErrors = ref<Record<string, string>[]>([])
// « + Nouveau prix » : autorisé si la liste est vide, sinon le dernier bloc doit
// être valide (branche complète + prix — RG-4.09→4.11, pré-check léger).
const canAddPrice = computed(() => {
const last = prices.value[prices.value.length - 1]
return last === undefined || isCarrierPriceValid(last)
})
function addPrice(): void {
if (canAddPrice.value) {
prices.value.push(emptyCarrierPrice())
}
}
/**
* Pré-validation FRONT d'un bloc prix (ERP-101) : renvoie les erreurs inline par
* champ obligatoire (sens + branche active + communs). Nécessaire car côté back
* l'Assert\NotBlank sur les scalaires (price/priceState...) court-circuite la
* validation de branche du CarrierPriceProcessor : le 422 ne porterait jamais
* client/supplier/adresses en même temps. Messages alignés sur le back.
*/
function validatePriceRow(price: CarrierPriceFormDraft): Record<string, string> {
const errs: Record<string, string> = {}
const msg = (key: string): string => t(`transport.carriers.form.price.errors.${key}`)
if (!price.direction) {
errs.direction = msg('direction')
}
if (price.direction === 'CLIENT') {
if (!price.clientIri) errs.client = msg('client')
if (!price.clientDeliveryAddressIri) errs.clientDeliveryAddress = msg('clientDeliveryAddress')
if (!price.departureSiteIri) errs.departureSite = msg('departureSite')
}
if (price.direction === 'FOURNISSEUR') {
if (!price.supplierIri) errs.supplier = msg('supplier')
if (!price.supplierSupplyAddressIri) errs.supplierSupplyAddress = msg('supplierSupplyAddress')
if (!price.deliverySiteIri) errs.deliverySite = msg('deliverySite')
}
if (!price.containerType) errs.containerType = msg('containerType')
if (!price.pricingUnit) errs.pricingUnit = msg('pricingUnit')
if (!price.price || price.price.trim() === '') errs.price = msg('price')
if (!price.priceState) errs.priceState = msg('priceState')
return errs
}
/** Suppression immédiate d'un prix existant (DELETE /carrier_prices/{id}). */
async function removePrice(index: number): Promise<void> {
await removeCollectionRow({
rows: prices.value,
errors: priceErrors.value,
index,
endpoint: '/carrier_prices',
deleteRow: url => api.delete(url, {}, { toast: false }),
makeEmpty: emptyCarrierPrice,
onError: notifyRemovalError,
onSuccess: notifyRemovalSuccess,
})
}
/**
* Valide l'onglet Prix : POST des nouveaux prix sur /carriers/{id}/prices, PATCH
* des existants sur /carrier_prices/{id} (groupe carrier:write:prices). La
* cohérence de branche CLIENT/FOURNISSEUR (RG-4.094.11) est re-validée back
* 422 par ligne. Onglet Prix optionnel : une liste vide finalise sans appel.
* Retourne true si l'onglet a é validé (création terminée).
*/
async function submitPrices(onError: (error: unknown) => void): Promise<boolean> {
if (carrierId.value === null || tabSubmitting.value) {
return false
}
// Pré-check front : affiche toutes les obligations sous leur champ d'un coup
// (le back ne peut pas tout renvoyer en une passe — cf. validatePriceRow).
const frontErrors = prices.value.map(validatePriceRow)
if (frontErrors.some(errs => Object.keys(errs).length > 0)) {
priceErrors.value = frontErrors
return false
}
tabSubmitting.value = true
try {
const hasError = await submitRows(
prices.value,
priceErrors,
async (price) => {
const body = buildCarrierPricePayload(price)
if (price.id === null) {
const created = await api.post<{ id: number }>(
`/carriers/${carrierId.value}/prices`,
body,
{ headers: { Accept: 'application/ld+json' }, toast: false },
)
price.id = created.id
}
else {
await api.patch(`/carrier_prices/${price.id}`, body, { toast: false })
}
},
onError,
)
if (hasError) {
return false
}
completeTab('prices')
return true
}
finally {
tabSubmitting.value = false
}
}
/**
* Intègre une ligne QUALIMAT sélectionnée dans l'onglet Qualimat (RG-4.01 /
* § 2.5) : copie le nom, force la certification à « QUALIMAT » (lecture seule),
@@ -500,16 +750,20 @@ export function useCarrierForm() {
city: row.city ?? '',
street: row.address ?? '',
}
// RG-4.05 : pré-remplit le 1er bloc de l'onglet Adresses par copie (la FK
// QUALIMAT survit, les champs restent éditables — § 2.5).
addresses.value = [{
id: null,
country: 'France',
postalCode: row.postalCode || null,
city: row.city || null,
street: row.address || null,
streetComplement: null,
}]
// RG-4.05 : à la CRÉATION, pré-remplit l'adresse (unique) par copie du
// référentiel QUALIMAT (champs éditables, la FK QUALIMAT survit — § 2.5).
// En MODIFICATION (ERP-172) : on NE TOUCHE PAS l'adresse déjà saisie — la
// re-sélection Qualimat actualise seulement nom + certification + FK.
if (!editMode.value) {
address.value = {
id: null,
country: 'France',
postalCode: row.postalCode || null,
city: row.city || null,
street: row.address || null,
streetComplement: null,
}
}
return true
}
@@ -543,6 +797,7 @@ export function useCarrierForm() {
mainSubmitting,
tabSubmitting,
mainErrors,
dischargeUploading,
// affichage conditionnel
isLiot,
isQualimat,
@@ -557,13 +812,10 @@ export function useCarrierForm() {
validated,
editMode,
isValidated,
// adresses
addresses,
// adresse (unique)
address,
addressErrors,
canAddAddress,
addAddress,
removeAddress,
submitAddresses,
submitAddress,
// contacts
contacts,
contactErrors,
@@ -571,10 +823,22 @@ export function useCarrierForm() {
addContact,
removeContact,
submitContacts,
// prix
prices,
priceErrors,
canAddPrice,
addPrice,
removePrice,
submitPrices,
// actions
setCertification,
selectDischarge,
clearDischarge,
validateMainFront,
buildMainPayload,
submitMain,
updateMain,
prefillFrom,
patchCarrier,
applyQualimatSelection,
completeTab,
@@ -66,5 +66,6 @@ export interface CarrierFilters {
* `usePaginatedList`. Aucun reset au logout a gerer.
*/
export function useCarriersRepository() {
return usePaginatedList<Carrier, CarrierFilters>({ url: '/carriers' })
// Pagination par defaut a 25 sur le repertoire (retour metier ERP-193).
return usePaginatedList<Carrier, CarrierFilters>({ url: '/carriers', defaultItemsPerPage: 25 })
}
@@ -0,0 +1,432 @@
<template>
<div>
<!-- En-tête : retour consultation + titre. -->
<div class="flex items-center gap-3 pt-11">
<MalioButtonIcon
icon="mdi:arrow-left-bold"
icon-size="24"
variant="ghost"
v-bind="{ ariaLabel: t('transport.carriers.edit.back') }"
@click="goBack"
/>
<h1 class="text-[30px] font-semibold text-m-primary">{{ t('transport.carriers.edit.title') }}</h1>
</div>
<p v-if="loading" class="mt-12 text-center text-black/60">{{ t('transport.carriers.edit.loading') }}</p>
<p v-else-if="error" class="mt-12 text-center text-m-danger">{{ t('transport.carriers.edit.notFound') }}</p>
<template v-else>
<!-- Formulaire principal (éditable, PATCH partiel) -->
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
<MalioInputText
v-model="main.name"
:mask="FREE_TEXT_MASK"
:label="t('transport.carriers.form.main.name')"
:required="true"
:error="mainErrors.errors.name"
/>
<!-- Cas LIOT : le champ immatriculations occupe les colonnes restantes
de la ligne (3 en xl, 2 sinon). Wrapper pour le col-span car
MalioInputText (inheritAttrs:false) renvoie `class` sur l'input. -->
<div v-if="isLiot" class="col-span-2 xl:col-span-3">
<MalioInputText
v-model="main.liotPlates"
:mask="LIOT_PLATES_MASK"
:label="t('transport.carriers.form.main.liotPlates')"
:hint="t('transport.carriers.form.main.liotPlatesHint')"
:required="true"
:error="mainErrors.errors.liotPlates"
/>
</div>
<template v-if="!isLiot">
<MalioSelect
:model-value="main.certificationType"
:options="certificationOptions"
:label="t('transport.carriers.form.main.certificationType')"
empty-option-label=""
:required="true"
:disabled="certificationReadonly"
:error="mainErrors.errors.certificationType"
@update:model-value="(v: string | number | null) => setCertification(v === null ? null : String(v))"
/>
<MalioInputUpload
v-if="showDischarge"
:model-value="dischargeFileName"
:label="t('transport.carriers.form.main.discharge')"
accept="application/pdf,image/*"
:required="true"
:disabled="dischargeUploading"
:clearable="true"
:error="mainErrors.errors.dischargeDocument"
@update:model-value="(v: string) => dischargeFileName = v"
@file-selected="selectDischarge"
@clear="onClearDischarge"
/>
<div v-else class="hidden xl:block"></div>
<div class="flex h-12 items-center">
<MalioCheckbox
id="carrier-edit-chartered"
:label="t('transport.carriers.form.main.isChartered')"
:model-value="main.isChartered"
:reserve-message-space="false"
@update:model-value="(val: boolean) => main.isChartered = val"
/>
</div>
<template v-if="showCharteredFields">
<MalioInputAmount
:key="indexationKey"
:model-value="main.indexationRate"
:label="t('transport.carriers.form.main.indexationRate')"
icon-name="mdi:percent"
icon-position="right"
:required="true"
:error="mainErrors.errors.indexationRate"
@update:model-value="onIndexationInput"
/>
<!-- Contenant : Benne / Fond mouvant en radios, centrés (h-12) comme
à l'onglet Prix (Benne par défaut). -->
<div>
<div class="flex h-12 items-center gap-4">
<MalioRadioButton
:model-value="main.containerType"
name="carrier-main-container"
value="BENNE"
:label="t('transport.carriers.containerType.BENNE')"
group-class="mt-0"
@update:model-value="(v: string | number | boolean | null) => main.containerType = v === null ? null : String(v)"
/>
<MalioRadioButton
:model-value="main.containerType"
name="carrier-main-container"
value="FOND_MOUVANT"
:label="t('transport.carriers.containerType.FOND_MOUVANT')"
group-class="mt-0"
@update:model-value="(v: string | number | boolean | null) => main.containerType = v === null ? null : String(v)"
/>
</div>
<p v-if="mainErrors.errors.containerType" class="ml-[2px] text-xs text-m-danger">{{ mainErrors.errors.containerType }}</p>
</div>
<MalioInputText
:model-value="main.volumeM3"
:label="t('transport.carriers.form.main.volumeM3')"
:required="true"
:error="mainErrors.errors.volumeM3"
@update:model-value="(v: string) => main.volumeM3 = sanitizeDecimal(v)"
/>
</template>
</template>
</div>
<div class="mt-12 flex justify-center">
<MalioButton
variant="primary"
:label="t('transport.carriers.edit.save')"
:disabled="mainSubmitting"
@click="onUpdateMain"
/>
</div>
<!-- Onglets éditables (navigation libre, PATCH partiel par onglet) -->
<MalioTabList v-model="activeTab" :tabs="tabs" class="mt-[60px]">
<!-- Qualimat : actualiser nom + certification depuis le référentiel (ERP-172). -->
<template #qualimat>
<CarrierQualimatTab
:search-name="main.name"
:selected-iri="main.qualimatCarrierIri"
@integrate="onIntegrateQualimat"
/>
</template>
<template #addresses>
<div class="mt-12 flex flex-col gap-6">
<!-- Adresse UNIQUE (ERP-172) : un seul bloc, sans ajouter/supprimer. -->
<CarrierAddressBlock
:model-value="address"
:country-options="countryOptions"
:errors="addressErrors"
@update:model-value="(v) => address = v"
@degraded="onAddressDegraded"
/>
<div class="flex justify-center gap-6">
<MalioButton variant="primary" :label="t('transport.carriers.edit.save')" :disabled="tabSubmitting" @click="onSubmitAddresses" />
</div>
</div>
</template>
<template #contacts>
<div class="mt-12 flex flex-col gap-6">
<CarrierContactBlock
v-for="(contact, index) in contacts"
:key="index"
:model-value="contact"
:removable="isRowRemovable(contacts, index)"
:errors="contactErrors[index]"
@update:model-value="(v) => contacts[index] = v"
@remove="askRemoveContact(index)"
/>
<div class="flex justify-center gap-6">
<MalioButton variant="secondary" icon-name="mdi:add-bold" icon-position="left" :label="t('transport.carriers.form.contact.add')" :disabled="!canAddContact" @click="addContact" />
<MalioButton variant="primary" :label="t('transport.carriers.edit.save')" :disabled="tabSubmitting" @click="onSubmitContacts" />
</div>
</div>
</template>
<template #prices>
<div class="mt-12 flex flex-col gap-6">
<CarrierPriceBlock
v-for="(price, index) in prices"
:key="index"
:model-value="price"
:client-options="clientOptions"
:supplier-options="supplierOptions"
:site-options="siteOptions"
removable
:errors="priceErrors[index]"
@update:model-value="(v) => prices[index] = v"
@remove="askRemovePrice(index)"
/>
<div class="flex justify-center gap-6">
<MalioButton variant="secondary" icon-name="mdi:add-bold" icon-position="left" :label="t('transport.carriers.form.price.add')" :disabled="!canAddPrice" @click="addPrice" />
<MalioButton variant="primary" :label="t('transport.carriers.edit.save')" :disabled="tabSubmitting" @click="onSubmitPrices" />
</div>
</div>
</template>
</MalioTabList>
</template>
<!-- Modal de confirmation de suppression de bloc. -->
<MalioModal v-model="deleteConfirm.open" modal-class="max-w-md">
<template #header>
<h2 class="text-[24px] font-bold">{{ t('transport.carriers.form.confirmDelete.title') }}</h2>
</template>
<p>{{ t('transport.carriers.form.confirmDelete.message') }}</p>
<template #footer>
<MalioButton variant="secondary" button-class="flex-1" :label="t('transport.carriers.form.confirmDelete.cancel')" @click="deleteConfirm.open = false" />
<MalioButton variant="danger" button-class="flex-1" :label="t('transport.carriers.form.confirmDelete.confirm')" @click="runDeleteConfirm" />
</template>
</MalioModal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { extractApiErrorMessage } from '~/shared/utils/api'
import { isRowRemovable } from '~/shared/utils/collectionRow'
import CarrierAddressBlock from '~/modules/transport/components/CarrierAddressBlock.vue'
import CarrierContactBlock from '~/modules/transport/components/CarrierContactBlock.vue'
import CarrierPriceBlock from '~/modules/transport/components/CarrierPriceBlock.vue'
import CarrierQualimatTab from '~/modules/transport/components/CarrierQualimatTab.vue'
import { useCarrierForm } from '~/modules/transport/composables/useCarrierForm'
import { useCarrier } from '~/modules/transport/composables/useCarrier'
import type { QualimatCarrierRow } from '~/modules/transport/composables/useQualimatSearch'
import { clampPercent, LIOT_PLATES_MASK, sanitizeDecimal } from '~/modules/transport/utils/forms/numberInput'
import { FREE_TEXT_MASK } from '~/shared/utils/textSanitize'
interface SelectOption {
value: string
label: string
}
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const toast = useToast()
const api = useApi()
const { can } = usePermissions()
const carrierId = route.params.id as string
useHead({ title: t('transport.carriers.edit.title') })
// Gating route : l'édition est réservée à `manage` ; sinon retour consultation.
if (!can('transport.carriers.manage')) {
await navigateTo(`/carriers/${carrierId}`)
}
const { carrier, loading, error, load } = useCarrier(carrierId)
const {
main,
mainSubmitting,
tabSubmitting,
mainErrors,
dischargeUploading,
selectDischarge,
clearDischarge,
setCertification,
isLiot,
certificationReadonly,
showCharteredFields,
showDischarge,
applyQualimatSelection,
address,
addressErrors,
submitAddress,
contacts,
contactErrors,
canAddContact,
addContact,
removeContact,
submitContacts,
prices,
priceErrors,
canAddPrice,
addPrice,
removePrice,
submitPrices,
updateMain,
prefillFrom,
} = useCarrierForm()
const SELECTABLE_CERTIFICATIONS = ['GMP_PLUS', 'OVOCOM', 'COMPTE_PROPRE', 'AUTRE'] as const
const certificationOptions = computed<SelectOption[]>(() => {
const codes: string[] = [...SELECTABLE_CERTIFICATIONS]
if (main.certificationType === 'QUALIMAT') codes.unshift('QUALIMAT')
return codes.map(code => ({ value: code, label: t(`transport.carriers.certification.${code}`) }))
})
const TAB_ICONS: Record<string, string> = {
qualimat: 'mdi:truck-fast-outline',
addresses: 'mdi:map-marker-outline',
contacts: 'mdi:account-box-plus-outline',
prices: 'mdi:payment',
}
// Onglet Qualimat disponible en modif (ERP-172) : « actualiser » nom + certification.
const TAB_KEYS = ['qualimat', 'addresses', 'contacts', 'prices']
// ERP-193 : on honore l'onglet demande via `?tab=` (navigation depuis la
// consultation) pour retomber sur le meme onglet ; defaut « addresses ».
const requestedTab = typeof route.query.tab === 'string' ? route.query.tab : ''
const activeTab = ref(TAB_KEYS.includes(requestedTab) ? requestedTab : 'addresses')
const tabs = computed(() => TAB_KEYS.map(key => ({
key,
label: t(`transport.carriers.tab.${key}`),
icon: TAB_ICONS[key],
})))
// Référentiels (pays + clients / fournisseurs / sites pour l'onglet Prix)
const countryOptions = ref<SelectOption[]>([{ value: 'France', label: 'France' }])
const clientOptions = ref<SelectOption[]>([])
const supplierOptions = ref<SelectOption[]>([])
const siteOptions = ref<SelectOption[]>([])
async function loadOptions(url: string, target: typeof clientOptions, labelOf: (m: Record<string, unknown>) => string): Promise<void> {
try {
const data = await api.get<{ member?: Record<string, unknown>[] }>(url, { pagination: 'false' }, { headers: { Accept: 'application/ld+json' }, toast: false })
target.value = (data.member ?? []).map(m => ({ value: String(m['@id']), label: labelOf(m) }))
}
catch {
target.value = []
}
}
async function loadCountries(): Promise<void> {
try {
const data = await api.get<{ member?: { name: string }[] }>('/countries', { pagination: 'false' }, { headers: { Accept: 'application/ld+json' }, toast: false })
const list = (data.member ?? []).map(c => ({ value: c.name, label: c.name }))
countryOptions.value = list.some(c => c.value === 'France') ? list : [{ value: 'France', label: 'France' }, ...list]
}
catch { /* fallback France */ }
}
// Chargement + préremplissage
onMounted(async () => {
await load()
if (carrier.value) {
prefillFrom(carrier.value)
// Pré-affiche le nom du fichier de décharge déjà rattaché (s'il existe).
const doc = carrier.value.dischargeDocument
if (doc && typeof doc !== 'string') {
const meta = doc as Record<string, unknown>
dischargeFileName.value = String(meta.originalFilename ?? meta.name ?? '')
}
}
loadCountries().catch(() => {})
void loadOptions('/clients', clientOptions, m => String(m.companyName ?? m['@id']))
void loadOptions('/suppliers', supplierOptions, m => String(m.companyName ?? m['@id']))
void loadOptions('/sites', siteOptions, m => String(m.name ?? m['@id']))
})
function apiErrorMessage(err: unknown): string {
const data = (err as { response?: { _data?: unknown } })?.response?._data
return extractApiErrorMessage(data) || t('transport.carriers.toast.error')
}
// Nom de fichier affiché dans le champ Décharge (alimenté à la sélection ou au
// chargement d'un transporteur ayant déjà une décharge).
const dischargeFileName = ref('')
/** Vidage du champ Décharge : oublie le fichier en attente / l'IRI + le nom affiché. */
function onClearDischarge(): void {
clearDischarge()
dischargeFileName.value = ''
}
// Indexation plafonnée à 100 % : la clé force le ré-affichage du MalioInputAmount
// (contrôlé) quand le plafonnement laisse le modelValue inchangé.
const indexationKey = ref(0)
/** Saisie de l'indexation : plafonne à 100 et re-synchronise le champ si plafonné. */
function onIndexationInput(value: string): void {
const clamped = clampPercent(value)
main.indexationRate = clamped
if (clamped !== value) {
indexationKey.value += 1
}
}
function goBack(): void {
// ERP-193 : on transmet l'onglet courant pour retomber dessus en consultation.
router.push({ path: `/carriers/${carrierId}`, query: { tab: activeTab.value } })
}
/** PATCH du formulaire principal (pas de re-POST). */
async function onUpdateMain(): Promise<void> {
const ok = await updateMain()
if (ok) {
toast.success({ title: t('transport.carriers.toast.updateSuccess') })
}
}
/** Intégration d'une ligne QUALIMAT (onglet Qualimat) : actualise nom + certification
* + FK via PATCH (applyQualimatSelection). L'adresse existante n'est pas touchée. */
async function onIntegrateQualimat(row: QualimatCarrierRow): Promise<void> {
const ok = await applyQualimatSelection(row)
if (ok) {
toast.success({ title: t('transport.carriers.toast.integrateSuccess') })
}
}
async function onSubmitAddresses(): Promise<void> {
const ok = await submitAddress(err => toast.error({ title: t('transport.carriers.toast.error'), message: apiErrorMessage(err) }))
if (ok) toast.success({ title: t('transport.carriers.toast.addressSaved') })
}
async function onSubmitContacts(): Promise<void> {
const ok = await submitContacts(err => toast.error({ title: t('transport.carriers.toast.error'), message: apiErrorMessage(err) }))
if (ok) toast.success({ title: t('transport.carriers.toast.contactSaved') })
}
async function onSubmitPrices(): Promise<void> {
const ok = await submitPrices(err => toast.error({ title: t('transport.carriers.toast.error'), message: apiErrorMessage(err) }))
if (ok) toast.success({ title: t('transport.carriers.toast.priceSaved') })
}
// Suppression de bloc (modal de confirmation générique)
const deleteConfirm = reactive({ open: false, action: null as null | (() => void) })
function askRemoveContact(index: number): void {
deleteConfirm.action = () => { void removeContact(index) }
deleteConfirm.open = true
}
function askRemovePrice(index: number): void {
deleteConfirm.action = () => { void removePrice(index) }
deleteConfirm.open = true
}
function runDeleteConfirm(): void {
deleteConfirm.action?.()
deleteConfirm.action = null
deleteConfirm.open = false
}
function onAddressDegraded(): void {
toast.warning({ title: t('transport.carriers.toast.error'), message: t('transport.carriers.form.address.degraded') })
}
</script>
@@ -0,0 +1,544 @@
<template>
<div>
<!-- En-tête : retour répertoire + nom + actions. -->
<div class="flex items-center gap-3 pt-11">
<MalioButtonIcon
icon="mdi:arrow-left-bold"
icon-size="24"
variant="ghost"
v-bind="{ ariaLabel: t('transport.carriers.consultation.back') }"
@click="goBack"
/>
<h1 class="text-[30px] font-semibold text-m-primary">{{ headerTitle }}</h1>
<div class="ml-auto flex items-center gap-12">
<MalioButton
v-if="canEdit"
variant="secondary"
icon-name="mdi:pencil-outline"
icon-position="left"
:label="t('transport.carriers.action.edit')"
@click="goEdit"
/>
<MalioButton
v-if="showArchive"
variant="danger"
icon-name="mdi:archive-arrow-down-outline"
icon-position="left"
:label="t('transport.carriers.action.archive')"
@click="askToggleArchive"
/>
<MalioButton
v-if="showRestore"
variant="secondary"
icon-name="mdi:archive-arrow-up-outline"
icon-position="left"
:label="t('transport.carriers.action.restore')"
@click="askToggleArchive"
/>
</div>
</div>
<p v-if="loading" class="mt-12 text-center text-black/60">{{ t('transport.carriers.consultation.loading') }}</p>
<p v-else-if="error" class="mt-12 text-center text-m-danger">{{ t('transport.carriers.consultation.notFound') }}</p>
<template v-else-if="carrier">
<!-- Bloc principal (lecture seule) même disposition que l'ajout -->
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
<MalioInputText :model-value="main.name" :label="t('transport.carriers.form.main.name')" disabled />
<!-- Cas LIOT : le champ immatriculations occupe les colonnes restantes
de la ligne (3 en xl, 2 sinon), comme à l'ajout / la modification. -->
<div v-if="isLiot" class="col-span-2 xl:col-span-3">
<MalioInputText
:model-value="main.liotPlates"
:label="t('transport.carriers.form.main.liotPlates')"
disabled
/>
</div>
<!-- Cas standard : certification + décharge (col 3 réservée) + affrètement (col 4). -->
<template v-if="!isLiot">
<MalioInputText
:model-value="certificationLabel"
:label="t('transport.carriers.form.main.certificationType')"
disabled
/>
<!-- Colonne 3 réservée à la décharge (si AUTRE), sinon vide (xl). -->
<MalioInputText
v-if="main.certificationType === 'AUTRE'"
:model-value="dischargeLabel"
:label="t('transport.carriers.form.main.discharge')"
disabled
/>
<div v-else class="hidden xl:block"></div>
<!-- Affréter : colonne 4, centré (h-12) comme à l'ajout. -->
<div class="flex h-12 items-center">
<MalioCheckbox
id="carrier-view-chartered"
:label="t('transport.carriers.form.main.isChartered')"
:model-value="main.isChartered"
disabled
:reserve-message-space="false"
/>
</div>
<!-- Champs d'affrètement (ligne 2) si affrété. -->
<template v-if="main.isChartered">
<MalioInputText :model-value="indexationDisplay" :label="t('transport.carriers.form.main.indexationRate')" disabled />
<!-- Contenant : radios désactivés (lecture seule), aligné sur l'ajout / la modif. -->
<div>
<div class="flex h-12 items-center gap-4">
<MalioRadioButton
:model-value="main.containerType"
name="carrier-view-container"
value="BENNE"
:label="t('transport.carriers.containerType.BENNE')"
disabled
group-class="mt-0"
/>
<MalioRadioButton
:model-value="main.containerType"
name="carrier-view-container"
value="FOND_MOUVANT"
:label="t('transport.carriers.containerType.FOND_MOUVANT')"
disabled
group-class="mt-0"
/>
</div>
</div>
<MalioInputText :model-value="main.volumeM3" :label="t('transport.carriers.form.main.volumeM3')" disabled />
</template>
</template>
</div>
<!-- Onglets (Adresses · Contacts · Prix) ouvre sur Adresses -->
<!-- ERP-193 : barre masquee s'il ne reste aucun onglet non vide. -->
<MalioTabList v-if="visibleTabKeys.length" v-model="activeTab" :tabs="tabs" class="mt-[60px]">
<template #addresses>
<div class="mt-12 flex flex-col gap-6">
<!-- Adresse UNIQUE (ERP-172). -->
<CarrierAddressBlock
:model-value="address"
:country-options="countryOptionsFor(address.country)"
disabled
/>
</div>
</template>
<template #contacts>
<div class="mt-12 flex flex-col gap-6">
<CarrierContactBlock
v-for="(contact, index) in contacts"
:key="index"
:model-value="contact"
disabled
/>
</div>
</template>
<!-- Prix : tableau présentationnel regroupé par contenant + export. -->
<template #prices>
<div class="mt-12 flex flex-col gap-6">
<!-- Police / bordures / radius alignés sur MalioDataTable (header
16px, corps 14px). 1re colonne « Contenant » : libellé du
groupe (Fond Mouvant / Benne) fusionné en rowspan ; séparateur
épais entre les deux groupes. -->
<table class="w-full table-fixed border-separate border-spacing-0 overflow-hidden rounded-malio border border-black text-left text-black">
<!-- Répartition (table-fixed) : « Transport » étroit (libellé
court Benne / Fond mouvant) ; Fournisseurs/Clients et
Adresse livraisons larges ; Forfait / Tonne / Indexation
/ État réduits. -->
<colgroup>
<col class="w-[120px]" />
<col class="w-[20%]" />
<col class="w-[24%]" />
<col class="w-[11%]" />
<col class="w-[9%]" />
<col class="w-[9%]" />
<col class="w-[9%]" />
<col class="w-[9%]" />
</colgroup>
<thead>
<tr>
<!-- En-tête centré pour matcher les cellules fusionnées Benne / Fond mouvant. -->
<th class="border-b border-r border-black bg-m-surface px-3 py-3 text-center align-middle text-[16px] font-semibold">{{ t('transport.carriers.consultation.price.group') }}</th>
<th class="border-b border-black bg-m-surface px-3 py-3 align-middle text-[16px] font-semibold">{{ t('transport.carriers.consultation.price.carrier') }}</th>
<th class="border-b border-black bg-m-surface px-3 py-3 align-middle text-[16px] font-semibold">{{ t('transport.carriers.consultation.price.delivery') }}</th>
<th class="border-b border-black bg-m-surface px-3 py-3 align-middle text-[16px] font-semibold">{{ t('transport.carriers.consultation.price.aproOrSite') }}</th>
<th class="border-b border-black bg-m-surface px-3 py-3 align-middle text-[16px] font-semibold">{{ t('transport.carriers.consultation.price.forfait') }}</th>
<th class="border-b border-black bg-m-surface px-3 py-3 align-middle text-[16px] font-semibold">{{ t('transport.carriers.consultation.price.tonne') }}</th>
<th class="border-b border-black bg-m-surface px-3 py-3 align-middle text-[16px] font-semibold">{{ t('transport.carriers.consultation.price.indexation') }}</th>
<th class="border-b border-black bg-m-surface px-3 py-3 align-middle text-[16px] font-semibold">{{ t('transport.carriers.consultation.price.state') }}</th>
</tr>
</thead>
<tbody>
<template v-for="(group, gi) in priceGroups" :key="gi">
<tr
v-for="(row, i) in group.rows"
:key="`${gi}-${i}`"
>
<!-- Contenant par ligne (plus de cellule fusionnée) ; séparateur
à droite, comme l'ancienne colonne de groupe. -->
<td class="border-r border-black px-3 py-4 text-center align-middle text-[14px] font-medium" :class="dataBorder(gi, i)">{{ row.transport }}</td>
<td class="px-3 py-4 text-[14px]" :class="dataBorder(gi, i)">{{ row.party }}</td>
<td class="px-3 py-4 text-[14px]" :class="dataBorder(gi, i)">{{ row.delivery }}</td>
<td class="px-3 py-4 text-[14px]" :class="dataBorder(gi, i)">{{ row.apro }}</td>
<td class="px-3 py-4 text-[14px]" :class="dataBorder(gi, i)">{{ row.forfait }}</td>
<td class="px-3 py-4 text-[14px]" :class="dataBorder(gi, i)">{{ row.tonne }}</td>
<td class="px-3 py-4 text-[14px]" :class="dataBorder(gi, i)">{{ row.indexation }}</td>
<td class="px-3 py-4 text-[14px]" :class="dataBorder(gi, i)">{{ row.state }}</td>
</tr>
</template>
<tr v-if="!hasPrices">
<td colspan="8" class="px-3 py-4 text-center text-[14px] text-m-muted">
{{ t('transport.carriers.consultation.price.empty') }}
</td>
</tr>
</tbody>
</table>
<div v-if="hasPrices" class="flex justify-center">
<MalioButton
variant="primary"
:label="t('transport.carriers.consultation.price.export')"
:disabled="exporting"
@click="exportPrices"
/>
</div>
</div>
</template>
</MalioTabList>
</template>
<!-- Modal de confirmation archivage / restauration. -->
<MalioModal v-model="confirmArchive.open" modal-class="max-w-md">
<template #header>
<h2 class="text-[24px] font-bold">{{ confirmArchive.title }}</h2>
</template>
<p>{{ confirmArchive.message }}</p>
<template #footer>
<MalioButton
variant="secondary"
button-class="flex-1"
:label="t('transport.carriers.form.confirmDelete.cancel')"
@click="confirmArchive.open = false"
/>
<MalioButton
variant="danger"
button-class="flex-1"
:label="confirmArchive.confirmLabel"
@click="runToggleArchive"
/>
</template>
</MalioModal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import CarrierAddressBlock from '~/modules/transport/components/CarrierAddressBlock.vue'
import CarrierContactBlock from '~/modules/transport/components/CarrierContactBlock.vue'
import { useCarrier } from '~/modules/transport/composables/useCarrier'
import {
canEditCarrier,
carrierConsultationVisibleTabs,
labelOfRelation,
mapAddressToDraft,
mapContactToDraft,
mapMainToDraft,
showArchiveAction,
showRestoreAction,
type CarrierPriceRead,
type Relation,
} from '~/modules/transport/utils/forms/carrierMappers'
import { extractApiErrorMessage } from '~/shared/utils/api'
interface SelectOption {
value: string
label: string
}
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const toast = useToast()
const api = useApi()
const { can } = usePermissions()
const carrierId = route.params.id as string
const { carrier, loading, error, load, archive, restore } = useCarrier(carrierId)
const isArchived = computed(() => carrier.value?.isArchived ?? false)
const canEdit = computed(() => canEditCarrier(can))
const showArchive = computed(() => showArchiveAction(can, isArchived.value))
const showRestore = computed(() => showRestoreAction(can, isArchived.value))
const headerTitle = computed(() => carrier.value?.name || t('transport.carriers.consultation.title'))
useHead({ title: t('transport.carriers.consultation.title') })
// Bloc principal mappé (lecture seule)
const main = computed(() => mapMainToDraft(carrier.value ?? { id: 0, '@id': '' }))
const isLiot = computed(() => main.value.name.trim().toUpperCase() === 'LIOT')
const certificationLabel = computed(() => main.value.certificationType
? t(`transport.carriers.certification.${main.value.certificationType}`)
: '')
// Indexation affichée avec le « % » (comme l'icône du champ amount de l'ajout).
const indexationDisplay = computed(() => main.value.indexationRate ? `${main.value.indexationRate} %` : '')
// Décharge : nom du fichier embarqué si présent (sinon vide ; la colonne reste réservée).
const dischargeLabel = computed(() => {
const doc = carrier.value?.dischargeDocument
if (doc && typeof doc !== 'string') {
const meta = doc as Record<string, unknown>
return String(meta.originalFilename ?? meta.name ?? '')
}
return ''
})
// Onglets : Adresses · Contacts · Prix (ouvre sur Adresses, pas de Qualimat)
// ERP-193 (retour metier) : on masque tout onglet de donnees vide.
const TAB_ICONS: Record<string, string> = {
addresses: 'mdi:map-marker-outline',
contacts: 'mdi:account-box-plus-outline',
prices: 'mdi:payment',
}
const visibleTabKeys = computed(() => carrierConsultationVisibleTabs(carrier.value))
const tabs = computed(() => visibleTabKeys.value.map(key => ({
key,
label: t(`transport.carriers.tab.${key}`),
icon: TAB_ICONS[key],
})))
// Onglet initial : vide tant que le transporteur n'est pas charge, puis premier
// onglet visible. Un watcher recale si l'onglet courant disparait. ERP-193 : on
// honore l'onglet demande via `?tab=` (navigation depuis l'edition) s'il est
// visible, pour retomber sur le meme onglet en passant edition <-> consultation.
const activeTab = ref('')
let requestedTab = typeof route.query.tab === 'string' ? route.query.tab : ''
watch(visibleTabKeys, (keys) => {
if (keys.length === 0) {
activeTab.value = ''
return
}
if (!keys.includes(activeTab.value)) {
activeTab.value = requestedTab && keys.includes(requestedTab) ? requestedTab : keys[0]
requestedTab = ''
}
}, { immediate: true })
// Adresse UNIQUE (ERP-172) : un seul bloc en lecture seule (vide si pas d'adresse).
const address = computed(() => carrier.value?.address
? mapAddressToDraft(carrier.value.address)
: mapAddressToDraft({ id: 0, '@id': '' }))
const contacts = computed(() => {
const list = (carrier.value?.contacts ?? []).map(mapContactToDraft)
return list.length > 0 ? list : [mapContactToDraft({ id: 0, '@id': '' })]
})
/** Pays : une seule option (valeur courante), suffisant pour l'affichage readonly. */
function countryOptionsFor(country: string): SelectOption[] {
return country ? [{ value: country, label: country }] : []
}
// Tableau Prix consultation (regroupé par ADRESSE DE LIVRAISON)
// Rang d'affichage des contenants au sein d'une même adresse (Fond mouvant puis Benne).
const CONTAINER_RANK: Record<string, number> = { FOND_MOUVANT: 0, BENNE: 1 }
interface PriceRowView {
/** Contenant (libellé affiché : Fond mouvant / Benne). */
transport: string
/** Contenant brut (FOND_MOUVANT / BENNE) — tri interne du groupe. */
transportType: string
/** Fournisseur ou client lié au prix (raison sociale). */
party: string
apro: string
delivery: string
forfait: string
tonne: string
indexation: string
state: string
}
/** Groupe de prix d'une même adresse de livraison (lignes consécutives). */
interface PriceGroupView {
rows: PriceRowView[]
}
/** Formate un montant décimal en « 1 000,00 € » (chaîne vide si absent). */
function formatAmount(value: string | null | undefined): string {
if (!value) {
return ''
}
const n = Number(value)
if (Number.isNaN(n)) {
return ''
}
return `${n.toLocaleString('fr-FR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} €`
}
/** Code du site = département (2 premiers chiffres du code postal, ex: 86 / 17 / 82). */
function siteCode(relation: Relation): string {
if (!relation || typeof relation === 'string') {
return ''
}
const postalCode = relation.postalCode as string | undefined
return postalCode ? postalCode.slice(0, 2) : ''
}
/**
* Construit une ligne d'affichage depuis un prix embarqué (maquette Prix) :
* - « Transport » = le contenant (Fond mouvant / Benne) ;
* - « Fournisseurs / Clients » = le fournisseur OU le client lié (raison sociale) ;
* - « Adresse sites » = le CODE du site (département, ex: 86 / 17 / 82) ;
* - « Adresse livraisons » = l'adresse (voie) du client/fournisseur ;
* - le prix tombe dans Forfait OU Tonne selon `pricingUnit`.
*/
function toPriceRow(price: CarrierPriceRead): PriceRowView {
const isClient = price.direction === 'CLIENT'
const containerType = price.containerType ?? ''
return {
transportType: containerType,
transport: containerType ? t(`transport.carriers.containerType.${containerType}`) : '',
party: labelOfRelation(isClient ? price.client : price.supplier),
apro: isClient ? siteCode(price.departureSite) : siteCode(price.deliverySite),
delivery: isClient ? labelOfRelation(price.clientDeliveryAddress) : labelOfRelation(price.supplierSupplyAddress),
forfait: price.pricingUnit === 'FORFAIT' ? formatAmount(price.price) : '',
tonne: price.pricingUnit === 'TONNE' ? formatAmount(price.price) : '',
// CarrierPrice n'a pas de taux d'indexation propre on affiche celui du
// transporteur (formulaire principal). À faire évoluer si un taux par prix
// est requis (gap back).
indexation: main.value.indexationRate ? `${main.value.indexationRate} %` : '',
state: price.priceState ? t(`transport.carriers.form.price.state${stateSuffix(price.priceState)}`) : '',
}
}
/** EN_COURS → EnCours, VALIDE → Valide, NON_VALIDE → NonValide (clés i18n existantes). */
function stateSuffix(state: string): string {
const map: Record<string, string> = { EN_COURS: 'EnCours', VALIDE: 'Valide', NON_VALIDE: 'NonValide' }
return map[state] ?? ''
}
// Prix regroupés par ADRESSE DE LIVRAISON : les lignes d'une même adresse sont
// consécutives (triées par contenant Fond mouvant Benne), les groupes triés
// alphabétiquement par adresse. Un séparateur épais sépare deux adresses.
const priceGroups = computed<PriceGroupView[]>(() => {
const rows = (carrier.value?.prices ?? []).map(toPriceRow)
const byDelivery = new Map<string, PriceRowView[]>()
for (const row of rows) {
const list = byDelivery.get(row.delivery)
if (list) {
list.push(row)
} else {
byDelivery.set(row.delivery, [row])
}
}
return [...byDelivery.entries()]
.sort(([a], [b]) => a.localeCompare(b, 'fr'))
.map(([, groupRows]) => ({
rows: groupRows
.slice()
.sort((x, y) => (CONTAINER_RANK[x.transportType] ?? 99) - (CONTAINER_RANK[y.transportType] ?? 99)),
}))
})
const hasPrices = computed(() => priceGroups.value.length > 0)
/**
* Bordure basse d'une cellule de données :
* - ligne interne d'un groupe d'adresse (même adresse de livraison) fine grise ;
* - dernière ligne d'un groupe NON final épaisse noire (sépare deux adresses) ;
* - dernière ligne du DERNIER groupe aucune (le cadre du tableau s'en charge,
* évite la double bordure tout en bas).
*/
function dataBorder(gi: number, i: number): string {
const group = priceGroups.value[gi]
const isLastRow = i === group.rows.length - 1
const isLastGroup = gi === priceGroups.value.length - 1
// Couleur de bordure SIDE-SPECIFIC (border-b-*) : un `border-{color}` global
// ecraserait la couleur du bord droit noir de la colonne Transport.
if (!isLastRow) {
return 'border-b border-b-m-muted/30'
}
return isLastGroup ? '' : 'border-b-2 border-b-black'
}
// Export XLSX des prix
const exporting = ref(false)
async function exportPrices(): Promise<void> {
if (exporting.value) return
exporting.value = true
try {
const blob = await api.get<Blob>(`/carriers/${carrierId}/prices/export.xlsx`, {}, {
responseType: 'blob',
toast: false,
} as unknown as Parameters<typeof api.get>[2])
triggerDownload(blob, `transporteur-${carrierId}-prix.xlsx`)
}
catch {
toast.error({ title: t('transport.carriers.toast.error'), message: t('transport.carriers.toast.exportError') })
}
finally {
exporting.value = false
}
}
function triggerDownload(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = filename
document.body.appendChild(link)
link.click()
link.remove()
URL.revokeObjectURL(url)
}
// Navigation / archivage
function goBack(): void {
router.push('/carriers')
}
function goEdit(): void {
// ERP-193 : on transmet l'onglet courant pour retomber dessus en edition.
router.push({ path: `/carriers/${carrierId}/edit`, query: activeTab.value ? { tab: activeTab.value } : {} })
}
const confirmArchive = reactive({ open: false, title: '', message: '', confirmLabel: '' })
function askToggleArchive(): void {
const archiving = !isArchived.value
confirmArchive.title = archiving ? t('transport.carriers.action.archive') : t('transport.carriers.action.restore')
confirmArchive.message = archiving
? t('transport.carriers.consultation.confirmArchive.message')
: t('transport.carriers.consultation.confirmRestore.message')
confirmArchive.confirmLabel = archiving ? t('transport.carriers.action.archive') : t('transport.carriers.action.restore')
confirmArchive.open = true
}
async function runToggleArchive(): Promise<void> {
const archiving = !isArchived.value
confirmArchive.open = false
try {
await (archiving ? archive() : restore())
toast.success({
title: archiving
? t('transport.carriers.toast.archiveSuccess')
: t('transport.carriers.toast.restoreSuccess'),
})
}
catch (err) {
// Surface le message back (ex. 409 « homonyme actif » à la restauration),
// propagé exprès par useCarrier ; fallback générique sinon.
const data = (err as { response?: { _data?: unknown } })?.response?._data
toast.error({
title: t('transport.carriers.toast.error'),
message: extractApiErrorMessage(data) || undefined,
})
}
}
onMounted(load)
</script>
+218 -254
View File
@@ -20,22 +20,28 @@
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
<MalioInputText
v-model="main.name"
:mask="FREE_TEXT_MASK"
:label="t('transport.carriers.form.main.name')"
:required="true"
:readonly="mainLocked"
:disabled="mainLocked"
:error="mainErrors.errors.name"
/>
<!-- Cas LIOT : seul le champ immatriculations est pertinent. -->
<MalioInputText
v-if="isLiot"
v-model="main.liotPlates"
:label="t('transport.carriers.form.main.liotPlates')"
:hint="t('transport.carriers.form.main.liotPlatesHint')"
:required="true"
:readonly="mainLocked"
:error="mainErrors.errors.liotPlates"
/>
<!-- Cas LIOT : seul le champ immatriculations est pertinent. Il occupe
les colonnes restantes de la ligne (3 en xl, 2 sinon) le wrapper
porte le col-span car MalioInputText (inheritAttrs:false) renvoie
`class` sur l'input interne, pas sur la cellule de grille. -->
<div v-if="isLiot" class="col-span-2 xl:col-span-3">
<MalioInputText
v-model="main.liotPlates"
:mask="LIOT_PLATES_MASK"
:label="t('transport.carriers.form.main.liotPlates')"
:hint="t('transport.carriers.form.main.liotPlatesHint')"
:required="true"
:disabled="mainLocked"
:error="mainErrors.errors.liotPlates"
/>
</div>
<!-- Cas standard : certification + affretement + champs conditionnels. -->
<template v-if="!isLiot">
@@ -45,7 +51,7 @@
:label="t('transport.carriers.form.main.certificationType')"
empty-option-label=""
:required="true"
:readonly="certificationReadonly"
:disabled="certificationReadonly"
:error="mainErrors.errors.certificationType"
@update:model-value="(v: string | number | null) => main.certificationType = v === null ? null : String(v)"
/>
@@ -53,18 +59,20 @@
<!-- Colonne 3 RÉSERVÉE à la Décharge (RG-4.02 : visible et obligatoire
si certification AUTRE). Si elle n'apparaît pas, on garde la colonne
vide (xl) pour qu'« Affréter » reste en colonne 4 de la ligne 1.
L'upload reel (File IRI via useUpload) arrive a ERP-171. -->
<!-- TODO ERP-171 : brancher useUpload pour resoudre le File en IRI
(main.dischargeDocumentIri). Le champ est deja visible/obligatoire. -->
Upload DIFFÉRÉ (ERP-171) : le fichier choisi est mis en attente
et envoyé seulement à la validation du formulaire. -->
<MalioInputUpload
v-if="showDischarge"
:model-value="dischargeFileName"
:label="t('transport.carriers.form.main.discharge')"
accept="application/pdf,image/*"
:required="true"
:readonly="mainLocked"
:disabled="mainLocked || dischargeUploading"
:clearable="true"
:error="mainErrors.errors.dischargeDocument"
@clear="main.dischargeDocumentIri = null"
@update:model-value="(v: string) => dischargeFileName = v"
@file-selected="selectDischarge"
@clear="onClearDischarge"
/>
<div v-else class="hidden xl:block"></div>
@@ -76,7 +84,7 @@
id="carrier-is-chartered"
:label="t('transport.carriers.form.main.isChartered')"
:model-value="main.isChartered"
:readonly="mainLocked"
:disabled="mainLocked"
:reserve-message-space="false"
@update:model-value="(val: boolean) => main.isChartered = val"
/>
@@ -86,32 +94,55 @@
« Affreter ». La ligne 1 étant pleine (4 colonnes), ils démarrent
naturellement en colonne 1 de la ligne 2. -->
<template v-if="showCharteredFields">
<MalioInputNumber
v-model="main.indexationRate"
<!-- Indexation : montant en % (icône à droite), plafonné à 100. La
:key force le -affichage du champ contrôlé quand on plafonne
(sinon le modelValue inchangé n'est pas re-synchronisé par Vue). -->
<MalioInputAmount
:key="indexationKey"
:model-value="main.indexationRate"
:label="t('transport.carriers.form.main.indexationRate')"
icon-name="mdi:percent"
icon-position="right"
:required="true"
:readonly="mainLocked"
:disabled="mainLocked"
:error="mainErrors.errors.indexationRate"
@update:model-value="onIndexationInput"
/>
<!-- Contenant : Benne / Fond mouvant (RG-4.03). -->
<MalioSelect
:model-value="main.containerType"
:options="containerOptions"
:label="t('transport.carriers.form.main.containerType')"
empty-option-label=""
:required="true"
:readonly="mainLocked"
:error="mainErrors.errors.containerType"
@update:model-value="(v: string | number | null) => main.containerType = v === null ? null : String(v)"
/>
<!-- Contenant : Benne / Fond mouvant en radios, centrés (h-12) comme
à l'onglet Prix (Benne par défaut). -->
<div>
<div class="flex h-12 items-center gap-4">
<MalioRadioButton
:model-value="main.containerType"
name="carrier-main-container"
value="BENNE"
:label="t('transport.carriers.containerType.BENNE')"
:disabled="mainLocked"
group-class="mt-0"
@update:model-value="(v: string | number | boolean | null) => main.containerType = v === null ? null : String(v)"
/>
<MalioRadioButton
:model-value="main.containerType"
name="carrier-main-container"
value="FOND_MOUVANT"
:label="t('transport.carriers.containerType.FOND_MOUVANT')"
:disabled="mainLocked"
group-class="mt-0"
@update:model-value="(v: string | number | boolean | null) => main.containerType = v === null ? null : String(v)"
/>
</div>
<p v-if="mainErrors.errors.containerType" class="ml-[2px] text-xs text-m-danger">{{ mainErrors.errors.containerType }}</p>
</div>
<MalioInputNumber
v-model="main.volumeM3"
<!-- Volume : champ texte restreint aux nombres à décimales (point). -->
<MalioInputText
:model-value="main.volumeM3"
:label="t('transport.carriers.form.main.volumeM3')"
:required="true"
:readonly="mainLocked"
:disabled="mainLocked"
:error="mainErrors.errors.volumeM3"
@update:model-value="(v: string) => main.volumeM3 = sanitizeDecimal(v)"
/>
</template>
</template>
@@ -131,72 +162,32 @@
assistee (table de selection) ; Adresses / Contacts / Prix arrivent aux
tickets suivants (placeholders « A venir »). -->
<MalioTabList v-model="activeTab" :tabs="tabs" class="mt-[60px]">
<!-- Onglet Qualimat : datatable paginé filtré par le NOM du transporteur
(pas de champ de recherche dédié RG-4.01 / 4.04). -->
<!-- Onglet Qualimat : saisie assistée (recherche par nom). Composant
mutualisé avec l'écran de modification (ERP-172). -->
<template #qualimat>
<div class="mt-12 flex flex-col gap-6">
<MalioDataTable
:columns="qualimatColumns"
:items="qualimatRows"
:total-items="qualimatTotalDisplay"
:page="qualimatPage"
:per-page="qualimatPerPage"
:per-page-options="qualimatPerPageOptions"
row-clickable
:empty-message="qualimatEmptyMessage"
@row-click="onQualimatRowClick"
@update:page="qualimatGoToPage"
@update:per-page="qualimatSetPerPage"
>
<!-- Radio reflétant la ligne QUALIMAT intégrée (lecture). -->
<template #cell-select="{ item }">
<MalioRadioButton
:model-value="main.qualimatCarrierIri"
name="qualimat-row"
:value="item.iri"
group-class="mt-0"
/>
</template>
<!-- Date de validité : fond rouge si périmée (RG-4.04). -->
<template #cell-validityDate="{ item }">
<span
v-if="item.validityDate"
:class="isExpired(item.validityDate as string) ? 'inline-block rounded px-2 py-0.5 bg-m-danger text-white' : ''"
>
{{ formatDateFr(item.validityDate as string) }}
</span>
</template>
</MalioDataTable>
</div>
<CarrierQualimatTab
:search-name="main.name"
:selected-iri="main.qualimatCarrierIri"
@integrate="onIntegrateQualimat"
/>
</template>
<!-- Onglet Adresses (ERP-167) : un bloc par adresse + BAN. RG-4.05
préremplissage si QUALIMAT ; RG-4.07 pas de Valider si QUALIMAT. -->
<template #addresses>
<div class="mt-12 flex flex-col gap-6">
<!-- Adresse UNIQUE (ERP-172) : un seul bloc, sans ajouter/supprimer. -->
<CarrierAddressBlock
v-for="(address, index) in addresses"
:key="index"
:model-value="address"
:country-options="countryOptions"
:removable="isRowRemovable(addresses, index)"
:readonly="isQualimat || isValidated('addresses')"
:errors="addressErrors[index]"
@update:model-value="(v) => addresses[index] = v"
@remove="askRemoveAddress(index)"
:disabled="isQualimat || isValidated('addresses')"
:errors="addressErrors"
@update:model-value="(v) => address = v"
@degraded="onAddressDegraded"
/>
<!-- RG-4.07 : pas de bouton Valider pour un transporteur QUALIMAT
(adresse copiée et persistée automatiquement). -->
<div v-if="!isQualimat && !isValidated('addresses')" class="flex justify-center gap-6">
<MalioButton
variant="secondary"
icon-name="mdi:add-bold"
icon-position="left"
:label="t('transport.carriers.form.address.add')"
:disabled="!canAddAddress"
@click="addAddress"
/>
<MalioButton
variant="primary"
:label="t('transport.carriers.form.submit')"
@@ -207,8 +198,8 @@
</div>
</template>
<!-- Onglet Contacts (ERP-168) : un bloc par contact (RG-4.08 1 champ,
max 2 téléphones). Erreurs 422 par ligne. -->
<!-- Onglet Contacts (ERP-168) : un bloc par contact (bloc optionnel,
ERP-193 ; max 2 téléphones). Erreurs 422 par ligne. -->
<template #contacts>
<div class="mt-12 flex flex-col gap-6">
<CarrierContactBlock
@@ -216,7 +207,7 @@
:key="index"
:model-value="contact"
:removable="isRowRemovable(contacts, index)"
:readonly="isValidated('contacts')"
:disabled="isValidated('contacts')"
:errors="contactErrors[index]"
@update:model-value="(v) => contacts[index] = v"
@remove="askRemoveContact(index)"
@@ -240,7 +231,43 @@
</div>
</template>
<!-- Prix : contenu au ticket suivant. -->
<!-- Onglet Prix (ERP-169) : blocs multiples, branche CLIENT/FOURNISSEUR
(RG-4.094.11). Démarre vide ; l'utilisateur ajoute via « + Nouveau prix ». -->
<template #prices>
<div class="mt-12 flex flex-col gap-6">
<CarrierPriceBlock
v-for="(price, index) in prices"
:key="index"
:model-value="price"
:client-options="clientOptions"
:supplier-options="supplierOptions"
:site-options="siteOptions"
:removable="!isValidated('prices')"
:disabled="isValidated('prices')"
:errors="priceErrors[index]"
@update:model-value="(v) => prices[index] = v"
@remove="askRemovePrice(index)"
/>
<div v-if="!isValidated('prices')" class="flex justify-center gap-6">
<MalioButton
variant="secondary"
icon-name="mdi:add-bold"
icon-position="left"
:label="t('transport.carriers.form.price.add')"
:disabled="!canAddPrice"
@click="addPrice"
/>
<MalioButton
variant="primary"
:label="t('transport.carriers.form.submit')"
:disabled="tabSubmitting || carrierId === null"
@click="onSubmitPrices"
/>
</div>
</div>
</template>
<!-- Plus d'onglet placeholder : tous les onglets ont leur contenu. -->
<template
v-for="key in placeholderTabs"
:key="key"
@@ -252,29 +279,7 @@
</template>
</MalioTabList>
<!-- Modal de confirmation d'integration QUALIMAT (RG-4.01). -->
<MalioModal v-model="confirmOpen" modal-class="max-w-md">
<template #header>
<h2 class="text-[24px] font-bold">{{ t('transport.carriers.form.qualimat.confirm.title') }}</h2>
</template>
<p>{{ t('transport.carriers.form.qualimat.confirm.message') }}</p>
<template #footer>
<MalioButton
variant="secondary"
button-class="flex-1"
:label="t('transport.carriers.form.qualimat.confirm.cancel')"
@click="confirmOpen = false"
/>
<MalioButton
variant="primary"
button-class="flex-1"
:label="t('transport.carriers.form.qualimat.confirm.confirm')"
@click="confirmIntegrate"
/>
</template>
</MalioModal>
<!-- Modal de confirmation de suppression (bloc adresse). -->
<!-- Modal de confirmation de suppression (bloc contact / prix). -->
<MalioModal v-model="deleteConfirm.open" modal-class="max-w-md">
<template #header>
<h2 class="text-[24px] font-bold">{{ t('transport.carriers.form.confirmDelete.title') }}</h2>
@@ -299,14 +304,17 @@
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { debounce } from '~/shared/utils/debounce'
import { computed, onMounted, reactive, ref } from 'vue'
import { extractApiErrorMessage } from '~/shared/utils/api'
import { isRowRemovable } from '~/shared/utils/collectionRow'
import CarrierAddressBlock from '~/modules/transport/components/CarrierAddressBlock.vue'
import CarrierContactBlock from '~/modules/transport/components/CarrierContactBlock.vue'
import CarrierPriceBlock from '~/modules/transport/components/CarrierPriceBlock.vue'
import CarrierQualimatTab from '~/modules/transport/components/CarrierQualimatTab.vue'
import { useCarrierForm } from '~/modules/transport/composables/useCarrierForm'
import { useQualimatSearch, type QualimatCarrierRow } from '~/modules/transport/composables/useQualimatSearch'
import type { QualimatCarrierRow } from '~/modules/transport/composables/useQualimatSearch'
import { clampPercent, LIOT_PLATES_MASK, sanitizeDecimal } from '~/modules/transport/utils/forms/numberInput'
import { FREE_TEXT_MASK } from '~/shared/utils/textSanitize'
interface SelectOption {
value: string
@@ -334,6 +342,9 @@ const {
mainSubmitting,
tabSubmitting,
mainErrors,
dischargeUploading,
selectDischarge,
clearDischarge,
isLiot,
isQualimat,
certificationReadonly,
@@ -343,32 +354,33 @@ const {
activeTab,
unlockedIndex,
isValidated,
addresses,
address,
addressErrors,
canAddAddress,
addAddress,
removeAddress,
submitAddresses,
submitAddress,
contacts,
contactErrors,
canAddContact,
addContact,
removeContact,
submitContacts,
prices,
priceErrors,
canAddPrice,
addPrice,
removePrice,
submitPrices,
submitMain,
applyQualimatSelection,
} = useCarrierForm()
const {
items: qualimatItems,
totalItems: qualimatTotal,
currentPage: qualimatPage,
itemsPerPage: qualimatPerPage,
itemsPerPageOptions: qualimatPerPageOptions,
goToPage: qualimatGoToPage,
setItemsPerPage: qualimatSetPerPage,
setFilters: qualimatSetFilters,
} = useQualimatSearch()
// Nom de fichier affiché dans le champ Décharge (alimenté à la sélection).
const dischargeFileName = ref('')
/** Vidage du champ Décharge : oublie le fichier en attente / l'IRI + le nom affiché. */
function onClearDischarge(): void {
clearDischarge()
dischargeFileName.value = ''
}
// Certifications selectionnables manuellement (spec § Formulaire principal) :
// GMP+ / OVOCOM / Compte-propre / Autre. QUALIMAT n'y figure PAS il est posé par
@@ -388,55 +400,12 @@ const certificationOptions = computed<SelectOption[]>(() => {
}))
})
// Colonnes du datatable de selection QUALIMAT (radio / Nom / Adresse / Validite).
const qualimatColumns = [
{ key: 'select', label: '' },
{ key: 'name', label: t('transport.carriers.form.qualimat.columns.name') },
{ key: 'address', label: t('transport.carriers.form.qualimat.columns.address') },
{ key: 'validityDate', label: t('transport.carriers.form.qualimat.columns.validityDate') },
]
// Le datatable n'affiche QUE des résultats de recherche : vide tant que le Nom n'est
// pas saisi (pas de liste complète par défaut). `main.name` pilote l'affichage.
const hasQualimatSearch = computed(() => main.name.trim() !== '')
// Lignes « plates » pour MalioDataTable (l'IRI sert au radio + à retrouver la ligne
// source au clic). Le détail QUALIMAT complet reste dans `qualimatItems`.
const qualimatRows = computed(() => {
if (!hasQualimatSearch.value) {
return []
}
return qualimatItems.value.map(row => ({
id: row.id,
iri: row['@id'],
name: row.name,
address: formatQualimatAddress(row),
validityDate: row.validityDate,
}))
})
// Total / message vide alignés sur « tableau vide tant qu'on n'a pas recherché ».
const qualimatTotalDisplay = computed(() => (hasQualimatSearch.value ? qualimatTotal.value : 0))
const qualimatEmptyMessage = computed(() => hasQualimatSearch.value
? t('transport.carriers.form.qualimat.empty')
: t('transport.carriers.form.qualimat.searchHint'))
// Contenant (RG-4.03) : Benne / Fond mouvant select simple.
const CONTAINER_TYPES = ['BENNE', 'FOND_MOUVANT'] as const
const containerOptions = computed<SelectOption[]>(() =>
CONTAINER_TYPES.map(code => ({
value: code,
label: t(`transport.carriers.containerType.${code}`),
})),
)
// Icone (Iconify) affichee dans chaque onglet, par cle.
const TAB_ICONS: Record<string, string> = {
qualimat: 'mdi:truck-check-outline',
qualimat: 'mdi:truck-fast-outline',
addresses: 'mdi:map-marker-outline',
contacts: 'mdi:account-box-plus-outline',
prices: 'mdi:currency-eur',
prices: 'mdi:payment',
}
// Onglets desactives tant que le formulaire principal n'est pas valide
@@ -448,11 +417,42 @@ const tabs = computed(() => tabKeys.value.map((key, index) => ({
disabled: index > unlockedIndex.value,
})))
// Onglets dont le contenu arrive aux tickets suivants (Prix).
// Tous les onglets ont désormais leur contenu (qualimat / addresses / contacts / prices).
const placeholderTabs = computed(() => tabKeys.value.filter(
key => key !== 'qualimat' && key !== 'addresses' && key !== 'contacts',
key => key !== 'qualimat' && key !== 'addresses' && key !== 'contacts' && key !== 'prices',
))
// Référentiels de l'onglet Prix (clients / fournisseurs / sites)
const clientOptions = ref<SelectOption[]>([])
const supplierOptions = ref<SelectOption[]>([])
const siteOptions = ref<SelectOption[]>([])
/** Charge un référentiel paginé (?pagination=false) et mappe en options { IRI, libellé }. */
async function loadOptions(
url: string,
target: typeof clientOptions,
labelOf: (m: Record<string, unknown>) => string,
): Promise<void> {
try {
const data = await api.get<{ member?: Record<string, unknown>[] }>(
url,
{ pagination: 'false' },
{ headers: { Accept: 'application/ld+json' }, toast: false },
)
target.value = (data.member ?? []).map(m => ({ value: String(m['@id']), label: labelOf(m) }))
}
catch {
target.value = []
}
}
/** Charge les référentiels de l'onglet Prix (non bloquant : selects vides si échec). */
function loadPriceReferentials(): void {
void loadOptions('/clients', clientOptions, m => String(m.companyName ?? m['@id']))
void loadOptions('/suppliers', supplierOptions, m => String(m.companyName ?? m['@id']))
void loadOptions('/sites', siteOptions, m => String(m.name ?? m['@id']))
}
// Onglet Adresses (ERP-167)
// Pays : France garantie en tete meme si /countries echoue (resilience), pour
// rester preselectionnable par defaut sur chaque adresse (RG-4.05).
@@ -478,6 +478,7 @@ async function loadCountries(): Promise<void> {
onMounted(() => {
loadCountries().catch(() => {})
loadPriceReferentials()
})
// Avertissement unique quand l'autocompletion d'adresse bascule en degrade.
@@ -502,7 +503,7 @@ function apiErrorMessage(error: unknown): string {
/** Valide l'onglet Adresses (POST/PATCH par ligne ; avance gere par le composable). */
async function onSubmitAddresses(): Promise<void> {
const ok = await submitAddresses(error => toast.error({
const ok = await submitAddress(error => toast.error({
title: t('transport.carriers.toast.error'),
message: apiErrorMessage(error),
}))
@@ -511,14 +512,9 @@ async function onSubmitAddresses(): Promise<void> {
}
}
// Modal de confirmation de suppression (générique : bloc adresse OU contact).
// Modal de confirmation de suppression (générique : bloc contact OU prix).
const deleteConfirm = reactive({ open: false, action: null as null | (() => void) })
function askRemoveAddress(index: number): void {
deleteConfirm.action = () => { void removeAddress(index) }
deleteConfirm.open = true
}
/** Valide l'onglet Contacts (POST/PATCH par ligne ; avance gérée par le composable). */
async function onSubmitContacts(): Promise<void> {
const ok = await submitContacts(error => toast.error({
@@ -535,86 +531,54 @@ function askRemoveContact(index: number): void {
deleteConfirm.open = true
}
/**
* Valide l'onglet Prix = DERNIER onglet du flux de création. Au succès, l'ajout est
* terminé : toast final + retour au répertoire transporteurs (aligné sur M1/M2/M3).
*/
async function onSubmitPrices(): Promise<void> {
const ok = await submitPrices(error => toast.error({
title: t('transport.carriers.toast.error'),
message: apiErrorMessage(error),
}))
if (ok) {
toast.success({ title: t('transport.carriers.toast.priceSaved') })
await navigateTo('/carriers')
}
}
function askRemovePrice(index: number): void {
deleteConfirm.action = () => { void removePrice(index) }
deleteConfirm.open = true
}
function runDeleteConfirm(): void {
deleteConfirm.action?.()
deleteConfirm.action = null
deleteConfirm.open = false
}
// Saisie assistee QUALIMAT (onglet Qualimat)
const confirmOpen = ref(false)
const pendingRow = ref<QualimatCarrierRow | null>(null)
// Le datatable QUALIMAT est filtré par le NOM saisi dans le formulaire principal
// (RG-4.01) pas de champ de recherche dédié. Aucune recherche tant que le Nom est
// vide (tableau vide par défaut) ; sinon re-filtrage debouncé à chaque frappe.
const filterQualimatByName = debounce((term: string) => {
if (term.trim() === '') {
return
}
void qualimatSetFilters({ search: term })
}, 300)
watch(() => main.name, term => filterQualimatByName(term))
/** Adresse QUALIMAT condensee pour la colonne « Adresse » (voie · CP · ville). */
function formatQualimatAddress(row: QualimatCarrierRow): string {
return [row.address, row.postalCode, row.city].filter(Boolean).join(' · ')
}
/** RG-4.04 : un agrement est perime si sa date de validite est < aujourd'hui. */
function isExpired(value: string): boolean {
const date = new Date(value)
if (Number.isNaN(date.getTime())) {
return false
}
const today = new Date()
today.setHours(0, 0, 0, 0)
date.setHours(0, 0, 0, 0)
return date.getTime() < today.getTime()
}
/** Format court francais JJ-MM-AAAA (chaine vide si date absente / invalide). */
function formatDateFr(value: string | null | undefined): string {
if (!value) {
return ''
}
const date = new Date(value)
if (Number.isNaN(date.getTime())) {
return ''
}
const day = String(date.getDate()).padStart(2, '0')
const month = String(date.getMonth() + 1).padStart(2, '0')
return `${day}-${month}-${date.getFullYear()}`
}
/** Clic sur une ligne du datatable → retrouve la ligne QUALIMAT source + modal. */
function onQualimatRowClick(item: Record<string, unknown>): void {
const row = qualimatItems.value.find(r => r.id === item.id)
if (row) {
askIntegrate(row)
}
}
/** Ouvre la modal de confirmation d'integration pour une ligne QUALIMAT. */
function askIntegrate(row: QualimatCarrierRow): void {
pendingRow.value = row
confirmOpen.value = true
}
/** Confirme l'integration : copie + PATCH (cf. useCarrierForm.applyQualimatSelection). */
async function confirmIntegrate(): Promise<void> {
const row = pendingRow.value
confirmOpen.value = false
if (row === null) {
return
}
/** Intégration d'une ligne QUALIMAT (émise par CarrierQualimatTab) : copie + PATCH
* (cf. useCarrierForm.applyQualimatSelection). */
async function onIntegrateQualimat(row: QualimatCarrierRow): Promise<void> {
const ok = await applyQualimatSelection(row)
if (ok) {
toast.success({ title: t('transport.carriers.toast.integrateSuccess') })
}
}
// Indexation plafonnée à 100 % : la clé force le ré-affichage du MalioInputAmount
// (contrôlé) quand le plafonnement laisse le modelValue inchangé.
const indexationKey = ref(0)
/** Saisie de l'indexation : plafonne à 100 et re-synchronise le champ si plafonné. */
function onIndexationInput(value: string): void {
const clamped = clampPercent(value)
main.indexationRate = clamped
if (clamped !== value) {
indexationKey.value += 1
}
}
/** Retour vers le repertoire transporteurs (fleche d'en-tete). */
function goBack(): void {
router.push('/carriers')
@@ -628,7 +592,7 @@ function goBack(): void {
async function onSubmitMain(): Promise<void> {
const ok = await submitMain()
if (ok && isQualimat.value) {
await submitAddresses(error => toast.error({
await submitAddress(error => toast.error({
title: t('transport.carriers.toast.error'),
message: apiErrorMessage(error),
}))
@@ -40,7 +40,8 @@ export function emptyCarrierMain(): CarrierMainDraft {
certificationType: null,
isChartered: false,
indexationRate: '',
containerType: null,
// Défaut métier : Benne pré-sélectionné (radio du formulaire principal).
containerType: 'BENNE',
volumeM3: '',
liotPlates: '',
dischargeDocumentIri: null,
@@ -129,6 +130,51 @@ export function emptyCarrierContact(): CarrierContactFormDraft {
}
}
/**
* Brouillon d'un bloc Prix (onglet Prix, ERP-169 RG-4.094.11). `direction`
* pilote la branche active : CLIENT (client + adresse de livraison + site de
* départ) ou FOURNISSEUR (fournisseur + adresse d'appro + site de livraison). Les
* relations partent au back en IRI (string). `price` est une chaîne (MalioInputAmount).
*/
export interface CarrierPriceFormDraft {
id: number | null
direction: 'CLIENT' | 'FOURNISSEUR' | null
// Branche CLIENT (RG-4.10).
clientIri: string | null
clientDeliveryAddressIri: string | null
departureSiteIri: string | null
// Branche FOURNISSEUR (RG-4.11).
supplierIri: string | null
supplierSupplyAddressIri: string | null
deliverySiteIri: string | null
// Communs (toujours requis).
containerType: string | null
pricingUnit: string | null
price: string | null
priceState: string | null
}
/** Brouillon de prix vide (état initial d'un bloc Prix : tout masqué tant que direction null). */
export function emptyCarrierPrice(): CarrierPriceFormDraft {
return {
id: null,
// Défaut métier : sens CLIENT pré-sélectionné (un bloc prix CLIENT est présent
// d'office à l'ouverture de l'onglet).
direction: 'CLIENT',
clientIri: null,
clientDeliveryAddressIri: null,
departureSiteIri: null,
supplierIri: null,
supplierSupplyAddressIri: null,
deliverySiteIri: null,
// Défauts métier : Benne + Forfait pré-sélectionnés à l'ajout d'un bloc prix.
containerType: 'BENNE',
pricingUnit: 'FORFAIT',
price: null,
priceState: null,
}
}
/**
* Réponse du POST / PATCH principal (groupe `carrier:read`). Le serveur renvoie
* le nom normalisé (UPPERCASE, RG-4.13) que l'UI réaffiche tel quel.
@@ -0,0 +1,170 @@
import { describe, it, expect } from 'vitest'
import {
canEditCarrier,
carrierConsultationVisibleTabs,
hasAddressData,
iriOf,
labelOfRelation,
mapAddressToDraft,
mapContactToDraft,
mapMainToDraft,
mapPriceToDraft,
showArchiveAction,
showRestoreAction,
type CarrierDetail,
} from '../carrierMappers'
/**
* Tests des mappers détail brouillons (M4 Transport, ERP-170) : peuplent les écrans
* Consultation / Modification depuis la SEULE réponse `GET /api/carriers/{id}`, et
* helpers de visibilité des boutons (Modifier / Archiver / Restaurer) selon la permission.
*/
describe('carrierMappers', () => {
it('iriOf : objet embarqué, IRI nu, ou null', () => {
expect(iriOf({ '@id': '/api/clients/3' })).toBe('/api/clients/3')
expect(iriOf('/api/sites/1')).toBe('/api/sites/1')
expect(iriOf(null)).toBeNull()
expect(iriOf(undefined)).toBeNull()
})
it('labelOfRelation : companyName (client/fournisseur) prioritaire sur name/adresse', () => {
expect(labelOfRelation({ '@id': '/api/suppliers/8', companyName: 'AAAAAAA', name: 'X' })).toBe('AAAAAAA')
})
it('labelOfRelation : name (site) à défaut adresse condensée', () => {
expect(labelOfRelation({ '@id': '/api/sites/1', name: 'Châtellerault' })).toBe('Châtellerault')
expect(labelOfRelation({ '@id': '/api/client_addresses/8', street: '1 rue X', postalCode: '86000', city: 'Poitiers' })).toBe('1 rue X · 86000 · Poitiers')
expect(labelOfRelation('/api/sites/1')).toBe('')
expect(labelOfRelation(null)).toBe('')
})
it('mapMainToDraft : scalaires + IRI décharge / qualimat', () => {
const detail: CarrierDetail = {
'@id': '/api/carriers/7',
id: 7,
name: 'TRANSPORTS ACME',
certificationType: 'QUALIMAT',
isChartered: true,
indexationRate: '5.00',
containerType: 'BENNE',
volumeM3: '30.00',
dischargeDocument: { '@id': '/api/uploaded_documents/4' },
qualimatCarrier: { '@id': '/api/qualimat_carriers/42' },
}
expect(mapMainToDraft(detail)).toEqual({
name: 'TRANSPORTS ACME',
certificationType: 'QUALIMAT',
isChartered: true,
indexationRate: '5.00',
containerType: 'BENNE',
volumeM3: '30.00',
liotPlates: '',
dischargeDocumentIri: '/api/uploaded_documents/4',
qualimatCarrierIri: '/api/qualimat_carriers/42',
})
})
it('mapAddressToDraft : pays par défaut France si absent', () => {
expect(mapAddressToDraft({ '@id': '/api/carrier_addresses/3', id: 3, postalCode: '86000', city: 'Poitiers' }))
.toEqual({ id: 3, country: 'France', postalCode: '86000', city: 'Poitiers', street: null, streetComplement: null })
})
it('mapContactToDraft : hasSecondaryPhone vrai seulement si 2e numéro présent', () => {
const one = mapContactToDraft({ '@id': '/api/carrier_contacts/1', id: 1, firstName: 'Jean', phonePrimary: '0102030405' })
expect(one.hasSecondaryPhone).toBe(false)
expect(one.firstName).toBe('Jean')
const two = mapContactToDraft({ '@id': '/api/carrier_contacts/2', id: 2, phonePrimary: '0102030405', phoneSecondary: '0605040302' })
expect(two.hasSecondaryPhone).toBe(true)
expect(two.phoneSecondary).toBeTruthy()
})
it('mapPriceToDraft : direction + IRIs des relations de branche', () => {
const draft = mapPriceToDraft({
'@id': '/api/carrier_prices/5',
id: 5,
direction: 'CLIENT',
client: { '@id': '/api/clients/3' },
clientDeliveryAddress: { '@id': '/api/client_addresses/8' },
departureSite: '/api/sites/1',
containerType: 'BENNE',
pricingUnit: 'FORFAIT',
price: '120.00',
priceState: 'EN_COURS',
})
expect(draft).toMatchObject({
id: 5,
direction: 'CLIENT',
clientIri: '/api/clients/3',
clientDeliveryAddressIri: '/api/client_addresses/8',
departureSiteIri: '/api/sites/1',
supplierIri: null,
containerType: 'BENNE',
pricingUnit: 'FORFAIT',
price: '120.00',
priceState: 'EN_COURS',
})
})
it('visibilité des boutons selon la permission', () => {
const can = (granted: string[]) => (code: string) => granted.includes(code)
// Modifier : seulement avec manage.
expect(canEditCarrier(can(['transport.carriers.manage']))).toBe(true)
expect(canEditCarrier(can(['transport.carriers.view']))).toBe(false)
// Archiver : permission archive ET actif ; Restaurer : archive ET archivé.
const withArchive = can(['transport.carriers.archive'])
const noArchive = can(['transport.carriers.manage'])
expect(showArchiveAction(withArchive, false)).toBe(true)
expect(showArchiveAction(withArchive, true)).toBe(false)
expect(showRestoreAction(withArchive, true)).toBe(true)
expect(showRestoreAction(withArchive, false)).toBe(false)
expect(showArchiveAction(noArchive, false)).toBe(false)
expect(showRestoreAction(noArchive, true)).toBe(false)
})
})
describe('hasAddressData', () => {
it('faux pour une adresse absente ou entièrement vide', () => {
expect(hasAddressData(null)).toBe(false)
expect(hasAddressData(undefined)).toBe(false)
expect(hasAddressData({ '@id': '/api/carrier_addresses/1', id: 1 })).toBe(false)
})
it('vrai dès qu\'un champ adresse est rempli', () => {
expect(hasAddressData({ '@id': '/api/carrier_addresses/1', id: 1, city: 'Poitiers' })).toBe(true)
expect(hasAddressData({ '@id': '/api/carrier_addresses/1', id: 1, country: 'France' })).toBe(true)
})
})
describe('carrierConsultationVisibleTabs', () => {
it('retourne [] tant que le transporteur n\'est pas chargé', () => {
expect(carrierConsultationVisibleTabs(null)).toEqual([])
expect(carrierConsultationVisibleTabs(undefined)).toEqual([])
})
it('masque les onglets vides (transporteur minimal)', () => {
expect(carrierConsultationVisibleTabs({ '@id': '/api/carriers/1', id: 1, name: 'LIOT' })).toEqual([])
})
it('affiche addresses/contacts/prices dans l\'ordre quand renseignés', () => {
const carrier: CarrierDetail = {
'@id': '/api/carriers/1', id: 1,
address: { '@id': '/api/carrier_addresses/1', id: 1, city: 'Poitiers' },
contacts: [{ '@id': '/api/carrier_contacts/1', id: 1 }],
prices: [{ '@id': '/api/carrier_prices/1', id: 1 }],
}
expect(carrierConsultationVisibleTabs(carrier)).toEqual(['addresses', 'contacts', 'prices'])
})
it('ne garde que les onglets non vides (contacts seulement)', () => {
const carrier: CarrierDetail = {
'@id': '/api/carriers/1', id: 1,
address: { '@id': '/api/carrier_addresses/1', id: 1 },
contacts: [{ '@id': '/api/carrier_contacts/1', id: 1 }],
prices: [],
}
expect(carrierConsultationVisibleTabs(carrier)).toEqual(['contacts'])
})
})
@@ -0,0 +1,33 @@
import { describe, expect, it } from 'vitest'
import { Mask } from 'maska'
import { clampPercent, LIOT_PLATES_MASK, sanitizeDecimal } from '../numberInput'
describe('numberInput — saisie volume / indexation (ERP-170)', () => {
it('sanitizeDecimal : ne garde que chiffres + un seul point', () => {
expect(sanitizeDecimal('30')).toBe('30')
expect(sanitizeDecimal('30.5')).toBe('30.5')
expect(sanitizeDecimal('30,5 kg')).toBe('30.5') // virgule FR → point ; espace + lettres retirés
expect(sanitizeDecimal('1.2.3')).toBe('1.23') // un seul point conservé
expect(sanitizeDecimal('abc12.3x')).toBe('12.3')
expect(sanitizeDecimal('')).toBe('')
})
it('clampPercent : plafonne à 100, laisse le reste tel quel', () => {
expect(clampPercent('50')).toBe('50')
expect(clampPercent('100')).toBe('100')
expect(clampPercent('150')).toBe('100')
expect(clampPercent('100.01')).toBe('100')
expect(clampPercent('12,5')).toBe('12,5') // ≤ 100 → inchangé
expect(clampPercent('')).toBe('')
})
it('LIOT_PLATES_MASK : garde lettres/chiffres/tiret/point-virgule, bloque espaces et reste', () => {
// Reproduit ce que fait maska au runtime (MaskInput) : preProcess puis masked.
const masked = (v: string) => new Mask(LIOT_PLATES_MASK).masked(LIOT_PLATES_MASK.preProcess!(v))
expect(masked('AB-123-CD;EF-456-GH')).toBe('AB-123-CD;EF-456-GH')
expect(masked('ab-123-cd ; ef-456-gh')).toBe('ab-123-cd;ef-456-gh') // espaces retirés
expect(masked('AB 123 CD')).toBe('AB123CD') // espaces retirés
expect(masked('AB.123/CD#42&²²')).toBe('AB123CD42') // . / # & ² retirés
expect(masked('')).toBe('')
})
})
@@ -8,18 +8,7 @@
import type { CarrierAddressFormDraft } from '~/modules/transport/types/carrierForm'
/**
* RG-4.05 : gate du bouton « + Nouvelle adresse ». Une adresse est « complète »
* (donc on autorise l'ajout d'un nouveau bloc) dès qu'elle porte un code postal,
* une ville ET une rue. Les RG conditionnelles (obligatoire si affrété) restent
* validées par le back (422 inline) ce gate empêche seulement d'empiler des
* blocs vides.
*/
export function isCarrierAddressValid(address: CarrierAddressFormDraft): boolean {
return Boolean(address.postalCode?.trim() && address.city?.trim() && address.street?.trim())
}
/**
* Payload de la sous-ressource addresses (groupe `carrier:write:addresses`). Les
* Payload de la sous-ressource address (groupe `carrier:write:addresses`). Les
* scalaires sont nullable côté entité : on envoie `null` quand le champ est vide
* (le `CarrierAddressProcessor` re-valide la présence si affrété RG-4.05 et
* renvoie une 422 par champ).
@@ -1,10 +1,10 @@
/**
* Helpers purs de l'onglet Contact transporteur (M4 Transport, ERP-168) ALIGNÉ
* sur `providerContact.ts` (M3) / les autres modules : mêmes règles de validité et
* de gating « + Nouveau contact » (un contact est « nommé » dès qu'il porte un
* prénom OU un nom). Seule spécificité M4 conservée : les téléphones partent au back
* dans le tableau virtuel `phones` (max 2), mappés par le CarrierContactProcessor.
* Testables sans Vue ni API.
* Helpers purs de l'onglet Contact transporteur (M4 Transport, ERP-168). ERP-193
* (retour métier) : l'onglet Contact n'est plus obligatoire la règle « prénom OU
* nom » est retirée. Le gating « + Nouveau contact » repose désormais sur « le
* dernier bloc n'est pas vide » (et non plus « nommé »). Spécificité M4 conservée :
* les téléphones partent au back dans le tableau virtuel `phones` (max 2), mappés
* par le CarrierContactProcessor. Testables sans Vue ni API.
*/
import type { CarrierContactFormDraft } from '~/modules/transport/types/carrierForm'
@@ -30,15 +30,6 @@ export function isCarrierContactBlank(contact: CarrierContactFormDraft): boolean
].some(isFilled)
}
/**
* Un contact est « nommé » (valide) dès qu'il porte un prénom OU un nom aligné
* sur M1/M2/M3. Pilote le gating « + Nouveau contact » : la fonction / le téléphone
* / l'email seuls ne suffisent pas pour ajouter un nouveau bloc.
*/
export function isCarrierContactNamed(contact: CarrierContactFormDraft): boolean {
return isFilled(contact.firstName) || isFilled(contact.lastName)
}
/**
* Payload de la sous-ressource contacts (groupe `carrier:write:contacts`). Les
* chaînes vides partent à null (le serveur normalise/trim). Les téléphones sont
@@ -0,0 +1,252 @@
/**
* Helpers purs des écrans Consultation / Modification transporteur (M4, ERP-170)
* miroir de `providerDetail.ts` (M3). Mappent le payload `GET /api/carriers/{id}`
* (relations embarquées via les groupes `carrier:item:read` + `qualimat:read` +
* read-groups cross-module client/supplier/site/adresses) vers les brouillons
* « plats » partagés avec les blocs Adresse / Contact / Prix.
*
* Ne touchent ni à l'API ni à l'état réactif (testables unitairement). Les champs
* nuls peuvent être OMIS (skip_null_values) toujours lire avec `?? null`.
*/
import { formatPhoneFR } from '~/shared/utils/phone'
import type {
CarrierAddressFormDraft,
CarrierContactFormDraft,
CarrierMainDraft,
CarrierPriceFormDraft,
} from '~/modules/transport/types/carrierForm'
/** Référence Hydra embarquée minimale (@id toujours présent). */
export interface HydraRef {
'@id': string
[key: string]: unknown
}
/** Une relation peut être embarquée (objet), un IRI nu (chaîne) ou absente. */
export type Relation = HydraRef | string | null | undefined
/** Adresse embarquée (groupe carrier:item:read). */
export interface CarrierAddressRead extends HydraRef {
id: number
country?: string | null
postalCode?: string | null
city?: string | null
street?: string | null
streetComplement?: string | null
}
/** Contact embarqué (groupe carrier:item:read). */
export interface CarrierContactRead extends HydraRef {
id: number
firstName?: string | null
lastName?: string | null
jobTitle?: string | null
phonePrimary?: string | null
phoneSecondary?: string | null
email?: string | null
}
/** Prix embarqué (groupe carrier:item:read + relations cross-module). */
export interface CarrierPriceRead extends HydraRef {
id: number
direction?: string | null
client?: Relation
clientDeliveryAddress?: Relation
departureSite?: Relation
supplier?: Relation
supplierSupplyAddress?: Relation
deliverySite?: Relation
containerType?: string | null
pricingUnit?: string | null
price?: string | null
priceState?: string | null
}
/**
* Détail d'un transporteur (`GET /api/carriers/{id}`). Tous les champs optionnels :
* skip_null_values peut omettre n'importe quelle clé.
*/
export interface CarrierDetail extends HydraRef {
id: number
name?: string | null
certificationType?: string | null
isChartered?: boolean
indexationRate?: string | null
containerType?: string | null
volumeM3?: string | null
liotPlates?: string | null
dischargeDocument?: Relation
qualimatCarrier?: Relation
isArchived?: boolean
// Adresse UNIQUE (OneToOne, ERP-172) : objet embarqué (ou absent), pas une liste.
address?: CarrierAddressRead | null
contacts?: CarrierContactRead[]
prices?: CarrierPriceRead[]
}
/** Extrait l'IRI d'une relation (objet embarqué, IRI nu, ou null si absente). */
export function iriOf(relation: Relation): string | null {
if (relation === null || relation === undefined) {
return null
}
if (typeof relation === 'string') {
return relation
}
return relation['@id'] ?? null
}
/**
* Libellé d'affichage d'une relation embarquée : `companyName` (client/fournisseur)
* à défaut `name` (site), à défaut une adresse condensée (voie · CP · ville). Chaîne
* vide si la relation est un IRI nu / absente.
*/
export function labelOfRelation(relation: Relation): string {
if (!relation || typeof relation === 'string') {
return ''
}
const companyName = relation.companyName as string | undefined
if (companyName) {
return companyName
}
const name = relation.name as string | undefined
if (name) {
return name
}
const parts = [relation.street, relation.postalCode, relation.city].filter(Boolean)
return parts.join(' · ')
}
/** Mappe le détail vers le brouillon du formulaire principal. */
export function mapMainToDraft(detail: CarrierDetail): CarrierMainDraft {
return {
name: detail.name ?? '',
certificationType: detail.certificationType ?? null,
isChartered: detail.isChartered ?? false,
indexationRate: detail.indexationRate ?? '',
containerType: detail.containerType ?? null,
volumeM3: detail.volumeM3 ?? '',
liotPlates: detail.liotPlates ?? '',
dischargeDocumentIri: iriOf(detail.dischargeDocument),
qualimatCarrierIri: iriOf(detail.qualimatCarrier),
}
}
/** Mappe une adresse embarquée vers un brouillon. */
export function mapAddressToDraft(address: CarrierAddressRead): CarrierAddressFormDraft {
return {
id: address.id,
country: address.country ?? 'France',
postalCode: address.postalCode ?? null,
city: address.city ?? null,
street: address.street ?? null,
streetComplement: address.streetComplement ?? null,
}
}
/** Mappe un contact embarqué vers un brouillon (téléphones formatés XX XX XX XX XX). */
export function mapContactToDraft(contact: CarrierContactRead): CarrierContactFormDraft {
const secondary = contact.phoneSecondary ?? null
return {
id: contact.id,
firstName: contact.firstName ?? null,
lastName: contact.lastName ?? null,
jobTitle: contact.jobTitle ?? null,
phonePrimary: contact.phonePrimary ? formatPhoneFR(contact.phonePrimary) : null,
phoneSecondary: secondary ? formatPhoneFR(secondary) : null,
email: contact.email ?? null,
hasSecondaryPhone: secondary !== null && secondary !== '',
}
}
/** Mappe un prix embarqué vers un brouillon (relations en IRI). */
export function mapPriceToDraft(price: CarrierPriceRead): CarrierPriceFormDraft {
const direction = price.direction === 'CLIENT' || price.direction === 'FOURNISSEUR'
? price.direction
: null
return {
id: price.id,
direction,
clientIri: iriOf(price.client),
clientDeliveryAddressIri: iriOf(price.clientDeliveryAddress),
departureSiteIri: iriOf(price.departureSite),
supplierIri: iriOf(price.supplier),
supplierSupplyAddressIri: iriOf(price.supplierSupplyAddress),
deliverySiteIri: iriOf(price.deliverySite),
containerType: price.containerType ?? null,
pricingUnit: price.pricingUnit ?? null,
price: price.price ?? null,
priceState: price.priceState ?? null,
}
}
/**
* Vrai si une valeur scalaire porte une donnée affichable (non null/undefined,
* et non chaîne vide après trim). Sert aux prédicats « onglet vide » ci-dessous.
*/
function hasValue(value: unknown): boolean {
if (value === null || value === undefined) {
return false
}
if (typeof value === 'string') {
return value.trim() !== ''
}
return true
}
/**
* Vrai si l'adresse unique (OneToOne, ERP-172) porte au moins un champ rempli.
* Un objet adresse vide (toutes clés nulles) est considéré comme « pas d'adresse ».
*/
export function hasAddressData(address: CarrierAddressRead | null | undefined): boolean {
if (!address) {
return false
}
return [
address.postalCode,
address.city,
address.street,
address.streetComplement,
address.country,
].some(hasValue)
}
/**
* Onglets visibles en consultation (ERP-193, retour métier) : on masque tout
* onglet de données vide. Le transporteur n'a pas de coquille « à venir ».
* Ordre : Adresses · Contacts · Prix. Retourne `[]` tant que le transporteur
* n'est pas chargé.
*/
export function carrierConsultationVisibleTabs(
carrier: CarrierDetail | null | undefined,
): string[] {
if (!carrier) {
return []
}
const visible: string[] = []
if (hasAddressData(carrier.address)) {
visible.push('addresses')
}
if ((carrier.contacts ?? []).length > 0) {
visible.push('contacts')
}
if ((carrier.prices ?? []).length > 0) {
visible.push('prices')
}
return visible
}
/** Bouton « Modifier » : visible avec la permission `manage` (Admin / Bureau). */
export function canEditCarrier(can: (code: string) => boolean): boolean {
return can('transport.carriers.manage')
}
/** Bouton « Archiver » : permission archive ET transporteur encore actif (Admin seul). */
export function showArchiveAction(can: (code: string) => boolean, isArchived: boolean): boolean {
return can('transport.carriers.archive') && !isArchived
}
/** Bouton « Restaurer » : permission archive ET transporteur déjà archivé (Admin seul). */
export function showRestoreAction(can: (code: string) => boolean, isArchived: boolean): boolean {
return can('transport.carriers.archive') && isArchived
}
@@ -0,0 +1,77 @@
/**
* Helpers purs de l'onglet Prix transporteur (M4 Transport, ERP-169 RG-4.094.11).
* Une ligne porte une branche CLIENT ou FOURNISSEUR selon `direction` ; les champs
* de la branche INACTIVE doivent toujours partir à null (CHECK BDD
* chk_carrier_price_client_branch / supplier_branch). Testables sans Vue ni API.
*/
import type { CarrierPriceFormDraft } from '~/modules/transport/types/carrierForm'
/** Vrai si une chaîne porte au moins un caractère non-espace. */
function isFilled(value: string | null | undefined): boolean {
return value !== null && value !== undefined && value.trim() !== ''
}
/**
* Payload de la sous-ressource prix (groupe `carrier:write:prices`). Envoie les
* communs + UNIQUEMENT la branche active (l'autre branche à null, exigée par les
* CHECK BDD). Les relations partent en IRI (string|null).
*
* IMPORTANT : les scalaires obligatoires (direction / containerType / pricingUnit /
* price / priceState) sont OMIS s'ils sont vides — on n'envoie JAMAIS `null` sur un
* champ string. Sinon API Platform lève un 400 « The type of the "price" attribute
* must be "string", "NULL" given. » AVANT la validation (non mappable inline). Omis,
* le champ reste null côté entité l'Assert\NotBlank renvoie un 422 propre rattaché
* au champ, affiché sous l'input comme les autres blocs (ERP-101). Le back re-valide
* aussi l'obligation conditionnelle de branche + l'appartenance de l'adresse.
*/
export function buildCarrierPricePayload(price: CarrierPriceFormDraft): Record<string, unknown> {
const payload: Record<string, unknown> = {}
// Scalaires : présents seulement si remplis (jamais `null` → évite le 400 de type).
if (isFilled(price.direction)) payload.direction = price.direction
if (isFilled(price.containerType)) payload.containerType = price.containerType
if (isFilled(price.pricingUnit)) payload.pricingUnit = price.pricingUnit
if (isFilled(price.price)) payload.price = price.price
if (isFilled(price.priceState)) payload.priceState = price.priceState
// Branche active en IRI (null toléré sur une relation, ne déclenche pas le 400 de
// type) ; branche inactive forcée à null (CHECK BDD chk_carrier_price_*_branch).
if (price.direction === 'CLIENT') {
payload.client = price.clientIri || null
payload.clientDeliveryAddress = price.clientDeliveryAddressIri || null
payload.departureSite = price.departureSiteIri || null
payload.supplier = null
payload.supplierSupplyAddress = null
payload.deliverySite = null
}
else if (price.direction === 'FOURNISSEUR') {
payload.supplier = price.supplierIri || null
payload.supplierSupplyAddress = price.supplierSupplyAddressIri || null
payload.deliverySite = price.deliverySiteIri || null
payload.client = null
payload.clientDeliveryAddress = null
payload.departureSite = null
}
return payload
}
/**
* Pré-check léger du gating « + Nouveau prix » : direction choisie, prix rempli, et
* branche active complète (client/adresse/site OU fournisseur/adresse/site). Le back
* reste la couche autoritaire (RG-4.094.11) ; ce pré-check évite d'empiler des
* blocs vides.
*/
export function isCarrierPriceValid(price: CarrierPriceFormDraft): boolean {
if (!isFilled(price.price) || !isFilled(price.containerType) || !isFilled(price.pricingUnit) || !isFilled(price.priceState)) {
return false
}
if (price.direction === 'CLIENT') {
return isFilled(price.clientIri) && isFilled(price.clientDeliveryAddressIri) && isFilled(price.departureSiteIri)
}
if (price.direction === 'FOURNISSEUR') {
return isFilled(price.supplierIri) && isFilled(price.supplierSupplyAddressIri) && isFilled(price.deliverySiteIri)
}
return false
}
@@ -0,0 +1,47 @@
/**
* Helpers de saisie du formulaire principal transporteur (ERP-170).
* Champs texte restreints (volume m³ décimal, indexation plafonnée, immatriculations
* LIOT via mask maska). Purs / testables.
*/
import type { MaskInputOptions } from 'maska'
/**
* Restreint une saisie à un nombre décimal : chiffres + UN seul point (RG volume m³,
* « nombres avec des points » comme les autres modules). La virgule décimale FR est
* convertie en point (« 30,5 » « 30.5 ») ; tout autre caractère est supprimé.
*/
export function sanitizeDecimal(value: string): string {
let cleaned = (value ?? '').replace(/,/g, '.').replace(/[^0-9.]/g, '')
const dot = cleaned.indexOf('.')
if (dot !== -1) {
// Conserve le 1er point, retire les suivants.
cleaned = cleaned.slice(0, dot + 1) + cleaned.slice(dot + 1).replace(/\./g, '')
}
return cleaned
}
/**
* Plafonne un pourcentage à 100 (contrainte FRONT : l'indexation n'a pas de max back).
* Renvoie « 100 » si la valeur saisie dépasse 100, sinon la valeur telle quelle.
*/
export function clampPercent(value: string): string {
const n = Number(String(value ?? '').replace(',', '.').replace(/\s/g, ''))
return (!Number.isNaN(n) && n > 100) ? '100' : value
}
/**
* Mask maska des immatriculations LIOT : n'autorise que lettres, chiffres, tiret et
* point-virgule (séparateur de plaques), longueur libre. Filtrage NATIF (maska gère
* le focus et le curseur, contrairement à un nettoyage manuel). Espaces et tout autre
* caractère sont bloqués à la frappe / au collage. La normalisation finale (majuscules
* + « ; » espacé) reste au back (RG-4.13).
*
* `preProcess` retire d'abord tout caractère interdit (espaces, &, ², …) OÙ QU'IL
* SOIT (le masque positionnel seul s'arrêterait au 1er caractère invalide) ; le
* token `P` en `multiple: true` laisse ensuite passer le reste (longueur libre).
*/
export const LIOT_PLATES_MASK: MaskInputOptions = {
mask: 'P',
tokens: { P: { pattern: /[A-Za-z0-9;-]/, multiple: true } },
preProcess: (value: string) => value.replace(/[^A-Za-z0-9;-]/g, ''),
}
+4 -4
View File
@@ -7,7 +7,7 @@
"name": "starseed-frontend",
"hasInstallScript": true,
"dependencies": {
"@malio/layer-ui": "^1.7.12",
"@malio/layer-ui": "^1.7.13",
"@nuxt/icon": "^2.2.1",
"@nuxtjs/i18n": "^10.2.3",
"@nuxtjs/tailwindcss": "^6.14.0",
@@ -1866,9 +1866,9 @@
"license": "MIT"
},
"node_modules/@malio/layer-ui": {
"version": "1.7.12",
"resolved": "https://gitea.malio.fr/api/packages/MALIO-DEV/npm/%40malio%2Flayer-ui/-/1.7.12/layer-ui-1.7.12.tgz",
"integrity": "sha512-ezQLqi19K2ogI3XwSMsUyluU9x5C4W0tu1muxFbL3foKjibRYRg/FdvySivEhEsalAAt1E88V6Sv/06xPqyYTw==",
"version": "1.7.13",
"resolved": "https://gitea.malio.fr/api/packages/MALIO-DEV/npm/%40malio%2Flayer-ui/-/1.7.13/layer-ui-1.7.13.tgz",
"integrity": "sha512-/l3wAYKSeJSZslaom81/ugXrY/vVElrg6Mc6U16v7Pm2RruzLJQlX/90aIe+nYzl0xShRZPmdaD+eozFWmes/A==",
"dependencies": {
"@nuxt/icon": "^2.2.1",
"@nuxtjs/tailwindcss": "^6.14.0",
+1 -1
View File
@@ -17,7 +17,7 @@
"test:e2e:ui": "playwright test --ui"
},
"dependencies": {
"@malio/layer-ui": "^1.7.12",
"@malio/layer-ui": "^1.7.13",
"@nuxt/icon": "^2.2.1",
"@nuxtjs/i18n": "^10.2.3",
"@nuxtjs/tailwindcss": "^6.14.0",
@@ -0,0 +1,59 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
/**
* Tests du composable d'upload générique (ERP-171) :
* - succès : POST multipart /uploaded_documents (champ « file »), toast désactivé,
* renvoie l'IRI (@id) du document créé, `uploading` retombe à false ;
* - erreur MIME hors whitelist 422 : l'erreur est RELAYÉE à l'appelant (pour un
* affichage inline sous le champ), `uploading` -armé via le finally.
*/
const mockPost = vi.hoisted(() => vi.fn())
vi.stubGlobal('useApi', () => ({
get: vi.fn(),
post: mockPost,
put: vi.fn(),
patch: vi.fn(),
delete: vi.fn(),
}))
const { useUpload } = await import('../useUpload')
describe('useUpload', () => {
beforeEach(() => {
mockPost.mockReset()
})
it('succès : POST multipart champ « file » + toast:false → renvoie l\'IRI', async () => {
mockPost.mockResolvedValue({ '@id': '/api/uploaded_documents/9', originalFilename: 'decharge.pdf' })
const { upload, uploading } = useUpload()
const file = new File(['contenu'], 'decharge.pdf', { type: 'application/pdf' })
const iri = await upload(file)
expect(iri).toBe('/api/uploaded_documents/9')
const [url, body, options] = mockPost.mock.calls[0]
expect(url).toBe('/uploaded_documents')
expect(body).toBeInstanceOf(FormData)
const stored = (body as FormData).get('file')
expect(stored).toBeInstanceOf(File)
expect((stored as File).name).toBe('decharge.pdf')
expect(options).toMatchObject({ toast: false })
expect(uploading.value).toBe(false)
})
it('erreur MIME → 422 : l\'erreur est remontée à l\'appelant', async () => {
const error = Object.assign(new Error('422'), {
data: { 'hydra:description': 'Type de fichier non autorisé.' },
})
mockPost.mockRejectedValue(error)
const { upload, uploading } = useUpload()
const file = new File(['x'], 'malware.exe', { type: 'application/x-msdownload' })
await expect(upload(file)).rejects.toBe(error)
expect(uploading.value).toBe(false)
})
})
+53
View File
@@ -0,0 +1,53 @@
import { ref } from 'vue'
import type { AnyObject } from '~/shared/composables/useApi'
/**
* Réponse JSON-LD de POST /api/uploaded_documents (groupe `uploaded_document:read`).
* Seul l'IRI (`@id`) est exploité pour le poser sur la relation cible.
*/
export interface UploadedDocumentResponse {
'@id': string
originalFilename?: string
mimeType?: string
}
/**
* Upload d'un document générique vers l'infra partagée (ERP-154) :
* POST /api/uploaded_documents en multipart/form-data, champ « file », via
* `useApi()` (cookie JWT, parsing Hydra/erreurs). Renvoie l'IRI du document créé,
* à poser sur la relation cible (ex: `carrier.dischargeDocument` RG-4.02).
*
* Les erreurs (MIME hors whitelist / fichier trop volumineux 422) sont relayées
* (rethrow) à l'appelant pour un affichage inline sous le champ. `toast: false` par
* défaut : pas de toast fourre-tout, le formulaire mappe le message au bon champ.
*/
export function useUpload() {
// Indicateur d'upload en cours (désactivation UI / spinner éventuel).
const uploading = ref(false)
/**
* Envoie `file` et renvoie l'IRI du `UploadedDocument` créé.
* @throws relaie l'erreur réseau / 422 (MIME, taille) à l'appelant.
*/
async function upload(file: File, options: { toast?: boolean } = {}): Promise<string> {
const formData = new FormData()
formData.append('file', file)
uploading.value = true
try {
// useApi() détecte le FormData et n'impose pas de Content-Type JSON :
// le navigateur pose lui-même la frontière multipart.
const doc = await useApi().post<UploadedDocumentResponse>(
'/uploaded_documents',
formData as unknown as AnyObject,
{ toast: options.toast ?? false },
)
return doc['@id']
} finally {
uploading.value = false
}
}
return { uploading, upload }
}
@@ -22,11 +22,12 @@ describe('removeCollectionRow', () => {
const errors: Record<string, string>[] = [{}, {}]
const deleteRow = vi.fn().mockResolvedValue(undefined)
const onError = vi.fn()
const onSuccess = vi.fn()
const removed = await removeCollectionRow({
rows, errors, index: 0,
endpoint: '/client_contacts',
deleteRow, makeEmpty, onError,
deleteRow, makeEmpty, onError, onSuccess,
})
expect(deleteRow).toHaveBeenCalledOnce()
@@ -35,6 +36,8 @@ describe('removeCollectionRow', () => {
expect(rows).toEqual([{ id: 11, label: 'B' }])
expect(errors).toHaveLength(1)
expect(onError).not.toHaveBeenCalled()
// Toast de succes uniquement sur suppression serveur confirmee.
expect(onSuccess).toHaveBeenCalledOnce()
})
it('ne fait AUCUN appel reseau pour un bloc jamais persiste (id null) — retrait local', async () => {
@@ -42,16 +45,19 @@ describe('removeCollectionRow', () => {
const errors: Record<string, string>[] = [{}, {}]
const deleteRow = vi.fn().mockResolvedValue(undefined)
const onError = vi.fn()
const onSuccess = vi.fn()
const removed = await removeCollectionRow({
rows, errors, index: 1,
endpoint: '/client_contacts',
deleteRow, makeEmpty, onError,
deleteRow, makeEmpty, onError, onSuccess,
})
expect(deleteRow).not.toHaveBeenCalled()
expect(removed).toBe(true)
expect(rows).toEqual([{ id: 10, label: 'A' }])
// Retrait d'un simple brouillon local : pas de toast « supprime ».
expect(onSuccess).not.toHaveBeenCalled()
})
it('conserve le bloc et remonte l\'erreur si le DELETE serveur echoue (ex. 409 dernier RIB LCR)', async () => {
@@ -0,0 +1,19 @@
import { describe, expect, it } from 'vitest'
import { todayIso } from '../date'
describe('todayIso', () => {
it('formate la date locale en YYYY-MM-DD (zero-pad mois/jour)', () => {
// 7 mars 2026 (heure locale) -> '2026-03-07'.
expect(todayIso(new Date(2026, 2, 7, 10, 30))).toBe('2026-03-07')
})
it('utilise les composantes LOCALES, pas UTC (pas de decalage de minuit)', () => {
// 18 juin 2026 23:30 heure locale : la date locale reste le 18 meme si
// toISOString() (UTC) basculerait au 19 selon le fuseau.
expect(todayIso(new Date(2026, 5, 18, 23, 30))).toBe('2026-06-18')
})
it('gere le dernier jour de l\'annee', () => {
expect(todayIso(new Date(2026, 11, 31, 12, 0))).toBe('2026-12-31')
})
})
@@ -0,0 +1,65 @@
import { describe, expect, it } from 'vitest'
import { Mask, type MaskInputOptions } from 'maska'
import {
ADDRESS_MASK,
CODE_ALNUM_MASK,
FREE_TEXT_MASK,
PERSON_NAME_MASK,
} from '../textSanitize'
/** Reproduit le traitement maska au runtime (MaskInput) : preProcess puis masked. */
function apply(mask: MaskInputOptions, value: string): string {
const pre = mask.preProcess ? mask.preProcess(value) : value
return new Mask(mask).masked(pre)
}
describe('PERSON_NAME_MASK', () => {
it('garde lettres accentuees, espace, apostrophe, tiret, point', () => {
expect(apply(PERSON_NAME_MASK, 'Jean-Pierre')).toBe('Jean-Pierre')
expect(apply(PERSON_NAME_MASK, 'OBrien')).toBe('OBrien')
expect(apply(PERSON_NAME_MASK, "D'Angelo")).toBe("D'Angelo")
expect(apply(PERSON_NAME_MASK, 'Saint-Étienne J.')).toBe('Saint-Étienne J.')
})
it('retire chiffres et caracteres parasites (ou qu\'ils soient)', () => {
expect(apply(PERSON_NAME_MASK, 'Dupont²³')).toBe('Dupont')
expect(apply(PERSON_NAME_MASK, 'Jean§&#~|')).toBe('Jean')
expect(apply(PERSON_NAME_MASK, 'Ma§rie123')).toBe('Marie') // parasite AU MILIEU
})
})
describe('FREE_TEXT_MASK', () => {
it('garde &, /, parentheses, degre, chiffres', () => {
expect(apply(FREE_TEXT_MASK, 'Dupont & Fils')).toBe('Dupont & Fils')
expect(apply(FREE_TEXT_MASK, 'Resp. Achats/Ventes')).toBe('Resp. Achats/Ventes')
expect(apply(FREE_TEXT_MASK, 'SARL Léon (Pôle n°2)')).toBe('SARL Léon (Pôle n°2)')
})
it('retire les parasites ²³§~#|', () => {
expect(apply(FREE_TEXT_MASK, 'ACME²³§')).toBe('ACME')
expect(apply(FREE_TEXT_MASK, 'Te~#|st<>{}')).toBe('Test')
})
})
describe('ADDRESS_MASK', () => {
it('garde chiffres, virgule, point, apostrophe, slash, degre, tiret', () => {
expect(apply(ADDRESS_MASK, '12 bis, rue de l’Église')).toBe('12 bis, rue de l’Église')
expect(apply(ADDRESS_MASK, 'Bât. n°3 - Zone A/B')).toBe('Bât. n°3 - Zone A/B')
})
it('retire les parasites', () => {
expect(apply(ADDRESS_MASK, '5 rue X²³§&')).toBe('5 rue X')
})
})
describe('CODE_ALNUM_MASK', () => {
it('force la majuscule et ne garde que A-Z 0-9', () => {
expect(apply(CODE_ALNUM_MASK, '411dupont')).toBe('411DUPONT')
expect(apply(CODE_ALNUM_MASK, 'FR 12 345')).toBe('FR12345')
expect(apply(CODE_ALNUM_MASK, '4-11.000§')).toBe('411000')
})
it('chaine vide reste vide', () => {
expect(apply(CODE_ALNUM_MASK, '')).toBe('')
})
})
+13 -1
View File
@@ -33,6 +33,12 @@ export interface RemoveCollectionRowOptions<T extends DeletableRow> {
makeEmpty: () => T
/** Remontee d'erreur 409/422 mappee proprement (message back, pas de toast fourre-tout). */
onError: (error: unknown) => void
/**
* Callback de succes (toast) appele UNIQUEMENT apres une suppression serveur
* confirmee d'un bloc persiste (`id` non null). Pas appele sur le simple retrait
* d'un brouillon local non enregistre (aucune suppression reelle).
*/
onSuccess?: () => void
}
/**
@@ -55,8 +61,9 @@ export interface RemoveCollectionRowOptions<T extends DeletableRow> {
export async function removeCollectionRow<T extends DeletableRow>(
options: RemoveCollectionRowOptions<T>,
): Promise<boolean> {
const { rows, errors, index, endpoint, deleteRow, makeEmpty, onError } = options
const { rows, errors, index, endpoint, deleteRow, makeEmpty, onError, onSuccess } = options
const removed = rows[index]
let serverDeleted = false
// Bloc existant : suppression serveur d'abord, retrait local seulement si OK.
if (removed?.id != null) {
@@ -67,6 +74,7 @@ export async function removeCollectionRow<T extends DeletableRow>(
onError(error)
return false
}
serverDeleted = true
}
rows.splice(index, 1)
@@ -75,5 +83,9 @@ export async function removeCollectionRow<T extends DeletableRow>(
if (rows.length === 0) {
rows.push(makeEmpty())
}
// Toast de succes uniquement quand le serveur a confirme une vraie suppression.
if (serverDeleted) {
onSuccess?.()
}
return true
}
+17
View File
@@ -0,0 +1,17 @@
/**
* Helpers de date purs / testables (partages inter-modules).
*/
/**
* Date du jour au format ISO `YYYY-MM-DD` en heure LOCALE.
*
* On NE passe PAS par `toISOString()` (UTC) : pres de minuit, le decalage de
* fuseau (FR = UTC+1/+2) renverrait la veille ou le lendemain. On lit donc les
* composantes locales. Parametre `now` injectable pour les tests.
*/
export function todayIso(now: Date = new Date()): string {
const year = now.getFullYear()
const month = String(now.getMonth() + 1).padStart(2, '0')
const day = String(now.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
+47
View File
@@ -0,0 +1,47 @@
/**
* Masks de saisie texte (retour metier ERP-193) : filtrage NATIF (maska) des
* caracteres parasites (« ²³§~#| ») dans les champs texte libres. maska gere le
* focus et le curseur (contrairement a un nettoyage manuel sur @update qui laissait
* le caractere affiche jusqu'a la frappe suivante).
*
* Miroir FRONT des patterns back `App\Shared\Domain\Validation\TextInputPattern`
* (allow-list par famille de champ). Le back reste l'autorite (Assert\Regex
* 422 inline via useFormErrors) ; ces masks ne font que le confort de saisie.
*
* IMPORTANT : garder les classes de caracteres STRICTEMENT alignees sur le back.
*
* L'EMAIL n'a PAS de mask (decision ERP-101 : un email n'a pas de structure fixe,
* on valide le FORMAT via Assert\Email + erreur inline, jamais via un masque).
*/
import type { MaskInputOptions } from 'maska'
/**
* Construit un mask maska « jeu de caracteres autorise, longueur libre » :
* - `preProcess` retire d'abord TOUT caractere hors charset, OU QU'IL SOIT (un
* masque positionnel seul s'arreterait au 1er caractere invalide car le token
* `multiple` est glouton) ;
* - le token `P` (`multiple`) laisse ensuite passer le reste, sans limite de longueur.
*
* @param pattern classe des caracteres AUTORISES (1 caractere, sans flag global)
* @param strip negation de `pattern`, flag global (retire les interdits)
* @param upper force la majuscule (codes : n° compte / TVA / IBAN / BIC)
*/
function charsetMask(pattern: RegExp, strip: RegExp, upper = false): MaskInputOptions {
return {
mask: 'P',
tokens: { P: { pattern, multiple: true } },
preProcess: (v: string) => (upper ? v.toUpperCase() : v).replace(strip, ''),
}
}
/** Noms de personnes (Nom, Prenom, Dirigeant) : lettres (accents), espace, apostrophe, tiret, point. */
export const PERSON_NAME_MASK = charsetMask(/[\p{L}\p{M} '.-]/u, /[^\p{L}\p{M} '.-]/gu)
/** Texte societe / libre (Raison sociale, Concurrents, Fonction) : + chiffres, virgule, &, /, parentheses, degre. */
export const FREE_TEXT_MASK = charsetMask(/[\p{L}\p{M}0-9 '.,&/()°-]/u, /[^\p{L}\p{M}0-9 '.,&/()°-]/gu)
/** Adresse (voie, complement, ville) : lettres, chiffres, espace, apostrophe, point, virgule, slash, degre, tiret. */
export const ADDRESS_MASK = charsetMask(/[\p{L}\p{M}0-9 '.,/°-]/u, /[^\p{L}\p{M}0-9 '.,/°-]/gu)
/** Codes alphanumeriques majuscules (N° de compte, N° de TVA, IBAN, BIC) : A-Z et 0-9, majuscule forcee. */
export const CODE_ALNUM_MASK = charsetMask(/[A-Z0-9]/, /[^A-Z0-9]/g, true)
+6
View File
@@ -103,6 +103,12 @@ export const personas: Record<PersonaKey, Persona> = {
'transport.carriers.view',
'transport.carriers.manage',
'transport.carriers.archive',
// Logistique — Tickets de pesee (M5, ERP-181). Meme logique : mappe sur
// le persona "tout", pas de nouveau persona (regle ABSOLUE n°7).
// logistique.weighing_tickets.view n'ajoute pas de lien dans la section
// Administration, donc expectedAdminLinks reste inchange.
'logistique.weighing_tickets.view',
'logistique.weighing_tickets.manage',
],
expectedAdminLinks: ['users', 'roles', 'sites', 'categories', 'audit-log'],
},
+1 -1
View File
@@ -75,7 +75,7 @@ COPY infra/prod/maintenance.html /var/www/html/public/maintenance.html
RUN echo "APP_ENV=prod" > /var/www/html/.env
# Permissions
RUN mkdir -p /var/www/html/var /var/www/html/config/jwt \
RUN mkdir -p /var/www/html/var /var/www/html/var/log /var/www/html/config/jwt \
&& chown -R www-data:www-data /var/www/html/var
WORKDIR /var/www/html
+40
View File
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* ERP-172 adresse UNIQUE par transporteur (decision metier : un transporteur a
* au plus une adresse). Bascule la relation carrier_address.carrier_id en OneToOne :
* remplace l'index simple idx_carrier_address_carrier par une contrainte d'unicite
* uniq_carrier_address_carrier. La garde applicative (CarrierAddressProcessor) renvoie
* un 409 explicite avant d'atteindre cette contrainte.
*
* Placee au namespace racine DoctrineMigrations (et non en modulaire Transport) :
* elle ALTERE une table creee par une migration racine (Version20260615150000) ;
* le tri par version au sein du meme namespace garantit qu'elle joue APRES l'init
* (cf. CLAUDE.md regle 11 le tri cross-namespace casserait l'ordre sur base vide).
*/
final class Version20260617140000 extends AbstractMigration
{
public function getDescription(): string
{
return 'ERP-172 : adresse unique par transporteur — index unique sur carrier_address.carrier_id (OneToOne).';
}
public function up(Schema $schema): void
{
$this->addSql('DROP INDEX idx_carrier_address_carrier');
$this->addSql('CREATE UNIQUE INDEX uniq_carrier_address_carrier ON carrier_address (carrier_id)');
}
public function down(Schema $schema): void
{
$this->addSql('DROP INDEX uniq_carrier_address_carrier');
$this->addSql('CREATE INDEX idx_carrier_address_carrier ON carrier_address (carrier_id)');
}
}
+264
View File
@@ -0,0 +1,264 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use App\Shared\Infrastructure\Database\ColumnCommentsCatalog;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* M5 Tickets de pesee (ERP-182) : creation du schema BDD du module Logistique.
*
* Objets crees :
* - site.code : code court du site (86/17/82), prefixe de numerotation des
* tickets (RG-5.02). Backfill depuis les 2 premiers chiffres du code postal
* + index unique uq_site_code (§ 2.5). NULLABLE a ce ticket (l'entite Site ne
* mappe pas encore `code`) ; le mapping ORM + peuplement + SET NOT NULL sont
* portes par le ticket entite (WeighingTicket).
* - weighing_ticket_counter : sequence du numero de ticket par site (RG-5.02).
* - weighbridge_dsd_counter : compteur DSD du pont bascule par site (RG-5.04).
* - weighing_ticket : table principale (contrepartie Client/Fournisseur/Autre,
* immatriculation partagee, pesees a vide + a plein en colonnes plates,
* poids net derive, soft-delete prepare + Timestampable/Blamable).
*
* Namespace racine `DoctrineMigrations` (regle ABSOLUE n°11) et NON modulaire :
* la table porte des FK cross-module (user, client, supplier, site). Le tri par
* timestamp au sein du namespace racine garantit l'ordre apres la creation de
* ces tables sur base vide ; un namespace modulaire casserait `make db-reset`.
*
* Convention IDs (spec § 2.2) : `INT GENERATED BY DEFAULT AS IDENTITY`,
* horodatages `TIMESTAMP(0) WITHOUT TIME ZONE` (le TimestampableBlamableTrait
* mappe `datetime_immutable`).
*
* Chaque colonne porte son `COMMENT ON COLUMN` (regle ABSOLUE n°12).
*
* NB schema:update (test-db-setup) :
* - weighing_ticket_counter / weighbridge_dsd_counter ne sont JAMAIS mappees en
* ORM (DBAL brut sous verrou FOR UPDATE, § 2.5 / § 2.7) -> exclues du
* `schema_filter` (config/packages/doctrine.yaml) pour que schema:update ne
* les drope pas. Leurs descriptions sont aussi catalogue-es dans
* ColumnCommentsCatalog (rejeu par `app:apply-column-comments`).
* - weighing_ticket et la colonne site.code seront mappes en ORM au ticket
* suivant (entite WeighingTicket + propriete Site::code) ; d'ici la,
* schema:update les drope sur la base de TEST uniquement (sans impact : aucun
* test ne les reference encore, et dev/prod ne lancent jamais schema:update).
*/
final class Version20260617150000 extends AbstractMigration
{
public function getDescription(): string
{
return 'ERP-182 (M5) : site.code + compteurs (numero ticket / DSD) + table weighing_ticket (tickets de pesee).';
}
public function up(Schema $schema): void
{
$this->addSiteCode();
$this->createWeighingTicketCounter();
$this->createWeighbridgeDsdCounter();
$this->createWeighingTicket();
}
public function down(Schema $schema): void
{
// Ordre inverse : table principale puis compteurs, enfin la colonne site.code.
$this->addSql('DROP TABLE IF EXISTS weighing_ticket');
$this->addSql('DROP TABLE IF EXISTS weighbridge_dsd_counter');
$this->addSql('DROP TABLE IF EXISTS weighing_ticket_counter');
$this->addSql('DROP INDEX IF EXISTS uq_site_code');
$this->addSql('ALTER TABLE site DROP COLUMN IF EXISTS code');
}
// =================================================================
// site.code — prefixe de numerotation des tickets (§ 2.5)
// =================================================================
private function addSiteCode(): void
{
// Colonne NULLABLE a ce ticket : l'entite Site ne mappe pas encore `code`,
// donc tout persist ORM (fixtures, tests) l'omettrait -> un NOT NULL casserait
// `make db-reset`. Le mapping ORM Site::code, son peuplement (86/17/82) et le
// passage `SET NOT NULL` sont portes par le ticket suivant (entite WeighingTicket
// + Site::code), via une 2e migration. L'index unique est pose des maintenant
// (Postgres tolere plusieurs NULL) : il garantit l'unicite des qu'ils seront peuples.
$this->addSql('ALTER TABLE site ADD COLUMN code VARCHAR(8) DEFAULT NULL');
// Backfill : 2 premiers chiffres du code postal (departement) par defaut,
// editable ensuite cote admin Sites. No-op sur base fraiche (aucun site encore).
$this->addSql('UPDATE site SET code = LEFT(postal_code, 2) WHERE code IS NULL');
$this->addSql('CREATE UNIQUE INDEX uq_site_code ON site (code)');
$this->comment('site', 'code', 'Code court du site (ex. 86/17/82) — prefixe de numerotation des tickets de pesee (RG-5.02). Unique (uq_site_code). Backfill = 2 premiers chiffres du CP. NOT NULL pose au ticket entite.');
}
// =================================================================
// Compteur du numero de ticket (sequence par site) — RG-5.02
// =================================================================
private function createWeighingTicketCounter(): void
{
$this->addSql(<<<'SQL'
CREATE TABLE weighing_ticket_counter (
site_id INT NOT NULL,
last_value INT DEFAULT 0 NOT NULL,
PRIMARY KEY (site_id),
CONSTRAINT fk_wt_counter_site
FOREIGN KEY (site_id) REFERENCES site (id) ON DELETE CASCADE
)
SQL);
$this->comment('weighing_ticket_counter', '_table', 'Sequence du numero de ticket de pesee par site (RG-5.02, M5 Logistique) — incrementee en DBAL brut sous verrou FOR UPDATE, hors ORM.');
$this->comment('weighing_ticket_counter', 'site_id', 'Site proprietaire de la sequence (1 ligne par site). PK + FK -> site.id, ON DELETE CASCADE.');
$this->comment('weighing_ticket_counter', 'last_value', 'Dernier numero de ticket attribue pour le site. Increment verrouille FOR UPDATE (RG-5.02).');
}
// =================================================================
// Compteur DSD (pesee du pont, par site) — RG-5.04
// =================================================================
private function createWeighbridgeDsdCounter(): void
{
$this->addSql(<<<'SQL'
CREATE TABLE weighbridge_dsd_counter (
site_id INT NOT NULL,
last_value INT DEFAULT 0 NOT NULL,
PRIMARY KEY (site_id),
CONSTRAINT fk_dsd_counter_site
FOREIGN KEY (site_id) REFERENCES site (id) ON DELETE CASCADE
)
SQL);
$this->comment('weighbridge_dsd_counter', '_table', 'Compteur DSD du pont bascule par site (RG-5.04, M5 Logistique) — chaque pesee consomme une valeur. Incremente en DBAL brut sous verrou FOR UPDATE, hors ORM.');
$this->comment('weighbridge_dsd_counter', 'site_id', 'Site proprietaire du compteur (1 pont par site). PK + FK -> site.id, ON DELETE CASCADE.');
$this->comment('weighbridge_dsd_counter', 'last_value', 'Derniere valeur DSD attribuee pour le site (pont bascule). Increment verrouille FOR UPDATE (RG-5.04).');
}
// =================================================================
// Table principale `weighing_ticket`
// =================================================================
private function createWeighingTicket(): void
{
$this->addSql(<<<'SQL'
CREATE TABLE weighing_ticket (
id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
site_id INT NOT NULL,
number VARCHAR(20) NOT NULL,
counterparty_type VARCHAR(12) NOT NULL,
client_id INT DEFAULT NULL,
supplier_id INT DEFAULT NULL,
other_label VARCHAR(255) DEFAULT NULL,
immatriculation VARCHAR(20) NOT NULL,
plate_free_format BOOLEAN DEFAULT FALSE NOT NULL,
empty_date TIMESTAMP(0) WITHOUT TIME ZONE DEFAULT NULL,
empty_weight INT DEFAULT NULL,
empty_dsd INT DEFAULT NULL,
empty_mode VARCHAR(8) DEFAULT NULL,
empty_manual_number VARCHAR(50) DEFAULT NULL,
full_date TIMESTAMP(0) WITHOUT TIME ZONE DEFAULT NULL,
full_weight INT DEFAULT NULL,
full_dsd INT DEFAULT NULL,
full_mode VARCHAR(8) DEFAULT NULL,
full_manual_number VARCHAR(50) DEFAULT NULL,
net_weight INT 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 chk_wt_counterparty_type
CHECK (counterparty_type IN ('CLIENT', 'FOURNISSEUR', 'AUTRE')),
CONSTRAINT chk_wt_empty_mode
CHECK (empty_mode IS NULL OR empty_mode IN ('AUTO', 'MANUAL')),
CONSTRAINT chk_wt_full_mode
CHECK (full_mode IS NULL OR full_mode IN ('AUTO', 'MANUAL')),
CONSTRAINT chk_wt_client_branch
CHECK (counterparty_type <> 'CLIENT' OR (client_id IS NOT NULL AND supplier_id IS NULL AND other_label IS NULL)),
CONSTRAINT chk_wt_supplier_branch
CHECK (counterparty_type <> 'FOURNISSEUR' OR (supplier_id IS NOT NULL AND client_id IS NULL AND other_label IS NULL)),
CONSTRAINT chk_wt_other_branch
CHECK (counterparty_type <> 'AUTRE' OR (other_label IS NOT NULL AND client_id IS NULL AND supplier_id IS NULL)),
CONSTRAINT fk_wt_site
FOREIGN KEY (site_id) REFERENCES site (id) ON DELETE RESTRICT,
CONSTRAINT fk_wt_client
FOREIGN KEY (client_id) REFERENCES client (id) ON DELETE RESTRICT,
CONSTRAINT fk_wt_supplier
FOREIGN KEY (supplier_id) REFERENCES supplier (id) ON DELETE RESTRICT,
CONSTRAINT fk_wt_created_by
FOREIGN KEY (created_by) REFERENCES "user" (id) ON DELETE SET NULL,
CONSTRAINT fk_wt_updated_by
FOREIGN KEY (updated_by) REFERENCES "user" (id) ON DELETE SET NULL
)
SQL);
$this->addSql('CREATE UNIQUE INDEX uq_weighing_ticket_number ON weighing_ticket (site_id, number)');
$this->addSql('CREATE INDEX idx_wt_site ON weighing_ticket (site_id)');
$this->addSql('CREATE INDEX idx_wt_client ON weighing_ticket (client_id)');
$this->addSql('CREATE INDEX idx_wt_supplier ON weighing_ticket (supplier_id)');
$this->addSql('CREATE INDEX idx_wt_deleted_at ON weighing_ticket (deleted_at)');
$this->addSql('CREATE INDEX idx_wt_created_by ON weighing_ticket (created_by)');
$this->addSql('CREATE INDEX idx_wt_updated_by ON weighing_ticket (updated_by)');
$this->comment('weighing_ticket', '_table', 'Tickets de pesee (M5 Logistique) — pesee a vide + a plein au pont bascule, contrepartie Client/Fournisseur/Autre. Cloisonne par site courant.');
$this->comment('weighing_ticket', 'id', 'Identifiant interne auto-incremente.');
$this->comment('weighing_ticket', 'site_id', 'Site du pont bascule (cloisonnement § 2.3). FK -> site.id, ON DELETE RESTRICT. Renseigne serveur depuis le site courant, immuable (RG-5.09).');
$this->comment('weighing_ticket', 'number', 'Numero {siteCode}-TP-{NNNN}, unique par site (uq_weighing_ticket_number), immuable. Sequence weighing_ticket_counter (RG-5.02).');
$this->comment('weighing_ticket', 'counterparty_type', 'Contrepartie : CLIENT, FOURNISSEUR ou AUTRE (chk_wt_counterparty_type, RG-5.03). Pilote l obligation client_id / supplier_id / other_label.');
$this->comment('weighing_ticket', 'client_id', 'Branche CLIENT (RG-5.03) : client concerne. FK -> client.id, ON DELETE RESTRICT. Requis ssi counterparty_type = CLIENT, nul sinon (chk_wt_client_branch).');
$this->comment('weighing_ticket', 'supplier_id', 'Branche FOURNISSEUR (RG-5.03) : fournisseur concerne. FK -> supplier.id, ON DELETE RESTRICT. Requis ssi counterparty_type = FOURNISSEUR (chk_wt_supplier_branch).');
$this->comment('weighing_ticket', 'other_label', 'Branche AUTRE (RG-5.03) : libelle libre de la contrepartie. Requis ssi counterparty_type = AUTRE, nul sinon (chk_wt_other_branch).');
$this->comment('weighing_ticket', 'immatriculation', 'Plaque du vehicule, partagee entre pesee vide et plein. Masque XX-000-XX sauf si plate_free_format (RG-5.01). Normalisee serveur (trim/UPPER).');
$this->comment('weighing_ticket', 'plate_free_format', '« Tout format » : desactive le masque XX-000-XX de l immatriculation (RG-5.01). Partage entre les 2 formulaires. Faux par defaut.');
$this->comment('weighing_ticket', 'empty_date', 'Date/heure de la pesee a vide (tare). Defaut jour courant cote front (RG-5.07). Null tant que la pesee vide n est pas faite.');
$this->comment('weighing_ticket', 'empty_weight', 'Poids a vide (tare) en kg — readonly UI, rempli par la pesee (RG-5.07).');
$this->comment('weighing_ticket', 'empty_dsd', 'Compteur DSD du pont a la pesee a vide. AUTO = valeur du pont ; MANUAL = dernier dsd du site + 1 (RG-5.04).');
$this->comment('weighing_ticket', 'empty_mode', 'Mode de la pesee a vide : AUTO (pont bascule) ou MANUAL (saisie) — chk_wt_empty_mode (RG-5.06).');
$this->comment('weighing_ticket', 'empty_manual_number', 'Numero de pesee saisi en pesee manuelle (distinct du DSD) — formulaire a vide (RG-5.04).');
$this->comment('weighing_ticket', 'full_date', 'Date/heure de la pesee a plein (brut). Null tant que la pesee plein n est pas faite.');
$this->comment('weighing_ticket', 'full_weight', 'Poids a plein (brut) en kg — readonly UI, rempli par la pesee (RG-5.07).');
$this->comment('weighing_ticket', 'full_dsd', 'Compteur DSD du pont a la pesee a plein. AUTO = valeur du pont ; MANUAL = dernier dsd du site + 1 (RG-5.04).');
$this->comment('weighing_ticket', 'full_mode', 'Mode de la pesee a plein : AUTO (pont bascule) ou MANUAL (saisie) — chk_wt_full_mode (RG-5.06).');
$this->comment('weighing_ticket', 'full_manual_number', 'Numero de pesee saisi en pesee manuelle (distinct du DSD) — formulaire a plein (RG-5.04).');
$this->comment('weighing_ticket', 'net_weight', 'Poids net = full_weight - empty_weight (kg), calcule serveur (RG-5.05). Null si une pesee manque. Colonne Poids de la liste.');
$this->comment('weighing_ticket', 'deleted_at', 'Horodatage du soft-delete technique — prepare mais non expose par l API au M5 (§ 2.13). Null = ligne active.');
$this->addTimestampableBlamableComments('weighing_ticket');
}
// =================================================================
// Helpers (identiques au M4 Version20260615150000)
// =================================================================
/**
* Pose les 4 commentaires standardises Timestampable/Blamable sur une table,
* en reutilisant le catalogue partage (source unique, 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,
));
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* ERP-172 nettoyage des reliquats du multi-adresses sur carrier_address, suite a
* la bascule en adresse UNIQUE (Version20260617140000). La colonne `position`
* servait a ordonner une LISTE d'adresses ; avec une seule adresse par transporteur
* (OneToOne) elle n'a plus de sens -> on la supprime. On reactualise aussi le
* COMMENT ON TABLE qui annoncait encore une relation 1:n.
*
* Placee au namespace racine DoctrineMigrations (et non en modulaire Transport) :
* elle ALTERE une table creee par une migration racine (Version20260615150000) ;
* le tri par version au sein du meme namespace garantit qu'elle joue APRES l'init
* et apres la bascule OneToOne (cf. CLAUDE.md regle 11).
*/
final class Version20260617160000 extends AbstractMigration
{
public function getDescription(): string
{
return 'ERP-172 : retire la colonne carrier_address.position (relique multi-adresses) + COMMENT ON TABLE 1:1.';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE carrier_address DROP COLUMN position');
$this->addSql("COMMENT ON TABLE carrier_address IS 'Adresse d un transporteur (1:1, OneToOne — ERP-172 : adresse UNIQUE) — onglet Adresse (M4). Pre-remplie depuis QUALIMAT si applicable (RG-4.05).'");
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE carrier_address ADD COLUMN position INT DEFAULT 0 NOT NULL');
$this->addSql("COMMENT ON COLUMN carrier_address.position IS 'Ordre d affichage de l adresse dans la liste du transporteur (croissant).'");
$this->addSql("COMMENT ON TABLE carrier_address IS 'Adresses d un transporteur (1:n) — onglet Adresse (M4). Pre-remplie depuis QUALIMAT si applicable (RG-4.05).'");
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* M5 Tickets de pesee (ERP-183) : finalisation de site.code en NOT NULL.
*
* Cadencement en 2 temps (RETEX dev ERP-182, § 2.5) :
* - ERP-182 (Version20260617150000) a cree site.code NULLABLE + backfill +
* index unique uq_site_code, car l'entite Site ne mappait pas encore `code`
* (un persist ORM l'aurait omis -> violation NOT NULL au `make db-reset`).
* - ERP-183 mappe desormais Site::code (propriete + getter/setter + derivation
* auto du CP au prePersist) et le peuple dans SitesFixtures (86/17/82). La
* colonne est donc systematiquement renseignee : on peut poser le NOT NULL.
*
* Namespace racine `DoctrineMigrations` (regle ABSOLUE n°11), comme la migration
* de schema M5 dont celle-ci depend (elle doit s'executer apres).
*
* Le COMMENT ON COLUMN est repose avec le texte definitif (sans la mention
* « NOT NULL pose au ticket entite » devenue caduque), aligne sur l'entree
* `site.code` du ColumnCommentsCatalog (chemin schema:update de la BDD de test).
*/
final class Version20260617170000 extends AbstractMigration
{
public function getDescription(): string
{
return 'ERP-183 (M5) : site.code -> NOT NULL (la propriete ORM Site::code est desormais mappee et peuplee).';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE site ALTER COLUMN code SET NOT NULL');
$this->addSql("COMMENT ON COLUMN site.code IS \$_\$Code court du site (ex. 86/17/82) — prefixe de numerotation des tickets de pesee (RG-5.02). Auto-derive des 2 premiers chiffres du CP a la creation, editable ensuite. Unique (uq_site_code).\$_\$");
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE site ALTER COLUMN code DROP NOT NULL');
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* ERP-193 (retour metier) l'onglet Contact d'un transporteur n'est plus
* obligatoire : suppression de la garde « prenom OU nom » (ex RG-4.08). Drop du
* CHECK chk_carrier_contact_name et mise a jour des commentaires de colonnes. La
* garde applicative (CarrierContactProcessor::validateName) est retiree dans le
* meme commit ; le catalogue ColumnCommentsCatalog aussi.
*
* Placee au namespace racine DoctrineMigrations (et non en modulaire Transport) :
* elle ALTERE une table creee par une migration racine (Version20260615150000),
* comme la migration qui avait introduit le CHECK (Version20260617120000) ; le tri
* par version au sein du meme namespace garantit qu'elle joue APRES (cf. CLAUDE.md
* regle 11 le tri cross-namespace casserait l'ordre sur base vide).
*/
final class Version20260619120000 extends AbstractMigration
{
public function getDescription(): string
{
return 'ERP-193 : onglet Contact transporteur non obligatoire — drop du CHECK chk_carrier_contact_name.';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE carrier_contact DROP CONSTRAINT chk_carrier_contact_name');
$this->addSql('COMMENT ON TABLE carrier_contact IS $_$Contacts d un transporteur (1:n) — onglet Contact (M4). Bloc optionnel (ERP-193) ; max 2 telephones.$_$');
$this->addSql('COMMENT ON COLUMN carrier_contact.first_name IS $_$Prenom du contact (capitalise serveur). Optionnel (ERP-193).$_$');
$this->addSql('COMMENT ON COLUMN carrier_contact.last_name IS $_$Nom du contact (capitalise serveur). Optionnel (ERP-193).$_$');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE carrier_contact ADD CONSTRAINT chk_carrier_contact_name CHECK (first_name IS NOT NULL OR last_name IS NOT NULL)');
$this->addSql('COMMENT ON TABLE carrier_contact IS $_$Contacts d un transporteur (1:n) — onglet Contact (M4). Au moins le prenom OU le nom rempli (RG-4.08, chk_carrier_contact_name), max 2 telephones.$_$');
$this->addSql('COMMENT ON COLUMN carrier_contact.first_name IS $_$Prenom du contact (capitalise serveur). Prenom OU nom obligatoire (RG-4.08, chk_carrier_contact_name).$_$');
$this->addSql('COMMENT ON COLUMN carrier_contact.last_name IS $_$Nom du contact (capitalise serveur). Prenom OU nom obligatoire (RG-4.08, chk_carrier_contact_name).$_$');
}
}
@@ -19,6 +19,7 @@ use App\Shared\Domain\Contract\ClientInterface;
use App\Shared\Domain\Contract\SiteInterface;
use App\Shared\Domain\Contract\TimestampableInterface;
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
use App\Shared\Domain\Validation\TextInputPattern;
use DateTimeImmutable;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
@@ -162,6 +163,7 @@ class Client implements TimestampableInterface, BlamableInterface, ClientInterfa
#[ORM\Column(length: 180)]
#[Assert\NotBlank(message: 'Le nom de l\'entreprise est obligatoire.', 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')]
#[Assert\Regex(pattern: TextInputPattern::FREE_TEXT, message: TextInputPattern::FREE_TEXT_MESSAGE)]
#[Groups(['client:read', 'client:write:main'])]
private ?string $companyName = null;
@@ -214,11 +216,14 @@ class Client implements TimestampableInterface, BlamableInterface, ClientInterfa
#[ORM\Column(length: 255, nullable: true)]
#[Assert\Length(max: 255, maxMessage: 'La liste des concurrents ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
#[Assert\Regex(pattern: TextInputPattern::FREE_TEXT, message: TextInputPattern::FREE_TEXT_MESSAGE)]
#[Groups(['client:read', 'client:write:information'])]
private ?string $competitors = null;
#[ORM\Column(type: 'date_immutable', nullable: true)]
#[Groups(['client:read', 'client:write:information'])]
// Date de creation jamais dans le futur (retour metier ERP-193) : <= aujourd'hui.
#[Assert\LessThanOrEqual(value: 'today', message: 'La date de création ne peut pas être dans le futur.')]
// Format d'ENTREE strict ISO `Y-m-d` (le `!` remet l'heure a 00:00:00). Sans
// ce format, PHP DateTime accepte des formes ambigues : « 12/25/2026 » (que
// le front MalioDate juge invalide en JJ/MM/AAAA) serait sinon interprete en
@@ -233,12 +238,16 @@ class Client implements TimestampableInterface, BlamableInterface, ClientInterfa
#[Groups(['client:read', 'client:write:information'])]
private ?int $employeesCount = null;
// Chiffre d'affaires plafonne a 999 999 999 999,99 (12 chiffres, retour metier
// ERP-193). La colonne (decimal 15,2) tolere plus, mais le metier borne la saisie.
#[ORM\Column(type: 'decimal', precision: 15, scale: 2, nullable: true)]
#[Assert\LessThanOrEqual(value: 999_999_999_999.99, message: 'Le chiffre d\'affaires ne peut pas dépasser 999 999 999 999,99.')]
#[Groups(['client:read', 'client: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')]
#[Assert\Regex(pattern: TextInputPattern::PERSON_NAME, message: TextInputPattern::PERSON_NAME_MESSAGE)]
#[Groups(['client:read', 'client:write:information'])]
private ?string $directorName = null;
@@ -257,6 +266,7 @@ class Client implements TimestampableInterface, BlamableInterface, ClientInterfa
#[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')]
#[Assert\Regex(pattern: TextInputPattern::CODE_ALNUM, message: TextInputPattern::CODE_ALNUM_MESSAGE)]
#[Groups(['client:read:accounting', 'client:write:accounting'])]
private ?string $accountNumber = null;
@@ -267,6 +277,7 @@ class Client implements TimestampableInterface, BlamableInterface, ClientInterfa
#[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')]
#[Assert\Regex(pattern: TextInputPattern::CODE_ALNUM, message: TextInputPattern::CODE_ALNUM_MESSAGE)]
#[Groups(['client:read:accounting', 'client:write:accounting'])]
private ?string $nTva = null;
@@ -19,6 +19,7 @@ use App\Shared\Domain\Contract\ClientAddressInterface;
use App\Shared\Domain\Contract\SiteInterface;
use App\Shared\Domain\Contract\TimestampableInterface;
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
use App\Shared\Domain\Validation\TextInputPattern;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
@@ -158,17 +159,20 @@ class ClientAddress implements TimestampableInterface, BlamableInterface, Client
#[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')]
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
#[Groups(['client_address:read', 'client_address:write'])]
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')]
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
#[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')]
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
#[Groups(['client_address:read', 'client_address:write'])]
private ?string $streetComplement = null;
@@ -16,6 +16,7 @@ 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 App\Shared\Domain\Validation\TextInputPattern;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Validator\Constraints as Assert;
@@ -94,16 +95,19 @@ class ClientContact implements TimestampableInterface, BlamableInterface
// 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')]
#[Assert\Regex(pattern: TextInputPattern::PERSON_NAME, message: TextInputPattern::PERSON_NAME_MESSAGE)]
#[Groups(['client_contact:read', 'client_contact:write'])]
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')]
#[Assert\Regex(pattern: TextInputPattern::PERSON_NAME, message: TextInputPattern::PERSON_NAME_MESSAGE)]
#[Groups(['client_contact:read', 'client_contact:write'])]
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')]
#[Assert\Regex(pattern: TextInputPattern::FREE_TEXT, message: TextInputPattern::FREE_TEXT_MESSAGE)]
#[Groups(['client_contact:read', 'client_contact:write'])]
private ?string $jobTitle = null;
@@ -19,6 +19,7 @@ use App\Shared\Domain\Contract\SiteInterface;
use App\Shared\Domain\Contract\SupplierInterface;
use App\Shared\Domain\Contract\TimestampableInterface;
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
use App\Shared\Domain\Validation\TextInputPattern;
use DateTimeImmutable;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
@@ -171,6 +172,7 @@ class Supplier implements TimestampableInterface, BlamableInterface, SupplierInt
#[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')]
#[Assert\Regex(pattern: TextInputPattern::FREE_TEXT, message: TextInputPattern::FREE_TEXT_MESSAGE)]
#[Groups(['supplier:read', 'supplier:write:main'])]
private ?string $companyName = null;
@@ -195,11 +197,14 @@ class Supplier implements TimestampableInterface, BlamableInterface, SupplierInt
#[ORM\Column(length: 255, nullable: true)]
#[Assert\Length(max: 255, maxMessage: 'La liste des concurrents ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
#[Assert\Regex(pattern: TextInputPattern::FREE_TEXT, message: TextInputPattern::FREE_TEXT_MESSAGE)]
#[Groups(['supplier:read', 'supplier:write:information'])]
private ?string $competitors = null;
#[ORM\Column(type: 'date_immutable', nullable: true)]
#[Groups(['supplier:read', 'supplier:write:information'])]
// Date de creation jamais dans le futur (retour metier ERP-193) : <= aujourd'hui.
#[Assert\LessThanOrEqual(value: 'today', message: 'La date de création ne peut pas être dans le futur.')]
// Format d'ENTREE strict ISO `Y-m-d` : sans lui, PHP DateTime accepte des
// formes ambigues (« 12/25/2026 », jugee invalide par MalioDate en JJ/MM/AAAA,
// serait lue en M/J -> 25 decembre et acceptee a tort). Avec le format, toute
@@ -212,12 +217,16 @@ class Supplier implements TimestampableInterface, BlamableInterface, SupplierInt
#[Groups(['supplier:read', 'supplier:write:information'])]
private ?int $employeesCount = null;
// Chiffre d'affaires plafonne a 999 999 999 999,99 (12 chiffres, retour metier
// ERP-193). La colonne (decimal 15,2) tolere plus, mais le metier borne la saisie.
#[ORM\Column(type: 'decimal', precision: 15, scale: 2, nullable: true)]
#[Assert\LessThanOrEqual(value: 999_999_999_999.99, message: 'Le chiffre d\'affaires ne peut pas dépasser 999 999 999 999,99.')]
#[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')]
#[Assert\Regex(pattern: TextInputPattern::PERSON_NAME, message: TextInputPattern::PERSON_NAME_MESSAGE)]
#[Groups(['supplier:read', 'supplier:write:information'])]
private ?string $directorName = null;
@@ -243,6 +252,7 @@ class Supplier implements TimestampableInterface, BlamableInterface, SupplierInt
#[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')]
#[Assert\Regex(pattern: TextInputPattern::CODE_ALNUM, message: TextInputPattern::CODE_ALNUM_MESSAGE)]
#[Groups(['supplier:read:accounting', 'supplier:write:accounting'])]
private ?string $accountNumber = null;
@@ -253,6 +263,7 @@ class Supplier implements TimestampableInterface, BlamableInterface, SupplierInt
#[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')]
#[Assert\Regex(pattern: TextInputPattern::CODE_ALNUM, message: TextInputPattern::CODE_ALNUM_MESSAGE)]
#[Groups(['supplier:read:accounting', 'supplier:write:accounting'])]
private ?string $nTva = null;
@@ -19,6 +19,7 @@ use App\Shared\Domain\Contract\SiteInterface;
use App\Shared\Domain\Contract\SupplierAddressInterface;
use App\Shared\Domain\Contract\TimestampableInterface;
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
use App\Shared\Domain\Validation\TextInputPattern;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
@@ -154,17 +155,20 @@ class SupplierAddress implements TimestampableInterface, BlamableInterface, Supp
#[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')]
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
#[Groups(['supplier:item:read', 'supplier:write:addresses', 'supplier_address:read'])]
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')]
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
#[Groups(['supplier:item:read', 'supplier:write:addresses', 'supplier_address:read'])]
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')]
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
#[Groups(['supplier:item:read', 'supplier:write:addresses', 'supplier_address:read'])]
private ?string $streetComplement = null;
@@ -16,6 +16,7 @@ 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 App\Shared\Domain\Validation\TextInputPattern;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Validator\Constraints as Assert;
@@ -99,16 +100,19 @@ class SupplierContact implements TimestampableInterface, BlamableInterface
// 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')]
#[Assert\Regex(pattern: TextInputPattern::PERSON_NAME, message: TextInputPattern::PERSON_NAME_MESSAGE)]
#[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')]
#[Assert\Regex(pattern: TextInputPattern::PERSON_NAME, message: TextInputPattern::PERSON_NAME_MESSAGE)]
#[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')]
#[Assert\Regex(pattern: TextInputPattern::FREE_TEXT, message: TextInputPattern::FREE_TEXT_MESSAGE)]
#[Groups(['supplier:item:read', 'supplier:write:contacts'])]
private ?string $jobTitle = null;
@@ -80,6 +80,9 @@ final class RbacSeeder
// Transporteurs (M4 § 5.2, ERP-153) : view + manage (PAS archive -> admin seul).
'transport.carriers.view',
'transport.carriers.manage',
// Tickets de pesee (M5 § 5.2, ERP-181) : view + manage (« Tout »).
'logistique.weighing_tickets.view',
'logistique.weighing_tickets.manage',
// Visibilite multi-site des prestataires (M3 § 2.13) : voit tous les sites.
'sites.bypass_scope',
// Lecture des referentiels transverses pour les selects client (ERP-102).
@@ -137,9 +140,14 @@ final class RbacSeeder
'label' => 'Usine',
// Prestataires (M3 § 2.9 + § 2.13, ERP-138) : view en lecture seule,
// SANS `sites.bypass_scope` -> cloisonne aux prestataires de son site
// courant. Aucun autre acces metier.
// courant.
'permissions' => [
'technique.providers.view',
// Tickets de pesee (M5 § 5.2, ERP-181) : view + manage. L'Usine
// pese sur site -> reste cloisonnee a son site courant (pas de
// bypass_scope ; les tickets sont filtres par SiteScopedQueryExtension).
'logistique.weighing_tickets.view',
'logistique.weighing_tickets.manage',
],
],
];
@@ -217,6 +217,10 @@ final class SeedE2ECommand extends Command
'transport.carriers.view',
'transport.carriers.manage',
'transport.carriers.archive',
// Logistique — Tickets de pesee (M5, ERP-181). Meme logique :
// mappe sur le persona "tout". Miroir de personas.ts.
'logistique.weighing_tickets.view',
'logistique.weighing_tickets.manage',
],
],
[
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Module\Logistique\Application\Service;
use App\Shared\Domain\Contract\SiteInterface;
/**
* Allocateur du compteur DSD du pont bascule (RG-5.04, § 2.7).
*
* Le DSD est un index sequentiel de pesee, propre a CHAQUE site (un pont par
* site). Chaque pesee bascule (AUTO) ou manuelle (MANUAL) consomme une
* valeur : la suivante = dernier DSD du site + 1.
*
* Port (interface en couche Application) ; l'implementation (DsdAllocator,
* Infrastructure) incremente le compteur sous verrou ligne `SELECT ... FOR
* UPDATE` pour garantir l'unicite en concurrence.
*/
interface DsdAllocatorInterface
{
/**
* Attribue et renvoie la prochaine valeur DSD pour le site (dernier + 1),
* en persistant l'increment de maniere atomique (verrou ligne).
*/
public function next(SiteInterface $site): int;
}
@@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
namespace App\Module\Logistique\Application\Service;
use App\Module\Logistique\Domain\Exception\InvalidImmatriculationException;
/**
* Normalisation serveur des champs texte d'un WeighingTicket, appliquee par le
* WeighingTicketProcessor AVANT persistance. Cf. spec-back M5 § 6 + RG-5.01 /
* RG-5.10. Jumeau leger de CarrierFieldNormalizer (M4).
*
* - immatriculation (RG-5.01 / RG-5.10) : trim + UPPER. Si « Tout format » N'EST
* PAS coche (freeFormat = false), la saisie est ramenee au masque SIV
* canonique XX-000-XX (separateurs/espaces ignores a la saisie, re-poses) ; une
* plaque qui ne s'y conforme pas leve InvalidImmatriculationException (-> 422
* par le Processor). En « Tout format » (anciennes plaques, etranger, engins),
* seul le trim + UPPER s'applique.
* - otherLabel (RG-5.03) : trim ; une chaine vide apres trim devient null (evite
* de persister "" dans une colonne nullable).
*
* Methodes null-safe : une entree null ressort null (l'obligation eventuelle est
* portee par les Assert de l'entite / la coherence contrepartie, pas ici).
*/
final class WeighingTicketFieldNormalizer
{
/**
* Plaque SIV « nue » (sans separateurs) : 2 lettres, 3 chiffres, 2 lettres.
* Les lettres interdites du SIV (I, O, U + SS) ne sont pas filtrees ici : le
* masque de saisie reste volontairement simple (le metier accepte ces cas via
* « Tout format » si besoin).
*/
private const string SIV_BARE_PATTERN = '/^[A-Z]{2}[0-9]{3}[A-Z]{2}$/';
/**
* Normalise l'immatriculation (RG-5.01 / RG-5.10).
*
* @param bool $freeFormat « Tout format » coche -> masque SIV desactive
*
* @throws InvalidImmatriculationException si !freeFormat et la plaque ne
* respecte pas le masque XX-000-XX
*/
public function normalizeImmatriculation(?string $value, bool $freeFormat): ?string
{
if (null === $value) {
return null;
}
$value = mb_strtoupper(trim($value), 'UTF-8');
if ('' === $value) {
return null;
}
// « Tout format » : aucune contrainte de masque (RG-5.01).
if ($freeFormat) {
return $value;
}
// Masque SIV : on ignore tout ce qui n'est pas alphanumerique (l'operateur
// peut saisir « ab123cd », « AB 123 CD » ou « AB-123-CD ») puis on valide
// le squelette 2-3-2 et on repose les separateurs canoniques.
$bare = preg_replace('/[^A-Z0-9]/', '', $value) ?? '';
if (1 !== preg_match(self::SIV_BARE_PATTERN, $bare)) {
throw new InvalidImmatriculationException(
'Format d\'immatriculation invalide : attendu XX-000-XX (cochez « Tout format » pour une plaque libre).',
);
}
return sprintf('%s-%s-%s', substr($bare, 0, 2), substr($bare, 2, 3), substr($bare, 5, 2));
}
/**
* Trim du libelle « Autre » (RG-5.03). Une chaine vide apres trim devient null.
*/
public function normalizeOtherLabel(?string $value): ?string
{
if (null === $value) {
return null;
}
$value = trim($value);
return '' === $value ? null : $value;
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Module\Logistique\Application\Service;
use App\Module\Sites\Domain\Entity\Site;
/**
* Allocateur du numero de ticket de pesee (RG-5.02, § 2.5).
*
* Le numero a le format {siteCode}-TP-{NNNN} (ex. 86-TP-0001), UNIQUE PAR SITE
* et immuable. Chaque site porte sa propre sequence : 86-TP-0001 et 17-TP-0001
* coexistent.
*
* Le code du site (prefixe) vit sur l'entite Site (site.code, ERP-183) — d'ou le
* type-hint sur Site concret (et non SiteInterface qui n'expose pas getCode()) ;
* c'est la meme reference ORM partagee que celle consommee par WeighingTicket
* (§ 2.1, pas de logique inter-module).
*
* Port (couche Application) ; l'implementation (WeighingTicketNumberAllocator,
* Infrastructure) incremente le compteur weighing_ticket_counter sous verrou ligne
* `SELECT ... FOR UPDATE` pour garantir l'unicite meme en concurrence.
*/
interface WeighingTicketNumberAllocatorInterface
{
/**
* Attribue et renvoie le prochain numero formate {siteCode}-TP-{NNNN} pour le
* site, en persistant l'increment de maniere atomique (verrou ligne).
*/
public function allocate(Site $site): string;
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Module\Logistique\Domain\Contract;
use App\Module\Logistique\Domain\Exception\WeighbridgeUnavailableException;
use App\Module\Logistique\Domain\Weighbridge\WeighbridgeReading;
use App\Shared\Domain\Contract\SiteInterface;
/**
* Contrat de lecture du pont bascule (§ 2.6).
*
* Abstraction posee au M5 pour decoupler l'API du materiel : l'implementation
* livree est un stub (RandomWeighbridgeReader, poids aleatoire [10000,50000]
* kg). Le driver materiel reel (protocole serie/TCP de l'indicateur de pesage)
* est hors perimetre M5 (HP-M5-02) : le jour venu on substitue l'implementation
* derriere cette interface zero impact sur les ecrans / l'API.
*/
interface WeighbridgeReaderInterface
{
/**
* Effectue une pesee « bascule » (AUTO) pour le site donne : renvoie le poids
* lu et le DSD (index de pesee du pont) attribue pour ce site (RG-5.04).
*
* @throws WeighbridgeUnavailableException si la bascule ne repond pas
* (le Processor traduit en HTTP 503
* bascule manuelle, RG-5.06)
*/
public function read(SiteInterface $site): WeighbridgeReading;
}
@@ -0,0 +1,557 @@
<?php
declare(strict_types=1);
namespace App\Module\Logistique\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\Domain\Entity\Client; // relation ORM partagee (§ 2.1)
use App\Module\Commercial\Domain\Entity\Supplier; // relation ORM partagee (§ 2.1)
use App\Module\Logistique\Infrastructure\ApiPlatform\State\Processor\WeighingTicketProcessor;
use App\Module\Logistique\Infrastructure\ApiPlatform\State\Provider\WeighingTicketProvider;
use App\Module\Logistique\Infrastructure\Doctrine\DoctrineWeighingTicketRepository;
use App\Module\Sites\Domain\Entity\Site; // relation ORM partagee (§ 2.1)
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 DateTimeImmutable;
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;
/**
* Ticket de pesee (M5 Logistique) entite racine du module, jumelle de
* Carrier (M4) / Supplier (M2) cote pattern (#[Auditable], TimestampableBlamable,
* contrat de serialisation 3 maillons). Porte EXACTEMENT deux pesees modelisees
* en colonnes plates (vide + plein, § 2.4), une contrepartie Client/Fournisseur/
* Autre (RG-5.03) et l'immatriculation partagee entre les deux formulaires
* (RG-5.01).
*
* Contrat de serialisation (RETEX M1, 3 maillons spec § 4.0) :
* - LISTE (weighing_ticket:read + client:read + supplier:read + site:read +
* default:read) : number, counterpartyType, client/supplier embarques,
* otherLabel, displayDate (= fullDate ?? emptyDate), netWeight,
* plateFreeFormat, createdAt/updatedAt (via default:read).
* - DETAIL (+ weighing_ticket:item:read) : ajoute site embarque, immatriculation
* et les deux pesees (empty* / full*).
*
* Champs renseignes SERVEUR (lecture seule cote API, sans groupe d'ecriture) :
* - number : numero {siteCode}-TP-{NNNN} attribue par le WeighingTicketProcessor
* (RG-5.02, immuable) ;
* - site : resolu depuis le site courant a la creation (CurrentSiteProvider,
* § 2.3), immuable (RG-5.09) ;
* - netWeight : poids net derive plein - vide, recalcule serveur (RG-5.05).
*
* Les RG inter-champs (RG-5.03 : champ associe a counterpartyType obligatoire)
* passent par une contrainte d'entite (Assert\Callback + ->atPath()) pour que
* chaque 422 porte un propertyPath exploitable par useFormErrors (mapping inline,
* pas un toast ERP-101). L'exclusivite « les autres champs forces nuls » est
* garantie par les CHECK Postgres (chk_wt_*_branch) + la normalisation du
* Processor (ERP-185). Pas de Delete, pas d'archive au M5 (§ 2.13).
*
* @see WeighingTicketProvider Lecture (liste paginee filtree site courant + item) ERP-185.
* @see WeighingTicketProcessor Ecriture (numerotation, normalisation, net) ERP-185.
*/
#[ApiResource(
operations: [
new GetCollection(
security: "is_granted('logistique.weighing_tickets.view')",
normalizationContext: ['groups' => [
'weighing_ticket:read',
'client:read',
'supplier:read',
'site:read',
'default:read',
]],
provider: WeighingTicketProvider::class,
),
new Get(
security: "is_granted('logistique.weighing_tickets.view')",
normalizationContext: ['groups' => [
'weighing_ticket:read',
'weighing_ticket:item:read',
'client:read',
'supplier:read',
'site:read',
'default:read',
]],
provider: WeighingTicketProvider::class,
),
new Post(
security: "is_granted('logistique.weighing_tickets.manage')",
normalizationContext: ['groups' => [
'weighing_ticket:read',
'weighing_ticket:item:read',
'client:read',
'supplier:read',
'site:read',
'default:read',
]],
denormalizationContext: ['groups' => ['weighing_ticket:write']],
processor: WeighingTicketProcessor::class,
),
new Patch(
security: "is_granted('logistique.weighing_tickets.manage')",
normalizationContext: ['groups' => [
'weighing_ticket:read',
'weighing_ticket:item:read',
'client:read',
'supplier:read',
'site:read',
'default:read',
]],
denormalizationContext: ['groups' => ['weighing_ticket:write']],
provider: WeighingTicketProvider::class,
processor: WeighingTicketProcessor::class,
),
// Pas de Delete au M5 (HP-M5-05). Pas d'archive (hors docx).
],
)]
#[ORM\Entity(repositoryClass: DoctrineWeighingTicketRepository::class)]
#[ORM\Table(name: 'weighing_ticket')]
#[ORM\Index(name: 'idx_wt_site', columns: ['site_id'])]
#[ORM\Index(name: 'idx_wt_client', columns: ['client_id'])]
#[ORM\Index(name: 'idx_wt_supplier', columns: ['supplier_id'])]
#[ORM\Index(name: 'idx_wt_deleted_at', columns: ['deleted_at'])]
#[ORM\Index(name: 'idx_wt_created_by', columns: ['created_by'])]
#[ORM\Index(name: 'idx_wt_updated_by', columns: ['updated_by'])]
#[ORM\UniqueConstraint(name: 'uq_weighing_ticket_number', columns: ['site_id', 'number'])]
#[Auditable]
class WeighingTicket implements TimestampableInterface, BlamableInterface
{
use TimestampableBlamableTrait;
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[Groups(['weighing_ticket:read'])]
private ?int $id = null;
/** Numero {siteCode}-TP-{NNNN} — attribue serveur, lecture seule, immuable (RG-5.02). */
#[ORM\Column(length: 20)]
#[Groups(['weighing_ticket:read'])]
private ?string $number = null;
/** Site du pont bascule — resolu serveur depuis le site courant, immuable (§ 2.3 / RG-5.09). */
#[ORM\ManyToOne(targetEntity: Site::class)]
#[ORM\JoinColumn(name: 'site_id', nullable: false, onDelete: 'RESTRICT')]
#[Groups(['weighing_ticket:item:read'])]
private ?Site $site = null;
/** CLIENT | FOURNISSEUR | AUTRE (RG-5.03) — pilote le champ associe obligatoire. */
#[ORM\Column(name: 'counterparty_type', length: 12)]
#[Assert\NotBlank(message: 'La contrepartie (Client / Fournisseur / Autre) est obligatoire.')]
#[Assert\Choice(choices: ['CLIENT', 'FOURNISSEUR', 'AUTRE'], message: 'Type de contrepartie invalide.')]
#[Groups(['weighing_ticket:read', 'weighing_ticket:write'])]
private ?string $counterpartyType = null;
/** Requis ssi counterpartyType = CLIENT (validateCounterpartyConsistency, RG-5.03). */
#[ORM\ManyToOne(targetEntity: Client::class)]
#[ORM\JoinColumn(name: 'client_id', nullable: true, onDelete: 'RESTRICT')]
#[Groups(['weighing_ticket:read', 'weighing_ticket:write'])]
private ?Client $client = null;
/** Requis ssi counterpartyType = FOURNISSEUR (RG-5.03). */
#[ORM\ManyToOne(targetEntity: Supplier::class)]
#[ORM\JoinColumn(name: 'supplier_id', nullable: true, onDelete: 'RESTRICT')]
#[Groups(['weighing_ticket:read', 'weighing_ticket:write'])]
private ?Supplier $supplier = null;
/** Libelle libre — requis ssi counterpartyType = AUTRE (RG-5.03). */
#[ORM\Column(name: 'other_label', length: 255, nullable: true)]
#[Assert\Length(max: 255, maxMessage: 'Le libellé ne peut pas dépasser {{ limit }} caractères.', normalizer: 'trim')]
#[Groups(['weighing_ticket:read', 'weighing_ticket:write'])]
private ?string $otherLabel = null;
/** Plaque du vehicule, partagee entre les 2 formulaires (RG-5.01). Masque XX-000-XX sauf plateFreeFormat. */
#[ORM\Column(length: 20)]
#[Assert\NotBlank(message: 'L\'immatriculation est obligatoire.', normalizer: 'trim')]
#[Assert\Length(max: 20, maxMessage: 'L\'immatriculation ne peut pas dépasser {{ limit }} caractères.', normalizer: 'trim')]
#[Groups(['weighing_ticket:item:read', 'weighing_ticket:write'])]
private ?string $immatriculation = null;
// « Tout format » : desactive le masque XX-000-XX (RG-5.01). Le groupe de
// LECTURE est porte par le getter isPlateFreeFormat() (+ SerializedName,
// piege booleen #3 M1) ; le groupe d'ECRITURE vit ici pour cibler le setter.
#[ORM\Column(name: 'plate_free_format', options: ['default' => false])]
#[Groups(['weighing_ticket:write'])]
private bool $plateFreeFormat = false;
// === Pesee a vide (§ 2.4) ===
#[ORM\Column(name: 'empty_date', type: 'datetime_immutable', nullable: true)]
#[Groups(['weighing_ticket:item:read', 'weighing_ticket:write'])]
private ?DateTimeImmutable $emptyDate = null;
/** Poids a vide (tare) en kg — readonly UI, rempli par la pesee (RG-5.07). */
#[ORM\Column(name: 'empty_weight', nullable: true)]
#[Groups(['weighing_ticket:item:read', 'weighing_ticket:write'])]
private ?int $emptyWeight = null;
#[ORM\Column(name: 'empty_dsd', nullable: true)]
#[Groups(['weighing_ticket:item:read', 'weighing_ticket:write'])]
private ?int $emptyDsd = null;
/** AUTO (pont bascule) | MANUAL (saisie) — chk_wt_empty_mode (RG-5.06). */
#[ORM\Column(name: 'empty_mode', length: 8, nullable: true)]
#[Assert\Choice(choices: ['AUTO', 'MANUAL'], message: 'Mode de pesée invalide.')]
#[Groups(['weighing_ticket:item:read', 'weighing_ticket:write'])]
private ?string $emptyMode = null;
/** Numero de pesee saisi en manuelle (distinct du DSD) — RG-5.04. */
#[ORM\Column(name: 'empty_manual_number', length: 50, nullable: true)]
#[Assert\Length(max: 50, maxMessage: 'Le numéro de pesée ne peut pas dépasser {{ limit }} caractères.', normalizer: 'trim')]
#[Groups(['weighing_ticket:item:read', 'weighing_ticket:write'])]
private ?string $emptyManualNumber = null;
// === Pesee a plein (§ 2.4) ===
#[ORM\Column(name: 'full_date', type: 'datetime_immutable', nullable: true)]
#[Groups(['weighing_ticket:item:read', 'weighing_ticket:write'])]
private ?DateTimeImmutable $fullDate = null;
/** Poids a plein (brut) en kg — readonly UI, rempli par la pesee (RG-5.07). */
#[ORM\Column(name: 'full_weight', nullable: true)]
#[Groups(['weighing_ticket:item:read', 'weighing_ticket:write'])]
private ?int $fullWeight = null;
#[ORM\Column(name: 'full_dsd', nullable: true)]
#[Groups(['weighing_ticket:item:read', 'weighing_ticket:write'])]
private ?int $fullDsd = null;
/** AUTO (pont bascule) | MANUAL (saisie) — chk_wt_full_mode (RG-5.06). */
#[ORM\Column(name: 'full_mode', length: 8, nullable: true)]
#[Assert\Choice(choices: ['AUTO', 'MANUAL'], message: 'Mode de pesée invalide.')]
#[Groups(['weighing_ticket:item:read', 'weighing_ticket:write'])]
private ?string $fullMode = null;
/** Numero de pesee saisi en manuelle (distinct du DSD) — RG-5.04. */
#[ORM\Column(name: 'full_manual_number', length: 50, nullable: true)]
#[Assert\Length(max: 50, maxMessage: 'Le numéro de pesée ne peut pas dépasser {{ limit }} caractères.', normalizer: 'trim')]
#[Groups(['weighing_ticket:item:read', 'weighing_ticket:write'])]
private ?string $fullManualNumber = null;
/** Poids net derive plein - vide (kg) — calcule serveur (RG-5.05). Colonne Poids de la liste. */
#[ORM\Column(name: 'net_weight', nullable: true)]
#[Groups(['weighing_ticket:read'])]
private ?int $netWeight = null;
/** Soft-delete technique prepare mais non expose au M5 (§ 2.13) — pas de groupe. */
#[ORM\Column(name: 'deleted_at', type: 'datetime_immutable', nullable: true)]
private ?DateTimeImmutable $deletedAt = null;
/**
* Coherence de la contrepartie (RG-5.03). Decision figee (miroir M4
* validateMainFormConsistency) : porte par une contrainte d'entite
* (Assert\Callback + ->atPath()) pour que chaque 422 soit mappee inline sous
* le champ par useFormErrors (pas un toast ERP-101). Jouee par API Platform
* AVANT le Processor, sur POST comme sur PATCH.
*
* Ne valide ICI que la PRESENCE du champ associe au type. L'exclusivite
* « les autres champs forces nuls » est garantie par les CHECK Postgres
* (chk_wt_*_branch) et la normalisation du Processor (qui null-ifie les
* champs hors-branche ERP-185).
*/
#[Assert\Callback]
public function validateCounterpartyConsistency(ExecutionContextInterface $context): void
{
switch ($this->counterpartyType) {
case 'CLIENT':
if (null === $this->client) {
$context->buildViolation('Le client est obligatoire pour une contrepartie « Client ».')
->atPath('client')
->addViolation()
;
}
break;
case 'FOURNISSEUR':
if (null === $this->supplier) {
$context->buildViolation('Le fournisseur est obligatoire pour une contrepartie « Fournisseur ».')
->atPath('supplier')
->addViolation()
;
}
break;
case 'AUTRE':
if (null === $this->otherLabel || '' === trim($this->otherLabel)) {
$context->buildViolation('Le libellé est obligatoire pour une contrepartie « Autre ».')
->atPath('otherLabel')
->addViolation()
;
}
break;
}
}
/**
* Date du ticket affichee en LISTE (§ 4.0) : date de la pesee a plein si
* disponible, sinon date de la pesee a vide. Getter calcule (jamais
* persiste), expose en lecture seule.
*/
#[Groups(['weighing_ticket:read'])]
public function getDisplayDate(): ?DateTimeImmutable
{
return $this->fullDate ?? $this->emptyDate;
}
public function getId(): ?int
{
return $this->id;
}
public function getNumber(): ?string
{
return $this->number;
}
public function setNumber(?string $number): static
{
$this->number = $number;
return $this;
}
public function getSite(): ?Site
{
return $this->site;
}
public function setSite(?Site $site): static
{
$this->site = $site;
return $this;
}
public function getCounterpartyType(): ?string
{
return $this->counterpartyType;
}
public function setCounterpartyType(?string $counterpartyType): static
{
$this->counterpartyType = $counterpartyType;
return $this;
}
public function getClient(): ?Client
{
return $this->client;
}
public function setClient(?Client $client): static
{
$this->client = $client;
return $this;
}
public function getSupplier(): ?Supplier
{
return $this->supplier;
}
public function setSupplier(?Supplier $supplier): static
{
$this->supplier = $supplier;
return $this;
}
public function getOtherLabel(): ?string
{
return $this->otherLabel;
}
public function setOtherLabel(?string $otherLabel): static
{
$this->otherLabel = $otherLabel;
return $this;
}
public function getImmatriculation(): ?string
{
return $this->immatriculation;
}
public function setImmatriculation(?string $immatriculation): static
{
$this->immatriculation = $immatriculation;
return $this;
}
// Piege booleen (RETEX M1 #3) : #[Groups] + #[SerializedName] sur le getter,
// sinon Symfony strip le prefixe « is » et drope la cle plateFreeFormat du JSON.
#[Groups(['weighing_ticket:read'])]
#[SerializedName('plateFreeFormat')]
public function isPlateFreeFormat(): bool
{
return $this->plateFreeFormat;
}
public function setPlateFreeFormat(bool $plateFreeFormat): static
{
$this->plateFreeFormat = $plateFreeFormat;
return $this;
}
public function getEmptyDate(): ?DateTimeImmutable
{
return $this->emptyDate;
}
public function setEmptyDate(?DateTimeImmutable $emptyDate): static
{
$this->emptyDate = $emptyDate;
return $this;
}
public function getEmptyWeight(): ?int
{
return $this->emptyWeight;
}
public function setEmptyWeight(?int $emptyWeight): static
{
$this->emptyWeight = $emptyWeight;
return $this;
}
public function getEmptyDsd(): ?int
{
return $this->emptyDsd;
}
public function setEmptyDsd(?int $emptyDsd): static
{
$this->emptyDsd = $emptyDsd;
return $this;
}
public function getEmptyMode(): ?string
{
return $this->emptyMode;
}
public function setEmptyMode(?string $emptyMode): static
{
$this->emptyMode = $emptyMode;
return $this;
}
public function getEmptyManualNumber(): ?string
{
return $this->emptyManualNumber;
}
public function setEmptyManualNumber(?string $emptyManualNumber): static
{
$this->emptyManualNumber = $emptyManualNumber;
return $this;
}
public function getFullDate(): ?DateTimeImmutable
{
return $this->fullDate;
}
public function setFullDate(?DateTimeImmutable $fullDate): static
{
$this->fullDate = $fullDate;
return $this;
}
public function getFullWeight(): ?int
{
return $this->fullWeight;
}
public function setFullWeight(?int $fullWeight): static
{
$this->fullWeight = $fullWeight;
return $this;
}
public function getFullDsd(): ?int
{
return $this->fullDsd;
}
public function setFullDsd(?int $fullDsd): static
{
$this->fullDsd = $fullDsd;
return $this;
}
public function getFullMode(): ?string
{
return $this->fullMode;
}
public function setFullMode(?string $fullMode): static
{
$this->fullMode = $fullMode;
return $this;
}
public function getFullManualNumber(): ?string
{
return $this->fullManualNumber;
}
public function setFullManualNumber(?string $fullManualNumber): static
{
$this->fullManualNumber = $fullManualNumber;
return $this;
}
public function getNetWeight(): ?int
{
return $this->netWeight;
}
public function setNetWeight(?int $netWeight): static
{
$this->netWeight = $netWeight;
return $this;
}
public function getDeletedAt(): ?DateTimeImmutable
{
return $this->deletedAt;
}
public function setDeletedAt(?DateTimeImmutable $deletedAt): static
{
$this->deletedAt = $deletedAt;
return $this;
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Module\Logistique\Domain\Exception;
use RuntimeException;
/**
* Levee quand une immatriculation ne respecte pas le masque SIV XX-000-XX alors
* que « Tout format » n'est PAS coche (plateFreeFormat = false, RG-5.01).
*
* Exception de DOMAINE (pure, sans dependance HTTP) levee par le
* WeighingTicketFieldNormalizer : c'est le WeighingTicketProcessor qui la traduit
* en 422 portant un propertyPath « immatriculation » (mapping inline useFormErrors,
* convention ERP-101) plutot qu'un toast.
*/
final class InvalidImmatriculationException extends RuntimeException {}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Module\Logistique\Domain\Exception;
use RuntimeException;
/**
* Levee lorsque le pont bascule ne repond pas / est indisponible (RG-5.06).
*
* Exception de DOMAINE (pure, sans dependance HTTP) : c'est le Processor de
* l'endpoint de pesee qui la traduit en reponse HTTP 503 « Pont bascule
* indisponible passez en pesee manuelle » (cf. WeighbridgeReadingProcessor).
*
* Au M5, le stub (RandomWeighbridgeReader) ne la leve jamais, mais le chemin
* d'erreur est implemente et teste pour le jour ou un driver materiel reel
* (HP-M5-02) sera branche derriere WeighbridgeReaderInterface.
*/
final class WeighbridgeUnavailableException extends RuntimeException {}

Some files were not shown because too many files have changed in this diff Show More