Skip to content

A local-first personal finance app

sidebar pt. 1: add account grouping models and handlers (#8764)

Matt Fiddaman2ffb81f72b79
diff --git a/packages/api/methods.ts b/packages/api/methods.ts
index 1ad394bb50..df42679b48 100644
--- a/packages/api/methods.ts
+++ b/packages/api/methods.ts
@@ -1,6 +1,7 @@
import { send } from '@actual-app/core/platform/client/connection';
import type {
APIAccountEntity,
+ APIAccountGroupEntity,
APICategoryEntity,
APICategoryGroupEntity,
APIFileEntity,
@@ -254,6 +255,25 @@ export function getAccountBalance(id: APIAccountEntity['id'], cutoff?: Date) {
return send('api/account-balance', { id, cutoff });
}
+export function getAccountGroups() {
+ return send('api/account-groups-get');
+}
+
+export function createAccountGroup(group: Omit<APIAccountGroupEntity, 'id'>) {
+ return send('api/account-group-create', { group });
+}
+
+export function updateAccountGroup(
+ id: APIAccountGroupEntity['id'],
+ fields: Partial<Omit<APIAccountGroupEntity, 'id'>>,
+) {
+ return send('api/account-group-update', { id, fields });
+}
+
+export function deleteAccountGroup(id: APIAccountGroupEntity['id']) {
+ return send('api/account-group-delete', { id });
+}
+
export function getCategoryGroups(options: { hidden?: boolean } = {}) {
return send('api/category-groups-get', options);
}
diff --git a/packages/desktop-client/src/components/modals/SelectLinkedAccountsModal.test.ts b/packages/desktop-client/src/components/modals/SelectLinkedAccountsModal.test.ts
index da78f16667..19c5feb6ec 100644
--- a/packages/desktop-client/src/components/modals/SelectLinkedAccountsModal.test.ts
+++ b/packages/desktop-client/src/components/modals/SelectLinkedAccountsModal.test.ts
@@ -33,6 +33,7 @@ function makeLocalAccount(
account_sync_source: null,
last_sync: null,
bank_sync_status: null,
+ account_group_id: null,
...overrides,
};
}
diff --git a/packages/desktop-client/src/hooks/useAccountPreviewTransactions.test.ts b/packages/desktop-client/src/hooks/useAccountPreviewTransactions.test.ts
index 6555fa9755..119ca2404c 100644
--- a/packages/desktop-client/src/hooks/useAccountPreviewTransactions.test.ts
+++ b/packages/desktop-client/src/hooks/useAccountPreviewTransactions.test.ts
@@ -32,6 +32,7 @@ function makeAccount(id: string): AccountEntity {
account_sync_source: null,
last_sync: null,
bank_sync_status: null,
+ account_group_id: null,
};
}
diff --git a/packages/docs/docs/api/reference.md b/packages/docs/docs/api/reference.md
index ce241c5a21..14b9269f6b 100644
--- a/packages/docs/docs/api/reference.md
+++ b/packages/docs/docs/api/reference.md
@@ -351,20 +351,6 @@ await updateTransaction(id, { category: foodCategory.id });
<StructType fields={objects.account} />
-#### Account Types
-
-The account type must be one of these valid strings:
-
-- `checking`
-- `savings`
-- `credit`
-- `investment`
-- `mortgage`
-- `debt`
-- `other`
-
-The account type does not affect anything currently. It's simply extra information about the account.
-
#### Closing Accounts
Avoid setting the `closed` property directly to close an account; instead use the `closeAccount` method. If the account still has money in it you will be required to specify another account to transfer the current balance to. This will help track your money correctly.
@@ -424,11 +410,10 @@ Gets the balance for an account. If a cutoff is given, it gives the account bala
#### Examples
```js
-// Create a savings accounts
+// Create a savings account
createAccount({
- name: "Ally Savings",
- type: "savings
-})
+ name: 'Ally Savings',
+});
```
```js
@@ -437,6 +422,50 @@ createAccount({
let accounts = await getAccounts();
```
+## Account Groups
+
+### Account Group
+
+<StructType fields={objects.accountGroup} />
+
+Account groups let you organize accounts into named groups, for example "Savings" or "Credit Cards". An account can belong to at most one group, set through the `account_group_id` field on [`Account`](#account).
+
+#### Methods
+
+#### `getAccountGroups`
+
+<Method name="getAccountGroups" args={[]} returns="Promise<AccountGroup[]>" />
+
+Get all account groups. Returns an array of [`Account Group`](#account-group) objects.
+
+#### `createAccountGroup`
+
+<Method name="createAccountGroup" args={[{ name: 'group', type: 'AccountGroup' }]} returns="Promise<id>" />
+
+Create an account group. Returns the `id` of the new group.
+
+#### `updateAccountGroup`
+
+<Method name="updateAccountGroup" args={[{ name: 'id', type: 'id' }, { name: 'fields', type: 'object' }]} />
+
+Update fields of an account group. `fields` can specify the `name` field described in [`Account Group`](#account-group).
+
+#### `deleteAccountGroup`
+
+<Method name="deleteAccountGroup" args={[{ name: 'id', type: 'id' }]} />
+
+Delete an account group. Any accounts in the group are left ungrouped.
+
+#### Examples
+
+```js
+// Group two accounts under "Savings"
+
+const groupId = await createAccountGroup({ name: 'Savings' });
+await updateAccount(allySavingsId, { account_group_id: groupId });
+await updateAccount(marcusSavingsId, { account_group_id: groupId });
+```
+
## Categories
#### Category
diff --git a/packages/docs/docs/api/types.jsx b/packages/docs/docs/api/types.jsx
index d158d7ff67..0a4b1b75cd 100644
--- a/packages/docs/docs/api/types.jsx
+++ b/packages/docs/docs/api/types.jsx
@@ -171,6 +171,21 @@ export const objects = {
</span>
),
},
+ {
+ name: 'account_group_id',
+ type: 'id | null',
+ description: (
+ <span>
+ The <a href="#account-group">account group</a> this account belongs
+ to. Defaults to <code>null</code>
+ </span>
+ ),
+ },
+ ],
+
+ accountGroup: [
+ { name: 'id', type: types.id },
+ { name: 'name', type: 'string', required: true },
],
category: [
diff --git a/packages/loot-core/migrations/1787013118115_add_account_groups.sql b/packages/loot-core/migrations/1787013118115_add_account_groups.sql
new file mode 100644
index 0000000000..46bdbe17a8
--- /dev/null
+++ b/packages/loot-core/migrations/1787013118115_add_account_groups.sql
@@ -0,0 +1,11 @@
+BEGIN TRANSACTION;
+
+CREATE TABLE account_groups
+ (id TEXT PRIMARY KEY,
+ name TEXT,
+ sort_order REAL,
+ tombstone INTEGER DEFAULT 0);
+
+ALTER TABLE accounts ADD COLUMN account_group_id TEXT DEFAULT NULL;
+
+COMMIT;
diff --git a/packages/loot-core/src/mocks/index.ts b/packages/loot-core/src/mocks/index.ts
index 66cf6ca9ca..8c4532b50b 100644
--- a/packages/loot-core/src/mocks/index.ts
+++ b/packages/loot-core/src/mocks/index.ts
@@ -23,6 +23,7 @@ export function generateAccount(
last_reconciled: null,
tombstone: 0,
closed: 0,
+ account_group_id: null,
...emptySyncFields(),
};
diff --git a/packages/loot-core/src/server/account-groups/app.test.ts b/packages/loot-core/src/server/account-groups/app.test.ts
new file mode 100644
index 0000000000..5065ee8a5c
--- /dev/null
+++ b/packages/loot-core/src/server/account-groups/app.test.ts
@@ -0,0 +1,166 @@
+import { app } from '#server/account-groups/app';
+import { app as accountsApp } from '#server/accounts/app';
+import * as db from '#server/db';
+import { loadMappings } from '#server/db/mappings';
+
+beforeEach(async () => {
+ await global.emptyDatabase()();
+ await loadMappings();
+});
+
+describe('account groups app', () => {
+ describe('account-group-create / account-groups-get', () => {
+ it('creates groups and returns them in creation order', async () => {
+ const savingsId = await app.handlers['account-group-create']({
+ name: 'Savings',
+ });
+ const currentId = await app.handlers['account-group-create']({
+ name: 'Current Accounts',
+ });
+
+ const groups = await app.handlers['account-groups-get']();
+ expect(groups.map(group => group.id)).toEqual([savingsId, currentId]);
+ expect(groups.map(group => group.name)).toEqual([
+ 'Savings',
+ 'Current Accounts',
+ ]);
+ expect(groups[0].sort_order).toBeLessThan(groups[1].sort_order);
+ });
+
+ it('rejects duplicate names case-insensitively', async () => {
+ await app.handlers['account-group-create']({ name: 'Savings' });
+
+ await expect(
+ app.handlers['account-group-create']({ name: 'savings' }),
+ ).rejects.toThrow(/already exists/);
+ });
+
+ it('allows reusing the name of a deleted group', async () => {
+ const id = await app.handlers['account-group-create']({
+ name: 'Savings',
+ });
+ await app.handlers['account-group-delete']({ id });
+
+ const newId = await app.handlers['account-group-create']({
+ name: 'Savings',
+ });
+ expect(newId).not.toBe(id);
+
+ const groups = await app.handlers['account-groups-get']();
+ expect(groups.map(group => group.id)).toEqual([newId]);
+ });
+ });
+
+ describe('account-group-update', () => {
+ it('renames a group', async () => {
+ const id = await app.handlers['account-group-create']({
+ name: 'Savings',
+ });
+ await app.handlers['account-group-update']({ id, name: 'ISAs' });
+
+ const groups = await app.handlers['account-groups-get']();
+ expect(groups.map(group => group.name)).toEqual(['ISAs']);
+ });
+
+ it('rejects renaming to an existing name but allows renaming itself', async () => {
+ await app.handlers['account-group-create']({ name: 'Savings' });
+ const id = await app.handlers['account-group-create']({
+ name: 'Cards',
+ });
+
+ await expect(
+ app.handlers['account-group-update']({ id, name: 'SAVINGS' }),
+ ).rejects.toThrow(/already exists/);
+
+ await app.handlers['account-group-update']({ id, name: 'CARDS' });
+ const groups = await app.handlers['account-groups-get']();
+ expect(groups.map(group => group.name)).toEqual(['Savings', 'CARDS']);
+ });
+ });
+
+ describe('account-group-move', () => {
+ it('moves a group before a target and appends with a null target', async () => {
+ const aId = await app.handlers['account-group-create']({ name: 'A' });
+ const bId = await app.handlers['account-group-create']({ name: 'B' });
+ const cId = await app.handlers['account-group-create']({ name: 'C' });
+
+ await app.handlers['account-group-move']({ id: cId, targetId: aId });
+ let groups = await app.handlers['account-groups-get']();
+ expect(groups.map(group => group.id)).toEqual([cId, aId, bId]);
+
+ await app.handlers['account-group-move']({ id: cId, targetId: null });
+ groups = await app.handlers['account-groups-get']();
+ expect(groups.map(group => group.id)).toEqual([aId, bId, cId]);
+ });
+ });
+
+ describe('account-group-delete', () => {
+ it('tombstones the group and clears member account refs only', async () => {
+ const cardsId = await app.handlers['account-group-create']({
+ name: 'Cards',
+ });
+ const otherId = await app.handlers['account-group-create']({
+ name: 'Other',
+ });
+
+ await db.insertAccount({ id: 'acct1', name: 'Amex' });
+ await db.insertAccount({ id: 'acct2', name: 'Checking' });
+ await accountsApp.handlers['account-update']({
+ id: 'acct1',
+ name: 'Amex',
+ account_group_id: cardsId,
+ });
+ await accountsApp.handlers['account-update']({
+ id: 'acct2',
+ name: 'Checking',
+ account_group_id: otherId,
+ });
+
+ await app.handlers['account-group-delete']({ id: cardsId });
+
+ const groups = await app.handlers['account-groups-get']();
+ expect(groups.map(group => group.id)).toEqual([otherId]);
+
+ const accounts = await accountsApp.handlers['accounts-get']();
+ expect(
+ accounts.find(account => account.id === 'acct1')?.account_group_id,
+ ).toBeNull();
+ expect(
+ accounts.find(account => account.id === 'acct2')?.account_group_id,
+ ).toBe(otherId);
+ });
+ });
+
+ describe('account-update', () => {
+ it('persists, keeps and clears the account group', async () => {
+ const groupId = await app.handlers['account-group-create']({
+ name: 'Savings',
+ });
+ await db.insertAccount({ id: 'acct1', name: 'Marcus' });
+
+ await accountsApp.handlers['account-update']({
+ id: 'acct1',
+ name: 'Marcus',
+ account_group_id: groupId,
+ });
+ let accounts = await accountsApp.handlers['accounts-get']();
+ expect(accounts[0].account_group_id).toBe(groupId);
+
+ await accountsApp.handlers['account-update']({
+ id: 'acct1',
+ name: 'Marcus Savings',
+ });
+ accounts = await accountsApp.handlers['accounts-get']();
+ expect(accounts[0].name).toBe('Marcus Savings');
+ expect(accounts[0].account_group_id).toBe(groupId);
+
+ await accountsApp.handlers['account-update']({
+ id: 'acct1',
+ name: 'Marcus Savings',
+ account_group_id: null,
+ });
+ accounts = await accountsApp.handlers['accounts-get']();
+ expect(accounts[0].account_group_id).toBeNull();
+ });
+ });
+});
diff --git a/packages/loot-core/src/server/account-groups/app.ts b/packages/loot-core/src/server/account-groups/app.ts
new file mode 100644
index 0000000000..baa6d90b23
--- /dev/null
+++ b/packages/loot-core/src/server/account-groups/app.ts
@@ -0,0 +1,58 @@
+import { createApp } from '#server/app';
+import * as db from '#server/db';
+import { mutator } from '#server/mutators';
+import { undoable } from '#server/undo';
+import type { AccountGroupEntity } from '#types/models';
+
+export type AccountGroupsHandlers = {
+ 'account-groups-get': typeof getAccountGroups;
+ 'account-group-create': typeof createAccountGroup;
+ 'account-group-update': typeof updateAccountGroup;
+ 'account-group-delete': typeof deleteAccountGroup;
+ 'account-group-move': typeof moveAccountGroup;
+};
+
+export const app = createApp<AccountGroupsHandlers>();
+app.method('account-groups-get', getAccountGroups);
+app.method('account-group-create', mutator(undoable(createAccountGroup)));
+app.method('account-group-update', mutator(undoable(updateAccountGroup)));
+app.method('account-group-delete', mutator(undoable(deleteAccountGroup)));
+app.method('account-group-move', mutator(undoable(moveAccountGroup)));
+
+async function getAccountGroups(): Promise<AccountGroupEntity[]> {
+ const groups = await db.getAccountGroups();
+ return groups.map(group => ({
+ id: group.id,
+ name: group.name,
+ sort_order: group.sort_order,
+ }));
+}
+
+async function createAccountGroup({
+ name,
+}: Pick<AccountGroupEntity, 'name'>): Promise<AccountGroupEntity['id']> {
+ return db.insertAccountGroup({ name });
+}
+
+async function updateAccountGroup(
+ group: Pick<AccountGroupEntity, 'id' | 'name'>,
+): Promise<void> {
+ await db.updateAccountGroup(group);
+}
+
+async function deleteAccountGroup({
+ id,
+}: Pick<AccountGroupEntity, 'id'>): Promise<AccountGroupEntity['id']> {
+ await db.deleteAccountGroup({ id });
+ return id;
+}
+
+async function moveAccountGroup({
+ id,
+ targetId,
+}: {
+ id: AccountGroupEntity['id'];
+ targetId: AccountGroupEntity['id'] | null;
+}): Promise<void> {
+ await db.moveAccountGroup(id, targetId);
+}
diff --git a/packages/loot-core/src/server/accounts/app.ts b/packages/loot-core/src/server/accounts/app.ts
index 8d1138b101..03ec882efd 100644
--- a/packages/loot-core/src/server/accounts/app.ts
+++ b/packages/loot-core/src/server/accounts/app.ts
@@ -95,12 +95,14 @@ async function updateAccount({
id,
name,
last_reconciled,
+ account_group_id,
}: Pick<AccountEntity, 'id' | 'name'> &
- Partial<Pick<AccountEntity, 'last_reconciled'>>) {
+ Partial<Pick<AccountEntity, 'last_reconciled' | 'account_group_id'>>) {
await db.update('accounts', {
id,
name,
...(last_reconciled && { last_reconciled }),
+ ...(account_group_id !== undefined && { account_group_id }),
});
return {};
}
@@ -129,6 +131,7 @@ async function getAccounts(): Promise<AccountEntity[]> {
account_sync_source: dbAccount.account_sync_source ?? null,
last_sync: dbAccount.last_sync ?? null,
bank_sync_status: dbAccount.bank_sync_status ?? null,
+ account_group_id: dbAccount.account_group_id ?? null,
}) satisfies AccountEntity,
);
}
diff --git a/packages/loot-core/src/server/api-models.ts b/packages/loot-core/src/server/api-models.ts
index b2c791965f..238c0c7ba9 100644
--- a/packages/loot-core/src/server/api-models.ts
+++ b/packages/loot-core/src/server/api-models.ts
@@ -1,6 +1,7 @@
import type { Budget } from '#types/budget';
import type {
AccountEntity,
+ AccountGroupEntity,
CategoryEntity,
CategoryGroupEntity,
NewRuleEntity,
@@ -17,6 +18,7 @@ export type APIAccountEntity = Pick<AccountEntity, 'id' | 'name'> & {
offbudget?: boolean;
closed?: boolean;
balance_current?: number | null;
+ account_group_id?: string | null;
};
export const accountModel = {
@@ -29,6 +31,7 @@ export const accountModel = {
offbudget: account.offbudget ? true : false,
closed: account.closed ? true : false,
balance_current: account.balance_current ?? null,
+ account_group_id: account.account_group_id ?? null,
};
},
@@ -44,6 +47,24 @@ export const accountModel = {
},
};
+export type APIAccountGroupEntity = Pick<AccountGroupEntity, 'id' | 'name'>;
+
+export const accountGroupModel = {
+ ...models.accountGroupModel,
+
+ toExternal(group: AccountGroupEntity): APIAccountGroupEntity {
+ return {
+ id: group.id,
+ name: group.name,
+ };
+ },
+
+ fromExternal(group: Partial<APIAccountGroupEntity>) {
+ // No translation is needed
+ return group as Partial<AccountGroupEntity>;
+ },
+};
+
export type APICategoryEntity = Pick<
CategoryEntity,
'id' | 'name' | 'is_income' | 'hidden'
diff --git a/packages/loot-core/src/server/api.test.ts b/packages/loot-core/src/server/api.test.ts
index 7e371df7ee..32f6ed6582 100644
--- a/packages/loot-core/src/server/api.test.ts
+++ b/packages/loot-core/src/server/api.test.ts
@@ -3,6 +3,8 @@ import * as sheet from '#server/sheet';
import { getBankSyncError } from '#shared/errors';
import type { ServerHandlers } from '#types/server-handlers';
+import { app as accountGroupsApp } from './account-groups/app';
+import { app as accountsApp } from './accounts/app';
import { installAPI } from './api';
import { createBudget } from './budget/base';
import * as prefs from './prefs';
@@ -55,6 +57,54 @@ describe('API handlers', () => {
});
});
+ describe('api/account-groups', () => {
+ beforeEach(global.emptyDatabase());
+
+ beforeEach(async () => {
+ await prefs.loadPrefs();
+
+ handlers['account-groups-get'] =
+ accountGroupsApp.handlers['account-groups-get'];
+ handlers['account-group-create'] =
+ accountGroupsApp.handlers['account-group-create'];
+ handlers['account-group-update'] =
+ accountGroupsApp.handlers['account-group-update'];
+ handlers['account-group-delete'] =
+ accountGroupsApp.handlers['account-group-delete'];
+ handlers['accounts-get'] = accountsApp.handlers['accounts-get'];
+ });
+
+ it('round-trips account groups and exposes account_group_id on accounts', async () => {
+ const id = await handlers['api/account-group-create']({
+ group: { name: 'Savings' },
+ });
+ await expect(handlers['api/account-groups-get']()).resolves.toEqual([
+ { id, name: 'Savings' },
+ ]);
+
+ await handlers['api/account-group-update']({
+ id,
+ fields: { name: 'ISAs' },
+ });
+ await expect(handlers['api/account-groups-get']()).resolves.toEqual([
+ { id, name: 'ISAs' },
+ ]);
+
+ await db.insertAccount({ id: 'acct1', name: 'Marcus' });
+ await handlers['api/account-update']({
+ id: 'acct1',
+ fields: { account_group_id: id },
+ });
+ const accounts = await handlers['api/accounts-get']();
+ expect(accounts[0]).toMatchObject({ id: 'acct1', account_group_id: id });
+
+ await handlers['api/account-group-delete']({ id });
+ await expect(handlers['api/account-groups-get']()).resolves.toEqual([]);
+ const after = await handlers['api/accounts-get']();
+ expect(after[0].account_group_id).toBeNull();
+ });
+ });
+
describe('api/budget-month', () => {
beforeEach(global.emptyDatabase());
diff --git a/packages/loot-core/src/server/api.ts b/packages/loot-core/src/server/api.ts
index 8c7389e93a..168099aa0e 100644
--- a/packages/loot-core/src/server/api.ts
+++ b/packages/loot-core/src/server/api.ts
@@ -27,6 +27,7 @@ import type { ServerHandlers } from '#types/server-handlers';
import { addTransactions } from './accounts/sync';
import {
+ accountGroupModel,
accountModel,
budgetModel,
categoryGroupModel,
@@ -670,6 +671,34 @@ handlers['api/account-balance'] = withMutation(async function ({
return handlers['account-balance']({ id, cutoff });
});
+handlers['api/account-groups-get'] = async function () {
+ checkFileOpen();
+ const groups = await handlers['account-groups-get']();
+ return groups.map(group => accountGroupModel.toExternal(group));
+};
+
+handlers['api/account-group-create'] = withMutation(async function ({ group }) {
+ checkFileOpen();
+ return handlers['account-group-create']({ name: group.name });
+});
+
+handlers['api/account-group-update'] = withMutation(async function ({
+ id,
+ fields,
+}) {
+ checkFileOpen();
+ const group = accountGroupModel.fromExternal(fields);
+ if (group.name == null) {
+ throw APIError('Account group name is required');
+ }
+ return handlers['account-group-update']({ id, name: group.name });
+});
+
+handlers['api/account-group-delete'] = withMutation(async function ({ id }) {
+ checkFileOpen();
+ await handlers['account-group-delete']({ id });
+});
+
handlers['api/categories-get'] = async function ({
hidden,
}: { hidden?: boolean } = {}) {
diff --git a/packages/loot-core/src/server/aql/schema/index.ts b/packages/loot-core/src/server/aql/schema/index.ts
index ecada54515..2ecf4a6508 100644
--- a/packages/loot-core/src/server/aql/schema/index.ts
+++ b/packages/loot-core/src/server/aql/schema/index.ts
@@ -78,6 +78,13 @@ export const schema = {
last_reconciled: f('string'),
last_sync: f('string'),
bank_sync_status: f('string'),
+ account_group_id: f('id', { ref: 'account_groups' }),
+ },
+ account_groups: {
+ id: f('id'),
+ name: f('string'),
+ sort_order: f('float'),
+ tombstone: f('boolean'),
},
categories: {
id: f('id'),
@@ -287,6 +294,8 @@ export const schemaConfig: SchemaConfig = {
];
case 'accounts':
return ['sort_order', 'name'];
+ case 'account_groups':
+ return ['sort_order', 'id'];
case 'schedules':
return [{ $condition: { completed: true } }, 'next_date'];
default:
diff --git a/packages/loot-core/src/server/db/index.ts b/packages/loot-core/src/server/db/index.ts
index 36da347334..0eeeffee46 100644
--- a/packages/loot-core/src/server/db/index.ts
+++ b/packages/loot-core/src/server/db/index.ts
@@ -21,6 +21,7 @@ import {
schemaConfig,
} from '#server/aql';
import {
+ accountGroupModel,
accountModel,
categoryGroupModel,
categoryModel,
@@ -41,6 +42,7 @@ import {
} from './sort';
import type {
DbAccount,
+ DbAccountGroup,
DbBank,
DbCategory,
DbCategoryGroup,
@@ -782,6 +784,88 @@ export async function moveAccount(
});
}
+export function getAccountGroups() {
+ return all<DbAccountGroup>(
+ `SELECT * FROM account_groups WHERE tombstone = 0 ORDER BY sort_order, id`,
+ );
+}
+
+export async function insertAccountGroup(
+ group: WithRequired<Partial<DbAccountGroup>, 'name'>,
+): Promise<DbAccountGroup['id']> {
+ // Don't allow duplicate group
+ const existingGroup = await first<Pick<DbAccountGroup, 'id' | 'name'>>(
+ `SELECT id, name FROM account_groups WHERE UPPER(name) = ? AND tombstone = 0 LIMIT 1`,
+ [group.name.toUpperCase()],
+ );
+ if (existingGroup) {
+ throw new Error(`An '${existingGroup.name}' account group already exists.`);
+ }
+
+ const lastGroup = await first<Pick<DbAccountGroup, 'sort_order'>>(`
+ SELECT sort_order FROM account_groups WHERE tombstone = 0 ORDER BY sort_order DESC, id DESC LIMIT 1
+ `);
+ const sort_order = (lastGroup ? lastGroup.sort_order : 0) + SORT_INCREMENT;
+
+ group = {
+ ...accountGroupModel.validate(group),
+ sort_order,
+ };
+ const id: DbAccountGroup['id'] = await insertWithUUID(
+ 'account_groups',
+ group,
+ );
+ return id;
+}
+
+export async function updateAccountGroup(
+ group: WithRequired<Partial<DbAccountGroup>, 'id' | 'name'>,
+) {
+ const existingGroup = await first<Pick<DbAccountGroup, 'id' | 'name'>>(
+ `SELECT id, name FROM account_groups WHERE UPPER(name) = ? AND id != ? AND tombstone = 0 LIMIT 1`,
+ [group.name.toUpperCase(), group.id],
+ );
+ if (existingGroup) {
+ throw new Error(`An '${existingGroup.name}' account group already exists.`);
+ }
+ group = accountGroupModel.validate(group, { update: true });
+ return update('account_groups', group);
+}
+
+export async function moveAccountGroup(
+ id: DbAccountGroup['id'],
+ targetId?: DbAccountGroup['id'] | null,
+) {
+ const groups = await all<Pick<DbAccountGroup, 'id' | 'sort_order'>>(
+ `SELECT id, sort_order FROM account_groups WHERE tombstone = 0 ORDER BY sort_order, id`,
+ );
+
+ const { updates, sort_order } = shoveSortOrders(groups, targetId);
+ await batchMessages(async () => {
+ for (const info of updates) {
+ await update('account_groups', info);
+ }
+ await update('account_groups', { id, sort_order });
+ });
+}
+
+export async function deleteAccountGroup(group: Pick<DbAccountGroup, 'id'>) {
+ const accounts = await all<Pick<DbAccount, 'id'>>(
+ `SELECT id FROM accounts WHERE account_group_id = ? AND tombstone = 0`,
+ [group.id],
+ );
+
+ // Clearing member refs is best-effort under CRDT sync: a concurrent
+ // assignment on another device can win against these nulls, so consumers
+ // must always treat a ref to a missing/tombstoned group as ungrouped.
+ await batchMessages(async () => {
+ for (const account of accounts) {
+ await update('accounts', { id: account.id, account_group_id: null });
+ }
+ await delete_('account_groups', group.id);
+ });
+}
+
export async function getTransaction(id: DbViewTransaction['id']) {
const rows = await selectWithSchema(
'transactions',
diff --git a/packages/loot-core/src/server/db/types/index.ts b/packages/loot-core/src/server/db/types/index.ts
index 54c851d68d..4991cb285c 100644
--- a/packages/loot-core/src/server/db/types/index.ts
+++ b/packages/loot-core/src/server/db/types/index.ts
@@ -35,6 +35,14 @@ export type DbAccount = {
| 'timed-out'
| 'account-missing'
| null;
+ account_group_id?: DbAccountGroup['id'] | null;
+};
+
+export type DbAccountGroup = {
+ id: string;
+ name: string;
+ sort_order: number;
+ tombstone: 1 | 0;
};
export type DbBank = {
diff --git a/packages/loot-core/src/server/main.ts b/packages/loot-core/src/server/main.ts
index 25826588fc..6ba51b3802 100644
--- a/packages/loot-core/src/server/main.ts
+++ b/packages/loot-core/src/server/main.ts
@@ -8,6 +8,7 @@ import { q } from '#shared/query';
import { amountToInteger, integerToAmount } from '#shared/util';
import type { Handlers } from '#types/handlers';
+import { app as accountGroupsApp } from './account-groups/app';
import { app as accountsApp } from './accounts/app';
import { app as adminApp } from './admin/app';
import { installAPI } from './api';
@@ -144,6 +145,7 @@ app.combine(
adminApp,
transactionsApp,
accountsApp,
+ accountGroupsApp,
payeesApp,
spreadsheetApp,
syncApp,
diff --git a/packages/loot-core/src/server/models.ts b/packages/loot-core/src/server/models.ts
index 3a745b3d50..b656e10986 100644
--- a/packages/loot-core/src/server/models.ts
+++ b/packages/loot-core/src/server/models.ts
@@ -11,7 +11,13 @@ import {
schema,
schemaConfig,
} from './aql';
-import type { DbAccount, DbCategory, DbCategoryGroup, DbPayee } from './db';
+import type {
+ DbAccount,
+ DbAccountGroup,
+ DbCategory,
+ DbCategoryGroup,
+ DbPayee,
+} from './db';
import { ValidationError } from './errors';
export function requiredFields<T extends object, K extends keyof T>(
@@ -69,6 +75,23 @@ export const accountModel = {
},
};
+export const accountGroupModel = {
+ validate<T extends Partial<DbAccountGroup>>(
+ accountGroup: T,
+ { update }: { update?: boolean } = {},
+ ): Omit<T, 'sort_order'> {
+ requiredFields<Partial<DbAccountGroup>, 'name'>(
+ 'accountGroup',
+ accountGroup,
+ ['name'],
+ update,
+ );
+
+ const { sort_order: _sort_order, ...rest } = accountGroup;
+ return rest;
+ },
+};
+
export const categoryModel = {
validate(
category: Partial<DbCategory>,
diff --git a/packages/loot-core/src/types/api-handlers.ts b/packages/loot-core/src/types/api-handlers.ts
index 84a23be64a..383e178801 100644
--- a/packages/loot-core/src/types/api-handlers.ts
+++ b/packages/loot-core/src/types/api-handlers.ts
@@ -2,6 +2,7 @@
import type { ImportTransactionsResult } from '#server/accounts/app';
import type {
APIAccountEntity,
+ APIAccountGroupEntity,
APICategoryEntity,
APICategoryGroupEntity,
APIFileEntity,
@@ -164,6 +165,21 @@ export type ApiHandlers = {
cutoff?: Date;
}) => Promise<number>;
+ 'api/account-groups-get': () => Promise<APIAccountGroupEntity[]>;
+
+ 'api/account-group-create': (arg: {
+ group: Omit<APIAccountGroupEntity, 'id'>;
+ }) => Promise<APIAccountGroupEntity['id']>;
+
+ 'api/account-group-update': (arg: {
+ id: APIAccountGroupEntity['id'];
+ fields: Partial<Omit<APIAccountGroupEntity, 'id'>>;
+ }) => Promise<void>;
+
+ 'api/account-group-delete': (arg: {
+ id: APIAccountGroupEntity['id'];
+ }) => Promise<void>;
+
'api/categories-get': (arg: {
hidden?: boolean;
}) => Promise<APICategoryEntity[]>;
diff --git a/packages/loot-core/src/types/handlers.ts b/packages/loot-core/src/types/handlers.ts
index 5921ad3b3a..1db87b0060 100644
--- a/packages/loot-core/src/types/handlers.ts
+++ b/packages/loot-core/src/types/handlers.ts
@@ -1,3 +1,4 @@
+import type { AccountGroupsHandlers } from '#server/account-groups/app';
import type { AccountHandlers } from '#server/accounts/app';
import type { AdminHandlers } from '#server/admin/app';
import type { AuthHandlers } from '#server/auth/app';
@@ -39,6 +40,7 @@ export type Handlers = {} & ServerHandlers &
AdminHandlers &
ToolsHandlers &
AccountHandlers &
+ AccountGroupsHandlers &
PayeesHandlers &
SpreadsheetHandlers &
SyncHandlers &
diff --git a/packages/loot-core/src/types/models/account-group.ts b/packages/loot-core/src/types/models/account-group.ts
new file mode 100644
index 0000000000..3d5909f2ce
--- /dev/null
+++ b/packages/loot-core/src/types/models/account-group.ts
@@ -0,0 +1,6 @@
+export type AccountGroupEntity = {
+ id: string;
+ name: string;
+ sort_order: number;
+ tombstone?: boolean;
+};
diff --git a/packages/loot-core/src/types/models/account.ts b/packages/loot-core/src/types/models/account.ts
index c05529489a..c07fe1f387 100644
--- a/packages/loot-core/src/types/models/account.ts
+++ b/packages/loot-core/src/types/models/account.ts
@@ -1,3 +1,4 @@
+import type { AccountGroupEntity } from './account-group';
import type { BankSyncProviders } from './bank-sync';
export type AccountEntity = {
@@ -8,6 +9,7 @@ export type AccountEntity = {
sort_order: number;
last_reconciled: string | null;
tombstone: 0 | 1;
+ account_group_id: AccountGroupEntity['id'] | null;
// Sync fields
account_id: string | null;
diff --git a/packages/loot-core/src/types/models/index.ts b/packages/loot-core/src/types/models/index.ts
index 2516ef6694..9f8f908983 100644
--- a/packages/loot-core/src/types/models/index.ts
+++ b/packages/loot-core/src/types/models/index.ts
@@ -1,4 +1,5 @@
export type * from './account';
+export type * from './account-group';
export type * from './akahu';
export type * from './bank';
export type * from './bank-sync';
diff --git a/upcoming-release-notes/add-account-groups-backend.md b/upcoming-release-notes/add-account-groups-backend.md
new file mode 100644
index 0000000000..cac11f1473
--- /dev/null
+++ b/upcoming-release-notes/add-account-groups-backend.md
@@ -0,0 +1,6 @@
+---
+category: Features
+authors: [matt-fidd]
+---
+
+Add backend support for grouping accounts into custom account groups