6 Commits

Author SHA1 Message Date
Matthieu
c7fd8328d6 fix(errors) : humanize backend error messages for end users
Add centralized error translation layer (humanizeError) that converts
raw Symfony/Doctrine/API Platform messages into user-friendly French.
Fix useApi to extract errors from all backend response formats
(violations, error, message, hydra:description, detail).
Add toast deduplication to prevent double display. Replace error toast
icon (X → CircleX) to distinguish from the dismiss button.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 09:48:51 +01:00
Matthieu
55e2a4fafe fix(navbar) : reorder nav groups and add lucide icons
- Reorder: Composants, Pieces, Produits (was Pieces, Produits, Composants)
- Add icons to all nav links and dropdown groups
- Dashboard, Factory, ClipboardList, Cpu, Puzzle, Package, Link

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 15:31:26 +01:00
Matthieu
e88ed5b8f2 feat(documents): migrate storage to filesystem, add server-side pagination
- Replace Base64 data URIs with file-based storage served via dedicated endpoints
- Add DocumentPreviewModal navigation, DocumentThumbnail fileUrl support
- Refactor documents page with server-side pagination, search, sort and filters
- Update all components to use fileUrl/downloadUrl instead of raw path
- Add pagination composable support (total, page, itemsPerPage, attachmentFilter)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 15:17:59 +01:00
Matthieu
546cc37a09 feat(catalog): add description column with hover popover + skeleton edit guard
- Add description column to pieces and component catalog tables
- Show full text in a popover on hover for truncated descriptions
- Block skeleton editing when machines are linked (warning alert)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 10:13:06 +01:00
Matthieu
efd0fbe407 feat(catalog) : add description textarea to piece and component forms
Add description field (textarea) between name and reference/fournisseur
on create and edit pages for both pieces and components.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 17:35:52 +01:00
Matthieu
607f84fc3d fix(sites): remove toRefs shadowing causing [object Object] in site name field 2026-03-02 16:33:30 +01:00
36 changed files with 942 additions and 351 deletions

View File

@@ -3,6 +3,7 @@
<DocumentPreviewModal <DocumentPreviewModal
:document="previewDocument" :document="previewDocument"
:visible="previewVisible" :visible="previewVisible"
:documents="componentDocuments"
@close="closePreview" @close="closePreview"
/> />
@@ -174,8 +175,8 @@
class="flex-shrink-0 overflow-hidden rounded-md border border-base-200 bg-base-200/70 flex items-center justify-center h-12 w-10" class="flex-shrink-0 overflow-hidden rounded-md border border-base-200 bg-base-200/70 flex items-center justify-center h-12 w-10"
> >
<img <img
v-if="isImageDocument(document) && document.path" v-if="isImageDocument(document) && (document.fileUrl || document.path)"
:src="document.path" :src="document.fileUrl || document.path"
class="h-full w-full object-cover" class="h-full w-full object-cover"
:alt="`Aperçu de ${document.name}`" :alt="`Aperçu de ${document.name}`"
> >
@@ -332,8 +333,8 @@
:class="documentThumbnailClass(document)" :class="documentThumbnailClass(document)"
> >
<img <img
v-if="isImageDocument(document) && document.path" v-if="isImageDocument(document) && (document.fileUrl || document.path)"
:src="document.path" :src="document.fileUrl || document.path"
class="h-full w-full object-cover" class="h-full w-full object-cover"
:alt="`Aperçu de ${document.name}`" :alt="`Aperçu de ${document.name}`"
> >

View File

@@ -10,9 +10,12 @@
<div class="min-w-0"> <div class="min-w-0">
<h3 class="font-bold text-xl truncate"> <h3 class="font-bold text-xl truncate">
Prévisualisation Prévisualisation
<span v-if="navTotal > 1" class="text-base font-normal text-gray-500">
{{ activeIndex + 1 }} / {{ navTotal }}
</span>
</h3> </h3>
<p class="text-sm text-gray-500 truncate"> <p class="text-sm text-gray-500 truncate">
{{ document?.name || document?.filename }}<span v-if="documentDescription"> {{ documentDescription }}</span> {{ activeDoc?.name || activeDoc?.filename }}<span v-if="documentDescription"> &bull; {{ documentDescription }}</span>
</p> </p>
</div> </div>
<button type="button" class="btn btn-ghost btn-sm shrink-0" @click="close"> <button type="button" class="btn btn-ghost btn-sm shrink-0" @click="close">
@@ -20,15 +23,35 @@
</button> </button>
</header> </header>
<section class="flex-1 bg-base-200/40 px-6 py-5 overflow-hidden"> <section class="flex-1 bg-base-200/40 px-6 py-5 overflow-hidden relative">
<button
v-if="hasPrev"
type="button"
class="absolute left-8 top-1/2 -translate-y-1/2 z-10 btn btn-circle bg-base-100/80 hover:bg-base-100 shadow-lg border-base-300"
title="Document précédent (←)"
@click="goToPrev"
>
</button>
<button
v-if="hasNext"
type="button"
class="absolute right-8 top-1/2 -translate-y-1/2 z-10 btn btn-circle bg-base-100/80 hover:bg-base-100 shadow-lg border-base-300"
title="Document suivant (→)"
@click="goToNext"
>
</button>
<div class="h-full w-full rounded-xl border border-base-300 bg-base-100 flex items-center justify-center overflow-hidden"> <div class="h-full w-full rounded-xl border border-base-300 bg-base-100 flex items-center justify-center overflow-hidden">
<template v-if="previewType === 'image'"> <template v-if="previewType === 'image'">
<img :src="document?.path" alt="preview" class="max-h-full max-w-full object-contain"> <img :src="documentSrc" alt="preview" class="max-h-full max-w-full object-contain">
</template> </template>
<template v-else-if="previewType === 'pdf'"> <template v-else-if="previewType === 'pdf'">
<iframe <iframe
:src="document?.path" :src="documentSrc"
class="w-full h-full bg-white" class="w-full h-full bg-white"
frameborder="0" frameborder="0"
title="Aperçu PDF" title="Aperçu PDF"
@@ -36,11 +59,11 @@
</template> </template>
<template v-else-if="previewType === 'audio'"> <template v-else-if="previewType === 'audio'">
<audio :src="document?.path" controls class="w-full" /> <audio :src="documentSrc" controls class="w-full" />
</template> </template>
<template v-else-if="previewType === 'video'"> <template v-else-if="previewType === 'video'">
<video :src="document?.path" controls class="w-full h-full bg-black" /> <video :src="documentSrc" controls class="w-full h-full bg-black" />
</template> </template>
<template v-else-if="previewType === 'text'"> <template v-else-if="previewType === 'text'">
@@ -80,31 +103,110 @@
</template> </template>
<script setup> <script setup>
import { ref, computed, watch } from 'vue' import { ref, computed, watch, onUnmounted } from 'vue'
import { getPreviewType, describeDocument } from '~/utils/documentPreview' import { getPreviewType, describeDocument, canPreviewDocument } from '~/utils/documentPreview'
const props = defineProps({ const props = defineProps({
document: { document: {
type: Object, type: Object,
default: null default: null,
}, },
visible: { visible: {
type: Boolean, type: Boolean,
default: false default: false,
} },
documents: {
type: Array,
default: () => [],
},
}) })
const emit = defineEmits(['close']) const emit = defineEmits(['close'])
const previewType = computed(() => getPreviewType(props.document)) // --- Carousel navigation ---
const documentDescription = computed(() => describeDocument(props.document))
const previewableDocuments = computed(() => {
if (!props.documents?.length) return []
return props.documents.filter((doc) => canPreviewDocument(doc))
})
const navTotal = computed(() => previewableDocuments.value.length)
const activeIndex = ref(0)
// Sync index when the parent changes the document prop (e.g. user clicks a different "Consulter")
watch(
() => props.document,
(doc) => {
if (!doc || !previewableDocuments.value.length) {
activeIndex.value = 0
return
}
const idx = previewableDocuments.value.findIndex((d) => d.id === doc.id)
activeIndex.value = idx >= 0 ? idx : 0
},
{ immediate: true },
)
const activeDoc = computed(() => {
if (previewableDocuments.value.length && activeIndex.value < previewableDocuments.value.length) {
return previewableDocuments.value[activeIndex.value]
}
return props.document
})
const hasPrev = computed(() => navTotal.value > 1 && activeIndex.value > 0)
const hasNext = computed(() => navTotal.value > 1 && activeIndex.value < navTotal.value - 1)
const goToPrev = () => {
if (hasPrev.value) activeIndex.value--
}
const goToNext = () => {
if (hasNext.value) activeIndex.value++
}
// Keyboard navigation
const handleKeydown = (e) => {
if (!props.visible) return
if (e.key === 'ArrowLeft') {
e.preventDefault()
goToPrev()
} else if (e.key === 'ArrowRight') {
e.preventDefault()
goToNext()
} else if (e.key === 'Escape') {
e.preventDefault()
close()
}
}
watch(
() => props.visible,
(val) => {
if (val) {
document.addEventListener('keydown', handleKeydown)
} else {
document.removeEventListener('keydown', handleKeydown)
}
},
)
onUnmounted(() => {
document.removeEventListener('keydown', handleKeydown)
})
// --- Preview logic (uses activeDoc) ---
const previewType = computed(() => getPreviewType(activeDoc.value))
const documentDescription = computed(() => describeDocument(activeDoc.value))
const documentSrc = computed(() => activeDoc.value?.fileUrl || activeDoc.value?.path || '')
const textContent = ref('') const textContent = ref('')
const textLoading = ref(false) const textLoading = ref(false)
const textError = ref('') const textError = ref('')
watch( watch(
() => props.document, activeDoc,
async (doc) => { async (doc) => {
textContent.value = '' textContent.value = ''
textError.value = '' textError.value = ''
@@ -115,22 +217,17 @@ watch(
try { try {
textLoading.value = true textLoading.value = true
const path = doc.path || '' const url = doc.fileUrl || doc.path || ''
if (path.startsWith('data:')) { if (!url) {
const base64Part = path.split(',')[1] || '' textError.value = 'Aucune URL de document disponible.'
if (!base64Part) { return
textError.value = 'Impossible de lire ce document texte.'
return
}
const decoded = atob(base64Part)
textContent.value = decodeURIComponent(escape(decoded))
} else {
const response = await fetch(path)
if (!response.ok) {
throw new Error('Téléchargement du document impossible')
}
textContent.value = await response.text()
} }
const response = await fetch(url, { credentials: 'include' })
if (!response.ok) {
throw new Error('Téléchargement du document impossible')
}
textContent.value = await response.text()
} catch (error) { } catch (error) {
console.error('Erreur lors du chargement du texte:', error) console.error('Erreur lors du chargement du texte:', error)
textError.value = error.message || 'Impossible de lire ce document.' textError.value = error.message || 'Impossible de lire ce document.'
@@ -138,7 +235,7 @@ watch(
textLoading.value = false textLoading.value = false
} }
}, },
{ immediate: true } { immediate: true },
) )
const close = () => { const close = () => {
@@ -146,11 +243,8 @@ const close = () => {
} }
const download = () => { const download = () => {
if (!props.document?.path) { return } const url = activeDoc.value?.downloadUrl || activeDoc.value?.fileUrl || activeDoc.value?.path
const link = document.createElement('a') if (!url) { return }
link.href = props.document.path window.open(url, '_blank')
link.download = props.document.filename || props.document.name || 'document'
link.target = '_blank'
link.click()
} }
</script> </script>

View File

@@ -40,6 +40,8 @@ type GenericDocument = {
filename?: string | null; filename?: string | null;
mimeType?: string | null; mimeType?: string | null;
path?: string | null; path?: string | null;
fileUrl?: string | null;
downloadUrl?: string | null;
size?: number | null; size?: number | null;
}; };
@@ -52,7 +54,7 @@ const normalizedDocument = computed(() => props.document ?? null);
const canRenderImage = computed(() => { const canRenderImage = computed(() => {
const doc = normalizedDocument.value; const doc = normalizedDocument.value;
return !!(doc && isImageDocument(doc) && doc.path); return !!(doc && isImageDocument(doc) && (doc.fileUrl || doc.path));
}); });
const canRenderPdf = computed(() => { const canRenderPdf = computed(() => {
@@ -73,13 +75,14 @@ const appendPdfViewerParams = (src: string) => {
const previewSrc = computed(() => { const previewSrc = computed(() => {
const doc = normalizedDocument.value; const doc = normalizedDocument.value;
if (!doc || !doc.path) { const url = doc?.fileUrl || doc?.path;
if (!doc || !url) {
return ''; return '';
} }
if (isPdfDocument(doc)) { if (isPdfDocument(doc)) {
return appendPdfViewerParams(doc.path); return appendPdfViewerParams(url);
} }
return doc.path; return url;
}); });
const thumbnailClass = computed(() => (canRenderImage.value || canRenderPdf.value ? 'h-20 w-16' : 'h-16 w-16')); const thumbnailClass = computed(() => (canRenderImage.value || canRenderPdf.value ? 'h-20 w-16' : 'h-16 w-16'));

View File

@@ -3,6 +3,7 @@
<DocumentPreviewModal <DocumentPreviewModal
:document="previewDocument" :document="previewDocument"
:visible="previewVisible" :visible="previewVisible"
:documents="pieceDocuments"
@close="closePreview" @close="closePreview"
/> />
@@ -184,8 +185,8 @@
class="flex-shrink-0 overflow-hidden rounded-md border border-base-200 bg-base-200/70 flex items-center justify-center h-10 w-8" class="flex-shrink-0 overflow-hidden rounded-md border border-base-200 bg-base-200/70 flex items-center justify-center h-10 w-8"
> >
<img <img
v-if="isImageDocument(document) && document.path" v-if="isImageDocument(document) && (document.fileUrl || document.path)"
:src="document.path" :src="document.fileUrl || document.path"
class="h-full w-full object-cover" class="h-full w-full object-cover"
:alt="`Aperçu de ${document.name}`" :alt="`Aperçu de ${document.name}`"
> >
@@ -413,8 +414,8 @@
:class="documentThumbnailClass(document)" :class="documentThumbnailClass(document)"
> >
<img <img
v-if="isImageDocument(document) && document.path" v-if="isImageDocument(document) && (document.fileUrl || document.path)"
:src="document.path" :src="document.fileUrl || document.path"
class="h-full w-full object-cover" class="h-full w-full object-cover"
:alt="`Aperçu de ${document.name}`" :alt="`Aperçu de ${document.name}`"
> >

View File

@@ -24,7 +24,7 @@
class="w-4 h-4" class="w-4 h-4"
aria-hidden="true" aria-hidden="true"
/> />
<IconLucideX <IconLucideCircleX
v-else-if="toast.type === 'error'" v-else-if="toast.type === 'error'"
class="w-4 h-4" class="w-4 h-4"
aria-hidden="true" aria-hidden="true"
@@ -64,6 +64,7 @@
import { useToast } from '~/composables/useToast' import { useToast } from '~/composables/useToast'
import IconLucideCheck from '~icons/lucide/check' import IconLucideCheck from '~icons/lucide/check'
import IconLucideX from '~icons/lucide/x' import IconLucideX from '~icons/lucide/x'
import IconLucideCircleX from '~icons/lucide/circle-x'
import IconLucideAlertTriangle from '~icons/lucide/alert-triangle' import IconLucideAlertTriangle from '~icons/lucide/alert-triangle'
import IconLucideInfo from '~icons/lucide/info' import IconLucideInfo from '~icons/lucide/info'

View File

@@ -24,9 +24,10 @@
<li v-for="link in simpleLinks" :key="link.to"> <li v-for="link in simpleLinks" :key="link.to">
<NuxtLink <NuxtLink
:to="link.to" :to="link.to"
class="rounded-md px-2 py-1 transition-colors" class="rounded-md px-2 py-1 transition-colors flex items-center gap-2"
:class="linkClass(link)" :class="linkClass(link)"
> >
<component :is="link.icon" v-if="link.icon" class="w-4 h-4" aria-hidden="true" />
{{ link.label }} {{ link.label }}
</NuxtLink> </NuxtLink>
</li> </li>
@@ -46,7 +47,10 @@
@keydown.enter.prevent="toggleDropdown(group.id + '-mobile')" @keydown.enter.prevent="toggleDropdown(group.id + '-mobile')"
@keydown.space.prevent="toggleDropdown(group.id + '-mobile')" @keydown.space.prevent="toggleDropdown(group.id + '-mobile')"
> >
<span>{{ group.label }}</span> <span class="flex items-center gap-2">
<component :is="group.icon" v-if="group.icon" class="w-4 h-4" aria-hidden="true" />
{{ group.label }}
</span>
<IconLucideChevronRight <IconLucideChevronRight
class="h-4 w-4 transition-transform" class="h-4 w-4 transition-transform"
:class="openDropdown === group.id + '-mobile' ? 'rotate-90' : ''" :class="openDropdown === group.id + '-mobile' ? 'rotate-90' : ''"
@@ -100,9 +104,10 @@
<li v-for="link in simpleLinks" :key="link.to"> <li v-for="link in simpleLinks" :key="link.to">
<NuxtLink <NuxtLink
:to="link.to" :to="link.to"
class="transition-colors px-3 py-2 rounded-md" class="transition-colors px-3 py-2 rounded-md flex items-center gap-1.5"
:class="linkClass(link)" :class="linkClass(link)"
> >
<component :is="link.icon" v-if="link.icon" class="w-4 h-4" aria-hidden="true" />
{{ link.label }} {{ link.label }}
</NuxtLink> </NuxtLink>
</li> </li>
@@ -119,13 +124,14 @@
> >
<button <button
type="button" type="button"
class="inline-flex items-center gap-1 rounded-md px-3 py-2 transition-colors" class="inline-flex items-center gap-1.5 rounded-md px-3 py-2 transition-colors"
:class="groupClass(group)" :class="groupClass(group)"
:aria-expanded="openDropdown === group.id + '-desktop'" :aria-expanded="openDropdown === group.id + '-desktop'"
@click="toggleDropdown(group.id + '-desktop')" @click="toggleDropdown(group.id + '-desktop')"
@keydown.enter.prevent="toggleDropdown(group.id + '-desktop')" @keydown.enter.prevent="toggleDropdown(group.id + '-desktop')"
@keydown.space.prevent="toggleDropdown(group.id + '-desktop')" @keydown.space.prevent="toggleDropdown(group.id + '-desktop')"
> >
<component :is="group.icon" v-if="group.icon" class="w-4 h-4" aria-hidden="true" />
{{ group.label }} {{ group.label }}
<IconLucideChevronRight <IconLucideChevronRight
class="h-4 w-4 transition-transform" class="h-4 w-4 transition-transform"
@@ -233,7 +239,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue' import { ref, computed, onMounted, onBeforeUnmount, type Component } from 'vue'
import { useRoute } from '#imports' import { useRoute } from '#imports'
import { useNavDropdown } from '~/composables/useNavDropdown' import { useNavDropdown } from '~/composables/useNavDropdown'
import { usePermissions } from '~/composables/usePermissions' import { usePermissions } from '~/composables/usePermissions'
@@ -243,6 +249,13 @@ import IconLucideMenu from '~icons/lucide/menu'
import IconLucideSettings from '~icons/lucide/settings' import IconLucideSettings from '~icons/lucide/settings'
import IconLucideChevronRight from '~icons/lucide/chevron-right' import IconLucideChevronRight from '~icons/lucide/chevron-right'
import IconLucideLogOut from '~icons/lucide/log-out' import IconLucideLogOut from '~icons/lucide/log-out'
import IconLucideLayoutDashboard from '~icons/lucide/layout-dashboard'
import IconLucideFactory from '~icons/lucide/factory'
import IconLucideClipboardList from '~icons/lucide/clipboard-list'
import IconLucideCpu from '~icons/lucide/cpu'
import IconLucidePuzzle from '~icons/lucide/puzzle'
import IconLucidePackage from '~icons/lucide/package'
import IconLucideLink from '~icons/lucide/link'
import logoSrc from '~/assets/LOGO_CARRE_BLANC.png' import logoSrc from '~/assets/LOGO_CARRE_BLANC.png'
defineEmits<{ defineEmits<{
@@ -253,25 +266,38 @@ defineEmits<{
interface NavLink { interface NavLink {
to: string to: string
label: string label: string
icon?: Component
} }
interface NavGroup { interface NavGroup {
id: string id: string
label: string label: string
icon?: Component
activePaths: string[] activePaths: string[]
children: NavLink[] children: NavLink[]
} }
const simpleLinks: NavLink[] = [ const simpleLinks: NavLink[] = [
{ to: '/', label: 'Vue d\'ensemble' }, { to: '/', label: 'Vue d\'ensemble', icon: IconLucideLayoutDashboard },
{ to: '/machines', label: 'Parc Machines' }, { to: '/machines', label: 'Parc Machines', icon: IconLucideFactory },
{ to: '/machine-skeleton', label: 'Squelettes de machine' }, { to: '/machine-skeleton', label: 'Squelettes', icon: IconLucideClipboardList },
] ]
const navGroups: NavGroup[] = [ const navGroups: NavGroup[] = [
{
id: 'component',
label: 'Composants',
icon: IconLucideCpu,
activePaths: ['/component-category', '/component-catalog'],
children: [
{ to: '/component-catalog', label: 'Catalogue des composants' },
{ to: '/component-category', label: 'Catégorie de composant' },
],
},
{ {
id: 'pieces', id: 'pieces',
label: 'Pièces', label: 'Pièces',
icon: IconLucidePuzzle,
activePaths: ['/piece-category', '/pieces-catalog'], activePaths: ['/piece-category', '/pieces-catalog'],
children: [ children: [
{ to: '/pieces-catalog', label: 'Catalogue des pièces' }, { to: '/pieces-catalog', label: 'Catalogue des pièces' },
@@ -281,24 +307,17 @@ const navGroups: NavGroup[] = [
{ {
id: 'products', id: 'products',
label: 'Produits', label: 'Produits',
icon: IconLucidePackage,
activePaths: ['/product-category', '/product-catalog'], activePaths: ['/product-category', '/product-catalog'],
children: [ children: [
{ to: '/product-catalog', label: 'Catalogue des produits' }, { to: '/product-catalog', label: 'Catalogue des produits' },
{ to: '/product-category', label: 'Catégorie de produit' }, { to: '/product-category', label: 'Catégorie de produit' },
], ],
}, },
{
id: 'component',
label: 'Composant',
activePaths: ['/component-category', '/component-catalog'],
children: [
{ to: '/component-catalog', label: 'Catalogue des composants' },
{ to: '/component-category', label: 'Catégorie de composant' },
],
},
{ {
id: 'resources', id: 'resources',
label: 'Ressources liées', label: 'Ressources liées',
icon: IconLucideLink,
activePaths: ['/sites', '/documents', '/constructeurs', '/activity-log', '/comments'], activePaths: ['/sites', '/documents', '/constructeurs', '/activity-log', '/comments'],
children: [ children: [
{ to: '/sites', label: 'Sites' }, { to: '/sites', label: 'Sites' },

View File

@@ -32,8 +32,8 @@
:class="documentThumbnailClass(doc)" :class="documentThumbnailClass(doc)"
> >
<img <img
v-if="isImageDocument(doc) && doc.path" v-if="isImageDocument(doc) && (doc.fileUrl || doc.path)"
:src="doc.path" :src="doc.fileUrl || doc.path"
class="h-full w-full object-cover" class="h-full w-full object-cover"
:alt="`Aperçu de ${doc.name}`" :alt="`Aperçu de ${doc.name}`"
> >

View File

@@ -119,6 +119,7 @@ import {
type ModelTypeListResponse, type ModelTypeListResponse,
} from "~/services/modelTypes"; } from "~/services/modelTypes";
import { useToast } from "~/composables/useToast"; import { useToast } from "~/composables/useToast";
import { humanizeError } from "~/shared/utils/errorMessages";
import { invalidateEntityTypeCache } from "~/composables/useEntityTypes"; import { invalidateEntityTypeCache } from "~/composables/useEntityTypes";
const DEFAULT_DESCRIPTION = const DEFAULT_DESCRIPTION =
@@ -183,7 +184,8 @@ useHead(() => ({
title: headingText.value, title: headingText.value,
})); }));
const extractErrorMessage = (error: unknown) => { const extractErrorMessage = (error: unknown): string => {
let raw: string | null = null;
if (error && typeof error === "object") { if (error && typeof error === "object") {
const maybeFetchError = error as { const maybeFetchError = error as {
data?: Record<string, unknown>; data?: Record<string, unknown>;
@@ -192,21 +194,16 @@ const extractErrorMessage = (error: unknown) => {
}; };
if (maybeFetchError.data) { if (maybeFetchError.data) {
const data = maybeFetchError.data; const data = maybeFetchError.data;
if (typeof data.message === "string") { if (typeof data['hydra:description'] === "string") raw = data['hydra:description'];
return data.message; else if (typeof data.detail === "string") raw = data.detail;
} else if (typeof data.message === "string") raw = data.message;
if (Array.isArray(data.message) && data.message.length > 0) { else if (Array.isArray(data.message) && data.message.length > 0) raw = data.message[0];
return data.message[0]; else if (typeof data.error === "string") raw = data.error;
}
}
if (typeof maybeFetchError.statusMessage === "string") {
return maybeFetchError.statusMessage;
}
if (typeof maybeFetchError.message === "string") {
return maybeFetchError.message;
} }
if (!raw && typeof maybeFetchError.statusMessage === "string") raw = maybeFetchError.statusMessage;
if (!raw && typeof maybeFetchError.message === "string") raw = maybeFetchError.message;
} }
return "Une erreur est survenue lors de la communication avec le serveur."; return humanizeError(raw);
}; };
const refresh = async ({ const refresh = async ({

View File

@@ -57,8 +57,8 @@
<div class="flex items-center gap-3 text-sm"> <div class="flex items-center gap-3 text-sm">
<div class="h-14 w-14 flex-shrink-0 overflow-hidden rounded-md border border-base-200 bg-base-200/70 flex items-center justify-center"> <div class="h-14 w-14 flex-shrink-0 overflow-hidden rounded-md border border-base-200 bg-base-200/70 flex items-center justify-center">
<img <img
v-if="isImageDocument(document) && document.path" v-if="isImageDocument(document) && (document.fileUrl || document.path)"
:src="document.path" :src="document.fileUrl || document.path"
class="h-full w-full object-cover" class="h-full w-full object-cover"
:alt="`Aperçu de ${document.name}`" :alt="`Aperçu de ${document.name}`"
> >
@@ -116,7 +116,7 @@
</template> </template>
<script setup> <script setup>
import { computed, toRefs } from 'vue' import { computed } from 'vue'
import { isImageDocument } from '~/utils/documentPreview' import { isImageDocument } from '~/utils/documentPreview'
import DocumentUpload from '~/components/DocumentUpload.vue' import DocumentUpload from '~/components/DocumentUpload.vue'
import SiteContactFormFields from '~/components/sites/SiteContactFormFields.vue' import SiteContactFormFields from '~/components/sites/SiteContactFormFields.vue'
@@ -173,8 +173,6 @@ const emit = defineEmits([
'update:selectedFiles' 'update:selectedFiles'
]) ])
const form = toRefs(props.form)
const selectedFilesModel = computed({ const selectedFilesModel = computed({
get: () => props.selectedFiles, get: () => props.selectedFiles,
set: value => emit('update:selectedFiles', value) set: value => emit('update:selectedFiles', value)

View File

@@ -1,4 +1,5 @@
import { useToast } from './useToast' import { useToast } from './useToast'
import { humanizeError, extractApiErrorMessage } from '~/shared/utils/errorMessages'
export interface ApiResponse<T = any> { export interface ApiResponse<T = any> {
success: boolean success: boolean
@@ -20,11 +21,10 @@ export function useApi() {
const apiCall = async <T = any>(endpoint: string, options: ApiCallOptions = {}): Promise<ApiResponse<T>> => { const apiCall = async <T = any>(endpoint: string, options: ApiCallOptions = {}): Promise<ApiResponse<T>> => {
const url = `${API_BASE_URL}${endpoint}` const url = `${API_BASE_URL}${endpoint}`
const isFormData = options.body instanceof FormData
const defaultOptions: ApiCallOptions = { const defaultOptions: ApiCallOptions = {
credentials: 'include', credentials: 'include',
headers: { headers: isFormData ? {} : { 'Content-Type': 'application/json' },
'Content-Type': 'application/json',
},
} }
// Ajouter un timeout à la requête // Ajouter un timeout à la requête
@@ -60,23 +60,26 @@ export function useApi() {
} else { } else {
const contentType = response.headers.get('content-type') || '' const contentType = response.headers.get('content-type') || ''
let errorData: Record<string, unknown> = {} let errorData: Record<string, unknown> = {}
if (contentType.includes('application/json')) { if (contentType.includes('json')) {
errorData = await response.json().catch(() => ({})) errorData = await response.json().catch(() => ({}))
} else { } else {
const text = await response.text().catch(() => '') const text = await response.text().catch(() => '')
errorData = text ? { message: text } : {} errorData = text ? { message: text } : {}
} }
const errorMessage = response.status === 403 const rawMessage = response.status === 403
? 'Permissions insuffisantes pour cette action.' ? 'Permissions insuffisantes pour cette action.'
: (errorData.message as string) || `Erreur ${response.status}: ${response.statusText}` : extractApiErrorMessage(errorData) || `Erreur ${response.status}: ${response.statusText}`
const errorMessage = humanizeError(rawMessage)
showError(errorMessage) showError(errorMessage)
return { success: false, error: errorMessage, status: response.status } return { success: false, error: errorMessage, status: response.status }
} }
} catch (error) { } catch (error) {
clearTimeout(timeoutId) clearTimeout(timeoutId)
const err = error as Error & { name?: string } const err = error as Error & { name?: string }
const errorMessage = err.name === 'AbortError' ? 'Timeout de la requête' : err.message || 'Erreur réseau' const errorMessage = err.name === 'AbortError'
showError(`Erreur réseau: ${errorMessage}`) ? 'La requête a pris trop de temps. Veuillez réessayer.'
: 'Impossible de contacter le serveur. Vérifiez votre connexion.'
showError(errorMessage)
return { success: false, error: errorMessage } return { success: false, error: errorMessage }
} }
} }
@@ -115,6 +118,13 @@ export function useApi() {
}) })
} }
const postFormData = async <T = any>(endpoint: string, formData: FormData): Promise<ApiResponse<T>> => {
return apiCall<T>(endpoint, {
method: 'POST',
body: formData,
})
}
const del = async <T = any>(endpoint: string): Promise<ApiResponse<T>> => { const del = async <T = any>(endpoint: string): Promise<ApiResponse<T>> => {
return apiCall<T>(endpoint, { method: 'DELETE' }) return apiCall<T>(endpoint, { method: 'DELETE' })
} }
@@ -123,6 +133,7 @@ export function useApi() {
apiCall, apiCall,
get, get,
post, post,
postFormData,
patch, patch,
put, put,
delete: del, delete: del,

View File

@@ -10,6 +10,7 @@ export interface Composant {
id: string id: string
name: string name: string
reference?: string | null reference?: string | null
description?: string | null
typeComposantId?: string | null typeComposantId?: string | null
typeComposant?: { id: string; name?: string } | null typeComposant?: { id: string; name?: string } | null
productId?: string | null productId?: string | null

View File

@@ -1,7 +1,6 @@
import { ref } from 'vue' import { ref } from 'vue'
import { useApi } from './useApi' import { useApi } from './useApi'
import { useToast } from './useToast' import { useToast } from './useToast'
import { normalizeRelationIds } from '~/shared/apiRelations'
import { extractCollection } from '~/shared/utils/apiHelpers' import { extractCollection } from '~/shared/utils/apiHelpers'
export interface Document { export interface Document {
@@ -10,12 +9,21 @@ export interface Document {
filename: string filename: string
mimeType: string mimeType: string
size: number size: number
path: string fileUrl: string
downloadUrl: string
/** @deprecated Legacy Base64 data URI — use fileUrl instead */
path?: string
createdAt?: string
siteId?: string siteId?: string
machineId?: string machineId?: string
composantId?: string composantId?: string
productId?: string productId?: string
pieceId?: string pieceId?: string
site?: { id: string; name?: string } | null
machine?: { id: string; name?: string } | null
composant?: { id: string; name?: string } | null
piece?: { id: string; name?: string } | null
product?: { id: string; name?: string } | null
} }
export interface UploadContext { export interface UploadContext {
@@ -32,19 +40,30 @@ export interface DocumentResult {
error?: string error?: string
} }
const documents = ref<Document[]>([]) interface LoadDocumentsOptions {
const loading = ref(false) search?: string
page?: number
itemsPerPage?: number
orderBy?: string
orderDir?: 'asc' | 'desc'
attachmentFilter?: string
force?: boolean
}
const fileToBase64 = (file: File): Promise<string> => const documents = ref<Document[]>([])
new Promise((resolve, reject) => { const total = ref(0)
const reader = new FileReader() const loading = ref(false)
reader.onload = () => resolve(reader.result as string) const loaded = ref(false)
reader.onerror = () => reject(new Error(`Lecture du fichier ${file.name} impossible`))
reader.readAsDataURL(file) const extractTotal = (payload: unknown, fallbackLength: number): number => {
}) const p = payload as Record<string, unknown> | null
if (typeof p?.totalItems === 'number') return p.totalItems
if (typeof p?.['hydra:totalItems'] === 'number') return p['hydra:totalItems']
return fallbackLength
}
export function useDocuments() { export function useDocuments() {
const { get, post, delete: del } = useApi() const { get, postFormData, delete: del } = useApi()
const { showError, showSuccess } = useToast() const { showError, showSuccess } = useToast()
const loadFromEndpoint = async ( const loadFromEndpoint = async (
@@ -76,10 +95,61 @@ export function useDocuments() {
} }
} }
const loadDocuments = async ( const loadDocuments = async (options: LoadDocumentsOptions = {}): Promise<DocumentResult> => {
options: { updateStore?: boolean; itemsPerPage?: number } = {}, const {
): Promise<DocumentResult> => { search = '',
return loadFromEndpoint('/documents', { updateStore: options.updateStore ?? true, itemsPerPage: options.itemsPerPage }) page = 1,
itemsPerPage = 30,
orderBy = 'createdAt',
orderDir = 'desc',
attachmentFilter = 'all',
force = false,
} = options
if (!force && loaded.value && !search && page === 1 && attachmentFilter === 'all') {
return { success: true, data: documents.value }
}
if (loading.value) {
return { success: true, data: documents.value }
}
loading.value = true
try {
const params = new URLSearchParams()
params.set('itemsPerPage', String(itemsPerPage))
params.set('page', String(page))
if (search && search.trim()) {
params.set('name', search.trim())
}
if (attachmentFilter && attachmentFilter !== 'all') {
params.set(`exists[${attachmentFilter}]`, 'true')
}
params.set(`order[${orderBy}]`, orderDir)
const result = await get(`/documents?${params.toString()}`)
if (result.success) {
const items = extractCollection(result.data)
documents.value = items
total.value = extractTotal(result.data, items.length)
loaded.value = true
return { success: true, data: items }
}
if (result.error) {
showError(result.error)
}
return result as DocumentResult
} catch (error) {
const err = error as Error
console.error('Erreur lors du chargement des documents:', error)
showError('Impossible de charger les documents')
return { success: false, error: err.message }
} finally {
loading.value = false
}
} }
const loadDocumentsBySite = async ( const loadDocumentsBySite = async (
@@ -145,18 +215,17 @@ export function useDocuments() {
try { try {
for (const file of files) { for (const file of files) {
const dataUrl = await fileToBase64(file) const formData = new FormData()
formData.append('file', file)
formData.append('name', file.name)
const payload = normalizeRelationIds({ if (context.siteId) formData.append('siteId', context.siteId)
name: file.name, if (context.machineId) formData.append('machineId', context.machineId)
filename: file.name, if (context.composantId) formData.append('composantId', context.composantId)
mimeType: file.type || 'application/octet-stream', if (context.productId) formData.append('productId', context.productId)
size: file.size, if (context.pieceId) formData.append('pieceId', context.pieceId)
path: dataUrl,
...context,
})
const result = await post('/documents', payload) const result = await postFormData('/documents', formData)
if (result.success) { if (result.success) {
created.push(result.data as Document) created.push(result.data as Document)
showSuccess(`Document "${file.name}" ajouté`) showSuccess(`Document "${file.name}" ajouté`)
@@ -213,7 +282,9 @@ export function useDocuments() {
return { return {
documents, documents,
total,
loading, loading,
loaded,
loadDocuments, loadDocuments,
loadDocumentsBySite, loadDocumentsBySite,
loadDocumentsByMachine, loadDocumentsByMachine,

View File

@@ -7,6 +7,7 @@
import { ref, type Ref } from 'vue' import { ref, type Ref } from 'vue'
import { useToast } from './useToast' import { useToast } from './useToast'
import { humanizeError } from '~/shared/utils/errorMessages'
import { import {
listModelTypes, listModelTypes,
createModelType, createModelType,
@@ -102,8 +103,8 @@ export function useEntityTypes(config: EntityTypeConfig) {
return { success: true, data: state.types.value } return { success: true, data: state.types.value }
} catch (error) { } catch (error) {
const err = error as Error & { message?: string } const err = error as Error & { message?: string }
const message = err?.message || 'Erreur inconnue' const message = humanizeError(err?.message)
showError(`Impossible de charger les types de ${label}: ${message}`) showError(`Impossible de charger les types de ${label}.`)
return { success: false, error: message } return { success: false, error: message }
} finally { } finally {
state.loading.value = false state.loading.value = false
@@ -127,8 +128,9 @@ export function useEntityTypes(config: EntityTypeConfig) {
return { success: true, data: normalized } return { success: true, data: normalized }
} catch (error) { } catch (error) {
const err = error as Error & { data?: { message?: string }; message?: string } const err = error as Error & { data?: { message?: string }; message?: string }
const message = err?.data?.message || err?.message || 'Erreur inconnue' const raw = err?.data?.message || err?.message
showError(`Erreur lors de la création du type de ${label}: ${message}`) const message = humanizeError(raw)
showError(`Impossible de créer le type de ${label} : ${message}`)
return { success: false, error: message } return { success: false, error: message }
} finally { } finally {
state.loading.value = false state.loading.value = false
@@ -152,8 +154,9 @@ export function useEntityTypes(config: EntityTypeConfig) {
return { success: true, data: normalized } return { success: true, data: normalized }
} catch (error) { } catch (error) {
const err = error as Error & { data?: { message?: string }; message?: string } const err = error as Error & { data?: { message?: string }; message?: string }
const message = err?.data?.message || err?.message || 'Erreur inconnue' const raw = err?.data?.message || err?.message
showError(`Erreur lors de la mise à jour du type de ${label}: ${message}`) const message = humanizeError(raw)
showError(`Impossible de mettre à jour le type de ${label} : ${message}`)
return { success: false, error: message } return { success: false, error: message }
} finally { } finally {
state.loading.value = false state.loading.value = false
@@ -169,8 +172,9 @@ export function useEntityTypes(config: EntityTypeConfig) {
return { success: true } return { success: true }
} catch (error) { } catch (error) {
const err = error as Error & { data?: { message?: string }; message?: string } const err = error as Error & { data?: { message?: string }; message?: string }
const message = err?.data?.message || err?.message || 'Erreur inconnue' const raw = err?.data?.message || err?.message
showError(`Erreur lors de la suppression du type de ${label}: ${message}`) const message = humanizeError(raw)
showError(`Impossible de supprimer le type de ${label} : ${message}`)
return { success: false, error: message } return { success: false, error: message }
} finally { } finally {
state.loading.value = false state.loading.value = false

View File

@@ -15,6 +15,7 @@ import { usePieces } from '~/composables/usePieces'
import { useProducts } from '~/composables/useProducts' import { useProducts } from '~/composables/useProducts'
import { useApi } from '~/composables/useApi' import { useApi } from '~/composables/useApi'
import { useToast } from '~/composables/useToast' import { useToast } from '~/composables/useToast'
import { humanizeError } from '~/shared/utils/errorMessages'
import { useMachineCreateSelections } from '~/composables/useMachineCreateSelections' import { useMachineCreateSelections } from '~/composables/useMachineCreateSelections'
import { import {
useMachineCreatePreview, useMachineCreatePreview,
@@ -365,10 +366,10 @@ export function useMachineCreatePage() {
clearRequirementSelections() clearRequirementSelections()
await navigateTo('/machines') await navigateTo('/machines')
} else if (result.error) { } else if (result.error) {
toast.showError(`Impossible de créer la machine: ${result.error}`) toast.showError(`Impossible de créer la machine : ${humanizeError(result.error)}`)
} }
} catch (error: any) { } catch (error: any) {
toast.showError(`Erreur lors de la création: ${error.message}`) toast.showError(`Impossible de créer la machine : ${humanizeError(error.message)}`)
} finally { } finally {
submitting.value = false submitting.value = false
} }

View File

@@ -10,6 +10,7 @@ export interface Piece {
id: string id: string
name: string name: string
reference?: string | null reference?: string | null
description?: string | null
typePieceId?: string | null typePieceId?: string | null
typePiece?: { id: string; name?: string } | null typePiece?: { id: string; name?: string } | null
productId?: string | null productId?: string | null

View File

@@ -1,6 +1,7 @@
import { ref } from 'vue' import { ref } from 'vue'
import { useToast } from './useToast' import { useToast } from './useToast'
import { useApi } from './useApi' import { useApi } from './useApi'
import { humanizeError } from '~/shared/utils/errorMessages'
import { buildConstructeurRequestPayload, uniqueConstructeurIds } from '~/shared/constructeurUtils' import { buildConstructeurRequestPayload, uniqueConstructeurIds } from '~/shared/constructeurUtils'
import { useConstructeurs, type Constructeur } from './useConstructeurs' import { useConstructeurs, type Constructeur } from './useConstructeurs'
import { extractRelationId, normalizeRelationIds } from '~/shared/apiRelations' import { extractRelationId, normalizeRelationIds } from '~/shared/apiRelations'
@@ -168,9 +169,9 @@ export function useProducts() {
return result as ProductListResult return result as ProductListResult
} catch (err) { } catch (err) {
console.error('Erreur lors du chargement des produits:', err) console.error('Erreur lors du chargement des produits:', err)
const message = (err as Error)?.message ?? 'Erreur inconnue' const message = humanizeError((err as Error)?.message)
error.value = message error.value = message
showError(`Impossible de charger les produits: ${message}`) showError(`Impossible de charger les produits.`)
return { success: false, error: message } return { success: false, error: message }
} finally { } finally {
loading.value = false loading.value = false
@@ -197,9 +198,9 @@ export function useProducts() {
return { success: false, error: result.error } return { success: false, error: result.error }
} catch (err) { } catch (err) {
console.error('Erreur lors de la création du produit:', err) console.error('Erreur lors de la création du produit:', err)
const message = (err as Error)?.message ?? 'Erreur inconnue' const message = humanizeError((err as Error)?.message)
error.value = message error.value = message
showError(message) showError('Impossible de créer le produit.')
return { success: false, error: message } return { success: false, error: message }
} finally { } finally {
loading.value = false loading.value = false
@@ -223,9 +224,9 @@ export function useProducts() {
return { success: false, error: result.error } return { success: false, error: result.error }
} catch (err) { } catch (err) {
console.error('Erreur lors de la mise à jour du produit:', err) console.error('Erreur lors de la mise à jour du produit:', err)
const message = (err as Error)?.message ?? 'Erreur inconnue' const message = humanizeError((err as Error)?.message)
error.value = message error.value = message
showError(message) showError('Impossible de mettre à jour le produit.')
return { success: false, error: message } return { success: false, error: message }
} finally { } finally {
loading.value = false loading.value = false
@@ -248,9 +249,9 @@ export function useProducts() {
return { success: false, error: result.error } return { success: false, error: result.error }
} catch (err) { } catch (err) {
console.error('Erreur lors de la suppression du produit:', err) console.error('Erreur lors de la suppression du produit:', err)
const message = (err as Error)?.message ?? 'Erreur inconnue' const message = humanizeError((err as Error)?.message)
error.value = message error.value = message
showError(message) showError('Impossible de supprimer le produit.')
return { success: false, error: message } return { success: false, error: message }
} finally { } finally {
loading.value = false loading.value = false

View File

@@ -2,6 +2,7 @@ import { computed, onMounted, reactive, ref, watch } from 'vue'
import { navigateTo, useRoute } from '#imports' import { navigateTo, useRoute } from '#imports'
import { useSites } from '~/composables/useSites' import { useSites } from '~/composables/useSites'
import { useToast } from '~/composables/useToast' import { useToast } from '~/composables/useToast'
import { humanizeError } from '~/shared/utils/errorMessages'
import { useDocuments } from '~/composables/useDocuments' import { useDocuments } from '~/composables/useDocuments'
import { useConfirm } from '~/composables/useConfirm' import { useConfirm } from '~/composables/useConfirm'
import { getFileIcon } from '~/utils/fileIcons' import { getFileIcon } from '~/utils/fileIcons'
@@ -23,6 +24,8 @@ type SiteDocument = {
mimeType?: string mimeType?: string
size?: number size?: number
path?: string path?: string
fileUrl?: string
downloadUrl?: string
} }
type SiteWithDocuments = { type SiteWithDocuments = {
@@ -209,17 +212,23 @@ export function useSiteManagement() {
} }
const downloadDocument = (doc: SiteDocument) => { const downloadDocument = (doc: SiteDocument) => {
if (!doc?.path) return if (doc?.downloadUrl) {
window.open(doc.downloadUrl, '_blank')
return
}
if (doc.path.startsWith('data:')) { const url = doc?.fileUrl || doc?.path
if (!url) return
if (url.startsWith('data:')) {
const link = document.createElement('a') const link = document.createElement('a')
link.href = doc.path link.href = url
link.download = doc.filename || doc.name || 'document' link.download = doc.filename || doc.name || 'document'
link.click() link.click()
return return
} }
window.open(doc.path, '_blank') window.open(url, '_blank')
} }
const openPreview = (doc: SiteDocument) => { const openPreview = (doc: SiteDocument) => {
@@ -266,10 +275,10 @@ export function useSiteManagement() {
if (result.success) { if (result.success) {
showSuccess(`Site "${site.name}" supprimé avec succès`) showSuccess(`Site "${site.name}" supprimé avec succès`)
} else { } else {
showError(`Erreur lors de la suppression: ${result.error}`) showError(`Impossible de supprimer le site : ${humanizeError(result.error)}`)
} }
} catch (error: any) { } catch (error: any) {
showError(`Erreur lors de la suppression: ${error.message}`) showError(`Impossible de supprimer le site : ${humanizeError(error.message)}`)
} }
} }

View File

@@ -13,8 +13,19 @@ const toasts = ref<Toast[]>([])
const MAX_TOASTS = 3 const MAX_TOASTS = 3
let nextId = 1 let nextId = 1
// Anti-doublon : ignore un toast identique affiché dans les 2 dernières secondes
const recentMessages = new Map<string, number>()
const DEDUP_WINDOW = 2000
export function useToast() { export function useToast() {
const showToast = (message: string, type: ToastType = 'info', duration = 3500): number => { const showToast = (message: string, type: ToastType = 'info', duration = 3500): number => {
const dedupKey = `${type}::${message}`
const lastShown = recentMessages.get(dedupKey)
if (lastShown && Date.now() - lastShown < DEDUP_WINDOW) {
return -1
}
recentMessages.set(dedupKey, Date.now())
const id = nextId++ const id = nextId++
const toast: Toast = { const toast: Toast = {
id, id,

View File

@@ -116,6 +116,7 @@
<th class="w-24">Aperçu</th> <th class="w-24">Aperçu</th>
<th>Nom</th> <th>Nom</th>
<th>Référence</th> <th>Référence</th>
<th>Description</th>
<th>Type de composant</th> <th>Type de composant</th>
<th>Actions</th> <th>Actions</th>
</tr> </tr>
@@ -130,6 +131,15 @@
</td> </td>
<td>{{ component.name || 'Composant sans nom' }}</td> <td>{{ component.name || 'Composant sans nom' }}</td>
<td>{{ component.reference || '—' }}</td> <td>{{ component.reference || '—' }}</td>
<td class="max-w-xs">
<div v-if="component.description" class="group relative">
<span class="block cursor-help truncate">{{ component.description }}</span>
<div class="pointer-events-none invisible absolute left-0 top-full z-50 mt-1 max-w-sm overflow-hidden rounded-lg border border-base-300 bg-base-100 p-3 text-sm shadow-lg group-hover:pointer-events-auto group-hover:visible">
<p class="break-words whitespace-pre-wrap">{{ component.description }}</p>
</div>
</div>
<span v-else></span>
</td>
<td> <td>
<NuxtLink <NuxtLink
v-if="component.typeComposant?.id" v-if="component.typeComposant?.id"
@@ -269,7 +279,7 @@ const resolvePrimaryDocument = (component: Record<string, any>) => {
return null return null
} }
const normalized = documents.filter((doc) => doc && typeof doc === 'object') const normalized = documents.filter((doc) => doc && typeof doc === 'object')
const withPath = normalized.filter((doc) => doc?.path) const withPath = normalized.filter((doc) => doc?.fileUrl || doc?.path)
const pdf = withPath.find((doc) => isPdfDocument(doc)) const pdf = withPath.find((doc) => isPdfDocument(doc))
if (pdf) { if (pdf) {
return pdf return pdf

View File

@@ -2,6 +2,7 @@
<DocumentPreviewModal <DocumentPreviewModal
:document="previewDocument" :document="previewDocument"
:visible="previewVisible" :visible="previewVisible"
:documents="componentDocuments"
@close="closePreview" @close="closePreview"
/> />
<main class="container mx-auto px-6 py-10"> <main class="container mx-auto px-6 py-10">
@@ -79,6 +80,19 @@
</div> </div>
</div> </div>
<div class="form-control">
<label class="label">
<span class="label-text">Description</span>
</label>
<textarea
v-model="editionForm.description"
class="textarea textarea-bordered textarea-sm md:textarea-md"
:disabled="!canEdit || saving"
placeholder="Description du composant (optionnel)"
rows="3"
/>
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2"> <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label">
@@ -373,8 +387,8 @@
:class="documentThumbnailClass(document)" :class="documentThumbnailClass(document)"
> >
<img <img
v-if="isImageDocument(document) && document.path" v-if="isImageDocument(document) && (document.fileUrl || document.path)"
:src="document.path" :src="document.fileUrl || document.path"
class="h-full w-full object-cover" class="h-full w-full object-cover"
:alt="`Aperçu de ${document.name}`" :alt="`Aperçu de ${document.name}`"
> >
@@ -625,6 +639,7 @@ const historyDiffEntries = (entry: ComponentHistoryEntry) =>
const selectedTypeId = ref<string>('') const selectedTypeId = ref<string>('')
const editionForm = reactive({ const editionForm = reactive({
name: '' as string, name: '' as string,
description: '' as string,
reference: '' as string, reference: '' as string,
constructeurIds: [] as string[], constructeurIds: [] as string[],
prix: '' as string, prix: '' as string,
@@ -805,6 +820,7 @@ watch(
selectedTypeId.value = resolvedTypeId selectedTypeId.value = resolvedTypeId
editionForm.name = currentComponent.name || '' editionForm.name = currentComponent.name || ''
editionForm.description = currentComponent.description || ''
editionForm.reference = currentComponent.reference || '' editionForm.reference = currentComponent.reference || ''
editionForm.constructeurIds = uniqueConstructeurIds( editionForm.constructeurIds = uniqueConstructeurIds(
currentComponent, currentComponent,
@@ -845,6 +861,7 @@ const submitEdition = async () => {
const payload: Record<string, any> = { const payload: Record<string, any> = {
name: editionForm.name.trim(), name: editionForm.name.trim(),
description: editionForm.description.trim() || null,
} }
const reference = editionForm.reference.trim() const reference = editionForm.reference.trim()

View File

@@ -52,6 +52,19 @@
</div> </div>
</div> </div>
<div class="form-control">
<label class="label">
<span class="label-text">Description</span>
</label>
<textarea
v-model="creationForm.description"
class="textarea textarea-bordered textarea-sm md:textarea-md"
:disabled="!canEdit || submitting || !selectedType"
placeholder="Description du composant (optionnel)"
rows="3"
/>
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2"> <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label">
@@ -357,6 +370,7 @@ import { useProducts } from '~/composables/useProducts'
import { useProductTypes } from '~/composables/useProductTypes' import { useProductTypes } from '~/composables/useProductTypes'
import { useApi } from '~/composables/useApi' import { useApi } from '~/composables/useApi'
import { useToast } from '~/composables/useToast' import { useToast } from '~/composables/useToast'
import { humanizeError } from '~/shared/utils/errorMessages'
import { useCustomFields } from '~/composables/useCustomFields' import { useCustomFields } from '~/composables/useCustomFields'
import { useDocuments } from '~/composables/useDocuments' import { useDocuments } from '~/composables/useDocuments'
import { formatStructurePreview, normalizeStructureForEditor } from '~/shared/modelUtils' import { formatStructurePreview, normalizeStructureForEditor } from '~/shared/modelUtils'
@@ -408,6 +422,7 @@ const selectedTypeId = ref<string>(initialTypeId.value)
const submitting = ref(false) const submitting = ref(false)
const creationForm = reactive({ const creationForm = reactive({
name: '' as string, name: '' as string,
description: '' as string,
reference: '' as string, reference: '' as string,
constructeurIds: [] as string[], constructeurIds: [] as string[],
prix: '' as string, prix: '' as string,
@@ -889,6 +904,7 @@ const resolveSubcomponentLabel = (node: Record<string, any>) => {
const clearCreationForm = () => { const clearCreationForm = () => {
creationForm.name = '' creationForm.name = ''
creationForm.description = ''
creationForm.reference = '' creationForm.reference = ''
creationForm.constructeurIds = [] creationForm.constructeurIds = []
creationForm.prix = '' creationForm.prix = ''
@@ -906,6 +922,11 @@ const submitCreation = async () => {
typeComposantId: selectedType.value.id, typeComposantId: selectedType.value.id,
} }
const description = creationForm.description.trim()
if (description) {
payload.description = description
}
const reference = creationForm.reference.trim() const reference = creationForm.reference.trim()
if (reference) { if (reference) {
payload.reference = reference payload.reference = reference
@@ -978,7 +999,7 @@ const submitCreation = async () => {
toast.showError(result.error) toast.showError(result.error)
} }
} catch (error: any) { } catch (error: any) {
toast.showError(error?.message || 'Erreur lors de la création du composant') toast.showError(humanizeError(error?.message) || 'Impossible de créer le composant')
} finally { } finally {
submitting.value = false submitting.value = false
uploadingDocuments.value = false uploadingDocuments.value = false

View File

@@ -3,46 +3,107 @@
<DocumentPreviewModal <DocumentPreviewModal
:document="previewDocument" :document="previewDocument"
:visible="previewVisible" :visible="previewVisible"
:documents="documents"
@close="closePreview" @close="closePreview"
/> />
<section class="card bg-base-100 shadow-lg"> <section class="card bg-base-100 shadow-lg">
<div class="card-body space-y-6"> <div class="card-body space-y-6">
<div class="flex flex-col gap-4 md:flex-row md:items-end md:justify-between"> <div class="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
<div class="w-full md:w-2/3"> <div class="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center">
<label class="label"> <label class="w-full sm:w-72">
<span class="label-text">Recherche</span> <span class="text-xs font-semibold uppercase tracking-wide text-base-content/70">Recherche</span>
<input
v-model="searchTerm"
type="text"
class="input input-bordered input-sm w-full mt-1"
placeholder="Nom du document..."
@input="debouncedSearch"
/>
</label> </label>
<input
v-model="searchTerm" <div class="flex items-center gap-2">
type="search" <label
placeholder="Nom du document, type, site, machine..." class="text-xs font-semibold uppercase tracking-wide text-base-content/70"
class="input input-bordered w-full" for="doc-filter"
> >
Rattachement
</label>
<select
id="doc-filter"
v-model="attachmentFilter"
class="select select-bordered select-sm"
@change="handleFilterChange"
>
<option value="all">Tous</option>
<option value="site">Sites</option>
<option value="machine">Machines</option>
<option value="composant">Composants</option>
<option value="piece">Pi&egrave;ces</option>
<option value="product">Produits</option>
</select>
</div>
<div class="flex items-center gap-2">
<label
class="text-xs font-semibold uppercase tracking-wide text-base-content/70"
for="doc-sort"
>
Trier par
</label>
<select
id="doc-sort"
v-model="sortField"
class="select select-bordered select-sm"
@change="handleSortChange"
>
<option value="createdAt">Date</option>
<option value="name">Nom</option>
<option value="size">Taille</option>
</select>
</div>
<div class="flex items-center gap-2">
<label
class="text-xs font-semibold uppercase tracking-wide text-base-content/70"
for="doc-dir"
>
Ordre
</label>
<select
id="doc-dir"
v-model="sortDirection"
class="select select-bordered select-sm"
@change="handleSortChange"
>
<option value="asc">Ascendant</option>
<option value="desc">Descendant</option>
</select>
</div>
<div class="flex items-center gap-2">
<label
class="text-xs font-semibold uppercase tracking-wide text-base-content/70"
for="doc-per-page"
>
Par page
</label>
<select
id="doc-per-page"
v-model.number="itemsPerPage"
class="select select-bordered select-sm"
@change="handlePerPageChange"
>
<option :value="20">20</option>
<option :value="50">50</option>
<option :value="100">100</option>
</select>
</div>
</div> </div>
<div class="w-full md:w-1/3"> <p class="text-xs text-base-content/50 lg:text-right">
<label class="label"> {{ documentsOnPage }} / {{ documentsTotal }} r&eacute;sultat{{ documentsTotal > 1 ? 's' : '' }}
<span class="label-text">Filtrer par rattachement</span> </p>
</label>
<select v-model="attachmentFilter" class="select select-bordered w-full">
<option value="all">
Tous
</option>
<option value="site">
Sites
</option>
<option value="machine">
Machines
</option>
<option value="composant">
Composants
</option>
<option value="piece">
Pièces
</option>
</select>
</div>
</div> </div>
<div class="divider my-0" /> <div class="divider my-0" />
@@ -52,181 +113,191 @@
Chargement des documents... Chargement des documents...
</div> </div>
<div v-else-if="filteredDocuments.length === 0" class="text-center py-16 text-sm text-gray-500"> <div v-else-if="!documentsTotal" class="text-center py-16 text-sm text-gray-500">
<IconLucideFileSearch class="mx-auto mb-4 h-14 w-14 text-gray-400" aria-hidden="true" /> <IconLucideFileSearch class="mx-auto mb-4 h-14 w-14 text-gray-400" aria-hidden="true" />
Aucun document ne correspond à votre recherche pour l'instant. Aucun document n'a encore &eacute;t&eacute; ajout&eacute;.
</div> </div>
<div v-else class="overflow-x-auto"> <div v-else-if="!documents.length" class="text-center py-16 text-sm text-gray-500">
<table class="table"> <IconLucideFileSearch class="mx-auto mb-4 h-14 w-14 text-gray-400" aria-hidden="true" />
<thead> Aucun document ne correspond &agrave; votre recherche.
<tr class="text-xs uppercase"> </div>
<th>Nom</th>
<th>Type</th> <template v-else>
<th>Taille</th> <div class="overflow-x-auto">
<th>Rattaché à</th> <table class="table">
<th>Date</th> <thead>
<th class="text-right"> <tr class="text-xs uppercase">
Actions <th>Nom</th>
</th> <th>Type</th>
</tr> <th>Taille</th>
</thead> <th>Rattach&eacute; &agrave;</th>
<tbody> <th>Date</th>
<tr v-for="document in filteredDocuments" :key="document.id" class="text-sm"> <th class="text-right">Actions</th>
<td> </tr>
<div class="flex items-center gap-3"> </thead>
<span class="text-xl" :class="documentIcon(document).colorClass"> <tbody>
<component <tr v-for="doc in documents" :key="doc.id" class="text-sm">
:is="documentIcon(document).component" <td>
class="h-6 w-6" <div class="flex items-center gap-3">
aria-hidden="true" <span class="text-xl" :class="documentIcon(doc).colorClass">
/> <component
</span> :is="documentIcon(doc).component"
<div> class="h-6 w-6"
<div class="font-semibold"> aria-hidden="true"
{{ document.name }} />
</div> </span>
<div class="text-xs text-gray-500"> <div>
{{ document.filename }} <div class="font-semibold">{{ doc.name }}</div>
<div class="text-xs text-gray-500">{{ doc.filename }}</div>
</div> </div>
</div> </div>
</div> </td>
</td> <td>{{ doc.mimeType || 'Inconnu' }}</td>
<td>{{ document.mimeType || 'Inconnu' }}</td> <td>{{ formatSize(doc.size) }}</td>
<td>{{ formatSize(document.size) }}</td> <td>
<td> <div class="flex flex-col text-xs">
<div class="flex flex-col text-xs"> <span v-if="doc.site">Site &middot; {{ doc.site.name }}</span>
<span v-if="document.site">Site · {{ document.site.name }}</span> <span v-else-if="doc.machine">Machine &middot; {{ doc.machine.name }}</span>
<span v-else-if="document.machine">Machine · {{ document.machine.name }}</span> <span v-else-if="doc.composant">Composant &middot; {{ doc.composant.name }}</span>
<span v-else-if="document.composant">Composant · {{ document.composant.name }}</span> <span v-else-if="doc.piece">Pi&egrave;ce &middot; {{ doc.piece.name }}</span>
<span v-else-if="document.piece">Pièce · {{ document.piece.name }}</span> <span v-else-if="doc.product">Produit &middot; {{ doc.product.name }}</span>
<span v-else class="text-gray-400">Non défini</span> <span v-else class="text-gray-400">Non d&eacute;fini</span>
</div> </div>
</td> </td>
<td>{{ formatFrenchDate(document.createdAt) }}</td> <td>{{ formatFrenchDate(doc.createdAt) }}</td>
<td class="text-right"> <td class="text-right">
<div class="flex justify-end gap-2"> <div class="flex justify-end gap-2">
<button <button
class="btn btn-ghost btn-xs" class="btn btn-ghost btn-xs"
type="button" type="button"
:disabled="!canPreviewDocument(document)" :disabled="!canPreviewDocument(doc)"
:title="canPreviewDocument(document) ? 'Consulter le document' : 'Aucun aperçu disponible pour ce type'" :title="canPreviewDocument(doc) ? 'Consulter le document' : 'Aucun aper\u00E7u disponible pour ce type'"
@click="openPreview(document)" @click="openPreview(doc)"
> >
Consulter Consulter
</button> </button>
<button class="btn btn-ghost btn-xs" type="button" @click="downloadDocument(document)"> <button class="btn btn-ghost btn-xs" type="button" @click="downloadDocument(doc)">
Télécharger T&eacute;l&eacute;charger
</button> </button>
</div> </div>
</td> </td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
</div> </div>
<Pagination
:current-page="currentPage"
:total-pages="totalPages"
@update:current-page="handlePageChange"
/>
</template>
</div> </div>
</section> </section>
</main> </main>
</template> </template>
<script setup> <script setup lang="ts">
import { ref, computed, onMounted } from 'vue' import { computed, onMounted, ref } from 'vue'
import { useDocuments } from '~/composables/useDocuments' import { useDocuments } from '~/composables/useDocuments'
import { useApi } from '~/composables/useApi'
import { useUrlState } from '~/composables/useUrlState' import { useUrlState } from '~/composables/useUrlState'
import { getFileIcon } from '~/utils/fileIcons' import { getFileIcon } from '~/utils/fileIcons'
import { canPreviewDocument } from '~/utils/documentPreview' import { canPreviewDocument } from '~/utils/documentPreview'
import { formatFrenchDate } from '~/utils/date' import { formatFrenchDate } from '~/utils/date'
import DocumentPreviewModal from '~/components/DocumentPreviewModal.vue' import DocumentPreviewModal from '~/components/DocumentPreviewModal.vue'
import Pagination from '~/components/common/Pagination.vue'
import IconLucideFileSearch from '~icons/lucide/file-search' import IconLucideFileSearch from '~icons/lucide/file-search'
const { documents, loading, loadDocuments } = useDocuments() const { documents, total, loading, loadDocuments } = useDocuments()
const { get } = useApi()
const { q: searchTerm, filter: attachmentFilter } = useUrlState({ const {
page: currentPage,
perPage: itemsPerPage,
q: searchTerm,
filter: attachmentFilter,
sort: sortField,
dir: sortDirection,
} = useUrlState({
page: { default: 1, type: 'number' },
perPage: { default: 30, type: 'number' },
q: { default: '', debounce: 300 }, q: { default: '', debounce: 300 },
filter: { default: 'all' }, filter: { default: 'all' },
sort: { default: 'createdAt' },
dir: { default: 'desc' },
}, {
onRestore: () => fetchDocuments(),
}) })
const previewDocument = ref(null)
const previewDocument = ref<any>(null)
const previewVisible = ref(false) const previewVisible = ref(false)
onMounted(() => { const documentsTotal = computed(() => total.value)
loadDocuments({ itemsPerPage: 200 }) const documentsOnPage = computed(() => documents.value.length)
}) const totalPages = computed(() => Math.ceil(documentsTotal.value / itemsPerPage.value) || 1)
const filteredDocuments = computed(() => { const fetchDocuments = async () => {
const term = searchTerm.value.trim().toLowerCase() await loadDocuments({
const filter = attachmentFilter.value search: searchTerm.value,
page: currentPage.value,
return documents.value.filter((document) => { itemsPerPage: itemsPerPage.value,
const matchesFilter = orderBy: sortField.value,
filter === 'all' || orderDir: sortDirection.value as 'asc' | 'desc',
(filter === 'site' && document.site) || attachmentFilter: attachmentFilter.value,
(filter === 'machine' && document.machine) || force: true,
(filter === 'composant' && document.composant) ||
(filter === 'piece' && document.piece)
if (!matchesFilter) { return false }
if (!term) { return true }
const searchable = [
document.name,
document.filename,
document.mimeType,
document.site?.name,
document.machine?.name,
document.composant?.name,
document.piece?.name
]
.filter(Boolean)
.map(value => value.toLowerCase())
return searchable.some(value => value.includes(term))
}) })
}) }
const formatSize = (size) => { // Search debounce
if (size === undefined || size === null) { return '—' } let searchTimeout: ReturnType<typeof setTimeout> | null = null
if (size === 0) { return '0 B' }
const debouncedSearch = () => {
if (searchTimeout) clearTimeout(searchTimeout)
searchTimeout = setTimeout(() => {
currentPage.value = 1
fetchDocuments()
}, 300)
}
const handlePageChange = (page: number) => {
currentPage.value = page
fetchDocuments()
}
const handleSortChange = () => {
currentPage.value = 1
fetchDocuments()
}
const handleFilterChange = () => {
currentPage.value = 1
fetchDocuments()
}
const handlePerPageChange = () => {
currentPage.value = 1
fetchDocuments()
}
const formatSize = (size: number | undefined | null) => {
if (size === undefined || size === null) return '\u2014'
if (size === 0) return '0 B'
const units = ['B', 'KB', 'MB', 'GB'] const units = ['B', 'KB', 'MB', 'GB']
const index = Math.min(units.length - 1, Math.floor(Math.log(size) / Math.log(1024))) const index = Math.min(units.length - 1, Math.floor(Math.log(size) / Math.log(1024)))
const formatted = size / Math.pow(1024, index) const formatted = size / Math.pow(1024, index)
return `${formatted.toFixed(1)} ${units[index]}` return `${formatted.toFixed(1)} ${units[index]}`
} }
const documentIcon = doc => getFileIcon({ name: doc.filename || doc.name, mime: doc.mimeType }) const documentIcon = (doc: any) => getFileIcon({ name: doc.filename || doc.name, mime: doc.mimeType })
/** Fetch the full document (with path) from the API on demand. */ const downloadDocument = (doc: any) => {
const fetchDocumentPath = async (doc) => { if (doc?.downloadUrl) {
if (doc?.path) { return doc.path } window.open(doc.downloadUrl, '_blank')
if (!doc?.id) { return null }
const result = await get(`/documents/${doc.id}`)
if (result.success && result.data?.path) {
doc.path = result.data.path
return result.data.path
} }
return null
} }
const downloadDocument = async (doc) => { const openPreview = (doc: any) => {
const path = await fetchDocumentPath(doc) if (!canPreviewDocument(doc)) return
if (!path) { return }
if (path.startsWith('data:')) {
const link = document.createElement('a')
link.href = path
link.download = doc.filename || doc.name || 'document'
link.click()
return
}
window.open(path, '_blank')
}
const openPreview = async (doc) => {
if (!canPreviewDocument(doc)) { return }
await fetchDocumentPath(doc)
previewDocument.value = doc previewDocument.value = doc
previewVisible.value = true previewVisible.value = true
} }
@@ -235,4 +306,8 @@ const closePreview = () => {
previewVisible.value = false previewVisible.value = false
previewDocument.value = null previewDocument.value = null
} }
onMounted(() => {
fetchDocuments()
})
</script> </script>

View File

@@ -472,6 +472,7 @@ import { useSites } from '~/composables/useSites'
import { useMachineTypesApi } from '~/composables/useMachineTypesApi' import { useMachineTypesApi } from '~/composables/useMachineTypesApi'
import { useMachines } from '~/composables/useMachines' import { useMachines } from '~/composables/useMachines'
import { useToast } from '~/composables/useToast' import { useToast } from '~/composables/useToast'
import { humanizeError } from '~/shared/utils/errorMessages'
import IconLucideFactory from '~icons/lucide/factory' import IconLucideFactory from '~icons/lucide/factory'
import IconLucideMapPin from '~icons/lucide/map-pin' import IconLucideMapPin from '~icons/lucide/map-pin'
import IconLucideUser from '~icons/lucide/user' import IconLucideUser from '~icons/lucide/user'
@@ -731,10 +732,10 @@ const confirmDeleteMachine = async (machine) => {
showSuccess(`Machine "${machine.name}" supprimée avec succès`) showSuccess(`Machine "${machine.name}" supprimée avec succès`)
await loadMachines() await loadMachines()
} else { } else {
showError(`Erreur lors de la suppression: ${result.error}`) showError(`Impossible de supprimer la machine : ${result.error}`)
} }
} catch (error) { } catch (error) {
showError(`Erreur lors de la suppression: ${error.message}`) showError(`Impossible de supprimer la machine : ${humanizeError(error.message)}`)
} }
} }
} }

View File

@@ -104,6 +104,7 @@
import { ref, computed, onMounted } from "vue"; import { ref, computed, onMounted } from "vue";
import { useMachineTypesApi } from "~/composables/useMachineTypesApi"; import { useMachineTypesApi } from "~/composables/useMachineTypesApi";
import { useToast } from "~/composables/useToast"; import { useToast } from "~/composables/useToast";
import { humanizeError } from "~/shared/utils/errorMessages";
import IconLucidePlus from "~icons/lucide/plus"; import IconLucidePlus from "~icons/lucide/plus";
import IconLucidePackage from "~icons/lucide/package"; import IconLucidePackage from "~icons/lucide/package";
import IconLucideLayoutGrid from "~icons/lucide/layout-grid"; import IconLucideLayoutGrid from "~icons/lucide/layout-grid";
@@ -148,10 +149,10 @@ const confirmDeleteType = async (type) => {
if (result.success) { if (result.success) {
showSuccess(`Type "${type.name}" supprimé avec succès`); showSuccess(`Type "${type.name}" supprimé avec succès`);
} else { } else {
showError(`Erreur lors de la suppression: ${result.error}`); showError(`Impossible de supprimer le type : ${result.error}`);
} }
} catch (error) { } catch (error) {
showError(`Erreur lors de la suppression: ${error.message}`); showError(`Impossible de supprimer le type : ${humanizeError(error.message)}`);
} }
} }
}; };

View File

@@ -10,6 +10,7 @@
<DocumentPreviewModal <DocumentPreviewModal
:document="d.previewDocument.value" :document="d.previewDocument.value"
:visible="d.previewVisible.value" :visible="d.previewVisible.value"
:documents="d.machineDocumentsList.value"
@close="d.closePreview" @close="d.closePreview"
/> />

View File

@@ -138,6 +138,7 @@ import { useMachines } from '~/composables/useMachines'
import { useSites } from '~/composables/useSites' import { useSites } from '~/composables/useSites'
import { useMachineTypesApi } from '~/composables/useMachineTypesApi' import { useMachineTypesApi } from '~/composables/useMachineTypesApi'
import { useToast } from '~/composables/useToast' import { useToast } from '~/composables/useToast'
import { humanizeError } from '~/shared/utils/errorMessages'
import IconLucidePlus from '~icons/lucide/plus' import IconLucidePlus from '~icons/lucide/plus'
import IconLucideFactory from '~icons/lucide/factory' import IconLucideFactory from '~icons/lucide/factory'
import IconLucideMapPin from '~icons/lucide/map-pin' import IconLucideMapPin from '~icons/lucide/map-pin'
@@ -214,10 +215,10 @@ const confirmDeleteMachine = async (machine) => {
if (result.success) { if (result.success) {
showSuccess(`Machine "${machine.name}" supprimée avec succès`) showSuccess(`Machine "${machine.name}" supprimée avec succès`)
} else { } else {
showError(`Erreur lors de la suppression: ${result.error}`) showError(`Impossible de supprimer la machine : ${result.error}`)
} }
} catch (error) { } catch (error) {
showError(`Erreur lors de la suppression: ${error.message}`) showError(`Impossible de supprimer la machine : ${humanizeError(error.message)}`)
} }
} }
} }

View File

@@ -115,6 +115,7 @@
<th class="w-24">Aperçu</th> <th class="w-24">Aperçu</th>
<th>Nom</th> <th>Nom</th>
<th>Référence</th> <th>Référence</th>
<th>Description</th>
<th>Fournisseurs</th> <th>Fournisseurs</th>
<th>Type de pièce</th> <th>Type de pièce</th>
<th>Actions</th> <th>Actions</th>
@@ -130,6 +131,15 @@
</td> </td>
<td>{{ row.piece.name || 'Pièce sans nom' }}</td> <td>{{ row.piece.name || 'Pièce sans nom' }}</td>
<td>{{ row.piece.reference || '—' }}</td> <td>{{ row.piece.reference || '—' }}</td>
<td class="max-w-xs">
<div v-if="row.piece.description" class="group relative">
<span class="block cursor-help truncate">{{ row.piece.description }}</span>
<div class="pointer-events-none invisible absolute left-0 top-full z-50 mt-1 max-w-sm overflow-hidden rounded-lg border border-base-300 bg-base-100 p-3 text-sm shadow-lg group-hover:pointer-events-auto group-hover:visible">
<p class="break-words whitespace-pre-wrap">{{ row.piece.description }}</p>
</div>
</div>
<span v-else></span>
</td>
<td> <td>
<div <div
v-if="row.suppliers.visible.length" v-if="row.suppliers.visible.length"
@@ -291,7 +301,7 @@ const resolvePrimaryDocument = (piece: Record<string, any>) => {
return null return null
} }
const normalized = documents.filter((doc) => doc && typeof doc === 'object') const normalized = documents.filter((doc) => doc && typeof doc === 'object')
const withPath = normalized.filter((doc) => doc?.path) const withPath = normalized.filter((doc) => doc?.fileUrl || doc?.path)
const pdf = withPath.find((doc) => isPdfDocument(doc)) const pdf = withPath.find((doc) => isPdfDocument(doc))
if (pdf) { if (pdf) {

View File

@@ -2,6 +2,7 @@
<DocumentPreviewModal <DocumentPreviewModal
:document="previewDocument" :document="previewDocument"
:visible="previewVisible" :visible="previewVisible"
:documents="pieceDocuments"
@close="closePreview" @close="closePreview"
/> />
<main class="container mx-auto px-6 py-10"> <main class="container mx-auto px-6 py-10">
@@ -79,6 +80,19 @@
</div> </div>
</div> </div>
<div class="form-control">
<label class="label">
<span class="label-text">Description</span>
</label>
<textarea
v-model="editionForm.description"
class="textarea textarea-bordered textarea-sm md:textarea-md"
:disabled="!canEdit || saving"
placeholder="Description de la pièce (optionnel)"
rows="3"
/>
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2"> <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label">
@@ -320,8 +334,8 @@
:class="documentThumbnailClass(document)" :class="documentThumbnailClass(document)"
> >
<img <img
v-if="isImageDocument(document) && document.path" v-if="isImageDocument(document) && (document.fileUrl || document.path)"
:src="document.path" :src="document.fileUrl || document.path"
class="h-full w-full object-cover" class="h-full w-full object-cover"
:alt="`Aperçu de ${document.name}`" :alt="`Aperçu de ${document.name}`"
> >
@@ -568,6 +582,7 @@ const selectedTypeId = ref<string>('')
const pieceTypeDetails = ref<any | null>(null) const pieceTypeDetails = ref<any | null>(null)
const editionForm = reactive({ const editionForm = reactive({
name: '' as string, name: '' as string,
description: '' as string,
reference: '' as string, reference: '' as string,
constructeurIds: [] as string[], constructeurIds: [] as string[],
prix: '' as string, prix: '' as string,
@@ -823,6 +838,7 @@ watch(
selectedTypeId.value = resolvedTypeId selectedTypeId.value = resolvedTypeId
editionForm.name = currentPiece.name || '' editionForm.name = currentPiece.name || ''
editionForm.description = currentPiece.description || ''
editionForm.reference = currentPiece.reference || '' editionForm.reference = currentPiece.reference || ''
editionForm.constructeurIds = uniqueConstructeurIds( editionForm.constructeurIds = uniqueConstructeurIds(
currentPiece, currentPiece,
@@ -895,6 +911,7 @@ const submitEdition = async () => {
const payload: Record<string, any> = { const payload: Record<string, any> = {
name: editionForm.name.trim(), name: editionForm.name.trim(),
description: editionForm.description.trim() || null,
constructeurIds, constructeurIds,
} }

View File

@@ -52,6 +52,19 @@
</div> </div>
</div> </div>
<div class="form-control">
<label class="label">
<span class="label-text">Description</span>
</label>
<textarea
v-model="creationForm.description"
class="textarea textarea-bordered textarea-sm md:textarea-md"
:disabled="!canEdit || submitting || !selectedType"
placeholder="Description de la pièce (optionnel)"
rows="3"
/>
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2"> <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="form-control"> <div class="form-control">
<label class="label"> <label class="label">
@@ -302,6 +315,7 @@ import SearchSelect from '~/components/common/SearchSelect.vue'
import { usePieceTypes } from '~/composables/usePieceTypes' import { usePieceTypes } from '~/composables/usePieceTypes'
import { usePieces } from '~/composables/usePieces' import { usePieces } from '~/composables/usePieces'
import { useToast } from '~/composables/useToast' import { useToast } from '~/composables/useToast'
import { humanizeError } from '~/shared/utils/errorMessages'
import { useCustomFields } from '~/composables/useCustomFields' import { useCustomFields } from '~/composables/useCustomFields'
import { useDocuments } from '~/composables/useDocuments' import { useDocuments } from '~/composables/useDocuments'
import { formatPieceStructurePreview } from '~/shared/modelUtils' import { formatPieceStructurePreview } from '~/shared/modelUtils'
@@ -336,6 +350,7 @@ const selectedTypeId = ref<string>(initialTypeId.value)
const submitting = ref(false) const submitting = ref(false)
const creationForm = reactive({ const creationForm = reactive({
name: '' as string, name: '' as string,
description: '' as string,
reference: '' as string, reference: '' as string,
constructeurIds: [] as string[], constructeurIds: [] as string[],
prix: '' as string, prix: '' as string,
@@ -490,6 +505,7 @@ const canSubmit = computed(() =>
const clearCreationForm = () => { const clearCreationForm = () => {
creationForm.name = '' creationForm.name = ''
creationForm.description = ''
creationForm.reference = '' creationForm.reference = ''
creationForm.constructeurIds = [] creationForm.constructeurIds = []
creationForm.prix = '' creationForm.prix = ''
@@ -513,6 +529,11 @@ const submitCreation = async () => {
typePieceId: selectedType.value.id, typePieceId: selectedType.value.id,
} }
const description = creationForm.description.trim()
if (description) {
payload.description = description
}
const reference = creationForm.reference.trim() const reference = creationForm.reference.trim()
if (reference) { if (reference) {
payload.reference = reference payload.reference = reference
@@ -579,7 +600,7 @@ const submitCreation = async () => {
toast.showError(result.error) toast.showError(result.error)
} }
} catch (error: any) { } catch (error: any) {
toast.showError(error?.message || 'Erreur lors de la création de la pièce') toast.showError(humanizeError(error?.message) || 'Impossible de créer la pièce')
} finally { } finally {
submitting.value = false submitting.value = false
uploadingDocuments.value = false uploadingDocuments.value = false

View File

@@ -367,7 +367,7 @@ const resolvePrimaryDocument = (product: Record<string, any>) => {
return null return null
} }
const normalized = documents.filter((doc) => doc && typeof doc === 'object') const normalized = documents.filter((doc) => doc && typeof doc === 'object')
const withPath = normalized.filter((doc) => doc?.path) const withPath = normalized.filter((doc) => doc?.fileUrl || doc?.path)
if (!withPath.length) { if (!withPath.length) {
return normalized[0] ?? null return normalized[0] ?? null
} }

View File

@@ -2,6 +2,7 @@
<DocumentPreviewModal <DocumentPreviewModal
:document="previewDocument" :document="previewDocument"
:visible="previewVisible" :visible="previewVisible"
:documents="productDocuments"
@close="closePreview" @close="closePreview"
/> />
<main class="container mx-auto px-6 py-10"> <main class="container mx-auto px-6 py-10">
@@ -244,8 +245,8 @@
:class="documentThumbnailClass(document)" :class="documentThumbnailClass(document)"
> >
<img <img
v-if="isImageDocument(document) && document.path" v-if="isImageDocument(document) && (document.fileUrl || document.path)"
:src="document.path" :src="document.fileUrl || document.path"
class="h-full w-full object-cover" class="h-full w-full object-cover"
:alt="`Aperçu de ${document.name}`" :alt="`Aperçu de ${document.name}`"
> >
@@ -406,6 +407,7 @@ import DocumentPreviewModal from '~/components/DocumentPreviewModal.vue'
import { useProducts } from '~/composables/useProducts' import { useProducts } from '~/composables/useProducts'
import { useCustomFields } from '~/composables/useCustomFields' import { useCustomFields } from '~/composables/useCustomFields'
import { useToast } from '~/composables/useToast' import { useToast } from '~/composables/useToast'
import { humanizeError } from '~/shared/utils/errorMessages'
import { useDocuments } from '~/composables/useDocuments' import { useDocuments } from '~/composables/useDocuments'
import { useConstructeurs } from '~/composables/useConstructeurs' import { useConstructeurs } from '~/composables/useConstructeurs'
import { useProductHistory, type ProductHistoryEntry } from '~/composables/useProductHistory' import { useProductHistory, type ProductHistoryEntry } from '~/composables/useProductHistory'
@@ -699,7 +701,7 @@ const submitEdition = async () => {
await router.push('/product-catalog') await router.push('/product-catalog')
} }
} catch (error: any) { } catch (error: any) {
toast.showError(error?.message || 'Erreur lors de la mise à jour du produit') toast.showError(humanizeError(error?.message) || 'Impossible de mettre à jour le produit')
} finally { } finally {
saving.value = false saving.value = false
} }

View File

@@ -3,6 +3,7 @@
<DocumentPreviewModal <DocumentPreviewModal
:document="previewDocument" :document="previewDocument"
:visible="previewVisible" :visible="previewVisible"
:documents="siteDocuments"
@close="closePreview" @close="closePreview"
/> />

View File

@@ -8,6 +8,26 @@
</p> </p>
</div> </div>
<!-- Locked: machines linked -->
<div v-else-if="type && hasMachines" class="my-8">
<div class="card bg-base-100 shadow-xl">
<div class="card-body">
<div class="flex items-center justify-between mb-6">
<h2 class="card-title text-2xl">
{{ type.name }}
</h2>
<NuxtLink to="/machine-skeleton" class="btn btn-outline">
Retour
</NuxtLink>
</div>
<div class="alert alert-warning">
<IconLucideTriangleAlert class="w-5 h-5" />
<span>Ce squelette ne peut pas être modifié car des machines y sont rattachées.</span>
</div>
</div>
</div>
</div>
<!-- Edit Form --> <!-- Edit Form -->
<div v-else-if="type" class="my-8"> <div v-else-if="type" class="my-8">
<div class="card bg-base-100 shadow-xl"> <div class="card bg-base-100 shadow-xl">
@@ -48,11 +68,12 @@
</template> </template>
<script setup> <script setup>
import { ref, onMounted } from 'vue' import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import { useMachineTypesApi } from '~/composables/useMachineTypesApi' import { useMachineTypesApi } from '~/composables/useMachineTypesApi'
import { useToast } from '~/composables/useToast' import { useToast } from '~/composables/useToast'
import { extractRelationId } from '~/shared/apiRelations' import { extractRelationId } from '~/shared/apiRelations'
import IconLucideTriangleAlert from '~icons/lucide/triangle-alert'
const { canEdit } = usePermissions() const { canEdit } = usePermissions()
const route = useRoute() const route = useRoute()
@@ -63,6 +84,10 @@ const { showSuccess, showError } = useToast()
const type = ref(null) const type = ref(null)
const loading = ref(true) const loading = ref(true)
const saving = ref(false) const saving = ref(false)
const hasMachines = computed(() => {
const machines = type.value?.machines
return Array.isArray(machines) && machines.length > 0
})
// Données éditées du type // Données éditées du type
const editedType = ref({ const editedType = ref({

View File

@@ -19,26 +19,32 @@ export const formatSize = (size: number | null | undefined): string => {
return `${formatted.toFixed(1)} ${units[index]}` return `${formatted.toFixed(1)} ${units[index]}`
} }
const resolveUrl = (doc: any): string => doc?.fileUrl || doc?.path || ''
export const shouldInlinePdf = (doc: any): boolean => { export const shouldInlinePdf = (doc: any): boolean => {
if (!doc || !isPdfDocument(doc) || !doc.path) return false if (!doc || !isPdfDocument(doc)) return false
const url = resolveUrl(doc)
if (!url) return false
if (typeof doc.size === 'number' && doc.size > PDF_PREVIEW_MAX_BYTES) return false if (typeof doc.size === 'number' && doc.size > PDF_PREVIEW_MAX_BYTES) return false
return true return true
} }
export const appendPdfViewerParams = (src: string): string => { export const appendPdfViewerParams = (src: string): string => {
if (!src || src.startsWith('data:')) return src || '' if (!src) return ''
if (src.startsWith('data:')) return src
if (src.includes('#')) return `${src}&toolbar=0&navpanes=0` if (src.includes('#')) return `${src}&toolbar=0&navpanes=0`
return `${src}#toolbar=0&navpanes=0` return `${src}#toolbar=0&navpanes=0`
} }
export const documentPreviewSrc = (doc: any): string => { export const documentPreviewSrc = (doc: any): string => {
if (!doc?.path) return '' const url = resolveUrl(doc)
if (isPdfDocument(doc)) return appendPdfViewerParams(doc.path) if (!url) return ''
return doc.path if (isPdfDocument(doc)) return appendPdfViewerParams(url)
return url
} }
export const documentThumbnailClass = (doc: any): string => { export const documentThumbnailClass = (doc: any): string => {
if (shouldInlinePdf(doc) || (isImageDocument(doc) && doc?.path)) return 'h-24 w-20' if (shouldInlinePdf(doc) || (isImageDocument(doc) && resolveUrl(doc))) return 'h-24 w-20'
return 'h-16 w-16' return 'h-16 w-16'
} }
@@ -52,8 +58,14 @@ export const documentIcon = (doc: any): FileIconResult =>
getFileIcon({ name: doc?.filename || doc?.name, mime: doc?.mimeType }) getFileIcon({ name: doc?.filename || doc?.name, mime: doc?.mimeType })
export const downloadDocument = (doc: any): void => { export const downloadDocument = (doc: any): void => {
if (!doc?.path) return // Prefer dedicated download endpoint
const target = String(doc.path) if (doc?.downloadUrl) {
window.open(doc.downloadUrl, '_blank')
return
}
// Fallback for legacy data: URIs during migration
const target = resolveUrl(doc)
if (!target) return
if (target.startsWith('data:')) { if (target.startsWith('data:')) {
const link = document.createElement('a') const link = document.createElement('a')
link.href = target link.href = target

View File

@@ -0,0 +1,152 @@
/**
* Translates raw backend error messages (Symfony, Doctrine, API Platform)
* into user-friendly French messages for display in toasts/alerts.
*/
const EXACT_MATCHES: Record<string, string> = {
// UniqueConstraintSubscriber (HTTP 409)
'nom duplique': 'Un élément avec ce nom existe déjà.',
// English backend messages → French
'Machine not found.': 'Machine introuvable.',
'Composant not found.': 'Composant introuvable.',
'Piece not found.': 'Pièce introuvable.',
'Product not found.': 'Produit introuvable.',
'Site not found.': 'Site introuvable.',
'Custom field not found.': 'Champ personnalisé introuvable.',
'Custom field value not found.': 'Valeur du champ personnalisé introuvable.',
'Document not found.': 'Document introuvable.',
'File not found on disk.': 'Le fichier n\'a pas été trouvé sur le serveur.',
'Invalid document data.': 'Les données du document sont invalides.',
'Invalid JSON payload.': 'Les données envoyées sont invalides.',
'Unsupported entity type.': 'Type d\'entité non supporté.',
'Entity target is missing.': 'La cible de l\'entité est manquante.',
'customFieldId or customFieldName is required.': 'L\'identifiant du champ personnalisé est requis.',
// Symfony validator messages
'This value should not be blank.': 'Ce champ ne peut pas être vide.',
'This value is not a valid email address.': 'L\'adresse email n\'est pas valide.',
'This value is already used.': 'Cette valeur est déjà utilisée.',
'This field is missing.': 'Un champ obligatoire est manquant.',
// HTTP status texts (used in "Erreur XXX: StatusText" fallback)
'Internal Server Error': 'Erreur interne du serveur. Veuillez réessayer.',
'Bad Request': 'Requête invalide.',
'Not Found': 'Ressource introuvable.',
'Conflict': 'Un élément similaire existe déjà.',
'Unprocessable Entity': 'Données invalides.',
'Unprocessable Content': 'Données invalides.',
'Service Unavailable': 'Service temporairement indisponible. Veuillez réessayer.',
'Gateway Timeout': 'Le serveur met trop de temps à répondre. Veuillez réessayer.',
}
const TECHNICAL_PATTERNS: Array<[RegExp, string]> = [
// Database / Doctrine errors
[/SQLSTATE\[/i, 'Une erreur est survenue. Veuillez réessayer.'],
[/An exception occurred/i, 'Une erreur est survenue. Veuillez réessayer.'],
[/Duplicate entry/i, 'Un élément avec ces données existe déjà.'],
[/unique.*constraint.*violation/i, 'Un élément avec ces données existe déjà.'],
[/foreign key constraint/i, 'Impossible de supprimer cet élément car il est utilisé ailleurs.'],
[/violates not-null constraint/i, 'Un champ obligatoire n\'a pas été renseigné.'],
[/violates check constraint/i, 'Une valeur saisie est invalide.'],
// Symfony / API Platform internal messages
[/Expected argument of type/i, 'Les données envoyées sont invalides.'],
[/Could not denormalize/i, 'Les données envoyées sont invalides.'],
[/The JSON value could not be decoded/i, 'Les données envoyées sont invalides.'],
[/Syntax error.*JSON/i, 'Les données envoyées sont invalides.'],
[/No route found/i, 'Ressource introuvable.'],
[/Access Denied/i, 'Permissions insuffisantes pour cette action.'],
]
/**
* Detects if a message contains technical jargon that should not be shown to users.
*/
function containsTechnicalJargon(message: string): boolean {
const patterns = [
/stack trace/i,
/exception/i,
/\bat\s+[\w\\]+::/,
/vendor\//,
/\.php/,
/doctrine/i,
/symfony/i,
/SQLSTATE/i,
/PDOException/i,
/DBALException/i,
/RuntimeException/i,
/TypeError/i,
/LogicException/i,
/InvalidArgumentException/i,
/UnexpectedValueException/i,
/constraint.*violation/i,
/entity.*manager/i,
/Hydra error/i,
]
return patterns.some((p) => p.test(message))
}
/**
* Translates a raw backend error message into a user-friendly French message.
*
* Usage:
* import { humanizeError } from '~/shared/utils/errorMessages'
* showError(humanizeError(rawMessage))
*/
export function humanizeError(rawMessage: string | undefined | null): string {
if (!rawMessage) return 'Une erreur est survenue.'
const trimmed = rawMessage.trim()
if (!trimmed) return 'Une erreur est survenue.'
// 1. Exact match
if (EXACT_MATCHES[trimmed]) return EXACT_MATCHES[trimmed]
// 2. "Erreur XXX: StatusText" pattern — translate the status text
const httpMatch = trimmed.match(/^Erreur (\d{3})\s*:\s*(.+)$/)
if (httpMatch) {
const statusText = httpMatch[2]!.trim()
if (EXACT_MATCHES[statusText]) return EXACT_MATCHES[statusText]
return `Erreur serveur (${httpMatch[1]}). Veuillez réessayer.`
}
// 3. Regex patterns for technical errors
for (const [pattern, replacement] of TECHNICAL_PATTERNS) {
if (pattern.test(trimmed)) return replacement
}
// 4. If it contains technical jargon, replace with generic message
if (containsTechnicalJargon(trimmed)) {
return 'Une erreur est survenue. Veuillez réessayer.'
}
// 5. Already user-friendly — return as-is
return trimmed
}
/**
* Extracts the best error message from various backend response formats.
* Handles: { message }, { error }, { detail }, { "hydra:description" }
*/
export function extractApiErrorMessage(errorData: Record<string, unknown>): string | null {
if (!errorData || typeof errorData !== 'object') return null
// Symfony validator violations — priorité max (message propre sans préfixe champ)
if (Array.isArray(errorData.violations) && errorData.violations.length > 0) {
const first = errorData.violations[0] as Record<string, unknown>
if (typeof first?.message === 'string') return first.message
}
// UniqueConstraintSubscriber format ({ success: false, error: "nom duplique" })
if (typeof errorData.error === 'string') return errorData.error
// Custom controllers format
if (typeof errorData.message === 'string') return errorData.message
if (Array.isArray(errorData.message) && typeof errorData.message[0] === 'string') return errorData.message[0]
// API Platform hydra format (fallback — peut contenir "propertyPath: message")
if (typeof errorData['hydra:description'] === 'string') return errorData['hydra:description']
if (typeof errorData.detail === 'string') return errorData.detail
return null
}

View File

@@ -3,19 +3,19 @@ import { getFileIcon } from './fileIcons'
export const getPreviewType = (document) => { export const getPreviewType = (document) => {
if (!document) { return null } if (!document) { return null }
const mime = (document.mimeType || '').toLowerCase() const mime = (document.mimeType || '').toLowerCase()
const path = document.path || ''
const check = prefix => mime.startsWith(prefix) || path.startsWith(`data:${prefix}`) if (mime.startsWith('image/')) { return 'image' }
if (mime === 'application/pdf') { return 'pdf' }
if (check('image/')) { return 'image' } if (mime.startsWith('audio/')) { return 'audio' }
if (mime === 'application/pdf' || path.startsWith('data:application/pdf')) { return 'pdf' } if (mime.startsWith('video/')) { return 'video' }
if (check('audio/')) { return 'audio' } if (mime.startsWith('text/') || mime.includes('json') || mime.includes('xml')) { return 'text' }
if (check('video/')) { return 'video' }
if (check('text/') || mime.includes('json') || mime.includes('xml') || path.startsWith('data:application/json')) { return 'text' }
return null return null
} }
export const canPreviewDocument = (document = {}) => !!getPreviewType(document) export const canPreviewDocument = (document = {}) => {
if (!getPreviewType(document)) return false
return !!(document.fileUrl || document.path)
}
export const isImageDocument = (document = {}) => getPreviewType(document) === 'image' export const isImageDocument = (document = {}) => getPreviewType(document) === 'image'