golscontrol-frontend-v1/src/stores/WarehouseClassifications.js

218 lines
8.2 KiB
JavaScript

import { defineStore } from 'pinia'
import { api } from '../services/Api'
// Store para las clasificaciones de almacén
const useWarehouseClassifications = defineStore('warehouseClassifications', {
state: () => ({
classifications: [],
loading: false,
error: null
}),
getters: {
// Obtener todas las clasificaciones
allClassifications(state) {
return state.classifications
},
// Obtener solo las clasificaciones principales (sin padre)
mainClassifications(state) {
return state.classifications.filter(c => !c.parent_id)
},
// Obtener clasificaciones por estado
activeClassifications(state) {
return state.classifications.filter(c => c.is_active)
},
// Obtener subcategorías de una clasificación específica
getSubcategoriesByParentId: (state) => (parentId) => {
return state.classifications.filter(c => c.parent_id === parentId)
},
// Obtener una clasificación por ID
getClassificationById: (state) => (id) => {
return state.classifications.find(c => c.id === id)
},
// Verificar si está cargando
isLoading(state) {
return state.loading
},
// Obtener error actual
currentError(state) {
return state.error
}
},
actions: {
// Cargar todas las clasificaciones
async fetchClassifications() {
this.loading = true
this.error = null
try {
const response = await api.get('/warehouse-classifications')
this.classifications = response.data.data || response.data
return response.data
} catch (error) {
this.error = error.message || 'Error al cargar las clasificaciones'
console.error('Error fetching classifications:', error)
throw error
} finally {
this.loading = false
}
},
// Crear nueva clasificación
async createClassification(data) {
this.loading = true
this.error = null
try {
const response = await api.post('/warehouse-classifications', data)
const newClassification = response.data.data || response.data
// Agregar la nueva clasificación al estado
this.classifications.push(newClassification)
// Si tiene parent_id, actualizar la lista de children del padre
if (newClassification.parent_id) {
const parent = this.getClassificationById(newClassification.parent_id)
if (parent) {
if (!parent.children) {
parent.children = []
}
parent.children.push(newClassification)
}
}
return response.data
} catch (error) {
this.error = error.message || 'Error al crear la clasificación'
console.error('Error creating classification:', error)
throw error
} finally {
this.loading = false
}
},
// Actualizar clasificación
async updateClassification(id, data) {
this.loading = true
this.error = null
try {
const response = await api.put(`/warehouse-classifications/${id}`, data)
const updatedClassification = response.data.data || response.data
// Actualizar en el estado local
const index = this.classifications.findIndex(c => c.id === id)
if (index !== -1) {
this.classifications[index] = { ...this.classifications[index], ...updatedClassification }
}
// También actualizar en children si existe
this.classifications.forEach(classification => {
if (classification.children) {
const childIndex = classification.children.findIndex(c => c.id === id)
if (childIndex !== -1) {
classification.children[childIndex] = { ...classification.children[childIndex], ...updatedClassification }
}
}
})
return response.data
} catch (error) {
this.error = error.message || 'Error al actualizar la clasificación'
console.error('Error updating classification:', error)
throw error
} finally {
this.loading = false
}
},
// Eliminar clasificación
async deleteClassification(id) {
this.loading = true
this.error = null
try {
await api.delete(`/warehouse-classifications/${id}`)
// Remover del estado local
this.classifications = this.classifications.filter(c => c.id !== id)
// También remover de children si existe
this.classifications.forEach(classification => {
if (classification.children) {
classification.children = classification.children.filter(c => c.id !== id)
}
})
return true
} catch (error) {
this.error = error.message || 'Error al eliminar la clasificación'
console.error('Error deleting classification:', error)
throw error
} finally {
this.loading = false
}
},
// Cambiar estado de una clasificación
async toggleClassificationStatus(classification) {
this.loading = true
this.error = null
try {
const newStatus = !classification.is_active
const response = await api.put(`/warehouse-classifications/${classification.id}`, {
...classification,
is_active: newStatus
})
const updatedClassification = response.data.data || response.data
// Actualizar en el estado local
const index = this.classifications.findIndex(c => c.id === classification.id)
if (index !== -1) {
this.classifications[index].is_active = newStatus
}
// También actualizar en children si existe
this.classifications.forEach(parentClassification => {
if (parentClassification.children) {
const childIndex = parentClassification.children.findIndex(c => c.id === classification.id)
if (childIndex !== -1) {
parentClassification.children[childIndex].is_active = newStatus
}
}
})
return response.data
} catch (error) {
this.error = error.message || 'Error al cambiar el estado'
console.error('Error toggling status:', error)
throw error
} finally {
this.loading = false
}
},
// Limpiar errores
clearError() {
this.error = null
},
// Reset del store
$reset() {
this.classifications = []
this.loading = false
this.error = null
}
}
})
export { useWarehouseClassifications }