Files
Inventory_frontend/app/composables/useProductHistory.ts

68 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { ref } from 'vue'
import { useApi } from '~/composables/useApi'
export type ProductHistoryActor = {
id: string
label: string
}
export type ProductHistoryEntry = {
id: string
action: 'create' | 'update' | 'delete' | string
createdAt: string
actor: ProductHistoryActor | null
diff: Record<string, { from: unknown; to: unknown }> | null
snapshot: Record<string, unknown> | null
}
const extractItems = (payload: any): ProductHistoryEntry[] => {
if (Array.isArray(payload?.items)) {
return payload.items
}
if (Array.isArray(payload?.member)) {
return payload.member
}
if (Array.isArray(payload?.['hydra:member'])) {
return payload['hydra:member']
}
return []
}
export function useProductHistory () {
const { get } = useApi()
const history = ref<ProductHistoryEntry[]>([])
const loading = ref(false)
const error = ref<string | null>(null)
const loadHistory = async (productId: string) => {
loading.value = true
error.value = null
try {
const result = await get(`/products/${productId}/history`)
if (!result.success) {
error.value = result.error ?? 'Impossible de charger lhistorique.'
history.value = []
return result
}
history.value = extractItems(result.data) as ProductHistoryEntry[]
return { success: true, data: history.value }
} catch (err: any) {
const message = err?.message ?? 'Erreur inconnue'
error.value = message
history.value = []
return { success: false, error: message }
} finally {
loading.value = false
}
}
return {
history,
loading,
error,
loadHistory,
}
}