3 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
35 changed files with 823 additions and 347 deletions

View File

@@ -3,6 +3,7 @@
<DocumentPreviewModal
:document="previewDocument"
:visible="previewVisible"
:documents="componentDocuments"
@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"
>
<img
v-if="isImageDocument(document) && document.path"
:src="document.path"
v-if="isImageDocument(document) && (document.fileUrl || document.path)"
:src="document.fileUrl || document.path"
class="h-full w-full object-cover"
:alt="`Aperçu de ${document.name}`"
>
@@ -332,8 +333,8 @@
:class="documentThumbnailClass(document)"
>
<img
v-if="isImageDocument(document) && document.path"
:src="document.path"
v-if="isImageDocument(document) && (document.fileUrl || document.path)"
:src="document.fileUrl || document.path"
class="h-full w-full object-cover"
:alt="`Aperçu de ${document.name}`"
>

View File

@@ -10,9 +10,12 @@
<div class="min-w-0">
<h3 class="font-bold text-xl truncate">
Prévisualisation
<span v-if="navTotal > 1" class="text-base font-normal text-gray-500">
{{ activeIndex + 1 }} / {{ navTotal }}
</span>
</h3>
<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>
</div>
<button type="button" class="btn btn-ghost btn-sm shrink-0" @click="close">
@@ -20,15 +23,35 @@
</button>
</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">
<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 v-else-if="previewType === 'pdf'">
<iframe
:src="document?.path"
:src="documentSrc"
class="w-full h-full bg-white"
frameborder="0"
title="Aperçu PDF"
@@ -36,11 +59,11 @@
</template>
<template v-else-if="previewType === 'audio'">
<audio :src="document?.path" controls class="w-full" />
<audio :src="documentSrc" controls class="w-full" />
</template>
<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 v-else-if="previewType === 'text'">
@@ -80,31 +103,110 @@
</template>
<script setup>
import { ref, computed, watch } from 'vue'
import { getPreviewType, describeDocument } from '~/utils/documentPreview'
import { ref, computed, watch, onUnmounted } from 'vue'
import { getPreviewType, describeDocument, canPreviewDocument } from '~/utils/documentPreview'
const props = defineProps({
document: {
type: Object,
default: null
default: null,
},
visible: {
type: Boolean,
default: false
}
default: false,
},
documents: {
type: Array,
default: () => [],
},
})
const emit = defineEmits(['close'])
const previewType = computed(() => getPreviewType(props.document))
const documentDescription = computed(() => describeDocument(props.document))
// --- Carousel navigation ---
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 textLoading = ref(false)
const textError = ref('')
watch(
() => props.document,
activeDoc,
async (doc) => {
textContent.value = ''
textError.value = ''
@@ -115,22 +217,17 @@ watch(
try {
textLoading.value = true
const path = doc.path || ''
if (path.startsWith('data:')) {
const base64Part = path.split(',')[1] || ''
if (!base64Part) {
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 url = doc.fileUrl || doc.path || ''
if (!url) {
textError.value = 'Aucune URL de document disponible.'
return
}
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) {
console.error('Erreur lors du chargement du texte:', error)
textError.value = error.message || 'Impossible de lire ce document.'
@@ -138,7 +235,7 @@ watch(
textLoading.value = false
}
},
{ immediate: true }
{ immediate: true },
)
const close = () => {
@@ -146,11 +243,8 @@ const close = () => {
}
const download = () => {
if (!props.document?.path) { return }
const link = document.createElement('a')
link.href = props.document.path
link.download = props.document.filename || props.document.name || 'document'
link.target = '_blank'
link.click()
const url = activeDoc.value?.downloadUrl || activeDoc.value?.fileUrl || activeDoc.value?.path
if (!url) { return }
window.open(url, '_blank')
}
</script>

View File

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

View File

@@ -3,6 +3,7 @@
<DocumentPreviewModal
:document="previewDocument"
:visible="previewVisible"
:documents="pieceDocuments"
@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"
>
<img
v-if="isImageDocument(document) && document.path"
:src="document.path"
v-if="isImageDocument(document) && (document.fileUrl || document.path)"
:src="document.fileUrl || document.path"
class="h-full w-full object-cover"
:alt="`Aperçu de ${document.name}`"
>
@@ -413,8 +414,8 @@
:class="documentThumbnailClass(document)"
>
<img
v-if="isImageDocument(document) && document.path"
:src="document.path"
v-if="isImageDocument(document) && (document.fileUrl || document.path)"
:src="document.fileUrl || document.path"
class="h-full w-full object-cover"
:alt="`Aperçu de ${document.name}`"
>

View File

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

View File

@@ -24,9 +24,10 @@
<li v-for="link in simpleLinks" :key="link.to">
<NuxtLink
: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)"
>
<component :is="link.icon" v-if="link.icon" class="w-4 h-4" aria-hidden="true" />
{{ link.label }}
</NuxtLink>
</li>
@@ -46,7 +47,10 @@
@keydown.enter.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
class="h-4 w-4 transition-transform"
:class="openDropdown === group.id + '-mobile' ? 'rotate-90' : ''"
@@ -100,9 +104,10 @@
<li v-for="link in simpleLinks" :key="link.to">
<NuxtLink
: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)"
>
<component :is="link.icon" v-if="link.icon" class="w-4 h-4" aria-hidden="true" />
{{ link.label }}
</NuxtLink>
</li>
@@ -119,13 +124,14 @@
>
<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)"
:aria-expanded="openDropdown === group.id + '-desktop'"
@click="toggleDropdown(group.id + '-desktop')"
@keydown.enter.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 }}
<IconLucideChevronRight
class="h-4 w-4 transition-transform"
@@ -233,7 +239,7 @@
</template>
<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 { useNavDropdown } from '~/composables/useNavDropdown'
import { usePermissions } from '~/composables/usePermissions'
@@ -243,6 +249,13 @@ import IconLucideMenu from '~icons/lucide/menu'
import IconLucideSettings from '~icons/lucide/settings'
import IconLucideChevronRight from '~icons/lucide/chevron-right'
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'
defineEmits<{
@@ -253,25 +266,38 @@ defineEmits<{
interface NavLink {
to: string
label: string
icon?: Component
}
interface NavGroup {
id: string
label: string
icon?: Component
activePaths: string[]
children: NavLink[]
}
const simpleLinks: NavLink[] = [
{ to: '/', label: 'Vue d\'ensemble' },
{ to: '/machines', label: 'Parc Machines' },
{ to: '/machine-skeleton', label: 'Squelettes de machine' },
{ to: '/', label: 'Vue d\'ensemble', icon: IconLucideLayoutDashboard },
{ to: '/machines', label: 'Parc Machines', icon: IconLucideFactory },
{ to: '/machine-skeleton', label: 'Squelettes', icon: IconLucideClipboardList },
]
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',
label: 'Pièces',
icon: IconLucidePuzzle,
activePaths: ['/piece-category', '/pieces-catalog'],
children: [
{ to: '/pieces-catalog', label: 'Catalogue des pièces' },
@@ -281,24 +307,17 @@ const navGroups: NavGroup[] = [
{
id: 'products',
label: 'Produits',
icon: IconLucidePackage,
activePaths: ['/product-category', '/product-catalog'],
children: [
{ to: '/product-catalog', label: 'Catalogue des produits' },
{ 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',
label: 'Ressources liées',
icon: IconLucideLink,
activePaths: ['/sites', '/documents', '/constructeurs', '/activity-log', '/comments'],
children: [
{ to: '/sites', label: 'Sites' },

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,6 @@
import { ref } from 'vue'
import { useApi } from './useApi'
import { useToast } from './useToast'
import { normalizeRelationIds } from '~/shared/apiRelations'
import { extractCollection } from '~/shared/utils/apiHelpers'
export interface Document {
@@ -10,12 +9,21 @@ export interface Document {
filename: string
mimeType: string
size: number
path: string
fileUrl: string
downloadUrl: string
/** @deprecated Legacy Base64 data URI — use fileUrl instead */
path?: string
createdAt?: string
siteId?: string
machineId?: string
composantId?: string
productId?: 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 {
@@ -32,19 +40,30 @@ export interface DocumentResult {
error?: string
}
const documents = ref<Document[]>([])
const loading = ref(false)
interface LoadDocumentsOptions {
search?: string
page?: number
itemsPerPage?: number
orderBy?: string
orderDir?: 'asc' | 'desc'
attachmentFilter?: string
force?: boolean
}
const fileToBase64 = (file: File): Promise<string> =>
new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(reader.result as string)
reader.onerror = () => reject(new Error(`Lecture du fichier ${file.name} impossible`))
reader.readAsDataURL(file)
})
const documents = ref<Document[]>([])
const total = ref(0)
const loading = ref(false)
const loaded = ref(false)
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() {
const { get, post, delete: del } = useApi()
const { get, postFormData, delete: del } = useApi()
const { showError, showSuccess } = useToast()
const loadFromEndpoint = async (
@@ -76,10 +95,61 @@ export function useDocuments() {
}
}
const loadDocuments = async (
options: { updateStore?: boolean; itemsPerPage?: number } = {},
): Promise<DocumentResult> => {
return loadFromEndpoint('/documents', { updateStore: options.updateStore ?? true, itemsPerPage: options.itemsPerPage })
const loadDocuments = async (options: LoadDocumentsOptions = {}): Promise<DocumentResult> => {
const {
search = '',
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 (
@@ -145,18 +215,17 @@ export function useDocuments() {
try {
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({
name: file.name,
filename: file.name,
mimeType: file.type || 'application/octet-stream',
size: file.size,
path: dataUrl,
...context,
})
if (context.siteId) formData.append('siteId', context.siteId)
if (context.machineId) formData.append('machineId', context.machineId)
if (context.composantId) formData.append('composantId', context.composantId)
if (context.productId) formData.append('productId', context.productId)
if (context.pieceId) formData.append('pieceId', context.pieceId)
const result = await post('/documents', payload)
const result = await postFormData('/documents', formData)
if (result.success) {
created.push(result.data as Document)
showSuccess(`Document "${file.name}" ajouté`)
@@ -213,7 +282,9 @@ export function useDocuments() {
return {
documents,
total,
loading,
loaded,
loadDocuments,
loadDocumentsBySite,
loadDocumentsByMachine,

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,7 @@
import { ref } from 'vue'
import { useToast } from './useToast'
import { useApi } from './useApi'
import { humanizeError } from '~/shared/utils/errorMessages'
import { buildConstructeurRequestPayload, uniqueConstructeurIds } from '~/shared/constructeurUtils'
import { useConstructeurs, type Constructeur } from './useConstructeurs'
import { extractRelationId, normalizeRelationIds } from '~/shared/apiRelations'
@@ -168,9 +169,9 @@ export function useProducts() {
return result as ProductListResult
} catch (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
showError(`Impossible de charger les produits: ${message}`)
showError(`Impossible de charger les produits.`)
return { success: false, error: message }
} finally {
loading.value = false
@@ -197,9 +198,9 @@ export function useProducts() {
return { success: false, error: result.error }
} catch (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
showError(message)
showError('Impossible de créer le produit.')
return { success: false, error: message }
} finally {
loading.value = false
@@ -223,9 +224,9 @@ export function useProducts() {
return { success: false, error: result.error }
} catch (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
showError(message)
showError('Impossible de mettre à jour le produit.')
return { success: false, error: message }
} finally {
loading.value = false
@@ -248,9 +249,9 @@ export function useProducts() {
return { success: false, error: result.error }
} catch (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
showError(message)
showError('Impossible de supprimer le produit.')
return { success: false, error: message }
} finally {
loading.value = false

View File

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

View File

@@ -279,7 +279,7 @@ const resolvePrimaryDocument = (component: Record<string, any>) => {
return null
}
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))
if (pdf) {
return pdf

View File

@@ -2,6 +2,7 @@
<DocumentPreviewModal
:document="previewDocument"
:visible="previewVisible"
:documents="componentDocuments"
@close="closePreview"
/>
<main class="container mx-auto px-6 py-10">
@@ -386,8 +387,8 @@
:class="documentThumbnailClass(document)"
>
<img
v-if="isImageDocument(document) && document.path"
:src="document.path"
v-if="isImageDocument(document) && (document.fileUrl || document.path)"
:src="document.fileUrl || document.path"
class="h-full w-full object-cover"
:alt="`Aperçu de ${document.name}`"
>

View File

@@ -370,6 +370,7 @@ import { useProducts } from '~/composables/useProducts'
import { useProductTypes } from '~/composables/useProductTypes'
import { useApi } from '~/composables/useApi'
import { useToast } from '~/composables/useToast'
import { humanizeError } from '~/shared/utils/errorMessages'
import { useCustomFields } from '~/composables/useCustomFields'
import { useDocuments } from '~/composables/useDocuments'
import { formatStructurePreview, normalizeStructureForEditor } from '~/shared/modelUtils'
@@ -998,7 +999,7 @@ const submitCreation = async () => {
toast.showError(result.error)
}
} 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 {
submitting.value = false
uploadingDocuments.value = false

View File

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

View File

@@ -472,6 +472,7 @@ import { useSites } from '~/composables/useSites'
import { useMachineTypesApi } from '~/composables/useMachineTypesApi'
import { useMachines } from '~/composables/useMachines'
import { useToast } from '~/composables/useToast'
import { humanizeError } from '~/shared/utils/errorMessages'
import IconLucideFactory from '~icons/lucide/factory'
import IconLucideMapPin from '~icons/lucide/map-pin'
import IconLucideUser from '~icons/lucide/user'
@@ -731,10 +732,10 @@ const confirmDeleteMachine = async (machine) => {
showSuccess(`Machine "${machine.name}" supprimée avec succès`)
await loadMachines()
} else {
showError(`Erreur lors de la suppression: ${result.error}`)
showError(`Impossible de supprimer la machine : ${result.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 { useMachineTypesApi } from "~/composables/useMachineTypesApi";
import { useToast } from "~/composables/useToast";
import { humanizeError } from "~/shared/utils/errorMessages";
import IconLucidePlus from "~icons/lucide/plus";
import IconLucidePackage from "~icons/lucide/package";
import IconLucideLayoutGrid from "~icons/lucide/layout-grid";
@@ -148,10 +149,10 @@ const confirmDeleteType = async (type) => {
if (result.success) {
showSuccess(`Type "${type.name}" supprimé avec succès`);
} else {
showError(`Erreur lors de la suppression: ${result.error}`);
showError(`Impossible de supprimer le type : ${result.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
:document="d.previewDocument.value"
:visible="d.previewVisible.value"
:documents="d.machineDocumentsList.value"
@close="d.closePreview"
/>

View File

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

View File

@@ -301,7 +301,7 @@ const resolvePrimaryDocument = (piece: Record<string, any>) => {
return null
}
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))
if (pdf) {

View File

@@ -2,6 +2,7 @@
<DocumentPreviewModal
:document="previewDocument"
:visible="previewVisible"
:documents="pieceDocuments"
@close="closePreview"
/>
<main class="container mx-auto px-6 py-10">
@@ -333,8 +334,8 @@
:class="documentThumbnailClass(document)"
>
<img
v-if="isImageDocument(document) && document.path"
:src="document.path"
v-if="isImageDocument(document) && (document.fileUrl || document.path)"
:src="document.fileUrl || document.path"
class="h-full w-full object-cover"
:alt="`Aperçu de ${document.name}`"
>

View File

@@ -315,6 +315,7 @@ import SearchSelect from '~/components/common/SearchSelect.vue'
import { usePieceTypes } from '~/composables/usePieceTypes'
import { usePieces } from '~/composables/usePieces'
import { useToast } from '~/composables/useToast'
import { humanizeError } from '~/shared/utils/errorMessages'
import { useCustomFields } from '~/composables/useCustomFields'
import { useDocuments } from '~/composables/useDocuments'
import { formatPieceStructurePreview } from '~/shared/modelUtils'
@@ -599,7 +600,7 @@ const submitCreation = async () => {
toast.showError(result.error)
}
} 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 {
submitting.value = false
uploadingDocuments.value = false

View File

@@ -367,7 +367,7 @@ const resolvePrimaryDocument = (product: Record<string, any>) => {
return null
}
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) {
return normalized[0] ?? null
}

View File

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

View File

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

View File

@@ -19,26 +19,32 @@ export const formatSize = (size: number | null | undefined): string => {
return `${formatted.toFixed(1)} ${units[index]}`
}
const resolveUrl = (doc: any): string => doc?.fileUrl || doc?.path || ''
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
return true
}
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`
return `${src}#toolbar=0&navpanes=0`
}
export const documentPreviewSrc = (doc: any): string => {
if (!doc?.path) return ''
if (isPdfDocument(doc)) return appendPdfViewerParams(doc.path)
return doc.path
const url = resolveUrl(doc)
if (!url) return ''
if (isPdfDocument(doc)) return appendPdfViewerParams(url)
return url
}
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'
}
@@ -52,8 +58,14 @@ export const documentIcon = (doc: any): FileIconResult =>
getFileIcon({ name: doc?.filename || doc?.name, mime: doc?.mimeType })
export const downloadDocument = (doc: any): void => {
if (!doc?.path) return
const target = String(doc.path)
// Prefer dedicated download endpoint
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:')) {
const link = document.createElement('a')
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) => {
if (!document) { return null }
const mime = (document.mimeType || '').toLowerCase()
const path = document.path || ''
const check = prefix => mime.startsWith(prefix) || path.startsWith(`data:${prefix}`)
if (check('image/')) { return 'image' }
if (mime === 'application/pdf' || path.startsWith('data:application/pdf')) { return 'pdf' }
if (check('audio/')) { return 'audio' }
if (check('video/')) { return 'video' }
if (check('text/') || mime.includes('json') || mime.includes('xml') || path.startsWith('data:application/json')) { return 'text' }
if (mime.startsWith('image/')) { return 'image' }
if (mime === 'application/pdf') { return 'pdf' }
if (mime.startsWith('audio/')) { return 'audio' }
if (mime.startsWith('video/')) { return 'video' }
if (mime.startsWith('text/') || mime.includes('json') || mime.includes('xml')) { return 'text' }
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'