214 lines
6.6 KiB
JavaScript
214 lines
6.6 KiB
JavaScript
import { ref } from 'vue'
|
|
import { useToast } from './useToast'
|
|
import { useApi } from './useApi'
|
|
import { buildConstructeurRequestPayload, uniqueConstructeurIds } from '~/shared/constructeurUtils'
|
|
import { useConstructeurs } from './useConstructeurs'
|
|
import { extractRelationId, normalizeRelationIds } from '~/shared/apiRelations'
|
|
|
|
const composants = ref([])
|
|
const total = ref(0)
|
|
const loading = ref(false)
|
|
|
|
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 extractTotal = (payload, fallbackLength) => {
|
|
if (typeof payload?.totalItems === 'number') {
|
|
return payload.totalItems
|
|
}
|
|
if (typeof payload?.['hydra:totalItems'] === 'number') {
|
|
return payload['hydra:totalItems']
|
|
}
|
|
return fallbackLength
|
|
}
|
|
|
|
export function useComposants () {
|
|
const { showSuccess, showError, showInfo } = useToast()
|
|
const { get, post, patch, delete: del } = useApi()
|
|
const { ensureConstructeurs } = useConstructeurs()
|
|
|
|
const withResolvedConstructeurs = async (composant) => {
|
|
if (!composant || typeof composant !== 'object') {
|
|
return composant
|
|
}
|
|
if (!composant.typeComposantId) {
|
|
const typeComposantId = extractRelationId(composant.typeComposant)
|
|
if (typeComposantId) {
|
|
composant.typeComposantId = typeComposantId
|
|
}
|
|
}
|
|
if (!composant.productId) {
|
|
const productId = extractRelationId(composant.product)
|
|
if (productId) {
|
|
composant.productId = productId
|
|
}
|
|
}
|
|
const ids = uniqueConstructeurIds(
|
|
composant.constructeurIds,
|
|
composant.constructeurs,
|
|
composant.constructeur,
|
|
)
|
|
const hasResolvedConstructeurs =
|
|
Array.isArray(composant.constructeurs)
|
|
&& composant.constructeurs.length > 0
|
|
&& composant.constructeurs.every((item) => item && typeof item === 'object')
|
|
|
|
if (ids.length && !hasResolvedConstructeurs) {
|
|
const resolved = await ensureConstructeurs(ids)
|
|
if (resolved.length) {
|
|
composant.constructeurs = resolved
|
|
composant.constructeurIds = ids
|
|
}
|
|
}
|
|
return composant
|
|
}
|
|
|
|
/**
|
|
* Load composants with pagination and search support
|
|
* @param {Object} options - Query options
|
|
* @param {string} [options.search] - Search term for name/reference
|
|
* @param {number} [options.page=1] - Current page (1-based)
|
|
* @param {number} [options.itemsPerPage=30] - Items per page
|
|
* @param {string} [options.orderBy='name'] - Field to order by
|
|
* @param {string} [options.orderDir='asc'] - Order direction (asc/desc)
|
|
*/
|
|
const loadComposants = async (options = {}) => {
|
|
loading.value = true
|
|
try {
|
|
const {
|
|
search = '',
|
|
page = 1,
|
|
itemsPerPage = 30,
|
|
orderBy = 'name',
|
|
orderDir = 'asc'
|
|
} = options
|
|
|
|
const params = new URLSearchParams()
|
|
params.set('itemsPerPage', String(itemsPerPage))
|
|
params.set('page', String(page))
|
|
|
|
if (search && search.trim()) {
|
|
params.set('name', search.trim())
|
|
}
|
|
|
|
params.set(`order[${orderBy}]`, orderDir)
|
|
|
|
const result = await get(`/composants?${params.toString()}`)
|
|
if (result.success) {
|
|
const items = extractCollection(result.data)
|
|
const enrichedItems = await Promise.all(items.map((item) => withResolvedConstructeurs(item)))
|
|
composants.value = enrichedItems
|
|
total.value = extractTotal(result.data, items.length)
|
|
return {
|
|
success: true,
|
|
data: {
|
|
items: enrichedItems,
|
|
total: total.value,
|
|
page,
|
|
itemsPerPage
|
|
}
|
|
}
|
|
}
|
|
return result
|
|
} catch (error) {
|
|
console.error('Erreur lors du chargement des composants:', error)
|
|
return { success: false, error: error.message }
|
|
} finally {
|
|
loading.value = false
|
|
}
|
|
}
|
|
|
|
const createComposant = async (composantData) => {
|
|
loading.value = true
|
|
try {
|
|
const normalizedPayload = normalizeRelationIds(buildConstructeurRequestPayload(composantData))
|
|
const result = await post('/composants', normalizedPayload)
|
|
if (result.success) {
|
|
const enriched = await withResolvedConstructeurs(result.data)
|
|
composants.value.unshift(enriched)
|
|
total.value += 1
|
|
const displayName = result.data?.name
|
|
|| composantData?.definition?.name
|
|
|| composantData?.name
|
|
|| 'Composant'
|
|
showSuccess(`Composant "${displayName}" créé avec succès`)
|
|
}
|
|
return result
|
|
} catch (error) {
|
|
console.error('Erreur lors de la création du composant:', error)
|
|
return { success: false, error: error.message }
|
|
} finally {
|
|
loading.value = false
|
|
}
|
|
}
|
|
|
|
const updateComposantData = async (id, composantData) => {
|
|
loading.value = true
|
|
try {
|
|
const normalizedPayload = normalizeRelationIds(buildConstructeurRequestPayload(composantData))
|
|
const result = await patch(`/composants/${id}`, normalizedPayload)
|
|
if (result.success) {
|
|
const updated = await withResolvedConstructeurs(result.data)
|
|
const index = composants.value.findIndex(comp => comp.id === id)
|
|
if (index !== -1) {
|
|
composants.value[index] = updated
|
|
}
|
|
showSuccess(`Composant "${updated?.name || composantData.name || ''}" mis à jour avec succès`)
|
|
}
|
|
return result
|
|
} catch (error) {
|
|
console.error('Erreur lors de la mise à jour du composant:', error)
|
|
return { success: false, error: error.message }
|
|
} finally {
|
|
loading.value = false
|
|
}
|
|
}
|
|
|
|
const deleteComposant = async (id) => {
|
|
loading.value = true
|
|
try {
|
|
const result = await del(`/composants/${id}`)
|
|
if (result.success) {
|
|
const deletedComposant = composants.value.find(comp => comp.id === id)
|
|
composants.value = composants.value.filter(comp => comp.id !== id)
|
|
total.value = Math.max(0, total.value - 1)
|
|
showSuccess(`Composant "${deletedComposant?.name || 'inconnu'}" supprimé avec succès`)
|
|
}
|
|
return result
|
|
} catch (error) {
|
|
console.error('Erreur lors de la suppression du composant:', error)
|
|
return { success: false, error: error.message }
|
|
} finally {
|
|
loading.value = false
|
|
}
|
|
}
|
|
|
|
const getComposants = () => composants.value
|
|
const isLoading = () => loading.value
|
|
|
|
return {
|
|
composants,
|
|
total,
|
|
loading,
|
|
loadComposants,
|
|
createComposant,
|
|
updateComposant: updateComposantData,
|
|
deleteComposant,
|
|
getComposants,
|
|
isLoading
|
|
}
|
|
}
|