Files
Inventory/app/composables/useConstructeurs.js

213 lines
5.7 KiB
JavaScript

import { ref } from 'vue'
import { useApi } from './useApi'
import { useToast } from './useToast'
const constructeurs = ref([])
const loading = ref(false)
const uniqueConstructeurs = (items = []) => {
const map = new Map()
items.forEach((item) => {
if (item && typeof item === 'object' && typeof item.id === 'string') {
map.set(item.id, item)
}
})
return Array.from(map.values())
}
const normalizeIds = (ids = []) => {
if (!Array.isArray(ids)) {
return []
}
return Array.from(
new Set(
ids
.map((value) => (typeof value === 'string' ? value.trim() : ''))
.filter((value) => value.length > 0),
),
)
}
const upsertConstructeurs = (items = []) => {
if (!Array.isArray(items) || !items.length) {
return
}
const merged = uniqueConstructeurs([...constructeurs.value, ...items])
constructeurs.value = merged
}
const getIndexedConstructeur = (id) =>
constructeurs.value.find((item) => item && item.id === id) || null
const extractCollection = (payload) => {
if (Array.isArray(payload)) {
return payload
}
if (Array.isArray(payload?.member)) {
return payload.member
}
if (Array.isArray(payload?.['hydra:member'])) {
return payload['hydra:member']
}
if (Array.isArray(payload?.data)) {
return payload.data
}
return []
}
const pendingFetches = new Map()
export function useConstructeurs () {
const { get, post, patch, delete: del } = useApi()
const { showSuccess, showError } = useToast()
const loadConstructeurs = async (search = '') => {
loading.value = true
try {
const query = search ? `?search=${encodeURIComponent(search)}` : ''
const result = await get(`/constructeurs${query}`)
if (result.success) {
const items = extractCollection(result.data)
constructeurs.value = uniqueConstructeurs(items)
}
return result
} catch (error) {
console.error('Erreur lors du chargement des fournisseurs:', error)
return { success: false, error: error.message }
} finally {
loading.value = false
}
}
const searchConstructeurs = async (search = '') => {
return loadConstructeurs(search)
}
const createConstructeur = async (data) => {
loading.value = true
try {
const result = await post('/constructeurs', data)
if (result.success) {
upsertConstructeurs([result.data])
showSuccess(`Fournisseur "${result.data.name}" créé`)
} else if (result.error) {
showError(result.error)
}
return result
} catch (error) {
console.error('Erreur lors de la création du fournisseur:', error)
showError('Impossible de créer le fournisseur')
return { success: false, error: error.message }
} finally {
loading.value = false
}
}
const ensureConstructeurs = async (ids = []) => {
const normalizedIds = normalizeIds(ids)
if (!normalizedIds.length) {
return []
}
const collected = []
const missing = []
normalizedIds.forEach((id) => {
const existing = getIndexedConstructeur(id)
if (existing) {
collected.push(existing)
} else {
missing.push(id)
}
})
if (missing.length) {
const fetchTasks = missing.map((id) => {
const cached = pendingFetches.get(id)
if (cached) {
return cached
}
const task = get(`/constructeurs/${id}`)
.then((result) => {
if (result.success && result.data) {
return result.data
}
return null
})
.catch((error) => {
console.error('Erreur lors du chargement du fournisseur:', error)
return null
})
.finally(() => {
pendingFetches.delete(id)
})
pendingFetches.set(id, task)
return task
})
const fetched = await Promise.all(fetchTasks)
const validFetched = fetched.filter((item) => item && item.id)
if (validFetched.length) {
upsertConstructeurs(validFetched)
}
}
return normalizedIds
.map((id) => getIndexedConstructeur(id))
.filter((item) => Boolean(item))
}
const updateConstructeur = async (id, data) => {
loading.value = true
try {
const result = await patch(`/constructeurs/${id}`, data)
if (result.success) {
upsertConstructeurs([result.data])
showSuccess(`Fournisseur "${result.data.name}" mis à jour`)
} else if (result.error) {
showError(result.error)
}
return result
} catch (error) {
console.error('Erreur lors de la mise à jour du fournisseur:', error)
showError('Impossible de mettre à jour le fournisseur')
return { success: false, error: error.message }
} finally {
loading.value = false
}
}
const deleteConstructeur = async (id) => {
loading.value = true
try {
const result = await del(`/constructeurs/${id}`)
if (result.success) {
constructeurs.value = constructeurs.value.filter(item => item.id !== id)
showSuccess('Fournisseur supprimé')
} else if (result.error) {
showError(result.error)
}
return result
} catch (error) {
console.error('Erreur lors de la suppression du fournisseur:', error)
showError('Impossible de supprimer le fournisseur')
return { success: false, error: error.message }
} finally {
loading.value = false
}
}
const getConstructeurById = (id) => getIndexedConstructeur(id)
return {
constructeurs,
loading,
loadConstructeurs,
searchConstructeurs,
createConstructeur,
updateConstructeur,
deleteConstructeur,
getConstructeurById,
ensureConstructeurs,
}
}