Skip to content

A local-first personal finance app

[AI] Implement tag-split report calculations and persistence (#8947)

Julian Dominguez-Schatz01dadbcae934
diff --git a/packages/desktop-client/package.json b/packages/desktop-client/package.json
index 59adfc4341..b07e0702ba 100644
--- a/packages/desktop-client/package.json
+++ b/packages/desktop-client/package.json
@@ -75,6 +75,7 @@
"#components/reports/reports/monte-carlo/monteCarloYearStory": "./src/components/reports/reports/monte-carlo/monteCarloYearStory.ts",
"#components/reports/reports/monte-carlo/useResolvedMonteCarloConfig": "./src/components/reports/reports/monte-carlo/useResolvedMonteCarloConfig.ts",
"#components/reports/setSessionReport": "./src/components/reports/setSessionReport.ts",
+ "#components/reports/tagScope": "./src/components/reports/tagScope.ts",
"#components/reports/spendingAverageRange": "./src/components/reports/spendingAverageRange.ts",
"#components/reports/spreadsheets/cash-flow-spreadsheet": "./src/components/reports/spreadsheets/cash-flow-spreadsheet.tsx",
"#components/reports/spreadsheets/*": "./src/components/reports/spreadsheets/*.ts",
diff --git a/packages/desktop-client/src/components/reports/ReportOptions.ts b/packages/desktop-client/src/components/reports/ReportOptions.ts
index f2c2c0c137..e9bfd63525 100644
--- a/packages/desktop-client/src/components/reports/ReportOptions.ts
+++ b/packages/desktop-client/src/components/reports/ReportOptions.ts
@@ -19,6 +19,7 @@ export const defaultReport: CustomReportEntity = {
dateRange: 'Last 6 months',
mode: 'total',
groupBy: 'Category',
+ tagScope: { mode: 'all' },
interval: 'Monthly',
balanceType: 'Payment',
sortBy: 'desc',
@@ -325,7 +326,7 @@ export function getIntervalFormat(
export type QueryDataEntity = {
date: string;
- category: string;
+ category: string | null;
categoryHidden: boolean;
categoryGroup: string;
categoryGroupHidden: boolean;
@@ -333,6 +334,8 @@ export type QueryDataEntity = {
accountOffBudget: boolean;
payee: string;
transferAccount: string;
+ notes?: string | null;
+ tagBucketId?: string;
amount: number;
};
@@ -343,6 +346,7 @@ export type UncategorizedEntity = Pick<
'id' | 'name' | 'hidden'
> & {
uncategorized_id?: UncategorizedId;
+ bucketTagNames?: string[];
};
const uncategorizedCategory: UncategorizedEntity = {
@@ -415,10 +419,15 @@ export const groupBySelections = (
accounts: UncategorizedEntity[],
): [
UncategorizedEntity[],
- 'category' | 'categoryGroup' | 'payee' | 'account',
+ 'category' | 'categoryGroup' | 'payee' | 'account' | 'tagBucketId',
] => {
let groupByList: UncategorizedEntity[];
- let groupByLabel: 'category' | 'categoryGroup' | 'payee' | 'account';
+ let groupByLabel:
+ | 'category'
+ | 'categoryGroup'
+ | 'payee'
+ | 'account'
+ | 'tagBucketId';
switch (groupBy) {
case 'Category':
groupByList = categoryList;
@@ -461,6 +470,10 @@ export const groupBySelections = (
});
groupByLabel = 'account';
break;
+ case 'Tag':
+ groupByList = [];
+ groupByLabel = 'tagBucketId';
+ break;
case 'Interval':
groupByList = categoryList;
groupByLabel = 'category';
diff --git a/packages/desktop-client/src/components/reports/graphs/showActivity.test.ts b/packages/desktop-client/src/components/reports/graphs/showActivity.test.ts
index 352595869e..12ec90394b 100644
--- a/packages/desktop-client/src/components/reports/graphs/showActivity.test.ts
+++ b/packages/desktop-client/src/components/reports/graphs/showActivity.test.ts
@@ -1,3 +1,4 @@
+import { makeExactTagSetQueryFilter } from '@actual-app/core/shared/tags';
import type {
AccountEntity,
CategoryEntity,
@@ -14,6 +15,37 @@ const categories: { grouped: CategoryGroupEntity[]; list: CategoryEntity[] } = {
const accounts: AccountEntity[] = [];
describe('showActivity', () => {
+ it('uses the exact tag query filter when opening report activity', () => {
+ const navigate = vi.fn();
+
+ showActivity({
+ navigate,
+ categories,
+ accounts,
+ balanceTypeOp: 'totalAssets',
+ filters: [],
+ showHiddenCategories: true,
+ showOffBudget: true,
+ type: 'totals',
+ startDate: '2026-05-24',
+ endDate: '2026-05-30',
+ field: 'tag',
+ id: 'tag-group:circle-id:red-id',
+ bucketTagNames: ['circle', 'red'],
+ scopeTagNames: ['circle', 'red', 'blue'],
+ });
+
+ const [, options] = navigate.mock.calls[0];
+ expect(options.state.filterConditions).toContainEqual(
+ expect.objectContaining({
+ queryFilter: makeExactTagSetQueryFilter(
+ ['circle', 'red'],
+ ['circle', 'red', 'blue'],
+ ),
+ }),
+ );
+ });
+
it('adds a transfer filter for the virtual Transfers category', () => {
const navigate = vi.fn();
diff --git a/packages/desktop-client/src/components/reports/graphs/showActivity.ts b/packages/desktop-client/src/components/reports/graphs/showActivity.ts
index 86f27c588f..2080db61d5 100644
--- a/packages/desktop-client/src/components/reports/graphs/showActivity.ts
+++ b/packages/desktop-client/src/components/reports/graphs/showActivity.ts
@@ -1,6 +1,7 @@
import type { NavigateFunction } from 'react-router';
import * as monthUtils from '@actual-app/core/shared/months';
+import { makeExactTagSetQueryFilter } from '@actual-app/core/shared/tags';
import type {
AccountEntity,
balanceTypeOpType,
@@ -8,6 +9,7 @@ import type {
CategoryGroupEntity,
RuleConditionEntity,
} from '@actual-app/core/types/models';
+import { t } from 'i18next';
import { ReportOptions } from '#components/reports/ReportOptions';
@@ -26,6 +28,8 @@ type showActivityProps = {
id?: string | string[]; // changed: supports array for oneOf
uncategorizedId?: 'off_budget' | 'transfer' | 'other' | 'all';
interval?: string;
+ bucketTagNames?: string[];
+ scopeTagNames?: string[];
};
export function showActivity({
@@ -43,6 +47,8 @@ export function showActivity({
id,
uncategorizedId,
interval = 'Day',
+ bucketTagNames,
+ scopeTagNames = [],
}: showActivityProps) {
const isOutFlow =
balanceTypeOp === 'totalDebts' || type === 'debts' ? true : false;
@@ -55,28 +61,45 @@ export function showActivity({
'FromDate') as 'dayFromDate' | 'monthFromDate' | 'yearFromDate');
const isDateOp = interval === 'Weekly' || type !== 'time';
const drilldownFilter =
- field === 'category' && uncategorizedId === 'transfer'
+ field === 'tag' && bucketTagNames
? {
- field: 'transfer',
- op: 'is',
- value: true,
- type: 'boolean',
+ field: 'notes',
+ op: 'hasTags',
+ value: bucketTagNames.map(tag => `#${tag}`).join(' '),
+ type: 'string',
+ customName:
+ bucketTagNames.length === 0
+ ? t('Tag: Untagged')
+ : t('Tag: {{tags}}', {
+ tags: bucketTagNames.map(tag => `#${tag}`).join(' + '),
+ }),
+ queryFilter: makeExactTagSetQueryFilter(
+ bucketTagNames,
+ scopeTagNames,
+ ),
}
- : field === 'group'
- ? !uncategorizedId &&
- id && {
- field: 'category_group',
+ : field === 'category' && uncategorizedId === 'transfer'
+ ? {
+ field: 'transfer',
op: 'is',
- value: id,
- type: 'id',
+ value: true,
+ type: 'boolean',
}
- : id && {
- // changed: use oneOf when id is an array, is when it's a string
- field,
- op: Array.isArray(id) ? 'oneOf' : 'is',
- value: id,
- type: 'id',
- };
+ : field === 'group'
+ ? !uncategorizedId &&
+ id && {
+ field: 'category_group',
+ op: 'is',
+ value: id,
+ type: 'id',
+ }
+ : id && {
+ // changed: use oneOf when id is an array, is when it's a string
+ field,
+ op: Array.isArray(id) ? 'oneOf' : 'is',
+ value: id,
+ type: 'id',
+ };
const filterConditions = [
...filters,
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/calculateLegend.ts b/packages/desktop-client/src/components/reports/spreadsheets/calculateLegend.ts
index 9f44358785..336259afe7 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/calculateLegend.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/calculateLegend.ts
@@ -73,6 +73,8 @@ export function calculateLegend(
dataKey: item.id || item.name || '', // Use id for unique data lookup
uncategorizedId:
'uncategorizedId' in item.data ? item.data.uncategorizedId : undefined,
+ bucketTagNames:
+ 'bucketTagNames' in item.data ? item.data.bucketTagNames : undefined,
};
});
return legend;
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/custom-spreadsheet.test.ts b/packages/desktop-client/src/components/reports/spreadsheets/custom-spreadsheet.test.ts
new file mode 100644
index 0000000000..ed8f64ab2a
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/spreadsheets/custom-spreadsheet.test.ts
@@ -0,0 +1,79 @@
+import type { DataEntity } from '@actual-app/core/types/models';
+import { renderHook } from '@testing-library/react';
+
+import type { QueryDataEntity } from '#components/reports/ReportOptions';
+import { SpreadsheetProvider, useSpreadsheet } from '#hooks/useSpreadsheet';
+
+import { createCustomSpreadsheet } from './custom-spreadsheet';
+import { fetchSpreadsheetQueryData } from './fetchSpreadsheetQueryData';
+
+vi.mock('@actual-app/core/platform/client/connection', () => ({
+ send: vi.fn().mockResolvedValue({ filters: [] }),
+ listen: vi.fn(() => vi.fn()),
+}));
+vi.mock('./fetchSpreadsheetQueryData');
+
+const transaction: QueryDataEntity = {
+ date: '2026-01',
+ category: 'category',
+ categoryHidden: false,
+ categoryGroup: 'group',
+ categoryGroupHidden: false,
+ account: 'account',
+ accountOffBudget: false,
+ payee: 'payee',
+ transferAccount: '',
+ notes: '#red #circle',
+ amount: -100,
+};
+
+it.each([
+ { categoryHidden: true },
+ { categoryGroupHidden: true },
+ { accountOffBudget: true },
+ { category: null },
+])(
+ 'does not create empty combinations from excluded transactions %j',
+ async excluded => {
+ vi.mocked(fetchSpreadsheetQueryData).mockResolvedValue({
+ assets: [],
+ debts: [
+ { ...transaction, ...excluded },
+ { ...transaction, notes: '#red', amount: -50 },
+ { ...transaction, notes: '#red', amount: -25, date: '2026-02' },
+ ],
+ });
+ const { result } = renderHook(useSpreadsheet, {
+ wrapper: SpreadsheetProvider,
+ });
+ const setData = vi.fn<(data: DataEntity) => void>();
+ await createCustomSpreadsheet({
+ startDate: '2026-01',
+ endDate: '2026-02',
+ interval: 'Monthly',
+ categories: { list: [], grouped: [] },
+ conditions: [],
+ conditionsOp: 'and',
+ showEmpty: true,
+ showOffBudget: false,
+ showHiddenCategories: false,
+ showUncategorized: false,
+ trimIntervals: false,
+ groupBy: 'Tag',
+ tags: [
+ { id: 'red', tag: 'red' },
+ { id: 'circle', tag: 'circle' },
+ ],
+ })(result.current, setData);
+
+ const data = setData.mock.calls[0][0];
+ expect(data.data?.map(group => group.name)).toEqual(
+ expect.arrayContaining(['#red', '#circle', 'Untagged']),
+ );
+ expect(data.data).toHaveLength(3);
+ expect(data.totalDebts).toBe(-75);
+ expect(data.intervalData.map(interval => interval.totalDebts)).toEqual([
+ -50, -25,
+ ]);
+ },
+);
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/custom-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/custom-spreadsheet.ts
index 59a4adf763..86853859f6 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/custom-spreadsheet.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/custom-spreadsheet.ts
@@ -5,12 +5,14 @@ import type {
balanceTypeOpType,
CategoryEntity,
CategoryGroupEntity,
+ CustomReportTagScope,
DataEntity,
GroupedEntity,
IntervalEntity,
PayeeEntity,
RuleConditionEntity,
sortByOpType,
+ TagEntity,
} from '@actual-app/core/types/models';
import type { SyncedPrefs } from '@actual-app/core/types/prefs';
import * as d from 'date-fns';
@@ -21,18 +23,20 @@ import {
groupBySelections,
ReportOptions,
} from '#components/reports/ReportOptions';
-import type {
- QueryDataEntity,
- UncategorizedEntity,
-} from '#components/reports/ReportOptions';
+import type { QueryDataEntity } from '#components/reports/ReportOptions';
+import { resolveTagScope } from '#components/reports/tagScope';
import type { useSpreadsheet } from '#hooks/useSpreadsheet';
import { calculateLegend } from './calculateLegend';
import { fetchSpreadsheetQueryData } from './fetchSpreadsheetQueryData';
import { filterEmptyRows } from './filterEmptyRows';
-import { filterHiddenItems } from './filterHiddenItems';
+import {
+ filterHiddenItems,
+ filterReportTransactions,
+} from './filterHiddenItems';
import { recalculate } from './recalculate';
import { sortData } from './sortData';
+import { groupQueryDataByTags } from './tagGroups';
import {
determineIntervalRange,
trimIntervalDataToRange,
@@ -57,6 +61,8 @@ export type createCustomSpreadsheetProps = {
sortByOp?: sortByOpType;
payees?: PayeeEntity[];
accounts?: AccountEntity[];
+ tags?: TagEntity[];
+ tagScope?: CustomReportTagScope;
graphType?: string;
firstDayOfWeekIdx?: SyncedPrefs['firstDayOfWeekIdx'];
dateFormat?: SyncedPrefs['dateFormat'];
@@ -80,35 +86,43 @@ export function createCustomSpreadsheet({
sortByOp = 'desc',
payees = [],
accounts = [],
+ tags = [],
+ tagScope,
graphType,
firstDayOfWeekIdx,
dateFormat,
}: createCustomSpreadsheetProps) {
const [categoryList, categoryGroup] = categoryLists(categories);
-
- const [groupByList, groupByLabel]: [
- groupByList: UncategorizedEntity[],
- groupByLabel: 'category' | 'categoryGroup' | 'payee' | 'account',
- ] = groupBySelections(groupBy, categoryList, categoryGroup, payees, accounts);
+ const [initialGroups, groupByLabel] = groupBySelections(
+ groupBy,
+ categoryList,
+ categoryGroup,
+ payees,
+ accounts,
+ );
return async (
spreadsheet: ReturnType<typeof useSpreadsheet>,
setData: (data: DataEntity) => void,
) => {
- if (groupByList.length === 0) {
- setData({
- data: [],
- intervalData: [],
- legend: [],
- startDate,
- endDate,
- totalAssets: 0,
- totalDebts: 0,
- netAssets: 0,
- netDebts: 0,
- totalTotals: 0,
- totalBudgeted: 0,
- });
+ let groupByList = initialGroups;
+ let scopeTagNames: string[] | undefined;
+ const emptyData: DataEntity = {
+ data: [],
+ intervalData: [],
+ legend: [],
+ startDate,
+ endDate,
+ totalAssets: 0,
+ totalDebts: 0,
+ netAssets: 0,
+ netDebts: 0,
+ totalTotals: 0,
+ totalBudgeted: 0,
+ };
+
+ if (groupBy !== 'Tag' && groupByList.length === 0) {
+ setData(emptyData);
return;
}
@@ -132,8 +146,38 @@ export function createCustomSpreadsheet({
conditionsOpKey,
filters,
budgetType,
+ groupBy,
}));
+ if (groupBy === 'Tag') {
+ const resolvedScope = resolveTagScope(tags, tagScope);
+ scopeTagNames = resolvedScope.map(tag => tag.tag);
+ const groupedQueryData = groupQueryDataByTags({
+ assets: filterReportTransactions(
+ assets,
+ showOffBudget,
+ showHiddenCategories,
+ showUncategorized,
+ ),
+ debts: filterReportTransactions(
+ debts,
+ showOffBudget,
+ showHiddenCategories,
+ showUncategorized,
+ ),
+ tags: resolvedScope,
+ showEmpty,
+ });
+ assets = groupedQueryData.assets;
+ debts = groupedQueryData.debts;
+ groupByList = groupedQueryData.groups;
+ }
+
+ if (groupByList.length === 0) {
+ setData(emptyData);
+ return;
+ }
+
if (interval === 'Weekly' && balanceTypeOp !== 'totalBudgeted') {
debts = debts.map(d => {
return {
@@ -336,6 +380,7 @@ export function createCustomSpreadsheet({
// the underlying dataset when `balanceTypeOp === 'totalBudgeted'`.
totalTotals: totalAssets + totalDebts,
totalBudgeted: totalAssets + totalDebts,
+ scopeTagNames,
});
};
}
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/fetchSpreadsheetQueryData.ts b/packages/desktop-client/src/components/reports/spreadsheets/fetchSpreadsheetQueryData.ts
index 6a1aa2c1cc..450291e2b9 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/fetchSpreadsheetQueryData.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/fetchSpreadsheetQueryData.ts
@@ -24,6 +24,7 @@ export async function fetchSpreadsheetQueryData({
conditionsOpKey,
filters,
budgetType,
+ groupBy,
}: {
balanceTypeOp: balanceTypeOpType | undefined;
startDate: string;
@@ -36,6 +37,7 @@ export async function fetchSpreadsheetQueryData({
conditionsOpKey: string;
filters: unknown[];
budgetType?: SyncedPrefs['budgetType'];
+ groupBy?: string;
}): Promise<{ assets: QueryDataEntity[]; debts: QueryDataEntity[] }> {
if (balanceTypeOp === 'totalBudgeted') {
return fetchBudgetData({
@@ -59,6 +61,7 @@ export async function fetchSpreadsheetQueryData({
interval,
conditionsOpKey,
filters,
+ groupBy,
),
).then(({ data }) => data),
aqlQuery(
@@ -69,6 +72,7 @@ export async function fetchSpreadsheetQueryData({
interval,
conditionsOpKey,
filters,
+ groupBy,
),
).then(({ data }) => data),
]);
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/filterHiddenItems.ts b/packages/desktop-client/src/components/reports/spreadsheets/filterHiddenItems.ts
index 09069bf7a5..8a0fdcf082 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/filterHiddenItems.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/filterHiddenItems.ts
@@ -11,17 +11,12 @@ export function filterHiddenItems(
showUncategorized?: boolean,
groupByCategory?: boolean,
) {
- const showHide = data
- .filter(
- e =>
- showHiddenCategories ||
- (e.categoryHidden === false && e.categoryGroupHidden === false),
- )
- .filter(e => showOffBudget || e.accountOffBudget === false)
- .filter(
- e =>
- showUncategorized || e.category !== null || e.accountOffBudget === true,
- );
+ const showHide = filterReportTransactions(
+ data,
+ showOffBudget,
+ showHiddenCategories,
+ showUncategorized,
+ );
return showHide.filter(query => {
if (!groupByCategory) return true;
@@ -48,3 +43,22 @@ export function filterHiddenItems(
}
});
}
+
+export function filterReportTransactions(
+ data: QueryDataEntity[],
+ showOffBudget?: boolean,
+ showHiddenCategories?: boolean,
+ showUncategorized?: boolean,
+) {
+ return data
+ .filter(
+ e =>
+ showHiddenCategories ||
+ (e.categoryHidden === false && e.categoryGroupHidden === false),
+ )
+ .filter(e => showOffBudget || e.accountOffBudget === false)
+ .filter(
+ e =>
+ showUncategorized || e.category !== null || e.accountOffBudget === true,
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/makeQuery.test.ts b/packages/desktop-client/src/components/reports/spreadsheets/makeQuery.test.ts
new file mode 100644
index 0000000000..0ec164c969
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/spreadsheets/makeQuery.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+
+import { makeQuery } from './makeQuery';
+
+function serialize(groupBy?: string) {
+ return makeQuery(
+ 'assets',
+ '2026-01-01',
+ '2026-01-31',
+ 'Daily',
+ '$and',
+ [],
+ groupBy,
+ ).serialize();
+}
+
+describe('makeQuery', () => {
+ it('groups and selects notes for tag reports', () => {
+ const query = serialize('Tag');
+
+ expect(query.groupExpressions).toContain('notes');
+ expect(query.selectExpressions).toContain('notes');
+ });
+
+ it.each(['Category', 'Payee', 'Account', 'Interval', undefined])(
+ 'does not select notes for %s reports',
+ groupBy => {
+ const query = serialize(groupBy);
+
+ expect(query.groupExpressions).not.toContain('notes');
+ expect(query.selectExpressions).not.toContain('notes');
+ },
+ );
+});
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/makeQuery.ts b/packages/desktop-client/src/components/reports/spreadsheets/makeQuery.ts
index 1196648d21..def1439306 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/makeQuery.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/makeQuery.ts
@@ -1,4 +1,5 @@
import { q } from '@actual-app/core/shared/query';
+import type { ObjectExpression } from '@actual-app/core/shared/query';
import { ReportOptions } from '#components/reports/ReportOptions';
@@ -9,6 +10,7 @@ export function makeQuery(
interval: string,
conditionsOpKey: string,
filters: unknown[],
+ groupBy?: string,
) {
const intervalGroup =
interval === 'Monthly'
@@ -38,25 +40,31 @@ export function makeQuery(
name === 'assets' ? { amount: { $gt: 0 } } : { amount: { $lt: 0 } },
);
- return query
- .groupBy([
- intervalGroup,
- { $id: '$account' },
- { $id: '$payee' },
- { $id: '$category' },
- { $id: '$payee.transfer_acct.id' },
- ])
- .select([
- { date: intervalGroup },
- { category: { $id: '$category.id' } },
- { categoryHidden: { $id: '$category.hidden' } },
- { categoryIncome: { $id: '$category.is_income' } },
- { categoryGroup: { $id: '$category.group.id' } },
- { categoryGroupHidden: { $id: '$category.group.hidden' } },
- { account: { $id: '$account.id' } },
- { accountOffBudget: { $id: '$account.offbudget' } },
- { payee: { $id: '$payee.id' } },
- { transferAccount: { $id: '$payee.transfer_acct.id' } },
- { amount: { $sum: '$amount' } },
- ]);
+ const groupByFields: Array<ObjectExpression | string> = [
+ intervalGroup,
+ { $id: '$account' },
+ { $id: '$payee' },
+ { $id: '$category' },
+ { $id: '$payee.transfer_acct.id' },
+ ];
+ const selectedFields: Array<ObjectExpression | string> = [
+ { date: intervalGroup },
+ { category: { $id: '$category.id' } },
+ { categoryHidden: { $id: '$category.hidden' } },
+ { categoryIncome: { $id: '$category.is_income' } },
+ { categoryGroup: { $id: '$category.group.id' } },
+ { categoryGroupHidden: { $id: '$category.group.hidden' } },
+ { account: { $id: '$account.id' } },
+ { accountOffBudget: { $id: '$account.offbudget' } },
+ { payee: { $id: '$payee.id' } },
+ { transferAccount: { $id: '$payee.transfer_acct.id' } },
+ { amount: { $sum: '$amount' } },
+ ];
+
+ if (groupBy === 'Tag') {
+ groupByFields.push('notes');
+ selectedFields.push('notes');
+ }
+
+ return query.groupBy(groupByFields).select(selectedFields);
}
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/recalculate.ts b/packages/desktop-client/src/components/reports/spreadsheets/recalculate.ts
index 14432743b4..56cda83e26 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/recalculate.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/recalculate.ts
@@ -16,7 +16,12 @@ type recalculateProps = {
intervals: Array<string>;
assets: QueryDataEntity[];
debts: QueryDataEntity[];
- groupByLabel: 'category' | 'categoryGroup' | 'payee' | 'account';
+ groupByLabel:
+ | 'category'
+ | 'categoryGroup'
+ | 'payee'
+ | 'account'
+ | 'tagBucketId';
showOffBudget?: boolean;
showHiddenCategories?: boolean;
showUncategorized?: boolean;
@@ -109,6 +114,7 @@ export function recalculate({
id: item.id || '',
name: item.name,
uncategorizedId: item.uncategorized_id,
+ bucketTagNames: item.bucketTagNames,
totalAssets,
totalDebts,
netAssets: totalTotals > 0 ? totalTotals : 0,
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/tagGroups.test.ts b/packages/desktop-client/src/components/reports/spreadsheets/tagGroups.test.ts
new file mode 100644
index 0000000000..000eae6594
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/spreadsheets/tagGroups.test.ts
@@ -0,0 +1,120 @@
+import type { TagEntity } from '@actual-app/core/types/models';
+import { describe, expect, it } from 'vitest';
+
+import type { QueryDataEntity } from '#components/reports/ReportOptions';
+
+import { recalculate } from './recalculate';
+import { groupQueryDataByTags, UNTAGGED_BUCKET_ID } from './tagGroups';
+
+const tags: TagEntity[] = [
+ { id: 'red-id', tag: 'red' },
+ { id: 'circle-id', tag: 'circle' },
+];
+
+function row(notes: string | null, amount = 100): QueryDataEntity {
+ return {
+ date: '2026-01-01',
+ category: 'category',
+ categoryHidden: false,
+ categoryGroup: 'group',
+ categoryGroupHidden: false,
+ account: 'account',
+ accountOffBudget: false,
+ payee: 'payee',
+ transferAccount: '',
+ notes,
+ amount,
+ };
+}
+
+describe('groupQueryDataByTags', () => {
+ it('uses one bucket for distinct tags that collate equally in either order', () => {
+ const result = groupQueryDataByTags({
+ assets: [row('#é #é'), row('#é #é')],
+ debts: [],
+ tags: [
+ { id: 'a', tag: 'é' },
+ { id: 'b', tag: 'é' },
+ ],
+ showEmpty: false,
+ });
+
+ expect(result.groups).toHaveLength(1);
+ expect(result.assets[0].tagBucketId).toBe(result.assets[1].tagBucketId);
+ });
+
+ it('puts each row in one stable canonical bucket without double-counting', () => {
+ const result = groupQueryDataByTags({
+ assets: [
+ row('#red #circle #red', 125),
+ row('#red #unmanaged', 75),
+ row('#redder and ##red', 50),
+ ],
+ debts: [row(null, -40)],
+ tags,
+ showEmpty: false,
+ });
+
+ expect(result.groups).toEqual([
+ expect.objectContaining({
+ id: 'tag-group:circle-id:red-id',
+ name: '#circle + #red',
+ bucketTagNames: ['circle', 'red'],
+ }),
+ expect.objectContaining({
+ id: 'tag-group:red-id',
+ name: '#red',
+ bucketTagNames: ['red'],
+ }),
+ expect.objectContaining({
+ id: UNTAGGED_BUCKET_ID,
+ name: 'Untagged',
+ bucketTagNames: [],
+ }),
+ ]);
+ const intervalTotals = result.groups.map(item =>
+ recalculate({
+ item,
+ intervals: ['2026-01-01'],
+ assets: result.assets,
+ debts: result.debts,
+ groupByLabel: 'tagBucketId',
+ startDate: '2026-01-01',
+ endDate: '2026-01-01',
+ }),
+ );
+ expect(
+ intervalTotals.reduce((total, item) => total + item.totalTotals, 0),
+ ).toBe(210);
+ });
+
+ it('reduces a combination to the selected tag and ignores unrelated tags', () => {
+ const result = groupQueryDataByTags({
+ assets: [row('#red #circle', 125), row('#circle', 25)],
+ debts: [],
+ tags: [tags[0]],
+ showEmpty: false,
+ });
+
+ expect(result.assets.map(item => item.tagBucketId)).toEqual([
+ 'tag-group:red-id',
+ UNTAGGED_BUCKET_ID,
+ ]);
+ });
+
+ it('only synthesizes singleton and Untagged buckets for empty rows', () => {
+ const result = groupQueryDataByTags({
+ assets: [row('#red #circle')],
+ debts: [],
+ tags,
+ showEmpty: true,
+ });
+
+ expect(result.groups.map(group => group.name)).toEqual([
+ '#red',
+ '#circle',
+ 'Untagged',
+ '#circle + #red',
+ ]);
+ });
+});
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/tagGroups.ts b/packages/desktop-client/src/components/reports/spreadsheets/tagGroups.ts
new file mode 100644
index 0000000000..e1b6bb13a8
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/spreadsheets/tagGroups.ts
@@ -0,0 +1,85 @@
+import { extractTagsFromText } from '@actual-app/core/shared/tags';
+import type { TagEntity } from '@actual-app/core/types/models';
+import { t } from 'i18next';
+
+import type {
+ QueryDataEntity,
+ UncategorizedEntity,
+} from '#components/reports/ReportOptions';
+
+export const UNTAGGED_BUCKET_ID = 'tag-group:untagged';
+
+const tagCollator = new Intl.Collator('en', {
+ numeric: true,
+ sensitivity: 'variant',
+});
+
+function makeTagBucket(tags: TagEntity[]): UncategorizedEntity {
+ if (tags.length === 0) {
+ return {
+ id: UNTAGGED_BUCKET_ID,
+ name: t('Untagged'),
+ hidden: false,
+ bucketTagNames: [],
+ };
+ }
+
+ const sortedTags = [...tags].sort(
+ (a, b) => tagCollator.compare(a.tag, b.tag) || a.id.localeCompare(b.id),
+ );
+
+ return {
+ id: `tag-group:${sortedTags.map(tag => tag.id).join(':')}`,
+ name: sortedTags.map(tag => `#${tag.tag}`).join(' + '),
+ hidden: false,
+ bucketTagNames: sortedTags.map(tag => tag.tag),
+ };
+}
+
+function assignTagBucket(
+ row: QueryDataEntity,
+ tagsByName: Map<string, TagEntity>,
+ buckets: Map<string, UncategorizedEntity>,
+): QueryDataEntity {
+ const matchingTags = extractTagsFromText(row.notes ?? '')
+ .map(tagName => tagsByName.get(tagName))
+ .filter((tag): tag is TagEntity => tag !== undefined);
+ const bucket = makeTagBucket(matchingTags);
+ buckets.set(bucket.id, bucket);
+
+ return { ...row, tagBucketId: bucket.id };
+}
+
+export function groupQueryDataByTags({
+ assets,
+ debts,
+ tags,
+ showEmpty,
+}: {
+ assets: QueryDataEntity[];
+ debts: QueryDataEntity[];
+ tags: TagEntity[];
+ showEmpty: boolean;
+}): {
+ assets: QueryDataEntity[];
+ debts: QueryDataEntity[];
+ groups: UncategorizedEntity[];
+} {
+ const tagsByName = new Map(tags.map(tag => [tag.tag, tag]));
+ const buckets = new Map<string, UncategorizedEntity>();
+
+ if (showEmpty) {
+ for (const tag of tags) {
+ const bucket = makeTagBucket([tag]);
+ buckets.set(bucket.id, bucket);
+ }
+ const untaggedBucket = makeTagBucket([]);
+ buckets.set(untaggedBucket.id, untaggedBucket);
+ }
+
+ return {
+ assets: assets.map(row => assignTagBucket(row, tagsByName, buckets)),
+ debts: debts.map(row => assignTagBucket(row, tagsByName, buckets)),
+ groups: [...buckets.values()],
+ };
+}
diff --git a/packages/desktop-client/src/components/reports/tagScope.test.ts b/packages/desktop-client/src/components/reports/tagScope.test.ts
new file mode 100644
index 0000000000..70fe3d8fa3
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/tagScope.test.ts
@@ -0,0 +1,39 @@
+import type {
+ CustomReportTagScope,
+ TagEntity,
+} from '@actual-app/core/types/models';
+import { describe, expect, it } from 'vitest';
+
+import { normalizeTagScope, resolveTagScope } from './tagScope';
+
+const tags: TagEntity[] = [
+ { id: 'red-id', tag: 'red' },
+ { id: 'circle-id', tag: 'circle' },
+ { id: 'hidden-id', tag: 'hidden', hidden: true },
+];
+
+describe('tag scope', () => {
+ it('defaults missing and empty selections to all visible tags', () => {
+ const scopes: (CustomReportTagScope | undefined)[] = [
+ undefined,
+ { mode: 'selected', tagIds: [] },
+ ];
+ for (const scope of scopes) {
+ const normalized = normalizeTagScope(scope);
+ expect(normalized).toEqual({ mode: 'all' });
+ expect(resolveTagScope(tags, normalized)).toEqual(tags.slice(0, 2));
+ }
+ });
+
+ it('retains saved IDs but excludes hidden or missing tags from grouping', () => {
+ const scope = normalizeTagScope({
+ mode: 'selected',
+ tagIds: ['red-id', 'hidden-id', 'missing-id'],
+ });
+ expect(scope).toEqual({
+ mode: 'selected',
+ tagIds: ['red-id', 'hidden-id', 'missing-id'],
+ });
+ expect(resolveTagScope(tags, scope)).toEqual([tags[0]]);
+ });
+});
diff --git a/packages/desktop-client/src/components/reports/tagScope.ts b/packages/desktop-client/src/components/reports/tagScope.ts
new file mode 100644
index 0000000000..8a088b6d18
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/tagScope.ts
@@ -0,0 +1,30 @@
+import type {
+ CustomReportTagScope,
+ TagEntity,
+} from '@actual-app/core/types/models';
+
+export function normalizeTagScope(
+ scope: CustomReportTagScope | null | undefined,
+): CustomReportTagScope {
+ if (!scope || (scope.mode === 'selected' && scope.tagIds.length === 0)) {
+ return { mode: 'all' };
+ }
+
+ return scope;
+}
+
+export function resolveTagScope(
+ tags: TagEntity[],
+ tagScope: CustomReportTagScope | undefined,
+): TagEntity[] {
+ const visibleTags = tags.filter(tag => !tag.hidden);
+ const scope = normalizeTagScope(tagScope);
+ if (scope.mode === 'all') {
+ return visibleTags;
+ }
+
+ const tagsById = new Map(visibleTags.map(tag => [tag.id, tag]));
+ return scope.tagIds
+ .map(id => tagsById.get(id))
+ .filter((tag): tag is TagEntity => tag !== undefined);
+}
diff --git a/packages/desktop-client/src/components/reports/util.test.ts b/packages/desktop-client/src/components/reports/util.test.ts
new file mode 100644
index 0000000000..7cd46123b6
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/util.test.ts
@@ -0,0 +1,46 @@
+import type { TagEntity } from '@actual-app/core/types/models';
+import { describe, expect, it } from 'vitest';
+
+import { calculateHasWarning } from './util';
+
+const tags: TagEntity[] = [
+ { id: 'visible-id', tag: 'visible' },
+ { id: 'hidden-id', tag: 'hidden', hidden: true },
+];
+
+describe('calculateHasWarning tag scope', () => {
+ const entities = { categories: [], accounts: [], payees: [], tags };
+
+ it('accepts all tags and a selected visible tag', () => {
+ expect(
+ calculateHasWarning([], {
+ ...entities,
+ tagScope: { mode: 'all' },
+ }),
+ ).toBe(false);
+ expect(
+ calculateHasWarning([], {
+ ...entities,
+ tagScope: { mode: 'selected', tagIds: ['visible-id'] },
+ }),
+ ).toBe(false);
+ });
+
+ it('warns when a selected tag is missing or hidden', () => {
+ expect(
+ calculateHasWarning([], {
+ ...entities,
+ tagScope: {
+ mode: 'selected',
+ tagIds: ['visible-id', 'missing-id'],
+ },
+ }),
+ ).toBe(true);
+ expect(
+ calculateHasWarning([], {
+ ...entities,
+ tagScope: { mode: 'selected', tagIds: ['hidden-id'] },
+ }),
+ ).toBe(true);
+ });
+});
diff --git a/packages/desktop-client/src/components/reports/util.ts b/packages/desktop-client/src/components/reports/util.ts
index a733e25eff..27a9db8554 100644
--- a/packages/desktop-client/src/components/reports/util.ts
+++ b/packages/desktop-client/src/components/reports/util.ts
@@ -3,8 +3,10 @@ import type { Query } from '@actual-app/core/shared/query';
import type {
AccountEntity,
CategoryEntity,
+ CustomReportTagScope,
PayeeEntity,
RuleConditionEntity,
+ TagEntity,
} from '@actual-app/core/types/models';
import { aqlQuery } from '#queries/aqlQuery';
@@ -39,7 +41,7 @@ export function indexCashFlow<
/**
* Checks if the given conditions have issues
- * (i.e. non-existing category/payee/account being used).
+ * (i.e. a non-existing category/payee/account/tag being used).
*/
export function calculateHasWarning(
@@ -48,15 +50,27 @@ export function calculateHasWarning(
categories,
accounts,
payees,
+ tags = [],
+ tagScope,
}: {
categories: CategoryEntity[];
accounts: AccountEntity[];
payees: PayeeEntity[];
+ tags?: TagEntity[];
+ tagScope?: CustomReportTagScope;
},
) {
const categoryIds = new Set(categories.map(({ id }) => id));
const payeeIds = new Set(payees.map(({ id }) => id));
const accountIds = new Set(accounts.map(({ id }) => id));
+ const tagIds = new Set(tags.filter(tag => !tag.hidden).map(({ id }) => id));
+
+ if (
+ tagScope?.mode === 'selected' &&
+ tagScope.tagIds.some(id => !tagIds.has(id))
+ ) {
+ return true;
+ }
if (!conditions) {
return false;
diff --git a/packages/loot-core/src/server/aql/compiler.ts b/packages/loot-core/src/server/aql/compiler.ts
index bbdbf059a7..b44af9f6d7 100644
--- a/packages/loot-core/src/server/aql/compiler.ts
+++ b/packages/loot-core/src/server/aql/compiler.ts
@@ -738,6 +738,10 @@ const compileOp = saveStack('op', (state, fieldRef, opData) => {
const [left, right] = valArray(state, [lhs, rhs], ['string', 'string']);
return `REGEXP(${right}, ${left})`;
}
+ case '$notregexp': {
+ const [left, right] = valArray(state, [lhs, rhs], ['string', 'string']);
+ return `(NOT REGEXP(${right}, ${left}) OR ${left} IS NULL)`;
+ }
case '$notlike': {
const [left, right] = valArray(state, [lhs, rhs], ['string', 'string']);
return `(NOT UNICODE_LIKE(${getNormalisedString(right)}, NORMALISE(${left}))\n OR ${left} IS NULL)`;
diff --git a/packages/loot-core/src/server/reports/app.test.ts b/packages/loot-core/src/server/reports/app.test.ts
new file mode 100644
index 0000000000..aa31d7291e
--- /dev/null
+++ b/packages/loot-core/src/server/reports/app.test.ts
@@ -0,0 +1,173 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import * as fs from '#platform/server/fs';
+import { app as dashboardApp } from '#server/dashboard/app';
+import * as db from '#server/db';
+import { loadMappings } from '#server/db/mappings';
+import { runMutator } from '#server/mutators';
+import type { CustomReportEntity, CustomReportTagScope } from '#types/models';
+
+import { app as reportApp, reportModel } from './app';
+
+const dashboardImportPath = '/tmp/custom-report-dashboard.json';
+
+const report: CustomReportEntity = {
+ id: 'report-id',
+ name: 'Tags report',
+ startDate: '2026-01-01',
+ endDate: '2026-01-31',
+ isDateStatic: true,
+ dateRange: 'This month',
+ mode: 'total',
+ groupBy: 'Tag',
+ interval: 'Daily',
+ balanceType: 'Payment',
+ sortBy: 'desc',
+ showEmpty: false,
+ showOffBudget: false,
+ showHiddenCategories: false,
+ includeCurrentInterval: false,
+ showUncategorized: true,
+ trimIntervals: false,
+ showTrendLines: false,
+ graphType: 'TableGraph',
+ conditions: [],
+ conditionsOp: 'and',
+};
+
+async function writeDashboardReport(meta: unknown) {
+ await fs.writeFile(
+ dashboardImportPath,
+ JSON.stringify({
+ version: 1,
+ widgets: [
+ {
+ type: 'custom-report',
+ x: 0,
+ y: 0,
+ width: 4,
+ height: 2,
+ dashboard_page_id: 'exported-dashboard-page-id',
+ meta,
+ },
+ ],
+ }),
+ );
+}
+
+describe('custom report tag scope mapping', () => {
+ beforeEach(async () => {
+ await global.emptyDatabase()();
+ await loadMappings();
+ });
+
+ afterEach(async () => {
+ if (await fs.exists(dashboardImportPath)) {
+ await fs.removeFile(dashboardImportPath);
+ }
+ });
+
+ it('updates tag scope through SQLite and AQL, retaining missing IDs and other metadata', async () => {
+ const tagScope = {
+ mode: 'selected',
+ tagIds: ['visible-id', 'missing-id'],
+ } satisfies CustomReportTagScope;
+ await db.insertWithSchema(
+ 'custom_reports',
+ reportModel.fromJS({
+ ...report,
+ tagScope,
+ metadata: { presentation: 'compact' },
+ }),
+ );
+
+ const [selectedReport] = await reportApp.handlers['report/get']();
+ expect(selectedReport).toMatchObject({
+ tagScope,
+ metadata: { presentation: 'compact' },
+ });
+
+ await db.updateWithSchema(
+ 'custom_reports',
+ reportModel.fromJS({ ...selectedReport, tagScope: { mode: 'all' } }),
+ );
+ const [allTagsReport] = await reportApp.handlers['report/get']();
+ expect(allTagsReport).toMatchObject({
+ tagScope: { mode: 'all' },
+ metadata: { presentation: 'compact' },
+ });
+
+ await db.updateWithSchema(
+ 'custom_reports',
+ reportModel.fromJS({ ...allTagsReport, tagScope: undefined }),
+ );
+ const [clearedReport] = await reportApp.handlers['report/get']();
+ expect(clearedReport.tagScope).toBeUndefined();
+ expect(clearedReport.metadata).toEqual({ presentation: 'compact' });
+ });
+
+ it('loads reports that have no metadata', async () => {
+ const reportWithoutMetadata = reportModel.fromJS(report);
+ delete reportWithoutMetadata.metadata;
+ await db.insertWithSchema('custom_reports', reportWithoutMetadata);
+
+ const [loadedReport] = await reportApp.handlers['report/get']();
+ expect(loadedReport.tagScope).toBeUndefined();
+ });
+
+ it.each([
+ { balanceType: 'Budgeted' },
+ { tagScope: { mode: 'selected' } },
+ { tagScope: { mode: 'selected', tagIds: 'red-id' } },
+ { tagScope: { mode: 'selected', tagIds: [42] } },
+ { tagScope: { mode: 'unknown' } },
+ { tagScope: null },
+ ])('rejects invalid imported tag reports: %j', async invalid => {
+ await writeDashboardReport({ ...report, ...invalid });
+
+ await expect(
+ runMutator(() =>
+ dashboardApp.handlers['dashboard-import']({
+ filePath: dashboardImportPath,
+ dashboardPageId: 'dashboard-page-id',
+ }),
+ ),
+ ).rejects.toMatchObject({ cause: 'validation-error' });
+ expect(await reportApp.handlers['report/get']()).toEqual([]);
+ });
+
+ it.each<CustomReportTagScope>([
+ { mode: 'all' },
+ { mode: 'selected', tagIds: [] },
+ {
+ mode: 'selected',
+ tagIds: ['existing-id', 'missing-id'],
+ },
+ ])(
+ 'restores tag scope when importing a deleted report: %j',
+ async tagScope => {
+ await db.insertWithSchema(
+ 'custom_reports',
+ reportModel.fromJS({ ...report, tagScope }),
+ );
+ await db.insertWithSchema('dashboard_pages', {
+ id: 'dashboard-page-id',
+ name: 'Dashboard',
+ });
+
+ const [exportedReport] = await reportApp.handlers['report/get']();
+ await writeDashboardReport(exportedReport);
+
+ await db.delete_('custom_reports', report.id);
+ await runMutator(() =>
+ dashboardApp.handlers['dashboard-import']({
+ filePath: dashboardImportPath,
+ dashboardPageId: 'dashboard-page-id',
+ }),
+ );
+
+ const [importedReport] = await reportApp.handlers['report/get']();
+ expect(importedReport.tagScope).toEqual(tagScope);
+ },
+ );
+});
diff --git a/packages/loot-core/src/server/reports/app.ts b/packages/loot-core/src/server/reports/app.ts
index de16dedcaf..ec8b89f7e2 100644
--- a/packages/loot-core/src/server/reports/app.ts
+++ b/packages/loot-core/src/server/reports/app.ts
@@ -25,10 +25,28 @@ export const reportModel = {
}
}
+ if (report.groupBy === 'Tag' && report.balanceType === 'Budgeted') {
+ throw new ValidationError('Budgeted reports cannot be split by tags.');
+ }
+
+ const scope = report.tagScope;
+ if (
+ scope !== undefined &&
+ (scope === null ||
+ !['all', 'selected'].includes(scope.mode) ||
+ (scope.mode === 'selected' &&
+ (!Array.isArray(scope.tagIds) ||
+ scope.tagIds.some(id => typeof id !== 'string'))))
+ ) {
+ throw new ValidationError('Invalid report tag scope.');
+ }
+
return report;
},
toJS(row: CustomReportData): CustomReportEntity {
+ const { tagScope, ...metadata } = row.metadata ?? {};
+
return {
id: row.id,
name: row.name ?? '',
@@ -38,6 +56,7 @@ export const reportModel = {
dateRange: row.date_range,
mode: row.mode,
groupBy: row.group_by,
+ tagScope,
sortBy: row.sort_by,
interval: row.interval,
balanceType: row.balance_type,
@@ -51,7 +70,7 @@ export const reportModel = {
graphType: row.graph_type,
conditions: row.conditions ?? [],
conditionsOp: row.conditions_op ?? 'and',
- metadata: row.metadata,
+ metadata,
};
},
@@ -78,6 +97,7 @@ export const reportModel = {
graph_type: report.graphType,
conditions: report.conditions,
conditions_op: report.conditionsOp,
+ metadata: { ...report.metadata, tagScope: report.tagScope },
};
},
};
diff --git a/packages/loot-core/src/server/tags/app.test.ts b/packages/loot-core/src/server/tags/app.test.ts
index 0728c7d139..0a17d02cd9 100644
--- a/packages/loot-core/src/server/tags/app.test.ts
+++ b/packages/loot-core/src/server/tags/app.test.ts
@@ -102,3 +102,30 @@ describe('tags app', () => {
});
});
});
+
+it('discovers unique tags using exact hashtag boundaries', async () => {
+ const account = await db.insertAccount({ name: 'Checking' });
+ const existingId = await db.insertTag({ tag: 'red' });
+ for (const notes of [
+ '#red#circle #red ##ignored',
+ '#circle #Red #$splurge',
+ ]) {
+ await db.insertTransaction({
+ date: '2026-01-01',
+ account,
+ notes,
+ amount: -100,
+ });
+ }
+
+ const tags = await app.handlers['tags-discover']();
+
+ expect(tags.map(tag => tag.tag).sort()).toEqual([
+ '$splurge',
+ 'Red',
+ 'circle',
+ 'red',
+ ]);
+ expect(tags.find(tag => tag.tag === 'red')?.id).toBe(existingId);
+ expect(await db.getTags()).toHaveLength(4);
+});
diff --git a/packages/loot-core/src/server/tags/app.ts b/packages/loot-core/src/server/tags/app.ts
index a83e71d066..e5f2288d11 100644
--- a/packages/loot-core/src/server/tags/app.ts
+++ b/packages/loot-core/src/server/tags/app.ts
@@ -3,7 +3,7 @@ import * as db from '#server/db';
import { mutator } from '#server/mutators';
import { batchMessages } from '#server/sync';
import { undoable } from '#server/undo';
-import { renameTagInNotes } from '#shared/tags';
+import { extractTagsFromText, renameTagInNotes } from '#shared/tags';
import type { TagEntity } from '#types/models';
export type TagsHandlers = {
@@ -154,7 +154,7 @@ async function discoverTags(): Promise<TagEntity[]> {
const tags = await getTags();
for (const { notes } of taggedNotes) {
- for (const [_, tag] of notes.matchAll(/(?<!#)#([^#\s]+)/g)) {
+ for (const tag of extractTagsFromText(notes)) {
if (!tags.find(t => t.tag === tag)) {
tags.push(await createTag({ tag }));
}
diff --git a/packages/loot-core/src/server/transactions/transaction-rules.test.ts b/packages/loot-core/src/server/transactions/transaction-rules.test.ts
index 1819f00971..4fda79077d 100644
--- a/packages/loot-core/src/server/transactions/transaction-rules.test.ts
+++ b/packages/loot-core/src/server/transactions/transaction-rules.test.ts
@@ -3,6 +3,7 @@ import * as db from '#server/db';
import { loadMappings } from '#server/db/mappings';
// @ts-strict-ignore
import { q } from '#shared/query';
+import { extractTagsFromText, makeExactTagSetQueryFilter } from '#shared/tags';
import {
actionsReferenceBalance,
@@ -667,6 +668,120 @@ describe('Transaction rules', () => {
expect(transactions.map(t => t.id)).toEqual(['2']);
});
+ test('exact tag drill-down agrees with tag extraction at hashtag and regex boundaries', async () => {
+ const account = await db.insertAccount({ name: 'bank' });
+ const scope = ['red', 'circle', '$splurge', 'a.b', 'a+b', 'Red'];
+ const notes = [
+ '#red#circle',
+ '##red',
+ '#red##circle',
+ '#redder',
+ 'text#red',
+ '#Red',
+ '#red #red',
+ '#$splurge',
+ '#a.b',
+ '#axb',
+ '#a+b',
+ '#red\n#circle',
+ null,
+ ];
+ for (const [index, note] of notes.entries()) {
+ await db.insertTransaction({
+ id: String(index),
+ date: '2026-01-01',
+ account,
+ notes: note,
+ amount: 100,
+ });
+ }
+
+ for (const note of notes) {
+ const bucket = extractTagsFromText(note ?? '')
+ .filter(tag => scope.includes(tag))
+ .sort();
+ const { data } = await aqlQuery(
+ q('transactions')
+ .filter(makeExactTagSetQueryFilter(bucket, scope))
+ .select('id'),
+ );
+ const expectedIds = notes.flatMap((candidate, index) => {
+ const tags = extractTagsFromText(candidate ?? '')
+ .filter(tag => scope.includes(tag))
+ .sort();
+ return JSON.stringify(tags) === JSON.stringify(bucket)
+ ? [String(index)]
+ : [];
+ });
+ expect(data.map(row => row.id).sort()).toEqual(expectedIds.sort());
+ }
+
+ const { data } = await aqlQuery(
+ q('transactions').filter(makeExactTagSetQueryFilter([], [])).select('id'),
+ );
+ expect(data).toHaveLength(notes.length);
+ });
+
+ test('transactions can be queried by their exact tag set within a scope', async () => {
+ const account = await db.insertAccount({ name: 'bank' });
+ const payee = await db.insertPayee({ name: 'payee' });
+ const notes = [
+ '#red',
+ '#circle #red',
+ '#red #blue',
+ '#redder',
+ null,
+ '#blue',
+ ];
+
+ await Promise.all(
+ notes.map((note, index) =>
+ db.insertTransaction({
+ id: String(index + 1),
+ date: '2020-10-01',
+ account,
+ payee,
+ notes: note,
+ amount: 123,
+ }),
+ ),
+ );
+
+ async function query(tagNames: string[], scopeTagNames: string[]) {
+ const { data } = await aqlQuery(
+ q('transactions')
+ .filter(makeExactTagSetQueryFilter(tagNames, scopeTagNames))
+ .select('id'),
+ );
+ return data.map(transaction => transaction.id);
+ }
+
+ await expect(
+ query(
+ ['circle', 'red'],
+ [
+ 'mortgage',
+ 'circle',
+ 'red',
+ 'groceries',
+ '$splurge',
+ 'online-shopping',
+ 'subscription',
+ 'utilities',
+ ],
+ ),
+ ).resolves.toEqual(['2']);
+ await expect(query(['red'], ['circle', 'red'])).resolves.toEqual([
+ '1',
+ '3',
+ ]);
+ await expect(query([], ['circle', 'red'])).resolves.toEqual([
+ '4',
+ '5',
+ '6',
+ ]);
+ });
+
test('transactions can be queried by hasTags if no "#" is included', async () => {
await loadRules();
const account = await db.insertAccount({ name: 'bank' });
diff --git a/packages/loot-core/src/server/transactions/transaction-rules.ts b/packages/loot-core/src/server/transactions/transaction-rules.ts
index 5e3081dd91..a3e3329ad3 100644
--- a/packages/loot-core/src/server/transactions/transaction-rules.ts
+++ b/packages/loot-core/src/server/transactions/transaction-rules.ts
@@ -39,7 +39,7 @@ import {
} from '#shared/months';
import { q } from '#shared/query';
import { getApproxNumberThreshold, sortNumbers } from '#shared/rules';
-import { extractTagsForFilter } from '#shared/tags';
+import { extractTagsForFilter, makeTagAqlRegex } from '#shared/tags';
import { ungroupTransaction } from '#shared/transactions';
import { fastSetMerge, partitionByField } from '#shared/util';
import type {
@@ -677,13 +677,7 @@ export function conditionsToAQL(
}
return {
- $and: tagValues.map(v => {
- const escapedTag = v
- .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
- .replace(/\\\$/g, '[$]'); // Use '[$]' instead of '\$' so AQL string unescaping doesn't turn it into a bare '$' end-of-string anchor
- const pattern = `(?<!#)${escapedTag}([\\s#]|$)`;
- return apply(field, '$regexp', pattern);
- }),
+ $and: tagValues.map(v => apply(field, '$regexp', makeTagAqlRegex(v))),
};
}
@@ -693,13 +687,7 @@ export function conditionsToAQL(
return { id: null };
}
return {
- $or: tagValues.map(v => {
- const escapedTag = v
- .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
- .replace(/\\\$/g, '[$]'); // Use '[$]' instead of '\$' so AQL string unescaping doesn't turn it into a bare '$' end-of-string anchor
- const pattern = `(?<!#)${escapedTag}([\\s#]|$)`;
- return apply(field, '$regexp', pattern);
- }),
+ $or: tagValues.map(v => apply(field, '$regexp', makeTagAqlRegex(v))),
};
}
diff --git a/packages/loot-core/src/shared/tags.ts b/packages/loot-core/src/shared/tags.ts
index e156f08fbb..b04a605d8e 100644
--- a/packages/loot-core/src/shared/tags.ts
+++ b/packages/loot-core/src/shared/tags.ts
@@ -1,3 +1,5 @@
+import type { ObjectExpression } from './query';
+
// for a given string, returns an array of unique words
// (whitespace-separated) with only a single # prepended,
// so "one #one ##one ##two three" becomes
@@ -28,3 +30,46 @@ export function renameTagInNotes(
const pattern = new RegExp(`(?<!#)#${escaped}(?=[\\s#]|$)`, 'g');
return notes.replace(pattern, () => `#${newTag}`);
}
+
+export function extractTagsFromText(value: string): string[] {
+ if (!value) return [];
+
+ const tags: string[] = [];
+ const seenTags = new Set<string>();
+ for (const match of value.matchAll(/(?<!#)#([^#\s]+)/g)) {
+ const tag = match[1];
+ if (!seenTags.has(tag)) {
+ seenTags.add(tag);
+ tags.push(tag);
+ }
+ }
+
+ return tags;
+}
+
+export function makeTagAqlRegex(tag: string): string {
+ const tagWithHash = tag.startsWith('#') ? tag : `#${tag}`;
+ const escapedTag = tagWithHash
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+ // AQL unescapes `\$`, so a character class is needed for a literal `$`.
+ .replace(/\\\$/g, '[$]');
+
+ return `(^|[^#])${escapedTag}([\\s#]|$)`;
+}
+
+export function makeExactTagSetQueryFilter(
+ bucketTagNames: string[],
+ scopeTagNames: string[],
+): ObjectExpression {
+ const bucketTags = new Set(bucketTagNames);
+ const includedTagFilters = bucketTagNames.map(tag => ({
+ notes: { $regexp: makeTagAqlRegex(tag) },
+ }));
+ const excludedTagFilters = scopeTagNames
+ .filter(tag => !bucketTags.has(tag))
+ .map(tag => ({
+ notes: { $notregexp: makeTagAqlRegex(tag) },
+ }));
+
+ return { $and: [...includedTagFilters, ...excludedTagFilters] };
+}
diff --git a/packages/loot-core/src/types/models/reports.ts b/packages/loot-core/src/types/models/reports.ts
index 2675c9a3ae..28b9852dce 100644
--- a/packages/loot-core/src/types/models/reports.ts
+++ b/packages/loot-core/src/types/models/reports.ts
@@ -1,5 +1,15 @@
import type { RuleConditionEntity } from './rule';
+export type CustomReportTagScope =
+ | { mode: 'all' }
+ | { mode: 'selected'; tagIds: string[] };
+
+export type CustomReportMetadata = Record<string, unknown>;
+
+type CustomReportStoredMetadata = CustomReportMetadata & {
+ tagScope?: CustomReportTagScope;
+};
+
export type CustomReportEntity = {
id: string;
name: string;
@@ -9,6 +19,7 @@ export type CustomReportEntity = {
dateRange: string;
mode: string;
groupBy: string;
+ tagScope?: CustomReportTagScope;
interval: string;
balanceType: string;
sortBy?: sortByOpType;
@@ -22,7 +33,7 @@ export type CustomReportEntity = {
graphType: string;
conditions?: RuleConditionEntity[];
conditionsOp: 'and' | 'or';
- metadata?: GroupedEntity;
+ metadata?: CustomReportMetadata;
tombstone?: boolean;
};
@@ -88,6 +99,7 @@ export type DataEntity = {
netDebts: number;
totalTotals: number;
totalBudgeted: number;
+ scopeTagNames?: string[];
};
export type LegendEntity = {
@@ -96,6 +108,7 @@ export type LegendEntity = {
color: string;
dataKey: string; // Uses id for unique data lookup when categories have same name
uncategorizedId?: 'off_budget' | 'transfer' | 'other' | 'all';
+ bucketTagNames?: string[];
};
export type IntervalEntity = {
@@ -124,6 +137,7 @@ export type GroupedEntity = {
netDebts: number;
totalBudgeted: number;
categories?: GroupedEntity[];
+ bucketTagNames?: string[];
};
export type Interval = {
@@ -151,7 +165,7 @@ export type CustomReportData = {
graph_type: string;
conditions?: RuleConditionEntity[];
conditions_op: 'and' | 'or';
- metadata?: GroupedEntity;
+ metadata?: CustomReportStoredMetadata;
interval: string;
color_scheme?: string;
};
diff --git a/packages/loot-core/src/types/models/rule.ts b/packages/loot-core/src/types/models/rule.ts
index d22fb3d6b7..7c0665a1d0 100644
--- a/packages/loot-core/src/types/models/rule.ts
+++ b/packages/loot-core/src/types/models/rule.ts
@@ -1,3 +1,5 @@
+import type { ObjectExpression } from '#shared/query';
+
import type { RecurConfig, ScheduleEntity } from './schedule';
export type NewRuleEntity = {
@@ -51,7 +53,7 @@ type BaseConditionEntity<
conditionsOp?: 'and' | 'or';
type?: 'id' | 'boolean' | 'date' | 'number' | 'string';
customName?: string;
- queryFilter?: Record<string, { $oneof: string[] }>;
+ queryFilter?: ObjectExpression;
};
export type RuleConditionEntity =
diff --git a/upcoming-release-notes/tag-report-calculations.md b/upcoming-release-notes/tag-report-calculations.md
new file mode 100644
index 0000000000..64752370b2
--- /dev/null
+++ b/upcoming-release-notes/tag-report-calculations.md
@@ -0,0 +1,6 @@
+---
+category: Maintenance
+authors: [jfdoming]
+---
+
+Add calculation and storage support for splitting custom reports by tags.