import { ref } from "vue"; import { defineStore } from "pinia"; import * as api from "@/api/systems"; import type { System } from "@/api/systems"; import { useToastStore } from "@/stores/toast"; export const useSystemsStore = defineStore("systems", () => { const systemsByProject = ref>({}); const loading = ref(false); async function fetchSystems(projectId: number) { loading.value = true; try { systemsByProject.value[projectId] = await api.listSystems(projectId); } catch (e) { useToastStore().show("Failed to load systems", "error"); throw e; } finally { loading.value = false; } } async function createSystem( projectId: number, data: Parameters[1], ) { const system = await api.createSystem(projectId, data); if (!systemsByProject.value[projectId]) systemsByProject.value[projectId] = []; systemsByProject.value[projectId].push(system); return system; } async function updateSystem( projectId: number, systemId: number, data: Parameters[2], ) { const system = await api.updateSystem(projectId, systemId, data); const list = systemsByProject.value[projectId]; if (list) { const idx = list.findIndex((s) => s.id === systemId); // Merged, not replaced: the PATCH reply is the bare System, and the // list's read-side decorations (issue count, rulings usage) would // otherwise vanish from the row until the next reload. if (idx >= 0) list[idx] = { ...list[idx], ...system }; } return system; } async function archiveSystem(projectId: number, systemId: number) { return updateSystem(projectId, systemId, { status: "archived" }); } async function unarchiveSystem(projectId: number, systemId: number) { return updateSystem(projectId, systemId, { status: "active" }); } async function deleteSystem(projectId: number, systemId: number) { await api.deleteSystem(projectId, systemId); const list = systemsByProject.value[projectId]; if (list) { systemsByProject.value[projectId] = list.filter((s) => s.id !== systemId); } } return { systemsByProject, loading, fetchSystems, createSystem, updateSystem, archiveSystem, unarchiveSystem, deleteSystem, }; });