Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4cf26298e3 |
+1
-1
@@ -1,2 +1,2 @@
|
|||||||
parameters:
|
parameters:
|
||||||
app.version: '0.1.106'
|
app.version: '0.1.104'
|
||||||
|
|||||||
@@ -1,95 +0,0 @@
|
|||||||
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)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
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),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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 && visibleRibs.length > 1"
|
v-if="!accountingReadonly"
|
||||||
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"
|
||||||
@@ -689,7 +689,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, { forUpdate: true }), {
|
const updated = await api.patch<ClientDetail>(`/clients/${clientId}`, buildMainPayload(main), {
|
||||||
headers: { Accept: 'application/ld+json' },
|
headers: { Accept: 'application/ld+json' },
|
||||||
toast: false,
|
toast: false,
|
||||||
})
|
})
|
||||||
@@ -859,10 +859,7 @@ async function submitAddresses(): Promise<void> {
|
|||||||
addresses.value,
|
addresses.value,
|
||||||
addressErrors,
|
addressErrors,
|
||||||
async (address) => {
|
async (address) => {
|
||||||
// Edition d'une adresse existante : champ requis vide envoye en `''`
|
const body = buildAddressPayload(address, isBillingEmailRequired(address))
|
||||||
// (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`,
|
||||||
@@ -953,18 +950,13 @@ async function submitAccounting(): Promise<void> {
|
|||||||
try {
|
try {
|
||||||
// 1) POST/PATCH des RIB d'abord (erreurs inline par ligne, tous les blocs
|
// 1) POST/PATCH des RIB d'abord (erreurs inline par ligne, tous les blocs
|
||||||
// tentes). Le back exige >=1 RIB persiste pour valider une LCR a l'etape 2.
|
// tentes). Le back exige >=1 RIB persiste pour valider une LCR a l'etape 2.
|
||||||
// On ne saute une amorce neuve vide QUE s'il reste un autre RIB soumettable :
|
// Seuls les blocs RIB TOTALEMENT vides sont ignores : un RIB partiel (ex.
|
||||||
// sinon (ex. l'unique RIB existant supprime, remplace par un bloc vide), on la
|
// IBAN seul) est soumis -> 422 NotBlank (label / bic / iban) inline.
|
||||||
// soumet pour declencher la 422 NotBlank inline plutot que de laisser le DELETE
|
|
||||||
// echouer en « dernier RIB d'une LCR » (message plat sans propertyPath).
|
|
||||||
const hasSubmittableRib = ribs.value.some(r => r.id !== null || !isRibBlank(r))
|
|
||||||
const ribHasError = await submitRows(
|
const ribHasError = await submitRows(
|
||||||
ribs.value,
|
ribs.value,
|
||||||
ribErrors,
|
ribErrors,
|
||||||
async (rib) => {
|
async (rib) => {
|
||||||
// Edition d'un RIB existant : champ requis vide envoye en `''` (NotBlank
|
const body = buildRibPayload(rib)
|
||||||
// 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) {
|
if (rib.id === null) {
|
||||||
const created = await api.post<{ id: number }>(
|
const created = await api.post<{ id: number }>(
|
||||||
`/clients/${clientId}/ribs`,
|
`/clients/${clientId}/ribs`,
|
||||||
@@ -978,10 +970,10 @@ async function submitAccounting(): Promise<void> {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
error => showError(error),
|
error => showError(error),
|
||||||
// On ne saute une amorce neuve (id null) totalement vide que si un autre RIB
|
// On ne saute QUE les amorces neuves (id null) totalement vides. Un
|
||||||
// est soumettable. Un RIB existant vide est toujours soumis -> 422 NotBlank
|
// RIB existant vide est soumis -> 422 NotBlank inline (sinon la modif
|
||||||
// inline (sinon la modif serait perdue en silence avec un faux toast succes).
|
// serait perdue en silence avec un faux toast de succes).
|
||||||
rib => hasSubmittableRib && rib.id === null && isRibBlank(rib),
|
rib => rib.id === null && isRibBlank(rib),
|
||||||
)
|
)
|
||||||
if (ribHasError) return
|
if (ribHasError) return
|
||||||
|
|
||||||
|
|||||||
@@ -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 && visibleRibs.length > 1"
|
v-if="!accountingReadonly"
|
||||||
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"
|
||||||
@@ -920,9 +920,8 @@ async function submitAccounting(): Promise<void> {
|
|||||||
try {
|
try {
|
||||||
// 1) POST/PATCH des RIB d'abord (erreurs inline par ligne, tous les blocs
|
// 1) POST/PATCH des RIB d'abord (erreurs inline par ligne, tous les blocs
|
||||||
// tentes). Le back exige >=1 RIB persiste pour valider une LCR a l'etape 2.
|
// tentes). Le back exige >=1 RIB persiste pour valider une LCR a l'etape 2.
|
||||||
// On ne saute une amorce neuve vide QUE s'il reste un autre RIB soumettable :
|
// Seuls les blocs RIB TOTALEMENT vides sont ignores : un RIB partiel (ex.
|
||||||
// sinon (LCR sans aucun RIB rempli) on la soumet -> 422 NotBlank inline.
|
// IBAN seul) est soumis -> 422 NotBlank (label / bic / iban) inline.
|
||||||
const hasSubmittableRib = ribs.value.some(r => r.id !== null || !isRibBlank(r))
|
|
||||||
const ribHasError = await submitRows(
|
const ribHasError = await submitRows(
|
||||||
ribs.value,
|
ribs.value,
|
||||||
ribErrors,
|
ribErrors,
|
||||||
@@ -942,10 +941,10 @@ async function submitAccounting(): Promise<void> {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
error => toast.error({ title: t('commercial.clients.toast.error'), message: apiErrorMessage(error) }),
|
error => toast.error({ title: t('commercial.clients.toast.error'), message: apiErrorMessage(error) }),
|
||||||
// On ne saute une amorce neuve (id null) totalement vide que si un autre RIB
|
// On ne saute QUE les amorces neuves (id null) totalement vides. Un
|
||||||
// est soumettable. Un RIB existant vide est toujours soumis -> 422 NotBlank
|
// RIB existant vide est soumis -> 422 NotBlank inline (sinon la modif
|
||||||
// inline (sinon la modif serait perdue en silence avec un faux toast succes).
|
// serait perdue en silence avec un faux toast de succes).
|
||||||
rib => hasSubmittableRib && rib.id === null && isRibBlank(rib),
|
rib => rib.id === null && isRibBlank(rib),
|
||||||
)
|
)
|
||||||
if (ribHasError) return
|
if (ribHasError) return
|
||||||
|
|
||||||
|
|||||||
@@ -1,927 +0,0 @@
|
|||||||
<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 ?? ''),
|
|
||||||
})),
|
|
||||||
)
|
|
||||||
|
|
||||||
const countryOptions: RefOption[] = [
|
|
||||||
{ value: 'France', label: 'France' },
|
|
||||||
{ value: 'Espagne', label: 'Espagne' },
|
|
||||||
]
|
|
||||||
|
|
||||||
// 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
|
|
||||||
// Les RIB n'ont de sens que pour une LCR (RG-2.08) : on amorce un bloc vide
|
|
||||||
// quand LCR est choisi, sinon on vide la liste — les RIB deja persistes sont
|
|
||||||
// marques pour suppression serveur au prochain enregistrement.
|
|
||||||
if (isRibRequired.value) {
|
|
||||||
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
for (const rib of ribs.value) {
|
|
||||||
if (rib.id != null) removedRibIds.value.push(rib.id)
|
|
||||||
}
|
|
||||||
ribs.value = []
|
|
||||||
ribErrors.value = []
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// « + RIB » desactive tant que le dernier bloc RIB n'est pas complet.
|
|
||||||
const canAddRib = computed(() => {
|
|
||||||
const last = ribs.value[ribs.value.length - 1]
|
|
||||||
return last !== undefined && isRibComplete(last)
|
|
||||||
})
|
|
||||||
|
|
||||||
function addRib(): void {
|
|
||||||
if (canAddRib.value) ribs.value.push(emptyRib())
|
|
||||||
}
|
|
||||||
|
|
||||||
function askRemoveRib(index: number): void {
|
|
||||||
askConfirm(t('commercial.suppliers.form.confirmDelete.rib'), () => {
|
|
||||||
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 retires. Les RIB crees d'abord : le back valide
|
|
||||||
* RG-2.08 (LCR => au moins un RIB persiste) sur le PATCH scalaires. 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 (erreurs inline par ligne, tous les blocs
|
|
||||||
// tentes). 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).
|
|
||||||
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 retires : APRES le PATCH scalaires (si on quitte LCR, le
|
|
||||||
// guard back n'autorise la suppression du dernier RIB qu'une fois le type change).
|
|
||||||
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>
|
|
||||||
@@ -1,454 +0,0 @@
|
|||||||
<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 } from '~/modules/commercial/utils/supplierFormRules'
|
|
||||||
import { readHistoryTab } from '~/shared/utils/historyTab'
|
|
||||||
import {
|
|
||||||
canEditSupplier,
|
|
||||||
categoryOptionsOf,
|
|
||||||
contactOptionsOf,
|
|
||||||
emptyAddress,
|
|
||||||
mapAccountingDraft,
|
|
||||||
mapAddressView,
|
|
||||||
mapContactToDraft,
|
|
||||||
mapRibToDraft,
|
|
||||||
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 (un RIB n'existe que pour un reglement LCR — RG-2.08).
|
|
||||||
const ribs = computed(() => (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),
|
|
||||||
})),
|
|
||||||
)
|
|
||||||
|
|
||||||
const countryOptions: SelectOption[] = [
|
|
||||||
{ value: 'France', label: 'France' },
|
|
||||||
{ value: 'Espagne', label: 'Espagne' },
|
|
||||||
]
|
|
||||||
|
|
||||||
// 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 && visibleRibs.length > 1"
|
v-if="!accountingReadonly"
|
||||||
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"
|
||||||
@@ -782,10 +782,8 @@ 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). On ne saute une
|
// 1) POST/PATCH des RIB d'abord (erreurs inline par ligne). Seuls les blocs
|
||||||
// amorce neuve vide QUE s'il reste un autre RIB soumettable : sinon (LCR sans
|
// RIB TOTALEMENT vides (amorce neuve) sont ignores.
|
||||||
// aucun RIB rempli) on la soumet pour declencher la 422 NotBlank inline.
|
|
||||||
const hasSubmittableRib = ribs.value.some(r => r.id !== null || !isRibBlank(r))
|
|
||||||
const ribHasError = await submitRows(
|
const ribHasError = await submitRows(
|
||||||
ribs.value,
|
ribs.value,
|
||||||
ribErrors,
|
ribErrors,
|
||||||
@@ -804,7 +802,7 @@ async function submitAccounting(): Promise<void> {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
error => toast.error({ title: t('commercial.suppliers.toast.error'), message: apiErrorMessage(error) }),
|
error => toast.error({ title: t('commercial.suppliers.toast.error'), message: apiErrorMessage(error) }),
|
||||||
rib => hasSubmittableRib && rib.id === null && isRibBlank(rib),
|
rib => rib.id === null && isRibBlank(rib),
|
||||||
)
|
)
|
||||||
if (ribHasError) return
|
if (ribHasError) return
|
||||||
|
|
||||||
|
|||||||
@@ -211,38 +211,6 @@ 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 = {
|
||||||
|
|||||||
@@ -1,224 +0,0 @@
|
|||||||
import { describe, expect, it } from 'vitest'
|
|
||||||
import {
|
|
||||||
canEditSupplier,
|
|
||||||
categoryOptionsOf,
|
|
||||||
contactOptionsOf,
|
|
||||||
iriOf,
|
|
||||||
mapAccountingDraft,
|
|
||||||
mapAddressToDraft,
|
|
||||||
mapAddressView,
|
|
||||||
mapContactToDraft,
|
|
||||||
mapRibToDraft,
|
|
||||||
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)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -6,12 +6,7 @@ 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)', () => {
|
||||||
@@ -22,17 +17,11 @@ describe('buildMainPayload (groupe supplier:write:main)', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('CREATION : omet companyName vide (-> 422 NotBlank, ERP-119)', () => {
|
it('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)', () => {
|
||||||
@@ -97,16 +86,6 @@ 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)
|
||||||
@@ -134,85 +113,3 @@ 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 })
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ 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,
|
||||||
@@ -140,35 +139,12 @@ 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, options: BuildPayloadOptions = {}): Record<string, unknown> {
|
export function buildMainPayload(main: MainFormDraft): 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
|
||||||
@@ -176,14 +152,14 @@ export function buildMainPayload(main: MainFormDraft, options: BuildPayloadOptio
|
|||||||
// 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 finalizeRequired({
|
return omitEmptyRequired({
|
||||||
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, options)
|
}, MAIN_REQUIRED_NON_NULLABLE_KEYS)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Payload de l'onglet Information — groupe client:write:information UNIQUEMENT. */
|
/** Payload de l'onglet Information — groupe client:write:information UNIQUEMENT. */
|
||||||
@@ -235,10 +211,9 @@ 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 a la creation, `''` en edition -> 422 NotBlank (ERP-119).
|
// postalCode / city / street omis si vides -> 422 NotBlank (ERP-119).
|
||||||
return finalizeRequired({
|
return omitEmptyRequired({
|
||||||
isProspect: address.isProspect,
|
isProspect: address.isProspect,
|
||||||
isDelivery: address.isDelivery,
|
isDelivery: address.isDelivery,
|
||||||
isBilling: address.isBilling,
|
isBilling: address.isBilling,
|
||||||
@@ -254,18 +229,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, options)
|
}, ADDRESS_REQUIRED_NON_NULLABLE_KEYS)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Payload d'un RIB (sous-ressource client_rib). */
|
/** Payload d'un RIB (sous-ressource client_rib). */
|
||||||
export function buildRibPayload(rib: RibFormDraft, options: BuildPayloadOptions = {}): Record<string, unknown> {
|
export function buildRibPayload(rib: RibFormDraft): Record<string, unknown> {
|
||||||
// label / bic / iban : omis a la creation, `''` en edition -> 422 NotBlank au lieu
|
// label / bic / iban omis si vides -> 422 NotBlank au lieu d'un 400 de type
|
||||||
// d'un 400 de type (ou d'un faux 200 PATCH qui garderait l'ancienne valeur). ERP-119.
|
// sur un RIB partiel (ex. IBAN seul). ERP-119.
|
||||||
return finalizeRequired({
|
return omitEmptyRequired({
|
||||||
label: rib.label,
|
label: rib.label,
|
||||||
bic: rib.bic,
|
bic: rib.bic,
|
||||||
iban: rib.iban,
|
iban: rib.iban,
|
||||||
}, RIB_REQUIRED_NON_NULLABLE_KEYS, options)
|
}, RIB_REQUIRED_NON_NULLABLE_KEYS)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Gating par permission ────────────────────────────────────────────────────
|
// ── Gating par permission ────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -419,28 +419,3 @@ 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
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,301 +0,0 @@
|
|||||||
/**
|
|
||||||
* 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 }]
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 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,24 +1,19 @@
|
|||||||
/**
|
/**
|
||||||
* Helpers purs des ecrans « Ajouter » / « Modifier » un fournisseur (M2
|
* Helpers purs de payload de l'ecran « Ajouter un fournisseur » (M2 Commercial),
|
||||||
* Commercial) — miroir de `clientEdit.ts` (M1). Deux responsabilites, toutes deux
|
* partages avec la future modification (96) — miroir de `clientEdit.ts` (M1).
|
||||||
* 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).
|
|
||||||
*
|
*
|
||||||
* Ces helpers ne touchent ni a l'API ni a l'etat reactif.
|
* Scoping STRICT des payloads (mode strict, aligne ERP-74/RG) : chaque onglet
|
||||||
|
* n'envoie QUE les champs de SON groupe de serialisation, jamais un payload mixte
|
||||||
|
* (un champ hors-permission = 403 sur l'integralite cote back). Ces helpers ne
|
||||||
|
* touchent ni a l'API ni a l'etat reactif.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import {
|
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,
|
||||||
@@ -58,118 +53,15 @@ 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 vide -> 422 NotBlank (omis a la creation, `''` en edition — ERP-119).
|
* companyName omis si vide -> 422 NotBlank au lieu d'un 400 de type (ERP-119).
|
||||||
*/
|
*/
|
||||||
export function buildMainPayload(main: MainFormDraft, options: BuildPayloadOptions = {}): Record<string, unknown> {
|
export function buildMainPayload(main: MainFormDraft): Record<string, unknown> {
|
||||||
return finalizeRequired({
|
return omitEmptyRequired({
|
||||||
companyName: main.companyName,
|
companyName: main.companyName,
|
||||||
categories: main.categoryIris,
|
categories: main.categoryIris,
|
||||||
}, MAIN_REQUIRED_NON_NULLABLE_KEYS, options)
|
}, MAIN_REQUIRED_NON_NULLABLE_KEYS)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Payload de l'onglet Information — groupe supplier:write:information UNIQUEMENT. */
|
/** Payload de l'onglet Information — groupe supplier:write:information UNIQUEMENT. */
|
||||||
@@ -224,8 +116,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, options: BuildPayloadOptions = {}): Record<string, unknown> {
|
export function buildAddressPayload(address: SupplierAddressFormDraft): Record<string, unknown> {
|
||||||
return finalizeRequired({
|
return omitEmptyRequired({
|
||||||
addressType: address.addressType,
|
addressType: address.addressType,
|
||||||
country: address.country,
|
country: address.country,
|
||||||
postalCode: address.postalCode || null,
|
postalCode: address.postalCode || null,
|
||||||
@@ -237,14 +129,14 @@ export function buildAddressPayload(address: SupplierAddressFormDraft, options:
|
|||||||
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, options)
|
}, ADDRESS_REQUIRED_NON_NULLABLE_KEYS)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Payload d'un RIB (sous-ressource supplier_rib). */
|
/** Payload d'un RIB (sous-ressource supplier_rib). */
|
||||||
export function buildRibPayload(rib: SupplierRibFormDraft, options: BuildPayloadOptions = {}): Record<string, unknown> {
|
export function buildRibPayload(rib: SupplierRibFormDraft): Record<string, unknown> {
|
||||||
return finalizeRequired({
|
return omitEmptyRequired({
|
||||||
label: rib.label,
|
label: rib.label,
|
||||||
bic: rib.bic,
|
bic: rib.bic,
|
||||||
iban: rib.iban,
|
iban: rib.iban,
|
||||||
}, RIB_REQUIRED_NON_NULLABLE_KEYS, options)
|
}, RIB_REQUIRED_NON_NULLABLE_KEYS)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -217,28 +217,3 @@ 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
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user