budgeteer/web/src/stores/budget-account.ts

109 lines
3.6 KiB
TypeScript

import { defineStore } from "pinia"
import { GET } from "../api";
import { useSessionStore } from "./session";
interface State {
Accounts: Map<string, Account>,
CurrentAccountID: string | null,
Categories: Map<string, Category>,
Months: Map<number, Map<number, Map<string, Category>>>,
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<string, Account>(),
CurrentAccountID: null,
Months: new Map<number, Map<number, Map<string, Category>>>(),
Categories: new Map<string, Category>(),
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<number, Map<string, Category>>();
this.Months.set(year, yearMap);
const monthMap = yearMap.get(month) || new Map<string, Category>();
yearMap.set(month, monthMap);
for (const category of categories){
monthMap.set(category.ID, category);
}
},
logout() {
this.$reset()
},
}
})