99 lines
2.9 KiB
TypeScript

import { defineStore } from "pinia";
import WarehouseService, { Warehouse, WarehouseFormData } from "@/services/warehouse";
const warehouseService = new WarehouseService();
export const useWarehouseStore = defineStore("warehouse", {
state: () => ({
warehouses: [] as Warehouse[],
currentWarehouse: null as Warehouse | null,
loading: false,
error: null as string | null,
}),
actions: {
async fetchWarehouses() {
this.loading = true;
this.error = null;
try {
const response = await warehouseService.getAllWarehouses();
this.warehouses = response.data;
return this.warehouses;
} catch (error: any) {
this.error = error.message || "Erreur lors du chargement des entrepôts";
throw error;
} finally {
this.loading = false;
}
},
async fetchWarehouse(id: number) {
this.loading = true;
this.error = null;
try {
const response = await warehouseService.getWarehouse(id);
this.currentWarehouse = response.data;
return this.currentWarehouse;
} catch (error: any) {
this.error = error.message || "Erreur lors du chargement de l'entrepôt";
throw error;
} finally {
this.loading = false;
}
},
async createWarehouse(data: WarehouseFormData) {
this.loading = true;
this.error = null;
try {
const response = await warehouseService.createWarehouse(data);
this.warehouses.push(response.data);
return response.data;
} catch (error: any) {
this.error = error.message || "Erreur lors de la création de l'entrepôt";
throw error;
} finally {
this.loading = false;
}
},
async updateWarehouse(id: number, data: WarehouseFormData) {
this.loading = true;
this.error = null;
try {
const response = await warehouseService.updateWarehouse(id, data);
const index = this.warehouses.findIndex((w) => w.id === id);
if (index !== -1) {
this.warehouses[index] = response.data;
}
if (this.currentWarehouse?.id === id) {
this.currentWarehouse = response.data;
}
return response.data;
} catch (error: any) {
this.error = error.message || "Erreur lors de la mise à jour de l'entrepôt";
throw error;
} finally {
this.loading = false;
}
},
async deleteWarehouse(id: number) {
this.loading = true;
this.error = null;
try {
await warehouseService.deleteWarehouse(id);
this.warehouses = this.warehouses.filter((w) => w.id !== id);
if (this.currentWarehouse?.id === id) {
this.currentWarehouse = null;
}
} catch (error: any) {
this.error = error.message || "Erreur lors de la suppression de l'entrepôt";
throw error;
} finally {
this.loading = false;
}
},
},
});