feat(front) : page Consultation fournisseur (/suppliers/{id}) lecture seule (ERP-95)
- useSupplier(id) : GET /api/suppliers/{id} en Hydra (embed contacts/adresses/ribs
+ scalaires compta si accounting.view), archive()/restore() via PATCH isArchived seul
- supplierConsultation : mappers purs de l'embed (addressType, bennes, triageProvider,
volumeForecast ; gating compta par omission de cle), helpers de permissions
- page [id]/index.vue : lecture seule, bloc principal + onglets (Information/Contacts/
Adresses/Comptabilite selon permission/4 coquilles A venir), Modifier/Archiver/Restaurer,
fleche retour repertoire ; miroir de l'ecran Consultation client (M1)
- tests Vitest : supplierConsultation (mappers + permissions) + useSupplier (GET/PATCH)
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
// Mocks des composables auto-importes par Nuxt (indisponibles sous happy-dom).
|
||||
const mockGet = vi.hoisted(() => vi.fn())
|
||||
const mockPatch = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.stubGlobal('useApi', () => ({
|
||||
get: mockGet,
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
patch: mockPatch,
|
||||
delete: vi.fn(),
|
||||
}))
|
||||
|
||||
const { useSupplier } = await import('../useSupplier')
|
||||
|
||||
const SAMPLE = { '@id': '/api/suppliers/85', id: 85, companyName: 'DOD59393F 862875', isArchived: false }
|
||||
|
||||
describe('useSupplier', () => {
|
||||
beforeEach(() => {
|
||||
mockGet.mockReset()
|
||||
mockPatch.mockReset()
|
||||
mockGet.mockResolvedValue(SAMPLE)
|
||||
mockPatch.mockResolvedValue({ ...SAMPLE, isArchived: true })
|
||||
})
|
||||
|
||||
it('charge le detail via GET /suppliers/{id} en Hydra, sans toast', async () => {
|
||||
const { supplier, load } = useSupplier(85)
|
||||
await load()
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
'/suppliers/85',
|
||||
{},
|
||||
expect.objectContaining({
|
||||
headers: { Accept: 'application/ld+json' },
|
||||
toast: false,
|
||||
}),
|
||||
)
|
||||
expect(supplier.value).toEqual(SAMPLE)
|
||||
})
|
||||
|
||||
it('bascule loading pendant le chargement et le retombe a false', async () => {
|
||||
const { loading, load } = useSupplier(85)
|
||||
const promise = load()
|
||||
expect(loading.value).toBe(true)
|
||||
await promise
|
||||
expect(loading.value).toBe(false)
|
||||
})
|
||||
|
||||
it('marque error et laisse supplier null si le GET echoue (404...)', async () => {
|
||||
mockGet.mockRejectedValueOnce(new Error('not found'))
|
||||
const { supplier, error, load } = useSupplier(99)
|
||||
await load()
|
||||
expect(error.value).toBe(true)
|
||||
expect(supplier.value).toBeNull()
|
||||
})
|
||||
|
||||
it('archive() PATCHe { isArchived: true } sans toast puis RECHARGE le detail complet', async () => {
|
||||
// 1er GET = chargement initial, 2e GET = rechargement post-archivage.
|
||||
mockGet.mockResolvedValueOnce(SAMPLE)
|
||||
mockGet.mockResolvedValueOnce({ ...SAMPLE, isArchived: true })
|
||||
const { supplier, load, archive } = useSupplier(85)
|
||||
await load()
|
||||
await archive()
|
||||
|
||||
expect(mockPatch).toHaveBeenCalledWith(
|
||||
'/suppliers/85',
|
||||
{ isArchived: true },
|
||||
expect.objectContaining({ toast: false }),
|
||||
)
|
||||
// Le detail est re-fetch (le PATCH ne renvoie pas l'embed complet).
|
||||
expect(mockGet).toHaveBeenCalledTimes(2)
|
||||
expect(supplier.value?.isArchived).toBe(true)
|
||||
})
|
||||
|
||||
it('restore() PATCHe { isArchived: false } (payload isArchived SEUL)', async () => {
|
||||
const { load, restore } = useSupplier(85)
|
||||
await load()
|
||||
await restore()
|
||||
|
||||
expect(mockPatch).toHaveBeenCalledWith(
|
||||
'/suppliers/85',
|
||||
{ isArchived: false },
|
||||
expect.objectContaining({ toast: false }),
|
||||
)
|
||||
})
|
||||
|
||||
it('propage l\'erreur (ex: 403 sans permission archive, 409 conflit homonyme) au lieu de l\'avaler', async () => {
|
||||
const forbidden = { response: { status: 403 } }
|
||||
mockPatch.mockRejectedValueOnce(forbidden)
|
||||
const { load, archive } = useSupplier(85)
|
||||
await load()
|
||||
await expect(archive()).rejects.toBe(forbidden)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
import { ref } from 'vue'
|
||||
import type { SupplierDetail } from '~/modules/commercial/utils/supplierConsultation'
|
||||
|
||||
/**
|
||||
* Chargement et actions d'archivage d'un fournisseur unique (ecran « Consultation
|
||||
* fournisseur », ERP-95). Miroir de `useClient` (M1). Lit le detail embarque via
|
||||
* `GET /api/suppliers/{id}` (contacts / adresses / ribs sous `supplier:item:read` /
|
||||
* `supplier:read:accounting`) et expose les bascules d'archivage (PATCH `isArchived`
|
||||
* SEUL — tout autre champ => 422).
|
||||
*
|
||||
* L'en-tete `Accept: application/ld+json` est impose pour obtenir le payload
|
||||
* Hydra complet (sans lui, API Platform 4 renvoie une representation reduite).
|
||||
*
|
||||
* Etat 100 % local a l'instance (refs) — aucune persistance URL. Les erreurs
|
||||
* d'archivage/restauration (notamment le 409 d'homonyme actif a la restauration)
|
||||
* sont PROPAGEES a l'appelant, qui decide du toast a afficher.
|
||||
*/
|
||||
export function useSupplier(id: number | string) {
|
||||
const api = useApi()
|
||||
|
||||
const supplier = ref<SupplierDetail | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref(false)
|
||||
|
||||
/** Recupere le detail complet (embed contacts/adresses/ribs + comptabilite). */
|
||||
function fetchDetail(): Promise<SupplierDetail> {
|
||||
return api.get<SupplierDetail>(
|
||||
`/suppliers/${id}`,
|
||||
{},
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
}
|
||||
|
||||
/** Charge le detail du fournisseur. En cas d'echec : `error = true`, `supplier = null`. */
|
||||
async function load(): Promise<void> {
|
||||
loading.value = true
|
||||
error.value = false
|
||||
try {
|
||||
supplier.value = await fetchDetail()
|
||||
}
|
||||
catch {
|
||||
error.value = true
|
||||
supplier.value = null
|
||||
}
|
||||
finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bascule l'archivage (PATCH `isArchived` SEUL — tout autre champ => 422),
|
||||
* puis RECHARGE le detail complet : la reponse du PATCH ne porte que le groupe
|
||||
* `supplier:read` (ni l'embed contacts/adresses/ribs ni les libelles des
|
||||
* referentiels comptables), un simple merge laisserait l'affichage incoherent.
|
||||
* Toute erreur (notamment le 409 d'homonyme actif a la restauration) est
|
||||
* propagee a l'appelant AVANT le rechargement.
|
||||
*/
|
||||
async function setArchived(isArchived: boolean): Promise<void> {
|
||||
await api.patch(`/suppliers/${id}`, { isArchived }, { toast: false })
|
||||
supplier.value = await fetchDetail()
|
||||
}
|
||||
|
||||
return {
|
||||
supplier,
|
||||
loading,
|
||||
error,
|
||||
load,
|
||||
archive: () => setArchived(true),
|
||||
restore: () => setArchived(false),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
<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>
|
||||
@@ -0,0 +1,224 @@
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* 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 }
|
||||
Reference in New Issue
Block a user