Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f9c881c771 |
+1
-1
@@ -1,2 +1,2 @@
|
|||||||
parameters:
|
parameters:
|
||||||
app.version: '0.1.71'
|
app.version: '0.1.69'
|
||||||
|
|||||||
@@ -87,24 +87,7 @@
|
|||||||
"archiveSuccess": "Client archivé avec succès",
|
"archiveSuccess": "Client archivé avec succès",
|
||||||
"restoreSuccess": "Client restauré avec succès",
|
"restoreSuccess": "Client restauré avec succès",
|
||||||
"error": "Une erreur est survenue. Réessayez.",
|
"error": "Une erreur est survenue. Réessayez.",
|
||||||
"exportError": "L'export du répertoire clients a échoué. Réessayez.",
|
"exportError": "L'export du répertoire clients a échoué. Réessayez."
|
||||||
"restoreConflict": "Impossible de restaurer : un client actif portant ce nom existe déjà."
|
|
||||||
},
|
|
||||||
"consultation": {
|
|
||||||
"title": "Consultation client",
|
|
||||||
"back": "Retour au répertoire",
|
|
||||||
"loading": "Chargement du client…",
|
|
||||||
"notFound": "Client introuvable.",
|
|
||||||
"emptyContacts": "Aucun contact enregistré.",
|
|
||||||
"emptyAddresses": "Aucune adresse enregistrée.",
|
|
||||||
"confirmArchive": {
|
|
||||||
"title": "Archiver le client",
|
|
||||||
"message": "Ce client n'apparaîtra plus dans le répertoire actif. Confirmer l'archivage ?"
|
|
||||||
},
|
|
||||||
"confirmRestore": {
|
|
||||||
"title": "Restaurer le client",
|
|
||||||
"message": "Ce client réapparaîtra dans le répertoire actif. Confirmer la restauration ?"
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
"validation": {
|
"validation": {
|
||||||
"informationRequiredForCommercial": "Les informations de l'entreprise sont obligatoires pour le rôle Commerciale.",
|
"informationRequiredForCommercial": "Les informations de l'entreprise sont obligatoires pour le rôle Commerciale.",
|
||||||
|
|||||||
@@ -88,11 +88,9 @@
|
|||||||
sur l'input interne, pas sur la cellule de grille. Le wrapper porte
|
sur l'input interne, pas sur la cellule de grille. Le wrapper porte
|
||||||
le col-span-2, le champ le remplit (w-full). -->
|
le col-span-2, le champ le remplit (w-full). -->
|
||||||
<div class="col-span-2">
|
<div class="col-span-2">
|
||||||
<!-- Adresse : saisie assistee (BAN) en edition ; champ texte simple en
|
<!-- Adresse : saisie assistee (BAN) ou libre en mode degrade. -->
|
||||||
mode degrade OU en lecture seule (MalioInputAutocomplete ne reaffiche
|
|
||||||
pas sa valeur liee, il n'afficherait rien en readonly). -->
|
|
||||||
<MalioInputAutocomplete
|
<MalioInputAutocomplete
|
||||||
v-if="!degraded && !readonly"
|
v-if="!degraded"
|
||||||
:model-value="model.street"
|
:model-value="model.street"
|
||||||
:options="addressOptions"
|
:options="addressOptions"
|
||||||
:loading="addressLoading"
|
:loading="addressLoading"
|
||||||
@@ -199,21 +197,8 @@ const model = computed(() => props.modelValue)
|
|||||||
|
|
||||||
// Mode degrade : service BAN indisponible → Ville/Adresse en saisie libre.
|
// Mode degrade : service BAN indisponible → Ville/Adresse en saisie libre.
|
||||||
const degraded = ref(false)
|
const degraded = ref(false)
|
||||||
// Villes proposees par la BAN (alimentees a la saisie du code postal).
|
const cityOptions = ref<RefOption[]>([])
|
||||||
const banCityOptions = ref<RefOption[]>([])
|
|
||||||
const addressOptions = ref<RefOption[]>([])
|
const addressOptions = ref<RefOption[]>([])
|
||||||
|
|
||||||
// Options ville effectives : on garantit que la ville courante figure toujours
|
|
||||||
// dans la liste, sinon MalioSelect (qui resout le libelle depuis ses options)
|
|
||||||
// afficherait un champ vide en lecture seule (consultation 1.11) ou en edition
|
|
||||||
// d'une adresse existante (1.12), ou la BAN n'a pas (re)peuple les suggestions.
|
|
||||||
const cityOptions = computed<RefOption[]>(() => {
|
|
||||||
const current = props.modelValue.city
|
|
||||||
if (current && !banCityOptions.value.some(o => o.value === current)) {
|
|
||||||
return [{ value: current, label: current }, ...banCityOptions.value]
|
|
||||||
}
|
|
||||||
return banCityOptions.value
|
|
||||||
})
|
|
||||||
const addressLoading = ref(false)
|
const addressLoading = ref(false)
|
||||||
// Conserve les suggestions d'adresse pour retrouver ville/CP au moment du select.
|
// Conserve les suggestions d'adresse pour retrouver ville/CP au moment du select.
|
||||||
let lastAddressSuggestions: AddressSuggestion[] = []
|
let lastAddressSuggestions: AddressSuggestion[] = []
|
||||||
@@ -263,7 +248,7 @@ async function onPostalCodeChange(value: string): Promise<void> {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const suggestions = await autocomplete.searchCity(digits)
|
const suggestions = await autocomplete.searchCity(digits)
|
||||||
banCityOptions.value = suggestions.map(s => ({ value: s.city, label: s.city }))
|
cityOptions.value = suggestions.map(s => ({ value: s.city, label: s.city }))
|
||||||
}
|
}
|
||||||
catch {
|
catch {
|
||||||
enterDegraded()
|
enterDegraded()
|
||||||
|
|||||||
@@ -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 { useClient } = await import('../useClient')
|
|
||||||
|
|
||||||
const SAMPLE = { '@id': '/api/clients/42', id: 42, companyName: 'ACME', isArchived: false }
|
|
||||||
|
|
||||||
describe('useClient', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
mockGet.mockReset()
|
|
||||||
mockPatch.mockReset()
|
|
||||||
mockGet.mockResolvedValue(SAMPLE)
|
|
||||||
mockPatch.mockResolvedValue({ ...SAMPLE, isArchived: true })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('charge le detail via GET /clients/{id} en Hydra, sans toast', async () => {
|
|
||||||
const { client, load } = useClient(42)
|
|
||||||
await load()
|
|
||||||
|
|
||||||
expect(mockGet).toHaveBeenCalledWith(
|
|
||||||
'/clients/42',
|
|
||||||
{},
|
|
||||||
expect.objectContaining({
|
|
||||||
headers: { Accept: 'application/ld+json' },
|
|
||||||
toast: false,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
expect(client.value).toEqual(SAMPLE)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('bascule loading pendant le chargement et le retombe a false', async () => {
|
|
||||||
const { loading, load } = useClient(42)
|
|
||||||
const promise = load()
|
|
||||||
expect(loading.value).toBe(true)
|
|
||||||
await promise
|
|
||||||
expect(loading.value).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('marque error et laisse client null si le GET echoue (404...)', async () => {
|
|
||||||
mockGet.mockRejectedValueOnce(new Error('not found'))
|
|
||||||
const { client, error, load } = useClient(99)
|
|
||||||
await load()
|
|
||||||
expect(error.value).toBe(true)
|
|
||||||
expect(client.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 { client, load, archive } = useClient(42)
|
|
||||||
await load()
|
|
||||||
await archive()
|
|
||||||
|
|
||||||
expect(mockPatch).toHaveBeenCalledWith(
|
|
||||||
'/clients/42',
|
|
||||||
{ isArchived: true },
|
|
||||||
expect.objectContaining({ toast: false }),
|
|
||||||
)
|
|
||||||
// Le detail est re-fetch (le PATCH ne renvoie pas l'embed complet).
|
|
||||||
expect(mockGet).toHaveBeenCalledTimes(2)
|
|
||||||
expect(client.value?.isArchived).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('restore() PATCHe { isArchived: false } (payload isArchived SEUL)', async () => {
|
|
||||||
const { load, restore } = useClient(42)
|
|
||||||
await load()
|
|
||||||
await restore()
|
|
||||||
|
|
||||||
expect(mockPatch).toHaveBeenCalledWith(
|
|
||||||
'/clients/42',
|
|
||||||
{ isArchived: false },
|
|
||||||
expect.objectContaining({ toast: false }),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('propage l\'erreur (ex: 409 conflit homonyme RG-1.23) au lieu de l\'avaler', async () => {
|
|
||||||
const conflict = { response: { status: 409 } }
|
|
||||||
mockPatch.mockRejectedValueOnce(conflict)
|
|
||||||
const { load, restore } = useClient(42)
|
|
||||||
await load()
|
|
||||||
await expect(restore()).rejects.toBe(conflict)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||||
|
|
||||||
|
// `useApi` est un auto-import Nuxt : on le stubbe globalement pour intercepter
|
||||||
|
// les appels de chargement des referentiels et simuler un endpoint en echec
|
||||||
|
// (ex: 403 sur /categories pour un role sans la permission de lecture).
|
||||||
|
// Meme pattern que useClientsRepository.spec.ts.
|
||||||
|
const mockGet = vi.hoisted(() => vi.fn())
|
||||||
|
vi.stubGlobal('useApi', () => ({
|
||||||
|
get: mockGet,
|
||||||
|
post: vi.fn(),
|
||||||
|
put: vi.fn(),
|
||||||
|
patch: vi.fn(),
|
||||||
|
delete: vi.fn(),
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Import APRES le stub pour que useApi soit bien resolu au top-level du module.
|
||||||
|
const { useClientReferentials } = await import('../useClientReferentials')
|
||||||
|
|
||||||
|
describe('useClientReferentials.loadCommon (resilience ERP-102)', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
mockGet.mockReset()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('un referentiel en echec (403) ne vide QUE son select, pas les autres', async () => {
|
||||||
|
// /categories rejette (simulateur d'un 403), tous les autres repondent.
|
||||||
|
mockGet.mockImplementation((url: string) => {
|
||||||
|
if (url === '/categories') {
|
||||||
|
return Promise.reject(new Error('403 Forbidden'))
|
||||||
|
}
|
||||||
|
if (url === '/sites') {
|
||||||
|
return Promise.resolve({ member: [{ '@id': '/api/sites/1', name: 'Chatellerault' }] })
|
||||||
|
}
|
||||||
|
return Promise.resolve({
|
||||||
|
member: [{ '@id': '/api/x/1', code: 'X', label: 'Libelle X' }],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
const refs = useClientReferentials()
|
||||||
|
// loadCommon ne doit JAMAIS rejeter : l'echec d'un referentiel est isole.
|
||||||
|
await refs.loadCommon()
|
||||||
|
|
||||||
|
// Resilience : les referentiels OK sont peuples malgre l'echec de /categories.
|
||||||
|
expect(refs.sites.value).toEqual([{ value: '/api/sites/1', label: 'Chatellerault' }])
|
||||||
|
expect(refs.tvaModes.value).toEqual([{ value: '/api/x/1', label: 'Libelle X' }])
|
||||||
|
expect(refs.banks.value).toEqual([{ value: '/api/x/1', label: 'Libelle X' }])
|
||||||
|
|
||||||
|
// Seul le select en echec reste vide.
|
||||||
|
expect(refs.categories.value).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('charge tous les referentiels quand tout repond', async () => {
|
||||||
|
mockGet.mockImplementation((url: string) => {
|
||||||
|
if (url === '/categories') {
|
||||||
|
return Promise.resolve({
|
||||||
|
member: [{ '@id': '/api/categories/1', code: 'SECTEUR', name: 'Secteur' }],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (url === '/sites') {
|
||||||
|
return Promise.resolve({ member: [{ '@id': '/api/sites/1', name: 'Chatellerault' }] })
|
||||||
|
}
|
||||||
|
return Promise.resolve({ member: [] })
|
||||||
|
})
|
||||||
|
|
||||||
|
const refs = useClientReferentials()
|
||||||
|
await refs.loadCommon()
|
||||||
|
|
||||||
|
expect(refs.categories.value).toEqual([
|
||||||
|
{ value: '/api/categories/1', label: 'Secteur', code: 'SECTEUR' },
|
||||||
|
])
|
||||||
|
expect(refs.sites.value).toEqual([{ value: '/api/sites/1', label: 'Chatellerault' }])
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
import { ref } from 'vue'
|
|
||||||
import type { ClientDetail } from '~/modules/commercial/utils/clientConsultation'
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Chargement et actions d'archivage d'un client unique (ecran « Consultation
|
|
||||||
* client », 1.11). Lit le detail embarque via `GET /api/clients/{id}` (contacts /
|
|
||||||
* adresses / ribs sous `client:item:read` / `client: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 RG-1.23 : homonyme actif a la
|
|
||||||
* restauration) sont PROPAGEES a l'appelant, qui decide du toast a afficher.
|
|
||||||
*/
|
|
||||||
export function useClient(id: number | string) {
|
|
||||||
const api = useApi()
|
|
||||||
|
|
||||||
const client = ref<ClientDetail | null>(null)
|
|
||||||
const loading = ref(false)
|
|
||||||
const error = ref(false)
|
|
||||||
|
|
||||||
/** Recupere le detail complet (embed contacts/adresses/ribs + comptabilite). */
|
|
||||||
function fetchDetail(): Promise<ClientDetail> {
|
|
||||||
return api.get<ClientDetail>(
|
|
||||||
`/clients/${id}`,
|
|
||||||
{},
|
|
||||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Charge le detail du client. En cas d'echec : `error = true`, `client = null`. */
|
|
||||||
async function load(): Promise<void> {
|
|
||||||
loading.value = true
|
|
||||||
error.value = false
|
|
||||||
try {
|
|
||||||
client.value = await fetchDetail()
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
error.value = true
|
|
||||||
client.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
|
|
||||||
* `client: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, RG-1.23)
|
|
||||||
* est propagee a l'appelant AVANT le rechargement.
|
|
||||||
*/
|
|
||||||
async function setArchived(isArchived: boolean): Promise<void> {
|
|
||||||
await api.patch(`/clients/${id}`, { isArchived }, { toast: false })
|
|
||||||
client.value = await fetchDetail()
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
client,
|
|
||||||
loading,
|
|
||||||
error,
|
|
||||||
load,
|
|
||||||
archive: () => setArchived(true),
|
|
||||||
restore: () => setArchived(false),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -88,23 +88,35 @@ export function useClientReferentials() {
|
|||||||
* charges a la demande selon la relation choisie). Les selects compta ne sont
|
* charges a la demande selon la relation choisie). Les selects compta ne sont
|
||||||
* pertinents que si l'utilisateur a acces a l'onglet, mais le cout est
|
* pertinents que si l'utilisateur a acces a l'onglet, mais le cout est
|
||||||
* negligeable et simplifie l'orchestration.
|
* negligeable et simplifie l'orchestration.
|
||||||
|
*
|
||||||
|
* Resilience (ERP-102) : chaque referentiel est charge et affecte
|
||||||
|
* independamment via `Promise.allSettled`. Si UN endpoint echoue (ex: 403,
|
||||||
|
* coupure reseau), seul SON select reste vide — les autres sont peuples
|
||||||
|
* normalement. Un `Promise.all` rejetterait au premier echec et viderait la
|
||||||
|
* TOTALITE des selects, rendant le formulaire de creation client inutilisable.
|
||||||
|
* `loadCommon` ne rejette donc jamais.
|
||||||
*/
|
*/
|
||||||
async function loadCommon(): Promise<void> {
|
async function loadCommon(): Promise<void> {
|
||||||
const [cats, sitesList, tva, delays, types, banksList] = await Promise.all([
|
await Promise.allSettled([
|
||||||
fetchAll<CategoryMember>('/categories'),
|
fetchAll<CategoryMember>('/categories').then(cats => {
|
||||||
fetchAll<SiteMember>('/sites'),
|
|
||||||
fetchAll<ReferentialMember>('/tva_modes'),
|
|
||||||
fetchAll<ReferentialMember>('/payment_delays'),
|
|
||||||
fetchAll<ReferentialMember>('/payment_types'),
|
|
||||||
fetchAll<ReferentialMember>('/banks'),
|
|
||||||
])
|
|
||||||
|
|
||||||
categories.value = cats.map(c => ({ value: c['@id'], label: c.name, code: c.code }))
|
categories.value = cats.map(c => ({ value: c['@id'], label: c.name, code: c.code }))
|
||||||
|
}),
|
||||||
|
fetchAll<SiteMember>('/sites').then(sitesList => {
|
||||||
sites.value = sitesList.map(s => ({ value: s['@id'], label: s.name }))
|
sites.value = sitesList.map(s => ({ value: s['@id'], label: s.name }))
|
||||||
|
}),
|
||||||
|
fetchAll<ReferentialMember>('/tva_modes').then(tva => {
|
||||||
tvaModes.value = tva.map(t => ({ value: t['@id'], label: t.label }))
|
tvaModes.value = tva.map(t => ({ value: t['@id'], label: t.label }))
|
||||||
|
}),
|
||||||
|
fetchAll<ReferentialMember>('/payment_delays').then(delays => {
|
||||||
paymentDelays.value = delays.map(d => ({ value: d['@id'], label: d.label }))
|
paymentDelays.value = delays.map(d => ({ value: d['@id'], label: d.label }))
|
||||||
|
}),
|
||||||
|
fetchAll<ReferentialMember>('/payment_types').then(types => {
|
||||||
paymentTypes.value = types.map(t => ({ value: t['@id'], label: t.label, code: t.code }))
|
paymentTypes.value = types.map(t => ({ value: t['@id'], label: t.label, code: t.code }))
|
||||||
|
}),
|
||||||
|
fetchAll<ReferentialMember>('/banks').then(banksList => {
|
||||||
banks.value = banksList.map(b => ({ value: b['@id'], label: b.label }))
|
banks.value = banksList.map(b => ({ value: b['@id'], label: b.label }))
|
||||||
|
}),
|
||||||
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Liste des clients pouvant etre choisis comme distributeur (code DISTRIBUTEUR). */
|
/** Liste des clients pouvant etre choisis comme distributeur (code DISTRIBUTEUR). */
|
||||||
|
|||||||
@@ -1,481 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div>
|
|
||||||
<!-- En-tete : retour repertoire + nom du client + actions (Modifier / Archiver|Restaurer). -->
|
|
||||||
<div class="flex items-center gap-3">
|
|
||||||
<MalioButtonIcon
|
|
||||||
icon="mdi:arrow-left-bold"
|
|
||||||
icon-size="24"
|
|
||||||
variant="ghost"
|
|
||||||
v-bind="{ ariaLabel: t('commercial.clients.consultation.back') }"
|
|
||||||
@click="goBack"
|
|
||||||
/>
|
|
||||||
<h1 class="text-[32px] font-bold 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.clients.action.edit')"
|
|
||||||
@click="goEdit"
|
|
||||||
/>
|
|
||||||
<MalioButton
|
|
||||||
v-if="showArchive"
|
|
||||||
variant="secondary"
|
|
||||||
icon-name="mdi:archive-arrow-down-outline"
|
|
||||||
icon-position="left"
|
|
||||||
:label="t('commercial.clients.action.archive')"
|
|
||||||
@click="askToggleArchive"
|
|
||||||
/>
|
|
||||||
<MalioButton
|
|
||||||
v-if="showRestore"
|
|
||||||
variant="secondary"
|
|
||||||
icon-name="mdi:archive-arrow-up-outline"
|
|
||||||
icon-position="left"
|
|
||||||
:label="t('commercial.clients.action.restore')"
|
|
||||||
@click="askToggleArchive"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Etats de chargement / introuvable. -->
|
|
||||||
<p v-if="loading" class="mt-12 text-center text-black/60">{{ t('commercial.clients.consultation.loading') }}</p>
|
|
||||||
<p v-else-if="error" class="mt-12 text-center text-m-danger">{{ t('commercial.clients.consultation.notFound') }}</p>
|
|
||||||
|
|
||||||
<template v-else-if="client">
|
|
||||||
<!-- ── 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="client.companyName"
|
|
||||||
:label="t('commercial.clients.form.main.companyName')"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<MalioInputText
|
|
||||||
:model-value="client.lastName"
|
|
||||||
:label="t('commercial.clients.form.main.lastName')"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<MalioInputText
|
|
||||||
:model-value="client.firstName"
|
|
||||||
:label="t('commercial.clients.form.main.firstName')"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<MalioSelectCheckbox
|
|
||||||
:model-value="categoryIris"
|
|
||||||
:options="mainCategoryOptions"
|
|
||||||
:label="t('commercial.clients.form.main.categories')"
|
|
||||||
:display-tag="true"
|
|
||||||
disabled
|
|
||||||
/>
|
|
||||||
<MalioInputPhone
|
|
||||||
v-for="(phone, index) in mainPhones"
|
|
||||||
:key="index"
|
|
||||||
:model-value="phone"
|
|
||||||
:label="index === 0 ? t('commercial.clients.form.main.phonePrimary') : t('commercial.clients.form.main.phoneSecondary')"
|
|
||||||
:mask="PHONE_MASK"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<MalioInputEmail
|
|
||||||
:model-value="client.email"
|
|
||||||
:label="t('commercial.clients.form.main.email')"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<MalioSelect
|
|
||||||
v-if="relation.type"
|
|
||||||
:model-value="relation.type"
|
|
||||||
:options="relationOptions"
|
|
||||||
:label="t('commercial.clients.form.main.relation')"
|
|
||||||
disabled
|
|
||||||
/>
|
|
||||||
<MalioInputText
|
|
||||||
v-if="relation.type"
|
|
||||||
:model-value="relation.name"
|
|
||||||
:label="relation.type === 'distributeur' ? t('commercial.clients.form.main.distributorName') : t('commercial.clients.form.main.brokerName')"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<MalioCheckbox
|
|
||||||
:model-value="client.triageService === true"
|
|
||||||
:label="t('commercial.clients.form.main.triageService')"
|
|
||||||
group-class="self-center"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- ── Onglets (navigation libre, tout en lecture seule) ─────────── -->
|
|
||||||
<MalioTabList v-model="activeTab" :tabs="tabs" class="mt-[60px]">
|
|
||||||
<!-- Onglet Information -->
|
|
||||||
<template #information>
|
|
||||||
<div class="mt-12 grid grid-cols-4 gap-x-[44px] gap-y-4 bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
|
|
||||||
<MalioInputTextArea
|
|
||||||
:model-value="information.description"
|
|
||||||
:label="t('commercial.clients.form.information.description')"
|
|
||||||
resize="none"
|
|
||||||
group-class="row-span-2 pt-1"
|
|
||||||
text-input="h-full text-lg"
|
|
||||||
disabled
|
|
||||||
/>
|
|
||||||
<MalioInputText
|
|
||||||
:model-value="information.competitors"
|
|
||||||
:label="t('commercial.clients.form.information.competitors')"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<MalioDate
|
|
||||||
:model-value="information.foundedAt"
|
|
||||||
:label="t('commercial.clients.form.information.foundedAt')"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<MalioInputText
|
|
||||||
:model-value="information.employeesCount"
|
|
||||||
:label="t('commercial.clients.form.information.employeesCount')"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<MalioInputAmount
|
|
||||||
:model-value="information.revenueAmount"
|
|
||||||
:label="t('commercial.clients.form.information.revenueAmount')"
|
|
||||||
disabled
|
|
||||||
/>
|
|
||||||
<MalioInputText
|
|
||||||
:model-value="information.directorName"
|
|
||||||
:label="t('commercial.clients.form.information.directorName')"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<MalioInputAmount
|
|
||||||
:model-value="information.profitAmount"
|
|
||||||
:label="t('commercial.clients.form.information.profitAmount')"
|
|
||||||
disabled
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<!-- Onglet Contact -->
|
|
||||||
<template #contact>
|
|
||||||
<div class="mt-12 flex flex-col gap-6">
|
|
||||||
<ClientContactBlock
|
|
||||||
v-for="(contact, index) in contacts"
|
|
||||||
:key="contact.id ?? index"
|
|
||||||
:model-value="contact"
|
|
||||||
:title="t('commercial.clients.form.contact.title', { n: index + 1 })"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<p v-if="contacts.length === 0" class="text-center text-black/60">
|
|
||||||
{{ t('commercial.clients.consultation.emptyContacts') }}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<!-- Onglet Adresse -->
|
|
||||||
<template #address>
|
|
||||||
<div class="mt-12 flex flex-col gap-6">
|
|
||||||
<ClientAddressBlock
|
|
||||||
v-for="(view, index) in addressViews"
|
|
||||||
:key="view.draft.id ?? index"
|
|
||||||
:model-value="view.draft"
|
|
||||||
:title="t('commercial.clients.form.address.title', { n: index + 1 })"
|
|
||||||
:category-options="view.categoryOptions"
|
|
||||||
:site-options="view.siteOptions"
|
|
||||||
:contact-options="contactOptions"
|
|
||||||
:country-options="countryOptions"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<p v-if="addressViews.length === 0" class="text-center text-black/60">
|
|
||||||
{{ t('commercial.clients.consultation.emptyAddresses') }}
|
|
||||||
</p>
|
|
||||||
</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-3 gap-x-[80px] gap-y-5">
|
|
||||||
<MalioInputText
|
|
||||||
:model-value="accounting.siren"
|
|
||||||
:label="t('commercial.clients.form.accounting.siren')"
|
|
||||||
:mask="SIREN_MASK"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<MalioInputText
|
|
||||||
:model-value="accounting.accountNumber"
|
|
||||||
:label="t('commercial.clients.form.accounting.accountNumber')"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<MalioSelect
|
|
||||||
:model-value="accounting.tvaModeIri"
|
|
||||||
:options="tvaModeOptions"
|
|
||||||
:label="t('commercial.clients.form.accounting.tvaMode')"
|
|
||||||
empty-option-label=""
|
|
||||||
disabled
|
|
||||||
/>
|
|
||||||
<MalioInputText
|
|
||||||
:model-value="accounting.nTva"
|
|
||||||
:label="t('commercial.clients.form.accounting.nTva')"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<MalioSelect
|
|
||||||
:model-value="accounting.paymentDelayIri"
|
|
||||||
:options="paymentDelayOptions"
|
|
||||||
:label="t('commercial.clients.form.accounting.paymentDelay')"
|
|
||||||
empty-option-label=""
|
|
||||||
disabled
|
|
||||||
/>
|
|
||||||
<MalioSelect
|
|
||||||
:model-value="accounting.paymentTypeIri"
|
|
||||||
:options="paymentTypeOptions"
|
|
||||||
:label="t('commercial.clients.form.accounting.paymentType')"
|
|
||||||
empty-option-label=""
|
|
||||||
disabled
|
|
||||||
/>
|
|
||||||
<MalioSelect
|
|
||||||
v-if="accounting.bankIri"
|
|
||||||
:model-value="accounting.bankIri"
|
|
||||||
:options="bankOptions"
|
|
||||||
:label="t('commercial.clients.form.accounting.bank')"
|
|
||||||
empty-option-label=""
|
|
||||||
disabled
|
|
||||||
/>
|
|
||||||
</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-3 gap-x-[80px] gap-y-5">
|
|
||||||
<MalioInputText
|
|
||||||
:model-value="rib.label"
|
|
||||||
:label="t('commercial.clients.form.accounting.ribLabel')"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<MalioInputText
|
|
||||||
:model-value="rib.bic"
|
|
||||||
:label="t('commercial.clients.form.accounting.ribBic')"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
<MalioInputText
|
|
||||||
:model-value="rib.iban"
|
|
||||||
:label="t('commercial.clients.form.accounting.ribIban')"
|
|
||||||
readonly
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<!-- Onglets non encore implementes : frame vide (navigation libre). -->
|
|
||||||
<template #transport><TabPlaceholderBlank /></template>
|
|
||||||
<template #statistics><TabPlaceholderBlank /></template>
|
|
||||||
<template #reports><TabPlaceholderBlank /></template>
|
|
||||||
<template #exchanges><TabPlaceholderBlank /></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.clients.consultation.confirmRestore.title') : t('commercial.clients.consultation.confirmArchive.title') }}
|
|
||||||
</h2>
|
|
||||||
</template>
|
|
||||||
<p>{{ isArchived ? t('commercial.clients.consultation.confirmRestore.message') : t('commercial.clients.consultation.confirmArchive.message') }}</p>
|
|
||||||
<template #footer>
|
|
||||||
<MalioButton
|
|
||||||
variant="secondary"
|
|
||||||
button-class="flex-1"
|
|
||||||
:label="t('commercial.clients.form.confirmDelete.cancel')"
|
|
||||||
@click="confirmOpen = false"
|
|
||||||
/>
|
|
||||||
<MalioButton
|
|
||||||
:variant="isArchived ? 'primary' : 'danger'"
|
|
||||||
button-class="flex-1"
|
|
||||||
:label="t('commercial.clients.form.confirmDelete.confirm')"
|
|
||||||
:disabled="toggling"
|
|
||||||
@click="confirmToggleArchive"
|
|
||||||
/>
|
|
||||||
</template>
|
|
||||||
</MalioModal>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup lang="ts">
|
|
||||||
import { computed, onMounted, ref } from 'vue'
|
|
||||||
import { useClient } from '~/modules/commercial/composables/useClient'
|
|
||||||
import { buildClientFormTabKeys } from '~/modules/commercial/utils/clientFormRules'
|
|
||||||
import {
|
|
||||||
canEditClient,
|
|
||||||
categoryOptionsOf,
|
|
||||||
contactOptionsOf,
|
|
||||||
mapAccountingDraft,
|
|
||||||
mapAddressView,
|
|
||||||
mapContactToDraft,
|
|
||||||
mapRibToDraft,
|
|
||||||
referentialOptionOf,
|
|
||||||
relationOf,
|
|
||||||
showArchiveAction,
|
|
||||||
showRestoreAction,
|
|
||||||
type ClientDetail,
|
|
||||||
type SelectOption,
|
|
||||||
} from '~/modules/commercial/utils/clientConsultation'
|
|
||||||
import { formatPhoneFR } from '~/shared/utils/phone'
|
|
||||||
|
|
||||||
// Masques d'affichage (purement visuels, la donnee reste celle du serveur).
|
|
||||||
const PHONE_MASK = '## ## ## ## ##'
|
|
||||||
const SIREN_MASK = '#########'
|
|
||||||
|
|
||||||
const { t } = useI18n()
|
|
||||||
const route = useRoute()
|
|
||||||
const router = useRouter()
|
|
||||||
const toast = useToast()
|
|
||||||
const { can, canAny } = usePermissions()
|
|
||||||
|
|
||||||
// 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.clients.view')) {
|
|
||||||
await navigateTo('/clients')
|
|
||||||
}
|
|
||||||
|
|
||||||
const clientId = route.params.id as string
|
|
||||||
|
|
||||||
const { client, loading, error, load, archive, restore } = useClient(clientId)
|
|
||||||
|
|
||||||
// ── Permissions / visibilite des actions ───────────────────────────────────
|
|
||||||
const canAccountingView = computed(() => can('commercial.clients.accounting.view'))
|
|
||||||
const canEdit = computed(() => canEditClient(canAny))
|
|
||||||
const isArchived = computed(() => client.value?.isArchived === true)
|
|
||||||
const showArchive = computed(() => showArchiveAction(can, isArchived.value))
|
|
||||||
const showRestore = computed(() => showRestoreAction(can, isArchived.value))
|
|
||||||
|
|
||||||
const headerTitle = computed(() => client.value?.companyName ?? t('commercial.clients.consultation.title'))
|
|
||||||
|
|
||||||
// ── Donnees derivees du payload (lecture seule) ────────────────────────────
|
|
||||||
const relation = computed(() => (client.value ? relationOf(client.value) : { type: null, name: null }))
|
|
||||||
const categoryIris = computed(() => (client.value?.categories ?? []).map(c => c['@id']))
|
|
||||||
|
|
||||||
// Telephones du formulaire principal, formates XX XX XX XX XX (RG d'affichage).
|
|
||||||
const mainPhones = computed(() =>
|
|
||||||
[client.value?.phonePrimary, client.value?.phoneSecondary]
|
|
||||||
.filter((p): p is string => Boolean(p))
|
|
||||||
.map(formatPhoneFR),
|
|
||||||
)
|
|
||||||
|
|
||||||
const information = computed(() => ({
|
|
||||||
description: client.value?.description ?? null,
|
|
||||||
competitors: client.value?.competitors ?? null,
|
|
||||||
// MalioDate attend strictement YYYY-MM-DD : on tronque l'ISO datetime renvoye.
|
|
||||||
foundedAt: client.value?.foundedAt ? client.value.foundedAt.slice(0, 10) : null,
|
|
||||||
employeesCount: client.value?.employeesCount != null ? String(client.value.employeesCount) : null,
|
|
||||||
revenueAmount: client.value?.revenueAmount ?? null,
|
|
||||||
profitAmount: client.value?.profitAmount ?? null,
|
|
||||||
directorName: client.value?.directorName ?? null,
|
|
||||||
}))
|
|
||||||
|
|
||||||
const contacts = computed(() => (client.value?.contacts ?? []).map(mapContactToDraft))
|
|
||||||
// Vue par adresse : brouillon + options (sites/categories) propres a l'adresse.
|
|
||||||
const addressViews = computed(() => (client.value?.addresses ?? []).map(mapAddressView))
|
|
||||||
const ribs = computed(() => (client.value?.ribs ?? []).map(mapRibToDraft))
|
|
||||||
// Draft comptable (tout null si l'utilisateur n'a pas accounting.view).
|
|
||||||
const accounting = computed(() => mapAccountingDraft(client.value ?? ({} as ClientDetail)))
|
|
||||||
|
|
||||||
// ── 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(client.value?.categories))
|
|
||||||
const contactOptions = computed(() => contactOptionsOf(client.value?.contacts))
|
|
||||||
|
|
||||||
const relationOptions = computed<SelectOption[]>(() => [
|
|
||||||
{ value: 'distributeur', label: t('commercial.clients.form.main.relationDistributor') },
|
|
||||||
{ value: 'courtier', label: t('commercial.clients.form.main.relationBroker') },
|
|
||||||
])
|
|
||||||
|
|
||||||
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(client.value?.tvaMode))
|
|
||||||
const paymentDelayOptions = computed(() => referentialOptionOf(client.value?.paymentDelay))
|
|
||||||
const paymentTypeOptions = computed(() => referentialOptionOf(client.value?.paymentType))
|
|
||||||
const bankOptions = computed(() => referentialOptionOf(client.value?.bank))
|
|
||||||
|
|
||||||
// ── Onglets : navigation LIBRE (pas de sequence forcee en consultation) ────
|
|
||||||
// 4 onglets actifs (Information, Contact, Adresse, + Comptabilite si droit) et
|
|
||||||
// 4 coquilles (Transport, Statistiques, Rapports, Echanges).
|
|
||||||
const tabKeys = computed(() => buildClientFormTabKeys(canAccountingView.value, { includeEditOnlyTabs: true }))
|
|
||||||
|
|
||||||
const TAB_ICONS: Record<string, string> = {
|
|
||||||
information: 'mdi:account-outline',
|
|
||||||
contact: 'mdi:account-box-plus-outline',
|
|
||||||
address: '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.clients.tab.${key}`),
|
|
||||||
icon: TAB_ICONS[key],
|
|
||||||
})))
|
|
||||||
|
|
||||||
const activeTab = ref('information')
|
|
||||||
|
|
||||||
// ── Navigation ─────────────────────────────────────────────────────────────
|
|
||||||
function goBack(): void {
|
|
||||||
router.push('/clients')
|
|
||||||
}
|
|
||||||
|
|
||||||
function goEdit(): void {
|
|
||||||
router.push(`/clients/${clientId}/edit`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 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 (RG-1.23) 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.clients.toast.restoreSuccess') })
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
await archive()
|
|
||||||
toast.success({ title: t('commercial.clients.toast.archiveSuccess') })
|
|
||||||
}
|
|
||||||
confirmOpen.value = false
|
|
||||||
}
|
|
||||||
catch (e) {
|
|
||||||
const status = (e as { response?: { status?: number } })?.response?.status
|
|
||||||
toast.error({
|
|
||||||
title: t('commercial.clients.toast.error'),
|
|
||||||
message: restoring && status === 409
|
|
||||||
? t('commercial.clients.toast.restoreConflict')
|
|
||||||
: t('commercial.clients.toast.error'),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
toggling.value = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
useHead({ title: headerTitle })
|
|
||||||
|
|
||||||
onMounted(load)
|
|
||||||
</script>
|
|
||||||
@@ -1,235 +0,0 @@
|
|||||||
import { describe, expect, it } from 'vitest'
|
|
||||||
import {
|
|
||||||
canEditClient,
|
|
||||||
categoryOptionsOf,
|
|
||||||
contactOptionsOf,
|
|
||||||
iriOf,
|
|
||||||
mapAccountingDraft,
|
|
||||||
mapAddressToDraft,
|
|
||||||
mapAddressView,
|
|
||||||
mapContactToDraft,
|
|
||||||
mapRibToDraft,
|
|
||||||
referentialOptionOf,
|
|
||||||
relationOf,
|
|
||||||
showArchiveAction,
|
|
||||||
showRestoreAction,
|
|
||||||
siteOptionsOf,
|
|
||||||
type ClientDetail,
|
|
||||||
} from '../clientConsultation'
|
|
||||||
|
|
||||||
describe('iriOf', () => {
|
|
||||||
it('retourne l\'@id d\'une relation embarquee (objet)', () => {
|
|
||||||
expect(iriOf({ '@id': '/api/payment_types/10', code: 'LCR' })).toBe('/api/payment_types/10')
|
|
||||||
})
|
|
||||||
|
|
||||||
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('relationOf', () => {
|
|
||||||
it('detecte une relation distributeur et expose son nom', () => {
|
|
||||||
const client = { distributor: { '@id': '/api/clients/15', companyName: 'DISTRIB GRAND SUD-OUEST' } } as ClientDetail
|
|
||||||
expect(relationOf(client)).toEqual({ type: 'distributeur', name: 'DISTRIB GRAND SUD-OUEST' })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('detecte une relation courtier et expose son nom', () => {
|
|
||||||
const client = { broker: { '@id': '/api/clients/16', companyName: 'CABINET LEONARD' } } as ClientDetail
|
|
||||||
expect(relationOf(client)).toEqual({ type: 'courtier', name: 'CABINET LEONARD' })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('retourne type null quand aucune relation n\'est posee (cles omises)', () => {
|
|
||||||
expect(relationOf({} as ClientDetail)).toEqual({ type: null, name: null })
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('mapContactToDraft', () => {
|
|
||||||
it('formate les telephones en XX XX XX XX XX et conserve l\'iri', () => {
|
|
||||||
const draft = mapContactToDraft({
|
|
||||||
'@id': '/api/client_contacts/18',
|
|
||||||
id: 18,
|
|
||||||
firstName: 'Sophie',
|
|
||||||
lastName: 'Léonard',
|
|
||||||
jobTitle: 'Gérante',
|
|
||||||
phonePrimary: '0549112233',
|
|
||||||
email: 'sophie@x.fr',
|
|
||||||
})
|
|
||||||
expect(draft.id).toBe(18)
|
|
||||||
expect(draft.iri).toBe('/api/client_contacts/18')
|
|
||||||
expect(draft.phonePrimary).toBe('05 49 11 22 33')
|
|
||||||
expect(draft.hasSecondaryPhone).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('revele le 2e telephone quand phoneSecondary est present', () => {
|
|
||||||
const draft = mapContactToDraft({
|
|
||||||
'@id': '/api/client_contacts/19',
|
|
||||||
id: 19,
|
|
||||||
phonePrimary: '0600000000',
|
|
||||||
phoneSecondary: '0611111111',
|
|
||||||
})
|
|
||||||
expect(draft.hasSecondaryPhone).toBe(true)
|
|
||||||
expect(draft.phoneSecondary).toBe('06 11 11 11 11')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('mapAddressToDraft', () => {
|
|
||||||
it('extrait les iris de sites / categories / contacts (objets ou chaines)', () => {
|
|
||||||
const draft = mapAddressToDraft({
|
|
||||||
'@id': '/api/client_addresses/18',
|
|
||||||
id: 18,
|
|
||||||
country: 'France',
|
|
||||||
postalCode: '86100',
|
|
||||||
city: 'Châtellerault',
|
|
||||||
street: '5 rue des Courtiers',
|
|
||||||
billingEmail: 'factures@x.fr',
|
|
||||||
isProspect: false,
|
|
||||||
isDelivery: false,
|
|
||||||
isBilling: true,
|
|
||||||
sites: [{ '@id': '/api/sites/4', name: 'Chatellerault', color: '#056CF2' }],
|
|
||||||
categories: [{ '@id': '/api/categories/3', code: 'SECTEUR' }],
|
|
||||||
contacts: [{ '@id': '/api/client_contacts/18' }, '/api/client_contacts/20'],
|
|
||||||
})
|
|
||||||
expect(draft.siteIris).toEqual(['/api/sites/4'])
|
|
||||||
expect(draft.categoryIris).toEqual(['/api/categories/3'])
|
|
||||||
expect(draft.contactIris).toEqual(['/api/client_contacts/18', '/api/client_contacts/20'])
|
|
||||||
expect(draft.isBilling).toBe(true)
|
|
||||||
expect(draft.city).toBe('Châtellerault')
|
|
||||||
expect(draft.country).toBe('France')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('tolere les sous-collections absentes (defaut tableau vide, pays France)', () => {
|
|
||||||
const draft = mapAddressToDraft({ '@id': '/api/client_addresses/9', id: 9 })
|
|
||||||
expect(draft.siteIris).toEqual([])
|
|
||||||
expect(draft.categoryIris).toEqual([])
|
|
||||||
expect(draft.contactIris).toEqual([])
|
|
||||||
expect(draft.country).toBe('France')
|
|
||||||
expect(draft.isBilling).toBe(false)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('mapRibToDraft', () => {
|
|
||||||
it('mappe label / bic / iban et l\'id serveur', () => {
|
|
||||||
const draft = mapRibToDraft({ '@id': '/api/client_ribs/3', id: 3, label: 'Compte', bic: 'BNPAFRPPXXX', iban: 'FR14...' })
|
|
||||||
expect(draft).toEqual({ id: 3, label: 'Compte', bic: 'BNPAFRPPXXX', iban: 'FR14...' })
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('mapAccountingDraft', () => {
|
|
||||||
it('mappe les scalaires et resout les iris des referentiels embarques', () => {
|
|
||||||
const acc = mapAccountingDraft({
|
|
||||||
'@id': '/api/clients/1',
|
|
||||||
id: 1,
|
|
||||||
siren: '123456789',
|
|
||||||
accountNumber: '411000',
|
|
||||||
nTva: 'FR123',
|
|
||||||
tvaMode: { '@id': '/api/tva_modes/1' },
|
|
||||||
paymentDelay: { '@id': '/api/payment_delays/2' },
|
|
||||||
paymentType: { '@id': '/api/payment_types/10', code: 'LCR' },
|
|
||||||
bank: { '@id': '/api/banks/3' },
|
|
||||||
} as ClientDetail)
|
|
||||||
expect(acc).toEqual({
|
|
||||||
siren: '123456789',
|
|
||||||
accountNumber: '411000',
|
|
||||||
nTva: 'FR123',
|
|
||||||
tvaModeIri: '/api/tva_modes/1',
|
|
||||||
paymentDelayIri: '/api/payment_delays/2',
|
|
||||||
paymentTypeIri: '/api/payment_types/10',
|
|
||||||
bankIri: '/api/banks/3',
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('renvoie des null quand les champs comptables sont absents (sans accounting.view)', () => {
|
|
||||||
const acc = mapAccountingDraft({} as ClientDetail)
|
|
||||||
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/3', name: 'Secteur', code: 'SECTEUR' }])).toEqual([
|
|
||||||
{ value: '/api/categories/3', label: 'Secteur', code: 'SECTEUR' },
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('siteOptionsOf expose value=IRI, label=nom', () => {
|
|
||||||
expect(siteOptionsOf([{ '@id': '/api/sites/4', name: 'Chatellerault', color: '#000' }])).toEqual([
|
|
||||||
{ value: '/api/sites/4', label: 'Chatellerault' },
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('contactOptionsOf compose le libelle (nom complet, sinon email)', () => {
|
|
||||||
expect(contactOptionsOf([
|
|
||||||
{ '@id': '/api/client_contacts/1', id: 1, firstName: 'Jean', lastName: 'Dupont' },
|
|
||||||
{ '@id': '/api/client_contacts/2', id: 2, email: 'a@b.fr' },
|
|
||||||
])).toEqual([
|
|
||||||
{ value: '/api/client_contacts/1', label: 'Jean Dupont' },
|
|
||||||
{ value: '/api/client_contacts/2', label: 'a@b.fr' },
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('referentialOptionOf : option unique depuis l\'embed, vide pour IRI nu / absent', () => {
|
|
||||||
expect(referentialOptionOf({ '@id': '/api/payment_types/10', label: 'LCR' })).toEqual([
|
|
||||||
{ value: '/api/payment_types/10', 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/client_addresses/18',
|
|
||||||
id: 18,
|
|
||||||
city: 'Châtellerault',
|
|
||||||
sites: [{ '@id': '/api/sites/4', name: 'Chatellerault' }],
|
|
||||||
categories: [{ '@id': '/api/categories/3', name: 'Secteur', code: 'SECTEUR' }],
|
|
||||||
})
|
|
||||||
expect(view.draft.id).toBe(18)
|
|
||||||
expect(view.siteOptions).toEqual([{ value: '/api/sites/4', label: 'Chatellerault' }])
|
|
||||||
expect(view.categoryOptions).toEqual([{ value: '/api/categories/3', label: 'Secteur', code: 'SECTEUR' }])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('canEditClient', () => {
|
|
||||||
const can = (granted: string[]) => (codes: string[]) => codes.some(c => granted.includes(c))
|
|
||||||
|
|
||||||
it('visible pour manage', () => {
|
|
||||||
expect(canEditClient(can(['commercial.clients.manage']))).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('visible pour accounting.manage (role Compta)', () => {
|
|
||||||
expect(canEditClient(can(['commercial.clients.accounting.manage']))).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('masque sans aucune des deux permissions (role Usine)', () => {
|
|
||||||
expect(canEditClient(can(['commercial.clients.view']))).toBe(false)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('showArchiveAction / showRestoreAction', () => {
|
|
||||||
const can = (granted: string[]) => (code: string) => granted.includes(code)
|
|
||||||
|
|
||||||
it('Archiver : visible avec la permission archive ET client non archive', () => {
|
|
||||||
expect(showArchiveAction(can(['commercial.clients.archive']), false)).toBe(true)
|
|
||||||
expect(showArchiveAction(can(['commercial.clients.archive']), true)).toBe(false)
|
|
||||||
expect(showArchiveAction(can([]), false)).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('Restaurer : visible avec la permission archive ET client archive', () => {
|
|
||||||
expect(showRestoreAction(can(['commercial.clients.archive']), true)).toBe(true)
|
|
||||||
expect(showRestoreAction(can(['commercial.clients.archive']), false)).toBe(false)
|
|
||||||
expect(showRestoreAction(can([]), true)).toBe(false)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,321 +0,0 @@
|
|||||||
/**
|
|
||||||
* Helpers purs de l'ecran « Consultation client » (M1 Commercial, lecture seule).
|
|
||||||
*
|
|
||||||
* Mappent le payload `GET /api/clients/{id}` (relations embarquees, cf. groupe
|
|
||||||
* `client:item:read` + `client:read:accounting`) vers les brouillons « plats »
|
|
||||||
* partages avec les blocs reutilisables `ClientContactBlock` / `ClientAddressBlock`
|
|
||||||
* et l'onglet Comptabilite. Ne touchent ni a l'API ni a l'etat reactif : testables
|
|
||||||
* unitairement (cf. clientConsultation.spec.ts).
|
|
||||||
*
|
|
||||||
* Rappels de contrat back (verifies sur l'API reelle) :
|
|
||||||
* - les relations ManyToOne (distributor/broker/tvaMode/paymentType/...) sont
|
|
||||||
* serialisees en OBJETS embarques (avec @id + companyName/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 sans permission
|
|
||||||
* accounting.view (gate serveur via ClientReadGroupContextBuilder).
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { formatPhoneFR } from '~/shared/utils/phone'
|
|
||||||
import type {
|
|
||||||
AddressFormDraft,
|
|
||||||
ContactFormDraft,
|
|
||||||
RibFormDraft,
|
|
||||||
} from '~/modules/commercial/types/clientForm'
|
|
||||||
|
|
||||||
/** 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 client_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 client_address:read). */
|
|
||||||
export interface AddressRead extends HydraRef {
|
|
||||||
id: number
|
|
||||||
country?: string | null
|
|
||||||
postalCode?: string | null
|
|
||||||
city?: string | null
|
|
||||||
street?: string | null
|
|
||||||
streetComplement?: string | null
|
|
||||||
billingEmail?: string | null
|
|
||||||
isProspect?: boolean
|
|
||||||
isDelivery?: boolean
|
|
||||||
isBilling?: 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 client:read:accounting, present ssi accounting.view). */
|
|
||||||
export interface RibRead extends HydraRef {
|
|
||||||
id: number
|
|
||||||
label?: string | null
|
|
||||||
bic?: string | null
|
|
||||||
iban?: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Client relie (distributeur / courtier) embarque (groupe client:read). */
|
|
||||||
export interface RelatedClientRead extends HydraRef {
|
|
||||||
companyName?: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Detail d'un client tel que renvoye par `GET /api/clients/{id}`. Tous les
|
|
||||||
* champs sont optionnels : skip_null_values cote serveur et gating accounting
|
|
||||||
* peuvent omettre n'importe quelle cle.
|
|
||||||
*/
|
|
||||||
export interface ClientDetail extends HydraRef {
|
|
||||||
id: number
|
|
||||||
companyName?: string | null
|
|
||||||
firstName?: string | null
|
|
||||||
lastName?: string | null
|
|
||||||
phonePrimary?: string | null
|
|
||||||
phoneSecondary?: string | null
|
|
||||||
email?: string | null
|
|
||||||
triageService?: boolean
|
|
||||||
isArchived?: boolean
|
|
||||||
categories?: CategoryRead[]
|
|
||||||
distributor?: RelatedClientRead | string | null
|
|
||||||
broker?: RelatedClientRead | string | null
|
|
||||||
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
|
|
||||||
// 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 1.10). */
|
|
||||||
export interface AccountingDraft {
|
|
||||||
siren: string | null
|
|
||||||
accountNumber: string | null
|
|
||||||
nTva: string | null
|
|
||||||
tvaModeIri: string | null
|
|
||||||
paymentDelayIri: string | null
|
|
||||||
paymentTypeIri: string | null
|
|
||||||
bankIri: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Relation Distributeur/Courtier resolue pour l'affichage en lecture seule. */
|
|
||||||
export interface ClientRelation {
|
|
||||||
type: 'distributeur' | 'courtier' | null
|
|
||||||
name: 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: AddressFormDraft
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resout la relation Distributeur/Courtier (RG-1.03 : mutuellement exclusives).
|
|
||||||
* Le nom est lu sur l'objet embarque (`companyName`) ; null si la relation est
|
|
||||||
* un IRI nu ou absente.
|
|
||||||
*/
|
|
||||||
export function relationOf(client: ClientDetail): ClientRelation {
|
|
||||||
const nameOf = (rel: RelatedClientRead | string | null | undefined): string | null =>
|
|
||||||
rel && typeof rel === 'object' ? (rel.companyName ?? null) : null
|
|
||||||
|
|
||||||
if (client.distributor) {
|
|
||||||
return { type: 'distributeur', name: nameOf(client.distributor) }
|
|
||||||
}
|
|
||||||
if (client.broker) {
|
|
||||||
return { type: 'courtier', name: nameOf(client.broker) }
|
|
||||||
}
|
|
||||||
return { type: null, name: null }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Mappe un contact embarque vers un brouillon (telephones formates XX XX XX XX XX). */
|
|
||||||
export function mapContactToDraft(contact: ContactRead): ContactFormDraft {
|
|
||||||
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). */
|
|
||||||
export function mapAddressToDraft(address: AddressRead): AddressFormDraft {
|
|
||||||
return {
|
|
||||||
id: address.id,
|
|
||||||
isProspect: address.isProspect ?? false,
|
|
||||||
isDelivery: address.isDelivery ?? false,
|
|
||||||
isBilling: address.isBilling ?? false,
|
|
||||||
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'])),
|
|
||||||
billingEmail: address.billingEmail ?? null,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Mappe un RIB embarque vers un brouillon. */
|
|
||||||
export function mapRibToDraft(rib: RibRead): RibFormDraft {
|
|
||||||
return {
|
|
||||||
id: rib.id,
|
|
||||||
label: rib.label ?? null,
|
|
||||||
bic: rib.bic ?? null,
|
|
||||||
iban: rib.iban ?? null,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Mappe les champs comptables du client (scalaires + IRI des referentiels). */
|
|
||||||
export function mapAccountingDraft(client: ClientDetail): AccountingDraft {
|
|
||||||
return {
|
|
||||||
siren: client.siren ?? null,
|
|
||||||
accountNumber: client.accountNumber ?? null,
|
|
||||||
nTva: client.nTva ?? null,
|
|
||||||
tvaModeIri: iriOf(client.tvaMode),
|
|
||||||
paymentDelayIri: iriOf(client.paymentDelay),
|
|
||||||
paymentTypeIri: iriOf(client.paymentType),
|
|
||||||
bankIri: iriOf(client.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 client. */
|
|
||||||
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 (1.12).
|
|
||||||
*/
|
|
||||||
export function canEditClient(canAny: (codes: string[]) => boolean): boolean {
|
|
||||||
return canAny(['commercial.clients.manage', 'commercial.clients.accounting.manage'])
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Bouton « Archiver » : permission archive ET client encore actif. */
|
|
||||||
export function showArchiveAction(can: (code: string) => boolean, isArchived: boolean): boolean {
|
|
||||||
return can('commercial.clients.archive') && !isArchived
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Bouton « Restaurer » : permission archive ET client deja archive. */
|
|
||||||
export function showRestoreAction(can: (code: string) => boolean, isArchived: boolean): boolean {
|
|
||||||
return can('commercial.clients.archive') && isArchived
|
|
||||||
}
|
|
||||||
@@ -38,6 +38,11 @@ final class CatalogModule
|
|||||||
return [
|
return [
|
||||||
['code' => 'catalog.categories.view', 'label' => 'Voir les categories'],
|
['code' => 'catalog.categories.view', 'label' => 'Voir les categories'],
|
||||||
['code' => 'catalog.categories.manage', 'label' => 'Gerer les categories (creer, editer, supprimer)'],
|
['code' => 'catalog.categories.manage', 'label' => 'Gerer les categories (creer, editer, supprimer)'],
|
||||||
|
// Lecture-referentiel transverse (ERP-102) : permet de LISTER les categories
|
||||||
|
// pour alimenter les selects des modules Tiers (clients, fournisseurs...),
|
||||||
|
// sans donner l'acces d'administration `.view` (qui ouvre la page Catalogue
|
||||||
|
// dans la sidebar). Accordee aux roles metier via la matrice RBAC § 2.7.
|
||||||
|
['code' => 'catalog.categories.read_ref', 'label' => 'Lire le referentiel categories (transverse, lecture seule)'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,13 +42,19 @@ use Symfony\Component\Validator\Constraints as Assert;
|
|||||||
*/
|
*/
|
||||||
#[ApiResource(
|
#[ApiResource(
|
||||||
operations: [
|
operations: [
|
||||||
|
// Lecture (liste + item) : permission d'administration `view` OU permission
|
||||||
|
// de lecture-referentiel transverse `read_ref` (ERP-102). Les referentiels
|
||||||
|
// categories sont consommes par les modules Tiers (selects creation/filtre
|
||||||
|
// client) : tout role qui gere des tiers doit pouvoir les lire sans porter
|
||||||
|
// l'acces admin du Catalogue. `read_ref` est une permission Catalog (pas un
|
||||||
|
// code d'un autre module) -> isolement inter-module preserve.
|
||||||
new GetCollection(
|
new GetCollection(
|
||||||
security: "is_granted('catalog.categories.view')",
|
security: "is_granted('catalog.categories.view') or is_granted('catalog.categories.read_ref')",
|
||||||
normalizationContext: ['groups' => ['category:read', 'default:read']],
|
normalizationContext: ['groups' => ['category:read', 'default:read']],
|
||||||
provider: CategoryProvider::class,
|
provider: CategoryProvider::class,
|
||||||
),
|
),
|
||||||
new Get(
|
new Get(
|
||||||
security: "is_granted('catalog.categories.view')",
|
security: "is_granted('catalog.categories.view') or is_granted('catalog.categories.read_ref')",
|
||||||
normalizationContext: ['groups' => ['category:read', 'default:read']],
|
normalizationContext: ['groups' => ['category:read', 'default:read']],
|
||||||
provider: CategoryProvider::class,
|
provider: CategoryProvider::class,
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -62,6 +62,9 @@ final class RbacSeeder
|
|||||||
'permissions' => [
|
'permissions' => [
|
||||||
'commercial.clients.view',
|
'commercial.clients.view',
|
||||||
'commercial.clients.manage',
|
'commercial.clients.manage',
|
||||||
|
// Lecture des referentiels transverses pour les selects client (ERP-102).
|
||||||
|
'catalog.categories.read_ref',
|
||||||
|
'sites.read_ref',
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
self::ROLE_COMPTA => [
|
self::ROLE_COMPTA => [
|
||||||
@@ -70,6 +73,9 @@ final class RbacSeeder
|
|||||||
'commercial.clients.view',
|
'commercial.clients.view',
|
||||||
'commercial.clients.accounting.view',
|
'commercial.clients.accounting.view',
|
||||||
'commercial.clients.accounting.manage',
|
'commercial.clients.accounting.manage',
|
||||||
|
// Lecture des referentiels transverses pour les selects client (ERP-102).
|
||||||
|
'catalog.categories.read_ref',
|
||||||
|
'sites.read_ref',
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
self::ROLE_COMMERCIALE => [
|
self::ROLE_COMMERCIALE => [
|
||||||
@@ -77,6 +83,9 @@ final class RbacSeeder
|
|||||||
'permissions' => [
|
'permissions' => [
|
||||||
'commercial.clients.view',
|
'commercial.clients.view',
|
||||||
'commercial.clients.manage',
|
'commercial.clients.manage',
|
||||||
|
// Lecture des referentiels transverses pour les selects client (ERP-102).
|
||||||
|
'catalog.categories.read_ref',
|
||||||
|
'sites.read_ref',
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
self::ROLE_USINE => [
|
self::ROLE_USINE => [
|
||||||
|
|||||||
@@ -40,13 +40,18 @@ use Symfony\Component\Validator\Constraints as Assert;
|
|||||||
*/
|
*/
|
||||||
#[ApiResource(
|
#[ApiResource(
|
||||||
operations: [
|
operations: [
|
||||||
|
// Lecture (liste + item) : permission d'administration `sites.view` OU
|
||||||
|
// permission de lecture-referentiel transverse `sites.read_ref` (ERP-102).
|
||||||
|
// Le referentiel sites alimente les selects d'adresse des modules Tiers :
|
||||||
|
// tout role qui gere des tiers doit pouvoir le lire sans porter l'acces
|
||||||
|
// admin des Sites.
|
||||||
new GetCollection(
|
new GetCollection(
|
||||||
normalizationContext: ['groups' => ['site:read']],
|
normalizationContext: ['groups' => ['site:read']],
|
||||||
security: "is_granted('sites.view')",
|
security: "is_granted('sites.view') or is_granted('sites.read_ref')",
|
||||||
),
|
),
|
||||||
new Get(
|
new Get(
|
||||||
normalizationContext: ['groups' => ['site:read']],
|
normalizationContext: ['groups' => ['site:read']],
|
||||||
security: "is_granted('sites.view')",
|
security: "is_granted('sites.view') or is_granted('sites.read_ref')",
|
||||||
),
|
),
|
||||||
new Post(
|
new Post(
|
||||||
normalizationContext: ['groups' => ['site:read']],
|
normalizationContext: ['groups' => ['site:read']],
|
||||||
|
|||||||
@@ -33,6 +33,11 @@ final class SitesModule
|
|||||||
['code' => 'sites.view', 'label' => 'Voir les sites'],
|
['code' => 'sites.view', 'label' => 'Voir les sites'],
|
||||||
['code' => 'sites.manage', 'label' => 'Gerer les sites (creer, editer, supprimer)'],
|
['code' => 'sites.manage', 'label' => 'Gerer les sites (creer, editer, supprimer)'],
|
||||||
['code' => 'sites.bypass_scope', 'label' => 'Voir les donnees site-scoped de tous les sites (bypass du filtrage)'],
|
['code' => 'sites.bypass_scope', 'label' => 'Voir les donnees site-scoped de tous les sites (bypass du filtrage)'],
|
||||||
|
// Lecture-referentiel transverse (ERP-102) : permet de LISTER les sites
|
||||||
|
// pour alimenter les selects des modules Tiers (adresses client...), sans
|
||||||
|
// donner l'acces d'administration `.view` (qui ouvre la page Sites dans la
|
||||||
|
// sidebar). Accordee aux roles metier via la matrice RBAC § 2.7.
|
||||||
|
['code' => 'sites.read_ref', 'label' => 'Lire le referentiel sites (transverse, lecture seule)'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -272,6 +272,33 @@ final class ClientRBACMatrixTest extends AbstractCommercialApiTestCase
|
|||||||
self::assertResponseStatusCodeSame(200);
|
self::assertResponseStatusCodeSame(200);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testBusinessRolesCanReadCategoriesAndSitesReferentials(): void
|
||||||
|
{
|
||||||
|
// ERP-102 : /categories et /sites sont des referentiels TRANSVERSES.
|
||||||
|
// Tout role qui gere des clients (bureau / compta / commerciale) doit
|
||||||
|
// pouvoir les LISTER pour alimenter les selects de creation/filtre client,
|
||||||
|
// via la permission de lecture-referentiel dediee (catalog.categories.read_ref
|
||||||
|
// / sites.read_ref) attachee par la matrice § 2.7 — sans pour autant porter
|
||||||
|
// la permission d'administration `.view`. Usine, sans aucune permission,
|
||||||
|
// reste interdit.
|
||||||
|
foreach (['bureau', 'compta', 'commerciale'] as $role) {
|
||||||
|
$client = $this->authAs($role);
|
||||||
|
|
||||||
|
$client->request('GET', '/api/categories', ['headers' => ['Accept' => self::LD]]);
|
||||||
|
self::assertResponseStatusCodeSame(200, sprintf('Le role %s doit pouvoir lister /categories', $role));
|
||||||
|
|
||||||
|
$client->request('GET', '/api/sites', ['headers' => ['Accept' => self::LD]]);
|
||||||
|
self::assertResponseStatusCodeSame(200, sprintf('Le role %s doit pouvoir lister /sites', $role));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Usine : aucune permission -> reste a 403 sur les referentiels.
|
||||||
|
$usine = $this->authAs('usine');
|
||||||
|
$usine->request('GET', '/api/categories', ['headers' => ['Accept' => self::LD]]);
|
||||||
|
self::assertResponseStatusCodeSame(403, 'Usine ne doit pas pouvoir lister /categories');
|
||||||
|
$usine->request('GET', '/api/sites', ['headers' => ['Accept' => self::LD]]);
|
||||||
|
self::assertResponseStatusCodeSame(403, 'Usine ne doit pas pouvoir lister /sites');
|
||||||
|
}
|
||||||
|
|
||||||
private function authAs(string $role): Client
|
private function authAs(string $role): Client
|
||||||
{
|
{
|
||||||
return $this->authenticatedClient($role, self::PWD);
|
return $this->authenticatedClient($role, self::PWD);
|
||||||
|
|||||||
@@ -16,17 +16,18 @@ use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
|
|||||||
*/
|
*/
|
||||||
final class SitesModuleTest extends KernelTestCase
|
final class SitesModuleTest extends KernelTestCase
|
||||||
{
|
{
|
||||||
public function testPermissionsSetContainsExactlyThreeCodes(): void
|
public function testPermissionsSetContainsExactlyFourCodes(): void
|
||||||
{
|
{
|
||||||
// Garde-fou : si quelqu'un ajoute une permission sans ajuster les
|
// Garde-fou : si quelqu'un ajoute une permission sans ajuster les
|
||||||
// tests ou la doc, ce test casse explicitement. Si au contraire une
|
// tests ou la doc, ce test casse explicitement. Si au contraire une
|
||||||
// permission disparait (ex: bypass_scope retire par erreur), meme
|
// permission disparait (ex: bypass_scope retire par erreur), meme
|
||||||
// effet. Le set de 3 permissions est fige par ce test.
|
// effet. Le set de permissions est fige par ce test.
|
||||||
|
// `sites.read_ref` ajoutee en ERP-102 (lecture-referentiel transverse).
|
||||||
$codes = array_column(SitesModule::permissions(), 'code');
|
$codes = array_column(SitesModule::permissions(), 'code');
|
||||||
sort($codes);
|
sort($codes);
|
||||||
|
|
||||||
self::assertSame(
|
self::assertSame(
|
||||||
['sites.bypass_scope', 'sites.manage', 'sites.view'],
|
['sites.bypass_scope', 'sites.manage', 'sites.read_ref', 'sites.view'],
|
||||||
$codes,
|
$codes,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user