Skip to content

A local-first personal finance app

[AI] Fix monthly spending category group budgets (#8043)

sys0442bec810210fd
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/budgetDataQuery.ts b/packages/desktop-client/src/components/reports/spreadsheets/budgetDataQuery.ts
index 9a6e05cfba..5ebccd8e02 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/budgetDataQuery.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/budgetDataQuery.ts
@@ -43,6 +43,35 @@ async function mapWithConcurrency<TItem, TResult>(
return results;
}
+export function isSupportedCategoryCondition(
+ condition: RuleConditionEntity,
+): boolean {
+ if (condition.field !== 'category' && condition.field !== 'category_group') {
+ return false;
+ }
+
+ if (condition.op === 'is' || condition.op === 'isNot') {
+ return typeof condition.value === 'string';
+ }
+
+ if (condition.op === 'oneOf' || condition.op === 'notOneOf') {
+ return (
+ Array.isArray(condition.value) &&
+ condition.value.every(id => typeof id === 'string')
+ );
+ }
+
+ if (
+ condition.op === 'contains' ||
+ condition.op === 'doesNotContain' ||
+ condition.op === 'matches'
+ ) {
+ return typeof condition.value === 'string';
+ }
+
+ return false;
+}
+
export function filterCategoriesByConditions(
categories: CategoryEntity[],
categoryGroups: CategoryGroupEntity[],
@@ -72,37 +101,9 @@ export function filterCategoriesByConditions(
categoryGroups.map(group => [group.id, group.name] as const),
);
- const isSupportedCondition = (
- condition: Extract<
- RuleConditionEntity,
- { field: 'category' | 'category_group' }
- >,
- ) => {
- if (condition.op === 'is' || condition.op === 'isNot') {
- return typeof condition.value === 'string';
- }
-
- if (condition.op === 'oneOf' || condition.op === 'notOneOf') {
- return (
- Array.isArray(condition.value) &&
- condition.value.every(id => typeof id === 'string')
- );
- }
-
- if (
- condition.op === 'contains' ||
- condition.op === 'doesNotContain' ||
- condition.op === 'matches'
- ) {
- return typeof condition.value === 'string';
- }
-
- return false;
- };
-
// If we can't safely interpret any category condition, do not attempt to
// filter categories (better to be broad than silently exclude data).
- if (!categoryConditions.every(isSupportedCondition)) {
+ if (!categoryConditions.every(isSupportedCategoryCondition)) {
return categories;
}
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.test.ts b/packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.test.ts
new file mode 100644
index 0000000000..bace5a5d68
--- /dev/null
+++ b/packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.test.ts
@@ -0,0 +1,73 @@
+import type {
+ CategoryEntity,
+ CategoryGroupEntity,
+ RuleConditionEntity,
+} from '@actual-app/core/types/models';
+import { describe, expect, it } from 'vitest';
+
+import { getSpendingBudgetFilters } from './spending-spreadsheet';
+
+const categoryGroups = [
+ { id: 'group-bills', name: 'Bills' },
+ { id: 'group-fun', name: 'Fun Money' },
+] satisfies CategoryGroupEntity[];
+
+const categories = [
+ { id: 'cat-rent', name: 'Rent', group: 'group-bills' },
+ { id: 'cat-electric', name: 'Electric', group: 'group-bills' },
+ { id: 'cat-dining', name: 'Dining Out', group: 'group-fun' },
+] satisfies CategoryEntity[];
+
+describe('getSpendingBudgetFilters', () => {
+ it('filters budget categories by category group', () => {
+ const result = getSpendingBudgetFilters({
+ categories,
+ categoryGroups,
+ conditions: [
+ {
+ field: 'category_group',
+ op: 'is',
+ value: 'group-bills',
+ },
+ ] satisfies RuleConditionEntity[],
+ });
+
+ expect(result).toEqual([
+ { category: { $oneof: ['cat-rent', 'cat-electric'] } },
+ ]);
+ });
+
+ it('does not filter budgets when no category condition is present', () => {
+ const result = getSpendingBudgetFilters({
+ categories,
+ categoryGroups,
+ conditions: [
+ {
+ field: 'account',
+ op: 'is',
+ value: 'account-checking',
+ },
+ ] satisfies RuleConditionEntity[],
+ });
+
+ expect(result).toEqual([]);
+ });
+
+ it('filters budget categories by direct category IDs', () => {
+ const result = getSpendingBudgetFilters({
+ categories,
+ categoryGroups,
+ conditions: [
+ {
+ field: 'category',
+ op: 'oneOf',
+ value: ['cat-rent', 'cat-dining'],
+ },
+ ] satisfies RuleConditionEntity[],
+ });
+
+ expect(result).toEqual([
+ { category: { $oneof: ['cat-rent', 'cat-dining'] } },
+ ]);
+ });
+});
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.ts
index 9afdf02e74..d40c2bd899 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.ts
@@ -2,6 +2,8 @@ import { send } from '@actual-app/core/platform/client/connection';
import * as monthUtils from '@actual-app/core/shared/months';
import { q } from '@actual-app/core/shared/query';
import type {
+ CategoryEntity,
+ CategoryGroupEntity,
RuleConditionEntity,
SpendingAverageRange,
SpendingEntity,
@@ -15,17 +17,56 @@ import { fromDateRepr } from '#components/reports/util';
import type { useSpreadsheet } from '#hooks/useSpreadsheet';
import { aqlQuery } from '#queries/aqlQuery';
+import {
+ filterCategoriesByConditions,
+ isSupportedCategoryCondition,
+} from './budgetDataQuery';
import { makeQuery } from './makeQuery';
type createSpendingSpreadsheetProps = {
conditions?: RuleConditionEntity[];
- conditionsOp?: string;
+ conditionsOp?: 'and' | 'or';
compare?: string;
compareTo?: string;
averageRange?: SpendingAverageRange;
budgetType?: 'envelope' | 'tracking';
};
+export function getSpendingBudgetFilters({
+ categories,
+ categoryGroups,
+ conditions,
+ conditionsOp,
+}: {
+ categories: CategoryEntity[];
+ categoryGroups: CategoryGroupEntity[];
+ conditions: RuleConditionEntity[];
+ conditionsOp?: 'and' | 'or';
+}) {
+ const budgetConditions = conditions.filter(
+ cond =>
+ !cond.customName &&
+ (cond.field === 'category' || cond.field === 'category_group'),
+ );
+
+ if (budgetConditions.length === 0) {
+ return [];
+ }
+
+ if (!budgetConditions.every(isSupportedCategoryCondition)) {
+ return [];
+ }
+
+ const matchingCategoryIds = filterCategoriesByConditions(
+ categories,
+ categoryGroups,
+ budgetConditions,
+ conditionsOp ?? 'and',
+ ).map(category => category.id);
+
+ return [{ category: { $oneof: matchingCategoryIds } }];
+}
+
export function createSpendingSpreadsheet({
conditions = [],
conditionsOp,
@@ -68,16 +109,6 @@ export function createSpendingSpreadsheet({
conditions: conditions.filter(cond => !cond.customName),
});
- const { filters: budgetFilters } = await send(
- 'make-filters-from-conditions',
- {
- conditions: conditions.filter(
- cond => !cond.customName && cond.field === 'category',
- ),
- applySpecialCases: false,
- },
- );
-
const conditionsOpKey = conditionsOp === 'or' ? '$or' : '$and';
const [assets, debts] = await Promise.all([
@@ -163,14 +194,26 @@ export function createSpendingSpreadsheet({
const budgetMonth = parseInt(compareMonth.replace('-', ''));
const budgetTable =
budgetType === 'tracking' ? 'reflect_budgets' : 'zero_budgets';
+ const hasBudgetConditions = conditions.some(
+ cond =>
+ !cond.customName &&
+ (cond.field === 'category' || cond.field === 'category_group'),
+ );
+ const budgetFilters = hasBudgetConditions
+ ? await send('get-categories').then(({ list, grouped }) =>
+ getSpendingBudgetFilters({
+ categories: list,
+ categoryGroups: grouped,
+ conditions,
+ conditionsOp,
+ }),
+ )
+ : [];
const [budgets] = await Promise.all([
aqlQuery(
q(budgetTable)
.filter({
- $and: [{ month: { $eq: budgetMonth } }],
- })
- .filter({
- [conditionsOpKey]: budgetFilters,
+ $and: [{ month: { $eq: budgetMonth } }, ...budgetFilters],
})
.groupBy([{ $id: '$category' }])
.select([
diff --git a/upcoming-release-notes/8043.md b/upcoming-release-notes/8043.md
new file mode 100644
index 0000000000..11289a7c69
--- /dev/null
+++ b/upcoming-release-notes/8043.md
@@ -0,0 +1,6 @@
+---
+category: Bugfixes
+authors: [sys044]
+---
+
+Fix monthly spending reports to correctly filter budgets by category groups.