MoneyMgr/moneymgr_web/src/api/AccountApi.ts
2025-04-14 23:25:45 +02:00

100 lines
1.9 KiB
TypeScript

import { APIClient } from "./ApiClient";
import { ServerApi } from "./ServerApi";
export interface Account {
id: number;
name: string;
user_id: number;
time_create: number;
time_update: number;
type: string;
default_account: boolean;
}
export class AccountsList {
list: Account[];
constructor(list: Account[]) {
this.list = list;
this.list.sort((a, b) => a.id - b.id);
}
/**
* Check if accounts list is empty
*/
get isEmpty(): boolean {
return this.list.length === 0;
}
/**
* Get a single account by its id
*/
get(id: number): Account | null {
return this.list.find((a) => a.id === id) ?? null;
}
}
export class AccountApi {
/**
* Get the current list of accounts of the user
*/
static async GetList(): Promise<AccountsList> {
const array = (
await APIClient.exec({
uri: "/accounts",
method: "GET",
})
).data;
return new AccountsList(array);
}
/**
* Set default account
*/
static async SetDefaultAccount(account: Account): Promise<void> {
await APIClient.exec({
uri: `/account/${account.id}/default`,
method: "PUT",
});
}
/**
* Create a new account
*/
static async Create(name: string): Promise<void> {
await APIClient.exec({
uri: `/account`,
method: "POST",
jsonData: {
name,
type: ServerApi.Config.accounts_types[0].code,
},
});
}
/**
* Update account
*/
static async Update(account: Account): Promise<void> {
await APIClient.exec({
uri: `/account/${account.id}`,
method: "PUT",
jsonData: {
name: account.name,
type: account.type,
},
});
}
/**
* Delete account
*/
static async Delete(account: Account): Promise<void> {
await APIClient.exec({
uri: `/account/${account.id}`,
method: "DELETE",
});
}
}