import { defineStore } from "pinia" import { GET } from "../api"; import { useSessionStore } from "./session"; interface State { Accounts: Map, CurrentAccountID: string | null, Categories: Map, Months: Map>>, Transactions: [], Assignments: [] } export interface Account { ID: string Name: string OnBudget: boolean Balance: Number } export interface Category { ID: string Group: string Name: string AvailableLastMonth: number Assigned: number Activity: number Available: number } export const useAccountStore = defineStore("budget/account", { state: (): State => ({ Accounts: new Map(), CurrentAccountID: null, Months: new Map>>(), Categories: new Map(), Transactions: [], Assignments: [] }), getters: { AccountsList(state) { return [ ...state.Accounts.values() ]; }, CategoriesForMonth: (state) => (year : number, month : number) => { console.log("MTH", state.Months) const yearMap = state.Months.get(year); return [ ...yearMap?.get(month)?.values() || [] ]; }, CurrentAccount(state) : Account | undefined { if (state.CurrentAccountID == null) return undefined; return state.Accounts.get(state.CurrentAccountID); }, OnBudgetAccounts(state) { return [ ...state.Accounts.values() ].filter(x => x.OnBudget); }, OnBudgetAccountsBalance(state) : Number { return this.OnBudgetAccounts.reduce((prev, curr) => prev + Number(curr.Balance), 0); }, OffBudgetAccounts(state) { return [ ...state.Accounts.values() ].filter(x => !x.OnBudget); }, OffBudgetAccountsBalance(state) : Number { return this.OffBudgetAccounts.reduce((prev, curr) => prev + Number(curr.Balance), 0); }, TransactionsList(state) { return (state.Transactions || []); } }, actions: { async SetCurrentAccount(budgetid : string, accountid : string) { if (budgetid == null) return this.CurrentAccountID = accountid; if (this.CurrentAccount == undefined) return useSessionStore().setTitle(this.CurrentAccount.Name); await this.FetchAccount(accountid); }, async FetchAccount(accountid : string) { const result = await GET("/account/" + accountid + "/transactions"); const response = await result.json(); this.Transactions = response.Transactions; }, async FetchMonthBudget(budgetid : string, year : number, month : number) { const result = await GET("/budget/" + budgetid + "/" + year + "/" + month); const response = await result.json(); this.addCategoriesForMonth(year, month, response.Categories); }, addCategoriesForMonth(year : number, month : number, categories : Category[]) : void { const yearMap = this.Months.get(year) || new Map>(); this.Months.set(year, yearMap); const monthMap = yearMap.get(month) || new Map(); yearMap.set(month, monthMap); for (const category of categories){ monthMap.set(category.ID, category); } }, logout() { this.$reset() }, } })