feat(front) : page Ajouter un fournisseur (/suppliers/new) + workflow par onglets (ERP-94)
This commit is contained in:
@@ -116,6 +116,81 @@
|
||||
"loading": "Chargement du fournisseur…",
|
||||
"notFound": "Fournisseur introuvable.",
|
||||
"save": "Valider"
|
||||
},
|
||||
"form": {
|
||||
"title": "Ajouter un fournisseur",
|
||||
"back": "Précédent",
|
||||
"submit": "Valider",
|
||||
"duplicateCompany": "Un fournisseur portant ce nom de société existe déjà.",
|
||||
"main": {
|
||||
"companyName": "Nom du fournisseur (Entreprise)",
|
||||
"categories": "Catégorie"
|
||||
},
|
||||
"information": {
|
||||
"description": "Description",
|
||||
"competitors": "Concurrent",
|
||||
"foundedAt": "Date de création",
|
||||
"employeesCount": "Nombre de salariés",
|
||||
"revenueAmount": "CA",
|
||||
"profitAmount": "Résultat",
|
||||
"directorName": "Dirigeant",
|
||||
"volumeForecast": "Volume prévisionnel"
|
||||
},
|
||||
"contact": {
|
||||
"title": "Contact {n}",
|
||||
"lastName": "Nom",
|
||||
"firstName": "Prénom",
|
||||
"jobTitle": "Fonction",
|
||||
"email": "Email",
|
||||
"phonePrimary": "Téléphone",
|
||||
"phoneSecondary": "Téléphone (2)",
|
||||
"addPhone": "Ajouter un numéro",
|
||||
"remove": "Supprimer le contact",
|
||||
"add": "Nouveau contact"
|
||||
},
|
||||
"address": {
|
||||
"title": "Adresse {n}",
|
||||
"addressType": "Type d'adresse",
|
||||
"addressTypeProspect": "Prospect",
|
||||
"addressTypeDepart": "Départ",
|
||||
"addressTypeRendu": "Rendu",
|
||||
"categories": "Catégorie",
|
||||
"country": "Pays",
|
||||
"postalCode": "Code postal",
|
||||
"city": "Ville",
|
||||
"street": "Adresse",
|
||||
"streetNotFound": "Adresse introuvable ? Saisissez-la directement.",
|
||||
"streetComplement": "Adresse complémentaire",
|
||||
"sites": "Sites",
|
||||
"contacts": "Contact(s) rattaché(s)",
|
||||
"bennes": "Benne(s)",
|
||||
"triageProvider": "Prestation de triage",
|
||||
"remove": "Supprimer l'adresse",
|
||||
"add": "Nouvelle adresse",
|
||||
"degraded": "Service d'adresse indisponible : saisie de la ville et de l'adresse en mode libre."
|
||||
},
|
||||
"accounting": {
|
||||
"siren": "SIREN",
|
||||
"accountNumber": "Numéro de compte",
|
||||
"tvaMode": "Mode de TVA",
|
||||
"nTva": "N° de TVA",
|
||||
"paymentDelay": "Délai de règlement",
|
||||
"paymentType": "Type de règlement",
|
||||
"bank": "Banque",
|
||||
"ribLabel": "Libellé",
|
||||
"ribBic": "BIC",
|
||||
"ribIban": "IBAN",
|
||||
"addRib": "Ajouter un RIB",
|
||||
"removeRib": "Supprimer le RIB"
|
||||
},
|
||||
"confirmDelete": {
|
||||
"title": "Confirmer la suppression",
|
||||
"contact": "Supprimer ce contact ?",
|
||||
"address": "Supprimer cette adresse ?",
|
||||
"rib": "Supprimer ce RIB ?",
|
||||
"cancel": "Annuler",
|
||||
"confirm": "Confirmer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"clients": {
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
<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 cote parent. -->
|
||||
<MalioButtonIcon
|
||||
v-if="removable && !readonly"
|
||||
icon="mdi:delete-outline"
|
||||
variant="ghost"
|
||||
button-class="absolute top-3 right-3"
|
||||
v-bind="{ ariaLabel: t('commercial.suppliers.form.address.remove') }"
|
||||
@click="$emit('remove')"
|
||||
/>
|
||||
|
||||
<!-- Type d'adresse : radio exclusif Prospect / Depart / Rendu (RG-2.09).
|
||||
Erreur portee sur `addressType` cote back (Assert\Choice + NotNull)
|
||||
-> affichee sous le groupe. col-span-2 pour loger les 3 options. -->
|
||||
<div class="col-span-2 flex flex-col gap-1">
|
||||
<span class="text-sm font-medium">
|
||||
{{ t('commercial.suppliers.form.address.addressType') }}<span class="text-red-600"> *</span>
|
||||
</span>
|
||||
<div class="flex items-center gap-6">
|
||||
<MalioRadioButton
|
||||
v-for="opt in addressTypeOptions"
|
||||
:key="opt.value"
|
||||
:name="radioName"
|
||||
:model-value="model.addressType"
|
||||
:value="opt.value"
|
||||
:label="opt.label"
|
||||
:readonly="readonly"
|
||||
:disabled="readonly"
|
||||
group-class="mt-0"
|
||||
@update:model-value="() => update('addressType', opt.value)"
|
||||
/>
|
||||
</div>
|
||||
<span v-if="errors?.addressType" class="text-sm text-red-600">{{ errors.addressType }}</span>
|
||||
</div>
|
||||
|
||||
<MalioSelect
|
||||
:model-value="model.country"
|
||||
:options="countryOptions"
|
||||
:label="t('commercial.suppliers.form.address.country')"
|
||||
:readonly="readonly"
|
||||
:required="true"
|
||||
@update:model-value="(v: string | number | null) => update('country', String(v ?? 'France'))"
|
||||
/>
|
||||
|
||||
<MalioInputText
|
||||
:model-value="model.postalCode"
|
||||
:label="t('commercial.suppliers.form.address.postalCode')"
|
||||
:mask="POSTAL_CODE_MASK"
|
||||
:readonly="readonly"
|
||||
:required="true"
|
||||
:error="errors?.postalCode"
|
||||
@update:model-value="onPostalCodeChange"
|
||||
/>
|
||||
|
||||
<!-- Ville : MalioSelect alimente par le code postal (BAN). Saisie libre si BAN indispo. -->
|
||||
<MalioSelect
|
||||
v-if="!degraded"
|
||||
:model-value="model.city"
|
||||
:options="cityOptions"
|
||||
:label="t('commercial.suppliers.form.address.city')"
|
||||
:readonly="readonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="errors?.city"
|
||||
@update:model-value="(v: string | number | null) => update('city', v === null ? null : String(v))"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-else
|
||||
:model-value="model.city"
|
||||
:label="t('commercial.suppliers.form.address.city')"
|
||||
:readonly="readonly"
|
||||
:required="true"
|
||||
:error="errors?.city"
|
||||
@update:model-value="(v: string) => update('city', v)"
|
||||
/>
|
||||
|
||||
<!-- Adresse (BAN) + Adresse complementaire. allow-create : le texte saisi
|
||||
est conserve si la BAN ne propose rien (saisie manuelle). -->
|
||||
<div class="col-span-2">
|
||||
<MalioInputAutocomplete
|
||||
v-if="!readonly"
|
||||
:model-value="model.street"
|
||||
:options="addressOptions"
|
||||
:loading="addressLoading"
|
||||
:min-search-length="3"
|
||||
:label="t('commercial.suppliers.form.address.street')"
|
||||
:readonly="readonly"
|
||||
:required="true"
|
||||
:error="errors?.street"
|
||||
:allow-create="true"
|
||||
:no-results-text="t('commercial.suppliers.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('commercial.suppliers.form.address.street')"
|
||||
:readonly="readonly"
|
||||
:required="true"
|
||||
:error="errors?.street"
|
||||
@update:model-value="(v: string) => update('street', v)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="col-span-1">
|
||||
<MalioInputText
|
||||
:model-value="model.streetComplement"
|
||||
:label="t('commercial.suppliers.form.address.streetComplement')"
|
||||
:readonly="readonly"
|
||||
:error="errors?.streetComplement"
|
||||
@update:model-value="(v: string) => update('streetComplement', v)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Sites Starseed (>= 1 obligatoire, RG-2.06). -->
|
||||
<MalioSelectCheckbox
|
||||
:model-value="model.siteIris"
|
||||
:options="siteOptions"
|
||||
:label="t('commercial.suppliers.form.address.sites')"
|
||||
:display-tag="true"
|
||||
:readonly="readonly"
|
||||
:required="true"
|
||||
:error="errors?.sites"
|
||||
@update:model-value="(v: (string | number)[]) => update('siteIris', v.map(String))"
|
||||
/>
|
||||
|
||||
<!-- Categories de type FOURNISSEUR (>= 1 obligatoire, RG-2.10). -->
|
||||
<MalioSelectCheckbox
|
||||
:model-value="model.categoryIris"
|
||||
:options="categoryOptions"
|
||||
:label="t('commercial.suppliers.form.address.categories')"
|
||||
:display-tag="true"
|
||||
:readonly="readonly"
|
||||
:required="true"
|
||||
:error="errors?.categories"
|
||||
@update:model-value="(v: (string | number)[]) => update('categoryIris', v.map(String))"
|
||||
/>
|
||||
|
||||
<!-- Contacts rattaches (M2M, facultatif). -->
|
||||
<MalioSelectCheckbox
|
||||
:model-value="model.contactIris"
|
||||
:options="contactOptions"
|
||||
:label="t('commercial.suppliers.form.address.contacts')"
|
||||
:display-tag="true"
|
||||
:readonly="readonly"
|
||||
@update:model-value="(v: (string | number)[]) => update('contactIris', v.map(String))"
|
||||
/>
|
||||
|
||||
<!-- Filler : pousse Bennes + Triage sur une nouvelle ligne (disposition maquette). -->
|
||||
<div aria-hidden="true" />
|
||||
|
||||
<!-- Bennes : stepper (specifique fournisseur, defaut 0). -->
|
||||
<MalioInputNumber
|
||||
:model-value="model.bennes"
|
||||
:label="t('commercial.suppliers.form.address.bennes')"
|
||||
:min="0"
|
||||
:readonly="readonly"
|
||||
:error="errors?.bennes"
|
||||
@update:model-value="(v: string) => update('bennes', v)"
|
||||
/>
|
||||
|
||||
<!-- Prestation de triage : booleen porte par l'adresse (specifique fournisseur). -->
|
||||
<MalioCheckbox
|
||||
id="address-triage-provider"
|
||||
:label="t('commercial.suppliers.form.address.triageProvider')"
|
||||
:model-value="model.triageProvider"
|
||||
group-class="self-center"
|
||||
:readonly="readonly"
|
||||
@update:model-value="(v: boolean) => update('triageProvider', v)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
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'
|
||||
|
||||
// Masque code postal FR : 5 chiffres.
|
||||
const POSTAL_CODE_MASK = '#####'
|
||||
|
||||
const props = defineProps<{
|
||||
/** Brouillon de l'adresse (v-model). */
|
||||
modelValue: SupplierAddressFormDraft
|
||||
title: string
|
||||
/** Categories autorisees sur une adresse (type FOURNISSEUR). */
|
||||
categoryOptions: CategoryOption[]
|
||||
/** Sites Starseed disponibles. */
|
||||
siteOptions: RefOption[]
|
||||
/** Contacts deja saisis, rattachables a l'adresse. */
|
||||
contactOptions: RefOption[]
|
||||
/** Pays disponibles (France par defaut). */
|
||||
countryOptions: RefOption[]
|
||||
removable?: boolean
|
||||
readonly?: boolean
|
||||
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: SupplierAddressFormDraft]
|
||||
'remove': []
|
||||
/** Emis une fois quand le service d'autocompletion bascule en indisponible. */
|
||||
'degraded': []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const autocomplete = useAddressAutocomplete()
|
||||
|
||||
const model = computed(() => props.modelValue)
|
||||
|
||||
// Nom de groupe radio unique par bloc (sinon les radios de blocs differents se
|
||||
// partageraient la selection). Derive du titre (« Adresse 1 », « Adresse 2 »...).
|
||||
const radioName = computed(() => `supplier-address-type-${props.title.replace(/\s+/g, '-')}`)
|
||||
|
||||
const addressTypeOptions = computed<{ value: SupplierAddressType, label: string }[]>(() => [
|
||||
{ value: 'PROSPECT', label: t('commercial.suppliers.form.address.addressTypeProspect') },
|
||||
{ value: 'DEPART', label: t('commercial.suppliers.form.address.addressTypeDepart') },
|
||||
{ value: 'RENDU', label: t('commercial.suppliers.form.address.addressTypeRendu') },
|
||||
])
|
||||
|
||||
// Repli saisie libre de la VILLE quand la BAN est indisponible (recuperable).
|
||||
const degraded = ref(false)
|
||||
let unavailableNotified = false
|
||||
const banCityOptions = ref<RefOption[]>([])
|
||||
const banAddressOptions = ref<RefOption[]>([])
|
||||
|
||||
// Options ville effectives : on garantit que la ville courante figure toujours
|
||||
// dans la liste, sinon MalioSelect afficherait un champ vide en lecture seule.
|
||||
const cityOptions = computed<RefOption[]>(() => {
|
||||
const current = props.modelValue.city
|
||||
if (current && !banCityOptions.value.some(o => o.value === current)) {
|
||||
return [{ value: current, label: current }, ...banCityOptions.value]
|
||||
}
|
||||
return banCityOptions.value
|
||||
})
|
||||
|
||||
// Meme garantie pour le champ Adresse : la rue courante doit toujours figurer
|
||||
// dans les options, sinon MalioInputAutocomplete laisse le champ vide.
|
||||
const addressOptions = computed<RefOption[]>(() => {
|
||||
const current = props.modelValue.street
|
||||
if (current && !banAddressOptions.value.some(o => o.value === current)) {
|
||||
return [{ value: current, label: current }, ...banAddressOptions.value]
|
||||
}
|
||||
return banAddressOptions.value
|
||||
})
|
||||
const addressLoading = ref(false)
|
||||
// Conserve les suggestions d'adresse pour retrouver ville/CP au moment du select.
|
||||
let lastAddressSuggestions: AddressSuggestion[] = []
|
||||
|
||||
/** Emet un nouveau brouillon avec le champ modifie (immutabilite). */
|
||||
function update<K extends keyof SupplierAddressFormDraft>(field: K, value: SupplierAddressFormDraft[K]): void {
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: value })
|
||||
}
|
||||
|
||||
/** Previent le parent (toast unique) que l'autocompletion est indisponible. */
|
||||
function notifyUnavailable(): void {
|
||||
if (!unavailableNotified) {
|
||||
unavailableNotified = true
|
||||
emit('degraded')
|
||||
}
|
||||
}
|
||||
|
||||
/** Saisie du code postal → met a jour le champ + interroge la BAN pour la ville. */
|
||||
async function onPostalCodeChange(value: string): Promise<void> {
|
||||
update('postalCode', value)
|
||||
|
||||
const digits = (value ?? '').replace(/\D/g, '')
|
||||
if (digits.length < 5) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const suggestions = await autocomplete.searchCity(digits)
|
||||
banCityOptions.value = suggestions.map(s => ({ value: s.city, label: s.city }))
|
||||
degraded.value = false
|
||||
}
|
||||
catch {
|
||||
degraded.value = true
|
||||
notifyUnavailable()
|
||||
}
|
||||
}
|
||||
|
||||
/** Recherche d'adresse assistee (event de MalioInputAutocomplete). */
|
||||
async function onAddressSearch(query: string): Promise<void> {
|
||||
// La BAN exige au moins 3 caracteres : on n'envoie rien en deca (evite un 400).
|
||||
if (query.trim().length < 3) {
|
||||
banAddressOptions.value = []
|
||||
return
|
||||
}
|
||||
addressLoading.value = true
|
||||
try {
|
||||
const postalCode = (model.value.postalCode ?? '').replace(/\D/g, '') || undefined
|
||||
const suggestions = await autocomplete.searchAddress(query, postalCode)
|
||||
lastAddressSuggestions = suggestions
|
||||
banAddressOptions.value = suggestions.map(s => ({ value: s.street, label: s.label }))
|
||||
}
|
||||
catch {
|
||||
// Erreur transitoire : on vide les suggestions, la prochaine frappe reessaie.
|
||||
banAddressOptions.value = []
|
||||
notifyUnavailable()
|
||||
}
|
||||
finally {
|
||||
addressLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Selection d'une suggestion d'adresse → remplit rue + ville + CP. */
|
||||
function onAddressSelect(option: { label: string, value: string | number } | null): void {
|
||||
if (option === null) {
|
||||
return
|
||||
}
|
||||
const suggestion = lastAddressSuggestions.find(s => s.street === option.value)
|
||||
if (!suggestion) {
|
||||
update('street', String(option.value))
|
||||
return
|
||||
}
|
||||
emit('update:modelValue', {
|
||||
...props.modelValue,
|
||||
street: suggestion.street,
|
||||
city: suggestion.city,
|
||||
postalCode: suggestion.postalCode,
|
||||
})
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,104 @@
|
||||
<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 cote parent. Masquee si
|
||||
non supprimable (1er bloc, RG-2.13) ou en lecture seule. -->
|
||||
<MalioButtonIcon
|
||||
v-if="removable && !readonly"
|
||||
icon="mdi:delete-outline"
|
||||
variant="ghost"
|
||||
button-class="absolute top-3 right-3"
|
||||
v-bind="{ ariaLabel: t('commercial.suppliers.form.contact.remove') }"
|
||||
@click="$emit('remove')"
|
||||
/>
|
||||
|
||||
<MalioInputText
|
||||
:model-value="model.lastName"
|
||||
:label="t('commercial.suppliers.form.contact.lastName')"
|
||||
:readonly="readonly"
|
||||
:error="errors?.lastName"
|
||||
@update:model-value="(v: string) => update('lastName', v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="model.firstName"
|
||||
:label="t('commercial.suppliers.form.contact.firstName')"
|
||||
:readonly="readonly"
|
||||
:error="errors?.firstName"
|
||||
@update:model-value="(v: string) => update('firstName', v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="model.jobTitle"
|
||||
:label="t('commercial.suppliers.form.contact.jobTitle')"
|
||||
:readonly="readonly"
|
||||
:error="errors?.jobTitle"
|
||||
@update:model-value="(v: string) => update('jobTitle', v)"
|
||||
/>
|
||||
<MalioInputEmail
|
||||
:model-value="model.email"
|
||||
:label="t('commercial.suppliers.form.contact.email')"
|
||||
:readonly="readonly"
|
||||
:lowercase="true"
|
||||
:error="errors?.email"
|
||||
@update:model-value="(v: string) => update('email', v)"
|
||||
/>
|
||||
<MalioInputPhone
|
||||
:model-value="model.phonePrimary"
|
||||
:label="t('commercial.suppliers.form.contact.phonePrimary')"
|
||||
:mask="PHONE_MASK"
|
||||
:readonly="readonly"
|
||||
:error="errors?.phonePrimary"
|
||||
:addable="!model.hasSecondaryPhone && !readonly"
|
||||
:add-button-label="t('commercial.suppliers.form.contact.addPhone')"
|
||||
@update:model-value="(v: string) => update('phonePrimary', v)"
|
||||
@add="revealSecondaryPhone"
|
||||
/>
|
||||
<MalioInputPhone
|
||||
v-if="model.hasSecondaryPhone"
|
||||
:model-value="model.phoneSecondary"
|
||||
:label="t('commercial.suppliers.form.contact.phoneSecondary')"
|
||||
:mask="PHONE_MASK"
|
||||
:readonly="readonly"
|
||||
:error="errors?.phoneSecondary"
|
||||
@update:model-value="(v: string) => update('phoneSecondary', v)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { SupplierContactFormDraft } from '~/modules/commercial/types/supplierForm'
|
||||
|
||||
// Masque telephone FR : 5 groupes de 2 chiffres (la normalisation finale reste serveur).
|
||||
const PHONE_MASK = '## ## ## ## ##'
|
||||
|
||||
const props = defineProps<{
|
||||
/** Brouillon du contact (v-model). */
|
||||
modelValue: SupplierContactFormDraft
|
||||
/** Titre du bloc (ex: « Contact 1 »). */
|
||||
title: string
|
||||
/** Affiche l'icone de suppression (1er bloc non supprimable, RG-2.13). */
|
||||
removable?: boolean
|
||||
/** Bloc en lecture seule (onglet valide). */
|
||||
readonly?: boolean
|
||||
/** Erreurs serveur 422 de cette ligne, indexees par champ (ERP-101). */
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: SupplierContactFormDraft]
|
||||
'remove': []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
// Alias local pour la lisibilite du template.
|
||||
const model = computed(() => props.modelValue)
|
||||
|
||||
/** Emet un nouveau brouillon avec le champ modifie (immutabilite). */
|
||||
function update<K extends keyof SupplierContactFormDraft>(field: K, value: SupplierContactFormDraft[K]): void {
|
||||
emit('update:modelValue', { ...props.modelValue, [field]: value })
|
||||
}
|
||||
|
||||
/** Revele le 2e numero (max 1 secondaire, le « + » disparait). */
|
||||
function revealSecondaryPhone(): void {
|
||||
emit('update:modelValue', { ...props.modelValue, hasSecondaryPhone: true })
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,173 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { mount, flushPromises } from '@vue/test-utils'
|
||||
import { defineComponent, h, ref, computed } from 'vue'
|
||||
import { emptyAddress } from '~/modules/commercial/types/supplierForm'
|
||||
import SupplierAddressBlock from '../SupplierAddressBlock.vue'
|
||||
|
||||
// Mocks controlables du composable BAN (hoisted).
|
||||
const { searchCityMock, searchAddressMock } = vi.hoisted(() => ({
|
||||
searchCityMock: vi.fn(),
|
||||
searchAddressMock: vi.fn(),
|
||||
}))
|
||||
vi.mock('~/shared/composables/useAddressAutocomplete', () => ({
|
||||
useAddressAutocomplete: () => ({
|
||||
searchCity: searchCityMock,
|
||||
searchAddress: searchAddressMock,
|
||||
}),
|
||||
}))
|
||||
|
||||
// Auto-imports Nuxt/Vue utilises sans import explicite par le composant.
|
||||
vi.stubGlobal('useI18n', () => ({ t: (key: string) => key }))
|
||||
vi.stubGlobal('ref', ref)
|
||||
vi.stubGlobal('computed', computed)
|
||||
|
||||
// Stub de MalioInputAutocomplete : expose les `value` des options + allowCreate.
|
||||
const MalioInputAutocompleteStub = defineComponent({
|
||||
name: 'MalioInputAutocomplete',
|
||||
props: {
|
||||
modelValue: { type: [String, Number, null], default: undefined },
|
||||
options: { type: Array as () => { value: string | number, label: string }[], default: () => [] },
|
||||
loading: { type: Boolean, default: false },
|
||||
minSearchLength: { type: Number, default: 0 },
|
||||
label: { type: String, default: '' },
|
||||
readonly: { 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> = {}, errors?: Record<string, string>) {
|
||||
return mount(SupplierAddressBlock, {
|
||||
props: {
|
||||
modelValue: { ...emptyAddress(), ...overrides },
|
||||
title: 'Adresse 1',
|
||||
categoryOptions: [],
|
||||
siteOptions: [],
|
||||
contactOptions: [],
|
||||
countryOptions: [],
|
||||
...(errors ? { errors } : {}),
|
||||
},
|
||||
global: {
|
||||
stubs: {
|
||||
MalioButtonIcon: true,
|
||||
MalioCheckbox: true,
|
||||
MalioRadioButton: true,
|
||||
MalioInputNumber: true,
|
||||
MalioSelect: true,
|
||||
MalioSelectCheckbox: true,
|
||||
MalioInputText: true,
|
||||
MalioInputAutocomplete: MalioInputAutocompleteStub,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
describe('SupplierAddressBlock — specificites M2 (radio type, bennes, triage)', () => {
|
||||
it('rend les 3 options de type d\'adresse (Prospect / Départ / Rendu)', () => {
|
||||
const wrapper = mountBlock()
|
||||
expect(wrapper.findAll('malio-radio-button-stub')).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('rend le stepper Bennes et la case Prestation de triage (champs specifiques fournisseur)', () => {
|
||||
const wrapper = mountBlock()
|
||||
expect(wrapper.find('malio-input-number-stub').exists()).toBe(true)
|
||||
expect(wrapper.find('malio-checkbox-stub').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('ne rend aucun champ d\'email de facturation (difference M1)', () => {
|
||||
const wrapper = mountBlock()
|
||||
// Aucun MalioInputEmail dans le bloc adresse fournisseur.
|
||||
expect(wrapper.find('malio-input-email-stub').exists()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('SupplierAddressBlock — mapping erreur par champ (ERP-101)', () => {
|
||||
it('affiche l\'erreur serveur du type d\'adresse (propertyPath addressType)', () => {
|
||||
const wrapper = mountBlock({}, { addressType: 'Le type d\'adresse doit être Prospect, Départ ou Rendu.' })
|
||||
expect(wrapper.text()).toContain('Le type d\'adresse doit être Prospect, Départ ou Rendu.')
|
||||
})
|
||||
|
||||
it('affiche les erreurs serveur sur sites et categories', () => {
|
||||
const wrapper = mountBlock({}, {
|
||||
sites: 'Au moins un site est obligatoire.',
|
||||
categories: 'Au moins une catégorie est obligatoire.',
|
||||
})
|
||||
const checkboxes = wrapper.findAll('malio-select-checkbox-stub')
|
||||
const sitesField = checkboxes.find(el => el.attributes('label') === 'commercial.suppliers.form.address.sites')
|
||||
const categoriesField = checkboxes.find(el => el.attributes('label') === 'commercial.suppliers.form.address.categories')
|
||||
|
||||
expect(sitesField?.attributes('error')).toBe('Au moins un site est obligatoire.')
|
||||
expect(categoriesField?.attributes('error')).toBe('Au moins une catégorie est obligatoire.')
|
||||
})
|
||||
|
||||
it('affiche l\'erreur serveur sur le code postal', () => {
|
||||
const wrapper = mountBlock({}, { postalCode: 'Code postal invalide.' })
|
||||
const field = wrapper.findAll('malio-input-text-stub').find(
|
||||
el => el.attributes('label') === 'commercial.suppliers.form.address.postalCode',
|
||||
)
|
||||
expect(field?.attributes('error')).toBe('Code postal invalide.')
|
||||
})
|
||||
})
|
||||
|
||||
describe('SupplierAddressBlock — autocompletion adresse (BAN) robuste', () => {
|
||||
beforeEach(() => {
|
||||
searchAddressMock.mockReset()
|
||||
})
|
||||
|
||||
it('n\'appelle pas la BAN en deca de 3 caracteres', async () => {
|
||||
const wrapper = mountBlock()
|
||||
wrapper.findComponent(MalioInputAutocompleteStub).vm.$emit('search', 'ab')
|
||||
await flushPromises()
|
||||
expect(searchAddressMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('relance la recherche apres une erreur (pas de bascule definitive)', async () => {
|
||||
searchAddressMock
|
||||
.mockRejectedValueOnce(new Error('BAN indisponible'))
|
||||
.mockResolvedValueOnce([
|
||||
{ label: '8 Boulevard du Port, Paris', street: '8 Boulevard du Port', postalCode: '75001', city: 'Paris' },
|
||||
])
|
||||
|
||||
const wrapper = mountBlock()
|
||||
const auto = wrapper.findComponent(MalioInputAutocompleteStub)
|
||||
|
||||
auto.vm.$emit('search', 'boulevard du port')
|
||||
await flushPromises()
|
||||
auto.vm.$emit('search', 'boulevard du porte')
|
||||
await flushPromises()
|
||||
|
||||
expect(searchAddressMock).toHaveBeenCalledTimes(2)
|
||||
expect(wrapper.find('[data-testid="addr-autocomplete"]').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('emet « degraded » une seule fois malgre plusieurs erreurs', async () => {
|
||||
searchAddressMock.mockRejectedValue(new Error('BAN indisponible'))
|
||||
|
||||
const wrapper = mountBlock()
|
||||
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)
|
||||
})
|
||||
|
||||
it('inclut la rue courante dans les options meme sans recherche BAN', () => {
|
||||
const wrapper = mountBlock({ street: '8 Boulevard du Port' })
|
||||
const values = JSON.parse(wrapper.find('[data-testid="addr-autocomplete"]').attributes('data-options') ?? '[]')
|
||||
expect(values).toContain('8 Boulevard du Port')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { defineComponent, h, ref, computed } from 'vue'
|
||||
import { emptyContact } from '~/modules/commercial/types/supplierForm'
|
||||
import SupplierContactBlock from '../SupplierContactBlock.vue'
|
||||
|
||||
// Auto-imports Nuxt/Vue utilises sans import explicite par le composant.
|
||||
vi.stubGlobal('useI18n', () => ({ t: (key: string) => key }))
|
||||
vi.stubGlobal('ref', ref)
|
||||
vi.stubGlobal('computed', computed)
|
||||
|
||||
/** Stub d'un champ Malio qui re-expose la prop `error` recue dans un data-* attribut. */
|
||||
function errorProbe(testid: string) {
|
||||
return defineComponent({
|
||||
name: `Probe-${testid}`,
|
||||
props: {
|
||||
modelValue: { type: [String, Number, null], default: undefined },
|
||||
error: { type: String, default: '' },
|
||||
label: { type: String, default: '' },
|
||||
readonly: { type: Boolean, default: false },
|
||||
},
|
||||
setup(props) {
|
||||
return () => h('div', { 'data-testid': testid, 'data-error': props.error })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function mountBlock(errors?: Record<string, string>) {
|
||||
return mount(SupplierContactBlock, {
|
||||
props: {
|
||||
modelValue: emptyContact(),
|
||||
title: 'Contact 1',
|
||||
...(errors ? { errors } : {}),
|
||||
},
|
||||
global: {
|
||||
stubs: {
|
||||
MalioButtonIcon: true,
|
||||
MalioInputPhone: true,
|
||||
MalioInputText: errorProbe('contact-text'),
|
||||
MalioInputEmail: errorProbe('contact-email'),
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
describe('SupplierContactBlock — mapping erreur par champ (ERP-101)', () => {
|
||||
it('affiche l\'erreur serveur sur le champ email via la prop errors', () => {
|
||||
const wrapper = mountBlock({ email: 'Adresse e-mail invalide.' })
|
||||
expect(wrapper.find('[data-testid="contact-email"]').attributes('data-error')).toBe('Adresse e-mail invalide.')
|
||||
})
|
||||
|
||||
it('laisse les champs sans erreur quand errors est absent', () => {
|
||||
const wrapper = mountBlock()
|
||||
expect(wrapper.find('[data-testid="contact-email"]').attributes('data-error')).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
// `useApi` est un auto-import Nuxt : on le stubbe globalement pour intercepter
|
||||
// les appels de chargement des referentiels et controler les reponses Hydra.
|
||||
const mockGet = vi.hoisted(() => vi.fn())
|
||||
vi.stubGlobal('useApi', () => ({ get: mockGet }))
|
||||
|
||||
const { useSupplierReferentials } = await import('../useSupplierReferentials')
|
||||
|
||||
describe('useSupplierReferentials', () => {
|
||||
beforeEach(() => {
|
||||
mockGet.mockReset()
|
||||
mockGet.mockResolvedValue({ member: [] })
|
||||
})
|
||||
|
||||
it('charge les categories filtrees sur le type FOURNISSEUR (RG-2.10)', async () => {
|
||||
await useSupplierReferentials().loadCommon()
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
'/categories',
|
||||
expect.objectContaining({ pagination: 'false', typeCode: 'FOURNISSEUR' }),
|
||||
expect.objectContaining({ toast: false }),
|
||||
)
|
||||
})
|
||||
|
||||
it('mappe les categories en options { value: IRI, label: name, code }', async () => {
|
||||
mockGet.mockImplementation((url: string) => {
|
||||
if (url === '/categories') {
|
||||
return Promise.resolve({ member: [{ '@id': '/api/categories/9', code: 'NEGOCIANT', name: 'Négociant' }] })
|
||||
}
|
||||
return Promise.resolve({ member: [] })
|
||||
})
|
||||
|
||||
const refs = useSupplierReferentials()
|
||||
await refs.loadCommon()
|
||||
|
||||
expect(refs.categories.value).toEqual([{ value: '/api/categories/9', label: 'Négociant', code: 'NEGOCIANT' }])
|
||||
})
|
||||
|
||||
it('ne charge ni distributeurs ni courtiers (absents du modele fournisseur)', async () => {
|
||||
await useSupplierReferentials().loadCommon()
|
||||
|
||||
const urls = mockGet.mock.calls.map(c => c[0])
|
||||
expect(urls).not.toContain('/clients')
|
||||
expect(urls).toEqual(
|
||||
expect.arrayContaining(['/categories', '/sites', '/tva_modes', '/payment_delays', '/payment_types', '/banks']),
|
||||
)
|
||||
})
|
||||
|
||||
it('reste resilient : un referentiel en echec n\'empeche pas les autres', async () => {
|
||||
mockGet.mockImplementation((url: string) => {
|
||||
if (url === '/categories') return Promise.reject(new Error('403'))
|
||||
if (url === '/banks') return Promise.resolve({ member: [{ '@id': '/api/banks/1', code: 'SG', label: 'Société Générale' }] })
|
||||
return Promise.resolve({ member: [] })
|
||||
})
|
||||
|
||||
const refs = useSupplierReferentials()
|
||||
await refs.loadCommon()
|
||||
|
||||
expect(refs.categories.value).toEqual([])
|
||||
expect(refs.banks.value).toEqual([{ value: '/api/banks/1', label: 'Société Générale' }])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Composable d'erreurs partage des ecrans fournisseur (creation + edition, M2
|
||||
* Commercial). Miroir de `useClientFormErrors` (M1) :
|
||||
* - un `useFormErrors` par groupe scalaire (Principal / Information /
|
||||
* Comptabilite) : violations 422 affichees inline sous chaque champ ;
|
||||
* - un tableau d'erreurs PAR LIGNE pour chaque collection (contacts /
|
||||
* adresses / RIB), aligne sur l'index du `v-for`.
|
||||
*
|
||||
* `mapRowError` ne toaste PAS lui-meme : il retourne un booleen (true = mappe
|
||||
* inline). Chaque page conserve ainsi son propre fallback dans le `catch`.
|
||||
*/
|
||||
import { ref, type Ref } from 'vue'
|
||||
import { mapViolationsToRecord } from '~/shared/utils/api'
|
||||
|
||||
export function useSupplierFormErrors() {
|
||||
const mainErrors = useFormErrors()
|
||||
const informationErrors = useFormErrors()
|
||||
const accountingErrors = useFormErrors()
|
||||
const contactErrors = ref<Record<string, string>[]>([])
|
||||
const addressErrors = ref<Record<string, string>[]>([])
|
||||
const ribErrors = ref<Record<string, string>[]>([])
|
||||
|
||||
/**
|
||||
* Mappe l'erreur d'une ligne de collection sur le tableau cible (par index).
|
||||
* 422 avec violations exploitables → erreurs inline sous les champs de la
|
||||
* ligne + retourne true. Sinon → ne touche pas la cible et retourne false.
|
||||
*/
|
||||
function mapRowError(
|
||||
error: unknown,
|
||||
target: Ref<Record<string, string>[]>,
|
||||
index: number,
|
||||
): boolean {
|
||||
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
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Soumet TOUS les blocs d'une collection (contacts / adresses / RIB) en
|
||||
* collectant les erreurs par index : on n'arrete PAS au premier bloc en echec
|
||||
* (decision ERP-110 / ERP-101). Reinitialise le tableau d'erreurs cible, tente
|
||||
* chaque ligne via `saveRow`, mappe les 422 inline (mapRowError) ou delegue le
|
||||
* fallback a `onUnmappedError`. `shouldSkip` permet d'ignorer les blocs vides.
|
||||
* Retourne true si au moins un bloc a echoue.
|
||||
*/
|
||||
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) {
|
||||
if (!mapRowError(error, target, index)) {
|
||||
onUnmappedError(error, index)
|
||||
}
|
||||
hasError = true
|
||||
}
|
||||
}
|
||||
|
||||
return hasError
|
||||
}
|
||||
|
||||
return {
|
||||
mainErrors,
|
||||
informationErrors,
|
||||
accountingErrors,
|
||||
contactErrors,
|
||||
addressErrors,
|
||||
ribErrors,
|
||||
mapRowError,
|
||||
submitRows,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { ref } from 'vue'
|
||||
|
||||
/**
|
||||
* Charge les referentiels (listes courtes) alimentant les selects de l'ecran
|
||||
* « Ajouter un fournisseur » : categories (type FOURNISSEUR), sites, modes de TVA,
|
||||
* delais et types de reglement, banques. Miroir de `useClientReferentials` (M1).
|
||||
*
|
||||
* Toutes les collections sont recuperees en entier via l'echappatoire prevue
|
||||
* `?pagination=false` (referentiels de quelques dizaines d'entrees max), avec
|
||||
* l'en-tete `Accept: application/ld+json` impose par API Platform 4 pour obtenir
|
||||
* l'enveloppe Hydra (`member`). Les valeurs d'option sont les IRI Hydra (`@id`)
|
||||
* renvoyees telles quelles dans les payloads POST/PATCH (relations M:1 / M:N).
|
||||
*
|
||||
* Difference M2 : pas de distributeurs/courtiers (absents du modele fournisseur).
|
||||
*
|
||||
* Etat 100 % local a l'instance (refs) — aucune persistance URL.
|
||||
*/
|
||||
|
||||
/** Option generique au format attendu par MalioSelect / MalioSelectCheckbox. */
|
||||
export interface RefOption {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
/** Option de type de reglement enrichie de son code stable (RG-2.07 / RG-2.08). */
|
||||
export interface PaymentTypeOption extends RefOption {
|
||||
code: string
|
||||
}
|
||||
|
||||
/** Option de categorie enrichie de son code stable. */
|
||||
export interface CategoryOption extends RefOption {
|
||||
code: string
|
||||
}
|
||||
|
||||
interface HydraMember {
|
||||
'@id': string
|
||||
}
|
||||
|
||||
interface CategoryMember extends HydraMember {
|
||||
code: string
|
||||
name: string
|
||||
}
|
||||
|
||||
interface SiteMember extends HydraMember {
|
||||
name: string
|
||||
postalCode: string
|
||||
}
|
||||
|
||||
interface ReferentialMember extends HydraMember {
|
||||
code: string
|
||||
label: string
|
||||
}
|
||||
|
||||
const LD_JSON_HEADERS = { Accept: 'application/ld+json' }
|
||||
|
||||
export function useSupplierReferentials() {
|
||||
const api = useApi()
|
||||
|
||||
const categories = ref<CategoryOption[]>([])
|
||||
const sites = ref<RefOption[]>([])
|
||||
const tvaModes = ref<RefOption[]>([])
|
||||
const paymentDelays = ref<RefOption[]>([])
|
||||
const paymentTypes = ref<PaymentTypeOption[]>([])
|
||||
const banks = ref<RefOption[]>([])
|
||||
|
||||
/** Recupere une collection complete (pagination desactivee) en Hydra. */
|
||||
async function fetchAll<T extends HydraMember>(
|
||||
url: string,
|
||||
query: Record<string, string | string[]> = {},
|
||||
): Promise<T[]> {
|
||||
const res = await api.get<{ member?: T[] }>(
|
||||
url,
|
||||
{ pagination: 'false', ...query },
|
||||
{ headers: LD_JSON_HEADERS, toast: false },
|
||||
)
|
||||
return res.member ?? []
|
||||
}
|
||||
|
||||
/**
|
||||
* Charge en parallele les referentiels communs.
|
||||
*
|
||||
* Chargement RESILIENT (Promise.allSettled) : chaque referentiel est isole.
|
||||
* Necessaire pour les roles metier qui n'ont pas toutes les permissions de
|
||||
* lecture (ex. Compta a `commercial.suppliers.view` mais pas forcement
|
||||
* `catalog.categories.view` ni `sites.view`). Un referentiel en echec reste
|
||||
* simplement vide.
|
||||
*/
|
||||
async function loadCommon(): Promise<void> {
|
||||
await Promise.allSettled([
|
||||
// Taxonomie multi-types (ERP-84) : un fournisseur ne porte que des
|
||||
// categories de type FOURNISSEUR (RG-2.10) -> on filtre cote API.
|
||||
fetchAll<CategoryMember>('/categories', { typeCode: 'FOURNISSEUR' })
|
||||
.then((cats) => { categories.value = cats.map(c => ({ value: c['@id'], label: c.name, code: c.code })) }),
|
||||
fetchAll<SiteMember>('/sites')
|
||||
// Libelle = numero de departement (2 premiers chiffres du code
|
||||
// postal du site), ex: 86100 -> « 86 ».
|
||||
.then((sitesList) => { sites.value = sitesList.map(s => ({ value: s['@id'], label: (s.postalCode ?? '').slice(0, 2) })) }),
|
||||
fetchAll<ReferentialMember>('/tva_modes')
|
||||
.then((tva) => { tvaModes.value = tva.map(t => ({ value: t['@id'], label: t.label })) }),
|
||||
fetchAll<ReferentialMember>('/payment_delays')
|
||||
.then((delays) => { paymentDelays.value = delays.map(d => ({ value: d['@id'], label: d.label })) }),
|
||||
fetchAll<ReferentialMember>('/payment_types')
|
||||
.then((types) => { paymentTypes.value = types.map(t => ({ value: t['@id'], label: t.label, code: t.code })) }),
|
||||
fetchAll<ReferentialMember>('/banks')
|
||||
.then((banksList) => { banks.value = banksList.map(b => ({ value: b['@id'], label: b.label })) }),
|
||||
])
|
||||
}
|
||||
|
||||
return {
|
||||
categories,
|
||||
sites,
|
||||
tvaModes,
|
||||
paymentDelays,
|
||||
paymentTypes,
|
||||
banks,
|
||||
loadCommon,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,862 @@
|
||||
<template>
|
||||
<div>
|
||||
<!-- En-tete : retour vers le repertoire + titre. -->
|
||||
<div class="flex items-center gap-3 pt-11">
|
||||
<MalioButtonIcon
|
||||
icon="mdi:arrow-left-bold"
|
||||
icon-size="24"
|
||||
variant="ghost"
|
||||
v-bind="{ ariaLabel: t('commercial.suppliers.form.back') }"
|
||||
@click="goBack"
|
||||
/>
|
||||
<h1 class="text-[30px] font-semibold text-m-primary">{{ t('commercial.suppliers.form.title') }}</h1>
|
||||
</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 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"
|
||||
:label="t('commercial.suppliers.form.main.companyName')"
|
||||
:required="true"
|
||||
:readonly="mainLocked"
|
||||
:error="mainErrors.errors.companyName"
|
||||
/>
|
||||
<MalioSelectCheckbox
|
||||
:model-value="main.categoryIris"
|
||||
:options="referentials.categories.value"
|
||||
:label="t('commercial.suppliers.form.main.categories')"
|
||||
:display-tag="true"
|
||||
:readonly="mainLocked"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.categories"
|
||||
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="!mainLocked" class="mt-12 flex justify-center">
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('commercial.suppliers.form.submit')"
|
||||
:disabled="mainSubmitting"
|
||||
@click="submitMain"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- ── Onglets a validation incrementale ─────────────────────────────-->
|
||||
<MalioTabList v-model="activeTab" :tabs="tabs" 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)]">
|
||||
<MalioInputTextArea
|
||||
v-model="information.description"
|
||||
:label="t('commercial.suppliers.form.information.description')"
|
||||
resize="none"
|
||||
group-class="row-span-2 pt-1 pb-1"
|
||||
text-input="h-full text-lg"
|
||||
:readonly="isValidated('information')"
|
||||
:error="informationErrors.errors.description"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.competitors"
|
||||
:label="t('commercial.suppliers.form.information.competitors')"
|
||||
:readonly="isValidated('information')"
|
||||
:error="informationErrors.errors.competitors"
|
||||
/>
|
||||
<MalioDate
|
||||
v-model="information.foundedAt"
|
||||
:label="t('commercial.suppliers.form.information.foundedAt')"
|
||||
:readonly="isValidated('information')"
|
||||
:editable="true"
|
||||
:error="informationErrors.errors.foundedAt"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.employeesCount"
|
||||
:label="t('commercial.suppliers.form.information.employeesCount')"
|
||||
:mask="EMPLOYEES_MASK"
|
||||
:readonly="isValidated('information')"
|
||||
:error="informationErrors.errors.employeesCount"
|
||||
/>
|
||||
<MalioInputAmount
|
||||
v-model="information.revenueAmount"
|
||||
:label="t('commercial.suppliers.form.information.revenueAmount')"
|
||||
:readonly="isValidated('information')"
|
||||
:error="informationErrors.errors.revenueAmount"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.directorName"
|
||||
:label="t('commercial.suppliers.form.information.directorName')"
|
||||
:readonly="isValidated('information')"
|
||||
:error="informationErrors.errors.directorName"
|
||||
/>
|
||||
<MalioInputAmount
|
||||
v-model="information.profitAmount"
|
||||
:label="t('commercial.suppliers.form.information.profitAmount')"
|
||||
:readonly="isValidated('information')"
|
||||
:error="informationErrors.errors.profitAmount"
|
||||
/>
|
||||
<!-- Volume previsionnel : specifique fournisseur (entier >= 0). -->
|
||||
<MalioInputNumber
|
||||
:model-value="information.volumeForecast"
|
||||
:label="t('commercial.suppliers.form.information.volumeForecast')"
|
||||
:min="0"
|
||||
:readonly="isValidated('information')"
|
||||
:error="informationErrors.errors.volumeForecast"
|
||||
@update:model-value="(v: string) => information.volumeForecast = v"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="!isValidated('information')" class="mt-12 flex justify-center">
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('commercial.suppliers.form.submit')"
|
||||
:disabled="tabSubmitting || supplierId === null"
|
||||
@click="submitInformation"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Onglet Contacts -->
|
||||
<template #contacts>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
<SupplierContactBlock
|
||||
v-for="(contact, index) in contacts"
|
||||
:key="index"
|
||||
:model-value="contact"
|
||||
:title="t('commercial.suppliers.form.contact.title', { n: index + 1 })"
|
||||
:removable="index > 0"
|
||||
:readonly="isValidated('contacts')"
|
||||
:errors="contactErrors[index]"
|
||||
@update:model-value="(v) => contacts[index] = v"
|
||||
@remove="askRemoveContact(index)"
|
||||
/>
|
||||
<div v-if="!isValidated('contacts')" class="flex justify-center gap-6">
|
||||
<MalioButton
|
||||
variant="secondary"
|
||||
icon-name="mdi:add-bold"
|
||||
icon-position="left"
|
||||
:label="t('commercial.suppliers.form.contact.add')"
|
||||
:disabled="!canAddContact"
|
||||
@click="addContact"
|
||||
/>
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('commercial.suppliers.form.submit')"
|
||||
:disabled="tabSubmitting"
|
||||
@click="submitContacts"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Onglet Adresses -->
|
||||
<template #addresses>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
<SupplierAddressBlock
|
||||
v-for="(address, index) in addresses"
|
||||
:key="index"
|
||||
:model-value="address"
|
||||
:title="t('commercial.suppliers.form.address.title', { n: index + 1 })"
|
||||
:category-options="referentials.categories.value"
|
||||
:site-options="referentials.sites.value"
|
||||
:contact-options="contactOptions"
|
||||
:country-options="countryOptions"
|
||||
:removable="index > 0"
|
||||
:readonly="isValidated('addresses')"
|
||||
:errors="addressErrors[index]"
|
||||
@update:model-value="(v) => addresses[index] = v"
|
||||
@remove="askRemoveAddress(index)"
|
||||
@degraded="onAddressDegraded"
|
||||
/>
|
||||
<div v-if="!isValidated('addresses')" class="flex justify-center gap-6">
|
||||
<MalioButton
|
||||
variant="secondary"
|
||||
icon-name="mdi:add-bold"
|
||||
icon-position="left"
|
||||
:label="t('commercial.suppliers.form.address.add')"
|
||||
:disabled="!canAddAddress"
|
||||
@click="addAddress"
|
||||
/>
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('commercial.suppliers.form.submit')"
|
||||
:disabled="tabSubmitting"
|
||||
@click="submitAddresses"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 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
|
||||
v-model="accounting.siren"
|
||||
:label="t('commercial.suppliers.form.accounting.siren')"
|
||||
:mask="SIREN_MASK"
|
||||
:readonly="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.siren"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="accounting.accountNumber"
|
||||
:label="t('commercial.suppliers.form.accounting.accountNumber')"
|
||||
:readonly="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.accountNumber"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.tvaModeIri"
|
||||
:options="referentials.tvaModes.value"
|
||||
:label="t('commercial.suppliers.form.accounting.tvaMode')"
|
||||
:readonly="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"
|
||||
:label="t('commercial.suppliers.form.accounting.nTva')"
|
||||
:readonly="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.nTva"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.paymentDelayIri"
|
||||
:options="referentials.paymentDelays.value"
|
||||
:label="t('commercial.suppliers.form.accounting.paymentDelay')"
|
||||
:readonly="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.paymentDelay"
|
||||
@update:model-value="(v: string | number | null) => accounting.paymentDelayIri = v === null ? null : String(v)"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.paymentTypeIri"
|
||||
:options="referentials.paymentTypes.value"
|
||||
:label="t('commercial.suppliers.form.accounting.paymentType')"
|
||||
:readonly="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.paymentType"
|
||||
@update:model-value="onPaymentTypeChange"
|
||||
/>
|
||||
<MalioSelect
|
||||
v-if="isBankRequired"
|
||||
:model-value="accounting.bankIri"
|
||||
:options="referentials.banks.value"
|
||||
:label="t('commercial.suppliers.form.accounting.bank')"
|
||||
:readonly="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.bank"
|
||||
@update:model-value="(v: string | number | null) => accounting.bankIri = v === null ? null : String(v)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Blocs RIB — affiches uniquement si type de reglement = LCR (RG-2.08). -->
|
||||
<div
|
||||
v-for="(rib, index) in visibleRibs"
|
||||
:key="index"
|
||||
class="relative bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]"
|
||||
>
|
||||
<MalioButtonIcon
|
||||
v-if="!accountingReadonly"
|
||||
icon="mdi:delete-outline"
|
||||
variant="ghost"
|
||||
button-class="absolute top-3 right-3"
|
||||
v-bind="{ ariaLabel: t('commercial.suppliers.form.accounting.removeRib') }"
|
||||
@click="askRemoveRib(index)"
|
||||
/>
|
||||
<div class="grid grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText
|
||||
v-model="rib.label"
|
||||
:label="t('commercial.suppliers.form.accounting.ribLabel')"
|
||||
:readonly="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.label"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="rib.bic"
|
||||
:label="t('commercial.suppliers.form.accounting.ribBic')"
|
||||
:readonly="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.bic"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="rib.iban"
|
||||
:label="t('commercial.suppliers.form.accounting.ribIban')"
|
||||
:readonly="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.iban"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!accountingReadonly" class="flex justify-center gap-6">
|
||||
<MalioButton
|
||||
v-if="isRibRequired"
|
||||
variant="secondary"
|
||||
icon-name="mdi:add-bold"
|
||||
icon-position="left"
|
||||
:label="t('commercial.suppliers.form.accounting.addRib')"
|
||||
:disabled="!canAddRib"
|
||||
@click="addRib"
|
||||
/>
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('commercial.suppliers.form.submit')"
|
||||
:disabled="tabSubmitting"
|
||||
@click="submitAccounting"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Onglet placeholder : frame vide, passage automatique. -->
|
||||
<template #transport><ComingSoonPlaceholder /></template>
|
||||
</MalioTabList>
|
||||
|
||||
<!-- Modal de confirmation generique (suppression contact/adresse/RIB). -->
|
||||
<MalioModal v-model="confirmModal.open" modal-class="max-w-md">
|
||||
<template #header>
|
||||
<h2 class="text-[24px] font-bold">{{ t('commercial.suppliers.form.confirmDelete.title') }}</h2>
|
||||
</template>
|
||||
<p>{{ confirmModal.message }}</p>
|
||||
<template #footer>
|
||||
<MalioButton
|
||||
variant="secondary"
|
||||
button-class="flex-1"
|
||||
:label="t('commercial.suppliers.form.confirmDelete.cancel')"
|
||||
@click="confirmModal.open = false"
|
||||
/>
|
||||
<MalioButton
|
||||
variant="danger"
|
||||
button-class="flex-1"
|
||||
:label="t('commercial.suppliers.form.confirmDelete.confirm')"
|
||||
@click="runConfirm"
|
||||
/>
|
||||
</template>
|
||||
</MalioModal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { useSupplierReferentials, type RefOption } from '~/modules/commercial/composables/useSupplierReferentials'
|
||||
import { useSupplierFormErrors } from '~/modules/commercial/composables/useSupplierFormErrors'
|
||||
import {
|
||||
buildSupplierFormTabKeys,
|
||||
SUPPLIER_FORM_PLACEHOLDER_TABS,
|
||||
isAddressValid,
|
||||
isBankRequiredForPaymentType,
|
||||
isContactBlank,
|
||||
isContactNamed,
|
||||
isRibBlank,
|
||||
isRibComplete,
|
||||
isRibRequiredForPaymentType,
|
||||
lastFillableTabKey,
|
||||
} from '~/modules/commercial/utils/supplierFormRules'
|
||||
import {
|
||||
buildAccountingPayload,
|
||||
buildAddressPayload,
|
||||
buildContactPayload,
|
||||
buildInformationPayload,
|
||||
buildMainPayload,
|
||||
buildRibPayload,
|
||||
} from '~/modules/commercial/utils/supplierEdit'
|
||||
import {
|
||||
emptyAddress,
|
||||
emptyContact,
|
||||
emptyRib,
|
||||
type SupplierAddressFormDraft,
|
||||
type SupplierContactFormDraft,
|
||||
type SupplierRibFormDraft,
|
||||
} from '~/modules/commercial/types/supplierForm'
|
||||
import { extractApiErrorMessage } from '~/shared/utils/api'
|
||||
|
||||
// Masques de saisie (la normalisation finale reste serveur).
|
||||
const SIREN_MASK = '#########'
|
||||
const EMPLOYEES_MASK = '#######'
|
||||
|
||||
const { t } = useI18n()
|
||||
const api = useApi()
|
||||
const toast = useToast()
|
||||
const router = useRouter()
|
||||
const { can } = usePermissions()
|
||||
|
||||
/** Retour vers le repertoire fournisseurs (fleche d'en-tete). */
|
||||
function goBack(): void {
|
||||
router.push('/suppliers')
|
||||
}
|
||||
|
||||
/**
|
||||
* Message d'erreur a afficher dans un toast a partir d'une erreur d'API. Retourne
|
||||
* TOUJOURS une chaine (le composant de toast plante sur `undefined`).
|
||||
*/
|
||||
function apiErrorMessage(error: unknown): string {
|
||||
const data = (error as { data?: unknown })?.data
|
||||
return extractApiErrorMessage(data) || t('commercial.suppliers.toast.error')
|
||||
}
|
||||
|
||||
// ── Erreurs de validation par champ (ERP-101) ───────────────────────────────
|
||||
const {
|
||||
mainErrors,
|
||||
informationErrors,
|
||||
accountingErrors,
|
||||
contactErrors,
|
||||
addressErrors,
|
||||
ribErrors,
|
||||
submitRows,
|
||||
} = useSupplierFormErrors()
|
||||
|
||||
useHead({ title: t('commercial.suppliers.form.title') })
|
||||
|
||||
// Gating de la route : la creation est reservee a `manage`. Compta (accounting
|
||||
// seul) et Usine sont rediriges vers le repertoire.
|
||||
if (!can('commercial.suppliers.manage')) {
|
||||
await navigateTo('/suppliers')
|
||||
}
|
||||
|
||||
const canAccountingView = computed(() => can('commercial.suppliers.accounting.view'))
|
||||
const canAccountingManage = computed(() => can('commercial.suppliers.accounting.manage'))
|
||||
|
||||
const referentials = useSupplierReferentials()
|
||||
|
||||
// ── Etat du fournisseur cree ────────────────────────────────────────────────
|
||||
const supplierId = ref<number | null>(null)
|
||||
const mainLocked = ref(false)
|
||||
const mainSubmitting = ref(false)
|
||||
const tabSubmitting = ref(false)
|
||||
|
||||
// ── Formulaire principal ────────────────────────────────────────────────────
|
||||
const main = reactive({
|
||||
companyName: null as string | null,
|
||||
categoryIris: [] as string[],
|
||||
})
|
||||
|
||||
/** POST /suppliers (groupe supplier:write:main). Au succes : verrouille + bascule Information. */
|
||||
async function submitMain(): Promise<void> {
|
||||
if (mainSubmitting.value) return
|
||||
mainSubmitting.value = true
|
||||
mainErrors.clearErrors()
|
||||
try {
|
||||
const created = await api.post<SupplierResponse>('/suppliers', buildMainPayload(main), {
|
||||
headers: { Accept: 'application/ld+json' },
|
||||
toast: false,
|
||||
})
|
||||
|
||||
supplierId.value = created.id
|
||||
// Reaffiche la valeur normalisee renvoyee par le serveur (UPPERCASE, RG-2.12).
|
||||
main.companyName = created.companyName ?? main.companyName
|
||||
|
||||
mainLocked.value = true
|
||||
// Information est facultatif : on deverrouille jusqu'a Contacts (index 1).
|
||||
unlockedIndex.value = tabIndex('contacts')
|
||||
activeTab.value = 'information'
|
||||
toast.success({ title: t('commercial.suppliers.toast.createSuccess') })
|
||||
}
|
||||
catch (error) {
|
||||
// 409 = doublon nom de societe (RG d'unicite) → erreur inline + toast ;
|
||||
// 422 → mapping inline par champ ; autre → toast de fallback (ERP-101).
|
||||
const status = (error as { response?: { status?: number } })?.response?.status
|
||||
if (status === 409) {
|
||||
const message = t('commercial.suppliers.form.duplicateCompany')
|
||||
mainErrors.setError('companyName', message)
|
||||
toast.error({ title: t('commercial.suppliers.toast.error'), message })
|
||||
}
|
||||
else {
|
||||
mainErrors.handleApiError(error, { fallbackMessage: t('commercial.suppliers.toast.error') })
|
||||
}
|
||||
}
|
||||
finally {
|
||||
mainSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ── Onglets : ordre + gating progressif ─────────────────────────────────────
|
||||
const activeTab = ref('information')
|
||||
// Index du dernier onglet deverrouille (-1 tant que le fournisseur n'est pas cree).
|
||||
const unlockedIndex = ref(-1)
|
||||
// Onglets valides (passent en lecture seule).
|
||||
const validated = reactive<Record<string, boolean>>({})
|
||||
|
||||
const tabKeys = computed(() => buildSupplierFormTabKeys(canAccountingView.value))
|
||||
|
||||
// Dernier onglet REMPLISSABLE par le role : sa validation cloture l'ajout.
|
||||
const lastFillableTab = computed(() => lastFillableTabKey(tabKeys.value))
|
||||
|
||||
// Icone (Iconify) affichee dans l'onglet, par cle.
|
||||
const TAB_ICONS: Record<string, string> = {
|
||||
information: 'mdi:account-outline',
|
||||
contacts: 'mdi:account-box-plus-outline',
|
||||
addresses: 'mdi:map-marker-outline',
|
||||
transport: 'mdi:truck-delivery-outline',
|
||||
accounting: 'mdi:bank-circle-outline',
|
||||
}
|
||||
|
||||
const tabs = computed(() => tabKeys.value.map((key, index) => ({
|
||||
key,
|
||||
label: t(`commercial.suppliers.tab.${key}`),
|
||||
icon: TAB_ICONS[key],
|
||||
disabled: index > unlockedIndex.value,
|
||||
})))
|
||||
|
||||
function isValidated(key: string): boolean {
|
||||
return validated[key] === true
|
||||
}
|
||||
|
||||
function tabIndex(key: string): number {
|
||||
return tabKeys.value.indexOf(key)
|
||||
}
|
||||
|
||||
/**
|
||||
* Marque l'onglet valide. Si c'est le dernier onglet remplissable, l'ajout est
|
||||
* termine : toast final + redirection vers la liste, et on retourne true. Sinon,
|
||||
* deverrouille et avance a l'onglet suivant, et retourne false.
|
||||
*/
|
||||
function completeTab(key: string): boolean {
|
||||
validated[key] = true
|
||||
if (key === lastFillableTab.value) {
|
||||
toast.success({ title: t('commercial.suppliers.toast.addComplete') })
|
||||
router.push('/suppliers')
|
||||
return true
|
||||
}
|
||||
const next = tabKeys.value[tabIndex(key) + 1]
|
||||
unlockedIndex.value = Math.max(unlockedIndex.value, tabIndex(key) + 1)
|
||||
if (next) activeTab.value = next
|
||||
return false
|
||||
}
|
||||
|
||||
// Passage automatique sur les onglets coquille (Transport).
|
||||
watch(activeTab, (key) => {
|
||||
if ((SUPPLIER_FORM_PLACEHOLDER_TABS as readonly string[]).includes(key)) {
|
||||
const next = tabKeys.value[tabIndex(key) + 1]
|
||||
unlockedIndex.value = Math.max(unlockedIndex.value, tabIndex(key) + 1)
|
||||
if (next) activeTab.value = next
|
||||
}
|
||||
})
|
||||
|
||||
// ── Onglet Information ──────────────────────────────────────────────────────
|
||||
const information = reactive({
|
||||
description: null as string | null,
|
||||
competitors: null as string | null,
|
||||
foundedAt: null as string | null,
|
||||
employeesCount: null as string | null,
|
||||
revenueAmount: null as string | null,
|
||||
profitAmount: null as string | null,
|
||||
directorName: null as string | null,
|
||||
volumeForecast: null as string | null,
|
||||
})
|
||||
|
||||
/** PATCH /suppliers/{id} — mode strict : uniquement les champs du groupe information. */
|
||||
async function submitInformation(): Promise<void> {
|
||||
if (supplierId.value === null || tabSubmitting.value) return
|
||||
tabSubmitting.value = true
|
||||
informationErrors.clearErrors()
|
||||
try {
|
||||
await api.patch(`/suppliers/${supplierId.value}`, buildInformationPayload(information), { toast: false })
|
||||
if (completeTab('information')) return
|
||||
toast.success({ title: t('commercial.suppliers.toast.updateSuccess') })
|
||||
}
|
||||
catch (error) {
|
||||
informationErrors.handleApiError(error, { fallbackMessage: t('commercial.suppliers.toast.error') })
|
||||
}
|
||||
finally {
|
||||
tabSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ── Onglet Contacts ─────────────────────────────────────────────────────────
|
||||
const contacts = ref<SupplierContactFormDraft[]>([emptyContact()])
|
||||
|
||||
// « + Nouveau contact » desactive tant que le dernier bloc n'a ni nom ni prenom.
|
||||
const canAddContact = computed(() => {
|
||||
const last = contacts.value[contacts.value.length - 1]
|
||||
return last !== undefined && isContactNamed(last)
|
||||
})
|
||||
|
||||
function addContact(): void {
|
||||
if (canAddContact.value) contacts.value.push(emptyContact())
|
||||
}
|
||||
|
||||
function askRemoveContact(index: number): void {
|
||||
askConfirm(t('commercial.suppliers.form.confirmDelete.contact'), () => {
|
||||
contacts.value.splice(index, 1)
|
||||
contactErrors.value.splice(index, 1)
|
||||
})
|
||||
}
|
||||
|
||||
/** POST/PATCH des contacts sur la sous-ressource /suppliers/{id}/contacts. */
|
||||
async function submitContacts(): Promise<void> {
|
||||
if (supplierId.value === null || tabSubmitting.value) return
|
||||
tabSubmitting.value = true
|
||||
try {
|
||||
// RG-2.13 : au moins un contact requis. Si l'onglet ne contient QUE des
|
||||
// amorces vides, on les soumet pour declencher la 422 RG-2.04 inline.
|
||||
const hasSubmittableContact = contacts.value.some(c => c.id !== null || !isContactBlank(c))
|
||||
const hasError = await submitRows(
|
||||
contacts.value,
|
||||
contactErrors,
|
||||
async (contact) => {
|
||||
const body = buildContactPayload(contact)
|
||||
if (contact.id === null) {
|
||||
const created = await api.post<ContactResponse>(
|
||||
`/suppliers/${supplierId.value}/contacts`,
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
contact.id = created.id
|
||||
contact.iri = created['@id'] ?? null
|
||||
}
|
||||
else {
|
||||
await api.patch(`/supplier_contacts/${contact.id}`, body, { toast: false })
|
||||
}
|
||||
},
|
||||
error => toast.error({ title: t('commercial.suppliers.toast.error'), message: apiErrorMessage(error) }),
|
||||
contact => hasSubmittableContact && contact.id === null && isContactBlank(contact),
|
||||
)
|
||||
if (hasError) return
|
||||
if (completeTab('contacts')) return
|
||||
toast.success({ title: t('commercial.suppliers.toast.updateSuccess') })
|
||||
}
|
||||
finally {
|
||||
tabSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ── Onglet Adresses ─────────────────────────────────────────────────────────
|
||||
const addresses = ref<SupplierAddressFormDraft[]>([emptyAddress()])
|
||||
const addressDegradedNotified = ref(false)
|
||||
|
||||
// Contacts deja crees, rattachables a une adresse (M2M, via leur IRI).
|
||||
const contactOptions = computed<RefOption[]>(() =>
|
||||
contacts.value
|
||||
.filter(c => c.iri !== null)
|
||||
.map(c => ({
|
||||
value: c.iri as string,
|
||||
label: [c.firstName, c.lastName].filter(Boolean).join(' ') || (c.email ?? ''),
|
||||
})),
|
||||
)
|
||||
|
||||
// Pays disponibles (France preselectionnee par defaut sur chaque adresse).
|
||||
const countryOptions: RefOption[] = [
|
||||
{ value: 'France', label: 'France' },
|
||||
{ value: 'Espagne', label: 'Espagne' },
|
||||
]
|
||||
|
||||
// « + Adresse » desactive tant que la derniere adresse n'est pas valide.
|
||||
const canAddAddress = computed(() => {
|
||||
const last = addresses.value[addresses.value.length - 1]
|
||||
return last !== undefined && isAddressValid(last)
|
||||
})
|
||||
|
||||
function addAddress(): void {
|
||||
if (canAddAddress.value) addresses.value.push(emptyAddress())
|
||||
}
|
||||
|
||||
function askRemoveAddress(index: number): void {
|
||||
askConfirm(t('commercial.suppliers.form.confirmDelete.address'), () => {
|
||||
addresses.value.splice(index, 1)
|
||||
addressErrors.value.splice(index, 1)
|
||||
})
|
||||
}
|
||||
|
||||
/** Avertit une seule fois quand l'autocompletion d'adresse bascule en degrade. */
|
||||
function onAddressDegraded(): void {
|
||||
if (addressDegradedNotified.value) return
|
||||
addressDegradedNotified.value = true
|
||||
toast.warning({
|
||||
title: t('commercial.suppliers.toast.error'),
|
||||
message: t('commercial.suppliers.form.address.degraded'),
|
||||
})
|
||||
}
|
||||
|
||||
/** POST/PATCH des adresses sur la sous-ressource /suppliers/{id}/addresses. */
|
||||
async function submitAddresses(): Promise<void> {
|
||||
if (supplierId.value === null || tabSubmitting.value) return
|
||||
tabSubmitting.value = true
|
||||
try {
|
||||
const hasError = await submitRows(
|
||||
addresses.value,
|
||||
addressErrors,
|
||||
async (address) => {
|
||||
const body = buildAddressPayload(address)
|
||||
if (address.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/suppliers/${supplierId.value}/addresses`,
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
address.id = created.id
|
||||
}
|
||||
else {
|
||||
await api.patch(`/supplier_addresses/${address.id}`, body, { toast: false })
|
||||
}
|
||||
},
|
||||
error => toast.error({ title: t('commercial.suppliers.toast.error'), message: apiErrorMessage(error) }),
|
||||
)
|
||||
if (hasError) return
|
||||
if (completeTab('addresses')) return
|
||||
toast.success({ title: t('commercial.suppliers.toast.updateSuccess') })
|
||||
}
|
||||
finally {
|
||||
tabSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ── Onglet Comptabilite ─────────────────────────────────────────────────────
|
||||
const accounting = reactive({
|
||||
siren: null as string | null,
|
||||
accountNumber: null as string | null,
|
||||
tvaModeIri: null as string | null,
|
||||
nTva: null as string | null,
|
||||
paymentDelayIri: null as string | null,
|
||||
paymentTypeIri: null as string | null,
|
||||
bankIri: null as string | null,
|
||||
})
|
||||
const ribs = ref<SupplierRibFormDraft[]>([])
|
||||
|
||||
// L'onglet est editable seulement avec accounting.manage (sinon lecture seule).
|
||||
const accountingReadonly = computed(() => isValidated('accounting') || !canAccountingManage.value)
|
||||
|
||||
// Code du type de reglement selectionne (pour RG-2.07 / RG-2.08).
|
||||
const selectedPaymentTypeCode = computed(() =>
|
||||
referentials.paymentTypes.value.find(p => p.value === accounting.paymentTypeIri)?.code ?? null,
|
||||
)
|
||||
const isBankRequired = computed(() => isBankRequiredForPaymentType(selectedPaymentTypeCode.value))
|
||||
const isRibRequired = computed(() => isRibRequiredForPaymentType(selectedPaymentTypeCode.value))
|
||||
|
||||
// Les blocs RIB ne sont affiches que pour une LCR (RG-2.08).
|
||||
const visibleRibs = computed(() => isRibRequired.value ? ribs.value : [])
|
||||
|
||||
function onPaymentTypeChange(value: string | number | null): void {
|
||||
accounting.paymentTypeIri = value === null ? null : String(value)
|
||||
// La banque n'a de sens que pour un virement : on la vide sinon (RG-2.07).
|
||||
if (!isBankRequired.value) accounting.bankIri = null
|
||||
// Les RIB n'ont de sens que pour une LCR (RG-2.08) : amorce un bloc vide quand
|
||||
// LCR est choisi, vide la liste sinon (pas de RIB fantome soumis).
|
||||
if (isRibRequired.value) {
|
||||
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||
}
|
||||
else {
|
||||
ribs.value = []
|
||||
ribErrors.value = []
|
||||
}
|
||||
}
|
||||
|
||||
// « + RIB » desactive tant que le dernier bloc RIB n'est pas complet.
|
||||
const canAddRib = computed(() => {
|
||||
const last = ribs.value[ribs.value.length - 1]
|
||||
return last !== undefined && isRibComplete(last)
|
||||
})
|
||||
|
||||
function addRib(): void {
|
||||
if (canAddRib.value) ribs.value.push(emptyRib())
|
||||
}
|
||||
|
||||
function askRemoveRib(index: number): void {
|
||||
askConfirm(t('commercial.suppliers.form.confirmDelete.rib'), () => {
|
||||
ribs.value.splice(index, 1)
|
||||
ribErrors.value.splice(index, 1)
|
||||
// Garde au moins un bloc RIB visible.
|
||||
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Valide l'onglet Comptabilite : POST/PATCH des RIB sur /suppliers/{id}/ribs PUIS
|
||||
* PATCH des scalaires (groupe supplier:write:accounting). Les RIB d'abord : le back
|
||||
* valide RG-2.08 (LCR => au moins un RIB persiste) sur le PATCH scalaires, les RIB
|
||||
* doivent donc exister en base AVANT. Deux appels distincts (mode strict).
|
||||
*/
|
||||
async function submitAccounting(): Promise<void> {
|
||||
if (supplierId.value === null || tabSubmitting.value) return
|
||||
tabSubmitting.value = true
|
||||
accountingErrors.clearErrors()
|
||||
try {
|
||||
// 1) POST/PATCH des RIB d'abord (erreurs inline par ligne). Seuls les blocs
|
||||
// RIB TOTALEMENT vides (amorce neuve) sont ignores.
|
||||
const ribHasError = await submitRows(
|
||||
ribs.value,
|
||||
ribErrors,
|
||||
async (rib) => {
|
||||
const body = buildRibPayload(rib)
|
||||
if (rib.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/suppliers/${supplierId.value}/ribs`,
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
rib.id = created.id
|
||||
}
|
||||
else {
|
||||
await api.patch(`/supplier_ribs/${rib.id}`, body, { toast: false })
|
||||
}
|
||||
},
|
||||
error => toast.error({ title: t('commercial.suppliers.toast.error'), message: apiErrorMessage(error) }),
|
||||
rib => rib.id === null && isRibBlank(rib),
|
||||
)
|
||||
if (ribHasError) return
|
||||
|
||||
// 2) PATCH des scalaires comptables (erreurs inline sur leurs champs).
|
||||
try {
|
||||
await api.patch(
|
||||
`/suppliers/${supplierId.value}`,
|
||||
buildAccountingPayload(accounting, isBankRequired.value),
|
||||
{ toast: false },
|
||||
)
|
||||
}
|
||||
catch (error) {
|
||||
accountingErrors.handleApiError(error, { fallbackMessage: t('commercial.suppliers.toast.error') })
|
||||
return
|
||||
}
|
||||
|
||||
if (completeTab('accounting')) return
|
||||
toast.success({ title: t('commercial.suppliers.toast.updateSuccess') })
|
||||
}
|
||||
finally {
|
||||
tabSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ── Modal de confirmation generique ─────────────────────────────────────────
|
||||
const confirmModal = reactive({
|
||||
open: false,
|
||||
message: '',
|
||||
action: null as null | (() => void),
|
||||
})
|
||||
|
||||
function askConfirm(message: string, action: () => void): void {
|
||||
confirmModal.message = message
|
||||
confirmModal.action = action
|
||||
confirmModal.open = true
|
||||
}
|
||||
|
||||
function runConfirm(): void {
|
||||
confirmModal.action?.()
|
||||
confirmModal.action = null
|
||||
confirmModal.open = false
|
||||
}
|
||||
|
||||
// ── Types de reponse API ────────────────────────────────────────────────────
|
||||
interface SupplierResponse {
|
||||
id: number
|
||||
companyName: string | null
|
||||
}
|
||||
|
||||
interface ContactResponse {
|
||||
'@id'?: string
|
||||
id: number
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
// Echec du chargement des referentiels non bloquant : les selects restent vides.
|
||||
referentials.loadCommon().catch(() => {})
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Types « brouillon » de l'ecran « Ajouter un fournisseur » (M2 Commercial).
|
||||
*
|
||||
* Miroir de `types/clientForm.ts` (M1). Ces interfaces decrivent l'etat LOCAL du
|
||||
* formulaire (refs Vue), distinct des DTO de l'API : elles portent en plus des
|
||||
* champs purement UI (`hasSecondaryPhone`) et l'`iri` Hydra des entites creees
|
||||
* (necessaire pour rattacher une adresse a des contacts deja persistes, M2M).
|
||||
* Partage par la page de creation et les blocs `SupplierContactBlock` /
|
||||
* `SupplierAddressBlock` (reutilises par la consultation/modification 95/96).
|
||||
*
|
||||
* Differences M2 vs M1 (cf. spec-front § « Differences notables ») :
|
||||
* - Adresse : type via enum exclusif `addressType` (PROSPECT/DEPART/RENDU,
|
||||
* RG-2.09) — pas de drapeaux isProspect/isDelivery/isBilling.
|
||||
* - Adresse : champs specifiques fournisseur `bennes` (nombre) et
|
||||
* `triageProvider` (prestation de triage). Pas d'email de facturation.
|
||||
* - Pas de relation Distributeur/Courtier ni de triage sur le bloc principal.
|
||||
*/
|
||||
|
||||
/** Type d'adresse fournisseur (enum exclusif RG-2.09). */
|
||||
export type SupplierAddressType = 'PROSPECT' | 'DEPART' | 'RENDU'
|
||||
|
||||
/** Un contact du fournisseur (onglet Contacts). */
|
||||
export interface SupplierContactFormDraft {
|
||||
/** Id serveur une fois le contact cree (null tant que non persiste). */
|
||||
id: number | null
|
||||
/** IRI Hydra du contact cree — utilise pour le rattachement M2M cote adresse. */
|
||||
iri: string | null
|
||||
firstName: string | null
|
||||
lastName: string | null
|
||||
jobTitle: string | null
|
||||
phonePrimary: string | null
|
||||
phoneSecondary: string | null
|
||||
email: string | null
|
||||
/** UI : le 2e numero a ete revele via le bouton « + ». */
|
||||
hasSecondaryPhone: boolean
|
||||
}
|
||||
|
||||
/** Une adresse du fournisseur (onglet Adresses). */
|
||||
export interface SupplierAddressFormDraft {
|
||||
id: number | null
|
||||
/** Type exclusif Prospect / Depart / Rendu (RG-2.09). null tant que non choisi. */
|
||||
addressType: SupplierAddressType | null
|
||||
country: string
|
||||
postalCode: string | null
|
||||
city: string | null
|
||||
street: string | null
|
||||
streetComplement: string | null
|
||||
/** IRI des categories rattachees (type FOURNISSEUR, RG-2.10). */
|
||||
categoryIris: string[]
|
||||
/** IRI des sites Starseed rattaches (>= 1 obligatoire — RG-2.06). */
|
||||
siteIris: string[]
|
||||
/** IRI des contacts rattaches (= blocs Contact deja crees). */
|
||||
contactIris: string[]
|
||||
/** Nombre de bennes (stepper, defaut 0). Chaine pour MalioInputNumber, convertie au payload. */
|
||||
bennes: string | null
|
||||
/** Prestation de triage (specifique fournisseur, portee par l'adresse — RG). */
|
||||
triageProvider: boolean
|
||||
}
|
||||
|
||||
/** Un RIB du fournisseur (onglet Comptabilite). */
|
||||
export interface SupplierRibFormDraft {
|
||||
id: number | null
|
||||
label: string | null
|
||||
bic: string | null
|
||||
iban: string | null
|
||||
}
|
||||
|
||||
/** Fabrique un contact vierge. */
|
||||
export function emptyContact(): SupplierContactFormDraft {
|
||||
return {
|
||||
id: null,
|
||||
iri: null,
|
||||
firstName: null,
|
||||
lastName: null,
|
||||
jobTitle: null,
|
||||
phonePrimary: null,
|
||||
phoneSecondary: null,
|
||||
email: null,
|
||||
hasSecondaryPhone: false,
|
||||
}
|
||||
}
|
||||
|
||||
/** Fabrique une adresse vierge (pays prerempli « France », 0 benne). */
|
||||
export function emptyAddress(): SupplierAddressFormDraft {
|
||||
return {
|
||||
id: null,
|
||||
addressType: null,
|
||||
country: 'France',
|
||||
postalCode: null,
|
||||
city: null,
|
||||
street: null,
|
||||
streetComplement: null,
|
||||
categoryIris: [],
|
||||
siteIris: [],
|
||||
contactIris: [],
|
||||
bennes: '0',
|
||||
triageProvider: false,
|
||||
}
|
||||
}
|
||||
|
||||
/** Fabrique un RIB vierge. */
|
||||
export function emptyRib(): SupplierRibFormDraft {
|
||||
return {
|
||||
id: null,
|
||||
label: null,
|
||||
bic: null,
|
||||
iban: null,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
buildAccountingPayload,
|
||||
buildAddressPayload,
|
||||
buildContactPayload,
|
||||
buildInformationPayload,
|
||||
buildMainPayload,
|
||||
buildRibPayload,
|
||||
} from '../supplierEdit'
|
||||
import { emptyAddress, emptyContact, emptyRib } from '~/modules/commercial/types/supplierForm'
|
||||
|
||||
describe('buildMainPayload (groupe supplier:write:main)', () => {
|
||||
it('envoie companyName + categories quand renseignes', () => {
|
||||
expect(buildMainPayload({ companyName: 'ACME', categoryIris: ['/api/categories/1'] })).toEqual({
|
||||
companyName: 'ACME',
|
||||
categories: ['/api/categories/1'],
|
||||
})
|
||||
})
|
||||
|
||||
it('omet companyName vide (-> 422 NotBlank, ERP-119)', () => {
|
||||
const payload = buildMainPayload({ companyName: null, categoryIris: [] })
|
||||
expect('companyName' in payload).toBe(false)
|
||||
expect(payload.categories).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildInformationPayload (groupe supplier:write:information)', () => {
|
||||
const base = {
|
||||
description: null, competitors: null, foundedAt: null, employeesCount: null,
|
||||
revenueAmount: null, profitAmount: null, directorName: null, volumeForecast: null,
|
||||
}
|
||||
|
||||
it('convertit employeesCount et volumeForecast en nombre, null si vide', () => {
|
||||
expect(buildInformationPayload({ ...base, employeesCount: '42', volumeForecast: '1000' })).toMatchObject({
|
||||
employeesCount: 42,
|
||||
volumeForecast: 1000,
|
||||
})
|
||||
expect(buildInformationPayload(base)).toMatchObject({ employeesCount: null, volumeForecast: null })
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildContactPayload (sous-ressource supplier_contact)', () => {
|
||||
it('n\'envoie le 2e telephone que si revele (hasSecondaryPhone)', () => {
|
||||
const contact = { ...emptyContact(), phonePrimary: '0102030405', phoneSecondary: '0607080910' }
|
||||
expect(buildContactPayload({ ...contact, hasSecondaryPhone: false }).phoneSecondary).toBeNull()
|
||||
expect(buildContactPayload({ ...contact, hasSecondaryPhone: true }).phoneSecondary).toBe('0607080910')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildAddressPayload (sous-ressource supplier_address — specificites M2)', () => {
|
||||
it('envoie addressType (enum), bennes (nombre) et triageProvider', () => {
|
||||
const address = {
|
||||
...emptyAddress(),
|
||||
addressType: 'RENDU' as const,
|
||||
postalCode: '86100', city: 'Châtellerault', street: '1 rue de la Paix',
|
||||
siteIris: ['/api/sites/1'], categoryIris: ['/api/categories/2'],
|
||||
bennes: '3', triageProvider: true,
|
||||
}
|
||||
expect(buildAddressPayload(address)).toMatchObject({
|
||||
addressType: 'RENDU',
|
||||
bennes: 3,
|
||||
triageProvider: true,
|
||||
sites: ['/api/sites/1'],
|
||||
categories: ['/api/categories/2'],
|
||||
})
|
||||
})
|
||||
|
||||
it('bennes null quand le champ est vide', () => {
|
||||
expect(buildAddressPayload({ ...emptyAddress(), bennes: '' }).bennes).toBeNull()
|
||||
})
|
||||
|
||||
it('omet postalCode / city / street vides (-> 422 NotBlank, ERP-119)', () => {
|
||||
const payload = buildAddressPayload({ ...emptyAddress(), addressType: 'PROSPECT' })
|
||||
expect('postalCode' in payload).toBe(false)
|
||||
expect('city' in payload).toBe(false)
|
||||
expect('street' in payload).toBe(false)
|
||||
// Les champs non requis restent presents.
|
||||
expect('streetComplement' in payload).toBe(true)
|
||||
expect(payload.addressType).toBe('PROSPECT')
|
||||
})
|
||||
|
||||
it('n\'expose jamais d\'email de facturation (difference M1)', () => {
|
||||
const payload = buildAddressPayload({ ...emptyAddress(), addressType: 'DEPART' })
|
||||
expect('billingEmail' in payload).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildAccountingPayload (groupe supplier:write:accounting)', () => {
|
||||
const base = {
|
||||
siren: '123456789', accountNumber: '00012345678', nTva: 'FR123',
|
||||
tvaModeIri: '/api/tva_modes/1', paymentDelayIri: '/api/payment_delays/1',
|
||||
paymentTypeIri: '/api/payment_types/1', bankIri: '/api/banks/1',
|
||||
}
|
||||
|
||||
it('envoie la banque seulement si requise (VIREMENT, RG-2.07)', () => {
|
||||
expect(buildAccountingPayload(base, true).bank).toBe('/api/banks/1')
|
||||
expect(buildAccountingPayload(base, false).bank).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildRibPayload (sous-ressource supplier_rib)', () => {
|
||||
it('omet les champs requis vides (-> 422 NotBlank, ERP-119)', () => {
|
||||
const payload = buildRibPayload({ ...emptyRib(), iban: 'FR1420041010050500013M02606' })
|
||||
expect('label' in payload).toBe(false)
|
||||
expect('bic' in payload).toBe(false)
|
||||
expect(payload.iban).toBe('FR1420041010050500013M02606')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,190 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
buildSupplierFormTabKeys,
|
||||
hasAtLeastOneValidContact,
|
||||
isAddressValid,
|
||||
isBankRequiredForPaymentType,
|
||||
isBlankRow,
|
||||
isContactBlank,
|
||||
isContactNamed,
|
||||
isRibBlank,
|
||||
isRibComplete,
|
||||
isRibRequiredForPaymentType,
|
||||
lastFillableTabKey,
|
||||
omitEmptyRequired,
|
||||
type AddressValidityDraft,
|
||||
type ContactDraft,
|
||||
type ContactFillableDraft,
|
||||
} from '../supplierFormRules'
|
||||
|
||||
/** Bloc contact totalement vide (amorce par defaut). */
|
||||
function blankContact(): ContactFillableDraft {
|
||||
return {
|
||||
firstName: null,
|
||||
lastName: null,
|
||||
jobTitle: null,
|
||||
phonePrimary: null,
|
||||
phoneSecondary: null,
|
||||
email: null,
|
||||
}
|
||||
}
|
||||
|
||||
describe('buildSupplierFormTabKeys (gating onglet Comptabilite + onglets edit-only)', () => {
|
||||
it('inclut l onglet accounting si l utilisateur a accounting.view', () => {
|
||||
expect(buildSupplierFormTabKeys(true)).toContain('accounting')
|
||||
})
|
||||
|
||||
it('exclut l onglet accounting sinon (Bureau / Commerciale)', () => {
|
||||
expect(buildSupplierFormTabKeys(false)).not.toContain('accounting')
|
||||
})
|
||||
|
||||
it('a la creation, ordre = information / contacts / addresses / transport (+ accounting si vu)', () => {
|
||||
expect(buildSupplierFormTabKeys(true)).toEqual(['information', 'contacts', 'addresses', 'transport', 'accounting'])
|
||||
expect(buildSupplierFormTabKeys(false)).toEqual(['information', 'contacts', 'addresses', 'transport'])
|
||||
})
|
||||
|
||||
it('a la creation, exclut Statistiques / Rapports / Echanges', () => {
|
||||
const keys = buildSupplierFormTabKeys(true)
|
||||
expect(keys).not.toContain('statistics')
|
||||
expect(keys).not.toContain('reports')
|
||||
expect(keys).not.toContain('exchanges')
|
||||
})
|
||||
|
||||
it('en modification (includeEditOnlyTabs), ajoute les onglets edit-only en fin', () => {
|
||||
expect(buildSupplierFormTabKeys(true, { includeEditOnlyTabs: true })).toEqual([
|
||||
'information', 'contacts', 'addresses', 'transport', 'accounting', 'statistics', 'reports', 'exchanges',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('lastFillableTabKey (redirection fin d\'ajout, role-aware)', () => {
|
||||
it('addresses pour un role sans Comptabilite (Bureau / Commerciale)', () => {
|
||||
expect(lastFillableTabKey(buildSupplierFormTabKeys(false))).toBe('addresses')
|
||||
})
|
||||
|
||||
it('accounting pour un role avec accounting.view (Admin)', () => {
|
||||
expect(lastFillableTabKey(buildSupplierFormTabKeys(true))).toBe('accounting')
|
||||
})
|
||||
|
||||
it('ignore les onglets placeholder (Transport en dernier ne compte pas)', () => {
|
||||
expect(lastFillableTabKey(['information', 'contacts', 'addresses', 'transport'])).toBe('addresses')
|
||||
})
|
||||
|
||||
it('undefined si aucun onglet remplissable (que des placeholders)', () => {
|
||||
expect(lastFillableTabKey(['transport', 'statistics'])).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('isContactNamed (RG-2.04)', () => {
|
||||
it('vrai si le prenom ou le nom est renseigne', () => {
|
||||
expect(isContactNamed({ firstName: 'Alice', lastName: null })).toBe(true)
|
||||
expect(isContactNamed({ firstName: null, lastName: 'Martin' })).toBe(true)
|
||||
})
|
||||
|
||||
it('faux si les deux sont vides ou espaces uniquement', () => {
|
||||
expect(isContactNamed({ firstName: null, lastName: null })).toBe(false)
|
||||
expect(isContactNamed({ firstName: ' ', lastName: '' })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasAtLeastOneValidContact (RG-2.13)', () => {
|
||||
it('faux sur une liste vide ou sans contact nomme', () => {
|
||||
expect(hasAtLeastOneValidContact([])).toBe(false)
|
||||
const contacts: ContactDraft[] = [{ firstName: null, lastName: null }, { firstName: '', lastName: ' ' }]
|
||||
expect(hasAtLeastOneValidContact(contacts)).toBe(false)
|
||||
})
|
||||
|
||||
it('vrai des qu un contact a un nom ou un prenom', () => {
|
||||
expect(hasAtLeastOneValidContact([{ firstName: null, lastName: null }, { firstName: 'Bob', lastName: null }])).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isBlankRow / isContactBlank / isRibBlank (blocs vides vs partiels)', () => {
|
||||
it('isBlankRow vrai si toutes les valeurs sont vides', () => {
|
||||
expect(isBlankRow([null, undefined, '', ' '])).toBe(true)
|
||||
expect(isBlankRow([null, 'x', ''])).toBe(false)
|
||||
})
|
||||
|
||||
it('isContactBlank faux si un email seul est saisi (bloc a soumettre -> 422 RG-2.04 inline)', () => {
|
||||
expect(isContactBlank(blankContact())).toBe(true)
|
||||
expect(isContactBlank({ ...blankContact(), email: 'jean@acme.fr' })).toBe(false)
|
||||
})
|
||||
|
||||
it('isRibBlank faux si un IBAN seul est saisi (bloc a soumettre -> 422 NotBlank inline)', () => {
|
||||
expect(isRibBlank({ label: null, bic: null, iban: null })).toBe(true)
|
||||
expect(isRibBlank({ label: null, bic: null, iban: 'FR1420041010050500013M02606' })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isRibComplete (gating « + RIB » + RG-2.08)', () => {
|
||||
it('vrai quand label + BIC + IBAN sont remplis', () => {
|
||||
expect(isRibComplete({ label: 'Compte courant', bic: 'BNPAFRPP', iban: 'FR1420041010050500013M02606' })).toBe(true)
|
||||
})
|
||||
|
||||
it('faux si un champ manque', () => {
|
||||
expect(isRibComplete({ label: null, bic: 'BNPAFRPP', iban: 'FR14...' })).toBe(false)
|
||||
expect(isRibComplete({ label: 'Compte', bic: ' ', iban: 'FR14...' })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('regles type de reglement (RG-2.07 / RG-2.08)', () => {
|
||||
it('banque obligatoire si VIREMENT', () => {
|
||||
expect(isBankRequiredForPaymentType('VIREMENT')).toBe(true)
|
||||
expect(isBankRequiredForPaymentType('LCR')).toBe(false)
|
||||
expect(isBankRequiredForPaymentType(null)).toBe(false)
|
||||
})
|
||||
|
||||
it('RIB obligatoire si LCR', () => {
|
||||
expect(isRibRequiredForPaymentType('LCR')).toBe(true)
|
||||
expect(isRibRequiredForPaymentType('VIREMENT')).toBe(false)
|
||||
expect(isRibRequiredForPaymentType(null)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isAddressValid (enum addressType, RG-2.06/2.09/2.10 ; pas d\'email facturation)', () => {
|
||||
function validAddress(): AddressValidityDraft {
|
||||
return {
|
||||
addressType: 'DEPART',
|
||||
categoryIris: ['/api/categories/1'],
|
||||
siteIris: ['/api/sites/1'],
|
||||
}
|
||||
}
|
||||
|
||||
it('vrai quand type + >= 1 site + >= 1 categorie', () => {
|
||||
expect(isAddressValid(validAddress())).toBe(true)
|
||||
})
|
||||
|
||||
it('faux si le type d\'adresse n\'est pas renseigne (amorce vierge)', () => {
|
||||
expect(isAddressValid({ ...validAddress(), addressType: null })).toBe(false)
|
||||
})
|
||||
|
||||
it('faux si aucun site (RG-2.06)', () => {
|
||||
expect(isAddressValid({ ...validAddress(), siteIris: [] })).toBe(false)
|
||||
})
|
||||
|
||||
it('faux si aucune categorie (RG-2.10)', () => {
|
||||
expect(isAddressValid({ ...validAddress(), categoryIris: [] })).toBe(false)
|
||||
})
|
||||
|
||||
it('accepte les trois valeurs d\'enum PROSPECT / DEPART / RENDU', () => {
|
||||
for (const type of ['PROSPECT', 'DEPART', 'RENDU'] as const) {
|
||||
expect(isAddressValid({ ...validAddress(), addressType: type })).toBe(true)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('omitEmptyRequired (ERP-119 : 422 NotBlank au lieu de 400 de type)', () => {
|
||||
it('retire les cles requises vides et conserve le reste', () => {
|
||||
const payload = omitEmptyRequired(
|
||||
{ companyName: null, sites: ['/api/sites/1'] },
|
||||
['companyName'],
|
||||
)
|
||||
expect('companyName' in payload).toBe(false)
|
||||
expect(payload.sites).toEqual(['/api/sites/1'])
|
||||
})
|
||||
|
||||
it('false / 0 ne sont pas consideres vides (booleens / nombres preserves)', () => {
|
||||
const payload = omitEmptyRequired({ triageProvider: false, bennes: 0 }, ['triageProvider', 'bennes'])
|
||||
expect(payload).toEqual({ triageProvider: false, bennes: 0 })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* Helpers purs de payload de l'ecran « Ajouter un fournisseur » (M2 Commercial),
|
||||
* partages avec la future modification (96) — miroir de `clientEdit.ts` (M1).
|
||||
*
|
||||
* Scoping STRICT des payloads (mode strict, aligne ERP-74/RG) : chaque onglet
|
||||
* n'envoie QUE les champs de SON groupe de serialisation, jamais un payload mixte
|
||||
* (un champ hors-permission = 403 sur l'integralite cote back). Ces helpers ne
|
||||
* touchent ni a l'API ni a l'etat reactif.
|
||||
*/
|
||||
|
||||
import {
|
||||
ADDRESS_REQUIRED_NON_NULLABLE_KEYS,
|
||||
MAIN_REQUIRED_NON_NULLABLE_KEYS,
|
||||
omitEmptyRequired,
|
||||
RIB_REQUIRED_NON_NULLABLE_KEYS,
|
||||
} from '~/modules/commercial/utils/supplierFormRules'
|
||||
import type {
|
||||
SupplierAddressFormDraft,
|
||||
SupplierContactFormDraft,
|
||||
SupplierRibFormDraft,
|
||||
} from '~/modules/commercial/types/supplierForm'
|
||||
|
||||
/** Etat « plat » du bloc principal (groupe supplier:write:main). */
|
||||
export interface MainFormDraft {
|
||||
companyName: string | null
|
||||
/** IRI des categories rattachees (M2M, type FOURNISSEUR). */
|
||||
categoryIris: string[]
|
||||
}
|
||||
|
||||
/** Etat « plat » de l'onglet Information (groupe supplier:write:information). */
|
||||
export interface InformationFormDraft {
|
||||
description: string | null
|
||||
competitors: string | null
|
||||
/** Date de creation de l'entreprise au format YYYY-MM-DD (MalioDate). */
|
||||
foundedAt: string | null
|
||||
/** Nombre de salaries en chaine (saisie masquee), converti en number au PATCH. */
|
||||
employeesCount: string | null
|
||||
revenueAmount: string | null
|
||||
profitAmount: string | null
|
||||
directorName: string | null
|
||||
/** Volume previsionnel (entier >= 0, specifique fournisseur) en chaine. */
|
||||
volumeForecast: string | null
|
||||
}
|
||||
|
||||
/** Etat « plat » de l'onglet Comptabilite (groupe supplier:write:accounting). */
|
||||
export interface AccountingFormDraft {
|
||||
siren: string | null
|
||||
accountNumber: string | null
|
||||
nTva: string | null
|
||||
tvaModeIri: string | null
|
||||
paymentDelayIri: string | null
|
||||
paymentTypeIri: string | null
|
||||
bankIri: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload du bloc principal — groupe supplier:write:main UNIQUEMENT.
|
||||
* companyName omis si vide -> 422 NotBlank au lieu d'un 400 de type (ERP-119).
|
||||
*/
|
||||
export function buildMainPayload(main: MainFormDraft): Record<string, unknown> {
|
||||
return omitEmptyRequired({
|
||||
companyName: main.companyName,
|
||||
categories: main.categoryIris,
|
||||
}, MAIN_REQUIRED_NON_NULLABLE_KEYS)
|
||||
}
|
||||
|
||||
/** Payload de l'onglet Information — groupe supplier:write:information UNIQUEMENT. */
|
||||
export function buildInformationPayload(information: InformationFormDraft): Record<string, unknown> {
|
||||
return {
|
||||
description: information.description || null,
|
||||
competitors: information.competitors || null,
|
||||
foundedAt: information.foundedAt || null,
|
||||
employeesCount: information.employeesCount ? Number(information.employeesCount) : null,
|
||||
revenueAmount: information.revenueAmount || null,
|
||||
profitAmount: information.profitAmount || null,
|
||||
directorName: information.directorName || null,
|
||||
volumeForecast: information.volumeForecast ? Number(information.volumeForecast) : null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload des scalaires de l'onglet Comptabilite — groupe supplier:write:accounting
|
||||
* UNIQUEMENT (les RIB passent par la sous-ressource /suppliers/{id}/ribs). La
|
||||
* banque n'a de sens que pour un Virement (RG-2.07) : forcee a null sinon.
|
||||
*/
|
||||
export function buildAccountingPayload(
|
||||
accounting: AccountingFormDraft,
|
||||
isBankRequired: boolean,
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
siren: accounting.siren || null,
|
||||
accountNumber: accounting.accountNumber || null,
|
||||
tvaMode: accounting.tvaModeIri,
|
||||
nTva: accounting.nTva || null,
|
||||
paymentDelay: accounting.paymentDelayIri,
|
||||
paymentType: accounting.paymentTypeIri,
|
||||
bank: isBankRequired ? accounting.bankIri : null,
|
||||
}
|
||||
}
|
||||
|
||||
/** Payload d'un contact (sous-ressource supplier_contact). */
|
||||
export function buildContactPayload(contact: SupplierContactFormDraft): Record<string, unknown> {
|
||||
return {
|
||||
firstName: contact.firstName || null,
|
||||
lastName: contact.lastName || null,
|
||||
jobTitle: contact.jobTitle || null,
|
||||
phonePrimary: contact.phonePrimary || null,
|
||||
phoneSecondary: contact.hasSecondaryPhone ? (contact.phoneSecondary || null) : null,
|
||||
email: contact.email || null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload d'une adresse (sous-ressource supplier_address). postalCode / city /
|
||||
* street omis si vides -> 422 NotBlank (ERP-119). Specifique fournisseur :
|
||||
* `bennes` (entier, 0 par defaut) + `triageProvider` (booleen). Pas d'email de
|
||||
* facturation (difference M1).
|
||||
*/
|
||||
export function buildAddressPayload(address: SupplierAddressFormDraft): Record<string, unknown> {
|
||||
return omitEmptyRequired({
|
||||
addressType: address.addressType,
|
||||
country: address.country,
|
||||
postalCode: address.postalCode || null,
|
||||
city: address.city || null,
|
||||
street: address.street || null,
|
||||
streetComplement: address.streetComplement || null,
|
||||
categories: address.categoryIris,
|
||||
sites: address.siteIris,
|
||||
contacts: address.contactIris,
|
||||
bennes: address.bennes !== null && address.bennes !== '' ? Number(address.bennes) : null,
|
||||
triageProvider: address.triageProvider,
|
||||
}, ADDRESS_REQUIRED_NON_NULLABLE_KEYS)
|
||||
}
|
||||
|
||||
/** Payload d'un RIB (sous-ressource supplier_rib). */
|
||||
export function buildRibPayload(rib: SupplierRibFormDraft): Record<string, unknown> {
|
||||
return omitEmptyRequired({
|
||||
label: rib.label,
|
||||
bic: rib.bic,
|
||||
iban: rib.iban,
|
||||
}, RIB_REQUIRED_NON_NULLABLE_KEYS)
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* Regles metier pures de l'ecran « Ajouter un fournisseur » (M2 Commercial).
|
||||
*
|
||||
* Miroir de `clientFormRules.ts` (M1), centralisees ici (hors composant) pour
|
||||
* rester testables unitairement et partagees entre la creation et les ecrans
|
||||
* d'edition/consultation (95/96). Ces helpers ne touchent ni a l'API ni a l'etat
|
||||
* reactif : ils prennent des brouillons « plats » et retournent des booleens.
|
||||
*
|
||||
* Le back reste la source de verite (les RG sont re-validees serveur, mode
|
||||
* strict) ; ces regles ne servent qu'au feedback UI immediat (gating de boutons).
|
||||
*
|
||||
* Differences M2 vs M1 :
|
||||
* - Adresse via enum `addressType` (PROSPECT/DEPART/RENDU, RG-2.09) — pas de
|
||||
* drapeaux ni d'exclusivite a gerer cote front (le radio est exclusif par nature).
|
||||
* - Pas d'email de facturation, pas de relation Distributeur/Courtier.
|
||||
*/
|
||||
|
||||
import type { SupplierAddressType } from '~/modules/commercial/types/supplierForm'
|
||||
|
||||
/**
|
||||
* Onglets « coquille » (non encore implementes) : frame vide, passage
|
||||
* automatique a l'onglet suivant (aligne M1).
|
||||
*/
|
||||
export const SUPPLIER_FORM_PLACEHOLDER_TABS = ['transport', 'statistics', 'reports', 'exchanges'] as const
|
||||
|
||||
/**
|
||||
* Onglets affiches uniquement en MODIFICATION/CONSULTATION (jamais a la
|
||||
* creation) : Statistiques / Rapports / Echanges. A rebrancher dans les ecrans
|
||||
* 95/96 via l'option `includeEditOnlyTabs`.
|
||||
*/
|
||||
export const SUPPLIER_FORM_EDIT_ONLY_TABS = ['statistics', 'reports', 'exchanges'] as const
|
||||
|
||||
/**
|
||||
* Construit l'ordre des onglets du formulaire fournisseur.
|
||||
* - L'onglet Comptabilite n'est present que si l'utilisateur a `accounting.view`
|
||||
* (Bureau / Commerciale ne le voient pas).
|
||||
* - Les onglets edit-only sont exclus par defaut (creation) ; passer
|
||||
* `includeEditOnlyTabs: true` pour les afficher en modification/consultation.
|
||||
* Ordre aligne sur la spec M2 § Ecran « Ajouter un fournisseur » (barre 5 onglets).
|
||||
*/
|
||||
export function buildSupplierFormTabKeys(
|
||||
canAccountingView: boolean,
|
||||
options: { includeEditOnlyTabs?: boolean } = {},
|
||||
): string[] {
|
||||
const keys = ['information', 'contacts', 'addresses', 'transport']
|
||||
if (canAccountingView) {
|
||||
keys.push('accounting')
|
||||
}
|
||||
if (options.includeEditOnlyTabs) {
|
||||
keys.push(...SUPPLIER_FORM_EDIT_ONLY_TABS)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
/**
|
||||
* Dernier onglet REMPLISSABLE d'un jeu d'onglets : le dernier qui n'est pas un
|
||||
* placeholder. Role-aware sans regle ad hoc — il suffit de lui passer les
|
||||
* `tabKeys` deja filtres par permission. Sa validation marque la fin de l'ajout.
|
||||
*/
|
||||
export function lastFillableTabKey(tabKeys: string[]): string | undefined {
|
||||
return [...tabKeys].reverse().find(
|
||||
key => !(SUPPLIER_FORM_PLACEHOLDER_TABS as readonly string[]).includes(key),
|
||||
)
|
||||
}
|
||||
|
||||
/** Sous-ensemble d'un contact necessaire aux regles de nommage (RG-2.04/2.13). */
|
||||
export interface ContactDraft {
|
||||
firstName: string | null
|
||||
lastName: string | null
|
||||
}
|
||||
|
||||
/** Vrai si une chaine porte au moins un caractere non-espace. */
|
||||
function isFilled(value: string | null | undefined): boolean {
|
||||
return value !== null && value !== undefined && value.trim() !== ''
|
||||
}
|
||||
|
||||
/** RG-2.04 : un contact est valide des qu'il porte un nom OU un prenom. */
|
||||
export function isContactNamed(contact: ContactDraft): boolean {
|
||||
return isFilled(contact.firstName) || isFilled(contact.lastName)
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-2.13 : l'onglet Contacts ne peut etre finalise que s'il reste au moins un
|
||||
* contact nomme (nom ou prenom).
|
||||
*/
|
||||
export function hasAtLeastOneValidContact(contacts: ContactDraft[]): boolean {
|
||||
return contacts.some(isContactNamed)
|
||||
}
|
||||
|
||||
/**
|
||||
* Primitive reutilisable : vrai si TOUTES les valeurs fournies sont vides. Sert a
|
||||
* detecter un bloc de collection totalement vide (amorce non remplie). Un bloc qui
|
||||
* porte la moindre donnee n'est PAS « blank » : il doit etre soumis pour declencher
|
||||
* sa 422 inline plutot que d'etre saute silencieusement.
|
||||
*/
|
||||
export function isBlankRow(values: (string | null | undefined)[]): boolean {
|
||||
return values.every(value => !isFilled(value))
|
||||
}
|
||||
|
||||
/** Champs saisissables d'un bloc contact (pour detecter un bloc totalement vide). */
|
||||
export interface ContactFillableDraft extends ContactDraft {
|
||||
jobTitle: string | null
|
||||
phonePrimary: string | null
|
||||
phoneSecondary: string | null
|
||||
email: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si AUCUN champ saisissable du bloc contact n'est rempli. Distingue un bloc
|
||||
* d'amorce vide (a ignorer au submit) d'un bloc partiellement rempli sans nom
|
||||
* (email/telephone/fonction seul) : ce dernier doit etre soumis pour declencher la
|
||||
* 422 RG-2.04 affichee inline.
|
||||
*/
|
||||
export function isContactBlank(contact: ContactFillableDraft): boolean {
|
||||
return isBlankRow([
|
||||
contact.firstName,
|
||||
contact.lastName,
|
||||
contact.jobTitle,
|
||||
contact.phonePrimary,
|
||||
contact.phoneSecondary,
|
||||
contact.email,
|
||||
])
|
||||
}
|
||||
|
||||
/** Champs saisissables d'un bloc RIB (pour detecter un bloc totalement vide). */
|
||||
export interface RibFillableDraft {
|
||||
label: string | null
|
||||
bic: string | null
|
||||
iban: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrai si AUCUN champ du bloc RIB n'est rempli. Un RIB partiellement rempli (ex.
|
||||
* IBAN seul) n'est PAS « blank » : il doit etre soumis pour declencher les 422
|
||||
* NotBlank inline plutot que d'etre saute silencieusement.
|
||||
*/
|
||||
export function isRibBlank(rib: RibFillableDraft): boolean {
|
||||
return isBlankRow([rib.label, rib.bic, rib.iban])
|
||||
}
|
||||
|
||||
/**
|
||||
* RG-2.08 : un RIB est complet quand ses trois champs sont remplis (label, BIC,
|
||||
* IBAN). Predicat partage entre le gating du bouton « + RIB » et la validation de
|
||||
* l'onglet (au moins un RIB complet si reglement LCR).
|
||||
*/
|
||||
export function isRibComplete(rib: RibFillableDraft): boolean {
|
||||
return isFilled(rib.label) && isFilled(rib.bic) && isFilled(rib.iban)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sous-ensemble d'une adresse necessaire a sa validite par-bloc : type (enum),
|
||||
* sites et categories rattaches.
|
||||
*/
|
||||
export interface AddressValidityDraft {
|
||||
addressType: SupplierAddressType | null
|
||||
categoryIris: string[]
|
||||
siteIris: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Validite par-bloc d'une adresse : type renseigne (RG-2.09), >= 1 site (RG-2.06)
|
||||
* et >= 1 categorie (RG-2.10). Predicat partage entre le gating du bouton
|
||||
* « + Adresse » (le dernier bloc doit etre valide avant d'en ajouter un autre) et
|
||||
* la validation de l'onglet (toutes les adresses valides). Pas d'email de
|
||||
* facturation cote fournisseur (difference M1).
|
||||
*/
|
||||
export function isAddressValid(address: AddressValidityDraft): boolean {
|
||||
return address.addressType !== null
|
||||
&& address.siteIris.length >= 1
|
||||
&& address.categoryIris.length >= 1
|
||||
}
|
||||
|
||||
/** Code stable du type de reglement « virement » (RG-2.07). */
|
||||
const PAYMENT_TYPE_TRANSFER = 'VIREMENT'
|
||||
|
||||
/** Code stable du type de reglement « lettre de change » (RG-2.08). */
|
||||
const PAYMENT_TYPE_LCR = 'LCR'
|
||||
|
||||
/** RG-2.07 : la banque est obligatoire lorsque le type de reglement est un virement. */
|
||||
export function isBankRequiredForPaymentType(code: string | null | undefined): boolean {
|
||||
return code === PAYMENT_TYPE_TRANSFER
|
||||
}
|
||||
|
||||
/** RG-2.08 : au moins un RIB complet est obligatoire lorsque le type de reglement est une LCR. */
|
||||
export function isRibRequiredForPaymentType(code: string | null | undefined): boolean {
|
||||
return code === PAYMENT_TYPE_LCR
|
||||
}
|
||||
|
||||
// ── Champs requis adosses a une colonne NON-nullable (ERP-119) ───────────────
|
||||
// Memes contraintes qu'au M1 : un champ requis (NotBlank) porte par une colonne
|
||||
// Doctrine NON nullable rejette `null` en 400 de TYPE avant le Validator. Parade :
|
||||
// OMETTRE la cle du payload quand elle est vide -> le back produit une 422 NotBlank
|
||||
// avec propertyPath, mappee en rouge sous le champ.
|
||||
export const MAIN_REQUIRED_NON_NULLABLE_KEYS = ['companyName'] as const
|
||||
export const ADDRESS_REQUIRED_NON_NULLABLE_KEYS = ['postalCode', 'city', 'street'] as const
|
||||
export const RIB_REQUIRED_NON_NULLABLE_KEYS = ['label', 'bic', 'iban'] as const
|
||||
|
||||
/**
|
||||
* Retire d'un payload d'ecriture les cles requises laissees vides (null / '' /
|
||||
* undefined), pour laisser le back produire une 422 NotBlank par champ plutot
|
||||
* qu'un 400 de type sur une colonne non-nullable. Mute et retourne le payload.
|
||||
*/
|
||||
export function omitEmptyRequired<T extends Record<string, unknown>>(
|
||||
payload: T,
|
||||
requiredKeys: readonly string[],
|
||||
): T {
|
||||
for (const key of requiredKeys) {
|
||||
const value = payload[key]
|
||||
if (value === null || value === undefined || value === '') {
|
||||
delete payload[key]
|
||||
}
|
||||
}
|
||||
|
||||
return payload
|
||||
}
|
||||
Reference in New Issue
Block a user