budgeteer/web/src/stores/budget.ts
2022-03-15 12:52:23 +00:00

71 lines
2.4 KiB
TypeScript

import { defineStore } from "pinia";
import { GET, POST } from "../api";
import { useAccountStore } from "./budget-account";
import { Budget, useSessionStore } from "./session";
interface State {
CurrentBudgetID: string | null;
}
export const useBudgetsStore = defineStore("budget", {
state: (): State => ({
CurrentBudgetID: null,
}),
getters: {
CurrentBudget(): Budget | undefined {
if (this.CurrentBudgetID == null) return undefined;
const sessionStore = useSessionStore();
return sessionStore.Budgets.get(this.CurrentBudgetID);
},
CurrentBudgetName(state): string {
return this.CurrentBudget?.Name ?? "";
},
},
actions: {
ImportYNAB(formData: FormData) {
return POST(
"/budget/" + this.CurrentBudgetID + "/import/ynab",
formData
);
},
async NewBudget(budgetName: string): Promise<void> {
const result = await POST(
"/budget/new",
JSON.stringify({ name: budgetName })
);
const response = await result.json();
const sessionStore = useSessionStore();
sessionStore.Budgets.set(response.ID, response);
},
async SetCurrentBudget(budgetid: string): Promise<void> {
this.CurrentBudgetID = budgetid;
if (budgetid == null) return;
await this.FetchBudget(budgetid);
},
async FetchBudget(budgetid: string) {
const result = await GET("/budget/" + budgetid);
const response = await result.json();
this.MergeBudgetingData(response);
},
MergeBudgetingData(response: any) {
const accounts = useAccountStore();
for (const account of response.Accounts || []) {
const existingAccount = accounts.Accounts.get(account.ID);
account.Transactions = existingAccount?.Transactions ?? [];
if (account.LastReconciled.Valid)
account.LastReconciled.Time = new Date(
account.LastReconciled.Time
);
accounts.Accounts.set(account.ID, account);
}
for (const category of response.Categories || []) {
accounts.Categories.set(category.ID, category);
}
},
},
});