feat(catalog) : M6 — page liste produits /admin/products (ERP-204)
Ecran d'entree du catalogue produit (admin-only) : liste paginee (usePaginatedList), drawer de filtres (categorie/etat/sites), export XLSX et navigation vers creation/edition. - colonnes Nom / Numero (code) / Categorie (category.name), tri name ASC serveur - filtres mappes sur les query params du provider (categoryId, state, siteId[]) - etat du tableau 100% local (jamais dans l'URL) - type Product calque sur le contrat JSON capture (ERP-203) - i18n admin.products ; 11 tests Vitest
This commit is contained in:
@@ -1020,6 +1020,37 @@
|
||||
"duplicate": "Une catégorie nommée « {name} » existe déjà.",
|
||||
"typesLoadFailed": "Impossible de charger les types de catégorie. Réessayez."
|
||||
}
|
||||
},
|
||||
"products": {
|
||||
"title": "Catalogue produit",
|
||||
"add": "Ajouter",
|
||||
"export": "Exporter",
|
||||
"empty": "Aucun produit pour l'instant.",
|
||||
"column": {
|
||||
"name": "Nom",
|
||||
"code": "Numéro",
|
||||
"category": "Catégorie"
|
||||
},
|
||||
"state": {
|
||||
"PURCHASE": "Acheté",
|
||||
"SALE": "Vendu",
|
||||
"OTHER": "Autre"
|
||||
},
|
||||
"filters": {
|
||||
"title": "Filtres",
|
||||
"search": "Recherche",
|
||||
"category": "Catégorie",
|
||||
"categoryAll": "Toutes les catégories",
|
||||
"state": "État",
|
||||
"stateAll": "Tous les états",
|
||||
"site": "Sites",
|
||||
"apply": "Voir les résultats",
|
||||
"reset": "Réinitialiser"
|
||||
},
|
||||
"toast": {
|
||||
"error": "Une erreur est survenue. Réessayez.",
|
||||
"exportError": "L'export du catalogue produit a échoué. Réessayez."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { mount, flushPromises } from '@vue/test-utils'
|
||||
import { defineComponent, h, ref } from 'vue'
|
||||
|
||||
// ── Auto-imports Nuxt stubbes globalement ───────────────────────────────────
|
||||
// La page ne les importe pas (auto-import) : on les expose en globals pour le
|
||||
// runtime de test (happy-dom). Meme philosophie que les specs M1→M5.
|
||||
const mockPush = vi.hoisted(() => vi.fn())
|
||||
const mockApiGet = vi.hoisted(() => vi.fn())
|
||||
const mockCan = vi.hoisted(() => vi.fn())
|
||||
const mockSetFilters = vi.hoisted(() => vi.fn())
|
||||
const mockFetch = vi.hoisted(() => vi.fn())
|
||||
const mockToastError = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.stubGlobal('useI18n', () => ({ t: (key: string) => key }))
|
||||
vi.stubGlobal('useHead', () => undefined)
|
||||
vi.stubGlobal('useApi', () => ({ get: mockApiGet }))
|
||||
vi.stubGlobal('useRouter', () => ({ push: mockPush }))
|
||||
vi.stubGlobal('useToast', () => ({ error: mockToastError, success: vi.fn() }))
|
||||
vi.stubGlobal('usePermissions', () => ({ can: mockCan }))
|
||||
// usePaginatedList est l'auto-import pilotant la liste : on controle items +
|
||||
// setFilters + fetch. La ligne reproduit le contrat JSON reel (§ 4.0.bis).
|
||||
vi.stubGlobal('usePaginatedList', () => ({
|
||||
items: ref<Array<Record<string, unknown>>>([
|
||||
{
|
||||
id: 34,
|
||||
code: 'BLE-TENDRE-01',
|
||||
name: 'Blé tendre',
|
||||
states: ['PURCHASE', 'SALE'],
|
||||
manufactured: true,
|
||||
containsMolasses: true,
|
||||
category: { id: 12, name: 'Céréales', code: 'CEREALES' },
|
||||
sites: [{ id: 1, name: 'Chatellerault', code: '86' }],
|
||||
storageTypes: [{ id: 9, code: 'TAS', label: 'Tas' }],
|
||||
},
|
||||
]),
|
||||
totalItems: ref(1),
|
||||
currentPage: ref(1),
|
||||
itemsPerPage: ref(10),
|
||||
itemsPerPageOptions: ref([10, 25, 50]),
|
||||
fetch: mockFetch,
|
||||
goToPage: vi.fn(),
|
||||
setItemsPerPage: vi.fn(),
|
||||
setFilters: mockSetFilters,
|
||||
}))
|
||||
|
||||
// happy-dom n'implemente pas createObjectURL : on ajoute les methodes statiques
|
||||
// sur la classe URL existante (sans la remplacer — sinon `new URL()` casse).
|
||||
globalThis.URL.createObjectURL = vi.fn(() => 'blob:fake')
|
||||
globalThis.URL.revokeObjectURL = vi.fn()
|
||||
|
||||
// Import APRES les stubs (la page resout les auto-imports au top-level du module).
|
||||
const ProductsIndex = (await import('../admin/products.vue')).default
|
||||
|
||||
// ── Stubs de composants ──────────────────────────────────────────────────────
|
||||
const ButtonStub = defineComponent({
|
||||
props: { label: { type: String, default: '' }, disabled: { type: Boolean, default: false } },
|
||||
emits: ['click'],
|
||||
setup(props, { emit }) {
|
||||
return () => h('button', { 'data-label': props.label, onClick: () => emit('click') }, props.label)
|
||||
},
|
||||
})
|
||||
|
||||
const DataTableStub = defineComponent({
|
||||
props: { items: { type: Array, default: () => [] } },
|
||||
emits: ['row-click', 'update:page', 'update:per-page'],
|
||||
setup(props, { emit }) {
|
||||
return () => h('div', { 'data-testid': 'datatable' },
|
||||
(props.items as Array<Record<string, unknown>>).map(it =>
|
||||
h('tr', {
|
||||
'data-row-id': it.id,
|
||||
'data-name': it.name,
|
||||
'data-code': it.code,
|
||||
'data-category': it.categoryName,
|
||||
'onClick': () => emit('row-click', it),
|
||||
}),
|
||||
),
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
const DrawerStub = defineComponent({
|
||||
props: { modelValue: { type: Boolean, default: false } },
|
||||
setup(_, { slots }) {
|
||||
return () => h('div', {}, [slots.header?.(), slots.default?.(), slots.footer?.()])
|
||||
},
|
||||
})
|
||||
|
||||
const SlotStub = defineComponent({ setup(_, { slots }) { return () => h('div', {}, slots.default?.()) } })
|
||||
|
||||
const PageHeaderStub = defineComponent({
|
||||
setup(_, { slots }) { return () => h('div', {}, [slots.default?.(), slots.actions?.()]) },
|
||||
})
|
||||
|
||||
const CheckboxStub = defineComponent({
|
||||
props: { id: { type: String, default: '' }, modelValue: { type: Boolean, default: false } },
|
||||
emits: ['update:model-value'],
|
||||
setup(props, { emit }) {
|
||||
return () => h('input', {
|
||||
'type': 'checkbox',
|
||||
'data-id': props.id,
|
||||
'onChange': (e: Event) => emit('update:model-value', (e.target as HTMLInputElement).checked),
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
const SelectStub = defineComponent({
|
||||
props: {
|
||||
modelValue: { type: [String, Number, null] as unknown as () => string | number | null, default: null },
|
||||
options: { type: Array, default: () => [] },
|
||||
emptyOptionLabel: { type: String, default: '' },
|
||||
},
|
||||
emits: ['update:model-value'],
|
||||
setup(props, { emit }) {
|
||||
return () => h('select', {
|
||||
'data-empty-label': props.emptyOptionLabel,
|
||||
'onChange': (e: Event) => emit('update:model-value', (e.target as HTMLSelectElement).value),
|
||||
}, (props.options as Array<{ value: string | number, label: string }>).map(o =>
|
||||
h('option', { value: o.value }, o.label),
|
||||
))
|
||||
},
|
||||
})
|
||||
|
||||
const InputTextStub = defineComponent({ setup() { return () => h('input') } })
|
||||
|
||||
function mountPage() {
|
||||
return mount(ProductsIndex, {
|
||||
global: {
|
||||
stubs: {
|
||||
PageHeader: PageHeaderStub,
|
||||
MalioButton: ButtonStub,
|
||||
MalioDataTable: DataTableStub,
|
||||
MalioDrawer: DrawerStub,
|
||||
MalioAccordion: SlotStub,
|
||||
MalioAccordionItem: SlotStub,
|
||||
MalioInputText: InputTextStub,
|
||||
MalioSelect: SelectStub,
|
||||
MalioCheckbox: CheckboxStub,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
describe('Catalogue produit (page /admin/products)', () => {
|
||||
beforeEach(() => {
|
||||
mockPush.mockReset()
|
||||
mockApiGet.mockReset().mockImplementation((url: string) => {
|
||||
if (url === '/categories') {
|
||||
return Promise.resolve({ member: [{ '@id': '/api/categories/12', id: 12, name: 'Céréales' }] })
|
||||
}
|
||||
if (url === '/sites') {
|
||||
return Promise.resolve({ member: [{ id: 1, name: 'Chatellerault' }] })
|
||||
}
|
||||
return Promise.resolve({ member: [] })
|
||||
})
|
||||
mockCan.mockReset().mockReturnValue(true)
|
||||
mockSetFilters.mockReset()
|
||||
mockFetch.mockReset()
|
||||
mockToastError.mockReset()
|
||||
})
|
||||
|
||||
it('charge la liste au montage', async () => {
|
||||
mountPage()
|
||||
await flushPromises()
|
||||
expect(mockFetch).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('mappe les colonnes Nom / Numéro / Catégorie sur le JSON réel (§ 4.0.bis)', async () => {
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
const row = wrapper.find('tr[data-row-id="34"]')
|
||||
expect(row.attributes('data-name')).toBe('Blé tendre')
|
||||
expect(row.attributes('data-code')).toBe('BLE-TENDRE-01')
|
||||
expect(row.attributes('data-category')).toBe('Céréales')
|
||||
})
|
||||
|
||||
it('affiche « + Ajouter » uniquement avec la permission manage', async () => {
|
||||
mockCan.mockImplementation((perm: string) => perm === 'catalog.products.manage')
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
expect(wrapper.find('[data-label="admin.products.add"]').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('masque « + Ajouter » sans la permission manage (view seul)', async () => {
|
||||
mockCan.mockImplementation((perm: string) => perm === 'catalog.products.view')
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
expect(wrapper.find('[data-label="admin.products.add"]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('navigue vers l\'édition au clic sur une ligne', async () => {
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
await wrapper.find('tr[data-row-id="34"]').trigger('click')
|
||||
expect(mockPush).toHaveBeenCalledWith('/admin/products/34/edit')
|
||||
})
|
||||
|
||||
it('navigue vers la création au clic sur « + Ajouter »', async () => {
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
await wrapper.find('[data-label="admin.products.add"]').trigger('click')
|
||||
expect(mockPush).toHaveBeenCalledWith('/admin/products/new')
|
||||
})
|
||||
|
||||
it('appelle l\'export XLSX sur /products/export.xlsx en blob', async () => {
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
await wrapper.find('[data-label="admin.products.export"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(mockApiGet).toHaveBeenCalledWith(
|
||||
'/products/export.xlsx',
|
||||
expect.any(Object),
|
||||
expect.objectContaining({ responseType: 'blob', toast: false }),
|
||||
)
|
||||
})
|
||||
|
||||
it('répercute les sites cochés dans setFilters (filtre multi, clé siteId[])', async () => {
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
|
||||
await wrapper.find('input[data-id="filter-site-1"]').setValue(true)
|
||||
await wrapper.find('[data-label="admin.products.filters.apply"]').trigger('click')
|
||||
|
||||
expect(mockSetFilters).toHaveBeenLastCalledWith(
|
||||
{ 'siteId[]': ['1'] },
|
||||
{ replace: true },
|
||||
)
|
||||
// Etat 100 % local (regle n°6) : aucune navigation/query string declenchee.
|
||||
expect(mockPush).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('répercute l\'état sélectionné dans setFilters (param state)', async () => {
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
|
||||
await wrapper.find('select[data-empty-label="admin.products.filters.stateAll"]').setValue('SALE')
|
||||
await wrapper.find('[data-label="admin.products.filters.apply"]').trigger('click')
|
||||
|
||||
expect(mockSetFilters).toHaveBeenLastCalledWith(
|
||||
{ state: 'SALE' },
|
||||
{ replace: true },
|
||||
)
|
||||
})
|
||||
|
||||
it('répercute la catégorie sélectionnée dans setFilters (param categoryId)', async () => {
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
|
||||
await wrapper.find('select[data-empty-label="admin.products.filters.categoryAll"]').setValue('12')
|
||||
await wrapper.find('[data-label="admin.products.filters.apply"]').trigger('click')
|
||||
|
||||
expect(mockSetFilters).toHaveBeenLastCalledWith(
|
||||
{ categoryId: '12' },
|
||||
{ replace: true },
|
||||
)
|
||||
})
|
||||
|
||||
it('badge filtres actifs + Réinitialiser vide l\'état appliqué', async () => {
|
||||
const wrapper = mountPage()
|
||||
await flushPromises()
|
||||
|
||||
await wrapper.find('input[data-id="filter-site-1"]').setValue(true)
|
||||
await wrapper.find('[data-label="admin.products.filters.apply"]').trigger('click')
|
||||
|
||||
// Le libelle du bouton Filtrer porte le compteur (1 filtre actif).
|
||||
expect(wrapper.find('[data-label="admin.products.filters.title (1)"]').exists()).toBe(true)
|
||||
|
||||
// Réinitialiser → query propre (setFilters avec objet vide).
|
||||
await wrapper.find('[data-label="admin.products.filters.reset"]').trigger('click')
|
||||
expect(mockSetFilters).toHaveBeenLastCalledWith({}, { replace: true })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,377 @@
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader>
|
||||
{{ t('admin.products.title') }}
|
||||
<template #actions>
|
||||
<!-- gap-8 = 32px d'espacement entre Filtrer et Ajouter (meme
|
||||
design que le Repertoire transporteurs / la Gestion des categories). -->
|
||||
<div class="flex items-center gap-8">
|
||||
<!-- Bouton Filtrer a GAUCHE d'Ajouter. Le compteur reflete les filtres actifs. -->
|
||||
<MalioButton
|
||||
v-if="canView"
|
||||
variant="tertiary"
|
||||
:label="filterButtonLabel"
|
||||
icon-name="mdi:tune"
|
||||
icon-position="left"
|
||||
icon-size="24"
|
||||
@click="openFilters"
|
||||
/>
|
||||
<MalioButton
|
||||
v-if="canManage"
|
||||
variant="secondary"
|
||||
:label="t('admin.products.add')"
|
||||
icon-name="mdi:add-bold"
|
||||
icon-position="left"
|
||||
@click="goToCreate"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<!-- Datatable branchee sur usePaginatedList : pagination serveur, tri
|
||||
name ASC par defaut (cote back, § 4.1). Colonnes Nom / Numero /
|
||||
Categorie (docx p.3). -->
|
||||
<MalioDataTable
|
||||
:columns="columns"
|
||||
:items="rows"
|
||||
:total-items="totalItems"
|
||||
:page="currentPage"
|
||||
:per-page="itemsPerPage"
|
||||
:per-page-options="itemsPerPageOptions"
|
||||
row-clickable
|
||||
:empty-message="t('admin.products.empty')"
|
||||
@row-click="onRowClick"
|
||||
@update:page="goToPage"
|
||||
@update:per-page="setItemsPerPage"
|
||||
/>
|
||||
|
||||
<div class="flex justify-center mt-4">
|
||||
<MalioButton
|
||||
v-if="canView"
|
||||
variant="primary"
|
||||
:label="t('admin.products.export')"
|
||||
:disabled="exporting"
|
||||
@click="exportXlsx"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Drawer de filtres : etat BROUILLON, applique uniquement au clic sur
|
||||
« Voir les résultats ». Meme pattern que les repertoires M1→M5.
|
||||
Etat 100 % local, jamais dans l'URL (regle ABSOLUE n°6). -->
|
||||
<MalioDrawer
|
||||
v-model="filterDrawerOpen"
|
||||
drawer-class="max-w-[450px]"
|
||||
body-class="p-0"
|
||||
footer-class="justify-between border-t border-black p-6"
|
||||
>
|
||||
<template #header>
|
||||
<h2 class="text-[24px] font-bold uppercase">{{ t('admin.products.filters.title') }}</h2>
|
||||
</template>
|
||||
|
||||
<MalioAccordion>
|
||||
<!-- Recherche : code + nom (param `search`, partiel insensible a la casse). -->
|
||||
<MalioAccordionItem :title="t('admin.products.filters.search')" value="search">
|
||||
<MalioInputText
|
||||
v-model="draftSearch"
|
||||
icon-name="mdi:magnify"
|
||||
/>
|
||||
</MalioAccordionItem>
|
||||
|
||||
<!-- Categorie : select simple (param `categoryId`). Referentiel borne
|
||||
aux categories de type PRODUIT (RG-6.05). -->
|
||||
<MalioAccordionItem :title="t('admin.products.filters.category')" value="category">
|
||||
<MalioSelect
|
||||
:model-value="draftCategoryId"
|
||||
:options="categoryOptions"
|
||||
:empty-option-label="t('admin.products.filters.categoryAll')"
|
||||
@update:model-value="(v: string | number | null) => draftCategoryId = v === null || v === '' ? null : Number(v)"
|
||||
/>
|
||||
</MalioAccordionItem>
|
||||
|
||||
<!-- Etat : select simple (param `state`, enum PURCHASE / SALE / OTHER). -->
|
||||
<MalioAccordionItem :title="t('admin.products.filters.state')" value="state">
|
||||
<MalioSelect
|
||||
:model-value="draftState"
|
||||
:options="stateOptions"
|
||||
:empty-option-label="t('admin.products.filters.stateAll')"
|
||||
@update:model-value="(v: string | number | null) => draftState = v === null || v === '' ? null : String(v)"
|
||||
/>
|
||||
</MalioAccordionItem>
|
||||
|
||||
<!-- Site(s) : cases a cocher (multi, param `siteId[]`). Un produit
|
||||
remonte s'il est disponible sur AU MOINS UN des sites coches. -->
|
||||
<MalioAccordionItem :title="t('admin.products.filters.site')" value="site">
|
||||
<div class="flex flex-col">
|
||||
<MalioCheckbox
|
||||
v-for="opt in siteOptions"
|
||||
:id="`filter-site-${opt.value}`"
|
||||
:key="opt.value"
|
||||
:label="opt.label"
|
||||
:model-value="draftSiteIds.includes(opt.value)"
|
||||
@update:model-value="(val: boolean) => toggleSite(opt.value, val)"
|
||||
/>
|
||||
</div>
|
||||
</MalioAccordionItem>
|
||||
</MalioAccordion>
|
||||
|
||||
<template #footer>
|
||||
<MalioButton
|
||||
variant="tertiary"
|
||||
:label="t('admin.products.filters.reset')"
|
||||
button-class="w-m-btn-action"
|
||||
@click="resetFilters"
|
||||
/>
|
||||
<MalioButton
|
||||
variant="primary"
|
||||
:label="t('admin.products.filters.apply')"
|
||||
button-class="w-[170px]"
|
||||
@click="applyFilters"
|
||||
/>
|
||||
</template>
|
||||
</MalioDrawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import type { Product } from '~/modules/catalog/types/product'
|
||||
|
||||
interface FilterOption {
|
||||
value: number
|
||||
label: string
|
||||
}
|
||||
|
||||
const { t } = useI18n()
|
||||
const api = useApi()
|
||||
const router = useRouter()
|
||||
const toast = useToast()
|
||||
const { can } = usePermissions()
|
||||
|
||||
useHead({ title: t('admin.products.title') })
|
||||
|
||||
// Catalogue produit admin-only (docx p.3) : « + Ajouter » reserve a `manage`.
|
||||
// « Filtrer » / « Exporter » suivent `view` (gate page-level). L'item sidebar
|
||||
// est deja masque cote back pour les roles sans `view` (RBAC § 5.2).
|
||||
const canManage = computed(() => can('catalog.products.manage'))
|
||||
const canView = computed(() => can('catalog.products.view'))
|
||||
|
||||
// Pagination serveur via le composable partage. Le ProductProvider applique
|
||||
// deja name ASC (§ 4.1) — pas de defaultSort cote front tant qu'aucun
|
||||
// OrderFilter n'est expose.
|
||||
const {
|
||||
items: products,
|
||||
totalItems,
|
||||
currentPage,
|
||||
itemsPerPage,
|
||||
itemsPerPageOptions,
|
||||
fetch: loadProducts,
|
||||
goToPage,
|
||||
setItemsPerPage,
|
||||
setFilters,
|
||||
} = usePaginatedList<Product>({ url: '/products' })
|
||||
|
||||
// Mappe les produits en objets « plats » pour MalioDataTable (items typees
|
||||
// Record<string, unknown>[]) : un objet litteral porte une signature d'index
|
||||
// implicite, contrairement a l'interface Product. Meme pattern que M1→M5.
|
||||
const rows = computed(() => products.value.map(product => ({
|
||||
id: product.id,
|
||||
name: product.name,
|
||||
code: product.code,
|
||||
categoryName: product.category?.name ?? '',
|
||||
})))
|
||||
|
||||
const columns = [
|
||||
{ key: 'name', label: t('admin.products.column.name') },
|
||||
{ key: 'code', label: t('admin.products.column.code') },
|
||||
{ key: 'categoryName', label: t('admin.products.column.category') },
|
||||
]
|
||||
|
||||
/** Clic sur une ligne → ecran d'edition (route imbriquee /admin/products/{id}/edit). */
|
||||
function onRowClick(item: Record<string, unknown>): void {
|
||||
router.push(`/admin/products/${item.id}/edit`)
|
||||
}
|
||||
|
||||
function goToCreate(): void {
|
||||
router.push('/admin/products/new')
|
||||
}
|
||||
|
||||
// ── Referentiels des filtres ─────────────────────────────────────────────────
|
||||
// Charges une fois (pagination desactivee, referentiels bornes). Categories
|
||||
// filtrees au type PRODUIT (RG-6.05) ; sites = tous les sites actifs.
|
||||
const categoryOptions = ref<FilterOption[]>([])
|
||||
const siteOptions = ref<FilterOption[]>([])
|
||||
|
||||
// Etats produit (miroir de l'enum back Product::STATE_*). Le libelle est resolu
|
||||
// par i18n. Select simple cote filtre (`?state=` n'accepte qu'une valeur).
|
||||
const PRODUCT_STATES = ['PURCHASE', 'SALE', 'OTHER'] as const
|
||||
|
||||
const stateOptions = computed(() =>
|
||||
PRODUCT_STATES.map(code => ({ value: code, label: t(`admin.products.state.${code}`) })),
|
||||
)
|
||||
|
||||
interface HydraMember { '@id': string, id: number, name?: string, postalCode?: string }
|
||||
|
||||
/** Recupere une collection complete (pagination desactivee) en Hydra. */
|
||||
async function fetchAll<T extends HydraMember>(
|
||||
url: string,
|
||||
query: Record<string, string> = {},
|
||||
): Promise<T[]> {
|
||||
const res = await api.get<{ member?: T[] }>(
|
||||
url,
|
||||
{ pagination: 'false', ...query },
|
||||
{ headers: { Accept: 'application/ld+json' }, toast: false },
|
||||
)
|
||||
return res.member ?? []
|
||||
}
|
||||
|
||||
/**
|
||||
* Charge les referentiels des filtres en parallele et de maniere resiliente :
|
||||
* un referentiel en echec (403/500) reste vide sans casser l'autre.
|
||||
*/
|
||||
async function loadFilterReferentials(): Promise<void> {
|
||||
await Promise.allSettled([
|
||||
fetchAll('/categories', { typeCode: 'PRODUIT' })
|
||||
.then((cats) => { categoryOptions.value = cats.map(c => ({ value: c.id, label: c.name ?? '' })) }),
|
||||
fetchAll('/sites')
|
||||
.then((sitesList) => { siteOptions.value = sitesList.map(s => ({ value: s.id, label: s.name ?? '' })) }),
|
||||
])
|
||||
}
|
||||
|
||||
// ── Filtres (drawer) ─────────────────────────────────────────────────────────
|
||||
// Deux niveaux d'etat (pattern repertoires M1→M5) :
|
||||
// - APPLIED : pilote la liste/l'export + le compteur du bouton. Modifie
|
||||
// uniquement au clic « Voir les résultats » / « Réinitialiser ».
|
||||
// - DRAFT : edite librement dans le drawer ; recopie vers applied a la validation.
|
||||
const filterDrawerOpen = ref(false)
|
||||
|
||||
const draftSearch = ref('')
|
||||
const draftCategoryId = ref<number | null>(null)
|
||||
const draftState = ref<string | null>(null)
|
||||
const draftSiteIds = ref<number[]>([])
|
||||
|
||||
const appliedSearch = ref('')
|
||||
const appliedCategoryId = ref<number | null>(null)
|
||||
const appliedState = ref<string | null>(null)
|
||||
const appliedSiteIds = ref<number[]>([])
|
||||
|
||||
const activeFilterCount = computed(() => {
|
||||
let count = 0
|
||||
if (appliedSearch.value.trim() !== '') count++
|
||||
if (appliedCategoryId.value !== null) count++
|
||||
if (appliedState.value !== null) count++
|
||||
if (appliedSiteIds.value.length > 0) count++
|
||||
return count
|
||||
})
|
||||
|
||||
const filterButtonLabel = computed(() => {
|
||||
const base = t('admin.products.filters.title')
|
||||
return activeFilterCount.value > 0 ? `${base} (${activeFilterCount.value})` : base
|
||||
})
|
||||
|
||||
// Recopie l'etat applique vers le brouillon puis ouvre le drawer : la reouverture
|
||||
// reflete les filtres actifs.
|
||||
function openFilters(): void {
|
||||
draftSearch.value = appliedSearch.value
|
||||
draftCategoryId.value = appliedCategoryId.value
|
||||
draftState.value = appliedState.value
|
||||
draftSiteIds.value = [...appliedSiteIds.value]
|
||||
filterDrawerOpen.value = true
|
||||
}
|
||||
|
||||
/** Coche / decoche un site dans le brouillon (filtre multi). */
|
||||
function toggleSite(id: number, selected: boolean): void {
|
||||
draftSiteIds.value = selected
|
||||
? [...draftSiteIds.value, id]
|
||||
: draftSiteIds.value.filter(s => s !== id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Construit le payload de filtres serveur a partir de l'etat applique. Cle
|
||||
* `siteId[]` pour que PHP la parse en tableau (OR cote back). Les filtres vides
|
||||
* sont omis pour une query propre.
|
||||
*/
|
||||
function buildFilterPayload(): Record<string, string | string[]> {
|
||||
const payload: Record<string, string | string[]> = {}
|
||||
if (appliedSearch.value.trim() !== '') payload.search = appliedSearch.value.trim()
|
||||
if (appliedCategoryId.value !== null) payload.categoryId = String(appliedCategoryId.value)
|
||||
if (appliedState.value !== null) payload.state = appliedState.value
|
||||
if (appliedSiteIds.value.length > 0) payload['siteId[]'] = appliedSiteIds.value.map(String)
|
||||
return payload
|
||||
}
|
||||
|
||||
// « Voir les résultats » : recopie brouillon → applied, pousse les filtres
|
||||
// (retombe en page 1 via usePaginatedList) et ferme le drawer.
|
||||
function applyFilters(): void {
|
||||
appliedSearch.value = draftSearch.value.trim()
|
||||
appliedCategoryId.value = draftCategoryId.value
|
||||
appliedState.value = draftState.value
|
||||
appliedSiteIds.value = [...draftSiteIds.value]
|
||||
|
||||
setFilters(buildFilterPayload(), { replace: true })
|
||||
filterDrawerOpen.value = false
|
||||
}
|
||||
|
||||
// « Réinitialiser » : vide brouillon ET applied, recharge la liste complete.
|
||||
// Le drawer reste ouvert pour montrer le formulaire vide.
|
||||
function resetFilters(): void {
|
||||
draftSearch.value = ''
|
||||
draftCategoryId.value = null
|
||||
draftState.value = null
|
||||
draftSiteIds.value = []
|
||||
|
||||
appliedSearch.value = ''
|
||||
appliedCategoryId.value = null
|
||||
appliedState.value = null
|
||||
appliedSiteIds.value = []
|
||||
|
||||
setFilters({}, { replace: true })
|
||||
}
|
||||
|
||||
// ── Export XLSX ──────────────────────────────────────────────────────────────
|
||||
// Memes filtres que la vue : l'export reflete exactement ce que l'utilisateur voit.
|
||||
const exporting = ref(false)
|
||||
|
||||
async function exportXlsx(): Promise<void> {
|
||||
if (exporting.value) {
|
||||
return
|
||||
}
|
||||
exporting.value = true
|
||||
try {
|
||||
// useApi type ses options en JSON ; l'export renvoie un binaire, donc on
|
||||
// force responseType:'blob' (transmis tel quel a ofetch au runtime). Cast
|
||||
// contenu faute d'overload blob sur le client partage (meme pattern M2→M5).
|
||||
const blob = await api.get<Blob>('/products/export.xlsx', buildFilterPayload(), {
|
||||
responseType: 'blob',
|
||||
toast: false,
|
||||
} as unknown as Parameters<typeof api.get>[2])
|
||||
|
||||
triggerDownload(blob, 'catalogue-produits.xlsx')
|
||||
}
|
||||
catch {
|
||||
toast.error({
|
||||
title: t('admin.products.toast.error'),
|
||||
message: t('admin.products.toast.exportError'),
|
||||
})
|
||||
}
|
||||
finally {
|
||||
exporting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Declenche le telechargement d'un blob via un lien temporaire. */
|
||||
function triggerDownload(blob: Blob, filename: string): void {
|
||||
const url = URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = filename
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadProducts()
|
||||
loadFilterReferentials()
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Types front du module Catalog (M6 — Catalogue produit).
|
||||
*
|
||||
* Contrats API consommes :
|
||||
* - GET /api/products → HydraCollection<Product>
|
||||
* - GET /api/products/{id} → Product
|
||||
* - GET /api/products/export.xlsx → binaire XLSX (export complet, filtres actifs)
|
||||
*
|
||||
* Notes (cf. spec-back § 4.0.bis, contrat JSON capture en ERP-203) :
|
||||
* - `category` est embarque (objet, pas IRI) ; idem `sites` / `storageTypes`
|
||||
* (tableaux d'objets bornes). On n'a besoin que de `category.name` en liste.
|
||||
* - `states` est un tableau de chaines (PURCHASE / SALE / OTHER).
|
||||
* - `skip_null_values` actif cote back : ne pas presumer la presence des nulls.
|
||||
*/
|
||||
|
||||
/** Type de categorie embarque dans `category.categoryTypes` (RG-6.05). */
|
||||
export interface ProductCategoryType {
|
||||
id: number
|
||||
code: string
|
||||
label: string
|
||||
}
|
||||
|
||||
/** Categorie embarquee dans un produit (lecture seule, sous-ensemble utile au front). */
|
||||
export interface ProductCategory {
|
||||
id: number
|
||||
name: string
|
||||
code: string
|
||||
categoryTypes?: ProductCategoryType[]
|
||||
}
|
||||
|
||||
/** Site de disponibilite embarque dans un produit (groupe `site:read`). */
|
||||
export interface ProductSite {
|
||||
id: number
|
||||
name: string
|
||||
code: string
|
||||
postalCode: string
|
||||
city: string
|
||||
color: string
|
||||
fullAddress: string
|
||||
}
|
||||
|
||||
/** Type de stockage embarque dans un produit (referentiel borne, § 2.4). */
|
||||
export interface ProductStorageType {
|
||||
id: number
|
||||
code: string
|
||||
label: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Produit metier — tel qu'il est lu depuis l'API. L'entite porte le pattern
|
||||
* Timestampable+Blamable (cf. spec-back § 2.8).
|
||||
*/
|
||||
export interface Product {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
/** Etats : sous-ensemble de PURCHASE / SALE / OTHER (RG-6.02). */
|
||||
states: string[]
|
||||
manufactured: boolean
|
||||
containsMolasses: boolean
|
||||
category: ProductCategory | null
|
||||
sites: ProductSite[]
|
||||
storageTypes: ProductStorageType[]
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
Reference in New Issue
Block a user