Compare commits
72 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6d3122a0b8 | |||
| fa00a2b6e1 | |||
| a98f58cb33 | |||
| ab33b09bc0 | |||
| 023f70dd1d | |||
| c243232799 | |||
| cdd43960cd | |||
| 9a42c432f8 | |||
| 865e580b6e | |||
| 0ad4a739ca | |||
| cdcc7d1e75 | |||
| 07f5a95a6b | |||
| 403dc4a870 | |||
| 745b03083c | |||
| 868141e324 | |||
| 86507486a4 | |||
| 29aa9b352d | |||
| 5f2aa5334b | |||
| 21b1c64a5f | |||
| fd89160c4b | |||
| 8daf0ff5d4 | |||
| 87c53c354b | |||
| f8b45cb30b | |||
| 0c0b57f898 | |||
| 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 | |||
| 40fdded7e2 | |||
| 0733a239a8 | |||
| cf645493c1 | |||
| 388d39a379 | |||
| d6d2144cc1 | |||
| 6a519874ed | |||
| 3804362546 | |||
| 9864dbc00f | |||
| be03f4e51a | |||
| 8cc2cea444 | |||
| f70e701854 |
+1
-1
@@ -1,2 +1,2 @@
|
||||
parameters:
|
||||
app.version: '0.1.131'
|
||||
app.version: '0.1.138'
|
||||
|
||||
+158
-21
@@ -67,7 +67,7 @@
|
||||
"companyName": "Nom",
|
||||
"categories": "Catégories",
|
||||
"sites": "Site",
|
||||
"lastActivity": "Dernière activité"
|
||||
"lastActivity": "Dernière modification"
|
||||
},
|
||||
"filters": {
|
||||
"title": "Filtres",
|
||||
@@ -211,7 +211,7 @@
|
||||
"companyName": "Nom",
|
||||
"categories": "Catégories",
|
||||
"sites": "Site",
|
||||
"lastActivity": "Dernière activité"
|
||||
"lastActivity": "Dernière modification"
|
||||
},
|
||||
"filters": {
|
||||
"title": "Filtres",
|
||||
@@ -381,7 +381,7 @@
|
||||
"companyName": "Nom",
|
||||
"categories": "Catégories",
|
||||
"sites": "Site",
|
||||
"lastActivity": "Dernière activité"
|
||||
"lastActivity": "Dernière modification"
|
||||
},
|
||||
"filters": {
|
||||
"title": "Filtres",
|
||||
@@ -505,7 +505,7 @@
|
||||
"name": "Nom",
|
||||
"certification": "Certification",
|
||||
"validityDate": "Date de validité",
|
||||
"lastActivity": "Dernière activité"
|
||||
"lastActivity": "Dernière modification"
|
||||
},
|
||||
"certification": {
|
||||
"QUALIMAT": "QUALIMAT",
|
||||
@@ -526,7 +526,56 @@
|
||||
"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"
|
||||
"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": "Transport",
|
||||
"carrier": "Fournisseurs / Clients",
|
||||
"aproOrSite": "Adresse sites",
|
||||
"delivery": "Adresse livraisons",
|
||||
"forfait": "Forfait (€)",
|
||||
"tonne": "Tonne (€)",
|
||||
"indexation": "Indexation",
|
||||
"state": "État du prix",
|
||||
"export": "Exporter",
|
||||
"empty": "Aucun prix pour ce transporteur."
|
||||
}
|
||||
},
|
||||
"edit": {
|
||||
"title": "Modifier le transporteur",
|
||||
"back": "Retour à la consultation",
|
||||
"loading": "Chargement du transporteur…",
|
||||
"notFound": "Transporteur introuvable.",
|
||||
"save": "Enregistrer"
|
||||
},
|
||||
"containerType": {
|
||||
"BENNE": "Benne",
|
||||
"FOND_MOUVANT": "Fond mouvant"
|
||||
},
|
||||
"tab": {
|
||||
"qualimat": "Qualimat",
|
||||
@@ -543,10 +592,98 @@
|
||||
"main": {
|
||||
"name": "Nom",
|
||||
"certificationType": "Certification transport",
|
||||
"isChartered": "Affréter"
|
||||
"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."
|
||||
"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."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -593,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",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<div class="relative grid grid-cols-4 gap-x-[44px] gap-y-4 bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
|
||||
<!-- ariaLabel via v-bind objet (prop camelCase ; aria-* serait un attribut HTML). -->
|
||||
<MalioButtonIcon
|
||||
v-if="removable && !readonly"
|
||||
v-if="removable && !readonly && !disabled"
|
||||
icon="mdi:delete-outline"
|
||||
variant="ghost"
|
||||
button-class="absolute top-3 right-3"
|
||||
@@ -21,6 +21,7 @@
|
||||
:options="addressTypeOptions"
|
||||
:label="t('commercial.clients.form.address.addressType')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.isProspect"
|
||||
@update:model-value="onAddressTypeChange"
|
||||
@@ -33,6 +34,7 @@
|
||||
:label="t('commercial.clients.form.address.sites')"
|
||||
:display-tag="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.sites"
|
||||
@update:model-value="(v: (string | number)[]) => update('siteIris', v.map(String))"
|
||||
@@ -44,6 +46,7 @@
|
||||
:label="t('commercial.clients.form.address.contacts')"
|
||||
:display-tag="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
@update:model-value="(v: (string | number)[]) => update('contactIris', v.map(String))"
|
||||
/>
|
||||
|
||||
@@ -57,6 +60,7 @@
|
||||
:label="t('commercial.clients.form.address.billingEmail')"
|
||||
:required="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:lowercase="true"
|
||||
:error="errors?.billingEmail"
|
||||
:addable="!model.hasSecondaryBillingEmail && !readonly"
|
||||
@@ -71,6 +75,7 @@
|
||||
:model-value="model.billingEmailSecondary"
|
||||
:label="t('commercial.clients.form.address.billingEmailSecondary')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:lowercase="true"
|
||||
:error="errors?.billingEmailSecondary"
|
||||
@update:model-value="(v: string) => update('billingEmailSecondary', v)"
|
||||
@@ -82,6 +87,7 @@
|
||||
:label="t('commercial.clients.form.address.categories')"
|
||||
:display-tag="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.categories"
|
||||
@update:model-value="(v: (string | number)[]) => update('categoryIris', v.map(String))"
|
||||
@@ -92,6 +98,7 @@
|
||||
:options="countryOptions"
|
||||
:label="t('commercial.clients.form.address.country')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
@update:model-value="(v: string | number | null) => update('country', String(v ?? 'France'))"
|
||||
/>
|
||||
@@ -101,6 +108,7 @@
|
||||
:label="t('commercial.clients.form.address.postalCode')"
|
||||
:mask="POSTAL_CODE_MASK"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.postalCode"
|
||||
@update:model-value="onPostalCodeChange"
|
||||
@@ -115,6 +123,7 @@
|
||||
:options="cityOptions"
|
||||
:label="t('commercial.clients.form.address.city')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="errors?.city"
|
||||
@@ -125,6 +134,7 @@
|
||||
:model-value="model.city"
|
||||
:label="t('commercial.clients.form.address.city')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.city"
|
||||
@update:model-value="(v: string) => update('city', v)"
|
||||
@@ -142,13 +152,14 @@
|
||||
blur/Entree (saisie manuelle) — sinon il serait efface. La ville reste
|
||||
pilotee par le code postal ; choisir une suggestion remplit rue+ville+CP. -->
|
||||
<MalioInputAutocomplete
|
||||
v-if="!readonly"
|
||||
v-if="!readonly && !disabled"
|
||||
:model-value="model.street"
|
||||
:options="addressOptions"
|
||||
:loading="addressLoading"
|
||||
:min-search-length="3"
|
||||
:label="t('commercial.clients.form.address.street')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.street"
|
||||
:allow-create="true"
|
||||
@@ -162,6 +173,7 @@
|
||||
:model-value="model.street"
|
||||
:label="t('commercial.clients.form.address.street')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.street"
|
||||
@update:model-value="(v: string) => update('street', v)"
|
||||
@@ -173,6 +185,7 @@
|
||||
:model-value="model.streetComplement"
|
||||
:label="t('commercial.clients.form.address.streetComplement')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.streetComplement"
|
||||
@update:model-value="(v: string) => update('streetComplement', v)"
|
||||
/>
|
||||
@@ -191,6 +204,7 @@ import {
|
||||
import { useAddressAutocomplete, type AddressSuggestion } from '~/shared/composables/useAddressAutocomplete'
|
||||
import type { CategoryOption, RefOption } from '~/modules/commercial/composables/useClientReferentials'
|
||||
import type { AddressFormDraft } from '~/modules/commercial/types/clientForm'
|
||||
import { sanitizeAddress, sanitizeEmail } from '~/shared/utils/textSanitize'
|
||||
|
||||
// Masque code postal FR : 5 chiffres.
|
||||
const POSTAL_CODE_MASK = '#####'
|
||||
@@ -209,6 +223,8 @@ const props = defineProps<{
|
||||
countryOptions: RefOption[]
|
||||
removable?: boolean
|
||||
readonly?: boolean
|
||||
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
|
||||
disabled?: boolean
|
||||
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
@@ -284,9 +300,23 @@ 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). */
|
||||
// Filtres de saisie par champ (ERP-193) : voie / complement / ville = profil
|
||||
// adresse, emails de facturation = profil email.
|
||||
const FIELD_SANITIZERS: Partial<Record<keyof AddressFormDraft, (v: string) => string>> = {
|
||||
street: sanitizeAddress,
|
||||
streetComplement: sanitizeAddress,
|
||||
city: sanitizeAddress,
|
||||
billingEmail: sanitizeEmail,
|
||||
billingEmailSecondary: sanitizeEmail,
|
||||
}
|
||||
|
||||
/** Emet un nouveau brouillon avec le champ modifie (immutabilite), sanitise si besoin. */
|
||||
function update<K extends keyof AddressFormDraft>(field: K, value: AddressFormDraft[K]): void {
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: value })
|
||||
const sanitizer = FIELD_SANITIZERS[field]
|
||||
const next = (sanitizer && typeof value === 'string')
|
||||
? (sanitizer(value) as AddressFormDraft[K])
|
||||
: value
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: next })
|
||||
}
|
||||
|
||||
/** Revele le 2e champ email de facturation (clic sur le « + »). */
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
non supprimable (1er bloc obligatoire RG-1.14) ou en lecture seule.
|
||||
ariaLabel via v-bind objet (prop camelCase ; aria-* serait un attribut HTML). -->
|
||||
<MalioButtonIcon
|
||||
v-if="removable && !readonly"
|
||||
v-if="removable && !readonly && !disabled"
|
||||
icon="mdi:delete-outline"
|
||||
variant="ghost"
|
||||
button-class="absolute top-3 right-3"
|
||||
@@ -16,6 +16,7 @@
|
||||
:model-value="model.lastName"
|
||||
:label="t('commercial.clients.form.contact.lastName')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.lastName"
|
||||
@update:model-value="(v: string) => update('lastName', v)"
|
||||
/>
|
||||
@@ -23,6 +24,7 @@
|
||||
:model-value="model.firstName"
|
||||
:label="t('commercial.clients.form.contact.firstName')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.firstName"
|
||||
@update:model-value="(v: string) => update('firstName', v)"
|
||||
/>
|
||||
@@ -34,6 +36,7 @@
|
||||
:model-value="model.jobTitle"
|
||||
:label="t('commercial.clients.form.contact.jobTitle')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.jobTitle"
|
||||
@update:model-value="(v: string) => update('jobTitle', v)"
|
||||
/>
|
||||
@@ -42,6 +45,7 @@
|
||||
:model-value="model.email"
|
||||
:label="t('commercial.clients.form.contact.email')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:lowercase="true"
|
||||
:error="errors?.email"
|
||||
@update:model-value="(v: string) => update('email', v)"
|
||||
@@ -51,6 +55,7 @@
|
||||
:label="t('commercial.clients.form.contact.phonePrimary')"
|
||||
:mask="PHONE_MASK"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.phonePrimary"
|
||||
:addable="!model.hasSecondaryPhone && !readonly"
|
||||
:add-button-label="t('commercial.clients.form.contact.addPhone')"
|
||||
@@ -63,6 +68,7 @@
|
||||
:label="t('commercial.clients.form.contact.phoneSecondary')"
|
||||
:mask="PHONE_MASK"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.phoneSecondary"
|
||||
@update:model-value="(v: string) => update('phoneSecondary', v)"
|
||||
/>
|
||||
@@ -71,6 +77,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { ContactFormDraft } from '~/modules/commercial/types/clientForm'
|
||||
import { sanitizeEmail, sanitizeFreeText, sanitizePersonName } from '~/shared/utils/textSanitize'
|
||||
|
||||
// Masque telephone FR : 5 groupes de 2 chiffres (la normalisation finale reste
|
||||
// serveur, cf. formatPhoneFR re-applique a la valeur renvoyee).
|
||||
@@ -85,6 +92,8 @@ const props = defineProps<{
|
||||
removable?: boolean
|
||||
/** Bloc en lecture seule (onglet valide). */
|
||||
readonly?: boolean
|
||||
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
|
||||
disabled?: boolean
|
||||
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
@@ -99,9 +108,22 @@ const { t } = useI18n()
|
||||
// Alias local pour la lisibilite du template.
|
||||
const model = computed(() => props.modelValue)
|
||||
|
||||
/** Emet un nouveau brouillon avec le champ modifie (immutabilite). */
|
||||
// Filtres de saisie par champ (ERP-193) : on retire les caracteres parasites a la
|
||||
// frappe. Noms = profil personne, fonction = texte libre, email = profil email.
|
||||
const FIELD_SANITIZERS: Partial<Record<keyof ContactFormDraft, (v: string) => string>> = {
|
||||
lastName: sanitizePersonName,
|
||||
firstName: sanitizePersonName,
|
||||
jobTitle: sanitizeFreeText,
|
||||
email: sanitizeEmail,
|
||||
}
|
||||
|
||||
/** Emet un nouveau brouillon avec le champ modifie (immutabilite), sanitise si besoin. */
|
||||
function update<K extends keyof ContactFormDraft>(field: K, value: ContactFormDraft[K]): void {
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: value })
|
||||
const sanitizer = FIELD_SANITIZERS[field]
|
||||
const next = (sanitizer && typeof value === 'string')
|
||||
? (sanitizer(value) as ContactFormDraft[K])
|
||||
: value
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: next })
|
||||
}
|
||||
|
||||
/** Revele le 2e numero (RG-1.02/1.20 : max 1 secondaire, le « + » disparait). */
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<div class="relative grid grid-cols-4 gap-x-[44px] gap-y-4 bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
|
||||
<!-- Suppression : modal de confirmation cote parent. -->
|
||||
<MalioButtonIcon
|
||||
v-if="removable && !readonly"
|
||||
v-if="removable && !readonly && !disabled"
|
||||
icon="mdi:delete-outline"
|
||||
variant="ghost"
|
||||
button-class="absolute top-3 right-3"
|
||||
@@ -18,6 +18,7 @@
|
||||
:options="addressTypeOptions"
|
||||
:label="t('commercial.suppliers.form.address.addressType')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="errors?.addressType"
|
||||
@@ -31,6 +32,7 @@
|
||||
:label="t('commercial.suppliers.form.address.sites')"
|
||||
:display-tag="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.sites"
|
||||
@update:model-value="(v: (string | number)[]) => update('siteIris', v.map(String))"
|
||||
@@ -43,6 +45,7 @@
|
||||
:label="t('commercial.suppliers.form.address.contacts')"
|
||||
:display-tag="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
@update:model-value="(v: (string | number)[]) => update('contactIris', v.map(String))"
|
||||
/>
|
||||
|
||||
@@ -57,6 +60,7 @@
|
||||
:label="t('commercial.suppliers.form.address.categories')"
|
||||
:display-tag="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.categories"
|
||||
@update:model-value="(v: (string | number)[]) => update('categoryIris', v.map(String))"
|
||||
@@ -67,6 +71,7 @@
|
||||
:options="countryOptions"
|
||||
:label="t('commercial.suppliers.form.address.country')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
@update:model-value="(v: string | number | null) => update('country', String(v ?? 'France'))"
|
||||
/>
|
||||
@@ -76,6 +81,7 @@
|
||||
:label="t('commercial.suppliers.form.address.postalCode')"
|
||||
:mask="POSTAL_CODE_MASK"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.postalCode"
|
||||
@update:model-value="onPostalCodeChange"
|
||||
@@ -88,6 +94,7 @@
|
||||
:options="cityOptions"
|
||||
:label="t('commercial.suppliers.form.address.city')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="errors?.city"
|
||||
@@ -98,6 +105,7 @@
|
||||
:model-value="model.city"
|
||||
:label="t('commercial.suppliers.form.address.city')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.city"
|
||||
@update:model-value="(v: string) => update('city', v)"
|
||||
@@ -107,13 +115,14 @@
|
||||
texte saisi est conserve si la BAN ne propose rien (saisie manuelle). -->
|
||||
<div class="col-span-2">
|
||||
<MalioInputAutocomplete
|
||||
v-if="!readonly"
|
||||
v-if="!readonly && !disabled"
|
||||
:model-value="model.street"
|
||||
:options="addressOptions"
|
||||
:loading="addressLoading"
|
||||
:min-search-length="3"
|
||||
:label="t('commercial.suppliers.form.address.street')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.street"
|
||||
:allow-create="true"
|
||||
@@ -127,6 +136,7 @@
|
||||
:model-value="model.street"
|
||||
:label="t('commercial.suppliers.form.address.street')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.street"
|
||||
@update:model-value="(v: string) => update('street', v)"
|
||||
@@ -138,6 +148,7 @@
|
||||
:model-value="model.streetComplement"
|
||||
:label="t('commercial.suppliers.form.address.streetComplement')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.streetComplement"
|
||||
@update:model-value="(v: string) => update('streetComplement', v)"
|
||||
/>
|
||||
@@ -149,6 +160,7 @@
|
||||
:label="t('commercial.suppliers.form.address.bennes')"
|
||||
:min="0"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.bennes"
|
||||
@update:model-value="(v: string) => update('bennes', v)"
|
||||
/>
|
||||
@@ -160,6 +172,7 @@
|
||||
:model-value="model.triageProvider"
|
||||
group-class="self-center"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
@update:model-value="(v: boolean) => update('triageProvider', v)"
|
||||
/>
|
||||
</div>
|
||||
@@ -169,6 +182,7 @@
|
||||
import { useAddressAutocomplete, type AddressSuggestion } from '~/shared/composables/useAddressAutocomplete'
|
||||
import type { CategoryOption, RefOption } from '~/modules/commercial/composables/useSupplierReferentials'
|
||||
import type { SupplierAddressFormDraft, SupplierAddressType } from '~/modules/commercial/types/supplierForm'
|
||||
import { sanitizeAddress } from '~/shared/utils/textSanitize'
|
||||
|
||||
// Masque code postal FR : 5 chiffres.
|
||||
const POSTAL_CODE_MASK = '#####'
|
||||
@@ -187,6 +201,8 @@ const props = defineProps<{
|
||||
countryOptions: RefOption[]
|
||||
removable?: boolean
|
||||
readonly?: boolean
|
||||
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
|
||||
disabled?: boolean
|
||||
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
@@ -238,9 +254,21 @@ 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). */
|
||||
// Filtres de saisie par champ (ERP-193) : voie / complement / ville = profil
|
||||
// adresse. Les autres champs (CP, bennes, selects) ne sont pas filtres ici.
|
||||
const FIELD_SANITIZERS: Partial<Record<keyof SupplierAddressFormDraft, (v: string) => string>> = {
|
||||
street: sanitizeAddress,
|
||||
streetComplement: sanitizeAddress,
|
||||
city: sanitizeAddress,
|
||||
}
|
||||
|
||||
/** Emet un nouveau brouillon avec le champ modifie (immutabilite), sanitise si besoin. */
|
||||
function update<K extends keyof SupplierAddressFormDraft>(field: K, value: SupplierAddressFormDraft[K]): void {
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: value })
|
||||
const sanitizer = FIELD_SANITIZERS[field]
|
||||
const next = (sanitizer && typeof value === 'string')
|
||||
? (sanitizer(value) as SupplierAddressFormDraft[K])
|
||||
: value
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: next })
|
||||
}
|
||||
|
||||
/** Previent le parent (toast unique) que l'autocompletion est indisponible. */
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<!-- Suppression : ouvre une modal de confirmation cote parent. Masquee si
|
||||
non supprimable (1er bloc, RG-2.13) ou en lecture seule. -->
|
||||
<MalioButtonIcon
|
||||
v-if="removable && !readonly"
|
||||
v-if="removable && !readonly && !disabled"
|
||||
icon="mdi:delete-outline"
|
||||
variant="ghost"
|
||||
button-class="absolute top-3 right-3"
|
||||
@@ -15,6 +15,7 @@
|
||||
:model-value="model.lastName"
|
||||
:label="t('commercial.suppliers.form.contact.lastName')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.lastName"
|
||||
@update:model-value="(v: string) => update('lastName', v)"
|
||||
/>
|
||||
@@ -22,6 +23,7 @@
|
||||
:model-value="model.firstName"
|
||||
:label="t('commercial.suppliers.form.contact.firstName')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.firstName"
|
||||
@update:model-value="(v: string) => update('firstName', v)"
|
||||
/>
|
||||
@@ -33,6 +35,7 @@
|
||||
:model-value="model.jobTitle"
|
||||
:label="t('commercial.suppliers.form.contact.jobTitle')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.jobTitle"
|
||||
@update:model-value="(v: string) => update('jobTitle', v)"
|
||||
/>
|
||||
@@ -41,6 +44,7 @@
|
||||
:model-value="model.email"
|
||||
:label="t('commercial.suppliers.form.contact.email')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:lowercase="true"
|
||||
:error="errors?.email"
|
||||
@update:model-value="(v: string) => update('email', v)"
|
||||
@@ -50,6 +54,7 @@
|
||||
:label="t('commercial.suppliers.form.contact.phonePrimary')"
|
||||
:mask="PHONE_MASK"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.phonePrimary"
|
||||
:addable="!model.hasSecondaryPhone && !readonly"
|
||||
:add-button-label="t('commercial.suppliers.form.contact.addPhone')"
|
||||
@@ -62,6 +67,7 @@
|
||||
:label="t('commercial.suppliers.form.contact.phoneSecondary')"
|
||||
:mask="PHONE_MASK"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.phoneSecondary"
|
||||
@update:model-value="(v: string) => update('phoneSecondary', v)"
|
||||
/>
|
||||
@@ -70,6 +76,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { SupplierContactFormDraft } from '~/modules/commercial/types/supplierForm'
|
||||
import { sanitizeEmail, sanitizeFreeText, sanitizePersonName } from '~/shared/utils/textSanitize'
|
||||
|
||||
// Masque telephone FR : 5 groupes de 2 chiffres (la normalisation finale reste serveur).
|
||||
const PHONE_MASK = '## ## ## ## ##'
|
||||
@@ -83,6 +90,8 @@ const props = defineProps<{
|
||||
removable?: boolean
|
||||
/** Bloc en lecture seule (onglet valide). */
|
||||
readonly?: boolean
|
||||
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
|
||||
disabled?: boolean
|
||||
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
@@ -97,9 +106,22 @@ const { t } = useI18n()
|
||||
// Alias local pour la lisibilite du template.
|
||||
const model = computed(() => props.modelValue)
|
||||
|
||||
/** Emet un nouveau brouillon avec le champ modifie (immutabilite). */
|
||||
// Filtres de saisie par champ (ERP-193) : on retire les caracteres parasites a la
|
||||
// frappe. Noms = profil personne, fonction = texte libre, email = profil email.
|
||||
const FIELD_SANITIZERS: Partial<Record<keyof SupplierContactFormDraft, (v: string) => string>> = {
|
||||
lastName: sanitizePersonName,
|
||||
firstName: sanitizePersonName,
|
||||
jobTitle: sanitizeFreeText,
|
||||
email: sanitizeEmail,
|
||||
}
|
||||
|
||||
/** Emet un nouveau brouillon avec le champ modifie (immutabilite), sanitise si besoin. */
|
||||
function update<K extends keyof SupplierContactFormDraft>(field: K, value: SupplierContactFormDraft[K]): void {
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: value })
|
||||
const sanitizer = FIELD_SANITIZERS[field]
|
||||
const next = (sanitizer && typeof value === 'string')
|
||||
? (sanitizer(value) as SupplierContactFormDraft[K])
|
||||
: value
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: next })
|
||||
}
|
||||
|
||||
/** Revele le 2e numero (max 1 secondaire, le « + » disparait). */
|
||||
|
||||
@@ -25,8 +25,8 @@ function makeHydra(total: number): HydraCollection<Client> {
|
||||
describe('useClientsRepository', () => {
|
||||
beforeEach(() => {
|
||||
mockGet.mockReset()
|
||||
// 25 items → 3 pages a 10/page : permet de tester la navigation page 2.
|
||||
mockGet.mockResolvedValue(makeHydra(25))
|
||||
// 60 items → 3 pages a 25/page : permet de tester la navigation page 2.
|
||||
mockGet.mockResolvedValue(makeHydra(60))
|
||||
})
|
||||
|
||||
it('cible la ressource /clients en page 1 par defaut', async () => {
|
||||
@@ -35,7 +35,7 @@ describe('useClientsRepository', () => {
|
||||
|
||||
expect(mockGet).toHaveBeenLastCalledWith(
|
||||
'/clients',
|
||||
{ page: 1, itemsPerPage: 10 },
|
||||
{ page: 1, itemsPerPage: 25 },
|
||||
expect.objectContaining({ toast: false }),
|
||||
)
|
||||
})
|
||||
@@ -65,7 +65,7 @@ describe('useClientsRepository', () => {
|
||||
'siteId[]': ['1', '2'],
|
||||
archivedOnly: true,
|
||||
page: 1,
|
||||
itemsPerPage: 10,
|
||||
itemsPerPage: 25,
|
||||
},
|
||||
expect.objectContaining({ toast: false }),
|
||||
)
|
||||
@@ -78,7 +78,7 @@ describe('useClientsRepository', () => {
|
||||
|
||||
expect(mockGet).toHaveBeenLastCalledWith(
|
||||
'/clients',
|
||||
{ page: 1, itemsPerPage: 10 },
|
||||
{ page: 1, itemsPerPage: 25 },
|
||||
expect.objectContaining({ toast: false }),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -25,8 +25,8 @@ function makeHydra(total: number): HydraCollection<Supplier> {
|
||||
describe('useSuppliersRepository', () => {
|
||||
beforeEach(() => {
|
||||
mockGet.mockReset()
|
||||
// 25 items → 3 pages a 10/page : permet de tester la navigation page 2.
|
||||
mockGet.mockResolvedValue(makeHydra(25))
|
||||
// 60 items → 3 pages a 25/page : permet de tester la navigation page 2.
|
||||
mockGet.mockResolvedValue(makeHydra(60))
|
||||
})
|
||||
|
||||
it('cible la ressource /suppliers en page 1 par defaut', async () => {
|
||||
@@ -35,7 +35,7 @@ describe('useSuppliersRepository', () => {
|
||||
|
||||
expect(mockGet).toHaveBeenLastCalledWith(
|
||||
'/suppliers',
|
||||
{ page: 1, itemsPerPage: 10 },
|
||||
{ page: 1, itemsPerPage: 25 },
|
||||
expect.objectContaining({ toast: false }),
|
||||
)
|
||||
})
|
||||
@@ -65,7 +65,7 @@ describe('useSuppliersRepository', () => {
|
||||
'siteId[]': ['86', '17'],
|
||||
archivedOnly: true,
|
||||
page: 1,
|
||||
itemsPerPage: 10,
|
||||
itemsPerPage: 25,
|
||||
},
|
||||
expect.objectContaining({ toast: false }),
|
||||
)
|
||||
@@ -78,7 +78,7 @@ describe('useSuppliersRepository', () => {
|
||||
|
||||
expect(mockGet).toHaveBeenLastCalledWith(
|
||||
'/suppliers',
|
||||
{ page: 1, itemsPerPage: 10 },
|
||||
{ page: 1, itemsPerPage: 25 },
|
||||
expect.objectContaining({ toast: false }),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -49,5 +49,6 @@ export interface Client {
|
||||
* gerer.
|
||||
*/
|
||||
export function useClientsRepository() {
|
||||
return usePaginatedList<Client>({ url: '/clients' })
|
||||
// Pagination par defaut a 25 sur le repertoire (retour metier ERP-193).
|
||||
return usePaginatedList<Client>({ url: '/clients', defaultItemsPerPage: 25 })
|
||||
}
|
||||
|
||||
@@ -51,5 +51,6 @@ export interface Supplier {
|
||||
* `usePaginatedList`. Aucun reset au logout a gerer.
|
||||
*/
|
||||
export function useSuppliersRepository() {
|
||||
return usePaginatedList<Supplier>({ url: '/suppliers' })
|
||||
// Pagination par defaut a 25 sur le repertoire (retour metier ERP-193).
|
||||
return usePaginatedList<Supplier>({ url: '/suppliers', defaultItemsPerPage: 25 })
|
||||
}
|
||||
|
||||
@@ -24,10 +24,11 @@
|
||||
`manage` (ex. Compta). -->
|
||||
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText
|
||||
v-model="main.companyName"
|
||||
:model-value="main.companyName"
|
||||
@update:model-value="(v: string) => main.companyName = sanitizeFreeText(v)"
|
||||
:label="t('commercial.clients.form.main.companyName')"
|
||||
:required="true"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:error="mainErrors.errors.companyName"
|
||||
/>
|
||||
<MalioSelectCheckbox
|
||||
@@ -35,7 +36,7 @@
|
||||
:options="mainCategoryOptions"
|
||||
:label="t('commercial.clients.form.main.categories')"
|
||||
:display-tag="true"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.categories"
|
||||
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
|
||||
@@ -46,7 +47,7 @@
|
||||
:options="relationOptions"
|
||||
:label="t('commercial.clients.form.main.relation')"
|
||||
:empty-option-label="t('commercial.clients.form.main.relationNone')"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
@update:model-value="onRelationChange"
|
||||
/>
|
||||
<MalioSelect
|
||||
@@ -54,7 +55,7 @@
|
||||
:model-value="main.brokerIri"
|
||||
:options="brokerOptions"
|
||||
:label="t('commercial.clients.form.main.brokerName')"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.broker"
|
||||
@update:model-value="(v: string | number | null) => main.brokerIri = v === null ? null : String(v)"
|
||||
@@ -64,7 +65,7 @@
|
||||
:model-value="main.distributorIri"
|
||||
:options="distributorOptions"
|
||||
:label="t('commercial.clients.form.main.distributorName')"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.distributor"
|
||||
@update:model-value="(v: string | number | null) => main.distributorIri = v === null ? null : String(v)"
|
||||
@@ -74,7 +75,7 @@
|
||||
v-model="main.triageService"
|
||||
:label="t('commercial.clients.form.main.triageService')"
|
||||
group-class="self-center"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -101,20 +102,24 @@
|
||||
resize="none"
|
||||
group-class="row-span-2 pt-1 pb-1"
|
||||
text-input="h-full text-lg"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:error="informationErrors.errors.description"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.competitors"
|
||||
:model-value="information.competitors"
|
||||
@update:model-value="(v: string) => information.competitors = sanitizeFreeText(v)"
|
||||
:label="t('commercial.clients.form.information.competitors')"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:error="informationErrors.errors.competitors"
|
||||
/>
|
||||
<!-- Date de creation jamais dans le futur (ERP-193) : :max plafonne
|
||||
le calendrier a aujourd'hui et invalide une saisie future. -->
|
||||
<MalioDate
|
||||
v-model="information.foundedAt"
|
||||
:label="t('commercial.clients.form.information.foundedAt')"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:editable="true"
|
||||
:max="maxFoundedAt"
|
||||
:error="informationErrors.errors.foundedAt"
|
||||
@update:raw-value="(v: string) => information.foundedAtRaw = v"
|
||||
/>
|
||||
@@ -122,25 +127,30 @@
|
||||
v-model="information.employeesCount"
|
||||
:label="t('commercial.clients.form.information.employeesCount')"
|
||||
:mask="EMPLOYEES_MASK"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:error="informationErrors.errors.employeesCount"
|
||||
/>
|
||||
<!-- CA plafonne a 999 999 999 999,99 (ERP-193) : clamp a la saisie,
|
||||
:key force le re-affichage quand on plafonne (modelValue inchange). -->
|
||||
<MalioInputAmount
|
||||
v-model="information.revenueAmount"
|
||||
:key="revenueAmountKey"
|
||||
:model-value="information.revenueAmount"
|
||||
:label="t('commercial.clients.form.information.revenueAmount')"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:error="informationErrors.errors.revenueAmount"
|
||||
@update:model-value="onRevenueAmountInput"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.directorName"
|
||||
:model-value="information.directorName"
|
||||
@update:model-value="(v: string) => information.directorName = sanitizePersonName(v)"
|
||||
:label="t('commercial.clients.form.information.directorName')"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:error="informationErrors.errors.directorName"
|
||||
/>
|
||||
<MalioInputAmount
|
||||
v-model="information.profitAmount"
|
||||
:label="t('commercial.clients.form.information.profitAmount')"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:error="informationErrors.errors.profitAmount"
|
||||
/>
|
||||
</div>
|
||||
@@ -167,7 +177,7 @@
|
||||
:model-value="contact"
|
||||
:title="t('commercial.clients.form.contact.title', { n: index + 1 })"
|
||||
:removable="isRowRemovable(contacts, index)"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:errors="contactErrors[index]"
|
||||
@update:model-value="(v) => contacts[index] = v"
|
||||
@remove="askRemoveContact(index)"
|
||||
@@ -204,7 +214,7 @@
|
||||
:contact-options="contactOptions"
|
||||
:country-options="countryOptions"
|
||||
:removable="isRowRemovable(addresses, index)"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:errors="addressErrors[index]"
|
||||
@update:model-value="(v) => addresses[index] = v"
|
||||
@remove="askRemoveAddress(index)"
|
||||
@@ -239,14 +249,15 @@
|
||||
v-model="accounting.siren"
|
||||
:label="t('commercial.clients.form.accounting.siren')"
|
||||
:mask="SIREN_MASK"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.siren"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="accounting.accountNumber"
|
||||
:model-value="accounting.accountNumber"
|
||||
@update:model-value="(v: string) => accounting.accountNumber = sanitizeCodeAlnum(v)"
|
||||
:label="t('commercial.clients.form.accounting.accountNumber')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.accountNumber"
|
||||
/>
|
||||
@@ -254,16 +265,17 @@
|
||||
:model-value="accounting.tvaModeIri"
|
||||
:options="tvaModeOptions"
|
||||
:label="t('commercial.clients.form.accounting.tvaMode')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.tvaMode"
|
||||
@update:model-value="(v: string | number | null) => accounting.tvaModeIri = v === null ? null : String(v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="accounting.nTva"
|
||||
:model-value="accounting.nTva"
|
||||
@update:model-value="(v: string) => accounting.nTva = sanitizeCodeAlnum(v)"
|
||||
:label="t('commercial.clients.form.accounting.nTva')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.nTva"
|
||||
/>
|
||||
@@ -271,7 +283,7 @@
|
||||
:model-value="accounting.paymentDelayIri"
|
||||
:options="paymentDelayOptions"
|
||||
:label="t('commercial.clients.form.accounting.paymentDelay')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.paymentDelay"
|
||||
@@ -281,7 +293,7 @@
|
||||
:model-value="accounting.paymentTypeIri"
|
||||
:options="paymentTypeOptions"
|
||||
:label="t('commercial.clients.form.accounting.paymentType')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.paymentType"
|
||||
@@ -292,7 +304,7 @@
|
||||
:model-value="accounting.bankIri"
|
||||
:options="bankOptions"
|
||||
:label="t('commercial.clients.form.accounting.bank')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.bank"
|
||||
@@ -319,21 +331,23 @@
|
||||
<MalioInputText
|
||||
v-model="rib.label"
|
||||
:label="t('commercial.clients.form.accounting.ribLabel')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.label"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="rib.bic"
|
||||
:model-value="rib.bic"
|
||||
@update:model-value="(v: string) => rib.bic = sanitizeCodeAlnum(v)"
|
||||
:label="t('commercial.clients.form.accounting.ribBic')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.bic"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="rib.iban"
|
||||
:model-value="rib.iban"
|
||||
@update:model-value="(v: string) => rib.iban = sanitizeCodeAlnum(v)"
|
||||
:label="t('commercial.clients.form.accounting.ribIban')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.iban"
|
||||
/>
|
||||
@@ -423,6 +437,9 @@ import {
|
||||
type InformationFormDraft,
|
||||
type MainFormDraft,
|
||||
} from '~/modules/commercial/utils/forms/clientEdit'
|
||||
import { clampRevenueAmount } from '~/modules/commercial/utils/forms/amountInput'
|
||||
import { todayIso } from '~/shared/utils/date'
|
||||
import { sanitizeCodeAlnum, sanitizeFreeText, sanitizePersonName } from '~/shared/utils/textSanitize'
|
||||
import {
|
||||
buildClientFormTabKeys,
|
||||
isAddressValid,
|
||||
@@ -491,6 +508,22 @@ const headerTitle = computed(() => client.value?.companyName ?? t('commercial.cl
|
||||
const main = reactive<MainFormDraft>(mapMainDraft({} as ClientDetail))
|
||||
const information = reactive<InformationFormDraft>(mapInformationDraft({} as ClientDetail))
|
||||
const accounting = reactive<AccountingFormDraft>(mapAccountingFormDraft({} as ClientDetail))
|
||||
|
||||
// Borne haute de la date de creation : aujourd'hui (ERP-193, pas de date future).
|
||||
const maxFoundedAt = todayIso()
|
||||
|
||||
// CA plafonne a 999 999 999 999,99 (ERP-193). La :key force le re-affichage du
|
||||
// champ controle quand le plafonnement laisse le modelValue inchange.
|
||||
const revenueAmountKey = ref(0)
|
||||
|
||||
/** Saisie du CA : plafonne au maximum metier et re-synchronise le champ si plafonne. */
|
||||
function onRevenueAmountInput(value: string | null): void {
|
||||
const clamped = clampRevenueAmount(value)
|
||||
information.revenueAmount = clamped ?? null
|
||||
if (clamped !== value) {
|
||||
revenueAmountKey.value += 1
|
||||
}
|
||||
}
|
||||
const contacts = ref<ContactFormDraft[]>([])
|
||||
const addresses = ref<AddressFormDraft[]>([])
|
||||
const ribs = ref<RibFormDraft[]>([])
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
/>
|
||||
<MalioButton
|
||||
v-if="showArchive"
|
||||
variant="secondary"
|
||||
variant="danger"
|
||||
icon-name="mdi:archive-arrow-down-outline"
|
||||
icon-position="left"
|
||||
:label="t('commercial.clients.action.archive')"
|
||||
@@ -50,14 +50,14 @@
|
||||
<MalioInputText
|
||||
:model-value="client.companyName"
|
||||
:label="t('commercial.clients.form.main.companyName')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioSelectCheckbox
|
||||
:model-value="categoryIris"
|
||||
:options="mainCategoryOptions"
|
||||
:label="t('commercial.clients.form.main.categories')"
|
||||
:display-tag="true"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<!-- Relation toujours affichee (vide = « Aucun »), comme en edition. -->
|
||||
<MalioSelect
|
||||
@@ -65,7 +65,7 @@
|
||||
:options="relationOptions"
|
||||
:label="t('commercial.clients.form.main.relation')"
|
||||
:empty-option-label="t('commercial.clients.form.main.relationNone')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<!-- Nom du distributeur/courtier : conditionnel (libelle type-dependant,
|
||||
aucune valeur sans relation — meme comportement qu'en edition). -->
|
||||
@@ -73,18 +73,20 @@
|
||||
v-if="relation.type"
|
||||
:model-value="relation.name"
|
||||
:label="relation.type === 'distributeur' ? t('commercial.clients.form.main.distributorName') : t('commercial.clients.form.main.brokerName')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioCheckbox
|
||||
:model-value="client.triageService === true"
|
||||
:label="t('commercial.clients.form.main.triageService')"
|
||||
group-class="self-center"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- ── Onglets (navigation libre, tout en lecture seule) ─────────── -->
|
||||
<MalioTabList v-model="activeTab" :tabs="tabs" :max-visible-tabs="5" :max-width="1100" class="mt-[60px]">
|
||||
<!-- ERP-193 : on n'affiche la barre que s'il reste au moins un onglet
|
||||
non vide (sinon seul le bloc principal est visible). -->
|
||||
<MalioTabList v-if="visibleTabKeys.length" v-model="activeTab" :tabs="tabs" :max-visible-tabs="5" :max-width="1100" class="mt-[60px]">
|
||||
<!-- Onglet Information -->
|
||||
<template #information>
|
||||
<div class="mt-12 grid grid-cols-4 gap-x-[44px] gap-y-4 bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
|
||||
@@ -97,37 +99,37 @@
|
||||
resize="none"
|
||||
group-class="row-span-2 pt-1 pb-1"
|
||||
text-input="h-full text-lg"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="information.competitors"
|
||||
:label="t('commercial.clients.form.information.competitors')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioDate
|
||||
:model-value="information.foundedAt"
|
||||
:label="t('commercial.clients.form.information.foundedAt')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="information.employeesCount"
|
||||
:label="t('commercial.clients.form.information.employeesCount')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputAmount
|
||||
:model-value="information.revenueAmount"
|
||||
:label="t('commercial.clients.form.information.revenueAmount')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="information.directorName"
|
||||
:label="t('commercial.clients.form.information.directorName')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputAmount
|
||||
:model-value="information.profitAmount"
|
||||
:label="t('commercial.clients.form.information.profitAmount')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -140,7 +142,7 @@
|
||||
:key="contact.id ?? index"
|
||||
:model-value="contact"
|
||||
:title="t('commercial.clients.form.contact.title', { n: index + 1 })"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -157,7 +159,7 @@
|
||||
:site-options="allSiteOptions"
|
||||
:contact-options="contactOptions"
|
||||
:country-options="countryOptions"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -171,38 +173,38 @@
|
||||
:model-value="accounting.siren"
|
||||
:label="t('commercial.clients.form.accounting.siren')"
|
||||
:mask="SIREN_MASK"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="accounting.accountNumber"
|
||||
:label="t('commercial.clients.form.accounting.accountNumber')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.tvaModeIri"
|
||||
:options="tvaModeOptions"
|
||||
:label="t('commercial.clients.form.accounting.tvaMode')"
|
||||
empty-option-label=""
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="accounting.nTva"
|
||||
:label="t('commercial.clients.form.accounting.nTva')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.paymentDelayIri"
|
||||
:options="paymentDelayOptions"
|
||||
:label="t('commercial.clients.form.accounting.paymentDelay')"
|
||||
empty-option-label=""
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.paymentTypeIri"
|
||||
:options="paymentTypeOptions"
|
||||
:label="t('commercial.clients.form.accounting.paymentType')"
|
||||
empty-option-label=""
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioSelect
|
||||
v-if="accounting.bankIri"
|
||||
@@ -210,7 +212,7 @@
|
||||
:options="bankOptions"
|
||||
:label="t('commercial.clients.form.accounting.bank')"
|
||||
empty-option-label=""
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -225,28 +227,25 @@
|
||||
<MalioInputText
|
||||
:model-value="rib.label"
|
||||
:label="t('commercial.clients.form.accounting.ribLabel')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="rib.bic"
|
||||
:label="t('commercial.clients.form.accounting.ribBic')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="rib.iban"
|
||||
:label="t('commercial.clients.form.accounting.ribIban')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Onglets non encore implementes : frame vide (navigation libre). -->
|
||||
<template #transport><ComingSoonPlaceholder /></template>
|
||||
<template #statistics><ComingSoonPlaceholder /></template>
|
||||
<template #reports><ComingSoonPlaceholder /></template>
|
||||
<template #exchanges><ComingSoonPlaceholder /></template>
|
||||
<!-- ERP-193 : les onglets « a venir » (Transport / Statistiques /
|
||||
Rapports / Echanges) ne sont plus rendus en consultation
|
||||
(masquage des onglets vides) — slots supprimes. -->
|
||||
</MalioTabList>
|
||||
</template>
|
||||
|
||||
@@ -278,13 +277,14 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useClient } from '~/modules/commercial/composables/useClient'
|
||||
import { buildClientFormTabKeys, isRibRequiredForPaymentType } from '~/modules/commercial/utils/forms/clientFormRules'
|
||||
import { isRibRequiredForPaymentType } from '~/modules/commercial/utils/forms/clientFormRules'
|
||||
import { readHistoryTab } from '~/shared/utils/historyTab'
|
||||
import {
|
||||
canEditClient,
|
||||
categoryOptionsOf,
|
||||
clientConsultationVisibleTabs,
|
||||
contactOptionsOf,
|
||||
mapAccountingDraft,
|
||||
mapAddressView,
|
||||
@@ -412,9 +412,11 @@ const paymentTypeOptions = computed(() => referentialOptionOf(client.value?.paym
|
||||
const bankOptions = computed(() => referentialOptionOf(client.value?.bank))
|
||||
|
||||
// ── Onglets : navigation LIBRE (pas de sequence forcee en consultation) ────
|
||||
// 4 onglets actifs (Information, Contact, Adresse, + Comptabilite si droit) et
|
||||
// 4 coquilles (Transport, Statistiques, Rapports, Echanges).
|
||||
const tabKeys = computed(() => buildClientFormTabKeys(canAccountingView.value, { includeEditOnlyTabs: true }))
|
||||
// ERP-193 (retour metier) : on masque les coquilles non implementees ET tout
|
||||
// onglet de donnees vide. La liste depend donc du payload charge.
|
||||
const visibleTabKeys = computed(() => clientConsultationVisibleTabs(client.value, {
|
||||
canAccountingView: canAccountingView.value,
|
||||
}))
|
||||
|
||||
const TAB_ICONS: Record<string, string> = {
|
||||
information: 'mdi:account-outline',
|
||||
@@ -427,14 +429,26 @@ const TAB_ICONS: Record<string, string> = {
|
||||
exchanges: 'mdi:account-group-outline',
|
||||
}
|
||||
|
||||
const tabs = computed(() => tabKeys.value.map(key => ({
|
||||
const tabs = computed(() => visibleTabKeys.value.map(key => ({
|
||||
key,
|
||||
label: t(`commercial.clients.tab.${key}`),
|
||||
icon: TAB_ICONS[key],
|
||||
})))
|
||||
|
||||
// Onglet initial : repris de l'edition au retour (history.state), sinon Information.
|
||||
const activeTab = ref(readHistoryTab(tabKeys.value) ?? 'information')
|
||||
// Onglet initial : vide tant que le client n'est pas charge. Des que la liste
|
||||
// des onglets visibles est connue, on cale sur l'onglet repris de l'edition
|
||||
// (history.state) s'il est encore visible, sinon le premier onglet visible.
|
||||
// Un watcher recale aussi si l'onglet courant disparait (ex: changement de droit).
|
||||
const activeTab = ref('')
|
||||
watch(visibleTabKeys, (keys) => {
|
||||
if (keys.length === 0) {
|
||||
activeTab.value = ''
|
||||
return
|
||||
}
|
||||
if (!keys.includes(activeTab.value)) {
|
||||
activeTab.value = readHistoryTab(keys) ?? keys[0]
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
// ── Navigation ─────────────────────────────────────────────────────────────
|
||||
function goBack(): void {
|
||||
|
||||
@@ -18,10 +18,11 @@
|
||||
automatiquement sur l'onglet Information. -->
|
||||
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText
|
||||
v-model="main.companyName"
|
||||
:model-value="main.companyName"
|
||||
@update:model-value="(v: string) => main.companyName = sanitizeFreeText(v)"
|
||||
:label="t('commercial.clients.form.main.companyName')"
|
||||
:required="true"
|
||||
:readonly="mainLocked"
|
||||
:disabled="mainLocked"
|
||||
:error="mainErrors.errors.companyName"
|
||||
/>
|
||||
<MalioSelectCheckbox
|
||||
@@ -29,7 +30,7 @@
|
||||
:options="referentials.categories.value"
|
||||
:label="t('commercial.clients.form.main.categories')"
|
||||
:display-tag="true"
|
||||
:readonly="mainLocked"
|
||||
:disabled="mainLocked"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.categories"
|
||||
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
|
||||
@@ -40,7 +41,7 @@
|
||||
:options="relationOptions"
|
||||
:label="t('commercial.clients.form.main.relation')"
|
||||
:empty-option-label="t('commercial.clients.form.main.relationNone')"
|
||||
:readonly="mainLocked"
|
||||
:disabled="mainLocked"
|
||||
@update:model-value="onRelationChange"
|
||||
/>
|
||||
<MalioSelect
|
||||
@@ -48,7 +49,7 @@
|
||||
:model-value="main.brokerIri"
|
||||
:options="referentials.brokers.value"
|
||||
:label="t('commercial.clients.form.main.brokerName')"
|
||||
:readonly="mainLocked"
|
||||
:disabled="mainLocked"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.broker"
|
||||
@update:model-value="(v: string | number | null) => main.brokerIri = v === null ? null : String(v)"
|
||||
@@ -58,7 +59,7 @@
|
||||
:model-value="main.distributorIri"
|
||||
:options="referentials.distributors.value"
|
||||
:label="t('commercial.clients.form.main.distributorName')"
|
||||
:readonly="mainLocked"
|
||||
:disabled="mainLocked"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.distributor"
|
||||
@update:model-value="(v: string | number | null) => main.distributorIri = v === null ? null : String(v)"
|
||||
@@ -68,7 +69,7 @@
|
||||
v-model="main.triageService"
|
||||
:label="t('commercial.clients.form.main.triageService')"
|
||||
group-class="self-center"
|
||||
:readonly="mainLocked"
|
||||
:disabled="mainLocked"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -96,20 +97,24 @@
|
||||
resize="none"
|
||||
group-class="row-span-2 pt-1 pb-1"
|
||||
text-input="h-full text-lg"
|
||||
:readonly="isValidated('information')"
|
||||
:disabled="isValidated('information')"
|
||||
:error="informationErrors.errors.description"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.competitors"
|
||||
:model-value="information.competitors"
|
||||
@update:model-value="(v: string) => information.competitors = sanitizeFreeText(v)"
|
||||
:label="t('commercial.clients.form.information.competitors')"
|
||||
:readonly="isValidated('information')"
|
||||
:disabled="isValidated('information')"
|
||||
:error="informationErrors.errors.competitors"
|
||||
/>
|
||||
<!-- Date de creation jamais dans le futur (ERP-193) : :max plafonne
|
||||
le calendrier a aujourd'hui et invalide une saisie future. -->
|
||||
<MalioDate
|
||||
v-model="information.foundedAt"
|
||||
:label="t('commercial.clients.form.information.foundedAt')"
|
||||
:readonly="isValidated('information')"
|
||||
:disabled="isValidated('information')"
|
||||
:editable="true"
|
||||
:max="maxFoundedAt"
|
||||
:error="informationErrors.errors.foundedAt"
|
||||
@update:raw-value="(v: string) => information.foundedAtRaw = v"
|
||||
/>
|
||||
@@ -117,25 +122,30 @@
|
||||
v-model="information.employeesCount"
|
||||
:label="t('commercial.clients.form.information.employeesCount')"
|
||||
:mask="EMPLOYEES_MASK"
|
||||
:readonly="isValidated('information')"
|
||||
:disabled="isValidated('information')"
|
||||
:error="informationErrors.errors.employeesCount"
|
||||
/>
|
||||
<!-- CA plafonne a 999 999 999 999,99 (ERP-193) : clamp a la saisie,
|
||||
:key force le re-affichage quand on plafonne (modelValue inchange). -->
|
||||
<MalioInputAmount
|
||||
v-model="information.revenueAmount"
|
||||
:key="revenueAmountKey"
|
||||
:model-value="information.revenueAmount"
|
||||
:label="t('commercial.clients.form.information.revenueAmount')"
|
||||
:readonly="isValidated('information')"
|
||||
:disabled="isValidated('information')"
|
||||
:error="informationErrors.errors.revenueAmount"
|
||||
@update:model-value="onRevenueAmountInput"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.directorName"
|
||||
:model-value="information.directorName"
|
||||
@update:model-value="(v: string) => information.directorName = sanitizePersonName(v)"
|
||||
:label="t('commercial.clients.form.information.directorName')"
|
||||
:readonly="isValidated('information')"
|
||||
:disabled="isValidated('information')"
|
||||
:error="informationErrors.errors.directorName"
|
||||
/>
|
||||
<MalioInputAmount
|
||||
v-model="information.profitAmount"
|
||||
:label="t('commercial.clients.form.information.profitAmount')"
|
||||
:readonly="isValidated('information')"
|
||||
:disabled="isValidated('information')"
|
||||
:error="informationErrors.errors.profitAmount"
|
||||
/>
|
||||
</div>
|
||||
@@ -166,7 +176,7 @@
|
||||
:model-value="contact"
|
||||
:title="t('commercial.clients.form.contact.title', { n: index + 1 })"
|
||||
:removable="isRowRemovable(contacts, index)"
|
||||
:readonly="isValidated('contact')"
|
||||
:disabled="isValidated('contact')"
|
||||
:errors="contactErrors[index]"
|
||||
@update:model-value="(v) => contacts[index] = v"
|
||||
@remove="askRemoveContact(index)"
|
||||
@@ -203,7 +213,7 @@
|
||||
:contact-options="contactOptions"
|
||||
:country-options="countryOptions"
|
||||
:removable="isRowRemovable(addresses, index)"
|
||||
:readonly="isValidated('address')"
|
||||
:disabled="isValidated('address')"
|
||||
:errors="addressErrors[index]"
|
||||
@update:model-value="(v) => addresses[index] = v"
|
||||
@remove="askRemoveAddress(index)"
|
||||
@@ -237,14 +247,15 @@
|
||||
v-model="accounting.siren"
|
||||
:label="t('commercial.clients.form.accounting.siren')"
|
||||
:mask="SIREN_MASK"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.siren"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="accounting.accountNumber"
|
||||
:model-value="accounting.accountNumber"
|
||||
@update:model-value="(v: string) => accounting.accountNumber = sanitizeCodeAlnum(v)"
|
||||
:label="t('commercial.clients.form.accounting.accountNumber')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.accountNumber"
|
||||
/>
|
||||
@@ -252,16 +263,17 @@
|
||||
:model-value="accounting.tvaModeIri"
|
||||
:options="referentials.tvaModes.value"
|
||||
:label="t('commercial.clients.form.accounting.tvaMode')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.tvaMode"
|
||||
@update:model-value="(v: string | number | null) => accounting.tvaModeIri = v === null ? null : String(v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="accounting.nTva"
|
||||
:model-value="accounting.nTva"
|
||||
@update:model-value="(v: string) => accounting.nTva = sanitizeCodeAlnum(v)"
|
||||
:label="t('commercial.clients.form.accounting.nTva')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.nTva"
|
||||
/>
|
||||
@@ -269,7 +281,7 @@
|
||||
:model-value="accounting.paymentDelayIri"
|
||||
:options="referentials.paymentDelays.value"
|
||||
:label="t('commercial.clients.form.accounting.paymentDelay')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.paymentDelay"
|
||||
@@ -279,7 +291,7 @@
|
||||
:model-value="accounting.paymentTypeIri"
|
||||
:options="referentials.paymentTypes.value"
|
||||
:label="t('commercial.clients.form.accounting.paymentType')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.paymentType"
|
||||
@@ -290,7 +302,7 @@
|
||||
:model-value="accounting.bankIri"
|
||||
:options="referentials.banks.value"
|
||||
:label="t('commercial.clients.form.accounting.bank')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.bank"
|
||||
@@ -318,21 +330,23 @@
|
||||
<MalioInputText
|
||||
v-model="rib.label"
|
||||
:label="t('commercial.clients.form.accounting.ribLabel')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.label"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="rib.bic"
|
||||
:model-value="rib.bic"
|
||||
@update:model-value="(v: string) => rib.bic = sanitizeCodeAlnum(v)"
|
||||
:label="t('commercial.clients.form.accounting.ribBic')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.bic"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="rib.iban"
|
||||
:model-value="rib.iban"
|
||||
@update:model-value="(v: string) => rib.iban = sanitizeCodeAlnum(v)"
|
||||
:label="t('commercial.clients.form.accounting.ribIban')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.iban"
|
||||
/>
|
||||
@@ -407,6 +421,9 @@ import {
|
||||
lastFillableTabKey,
|
||||
showsRelationAndTriageFields,
|
||||
} from '~/modules/commercial/utils/forms/clientFormRules'
|
||||
import { clampRevenueAmount } from '~/modules/commercial/utils/forms/amountInput'
|
||||
import { todayIso } from '~/shared/utils/date'
|
||||
import { sanitizeCodeAlnum, sanitizeFreeText, sanitizePersonName } from '~/shared/utils/textSanitize'
|
||||
import {
|
||||
buildAddressPayload,
|
||||
buildMainPayload,
|
||||
@@ -665,6 +682,22 @@ const information = reactive({
|
||||
directorName: null as string | null,
|
||||
})
|
||||
|
||||
// Borne haute de la date de creation : aujourd'hui (ERP-193, pas de date future).
|
||||
const maxFoundedAt = todayIso()
|
||||
|
||||
// CA plafonne a 999 999 999 999,99 (ERP-193). La :key force le re-affichage du
|
||||
// champ controle quand le plafonnement laisse le modelValue inchange.
|
||||
const revenueAmountKey = ref(0)
|
||||
|
||||
/** Saisie du CA : plafonne au maximum metier et re-synchronise le champ si plafonne. */
|
||||
function onRevenueAmountInput(value: string | null): void {
|
||||
const clamped = clampRevenueAmount(value)
|
||||
information.revenueAmount = clamped ?? null
|
||||
if (clamped !== value) {
|
||||
revenueAmountKey.value += 1
|
||||
}
|
||||
}
|
||||
|
||||
/** PATCH /clients/{id} — mode strict : uniquement les champs du groupe information. */
|
||||
async function submitInformation(): Promise<void> {
|
||||
if (clientId.value === null || tabSubmitting.value) return
|
||||
|
||||
@@ -23,18 +23,19 @@
|
||||
roles sans `manage` (ex. Compta). Pas de contact inline (ERP-106). -->
|
||||
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText
|
||||
v-model="main.companyName"
|
||||
:model-value="main.companyName"
|
||||
:label="t('commercial.suppliers.form.main.companyName')"
|
||||
:required="true"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:error="mainErrors.errors.companyName"
|
||||
@update:model-value="(v: string) => main.companyName = sanitizeFreeText(v)"
|
||||
/>
|
||||
<MalioSelectCheckbox
|
||||
:model-value="main.categoryIris"
|
||||
:options="mainCategoryOptions"
|
||||
:label="t('commercial.suppliers.form.main.categories')"
|
||||
:display-tag="true"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.categories"
|
||||
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
|
||||
@@ -62,20 +63,24 @@
|
||||
resize="none"
|
||||
group-class="row-span-2 pt-1 pb-1"
|
||||
text-input="h-full text-lg"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:error="informationErrors.errors.description"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.competitors"
|
||||
:model-value="information.competitors"
|
||||
:label="t('commercial.suppliers.form.information.competitors')"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:error="informationErrors.errors.competitors"
|
||||
@update:model-value="(v: string) => information.competitors = sanitizeFreeText(v)"
|
||||
/>
|
||||
<!-- Date de creation jamais dans le futur (ERP-193) : :max plafonne
|
||||
le calendrier a aujourd'hui et invalide une saisie future. -->
|
||||
<MalioDate
|
||||
v-model="information.foundedAt"
|
||||
:label="t('commercial.suppliers.form.information.foundedAt')"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:editable="true"
|
||||
:max="maxFoundedAt"
|
||||
:error="informationErrors.errors.foundedAt"
|
||||
@update:raw-value="(v: string) => information.foundedAtRaw = v"
|
||||
/>
|
||||
@@ -83,25 +88,30 @@
|
||||
v-model="information.employeesCount"
|
||||
:label="t('commercial.suppliers.form.information.employeesCount')"
|
||||
:mask="EMPLOYEES_MASK"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:error="informationErrors.errors.employeesCount"
|
||||
/>
|
||||
<!-- CA plafonne a 999 999 999 999,99 (ERP-193) : clamp a la saisie,
|
||||
:key force le re-affichage quand on plafonne (modelValue inchange). -->
|
||||
<MalioInputAmount
|
||||
v-model="information.revenueAmount"
|
||||
:key="revenueAmountKey"
|
||||
:model-value="information.revenueAmount"
|
||||
:label="t('commercial.suppliers.form.information.revenueAmount')"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:error="informationErrors.errors.revenueAmount"
|
||||
@update:model-value="onRevenueAmountInput"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.directorName"
|
||||
:model-value="information.directorName"
|
||||
:label="t('commercial.suppliers.form.information.directorName')"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:error="informationErrors.errors.directorName"
|
||||
@update:model-value="(v: string) => information.directorName = sanitizePersonName(v)"
|
||||
/>
|
||||
<MalioInputAmount
|
||||
v-model="information.profitAmount"
|
||||
:label="t('commercial.suppliers.form.information.profitAmount')"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:error="informationErrors.errors.profitAmount"
|
||||
/>
|
||||
<!-- Volume previsionnel : specifique fournisseur (entier). -->
|
||||
@@ -109,7 +119,7 @@
|
||||
v-model="information.volumeForecast"
|
||||
:label="t('commercial.suppliers.form.information.volumeForecast')"
|
||||
:mask="VOLUME_FORECAST_MASK"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:error="informationErrors.errors.volumeForecast"
|
||||
/>
|
||||
</div>
|
||||
@@ -136,7 +146,7 @@
|
||||
:model-value="contact"
|
||||
:title="t('commercial.suppliers.form.contact.title', { n: index + 1 })"
|
||||
:removable="isRowRemovable(contacts, index)"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:errors="contactErrors[index]"
|
||||
@update:model-value="(v) => contacts[index] = v"
|
||||
@remove="askRemoveContact(index)"
|
||||
@@ -173,7 +183,7 @@
|
||||
:contact-options="contactOptions"
|
||||
:country-options="countryOptions"
|
||||
:removable="isRowRemovable(addresses, index)"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:errors="addressErrors[index]"
|
||||
@update:model-value="(v) => addresses[index] = v"
|
||||
@remove="askRemoveAddress(index)"
|
||||
@@ -208,39 +218,41 @@
|
||||
v-model="accounting.siren"
|
||||
:label="t('commercial.suppliers.form.accounting.siren')"
|
||||
:mask="SIREN_MASK"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.siren"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="accounting.accountNumber"
|
||||
:model-value="accounting.accountNumber"
|
||||
:label="t('commercial.suppliers.form.accounting.accountNumber')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.accountNumber"
|
||||
@update:model-value="(v: string) => accounting.accountNumber = sanitizeCodeAlnum(v)"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.tvaModeIri"
|
||||
:options="tvaModeOptions"
|
||||
:label="t('commercial.suppliers.form.accounting.tvaMode')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.tvaMode"
|
||||
@update:model-value="(v: string | number | null) => accounting.tvaModeIri = v === null ? null : String(v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="accounting.nTva"
|
||||
:model-value="accounting.nTva"
|
||||
:label="t('commercial.suppliers.form.accounting.nTva')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.nTva"
|
||||
@update:model-value="(v: string) => accounting.nTva = sanitizeCodeAlnum(v)"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.paymentDelayIri"
|
||||
:options="paymentDelayOptions"
|
||||
:label="t('commercial.suppliers.form.accounting.paymentDelay')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.paymentDelay"
|
||||
@@ -250,7 +262,7 @@
|
||||
:model-value="accounting.paymentTypeIri"
|
||||
:options="paymentTypeOptions"
|
||||
:label="t('commercial.suppliers.form.accounting.paymentType')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.paymentType"
|
||||
@@ -261,7 +273,7 @@
|
||||
:model-value="accounting.bankIri"
|
||||
:options="bankOptions"
|
||||
:label="t('commercial.suppliers.form.accounting.bank')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.bank"
|
||||
@@ -288,23 +300,25 @@
|
||||
<MalioInputText
|
||||
v-model="rib.label"
|
||||
:label="t('commercial.suppliers.form.accounting.ribLabel')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.label"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="rib.bic"
|
||||
:model-value="rib.bic"
|
||||
:label="t('commercial.suppliers.form.accounting.ribBic')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.bic"
|
||||
@update:model-value="(v: string) => rib.bic = sanitizeCodeAlnum(v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="rib.iban"
|
||||
:model-value="rib.iban"
|
||||
:label="t('commercial.suppliers.form.accounting.ribIban')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.iban"
|
||||
@update:model-value="(v: string) => rib.iban = sanitizeCodeAlnum(v)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -392,6 +406,8 @@ import {
|
||||
type MainFormDraft,
|
||||
type SupplierEditAbilities,
|
||||
} from '~/modules/commercial/utils/forms/supplierEdit'
|
||||
import { clampRevenueAmount } from '~/modules/commercial/utils/forms/amountInput'
|
||||
import { todayIso } from '~/shared/utils/date'
|
||||
import {
|
||||
buildSupplierFormTabKeys,
|
||||
isAddressValid,
|
||||
@@ -412,6 +428,7 @@ import {
|
||||
} from '~/modules/commercial/types/supplierForm'
|
||||
import { extractApiErrorMessage } from '~/shared/utils/api'
|
||||
import { isRowRemovable, removeCollectionRow } from '~/shared/utils/collectionRow'
|
||||
import { sanitizeCodeAlnum, sanitizeFreeText, sanitizePersonName } from '~/shared/utils/textSanitize'
|
||||
import { readHistoryTab } from '~/shared/utils/historyTab'
|
||||
|
||||
// Masques de saisie (la normalisation finale reste serveur).
|
||||
@@ -457,6 +474,22 @@ const headerTitle = computed(() => supplier.value?.companyName ?? t('commercial.
|
||||
const main = reactive<MainFormDraft>(mapMainDraft({} as SupplierDetail))
|
||||
const information = reactive<InformationFormDraft>(mapInformationDraft({} as SupplierDetail))
|
||||
const accounting = reactive<AccountingFormDraft>(mapAccountingFormDraft({} as SupplierDetail))
|
||||
|
||||
// Borne haute de la date de creation : aujourd'hui (ERP-193, pas de date future).
|
||||
const maxFoundedAt = todayIso()
|
||||
|
||||
// CA plafonne a 999 999 999 999,99 (ERP-193). La :key force le re-affichage du
|
||||
// champ controle quand le plafonnement laisse le modelValue inchange.
|
||||
const revenueAmountKey = ref(0)
|
||||
|
||||
/** Saisie du CA : plafonne au maximum metier et re-synchronise le champ si plafonne. */
|
||||
function onRevenueAmountInput(value: string | null): void {
|
||||
const clamped = clampRevenueAmount(value)
|
||||
information.revenueAmount = clamped ?? null
|
||||
if (clamped !== value) {
|
||||
revenueAmountKey.value += 1
|
||||
}
|
||||
}
|
||||
const contacts = ref<SupplierContactFormDraft[]>([])
|
||||
const addresses = ref<SupplierAddressFormDraft[]>([])
|
||||
const ribs = ref<SupplierRibFormDraft[]>([])
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
/>
|
||||
<MalioButton
|
||||
v-if="showArchive"
|
||||
variant="secondary"
|
||||
variant="danger"
|
||||
icon-name="mdi:archive-arrow-down-outline"
|
||||
icon-position="left"
|
||||
:label="t('commercial.suppliers.action.archive')"
|
||||
@@ -50,14 +50,14 @@
|
||||
<MalioInputText
|
||||
:model-value="supplier.companyName"
|
||||
:label="t('commercial.suppliers.form.main.companyName')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioSelectCheckbox
|
||||
:model-value="categoryIris"
|
||||
:options="mainCategoryOptions"
|
||||
:label="t('commercial.suppliers.form.main.categories')"
|
||||
:display-tag="true"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -74,43 +74,43 @@
|
||||
resize="none"
|
||||
group-class="row-span-2 pt-1 pb-1"
|
||||
text-input="h-full text-lg"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="information.competitors"
|
||||
:label="t('commercial.suppliers.form.information.competitors')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioDate
|
||||
:model-value="information.foundedAt"
|
||||
:label="t('commercial.suppliers.form.information.foundedAt')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="information.employeesCount"
|
||||
:label="t('commercial.suppliers.form.information.employeesCount')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputAmount
|
||||
:model-value="information.revenueAmount"
|
||||
:label="t('commercial.suppliers.form.information.revenueAmount')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="information.directorName"
|
||||
:label="t('commercial.suppliers.form.information.directorName')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputAmount
|
||||
:model-value="information.profitAmount"
|
||||
:label="t('commercial.suppliers.form.information.profitAmount')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<!-- Volume previsionnel : specifique fournisseur (entier). -->
|
||||
<MalioInputText
|
||||
:model-value="information.volumeForecast"
|
||||
:label="t('commercial.suppliers.form.information.volumeForecast')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -123,7 +123,7 @@
|
||||
:key="contact.id ?? index"
|
||||
:model-value="contact"
|
||||
:title="t('commercial.suppliers.form.contact.title', { n: index + 1 })"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -140,7 +140,7 @@
|
||||
:site-options="allSiteOptions"
|
||||
:contact-options="contactOptions"
|
||||
:country-options="countryOptions"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -154,38 +154,38 @@
|
||||
:model-value="accounting.siren"
|
||||
:label="t('commercial.suppliers.form.accounting.siren')"
|
||||
:mask="SIREN_MASK"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="accounting.accountNumber"
|
||||
:label="t('commercial.suppliers.form.accounting.accountNumber')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.tvaModeIri"
|
||||
:options="tvaModeOptions"
|
||||
:label="t('commercial.suppliers.form.accounting.tvaMode')"
|
||||
empty-option-label=""
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="accounting.nTva"
|
||||
:label="t('commercial.suppliers.form.accounting.nTva')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.paymentDelayIri"
|
||||
:options="paymentDelayOptions"
|
||||
:label="t('commercial.suppliers.form.accounting.paymentDelay')"
|
||||
empty-option-label=""
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.paymentTypeIri"
|
||||
:options="paymentTypeOptions"
|
||||
:label="t('commercial.suppliers.form.accounting.paymentType')"
|
||||
empty-option-label=""
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioSelect
|
||||
v-if="accounting.bankIri"
|
||||
@@ -193,7 +193,7 @@
|
||||
:options="bankOptions"
|
||||
:label="t('commercial.suppliers.form.accounting.bank')"
|
||||
empty-option-label=""
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -208,28 +208,25 @@
|
||||
<MalioInputText
|
||||
:model-value="rib.label"
|
||||
:label="t('commercial.suppliers.form.accounting.ribLabel')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="rib.bic"
|
||||
:label="t('commercial.suppliers.form.accounting.ribBic')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="rib.iban"
|
||||
:label="t('commercial.suppliers.form.accounting.ribIban')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Onglets non encore implementes : frame vide (navigation libre). -->
|
||||
<template #transport><ComingSoonPlaceholder /></template>
|
||||
<template #statistics><ComingSoonPlaceholder /></template>
|
||||
<template #reports><ComingSoonPlaceholder /></template>
|
||||
<template #exchanges><ComingSoonPlaceholder /></template>
|
||||
<!-- ERP-193 : les onglets « a venir » (Transport / Statistiques /
|
||||
Rapports / Echanges) ne sont plus rendus en consultation
|
||||
(masquage des onglets vides) — slots supprimes. -->
|
||||
</MalioTabList>
|
||||
</template>
|
||||
|
||||
@@ -261,9 +258,9 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useSupplier } from '~/modules/commercial/composables/useSupplier'
|
||||
import { buildSupplierFormTabKeys, isRibRequiredForPaymentType } from '~/modules/commercial/utils/forms/supplierFormRules'
|
||||
import { isRibRequiredForPaymentType } from '~/modules/commercial/utils/forms/supplierFormRules'
|
||||
import { readHistoryTab } from '~/shared/utils/historyTab'
|
||||
import {
|
||||
canEditSupplier,
|
||||
@@ -278,6 +275,7 @@ import {
|
||||
referentialOptionOf,
|
||||
showArchiveAction,
|
||||
showRestoreAction,
|
||||
supplierConsultationVisibleTabs,
|
||||
type SelectOption,
|
||||
type SupplierDetail,
|
||||
} from '~/modules/commercial/utils/forms/supplierConsultation'
|
||||
@@ -387,9 +385,11 @@ const paymentTypeOptions = computed(() => referentialOptionOf(supplier.value?.pa
|
||||
const bankOptions = computed(() => referentialOptionOf(supplier.value?.bank))
|
||||
|
||||
// ── Onglets : navigation LIBRE (pas de sequence forcee en consultation) ────
|
||||
// 3 onglets actifs (Information, Contacts, Adresses, + Comptabilite si droit) et
|
||||
// 4 coquilles (Transport, Statistiques, Rapports, Echanges).
|
||||
const tabKeys = computed(() => buildSupplierFormTabKeys(canAccountingView.value, { includeEditOnlyTabs: true }))
|
||||
// ERP-193 (retour metier) : on masque les coquilles non implementees ET tout
|
||||
// onglet de donnees vide. La liste depend donc du payload charge.
|
||||
const visibleTabKeys = computed(() => supplierConsultationVisibleTabs(supplier.value, {
|
||||
canAccountingView: canAccountingView.value,
|
||||
}))
|
||||
|
||||
const TAB_ICONS: Record<string, string> = {
|
||||
information: 'mdi:account-outline',
|
||||
@@ -402,14 +402,25 @@ const TAB_ICONS: Record<string, string> = {
|
||||
exchanges: 'mdi:account-group-outline',
|
||||
}
|
||||
|
||||
const tabs = computed(() => tabKeys.value.map(key => ({
|
||||
const tabs = computed(() => visibleTabKeys.value.map(key => ({
|
||||
key,
|
||||
label: t(`commercial.suppliers.tab.${key}`),
|
||||
icon: TAB_ICONS[key],
|
||||
})))
|
||||
|
||||
// Onglet initial : repris de l'edition au retour (history.state), sinon Information.
|
||||
const activeTab = ref(readHistoryTab(tabKeys.value) ?? 'information')
|
||||
// Onglet initial : vide tant que le fournisseur n'est pas charge. Des que la
|
||||
// liste des onglets visibles est connue, on cale sur l'onglet repris de
|
||||
// l'edition (history.state) s'il est encore visible, sinon le premier visible.
|
||||
const activeTab = ref('')
|
||||
watch(visibleTabKeys, (keys) => {
|
||||
if (keys.length === 0) {
|
||||
activeTab.value = ''
|
||||
return
|
||||
}
|
||||
if (!keys.includes(activeTab.value)) {
|
||||
activeTab.value = readHistoryTab(keys) ?? keys[0]
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
// ── Navigation ─────────────────────────────────────────────────────────────
|
||||
function goBack(): void {
|
||||
|
||||
@@ -18,18 +18,19 @@
|
||||
automatiquement sur l'onglet Information. Pas de contact inline (ERP-106). -->
|
||||
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText
|
||||
v-model="main.companyName"
|
||||
:model-value="main.companyName"
|
||||
:label="t('commercial.suppliers.form.main.companyName')"
|
||||
:required="true"
|
||||
:readonly="mainLocked"
|
||||
:disabled="mainLocked"
|
||||
:error="mainErrors.errors.companyName"
|
||||
@update:model-value="(v: string) => main.companyName = sanitizeFreeText(v)"
|
||||
/>
|
||||
<MalioSelectCheckbox
|
||||
:model-value="main.categoryIris"
|
||||
:options="referentials.categories.value"
|
||||
:label="t('commercial.suppliers.form.main.categories')"
|
||||
:display-tag="true"
|
||||
:readonly="mainLocked"
|
||||
:disabled="mainLocked"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.categories"
|
||||
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
|
||||
@@ -56,20 +57,24 @@
|
||||
resize="none"
|
||||
group-class="row-span-2 pt-1 pb-1"
|
||||
text-input="h-full text-lg"
|
||||
:readonly="isValidated('information')"
|
||||
:disabled="isValidated('information')"
|
||||
:error="informationErrors.errors.description"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.competitors"
|
||||
:model-value="information.competitors"
|
||||
:label="t('commercial.suppliers.form.information.competitors')"
|
||||
:readonly="isValidated('information')"
|
||||
:disabled="isValidated('information')"
|
||||
:error="informationErrors.errors.competitors"
|
||||
@update:model-value="(v: string) => information.competitors = sanitizeFreeText(v)"
|
||||
/>
|
||||
<!-- Date de creation jamais dans le futur (ERP-193) : :max plafonne
|
||||
le calendrier a aujourd'hui et invalide une saisie future. -->
|
||||
<MalioDate
|
||||
v-model="information.foundedAt"
|
||||
:label="t('commercial.suppliers.form.information.foundedAt')"
|
||||
:readonly="isValidated('information')"
|
||||
:disabled="isValidated('information')"
|
||||
:editable="true"
|
||||
:max="maxFoundedAt"
|
||||
:error="informationErrors.errors.foundedAt"
|
||||
@update:raw-value="(v: string) => information.foundedAtRaw = v"
|
||||
/>
|
||||
@@ -77,25 +82,30 @@
|
||||
v-model="information.employeesCount"
|
||||
:label="t('commercial.suppliers.form.information.employeesCount')"
|
||||
:mask="EMPLOYEES_MASK"
|
||||
:readonly="isValidated('information')"
|
||||
:disabled="isValidated('information')"
|
||||
:error="informationErrors.errors.employeesCount"
|
||||
/>
|
||||
<!-- CA plafonne a 999 999 999 999,99 (ERP-193) : clamp a la saisie,
|
||||
:key force le re-affichage quand on plafonne (modelValue inchange). -->
|
||||
<MalioInputAmount
|
||||
v-model="information.revenueAmount"
|
||||
:key="revenueAmountKey"
|
||||
:model-value="information.revenueAmount"
|
||||
:label="t('commercial.suppliers.form.information.revenueAmount')"
|
||||
:readonly="isValidated('information')"
|
||||
:disabled="isValidated('information')"
|
||||
:error="informationErrors.errors.revenueAmount"
|
||||
@update:model-value="onRevenueAmountInput"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.directorName"
|
||||
:model-value="information.directorName"
|
||||
:label="t('commercial.suppliers.form.information.directorName')"
|
||||
:readonly="isValidated('information')"
|
||||
:disabled="isValidated('information')"
|
||||
:error="informationErrors.errors.directorName"
|
||||
@update:model-value="(v: string) => information.directorName = sanitizePersonName(v)"
|
||||
/>
|
||||
<MalioInputAmount
|
||||
v-model="information.profitAmount"
|
||||
:label="t('commercial.suppliers.form.information.profitAmount')"
|
||||
:readonly="isValidated('information')"
|
||||
:disabled="isValidated('information')"
|
||||
:error="informationErrors.errors.profitAmount"
|
||||
/>
|
||||
<!-- Volume previsionnel : specifique fournisseur. Champ texte
|
||||
@@ -104,7 +114,7 @@
|
||||
v-model="information.volumeForecast"
|
||||
:label="t('commercial.suppliers.form.information.volumeForecast')"
|
||||
:mask="VOLUME_FORECAST_MASK"
|
||||
:readonly="isValidated('information')"
|
||||
:disabled="isValidated('information')"
|
||||
:error="informationErrors.errors.volumeForecast"
|
||||
/>
|
||||
</div>
|
||||
@@ -131,7 +141,7 @@
|
||||
:model-value="contact"
|
||||
:title="t('commercial.suppliers.form.contact.title', { n: index + 1 })"
|
||||
:removable="isRowRemovable(contacts, index)"
|
||||
:readonly="isValidated('contacts')"
|
||||
:disabled="isValidated('contacts')"
|
||||
:errors="contactErrors[index]"
|
||||
@update:model-value="(v) => contacts[index] = v"
|
||||
@remove="askRemoveContact(index)"
|
||||
@@ -168,7 +178,7 @@
|
||||
:contact-options="contactOptions"
|
||||
:country-options="countryOptions"
|
||||
:removable="isRowRemovable(addresses, index)"
|
||||
:readonly="isValidated('addresses')"
|
||||
:disabled="isValidated('addresses')"
|
||||
:errors="addressErrors[index]"
|
||||
@update:model-value="(v) => addresses[index] = v"
|
||||
@remove="askRemoveAddress(index)"
|
||||
@@ -202,39 +212,41 @@
|
||||
v-model="accounting.siren"
|
||||
:label="t('commercial.suppliers.form.accounting.siren')"
|
||||
:mask="SIREN_MASK"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.siren"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="accounting.accountNumber"
|
||||
:model-value="accounting.accountNumber"
|
||||
:label="t('commercial.suppliers.form.accounting.accountNumber')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.accountNumber"
|
||||
@update:model-value="(v: string) => accounting.accountNumber = sanitizeCodeAlnum(v)"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.tvaModeIri"
|
||||
:options="referentials.tvaModes.value"
|
||||
:label="t('commercial.suppliers.form.accounting.tvaMode')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.tvaMode"
|
||||
@update:model-value="(v: string | number | null) => accounting.tvaModeIri = v === null ? null : String(v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="accounting.nTva"
|
||||
:model-value="accounting.nTva"
|
||||
:label="t('commercial.suppliers.form.accounting.nTva')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.nTva"
|
||||
@update:model-value="(v: string) => accounting.nTva = sanitizeCodeAlnum(v)"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.paymentDelayIri"
|
||||
:options="referentials.paymentDelays.value"
|
||||
:label="t('commercial.suppliers.form.accounting.paymentDelay')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.paymentDelay"
|
||||
@@ -244,7 +256,7 @@
|
||||
:model-value="accounting.paymentTypeIri"
|
||||
:options="referentials.paymentTypes.value"
|
||||
:label="t('commercial.suppliers.form.accounting.paymentType')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.paymentType"
|
||||
@@ -255,7 +267,7 @@
|
||||
:model-value="accounting.bankIri"
|
||||
:options="referentials.banks.value"
|
||||
:label="t('commercial.suppliers.form.accounting.bank')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.bank"
|
||||
@@ -282,23 +294,25 @@
|
||||
<MalioInputText
|
||||
v-model="rib.label"
|
||||
:label="t('commercial.suppliers.form.accounting.ribLabel')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.label"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="rib.bic"
|
||||
:model-value="rib.bic"
|
||||
:label="t('commercial.suppliers.form.accounting.ribBic')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.bic"
|
||||
@update:model-value="(v: string) => rib.bic = sanitizeCodeAlnum(v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="rib.iban"
|
||||
:model-value="rib.iban"
|
||||
:label="t('commercial.suppliers.form.accounting.ribIban')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.iban"
|
||||
@update:model-value="(v: string) => rib.iban = sanitizeCodeAlnum(v)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -375,6 +389,8 @@ import {
|
||||
buildMainPayload,
|
||||
buildRibPayload,
|
||||
} from '~/modules/commercial/utils/forms/supplierEdit'
|
||||
import { clampRevenueAmount } from '~/modules/commercial/utils/forms/amountInput'
|
||||
import { todayIso } from '~/shared/utils/date'
|
||||
import {
|
||||
emptyAddress,
|
||||
emptyContact,
|
||||
@@ -385,6 +401,7 @@ import {
|
||||
} from '~/modules/commercial/types/supplierForm'
|
||||
import { extractApiErrorMessage } from '~/shared/utils/api'
|
||||
import { isRowRemovable } from '~/shared/utils/collectionRow'
|
||||
import { sanitizeCodeAlnum, sanitizeFreeText, sanitizePersonName } from '~/shared/utils/textSanitize'
|
||||
|
||||
// Masques de saisie (la normalisation finale reste serveur).
|
||||
const SIREN_MASK = '#########'
|
||||
@@ -564,6 +581,22 @@ const information = reactive({
|
||||
volumeForecast: null as string | null,
|
||||
})
|
||||
|
||||
// Borne haute de la date de creation : aujourd'hui (ERP-193, pas de date future).
|
||||
const maxFoundedAt = todayIso()
|
||||
|
||||
// CA plafonne a 999 999 999 999,99 (ERP-193). La :key force le re-affichage du
|
||||
// champ controle quand le plafonnement laisse le modelValue inchange.
|
||||
const revenueAmountKey = ref(0)
|
||||
|
||||
/** Saisie du CA : plafonne au maximum metier et re-synchronise le champ si plafonne. */
|
||||
function onRevenueAmountInput(value: string | null): void {
|
||||
const clamped = clampRevenueAmount(value)
|
||||
information.revenueAmount = clamped ?? null
|
||||
if (clamped !== value) {
|
||||
revenueAmountKey.value += 1
|
||||
}
|
||||
}
|
||||
|
||||
/** PATCH /suppliers/{id} — mode strict : uniquement les champs du groupe information. */
|
||||
async function submitInformation(): Promise<void> {
|
||||
if (supplierId.value === null || tabSubmitting.value) return
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { clampRevenueAmount, REVENUE_AMOUNT_MAX } from '../amountInput'
|
||||
|
||||
describe('clampRevenueAmount', () => {
|
||||
it('laisse les valeurs vides / nulles telles quelles', () => {
|
||||
expect(clampRevenueAmount(null)).toBeNull()
|
||||
expect(clampRevenueAmount(undefined)).toBeUndefined()
|
||||
expect(clampRevenueAmount('')).toBe('')
|
||||
})
|
||||
|
||||
it('laisse une valeur sous le plafond inchangee', () => {
|
||||
expect(clampRevenueAmount('1000.50')).toBe('1000.50')
|
||||
expect(clampRevenueAmount('999999999999.99')).toBe('999999999999.99')
|
||||
})
|
||||
|
||||
it('plafonne une valeur au-dessus du maximum', () => {
|
||||
expect(clampRevenueAmount('1000000000000')).toBe('999999999999.99')
|
||||
expect(clampRevenueAmount('999999999999999.99')).toBe('999999999999.99')
|
||||
})
|
||||
|
||||
it('tolere une saisie a virgule / avec espaces (securite)', () => {
|
||||
expect(clampRevenueAmount('1 000 000 000 000,00')).toBe('999999999999.99')
|
||||
expect(clampRevenueAmount('12,5')).toBe('12,5')
|
||||
})
|
||||
|
||||
it('ne touche pas une saisie non numerique', () => {
|
||||
expect(clampRevenueAmount('abc')).toBe('abc')
|
||||
})
|
||||
|
||||
it('expose le plafond metier', () => {
|
||||
expect(REVENUE_AMOUNT_MAX).toBe(999_999_999_999.99)
|
||||
})
|
||||
})
|
||||
@@ -2,7 +2,10 @@ import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
canEditClient,
|
||||
categoryOptionsOf,
|
||||
clientConsultationVisibleTabs,
|
||||
contactOptionsOf,
|
||||
hasAccountingData,
|
||||
hasInformationData,
|
||||
iriOf,
|
||||
mapAccountingDraft,
|
||||
mapAddressToDraft,
|
||||
@@ -248,3 +251,73 @@ describe('paymentTypeCodeOf (ERP-121 : RIB masques hors-LCR en consultation)', (
|
||||
expect(paymentTypeCodeOf(undefined)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasInformationData', () => {
|
||||
it('faux si tous les champs Information sont vides/absents', () => {
|
||||
expect(hasInformationData({ '@id': '/api/clients/1', id: 1 })).toBe(false)
|
||||
expect(hasInformationData({ '@id': '/api/clients/1', id: 1, description: ' ' })).toBe(false)
|
||||
})
|
||||
|
||||
it('vrai des qu\'un champ Information porte une donnee', () => {
|
||||
expect(hasInformationData({ '@id': '/api/clients/1', id: 1, directorName: 'Dupont' })).toBe(true)
|
||||
expect(hasInformationData({ '@id': '/api/clients/1', id: 1, employeesCount: 0 })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasAccountingData', () => {
|
||||
it('faux sans champ comptable ni RIB', () => {
|
||||
expect(hasAccountingData({ '@id': '/api/clients/1', id: 1 })).toBe(false)
|
||||
})
|
||||
|
||||
it('vrai avec un champ comptable scalaire', () => {
|
||||
expect(hasAccountingData({ '@id': '/api/clients/1', id: 1, siren: '123456789' })).toBe(true)
|
||||
})
|
||||
|
||||
it('vrai avec une relation comptable embarquee (paymentType)', () => {
|
||||
expect(hasAccountingData({
|
||||
'@id': '/api/clients/1', id: 1,
|
||||
paymentType: { '@id': '/api/payment_types/1', code: 'LCR' },
|
||||
})).toBe(true)
|
||||
})
|
||||
|
||||
it('vrai avec au moins un RIB', () => {
|
||||
expect(hasAccountingData({
|
||||
'@id': '/api/clients/1', id: 1,
|
||||
ribs: [{ '@id': '/api/ribs/1', id: 1, iban: 'FR76...' }],
|
||||
})).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('clientConsultationVisibleTabs', () => {
|
||||
it('retourne [] tant que le client n\'est pas charge', () => {
|
||||
expect(clientConsultationVisibleTabs(null, { canAccountingView: true })).toEqual([])
|
||||
expect(clientConsultationVisibleTabs(undefined, { canAccountingView: true })).toEqual([])
|
||||
})
|
||||
|
||||
it('masque les coquilles et les onglets vides (client minimal)', () => {
|
||||
const client: ClientDetail = { '@id': '/api/clients/1', id: 1, companyName: 'ACME' }
|
||||
expect(clientConsultationVisibleTabs(client, { canAccountingView: true })).toEqual([])
|
||||
})
|
||||
|
||||
it('affiche les onglets non vides dans l\'ordre information/contact/address/accounting', () => {
|
||||
const client: ClientDetail = {
|
||||
'@id': '/api/clients/1', id: 1,
|
||||
directorName: 'Dupont',
|
||||
contacts: [{ '@id': '/api/client_contacts/1', id: 1 }],
|
||||
addresses: [{ '@id': '/api/client_addresses/1', id: 1 }],
|
||||
siren: '123456789',
|
||||
}
|
||||
expect(clientConsultationVisibleTabs(client, { canAccountingView: true }))
|
||||
.toEqual(['information', 'contact', 'address', 'accounting'])
|
||||
})
|
||||
|
||||
it('masque Comptabilite sans le droit accounting.view meme si des donnees existent', () => {
|
||||
const client: ClientDetail = {
|
||||
'@id': '/api/clients/1', id: 1,
|
||||
contacts: [{ '@id': '/api/client_contacts/1', id: 1 }],
|
||||
siren: '123456789',
|
||||
}
|
||||
expect(clientConsultationVisibleTabs(client, { canAccountingView: false }))
|
||||
.toEqual(['contact'])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
canEditSupplier,
|
||||
categoryOptionsOf,
|
||||
contactOptionsOf,
|
||||
hasAccountingData,
|
||||
hasInformationData,
|
||||
iriOf,
|
||||
mapAccountingDraft,
|
||||
mapAddressToDraft,
|
||||
@@ -14,6 +16,7 @@ import {
|
||||
showArchiveAction,
|
||||
showRestoreAction,
|
||||
siteOptionsOf,
|
||||
supplierConsultationVisibleTabs,
|
||||
type SupplierDetail,
|
||||
} from '../supplierConsultation'
|
||||
|
||||
@@ -237,3 +240,60 @@ describe('paymentTypeCodeOf (ERP-121 : RIB masques hors-LCR en consultation)', (
|
||||
expect(paymentTypeCodeOf(undefined)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasInformationData (fournisseur)', () => {
|
||||
it('faux si tous les champs Information (volume previsionnel inclus) sont vides', () => {
|
||||
expect(hasInformationData({ '@id': '/api/suppliers/1', id: 1 })).toBe(false)
|
||||
})
|
||||
|
||||
it('vrai des qu\'un champ Information porte une donnee', () => {
|
||||
expect(hasInformationData({ '@id': '/api/suppliers/1', id: 1, directorName: 'Martin' })).toBe(true)
|
||||
expect(hasInformationData({ '@id': '/api/suppliers/1', id: 1, volumeForecast: 1200 })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasAccountingData (fournisseur)', () => {
|
||||
it('faux sans champ comptable ni RIB', () => {
|
||||
expect(hasAccountingData({ '@id': '/api/suppliers/1', id: 1 })).toBe(false)
|
||||
})
|
||||
|
||||
it('vrai avec un champ comptable ou un RIB', () => {
|
||||
expect(hasAccountingData({ '@id': '/api/suppliers/1', id: 1, siren: '123456789' })).toBe(true)
|
||||
expect(hasAccountingData({
|
||||
'@id': '/api/suppliers/1', id: 1,
|
||||
ribs: [{ '@id': '/api/supplier_ribs/1', id: 1, iban: 'FR76...' }],
|
||||
})).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('supplierConsultationVisibleTabs', () => {
|
||||
it('retourne [] tant que le fournisseur n\'est pas charge', () => {
|
||||
expect(supplierConsultationVisibleTabs(null, { canAccountingView: true })).toEqual([])
|
||||
})
|
||||
|
||||
it('masque les coquilles et les onglets vides (fournisseur minimal)', () => {
|
||||
expect(supplierConsultationVisibleTabs(
|
||||
{ '@id': '/api/suppliers/1', id: 1, companyName: 'ACME' },
|
||||
{ canAccountingView: true },
|
||||
)).toEqual([])
|
||||
})
|
||||
|
||||
it('affiche information/contacts/addresses/accounting (cles plurielles) dans l\'ordre', () => {
|
||||
const supplier: SupplierDetail = {
|
||||
'@id': '/api/suppliers/1', id: 1,
|
||||
volumeForecast: 1000,
|
||||
contacts: [{ '@id': '/api/supplier_contacts/1', id: 1 }],
|
||||
addresses: [{ '@id': '/api/supplier_addresses/1', id: 1 }],
|
||||
siren: '123456789',
|
||||
}
|
||||
expect(supplierConsultationVisibleTabs(supplier, { canAccountingView: true }))
|
||||
.toEqual(['information', 'contacts', 'addresses', 'accounting'])
|
||||
})
|
||||
|
||||
it('masque Comptabilite sans le droit accounting.view', () => {
|
||||
expect(supplierConsultationVisibleTabs(
|
||||
{ '@id': '/api/suppliers/1', id: 1, siren: '123456789' },
|
||||
{ canAccountingView: false },
|
||||
)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Helpers de saisie des montants des formulaires Client / Fournisseur (commercial).
|
||||
* Purs / testables. Pendant FRONT de la contrainte back `LessThanOrEqual` posee sur
|
||||
* `revenueAmount` (Client/Supplier) — retour metier ERP-193 : le chiffre d'affaires
|
||||
* est plafonne a 999 999 999 999,99.
|
||||
*/
|
||||
|
||||
/** Plafond metier du chiffre d'affaires (CA) : 999 999 999 999,99. */
|
||||
export const REVENUE_AMOUNT_MAX = 999_999_999_999.99
|
||||
|
||||
/** Valeur « modele » (decimale a point, sans separateur) renvoyee quand on plafonne. */
|
||||
const REVENUE_AMOUNT_MAX_MODEL = '999999999999.99'
|
||||
|
||||
/**
|
||||
* Plafonne le CA au maximum metier. Recoit le modele emis par `MalioInputAmount`
|
||||
* (chaine propre a decimale `.`, sans espaces) ; tolere malgre tout une virgule /
|
||||
* des espaces par securite. Renvoie la valeur telle quelle si elle est vide, non
|
||||
* numerique ou sous le plafond ; sinon la valeur plafonnee.
|
||||
*/
|
||||
export function clampRevenueAmount(value: string | null | undefined): string | null | undefined {
|
||||
if (value === null || value === undefined || value === '') {
|
||||
return value
|
||||
}
|
||||
const n = Number(String(value).replace(/\s/g, '').replace(',', '.'))
|
||||
if (Number.isNaN(n)) {
|
||||
return value
|
||||
}
|
||||
return n > REVENUE_AMOUNT_MAX ? REVENUE_AMOUNT_MAX_MODEL : value
|
||||
}
|
||||
@@ -317,6 +317,77 @@ export function mapAddressView(address: AddressRead): AddressView {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si une valeur scalaire porte une donnee affichable (non null/undefined,
|
||||
* et non chaine vide apres trim). Sert aux predicats « onglet vide » ci-dessous.
|
||||
*/
|
||||
function hasValue(value: unknown): boolean {
|
||||
if (value === null || value === undefined) {
|
||||
return false
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
return value.trim() !== ''
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si l'onglet Information porte au moins une donnee. ERP-193 : en
|
||||
* consultation on masque les onglets vides ; Information n'echappe pas a la
|
||||
* regle malgre son statut d'onglet d'atterrissage par defaut.
|
||||
*/
|
||||
export function hasInformationData(client: ClientDetail): boolean {
|
||||
return [
|
||||
client.description,
|
||||
client.competitors,
|
||||
client.foundedAt,
|
||||
client.employeesCount,
|
||||
client.revenueAmount,
|
||||
client.profitAmount,
|
||||
client.directorName,
|
||||
].some(hasValue)
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si l'onglet Comptabilite porte au moins un champ comptable OU un RIB.
|
||||
* (Le gating permission `accounting.view` reste applique en amont par l'appelant.)
|
||||
*/
|
||||
export function hasAccountingData(client: ClientDetail): boolean {
|
||||
const draft = mapAccountingDraft(client)
|
||||
const hasField = Object.values(draft).some(hasValue)
|
||||
const hasRib = (client.ribs ?? []).length > 0
|
||||
return hasField || hasRib
|
||||
}
|
||||
|
||||
/**
|
||||
* Onglets visibles en consultation (ERP-193, retour metier) : on masque les
|
||||
* coquilles non implementees (Transport / Statistiques / Rapports / Echanges)
|
||||
* ET tout onglet de donnees vide. L'ordre reproduit `buildClientFormTabKeys`.
|
||||
* Retourne `[]` tant que le client n'est pas charge.
|
||||
*/
|
||||
export function clientConsultationVisibleTabs(
|
||||
client: ClientDetail | null | undefined,
|
||||
options: { canAccountingView: boolean },
|
||||
): string[] {
|
||||
if (!client) {
|
||||
return []
|
||||
}
|
||||
const visible: string[] = []
|
||||
if (hasInformationData(client)) {
|
||||
visible.push('information')
|
||||
}
|
||||
if ((client.contacts ?? []).length > 0) {
|
||||
visible.push('contact')
|
||||
}
|
||||
if ((client.addresses ?? []).length > 0) {
|
||||
visible.push('address')
|
||||
}
|
||||
if (options.canAccountingView && hasAccountingData(client)) {
|
||||
visible.push('accounting')
|
||||
}
|
||||
return visible
|
||||
}
|
||||
|
||||
/**
|
||||
* Bouton « Modifier » : visible si l'utilisateur peut editer au moins un onglet
|
||||
* — `manage` (formulaire/onglets metier) OU `accounting.manage` (le role Compta
|
||||
|
||||
@@ -292,6 +292,78 @@ export function mapAddressView(address: AddressRead): AddressView {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si une valeur scalaire porte une donnee affichable (non null/undefined,
|
||||
* et non chaine vide apres trim). Sert aux predicats « onglet vide » ci-dessous.
|
||||
*/
|
||||
function hasValue(value: unknown): boolean {
|
||||
if (value === null || value === undefined) {
|
||||
return false
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
return value.trim() !== ''
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si l'onglet Information porte au moins une donnee (volume previsionnel
|
||||
* inclus, specifique fournisseur). ERP-193 : en consultation on masque les
|
||||
* onglets vides, Information comprise.
|
||||
*/
|
||||
export function hasInformationData(supplier: SupplierDetail): boolean {
|
||||
return [
|
||||
supplier.description,
|
||||
supplier.competitors,
|
||||
supplier.foundedAt,
|
||||
supplier.employeesCount,
|
||||
supplier.revenueAmount,
|
||||
supplier.profitAmount,
|
||||
supplier.directorName,
|
||||
supplier.volumeForecast,
|
||||
].some(hasValue)
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si l'onglet Comptabilite porte au moins un champ comptable OU un RIB.
|
||||
* (Le gating permission `accounting.view` reste applique en amont par l'appelant.)
|
||||
*/
|
||||
export function hasAccountingData(supplier: SupplierDetail): boolean {
|
||||
const draft = mapAccountingDraft(supplier)
|
||||
const hasField = Object.values(draft).some(hasValue)
|
||||
const hasRib = (supplier.ribs ?? []).length > 0
|
||||
return hasField || hasRib
|
||||
}
|
||||
|
||||
/**
|
||||
* Onglets visibles en consultation (ERP-193, retour metier) : on masque les
|
||||
* coquilles non implementees (Transport / Statistiques / Rapports / Echanges)
|
||||
* ET tout onglet de donnees vide. L'ordre reproduit `buildSupplierFormTabKeys`.
|
||||
* Retourne `[]` tant que le fournisseur n'est pas charge.
|
||||
*/
|
||||
export function supplierConsultationVisibleTabs(
|
||||
supplier: SupplierDetail | null | undefined,
|
||||
options: { canAccountingView: boolean },
|
||||
): string[] {
|
||||
if (!supplier) {
|
||||
return []
|
||||
}
|
||||
const visible: string[] = []
|
||||
if (hasInformationData(supplier)) {
|
||||
visible.push('information')
|
||||
}
|
||||
if ((supplier.contacts ?? []).length > 0) {
|
||||
visible.push('contacts')
|
||||
}
|
||||
if ((supplier.addresses ?? []).length > 0) {
|
||||
visible.push('addresses')
|
||||
}
|
||||
if (options.canAccountingView && hasAccountingData(supplier)) {
|
||||
visible.push('accounting')
|
||||
}
|
||||
return visible
|
||||
}
|
||||
|
||||
/**
|
||||
* Bouton « Modifier » : visible si l'utilisateur peut editer au moins un onglet
|
||||
* — `manage` (formulaire/onglets metier) OU `accounting.manage` (le role Compta
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<div class="relative grid grid-cols-4 gap-x-[44px] gap-y-4 bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
|
||||
<!-- Suppression : modal de confirmation cote parent. -->
|
||||
<MalioButtonIcon
|
||||
v-if="removable && !readonly"
|
||||
v-if="removable && !readonly && !disabled"
|
||||
icon="mdi:delete-outline"
|
||||
variant="ghost"
|
||||
button-class="absolute top-3 right-3"
|
||||
@@ -17,6 +17,7 @@
|
||||
:label="t('technique.providers.form.address.sites')"
|
||||
:display-tag="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.sites"
|
||||
@update:model-value="(v: (string | number)[]) => update('siteIris', v.map(String))"
|
||||
@@ -29,6 +30,7 @@
|
||||
:label="t('technique.providers.form.address.categories')"
|
||||
:display-tag="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.categories"
|
||||
@update:model-value="(v: (string | number)[]) => update('categoryIris', v.map(String))"
|
||||
@@ -41,6 +43,7 @@
|
||||
:label="t('technique.providers.form.address.contacts')"
|
||||
:display-tag="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
@update:model-value="(v: (string | number)[]) => update('contactIris', v.map(String))"
|
||||
/>
|
||||
|
||||
@@ -49,6 +52,7 @@
|
||||
:options="countryOptions"
|
||||
:label="t('technique.providers.form.address.country')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
@update:model-value="(v: string | number | null) => update('country', String(v ?? 'France'))"
|
||||
/>
|
||||
@@ -58,6 +62,7 @@
|
||||
:label="t('technique.providers.form.address.postalCode')"
|
||||
:mask="POSTAL_CODE_MASK"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.postalCode"
|
||||
@update:model-value="onPostalCodeChange"
|
||||
@@ -70,6 +75,7 @@
|
||||
:options="cityOptions"
|
||||
:label="t('technique.providers.form.address.city')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="errors?.city"
|
||||
@@ -80,6 +86,7 @@
|
||||
:model-value="model.city"
|
||||
:label="t('technique.providers.form.address.city')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.city"
|
||||
@update:model-value="(v: string) => update('city', v)"
|
||||
@@ -89,13 +96,14 @@
|
||||
texte saisi est conserve si la BAN ne propose rien (saisie manuelle). -->
|
||||
<div class="col-span-2">
|
||||
<MalioInputAutocomplete
|
||||
v-if="!readonly"
|
||||
v-if="!readonly && !disabled"
|
||||
:model-value="model.street"
|
||||
:options="addressOptions"
|
||||
:loading="addressLoading"
|
||||
:min-search-length="3"
|
||||
:label="t('technique.providers.form.address.street')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.street"
|
||||
:allow-create="true"
|
||||
@@ -109,6 +117,7 @@
|
||||
:model-value="model.street"
|
||||
:label="t('technique.providers.form.address.street')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:required="true"
|
||||
:error="errors?.street"
|
||||
@update:model-value="(v: string) => update('street', v)"
|
||||
@@ -120,6 +129,7 @@
|
||||
:model-value="model.streetComplement"
|
||||
:label="t('technique.providers.form.address.streetComplement')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.streetComplement"
|
||||
@update:model-value="(v: string) => update('streetComplement', v)"
|
||||
/>
|
||||
@@ -131,6 +141,7 @@
|
||||
import { useAddressAutocomplete, type AddressSuggestion } from '~/shared/composables/useAddressAutocomplete'
|
||||
import type { RefOption } from '~/modules/technique/composables/useProviderReferentials'
|
||||
import type { ProviderAddressFormDraft } from '~/modules/technique/types/providerForm'
|
||||
import { sanitizeAddress } from '~/shared/utils/textSanitize'
|
||||
|
||||
// Masque code postal FR : 5 chiffres.
|
||||
const POSTAL_CODE_MASK = '#####'
|
||||
@@ -148,6 +159,8 @@ const props = defineProps<{
|
||||
countryOptions: RefOption[]
|
||||
removable?: boolean
|
||||
readonly?: boolean
|
||||
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
|
||||
disabled?: boolean
|
||||
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
@@ -193,9 +206,20 @@ 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). */
|
||||
// Filtres de saisie par champ (ERP-193) : voie / complement / ville = profil adresse.
|
||||
const FIELD_SANITIZERS: Partial<Record<keyof ProviderAddressFormDraft, (v: string) => string>> = {
|
||||
street: sanitizeAddress,
|
||||
streetComplement: sanitizeAddress,
|
||||
city: sanitizeAddress,
|
||||
}
|
||||
|
||||
/** Emet un nouveau brouillon avec le champ modifie (immutabilite), sanitise si besoin. */
|
||||
function update<K extends keyof ProviderAddressFormDraft>(field: K, value: ProviderAddressFormDraft[K]): void {
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: value })
|
||||
const sanitizer = FIELD_SANITIZERS[field]
|
||||
const next = (sanitizer && typeof value === 'string')
|
||||
? (sanitizer(value) as ProviderAddressFormDraft[K])
|
||||
: value
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: next })
|
||||
}
|
||||
|
||||
/** Previent le parent (toast unique) que l'autocompletion est indisponible. */
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<!-- Suppression : ouvre une modal de confirmation cote parent. Masquee si
|
||||
non supprimable (1er bloc) ou en lecture seule. -->
|
||||
<MalioButtonIcon
|
||||
v-if="removable && !readonly"
|
||||
v-if="removable && !readonly && !disabled"
|
||||
icon="mdi:delete-outline"
|
||||
variant="ghost"
|
||||
button-class="absolute top-3 right-3"
|
||||
@@ -15,6 +15,7 @@
|
||||
:model-value="model.lastName"
|
||||
:label="t('technique.providers.form.contact.lastName')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.lastName"
|
||||
@update:model-value="(v: string) => update('lastName', v)"
|
||||
/>
|
||||
@@ -22,6 +23,7 @@
|
||||
:model-value="model.firstName"
|
||||
:label="t('technique.providers.form.contact.firstName')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.firstName"
|
||||
@update:model-value="(v: string) => update('firstName', v)"
|
||||
/>
|
||||
@@ -33,6 +35,7 @@
|
||||
:model-value="model.jobTitle"
|
||||
:label="t('technique.providers.form.contact.jobTitle')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.jobTitle"
|
||||
@update:model-value="(v: string) => update('jobTitle', v)"
|
||||
/>
|
||||
@@ -41,6 +44,7 @@
|
||||
:model-value="model.email"
|
||||
:label="t('technique.providers.form.contact.email')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:lowercase="true"
|
||||
:error="errors?.email"
|
||||
@update:model-value="(v: string) => update('email', v)"
|
||||
@@ -50,6 +54,7 @@
|
||||
:label="t('technique.providers.form.contact.phonePrimary')"
|
||||
:mask="PHONE_MASK"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.phonePrimary"
|
||||
:addable="!model.hasSecondaryPhone && !readonly"
|
||||
:add-button-label="t('technique.providers.form.contact.addPhone')"
|
||||
@@ -63,6 +68,7 @@
|
||||
:label="t('technique.providers.form.contact.phoneSecondary')"
|
||||
:mask="PHONE_MASK"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.phoneSecondary"
|
||||
@update:model-value="(v: string) => update('phoneSecondary', v)"
|
||||
/>
|
||||
@@ -71,6 +77,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { ProviderContactFormDraft } from '~/modules/technique/types/providerForm'
|
||||
import { sanitizeEmail, sanitizeFreeText, sanitizePersonName } from '~/shared/utils/textSanitize'
|
||||
|
||||
// Masque telephone FR : 5 groupes de 2 chiffres (la normalisation finale reste serveur).
|
||||
const PHONE_MASK = '## ## ## ## ##'
|
||||
@@ -82,6 +89,8 @@ const props = defineProps<{
|
||||
removable?: boolean
|
||||
/** Bloc en lecture seule (onglet valide). */
|
||||
readonly?: boolean
|
||||
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
|
||||
disabled?: boolean
|
||||
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
@@ -96,9 +105,22 @@ const { t } = useI18n()
|
||||
// Alias local pour la lisibilite du template.
|
||||
const model = computed(() => props.modelValue)
|
||||
|
||||
/** Emet un nouveau brouillon avec le champ modifie (immutabilite). */
|
||||
// Filtres de saisie par champ (ERP-193) : on retire les caracteres parasites a la
|
||||
// frappe. Noms = profil personne, fonction = texte libre, email = profil email.
|
||||
const FIELD_SANITIZERS: Partial<Record<keyof ProviderContactFormDraft, (v: string) => string>> = {
|
||||
lastName: sanitizePersonName,
|
||||
firstName: sanitizePersonName,
|
||||
jobTitle: sanitizeFreeText,
|
||||
email: sanitizeEmail,
|
||||
}
|
||||
|
||||
/** Emet un nouveau brouillon avec le champ modifie (immutabilite), sanitise si besoin. */
|
||||
function update<K extends keyof ProviderContactFormDraft>(field: K, value: ProviderContactFormDraft[K]): void {
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: value })
|
||||
const sanitizer = FIELD_SANITIZERS[field]
|
||||
const next = (sanitizer && typeof value === 'string')
|
||||
? (sanitizer(value) as ProviderContactFormDraft[K])
|
||||
: value
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: next })
|
||||
}
|
||||
|
||||
/** Revele le 2e numero (max 1 secondaire, le « + » disparait). */
|
||||
|
||||
@@ -44,7 +44,7 @@ describe('useProvidersRepository', () => {
|
||||
expect(mockApiGet).toHaveBeenCalledTimes(1)
|
||||
const [url, query, opts] = mockApiGet.mock.calls[0]
|
||||
expect(url).toBe('/providers')
|
||||
expect(query).toMatchObject({ page: 1, itemsPerPage: 10 })
|
||||
expect(query).toMatchObject({ page: 1, itemsPerPage: 25 })
|
||||
expect(opts).toMatchObject({
|
||||
toast: false,
|
||||
headers: { Accept: 'application/ld+json' },
|
||||
|
||||
@@ -59,5 +59,6 @@ export interface Provider {
|
||||
* `usePaginatedList`. Aucun reset au logout a gerer.
|
||||
*/
|
||||
export function useProvidersRepository() {
|
||||
return usePaginatedList<Provider>({ url: '/providers' })
|
||||
// Pagination par defaut a 25 sur le repertoire (retour metier ERP-193).
|
||||
return usePaginatedList<Provider>({ url: '/providers', defaultItemsPerPage: 25 })
|
||||
}
|
||||
|
||||
@@ -20,18 +20,19 @@
|
||||
<!-- ── Bloc principal (pre-rempli, editable si `manage`) ──────────── -->
|
||||
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText
|
||||
v-model="main.companyName"
|
||||
:model-value="main.companyName"
|
||||
:label="t('technique.providers.form.main.companyName')"
|
||||
:required="true"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:error="mainErrors.errors.companyName"
|
||||
@update:model-value="(v: string) => main.companyName = sanitizeFreeText(v)"
|
||||
/>
|
||||
<MalioSelectCheckbox
|
||||
:model-value="main.categoryIris"
|
||||
:options="referentials.categories.value"
|
||||
:label="t('technique.providers.form.main.categories')"
|
||||
:display-tag="true"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.categories"
|
||||
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
|
||||
@@ -41,7 +42,7 @@
|
||||
:options="referentials.sites.value"
|
||||
:label="t('technique.providers.form.main.sites')"
|
||||
:display-tag="true"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.sites"
|
||||
@update:model-value="(v: (string | number)[]) => main.siteIris = v.map(String)"
|
||||
@@ -71,7 +72,7 @@
|
||||
:key="index"
|
||||
:model-value="contact"
|
||||
:removable="isRowRemovable(contacts, index)"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:errors="contactErrors[index]"
|
||||
@update:model-value="(v) => contacts[index] = v"
|
||||
@remove="askRemoveContact(index)"
|
||||
@@ -107,7 +108,7 @@
|
||||
:contact-options="contactOptions"
|
||||
:country-options="countryOptions"
|
||||
:removable="isRowRemovable(addresses, index)"
|
||||
:readonly="businessReadonly"
|
||||
:disabled="businessReadonly"
|
||||
:errors="addressErrors[index]"
|
||||
@update:model-value="(v) => addresses[index] = v"
|
||||
@remove="askRemoveAddress(index)"
|
||||
@@ -141,39 +142,41 @@
|
||||
v-model="accounting.siren"
|
||||
:label="t('technique.providers.form.accounting.siren')"
|
||||
:mask="SIREN_MASK"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.siren"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="accounting.accountNumber"
|
||||
:model-value="accounting.accountNumber"
|
||||
:label="t('technique.providers.form.accounting.accountNumber')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.accountNumber"
|
||||
@update:model-value="(v: string) => accounting.accountNumber = sanitizeCodeAlnum(v)"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.tvaModeIri"
|
||||
:options="referentials.tvaModes.value"
|
||||
:label="t('technique.providers.form.accounting.tvaMode')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.tvaMode"
|
||||
@update:model-value="(v: string | number | null) => accounting.tvaModeIri = v === null ? null : String(v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="accounting.nTva"
|
||||
:model-value="accounting.nTva"
|
||||
:label="t('technique.providers.form.accounting.nTva')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.nTva"
|
||||
@update:model-value="(v: string) => accounting.nTva = sanitizeCodeAlnum(v)"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.paymentDelayIri"
|
||||
:options="referentials.paymentDelays.value"
|
||||
:label="t('technique.providers.form.accounting.paymentDelay')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.paymentDelay"
|
||||
@@ -183,7 +186,7 @@
|
||||
:model-value="accounting.paymentTypeIri"
|
||||
:options="referentials.paymentTypes.value"
|
||||
:label="t('technique.providers.form.accounting.paymentType')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.paymentType"
|
||||
@@ -194,7 +197,7 @@
|
||||
:model-value="accounting.bankIri"
|
||||
:options="referentials.banks.value"
|
||||
:label="t('technique.providers.form.accounting.bank')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.bank"
|
||||
@@ -221,23 +224,25 @@
|
||||
<MalioInputText
|
||||
v-model="rib.label"
|
||||
:label="t('technique.providers.form.accounting.ribLabel')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="ribErrors[index]?.label"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="rib.bic"
|
||||
:model-value="rib.bic"
|
||||
:label="t('technique.providers.form.accounting.ribBic')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="ribErrors[index]?.bic"
|
||||
@update:model-value="(v: string) => rib.bic = sanitizeCodeAlnum(v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="rib.iban"
|
||||
:model-value="rib.iban"
|
||||
:label="t('technique.providers.form.accounting.ribIban')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="ribErrors[index]?.iban"
|
||||
@update:model-value="(v: string) => rib.iban = sanitizeCodeAlnum(v)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -313,6 +318,7 @@ import {
|
||||
} from '~/modules/technique/types/providerForm'
|
||||
import { extractApiErrorMessage } from '~/shared/utils/api'
|
||||
import { isRowRemovable } from '~/shared/utils/collectionRow'
|
||||
import { sanitizeCodeAlnum, sanitizeFreeText } from '~/shared/utils/textSanitize'
|
||||
|
||||
// Masque SIREN : 9 chiffres (la normalisation finale reste serveur).
|
||||
const SIREN_MASK = '#########'
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
/>
|
||||
<MalioButton
|
||||
v-if="showArchive"
|
||||
variant="secondary"
|
||||
variant="danger"
|
||||
icon-name="mdi:archive-arrow-down-outline"
|
||||
icon-position="left"
|
||||
:label="t('technique.providers.action.archive')"
|
||||
@@ -49,26 +49,27 @@
|
||||
<MalioInputText
|
||||
:model-value="provider.companyName"
|
||||
:label="t('technique.providers.form.main.companyName')"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioSelectCheckbox
|
||||
:model-value="mainCategoryIris"
|
||||
:options="mainCategoryOptions"
|
||||
:label="t('technique.providers.form.main.categories')"
|
||||
:display-tag="true"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
<MalioSelectCheckbox
|
||||
:model-value="mainSiteIris"
|
||||
:options="mainSiteOptions"
|
||||
:label="t('technique.providers.form.main.sites')"
|
||||
:display-tag="true"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- ── Onglets (navigation libre, tout en lecture seule) ──────────── -->
|
||||
<MalioTabList v-model="activeTab" :tabs="tabs" :max-visible-tabs="5" :max-width="1100" class="mt-[60px]">
|
||||
<!-- ERP-193 : barre masquee s'il ne reste aucun onglet non vide. -->
|
||||
<MalioTabList v-if="visibleTabKeys.length" v-model="activeTab" :tabs="tabs" :max-visible-tabs="5" :max-width="1100" class="mt-[60px]">
|
||||
<!-- Onglet Contacts -->
|
||||
<template #contacts>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
@@ -76,7 +77,7 @@
|
||||
v-for="(contact, index) in contacts"
|
||||
:key="index"
|
||||
:model-value="contact"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -92,27 +93,25 @@
|
||||
:site-options="view.siteOptions"
|
||||
:contact-options="contactOptions"
|
||||
:country-options="countryOptionsFor(view.draft.country)"
|
||||
readonly
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Onglets placeholder « A venir » (comme les autres modules). -->
|
||||
<template #reports><ComingSoonPlaceholder /></template>
|
||||
<template #exchanges><ComingSoonPlaceholder /></template>
|
||||
<!-- ERP-193 : les onglets « a venir » (Rapports / Echanges) ne sont
|
||||
plus rendus en consultation (masquage des onglets vides). -->
|
||||
|
||||
<!-- Onglet Comptabilite (present uniquement si accounting.view). -->
|
||||
<template v-if="canAccountingView" #accounting>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
<div class="bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
|
||||
<div class="grid grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText :model-value="accounting.siren" :label="t('technique.providers.form.accounting.siren')" readonly />
|
||||
<MalioInputText :model-value="accounting.accountNumber" :label="t('technique.providers.form.accounting.accountNumber')" readonly />
|
||||
<MalioSelect :model-value="accounting.tvaModeIri" :options="tvaModeOptions" :label="t('technique.providers.form.accounting.tvaMode')" readonly empty-option-label="" />
|
||||
<MalioInputText :model-value="accounting.nTva" :label="t('technique.providers.form.accounting.nTva')" readonly />
|
||||
<MalioSelect :model-value="accounting.paymentDelayIri" :options="paymentDelayOptions" :label="t('technique.providers.form.accounting.paymentDelay')" readonly empty-option-label="" />
|
||||
<MalioSelect :model-value="accounting.paymentTypeIri" :options="paymentTypeOptions" :label="t('technique.providers.form.accounting.paymentType')" readonly empty-option-label="" />
|
||||
<MalioSelect v-if="isBankRequired" :model-value="accounting.bankIri" :options="bankOptions" :label="t('technique.providers.form.accounting.bank')" readonly empty-option-label="" />
|
||||
<MalioInputText :model-value="accounting.siren" :label="t('technique.providers.form.accounting.siren')" disabled />
|
||||
<MalioInputText :model-value="accounting.accountNumber" :label="t('technique.providers.form.accounting.accountNumber')" disabled />
|
||||
<MalioSelect :model-value="accounting.tvaModeIri" :options="tvaModeOptions" :label="t('technique.providers.form.accounting.tvaMode')" disabled empty-option-label="" />
|
||||
<MalioInputText :model-value="accounting.nTva" :label="t('technique.providers.form.accounting.nTva')" disabled />
|
||||
<MalioSelect :model-value="accounting.paymentDelayIri" :options="paymentDelayOptions" :label="t('technique.providers.form.accounting.paymentDelay')" disabled empty-option-label="" />
|
||||
<MalioSelect :model-value="accounting.paymentTypeIri" :options="paymentTypeOptions" :label="t('technique.providers.form.accounting.paymentType')" disabled empty-option-label="" />
|
||||
<MalioSelect v-if="isBankRequired" :model-value="accounting.bankIri" :options="bankOptions" :label="t('technique.providers.form.accounting.bank')" disabled empty-option-label="" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -123,9 +122,9 @@
|
||||
class="bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]"
|
||||
>
|
||||
<div class="grid grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText :model-value="rib.label" :label="t('technique.providers.form.accounting.ribLabel')" readonly />
|
||||
<MalioInputText :model-value="rib.bic" :label="t('technique.providers.form.accounting.ribBic')" readonly />
|
||||
<MalioInputText :model-value="rib.iban" :label="t('technique.providers.form.accounting.ribIban')" readonly />
|
||||
<MalioInputText :model-value="rib.label" :label="t('technique.providers.form.accounting.ribLabel')" disabled />
|
||||
<MalioInputText :model-value="rib.bic" :label="t('technique.providers.form.accounting.ribBic')" disabled />
|
||||
<MalioInputText :model-value="rib.iban" :label="t('technique.providers.form.accounting.ribIban')" disabled />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -158,7 +157,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { useProvider } from '~/modules/technique/composables/useProvider'
|
||||
import {
|
||||
canEditProvider,
|
||||
@@ -170,6 +169,7 @@ import {
|
||||
mapContactToDraft,
|
||||
mapRibToDraft,
|
||||
paymentTypeCodeOf,
|
||||
providerConsultationVisibleTabs,
|
||||
referentialOptionOf,
|
||||
showArchiveAction,
|
||||
showRestoreAction,
|
||||
@@ -197,7 +197,6 @@ const headerTitle = computed(() => provider.value?.companyName || t('technique.p
|
||||
useHead({ title: t('technique.providers.consultation.title') })
|
||||
|
||||
// ── Onglets (ordre spec : Contacts · Adresse · Rapports · Échanges · Comptabilité) ──
|
||||
const activeTab = ref('contacts')
|
||||
const TAB_ICONS: Record<string, string> = {
|
||||
contacts: 'mdi:account-box-plus-outline',
|
||||
address: 'mdi:map-marker-outline',
|
||||
@@ -205,11 +204,27 @@ const TAB_ICONS: Record<string, string> = {
|
||||
exchanges: 'mdi:swap-horizontal',
|
||||
accounting: 'mdi:bank-circle-outline',
|
||||
}
|
||||
const tabs = computed(() => {
|
||||
const keys = ['contacts', 'address', 'reports', 'exchanges']
|
||||
if (canAccountingView.value) keys.push('accounting')
|
||||
return keys.map(key => ({ key, label: t(`technique.providers.tab.${key}`), icon: TAB_ICONS[key] }))
|
||||
})
|
||||
// ERP-193 (retour metier) : on masque les coquilles (Rapports / Echanges) ET
|
||||
// tout onglet de donnees vide. La liste depend donc du payload charge.
|
||||
const visibleTabKeys = computed(() => providerConsultationVisibleTabs(provider.value, {
|
||||
canAccountingView: canAccountingView.value,
|
||||
}))
|
||||
const tabs = computed(() => visibleTabKeys.value.map(
|
||||
key => ({ key, label: t(`technique.providers.tab.${key}`), icon: TAB_ICONS[key] }),
|
||||
))
|
||||
|
||||
// Onglet initial : vide tant que le prestataire n'est pas charge, puis premier
|
||||
// onglet visible. Un watcher recale si l'onglet courant disparait.
|
||||
const activeTab = ref('')
|
||||
watch(visibleTabKeys, (keys) => {
|
||||
if (keys.length === 0) {
|
||||
activeTab.value = ''
|
||||
return
|
||||
}
|
||||
if (!keys.includes(activeTab.value)) {
|
||||
activeTab.value = keys[0]
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
// ── Donnees mappees depuis la SEULE reponse detail ─────────────────────────────
|
||||
const mainCategoryIris = computed(() => irisOf(provider.value?.categories))
|
||||
|
||||
@@ -19,18 +19,19 @@
|
||||
Selecteur de site present ici (RG-3.03, relation directe). -->
|
||||
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText
|
||||
v-model="main.companyName"
|
||||
:model-value="main.companyName"
|
||||
:label="t('technique.providers.form.main.companyName')"
|
||||
:required="true"
|
||||
:readonly="mainLocked"
|
||||
:disabled="mainLocked"
|
||||
:error="mainErrors.errors.companyName"
|
||||
@update:model-value="(v: string) => main.companyName = sanitizeFreeText(v)"
|
||||
/>
|
||||
<MalioSelectCheckbox
|
||||
:model-value="main.categoryIris"
|
||||
:options="referentials.categories.value"
|
||||
:label="t('technique.providers.form.main.categories')"
|
||||
:display-tag="true"
|
||||
:readonly="mainLocked"
|
||||
:disabled="mainLocked"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.categories"
|
||||
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
|
||||
@@ -40,7 +41,7 @@
|
||||
:options="referentials.sites.value"
|
||||
:label="t('technique.providers.form.main.sites')"
|
||||
:display-tag="true"
|
||||
:readonly="mainLocked"
|
||||
:disabled="mainLocked"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.sites"
|
||||
@update:model-value="(v: (string | number)[]) => main.siteIris = v.map(String)"
|
||||
@@ -72,7 +73,7 @@
|
||||
:key="index"
|
||||
:model-value="contact"
|
||||
:removable="isRowRemovable(contacts, index)"
|
||||
:readonly="isValidated('contact')"
|
||||
:disabled="isValidated('contact')"
|
||||
:errors="contactErrors[index]"
|
||||
@update:model-value="(v) => contacts[index] = v"
|
||||
@remove="askRemoveContact(index)"
|
||||
@@ -107,7 +108,7 @@
|
||||
:contact-options="contactOptions"
|
||||
:country-options="countryOptions"
|
||||
:removable="isRowRemovable(addresses, index)"
|
||||
:readonly="isValidated('address')"
|
||||
:disabled="isValidated('address')"
|
||||
:errors="addressErrors[index]"
|
||||
@update:model-value="(v) => addresses[index] = v"
|
||||
@remove="askRemoveAddress(index)"
|
||||
@@ -140,39 +141,41 @@
|
||||
v-model="accounting.siren"
|
||||
:label="t('technique.providers.form.accounting.siren')"
|
||||
:mask="SIREN_MASK"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.siren"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="accounting.accountNumber"
|
||||
:model-value="accounting.accountNumber"
|
||||
:label="t('technique.providers.form.accounting.accountNumber')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.accountNumber"
|
||||
@update:model-value="(v: string) => accounting.accountNumber = sanitizeCodeAlnum(v)"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.tvaModeIri"
|
||||
:options="referentials.tvaModes.value"
|
||||
:label="t('technique.providers.form.accounting.tvaMode')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.tvaMode"
|
||||
@update:model-value="(v: string | number | null) => accounting.tvaModeIri = v === null ? null : String(v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="accounting.nTva"
|
||||
:model-value="accounting.nTva"
|
||||
:label="t('technique.providers.form.accounting.nTva')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.nTva"
|
||||
@update:model-value="(v: string) => accounting.nTva = sanitizeCodeAlnum(v)"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.paymentDelayIri"
|
||||
:options="referentials.paymentDelays.value"
|
||||
:label="t('technique.providers.form.accounting.paymentDelay')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.paymentDelay"
|
||||
@@ -182,7 +185,7 @@
|
||||
:model-value="accounting.paymentTypeIri"
|
||||
:options="referentials.paymentTypes.value"
|
||||
:label="t('technique.providers.form.accounting.paymentType')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.paymentType"
|
||||
@@ -194,7 +197,7 @@
|
||||
:model-value="accounting.bankIri"
|
||||
:options="referentials.banks.value"
|
||||
:label="t('technique.providers.form.accounting.bank')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.bank"
|
||||
@@ -221,23 +224,25 @@
|
||||
<MalioInputText
|
||||
v-model="rib.label"
|
||||
:label="t('technique.providers.form.accounting.ribLabel')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="ribErrors[index]?.label"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="rib.bic"
|
||||
:model-value="rib.bic"
|
||||
:label="t('technique.providers.form.accounting.ribBic')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="ribErrors[index]?.bic"
|
||||
@update:model-value="(v: string) => rib.bic = sanitizeCodeAlnum(v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="rib.iban"
|
||||
:model-value="rib.iban"
|
||||
:label="t('technique.providers.form.accounting.ribIban')"
|
||||
:readonly="accountingReadonly"
|
||||
:disabled="accountingReadonly"
|
||||
:required="true"
|
||||
:error="ribErrors[index]?.iban"
|
||||
@update:model-value="(v: string) => rib.iban = sanitizeCodeAlnum(v)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -297,6 +302,7 @@ import {
|
||||
} from '~/modules/technique/utils/forms/providerAccounting'
|
||||
import { extractApiErrorMessage } from '~/shared/utils/api'
|
||||
import { isRowRemovable } from '~/shared/utils/collectionRow'
|
||||
import { sanitizeCodeAlnum, sanitizeFreeText } from '~/shared/utils/textSanitize'
|
||||
|
||||
// Masque SIREN : 9 chiffres (la normalisation finale reste serveur).
|
||||
const SIREN_MASK = '#########'
|
||||
|
||||
@@ -10,6 +10,7 @@ const {
|
||||
canEditProvider,
|
||||
categoryOptionsOf,
|
||||
contactOptionsOf,
|
||||
hasAccountingData,
|
||||
iriOf,
|
||||
irisOf,
|
||||
mapAccountingDraft,
|
||||
@@ -17,6 +18,7 @@ const {
|
||||
mapContactToDraft,
|
||||
mapRibToDraft,
|
||||
paymentTypeCodeOf,
|
||||
providerConsultationVisibleTabs,
|
||||
referentialOptionOf,
|
||||
showArchiveAction,
|
||||
showRestoreAction,
|
||||
@@ -165,3 +167,48 @@ describe('providerDetail helpers', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasAccountingData (prestataire)', () => {
|
||||
it('faux sans champ comptable ni RIB', () => {
|
||||
expect(hasAccountingData({ '@id': '/api/providers/1', id: 1 })).toBe(false)
|
||||
})
|
||||
|
||||
it('vrai avec un champ comptable ou un RIB', () => {
|
||||
expect(hasAccountingData({ '@id': '/api/providers/1', id: 1, siren: '123456789' })).toBe(true)
|
||||
expect(hasAccountingData({
|
||||
'@id': '/api/providers/1', id: 1,
|
||||
ribs: [{ '@id': '/api/provider_ribs/1', id: 1, iban: 'FR76...' }],
|
||||
})).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('providerConsultationVisibleTabs', () => {
|
||||
it('retourne [] tant que le prestataire n\'est pas charge', () => {
|
||||
expect(providerConsultationVisibleTabs(null, { canAccountingView: true })).toEqual([])
|
||||
})
|
||||
|
||||
it('masque les coquilles (reports/exchanges) et les onglets vides', () => {
|
||||
expect(providerConsultationVisibleTabs(
|
||||
{ '@id': '/api/providers/1', id: 1, companyName: 'ACME' },
|
||||
{ canAccountingView: true },
|
||||
)).toEqual([])
|
||||
})
|
||||
|
||||
it('affiche contacts/address/accounting dans l\'ordre (pas d\'onglet information)', () => {
|
||||
const provider = {
|
||||
'@id': '/api/providers/1', id: 1,
|
||||
contacts: [{ '@id': '/api/provider_contacts/1', id: 1 }],
|
||||
addresses: [{ '@id': '/api/provider_addresses/1', id: 1 }],
|
||||
siren: '123456789',
|
||||
}
|
||||
expect(providerConsultationVisibleTabs(provider, { canAccountingView: true }))
|
||||
.toEqual(['contacts', 'address', 'accounting'])
|
||||
})
|
||||
|
||||
it('masque Comptabilite sans le droit accounting.view', () => {
|
||||
expect(providerConsultationVisibleTabs(
|
||||
{ '@id': '/api/providers/1', id: 1, siren: '123456789' },
|
||||
{ canAccountingView: false },
|
||||
)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -224,6 +224,58 @@ export function paymentTypeCodeOf(relation: Relation): string | null {
|
||||
return (relation.code as string | undefined) ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si une valeur scalaire porte une donnee affichable (non null/undefined,
|
||||
* et non chaine vide apres trim). Sert au predicat « onglet vide » ci-dessous.
|
||||
*/
|
||||
function hasValue(value: unknown): boolean {
|
||||
if (value === null || value === undefined) {
|
||||
return false
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
return value.trim() !== ''
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si l'onglet Comptabilite porte au moins un champ comptable OU un RIB.
|
||||
* (Le gating permission `accounting.view` reste applique en amont par l'appelant.)
|
||||
*/
|
||||
export function hasAccountingData(provider: ProviderDetail): boolean {
|
||||
const draft = mapAccountingDraft(provider)
|
||||
const hasField = Object.values(draft).some(hasValue)
|
||||
const hasRib = (provider.ribs ?? []).length > 0
|
||||
return hasField || hasRib
|
||||
}
|
||||
|
||||
/**
|
||||
* Onglets visibles en consultation (ERP-193, retour metier) : on masque les
|
||||
* coquilles non implementees (Rapports / Echanges) ET tout onglet de donnees
|
||||
* vide. Le prestataire n'a pas d'onglet Information (bloc principal au-dessus
|
||||
* des onglets). Ordre : Contacts · Adresse · Comptabilite. Retourne `[]` tant
|
||||
* que le prestataire n'est pas charge.
|
||||
*/
|
||||
export function providerConsultationVisibleTabs(
|
||||
provider: ProviderDetail | null | undefined,
|
||||
options: { canAccountingView: boolean },
|
||||
): string[] {
|
||||
if (!provider) {
|
||||
return []
|
||||
}
|
||||
const visible: string[] = []
|
||||
if ((provider.contacts ?? []).length > 0) {
|
||||
visible.push('contacts')
|
||||
}
|
||||
if ((provider.addresses ?? []).length > 0) {
|
||||
visible.push('address')
|
||||
}
|
||||
if (options.canAccountingView && hasAccountingData(provider)) {
|
||||
visible.push('accounting')
|
||||
}
|
||||
return visible
|
||||
}
|
||||
|
||||
/**
|
||||
* Bouton « Modifier » : visible si l'utilisateur peut editer au moins un onglet —
|
||||
* `manage` (onglets metier) OU `accounting.manage` (le role Compta doit pouvoir
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
<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"
|
||||
:disabled="disabled"
|
||||
: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"
|
||||
:disabled="disabled"
|
||||
: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"
|
||||
:disabled="disabled"
|
||||
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"
|
||||
:disabled="disabled"
|
||||
: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 && !disabled"
|
||||
:model-value="model.street"
|
||||
:options="addressOptions"
|
||||
:loading="addressLoading"
|
||||
:min-search-length="3"
|
||||
:label="t('transport.carriers.form.address.street')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
: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"
|
||||
:disabled="disabled"
|
||||
: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"
|
||||
:disabled="disabled"
|
||||
: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'
|
||||
import { sanitizeAddress } from '~/shared/utils/textSanitize'
|
||||
|
||||
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
|
||||
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
|
||||
disabled?: boolean
|
||||
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: CarrierAddressFormDraft]
|
||||
/** 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[] = []
|
||||
|
||||
// Filtres de saisie par champ (ERP-193) : voie / complement / ville = profil
|
||||
// adresse. Le code postal (masque numerique) n'est pas filtre ici.
|
||||
const FIELD_SANITIZERS: Partial<Record<keyof CarrierAddressFormDraft, (v: string) => string>> = {
|
||||
street: sanitizeAddress,
|
||||
streetComplement: sanitizeAddress,
|
||||
city: sanitizeAddress,
|
||||
}
|
||||
|
||||
/** Emet un nouveau brouillon avec le champ modifie (immutabilite), sanitise si besoin. */
|
||||
function update<K extends keyof CarrierAddressFormDraft>(field: K, value: CarrierAddressFormDraft[K]): void {
|
||||
const sanitizer = FIELD_SANITIZERS[field]
|
||||
const next = (sanitizer && typeof value === 'string')
|
||||
? (sanitizer(value) as CarrierAddressFormDraft[K])
|
||||
: value
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: next })
|
||||
}
|
||||
|
||||
/** 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,130 @@
|
||||
<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 && !disabled"
|
||||
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"
|
||||
:disabled="disabled"
|
||||
:error="errors?.lastName"
|
||||
@update:model-value="(v: string) => update('lastName', v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="model.firstName"
|
||||
:label="t('transport.carriers.form.contact.firstName')"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
: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"
|
||||
:disabled="disabled"
|
||||
: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"
|
||||
:disabled="disabled"
|
||||
: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"
|
||||
:disabled="disabled"
|
||||
: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"
|
||||
:disabled="disabled"
|
||||
: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'
|
||||
import { sanitizeEmail, sanitizeFreeText, sanitizePersonName } from '~/shared/utils/textSanitize'
|
||||
|
||||
// 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
|
||||
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
|
||||
disabled?: boolean
|
||||
/** Erreurs serveur 422 de cette ligne, indexées par champ (ERP-101). */
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: CarrierContactFormDraft]
|
||||
'remove': []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
// Alias local pour la lisibilité du template.
|
||||
const model = computed(() => props.modelValue)
|
||||
|
||||
// Filtres de saisie par champ (ERP-193) : on retire les caractères parasites à la
|
||||
// frappe. Noms = profil personne, fonction = texte libre, email = profil email.
|
||||
const FIELD_SANITIZERS: Partial<Record<keyof CarrierContactFormDraft, (v: string) => string>> = {
|
||||
lastName: sanitizePersonName,
|
||||
firstName: sanitizePersonName,
|
||||
jobTitle: sanitizeFreeText,
|
||||
email: sanitizeEmail,
|
||||
}
|
||||
|
||||
/** Émet un nouveau brouillon avec le champ modifié (immutabilité), sanitisé si besoin. */
|
||||
function update<K extends keyof CarrierContactFormDraft>(field: K, value: CarrierContactFormDraft[K]): void {
|
||||
const sanitizer = FIELD_SANITIZERS[field]
|
||||
const next = (sanitizer && typeof value === 'string')
|
||||
? (sanitizer(value) as CarrierContactFormDraft[K])
|
||||
: value
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: next })
|
||||
}
|
||||
|
||||
/** 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,317 @@
|
||||
<template>
|
||||
<div class="relative grid grid-cols-4 gap-x-[44px] gap-y-4 bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
|
||||
<!-- Suppression : modal de confirmation côté parent. -->
|
||||
<MalioButtonIcon
|
||||
v-if="removable && !readonly && !disabled"
|
||||
icon="mdi:delete-outline"
|
||||
variant="ghost"
|
||||
button-class="absolute top-3 right-3"
|
||||
v-bind="{ ariaLabel: t('transport.carriers.form.price.remove') }"
|
||||
@click="$emit('remove')"
|
||||
/>
|
||||
|
||||
<!-- RG-4.09 : sens du prix (CLIENT / FOURNISSEUR) en colonne 1 / ligne 1, radios
|
||||
EN LIGNE (horizontaux), centrés sur la hauteur de champ (h-12) comme la
|
||||
case « Affréter ». Pas de label de groupe. -->
|
||||
<div>
|
||||
<div class="flex h-12 items-center gap-6">
|
||||
<MalioRadioButton
|
||||
:model-value="model.direction"
|
||||
:name="`price-direction-${uid}`"
|
||||
value="CLIENT"
|
||||
:label="t('transport.carriers.form.price.directionClient')"
|
||||
:disabled="readonly || disabled"
|
||||
group-class="mt-0"
|
||||
@update:model-value="onDirectionChange"
|
||||
/>
|
||||
<MalioRadioButton
|
||||
:model-value="model.direction"
|
||||
:name="`price-direction-${uid}`"
|
||||
value="FOURNISSEUR"
|
||||
:label="t('transport.carriers.form.price.directionSupplier')"
|
||||
:disabled="readonly || disabled"
|
||||
group-class="mt-0"
|
||||
@update:model-value="onDirectionChange"
|
||||
/>
|
||||
</div>
|
||||
<p v-if="errors?.direction" class="ml-[2px] text-xs text-m-danger">{{ errors.direction }}</p>
|
||||
</div>
|
||||
|
||||
<!-- Branche CLIENT (RG-4.10). -->
|
||||
<template v-if="model.direction === 'CLIENT'">
|
||||
<MalioSelect
|
||||
:model-value="model.clientIri"
|
||||
:options="clientOptions"
|
||||
:label="t('transport.carriers.form.price.client')"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.client"
|
||||
@update:model-value="onClientChange"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="model.clientDeliveryAddressIri"
|
||||
:options="clientAddressOptions"
|
||||
:label="t('transport.carriers.form.price.clientDeliveryAddress')"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.clientDeliveryAddress"
|
||||
@update:model-value="(v: string | number | null) => update('clientDeliveryAddressIri', v === null ? null : String(v))"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="model.departureSiteIri"
|
||||
:options="siteOptions"
|
||||
:label="t('transport.carriers.form.price.departureSite')"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.departureSite"
|
||||
@update:model-value="(v: string | number | null) => update('departureSiteIri', v === null ? null : String(v))"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<!-- Branche FOURNISSEUR (RG-4.11). -->
|
||||
<template v-else-if="model.direction === 'FOURNISSEUR'">
|
||||
<MalioSelect
|
||||
:model-value="model.supplierIri"
|
||||
:options="supplierOptions"
|
||||
:label="t('transport.carriers.form.price.supplier')"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.supplier"
|
||||
@update:model-value="onSupplierChange"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="model.supplierSupplyAddressIri"
|
||||
:options="supplierAddressOptions"
|
||||
:label="t('transport.carriers.form.price.supplierSupplyAddress')"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.supplierSupplyAddress"
|
||||
@update:model-value="(v: string | number | null) => update('supplierSupplyAddressIri', v === null ? null : String(v))"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="model.deliverySiteIri"
|
||||
:options="siteOptions"
|
||||
:label="t('transport.carriers.form.price.deliverySite')"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.deliverySite"
|
||||
@update:model-value="(v: string | number | null) => update('deliverySiteIri', v === null ? null : String(v))"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<!-- Communs (visibles dès qu'un sens est choisi). -->
|
||||
<template v-if="model.direction !== null">
|
||||
<!-- Contenant : Benne / Fond mouvant (radios centrés h-12, pas de label). -->
|
||||
<div>
|
||||
<div class="flex h-12 items-center gap-4">
|
||||
<MalioRadioButton
|
||||
:model-value="model.containerType"
|
||||
:name="`price-container-${uid}`"
|
||||
value="BENNE"
|
||||
:label="t('transport.carriers.containerType.BENNE')"
|
||||
:disabled="readonly || disabled"
|
||||
group-class="mt-0"
|
||||
@update:model-value="(v: string | number | boolean | null) => update('containerType', v === null ? null : String(v))"
|
||||
/>
|
||||
<MalioRadioButton
|
||||
:model-value="model.containerType"
|
||||
:name="`price-container-${uid}`"
|
||||
value="FOND_MOUVANT"
|
||||
:label="t('transport.carriers.containerType.FOND_MOUVANT')"
|
||||
:disabled="readonly || disabled"
|
||||
group-class="mt-0"
|
||||
@update:model-value="(v: string | number | boolean | null) => update('containerType', v === null ? null : String(v))"
|
||||
/>
|
||||
</div>
|
||||
<p v-if="errors?.containerType" class="ml-[2px] text-xs text-m-danger">{{ errors.containerType }}</p>
|
||||
</div>
|
||||
|
||||
<!-- Tarification : Forfait / Tonne (radios centrés h-12, pas de label). -->
|
||||
<div>
|
||||
<div class="flex h-12 items-center gap-4">
|
||||
<MalioRadioButton
|
||||
:model-value="model.pricingUnit"
|
||||
:name="`price-unit-${uid}`"
|
||||
value="FORFAIT"
|
||||
:label="t('transport.carriers.form.price.pricingForfait')"
|
||||
:disabled="readonly || disabled"
|
||||
group-class="mt-0"
|
||||
@update:model-value="(v: string | number | boolean | null) => update('pricingUnit', v === null ? null : String(v))"
|
||||
/>
|
||||
<MalioRadioButton
|
||||
:model-value="model.pricingUnit"
|
||||
:name="`price-unit-${uid}`"
|
||||
value="TONNE"
|
||||
:label="t('transport.carriers.form.price.pricingTonne')"
|
||||
:disabled="readonly || disabled"
|
||||
group-class="mt-0"
|
||||
@update:model-value="(v: string | number | boolean | null) => update('pricingUnit', v === null ? null : String(v))"
|
||||
/>
|
||||
</div>
|
||||
<p v-if="errors?.pricingUnit" class="ml-[2px] text-xs text-m-danger">{{ errors.pricingUnit }}</p>
|
||||
</div>
|
||||
|
||||
<MalioInputAmount
|
||||
:model-value="model.price"
|
||||
:label="t('transport.carriers.form.price.price')"
|
||||
:required="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.price"
|
||||
@update:model-value="(v: string) => update('price', v)"
|
||||
/>
|
||||
|
||||
<MalioSelect
|
||||
:model-value="model.priceState"
|
||||
:options="priceStateOptions"
|
||||
:label="t('transport.carriers.form.price.priceState')"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:readonly="readonly"
|
||||
:disabled="disabled"
|
||||
:error="errors?.priceState"
|
||||
@update:model-value="(v: string | number | null) => update('priceState', v === null ? null : String(v))"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, useId, watch } from 'vue'
|
||||
import type { CarrierPriceFormDraft } from '~/modules/transport/types/carrierForm'
|
||||
|
||||
interface SelectOption {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
/** Brouillon du prix (v-model). */
|
||||
modelValue: CarrierPriceFormDraft
|
||||
/** Clients disponibles (IRI en value). */
|
||||
clientOptions: SelectOption[]
|
||||
/** Fournisseurs disponibles (IRI en value). */
|
||||
supplierOptions: SelectOption[]
|
||||
/** Sites Starseed (3 sites — IRI en value). */
|
||||
siteOptions: SelectOption[]
|
||||
removable?: boolean
|
||||
readonly?: boolean
|
||||
/** Bloc desactive (champs grises, consultation — distinct de readonly). */
|
||||
disabled?: boolean
|
||||
/** Erreurs serveur 422 de cette ligne, indexées par champ (ERP-101). */
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: CarrierPriceFormDraft]
|
||||
'remove': []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const api = useApi()
|
||||
|
||||
// Identifiant unique par instance : les groupes de radios (sens / contenant / tarif)
|
||||
// doivent avoir un `name` PROPRE à chaque bloc prix, sinon plusieurs blocs partagent
|
||||
// le même groupe HTML et leurs radios se désélectionnent mutuellement.
|
||||
const uid = useId()
|
||||
|
||||
const model = computed(() => props.modelValue)
|
||||
|
||||
const priceStateOptions = computed<SelectOption[]>(() => [
|
||||
{ value: 'EN_COURS', label: t('transport.carriers.form.price.stateEnCours') },
|
||||
{ value: 'VALIDE', label: t('transport.carriers.form.price.stateValide') },
|
||||
{ value: 'NON_VALIDE', label: t('transport.carriers.form.price.stateNonValide') },
|
||||
])
|
||||
|
||||
// Adresses chargées à la volée pour le client / fournisseur sélectionné (par bloc).
|
||||
const clientAddressOptions = ref<SelectOption[]>([])
|
||||
const supplierAddressOptions = ref<SelectOption[]>([])
|
||||
|
||||
/** Émet un nouveau brouillon avec le champ modifié (immutabilité). */
|
||||
function update<K extends keyof CarrierPriceFormDraft>(field: K, value: CarrierPriceFormDraft[K]): void {
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: value })
|
||||
}
|
||||
|
||||
/** Changement de sens : réinitialise les DEUX branches (cohérence CHECK BDD). */
|
||||
function onDirectionChange(value: string | number | boolean | null): void {
|
||||
const direction = value === 'CLIENT' || value === 'FOURNISSEUR' ? value : null
|
||||
emit('update:modelValue', {
|
||||
...props.modelValue,
|
||||
direction,
|
||||
clientIri: null,
|
||||
clientDeliveryAddressIri: null,
|
||||
departureSiteIri: null,
|
||||
supplierIri: null,
|
||||
supplierSupplyAddressIri: null,
|
||||
deliverySiteIri: null,
|
||||
})
|
||||
}
|
||||
|
||||
/** Sélection d'un client → maj IRI + reset de l'adresse de livraison (autre client). */
|
||||
function onClientChange(value: string | number | null): void {
|
||||
emit('update:modelValue', {
|
||||
...props.modelValue,
|
||||
clientIri: value === null ? null : String(value),
|
||||
clientDeliveryAddressIri: null,
|
||||
})
|
||||
}
|
||||
|
||||
/** Sélection d'un fournisseur → maj IRI + reset de l'adresse d'appro. */
|
||||
function onSupplierChange(value: string | number | null): void {
|
||||
emit('update:modelValue', {
|
||||
...props.modelValue,
|
||||
supplierIri: value === null ? null : String(value),
|
||||
supplierSupplyAddressIri: null,
|
||||
})
|
||||
}
|
||||
|
||||
/** Réponse détail (client / fournisseur) embarquant ses adresses. */
|
||||
interface ParentWithAddresses {
|
||||
addresses?: { '@id': string, street?: string | null, postalCode?: string | null, city?: string | null }[]
|
||||
}
|
||||
|
||||
/** Mappe les adresses embarquées en options (IRI en value, voie · CP · ville en label). */
|
||||
function toAddressOptions(parent: ParentWithAddresses): SelectOption[] {
|
||||
return (parent.addresses ?? []).map(a => ({
|
||||
value: a['@id'],
|
||||
label: [a.street, a.postalCode, a.city].filter(Boolean).join(' · ') || a['@id'],
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Charge les adresses d'un parent (client/fournisseur) à la volée via son détail
|
||||
* (GET de l'IRI, qui embarque `addresses`). Échec → liste vide (non bloquant).
|
||||
*/
|
||||
async function loadAddresses(iri: string | null, target: typeof clientAddressOptions): Promise<void> {
|
||||
if (!iri) {
|
||||
target.value = []
|
||||
return
|
||||
}
|
||||
try {
|
||||
// L'IRI est absolue (/api/clients/5) ; useApi préfixe déjà /api → on le retire.
|
||||
const path = iri.replace(/^\/api/, '')
|
||||
const data = await api.get<ParentWithAddresses>(path, {}, { headers: { Accept: 'application/ld+json' }, toast: false })
|
||||
target.value = toAddressOptions(data)
|
||||
}
|
||||
catch {
|
||||
target.value = []
|
||||
}
|
||||
}
|
||||
|
||||
// Recharge les adresses quand le client / fournisseur change (immediate pour le
|
||||
// pré-remplissage en édition).
|
||||
watch(() => props.modelValue.clientIri, iri => loadAddresses(iri, clientAddressOptions), { immediate: true })
|
||||
watch(() => props.modelValue.supplierIri, iri => loadAddresses(iri, supplierAddressOptions), { immediate: true })
|
||||
</script>
|
||||
@@ -0,0 +1,201 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { debounce } from '~/shared/utils/debounce'
|
||||
import { useQualimatSearch, type QualimatCarrierRow } from '~/modules/transport/composables/useQualimatSearch'
|
||||
|
||||
/**
|
||||
* Onglet « Qualimat » — saisie assistée par recherche dans le référentiel QUALIMAT
|
||||
* (RG-4.01 / RG-4.04). Datatable paginé filtré par le NOM (`searchName`), sélection
|
||||
* d'une ligne → modal de confirmation → `integrate`. Mutualisé entre l'écran
|
||||
* d'AJOUT (ERP-166) et l'écran de MODIFICATION (ERP-172, « actualiser le
|
||||
* transporteur »). La persistance (copie nom / certification / FK) est portée par
|
||||
* le parent via `useCarrierForm.applyQualimatSelection`.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
/** Terme de recherche (nom du transporteur saisi dans le formulaire principal). */
|
||||
searchName: string
|
||||
/** IRI QUALIMAT actuellement lié (coche le radio de la ligne correspondante). */
|
||||
selectedIri: string | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(event: 'integrate', row: QualimatCarrierRow): void
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const {
|
||||
items: qualimatItems,
|
||||
totalItems: qualimatTotal,
|
||||
currentPage: qualimatPage,
|
||||
itemsPerPage: qualimatPerPage,
|
||||
itemsPerPageOptions: qualimatPerPageOptions,
|
||||
goToPage: qualimatGoToPage,
|
||||
setItemsPerPage: qualimatSetPerPage,
|
||||
setFilters: qualimatSetFilters,
|
||||
} = useQualimatSearch()
|
||||
|
||||
// Colonnes du datatable de sélection QUALIMAT (radio / Nom / Adresse / Validité).
|
||||
const qualimatColumns = [
|
||||
{ key: 'select', label: '' },
|
||||
{ key: 'name', label: t('transport.carriers.form.qualimat.columns.name') },
|
||||
{ key: 'address', label: t('transport.carriers.form.qualimat.columns.address') },
|
||||
{ key: 'validityDate', label: t('transport.carriers.form.qualimat.columns.validityDate') },
|
||||
]
|
||||
|
||||
// Le datatable n'affiche QUE des résultats de recherche : vide tant que le Nom n'est
|
||||
// pas saisi (pas de liste complète par défaut).
|
||||
const hasQualimatSearch = computed(() => props.searchName.trim() !== '')
|
||||
|
||||
const qualimatRows = computed(() => {
|
||||
if (!hasQualimatSearch.value) {
|
||||
return []
|
||||
}
|
||||
return qualimatItems.value.map(row => ({
|
||||
id: row.id,
|
||||
iri: row['@id'],
|
||||
name: row.name,
|
||||
address: formatQualimatAddress(row),
|
||||
validityDate: row.validityDate,
|
||||
}))
|
||||
})
|
||||
|
||||
const qualimatTotalDisplay = computed(() => (hasQualimatSearch.value ? qualimatTotal.value : 0))
|
||||
const qualimatEmptyMessage = computed(() => hasQualimatSearch.value
|
||||
? t('transport.carriers.form.qualimat.empty')
|
||||
: t('transport.carriers.form.qualimat.searchHint'))
|
||||
|
||||
// Re-filtrage debouncé sur le nom ; aucune recherche tant que le Nom est vide.
|
||||
const filterQualimatByName = debounce((term: string) => {
|
||||
if (term.trim() === '') {
|
||||
return
|
||||
}
|
||||
void qualimatSetFilters({ search: term })
|
||||
}, 300)
|
||||
|
||||
watch(() => props.searchName, term => filterQualimatByName(term), { immediate: true })
|
||||
|
||||
/** Adresse QUALIMAT condensée pour la colonne « Adresse » (voie · CP · ville). */
|
||||
function formatQualimatAddress(row: QualimatCarrierRow): string {
|
||||
return [row.address, row.postalCode, row.city].filter(Boolean).join(' · ')
|
||||
}
|
||||
|
||||
/** RG-4.04 : un agrément est périmé si sa date de validité est < aujourd'hui. */
|
||||
function isExpired(value: string): boolean {
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return false
|
||||
}
|
||||
const today = new Date()
|
||||
today.setHours(0, 0, 0, 0)
|
||||
date.setHours(0, 0, 0, 0)
|
||||
return date.getTime() < today.getTime()
|
||||
}
|
||||
|
||||
/** Format court français JJ-MM-AAAA (chaîne vide si date absente / invalide). */
|
||||
function formatDateFr(value: string | null | undefined): string {
|
||||
if (!value) {
|
||||
return ''
|
||||
}
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return ''
|
||||
}
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
return `${day}-${month}-${date.getFullYear()}`
|
||||
}
|
||||
|
||||
// ── Confirmation d'intégration ───────────────────────────────────────────────
|
||||
const confirmOpen = ref(false)
|
||||
const pendingRow = ref<QualimatCarrierRow | null>(null)
|
||||
|
||||
/** Clic sur une ligne → retrouve la ligne QUALIMAT source + ouvre la modal. */
|
||||
function onQualimatRowClick(item: Record<string, unknown>): void {
|
||||
const row = qualimatItems.value.find(r => r.id === item.id)
|
||||
if (row) {
|
||||
pendingRow.value = row
|
||||
confirmOpen.value = true
|
||||
}
|
||||
}
|
||||
|
||||
/** Confirme l'intégration : délègue la persistance au parent via `integrate`. */
|
||||
function confirmIntegrate(): void {
|
||||
const row = pendingRow.value
|
||||
confirmOpen.value = false
|
||||
if (row !== null) {
|
||||
emit('integrate', row)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
<!-- table-fixed : 1re colonne (radio) étroite, les 3 autres à parts égales. -->
|
||||
<MalioDataTable
|
||||
class="qualimat-table"
|
||||
table-class="table-fixed"
|
||||
:columns="qualimatColumns"
|
||||
:items="qualimatRows"
|
||||
:total-items="qualimatTotalDisplay"
|
||||
:page="qualimatPage"
|
||||
:per-page="qualimatPerPage"
|
||||
:per-page-options="qualimatPerPageOptions"
|
||||
row-clickable
|
||||
:empty-message="qualimatEmptyMessage"
|
||||
@row-click="onQualimatRowClick"
|
||||
@update:page="qualimatGoToPage"
|
||||
@update:per-page="qualimatSetPerPage"
|
||||
>
|
||||
<!-- Radio reflétant la ligne QUALIMAT intégrée (lecture). -->
|
||||
<template #cell-select="{ item }">
|
||||
<MalioRadioButton
|
||||
:model-value="selectedIri"
|
||||
name="qualimat-row"
|
||||
:value="item.iri"
|
||||
group-class="mt-0"
|
||||
/>
|
||||
</template>
|
||||
<!-- Date de validité : fond rouge si périmée (RG-4.04). -->
|
||||
<template #cell-validityDate="{ item }">
|
||||
<span
|
||||
v-if="item.validityDate"
|
||||
:class="isExpired(item.validityDate as string) ? 'inline-block rounded px-2 py-0.5 bg-m-danger text-white' : ''"
|
||||
>
|
||||
{{ formatDateFr(item.validityDate as string) }}
|
||||
</span>
|
||||
</template>
|
||||
</MalioDataTable>
|
||||
|
||||
<!-- Modal de confirmation d'intégration QUALIMAT. -->
|
||||
<MalioModal v-model="confirmOpen" modal-class="max-w-md">
|
||||
<template #header>
|
||||
<h2 class="text-[24px] font-bold">{{ t('transport.carriers.form.qualimat.confirm.title') }}</h2>
|
||||
</template>
|
||||
<p>{{ t('transport.carriers.form.qualimat.confirm.message') }}</p>
|
||||
<template #footer>
|
||||
<MalioButton
|
||||
variant="secondary"
|
||||
button-class="flex-1"
|
||||
:label="t('transport.carriers.form.qualimat.confirm.cancel')"
|
||||
@click="confirmOpen = false"
|
||||
/>
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
button-class="flex-1"
|
||||
:label="t('transport.carriers.form.qualimat.confirm.confirm')"
|
||||
@click="confirmIntegrate"
|
||||
/>
|
||||
</template>
|
||||
</MalioModal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* Datatable QUALIMAT en table-fixed : la colonne radio (1re) reste étroite,
|
||||
les 3 autres (nom / adresse / validité) se partagent l'espace à parts égales. */
|
||||
.qualimat-table :deep(th:first-child),
|
||||
.qualimat-table :deep(td:first-child) {
|
||||
width: 56px;
|
||||
}
|
||||
</style>
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -19,13 +19,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mockPost = vi.hoisted(() => vi.fn())
|
||||
const mockPatch = vi.hoisted(() => vi.fn())
|
||||
const mockDelete = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.stubGlobal('useApi', () => ({
|
||||
get: vi.fn(),
|
||||
post: mockPost,
|
||||
put: vi.fn(),
|
||||
patch: mockPatch,
|
||||
delete: vi.fn(),
|
||||
delete: mockDelete,
|
||||
}))
|
||||
vi.stubGlobal('useI18n', () => ({ t: (key: string) => key }))
|
||||
vi.stubGlobal('useToast', () => ({
|
||||
@@ -36,6 +37,9 @@ vi.stubGlobal('useToast', () => ({
|
||||
}))
|
||||
|
||||
const { useCarrierForm, CARRIER_TAB_KEYS } = await import('../useCarrierForm')
|
||||
const { buildCarrierContactPayload, isCarrierContactBlank, isCarrierContactNamed } = await import('../../utils/forms/carrierContact')
|
||||
const { buildCarrierPricePayload, isCarrierPriceValid } = await import('../../utils/forms/carrierPrice')
|
||||
const { emptyCarrierContact, emptyCarrierPrice } = await import('../../types/carrierForm')
|
||||
|
||||
describe('useCarrierForm', () => {
|
||||
beforeEach(() => {
|
||||
@@ -65,12 +69,87 @@ describe('useCarrierForm', () => {
|
||||
expect(form.mainErrors.errors.name).toBe('transport.carriers.form.errors.nameRequired')
|
||||
})
|
||||
|
||||
it('front : certification vide (hors LIOT) → erreur inline sur certificationType, pas de POST', async () => {
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'Acme'
|
||||
// certificationType laissé null → bloqué côté front (RG-4.01).
|
||||
|
||||
const created = await form.submitMain()
|
||||
|
||||
expect(created).toBe(false)
|
||||
expect(mockPost).not.toHaveBeenCalled()
|
||||
expect(form.mainErrors.errors.certificationType).toBe('transport.carriers.form.errors.certificationRequired')
|
||||
})
|
||||
|
||||
it('front : cas LIOT → certification non requise (aucune erreur de certification)', async () => {
|
||||
mockPost.mockResolvedValueOnce({ id: 5, name: 'LIOT', certificationType: null })
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'LIOT'
|
||||
form.main.liotPlates = 'AA-123-BB'
|
||||
|
||||
const created = await form.submitMain()
|
||||
|
||||
expect(created).toBe(true)
|
||||
expect(form.mainErrors.errors.certificationType).toBeUndefined()
|
||||
})
|
||||
|
||||
it('front RG-4.02 : certification AUTRE sans décharge → erreur inline, pas de POST', async () => {
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'Acme'
|
||||
form.main.certificationType = 'AUTRE'
|
||||
// dischargeDocumentIri null (upload non fourni).
|
||||
|
||||
const created = await form.submitMain()
|
||||
|
||||
expect(created).toBe(false)
|
||||
expect(mockPost).not.toHaveBeenCalled()
|
||||
expect(form.mainErrors.errors.dischargeDocument).toBe('transport.carriers.form.errors.dischargeRequired')
|
||||
})
|
||||
|
||||
it('front RG-4.03 : affrété sans indexation / contenant / volume → 3 erreurs inline, pas de POST', async () => {
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'Acme'
|
||||
form.main.certificationType = 'GMP_PLUS'
|
||||
form.main.isChartered = true
|
||||
// Annule le défaut « BENNE » pour vérifier la garde « contenant obligatoire ».
|
||||
form.main.containerType = null
|
||||
|
||||
const created = await form.submitMain()
|
||||
|
||||
expect(created).toBe(false)
|
||||
expect(mockPost).not.toHaveBeenCalled()
|
||||
expect(form.mainErrors.errors.indexationRate).toBe('transport.carriers.form.errors.indexationRequired')
|
||||
expect(form.mainErrors.errors.containerType).toBe('transport.carriers.form.errors.containerTypeRequired')
|
||||
expect(form.mainErrors.errors.volumeM3).toBe('transport.carriers.form.errors.volumeRequired')
|
||||
})
|
||||
|
||||
it('front RG-4.03 : affrété avec tous les champs remplis → POST envoyé', async () => {
|
||||
mockPost.mockResolvedValueOnce({ id: 8, name: 'ACME', certificationType: 'GMP_PLUS' })
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'Acme'
|
||||
form.main.certificationType = 'GMP_PLUS'
|
||||
form.main.isChartered = true
|
||||
form.main.indexationRate = '5'
|
||||
form.main.containerType = 'BENNE'
|
||||
form.main.volumeM3 = '30'
|
||||
|
||||
const created = await form.submitMain()
|
||||
|
||||
expect(created).toBe(true)
|
||||
expect(mockPost).toHaveBeenCalledTimes(1)
|
||||
expect(mockPost.mock.calls[0]?.[1]).toMatchObject({
|
||||
isChartered: true,
|
||||
indexationRate: '5',
|
||||
containerType: 'BENNE',
|
||||
volumeM3: '30',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /carriers avec Accept ld+json, verrouille et bascule sur Qualimat', async () => {
|
||||
mockPost.mockResolvedValueOnce({ id: 42, name: 'TRANSPORTS ACME', certificationType: 'GMP_PLUS' })
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'Transports Acme'
|
||||
form.main.certificationType = 'GMP_PLUS'
|
||||
form.main.isChartered = true
|
||||
|
||||
const created = await form.submitMain()
|
||||
|
||||
@@ -81,7 +160,7 @@ describe('useCarrierForm', () => {
|
||||
expect(body).toEqual({
|
||||
name: 'Transports Acme',
|
||||
certificationType: 'GMP_PLUS',
|
||||
isChartered: true,
|
||||
isChartered: false,
|
||||
})
|
||||
expect(opts).toMatchObject({ toast: false, headers: { Accept: 'application/ld+json' } })
|
||||
|
||||
@@ -89,19 +168,17 @@ describe('useCarrierForm', () => {
|
||||
// RG-4.13 : réaffiche le nom normalisé (UPPERCASE) renvoyé par le serveur.
|
||||
expect(form.main.name).toBe('TRANSPORTS ACME')
|
||||
expect(form.mainLocked.value).toBe(true)
|
||||
expect(form.activeTab.value).toBe('qualimat')
|
||||
expect(form.unlockedIndex.value).toBe(0)
|
||||
// L'onglet Qualimat était déjà accessible (saisie assistée) ; le POST
|
||||
// déverrouille Adresses (index 1) et bascule dessus.
|
||||
expect(form.activeTab.value).toBe('addresses')
|
||||
expect(form.unlockedIndex.value).toBe(1)
|
||||
})
|
||||
|
||||
it('payload : omet name et certificationType vides, garde isChartered', async () => {
|
||||
mockPost.mockRejectedValueOnce({ response: { status: 422, _data: { violations: [] } } })
|
||||
it('buildMainPayload : omet certificationType vide, garde isChartered', () => {
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'X' // nom présent pour passer le pré-check front
|
||||
// certificationType laissé null → omis pour que la 422 « obligatoire » porte.
|
||||
form.main.name = 'X'
|
||||
|
||||
await form.submitMain()
|
||||
|
||||
const body = mockPost.mock.calls[0]?.[1] as Record<string, unknown>
|
||||
const body = form.buildMainPayload()
|
||||
expect(body).toEqual({ name: 'X', isChartered: false })
|
||||
expect('certificationType' in body).toBe(false)
|
||||
})
|
||||
@@ -110,7 +187,7 @@ describe('useCarrierForm', () => {
|
||||
mockPost.mockRejectedValueOnce({ response: { status: 409 } })
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'Doublon'
|
||||
form.main.certificationType = 'AUTRE'
|
||||
form.main.certificationType = 'GMP_PLUS'
|
||||
|
||||
const created = await form.submitMain()
|
||||
|
||||
@@ -120,19 +197,23 @@ describe('useCarrierForm', () => {
|
||||
})
|
||||
|
||||
it('422 : mappe les violations serveur inline par champ', async () => {
|
||||
// Contrainte re-validée uniquement back (ex. longueur du nom) : le pré-check
|
||||
// front passe (nom rempli, certif choisie, non affrété), la 422 mappe inline
|
||||
// sur le champ via son propertyPath.
|
||||
mockPost.mockRejectedValueOnce({
|
||||
response: {
|
||||
status: 422,
|
||||
_data: { violations: [{ propertyPath: 'certificationType', message: 'Le type de certification est obligatoire.' }] },
|
||||
_data: { violations: [{ propertyPath: 'name', message: 'Le nom du transporteur ne peut dépasser 255 caractères.' }] },
|
||||
},
|
||||
})
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'Sans Certif'
|
||||
form.main.name = 'Acme'
|
||||
form.main.certificationType = 'GMP_PLUS'
|
||||
|
||||
const created = await form.submitMain()
|
||||
|
||||
expect(created).toBe(false)
|
||||
expect(form.mainErrors.errors.certificationType).toBe('Le type de certification est obligatoire.')
|
||||
expect(form.mainErrors.errors.name).toBe('Le nom du transporteur ne peut dépasser 255 caractères.')
|
||||
expect(form.mainLocked.value).toBe(false)
|
||||
})
|
||||
|
||||
@@ -140,8 +221,9 @@ describe('useCarrierForm', () => {
|
||||
expect(CARRIER_TAB_KEYS).toEqual(['qualimat', 'addresses', 'contacts', 'prices'])
|
||||
const form = useCarrierForm()
|
||||
expect(form.tabKeys.value).toEqual(['qualimat', 'addresses', 'contacts', 'prices'])
|
||||
// Tous verrouillés tant que le formulaire principal n'est pas validé.
|
||||
expect(form.unlockedIndex.value).toBe(-1)
|
||||
// L'onglet Qualimat (index 0) est accessible dès le départ (saisie assistée) ;
|
||||
// Adresses / Contacts / Prix restent verrouillés jusqu'au POST principal.
|
||||
expect(form.unlockedIndex.value).toBe(0)
|
||||
})
|
||||
|
||||
it('completeTab : déverrouille/avance, et signale le dernier onglet du flux', () => {
|
||||
@@ -189,3 +271,777 @@ describe('useCarrierForm', () => {
|
||||
expect(mockPatch).toHaveBeenCalledWith('/carriers/9', { liotPlates: 'AA-123-BB' }, { toast: false })
|
||||
})
|
||||
})
|
||||
|
||||
describe('useCarrierForm — champs conditionnels (ERP-166)', () => {
|
||||
beforeEach(() => {
|
||||
mockPost.mockReset()
|
||||
mockPatch.mockReset()
|
||||
})
|
||||
|
||||
it('cas LIOT (insensible à la casse) : masque la certification, payload réduit', () => {
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'liot'
|
||||
|
||||
expect(form.isLiot.value).toBe(true)
|
||||
expect(form.showCertification.value).toBe(false)
|
||||
|
||||
form.main.liotPlates = 'AA-123-BB ; CC-456-DD'
|
||||
expect(form.buildMainPayload()).toEqual({
|
||||
name: 'liot',
|
||||
isChartered: false,
|
||||
liotPlates: 'AA-123-BB ; CC-456-DD',
|
||||
})
|
||||
})
|
||||
|
||||
it('LIOT masque les champs conditionnels (affrètement / décharge)', () => {
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'LIOT'
|
||||
form.main.isChartered = true
|
||||
form.main.certificationType = 'AUTRE'
|
||||
|
||||
expect(form.showCharteredFields.value).toBe(false)
|
||||
expect(form.showDischarge.value).toBe(false)
|
||||
})
|
||||
|
||||
it('RG-4.03 affrété : indexation / contenant / volume visibles et dans le payload', () => {
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'Acme'
|
||||
form.main.certificationType = 'GMP_PLUS'
|
||||
form.main.isChartered = true
|
||||
|
||||
expect(form.showCharteredFields.value).toBe(true)
|
||||
|
||||
form.main.indexationRate = '5'
|
||||
form.main.containerType = 'BENNE'
|
||||
form.main.volumeM3 = '30'
|
||||
|
||||
expect(form.buildMainPayload()).toEqual({
|
||||
name: 'Acme',
|
||||
certificationType: 'GMP_PLUS',
|
||||
isChartered: true,
|
||||
indexationRate: '5',
|
||||
containerType: 'BENNE',
|
||||
volumeM3: '30',
|
||||
})
|
||||
})
|
||||
|
||||
it('RG-4.03 affrété, indexation/volume vides : omis du payload (containerType garde son défaut BENNE)', () => {
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'Acme'
|
||||
form.main.certificationType = 'GMP_PLUS'
|
||||
form.main.isChartered = true
|
||||
|
||||
// indexation / volume vides → omis (422 NotBlank back) ; containerType défaut « BENNE » envoyé.
|
||||
expect(form.buildMainPayload()).toEqual({
|
||||
name: 'Acme',
|
||||
certificationType: 'GMP_PLUS',
|
||||
isChartered: true,
|
||||
containerType: 'BENNE',
|
||||
})
|
||||
})
|
||||
|
||||
it('RG-4.02 AUTRE : décharge visible + dischargeDocument dans le payload si IRI résolu', () => {
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'Acme'
|
||||
form.main.certificationType = 'AUTRE'
|
||||
|
||||
expect(form.showDischarge.value).toBe(true)
|
||||
|
||||
form.main.dischargeDocumentIri = '/api/uploaded_documents/7'
|
||||
expect(form.buildMainPayload()).toMatchObject({ dischargeDocument: '/api/uploaded_documents/7' })
|
||||
})
|
||||
|
||||
it('RG-4.02 upload différé : selectDischarge ne POST pas ; submitMain upload PUIS crée', async () => {
|
||||
mockPost.mockReset()
|
||||
// 1er POST = /uploaded_documents (renvoie l'IRI) ; 2e = /carriers (création).
|
||||
mockPost
|
||||
.mockResolvedValueOnce({ '@id': '/api/uploaded_documents/7' })
|
||||
.mockResolvedValueOnce({ id: 12, name: 'ACME', certificationType: 'AUTRE' })
|
||||
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'Acme'
|
||||
form.main.certificationType = 'AUTRE'
|
||||
|
||||
// Sélection du fichier : aucun appel réseau (upload différé à l'enregistrement).
|
||||
form.selectDischarge(new File(['x'], 'decharge.pdf', { type: 'application/pdf' }))
|
||||
expect(mockPost).not.toHaveBeenCalled()
|
||||
// La validation est satisfaite par le fichier en attente (pas encore d'IRI).
|
||||
expect(form.mainErrors.errors.dischargeDocument).toBeUndefined()
|
||||
|
||||
const created = await form.submitMain()
|
||||
expect(created).toBe(true)
|
||||
|
||||
// 1er appel : upload multipart ; 2e : création carrier avec l'IRI résolu.
|
||||
expect(mockPost.mock.calls[0][0]).toBe('/uploaded_documents')
|
||||
expect(mockPost.mock.calls[1][0]).toBe('/carriers')
|
||||
expect(mockPost.mock.calls[1][1]).toMatchObject({ dischargeDocument: '/api/uploaded_documents/7' })
|
||||
})
|
||||
|
||||
it('RG-4.02 upload différé : un 422 MIME bloque la création (message inline, pas de POST /carriers)', async () => {
|
||||
mockPost.mockReset()
|
||||
// Le POST /uploaded_documents échoue (MIME hors whitelist) → 422.
|
||||
mockPost.mockRejectedValueOnce(Object.assign(new Error('422'), {
|
||||
data: { 'hydra:description': 'Type de fichier non autorisé.' },
|
||||
}))
|
||||
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'Acme'
|
||||
form.main.certificationType = 'AUTRE'
|
||||
form.selectDischarge(new File(['x'], 'malware.exe', { type: 'application/x-msdownload' }))
|
||||
|
||||
const created = await form.submitMain()
|
||||
expect(created).toBe(false)
|
||||
// Message back affiché inline sous le champ ; aucune création de carrier.
|
||||
expect(form.mainErrors.errors.dischargeDocument).toBe('Type de fichier non autorisé.')
|
||||
expect(mockPost).toHaveBeenCalledTimes(1)
|
||||
expect(mockPost.mock.calls[0][0]).toBe('/uploaded_documents')
|
||||
})
|
||||
})
|
||||
|
||||
describe('useCarrierForm — copie QUALIMAT (ERP-166)', () => {
|
||||
const QUALIMAT_ROW = {
|
||||
'@id': '/api/qualimat_carriers/42',
|
||||
id: '42',
|
||||
name: 'TRANSPORTS QUALIMAT',
|
||||
siret: '12345678900012',
|
||||
address: '1 rue du Port',
|
||||
postalCode: '86000',
|
||||
city: 'Poitiers',
|
||||
validityDate: '2027-01-15',
|
||||
status: 'VALIDE',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockPost.mockReset()
|
||||
mockPatch.mockReset()
|
||||
})
|
||||
|
||||
it('copie name + certificationType=QUALIMAT (readonly) + IRI + adresse, sans PATCH avant création', async () => {
|
||||
const form = useCarrierForm()
|
||||
|
||||
const ok = await form.applyQualimatSelection(QUALIMAT_ROW)
|
||||
|
||||
expect(ok).toBe(true)
|
||||
expect(mockPatch).not.toHaveBeenCalled()
|
||||
expect(form.main.name).toBe('TRANSPORTS QUALIMAT')
|
||||
expect(form.main.certificationType).toBe('QUALIMAT')
|
||||
expect(form.main.qualimatCarrierIri).toBe('/api/qualimat_carriers/42')
|
||||
expect(form.isQualimat.value).toBe(true)
|
||||
expect(form.certificationReadonly.value).toBe(true)
|
||||
expect(form.qualimatAddress.value).toEqual({
|
||||
country: 'France',
|
||||
postalCode: '86000',
|
||||
city: 'Poitiers',
|
||||
street: '1 rue du Port',
|
||||
})
|
||||
})
|
||||
|
||||
it('après création : PATCH /carriers/{id} avec qualimatCarrier + name + certification', async () => {
|
||||
mockPost.mockResolvedValueOnce({ id: 9, name: 'X', certificationType: 'GMP_PLUS' })
|
||||
mockPatch.mockResolvedValueOnce({})
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'X'
|
||||
form.main.certificationType = 'GMP_PLUS'
|
||||
await form.submitMain()
|
||||
|
||||
const ok = await form.applyQualimatSelection(QUALIMAT_ROW)
|
||||
|
||||
expect(ok).toBe(true)
|
||||
expect(mockPatch).toHaveBeenCalledWith(
|
||||
'/carriers/9',
|
||||
{
|
||||
qualimatCarrier: '/api/qualimat_carriers/42',
|
||||
name: 'TRANSPORTS QUALIMAT',
|
||||
certificationType: 'QUALIMAT',
|
||||
},
|
||||
{ toast: false },
|
||||
)
|
||||
})
|
||||
|
||||
it('après création : PATCH en échec → pas de copie locale (rollback) et retour false', async () => {
|
||||
mockPost.mockResolvedValueOnce({ id: 9, name: 'X', certificationType: 'GMP_PLUS' })
|
||||
mockPatch.mockRejectedValueOnce({ response: { status: 500, _data: {} } })
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'X'
|
||||
form.main.certificationType = 'GMP_PLUS'
|
||||
await form.submitMain()
|
||||
|
||||
const ok = await form.applyQualimatSelection(QUALIMAT_ROW)
|
||||
|
||||
// Échec serveur : l'UI ne doit pas refléter une intégration QUALIMAT non persistée.
|
||||
expect(ok).toBe(false)
|
||||
expect(form.main.name).toBe('X')
|
||||
expect(form.main.certificationType).toBe('GMP_PLUS')
|
||||
expect(form.main.qualimatCarrierIri).toBeNull()
|
||||
})
|
||||
|
||||
it('buildMainPayload inclut qualimatCarrier + certificationType QUALIMAT après intégration', async () => {
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'Acme'
|
||||
await form.applyQualimatSelection(QUALIMAT_ROW)
|
||||
|
||||
expect(form.buildMainPayload()).toMatchObject({
|
||||
qualimatCarrier: '/api/qualimat_carriers/42',
|
||||
certificationType: 'QUALIMAT',
|
||||
})
|
||||
})
|
||||
|
||||
it('applyQualimatSelection pré-remplit l\'adresse unique à la création (RG-4.05)', async () => {
|
||||
const form = useCarrierForm()
|
||||
form.main.name = 'Acme'
|
||||
|
||||
await form.applyQualimatSelection(QUALIMAT_ROW)
|
||||
|
||||
expect(form.address.value).toEqual({
|
||||
id: null,
|
||||
country: 'France',
|
||||
postalCode: '86000',
|
||||
city: 'Poitiers',
|
||||
street: '1 rue du Port',
|
||||
streetComplement: null,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('useCarrierForm — onglet Adresse (ERP-167 / ERP-172 : adresse unique)', () => {
|
||||
beforeEach(() => {
|
||||
mockPost.mockReset()
|
||||
mockPatch.mockReset()
|
||||
mockDelete.mockReset()
|
||||
})
|
||||
|
||||
/** Transporteur créé, onglet Adresse accessible. */
|
||||
function createdForm() {
|
||||
const form = useCarrierForm()
|
||||
form.carrierId.value = 7
|
||||
return form
|
||||
}
|
||||
|
||||
/** Remplit l'unique bloc adresse (CP + ville + rue). */
|
||||
function fillAddress(form: ReturnType<typeof useCarrierForm>): void {
|
||||
const a = form.address.value
|
||||
a.postalCode = '86100'
|
||||
a.city = 'Châtellerault'
|
||||
a.street = '1 rue du Test'
|
||||
}
|
||||
|
||||
it('submitAddress : POST sur /carriers/{id}/address, capture l\'id, finalise l\'onglet', async () => {
|
||||
mockPost.mockResolvedValueOnce({ id: 88 })
|
||||
const form = createdForm()
|
||||
fillAddress(form)
|
||||
|
||||
const ok = await form.submitAddress(vi.fn())
|
||||
|
||||
expect(ok).toBe(true)
|
||||
const [url, body, opts] = mockPost.mock.calls[0] ?? []
|
||||
expect(url).toBe('/carriers/7/address')
|
||||
expect(body).toEqual({
|
||||
country: 'France',
|
||||
postalCode: '86100',
|
||||
city: 'Châtellerault',
|
||||
street: '1 rue du Test',
|
||||
streetComplement: null,
|
||||
})
|
||||
expect(opts).toMatchObject({ toast: false, headers: { Accept: 'application/ld+json' } })
|
||||
expect(form.address.value.id).toBe(88)
|
||||
expect(form.isValidated('addresses')).toBe(true)
|
||||
})
|
||||
|
||||
it('submitAddress : PATCH de l\'adresse existante sur /carrier_addresses/{id}', async () => {
|
||||
mockPatch.mockResolvedValueOnce({})
|
||||
const form = createdForm()
|
||||
fillAddress(form)
|
||||
form.address.value.id = 88
|
||||
|
||||
await form.submitAddress(vi.fn())
|
||||
|
||||
expect(mockPost).not.toHaveBeenCalled()
|
||||
expect(mockPatch).toHaveBeenCalledWith('/carrier_addresses/88', expect.objectContaining({ city: 'Châtellerault' }), { toast: false })
|
||||
})
|
||||
|
||||
it('submitAddress : mappe les 422 inline par champ et ne finalise pas l\'onglet (RG-4.05)', async () => {
|
||||
mockPost.mockRejectedValueOnce({
|
||||
response: {
|
||||
status: 422,
|
||||
_data: { violations: [{ propertyPath: 'city', message: 'La ville est obligatoire pour un transporteur affrété.' }] },
|
||||
},
|
||||
})
|
||||
const form = createdForm()
|
||||
fillAddress(form)
|
||||
|
||||
const ok = await form.submitAddress(vi.fn())
|
||||
|
||||
expect(ok).toBe(false)
|
||||
expect(form.addressErrors.value.city).toBe('La ville est obligatoire pour un transporteur affrété.')
|
||||
expect(form.isValidated('addresses')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('carrierContact (util) — validité alignée M1/M2/M3 + max 2 téléphones', () => {
|
||||
it('isCarrierContactBlank : vrai si vide, faux dès un champ comptant rempli (phoneSecondary exclu)', () => {
|
||||
expect(isCarrierContactBlank(emptyCarrierContact())).toBe(true)
|
||||
expect(isCarrierContactBlank({ ...emptyCarrierContact(), jobTitle: 'Acheteur' })).toBe(false)
|
||||
expect(isCarrierContactBlank({ ...emptyCarrierContact(), phonePrimary: '0102030405' })).toBe(false)
|
||||
// phoneSecondary seul ne compte pas (aligné M1/M2/M3).
|
||||
expect(isCarrierContactBlank({ ...emptyCarrierContact(), phoneSecondary: '0605040302', hasSecondaryPhone: true })).toBe(true)
|
||||
})
|
||||
|
||||
it('isCarrierContactNamed : nommé seulement avec un prénom OU un nom', () => {
|
||||
expect(isCarrierContactNamed(emptyCarrierContact())).toBe(false)
|
||||
expect(isCarrierContactNamed({ ...emptyCarrierContact(), firstName: 'Jean' })).toBe(true)
|
||||
expect(isCarrierContactNamed({ ...emptyCarrierContact(), lastName: 'Doe' })).toBe(true)
|
||||
// Fonction / téléphone / email seuls ne « nomment » pas (≠ RG-4.08 large).
|
||||
expect(isCarrierContactNamed({ ...emptyCarrierContact(), jobTitle: 'Acheteur' })).toBe(false)
|
||||
expect(isCarrierContactNamed({ ...emptyCarrierContact(), email: 'a@b.fr' })).toBe(false)
|
||||
})
|
||||
|
||||
it('buildCarrierContactPayload : phones = 1 numéro sans secondaire', () => {
|
||||
const body = buildCarrierContactPayload({ ...emptyCarrierContact(), phonePrimary: '0102030405' })
|
||||
expect(body.phones).toEqual(['0102030405'])
|
||||
})
|
||||
|
||||
it('buildCarrierContactPayload : phones = 2 numéros si secondaire révélé', () => {
|
||||
const body = buildCarrierContactPayload({
|
||||
...emptyCarrierContact(),
|
||||
phonePrimary: '0102030405',
|
||||
phoneSecondary: '0605040302',
|
||||
hasSecondaryPhone: true,
|
||||
})
|
||||
expect(body.phones).toEqual(['0102030405', '0605040302'])
|
||||
})
|
||||
|
||||
it('buildCarrierContactPayload : 2e numéro ignoré tant que non révélé', () => {
|
||||
const body = buildCarrierContactPayload({
|
||||
...emptyCarrierContact(),
|
||||
phonePrimary: '0102030405',
|
||||
phoneSecondary: '0605040302',
|
||||
hasSecondaryPhone: false,
|
||||
})
|
||||
expect(body.phones).toEqual(['0102030405'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('useCarrierForm — onglet Contacts (ERP-168)', () => {
|
||||
beforeEach(() => {
|
||||
mockPost.mockReset()
|
||||
mockPatch.mockReset()
|
||||
mockDelete.mockReset()
|
||||
})
|
||||
|
||||
/** Transporteur créé, onglet Contacts accessible. */
|
||||
function createdForm() {
|
||||
const form = useCarrierForm()
|
||||
form.carrierId.value = 7
|
||||
return form
|
||||
}
|
||||
|
||||
it('« + Nouveau contact » désactivé tant que le bloc n\'est pas nommé (prénom OU nom, aligné M1/M2/M3)', () => {
|
||||
const form = createdForm()
|
||||
expect(form.canAddContact.value).toBe(false)
|
||||
|
||||
// addContact est un no-op tant que le bloc n'est pas nommé.
|
||||
form.addContact()
|
||||
expect(form.contacts.value).toHaveLength(1)
|
||||
|
||||
// Fonction seule ne suffit PAS à ajouter un nouveau bloc (≠ RG-4.08 large).
|
||||
const first = form.contacts.value[0]
|
||||
if (first) first.jobTitle = 'Acheteur'
|
||||
expect(form.canAddContact.value).toBe(false)
|
||||
form.addContact()
|
||||
expect(form.contacts.value).toHaveLength(1)
|
||||
|
||||
// Un nom (ou prénom) débloque l'ajout.
|
||||
if (first) first.lastName = 'Doe'
|
||||
expect(form.canAddContact.value).toBe(true)
|
||||
form.addContact()
|
||||
expect(form.contacts.value).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('submitContacts : POST des nouveaux contacts (phones tableau), capture id, finalise', async () => {
|
||||
mockPost.mockResolvedValueOnce({ id: 55 })
|
||||
const form = createdForm()
|
||||
const c = form.contacts.value[0]
|
||||
if (c) { c.firstName = 'Jean'; c.phonePrimary = '0102030405' }
|
||||
|
||||
const ok = await form.submitContacts(vi.fn())
|
||||
|
||||
expect(ok).toBe(true)
|
||||
const [url, body, opts] = mockPost.mock.calls[0] ?? []
|
||||
expect(url).toBe('/carriers/7/contacts')
|
||||
expect(body).toMatchObject({ firstName: 'Jean', phones: ['0102030405'] })
|
||||
expect(opts).toMatchObject({ toast: false, headers: { Accept: 'application/ld+json' } })
|
||||
expect(form.contacts.value[0]?.id).toBe(55)
|
||||
expect(form.isValidated('contacts')).toBe(true)
|
||||
})
|
||||
|
||||
it('submitContacts : PATCH des contacts existants sur /carrier_contacts/{id}', async () => {
|
||||
mockPatch.mockResolvedValueOnce({})
|
||||
const form = createdForm()
|
||||
const c = form.contacts.value[0]
|
||||
if (c) { c.id = 55; c.lastName = 'Doe' }
|
||||
|
||||
await form.submitContacts(vi.fn())
|
||||
|
||||
expect(mockPost).not.toHaveBeenCalled()
|
||||
expect(mockPatch).toHaveBeenCalledWith('/carrier_contacts/55', expect.objectContaining({ lastName: 'Doe' }), { toast: false })
|
||||
})
|
||||
|
||||
it('RG-4.08 : onglet vide → soumet l\'amorce pour déclencher la 422 inline', async () => {
|
||||
mockPost.mockRejectedValueOnce({
|
||||
response: {
|
||||
status: 422,
|
||||
_data: { violations: [{ propertyPath: 'firstName', message: 'Au moins un champ du contact est obligatoire.' }] },
|
||||
},
|
||||
})
|
||||
const form = createdForm()
|
||||
|
||||
const ok = await form.submitContacts(vi.fn())
|
||||
|
||||
expect(ok).toBe(false)
|
||||
expect(mockPost).toHaveBeenCalledTimes(1)
|
||||
expect(form.contactErrors.value[0]?.firstName).toBe('Au moins un champ du contact est obligatoire.')
|
||||
expect(form.isValidated('contacts')).toBe(false)
|
||||
})
|
||||
|
||||
it('removeContact : DELETE /carrier_contacts/{id} puis retrait du bloc', async () => {
|
||||
mockDelete.mockResolvedValueOnce({})
|
||||
const form = createdForm()
|
||||
const c = form.contacts.value[0]
|
||||
if (c) { c.id = 90; c.lastName = 'Doe' }
|
||||
form.addContact()
|
||||
const c2 = form.contacts.value[1]
|
||||
if (c2) c2.firstName = 'Jean'
|
||||
|
||||
await form.removeContact(0)
|
||||
|
||||
expect(mockDelete).toHaveBeenCalledWith('/carrier_contacts/90', {}, { toast: false })
|
||||
expect(form.contacts.value).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('carrierPrice (util) — bascule CLIENT/FOURNISSEUR + champs requis par branche', () => {
|
||||
const CLIENT = '/api/clients/3'
|
||||
const CLIENT_ADDR = '/api/client_addresses/8'
|
||||
const SUPPLIER = '/api/suppliers/5'
|
||||
const SUPPLIER_ADDR = '/api/supplier_addresses/9'
|
||||
const SITE = '/api/sites/1'
|
||||
|
||||
it('buildCarrierPricePayload CLIENT : branche client envoyée, branche fournisseur à null', () => {
|
||||
const body = buildCarrierPricePayload({
|
||||
...emptyCarrierPrice(),
|
||||
direction: 'CLIENT',
|
||||
clientIri: CLIENT,
|
||||
clientDeliveryAddressIri: CLIENT_ADDR,
|
||||
departureSiteIri: SITE,
|
||||
containerType: 'BENNE',
|
||||
pricingUnit: 'FORFAIT',
|
||||
price: '120.00',
|
||||
priceState: 'EN_COURS',
|
||||
})
|
||||
expect(body).toMatchObject({
|
||||
direction: 'CLIENT',
|
||||
client: CLIENT,
|
||||
clientDeliveryAddress: CLIENT_ADDR,
|
||||
departureSite: SITE,
|
||||
supplier: null,
|
||||
supplierSupplyAddress: null,
|
||||
deliverySite: null,
|
||||
containerType: 'BENNE',
|
||||
pricingUnit: 'FORFAIT',
|
||||
price: '120.00',
|
||||
priceState: 'EN_COURS',
|
||||
})
|
||||
})
|
||||
|
||||
it('buildCarrierPricePayload FOURNISSEUR : branche fournisseur envoyée, branche client à null', () => {
|
||||
const body = buildCarrierPricePayload({
|
||||
...emptyCarrierPrice(),
|
||||
direction: 'FOURNISSEUR',
|
||||
supplierIri: SUPPLIER,
|
||||
supplierSupplyAddressIri: SUPPLIER_ADDR,
|
||||
deliverySiteIri: SITE,
|
||||
containerType: 'FOND_MOUVANT',
|
||||
pricingUnit: 'TONNE',
|
||||
price: '45',
|
||||
priceState: 'VALIDE',
|
||||
})
|
||||
expect(body).toMatchObject({
|
||||
direction: 'FOURNISSEUR',
|
||||
supplier: SUPPLIER,
|
||||
supplierSupplyAddress: SUPPLIER_ADDR,
|
||||
deliverySite: SITE,
|
||||
client: null,
|
||||
clientDeliveryAddress: null,
|
||||
departureSite: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('isCarrierPriceValid : faux si branche incomplète, vrai si branche complète + communs', () => {
|
||||
const base = { ...emptyCarrierPrice(), containerType: 'BENNE', pricingUnit: 'FORFAIT', price: '10', priceState: 'EN_COURS' }
|
||||
// Direction non choisie → invalide.
|
||||
expect(isCarrierPriceValid({ ...base, direction: null })).toBe(false)
|
||||
// Sens CLIENT par défaut mais branche incomplète → invalide.
|
||||
expect(isCarrierPriceValid(base)).toBe(false)
|
||||
// CLIENT sans adresse/site → invalide.
|
||||
expect(isCarrierPriceValid({ ...base, direction: 'CLIENT', clientIri: CLIENT })).toBe(false)
|
||||
// CLIENT complet → valide.
|
||||
expect(isCarrierPriceValid({ ...base, direction: 'CLIENT', clientIri: CLIENT, clientDeliveryAddressIri: CLIENT_ADDR, departureSiteIri: SITE })).toBe(true)
|
||||
// FOURNISSEUR complet → valide.
|
||||
expect(isCarrierPriceValid({ ...base, direction: 'FOURNISSEUR', supplierIri: SUPPLIER, supplierSupplyAddressIri: SUPPLIER_ADDR, deliverySiteIri: SITE })).toBe(true)
|
||||
// Prix manquant → invalide même branche complète.
|
||||
expect(isCarrierPriceValid({ ...emptyCarrierPrice(), direction: 'CLIENT', clientIri: CLIENT, clientDeliveryAddressIri: CLIENT_ADDR, departureSiteIri: SITE, containerType: 'BENNE', pricingUnit: 'FORFAIT', priceState: 'EN_COURS' })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useCarrierForm — onglet Prix (ERP-169)', () => {
|
||||
beforeEach(() => {
|
||||
mockPost.mockReset()
|
||||
mockPatch.mockReset()
|
||||
mockDelete.mockReset()
|
||||
})
|
||||
|
||||
function createdForm() {
|
||||
const form = useCarrierForm()
|
||||
form.carrierId.value = 7
|
||||
return form
|
||||
}
|
||||
|
||||
it('démarre avec un bloc CLIENT par défaut ; « + Nouveau prix » bloqué tant qu\'il est incomplet', () => {
|
||||
const form = createdForm()
|
||||
// Un bloc présent d'office, sens CLIENT pré-sélectionné.
|
||||
expect(form.prices.value).toHaveLength(1)
|
||||
expect(form.prices.value[0]?.direction).toBe('CLIENT')
|
||||
// Bloc incomplet → on ne peut pas en ajouter un autre.
|
||||
expect(form.canAddPrice.value).toBe(false)
|
||||
form.addPrice()
|
||||
expect(form.prices.value).toHaveLength(1)
|
||||
|
||||
// Une fois le bloc complété, l'ajout est autorisé.
|
||||
const p = form.prices.value[0]
|
||||
if (p) {
|
||||
p.clientIri = '/api/clients/3'
|
||||
p.clientDeliveryAddressIri = '/api/client_addresses/8'
|
||||
p.departureSiteIri = '/api/sites/1'
|
||||
p.price = '120'
|
||||
p.priceState = 'EN_COURS'
|
||||
}
|
||||
expect(form.canAddPrice.value).toBe(true)
|
||||
form.addPrice()
|
||||
expect(form.prices.value).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('submitPrices : POST des nouveaux prix (branche CLIENT), capture l\'id, finalise', async () => {
|
||||
mockPost.mockResolvedValueOnce({ id: 50 })
|
||||
const form = createdForm()
|
||||
form.addPrice()
|
||||
const p = form.prices.value[0]
|
||||
if (p) {
|
||||
p.direction = 'CLIENT'
|
||||
p.clientIri = '/api/clients/3'
|
||||
p.clientDeliveryAddressIri = '/api/client_addresses/8'
|
||||
p.departureSiteIri = '/api/sites/1'
|
||||
p.containerType = 'BENNE'
|
||||
p.pricingUnit = 'FORFAIT'
|
||||
p.price = '120'
|
||||
p.priceState = 'EN_COURS'
|
||||
}
|
||||
|
||||
const ok = await form.submitPrices(vi.fn())
|
||||
|
||||
expect(ok).toBe(true)
|
||||
const [url, body, opts] = mockPost.mock.calls[0] ?? []
|
||||
expect(url).toBe('/carriers/7/prices')
|
||||
expect(body).toMatchObject({ direction: 'CLIENT', client: '/api/clients/3', supplier: null })
|
||||
expect(opts).toMatchObject({ toast: false, headers: { Accept: 'application/ld+json' } })
|
||||
expect(form.prices.value[0]?.id).toBe(50)
|
||||
expect(form.isValidated('prices')).toBe(true)
|
||||
})
|
||||
|
||||
it('submitPrices : PATCH des prix existants sur /carrier_prices/{id}', async () => {
|
||||
mockPatch.mockResolvedValueOnce({})
|
||||
const form = createdForm()
|
||||
const p = form.prices.value[0]
|
||||
if (p) {
|
||||
p.id = 50
|
||||
p.direction = 'FOURNISSEUR'
|
||||
p.supplierIri = '/api/suppliers/5'
|
||||
p.supplierSupplyAddressIri = '/api/supplier_addresses/9'
|
||||
p.deliverySiteIri = '/api/sites/1'
|
||||
p.price = '10'
|
||||
p.priceState = 'VALIDE'
|
||||
}
|
||||
|
||||
await form.submitPrices(vi.fn())
|
||||
|
||||
expect(mockPost).not.toHaveBeenCalled()
|
||||
expect(mockPatch).toHaveBeenCalledWith('/carrier_prices/50', expect.objectContaining({ direction: 'FOURNISSEUR' }), { toast: false })
|
||||
})
|
||||
|
||||
it('front : bloc prix incomplet → erreurs inline sous chaque champ requis, pas d\'appel back', async () => {
|
||||
const form = createdForm()
|
||||
// Bloc CLIENT par défaut, rien d'autre rempli.
|
||||
const ok = await form.submitPrices(vi.fn())
|
||||
|
||||
expect(ok).toBe(false)
|
||||
expect(mockPost).not.toHaveBeenCalled()
|
||||
const errs = form.priceErrors.value[0]
|
||||
expect(errs?.client).toBeTruthy()
|
||||
expect(errs?.clientDeliveryAddress).toBeTruthy()
|
||||
expect(errs?.departureSite).toBeTruthy()
|
||||
expect(errs?.price).toBeTruthy()
|
||||
expect(errs?.priceState).toBeTruthy()
|
||||
})
|
||||
|
||||
it('submitPrices : mappe les 422 back par ligne (appartenance adresse) et ne finalise pas', async () => {
|
||||
mockPost.mockRejectedValueOnce({
|
||||
response: { status: 422, _data: { violations: [{ propertyPath: 'clientDeliveryAddress', message: 'L\'adresse de livraison doit appartenir au client selectionne.' }] } },
|
||||
})
|
||||
const form = createdForm()
|
||||
// Tous les champs requis remplis (le pré-check front passe) ; le back 422 sur
|
||||
// une RG qu'il est seul à connaître (appartenance de l'adresse au client).
|
||||
const p = form.prices.value[0]
|
||||
if (p) {
|
||||
p.direction = 'CLIENT'
|
||||
p.clientIri = '/api/clients/3'
|
||||
p.clientDeliveryAddressIri = '/api/client_addresses/8'
|
||||
p.departureSiteIri = '/api/sites/1'
|
||||
p.price = '10'
|
||||
p.priceState = 'EN_COURS'
|
||||
}
|
||||
|
||||
const ok = await form.submitPrices(vi.fn())
|
||||
|
||||
expect(ok).toBe(false)
|
||||
expect(form.priceErrors.value[0]?.clientDeliveryAddress).toBe('L\'adresse de livraison doit appartenir au client selectionne.')
|
||||
expect(form.isValidated('prices')).toBe(false)
|
||||
})
|
||||
|
||||
it('removePrice : DELETE /carrier_prices/{id} puis retrait du bloc', async () => {
|
||||
mockDelete.mockResolvedValueOnce({})
|
||||
const form = createdForm()
|
||||
form.addPrice()
|
||||
const p = form.prices.value[0]
|
||||
if (p) { p.id = 77; p.direction = 'CLIENT'; p.clientIri = '/api/clients/3'; p.clientDeliveryAddressIri = '/api/client_addresses/8'; p.departureSiteIri = '/api/sites/1'; p.containerType = 'BENNE'; p.pricingUnit = 'FORFAIT'; p.price = '10'; p.priceState = 'EN_COURS' }
|
||||
form.addPrice()
|
||||
|
||||
await form.removePrice(0)
|
||||
|
||||
expect(mockDelete).toHaveBeenCalledWith('/carrier_prices/77', {}, { toast: false })
|
||||
expect(form.prices.value).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useCarrierForm — édition (ERP-170)', () => {
|
||||
beforeEach(() => {
|
||||
mockPost.mockReset()
|
||||
mockPatch.mockReset()
|
||||
})
|
||||
|
||||
it('prefillFrom : peuple carrierId + principal + sous-collections, passe en editMode', () => {
|
||||
const form = useCarrierForm()
|
||||
form.prefillFrom({
|
||||
'@id': '/api/carriers/7',
|
||||
id: 7,
|
||||
name: 'TRANSPORTS ACME',
|
||||
certificationType: 'GMP_PLUS',
|
||||
address: { '@id': '/api/carrier_addresses/3', id: 3, city: 'Poitiers' },
|
||||
contacts: [{ '@id': '/api/carrier_contacts/9', id: 9, lastName: 'Doe', phonePrimary: '0102030405' }],
|
||||
prices: [{ '@id': '/api/carrier_prices/5', id: 5, direction: 'CLIENT', client: { '@id': '/api/clients/3' }, containerType: 'BENNE', pricingUnit: 'FORFAIT', price: '120', priceState: 'EN_COURS' }],
|
||||
})
|
||||
|
||||
expect(form.carrierId.value).toBe(7)
|
||||
expect(form.editMode.value).toBe(true)
|
||||
expect(form.main.name).toBe('TRANSPORTS ACME')
|
||||
expect(form.main.certificationType).toBe('GMP_PLUS')
|
||||
expect(form.address.value.id).toBe(3)
|
||||
expect(form.contacts.value[0]?.id).toBe(9)
|
||||
expect(form.prices.value[0]?.clientIri).toBe('/api/clients/3')
|
||||
})
|
||||
|
||||
it('updateMain : PATCH /carriers/{id} (pas de POST), réaffiche le nom normalisé', async () => {
|
||||
mockPatch.mockResolvedValueOnce({ id: 7, name: 'TRANSPORTS ACME', certificationType: 'GMP_PLUS' })
|
||||
const form = useCarrierForm()
|
||||
form.prefillFrom({ '@id': '/api/carriers/7', id: 7, name: 'Transports Acme', certificationType: 'GMP_PLUS' })
|
||||
|
||||
const ok = await form.updateMain()
|
||||
|
||||
expect(ok).toBe(true)
|
||||
expect(mockPost).not.toHaveBeenCalled()
|
||||
expect(mockPatch).toHaveBeenCalledWith(
|
||||
'/carriers/7',
|
||||
expect.objectContaining({ name: 'Transports Acme', certificationType: 'GMP_PLUS' }),
|
||||
{ toast: false },
|
||||
)
|
||||
expect(form.main.name).toBe('TRANSPORTS ACME')
|
||||
})
|
||||
})
|
||||
|
||||
describe('useCarrierForm — modification : Qualimat + certification (ERP-172)', () => {
|
||||
const QUALIMAT_ROW = {
|
||||
'@id': '/api/qualimat_carriers/42',
|
||||
id: '42',
|
||||
name: 'TRANSPORTS QUALIMAT',
|
||||
address: '1 rue du Port',
|
||||
postalCode: '86000',
|
||||
city: 'Poitiers',
|
||||
validityDate: '2027-01-15',
|
||||
status: 'VALIDE',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockPost.mockReset()
|
||||
mockPatch.mockReset()
|
||||
})
|
||||
|
||||
it('setCertification : quitter QUALIMAT délie la FK qualimatCarrier', () => {
|
||||
const form = useCarrierForm()
|
||||
form.main.qualimatCarrierIri = '/api/qualimat_carriers/42'
|
||||
form.main.certificationType = 'QUALIMAT'
|
||||
|
||||
form.setCertification('GMP_PLUS')
|
||||
|
||||
expect(form.main.certificationType).toBe('GMP_PLUS')
|
||||
expect(form.main.qualimatCarrierIri).toBeNull()
|
||||
})
|
||||
|
||||
it('certificationReadonly : éditable en modification même pour un QUALIMAT', () => {
|
||||
const form = useCarrierForm()
|
||||
form.prefillFrom({
|
||||
'@id': '/api/carriers/7', id: 7, name: 'ACME', certificationType: 'QUALIMAT',
|
||||
qualimatCarrier: { '@id': '/api/qualimat_carriers/42' },
|
||||
})
|
||||
expect(form.isQualimat.value).toBe(true)
|
||||
expect(form.certificationReadonly.value).toBe(false)
|
||||
})
|
||||
|
||||
it('buildMainPayload : en modification, délie le Qualimat (qualimatCarrier: null) sans lien', () => {
|
||||
const form = useCarrierForm()
|
||||
form.prefillFrom({
|
||||
'@id': '/api/carriers/7', id: 7, name: 'ACME', certificationType: 'QUALIMAT',
|
||||
qualimatCarrier: { '@id': '/api/qualimat_carriers/42' },
|
||||
})
|
||||
form.setCertification('GMP_PLUS')
|
||||
|
||||
expect(form.buildMainPayload()).toMatchObject({ certificationType: 'GMP_PLUS', qualimatCarrier: null })
|
||||
})
|
||||
|
||||
it('applyQualimatSelection : en modification, conserve l\'adresse existante (PATCH nom/certif/FK)', async () => {
|
||||
mockPatch.mockResolvedValueOnce({})
|
||||
const form = useCarrierForm()
|
||||
form.prefillFrom({
|
||||
'@id': '/api/carriers/7', id: 7, name: 'OLD', certificationType: 'GMP_PLUS',
|
||||
address: { '@id': '/api/carrier_addresses/3', id: 3, city: 'Poitiers', street: 'rue A' },
|
||||
})
|
||||
const addressBefore = { ...form.address.value }
|
||||
|
||||
const ok = await form.applyQualimatSelection(QUALIMAT_ROW)
|
||||
|
||||
expect(ok).toBe(true)
|
||||
// Décision « conserver » (ERP-172) : l'adresse n'est pas réécrite en modification.
|
||||
expect(form.address.value).toEqual(addressBefore)
|
||||
// Nom + certification + FK actualisés via PATCH.
|
||||
expect(form.main.name).toBe('TRANSPORTS QUALIMAT')
|
||||
expect(form.main.certificationType).toBe('QUALIMAT')
|
||||
expect(form.main.qualimatCarrierIri).toBe('/api/qualimat_carriers/42')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -50,7 +50,7 @@ describe('useCarriersRepository', () => {
|
||||
expect(mockApiGet).toHaveBeenCalledTimes(1)
|
||||
const [url, query, opts] = mockApiGet.mock.calls[0]
|
||||
expect(url).toBe('/carriers')
|
||||
expect(query).toMatchObject({ page: 1, itemsPerPage: 10 })
|
||||
expect(query).toMatchObject({ page: 1, itemsPerPage: 25 })
|
||||
expect(opts).toMatchObject({
|
||||
toast: false,
|
||||
headers: { Accept: 'application/ld+json' },
|
||||
|
||||
@@ -0,0 +1,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),
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,35 @@
|
||||
import { reactive, ref } from 'vue'
|
||||
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) —
|
||||
@@ -42,18 +67,46 @@ export function useCarrierForm() {
|
||||
// Erreurs de validation par champ (ERP-101) du formulaire principal.
|
||||
const mainErrors = useFormErrors()
|
||||
|
||||
// Upload de la décharge (RG-4.02) — infra partagée /api/uploaded_documents.
|
||||
// L'upload est DIFFÉRÉ : le fichier choisi attend ici jusqu'à l'enregistrement.
|
||||
const { uploading: dischargeUploading, upload: uploadFile } = useUpload()
|
||||
const pendingDischargeFile = ref<File | null>(null)
|
||||
|
||||
// ── État du transporteur créé ─────────────────────────────────────────────
|
||||
const carrierId = ref<number | null>(null)
|
||||
const mainLocked = ref(false)
|
||||
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é (-1 tant que le transporteur n'est pas créé).
|
||||
const unlockedIndex = ref(-1)
|
||||
// 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>>({})
|
||||
@@ -71,10 +124,11 @@ export function useCarrierForm() {
|
||||
|
||||
/**
|
||||
* Validation FRONT du formulaire principal : seul le nom est requis côté front
|
||||
* (RG-4.01). Le back reste la couche autoritaire (ERP-101) — la certification
|
||||
* obligatoire (sauf LIOT) et les RG conditionnelles sont re-validées serveur et
|
||||
* remontées en 422 inline, sans pré-check front (qui devrait connaître le cas
|
||||
* LIOT, hors périmètre ERP-165).
|
||||
* (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
|
||||
@@ -82,9 +136,96 @@ export function useCarrierForm() {
|
||||
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
|
||||
@@ -92,22 +233,58 @@ export function useCarrierForm() {
|
||||
* certification) sur le champ plutôt qu'une erreur de type.
|
||||
*/
|
||||
function buildMainPayload(): Record<string, unknown> {
|
||||
const payload: Record<string, unknown> = {
|
||||
isChartered: main.isChartered,
|
||||
// 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
|
||||
}
|
||||
if (main.name?.trim()) {
|
||||
|
||||
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 (nom), puis
|
||||
* création. Au succès : verrouille le bloc principal, déverrouille le 1er onglet
|
||||
* et bascule sur « Qualimat ». Retourne true si créé, false sinon.
|
||||
* 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
|
||||
@@ -116,6 +293,9 @@ export function useCarrierForm() {
|
||||
|
||||
mainSubmitting.value = true
|
||||
try {
|
||||
// Upload différé de la décharge : envoyé seulement maintenant (au Valider).
|
||||
if (!(await resolveDischargeUpload())) return false
|
||||
|
||||
const created = await api.post<CarrierMainResponse>('/carriers', buildMainPayload(), {
|
||||
headers: { Accept: 'application/ld+json' },
|
||||
toast: false,
|
||||
@@ -128,8 +308,9 @@ export function useCarrierForm() {
|
||||
main.certificationType = created.certificationType ?? main.certificationType
|
||||
|
||||
mainLocked.value = true
|
||||
unlockedIndex.value = 0
|
||||
activeTab.value = tabKeys.value[0] ?? CARRIER_TAB_KEYS[0]
|
||||
// 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
|
||||
}
|
||||
@@ -152,6 +333,71 @@ export function useCarrierForm() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* MODIFICATION du formulaire principal (ERP-170) : PATCH /api/carriers/{id} sur le
|
||||
* groupe carrier:write:main (PAS de re-POST). Pré-check front + 409 doublon / 422
|
||||
* inline comme `submitMain`. Ne verrouille rien et ne bascule pas d'onglet (édition
|
||||
* = navigation libre). Retourne true si le PATCH a réussi.
|
||||
*/
|
||||
async function updateMain(): Promise<boolean> {
|
||||
if (carrierId.value === null || mainSubmitting.value) return false
|
||||
mainErrors.clearErrors()
|
||||
if (!validateMainFront()) return false
|
||||
|
||||
mainSubmitting.value = true
|
||||
try {
|
||||
// Upload différé de la décharge : envoyé seulement maintenant (à l'Enregistrer).
|
||||
if (!(await resolveDischargeUpload())) return false
|
||||
|
||||
const updated = await api.patch<CarrierMainResponse>(
|
||||
`/carriers/${carrierId.value}`,
|
||||
buildMainPayload(),
|
||||
{ toast: false },
|
||||
)
|
||||
main.name = updated.name ?? main.name
|
||||
main.certificationType = updated.certificationType ?? main.certificationType
|
||||
return true
|
||||
}
|
||||
catch (error) {
|
||||
const status = (error as { response?: { status?: number } })?.response?.status
|
||||
if (status === 409) {
|
||||
const message = t('transport.carriers.form.duplicateName')
|
||||
mainErrors.setError('name', message)
|
||||
toast.error({ title: t('transport.carriers.toast.error'), message })
|
||||
}
|
||||
else {
|
||||
mainErrors.handleApiError(error, { fallbackMessage: t('transport.carriers.toast.error') })
|
||||
}
|
||||
return false
|
||||
}
|
||||
finally {
|
||||
mainSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pré-remplit le formulaire depuis le détail `GET /api/carriers/{id}` (écran
|
||||
* Modification) : peuple carrierId + principal + adresses / contacts / prix via les
|
||||
* mappers, passe en `editMode` (navigation libre, tous onglets accessibles, bloc
|
||||
* principal éditable). Au moins un bloc Adresse / Contact affiché même sans donnée.
|
||||
*/
|
||||
function prefillFrom(detail: CarrierDetail): void {
|
||||
carrierId.value = detail.id
|
||||
editMode.value = true
|
||||
mainLocked.value = false
|
||||
unlockedIndex.value = tabKeys.value.length - 1
|
||||
|
||||
Object.assign(main, mapMainToDraft(detail))
|
||||
|
||||
// Adresse UNIQUE (ERP-172) : objet `address` (ou null) au lieu d'une liste.
|
||||
address.value = detail.address ? mapAddressToDraft(detail.address) : emptyCarrierAddress()
|
||||
|
||||
const mappedContacts = (detail.contacts ?? []).map(mapContactToDraft)
|
||||
contacts.value = mappedContacts.length > 0 ? mappedContacts : [emptyCarrierContact()]
|
||||
|
||||
prices.value = (detail.prices ?? []).map(mapPriceToDraft)
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH partiel du transporteur (mode strict : un seul groupe de sérialisation
|
||||
* par appel — spec-back § 2.9). Servira les onglets à champs scalaires des
|
||||
@@ -162,6 +408,353 @@ export function useCarrierForm() {
|
||||
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
|
||||
@@ -186,10 +779,20 @@ export function useCarrierForm() {
|
||||
return {
|
||||
// état
|
||||
main,
|
||||
qualimatAddress,
|
||||
carrierId,
|
||||
mainLocked,
|
||||
mainSubmitting,
|
||||
tabSubmitting,
|
||||
mainErrors,
|
||||
dischargeUploading,
|
||||
// affichage conditionnel
|
||||
isLiot,
|
||||
isQualimat,
|
||||
showCertification,
|
||||
certificationReadonly,
|
||||
showCharteredFields,
|
||||
showDischarge,
|
||||
// onglets
|
||||
tabKeys,
|
||||
activeTab,
|
||||
@@ -197,11 +800,36 @@ export function useCarrierForm() {
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,5 +66,6 @@ export interface CarrierFilters {
|
||||
* `usePaginatedList`. Aucun reset au logout a gerer.
|
||||
*/
|
||||
export function useCarriersRepository() {
|
||||
return usePaginatedList<Carrier, CarrierFilters>({ url: '/carriers' })
|
||||
// Pagination par defaut a 25 sur le repertoire (retour metier ERP-193).
|
||||
return usePaginatedList<Carrier, CarrierFilters>({ url: '/carriers', defaultItemsPerPage: 25 })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,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,442 @@
|
||||
<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
|
||||
:model-value="main.name"
|
||||
@update:model-value="(v: string) => main.name = sanitizeFreeText(v)"
|
||||
:label="t('transport.carriers.form.main.name')"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.name"
|
||||
/>
|
||||
<!-- Cas LIOT : le champ immatriculations occupe les colonnes restantes
|
||||
de la ligne (3 en xl, 2 sinon). Wrapper pour le col-span car
|
||||
MalioInputText (inheritAttrs:false) renvoie `class` sur l'input. -->
|
||||
<div v-if="isLiot" class="col-span-2 xl:col-span-3">
|
||||
<MalioInputText
|
||||
:key="liotPlatesKey"
|
||||
:model-value="main.liotPlates"
|
||||
@update:model-value="onLiotPlatesInput"
|
||||
:label="t('transport.carriers.form.main.liotPlates')"
|
||||
:hint="t('transport.carriers.form.main.liotPlatesHint')"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.liotPlates"
|
||||
/>
|
||||
</div>
|
||||
<template v-if="!isLiot">
|
||||
<MalioSelect
|
||||
:model-value="main.certificationType"
|
||||
:options="certificationOptions"
|
||||
:label="t('transport.carriers.form.main.certificationType')"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:disabled="certificationReadonly"
|
||||
:error="mainErrors.errors.certificationType"
|
||||
@update:model-value="(v: string | number | null) => setCertification(v === null ? null : String(v))"
|
||||
/>
|
||||
<MalioInputUpload
|
||||
v-if="showDischarge"
|
||||
:model-value="dischargeFileName"
|
||||
:label="t('transport.carriers.form.main.discharge')"
|
||||
accept="application/pdf,image/*"
|
||||
:required="true"
|
||||
:disabled="dischargeUploading"
|
||||
:clearable="true"
|
||||
:error="mainErrors.errors.dischargeDocument"
|
||||
@update:model-value="(v: string) => dischargeFileName = v"
|
||||
@file-selected="selectDischarge"
|
||||
@clear="onClearDischarge"
|
||||
/>
|
||||
<div v-else class="hidden xl:block"></div>
|
||||
<div class="flex h-12 items-center">
|
||||
<MalioCheckbox
|
||||
id="carrier-edit-chartered"
|
||||
:label="t('transport.carriers.form.main.isChartered')"
|
||||
:model-value="main.isChartered"
|
||||
:reserve-message-space="false"
|
||||
@update:model-value="(val: boolean) => main.isChartered = val"
|
||||
/>
|
||||
</div>
|
||||
<template v-if="showCharteredFields">
|
||||
<MalioInputAmount
|
||||
:key="indexationKey"
|
||||
:model-value="main.indexationRate"
|
||||
:label="t('transport.carriers.form.main.indexationRate')"
|
||||
icon-name="mdi:percent"
|
||||
icon-position="right"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.indexationRate"
|
||||
@update:model-value="onIndexationInput"
|
||||
/>
|
||||
<!-- Contenant : Benne / Fond mouvant en radios, centrés (h-12) comme
|
||||
à l'onglet Prix (Benne par défaut). -->
|
||||
<div>
|
||||
<div class="flex h-12 items-center gap-4">
|
||||
<MalioRadioButton
|
||||
:model-value="main.containerType"
|
||||
name="carrier-main-container"
|
||||
value="BENNE"
|
||||
:label="t('transport.carriers.containerType.BENNE')"
|
||||
group-class="mt-0"
|
||||
@update:model-value="(v: string | number | boolean | null) => main.containerType = v === null ? null : String(v)"
|
||||
/>
|
||||
<MalioRadioButton
|
||||
:model-value="main.containerType"
|
||||
name="carrier-main-container"
|
||||
value="FOND_MOUVANT"
|
||||
:label="t('transport.carriers.containerType.FOND_MOUVANT')"
|
||||
group-class="mt-0"
|
||||
@update:model-value="(v: string | number | boolean | null) => main.containerType = v === null ? null : String(v)"
|
||||
/>
|
||||
</div>
|
||||
<p v-if="mainErrors.errors.containerType" class="ml-[2px] text-xs text-m-danger">{{ mainErrors.errors.containerType }}</p>
|
||||
</div>
|
||||
<MalioInputText
|
||||
:model-value="main.volumeM3"
|
||||
:label="t('transport.carriers.form.main.volumeM3')"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.volumeM3"
|
||||
@update:model-value="(v: string) => main.volumeM3 = sanitizeDecimal(v)"
|
||||
/>
|
||||
</template>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="mt-12 flex justify-center">
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('transport.carriers.edit.save')"
|
||||
:disabled="mainSubmitting"
|
||||
@click="onUpdateMain"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- ── Onglets éditables (navigation libre, PATCH partiel par onglet) ── -->
|
||||
<MalioTabList v-model="activeTab" :tabs="tabs" class="mt-[60px]">
|
||||
<!-- Qualimat : actualiser nom + certification depuis le référentiel (ERP-172). -->
|
||||
<template #qualimat>
|
||||
<CarrierQualimatTab
|
||||
:search-name="main.name"
|
||||
:selected-iri="main.qualimatCarrierIri"
|
||||
@integrate="onIntegrateQualimat"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template #addresses>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
<!-- Adresse UNIQUE (ERP-172) : un seul bloc, sans ajouter/supprimer. -->
|
||||
<CarrierAddressBlock
|
||||
:model-value="address"
|
||||
:country-options="countryOptions"
|
||||
:errors="addressErrors"
|
||||
@update:model-value="(v) => address = v"
|
||||
@degraded="onAddressDegraded"
|
||||
/>
|
||||
<div class="flex justify-center gap-6">
|
||||
<MalioButton variant="primary" :label="t('transport.carriers.edit.save')" :disabled="tabSubmitting" @click="onSubmitAddresses" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #contacts>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
<CarrierContactBlock
|
||||
v-for="(contact, index) in contacts"
|
||||
:key="index"
|
||||
:model-value="contact"
|
||||
:removable="isRowRemovable(contacts, index)"
|
||||
:errors="contactErrors[index]"
|
||||
@update:model-value="(v) => contacts[index] = v"
|
||||
@remove="askRemoveContact(index)"
|
||||
/>
|
||||
<div class="flex justify-center gap-6">
|
||||
<MalioButton variant="secondary" icon-name="mdi:add-bold" icon-position="left" :label="t('transport.carriers.form.contact.add')" :disabled="!canAddContact" @click="addContact" />
|
||||
<MalioButton variant="primary" :label="t('transport.carriers.edit.save')" :disabled="tabSubmitting" @click="onSubmitContacts" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #prices>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
<CarrierPriceBlock
|
||||
v-for="(price, index) in prices"
|
||||
:key="index"
|
||||
:model-value="price"
|
||||
:client-options="clientOptions"
|
||||
:supplier-options="supplierOptions"
|
||||
:site-options="siteOptions"
|
||||
removable
|
||||
:errors="priceErrors[index]"
|
||||
@update:model-value="(v) => prices[index] = v"
|
||||
@remove="askRemovePrice(index)"
|
||||
/>
|
||||
<div class="flex justify-center gap-6">
|
||||
<MalioButton variant="secondary" icon-name="mdi:add-bold" icon-position="left" :label="t('transport.carriers.form.price.add')" :disabled="!canAddPrice" @click="addPrice" />
|
||||
<MalioButton variant="primary" :label="t('transport.carriers.edit.save')" :disabled="tabSubmitting" @click="onSubmitPrices" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</MalioTabList>
|
||||
</template>
|
||||
|
||||
<!-- Modal de confirmation de suppression de bloc. -->
|
||||
<MalioModal v-model="deleteConfirm.open" modal-class="max-w-md">
|
||||
<template #header>
|
||||
<h2 class="text-[24px] font-bold">{{ t('transport.carriers.form.confirmDelete.title') }}</h2>
|
||||
</template>
|
||||
<p>{{ t('transport.carriers.form.confirmDelete.message') }}</p>
|
||||
<template #footer>
|
||||
<MalioButton variant="secondary" button-class="flex-1" :label="t('transport.carriers.form.confirmDelete.cancel')" @click="deleteConfirm.open = false" />
|
||||
<MalioButton variant="danger" button-class="flex-1" :label="t('transport.carriers.form.confirmDelete.confirm')" @click="runDeleteConfirm" />
|
||||
</template>
|
||||
</MalioModal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { extractApiErrorMessage } from '~/shared/utils/api'
|
||||
import { isRowRemovable } from '~/shared/utils/collectionRow'
|
||||
import CarrierAddressBlock from '~/modules/transport/components/CarrierAddressBlock.vue'
|
||||
import CarrierContactBlock from '~/modules/transport/components/CarrierContactBlock.vue'
|
||||
import CarrierPriceBlock from '~/modules/transport/components/CarrierPriceBlock.vue'
|
||||
import CarrierQualimatTab from '~/modules/transport/components/CarrierQualimatTab.vue'
|
||||
import { useCarrierForm } from '~/modules/transport/composables/useCarrierForm'
|
||||
import { useCarrier } from '~/modules/transport/composables/useCarrier'
|
||||
import type { QualimatCarrierRow } from '~/modules/transport/composables/useQualimatSearch'
|
||||
import { clampPercent, sanitizeDecimal, sanitizeLiotPlates } from '~/modules/transport/utils/forms/numberInput'
|
||||
import { sanitizeFreeText } from '~/shared/utils/textSanitize'
|
||||
|
||||
interface SelectOption {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
const { t } = useI18n()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const toast = useToast()
|
||||
const api = useApi()
|
||||
const { can } = usePermissions()
|
||||
|
||||
const carrierId = route.params.id as string
|
||||
useHead({ title: t('transport.carriers.edit.title') })
|
||||
|
||||
// Gating route : l'édition est réservée à `manage` ; sinon retour consultation.
|
||||
if (!can('transport.carriers.manage')) {
|
||||
await navigateTo(`/carriers/${carrierId}`)
|
||||
}
|
||||
|
||||
const { carrier, loading, error, load } = useCarrier(carrierId)
|
||||
|
||||
const {
|
||||
main,
|
||||
mainSubmitting,
|
||||
tabSubmitting,
|
||||
mainErrors,
|
||||
dischargeUploading,
|
||||
selectDischarge,
|
||||
clearDischarge,
|
||||
setCertification,
|
||||
isLiot,
|
||||
certificationReadonly,
|
||||
showCharteredFields,
|
||||
showDischarge,
|
||||
applyQualimatSelection,
|
||||
address,
|
||||
addressErrors,
|
||||
submitAddress,
|
||||
contacts,
|
||||
contactErrors,
|
||||
canAddContact,
|
||||
addContact,
|
||||
removeContact,
|
||||
submitContacts,
|
||||
prices,
|
||||
priceErrors,
|
||||
canAddPrice,
|
||||
addPrice,
|
||||
removePrice,
|
||||
submitPrices,
|
||||
updateMain,
|
||||
prefillFrom,
|
||||
} = useCarrierForm()
|
||||
|
||||
const SELECTABLE_CERTIFICATIONS = ['GMP_PLUS', 'OVOCOM', 'COMPTE_PROPRE', 'AUTRE'] as const
|
||||
const certificationOptions = computed<SelectOption[]>(() => {
|
||||
const codes: string[] = [...SELECTABLE_CERTIFICATIONS]
|
||||
if (main.certificationType === 'QUALIMAT') codes.unshift('QUALIMAT')
|
||||
return codes.map(code => ({ value: code, label: t(`transport.carriers.certification.${code}`) }))
|
||||
})
|
||||
|
||||
|
||||
const TAB_ICONS: Record<string, string> = {
|
||||
qualimat: 'mdi:truck-fast-outline',
|
||||
addresses: 'mdi:map-marker-outline',
|
||||
contacts: 'mdi:account-box-plus-outline',
|
||||
prices: 'mdi:payment',
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// Immatriculations LIOT : la clé force le ré-affichage quand le filtrage laisse le
|
||||
// modelValue inchangé (ex: caractère interdit seul tapé) — sinon le DOM garderait
|
||||
// le caractère parasite alors que le modèle est déjà propre.
|
||||
const liotPlatesKey = ref(0)
|
||||
|
||||
/** Saisie des immatriculations LIOT : filtre la saisie et re-synchronise si filtré. */
|
||||
function onLiotPlatesInput(value: string): void {
|
||||
const clean = sanitizeLiotPlates(value)
|
||||
main.liotPlates = clean
|
||||
if (clean !== value) {
|
||||
liotPlatesKey.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,539 @@
|
||||
<template>
|
||||
<div>
|
||||
<!-- En-tête : retour répertoire + nom + actions. -->
|
||||
<div class="flex items-center gap-3 pt-11">
|
||||
<MalioButtonIcon
|
||||
icon="mdi:arrow-left-bold"
|
||||
icon-size="24"
|
||||
variant="ghost"
|
||||
v-bind="{ ariaLabel: t('transport.carriers.consultation.back') }"
|
||||
@click="goBack"
|
||||
/>
|
||||
<h1 class="text-[30px] font-semibold text-m-primary">{{ headerTitle }}</h1>
|
||||
|
||||
<div class="ml-auto flex items-center gap-12">
|
||||
<MalioButton
|
||||
v-if="canEdit"
|
||||
variant="secondary"
|
||||
icon-name="mdi:pencil-outline"
|
||||
icon-position="left"
|
||||
:label="t('transport.carriers.action.edit')"
|
||||
@click="goEdit"
|
||||
/>
|
||||
<MalioButton
|
||||
v-if="showArchive"
|
||||
variant="danger"
|
||||
icon-name="mdi:archive-arrow-down-outline"
|
||||
icon-position="left"
|
||||
:label="t('transport.carriers.action.archive')"
|
||||
@click="askToggleArchive"
|
||||
/>
|
||||
<MalioButton
|
||||
v-if="showRestore"
|
||||
variant="secondary"
|
||||
icon-name="mdi:archive-arrow-up-outline"
|
||||
icon-position="left"
|
||||
:label="t('transport.carriers.action.restore')"
|
||||
@click="askToggleArchive"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p v-if="loading" class="mt-12 text-center text-black/60">{{ t('transport.carriers.consultation.loading') }}</p>
|
||||
<p v-else-if="error" class="mt-12 text-center text-m-danger">{{ t('transport.carriers.consultation.notFound') }}</p>
|
||||
|
||||
<template v-else-if="carrier">
|
||||
<!-- ── Bloc principal (lecture seule) — même disposition que l'ajout ── -->
|
||||
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText :model-value="main.name" :label="t('transport.carriers.form.main.name')" disabled />
|
||||
|
||||
<!-- Cas LIOT : le champ immatriculations occupe les colonnes restantes
|
||||
de la ligne (3 en xl, 2 sinon), comme à l'ajout / la modification. -->
|
||||
<div v-if="isLiot" class="col-span-2 xl:col-span-3">
|
||||
<MalioInputText
|
||||
:model-value="main.liotPlates"
|
||||
:label="t('transport.carriers.form.main.liotPlates')"
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Cas standard : certification + décharge (col 3 réservée) + affrètement (col 4). -->
|
||||
<template v-if="!isLiot">
|
||||
<MalioInputText
|
||||
:model-value="certificationLabel"
|
||||
:label="t('transport.carriers.form.main.certificationType')"
|
||||
disabled
|
||||
/>
|
||||
|
||||
<!-- Colonne 3 réservée à la décharge (si AUTRE), sinon vide (xl). -->
|
||||
<MalioInputText
|
||||
v-if="main.certificationType === 'AUTRE'"
|
||||
:model-value="dischargeLabel"
|
||||
:label="t('transport.carriers.form.main.discharge')"
|
||||
disabled
|
||||
/>
|
||||
<div v-else class="hidden xl:block"></div>
|
||||
|
||||
<!-- Affréter : colonne 4, centré (h-12) comme à l'ajout. -->
|
||||
<div class="flex h-12 items-center">
|
||||
<MalioCheckbox
|
||||
id="carrier-view-chartered"
|
||||
:label="t('transport.carriers.form.main.isChartered')"
|
||||
:model-value="main.isChartered"
|
||||
disabled
|
||||
:reserve-message-space="false"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Champs d'affrètement (ligne 2) si affrété. -->
|
||||
<template v-if="main.isChartered">
|
||||
<MalioInputText :model-value="indexationDisplay" :label="t('transport.carriers.form.main.indexationRate')" disabled />
|
||||
<!-- Contenant : radios désactivés (lecture seule), aligné sur l'ajout / la modif. -->
|
||||
<div>
|
||||
<div class="flex h-12 items-center gap-4">
|
||||
<MalioRadioButton
|
||||
:model-value="main.containerType"
|
||||
name="carrier-view-container"
|
||||
value="BENNE"
|
||||
:label="t('transport.carriers.containerType.BENNE')"
|
||||
disabled
|
||||
group-class="mt-0"
|
||||
/>
|
||||
<MalioRadioButton
|
||||
:model-value="main.containerType"
|
||||
name="carrier-view-container"
|
||||
value="FOND_MOUVANT"
|
||||
:label="t('transport.carriers.containerType.FOND_MOUVANT')"
|
||||
disabled
|
||||
group-class="mt-0"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<MalioInputText :model-value="main.volumeM3" :label="t('transport.carriers.form.main.volumeM3')" disabled />
|
||||
</template>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- ── Onglets (Adresses · Contacts · Prix) — ouvre sur Adresses ──── -->
|
||||
<!-- ERP-193 : barre masquee s'il ne reste aucun onglet non vide. -->
|
||||
<MalioTabList v-if="visibleTabKeys.length" v-model="activeTab" :tabs="tabs" class="mt-[60px]">
|
||||
<template #addresses>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
<!-- Adresse UNIQUE (ERP-172). -->
|
||||
<CarrierAddressBlock
|
||||
:model-value="address"
|
||||
:country-options="countryOptionsFor(address.country)"
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #contacts>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
<CarrierContactBlock
|
||||
v-for="(contact, index) in contacts"
|
||||
:key="index"
|
||||
:model-value="contact"
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Prix : tableau présentationnel regroupé par contenant + export. -->
|
||||
<template #prices>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
<!-- Police / bordures / radius alignés sur MalioDataTable (header
|
||||
16px, corps 14px). 1re colonne « Contenant » : libellé du
|
||||
groupe (Fond Mouvant / Benne) fusionné en rowspan ; séparateur
|
||||
épais entre les deux groupes. -->
|
||||
<table class="w-full table-fixed border-separate border-spacing-0 overflow-hidden rounded-malio border border-black text-left text-black">
|
||||
<!-- Répartition (table-fixed) : « Transport » étroit (libellé
|
||||
court Benne / Fond mouvant) ; Fournisseurs/Clients et
|
||||
Adresse livraisons larges ; Forfait / Tonne / Indexation
|
||||
/ État réduits. -->
|
||||
<colgroup>
|
||||
<col class="w-[120px]" />
|
||||
<col class="w-[20%]" />
|
||||
<col class="w-[24%]" />
|
||||
<col class="w-[11%]" />
|
||||
<col class="w-[9%]" />
|
||||
<col class="w-[9%]" />
|
||||
<col class="w-[9%]" />
|
||||
<col class="w-[9%]" />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<!-- En-tête centré pour matcher les cellules fusionnées Benne / Fond mouvant. -->
|
||||
<th class="border-b border-r border-black bg-m-surface px-3 py-3 text-center align-middle text-[16px] font-semibold">{{ t('transport.carriers.consultation.price.group') }}</th>
|
||||
<th class="border-b border-black bg-m-surface px-3 py-3 align-middle text-[16px] font-semibold">{{ t('transport.carriers.consultation.price.carrier') }}</th>
|
||||
<th class="border-b border-black bg-m-surface px-3 py-3 align-middle text-[16px] font-semibold">{{ t('transport.carriers.consultation.price.delivery') }}</th>
|
||||
<th class="border-b border-black bg-m-surface px-3 py-3 align-middle text-[16px] font-semibold">{{ t('transport.carriers.consultation.price.aproOrSite') }}</th>
|
||||
<th class="border-b border-black bg-m-surface px-3 py-3 align-middle text-[16px] font-semibold">{{ t('transport.carriers.consultation.price.forfait') }}</th>
|
||||
<th class="border-b border-black bg-m-surface px-3 py-3 align-middle text-[16px] font-semibold">{{ t('transport.carriers.consultation.price.tonne') }}</th>
|
||||
<th class="border-b border-black bg-m-surface px-3 py-3 align-middle text-[16px] font-semibold">{{ t('transport.carriers.consultation.price.indexation') }}</th>
|
||||
<th class="border-b border-black bg-m-surface px-3 py-3 align-middle text-[16px] font-semibold">{{ t('transport.carriers.consultation.price.state') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-for="(group, gi) in priceGroups" :key="gi">
|
||||
<tr
|
||||
v-for="(row, i) in group.rows"
|
||||
:key="`${gi}-${i}`"
|
||||
>
|
||||
<!-- Contenant par ligne (plus de cellule fusionnée) ; séparateur
|
||||
à droite, comme l'ancienne colonne de groupe. -->
|
||||
<td class="border-r border-black px-3 py-4 text-center align-middle text-[14px] font-medium" :class="dataBorder(gi, i)">{{ row.transport }}</td>
|
||||
<td class="px-3 py-4 text-[14px]" :class="dataBorder(gi, i)">{{ row.party }}</td>
|
||||
<td class="px-3 py-4 text-[14px]" :class="dataBorder(gi, i)">{{ row.delivery }}</td>
|
||||
<td class="px-3 py-4 text-[14px]" :class="dataBorder(gi, i)">{{ row.apro }}</td>
|
||||
<td class="px-3 py-4 text-[14px]" :class="dataBorder(gi, i)">{{ row.forfait }}</td>
|
||||
<td class="px-3 py-4 text-[14px]" :class="dataBorder(gi, i)">{{ row.tonne }}</td>
|
||||
<td class="px-3 py-4 text-[14px]" :class="dataBorder(gi, i)">{{ row.indexation }}</td>
|
||||
<td class="px-3 py-4 text-[14px]" :class="dataBorder(gi, i)">{{ row.state }}</td>
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-if="!hasPrices">
|
||||
<td colspan="8" class="px-3 py-4 text-center text-[14px] text-m-muted">
|
||||
{{ t('transport.carriers.consultation.price.empty') }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div v-if="hasPrices" class="flex justify-center">
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('transport.carriers.consultation.price.export')"
|
||||
:disabled="exporting"
|
||||
@click="exportPrices"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</MalioTabList>
|
||||
</template>
|
||||
|
||||
<!-- Modal de confirmation archivage / restauration. -->
|
||||
<MalioModal v-model="confirmArchive.open" modal-class="max-w-md">
|
||||
<template #header>
|
||||
<h2 class="text-[24px] font-bold">{{ confirmArchive.title }}</h2>
|
||||
</template>
|
||||
<p>{{ confirmArchive.message }}</p>
|
||||
<template #footer>
|
||||
<MalioButton
|
||||
variant="secondary"
|
||||
button-class="flex-1"
|
||||
:label="t('transport.carriers.form.confirmDelete.cancel')"
|
||||
@click="confirmArchive.open = false"
|
||||
/>
|
||||
<MalioButton
|
||||
variant="danger"
|
||||
button-class="flex-1"
|
||||
:label="confirmArchive.confirmLabel"
|
||||
@click="runToggleArchive"
|
||||
/>
|
||||
</template>
|
||||
</MalioModal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import CarrierAddressBlock from '~/modules/transport/components/CarrierAddressBlock.vue'
|
||||
import CarrierContactBlock from '~/modules/transport/components/CarrierContactBlock.vue'
|
||||
import { useCarrier } from '~/modules/transport/composables/useCarrier'
|
||||
import {
|
||||
canEditCarrier,
|
||||
carrierConsultationVisibleTabs,
|
||||
labelOfRelation,
|
||||
mapAddressToDraft,
|
||||
mapContactToDraft,
|
||||
mapMainToDraft,
|
||||
showArchiveAction,
|
||||
showRestoreAction,
|
||||
type CarrierPriceRead,
|
||||
type Relation,
|
||||
} from '~/modules/transport/utils/forms/carrierMappers'
|
||||
import { extractApiErrorMessage } from '~/shared/utils/api'
|
||||
|
||||
interface SelectOption {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
const { t } = useI18n()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const toast = useToast()
|
||||
const api = useApi()
|
||||
const { can } = usePermissions()
|
||||
|
||||
const carrierId = route.params.id as string
|
||||
const { carrier, loading, error, load, archive, restore } = useCarrier(carrierId)
|
||||
|
||||
const isArchived = computed(() => carrier.value?.isArchived ?? false)
|
||||
const canEdit = computed(() => canEditCarrier(can))
|
||||
const showArchive = computed(() => showArchiveAction(can, isArchived.value))
|
||||
const showRestore = computed(() => showRestoreAction(can, isArchived.value))
|
||||
|
||||
const headerTitle = computed(() => carrier.value?.name || t('transport.carriers.consultation.title'))
|
||||
useHead({ title: t('transport.carriers.consultation.title') })
|
||||
|
||||
// ── Bloc principal mappé (lecture seule) ─────────────────────────────────────
|
||||
const main = computed(() => mapMainToDraft(carrier.value ?? { id: 0, '@id': '' }))
|
||||
const isLiot = computed(() => main.value.name.trim().toUpperCase() === 'LIOT')
|
||||
const certificationLabel = computed(() => main.value.certificationType
|
||||
? t(`transport.carriers.certification.${main.value.certificationType}`)
|
||||
: '')
|
||||
// Indexation affichée avec le « % » (comme l'icône du champ amount de l'ajout).
|
||||
const indexationDisplay = computed(() => main.value.indexationRate ? `${main.value.indexationRate} %` : '')
|
||||
// Décharge : nom du fichier embarqué si présent (sinon vide ; la colonne reste réservée).
|
||||
const dischargeLabel = computed(() => {
|
||||
const doc = carrier.value?.dischargeDocument
|
||||
if (doc && typeof doc !== 'string') {
|
||||
const meta = doc as Record<string, unknown>
|
||||
return String(meta.originalFilename ?? meta.name ?? '')
|
||||
}
|
||||
return ''
|
||||
})
|
||||
|
||||
// ── Onglets : Adresses · Contacts · Prix (ouvre sur Adresses, pas de Qualimat) ──
|
||||
// ERP-193 (retour metier) : on masque tout onglet de donnees vide.
|
||||
const TAB_ICONS: Record<string, string> = {
|
||||
addresses: 'mdi:map-marker-outline',
|
||||
contacts: 'mdi:account-box-plus-outline',
|
||||
prices: 'mdi:payment',
|
||||
}
|
||||
const visibleTabKeys = computed(() => carrierConsultationVisibleTabs(carrier.value))
|
||||
const tabs = computed(() => visibleTabKeys.value.map(key => ({
|
||||
key,
|
||||
label: t(`transport.carriers.tab.${key}`),
|
||||
icon: TAB_ICONS[key],
|
||||
})))
|
||||
|
||||
// Onglet initial : vide tant que le transporteur n'est pas charge, puis premier
|
||||
// onglet visible. Un watcher recale si l'onglet courant disparait.
|
||||
const activeTab = ref('')
|
||||
watch(visibleTabKeys, (keys) => {
|
||||
if (keys.length === 0) {
|
||||
activeTab.value = ''
|
||||
return
|
||||
}
|
||||
if (!keys.includes(activeTab.value)) {
|
||||
activeTab.value = keys[0]
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
// Adresse UNIQUE (ERP-172) : un seul bloc en lecture seule (vide si pas d'adresse).
|
||||
const address = computed(() => carrier.value?.address
|
||||
? mapAddressToDraft(carrier.value.address)
|
||||
: mapAddressToDraft({ id: 0, '@id': '' }))
|
||||
const contacts = computed(() => {
|
||||
const list = (carrier.value?.contacts ?? []).map(mapContactToDraft)
|
||||
return list.length > 0 ? list : [mapContactToDraft({ id: 0, '@id': '' })]
|
||||
})
|
||||
|
||||
/** Pays : une seule option (valeur courante), suffisant pour l'affichage readonly. */
|
||||
function countryOptionsFor(country: string): SelectOption[] {
|
||||
return country ? [{ value: country, label: country }] : []
|
||||
}
|
||||
|
||||
// ── Tableau Prix consultation (regroupé par ADRESSE DE LIVRAISON) ─────────────
|
||||
// Rang d'affichage des contenants au sein d'une même adresse (Fond mouvant puis Benne).
|
||||
const CONTAINER_RANK: Record<string, number> = { FOND_MOUVANT: 0, BENNE: 1 }
|
||||
|
||||
interface PriceRowView {
|
||||
/** Contenant (libellé affiché : Fond mouvant / Benne). */
|
||||
transport: string
|
||||
/** Contenant brut (FOND_MOUVANT / BENNE) — tri interne du groupe. */
|
||||
transportType: string
|
||||
/** Fournisseur ou client lié au prix (raison sociale). */
|
||||
party: string
|
||||
apro: string
|
||||
delivery: string
|
||||
forfait: string
|
||||
tonne: string
|
||||
indexation: string
|
||||
state: string
|
||||
}
|
||||
|
||||
/** Groupe de prix d'une même adresse de livraison (lignes consécutives). */
|
||||
interface PriceGroupView {
|
||||
rows: PriceRowView[]
|
||||
}
|
||||
|
||||
/** Formate un montant décimal en « 1 000,00 € » (chaîne vide si absent). */
|
||||
function formatAmount(value: string | null | undefined): string {
|
||||
if (!value) {
|
||||
return ''
|
||||
}
|
||||
const n = Number(value)
|
||||
if (Number.isNaN(n)) {
|
||||
return ''
|
||||
}
|
||||
return `${n.toLocaleString('fr-FR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} €`
|
||||
}
|
||||
|
||||
/** Code du site = département (2 premiers chiffres du code postal, ex: 86 / 17 / 82). */
|
||||
function siteCode(relation: Relation): string {
|
||||
if (!relation || typeof relation === 'string') {
|
||||
return ''
|
||||
}
|
||||
const postalCode = relation.postalCode as string | undefined
|
||||
return postalCode ? postalCode.slice(0, 2) : ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Construit une ligne d'affichage depuis un prix embarqué (maquette Prix) :
|
||||
* - « Transport » = le contenant (Fond mouvant / Benne) ;
|
||||
* - « Fournisseurs / Clients » = le fournisseur OU le client lié (raison sociale) ;
|
||||
* - « Adresse sites » = le CODE du site (département, ex: 86 / 17 / 82) ;
|
||||
* - « Adresse livraisons » = l'adresse (voie) du client/fournisseur ;
|
||||
* - le prix tombe dans Forfait € OU Tonne € selon `pricingUnit`.
|
||||
*/
|
||||
function toPriceRow(price: CarrierPriceRead): PriceRowView {
|
||||
const isClient = price.direction === 'CLIENT'
|
||||
const containerType = price.containerType ?? ''
|
||||
return {
|
||||
transportType: containerType,
|
||||
transport: containerType ? t(`transport.carriers.containerType.${containerType}`) : '',
|
||||
party: labelOfRelation(isClient ? price.client : price.supplier),
|
||||
apro: isClient ? siteCode(price.departureSite) : siteCode(price.deliverySite),
|
||||
delivery: isClient ? labelOfRelation(price.clientDeliveryAddress) : labelOfRelation(price.supplierSupplyAddress),
|
||||
forfait: price.pricingUnit === 'FORFAIT' ? formatAmount(price.price) : '',
|
||||
tonne: price.pricingUnit === 'TONNE' ? formatAmount(price.price) : '',
|
||||
// CarrierPrice n'a pas de taux d'indexation propre → on affiche celui du
|
||||
// transporteur (formulaire principal). À faire évoluer si un taux par prix
|
||||
// est requis (gap back).
|
||||
indexation: main.value.indexationRate ? `${main.value.indexationRate} %` : '',
|
||||
state: price.priceState ? t(`transport.carriers.form.price.state${stateSuffix(price.priceState)}`) : '',
|
||||
}
|
||||
}
|
||||
|
||||
/** EN_COURS → EnCours, VALIDE → Valide, NON_VALIDE → NonValide (clés i18n existantes). */
|
||||
function stateSuffix(state: string): string {
|
||||
const map: Record<string, string> = { EN_COURS: 'EnCours', VALIDE: 'Valide', NON_VALIDE: 'NonValide' }
|
||||
return map[state] ?? ''
|
||||
}
|
||||
|
||||
// Prix regroupés par ADRESSE DE LIVRAISON : les lignes d'une même adresse sont
|
||||
// consécutives (triées par contenant Fond mouvant → Benne), les groupes triés
|
||||
// alphabétiquement par adresse. Un séparateur épais sépare deux adresses.
|
||||
const priceGroups = computed<PriceGroupView[]>(() => {
|
||||
const rows = (carrier.value?.prices ?? []).map(toPriceRow)
|
||||
const byDelivery = new Map<string, PriceRowView[]>()
|
||||
for (const row of rows) {
|
||||
const list = byDelivery.get(row.delivery)
|
||||
if (list) {
|
||||
list.push(row)
|
||||
} else {
|
||||
byDelivery.set(row.delivery, [row])
|
||||
}
|
||||
}
|
||||
return [...byDelivery.entries()]
|
||||
.sort(([a], [b]) => a.localeCompare(b, 'fr'))
|
||||
.map(([, groupRows]) => ({
|
||||
rows: groupRows
|
||||
.slice()
|
||||
.sort((x, y) => (CONTAINER_RANK[x.transportType] ?? 99) - (CONTAINER_RANK[y.transportType] ?? 99)),
|
||||
}))
|
||||
})
|
||||
|
||||
const hasPrices = computed(() => priceGroups.value.length > 0)
|
||||
|
||||
/**
|
||||
* Bordure basse d'une cellule de données :
|
||||
* - ligne interne d'un groupe d'adresse (même adresse de livraison) → fine grise ;
|
||||
* - dernière ligne d'un groupe NON final → épaisse noire (sépare deux adresses) ;
|
||||
* - dernière ligne du DERNIER groupe → aucune (le cadre du tableau s'en charge,
|
||||
* évite la double bordure tout en bas).
|
||||
*/
|
||||
function dataBorder(gi: number, i: number): string {
|
||||
const group = priceGroups.value[gi]
|
||||
const isLastRow = i === group.rows.length - 1
|
||||
const isLastGroup = gi === priceGroups.value.length - 1
|
||||
// Couleur de bordure SIDE-SPECIFIC (border-b-*) : un `border-{color}` global
|
||||
// ecraserait la couleur du bord droit noir de la colonne Transport.
|
||||
if (!isLastRow) {
|
||||
return 'border-b border-b-m-muted/30'
|
||||
}
|
||||
return isLastGroup ? '' : 'border-b-2 border-b-black'
|
||||
}
|
||||
|
||||
// ── Export XLSX des prix ─────────────────────────────────────────────────────
|
||||
const exporting = ref(false)
|
||||
|
||||
async function exportPrices(): Promise<void> {
|
||||
if (exporting.value) return
|
||||
exporting.value = true
|
||||
try {
|
||||
const blob = await api.get<Blob>(`/carriers/${carrierId}/prices/export.xlsx`, {}, {
|
||||
responseType: 'blob',
|
||||
toast: false,
|
||||
} as unknown as Parameters<typeof api.get>[2])
|
||||
triggerDownload(blob, `transporteur-${carrierId}-prix.xlsx`)
|
||||
}
|
||||
catch {
|
||||
toast.error({ title: t('transport.carriers.toast.error'), message: t('transport.carriers.toast.exportError') })
|
||||
}
|
||||
finally {
|
||||
exporting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function triggerDownload(blob: Blob, filename: string): void {
|
||||
const url = URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = filename
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
// ── Navigation / archivage ───────────────────────────────────────────────────
|
||||
function goBack(): void {
|
||||
router.push('/carriers')
|
||||
}
|
||||
|
||||
function goEdit(): void {
|
||||
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>
|
||||
@@ -13,42 +13,140 @@
|
||||
</div>
|
||||
|
||||
<!-- ── Formulaire principal (pre-onglets) ─────────────────────────────
|
||||
Sans validation de ce bloc, les onglets restent inaccessibles. Au
|
||||
succes du POST, les champs passent en lecture seule et on bascule
|
||||
automatiquement sur l'onglet Qualimat. Les champs conditionnels
|
||||
(indexation / benne / volume si affrete, decharge si AUTRE, cas LIOT)
|
||||
et la saisie assistee QUALIMAT arrivent a ERP-166. -->
|
||||
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"
|
||||
:model-value="main.name"
|
||||
@update:model-value="(v: string) => main.name = sanitizeFreeText(v)"
|
||||
:label="t('transport.carriers.form.main.name')"
|
||||
:required="true"
|
||||
:readonly="mainLocked"
|
||||
:disabled="mainLocked"
|
||||
:error="mainErrors.errors.name"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="main.certificationType"
|
||||
:options="certificationOptions"
|
||||
:label="t('transport.carriers.form.main.certificationType')"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:readonly="mainLocked"
|
||||
:error="mainErrors.errors.certificationType"
|
||||
@update:model-value="(v: string | number | null) => main.certificationType = v === null ? null : String(v)"
|
||||
/>
|
||||
<!-- Wrapper h-12 + centrage vertical : aligne la case a cocher sur la
|
||||
ligne de champ des inputs/selects (qui posent un h-12 items-center
|
||||
en interne). reserve-message-space=false pour un centrage exact. -->
|
||||
<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"
|
||||
|
||||
<!-- Cas LIOT : seul le champ immatriculations est pertinent. Il occupe
|
||||
les colonnes restantes de la ligne (3 en xl, 2 sinon) — le wrapper
|
||||
porte le col-span car MalioInputText (inheritAttrs:false) renvoie
|
||||
`class` sur l'input interne, pas sur la cellule de grille. -->
|
||||
<div v-if="isLiot" class="col-span-2 xl:col-span-3">
|
||||
<MalioInputText
|
||||
:key="liotPlatesKey"
|
||||
:model-value="main.liotPlates"
|
||||
@update:model-value="onLiotPlatesInput"
|
||||
:label="t('transport.carriers.form.main.liotPlates')"
|
||||
:hint="t('transport.carriers.form.main.liotPlatesHint')"
|
||||
:required="true"
|
||||
:disabled="mainLocked"
|
||||
:error="mainErrors.errors.liotPlates"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Cas standard : certification + affretement + champs conditionnels. -->
|
||||
<template v-if="!isLiot">
|
||||
<MalioSelect
|
||||
:model-value="main.certificationType"
|
||||
:options="certificationOptions"
|
||||
:label="t('transport.carriers.form.main.certificationType')"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:disabled="certificationReadonly"
|
||||
:error="mainErrors.errors.certificationType"
|
||||
@update:model-value="(v: string | number | null) => 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"
|
||||
:disabled="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"
|
||||
:disabled="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"
|
||||
:disabled="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"
|
||||
:disabled="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">
|
||||
@@ -61,13 +159,118 @@
|
||||
</div>
|
||||
|
||||
<!-- ── Onglets a validation incrementale ─────────────────────────────
|
||||
Barre Qualimat · Adresses · Contacts · Prix. Onglets verrouilles tant
|
||||
que le formulaire principal n'est pas valide (unlockedIndex = -1) puis
|
||||
deverrouilles progressivement. Le contenu de chaque onglet arrive aux
|
||||
tickets suivants (ERP-166+) : placeholders « A venir » pour l'instant. -->
|
||||
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"
|
||||
:disabled="isQualimat || isValidated('addresses')"
|
||||
:errors="addressErrors"
|
||||
@update:model-value="(v) => address = v"
|
||||
@degraded="onAddressDegraded"
|
||||
/>
|
||||
<!-- RG-4.07 : pas de bouton Valider pour un transporteur QUALIMAT
|
||||
(adresse copiée et persistée automatiquement). -->
|
||||
<div v-if="!isQualimat && !isValidated('addresses')" class="flex justify-center gap-6">
|
||||
<MalioButton
|
||||
variant="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)"
|
||||
:disabled="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')"
|
||||
:disabled="isValidated('prices')"
|
||||
:errors="priceErrors[index]"
|
||||
@update:model-value="(v) => prices[index] = v"
|
||||
@remove="askRemovePrice(index)"
|
||||
/>
|
||||
<div v-if="!isValidated('prices')" class="flex justify-center gap-6">
|
||||
<MalioButton
|
||||
variant="secondary"
|
||||
icon-name="mdi:add-bold"
|
||||
icon-position="left"
|
||||
:label="t('transport.carriers.form.price.add')"
|
||||
:disabled="!canAddPrice"
|
||||
@click="addPrice"
|
||||
/>
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('transport.carriers.form.submit')"
|
||||
:disabled="tabSubmitting || carrierId === null"
|
||||
@click="onSubmitPrices"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Plus d'onglet placeholder : tous les onglets ont leur contenu. -->
|
||||
<template
|
||||
v-for="key in tabKeys"
|
||||
v-for="key in placeholderTabs"
|
||||
:key="key"
|
||||
#[key]
|
||||
>
|
||||
@@ -76,12 +279,43 @@
|
||||
</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 } from 'vue'
|
||||
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, sanitizeLiotPlates } from '~/modules/transport/utils/forms/numberInput'
|
||||
import { sanitizeFreeText } from '~/shared/utils/textSanitize'
|
||||
|
||||
interface SelectOption {
|
||||
value: string
|
||||
@@ -89,7 +323,9 @@ interface SelectOption {
|
||||
}
|
||||
|
||||
const { t } = useI18n()
|
||||
const api = useApi()
|
||||
const router = useRouter()
|
||||
const toast = useToast()
|
||||
const { can } = usePermissions()
|
||||
|
||||
useHead({ title: t('transport.carriers.form.title') })
|
||||
@@ -102,33 +338,75 @@ if (!can('transport.carriers.manage')) {
|
||||
|
||||
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()
|
||||
|
||||
// Certifications selectionnables manuellement (spec § Formulaire principal).
|
||||
// QUALIMAT n'est PAS dans cette liste : il est pose par la saisie assistee QUALIMAT
|
||||
// (ERP-166), pas choisi a la main.
|
||||
// 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[]>(() =>
|
||||
SELECTABLE_CERTIFICATIONS.map(code => ({
|
||||
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-check-outline',
|
||||
qualimat: 'mdi:truck-fast-outline',
|
||||
addresses: 'mdi:map-marker-outline',
|
||||
contacts: 'mdi:account-box-plus-outline',
|
||||
prices: 'mdi:currency-eur',
|
||||
prices: 'mdi:payment',
|
||||
}
|
||||
|
||||
// Onglets desactives tant que le formulaire principal n'est pas valide
|
||||
@@ -140,13 +418,199 @@ const tabs = computed(() => tabKeys.value.map((key, index) => ({
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// Immatriculations LIOT : la clé force le ré-affichage quand le filtrage laisse le
|
||||
// modelValue inchangé (ex: caractère interdit seul tapé) — sinon le DOM garderait
|
||||
// le caractère parasite alors que le modèle est déjà propre.
|
||||
const liotPlatesKey = ref(0)
|
||||
|
||||
/** Saisie des immatriculations LIOT : filtre la saisie et re-synchronise si filtré. */
|
||||
function onLiotPlatesInput(value: string): void {
|
||||
const clean = sanitizeLiotPlates(value)
|
||||
main.liotPlates = clean
|
||||
if (clean !== value) {
|
||||
liotPlatesKey.value += 1
|
||||
}
|
||||
}
|
||||
|
||||
/** Retour vers le repertoire transporteurs (fleche d'en-tete). */
|
||||
function goBack(): void {
|
||||
router.push('/carriers')
|
||||
}
|
||||
|
||||
/** Valide le formulaire principal (POST /carriers ; bascule gerée par le composable). */
|
||||
/**
|
||||
* 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> {
|
||||
await submitMain()
|
||||
const ok = await submitMain()
|
||||
if (ok && isQualimat.value) {
|
||||
await submitAddress(error => toast.error({
|
||||
title: t('transport.carriers.toast.error'),
|
||||
message: apiErrorMessage(error),
|
||||
}))
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -1,22 +1,36 @@
|
||||
/**
|
||||
* Types du workflow « Ajouter un transporteur » (M4 Transport, ERP-165).
|
||||
* Types du workflow « Ajouter un transporteur » (M4 Transport, ERP-165 / ERP-166).
|
||||
*
|
||||
* Périmètre ERP-165 = formulaire PRINCIPAL (pré-onglets) uniquement : Nom +
|
||||
* Certification + Affréter. Les champs conditionnels (indexation / benne / volume
|
||||
* si affrété, décharge si AUTRE, immatriculations LIOT) et la saisie assistée
|
||||
* QUALIMAT arrivent à ERP-166 ; les onglets Adresses / Contacts / Prix aux tickets
|
||||
* suivants. On garde donc volontairement ce draft minimal — il s'étendra.
|
||||
* 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. `certificationType` est un code enum back
|
||||
* (GMP_PLUS | OVOCOM | COMPTE_PROPRE | AUTRE ; QUALIMAT sera posé par la saisie
|
||||
* assistée à ERP-166) ou `null` tant que rien n'est choisi.
|
||||
* 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). */
|
||||
@@ -25,6 +39,139 @@ export function emptyCarrierMain(): CarrierMainDraft {
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
canEditCarrier,
|
||||
carrierConsultationVisibleTabs,
|
||||
hasAddressData,
|
||||
iriOf,
|
||||
labelOfRelation,
|
||||
mapAddressToDraft,
|
||||
mapContactToDraft,
|
||||
mapMainToDraft,
|
||||
mapPriceToDraft,
|
||||
showArchiveAction,
|
||||
showRestoreAction,
|
||||
type CarrierDetail,
|
||||
} from '../carrierMappers'
|
||||
|
||||
/**
|
||||
* Tests des mappers détail → brouillons (M4 Transport, ERP-170) : peuplent les écrans
|
||||
* Consultation / Modification depuis la SEULE réponse `GET /api/carriers/{id}`, et
|
||||
* helpers de visibilité des boutons (Modifier / Archiver / Restaurer) selon la permission.
|
||||
*/
|
||||
describe('carrierMappers', () => {
|
||||
it('iriOf : objet embarqué, IRI nu, ou null', () => {
|
||||
expect(iriOf({ '@id': '/api/clients/3' })).toBe('/api/clients/3')
|
||||
expect(iriOf('/api/sites/1')).toBe('/api/sites/1')
|
||||
expect(iriOf(null)).toBeNull()
|
||||
expect(iriOf(undefined)).toBeNull()
|
||||
})
|
||||
|
||||
it('labelOfRelation : companyName (client/fournisseur) prioritaire sur name/adresse', () => {
|
||||
expect(labelOfRelation({ '@id': '/api/suppliers/8', companyName: 'AAAAAAA', name: 'X' })).toBe('AAAAAAA')
|
||||
})
|
||||
|
||||
it('labelOfRelation : name (site) à défaut adresse condensée', () => {
|
||||
expect(labelOfRelation({ '@id': '/api/sites/1', name: 'Châtellerault' })).toBe('Châtellerault')
|
||||
expect(labelOfRelation({ '@id': '/api/client_addresses/8', street: '1 rue X', postalCode: '86000', city: 'Poitiers' })).toBe('1 rue X · 86000 · Poitiers')
|
||||
expect(labelOfRelation('/api/sites/1')).toBe('')
|
||||
expect(labelOfRelation(null)).toBe('')
|
||||
})
|
||||
|
||||
it('mapMainToDraft : scalaires + IRI décharge / qualimat', () => {
|
||||
const detail: CarrierDetail = {
|
||||
'@id': '/api/carriers/7',
|
||||
id: 7,
|
||||
name: 'TRANSPORTS ACME',
|
||||
certificationType: 'QUALIMAT',
|
||||
isChartered: true,
|
||||
indexationRate: '5.00',
|
||||
containerType: 'BENNE',
|
||||
volumeM3: '30.00',
|
||||
dischargeDocument: { '@id': '/api/uploaded_documents/4' },
|
||||
qualimatCarrier: { '@id': '/api/qualimat_carriers/42' },
|
||||
}
|
||||
expect(mapMainToDraft(detail)).toEqual({
|
||||
name: 'TRANSPORTS ACME',
|
||||
certificationType: 'QUALIMAT',
|
||||
isChartered: true,
|
||||
indexationRate: '5.00',
|
||||
containerType: 'BENNE',
|
||||
volumeM3: '30.00',
|
||||
liotPlates: '',
|
||||
dischargeDocumentIri: '/api/uploaded_documents/4',
|
||||
qualimatCarrierIri: '/api/qualimat_carriers/42',
|
||||
})
|
||||
})
|
||||
|
||||
it('mapAddressToDraft : pays par défaut France si absent', () => {
|
||||
expect(mapAddressToDraft({ '@id': '/api/carrier_addresses/3', id: 3, postalCode: '86000', city: 'Poitiers' }))
|
||||
.toEqual({ id: 3, country: 'France', postalCode: '86000', city: 'Poitiers', street: null, streetComplement: null })
|
||||
})
|
||||
|
||||
it('mapContactToDraft : hasSecondaryPhone vrai seulement si 2e numéro présent', () => {
|
||||
const one = mapContactToDraft({ '@id': '/api/carrier_contacts/1', id: 1, firstName: 'Jean', phonePrimary: '0102030405' })
|
||||
expect(one.hasSecondaryPhone).toBe(false)
|
||||
expect(one.firstName).toBe('Jean')
|
||||
|
||||
const two = mapContactToDraft({ '@id': '/api/carrier_contacts/2', id: 2, phonePrimary: '0102030405', phoneSecondary: '0605040302' })
|
||||
expect(two.hasSecondaryPhone).toBe(true)
|
||||
expect(two.phoneSecondary).toBeTruthy()
|
||||
})
|
||||
|
||||
it('mapPriceToDraft : direction + IRIs des relations de branche', () => {
|
||||
const draft = mapPriceToDraft({
|
||||
'@id': '/api/carrier_prices/5',
|
||||
id: 5,
|
||||
direction: 'CLIENT',
|
||||
client: { '@id': '/api/clients/3' },
|
||||
clientDeliveryAddress: { '@id': '/api/client_addresses/8' },
|
||||
departureSite: '/api/sites/1',
|
||||
containerType: 'BENNE',
|
||||
pricingUnit: 'FORFAIT',
|
||||
price: '120.00',
|
||||
priceState: 'EN_COURS',
|
||||
})
|
||||
expect(draft).toMatchObject({
|
||||
id: 5,
|
||||
direction: 'CLIENT',
|
||||
clientIri: '/api/clients/3',
|
||||
clientDeliveryAddressIri: '/api/client_addresses/8',
|
||||
departureSiteIri: '/api/sites/1',
|
||||
supplierIri: null,
|
||||
containerType: 'BENNE',
|
||||
pricingUnit: 'FORFAIT',
|
||||
price: '120.00',
|
||||
priceState: 'EN_COURS',
|
||||
})
|
||||
})
|
||||
|
||||
it('visibilité des boutons selon la permission', () => {
|
||||
const can = (granted: string[]) => (code: string) => granted.includes(code)
|
||||
|
||||
// Modifier : seulement avec manage.
|
||||
expect(canEditCarrier(can(['transport.carriers.manage']))).toBe(true)
|
||||
expect(canEditCarrier(can(['transport.carriers.view']))).toBe(false)
|
||||
|
||||
// Archiver : permission archive ET actif ; Restaurer : archive ET archivé.
|
||||
const withArchive = can(['transport.carriers.archive'])
|
||||
const noArchive = can(['transport.carriers.manage'])
|
||||
expect(showArchiveAction(withArchive, false)).toBe(true)
|
||||
expect(showArchiveAction(withArchive, true)).toBe(false)
|
||||
expect(showRestoreAction(withArchive, true)).toBe(true)
|
||||
expect(showRestoreAction(withArchive, false)).toBe(false)
|
||||
expect(showArchiveAction(noArchive, false)).toBe(false)
|
||||
expect(showRestoreAction(noArchive, true)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasAddressData', () => {
|
||||
it('faux pour une adresse absente ou entièrement vide', () => {
|
||||
expect(hasAddressData(null)).toBe(false)
|
||||
expect(hasAddressData(undefined)).toBe(false)
|
||||
expect(hasAddressData({ '@id': '/api/carrier_addresses/1', id: 1 })).toBe(false)
|
||||
})
|
||||
|
||||
it('vrai dès qu\'un champ adresse est rempli', () => {
|
||||
expect(hasAddressData({ '@id': '/api/carrier_addresses/1', id: 1, city: 'Poitiers' })).toBe(true)
|
||||
expect(hasAddressData({ '@id': '/api/carrier_addresses/1', id: 1, country: 'France' })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('carrierConsultationVisibleTabs', () => {
|
||||
it('retourne [] tant que le transporteur n\'est pas chargé', () => {
|
||||
expect(carrierConsultationVisibleTabs(null)).toEqual([])
|
||||
expect(carrierConsultationVisibleTabs(undefined)).toEqual([])
|
||||
})
|
||||
|
||||
it('masque les onglets vides (transporteur minimal)', () => {
|
||||
expect(carrierConsultationVisibleTabs({ '@id': '/api/carriers/1', id: 1, name: 'LIOT' })).toEqual([])
|
||||
})
|
||||
|
||||
it('affiche addresses/contacts/prices dans l\'ordre quand renseignés', () => {
|
||||
const carrier: CarrierDetail = {
|
||||
'@id': '/api/carriers/1', id: 1,
|
||||
address: { '@id': '/api/carrier_addresses/1', id: 1, city: 'Poitiers' },
|
||||
contacts: [{ '@id': '/api/carrier_contacts/1', id: 1 }],
|
||||
prices: [{ '@id': '/api/carrier_prices/1', id: 1 }],
|
||||
}
|
||||
expect(carrierConsultationVisibleTabs(carrier)).toEqual(['addresses', 'contacts', 'prices'])
|
||||
})
|
||||
|
||||
it('ne garde que les onglets non vides (contacts seulement)', () => {
|
||||
const carrier: CarrierDetail = {
|
||||
'@id': '/api/carriers/1', id: 1,
|
||||
address: { '@id': '/api/carrier_addresses/1', id: 1 },
|
||||
contacts: [{ '@id': '/api/carrier_contacts/1', id: 1 }],
|
||||
prices: [],
|
||||
}
|
||||
expect(carrierConsultationVisibleTabs(carrier)).toEqual(['contacts'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { clampPercent, sanitizeDecimal, sanitizeLiotPlates } from '../numberInput'
|
||||
|
||||
describe('numberInput — saisie volume / indexation (ERP-170)', () => {
|
||||
it('sanitizeDecimal : ne garde que chiffres + un seul point', () => {
|
||||
expect(sanitizeDecimal('30')).toBe('30')
|
||||
expect(sanitizeDecimal('30.5')).toBe('30.5')
|
||||
expect(sanitizeDecimal('30,5 kg')).toBe('30.5') // virgule FR → point ; espace + lettres retirés
|
||||
expect(sanitizeDecimal('1.2.3')).toBe('1.23') // un seul point conservé
|
||||
expect(sanitizeDecimal('abc12.3x')).toBe('12.3')
|
||||
expect(sanitizeDecimal('')).toBe('')
|
||||
})
|
||||
|
||||
it('clampPercent : plafonne à 100, laisse le reste tel quel', () => {
|
||||
expect(clampPercent('50')).toBe('50')
|
||||
expect(clampPercent('100')).toBe('100')
|
||||
expect(clampPercent('150')).toBe('100')
|
||||
expect(clampPercent('100.01')).toBe('100')
|
||||
expect(clampPercent('12,5')).toBe('12,5') // ≤ 100 → inchangé
|
||||
expect(clampPercent('')).toBe('')
|
||||
})
|
||||
|
||||
it('sanitizeLiotPlates : garde lettres/chiffres/tiret/point-virgule, retire espaces et reste', () => {
|
||||
expect(sanitizeLiotPlates('AB-123-CD;EF-456-GH')).toBe('AB-123-CD;EF-456-GH')
|
||||
expect(sanitizeLiotPlates('ab-123-cd ; ef-456-gh')).toBe('ab-123-cd;ef-456-gh') // espaces retirés
|
||||
expect(sanitizeLiotPlates('AB 123 CD')).toBe('AB123CD') // espaces retirés
|
||||
expect(sanitizeLiotPlates('AB.123/CD#42')).toBe('AB123CD42') // . / # retirés
|
||||
expect(sanitizeLiotPlates('')).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,252 @@
|
||||
/**
|
||||
* Helpers purs des écrans Consultation / Modification transporteur (M4, ERP-170) —
|
||||
* miroir de `providerDetail.ts` (M3). Mappent le payload `GET /api/carriers/{id}`
|
||||
* (relations embarquées via les groupes `carrier:item:read` + `qualimat:read` +
|
||||
* read-groups cross-module client/supplier/site/adresses) vers les brouillons
|
||||
* « plats » partagés avec les blocs Adresse / Contact / Prix.
|
||||
*
|
||||
* Ne touchent ni à l'API ni à l'état réactif (testables unitairement). Les champs
|
||||
* nuls peuvent être OMIS (skip_null_values) → toujours lire avec `?? null`.
|
||||
*/
|
||||
|
||||
import { formatPhoneFR } from '~/shared/utils/phone'
|
||||
import type {
|
||||
CarrierAddressFormDraft,
|
||||
CarrierContactFormDraft,
|
||||
CarrierMainDraft,
|
||||
CarrierPriceFormDraft,
|
||||
} from '~/modules/transport/types/carrierForm'
|
||||
|
||||
/** Référence Hydra embarquée minimale (@id toujours présent). */
|
||||
export interface HydraRef {
|
||||
'@id': string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
/** Une relation peut être embarquée (objet), un IRI nu (chaîne) ou absente. */
|
||||
export type Relation = HydraRef | string | null | undefined
|
||||
|
||||
/** Adresse embarquée (groupe carrier:item:read). */
|
||||
export interface CarrierAddressRead extends HydraRef {
|
||||
id: number
|
||||
country?: string | null
|
||||
postalCode?: string | null
|
||||
city?: string | null
|
||||
street?: string | null
|
||||
streetComplement?: string | null
|
||||
}
|
||||
|
||||
/** Contact embarqué (groupe carrier:item:read). */
|
||||
export interface CarrierContactRead extends HydraRef {
|
||||
id: number
|
||||
firstName?: string | null
|
||||
lastName?: string | null
|
||||
jobTitle?: string | null
|
||||
phonePrimary?: string | null
|
||||
phoneSecondary?: string | null
|
||||
email?: string | null
|
||||
}
|
||||
|
||||
/** Prix embarqué (groupe carrier:item:read + relations cross-module). */
|
||||
export interface CarrierPriceRead extends HydraRef {
|
||||
id: number
|
||||
direction?: string | null
|
||||
client?: Relation
|
||||
clientDeliveryAddress?: Relation
|
||||
departureSite?: Relation
|
||||
supplier?: Relation
|
||||
supplierSupplyAddress?: Relation
|
||||
deliverySite?: Relation
|
||||
containerType?: string | null
|
||||
pricingUnit?: string | null
|
||||
price?: string | null
|
||||
priceState?: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Détail d'un transporteur (`GET /api/carriers/{id}`). Tous les champs optionnels :
|
||||
* skip_null_values peut omettre n'importe quelle clé.
|
||||
*/
|
||||
export interface CarrierDetail extends HydraRef {
|
||||
id: number
|
||||
name?: string | null
|
||||
certificationType?: string | null
|
||||
isChartered?: boolean
|
||||
indexationRate?: string | null
|
||||
containerType?: string | null
|
||||
volumeM3?: string | null
|
||||
liotPlates?: string | null
|
||||
dischargeDocument?: Relation
|
||||
qualimatCarrier?: Relation
|
||||
isArchived?: boolean
|
||||
// Adresse UNIQUE (OneToOne, ERP-172) : objet embarqué (ou absent), pas une liste.
|
||||
address?: CarrierAddressRead | null
|
||||
contacts?: CarrierContactRead[]
|
||||
prices?: CarrierPriceRead[]
|
||||
}
|
||||
|
||||
/** Extrait l'IRI d'une relation (objet embarqué, IRI nu, ou null si absente). */
|
||||
export function iriOf(relation: Relation): string | null {
|
||||
if (relation === null || relation === undefined) {
|
||||
return null
|
||||
}
|
||||
if (typeof relation === 'string') {
|
||||
return relation
|
||||
}
|
||||
return relation['@id'] ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Libellé d'affichage d'une relation embarquée : `companyName` (client/fournisseur)
|
||||
* à défaut `name` (site), à défaut une adresse condensée (voie · CP · ville). Chaîne
|
||||
* vide si la relation est un IRI nu / absente.
|
||||
*/
|
||||
export function labelOfRelation(relation: Relation): string {
|
||||
if (!relation || typeof relation === 'string') {
|
||||
return ''
|
||||
}
|
||||
const companyName = relation.companyName as string | undefined
|
||||
if (companyName) {
|
||||
return companyName
|
||||
}
|
||||
const name = relation.name as string | undefined
|
||||
if (name) {
|
||||
return name
|
||||
}
|
||||
const parts = [relation.street, relation.postalCode, relation.city].filter(Boolean)
|
||||
return parts.join(' · ')
|
||||
}
|
||||
|
||||
/** Mappe le détail vers le brouillon du formulaire principal. */
|
||||
export function mapMainToDraft(detail: CarrierDetail): CarrierMainDraft {
|
||||
return {
|
||||
name: detail.name ?? '',
|
||||
certificationType: detail.certificationType ?? null,
|
||||
isChartered: detail.isChartered ?? false,
|
||||
indexationRate: detail.indexationRate ?? '',
|
||||
containerType: detail.containerType ?? null,
|
||||
volumeM3: detail.volumeM3 ?? '',
|
||||
liotPlates: detail.liotPlates ?? '',
|
||||
dischargeDocumentIri: iriOf(detail.dischargeDocument),
|
||||
qualimatCarrierIri: iriOf(detail.qualimatCarrier),
|
||||
}
|
||||
}
|
||||
|
||||
/** Mappe une adresse embarquée vers un brouillon. */
|
||||
export function mapAddressToDraft(address: CarrierAddressRead): CarrierAddressFormDraft {
|
||||
return {
|
||||
id: address.id,
|
||||
country: address.country ?? 'France',
|
||||
postalCode: address.postalCode ?? null,
|
||||
city: address.city ?? null,
|
||||
street: address.street ?? null,
|
||||
streetComplement: address.streetComplement ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/** Mappe un contact embarqué vers un brouillon (téléphones formatés XX XX XX XX XX). */
|
||||
export function mapContactToDraft(contact: CarrierContactRead): CarrierContactFormDraft {
|
||||
const secondary = contact.phoneSecondary ?? null
|
||||
return {
|
||||
id: contact.id,
|
||||
firstName: contact.firstName ?? null,
|
||||
lastName: contact.lastName ?? null,
|
||||
jobTitle: contact.jobTitle ?? null,
|
||||
phonePrimary: contact.phonePrimary ? formatPhoneFR(contact.phonePrimary) : null,
|
||||
phoneSecondary: secondary ? formatPhoneFR(secondary) : null,
|
||||
email: contact.email ?? null,
|
||||
hasSecondaryPhone: secondary !== null && secondary !== '',
|
||||
}
|
||||
}
|
||||
|
||||
/** Mappe un prix embarqué vers un brouillon (relations en IRI). */
|
||||
export function mapPriceToDraft(price: CarrierPriceRead): CarrierPriceFormDraft {
|
||||
const direction = price.direction === 'CLIENT' || price.direction === 'FOURNISSEUR'
|
||||
? price.direction
|
||||
: null
|
||||
return {
|
||||
id: price.id,
|
||||
direction,
|
||||
clientIri: iriOf(price.client),
|
||||
clientDeliveryAddressIri: iriOf(price.clientDeliveryAddress),
|
||||
departureSiteIri: iriOf(price.departureSite),
|
||||
supplierIri: iriOf(price.supplier),
|
||||
supplierSupplyAddressIri: iriOf(price.supplierSupplyAddress),
|
||||
deliverySiteIri: iriOf(price.deliverySite),
|
||||
containerType: price.containerType ?? null,
|
||||
pricingUnit: price.pricingUnit ?? null,
|
||||
price: price.price ?? null,
|
||||
priceState: price.priceState ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si une valeur scalaire porte une donnée affichable (non null/undefined,
|
||||
* et non chaîne vide après trim). Sert aux prédicats « onglet vide » ci-dessous.
|
||||
*/
|
||||
function hasValue(value: unknown): boolean {
|
||||
if (value === null || value === undefined) {
|
||||
return false
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
return value.trim() !== ''
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si l'adresse unique (OneToOne, ERP-172) porte au moins un champ rempli.
|
||||
* Un objet adresse vide (toutes clés nulles) est considéré comme « pas d'adresse ».
|
||||
*/
|
||||
export function hasAddressData(address: CarrierAddressRead | null | undefined): boolean {
|
||||
if (!address) {
|
||||
return false
|
||||
}
|
||||
return [
|
||||
address.postalCode,
|
||||
address.city,
|
||||
address.street,
|
||||
address.streetComplement,
|
||||
address.country,
|
||||
].some(hasValue)
|
||||
}
|
||||
|
||||
/**
|
||||
* Onglets visibles en consultation (ERP-193, retour métier) : on masque tout
|
||||
* onglet de données vide. Le transporteur n'a pas de coquille « à venir ».
|
||||
* Ordre : Adresses · Contacts · Prix. Retourne `[]` tant que le transporteur
|
||||
* n'est pas chargé.
|
||||
*/
|
||||
export function carrierConsultationVisibleTabs(
|
||||
carrier: CarrierDetail | null | undefined,
|
||||
): string[] {
|
||||
if (!carrier) {
|
||||
return []
|
||||
}
|
||||
const visible: string[] = []
|
||||
if (hasAddressData(carrier.address)) {
|
||||
visible.push('addresses')
|
||||
}
|
||||
if ((carrier.contacts ?? []).length > 0) {
|
||||
visible.push('contacts')
|
||||
}
|
||||
if ((carrier.prices ?? []).length > 0) {
|
||||
visible.push('prices')
|
||||
}
|
||||
return visible
|
||||
}
|
||||
|
||||
/** Bouton « Modifier » : visible avec la permission `manage` (Admin / Bureau). */
|
||||
export function canEditCarrier(can: (code: string) => boolean): boolean {
|
||||
return can('transport.carriers.manage')
|
||||
}
|
||||
|
||||
/** Bouton « Archiver » : permission archive ET transporteur encore actif (Admin seul). */
|
||||
export function showArchiveAction(can: (code: string) => boolean, isArchived: boolean): boolean {
|
||||
return can('transport.carriers.archive') && !isArchived
|
||||
}
|
||||
|
||||
/** Bouton « Restaurer » : permission archive ET transporteur déjà archivé (Admin seul). */
|
||||
export function showRestoreAction(can: (code: string) => boolean, isArchived: boolean): boolean {
|
||||
return can('transport.carriers.archive') && isArchived
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Helpers purs de l'onglet Prix transporteur (M4 Transport, ERP-169 — RG-4.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,38 @@
|
||||
/**
|
||||
* 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
|
||||
}
|
||||
|
||||
/**
|
||||
* Restreint la saisie des immatriculations LIOT : ne garde que lettres, chiffres,
|
||||
* tiret et point-virgule (séparateur de plaques). Les espaces et tout autre
|
||||
* caractère sont supprimés à la frappe / au collage. La normalisation finale
|
||||
* (majuscules + « ; » espacé) reste au back (RG-4.13).
|
||||
*/
|
||||
export function sanitizeLiotPlates(value: string): string {
|
||||
return (value ?? '').replace(/[^A-Za-z0-9;-]/g, '')
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { todayIso } from '../date'
|
||||
|
||||
describe('todayIso', () => {
|
||||
it('formate la date locale en YYYY-MM-DD (zero-pad mois/jour)', () => {
|
||||
// 7 mars 2026 (heure locale) -> '2026-03-07'.
|
||||
expect(todayIso(new Date(2026, 2, 7, 10, 30))).toBe('2026-03-07')
|
||||
})
|
||||
|
||||
it('utilise les composantes LOCALES, pas UTC (pas de decalage de minuit)', () => {
|
||||
// 18 juin 2026 23:30 heure locale : la date locale reste le 18 meme si
|
||||
// toISOString() (UTC) basculerait au 19 selon le fuseau.
|
||||
expect(todayIso(new Date(2026, 5, 18, 23, 30))).toBe('2026-06-18')
|
||||
})
|
||||
|
||||
it('gere le dernier jour de l\'annee', () => {
|
||||
expect(todayIso(new Date(2026, 11, 31, 12, 0))).toBe('2026-12-31')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
sanitizeAddress,
|
||||
sanitizeCodeAlnum,
|
||||
sanitizeEmail,
|
||||
sanitizeFreeText,
|
||||
sanitizePersonName,
|
||||
} from '../textSanitize'
|
||||
|
||||
describe('sanitizePersonName', () => {
|
||||
it('garde lettres accentuees, espace, apostrophe, tiret, point', () => {
|
||||
expect(sanitizePersonName('Jean-Pierre')).toBe('Jean-Pierre')
|
||||
expect(sanitizePersonName('O’Brien')).toBe('O’Brien')
|
||||
expect(sanitizePersonName("D'Angelo")).toBe("D'Angelo")
|
||||
expect(sanitizePersonName('Saint-Étienne J.')).toBe('Saint-Étienne J.')
|
||||
})
|
||||
|
||||
it('retire chiffres et caracteres parasites', () => {
|
||||
expect(sanitizePersonName('Dupont²³')).toBe('Dupont')
|
||||
expect(sanitizePersonName('Jean§&#~|')).toBe('Jean')
|
||||
expect(sanitizePersonName('Marie123')).toBe('Marie')
|
||||
})
|
||||
})
|
||||
|
||||
describe('sanitizeFreeText', () => {
|
||||
it('garde &, /, parentheses, degre, chiffres (raison sociale / fonction)', () => {
|
||||
expect(sanitizeFreeText('Dupont & Fils')).toBe('Dupont & Fils')
|
||||
expect(sanitizeFreeText('Resp. Achats/Ventes')).toBe('Resp. Achats/Ventes')
|
||||
expect(sanitizeFreeText('SARL Léon (Pôle n°2)')).toBe('SARL Léon (Pôle n°2)')
|
||||
})
|
||||
|
||||
it('retire les parasites ²³§~#|', () => {
|
||||
expect(sanitizeFreeText('ACME²³§')).toBe('ACME')
|
||||
expect(sanitizeFreeText('Test~#|<>{}')).toBe('Test')
|
||||
})
|
||||
})
|
||||
|
||||
describe('sanitizeAddress', () => {
|
||||
it('garde chiffres, virgule, point, apostrophe, slash, degre, tiret', () => {
|
||||
expect(sanitizeAddress('12 bis, rue de l’Église')).toBe('12 bis, rue de l’Église')
|
||||
expect(sanitizeAddress('Bât. n°3 - Zone A/B')).toBe('Bât. n°3 - Zone A/B')
|
||||
})
|
||||
|
||||
it('retire les parasites', () => {
|
||||
expect(sanitizeAddress('5 rue X²³§&')).toBe('5 rue X')
|
||||
})
|
||||
})
|
||||
|
||||
describe('sanitizeEmail', () => {
|
||||
it('garde les caracteres email valides', () => {
|
||||
expect(sanitizeEmail('jean.dupont+pro@acme-corp.fr')).toBe('jean.dupont+pro@acme-corp.fr')
|
||||
})
|
||||
|
||||
it('retire espaces et parasites', () => {
|
||||
expect(sanitizeEmail('jean §² dupont@acme.fr')).toBe('jeandupont@acme.fr')
|
||||
expect(sanitizeEmail('a&b#c@x.fr')).toBe('abc@x.fr')
|
||||
})
|
||||
})
|
||||
|
||||
describe('sanitizeCodeAlnum', () => {
|
||||
it('force la majuscule et ne garde que A-Z 0-9', () => {
|
||||
expect(sanitizeCodeAlnum('411dupont')).toBe('411DUPONT')
|
||||
expect(sanitizeCodeAlnum('FR 12 345')).toBe('FR12345')
|
||||
expect(sanitizeCodeAlnum('4-11.000§')).toBe('411000')
|
||||
})
|
||||
|
||||
it('chaine vide reste vide', () => {
|
||||
expect(sanitizeCodeAlnum('')).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Helpers de date purs / testables (partages inter-modules).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Date du jour au format ISO `YYYY-MM-DD` en heure LOCALE.
|
||||
*
|
||||
* On NE passe PAS par `toISOString()` (UTC) : pres de minuit, le decalage de
|
||||
* fuseau (FR = UTC+1/+2) renverrait la veille ou le lendemain. On lit donc les
|
||||
* composantes locales. Parametre `now` injectable pour les tests.
|
||||
*/
|
||||
export function todayIso(now: Date = new Date()): string {
|
||||
const year = now.getFullYear()
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(now.getDate()).padStart(2, '0')
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Filtres de saisie texte (retour metier ERP-193) : on retire a la frappe / au
|
||||
* collage les caracteres parasites (« ²³§~#| … ») des champs texte libres.
|
||||
*
|
||||
* Miroir FRONT des patterns back `App\Shared\Domain\Validation\TextInputPattern`
|
||||
* (allow-list par famille de champ). Le back reste l'autorite (Assert\Regex →
|
||||
* 422 inline via useFormErrors) ; ces fonctions ne font que le confort de saisie.
|
||||
* Purs / testables.
|
||||
*
|
||||
* IMPORTANT : garder les classes de caracteres STRICTEMENT alignees sur le back
|
||||
* (toute divergence = soit un caractere bloque au front mais accepte au back, soit
|
||||
* l'inverse → 422 surprise).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Noms de personnes (Nom, Prenom, Dirigeant) : lettres (accents), espace,
|
||||
* apostrophe droite/courbe, tiret, point.
|
||||
*/
|
||||
export function sanitizePersonName(value: string): string {
|
||||
return value.replace(/[^\p{L}\p{M} '’.-]/gu, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Texte societe / libre (Raison sociale, Concurrents, Fonction) : nom + chiffres,
|
||||
* virgule, esperluette, slash, parentheses, degre.
|
||||
*/
|
||||
export function sanitizeFreeText(value: string): string {
|
||||
// 0-9 (et pas \p{N}) : \p{N} engloberait les exposants ² ³ — justement parasites.
|
||||
return value.replace(/[^\p{L}\p{M}0-9 '’.,&/()°-]/gu, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Adresse (voie, complement, ville) : lettres, chiffres, espace, apostrophe,
|
||||
* point, virgule, slash, degre, tiret.
|
||||
*/
|
||||
export function sanitizeAddress(value: string): string {
|
||||
// 0-9 (et pas \p{N}) : evite de laisser passer les exposants ² ³.
|
||||
return value.replace(/[^\p{L}\p{M}0-9 '’.,/°-]/gu, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Codes alphanumeriques majuscules (N° de compte comptable, N° de TVA, IBAN, BIC) :
|
||||
* uniquement A-Z et 0-9, majuscule forcee.
|
||||
*/
|
||||
export function sanitizeCodeAlnum(value: string): string {
|
||||
return value.toUpperCase().replace(/[^A-Z0-9]/g, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Email : retire espaces et caracteres impossibles dans une adresse, en gardant
|
||||
* le jeu de caracteres email valides (lettres, chiffres, @ . _ % + - '). La
|
||||
* validation de FORMAT reste au back (Assert\Email) ; ici on bloque juste les
|
||||
* parasites (« ²³§~#| … ») a la frappe. La normalisation lowercase est portee par
|
||||
* MalioInputEmail (prop `lowercase`), on ne la duplique pas.
|
||||
*/
|
||||
export function sanitizeEmail(value: string): string {
|
||||
return value.replace(/[^A-Za-z0-9@._%+'-]/g, '')
|
||||
}
|
||||
@@ -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).'");
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ use App\Shared\Domain\Contract\ClientInterface;
|
||||
use App\Shared\Domain\Contract\SiteInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use App\Shared\Domain\Validation\TextInputPattern;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
@@ -162,6 +163,7 @@ class Client implements TimestampableInterface, BlamableInterface, ClientInterfa
|
||||
#[ORM\Column(length: 180)]
|
||||
#[Assert\NotBlank(message: 'Le nom de l\'entreprise est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(min: 2, max: 180, minMessage: 'Le nom de l\'entreprise doit comporter au moins {{ limit }} caractères.', maxMessage: 'Le nom de l\'entreprise ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::FREE_TEXT, message: TextInputPattern::FREE_TEXT_MESSAGE)]
|
||||
#[Groups(['client:read', 'client:write:main'])]
|
||||
private ?string $companyName = null;
|
||||
|
||||
@@ -214,11 +216,14 @@ class Client implements TimestampableInterface, BlamableInterface, ClientInterfa
|
||||
|
||||
#[ORM\Column(length: 255, nullable: true)]
|
||||
#[Assert\Length(max: 255, maxMessage: 'La liste des concurrents ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::FREE_TEXT, message: TextInputPattern::FREE_TEXT_MESSAGE)]
|
||||
#[Groups(['client:read', 'client:write:information'])]
|
||||
private ?string $competitors = null;
|
||||
|
||||
#[ORM\Column(type: 'date_immutable', nullable: true)]
|
||||
#[Groups(['client:read', 'client:write:information'])]
|
||||
// Date de creation jamais dans le futur (retour metier ERP-193) : <= aujourd'hui.
|
||||
#[Assert\LessThanOrEqual(value: 'today', message: 'La date de création ne peut pas être dans le futur.')]
|
||||
// Format d'ENTREE strict ISO `Y-m-d` (le `!` remet l'heure a 00:00:00). Sans
|
||||
// ce format, PHP DateTime accepte des formes ambigues : « 12/25/2026 » (que
|
||||
// le front MalioDate juge invalide en JJ/MM/AAAA) serait sinon interprete en
|
||||
@@ -233,12 +238,16 @@ class Client implements TimestampableInterface, BlamableInterface, ClientInterfa
|
||||
#[Groups(['client:read', 'client:write:information'])]
|
||||
private ?int $employeesCount = null;
|
||||
|
||||
// Chiffre d'affaires plafonne a 999 999 999 999,99 (12 chiffres, retour metier
|
||||
// ERP-193). La colonne (decimal 15,2) tolere plus, mais le metier borne la saisie.
|
||||
#[ORM\Column(type: 'decimal', precision: 15, scale: 2, nullable: true)]
|
||||
#[Assert\LessThanOrEqual(value: 999_999_999_999.99, message: 'Le chiffre d\'affaires ne peut pas dépasser 999 999 999 999,99.')]
|
||||
#[Groups(['client:read', 'client:write:information'])]
|
||||
private ?string $revenueAmount = null;
|
||||
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le nom du dirigeant ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::PERSON_NAME, message: TextInputPattern::PERSON_NAME_MESSAGE)]
|
||||
#[Groups(['client:read', 'client:write:information'])]
|
||||
private ?string $directorName = null;
|
||||
|
||||
@@ -257,6 +266,7 @@ class Client implements TimestampableInterface, BlamableInterface, ClientInterfa
|
||||
|
||||
#[ORM\Column(length: 40, nullable: true)]
|
||||
#[Assert\Length(max: 40, maxMessage: 'Le numéro de compte ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::CODE_ALNUM, message: TextInputPattern::CODE_ALNUM_MESSAGE)]
|
||||
#[Groups(['client:read:accounting', 'client:write:accounting'])]
|
||||
private ?string $accountNumber = null;
|
||||
|
||||
@@ -267,6 +277,7 @@ class Client implements TimestampableInterface, BlamableInterface, ClientInterfa
|
||||
|
||||
#[ORM\Column(length: 40, nullable: true)]
|
||||
#[Assert\Length(max: 40, maxMessage: 'Le numéro de TVA ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::CODE_ALNUM, message: TextInputPattern::CODE_ALNUM_MESSAGE)]
|
||||
#[Groups(['client:read:accounting', 'client:write:accounting'])]
|
||||
private ?string $nTva = null;
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ use App\Shared\Domain\Contract\ClientAddressInterface;
|
||||
use App\Shared\Domain\Contract\SiteInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use App\Shared\Domain\Validation\TextInputPattern;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
@@ -158,17 +159,20 @@ class ClientAddress implements TimestampableInterface, BlamableInterface, Client
|
||||
#[ORM\Column(length: 120)]
|
||||
#[Assert\NotBlank(message: 'La ville est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(max: 120, maxMessage: 'La ville ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
|
||||
#[Groups(['client_address:read', 'client_address:write'])]
|
||||
private ?string $city = null;
|
||||
|
||||
#[ORM\Column(length: 255)]
|
||||
#[Assert\NotBlank(message: 'La rue est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(max: 255, maxMessage: 'La rue ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
|
||||
#[Groups(['client_address:read', 'client_address:write'])]
|
||||
private ?string $street = null;
|
||||
|
||||
#[ORM\Column(length: 255, nullable: true)]
|
||||
#[Assert\Length(max: 255, maxMessage: 'Le complément d\'adresse ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
|
||||
#[Groups(['client_address:read', 'client_address:write'])]
|
||||
private ?string $streetComplement = null;
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ use App\Shared\Domain\Attribute\Auditable;
|
||||
use App\Shared\Domain\Contract\BlamableInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use App\Shared\Domain\Validation\TextInputPattern;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
@@ -94,16 +95,19 @@ class ClientContact implements TimestampableInterface, BlamableInterface
|
||||
// deux restent nullable au niveau ORM.
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le prénom ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::PERSON_NAME, message: TextInputPattern::PERSON_NAME_MESSAGE)]
|
||||
#[Groups(['client_contact:read', 'client_contact:write'])]
|
||||
private ?string $firstName = null;
|
||||
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le nom ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::PERSON_NAME, message: TextInputPattern::PERSON_NAME_MESSAGE)]
|
||||
#[Groups(['client_contact:read', 'client_contact:write'])]
|
||||
private ?string $lastName = null;
|
||||
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'La fonction ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::FREE_TEXT, message: TextInputPattern::FREE_TEXT_MESSAGE)]
|
||||
#[Groups(['client_contact:read', 'client_contact:write'])]
|
||||
private ?string $jobTitle = null;
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ use App\Shared\Domain\Contract\SiteInterface;
|
||||
use App\Shared\Domain\Contract\SupplierInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use App\Shared\Domain\Validation\TextInputPattern;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
@@ -171,6 +172,7 @@ class Supplier implements TimestampableInterface, BlamableInterface, SupplierInt
|
||||
#[ORM\Column(length: 180)]
|
||||
#[Assert\NotBlank(message: 'Le nom du fournisseur est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(min: 2, max: 180, minMessage: 'Le nom du fournisseur doit comporter au moins {{ limit }} caractères.', maxMessage: 'Le nom du fournisseur ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::FREE_TEXT, message: TextInputPattern::FREE_TEXT_MESSAGE)]
|
||||
#[Groups(['supplier:read', 'supplier:write:main'])]
|
||||
private ?string $companyName = null;
|
||||
|
||||
@@ -195,11 +197,14 @@ class Supplier implements TimestampableInterface, BlamableInterface, SupplierInt
|
||||
|
||||
#[ORM\Column(length: 255, nullable: true)]
|
||||
#[Assert\Length(max: 255, maxMessage: 'La liste des concurrents ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::FREE_TEXT, message: TextInputPattern::FREE_TEXT_MESSAGE)]
|
||||
#[Groups(['supplier:read', 'supplier:write:information'])]
|
||||
private ?string $competitors = null;
|
||||
|
||||
#[ORM\Column(type: 'date_immutable', nullable: true)]
|
||||
#[Groups(['supplier:read', 'supplier:write:information'])]
|
||||
// Date de creation jamais dans le futur (retour metier ERP-193) : <= aujourd'hui.
|
||||
#[Assert\LessThanOrEqual(value: 'today', message: 'La date de création ne peut pas être dans le futur.')]
|
||||
// Format d'ENTREE strict ISO `Y-m-d` : sans lui, PHP DateTime accepte des
|
||||
// formes ambigues (« 12/25/2026 », jugee invalide par MalioDate en JJ/MM/AAAA,
|
||||
// serait lue en M/J -> 25 decembre et acceptee a tort). Avec le format, toute
|
||||
@@ -212,12 +217,16 @@ class Supplier implements TimestampableInterface, BlamableInterface, SupplierInt
|
||||
#[Groups(['supplier:read', 'supplier:write:information'])]
|
||||
private ?int $employeesCount = null;
|
||||
|
||||
// Chiffre d'affaires plafonne a 999 999 999 999,99 (12 chiffres, retour metier
|
||||
// ERP-193). La colonne (decimal 15,2) tolere plus, mais le metier borne la saisie.
|
||||
#[ORM\Column(type: 'decimal', precision: 15, scale: 2, nullable: true)]
|
||||
#[Assert\LessThanOrEqual(value: 999_999_999_999.99, message: 'Le chiffre d\'affaires ne peut pas dépasser 999 999 999 999,99.')]
|
||||
#[Groups(['supplier:read', 'supplier:write:information'])]
|
||||
private ?string $revenueAmount = null;
|
||||
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le nom du dirigeant ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::PERSON_NAME, message: TextInputPattern::PERSON_NAME_MESSAGE)]
|
||||
#[Groups(['supplier:read', 'supplier:write:information'])]
|
||||
private ?string $directorName = null;
|
||||
|
||||
@@ -243,6 +252,7 @@ class Supplier implements TimestampableInterface, BlamableInterface, SupplierInt
|
||||
|
||||
#[ORM\Column(length: 40, nullable: true)]
|
||||
#[Assert\Length(max: 40, maxMessage: 'Le numéro de compte ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::CODE_ALNUM, message: TextInputPattern::CODE_ALNUM_MESSAGE)]
|
||||
#[Groups(['supplier:read:accounting', 'supplier:write:accounting'])]
|
||||
private ?string $accountNumber = null;
|
||||
|
||||
@@ -253,6 +263,7 @@ class Supplier implements TimestampableInterface, BlamableInterface, SupplierInt
|
||||
|
||||
#[ORM\Column(length: 40, nullable: true)]
|
||||
#[Assert\Length(max: 40, maxMessage: 'Le numéro de TVA ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::CODE_ALNUM, message: TextInputPattern::CODE_ALNUM_MESSAGE)]
|
||||
#[Groups(['supplier:read:accounting', 'supplier:write:accounting'])]
|
||||
private ?string $nTva = null;
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ use App\Shared\Domain\Contract\SiteInterface;
|
||||
use App\Shared\Domain\Contract\SupplierAddressInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use App\Shared\Domain\Validation\TextInputPattern;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
@@ -154,17 +155,20 @@ class SupplierAddress implements TimestampableInterface, BlamableInterface, Supp
|
||||
#[ORM\Column(length: 120)]
|
||||
#[Assert\NotBlank(message: 'La ville est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(max: 120, maxMessage: 'La ville ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:addresses', 'supplier_address:read'])]
|
||||
private ?string $city = null;
|
||||
|
||||
#[ORM\Column(length: 255)]
|
||||
#[Assert\NotBlank(message: 'La rue est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(max: 255, maxMessage: 'La rue ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:addresses', 'supplier_address:read'])]
|
||||
private ?string $street = null;
|
||||
|
||||
#[ORM\Column(length: 255, nullable: true)]
|
||||
#[Assert\Length(max: 255, maxMessage: 'Le complément d\'adresse ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:addresses', 'supplier_address:read'])]
|
||||
private ?string $streetComplement = null;
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ use App\Shared\Domain\Attribute\Auditable;
|
||||
use App\Shared\Domain\Contract\BlamableInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use App\Shared\Domain\Validation\TextInputPattern;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
@@ -99,16 +100,19 @@ class SupplierContact implements TimestampableInterface, BlamableInterface
|
||||
// deux restent nullable au niveau ORM.
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le prénom ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::PERSON_NAME, message: TextInputPattern::PERSON_NAME_MESSAGE)]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:contacts'])]
|
||||
private ?string $firstName = null;
|
||||
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le nom ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::PERSON_NAME, message: TextInputPattern::PERSON_NAME_MESSAGE)]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:contacts'])]
|
||||
private ?string $lastName = null;
|
||||
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'La fonction ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::FREE_TEXT, message: TextInputPattern::FREE_TEXT_MESSAGE)]
|
||||
#[Groups(['supplier:item:read', 'supplier:write:contacts'])]
|
||||
private ?string $jobTitle = null;
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ use App\Shared\Domain\Contract\CategoryInterface;
|
||||
use App\Shared\Domain\Contract\SiteInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use App\Shared\Domain\Validation\TextInputPattern;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
@@ -156,6 +157,7 @@ class Provider implements TimestampableInterface, BlamableInterface
|
||||
#[ORM\Column(length: 180)]
|
||||
#[Assert\NotBlank(message: 'Le nom du prestataire est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(min: 2, max: 180, minMessage: 'Le nom du prestataire doit comporter au moins {{ limit }} caractères.', maxMessage: 'Le nom du prestataire ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::FREE_TEXT, message: TextInputPattern::FREE_TEXT_MESSAGE)]
|
||||
#[Groups(['provider:read', 'provider:write:main'])]
|
||||
private ?string $companyName = null;
|
||||
|
||||
@@ -200,6 +202,7 @@ class Provider implements TimestampableInterface, BlamableInterface
|
||||
|
||||
#[ORM\Column(length: 40, nullable: true)]
|
||||
#[Assert\Length(max: 40, maxMessage: 'Le numéro de compte ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::CODE_ALNUM, message: TextInputPattern::CODE_ALNUM_MESSAGE)]
|
||||
#[Groups(['provider:read:accounting', 'provider:write:accounting'])]
|
||||
private ?string $accountNumber = null;
|
||||
|
||||
@@ -210,6 +213,7 @@ class Provider implements TimestampableInterface, BlamableInterface
|
||||
|
||||
#[ORM\Column(length: 40, nullable: true)]
|
||||
#[Assert\Length(max: 40, maxMessage: 'Le numéro de TVA ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::CODE_ALNUM, message: TextInputPattern::CODE_ALNUM_MESSAGE)]
|
||||
#[Groups(['provider:read:accounting', 'provider:write:accounting'])]
|
||||
private ?string $nTva = null;
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ use App\Shared\Domain\Contract\CategoryInterface;
|
||||
use App\Shared\Domain\Contract\SiteInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use App\Shared\Domain\Validation\TextInputPattern;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
@@ -135,17 +136,20 @@ class ProviderAddress implements TimestampableInterface, BlamableInterface, Prov
|
||||
#[ORM\Column(length: 120)]
|
||||
#[Assert\NotBlank(message: 'La ville est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(max: 120, maxMessage: 'La ville ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
|
||||
#[Groups(['provider:item:read', 'provider:write:addresses'])]
|
||||
private ?string $city = null;
|
||||
|
||||
#[ORM\Column(length: 255)]
|
||||
#[Assert\NotBlank(message: 'La rue est obligatoire.', normalizer: 'trim')]
|
||||
#[Assert\Length(max: 255, maxMessage: 'La rue ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
|
||||
#[Groups(['provider:item:read', 'provider:write:addresses'])]
|
||||
private ?string $street = null;
|
||||
|
||||
#[ORM\Column(length: 255, nullable: true)]
|
||||
#[Assert\Length(max: 255, maxMessage: 'Le complément d\'adresse ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
|
||||
#[Groups(['provider:item:read', 'provider:write:addresses'])]
|
||||
private ?string $streetComplement = null;
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ use App\Shared\Domain\Attribute\Auditable;
|
||||
use App\Shared\Domain\Contract\BlamableInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use App\Shared\Domain\Validation\TextInputPattern;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
@@ -102,16 +103,19 @@ class ProviderContact implements TimestampableInterface, BlamableInterface, Prov
|
||||
// champs restent nullable au niveau ORM.
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le prénom ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::PERSON_NAME, message: TextInputPattern::PERSON_NAME_MESSAGE)]
|
||||
#[Groups(['provider:item:read', 'provider:write:contacts'])]
|
||||
private ?string $firstName = null;
|
||||
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le nom ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::PERSON_NAME, message: TextInputPattern::PERSON_NAME_MESSAGE)]
|
||||
#[Groups(['provider:item:read', 'provider:write:contacts'])]
|
||||
private ?string $lastName = null;
|
||||
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'La fonction ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::FREE_TEXT, message: TextInputPattern::FREE_TEXT_MESSAGE)]
|
||||
#[Groups(['provider:item:read', 'provider:write:contacts'])]
|
||||
private ?string $jobTitle = null;
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ use App\Shared\Domain\Contract\BlamableInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Entity\UploadedDocument;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use App\Shared\Domain\Validation\TextInputPattern;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
@@ -81,6 +82,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,
|
||||
@@ -142,6 +146,7 @@ class Carrier implements TimestampableInterface, BlamableInterface
|
||||
maxMessage: 'Le nom du transporteur ne peut dépasser {{ limit }} caractères.',
|
||||
normalizer: 'trim',
|
||||
)]
|
||||
#[Assert\Regex(pattern: TextInputPattern::FREE_TEXT, message: TextInputPattern::FREE_TEXT_MESSAGE)]
|
||||
#[Groups(['carrier:read', 'carrier:write:main'])]
|
||||
private ?string $name = null;
|
||||
|
||||
@@ -195,10 +200,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 +233,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 +413,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
|
||||
|
||||
@@ -15,14 +15,16 @@ use App\Shared\Domain\Attribute\Auditable;
|
||||
use App\Shared\Domain\Contract\BlamableInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use App\Shared\Domain\Validation\TextInputPattern;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
|
||||
/**
|
||||
* 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 +32,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 +61,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 +88,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 +104,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;
|
||||
|
||||
@@ -120,22 +124,22 @@ class CarrierAddress implements TimestampableInterface, BlamableInterface
|
||||
|
||||
#[ORM\Column(length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'La ville ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
|
||||
#[Groups(['carrier:item:read', 'carrier:write:addresses'])]
|
||||
private ?string $city = null;
|
||||
|
||||
#[ORM\Column(length: 255, nullable: true)]
|
||||
#[Assert\Length(max: 255, maxMessage: 'L\'adresse ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
|
||||
#[Groups(['carrier:item:read', 'carrier:write:addresses'])]
|
||||
private ?string $street = null;
|
||||
|
||||
#[ORM\Column(name: 'street_complement', length: 255, nullable: true)]
|
||||
#[Assert\Length(max: 255, maxMessage: 'Le complément d\'adresse ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::ADDRESS, message: TextInputPattern::ADDRESS_MESSAGE)]
|
||||
#[Groups(['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 +216,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,14 +15,15 @@ use App\Shared\Domain\Attribute\Auditable;
|
||||
use App\Shared\Domain\Contract\BlamableInterface;
|
||||
use App\Shared\Domain\Contract\TimestampableInterface;
|
||||
use App\Shared\Domain\Trait\TimestampableBlamableTrait;
|
||||
use App\Shared\Domain\Validation\TextInputPattern;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
|
||||
/**
|
||||
* 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`.
|
||||
@@ -102,16 +103,19 @@ class CarrierContact implements TimestampableInterface, BlamableInterface
|
||||
// Processor + CHECK BDD). Les colonnes restent nullable au niveau ORM.
|
||||
#[ORM\Column(name: 'first_name', length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le prénom ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::PERSON_NAME, message: TextInputPattern::PERSON_NAME_MESSAGE)]
|
||||
#[Groups(['carrier:item:read', 'carrier:write:contacts'])]
|
||||
private ?string $firstName = null;
|
||||
|
||||
#[ORM\Column(name: 'last_name', length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'Le nom ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::PERSON_NAME, message: TextInputPattern::PERSON_NAME_MESSAGE)]
|
||||
#[Groups(['carrier:item:read', 'carrier:write:contacts'])]
|
||||
private ?string $lastName = null;
|
||||
|
||||
#[ORM\Column(name: 'job_title', length: 120, nullable: true)]
|
||||
#[Assert\Length(max: 120, maxMessage: 'La fonction ne peut dépasser {{ limit }} caractères.', normalizer: 'trim')]
|
||||
#[Assert\Regex(pattern: TextInputPattern::FREE_TEXT, message: TextInputPattern::FREE_TEXT_MESSAGE)]
|
||||
#[Groups(['carrier:item:read', 'carrier:write:contacts'])]
|
||||
private ?string $jobTitle = null;
|
||||
|
||||
|
||||
+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)]
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Shared\Domain\Validation;
|
||||
|
||||
/**
|
||||
* Profils de caracteres autorises pour les champs texte libres (retour metier
|
||||
* ERP-193 : bloquer les caracteres parasites « ²³§~#| … » sans casser les saisies
|
||||
* legitimes — accents, apostrophe, tiret, &, etc.).
|
||||
*
|
||||
* Approche allow-list (pas blacklist) : on definit ce qui est AUTORISE par famille
|
||||
* de champ, le reste est rejete. Couche AUTORITAIRE (back) : `#[Assert\Regex]` avec
|
||||
* ces patterns et messages FR ; le front (shared/utils/textSanitize.ts) miroite ces
|
||||
* memes ensembles en filtrant la saisie a la frappe.
|
||||
*
|
||||
* Note : `Assert\Regex` laisse passer null et la chaine vide (champs nullable OK) ;
|
||||
* seules les valeurs non vides sont controlees.
|
||||
*/
|
||||
final class TextInputPattern
|
||||
{
|
||||
/**
|
||||
* Noms de personnes (Nom, Prenom, Dirigeant) : lettres (accents inclus),
|
||||
* espace, apostrophe droite/courbe, tiret, point. Ni chiffres ni symboles.
|
||||
*/
|
||||
public const string PERSON_NAME = '/^[\p{L}\p{M} \'’.\-]+$/u';
|
||||
public const string PERSON_NAME_MESSAGE = 'Ce champ ne peut contenir que des lettres, espaces, apostrophes, tirets et points.';
|
||||
|
||||
/**
|
||||
* Texte societe / libre (Raison sociale, Concurrents, Fonction) : comme un nom
|
||||
* + chiffres, virgule, esperluette, slash, parentheses, degre (n°). Couvre
|
||||
* « Dupont & Fils », « Achats/Ventes », « Pole 2 ».
|
||||
*/
|
||||
// 0-9 (et pas \p{N}) : \p{N} engloberait les exposants ² ³ — justement parasites.
|
||||
public const string FREE_TEXT = '/^[\p{L}\p{M}0-9 \'’.,&\/()°\-]+$/u';
|
||||
public const string FREE_TEXT_MESSAGE = 'Ce champ contient des caractères non autorisés.';
|
||||
|
||||
/**
|
||||
* Adresse (voie, complement, ville) : lettres, chiffres, espace, apostrophe,
|
||||
* point, virgule, slash, degre, tiret. Couvre « 12 bis, rue de l’Église ».
|
||||
*/
|
||||
public const string ADDRESS = '/^[\p{L}\p{M}0-9 \'’.,\/°\-]+$/u';
|
||||
public const string ADDRESS_MESSAGE = 'Cette adresse contient des caractères non autorisés.';
|
||||
|
||||
/**
|
||||
* Codes alphanumeriques majuscules (N° de compte comptable, N° de TVA) :
|
||||
* uniquement A-Z et 0-9. Le front force la majuscule a la frappe.
|
||||
*/
|
||||
public const string CODE_ALNUM = '/^[A-Z0-9]+$/';
|
||||
public const string CODE_ALNUM_MESSAGE = 'Ce champ ne doit contenir que des lettres majuscules et des chiffres.';
|
||||
}
|
||||
@@ -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).',
|
||||
|
||||
@@ -95,6 +95,7 @@ final class EntityConstraintsHaveFrenchMessageTest extends TestCase
|
||||
Assert\Positive::class,
|
||||
Assert\NegativeOrZero::class,
|
||||
Assert\Negative::class,
|
||||
Assert\LessThanOrEqual::class,
|
||||
];
|
||||
|
||||
public function testEveryConstraintHasAnExplicitFrenchMessage(): void
|
||||
@@ -302,7 +303,9 @@ final class EntityConstraintsHaveFrenchMessageTest extends TestCase
|
||||
Assert\Length::class => new Assert\Length(max: 1),
|
||||
Assert\Count::class => new Assert\Count(min: 1),
|
||||
Assert\Regex::class => new Assert\Regex(pattern: '/^x$/'),
|
||||
default => new $class(),
|
||||
// AbstractComparison exige value|propertyPath des l'instanciation.
|
||||
Assert\LessThanOrEqual::class => new Assert\LessThanOrEqual(value: 0),
|
||||
default => new $class(),
|
||||
};
|
||||
|
||||
$value = $bare->{$prop} ?? null;
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Module\Commercial\Api;
|
||||
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* Validation back-autoritative de la date de creation (foundedAt) sur Client ET
|
||||
* Fournisseur — retour metier ERP-193 : une date dans le futur est refusee.
|
||||
*
|
||||
* Le front (MalioDate `:max`) plafonne deja le calendrier a aujourd'hui, mais le
|
||||
* back reste la couche autoritaire : `Assert\LessThanOrEqual('today')` rejette une
|
||||
* date future (ISO valide) avec une 422 portee sur `foundedAt` (mappable inline par
|
||||
* useFormErrors). Une date passee ou egale a aujourd'hui reste acceptee.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class FoundedAtFutureTest extends AbstractSupplierApiTestCase
|
||||
{
|
||||
/** Client : date de creation future -> 422 portee sur foundedAt. */
|
||||
public function testClientFoundedAtFuturEst422(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedClient('Founded Future SARL');
|
||||
|
||||
$body = $client->request('PATCH', '/api/clients/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['foundedAt' => $this->futureDate()],
|
||||
])->toArray(false);
|
||||
|
||||
self::assertResponseStatusCodeSame(422);
|
||||
self::assertArrayHasKey('foundedAt', $this->violationsByPath($body));
|
||||
}
|
||||
|
||||
/** Client : date de creation passee -> acceptee (200). */
|
||||
public function testClientFoundedAtPasseEst200(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedClient('Founded Past SARL');
|
||||
|
||||
$client->request('PATCH', '/api/clients/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['foundedAt' => '2000-06-15'],
|
||||
]);
|
||||
|
||||
self::assertResponseStatusCodeSame(200);
|
||||
}
|
||||
|
||||
/** Fournisseur : date de creation future -> 422 portee sur foundedAt. */
|
||||
public function testSupplierFoundedAtFuturEst422(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedSupplier('Founded Future Fournisseur SARL');
|
||||
|
||||
$body = $client->request('PATCH', '/api/suppliers/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['foundedAt' => $this->futureDate()],
|
||||
])->toArray(false);
|
||||
|
||||
self::assertResponseStatusCodeSame(422);
|
||||
self::assertArrayHasKey('foundedAt', $this->violationsByPath($body));
|
||||
}
|
||||
|
||||
/** Fournisseur : date de creation passee -> acceptee (200). */
|
||||
public function testSupplierFoundedAtPasseEst200(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedSupplier('Founded Past Fournisseur SARL');
|
||||
|
||||
$client->request('PATCH', '/api/suppliers/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['foundedAt' => '2000-06-15'],
|
||||
]);
|
||||
|
||||
self::assertResponseStatusCodeSame(200);
|
||||
}
|
||||
|
||||
/** Date ISO clairement dans le futur. */
|
||||
private function futureDate(): string
|
||||
{
|
||||
return new DateTimeImmutable('+1 year')->format('Y-m-d');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Module\Commercial\Api;
|
||||
|
||||
/**
|
||||
* Validation back-autoritative du plafond du chiffre d'affaires (revenueAmount,
|
||||
* onglet Information) sur Client ET Fournisseur — retour metier ERP-193.
|
||||
*
|
||||
* Le CA est plafonne a 999 999 999 999,99 (12 chiffres). La colonne decimal(15,2)
|
||||
* tolererait plus, mais le metier borne la saisie : au-dela, 422 porte sur
|
||||
* `revenueAmount` (mappable inline par useFormErrors). La valeur exactement egale
|
||||
* au plafond reste acceptee. Le front clampe deja la saisie (amountInput.ts), mais
|
||||
* le back reste la couche autoritaire.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class RevenueAmountCapTest extends AbstractSupplierApiTestCase
|
||||
{
|
||||
/** Plafond metier : 12 chiffres + 2 decimales. */
|
||||
private const string MAX = '999999999999.99';
|
||||
|
||||
/** Client : CA au-dela du plafond -> 422 porte sur revenueAmount. */
|
||||
public function testClientRevenueAmountAuDelaDuPlafondEst422(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedClient('CA Cap Client SARL');
|
||||
|
||||
$body = $client->request('PATCH', '/api/clients/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['revenueAmount' => '1000000000000.00'],
|
||||
])->toArray(false);
|
||||
|
||||
self::assertResponseStatusCodeSame(422);
|
||||
self::assertArrayHasKey('revenueAmount', $this->violationsByPath($body));
|
||||
}
|
||||
|
||||
/** Client : CA exactement au plafond -> accepte (200). */
|
||||
public function testClientRevenueAmountAuPlafondEst200(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedClient('CA Max Client SARL');
|
||||
|
||||
$client->request('PATCH', '/api/clients/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['revenueAmount' => self::MAX],
|
||||
]);
|
||||
|
||||
self::assertResponseStatusCodeSame(200);
|
||||
}
|
||||
|
||||
/** Fournisseur : CA au-dela du plafond -> 422 porte sur revenueAmount. */
|
||||
public function testSupplierRevenueAmountAuDelaDuPlafondEst422(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedSupplier('CA Cap Fournisseur SARL');
|
||||
|
||||
$body = $client->request('PATCH', '/api/suppliers/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['revenueAmount' => '1000000000000.00'],
|
||||
])->toArray(false);
|
||||
|
||||
self::assertResponseStatusCodeSame(422);
|
||||
self::assertArrayHasKey('revenueAmount', $this->violationsByPath($body));
|
||||
}
|
||||
|
||||
/** Fournisseur : CA exactement au plafond -> accepte (200). */
|
||||
public function testSupplierRevenueAmountAuPlafondEst200(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedSupplier('CA Max Fournisseur SARL');
|
||||
|
||||
$client->request('PATCH', '/api/suppliers/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['revenueAmount' => self::MAX],
|
||||
]);
|
||||
|
||||
self::assertResponseStatusCodeSame(200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Module\Commercial\Api;
|
||||
|
||||
/**
|
||||
* Validation back-autoritative des caracteres autorises dans les champs texte
|
||||
* (retour metier ERP-193) : on rejette les caracteres parasites « ²³§~#| … » via
|
||||
* une allow-list par profil (App\Shared\Domain\Validation\TextInputPattern). Le
|
||||
* front filtre deja a la frappe, mais le back reste l'autorite : une 422 portee
|
||||
* sur le champ fautif (mappable inline par useFormErrors).
|
||||
*
|
||||
* On couvre les clients (M1) et les fournisseurs (M2) — meme socle de profils.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class TextInputSanitizationTest extends AbstractSupplierApiTestCase
|
||||
{
|
||||
/** Raison sociale avec exposants ²³ et § -> 422 sur companyName. */
|
||||
public function testClientCompanyNameAvecParasitesEst422(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedClient('Parasite Client SARL');
|
||||
|
||||
$body = $client->request('PATCH', '/api/clients/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['companyName' => 'ACME²³§'],
|
||||
])->toArray(false);
|
||||
|
||||
self::assertResponseStatusCodeSame(422);
|
||||
self::assertArrayHasKey('companyName', $this->violationsByPath($body));
|
||||
}
|
||||
|
||||
/** Raison sociale legitime « Dupont & Fils » (esperluette) -> acceptee (200). */
|
||||
public function testClientCompanyNameLegitimeEst200(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedClient('Legit Client SARL');
|
||||
|
||||
$client->request('PATCH', '/api/clients/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['companyName' => 'Dupont & Fils (Pôle n°2)'],
|
||||
]);
|
||||
|
||||
self::assertResponseStatusCodeSame(200);
|
||||
}
|
||||
|
||||
/** Dirigeant avec chiffres -> 422 (profil nom de personne, pas de chiffres). */
|
||||
public function testClientDirectorNameAvecChiffresEst422(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedClient('Director Parasite SARL');
|
||||
|
||||
$body = $client->request('PATCH', '/api/clients/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['directorName' => 'Jean123'],
|
||||
])->toArray(false);
|
||||
|
||||
self::assertResponseStatusCodeSame(422);
|
||||
self::assertArrayHasKey('directorName', $this->violationsByPath($body));
|
||||
}
|
||||
|
||||
/** N° de compte avec caractere special -> 422 (profil code alphanumerique). */
|
||||
public function testClientAccountNumberAvecParasiteEst422(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedClient('Account Parasite SARL');
|
||||
|
||||
$body = $client->request('PATCH', '/api/clients/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['accountNumber' => '411#DUP'],
|
||||
])->toArray(false);
|
||||
|
||||
self::assertResponseStatusCodeSame(422);
|
||||
self::assertArrayHasKey('accountNumber', $this->violationsByPath($body));
|
||||
}
|
||||
|
||||
/** Fournisseur : raison sociale avec parasites -> 422 sur companyName. */
|
||||
public function testSupplierCompanyNameAvecParasitesEst422(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedSupplier('Parasite Fournisseur SARL');
|
||||
|
||||
$body = $client->request('PATCH', '/api/suppliers/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['companyName' => 'NEGOCE~#|²'],
|
||||
])->toArray(false);
|
||||
|
||||
self::assertResponseStatusCodeSame(422);
|
||||
self::assertArrayHasKey('companyName', $this->violationsByPath($body));
|
||||
}
|
||||
}
|
||||
@@ -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