246 lines
7.6 KiB
JavaScript
246 lines
7.6 KiB
JavaScript
import { ref } from 'vue'
|
||
import { useToast } from './useToast'
|
||
import { useApi } from './useApi'
|
||
import { buildConstructeurRequestPayload } from '~/shared/constructeurUtils'
|
||
|
||
const machines = ref([])
|
||
const loading = ref(false)
|
||
|
||
const resolveLinkCollection = (source, keys) => {
|
||
if (!source || typeof source !== 'object') {
|
||
return undefined
|
||
}
|
||
|
||
for (const key of keys) {
|
||
const value = source[key]
|
||
if (Array.isArray(value)) {
|
||
return value
|
||
}
|
||
}
|
||
|
||
return undefined
|
||
}
|
||
|
||
const normalizeMachineResponse = (payload) => {
|
||
if (!payload || typeof payload !== 'object') {
|
||
return null
|
||
}
|
||
|
||
const container = payload.machine && typeof payload.machine === 'object'
|
||
? payload.machine
|
||
: payload
|
||
|
||
const normalized = { ...container }
|
||
|
||
const componentLinks = resolveLinkCollection(payload, ['componentLinks', 'machineComponentLinks']) ??
|
||
resolveLinkCollection(container, ['componentLinks', 'machineComponentLinks']) ??
|
||
[]
|
||
const pieceLinks = resolveLinkCollection(payload, ['pieceLinks', 'machinePieceLinks']) ??
|
||
resolveLinkCollection(container, ['pieceLinks', 'machinePieceLinks']) ??
|
||
[]
|
||
|
||
normalized.componentLinks = componentLinks
|
||
normalized.pieceLinks = pieceLinks
|
||
|
||
return normalized
|
||
}
|
||
|
||
export function useMachines () {
|
||
const { showSuccess, showError, showInfo } = useToast()
|
||
const { get, post, patch, delete: del } = useApi()
|
||
|
||
const loadMachines = async () => {
|
||
loading.value = true
|
||
try {
|
||
const result = await get('/machines')
|
||
if (result.success) {
|
||
const machineList = Array.isArray(result.data)
|
||
? result.data
|
||
: Array.isArray(result.data?.machines)
|
||
? result.data.machines
|
||
: Array.isArray(result.data?.data)
|
||
? result.data.data
|
||
: []
|
||
const normalized = machineList
|
||
.map((item) => normalizeMachineResponse(item))
|
||
.filter(Boolean)
|
||
machines.value = normalized
|
||
showInfo(`Chargement de ${normalized.length} machine(s) réussi`)
|
||
}
|
||
} catch (error) {
|
||
console.error('Erreur lors du chargement des machines:', error)
|
||
} finally {
|
||
loading.value = false
|
||
}
|
||
}
|
||
|
||
const createMachine = async (machineData) => {
|
||
loading.value = true
|
||
try {
|
||
const result = await post('/machines', buildConstructeurRequestPayload(machineData))
|
||
if (result.success) {
|
||
const createdMachine = normalizeMachineResponse(result.data) ||
|
||
normalizeMachineResponse(result.data?.machine) ||
|
||
null
|
||
if (createdMachine) {
|
||
machines.value.push(createdMachine)
|
||
}
|
||
const displayName = createdMachine?.name || machineData?.name || ''
|
||
showSuccess(`Machine "${displayName}" créée avec succès`)
|
||
}
|
||
return result
|
||
} catch (error) {
|
||
console.error('Erreur lors de la création de la machine:', error)
|
||
return { success: false, error: error.message }
|
||
} finally {
|
||
loading.value = false
|
||
}
|
||
}
|
||
|
||
const createMachineFromType = async (machineData, typeMachine) => {
|
||
// Créer la machine avec la structure héritée du type
|
||
const machineWithStructure = {
|
||
...machineData,
|
||
typeMachineId: typeMachine.id
|
||
// La structure sera automatiquement héritée du type
|
||
// Les composants et pièces seront créés automatiquement
|
||
}
|
||
|
||
return await createMachine(buildConstructeurRequestPayload(machineWithStructure))
|
||
}
|
||
|
||
const updateMachineData = async (id, machineData) => {
|
||
loading.value = true
|
||
try {
|
||
const result = await patch(`/machines/${id}`, buildConstructeurRequestPayload(machineData))
|
||
if (result.success) {
|
||
const updatedMachine = normalizeMachineResponse(result.data) ||
|
||
normalizeMachineResponse(result.data?.machine) ||
|
||
null
|
||
const index = machines.value.findIndex(machine => machine.id === id)
|
||
if (index !== -1 && updatedMachine) {
|
||
machines.value[index] = {
|
||
...machines.value[index],
|
||
...updatedMachine,
|
||
}
|
||
}
|
||
showSuccess(`Machine "${updatedMachine?.name || machineData.name || ''}" mise à jour avec succès`)
|
||
}
|
||
return result
|
||
} catch (error) {
|
||
console.error('Erreur lors de la mise à jour de la machine:', error)
|
||
return { success: false, error: error.message }
|
||
} finally {
|
||
loading.value = false
|
||
}
|
||
}
|
||
|
||
const reconfigureSkeleton = async (machineId, payload) => {
|
||
if (!machineId) {
|
||
return { success: false, error: 'Identifiant de machine manquant' }
|
||
}
|
||
|
||
loading.value = true
|
||
try {
|
||
const result = await patch(`/machines/${machineId}/skeleton`, payload)
|
||
if (result.success) {
|
||
const index = machines.value.findIndex(machine => machine.id === machineId)
|
||
if (index !== -1) {
|
||
const updatedMachine = normalizeMachineResponse(result.data) ||
|
||
normalizeMachineResponse(result.data?.machine) ||
|
||
machines.value[index]
|
||
machines.value[index] = {
|
||
...machines.value[index],
|
||
...(updatedMachine || {}),
|
||
}
|
||
}
|
||
showSuccess('Structure de la machine mise à jour avec succès')
|
||
}
|
||
return result
|
||
} catch (error) {
|
||
console.error('Erreur lors de la reconfiguration du squelette de la machine:', error)
|
||
return { success: false, error: error.message }
|
||
} finally {
|
||
loading.value = false
|
||
}
|
||
}
|
||
|
||
const addMissingCustomFields = async (machineId, { showToast: shouldShowToast = true } = {}) => {
|
||
if (!machineId) {
|
||
const error = 'Identifiant de machine manquant'
|
||
if (shouldShowToast) {
|
||
showError(error)
|
||
}
|
||
return { success: false, error }
|
||
}
|
||
|
||
try {
|
||
const result = await post(`/machines/${machineId}/add-custom-fields`)
|
||
if (result.success) {
|
||
if (shouldShowToast) {
|
||
showSuccess('Champs personnalisés complétés avec succès')
|
||
}
|
||
} else if (shouldShowToast && result.error) {
|
||
showError(result.error)
|
||
}
|
||
return result
|
||
} catch (error) {
|
||
console.error('Erreur lors de l’ajout des champs personnalisés manquants:', error)
|
||
if (shouldShowToast) {
|
||
showError('Erreur lors de la complétion des champs personnalisés')
|
||
}
|
||
return { success: false, error: error.message }
|
||
}
|
||
}
|
||
|
||
const deleteMachine = async (id) => {
|
||
loading.value = true
|
||
try {
|
||
const result = await del(`/machines/${id}`)
|
||
if (result.success) {
|
||
const deletedMachine = machines.value.find(machine => machine.id === id)
|
||
machines.value = machines.value.filter(machine => machine.id !== id)
|
||
showSuccess(`Machine "${deletedMachine?.name || 'inconnu'}" supprimée avec succès`)
|
||
}
|
||
return result
|
||
} catch (error) {
|
||
console.error('Erreur lors de la suppression de la machine:', error)
|
||
return { success: false, error: error.message }
|
||
} finally {
|
||
loading.value = false
|
||
}
|
||
}
|
||
|
||
const getMachineById = (id) => {
|
||
return machines.value.find(machine => machine.id === id)
|
||
}
|
||
|
||
const getMachinesBySite = (siteId) => {
|
||
return machines.value.filter(machine => machine.siteId === siteId)
|
||
}
|
||
|
||
const getMachinesByType = (typeMachineId) => {
|
||
return machines.value.filter(machine => machine.typeMachineId === typeMachineId)
|
||
}
|
||
|
||
const getMachines = () => machines.value
|
||
const isLoading = () => loading.value
|
||
|
||
return {
|
||
machines,
|
||
loading,
|
||
loadMachines,
|
||
createMachine,
|
||
createMachineFromType,
|
||
updateMachine: updateMachineData,
|
||
reconfigureSkeleton,
|
||
deleteMachine,
|
||
getMachineById,
|
||
getMachinesBySite,
|
||
getMachinesByType,
|
||
getMachines,
|
||
isLoading,
|
||
addMissingCustomFields
|
||
}
|
||
}
|