Compare commits
67 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5f2aa5334b | |||
| 21b1c64a5f | |||
| fd89160c4b | |||
| 8daf0ff5d4 | |||
| 87c53c354b | |||
| f8b45cb30b | |||
| 0c0b57f898 | |||
| c18566124a | |||
| f767733b87 | |||
| 40da5dfb31 | |||
| d304b74289 | |||
| 80b3741f64 | |||
| c468374b16 | |||
| 7ddf495d7f | |||
| 9fcf5c24f6 | |||
| 76fb01c063 | |||
| e76bd1dd63 | |||
| 498cef8cc0 | |||
| 7668d77c78 | |||
| 1d5110d000 | |||
| b6b5bb06e8 | |||
| fb9c15c52a | |||
| c371057c0b | |||
| e1712465f1 | |||
| 5125883e21 | |||
| 6ff5b13ce2 | |||
| 5bbd4ddb47 | |||
| a26bb09ee1 | |||
| 20296ac149 | |||
| 07e0bcbcce | |||
| fe1d012548 | |||
| d86dc69cf2 | |||
| 07ed57f283 | |||
| b5749520bc | |||
| 02d2fde653 | |||
| 0d284fe488 | |||
| 48ca963a9d | |||
| b11968f5e5 | |||
| 5109b5f57a | |||
| d5a01ac85f | |||
| 7adf3a511a | |||
| e612eae391 | |||
| f29266e5e8 | |||
| f27db02cb6 | |||
| 5765ba7178 | |||
| ef996c3672 | |||
| c6259a96cd | |||
| 726be37ccf | |||
| 40fdded7e2 | |||
| 4202977950 | |||
| 45158af920 | |||
| c09b3cda2b | |||
| 0733a239a8 | |||
| cf645493c1 | |||
| 388d39a379 | |||
| d6d2144cc1 | |||
| 6a519874ed | |||
| 3804362546 | |||
| 9864dbc00f | |||
| be03f4e51a | |||
| 8cc2cea444 | |||
| f70e701854 | |||
| f1b18cfbbe | |||
| 5734aaef54 | |||
| 597c63bb2e | |||
| 8046de76c6 | |||
| 1ef4215ebf |
@@ -56,7 +56,10 @@ jobs:
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '8.4'
|
||||
extensions: pdo, pdo_pgsql, intl, opcache, zip, mbstring, sodium
|
||||
# gd requis par phpoffice/phpspreadsheet (export XLSX). Doit etre explicite :
|
||||
# sinon `composer install` echoue sur la verification de plateforme des que
|
||||
# le runner ne fournit pas l'extension par defaut (ext-gd manquante).
|
||||
extensions: pdo, pdo_pgsql, intl, opcache, zip, mbstring, sodium, gd
|
||||
coverage: none
|
||||
tools: composer:v2
|
||||
|
||||
|
||||
+13
-18
@@ -78,23 +78,6 @@ return [
|
||||
],
|
||||
],
|
||||
],
|
||||
// Section "Transport" (M4, ERP-153) : pole logistique, porte le repertoire
|
||||
// transporteurs. L'item est gate par `transport.carriers.view` ; la section
|
||||
// disparait automatiquement (SidebarProvider) si le module `transport` est
|
||||
// desactive ou si l'user n'a pas la permission (Compta / Usine).
|
||||
[
|
||||
'label' => 'sidebar.transport.section',
|
||||
'icon' => 'mdi:truck-outline',
|
||||
'items' => [
|
||||
[
|
||||
'label' => 'sidebar.transport.carriers',
|
||||
'to' => '/carriers',
|
||||
'icon' => 'mdi:truck-outline',
|
||||
'module' => 'transport',
|
||||
'permission' => 'transport.carriers.view',
|
||||
],
|
||||
],
|
||||
],
|
||||
// Section "Administration" : regroupe toutes les pages de configuration
|
||||
// applicative (RBAC, users, sites, audit log).
|
||||
//
|
||||
@@ -117,8 +100,20 @@ return [
|
||||
// individuelles"), ajouter : 'permission' => 'core.admin.access'.
|
||||
[
|
||||
'label' => 'sidebar.administration.section',
|
||||
'icon' => 'mdi:cog-outline',
|
||||
'icon' => 'mdi:file-settings-cog-outline',
|
||||
'items' => [
|
||||
// Transport — Repertoire transporteurs (M4, ERP-164). Rattache a
|
||||
// l'Administration (premier item) plutot qu'a une section dediee :
|
||||
// referentiel global de configuration applicative, sans cloisonnement
|
||||
// par site. Reste gate par sa propre permission `transport.carriers.view`
|
||||
// (Admin / Bureau / Commerciale) et son module owner `transport`.
|
||||
[
|
||||
'label' => 'sidebar.transport.carriers',
|
||||
'to' => '/carriers',
|
||||
'icon' => 'mdi:truck-outline',
|
||||
'module' => 'transport',
|
||||
'permission' => 'transport.carriers.view',
|
||||
],
|
||||
[
|
||||
'label' => 'sidebar.core.roles',
|
||||
'to' => '/admin/roles',
|
||||
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
parameters:
|
||||
app.version: '0.1.129'
|
||||
app.version: '0.1.138'
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
# Donnees extraites de Mixgraine : raisons sociales, contacts, adresses,
|
||||
# n TVA et coordonnees bancaires (IBAN/BIC) reelles. NE JAMAIS committer.
|
||||
# Reproductible localement via `MIXGRAINE_JWT=... ./run.sh`.
|
||||
mixgraine-export/
|
||||
@@ -1,80 +0,0 @@
|
||||
# Migration Mixgraine → Starseed — Outils
|
||||
|
||||
Boîte à outils pour migrer les tiers (clients / fournisseurs / prestataires) depuis
|
||||
le CRM Mixgraine vers Starseed. Tout est autonome : 2 scripts Python + ce README.
|
||||
|
||||
| Fichier | Rôle |
|
||||
|---|---|
|
||||
| `mixgraine-migration-analysis.md` | Rapport d'analyse + mapping des champs (à lire en premier) |
|
||||
| `extract_mixgraine.py` | Récupère les tiers depuis l'API Mixgraine et les normalise en JSON |
|
||||
| `build_tiers_xlsx.py` | Produit un Excel avec **un onglet par type** + filtre « Site manquant » |
|
||||
| `run.sh` | Enchaîne les deux scripts |
|
||||
|
||||
---
|
||||
|
||||
## Prérequis
|
||||
|
||||
- **Python 3** (déjà présent sur un poste Linux/Mac) — vérifier : `python3 --version`
|
||||
- **openpyxl** (pour les Excel) : `pip install openpyxl` (ou `pip install --break-system-packages openpyxl`)
|
||||
- Un **token Mixgraine** (JWT) valide — voir ci-dessous.
|
||||
|
||||
### Récupérer le token Mixgraine
|
||||
|
||||
1. Ouvrir `https://liot.mixsuite.fr` dans Chrome, connecté.
|
||||
2. Ouvrir les outils dev (F12) → onglet **Network**.
|
||||
3. Cliquer sur n'importe quelle liste (clients…) pour déclencher un appel `api/customer`.
|
||||
4. Cliquer sur la requête → **Headers** → copier la valeur après `authorization: Bearer ` (la longue chaîne `eyJ0eXAi...`).
|
||||
|
||||
> Le token expire au bout de quelques jours. S'il est expiré, en récupérer un nouveau de la même façon. **Ne jamais le committer dans git.**
|
||||
|
||||
---
|
||||
|
||||
## Lancement
|
||||
|
||||
### Méthode simple (script tout-en-un)
|
||||
|
||||
```bash
|
||||
cd docs/migration
|
||||
export MIXGRAINE_JWT="eyJ0eXAi...colle-ton-token-ici..."
|
||||
./run.sh
|
||||
```
|
||||
|
||||
### Ou étape par étape
|
||||
|
||||
```bash
|
||||
cd docs/migration
|
||||
export MIXGRAINE_JWT="eyJ0eXAi..."
|
||||
|
||||
# 1) Extraction + normalisation (lent : ~1 requête/seconde, soyez patient)
|
||||
python3 extract_mixgraine.py
|
||||
# -> écrit dans ./mixgraine-export/ : clients.json, suppliers.json,
|
||||
# providers.json, referentials.json, extraction-report.txt
|
||||
# Test rapide sur 20 tiers : python3 extract_mixgraine.py --limit-ids 20
|
||||
|
||||
# 2) Génération de l'Excel de relecture (un onglet par type)
|
||||
python3 build_tiers_xlsx.py --in mixgraine-export
|
||||
# -> mixgraine-export/mixgraine-tiers.xlsx
|
||||
# onglets Clients / Fournisseurs / Prestataires + Synthèse,
|
||||
# colonne « Site manquant » filtrable, lignes à problème surlignées
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ce que tu obtiens
|
||||
|
||||
Tout est écrit dans `docs/migration/mixgraine-export/` :
|
||||
|
||||
- **`*.json`** — données normalisées au format Starseed (utilisées plus tard par les commandes d'import).
|
||||
- **`mixgraine-tiers.xlsx`** — un onglet par type (**Clients / Fournisseurs / Prestataires**) + un onglet **Synthèse**. Chaque onglet liste toutes les données (une ligne par adresse), avec une colonne **Site manquant** (OUI/vide) et une colonne **Problèmes**. Le **filtre automatique** est activé : clique l'entonnoir de la colonne « Site manquant » → coche `OUI` pour isoler les adresses sans site.
|
||||
- **`extraction-report.txt`** — compteurs + avertissements.
|
||||
- **`cache/`** — réponses brutes par tiers (permet de relancer sans tout refetch).
|
||||
|
||||
**Workflow conseillé** : ouvrir `mixgraine-tiers.xlsx`, filtrer « Site manquant = OUI » dans chaque onglet, corriger la donnée **à la source dans Mixgraine** (re-cocher les organisations/sites, compléter les emails de facturation), puis relancer (le cache accélère).
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- L'extraction est **reprenable** : si elle s'interrompt, relance-la, elle repart du cache.
|
||||
- Le débit est volontairement lent (`--delay 1.0` par défaut) pour ne pas saturer le serveur. Pour aller plus vite (à tes risques) : `--delay 0.3`.
|
||||
- Le dossier `mixgraine-export/` n'a pas vocation à être committé (données + token-sensible). Pense à l'ajouter au `.gitignore` si besoin.
|
||||
@@ -1,201 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Construit UN classeur Excel de relecture a partir des JSON produits par
|
||||
extract_mixgraine.py, avec UN ONGLET PAR TYPE :
|
||||
|
||||
- Clients
|
||||
- Fournisseurs
|
||||
- Prestataires
|
||||
- Synthese (compteurs)
|
||||
|
||||
Chaque onglet liste TOUTES les donnees, une ligne par adresse (les colonnes du
|
||||
tiers sont repetees). Une colonne « Site manquant » (OUI / vide) + le filtre
|
||||
automatique Excel permettent de trier en un clic les adresses sans site
|
||||
(obligatoire cote Starseed — RG-1.10 / 2.06 / 3.03). Les lignes a probleme sont
|
||||
surlignees en rouge clair.
|
||||
|
||||
Usage :
|
||||
pip install openpyxl
|
||||
python3 build_tiers_xlsx.py --in mixgraine-export
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from collections import Counter
|
||||
|
||||
try:
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, PatternFill, Alignment
|
||||
from openpyxl.utils import get_column_letter
|
||||
except ImportError:
|
||||
sys.exit("Dependance manquante : pip install openpyxl")
|
||||
|
||||
|
||||
# Compatibilite : les JSON deja generes portent la cle "lauttreeId" ;
|
||||
# les extractions ulterieures porteront "mixgraineId".
|
||||
def tid(t):
|
||||
return t.get("mixgraineId") or t.get("lauttreeId")
|
||||
|
||||
|
||||
def address_problems(addr, target):
|
||||
pb = []
|
||||
if not addr.get("sites"):
|
||||
pb.append("aucun site")
|
||||
if not addr.get("postalCode"):
|
||||
pb.append("code postal absent/invalide")
|
||||
if not addr.get("city"):
|
||||
pb.append("ville absente")
|
||||
if not addr.get("street"):
|
||||
pb.append("rue absente")
|
||||
if target == "Client" and addr.get("isBilling") and not addr.get("billingEmail"):
|
||||
pb.append("facturation sans email")
|
||||
return pb
|
||||
|
||||
|
||||
def tiers_problems(t, target):
|
||||
pb = []
|
||||
if not t.get("companyName"):
|
||||
pb.append("nom absent")
|
||||
if t.get("paymentType") == "VIREMENT" and not t.get("bank"):
|
||||
pb.append("VIREMENT sans banque")
|
||||
if t.get("paymentType") == "LCR" and not t.get("ribs"):
|
||||
pb.append("LCR sans RIB")
|
||||
if target == "Provider" and not t.get("sites"):
|
||||
pb.append("prestataire sans site")
|
||||
if t.get("categories") == ["A QUALIFIER"]:
|
||||
pb.append("categorie a qualifier")
|
||||
return pb
|
||||
|
||||
|
||||
# Colonnes communes (tiers). La colonne « Sites prestataire » n'existe QUE dans
|
||||
# l'onglet Prestataires (le site y est porte par le tiers, RG-3.03). Pour Clients
|
||||
# et Fournisseurs, le site est uniquement au niveau adresse (« Sites adresse »).
|
||||
TIERS_COLS = [
|
||||
"Réf.", "Société", "Catégories", "Mode paiement", "Banque", "N° TVA",
|
||||
"N° compte", "Distributeur", "Courtier", "Nb contacts", "Nb RIB",
|
||||
]
|
||||
ADDR_COLS = [
|
||||
"Rue", "Complément", "Code postal", "Ville", "Pays", "Sites adresse",
|
||||
"Facturation", "Email facturation", "Site manquant", "Problèmes tiers",
|
||||
]
|
||||
|
||||
|
||||
def headers_for(target):
|
||||
cols = list(TIERS_COLS)
|
||||
if target == "Provider":
|
||||
cols.append("Sites prestataire")
|
||||
return cols + ADDR_COLS
|
||||
|
||||
|
||||
HEADER_FILL = PatternFill("solid", fgColor="222783")
|
||||
HEADER_FONT = Font(bold=True, color="FFFFFF")
|
||||
BAD_FILL = PatternFill("solid", fgColor="FCE4E4") # rouge clair (probleme)
|
||||
WARN_FILL = PatternFill("solid", fgColor="FFF4D6") # orange clair (site manquant)
|
||||
|
||||
|
||||
def row_for(t, target, addr):
|
||||
pbt = " ; ".join(tiers_problems(t, target))
|
||||
base = [
|
||||
tid(t), t.get("companyName"), ", ".join(t.get("categories") or []),
|
||||
t.get("paymentType") or "", t.get("bank") or "", t.get("nTva") or "",
|
||||
t.get("accountNumber") or "", t.get("distributorName") or "",
|
||||
t.get("brokerName") or "", len(t.get("contacts", [])), len(t.get("ribs", [])),
|
||||
]
|
||||
if target == "Provider":
|
||||
base.append(", ".join(t.get("sites") or []))
|
||||
if addr is None:
|
||||
return base + ["", "", "", "", "", "", "", "", "(pas d'adresse)", pbt]
|
||||
site_missing = "OUI" if not addr.get("sites") else ""
|
||||
return base + [
|
||||
addr.get("street") or "", addr.get("streetComplement") or "",
|
||||
addr.get("postalCode") or "", addr.get("city") or "",
|
||||
addr.get("country") or "", ", ".join(addr.get("sites") or []),
|
||||
"oui" if addr.get("isBilling") else "", addr.get("billingEmail") or "",
|
||||
site_missing, pbt,
|
||||
]
|
||||
|
||||
|
||||
def build_sheet(wb, title, data, target):
|
||||
headers = headers_for(target)
|
||||
site_col = headers.index("Site manquant") + 1
|
||||
prob_col = len(headers)
|
||||
ws = wb.create_sheet(title=title)
|
||||
ws.append(headers)
|
||||
for c in range(1, len(headers) + 1):
|
||||
cell = ws.cell(row=1, column=c)
|
||||
cell.fill = HEADER_FILL
|
||||
cell.font = HEADER_FONT
|
||||
cell.alignment = Alignment(vertical="center")
|
||||
rows = []
|
||||
for t in data:
|
||||
for a in (t.get("addresses") or [None]):
|
||||
rows.append((row_for(t, target, a), address_problems(a, target) if a else ["aucune adresse"]))
|
||||
for values, pbs in rows:
|
||||
ws.append(values)
|
||||
r = ws.max_row
|
||||
if values[site_col - 1] == "OUI":
|
||||
ws.cell(row=r, column=site_col).fill = WARN_FILL
|
||||
if pbs or values[-1]:
|
||||
ws.cell(row=r, column=prob_col).fill = BAD_FILL
|
||||
# filtre + gel des en-tetes + largeurs
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(headers))}{ws.max_row}"
|
||||
ws.freeze_panes = "A2"
|
||||
for c, h in enumerate(headers, 1):
|
||||
sample = [len(str(h))] + [len(str(v[c - 1])) for v, _ in rows[:300]]
|
||||
ws.column_dimensions[get_column_letter(c)].width = min(max(max(sample) + 2, 10), 50)
|
||||
return len(rows)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Excel par type (Clients/Fournisseurs/Prestataires) + filtre site manquant")
|
||||
ap.add_argument("--in", dest="indir", default="mixgraine-export", help="dossier des JSON")
|
||||
ap.add_argument("--out", default=None, help="chemin du xlsx (defaut: <in>/mixgraine-tiers.xlsx)")
|
||||
args = ap.parse_args()
|
||||
|
||||
def load(name):
|
||||
path = os.path.join(args.indir, name)
|
||||
return json.load(open(path, encoding="utf-8")) if os.path.exists(path) else []
|
||||
|
||||
sources = [
|
||||
("Clients", load("clients.json"), "Client"),
|
||||
("Fournisseurs", load("suppliers.json"), "Supplier"),
|
||||
("Prestataires", load("providers.json"), "Provider"),
|
||||
]
|
||||
|
||||
wb = Workbook()
|
||||
wb.remove(wb.active)
|
||||
summary = []
|
||||
for title, data, target in sources:
|
||||
n_rows = build_sheet(wb, title, data, target)
|
||||
n_tiers = len(data)
|
||||
n_addr_missing = sum(1 for t in data for a in (t.get("addresses") or []) if not a.get("sites"))
|
||||
n_nocat = sum(1 for t in data if t.get("categories") == ["A QUALIFIER"])
|
||||
summary.append((title, n_tiers, n_rows, n_addr_missing, n_nocat))
|
||||
|
||||
# onglet Synthese
|
||||
ws = wb.create_sheet(title="Synthèse")
|
||||
sh = ["Type", "Tiers", "Lignes (adresses)", "Adresses sans site", "Sans catégorie"]
|
||||
ws.append(sh)
|
||||
for c in range(1, len(sh) + 1):
|
||||
ws.cell(row=1, column=c).fill = HEADER_FILL
|
||||
ws.cell(row=1, column=c).font = HEADER_FONT
|
||||
for r in summary:
|
||||
ws.append(list(r))
|
||||
for c in range(1, len(sh) + 1):
|
||||
ws.column_dimensions[get_column_letter(c)].width = 20
|
||||
# place la synthese en premier
|
||||
wb.move_sheet("Synthèse", -(len(wb.sheetnames) - 1))
|
||||
|
||||
out = args.out or os.path.join(args.indir, "mixgraine-tiers.xlsx")
|
||||
wb.save(out)
|
||||
print(f"Ecrit : {out}")
|
||||
print(f"{'Type':14}{'Tiers':>7}{'Lignes':>8}{'AdrSansSite':>13}{'SansCat':>9}")
|
||||
for title, n_tiers, n_rows, n_miss, n_nocat in summary:
|
||||
print(f"{title:14}{n_tiers:7}{n_rows:8}{n_miss:13}{n_nocat:9}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,496 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Extraction + normalisation des tiers (clients / fournisseurs) depuis le CRM
|
||||
Mixgraine (https://liot.mixsuite.fr) vers le format des entites Client / Supplier
|
||||
de Starseed.
|
||||
|
||||
Principe :
|
||||
1. Pagine GET /api/customer/?...&page=N pour collecter tous les id.
|
||||
2. Pour chaque id, recupere la fiche COMPLETE via
|
||||
PUT /api/customer/{id} body {"__data": true}
|
||||
(c'est l'appel que fait le front pour PRECHARGER le formulaire d'edition :
|
||||
il NE MODIFIE RIEN, il renvoie le schema + les valeurs courantes).
|
||||
3. Resout les selects (paymentType, banque, pays, distributeur, sites...) via
|
||||
le schema renvoye, puis normalise chaque tiers au format Starseed.
|
||||
4. Ecrit clients.json, suppliers.json, referentials.json + un rapport.
|
||||
|
||||
Caracteristiques :
|
||||
- Zero dependance (stdlib uniquement).
|
||||
- Cache disque par id (reprise apres interruption, pas de refetch).
|
||||
- Debit volontairement lent (--delay) pour ne pas saturer le serveur.
|
||||
- Backoff automatique sur erreur reseau / 429 / 5xx.
|
||||
|
||||
Usage :
|
||||
export MIXGRAINE_JWT="eyJ0eXAi..." # ton token Bearer (NE PAS committer)
|
||||
python3 extract_mixgraine.py # extraction complete
|
||||
python3 extract_mixgraine.py --delay 1.0 # encore plus doux
|
||||
python3 extract_mixgraine.py --limit-ids 20 # test rapide sur 20 tiers
|
||||
|
||||
Le JWT est un secret de session : passe-le par variable d'environnement,
|
||||
ne l'ecris jamais en dur ici.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
BASE = os.environ.get("MIXGRAINE_BASE", "https://liot.mixsuite.fr")
|
||||
JWT = os.environ.get("MIXGRAINE_JWT") or os.environ.get("LAUTTREE_JWT", "")
|
||||
|
||||
# --- Tables de correspondance Mixgraine -> codes referentiels Starseed ---------
|
||||
|
||||
TVA_MODE = {
|
||||
"France (ventes)": "FRANCE_VENTES",
|
||||
"Export (ventes)": "EXPORT_VENTES",
|
||||
"Intracom (ventes)": "INTRACOM_VENTES",
|
||||
"France (achats)": "FRANCE_VENTES", # pas de mode "achats" au seed -> a trancher
|
||||
}
|
||||
PAYMENT_DELAY = {
|
||||
"15 jours": "J15",
|
||||
"20 jours": "J20", # absent du seed Starseed -> a creer
|
||||
"30 jours": "J30",
|
||||
"A reception": "A_RECEPTION",
|
||||
"A réception": "A_RECEPTION",
|
||||
}
|
||||
PAYMENT_TYPE = {
|
||||
"LCR non soumise": "NON_SOUMISE", # pas LCR : on n'a pas toujours de RIB (RG-1.13)
|
||||
"Virement": "VIREMENT",
|
||||
"Cheque": "CHEQUE",
|
||||
"Chèque": "CHEQUE",
|
||||
}
|
||||
BANK = {
|
||||
"CIC": "CIC",
|
||||
"SOCIETE GENERALE": "SG",
|
||||
"CREDIT AGRICOLE": "CA",
|
||||
}
|
||||
|
||||
CIVILITES = ("Mme", "Mlle", "Mle", "M.", "Mr", "M") # ordre : plus long d'abord
|
||||
|
||||
|
||||
# --- Petites fonctions utilitaires -------------------------------------------
|
||||
|
||||
def http(method, path, body=None, tries=5):
|
||||
"""Appel HTTP avec retry/backoff. Renvoie le JSON decode."""
|
||||
url = BASE + path
|
||||
data = json.dumps(body).encode("utf-8") if body is not None else None
|
||||
headers = {
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Authorization": "Bearer " + JWT,
|
||||
}
|
||||
if data is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
delay = 2.0
|
||||
for attempt in range(1, tries + 1):
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code in (429, 500, 502, 503, 504) and attempt < tries:
|
||||
print(f" ! HTTP {e.code} sur {path} -> retry dans {delay:.0f}s", file=sys.stderr)
|
||||
time.sleep(delay)
|
||||
delay *= 2
|
||||
continue
|
||||
raise
|
||||
except (urllib.error.URLError, TimeoutError) as e:
|
||||
if attempt < tries:
|
||||
print(f" ! reseau ({e}) -> retry dans {delay:.0f}s", file=sys.stderr)
|
||||
time.sleep(delay)
|
||||
delay *= 2
|
||||
continue
|
||||
raise
|
||||
raise RuntimeError("echec apres %d tentatives : %s" % (tries, path))
|
||||
|
||||
|
||||
def choices_map(field):
|
||||
"""Construit {value: label} depuis un champ select du schema."""
|
||||
out = {}
|
||||
try:
|
||||
for c in field["type"]["choices"]:
|
||||
out[c["value"]] = c["label"]
|
||||
except (KeyError, TypeError):
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def first_id(val):
|
||||
"""Mixgraine renvoie soit un id, soit [] (vide), soit [{id:..}]."""
|
||||
if isinstance(val, list):
|
||||
return val[0]["id"] if val and isinstance(val[0], dict) else None
|
||||
return val if val not in ("", None) else None
|
||||
|
||||
|
||||
def parse_contact_name(name):
|
||||
"""'M.ROBERT Florian' -> (lastName='ROBERT', firstName='Florian')."""
|
||||
if not name:
|
||||
return None, None
|
||||
s = name.strip()
|
||||
for civ in CIVILITES:
|
||||
if s.upper().startswith(civ.upper()):
|
||||
s = s[len(civ):].strip(" .")
|
||||
break
|
||||
parts = [p for p in s.split() if p]
|
||||
if not parts:
|
||||
return None, None
|
||||
if len(parts) == 1:
|
||||
return parts[0], None # un seul mot -> nom de famille
|
||||
return parts[0], " ".join(parts[1:]) # 1er = nom, reste = prenom
|
||||
|
||||
|
||||
def clean_phone(p):
|
||||
"""Tronque/nettoie pour tenir dans 20 caracteres (limite Starseed)."""
|
||||
if not p:
|
||||
return None, None
|
||||
raw = str(p).strip()
|
||||
# garde le 1er numero si plusieurs ('... (direct) / ... (standard)')
|
||||
candidate = re.split(r"[/(]", raw)[0].strip()
|
||||
cleaned = candidate if candidate else raw
|
||||
flag = None
|
||||
if len(cleaned) > 20:
|
||||
flag = f"tel tronque ({raw!r})"
|
||||
cleaned = cleaned[:20].strip()
|
||||
return cleaned, flag
|
||||
|
||||
|
||||
POSTCODE_RE = re.compile(r"^\d{4,5}$")
|
||||
|
||||
|
||||
def clean_postcode(p):
|
||||
if not p:
|
||||
return None, None
|
||||
s = str(p).strip()
|
||||
if POSTCODE_RE.match(s):
|
||||
return s, None
|
||||
return None, f"code postal invalide ({p!r})"
|
||||
|
||||
|
||||
# --- Normalisation d'un tiers -------------------------------------------------
|
||||
|
||||
def normalize(record, warnings):
|
||||
"""record = reponse PUT {__data:true}. Renvoie un dict normalise Starseed."""
|
||||
fields = record.get("fields", {})
|
||||
d = record.get("__data", {})
|
||||
details = record.get("details", {})
|
||||
geo = details.get("geo", {}) or {}
|
||||
|
||||
tid = d.get("id")
|
||||
name = d.get("name") or d.get("reference")
|
||||
|
||||
# --- resolveurs depuis le schema de CE record ---
|
||||
liab = choices_map(fields.get("liability", {}))
|
||||
pdelay = choices_map(fields.get("paymentDelay", {}))
|
||||
ptype = choices_map(fields.get("paymentType", {}))
|
||||
bank = choices_map(fields.get("accountingBank", {}))
|
||||
distrib = choices_map(fields.get("distributor", {}))
|
||||
courtier = choices_map(fields.get("courtier", {}))
|
||||
cats = choices_map(fields.get("categories", {}))
|
||||
addr_fields = fields.get("addresses", {}).get("type", {}).get("fields", {})
|
||||
country_map = choices_map(addr_fields.get("country", {}))
|
||||
addr_cats = choices_map(addr_fields.get("categories", {}))
|
||||
carrier_map = choices_map(addr_fields.get("carrierType", {}))
|
||||
# libelles des sites (organisations)
|
||||
site_labels = {
|
||||
"organization_1": addr_fields.get("organization_1", {}).get("label"),
|
||||
"organization_2": addr_fields.get("organization_2", {}).get("label"),
|
||||
"organization_3": addr_fields.get("organization_3", {}).get("label"),
|
||||
}
|
||||
|
||||
def map_ref(table, label, what):
|
||||
if label is None:
|
||||
return None
|
||||
code = table.get(label)
|
||||
if code is None:
|
||||
warnings.append(f"tiers {tid} ({name}): {what} non mappe : {label!r}")
|
||||
return code
|
||||
|
||||
# --- referentiels comptables ---
|
||||
tva = map_ref(TVA_MODE, liab.get(first_id(d.get("liability"))), "tvaMode")
|
||||
delay = map_ref(PAYMENT_DELAY, pdelay.get(first_id(d.get("paymentDelay"))), "paymentDelay")
|
||||
pay = map_ref(PAYMENT_TYPE, ptype.get(first_id(d.get("paymentType"))), "paymentType")
|
||||
bnk = map_ref(BANK, bank.get(first_id(d.get("accountingBank"))), "bank")
|
||||
|
||||
# --- categories tiers ---
|
||||
categories = []
|
||||
for c in d.get("categories", []) or []:
|
||||
lbl = cats.get(c.get("id"))
|
||||
if lbl:
|
||||
categories.append(lbl)
|
||||
if not categories:
|
||||
categories = ["A QUALIFIER"] # contrainte min 1 cote Starseed
|
||||
warnings.append(f"tiers {tid} ({name}): aucune categorie -> 'A QUALIFIER'")
|
||||
|
||||
# --- contacts ---
|
||||
contacts = []
|
||||
contact_phones = set()
|
||||
for c in d.get("contacts", []) or []:
|
||||
last, first = parse_contact_name(c.get("name"))
|
||||
phone, f1 = clean_phone(c.get("phone"))
|
||||
mobile, f2 = clean_phone(c.get("mobile"))
|
||||
if f1:
|
||||
warnings.append(f"tiers {tid} ({name}): {f1}")
|
||||
if f2:
|
||||
warnings.append(f"tiers {tid} ({name}): {f2}")
|
||||
if not last and not first:
|
||||
last = "Standard" # RG-1.05/2.04 : au moins un nom
|
||||
for ph in (phone, mobile):
|
||||
if ph:
|
||||
contact_phones.add(re.sub(r"\D", "", ph))
|
||||
contacts.append({
|
||||
"mixgraineId": c.get("id"),
|
||||
"lastName": last,
|
||||
"firstName": first,
|
||||
"jobTitle": c.get("function"),
|
||||
"email": (c.get("email") or None),
|
||||
"phonePrimary": phone,
|
||||
"phoneSecondary": mobile,
|
||||
})
|
||||
|
||||
# tel porte par l'objet de base -> dans la liste de contacts (jamais a la racine)
|
||||
base_phone, fb = clean_phone(d.get("phone"))
|
||||
if fb:
|
||||
warnings.append(f"tiers {tid} ({name}): {fb}")
|
||||
if base_phone and re.sub(r"\D", "", base_phone) not in contact_phones:
|
||||
if contacts:
|
||||
# complete le 1er contact sans tel secondaire
|
||||
for c in contacts:
|
||||
if not c["phoneSecondary"]:
|
||||
c["phoneSecondary"] = base_phone
|
||||
break
|
||||
else:
|
||||
contacts[0]["phoneSecondary"] = base_phone
|
||||
else:
|
||||
contacts.append({
|
||||
"mixgraineId": None, "lastName": "Standard", "firstName": None,
|
||||
"jobTitle": None, "email": None,
|
||||
"phonePrimary": base_phone, "phoneSecondary": None,
|
||||
})
|
||||
|
||||
# --- emails de facturation (mails[] avec invoice=true) ---
|
||||
billing_mails = [m["mail"] for m in (d.get("mails") or []) if m.get("invoice") and m.get("mail")]
|
||||
|
||||
# --- adresses ---
|
||||
addresses = []
|
||||
for a in d.get("addresses", []) or []:
|
||||
pc, fp = clean_postcode(a.get("postcode"))
|
||||
if fp:
|
||||
warnings.append(f"tiers {tid} ({name}): {fp}")
|
||||
# sites depuis les booleens organization_n
|
||||
sites = [site_labels[k] for k in ("organization_1", "organization_2", "organization_3")
|
||||
if a.get(k) and site_labels[k]]
|
||||
# categories d'adresse
|
||||
acats = [addr_cats.get(c.get("id")) for c in (a.get("categories") or []) if addr_cats.get(c.get("id"))]
|
||||
# type d'adresse fournisseur (Rendu/Depart) depuis carrierType
|
||||
carrier = carrier_map.get(a.get("carrierType"))
|
||||
supplier_addr_type = {"Rendu": "RENDU", "Départ": "DEPART", "Depart": "DEPART"}.get(carrier)
|
||||
latlng = geo.get(str(a.get("id"))) or geo.get(a.get("id"))
|
||||
lat, lng = (latlng.split(",") + [None, None])[:2] if isinstance(latlng, str) else (None, None)
|
||||
addresses.append({
|
||||
"mixgraineId": a.get("id"),
|
||||
"street": a.get("street1"),
|
||||
"streetComplement": a.get("street2"),
|
||||
"postalCode": pc,
|
||||
"city": a.get("city"),
|
||||
"country": country_map.get(a.get("country"), "France"),
|
||||
# flags client
|
||||
"isBilling": bool(a.get("billing")),
|
||||
"isDelivery": bool(a.get("sales")),
|
||||
"isProspect": bool(a.get("salesTrip")),
|
||||
# type fournisseur
|
||||
"supplierAddressType": supplier_addr_type or "PROSPECT",
|
||||
"bennes": a.get("benneCount"),
|
||||
"sites": sites,
|
||||
"categories": acats,
|
||||
"billingEmail": (billing_mails[0] if (a.get("billing") and billing_mails) else None),
|
||||
"contactMixgraineIds": [c.get("id") for c in (a.get("contacts") or [])],
|
||||
"lat": lat, "lng": lng, # conserve pour info (pas de cible Starseed)
|
||||
})
|
||||
|
||||
# --- RIB (banks[]) ---
|
||||
ribs = [{
|
||||
"label": b.get("label") or "Compte principal",
|
||||
"iban": b.get("iban"),
|
||||
"bic": b.get("bic"),
|
||||
} for b in (d.get("banks") or []) if b.get("iban")]
|
||||
|
||||
return {
|
||||
"mixgraineId": tid,
|
||||
"companyName": name,
|
||||
"isCustomer": bool(d.get("customer")),
|
||||
"isSupplier": bool(d.get("supplier")),
|
||||
"accountNumber": d.get("billingAccount") or None,
|
||||
"nTva": d.get("vatNumber") or None,
|
||||
"tvaMode": tva,
|
||||
"paymentDelay": delay,
|
||||
"paymentType": pay,
|
||||
"bank": bnk,
|
||||
"distributorName": distrib.get(first_id(d.get("distributor"))),
|
||||
"brokerName": courtier.get(first_id(d.get("courtier"))),
|
||||
"categories": categories,
|
||||
"contacts": contacts,
|
||||
"addresses": addresses,
|
||||
"ribs": ribs,
|
||||
}
|
||||
|
||||
|
||||
# --- Recuperation de la liste des id -----------------------------------------
|
||||
|
||||
def fetch_ids_for(filters, limit, delay):
|
||||
"""Pagine /api/customer/ pour un jeu de filtres donne et renvoie la liste d'id."""
|
||||
fields = urllib.parse.quote('["name"]')
|
||||
fstr = urllib.parse.quote(json.dumps(filters)) if filters else ""
|
||||
ids, page, count = [], 0, None
|
||||
while True:
|
||||
path = f"/api/customer/?fields={fields}&limit={limit}&order=name&page={page}"
|
||||
if fstr:
|
||||
path += f"&filters={fstr}"
|
||||
resp = http("GET", path)
|
||||
if count is None:
|
||||
count = resp.get("count", 0)
|
||||
batch = resp.get("data", [])
|
||||
if not batch:
|
||||
break
|
||||
ids.extend(r["id"] for r in batch)
|
||||
page += 1
|
||||
if count and len(ids) >= count:
|
||||
break
|
||||
time.sleep(delay)
|
||||
return ids
|
||||
|
||||
|
||||
def fetch_all_ids(limit, delay):
|
||||
"""Collecte les id par groupe (client / fournisseur / prestataire) + union.
|
||||
|
||||
On s'appuie sur l'APPARTENANCE aux listes filtrees pour classer chaque tiers,
|
||||
plus fiable que les flags parfois absents du formulaire __data.
|
||||
"""
|
||||
print(" - clients (customer=true)")
|
||||
customer_ids = set(fetch_ids_for({"customer": True}, limit, delay))
|
||||
print(f" {len(customer_ids)}")
|
||||
print(" - fournisseurs (supplier=true)")
|
||||
supplier_ids = set(fetch_ids_for({"supplier": True}, limit, delay))
|
||||
print(f" {len(supplier_ids)}")
|
||||
print(" - prestataires (prestataire=true) -> ranges en fournisseurs")
|
||||
prestataire_ids = set(fetch_ids_for({"prestataire": True}, limit, delay))
|
||||
print(f" {len(prestataire_ids)}")
|
||||
|
||||
all_ids = sorted(customer_ids | supplier_ids | prestataire_ids)
|
||||
print(f" total tiers distincts : {len(all_ids)}")
|
||||
return all_ids, customer_ids, supplier_ids, prestataire_ids
|
||||
|
||||
|
||||
# --- Main ---------------------------------------------------------------------
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Extraction Mixgraine -> format Starseed")
|
||||
ap.add_argument("--out", default="mixgraine-export", help="dossier de sortie")
|
||||
ap.add_argument("--delay", type=float, default=1.0, help="pause (s) entre chaque fiche (defaut 1 req/s)")
|
||||
ap.add_argument("--limit", type=int, default=200, help="taille de page pour la liste")
|
||||
ap.add_argument("--limit-ids", type=int, default=0, help="ne traiter que N tiers (test)")
|
||||
args = ap.parse_args()
|
||||
|
||||
if not JWT:
|
||||
sys.exit("ERREUR : export MIXGRAINE_JWT='<ton token>' avant de lancer.")
|
||||
|
||||
cache_dir = os.path.join(args.out, "cache")
|
||||
os.makedirs(cache_dir, exist_ok=True)
|
||||
|
||||
print("== Etape 1 : liste des id (par groupe) ==")
|
||||
ids, customer_ids, supplier_ids, prestataire_ids = fetch_all_ids(args.limit, args.delay)
|
||||
if args.limit_ids:
|
||||
ids = ids[:args.limit_ids]
|
||||
print(f"{len(ids)} tiers a recuperer.\n")
|
||||
|
||||
print("== Etape 2 : fiches detaillees (lent, soyez patient) ==")
|
||||
raw_by_id = {}
|
||||
for n, tid in enumerate(ids, 1):
|
||||
cache_file = os.path.join(cache_dir, f"{tid}.json")
|
||||
if os.path.exists(cache_file):
|
||||
with open(cache_file, encoding="utf-8") as f:
|
||||
raw_by_id[tid] = json.load(f)
|
||||
continue
|
||||
rec = http("PUT", f"/api/customer/{tid}", body={"__data": True})
|
||||
with open(cache_file, "w", encoding="utf-8") as f:
|
||||
json.dump(rec, f, ensure_ascii=False)
|
||||
raw_by_id[tid] = rec
|
||||
if n % 25 == 0 or n == len(ids):
|
||||
print(f" {n}/{len(ids)} fiches")
|
||||
time.sleep(args.delay)
|
||||
|
||||
print("\n== Etape 3 : normalisation ==")
|
||||
warnings = []
|
||||
clients, suppliers, providers = [], [], []
|
||||
cat_set, site_set = set(), set()
|
||||
for tid in ids:
|
||||
norm = normalize(raw_by_id[tid], warnings)
|
||||
# classification par APPARTENANCE aux listes filtrees (source fiable) :
|
||||
# customer -> Client (module Commercial)
|
||||
# supplier -> Supplier (module Commercial)
|
||||
# prestataire -> Provider (module Technique) — entite dediee, PAS un Supplier
|
||||
is_customer = tid in customer_ids or norm["isCustomer"]
|
||||
is_supplier = tid in supplier_ids or norm["isSupplier"]
|
||||
is_prestataire = tid in prestataire_ids
|
||||
norm["isCustomer"] = is_customer
|
||||
norm["isSupplier"] = is_supplier
|
||||
norm["isPrestataire"] = is_prestataire
|
||||
# Provider porte les sites DIRECTEMENT (RG-3.03) : on agrege les sites des adresses.
|
||||
norm["sites"] = sorted({s for a in norm["addresses"] for s in a["sites"]})
|
||||
cat_set.update(norm["categories"])
|
||||
for a in norm["addresses"]:
|
||||
site_set.update(a["sites"])
|
||||
cat_set.update(a["categories"])
|
||||
# un tiers peut cumuler plusieurs roles -> cree dans chaque table concernee
|
||||
if is_customer:
|
||||
clients.append(norm)
|
||||
if is_supplier:
|
||||
suppliers.append(norm)
|
||||
if is_prestataire:
|
||||
providers.append(norm)
|
||||
if not (is_customer or is_supplier or is_prestataire):
|
||||
clients.append(norm) # filet de securite : client par defaut
|
||||
warnings.append(f"tiers {tid} ({norm['companyName']}): aucun flag -> client par defaut")
|
||||
|
||||
referentials = {
|
||||
"categories": sorted(cat_set),
|
||||
"sites": sorted(site_set),
|
||||
"tvaModes": sorted(set(TVA_MODE.values())),
|
||||
"paymentDelays": sorted(set(PAYMENT_DELAY.values())),
|
||||
"paymentTypes": sorted(set(PAYMENT_TYPE.values())),
|
||||
"banks": sorted(set(BANK.values())),
|
||||
}
|
||||
|
||||
def dump(fname, obj):
|
||||
with open(os.path.join(args.out, fname), "w", encoding="utf-8") as f:
|
||||
json.dump(obj, f, ensure_ascii=False, indent=2)
|
||||
|
||||
dump("clients.json", clients)
|
||||
dump("suppliers.json", suppliers)
|
||||
dump("providers.json", providers)
|
||||
dump("referentials.json", referentials)
|
||||
with open(os.path.join(args.out, "extraction-report.txt"), "w", encoding="utf-8") as f:
|
||||
f.write(f"Tiers traites : {len(ids)}\n")
|
||||
f.write(f"Clients : {len(clients)}\n")
|
||||
f.write(f"Fournisseurs : {len(suppliers)}\n")
|
||||
f.write(f"Prestataires : {len(providers)}\n")
|
||||
f.write(f"Categories uniques : {len(referentials['categories'])}\n")
|
||||
f.write(f"Sites uniques : {referentials['sites']}\n")
|
||||
f.write(f"Avertissements : {len(warnings)}\n\n")
|
||||
f.write("\n".join(warnings))
|
||||
|
||||
print(f"\nTermine.")
|
||||
print(f" clients.json : {len(clients)}")
|
||||
print(f" suppliers.json : {len(suppliers)}")
|
||||
print(f" providers.json : {len(providers)} (prestataires)")
|
||||
print(f" referentials.json : {len(referentials['categories'])} categories, sites {referentials['sites']}")
|
||||
print(f" avertissements : {len(warnings)} (voir extraction-report.txt)")
|
||||
print(f"Sortie dans : {os.path.abspath(args.out)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,306 +0,0 @@
|
||||
# Migration Mixgraine → Starseed — Analyse des tiers (clients / fournisseurs)
|
||||
|
||||
> Sources analysées (exports Mixgraine triés par groupe) :
|
||||
> - `client.json.json` — **1023 clients** (`customer=true`)
|
||||
> - `fournisseur.json` — **306 fournisseurs** (`supplier=true`)
|
||||
> - `fournisseur-client.json` — **106 tiers mixtes** (`customer=true` ET `supplier=true`)
|
||||
>
|
||||
> Cible : module `Commercial` de Starseed — entités `Client` / `Supplier` et leurs sous-entités `*Contact`, `*Address`, `*Rib`.
|
||||
> Date d'analyse : 2026-06-16. (Remplace l'analyse initiale faite sur `customer.json`, 737 tiers, où la classification était absente.)
|
||||
>
|
||||
> 🔑 **Source de migration recommandée : l'endpoint unitaire, pas l'export en masse.**
|
||||
> Les exports CSV/JSON en masse sont **incomplets** : ni RIB/IBAN, ni N° TVA, ni banque de virement, ni rattachement aux sites. Toutes ces données existent dans l'endpoint détail `GET /api/customer/{id}` et surtout dans `PUT /api/customer/{id}` avec `{"__data":true}` (renvoie le **schéma de formulaire complet + les valeurs**). Procédure : paginer `GET /api/customer/?...&limit=...&page=N` pour récupérer les `id`, puis appeler l'endpoint détail pour chaque id. Cf. § 9.
|
||||
|
||||
---
|
||||
|
||||
## 1. Synthèse
|
||||
|
||||
L'export est désormais **trié par groupe** : la distinction client / fournisseur est nette, ce qui lève le principal point bloquant de l'analyse précédente. **1435 tiers distincts** (aucun recoupement d'id entre les trois fichiers).
|
||||
|
||||
| Groupe source | Tiers | Devient dans Starseed |
|
||||
|---|---|---|
|
||||
| `client.json.json` (`customer=true`) | 1023 | `Client` |
|
||||
| `fournisseur.json` (`supplier=true`) | 306 | `Supplier` |
|
||||
| `fournisseur-client.json` (`customer=true` + `supplier=true`) | 106 | **`Client` ET `Supplier`** (cf. § 4) |
|
||||
| **prestataires** (`prestataire=true`, vue séparée Mixgraine) | à extraire via l'API (filtre `prestataire:true`) | **`Provider`** (module Technique, M3) |
|
||||
|
||||
> ✅ Les **prestataires** sont un 4e type de tiers, géré dans une vue dédiée de Mixgraine mais sur le **même endpoint** `/api/customer/` (filtre `{"prestataire":true}`). Côté Starseed, ils ont une **entité dédiée** : `Provider` (module **Technique**, `src/Module/Technique/Domain/Entity/Provider.php`), jumelle du `Supplier`, avec `ProviderContact` / `ProviderAddress` / `ProviderRib`. **Ils ne deviennent donc PAS des `Supplier`.** Particularités vs Supplier : pas d'onglet Information (entité minimale nom + comptabilité) et les **sites sont rattachés directement au prestataire** (M2M `provider_site`, min 1, RG-3.03) — le script agrège donc les sites des adresses au niveau du prestataire. Catégories de type **PRESTATAIRE** exigées (RG-3.09). Le script collecte les prestataires via leur liste dédiée et produit `providers.json` (§ 9).
|
||||
|
||||
Volumétrie migrable (tous groupes confondus) :
|
||||
|
||||
| Objet source | Quantité | Cible Starseed |
|
||||
|---|---|---|
|
||||
| Tiers racine | 1435 | `Client` (1129) + `Supplier` (412) = **1541 entités** créées (les 106 mixtes comptent double) |
|
||||
| Adresses | **2282** | `ClientAddress` / `SupplierAddress` |
|
||||
| Contacts | **2704** | `ClientContact` / `SupplierContact` |
|
||||
| RIB | **0** | *rien à migrer (ni IBAN ni BIC dans l'export)* |
|
||||
|
||||
Détail par groupe :
|
||||
|
||||
| Groupe | Tiers | Adresses | Contacts | Avec tél | Avec catégorie | Avec type paiement |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Clients | 1023 | 1125 | 1279 | 1023 (100 %) | 648 (63 %) | 599 |
|
||||
| Fournisseurs | 306 | 585 | 758 | 306 (100 %) | 92 (30 %) | 283 |
|
||||
| Mixtes | 106 | 572 | 667 | 106 (100 %) | 37 (35 %) | 95 |
|
||||
|
||||
Points de décision restants (détaillés plus bas) :
|
||||
|
||||
1. **Les 106 tiers mixtes** doivent être dédoublés en un `Client` + un `Supplier` (le modèle Starveed sépare les deux entités). § 4.
|
||||
2. **Référentiels à compléter** : `paymentDelay` (« 20 jours » absent du seed), `tvaMode` (Intracom/Export/achats), mapping des ~100 catégories. § 5.
|
||||
3. **Site obligatoire par adresse** (min 1) — notion toujours absente de l'export. § 6.
|
||||
|
||||
---
|
||||
|
||||
## 2. Structure de l'export
|
||||
|
||||
Chaque ligne = un tiers. Les champs `addresses.*` et `contacts.*` sont des **listes parallèles** (un tiers peut avoir plusieurs adresses / contacts).
|
||||
|
||||
Qualité des données (tous groupes) :
|
||||
|
||||
- **Téléphone racine** : rempli sur **100 %** des tiers (1435/1435).
|
||||
- **Emails contacts** : 1257 présents, **1256 valides** (1 invalide).
|
||||
- **Codes postaux** : 2282 présents, **10 invalides** à nettoyer : `.` (×3), `B.5300`, `?`, `684`, `854300`, etc. (sinon 422 sur la regex 4-5 chiffres RG-1.09/2.05).
|
||||
- **Catégories** : 55 % des tiers en ont au moins une (45 % sans) ; **92 % des adresses** ont une catégorie (2104/2282).
|
||||
- **Noms de contact** : format « `CIVILITÉ NOM PRÉNOM` » (`M `, `Mme`, `M.`) → à parser pour `lastName` / `firstName`.
|
||||
|
||||
Pays des adresses : FR (2266), ES (11), BE (2), NL (2), PT (1).
|
||||
|
||||
---
|
||||
|
||||
## 3. Mapping champ par champ
|
||||
|
||||
Légende : ✅ champ existant · ⚠️ migrable avec transformation · ❌ pas de cible (donnée perdue) · 🔒 contrainte de validation à gérer.
|
||||
|
||||
### 3.1 Niveau Tiers → `Client` / `Supplier`
|
||||
|
||||
| Champ Mixgraine | Cible Starseed | Statut | Note de transformation |
|
||||
|---|---|---|---|
|
||||
| `name` / `reference` | `companyName` (≤180) | ✅ | Vérifier l'unicité (index partiel `LOWER(company_name)`). Risque : un même nom présent en client ET fournisseur reste OK (tables distinctes) ; doublons intra-table à contrôler. |
|
||||
| `phone` (tél de l'objet de base) | `*Contact.phonePrimary` | ⚠️ | **Migré dans la liste de contacts** (cf. § 3.3bis), jamais au niveau racine. Rempli à 100 %. |
|
||||
| `categoriesStr` / `category.name` | `categories` (M2M `Category`) | ⚠️🔒 | **Min 1 obligatoire**. ~100 valeurs distinctes à mapper vers le référentiel `Category` (§ 5.1). Attention `Courtier`/`Distributeur` (cf. broker/distributor). |
|
||||
| `liability.name` | `tvaMode` | ⚠️ | `France (ventes)`→`FRANCE_VENTES` (1426), `Intracom (ventes)`→`INTRACOM_VENTES` (6), `Export (ventes)`→`EXPORT_VENTES` (2), `France (achats)`→**pas de mode « achats » au seed** (1 cas). |
|
||||
| `paymentDelay.label` | `paymentDelay` | ⚠️🔒 | `15 jours`→`J15` (1376), `30 jours`→`J30` (43), `A réception`→`A_RECEPTION` (1), **`20 jours` (15)→ code `J20` à créer** (absent du seed). |
|
||||
| `paymentType.label` | `paymentType` | ⚠️🔒 | `LCR non soumise`→**à trancher** (`LCR` impose ≥1 RIB, or 0 RIB → préférer `NON_SOUMISE`), `Virement`→`VIREMENT` (95, **exige `bank`** absente de la source), `Chèque`→`CHEQUE` (28). |
|
||||
| `billingAccount` | `accountNumber` (≤40) | ✅ | Peu rempli. |
|
||||
| `distributor.name` | `distributor` (FK auto-réf. `Client`) | ⚠️ | Suppose que le distributeur existe comme `Client`. Pas d'équivalent côté `Supplier`. |
|
||||
| `courtier.id` / `courtier.name` | `broker` (FK auto-réf.) | ⚠️ | À vérifier sur les nouveaux exports (vide dans l'ancien). Mutuellement exclusif avec `distributor` (RG-1.03). |
|
||||
| `customer` / `supplier` | choix de l'entité cible (`Client` vs `Supplier`) | ⚠️ | **Sert au routage**, pas stocké tel quel. |
|
||||
| `tiersIndexable`, `prestataire`, `coreLocked`, `isOgm`, `maxOwed`, `autoGenerateInvoice` | — | ❌ | Flags Mixgraine sans équivalent métier. |
|
||||
| `organization1..3` / `organizationsStr` | — | ❌ | Notion d'organisation/agence absente du modèle. |
|
||||
| `articlesSold.*` | — | ❌ | Relève du catalogue, hors périmètre Client/Supplier. |
|
||||
| `siren`, `nTva`, `bank` | `siren`, `nTva`, `bank` | ❌ | **Non présents dans l'export** → resteront vides. |
|
||||
|
||||
### 3.2 Niveau Adresse → `ClientAddress` / `SupplierAddress`
|
||||
|
||||
| Champ Mixgraine | Cible Starseed | Statut | Note |
|
||||
|---|---|---|---|
|
||||
| `addresses.street1` | `street` (≤255) | ✅ | Obligatoire. |
|
||||
| `addresses.street2` | `streetComplement` (≤255) | ✅ | |
|
||||
| `addresses.postcode` | `postalCode` (≤20, regex 4-5 chiffres) | ⚠️ | 10 valeurs à nettoyer. |
|
||||
| `addresses.city` | `city` (≤120) | ✅ | Obligatoire. |
|
||||
| `addresses.country` | `country` (≤80, défaut « France ») | ⚠️ | Convertir code ISO → libellé (`FR`→France, `ES`→Espagne, `BE`→Belgique, `NL`→Pays-Bas, `PT`→Portugal). |
|
||||
| `addresses.lat` / `addresses.lng` | — | ❌ | Coordonnées GPS perdues (pas de champ géo). |
|
||||
| `addresses.billing` (true) | `isBilling` (Client) | ⚠️🔒 | Si `true`, `billingEmail` **obligatoire** (RG-1.11), absent de la source → soit ne pas marquer facturation, soit collecter l'email. |
|
||||
| `addresses.sales` | `isDelivery` (Client) | ⚠️ | |
|
||||
| `addresses.purchase` | type adresse (Supplier : `DEPART`/`RENDU`) | ⚠️ | Côté fournisseur, l'adresse a un enum `PROSPECT`/`DEPART`/`RENDU`. |
|
||||
| `addresses.salesTrip` | `isProspect` (?) | ⚠️ | Sémantique « tournée commerciale » à confirmer. |
|
||||
| `addresses.benneCount` | `bennes` (SupplierAddress) | ⚠️ | Souvent vide. |
|
||||
| `addresses.carrierTypeStr`, `addresses.name`, `addresses.distances` | — | ❌ | Sans cible. |
|
||||
| `addresses.categories.name` | `categories` (M2M adresse) | ⚠️🔒 | 92 % des adresses en ont une. **Min 1 obligatoire** côté `ClientAddress`. ⚠️ Codes `DISTRIBUTEUR`/`COURTIER` **interdits** au niveau adresse (RG-1.29). |
|
||||
| — (aucun) | `sites` (M2M, **min 1**) | 🔒 | **Notion absente de l'export** — bloquant majeur (§ 6). |
|
||||
|
||||
### 3.3 Niveau Contact → `ClientContact` / `SupplierContact`
|
||||
|
||||
| Champ Mixgraine | Cible Starseed | Statut | Note |
|
||||
|---|---|---|---|
|
||||
| `contacts.name` | `lastName` / `firstName` (≤120) | ⚠️ | Parser « CIVILITÉ NOM PRÉNOM » : retirer civilité, 1er token = `lastName`, reste = `firstName`. Au moins l'un des deux requis (RG-1.05/2.04). |
|
||||
| `contacts.function` | `jobTitle` (≤120) | ✅ | |
|
||||
| `contacts.email` | `email` (≤180) | ✅ | 99,9 % valides. |
|
||||
| `contacts.phone` | `phonePrimary` (≤20) | ✅ | |
|
||||
| `contacts.mobile` | `phoneSecondary` (≤20) | ✅ | |
|
||||
| `contacts.fax` | — | ❌ | Pas de champ fax dans les contacts Starseed. |
|
||||
| `contacts.siege` | — | ❌ | Notion « contact siège » non modélisée. |
|
||||
| `addresses.contacts.*` | `*Address.contacts` (M2M) | ⚠️ | Rattachement contact↔adresse via les ids `addresses.contacts.id`. |
|
||||
|
||||
### 3.3bis — Règle : le contact porté par l'objet de base va dans la liste de contacts
|
||||
|
||||
Starseed n'a **aucun champ contact au niveau racine** de `Client`/`Supplier`. Tout doit atterrir dans la collection `*Contact` :
|
||||
|
||||
- Le bloc `contacts.*` (nom, fonction, email, tél, mobile) → une entrée `*Contact` par contact.
|
||||
- Le `phone` de l'objet de base (rempli à 100 %) → reporté sur un contact :
|
||||
- si le numéro figure déjà sur un contact → ne rien créer (déduplication) ;
|
||||
- s'il diffère → l'ajouter comme `phoneSecondary` d'un contact existant ;
|
||||
- si le tiers **n'a aucun contact** → **créer un contact « Standard »** (`lastName = "Standard"` pour respecter RG-1.05/2.04) portant ce `phonePrimary`.
|
||||
|
||||
Conséquence : aucun tiers ne perd son téléphone, et rien n'est stocké au niveau racine (conforme au modèle Starseed).
|
||||
|
||||
### 3.4 Niveau RIB → `ClientRib` / `SupplierRib`
|
||||
|
||||
**Disponible via l'endpoint unitaire** (champ `banks[]`), absent de l'export en masse. Mapping direct :
|
||||
|
||||
| Champ Mixgraine (`banks[]`) | Cible Starseed (`*Rib`) | Statut |
|
||||
|---|---|---|
|
||||
| `banks[].label` | `label` (≤120) | ✅ |
|
||||
| `banks[].iban` | `iban` (≤34) | ✅ (validé Assert\Iban) |
|
||||
| `banks[].bic` | `bic` (≤20) | ✅ (validé Assert\Bic) |
|
||||
|
||||
⚠️ Toujours mapper `paymentType="LCR non soumise"` vers `NON_SOUMISE` (et pas `LCR`) : les tiers sans `banks[]` violeraient sinon RG-1.13/2.08 (min 1 RIB).
|
||||
|
||||
### 3.5 Champs supplémentaires de l'endpoint unitaire (absents de l'export en masse)
|
||||
|
||||
| Champ Mixgraine (détail / `__data`) | Cible Starseed | Statut | Note |
|
||||
|---|---|---|---|
|
||||
| `vatNumber` | `nTva` (≤40) | ✅ | N° TVA. |
|
||||
| `accountingBank` (1=CIC, 2=SOCIETE GENERALE, 3=CREDIT AGRICOLE) | `bank` (FK) | ✅ | **Correspond au seed Starseed** (CIC/SG/CA). Banque de virement. |
|
||||
| `courtier` (FK select, 18 valeurs) | `broker` (FK auto-réf.) | ✅ | Courtier réel (≠ catégorie « Courtier »). Exclusif avec `distributor` (RG-1.03). |
|
||||
| `distributor` (FK select, 14 valeurs) | `distributor` (FK auto-réf.) | ✅ | Distributeur réel. |
|
||||
| `mails[]` {`mail`, `invoice`} | `ClientAddress.billingEmail` / secondaire | ⚠️ | Emails d'envoi de documents ; `invoice=true` → email de facturation (RG-1.11). |
|
||||
| address `carrierType` (1=Rendu, 2=Départ) | `SupplierAddress.addressType` (RENDU/DEPART) | ⚠️ | Radio exclusif côté fournisseur (RG-2.09). |
|
||||
| address `organization_1/2/3` | `*Address.sites` (M2M) | ✅ | **Les sites** (cf. § 6). |
|
||||
| address `hasBenne` / `benneCount` | `SupplierAddress.bennes` | ⚠️ | Nombre de bennes. |
|
||||
| address `validated` | — | ❌ | « Adresse vérifiée », pas de cible. |
|
||||
| `isDistributor`, `directBilling`, `distributorDirectOrder`, `newGuarantees`, `commentMail`, `zoneChartering(2)`, `emailDocument*` | — | ❌ | Champs Mixgraine sans équivalent métier. |
|
||||
|
||||
---
|
||||
|
||||
## 4. Tiers mixtes (client + fournisseur) — 106 cas
|
||||
|
||||
Les 106 tiers du fichier `fournisseur-client.json` sont **à la fois client et fournisseur**. Le modèle Starseed sépare strictement `Client` et `Supplier` (deux tables, deux jeux de sous-entités). Deux options :
|
||||
|
||||
- **(Recommandé)** Créer **deux entités** par tiers mixte : un `Client` et un `Supplier`, chacun avec sa copie des adresses/contacts. C'est cohérent avec le modèle, au prix d'une duplication (à reconcilier plus tard si un lien inter-entités est ajouté).
|
||||
- Choisir une seule face (client OU fournisseur) selon l'usage dominant — risque de perte d'information.
|
||||
|
||||
Impact volumétrie : 1023 + 106 = **1129 `Client`**, 306 + 106 = **412 `Supplier`**.
|
||||
|
||||
---
|
||||
|
||||
## 5. Référentiels à préparer avant import
|
||||
|
||||
### 5.1 Catégories (`Category`)
|
||||
|
||||
Situation nettement meilleure que l'export initial : **55 % des tiers** et **92 % des adresses** portent une catégorie. L'export contient **~100 valeurs distinctes** (top : Eleveur 392, Semencier 61, Coopérative 53, Courtier 38, Négociant 30, …, puis une longue traîne de catégories « fournisseur » métier : Transports, Informatique, Garagistes, Banques…).
|
||||
|
||||
À faire :
|
||||
- **Construire le référentiel `Category`** depuis ces valeurs (dédoublonner casse/accents, ex. `Courtier`/`COURTIERS`).
|
||||
- **Politique pour les 45 % sans catégorie** : attribuer une catégorie par défaut (ex. `À QUALIFIER`) pour satisfaire la contrainte min 1.
|
||||
- **Niveau adresse** : exclure `DISTRIBUTEUR`/`COURTIER` (interdits RG-1.29) — les router vers les FK `distributor`/`broker` ou la catégorie tiers.
|
||||
- Distinguer catégories **type CLIENT** vs **type FOURNISSEUR** (RG-2.10 : une catégorie fournisseur est exigée sur un `Supplier`).
|
||||
|
||||
### 5.2 Référentiels comptables
|
||||
|
||||
| Référentiel | Valeurs export | Action |
|
||||
|---|---|---|
|
||||
| `paymentDelay` | 15 jours, 30 jours, **20 jours**, A réception | Le seed n'a que `J15`/`J30`/`A_RECEPTION` → **créer `J20`**. |
|
||||
| `paymentType` | LCR non soumise, Virement, Chèque | Mapper `LCR non soumise`→`NON_SOUMISE` (éviter la contrainte RIB) ; `Virement`→`VIREMENT` (mais `bank` absente → soit la laisser vide en assouplissant RG-1.12, soit collecter). |
|
||||
| `tvaMode` | France (ventes), Intracom (ventes), Export (ventes), **France (achats)** | Mapper sur `FRANCE_VENTES`/`INTRACOM_VENTES`/`EXPORT_VENTES` ; pas de mode « achats » au seed (1 cas) → décision. |
|
||||
|
||||
---
|
||||
|
||||
## 6. Sites — résolu via les « organisations » Mixgraine
|
||||
|
||||
Chaque `ClientAddress`/`SupplierAddress` doit référencer **au moins un `Site`** (RG-1.10/2.06). Cette notion **existe dans Mixgraine** sous le nom d'**organisations**, visible dans l'endpoint unitaire :
|
||||
|
||||
- au niveau tiers : `organizationsStr` (ex. `"Châtellerault, Saint-Jean, Pommevic"`) ;
|
||||
- au niveau adresse : trois booléens `organization_1` / `organization_2` / `organization_3` étiquetés **Châtellerault / Saint-Jean / Pommevic** ;
|
||||
- le bloc `addresses.distances` donne même la distance de l'adresse vers chacun de ces 3 sites.
|
||||
|
||||
**Les 3 sites à créer dans Starseed** : `Châtellerault`, `Saint-Jean`, `Pommevic`. Le rattachement adresse↔site se reconstruit depuis les booléens `organization_n=true`. Pour une adresse sans aucune organisation cochée, prévoir un site par défaut (à décider).
|
||||
|
||||
⚠️ Ce rattachement n'est lisible que via l'endpoint unitaire — raison de plus pour migrer depuis le détail (cf. § 9).
|
||||
|
||||
---
|
||||
|
||||
## 7. Synthèse des pertes de données
|
||||
|
||||
Perdus si non traités en amont : coordonnées GPS (`lat`/`lng`), fax des contacts, contact siège, articles vendus, « adresse vérifiée », et divers flags Mixgraine (`isOgm`, `maxOwed`, `directBilling`, `zoneChartering`, `commentMail`).
|
||||
|
||||
Champs cibles qui resteront vides (vraiment absents de la source, même au détail) : `siren` (le `vatNumber` alimente `nTva`, mais pas de SIREN distinct).
|
||||
|
||||
> Note : `nTva`, `bank` et les `*Rib` ne sont **plus** des pertes — ils sont disponibles via l'endpoint unitaire (§ 3.4 / § 3.5). Ils n'étaient absents que de l'export en masse.
|
||||
|
||||
---
|
||||
|
||||
## 7bis. Excel de relecture (un onglet par type)
|
||||
|
||||
Beaucoup d'adresses n'ont **aucun site** rattaché (les organisations ne sont pas cochées dans Mixgraine), et d'autres trous existent (CP invalide, facturation sans email…). Avant tout import, on produit un classeur via `build_tiers_xlsx.py` : **`mixgraine-tiers.xlsx`**.
|
||||
|
||||
- Un onglet **Synthèse** (compteurs) + un onglet par type : **Clients**, **Fournisseurs**, **Prestataires**.
|
||||
- Chaque onglet liste toutes les données, **une ligne par adresse** (colonnes du tiers répétées).
|
||||
- Colonne **Site manquant** (OUI/vide) + **filtre automatique** → un clic pour isoler les adresses sans site. Colonne **Problèmes** pour le reste. Lignes à problème surlignées.
|
||||
|
||||
Chiffres réels (extraction 2026-06-16, 1442 tiers) :
|
||||
|
||||
| Type | Tiers | Lignes (adresses) | Adresses sans site | Sans catégorie |
|
||||
|---|---|---|---|---|
|
||||
| Clients | 1129 | 1697 | 1111 | 444 (39 %) |
|
||||
| Fournisseurs | 412 | 1157 | 612 | 283 (68 %) |
|
||||
| Prestataires | 300 | 333 | 0 | 8 (2 %) |
|
||||
| **Total** | **1841\*** | **3187** | **1723** | **735** |
|
||||
|
||||
\* mixtes comptés en Client + Fournisseur. RIB extraits : 90. Tiers totalement bloqués : 90.
|
||||
|
||||
Motifs de blocage détectés :
|
||||
|
||||
| Niveau | Motif bloquant |
|
||||
|---|---|
|
||||
| Adresse | **aucun site rattaché** (RG-1.10/2.06/3.03), code postal absent/invalide, ville absente, rue absente, facturation sans email (client) |
|
||||
| Tiers | nom absent, `VIREMENT` sans banque, `LCR` sans RIB, **prestataire sans aucun site** (RG-3.03), catégorie `À QUALIFIER` |
|
||||
|
||||
Filtrer « Site manquant = OUI » dans chaque onglet permet de corriger la donnée à la source (re-cocher les organisations dans Mixgraine, compléter les emails) **avant** de relancer l'import (le cache accélère).
|
||||
|
||||
---
|
||||
|
||||
## 8. Séquence d'import recommandée
|
||||
|
||||
1. **Extraire la donnée complète** depuis l'endpoint unitaire (§ 9) — pas depuis l'export en masse.
|
||||
2. **Relecture** : `build_tiers_xlsx.py` → `mixgraine-tiers.xlsx` (un onglet par type, filtre « Site manquant »), faire corriger à la source (§ 7bis).
|
||||
2. **Sites** : créer les 3 sites (Châtellerault, Saint-Jean, Pommevic) + un site par défaut éventuel (§ 6).
|
||||
3. **Référentiels** : créer/compléter `Category` (~100 valeurs + défaut `À QUALIFIER`), `paymentDelay` (ajouter `J20`), `tvaMode`, vérifier `paymentType`, `bank` (CIC/SG/CA déjà OK) (§ 5).
|
||||
4. **Nettoyer** : 10 codes postaux invalides, parser les noms de contacts (civilité), convertir codes pays ISO → libellés (table fournie par le schéma `country`).
|
||||
5. **Importer dans l'ordre** : référentiels + sites → tiers → adresses (+ rattachement site via `organization_n`) → contacts (+ rattachement adresse + tél de l'objet de base) → RIB (`banks[]`).
|
||||
6. **Tiers mixtes** (106) : créer Client + Supplier (§ 4).
|
||||
7. **Gérer les 422 attendus** : adresses `isBilling=true` sans `billingEmail` ; `paymentType=VIREMENT` sans `bank`.
|
||||
|
||||
---
|
||||
|
||||
## 9. Stratégie d'extraction via l'API Mixgraine
|
||||
|
||||
L'export en masse est insuffisant (§ entête). La donnée complète s'obtient en deux temps depuis `https://liot.mixsuite.fr` (auth : `Authorization: Bearer <JWT>`) :
|
||||
|
||||
1. **Lister les ids par groupe, page par page** :
|
||||
`GET /api/customer/?fields=["name"]&filters={...}&limit=200&order=name&page=N`
|
||||
La réponse porte `count` (total) et `data[].id`. On pagine **trois listes filtrées** puis on fait l'union dédupliquée :
|
||||
- `{"customer":true}` → clients (`Client`),
|
||||
- `{"supplier":true}` → fournisseurs (`Supplier`),
|
||||
- `{"prestataire":true}` → prestataires (`Provider`, module Technique).
|
||||
|
||||
La **classification se fait par appartenance** à ces listes (plus fiable que les flags du formulaire `__data`) : un id dans `customer` ET `supplier` = mixte (Client + Supplier) ; un id dans `prestataire` = `Provider`. Le script produit `clients.json`, `suppliers.json`, `providers.json` + `referentials.json`.
|
||||
|
||||
2. **Récupérer le détail complet de chaque tiers** :
|
||||
`GET /api/customer/{id}` (objet riche : contacts, addresses, banks, liability, paymentType…)
|
||||
ou `PUT /api/customer/{id}` avec corps `{"__data":true}` qui renvoie en plus le **schéma de formulaire** (libellés des organisations/sites, choix des référentiels, FK distributor/courtier) **et** les valeurs sous `__data`.
|
||||
|
||||
Champs clés présents uniquement au détail : `banks[]` (RIB), `vatNumber`, `accountingBank`, `courtier`, `distributor`, `mails[]`, `addresses[].organization_1/2/3` (sites), `addresses[].carrierType`, `details.geo` (lat/lng par adresse).
|
||||
|
||||
> ⚠️ Le JWT fourni est un secret de session : ne pas le committer dans le repo. À passer en variable d'environnement au script d'extraction.
|
||||
|
||||
---
|
||||
|
||||
## 📦 Tickets Lesstime générés
|
||||
|
||||
TaskGroup Lesstime : **#32 — Migration tiers Mixgraine → Starseed** (projet STARSEED / ERP)
|
||||
|
||||
| # | Ticket | Réf. | Effort | Tag |
|
||||
|---|---|---|---|---|
|
||||
| 1.1 | Extraire et normaliser les tiers Mixgraine en JSON | ERP-174 | M | Backend |
|
||||
| 1.2 | Seeder les référentiels et les 3 sites | ERP-175 | M | Backend |
|
||||
| 1.3 | Importer les clients (Commercial) + adresses/contacts/RIB | ERP-176 | L | Backend |
|
||||
| 1.4 | Importer les fournisseurs (Commercial) + adresses/contacts/RIB | ERP-177 | M | Backend |
|
||||
| 1.5 | Importer les prestataires (Technique/Provider) | ERP-178 | M | Backend |
|
||||
| 1.6 | Relier distributeurs/courtiers, traiter les mixtes et vérifier | ERP-179 | M | Backend |
|
||||
|
||||
Tous au statut **Prêt à dev**. Prochaine action : lancer le 1.1 (le script `extract_mixgraine.py` est déjà écrit, reste à le tester avec un vrai token).
|
||||
|
||||
---
|
||||
|
||||
*Document basé sur l'analyse des exports en masse `client.json.json` / `fournisseur.json` / `fournisseur-client.json` et sur les réponses des endpoints `/api/customer/` (liste), `/api/customer/{id}` (détail) et `PUT /api/customer/{id}` (`__data`). Aucune donnée n'a été importée — rapport d'analyse préalable.*
|
||||
@@ -1,25 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Enchaine extraction Mixgraine + generation des Excel de relecture.
|
||||
# Usage : export MIXGRAINE_JWT="eyJ..." && ./run.sh
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
if [[ -z "${MIXGRAINE_JWT:-}" ]]; then
|
||||
echo "ERREUR : export MIXGRAINE_JWT='<ton token>' avant de lancer." >&2
|
||||
echo " (Chrome -> F12 -> Network -> requete api/customer -> header authorization: Bearer ...)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
OUT="${1:-mixgraine-export}"
|
||||
|
||||
echo "==> 1/2 Extraction Mixgraine (lent, ~1 req/s)..."
|
||||
python3 extract_mixgraine.py --out "$OUT"
|
||||
|
||||
echo "==> 2/2 Generation de l'Excel par type..."
|
||||
python3 build_tiers_xlsx.py --in "$OUT"
|
||||
|
||||
echo
|
||||
echo "Termine. Resultats dans : $OUT/"
|
||||
echo " - mixgraine-tiers.xlsx (1 onglet par type + Synthese, filtre 'Site manquant')"
|
||||
echo " - *.json + extraction-report.txt"
|
||||
+207
-14
@@ -495,6 +495,199 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"transport": {
|
||||
"carriers": {
|
||||
"title": "Répertoire transporteurs",
|
||||
"add": "Ajouter",
|
||||
"export": "Exporter",
|
||||
"empty": "Aucun transporteur pour l'instant.",
|
||||
"column": {
|
||||
"name": "Nom",
|
||||
"certification": "Certification",
|
||||
"validityDate": "Date de validité",
|
||||
"lastActivity": "Dernière activité"
|
||||
},
|
||||
"certification": {
|
||||
"QUALIMAT": "QUALIMAT",
|
||||
"GMP_PLUS": "GMP+",
|
||||
"OVOCOM": "OVOCOM",
|
||||
"COMPTE_PROPRE": "Compte-propre",
|
||||
"AUTRE": "Autre"
|
||||
},
|
||||
"filters": {
|
||||
"title": "Filtres",
|
||||
"search": "Recherche",
|
||||
"certification": "Certification",
|
||||
"status": "Statut",
|
||||
"archivedOnly": "Voir les archivés",
|
||||
"apply": "Voir les résultats",
|
||||
"reset": "Réinitialiser"
|
||||
},
|
||||
"toast": {
|
||||
"error": "Une erreur est survenue. Réessayez.",
|
||||
"exportError": "L'export du répertoire transporteurs a échoué. Réessayez.",
|
||||
"createSuccess": "Transporteur créé avec succès",
|
||||
"integrateSuccess": "Transporteur QUALIMAT intégré",
|
||||
"addressSaved": "Adresse enregistrée",
|
||||
"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": "Type de transport",
|
||||
"carrier": "Transporteurs",
|
||||
"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",
|
||||
"FOND_MOUVANT": "Fond mouvant"
|
||||
},
|
||||
"tab": {
|
||||
"qualimat": "Qualimat",
|
||||
"addresses": "Adresses",
|
||||
"contacts": "Contacts",
|
||||
"prices": "Prix"
|
||||
},
|
||||
"form": {
|
||||
"title": "Ajouter un transporteur",
|
||||
"back": "Retour au répertoire",
|
||||
"submit": "Valider",
|
||||
"comingSoon": "À venir",
|
||||
"duplicateName": "Un transporteur actif portant ce nom existe déjà.",
|
||||
"main": {
|
||||
"name": "Nom",
|
||||
"certificationType": "Certification transport",
|
||||
"isChartered": "Affréter",
|
||||
"indexationRate": "Indexation %",
|
||||
"containerType": "Benne / Fond mouvant",
|
||||
"volumeM3": "Volume m³",
|
||||
"discharge": "Décharge",
|
||||
"liotPlates": "Immatriculations LIOT",
|
||||
"liotPlatesHint": "Séparées par « ; »"
|
||||
},
|
||||
"qualimat": {
|
||||
"empty": "Aucun transporteur QUALIMAT trouvé.",
|
||||
"searchHint": "Saisissez le nom du transporteur pour lancer la recherche.",
|
||||
"columns": {
|
||||
"name": "Nom",
|
||||
"address": "Adresse",
|
||||
"validityDate": "Date de validité"
|
||||
},
|
||||
"confirm": {
|
||||
"title": "Intégration QUALIMAT",
|
||||
"message": "Êtes-vous sûr de vouloir intégrer ce transporteur ?",
|
||||
"cancel": "Annuler",
|
||||
"confirm": "Intégrer"
|
||||
}
|
||||
},
|
||||
"errors": {
|
||||
"nameRequired": "Le nom du transporteur est obligatoire.",
|
||||
"certificationRequired": "Le type de certification est obligatoire.",
|
||||
"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é.",
|
||||
"uploadFailed": "Le téléversement de la décharge a échoué."
|
||||
},
|
||||
"address": {
|
||||
"country": "Pays",
|
||||
"postalCode": "Code postal",
|
||||
"city": "Ville",
|
||||
"street": "Adresse",
|
||||
"streetComplement": "Adresse complémentaire",
|
||||
"streetNotFound": "Adresse introuvable ? Saisissez-la directement.",
|
||||
"degraded": "Service d'adresse indisponible : saisie de la ville et de l'adresse en mode libre."
|
||||
},
|
||||
"contact": {
|
||||
"lastName": "Nom",
|
||||
"firstName": "Prénom",
|
||||
"jobTitle": "Fonction",
|
||||
"phonePrimary": "Téléphone",
|
||||
"phoneSecondary": "Téléphone (2)",
|
||||
"addPhone": "Ajouter un numéro",
|
||||
"email": "Email",
|
||||
"add": "Nouveau contact",
|
||||
"remove": "Supprimer le contact"
|
||||
},
|
||||
"confirmDelete": {
|
||||
"title": "Supprimer ce bloc",
|
||||
"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."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"auth": {
|
||||
"login": "Connexion",
|
||||
"logout": "Deconnexion",
|
||||
@@ -537,27 +730,27 @@
|
||||
"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"
|
||||
},
|
||||
"empty": "Aucune activité enregistrée",
|
||||
"no_results": "Aucun résultat pour ces filtres",
|
||||
|
||||
@@ -41,9 +41,10 @@ export interface Supplier {
|
||||
* sur la ressource `/suppliers` (RG-13 : pagination serveur obligatoire ; jamais
|
||||
* de chargement integral en memoire). Miroir de `useClientsRepository` (M1).
|
||||
*
|
||||
* Les filtres (recherche, categories, sites, inclusion des archives) sont pilotes
|
||||
* par la page via `setFilters` du composable partage — la remise en page 1 est
|
||||
* garantie.
|
||||
* Les filtres (recherche, categories, sites, archives) sont pilotes par la page
|
||||
* via `setFilters` du composable partage — la remise en page 1 est garantie.
|
||||
* Cocher « Voir les archivés » envoie `archivedOnly=true` → seules les archives
|
||||
* sont listees (aligne sur Client).
|
||||
*
|
||||
* Volontairement PAR INSTANCE (pas de singleton module-level) : l'etat tableau
|
||||
* est propre a l'ecran Repertoire et meurt avec lui, comme tout consommateur de
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
<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)]">
|
||||
<!-- Pays : prerempli « France » (RG-4.05). -->
|
||||
<MalioSelect
|
||||
:model-value="model.country"
|
||||
:options="countryOptions"
|
||||
:label="t('transport.carriers.form.address.country')"
|
||||
:readonly="readonly"
|
||||
:required="true"
|
||||
:error="errors?.country"
|
||||
@update:model-value="(v: string | number | null) => update('country', String(v ?? 'France'))"
|
||||
/>
|
||||
|
||||
<!-- Code postal (RG-4.06) : declenche l'autocomplete ville (BAN). -->
|
||||
<MalioInputText
|
||||
:model-value="model.postalCode"
|
||||
:label="t('transport.carriers.form.address.postalCode')"
|
||||
:mask="POSTAL_CODE_MASK"
|
||||
:readonly="readonly"
|
||||
:required="true"
|
||||
:error="errors?.postalCode"
|
||||
@update:model-value="onPostalCodeChange"
|
||||
/>
|
||||
|
||||
<!-- Ville : MalioSelect alimente par le code postal (BAN). Saisie libre si BAN indispo. -->
|
||||
<MalioSelect
|
||||
v-if="!degraded"
|
||||
:model-value="model.city"
|
||||
:options="cityOptions"
|
||||
:label="t('transport.carriers.form.address.city')"
|
||||
:readonly="readonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="errors?.city"
|
||||
@update:model-value="(v: string | number | null) => update('city', v === null ? null : String(v))"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-else
|
||||
:model-value="model.city"
|
||||
:label="t('transport.carriers.form.address.city')"
|
||||
:readonly="readonly"
|
||||
:required="true"
|
||||
:error="errors?.city"
|
||||
@update:model-value="(v: string) => update('city', v)"
|
||||
/>
|
||||
|
||||
<!-- Filler : aligne le debut de la ligne suivante sur la grille. -->
|
||||
<div aria-hidden="true" />
|
||||
|
||||
<!-- Adresse (BAN) sur 2 colonnes + Adresse complementaire. allow-create : le
|
||||
texte saisi est conserve si la BAN ne propose rien (saisie manuelle). -->
|
||||
<div class="col-span-2">
|
||||
<MalioInputAutocomplete
|
||||
v-if="!readonly"
|
||||
:model-value="model.street"
|
||||
:options="addressOptions"
|
||||
:loading="addressLoading"
|
||||
:min-search-length="3"
|
||||
:label="t('transport.carriers.form.address.street')"
|
||||
:readonly="readonly"
|
||||
:required="true"
|
||||
:error="errors?.street"
|
||||
:allow-create="true"
|
||||
:no-results-text="t('transport.carriers.form.address.streetNotFound')"
|
||||
@update:model-value="(v: string | number | null) => update('street', v === null ? null : String(v))"
|
||||
@search="onAddressSearch"
|
||||
@select="onAddressSelect"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-else
|
||||
:model-value="model.street"
|
||||
:label="t('transport.carriers.form.address.street')"
|
||||
:readonly="readonly"
|
||||
:required="true"
|
||||
:error="errors?.street"
|
||||
@update:model-value="(v: string) => update('street', v)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<MalioInputText
|
||||
:model-value="model.streetComplement"
|
||||
:label="t('transport.carriers.form.address.streetComplement')"
|
||||
:readonly="readonly"
|
||||
:error="errors?.streetComplement"
|
||||
@update:model-value="(v: string) => update('streetComplement', v)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useAddressAutocomplete, type AddressSuggestion } from '~/shared/composables/useAddressAutocomplete'
|
||||
import type { CarrierAddressFormDraft } from '~/modules/transport/types/carrierForm'
|
||||
|
||||
interface RefOption {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
// Masque code postal FR : 5 chiffres.
|
||||
const POSTAL_CODE_MASK = '#####'
|
||||
|
||||
const props = defineProps<{
|
||||
/** Brouillon de l'adresse (v-model). */
|
||||
modelValue: CarrierAddressFormDraft
|
||||
/** Pays disponibles (France par defaut). */
|
||||
countryOptions: RefOption[]
|
||||
readonly?: boolean
|
||||
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: CarrierAddressFormDraft]
|
||||
/** Emis une fois quand le service d'autocompletion bascule en indisponible. */
|
||||
'degraded': []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const autocomplete = useAddressAutocomplete()
|
||||
|
||||
const model = computed(() => props.modelValue)
|
||||
|
||||
// Repli saisie libre de la VILLE quand la BAN est indisponible (recuperable).
|
||||
const degraded = ref(false)
|
||||
let unavailableNotified = false
|
||||
const banCityOptions = ref<RefOption[]>([])
|
||||
const banAddressOptions = ref<RefOption[]>([])
|
||||
|
||||
// Options ville effectives : on garantit que la ville courante figure toujours
|
||||
// dans la liste, sinon MalioSelect afficherait un champ vide en lecture seule.
|
||||
const cityOptions = computed<RefOption[]>(() => {
|
||||
const current = props.modelValue.city
|
||||
if (current && !banCityOptions.value.some(o => o.value === current)) {
|
||||
return [{ value: current, label: current }, ...banCityOptions.value]
|
||||
}
|
||||
return banCityOptions.value
|
||||
})
|
||||
|
||||
// Meme garantie pour le champ Adresse : la rue courante doit toujours figurer
|
||||
// dans les options, sinon MalioInputAutocomplete laisse le champ vide.
|
||||
const addressOptions = computed<RefOption[]>(() => {
|
||||
const current = props.modelValue.street
|
||||
if (current && !banAddressOptions.value.some(o => o.value === current)) {
|
||||
return [{ value: current, label: current }, ...banAddressOptions.value]
|
||||
}
|
||||
return banAddressOptions.value
|
||||
})
|
||||
const addressLoading = ref(false)
|
||||
// Conserve les suggestions d'adresse pour retrouver ville/CP au moment du select.
|
||||
let lastAddressSuggestions: AddressSuggestion[] = []
|
||||
|
||||
/** 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 })
|
||||
}
|
||||
|
||||
/** Previent le parent (toast unique) que l'autocompletion est indisponible. */
|
||||
function notifyUnavailable(): void {
|
||||
if (!unavailableNotified) {
|
||||
unavailableNotified = true
|
||||
emit('degraded')
|
||||
}
|
||||
}
|
||||
|
||||
/** Saisie du code postal → met a jour le champ + interroge la BAN pour la ville. */
|
||||
async function onPostalCodeChange(value: string): Promise<void> {
|
||||
update('postalCode', value)
|
||||
|
||||
const digits = (value ?? '').replace(/\D/g, '')
|
||||
if (digits.length < 5) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const suggestions = await autocomplete.searchCity(digits)
|
||||
banCityOptions.value = suggestions.map(s => ({ value: s.city, label: s.city }))
|
||||
degraded.value = false
|
||||
}
|
||||
catch {
|
||||
degraded.value = true
|
||||
notifyUnavailable()
|
||||
}
|
||||
}
|
||||
|
||||
/** Recherche d'adresse assistee (event de MalioInputAutocomplete). */
|
||||
async function onAddressSearch(query: string): Promise<void> {
|
||||
// La BAN exige au moins 3 caracteres : on n'envoie rien en deca (evite un 400).
|
||||
if (query.trim().length < 3) {
|
||||
banAddressOptions.value = []
|
||||
return
|
||||
}
|
||||
addressLoading.value = true
|
||||
try {
|
||||
const postalCode = (model.value.postalCode ?? '').replace(/\D/g, '') || undefined
|
||||
const suggestions = await autocomplete.searchAddress(query, postalCode)
|
||||
lastAddressSuggestions = suggestions
|
||||
banAddressOptions.value = suggestions.map(s => ({ value: s.street, label: s.label }))
|
||||
}
|
||||
catch {
|
||||
// Erreur transitoire : on vide les suggestions, la prochaine frappe reessaie.
|
||||
banAddressOptions.value = []
|
||||
notifyUnavailable()
|
||||
}
|
||||
finally {
|
||||
addressLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Selection d'une suggestion d'adresse → remplit rue + ville + CP. */
|
||||
function onAddressSelect(option: { label: string, value: string | number } | null): void {
|
||||
if (option === null) {
|
||||
return
|
||||
}
|
||||
const suggestion = lastAddressSuggestions.find(s => s.street === option.value)
|
||||
if (!suggestion) {
|
||||
update('street', String(option.value))
|
||||
return
|
||||
}
|
||||
emit('update:modelValue', {
|
||||
...props.modelValue,
|
||||
street: suggestion.street,
|
||||
city: suggestion.city,
|
||||
postalCode: suggestion.postalCode,
|
||||
})
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,108 @@
|
||||
<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 : ouvre une modal de confirmation côté parent. Masquée si
|
||||
non supprimable (1er bloc) ou en lecture seule. -->
|
||||
<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.contact.remove') }"
|
||||
@click="$emit('remove')"
|
||||
/>
|
||||
|
||||
<MalioInputText
|
||||
:model-value="model.lastName"
|
||||
:label="t('transport.carriers.form.contact.lastName')"
|
||||
:readonly="readonly"
|
||||
:error="errors?.lastName"
|
||||
@update:model-value="(v: string) => update('lastName', v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="model.firstName"
|
||||
:label="t('transport.carriers.form.contact.firstName')"
|
||||
:readonly="readonly"
|
||||
:error="errors?.firstName"
|
||||
@update:model-value="(v: string) => update('firstName', v)"
|
||||
/>
|
||||
<!-- Fonction sur 2 colonnes : on wrappe car MalioInputText (inheritAttrs:false)
|
||||
renvoie `class` sur l'input interne, pas sur la cellule de grille. -->
|
||||
<div class="col-span-2">
|
||||
<MalioInputText
|
||||
:model-value="model.jobTitle"
|
||||
:label="t('transport.carriers.form.contact.jobTitle')"
|
||||
:readonly="readonly"
|
||||
:error="errors?.jobTitle"
|
||||
@update:model-value="(v: string) => update('jobTitle', v)"
|
||||
/>
|
||||
</div>
|
||||
<MalioInputEmail
|
||||
:model-value="model.email"
|
||||
:label="t('transport.carriers.form.contact.email')"
|
||||
:readonly="readonly"
|
||||
:lowercase="true"
|
||||
:error="errors?.email"
|
||||
@update:model-value="(v: string) => update('email', v)"
|
||||
/>
|
||||
<!-- Téléphone principal + bouton « + » révélant le 2e numéro (max 2). -->
|
||||
<MalioInputPhone
|
||||
:model-value="model.phonePrimary"
|
||||
:label="t('transport.carriers.form.contact.phonePrimary')"
|
||||
:mask="PHONE_MASK"
|
||||
:readonly="readonly"
|
||||
:error="errors?.phonePrimary"
|
||||
:addable="!model.hasSecondaryPhone && !readonly"
|
||||
:add-button-label="t('transport.carriers.form.contact.addPhone')"
|
||||
@update:model-value="(v: string) => update('phonePrimary', v)"
|
||||
@add="revealSecondaryPhone"
|
||||
/>
|
||||
<!-- 2e numéro : révélé à la demande (max 2 téléphones — RG-4.08). -->
|
||||
<MalioInputPhone
|
||||
v-if="model.hasSecondaryPhone"
|
||||
:model-value="model.phoneSecondary"
|
||||
:label="t('transport.carriers.form.contact.phoneSecondary')"
|
||||
:mask="PHONE_MASK"
|
||||
:readonly="readonly"
|
||||
:error="errors?.phoneSecondary"
|
||||
@update:model-value="(v: string) => update('phoneSecondary', v)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { CarrierContactFormDraft } from '~/modules/transport/types/carrierForm'
|
||||
|
||||
// Masque téléphone FR : 5 groupes de 2 chiffres (la normalisation finale reste serveur).
|
||||
const PHONE_MASK = '## ## ## ## ##'
|
||||
|
||||
const props = defineProps<{
|
||||
/** Brouillon du contact (v-model). */
|
||||
modelValue: CarrierContactFormDraft
|
||||
/** Affiche l'icône de suppression (1er bloc non supprimable). */
|
||||
removable?: boolean
|
||||
/** Bloc en lecture seule (onglet validé). */
|
||||
readonly?: boolean
|
||||
/** Erreurs serveur 422 de cette ligne, indexées par champ (ERP-101). */
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: CarrierContactFormDraft]
|
||||
'remove': []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
// Alias local pour la lisibilité du template.
|
||||
const model = computed(() => props.modelValue)
|
||||
|
||||
/** É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 })
|
||||
}
|
||||
|
||||
/** Révèle le 2e numéro (max 1 secondaire, le « + » disparaît). */
|
||||
function revealSecondaryPhone(): void {
|
||||
emit('update:modelValue', { ...props.modelValue, hasSecondaryPhone: true })
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,307 @@
|
||||
<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"
|
||||
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"
|
||||
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"
|
||||
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"
|
||||
: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"
|
||||
: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"
|
||||
: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"
|
||||
: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"
|
||||
: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"
|
||||
: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"
|
||||
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"
|
||||
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"
|
||||
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"
|
||||
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"
|
||||
: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"
|
||||
: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
|
||||
/** 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>
|
||||
@@ -0,0 +1,150 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { mount, flushPromises } from '@vue/test-utils'
|
||||
import { defineComponent, h, ref, computed } from 'vue'
|
||||
import { emptyCarrierAddress } from '~/modules/transport/types/carrierForm'
|
||||
import CarrierAddressBlock from '../CarrierAddressBlock.vue'
|
||||
|
||||
/**
|
||||
* Tests de l'autocomplétion BAN du bloc Adresse transporteur (ERP-167) — réutilise
|
||||
* `useAddressAutocomplete` (M1/M2/M3). On vérifie le NOMINAL (CP → ville) et le
|
||||
* DÉGRADÉ (BAN indisponible → saisie libre + event `degraded`).
|
||||
*/
|
||||
|
||||
const { searchCityMock, searchAddressMock } = vi.hoisted(() => ({
|
||||
searchCityMock: vi.fn(),
|
||||
searchAddressMock: vi.fn(),
|
||||
}))
|
||||
vi.mock('~/shared/composables/useAddressAutocomplete', () => ({
|
||||
useAddressAutocomplete: () => ({
|
||||
searchCity: searchCityMock,
|
||||
searchAddress: searchAddressMock,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.stubGlobal('useI18n', () => ({ t: (key: string) => key }))
|
||||
vi.stubGlobal('ref', ref)
|
||||
vi.stubGlobal('computed', computed)
|
||||
|
||||
const MalioInputTextStub = defineComponent({
|
||||
name: 'MalioInputText',
|
||||
props: { modelValue: { default: null }, label: { type: String, default: '' }, error: { type: String, default: '' } },
|
||||
emits: ['update:modelValue'],
|
||||
setup(props) {
|
||||
return () => h('div', { 'data-testid': 'input-text', 'data-label': props.label, 'data-error': props.error })
|
||||
},
|
||||
})
|
||||
|
||||
const MalioSelectStub = defineComponent({
|
||||
name: 'MalioSelect',
|
||||
props: { modelValue: { default: null }, options: { type: Array as () => { value: string }[], default: () => [] }, label: { type: String, default: '' }, error: { type: String, default: '' } },
|
||||
emits: ['update:modelValue'],
|
||||
setup(props) {
|
||||
return () => h('div', { 'data-testid': 'select', 'data-label': props.label, 'data-options': JSON.stringify(props.options.map(o => o.value)) })
|
||||
},
|
||||
})
|
||||
|
||||
const MalioInputAutocompleteStub = defineComponent({
|
||||
name: 'MalioInputAutocomplete',
|
||||
props: { modelValue: { default: null }, options: { type: Array as () => { value: string }[], default: () => [] }, loading: { type: Boolean, default: false }, allowCreate: { type: Boolean, default: false } },
|
||||
emits: ['update:modelValue', 'search', 'select'],
|
||||
setup(props) {
|
||||
return () => h('div', { 'data-testid': 'addr-autocomplete', 'data-options': JSON.stringify(props.options.map(o => o.value)) })
|
||||
},
|
||||
})
|
||||
|
||||
function mountBlock(overrides: Record<string, unknown> = {}) {
|
||||
return mount(CarrierAddressBlock, {
|
||||
props: {
|
||||
modelValue: { ...emptyCarrierAddress(), ...overrides },
|
||||
countryOptions: [{ value: 'France', label: 'France' }],
|
||||
},
|
||||
global: {
|
||||
stubs: {
|
||||
MalioButtonIcon: true,
|
||||
MalioInputText: MalioInputTextStub,
|
||||
MalioSelect: MalioSelectStub,
|
||||
MalioInputAutocomplete: MalioInputAutocompleteStub,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** Récupère le composant MalioInputText d'un label donné. */
|
||||
function inputTextByLabel(wrapper: ReturnType<typeof mountBlock>, label: string) {
|
||||
return wrapper.findAllComponents(MalioInputTextStub).find(c => c.props('label') === label)
|
||||
}
|
||||
|
||||
describe('CarrierAddressBlock — autocomplétion ville (BAN) NOMINAL', () => {
|
||||
beforeEach(() => {
|
||||
searchCityMock.mockReset()
|
||||
searchAddressMock.mockReset()
|
||||
})
|
||||
|
||||
it('saisie d\'un CP à 5 chiffres → searchCity + peuple le select Ville', async () => {
|
||||
searchCityMock.mockResolvedValueOnce([{ city: 'Poitiers', postalCode: '86000' }])
|
||||
const wrapper = mountBlock()
|
||||
|
||||
const cp = inputTextByLabel(wrapper, 'transport.carriers.form.address.postalCode')
|
||||
cp?.vm.$emit('update:modelValue', '86000')
|
||||
await flushPromises()
|
||||
|
||||
expect(searchCityMock).toHaveBeenCalledWith('86000')
|
||||
const citySelect = wrapper.findAllComponents(MalioSelectStub).find(c => c.props('label') === 'transport.carriers.form.address.city')
|
||||
const options = JSON.parse(citySelect?.attributes('data-options') ?? '[]')
|
||||
expect(options).toContain('Poitiers')
|
||||
expect(wrapper.emitted('degraded')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('n\'interroge pas la BAN sous 5 chiffres', async () => {
|
||||
const wrapper = mountBlock()
|
||||
inputTextByLabel(wrapper, 'transport.carriers.form.address.postalCode')?.vm.$emit('update:modelValue', '860')
|
||||
await flushPromises()
|
||||
expect(searchCityMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('CarrierAddressBlock — autocomplétion DÉGRADÉE', () => {
|
||||
beforeEach(() => {
|
||||
searchCityMock.mockReset()
|
||||
searchAddressMock.mockReset()
|
||||
})
|
||||
|
||||
it('BAN ville indisponible → bascule en saisie libre + émet « degraded »', async () => {
|
||||
searchCityMock.mockRejectedValueOnce(new Error('BAN indisponible'))
|
||||
const wrapper = mountBlock()
|
||||
|
||||
inputTextByLabel(wrapper, 'transport.carriers.form.address.postalCode')?.vm.$emit('update:modelValue', '86000')
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.emitted('degraded')).toHaveLength(1)
|
||||
// En dégradé, la Ville devient un MalioInputText (plus de MalioSelect ville).
|
||||
const citySelect = wrapper.findAllComponents(MalioSelectStub).find(c => c.props('label') === 'transport.carriers.form.address.city')
|
||||
expect(citySelect).toBeUndefined()
|
||||
expect(inputTextByLabel(wrapper, 'transport.carriers.form.address.city')).toBeDefined()
|
||||
})
|
||||
|
||||
it('autocomplétion adresse : pas d\'appel BAN sous 3 caractères', async () => {
|
||||
const wrapper = mountBlock()
|
||||
wrapper.findComponent(MalioInputAutocompleteStub).vm.$emit('search', 'ab')
|
||||
await flushPromises()
|
||||
expect(searchAddressMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('autocomplétion adresse : émet « degraded » une seule fois malgré plusieurs erreurs', async () => {
|
||||
searchAddressMock.mockRejectedValue(new Error('BAN indisponible'))
|
||||
const wrapper = mountBlock()
|
||||
const auto = wrapper.findComponent(MalioInputAutocompleteStub)
|
||||
|
||||
auto.vm.$emit('search', 'rue de la paix')
|
||||
await flushPromises()
|
||||
auto.vm.$emit('search', 'rue de la paixx')
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.emitted('degraded')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('active allow-create sur le champ Adresse (saisie manuelle libre)', () => {
|
||||
const wrapper = mountBlock()
|
||||
expect(wrapper.findComponent(MalioInputAutocompleteStub).props('allowCreate')).toBe(true)
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,97 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { useCarriersRepository, type Carrier } from '../useCarriersRepository'
|
||||
|
||||
const mockApiGet = vi.hoisted(() => vi.fn())
|
||||
vi.stubGlobal('useApi', () => ({ get: mockApiGet }))
|
||||
|
||||
/**
|
||||
* Tests du repertoire transporteurs (ERP-164).
|
||||
*
|
||||
* `useCarriersRepository` est une fine enveloppe de `usePaginatedList<Carrier>`
|
||||
* sur `/carriers`. Les invariants generiques de pagination sont deja couverts par
|
||||
* `usePaginatedList.test.ts` ; on verifie ici le CONTRAT propre au repertoire :
|
||||
* - la ressource ciblee est bien `/carriers` ;
|
||||
* - l'enveloppe Hydra (member / totalItems) est consommee ;
|
||||
* - le header `Accept: application/ld+json` est envoye (sinon API Platform 4
|
||||
* renvoie un tableau plat sans pagination) ;
|
||||
* - EXCLUSION DES ARCHIVES PAR DEFAUT : aucun `archivedOnly` n'est envoye
|
||||
* tant que l'utilisateur ne coche pas le filtre (le back masque alors les
|
||||
* archives) ; le filtre « Voir les archivés » est bien transmis une fois
|
||||
* applique (aligne sur Client / Fournisseur / Prestataire).
|
||||
*/
|
||||
describe('useCarriersRepository', () => {
|
||||
beforeEach(() => {
|
||||
mockApiGet.mockReset()
|
||||
})
|
||||
|
||||
/** Une page de transporteurs Hydra, avec qualimatCarrier embarque (RG-4.04). */
|
||||
const PAGE: Carrier[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: 'TRANSPORTS ACME',
|
||||
certificationType: 'QUALIMAT',
|
||||
qualimatCarrier: {
|
||||
id: '42',
|
||||
name: 'TRANSPORTS ACME',
|
||||
validityDate: '2027-01-15',
|
||||
status: 'VALIDE',
|
||||
},
|
||||
updatedAt: '2026-06-15T08:12:01+02:00',
|
||||
isArchived: false,
|
||||
},
|
||||
]
|
||||
|
||||
it('cible /carriers, consomme l\'enveloppe Hydra et envoie l\'Accept ld+json', async () => {
|
||||
mockApiGet.mockResolvedValueOnce({ member: PAGE, totalItems: 1 })
|
||||
const repo = useCarriersRepository()
|
||||
|
||||
await repo.fetch()
|
||||
|
||||
expect(mockApiGet).toHaveBeenCalledTimes(1)
|
||||
const [url, query, opts] = mockApiGet.mock.calls[0]
|
||||
expect(url).toBe('/carriers')
|
||||
expect(query).toMatchObject({ page: 1, itemsPerPage: 10 })
|
||||
expect(opts).toMatchObject({
|
||||
toast: false,
|
||||
headers: { Accept: 'application/ld+json' },
|
||||
})
|
||||
expect(repo.items.value).toEqual(PAGE)
|
||||
expect(repo.totalItems.value).toBe(1)
|
||||
})
|
||||
|
||||
it('exclut les archives par defaut : aucun archivedOnly au premier fetch', async () => {
|
||||
mockApiGet.mockResolvedValueOnce({ member: PAGE, totalItems: 1 })
|
||||
const repo = useCarriersRepository()
|
||||
|
||||
await repo.fetch()
|
||||
|
||||
const query = mockApiGet.mock.calls[0][1] as Record<string, unknown>
|
||||
expect(query.archivedOnly).toBeUndefined()
|
||||
})
|
||||
|
||||
it('transmet archivedOnly une fois le filtre applique (retour page 1)', async () => {
|
||||
mockApiGet.mockResolvedValueOnce({ member: PAGE, totalItems: 1 })
|
||||
const repo = useCarriersRepository()
|
||||
await repo.fetch()
|
||||
|
||||
mockApiGet.mockResolvedValueOnce({ member: PAGE, totalItems: 1 })
|
||||
await repo.setFilters({ archivedOnly: true })
|
||||
|
||||
expect(repo.currentPage.value).toBe(1)
|
||||
const query = mockApiGet.mock.calls.at(-1)?.[1] as Record<string, unknown>
|
||||
expect(query.archivedOnly).toBe(true)
|
||||
})
|
||||
|
||||
it('transmet les certifications multiples + la recherche', async () => {
|
||||
mockApiGet.mockResolvedValueOnce({ member: PAGE, totalItems: 1 })
|
||||
const repo = useCarriersRepository()
|
||||
await repo.fetch()
|
||||
|
||||
mockApiGet.mockResolvedValueOnce({ member: PAGE, totalItems: 1 })
|
||||
await repo.setFilters({ search: 'acme', 'certificationType[]': ['QUALIMAT', 'AUTRE'] })
|
||||
|
||||
const query = mockApiGet.mock.calls.at(-1)?.[1] as Record<string, unknown>
|
||||
expect(query.search).toBe('acme')
|
||||
expect(query['certificationType[]']).toEqual(['QUALIMAT', 'AUTRE'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { useQualimatSearch, type QualimatCarrierRow } from '../useQualimatSearch'
|
||||
|
||||
const mockApiGet = vi.hoisted(() => vi.fn())
|
||||
vi.stubGlobal('useApi', () => ({ get: mockApiGet }))
|
||||
|
||||
/**
|
||||
* Tests de la saisie assistée QUALIMAT (M4 Transport, ERP-166 — RG-4.01).
|
||||
*
|
||||
* `useQualimatSearch` est une fine enveloppe de `usePaginatedList<QualimatCarrierRow>`
|
||||
* sur `/qualimat_carriers`. La pagination générique est couverte par
|
||||
* `usePaginatedList.test.ts` ; on vérifie ici le CONTRAT propre à la recherche :
|
||||
* - ressource ciblée `/qualimat_carriers` + enveloppe Hydra + `Accept: application/ld+json` ;
|
||||
* - le filtre `search` (branché sur le nom du transporteur) est transmis et
|
||||
* retombe en page 1.
|
||||
*/
|
||||
describe('useQualimatSearch', () => {
|
||||
beforeEach(() => {
|
||||
mockApiGet.mockReset()
|
||||
})
|
||||
|
||||
const PAGE: QualimatCarrierRow[] = [
|
||||
{
|
||||
'@id': '/api/qualimat_carriers/1',
|
||||
id: '1',
|
||||
name: 'TRANSPORTS ACME',
|
||||
siret: '12345678900012',
|
||||
address: '1 rue du Port',
|
||||
postalCode: '86000',
|
||||
city: 'Poitiers',
|
||||
validityDate: '2027-01-15',
|
||||
status: 'VALIDE',
|
||||
},
|
||||
]
|
||||
|
||||
it('cible /qualimat_carriers, consomme l\'enveloppe Hydra et envoie l\'Accept ld+json', async () => {
|
||||
mockApiGet.mockResolvedValueOnce({ member: PAGE, totalItems: 1 })
|
||||
const repo = useQualimatSearch()
|
||||
|
||||
await repo.fetch()
|
||||
|
||||
const [url, query, opts] = mockApiGet.mock.calls[0]
|
||||
expect(url).toBe('/qualimat_carriers')
|
||||
expect(query).toMatchObject({ page: 1, itemsPerPage: 10 })
|
||||
expect(opts).toMatchObject({ toast: false, headers: { Accept: 'application/ld+json' } })
|
||||
expect(repo.items.value).toEqual(PAGE)
|
||||
expect(repo.totalItems.value).toBe(1)
|
||||
})
|
||||
|
||||
it('transmet le filtre `search` (nom du transporteur) et retombe en page 1', async () => {
|
||||
mockApiGet.mockResolvedValueOnce({ member: PAGE, totalItems: 1 })
|
||||
const repo = useQualimatSearch()
|
||||
await repo.fetch()
|
||||
|
||||
mockApiGet.mockResolvedValueOnce({ member: PAGE, totalItems: 1 })
|
||||
await repo.setFilters({ search: 'acme' })
|
||||
|
||||
expect(repo.currentPage.value).toBe(1)
|
||||
const query = mockApiGet.mock.calls.at(-1)?.[1] as Record<string, unknown>
|
||||
expect(query.search).toBe('acme')
|
||||
})
|
||||
})
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,835 @@
|
||||
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 {
|
||||
emptyCarrierAddress,
|
||||
emptyCarrierAddressCopy,
|
||||
emptyCarrierContact,
|
||||
emptyCarrierMain,
|
||||
emptyCarrierPrice,
|
||||
type CarrierAddressCopy,
|
||||
type CarrierAddressFormDraft,
|
||||
type CarrierContactFormDraft,
|
||||
type CarrierMainDraft,
|
||||
type CarrierMainResponse,
|
||||
type CarrierPriceFormDraft,
|
||||
} from '~/modules/transport/types/carrierForm'
|
||||
import { buildCarrierAddressPayload } from '~/modules/transport/utils/forms/carrierAddress'
|
||||
import { buildCarrierContactPayload, isCarrierContactBlank, isCarrierContactNamed } 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). */
|
||||
const LIOT_NAME = 'LIOT'
|
||||
|
||||
/**
|
||||
* Workflow de l'écran « Ajouter un transporteur » (M4 Transport, ERP-165) —
|
||||
* miroir conceptuel de `useSupplierForm` (M2) / `useProviderForm` (M3).
|
||||
*
|
||||
* Périmètre ERP-165 : le formulaire PRINCIPAL (pré-onglets) et l'orchestration de
|
||||
* la barre d'onglets. La création est INCRÉMENTALE (spec-front § Écran Ajouter) :
|
||||
* - on POST d'abord le formulaire principal (`POST /api/carriers`) ;
|
||||
* - au succès le bloc principal passe en lecture seule, le 1er onglet (Qualimat)
|
||||
* se déverrouille et devient actif ;
|
||||
* - chaque onglet validé déverrouille le suivant (PATCH partiels par groupe de
|
||||
* sérialisation) et passe en lecture seule.
|
||||
*
|
||||
* Les champs conditionnels du formulaire principal (indexation / benne / volume
|
||||
* si affrété, décharge si AUTRE, cas LIOT) et la saisie assistée QUALIMAT arrivent
|
||||
* à ERP-166 ; le contenu des onglets Adresses / Contacts / Prix aux tickets
|
||||
* suivants. Ce composable pose le POST principal, le PATCH partiel et le gating
|
||||
* des onglets.
|
||||
*
|
||||
* État 100 % local à l'instance (refs / reactive) — aucune persistance URL.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Clés des onglets du flux de création, dans l'ordre de la barre (spec-front
|
||||
* § Écran Ajouter). Toujours les 4 (pas de gating par permission au M4, ≠ l'onglet
|
||||
* Comptabilité du M3).
|
||||
*/
|
||||
export const CARRIER_TAB_KEYS = ['qualimat', 'addresses', 'contacts', 'prices'] as const
|
||||
|
||||
export function useCarrierForm() {
|
||||
const api = useApi()
|
||||
const { t } = useI18n()
|
||||
const toast = useToast()
|
||||
|
||||
// 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)
|
||||
const mainSubmitting = ref(false)
|
||||
const tabSubmitting = ref(false)
|
||||
|
||||
// ── Formulaire principal ──────────────────────────────────────────────────
|
||||
const main = reactive<CarrierMainDraft>(emptyCarrierMain())
|
||||
|
||||
// Adresse copiée depuis QUALIMAT à la sélection (alimente l'onglet Adresses,
|
||||
// ticket ultérieur). Vide tant qu'aucun transporteur QUALIMAT n'est intégré.
|
||||
const qualimatAddress = ref<CarrierAddressCopy>(emptyCarrierAddressCopy())
|
||||
|
||||
// ── Affichage conditionnel du formulaire principal (RG-4.01 / 4.02 / 4.03) ──
|
||||
// Cas LIOT : nom == « LIOT » → seul `liotPlates` est pertinent, le reste masqué.
|
||||
const isLiot = computed(() => main.name.trim().toUpperCase() === LIOT_NAME)
|
||||
// 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 && !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)
|
||||
// RG-4.02 : décharge visible et obligatoire si certification == AUTRE (hors LIOT).
|
||||
const showDischarge = computed(() => main.certificationType === 'AUTRE' && !isLiot.value)
|
||||
|
||||
// ── Onglets : ordre + gating progressif ───────────────────────────────────
|
||||
const tabKeys = ref<string[]>([...CARRIER_TAB_KEYS])
|
||||
// Index du dernier onglet déverrouillé. L'onglet Qualimat (index 0) est la saisie
|
||||
// assistée du formulaire principal : accessible DÈS LE DÉPART (≠ Adresses /
|
||||
// Contacts / Prix, déverrouillés seulement après le POST principal).
|
||||
const unlockedIndex = ref(0)
|
||||
const activeTab = ref<string>(CARRIER_TAB_KEYS[0])
|
||||
// Onglets validés (passent en lecture seule).
|
||||
const validated = reactive<Record<string, boolean>>({})
|
||||
// Mode MODIFICATION (ticket ultérieur) : navigation libre, pas de verrouillage
|
||||
// ni de bascule automatique d'onglet à la validation (cf. completeTab).
|
||||
const editMode = ref(false)
|
||||
|
||||
function isValidated(key: string): boolean {
|
||||
return validated[key] === true
|
||||
}
|
||||
|
||||
function tabIndex(key: string): number {
|
||||
return tabKeys.value.indexOf(key)
|
||||
}
|
||||
|
||||
/**
|
||||
* Validation FRONT du formulaire principal : seul le nom est requis côté front
|
||||
* (ERP-101) : feedback immédiat sur tous les champs obligatoires (y compris
|
||||
* conditionnels), alignés sur les RG du back (qui reste autoritaire) :
|
||||
* - RG-4.01 : nom requis ; certification requise hors cas LIOT (où tout est masqué) ;
|
||||
* - RG-4.02 : décharge requise si certification AUTRE ;
|
||||
* - RG-4.03 : indexation + contenant + volume requis si « Affréter ».
|
||||
*/
|
||||
function validateMainFront(): boolean {
|
||||
let valid = true
|
||||
if (!main.name?.trim()) {
|
||||
mainErrors.setError('name', t('transport.carriers.form.errors.nameRequired'))
|
||||
valid = false
|
||||
}
|
||||
|
||||
// Cas LIOT : seul le nom compte, les autres champs sont masqués (RG-4.01).
|
||||
if (isLiot.value) {
|
||||
return valid
|
||||
}
|
||||
|
||||
// RG-4.01 : certification obligatoire hors LIOT.
|
||||
if (!main.certificationType) {
|
||||
mainErrors.setError('certificationType', t('transport.carriers.form.errors.certificationRequired'))
|
||||
valid = false
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// RG-4.03 : indexation / contenant / volume obligatoires si affrété.
|
||||
if (main.isChartered) {
|
||||
if (!main.indexationRate.trim()) {
|
||||
mainErrors.setError('indexationRate', t('transport.carriers.form.errors.indexationRequired'))
|
||||
valid = false
|
||||
}
|
||||
if (!main.containerType) {
|
||||
mainErrors.setError('containerType', t('transport.carriers.form.errors.containerTypeRequired'))
|
||||
valid = false
|
||||
}
|
||||
if (!main.volumeM3.trim()) {
|
||||
mainErrors.setError('volumeM3', t('transport.carriers.form.errors.volumeRequired'))
|
||||
valid = false
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
* violation métier (NotBlank sur le nom, « certification obligatoire » sur la
|
||||
* certification) sur le champ plutôt qu'une erreur de type.
|
||||
*/
|
||||
function buildMainPayload(): Record<string, unknown> {
|
||||
// Cas LIOT (RG-4.01) : seul `liotPlates` est pertinent ; les autres champs
|
||||
// sont masqués côté front et non envoyés (le back stocke ce qu'il reçoit).
|
||||
if (isLiot.value) {
|
||||
const payload: Record<string, unknown> = { name: main.name, isChartered: false }
|
||||
if (main.liotPlates.trim()) {
|
||||
payload.liotPlates = main.liotPlates
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
const payload: Record<string, unknown> = { isChartered: main.isChartered }
|
||||
if (main.name.trim()) {
|
||||
payload.name = main.name
|
||||
}
|
||||
if (main.certificationType) {
|
||||
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) {
|
||||
payload.dischargeDocument = main.dischargeDocumentIri
|
||||
}
|
||||
// RG-4.03 : indexation / contenant / volume envoyés seulement si affrété ;
|
||||
// omis quand vides pour déclencher la 422 NotBlank inline sur le champ.
|
||||
if (main.isChartered) {
|
||||
if (main.indexationRate.trim()) {
|
||||
payload.indexationRate = main.indexationRate
|
||||
}
|
||||
if (main.containerType) {
|
||||
payload.containerType = main.containerType
|
||||
}
|
||||
if (main.volumeM3.trim()) {
|
||||
payload.volumeM3 = main.volumeM3
|
||||
}
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /carriers (groupe `carrier:write:main`). Pré-check front, puis création.
|
||||
* Au succès : verrouille le bloc principal, déverrouille l'onglet Adresses et
|
||||
* bascule dessus (l'onglet Qualimat, saisie assistée, était déjà accessible).
|
||||
* Retourne true si créé, false sinon.
|
||||
*/
|
||||
async function submitMain(): Promise<boolean> {
|
||||
if (mainSubmitting.value) return false
|
||||
mainErrors.clearErrors()
|
||||
if (!validateMainFront()) return false
|
||||
|
||||
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,
|
||||
})
|
||||
|
||||
carrierId.value = created.id
|
||||
// Réaffiche les valeurs normalisées renvoyées par le serveur (nom en
|
||||
// UPPERCASE — RG-4.13 ; certification éventuellement forcée).
|
||||
main.name = created.name ?? main.name
|
||||
main.certificationType = created.certificationType ?? main.certificationType
|
||||
|
||||
mainLocked.value = true
|
||||
// Déverrouille l'onglet suivant (Adresses, index 1) et bascule dessus.
|
||||
unlockedIndex.value = Math.max(unlockedIndex.value, 1)
|
||||
activeTab.value = tabKeys.value[1] ?? CARRIER_TAB_KEYS[1]
|
||||
toast.success({ title: t('transport.carriers.toast.createSuccess') })
|
||||
return true
|
||||
}
|
||||
catch (error) {
|
||||
// 409 = doublon de nom (RG-4.12) → erreur inline dédiée + toast ;
|
||||
// 422 → mapping inline par champ ; autre → toast de fallback (ERP-101).
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* tickets suivants. No-op tant que le transporteur n'existe pas.
|
||||
*/
|
||||
async function patchCarrier(payload: Record<string, unknown>): Promise<void> {
|
||||
if (carrierId.value === null) return
|
||||
await api.patch(`/carriers/${carrierId.value}`, payload, { toast: false })
|
||||
}
|
||||
|
||||
/** Remontée d'erreur de suppression immédiate d'une sous-ressource (toast dédié). */
|
||||
function notifyRemovalError(error: unknown): void {
|
||||
toast.error({
|
||||
title: t('transport.carriers.toast.error'),
|
||||
message: extractApiErrorMessage((error as { data?: unknown })?.data) || t('transport.carriers.toast.error'),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* cible, tente chaque ligne via `saveRow`, mappe les 422 inline ou délègue le
|
||||
* fallback à `onUnmappedError`. `shouldSkip` ignore les amorces vides. Retourne
|
||||
* true si au moins un bloc a échoué. Miroir de `useProviderForm.submitRows`.
|
||||
*/
|
||||
async function submitRows<T>(
|
||||
rows: T[],
|
||||
target: Ref<Record<string, string>[]>,
|
||||
saveRow: (row: T, index: number) => Promise<void>,
|
||||
onUnmappedError: (error: unknown, index: number) => void,
|
||||
shouldSkip?: (row: T, index: number) => boolean,
|
||||
): Promise<boolean> {
|
||||
target.value = []
|
||||
let hasError = false
|
||||
for (let index = 0; index < rows.length; index++) {
|
||||
const row = rows[index] as T
|
||||
if (shouldSkip?.(row, index)) {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
await saveRow(row, index)
|
||||
}
|
||||
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) {
|
||||
target.value[index] = mapped
|
||||
}
|
||||
else {
|
||||
onUnmappedError(error, index)
|
||||
}
|
||||
hasError = true
|
||||
}
|
||||
}
|
||||
return hasError
|
||||
}
|
||||
|
||||
// ── 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 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 été validé.
|
||||
*/
|
||||
async function submitAddress(onError: (error: unknown) => void): Promise<boolean> {
|
||||
if (carrierId.value === null || tabSubmitting.value) {
|
||||
return false
|
||||
}
|
||||
tabSubmitting.value = true
|
||||
addressErrors.value = {}
|
||||
try {
|
||||
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')
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// ── Onglet Contacts (ERP-168) ─────────────────────────────────────────────
|
||||
const contacts = ref<CarrierContactFormDraft[]>([emptyCarrierContact()])
|
||||
// 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).
|
||||
const canAddContact = computed(() => {
|
||||
const last = contacts.value[contacts.value.length - 1]
|
||||
return last !== undefined && isCarrierContactNamed(last)
|
||||
})
|
||||
|
||||
function addContact(): void {
|
||||
if (canAddContact.value) {
|
||||
contacts.value.push(emptyCarrierContact())
|
||||
}
|
||||
}
|
||||
|
||||
/** Suppression immédiate d'un contact existant (DELETE /carrier_contacts/{id}). */
|
||||
async function removeContact(index: number): Promise<void> {
|
||||
await removeCollectionRow({
|
||||
rows: contacts.value,
|
||||
errors: contactErrors.value,
|
||||
index,
|
||||
endpoint: '/carrier_contacts',
|
||||
deleteRow: url => api.delete(url, {}, { toast: false }),
|
||||
makeEmpty: emptyCarrierContact,
|
||||
onError: notifyRemovalError,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 été validé.
|
||||
*/
|
||||
async function submitContacts(onError: (error: unknown) => void): Promise<boolean> {
|
||||
if (carrierId.value === null || tabSubmitting.value) {
|
||||
return false
|
||||
}
|
||||
tabSubmitting.value = true
|
||||
try {
|
||||
const hasSubmittable = contacts.value.some(c => c.id !== null || !isCarrierContactBlank(c))
|
||||
const hasError = await submitRows(
|
||||
contacts.value,
|
||||
contactErrors,
|
||||
async (contact) => {
|
||||
const body = buildCarrierContactPayload(contact)
|
||||
if (contact.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/carriers/${carrierId.value}/contacts`,
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
contact.id = created.id
|
||||
}
|
||||
else {
|
||||
await api.patch(`/carrier_contacts/${contact.id}`, body, { toast: false })
|
||||
}
|
||||
},
|
||||
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),
|
||||
)
|
||||
if (hasError) {
|
||||
return false
|
||||
}
|
||||
completeTab('contacts')
|
||||
return true
|
||||
}
|
||||
finally {
|
||||
tabSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ── 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,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.09→4.11) est re-validée back →
|
||||
* 422 par ligne. Onglet Prix optionnel : une liste vide finalise sans appel.
|
||||
* Retourne true si l'onglet a été 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),
|
||||
* pose la FK `qualimatCarrier` (IRI) et copie l'adresse (pour l'onglet Adresses).
|
||||
* Si le transporteur existe déjà (post-POST, cas nominal de l'onglet), persiste
|
||||
* d'abord la copie via un PATCH partiel `carrier:write:main` : la copie locale
|
||||
* (nom, certification figée « QUALIMAT », FK, adresse) n'est appliquée qu'en cas
|
||||
* de succès, pour ne pas laisser l'UI dans un état QUALIMAT non sauvegardé si le
|
||||
* PATCH échoue. Retourne true si l'intégration a abouti.
|
||||
*/
|
||||
async function applyQualimatSelection(row: QualimatCarrierRow): Promise<boolean> {
|
||||
// Transporteur déjà créé : on persiste avant de refléter localement.
|
||||
if (carrierId.value !== null) {
|
||||
try {
|
||||
await patchCarrier({
|
||||
qualimatCarrier: row['@id'],
|
||||
name: row.name,
|
||||
certificationType: 'QUALIMAT',
|
||||
})
|
||||
}
|
||||
catch (error) {
|
||||
mainErrors.handleApiError(error, { fallbackMessage: t('transport.carriers.toast.error') })
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
main.name = row.name ?? ''
|
||||
main.certificationType = 'QUALIMAT'
|
||||
main.qualimatCarrierIri = row['@id']
|
||||
qualimatAddress.value = {
|
||||
country: 'France',
|
||||
postalCode: row.postalCode ?? '',
|
||||
city: row.city ?? '',
|
||||
street: row.address ?? '',
|
||||
}
|
||||
// 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
|
||||
}
|
||||
|
||||
/**
|
||||
* Marque un onglet validé (passe en lecture seule), déverrouille et avance à
|
||||
* l'onglet suivant. Retourne true si c'était le dernier onglet du flux (création
|
||||
* terminée), false sinon.
|
||||
*/
|
||||
function completeTab(key: string): boolean {
|
||||
// En modification : navigation libre, l'onglet reste éditable après validation.
|
||||
if (editMode.value) {
|
||||
return false
|
||||
}
|
||||
validated[key] = true
|
||||
const index = tabIndex(key)
|
||||
const next = tabKeys.value[index + 1]
|
||||
if (next === undefined) {
|
||||
return true
|
||||
}
|
||||
unlockedIndex.value = Math.max(unlockedIndex.value, index + 1)
|
||||
activeTab.value = next
|
||||
return false
|
||||
}
|
||||
|
||||
return {
|
||||
// état
|
||||
main,
|
||||
qualimatAddress,
|
||||
carrierId,
|
||||
mainLocked,
|
||||
mainSubmitting,
|
||||
tabSubmitting,
|
||||
mainErrors,
|
||||
dischargeUploading,
|
||||
// affichage conditionnel
|
||||
isLiot,
|
||||
isQualimat,
|
||||
showCertification,
|
||||
certificationReadonly,
|
||||
showCharteredFields,
|
||||
showDischarge,
|
||||
// onglets
|
||||
tabKeys,
|
||||
activeTab,
|
||||
unlockedIndex,
|
||||
validated,
|
||||
editMode,
|
||||
isValidated,
|
||||
// adresse (unique)
|
||||
address,
|
||||
addressErrors,
|
||||
submitAddress,
|
||||
// contacts
|
||||
contacts,
|
||||
contactErrors,
|
||||
canAddContact,
|
||||
addContact,
|
||||
removeContact,
|
||||
submitContacts,
|
||||
// prix
|
||||
prices,
|
||||
priceErrors,
|
||||
canAddPrice,
|
||||
addPrice,
|
||||
removePrice,
|
||||
submitPrices,
|
||||
// actions
|
||||
setCertification,
|
||||
selectDischarge,
|
||||
clearDischarge,
|
||||
validateMainFront,
|
||||
buildMainPayload,
|
||||
submitMain,
|
||||
updateMain,
|
||||
prefillFrom,
|
||||
patchCarrier,
|
||||
applyQualimatSelection,
|
||||
completeTab,
|
||||
submitRows,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { usePaginatedList } from '~/shared/composables/usePaginatedList'
|
||||
|
||||
/**
|
||||
* Vue MINIMALE du referentiel QUALIMAT embarque (groupe `qualimat:read`) dans la
|
||||
* LISTE des transporteurs. Seuls les champs consommes par le Repertoire sont
|
||||
* types : `validityDate` alimente la colonne « Date de validité » (fond rouge si
|
||||
* perimee — RG-4.04). L'id QUALIMAT est une chaine (colonne BIGINT cote back).
|
||||
*/
|
||||
export interface CarrierQualimat {
|
||||
id: string
|
||||
name: string | null
|
||||
/** Date ISO de validite de l'agrement QUALIMAT (date_immutable) — RG-4.04. */
|
||||
validityDate: string | null
|
||||
status: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Vue MINIMALE d'un transporteur pour le Repertoire (datatable). Volontairement
|
||||
* partielle : seuls les champs des colonnes + l'id (navigation) sont types ici.
|
||||
* Le detail complet (onglets Adresses / Contacts / Prix) est hors perimetre de
|
||||
* cet ecran (ERP-164, ticket #9).
|
||||
*
|
||||
* `certificationType` : QUALIMAT | GMP_PLUS | OVOCOM | COMPTE_PROPRE | AUTRE, ou
|
||||
* `null` dans le cas LIOT (compte-propre interne sans certification — RG-4.01).
|
||||
* Le libelle affiche est resolu cote front (cle i18n `transport.carriers.certification.*`).
|
||||
*/
|
||||
export interface Carrier {
|
||||
id: number
|
||||
name: string | null
|
||||
certificationType: string | null
|
||||
/** Lien editable vers le referentiel QUALIMAT (null si transporteur non QUALIMAT). */
|
||||
qualimatCarrier: CarrierQualimat | null
|
||||
/** Date ISO de derniere modification (default:read) — colonne « Dernière activité ». */
|
||||
updatedAt: string | null
|
||||
isArchived: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Filtres du Repertoire transporteurs, branches sur les query params de
|
||||
* `GET /api/carriers` (spec-back § 4.1). Pilotes par la page via `setFilters` :
|
||||
* - `search` : recherche fuzzy sur le nom ;
|
||||
* - `certificationType[]` : multi-valeurs (OR cote back) ;
|
||||
* - `archivedOnly` : n'affiche QUE les archives (toggle « Voir les archivés »,
|
||||
* aligne sur les autres repertoires M1/M2/M3).
|
||||
*/
|
||||
export interface CarrierFilters {
|
||||
search?: string
|
||||
'certificationType[]'?: string[]
|
||||
archivedOnly?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Repertoire transporteurs (M4, ERP-164) — simple enveloppe de
|
||||
* `usePaginatedList<Carrier>` sur la ressource `/carriers` (regle ABSOLUE n°13 :
|
||||
* pagination serveur obligatoire ; jamais de chargement integral en memoire).
|
||||
* Miroir de `useSuppliersRepository` (M2) / `useProvidersRepository` (M3).
|
||||
*
|
||||
* Les filtres (recherche, certifications, archives) sont pilotes par la page via
|
||||
* `setFilters` du composable partage — la remise en page 1 est garantie. Par
|
||||
* defaut AUCUN `archivedOnly` n'est envoye : le back masque alors les archives
|
||||
* (§ 2.4). Cocher « Voir les archivés » envoie `archivedOnly=true` (seules les
|
||||
* archives sont listees, aligne sur Client / Fournisseur / Prestataire).
|
||||
*
|
||||
* Volontairement PAR INSTANCE (pas de singleton module-level) : l'etat tableau
|
||||
* est propre a l'ecran Repertoire et meurt avec lui, comme tout consommateur de
|
||||
* `usePaginatedList`. Aucun reset au logout a gerer.
|
||||
*/
|
||||
export function useCarriersRepository() {
|
||||
return usePaginatedList<Carrier, CarrierFilters>({ url: '/carriers' })
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { usePaginatedList } from '~/shared/composables/usePaginatedList'
|
||||
|
||||
/**
|
||||
* Ligne du référentiel QUALIMAT renvoyée par la saisie assistée (groupe
|
||||
* `qualimat:read`). `@id` est l'IRI conservée comme FK `carrier.qualimatCarrier`
|
||||
* (RG-4.01 / § 2.5) ; `validityDate` pilote le fond rouge de la colonne « Date de
|
||||
* validité » (RG-4.04).
|
||||
*/
|
||||
export interface QualimatCarrierRow {
|
||||
'@id': string
|
||||
id: string
|
||||
name: string | null
|
||||
siret: string | null
|
||||
address: string | null
|
||||
postalCode: string | null
|
||||
city: string | null
|
||||
validityDate: string | null
|
||||
status: string | null
|
||||
}
|
||||
|
||||
/** Filtre de la recherche QUALIMAT (branché sur le nom du transporteur). */
|
||||
export interface QualimatSearchFilters {
|
||||
search?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Saisie assistée QUALIMAT (M4 Transport, ERP-166 — RG-4.01 / spec-back § 4.7).
|
||||
*
|
||||
* `GET /api/qualimat_carriers?search=` : référentiel en LECTURE SEULE, lignes
|
||||
* actives uniquement (filtré côté serveur), recherche fuzzy nom + siret. Simple
|
||||
* enveloppe de `usePaginatedList` (règle frontend : toute GetCollection passe par
|
||||
* ce composable — pagination Hydra, état 100 % local) consommée par le
|
||||
* `MalioDataTable` de l'onglet Qualimat. Le filtre `search` est piloté par le nom
|
||||
* saisi dans le formulaire principal (pas de champ de recherche dédié).
|
||||
*
|
||||
* Volontairement PAR INSTANCE (état local à l'écran d'ajout).
|
||||
*/
|
||||
export function useQualimatSearch() {
|
||||
return usePaginatedList<QualimatCarrierRow, QualimatSearchFilters>({ url: '/qualimat_carriers' })
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { mount, flushPromises } from '@vue/test-utils'
|
||||
import { defineComponent, h, ref } from 'vue'
|
||||
|
||||
// ── Auto-imports Nuxt stubbes globalement ───────────────────────────────────
|
||||
// La page ne les importe pas (auto-import) : on les expose en globals pour le
|
||||
// runtime de test (happy-dom). Meme philosophie que les specs M1/M2/M3.
|
||||
const mockPush = vi.hoisted(() => vi.fn())
|
||||
const mockApiGet = vi.hoisted(() => vi.fn())
|
||||
const mockCan = vi.hoisted(() => vi.fn())
|
||||
const mockSetFilters = vi.hoisted(() => vi.fn())
|
||||
const mockFetch = vi.hoisted(() => vi.fn())
|
||||
const mockToastError = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.stubGlobal('useI18n', () => ({ t: (key: string) => key }))
|
||||
vi.stubGlobal('useHead', () => undefined)
|
||||
vi.stubGlobal('useApi', () => ({ get: mockApiGet }))
|
||||
vi.stubGlobal('useRouter', () => ({ push: mockPush }))
|
||||
vi.stubGlobal('useToast', () => ({ error: mockToastError, success: vi.fn() }))
|
||||
vi.stubGlobal('usePermissions', () => ({ can: mockCan }))
|
||||
|
||||
// Le repository est lui aussi un auto-import : on controle items + setFilters.
|
||||
vi.stubGlobal('useCarriersRepository', () => ({
|
||||
items: ref([
|
||||
{
|
||||
id: 7,
|
||||
name: 'TRANSPORTS ACME',
|
||||
certificationType: 'QUALIMAT',
|
||||
qualimatCarrier: { id: '42', name: 'TRANSPORTS ACME', validityDate: '2027-01-15', status: 'VALIDE' },
|
||||
updatedAt: '2026-01-15T10:00:00+00:00',
|
||||
isArchived: false,
|
||||
},
|
||||
]),
|
||||
totalItems: ref(1),
|
||||
currentPage: ref(1),
|
||||
itemsPerPage: ref(10),
|
||||
itemsPerPageOptions: ref([10, 25, 50]),
|
||||
fetch: mockFetch,
|
||||
goToPage: vi.fn(),
|
||||
setItemsPerPage: vi.fn(),
|
||||
setFilters: mockSetFilters,
|
||||
}))
|
||||
|
||||
// happy-dom n'implemente pas createObjectURL : on ajoute les methodes statiques
|
||||
// sur la classe URL existante (sans la remplacer — sinon `new URL()` casse).
|
||||
globalThis.URL.createObjectURL = vi.fn(() => 'blob:fake')
|
||||
globalThis.URL.revokeObjectURL = vi.fn()
|
||||
|
||||
// Import APRES les stubs (la page resout les auto-imports au top-level du module).
|
||||
const CarriersIndex = (await import('../carriers/index.vue')).default
|
||||
|
||||
// ── Stubs de composants ──────────────────────────────────────────────────────
|
||||
const ButtonStub = defineComponent({
|
||||
props: { label: { type: String, default: '' }, disabled: { type: Boolean, default: false } },
|
||||
emits: ['click'],
|
||||
setup(props, { emit }) {
|
||||
return () => h('button', { 'data-label': props.label, onClick: () => emit('click') }, props.label)
|
||||
},
|
||||
})
|
||||
|
||||
const DataTableStub = defineComponent({
|
||||
props: { items: { type: Array, default: () => [] } },
|
||||
emits: ['row-click', 'update:page', 'update:per-page'],
|
||||
setup(props, { emit }) {
|
||||
return () => h('div', { 'data-testid': 'datatable' },
|
||||
(props.items as Array<{ id: number }>).map(it =>
|
||||
h('tr', { 'data-row-id': it.id, onClick: () => emit('row-click', it) }),
|
||||
),
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
const DrawerStub = defineComponent({
|
||||
props: { modelValue: { type: Boolean, default: false } },
|
||||
setup(_, { slots }) {
|
||||
return () => h('div', {}, [slots.header?.(), slots.default?.(), slots.footer?.()])
|
||||
},
|
||||
})
|
||||
|
||||
const SlotStub = defineComponent({ setup(_, { slots }) { return () => h('div', {}, slots.default?.()) } })
|
||||
|
||||
const PageHeaderStub = defineComponent({
|
||||
setup(_, { slots }) { return () => h('div', {}, [slots.default?.(), slots.actions?.()]) },
|
||||
})
|
||||
|
||||
const CheckboxStub = defineComponent({
|
||||
props: { id: { type: String, default: '' }, modelValue: { type: Boolean, default: false } },
|
||||
emits: ['update:model-value'],
|
||||
setup(props, { emit }) {
|
||||
return () => h('input', {
|
||||
'type': 'checkbox',
|
||||
'data-id': props.id,
|
||||
'onChange': (e: Event) => emit('update:model-value', (e.target as HTMLInputElement).checked),
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
const InputTextStub = defineComponent({ setup() { return () => h('input') } })
|
||||
|
||||
function mountPage() {
|
||||
return mount(CarriersIndex, {
|
||||
global: {
|
||||
stubs: {
|
||||
PageHeader: PageHeaderStub,
|
||||
MalioButton: ButtonStub,
|
||||
MalioDataTable: DataTableStub,
|
||||
MalioDrawer: DrawerStub,
|
||||
MalioAccordion: SlotStub,
|
||||
MalioAccordionItem: SlotStub,
|
||||
MalioInputText: InputTextStub,
|
||||
MalioCheckbox: CheckboxStub,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
describe('Répertoire transporteurs (page /carriers)', () => {
|
||||
beforeEach(() => {
|
||||
mockPush.mockReset()
|
||||
mockApiGet.mockReset().mockResolvedValue({ member: [] })
|
||||
mockCan.mockReset().mockReturnValue(true)
|
||||
mockSetFilters.mockReset()
|
||||
mockFetch.mockReset()
|
||||
mockToastError.mockReset()
|
||||
})
|
||||
|
||||
it('charge la liste au montage', async () => {
|
||||
mountPage()
|
||||
await flushPromises()
|
||||
expect(mockFetch).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('affiche « + Ajouter » uniquement avec la permission manage', async () => {
|
||||
mockCan.mockImplementation((perm: string) => perm === 'transport.carriers.manage')
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
expect(wrapper.find('[data-label="transport.carriers.add"]').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('masque « + Ajouter » sans la permission manage (view seul)', async () => {
|
||||
mockCan.mockImplementation((perm: string) => perm === 'transport.carriers.view')
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
expect(wrapper.find('[data-label="transport.carriers.add"]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('navigue vers la consultation au clic sur une ligne', async () => {
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
await wrapper.find('tr[data-row-id="7"]').trigger('click')
|
||||
expect(mockPush).toHaveBeenCalledWith('/carriers/7')
|
||||
})
|
||||
|
||||
it('appelle l\'export XLSX sur /carriers/export.xlsx en blob', async () => {
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
await wrapper.find('[data-label="transport.carriers.export"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(mockApiGet).toHaveBeenCalledWith(
|
||||
'/carriers/export.xlsx',
|
||||
expect.any(Object),
|
||||
expect.objectContaining({ responseType: 'blob', toast: false }),
|
||||
)
|
||||
})
|
||||
|
||||
it('repercute le filtre « Voir les archivés » dans setFilters sans toucher l\'URL', async () => {
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
|
||||
// Coche « Voir les archivés » puis applique les filtres.
|
||||
await wrapper.find('input[data-id="filter-archived-only"]').setValue(true)
|
||||
await wrapper.find('[data-label="transport.carriers.filters.apply"]').trigger('click')
|
||||
|
||||
expect(mockSetFilters).toHaveBeenLastCalledWith(
|
||||
{ archivedOnly: true },
|
||||
{ replace: true },
|
||||
)
|
||||
// Etat 100 % local (regle n°6) : aucune navigation/query string declenchee.
|
||||
expect(mockPush).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('repercute les certifications cochees dans setFilters (filtre multi)', async () => {
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
|
||||
// Coche deux certifications via les cases a cocher (pattern repertoire clients).
|
||||
await wrapper.find('input[data-id="filter-certification-QUALIMAT"]').setValue(true)
|
||||
await wrapper.find('input[data-id="filter-certification-AUTRE"]').setValue(true)
|
||||
await wrapper.find('[data-label="transport.carriers.filters.apply"]').trigger('click')
|
||||
|
||||
expect(mockSetFilters).toHaveBeenLastCalledWith(
|
||||
{ 'certificationType[]': ['QUALIMAT', 'AUTRE'] },
|
||||
{ replace: true },
|
||||
)
|
||||
})
|
||||
|
||||
it('badge filtres actifs + Réinitialiser vide l\'etat applique', async () => {
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
|
||||
await wrapper.find('input[data-id="filter-archived-only"]').setValue(true)
|
||||
await wrapper.find('[data-label="transport.carriers.filters.apply"]').trigger('click')
|
||||
|
||||
// Le libelle du bouton Filtrer porte le compteur (1 filtre actif).
|
||||
expect(wrapper.find('[data-label="transport.carriers.filters.title (1)"]').exists()).toBe(true)
|
||||
|
||||
// Réinitialiser → query propre (setFilters avec objet vide).
|
||||
await wrapper.find('[data-label="transport.carriers.filters.reset"]').trigger('click')
|
||||
expect(mockSetFilters).toHaveBeenLastCalledWith({}, { replace: true })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,420 @@
|
||||
<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"
|
||||
:label="t('transport.carriers.form.main.name')"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.name"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-if="isLiot"
|
||||
v-model="main.liotPlates"
|
||||
:label="t('transport.carriers.form.main.liotPlates')"
|
||||
:hint="t('transport.carriers.form.main.liotPlatesHint')"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.liotPlates"
|
||||
/>
|
||||
<template v-if="!isLiot">
|
||||
<MalioSelect
|
||||
:model-value="main.certificationType"
|
||||
:options="certificationOptions"
|
||||
:label="t('transport.carriers.form.main.certificationType')"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:readonly="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"
|
||||
:readonly="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, sanitizeDecimal } from '~/modules/transport/utils/forms/numberInput'
|
||||
|
||||
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',
|
||||
}
|
||||
const activeTab = ref('addresses')
|
||||
// Onglet Qualimat disponible en modif (ERP-172) : « actualiser » nom + certification.
|
||||
const tabs = computed(() => ['qualimat', 'addresses', 'contacts', 'prices'].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 {
|
||||
router.push(`/carriers/${carrierId}`)
|
||||
}
|
||||
|
||||
/** 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,506 @@
|
||||
<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="secondary"
|
||||
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')" readonly />
|
||||
|
||||
<!-- Cas LIOT : seul le champ immatriculations. -->
|
||||
<MalioInputText
|
||||
v-if="isLiot"
|
||||
:model-value="main.liotPlates"
|
||||
:label="t('transport.carriers.form.main.liotPlates')"
|
||||
readonly
|
||||
/>
|
||||
|
||||
<!-- 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')"
|
||||
readonly
|
||||
/>
|
||||
|
||||
<!-- 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')"
|
||||
readonly
|
||||
/>
|
||||
<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"
|
||||
readonly
|
||||
: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')" readonly />
|
||||
<!-- 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')"
|
||||
readonly
|
||||
group-class="mt-0"
|
||||
/>
|
||||
<MalioRadioButton
|
||||
:model-value="main.containerType"
|
||||
name="carrier-view-container"
|
||||
value="FOND_MOUVANT"
|
||||
:label="t('transport.carriers.containerType.FOND_MOUVANT')"
|
||||
readonly
|
||||
group-class="mt-0"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<MalioInputText :model-value="main.volumeM3" :label="t('transport.carriers.form.main.volumeM3')" readonly />
|
||||
</template>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- ── Onglets (Adresses · Contacts · Prix) — ouvre sur Adresses ──── -->
|
||||
<MalioTabList 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)"
|
||||
readonly
|
||||
/>
|
||||
</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"
|
||||
readonly
|
||||
/>
|
||||
</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) : « Type de transport » un peu plus
|
||||
large ; Transporteurs et Adresse livraisons larges ; Forfait /
|
||||
Tonne / Indexation / État réduits. -->
|
||||
<colgroup>
|
||||
<col class="w-[170px]" />
|
||||
<col class="w-[20%]" />
|
||||
<col class="w-[11%]" />
|
||||
<col class="w-[24%]" />
|
||||
<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.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.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.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="group.label">
|
||||
<tr
|
||||
v-for="(row, i) in group.rows"
|
||||
:key="`${gi}-${i}`"
|
||||
>
|
||||
<!-- Cellule de groupe fusionnée (rowspan), centrée verticalement ;
|
||||
séparateur épais en bas entre les groupes (sauf dernier). -->
|
||||
<td
|
||||
v-if="i === 0"
|
||||
:rowspan="group.rows.length"
|
||||
class="border-r border-black px-3 text-center align-middle text-[14px] font-medium"
|
||||
:class="groupBorder(gi)"
|
||||
>
|
||||
{{ group.label }}
|
||||
</td>
|
||||
<td class="px-3 py-4 text-[14px]" :class="dataBorder(group, i, gi)">{{ headerTitle }}</td>
|
||||
<td class="px-3 py-4 text-[14px]" :class="dataBorder(group, i, gi)">{{ row.apro }}</td>
|
||||
<td class="px-3 py-4 text-[14px]" :class="dataBorder(group, i, gi)">{{ row.delivery }}</td>
|
||||
<td class="px-3 py-4 text-[14px]" :class="dataBorder(group, i, gi)">{{ row.forfait }}</td>
|
||||
<td class="px-3 py-4 text-[14px]" :class="dataBorder(group, i, gi)">{{ row.tonne }}</td>
|
||||
<td class="px-3 py-4 text-[14px]" :class="dataBorder(group, i, gi)">{{ row.indexation }}</td>
|
||||
<td class="px-3 py-4 text-[14px]" :class="dataBorder(group, i, gi)">{{ 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 } 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,
|
||||
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) ──
|
||||
const activeTab = ref('addresses')
|
||||
const TAB_ICONS: Record<string, string> = {
|
||||
addresses: 'mdi:map-marker-outline',
|
||||
contacts: 'mdi:account-box-plus-outline',
|
||||
prices: 'mdi:payment',
|
||||
}
|
||||
const tabs = computed(() => ['addresses', 'contacts', 'prices'].map(key => ({
|
||||
key,
|
||||
label: t(`transport.carriers.tab.${key}`),
|
||||
icon: TAB_ICONS[key],
|
||||
})))
|
||||
|
||||
// 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 contenant Fond Mouvant / Benne) ───
|
||||
const PRICE_GROUP_ORDER = ['FOND_MOUVANT', 'BENNE'] as const
|
||||
|
||||
interface PriceRowView {
|
||||
apro: string
|
||||
delivery: string
|
||||
forfait: string
|
||||
tonne: string
|
||||
indexation: string
|
||||
state: string
|
||||
}
|
||||
|
||||
/** Groupe de prix d'un même contenant (Fond Mouvant / Benne) — cellule fusionnée. */
|
||||
interface PriceGroupView {
|
||||
label: string
|
||||
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) :
|
||||
* - « 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'
|
||||
return {
|
||||
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 contenant (Fond Mouvant puis Benne) — une cellule fusionnée
|
||||
// par groupe (rowspan) à gauche, conformément à la maquette.
|
||||
const priceGroups = computed<PriceGroupView[]>(() => {
|
||||
const list = carrier.value?.prices ?? []
|
||||
return PRICE_GROUP_ORDER
|
||||
.map(container => ({
|
||||
label: t(`transport.carriers.containerType.${container}`),
|
||||
rows: list.filter(p => p.containerType === container).map(toPriceRow),
|
||||
}))
|
||||
.filter(group => group.rows.length > 0)
|
||||
})
|
||||
|
||||
const hasPrices = computed(() => priceGroups.value.length > 0)
|
||||
|
||||
/**
|
||||
* Bordure basse d'une cellule de données :
|
||||
* - ligne interne d'un groupe → fine grise ;
|
||||
* - dernière ligne d'un groupe NON final → épaisse noire (séparateur de groupe) ;
|
||||
* - dernière ligne du DERNIER groupe → aucune (le cadre du tableau s'en charge,
|
||||
* évite la double bordure tout en bas).
|
||||
*/
|
||||
function dataBorder(group: PriceGroupView, i: number, gi: number): string {
|
||||
const isLastRow = i === group.rows.length - 1
|
||||
const isLastGroup = gi === priceGroups.value.length - 1
|
||||
if (!isLastRow) {
|
||||
return 'border-b border-m-muted/30'
|
||||
}
|
||||
return isLastGroup ? '' : 'border-b-2 border-black'
|
||||
}
|
||||
|
||||
/** Bordure basse de la cellule de groupe fusionnée (séparateur épais sauf dernier groupe). */
|
||||
function groupBorder(gi: number): string {
|
||||
return gi === priceGroups.value.length - 1 ? '' : 'border-b-2 border-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 {
|
||||
router.push(`/carriers/${carrierId}/edit`)
|
||||
}
|
||||
|
||||
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>
|
||||
@@ -0,0 +1,389 @@
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader>
|
||||
{{ t('transport.carriers.title') }}
|
||||
<template #actions>
|
||||
<!-- gap-8 = 32px d'espacement entre Filtrer et Ajouter. -->
|
||||
<div class="flex items-center gap-8">
|
||||
<!-- Bouton Filtrer a GAUCHE d'Ajouter. Le compteur reflete les filtres actifs. -->
|
||||
<MalioButton
|
||||
v-if="canView"
|
||||
variant="tertiary"
|
||||
:label="filterButtonLabel"
|
||||
icon-name="mdi:tune"
|
||||
icon-position="left"
|
||||
icon-size="24"
|
||||
@click="openFilters"
|
||||
/>
|
||||
<MalioButton
|
||||
v-if="canManage"
|
||||
variant="secondary"
|
||||
:label="t('transport.carriers.add')"
|
||||
icon-name="mdi:add-bold"
|
||||
icon-position="left"
|
||||
@click="goToCreate"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<!-- Datatable branchee sur usePaginatedList via useCarriersRepository :
|
||||
pagination serveur, tri name ASC par defaut (cote back). -->
|
||||
<MalioDataTable
|
||||
:columns="columns"
|
||||
:items="rows"
|
||||
:total-items="totalItems"
|
||||
:page="currentPage"
|
||||
:per-page="itemsPerPage"
|
||||
:per-page-options="itemsPerPageOptions"
|
||||
row-clickable
|
||||
:empty-message="t('transport.carriers.empty')"
|
||||
@row-click="onRowClick"
|
||||
@update:page="goToPage"
|
||||
@update:per-page="setItemsPerPage"
|
||||
>
|
||||
<!-- Certification : libelle i18n (le back renvoie le code enum). -->
|
||||
<template #cell-certificationType="{ item }">
|
||||
{{ formatCertification(item) }}
|
||||
</template>
|
||||
|
||||
<!-- Date de validite QUALIMAT : fond rouge si perimee (< aujourd'hui — RG-4.04). -->
|
||||
<template #cell-validityDate="{ item }">
|
||||
<span
|
||||
v-if="getValidityDate(item)"
|
||||
:class="isValidityExpired(item) ? 'inline-block rounded px-2 py-0.5 bg-m-danger text-white' : ''"
|
||||
>
|
||||
{{ formatDateFr(getValidityDate(item)) }}
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<!-- Derniere activite : date de derniere modification (updatedAt). -->
|
||||
<template #cell-lastActivity="{ item }">
|
||||
{{ formatDateFr(item.updatedAt as string | null) }}
|
||||
</template>
|
||||
</MalioDataTable>
|
||||
|
||||
<div class="flex justify-center mt-4">
|
||||
<MalioButton
|
||||
v-if="canView"
|
||||
variant="primary"
|
||||
:label="t('transport.carriers.export')"
|
||||
:disabled="exporting"
|
||||
@click="exportXlsx"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Drawer de filtres : etat BROUILLON, applique uniquement au clic sur
|
||||
« Voir les résultats ». Meme pattern que les repertoires M1/M2/M3.
|
||||
Etat 100 % local, jamais dans l'URL (regle ABSOLUE n°6). -->
|
||||
<MalioDrawer
|
||||
v-model="filterDrawerOpen"
|
||||
drawer-class="max-w-[450px]"
|
||||
body-class="p-0"
|
||||
footer-class="justify-between border-t border-black p-6"
|
||||
>
|
||||
<template #header>
|
||||
<h2 class="text-[24px] font-bold uppercase">{{ t('transport.carriers.filters.title') }}</h2>
|
||||
</template>
|
||||
|
||||
<MalioAccordion>
|
||||
<!-- Recherche : nom du transporteur (param `search`). -->
|
||||
<MalioAccordionItem :title="t('transport.carriers.filters.search')" value="search">
|
||||
<MalioInputText
|
||||
v-model="draftSearch"
|
||||
icon-name="mdi:magnify"
|
||||
/>
|
||||
</MalioAccordionItem>
|
||||
|
||||
<!-- Certification : cases a cocher (multi). Valeur = code enum.
|
||||
Meme pattern que le filtre Categories du repertoire clients. -->
|
||||
<MalioAccordionItem :title="t('transport.carriers.filters.certification')" value="certification">
|
||||
<div class="flex flex-col">
|
||||
<MalioCheckbox
|
||||
v-for="opt in certificationOptions"
|
||||
:id="`filter-certification-${opt.value}`"
|
||||
:key="opt.value"
|
||||
:label="opt.label"
|
||||
:model-value="draftCertificationTypes.includes(opt.value)"
|
||||
@update:model-value="(val: boolean) => toggleCertification(opt.value, val)"
|
||||
/>
|
||||
</div>
|
||||
</MalioAccordionItem>
|
||||
|
||||
<!-- Statut : voir uniquement les archives (sinon actifs uniquement). -->
|
||||
<MalioAccordionItem :title="t('transport.carriers.filters.status')" value="status">
|
||||
<MalioCheckbox
|
||||
id="filter-archived-only"
|
||||
:label="t('transport.carriers.filters.archivedOnly')"
|
||||
:model-value="draftArchivedOnly"
|
||||
@update:model-value="(val: boolean) => draftArchivedOnly = val"
|
||||
/>
|
||||
</MalioAccordionItem>
|
||||
</MalioAccordion>
|
||||
|
||||
<template #footer>
|
||||
<MalioButton
|
||||
variant="tertiary"
|
||||
:label="t('transport.carriers.filters.reset')"
|
||||
button-class="w-m-btn-action"
|
||||
@click="resetFilters"
|
||||
/>
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('transport.carriers.filters.apply')"
|
||||
button-class="w-[170px]"
|
||||
@click="applyFilters"
|
||||
/>
|
||||
</template>
|
||||
</MalioDrawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
|
||||
interface FilterOption {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
const { t } = useI18n()
|
||||
const api = useApi()
|
||||
const router = useRouter()
|
||||
const toast = useToast()
|
||||
const { can } = usePermissions()
|
||||
|
||||
useHead({ title: t('transport.carriers.title') })
|
||||
|
||||
// Bouton « Ajouter » reserve a `manage` (Admin + Bureau). « Exporter » et
|
||||
// « Filtrer » suivent `view` (Admin / Bureau / Commerciale). Compta et Usine
|
||||
// n'ont aucun acces (item sidebar masque cote back).
|
||||
const canManage = computed(() => can('transport.carriers.manage'))
|
||||
const canView = computed(() => can('transport.carriers.view'))
|
||||
|
||||
const {
|
||||
items: carriers,
|
||||
totalItems,
|
||||
currentPage,
|
||||
itemsPerPage,
|
||||
itemsPerPageOptions,
|
||||
fetch: loadCarriers,
|
||||
goToPage,
|
||||
setItemsPerPage,
|
||||
setFilters,
|
||||
} = useCarriersRepository()
|
||||
|
||||
// Mappe les transporteurs en objets « plats » pour MalioDataTable (items typees
|
||||
// Record<string, unknown>[]) : un objet litteral porte une signature d'index
|
||||
// implicite, contrairement a l'interface Carrier. Meme pattern que M1/M2/M3.
|
||||
const rows = computed(() => carriers.value.map(carrier => ({
|
||||
id: carrier.id,
|
||||
name: carrier.name,
|
||||
certificationType: carrier.certificationType,
|
||||
validityDate: carrier.qualimatCarrier?.validityDate ?? null,
|
||||
updatedAt: carrier.updatedAt,
|
||||
})))
|
||||
|
||||
const columns = [
|
||||
{ key: 'name', label: t('transport.carriers.column.name') },
|
||||
{ key: 'certificationType', label: t('transport.carriers.column.certification') },
|
||||
{ key: 'validityDate', label: t('transport.carriers.column.validityDate') },
|
||||
{ key: 'lastActivity', label: t('transport.carriers.column.lastActivity') },
|
||||
]
|
||||
|
||||
// Codes de certification (miroir de l'enum back) + cas LIOT (null). Le libelle
|
||||
// est resolu par i18n ; un code inconnu retombe sur le code brut.
|
||||
const CERTIFICATION_CODES = ['QUALIMAT', 'GMP_PLUS', 'OVOCOM', 'COMPTE_PROPRE', 'AUTRE'] as const
|
||||
|
||||
const certificationOptions = computed<FilterOption[]>(() =>
|
||||
CERTIFICATION_CODES.map(code => ({
|
||||
value: code,
|
||||
label: t(`transport.carriers.certification.${code}`),
|
||||
})),
|
||||
)
|
||||
|
||||
/** Libelle i18n de la certification (vide en cas LIOT — certificationType null). */
|
||||
function formatCertification(item: Record<string, unknown>): string {
|
||||
const code = item.certificationType as string | null | undefined
|
||||
if (!code) {
|
||||
return ''
|
||||
}
|
||||
return t(`transport.carriers.certification.${code}`)
|
||||
}
|
||||
|
||||
/** Date de validite QUALIMAT de la ligne (null si transporteur non QUALIMAT). */
|
||||
function getValidityDate(item: Record<string, unknown>): string | null {
|
||||
return (item.validityDate as string | null | undefined) ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-4.04 : un agrement QUALIMAT est perime si sa date de validite est anterieure
|
||||
* a la date du jour (comparaison jour a jour, sans l'heure).
|
||||
*/
|
||||
function isValidityExpired(item: Record<string, unknown>): boolean {
|
||||
const value = getValidityDate(item)
|
||||
if (!value) {
|
||||
return false
|
||||
}
|
||||
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 (spec M4). 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 → ecran Consultation (route a plat /carriers/{id}). */
|
||||
function onRowClick(item: Record<string, unknown>): void {
|
||||
router.push(`/carriers/${item.id}`)
|
||||
}
|
||||
|
||||
function goToCreate(): void {
|
||||
router.push('/carriers/new')
|
||||
}
|
||||
|
||||
// ── Filtres (drawer) ────────────────────────────────────────────────────────
|
||||
// Deux niveaux d'etat (pattern repertoires M1/M2/M3) :
|
||||
// - APPLIED : pilote la liste/l'export + le compteur du bouton. Modifie
|
||||
// uniquement au clic « Voir les résultats » / « Réinitialiser ».
|
||||
// - DRAFT : edite librement dans le drawer ; recopie vers applied a la validation.
|
||||
const filterDrawerOpen = ref(false)
|
||||
|
||||
const draftSearch = ref('')
|
||||
const draftCertificationTypes = ref<string[]>([])
|
||||
const draftArchivedOnly = ref(false)
|
||||
|
||||
const appliedSearch = ref('')
|
||||
const appliedCertificationTypes = ref<string[]>([])
|
||||
const appliedArchivedOnly = ref(false)
|
||||
|
||||
const activeFilterCount = computed(() => {
|
||||
let count = 0
|
||||
if (appliedSearch.value.trim() !== '') count++
|
||||
if (appliedCertificationTypes.value.length > 0) count++
|
||||
if (appliedArchivedOnly.value) count++
|
||||
return count
|
||||
})
|
||||
|
||||
const filterButtonLabel = computed(() => {
|
||||
const base = t('transport.carriers.filters.title')
|
||||
return activeFilterCount.value > 0 ? `${base} (${activeFilterCount.value})` : base
|
||||
})
|
||||
|
||||
// Recopie l'etat applique vers le brouillon puis ouvre le drawer : la reouverture
|
||||
// reflete les filtres actifs.
|
||||
function openFilters(): void {
|
||||
draftSearch.value = appliedSearch.value
|
||||
draftCertificationTypes.value = [...appliedCertificationTypes.value]
|
||||
draftArchivedOnly.value = appliedArchivedOnly.value
|
||||
filterDrawerOpen.value = true
|
||||
}
|
||||
|
||||
/** Coche / decoche une certification dans le brouillon (filtre multi). */
|
||||
function toggleCertification(code: string, selected: boolean): void {
|
||||
draftCertificationTypes.value = selected
|
||||
? [...draftCertificationTypes.value, code]
|
||||
: draftCertificationTypes.value.filter(c => c !== code)
|
||||
}
|
||||
|
||||
/**
|
||||
* Construit le payload de filtres serveur a partir de l'etat applique. Cle
|
||||
* `certificationType[]` pour que PHP la parse en tableau (OR cote back). Les
|
||||
* filtres vides sont omis pour une query propre.
|
||||
*/
|
||||
function buildFilterPayload(): Record<string, string | string[] | boolean> {
|
||||
const payload: Record<string, string | string[] | boolean> = {}
|
||||
if (appliedSearch.value.trim() !== '') payload.search = appliedSearch.value.trim()
|
||||
if (appliedCertificationTypes.value.length > 0) payload['certificationType[]'] = [...appliedCertificationTypes.value]
|
||||
if (appliedArchivedOnly.value) payload.archivedOnly = true
|
||||
return payload
|
||||
}
|
||||
|
||||
// « Voir les résultats » : recopie brouillon → applied, pousse les filtres
|
||||
// (retombe en page 1 via usePaginatedList) et ferme le drawer.
|
||||
function applyFilters(): void {
|
||||
appliedSearch.value = draftSearch.value.trim()
|
||||
appliedCertificationTypes.value = [...draftCertificationTypes.value]
|
||||
appliedArchivedOnly.value = draftArchivedOnly.value
|
||||
|
||||
setFilters(buildFilterPayload(), { replace: true })
|
||||
filterDrawerOpen.value = false
|
||||
}
|
||||
|
||||
// « Réinitialiser » : vide brouillon ET applied, recharge la liste complete.
|
||||
// Le drawer reste ouvert pour montrer le formulaire vide.
|
||||
function resetFilters(): void {
|
||||
draftSearch.value = ''
|
||||
draftCertificationTypes.value = []
|
||||
draftArchivedOnly.value = false
|
||||
|
||||
appliedSearch.value = ''
|
||||
appliedCertificationTypes.value = []
|
||||
appliedArchivedOnly.value = false
|
||||
|
||||
setFilters({}, { replace: true })
|
||||
}
|
||||
|
||||
// ── Export XLSX ─────────────────────────────────────────────────────────────
|
||||
// Memes filtres que la vue : l'export reflete exactement ce que l'utilisateur voit.
|
||||
const exporting = ref(false)
|
||||
|
||||
async function exportXlsx(): Promise<void> {
|
||||
if (exporting.value) {
|
||||
return
|
||||
}
|
||||
exporting.value = true
|
||||
try {
|
||||
// useApi type ses options en JSON ; l'export renvoie un binaire, donc on
|
||||
// force responseType:'blob' (transmis tel quel a ofetch au runtime). Cast
|
||||
// contenu faute d'overload blob sur le client partage (meme pattern M2/M3).
|
||||
const blob = await api.get<Blob>('/carriers/export.xlsx', buildFilterPayload(), {
|
||||
responseType: 'blob',
|
||||
toast: false,
|
||||
} as unknown as Parameters<typeof api.get>[2])
|
||||
|
||||
triggerDownload(blob, 'repertoire-transporteurs.xlsx')
|
||||
}
|
||||
catch {
|
||||
toast.error({
|
||||
title: t('transport.carriers.toast.error'),
|
||||
message: t('transport.carriers.toast.exportError'),
|
||||
})
|
||||
}
|
||||
finally {
|
||||
exporting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Declenche le telechargement d'un blob via un lien temporaire. */
|
||||
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)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadCarriers()
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,594 @@
|
||||
<template>
|
||||
<div>
|
||||
<!-- En-tete : retour vers le repertoire + 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.form.back') }"
|
||||
@click="goBack"
|
||||
/>
|
||||
<h1 class="text-[30px] font-semibold text-m-primary">{{ t('transport.carriers.form.title') }}</h1>
|
||||
</div>
|
||||
|
||||
<!-- ── Formulaire principal (pre-onglets) ─────────────────────────────
|
||||
Champs conditionnels (ERP-166) : cas LIOT (nom == LIOT) → seul
|
||||
« immatriculations » ; certification AUTRE → champ Decharge ; Affreter
|
||||
coche → indexation / contenant / volume. La certification est en lecture
|
||||
seule pour un transporteur QUALIMAT (saisie assistee, onglet Qualimat). -->
|
||||
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText
|
||||
v-model="main.name"
|
||||
:label="t('transport.carriers.form.main.name')"
|
||||
:required="true"
|
||||
:readonly="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 standard : certification + affretement + champs conditionnels. -->
|
||||
<template v-if="!isLiot">
|
||||
<MalioSelect
|
||||
:model-value="main.certificationType"
|
||||
:options="certificationOptions"
|
||||
:label="t('transport.carriers.form.main.certificationType')"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:readonly="certificationReadonly"
|
||||
:error="mainErrors.errors.certificationType"
|
||||
@update:model-value="(v: string | number | null) => main.certificationType = v === null ? null : String(v)"
|
||||
/>
|
||||
|
||||
<!-- 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.
|
||||
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 || 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>
|
||||
|
||||
<!-- « Affréter » : toujours en colonne 4 de la ligne 1 (colonne 3
|
||||
réservée à la décharge ci-dessus). Wrapper h-12 + centrage vertical
|
||||
pour aligner la case sur la ligne de champ des inputs/selects. -->
|
||||
<div class="flex h-12 items-center">
|
||||
<MalioCheckbox
|
||||
id="carrier-is-chartered"
|
||||
:label="t('transport.carriers.form.main.isChartered')"
|
||||
:model-value="main.isChartered"
|
||||
:readonly="mainLocked"
|
||||
:reserve-message-space="false"
|
||||
@update:model-value="(val: boolean) => main.isChartered = val"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- RG-4.03 : champs d'affretement (ligne 2) visibles + obligatoires si
|
||||
« Affreter ». La ligne 1 étant pleine (4 colonnes), ils démarrent
|
||||
naturellement en colonne 1 de la ligne 2. -->
|
||||
<template v-if="showCharteredFields">
|
||||
<!-- Indexation : montant en % (icône à droite), plafonné à 100. La
|
||||
:key force le ré-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"
|
||||
: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')"
|
||||
: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>
|
||||
|
||||
<!-- Volume m³ : champ texte restreint aux nombres à décimales (point). -->
|
||||
<MalioInputText
|
||||
:model-value="main.volumeM3"
|
||||
:label="t('transport.carriers.form.main.volumeM3')"
|
||||
:required="true"
|
||||
:readonly="mainLocked"
|
||||
:error="mainErrors.errors.volumeM3"
|
||||
@update:model-value="(v: string) => main.volumeM3 = sanitizeDecimal(v)"
|
||||
/>
|
||||
</template>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div v-if="!mainLocked" class="mt-12 flex justify-center">
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('transport.carriers.form.submit')"
|
||||
:disabled="mainSubmitting"
|
||||
@click="onSubmitMain"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- ── Onglets a validation incrementale ─────────────────────────────
|
||||
Barre Qualimat · Adresses · Contacts · Prix. Onglet Qualimat = saisie
|
||||
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 : saisie assistée (recherche par nom). Composant
|
||||
mutualisé avec l'écran de modification (ERP-172). -->
|
||||
<template #qualimat>
|
||||
<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
|
||||
:model-value="address"
|
||||
:country-options="countryOptions"
|
||||
:readonly="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="primary"
|
||||
:label="t('transport.carriers.form.submit')"
|
||||
:disabled="tabSubmitting || carrierId === null"
|
||||
@click="onSubmitAddresses"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Onglet Contacts (ERP-168) : un bloc par contact (RG-4.08 ≥ 1 champ,
|
||||
max 2 téléphones). Erreurs 422 par ligne. -->
|
||||
<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)"
|
||||
:readonly="isValidated('contacts')"
|
||||
:errors="contactErrors[index]"
|
||||
@update:model-value="(v) => contacts[index] = v"
|
||||
@remove="askRemoveContact(index)"
|
||||
/>
|
||||
<div v-if="!isValidated('contacts')" 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.form.submit')"
|
||||
:disabled="tabSubmitting || carrierId === null"
|
||||
@click="onSubmitContacts"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Onglet Prix (ERP-169) : blocs multiples, branche CLIENT/FOURNISSEUR
|
||||
(RG-4.09→4.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')"
|
||||
:readonly="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"
|
||||
#[key]
|
||||
>
|
||||
<div class="mt-12 flex justify-center text-m-muted">
|
||||
{{ t('transport.carriers.form.comingSoon') }}
|
||||
</div>
|
||||
</template>
|
||||
</MalioTabList>
|
||||
|
||||
<!-- 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>
|
||||
</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 type { QualimatCarrierRow } from '~/modules/transport/composables/useQualimatSearch'
|
||||
import { clampPercent, sanitizeDecimal } from '~/modules/transport/utils/forms/numberInput'
|
||||
|
||||
interface SelectOption {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
const { t } = useI18n()
|
||||
const api = useApi()
|
||||
const router = useRouter()
|
||||
const toast = useToast()
|
||||
const { can } = usePermissions()
|
||||
|
||||
useHead({ title: t('transport.carriers.form.title') })
|
||||
|
||||
// Gating de la route : la creation est reservee a `manage` (Admin / Bureau).
|
||||
// Commerciale (consultation seule), Compta et Usine sont rediriges vers le repertoire.
|
||||
if (!can('transport.carriers.manage')) {
|
||||
await navigateTo('/carriers')
|
||||
}
|
||||
|
||||
const {
|
||||
main,
|
||||
carrierId,
|
||||
mainLocked,
|
||||
mainSubmitting,
|
||||
tabSubmitting,
|
||||
mainErrors,
|
||||
dischargeUploading,
|
||||
selectDischarge,
|
||||
clearDischarge,
|
||||
isLiot,
|
||||
isQualimat,
|
||||
certificationReadonly,
|
||||
showCharteredFields,
|
||||
showDischarge,
|
||||
tabKeys,
|
||||
activeTab,
|
||||
unlockedIndex,
|
||||
isValidated,
|
||||
address,
|
||||
addressErrors,
|
||||
submitAddress,
|
||||
contacts,
|
||||
contactErrors,
|
||||
canAddContact,
|
||||
addContact,
|
||||
removeContact,
|
||||
submitContacts,
|
||||
prices,
|
||||
priceErrors,
|
||||
canAddPrice,
|
||||
addPrice,
|
||||
removePrice,
|
||||
submitPrices,
|
||||
submitMain,
|
||||
applyQualimatSelection,
|
||||
} = useCarrierForm()
|
||||
|
||||
// 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
|
||||
// la saisie assistee (onglet Qualimat). On l'ajoute cependant aux options QUAND il
|
||||
// est deja selectionne (transporteur QUALIMAT integre), uniquement pour AFFICHER
|
||||
// son libelle dans le select en lecture seule.
|
||||
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}`),
|
||||
}))
|
||||
})
|
||||
|
||||
// Icone (Iconify) affichee dans chaque onglet, par cle.
|
||||
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',
|
||||
}
|
||||
|
||||
// Onglets desactives tant que le formulaire principal n'est pas valide
|
||||
// (unlockedIndex = -1 au depart) ; deverrouillage progressif ensuite.
|
||||
const tabs = computed(() => tabKeys.value.map((key, index) => ({
|
||||
key,
|
||||
label: t(`transport.carriers.tab.${key}`),
|
||||
icon: TAB_ICONS[key],
|
||||
disabled: index > unlockedIndex.value,
|
||||
})))
|
||||
|
||||
// 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 !== '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).
|
||||
const countryOptions = ref<SelectOption[]>([{ value: 'France', label: 'France' }])
|
||||
|
||||
/** Charge le referentiel pays (/api/countries) ; conserve France par defaut si echec. */
|
||||
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 {
|
||||
// Reste sur le fallback France (non bloquant).
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadCountries().catch(() => {})
|
||||
loadPriceReferentials()
|
||||
})
|
||||
|
||||
// Avertissement unique quand l'autocompletion d'adresse bascule en degrade.
|
||||
const addressDegradedNotified = ref(false)
|
||||
|
||||
function onAddressDegraded(): void {
|
||||
if (addressDegradedNotified.value) {
|
||||
return
|
||||
}
|
||||
addressDegradedNotified.value = true
|
||||
toast.warning({
|
||||
title: t('transport.carriers.toast.error'),
|
||||
message: t('transport.carriers.form.address.degraded'),
|
||||
})
|
||||
}
|
||||
|
||||
/** Message d'erreur affichable (toast) extrait d'une erreur API — jamais undefined. */
|
||||
function apiErrorMessage(error: unknown): string {
|
||||
const data = (error as { response?: { _data?: unknown } })?.response?._data
|
||||
return extractApiErrorMessage(data) || t('transport.carriers.toast.error')
|
||||
}
|
||||
|
||||
/** Valide l'onglet Adresses (POST/PATCH par ligne ; avance gere par le composable). */
|
||||
async function onSubmitAddresses(): Promise<void> {
|
||||
const ok = await submitAddress(error => toast.error({
|
||||
title: t('transport.carriers.toast.error'),
|
||||
message: apiErrorMessage(error),
|
||||
}))
|
||||
if (ok) {
|
||||
toast.success({ title: t('transport.carriers.toast.addressSaved') })
|
||||
}
|
||||
}
|
||||
|
||||
// Modal de confirmation de suppression (générique : bloc contact OU prix).
|
||||
const deleteConfirm = reactive({ open: false, action: null as null | (() => void) })
|
||||
|
||||
/** 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({
|
||||
title: t('transport.carriers.toast.error'),
|
||||
message: apiErrorMessage(error),
|
||||
}))
|
||||
if (ok) {
|
||||
toast.success({ title: t('transport.carriers.toast.contactSaved') })
|
||||
}
|
||||
}
|
||||
|
||||
function askRemoveContact(index: number): void {
|
||||
deleteConfirm.action = () => { void removeContact(index) }
|
||||
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
|
||||
}
|
||||
|
||||
/** 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')
|
||||
}
|
||||
|
||||
/**
|
||||
* Valide le formulaire principal (POST /carriers ; bascule geree par le composable).
|
||||
* RG-4.07 : pour un transporteur QUALIMAT, l'adresse copiee est persistee
|
||||
* automatiquement (pas de bouton Valider dans l'onglet Adresses).
|
||||
*/
|
||||
async function onSubmitMain(): Promise<void> {
|
||||
const ok = await submitMain()
|
||||
if (ok && isQualimat.value) {
|
||||
await submitAddress(error => toast.error({
|
||||
title: t('transport.carriers.toast.error'),
|
||||
message: apiErrorMessage(error),
|
||||
}))
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* Types du workflow « Ajouter un transporteur » (M4 Transport, ERP-165 / ERP-166).
|
||||
*
|
||||
* Périmètre :
|
||||
* - ERP-165 : formulaire PRINCIPAL minimal (Nom + Certification + Affréter).
|
||||
* - ERP-166 : champs CONDITIONNELS du formulaire principal (indexation / benne /
|
||||
* volume si affrété — RG-4.03 ; décharge si AUTRE — RG-4.02 ; immatriculations
|
||||
* LIOT — RG-4.01) + saisie assistée QUALIMAT (copie name / certification /
|
||||
* adresse + FK qualimatCarrier — RG-4.01 / § 2.5).
|
||||
*
|
||||
* L'upload réel de la décharge (file → IRI via useUpload) arrive à ERP-171 ; ici
|
||||
* on porte seulement l'IRI résolu (`dischargeDocumentIri`).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Brouillon du formulaire principal. Les décimales (indexation / volume) sont
|
||||
* portées en `string` car `MalioInputNumber` émet une chaîne ; le serveur parse.
|
||||
* `certificationType` est un code enum back (GMP_PLUS | OVOCOM | COMPTE_PROPRE |
|
||||
* AUTRE | QUALIMAT — ce dernier posé par la saisie assistée) ou `null`.
|
||||
* `containerType` vaut `BENNE` | `FOND_MOUVANT` (radio) ou `null`.
|
||||
*/
|
||||
export interface CarrierMainDraft {
|
||||
name: string
|
||||
certificationType: string | null
|
||||
isChartered: boolean
|
||||
indexationRate: string
|
||||
containerType: string | null
|
||||
volumeM3: string
|
||||
liotPlates: string
|
||||
/** IRI du document de décharge (résolu par useUpload — ERP-171). */
|
||||
dischargeDocumentIri: string | null
|
||||
/** IRI de la ligne QUALIMAT liée (saisie assistée — null si non QUALIMAT). */
|
||||
qualimatCarrierIri: string | null
|
||||
}
|
||||
|
||||
/** Brouillon principal vide (état initial du formulaire de création). */
|
||||
export function emptyCarrierMain(): CarrierMainDraft {
|
||||
return {
|
||||
name: '',
|
||||
certificationType: null,
|
||||
isChartered: false,
|
||||
indexationRate: '',
|
||||
// Défaut métier : Benne pré-sélectionné (radio du formulaire principal).
|
||||
containerType: 'BENNE',
|
||||
volumeM3: '',
|
||||
liotPlates: '',
|
||||
dischargeDocumentIri: null,
|
||||
qualimatCarrierIri: null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adresse copiée depuis le référentiel QUALIMAT à la sélection (RG-4.01 / § 2.5).
|
||||
* Stockée dans l'état du formulaire pour alimenter l'onglet Adresses (ticket
|
||||
* ultérieur) ; pré-remplie « France » côté pays par défaut.
|
||||
*/
|
||||
export interface CarrierAddressCopy {
|
||||
country: string
|
||||
postalCode: string
|
||||
city: string
|
||||
street: string
|
||||
}
|
||||
|
||||
/** Adresse copiée vide. */
|
||||
export function emptyCarrierAddressCopy(): CarrierAddressCopy {
|
||||
return { country: 'France', postalCode: '', city: '', street: '' }
|
||||
}
|
||||
|
||||
/**
|
||||
* Brouillon d'un bloc Adresse (onglet Adresses, ERP-167) — sous-ressource
|
||||
* `CarrierAddress` (groupe `carrier:write:addresses`). Version SIMPLIFIÉE de
|
||||
* l'adresse fournisseur (M2) / prestataire (M3) : pas de sites / catégories /
|
||||
* contacts ni type d'adresse (les sites du M4 vivent dans l'onglet Prix).
|
||||
*/
|
||||
export interface CarrierAddressFormDraft {
|
||||
/** Id serveur une fois l'adresse créée (null tant que non persistée). */
|
||||
id: number | null
|
||||
/** Pays (chaîne libre, défaut « France »). */
|
||||
country: string
|
||||
postalCode: string | null
|
||||
city: string | null
|
||||
street: string | null
|
||||
streetComplement: string | null
|
||||
}
|
||||
|
||||
/** Brouillon d'adresse vide (pays France par défaut, RG-4.05). */
|
||||
export function emptyCarrierAddress(): CarrierAddressFormDraft {
|
||||
return {
|
||||
id: null,
|
||||
country: 'France',
|
||||
postalCode: null,
|
||||
city: null,
|
||||
street: null,
|
||||
streetComplement: null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Brouillon d'un bloc Contact (onglet Contacts, ERP-168) — sous-ressource
|
||||
* `CarrierContact` (groupe `carrier:write:contacts`). Les téléphones sont saisis
|
||||
* en `phonePrimary` / `phoneSecondary` côté UI, puis envoyés au back sous forme du
|
||||
* tableau `phones` (max 2 — RG-4.08). `hasSecondaryPhone` pilote l'affichage du 2e
|
||||
* numéro (révélé via le bouton « + »). Pas d'`iri` : aucune relation M2M depuis
|
||||
* l'adresse au M4 (≠ M3).
|
||||
*/
|
||||
export interface CarrierContactFormDraft {
|
||||
/** Id serveur une fois le contact créé (null tant que non persisté). */
|
||||
id: number | null
|
||||
firstName: string | null
|
||||
lastName: string | null
|
||||
jobTitle: string | null
|
||||
phonePrimary: string | null
|
||||
phoneSecondary: string | null
|
||||
email: string | null
|
||||
/** UI : le 2e numéro a été révélé via le bouton « + » (max 2 téléphones). */
|
||||
hasSecondaryPhone: boolean
|
||||
}
|
||||
|
||||
/** Brouillon de contact vide (état initial d'un bloc Contact). */
|
||||
export function emptyCarrierContact(): CarrierContactFormDraft {
|
||||
return {
|
||||
id: null,
|
||||
firstName: null,
|
||||
lastName: null,
|
||||
jobTitle: null,
|
||||
phonePrimary: null,
|
||||
phoneSecondary: null,
|
||||
email: null,
|
||||
hasSecondaryPhone: false,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Brouillon d'un bloc Prix (onglet Prix, ERP-169 — RG-4.09→4.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.
|
||||
*/
|
||||
export interface CarrierMainResponse {
|
||||
id: number
|
||||
name: string | null
|
||||
certificationType: string | null
|
||||
'@id'?: string
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
canEditCarrier,
|
||||
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 : 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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { clampPercent, 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('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Helpers purs de l'onglet Adresse transporteur (M4 Transport, ERP-167) — miroir
|
||||
* SIMPLIFIÉ de `providerAddress` (M3) / `SupplierAddressBlock` (M2), sans sites /
|
||||
* catégories / contacts (les sites du M4 vivent dans l'onglet Prix). Testables
|
||||
* sans Vue.
|
||||
*/
|
||||
|
||||
import type { CarrierAddressFormDraft } from '~/modules/transport/types/carrierForm'
|
||||
|
||||
/**
|
||||
* 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).
|
||||
*/
|
||||
export function buildCarrierAddressPayload(address: CarrierAddressFormDraft): Record<string, unknown> {
|
||||
return {
|
||||
country: address.country,
|
||||
postalCode: address.postalCode || null,
|
||||
city: address.city || null,
|
||||
street: address.street || null,
|
||||
streetComplement: address.streetComplement || null,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import type { CarrierContactFormDraft } 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() !== ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Un bloc Contact est VIDE tant qu'aucun champ comptant pour la validité n'est
|
||||
* rempli — prénom / nom / fonction / téléphone principal / email. `phoneSecondary`
|
||||
* est EXCLU (aligné M1/M2/M3 : un bloc ne portant qu'un 2e numéro reste vide). Sert
|
||||
* le filtrage des amorces vides à la soumission.
|
||||
*/
|
||||
export function isCarrierContactBlank(contact: CarrierContactFormDraft): boolean {
|
||||
return ![
|
||||
contact.firstName,
|
||||
contact.lastName,
|
||||
contact.jobTitle,
|
||||
contact.phonePrimary,
|
||||
contact.email,
|
||||
].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
|
||||
* regroupés dans le tableau `phones` (numéros non vides, max 2 — RG-4.08) ; le 2e
|
||||
* numéro n'est inclus que s'il a été révélé (`hasSecondaryPhone`).
|
||||
*/
|
||||
export function buildCarrierContactPayload(contact: CarrierContactFormDraft): Record<string, unknown> {
|
||||
const phones = [
|
||||
contact.phonePrimary,
|
||||
contact.hasSecondaryPhone ? contact.phoneSecondary : null,
|
||||
].filter((phone): phone is string => isFilled(phone))
|
||||
|
||||
return {
|
||||
firstName: contact.firstName || null,
|
||||
lastName: contact.lastName || null,
|
||||
jobTitle: contact.jobTitle || null,
|
||||
email: contact.email || null,
|
||||
phones,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* 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 : `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 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,
|
||||
}
|
||||
}
|
||||
|
||||
/** 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.09→4.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.09→4.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,28 @@
|
||||
/**
|
||||
* Helpers de saisie numérique du formulaire principal transporteur (ERP-170).
|
||||
* Champs texte restreints (volume m³ décimal, indexation plafonnée). Purs / testables.
|
||||
*/
|
||||
|
||||
/**
|
||||
* 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
|
||||
}
|
||||
Generated
+10
-10
@@ -7,7 +7,7 @@
|
||||
"name": "starseed-frontend",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@malio/layer-ui": "^1.7.10",
|
||||
"@malio/layer-ui": "^1.7.12",
|
||||
"@nuxt/icon": "^2.2.1",
|
||||
"@nuxtjs/i18n": "^10.2.3",
|
||||
"@nuxtjs/tailwindcss": "^6.14.0",
|
||||
@@ -583,9 +583,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@emnapi/core": {
|
||||
"version": "1.11.0",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.0.tgz",
|
||||
"integrity": "sha512-l9Oo58x0HOP5znGzVhYW9U3e5wVuA4LAZU2AGezTmkhO1CgQRFDhDg4nneHsu/t3WniXg9QrG2nIXL/ZS8ln8Q==",
|
||||
"version": "1.11.1",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",
|
||||
"integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
@@ -594,9 +594,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/runtime": {
|
||||
"version": "1.11.0",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.0.tgz",
|
||||
"integrity": "sha512-55coeOFKHv1ywEcUXJtWU5f+Jr/W5tZDvZig8DLKSwUN1JpROQ4rk/SNOQiFWmaR/VKF4zuFyW1B8JduOSv6Pg==",
|
||||
"version": "1.11.1",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz",
|
||||
"integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
@@ -1866,9 +1866,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@malio/layer-ui": {
|
||||
"version": "1.7.10",
|
||||
"resolved": "https://gitea.malio.fr/api/packages/MALIO-DEV/npm/%40malio%2Flayer-ui/-/1.7.10/layer-ui-1.7.10.tgz",
|
||||
"integrity": "sha512-ZWYaKvl+VpGAqeTE+4xdyKOmuRd4zwjlUYVppeIBZwGeNAK16kZnrztR+4eQmnzUqPZVybBhEBdKP9weqWHSUg==",
|
||||
"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==",
|
||||
"dependencies": {
|
||||
"@nuxt/icon": "^2.2.1",
|
||||
"@nuxtjs/tailwindcss": "^6.14.0",
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
"test:e2e:ui": "playwright test --ui"
|
||||
},
|
||||
"dependencies": {
|
||||
"@malio/layer-ui": "^1.7.10",
|
||||
"@malio/layer-ui": "^1.7.12",
|
||||
"@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` ré-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)
|
||||
})
|
||||
})
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -95,10 +95,11 @@ export const personas: Record<PersonaKey, Persona> = {
|
||||
'technique.providers.accounting.view',
|
||||
'technique.providers.accounting.manage',
|
||||
'technique.providers.archive',
|
||||
// Transport — Repertoire transporteurs (M4, ERP-153). Meme logique :
|
||||
// Transport — Repertoire transporteurs (M4, ERP-164). Meme logique :
|
||||
// mappe sur le persona "tout", pas de nouveau persona (regle ABSOLUE
|
||||
// n°7). transport.carriers.view n'ajoute pas de lien dans la section
|
||||
// Administration, donc expectedAdminLinks reste inchange.
|
||||
// n°7). L'item transporteurs vit desormais dans la section Administration
|
||||
// (1er item, ERP-164) mais sur la route `/carriers` (hors `/admin/<slug>`),
|
||||
// donc il n'entre pas dans ALL_ADMIN_LINKS : expectedAdminLinks reste inchange.
|
||||
'transport.carriers.view',
|
||||
'transport.carriers.manage',
|
||||
'transport.carriers.archive',
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* RG-4.08 (correctif) — aligne la regle de validite d'un contact transporteur sur
|
||||
* le M1/M2/M3 : au moins le PRENOM OU le NOM (et non plus « un champ quelconque
|
||||
* parmi prenom/nom/fonction/telephone/email »). Remplace le CHECK
|
||||
* chk_carrier_contact_filled par chk_carrier_contact_name et met a jour les
|
||||
* commentaires de colonnes. La garde applicative (CarrierContactProcessor::validateName)
|
||||
* est alignee 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) ;
|
||||
* 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 Version20260617120000 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'RG-4.08 : contact transporteur valide si prenom OU nom (alignement M1/M2/M3) — CHECK chk_carrier_contact_name.';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE carrier_contact DROP CONSTRAINT chk_carrier_contact_filled');
|
||||
$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).$_$');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE carrier_contact DROP CONSTRAINT chk_carrier_contact_name');
|
||||
$this->addSql('ALTER TABLE carrier_contact ADD CONSTRAINT chk_carrier_contact_filled CHECK (first_name IS NOT NULL OR last_name IS NOT NULL OR job_title IS NOT NULL OR phone_primary IS NOT NULL OR email IS NOT NULL)');
|
||||
|
||||
$this->addSql('COMMENT ON TABLE carrier_contact IS $_$Contacts d un transporteur (1:n) — onglet Contact (M4). Au moins un champ rempli (RG-4.08, chk_carrier_contact_filled), max 2 telephones.$_$');
|
||||
$this->addSql('COMMENT ON COLUMN carrier_contact.first_name IS $_$Prenom du contact (capitalise serveur). Au moins un champ du contact est requis (RG-4.08).$_$');
|
||||
$this->addSql('COMMENT ON COLUMN carrier_contact.last_name IS $_$Nom du contact (capitalise serveur). Au moins un champ du contact est requis (RG-4.08).$_$');
|
||||
}
|
||||
}
|
||||
@@ -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)');
|
||||
}
|
||||
}
|
||||
@@ -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).'");
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,9 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
'supplier:read',
|
||||
'supplier_address:read',
|
||||
'site:read',
|
||||
// Embarque le nom de fichier de la decharge (RG-4.02) au lieu d'un
|
||||
// IRI nu, pour l'affichage en consultation / modification (ERP-171).
|
||||
'uploaded_document:reference',
|
||||
'default:read',
|
||||
]],
|
||||
provider: CarrierProvider::class,
|
||||
@@ -195,10 +198,13 @@ class Carrier implements TimestampableInterface, BlamableInterface
|
||||
#[Groups(['carrier:read', 'carrier:write:main'])]
|
||||
private ?string $liotPlates = null;
|
||||
|
||||
// === Adresse UNIQUE (OneToOne) — EMBARQUEE dans le DETAIL (read-group sur le getter) ===
|
||||
// Metier : un transporteur a au plus UNE adresse (decision metier ERP-172). La
|
||||
// FK porte un index UNIQUE (cote CarrierAddress.carrier en OneToOne owning side).
|
||||
#[ORM\OneToOne(mappedBy: 'carrier', targetEntity: CarrierAddress::class, cascade: ['persist', 'remove'], orphanRemoval: true)]
|
||||
private ?CarrierAddress $address = null;
|
||||
|
||||
// === Sous-collections — EMBARQUEES dans le DETAIL (read-group sur le getter) ===
|
||||
/** @var Collection<int, CarrierAddress> */
|
||||
#[ORM\OneToMany(mappedBy: 'carrier', targetEntity: CarrierAddress::class, cascade: ['persist', 'remove'], orphanRemoval: true)]
|
||||
private Collection $addresses;
|
||||
|
||||
/** @var Collection<int, CarrierContact> */
|
||||
#[ORM\OneToMany(mappedBy: 'carrier', targetEntity: CarrierContact::class, cascade: ['persist', 'remove'], orphanRemoval: true)]
|
||||
@@ -225,9 +231,8 @@ class Carrier implements TimestampableInterface, BlamableInterface
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->addresses = new ArrayCollection();
|
||||
$this->contacts = new ArrayCollection();
|
||||
$this->prices = new ArrayCollection();
|
||||
$this->contacts = new ArrayCollection();
|
||||
$this->prices = new ArrayCollection();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -406,32 +411,22 @@ class Carrier implements TimestampableInterface, BlamableInterface
|
||||
return $this;
|
||||
}
|
||||
|
||||
/** @return Collection<int, CarrierAddress> */
|
||||
#[Groups(['carrier:item:read'])]
|
||||
public function getAddresses(): Collection
|
||||
public function getAddress(): ?CarrierAddress
|
||||
{
|
||||
return $this->addresses;
|
||||
return $this->address;
|
||||
}
|
||||
|
||||
public function addAddress(CarrierAddress $address): static
|
||||
public function setAddress(?CarrierAddress $address): static
|
||||
{
|
||||
if (!$this->addresses->contains($address)) {
|
||||
$this->addresses->add($address);
|
||||
$this->address = $address;
|
||||
if (null !== $address && $address->getCarrier() !== $this) {
|
||||
$address->setCarrier($this);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function removeAddress(CarrierAddress $address): static
|
||||
{
|
||||
if ($this->addresses->removeElement($address) && $address->getCarrier() === $this) {
|
||||
$address->setCarrier(null);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/** @return Collection<int, CarrierContact> */
|
||||
#[Groups(['carrier:item:read'])]
|
||||
public function getContacts(): Collection
|
||||
|
||||
@@ -20,9 +20,10 @@ use Symfony\Component\Serializer\Attribute\Groups;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
|
||||
/**
|
||||
* Adresse d'un transporteur (1:n) — onglet Adresse (M4). Jumelle de
|
||||
* SupplierAddress (M2), version simplifiee (pas de type d'adresse, pas de M2M
|
||||
* sites/categories sur l'adresse : les sites du M4 vivent dans l'onglet Prix).
|
||||
* Adresse d'un transporteur (1:1, OneToOne — decision metier ERP-172) — onglet
|
||||
* Adresse (M4). Jumelle de SupplierAddress (M2), version simplifiee (pas de type
|
||||
* d'adresse, pas de M2M sites/categories sur l'adresse : les sites du M4 vivent
|
||||
* dans l'onglet Prix), et UNIQUE par transporteur (la jumelle M2 est 1:n).
|
||||
*
|
||||
* Lecture : proprietes en `carrier:item:read` (embarquees au detail du
|
||||
* transporteur). Ecriture : groupe `carrier:write:addresses`.
|
||||
@@ -30,9 +31,10 @@ use Symfony\Component\Validator\Constraints as Assert;
|
||||
* Sous-ressource API (ERP-159, spec § 4.5) — jumelle de SupplierAddress (M2) /
|
||||
* ProviderAddress (M3), sans address_type ni M2M (les sites du M4 vivent dans
|
||||
* l'onglet Prix) :
|
||||
* - POST /api/carriers/{carrierId}/addresses : creation rattachee au
|
||||
* - POST /api/carriers/{carrierId}/address : creation rattachee au
|
||||
* transporteur parent (Link toProperty 'carrier'), security
|
||||
* transport.carriers.manage.
|
||||
* transport.carriers.manage. 409 si le transporteur a deja une adresse
|
||||
* (CarrierAddressProcessor::guardSingleAddress, avant la contrainte d'unicite).
|
||||
* - PATCH / DELETE /api/carrier_addresses/{id} : security
|
||||
* transport.carriers.manage.
|
||||
* - GET /api/carrier_addresses/{id} : lecture unitaire (security view) — la
|
||||
@@ -58,14 +60,13 @@ use Symfony\Component\Validator\Constraints as Assert;
|
||||
normalizationContext: ['groups' => ['carrier:item:read', 'default:read']],
|
||||
),
|
||||
new Post(
|
||||
uriTemplate: '/carriers/{carrierId}/addresses',
|
||||
uriTemplate: '/carriers/{carrierId}/address',
|
||||
uriVariables: [
|
||||
'carrierId' => new Link(fromClass: Carrier::class, toProperty: 'carrier'),
|
||||
],
|
||||
// read:false : pas de stade lecture du parent. Le Link toProperty
|
||||
// resoudrait l'enfant (SELECT CarrierAddress ... WHERE carrier = :id)
|
||||
// et casse en NonUniqueResult des >= 2 enfants. Le parent est rattache
|
||||
// manuellement par CarrierAddressProcessor::linkParent (404 si absent).
|
||||
// read:false : pas de stade lecture du parent. Le parent est rattache
|
||||
// manuellement par CarrierAddressProcessor::linkParent (404 si absent),
|
||||
// qui refuse aussi une 2e adresse (RG metier : adresse UNIQUE — 409).
|
||||
read: false,
|
||||
security: "is_granted('transport.carriers.manage')",
|
||||
normalizationContext: ['groups' => ['carrier:item:read', 'default:read']],
|
||||
@@ -86,7 +87,9 @@ use Symfony\Component\Validator\Constraints as Assert;
|
||||
)]
|
||||
#[ORM\Entity]
|
||||
#[ORM\Table(name: 'carrier_address')]
|
||||
#[ORM\Index(name: 'idx_carrier_address_carrier', columns: ['carrier_id'])]
|
||||
// Adresse UNIQUE par transporteur (OneToOne owning side) : contrainte d'unicite
|
||||
// sur carrier_id (decision metier ERP-172).
|
||||
#[ORM\UniqueConstraint(name: 'uniq_carrier_address_carrier', columns: ['carrier_id'])]
|
||||
#[ORM\Index(name: 'idx_carrier_address_created_by', columns: ['created_by'])]
|
||||
#[ORM\Index(name: 'idx_carrier_address_updated_by', columns: ['updated_by'])]
|
||||
#[Auditable]
|
||||
@@ -100,7 +103,7 @@ class CarrierAddress implements TimestampableInterface, BlamableInterface
|
||||
#[Groups(['carrier:item:read'])]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: Carrier::class, inversedBy: 'addresses')]
|
||||
#[ORM\OneToOne(targetEntity: Carrier::class, inversedBy: 'address')]
|
||||
#[ORM\JoinColumn(name: 'carrier_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
|
||||
private ?Carrier $carrier = null;
|
||||
|
||||
@@ -133,9 +136,6 @@ class CarrierAddress implements TimestampableInterface, BlamableInterface
|
||||
#[Groups(['carrier:item:read', 'carrier:write:addresses'])]
|
||||
private ?string $streetComplement = null;
|
||||
|
||||
#[ORM\Column(options: ['default' => 0])]
|
||||
private int $position = 0;
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
@@ -212,16 +212,4 @@ class CarrierAddress implements TimestampableInterface, BlamableInterface
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPosition(): int
|
||||
{
|
||||
return $this->position;
|
||||
}
|
||||
|
||||
public function setPosition(int $position): static
|
||||
{
|
||||
$this->position = $position;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,8 +21,8 @@ use Symfony\Component\Validator\Constraints as Assert;
|
||||
|
||||
/**
|
||||
* Contact d'un transporteur (1:n) — onglet Contact (M4). Jumeau de
|
||||
* SupplierContact (M2) : au moins un champ rempli (RG-4.08, garanti par le
|
||||
* CHECK chk_carrier_contact_filled + le Processor), max 2 telephones.
|
||||
* SupplierContact (M2) : au moins le prenom OU le nom (RG-4.08, garanti par le
|
||||
* CHECK chk_carrier_contact_name + le Processor), max 2 telephones.
|
||||
*
|
||||
* Lecture : proprietes en `carrier:item:read` (embarquees au detail du
|
||||
* transporteur). Ecriture : groupe `carrier:write:contacts`.
|
||||
|
||||
+27
-1
@@ -6,12 +6,14 @@ namespace App\Module\Transport\Infrastructure\ApiPlatform\State\Processor;
|
||||
|
||||
use ApiPlatform\Metadata\DeleteOperationInterface;
|
||||
use ApiPlatform\Metadata\Operation;
|
||||
use ApiPlatform\Metadata\Post;
|
||||
use ApiPlatform\State\ProcessorInterface;
|
||||
use ApiPlatform\Validator\Exception\ValidationException;
|
||||
use App\Module\Transport\Domain\Entity\Carrier;
|
||||
use App\Module\Transport\Domain\Entity\CarrierAddress;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Symfony\Component\Validator\ConstraintViolation;
|
||||
use Symfony\Component\Validator\ConstraintViolationList;
|
||||
@@ -63,6 +65,7 @@ final class CarrierAddressProcessor implements ProcessorInterface
|
||||
}
|
||||
|
||||
$this->linkParent($data, $uriVariables);
|
||||
$this->guardSingleAddress($data, $operation);
|
||||
$this->guardCharteredAddress($data);
|
||||
|
||||
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
|
||||
@@ -70,7 +73,7 @@ final class CarrierAddressProcessor implements ProcessorInterface
|
||||
|
||||
/**
|
||||
* Rattache l'adresse au transporteur parent de la sous-ressource POST
|
||||
* (/carriers/{carrierId}/addresses) : la relation n'est pas peuplee
|
||||
* (/carriers/{carrierId}/address) : la relation n'est pas peuplee
|
||||
* automatiquement par le Link sur une ecriture. Sur PATCH, no-op.
|
||||
*/
|
||||
private function linkParent(CarrierAddress $address, array $uriVariables): void
|
||||
@@ -98,6 +101,29 @@ final class CarrierAddressProcessor implements ProcessorInterface
|
||||
$address->setCarrier($carrier);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adresse UNIQUE par transporteur (decision metier ERP-172) : un POST sur un
|
||||
* transporteur qui a deja une adresse -> 409 explicite (plutot qu'un 500 sur la
|
||||
* contrainte d'unicite carrier_id). No-op sur PATCH (mise a jour de l'adresse
|
||||
* existante). Lookup repository pour rester robuste a la synchro bidirectionnelle.
|
||||
*/
|
||||
private function guardSingleAddress(CarrierAddress $address, Operation $operation): void
|
||||
{
|
||||
if (!$operation instanceof Post) {
|
||||
return;
|
||||
}
|
||||
|
||||
$carrier = $address->getCarrier();
|
||||
if (!$carrier instanceof Carrier) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existing = $this->em->getRepository(CarrierAddress::class)->findOneBy(['carrier' => $carrier]);
|
||||
if (null !== $existing && $existing->getId() !== $address->getId()) {
|
||||
throw new ConflictHttpException('Ce transporteur a déjà une adresse.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-4.05 : si le transporteur parent est affrete (isChartered), l'adresse doit
|
||||
* porter Pays / Code postal / Ville / Adresse. Chaque champ manquant -> une
|
||||
|
||||
+19
-26
@@ -23,21 +23,21 @@ use function is_string;
|
||||
/**
|
||||
* Processor d'ecriture de la sous-ressource Contact d'un transporteur (M4,
|
||||
* spec-back § 4.5). Jumeau du SupplierContactProcessor (M2), recentre sur le
|
||||
* perimetre ERP-160, AVEC deux specificites M4 : RG-4.08 (≥ 1 champ rempli, max
|
||||
* 2 telephones) portee a la fois par le CHECK BDD chk_carrier_contact_filled et
|
||||
* par ce Processor.
|
||||
* perimetre ERP-160. RG-4.08 (correctif, alignement M1/M2/M3) : un contact exige
|
||||
* au moins le PRENOM OU le NOM (la fonction / le telephone / l'email seuls ne
|
||||
* suffisent pas), porte a la fois par le CHECK BDD chk_carrier_contact_name et par
|
||||
* ce Processor ; le « max 2 telephones » reste une specificite M4.
|
||||
*
|
||||
* Sequence :
|
||||
* - POST / PATCH : rattachement au transporteur parent (linkParent),
|
||||
* normalisation serveur RG-4.13 (prenom/nom Title Case, email lowercase),
|
||||
* mapping du tableau d'ecriture `phones` -> phonePrimary/phoneSecondary
|
||||
* (max 2, chiffres uniquement), puis garde RG-4.08 (≥ 1 champ) avant
|
||||
* persistance.
|
||||
* (max 2, chiffres uniquement), puis garde « prenom OU nom » avant persistance.
|
||||
* - DELETE : aucune regle metier specifique (suppression physique directe).
|
||||
*
|
||||
* RG-4.08 vit ICI (double du CHECK BDD) pour transformer une violation SQL (500
|
||||
* generique) en 422 propre rattachee au champ `firstName` (mapping inline
|
||||
* ERP-101). Le « max 2 telephones » est rattache au champ `phones` : seul
|
||||
* La garde « prenom OU nom » vit ICI (double du CHECK BDD) pour transformer une
|
||||
* violation SQL (500 generique) en 422 propre rattachee au champ `firstName`
|
||||
* (mapping inline ERP-101). Le « max 2 telephones » est rattache au champ `phones` : seul
|
||||
* point de saisie des numeros (les colonnes phonePrimary/phoneSecondary sont en
|
||||
* lecture seule).
|
||||
*
|
||||
@@ -77,7 +77,7 @@ final class CarrierContactProcessor implements ProcessorInterface
|
||||
$this->linkParent($data, $uriVariables);
|
||||
$this->normalize($data);
|
||||
$this->applyPhones($data);
|
||||
$this->validateAtLeastOneField($data);
|
||||
$this->validateName($data);
|
||||
|
||||
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
|
||||
}
|
||||
@@ -187,25 +187,18 @@ final class CarrierContactProcessor implements ProcessorInterface
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-4.08 : un bloc Contact est valide des qu'au moins 1 champ est rempli
|
||||
* (firstName, lastName, jobTitle, phonePrimary ou email — meme perimetre que
|
||||
* le CHECK BDD chk_carrier_contact_filled, qui exclut phoneSecondary). Double
|
||||
* garde : leve une 422 propre rattachee a `firstName` plutot qu'une 500 SQL.
|
||||
* Joue apres normalisation + mapping telephones, donc les chaines vides sont
|
||||
* deja ramenees a null.
|
||||
* RG-4.08 (alignement M1/M2/M3) : un bloc Contact exige au moins le PRENOM OU le
|
||||
* NOM — un contact se materialise par son nom ; fonction / telephone / email
|
||||
* seuls ne suffisent pas. Double garde avec le CHECK BDD chk_carrier_contact_name
|
||||
* — leve une 422 propre rattachee a `firstName` plutot qu'une 500 SQL. Joue apres
|
||||
* normalisation + mapping telephones, donc les chaines vides sont deja null.
|
||||
*/
|
||||
private function validateAtLeastOneField(CarrierContact $contact): void
|
||||
private function validateName(CarrierContact $contact): void
|
||||
{
|
||||
if (
|
||||
null === $contact->getFirstName()
|
||||
&& null === $contact->getLastName()
|
||||
&& null === $contact->getJobTitle()
|
||||
&& null === $contact->getPhonePrimary()
|
||||
&& null === $contact->getEmail()
|
||||
) {
|
||||
if (null === $contact->getFirstName() && null === $contact->getLastName()) {
|
||||
$violations = new ConstraintViolationList();
|
||||
$violations->add(new ConstraintViolation(
|
||||
'Renseignez au moins un champ pour le contact.',
|
||||
'Le prénom ou le nom du contact est obligatoire.',
|
||||
null,
|
||||
[],
|
||||
$contact,
|
||||
@@ -219,8 +212,8 @@ final class CarrierContactProcessor implements ProcessorInterface
|
||||
|
||||
/**
|
||||
* Trim + chaine vide -> null (la fonction n'est pas normalisee en casse,
|
||||
* contrairement aux noms de personne). Garantit que RG-4.08 detecte un champ
|
||||
* « non rempli » meme si le client envoie une chaine vide.
|
||||
* contrairement aux noms de personne). Evite de persister une chaine vide
|
||||
* (« » devient null) cote fonction du contact.
|
||||
*/
|
||||
private function blankToNull(?string $value): ?string
|
||||
{
|
||||
|
||||
@@ -189,12 +189,13 @@ class CarrierFixtures extends Fixture implements DependentFixtureInterface
|
||||
$address->setPostalCode($postalCode);
|
||||
$address->setCity($city);
|
||||
$address->setStreet($street);
|
||||
$carrier->addAddress($address);
|
||||
// Adresse UNIQUE (OneToOne) — ERP-172.
|
||||
$carrier->setAddress($address);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajoute un contact normalise au transporteur (cascade persist via
|
||||
* Carrier.contacts). Au moins un champ est toujours fourni (RG-4.08).
|
||||
* Carrier.contacts). Prenom OU nom toujours fourni (RG-4.08, chk_carrier_contact_name).
|
||||
*/
|
||||
private function addContact(
|
||||
Carrier $carrier,
|
||||
|
||||
@@ -75,8 +75,12 @@ class UploadedDocument
|
||||
#[Groups(['uploaded_document:read'])]
|
||||
private ?int $id = null;
|
||||
|
||||
// `uploaded_document:reference` : groupe minimal d'EMBARQUEMENT (nom de fichier
|
||||
// seul, sans `storedPath`/`checksum`) pour qu'une entite parente (ex: Carrier)
|
||||
// affiche le libelle du document au lieu d'un simple IRI. La parente l'ajoute a
|
||||
// son `normalizationContext`.
|
||||
#[ORM\Column(name: 'original_filename', length: 255)]
|
||||
#[Groups(['uploaded_document:read'])]
|
||||
#[Groups(['uploaded_document:read', 'uploaded_document:reference'])]
|
||||
private string $originalFilename;
|
||||
|
||||
#[ORM\Column(name: 'stored_path', length: 512)]
|
||||
|
||||
@@ -497,23 +497,22 @@ final class ColumnCommentsCatalog
|
||||
] + self::timestampableBlamableComments(),
|
||||
|
||||
'carrier_address' => [
|
||||
'_table' => 'Adresses d un transporteur (1:n) — onglet Adresse (M4). Pre-remplie depuis QUALIMAT si applicable (RG-4.05).',
|
||||
'_table' => 'Adresse d un transporteur (1:1, OneToOne — ERP-172 : adresse UNIQUE) — onglet Adresse (M4). Pre-remplie depuis QUALIMAT si applicable (RG-4.05).',
|
||||
'id' => 'Identifiant interne auto-incremente.',
|
||||
'carrier_id' => 'FK -> carrier.id, ON DELETE CASCADE — transporteur proprietaire de l adresse.',
|
||||
'carrier_id' => 'FK -> carrier.id, ON DELETE CASCADE, UNIQUE (uniq_carrier_address_carrier) — transporteur proprietaire de l unique adresse.',
|
||||
'country' => 'Pays de l adresse — defaut France.',
|
||||
'postal_code' => 'Code postal (saisie assistee BAN cote front, RG-4.06).',
|
||||
'city' => 'Ville — preremplie depuis le code postal via API BAN cote front.',
|
||||
'street' => 'Numero et voie de l adresse.',
|
||||
'street_complement' => 'Complement d adresse (etage, batiment...) — optionnel.',
|
||||
'position' => 'Ordre d affichage de l adresse dans la liste du transporteur (croissant).',
|
||||
] + self::timestampableBlamableComments(),
|
||||
|
||||
'carrier_contact' => [
|
||||
'_table' => 'Contacts d un transporteur (1:n) — onglet Contact (M4). Au moins un champ rempli (RG-4.08, chk_carrier_contact_filled), max 2 telephones.',
|
||||
'_table' => '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.',
|
||||
'id' => 'Identifiant interne auto-incremente.',
|
||||
'carrier_id' => 'FK -> carrier.id, ON DELETE CASCADE — transporteur proprietaire du contact.',
|
||||
'first_name' => 'Prenom du contact (capitalise serveur). Au moins un champ du contact est requis (RG-4.08).',
|
||||
'last_name' => 'Nom du contact (capitalise serveur). Au moins un champ du contact est requis (RG-4.08).',
|
||||
'first_name' => 'Prenom du contact (capitalise serveur). Prenom OU nom obligatoire (RG-4.08, chk_carrier_contact_name).',
|
||||
'last_name' => 'Nom du contact (capitalise serveur). Prenom OU nom obligatoire (RG-4.08, chk_carrier_contact_name).',
|
||||
'job_title' => 'Fonction / intitule de poste du contact (≤ 120 caracteres).',
|
||||
'phone_primary' => 'Telephone principal — chiffres uniquement (normalisation serveur).',
|
||||
'phone_secondary' => 'Telephone secondaire — chiffres uniquement (max 2 telephones, RG-4.08).',
|
||||
|
||||
@@ -149,7 +149,7 @@ abstract class AbstractCarrierApiTestCase extends AbstractApiTestCase
|
||||
$address->setPostalCode('86000');
|
||||
$address->setCity('Poitiers');
|
||||
$address->setStreet('12 rue des Acacias');
|
||||
$carrier->addAddress($address);
|
||||
$carrier->setAddress($address);
|
||||
$em->persist($address);
|
||||
|
||||
$contact = new CarrierContact();
|
||||
|
||||
@@ -13,7 +13,7 @@ use Symfony\Component\Console\Output\NullOutput;
|
||||
|
||||
/**
|
||||
* Sous-ressource Adresse d'un transporteur (spec-back M4 § 4.5, ERP-159).
|
||||
* POST /api/carriers/{id}/addresses, PATCH/DELETE /api/carrier_addresses/{id}.
|
||||
* POST /api/carriers/{id}/address, PATCH/DELETE /api/carrier_addresses/{id}.
|
||||
*
|
||||
* Contrat verifie :
|
||||
* - RG-4.06 : code postal hors ^[0-9]{4,5}$ -> 422 ;
|
||||
@@ -55,7 +55,7 @@ final class CarrierAddressApiTest extends AbstractCarrierApiTestCase
|
||||
$carrier = $this->seedCarrierWithChartered('Cp Invalide', false);
|
||||
$client = $this->createAdminClient();
|
||||
|
||||
$response = $client->request('POST', '/api/carriers/'.$carrier->getId().'/addresses', [
|
||||
$response = $client->request('POST', '/api/carriers/'.$carrier->getId().'/address', [
|
||||
'headers' => ['Content-Type' => self::LD],
|
||||
'json' => ['postalCode' => '123'], // 3 chiffres -> Regex KO
|
||||
]);
|
||||
@@ -73,7 +73,7 @@ final class CarrierAddressApiTest extends AbstractCarrierApiTestCase
|
||||
$carrier = $this->seedCarrierWithChartered('Cp Ville Incoherents', false);
|
||||
$client = $this->createAdminClient();
|
||||
|
||||
$client->request('POST', '/api/carriers/'.$carrier->getId().'/addresses', [
|
||||
$client->request('POST', '/api/carriers/'.$carrier->getId().'/address', [
|
||||
'headers' => ['Content-Type' => self::LD],
|
||||
'json' => [
|
||||
'postalCode' => '86000', // Poitiers
|
||||
@@ -91,7 +91,7 @@ final class CarrierAddressApiTest extends AbstractCarrierApiTestCase
|
||||
$carrier = $this->seedCarrierWithChartered('Affrete Incomplet', true);
|
||||
$client = $this->createAdminClient();
|
||||
|
||||
$response = $client->request('POST', '/api/carriers/'.$carrier->getId().'/addresses', [
|
||||
$response = $client->request('POST', '/api/carriers/'.$carrier->getId().'/address', [
|
||||
'headers' => ['Content-Type' => self::LD],
|
||||
'json' => ['postalCode' => '86000'],
|
||||
]);
|
||||
@@ -107,7 +107,7 @@ final class CarrierAddressApiTest extends AbstractCarrierApiTestCase
|
||||
$carrier = $this->seedCarrierWithChartered('Affrete Complet', true);
|
||||
$client = $this->createAdminClient();
|
||||
|
||||
$client->request('POST', '/api/carriers/'.$carrier->getId().'/addresses', [
|
||||
$client->request('POST', '/api/carriers/'.$carrier->getId().'/address', [
|
||||
'headers' => ['Content-Type' => self::LD],
|
||||
'json' => [
|
||||
'country' => 'France',
|
||||
@@ -119,13 +119,30 @@ final class CarrierAddressApiTest extends AbstractCarrierApiTestCase
|
||||
self::assertResponseStatusCodeSame(201);
|
||||
}
|
||||
|
||||
public function testSecondAddressReturns409(): void
|
||||
{
|
||||
// Adresse UNIQUE (ERP-172) : un 2e POST sur un transporteur qui a deja une
|
||||
// adresse -> 409 explicite (garde CarrierAddressProcessor avant la contrainte
|
||||
// d'unicite carrier_id).
|
||||
$address = $this->seedAddress('Deja Une Adresse', false);
|
||||
$carrier = $address->getCarrier();
|
||||
self::assertNotNull($carrier);
|
||||
|
||||
$client = $this->createAdminClient();
|
||||
$client->request('POST', '/api/carriers/'.$carrier->getId().'/address', [
|
||||
'headers' => ['Content-Type' => self::LD],
|
||||
'json' => ['postalCode' => '17000', 'city' => 'La Rochelle', 'street' => '2 rue Neuve'],
|
||||
]);
|
||||
self::assertResponseStatusCodeSame(409);
|
||||
}
|
||||
|
||||
public function testPostAddressOnUnknownCarrierReturns404(): void
|
||||
{
|
||||
// Sous-ressource en read:false : le parent introuvable n'est plus intercepte
|
||||
// en amont -> le processor doit lever un 404 explicite (sinon 500 au persist).
|
||||
$client = $this->createAdminClient();
|
||||
|
||||
$client->request('POST', '/api/carriers/999999/addresses', [
|
||||
$client->request('POST', '/api/carriers/999999/address', [
|
||||
'headers' => ['Content-Type' => self::LD],
|
||||
'json' => ['postalCode' => '86000', 'city' => 'Poitiers', 'street' => '1 rue X'],
|
||||
]);
|
||||
@@ -156,7 +173,7 @@ final class CarrierAddressApiTest extends AbstractCarrierApiTestCase
|
||||
self::assertNotNull($carrier);
|
||||
$client = $this->authenticatedClient('commerciale', self::PWD); // view seul
|
||||
|
||||
$client->request('POST', '/api/carriers/'.$carrier->getId().'/addresses', [
|
||||
$client->request('POST', '/api/carriers/'.$carrier->getId().'/address', [
|
||||
'headers' => ['Content-Type' => self::LD],
|
||||
'json' => ['postalCode' => '86000', 'city' => 'Poitiers', 'street' => '1 rue X'],
|
||||
]);
|
||||
@@ -201,7 +218,7 @@ final class CarrierAddressApiTest extends AbstractCarrierApiTestCase
|
||||
$address->setPostalCode('86000');
|
||||
$address->setCity('Poitiers');
|
||||
$address->setStreet('12 rue des Acacias');
|
||||
$carrier->addAddress($address);
|
||||
$carrier->setAddress($address);
|
||||
$em->persist($address);
|
||||
$em->flush();
|
||||
|
||||
|
||||
@@ -15,8 +15,8 @@ use Symfony\Component\Console\Output\NullOutput;
|
||||
* POST /api/carriers/{id}/contacts, PATCH/DELETE /api/carrier_contacts/{id}.
|
||||
*
|
||||
* Contrat verifie :
|
||||
* - RG-4.08 : contact totalement vide -> 422 (au moins 1 champ requis) ;
|
||||
* - RG-4.08 : 1 seul champ rempli -> 201 ;
|
||||
* - RG-4.08 : contact sans prenom ni nom -> 422 (alignement M1/M2/M3) ;
|
||||
* - RG-4.08 : un nom (ou prenom) suffit -> 201 ;
|
||||
* - RG-4.08 : 3 telephones (tableau `phones`) -> 422 (max 2) ;
|
||||
* - mapping `phones[]` -> phonePrimary / phoneSecondary + normalisation (RG-4.13) ;
|
||||
* - PATCH / DELETE OK avec transport.carriers.manage, 403 sans (view seul).
|
||||
@@ -51,7 +51,8 @@ final class CarrierContactApiTest extends AbstractCarrierApiTestCase
|
||||
|
||||
public function testEmptyContactReturns422(): void
|
||||
{
|
||||
// RG-4.08 : aucun champ rempli -> 422 (garde Processor, double du CHECK BDD).
|
||||
// RG-4.08 (alignement M1/M2/M3) : sans prenom ni nom -> 422 (garde Processor,
|
||||
// double du CHECK BDD chk_carrier_contact_name).
|
||||
$carrier = $this->seedCarrier('Contact Vide');
|
||||
$client = $this->createAdminClient();
|
||||
|
||||
@@ -60,13 +61,13 @@ final class CarrierContactApiTest extends AbstractCarrierApiTestCase
|
||||
'json' => [],
|
||||
]);
|
||||
self::assertResponseStatusCodeSame(422);
|
||||
// RG-4.08 : la violation est rattachee a `firstName` (mapping inline ERP-101).
|
||||
// La violation est rattachee a `firstName` (mapping inline ERP-101).
|
||||
self::assertViolationOnPath($response, 'firstName');
|
||||
}
|
||||
|
||||
public function testSingleFieldContactIsCreated(): void
|
||||
{
|
||||
// RG-4.08 : un seul champ suffit a valider le bloc.
|
||||
// RG-4.08 : un nom (ou prenom) suffit a valider le bloc.
|
||||
$carrier = $this->seedCarrier('Contact Mono');
|
||||
$client = $this->createAdminClient();
|
||||
|
||||
|
||||
@@ -4,9 +4,14 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Module\Transport\Api;
|
||||
|
||||
use App\Module\Transport\Domain\Entity\Carrier;
|
||||
use App\Shared\Domain\Entity\UploadedDocument;
|
||||
use App\Tests\Module\Commercial\Api\SupplierSerializationContractTest;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* Tests du CONTRAT DE SERIALISATION du repertoire transporteurs (M4, spec-back
|
||||
* § 4.0 / § 4.0.bis). Jumeau de {@see \App\Tests\Module\Commercial\Api\SupplierSerializationContractTest}.
|
||||
* § 4.0 / § 4.0.bis). Jumeau de {@see SupplierSerializationContractTest}.
|
||||
* Reverifie sur le JSON REEL les pieges silencieux du M1 transposes au M4 :
|
||||
* - #1/#2 : relations embarquees en OBJET (pas IRI nu) — qualimatCarrier, et au
|
||||
* detail prices[].client / .supplier / .departureSite / .deliverySite.
|
||||
@@ -88,8 +93,9 @@ final class CarrierSerializationContractTest extends AbstractCarrierApiTestCase
|
||||
self::assertArrayHasKey('isChartered', $data);
|
||||
self::assertFalse($data['isArchived']);
|
||||
|
||||
self::assertNotEmpty($data['addresses']);
|
||||
self::assertSame('Poitiers', $data['addresses'][0]['city']);
|
||||
// Adresse UNIQUE (OneToOne, ERP-172) : embarquee en OBJET (pas une liste).
|
||||
self::assertIsArray($data['address']);
|
||||
self::assertSame('Poitiers', $data['address']['city']);
|
||||
|
||||
self::assertNotEmpty($data['contacts']);
|
||||
self::assertSame('Marie', $data['contacts'][0]['firstName']);
|
||||
@@ -133,6 +139,43 @@ final class CarrierSerializationContractTest extends AbstractCarrierApiTestCase
|
||||
self::assertIsArray($supplierPrice['deliverySite']);
|
||||
}
|
||||
|
||||
// === Decharge (RG-4.02) embarquee en OBJET avec son nom de fichier (ERP-171) ===
|
||||
|
||||
public function testDetailEmbedsDischargeDocumentFilename(): void
|
||||
{
|
||||
$em = $this->getEm();
|
||||
|
||||
// Decharge (UploadedDocument) rattachee a un transporteur certifie AUTRE.
|
||||
$document = new UploadedDocument(
|
||||
originalFilename: 'decharge-test.pdf',
|
||||
storedPath: '2026/06/'.bin2hex(random_bytes(8)).'.pdf',
|
||||
mimeType: 'application/pdf',
|
||||
sizeBytes: 1234,
|
||||
checksum: hash('sha256', 'contenu'),
|
||||
createdAt: new DateTimeImmutable(),
|
||||
);
|
||||
$em->persist($document);
|
||||
|
||||
$carrier = new Carrier();
|
||||
$carrier->setName('AUTRE DISCHARGE CO');
|
||||
$carrier->setCertificationType('AUTRE');
|
||||
$carrier->setDischargeDocument($document);
|
||||
$em->persist($carrier);
|
||||
$em->flush();
|
||||
|
||||
$http = $this->createAdminClient();
|
||||
$data = $http->request('GET', '/api/carriers/'.$carrier->getId(), ['headers' => ['Accept' => self::LD]])->toArray();
|
||||
|
||||
// dischargeDocument embarque en OBJET (uploaded_document:reference) avec son
|
||||
// nom de fichier — sinon le front n'a qu'un IRI nu et affiche un champ vide.
|
||||
self::assertArrayHasKey('dischargeDocument', $data);
|
||||
self::assertIsArray($data['dischargeDocument'], 'dischargeDocument doit etre un objet embarque, pas un IRI nu.');
|
||||
self::assertSame('decharge-test.pdf', $data['dischargeDocument']['originalFilename']);
|
||||
// Le groupe minimal n'expose PAS les metadonnees internes (storedPath / checksum).
|
||||
self::assertArrayNotHasKey('storedPath', $data['dischargeDocument']);
|
||||
self::assertArrayNotHasKey('checksum', $data['dischargeDocument']);
|
||||
}
|
||||
|
||||
// === RBAC : 403 sans la permission view ===
|
||||
|
||||
public function testForbiddenWithoutViewPermission(): void
|
||||
@@ -167,7 +210,7 @@ final class CarrierSerializationContractTest extends AbstractCarrierApiTestCase
|
||||
|
||||
self::assertArrayHasKey('member', $list);
|
||||
self::assertArrayHasKey('qualimatCarrier', $detail);
|
||||
self::assertArrayHasKey('addresses', $detail);
|
||||
self::assertArrayHasKey('address', $detail);
|
||||
self::assertArrayHasKey('contacts', $detail);
|
||||
self::assertArrayHasKey('prices', $detail);
|
||||
|
||||
@@ -183,7 +226,7 @@ final class CarrierSerializationContractTest extends AbstractCarrierApiTestCase
|
||||
*
|
||||
* @param array<string, mixed> $collection
|
||||
*
|
||||
* @return array<string, mixed>|null
|
||||
* @return null|array<string, mixed>
|
||||
*/
|
||||
private function memberById(array $collection, int $id): ?array
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user