From 572291241360b6daba5f5f812d26da3e349f1364 Mon Sep 17 00:00:00 2001 From: tristan Date: Thu, 11 Jun 2026 08:13:35 +0200 Subject: [PATCH] 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) --- .../composables/__tests__/useSupplier.spec.ts | 95 ++++ .../commercial/composables/useSupplier.ts | 71 +++ .../commercial/pages/suppliers/[id]/index.vue | 454 ++++++++++++++++++ .../__tests__/supplierConsultation.spec.ts | 224 +++++++++ .../commercial/utils/supplierConsultation.ts | 301 ++++++++++++ 5 files changed, 1145 insertions(+) create mode 100644 frontend/modules/commercial/composables/__tests__/useSupplier.spec.ts create mode 100644 frontend/modules/commercial/composables/useSupplier.ts create mode 100644 frontend/modules/commercial/pages/suppliers/[id]/index.vue create mode 100644 frontend/modules/commercial/utils/__tests__/supplierConsultation.spec.ts create mode 100644 frontend/modules/commercial/utils/supplierConsultation.ts diff --git a/frontend/modules/commercial/composables/__tests__/useSupplier.spec.ts b/frontend/modules/commercial/composables/__tests__/useSupplier.spec.ts new file mode 100644 index 0000000..c2749e7 --- /dev/null +++ b/frontend/modules/commercial/composables/__tests__/useSupplier.spec.ts @@ -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) + }) +}) diff --git a/frontend/modules/commercial/composables/useSupplier.ts b/frontend/modules/commercial/composables/useSupplier.ts new file mode 100644 index 0000000..47d05a1 --- /dev/null +++ b/frontend/modules/commercial/composables/useSupplier.ts @@ -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(null) + const loading = ref(false) + const error = ref(false) + + /** Recupere le detail complet (embed contacts/adresses/ribs + comptabilite). */ + function fetchDetail(): Promise { + return api.get( + `/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 { + 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 { + await api.patch(`/suppliers/${id}`, { isArchived }, { toast: false }) + supplier.value = await fetchDetail() + } + + return { + supplier, + loading, + error, + load, + archive: () => setArchived(true), + restore: () => setArchived(false), + } +} diff --git a/frontend/modules/commercial/pages/suppliers/[id]/index.vue b/frontend/modules/commercial/pages/suppliers/[id]/index.vue new file mode 100644 index 0000000..41c721d --- /dev/null +++ b/frontend/modules/commercial/pages/suppliers/[id]/index.vue @@ -0,0 +1,454 @@ + + + diff --git a/frontend/modules/commercial/utils/__tests__/supplierConsultation.spec.ts b/frontend/modules/commercial/utils/__tests__/supplierConsultation.spec.ts new file mode 100644 index 0000000..eb67488 --- /dev/null +++ b/frontend/modules/commercial/utils/__tests__/supplierConsultation.spec.ts @@ -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) + }) +}) diff --git a/frontend/modules/commercial/utils/supplierConsultation.ts b/frontend/modules/commercial/utils/supplierConsultation.ts new file mode 100644 index 0000000..9264b61 --- /dev/null +++ b/frontend/modules/commercial/utils/supplierConsultation.ts @@ -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 +} + +/** 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 }