68 lines
2.2 KiB
TypeScript
68 lines
2.2 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 ?? [];
|
|
accounts.Accounts.set(account.ID, account);
|
|
}
|
|
for (const category of response.Categories || []) {
|
|
accounts.Categories.set(category.ID, category);
|
|
}
|
|
},
|
|
}
|
|
}) |