Skip to content

A local-first personal finance app

[AI] Add "Average of previous weeks" budget automation (#9405)

Timb450a9f26929
diff --git a/packages/desktop-client/src/components/budget/goals/TemplateSentence.tsx b/packages/desktop-client/src/components/budget/goals/TemplateSentence.tsx
index 9c2b7bc20f..e96c911271 100644
--- a/packages/desktop-client/src/components/budget/goals/TemplateSentence.tsx
+++ b/packages/desktop-client/src/components/budget/goals/TemplateSentence.tsx
@@ -39,6 +39,7 @@ export function TemplateSentence({
/>
);
case 'average':
+ case 'weeklyAverage':
case 'copy':
return <HistoricalAutomationReadOnly template={template} />;
case 'by':
diff --git a/packages/desktop-client/src/components/budget/goals/constants.ts b/packages/desktop-client/src/components/budget/goals/constants.ts
index 39e7092c9a..cce1cf70c5 100644
--- a/packages/desktop-client/src/components/budget/goals/constants.ts
+++ b/packages/desktop-client/src/components/budget/goals/constants.ts
@@ -10,6 +10,7 @@ import type {
RemainderTemplate,
ScheduleTemplate,
SpendTemplate,
+ WeeklyAverageTemplate,
} from '@actual-app/core/types/models/templates';
export const displayTemplateTypes = [
@@ -48,7 +49,7 @@ export type ReducerState =
displayType: 'percentage';
}
| {
- template: CopyTemplate | AverageTemplate;
+ template: CopyTemplate | AverageTemplate | WeeklyAverageTemplate;
displayType: 'historical';
}
| {
diff --git a/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustment.tsx b/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustment.tsx
index 4f1c38e372..542712201d 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustment.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustment.tsx
@@ -6,6 +6,7 @@ import { amountToInteger, integerToAmount } from '@actual-app/core/shared/util';
import type {
AverageTemplate,
ScheduleTemplate,
+ WeeklyAverageTemplate,
} from '@actual-app/core/types/models/templates';
import { updateTemplate } from '#components/budget/goals/actions';
@@ -14,7 +15,10 @@ import { FormField, FormLabel } from '#components/forms';
import { AmountInput } from '#components/util/AmountInput';
import { PercentInput } from '#components/util/PercentInput';
-type AdjustableTemplate = ScheduleTemplate | AverageTemplate;
+type AdjustableTemplate =
+ | ScheduleTemplate
+ | AverageTemplate
+ | WeeklyAverageTemplate;
type AdjustmentType = 'percent' | 'fixed';
type UnitOption = 'none' | AdjustmentType;
type Direction = 'increase' | 'decrease';
@@ -30,7 +34,7 @@ type AmountAdjustmentProps = {
};
// Editor for the optional increase/decrease modifier on schedule and average
-// templates. `adjustment` is stored as a single signed number. The unit
+// (monthly or weekly) templates. `adjustment` is stored as a single signed number. The unit
// dropdown turns the adjustment on and off and picks percentage vs fixed
// amount. A percentage uses an increase/decrease selector for the direction;
// a fixed amount uses AmountInput, whose own sign is the direction.
@@ -50,23 +54,13 @@ export const AmountAdjustment = ({
next: number | undefined,
type: AdjustmentType | undefined,
) => {
- if (template.type === 'schedule') {
- dispatch(
- updateTemplate({
- type: 'schedule',
- adjustment: next,
- adjustmentType: type,
- }),
- );
- } else {
- dispatch(
- updateTemplate({
- type: 'average',
- adjustment: next,
- adjustmentType: type,
- }),
- );
- }
+ dispatch(
+ updateTemplate({
+ type: template.type,
+ adjustment: next,
+ adjustmentType: type,
+ }),
+ );
};
const changeUnit = (unit: UnitOption) => {
@@ -86,7 +80,16 @@ export const AmountAdjustment = ({
return (
<SpaceBetween gap={50} style={{ marginTop: 10 }}>
<FormField style={{ flex: 1 }}>
- <FormLabel title={t('Adjustment')} htmlFor="adjustment-unit-field" />
+ <FormLabel
+ title={
+ // Weekly averages add a fixed adjustment once per week, so the
+ // month moves by 4-5x the entered amount.
+ template.type === 'weeklyAverage'
+ ? t('Adjustment per week')
+ : t('Adjustment')
+ }
+ htmlFor="adjustment-unit-field"
+ />
<SpaceBetween align="center" gap={12}>
<Select
id="adjustment-unit-field"
diff --git a/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustmentSummary.tsx b/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustmentSummary.tsx
index bb5b36d971..6f340612b2 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustmentSummary.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/AmountAdjustmentSummary.tsx
@@ -4,12 +4,13 @@ import { amountToInteger } from '@actual-app/core/shared/util';
import type {
AverageTemplate,
ScheduleTemplate,
+ WeeklyAverageTemplate,
} from '@actual-app/core/types/models/templates';
import { useFormat } from '#hooks/useFormat';
type AmountAdjustmentSummaryProps = {
- template: ScheduleTemplate | AverageTemplate;
+ template: ScheduleTemplate | AverageTemplate | WeeklyAverageTemplate;
};
// Trailing clause for a template's increase or decrease adjustment, e.g.
@@ -28,6 +29,13 @@ export function AmountAdjustmentSummary({
if (template.adjustmentType === 'fixed') {
const amount = format(amountToInteger(magnitude), 'financial');
+ if (template.type === 'weeklyAverage') {
+ return increase ? (
+ <Trans>(increased by {{ amount }} per week)</Trans>
+ ) : (
+ <Trans>(decreased by {{ amount }} per week)</Trans>
+ );
+ }
return increase ? (
<Trans>(increased by {{ amount }})</Trans>
) : (
diff --git a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx
index 6587331266..66945369d9 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx
@@ -5,9 +5,11 @@ import { useResponsive } from '@actual-app/components/hooks/useResponsive';
import { Input } from '@actual-app/components/input';
import { Select } from '@actual-app/components/select';
import { SpaceBetween } from '@actual-app/components/space-between';
+import { WEEKDAYS } from '@actual-app/core/shared/months';
import type {
AverageTemplate,
CopyTemplate,
+ WeeklyAverageTemplate,
} from '@actual-app/core/types/models/templates';
import { updateTemplate } from '#components/budget/goals/actions';
@@ -19,9 +21,14 @@ import {
STACKED_FIELD_FLEX,
} from '#components/budget/goals/editor/fieldLayout';
import { FormField, FormLabel } from '#components/forms';
+import { useDaysOfWeek } from '#hooks/useDaysOfWeek';
+
+// The dropdown lists Monday first; `WEEKDAYS` itself is Sunday first to match
+// `Date.getDay()`.
+const WEEKDAY_OPTION_ORDER = [1, 2, 3, 4, 5, 6, 0];
type HistoricalAutomationProps = {
- template: CopyTemplate | AverageTemplate;
+ template: CopyTemplate | AverageTemplate | WeeklyAverageTemplate;
dispatch: (action: Action) => void;
};
@@ -30,29 +37,37 @@ export const HistoricalAutomation = ({
dispatch,
}: HistoricalAutomationProps) => {
const { t } = useTranslation();
+ const daysOfWeek = useDaysOfWeek();
const { isNarrowWidth } = useResponsive();
const fieldFlex = isNarrowWidth ? STACKED_FIELD_FLEX : 1;
- const months =
- template.type === 'average' ? template.numMonths : template.lookBack;
- const [rawMonths, setRawMonths] = useState(String(months));
- const [prevMonths, setPrevMonths] = useState(months);
- if (months !== prevMonths) {
- setPrevMonths(months);
- setRawMonths(String(months));
+ const periods = getPeriodCount(template);
+ const [rawPeriods, setRawPeriods] = useState(String(periods));
+ const [prevPeriods, setPrevPeriods] = useState(periods);
+ if (periods !== prevPeriods) {
+ setPrevPeriods(periods);
+ setRawPeriods(String(periods));
}
- const commitMonths = () => {
- const parsed = Math.max(1, Math.trunc(Number(rawMonths)) || 1);
- setRawMonths(String(parsed));
- if (parsed === months) return;
- dispatch(
- updateTemplate(
- template.type === 'average'
- ? { type: 'average', numMonths: parsed }
- : { type: 'copy', lookBack: parsed },
- ),
- );
+ const commitPeriods = () => {
+ const parsed = Math.max(1, Math.trunc(Number(rawPeriods)) || 1);
+ setRawPeriods(String(parsed));
+ if (parsed === periods) return;
+ switch (template.type) {
+ case 'average':
+ dispatch(updateTemplate({ type: 'average', numMonths: parsed }));
+ break;
+ case 'weeklyAverage':
+ dispatch(updateTemplate({ type: 'weeklyAverage', numWeeks: parsed }));
+ break;
+ case 'copy':
+ dispatch(updateTemplate({ type: 'copy', lookBack: parsed }));
+ break;
+ default:
+ throw new Error(
+ `Unknown historical template: ${String(template satisfies never)}`,
+ );
+ }
};
return (
@@ -69,6 +84,7 @@ export const HistoricalAutomation = ({
options={[
['copy', t('Copy a previous month')],
['average', t('Average of previous months')],
+ ['weeklyAverage', t('Average of previous weeks')],
]}
value={template.type}
onChange={type => dispatch(updateTemplate({ type }))}
@@ -76,7 +92,11 @@ export const HistoricalAutomation = ({
</FormField>
<FormField style={{ flex: fieldFlex }}>
<FormLabel
- title={t('Number of months back')}
+ title={
+ template.type === 'weeklyAverage'
+ ? t('Number of weeks back')
+ : t('Number of months back')
+ }
htmlFor="look-back-field"
/>
<Input
@@ -84,15 +104,48 @@ export const HistoricalAutomation = ({
type="number"
min={1}
step={1}
- value={rawMonths}
- onChangeValue={setRawMonths}
- onBlur={commitMonths}
+ value={rawPeriods}
+ onChangeValue={setRawPeriods}
+ onBlur={commitPeriods}
/>
</FormField>
+ {template.type === 'weeklyAverage' && (
+ <FormField style={{ flex: fieldFlex }}>
+ <FormLabel title={t('Once every')} htmlFor="weekday-field" />
+ <Select
+ id="weekday-field"
+ options={WEEKDAY_OPTION_ORDER.map(
+ dayOfWeek =>
+ [WEEKDAYS[dayOfWeek], daysOfWeek[dayOfWeek]] as const,
+ )}
+ value={template.weekday}
+ onChange={weekday =>
+ dispatch(updateTemplate({ type: 'weeklyAverage', weekday }))
+ }
+ />
+ </FormField>
+ )}
</SpaceBetween>
- {template.type === 'average' && (
+ {(template.type === 'average' || template.type === 'weeklyAverage') && (
<AmountAdjustment template={template} dispatch={dispatch} />
)}
</>
);
};
+
+function getPeriodCount(
+ template: CopyTemplate | AverageTemplate | WeeklyAverageTemplate,
+): number {
+ switch (template.type) {
+ case 'average':
+ return template.numMonths;
+ case 'weeklyAverage':
+ return template.numWeeks;
+ case 'copy':
+ return template.lookBack;
+ default:
+ throw new Error(
+ `Unknown historical template: ${String(template satisfies never)}`,
+ );
+ }
+}
diff --git a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomationReadOnly.tsx b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomationReadOnly.tsx
index 5d97c5604b..4aa2627275 100644
--- a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomationReadOnly.tsx
+++ b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomationReadOnly.tsx
@@ -1,14 +1,18 @@
import { Trans } from 'react-i18next';
+import { WEEKDAYS } from '@actual-app/core/shared/months';
import type {
AverageTemplate,
CopyTemplate,
+ WeeklyAverageTemplate,
} from '@actual-app/core/types/models/templates';
+import { useDaysOfWeek } from '#hooks/useDaysOfWeek';
+
import { AmountAdjustmentSummary } from './AmountAdjustmentSummary';
type HistoricalAutomationReadOnlyProps = {
- template: CopyTemplate | AverageTemplate;
+ template: CopyTemplate | AverageTemplate | WeeklyAverageTemplate;
};
export const HistoricalAutomationReadOnly = ({
@@ -22,12 +26,15 @@ export const HistoricalAutomationReadOnly = ({
);
}
- const base = (
- <Trans count={template.numMonths}>
- Budget the average of the last {{ count: template.numMonths }} complete
- months
- </Trans>
- );
+ const base =
+ template.type === 'weeklyAverage' ? (
+ <WeeklyAverageSentence template={template} />
+ ) : (
+ <Trans count={template.numMonths}>
+ Budget the average of the last {{ count: template.numMonths }} complete
+ months
+ </Trans>
+ );
if (template.adjustment === undefined) {
return base;
@@ -39,3 +46,19 @@ export const HistoricalAutomationReadOnly = ({
</>
);
};
+
+function WeeklyAverageSentence({
+ template,
+}: {
+ template: WeeklyAverageTemplate;
+}) {
+ const daysOfWeek = useDaysOfWeek();
+ const weekday = daysOfWeek[WEEKDAYS.indexOf(template.weekday)];
+
+ return (
+ <Trans count={template.numWeeks}>
+ Budget the weekly average of the last {{ count: template.numWeeks }}{' '}
+ complete weeks for every {{ weekday }} in the month
+ </Trans>
+ );
+}
diff --git a/packages/desktop-client/src/components/budget/goals/reducer.ts b/packages/desktop-client/src/components/budget/goals/reducer.ts
index 19700613b1..5b8552bb93 100644
--- a/packages/desktop-client/src/components/budget/goals/reducer.ts
+++ b/packages/desktop-client/src/components/budget/goals/reducer.ts
@@ -4,12 +4,20 @@ import {
firstDayOfMonth,
monthFromDate,
} from '@actual-app/core/shared/months';
-import type { Template } from '@actual-app/core/types/models/templates';
+import type {
+ AverageTemplate,
+ CopyTemplate,
+ Template,
+ Weekday,
+ WeeklyAverageTemplate,
+} from '@actual-app/core/types/models/templates';
import type { Action } from './actions';
import type { DisplayTemplateType, ReducerState } from './constants';
export const DEFAULT_PRIORITY = 1;
+const DEFAULT_WEEKLY_AVERAGE_WEEKS = 12;
+const DEFAULT_WEEKLY_AVERAGE_WEEKDAY: Weekday = 'monday';
export const getInitialState = (template: Template | null): ReducerState => {
if (!template) {
@@ -72,6 +80,7 @@ export const getInitialState = (template: Template | null): ReducerState => {
displayType: 'refill',
};
case 'average':
+ case 'weeklyAverage':
case 'copy':
return {
template,
@@ -172,7 +181,8 @@ const changeType = (
case 'historical':
if (
prevState.template.type === 'copy' ||
- prevState.template.type === 'average'
+ prevState.template.type === 'average' ||
+ prevState.template.type === 'weeklyAverage'
) {
return prevState;
}
@@ -238,45 +248,95 @@ const changeType = (
}
};
+type HistoricalTemplate =
+ | CopyTemplate
+ | AverageTemplate
+ | WeeklyAverageTemplate;
+type TemplateUpdate = Partial<Template> & Pick<Template, 'type'>;
+type HistoricalUpdate = Partial<Template> & Pick<HistoricalTemplate, 'type'>;
+
+function isHistoricalUpdate(
+ template: TemplateUpdate,
+): template is HistoricalUpdate {
+ return (
+ template.type === 'copy' ||
+ template.type === 'average' ||
+ template.type === 'weeklyAverage'
+ );
+}
+
+// Switches between the historical modes, keeping whatever carries over: the
+// month count between copy and average, a percentage adjustment between the
+// two averages, and the priority always. Fixed adjustments are dropped: the
+// monthly average adds them once per month but the weekly average once per
+// week, so carrying one over would silently change the budgeted amount.
+function convertHistoricalTemplate(
+ prev: HistoricalTemplate,
+ template: HistoricalUpdate,
+): HistoricalTemplate {
+ const months =
+ prev.type === 'average'
+ ? prev.numMonths
+ : prev.type === 'copy'
+ ? prev.lookBack
+ : undefined;
+ const adjustment =
+ prev.type !== 'copy' && prev.adjustmentType === 'percent'
+ ? { adjustment: prev.adjustment, adjustmentType: prev.adjustmentType }
+ : {};
+
+ switch (template.type) {
+ case 'copy':
+ return {
+ ...template,
+ directive: 'template',
+ type: 'copy',
+ lookBack: months ?? 1,
+ priority: prev.priority,
+ };
+ case 'average':
+ return {
+ ...template,
+ directive: 'template',
+ type: 'average',
+ numMonths: months ?? 3,
+ ...adjustment,
+ priority: prev.priority,
+ };
+ case 'weeklyAverage':
+ return {
+ ...template,
+ directive: 'template',
+ type: 'weeklyAverage',
+ numWeeks: DEFAULT_WEEKLY_AVERAGE_WEEKS,
+ weekday: DEFAULT_WEEKLY_AVERAGE_WEEKDAY,
+ ...adjustment,
+ priority: prev.priority,
+ };
+ default:
+ throw new Error(
+ `Unknown historical template: ${String(template satisfies never)}`,
+ );
+ }
+}
+
function mapTemplateTypesForUpdate(
state: ReducerState,
- template: Partial<Template> & Pick<Template, 'type'>,
+ template: TemplateUpdate,
): ReducerState {
switch (state.template.type) {
case 'average':
- switch (template.type) {
- case 'copy':
- return {
- ...state,
- displayType: 'historical',
- template: {
- ...template,
- directive: 'template',
- type: 'copy',
- lookBack: state.template.numMonths,
- priority: state.template.priority,
- },
- };
- default:
- break;
- }
- break;
case 'copy':
- switch (template.type) {
- case 'average':
- return {
- ...state,
- displayType: 'historical',
- template: {
- ...template,
- directive: 'template',
- type: 'average',
- numMonths: state.template.lookBack,
- priority: state.template.priority,
- },
- };
- default:
- break;
+ case 'weeklyAverage':
+ if (
+ isHistoricalUpdate(template) &&
+ template.type !== state.template.type
+ ) {
+ return {
+ ...state,
+ displayType: 'historical',
+ template: convertHistoricalTemplate(state.template, template),
+ };
}
break;
case 'by':
diff --git a/packages/desktop-client/src/components/budget/goals/validateAutomation.ts b/packages/desktop-client/src/components/budget/goals/validateAutomation.ts
index 276c512359..a912fd6cfe 100644
--- a/packages/desktop-client/src/components/budget/goals/validateAutomation.ts
+++ b/packages/desktop-client/src/components/budget/goals/validateAutomation.ts
@@ -19,7 +19,9 @@ export type AutomationErrorKind =
function isAdjustmentOutOfRange(template: Template): boolean {
if (
- (template.type === 'schedule' || template.type === 'average') &&
+ (template.type === 'schedule' ||
+ template.type === 'average' ||
+ template.type === 'weeklyAverage') &&
template.adjustment !== undefined &&
template.adjustmentType === 'percent'
) {
diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationEditorPane.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationEditorPane.tsx
index 2dee4b53c7..9b8627c6b8 100644
--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationEditorPane.tsx
+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationEditorPane.tsx
@@ -168,6 +168,7 @@ export function AutomationEditorPane({
case 'simple':
case 'schedule':
case 'average':
+ case 'weeklyAverage':
case 'copy':
case 'refill':
return { ...entry, template: { ...t, priority } };
diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations.ts b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations.ts
index 13dc890f67..64605785ba 100644
--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations.ts
+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/migrateTemplatesToAutomations.ts
@@ -27,6 +27,7 @@ function getDisplayTypeFromTemplate(template: Template): DisplayTemplateType {
case 'refill':
return 'refill';
case 'average':
+ case 'weeklyAverage':
case 'copy':
return 'historical';
case 'by':
diff --git a/packages/desktop-client/src/hooks/useDaysOfWeek.ts b/packages/desktop-client/src/hooks/useDaysOfWeek.ts
index 86ebab39ef..600d351512 100644
--- a/packages/desktop-client/src/hooks/useDaysOfWeek.ts
+++ b/packages/desktop-client/src/hooks/useDaysOfWeek.ts
@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
export function useDaysOfWeek() {
const { t } = useTranslation();
- const daysOfWeek = {
+ const daysOfWeek: Record<number, string> = {
0: t('Sunday'),
1: t('Monday'),
2: t('Tuesday'),
@@ -12,7 +12,7 @@ export function useDaysOfWeek() {
4: t('Thursday'),
5: t('Friday'),
6: t('Saturday'),
- } satisfies Record<number, string>;
+ };
return daysOfWeek;
}
diff --git a/packages/docs/docs/experimental/budget-automation.md b/packages/docs/docs/experimental/budget-automation.md
index 115892c1b1..1b30d9a2e2 100644
--- a/packages/docs/docs/experimental/budget-automation.md
+++ b/packages/docs/docs/experimental/budget-automation.md
@@ -172,6 +172,7 @@ Choose a mode (A) and the number of months back (B). This is another automation
- **Copy a previous month.** This will copy the **budget** from a previous month.
- **Average of previous months.** This will average the **spending** from the previous number of months you choose. The average is calculated from completed months only, to ensure the amount accurately reflects actual spending behavior.
+- **Average of previous weeks.** This will average the weekly **spending** over the number of weeks you choose, then budget that amount once for every occurrence of the chosen weekday in the month. A month with five Fridays gets five weeks' worth. The weeks are the complete 7-day weeks ending the day before the month starts (or yesterday, for future months). Adjustments apply to the weekly amount.
### % of Income {#percentage}
diff --git a/packages/docs/docs/experimental/goal-templates.md b/packages/docs/docs/experimental/goal-templates.md
index c15dc15a6e..9b01a8becf 100644
--- a/packages/docs/docs/experimental/goal-templates.md
+++ b/packages/docs/docs/experimental/goal-templates.md
@@ -447,6 +447,28 @@ As an example, assume the spend for the category was [\$40, \$50, \$60] for the
| `#template average 3 months [increase 11]` | \$ 61 |
| `#template average 3 months [decrease 1]` | \$ 49 |
+#### Weekly averages
+
+Often spending follows the week rather than the month, like a weekly grocery shop or a commute. This means the amount needed per month varies, depending on how the weeks fall. The weekly average template averages your spending per week, then budgets that amount once for every occurrence of a chosen weekday in the month.
+
+| Syntax | Description |
+| --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
+| `#template average {number} weeks on {weekday}` | Budget the average weekly spend over the last `{number}` complete weeks, once for every `{weekday}` in the month |
+| `#template average {number} weeks on {weekday} [{increase/decrease} {number\|number%}]` | Same as above, with an adjustment applied to the weekly amount before it is multiplied by the number of weekdays |
+
+The averaging window is the `{number}` full 7-day weeks that end the day before the budget month starts. For example, `#template average 4 weeks on friday` for a November 2026 budget, averages spending from 2026-10-04 through 2026-10-31. Weeks before the category's first transaction are left out of the average.
+
+For averages calculated in future months, the window uses yesterday as the cut-off point for full 7-day weeks. This ensures averages take into account recent spending.
+
+As an example, assume you spent an average of \$ 50 per week over the last 4 weeks. October 2026 has five Fridays and four Mondays.
+
+| Template line | Budgeted Amount (October 2026) |
+| ---------------------------------------------------- | :----------------------------: |
+| `#template average 4 weeks on friday` | \$ 250 |
+| `#template average 4 weeks on monday` | \$ 200 |
+| `#template average 4 weeks on friday [increase 10%]` | \$ 275 |
+| `#template average 4 weeks on monday [increase 5]` | \$ 220 |
+
### Copy Type
The Copy template will copy the budget amount from some number of months prior.
diff --git a/packages/loot-core/src/server/budget/actions.test.ts b/packages/loot-core/src/server/budget/actions.test.ts
index 639fe8f193..4a22fb548b 100644
--- a/packages/loot-core/src/server/budget/actions.test.ts
+++ b/packages/loot-core/src/server/budget/actions.test.ts
@@ -7,6 +7,7 @@ import * as sheet from '#server/sheet';
import {
copyUntilYearEnd,
coverOverbudgeted,
+ getCategoryWeeklyAverage,
getSheetValue,
set3MonthAvg,
setBudget,
@@ -195,6 +196,39 @@ describe('set budget average', () => {
});
});
+describe('getCategoryWeeklyAverage', () => {
+ beforeEach(global.emptyDatabase());
+
+ it('averages the complete weeks just before the budget month', async () => {
+ await db.insertAccount({ id: 'account1', name: 'Account 1' });
+ await db.insertCategoryGroup({ id: 'group1', name: 'group1' });
+ await db.insertCategory({ id: 'cat1', name: 'cat1', cat_group: 'group1' });
+ // 2 weeks before 2016-11 is 2016-10-18 through 2016-10-31; the days on
+ // either side are outside the window.
+ for (const [date, amount] of [
+ ['2016-10-17', -1000],
+ ['2016-10-18', -300],
+ ['2016-10-31', -101],
+ ['2016-11-01', -1000],
+ ] as const) {
+ await db.insertTransaction({
+ date,
+ amount,
+ account: 'account1',
+ category: 'cat1',
+ });
+ }
+
+ expect(
+ await getCategoryWeeklyAverage({
+ month: '2016-11',
+ numWeeks: 2,
+ categoryId: 'cat1',
+ }),
+ ).toBe(-200.5);
+ });
+});
+
describe('coverOverbudgeted', () => {
beforeEach(global.emptyDatabase());
afterEach(global.emptyDatabase());
diff --git a/packages/loot-core/src/server/budget/actions.ts b/packages/loot-core/src/server/budget/actions.ts
index 33cc3ed485..f52976d976 100644
--- a/packages/loot-core/src/server/budget/actions.ts
+++ b/packages/loot-core/src/server/budget/actions.ts
@@ -10,6 +10,11 @@ import { integerToCurrencyWithDecimal, safeNumber } from '#shared/util';
import type { IntegerAmount } from '#shared/util';
import type { CategoryEntity } from '#types/models';
+import {
+ getWeeklyAverageWindow,
+ trimWeeklyAverageWindow,
+} from './weekly-average';
+
export async function getSheetValue(
sheetName: string,
cell: string,
@@ -412,6 +417,59 @@ export async function getCategoryAverage({
return Math.round(sumAmount / months.length);
}
+// Average weekly spending (signed, like `sum-amount`) over the `numWeeks`
+// complete weeks before `month`. See `getWeeklyAverageWindow` for the exact
+// window. Weeks before the category's first transaction are left out.
+// Not rounded: callers multiply it by the weekday count first, so rounding
+// here would drift the monthly amount by up to a few minor units.
+export async function getCategoryWeeklyAverage({
+ month,
+ numWeeks,
+ categoryId,
+}: {
+ month: string;
+ numWeeks: number;
+ categoryId: string;
+}): Promise<number> {
+ const fullWindow = getWeeklyAverageWindow({
+ month,
+ numWeeks,
+ today: monthUtils.currentDay(),
+ });
+
+ const firstActivity = await db.first<{ date: number | null }>(
+ `SELECT MIN(t.date) AS date
+ FROM v_transactions_internal_alive t
+ LEFT JOIN accounts a ON a.id = t.account
+ WHERE t.category = ?
+ AND t.date <= ?
+ AND a.offbudget = 0`,
+ [categoryId, db.toDateRepr(fullWindow.end)],
+ );
+ const window = trimWeeklyAverageWindow(
+ fullWindow,
+ firstActivity?.date == null ? null : db.fromDateRepr(firstActivity.date),
+ );
+ if (window == null) {
+ return 0;
+ }
+
+ // Same filters as the `sum-amount` cells so weekly and monthly averages
+ // agree on which transactions count.
+ const total = await db.first<{ amount: number | null }>(
+ `SELECT SUM(t.amount) AS amount
+ FROM v_transactions_internal_alive t
+ LEFT JOIN accounts a ON a.id = t.account
+ WHERE t.category = ?
+ AND t.date >= ?
+ AND t.date <= ?
+ AND a.offbudget = 0`,
+ [categoryId, db.toDateRepr(window.start), db.toDateRepr(window.end)],
+ );
+
+ return safeNumber(total?.amount ?? 0) / window.numWeeks;
+}
+
async function getAverageMonths({
month,
maxMonths,
diff --git a/packages/loot-core/src/server/budget/category-template-context.test.ts b/packages/loot-core/src/server/budget/category-template-context.test.ts
index 22c7d68eb3..21bebbee01 100644
--- a/packages/loot-core/src/server/budget/category-template-context.test.ts
+++ b/packages/loot-core/src/server/budget/category-template-context.test.ts
@@ -19,6 +19,7 @@ import * as statements from './statements';
// Mock getSheetValue and getCategories
vi.mock('./actions', () => ({
getCategoryAverage: vi.fn(),
+ getCategoryWeeklyAverage: vi.fn(),
getSheetValue: vi.fn(),
getSheetBoolean: vi.fn(),
isTrackingBudget: vi.fn(),
@@ -676,6 +677,29 @@ describe('CategoryTemplateContext', () => {
global.currentMonth = originalCurrentMonth;
});
+ // January 2024 has five Mondays but only four Fridays.
+ it.each([
+ ['monday', 1250],
+ ['friday', 1000],
+ ] as const)(
+ 'budgets a weekly average for every %s in the month',
+ async (weekday, expected) => {
+ vi.mocked(actions.getCategoryWeeklyAverage).mockResolvedValue(-250);
+
+ const result = await CategoryTemplateContext.runAverage(
+ {
+ type: 'weeklyAverage',
+ numWeeks: 4,
+ weekday,
+ directive: 'template',
+ priority: 1,
+ },
+ instance,
+ );
+ expect(result).toBe(expected);
+ },
+ );
+
it('should calculate average of 3 months', async () => {
const template: Template = {
type: 'average',
diff --git a/packages/loot-core/src/server/budget/category-template-context.ts b/packages/loot-core/src/server/budget/category-template-context.ts
index cfc5b6b803..636a64da04 100644
--- a/packages/loot-core/src/server/budget/category-template-context.ts
+++ b/packages/loot-core/src/server/budget/category-template-context.ts
@@ -17,10 +17,12 @@ import type {
SimpleTemplate,
SpendTemplate,
Template,
+ WeeklyAverageTemplate,
} from '#types/models/templates';
import {
getCategoryAverage,
+ getCategoryWeeklyAverage,
getSheetBoolean,
getSheetValue,
isTrackingBudget,
@@ -215,7 +217,8 @@ export class CategoryTemplateContext {
}
break;
}
- case 'average': {
+ case 'average':
+ case 'weeklyAverage': {
newBudget = await CategoryTemplateContext.runAverage(template, this);
break;
}
@@ -853,15 +856,25 @@ export class CategoryTemplateContext {
return Math.max(0, Math.round(monthlyIncome * (percent / 100)));
}
+ // Monthly averages budget the average once. Weekly averages budget it once
+ // per occurrence of the template's weekday in the month, so a month with
+ // five Fridays gets five weeks' worth; adjustments apply per week.
static async runAverage(
- template: AverageTemplate,
+ template: AverageTemplate | WeeklyAverageTemplate,
templateContext: CategoryTemplateContext,
): Promise<number> {
- let average = await getCategoryAverage({
- month: templateContext.month,
- maxMonths: template.numMonths,
- categoryId: templateContext.category.id,
- });
+ const isWeekly = template.type === 'weeklyAverage';
+ let average = isWeekly
+ ? await getCategoryWeeklyAverage({
+ month: templateContext.month,
+ numWeeks: template.numWeeks,
+ categoryId: templateContext.category.id,
+ })
+ : await getCategoryAverage({
+ month: templateContext.month,
+ maxMonths: template.numMonths,
+ categoryId: templateContext.category.id,
+ });
// negate as sheet value is cost ie negative
if (average < 0) {
average *= -1;
@@ -884,7 +897,13 @@ export class CategoryTemplateContext {
}
}
- return Math.round(average);
+ const occurrences = isWeekly
+ ? monthUtils.countDayOfWeekInMonth(
+ templateContext.month,
+ monthUtils.WEEKDAYS.indexOf(template.weekday),
+ )
+ : 1;
+ return Math.round(average * occurrences);
}
static runBy(templateContext: CategoryTemplateContext): {
diff --git a/packages/loot-core/src/server/budget/goal-template.pegjs b/packages/loot-core/src/server/budget/goal-template.pegjs
index 9469a43c83..c3e8cce78f 100644
--- a/packages/loot-core/src/server/budget/goal-template.pegjs
+++ b/packages/loot-core/src/server/budget/goal-template.pegjs
@@ -22,6 +22,8 @@ expr
{ return { type: 'schedule', name: name.trim(), priority: template.priority, directive: template.directive, full, adjustment: modifiers?.adjustment, adjustmentType: modifiers?.adjustmentType }}
/ template: template _ remainder: remainder limit: limit?
{ return { type: 'remainder', priority: null, directive: template.directive, weight: remainder, limit }}
+ / template: template _ 'average'i _ amount: positive _ ('weeks'i / 'week'i) _ 'on'i _ weekday: weekday modifiers:modifiers?
+ { return { type: 'weeklyAverage', numWeeks: +amount, weekday, priority: template.priority, directive: template.directive, adjustment: modifiers?.adjustment, adjustmentType: modifiers?.adjustmentType }}
/ template: template _ 'average'i _ amount: positive _ 'months'i? modifiers:modifiers?
{ return { type: 'average', numMonths: +amount, priority: template.priority, directive: template.directive, adjustment: modifiers?.adjustment, adjustmentType: modifiers?.adjustmentType }}
/ template: template _ 'copy from'i _ lookBack: positive _ 'months ago'i limit:limit?
@@ -64,6 +66,10 @@ periodCount = 'day'i { return {period: 'day', amount: 1 }}
/ 'year'i _ { return {period: 'year', amount: 1 }}
/ n: positive _ 'years'i _ { return { period: 'year', amount: +n }}
+weekday 'weekday'
+ = day: ('sunday'i / 'monday'i / 'tuesday'i / 'wednesday'i / 'thursday'i / 'friday'i / 'saturday'i)
+ { return day.toLowerCase() }
+
spendFrom = _ 'spend'i _ 'from'i _ month: month { return month }
week = 'week'i
diff --git a/packages/loot-core/src/server/budget/template-notes.test.ts b/packages/loot-core/src/server/budget/template-notes.test.ts
index 9f4470495d..b5692627a2 100644
--- a/packages/loot-core/src/server/budget/template-notes.test.ts
+++ b/packages/loot-core/src/server/budget/template-notes.test.ts
@@ -431,6 +431,7 @@ describe('unparse/parse round-trip', () => {
// average
'#template average 6 months',
'#template-5 average 12 months',
+ '#template-2 average 4 weeks on friday [increase 10%]',
// copy
'#template copy from 3 months ago',
'#template copy from 6 months ago',
diff --git a/packages/loot-core/src/server/budget/template-notes.ts b/packages/loot-core/src/server/budget/template-notes.ts
index 9941adbfb2..dcd216926e 100644
--- a/packages/loot-core/src/server/budget/template-notes.ts
+++ b/packages/loot-core/src/server/budget/template-notes.ts
@@ -111,6 +111,7 @@ async function getCategoriesWithTemplates(
// Validate schedule adjustments
if (
(parsedTemplate.type === 'average' ||
+ parsedTemplate.type === 'weeklyAverage' ||
parsedTemplate.type === 'schedule') &&
parsedTemplate.adjustment !== undefined
) {
@@ -199,11 +200,7 @@ function templateToLine(
}
result += ` ${template.name}`;
if (template.adjustment !== undefined) {
- const adj = template.adjustment;
- const op = adj >= 0 ? 'increase' : 'decrease';
- const val = Math.abs(adj);
- const type = template.adjustmentType === 'percent' ? '%' : '';
- result += ` [${op} ${val}${type}]`;
+ result += ` ${adjustmentToString(template)}`;
}
return result;
}
@@ -252,11 +249,15 @@ function templateToLine(
// #template average <numMonths> months [increase/decrease {number|number%}]
let result = `${prefix} average ${template.numMonths} months`;
if (template.adjustment !== undefined) {
- const adj = template.adjustment;
- const op = adj >= 0 ? 'increase' : 'decrease';
- const val = Math.abs(adj);
- const type = template.adjustmentType === 'percent' ? '%' : '';
- result += ` [${op} ${val}${type}]`;
+ result += ` ${adjustmentToString(template)}`;
+ }
+ return result;
+ }
+ case 'weeklyAverage': {
+ // #template average <numWeeks> weeks on <weekday> [increase/decrease {number|number%}]
+ let result = `${prefix} average ${template.numWeeks} weeks on ${template.weekday}`;
+ if (template.adjustment !== undefined) {
+ result += ` ${adjustmentToString(template)}`;
}
return result;
}
@@ -324,6 +325,18 @@ function limitToString(limit: {
}
}
+function adjustmentToString({
+ adjustment = 0,
+ adjustmentType,
+}: {
+ adjustment?: number;
+ adjustmentType?: 'percent' | 'fixed';
+}): string {
+ const op = adjustment >= 0 ? 'increase' : 'decrease';
+ const type = adjustmentType === 'percent' ? '%' : '';
+ return `[${op} ${Math.abs(adjustment)}${type}]`;
+}
+
function periodToString(p: {
period: 'day' | 'week' | 'month' | 'year';
amount: number;
diff --git a/packages/loot-core/src/server/budget/weekly-average.ts b/packages/loot-core/src/server/budget/weekly-average.ts
new file mode 100644
index 0000000000..8be1cce3ec
--- /dev/null
+++ b/packages/loot-core/src/server/budget/weekly-average.ts
@@ -0,0 +1,53 @@
+import * as monthUtils from '#shared/months';
+
+export type WeeklyAverageWindow = {
+ // First and last day of the window, both inclusive (YYYY-MM-DD).
+ start: string;
+ end: string;
+ numWeeks: number;
+};
+
+// The averaging window is the `numWeeks` complete 7-day weeks immediately
+// before the budget month starts. When the budget month hasn't started yet the
+// window ends yesterday instead, so it never includes today (incomplete) or
+// days in the future. This mirrors how the monthly average skips the current,
+// incomplete month.
+export function getWeeklyAverageWindow({
+ month,
+ numWeeks,
+ today,
+}: {
+ month: string;
+ numWeeks: number;
+ today: string;
+}): WeeklyAverageWindow {
+ const monthStart = monthUtils.firstDayOfMonth(month);
+ const endExclusive = monthStart < today ? monthStart : today;
+ return {
+ start: monthUtils.subDays(endExclusive, numWeeks * 7),
+ end: monthUtils.subDays(endExclusive, 1),
+ numWeeks,
+ };
+}
+
+// Drops whole weeks from the start of the window that end before the
+// category's first transaction, so a new category isn't averaged over weeks
+// it didn't exist for. The week containing the first transaction is kept.
+// Returns null when the category has no activity in the window.
+export function trimWeeklyAverageWindow(
+ window: WeeklyAverageWindow,
+ firstActivityDate: string | null,
+): WeeklyAverageWindow | null {
+ if (firstActivityDate == null || firstActivityDate > window.end) {
+ return null;
+ }
+
+ const daysWithActivity =
+ monthUtils.differenceInCalendarDays(window.end, firstActivityDate) + 1;
+ const numWeeks = Math.min(window.numWeeks, Math.ceil(daysWithActivity / 7));
+ return {
+ start: monthUtils.subDays(window.end, numWeeks * 7 - 1),
+ end: window.end,
+ numWeeks,
+ };
+}
diff --git a/packages/loot-core/src/shared/months.ts b/packages/loot-core/src/shared/months.ts
index 970465c445..a9e02b2293 100644
--- a/packages/loot-core/src/shared/months.ts
+++ b/packages/loot-core/src/shared/months.ts
@@ -4,6 +4,7 @@ import type { Locale } from 'date-fns';
import { memoizeOne } from '#shared/memoize';
import * as Platform from '#shared/platform';
+import type { Weekday } from '#types/models/templates';
import type { SyncedPrefs } from '#types/prefs';
type DateLike = string | Date;
@@ -400,6 +401,31 @@ export function getDay(day: string): number {
return Number(d.format(_parse(day), 'dd'));
}
+// Weekday names ordered to match `Date.prototype.getDay()` (0 = Sunday).
+export const WEEKDAYS = [
+ 'sunday',
+ 'monday',
+ 'tuesday',
+ 'wednesday',
+ 'thursday',
+ 'friday',
+ 'saturday',
+] as const satisfies readonly Weekday[];
+
+// How many times a day of the week (0 = Sunday, as `Date.getDay()`) falls in
+// `month`. Always 4 or 5.
+export function countDayOfWeekInMonth(
+ month: DateLike,
+ dayOfWeek: number,
+): number {
+ const start = _parse(firstDayOfMonth(month));
+ // Days from the 1st to the first occurrence of `dayOfWeek`.
+ const offset = (dayOfWeek - d.getDay(start) + 7) % 7;
+ // Every month has 4 full weeks (28 days); the extra 0-3 days decide whether
+ // the day appears a fifth time.
+ return offset < d.getDaysInMonth(start) - 28 ? 5 : 4;
+}
+
export function getMonthEnd(day: string): string {
return subDays(nextMonth(day.slice(0, 7)) + '-01', 1);
}
diff --git a/packages/loot-core/src/types/models/templates.ts b/packages/loot-core/src/types/models/templates.ts
index b71f7ccac2..06ca65aa02 100644
--- a/packages/loot-core/src/types/models/templates.ts
+++ b/packages/loot-core/src/types/models/templates.ts
@@ -76,6 +76,25 @@ export type AverageTemplate = {
adjustmentType?: 'percent' | 'fixed';
} & BaseTemplateWithPriority;
+export type Weekday =
+ | 'sunday'
+ | 'monday'
+ | 'tuesday'
+ | 'wednesday'
+ | 'thursday'
+ | 'friday'
+ | 'saturday';
+
+// Averages spending over the `numWeeks` complete weeks before the budget
+// month, then budgets that weekly amount once for every `weekday` in the month.
+export type WeeklyAverageTemplate = {
+ type: 'weeklyAverage';
+ numWeeks: number;
+ weekday: Weekday;
+ adjustment?: number;
+ adjustmentType?: 'percent' | 'fixed';
+} & BaseTemplateWithPriority;
+
export type CopyTemplate = {
type: 'copy';
lookBack: number;
@@ -130,6 +149,7 @@ export type Template =
| ScheduleTemplate
| RemainderTemplate
| AverageTemplate
+ | WeeklyAverageTemplate
| GoalTemplate
| CopyTemplate
| RefillTemplate
diff --git a/upcoming-release-notes/average-of-previous-weeks-automation.md b/upcoming-release-notes/average-of-previous-weeks-automation.md
new file mode 100644
index 0000000000..f18f1f03e5
--- /dev/null
+++ b/upcoming-release-notes/average-of-previous-weeks-automation.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [tim-smart]
+---
+
+Add an "Average of previous weeks" budget automation