inventory/web/src/stores/storage.ts

114 lines
3 KiB
TypeScript
Raw Normal View History

import { defineStore } from 'pinia';
export const useStorageStore = defineStore('storage', {
state: () => ({
storageSpaces: [] as any[],
objects: [] as any[],
loading: false,
error: null as string | null,
}),
getters: {
getStorageById: (state) => (id: number) => {
return state.storageSpaces.find(storage => storage.id === id);
},
getObjectsInStorage: (state) => (storageId: number) => {
return state.objects.filter(obj => obj.storagespaceId === storageId);
},
getChildStorages: (state) => (parentId: number) => {
return state.storageSpaces.filter(storage =>
storage.parent && storage.parent === parentId
);
}
},
actions: {
async fetchStorageSpaces() {
this.loading = true;
this.error = null;
try {
const response = await fetch('/api/v1/storageSpaces', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
},
});
if (!response.ok) {
throw new Error('Failed to fetch storage spaces');
}
const data = await response.json();
this.storageSpaces = data.map((space: any) => ({
id: space.id,
parent: space.parent,
location: space.location
}));
} catch (error: any) {
this.error = error.message;
throw error;
} finally {
this.loading = false;
}
},
async fetchObjectsInStorage(storageId: number) {
this.loading = true;
this.error = null;
try {
const response = await fetch(`/api/v1/storageSpaces/${storageId}/objects`, {
headers: {
'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
},
});
if (!response.ok) {
throw new Error('Failed to fetch objects');
}
const data = await response.json();
this.objects = data;
} catch (error: any) {
this.error = error.message;
throw error;
} finally {
this.loading = false;
}
},
async fetchStorageHierarchy(rootStorageId: number) {
this.loading = true;
this.error = null;
try {
// First, ensure we have all storage spaces
if (this.storageSpaces.length === 0) {
await this.fetchStorageSpaces();
}
// Then fetch all objects in the hierarchy
const response = await fetch(`/api/v1/storageSpaces/${rootStorageId}/hierarchy/objects`, {
headers: {
'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
},
});
if (!response.ok) {
throw new Error('Failed to fetch storage hierarchy');
}
const data = await response.json();
this.objects = data;
} catch (error: any) {
this.error = error.message;
throw error;
} finally {
this.loading = false;
}
}
}
});