Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c8bff68373 | |||
| b444061237 | |||
| 5f3da7022b | |||
| b36520d3b1 | |||
| a340d8139a | |||
| 7d8a633eee | |||
| df9451a5f4 | |||
| cb12490ba0 | |||
| a442d124a3 | |||
| 431d831c8b | |||
| 3f356f0679 | |||
| c1ce940c98 | |||
| c594a76d47 | |||
| 59bae8c5e6 | |||
| 477f77a6b5 |
@@ -79,6 +79,7 @@ Regles :
|
||||
- **Toujours `{ toast: false }`** sur l'appel API qui veut un mapping inline (sinon le toast natif d'`useApi` masque le fin).
|
||||
- **Cas metier specifique** (ex: 409 doublon) : `setError('champ', message)` + toast explicite **avant** de deleguer le reste a `handleApiError`. Cf. `useCategoryForm` (doublon RG-1.07).
|
||||
- **Collections** (listes de sous-entites sauvees par un appel par ligne) : une erreur PAR LIGNE via un tableau `ref<Record<string, string>[]>` aligne sur l'index, peuple par `mapViolationsToRecord(error.response._data)` (util pur de `shared/utils/api.ts`). Le composant de ligne expose une prop `:errors` (`Record<string, string>`) bindee sur le `:error` de chaque champ. Cf. `ClientContactBlock` / `ClientAddressBlock` et les submits de `clients/new.vue` / `clients/[id]/edit.vue`.
|
||||
- **Message back technique → surcharge i18n par code** : la plupart des contraintes back portent un message FR explicite (affiche tel quel). Mais une 422 peut porter un message TECHNIQUE non montrable (ex. erreur de type API Platform sur une date non parsable : « Cette valeur doit être de type DateTimeImmutable|null. », voire en anglais selon la negociation). On le surcharge **cote front** via le `code` de violation (UUID Symfony fige, robuste — pas un match sur le texte) : table `VIOLATION_MESSAGE_I18N` + `resolveViolationMessage` dans `shared/utils/api.ts`, appliquee par `useFormErrors`. Ajouter un cas = une entree `code -> cle i18n`. Cas reference : date invalide (MalioDate forwarde la saisie brute via `@update:rawValue`, le back renvoie 422 sur `foundedAt` grace a `collectDenormalizationErrors`, le front affiche `errors.validation.invalidDate`).
|
||||
|
||||
**Interdit** : se contenter d'un toast global sur une 422 quand le back identifie les champs fautifs (`propertyPath`). Reimplementer un mapping `if/else` par champ a la main au lieu d'`useFormErrors` / `mapViolationsToRecord`.
|
||||
|
||||
|
||||
@@ -5,10 +5,12 @@ use App\Module\Catalog\CatalogModule;
|
||||
use App\Module\Commercial\CommercialModule;
|
||||
use App\Module\Core\CoreModule;
|
||||
use App\Module\Sites\SitesModule;
|
||||
use App\Module\Transport\TransportModule;
|
||||
|
||||
return [
|
||||
CoreModule::class,
|
||||
CommercialModule::class,
|
||||
SitesModule::class,
|
||||
CatalogModule::class,
|
||||
TransportModule::class,
|
||||
];
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Active le composant HTTP Client (symfony/http-client) et enregistre
|
||||
# l'autowiring de HttpClientInterface. Utilise par les commandes de
|
||||
# synchronisation de referentiels externes (QUALIMAT, IDTF...).
|
||||
framework:
|
||||
http_client:
|
||||
default_options:
|
||||
timeout: 30
|
||||
headers:
|
||||
User-Agent: 'Starseed-ERP (referentiel-sync)'
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
parameters:
|
||||
app.version: '0.1.103'
|
||||
app.version: '0.1.110'
|
||||
|
||||
@@ -386,7 +386,10 @@
|
||||
},
|
||||
"title": "Erreur",
|
||||
"generic": "Une erreur est survenue.",
|
||||
"unknown": "Erreur inconnue."
|
||||
"unknown": "Erreur inconnue.",
|
||||
"validation": {
|
||||
"invalidDate": "Date invalide"
|
||||
}
|
||||
},
|
||||
"sites": {
|
||||
"selector": {
|
||||
|
||||
@@ -187,7 +187,7 @@ import {
|
||||
addressTypeFromFlags,
|
||||
isBillingEmailRequired,
|
||||
type AddressType,
|
||||
} from '~/modules/commercial/utils/clientFormRules'
|
||||
} from '~/modules/commercial/utils/forms/clientFormRules'
|
||||
import { useAddressAutocomplete, type AddressSuggestion } from '~/shared/composables/useAddressAutocomplete'
|
||||
import type { CategoryOption, RefOption } from '~/modules/commercial/composables/useClientReferentials'
|
||||
import type { AddressFormDraft } from '~/modules/commercial/types/clientForm'
|
||||
|
||||
@@ -26,13 +26,18 @@
|
||||
:error="errors?.firstName"
|
||||
@update:model-value="(v: string) => update('firstName', v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="model.jobTitle"
|
||||
:label="t('commercial.clients.form.contact.jobTitle')"
|
||||
:readonly="readonly"
|
||||
:error="errors?.jobTitle"
|
||||
@update:model-value="(v: string) => update('jobTitle', v)"
|
||||
/>
|
||||
<!-- Fonction sur 2 colonnes : on wrappe car MalioInputText
|
||||
(inheritAttrs:false) renvoie `class` sur l'input interne, pas sur la
|
||||
cellule de grille. Le wrapper porte le col-span-2, le champ le remplit. -->
|
||||
<div class="col-span-2">
|
||||
<MalioInputText
|
||||
:model-value="model.jobTitle"
|
||||
:label="t('commercial.clients.form.contact.jobTitle')"
|
||||
:readonly="readonly"
|
||||
:error="errors?.jobTitle"
|
||||
@update:model-value="(v: string) => update('jobTitle', v)"
|
||||
/>
|
||||
</div>
|
||||
<MalioInputEmail
|
||||
:model-value="model.email"
|
||||
:label="t('commercial.clients.form.contact.email')"
|
||||
|
||||
@@ -25,13 +25,18 @@
|
||||
:error="errors?.firstName"
|
||||
@update:model-value="(v: string) => update('firstName', v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="model.jobTitle"
|
||||
:label="t('commercial.suppliers.form.contact.jobTitle')"
|
||||
:readonly="readonly"
|
||||
:error="errors?.jobTitle"
|
||||
@update:model-value="(v: string) => update('jobTitle', v)"
|
||||
/>
|
||||
<!-- Fonction sur 2 colonnes : on wrappe car MalioInputText
|
||||
(inheritAttrs:false) renvoie `class` sur l'input interne, pas sur la
|
||||
cellule de grille. Le wrapper porte le col-span-2, le champ le remplit. -->
|
||||
<div class="col-span-2">
|
||||
<MalioInputText
|
||||
:model-value="model.jobTitle"
|
||||
:label="t('commercial.suppliers.form.contact.jobTitle')"
|
||||
:readonly="readonly"
|
||||
:error="errors?.jobTitle"
|
||||
@update:model-value="(v: string) => update('jobTitle', v)"
|
||||
/>
|
||||
</div>
|
||||
<MalioInputEmail
|
||||
:model-value="model.email"
|
||||
:label="t('commercial.suppliers.form.contact.email')"
|
||||
|
||||
@@ -30,6 +30,10 @@ describe('useClientReferentials.loadCommon (resilience ERP-102)', () => {
|
||||
if (url === '/sites') {
|
||||
return Promise.resolve({ member: [{ '@id': '/api/sites/1', name: 'Chatellerault', postalCode: '86100' }] })
|
||||
}
|
||||
if (url === '/countries') {
|
||||
// Pays : value === label === name (l'adresse stocke le nom).
|
||||
return Promise.resolve({ member: [{ '@id': '/api/countries/1', code: 'FR', name: 'France' }] })
|
||||
}
|
||||
return Promise.resolve({
|
||||
member: [{ '@id': '/api/x/1', code: 'X', label: 'Libelle X' }],
|
||||
})
|
||||
@@ -44,6 +48,8 @@ describe('useClientReferentials.loadCommon (resilience ERP-102)', () => {
|
||||
expect(refs.sites.value).toEqual([{ value: '/api/sites/1', label: '86' }])
|
||||
expect(refs.tvaModes.value).toEqual([{ value: '/api/x/1', label: 'Libelle X' }])
|
||||
expect(refs.banks.value).toEqual([{ value: '/api/x/1', label: 'Libelle X' }])
|
||||
// Pays : value = nom du pays (et non l'IRI).
|
||||
expect(refs.countries.value).toEqual([{ value: 'France', label: 'France' }])
|
||||
|
||||
// Seul le select en echec reste vide.
|
||||
expect(refs.categories.value).toEqual([])
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
// Mocks des composables auto-importes par Nuxt (indisponibles sous happy-dom).
|
||||
const mockGet = vi.hoisted(() => vi.fn())
|
||||
const mockPatch = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.stubGlobal('useApi', () => ({
|
||||
get: mockGet,
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
patch: mockPatch,
|
||||
delete: vi.fn(),
|
||||
}))
|
||||
|
||||
const { useSupplier } = await import('../useSupplier')
|
||||
|
||||
const SAMPLE = { '@id': '/api/suppliers/85', id: 85, companyName: 'DOD59393F 862875', isArchived: false }
|
||||
|
||||
describe('useSupplier', () => {
|
||||
beforeEach(() => {
|
||||
mockGet.mockReset()
|
||||
mockPatch.mockReset()
|
||||
mockGet.mockResolvedValue(SAMPLE)
|
||||
mockPatch.mockResolvedValue({ ...SAMPLE, isArchived: true })
|
||||
})
|
||||
|
||||
it('charge le detail via GET /suppliers/{id} en Hydra, sans toast', async () => {
|
||||
const { supplier, load } = useSupplier(85)
|
||||
await load()
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
'/suppliers/85',
|
||||
{},
|
||||
expect.objectContaining({
|
||||
headers: { Accept: 'application/ld+json' },
|
||||
toast: false,
|
||||
}),
|
||||
)
|
||||
expect(supplier.value).toEqual(SAMPLE)
|
||||
})
|
||||
|
||||
it('bascule loading pendant le chargement et le retombe a false', async () => {
|
||||
const { loading, load } = useSupplier(85)
|
||||
const promise = load()
|
||||
expect(loading.value).toBe(true)
|
||||
await promise
|
||||
expect(loading.value).toBe(false)
|
||||
})
|
||||
|
||||
it('marque error et laisse supplier null si le GET echoue (404...)', async () => {
|
||||
mockGet.mockRejectedValueOnce(new Error('not found'))
|
||||
const { supplier, error, load } = useSupplier(99)
|
||||
await load()
|
||||
expect(error.value).toBe(true)
|
||||
expect(supplier.value).toBeNull()
|
||||
})
|
||||
|
||||
it('archive() PATCHe { isArchived: true } sans toast puis RECHARGE le detail complet', async () => {
|
||||
// 1er GET = chargement initial, 2e GET = rechargement post-archivage.
|
||||
mockGet.mockResolvedValueOnce(SAMPLE)
|
||||
mockGet.mockResolvedValueOnce({ ...SAMPLE, isArchived: true })
|
||||
const { supplier, load, archive } = useSupplier(85)
|
||||
await load()
|
||||
await archive()
|
||||
|
||||
expect(mockPatch).toHaveBeenCalledWith(
|
||||
'/suppliers/85',
|
||||
{ isArchived: true },
|
||||
expect.objectContaining({ toast: false }),
|
||||
)
|
||||
// Le detail est re-fetch (le PATCH ne renvoie pas l'embed complet).
|
||||
expect(mockGet).toHaveBeenCalledTimes(2)
|
||||
expect(supplier.value?.isArchived).toBe(true)
|
||||
})
|
||||
|
||||
it('restore() PATCHe { isArchived: false } (payload isArchived SEUL)', async () => {
|
||||
const { load, restore } = useSupplier(85)
|
||||
await load()
|
||||
await restore()
|
||||
|
||||
expect(mockPatch).toHaveBeenCalledWith(
|
||||
'/suppliers/85',
|
||||
{ isArchived: false },
|
||||
expect.objectContaining({ toast: false }),
|
||||
)
|
||||
})
|
||||
|
||||
it('propage l\'erreur (ex: 403 sans permission archive, 409 conflit homonyme) au lieu de l\'avaler', async () => {
|
||||
const forbidden = { response: { status: 403 } }
|
||||
mockPatch.mockRejectedValueOnce(forbidden)
|
||||
const { load, archive } = useSupplier(85)
|
||||
await load()
|
||||
await expect(archive()).rejects.toBe(forbidden)
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ref } from 'vue'
|
||||
import type { ClientDetail } from '~/modules/commercial/utils/clientConsultation'
|
||||
import type { ClientDetail } from '~/modules/commercial/utils/forms/clientConsultation'
|
||||
|
||||
/**
|
||||
* Chargement et actions d'archivage d'un client unique (ecran « Consultation
|
||||
|
||||
@@ -3,7 +3,7 @@ import { ref } from 'vue'
|
||||
/**
|
||||
* Charge les referentiels (listes courtes) alimentant les selects de l'ecran
|
||||
* « Ajouter un client » : categories, sites, modes de TVA, delais et types de
|
||||
* reglement, banques, et les listes distributeurs / courtiers.
|
||||
* reglement, banques, pays, et les listes distributeurs / courtiers.
|
||||
*
|
||||
* Toutes les collections sont recuperees en entier via l'echappatoire prevue
|
||||
* `?pagination=false` (referentiels de quelques dizaines d'entrees max), avec
|
||||
@@ -57,6 +57,11 @@ interface ClientMember extends HydraMember {
|
||||
companyName: string
|
||||
}
|
||||
|
||||
interface CountryMember extends HydraMember {
|
||||
code: string
|
||||
name: string
|
||||
}
|
||||
|
||||
const LD_JSON_HEADERS = { Accept: 'application/ld+json' }
|
||||
|
||||
export function useClientReferentials() {
|
||||
@@ -68,6 +73,7 @@ export function useClientReferentials() {
|
||||
const paymentDelays = ref<RefOption[]>([])
|
||||
const paymentTypes = ref<PaymentTypeOption[]>([])
|
||||
const banks = ref<RefOption[]>([])
|
||||
const countries = ref<RefOption[]>([])
|
||||
const distributors = ref<ClientOption[]>([])
|
||||
const brokers = ref<ClientOption[]>([])
|
||||
|
||||
@@ -116,6 +122,12 @@ export function useClientReferentials() {
|
||||
.then((types) => { paymentTypes.value = types.map(t => ({ value: t['@id'], label: t.label, code: t.code })) }),
|
||||
fetchAll<ReferentialMember>('/banks')
|
||||
.then((banksList) => { banks.value = banksList.map(b => ({ value: b['@id'], label: b.label })) }),
|
||||
// Pays (ERP-116) : la valeur d'option est le NOM du pays (et non l'IRI),
|
||||
// car l'adresse stocke `country` en chaine libre (« France »...). On
|
||||
// conserve ainsi la compatibilite avec les adresses existantes sans FK
|
||||
// ni migration de donnees a ce stade. value === label.
|
||||
fetchAll<CountryMember>('/countries')
|
||||
.then((list) => { countries.value = list.map(c => ({ value: c.name, label: c.name })) }),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -144,6 +156,7 @@ export function useClientReferentials() {
|
||||
paymentDelays,
|
||||
paymentTypes,
|
||||
banks,
|
||||
countries,
|
||||
distributors,
|
||||
brokers,
|
||||
loadCommon,
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { ref } from 'vue'
|
||||
import type { SupplierDetail } from '~/modules/commercial/utils/forms/supplierConsultation'
|
||||
|
||||
/**
|
||||
* Chargement et actions d'archivage d'un fournisseur unique (ecran « Consultation
|
||||
* fournisseur », ERP-95). Miroir de `useClient` (M1). Lit le detail embarque via
|
||||
* `GET /api/suppliers/{id}` (contacts / adresses / ribs sous `supplier:item:read` /
|
||||
* `supplier:read:accounting`) et expose les bascules d'archivage (PATCH `isArchived`
|
||||
* SEUL — tout autre champ => 422).
|
||||
*
|
||||
* L'en-tete `Accept: application/ld+json` est impose pour obtenir le payload
|
||||
* Hydra complet (sans lui, API Platform 4 renvoie une representation reduite).
|
||||
*
|
||||
* Etat 100 % local a l'instance (refs) — aucune persistance URL. Les erreurs
|
||||
* d'archivage/restauration (notamment le 409 d'homonyme actif a la restauration)
|
||||
* sont PROPAGEES a l'appelant, qui decide du toast a afficher.
|
||||
*/
|
||||
export function useSupplier(id: number | string) {
|
||||
const api = useApi()
|
||||
|
||||
const supplier = ref<SupplierDetail | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref(false)
|
||||
|
||||
/** Recupere le detail complet (embed contacts/adresses/ribs + comptabilite). */
|
||||
function fetchDetail(): Promise<SupplierDetail> {
|
||||
return api.get<SupplierDetail>(
|
||||
`/suppliers/${id}`,
|
||||
{},
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
}
|
||||
|
||||
/** Charge le detail du fournisseur. En cas d'echec : `error = true`, `supplier = null`. */
|
||||
async function load(): Promise<void> {
|
||||
loading.value = true
|
||||
error.value = false
|
||||
try {
|
||||
supplier.value = await fetchDetail()
|
||||
}
|
||||
catch {
|
||||
error.value = true
|
||||
supplier.value = null
|
||||
}
|
||||
finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bascule l'archivage (PATCH `isArchived` SEUL — tout autre champ => 422),
|
||||
* puis RECHARGE le detail complet : la reponse du PATCH ne porte que le groupe
|
||||
* `supplier:read` (ni l'embed contacts/adresses/ribs ni les libelles des
|
||||
* referentiels comptables), un simple merge laisserait l'affichage incoherent.
|
||||
* Toute erreur (notamment le 409 d'homonyme actif a la restauration) est
|
||||
* propagee a l'appelant AVANT le rechargement.
|
||||
*/
|
||||
async function setArchived(isArchived: boolean): Promise<void> {
|
||||
await api.patch(`/suppliers/${id}`, { isArchived }, { toast: false })
|
||||
supplier.value = await fetchDetail()
|
||||
}
|
||||
|
||||
return {
|
||||
supplier,
|
||||
loading,
|
||||
error,
|
||||
load,
|
||||
archive: () => setArchived(true),
|
||||
restore: () => setArchived(false),
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,11 @@ interface ReferentialMember extends HydraMember {
|
||||
label: string
|
||||
}
|
||||
|
||||
interface CountryMember extends HydraMember {
|
||||
code: string
|
||||
name: string
|
||||
}
|
||||
|
||||
const LD_JSON_HEADERS = { Accept: 'application/ld+json' }
|
||||
|
||||
export function useSupplierReferentials() {
|
||||
@@ -62,6 +67,7 @@ export function useSupplierReferentials() {
|
||||
const paymentDelays = ref<RefOption[]>([])
|
||||
const paymentTypes = ref<PaymentTypeOption[]>([])
|
||||
const banks = ref<RefOption[]>([])
|
||||
const countries = ref<RefOption[]>([])
|
||||
|
||||
/** Recupere une collection complete (pagination desactivee) en Hydra. */
|
||||
async function fetchAll<T extends HydraMember>(
|
||||
@@ -103,6 +109,13 @@ export function useSupplierReferentials() {
|
||||
.then((types) => { paymentTypes.value = types.map(t => ({ value: t['@id'], label: t.label, code: t.code })) }),
|
||||
fetchAll<ReferentialMember>('/banks')
|
||||
.then((banksList) => { banks.value = banksList.map(b => ({ value: b['@id'], label: b.label })) }),
|
||||
// Pays (ERP-116) : la valeur d'option est le NOM du pays (et non l'IRI),
|
||||
// car l'adresse stocke `country` en chaine libre (« France »...). On
|
||||
// conserve ainsi la compatibilite avec les adresses existantes sans FK
|
||||
// ni migration de donnees a ce stade. value === label. Aligne sur les
|
||||
// clients (`useClientReferentials`) pour une liste de pays identique.
|
||||
fetchAll<CountryMember>('/countries')
|
||||
.then((list) => { countries.value = list.map(c => ({ value: c.name, label: c.name })) }),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -113,6 +126,7 @@ export function useSupplierReferentials() {
|
||||
paymentDelays,
|
||||
paymentTypes,
|
||||
banks,
|
||||
countries,
|
||||
loadCommon,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,6 +116,7 @@
|
||||
:readonly="businessReadonly"
|
||||
:editable="true"
|
||||
:error="informationErrors.errors.foundedAt"
|
||||
@update:raw-value="(v: string) => information.foundedAtRaw = v"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.employeesCount"
|
||||
@@ -303,7 +304,7 @@
|
||||
class="relative bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]"
|
||||
>
|
||||
<MalioButtonIcon
|
||||
v-if="!accountingReadonly"
|
||||
v-if="!accountingReadonly && visibleRibs.length > 1"
|
||||
icon="mdi:delete-outline"
|
||||
variant="ghost"
|
||||
button-class="absolute top-3 right-3"
|
||||
@@ -401,7 +402,7 @@ import {
|
||||
mapAddressToDraft,
|
||||
mapRibToDraft,
|
||||
type ClientDetail,
|
||||
} from '~/modules/commercial/utils/clientConsultation'
|
||||
} from '~/modules/commercial/utils/forms/clientConsultation'
|
||||
import {
|
||||
buildAccountingPayload,
|
||||
buildAddressPayload,
|
||||
@@ -417,7 +418,7 @@ import {
|
||||
type ClientEditAbilities,
|
||||
type InformationFormDraft,
|
||||
type MainFormDraft,
|
||||
} from '~/modules/commercial/utils/clientEdit'
|
||||
} from '~/modules/commercial/utils/forms/clientEdit'
|
||||
import {
|
||||
buildClientFormTabKeys,
|
||||
isAddressValid,
|
||||
@@ -429,7 +430,7 @@ import {
|
||||
isRibComplete,
|
||||
isRibRequiredForPaymentType,
|
||||
showsRelationAndTriageFields,
|
||||
} from '~/modules/commercial/utils/clientFormRules'
|
||||
} from '~/modules/commercial/utils/forms/clientFormRules'
|
||||
import {
|
||||
emptyAddress,
|
||||
emptyContact,
|
||||
@@ -553,10 +554,21 @@ const contactOptions = computed<RefOption[]>(() =>
|
||||
})),
|
||||
)
|
||||
|
||||
const countryOptions: RefOption[] = [
|
||||
{ value: 'France', label: 'France' },
|
||||
{ value: 'Espagne', label: 'Espagne' },
|
||||
]
|
||||
// Pays : referentiel `country` charge via l'API (ERP-116), en remplacement de
|
||||
// l'ancienne liste codee en dur. Valeur = nom du pays (l'adresse stocke
|
||||
// `country` en chaine libre, donc value === label). On merge la valeur deja
|
||||
// stockee sur chaque adresse (embed) — comme les autres selects de cet ecran —
|
||||
// pour ne pas vider le select si `/countries` echoue (resilience ERP-102) ou si
|
||||
// un pays historique n'appartient pas au referentiel.
|
||||
const embedCountryOptions = computed<RefOption[]>(() =>
|
||||
mergeOptions([], (client.value?.addresses ?? [])
|
||||
.map(a => a.country)
|
||||
.filter((c): c is string => !!c)
|
||||
.map(c => ({ value: c, label: c }))),
|
||||
)
|
||||
const countryOptions = computed<RefOption[]>(() =>
|
||||
mergeOptions(referentials.countries.value, embedCountryOptions.value),
|
||||
)
|
||||
|
||||
const relationOptions = computed<RefOption[]>(() => [
|
||||
{ value: 'distributeur', label: t('commercial.clients.form.main.relationDistributor') },
|
||||
@@ -689,7 +701,7 @@ async function submitMain(): Promise<void> {
|
||||
mainSubmitting.value = true
|
||||
mainErrors.clearErrors()
|
||||
try {
|
||||
const updated = await api.patch<ClientDetail>(`/clients/${clientId}`, buildMainPayload(main), {
|
||||
const updated = await api.patch<ClientDetail>(`/clients/${clientId}`, buildMainPayload(main, { forUpdate: true }), {
|
||||
headers: { Accept: 'application/ld+json' },
|
||||
toast: false,
|
||||
})
|
||||
@@ -859,7 +871,10 @@ async function submitAddresses(): Promise<void> {
|
||||
addresses.value,
|
||||
addressErrors,
|
||||
async (address) => {
|
||||
const body = buildAddressPayload(address, isBillingEmailRequired(address))
|
||||
// Edition d'une adresse existante : champ requis vide envoye en `''`
|
||||
// (NotBlank 422) au lieu d'etre omis — sinon le PATCH garderait
|
||||
// l'ancienne valeur (faux 200). Creation (id null) : omit classique.
|
||||
const body = buildAddressPayload(address, isBillingEmailRequired(address), { forUpdate: address.id !== null })
|
||||
if (address.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/clients/${clientId}/addresses`,
|
||||
@@ -898,17 +913,16 @@ const visibleRibs = computed(() => isRibRequired.value ? ribs.value : [])
|
||||
function onPaymentTypeChange(value: string | number | null): void {
|
||||
accounting.paymentTypeIri = value === null ? null : String(value)
|
||||
if (!isBankRequired.value) accounting.bankIri = null
|
||||
// Les RIB n'ont de sens que pour une LCR (RG-1.13) : on amorce un bloc vide
|
||||
// quand LCR est choisi, sinon on vide la liste — les RIB deja persistes sont
|
||||
// marques pour suppression serveur au prochain enregistrement.
|
||||
// ERP-121 : un RIB est une coordonnee bancaire du client, decouplee du mode de
|
||||
// reglement. Au passage hors-LCR on ne SUPPRIME plus les RIB existants : ils
|
||||
// restent en base, simplement masques a l'ecran (visibleRibs = []), et
|
||||
// reapparaissent tels quels si l'on repasse en LCR. Seule la corbeille d'un
|
||||
// bloc (askRemoveRib) retire reellement un RIB.
|
||||
if (isRibRequired.value) {
|
||||
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||
}
|
||||
else {
|
||||
for (const rib of ribs.value) {
|
||||
if (rib.id != null) removedRibIds.value.push(rib.id)
|
||||
}
|
||||
ribs.value = []
|
||||
// Hors-LCR : on nettoie seulement les erreurs inline (plus affichees).
|
||||
ribErrors.value = []
|
||||
}
|
||||
}
|
||||
@@ -937,45 +951,58 @@ function askRemoveRib(index: number): void {
|
||||
/**
|
||||
* Valide l'onglet Comptabilite : POST/PATCH des RIB sur la sous-ressource PUIS
|
||||
* PATCH des scalaires (groupe client:write:accounting, exige accounting.manage cote
|
||||
* back) PUIS DELETE des RIB retires. Les RIB crees d'abord : le back valide RG-1.13
|
||||
* (LCR => au moins un RIB persiste) sur le PATCH scalaires ; les suppressions en
|
||||
* dernier (le guard back n'autorise la suppression du dernier RIB qu'une fois quitte
|
||||
* LCR). Aucun champ main/information dans le payload (mode strict RG-1.28 : sinon
|
||||
* 403 sur tout le payload).
|
||||
* back) PUIS DELETE des RIB explicitement retires. Les RIB crees d'abord : le back
|
||||
* valide RG-1.13 (LCR => au moins un RIB persiste) sur le PATCH scalaires.
|
||||
*
|
||||
* ERP-121 : les RIB ne sont (re)soumis QUE sous LCR — hors-LCR ce sont des
|
||||
* coordonnees dormantes conservees telles quelles, masquees a l'ecran et jamais
|
||||
* re-ecrites. `removedRibIds` ne contient plus que les suppressions EXPLICITES
|
||||
* (corbeille d'un bloc, toujours sous LCR), plus l'auto-suppression au changement
|
||||
* de type de reglement. Aucun champ main/information dans le payload (mode strict
|
||||
* RG-1.28 : sinon 403 sur tout le payload).
|
||||
*/
|
||||
async function submitAccounting(): Promise<void> {
|
||||
if (accountingReadonly.value || tabSubmitting.value) return
|
||||
tabSubmitting.value = true
|
||||
accountingErrors.clearErrors()
|
||||
try {
|
||||
// 1) POST/PATCH des RIB d'abord (erreurs inline par ligne, tous les blocs
|
||||
// tentes). Le back exige >=1 RIB persiste pour valider une LCR a l'etape 2.
|
||||
// Seuls les blocs RIB TOTALEMENT vides sont ignores : un RIB partiel (ex.
|
||||
// IBAN seul) est soumis -> 422 NotBlank (label / bic / iban) inline.
|
||||
const ribHasError = await submitRows(
|
||||
ribs.value,
|
||||
ribErrors,
|
||||
async (rib) => {
|
||||
const body = buildRibPayload(rib)
|
||||
if (rib.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/clients/${clientId}/ribs`,
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
rib.id = created.id
|
||||
}
|
||||
else {
|
||||
await api.patch(`/client_ribs/${rib.id}`, body, { toast: false })
|
||||
}
|
||||
},
|
||||
error => showError(error),
|
||||
// On ne saute QUE les amorces neuves (id null) totalement vides. Un
|
||||
// RIB existant vide est soumis -> 422 NotBlank inline (sinon la modif
|
||||
// serait perdue en silence avec un faux toast de succes).
|
||||
rib => rib.id === null && isRibBlank(rib),
|
||||
)
|
||||
if (ribHasError) return
|
||||
// 1) POST/PATCH des RIB d'abord — UNIQUEMENT sous LCR (erreurs inline par
|
||||
// ligne, tous les blocs tentes). Le back exige >=1 RIB persiste pour valider
|
||||
// une LCR a l'etape 2. Hors-LCR (ERP-121), les RIB sont des coordonnees
|
||||
// dormantes : rien d'editable n'est affiche, on ne les re-soumet pas.
|
||||
// On ne saute une amorce neuve vide QUE s'il reste un autre RIB soumettable :
|
||||
// sinon (ex. l'unique RIB existant supprime, remplace par un bloc vide), on la
|
||||
// soumet pour declencher la 422 NotBlank inline plutot que de laisser le DELETE
|
||||
// echouer en « dernier RIB d'une LCR » (message plat sans propertyPath).
|
||||
if (isRibRequired.value) {
|
||||
const hasSubmittableRib = ribs.value.some(r => r.id !== null || !isRibBlank(r))
|
||||
const ribHasError = await submitRows(
|
||||
ribs.value,
|
||||
ribErrors,
|
||||
async (rib) => {
|
||||
// Edition d'un RIB existant : champ requis vide envoye en `''` (NotBlank
|
||||
// 422) au lieu d'etre omis (sinon le PATCH garderait l'ancienne valeur).
|
||||
const body = buildRibPayload(rib, { forUpdate: rib.id !== null })
|
||||
if (rib.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/clients/${clientId}/ribs`,
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
rib.id = created.id
|
||||
}
|
||||
else {
|
||||
await api.patch(`/client_ribs/${rib.id}`, body, { toast: false })
|
||||
}
|
||||
},
|
||||
error => showError(error),
|
||||
// On ne saute une amorce neuve (id null) totalement vide que si un autre RIB
|
||||
// est soumettable. Un RIB existant vide est toujours soumis -> 422 NotBlank
|
||||
// inline (sinon la modif serait perdue en silence avec un faux toast succes).
|
||||
rib => hasSubmittableRib && rib.id === null && isRibBlank(rib),
|
||||
)
|
||||
if (ribHasError) return
|
||||
}
|
||||
|
||||
// 2) PATCH des scalaires comptables (erreurs inline sur leurs champs).
|
||||
try {
|
||||
@@ -986,8 +1013,9 @@ async function submitAccounting(): Promise<void> {
|
||||
return
|
||||
}
|
||||
|
||||
// 3) DELETE des RIB retires : APRES le PATCH scalaires (si on quitte LCR, le
|
||||
// guard back n'autorise la suppression du dernier RIB qu'une fois le type change).
|
||||
// 3) DELETE des RIB explicitement retires (corbeille d'un bloc) : APRES le
|
||||
// PATCH scalaires (le guard back refuse la suppression du dernier RIB d'une
|
||||
// LCR). ERP-121 : plus aucune suppression automatique au passage hors-LCR.
|
||||
for (const id of removedRibIds.value) {
|
||||
await api.delete(`/client_ribs/${id}`, {}, { toast: false })
|
||||
}
|
||||
|
||||
@@ -280,7 +280,7 @@
|
||||
<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 { buildClientFormTabKeys, isRibRequiredForPaymentType } from '~/modules/commercial/utils/forms/clientFormRules'
|
||||
import { readHistoryTab } from '~/shared/utils/historyTab'
|
||||
import {
|
||||
canEditClient,
|
||||
@@ -290,13 +290,14 @@ import {
|
||||
mapAddressView,
|
||||
mapContactToDraft,
|
||||
mapRibToDraft,
|
||||
paymentTypeCodeOf,
|
||||
referentialOptionOf,
|
||||
relationOf,
|
||||
showArchiveAction,
|
||||
showRestoreAction,
|
||||
type ClientDetail,
|
||||
type SelectOption,
|
||||
} from '~/modules/commercial/utils/clientConsultation'
|
||||
} from '~/modules/commercial/utils/forms/clientConsultation'
|
||||
import { emptyAddress, emptyContact } from '~/modules/commercial/types/clientForm'
|
||||
|
||||
// Masque d'affichage (purement visuel, la donnee reste celle du serveur).
|
||||
@@ -355,9 +356,16 @@ const addressViews = computed(() => {
|
||||
return views.length ? views : [{ draft: emptyAddress(), siteOptions: [], categoryOptions: [] }]
|
||||
})
|
||||
// Exception au placeholder ci-dessus : on n'affiche AUCUN bloc RIB quand le
|
||||
// client n'en a pas (un RIB n'existe que pour un reglement LCR — RG-1.13). Pas
|
||||
// de bloc vierge fantome en consultation.
|
||||
const ribs = computed(() => (client.value?.ribs ?? []).map(mapRibToDraft))
|
||||
// client n'en a pas. Pas de bloc vierge fantome en consultation.
|
||||
// ERP-121 : un client peut desormais conserver des RIB « dormants » apres etre
|
||||
// repasse hors-LCR (on ne les supprime plus). En consultation, decision metier =
|
||||
// on les masque TOTALEMENT : on n'affiche les RIB que si le type de reglement
|
||||
// courant est LCR (le `code` est embarque sous client:read:accounting).
|
||||
const ribs = computed(() =>
|
||||
isRibRequiredForPaymentType(paymentTypeCodeOf(client.value?.paymentType))
|
||||
? (client.value?.ribs ?? []).map(mapRibToDraft)
|
||||
: [],
|
||||
)
|
||||
// Draft comptable (tout null si l'utilisateur n'a pas accounting.view).
|
||||
const accounting = computed(() => mapAccountingDraft(client.value ?? ({} as ClientDetail)))
|
||||
|
||||
@@ -384,10 +392,18 @@ const relationOptions = computed<SelectOption[]>(() => [
|
||||
{ value: 'courtier', label: t('commercial.clients.form.main.relationBroker') },
|
||||
])
|
||||
|
||||
const countryOptions: SelectOption[] = [
|
||||
{ value: 'France', label: 'France' },
|
||||
{ value: 'Espagne', label: 'Espagne' },
|
||||
]
|
||||
// Pays (ERP-116) : options construites depuis l'EMBED des adresses (jamais via
|
||||
// GET /countries, sur le meme principe que les autres selects de consultation
|
||||
// — en 403 pour les roles metier non-admin). Valeur = nom du pays stocke tel
|
||||
// quel dans l'adresse, donc value === label ; suffit a afficher le libelle en
|
||||
// lecture seule.
|
||||
const countryOptions = computed<SelectOption[]>(() =>
|
||||
[...new Set(
|
||||
(client.value?.addresses ?? [])
|
||||
.map(a => a.country)
|
||||
.filter((c): c is string => !!c),
|
||||
)].map(c => ({ value: c, label: c })),
|
||||
)
|
||||
|
||||
// Selects comptables : libelle issu de l'embed (option unique ou vide).
|
||||
const tvaModeOptions = computed(() => referentialOptionOf(client.value?.tvaMode))
|
||||
|
||||
@@ -111,6 +111,7 @@
|
||||
:readonly="isValidated('information')"
|
||||
:editable="true"
|
||||
:error="informationErrors.errors.foundedAt"
|
||||
@update:raw-value="(v: string) => information.foundedAtRaw = v"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.employeesCount"
|
||||
@@ -302,7 +303,7 @@
|
||||
>
|
||||
<!-- ariaLabel via v-bind objet (prop camelCase ; aria-* serait un attribut HTML). -->
|
||||
<MalioButtonIcon
|
||||
v-if="!accountingReadonly"
|
||||
v-if="!accountingReadonly && visibleRibs.length > 1"
|
||||
icon="mdi:delete-outline"
|
||||
variant="ghost"
|
||||
button-class="absolute top-3 right-3"
|
||||
@@ -401,12 +402,12 @@ import {
|
||||
isRibRequiredForPaymentType,
|
||||
lastFillableTabKey,
|
||||
showsRelationAndTriageFields,
|
||||
} from '~/modules/commercial/utils/clientFormRules'
|
||||
} from '~/modules/commercial/utils/forms/clientFormRules'
|
||||
import {
|
||||
buildAddressPayload,
|
||||
buildMainPayload,
|
||||
buildRibPayload,
|
||||
} from '~/modules/commercial/utils/clientEdit'
|
||||
} from '~/modules/commercial/utils/forms/clientEdit'
|
||||
import {
|
||||
emptyAddress,
|
||||
emptyContact,
|
||||
@@ -651,6 +652,8 @@ const information = reactive({
|
||||
description: null as string | null,
|
||||
competitors: null as string | null,
|
||||
foundedAt: null as string | null,
|
||||
// Saisie brute invalide remontee par MalioDate (cf. foundedAtRaw, MUI-44).
|
||||
foundedAtRaw: '',
|
||||
employeesCount: null as string | null,
|
||||
revenueAmount: null as string | null,
|
||||
profitAmount: null as string | null,
|
||||
@@ -666,7 +669,8 @@ async function submitInformation(): Promise<void> {
|
||||
await api.patch(`/clients/${clientId.value}`, {
|
||||
description: information.description || null,
|
||||
competitors: information.competitors || null,
|
||||
foundedAt: information.foundedAt || null,
|
||||
// Saisie invalide prioritaire -> 422 back sur foundedAt (cf. foundedAtRaw).
|
||||
foundedAt: information.foundedAtRaw || information.foundedAt || null,
|
||||
employeesCount: information.employeesCount ? Number(information.employeesCount) : null,
|
||||
revenueAmount: information.revenueAmount || null,
|
||||
profitAmount: information.profitAmount || null,
|
||||
@@ -778,11 +782,17 @@ const contactOptions = computed<RefOption[]>(() =>
|
||||
})),
|
||||
)
|
||||
|
||||
// Pays disponibles (France preselectionnee par defaut sur chaque adresse).
|
||||
const countryOptions: RefOption[] = [
|
||||
{ value: 'France', label: 'France' },
|
||||
{ value: 'Espagne', label: 'Espagne' },
|
||||
]
|
||||
// Pays disponibles : referentiel `country` charge via l'API (ERP-116), en
|
||||
// remplacement de l'ancienne liste codee en dur. France reste preselectionnee
|
||||
// par defaut sur chaque adresse (cf. valeur initiale du draft d'adresse) : on
|
||||
// garantit donc sa presence en fallback si `/countries` echoue (resilience
|
||||
// ERP-102), pour ne pas afficher un select vide sur une valeur deja soumise.
|
||||
const countryOptions = computed<RefOption[]>(() => {
|
||||
const list = referentials.countries.value
|
||||
return list.some(c => c.value === 'France')
|
||||
? list
|
||||
: [{ value: 'France', label: 'France' }, ...list]
|
||||
})
|
||||
|
||||
// « + Adresse » desactive tant que la derniere adresse n'est pas valide.
|
||||
const canAddAddress = computed(() => {
|
||||
@@ -875,13 +885,14 @@ function onPaymentTypeChange(value: string | number | null): void {
|
||||
accounting.paymentTypeIri = value === null ? null : String(value)
|
||||
// La banque n'a de sens que pour un virement : on la vide sinon (RG-1.12).
|
||||
if (!isBankRequired.value) accounting.bankIri = null
|
||||
// Les RIB n'ont de sens que pour une LCR (RG-1.13) : on amorce un bloc vide
|
||||
// quand LCR est choisi, on vide la liste sinon (pas de RIB fantome soumis).
|
||||
// ERP-121 : on ne jette plus la saisie RIB au passage hors-LCR. Les blocs sont
|
||||
// masques (visibleRibs = []) mais conserves, et reapparaissent si l'on repasse
|
||||
// en LCR. Ils ne sont persistes qu'a la validation SOUS LCR (cf. submitAccounting),
|
||||
// donc une saisie abandonnee hors-LCR ne cree aucun RIB orphelin.
|
||||
if (isRibRequired.value) {
|
||||
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||
}
|
||||
else {
|
||||
ribs.value = []
|
||||
ribErrors.value = []
|
||||
}
|
||||
}
|
||||
@@ -918,35 +929,41 @@ async function submitAccounting(): Promise<void> {
|
||||
tabSubmitting.value = true
|
||||
accountingErrors.clearErrors()
|
||||
try {
|
||||
// 1) POST/PATCH des RIB d'abord (erreurs inline par ligne, tous les blocs
|
||||
// tentes). Le back exige >=1 RIB persiste pour valider une LCR a l'etape 2.
|
||||
// Seuls les blocs RIB TOTALEMENT vides sont ignores : un RIB partiel (ex.
|
||||
// IBAN seul) est soumis -> 422 NotBlank (label / bic / iban) inline.
|
||||
const ribHasError = await submitRows(
|
||||
ribs.value,
|
||||
ribErrors,
|
||||
async (rib) => {
|
||||
// Payload partage avec l'edition (buildRibPayload, ERP-119).
|
||||
const body = buildRibPayload(rib)
|
||||
if (rib.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/clients/${clientId.value}/ribs`,
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
rib.id = created.id
|
||||
}
|
||||
else {
|
||||
await api.patch(`/client_ribs/${rib.id}`, body, { toast: false })
|
||||
}
|
||||
},
|
||||
error => toast.error({ title: t('commercial.clients.toast.error'), message: apiErrorMessage(error) }),
|
||||
// On ne saute QUE les amorces neuves (id null) totalement vides. Un
|
||||
// RIB existant vide est soumis -> 422 NotBlank inline (sinon la modif
|
||||
// serait perdue en silence avec un faux toast de succes).
|
||||
rib => rib.id === null && isRibBlank(rib),
|
||||
)
|
||||
if (ribHasError) return
|
||||
// 1) POST/PATCH des RIB d'abord — UNIQUEMENT sous LCR (erreurs inline par
|
||||
// ligne, tous les blocs tentes). Le back exige >=1 RIB persiste pour valider
|
||||
// une LCR a l'etape 2. Hors-LCR (ERP-121), une saisie RIB eventuellement
|
||||
// restee dans le brouillon est masquee et n'est PAS persistee (pas de RIB
|
||||
// orphelin sur un client en virement).
|
||||
// On ne saute une amorce neuve vide QUE s'il reste un autre RIB soumettable :
|
||||
// sinon (LCR sans aucun RIB rempli) on la soumet -> 422 NotBlank inline.
|
||||
if (isRibRequired.value) {
|
||||
const hasSubmittableRib = ribs.value.some(r => r.id !== null || !isRibBlank(r))
|
||||
const ribHasError = await submitRows(
|
||||
ribs.value,
|
||||
ribErrors,
|
||||
async (rib) => {
|
||||
// Payload partage avec l'edition (buildRibPayload, ERP-119).
|
||||
const body = buildRibPayload(rib)
|
||||
if (rib.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/clients/${clientId.value}/ribs`,
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
rib.id = created.id
|
||||
}
|
||||
else {
|
||||
await api.patch(`/client_ribs/${rib.id}`, body, { toast: false })
|
||||
}
|
||||
},
|
||||
error => toast.error({ title: t('commercial.clients.toast.error'), message: apiErrorMessage(error) }),
|
||||
// On ne saute une amorce neuve (id null) totalement vide que si un autre RIB
|
||||
// est soumettable. Un RIB existant vide est toujours soumis -> 422 NotBlank
|
||||
// inline (sinon la modif serait perdue en silence avec un faux toast succes).
|
||||
rib => hasSubmittableRib && rib.id === null && isRibBlank(rib),
|
||||
)
|
||||
if (ribHasError) return
|
||||
}
|
||||
|
||||
// 2) PATCH des scalaires comptables (erreurs inline sur leurs champs).
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,946 @@
|
||||
<template>
|
||||
<div>
|
||||
<!-- En-tete : retour consultation + nom du fournisseur. -->
|
||||
<div class="flex items-center gap-3 pt-11">
|
||||
<MalioButtonIcon
|
||||
icon="mdi:arrow-left-bold"
|
||||
icon-size="24"
|
||||
variant="ghost"
|
||||
v-bind="{ ariaLabel: t('commercial.suppliers.edit.back') }"
|
||||
@click="goBack"
|
||||
/>
|
||||
<h1 class="text-[30px] font-semibold text-m-primary">{{ headerTitle }}</h1>
|
||||
</div>
|
||||
|
||||
<!-- Etats de chargement / introuvable. -->
|
||||
<p v-if="loading" class="mt-12 text-center text-black/60">{{ t('commercial.suppliers.edit.loading') }}</p>
|
||||
<p v-else-if="error" class="mt-12 text-center text-m-danger">{{ t('commercial.suppliers.edit.notFound') }}</p>
|
||||
|
||||
<template v-else-if="supplier">
|
||||
<!-- ── Bloc principal (pre-rempli, editable si `manage`) ──────────────
|
||||
Conserve en modification (miroir client) ; edite via son propre
|
||||
PATCH scope sur le groupe supplier:write:main. Readonly pour les
|
||||
roles sans `manage` (ex. Compta). Pas de contact inline (ERP-106). -->
|
||||
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText
|
||||
v-model="main.companyName"
|
||||
:label="t('commercial.suppliers.form.main.companyName')"
|
||||
:required="true"
|
||||
:readonly="businessReadonly"
|
||||
:error="mainErrors.errors.companyName"
|
||||
/>
|
||||
<MalioSelectCheckbox
|
||||
:model-value="main.categoryIris"
|
||||
:options="mainCategoryOptions"
|
||||
:label="t('commercial.suppliers.form.main.categories')"
|
||||
:display-tag="true"
|
||||
:readonly="businessReadonly"
|
||||
:required="true"
|
||||
:error="mainErrors.errors.categories"
|
||||
@update:model-value="(v: (string | number)[]) => main.categoryIris = v.map(String)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="!businessReadonly" class="mt-12 flex justify-center">
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('commercial.suppliers.edit.save')"
|
||||
:disabled="mainSubmitting"
|
||||
@click="submitMain"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- ── Onglets : navigation LIBRE, edition independante par onglet ──── -->
|
||||
<MalioTabList v-model="activeTab" :tabs="tabs" :max-visible-tabs="5" :max-width="1100" class="mt-[60px]">
|
||||
<!-- Onglet Information -->
|
||||
<template #information>
|
||||
<div class="mt-12 grid grid-cols-4 gap-x-[44px] gap-y-4 bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
|
||||
<!-- pt-1/pb-1 alignent le textarea (h-full) sur les inputs. -->
|
||||
<MalioInputTextArea
|
||||
v-model="information.description"
|
||||
:label="t('commercial.suppliers.form.information.description')"
|
||||
resize="none"
|
||||
group-class="row-span-2 pt-1 pb-1"
|
||||
text-input="h-full text-lg"
|
||||
:readonly="businessReadonly"
|
||||
:error="informationErrors.errors.description"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.competitors"
|
||||
:label="t('commercial.suppliers.form.information.competitors')"
|
||||
:readonly="businessReadonly"
|
||||
:error="informationErrors.errors.competitors"
|
||||
/>
|
||||
<MalioDate
|
||||
v-model="information.foundedAt"
|
||||
:label="t('commercial.suppliers.form.information.foundedAt')"
|
||||
:readonly="businessReadonly"
|
||||
:editable="true"
|
||||
:error="informationErrors.errors.foundedAt"
|
||||
@update:raw-value="(v: string) => information.foundedAtRaw = v"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.employeesCount"
|
||||
:label="t('commercial.suppliers.form.information.employeesCount')"
|
||||
:mask="EMPLOYEES_MASK"
|
||||
:readonly="businessReadonly"
|
||||
:error="informationErrors.errors.employeesCount"
|
||||
/>
|
||||
<MalioInputAmount
|
||||
v-model="information.revenueAmount"
|
||||
:label="t('commercial.suppliers.form.information.revenueAmount')"
|
||||
:readonly="businessReadonly"
|
||||
:error="informationErrors.errors.revenueAmount"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.directorName"
|
||||
:label="t('commercial.suppliers.form.information.directorName')"
|
||||
:readonly="businessReadonly"
|
||||
:error="informationErrors.errors.directorName"
|
||||
/>
|
||||
<MalioInputAmount
|
||||
v-model="information.profitAmount"
|
||||
:label="t('commercial.suppliers.form.information.profitAmount')"
|
||||
:readonly="businessReadonly"
|
||||
:error="informationErrors.errors.profitAmount"
|
||||
/>
|
||||
<!-- Volume previsionnel : specifique fournisseur (entier). -->
|
||||
<MalioInputText
|
||||
v-model="information.volumeForecast"
|
||||
:label="t('commercial.suppliers.form.information.volumeForecast')"
|
||||
:mask="VOLUME_FORECAST_MASK"
|
||||
:readonly="businessReadonly"
|
||||
:error="informationErrors.errors.volumeForecast"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="!businessReadonly" class="mt-12 flex justify-center">
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('commercial.suppliers.edit.save')"
|
||||
:disabled="tabSubmitting"
|
||||
@click="submitInformation"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Onglet Contacts -->
|
||||
<template #contacts>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
<SupplierContactBlock
|
||||
v-for="(contact, index) in contacts"
|
||||
:key="contact.id ?? `new-${index}`"
|
||||
:model-value="contact"
|
||||
:title="t('commercial.suppliers.form.contact.title', { n: index + 1 })"
|
||||
:removable="contacts.length > 1"
|
||||
:readonly="businessReadonly"
|
||||
:errors="contactErrors[index]"
|
||||
@update:model-value="(v) => contacts[index] = v"
|
||||
@remove="askRemoveContact(index)"
|
||||
/>
|
||||
<div v-if="!businessReadonly" class="flex justify-center gap-6">
|
||||
<MalioButton
|
||||
variant="secondary"
|
||||
icon-name="mdi:add-bold"
|
||||
icon-position="left"
|
||||
:label="t('commercial.suppliers.form.contact.add')"
|
||||
:disabled="!canAddContact"
|
||||
@click="addContact"
|
||||
/>
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('commercial.suppliers.edit.save')"
|
||||
:disabled="tabSubmitting"
|
||||
@click="submitContacts"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Onglet Adresses -->
|
||||
<template #addresses>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
<SupplierAddressBlock
|
||||
v-for="(address, index) in addresses"
|
||||
:key="address.id ?? `new-${index}`"
|
||||
:model-value="address"
|
||||
:title="t('commercial.suppliers.form.address.title', { n: index + 1 })"
|
||||
:category-options="mainCategoryOptions"
|
||||
:site-options="siteOptions"
|
||||
:contact-options="contactOptions"
|
||||
:country-options="countryOptions"
|
||||
:removable="addresses.length > 1"
|
||||
:readonly="businessReadonly"
|
||||
:errors="addressErrors[index]"
|
||||
@update:model-value="(v) => addresses[index] = v"
|
||||
@remove="askRemoveAddress(index)"
|
||||
@degraded="onAddressDegraded"
|
||||
/>
|
||||
<div v-if="!businessReadonly" class="flex justify-center gap-6">
|
||||
<MalioButton
|
||||
variant="secondary"
|
||||
icon-name="mdi:add-bold"
|
||||
icon-position="left"
|
||||
:label="t('commercial.suppliers.form.address.add')"
|
||||
:disabled="!canAddAddress"
|
||||
@click="addAddress"
|
||||
/>
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('commercial.suppliers.edit.save')"
|
||||
:disabled="tabSubmitting"
|
||||
@click="submitAddresses"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Onglet Comptabilite (present uniquement si accounting.view ;
|
||||
editable uniquement si accounting.manage). -->
|
||||
<template v-if="canAccountingView" #accounting>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
<div class="bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
|
||||
<div class="grid grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText
|
||||
v-model="accounting.siren"
|
||||
:label="t('commercial.suppliers.form.accounting.siren')"
|
||||
:mask="SIREN_MASK"
|
||||
:readonly="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.siren"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="accounting.accountNumber"
|
||||
:label="t('commercial.suppliers.form.accounting.accountNumber')"
|
||||
:readonly="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.accountNumber"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.tvaModeIri"
|
||||
:options="tvaModeOptions"
|
||||
:label="t('commercial.suppliers.form.accounting.tvaMode')"
|
||||
:readonly="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.tvaMode"
|
||||
@update:model-value="(v: string | number | null) => accounting.tvaModeIri = v === null ? null : String(v)"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="accounting.nTva"
|
||||
:label="t('commercial.suppliers.form.accounting.nTva')"
|
||||
:readonly="accountingReadonly"
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.nTva"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.paymentDelayIri"
|
||||
:options="paymentDelayOptions"
|
||||
:label="t('commercial.suppliers.form.accounting.paymentDelay')"
|
||||
:readonly="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.paymentDelay"
|
||||
@update:model-value="(v: string | number | null) => accounting.paymentDelayIri = v === null ? null : String(v)"
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.paymentTypeIri"
|
||||
:options="paymentTypeOptions"
|
||||
:label="t('commercial.suppliers.form.accounting.paymentType')"
|
||||
:readonly="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.paymentType"
|
||||
@update:model-value="onPaymentTypeChange"
|
||||
/>
|
||||
<MalioSelect
|
||||
v-if="isBankRequired"
|
||||
:model-value="accounting.bankIri"
|
||||
:options="bankOptions"
|
||||
:label="t('commercial.suppliers.form.accounting.bank')"
|
||||
:readonly="accountingReadonly"
|
||||
empty-option-label=""
|
||||
:required="true"
|
||||
:error="accountingErrors.errors.bank"
|
||||
@update:model-value="(v: string | number | null) => accounting.bankIri = v === null ? null : String(v)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Blocs RIB — affiches uniquement si type de reglement = LCR (RG-2.08). -->
|
||||
<div
|
||||
v-for="(rib, index) in visibleRibs"
|
||||
:key="rib.id ?? `new-${index}`"
|
||||
class="relative bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]"
|
||||
>
|
||||
<MalioButtonIcon
|
||||
v-if="!accountingReadonly && visibleRibs.length > 1"
|
||||
icon="mdi:delete-outline"
|
||||
variant="ghost"
|
||||
button-class="absolute top-3 right-3"
|
||||
v-bind="{ ariaLabel: t('commercial.suppliers.form.accounting.removeRib') }"
|
||||
@click="askRemoveRib(index)"
|
||||
/>
|
||||
<div class="grid grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText
|
||||
v-model="rib.label"
|
||||
:label="t('commercial.suppliers.form.accounting.ribLabel')"
|
||||
:readonly="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.label"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="rib.bic"
|
||||
:label="t('commercial.suppliers.form.accounting.ribBic')"
|
||||
:readonly="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.bic"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="rib.iban"
|
||||
:label="t('commercial.suppliers.form.accounting.ribIban')"
|
||||
:readonly="accountingReadonly"
|
||||
:required="isRibRequired"
|
||||
:error="ribErrors[index]?.iban"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!accountingReadonly" class="flex justify-center gap-6">
|
||||
<MalioButton
|
||||
v-if="isRibRequired"
|
||||
variant="secondary"
|
||||
icon-name="mdi:add-bold"
|
||||
icon-position="left"
|
||||
:label="t('commercial.suppliers.form.accounting.addRib')"
|
||||
:disabled="!canAddRib"
|
||||
@click="addRib"
|
||||
/>
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('commercial.suppliers.edit.save')"
|
||||
:disabled="tabSubmitting"
|
||||
@click="submitAccounting"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Onglets non encore implementes : frame vide (navigation libre). -->
|
||||
<template #transport><ComingSoonPlaceholder /></template>
|
||||
<template #statistics><ComingSoonPlaceholder /></template>
|
||||
<template #reports><ComingSoonPlaceholder /></template>
|
||||
<template #exchanges><ComingSoonPlaceholder /></template>
|
||||
</MalioTabList>
|
||||
</template>
|
||||
|
||||
<!-- Modal de confirmation generique (suppression contact / adresse / RIB). -->
|
||||
<MalioModal v-model="confirmModal.open" modal-class="max-w-md">
|
||||
<template #header>
|
||||
<h2 class="text-[24px] font-bold">{{ t('commercial.suppliers.form.confirmDelete.title') }}</h2>
|
||||
</template>
|
||||
<p>{{ confirmModal.message }}</p>
|
||||
<template #footer>
|
||||
<MalioButton
|
||||
variant="secondary"
|
||||
button-class="flex-1"
|
||||
:label="t('commercial.suppliers.form.confirmDelete.cancel')"
|
||||
@click="confirmModal.open = false"
|
||||
/>
|
||||
<MalioButton
|
||||
variant="danger"
|
||||
button-class="flex-1"
|
||||
:label="t('commercial.suppliers.form.confirmDelete.confirm')"
|
||||
@click="runConfirm"
|
||||
/>
|
||||
</template>
|
||||
</MalioModal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { useSupplier } from '~/modules/commercial/composables/useSupplier'
|
||||
import { useSupplierReferentials, type CategoryOption, type RefOption } from '~/modules/commercial/composables/useSupplierReferentials'
|
||||
import { useSupplierFormErrors } from '~/modules/commercial/composables/useSupplierFormErrors'
|
||||
import {
|
||||
canEditSupplier,
|
||||
categoryOptionsOf,
|
||||
referentialOptionOf,
|
||||
siteOptionsOf,
|
||||
mapContactToDraft,
|
||||
mapAddressToDraft,
|
||||
mapRibToDraft,
|
||||
type SupplierDetail,
|
||||
} from '~/modules/commercial/utils/forms/supplierConsultation'
|
||||
import {
|
||||
buildAccountingPayload,
|
||||
buildAddressPayload,
|
||||
buildContactPayload,
|
||||
buildInformationPayload,
|
||||
buildMainPayload,
|
||||
buildRibPayload,
|
||||
mapAccountingFormDraft,
|
||||
mapInformationDraft,
|
||||
mapMainDraft,
|
||||
resolveTabEditability,
|
||||
type AccountingFormDraft,
|
||||
type InformationFormDraft,
|
||||
type MainFormDraft,
|
||||
type SupplierEditAbilities,
|
||||
} from '~/modules/commercial/utils/forms/supplierEdit'
|
||||
import {
|
||||
buildSupplierFormTabKeys,
|
||||
isAddressValid,
|
||||
isBankRequiredForPaymentType,
|
||||
isContactBlank,
|
||||
isContactNamed,
|
||||
isRibBlank,
|
||||
isRibComplete,
|
||||
isRibRequiredForPaymentType,
|
||||
} from '~/modules/commercial/utils/forms/supplierFormRules'
|
||||
import {
|
||||
emptyAddress,
|
||||
emptyContact,
|
||||
emptyRib,
|
||||
type SupplierAddressFormDraft,
|
||||
type SupplierContactFormDraft,
|
||||
type SupplierRibFormDraft,
|
||||
} from '~/modules/commercial/types/supplierForm'
|
||||
import { extractApiErrorMessage } from '~/shared/utils/api'
|
||||
import { readHistoryTab } from '~/shared/utils/historyTab'
|
||||
|
||||
// Masques de saisie (la normalisation finale reste serveur).
|
||||
const SIREN_MASK = '#########'
|
||||
const EMPLOYEES_MASK = '#######'
|
||||
// Volume previsionnel : champ texte borne aux chiffres (entier >= 0 cote back).
|
||||
const VOLUME_FORECAST_MASK = '##########'
|
||||
|
||||
const { t } = useI18n()
|
||||
const api = useApi()
|
||||
const toast = useToast()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const { can, canAny } = usePermissions()
|
||||
|
||||
// Gating de la route : l'edition exige de pouvoir editer au moins un onglet
|
||||
// (`manage` OU `accounting.manage`). Usine et roles en lecture seule sont
|
||||
// rediriges vers le repertoire (lui-meme protege).
|
||||
if (!canEditSupplier(canAny)) {
|
||||
await navigateTo('/suppliers')
|
||||
}
|
||||
|
||||
const supplierId = route.params.id as string
|
||||
|
||||
const { supplier, loading, error, load } = useSupplier(supplierId)
|
||||
const referentials = useSupplierReferentials()
|
||||
|
||||
// ── Permissions / editabilite par zone (option 1 ERP-74) ────────────────────
|
||||
const abilities = computed<SupplierEditAbilities>(() => ({
|
||||
canManage: can('commercial.suppliers.manage'),
|
||||
canAccountingView: can('commercial.suppliers.accounting.view'),
|
||||
canAccountingManage: can('commercial.suppliers.accounting.manage'),
|
||||
}))
|
||||
const editability = computed(() => resolveTabEditability(abilities.value))
|
||||
// Bloc principal + onglets Information / Contacts / Adresses.
|
||||
const businessReadonly = computed(() => !editability.value.businessEditable)
|
||||
const canAccountingView = computed(() => editability.value.accountingVisible)
|
||||
const accountingReadonly = computed(() => !editability.value.accountingEditable)
|
||||
|
||||
const headerTitle = computed(() => supplier.value?.companyName ?? t('commercial.suppliers.edit.title'))
|
||||
|
||||
// ── Brouillons editables (pre-remplis depuis le detail) ─────────────────────
|
||||
const main = reactive<MainFormDraft>(mapMainDraft({} as SupplierDetail))
|
||||
const information = reactive<InformationFormDraft>(mapInformationDraft({} as SupplierDetail))
|
||||
const accounting = reactive<AccountingFormDraft>(mapAccountingFormDraft({} as SupplierDetail))
|
||||
const contacts = ref<SupplierContactFormDraft[]>([])
|
||||
const addresses = ref<SupplierAddressFormDraft[]>([])
|
||||
const ribs = ref<SupplierRibFormDraft[]>([])
|
||||
|
||||
// Ids des sous-ressources existantes supprimees (DELETE differe au « Valider »).
|
||||
const removedContactIds = ref<number[]>([])
|
||||
const removedAddressIds = ref<number[]>([])
|
||||
const removedRibIds = ref<number[]>([])
|
||||
|
||||
const mainSubmitting = ref(false)
|
||||
const tabSubmitting = ref(false)
|
||||
const addressDegradedNotified = ref(false)
|
||||
|
||||
/** Recopie le detail charge dans les brouillons editables. */
|
||||
function hydrate(detail: SupplierDetail): void {
|
||||
Object.assign(main, mapMainDraft(detail))
|
||||
Object.assign(information, mapInformationDraft(detail))
|
||||
Object.assign(accounting, mapAccountingFormDraft(detail))
|
||||
contacts.value = (detail.contacts ?? []).map(mapContactToDraft)
|
||||
addresses.value = (detail.addresses ?? []).map(mapAddressToDraft)
|
||||
ribs.value = (detail.ribs ?? []).map(mapRibToDraft)
|
||||
// Chaque bloc reste visible meme vide : si une collection est vide, on amorce
|
||||
// un bloc vierge (non persiste tant qu'incomplet — cf. submit*/canAdd*).
|
||||
if (contacts.value.length === 0) contacts.value.push(emptyContact())
|
||||
if (addresses.value.length === 0) addresses.value.push(emptyAddress())
|
||||
// RIB : amorce un bloc vide seulement si le type de reglement est une LCR
|
||||
// (sinon la section reste masquee — RG-2.08).
|
||||
if (isRibRequired.value && ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||
}
|
||||
|
||||
// ── Options de selects (referentiels UNION valeurs courantes de l'embed) ─────
|
||||
// L'union garantit que les valeurs deja posees s'affichent meme quand le
|
||||
// referentiel complet n'est pas chargeable (roles metier sans
|
||||
// catalog.categories.view / sites.view → 403, cf. matrice § 2.7).
|
||||
function mergeOptions<T extends { value: string }>(primary: T[], extra: T[]): T[] {
|
||||
const seen = new Set(primary.map(o => o.value))
|
||||
return [...primary, ...extra.filter(o => !seen.has(o.value))]
|
||||
}
|
||||
|
||||
// Categories issues de l'embed (fournisseur + adresses), role-independantes.
|
||||
const embedCategoryOptions = computed<CategoryOption[]>(() => {
|
||||
const fromSupplier = categoryOptionsOf(supplier.value?.categories)
|
||||
const fromAddresses = (supplier.value?.addresses ?? []).flatMap(a => categoryOptionsOf(a.categories))
|
||||
return mergeOptions(fromSupplier, fromAddresses)
|
||||
})
|
||||
// Toutes les categories de type FOURNISSEUR sont autorisees, sur le bloc principal
|
||||
// comme sur une adresse (pas de restriction Distributeur/Courtier comme au M1 — RG-2.10).
|
||||
const mainCategoryOptions = computed(() => mergeOptions(referentials.categories.value, embedCategoryOptions.value))
|
||||
|
||||
const embedSiteOptions = computed<RefOption[]>(() =>
|
||||
mergeOptions([], (supplier.value?.addresses ?? []).flatMap(a => siteOptionsOf(a.sites))),
|
||||
)
|
||||
const siteOptions = computed(() => mergeOptions(referentials.sites.value, embedSiteOptions.value))
|
||||
|
||||
// Contacts deja persistes (iri non null), rattachables a une adresse (M2M).
|
||||
const contactOptions = computed<RefOption[]>(() =>
|
||||
contacts.value
|
||||
.filter(c => c.iri !== null)
|
||||
.map(c => ({
|
||||
value: c.iri as string,
|
||||
label: [c.firstName, c.lastName].filter(Boolean).join(' ') || (c.email ?? ''),
|
||||
})),
|
||||
)
|
||||
|
||||
// Pays : referentiel `country` charge via l'API (ERP-116), aligne sur l'ecran
|
||||
// client. On merge la valeur deja stockee sur chaque adresse (embed) — comme les
|
||||
// autres selects de cet ecran — pour ne pas vider le select si `/countries`
|
||||
// echoue (resilience ERP-102) ou si un pays historique n'est plus au referentiel.
|
||||
const embedCountryOptions = computed<RefOption[]>(() =>
|
||||
mergeOptions([], (supplier.value?.addresses ?? [])
|
||||
.map(a => a.country)
|
||||
.filter((c): c is string => !!c)
|
||||
.map(c => ({ value: c, label: c }))),
|
||||
)
|
||||
const countryOptions = computed<RefOption[]>(() =>
|
||||
mergeOptions(referentials.countries.value, embedCountryOptions.value),
|
||||
)
|
||||
|
||||
// Selects comptables : referentiel UNION valeur courante de l'embed (libelle).
|
||||
const tvaModeOptions = computed(() => mergeOptions(referentials.tvaModes.value, referentialOptionOf(supplier.value?.tvaMode)))
|
||||
const paymentDelayOptions = computed(() => mergeOptions(referentials.paymentDelays.value, referentialOptionOf(supplier.value?.paymentDelay)))
|
||||
const paymentTypeOptions = computed(() => mergeOptions(
|
||||
referentials.paymentTypes.value.map(p => ({ value: p.value, label: p.label })),
|
||||
referentialOptionOf(supplier.value?.paymentType),
|
||||
))
|
||||
const bankOptions = computed(() => mergeOptions(referentials.banks.value, referentialOptionOf(supplier.value?.bank)))
|
||||
|
||||
// ── Onglets : navigation libre (3 actifs + Compta + 4 coquilles) ────────────
|
||||
const tabKeys = computed(() => buildSupplierFormTabKeys(canAccountingView.value, { includeEditOnlyTabs: true }))
|
||||
|
||||
const TAB_ICONS: Record<string, string> = {
|
||||
information: 'mdi:account-outline',
|
||||
contacts: 'mdi:account-box-plus-outline',
|
||||
addresses: 'mdi:map-marker-outline',
|
||||
transport: 'mdi:truck-delivery-outline',
|
||||
accounting: 'mdi:bank-circle-outline',
|
||||
statistics: 'mdi:finance',
|
||||
reports: 'mdi:file-document-edit-outline',
|
||||
exchanges: 'mdi:account-group-outline',
|
||||
}
|
||||
|
||||
const tabs = computed(() => tabKeys.value.map(key => ({
|
||||
key,
|
||||
label: t(`commercial.suppliers.tab.${key}`),
|
||||
icon: TAB_ICONS[key],
|
||||
})))
|
||||
|
||||
// Onglet initial : repris de la consultation (history.state), sinon Information.
|
||||
const activeTab = ref(readHistoryTab(tabKeys.value) ?? 'information')
|
||||
|
||||
// ── Navigation ──────────────────────────────────────────────────────────────
|
||||
/** Retour consultation en conservant l'onglet courant (via history.state). */
|
||||
function goBack(): void {
|
||||
router.push({ path: `/suppliers/${supplierId}`, state: { tab: activeTab.value } })
|
||||
}
|
||||
|
||||
/**
|
||||
* Message d'erreur a afficher : violation 422 / detail renvoye par le serveur,
|
||||
* sinon un libelle generique. Le 409 d'unicite de nom (bloc principal) est
|
||||
* traduit explicitement par l'appelant.
|
||||
*/
|
||||
function apiErrorMessage(e: unknown): string {
|
||||
const data = (e as { data?: unknown })?.data
|
||||
return extractApiErrorMessage(data) || t('commercial.suppliers.toast.error')
|
||||
}
|
||||
|
||||
function showError(e: unknown): void {
|
||||
toast.error({ title: t('commercial.suppliers.toast.error'), message: apiErrorMessage(e) })
|
||||
}
|
||||
|
||||
// ── Erreurs de validation par champ (ERP-101) ───────────────────────────────
|
||||
const {
|
||||
mainErrors,
|
||||
informationErrors,
|
||||
accountingErrors,
|
||||
contactErrors,
|
||||
addressErrors,
|
||||
ribErrors,
|
||||
submitRows,
|
||||
} = useSupplierFormErrors()
|
||||
|
||||
// ── Bloc principal ───────────────────────────────────────────────────────────
|
||||
/** PATCH /suppliers/{id} — groupe supplier:write:main UNIQUEMENT (mode strict). */
|
||||
async function submitMain(): Promise<void> {
|
||||
if (businessReadonly.value || mainSubmitting.value) return
|
||||
mainSubmitting.value = true
|
||||
mainErrors.clearErrors()
|
||||
try {
|
||||
const updated = await api.patch<SupplierDetail>(`/suppliers/${supplierId}`, buildMainPayload(main, { forUpdate: true }), {
|
||||
headers: { Accept: 'application/ld+json' },
|
||||
toast: false,
|
||||
})
|
||||
// Reaffiche les valeurs normalisees renvoyees par le serveur (UPPERCASE, RG-2.12).
|
||||
Object.assign(main, mapMainDraft(updated))
|
||||
toast.success({ title: t('commercial.suppliers.toast.updateSuccess') })
|
||||
}
|
||||
catch (e) {
|
||||
// 409 = doublon nom de societe → erreur inline + toast ; 422 → mapping
|
||||
// inline par champ ; autre → toast de fallback. Cf. ERP-101.
|
||||
const status = (e as { response?: { status?: number } })?.response?.status
|
||||
if (status === 409) {
|
||||
const message = t('commercial.suppliers.form.duplicateCompany')
|
||||
mainErrors.setError('companyName', message)
|
||||
toast.error({ title: t('commercial.suppliers.toast.error'), message })
|
||||
}
|
||||
else {
|
||||
mainErrors.handleApiError(e, { fallbackMessage: t('commercial.suppliers.toast.error') })
|
||||
}
|
||||
}
|
||||
finally {
|
||||
mainSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ── Onglet Information ───────────────────────────────────────────────────────
|
||||
/** PATCH /suppliers/{id} — groupe supplier:write:information UNIQUEMENT. */
|
||||
async function submitInformation(): Promise<void> {
|
||||
if (businessReadonly.value || tabSubmitting.value) return
|
||||
tabSubmitting.value = true
|
||||
informationErrors.clearErrors()
|
||||
try {
|
||||
await api.patch(`/suppliers/${supplierId}`, buildInformationPayload(information), { toast: false })
|
||||
toast.success({ title: t('commercial.suppliers.toast.updateSuccess') })
|
||||
}
|
||||
catch (e) {
|
||||
informationErrors.handleApiError(e, { fallbackMessage: t('commercial.suppliers.toast.error') })
|
||||
}
|
||||
finally {
|
||||
tabSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ── Onglet Contacts ───────────────────────────────────────────────────────────
|
||||
const canAddContact = computed(() => {
|
||||
const last = contacts.value[contacts.value.length - 1]
|
||||
return last === undefined || isContactNamed(last)
|
||||
})
|
||||
function addContact(): void {
|
||||
if (canAddContact.value) contacts.value.push(emptyContact())
|
||||
}
|
||||
|
||||
function askRemoveContact(index: number): void {
|
||||
askConfirm(t('commercial.suppliers.form.confirmDelete.contact'), () => {
|
||||
const removed = contacts.value[index]
|
||||
if (removed?.id != null) removedContactIds.value.push(removed.id)
|
||||
contacts.value.splice(index, 1)
|
||||
contactErrors.value.splice(index, 1)
|
||||
// Garde au moins un bloc visible (cf. amorce a l'hydratation).
|
||||
if (contacts.value.length === 0) contacts.value.push(emptyContact())
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Valide l'onglet Contacts : DELETE des contacts retires (existants), puis
|
||||
* POST/PATCH des blocs restants sur la sous-ressource. Strictement scope a la
|
||||
* collection contacts (endpoints supplier_contact dedies).
|
||||
*/
|
||||
async function submitContacts(): Promise<void> {
|
||||
if (businessReadonly.value || tabSubmitting.value) return
|
||||
tabSubmitting.value = true
|
||||
contactErrors.value = []
|
||||
try {
|
||||
for (const id of removedContactIds.value) {
|
||||
await api.delete(`/supplier_contacts/${id}`, {}, { toast: false })
|
||||
}
|
||||
removedContactIds.value = []
|
||||
|
||||
// RG-2.13 : au moins un contact requis. Si l'onglet ne contient QUE des
|
||||
// amorces neuves vides, on les soumet -> 422 RG-2.04 inline (nom OU prenom).
|
||||
const hasSubmittableContact = contacts.value.some(c => c.id !== null || !isContactBlank(c))
|
||||
const hasError = await submitRows(
|
||||
contacts.value,
|
||||
contactErrors,
|
||||
async (contact) => {
|
||||
const body = buildContactPayload(contact)
|
||||
if (contact.id === null) {
|
||||
const created = await api.post<{ '@id'?: string, id: number }>(
|
||||
`/suppliers/${supplierId}/contacts`,
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
contact.id = created.id
|
||||
contact.iri = created['@id'] ?? null
|
||||
}
|
||||
else {
|
||||
await api.patch(`/supplier_contacts/${contact.id}`, body, { toast: false })
|
||||
}
|
||||
},
|
||||
error => showError(error),
|
||||
contact => hasSubmittableContact && contact.id === null && isContactBlank(contact),
|
||||
)
|
||||
if (hasError) return
|
||||
toast.success({ title: t('commercial.suppliers.toast.updateSuccess') })
|
||||
}
|
||||
catch (e) {
|
||||
showError(e)
|
||||
}
|
||||
finally {
|
||||
tabSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ── Onglet Adresses ───────────────────────────────────────────────────────────
|
||||
// « + Adresse » desactive tant que la derniere adresse n'est pas valide.
|
||||
const canAddAddress = computed(() => {
|
||||
const last = addresses.value[addresses.value.length - 1]
|
||||
return last !== undefined && isAddressValid(last)
|
||||
})
|
||||
|
||||
function addAddress(): void {
|
||||
if (canAddAddress.value) addresses.value.push(emptyAddress())
|
||||
}
|
||||
|
||||
function askRemoveAddress(index: number): void {
|
||||
askConfirm(t('commercial.suppliers.form.confirmDelete.address'), () => {
|
||||
const removed = addresses.value[index]
|
||||
if (removed?.id != null) removedAddressIds.value.push(removed.id)
|
||||
addresses.value.splice(index, 1)
|
||||
addressErrors.value.splice(index, 1)
|
||||
// Garde au moins un bloc visible (cf. amorce a l'hydratation).
|
||||
if (addresses.value.length === 0) addresses.value.push(emptyAddress())
|
||||
})
|
||||
}
|
||||
|
||||
function onAddressDegraded(): void {
|
||||
if (addressDegradedNotified.value) return
|
||||
addressDegradedNotified.value = true
|
||||
toast.warning({
|
||||
title: t('commercial.suppliers.toast.error'),
|
||||
message: t('commercial.suppliers.form.address.degraded'),
|
||||
})
|
||||
}
|
||||
|
||||
/** Valide l'onglet Adresses : DELETE des adresses retirees puis POST/PATCH. */
|
||||
async function submitAddresses(): Promise<void> {
|
||||
if (businessReadonly.value || tabSubmitting.value) return
|
||||
tabSubmitting.value = true
|
||||
addressErrors.value = []
|
||||
try {
|
||||
for (const id of removedAddressIds.value) {
|
||||
await api.delete(`/supplier_addresses/${id}`, {}, { toast: false })
|
||||
}
|
||||
removedAddressIds.value = []
|
||||
|
||||
const hasError = await submitRows(
|
||||
addresses.value,
|
||||
addressErrors,
|
||||
async (address) => {
|
||||
// Edition d'une adresse existante : champ requis vide envoye en `''`
|
||||
// (NotBlank 422) au lieu d'etre omis — sinon le PATCH garderait
|
||||
// l'ancienne valeur (faux 200). Creation (id null) : omit classique.
|
||||
const body = buildAddressPayload(address, { forUpdate: address.id !== null })
|
||||
if (address.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/suppliers/${supplierId}/addresses`,
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
address.id = created.id
|
||||
}
|
||||
else {
|
||||
await api.patch(`/supplier_addresses/${address.id}`, body, { toast: false })
|
||||
}
|
||||
},
|
||||
error => showError(error),
|
||||
)
|
||||
if (hasError) return
|
||||
toast.success({ title: t('commercial.suppliers.toast.updateSuccess') })
|
||||
}
|
||||
catch (e) {
|
||||
showError(e)
|
||||
}
|
||||
finally {
|
||||
tabSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ── Onglet Comptabilite ──────────────────────────────────────────────────────
|
||||
const selectedPaymentTypeCode = computed(() =>
|
||||
referentials.paymentTypes.value.find(p => p.value === accounting.paymentTypeIri)?.code ?? null,
|
||||
)
|
||||
const isBankRequired = computed(() => isBankRequiredForPaymentType(selectedPaymentTypeCode.value))
|
||||
const isRibRequired = computed(() => isRibRequiredForPaymentType(selectedPaymentTypeCode.value))
|
||||
|
||||
// Les blocs RIB ne sont affiches que pour une LCR (RG-2.08).
|
||||
const visibleRibs = computed(() => isRibRequired.value ? ribs.value : [])
|
||||
|
||||
function onPaymentTypeChange(value: string | number | null): void {
|
||||
accounting.paymentTypeIri = value === null ? null : String(value)
|
||||
if (!isBankRequired.value) accounting.bankIri = null
|
||||
// ERP-121 : un RIB est une coordonnee bancaire du fournisseur, decouplee du mode
|
||||
// de reglement. Au passage hors-LCR on ne SUPPRIME plus les RIB existants : ils
|
||||
// restent en base, simplement masques a l'ecran (visibleRibs = []), et
|
||||
// reapparaissent tels quels si l'on repasse en LCR. Seule la corbeille d'un
|
||||
// bloc (askRemoveRib) retire reellement un RIB.
|
||||
if (isRibRequired.value) {
|
||||
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||
}
|
||||
else {
|
||||
// Hors-LCR : on nettoie seulement les erreurs inline (plus affichees).
|
||||
ribErrors.value = []
|
||||
}
|
||||
}
|
||||
|
||||
// « + RIB » desactive tant que le dernier bloc RIB n'est pas complet.
|
||||
const canAddRib = computed(() => {
|
||||
const last = ribs.value[ribs.value.length - 1]
|
||||
return last !== undefined && isRibComplete(last)
|
||||
})
|
||||
|
||||
function addRib(): void {
|
||||
if (canAddRib.value) ribs.value.push(emptyRib())
|
||||
}
|
||||
|
||||
function askRemoveRib(index: number): void {
|
||||
askConfirm(t('commercial.suppliers.form.confirmDelete.rib'), () => {
|
||||
const removed = ribs.value[index]
|
||||
if (removed?.id != null) removedRibIds.value.push(removed.id)
|
||||
ribs.value.splice(index, 1)
|
||||
ribErrors.value.splice(index, 1)
|
||||
// Garde au moins un bloc RIB visible (cf. amorce a l'hydratation).
|
||||
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Valide l'onglet Comptabilite : POST/PATCH des RIB sur la sous-ressource PUIS
|
||||
* PATCH des scalaires (groupe supplier:write:accounting, exige accounting.manage
|
||||
* cote back) PUIS DELETE des RIB explicitement retires. Les RIB crees d'abord : le
|
||||
* back valide RG-2.08 (LCR => au moins un RIB persiste) sur le PATCH scalaires.
|
||||
*
|
||||
* ERP-121 : les RIB ne sont (re)soumis QUE sous LCR — hors-LCR ce sont des
|
||||
* coordonnees dormantes conservees telles quelles, masquees a l'ecran et jamais
|
||||
* re-ecrites. `removedRibIds` ne contient plus que les suppressions EXPLICITES
|
||||
* (corbeille d'un bloc, toujours sous LCR). Aucun champ main/information dans le
|
||||
* payload (mode strict RG-2.16 : sinon 403 sur tout le payload).
|
||||
*/
|
||||
async function submitAccounting(): Promise<void> {
|
||||
if (accountingReadonly.value || tabSubmitting.value) return
|
||||
tabSubmitting.value = true
|
||||
accountingErrors.clearErrors()
|
||||
try {
|
||||
// 1) POST/PATCH des RIB d'abord — UNIQUEMENT sous LCR (erreurs inline par
|
||||
// ligne, tous les blocs tentes). Hors-LCR (ERP-121), les RIB sont des
|
||||
// coordonnees dormantes : rien d'editable n'est affiche, on ne les re-soumet
|
||||
// pas. On ne saute une amorce neuve vide QUE s'il reste un autre RIB
|
||||
// soumettable : sinon (ex. l'unique RIB existant supprime, remplace par un
|
||||
// bloc vide), on la soumet pour declencher la 422 NotBlank inline plutot que
|
||||
// de laisser le DELETE echouer en « dernier RIB d'une LCR » (message plat).
|
||||
if (isRibRequired.value) {
|
||||
const hasSubmittableRib = ribs.value.some(r => r.id !== null || !isRibBlank(r))
|
||||
const ribHasError = await submitRows(
|
||||
ribs.value,
|
||||
ribErrors,
|
||||
async (rib) => {
|
||||
// Edition d'un RIB existant : champ requis vide envoye en `''` (NotBlank
|
||||
// 422) au lieu d'etre omis (sinon le PATCH garderait l'ancienne valeur).
|
||||
const body = buildRibPayload(rib, { forUpdate: rib.id !== null })
|
||||
if (rib.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/suppliers/${supplierId}/ribs`,
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
rib.id = created.id
|
||||
}
|
||||
else {
|
||||
await api.patch(`/supplier_ribs/${rib.id}`, body, { toast: false })
|
||||
}
|
||||
},
|
||||
error => showError(error),
|
||||
rib => hasSubmittableRib && rib.id === null && isRibBlank(rib),
|
||||
)
|
||||
if (ribHasError) return
|
||||
}
|
||||
|
||||
// 2) PATCH des scalaires comptables (erreurs inline sur leurs champs).
|
||||
try {
|
||||
await api.patch(`/suppliers/${supplierId}`, buildAccountingPayload(accounting, isBankRequired.value), { toast: false })
|
||||
}
|
||||
catch (error) {
|
||||
accountingErrors.handleApiError(error, { fallbackMessage: t('commercial.suppliers.toast.error') })
|
||||
return
|
||||
}
|
||||
|
||||
// 3) DELETE des RIB explicitement retires (corbeille d'un bloc) : APRES le
|
||||
// PATCH scalaires (le guard back refuse la suppression du dernier RIB d'une
|
||||
// LCR). ERP-121 : plus aucune suppression automatique au passage hors-LCR.
|
||||
for (const id of removedRibIds.value) {
|
||||
await api.delete(`/supplier_ribs/${id}`, {}, { toast: false })
|
||||
}
|
||||
removedRibIds.value = []
|
||||
|
||||
toast.success({ title: t('commercial.suppliers.toast.updateSuccess') })
|
||||
}
|
||||
catch (e) {
|
||||
showError(e)
|
||||
}
|
||||
finally {
|
||||
tabSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ── Modal de confirmation generique ──────────────────────────────────────────
|
||||
const confirmModal = reactive({
|
||||
open: false,
|
||||
message: '',
|
||||
action: null as null | (() => void),
|
||||
})
|
||||
|
||||
function askConfirm(message: string, action: () => void): void {
|
||||
confirmModal.message = message
|
||||
confirmModal.action = action
|
||||
confirmModal.open = true
|
||||
}
|
||||
|
||||
function runConfirm(): void {
|
||||
confirmModal.action?.()
|
||||
confirmModal.action = null
|
||||
confirmModal.open = false
|
||||
}
|
||||
|
||||
useHead({ title: headerTitle })
|
||||
|
||||
onMounted(async () => {
|
||||
// Referentiels en best-effort (echec non bloquant : l'embed alimente les
|
||||
// libelles des valeurs courantes).
|
||||
referentials.loadCommon().catch(() => {})
|
||||
await load()
|
||||
if (supplier.value) hydrate(supplier.value)
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,468 @@
|
||||
<template>
|
||||
<div>
|
||||
<!-- En-tete : retour repertoire + nom du fournisseur + actions (Modifier / Archiver|Restaurer). -->
|
||||
<div class="flex items-center gap-3 pt-11">
|
||||
<MalioButtonIcon
|
||||
icon="mdi:arrow-left-bold"
|
||||
icon-size="24"
|
||||
variant="ghost"
|
||||
v-bind="{ ariaLabel: t('commercial.suppliers.consultation.back') }"
|
||||
@click="goBack"
|
||||
/>
|
||||
<h1 class="text-[30px] font-semibold text-m-primary">{{ headerTitle }}</h1>
|
||||
|
||||
<!-- gap-12 = 48px : meme espacement que Ajouter / Filtres du repertoire. -->
|
||||
<div class="ml-auto flex items-center gap-12">
|
||||
<MalioButton
|
||||
v-if="canEdit"
|
||||
variant="secondary"
|
||||
icon-name="mdi:pencil-outline"
|
||||
icon-position="left"
|
||||
:label="t('commercial.suppliers.action.edit')"
|
||||
@click="goEdit"
|
||||
/>
|
||||
<MalioButton
|
||||
v-if="showArchive"
|
||||
variant="secondary"
|
||||
icon-name="mdi:archive-arrow-down-outline"
|
||||
icon-position="left"
|
||||
:label="t('commercial.suppliers.action.archive')"
|
||||
@click="askToggleArchive"
|
||||
/>
|
||||
<MalioButton
|
||||
v-if="showRestore"
|
||||
variant="secondary"
|
||||
icon-name="mdi:archive-arrow-up-outline"
|
||||
icon-position="left"
|
||||
:label="t('commercial.suppliers.action.restore')"
|
||||
@click="askToggleArchive"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Etats de chargement / introuvable. -->
|
||||
<p v-if="loading" class="mt-12 text-center text-black/60">{{ t('commercial.suppliers.consultation.loading') }}</p>
|
||||
<p v-else-if="error" class="mt-12 text-center text-m-danger">{{ t('commercial.suppliers.consultation.notFound') }}</p>
|
||||
|
||||
<template v-else-if="supplier">
|
||||
<!-- ── Formulaire principal (lecture seule) ──────────────────────── -->
|
||||
<div class="mt-[48px] grid grid-cols-3 xl:grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText
|
||||
:model-value="supplier.companyName"
|
||||
:label="t('commercial.suppliers.form.main.companyName')"
|
||||
readonly
|
||||
/>
|
||||
<MalioSelectCheckbox
|
||||
:model-value="categoryIris"
|
||||
:options="mainCategoryOptions"
|
||||
:label="t('commercial.suppliers.form.main.categories')"
|
||||
:display-tag="true"
|
||||
readonly
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- ── Onglets (navigation libre, tout en lecture seule) ─────────── -->
|
||||
<MalioTabList v-model="activeTab" :tabs="tabs" :max-visible-tabs="5" :max-width="1100" class="mt-[60px]">
|
||||
<!-- Onglet Information -->
|
||||
<template #information>
|
||||
<div class="mt-12 grid grid-cols-4 gap-x-[44px] gap-y-4 bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
|
||||
<!-- pt-1/pb-1 alignent le textarea (h-full) en haut ET en bas
|
||||
sur les inputs (champ 40px centre dans un h-12). -->
|
||||
<MalioInputTextArea
|
||||
:model-value="information.description"
|
||||
:label="t('commercial.suppliers.form.information.description')"
|
||||
resize="none"
|
||||
group-class="row-span-2 pt-1 pb-1"
|
||||
text-input="h-full text-lg"
|
||||
readonly
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="information.competitors"
|
||||
:label="t('commercial.suppliers.form.information.competitors')"
|
||||
readonly
|
||||
/>
|
||||
<MalioDate
|
||||
:model-value="information.foundedAt"
|
||||
:label="t('commercial.suppliers.form.information.foundedAt')"
|
||||
readonly
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="information.employeesCount"
|
||||
:label="t('commercial.suppliers.form.information.employeesCount')"
|
||||
readonly
|
||||
/>
|
||||
<MalioInputAmount
|
||||
:model-value="information.revenueAmount"
|
||||
:label="t('commercial.suppliers.form.information.revenueAmount')"
|
||||
readonly
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="information.directorName"
|
||||
:label="t('commercial.suppliers.form.information.directorName')"
|
||||
readonly
|
||||
/>
|
||||
<MalioInputAmount
|
||||
:model-value="information.profitAmount"
|
||||
:label="t('commercial.suppliers.form.information.profitAmount')"
|
||||
readonly
|
||||
/>
|
||||
<!-- Volume previsionnel : specifique fournisseur (entier). -->
|
||||
<MalioInputText
|
||||
:model-value="information.volumeForecast"
|
||||
:label="t('commercial.suppliers.form.information.volumeForecast')"
|
||||
readonly
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Onglet Contacts -->
|
||||
<template #contacts>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
<SupplierContactBlock
|
||||
v-for="(contact, index) in contacts"
|
||||
:key="contact.id ?? index"
|
||||
:model-value="contact"
|
||||
:title="t('commercial.suppliers.form.contact.title', { n: index + 1 })"
|
||||
readonly
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Onglet Adresses -->
|
||||
<template #addresses>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
<SupplierAddressBlock
|
||||
v-for="(view, index) in addressViews"
|
||||
:key="view.draft.id ?? index"
|
||||
:model-value="view.draft"
|
||||
:title="t('commercial.suppliers.form.address.title', { n: index + 1 })"
|
||||
:category-options="view.categoryOptions"
|
||||
:site-options="allSiteOptions"
|
||||
:contact-options="contactOptions"
|
||||
:country-options="countryOptions"
|
||||
readonly
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Onglet Comptabilite (present uniquement si accounting.view). -->
|
||||
<template v-if="canAccountingView" #accounting>
|
||||
<div class="mt-12 flex flex-col gap-6">
|
||||
<div class="bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]">
|
||||
<div class="grid grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText
|
||||
:model-value="accounting.siren"
|
||||
:label="t('commercial.suppliers.form.accounting.siren')"
|
||||
:mask="SIREN_MASK"
|
||||
readonly
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="accounting.accountNumber"
|
||||
:label="t('commercial.suppliers.form.accounting.accountNumber')"
|
||||
readonly
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.tvaModeIri"
|
||||
:options="tvaModeOptions"
|
||||
:label="t('commercial.suppliers.form.accounting.tvaMode')"
|
||||
empty-option-label=""
|
||||
readonly
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="accounting.nTva"
|
||||
:label="t('commercial.suppliers.form.accounting.nTva')"
|
||||
readonly
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.paymentDelayIri"
|
||||
:options="paymentDelayOptions"
|
||||
:label="t('commercial.suppliers.form.accounting.paymentDelay')"
|
||||
empty-option-label=""
|
||||
readonly
|
||||
/>
|
||||
<MalioSelect
|
||||
:model-value="accounting.paymentTypeIri"
|
||||
:options="paymentTypeOptions"
|
||||
:label="t('commercial.suppliers.form.accounting.paymentType')"
|
||||
empty-option-label=""
|
||||
readonly
|
||||
/>
|
||||
<MalioSelect
|
||||
v-if="accounting.bankIri"
|
||||
:model-value="accounting.bankIri"
|
||||
:options="bankOptions"
|
||||
:label="t('commercial.suppliers.form.accounting.bank')"
|
||||
empty-option-label=""
|
||||
readonly
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Blocs RIB (0..n), lecture seule. -->
|
||||
<div
|
||||
v-for="(rib, index) in ribs"
|
||||
:key="rib.id ?? index"
|
||||
class="bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]"
|
||||
>
|
||||
<div class="grid grid-cols-4 gap-x-[44px] gap-y-4">
|
||||
<MalioInputText
|
||||
:model-value="rib.label"
|
||||
:label="t('commercial.suppliers.form.accounting.ribLabel')"
|
||||
readonly
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="rib.bic"
|
||||
:label="t('commercial.suppliers.form.accounting.ribBic')"
|
||||
readonly
|
||||
/>
|
||||
<MalioInputText
|
||||
:model-value="rib.iban"
|
||||
:label="t('commercial.suppliers.form.accounting.ribIban')"
|
||||
readonly
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Onglets non encore implementes : frame vide (navigation libre). -->
|
||||
<template #transport><ComingSoonPlaceholder /></template>
|
||||
<template #statistics><ComingSoonPlaceholder /></template>
|
||||
<template #reports><ComingSoonPlaceholder /></template>
|
||||
<template #exchanges><ComingSoonPlaceholder /></template>
|
||||
</MalioTabList>
|
||||
</template>
|
||||
|
||||
<!-- Modal de confirmation Archiver / Restaurer. -->
|
||||
<MalioModal v-model="confirmOpen" modal-class="max-w-md">
|
||||
<template #header>
|
||||
<h2 class="text-[24px] font-bold">
|
||||
{{ isArchived ? t('commercial.suppliers.consultation.confirmRestore.title') : t('commercial.suppliers.consultation.confirmArchive.title') }}
|
||||
</h2>
|
||||
</template>
|
||||
<p>{{ isArchived ? t('commercial.suppliers.consultation.confirmRestore.message') : t('commercial.suppliers.consultation.confirmArchive.message') }}</p>
|
||||
<template #footer>
|
||||
<MalioButton
|
||||
variant="secondary"
|
||||
button-class="flex-1"
|
||||
:label="t('commercial.suppliers.form.confirmDelete.cancel')"
|
||||
@click="confirmOpen = false"
|
||||
/>
|
||||
<MalioButton
|
||||
:variant="isArchived ? 'primary' : 'danger'"
|
||||
button-class="flex-1"
|
||||
:label="t('commercial.suppliers.form.confirmDelete.confirm')"
|
||||
:disabled="toggling"
|
||||
@click="confirmToggleArchive"
|
||||
/>
|
||||
</template>
|
||||
</MalioModal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useSupplier } from '~/modules/commercial/composables/useSupplier'
|
||||
import { buildSupplierFormTabKeys, isRibRequiredForPaymentType } from '~/modules/commercial/utils/forms/supplierFormRules'
|
||||
import { readHistoryTab } from '~/shared/utils/historyTab'
|
||||
import {
|
||||
canEditSupplier,
|
||||
categoryOptionsOf,
|
||||
contactOptionsOf,
|
||||
emptyAddress,
|
||||
mapAccountingDraft,
|
||||
mapAddressView,
|
||||
mapContactToDraft,
|
||||
mapRibToDraft,
|
||||
paymentTypeCodeOf,
|
||||
referentialOptionOf,
|
||||
showArchiveAction,
|
||||
showRestoreAction,
|
||||
type SelectOption,
|
||||
type SupplierDetail,
|
||||
} from '~/modules/commercial/utils/forms/supplierConsultation'
|
||||
import { emptyContact } from '~/modules/commercial/types/supplierForm'
|
||||
|
||||
// Masque d'affichage (purement visuel, la donnee reste celle du serveur).
|
||||
const SIREN_MASK = '#########'
|
||||
|
||||
const { t } = useI18n()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const toast = useToast()
|
||||
const { can, canAny } = usePermissions()
|
||||
const authStore = useAuthStore()
|
||||
|
||||
// Gating de la route : la consultation exige `view`. Usine (sans view) est
|
||||
// redirige vers le repertoire (lui-meme protege). Cf. matrice § 2.7.
|
||||
if (!can('commercial.suppliers.view')) {
|
||||
await navigateTo('/suppliers')
|
||||
}
|
||||
|
||||
const supplierId = route.params.id as string
|
||||
|
||||
const { supplier, loading, error, load, archive, restore } = useSupplier(supplierId)
|
||||
|
||||
// ── Permissions / visibilite des actions ───────────────────────────────────
|
||||
const canAccountingView = computed(() => can('commercial.suppliers.accounting.view'))
|
||||
const canEdit = computed(() => canEditSupplier(canAny))
|
||||
const isArchived = computed(() => supplier.value?.isArchived === true)
|
||||
const showArchive = computed(() => showArchiveAction(can, isArchived.value))
|
||||
const showRestore = computed(() => showRestoreAction(can, isArchived.value))
|
||||
|
||||
const headerTitle = computed(() => supplier.value?.companyName ?? t('commercial.suppliers.consultation.title'))
|
||||
|
||||
// ── Donnees derivees du payload (lecture seule) ────────────────────────────
|
||||
const categoryIris = computed(() => (supplier.value?.categories ?? []).map(c => c['@id']))
|
||||
|
||||
const information = computed(() => ({
|
||||
description: supplier.value?.description ?? null,
|
||||
competitors: supplier.value?.competitors ?? null,
|
||||
// MalioDate attend strictement YYYY-MM-DD : on tronque l'ISO datetime renvoye.
|
||||
foundedAt: supplier.value?.foundedAt ? supplier.value.foundedAt.slice(0, 10) : null,
|
||||
employeesCount: supplier.value?.employeesCount != null ? String(supplier.value.employeesCount) : null,
|
||||
revenueAmount: supplier.value?.revenueAmount ?? null,
|
||||
profitAmount: supplier.value?.profitAmount ?? null,
|
||||
directorName: supplier.value?.directorName ?? null,
|
||||
volumeForecast: supplier.value?.volumeForecast != null ? String(supplier.value.volumeForecast) : null,
|
||||
}))
|
||||
|
||||
// Chaque bloc reste visible meme vide en consultation : si la collection est
|
||||
// vide, on affiche un bloc vierge en lecture seule (pas de message « Aucun … »).
|
||||
const contacts = computed(() => {
|
||||
const list = (supplier.value?.contacts ?? []).map(mapContactToDraft)
|
||||
return list.length ? list : [emptyContact()]
|
||||
})
|
||||
// Vue par adresse : brouillon + options (sites/categories) propres a l'adresse.
|
||||
const addressViews = computed(() => {
|
||||
const views = (supplier.value?.addresses ?? []).map(mapAddressView)
|
||||
return views.length ? views : [{ draft: emptyAddress(), siteOptions: [], categoryOptions: [] }]
|
||||
})
|
||||
// Exception au placeholder ci-dessus : on n'affiche AUCUN bloc RIB quand le
|
||||
// fournisseur n'en a pas. ERP-121 : un fournisseur peut desormais conserver des RIB
|
||||
// « dormants » apres etre repasse hors-LCR (on ne les supprime plus). En consultation,
|
||||
// decision metier = on les masque TOTALEMENT : on n'affiche les RIB que si le type de
|
||||
// reglement courant est LCR (le `code` est embarque sous supplier:read:accounting).
|
||||
const ribs = computed(() =>
|
||||
isRibRequiredForPaymentType(paymentTypeCodeOf(supplier.value?.paymentType))
|
||||
? (supplier.value?.ribs ?? []).map(mapRibToDraft)
|
||||
: [],
|
||||
)
|
||||
// Draft comptable (tout null si l'utilisateur n'a pas accounting.view).
|
||||
const accounting = computed(() => mapAccountingDraft(supplier.value ?? ({} as SupplierDetail)))
|
||||
|
||||
// ── Options des selects (construites depuis l'EMBED, jamais via un GET de
|
||||
// referentiel : /categories et /sites sont en 403 pour les roles metier
|
||||
// non-admin, ce qui laisserait les libelles vides). ───────────────────────
|
||||
const mainCategoryOptions = computed(() => categoryOptionsOf(supplier.value?.categories))
|
||||
const contactOptions = computed(() => contactOptionsOf(supplier.value?.contacts))
|
||||
|
||||
// Liste COMPLETE des sites disponibles, issue de /api/me (groupe me:read — donc
|
||||
// pas de 403 pour les roles metier, contrairement a GET /sites). Libelle = numero
|
||||
// de departement (2 premiers chiffres du code postal). Permet d'afficher TOUJOURS
|
||||
// toutes les cases « Sites » (86 / 17 / 82) dans le bloc adresse, meme celles non
|
||||
// rattachees a l'adresse consultee (les rattachees restent cochees via siteIris).
|
||||
const allSiteOptions = computed<SelectOption[]>(() =>
|
||||
(authStore.user?.sites ?? []).map(s => ({
|
||||
value: `/api/sites/${s.id}`,
|
||||
label: (s.postalCode ?? '').slice(0, 2),
|
||||
})),
|
||||
)
|
||||
|
||||
// Pays (consultation, lecture seule) : derive des adresses du fournisseur, comme
|
||||
// l'ecran client. Le referentiel `country` (ERP-116) n'est pas charge ici, l'ecran
|
||||
// n'affiche que les valeurs deja stockees.
|
||||
const countryOptions = computed<SelectOption[]>(() =>
|
||||
[...new Set(
|
||||
(supplier.value?.addresses ?? [])
|
||||
.map(a => a.country)
|
||||
.filter((c): c is string => !!c),
|
||||
)].map(c => ({ value: c, label: c })),
|
||||
)
|
||||
|
||||
// Selects comptables : libelle issu de l'embed (option unique ou vide).
|
||||
const tvaModeOptions = computed(() => referentialOptionOf(supplier.value?.tvaMode))
|
||||
const paymentDelayOptions = computed(() => referentialOptionOf(supplier.value?.paymentDelay))
|
||||
const paymentTypeOptions = computed(() => referentialOptionOf(supplier.value?.paymentType))
|
||||
const bankOptions = computed(() => referentialOptionOf(supplier.value?.bank))
|
||||
|
||||
// ── Onglets : navigation LIBRE (pas de sequence forcee en consultation) ────
|
||||
// 3 onglets actifs (Information, Contacts, Adresses, + Comptabilite si droit) et
|
||||
// 4 coquilles (Transport, Statistiques, Rapports, Echanges).
|
||||
const tabKeys = computed(() => buildSupplierFormTabKeys(canAccountingView.value, { includeEditOnlyTabs: true }))
|
||||
|
||||
const TAB_ICONS: Record<string, string> = {
|
||||
information: 'mdi:account-outline',
|
||||
contacts: 'mdi:account-box-plus-outline',
|
||||
addresses: 'mdi:map-marker-outline',
|
||||
transport: 'mdi:truck-delivery-outline',
|
||||
accounting: 'mdi:bank-circle-outline',
|
||||
statistics: 'mdi:finance',
|
||||
reports: 'mdi:file-document-edit-outline',
|
||||
exchanges: 'mdi:account-group-outline',
|
||||
}
|
||||
|
||||
const tabs = computed(() => tabKeys.value.map(key => ({
|
||||
key,
|
||||
label: t(`commercial.suppliers.tab.${key}`),
|
||||
icon: TAB_ICONS[key],
|
||||
})))
|
||||
|
||||
// Onglet initial : repris de l'edition au retour (history.state), sinon Information.
|
||||
const activeTab = ref(readHistoryTab(tabKeys.value) ?? 'information')
|
||||
|
||||
// ── Navigation ─────────────────────────────────────────────────────────────
|
||||
function goBack(): void {
|
||||
router.push('/suppliers')
|
||||
}
|
||||
|
||||
/** Bascule en edition en conservant l'onglet courant (via history.state). */
|
||||
function goEdit(): void {
|
||||
router.push({ path: `/suppliers/${supplierId}/edit`, state: { tab: activeTab.value } })
|
||||
}
|
||||
|
||||
// ── Archivage / Restauration ────────────────────────────────────────────────
|
||||
const confirmOpen = ref(false)
|
||||
const toggling = ref(false)
|
||||
|
||||
function askToggleArchive(): void {
|
||||
confirmOpen.value = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirme l'archivage ou la restauration (PATCH isArchived seul). Gere le 409
|
||||
* de conflit d'homonyme actif a la restauration avec un message dedie.
|
||||
*/
|
||||
async function confirmToggleArchive(): Promise<void> {
|
||||
if (toggling.value) return
|
||||
toggling.value = true
|
||||
const restoring = isArchived.value
|
||||
try {
|
||||
if (restoring) {
|
||||
await restore()
|
||||
toast.success({ title: t('commercial.suppliers.toast.restoreSuccess') })
|
||||
}
|
||||
else {
|
||||
await archive()
|
||||
toast.success({ title: t('commercial.suppliers.toast.archiveSuccess') })
|
||||
}
|
||||
confirmOpen.value = false
|
||||
}
|
||||
catch (e) {
|
||||
const status = (e as { response?: { status?: number } })?.response?.status
|
||||
toast.error({
|
||||
title: t('commercial.suppliers.toast.error'),
|
||||
message: restoring && status === 409
|
||||
? t('commercial.suppliers.toast.restoreConflict')
|
||||
: t('commercial.suppliers.toast.error'),
|
||||
})
|
||||
}
|
||||
finally {
|
||||
toggling.value = false
|
||||
}
|
||||
}
|
||||
|
||||
useHead({ title: headerTitle })
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
@@ -71,6 +71,7 @@
|
||||
:readonly="isValidated('information')"
|
||||
:editable="true"
|
||||
:error="informationErrors.errors.foundedAt"
|
||||
@update:raw-value="(v: string) => information.foundedAtRaw = v"
|
||||
/>
|
||||
<MalioInputText
|
||||
v-model="information.employeesCount"
|
||||
@@ -266,7 +267,7 @@
|
||||
class="relative bg-white py-4 pl-[28px] pr-[60px] shadow-[0_4px_4px_0_rgba(0,0,0,0.25)]"
|
||||
>
|
||||
<MalioButtonIcon
|
||||
v-if="!accountingReadonly"
|
||||
v-if="!accountingReadonly && visibleRibs.length > 1"
|
||||
icon="mdi:delete-outline"
|
||||
variant="ghost"
|
||||
button-class="absolute top-3 right-3"
|
||||
@@ -361,7 +362,7 @@ import {
|
||||
isRibComplete,
|
||||
isRibRequiredForPaymentType,
|
||||
lastFillableTabKey,
|
||||
} from '~/modules/commercial/utils/supplierFormRules'
|
||||
} from '~/modules/commercial/utils/forms/supplierFormRules'
|
||||
import {
|
||||
buildAccountingPayload,
|
||||
buildAddressPayload,
|
||||
@@ -369,7 +370,7 @@ import {
|
||||
buildInformationPayload,
|
||||
buildMainPayload,
|
||||
buildRibPayload,
|
||||
} from '~/modules/commercial/utils/supplierEdit'
|
||||
} from '~/modules/commercial/utils/forms/supplierEdit'
|
||||
import {
|
||||
emptyAddress,
|
||||
emptyContact,
|
||||
@@ -549,6 +550,8 @@ const information = reactive({
|
||||
description: null as string | null,
|
||||
competitors: null as string | null,
|
||||
foundedAt: null as string | null,
|
||||
// Saisie brute invalide remontee par MalioDate (cf. foundedAtRaw, MUI-44).
|
||||
foundedAtRaw: '',
|
||||
employeesCount: null as string | null,
|
||||
revenueAmount: null as string | null,
|
||||
profitAmount: null as string | null,
|
||||
@@ -646,11 +649,15 @@ const contactOptions = computed<RefOption[]>(() =>
|
||||
})),
|
||||
)
|
||||
|
||||
// Pays disponibles (France preselectionnee par defaut sur chaque adresse).
|
||||
const countryOptions: RefOption[] = [
|
||||
{ value: 'France', label: 'France' },
|
||||
{ value: 'Espagne', label: 'Espagne' },
|
||||
]
|
||||
// Pays : referentiel `country` charge via l'API (ERP-116), aligne sur l'ecran
|
||||
// client. France garantie en tete pour rester preselectionnable par defaut sur
|
||||
// chaque adresse meme si `/countries` echoue (resilience ERP-102).
|
||||
const countryOptions = computed<RefOption[]>(() => {
|
||||
const list = referentials.countries.value
|
||||
return list.some(c => c.value === 'France')
|
||||
? list
|
||||
: [{ value: 'France', label: 'France' }, ...list]
|
||||
})
|
||||
|
||||
// « + Adresse » desactive tant que la derniere adresse n'est pas valide.
|
||||
const canAddAddress = computed(() => {
|
||||
@@ -741,13 +748,14 @@ function onPaymentTypeChange(value: string | number | null): void {
|
||||
accounting.paymentTypeIri = value === null ? null : String(value)
|
||||
// La banque n'a de sens que pour un virement : on la vide sinon (RG-2.07).
|
||||
if (!isBankRequired.value) accounting.bankIri = null
|
||||
// Les RIB n'ont de sens que pour une LCR (RG-2.08) : amorce un bloc vide quand
|
||||
// LCR est choisi, vide la liste sinon (pas de RIB fantome soumis).
|
||||
// ERP-121 : on ne jette plus la saisie RIB au passage hors-LCR. Les blocs sont
|
||||
// masques (visibleRibs = []) mais conserves, et reapparaissent si l'on repasse
|
||||
// en LCR. Ils ne sont persistes qu'a la validation SOUS LCR (cf. submitAccounting),
|
||||
// donc une saisie abandonnee hors-LCR ne cree aucun RIB orphelin.
|
||||
if (isRibRequired.value) {
|
||||
if (ribs.value.length === 0) ribs.value.push(emptyRib())
|
||||
}
|
||||
else {
|
||||
ribs.value = []
|
||||
ribErrors.value = []
|
||||
}
|
||||
}
|
||||
@@ -782,29 +790,36 @@ async function submitAccounting(): Promise<void> {
|
||||
tabSubmitting.value = true
|
||||
accountingErrors.clearErrors()
|
||||
try {
|
||||
// 1) POST/PATCH des RIB d'abord (erreurs inline par ligne). Seuls les blocs
|
||||
// RIB TOTALEMENT vides (amorce neuve) sont ignores.
|
||||
const ribHasError = await submitRows(
|
||||
ribs.value,
|
||||
ribErrors,
|
||||
async (rib) => {
|
||||
const body = buildRibPayload(rib)
|
||||
if (rib.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/suppliers/${supplierId.value}/ribs`,
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
rib.id = created.id
|
||||
}
|
||||
else {
|
||||
await api.patch(`/supplier_ribs/${rib.id}`, body, { toast: false })
|
||||
}
|
||||
},
|
||||
error => toast.error({ title: t('commercial.suppliers.toast.error'), message: apiErrorMessage(error) }),
|
||||
rib => rib.id === null && isRibBlank(rib),
|
||||
)
|
||||
if (ribHasError) return
|
||||
// 1) POST/PATCH des RIB d'abord — UNIQUEMENT sous LCR (erreurs inline par
|
||||
// ligne). Hors-LCR (ERP-121), une saisie RIB eventuellement restee dans le
|
||||
// brouillon est masquee et n'est PAS persistee (pas de RIB orphelin sur un
|
||||
// fournisseur en virement). On ne saute une amorce neuve vide QUE s'il reste
|
||||
// un autre RIB soumettable : sinon (LCR sans aucun RIB rempli) on la soumet
|
||||
// pour declencher la 422 NotBlank inline.
|
||||
if (isRibRequired.value) {
|
||||
const hasSubmittableRib = ribs.value.some(r => r.id !== null || !isRibBlank(r))
|
||||
const ribHasError = await submitRows(
|
||||
ribs.value,
|
||||
ribErrors,
|
||||
async (rib) => {
|
||||
const body = buildRibPayload(rib)
|
||||
if (rib.id === null) {
|
||||
const created = await api.post<{ id: number }>(
|
||||
`/suppliers/${supplierId.value}/ribs`,
|
||||
body,
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
rib.id = created.id
|
||||
}
|
||||
else {
|
||||
await api.patch(`/supplier_ribs/${rib.id}`, body, { toast: false })
|
||||
}
|
||||
},
|
||||
error => toast.error({ title: t('commercial.suppliers.toast.error'), message: apiErrorMessage(error) }),
|
||||
rib => hasSubmittableRib && rib.id === null && isRibBlank(rib),
|
||||
)
|
||||
if (ribHasError) return
|
||||
}
|
||||
|
||||
// 2) PATCH des scalaires comptables (erreurs inline sur leurs champs).
|
||||
try {
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
buildAccountingPayload,
|
||||
buildAddressPayload,
|
||||
buildContactPayload,
|
||||
buildInformationPayload,
|
||||
buildMainPayload,
|
||||
buildRibPayload,
|
||||
} from '../supplierEdit'
|
||||
import { emptyAddress, emptyContact, emptyRib } from '~/modules/commercial/types/supplierForm'
|
||||
|
||||
describe('buildMainPayload (groupe supplier:write:main)', () => {
|
||||
it('envoie companyName + categories quand renseignes', () => {
|
||||
expect(buildMainPayload({ companyName: 'ACME', categoryIris: ['/api/categories/1'] })).toEqual({
|
||||
companyName: 'ACME',
|
||||
categories: ['/api/categories/1'],
|
||||
})
|
||||
})
|
||||
|
||||
it('omet companyName vide (-> 422 NotBlank, ERP-119)', () => {
|
||||
const payload = buildMainPayload({ companyName: null, categoryIris: [] })
|
||||
expect('companyName' in payload).toBe(false)
|
||||
expect(payload.categories).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildInformationPayload (groupe supplier:write:information)', () => {
|
||||
const base = {
|
||||
description: null, competitors: null, foundedAt: null, employeesCount: null,
|
||||
revenueAmount: null, profitAmount: null, directorName: null, volumeForecast: null,
|
||||
}
|
||||
|
||||
it('convertit employeesCount et volumeForecast en nombre, null si vide', () => {
|
||||
expect(buildInformationPayload({ ...base, employeesCount: '42', volumeForecast: '1000' })).toMatchObject({
|
||||
employeesCount: 42,
|
||||
volumeForecast: 1000,
|
||||
})
|
||||
expect(buildInformationPayload(base)).toMatchObject({ employeesCount: null, volumeForecast: null })
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildContactPayload (sous-ressource supplier_contact)', () => {
|
||||
it('n\'envoie le 2e telephone que si revele (hasSecondaryPhone)', () => {
|
||||
const contact = { ...emptyContact(), phonePrimary: '0102030405', phoneSecondary: '0607080910' }
|
||||
expect(buildContactPayload({ ...contact, hasSecondaryPhone: false }).phoneSecondary).toBeNull()
|
||||
expect(buildContactPayload({ ...contact, hasSecondaryPhone: true }).phoneSecondary).toBe('0607080910')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildAddressPayload (sous-ressource supplier_address — specificites M2)', () => {
|
||||
it('envoie addressType (enum), bennes (nombre) et triageProvider', () => {
|
||||
const address = {
|
||||
...emptyAddress(),
|
||||
addressType: 'RENDU' as const,
|
||||
postalCode: '86100', city: 'Châtellerault', street: '1 rue de la Paix',
|
||||
siteIris: ['/api/sites/1'], categoryIris: ['/api/categories/2'],
|
||||
bennes: '3', triageProvider: true,
|
||||
}
|
||||
expect(buildAddressPayload(address)).toMatchObject({
|
||||
addressType: 'RENDU',
|
||||
bennes: 3,
|
||||
triageProvider: true,
|
||||
sites: ['/api/sites/1'],
|
||||
categories: ['/api/categories/2'],
|
||||
})
|
||||
})
|
||||
|
||||
it('bennes null quand le champ est vide', () => {
|
||||
expect(buildAddressPayload({ ...emptyAddress(), bennes: '' }).bennes).toBeNull()
|
||||
})
|
||||
|
||||
it('omet postalCode / city / street vides (-> 422 NotBlank, ERP-119)', () => {
|
||||
const payload = buildAddressPayload({ ...emptyAddress(), addressType: 'PROSPECT' })
|
||||
expect('postalCode' in payload).toBe(false)
|
||||
expect('city' in payload).toBe(false)
|
||||
expect('street' in payload).toBe(false)
|
||||
// Les champs non requis restent presents.
|
||||
expect('streetComplement' in payload).toBe(true)
|
||||
expect(payload.addressType).toBe('PROSPECT')
|
||||
})
|
||||
|
||||
it('omet addressType quand aucun radio n\'est choisi (-> 422 NotBlank au lieu d\'un 400 de type)', () => {
|
||||
// emptyAddress() laisse addressType a null : la cle doit etre absente du
|
||||
// payload pour que le back renvoie une 422 propertyPath addressType.
|
||||
const payload = buildAddressPayload(emptyAddress())
|
||||
expect('addressType' in payload).toBe(false)
|
||||
})
|
||||
|
||||
it('n\'expose jamais d\'email de facturation (difference M1)', () => {
|
||||
const payload = buildAddressPayload({ ...emptyAddress(), addressType: 'DEPART' })
|
||||
expect('billingEmail' in payload).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildAccountingPayload (groupe supplier:write:accounting)', () => {
|
||||
const base = {
|
||||
siren: '123456789', accountNumber: '00012345678', nTva: 'FR123',
|
||||
tvaModeIri: '/api/tva_modes/1', paymentDelayIri: '/api/payment_delays/1',
|
||||
paymentTypeIri: '/api/payment_types/1', bankIri: '/api/banks/1',
|
||||
}
|
||||
|
||||
it('envoie la banque seulement si requise (VIREMENT, RG-2.07)', () => {
|
||||
expect(buildAccountingPayload(base, true).bank).toBe('/api/banks/1')
|
||||
expect(buildAccountingPayload(base, false).bank).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildRibPayload (sous-ressource supplier_rib)', () => {
|
||||
it('omet les champs requis vides (-> 422 NotBlank, ERP-119)', () => {
|
||||
const payload = buildRibPayload({ ...emptyRib(), iban: 'FR1420041010050500013M02606' })
|
||||
expect('label' in payload).toBe(false)
|
||||
expect('bic' in payload).toBe(false)
|
||||
expect(payload.iban).toBe('FR1420041010050500013M02606')
|
||||
})
|
||||
})
|
||||
+15
@@ -9,6 +9,7 @@ import {
|
||||
mapAddressView,
|
||||
mapContactToDraft,
|
||||
mapRibToDraft,
|
||||
paymentTypeCodeOf,
|
||||
referentialOptionOf,
|
||||
relationOf,
|
||||
showArchiveAction,
|
||||
@@ -233,3 +234,17 @@ describe('showArchiveAction / showRestoreAction', () => {
|
||||
expect(showRestoreAction(can([]), true)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('paymentTypeCodeOf (ERP-121 : RIB masques hors-LCR en consultation)', () => {
|
||||
it('retourne le code metier quand le type de reglement est embarque', () => {
|
||||
expect(paymentTypeCodeOf({ '@id': '/api/payment_types/1', code: 'LCR' })).toBe('LCR')
|
||||
expect(paymentTypeCodeOf({ '@id': '/api/payment_types/2', code: 'VIREMENT' })).toBe('VIREMENT')
|
||||
})
|
||||
|
||||
it('retourne null pour un IRI nu, un objet sans code, ou une relation absente', () => {
|
||||
expect(paymentTypeCodeOf('/api/payment_types/1')).toBeNull()
|
||||
expect(paymentTypeCodeOf({ '@id': '/api/payment_types/1' })).toBeNull()
|
||||
expect(paymentTypeCodeOf(null)).toBeNull()
|
||||
expect(paymentTypeCodeOf(undefined)).toBeNull()
|
||||
})
|
||||
})
|
||||
+43
@@ -36,6 +36,7 @@ function informationDraft(overrides: Partial<InformationFormDraft> = {}): Inform
|
||||
description: 'desc',
|
||||
competitors: 'concurrents',
|
||||
foundedAt: '2010-05-01',
|
||||
foundedAtRaw: '',
|
||||
employeesCount: '42',
|
||||
revenueAmount: '1000000',
|
||||
profitAmount: '50000',
|
||||
@@ -140,6 +141,16 @@ describe('buildInformationPayload — scoping strict groupe client:write:informa
|
||||
expect(payload.description).toBeNull()
|
||||
expect(payload.directorName).toBeNull()
|
||||
})
|
||||
|
||||
it('envoie la saisie invalide (foundedAtRaw) en priorite -> le back tranchera (422)', () => {
|
||||
// Saisie malformee : on transmet le texte brut tel quel pour declencher la
|
||||
// 422 back sur foundedAt (validation autoritaire du format, MUI-44).
|
||||
expect(buildInformationPayload(informationDraft({ foundedAt: null, foundedAtRaw: '32/13/2026' })).foundedAt)
|
||||
.toBe('32/13/2026')
|
||||
// Saisie valide : foundedAtRaw vide -> on envoie la date ISO.
|
||||
expect(buildInformationPayload(informationDraft({ foundedAt: '2010-05-01', foundedAtRaw: '' })).foundedAt)
|
||||
.toBe('2010-05-01')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildAccountingPayload — scoping strict groupe client:write:accounting', () => {
|
||||
@@ -211,6 +222,38 @@ describe('buildContactPayload / buildAddressPayload / buildRibPayload', () => {
|
||||
})
|
||||
})
|
||||
|
||||
// Bug edition : en PATCH (merge), une cle de champ requis OMISE laisse la valeur
|
||||
// serveur inchangee -> faux 200 quand l'utilisateur vide le champ. En `forUpdate`,
|
||||
// on envoie `''` (chaine valide, pas de 400 de type) -> NotBlank 422 inline.
|
||||
describe('forUpdate (EDITION/PATCH) : champ requis vide -> `\'\'` au lieu d\'etre omis', () => {
|
||||
it('buildMainPayload : companyName vide envoye en `\'\'`', () => {
|
||||
const payload = buildMainPayload(mainDraft({ companyName: '' }), { forUpdate: true })
|
||||
expect('companyName' in payload).toBe(true)
|
||||
expect(payload.companyName).toBe('')
|
||||
})
|
||||
|
||||
it('buildAddressPayload : postalCode / city / street vides envoyes en `\'\'`', () => {
|
||||
const address: AddressFormDraft = {
|
||||
id: 7, isProspect: false, isDelivery: true, isBilling: false, isBroker: false, isDistributor: false, country: 'France',
|
||||
postalCode: '', city: null, street: '1 rue X', streetComplement: null,
|
||||
categoryIris: ['/api/categories/2'], siteIris: ['/api/sites/1'], contactIris: [],
|
||||
billingEmail: null, billingEmailSecondary: null, hasSecondaryBillingEmail: false,
|
||||
}
|
||||
const payload = buildAddressPayload(address, false, { forUpdate: true })
|
||||
expect(payload.postalCode).toBe('')
|
||||
expect(payload.city).toBe('')
|
||||
// Un champ requis renseigne reste tel quel.
|
||||
expect(payload.street).toBe('1 rue X')
|
||||
})
|
||||
|
||||
it('buildRibPayload : label / bic vides envoyes en `\'\'`, iban conserve', () => {
|
||||
const payload = buildRibPayload({ id: 4, label: '', bic: null, iban: 'FR7612345' }, { forUpdate: true })
|
||||
expect(payload.label).toBe('')
|
||||
expect(payload.bic).toBe('')
|
||||
expect(payload.iban).toBe('FR7612345')
|
||||
})
|
||||
})
|
||||
|
||||
describe('mapMainDraft — pre-remplissage bloc principal', () => {
|
||||
it('resout la relation et extrait les IRI (sans contact inline)', () => {
|
||||
const client = {
|
||||
@@ -0,0 +1,239 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
canEditSupplier,
|
||||
categoryOptionsOf,
|
||||
contactOptionsOf,
|
||||
iriOf,
|
||||
mapAccountingDraft,
|
||||
mapAddressToDraft,
|
||||
mapAddressView,
|
||||
mapContactToDraft,
|
||||
mapRibToDraft,
|
||||
paymentTypeCodeOf,
|
||||
referentialOptionOf,
|
||||
showArchiveAction,
|
||||
showRestoreAction,
|
||||
siteOptionsOf,
|
||||
type SupplierDetail,
|
||||
} from '../supplierConsultation'
|
||||
|
||||
describe('iriOf', () => {
|
||||
it('retourne l\'@id d\'une relation embarquee (objet)', () => {
|
||||
expect(iriOf({ '@id': '/api/payment_types/14', code: 'LCR' })).toBe('/api/payment_types/14')
|
||||
})
|
||||
|
||||
it('retourne la chaine telle quelle si la relation est deja un IRI', () => {
|
||||
expect(iriOf('/api/banks/3')).toBe('/api/banks/3')
|
||||
})
|
||||
|
||||
it('retourne null pour une relation absente (null / undefined / skip_null_values)', () => {
|
||||
expect(iriOf(null)).toBeNull()
|
||||
expect(iriOf(undefined)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('mapContactToDraft', () => {
|
||||
it('formate les telephones en XX XX XX XX XX et conserve l\'iri', () => {
|
||||
const draft = mapContactToDraft({
|
||||
'@id': '/api/supplier_contacts/39',
|
||||
id: 39,
|
||||
firstName: 'Marie',
|
||||
lastName: 'Martin',
|
||||
jobTitle: 'Responsable achats',
|
||||
phonePrimary: '0612345678',
|
||||
email: 'marie.martin@seed.test',
|
||||
})
|
||||
expect(draft.id).toBe(39)
|
||||
expect(draft.iri).toBe('/api/supplier_contacts/39')
|
||||
expect(draft.phonePrimary).toBe('06 12 34 56 78')
|
||||
expect(draft.hasSecondaryPhone).toBe(false)
|
||||
})
|
||||
|
||||
it('revele le 2e telephone quand phoneSecondary est present', () => {
|
||||
const draft = mapContactToDraft({
|
||||
'@id': '/api/supplier_contacts/40',
|
||||
id: 40,
|
||||
phonePrimary: '0600000000',
|
||||
phoneSecondary: '0611111111',
|
||||
})
|
||||
expect(draft.hasSecondaryPhone).toBe(true)
|
||||
expect(draft.phoneSecondary).toBe('06 11 11 11 11')
|
||||
})
|
||||
})
|
||||
|
||||
describe('mapAddressToDraft', () => {
|
||||
it('mappe l\'enum addressType, les champs fournisseur et extrait les iris', () => {
|
||||
const draft = mapAddressToDraft({
|
||||
'@id': '/api/supplier_addresses/33',
|
||||
id: 33,
|
||||
addressType: 'DEPART',
|
||||
country: 'France',
|
||||
postalCode: '86000',
|
||||
city: 'Poitiers',
|
||||
street: '12 rue des Acacias',
|
||||
bennes: 3,
|
||||
triageProvider: true,
|
||||
sites: [{ '@id': '/api/sites/87', name: 'Chatellerault', color: '#056CF2' }],
|
||||
categories: [{ '@id': '/api/categories/2279', code: 'NEGOCIANT' }],
|
||||
contacts: [{ '@id': '/api/supplier_contacts/39' }, '/api/supplier_contacts/41'],
|
||||
})
|
||||
expect(draft.addressType).toBe('DEPART')
|
||||
expect(draft.siteIris).toEqual(['/api/sites/87'])
|
||||
expect(draft.categoryIris).toEqual(['/api/categories/2279'])
|
||||
expect(draft.contactIris).toEqual(['/api/supplier_contacts/39', '/api/supplier_contacts/41'])
|
||||
// bennes (entier) → chaine pour MalioInputNumber.
|
||||
expect(draft.bennes).toBe('3')
|
||||
expect(draft.triageProvider).toBe(true)
|
||||
expect(draft.city).toBe('Poitiers')
|
||||
expect(draft.country).toBe('France')
|
||||
})
|
||||
|
||||
it('tolere les champs absents (defauts : France, bennes « 0 », triage faux, type null)', () => {
|
||||
const draft = mapAddressToDraft({ '@id': '/api/supplier_addresses/9', id: 9 })
|
||||
expect(draft.addressType).toBeNull()
|
||||
expect(draft.siteIris).toEqual([])
|
||||
expect(draft.categoryIris).toEqual([])
|
||||
expect(draft.contactIris).toEqual([])
|
||||
expect(draft.country).toBe('France')
|
||||
expect(draft.bennes).toBe('0')
|
||||
expect(draft.triageProvider).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('mapRibToDraft', () => {
|
||||
it('mappe label / bic / iban et l\'id serveur', () => {
|
||||
const draft = mapRibToDraft({ '@id': '/api/supplier_ribs/27', id: 27, label: 'Compte principal', bic: 'BNPAFRPPXXX', iban: 'FR14...' })
|
||||
expect(draft).toEqual({ id: 27, label: 'Compte principal', bic: 'BNPAFRPPXXX', iban: 'FR14...' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('mapAccountingDraft', () => {
|
||||
it('mappe les scalaires et resout les iris des referentiels embarques', () => {
|
||||
const acc = mapAccountingDraft({
|
||||
'@id': '/api/suppliers/85',
|
||||
id: 85,
|
||||
siren: '123456789',
|
||||
accountNumber: 'F0001',
|
||||
nTva: 'FR00123456789',
|
||||
tvaMode: { '@id': '/api/tva_modes/30' },
|
||||
paymentDelay: { '@id': '/api/payment_delays/11' },
|
||||
paymentType: { '@id': '/api/payment_types/14', code: 'LCR' },
|
||||
bank: { '@id': '/api/banks/3' },
|
||||
} as SupplierDetail)
|
||||
expect(acc).toEqual({
|
||||
siren: '123456789',
|
||||
accountNumber: 'F0001',
|
||||
nTva: 'FR00123456789',
|
||||
tvaModeIri: '/api/tva_modes/30',
|
||||
paymentDelayIri: '/api/payment_delays/11',
|
||||
paymentTypeIri: '/api/payment_types/14',
|
||||
bankIri: '/api/banks/3',
|
||||
})
|
||||
})
|
||||
|
||||
it('renvoie des null quand les champs comptables sont absents (gating par omission, sans accounting.view)', () => {
|
||||
const acc = mapAccountingDraft({} as SupplierDetail)
|
||||
expect(acc).toEqual({
|
||||
siren: null,
|
||||
accountNumber: null,
|
||||
nTva: null,
|
||||
tvaModeIri: null,
|
||||
paymentDelayIri: null,
|
||||
paymentTypeIri: null,
|
||||
bankIri: null,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('options construites depuis l\'embed (role-independantes)', () => {
|
||||
it('categoryOptionsOf expose value=IRI, label=nom, code', () => {
|
||||
expect(categoryOptionsOf([{ '@id': '/api/categories/2279', name: 'Negociant', code: 'NEGOCIANT' }])).toEqual([
|
||||
{ value: '/api/categories/2279', label: 'Negociant', code: 'NEGOCIANT' },
|
||||
])
|
||||
})
|
||||
|
||||
it('siteOptionsOf expose value=IRI, label=nom', () => {
|
||||
expect(siteOptionsOf([{ '@id': '/api/sites/87', name: 'Chatellerault', color: '#000' }])).toEqual([
|
||||
{ value: '/api/sites/87', label: 'Chatellerault' },
|
||||
])
|
||||
})
|
||||
|
||||
it('contactOptionsOf compose le libelle (nom complet, sinon email)', () => {
|
||||
expect(contactOptionsOf([
|
||||
{ '@id': '/api/supplier_contacts/1', id: 1, firstName: 'Marie', lastName: 'Martin' },
|
||||
{ '@id': '/api/supplier_contacts/2', id: 2, email: 'a@b.fr' },
|
||||
])).toEqual([
|
||||
{ value: '/api/supplier_contacts/1', label: 'Marie Martin' },
|
||||
{ value: '/api/supplier_contacts/2', label: 'a@b.fr' },
|
||||
])
|
||||
})
|
||||
|
||||
it('referentialOptionOf : option unique depuis l\'embed, vide pour IRI nu / absent', () => {
|
||||
expect(referentialOptionOf({ '@id': '/api/payment_types/14', label: 'LCR' })).toEqual([
|
||||
{ value: '/api/payment_types/14', label: 'LCR' },
|
||||
])
|
||||
expect(referentialOptionOf('/api/banks/3')).toEqual([])
|
||||
expect(referentialOptionOf(null)).toEqual([])
|
||||
})
|
||||
|
||||
it('mapAddressView assemble brouillon + options propres a l\'adresse', () => {
|
||||
const view = mapAddressView({
|
||||
'@id': '/api/supplier_addresses/33',
|
||||
id: 33,
|
||||
addressType: 'RENDU',
|
||||
city: 'Poitiers',
|
||||
sites: [{ '@id': '/api/sites/87', name: 'Chatellerault' }],
|
||||
categories: [{ '@id': '/api/categories/2279', name: 'Negociant', code: 'NEGOCIANT' }],
|
||||
})
|
||||
expect(view.draft.id).toBe(33)
|
||||
expect(view.draft.addressType).toBe('RENDU')
|
||||
expect(view.siteOptions).toEqual([{ value: '/api/sites/87', label: 'Chatellerault' }])
|
||||
expect(view.categoryOptions).toEqual([{ value: '/api/categories/2279', label: 'Negociant', code: 'NEGOCIANT' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('canEditSupplier', () => {
|
||||
const can = (granted: string[]) => (codes: string[]) => codes.some(c => granted.includes(c))
|
||||
|
||||
it('visible pour manage', () => {
|
||||
expect(canEditSupplier(can(['commercial.suppliers.manage']))).toBe(true)
|
||||
})
|
||||
|
||||
it('visible pour accounting.manage (role Compta)', () => {
|
||||
expect(canEditSupplier(can(['commercial.suppliers.accounting.manage']))).toBe(true)
|
||||
})
|
||||
|
||||
it('masque sans aucune des deux permissions (role Usine)', () => {
|
||||
expect(canEditSupplier(can(['commercial.suppliers.view']))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('showArchiveAction / showRestoreAction', () => {
|
||||
const can = (granted: string[]) => (code: string) => granted.includes(code)
|
||||
|
||||
it('Archiver : visible avec la permission archive ET fournisseur non archive', () => {
|
||||
expect(showArchiveAction(can(['commercial.suppliers.archive']), false)).toBe(true)
|
||||
expect(showArchiveAction(can(['commercial.suppliers.archive']), true)).toBe(false)
|
||||
expect(showArchiveAction(can([]), false)).toBe(false)
|
||||
})
|
||||
|
||||
it('Restaurer : visible avec la permission archive ET fournisseur archive', () => {
|
||||
expect(showRestoreAction(can(['commercial.suppliers.archive']), true)).toBe(true)
|
||||
expect(showRestoreAction(can(['commercial.suppliers.archive']), false)).toBe(false)
|
||||
expect(showRestoreAction(can([]), true)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('paymentTypeCodeOf (ERP-121 : RIB masques hors-LCR en consultation)', () => {
|
||||
it('retourne le code metier quand le type de reglement est embarque', () => {
|
||||
expect(paymentTypeCodeOf({ '@id': '/api/payment_types/1', code: 'LCR' })).toBe('LCR')
|
||||
expect(paymentTypeCodeOf({ '@id': '/api/payment_types/2', code: 'VIREMENT' })).toBe('VIREMENT')
|
||||
})
|
||||
|
||||
it('retourne null pour un IRI nu, un objet sans code, ou une relation absente', () => {
|
||||
expect(paymentTypeCodeOf('/api/payment_types/1')).toBeNull()
|
||||
expect(paymentTypeCodeOf({ '@id': '/api/payment_types/1' })).toBeNull()
|
||||
expect(paymentTypeCodeOf(null)).toBeNull()
|
||||
expect(paymentTypeCodeOf(undefined)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,227 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
buildAccountingPayload,
|
||||
buildAddressPayload,
|
||||
buildContactPayload,
|
||||
buildInformationPayload,
|
||||
buildMainPayload,
|
||||
buildRibPayload,
|
||||
mapAccountingFormDraft,
|
||||
mapInformationDraft,
|
||||
mapMainDraft,
|
||||
resolveTabEditability,
|
||||
} from '../supplierEdit'
|
||||
import type { SupplierDetail } from '~/modules/commercial/utils/forms/supplierConsultation'
|
||||
import { emptyAddress, emptyContact, emptyRib } from '~/modules/commercial/types/supplierForm'
|
||||
|
||||
describe('buildMainPayload (groupe supplier:write:main)', () => {
|
||||
it('envoie companyName + categories quand renseignes', () => {
|
||||
expect(buildMainPayload({ companyName: 'ACME', categoryIris: ['/api/categories/1'] })).toEqual({
|
||||
companyName: 'ACME',
|
||||
categories: ['/api/categories/1'],
|
||||
})
|
||||
})
|
||||
|
||||
it('CREATION : omet companyName vide (-> 422 NotBlank, ERP-119)', () => {
|
||||
const payload = buildMainPayload({ companyName: null, categoryIris: [] })
|
||||
expect('companyName' in payload).toBe(false)
|
||||
expect(payload.categories).toEqual([])
|
||||
})
|
||||
|
||||
it('EDITION (forUpdate) : companyName vide envoye en `\'\'` (PATCH -> 422 NotBlank, pas un faux 200)', () => {
|
||||
const payload = buildMainPayload({ companyName: '', categoryIris: [] }, { forUpdate: true })
|
||||
expect('companyName' in payload).toBe(true)
|
||||
expect(payload.companyName).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildInformationPayload (groupe supplier:write:information)', () => {
|
||||
const base = {
|
||||
description: null, competitors: null, foundedAt: null, foundedAtRaw: '', employeesCount: null,
|
||||
revenueAmount: null, profitAmount: null, directorName: null, volumeForecast: null,
|
||||
}
|
||||
|
||||
it('convertit employeesCount et volumeForecast en nombre, null si vide', () => {
|
||||
expect(buildInformationPayload({ ...base, employeesCount: '42', volumeForecast: '1000' })).toMatchObject({
|
||||
employeesCount: 42,
|
||||
volumeForecast: 1000,
|
||||
})
|
||||
expect(buildInformationPayload(base)).toMatchObject({ employeesCount: null, volumeForecast: null })
|
||||
})
|
||||
|
||||
it('envoie la saisie invalide (foundedAtRaw) en priorite -> le back tranchera (422)', () => {
|
||||
// Saisie malformee transmise telle quelle pour declencher la 422 back (MUI-44).
|
||||
expect(buildInformationPayload({ ...base, foundedAt: null, foundedAtRaw: '32/13/2026' }).foundedAt)
|
||||
.toBe('32/13/2026')
|
||||
// Saisie valide : foundedAtRaw vide -> on envoie la date ISO.
|
||||
expect(buildInformationPayload({ ...base, foundedAt: '2008-04-01', foundedAtRaw: '' }).foundedAt)
|
||||
.toBe('2008-04-01')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildContactPayload (sous-ressource supplier_contact)', () => {
|
||||
it('n\'envoie le 2e telephone que si revele (hasSecondaryPhone)', () => {
|
||||
const contact = { ...emptyContact(), phonePrimary: '0102030405', phoneSecondary: '0607080910' }
|
||||
expect(buildContactPayload({ ...contact, hasSecondaryPhone: false }).phoneSecondary).toBeNull()
|
||||
expect(buildContactPayload({ ...contact, hasSecondaryPhone: true }).phoneSecondary).toBe('0607080910')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildAddressPayload (sous-ressource supplier_address — specificites M2)', () => {
|
||||
it('envoie addressType (enum), bennes (nombre) et triageProvider', () => {
|
||||
const address = {
|
||||
...emptyAddress(),
|
||||
addressType: 'RENDU' as const,
|
||||
postalCode: '86100', city: 'Châtellerault', street: '1 rue de la Paix',
|
||||
siteIris: ['/api/sites/1'], categoryIris: ['/api/categories/2'],
|
||||
bennes: '3', triageProvider: true,
|
||||
}
|
||||
expect(buildAddressPayload(address)).toMatchObject({
|
||||
addressType: 'RENDU',
|
||||
bennes: 3,
|
||||
triageProvider: true,
|
||||
sites: ['/api/sites/1'],
|
||||
categories: ['/api/categories/2'],
|
||||
})
|
||||
})
|
||||
|
||||
it('bennes null quand le champ est vide', () => {
|
||||
expect(buildAddressPayload({ ...emptyAddress(), bennes: '' }).bennes).toBeNull()
|
||||
})
|
||||
|
||||
it('omet postalCode / city / street vides (-> 422 NotBlank, ERP-119)', () => {
|
||||
const payload = buildAddressPayload({ ...emptyAddress(), addressType: 'PROSPECT' })
|
||||
expect('postalCode' in payload).toBe(false)
|
||||
expect('city' in payload).toBe(false)
|
||||
expect('street' in payload).toBe(false)
|
||||
// Les champs non requis restent presents.
|
||||
expect('streetComplement' in payload).toBe(true)
|
||||
expect(payload.addressType).toBe('PROSPECT')
|
||||
})
|
||||
|
||||
it('omet addressType quand aucun radio n\'est choisi (-> 422 NotBlank au lieu d\'un 400 de type)', () => {
|
||||
// emptyAddress() laisse addressType a null : la cle doit etre absente du
|
||||
// payload pour que le back renvoie une 422 propertyPath addressType.
|
||||
const payload = buildAddressPayload(emptyAddress())
|
||||
expect('addressType' in payload).toBe(false)
|
||||
})
|
||||
|
||||
it('EDITION (forUpdate) : un champ requis vide est envoye en `\'\'` (et NON omis) pour declencher la 422 NotBlank au PATCH', () => {
|
||||
// Bug edition : omettre la cle d'un champ requis vide laisse le PATCH garder
|
||||
// l'ancienne valeur (faux 200). En `forUpdate`, on envoie `''` -> NotBlank 422.
|
||||
const payload = buildAddressPayload({ ...emptyAddress(), addressType: 'DEPART', postalCode: '' }, { forUpdate: true })
|
||||
expect('postalCode' in payload).toBe(true)
|
||||
expect(payload.postalCode).toBe('')
|
||||
// Un champ requis renseigne reste tel quel.
|
||||
expect(payload.addressType).toBe('DEPART')
|
||||
})
|
||||
|
||||
it('n\'expose jamais d\'email de facturation (difference M1)', () => {
|
||||
const payload = buildAddressPayload({ ...emptyAddress(), addressType: 'DEPART' })
|
||||
expect('billingEmail' in payload).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildAccountingPayload (groupe supplier:write:accounting)', () => {
|
||||
const base = {
|
||||
siren: '123456789', accountNumber: '00012345678', nTva: 'FR123',
|
||||
tvaModeIri: '/api/tva_modes/1', paymentDelayIri: '/api/payment_delays/1',
|
||||
paymentTypeIri: '/api/payment_types/1', bankIri: '/api/banks/1',
|
||||
}
|
||||
|
||||
it('envoie la banque seulement si requise (VIREMENT, RG-2.07)', () => {
|
||||
expect(buildAccountingPayload(base, true).bank).toBe('/api/banks/1')
|
||||
expect(buildAccountingPayload(base, false).bank).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildRibPayload (sous-ressource supplier_rib)', () => {
|
||||
it('omet les champs requis vides (-> 422 NotBlank, ERP-119)', () => {
|
||||
const payload = buildRibPayload({ ...emptyRib(), iban: 'FR1420041010050500013M02606' })
|
||||
expect('label' in payload).toBe(false)
|
||||
expect('bic' in payload).toBe(false)
|
||||
expect(payload.iban).toBe('FR1420041010050500013M02606')
|
||||
})
|
||||
})
|
||||
|
||||
describe('mapMainDraft — pre-remplissage bloc principal (companyName + categories, pas de relation M2)', () => {
|
||||
it('extrait companyName et les IRI de categories', () => {
|
||||
const draft = mapMainDraft({
|
||||
'@id': '/api/suppliers/85', id: 85,
|
||||
companyName: 'DOD862875',
|
||||
categories: [{ '@id': '/api/categories/2279', code: 'NEGOCIANT' }],
|
||||
} as SupplierDetail)
|
||||
expect(draft.companyName).toBe('DOD862875')
|
||||
expect(draft.categoryIris).toEqual(['/api/categories/2279'])
|
||||
})
|
||||
|
||||
it('gere les cles omises (skip_null_values) sans planter', () => {
|
||||
const draft = mapMainDraft({ '@id': '/api/suppliers/2', id: 2 } as SupplierDetail)
|
||||
expect(draft.companyName).toBeNull()
|
||||
expect(draft.categoryIris).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('mapInformationDraft — pre-remplissage onglet Information (+ volumeForecast M2)', () => {
|
||||
it('tronque foundedAt, stringifie employeesCount et volumeForecast', () => {
|
||||
const draft = mapInformationDraft({
|
||||
'@id': '/api/suppliers/85', id: 85,
|
||||
foundedAt: '2008-04-01T00:00:00+02:00', employeesCount: 42, volumeForecast: 8000,
|
||||
} as SupplierDetail)
|
||||
expect(draft.foundedAt).toBe('2008-04-01')
|
||||
expect(draft.employeesCount).toBe('42')
|
||||
expect(draft.volumeForecast).toBe('8000')
|
||||
})
|
||||
|
||||
it('cles omises -> null (volumeForecast inclus)', () => {
|
||||
const draft = mapInformationDraft({ '@id': '/api/suppliers/1', id: 1 } as SupplierDetail)
|
||||
expect(draft.foundedAt).toBeNull()
|
||||
expect(draft.employeesCount).toBeNull()
|
||||
expect(draft.volumeForecast).toBeNull()
|
||||
expect(draft.description).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('mapAccountingFormDraft — pre-remplissage onglet Comptabilite', () => {
|
||||
it('extrait les scalaires et les IRI des referentiels embarques', () => {
|
||||
const draft = mapAccountingFormDraft({
|
||||
'@id': '/api/suppliers/85', id: 85,
|
||||
siren: '123456789', accountNumber: 'F0001', nTva: 'FR00123456789',
|
||||
tvaMode: { '@id': '/api/tva_modes/30', label: 'France (ventes)' },
|
||||
paymentType: '/api/payment_types/14',
|
||||
} as SupplierDetail)
|
||||
expect(draft.siren).toBe('123456789')
|
||||
expect(draft.tvaModeIri).toBe('/api/tva_modes/30')
|
||||
expect(draft.paymentTypeIri).toBe('/api/payment_types/14')
|
||||
expect(draft.bankIri).toBeNull()
|
||||
})
|
||||
|
||||
it('cles comptables absentes (gating par omission) -> scalaires/IRI null', () => {
|
||||
const draft = mapAccountingFormDraft({ '@id': '/api/suppliers/1', id: 1 } as SupplierDetail)
|
||||
expect(draft.siren).toBeNull()
|
||||
expect(draft.tvaModeIri).toBeNull()
|
||||
expect(draft.bankIri).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveTabEditability — gating par role (matrice § 2.7)', () => {
|
||||
it('Admin : tout editable', () => {
|
||||
expect(resolveTabEditability({ canManage: true, canAccountingView: true, canAccountingManage: true }))
|
||||
.toEqual({ businessEditable: true, accountingVisible: true, accountingEditable: true })
|
||||
})
|
||||
|
||||
it('Bureau / Commerciale (manage seul) : metier editable, Comptabilite masquee', () => {
|
||||
expect(resolveTabEditability({ canManage: true, canAccountingView: false, canAccountingManage: false }))
|
||||
.toEqual({ businessEditable: true, accountingVisible: false, accountingEditable: false })
|
||||
})
|
||||
|
||||
it('Compta (accounting seul) : metier readonly, Comptabilite editable', () => {
|
||||
expect(resolveTabEditability({ canManage: false, canAccountingView: true, canAccountingManage: true }))
|
||||
.toEqual({ businessEditable: false, accountingVisible: true, accountingEditable: true })
|
||||
})
|
||||
|
||||
it('Sans permission d\'edition : rien d\'editable', () => {
|
||||
expect(resolveTabEditability({ canManage: false, canAccountingView: false, canAccountingManage: false }))
|
||||
.toEqual({ businessEditable: false, accountingVisible: false, accountingEditable: false })
|
||||
})
|
||||
})
|
||||
+15
@@ -293,6 +293,21 @@ export function referentialOptionOf(relation: Relation): SelectOption[] {
|
||||
return [{ value: relation['@id'], label }]
|
||||
}
|
||||
|
||||
/**
|
||||
* Code metier d'un referentiel embarque (ex: PaymentType.code = 'LCR' / 'VIREMENT'),
|
||||
* ou null si la relation est absente / serialisee en IRI nu. Type-safe : la branche
|
||||
* chaine (IRI nu) et l'absence sont court-circuitees avant l'acces au code. Sert a
|
||||
* conditionner l'affichage selon le type de reglement courant (ERP-121 : RIB masques
|
||||
* hors-LCR en consultation).
|
||||
*/
|
||||
export function paymentTypeCodeOf(relation: Relation): string | null {
|
||||
if (!relation || typeof relation === 'string') {
|
||||
return null
|
||||
}
|
||||
|
||||
return (relation.code as string | undefined) ?? null
|
||||
}
|
||||
|
||||
/** Vue d'une adresse (brouillon + options de select propres a l'adresse). */
|
||||
export function mapAddressView(address: AddressRead): AddressView {
|
||||
return {
|
||||
+50
-14
@@ -20,13 +20,14 @@ import {
|
||||
iriOf,
|
||||
relationOf,
|
||||
type ClientDetail,
|
||||
} from '~/modules/commercial/utils/clientConsultation'
|
||||
} from '~/modules/commercial/utils/forms/clientConsultation'
|
||||
import {
|
||||
ADDRESS_REQUIRED_NON_NULLABLE_KEYS,
|
||||
blankEmptyRequired,
|
||||
MAIN_REQUIRED_NON_NULLABLE_KEYS,
|
||||
omitEmptyRequired,
|
||||
RIB_REQUIRED_NON_NULLABLE_KEYS,
|
||||
} from '~/modules/commercial/utils/clientFormRules'
|
||||
} from '~/modules/commercial/utils/forms/clientFormRules'
|
||||
import type { AddressFormDraft, ContactFormDraft, RibFormDraft } from '~/modules/commercial/types/clientForm'
|
||||
|
||||
/**
|
||||
@@ -52,6 +53,13 @@ export interface InformationFormDraft {
|
||||
competitors: string | null
|
||||
/** Date de creation de l'entreprise au format YYYY-MM-DD (MalioDate). */
|
||||
foundedAt: string | null
|
||||
/**
|
||||
* Saisie brute invalide remontee par MalioDate (`@update:rawValue`) : '' tant
|
||||
* que la saisie est valide/vide, sinon le texte tel que tape. On l'envoie au
|
||||
* back en priorite sur `foundedAt` pour que la 422 (validation autoritaire du
|
||||
* format, ERP-101) porte sur le champ et s'affiche inline. Cf. MUI-44.
|
||||
*/
|
||||
foundedAtRaw: string
|
||||
/** Nombre de salaries en chaine (saisie masquee), converti en number au PATCH. */
|
||||
employeesCount: string | null
|
||||
revenueAmount: string | null
|
||||
@@ -117,6 +125,8 @@ export function mapInformationDraft(client: ClientDetail): InformationFormDraft
|
||||
competitors: client.competitors ?? null,
|
||||
// MalioDate attend strictement YYYY-MM-DD : on tronque l'ISO datetime.
|
||||
foundedAt: client.foundedAt ? client.foundedAt.slice(0, 10) : null,
|
||||
// Aucune saisie brute invalide au chargement (la valeur stockee est valide).
|
||||
foundedAtRaw: '',
|
||||
employeesCount: client.employeesCount != null ? String(client.employeesCount) : null,
|
||||
revenueAmount: client.revenueAmount ?? null,
|
||||
profitAmount: client.profitAmount ?? null,
|
||||
@@ -139,12 +149,35 @@ export function mapAccountingFormDraft(client: ClientDetail): AccountingFormDraf
|
||||
|
||||
// ── Scoping strict des payloads PATCH ────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Options de construction d'un payload d'ecriture.
|
||||
* - `forUpdate: false` (defaut, CREATION/POST) : champs requis vides OMIS -> 422
|
||||
* NotBlank (le back ne reçoit pas la cle, la propriete garde son defaut).
|
||||
* - `forUpdate: true` (EDITION/PATCH d'une ligne existante) : champs requis vides
|
||||
* envoyes en `''` -> 422 NotBlank (sinon une cle omise laisse la valeur serveur
|
||||
* inchangee, faux 200 — cf. blankEmptyRequired).
|
||||
*/
|
||||
export interface BuildPayloadOptions {
|
||||
forUpdate?: boolean
|
||||
}
|
||||
|
||||
/** Selectionne le finaliseur des champs requis selon création (omit) vs édition (blank). */
|
||||
function finalizeRequired<T extends Record<string, unknown>>(
|
||||
payload: T,
|
||||
requiredKeys: readonly string[],
|
||||
options: BuildPayloadOptions,
|
||||
): T {
|
||||
return options.forUpdate
|
||||
? blankEmptyRequired(payload, requiredKeys)
|
||||
: omitEmptyRequired(payload, requiredKeys)
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload du bloc principal — groupe client:write:main UNIQUEMENT. La relation
|
||||
* Distributeur/Courtier est mutuellement exclusive (RG-1.03) : on ne renseigne
|
||||
* que la FK correspondant au type choisi, l'autre est forcee a null.
|
||||
*/
|
||||
export function buildMainPayload(main: MainFormDraft): Record<string, unknown> {
|
||||
export function buildMainPayload(main: MainFormDraft, options: BuildPayloadOptions = {}): Record<string, unknown> {
|
||||
// companyName omis si vide -> 422 NotBlank au lieu d'un 400 de type (ERP-119).
|
||||
// relationType : champ transitoire (non persiste cote back) qui porte
|
||||
// l'intention UI « ce client depend d'un distributeur / courtier ». Il sert
|
||||
@@ -152,14 +185,14 @@ export function buildMainPayload(main: MainFormDraft): Record<string, unknown> {
|
||||
// la FK correspondante devient obligatoire -> 422 sur distributor / broker.
|
||||
// Sans equivalent derivable cote back (FK nullable), c'est la seule facon de
|
||||
// rester sur « on soumet, le back tranche » plutot qu'une garde front-only.
|
||||
return omitEmptyRequired({
|
||||
return finalizeRequired({
|
||||
companyName: main.companyName,
|
||||
categories: main.categoryIris,
|
||||
relationType: main.relationType,
|
||||
distributor: main.relationType === 'distributeur' ? main.distributorIri : null,
|
||||
broker: main.relationType === 'courtier' ? main.brokerIri : null,
|
||||
triageService: main.triageService,
|
||||
}, MAIN_REQUIRED_NON_NULLABLE_KEYS)
|
||||
}, MAIN_REQUIRED_NON_NULLABLE_KEYS, options)
|
||||
}
|
||||
|
||||
/** Payload de l'onglet Information — groupe client:write:information UNIQUEMENT. */
|
||||
@@ -167,7 +200,9 @@ export function buildInformationPayload(information: InformationFormDraft): Reco
|
||||
return {
|
||||
description: information.description || null,
|
||||
competitors: information.competitors || null,
|
||||
foundedAt: information.foundedAt || null,
|
||||
// Saisie invalide (foundedAtRaw) prioritaire : on l'envoie telle quelle
|
||||
// pour que le back renvoie une 422 sur foundedAt (cf. foundedAtRaw).
|
||||
foundedAt: information.foundedAtRaw || information.foundedAt || null,
|
||||
employeesCount: information.employeesCount ? Number(information.employeesCount) : null,
|
||||
revenueAmount: information.revenueAmount || null,
|
||||
profitAmount: information.profitAmount || null,
|
||||
@@ -211,9 +246,10 @@ export function buildContactPayload(contact: ContactFormDraft): Record<string, u
|
||||
export function buildAddressPayload(
|
||||
address: AddressFormDraft,
|
||||
isBillingEmailRequired: boolean,
|
||||
options: BuildPayloadOptions = {},
|
||||
): Record<string, unknown> {
|
||||
// postalCode / city / street omis si vides -> 422 NotBlank (ERP-119).
|
||||
return omitEmptyRequired({
|
||||
// postalCode / city / street : omis a la creation, `''` en edition -> 422 NotBlank (ERP-119).
|
||||
return finalizeRequired({
|
||||
isProspect: address.isProspect,
|
||||
isDelivery: address.isDelivery,
|
||||
isBilling: address.isBilling,
|
||||
@@ -229,18 +265,18 @@ export function buildAddressPayload(
|
||||
contacts: address.contactIris,
|
||||
billingEmail: isBillingEmailRequired ? (address.billingEmail || null) : null,
|
||||
billingEmailSecondary: isBillingEmailRequired && address.hasSecondaryBillingEmail ? (address.billingEmailSecondary || null) : null,
|
||||
}, ADDRESS_REQUIRED_NON_NULLABLE_KEYS)
|
||||
}, ADDRESS_REQUIRED_NON_NULLABLE_KEYS, options)
|
||||
}
|
||||
|
||||
/** Payload d'un RIB (sous-ressource client_rib). */
|
||||
export function buildRibPayload(rib: RibFormDraft): Record<string, unknown> {
|
||||
// label / bic / iban omis si vides -> 422 NotBlank au lieu d'un 400 de type
|
||||
// sur un RIB partiel (ex. IBAN seul). ERP-119.
|
||||
return omitEmptyRequired({
|
||||
export function buildRibPayload(rib: RibFormDraft, options: BuildPayloadOptions = {}): Record<string, unknown> {
|
||||
// label / bic / iban : omis a la creation, `''` en edition -> 422 NotBlank au lieu
|
||||
// d'un 400 de type (ou d'un faux 200 PATCH qui garderait l'ancienne valeur). ERP-119.
|
||||
return finalizeRequired({
|
||||
label: rib.label,
|
||||
bic: rib.bic,
|
||||
iban: rib.iban,
|
||||
}, RIB_REQUIRED_NON_NULLABLE_KEYS)
|
||||
}, RIB_REQUIRED_NON_NULLABLE_KEYS, options)
|
||||
}
|
||||
|
||||
// ── Gating par permission ────────────────────────────────────────────────────
|
||||
+25
@@ -419,3 +419,28 @@ export function omitEmptyRequired<T extends Record<string, unknown>>(
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
/**
|
||||
* Variante PATCH (edition d'une ligne EXISTANTE) : remplace les cles requises
|
||||
* laissees vides par une chaine vide `''` au lieu de les OMETTRE.
|
||||
*
|
||||
* Pourquoi pas `omitEmptyRequired` en edition : un PATCH a semantique merge — une
|
||||
* cle absente laisse la valeur serveur INCHANGEE. Vider un champ requis puis valider
|
||||
* renverrait alors un 200 trompeur (l'ancienne valeur est conservee). En envoyant
|
||||
* `''` (chaine valide), on evite le 400 de type (« must be string, NULL given ») et
|
||||
* le Validator `NotBlank(trim)` rejette la valeur -> 422 avec propertyPath, mappee
|
||||
* inline sous le champ. Mute et retourne le payload.
|
||||
*/
|
||||
export function blankEmptyRequired<T extends Record<string, unknown>>(
|
||||
payload: T,
|
||||
requiredKeys: readonly string[],
|
||||
): T {
|
||||
for (const key of requiredKeys) {
|
||||
const value = payload[key]
|
||||
if (value === null || value === undefined || value === '') {
|
||||
(payload as Record<string, unknown>)[key] = ''
|
||||
}
|
||||
}
|
||||
|
||||
return payload
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
/**
|
||||
* Helpers purs de l'ecran « Consultation fournisseur » (M2 Commercial, lecture
|
||||
* seule). Miroir de `clientConsultation.ts` (M1), adapte aux differences M2.
|
||||
*
|
||||
* Mappent le payload `GET /api/suppliers/{id}` (relations embarquees, cf. groupe
|
||||
* `supplier:item:read` + `supplier:read:accounting`) vers les brouillons « plats »
|
||||
* partages avec les blocs reutilisables `SupplierContactBlock` / `SupplierAddressBlock`
|
||||
* et l'onglet Comptabilite. Ne touchent ni a l'API ni a l'etat reactif : testables
|
||||
* unitairement (cf. supplierConsultation.spec.ts).
|
||||
*
|
||||
* Rappels de contrat back (verifies sur le JSON reel fige — ERP-92, spec-back § 4.0.bis) :
|
||||
* - les relations ManyToOne (tvaMode/paymentDelay/paymentType/bank) sont
|
||||
* serialisees en OBJETS embarques (`{id, code, label}`), pas en IRI nu ;
|
||||
* - les champs nuls sont OMIS du JSON (skip_null_values) → toujours lire avec `?? null` ;
|
||||
* - les champs comptables et `ribs` sont TOTALEMENT ABSENTS (cle omise, pas `null`)
|
||||
* sans permission accounting.view (gate serveur via SupplierReadGroupContextBuilder).
|
||||
*
|
||||
* Differences M2 vs M1 :
|
||||
* - Adresse via enum `addressType` (PROSPECT/DEPART/RENDU, RG-2.09) — pas de
|
||||
* drapeaux isProspect/isDelivery/isBilling.
|
||||
* - Adresse : champs specifiques fournisseur `bennes` (nombre) et `triageProvider`.
|
||||
* Pas d'email de facturation.
|
||||
* - Information : champ specifique fournisseur `volumeForecast`.
|
||||
* - Pas de relation Distributeur/Courtier ni de triage sur le bloc principal.
|
||||
*/
|
||||
|
||||
import { formatPhoneFR } from '~/shared/utils/phone'
|
||||
import {
|
||||
emptyAddress,
|
||||
type SupplierAddressFormDraft,
|
||||
type SupplierAddressType,
|
||||
type SupplierContactFormDraft,
|
||||
type SupplierRibFormDraft,
|
||||
} from '~/modules/commercial/types/supplierForm'
|
||||
|
||||
/** Reference Hydra embarquee minimale (@id toujours present). */
|
||||
export interface HydraRef {
|
||||
'@id': string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
/** Une relation peut etre embarquee (objet), un IRI nu (chaine) ou absente. */
|
||||
export type Relation = HydraRef | string | null | undefined
|
||||
|
||||
/** Site embarque dans une adresse (groupe site:read). */
|
||||
export interface SiteRead extends HydraRef {
|
||||
name?: string
|
||||
color?: string
|
||||
}
|
||||
|
||||
/** Categorie embarquee (groupe category:read). */
|
||||
export interface CategoryRead extends HydraRef {
|
||||
code?: string
|
||||
name?: string
|
||||
}
|
||||
|
||||
/** Contact embarque (groupe supplier_contact:read). */
|
||||
export interface ContactRead extends HydraRef {
|
||||
id: number
|
||||
firstName?: string | null
|
||||
lastName?: string | null
|
||||
jobTitle?: string | null
|
||||
phonePrimary?: string | null
|
||||
phoneSecondary?: string | null
|
||||
email?: string | null
|
||||
}
|
||||
|
||||
/** Adresse embarquee (groupe supplier_address:read). */
|
||||
export interface AddressRead extends HydraRef {
|
||||
id: number
|
||||
addressType?: SupplierAddressType | null
|
||||
country?: string | null
|
||||
postalCode?: string | null
|
||||
city?: string | null
|
||||
street?: string | null
|
||||
streetComplement?: string | null
|
||||
bennes?: number | null
|
||||
triageProvider?: boolean
|
||||
sites?: SiteRead[]
|
||||
categories?: CategoryRead[]
|
||||
// L'embed M2M des contacts d'adresse peut etre un objet (partiel) ou un IRI nu.
|
||||
contacts?: Array<HydraRef | string>
|
||||
}
|
||||
|
||||
/** RIB embarque (groupe supplier:read:accounting, present ssi accounting.view). */
|
||||
export interface RibRead extends HydraRef {
|
||||
id: number
|
||||
label?: string | null
|
||||
bic?: string | null
|
||||
iban?: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Detail d'un fournisseur tel que renvoye par `GET /api/suppliers/{id}`. Tous les
|
||||
* champs sont optionnels : skip_null_values cote serveur et gating accounting
|
||||
* peuvent omettre n'importe quelle cle.
|
||||
*/
|
||||
export interface SupplierDetail extends HydraRef {
|
||||
id: number
|
||||
companyName?: string | null
|
||||
isArchived?: boolean
|
||||
categories?: CategoryRead[]
|
||||
contacts?: ContactRead[]
|
||||
addresses?: AddressRead[]
|
||||
ribs?: RibRead[]
|
||||
// Onglet Information
|
||||
description?: string | null
|
||||
competitors?: string | null
|
||||
foundedAt?: string | null
|
||||
employeesCount?: number | null
|
||||
revenueAmount?: string | null
|
||||
profitAmount?: string | null
|
||||
directorName?: string | null
|
||||
/** Volume previsionnel (entier, specifique fournisseur). */
|
||||
volumeForecast?: number | null
|
||||
// Onglet Comptabilite (present ssi accounting.view)
|
||||
siren?: string | null
|
||||
accountNumber?: string | null
|
||||
nTva?: string | null
|
||||
tvaMode?: Relation
|
||||
paymentDelay?: Relation
|
||||
paymentType?: Relation
|
||||
bank?: Relation
|
||||
}
|
||||
|
||||
/** Etat « plat » de l'onglet Comptabilite (miroir lecture du formulaire). */
|
||||
export interface AccountingDraft {
|
||||
siren: string | null
|
||||
accountNumber: string | null
|
||||
nTva: string | null
|
||||
tvaModeIri: string | null
|
||||
paymentDelayIri: string | null
|
||||
paymentTypeIri: string | null
|
||||
bankIri: string | null
|
||||
}
|
||||
|
||||
/** Option de select ({ value, label }) construite a partir de l'embed. */
|
||||
export interface SelectOption {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
/** Option de categorie enrichie de son code (compatible CategoryOption des blocs). */
|
||||
export interface CategorySelectOption extends SelectOption {
|
||||
code: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Vue d'une adresse pour la consultation : le brouillon + ses options de select
|
||||
* construites a partir de l'embed (sites/categories propres a CETTE adresse).
|
||||
*/
|
||||
export interface AddressView {
|
||||
draft: SupplierAddressFormDraft
|
||||
siteOptions: SelectOption[]
|
||||
categoryOptions: CategorySelectOption[]
|
||||
}
|
||||
|
||||
/** Extrait l'IRI d'une relation (objet embarque, IRI nu, ou null si absente). */
|
||||
export function iriOf(relation: Relation): string | null {
|
||||
if (relation === null || relation === undefined) {
|
||||
return null
|
||||
}
|
||||
if (typeof relation === 'string') {
|
||||
return relation
|
||||
}
|
||||
return relation['@id'] ?? null
|
||||
}
|
||||
|
||||
/** Mappe un contact embarque vers un brouillon (telephones formates XX XX XX XX XX). */
|
||||
export function mapContactToDraft(contact: ContactRead): SupplierContactFormDraft {
|
||||
const phoneSecondary = contact.phoneSecondary ?? null
|
||||
return {
|
||||
id: contact.id,
|
||||
iri: contact['@id'] ?? null,
|
||||
firstName: contact.firstName ?? null,
|
||||
lastName: contact.lastName ?? null,
|
||||
jobTitle: contact.jobTitle ?? null,
|
||||
phonePrimary: contact.phonePrimary ? formatPhoneFR(contact.phonePrimary) : null,
|
||||
phoneSecondary: phoneSecondary ? formatPhoneFR(phoneSecondary) : null,
|
||||
email: contact.email ?? null,
|
||||
hasSecondaryPhone: phoneSecondary !== null && phoneSecondary !== '',
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mappe une adresse embarquee vers un brouillon (IRI extraits des sous-collections).
|
||||
* `bennes` (entier) est converti en chaine pour MalioInputNumber (defaut « 0 »).
|
||||
*/
|
||||
export function mapAddressToDraft(address: AddressRead): SupplierAddressFormDraft {
|
||||
return {
|
||||
id: address.id,
|
||||
addressType: address.addressType ?? null,
|
||||
country: address.country ?? 'France',
|
||||
postalCode: address.postalCode ?? null,
|
||||
city: address.city ?? null,
|
||||
street: address.street ?? null,
|
||||
streetComplement: address.streetComplement ?? null,
|
||||
categoryIris: (address.categories ?? []).map(c => c['@id']),
|
||||
siteIris: (address.sites ?? []).map(s => s['@id']),
|
||||
contactIris: (address.contacts ?? []).map(c => (typeof c === 'string' ? c : c['@id'])),
|
||||
bennes: address.bennes != null ? String(address.bennes) : '0',
|
||||
triageProvider: address.triageProvider ?? false,
|
||||
}
|
||||
}
|
||||
|
||||
/** Mappe un RIB embarque vers un brouillon. */
|
||||
export function mapRibToDraft(rib: RibRead): SupplierRibFormDraft {
|
||||
return {
|
||||
id: rib.id,
|
||||
label: rib.label ?? null,
|
||||
bic: rib.bic ?? null,
|
||||
iban: rib.iban ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/** Mappe les champs comptables du fournisseur (scalaires + IRI des referentiels). */
|
||||
export function mapAccountingDraft(supplier: SupplierDetail): AccountingDraft {
|
||||
return {
|
||||
siren: supplier.siren ?? null,
|
||||
accountNumber: supplier.accountNumber ?? null,
|
||||
nTva: supplier.nTva ?? null,
|
||||
tvaModeIri: iriOf(supplier.tvaMode),
|
||||
paymentDelayIri: iriOf(supplier.paymentDelay),
|
||||
paymentTypeIri: iriOf(supplier.paymentType),
|
||||
bankIri: iriOf(supplier.bank),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Options de categories (value=IRI, label=nom, code) construites depuis l'embed.
|
||||
* Source role-independante : evite de dependre de `GET /categories` (403 pour les
|
||||
* roles metier non-admin), qui laisserait les libelles vides.
|
||||
*/
|
||||
export function categoryOptionsOf(categories: CategoryRead[] | undefined): CategorySelectOption[] {
|
||||
return (categories ?? []).map(c => ({
|
||||
value: c['@id'],
|
||||
label: c.name ?? c.code ?? c['@id'],
|
||||
code: c.code ?? '',
|
||||
}))
|
||||
}
|
||||
|
||||
/** Options de sites (value=IRI, label=nom) construites depuis l'embed d'une adresse. */
|
||||
export function siteOptionsOf(sites: SiteRead[] | undefined): SelectOption[] {
|
||||
return (sites ?? []).map(s => ({ value: s['@id'], label: s.name ?? s['@id'] }))
|
||||
}
|
||||
|
||||
/** Options de contacts (value=IRI, label=nom complet ou email) depuis l'embed fournisseur. */
|
||||
export function contactOptionsOf(contacts: ContactRead[] | undefined): SelectOption[] {
|
||||
return (contacts ?? []).map(c => ({
|
||||
value: c['@id'],
|
||||
label: [c.firstName, c.lastName].filter(Boolean).join(' ') || (c.email ?? c['@id']),
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Liste a une seule option (ou vide) construite depuis un referentiel embarque
|
||||
* (TvaMode / PaymentDelay / PaymentType / Bank) pour alimenter un MalioSelect en
|
||||
* lecture seule. Le libelle vient de l'embed (`label` ou `name`), jamais d'un
|
||||
* `GET` de referentiel — l'affichage reste correct quel que soit le role.
|
||||
*/
|
||||
export function referentialOptionOf(relation: Relation): SelectOption[] {
|
||||
if (!relation || typeof relation === 'string') {
|
||||
return []
|
||||
}
|
||||
const label = (relation.label as string | undefined)
|
||||
?? (relation.name as string | undefined)
|
||||
?? relation['@id']
|
||||
return [{ value: relation['@id'], label }]
|
||||
}
|
||||
|
||||
/**
|
||||
* Code metier d'un referentiel embarque (ex: PaymentType.code = 'LCR' / 'VIREMENT'),
|
||||
* ou null si la relation est absente / serialisee en IRI nu. Type-safe : la branche
|
||||
* chaine (IRI nu) et l'absence sont court-circuitees avant l'acces au code. Sert a
|
||||
* conditionner l'affichage selon le type de reglement courant (ERP-121 : RIB masques
|
||||
* hors-LCR en consultation).
|
||||
*/
|
||||
export function paymentTypeCodeOf(relation: Relation): string | null {
|
||||
if (!relation || typeof relation === 'string') {
|
||||
return null
|
||||
}
|
||||
|
||||
return (relation.code as string | undefined) ?? null
|
||||
}
|
||||
|
||||
/** Vue d'une adresse (brouillon + options de select propres a l'adresse). */
|
||||
export function mapAddressView(address: AddressRead): AddressView {
|
||||
return {
|
||||
draft: mapAddressToDraft(address),
|
||||
siteOptions: siteOptionsOf(address.sites),
|
||||
categoryOptions: categoryOptionsOf(address.categories),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bouton « Modifier » : visible si l'utilisateur peut editer au moins un onglet
|
||||
* — `manage` (formulaire/onglets metier) OU `accounting.manage` (le role Compta
|
||||
* doit pouvoir ouvrir l'edition pour son onglet Comptabilite). Le readonly fin
|
||||
* par onglet est gere sur l'ecran d'edition (96).
|
||||
*/
|
||||
export function canEditSupplier(canAny: (codes: string[]) => boolean): boolean {
|
||||
return canAny(['commercial.suppliers.manage', 'commercial.suppliers.accounting.manage'])
|
||||
}
|
||||
|
||||
/** Bouton « Archiver » : permission archive ET fournisseur encore actif. */
|
||||
export function showArchiveAction(can: (code: string) => boolean, isArchived: boolean): boolean {
|
||||
return can('commercial.suppliers.archive') && !isArchived
|
||||
}
|
||||
|
||||
/** Bouton « Restaurer » : permission archive ET fournisseur deja archive. */
|
||||
export function showRestoreAction(can: (code: string) => boolean, isArchived: boolean): boolean {
|
||||
return can('commercial.suppliers.archive') && isArchived
|
||||
}
|
||||
|
||||
/** Brouillon d'adresse vierge (reexport pour la page : 1 bloc vide si aucune adresse). */
|
||||
export { emptyAddress }
|
||||
@@ -0,0 +1,261 @@
|
||||
/**
|
||||
* Helpers purs des ecrans « Ajouter » / « Modifier » un fournisseur (M2
|
||||
* Commercial) — miroir de `clientEdit.ts` (M1). Deux responsabilites, toutes deux
|
||||
* testables unitairement (cf. supplierEdit.spec.ts) :
|
||||
* 1. Pre-remplissage : mapper le payload `GET /api/suppliers/{id}` (embed +
|
||||
* scalaires) vers les brouillons « plats » edites par la page de modification.
|
||||
* 2. Scoping STRICT des payloads PATCH (mode strict RG-2.16 / ERP-74) : chaque
|
||||
* onglet n'envoie QUE les champs de SON groupe de serialisation, jamais un
|
||||
* payload mixte (un champ hors-permission = 403 sur l'integralite cote back).
|
||||
*
|
||||
* Ces helpers ne touchent ni a l'API ni a l'etat reactif.
|
||||
*/
|
||||
|
||||
import {
|
||||
ADDRESS_REQUIRED_NON_NULLABLE_KEYS,
|
||||
blankEmptyRequired,
|
||||
MAIN_REQUIRED_NON_NULLABLE_KEYS,
|
||||
omitEmptyRequired,
|
||||
RIB_REQUIRED_NON_NULLABLE_KEYS,
|
||||
} from '~/modules/commercial/utils/forms/supplierFormRules'
|
||||
import { iriOf, type SupplierDetail } from '~/modules/commercial/utils/forms/supplierConsultation'
|
||||
import type {
|
||||
SupplierAddressFormDraft,
|
||||
SupplierContactFormDraft,
|
||||
SupplierRibFormDraft,
|
||||
} from '~/modules/commercial/types/supplierForm'
|
||||
|
||||
/** Etat « plat » du bloc principal (groupe supplier:write:main). */
|
||||
export interface MainFormDraft {
|
||||
companyName: string | null
|
||||
/** IRI des categories rattachees (M2M, type FOURNISSEUR). */
|
||||
categoryIris: string[]
|
||||
}
|
||||
|
||||
/** Etat « plat » de l'onglet Information (groupe supplier:write:information). */
|
||||
export interface InformationFormDraft {
|
||||
description: string | null
|
||||
competitors: string | null
|
||||
/** Date de creation de l'entreprise au format YYYY-MM-DD (MalioDate). */
|
||||
foundedAt: string | null
|
||||
/**
|
||||
* Saisie brute invalide remontee par MalioDate (`@update:rawValue`) : '' tant
|
||||
* que la saisie est valide/vide, sinon le texte tel que tape. On l'envoie au
|
||||
* back en priorite sur `foundedAt` pour que la 422 (validation autoritaire du
|
||||
* format, ERP-101) porte sur le champ et s'affiche inline. Cf. MUI-44.
|
||||
*/
|
||||
foundedAtRaw: string
|
||||
/** Nombre de salaries en chaine (saisie masquee), converti en number au PATCH. */
|
||||
employeesCount: string | null
|
||||
revenueAmount: string | null
|
||||
profitAmount: string | null
|
||||
directorName: string | null
|
||||
/** Volume previsionnel (entier >= 0, specifique fournisseur) en chaine. */
|
||||
volumeForecast: string | null
|
||||
}
|
||||
|
||||
/** Etat « plat » de l'onglet Comptabilite (groupe supplier:write:accounting). */
|
||||
export interface AccountingFormDraft {
|
||||
siren: string | null
|
||||
accountNumber: string | null
|
||||
nTva: string | null
|
||||
tvaModeIri: string | null
|
||||
paymentDelayIri: string | null
|
||||
paymentTypeIri: string | null
|
||||
bankIri: string | null
|
||||
}
|
||||
|
||||
/** Permissions de l'utilisateur courant pertinentes pour l'edition d'un fournisseur. */
|
||||
export interface SupplierEditAbilities {
|
||||
/** `commercial.suppliers.manage` : bloc principal + onglets metier. */
|
||||
canManage: boolean
|
||||
/** `commercial.suppliers.accounting.view` : visibilite de l'onglet Comptabilite. */
|
||||
canAccountingView: boolean
|
||||
/** `commercial.suppliers.accounting.manage` : edition de l'onglet Comptabilite. */
|
||||
canAccountingManage: boolean
|
||||
}
|
||||
|
||||
/** Editabilite resolue par zone d'onglet (deduite des permissions). */
|
||||
export interface TabEditability {
|
||||
/** Bloc principal + onglets Information / Contacts / Adresses editables. */
|
||||
businessEditable: boolean
|
||||
/** Onglet Comptabilite present (affiche). */
|
||||
accountingVisible: boolean
|
||||
/** Onglet Comptabilite editable. */
|
||||
accountingEditable: boolean
|
||||
}
|
||||
|
||||
// ── Pre-remplissage (GET detail -> brouillons) ──────────────────────────────
|
||||
|
||||
/** Mappe le detail fournisseur vers le brouillon du bloc principal. */
|
||||
export function mapMainDraft(supplier: SupplierDetail): MainFormDraft {
|
||||
return {
|
||||
companyName: supplier.companyName ?? null,
|
||||
categoryIris: (supplier.categories ?? []).map(c => c['@id']),
|
||||
}
|
||||
}
|
||||
|
||||
/** Mappe le detail fournisseur vers le brouillon de l'onglet Information. */
|
||||
export function mapInformationDraft(supplier: SupplierDetail): InformationFormDraft {
|
||||
return {
|
||||
description: supplier.description ?? null,
|
||||
competitors: supplier.competitors ?? null,
|
||||
// MalioDate attend strictement YYYY-MM-DD : on tronque l'ISO datetime.
|
||||
foundedAt: supplier.foundedAt ? supplier.foundedAt.slice(0, 10) : null,
|
||||
// Aucune saisie brute invalide au chargement (la valeur stockee est valide).
|
||||
foundedAtRaw: '',
|
||||
employeesCount: supplier.employeesCount != null ? String(supplier.employeesCount) : null,
|
||||
revenueAmount: supplier.revenueAmount ?? null,
|
||||
profitAmount: supplier.profitAmount ?? null,
|
||||
directorName: supplier.directorName ?? null,
|
||||
// Volume previsionnel (entier, specifique fournisseur) en chaine pour la saisie.
|
||||
volumeForecast: supplier.volumeForecast != null ? String(supplier.volumeForecast) : null,
|
||||
}
|
||||
}
|
||||
|
||||
/** Mappe les champs comptables du detail vers le brouillon de l'onglet (scalaires + IRI). */
|
||||
export function mapAccountingFormDraft(supplier: SupplierDetail): AccountingFormDraft {
|
||||
return {
|
||||
siren: supplier.siren ?? null,
|
||||
accountNumber: supplier.accountNumber ?? null,
|
||||
nTva: supplier.nTva ?? null,
|
||||
tvaModeIri: iriOf(supplier.tvaMode),
|
||||
paymentDelayIri: iriOf(supplier.paymentDelay),
|
||||
paymentTypeIri: iriOf(supplier.paymentType),
|
||||
bankIri: iriOf(supplier.bank),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resout l'editabilite par zone a partir des permissions (option 1 ERP-74,
|
||||
* miroir UI du re-gating champ-par-champ du SupplierProcessor) :
|
||||
* - bloc principal + Information/Contacts/Adresses : editables ssi `manage` ;
|
||||
* - Comptabilite : visible ssi `accounting.view`, editable ssi `accounting.manage`.
|
||||
*
|
||||
* Produit le comportement attendu :
|
||||
* - Admin : tout editable.
|
||||
* - Bureau / Commerciale (manage, sans accounting) : metier editable, Compta masquee.
|
||||
* - Compta (accounting seul, sans manage) : metier readonly, Compta editable.
|
||||
*/
|
||||
export function resolveTabEditability(abilities: SupplierEditAbilities): TabEditability {
|
||||
return {
|
||||
businessEditable: abilities.canManage,
|
||||
accountingVisible: abilities.canAccountingView,
|
||||
accountingEditable: abilities.canAccountingManage,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Scoping strict des payloads PATCH/POST ──────────────────────────────────
|
||||
|
||||
/**
|
||||
* Options de construction d'un payload d'ecriture.
|
||||
* - `forUpdate: false` (defaut, CREATION/POST) : les champs requis vides sont OMIS
|
||||
* -> 422 NotBlank a l'insert (le back ne reçoit pas la cle).
|
||||
* - `forUpdate: true` (EDITION/PATCH d'une ligne existante) : les champs requis
|
||||
* vides sont envoyes en `''` -> 422 NotBlank (sinon une cle omise laisse la valeur
|
||||
* serveur inchangee, faux 200 — cf. blankEmptyRequired).
|
||||
*/
|
||||
export interface BuildPayloadOptions {
|
||||
forUpdate?: boolean
|
||||
}
|
||||
|
||||
/** Selectionne le finaliseur des champs requis selon création (omit) vs édition (blank). */
|
||||
function finalizeRequired<T extends Record<string, unknown>>(
|
||||
payload: T,
|
||||
requiredKeys: readonly string[],
|
||||
options: BuildPayloadOptions,
|
||||
): T {
|
||||
return options.forUpdate
|
||||
? blankEmptyRequired(payload, requiredKeys)
|
||||
: omitEmptyRequired(payload, requiredKeys)
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload du bloc principal — groupe supplier:write:main UNIQUEMENT.
|
||||
* companyName vide -> 422 NotBlank (omis a la creation, `''` en edition — ERP-119).
|
||||
*/
|
||||
export function buildMainPayload(main: MainFormDraft, options: BuildPayloadOptions = {}): Record<string, unknown> {
|
||||
return finalizeRequired({
|
||||
companyName: main.companyName,
|
||||
categories: main.categoryIris,
|
||||
}, MAIN_REQUIRED_NON_NULLABLE_KEYS, options)
|
||||
}
|
||||
|
||||
/** Payload de l'onglet Information — groupe supplier:write:information UNIQUEMENT. */
|
||||
export function buildInformationPayload(information: InformationFormDraft): Record<string, unknown> {
|
||||
return {
|
||||
description: information.description || null,
|
||||
competitors: information.competitors || null,
|
||||
// Saisie invalide (foundedAtRaw) prioritaire : on l'envoie telle quelle
|
||||
// pour que le back renvoie une 422 sur foundedAt (cf. foundedAtRaw).
|
||||
foundedAt: information.foundedAtRaw || information.foundedAt || null,
|
||||
employeesCount: information.employeesCount ? Number(information.employeesCount) : null,
|
||||
revenueAmount: information.revenueAmount || null,
|
||||
profitAmount: information.profitAmount || null,
|
||||
directorName: information.directorName || null,
|
||||
volumeForecast: information.volumeForecast ? Number(information.volumeForecast) : null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload des scalaires de l'onglet Comptabilite — groupe supplier:write:accounting
|
||||
* UNIQUEMENT (les RIB passent par la sous-ressource /suppliers/{id}/ribs). La
|
||||
* banque n'a de sens que pour un Virement (RG-2.07) : forcee a null sinon.
|
||||
*/
|
||||
export function buildAccountingPayload(
|
||||
accounting: AccountingFormDraft,
|
||||
isBankRequired: boolean,
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
siren: accounting.siren || null,
|
||||
accountNumber: accounting.accountNumber || null,
|
||||
tvaMode: accounting.tvaModeIri,
|
||||
nTva: accounting.nTva || null,
|
||||
paymentDelay: accounting.paymentDelayIri,
|
||||
paymentType: accounting.paymentTypeIri,
|
||||
bank: isBankRequired ? accounting.bankIri : null,
|
||||
}
|
||||
}
|
||||
|
||||
/** Payload d'un contact (sous-ressource supplier_contact). */
|
||||
export function buildContactPayload(contact: SupplierContactFormDraft): Record<string, unknown> {
|
||||
return {
|
||||
firstName: contact.firstName || null,
|
||||
lastName: contact.lastName || null,
|
||||
jobTitle: contact.jobTitle || null,
|
||||
phonePrimary: contact.phonePrimary || null,
|
||||
phoneSecondary: contact.hasSecondaryPhone ? (contact.phoneSecondary || null) : null,
|
||||
email: contact.email || null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload d'une adresse (sous-ressource supplier_address). postalCode / city /
|
||||
* street omis si vides -> 422 NotBlank (ERP-119). Specifique fournisseur :
|
||||
* `bennes` (entier, 0 par defaut) + `triageProvider` (booleen). Pas d'email de
|
||||
* facturation (difference M1).
|
||||
*/
|
||||
export function buildAddressPayload(address: SupplierAddressFormDraft, options: BuildPayloadOptions = {}): Record<string, unknown> {
|
||||
return finalizeRequired({
|
||||
addressType: address.addressType,
|
||||
country: address.country,
|
||||
postalCode: address.postalCode || null,
|
||||
city: address.city || null,
|
||||
street: address.street || null,
|
||||
streetComplement: address.streetComplement || null,
|
||||
categories: address.categoryIris,
|
||||
sites: address.siteIris,
|
||||
contacts: address.contactIris,
|
||||
bennes: address.bennes !== null && address.bennes !== '' ? Number(address.bennes) : null,
|
||||
triageProvider: address.triageProvider,
|
||||
}, ADDRESS_REQUIRED_NON_NULLABLE_KEYS, options)
|
||||
}
|
||||
|
||||
/** Payload d'un RIB (sous-ressource supplier_rib). */
|
||||
export function buildRibPayload(rib: SupplierRibFormDraft, options: BuildPayloadOptions = {}): Record<string, unknown> {
|
||||
return finalizeRequired({
|
||||
label: rib.label,
|
||||
bic: rib.bic,
|
||||
iban: rib.iban,
|
||||
}, RIB_REQUIRED_NON_NULLABLE_KEYS, options)
|
||||
}
|
||||
+25
@@ -217,3 +217,28 @@ export function omitEmptyRequired<T extends Record<string, unknown>>(
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
/**
|
||||
* Variante PATCH (edition d'une ligne EXISTANTE) : remplace les cles requises
|
||||
* laissees vides par une chaine vide `''` au lieu de les OMETTRE.
|
||||
*
|
||||
* Pourquoi pas `omitEmptyRequired` en edition : un PATCH a semantique merge — une
|
||||
* cle absente laisse la valeur serveur INCHANGEE. Vider un champ requis puis valider
|
||||
* renverrait alors un 200 trompeur (l'ancienne valeur est conservee). En envoyant
|
||||
* `''`, la propriete `?string` est bien deserialisee (pas de 400 de type, contrairement
|
||||
* a `null` sur une colonne non-nullable), puis le Validator `NotBlank(trim)` la rejette
|
||||
* -> 422 avec propertyPath, mappee inline sous le champ. Mute et retourne le payload.
|
||||
*/
|
||||
export function blankEmptyRequired<T extends Record<string, unknown>>(
|
||||
payload: T,
|
||||
requiredKeys: readonly string[],
|
||||
): T {
|
||||
for (const key of requiredKeys) {
|
||||
const value = payload[key]
|
||||
if (value === null || value === undefined || value === '') {
|
||||
(payload as Record<string, unknown>)[key] = ''
|
||||
}
|
||||
}
|
||||
|
||||
return payload
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
/**
|
||||
* Helpers purs de payload de l'ecran « Ajouter un fournisseur » (M2 Commercial),
|
||||
* partages avec la future modification (96) — miroir de `clientEdit.ts` (M1).
|
||||
*
|
||||
* Scoping STRICT des payloads (mode strict, aligne ERP-74/RG) : chaque onglet
|
||||
* n'envoie QUE les champs de SON groupe de serialisation, jamais un payload mixte
|
||||
* (un champ hors-permission = 403 sur l'integralite cote back). Ces helpers ne
|
||||
* touchent ni a l'API ni a l'etat reactif.
|
||||
*/
|
||||
|
||||
import {
|
||||
ADDRESS_REQUIRED_NON_NULLABLE_KEYS,
|
||||
MAIN_REQUIRED_NON_NULLABLE_KEYS,
|
||||
omitEmptyRequired,
|
||||
RIB_REQUIRED_NON_NULLABLE_KEYS,
|
||||
} from '~/modules/commercial/utils/supplierFormRules'
|
||||
import type {
|
||||
SupplierAddressFormDraft,
|
||||
SupplierContactFormDraft,
|
||||
SupplierRibFormDraft,
|
||||
} from '~/modules/commercial/types/supplierForm'
|
||||
|
||||
/** Etat « plat » du bloc principal (groupe supplier:write:main). */
|
||||
export interface MainFormDraft {
|
||||
companyName: string | null
|
||||
/** IRI des categories rattachees (M2M, type FOURNISSEUR). */
|
||||
categoryIris: string[]
|
||||
}
|
||||
|
||||
/** Etat « plat » de l'onglet Information (groupe supplier:write:information). */
|
||||
export interface InformationFormDraft {
|
||||
description: string | null
|
||||
competitors: string | null
|
||||
/** Date de creation de l'entreprise au format YYYY-MM-DD (MalioDate). */
|
||||
foundedAt: string | null
|
||||
/** Nombre de salaries en chaine (saisie masquee), converti en number au PATCH. */
|
||||
employeesCount: string | null
|
||||
revenueAmount: string | null
|
||||
profitAmount: string | null
|
||||
directorName: string | null
|
||||
/** Volume previsionnel (entier >= 0, specifique fournisseur) en chaine. */
|
||||
volumeForecast: string | null
|
||||
}
|
||||
|
||||
/** Etat « plat » de l'onglet Comptabilite (groupe supplier:write:accounting). */
|
||||
export interface AccountingFormDraft {
|
||||
siren: string | null
|
||||
accountNumber: string | null
|
||||
nTva: string | null
|
||||
tvaModeIri: string | null
|
||||
paymentDelayIri: string | null
|
||||
paymentTypeIri: string | null
|
||||
bankIri: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload du bloc principal — groupe supplier:write:main UNIQUEMENT.
|
||||
* companyName omis si vide -> 422 NotBlank au lieu d'un 400 de type (ERP-119).
|
||||
*/
|
||||
export function buildMainPayload(main: MainFormDraft): Record<string, unknown> {
|
||||
return omitEmptyRequired({
|
||||
companyName: main.companyName,
|
||||
categories: main.categoryIris,
|
||||
}, MAIN_REQUIRED_NON_NULLABLE_KEYS)
|
||||
}
|
||||
|
||||
/** Payload de l'onglet Information — groupe supplier:write:information UNIQUEMENT. */
|
||||
export function buildInformationPayload(information: InformationFormDraft): Record<string, unknown> {
|
||||
return {
|
||||
description: information.description || null,
|
||||
competitors: information.competitors || null,
|
||||
foundedAt: information.foundedAt || null,
|
||||
employeesCount: information.employeesCount ? Number(information.employeesCount) : null,
|
||||
revenueAmount: information.revenueAmount || null,
|
||||
profitAmount: information.profitAmount || null,
|
||||
directorName: information.directorName || null,
|
||||
volumeForecast: information.volumeForecast ? Number(information.volumeForecast) : null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload des scalaires de l'onglet Comptabilite — groupe supplier:write:accounting
|
||||
* UNIQUEMENT (les RIB passent par la sous-ressource /suppliers/{id}/ribs). La
|
||||
* banque n'a de sens que pour un Virement (RG-2.07) : forcee a null sinon.
|
||||
*/
|
||||
export function buildAccountingPayload(
|
||||
accounting: AccountingFormDraft,
|
||||
isBankRequired: boolean,
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
siren: accounting.siren || null,
|
||||
accountNumber: accounting.accountNumber || null,
|
||||
tvaMode: accounting.tvaModeIri,
|
||||
nTva: accounting.nTva || null,
|
||||
paymentDelay: accounting.paymentDelayIri,
|
||||
paymentType: accounting.paymentTypeIri,
|
||||
bank: isBankRequired ? accounting.bankIri : null,
|
||||
}
|
||||
}
|
||||
|
||||
/** Payload d'un contact (sous-ressource supplier_contact). */
|
||||
export function buildContactPayload(contact: SupplierContactFormDraft): Record<string, unknown> {
|
||||
return {
|
||||
firstName: contact.firstName || null,
|
||||
lastName: contact.lastName || null,
|
||||
jobTitle: contact.jobTitle || null,
|
||||
phonePrimary: contact.phonePrimary || null,
|
||||
phoneSecondary: contact.hasSecondaryPhone ? (contact.phoneSecondary || null) : null,
|
||||
email: contact.email || null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload d'une adresse (sous-ressource supplier_address). postalCode / city /
|
||||
* street omis si vides -> 422 NotBlank (ERP-119). Specifique fournisseur :
|
||||
* `bennes` (entier, 0 par defaut) + `triageProvider` (booleen). Pas d'email de
|
||||
* facturation (difference M1).
|
||||
*/
|
||||
export function buildAddressPayload(address: SupplierAddressFormDraft): Record<string, unknown> {
|
||||
return omitEmptyRequired({
|
||||
addressType: address.addressType,
|
||||
country: address.country,
|
||||
postalCode: address.postalCode || null,
|
||||
city: address.city || null,
|
||||
street: address.street || null,
|
||||
streetComplement: address.streetComplement || null,
|
||||
categories: address.categoryIris,
|
||||
sites: address.siteIris,
|
||||
contacts: address.contactIris,
|
||||
bennes: address.bennes !== null && address.bennes !== '' ? Number(address.bennes) : null,
|
||||
triageProvider: address.triageProvider,
|
||||
}, ADDRESS_REQUIRED_NON_NULLABLE_KEYS)
|
||||
}
|
||||
|
||||
/** Payload d'un RIB (sous-ressource supplier_rib). */
|
||||
export function buildRibPayload(rib: SupplierRibFormDraft): Record<string, unknown> {
|
||||
return omitEmptyRequired({
|
||||
label: rib.label,
|
||||
bic: rib.bic,
|
||||
iban: rib.iban,
|
||||
}, RIB_REQUIRED_NON_NULLABLE_KEYS)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export default defineNuxtConfig({})
|
||||
Generated
+4
-4
@@ -7,7 +7,7 @@
|
||||
"name": "starseed-frontend",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@malio/layer-ui": "^1.7.8",
|
||||
"@malio/layer-ui": "^1.7.10",
|
||||
"@nuxt/icon": "^2.2.1",
|
||||
"@nuxtjs/i18n": "^10.2.3",
|
||||
"@nuxtjs/tailwindcss": "^6.14.0",
|
||||
@@ -1866,9 +1866,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@malio/layer-ui": {
|
||||
"version": "1.7.8",
|
||||
"resolved": "https://gitea.malio.fr/api/packages/MALIO-DEV/npm/%40malio%2Flayer-ui/-/1.7.8/layer-ui-1.7.8.tgz",
|
||||
"integrity": "sha512-gUMAZzBsPCfQUF3OQSjN/OFzjONvQZYfwqH0u5VUbxaqwBdX1hUGtjD4ym6RvZkyNsKulrxkncFZYTWCS+IdGA==",
|
||||
"version": "1.7.10",
|
||||
"resolved": "https://gitea.malio.fr/api/packages/MALIO-DEV/npm/%40malio%2Flayer-ui/-/1.7.10/layer-ui-1.7.10.tgz",
|
||||
"integrity": "sha512-ZWYaKvl+VpGAqeTE+4xdyKOmuRd4zwjlUYVppeIBZwGeNAK16kZnrztR+4eQmnzUqPZVybBhEBdKP9weqWHSUg==",
|
||||
"dependencies": {
|
||||
"@nuxt/icon": "^2.2.1",
|
||||
"@nuxtjs/tailwindcss": "^6.14.0",
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
"test:e2e:ui": "playwright test --ui"
|
||||
},
|
||||
"dependencies": {
|
||||
"@malio/layer-ui": "^1.7.8",
|
||||
"@malio/layer-ui": "^1.7.10",
|
||||
"@nuxt/icon": "^2.2.1",
|
||||
"@nuxtjs/i18n": "^10.2.3",
|
||||
"@nuxtjs/tailwindcss": "^6.14.0",
|
||||
|
||||
@@ -41,6 +41,22 @@ describe('useFormErrors', () => {
|
||||
expect(hasErrors.value).toBe(true)
|
||||
})
|
||||
|
||||
it('setServerErrors surcharge un message technique (erreur de type) par la cle i18n', () => {
|
||||
const { errors, setServerErrors } = useFormErrors()
|
||||
const mapped = setServerErrors({
|
||||
violations: [
|
||||
// Code Symfony Type::INVALID_TYPE_ERROR (date non parsable) : surcharge.
|
||||
{ propertyPath: 'foundedAt', message: 'Cette valeur doit être de type DateTimeImmutable|null.', code: 'ba785a8c-82cb-4283-967c-3cf342181b40' },
|
||||
// Violation metier classique : message back conserve.
|
||||
{ propertyPath: 'companyName', message: 'Obligatoire.', code: 'c1051bb4-d103-4f74-8988-acbcafc7fdc3' },
|
||||
],
|
||||
})
|
||||
expect(mapped).toBe(true)
|
||||
// Stub i18n -> renvoie la cle telle quelle.
|
||||
expect(errors.foundedAt).toBe('errors.validation.invalidDate')
|
||||
expect(errors.companyName).toBe('Obligatoire.')
|
||||
})
|
||||
|
||||
it('setServerErrors retourne false et ne touche rien sans violation', () => {
|
||||
const { errors, setServerErrors } = useFormErrors()
|
||||
expect(setServerErrors({})).toBe(false)
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
* appel par ligne), utiliser directement `mapViolationsToRecord` par ligne.
|
||||
*/
|
||||
import { computed, reactive } from 'vue'
|
||||
import { extractApiErrorMessage, mapViolationsToRecord } from '~/shared/utils/api'
|
||||
import { extractApiErrorMessage, extractApiViolations, resolveViolationMessage } from '~/shared/utils/api'
|
||||
|
||||
/**
|
||||
* Erreur HTTP capturee par ofetch. On n'expose que les champs lus ici (status
|
||||
@@ -69,13 +69,16 @@ export function useFormErrors() {
|
||||
* violation exploitable).
|
||||
*/
|
||||
function setServerErrors(data: unknown): boolean {
|
||||
const mapped = mapViolationsToRecord(data)
|
||||
const keys = Object.keys(mapped)
|
||||
if (keys.length === 0) return false
|
||||
for (const key of keys) {
|
||||
errors[key] = mapped[key]
|
||||
const violations = extractApiViolations(data)
|
||||
let mapped = false
|
||||
for (const v of violations) {
|
||||
if (!v.propertyPath) continue
|
||||
// Message back tel quel, sauf code surcharge par une cle i18n (ex.
|
||||
// erreur de type sur une date non parsable -> « Date invalide »).
|
||||
errors[v.propertyPath] = resolveViolationMessage(v, t)
|
||||
mapped = true
|
||||
}
|
||||
return true
|
||||
return mapped
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { mapViolationsToRecord } from '../api'
|
||||
import { mapViolationsToRecord, resolveViolationMessage } from '../api'
|
||||
|
||||
/**
|
||||
* Tests de `mapViolationsToRecord` — fondation du mapping erreur→champ des
|
||||
@@ -56,3 +56,30 @@ describe('mapViolationsToRecord', () => {
|
||||
expect(mapViolationsToRecord(data)).toEqual({ name: 'Second message.' })
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Tests de `resolveViolationMessage` — surcharge i18n d'un message back par code
|
||||
* de violation. Le back peut renvoyer un message technique (erreur de type sur
|
||||
* une date non parsable) : on le remplace via le `code` Symfony (stable) par une
|
||||
* cle i18n, sans toucher au back. Le `t` ici renvoie la cle telle quelle.
|
||||
*/
|
||||
describe('resolveViolationMessage', () => {
|
||||
const t = (key: string) => key
|
||||
// Code Symfony Constraints\Type::INVALID_TYPE_ERROR (fige).
|
||||
const TYPE_ERROR = 'ba785a8c-82cb-4283-967c-3cf342181b40'
|
||||
|
||||
it('surcharge le message technique d\'une erreur de type par la cle i18n', () => {
|
||||
const v = { propertyPath: 'foundedAt', message: 'Cette valeur doit être de type DateTimeImmutable|null.', code: TYPE_ERROR }
|
||||
expect(resolveViolationMessage(v, t)).toBe('errors.validation.invalidDate')
|
||||
})
|
||||
|
||||
it('renvoie le message back tel quel quand le code n\'est pas surcharge', () => {
|
||||
const v = { propertyPath: 'companyName', message: 'Le nom est obligatoire.', code: 'c1051bb4-d103-4f74-8988-acbcafc7fdc3' }
|
||||
expect(resolveViolationMessage(v, t)).toBe('Le nom est obligatoire.')
|
||||
})
|
||||
|
||||
it('renvoie le message back tel quel quand il n\'y a pas de code', () => {
|
||||
const v = { propertyPath: 'siren', message: 'SIREN deja utilise.', code: '' }
|
||||
expect(resolveViolationMessage(v, t)).toBe('SIREN deja utilise.')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -34,11 +34,15 @@ export function extractHydraMembers<T>(collection: HydraCollection<T>): T[] {
|
||||
|
||||
/**
|
||||
* Une violation de contrainte API Platform (reponse 422). Le `propertyPath`
|
||||
* pointe le champ concerne, `message` est le libelle a afficher.
|
||||
* pointe le champ concerne, `message` est le libelle a afficher, `code` est le
|
||||
* code de contrainte Symfony (UUID stable, independant de la langue) — il sert
|
||||
* a surcharger un message back technique par une cle i18n (cf.
|
||||
* `VIOLATION_MESSAGE_I18N` / `resolveViolationMessage`).
|
||||
*/
|
||||
export interface ApiViolation {
|
||||
propertyPath: string
|
||||
message: string
|
||||
code: string
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,6 +65,7 @@ export function extractApiViolations(data: unknown): ApiViolation[] {
|
||||
out.push({
|
||||
propertyPath: String(obj.propertyPath ?? ''),
|
||||
message: String(obj.message ?? ''),
|
||||
code: String(obj.code ?? ''),
|
||||
})
|
||||
}
|
||||
return out
|
||||
@@ -85,6 +90,45 @@ export function mapViolationsToRecord(data: unknown): Record<string, string> {
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Surcharge i18n d'un message back par CODE de violation.
|
||||
*
|
||||
* La plupart des contraintes back portent deja un message FR explicite (ex.
|
||||
* `#[Assert\NotBlank(message: '...')]`) : on l'affiche tel quel. Mais certaines
|
||||
* 422 portent un message TECHNIQUE non montrable a l'utilisateur — typiquement
|
||||
* l'erreur de TYPE renvoyee par API Platform quand le back ne peut pas
|
||||
* denormaliser la valeur (date non parsable envoyee sur un champ
|
||||
* `DateTimeImmutable` : « Cette valeur doit être de type DateTimeImmutable|null. »,
|
||||
* voire en anglais selon la negociation de langue).
|
||||
*
|
||||
* Plutot que de traduire/maquiller cote back, on surcharge ces messages cote
|
||||
* front via leur `code` de violation. Ce code est un UUID Symfony FIGE (contrat
|
||||
* de compatibilite : il ne change pas entre versions), donc bien plus robuste
|
||||
* qu'un match sur le texte du message (qui depend de la langue). La table
|
||||
* associe un code -> une cle i18n ; `resolveViolationMessage` l'applique.
|
||||
*
|
||||
* Limite a connaitre : le code de type-error est GENERIQUE (toute valeur de
|
||||
* mauvais type). Dans nos formulaires, seul un champ date saisi en texte libre
|
||||
* (MalioDate, qui forwarde la saisie brute invalide) le declenche, d'ou le
|
||||
* libelle « Date invalide ». Si un autre champ typé en saisie libre apparait,
|
||||
* affiner la resolution via `propertyPath` plutot que par code seul.
|
||||
*/
|
||||
export const VIOLATION_MESSAGE_I18N: Record<string, string> = {
|
||||
// Symfony `Constraints\Type::INVALID_TYPE_ERROR` — valeur de mauvais type.
|
||||
'ba785a8c-82cb-4283-967c-3cf342181b40': 'errors.validation.invalidDate',
|
||||
}
|
||||
|
||||
/**
|
||||
* Resout le message a afficher pour une violation : si son `code` est surcharge
|
||||
* par `VIOLATION_MESSAGE_I18N`, renvoie la traduction de la cle associee ;
|
||||
* sinon, le message back tel quel (cas nominal). `t` est passe par l'appelant
|
||||
* (les utils sont purs, sans acces a useI18n).
|
||||
*/
|
||||
export function resolveViolationMessage(v: ApiViolation, t: (key: string) => string): string {
|
||||
const i18nKey = VIOLATION_MESSAGE_I18N[v.code]
|
||||
return i18nKey ? t(i18nKey) : v.message
|
||||
}
|
||||
|
||||
/**
|
||||
* Extrait un message d'erreur lisible depuis un payload Hydra / JSON
|
||||
* d'erreur API Platform. Essaie les champs courants dans l'ordre :
|
||||
|
||||
@@ -249,6 +249,14 @@ sync-permissions:
|
||||
seed-rbac:
|
||||
$(SYMFONY_CONSOLE) --no-interaction app:seed-rbac
|
||||
|
||||
# Synchronise le referentiel des transporteurs QUALIMAT (ERP-39) : upsert sur
|
||||
# le SIRET + soft-delete des absents + journal. Idempotent (refresh complet),
|
||||
# prevu pour un cron quotidien.
|
||||
# Options : --dry-run (analyse sans ecriture), --file=<chemin.json> (source
|
||||
# locale au lieu de l'API), --ppp=<n> (taille de page API, defaut 10000).
|
||||
qualimat-sync:
|
||||
$(SYMFONY_CONSOLE) --no-interaction app:qualimat:sync
|
||||
|
||||
# Attention, supprime votre bdd local
|
||||
db-reset:
|
||||
$(DOCKER_COMPOSE) down -v
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* ERP-116 — Referentiel Pays (Country), 1re iteration : creation de la table
|
||||
* `country` + seed des 7 pays (France, Allemagne, Belgique, Espagne, Italie,
|
||||
* Royaume-Uni, Suisse). Devient la source unique du select pays, en
|
||||
* remplacement de la liste codee en dur cote front.
|
||||
*
|
||||
* Perimetre minimal voulu : code ISO 3166-1 alpha-2 + libelle FR + ordre
|
||||
* d'affichage UNIQUEMENT. Aucune longueur bancaire/fiscale (numero de compte,
|
||||
* IBAN, TVA, BIC, SIREN) a ce stade — iteration ulterieure du meme ticket.
|
||||
*
|
||||
* Pas de FK posee sur les adresses (client_address.country / supplier_address)
|
||||
* a cette etape : ces colonnes restent des chaines libres (« France »...), donc
|
||||
* aucune migration de donnees ni rupture de l'existant.
|
||||
*
|
||||
* Namespace racine `DoctrineMigrations` (regle ABSOLUE Starseed n°11) comme les
|
||||
* migrations M1/M2 du module Commercial : pas de migrations_path modulaire
|
||||
* configure pour Commercial, et le tri par timestamp reste garanti.
|
||||
*
|
||||
* Seed idempotent `ON CONFLICT (code) DO NOTHING` : la table peut deja porter
|
||||
* des donnees en prod lors d'un rejeu. Chaque colonne porte un `COMMENT ON
|
||||
* COLUMN` (regle ABSOLUE n°12, garde-fou ColumnsHaveSqlCommentTest) ; la table
|
||||
* est aussi mirroree dans ColumnCommentsCatalog pour survivre au
|
||||
* `schema:update --force` du setup de test.
|
||||
*/
|
||||
final class Version20260609100000 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'ERP-116 : table country (referentiel pays) + seed des 7 pays.';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql(<<<'SQL'
|
||||
CREATE TABLE country (
|
||||
id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
|
||||
code VARCHAR(2) NOT NULL,
|
||||
name VARCHAR(80) NOT NULL,
|
||||
position INT DEFAULT 0 NOT NULL,
|
||||
PRIMARY KEY (id)
|
||||
)
|
||||
SQL);
|
||||
$this->addSql('CREATE UNIQUE INDEX uq_country_code ON country (code)');
|
||||
|
||||
$this->comment('country', '_table', 'Referentiel des pays selectionnables dans les adresses (clients/fournisseurs). Perimetre minimal : code ISO + libelle + ordre (pas de longueurs bancaires/fiscales).');
|
||||
$this->comment('country', 'id', 'Identifiant interne auto-incremente.');
|
||||
$this->comment('country', 'code', 'Code pays ISO 3166-1 alpha-2 (2 lettres MAJUSCULES, ex: FR) — unique (uq_country_code), fige a la creation.');
|
||||
$this->comment('country', 'name', 'Libelle FR du pays (≤ 80 caracteres) — valeur stockee telle quelle dans les adresses (country en chaine libre a ce stade).');
|
||||
$this->comment('country', 'position', 'Ordre d affichage croissant dans le selecteur pays (tri position ASC puis name ASC ; France en tete).');
|
||||
|
||||
// Seed initial. France en tete (position 10) puis ordre alphabetique.
|
||||
// Table fraichement creee, mais ON CONFLICT pour rejouabilite en prod.
|
||||
$this->addSql(<<<'SQL'
|
||||
INSERT INTO country (code, name, position) VALUES
|
||||
('FR', 'France', 10),
|
||||
('DE', 'Allemagne', 20),
|
||||
('BE', 'Belgique', 30),
|
||||
('ES', 'Espagne', 40),
|
||||
('IT', 'Italie', 50),
|
||||
('GB', 'Royaume-Uni', 60),
|
||||
('CH', 'Suisse', 70)
|
||||
ON CONFLICT (code) DO NOTHING
|
||||
SQL);
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('DROP TABLE country');
|
||||
}
|
||||
|
||||
/**
|
||||
* Pose un `COMMENT ON TABLE` (colonne speciale `_table`) ou
|
||||
* `COMMENT ON COLUMN`. Quoting defensif des identifiants + delimiteur $_$
|
||||
* pour ne pas casser sur les apostrophes des descriptions.
|
||||
*/
|
||||
private function comment(string $table, string $column, string $description): void
|
||||
{
|
||||
$quotedTable = '"'.str_replace('"', '""', $table).'"';
|
||||
|
||||
if ('_table' === $column) {
|
||||
$this->addSql(sprintf('COMMENT ON TABLE %s IS $_$%s$_$', $quotedTable, $description));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->addSql(sprintf(
|
||||
'COMMENT ON COLUMN %s.%s IS $_$%s$_$',
|
||||
$quotedTable,
|
||||
'"'.str_replace('"', '""', $column).'"',
|
||||
$description,
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* ERP-39 (Module Transport) : referentiel des transporteurs agrees QUALIMAT.
|
||||
*
|
||||
* Tables alimentees par la commande de synchronisation `app:qualimat:sync`
|
||||
* (upsert sur le SIRET + soft-delete des absents + journal). Aucune FK
|
||||
* cross-module (referentiel autonome) : migration posee au namespace racine
|
||||
* `DoctrineMigrations`, comme les autres migrations de creation de tables.
|
||||
*/
|
||||
final class Version20260612150000 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'ERP-39 : tables qualimat_carrier + qualimat_sync_log (referentiel transporteurs QUALIMAT, synchro console).';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql(<<<'SQL'
|
||||
CREATE TABLE qualimat_carrier (
|
||||
id BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
|
||||
siret VARCHAR(20) NOT NULL,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
address VARCHAR(255) DEFAULT NULL,
|
||||
postal_code VARCHAR(10) DEFAULT NULL,
|
||||
city VARCHAR(255) DEFAULT NULL,
|
||||
phone VARCHAR(32) DEFAULT NULL,
|
||||
department VARCHAR(64) DEFAULT NULL,
|
||||
status VARCHAR(32) NOT NULL,
|
||||
validity_date DATE DEFAULT NULL,
|
||||
is_active BOOLEAN DEFAULT TRUE NOT NULL,
|
||||
last_synced_at TIMESTAMP(6) WITHOUT TIME ZONE NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uq_qualimat_carrier_siret UNIQUE (siret)
|
||||
)
|
||||
SQL);
|
||||
$this->addSql('CREATE INDEX idx_qualimat_carrier_active ON qualimat_carrier (is_active)');
|
||||
|
||||
$this->comment('qualimat_carrier', '_table', "Referentiel des transporteurs agrees QUALIMAT, synchronise quotidiennement depuis l'API qualimat.org (type=operateur_transport).");
|
||||
$this->comment('qualimat_carrier', 'id', 'Cle technique auto-incrementee.');
|
||||
$this->comment('qualimat_carrier', 'siret', 'SIRET normalise (chiffres sans espaces). Cle naturelle de synchro (unique). Source parfois incomplete (longueur variable), non contrainte a 14.');
|
||||
$this->comment('qualimat_carrier', 'name', 'Raison sociale du transporteur (champs Nom = Societe de la source, identiques).');
|
||||
$this->comment('qualimat_carrier', 'address', 'Adresse postale (voie). Nullable.');
|
||||
$this->comment('qualimat_carrier', 'postal_code', 'Code postal. Nullable.');
|
||||
$this->comment('qualimat_carrier', 'city', 'Ville. Nullable.');
|
||||
$this->comment('qualimat_carrier', 'phone', 'Telephone au format source "indicatif|numero" (ex: +33|0608890316). Nullable.');
|
||||
$this->comment('qualimat_carrier', 'department', 'Departement au format source "code - libelle" (ex: 65 - Hautes-Pyrenees). Nullable.');
|
||||
$this->comment('qualimat_carrier', 'status', "Statut d'agrement QUALIMAT (valeurs connues : Audite, Valide, Suspendu). Valeur brute de la source, non contrainte.");
|
||||
$this->comment('qualimat_carrier', 'validity_date', 'Date de fin de validite de la certification (convertie depuis dd/mm/yyyy). Nullable.');
|
||||
$this->comment('qualimat_carrier', 'is_active', 'Faux = transporteur absent du dernier import (soft-delete). Toute ligne non revue par le dernier run passe a FALSE.');
|
||||
$this->comment('qualimat_carrier', 'last_synced_at', 'Horodatage du run de synchro ayant vu cette ligne en dernier (soft-delete : last_synced_at < run courant).');
|
||||
|
||||
$this->addSql(<<<'SQL'
|
||||
CREATE TABLE qualimat_sync_log (
|
||||
id BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
|
||||
fetched_at TIMESTAMP(6) WITHOUT TIME ZONE NOT NULL,
|
||||
rows_total INT NOT NULL,
|
||||
rows_upserted INT NOT NULL,
|
||||
rows_skipped INT NOT NULL,
|
||||
rows_deactivated INT NOT NULL,
|
||||
created_at TIMESTAMP(6) WITHOUT TIME ZONE DEFAULT NOW() NOT NULL,
|
||||
PRIMARY KEY (id)
|
||||
)
|
||||
SQL);
|
||||
|
||||
$this->comment('qualimat_sync_log', '_table', 'Journal des synchronisations QUALIMAT (une ligne par run de la commande app:qualimat:sync).');
|
||||
$this->comment('qualimat_sync_log', 'id', 'Cle technique auto-incrementee.');
|
||||
$this->comment('qualimat_sync_log', 'fetched_at', "Horodatage de l'appel a l'API source (= run de synchro).");
|
||||
$this->comment('qualimat_sync_log', 'rows_total', "Nombre d'items renvoyes par l'API.");
|
||||
$this->comment('qualimat_sync_log', 'rows_upserted', 'Nombre de transporteurs inseres ou mis a jour.');
|
||||
$this->comment('qualimat_sync_log', 'rows_skipped', "Nombre d'items ignores (sans SIRET exploitable).");
|
||||
$this->comment('qualimat_sync_log', 'rows_deactivated', 'Nombre de transporteurs passes a is_active=false (absents de cet import).');
|
||||
$this->comment('qualimat_sync_log', 'created_at', 'Horodatage de fin du run (insertion du journal).');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('DROP TABLE IF EXISTS qualimat_sync_log');
|
||||
$this->addSql('DROP TABLE IF EXISTS qualimat_carrier');
|
||||
}
|
||||
|
||||
/**
|
||||
* Pose un COMMENT ON TABLE/COLUMN en dollar-quoting Postgres ($_$...$_$)
|
||||
* pour eviter tout echappement d'apostrophes dans les descriptions.
|
||||
*/
|
||||
private function comment(string $table, string $column, string $description): void
|
||||
{
|
||||
$quotedTable = '"'.str_replace('"', '""', $table).'"';
|
||||
|
||||
if ('_table' === $column) {
|
||||
$this->addSql(sprintf('COMMENT ON TABLE %s IS $_$%s$_$', $quotedTable, $description));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->addSql(sprintf(
|
||||
'COMMENT ON COLUMN %s.%s IS $_$%s$_$',
|
||||
$quotedTable,
|
||||
'"'.str_replace('"', '""', $column).'"',
|
||||
$description,
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -22,8 +22,10 @@ use DateTimeImmutable;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Serializer\Attribute\Context;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
use Symfony\Component\Serializer\Attribute\SerializedName;
|
||||
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
|
||||
@@ -94,6 +96,12 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
security: "is_granted('commercial.clients.manage')",
|
||||
normalizationContext: ['groups' => ['client:read', 'default:read', 'category:read', 'site:read']],
|
||||
denormalizationContext: ['groups' => ['client:write:main']],
|
||||
// Une valeur de mauvais type (ex. date non parsable sur foundedAt)
|
||||
// doit produire un 422 porte sur le champ (violations[].propertyPath,
|
||||
// mappable inline par useFormErrors) plutot qu'un 400 generique non
|
||||
// exploitable. Le front (MalioDate, MUI-44) forwarde la saisie brute
|
||||
// invalide : le back reste la couche autoritaire du format (ERP-101).
|
||||
collectDenormalizationErrors: true,
|
||||
processor: ClientProcessor::class,
|
||||
),
|
||||
new Patch(
|
||||
@@ -117,6 +125,10 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
'client:write:accounting',
|
||||
'client:write:archive',
|
||||
]],
|
||||
// Cf. Post : date non parsable (foundedAt) -> 422 porte sur le champ
|
||||
// au lieu d'un 400 generique. Indispensable au mapping inline du
|
||||
// front (MalioDate MUI-44 forwarde la saisie brute invalide).
|
||||
collectDenormalizationErrors: true,
|
||||
provider: ClientProvider::class,
|
||||
processor: ClientProcessor::class,
|
||||
),
|
||||
@@ -206,6 +218,13 @@ class Client implements TimestampableInterface, BlamableInterface
|
||||
|
||||
#[ORM\Column(type: 'date_immutable', nullable: true)]
|
||||
#[Groups(['client:read', 'client:write:information'])]
|
||||
// Format d'ENTREE strict ISO `Y-m-d` (le `!` remet l'heure a 00:00:00). Sans
|
||||
// ce format, PHP DateTime accepte des formes ambigues : « 12/25/2026 » (que
|
||||
// le front MalioDate juge invalide en JJ/MM/AAAA) serait sinon interprete en
|
||||
// M/J/AAAA -> 25 decembre 2026, et accepte a tort. Avec le format, toute
|
||||
// saisie brute non-ISO (forwardee par MalioDate sur date invalide) echoue la
|
||||
// denormalisation -> 422 sur foundedAt (cf. collectDenormalizationErrors).
|
||||
#[Context(denormalizationContext: [DateTimeNormalizer::FORMAT_KEY => '!Y-m-d'])]
|
||||
private ?DateTimeImmutable $foundedAt = null;
|
||||
|
||||
#[ORM\Column(nullable: true)]
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Domain\Entity;
|
||||
|
||||
use ApiPlatform\Metadata\ApiResource;
|
||||
use ApiPlatform\Metadata\Get;
|
||||
use ApiPlatform\Metadata\GetCollection;
|
||||
use App\Module\Commercial\Infrastructure\Doctrine\DoctrineCountryRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
|
||||
/**
|
||||
* Pays selectionnable dans les adresses (clients / fournisseurs) : referentiel
|
||||
* statique seede par la migration (France, Allemagne, Belgique, Espagne, Italie,
|
||||
* Royaume-Uni). Remplace la liste de pays jusqu'ici codee en dur cote front.
|
||||
*
|
||||
* Perimetre minimal (ticket ERP-116, 1re iteration) : code ISO + libelle + ordre
|
||||
* d'affichage uniquement. AUCUNE longueur bancaire/fiscale (numero de compte,
|
||||
* IBAN, TVA, BIC, SIREN) a ce stade — ces colonnes feront l'objet d'une iteration
|
||||
* ulterieure du meme ticket.
|
||||
*
|
||||
* Lecture seule : GetCollection + Get uniquement ; POST/PATCH/DELETE -> 405.
|
||||
* Permission alignee sur Bank (referentiel d'adresse partage clients/fournisseurs).
|
||||
* Pas de Timestampable/Blamable (referentiel statique whiteliste dans
|
||||
* EntitiesAreTimestampableBlamableTest::EXCLUDED, comme Bank).
|
||||
*/
|
||||
#[ApiResource(
|
||||
operations: [
|
||||
new GetCollection(
|
||||
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||
normalizationContext: ['groups' => ['country:read']],
|
||||
// Tri par defaut : position ASC (France en tete) puis name ASC.
|
||||
order: ['position' => 'ASC', 'name' => 'ASC'],
|
||||
// Toggle ?pagination=false pour alimenter le select (cf. Bank).
|
||||
paginationClientEnabled: true,
|
||||
),
|
||||
new Get(
|
||||
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||
normalizationContext: ['groups' => ['country:read']],
|
||||
),
|
||||
],
|
||||
security: "is_granted('commercial.clients.view') or is_granted('commercial.suppliers.view')",
|
||||
)]
|
||||
#[ORM\Entity(repositoryClass: DoctrineCountryRepository::class)]
|
||||
#[ORM\Table(name: 'country')]
|
||||
#[ORM\UniqueConstraint(name: 'uq_country_code', columns: ['code'])]
|
||||
class Country
|
||||
{
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column]
|
||||
#[Groups(['country:read'])]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(length: 2)]
|
||||
#[Groups(['country:read'])]
|
||||
private ?string $code = null;
|
||||
|
||||
#[ORM\Column(length: 80)]
|
||||
#[Groups(['country:read'])]
|
||||
private ?string $name = null;
|
||||
|
||||
#[ORM\Column(options: ['default' => 0])]
|
||||
#[Groups(['country:read'])]
|
||||
private int $position = 0;
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getCode(): ?string
|
||||
{
|
||||
return $this->code;
|
||||
}
|
||||
|
||||
public function setCode(string $code): static
|
||||
{
|
||||
$this->code = $code;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getName(): ?string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
public function setName(string $name): static
|
||||
{
|
||||
$this->name = $name;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPosition(): int
|
||||
{
|
||||
return $this->position;
|
||||
}
|
||||
|
||||
public function setPosition(int $position): static
|
||||
{
|
||||
$this->position = $position;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -22,8 +22,10 @@ use DateTimeImmutable;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Serializer\Attribute\Context;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
use Symfony\Component\Serializer\Attribute\SerializedName;
|
||||
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
|
||||
@@ -94,6 +96,12 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
security: "is_granted('commercial.suppliers.manage')",
|
||||
normalizationContext: ['groups' => ['supplier:read', 'default:read', 'category:read', 'site:read']],
|
||||
denormalizationContext: ['groups' => ['supplier:write:main']],
|
||||
// Une valeur de mauvais type (ex. date non parsable sur foundedAt)
|
||||
// doit produire un 422 porte sur le champ (violations[].propertyPath,
|
||||
// mappable inline par useFormErrors) plutot qu'un 400 generique. Le
|
||||
// front (MalioDate, MUI-44) forwarde la saisie brute invalide : le
|
||||
// back reste la couche autoritaire du format (ERP-101). Cf. Client.
|
||||
collectDenormalizationErrors: true,
|
||||
processor: SupplierProcessor::class,
|
||||
),
|
||||
new Patch(
|
||||
@@ -113,6 +121,10 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
'supplier:write:accounting',
|
||||
'supplier:write:archive',
|
||||
]],
|
||||
// Cf. Post : date non parsable (foundedAt) -> 422 porte sur le champ
|
||||
// au lieu d'un 400 generique. Indispensable au mapping inline du
|
||||
// front (MalioDate MUI-44 forwarde la saisie brute invalide).
|
||||
collectDenormalizationErrors: true,
|
||||
provider: SupplierProvider::class,
|
||||
processor: SupplierProcessor::class,
|
||||
),
|
||||
@@ -187,6 +199,11 @@ class Supplier implements TimestampableInterface, BlamableInterface
|
||||
|
||||
#[ORM\Column(type: 'date_immutable', nullable: true)]
|
||||
#[Groups(['supplier:read', 'supplier:write:information'])]
|
||||
// Format d'ENTREE strict ISO `Y-m-d` : sans lui, PHP DateTime accepte des
|
||||
// formes ambigues (« 12/25/2026 », jugee invalide par MalioDate en JJ/MM/AAAA,
|
||||
// serait lue en M/J -> 25 decembre et acceptee a tort). Avec le format, toute
|
||||
// saisie brute non-ISO echoue -> 422 sur foundedAt. Cf. Client.
|
||||
#[Context(denormalizationContext: [DateTimeNormalizer::FORMAT_KEY => '!Y-m-d'])]
|
||||
private ?DateTimeImmutable $foundedAt = null;
|
||||
|
||||
#[ORM\Column(nullable: true)]
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Domain\Repository;
|
||||
|
||||
use App\Module\Commercial\Domain\Entity\Country;
|
||||
|
||||
interface CountryRepositoryInterface
|
||||
{
|
||||
public function findById(int $id): ?Country;
|
||||
|
||||
/**
|
||||
* Retourne tous les pays tries position ASC puis name ASC.
|
||||
*
|
||||
* @return list<Country>
|
||||
*/
|
||||
public function findAllOrdered(): array;
|
||||
}
|
||||
+44
-3
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace App\Module\Commercial\Infrastructure\DataFixtures;
|
||||
|
||||
use App\Module\Commercial\Domain\Entity\Bank;
|
||||
use App\Module\Commercial\Domain\Entity\Country;
|
||||
use App\Module\Commercial\Domain\Entity\PaymentDelay;
|
||||
use App\Module\Commercial\Domain\Entity\PaymentType;
|
||||
use App\Module\Commercial\Domain\Entity\TvaMode;
|
||||
@@ -14,10 +15,11 @@ use Doctrine\Persistence\ObjectManager;
|
||||
/**
|
||||
* Fixtures du module Commercial : re-seed des 4 referentiels comptables
|
||||
* (tva_mode, payment_delay, payment_type, bank) seedes par la migration M1
|
||||
* (Version20260601000000).
|
||||
* (Version20260601000000) + du referentiel pays (country) seede par la
|
||||
* migration ERP-116 (Version20260609100000).
|
||||
*
|
||||
* Pourquoi cette fixture EN PLUS du seed de la migration : depuis ERP-54 ces
|
||||
* 4 tables sont des entites managees par l'ORM, donc le purger Doctrine les
|
||||
* Pourquoi cette fixture EN PLUS du seed de la migration : ces tables sont des
|
||||
* entites managees par l'ORM, donc le purger Doctrine les
|
||||
* vide avant chaque `doctrine:fixtures:load`. Sans cette fixture, les
|
||||
* referentiels seedes par la migration disparaitraient apres `make db-reset`
|
||||
* (0 ligne en dev/test) — cassant les FK Client -> referentiels et les tests
|
||||
@@ -59,15 +61,54 @@ class CommercialReferentialFixtures extends Fixture
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* Referentiel pays (ERP-116) : code ISO alpha-2 => [name, position].
|
||||
* Doit rester aligne sur le seed de la migration Version20260609100000.
|
||||
* Traite a part car Country porte `name` (et non `label`).
|
||||
*
|
||||
* @var array<string, array{string, int}>
|
||||
*/
|
||||
private const COUNTRIES = [
|
||||
'FR' => ['France', 10],
|
||||
'DE' => ['Allemagne', 20],
|
||||
'BE' => ['Belgique', 30],
|
||||
'ES' => ['Espagne', 40],
|
||||
'IT' => ['Italie', 50],
|
||||
'GB' => ['Royaume-Uni', 60],
|
||||
'CH' => ['Suisse', 70],
|
||||
];
|
||||
|
||||
public function load(ObjectManager $manager): void
|
||||
{
|
||||
foreach (self::REFERENTIALS as $entityClass => $rows) {
|
||||
$this->seedReferential($manager, $entityClass, $rows);
|
||||
}
|
||||
|
||||
$this->seedCountries($manager);
|
||||
|
||||
$manager->flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Upsert idempotent du referentiel pays (lookup par code). Distinct de
|
||||
* seedReferential car Country utilise setName au lieu de setLabel.
|
||||
*/
|
||||
private function seedCountries(ObjectManager $manager): void
|
||||
{
|
||||
$existingByCode = [];
|
||||
foreach ($manager->getRepository(Country::class)->findAll() as $country) {
|
||||
$existingByCode[$country->getCode()] = $country;
|
||||
}
|
||||
|
||||
foreach (self::COUNTRIES as $code => [$name, $position]) {
|
||||
$country = $existingByCode[$code] ?? new Country();
|
||||
$country->setCode($code);
|
||||
$country->setName($name);
|
||||
$country->setPosition($position);
|
||||
$manager->persist($country);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upsert idempotent d'un referentiel : indexe l'existant par code puis
|
||||
* cree/met a jour chaque entree. Les 4 entites partagent le meme contrat
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Commercial\Infrastructure\Doctrine;
|
||||
|
||||
use App\Module\Commercial\Domain\Entity\Country;
|
||||
use App\Module\Commercial\Domain\Repository\CountryRepositoryInterface;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/**
|
||||
* @extends ServiceEntityRepository<Country>
|
||||
*/
|
||||
class DoctrineCountryRepository extends ServiceEntityRepository implements CountryRepositoryInterface
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, Country::class);
|
||||
}
|
||||
|
||||
public function findById(int $id): ?Country
|
||||
{
|
||||
return $this->find($id);
|
||||
}
|
||||
|
||||
public function findAllOrdered(): array
|
||||
{
|
||||
return $this->createQueryBuilder('c')
|
||||
->orderBy('c.position', 'ASC')
|
||||
->addOrderBy('c.name', 'ASC')
|
||||
->getQuery()
|
||||
->getResult()
|
||||
;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Transport\Application\Qualimat;
|
||||
|
||||
/**
|
||||
* Mapping pur d'un item brut de l'API QUALIMAT vers une ligne normalisee
|
||||
* prete a l'upsert dans `qualimat_carrier`. Sans dependance (testable en
|
||||
* isolation). Voir ERP-39 § 2 pour les pieges qualite de la source.
|
||||
*/
|
||||
final class QualimatRowMapper
|
||||
{
|
||||
/**
|
||||
* Mappe un lot d'items. Les items sans SIRET exploitable sont ignores et
|
||||
* comptes a part (cf. `rows_skipped` du journal).
|
||||
*
|
||||
* @param array<int, array<string, mixed>> $items
|
||||
*
|
||||
* @return array{rows: list<array<string, mixed>>, skipped: int}
|
||||
*/
|
||||
public static function mapMany(array $items): array
|
||||
{
|
||||
$rows = [];
|
||||
$skipped = 0;
|
||||
|
||||
foreach ($items as $item) {
|
||||
$row = self::mapOne($item);
|
||||
|
||||
if (null === $row) {
|
||||
++$skipped;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$rows[] = $row;
|
||||
}
|
||||
|
||||
return ['rows' => $rows, 'skipped' => $skipped];
|
||||
}
|
||||
|
||||
/**
|
||||
* Mappe un item unique. Retourne null si le SIRET est absent ou vide
|
||||
* (ligne inexploitable : pas de cle naturelle pour l'upsert).
|
||||
*
|
||||
* @param array<string, mixed> $item
|
||||
*
|
||||
* @return null|array<string, mixed>
|
||||
*/
|
||||
public static function mapOne(array $item): ?array
|
||||
{
|
||||
$siret = self::normalizeSiret(self::str($item['Siret'] ?? null));
|
||||
|
||||
if (null === $siret) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'siret' => $siret,
|
||||
// Nom et Societe sont identiques a la source : une seule colonne.
|
||||
'name' => self::str($item['Nom'] ?? null) ?? '',
|
||||
'address' => self::str($item['Adresse'] ?? null),
|
||||
'postal_code' => self::str($item['CodePostal'] ?? null),
|
||||
'city' => self::str($item['Ville'] ?? null),
|
||||
'phone' => self::str($item['Telephone_1'] ?? null),
|
||||
'department' => self::str($item['Departement'] ?? null),
|
||||
// Statut conserve brut (feed externe, valeurs non contraintes).
|
||||
'status' => self::str($item['Statut'] ?? null) ?? '',
|
||||
'validity_date' => self::parseDate(self::str($item['Validite'] ?? null)),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise un SIRET : ne conserve que les chiffres. Null si vide.
|
||||
* La source est "sale" (longueurs variables 7 a 14) : aucune contrainte
|
||||
* de longueur, on stocke les chiffres tels quels.
|
||||
*/
|
||||
public static function normalizeSiret(?string $raw): ?string
|
||||
{
|
||||
if (null === $raw) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$digits = preg_replace('/\D+/', '', $raw) ?? '';
|
||||
|
||||
return '' === $digits ? null : $digits;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convertit une date "dd/mm/yyyy" en "yyyy-mm-dd". Null si le format ne
|
||||
* correspond pas ou si la date n'est pas un jour calendaire valide
|
||||
* (garde-fou : evite un INSERT en erreur sur une date impossible).
|
||||
*/
|
||||
public static function parseDate(?string $raw): ?string
|
||||
{
|
||||
if (null === $raw || !preg_match('#^(\d{2})/(\d{2})/(\d{4})$#', $raw, $m)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$day = (int) $m[1];
|
||||
$month = (int) $m[2];
|
||||
$year = (int) $m[3];
|
||||
|
||||
if (!checkdate($month, $day, $year)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return sprintf('%04d-%02d-%02d', $year, $month, $day);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trim d'une valeur scalaire ; null si la chaine resultante est vide.
|
||||
*/
|
||||
private static function str(mixed $value): ?string
|
||||
{
|
||||
if (null === $value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$trimmed = trim((string) $value);
|
||||
|
||||
return '' === $trimmed ? null : $trimmed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Transport\Infrastructure\Console;
|
||||
|
||||
use App\Module\Transport\Application\Qualimat\QualimatRowMapper;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\DBAL\Connection;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Console\Style\SymfonyStyle;
|
||||
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
use Throwable;
|
||||
|
||||
use function array_slice;
|
||||
use function count;
|
||||
use function is_array;
|
||||
|
||||
use const JSON_THROW_ON_ERROR;
|
||||
|
||||
/**
|
||||
* ERP-39 : synchronise le referentiel des transporteurs QUALIMAT.
|
||||
*
|
||||
* Recupere la liste des operateurs de transport depuis l'API publique (ou un
|
||||
* fichier local), normalise chaque ligne et synchronise `qualimat_carrier` de
|
||||
* facon transactionnelle : upsert sur le SIRET, soft-delete des absents,
|
||||
* journal dans `qualimat_sync_log`. Idempotente (refresh complet) : prevue
|
||||
* pour un cron quotidien.
|
||||
*/
|
||||
#[AsCommand(
|
||||
name: 'app:qualimat:sync',
|
||||
description: 'Synchronise le referentiel des transporteurs QUALIMAT (upsert + soft-delete + journal).',
|
||||
)]
|
||||
final class SyncQualimatCommand extends Command
|
||||
{
|
||||
private const string API_URL = 'https://www.qualimat.org/wp-json/qualimat/v1/getOperateurs';
|
||||
private const int DEFAULT_PPP = 10000;
|
||||
|
||||
public function __construct(
|
||||
private readonly Connection $connection,
|
||||
private readonly HttpClientInterface $httpClient,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
protected function configure(): void
|
||||
{
|
||||
$this
|
||||
->addOption('file', null, InputOption::VALUE_REQUIRED, "Chemin d'un JSON local (court-circuite l'appel HTTP, utile pour tests/rejeu).")
|
||||
->addOption('ppp', null, InputOption::VALUE_REQUIRED, "Taille de page demandee a l'API.", (string) self::DEFAULT_PPP)
|
||||
->addOption('dry-run', null, InputOption::VALUE_NONE, 'Analyse sans ecriture en base.')
|
||||
;
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$io = new SymfonyStyle($input, $output);
|
||||
$ppp = max(1, (int) $input->getOption('ppp'));
|
||||
$dryRun = (bool) $input->getOption('dry-run');
|
||||
$file = $input->getOption('file');
|
||||
|
||||
// 1. Recuperation des items (fichier local ou API).
|
||||
try {
|
||||
$items = null !== $file ? $this->readLocal((string) $file) : $this->fetchRemote($ppp);
|
||||
} catch (Throwable $e) {
|
||||
$io->error('Recuperation impossible : '.$e->getMessage());
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$total = count($items);
|
||||
$io->section(sprintf('QUALIMAT — %d items recus', $total));
|
||||
|
||||
// Garde-fou troncature : un retour egal a ppp signale un dataset coupe.
|
||||
if (null === $file && $total === $ppp) {
|
||||
$io->warning(sprintf("Le nombre d'items recus (%d) egale --ppp : resultat potentiellement tronque, augmente --ppp.", $ppp));
|
||||
}
|
||||
|
||||
// 2. Mapping / normalisation (les items sans SIRET sont ignores).
|
||||
['rows' => $rows, 'skipped' => $skipped] = QualimatRowMapper::mapMany($items);
|
||||
$io->writeln(sprintf('%d lignes exploitables, %d ignorees (sans SIRET).', count($rows), $skipped));
|
||||
|
||||
if ($dryRun) {
|
||||
$this->renderPreview($io, $rows);
|
||||
$io->note(sprintf('Dry-run : aucune ecriture. (%d lignes au total)', count($rows)));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
// 3. Sync transactionnelle : upsert -> soft-delete -> journal.
|
||||
$run = new DateTimeImmutable()->format('Y-m-d H:i:s.u');
|
||||
|
||||
$this->connection->beginTransaction();
|
||||
|
||||
try {
|
||||
$upserted = $this->upsertAll($rows, $run);
|
||||
$deactivated = $this->deactivateMissing($run);
|
||||
$this->log($run, $total, $upserted, $skipped, $deactivated);
|
||||
$this->connection->commit();
|
||||
} catch (Throwable $e) {
|
||||
$this->connection->rollBack();
|
||||
$io->error('Sync annulee (rollback) : '.$e->getMessage());
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$io->success(sprintf('%d upsert, %d ignore(s), %d desactive(s).', $upserted, $skipped, $deactivated));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejoue l'appel GET de l'API QUALIMAT et retourne le tableau d'items.
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
private function fetchRemote(int $ppp): array
|
||||
{
|
||||
$response = $this->httpClient->request('GET', self::API_URL, [
|
||||
'query' => ['type' => 'operateur_transport', 'ppp' => $ppp],
|
||||
'timeout' => 60,
|
||||
]);
|
||||
|
||||
// toArray() leve une exception sur un statut non-2xx ou un corps non-JSON.
|
||||
$data = $response->toArray();
|
||||
|
||||
return array_is_list($data) ? $data : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Lit un export JSON local (tableau d'objets).
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
private function readLocal(string $path): array
|
||||
{
|
||||
$raw = @file_get_contents($path);
|
||||
|
||||
if (false === $raw) {
|
||||
throw new RuntimeException(sprintf('Fichier illisible : %s', $path));
|
||||
}
|
||||
|
||||
$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
|
||||
|
||||
if (!is_array($data) || !array_is_list($data)) {
|
||||
throw new RuntimeException("Le JSON doit etre un tableau d'objets.");
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Upsert de toutes les lignes valides (cle naturelle = siret). Marque
|
||||
* is_active=TRUE et tamponne last_synced_at avec le run courant.
|
||||
*
|
||||
* @param list<array<string, mixed>> $rows
|
||||
*/
|
||||
private function upsertAll(array $rows, string $run): int
|
||||
{
|
||||
$sql = <<<'SQL'
|
||||
INSERT INTO qualimat_carrier
|
||||
(siret, name, address, postal_code, city, phone, department, status, validity_date, is_active, last_synced_at)
|
||||
VALUES
|
||||
(:siret, :name, :address, :postal_code, :city, :phone, :department, :status, :validity_date, TRUE, :run)
|
||||
ON CONFLICT (siret) DO UPDATE SET
|
||||
name = EXCLUDED.name,
|
||||
address = EXCLUDED.address,
|
||||
postal_code = EXCLUDED.postal_code,
|
||||
city = EXCLUDED.city,
|
||||
phone = EXCLUDED.phone,
|
||||
department = EXCLUDED.department,
|
||||
status = EXCLUDED.status,
|
||||
validity_date = EXCLUDED.validity_date,
|
||||
is_active = TRUE,
|
||||
last_synced_at = EXCLUDED.last_synced_at
|
||||
SQL;
|
||||
|
||||
$count = 0;
|
||||
|
||||
foreach ($rows as $r) {
|
||||
$this->connection->executeStatement($sql, [
|
||||
'siret' => $r['siret'],
|
||||
'name' => $r['name'],
|
||||
'address' => $r['address'],
|
||||
'postal_code' => $r['postal_code'],
|
||||
'city' => $r['city'],
|
||||
'phone' => $r['phone'],
|
||||
'department' => $r['department'],
|
||||
'status' => $r['status'],
|
||||
'validity_date' => $r['validity_date'],
|
||||
'run' => $run,
|
||||
]);
|
||||
++$count;
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Soft-delete : toute ligne active non revue par ce run (tampon anterieur)
|
||||
* passe a is_active=false.
|
||||
*/
|
||||
private function deactivateMissing(string $run): int
|
||||
{
|
||||
return (int) $this->connection->executeStatement(
|
||||
'UPDATE qualimat_carrier SET is_active = FALSE WHERE is_active = TRUE AND last_synced_at < :run',
|
||||
['run' => $run],
|
||||
);
|
||||
}
|
||||
|
||||
private function log(string $run, int $total, int $upserted, int $skipped, int $deactivated): void
|
||||
{
|
||||
$this->connection->executeStatement(
|
||||
<<<'SQL'
|
||||
INSERT INTO qualimat_sync_log (fetched_at, rows_total, rows_upserted, rows_skipped, rows_deactivated)
|
||||
VALUES (:run, :total, :upserted, :skipped, :deactivated)
|
||||
SQL,
|
||||
[
|
||||
'run' => $run,
|
||||
'total' => $total,
|
||||
'upserted' => $upserted,
|
||||
'skipped' => $skipped,
|
||||
'deactivated' => $deactivated,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string, mixed>> $rows
|
||||
*/
|
||||
private function renderPreview(SymfonyStyle $io, array $rows): void
|
||||
{
|
||||
$io->table(
|
||||
['SIRET', 'Nom', 'CP', 'Ville', 'Statut', 'Validite'],
|
||||
array_map(static fn (array $r): array => [
|
||||
(string) $r['siret'],
|
||||
mb_strimwidth((string) $r['name'], 0, 40, '…'),
|
||||
(string) ($r['postal_code'] ?? ''),
|
||||
mb_strimwidth((string) ($r['city'] ?? ''), 0, 25, '…'),
|
||||
(string) $r['status'],
|
||||
(string) ($r['validity_date'] ?? ''),
|
||||
], array_slice($rows, 0, 15)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Module\Transport;
|
||||
|
||||
final class TransportModule
|
||||
{
|
||||
public const string ID = 'transport';
|
||||
public const string LABEL = 'Transport';
|
||||
public const bool REQUIRED = false;
|
||||
|
||||
/**
|
||||
* Liste declarative des permissions RBAC exposees par le module Transport.
|
||||
*
|
||||
* Vide a ce stade : le module ne porte que des referentiels externes
|
||||
* synchronises par commandes console (codes IDTF - ERP-149, transporteurs
|
||||
* QUALIMAT - ERP-39), sans ecran ni action protegee. Les permissions seront
|
||||
* ajoutees quand une page de consultation sera exposee.
|
||||
*
|
||||
* Consommee par `app:sync-permissions` (un tableau vide est valide).
|
||||
*
|
||||
* @return array<int, array{code: string, label: string}>
|
||||
*/
|
||||
public static function permissions(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -170,6 +170,14 @@ final class ColumnCommentsCatalog
|
||||
'position' => 'Ordre d affichage croissant dans les selecteurs (tri position ASC puis label ASC).',
|
||||
],
|
||||
|
||||
'country' => [
|
||||
'_table' => 'Referentiel des pays selectionnables dans les adresses (clients/fournisseurs). Perimetre minimal : code ISO + libelle + ordre (pas de longueurs bancaires/fiscales).',
|
||||
'id' => 'Identifiant interne auto-incremente.',
|
||||
'code' => 'Code pays ISO 3166-1 alpha-2 (2 lettres MAJUSCULES, ex: FR) — unique (uq_country_code), fige a la creation.',
|
||||
'name' => 'Libelle FR du pays (≤ 80 caracteres) — valeur stockee telle quelle dans les adresses (country en chaine libre a ce stade).',
|
||||
'position' => 'Ordre d affichage croissant dans le selecteur pays (tri position ASC puis name ASC ; France en tete).',
|
||||
],
|
||||
|
||||
'client' => [
|
||||
'_table' => 'Repertoire clients (M1 Commercial) — entites archivables (is_archived) et soft-deletables (deleted_at, HP M2).',
|
||||
'id' => 'Identifiant interne auto-incremente.',
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace App\Tests\Architecture;
|
||||
|
||||
use App\Module\Catalog\Domain\Entity\CategoryType;
|
||||
use App\Module\Commercial\Domain\Entity\Bank;
|
||||
use App\Module\Commercial\Domain\Entity\Country;
|
||||
use App\Module\Commercial\Domain\Entity\PaymentDelay;
|
||||
use App\Module\Commercial\Domain\Entity\PaymentType;
|
||||
use App\Module\Commercial\Domain\Entity\TvaMode;
|
||||
@@ -58,6 +59,8 @@ final class EntitiesAreTimestampableBlamableTest extends TestCase
|
||||
* CommercialReferentialFixtures, lecture seule au M1 (HP-M2-2). Pas de
|
||||
* tracabilite user-driven, meme justification que CategoryType. Cf.
|
||||
* spec-back M1 § 2.6 + § 3.5.
|
||||
* - Country (ERP-116) : referentiel statique des pays (id/code/name/position),
|
||||
* seede par migration, lecture seule. Meme justification que Bank.
|
||||
*
|
||||
* Les futurs referentiels statiques s'ajoutent ici avec une justification.
|
||||
*/
|
||||
@@ -71,6 +74,7 @@ final class EntitiesAreTimestampableBlamableTest extends TestCase
|
||||
PaymentDelay::class,
|
||||
PaymentType::class,
|
||||
Bank::class,
|
||||
Country::class,
|
||||
];
|
||||
|
||||
public function testAllBusinessEntitiesImplementBothInterfaces(): void
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Module\Commercial\Api;
|
||||
|
||||
/**
|
||||
* Validation back-autoritative du FORMAT de la date de creation (foundedAt,
|
||||
* onglet Information).
|
||||
*
|
||||
* Le front (MalioDate, cf. MUI-44) forwarde desormais la saisie brute invalide
|
||||
* au serveur plutot que de l'avaler. Cote back, une date non parsable doit
|
||||
* produire un 422 porte sur `foundedAt` (mappable inline par useFormErrors),
|
||||
* et non un 400 generique. Repose sur `collectDenormalizationErrors` actif sur
|
||||
* l'operation Patch du Client.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class ClientFoundedAtFormatTest extends AbstractCommercialApiTestCase
|
||||
{
|
||||
private const string MERGE = 'application/merge-patch+json';
|
||||
|
||||
/** Date non parsable -> 422 porte sur foundedAt (et pas un 400 generique). */
|
||||
public function testFoundedAtNonParsableEst422(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedClient('Founded Format SARL');
|
||||
|
||||
$body = $client->request('PATCH', '/api/clients/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['foundedAt' => '32/13/2026'],
|
||||
])->toArray(false);
|
||||
|
||||
self::assertResponseStatusCodeSame(422);
|
||||
self::assertArrayHasKey('foundedAt', $this->violationsByPath($body));
|
||||
}
|
||||
|
||||
/**
|
||||
* Cas piege : « 12/25/2026 » est invalide cote front (JJ/MM/AAAA -> mois 25)
|
||||
* mais PHP DateTime l'accepterait en M/J/AAAA (25 decembre). Le format d'entree
|
||||
* strict ISO `Y-m-d` (Context sur foundedAt) doit le rejeter -> 422.
|
||||
*/
|
||||
public function testFoundedAtFormatAmbiguUsEst422(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedClient('Founded Ambigu SARL');
|
||||
|
||||
$body = $client->request('PATCH', '/api/clients/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['foundedAt' => '12/25/2026'],
|
||||
])->toArray(false);
|
||||
|
||||
self::assertResponseStatusCodeSame(422);
|
||||
self::assertArrayHasKey('foundedAt', $this->violationsByPath($body));
|
||||
}
|
||||
|
||||
/** Non-regression : une date ISO valide reste acceptee (200). */
|
||||
public function testFoundedAtIsoValideEst200(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$seed = $this->seedClient('Founded Ok SARL');
|
||||
|
||||
$data = $client->request('PATCH', '/api/clients/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['foundedAt' => '2010-05-01'],
|
||||
])->toArray();
|
||||
|
||||
self::assertResponseStatusCodeSame(200);
|
||||
self::assertStringStartsWith('2010-05-01', $data['foundedAt']);
|
||||
}
|
||||
}
|
||||
@@ -241,6 +241,72 @@ final class ReferentialApiTest extends AbstractCommercialApiTestCase
|
||||
self::assertResponseStatusCodeSame(401);
|
||||
}
|
||||
|
||||
/**
|
||||
* Referentiel pays (ERP-116) — teste a part des 4 referentiels comptables
|
||||
* car il expose `name` (et non `label`). Memes garanties : 200 + seed des 7
|
||||
* pays, France en tete (position ASC), lecture seule (405), gating (403/401).
|
||||
*/
|
||||
public function testCountriesCollectionReturns200WithSeed(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$response = $client->request('GET', '/api/countries?pagination=false', ['headers' => ['Accept' => self::LD]]);
|
||||
|
||||
self::assertResponseStatusCodeSame(200);
|
||||
|
||||
$members = $response->toArray()['member'];
|
||||
$codes = array_map(static fn (array $m): string => $m['code'], $members);
|
||||
|
||||
foreach (['FR', 'DE', 'BE', 'ES', 'IT', 'GB', 'CH'] as $expected) {
|
||||
self::assertContains($expected, $codes, '/api/countries doit exposer le pays seede '.$expected);
|
||||
}
|
||||
|
||||
// Le DTO de lecture expose id / code / name / position.
|
||||
$first = $members[0];
|
||||
self::assertArrayHasKey('id', $first);
|
||||
self::assertArrayHasKey('name', $first);
|
||||
self::assertArrayHasKey('position', $first);
|
||||
// Tri par defaut position ASC : France (position 10) en tete.
|
||||
self::assertSame('FR', $first['code'], 'France (FR) doit etre en tete (position 10, tri position ASC).');
|
||||
}
|
||||
|
||||
public function testCountriesGetItemReturns200(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
|
||||
$first = $client->request('GET', '/api/countries?pagination=false', ['headers' => ['Accept' => self::LD]])
|
||||
->toArray()['member'][0]
|
||||
;
|
||||
|
||||
$client->request('GET', '/api/countries/'.$first['id'], ['headers' => ['Accept' => self::LD]]);
|
||||
self::assertResponseStatusCodeSame(200);
|
||||
}
|
||||
|
||||
public function testCountriesPostReturns405(): void
|
||||
{
|
||||
$client = $this->createAdminClient();
|
||||
$client->request('POST', '/api/countries', [
|
||||
'headers' => ['Content-Type' => self::LD],
|
||||
'json' => ['code' => 'XX', 'name' => 'Pays X', 'position' => 1],
|
||||
]);
|
||||
self::assertResponseStatusCodeSame(405);
|
||||
}
|
||||
|
||||
public function testCountriesForbiddenWithoutPermission(): void
|
||||
{
|
||||
$creds = $this->createUserWithPermission('core.users.view');
|
||||
$client = $this->authenticatedClient($creds['username'], $creds['password']);
|
||||
|
||||
$client->request('GET', '/api/countries', ['headers' => ['Accept' => self::LD]]);
|
||||
self::assertResponseStatusCodeSame(403);
|
||||
}
|
||||
|
||||
public function testCountriesUnauthorizedWhenAnonymous(): void
|
||||
{
|
||||
$client = self::createClient();
|
||||
$client->request('GET', '/api/countries', ['headers' => ['Accept' => self::LD]]);
|
||||
self::assertResponseStatusCodeSame(401);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return iterable<string, array{string, list<string>}>
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Module\Commercial\Api;
|
||||
|
||||
/**
|
||||
* Validation back-autoritative du FORMAT de la date de creation (foundedAt,
|
||||
* onglet Information) du fournisseur. Miroir de {@see ClientFoundedAtFormatTest}.
|
||||
*
|
||||
* Une date non parsable (saisie brute forwardee par MalioDate, MUI-44) doit
|
||||
* produire un 422 porte sur `foundedAt` (mappable inline par useFormErrors), et
|
||||
* non un 400 generique. Repose sur `collectDenormalizationErrors` sur les
|
||||
* operations write du Supplier.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class SupplierFoundedAtFormatTest extends AbstractSupplierApiTestCase
|
||||
{
|
||||
/** Date non parsable -> 422 porte sur foundedAt (et pas un 400 generique). */
|
||||
public function testFoundedAtNonParsableEst422(): void
|
||||
{
|
||||
$seed = $this->seedSupplier('Founded Format Negoce');
|
||||
$credentials = $this->createUserWithPermission('commercial.suppliers.manage');
|
||||
$client = $this->authenticatedClient($credentials['username'], $credentials['password']);
|
||||
|
||||
$body = $client->request('PATCH', '/api/suppliers/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['foundedAt' => '32/13/2026'],
|
||||
])->toArray(false);
|
||||
|
||||
self::assertResponseStatusCodeSame(422);
|
||||
self::assertArrayHasKey('foundedAt', $this->violationsByPath($body));
|
||||
}
|
||||
|
||||
/**
|
||||
* Cas piege : « 12/25/2026 » est invalide cote front (JJ/MM/AAAA -> mois 25)
|
||||
* mais PHP DateTime l'accepterait en M/J/AAAA. Le format d'entree strict ISO
|
||||
* `Y-m-d` (Context sur foundedAt) doit le rejeter -> 422.
|
||||
*/
|
||||
public function testFoundedAtFormatAmbiguUsEst422(): void
|
||||
{
|
||||
$seed = $this->seedSupplier('Founded Ambigu Negoce');
|
||||
$credentials = $this->createUserWithPermission('commercial.suppliers.manage');
|
||||
$client = $this->authenticatedClient($credentials['username'], $credentials['password']);
|
||||
|
||||
$body = $client->request('PATCH', '/api/suppliers/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['foundedAt' => '12/25/2026'],
|
||||
])->toArray(false);
|
||||
|
||||
self::assertResponseStatusCodeSame(422);
|
||||
self::assertArrayHasKey('foundedAt', $this->violationsByPath($body));
|
||||
}
|
||||
|
||||
/** Non-regression : une date ISO valide reste acceptee (200). */
|
||||
public function testFoundedAtIsoValideEst200(): void
|
||||
{
|
||||
$seed = $this->seedSupplier('Founded Ok Negoce');
|
||||
$credentials = $this->createUserWithPermission('commercial.suppliers.manage');
|
||||
$client = $this->authenticatedClient($credentials['username'], $credentials['password']);
|
||||
|
||||
$data = $client->request('PATCH', '/api/suppliers/'.$seed->getId(), [
|
||||
'headers' => ['Content-Type' => self::MERGE],
|
||||
'json' => ['foundedAt' => '2010-05-01'],
|
||||
])->toArray();
|
||||
|
||||
self::assertResponseStatusCodeSame(200);
|
||||
self::assertStringStartsWith('2010-05-01', $data['foundedAt']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Module\Transport\Application\Qualimat;
|
||||
|
||||
use App\Module\Transport\Application\Qualimat\QualimatRowMapper;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class QualimatRowMapperTest extends TestCase
|
||||
{
|
||||
public function testNormalizeSiretStripsNonDigits(): void
|
||||
{
|
||||
self::assertSame('44415628500025', QualimatRowMapper::normalizeSiret('444 156 285 000 25'));
|
||||
self::assertNull(QualimatRowMapper::normalizeSiret(null));
|
||||
self::assertNull(QualimatRowMapper::normalizeSiret(' '));
|
||||
self::assertNull(QualimatRowMapper::normalizeSiret(''));
|
||||
}
|
||||
|
||||
public function testParseDate(): void
|
||||
{
|
||||
self::assertSame('2027-05-14', QualimatRowMapper::parseDate('14/05/2027'));
|
||||
self::assertNull(QualimatRowMapper::parseDate(null));
|
||||
self::assertNull(QualimatRowMapper::parseDate('2027-05-14'));
|
||||
self::assertNull(QualimatRowMapper::parseDate('14-05-2027'));
|
||||
// Date calendaire impossible : evite un INSERT en erreur.
|
||||
self::assertNull(QualimatRowMapper::parseDate('31/02/2027'));
|
||||
}
|
||||
|
||||
public function testMapOneNormalizesAndTrims(): void
|
||||
{
|
||||
$row = QualimatRowMapper::mapOne([
|
||||
'Nom' => ' 2C TRANS ',
|
||||
'Societe' => '2C TRANS',
|
||||
'Adresse' => '66 Impasse Mendi',
|
||||
'CodePostal' => '65500',
|
||||
'Ville' => 'VIC EN BIGORRE',
|
||||
'Telephone_1' => '+33|0608890316',
|
||||
'Siret' => '444 156 285 000 25',
|
||||
'Validite' => '14/05/2027',
|
||||
'Statut' => 'Audité',
|
||||
'Departement' => '65 - Hautes-Pyrénées',
|
||||
]);
|
||||
|
||||
self::assertNotNull($row);
|
||||
self::assertSame('44415628500025', $row['siret']);
|
||||
self::assertSame('2C TRANS', $row['name']);
|
||||
self::assertSame('2027-05-14', $row['validity_date']);
|
||||
self::assertSame('+33|0608890316', $row['phone']);
|
||||
self::assertSame('Audité', $row['status']);
|
||||
self::assertSame('65 - Hautes-Pyrénées', $row['department']);
|
||||
}
|
||||
|
||||
public function testMapOneReturnsNullWithoutSiret(): void
|
||||
{
|
||||
self::assertNull(QualimatRowMapper::mapOne(['Nom' => 'X', 'Siret' => null]));
|
||||
self::assertNull(QualimatRowMapper::mapOne(['Nom' => 'X']));
|
||||
self::assertNull(QualimatRowMapper::mapOne(['Nom' => 'X', 'Siret' => ' ']));
|
||||
}
|
||||
|
||||
public function testMapManyCountsSkipped(): void
|
||||
{
|
||||
$result = QualimatRowMapper::mapMany([
|
||||
['Nom' => 'A', 'Siret' => '111 111 111 00011', 'Statut' => 'Audité', 'Validite' => '01/01/2030'],
|
||||
['Nom' => 'B', 'Siret' => null],
|
||||
['Nom' => 'C', 'Siret' => ' '],
|
||||
]);
|
||||
|
||||
self::assertCount(1, $result['rows']);
|
||||
self::assertSame(2, $result['skipped']);
|
||||
}
|
||||
|
||||
public function testEmptyOptionalFieldsBecomeNull(): void
|
||||
{
|
||||
$row = QualimatRowMapper::mapOne([
|
||||
'Siret' => '111 111 111 00011',
|
||||
'Nom' => 'A',
|
||||
'Adresse' => '',
|
||||
'Ville' => ' ',
|
||||
]);
|
||||
|
||||
self::assertNotNull($row);
|
||||
self::assertNull($row['address']);
|
||||
self::assertNull($row['city']);
|
||||
self::assertNull($row['validity_date']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Tests\Module\Transport\Infrastructure\Console;
|
||||
|
||||
use Doctrine\DBAL\Connection;
|
||||
use Symfony\Bundle\FrameworkBundle\Console\Application;
|
||||
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
|
||||
use Symfony\Component\Console\Tester\CommandTester;
|
||||
|
||||
use const JSON_THROW_ON_ERROR;
|
||||
|
||||
/**
|
||||
* Test fonctionnel de `app:qualimat:sync` via l'option --file (pas d'appel
|
||||
* reseau) : verifie l'upsert normalise, le journal et le soft-delete.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class SyncQualimatCommandTest extends KernelTestCase
|
||||
{
|
||||
private Connection $connection;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
self::bootKernel();
|
||||
|
||||
/** @var Connection $connection */
|
||||
$connection = self::getContainer()->get('doctrine.dbal.default_connection');
|
||||
$this->connection = $connection;
|
||||
$this->purge();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->purge();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function testFirstSyncInsertsNormalizesAndLogs(): void
|
||||
{
|
||||
$tester = $this->runSync([
|
||||
[
|
||||
'Nom' => '2C TRANS',
|
||||
'Societe' => '2C TRANS',
|
||||
'Adresse' => '66 Impasse Mendi',
|
||||
'CodePostal' => '65500',
|
||||
'Ville' => 'VIC EN BIGORRE',
|
||||
'Telephone_1' => '+33|0608890316',
|
||||
'Siret' => '444 156 285 000 25',
|
||||
'Validite' => '14/05/2027',
|
||||
'Statut' => 'Audité',
|
||||
'Departement' => '65 - Hautes-Pyrénées',
|
||||
],
|
||||
// Item sans SIRET : doit etre ignore (compte dans rows_skipped).
|
||||
['Nom' => 'SANS SIRET', 'Siret' => null, 'Validite' => '01/01/2030', 'Statut' => 'Valide'],
|
||||
]);
|
||||
|
||||
$tester->assertCommandIsSuccessful();
|
||||
|
||||
self::assertSame(1, $this->countRows('SELECT COUNT(*) FROM qualimat_carrier'));
|
||||
|
||||
$row = $this->connection->fetchAssociative('SELECT * FROM qualimat_carrier');
|
||||
self::assertNotFalse($row);
|
||||
self::assertSame('44415628500025', $row['siret']);
|
||||
self::assertSame('2C TRANS', $row['name']);
|
||||
self::assertSame('2027-05-14', $row['validity_date']);
|
||||
self::assertSame('+33|0608890316', $row['phone']);
|
||||
self::assertSame(1, $this->countRows('SELECT COUNT(*) FROM qualimat_carrier WHERE is_active = TRUE'));
|
||||
|
||||
$log = $this->connection->fetchAssociative('SELECT * FROM qualimat_sync_log ORDER BY id DESC LIMIT 1');
|
||||
self::assertNotFalse($log);
|
||||
self::assertSame(2, (int) $log['rows_total']);
|
||||
self::assertSame(1, (int) $log['rows_upserted']);
|
||||
self::assertSame(1, (int) $log['rows_skipped']);
|
||||
self::assertSame(0, (int) $log['rows_deactivated']);
|
||||
}
|
||||
|
||||
public function testSecondSyncUpdatesAndSoftDeletesMissing(): void
|
||||
{
|
||||
$a = ['Nom' => 'A', 'Siret' => '111 111 111 00011', 'Validite' => '01/01/2030', 'Statut' => 'Audité'];
|
||||
$b = ['Nom' => 'B', 'Siret' => '222 222 222 00022', 'Validite' => '01/01/2030', 'Statut' => 'Audité'];
|
||||
|
||||
$this->runSync([$a, $b])->assertCommandIsSuccessful();
|
||||
self::assertSame(2, $this->countRows('SELECT COUNT(*) FROM qualimat_carrier WHERE is_active = TRUE'));
|
||||
|
||||
// 2e run sans B et avec A renomme : A est mis a jour, B est soft-delete.
|
||||
$aRenamed = ['Nom' => 'A BIS', 'Siret' => '111 111 111 00011', 'Validite' => '02/02/2031', 'Statut' => 'Valide'];
|
||||
$tester = $this->runSync([$aRenamed]);
|
||||
$tester->assertCommandIsSuccessful();
|
||||
|
||||
// Toujours 2 lignes en base, mais une seule active.
|
||||
self::assertSame(2, $this->countRows('SELECT COUNT(*) FROM qualimat_carrier'));
|
||||
self::assertSame(1, $this->countRows('SELECT COUNT(*) FROM qualimat_carrier WHERE is_active = TRUE'));
|
||||
self::assertSame(1, $this->countRows("SELECT COUNT(*) FROM qualimat_carrier WHERE siret = '22222222200022' AND is_active = FALSE"));
|
||||
|
||||
// A a bien ete mis a jour (nom + statut + date).
|
||||
$a = $this->connection->fetchAssociative("SELECT * FROM qualimat_carrier WHERE siret = '11111111100011'");
|
||||
self::assertNotFalse($a);
|
||||
self::assertSame('A BIS', $a['name']);
|
||||
self::assertSame('Valide', $a['status']);
|
||||
self::assertSame('2031-02-02', $a['validity_date']);
|
||||
|
||||
$log = $this->connection->fetchAssociative('SELECT * FROM qualimat_sync_log ORDER BY id DESC LIMIT 1');
|
||||
self::assertNotFalse($log);
|
||||
self::assertSame(1, (int) $log['rows_upserted']);
|
||||
self::assertSame(1, (int) $log['rows_deactivated']);
|
||||
self::assertSame(0, (int) $log['rows_skipped']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $items
|
||||
*/
|
||||
private function runSync(array $items): CommandTester
|
||||
{
|
||||
$path = tempnam(sys_get_temp_dir(), 'qualimat_').'.json';
|
||||
file_put_contents($path, json_encode($items, JSON_THROW_ON_ERROR));
|
||||
|
||||
$application = new Application(self::$kernel);
|
||||
$tester = new CommandTester($application->find('app:qualimat:sync'));
|
||||
$tester->execute(['--file' => $path]);
|
||||
|
||||
@unlink($path);
|
||||
|
||||
return $tester;
|
||||
}
|
||||
|
||||
private function countRows(string $sql): int
|
||||
{
|
||||
return (int) $this->connection->fetchOne($sql);
|
||||
}
|
||||
|
||||
private function purge(): void
|
||||
{
|
||||
$this->connection->executeStatement('DELETE FROM qualimat_carrier');
|
||||
$this->connection->executeStatement('DELETE FROM qualimat_sync_log');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user