import { defineStore } from "pinia"; import type { CreateOrUpdateAwardViewModel, AwardViewModel } from "../../viewmodels/admin/award.models"; import { http } from "../../serverCom"; export const useAwardStore = defineStore("award", { state: () => { return { awards: [] as Array, award: null as null | AwardViewModel, loadingAll: "loading" as "loading" | "fetched" | "failed", loadingSingle: "loading" as "loading" | "fetched" | "failed", createStatus: null as null | "loading" | { status: "success" | "failed"; reason?: string }, updateStatus: null as null | "loading" | { status: "success" | "failed"; reason?: string }, deleteStatus: null as null | "loading" | { status: "success" | "failed"; reason?: string }, }; }, actions: { resetStatus() { this.createStatus = null; this.updateStatus = null; this.deleteStatus = null; }, fetchAwards() { this.loadingAll = "loading"; http .get("/admin/award") .then((result) => { this.awards = result.data; this.loadingAll = "fetched"; }) .catch((err) => { this.loadingAll = "failed"; }); }, fetchAwardById(id: number) { this.award = null; this.loadingSingle = "loading"; http .get(`/admin/award/${id}`) .then((result) => { this.award = result.data; this.loadingSingle = "fetched"; }) .catch((err) => { this.loadingSingle = "failed"; }); }, createAward(award: CreateOrUpdateAwardViewModel) { this.createStatus = "loading"; http .post(`/admin/award`, { award: award.award, }) .then((result) => { this.createStatus = { status: "success" }; this.fetchAwards(); }) .catch((err) => { this.createStatus = { status: "failed" }; }); }, updateActiveAward(award: CreateOrUpdateAwardViewModel) { if (this.award == null) return; this.updateStatus = "loading"; http .patch(`/admin/award/${this.award.id}`, { award: award.award, }) .then((result) => { this.updateStatus = { status: "success" }; this.fetchAwards(); }) .catch((err) => { this.updateStatus = { status: "failed" }; }); }, deleteAward(award: number) { this.deleteStatus = "loading"; http .delete(`/admin/award/${award}`) .then((res) => { this.deleteStatus = { status: "success" }; this.fetchAwards(); }) .catch((err) => { this.deleteStatus = { status: "failed", reason: err.data }; }); }, }, });