Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7d8a633eee | |||
| df9451a5f4 | |||
| cb12490ba0 | |||
| a442d124a3 | |||
| 431d831c8b | |||
| 3f356f0679 | |||
| c1ce940c98 | |||
| c594a76d47 | |||
| 59bae8c5e6 | |||
| 477f77a6b5 |
+1
-1
@@ -1,2 +1,2 @@
|
|||||||
parameters:
|
parameters:
|
||||||
app.version: '0.1.103'
|
app.version: '0.1.109'
|
||||||
|
|||||||
@@ -26,13 +26,18 @@
|
|||||||
:error="errors?.firstName"
|
:error="errors?.firstName"
|
||||||
@update:model-value="(v: string) => update('firstName', v)"
|
@update:model-value="(v: string) => update('firstName', v)"
|
||||||
/>
|
/>
|
||||||
<MalioInputText
|
<!-- Fonction sur 2 colonnes : on wrappe car MalioInputText
|
||||||
:model-value="model.jobTitle"
|
(inheritAttrs:false) renvoie `class` sur l'input interne, pas sur la
|
||||||
:label="t('commercial.clients.form.contact.jobTitle')"
|
cellule de grille. Le wrapper porte le col-span-2, le champ le remplit. -->
|
||||||
:readonly="readonly"
|
<div class="col-span-2">
|
||||||
:error="errors?.jobTitle"
|
<MalioInputText
|
||||||
@update:model-value="(v: string) => update('jobTitle', v)"
|
:model-value="model.jobTitle"
|
||||||
/>
|
:label="t('commercial.clients.form.contact.jobTitle')"
|
||||||
|
:readonly="readonly"
|
||||||
|
:error="errors?.jobTitle"
|
||||||
|
@update:model-value="(v: string) => update('jobTitle', v)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
<MalioInputEmail
|
<MalioInputEmail
|
||||||
:model-value="model.email"
|
:model-value="model.email"
|
||||||
:label="t('commercial.clients.form.contact.email')"
|
:label="t('commercial.clients.form.contact.email')"
|
||||||
|
|||||||
@@ -25,13 +25,18 @@
|
|||||||
:error="errors?.firstName"
|
:error="errors?.firstName"
|
||||||
@update:model-value="(v: string) => update('firstName', v)"
|
@update:model-value="(v: string) => update('firstName', v)"
|
||||||
/>
|
/>
|
||||||
<MalioInputText
|
<!-- Fonction sur 2 colonnes : on wrappe car MalioInputText
|
||||||
:model-value="model.jobTitle"
|
(inheritAttrs:false) renvoie `class` sur l'input interne, pas sur la
|
||||||
:label="t('commercial.suppliers.form.contact.jobTitle')"
|
cellule de grille. Le wrapper porte le col-span-2, le champ le remplit. -->
|
||||||
:readonly="readonly"
|
<div class="col-span-2">
|
||||||
:error="errors?.jobTitle"
|
<MalioInputText
|
||||||
@update:model-value="(v: string) => update('jobTitle', v)"
|
:model-value="model.jobTitle"
|
||||||
/>
|
:label="t('commercial.suppliers.form.contact.jobTitle')"
|
||||||
|
:readonly="readonly"
|
||||||
|
:error="errors?.jobTitle"
|
||||||
|
@update:model-value="(v: string) => update('jobTitle', v)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
<MalioInputEmail
|
<MalioInputEmail
|
||||||
:model-value="model.email"
|
:model-value="model.email"
|
||||||
:label="t('commercial.suppliers.form.contact.email')"
|
:label="t('commercial.suppliers.form.contact.email')"
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ describe('useClientReferentials.loadCommon (resilience ERP-102)', () => {
|
|||||||
if (url === '/sites') {
|
if (url === '/sites') {
|
||||||
return Promise.resolve({ member: [{ '@id': '/api/sites/1', name: 'Chatellerault', postalCode: '86100' }] })
|
return Promise.resolve({ member: [{ '@id': '/api/sites/1', name: 'Chatellerault', postalCode: '86100' }] })
|
||||||
}
|
}
|
||||||
|
if (url === '/countries') {
|
||||||
|
// Pays : value === label === name (l'adresse stocke le nom).
|
||||||
|
return Promise.resolve({ member: [{ '@id': '/api/countries/1', code: 'FR', name: 'France' }] })
|
||||||
|
}
|
||||||
return Promise.resolve({
|
return Promise.resolve({
|
||||||
member: [{ '@id': '/api/x/1', code: 'X', label: 'Libelle X' }],
|
member: [{ '@id': '/api/x/1', code: 'X', label: 'Libelle X' }],
|
||||||
})
|
})
|
||||||
@@ -44,6 +48,8 @@ describe('useClientReferentials.loadCommon (resilience ERP-102)', () => {
|
|||||||
expect(refs.sites.value).toEqual([{ value: '/api/sites/1', label: '86' }])
|
expect(refs.sites.value).toEqual([{ value: '/api/sites/1', label: '86' }])
|
||||||
expect(refs.tvaModes.value).toEqual([{ value: '/api/x/1', label: 'Libelle X' }])
|
expect(refs.tvaModes.value).toEqual([{ value: '/api/x/1', label: 'Libelle X' }])
|
||||||
expect(refs.banks.value).toEqual([{ value: '/api/x/1', label: 'Libelle X' }])
|
expect(refs.banks.value).toEqual([{ value: '/api/x/1', label: 'Libelle X' }])
|
||||||
|
// Pays : value = nom du pays (et non l'IRI).
|
||||||
|
expect(refs.countries.value).toEqual([{ value: 'France', label: 'France' }])
|
||||||
|
|
||||||
// Seul le select en echec reste vide.
|
// Seul le select en echec reste vide.
|
||||||
expect(refs.categories.value).toEqual([])
|
expect(refs.categories.value).toEqual([])
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
// Mocks des composables auto-importes par Nuxt (indisponibles sous happy-dom).
|
||||||
|
const mockGet = vi.hoisted(() => vi.fn())
|
||||||
|
const mockPatch = vi.hoisted(() => vi.fn())
|
||||||
|
|
||||||
|
vi.stubGlobal('useApi', () => ({
|
||||||
|
get: mockGet,
|
||||||
|
post: vi.fn(),
|
||||||
|
put: vi.fn(),
|
||||||
|
patch: mockPatch,
|
||||||
|
delete: vi.fn(),
|
||||||
|
}))
|
||||||
|
|
||||||
|
const { useSupplier } = await import('../useSupplier')
|
||||||
|
|
||||||
|
const SAMPLE = { '@id': '/api/suppliers/85', id: 85, companyName: 'DOD59393F 862875', isArchived: false }
|
||||||
|
|
||||||
|
describe('useSupplier', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
mockGet.mockReset()
|
||||||
|
mockPatch.mockReset()
|
||||||
|
mockGet.mockResolvedValue(SAMPLE)
|
||||||
|
mockPatch.mockResolvedValue({ ...SAMPLE, isArchived: true })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('charge le detail via GET /suppliers/{id} en Hydra, sans toast', async () => {
|
||||||
|
const { supplier, load } = useSupplier(85)
|
||||||
|
await load()
|
||||||
|
|
||||||
|
expect(mockGet).toHaveBeenCalledWith(
|
||||||
|
'/suppliers/85',
|
||||||
|
{},
|
||||||
|
expect.objectContaining({
|
||||||
|
headers: { Accept: 'application/ld+json' },
|
||||||
|
toast: false,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
expect(supplier.value).toEqual(SAMPLE)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('bascule loading pendant le chargement et le retombe a false', async () => {
|
||||||
|
const { loading, load } = useSupplier(85)
|
||||||
|
const promise = load()
|
||||||
|
expect(loading.value).toBe(true)
|
||||||
|
await promise
|
||||||
|
expect(loading.value).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('marque error et laisse supplier null si le GET echoue (404...)', async () => {
|
||||||
|
mockGet.mockRejectedValueOnce(new Error('not found'))
|
||||||
|
const { supplier, error, load } = useSupplier(99)
|
||||||
|
await load()
|
||||||
|
expect(error.value).toBe(true)
|
||||||
|
expect(supplier.value).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('archive() PATCHe { isArchived: true } sans toast puis RECHARGE le detail complet', async () => {
|
||||||
|
// 1er GET = chargement initial, 2e GET = rechargement post-archivage.
|
||||||
|
mockGet.mockResolvedValueOnce(SAMPLE)
|
||||||
|
mockGet.mockResolvedValueOnce({ ...SAMPLE, isArchived: true })
|
||||||
|
const { supplier, load, archive } = useSupplier(85)
|
||||||
|
await load()
|
||||||
|
await archive()
|
||||||
|
|
||||||
|
expect(mockPatch).toHaveBeenCalledWith(
|
||||||
|
'/suppliers/85',
|
||||||
|
{ isArchived: true },
|
||||||
|
expect.objectContaining({ toast: false }),
|
||||||
|
)
|
||||||
|
// Le detail est re-fetch (le PATCH ne renvoie pas l'embed complet).
|
||||||
|
expect(mockGet).toHaveBeenCalledTimes(2)
|
||||||
|
expect(supplier.value?.isArchived).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('restore() PATCHe { isArchived: false } (payload isArchived SEUL)', async () => {
|
||||||
|
const { load, restore } = useSupplier(85)
|
||||||
|
await load()
|
||||||
|
await restore()
|
||||||
|
|
||||||
|
expect(mockPatch).toHaveBeenCalledWith(
|
||||||
|
'/suppliers/85',
|
||||||
|
{ isArchived: false },
|
||||||
|
expect.objectContaining({ toast: false }),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('propage l\'erreur (ex: 403 sans permission archive, 409 conflit homonyme) au lieu de l\'avaler', async () => {
|
||||||
|
const forbidden = { response: { status: 403 } }
|
||||||
|
mockPatch.mockRejectedValueOnce(forbidden)
|
||||||
|
const { load, archive } = useSupplier(85)
|
||||||
|
await load()
|
||||||
|
await expect(archive()).rejects.toBe(forbidden)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -3,7 +3,7 @@ import { ref } from 'vue'
|
|||||||
/**
|
/**
|
||||||
* Charge les referentiels (listes courtes) alimentant les selects de l'ecran
|
* Charge les referentiels (listes courtes) alimentant les selects de l'ecran
|
||||||
* « Ajouter un client » : categories, sites, modes de TVA, delais et types de
|
* « Ajouter un client » : categories, sites, modes de TVA, delais et types de
|
||||||
* reglement, banques, et les listes distributeurs / courtiers.
|
* reglement, banques, pays, et les listes distributeurs / courtiers.
|
||||||
*
|
*
|
||||||
* Toutes les collections sont recuperees en entier via l'echappatoire prevue
|
* Toutes les collections sont recuperees en entier via l'echappatoire prevue
|
||||||
* `?pagination=false` (referentiels de quelques dizaines d'entrees max), avec
|
* `?pagination=false` (referentiels de quelques dizaines d'entrees max), avec
|
||||||
@@ -57,6 +57,11 @@ interface ClientMember extends HydraMember {
|
|||||||
companyName: string
|
companyName: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface CountryMember extends HydraMember {
|
||||||
|
code: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
const LD_JSON_HEADERS = { Accept: 'application/ld+json' }
|
const LD_JSON_HEADERS = { Accept: 'application/ld+json' }
|
||||||
|
|
||||||
export function useClientReferentials() {
|
export function useClientReferentials() {
|
||||||
@@ -68,6 +73,7 @@ export function useClientReferentials() {
|
|||||||
const paymentDelays = ref<RefOption[]>([])
|
const paymentDelays = ref<RefOption[]>([])
|
||||||
const paymentTypes = ref<PaymentTypeOption[]>([])
|
const paymentTypes = ref<PaymentTypeOption[]>([])
|
||||||
const banks = ref<RefOption[]>([])
|
const banks = ref<RefOption[]>([])
|
||||||
|
const countries = ref<RefOption[]>([])
|
||||||
const distributors = ref<ClientOption[]>([])
|
const distributors = ref<ClientOption[]>([])
|
||||||
const brokers = ref<ClientOption[]>([])
|
const brokers = ref<ClientOption[]>([])
|
||||||
|
|
||||||
@@ -116,6 +122,12 @@ export function useClientReferentials() {
|
|||||||
.then((types) => { paymentTypes.value = types.map(t => ({ value: t['@id'], label: t.label, code: t.code })) }),
|
.then((types) => { paymentTypes.value = types.map(t => ({ value: t['@id'], label: t.label, code: t.code })) }),
|
||||||
fetchAll<ReferentialMember>('/banks')
|
fetchAll<ReferentialMember>('/banks')
|
||||||
.then((banksList) => { banks.value = banksList.map(b => ({ value: b['@id'], label: b.label })) }),
|
.then((banksList) => { banks.value = banksList.map(b => ({ value: b['@id'], label: b.label })) }),
|
||||||
|
// Pays (ERP-116) : la valeur d'option est le NOM du pays (et non l'IRI),
|
||||||
|
// car l'adresse stocke `country` en chaine libre (« France »...). On
|
||||||
|
// conserve ainsi la compatibilite avec les adresses existantes sans FK
|
||||||
|
// ni migration de donnees a ce stade. value === label.
|
||||||
|
fetchAll<CountryMember>('/countries')
|
||||||
|
.then((list) => { countries.value = list.map(c => ({ value: c.name, label: c.name })) }),
|
||||||
])
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,6 +156,7 @@ export function useClientReferentials() {
|
|||||||
paymentDelays,
|
paymentDelays,
|
||||||
paymentTypes,
|
paymentTypes,
|
||||||
banks,
|
banks,
|
||||||
|
countries,
|
||||||
distributors,
|
distributors,
|
||||||
brokers,
|
brokers,
|
||||||
loadCommon,
|
loadCommon,
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import { ref } from 'vue'
|
||||||
|
import type { SupplierDetail } from '~/modules/commercial/utils/supplierConsultation'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Chargement et actions d'archivage d'un fournisseur unique (ecran « Consultation
|
||||||
|
* fournisseur », ERP-95). Miroir de `useClient` (M1). Lit le detail embarque via
|
||||||
|
* `GET /api/suppliers/{id}` (contacts / adresses / ribs sous `supplier:item:read` /
|
||||||
|
* `supplier:read:accounting`) et expose les bascules d'archivage (PATCH `isArchived`
|
||||||
|
* SEUL — tout autre champ => 422).
|
||||||
|
*
|
||||||
|
* L'en-tete `Accept: application/ld+json` est impose pour obtenir le payload
|
||||||
|
* Hydra complet (sans lui, API Platform 4 renvoie une representation reduite).
|
||||||
|
*
|
||||||
|
* Etat 100 % local a l'instance (refs) — aucune persistance URL. Les erreurs
|
||||||
|
* d'archivage/restauration (notamment le 409 d'homonyme actif a la restauration)
|
||||||
|
* sont PROPAGEES a l'appelant, qui decide du toast a afficher.
|
||||||
|
*/
|
||||||
|
export function useSupplier(id: number | string) {
|
||||||
|
const api = useApi()
|
||||||
|
|
||||||
|
const supplier = ref<SupplierDetail | null>(null)
|
||||||
|
const loading = ref(false)
|
||||||
|
const error = ref(false)
|
||||||
|
|
||||||
|
/** Recupere le detail complet (embed contacts/adresses/ribs + comptabilite). */
|
||||||
|
function fetchDetail(): Promise<SupplierDetail> {
|
||||||
|
return api.get<SupplierDetail>(
|
||||||
|
`/suppliers/${id}`,
|
||||||
|
{},
|
||||||
|
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Charge le detail du fournisseur. En cas d'echec : `error = true`, `supplier = null`. */
|
||||||
|
async function load(): Promise<void> {
|
||||||
|
loading.value = true
|
||||||
|
error.value = false
|
||||||
|
try {
|
||||||
|
supplier.value = await fetchDetail()
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
error.value = true
|
||||||
|
supplier.value = null
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bascule l'archivage (PATCH `isArchived` SEUL — tout autre champ => 422),
|
||||||
|
* puis RECHARGE le detail complet : la reponse du PATCH ne porte que le groupe
|
||||||
|
* `supplier:read` (ni l'embed contacts/adresses/ribs ni les libelles des
|
||||||
|
* referentiels comptables), un simple merge laisserait l'affichage incoherent.
|
||||||
|
* Toute erreur (notamment le 409 d'homonyme actif a la restauration) est
|
||||||
|
* propagee a l'appelant AVANT le rechargement.
|
||||||
|
*/
|
||||||
|
async function setArchived(isArchived: boolean): Promise<void> {
|
||||||
|
await api.patch(`/suppliers/${id}`, { isArchived }, { toast: false })
|
||||||
|
supplier.value = await fetchDetail()
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
supplier,
|
||||||
|
loading,
|
||||||
|
error,
|
||||||
|
load,
|
||||||
|
archive: () => setArchived(true),
|
||||||
|
restore: () => setArchived(false),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -51,6 +51,11 @@ interface ReferentialMember extends HydraMember {
|
|||||||
label: string
|
label: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface CountryMember extends HydraMember {
|
||||||
|
code: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
const LD_JSON_HEADERS = { Accept: 'application/ld+json' }
|
const LD_JSON_HEADERS = { Accept: 'application/ld+json' }
|
||||||
|
|
||||||
export function useSupplierReferentials() {
|
export function useSupplierReferentials() {
|
||||||
@@ -62,6 +67,7 @@ export function useSupplierReferentials() {
|
|||||||
const paymentDelays = ref<RefOption[]>([])
|
const paymentDelays = ref<RefOption[]>([])
|
||||||
const paymentTypes = ref<PaymentTypeOption[]>([])
|
const paymentTypes = ref<PaymentTypeOption[]>([])
|
||||||
const banks = ref<RefOption[]>([])
|
const banks = ref<RefOption[]>([])
|
||||||
|
const countries = ref<RefOption[]>([])
|
||||||
|
|
||||||
/** Recupere une collection complete (pagination desactivee) en Hydra. */
|
/** Recupere une collection complete (pagination desactivee) en Hydra. */
|
||||||
async function fetchAll<T extends HydraMember>(
|
async function fetchAll<T extends HydraMember>(
|
||||||
@@ -103,6 +109,13 @@ export function useSupplierReferentials() {
|
|||||||
.then((types) => { paymentTypes.value = types.map(t => ({ value: t['@id'], label: t.label, code: t.code })) }),
|
.then((types) => { paymentTypes.value = types.map(t => ({ value: t['@id'], label: t.label, code: t.code })) }),
|
||||||
fetchAll<ReferentialMember>('/banks')
|
fetchAll<ReferentialMember>('/banks')
|
||||||
.then((banksList) => { banks.value = banksList.map(b => ({ value: b['@id'], label: b.label })) }),
|
.then((banksList) => { banks.value = banksList.map(b => ({ value: b['@id'], label: b.label })) }),
|
||||||
|
// Pays (ERP-116) : la valeur d'option est le NOM du pays (et non l'IRI),
|
||||||
|
// car l'adresse stocke `country` en chaine libre (« France »...). On
|
||||||
|
// conserve ainsi la compatibilite avec les adresses existantes sans FK
|
||||||
|
// ni migration de donnees a ce stade. value === label. Aligne sur les
|
||||||
|
// clients (`useClientReferentials`) pour une liste de pays identique.
|
||||||
|
fetchAll<CountryMember>('/countries')
|
||||||
|
.then((list) => { countries.value = list.map(c => ({ value: c.name, label: c.name })) }),
|
||||||
])
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,6 +126,7 @@ export function useSupplierReferentials() {
|
|||||||
paymentDelays,
|
paymentDelays,
|
||||||
paymentTypes,
|
paymentTypes,
|
||||||
banks,
|
banks,
|
||||||
|
countries,
|
||||||
loadCommon,
|
loadCommon,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -303,7 +303,7 @@
|
|||||||
class="relative bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]"
|
class="relative bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]"
|
||||||
>
|
>
|
||||||
<MalioButtonIcon
|
<MalioButtonIcon
|
||||||
v-if="!accountingReadonly"
|
v-if="!accountingReadonly && visibleRibs.length > 1"
|
||||||
icon="mdi:delete-outline"
|
icon="mdi:delete-outline"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
button-class="absolute top-3 right-3"
|
button-class="absolute top-3 right-3"
|
||||||
@@ -553,10 +553,21 @@ const contactOptions = computed<RefOption[]>(() =>
|
|||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
|
|
||||||
const countryOptions: RefOption[] = [
|
// Pays : referentiel `country` charge via l'API (ERP-116), en remplacement de
|
||||||
{ value: 'France', label: 'France' },
|
// l'ancienne liste codee en dur. Valeur = nom du pays (l'adresse stocke
|
||||||
{ value: 'Espagne', label: 'Espagne' },
|
// `country` en chaine libre, donc value === label). On merge la valeur deja
|
||||||
]
|
// stockee sur chaque adresse (embed) — comme les autres selects de cet ecran —
|
||||||
|
// pour ne pas vider le select si `/countries` echoue (resilience ERP-102) ou si
|
||||||
|
// un pays historique n'appartient pas au referentiel.
|
||||||
|
const embedCountryOptions = computed<RefOption[]>(() =>
|
||||||
|
mergeOptions([], (client.value?.addresses ?? [])
|
||||||
|
.map(a => a.country)
|
||||||
|
.filter((c): c is string => !!c)
|
||||||
|
.map(c => ({ value: c, label: c }))),
|
||||||
|
)
|
||||||
|
const countryOptions = computed<RefOption[]>(() =>
|
||||||
|
mergeOptions(referentials.countries.value, embedCountryOptions.value),
|
||||||
|
)
|
||||||
|
|
||||||
const relationOptions = computed<RefOption[]>(() => [
|
const relationOptions = computed<RefOption[]>(() => [
|
||||||
{ value: 'distributeur', label: t('commercial.clients.form.main.relationDistributor') },
|
{ value: 'distributeur', label: t('commercial.clients.form.main.relationDistributor') },
|
||||||
@@ -689,7 +700,7 @@ async function submitMain(): Promise<void> {
|
|||||||
mainSubmitting.value = true
|
mainSubmitting.value = true
|
||||||
mainErrors.clearErrors()
|
mainErrors.clearErrors()
|
||||||
try {
|
try {
|
||||||
const updated = await api.patch<ClientDetail>(`/clients/${clientId}`, buildMainPayload(main), {
|
const updated = await api.patch<ClientDetail>(`/clients/${clientId}`, buildMainPayload(main, { forUpdate: true }), {
|
||||||
headers: { Accept: 'application/ld+json' },
|
headers: { Accept: 'application/ld+json' },
|
||||||
toast: false,
|
toast: false,
|
||||||
})
|
})
|
||||||
@@ -859,7 +870,10 @@ async function submitAddresses(): Promise<void> {
|
|||||||
addresses.value,
|
addresses.value,
|
||||||
addressErrors,
|
addressErrors,
|
||||||
async (address) => {
|
async (address) => {
|
||||||
const body = buildAddressPayload(address, isBillingEmailRequired(address))
|
// Edition d'une adresse existante : champ requis vide envoye en `''`
|
||||||
|
// (NotBlank 422) au lieu d'etre omis — sinon le PATCH garderait
|
||||||
|
// l'ancienne valeur (faux 200). Creation (id null) : omit classique.
|
||||||
|
const body = buildAddressPayload(address, isBillingEmailRequired(address), { forUpdate: address.id !== null })
|
||||||
if (address.id === null) {
|
if (address.id === null) {
|
||||||
const created = await api.post<{ id: number }>(
|
const created = await api.post<{ id: number }>(
|
||||||
`/clients/${clientId}/addresses`,
|
`/clients/${clientId}/addresses`,
|
||||||
@@ -898,17 +912,16 @@ const visibleRibs = computed(() => isRibRequired.value ? ribs.value : [])
|
|||||||
function onPaymentTypeChange(value: string | number | null): void {
|
function onPaymentTypeChange(value: string | number | null): void {
|
||||||
accounting.paymentTypeIri = value === null ? null : String(value)
|
accounting.paymentTypeIri = value === null ? null : String(value)
|
||||||
if (!isBankRequired.value) accounting.bankIri = null
|
if (!isBankRequired.value) accounting.bankIri = null
|
||||||
// Les RIB n'ont de sens que pour une LCR (RG-1.13) : on amorce un bloc vide
|
// ERP-121 : un RIB est une coordonnee bancaire du client, decouplee du mode de
|
||||||
// quand LCR est choisi, sinon on vide la liste — les RIB deja persistes sont
|
// reglement. Au passage hors-LCR on ne SUPPRIME plus les RIB existants : ils
|
||||||
// marques pour suppression serveur au prochain enregistrement.
|
// restent en base, simplement masques a l'ecran (visibleRibs = []), et
|
||||||
|
// reapparaissent tels quels si l'on repasse en LCR. Seule la corbeille d'un
|
||||||
|
// bloc (askRemoveRib) retire reellement un RIB.
|
||||||
if (isRibRequired.value) {
|
if (isRibRequired.value) {
|
||||||
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
for (const rib of ribs.value) {
|
// Hors-LCR : on nettoie seulement les erreurs inline (plus affichees).
|
||||||
if (rib.id != null) removedRibIds.value.push(rib.id)
|
|
||||||
}
|
|
||||||
ribs.value = []
|
|
||||||
ribErrors.value = []
|
ribErrors.value = []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -937,45 +950,58 @@ function askRemoveRib(index: number): void {
|
|||||||
/**
|
/**
|
||||||
* Valide l'onglet Comptabilite : POST/PATCH des RIB sur la sous-ressource PUIS
|
* Valide l'onglet Comptabilite : POST/PATCH des RIB sur la sous-ressource PUIS
|
||||||
* PATCH des scalaires (groupe client:write:accounting, exige accounting.manage cote
|
* PATCH des scalaires (groupe client:write:accounting, exige accounting.manage cote
|
||||||
* back) PUIS DELETE des RIB retires. Les RIB crees d'abord : le back valide RG-1.13
|
* back) PUIS DELETE des RIB explicitement retires. Les RIB crees d'abord : le back
|
||||||
* (LCR => au moins un RIB persiste) sur le PATCH scalaires ; les suppressions en
|
* valide RG-1.13 (LCR => au moins un RIB persiste) sur le PATCH scalaires.
|
||||||
* dernier (le guard back n'autorise la suppression du dernier RIB qu'une fois quitte
|
*
|
||||||
* LCR). Aucun champ main/information dans le payload (mode strict RG-1.28 : sinon
|
* ERP-121 : les RIB ne sont (re)soumis QUE sous LCR — hors-LCR ce sont des
|
||||||
* 403 sur tout le payload).
|
* coordonnees dormantes conservees telles quelles, masquees a l'ecran et jamais
|
||||||
|
* re-ecrites. `removedRibIds` ne contient plus que les suppressions EXPLICITES
|
||||||
|
* (corbeille d'un bloc, toujours sous LCR), plus l'auto-suppression au changement
|
||||||
|
* de type de reglement. Aucun champ main/information dans le payload (mode strict
|
||||||
|
* RG-1.28 : sinon 403 sur tout le payload).
|
||||||
*/
|
*/
|
||||||
async function submitAccounting(): Promise<void> {
|
async function submitAccounting(): Promise<void> {
|
||||||
if (accountingReadonly.value || tabSubmitting.value) return
|
if (accountingReadonly.value || tabSubmitting.value) return
|
||||||
tabSubmitting.value = true
|
tabSubmitting.value = true
|
||||||
accountingErrors.clearErrors()
|
accountingErrors.clearErrors()
|
||||||
try {
|
try {
|
||||||
// 1) POST/PATCH des RIB d'abord (erreurs inline par ligne, tous les blocs
|
// 1) POST/PATCH des RIB d'abord — UNIQUEMENT sous LCR (erreurs inline par
|
||||||
// tentes). Le back exige >=1 RIB persiste pour valider une LCR a l'etape 2.
|
// ligne, tous les blocs tentes). Le back exige >=1 RIB persiste pour valider
|
||||||
// Seuls les blocs RIB TOTALEMENT vides sont ignores : un RIB partiel (ex.
|
// une LCR a l'etape 2. Hors-LCR (ERP-121), les RIB sont des coordonnees
|
||||||
// IBAN seul) est soumis -> 422 NotBlank (label / bic / iban) inline.
|
// dormantes : rien d'editable n'est affiche, on ne les re-soumet pas.
|
||||||
const ribHasError = await submitRows(
|
// On ne saute une amorce neuve vide QUE s'il reste un autre RIB soumettable :
|
||||||
ribs.value,
|
// sinon (ex. l'unique RIB existant supprime, remplace par un bloc vide), on la
|
||||||
ribErrors,
|
// soumet pour declencher la 422 NotBlank inline plutot que de laisser le DELETE
|
||||||
async (rib) => {
|
// echouer en « dernier RIB d'une LCR » (message plat sans propertyPath).
|
||||||
const body = buildRibPayload(rib)
|
if (isRibRequired.value) {
|
||||||
if (rib.id === null) {
|
const hasSubmittableRib = ribs.value.some(r => r.id !== null || !isRibBlank(r))
|
||||||
const created = await api.post<{ id: number }>(
|
const ribHasError = await submitRows(
|
||||||
`/clients/${clientId}/ribs`,
|
ribs.value,
|
||||||
body,
|
ribErrors,
|
||||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
async (rib) => {
|
||||||
)
|
// Edition d'un RIB existant : champ requis vide envoye en `''` (NotBlank
|
||||||
rib.id = created.id
|
// 422) au lieu d'etre omis (sinon le PATCH garderait l'ancienne valeur).
|
||||||
}
|
const body = buildRibPayload(rib, { forUpdate: rib.id !== null })
|
||||||
else {
|
if (rib.id === null) {
|
||||||
await api.patch(`/client_ribs/${rib.id}`, body, { toast: false })
|
const created = await api.post<{ id: number }>(
|
||||||
}
|
`/clients/${clientId}/ribs`,
|
||||||
},
|
body,
|
||||||
error => showError(error),
|
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||||
// On ne saute QUE les amorces neuves (id null) totalement vides. Un
|
)
|
||||||
// RIB existant vide est soumis -> 422 NotBlank inline (sinon la modif
|
rib.id = created.id
|
||||||
// serait perdue en silence avec un faux toast de succes).
|
}
|
||||||
rib => rib.id === null && isRibBlank(rib),
|
else {
|
||||||
)
|
await api.patch(`/client_ribs/${rib.id}`, body, { toast: false })
|
||||||
if (ribHasError) return
|
}
|
||||||
|
},
|
||||||
|
error => showError(error),
|
||||||
|
// On ne saute une amorce neuve (id null) totalement vide que si un autre RIB
|
||||||
|
// est soumettable. Un RIB existant vide est toujours soumis -> 422 NotBlank
|
||||||
|
// inline (sinon la modif serait perdue en silence avec un faux toast succes).
|
||||||
|
rib => hasSubmittableRib && rib.id === null && isRibBlank(rib),
|
||||||
|
)
|
||||||
|
if (ribHasError) return
|
||||||
|
}
|
||||||
|
|
||||||
// 2) PATCH des scalaires comptables (erreurs inline sur leurs champs).
|
// 2) PATCH des scalaires comptables (erreurs inline sur leurs champs).
|
||||||
try {
|
try {
|
||||||
@@ -986,8 +1012,9 @@ async function submitAccounting(): Promise<void> {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3) DELETE des RIB retires : APRES le PATCH scalaires (si on quitte LCR, le
|
// 3) DELETE des RIB explicitement retires (corbeille d'un bloc) : APRES le
|
||||||
// guard back n'autorise la suppression du dernier RIB qu'une fois le type change).
|
// PATCH scalaires (le guard back refuse la suppression du dernier RIB d'une
|
||||||
|
// LCR). ERP-121 : plus aucune suppression automatique au passage hors-LCR.
|
||||||
for (const id of removedRibIds.value) {
|
for (const id of removedRibIds.value) {
|
||||||
await api.delete(`/client_ribs/${id}`, {}, { toast: false })
|
await api.delete(`/client_ribs/${id}`, {}, { toast: false })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -280,7 +280,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, ref } from 'vue'
|
import { computed, onMounted, ref } from 'vue'
|
||||||
import { useClient } from '~/modules/commercial/composables/useClient'
|
import { useClient } from '~/modules/commercial/composables/useClient'
|
||||||
import { buildClientFormTabKeys } from '~/modules/commercial/utils/clientFormRules'
|
import { buildClientFormTabKeys, isRibRequiredForPaymentType } from '~/modules/commercial/utils/clientFormRules'
|
||||||
import { readHistoryTab } from '~/shared/utils/historyTab'
|
import { readHistoryTab } from '~/shared/utils/historyTab'
|
||||||
import {
|
import {
|
||||||
canEditClient,
|
canEditClient,
|
||||||
@@ -290,6 +290,7 @@ import {
|
|||||||
mapAddressView,
|
mapAddressView,
|
||||||
mapContactToDraft,
|
mapContactToDraft,
|
||||||
mapRibToDraft,
|
mapRibToDraft,
|
||||||
|
paymentTypeCodeOf,
|
||||||
referentialOptionOf,
|
referentialOptionOf,
|
||||||
relationOf,
|
relationOf,
|
||||||
showArchiveAction,
|
showArchiveAction,
|
||||||
@@ -355,9 +356,16 @@ const addressViews = computed(() => {
|
|||||||
return views.length ? views : [{ draft: emptyAddress(), siteOptions: [], categoryOptions: [] }]
|
return views.length ? views : [{ draft: emptyAddress(), siteOptions: [], categoryOptions: [] }]
|
||||||
})
|
})
|
||||||
// Exception au placeholder ci-dessus : on n'affiche AUCUN bloc RIB quand le
|
// Exception au placeholder ci-dessus : on n'affiche AUCUN bloc RIB quand le
|
||||||
// client n'en a pas (un RIB n'existe que pour un reglement LCR — RG-1.13). Pas
|
// client n'en a pas. Pas de bloc vierge fantome en consultation.
|
||||||
// de bloc vierge fantome en consultation.
|
// ERP-121 : un client peut desormais conserver des RIB « dormants » apres etre
|
||||||
const ribs = computed(() => (client.value?.ribs ?? []).map(mapRibToDraft))
|
// repasse hors-LCR (on ne les supprime plus). En consultation, decision metier =
|
||||||
|
// on les masque TOTALEMENT : on n'affiche les RIB que si le type de reglement
|
||||||
|
// courant est LCR (le `code` est embarque sous client:read:accounting).
|
||||||
|
const ribs = computed(() =>
|
||||||
|
isRibRequiredForPaymentType(paymentTypeCodeOf(client.value?.paymentType))
|
||||||
|
? (client.value?.ribs ?? []).map(mapRibToDraft)
|
||||||
|
: [],
|
||||||
|
)
|
||||||
// Draft comptable (tout null si l'utilisateur n'a pas accounting.view).
|
// Draft comptable (tout null si l'utilisateur n'a pas accounting.view).
|
||||||
const accounting = computed(() => mapAccountingDraft(client.value ?? ({} as ClientDetail)))
|
const accounting = computed(() => mapAccountingDraft(client.value ?? ({} as ClientDetail)))
|
||||||
|
|
||||||
@@ -384,10 +392,18 @@ const relationOptions = computed<SelectOption[]>(() => [
|
|||||||
{ value: 'courtier', label: t('commercial.clients.form.main.relationBroker') },
|
{ value: 'courtier', label: t('commercial.clients.form.main.relationBroker') },
|
||||||
])
|
])
|
||||||
|
|
||||||
const countryOptions: SelectOption[] = [
|
// Pays (ERP-116) : options construites depuis l'EMBED des adresses (jamais via
|
||||||
{ value: 'France', label: 'France' },
|
// GET /countries, sur le meme principe que les autres selects de consultation
|
||||||
{ value: 'Espagne', label: 'Espagne' },
|
// — en 403 pour les roles metier non-admin). Valeur = nom du pays stocke tel
|
||||||
]
|
// quel dans l'adresse, donc value === label ; suffit a afficher le libelle en
|
||||||
|
// lecture seule.
|
||||||
|
const countryOptions = computed<SelectOption[]>(() =>
|
||||||
|
[...new Set(
|
||||||
|
(client.value?.addresses ?? [])
|
||||||
|
.map(a => a.country)
|
||||||
|
.filter((c): c is string => !!c),
|
||||||
|
)].map(c => ({ value: c, label: c })),
|
||||||
|
)
|
||||||
|
|
||||||
// Selects comptables : libelle issu de l'embed (option unique ou vide).
|
// Selects comptables : libelle issu de l'embed (option unique ou vide).
|
||||||
const tvaModeOptions = computed(() => referentialOptionOf(client.value?.tvaMode))
|
const tvaModeOptions = computed(() => referentialOptionOf(client.value?.tvaMode))
|
||||||
|
|||||||
@@ -302,7 +302,7 @@
|
|||||||
>
|
>
|
||||||
<!-- ariaLabel via v-bind objet (prop camelCase ; aria-* serait un attribut HTML). -->
|
<!-- ariaLabel via v-bind objet (prop camelCase ; aria-* serait un attribut HTML). -->
|
||||||
<MalioButtonIcon
|
<MalioButtonIcon
|
||||||
v-if="!accountingReadonly"
|
v-if="!accountingReadonly && visibleRibs.length > 1"
|
||||||
icon="mdi:delete-outline"
|
icon="mdi:delete-outline"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
button-class="absolute top-3 right-3"
|
button-class="absolute top-3 right-3"
|
||||||
@@ -778,11 +778,17 @@ const contactOptions = computed<RefOption[]>(() =>
|
|||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
|
|
||||||
// Pays disponibles (France preselectionnee par defaut sur chaque adresse).
|
// Pays disponibles : referentiel `country` charge via l'API (ERP-116), en
|
||||||
const countryOptions: RefOption[] = [
|
// remplacement de l'ancienne liste codee en dur. France reste preselectionnee
|
||||||
{ value: 'France', label: 'France' },
|
// par defaut sur chaque adresse (cf. valeur initiale du draft d'adresse) : on
|
||||||
{ value: 'Espagne', label: 'Espagne' },
|
// garantit donc sa presence en fallback si `/countries` echoue (resilience
|
||||||
]
|
// ERP-102), pour ne pas afficher un select vide sur une valeur deja soumise.
|
||||||
|
const countryOptions = computed<RefOption[]>(() => {
|
||||||
|
const list = referentials.countries.value
|
||||||
|
return list.some(c => c.value === 'France')
|
||||||
|
? list
|
||||||
|
: [{ value: 'France', label: 'France' }, ...list]
|
||||||
|
})
|
||||||
|
|
||||||
// « + Adresse » desactive tant que la derniere adresse n'est pas valide.
|
// « + Adresse » desactive tant que la derniere adresse n'est pas valide.
|
||||||
const canAddAddress = computed(() => {
|
const canAddAddress = computed(() => {
|
||||||
@@ -875,13 +881,14 @@ function onPaymentTypeChange(value: string | number | null): void {
|
|||||||
accounting.paymentTypeIri = value === null ? null : String(value)
|
accounting.paymentTypeIri = value === null ? null : String(value)
|
||||||
// La banque n'a de sens que pour un virement : on la vide sinon (RG-1.12).
|
// La banque n'a de sens que pour un virement : on la vide sinon (RG-1.12).
|
||||||
if (!isBankRequired.value) accounting.bankIri = null
|
if (!isBankRequired.value) accounting.bankIri = null
|
||||||
// Les RIB n'ont de sens que pour une LCR (RG-1.13) : on amorce un bloc vide
|
// ERP-121 : on ne jette plus la saisie RIB au passage hors-LCR. Les blocs sont
|
||||||
// quand LCR est choisi, on vide la liste sinon (pas de RIB fantome soumis).
|
// masques (visibleRibs = []) mais conserves, et reapparaissent si l'on repasse
|
||||||
|
// en LCR. Ils ne sont persistes qu'a la validation SOUS LCR (cf. submitAccounting),
|
||||||
|
// donc une saisie abandonnee hors-LCR ne cree aucun RIB orphelin.
|
||||||
if (isRibRequired.value) {
|
if (isRibRequired.value) {
|
||||||
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
ribs.value = []
|
|
||||||
ribErrors.value = []
|
ribErrors.value = []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -918,35 +925,41 @@ async function submitAccounting(): Promise<void> {
|
|||||||
tabSubmitting.value = true
|
tabSubmitting.value = true
|
||||||
accountingErrors.clearErrors()
|
accountingErrors.clearErrors()
|
||||||
try {
|
try {
|
||||||
// 1) POST/PATCH des RIB d'abord (erreurs inline par ligne, tous les blocs
|
// 1) POST/PATCH des RIB d'abord — UNIQUEMENT sous LCR (erreurs inline par
|
||||||
// tentes). Le back exige >=1 RIB persiste pour valider une LCR a l'etape 2.
|
// ligne, tous les blocs tentes). Le back exige >=1 RIB persiste pour valider
|
||||||
// Seuls les blocs RIB TOTALEMENT vides sont ignores : un RIB partiel (ex.
|
// une LCR a l'etape 2. Hors-LCR (ERP-121), une saisie RIB eventuellement
|
||||||
// IBAN seul) est soumis -> 422 NotBlank (label / bic / iban) inline.
|
// restee dans le brouillon est masquee et n'est PAS persistee (pas de RIB
|
||||||
const ribHasError = await submitRows(
|
// orphelin sur un client en virement).
|
||||||
ribs.value,
|
// On ne saute une amorce neuve vide QUE s'il reste un autre RIB soumettable :
|
||||||
ribErrors,
|
// sinon (LCR sans aucun RIB rempli) on la soumet -> 422 NotBlank inline.
|
||||||
async (rib) => {
|
if (isRibRequired.value) {
|
||||||
// Payload partage avec l'edition (buildRibPayload, ERP-119).
|
const hasSubmittableRib = ribs.value.some(r => r.id !== null || !isRibBlank(r))
|
||||||
const body = buildRibPayload(rib)
|
const ribHasError = await submitRows(
|
||||||
if (rib.id === null) {
|
ribs.value,
|
||||||
const created = await api.post<{ id: number }>(
|
ribErrors,
|
||||||
`/clients/${clientId.value}/ribs`,
|
async (rib) => {
|
||||||
body,
|
// Payload partage avec l'edition (buildRibPayload, ERP-119).
|
||||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
const body = buildRibPayload(rib)
|
||||||
)
|
if (rib.id === null) {
|
||||||
rib.id = created.id
|
const created = await api.post<{ id: number }>(
|
||||||
}
|
`/clients/${clientId.value}/ribs`,
|
||||||
else {
|
body,
|
||||||
await api.patch(`/client_ribs/${rib.id}`, body, { toast: false })
|
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||||
}
|
)
|
||||||
},
|
rib.id = created.id
|
||||||
error => toast.error({ title: t('commercial.clients.toast.error'), message: apiErrorMessage(error) }),
|
}
|
||||||
// On ne saute QUE les amorces neuves (id null) totalement vides. Un
|
else {
|
||||||
// RIB existant vide est soumis -> 422 NotBlank inline (sinon la modif
|
await api.patch(`/client_ribs/${rib.id}`, body, { toast: false })
|
||||||
// serait perdue en silence avec un faux toast de succes).
|
}
|
||||||
rib => rib.id === null && isRibBlank(rib),
|
},
|
||||||
)
|
error => toast.error({ title: t('commercial.clients.toast.error'), message: apiErrorMessage(error) }),
|
||||||
if (ribHasError) return
|
// On ne saute une amorce neuve (id null) totalement vide que si un autre RIB
|
||||||
|
// est soumettable. Un RIB existant vide est toujours soumis -> 422 NotBlank
|
||||||
|
// inline (sinon la modif serait perdue en silence avec un faux toast succes).
|
||||||
|
rib => hasSubmittableRib && rib.id === null && isRibBlank(rib),
|
||||||
|
)
|
||||||
|
if (ribHasError) return
|
||||||
|
}
|
||||||
|
|
||||||
// 2) PATCH des scalaires comptables (erreurs inline sur leurs champs).
|
// 2) PATCH des scalaires comptables (erreurs inline sur leurs champs).
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -0,0 +1,945 @@
|
|||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<!-- En-tete : retour consultation + nom du fournisseur. -->
|
||||||
|
<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.edit.back') }"
|
||||||
|
@click="goBack"
|
||||||
|
/>
|
||||||
|
<h1 class="text-[30px] font-semibold text-m-primary">{{ headerTitle }}</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Etats de chargement / introuvable. -->
|
||||||
|
<p v-if="loading" class="mt-12 text-center text-black/60">{{ t('commercial.suppliers.edit.loading') }}</p>
|
||||||
|
<p v-else-if="error" class="mt-12 text-center text-m-danger">{{ t('commercial.suppliers.edit.notFound') }}</p>
|
||||||
|
|
||||||
|
<template v-else-if="supplier">
|
||||||
|
<!-- ── Bloc principal (pre-rempli, editable si `manage`) ──────────────
|
||||||
|
Conserve en modification (miroir client) ; edite via son propre
|
||||||
|
PATCH scope sur le groupe supplier:write:main. Readonly pour les
|
||||||
|
roles sans `manage` (ex. Compta). Pas de contact inline (ERP-106). -->
|
||||||
|
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
|
||||||
|
<MalioInputText
|
||||||
|
v-model="main.companyName"
|
||||||
|
:label="t('commercial.suppliers.form.main.companyName')"
|
||||||
|
:required="true"
|
||||||
|
:readonly="businessReadonly"
|
||||||
|
:error="mainErrors.errors.companyName"
|
||||||
|
/>
|
||||||
|
<MalioSelectCheckbox
|
||||||
|
:model-value="main.categoryIris"
|
||||||
|
:options="mainCategoryOptions"
|
||||||
|
:label="t('commercial.suppliers.form.main.categories')"
|
||||||
|
:display-tag="true"
|
||||||
|
:readonly="businessReadonly"
|
||||||
|
:required="true"
|
||||||
|
:error="mainErrors.errors.categories"
|
||||||
|
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="!businessReadonly" class="mt-12 flex justify-center">
|
||||||
|
<MalioButton
|
||||||
|
variant="primary"
|
||||||
|
:label="t('commercial.suppliers.edit.save')"
|
||||||
|
:disabled="mainSubmitting"
|
||||||
|
@click="submitMain"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ── Onglets : navigation LIBRE, edition independante par onglet ──── -->
|
||||||
|
<MalioTabList v-model="activeTab" :tabs="tabs" :max-visible-tabs="5" :max-width="1100" class="mt-[60px]">
|
||||||
|
<!-- Onglet Information -->
|
||||||
|
<template #information>
|
||||||
|
<div class="mt-12 grid grid-cols-4 gap-x-[44px] gap-y-4 bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
|
||||||
|
<!-- pt-1/pb-1 alignent le textarea (h-full) sur les inputs. -->
|
||||||
|
<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="businessReadonly"
|
||||||
|
:error="informationErrors.errors.description"
|
||||||
|
/>
|
||||||
|
<MalioInputText
|
||||||
|
v-model="information.competitors"
|
||||||
|
:label="t('commercial.suppliers.form.information.competitors')"
|
||||||
|
:readonly="businessReadonly"
|
||||||
|
:error="informationErrors.errors.competitors"
|
||||||
|
/>
|
||||||
|
<MalioDate
|
||||||
|
v-model="information.foundedAt"
|
||||||
|
:label="t('commercial.suppliers.form.information.foundedAt')"
|
||||||
|
:readonly="businessReadonly"
|
||||||
|
:editable="true"
|
||||||
|
:error="informationErrors.errors.foundedAt"
|
||||||
|
/>
|
||||||
|
<MalioInputText
|
||||||
|
v-model="information.employeesCount"
|
||||||
|
:label="t('commercial.suppliers.form.information.employeesCount')"
|
||||||
|
:mask="EMPLOYEES_MASK"
|
||||||
|
:readonly="businessReadonly"
|
||||||
|
:error="informationErrors.errors.employeesCount"
|
||||||
|
/>
|
||||||
|
<MalioInputAmount
|
||||||
|
v-model="information.revenueAmount"
|
||||||
|
:label="t('commercial.suppliers.form.information.revenueAmount')"
|
||||||
|
:readonly="businessReadonly"
|
||||||
|
:error="informationErrors.errors.revenueAmount"
|
||||||
|
/>
|
||||||
|
<MalioInputText
|
||||||
|
v-model="information.directorName"
|
||||||
|
:label="t('commercial.suppliers.form.information.directorName')"
|
||||||
|
:readonly="businessReadonly"
|
||||||
|
:error="informationErrors.errors.directorName"
|
||||||
|
/>
|
||||||
|
<MalioInputAmount
|
||||||
|
v-model="information.profitAmount"
|
||||||
|
:label="t('commercial.suppliers.form.information.profitAmount')"
|
||||||
|
:readonly="businessReadonly"
|
||||||
|
:error="informationErrors.errors.profitAmount"
|
||||||
|
/>
|
||||||
|
<!-- Volume previsionnel : specifique fournisseur (entier). -->
|
||||||
|
<MalioInputText
|
||||||
|
v-model="information.volumeForecast"
|
||||||
|
:label="t('commercial.suppliers.form.information.volumeForecast')"
|
||||||
|
:mask="VOLUME_FORECAST_MASK"
|
||||||
|
:readonly="businessReadonly"
|
||||||
|
:error="informationErrors.errors.volumeForecast"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div v-if="!businessReadonly" class="mt-12 flex justify-center">
|
||||||
|
<MalioButton
|
||||||
|
variant="primary"
|
||||||
|
:label="t('commercial.suppliers.edit.save')"
|
||||||
|
:disabled="tabSubmitting"
|
||||||
|
@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="contact.id ?? `new-${index}`"
|
||||||
|
:model-value="contact"
|
||||||
|
:title="t('commercial.suppliers.form.contact.title', { n: index + 1 })"
|
||||||
|
:removable="contacts.length > 1"
|
||||||
|
:readonly="businessReadonly"
|
||||||
|
:errors="contactErrors[index]"
|
||||||
|
@update:model-value="(v) => contacts[index] = v"
|
||||||
|
@remove="askRemoveContact(index)"
|
||||||
|
/>
|
||||||
|
<div v-if="!businessReadonly" 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.edit.save')"
|
||||||
|
: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="address.id ?? `new-${index}`"
|
||||||
|
:model-value="address"
|
||||||
|
:title="t('commercial.suppliers.form.address.title', { n: index + 1 })"
|
||||||
|
:category-options="mainCategoryOptions"
|
||||||
|
:site-options="siteOptions"
|
||||||
|
:contact-options="contactOptions"
|
||||||
|
:country-options="countryOptions"
|
||||||
|
:removable="addresses.length > 1"
|
||||||
|
:readonly="businessReadonly"
|
||||||
|
:errors="addressErrors[index]"
|
||||||
|
@update:model-value="(v) => addresses[index] = v"
|
||||||
|
@remove="askRemoveAddress(index)"
|
||||||
|
@degraded="onAddressDegraded"
|
||||||
|
/>
|
||||||
|
<div v-if="!businessReadonly" 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.edit.save')"
|
||||||
|
:disabled="tabSubmitting"
|
||||||
|
@click="submitAddresses"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Onglet Comptabilite (present uniquement si accounting.view ;
|
||||||
|
editable uniquement si accounting.manage). -->
|
||||||
|
<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="tvaModeOptions"
|
||||||
|
: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="paymentDelayOptions"
|
||||||
|
: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="paymentTypeOptions"
|
||||||
|
: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="bankOptions"
|
||||||
|
: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="rib.id ?? `new-${index}`"
|
||||||
|
class="relative bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]"
|
||||||
|
>
|
||||||
|
<MalioButtonIcon
|
||||||
|
v-if="!accountingReadonly && visibleRibs.length > 1"
|
||||||
|
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.edit.save')"
|
||||||
|
:disabled="tabSubmitting"
|
||||||
|
@click="submitAccounting"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Onglets non encore implementes : frame vide (navigation libre). -->
|
||||||
|
<template #transport><ComingSoonPlaceholder /></template>
|
||||||
|
<template #statistics><ComingSoonPlaceholder /></template>
|
||||||
|
<template #reports><ComingSoonPlaceholder /></template>
|
||||||
|
<template #exchanges><ComingSoonPlaceholder /></template>
|
||||||
|
</MalioTabList>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- 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 } from 'vue'
|
||||||
|
import { useSupplier } from '~/modules/commercial/composables/useSupplier'
|
||||||
|
import { useSupplierReferentials, type CategoryOption, type RefOption } from '~/modules/commercial/composables/useSupplierReferentials'
|
||||||
|
import { useSupplierFormErrors } from '~/modules/commercial/composables/useSupplierFormErrors'
|
||||||
|
import {
|
||||||
|
canEditSupplier,
|
||||||
|
categoryOptionsOf,
|
||||||
|
referentialOptionOf,
|
||||||
|
siteOptionsOf,
|
||||||
|
mapContactToDraft,
|
||||||
|
mapAddressToDraft,
|
||||||
|
mapRibToDraft,
|
||||||
|
type SupplierDetail,
|
||||||
|
} from '~/modules/commercial/utils/supplierConsultation'
|
||||||
|
import {
|
||||||
|
buildAccountingPayload,
|
||||||
|
buildAddressPayload,
|
||||||
|
buildContactPayload,
|
||||||
|
buildInformationPayload,
|
||||||
|
buildMainPayload,
|
||||||
|
buildRibPayload,
|
||||||
|
mapAccountingFormDraft,
|
||||||
|
mapInformationDraft,
|
||||||
|
mapMainDraft,
|
||||||
|
resolveTabEditability,
|
||||||
|
type AccountingFormDraft,
|
||||||
|
type InformationFormDraft,
|
||||||
|
type MainFormDraft,
|
||||||
|
type SupplierEditAbilities,
|
||||||
|
} from '~/modules/commercial/utils/supplierEdit'
|
||||||
|
import {
|
||||||
|
buildSupplierFormTabKeys,
|
||||||
|
isAddressValid,
|
||||||
|
isBankRequiredForPaymentType,
|
||||||
|
isContactBlank,
|
||||||
|
isContactNamed,
|
||||||
|
isRibBlank,
|
||||||
|
isRibComplete,
|
||||||
|
isRibRequiredForPaymentType,
|
||||||
|
} from '~/modules/commercial/utils/supplierFormRules'
|
||||||
|
import {
|
||||||
|
emptyAddress,
|
||||||
|
emptyContact,
|
||||||
|
emptyRib,
|
||||||
|
type SupplierAddressFormDraft,
|
||||||
|
type SupplierContactFormDraft,
|
||||||
|
type SupplierRibFormDraft,
|
||||||
|
} from '~/modules/commercial/types/supplierForm'
|
||||||
|
import { extractApiErrorMessage } from '~/shared/utils/api'
|
||||||
|
import { readHistoryTab } from '~/shared/utils/historyTab'
|
||||||
|
|
||||||
|
// Masques de saisie (la normalisation finale reste serveur).
|
||||||
|
const SIREN_MASK = '#########'
|
||||||
|
const EMPLOYEES_MASK = '#######'
|
||||||
|
// Volume previsionnel : champ texte borne aux chiffres (entier >= 0 cote back).
|
||||||
|
const VOLUME_FORECAST_MASK = '##########'
|
||||||
|
|
||||||
|
const { t } = useI18n()
|
||||||
|
const api = useApi()
|
||||||
|
const toast = useToast()
|
||||||
|
const route = useRoute()
|
||||||
|
const router = useRouter()
|
||||||
|
const { can, canAny } = usePermissions()
|
||||||
|
|
||||||
|
// Gating de la route : l'edition exige de pouvoir editer au moins un onglet
|
||||||
|
// (`manage` OU `accounting.manage`). Usine et roles en lecture seule sont
|
||||||
|
// rediriges vers le repertoire (lui-meme protege).
|
||||||
|
if (!canEditSupplier(canAny)) {
|
||||||
|
await navigateTo('/suppliers')
|
||||||
|
}
|
||||||
|
|
||||||
|
const supplierId = route.params.id as string
|
||||||
|
|
||||||
|
const { supplier, loading, error, load } = useSupplier(supplierId)
|
||||||
|
const referentials = useSupplierReferentials()
|
||||||
|
|
||||||
|
// ── Permissions / editabilite par zone (option 1 ERP-74) ────────────────────
|
||||||
|
const abilities = computed<SupplierEditAbilities>(() => ({
|
||||||
|
canManage: can('commercial.suppliers.manage'),
|
||||||
|
canAccountingView: can('commercial.suppliers.accounting.view'),
|
||||||
|
canAccountingManage: can('commercial.suppliers.accounting.manage'),
|
||||||
|
}))
|
||||||
|
const editability = computed(() => resolveTabEditability(abilities.value))
|
||||||
|
// Bloc principal + onglets Information / Contacts / Adresses.
|
||||||
|
const businessReadonly = computed(() => !editability.value.businessEditable)
|
||||||
|
const canAccountingView = computed(() => editability.value.accountingVisible)
|
||||||
|
const accountingReadonly = computed(() => !editability.value.accountingEditable)
|
||||||
|
|
||||||
|
const headerTitle = computed(() => supplier.value?.companyName ?? t('commercial.suppliers.edit.title'))
|
||||||
|
|
||||||
|
// ── Brouillons editables (pre-remplis depuis le detail) ─────────────────────
|
||||||
|
const main = reactive<MainFormDraft>(mapMainDraft({} as SupplierDetail))
|
||||||
|
const information = reactive<InformationFormDraft>(mapInformationDraft({} as SupplierDetail))
|
||||||
|
const accounting = reactive<AccountingFormDraft>(mapAccountingFormDraft({} as SupplierDetail))
|
||||||
|
const contacts = ref<SupplierContactFormDraft[]>([])
|
||||||
|
const addresses = ref<SupplierAddressFormDraft[]>([])
|
||||||
|
const ribs = ref<SupplierRibFormDraft[]>([])
|
||||||
|
|
||||||
|
// Ids des sous-ressources existantes supprimees (DELETE differe au « Valider »).
|
||||||
|
const removedContactIds = ref<number[]>([])
|
||||||
|
const removedAddressIds = ref<number[]>([])
|
||||||
|
const removedRibIds = ref<number[]>([])
|
||||||
|
|
||||||
|
const mainSubmitting = ref(false)
|
||||||
|
const tabSubmitting = ref(false)
|
||||||
|
const addressDegradedNotified = ref(false)
|
||||||
|
|
||||||
|
/** Recopie le detail charge dans les brouillons editables. */
|
||||||
|
function hydrate(detail: SupplierDetail): void {
|
||||||
|
Object.assign(main, mapMainDraft(detail))
|
||||||
|
Object.assign(information, mapInformationDraft(detail))
|
||||||
|
Object.assign(accounting, mapAccountingFormDraft(detail))
|
||||||
|
contacts.value = (detail.contacts ?? []).map(mapContactToDraft)
|
||||||
|
addresses.value = (detail.addresses ?? []).map(mapAddressToDraft)
|
||||||
|
ribs.value = (detail.ribs ?? []).map(mapRibToDraft)
|
||||||
|
// Chaque bloc reste visible meme vide : si une collection est vide, on amorce
|
||||||
|
// un bloc vierge (non persiste tant qu'incomplet — cf. submit*/canAdd*).
|
||||||
|
if (contacts.value.length === 0) contacts.value.push(emptyContact())
|
||||||
|
if (addresses.value.length === 0) addresses.value.push(emptyAddress())
|
||||||
|
// RIB : amorce un bloc vide seulement si le type de reglement est une LCR
|
||||||
|
// (sinon la section reste masquee — RG-2.08).
|
||||||
|
if (isRibRequired.value && ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Options de selects (referentiels UNION valeurs courantes de l'embed) ─────
|
||||||
|
// L'union garantit que les valeurs deja posees s'affichent meme quand le
|
||||||
|
// referentiel complet n'est pas chargeable (roles metier sans
|
||||||
|
// catalog.categories.view / sites.view → 403, cf. matrice § 2.7).
|
||||||
|
function mergeOptions<T extends { value: string }>(primary: T[], extra: T[]): T[] {
|
||||||
|
const seen = new Set(primary.map(o => o.value))
|
||||||
|
return [...primary, ...extra.filter(o => !seen.has(o.value))]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Categories issues de l'embed (fournisseur + adresses), role-independantes.
|
||||||
|
const embedCategoryOptions = computed<CategoryOption[]>(() => {
|
||||||
|
const fromSupplier = categoryOptionsOf(supplier.value?.categories)
|
||||||
|
const fromAddresses = (supplier.value?.addresses ?? []).flatMap(a => categoryOptionsOf(a.categories))
|
||||||
|
return mergeOptions(fromSupplier, fromAddresses)
|
||||||
|
})
|
||||||
|
// Toutes les categories de type FOURNISSEUR sont autorisees, sur le bloc principal
|
||||||
|
// comme sur une adresse (pas de restriction Distributeur/Courtier comme au M1 — RG-2.10).
|
||||||
|
const mainCategoryOptions = computed(() => mergeOptions(referentials.categories.value, embedCategoryOptions.value))
|
||||||
|
|
||||||
|
const embedSiteOptions = computed<RefOption[]>(() =>
|
||||||
|
mergeOptions([], (supplier.value?.addresses ?? []).flatMap(a => siteOptionsOf(a.sites))),
|
||||||
|
)
|
||||||
|
const siteOptions = computed(() => mergeOptions(referentials.sites.value, embedSiteOptions.value))
|
||||||
|
|
||||||
|
// Contacts deja persistes (iri non null), rattachables a une adresse (M2M).
|
||||||
|
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 : referentiel `country` charge via l'API (ERP-116), aligne sur l'ecran
|
||||||
|
// client. On merge la valeur deja stockee sur chaque adresse (embed) — comme les
|
||||||
|
// autres selects de cet ecran — pour ne pas vider le select si `/countries`
|
||||||
|
// echoue (resilience ERP-102) ou si un pays historique n'est plus au referentiel.
|
||||||
|
const embedCountryOptions = computed<RefOption[]>(() =>
|
||||||
|
mergeOptions([], (supplier.value?.addresses ?? [])
|
||||||
|
.map(a => a.country)
|
||||||
|
.filter((c): c is string => !!c)
|
||||||
|
.map(c => ({ value: c, label: c }))),
|
||||||
|
)
|
||||||
|
const countryOptions = computed<RefOption[]>(() =>
|
||||||
|
mergeOptions(referentials.countries.value, embedCountryOptions.value),
|
||||||
|
)
|
||||||
|
|
||||||
|
// Selects comptables : referentiel UNION valeur courante de l'embed (libelle).
|
||||||
|
const tvaModeOptions = computed(() => mergeOptions(referentials.tvaModes.value, referentialOptionOf(supplier.value?.tvaMode)))
|
||||||
|
const paymentDelayOptions = computed(() => mergeOptions(referentials.paymentDelays.value, referentialOptionOf(supplier.value?.paymentDelay)))
|
||||||
|
const paymentTypeOptions = computed(() => mergeOptions(
|
||||||
|
referentials.paymentTypes.value.map(p => ({ value: p.value, label: p.label })),
|
||||||
|
referentialOptionOf(supplier.value?.paymentType),
|
||||||
|
))
|
||||||
|
const bankOptions = computed(() => mergeOptions(referentials.banks.value, referentialOptionOf(supplier.value?.bank)))
|
||||||
|
|
||||||
|
// ── Onglets : navigation libre (3 actifs + Compta + 4 coquilles) ────────────
|
||||||
|
const tabKeys = computed(() => buildSupplierFormTabKeys(canAccountingView.value, { includeEditOnlyTabs: true }))
|
||||||
|
|
||||||
|
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',
|
||||||
|
statistics: 'mdi:finance',
|
||||||
|
reports: 'mdi:file-document-edit-outline',
|
||||||
|
exchanges: 'mdi:account-group-outline',
|
||||||
|
}
|
||||||
|
|
||||||
|
const tabs = computed(() => tabKeys.value.map(key => ({
|
||||||
|
key,
|
||||||
|
label: t(`commercial.suppliers.tab.${key}`),
|
||||||
|
icon: TAB_ICONS[key],
|
||||||
|
})))
|
||||||
|
|
||||||
|
// Onglet initial : repris de la consultation (history.state), sinon Information.
|
||||||
|
const activeTab = ref(readHistoryTab(tabKeys.value) ?? 'information')
|
||||||
|
|
||||||
|
// ── Navigation ──────────────────────────────────────────────────────────────
|
||||||
|
/** Retour consultation en conservant l'onglet courant (via history.state). */
|
||||||
|
function goBack(): void {
|
||||||
|
router.push({ path: `/suppliers/${supplierId}`, state: { tab: activeTab.value } })
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Message d'erreur a afficher : violation 422 / detail renvoye par le serveur,
|
||||||
|
* sinon un libelle generique. Le 409 d'unicite de nom (bloc principal) est
|
||||||
|
* traduit explicitement par l'appelant.
|
||||||
|
*/
|
||||||
|
function apiErrorMessage(e: unknown): string {
|
||||||
|
const data = (e as { data?: unknown })?.data
|
||||||
|
return extractApiErrorMessage(data) || t('commercial.suppliers.toast.error')
|
||||||
|
}
|
||||||
|
|
||||||
|
function showError(e: unknown): void {
|
||||||
|
toast.error({ title: t('commercial.suppliers.toast.error'), message: apiErrorMessage(e) })
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Erreurs de validation par champ (ERP-101) ───────────────────────────────
|
||||||
|
const {
|
||||||
|
mainErrors,
|
||||||
|
informationErrors,
|
||||||
|
accountingErrors,
|
||||||
|
contactErrors,
|
||||||
|
addressErrors,
|
||||||
|
ribErrors,
|
||||||
|
submitRows,
|
||||||
|
} = useSupplierFormErrors()
|
||||||
|
|
||||||
|
// ── Bloc principal ───────────────────────────────────────────────────────────
|
||||||
|
/** PATCH /suppliers/{id} — groupe supplier:write:main UNIQUEMENT (mode strict). */
|
||||||
|
async function submitMain(): Promise<void> {
|
||||||
|
if (businessReadonly.value || mainSubmitting.value) return
|
||||||
|
mainSubmitting.value = true
|
||||||
|
mainErrors.clearErrors()
|
||||||
|
try {
|
||||||
|
const updated = await api.patch<SupplierDetail>(`/suppliers/${supplierId}`, buildMainPayload(main, { forUpdate: true }), {
|
||||||
|
headers: { Accept: 'application/ld+json' },
|
||||||
|
toast: false,
|
||||||
|
})
|
||||||
|
// Reaffiche les valeurs normalisees renvoyees par le serveur (UPPERCASE, RG-2.12).
|
||||||
|
Object.assign(main, mapMainDraft(updated))
|
||||||
|
toast.success({ title: t('commercial.suppliers.toast.updateSuccess') })
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
// 409 = doublon nom de societe → erreur inline + toast ; 422 → mapping
|
||||||
|
// inline par champ ; autre → toast de fallback. Cf. ERP-101.
|
||||||
|
const status = (e 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(e, { fallbackMessage: t('commercial.suppliers.toast.error') })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
mainSubmitting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Onglet Information ───────────────────────────────────────────────────────
|
||||||
|
/** PATCH /suppliers/{id} — groupe supplier:write:information UNIQUEMENT. */
|
||||||
|
async function submitInformation(): Promise<void> {
|
||||||
|
if (businessReadonly.value || tabSubmitting.value) return
|
||||||
|
tabSubmitting.value = true
|
||||||
|
informationErrors.clearErrors()
|
||||||
|
try {
|
||||||
|
await api.patch(`/suppliers/${supplierId}`, buildInformationPayload(information), { toast: false })
|
||||||
|
toast.success({ title: t('commercial.suppliers.toast.updateSuccess') })
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
informationErrors.handleApiError(e, { fallbackMessage: t('commercial.suppliers.toast.error') })
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
tabSubmitting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Onglet Contacts ───────────────────────────────────────────────────────────
|
||||||
|
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'), () => {
|
||||||
|
const removed = contacts.value[index]
|
||||||
|
if (removed?.id != null) removedContactIds.value.push(removed.id)
|
||||||
|
contacts.value.splice(index, 1)
|
||||||
|
contactErrors.value.splice(index, 1)
|
||||||
|
// Garde au moins un bloc visible (cf. amorce a l'hydratation).
|
||||||
|
if (contacts.value.length === 0) contacts.value.push(emptyContact())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valide l'onglet Contacts : DELETE des contacts retires (existants), puis
|
||||||
|
* POST/PATCH des blocs restants sur la sous-ressource. Strictement scope a la
|
||||||
|
* collection contacts (endpoints supplier_contact dedies).
|
||||||
|
*/
|
||||||
|
async function submitContacts(): Promise<void> {
|
||||||
|
if (businessReadonly.value || tabSubmitting.value) return
|
||||||
|
tabSubmitting.value = true
|
||||||
|
contactErrors.value = []
|
||||||
|
try {
|
||||||
|
for (const id of removedContactIds.value) {
|
||||||
|
await api.delete(`/supplier_contacts/${id}`, {}, { toast: false })
|
||||||
|
}
|
||||||
|
removedContactIds.value = []
|
||||||
|
|
||||||
|
// RG-2.13 : au moins un contact requis. Si l'onglet ne contient QUE des
|
||||||
|
// amorces neuves vides, on les soumet -> 422 RG-2.04 inline (nom OU prenom).
|
||||||
|
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<{ '@id'?: string, id: number }>(
|
||||||
|
`/suppliers/${supplierId}/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 => showError(error),
|
||||||
|
contact => hasSubmittableContact && contact.id === null && isContactBlank(contact),
|
||||||
|
)
|
||||||
|
if (hasError) return
|
||||||
|
toast.success({ title: t('commercial.suppliers.toast.updateSuccess') })
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
showError(e)
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
tabSubmitting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Onglet Adresses ───────────────────────────────────────────────────────────
|
||||||
|
// « + 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'), () => {
|
||||||
|
const removed = addresses.value[index]
|
||||||
|
if (removed?.id != null) removedAddressIds.value.push(removed.id)
|
||||||
|
addresses.value.splice(index, 1)
|
||||||
|
addressErrors.value.splice(index, 1)
|
||||||
|
// Garde au moins un bloc visible (cf. amorce a l'hydratation).
|
||||||
|
if (addresses.value.length === 0) addresses.value.push(emptyAddress())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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'),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Valide l'onglet Adresses : DELETE des adresses retirees puis POST/PATCH. */
|
||||||
|
async function submitAddresses(): Promise<void> {
|
||||||
|
if (businessReadonly.value || tabSubmitting.value) return
|
||||||
|
tabSubmitting.value = true
|
||||||
|
addressErrors.value = []
|
||||||
|
try {
|
||||||
|
for (const id of removedAddressIds.value) {
|
||||||
|
await api.delete(`/supplier_addresses/${id}`, {}, { toast: false })
|
||||||
|
}
|
||||||
|
removedAddressIds.value = []
|
||||||
|
|
||||||
|
const hasError = await submitRows(
|
||||||
|
addresses.value,
|
||||||
|
addressErrors,
|
||||||
|
async (address) => {
|
||||||
|
// Edition d'une adresse existante : champ requis vide envoye en `''`
|
||||||
|
// (NotBlank 422) au lieu d'etre omis — sinon le PATCH garderait
|
||||||
|
// l'ancienne valeur (faux 200). Creation (id null) : omit classique.
|
||||||
|
const body = buildAddressPayload(address, { forUpdate: address.id !== null })
|
||||||
|
if (address.id === null) {
|
||||||
|
const created = await api.post<{ id: number }>(
|
||||||
|
`/suppliers/${supplierId}/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 => showError(error),
|
||||||
|
)
|
||||||
|
if (hasError) return
|
||||||
|
toast.success({ title: t('commercial.suppliers.toast.updateSuccess') })
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
showError(e)
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
tabSubmitting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Onglet Comptabilite ──────────────────────────────────────────────────────
|
||||||
|
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)
|
||||||
|
if (!isBankRequired.value) accounting.bankIri = null
|
||||||
|
// ERP-121 : un RIB est une coordonnee bancaire du fournisseur, decouplee du mode
|
||||||
|
// de reglement. Au passage hors-LCR on ne SUPPRIME plus les RIB existants : ils
|
||||||
|
// restent en base, simplement masques a l'ecran (visibleRibs = []), et
|
||||||
|
// reapparaissent tels quels si l'on repasse en LCR. Seule la corbeille d'un
|
||||||
|
// bloc (askRemoveRib) retire reellement un RIB.
|
||||||
|
if (isRibRequired.value) {
|
||||||
|
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// Hors-LCR : on nettoie seulement les erreurs inline (plus affichees).
|
||||||
|
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'), () => {
|
||||||
|
const removed = ribs.value[index]
|
||||||
|
if (removed?.id != null) removedRibIds.value.push(removed.id)
|
||||||
|
ribs.value.splice(index, 1)
|
||||||
|
ribErrors.value.splice(index, 1)
|
||||||
|
// Garde au moins un bloc RIB visible (cf. amorce a l'hydratation).
|
||||||
|
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valide l'onglet Comptabilite : POST/PATCH des RIB sur la sous-ressource PUIS
|
||||||
|
* PATCH des scalaires (groupe supplier:write:accounting, exige accounting.manage
|
||||||
|
* cote back) PUIS DELETE des RIB explicitement retires. Les RIB crees d'abord : le
|
||||||
|
* back valide RG-2.08 (LCR => au moins un RIB persiste) sur le PATCH scalaires.
|
||||||
|
*
|
||||||
|
* ERP-121 : les RIB ne sont (re)soumis QUE sous LCR — hors-LCR ce sont des
|
||||||
|
* coordonnees dormantes conservees telles quelles, masquees a l'ecran et jamais
|
||||||
|
* re-ecrites. `removedRibIds` ne contient plus que les suppressions EXPLICITES
|
||||||
|
* (corbeille d'un bloc, toujours sous LCR). Aucun champ main/information dans le
|
||||||
|
* payload (mode strict RG-2.16 : sinon 403 sur tout le payload).
|
||||||
|
*/
|
||||||
|
async function submitAccounting(): Promise<void> {
|
||||||
|
if (accountingReadonly.value || tabSubmitting.value) return
|
||||||
|
tabSubmitting.value = true
|
||||||
|
accountingErrors.clearErrors()
|
||||||
|
try {
|
||||||
|
// 1) POST/PATCH des RIB d'abord — UNIQUEMENT sous LCR (erreurs inline par
|
||||||
|
// ligne, tous les blocs tentes). Hors-LCR (ERP-121), les RIB sont des
|
||||||
|
// coordonnees dormantes : rien d'editable n'est affiche, on ne les re-soumet
|
||||||
|
// pas. On ne saute une amorce neuve vide QUE s'il reste un autre RIB
|
||||||
|
// soumettable : sinon (ex. l'unique RIB existant supprime, remplace par un
|
||||||
|
// bloc vide), on la soumet pour declencher la 422 NotBlank inline plutot que
|
||||||
|
// de laisser le DELETE echouer en « dernier RIB d'une LCR » (message plat).
|
||||||
|
if (isRibRequired.value) {
|
||||||
|
const hasSubmittableRib = ribs.value.some(r => r.id !== null || !isRibBlank(r))
|
||||||
|
const ribHasError = await submitRows(
|
||||||
|
ribs.value,
|
||||||
|
ribErrors,
|
||||||
|
async (rib) => {
|
||||||
|
// Edition d'un RIB existant : champ requis vide envoye en `''` (NotBlank
|
||||||
|
// 422) au lieu d'etre omis (sinon le PATCH garderait l'ancienne valeur).
|
||||||
|
const body = buildRibPayload(rib, { forUpdate: rib.id !== null })
|
||||||
|
if (rib.id === null) {
|
||||||
|
const created = await api.post<{ id: number }>(
|
||||||
|
`/suppliers/${supplierId}/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 => showError(error),
|
||||||
|
rib => hasSubmittableRib && rib.id === null && isRibBlank(rib),
|
||||||
|
)
|
||||||
|
if (ribHasError) return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) PATCH des scalaires comptables (erreurs inline sur leurs champs).
|
||||||
|
try {
|
||||||
|
await api.patch(`/suppliers/${supplierId}`, buildAccountingPayload(accounting, isBankRequired.value), { toast: false })
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
accountingErrors.handleApiError(error, { fallbackMessage: t('commercial.suppliers.toast.error') })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3) DELETE des RIB explicitement retires (corbeille d'un bloc) : APRES le
|
||||||
|
// PATCH scalaires (le guard back refuse la suppression du dernier RIB d'une
|
||||||
|
// LCR). ERP-121 : plus aucune suppression automatique au passage hors-LCR.
|
||||||
|
for (const id of removedRibIds.value) {
|
||||||
|
await api.delete(`/supplier_ribs/${id}`, {}, { toast: false })
|
||||||
|
}
|
||||||
|
removedRibIds.value = []
|
||||||
|
|
||||||
|
toast.success({ title: t('commercial.suppliers.toast.updateSuccess') })
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
showError(e)
|
||||||
|
}
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
useHead({ title: headerTitle })
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
// Referentiels en best-effort (echec non bloquant : l'embed alimente les
|
||||||
|
// libelles des valeurs courantes).
|
||||||
|
referentials.loadCommon().catch(() => {})
|
||||||
|
await load()
|
||||||
|
if (supplier.value) hydrate(supplier.value)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,468 @@
|
|||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<!-- En-tete : retour repertoire + nom du fournisseur + actions (Modifier / Archiver|Restaurer). -->
|
||||||
|
<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.consultation.back') }"
|
||||||
|
@click="goBack"
|
||||||
|
/>
|
||||||
|
<h1 class="text-[30px] font-semibold text-m-primary">{{ headerTitle }}</h1>
|
||||||
|
|
||||||
|
<!-- gap-12 = 48px : meme espacement que Ajouter / Filtres du repertoire. -->
|
||||||
|
<div class="ml-auto flex items-center gap-12">
|
||||||
|
<MalioButton
|
||||||
|
v-if="canEdit"
|
||||||
|
variant="secondary"
|
||||||
|
icon-name="mdi:pencil-outline"
|
||||||
|
icon-position="left"
|
||||||
|
:label="t('commercial.suppliers.action.edit')"
|
||||||
|
@click="goEdit"
|
||||||
|
/>
|
||||||
|
<MalioButton
|
||||||
|
v-if="showArchive"
|
||||||
|
variant="secondary"
|
||||||
|
icon-name="mdi:archive-arrow-down-outline"
|
||||||
|
icon-position="left"
|
||||||
|
:label="t('commercial.suppliers.action.archive')"
|
||||||
|
@click="askToggleArchive"
|
||||||
|
/>
|
||||||
|
<MalioButton
|
||||||
|
v-if="showRestore"
|
||||||
|
variant="secondary"
|
||||||
|
icon-name="mdi:archive-arrow-up-outline"
|
||||||
|
icon-position="left"
|
||||||
|
:label="t('commercial.suppliers.action.restore')"
|
||||||
|
@click="askToggleArchive"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Etats de chargement / introuvable. -->
|
||||||
|
<p v-if="loading" class="mt-12 text-center text-black/60">{{ t('commercial.suppliers.consultation.loading') }}</p>
|
||||||
|
<p v-else-if="error" class="mt-12 text-center text-m-danger">{{ t('commercial.suppliers.consultation.notFound') }}</p>
|
||||||
|
|
||||||
|
<template v-else-if="supplier">
|
||||||
|
<!-- ── Formulaire principal (lecture seule) ──────────────────────── -->
|
||||||
|
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
|
||||||
|
<MalioInputText
|
||||||
|
:model-value="supplier.companyName"
|
||||||
|
:label="t('commercial.suppliers.form.main.companyName')"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
<MalioSelectCheckbox
|
||||||
|
:model-value="categoryIris"
|
||||||
|
:options="mainCategoryOptions"
|
||||||
|
:label="t('commercial.suppliers.form.main.categories')"
|
||||||
|
:display-tag="true"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ── Onglets (navigation libre, tout en lecture seule) ─────────── -->
|
||||||
|
<MalioTabList v-model="activeTab" :tabs="tabs" :max-visible-tabs="5" :max-width="1100" class="mt-[60px]">
|
||||||
|
<!-- Onglet Information -->
|
||||||
|
<template #information>
|
||||||
|
<div class="mt-12 grid grid-cols-4 gap-x-[44px] gap-y-4 bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
|
||||||
|
<!-- pt-1/pb-1 alignent le textarea (h-full) en haut ET en bas
|
||||||
|
sur les inputs (champ 40px centre dans un h-12). -->
|
||||||
|
<MalioInputTextArea
|
||||||
|
:model-value="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
|
||||||
|
/>
|
||||||
|
<MalioInputText
|
||||||
|
:model-value="information.competitors"
|
||||||
|
:label="t('commercial.suppliers.form.information.competitors')"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
<MalioDate
|
||||||
|
:model-value="information.foundedAt"
|
||||||
|
:label="t('commercial.suppliers.form.information.foundedAt')"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
<MalioInputText
|
||||||
|
:model-value="information.employeesCount"
|
||||||
|
:label="t('commercial.suppliers.form.information.employeesCount')"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
<MalioInputAmount
|
||||||
|
:model-value="information.revenueAmount"
|
||||||
|
:label="t('commercial.suppliers.form.information.revenueAmount')"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
<MalioInputText
|
||||||
|
:model-value="information.directorName"
|
||||||
|
:label="t('commercial.suppliers.form.information.directorName')"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
<MalioInputAmount
|
||||||
|
:model-value="information.profitAmount"
|
||||||
|
:label="t('commercial.suppliers.form.information.profitAmount')"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
<!-- Volume previsionnel : specifique fournisseur (entier). -->
|
||||||
|
<MalioInputText
|
||||||
|
:model-value="information.volumeForecast"
|
||||||
|
:label="t('commercial.suppliers.form.information.volumeForecast')"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Onglet Contacts -->
|
||||||
|
<template #contacts>
|
||||||
|
<div class="mt-12 flex flex-col gap-6">
|
||||||
|
<SupplierContactBlock
|
||||||
|
v-for="(contact, index) in contacts"
|
||||||
|
:key="contact.id ?? index"
|
||||||
|
:model-value="contact"
|
||||||
|
:title="t('commercial.suppliers.form.contact.title', { n: index + 1 })"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Onglet Adresses -->
|
||||||
|
<template #addresses>
|
||||||
|
<div class="mt-12 flex flex-col gap-6">
|
||||||
|
<SupplierAddressBlock
|
||||||
|
v-for="(view, index) in addressViews"
|
||||||
|
:key="view.draft.id ?? index"
|
||||||
|
:model-value="view.draft"
|
||||||
|
:title="t('commercial.suppliers.form.address.title', { n: index + 1 })"
|
||||||
|
:category-options="view.categoryOptions"
|
||||||
|
:site-options="allSiteOptions"
|
||||||
|
:contact-options="contactOptions"
|
||||||
|
:country-options="countryOptions"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
</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
|
||||||
|
:model-value="accounting.siren"
|
||||||
|
:label="t('commercial.suppliers.form.accounting.siren')"
|
||||||
|
:mask="SIREN_MASK"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
<MalioInputText
|
||||||
|
:model-value="accounting.accountNumber"
|
||||||
|
:label="t('commercial.suppliers.form.accounting.accountNumber')"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
<MalioSelect
|
||||||
|
:model-value="accounting.tvaModeIri"
|
||||||
|
:options="tvaModeOptions"
|
||||||
|
:label="t('commercial.suppliers.form.accounting.tvaMode')"
|
||||||
|
empty-option-label=""
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
<MalioInputText
|
||||||
|
:model-value="accounting.nTva"
|
||||||
|
:label="t('commercial.suppliers.form.accounting.nTva')"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
<MalioSelect
|
||||||
|
:model-value="accounting.paymentDelayIri"
|
||||||
|
:options="paymentDelayOptions"
|
||||||
|
:label="t('commercial.suppliers.form.accounting.paymentDelay')"
|
||||||
|
empty-option-label=""
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
<MalioSelect
|
||||||
|
:model-value="accounting.paymentTypeIri"
|
||||||
|
:options="paymentTypeOptions"
|
||||||
|
:label="t('commercial.suppliers.form.accounting.paymentType')"
|
||||||
|
empty-option-label=""
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
<MalioSelect
|
||||||
|
v-if="accounting.bankIri"
|
||||||
|
:model-value="accounting.bankIri"
|
||||||
|
:options="bankOptions"
|
||||||
|
:label="t('commercial.suppliers.form.accounting.bank')"
|
||||||
|
empty-option-label=""
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Blocs RIB (0..n), lecture seule. -->
|
||||||
|
<div
|
||||||
|
v-for="(rib, index) in ribs"
|
||||||
|
:key="rib.id ?? index"
|
||||||
|
class="bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]"
|
||||||
|
>
|
||||||
|
<div class="grid grid-cols-4 gap-x-[44px] gap-y-4">
|
||||||
|
<MalioInputText
|
||||||
|
:model-value="rib.label"
|
||||||
|
:label="t('commercial.suppliers.form.accounting.ribLabel')"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
<MalioInputText
|
||||||
|
:model-value="rib.bic"
|
||||||
|
:label="t('commercial.suppliers.form.accounting.ribBic')"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
<MalioInputText
|
||||||
|
:model-value="rib.iban"
|
||||||
|
:label="t('commercial.suppliers.form.accounting.ribIban')"
|
||||||
|
readonly
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Onglets non encore implementes : frame vide (navigation libre). -->
|
||||||
|
<template #transport><ComingSoonPlaceholder /></template>
|
||||||
|
<template #statistics><ComingSoonPlaceholder /></template>
|
||||||
|
<template #reports><ComingSoonPlaceholder /></template>
|
||||||
|
<template #exchanges><ComingSoonPlaceholder /></template>
|
||||||
|
</MalioTabList>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Modal de confirmation Archiver / Restaurer. -->
|
||||||
|
<MalioModal v-model="confirmOpen" modal-class="max-w-md">
|
||||||
|
<template #header>
|
||||||
|
<h2 class="text-[24px] font-bold">
|
||||||
|
{{ isArchived ? t('commercial.suppliers.consultation.confirmRestore.title') : t('commercial.suppliers.consultation.confirmArchive.title') }}
|
||||||
|
</h2>
|
||||||
|
</template>
|
||||||
|
<p>{{ isArchived ? t('commercial.suppliers.consultation.confirmRestore.message') : t('commercial.suppliers.consultation.confirmArchive.message') }}</p>
|
||||||
|
<template #footer>
|
||||||
|
<MalioButton
|
||||||
|
variant="secondary"
|
||||||
|
button-class="flex-1"
|
||||||
|
:label="t('commercial.suppliers.form.confirmDelete.cancel')"
|
||||||
|
@click="confirmOpen = false"
|
||||||
|
/>
|
||||||
|
<MalioButton
|
||||||
|
:variant="isArchived ? 'primary' : 'danger'"
|
||||||
|
button-class="flex-1"
|
||||||
|
:label="t('commercial.suppliers.form.confirmDelete.confirm')"
|
||||||
|
:disabled="toggling"
|
||||||
|
@click="confirmToggleArchive"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
</MalioModal>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref } from 'vue'
|
||||||
|
import { useSupplier } from '~/modules/commercial/composables/useSupplier'
|
||||||
|
import { buildSupplierFormTabKeys, isRibRequiredForPaymentType } from '~/modules/commercial/utils/supplierFormRules'
|
||||||
|
import { readHistoryTab } from '~/shared/utils/historyTab'
|
||||||
|
import {
|
||||||
|
canEditSupplier,
|
||||||
|
categoryOptionsOf,
|
||||||
|
contactOptionsOf,
|
||||||
|
emptyAddress,
|
||||||
|
mapAccountingDraft,
|
||||||
|
mapAddressView,
|
||||||
|
mapContactToDraft,
|
||||||
|
mapRibToDraft,
|
||||||
|
paymentTypeCodeOf,
|
||||||
|
referentialOptionOf,
|
||||||
|
showArchiveAction,
|
||||||
|
showRestoreAction,
|
||||||
|
type SelectOption,
|
||||||
|
type SupplierDetail,
|
||||||
|
} from '~/modules/commercial/utils/supplierConsultation'
|
||||||
|
import { emptyContact } from '~/modules/commercial/types/supplierForm'
|
||||||
|
|
||||||
|
// Masque d'affichage (purement visuel, la donnee reste celle du serveur).
|
||||||
|
const SIREN_MASK = '#########'
|
||||||
|
|
||||||
|
const { t } = useI18n()
|
||||||
|
const route = useRoute()
|
||||||
|
const router = useRouter()
|
||||||
|
const toast = useToast()
|
||||||
|
const { can, canAny } = usePermissions()
|
||||||
|
const authStore = useAuthStore()
|
||||||
|
|
||||||
|
// Gating de la route : la consultation exige `view`. Usine (sans view) est
|
||||||
|
// redirige vers le repertoire (lui-meme protege). Cf. matrice § 2.7.
|
||||||
|
if (!can('commercial.suppliers.view')) {
|
||||||
|
await navigateTo('/suppliers')
|
||||||
|
}
|
||||||
|
|
||||||
|
const supplierId = route.params.id as string
|
||||||
|
|
||||||
|
const { supplier, loading, error, load, archive, restore } = useSupplier(supplierId)
|
||||||
|
|
||||||
|
// ── Permissions / visibilite des actions ───────────────────────────────────
|
||||||
|
const canAccountingView = computed(() => can('commercial.suppliers.accounting.view'))
|
||||||
|
const canEdit = computed(() => canEditSupplier(canAny))
|
||||||
|
const isArchived = computed(() => supplier.value?.isArchived === true)
|
||||||
|
const showArchive = computed(() => showArchiveAction(can, isArchived.value))
|
||||||
|
const showRestore = computed(() => showRestoreAction(can, isArchived.value))
|
||||||
|
|
||||||
|
const headerTitle = computed(() => supplier.value?.companyName ?? t('commercial.suppliers.consultation.title'))
|
||||||
|
|
||||||
|
// ── Donnees derivees du payload (lecture seule) ────────────────────────────
|
||||||
|
const categoryIris = computed(() => (supplier.value?.categories ?? []).map(c => c['@id']))
|
||||||
|
|
||||||
|
const information = computed(() => ({
|
||||||
|
description: supplier.value?.description ?? null,
|
||||||
|
competitors: supplier.value?.competitors ?? null,
|
||||||
|
// MalioDate attend strictement YYYY-MM-DD : on tronque l'ISO datetime renvoye.
|
||||||
|
foundedAt: supplier.value?.foundedAt ? supplier.value.foundedAt.slice(0, 10) : null,
|
||||||
|
employeesCount: supplier.value?.employeesCount != null ? String(supplier.value.employeesCount) : null,
|
||||||
|
revenueAmount: supplier.value?.revenueAmount ?? null,
|
||||||
|
profitAmount: supplier.value?.profitAmount ?? null,
|
||||||
|
directorName: supplier.value?.directorName ?? null,
|
||||||
|
volumeForecast: supplier.value?.volumeForecast != null ? String(supplier.value.volumeForecast) : null,
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Chaque bloc reste visible meme vide en consultation : si la collection est
|
||||||
|
// vide, on affiche un bloc vierge en lecture seule (pas de message « Aucun … »).
|
||||||
|
const contacts = computed(() => {
|
||||||
|
const list = (supplier.value?.contacts ?? []).map(mapContactToDraft)
|
||||||
|
return list.length ? list : [emptyContact()]
|
||||||
|
})
|
||||||
|
// Vue par adresse : brouillon + options (sites/categories) propres a l'adresse.
|
||||||
|
const addressViews = computed(() => {
|
||||||
|
const views = (supplier.value?.addresses ?? []).map(mapAddressView)
|
||||||
|
return views.length ? views : [{ draft: emptyAddress(), siteOptions: [], categoryOptions: [] }]
|
||||||
|
})
|
||||||
|
// Exception au placeholder ci-dessus : on n'affiche AUCUN bloc RIB quand le
|
||||||
|
// fournisseur n'en a pas. ERP-121 : un fournisseur peut desormais conserver des RIB
|
||||||
|
// « dormants » apres etre repasse hors-LCR (on ne les supprime plus). En consultation,
|
||||||
|
// decision metier = on les masque TOTALEMENT : on n'affiche les RIB que si le type de
|
||||||
|
// reglement courant est LCR (le `code` est embarque sous supplier:read:accounting).
|
||||||
|
const ribs = computed(() =>
|
||||||
|
isRibRequiredForPaymentType(paymentTypeCodeOf(supplier.value?.paymentType))
|
||||||
|
? (supplier.value?.ribs ?? []).map(mapRibToDraft)
|
||||||
|
: [],
|
||||||
|
)
|
||||||
|
// Draft comptable (tout null si l'utilisateur n'a pas accounting.view).
|
||||||
|
const accounting = computed(() => mapAccountingDraft(supplier.value ?? ({} as SupplierDetail)))
|
||||||
|
|
||||||
|
// ── Options des selects (construites depuis l'EMBED, jamais via un GET de
|
||||||
|
// referentiel : /categories et /sites sont en 403 pour les roles metier
|
||||||
|
// non-admin, ce qui laisserait les libelles vides). ───────────────────────
|
||||||
|
const mainCategoryOptions = computed(() => categoryOptionsOf(supplier.value?.categories))
|
||||||
|
const contactOptions = computed(() => contactOptionsOf(supplier.value?.contacts))
|
||||||
|
|
||||||
|
// Liste COMPLETE des sites disponibles, issue de /api/me (groupe me:read — donc
|
||||||
|
// pas de 403 pour les roles metier, contrairement a GET /sites). Libelle = numero
|
||||||
|
// de departement (2 premiers chiffres du code postal). Permet d'afficher TOUJOURS
|
||||||
|
// toutes les cases « Sites » (86 / 17 / 82) dans le bloc adresse, meme celles non
|
||||||
|
// rattachees a l'adresse consultee (les rattachees restent cochees via siteIris).
|
||||||
|
const allSiteOptions = computed<SelectOption[]>(() =>
|
||||||
|
(authStore.user?.sites ?? []).map(s => ({
|
||||||
|
value: `/api/sites/${s.id}`,
|
||||||
|
label: (s.postalCode ?? '').slice(0, 2),
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
|
||||||
|
// Pays (consultation, lecture seule) : derive des adresses du fournisseur, comme
|
||||||
|
// l'ecran client. Le referentiel `country` (ERP-116) n'est pas charge ici, l'ecran
|
||||||
|
// n'affiche que les valeurs deja stockees.
|
||||||
|
const countryOptions = computed<SelectOption[]>(() =>
|
||||||
|
[...new Set(
|
||||||
|
(supplier.value?.addresses ?? [])
|
||||||
|
.map(a => a.country)
|
||||||
|
.filter((c): c is string => !!c),
|
||||||
|
)].map(c => ({ value: c, label: c })),
|
||||||
|
)
|
||||||
|
|
||||||
|
// Selects comptables : libelle issu de l'embed (option unique ou vide).
|
||||||
|
const tvaModeOptions = computed(() => referentialOptionOf(supplier.value?.tvaMode))
|
||||||
|
const paymentDelayOptions = computed(() => referentialOptionOf(supplier.value?.paymentDelay))
|
||||||
|
const paymentTypeOptions = computed(() => referentialOptionOf(supplier.value?.paymentType))
|
||||||
|
const bankOptions = computed(() => referentialOptionOf(supplier.value?.bank))
|
||||||
|
|
||||||
|
// ── Onglets : navigation LIBRE (pas de sequence forcee en consultation) ────
|
||||||
|
// 3 onglets actifs (Information, Contacts, Adresses, + Comptabilite si droit) et
|
||||||
|
// 4 coquilles (Transport, Statistiques, Rapports, Echanges).
|
||||||
|
const tabKeys = computed(() => buildSupplierFormTabKeys(canAccountingView.value, { includeEditOnlyTabs: true }))
|
||||||
|
|
||||||
|
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',
|
||||||
|
statistics: 'mdi:finance',
|
||||||
|
reports: 'mdi:file-document-edit-outline',
|
||||||
|
exchanges: 'mdi:account-group-outline',
|
||||||
|
}
|
||||||
|
|
||||||
|
const tabs = computed(() => tabKeys.value.map(key => ({
|
||||||
|
key,
|
||||||
|
label: t(`commercial.suppliers.tab.${key}`),
|
||||||
|
icon: TAB_ICONS[key],
|
||||||
|
})))
|
||||||
|
|
||||||
|
// Onglet initial : repris de l'edition au retour (history.state), sinon Information.
|
||||||
|
const activeTab = ref(readHistoryTab(tabKeys.value) ?? 'information')
|
||||||
|
|
||||||
|
// ── Navigation ─────────────────────────────────────────────────────────────
|
||||||
|
function goBack(): void {
|
||||||
|
router.push('/suppliers')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bascule en edition en conservant l'onglet courant (via history.state). */
|
||||||
|
function goEdit(): void {
|
||||||
|
router.push({ path: `/suppliers/${supplierId}/edit`, state: { tab: activeTab.value } })
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Archivage / Restauration ────────────────────────────────────────────────
|
||||||
|
const confirmOpen = ref(false)
|
||||||
|
const toggling = ref(false)
|
||||||
|
|
||||||
|
function askToggleArchive(): void {
|
||||||
|
confirmOpen.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Confirme l'archivage ou la restauration (PATCH isArchived seul). Gere le 409
|
||||||
|
* de conflit d'homonyme actif a la restauration avec un message dedie.
|
||||||
|
*/
|
||||||
|
async function confirmToggleArchive(): Promise<void> {
|
||||||
|
if (toggling.value) return
|
||||||
|
toggling.value = true
|
||||||
|
const restoring = isArchived.value
|
||||||
|
try {
|
||||||
|
if (restoring) {
|
||||||
|
await restore()
|
||||||
|
toast.success({ title: t('commercial.suppliers.toast.restoreSuccess') })
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
await archive()
|
||||||
|
toast.success({ title: t('commercial.suppliers.toast.archiveSuccess') })
|
||||||
|
}
|
||||||
|
confirmOpen.value = false
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
const status = (e as { response?: { status?: number } })?.response?.status
|
||||||
|
toast.error({
|
||||||
|
title: t('commercial.suppliers.toast.error'),
|
||||||
|
message: restoring && status === 409
|
||||||
|
? t('commercial.suppliers.toast.restoreConflict')
|
||||||
|
: t('commercial.suppliers.toast.error'),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
toggling.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
useHead({ title: headerTitle })
|
||||||
|
|
||||||
|
onMounted(load)
|
||||||
|
</script>
|
||||||
@@ -266,7 +266,7 @@
|
|||||||
class="relative bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]"
|
class="relative bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]"
|
||||||
>
|
>
|
||||||
<MalioButtonIcon
|
<MalioButtonIcon
|
||||||
v-if="!accountingReadonly"
|
v-if="!accountingReadonly && visibleRibs.length > 1"
|
||||||
icon="mdi:delete-outline"
|
icon="mdi:delete-outline"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
button-class="absolute top-3 right-3"
|
button-class="absolute top-3 right-3"
|
||||||
@@ -646,11 +646,15 @@ const contactOptions = computed<RefOption[]>(() =>
|
|||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
|
|
||||||
// Pays disponibles (France preselectionnee par defaut sur chaque adresse).
|
// Pays : referentiel `country` charge via l'API (ERP-116), aligne sur l'ecran
|
||||||
const countryOptions: RefOption[] = [
|
// client. France garantie en tete pour rester preselectionnable par defaut sur
|
||||||
{ value: 'France', label: 'France' },
|
// chaque adresse meme si `/countries` echoue (resilience ERP-102).
|
||||||
{ value: 'Espagne', label: 'Espagne' },
|
const countryOptions = computed<RefOption[]>(() => {
|
||||||
]
|
const list = referentials.countries.value
|
||||||
|
return list.some(c => c.value === 'France')
|
||||||
|
? list
|
||||||
|
: [{ value: 'France', label: 'France' }, ...list]
|
||||||
|
})
|
||||||
|
|
||||||
// « + Adresse » desactive tant que la derniere adresse n'est pas valide.
|
// « + Adresse » desactive tant que la derniere adresse n'est pas valide.
|
||||||
const canAddAddress = computed(() => {
|
const canAddAddress = computed(() => {
|
||||||
@@ -741,13 +745,14 @@ function onPaymentTypeChange(value: string | number | null): void {
|
|||||||
accounting.paymentTypeIri = value === null ? null : String(value)
|
accounting.paymentTypeIri = value === null ? null : String(value)
|
||||||
// La banque n'a de sens que pour un virement : on la vide sinon (RG-2.07).
|
// La banque n'a de sens que pour un virement : on la vide sinon (RG-2.07).
|
||||||
if (!isBankRequired.value) accounting.bankIri = null
|
if (!isBankRequired.value) accounting.bankIri = null
|
||||||
// Les RIB n'ont de sens que pour une LCR (RG-2.08) : amorce un bloc vide quand
|
// ERP-121 : on ne jette plus la saisie RIB au passage hors-LCR. Les blocs sont
|
||||||
// LCR est choisi, vide la liste sinon (pas de RIB fantome soumis).
|
// masques (visibleRibs = []) mais conserves, et reapparaissent si l'on repasse
|
||||||
|
// en LCR. Ils ne sont persistes qu'a la validation SOUS LCR (cf. submitAccounting),
|
||||||
|
// donc une saisie abandonnee hors-LCR ne cree aucun RIB orphelin.
|
||||||
if (isRibRequired.value) {
|
if (isRibRequired.value) {
|
||||||
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
ribs.value = []
|
|
||||||
ribErrors.value = []
|
ribErrors.value = []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -782,29 +787,36 @@ async function submitAccounting(): Promise<void> {
|
|||||||
tabSubmitting.value = true
|
tabSubmitting.value = true
|
||||||
accountingErrors.clearErrors()
|
accountingErrors.clearErrors()
|
||||||
try {
|
try {
|
||||||
// 1) POST/PATCH des RIB d'abord (erreurs inline par ligne). Seuls les blocs
|
// 1) POST/PATCH des RIB d'abord — UNIQUEMENT sous LCR (erreurs inline par
|
||||||
// RIB TOTALEMENT vides (amorce neuve) sont ignores.
|
// ligne). Hors-LCR (ERP-121), une saisie RIB eventuellement restee dans le
|
||||||
const ribHasError = await submitRows(
|
// brouillon est masquee et n'est PAS persistee (pas de RIB orphelin sur un
|
||||||
ribs.value,
|
// fournisseur en virement). On ne saute une amorce neuve vide QUE s'il reste
|
||||||
ribErrors,
|
// un autre RIB soumettable : sinon (LCR sans aucun RIB rempli) on la soumet
|
||||||
async (rib) => {
|
// pour declencher la 422 NotBlank inline.
|
||||||
const body = buildRibPayload(rib)
|
if (isRibRequired.value) {
|
||||||
if (rib.id === null) {
|
const hasSubmittableRib = ribs.value.some(r => r.id !== null || !isRibBlank(r))
|
||||||
const created = await api.post<{ id: number }>(
|
const ribHasError = await submitRows(
|
||||||
`/suppliers/${supplierId.value}/ribs`,
|
ribs.value,
|
||||||
body,
|
ribErrors,
|
||||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
async (rib) => {
|
||||||
)
|
const body = buildRibPayload(rib)
|
||||||
rib.id = created.id
|
if (rib.id === null) {
|
||||||
}
|
const created = await api.post<{ id: number }>(
|
||||||
else {
|
`/suppliers/${supplierId.value}/ribs`,
|
||||||
await api.patch(`/supplier_ribs/${rib.id}`, body, { toast: false })
|
body,
|
||||||
}
|
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||||
},
|
)
|
||||||
error => toast.error({ title: t('commercial.suppliers.toast.error'), message: apiErrorMessage(error) }),
|
rib.id = created.id
|
||||||
rib => rib.id === null && isRibBlank(rib),
|
}
|
||||||
)
|
else {
|
||||||
if (ribHasError) return
|
await api.patch(`/supplier_ribs/${rib.id}`, body, { toast: false })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error => toast.error({ title: t('commercial.suppliers.toast.error'), message: apiErrorMessage(error) }),
|
||||||
|
rib => hasSubmittableRib && rib.id === null && isRibBlank(rib),
|
||||||
|
)
|
||||||
|
if (ribHasError) return
|
||||||
|
}
|
||||||
|
|
||||||
// 2) PATCH des scalaires comptables (erreurs inline sur leurs champs).
|
// 2) PATCH des scalaires comptables (erreurs inline sur leurs champs).
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
mapAddressView,
|
mapAddressView,
|
||||||
mapContactToDraft,
|
mapContactToDraft,
|
||||||
mapRibToDraft,
|
mapRibToDraft,
|
||||||
|
paymentTypeCodeOf,
|
||||||
referentialOptionOf,
|
referentialOptionOf,
|
||||||
relationOf,
|
relationOf,
|
||||||
showArchiveAction,
|
showArchiveAction,
|
||||||
@@ -233,3 +234,17 @@ describe('showArchiveAction / showRestoreAction', () => {
|
|||||||
expect(showRestoreAction(can([]), true)).toBe(false)
|
expect(showRestoreAction(can([]), true)).toBe(false)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('paymentTypeCodeOf (ERP-121 : RIB masques hors-LCR en consultation)', () => {
|
||||||
|
it('retourne le code metier quand le type de reglement est embarque', () => {
|
||||||
|
expect(paymentTypeCodeOf({ '@id': '/api/payment_types/1', code: 'LCR' })).toBe('LCR')
|
||||||
|
expect(paymentTypeCodeOf({ '@id': '/api/payment_types/2', code: 'VIREMENT' })).toBe('VIREMENT')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('retourne null pour un IRI nu, un objet sans code, ou une relation absente', () => {
|
||||||
|
expect(paymentTypeCodeOf('/api/payment_types/1')).toBeNull()
|
||||||
|
expect(paymentTypeCodeOf({ '@id': '/api/payment_types/1' })).toBeNull()
|
||||||
|
expect(paymentTypeCodeOf(null)).toBeNull()
|
||||||
|
expect(paymentTypeCodeOf(undefined)).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -211,6 +211,38 @@ describe('buildContactPayload / buildAddressPayload / buildRibPayload', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Bug edition : en PATCH (merge), une cle de champ requis OMISE laisse la valeur
|
||||||
|
// serveur inchangee -> faux 200 quand l'utilisateur vide le champ. En `forUpdate`,
|
||||||
|
// on envoie `''` (chaine valide, pas de 400 de type) -> NotBlank 422 inline.
|
||||||
|
describe('forUpdate (EDITION/PATCH) : champ requis vide -> `\'\'` au lieu d\'etre omis', () => {
|
||||||
|
it('buildMainPayload : companyName vide envoye en `\'\'`', () => {
|
||||||
|
const payload = buildMainPayload(mainDraft({ companyName: '' }), { forUpdate: true })
|
||||||
|
expect('companyName' in payload).toBe(true)
|
||||||
|
expect(payload.companyName).toBe('')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('buildAddressPayload : postalCode / city / street vides envoyes en `\'\'`', () => {
|
||||||
|
const address: AddressFormDraft = {
|
||||||
|
id: 7, isProspect: false, isDelivery: true, isBilling: false, isBroker: false, isDistributor: false, country: 'France',
|
||||||
|
postalCode: '', city: null, street: '1 rue X', streetComplement: null,
|
||||||
|
categoryIris: ['/api/categories/2'], siteIris: ['/api/sites/1'], contactIris: [],
|
||||||
|
billingEmail: null, billingEmailSecondary: null, hasSecondaryBillingEmail: false,
|
||||||
|
}
|
||||||
|
const payload = buildAddressPayload(address, false, { forUpdate: true })
|
||||||
|
expect(payload.postalCode).toBe('')
|
||||||
|
expect(payload.city).toBe('')
|
||||||
|
// Un champ requis renseigne reste tel quel.
|
||||||
|
expect(payload.street).toBe('1 rue X')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('buildRibPayload : label / bic vides envoyes en `\'\'`, iban conserve', () => {
|
||||||
|
const payload = buildRibPayload({ id: 4, label: '', bic: null, iban: 'FR7612345' }, { forUpdate: true })
|
||||||
|
expect(payload.label).toBe('')
|
||||||
|
expect(payload.bic).toBe('')
|
||||||
|
expect(payload.iban).toBe('FR7612345')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('mapMainDraft — pre-remplissage bloc principal', () => {
|
describe('mapMainDraft — pre-remplissage bloc principal', () => {
|
||||||
it('resout la relation et extrait les IRI (sans contact inline)', () => {
|
it('resout la relation et extrait les IRI (sans contact inline)', () => {
|
||||||
const client = {
|
const client = {
|
||||||
|
|||||||
@@ -0,0 +1,239 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import {
|
||||||
|
canEditSupplier,
|
||||||
|
categoryOptionsOf,
|
||||||
|
contactOptionsOf,
|
||||||
|
iriOf,
|
||||||
|
mapAccountingDraft,
|
||||||
|
mapAddressToDraft,
|
||||||
|
mapAddressView,
|
||||||
|
mapContactToDraft,
|
||||||
|
mapRibToDraft,
|
||||||
|
paymentTypeCodeOf,
|
||||||
|
referentialOptionOf,
|
||||||
|
showArchiveAction,
|
||||||
|
showRestoreAction,
|
||||||
|
siteOptionsOf,
|
||||||
|
type SupplierDetail,
|
||||||
|
} from '../supplierConsultation'
|
||||||
|
|
||||||
|
describe('iriOf', () => {
|
||||||
|
it('retourne l\'@id d\'une relation embarquee (objet)', () => {
|
||||||
|
expect(iriOf({ '@id': '/api/payment_types/14', code: 'LCR' })).toBe('/api/payment_types/14')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('retourne la chaine telle quelle si la relation est deja un IRI', () => {
|
||||||
|
expect(iriOf('/api/banks/3')).toBe('/api/banks/3')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('retourne null pour une relation absente (null / undefined / skip_null_values)', () => {
|
||||||
|
expect(iriOf(null)).toBeNull()
|
||||||
|
expect(iriOf(undefined)).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('mapContactToDraft', () => {
|
||||||
|
it('formate les telephones en XX XX XX XX XX et conserve l\'iri', () => {
|
||||||
|
const draft = mapContactToDraft({
|
||||||
|
'@id': '/api/supplier_contacts/39',
|
||||||
|
id: 39,
|
||||||
|
firstName: 'Marie',
|
||||||
|
lastName: 'Martin',
|
||||||
|
jobTitle: 'Responsable achats',
|
||||||
|
phonePrimary: '0612345678',
|
||||||
|
email: 'marie.martin@seed.test',
|
||||||
|
})
|
||||||
|
expect(draft.id).toBe(39)
|
||||||
|
expect(draft.iri).toBe('/api/supplier_contacts/39')
|
||||||
|
expect(draft.phonePrimary).toBe('06 12 34 56 78')
|
||||||
|
expect(draft.hasSecondaryPhone).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('revele le 2e telephone quand phoneSecondary est present', () => {
|
||||||
|
const draft = mapContactToDraft({
|
||||||
|
'@id': '/api/supplier_contacts/40',
|
||||||
|
id: 40,
|
||||||
|
phonePrimary: '0600000000',
|
||||||
|
phoneSecondary: '0611111111',
|
||||||
|
})
|
||||||
|
expect(draft.hasSecondaryPhone).toBe(true)
|
||||||
|
expect(draft.phoneSecondary).toBe('06 11 11 11 11')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('mapAddressToDraft', () => {
|
||||||
|
it('mappe l\'enum addressType, les champs fournisseur et extrait les iris', () => {
|
||||||
|
const draft = mapAddressToDraft({
|
||||||
|
'@id': '/api/supplier_addresses/33',
|
||||||
|
id: 33,
|
||||||
|
addressType: 'DEPART',
|
||||||
|
country: 'France',
|
||||||
|
postalCode: '86000',
|
||||||
|
city: 'Poitiers',
|
||||||
|
street: '12 rue des Acacias',
|
||||||
|
bennes: 3,
|
||||||
|
triageProvider: true,
|
||||||
|
sites: [{ '@id': '/api/sites/87', name: 'Chatellerault', color: '#056CF2' }],
|
||||||
|
categories: [{ '@id': '/api/categories/2279', code: 'NEGOCIANT' }],
|
||||||
|
contacts: [{ '@id': '/api/supplier_contacts/39' }, '/api/supplier_contacts/41'],
|
||||||
|
})
|
||||||
|
expect(draft.addressType).toBe('DEPART')
|
||||||
|
expect(draft.siteIris).toEqual(['/api/sites/87'])
|
||||||
|
expect(draft.categoryIris).toEqual(['/api/categories/2279'])
|
||||||
|
expect(draft.contactIris).toEqual(['/api/supplier_contacts/39', '/api/supplier_contacts/41'])
|
||||||
|
// bennes (entier) → chaine pour MalioInputNumber.
|
||||||
|
expect(draft.bennes).toBe('3')
|
||||||
|
expect(draft.triageProvider).toBe(true)
|
||||||
|
expect(draft.city).toBe('Poitiers')
|
||||||
|
expect(draft.country).toBe('France')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('tolere les champs absents (defauts : France, bennes « 0 », triage faux, type null)', () => {
|
||||||
|
const draft = mapAddressToDraft({ '@id': '/api/supplier_addresses/9', id: 9 })
|
||||||
|
expect(draft.addressType).toBeNull()
|
||||||
|
expect(draft.siteIris).toEqual([])
|
||||||
|
expect(draft.categoryIris).toEqual([])
|
||||||
|
expect(draft.contactIris).toEqual([])
|
||||||
|
expect(draft.country).toBe('France')
|
||||||
|
expect(draft.bennes).toBe('0')
|
||||||
|
expect(draft.triageProvider).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('mapRibToDraft', () => {
|
||||||
|
it('mappe label / bic / iban et l\'id serveur', () => {
|
||||||
|
const draft = mapRibToDraft({ '@id': '/api/supplier_ribs/27', id: 27, label: 'Compte principal', bic: 'BNPAFRPPXXX', iban: 'FR14...' })
|
||||||
|
expect(draft).toEqual({ id: 27, label: 'Compte principal', bic: 'BNPAFRPPXXX', iban: 'FR14...' })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('mapAccountingDraft', () => {
|
||||||
|
it('mappe les scalaires et resout les iris des referentiels embarques', () => {
|
||||||
|
const acc = mapAccountingDraft({
|
||||||
|
'@id': '/api/suppliers/85',
|
||||||
|
id: 85,
|
||||||
|
siren: '123456789',
|
||||||
|
accountNumber: 'F0001',
|
||||||
|
nTva: 'FR00123456789',
|
||||||
|
tvaMode: { '@id': '/api/tva_modes/30' },
|
||||||
|
paymentDelay: { '@id': '/api/payment_delays/11' },
|
||||||
|
paymentType: { '@id': '/api/payment_types/14', code: 'LCR' },
|
||||||
|
bank: { '@id': '/api/banks/3' },
|
||||||
|
} as SupplierDetail)
|
||||||
|
expect(acc).toEqual({
|
||||||
|
siren: '123456789',
|
||||||
|
accountNumber: 'F0001',
|
||||||
|
nTva: 'FR00123456789',
|
||||||
|
tvaModeIri: '/api/tva_modes/30',
|
||||||
|
paymentDelayIri: '/api/payment_delays/11',
|
||||||
|
paymentTypeIri: '/api/payment_types/14',
|
||||||
|
bankIri: '/api/banks/3',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renvoie des null quand les champs comptables sont absents (gating par omission, sans accounting.view)', () => {
|
||||||
|
const acc = mapAccountingDraft({} as SupplierDetail)
|
||||||
|
expect(acc).toEqual({
|
||||||
|
siren: null,
|
||||||
|
accountNumber: null,
|
||||||
|
nTva: null,
|
||||||
|
tvaModeIri: null,
|
||||||
|
paymentDelayIri: null,
|
||||||
|
paymentTypeIri: null,
|
||||||
|
bankIri: null,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('options construites depuis l\'embed (role-independantes)', () => {
|
||||||
|
it('categoryOptionsOf expose value=IRI, label=nom, code', () => {
|
||||||
|
expect(categoryOptionsOf([{ '@id': '/api/categories/2279', name: 'Negociant', code: 'NEGOCIANT' }])).toEqual([
|
||||||
|
{ value: '/api/categories/2279', label: 'Negociant', code: 'NEGOCIANT' },
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('siteOptionsOf expose value=IRI, label=nom', () => {
|
||||||
|
expect(siteOptionsOf([{ '@id': '/api/sites/87', name: 'Chatellerault', color: '#000' }])).toEqual([
|
||||||
|
{ value: '/api/sites/87', label: 'Chatellerault' },
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('contactOptionsOf compose le libelle (nom complet, sinon email)', () => {
|
||||||
|
expect(contactOptionsOf([
|
||||||
|
{ '@id': '/api/supplier_contacts/1', id: 1, firstName: 'Marie', lastName: 'Martin' },
|
||||||
|
{ '@id': '/api/supplier_contacts/2', id: 2, email: 'a@b.fr' },
|
||||||
|
])).toEqual([
|
||||||
|
{ value: '/api/supplier_contacts/1', label: 'Marie Martin' },
|
||||||
|
{ value: '/api/supplier_contacts/2', label: 'a@b.fr' },
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('referentialOptionOf : option unique depuis l\'embed, vide pour IRI nu / absent', () => {
|
||||||
|
expect(referentialOptionOf({ '@id': '/api/payment_types/14', label: 'LCR' })).toEqual([
|
||||||
|
{ value: '/api/payment_types/14', label: 'LCR' },
|
||||||
|
])
|
||||||
|
expect(referentialOptionOf('/api/banks/3')).toEqual([])
|
||||||
|
expect(referentialOptionOf(null)).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('mapAddressView assemble brouillon + options propres a l\'adresse', () => {
|
||||||
|
const view = mapAddressView({
|
||||||
|
'@id': '/api/supplier_addresses/33',
|
||||||
|
id: 33,
|
||||||
|
addressType: 'RENDU',
|
||||||
|
city: 'Poitiers',
|
||||||
|
sites: [{ '@id': '/api/sites/87', name: 'Chatellerault' }],
|
||||||
|
categories: [{ '@id': '/api/categories/2279', name: 'Negociant', code: 'NEGOCIANT' }],
|
||||||
|
})
|
||||||
|
expect(view.draft.id).toBe(33)
|
||||||
|
expect(view.draft.addressType).toBe('RENDU')
|
||||||
|
expect(view.siteOptions).toEqual([{ value: '/api/sites/87', label: 'Chatellerault' }])
|
||||||
|
expect(view.categoryOptions).toEqual([{ value: '/api/categories/2279', label: 'Negociant', code: 'NEGOCIANT' }])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('canEditSupplier', () => {
|
||||||
|
const can = (granted: string[]) => (codes: string[]) => codes.some(c => granted.includes(c))
|
||||||
|
|
||||||
|
it('visible pour manage', () => {
|
||||||
|
expect(canEditSupplier(can(['commercial.suppliers.manage']))).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('visible pour accounting.manage (role Compta)', () => {
|
||||||
|
expect(canEditSupplier(can(['commercial.suppliers.accounting.manage']))).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('masque sans aucune des deux permissions (role Usine)', () => {
|
||||||
|
expect(canEditSupplier(can(['commercial.suppliers.view']))).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('showArchiveAction / showRestoreAction', () => {
|
||||||
|
const can = (granted: string[]) => (code: string) => granted.includes(code)
|
||||||
|
|
||||||
|
it('Archiver : visible avec la permission archive ET fournisseur non archive', () => {
|
||||||
|
expect(showArchiveAction(can(['commercial.suppliers.archive']), false)).toBe(true)
|
||||||
|
expect(showArchiveAction(can(['commercial.suppliers.archive']), true)).toBe(false)
|
||||||
|
expect(showArchiveAction(can([]), false)).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('Restaurer : visible avec la permission archive ET fournisseur archive', () => {
|
||||||
|
expect(showRestoreAction(can(['commercial.suppliers.archive']), true)).toBe(true)
|
||||||
|
expect(showRestoreAction(can(['commercial.suppliers.archive']), false)).toBe(false)
|
||||||
|
expect(showRestoreAction(can([]), true)).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('paymentTypeCodeOf (ERP-121 : RIB masques hors-LCR en consultation)', () => {
|
||||||
|
it('retourne le code metier quand le type de reglement est embarque', () => {
|
||||||
|
expect(paymentTypeCodeOf({ '@id': '/api/payment_types/1', code: 'LCR' })).toBe('LCR')
|
||||||
|
expect(paymentTypeCodeOf({ '@id': '/api/payment_types/2', code: 'VIREMENT' })).toBe('VIREMENT')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('retourne null pour un IRI nu, un objet sans code, ou une relation absente', () => {
|
||||||
|
expect(paymentTypeCodeOf('/api/payment_types/1')).toBeNull()
|
||||||
|
expect(paymentTypeCodeOf({ '@id': '/api/payment_types/1' })).toBeNull()
|
||||||
|
expect(paymentTypeCodeOf(null)).toBeNull()
|
||||||
|
expect(paymentTypeCodeOf(undefined)).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -6,7 +6,12 @@ import {
|
|||||||
buildInformationPayload,
|
buildInformationPayload,
|
||||||
buildMainPayload,
|
buildMainPayload,
|
||||||
buildRibPayload,
|
buildRibPayload,
|
||||||
|
mapAccountingFormDraft,
|
||||||
|
mapInformationDraft,
|
||||||
|
mapMainDraft,
|
||||||
|
resolveTabEditability,
|
||||||
} from '../supplierEdit'
|
} from '../supplierEdit'
|
||||||
|
import type { SupplierDetail } from '~/modules/commercial/utils/supplierConsultation'
|
||||||
import { emptyAddress, emptyContact, emptyRib } from '~/modules/commercial/types/supplierForm'
|
import { emptyAddress, emptyContact, emptyRib } from '~/modules/commercial/types/supplierForm'
|
||||||
|
|
||||||
describe('buildMainPayload (groupe supplier:write:main)', () => {
|
describe('buildMainPayload (groupe supplier:write:main)', () => {
|
||||||
@@ -17,11 +22,17 @@ describe('buildMainPayload (groupe supplier:write:main)', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('omet companyName vide (-> 422 NotBlank, ERP-119)', () => {
|
it('CREATION : omet companyName vide (-> 422 NotBlank, ERP-119)', () => {
|
||||||
const payload = buildMainPayload({ companyName: null, categoryIris: [] })
|
const payload = buildMainPayload({ companyName: null, categoryIris: [] })
|
||||||
expect('companyName' in payload).toBe(false)
|
expect('companyName' in payload).toBe(false)
|
||||||
expect(payload.categories).toEqual([])
|
expect(payload.categories).toEqual([])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('EDITION (forUpdate) : companyName vide envoye en `\'\'` (PATCH -> 422 NotBlank, pas un faux 200)', () => {
|
||||||
|
const payload = buildMainPayload({ companyName: '', categoryIris: [] }, { forUpdate: true })
|
||||||
|
expect('companyName' in payload).toBe(true)
|
||||||
|
expect(payload.companyName).toBe('')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('buildInformationPayload (groupe supplier:write:information)', () => {
|
describe('buildInformationPayload (groupe supplier:write:information)', () => {
|
||||||
@@ -86,6 +97,16 @@ describe('buildAddressPayload (sous-ressource supplier_address — specificites
|
|||||||
expect('addressType' in payload).toBe(false)
|
expect('addressType' in payload).toBe(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('EDITION (forUpdate) : un champ requis vide est envoye en `\'\'` (et NON omis) pour declencher la 422 NotBlank au PATCH', () => {
|
||||||
|
// Bug edition : omettre la cle d'un champ requis vide laisse le PATCH garder
|
||||||
|
// l'ancienne valeur (faux 200). En `forUpdate`, on envoie `''` -> NotBlank 422.
|
||||||
|
const payload = buildAddressPayload({ ...emptyAddress(), addressType: 'DEPART', postalCode: '' }, { forUpdate: true })
|
||||||
|
expect('postalCode' in payload).toBe(true)
|
||||||
|
expect(payload.postalCode).toBe('')
|
||||||
|
// Un champ requis renseigne reste tel quel.
|
||||||
|
expect(payload.addressType).toBe('DEPART')
|
||||||
|
})
|
||||||
|
|
||||||
it('n\'expose jamais d\'email de facturation (difference M1)', () => {
|
it('n\'expose jamais d\'email de facturation (difference M1)', () => {
|
||||||
const payload = buildAddressPayload({ ...emptyAddress(), addressType: 'DEPART' })
|
const payload = buildAddressPayload({ ...emptyAddress(), addressType: 'DEPART' })
|
||||||
expect('billingEmail' in payload).toBe(false)
|
expect('billingEmail' in payload).toBe(false)
|
||||||
@@ -113,3 +134,85 @@ describe('buildRibPayload (sous-ressource supplier_rib)', () => {
|
|||||||
expect(payload.iban).toBe('FR1420041010050500013M02606')
|
expect(payload.iban).toBe('FR1420041010050500013M02606')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('mapMainDraft — pre-remplissage bloc principal (companyName + categories, pas de relation M2)', () => {
|
||||||
|
it('extrait companyName et les IRI de categories', () => {
|
||||||
|
const draft = mapMainDraft({
|
||||||
|
'@id': '/api/suppliers/85', id: 85,
|
||||||
|
companyName: 'DOD862875',
|
||||||
|
categories: [{ '@id': '/api/categories/2279', code: 'NEGOCIANT' }],
|
||||||
|
} as SupplierDetail)
|
||||||
|
expect(draft.companyName).toBe('DOD862875')
|
||||||
|
expect(draft.categoryIris).toEqual(['/api/categories/2279'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('gere les cles omises (skip_null_values) sans planter', () => {
|
||||||
|
const draft = mapMainDraft({ '@id': '/api/suppliers/2', id: 2 } as SupplierDetail)
|
||||||
|
expect(draft.companyName).toBeNull()
|
||||||
|
expect(draft.categoryIris).toEqual([])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('mapInformationDraft — pre-remplissage onglet Information (+ volumeForecast M2)', () => {
|
||||||
|
it('tronque foundedAt, stringifie employeesCount et volumeForecast', () => {
|
||||||
|
const draft = mapInformationDraft({
|
||||||
|
'@id': '/api/suppliers/85', id: 85,
|
||||||
|
foundedAt: '2008-04-01T00:00:00+02:00', employeesCount: 42, volumeForecast: 8000,
|
||||||
|
} as SupplierDetail)
|
||||||
|
expect(draft.foundedAt).toBe('2008-04-01')
|
||||||
|
expect(draft.employeesCount).toBe('42')
|
||||||
|
expect(draft.volumeForecast).toBe('8000')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('cles omises -> null (volumeForecast inclus)', () => {
|
||||||
|
const draft = mapInformationDraft({ '@id': '/api/suppliers/1', id: 1 } as SupplierDetail)
|
||||||
|
expect(draft.foundedAt).toBeNull()
|
||||||
|
expect(draft.employeesCount).toBeNull()
|
||||||
|
expect(draft.volumeForecast).toBeNull()
|
||||||
|
expect(draft.description).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('mapAccountingFormDraft — pre-remplissage onglet Comptabilite', () => {
|
||||||
|
it('extrait les scalaires et les IRI des referentiels embarques', () => {
|
||||||
|
const draft = mapAccountingFormDraft({
|
||||||
|
'@id': '/api/suppliers/85', id: 85,
|
||||||
|
siren: '123456789', accountNumber: 'F0001', nTva: 'FR00123456789',
|
||||||
|
tvaMode: { '@id': '/api/tva_modes/30', label: 'France (ventes)' },
|
||||||
|
paymentType: '/api/payment_types/14',
|
||||||
|
} as SupplierDetail)
|
||||||
|
expect(draft.siren).toBe('123456789')
|
||||||
|
expect(draft.tvaModeIri).toBe('/api/tva_modes/30')
|
||||||
|
expect(draft.paymentTypeIri).toBe('/api/payment_types/14')
|
||||||
|
expect(draft.bankIri).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('cles comptables absentes (gating par omission) -> scalaires/IRI null', () => {
|
||||||
|
const draft = mapAccountingFormDraft({ '@id': '/api/suppliers/1', id: 1 } as SupplierDetail)
|
||||||
|
expect(draft.siren).toBeNull()
|
||||||
|
expect(draft.tvaModeIri).toBeNull()
|
||||||
|
expect(draft.bankIri).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('resolveTabEditability — gating par role (matrice § 2.7)', () => {
|
||||||
|
it('Admin : tout editable', () => {
|
||||||
|
expect(resolveTabEditability({ canManage: true, canAccountingView: true, canAccountingManage: true }))
|
||||||
|
.toEqual({ businessEditable: true, accountingVisible: true, accountingEditable: true })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('Bureau / Commerciale (manage seul) : metier editable, Comptabilite masquee', () => {
|
||||||
|
expect(resolveTabEditability({ canManage: true, canAccountingView: false, canAccountingManage: false }))
|
||||||
|
.toEqual({ businessEditable: true, accountingVisible: false, accountingEditable: false })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('Compta (accounting seul) : metier readonly, Comptabilite editable', () => {
|
||||||
|
expect(resolveTabEditability({ canManage: false, canAccountingView: true, canAccountingManage: true }))
|
||||||
|
.toEqual({ businessEditable: false, accountingVisible: true, accountingEditable: true })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('Sans permission d\'edition : rien d\'editable', () => {
|
||||||
|
expect(resolveTabEditability({ canManage: false, canAccountingView: false, canAccountingManage: false }))
|
||||||
|
.toEqual({ businessEditable: false, accountingVisible: false, accountingEditable: false })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -293,6 +293,21 @@ export function referentialOptionOf(relation: Relation): SelectOption[] {
|
|||||||
return [{ value: relation['@id'], label }]
|
return [{ value: relation['@id'], label }]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Code metier d'un referentiel embarque (ex: PaymentType.code = 'LCR' / 'VIREMENT'),
|
||||||
|
* ou null si la relation est absente / serialisee en IRI nu. Type-safe : la branche
|
||||||
|
* chaine (IRI nu) et l'absence sont court-circuitees avant l'acces au code. Sert a
|
||||||
|
* conditionner l'affichage selon le type de reglement courant (ERP-121 : RIB masques
|
||||||
|
* hors-LCR en consultation).
|
||||||
|
*/
|
||||||
|
export function paymentTypeCodeOf(relation: Relation): string | null {
|
||||||
|
if (!relation || typeof relation === 'string') {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return (relation.code as string | undefined) ?? null
|
||||||
|
}
|
||||||
|
|
||||||
/** Vue d'une adresse (brouillon + options de select propres a l'adresse). */
|
/** Vue d'une adresse (brouillon + options de select propres a l'adresse). */
|
||||||
export function mapAddressView(address: AddressRead): AddressView {
|
export function mapAddressView(address: AddressRead): AddressView {
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ import {
|
|||||||
} from '~/modules/commercial/utils/clientConsultation'
|
} from '~/modules/commercial/utils/clientConsultation'
|
||||||
import {
|
import {
|
||||||
ADDRESS_REQUIRED_NON_NULLABLE_KEYS,
|
ADDRESS_REQUIRED_NON_NULLABLE_KEYS,
|
||||||
|
blankEmptyRequired,
|
||||||
MAIN_REQUIRED_NON_NULLABLE_KEYS,
|
MAIN_REQUIRED_NON_NULLABLE_KEYS,
|
||||||
omitEmptyRequired,
|
omitEmptyRequired,
|
||||||
RIB_REQUIRED_NON_NULLABLE_KEYS,
|
RIB_REQUIRED_NON_NULLABLE_KEYS,
|
||||||
@@ -139,12 +140,35 @@ export function mapAccountingFormDraft(client: ClientDetail): AccountingFormDraf
|
|||||||
|
|
||||||
// ── Scoping strict des payloads PATCH ────────────────────────────────────────
|
// ── Scoping strict des payloads PATCH ────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Options de construction d'un payload d'ecriture.
|
||||||
|
* - `forUpdate: false` (defaut, CREATION/POST) : champs requis vides OMIS -> 422
|
||||||
|
* NotBlank (le back ne reçoit pas la cle, la propriete garde son defaut).
|
||||||
|
* - `forUpdate: true` (EDITION/PATCH d'une ligne existante) : champs requis vides
|
||||||
|
* envoyes en `''` -> 422 NotBlank (sinon une cle omise laisse la valeur serveur
|
||||||
|
* inchangee, faux 200 — cf. blankEmptyRequired).
|
||||||
|
*/
|
||||||
|
export interface BuildPayloadOptions {
|
||||||
|
forUpdate?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Selectionne le finaliseur des champs requis selon création (omit) vs édition (blank). */
|
||||||
|
function finalizeRequired<T extends Record<string, unknown>>(
|
||||||
|
payload: T,
|
||||||
|
requiredKeys: readonly string[],
|
||||||
|
options: BuildPayloadOptions,
|
||||||
|
): T {
|
||||||
|
return options.forUpdate
|
||||||
|
? blankEmptyRequired(payload, requiredKeys)
|
||||||
|
: omitEmptyRequired(payload, requiredKeys)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Payload du bloc principal — groupe client:write:main UNIQUEMENT. La relation
|
* Payload du bloc principal — groupe client:write:main UNIQUEMENT. La relation
|
||||||
* Distributeur/Courtier est mutuellement exclusive (RG-1.03) : on ne renseigne
|
* Distributeur/Courtier est mutuellement exclusive (RG-1.03) : on ne renseigne
|
||||||
* que la FK correspondant au type choisi, l'autre est forcee a null.
|
* que la FK correspondant au type choisi, l'autre est forcee a null.
|
||||||
*/
|
*/
|
||||||
export function buildMainPayload(main: MainFormDraft): Record<string, unknown> {
|
export function buildMainPayload(main: MainFormDraft, options: BuildPayloadOptions = {}): Record<string, unknown> {
|
||||||
// companyName omis si vide -> 422 NotBlank au lieu d'un 400 de type (ERP-119).
|
// companyName omis si vide -> 422 NotBlank au lieu d'un 400 de type (ERP-119).
|
||||||
// relationType : champ transitoire (non persiste cote back) qui porte
|
// relationType : champ transitoire (non persiste cote back) qui porte
|
||||||
// l'intention UI « ce client depend d'un distributeur / courtier ». Il sert
|
// l'intention UI « ce client depend d'un distributeur / courtier ». Il sert
|
||||||
@@ -152,14 +176,14 @@ export function buildMainPayload(main: MainFormDraft): Record<string, unknown> {
|
|||||||
// la FK correspondante devient obligatoire -> 422 sur distributor / broker.
|
// la FK correspondante devient obligatoire -> 422 sur distributor / broker.
|
||||||
// Sans equivalent derivable cote back (FK nullable), c'est la seule facon de
|
// Sans equivalent derivable cote back (FK nullable), c'est la seule facon de
|
||||||
// rester sur « on soumet, le back tranche » plutot qu'une garde front-only.
|
// rester sur « on soumet, le back tranche » plutot qu'une garde front-only.
|
||||||
return omitEmptyRequired({
|
return finalizeRequired({
|
||||||
companyName: main.companyName,
|
companyName: main.companyName,
|
||||||
categories: main.categoryIris,
|
categories: main.categoryIris,
|
||||||
relationType: main.relationType,
|
relationType: main.relationType,
|
||||||
distributor: main.relationType === 'distributeur' ? main.distributorIri : null,
|
distributor: main.relationType === 'distributeur' ? main.distributorIri : null,
|
||||||
broker: main.relationType === 'courtier' ? main.brokerIri : null,
|
broker: main.relationType === 'courtier' ? main.brokerIri : null,
|
||||||
triageService: main.triageService,
|
triageService: main.triageService,
|
||||||
}, MAIN_REQUIRED_NON_NULLABLE_KEYS)
|
}, MAIN_REQUIRED_NON_NULLABLE_KEYS, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Payload de l'onglet Information — groupe client:write:information UNIQUEMENT. */
|
/** Payload de l'onglet Information — groupe client:write:information UNIQUEMENT. */
|
||||||
@@ -211,9 +235,10 @@ export function buildContactPayload(contact: ContactFormDraft): Record<string, u
|
|||||||
export function buildAddressPayload(
|
export function buildAddressPayload(
|
||||||
address: AddressFormDraft,
|
address: AddressFormDraft,
|
||||||
isBillingEmailRequired: boolean,
|
isBillingEmailRequired: boolean,
|
||||||
|
options: BuildPayloadOptions = {},
|
||||||
): Record<string, unknown> {
|
): Record<string, unknown> {
|
||||||
// postalCode / city / street omis si vides -> 422 NotBlank (ERP-119).
|
// postalCode / city / street : omis a la creation, `''` en edition -> 422 NotBlank (ERP-119).
|
||||||
return omitEmptyRequired({
|
return finalizeRequired({
|
||||||
isProspect: address.isProspect,
|
isProspect: address.isProspect,
|
||||||
isDelivery: address.isDelivery,
|
isDelivery: address.isDelivery,
|
||||||
isBilling: address.isBilling,
|
isBilling: address.isBilling,
|
||||||
@@ -229,18 +254,18 @@ export function buildAddressPayload(
|
|||||||
contacts: address.contactIris,
|
contacts: address.contactIris,
|
||||||
billingEmail: isBillingEmailRequired ? (address.billingEmail || null) : null,
|
billingEmail: isBillingEmailRequired ? (address.billingEmail || null) : null,
|
||||||
billingEmailSecondary: isBillingEmailRequired && address.hasSecondaryBillingEmail ? (address.billingEmailSecondary || null) : null,
|
billingEmailSecondary: isBillingEmailRequired && address.hasSecondaryBillingEmail ? (address.billingEmailSecondary || null) : null,
|
||||||
}, ADDRESS_REQUIRED_NON_NULLABLE_KEYS)
|
}, ADDRESS_REQUIRED_NON_NULLABLE_KEYS, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Payload d'un RIB (sous-ressource client_rib). */
|
/** Payload d'un RIB (sous-ressource client_rib). */
|
||||||
export function buildRibPayload(rib: RibFormDraft): Record<string, unknown> {
|
export function buildRibPayload(rib: RibFormDraft, options: BuildPayloadOptions = {}): Record<string, unknown> {
|
||||||
// label / bic / iban omis si vides -> 422 NotBlank au lieu d'un 400 de type
|
// label / bic / iban : omis a la creation, `''` en edition -> 422 NotBlank au lieu
|
||||||
// sur un RIB partiel (ex. IBAN seul). ERP-119.
|
// d'un 400 de type (ou d'un faux 200 PATCH qui garderait l'ancienne valeur). ERP-119.
|
||||||
return omitEmptyRequired({
|
return finalizeRequired({
|
||||||
label: rib.label,
|
label: rib.label,
|
||||||
bic: rib.bic,
|
bic: rib.bic,
|
||||||
iban: rib.iban,
|
iban: rib.iban,
|
||||||
}, RIB_REQUIRED_NON_NULLABLE_KEYS)
|
}, RIB_REQUIRED_NON_NULLABLE_KEYS, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Gating par permission ────────────────────────────────────────────────────
|
// ── Gating par permission ────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -419,3 +419,28 @@ export function omitEmptyRequired<T extends Record<string, unknown>>(
|
|||||||
|
|
||||||
return payload
|
return payload
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Variante PATCH (edition d'une ligne EXISTANTE) : remplace les cles requises
|
||||||
|
* laissees vides par une chaine vide `''` au lieu de les OMETTRE.
|
||||||
|
*
|
||||||
|
* Pourquoi pas `omitEmptyRequired` en edition : un PATCH a semantique merge — une
|
||||||
|
* cle absente laisse la valeur serveur INCHANGEE. Vider un champ requis puis valider
|
||||||
|
* renverrait alors un 200 trompeur (l'ancienne valeur est conservee). En envoyant
|
||||||
|
* `''` (chaine valide), on evite le 400 de type (« must be string, NULL given ») et
|
||||||
|
* le Validator `NotBlank(trim)` rejette la valeur -> 422 avec propertyPath, mappee
|
||||||
|
* inline sous le champ. Mute et retourne le payload.
|
||||||
|
*/
|
||||||
|
export function blankEmptyRequired<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 === '') {
|
||||||
|
(payload as Record<string, unknown>)[key] = ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return payload
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,316 @@
|
|||||||
|
/**
|
||||||
|
* Helpers purs de l'ecran « Consultation fournisseur » (M2 Commercial, lecture
|
||||||
|
* seule). Miroir de `clientConsultation.ts` (M1), adapte aux differences M2.
|
||||||
|
*
|
||||||
|
* Mappent le payload `GET /api/suppliers/{id}` (relations embarquees, cf. groupe
|
||||||
|
* `supplier:item:read` + `supplier:read:accounting`) vers les brouillons « plats »
|
||||||
|
* partages avec les blocs reutilisables `SupplierContactBlock` / `SupplierAddressBlock`
|
||||||
|
* et l'onglet Comptabilite. Ne touchent ni a l'API ni a l'etat reactif : testables
|
||||||
|
* unitairement (cf. supplierConsultation.spec.ts).
|
||||||
|
*
|
||||||
|
* Rappels de contrat back (verifies sur le JSON reel fige — ERP-92, spec-back § 4.0.bis) :
|
||||||
|
* - les relations ManyToOne (tvaMode/paymentDelay/paymentType/bank) sont
|
||||||
|
* serialisees en OBJETS embarques (`{id, code, label}`), pas en IRI nu ;
|
||||||
|
* - les champs nuls sont OMIS du JSON (skip_null_values) → toujours lire avec `?? null` ;
|
||||||
|
* - les champs comptables et `ribs` sont TOTALEMENT ABSENTS (cle omise, pas `null`)
|
||||||
|
* sans permission accounting.view (gate serveur via SupplierReadGroupContextBuilder).
|
||||||
|
*
|
||||||
|
* Differences M2 vs M1 :
|
||||||
|
* - Adresse via enum `addressType` (PROSPECT/DEPART/RENDU, RG-2.09) — pas de
|
||||||
|
* drapeaux isProspect/isDelivery/isBilling.
|
||||||
|
* - Adresse : champs specifiques fournisseur `bennes` (nombre) et `triageProvider`.
|
||||||
|
* Pas d'email de facturation.
|
||||||
|
* - Information : champ specifique fournisseur `volumeForecast`.
|
||||||
|
* - Pas de relation Distributeur/Courtier ni de triage sur le bloc principal.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { formatPhoneFR } from '~/shared/utils/phone'
|
||||||
|
import {
|
||||||
|
emptyAddress,
|
||||||
|
type SupplierAddressFormDraft,
|
||||||
|
type SupplierAddressType,
|
||||||
|
type SupplierContactFormDraft,
|
||||||
|
type SupplierRibFormDraft,
|
||||||
|
} from '~/modules/commercial/types/supplierForm'
|
||||||
|
|
||||||
|
/** Reference Hydra embarquee minimale (@id toujours present). */
|
||||||
|
export interface HydraRef {
|
||||||
|
'@id': string
|
||||||
|
[key: string]: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Une relation peut etre embarquee (objet), un IRI nu (chaine) ou absente. */
|
||||||
|
export type Relation = HydraRef | string | null | undefined
|
||||||
|
|
||||||
|
/** Site embarque dans une adresse (groupe site:read). */
|
||||||
|
export interface SiteRead extends HydraRef {
|
||||||
|
name?: string
|
||||||
|
color?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Categorie embarquee (groupe category:read). */
|
||||||
|
export interface CategoryRead extends HydraRef {
|
||||||
|
code?: string
|
||||||
|
name?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Contact embarque (groupe supplier_contact:read). */
|
||||||
|
export interface ContactRead extends HydraRef {
|
||||||
|
id: number
|
||||||
|
firstName?: string | null
|
||||||
|
lastName?: string | null
|
||||||
|
jobTitle?: string | null
|
||||||
|
phonePrimary?: string | null
|
||||||
|
phoneSecondary?: string | null
|
||||||
|
email?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Adresse embarquee (groupe supplier_address:read). */
|
||||||
|
export interface AddressRead extends HydraRef {
|
||||||
|
id: number
|
||||||
|
addressType?: SupplierAddressType | null
|
||||||
|
country?: string | null
|
||||||
|
postalCode?: string | null
|
||||||
|
city?: string | null
|
||||||
|
street?: string | null
|
||||||
|
streetComplement?: string | null
|
||||||
|
bennes?: number | null
|
||||||
|
triageProvider?: boolean
|
||||||
|
sites?: SiteRead[]
|
||||||
|
categories?: CategoryRead[]
|
||||||
|
// L'embed M2M des contacts d'adresse peut etre un objet (partiel) ou un IRI nu.
|
||||||
|
contacts?: Array<HydraRef | string>
|
||||||
|
}
|
||||||
|
|
||||||
|
/** RIB embarque (groupe supplier:read:accounting, present ssi accounting.view). */
|
||||||
|
export interface RibRead extends HydraRef {
|
||||||
|
id: number
|
||||||
|
label?: string | null
|
||||||
|
bic?: string | null
|
||||||
|
iban?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detail d'un fournisseur tel que renvoye par `GET /api/suppliers/{id}`. Tous les
|
||||||
|
* champs sont optionnels : skip_null_values cote serveur et gating accounting
|
||||||
|
* peuvent omettre n'importe quelle cle.
|
||||||
|
*/
|
||||||
|
export interface SupplierDetail extends HydraRef {
|
||||||
|
id: number
|
||||||
|
companyName?: string | null
|
||||||
|
isArchived?: boolean
|
||||||
|
categories?: CategoryRead[]
|
||||||
|
contacts?: ContactRead[]
|
||||||
|
addresses?: AddressRead[]
|
||||||
|
ribs?: RibRead[]
|
||||||
|
// Onglet Information
|
||||||
|
description?: string | null
|
||||||
|
competitors?: string | null
|
||||||
|
foundedAt?: string | null
|
||||||
|
employeesCount?: number | null
|
||||||
|
revenueAmount?: string | null
|
||||||
|
profitAmount?: string | null
|
||||||
|
directorName?: string | null
|
||||||
|
/** Volume previsionnel (entier, specifique fournisseur). */
|
||||||
|
volumeForecast?: number | null
|
||||||
|
// Onglet Comptabilite (present ssi accounting.view)
|
||||||
|
siren?: string | null
|
||||||
|
accountNumber?: string | null
|
||||||
|
nTva?: string | null
|
||||||
|
tvaMode?: Relation
|
||||||
|
paymentDelay?: Relation
|
||||||
|
paymentType?: Relation
|
||||||
|
bank?: Relation
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Etat « plat » de l'onglet Comptabilite (miroir lecture du formulaire). */
|
||||||
|
export interface AccountingDraft {
|
||||||
|
siren: string | null
|
||||||
|
accountNumber: string | null
|
||||||
|
nTva: string | null
|
||||||
|
tvaModeIri: string | null
|
||||||
|
paymentDelayIri: string | null
|
||||||
|
paymentTypeIri: string | null
|
||||||
|
bankIri: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Option de select ({ value, label }) construite a partir de l'embed. */
|
||||||
|
export interface SelectOption {
|
||||||
|
value: string
|
||||||
|
label: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Option de categorie enrichie de son code (compatible CategoryOption des blocs). */
|
||||||
|
export interface CategorySelectOption extends SelectOption {
|
||||||
|
code: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Vue d'une adresse pour la consultation : le brouillon + ses options de select
|
||||||
|
* construites a partir de l'embed (sites/categories propres a CETTE adresse).
|
||||||
|
*/
|
||||||
|
export interface AddressView {
|
||||||
|
draft: SupplierAddressFormDraft
|
||||||
|
siteOptions: SelectOption[]
|
||||||
|
categoryOptions: CategorySelectOption[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Extrait l'IRI d'une relation (objet embarque, IRI nu, ou null si absente). */
|
||||||
|
export function iriOf(relation: Relation): string | null {
|
||||||
|
if (relation === null || relation === undefined) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
if (typeof relation === 'string') {
|
||||||
|
return relation
|
||||||
|
}
|
||||||
|
return relation['@id'] ?? null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mappe un contact embarque vers un brouillon (telephones formates XX XX XX XX XX). */
|
||||||
|
export function mapContactToDraft(contact: ContactRead): SupplierContactFormDraft {
|
||||||
|
const phoneSecondary = contact.phoneSecondary ?? null
|
||||||
|
return {
|
||||||
|
id: contact.id,
|
||||||
|
iri: contact['@id'] ?? null,
|
||||||
|
firstName: contact.firstName ?? null,
|
||||||
|
lastName: contact.lastName ?? null,
|
||||||
|
jobTitle: contact.jobTitle ?? null,
|
||||||
|
phonePrimary: contact.phonePrimary ? formatPhoneFR(contact.phonePrimary) : null,
|
||||||
|
phoneSecondary: phoneSecondary ? formatPhoneFR(phoneSecondary) : null,
|
||||||
|
email: contact.email ?? null,
|
||||||
|
hasSecondaryPhone: phoneSecondary !== null && phoneSecondary !== '',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mappe une adresse embarquee vers un brouillon (IRI extraits des sous-collections).
|
||||||
|
* `bennes` (entier) est converti en chaine pour MalioInputNumber (defaut « 0 »).
|
||||||
|
*/
|
||||||
|
export function mapAddressToDraft(address: AddressRead): SupplierAddressFormDraft {
|
||||||
|
return {
|
||||||
|
id: address.id,
|
||||||
|
addressType: address.addressType ?? null,
|
||||||
|
country: address.country ?? 'France',
|
||||||
|
postalCode: address.postalCode ?? null,
|
||||||
|
city: address.city ?? null,
|
||||||
|
street: address.street ?? null,
|
||||||
|
streetComplement: address.streetComplement ?? null,
|
||||||
|
categoryIris: (address.categories ?? []).map(c => c['@id']),
|
||||||
|
siteIris: (address.sites ?? []).map(s => s['@id']),
|
||||||
|
contactIris: (address.contacts ?? []).map(c => (typeof c === 'string' ? c : c['@id'])),
|
||||||
|
bennes: address.bennes != null ? String(address.bennes) : '0',
|
||||||
|
triageProvider: address.triageProvider ?? false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mappe un RIB embarque vers un brouillon. */
|
||||||
|
export function mapRibToDraft(rib: RibRead): SupplierRibFormDraft {
|
||||||
|
return {
|
||||||
|
id: rib.id,
|
||||||
|
label: rib.label ?? null,
|
||||||
|
bic: rib.bic ?? null,
|
||||||
|
iban: rib.iban ?? null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mappe les champs comptables du fournisseur (scalaires + IRI des referentiels). */
|
||||||
|
export function mapAccountingDraft(supplier: SupplierDetail): AccountingDraft {
|
||||||
|
return {
|
||||||
|
siren: supplier.siren ?? null,
|
||||||
|
accountNumber: supplier.accountNumber ?? null,
|
||||||
|
nTva: supplier.nTva ?? null,
|
||||||
|
tvaModeIri: iriOf(supplier.tvaMode),
|
||||||
|
paymentDelayIri: iriOf(supplier.paymentDelay),
|
||||||
|
paymentTypeIri: iriOf(supplier.paymentType),
|
||||||
|
bankIri: iriOf(supplier.bank),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Options de categories (value=IRI, label=nom, code) construites depuis l'embed.
|
||||||
|
* Source role-independante : evite de dependre de `GET /categories` (403 pour les
|
||||||
|
* roles metier non-admin), qui laisserait les libelles vides.
|
||||||
|
*/
|
||||||
|
export function categoryOptionsOf(categories: CategoryRead[] | undefined): CategorySelectOption[] {
|
||||||
|
return (categories ?? []).map(c => ({
|
||||||
|
value: c['@id'],
|
||||||
|
label: c.name ?? c.code ?? c['@id'],
|
||||||
|
code: c.code ?? '',
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Options de sites (value=IRI, label=nom) construites depuis l'embed d'une adresse. */
|
||||||
|
export function siteOptionsOf(sites: SiteRead[] | undefined): SelectOption[] {
|
||||||
|
return (sites ?? []).map(s => ({ value: s['@id'], label: s.name ?? s['@id'] }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Options de contacts (value=IRI, label=nom complet ou email) depuis l'embed fournisseur. */
|
||||||
|
export function contactOptionsOf(contacts: ContactRead[] | undefined): SelectOption[] {
|
||||||
|
return (contacts ?? []).map(c => ({
|
||||||
|
value: c['@id'],
|
||||||
|
label: [c.firstName, c.lastName].filter(Boolean).join(' ') || (c.email ?? c['@id']),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Liste a une seule option (ou vide) construite depuis un referentiel embarque
|
||||||
|
* (TvaMode / PaymentDelay / PaymentType / Bank) pour alimenter un MalioSelect en
|
||||||
|
* lecture seule. Le libelle vient de l'embed (`label` ou `name`), jamais d'un
|
||||||
|
* `GET` de referentiel — l'affichage reste correct quel que soit le role.
|
||||||
|
*/
|
||||||
|
export function referentialOptionOf(relation: Relation): SelectOption[] {
|
||||||
|
if (!relation || typeof relation === 'string') {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
const label = (relation.label as string | undefined)
|
||||||
|
?? (relation.name as string | undefined)
|
||||||
|
?? relation['@id']
|
||||||
|
return [{ value: relation['@id'], label }]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Code metier d'un referentiel embarque (ex: PaymentType.code = 'LCR' / 'VIREMENT'),
|
||||||
|
* ou null si la relation est absente / serialisee en IRI nu. Type-safe : la branche
|
||||||
|
* chaine (IRI nu) et l'absence sont court-circuitees avant l'acces au code. Sert a
|
||||||
|
* conditionner l'affichage selon le type de reglement courant (ERP-121 : RIB masques
|
||||||
|
* hors-LCR en consultation).
|
||||||
|
*/
|
||||||
|
export function paymentTypeCodeOf(relation: Relation): string | null {
|
||||||
|
if (!relation || typeof relation === 'string') {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return (relation.code as string | undefined) ?? null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Vue d'une adresse (brouillon + options de select propres a l'adresse). */
|
||||||
|
export function mapAddressView(address: AddressRead): AddressView {
|
||||||
|
return {
|
||||||
|
draft: mapAddressToDraft(address),
|
||||||
|
siteOptions: siteOptionsOf(address.sites),
|
||||||
|
categoryOptions: categoryOptionsOf(address.categories),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bouton « Modifier » : visible si l'utilisateur peut editer au moins un onglet
|
||||||
|
* — `manage` (formulaire/onglets metier) OU `accounting.manage` (le role Compta
|
||||||
|
* doit pouvoir ouvrir l'edition pour son onglet Comptabilite). Le readonly fin
|
||||||
|
* par onglet est gere sur l'ecran d'edition (96).
|
||||||
|
*/
|
||||||
|
export function canEditSupplier(canAny: (codes: string[]) => boolean): boolean {
|
||||||
|
return canAny(['commercial.suppliers.manage', 'commercial.suppliers.accounting.manage'])
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bouton « Archiver » : permission archive ET fournisseur encore actif. */
|
||||||
|
export function showArchiveAction(can: (code: string) => boolean, isArchived: boolean): boolean {
|
||||||
|
return can('commercial.suppliers.archive') && !isArchived
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bouton « Restaurer » : permission archive ET fournisseur deja archive. */
|
||||||
|
export function showRestoreAction(can: (code: string) => boolean, isArchived: boolean): boolean {
|
||||||
|
return can('commercial.suppliers.archive') && isArchived
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Brouillon d'adresse vierge (reexport pour la page : 1 bloc vide si aucune adresse). */
|
||||||
|
export { emptyAddress }
|
||||||
@@ -1,19 +1,24 @@
|
|||||||
/**
|
/**
|
||||||
* Helpers purs de payload de l'ecran « Ajouter un fournisseur » (M2 Commercial),
|
* Helpers purs des ecrans « Ajouter » / « Modifier » un fournisseur (M2
|
||||||
* partages avec la future modification (96) — miroir de `clientEdit.ts` (M1).
|
* Commercial) — miroir de `clientEdit.ts` (M1). Deux responsabilites, toutes deux
|
||||||
|
* testables unitairement (cf. supplierEdit.spec.ts) :
|
||||||
|
* 1. Pre-remplissage : mapper le payload `GET /api/suppliers/{id}` (embed +
|
||||||
|
* scalaires) vers les brouillons « plats » edites par la page de modification.
|
||||||
|
* 2. Scoping STRICT des payloads PATCH (mode strict RG-2.16 / ERP-74) : 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).
|
||||||
*
|
*
|
||||||
* Scoping STRICT des payloads (mode strict, aligne ERP-74/RG) : chaque onglet
|
* Ces helpers ne touchent ni a l'API ni a l'etat reactif.
|
||||||
* 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 {
|
import {
|
||||||
ADDRESS_REQUIRED_NON_NULLABLE_KEYS,
|
ADDRESS_REQUIRED_NON_NULLABLE_KEYS,
|
||||||
|
blankEmptyRequired,
|
||||||
MAIN_REQUIRED_NON_NULLABLE_KEYS,
|
MAIN_REQUIRED_NON_NULLABLE_KEYS,
|
||||||
omitEmptyRequired,
|
omitEmptyRequired,
|
||||||
RIB_REQUIRED_NON_NULLABLE_KEYS,
|
RIB_REQUIRED_NON_NULLABLE_KEYS,
|
||||||
} from '~/modules/commercial/utils/supplierFormRules'
|
} from '~/modules/commercial/utils/supplierFormRules'
|
||||||
|
import { iriOf, type SupplierDetail } from '~/modules/commercial/utils/supplierConsultation'
|
||||||
import type {
|
import type {
|
||||||
SupplierAddressFormDraft,
|
SupplierAddressFormDraft,
|
||||||
SupplierContactFormDraft,
|
SupplierContactFormDraft,
|
||||||
@@ -53,15 +58,118 @@ export interface AccountingFormDraft {
|
|||||||
bankIri: string | null
|
bankIri: string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Permissions de l'utilisateur courant pertinentes pour l'edition d'un fournisseur. */
|
||||||
|
export interface SupplierEditAbilities {
|
||||||
|
/** `commercial.suppliers.manage` : bloc principal + onglets metier. */
|
||||||
|
canManage: boolean
|
||||||
|
/** `commercial.suppliers.accounting.view` : visibilite de l'onglet Comptabilite. */
|
||||||
|
canAccountingView: boolean
|
||||||
|
/** `commercial.suppliers.accounting.manage` : edition de l'onglet Comptabilite. */
|
||||||
|
canAccountingManage: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Editabilite resolue par zone d'onglet (deduite des permissions). */
|
||||||
|
export interface TabEditability {
|
||||||
|
/** Bloc principal + onglets Information / Contacts / Adresses editables. */
|
||||||
|
businessEditable: boolean
|
||||||
|
/** Onglet Comptabilite present (affiche). */
|
||||||
|
accountingVisible: boolean
|
||||||
|
/** Onglet Comptabilite editable. */
|
||||||
|
accountingEditable: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Pre-remplissage (GET detail -> brouillons) ──────────────────────────────
|
||||||
|
|
||||||
|
/** Mappe le detail fournisseur vers le brouillon du bloc principal. */
|
||||||
|
export function mapMainDraft(supplier: SupplierDetail): MainFormDraft {
|
||||||
|
return {
|
||||||
|
companyName: supplier.companyName ?? null,
|
||||||
|
categoryIris: (supplier.categories ?? []).map(c => c['@id']),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mappe le detail fournisseur vers le brouillon de l'onglet Information. */
|
||||||
|
export function mapInformationDraft(supplier: SupplierDetail): InformationFormDraft {
|
||||||
|
return {
|
||||||
|
description: supplier.description ?? null,
|
||||||
|
competitors: supplier.competitors ?? null,
|
||||||
|
// MalioDate attend strictement YYYY-MM-DD : on tronque l'ISO datetime.
|
||||||
|
foundedAt: supplier.foundedAt ? supplier.foundedAt.slice(0, 10) : null,
|
||||||
|
employeesCount: supplier.employeesCount != null ? String(supplier.employeesCount) : null,
|
||||||
|
revenueAmount: supplier.revenueAmount ?? null,
|
||||||
|
profitAmount: supplier.profitAmount ?? null,
|
||||||
|
directorName: supplier.directorName ?? null,
|
||||||
|
// Volume previsionnel (entier, specifique fournisseur) en chaine pour la saisie.
|
||||||
|
volumeForecast: supplier.volumeForecast != null ? String(supplier.volumeForecast) : null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mappe les champs comptables du detail vers le brouillon de l'onglet (scalaires + IRI). */
|
||||||
|
export function mapAccountingFormDraft(supplier: SupplierDetail): AccountingFormDraft {
|
||||||
|
return {
|
||||||
|
siren: supplier.siren ?? null,
|
||||||
|
accountNumber: supplier.accountNumber ?? null,
|
||||||
|
nTva: supplier.nTva ?? null,
|
||||||
|
tvaModeIri: iriOf(supplier.tvaMode),
|
||||||
|
paymentDelayIri: iriOf(supplier.paymentDelay),
|
||||||
|
paymentTypeIri: iriOf(supplier.paymentType),
|
||||||
|
bankIri: iriOf(supplier.bank),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resout l'editabilite par zone a partir des permissions (option 1 ERP-74,
|
||||||
|
* miroir UI du re-gating champ-par-champ du SupplierProcessor) :
|
||||||
|
* - bloc principal + Information/Contacts/Adresses : editables ssi `manage` ;
|
||||||
|
* - Comptabilite : visible ssi `accounting.view`, editable ssi `accounting.manage`.
|
||||||
|
*
|
||||||
|
* Produit le comportement attendu :
|
||||||
|
* - Admin : tout editable.
|
||||||
|
* - Bureau / Commerciale (manage, sans accounting) : metier editable, Compta masquee.
|
||||||
|
* - Compta (accounting seul, sans manage) : metier readonly, Compta editable.
|
||||||
|
*/
|
||||||
|
export function resolveTabEditability(abilities: SupplierEditAbilities): TabEditability {
|
||||||
|
return {
|
||||||
|
businessEditable: abilities.canManage,
|
||||||
|
accountingVisible: abilities.canAccountingView,
|
||||||
|
accountingEditable: abilities.canAccountingManage,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Scoping strict des payloads PATCH/POST ──────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Options de construction d'un payload d'ecriture.
|
||||||
|
* - `forUpdate: false` (defaut, CREATION/POST) : les champs requis vides sont OMIS
|
||||||
|
* -> 422 NotBlank a l'insert (le back ne reçoit pas la cle).
|
||||||
|
* - `forUpdate: true` (EDITION/PATCH d'une ligne existante) : les champs requis
|
||||||
|
* vides sont envoyes en `''` -> 422 NotBlank (sinon une cle omise laisse la valeur
|
||||||
|
* serveur inchangee, faux 200 — cf. blankEmptyRequired).
|
||||||
|
*/
|
||||||
|
export interface BuildPayloadOptions {
|
||||||
|
forUpdate?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Selectionne le finaliseur des champs requis selon création (omit) vs édition (blank). */
|
||||||
|
function finalizeRequired<T extends Record<string, unknown>>(
|
||||||
|
payload: T,
|
||||||
|
requiredKeys: readonly string[],
|
||||||
|
options: BuildPayloadOptions,
|
||||||
|
): T {
|
||||||
|
return options.forUpdate
|
||||||
|
? blankEmptyRequired(payload, requiredKeys)
|
||||||
|
: omitEmptyRequired(payload, requiredKeys)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Payload du bloc principal — groupe supplier:write:main UNIQUEMENT.
|
* Payload du bloc principal — groupe supplier:write:main UNIQUEMENT.
|
||||||
* companyName omis si vide -> 422 NotBlank au lieu d'un 400 de type (ERP-119).
|
* companyName vide -> 422 NotBlank (omis a la creation, `''` en edition — ERP-119).
|
||||||
*/
|
*/
|
||||||
export function buildMainPayload(main: MainFormDraft): Record<string, unknown> {
|
export function buildMainPayload(main: MainFormDraft, options: BuildPayloadOptions = {}): Record<string, unknown> {
|
||||||
return omitEmptyRequired({
|
return finalizeRequired({
|
||||||
companyName: main.companyName,
|
companyName: main.companyName,
|
||||||
categories: main.categoryIris,
|
categories: main.categoryIris,
|
||||||
}, MAIN_REQUIRED_NON_NULLABLE_KEYS)
|
}, MAIN_REQUIRED_NON_NULLABLE_KEYS, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Payload de l'onglet Information — groupe supplier:write:information UNIQUEMENT. */
|
/** Payload de l'onglet Information — groupe supplier:write:information UNIQUEMENT. */
|
||||||
@@ -116,8 +224,8 @@ export function buildContactPayload(contact: SupplierContactFormDraft): Record<s
|
|||||||
* `bennes` (entier, 0 par defaut) + `triageProvider` (booleen). Pas d'email de
|
* `bennes` (entier, 0 par defaut) + `triageProvider` (booleen). Pas d'email de
|
||||||
* facturation (difference M1).
|
* facturation (difference M1).
|
||||||
*/
|
*/
|
||||||
export function buildAddressPayload(address: SupplierAddressFormDraft): Record<string, unknown> {
|
export function buildAddressPayload(address: SupplierAddressFormDraft, options: BuildPayloadOptions = {}): Record<string, unknown> {
|
||||||
return omitEmptyRequired({
|
return finalizeRequired({
|
||||||
addressType: address.addressType,
|
addressType: address.addressType,
|
||||||
country: address.country,
|
country: address.country,
|
||||||
postalCode: address.postalCode || null,
|
postalCode: address.postalCode || null,
|
||||||
@@ -129,14 +237,14 @@ export function buildAddressPayload(address: SupplierAddressFormDraft): Record<s
|
|||||||
contacts: address.contactIris,
|
contacts: address.contactIris,
|
||||||
bennes: address.bennes !== null && address.bennes !== '' ? Number(address.bennes) : null,
|
bennes: address.bennes !== null && address.bennes !== '' ? Number(address.bennes) : null,
|
||||||
triageProvider: address.triageProvider,
|
triageProvider: address.triageProvider,
|
||||||
}, ADDRESS_REQUIRED_NON_NULLABLE_KEYS)
|
}, ADDRESS_REQUIRED_NON_NULLABLE_KEYS, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Payload d'un RIB (sous-ressource supplier_rib). */
|
/** Payload d'un RIB (sous-ressource supplier_rib). */
|
||||||
export function buildRibPayload(rib: SupplierRibFormDraft): Record<string, unknown> {
|
export function buildRibPayload(rib: SupplierRibFormDraft, options: BuildPayloadOptions = {}): Record<string, unknown> {
|
||||||
return omitEmptyRequired({
|
return finalizeRequired({
|
||||||
label: rib.label,
|
label: rib.label,
|
||||||
bic: rib.bic,
|
bic: rib.bic,
|
||||||
iban: rib.iban,
|
iban: rib.iban,
|
||||||
}, RIB_REQUIRED_NON_NULLABLE_KEYS)
|
}, RIB_REQUIRED_NON_NULLABLE_KEYS, options)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -217,3 +217,28 @@ export function omitEmptyRequired<T extends Record<string, unknown>>(
|
|||||||
|
|
||||||
return payload
|
return payload
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Variante PATCH (edition d'une ligne EXISTANTE) : remplace les cles requises
|
||||||
|
* laissees vides par une chaine vide `''` au lieu de les OMETTRE.
|
||||||
|
*
|
||||||
|
* Pourquoi pas `omitEmptyRequired` en edition : un PATCH a semantique merge — une
|
||||||
|
* cle absente laisse la valeur serveur INCHANGEE. Vider un champ requis puis valider
|
||||||
|
* renverrait alors un 200 trompeur (l'ancienne valeur est conservee). En envoyant
|
||||||
|
* `''`, la propriete `?string` est bien deserialisee (pas de 400 de type, contrairement
|
||||||
|
* a `null` sur une colonne non-nullable), puis le Validator `NotBlank(trim)` la rejette
|
||||||
|
* -> 422 avec propertyPath, mappee inline sous le champ. Mute et retourne le payload.
|
||||||
|
*/
|
||||||
|
export function blankEmptyRequired<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 === '') {
|
||||||
|
(payload as Record<string, unknown>)[key] = ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return payload
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace DoctrineMigrations;
|
||||||
|
|
||||||
|
use Doctrine\DBAL\Schema\Schema;
|
||||||
|
use Doctrine\Migrations\AbstractMigration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ERP-116 — Referentiel Pays (Country), 1re iteration : creation de la table
|
||||||
|
* `country` + seed des 7 pays (France, Allemagne, Belgique, Espagne, Italie,
|
||||||
|
* Royaume-Uni, Suisse). Devient la source unique du select pays, en
|
||||||
|
* remplacement de la liste codee en dur cote front.
|
||||||
|
*
|
||||||
|
* Perimetre minimal voulu : code ISO 3166-1 alpha-2 + libelle FR + ordre
|
||||||
|
* d'affichage UNIQUEMENT. Aucune longueur bancaire/fiscale (numero de compte,
|
||||||
|
* IBAN, TVA, BIC, SIREN) a ce stade — iteration ulterieure du meme ticket.
|
||||||
|
*
|
||||||
|
* Pas de FK posee sur les adresses (client_address.country / supplier_address)
|
||||||
|
* a cette etape : ces colonnes restent des chaines libres (« France »...), donc
|
||||||
|
* aucune migration de donnees ni rupture de l'existant.
|
||||||
|
*
|
||||||
|
* Namespace racine `DoctrineMigrations` (regle ABSOLUE Starseed n°11) comme les
|
||||||
|
* migrations M1/M2 du module Commercial : pas de migrations_path modulaire
|
||||||
|
* configure pour Commercial, et le tri par timestamp reste garanti.
|
||||||
|
*
|
||||||
|
* Seed idempotent `ON CONFLICT (code) DO NOTHING` : la table peut deja porter
|
||||||
|
* des donnees en prod lors d'un rejeu. Chaque colonne porte un `COMMENT ON
|
||||||
|
* COLUMN` (regle ABSOLUE n°12, garde-fou ColumnsHaveSqlCommentTest) ; la table
|
||||||
|
* est aussi mirroree dans ColumnCommentsCatalog pour survivre au
|
||||||
|
* `schema:update --force` du setup de test.
|
||||||
|
*/
|
||||||
|
final class Version20260609100000 extends AbstractMigration
|
||||||
|
{
|
||||||
|
public function getDescription(): string
|
||||||
|
{
|
||||||
|
return 'ERP-116 : table country (referentiel pays) + seed des 7 pays.';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function up(Schema $schema): void
|
||||||
|
{
|
||||||
|
$this->addSql(<<<'SQL'
|
||||||
|
CREATE TABLE country (
|
||||||
|
id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
|
||||||
|
code VARCHAR(2) NOT NULL,
|
||||||
|
name VARCHAR(80) NOT NULL,
|
||||||
|
position INT DEFAULT 0 NOT NULL,
|
||||||
|
PRIMARY KEY (id)
|
||||||
|
)
|
||||||
|
SQL);
|
||||||
|
$this->addSql('CREATE UNIQUE INDEX uq_country_code ON country (code)');
|
||||||
|
|
||||||
|
$this->comment('country', '_table', 'Referentiel des pays selectionnables dans les adresses (clients/fournisseurs). Perimetre minimal : code ISO + libelle + ordre (pas de longueurs bancaires/fiscales).');
|
||||||
|
$this->comment('country', 'id', 'Identifiant interne auto-incremente.');
|
||||||
|
$this->comment('country', 'code', 'Code pays ISO 3166-1 alpha-2 (2 lettres MAJUSCULES, ex: FR) — unique (uq_country_code), fige a la creation.');
|
||||||
|
$this->comment('country', 'name', 'Libelle FR du pays (≤ 80 caracteres) — valeur stockee telle quelle dans les adresses (country en chaine libre a ce stade).');
|
||||||
|
$this->comment('country', 'position', 'Ordre d affichage croissant dans le selecteur pays (tri position ASC puis name ASC ; France en tete).');
|
||||||
|
|
||||||
|
// Seed initial. France en tete (position 10) puis ordre alphabetique.
|
||||||
|
// Table fraichement creee, mais ON CONFLICT pour rejouabilite en prod.
|
||||||
|
$this->addSql(<<<'SQL'
|
||||||
|
INSERT INTO country (code, name, position) VALUES
|
||||||
|
('FR', 'France', 10),
|
||||||
|
('DE', 'Allemagne', 20),
|
||||||
|
('BE', 'Belgique', 30),
|
||||||
|
('ES', 'Espagne', 40),
|
||||||
|
('IT', 'Italie', 50),
|
||||||
|
('GB', 'Royaume-Uni', 60),
|
||||||
|
('CH', 'Suisse', 70)
|
||||||
|
ON CONFLICT (code) DO NOTHING
|
||||||
|
SQL);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(Schema $schema): void
|
||||||
|
{
|
||||||
|
$this->addSql('DROP TABLE country');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pose un `COMMENT ON TABLE` (colonne speciale `_table`) ou
|
||||||
|
* `COMMENT ON COLUMN`. Quoting defensif des identifiants + delimiteur $_$
|
||||||
|
* pour ne pas casser sur les apostrophes des descriptions.
|
||||||
|
*/
|
||||||
|
private function comment(string $table, string $column, string $description): void
|
||||||
|
{
|
||||||
|
$quotedTable = '"'.str_replace('"', '""', $table).'"';
|
||||||
|
|
||||||
|
if ('_table' === $column) {
|
||||||
|
$this->addSql(sprintf('COMMENT ON TABLE %s IS $_$%s$_$', $quotedTable, $description));
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->addSql(sprintf(
|
||||||
|
'COMMENT ON COLUMN %s.%s IS $_$%s$_$',
|
||||||
|
$quotedTable,
|
||||||
|
'"'.str_replace('"', '""', $column).'"',
|
||||||
|
$description,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Module\Commercial\Domain\Entity;
|
||||||
|
|
||||||
|
use ApiPlatform\Metadata\ApiResource;
|
||||||
|
use ApiPlatform\Metadata\Get;
|
||||||
|
use ApiPlatform\Metadata\GetCollection;
|
||||||
|
use App\Module\Commercial\Infrastructure\Doctrine\DoctrineCountryRepository;
|
||||||
|
use Doctrine\ORM\Mapping as ORM;
|
||||||
|
use Symfony\Component\Serializer\Attribute\Groups;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pays selectionnable dans les adresses (clients / fournisseurs) : referentiel
|
||||||
|
* statique seede par la migration (France, Allemagne, Belgique, Espagne, Italie,
|
||||||
|
* Royaume-Uni). Remplace la liste de pays jusqu'ici codee en dur cote front.
|
||||||
|
*
|
||||||
|
* Perimetre minimal (ticket ERP-116, 1re iteration) : code ISO + libelle + ordre
|
||||||
|
* d'affichage uniquement. AUCUNE longueur bancaire/fiscale (numero de compte,
|
||||||
|
* IBAN, TVA, BIC, SIREN) a ce stade — ces colonnes feront l'objet d'une iteration
|
||||||
|
* ulterieure du meme ticket.
|
||||||
|
*
|
||||||
|
* Lecture seule : GetCollection + Get uniquement ; POST/PATCH/DELETE -> 405.
|
||||||
|
* Permission alignee sur Bank (referentiel d'adresse partage clients/fournisseurs).
|
||||||
|
* Pas de Timestampable/Blamable (referentiel statique whiteliste dans
|
||||||
|
* EntitiesAreTimestampableBlamableTest::EXCLUDED, comme Bank).
|
||||||
|
*/
|
||||||
|
#[ApiResource(
|
||||||
|
operations: [
|
||||||
|
new GetCollection(
|
||||||
|
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||||
|
normalizationContext: ['groups' => ['country:read']],
|
||||||
|
// Tri par defaut : position ASC (France en tete) puis name ASC.
|
||||||
|
order: ['position' => 'ASC', 'name' => 'ASC'],
|
||||||
|
// Toggle ?pagination=false pour alimenter le select (cf. Bank).
|
||||||
|
paginationClientEnabled: true,
|
||||||
|
),
|
||||||
|
new Get(
|
||||||
|
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||||
|
normalizationContext: ['groups' => ['country:read']],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||||
|
)]
|
||||||
|
#[ORM\Entity(repositoryClass: DoctrineCountryRepository::class)]
|
||||||
|
#[ORM\Table(name: 'country')]
|
||||||
|
#[ORM\UniqueConstraint(name: 'uq_country_code', columns: ['code'])]
|
||||||
|
class Country
|
||||||
|
{
|
||||||
|
#[ORM\Id]
|
||||||
|
#[ORM\GeneratedValue]
|
||||||
|
#[ORM\Column]
|
||||||
|
#[Groups(['country:read'])]
|
||||||
|
private ?int $id = null;
|
||||||
|
|
||||||
|
#[ORM\Column(length: 2)]
|
||||||
|
#[Groups(['country:read'])]
|
||||||
|
private ?string $code = null;
|
||||||
|
|
||||||
|
#[ORM\Column(length: 80)]
|
||||||
|
#[Groups(['country:read'])]
|
||||||
|
private ?string $name = null;
|
||||||
|
|
||||||
|
#[ORM\Column(options: ['default' => 0])]
|
||||||
|
#[Groups(['country:read'])]
|
||||||
|
private int $position = 0;
|
||||||
|
|
||||||
|
public function getId(): ?int
|
||||||
|
{
|
||||||
|
return $this->id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getCode(): ?string
|
||||||
|
{
|
||||||
|
return $this->code;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setCode(string $code): static
|
||||||
|
{
|
||||||
|
$this->code = $code;
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getName(): ?string
|
||||||
|
{
|
||||||
|
return $this->name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setName(string $name): static
|
||||||
|
{
|
||||||
|
$this->name = $name;
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getPosition(): int
|
||||||
|
{
|
||||||
|
return $this->position;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setPosition(int $position): static
|
||||||
|
{
|
||||||
|
$this->position = $position;
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Module\Commercial\Domain\Repository;
|
||||||
|
|
||||||
|
use App\Module\Commercial\Domain\Entity\Country;
|
||||||
|
|
||||||
|
interface CountryRepositoryInterface
|
||||||
|
{
|
||||||
|
public function findById(int $id): ?Country;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retourne tous les pays tries position ASC puis name ASC.
|
||||||
|
*
|
||||||
|
* @return list<Country>
|
||||||
|
*/
|
||||||
|
public function findAllOrdered(): array;
|
||||||
|
}
|
||||||
+44
-3
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
|||||||
namespace App\Module\Commercial\Infrastructure\DataFixtures;
|
namespace App\Module\Commercial\Infrastructure\DataFixtures;
|
||||||
|
|
||||||
use App\Module\Commercial\Domain\Entity\Bank;
|
use App\Module\Commercial\Domain\Entity\Bank;
|
||||||
|
use App\Module\Commercial\Domain\Entity\Country;
|
||||||
use App\Module\Commercial\Domain\Entity\PaymentDelay;
|
use App\Module\Commercial\Domain\Entity\PaymentDelay;
|
||||||
use App\Module\Commercial\Domain\Entity\PaymentType;
|
use App\Module\Commercial\Domain\Entity\PaymentType;
|
||||||
use App\Module\Commercial\Domain\Entity\TvaMode;
|
use App\Module\Commercial\Domain\Entity\TvaMode;
|
||||||
@@ -14,10 +15,11 @@ use Doctrine\Persistence\ObjectManager;
|
|||||||
/**
|
/**
|
||||||
* Fixtures du module Commercial : re-seed des 4 referentiels comptables
|
* Fixtures du module Commercial : re-seed des 4 referentiels comptables
|
||||||
* (tva_mode, payment_delay, payment_type, bank) seedes par la migration M1
|
* (tva_mode, payment_delay, payment_type, bank) seedes par la migration M1
|
||||||
* (Version20260601000000).
|
* (Version20260601000000) + du referentiel pays (country) seede par la
|
||||||
|
* migration ERP-116 (Version20260609100000).
|
||||||
*
|
*
|
||||||
* Pourquoi cette fixture EN PLUS du seed de la migration : depuis ERP-54 ces
|
* Pourquoi cette fixture EN PLUS du seed de la migration : ces tables sont des
|
||||||
* 4 tables sont des entites managees par l'ORM, donc le purger Doctrine les
|
* entites managees par l'ORM, donc le purger Doctrine les
|
||||||
* vide avant chaque `doctrine:fixtures:load`. Sans cette fixture, les
|
* vide avant chaque `doctrine:fixtures:load`. Sans cette fixture, les
|
||||||
* referentiels seedes par la migration disparaitraient apres `make db-reset`
|
* referentiels seedes par la migration disparaitraient apres `make db-reset`
|
||||||
* (0 ligne en dev/test) — cassant les FK Client -> referentiels et les tests
|
* (0 ligne en dev/test) — cassant les FK Client -> referentiels et les tests
|
||||||
@@ -59,15 +61,54 @@ class CommercialReferentialFixtures extends Fixture
|
|||||||
],
|
],
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Referentiel pays (ERP-116) : code ISO alpha-2 => [name, position].
|
||||||
|
* Doit rester aligne sur le seed de la migration Version20260609100000.
|
||||||
|
* Traite a part car Country porte `name` (et non `label`).
|
||||||
|
*
|
||||||
|
* @var array<string, array{string, int}>
|
||||||
|
*/
|
||||||
|
private const COUNTRIES = [
|
||||||
|
'FR' => ['France', 10],
|
||||||
|
'DE' => ['Allemagne', 20],
|
||||||
|
'BE' => ['Belgique', 30],
|
||||||
|
'ES' => ['Espagne', 40],
|
||||||
|
'IT' => ['Italie', 50],
|
||||||
|
'GB' => ['Royaume-Uni', 60],
|
||||||
|
'CH' => ['Suisse', 70],
|
||||||
|
];
|
||||||
|
|
||||||
public function load(ObjectManager $manager): void
|
public function load(ObjectManager $manager): void
|
||||||
{
|
{
|
||||||
foreach (self::REFERENTIALS as $entityClass => $rows) {
|
foreach (self::REFERENTIALS as $entityClass => $rows) {
|
||||||
$this->seedReferential($manager, $entityClass, $rows);
|
$this->seedReferential($manager, $entityClass, $rows);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$this->seedCountries($manager);
|
||||||
|
|
||||||
$manager->flush();
|
$manager->flush();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Upsert idempotent du referentiel pays (lookup par code). Distinct de
|
||||||
|
* seedReferential car Country utilise setName au lieu de setLabel.
|
||||||
|
*/
|
||||||
|
private function seedCountries(ObjectManager $manager): void
|
||||||
|
{
|
||||||
|
$existingByCode = [];
|
||||||
|
foreach ($manager->getRepository(Country::class)->findAll() as $country) {
|
||||||
|
$existingByCode[$country->getCode()] = $country;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (self::COUNTRIES as $code => [$name, $position]) {
|
||||||
|
$country = $existingByCode[$code] ?? new Country();
|
||||||
|
$country->setCode($code);
|
||||||
|
$country->setName($name);
|
||||||
|
$country->setPosition($position);
|
||||||
|
$manager->persist($country);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Upsert idempotent d'un referentiel : indexe l'existant par code puis
|
* Upsert idempotent d'un referentiel : indexe l'existant par code puis
|
||||||
* cree/met a jour chaque entree. Les 4 entites partagent le meme contrat
|
* cree/met a jour chaque entree. Les 4 entites partagent le meme contrat
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Module\Commercial\Infrastructure\Doctrine;
|
||||||
|
|
||||||
|
use App\Module\Commercial\Domain\Entity\Country;
|
||||||
|
use App\Module\Commercial\Domain\Repository\CountryRepositoryInterface;
|
||||||
|
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||||
|
use Doctrine\Persistence\ManagerRegistry;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @extends ServiceEntityRepository<Country>
|
||||||
|
*/
|
||||||
|
class DoctrineCountryRepository extends ServiceEntityRepository implements CountryRepositoryInterface
|
||||||
|
{
|
||||||
|
public function __construct(ManagerRegistry $registry)
|
||||||
|
{
|
||||||
|
parent::__construct($registry, Country::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function findById(int $id): ?Country
|
||||||
|
{
|
||||||
|
return $this->find($id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function findAllOrdered(): array
|
||||||
|
{
|
||||||
|
return $this->createQueryBuilder('c')
|
||||||
|
->orderBy('c.position', 'ASC')
|
||||||
|
->addOrderBy('c.name', 'ASC')
|
||||||
|
->getQuery()
|
||||||
|
->getResult()
|
||||||
|
;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -170,6 +170,14 @@ final class ColumnCommentsCatalog
|
|||||||
'position' => 'Ordre d affichage croissant dans les selecteurs (tri position ASC puis label ASC).',
|
'position' => 'Ordre d affichage croissant dans les selecteurs (tri position ASC puis label ASC).',
|
||||||
],
|
],
|
||||||
|
|
||||||
|
'country' => [
|
||||||
|
'_table' => 'Referentiel des pays selectionnables dans les adresses (clients/fournisseurs). Perimetre minimal : code ISO + libelle + ordre (pas de longueurs bancaires/fiscales).',
|
||||||
|
'id' => 'Identifiant interne auto-incremente.',
|
||||||
|
'code' => 'Code pays ISO 3166-1 alpha-2 (2 lettres MAJUSCULES, ex: FR) — unique (uq_country_code), fige a la creation.',
|
||||||
|
'name' => 'Libelle FR du pays (≤ 80 caracteres) — valeur stockee telle quelle dans les adresses (country en chaine libre a ce stade).',
|
||||||
|
'position' => 'Ordre d affichage croissant dans le selecteur pays (tri position ASC puis name ASC ; France en tete).',
|
||||||
|
],
|
||||||
|
|
||||||
'client' => [
|
'client' => [
|
||||||
'_table' => 'Repertoire clients (M1 Commercial) — entites archivables (is_archived) et soft-deletables (deleted_at, HP M2).',
|
'_table' => 'Repertoire clients (M1 Commercial) — entites archivables (is_archived) et soft-deletables (deleted_at, HP M2).',
|
||||||
'id' => 'Identifiant interne auto-incremente.',
|
'id' => 'Identifiant interne auto-incremente.',
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ namespace App\Tests\Architecture;
|
|||||||
|
|
||||||
use App\Module\Catalog\Domain\Entity\CategoryType;
|
use App\Module\Catalog\Domain\Entity\CategoryType;
|
||||||
use App\Module\Commercial\Domain\Entity\Bank;
|
use App\Module\Commercial\Domain\Entity\Bank;
|
||||||
|
use App\Module\Commercial\Domain\Entity\Country;
|
||||||
use App\Module\Commercial\Domain\Entity\PaymentDelay;
|
use App\Module\Commercial\Domain\Entity\PaymentDelay;
|
||||||
use App\Module\Commercial\Domain\Entity\PaymentType;
|
use App\Module\Commercial\Domain\Entity\PaymentType;
|
||||||
use App\Module\Commercial\Domain\Entity\TvaMode;
|
use App\Module\Commercial\Domain\Entity\TvaMode;
|
||||||
@@ -58,6 +59,8 @@ final class EntitiesAreTimestampableBlamableTest extends TestCase
|
|||||||
* CommercialReferentialFixtures, lecture seule au M1 (HP-M2-2). Pas de
|
* CommercialReferentialFixtures, lecture seule au M1 (HP-M2-2). Pas de
|
||||||
* tracabilite user-driven, meme justification que CategoryType. Cf.
|
* tracabilite user-driven, meme justification que CategoryType. Cf.
|
||||||
* spec-back M1 § 2.6 + § 3.5.
|
* spec-back M1 § 2.6 + § 3.5.
|
||||||
|
* - Country (ERP-116) : referentiel statique des pays (id/code/name/position),
|
||||||
|
* seede par migration, lecture seule. Meme justification que Bank.
|
||||||
*
|
*
|
||||||
* Les futurs referentiels statiques s'ajoutent ici avec une justification.
|
* Les futurs referentiels statiques s'ajoutent ici avec une justification.
|
||||||
*/
|
*/
|
||||||
@@ -71,6 +74,7 @@ final class EntitiesAreTimestampableBlamableTest extends TestCase
|
|||||||
PaymentDelay::class,
|
PaymentDelay::class,
|
||||||
PaymentType::class,
|
PaymentType::class,
|
||||||
Bank::class,
|
Bank::class,
|
||||||
|
Country::class,
|
||||||
];
|
];
|
||||||
|
|
||||||
public function testAllBusinessEntitiesImplementBothInterfaces(): void
|
public function testAllBusinessEntitiesImplementBothInterfaces(): void
|
||||||
|
|||||||
@@ -241,6 +241,72 @@ final class ReferentialApiTest extends AbstractCommercialApiTestCase
|
|||||||
self::assertResponseStatusCodeSame(401);
|
self::assertResponseStatusCodeSame(401);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Referentiel pays (ERP-116) — teste a part des 4 referentiels comptables
|
||||||
|
* car il expose `name` (et non `label`). Memes garanties : 200 + seed des 7
|
||||||
|
* pays, France en tete (position ASC), lecture seule (405), gating (403/401).
|
||||||
|
*/
|
||||||
|
public function testCountriesCollectionReturns200WithSeed(): void
|
||||||
|
{
|
||||||
|
$client = $this->createAdminClient();
|
||||||
|
$response = $client->request('GET', '/api/countries?pagination=false', ['headers' => ['Accept' => self::LD]]);
|
||||||
|
|
||||||
|
self::assertResponseStatusCodeSame(200);
|
||||||
|
|
||||||
|
$members = $response->toArray()['member'];
|
||||||
|
$codes = array_map(static fn (array $m): string => $m['code'], $members);
|
||||||
|
|
||||||
|
foreach (['FR', 'DE', 'BE', 'ES', 'IT', 'GB', 'CH'] as $expected) {
|
||||||
|
self::assertContains($expected, $codes, '/api/countries doit exposer le pays seede '.$expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Le DTO de lecture expose id / code / name / position.
|
||||||
|
$first = $members[0];
|
||||||
|
self::assertArrayHasKey('id', $first);
|
||||||
|
self::assertArrayHasKey('name', $first);
|
||||||
|
self::assertArrayHasKey('position', $first);
|
||||||
|
// Tri par defaut position ASC : France (position 10) en tete.
|
||||||
|
self::assertSame('FR', $first['code'], 'France (FR) doit etre en tete (position 10, tri position ASC).');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testCountriesGetItemReturns200(): void
|
||||||
|
{
|
||||||
|
$client = $this->createAdminClient();
|
||||||
|
|
||||||
|
$first = $client->request('GET', '/api/countries?pagination=false', ['headers' => ['Accept' => self::LD]])
|
||||||
|
->toArray()['member'][0]
|
||||||
|
;
|
||||||
|
|
||||||
|
$client->request('GET', '/api/countries/'.$first['id'], ['headers' => ['Accept' => self::LD]]);
|
||||||
|
self::assertResponseStatusCodeSame(200);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testCountriesPostReturns405(): void
|
||||||
|
{
|
||||||
|
$client = $this->createAdminClient();
|
||||||
|
$client->request('POST', '/api/countries', [
|
||||||
|
'headers' => ['Content-Type' => self::LD],
|
||||||
|
'json' => ['code' => 'XX', 'name' => 'Pays X', 'position' => 1],
|
||||||
|
]);
|
||||||
|
self::assertResponseStatusCodeSame(405);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testCountriesForbiddenWithoutPermission(): void
|
||||||
|
{
|
||||||
|
$creds = $this->createUserWithPermission('core.users.view');
|
||||||
|
$client = $this->authenticatedClient($creds['username'], $creds['password']);
|
||||||
|
|
||||||
|
$client->request('GET', '/api/countries', ['headers' => ['Accept' => self::LD]]);
|
||||||
|
self::assertResponseStatusCodeSame(403);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testCountriesUnauthorizedWhenAnonymous(): void
|
||||||
|
{
|
||||||
|
$client = self::createClient();
|
||||||
|
$client->request('GET', '/api/countries', ['headers' => ['Accept' => self::LD]]);
|
||||||
|
self::assertResponseStatusCodeSame(401);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return iterable<string, array{string, list<string>}>
|
* @return iterable<string, array{string, list<string>}>
|
||||||
*/
|
*/
|
||||||
|
|||||||
Reference in New Issue
Block a user