A local-first personal finance app
Schedule forecast smoothing (#8862)
Mike Bishop53a61855b658
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.tsindex 191abdd5e9..22c7d68eb3 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@@ -3,6 +3,8 @@ import { vi } from 'vitest';import * as aql from '#server/aql';import * as db from '#server/db';import type { DbCategory } from '#server/db';+import { Rule } from '#server/rules';+import { getRuleForSchedule } from '#server/schedules/app';import * as monthUtils from '#shared/months';import { amountToInteger } from '#shared/util';import type { CategoryEntity } from '#types/models';@@ -11,6 +13,7 @@ import type { ByTemplate, Template } from '#types/models/templates';import * as actions from './actions';import { CategoryTemplateContext } from './category-template-context';import { distributeRemainder } from './goal-template';+import { runScheduleForecast } from './schedule-template';import * as statements from './statements';// Mock getSheetValue and getCategories@@ -23,8 +26,15 @@ vi.mock('./actions', () => ({vi.mock('#server/db', () => ({getCategories: vi.fn(),+ first: vi.fn(),+ getAccounts: vi.fn(),}));+vi.mock('#server/schedules/app', async () => {+ const actualModule = await vi.importActual('#server/schedules/app');+ return { ...actualModule, getRuleForSchedule: vi.fn() };+});+vi.mock('#server/aql', () => ({aqlQuery: vi.fn(),}));@@ -1219,6 +1229,131 @@ describe('CategoryTemplateContext', () => {});});+ describe('schedule templates', () => {+ const category: CategoryEntity = {+ id: 'gate-cat',+ name: 'Gate Category',+ group: 'g',+ is_income: false,+ };+ const templates: Template[] = [+ {+ type: 'schedule',+ name: 'Internet',+ directive: 'template',+ priority: 1,+ },+ {+ type: 'schedule',+ name: 'Insurance',+ directive: 'template',+ priority: 1,+ },+ ];++ function mockTwoSchedules() {+ vi.mocked(statements.getActiveSchedules).mockResolvedValue([+ { name: 'Internet', id: 's1' },+ { name: 'Insurance', id: 's2' },+ ] as Awaited<ReturnType<typeof statements.getActiveSchedules>>);+ vi.mocked(db.getAccounts).mockResolvedValue([]);+ vi.mocked(db.first).mockImplementation(async (_q, params?: unknown[]) => {+ const name = (params as string[] | undefined)?.[0] ?? '';+ return { id: name === 'Internet' ? 1 : 2, completed: 0 };+ });+ vi.mocked(getRuleForSchedule).mockImplementation(async id => {+ const isInternet = Number(id) === 1;+ return new Rule({+ id: String(id),+ stage: 'pre',+ conditionsOp: 'and',+ conditions: [+ {+ op: 'is',+ field: 'date',+ value: isInternet+ ? {+ start: '2024-03-15',+ interval: 1,+ frequency: 'yearly',+ patterns: [],+ skipWeekend: false,+ weekendSolveMode: 'before',+ endMode: 'never',+ endOccurrences: 1,+ endDate: '2099-01-01',+ }+ : {+ start: '2024-12-15',+ interval: 1,+ frequency: 'yearly',+ patterns: [],+ skipWeekend: false,+ weekendSolveMode: 'before',+ endMode: 'never',+ endOccurrences: 1,+ endDate: '2099-01-01',+ },+ type: 'date',+ },+ {+ op: 'is',+ field: 'amount',+ value: isInternet ? -10000 : -60000,+ type: 'number',+ },+ ],+ actions: [],+ });+ });+ vi.mocked(actions.isTrackingBudget).mockReturnValue(false);+ }++ beforeEach(() => {+ mockPreferences();+ vi.mocked(actions.getSheetValue).mockResolvedValue(0);+ vi.mocked(actions.getSheetBoolean).mockResolvedValue(false);+ vi.mocked(actions.isTrackingBudget).mockReturnValue(false);+ mockTwoSchedules();+ });++ it('budgets the forecast contribution for an empty category', async () => {+ const instance = await CategoryTemplateContext.init(+ templates,+ category,+ '2024-01',+ 0,+ );+ const result = await instance.runTemplatesForPriority(1, 100000, 100000);++ const expected = await runScheduleForecast(+ templates,+ '2024-01',+ 0,+ 0,+ category,+ );+ expect(expected.to_budget).toBeGreaterThan(0);+ expect(result).toBe(expected.to_budget);+ });++ it('budgets nothing when last month left more than the bills need', async () => {+ // $100 due each March and $600 each December: $5,000 left over+ // covers years of both.+ vi.mocked(actions.getSheetValue).mockResolvedValue(500000);++ const instance = await CategoryTemplateContext.init(+ templates,+ category,+ '2024-01',+ 0,+ );+ const result = await instance.runTemplatesForPriority(1, 100000, 100000);++ expect(result).toBe(0);+ });+ });+describe('full process', () => {it('should handle priority limits through the entire process', async () => {const category: CategoryEntity = {diff --git a/packages/loot-core/src/server/budget/category-template-context.ts b/packages/loot-core/src/server/budget/category-template-context.tsindex 446495cdd9..cfc5b6b803 100644--- a/packages/loot-core/src/server/budget/category-template-context.ts+++ b/packages/loot-core/src/server/budget/category-template-context.ts@@ -25,7 +25,7 @@ import {getSheetValue,isTrackingBudget,} from './actions';-import { runSchedule } from './schedule-template';+import { runScheduleForecast } from './schedule-template';import { getActiveSchedules } from './statements';export class CategoryTemplateContext {@@ -150,7 +150,6 @@ export class CategoryTemplateContext {let toBudget = 0;const perTemplateLocal = new Map<Template, number>();let byFlag = false;- let remainder = 0;let scheduleFlag = false;let schedulePerTemplate: Map<ScheduleTemplate, number> | null = null;let byPerTemplate: Map<ByTemplate, number> | null = null;@@ -201,20 +200,16 @@ export class CategoryTemplateContext {case 'schedule': {if (!scheduleFlag) {const budgeted = this.fromLastMonth + toBudget;- const ret = await runSchedule(+ const ret = await runScheduleForecast(t,this.month,budgeted,- remainder,- this.fromLastMonth,toBudget,- [],this.category,);// Schedules assume that its to budget value is the whole thing so this// needs to remove the previous funds so they aren't double countednewBudget = ret.to_budget - toBudget;- remainder = ret.remainder;schedulePerTemplate = ret.perScheduleMonthly;scheduleFlag = true;}@@ -237,7 +232,7 @@ export class CategoryTemplateContext {);}- // `runBy` and `runSchedule` produce a single batch total per priority bucket+ // `runBy` and `runScheduleForecast` produce a single batch total per priority bucket// and the loop above credits it to whichever sibling template ran first. For// per-template UI projections we want to split that batch across all the// sibling templates. The breakdown is approximate (equal split for schedule,@@ -251,7 +246,7 @@ export class CategoryTemplateContext {return Math.max(0, byPerTemplate?.get(template) ?? 0);});// Schedules: weight by each schedule's actual monthly contribution as- // computed by runSchedule, so the per-row UI projection reflects the+ // computed by runScheduleForecast, so the per-row UI projection reflects the// schedule's real cost rather than an equal split.redistributeBatch(perTemplateLocal, t, 'schedule', template => {if (template.type !== 'schedule') return 0;@@ -964,7 +959,7 @@ export class CategoryTemplateContext {}}-// `runBy` and `runSchedule` are batched: they compute a single budget number+// `runBy` and `runScheduleForecast` are batched: they compute a single budget number// for all sibling templates of the same type at a given priority, and the// caller loop credits that total to whichever template was iterated first.// Split the batch total across all siblings using `weightOf` so thediff --git a/packages/loot-core/src/server/budget/schedule-template.db.test.ts b/packages/loot-core/src/server/budget/schedule-template.db.test.tsnew file mode 100644index 0000000000..1b709de5e9--- /dev/null+++ b/packages/loot-core/src/server/budget/schedule-template.db.test.ts@@ -0,0 +1,654 @@+import * as db from '#server/db';+import { loadMappings } from '#server/db/mappings';+import {+ createSchedule,+ setNextDate,+ updateSchedule,+} from '#server/schedules/app';+import { loadRules } from '#server/transactions/transaction-rules';+import * as monthUtils from '#shared/months';+import type { CategoryEntity } from '#types/models';++import { runScheduleForecast } from './schedule-template';++// Runs the forecast against a real database, so the transaction queries go+// through the real AQL compiler rather than a mock that interprets their+// filters itself.++vi.mock('#shared/months', async () => {+ const actualModule =+ await vi.importActual<typeof monthUtils>('#shared/months');+ return { ...actualModule, currentDay: vi.fn(actualModule.currentDay) };+});++beforeEach(async () => {+ await global.emptyDatabase()();+ await loadMappings();+ await loadRules();+});++afterEach(() => {+ vi.mocked(monthUtils.currentDay).mockReset();+});++async function setUpRent(start = '2024-01-25') {+ const account = await db.insertAccount({+ name: 'Checking',+ offbudget: 0,+ closed: 0,+ });+ const group = await db.insertCategoryGroup({ name: 'Bills' });+ const categoryId = await db.insertCategory({+ name: 'Rent',+ cat_group: group,+ });+ const category = { id: categoryId, name: 'Rent' } as CategoryEntity;+ const scheduleId = await createSchedule({+ schedule: { name: 'Rent' },+ conditions: [+ { op: 'is', field: 'account', value: account },+ { op: 'is', field: 'amount', value: -10000 },+ {+ op: 'is',+ field: 'date',+ value: {+ start,+ frequency: 'monthly',+ interval: 1,+ patterns: [],+ skipWeekend: false,+ weekendSolveMode: 'after',+ endMode: 'never',+ },+ },+ ],+ });+ const payRent = (date: string, fromCategory: string | null = categoryId) =>+ db.insertTransaction({+ account,+ amount: -10000,+ date,+ category: fromCategory,+ schedule: scheduleId,+ });+ const template = {+ type: 'schedule',+ name: 'Rent',+ scheduleId,+ priority: 0,+ directive: 'template',+ } as const;+ return { account, category, payRent, template, scheduleId };+}++async function setUpOneTimeBills() {+ const account = await db.insertAccount({+ name: 'Checking',+ offbudget: 0,+ closed: 0,+ });+ const group = await db.insertCategoryGroup({ name: 'Bills' });+ const categoryId = await db.insertCategory({+ name: 'Annual bills',+ cat_group: group,+ });+ const category = { id: categoryId, name: 'Annual bills' } as CategoryEntity;+ const bills = [+ { name: 'Bill A', date: '2026-10-01', amount: -10000 },+ { name: 'Bill B', date: '2026-11-01', amount: -9000 },+ ];+ const templates = [];+ const scheduleIds: Record<string, string> = {};+ for (const bill of bills) {+ const scheduleId = await createSchedule({+ schedule: { name: bill.name },+ conditions: [+ { op: 'is', field: 'account', value: account },+ { op: 'is', field: 'amount', value: bill.amount },+ { op: 'is', field: 'date', value: bill.date },+ ],+ });+ scheduleIds[bill.name] = scheduleId;+ templates.push({+ type: 'schedule',+ name: bill.name,+ scheduleId,+ priority: 0,+ directive: 'template',+ } as const);+ }+ const payBill = (+ name: string,+ date: string,+ amount: number,+ fromCategory: string | null = categoryId,+ ) =>+ db.insertTransaction({+ account,+ amount,+ date,+ category: fromCategory,+ schedule: scheduleIds[name],+ });+ const otherCategoryId = await db.insertCategory({+ name: 'Other bills',+ cat_group: group,+ });+ return { category, otherCategoryId, payBill, templates, scheduleIds };+}++describe('runScheduleForecast against a real database', () => {+ it('ignores payments dated after today when re-running a past month', async () => {+ // Sep 15, re-running June. June's rent posted in June; September's and+ // October's are already entered with future dates. Only June's belongs+ // to June's budget.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-09-15');+ const { category, payRent, template } = await setUpRent();+ await payRent('2024-06-25');+ await payRent('2024-09-25');+ await payRent('2024-10-25');++ const result = await runScheduleForecast(+ [template],+ '2024-06',+ 0,+ 0,+ category,+ );++ expect(result.to_budget).toBe(10000);+ });++ it('ignores future-dated payments when budgeting the current month', async () => {+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-09-15');+ const { category, payRent, template } = await setUpRent();+ await payRent('2024-09-25');+ await payRent('2024-10-25');++ const result = await runScheduleForecast(+ [template],+ '2024-09',+ 0,+ 0,+ category,+ );++ expect(result.to_budget).toBe(10000);+ });++ it('does not charge a bill paid early in the previous month when budgeting ahead', async () => {+ // Oct 26, budgeting November. Rent is due on the 1st; November's was+ // paid and linked on Oct 25, so it already came out of the balance+ // carried into November. Only December onward is left to fund, so+ // December's $100 is saved over November and December.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-10-26');+ const { category, payRent, template } = await setUpRent('2024-01-01');+ await payRent('2024-10-01');+ await payRent('2024-10-25');++ const result = await runScheduleForecast(+ [template],+ '2024-11',+ 0,+ 0,+ category,+ );++ expect(result.to_budget).toBe(5000);+ });++ it('does not charge a bill paid early in the previous month when budgeting the current month', async () => {+ // Oct 15, budgeting October. October's rent, due on the 1st, was paid+ // and linked on Sep 29, so it already came out of the balance carried+ // into October. November's $100 is saved over October and November.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-10-15');+ const { category, payRent, template } = await setUpRent('2024-01-01');+ await payRent('2024-09-29');++ const result = await runScheduleForecast(+ [template],+ '2024-10',+ 0,+ 0,+ category,+ );++ expect(result.to_budget).toBe(5000);+ });++ it('reserves an unposted one-time bill from an earlier month when budgeting ahead', async () => {+ // Sep 22, budgeting November. Bill A ($100, Oct 1) hasn't posted, so+ // the $153.34 carried into November still has to pay it, leaving+ // $53.34 toward Bill B ($90, Nov 1).+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-09-22');+ const { category, templates } = await setUpOneTimeBills();++ const result = await runScheduleForecast(+ templates,+ '2026-11',+ 15334,+ 0,+ category,+ );++ expect(result.to_budget).toBe(3666);+ expect([...result.perScheduleMonthly.values()].every(Number.isFinite)).toBe(+ true,+ );+ });++ it('does not reserve a one-time bill from an earlier month once it has posted', async () => {+ // Same as above, but Bill A has posted, so the carry-in already+ // reflects it.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-09-22');+ const { category, payBill, templates } = await setUpOneTimeBills();+ await payBill('Bill A', '2026-10-01', -10000);++ const result = await runScheduleForecast(+ templates,+ '2026-11',+ 5334,+ 0,+ category,+ );++ expect(result.to_budget).toBe(3666);+ });++ it('still reserves a one-time bill when its only payment sits in another category', async () => {+ // Same schedule linked from two categories. The payment booked in the+ // other category didn't come out of this one's balance, so this+ // category still has to cover Bill A.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-09-22');+ const { category, otherCategoryId, payBill, templates } =+ await setUpOneTimeBills();+ await payBill('Bill A', '2026-10-01', -10000, otherCategoryId);++ const result = await runScheduleForecast(+ templates,+ '2026-11',+ 15334,+ 0,+ category,+ );++ expect(result.to_budget).toBe(3666);+ });++ it('covers a one-time bill that posted and completed this month', async () => {+ // Oct 3: Bill A posted on Oct 1 and the schedule service marked it+ // completed. $75 came into October, so October still owes the $25+ // the payment overspent.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-10-03');+ const { category, payBill, templates, scheduleIds } =+ await setUpOneTimeBills();+ await payBill('Bill A', '2026-10-01', -10000);+ await updateSchedule({+ schedule: { id: scheduleIds['Bill A'], completed: true },+ });++ const result = await runScheduleForecast(+ [templates[0]],+ '2026-10',+ 7500,+ 0,+ category,+ );++ expect(result.to_budget).toBe(2500);+ });++ it('covers a completed full-flag bill that posted this month', async () => {+ // Same as above, but the template carries the full flag.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-10-03');+ const { category, payBill, templates, scheduleIds } =+ await setUpOneTimeBills();+ await payBill('Bill A', '2026-10-01', -10000);+ await updateSchedule({+ schedule: { id: scheduleIds['Bill A'], completed: true },+ });++ const result = await runScheduleForecast(+ [{ ...templates[0], full: true }],+ '2026-10',+ 7500,+ 0,+ category,+ );++ expect(result.to_budget).toBe(2500);+ });++ it('asks a past month for the same amount before and after a schedule completes', async () => {+ // Oct 3, re-running August. Bill A posted Oct 1 and was completed.+ // From August, that payment is still a $100 outflow two months out,+ // alongside Bill B's $90 three months out: $190 over four months.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-10-03');+ const { category, payBill, templates, scheduleIds } =+ await setUpOneTimeBills();+ await payBill('Bill A', '2026-10-01', -10000);+ await updateSchedule({+ schedule: { id: scheduleIds['Bill A'], completed: true },+ });++ const result = await runScheduleForecast(+ templates,+ '2026-08',+ 0,+ 0,+ category,+ );++ expect(result.to_budget).toBe(4750);+ });++ it('counts a completed schedule payment dated later this month', async () => {+ // Oct 3: Bill A was entered for Oct 20 and marked completed by hand.+ // The payment is still ahead of today, so October has to cover it.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-10-03');+ const { category, payBill, templates, scheduleIds } =+ await setUpOneTimeBills();+ await payBill('Bill A', '2026-10-20', -10000);+ await updateSchedule({+ schedule: { id: scheduleIds['Bill A'], completed: true },+ });++ const result = await runScheduleForecast(+ [templates[0]],+ '2026-10',+ 7500,+ 0,+ category,+ );++ expect(result.to_budget).toBe(2500);+ });++ it('reserves a completed bill whose payment is not in this category when budgeting ahead', async () => {+ // Oct 7, budgeting November. Bill A posted Oct 1 and completed, but+ // the payment was uncategorized, so the $153.34 carried in still has+ // to pay it. Reported on #8862 as a way to budget next month before+ // this month's bill comes out.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-10-07');+ const { category, payBill, templates, scheduleIds } =+ await setUpOneTimeBills();+ await payBill('Bill A', '2026-10-01', -10000, null);+ await updateSchedule({+ schedule: { id: scheduleIds['Bill A'], completed: true },+ });++ const result = await runScheduleForecast(+ templates,+ '2026-11',+ 15334,+ 0,+ category,+ );++ expect(result.to_budget).toBe(3666);+ });++ it('counts a completed bill whose payment is dated after today', async () => {+ // Oct 7, budgeting November. Bill B was entered for Nov 1 and marked+ // completed by hand. The payment is still ahead, so November owes it.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-10-07');+ const { category, payBill, templates, scheduleIds } =+ await setUpOneTimeBills();+ await payBill('Bill B', '2026-11-01', -9000);+ await updateSchedule({+ schedule: { id: scheduleIds['Bill B'], completed: true },+ });++ const result = await runScheduleForecast(+ [templates[1]],+ '2026-11',+ 5334,+ 0,+ category,+ );++ expect(result.to_budget).toBe(3666);+ });++ it('ignores a schedule completed long ago whose template line was never removed', async () => {+ // Rent was completed in 2024 with its next date in June 2024. Two+ // years on, the rule would still yield a date every month (Oct 25 has+ // already passed), but nothing after that next date ever happened.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-06-01');+ const { category, template } = await setUpRent();+ await updateSchedule({+ schedule: { id: template.scheduleId, completed: true },+ });+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-10-27');++ const result = await runScheduleForecast(+ [template],+ '2026-10',+ 0,+ 0,+ category,+ );++ expect(result.to_budget).toBe(0);+ });++ it("does not count a posted full-flag payment as this month's spending", async () => {+ // Oct 10, budgeting October. Bill A is budgeted in full and was paid+ // Oct 1. Bill B is smoothed and due Nov 1. Bill A's $100 comes from its+ // own full amount; it isn't spending the forecast has to cover too.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-10-10');+ const { category, payBill, templates } = await setUpOneTimeBills();+ await payBill('Bill A', '2026-10-01', -10000);++ const result = await runScheduleForecast(+ [{ ...templates[0], full: true }, templates[1]],+ '2026-10',+ 0,+ 0,+ category,+ );++ // $100 for Bill A in full, plus $90 for Bill B spread over Oct and Nov.+ expect(result.to_budget).toBe(10000 + 4500);+ });++ it('counts a completed schedule up to a payment entered after its next date', async () => {+ // Rent was completed on Jun 1 with its next date Jun 25, after July's+ // and August's payments had been entered ahead of time. Earlier+ // payments are on file too. Budgeting August on Aug 1, the Aug 25+ // payment still has to be covered: it extends the schedule past its+ // next date, so the query for it must not drop it.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-06-01');+ const { category, payRent, template } = await setUpRent();+ for (const date of [+ '2024-04-25',+ '2024-05-25',+ '2024-07-25',+ '2024-08-25',+ ]) {+ await payRent(date);+ }+ await updateSchedule({+ schedule: { id: template.scheduleId, completed: true },+ });+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-08-01');++ const result = await runScheduleForecast(+ [template],+ '2024-08',+ 0,+ 0,+ category,+ );++ expect(result.to_budget).toBe(10000);+ });++ it('reserves nothing for a completed schedule when budgeting ahead', async () => {+ // Oct 3, budgeting November. Bill A completed, its payment already in+ // the carry-in. Only Bill B is left to cover.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-10-03');+ const { category, payBill, templates, scheduleIds } =+ await setUpOneTimeBills();+ await payBill('Bill A', '2026-10-01', -10000);+ await updateSchedule({+ schedule: { id: scheduleIds['Bill A'], completed: true },+ });++ const result = await runScheduleForecast(+ templates,+ '2026-11',+ 5334,+ 0,+ category,+ );++ expect(result.to_budget).toBe(3666);+ });++ it('splits among past one-time bills when no other schedule is left', async () => {+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-09-22');+ const { category, templates } = await setUpOneTimeBills();++ const result = await runScheduleForecast(+ [templates[0]],+ '2026-11',+ 5000,+ 0,+ category,+ );++ expect(result.to_budget).toBe(5000);+ expect(result.perScheduleMonthly.get(templates[0])).toBe(5000);+ });++ it('reserves a bill whose linked payment is not categorized yet when budgeting ahead', async () => {+ // Oct 26, budgeting November. October's rent (Oct 22) posted and is+ // linked, so the schedule moved on to Nov 22, but the payment hasn't+ // been categorized yet. The $100 carried into November still has to+ // pay it, so November needs its own $100.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-10-26');+ const { category, payRent, template, scheduleId } =+ await setUpRent('2026-10-22');+ await payRent('2026-10-22', null);+ await setNextDate({ id: scheduleId, advance: true });++ const result = await runScheduleForecast(+ [template],+ '2026-11',+ 10000,+ 0,+ category,+ );++ expect(result.to_budget).toBe(10000);+ });++ it('does not reserve a skipped occurrence when budgeting ahead', async () => {+ // Oct 26, budgeting November. October's rent was skipped, so the+ // $100 carried into November is free toward November's.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-10-26');+ const { category, template, scheduleId } = await setUpRent('2026-10-22');+ await setNextDate({ id: scheduleId, advance: true });++ const result = await runScheduleForecast(+ [template],+ '2026-11',+ 10000,+ 0,+ category,+ );++ expect(result.to_budget).toBe(0);+ });++ it('reserves a bill that has not posted yet this month when budgeting ahead', async () => {+ // Oct 20, budgeting November. October's rent (Oct 22) hasn't posted,+ // so the $100 carried into November still has to pay it.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-10-20');+ const { category, template } = await setUpRent('2026-10-22');++ const result = await runScheduleForecast(+ [template],+ '2026-11',+ 10000,+ 0,+ category,+ );++ expect(result.to_budget).toBe(10000);+ });++ describe('with an unpaid full-flag bill when budgeting ahead', () => {+ // Oct 20, budgeting November. Rent ($100 on the 25th) is budgeted in+ // full; October's was funded and hasn't posted. Insurance ($1,200 a+ // year, first due Oct 1, 2027) is smoothed and has nothing saved yet,+ // so it needs $100 a month.+ async function setUp() {+ vi.mocked(monthUtils.currentDay).mockReturnValue('2026-10-20');+ const { account, category, payRent, template } =+ await setUpRent('2026-01-25');+ const insuranceId = await createSchedule({+ schedule: { name: 'Insurance' },+ conditions: [+ { op: 'is', field: 'account', value: account },+ { op: 'is', field: 'amount', value: -120000 },+ {+ op: 'is',+ field: 'date',+ value: {+ start: '2027-10-01',+ frequency: 'yearly',+ interval: 1,+ patterns: [],+ skipWeekend: false,+ weekendSolveMode: 'after',+ endMode: 'never',+ },+ },+ ],+ });+ const templates = [+ { ...template, full: true },+ {+ type: 'schedule',+ name: 'Insurance',+ scheduleId: insuranceId,+ priority: 0,+ directive: 'template',+ } as const,+ ];+ return { category, payRent, templates };+ }++ it("does not treat the full-flag bill's funding as surplus", async () => {+ const { category, templates } = await setUp();++ const result = await runScheduleForecast(+ templates,+ '2026-11',+ 10000,+ 0,+ category,+ );++ // $100 for November's rent in full, plus $100 toward insurance.+ expect(result.to_budget).toBe(20000);+ });++ it('asks the same once the full-flag bill has posted', async () => {+ const { category, payRent, templates } = await setUp();+ await payRent('2026-10-20');++ const result = await runScheduleForecast(+ templates,+ '2026-11',+ 0,+ 0,+ category,+ );++ expect(result.to_budget).toBe(20000);+ });+ });+});diff --git a/packages/loot-core/src/server/budget/schedule-template.test.ts b/packages/loot-core/src/server/budget/schedule-template.test.tsindex a28e093591..a7f01d0c6f 100644--- a/packages/loot-core/src/server/budget/schedule-template.test.ts+++ b/packages/loot-core/src/server/budget/schedule-template.test.ts@@ -1,14 +1,30 @@+import { aqlQuery } from '#server/aql';import * as db from '#server/db';import { Rule } from '#server/rules';import { getRuleForSchedule } from '#server/schedules/app';+import * as monthUtils from '#shared/months';+import type { q } from '#shared/query';import type { CategoryEntity } from '#types/models';import type { ScheduleTemplate } from '#types/models/templates';-import { getSheetValue, isTrackingBudget } from './actions';-import { runSchedule } from './schedule-template';+import { isTrackingBudget } from './actions';+import {+ buildMonthlyOutflow,+ createScheduleList,+ runScheduleForecast,+ solveMonthlyContribution,+} from './schedule-template';vi.mock('#server/db');+vi.mock('#server/aql');vi.mock('./actions');+// currentDay() is pinned to 2017-01-01 under test; keep that by default and+// let the "relative to today" tests pin their own date.+vi.mock('#shared/months', async () => {+ const actualModule =+ await vi.importActual<typeof monthUtils>('#shared/months');+ return { ...actualModule, currentDay: vi.fn(actualModule.currentDay) };+});vi.mock('#server/schedules/app', async () => {const actualModule = await vi.importActual('#server/schedules/app');return {@@ -90,615 +106,1379 @@ function mockSchedulesByName(vi.mocked(isTrackingBudget).mockReturnValue(false);}-describe('runSchedule', () => {+describe('createScheduleList', () => {beforeEach(() => {vi.clearAllMocks();vi.mocked(db.getAccounts).mockResolvedValue([]);});- it('should return correct budget when recurring schedule set', async () => {- const template_lines = [- {- type: 'schedule',- name: 'Test Schedule',- priority: 0,- directive: 'template',- } as const,- ];+ it('includes dateConditions on each returned entry', async () => {mockSingleSchedule({start: '2024-08-01',amount: -10000,frequency: 'monthly',});+ const template = {+ type: 'schedule',+ name: 'Test Schedule',+ priority: 0,+ directive: 'template',+ } as const;- const result = await runSchedule(- template_lines,+ const { t } = await createScheduleList(+ [template],'2024-08-01',+ defaultCategory,+ );++ expect(t[0].dateConditions).toBeDefined();+ expect(t[0].dateConditions.value.frequency).toBe('monthly');+ });+});++describe('buildMonthlyOutflow', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(db.getAccounts).mockResolvedValue([]);+ });++ it('buckets each monthly schedule occurrence into its own month index', async () => {+ mockSingleSchedule({+ start: '2024-01-15',+ amount: -10000,+ frequency: 'monthly',+ });+ const template = {+ type: 'schedule',+ name: 'Rent',+ priority: 0,+ directive: 'template',+ } as const;+ const { t } = await createScheduleList(+ [template],+ '2024-01-01',+ defaultCategory,+ );++ vi.mocked(aqlQuery).mockResolvedValue({ data: [], dependencies: [] });++ const outflow = await buildMonthlyOutflow(t, '2024-01-01', defaultCategory);++ expect(outflow).toHaveLength(60);+ expect(outflow[0]).toBe(10000);+ expect(outflow[1]).toBe(10000);+ expect(outflow[59]).toBe(10000);+ });++ it('adds an unlinked future-dated transaction only to its own month', async () => {+ mockSingleSchedule({+ start: '2024-01-15',+ amount: -10000,+ frequency: 'monthly',+ });+ const template = {+ type: 'schedule',+ name: 'Rent',+ priority: 0,+ directive: 'template',+ } as const;+ const { t } = await createScheduleList(+ [template],+ '2024-01-01',+ defaultCategory,+ );++ vi.mocked(aqlQuery).mockResolvedValue({+ data: [{ amount: -5000, date: '2024-03-10' }],+ dependencies: [],+ });++ const outflow = await buildMonthlyOutflow(t, '2024-01-01', defaultCategory);++ expect(outflow[0]).toBe(10000);+ expect(outflow[2]).toBe(15000); // March: 10000 schedule + 5000 unlinked+ expect(outflow[3]).toBe(10000);+ });++ it('buckets a weekly schedule by its per-occurrence amount, not its monthly-aggregated target', async () => {+ // Regression test for the sub-monthly over-forecast bug: `target` on a+ // weekly entry is the *aggregated* monthly total (createScheduleList+ // sums every occurrence landing in its aggregation window into+ // `target`), not a per-occurrence amount. Bucketing occurrences by+ // `target` instead of `perOccurrenceAmount` would multiply an+ // already-aggregated monthly total by the occurrence count again.+ //+ // 2024-01-01 is a Monday, so weekly-every-Monday from that date lands+ // on 5 Mondays in January (1, 8, 15, 22, 29) and 4 in February (5, 12,+ // 19, 26) -- a real, independently-verifiable calendar fact, not a+ // number derived from the code under test.+ mockSingleSchedule({+ start: '2024-01-01',+ amount: -1000,+ frequency: 'weekly',+ });+ const template = {+ type: 'schedule',+ name: 'Weekly Bill',+ priority: 0,+ directive: 'template',+ } as const;+ const { t } = await createScheduleList(+ [template],+ '2024-01-01',+ defaultCategory,+ );++ // Sanity check on the fixture itself: target is the aggregated+ // January total (5 occurrences), not the single-occurrence amount.+ expect(t[0].target).toBe(5000);+ expect(t[0].perOccurrenceAmount).toBe(1000);++ vi.mocked(aqlQuery).mockResolvedValue({ data: [], dependencies: [] });++ const outflow = await buildMonthlyOutflow(t, '2024-01-01', defaultCategory);++ expect(outflow[0]).toBe(5000); // 5 Mondays in January x $10+ expect(outflow[1]).toBe(4000); // 4 Mondays in February x $10+ });+});++describe('buildMonthlyOutflow relative to today', () => {+ const rentTemplate = {+ type: 'schedule',+ name: 'Rent',+ priority: 0,+ directive: 'template',+ } as const;++ // A monthly $100 rent due on the 25th, with the schedule's stored+ // next_date (the first unpaid occurrence) given as a date repr.+ function mockRent(nextDateRepr: number | null) {+ mockSingleSchedule({+ start: '2024-01-25',+ amount: -10000,+ frequency: 'monthly',+ });+ vi.mocked(db.first).mockResolvedValue({+ id: 1,+ completed: 0,+ next_date: nextDateRepr,+ });+ }++ type QueryKind = 'posted' | 'unlinked' | 'linked';++ // buildMonthlyOutflow issues up to three transaction queries; tell them+ // apart by their filters, since the aqlQuery mock ignores them.+ function queryKind(query: ReturnType<typeof q>): QueryKind {+ const filters: ReadonlyArray<Record<string, unknown>> =+ query.serialize().filterExpressions;+ const scheduleFilter = filters.find(f => 'schedule' in f);+ if (scheduleFilter) {+ return scheduleFilter.schedule === null ? 'unlinked' : 'linked';+ }+ return 'posted';+ }++ type MockTransaction = {+ amount: number;+ date: string;+ schedule?: number | null;+ category?: string | null;+ };++ // Answers each query the way the database would: the transactions inside+ // its date range, limited to unlinked or linked ones where it asks. A+ // transaction is in defaultCategory unless it says otherwise.+ function mockTransactionQueries(transactions: MockTransaction[]) {+ vi.mocked(aqlQuery).mockImplementation(async rawQuery => {+ const query = rawQuery as ReturnType<typeof q>;+ const kind = queryKind(query);+ const range = dateFilter(kind, query);+ const data = transactions+ .filter(+ t =>+ (range.$gte === undefined || t.date >= range.$gte) &&+ (range.$lt === undefined || t.date < range.$lt) &&+ (kind === 'posted' ||+ (kind === 'unlinked' ? t.schedule == null : t.schedule != null)),+ )+ .map(t => ({ category: defaultCategory.id, ...t }));+ return { data, dependencies: [] };+ });+ }++ type DateRange = { $gte?: string; $lt?: string };++ // The date range a query actually applies, read the way AQL compiles it:+ // an array of operator objects is ANDed together, but an object with+ // several operators only applies its first one.+ function dateFilter(+ kind: QueryKind,+ query?: ReturnType<typeof q>,+ ): DateRange {+ query ??= vi+ .mocked(aqlQuery)+ .mock.calls.map(([call]) => call as ReturnType<typeof q>)+ .find(call => queryKind(call) === kind);+ const date = query+ ?.serialize()+ .filterExpressions.find((f: Record<string, unknown>) => 'date' in f)+ ?.date as DateRange | DateRange[] | undefined;+ if (date === undefined) return {};+ const operators = Array.isArray(date) ? date : [date];+ return Object.fromEntries(+ operators.map(operator => Object.entries(operator)[0]),+ );+ }++ function unlinkedDateFilter() {+ return dateFilter('unlinked');+ }++ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(db.getAccounts).mockResolvedValue([]);+ vi.mocked(aqlQuery).mockResolvedValue({ data: [], dependencies: [] });+ });++ afterEach(() => {+ // Restores the real (test-pinned) implementation passed to vi.fn.+ vi.mocked(monthUtils.currentDay).mockReset();+ });++ it('reads the stored next_date into storedNextDate', async () => {+ mockRent(20241025);+ const { t } = await createScheduleList(+ [rentTemplate],+ '2024-11',+ defaultCategory,+ );+ expect(t[0].storedNextDate).toBe('2024-10-25');+ });++ it('counts only future-dated unlinked transactions when re-running a past month', async () => {+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-09-15');+ mockRent(20240925);+ const { t } = await createScheduleList(+ [rentTemplate],+ '2024-06',+ defaultCategory,+ );++ await buildMonthlyOutflow(t, '2024-06', defaultCategory);++ expect(unlinkedDateFilter()).toEqual({+ $gte: '2024-09-16',+ $lt: '2029-06-01',+ });+ });++ it('still counts unlinked spending already posted in the current month', async () => {+ // Sep 15, budgeting September: a $40 unlinked purchase on Sep 5 has to+ // be covered alongside the $100 rent, which isn't due until Sep 25.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-09-15');+ mockRent(20240925);+ mockTransactionQueries([{ amount: -4000, date: '2024-09-05' }]);++ const result = await runScheduleForecast(+ [rentTemplate],+ '2024-09',0,0,+ defaultCategory,+ );++ expect(dateFilter('posted')).toEqual({+ $gte: '2024-09-01',+ $lt: '2024-09-16',+ });+ expect(unlinkedDateFilter()).toEqual({+ $gte: '2024-09-16',+ $lt: '2029-09-01',+ });+ expect(result.to_budget).toBe(14000);+ });++ it('does not double-count a hand-entered, unlinked payment of a bill already due this month', async () => {+ // Sep 26, re-running September: rent (Sep 25) was paid by hand and not+ // linked. It can't be told apart from the rent itself, so the month+ // needs max($100 due, $100 spent), not both.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-09-26');+ mockRent(20240925);+ mockTransactionQueries([{ amount: -10000, date: '2024-09-25' }]);++ const result = await runScheduleForecast(+ [rentTemplate],+ '2024-09',0,0,- [],defaultCategory,);expect(result.to_budget).toBe(10000);- expect(result.errors).toHaveLength(0);- expect(result.remainder).toBe(0);});- it('should return correct budget when yearly recurring schedule set and balance is greater than target', async () => {- const template_lines = [- {- type: 'schedule',- name: 'Test Schedule',- directive: 'template',- priority: 0,- } as const,- ];+ it('does not double-count a linked payment made before its due date this month', async () => {+ // Sep 21, re-running September: rent (Sep 25) was paid and linked on+ // Sep 20. The linked payment marks the Sep 25 occurrence as elapsed.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-09-21');+ mockRent(20240925);+ mockTransactionQueries([+ { amount: -10000, date: '2024-09-20', schedule: 1 },+ ]);+ const { t } = await createScheduleList(+ [rentTemplate],+ '2024-09',+ defaultCategory,+ );++ const outflow = await buildMonthlyOutflow(t, '2024-09', defaultCategory);++ expect(outflow[0]).toBe(10000);+ });++ it("attributes a late linked payment to last month's occurrence, not this month's", async () => {+ // Sep 15: August's rent (Aug 25) was paid late, linked, on Sep 2. It's+ // nearer Aug 25 than Sep 25, so September's rent is still due.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-09-15');+ mockRent(20240925);+ mockTransactionQueries([+ { amount: -10000, date: '2024-09-02', schedule: 1 },+ ]);+ const { t } = await createScheduleList(+ [rentTemplate],+ '2024-09',+ defaultCategory,+ );++ const outflow = await buildMonthlyOutflow(t, '2024-09', defaultCategory);++ expect(outflow[0]).toBe(20000); // the $100 already spent + Sep 25's $100+ });++ it.each([+ ['rent posted unlinked', [-10000], 10000],+ ['rent plus a $40 unlinked extra', [-10000, -4000], 14000],+ ['rent that came in at $105', [-10500], 10500],+ ['rent that came in at $95', [-9500], 10000],+ ])(+ 're-running a past month counts the larger of scheduled and actual spending: %s',+ async (_label, amounts, expected) => {+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-09-15');+ mockRent(20240925);+ mockTransactionQueries(+ amounts.map(amount => ({ amount, date: '2024-06-25' })),+ );+ const { t } = await createScheduleList(+ [rentTemplate],+ '2024-06',+ defaultCategory,+ );++ const outflow = await buildMonthlyOutflow(t, '2024-06', defaultCategory);++ expect(dateFilter('posted')).toEqual({+ $gte: '2024-06-01',+ $lt: '2024-07-01',+ });+ expect(outflow[0]).toBe(expected);+ expect(outflow[1]).toBe(10000);+ },+ );++ it('starts the unlinked-transaction window at the budget month when budgeting ahead', async () => {+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-10-20');+ mockRent(20241125);+ const { t } = await createScheduleList(+ [rentTemplate],+ '2024-11',+ defaultCategory,+ );++ await buildMonthlyOutflow(t, '2024-11', defaultCategory);++ expect(unlinkedDateFilter()).toEqual({+ $gte: '2024-11-01',+ $lt: '2029-11-01',+ });+ });++ it('counts an unpaid occurrence due before the budget month against month 0', async () => {+ // Budgeting November on Oct 20; October's rent (Oct 25) hasn't posted,+ // so the carried-over balance still holds the money for it.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-10-20');+ mockRent(20241025);+ const { t } = await createScheduleList(+ [rentTemplate],+ '2024-11',+ defaultCategory,+ );++ const outflow = await buildMonthlyOutflow(t, '2024-11', defaultCategory);++ expect(outflow[0]).toBe(20000); // October's pending rent + November's+ expect(outflow[1]).toBe(10000);+ });++ it('settles a pending occurrence with a linked payment made before its due date', async () => {+ // Oct 21: October's rent (Oct 25) was paid and linked on Oct 20.+ // next_date hasn't advanced, but the payment is already out of the+ // carried-over balance, so October isn't pending.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-10-21');+ mockRent(20241025);+ mockTransactionQueries([+ { amount: -10000, date: '2024-10-20', schedule: 1 },+ ]);+ const { t } = await createScheduleList(+ [rentTemplate],+ '2024-11',+ defaultCategory,+ );++ const outflow = await buildMonthlyOutflow(t, '2024-11', defaultCategory);++ expect(dateFilter('linked')).toEqual({+ $gte: '2022-10-01',+ $lt: '2024-11-01',+ });+ expect(outflow[0]).toBe(10000);+ });++ it('does not settle a pending occurrence with an unlinked payment', async () => {+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-10-21');+ mockRent(20241025);+ mockTransactionQueries([{ amount: -10000, date: '2024-10-20' }]);+ const { t } = await createScheduleList(+ [rentTemplate],+ '2024-11',+ defaultCategory,+ );++ const outflow = await buildMonthlyOutflow(t, '2024-11', defaultCategory);++ expect(outflow[0]).toBe(20000);+ });++ it("does not settle a pending occurrence with a late payment of last month's", async () => {+ // Oct 20: September's rent was paid late, linked, on Oct 3. It's nearer+ // Sep 25 than Oct 25, so October's rent is still pending.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-10-20');+ mockRent(20241025);+ mockTransactionQueries([+ { amount: -10000, date: '2024-10-03', schedule: 1 },+ ]);+ const { t } = await createScheduleList(+ [rentTemplate],+ '2024-11',+ defaultCategory,+ );++ const outflow = await buildMonthlyOutflow(t, '2024-11', defaultCategory);++ expect(outflow[0]).toBe(20000);+ });++ it('adds nothing extra once the prior occurrence has posted', async () => {+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-10-26');+ mockRent(20241125);+ const { t } = await createScheduleList(+ [rentTemplate],+ '2024-11',+ defaultCategory,+ );++ const outflow = await buildMonthlyOutflow(t, '2024-11', defaultCategory);++ expect(outflow[0]).toBe(10000);+ });++ it('ignores occurrences missed before the real current month', async () => {+ // next_date stuck in June (never paid); only October's occurrence,+ // which is still ahead of today, counts as pending.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-10-20');+ mockRent(20240625);+ const { t } = await createScheduleList(+ [rentTemplate],+ '2024-11',+ defaultCategory,+ );++ const outflow = await buildMonthlyOutflow(t, '2024-11', defaultCategory);++ expect(outflow[0]).toBe(20000);+ });++ it("does not settle a pending quarterly occurrence with a late payment of the previous quarter's", async () => {+ // Quarterly $300 due Jan 28, Apr 28, Jul 28. On Apr 20, budgeting+ // July: January's bill was paid late, linked, on Mar 12. That's nearer+ // Jan 28 than Apr 28, so April's occurrence is still pending.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-04-20');mockSingleSchedule({- start: '2024-08-01',- amount: -12000,- frequency: 'yearly',+ start: '2024-01-28',+ amount: -30000,+ frequency: 'monthly',+ interval: 3,+ });+ vi.mocked(db.first).mockResolvedValue({+ id: 1,+ completed: 0,+ next_date: 20240428,+ });+ mockTransactionQueries([+ { amount: -30000, date: '2024-03-12', schedule: 1 },+ ]);+ const { t } = await createScheduleList(+ [rentTemplate],+ '2024-07',+ defaultCategory,+ );++ const outflow = await buildMonthlyOutflow(t, '2024-07', defaultCategory);++ expect(outflow[0]).toBe(60000); // April's pending $300 + July's+ });++ it('settles a pending occurrence only once when it was paid in parts', async () => {+ // Every two weeks, $100, due Oct 12 and Oct 26. On Oct 10, budgeting+ // November: the Oct 12 bill was paid in two linked $50 parts. Both are+ // nearest Oct 12, so Oct 26 is still pending.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-10-10');+ mockSingleSchedule({+ start: '2024-09-28',+ amount: -10000,+ frequency: 'weekly',+ interval: 2,});+ vi.mocked(db.first).mockResolvedValue({+ id: 1,+ completed: 0,+ next_date: 20241012,+ });+ mockTransactionQueries([+ { amount: -5000, date: '2024-10-09', schedule: 1 },+ { amount: -5000, date: '2024-10-10', schedule: 1 },+ ]);+ const { t } = await createScheduleList(+ [rentTemplate],+ '2024-11',+ defaultCategory,+ );- const result = await runSchedule(- template_lines,- '2024-09-01',- 12000,- 0,- 12000,+ const outflow = await buildMonthlyOutflow(t, '2024-11', defaultCategory);++ // Oct 26 pending + Nov 9 + Nov 23+ expect(outflow[0]).toBe(30000);+ });++ it('budgets November in full when October rent is still unpaid', async () => {+ // Regression for budgeting next month early: October's $100 is still+ // in the balance but is spoken for, so November needs its own $100.+ vi.mocked(monthUtils.currentDay).mockReturnValue('2024-10-20');+ mockRent(20241025);++ const result = await runScheduleForecast(+ [rentTemplate],+ '2024-11',+ 10000,0,- [],defaultCategory,);- expect(result.to_budget).toBe(1000);- expect(result.errors).toHaveLength(0);- expect(result.remainder).toBe(0);+ expect(result.to_budget).toBe(10000);+ });+});++describe('runScheduleForecast', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(db.getAccounts).mockResolvedValue([]);+ vi.mocked(aqlQuery).mockResolvedValue({ data: [], dependencies: [] });});- it('returns a per-template monthly attribution map keyed by template', async () => {+ it('contributes the exact monthly amount for a single monthly schedule', async () => {const template_lines = [{type: 'schedule',- name: ' Test Schedule ',- directive: 'template',+ name: 'Rent',priority: 0,+ directive: 'template',} as const,];mockSingleSchedule({- start: '2024-08-01',+ start: '2024-01-15',amount: -10000,frequency: 'monthly',});- const result = await runSchedule(+ const result = await runScheduleForecast(template_lines,- '2024-08-01',- 0,- 0,+ '2024-01-01',0,0,- [],defaultCategory,);- expect(result.perScheduleMonthly.get(template_lines[0])).toBe(10000);expect(result.to_budget).toBe(10000);});- it('handles a pay-month-of monthly schedule alongside a yearly sinking schedule', async () => {+ it('never projects a negative month-end balance across two schedules sharing a category', async () => {const template_lines = [{type: 'schedule',- name: 'Internet',- directive: 'template',+ name: 'Monthly',priority: 0,+ directive: 'template',} as const,{type: 'schedule',- name: 'Insurance',- directive: 'template',+ name: 'Yearly',priority: 0,+ directive: 'template',} as const,];mockSchedulesByName({- Internet: {+ Monthly: {spec: { start: '2024-01-15', amount: -10000, frequency: 'monthly' },},- Insurance: {+ Yearly: {spec: { start: '2024-12-15', amount: -60000, frequency: 'yearly' },},});- const result = await runSchedule(+ const result = await runScheduleForecast(template_lines,'2024-01-01',0,0,- 0,- 0,- [],defaultCategory,);- expect(result.errors).toHaveLength(0);- const internet = result.perScheduleMonthly.get(template_lines[0]) ?? 0;- const insurance = result.perScheduleMonthly.get(template_lines[1]) ?? 0;- expect(internet).toBe(10000); // pay-month-of: full target- expect(insurance).toBeGreaterThan(0);- expect(insurance).toBeLessThan(internet);- expect(internet + insurance).toBeCloseTo(result.to_budget, -1);+ // Re-derive the projection with the returned candidate to check the+ // postcondition directly.+ const { t } = await createScheduleList(+ template_lines as ScheduleTemplate[],+ '2024-01-01',+ defaultCategory,+ );+ const outflow = await buildMonthlyOutflow(t, '2024-01-01', defaultCategory);+ let runningBalance = 0;+ let minBalance = Infinity;+ for (let i = 0; i < 60; i++) {+ runningBalance += result.to_budget - outflow[i];+ minBalance = Math.min(minBalance, runningBalance);+ }+ expect(minBalance).toBeGreaterThanOrEqual(0);+ // And it should be the *minimal* such contribution: one cent less+ // must produce a negative month somewhere.+ let runningBalanceMinusOne = 0;+ let wentNegative = false;+ for (let i = 0; i < 60; i++) {+ runningBalanceMinusOne += result.to_budget - 1 - outflow[i];+ if (runningBalanceMinusOne < 0) wentNegative = true;+ }+ expect(wentNegative).toBe(true);});- it('budgets nothing in advance for a yearly schedule with `full: true`', async () => {+ it('covers a same-month-due schedule in full immediately rather than smoothing it away', async () => {const template_lines = [{type: 'schedule',- name: 'Insurance',- full: true,- directive: 'template',+ name: 'DueNow',priority: 0,+ directive: 'template',} as const,];mockSingleSchedule({- start: '2024-12-15',+ start: '2024-01-15',amount: -60000,frequency: 'yearly',});- const result = await runSchedule(+ const result = await runScheduleForecast(template_lines,'2024-01-01',0,0,- 0,- 0,- [],defaultCategory,);- expect(result.to_budget).toBe(0);- expect(result.perScheduleMonthly.get(template_lines[0])).toBeUndefined();++ expect(result.to_budget).toBe(60000);});- it('only attributes contribution to schedules occurring this month when full: true is used', async () => {+ it('budgets full-flag schedules on top of, and separate from, the forecast', async () => {const template_lines = [{type: 'schedule',- name: 'Schedule A',+ name: 'Full',full: true,- directive: 'template',priority: 0,+ directive: 'template',} as const,{type: 'schedule',- name: 'Schedule B',- full: true,- directive: 'template',+ name: 'Smooth',priority: 0,+ directive: 'template',} as const,];mockSchedulesByName({- 'Schedule A': {- spec: { start: '2024-08-01', amount: -10000, frequency: 'monthly' },+ Full: {+ spec: { start: '2024-12-15', amount: -60000, frequency: 'yearly' },},- 'Schedule B': {- spec: { start: '2024-09-01', amount: -20000, frequency: 'monthly' },+ Smooth: {+ spec: { start: '2024-01-15', amount: -10000, frequency: 'monthly' },},});- const result = await runSchedule(+ const result = await runScheduleForecast(template_lines,- '2024-08-01',- 0,- 0,+ '2024-01-01',0,0,- [],defaultCategory,);+ // Full schedule isn't due this month, so its on-top contribution is 0;+ // only the smooth monthly schedule contributes.expect(result.to_budget).toBe(10000);- expect(result.perScheduleMonthly.get(template_lines[0])).toBe(10000);- expect(result.perScheduleMonthly.get(template_lines[1])).toBeUndefined();+ expect(result.perScheduleMonthly.get(template_lines[1])).toBe(10000);});- it('applies a percent adjustment to the schedule amount', async () => {+ it('does not fund a full-flag bill due this month twice', async () => {const template_lines = [{type: 'schedule',- name: 'Bill',- adjustment: 10,- adjustmentType: 'percent',- directive: 'template',+ name: 'Full',+ full: true,priority: 0,+ directive: 'template',} as const,- ];- mockSingleSchedule({- start: '2024-08-15',- amount: -10000,- frequency: 'monthly',- });-- const result = await runSchedule(- template_lines,- '2024-08-01',- 0,- 0,- 0,- 0,- [],- defaultCategory,- );- expect(result.to_budget).toBe(11000); // $100 × 1.10- });-- it('applies a fixed adjustment to the schedule amount', async () => {- const template_lines = [{type: 'schedule',- name: 'Bill',- adjustment: 5,- adjustmentType: 'fixed',- directive: 'template',+ name: 'Smooth',priority: 0,+ directive: 'template',} as const,];- mockSingleSchedule({- start: '2024-08-15',- amount: -10000,- frequency: 'monthly',+ mockSchedulesByName({+ Full: {+ spec: { start: '2024-01-20', amount: -60000, frequency: 'yearly' },+ },+ Smooth: {+ spec: { start: '2024-01-15', amount: -10000, frequency: 'monthly' },+ },});- const result = await runSchedule(+ const result = await runScheduleForecast(template_lines,- '2024-08-01',- 0,- 0,+ '2024-01-01',0,0,- [],defaultCategory,);- expect(result.to_budget).toBe(10500); // $100 + $5++ // $600 in full for the bill due this month, plus $100 for the monthly+ // one. The $600 is new money, so it doesn't also come off the balance.+ expect(result.to_budget).toBe(70000);});- it('skips completed schedules from the budget total', async () => {+ it('splits perScheduleMonthly by monthly-equivalent contribution, not raw target, for a monthly + yearly mix', async () => {const template_lines = [{type: 'schedule',- name: 'Done',- directive: 'template',+ name: 'Monthly',priority: 0,+ directive: 'template',} as const,- ];- mockSingleSchedule(- { start: '2024-08-15', amount: -10000, frequency: 'monthly' },- 1,- );-- const result = await runSchedule(- template_lines,- '2024-08-01',- 0,- 0,- 0,- 0,- [],- defaultCategory,- );- expect(result.to_budget).toBe(0);- });-- it('budgets all daily occurrences within the month for a daily schedule', async () => {- const template_lines = [{type: 'schedule',- name: 'Daily Bill',- directive: 'template',+ name: 'Yearly',priority: 0,+ directive: 'template',} as const,];- mockSingleSchedule({- start: '2024-01-01',- amount: -100,- frequency: 'daily',+ mockSchedulesByName({+ Monthly: {+ spec: { start: '2024-01-15', amount: -10000, frequency: 'monthly' },+ },+ Yearly: {+ spec: { start: '2024-12-15', amount: -60000, frequency: 'yearly' },+ },});- const result = await runSchedule(+ const result = await runScheduleForecast(template_lines,'2024-01-01',0,0,- 0,- 0,- [],defaultCategory,);- expect(result.to_budget).toBe(3100); // 31 days × $1++ // No full-flag entries and a starting balance of 0, so the whole+ // to_budget is the smoothed candidate.+ const candidate = result.to_budget;+ const monthlyShare = result.perScheduleMonthly.get(template_lines[0]);+ const yearlyShare = result.perScheduleMonthly.get(template_lines[1]);+ expect(monthlyShare).toBeDefined();+ expect(yearlyShare).toBeDefined();+ if (monthlyShare === undefined || yearlyShare === undefined) {+ throw new Error('unreachable');+ }++ // Monthly-equivalent weights are 10000 (Monthly, target/1) and 5000+ // (Yearly, target/1/12 = 60000/12) -- a 2:1 ratio -- not the raw+ // 10000:60000 (1:6) ratio a naive split on entry.target would produce.+ expect(monthlyShare / yearlyShare).toBeCloseTo(2, 1);+ // The two shares should still (modulo per-share rounding) add back up+ // to the single smoothed candidate.+ expect(monthlyShare + yearlyShare).toBeGreaterThanOrEqual(candidate - 1);+ expect(monthlyShare + yearlyShare).toBeLessThanOrEqual(candidate + 1);});- it('sorts sinking schedules by next due date so existing balance covers the earliest first', async () => {- // Templates given in reverse-date order to verify the engine sorts.- // Sorted (May first): ($1200-$200)/5 + $600/11 = $254.55 → 25455- // Unsorted (Nov first): ($600-$200)/11 + $1200/5 = $276.36 — the- // assertion below only matches if the sort runs.+ it('never produces a non-finite perScheduleMonthly share when smooth schedules in one category offset to a zero net weight', async () => {const template_lines = [{type: 'schedule',- name: 'November bill',- directive: 'template',+ name: 'Expense',priority: 0,+ directive: 'template',} as const,{type: 'schedule',- name: 'May bill',- directive: 'template',+ name: 'Refund',priority: 0,+ directive: 'template',} as const,];mockSchedulesByName({- 'November bill': {- spec: { start: '2024-11-15', amount: -60000, frequency: 'yearly' },+ // Monthly-equivalent weight: 10000 (target / interval).+ Expense: {+ spec: { start: '2024-01-15', amount: -10000, frequency: 'monthly' },},- 'May bill': {- spec: { start: '2024-05-15', amount: -120000, frequency: 'yearly' },+ // Monthly-equivalent weight: -120000 / 1 / 12 = -10000, exactly+ // offsetting Expense's weight so the total nets to zero while+ // neither individual weight is zero.+ Refund: {+ spec: { start: '2024-01-15', amount: 120000, frequency: 'yearly' },},});- const result = await runSchedule(+ const result = await runScheduleForecast(template_lines,'2024-01-01',0,0,- 20000,- 0,- [],defaultCategory,);- expect(result.errors).toHaveLength(0);- expect(result.to_budget).toBe(25455);+ expect(result.perScheduleMonthly.size).toBe(2);+ for (const share of result.perScheduleMonthly.values()) {+ expect(Number.isFinite(share)).toBe(true);+ }});- it('records a Past error for a non-repeating schedule whose date has already passed', async () => {- // Non-repeating (no frequency) and dated before current_month → engine- // marks it as past rather than rolling forward.+ it('never underfunds two annual schedules with different due dates, sharing a category (regression: actualbudget/actual#6513)', async () => {+ // #6513: two annual schedules in one category (£100 due Feb, £90 due+ // Mar), with £80 already banked going into January, under-budgeted+ // every month under the old algorithm's independent per-schedule+ // remainder chaining. Assert runScheduleForecast's own postcondition+ // directly: every projected month-end balance stays non-negative.const template_lines = [{type: 'schedule',- name: 'Past',+ name: 'Bill A',+ priority: 0,directive: 'template',+ } as const,+ {+ type: 'schedule',+ name: 'Bill B',priority: 0,+ directive: 'template',} as const,];- vi.mocked(db.first).mockResolvedValue({ id: 1, completed: 0 });- vi.mocked(getRuleForSchedule).mockResolvedValue(- new Rule({- id: 'r',- stage: 'pre',- conditionsOp: 'and',- conditions: [- { op: 'is', field: 'date', value: '2023-06-01', type: 'date' },- { op: 'is', field: 'amount', value: -10000, type: 'number' },- ],- actions: [],- }),- );- vi.mocked(isTrackingBudget).mockReturnValue(false);-- const result = await runSchedule(+ mockSchedulesByName({+ 'Bill A': {+ spec: { start: '2025-02-15', amount: -10000, frequency: 'yearly' },+ },+ 'Bill B': {+ spec: { start: '2025-03-15', amount: -9000, frequency: 'yearly' },+ },+ });++ const result = await runScheduleForecast(template_lines,- '2024-01-01',- 0,- 0,- 0,+ '2025-01-01',+ 8000,0,- [],defaultCategory,);- expect(result.errors).toContainEqual(- expect.stringMatching(/Schedule Past is in the Past/),++ const { t } = await createScheduleList(+ template_lines as ScheduleTemplate[],+ '2025-01-01',+ defaultCategory,);- expect(result.to_budget).toBe(0);+ const outflow = await buildMonthlyOutflow(t, '2025-01-01', defaultCategory);+ let runningBalance = 8000;+ let minBalance = Infinity;+ for (let i = 0; i < 60; i++) {+ runningBalance += result.to_budget - outflow[i];+ minBalance = Math.min(minBalance, runningBalance);+ }+ expect(minBalance).toBeGreaterThanOrEqual(0);+ });+});++describe('runScheduleForecast budgeting rules', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(db.getAccounts).mockResolvedValue([]);+ vi.mocked(aqlQuery).mockResolvedValue({ data: [], dependencies: [] });});- it('contributes target/interval per month for a fully-funded bi-monthly schedule', async () => {- // Every-2-months from 2024-03-15: interval 2 keeps it out of the- // pay-month-of fast path. With balance == target the engine takes- // the base-contribution branch: target / interval = $200 / 2 = $100.- const template_lines = [- {- type: 'schedule',- name: 'BiMonthly',- directive: 'template',- priority: 0,- } as const,- ];+ const billTemplate = {+ type: 'schedule',+ name: 'Bill',+ directive: 'template',+ priority: 0,+ } as const;++ it('applies a percent adjustment to the schedule amount', async () => {mockSingleSchedule({- start: '2024-03-15',- amount: -20000,+ start: '2024-08-15',+ amount: -10000,frequency: 'monthly',- interval: 2,});- const result = await runSchedule(- template_lines,- '2024-01-01',- 20000,- 0,+ const result = await runScheduleForecast(+ [{ ...billTemplate, adjustment: 10, adjustmentType: 'percent' }],+ '2024-08-01',0,0,- [],defaultCategory,);- expect(result.to_budget).toBe(10000);+ expect(result.to_budget).toBe(11000); // $100 × 1.10});- it('contributes target / months-spanned for a fully-funded six-week schedule', async () => {- // Every 6 weeks from 2024-02-12: outside the weekly pay-month-of- // cap (≤4), so it sinks. With balance == target the base path runs:- // prev = subWeeks(2024-02-12, 6) = 2024-01-01, span = 1 month →- // contribution = $60 / 1 = $60.- const template_lines = [- {- type: 'schedule',- name: 'EverySixWeeks',- directive: 'template',- priority: 0,- } as const,- ];+ it('applies a fixed adjustment to the schedule amount', async () => {mockSingleSchedule({- start: '2024-02-12',- amount: -6000,- frequency: 'weekly',- interval: 6,+ start: '2024-08-15',+ amount: -10000,+ frequency: 'monthly',});- const result = await runSchedule(- template_lines,- '2024-01-01',- 6000,- 0,+ const result = await runScheduleForecast(+ [{ ...billTemplate, adjustment: 5, adjustmentType: 'fixed' }],+ '2024-08-01',0,0,- [],defaultCategory,);- expect(result.to_budget).toBe(6000);+ expect(result.to_budget).toBe(10500); // $100 + $5});- it('contributes target / months-spanned for a fully-funded sixty-day schedule', async () => {- // Every 60 days from 2024-03-01: outside the daily pay-month-of- // cap (≤31), so it sinks. With balance == target the base path- // runs: prev = subDays(2024-03-01, 60) = 2024-01-01, span = 2- // months → contribution = $60 / 2 = $30.- const template_lines = [- {- type: 'schedule',- name: 'EverySixtyDays',- directive: 'template',- priority: 0,- } as const,- ];- mockSingleSchedule({- start: '2024-03-01',- amount: -6000,- frequency: 'daily',- interval: 60,- });+ it('budgets nothing for a completed schedule with no payments', async () => {+ mockSingleSchedule(+ { start: '2024-08-15', amount: -10000, frequency: 'monthly' },+ 1,+ );- const result = await runSchedule(- template_lines,- '2024-01-01',- 6000,- 0,+ const result = await runScheduleForecast(+ [billTemplate],+ '2024-08-01',0,0,- [],defaultCategory,);- expect(result.to_budget).toBe(3000);+ expect(result.to_budget).toBe(0);});it('keeps meeting the deadline for a schedule repeating every 360 days', async () => {- // Every 360 days is daily in shape but yearly in effect, so it sinks:- // $500 due 2026-05-15 spread over the five months from January is $100- // a month. Once January is funded, February used to drop to $41.67 --- // subDays(2026-05-15, 360) lands in May 2025, and that 12-month span- // became the divisor. The deadline and the $100 already saved were both- // ignored, so the category came up short in May.- const template_lines = [- {- type: 'schedule',- name: 'EveryThreeSixtyDays',- directive: 'template',- priority: 0,- } satisfies ScheduleTemplate,- ];+ // Every 360 days is daily in shape but yearly in effect. $500 is due+ // 2026-05-15 and $100 is already saved, so February through May need+ // the remaining $400 at $100 a month (#6644).mockSingleSchedule({start: '2026-05-15',amount: -50000,frequency: 'daily',interval: 360,});- // January budgeted $100 and nothing was spent, so it carries forward and- // is also last month's goal.- vi.mocked(getSheetValue).mockResolvedValue(10000);- const result = await runSchedule(- template_lines,+ const result = await runScheduleForecast(+ [billTemplate],'2026-02-01',10000,0,- 10000,- 0,- [],defaultCategory,);expect(result.to_budget).toBe(10000);});- it('absorbs surplus when last-month balance exceeds a sinking schedule target', async () => {- // Last-month balance ($150) > yearly target ($120). The sink rolls- // the surplus forward and contributes nothing this month.- const template_lines = [- {- type: 'schedule',- name: 'Overfunded',- directive: 'template',- priority: 0,- } as const,- ];+ it('budgets nothing while the category holds more than its bills need', async () => {+ // $1,200 due every March. The steady rate is $100 a month, and $5,000+ // banked covers years of it.mockSingleSchedule({- start: '2024-12-15',- amount: -12000,+ start: '2024-03-15',+ amount: -120000,frequency: 'yearly',});- const result = await runSchedule(- template_lines,+ const result = await runScheduleForecast(+ [billTemplate],'2024-01-01',+ 500000,0,+ defaultCategory,+ );+ expect(result.to_budget).toBe(0);+ });++ it('never takes money back out of the category', async () => {+ mockSingleSchedule({+ start: '2024-03-15',+ amount: -120000,+ frequency: 'yearly',+ });++ const result = await runScheduleForecast(+ [billTemplate],+ '2024-01-01',+ 10000000,0,- 15000,- 0,- [],defaultCategory,);expect(result.to_budget).toBe(0);});- it('forces sinking schedules into pay-month-of mode when tracking-budget is on', async () => {- // In tracking mode every schedule is treated as pay-month-of. A- // far-future yearly schedule that would normally contribute ~$100/mo- // sinking instead contributes 0 this month, since pay-month-of only- // counts schedules whose num_months is 0.+ describe('in a tracking budget', () => {+ it('budgets nothing ahead for a bill due in a later month', async () => {+ mockSingleSchedule({+ start: '2024-12-15',+ amount: -12000,+ frequency: 'yearly',+ });+ vi.mocked(isTrackingBudget).mockReturnValue(true);++ const result = await runScheduleForecast(+ [billTemplate],+ '2024-01-01',+ 0,+ 0,+ defaultCategory,+ );+ expect(result.to_budget).toBe(0);+ });++ it('budgets a bill in full in the month it is due', async () => {+ mockSingleSchedule({+ start: '2024-12-15',+ amount: -12000,+ frequency: 'yearly',+ });+ vi.mocked(isTrackingBudget).mockReturnValue(true);++ const result = await runScheduleForecast(+ [billTemplate],+ '2024-12-01',+ 0,+ 0,+ defaultCategory,+ );+ expect(result.to_budget).toBe(12000);+ });+ });+});++describe('runScheduleForecast (real AQL query path)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(db.getAccounts).mockResolvedValue([]);+ });++ it('builds and compiles a real unlinked-transaction query for a month-shaped current_month and a weekly schedule', async () => {+ // Integration regression test for Fix 1 (month-shaped `current_month`+ // like '2024-01' must not throw a CompileError from the AQL date+ // caster, which requires day-shaped date literals) and Fix 2 (a+ // weekly, non-monthly schedule must not be over-counted).+ //+ // `#server/aql` is automocked for the rest of this file (see the+ // top-level `vi.mock('#server/aql')`), which is exactly what would+ // hide both of these bugs: the query never actually gets built or+ // compiled. To exercise the real query-building/compiling path we+ // unmock just this module and re-import it (and its dependents) into+ // a fresh module registry, while `#server/db` stays mocked -- so the+ // real AQL compiler runs, and only the actual SQLite read at the very+ // bottom (`db.all`) is stubbed.+ vi.resetModules();+ vi.doUnmock('#server/aql');++ const dbMod = await import('#server/db');+ vi.mocked(dbMod.getAccounts).mockResolvedValue([]);+ vi.mocked(dbMod.first).mockResolvedValue({ id: 1, completed: 0 } as never);+ // The compiler's date caster stores dates as an integer (YYYYMMDD);+ // db.all returns raw SQLite rows, which applyTypes then converts back+ // to a 'yyyy-MM-dd' string via convertOutputType.+ // Return a fresh array/object on every call: `applyTypes` mutates the+ // returned rows in place when converting output types, and this test+ // calls the real query-building path more than once (`runScheduleForecast`+ // internally, then again independently below to verify the result).+ vi.mocked(dbMod.all).mockImplementation(+ async () => [{ amount: -500, date: 20240120 }] as never,+ );++ const scheduleAppMod = await import('#server/schedules/app');+ vi.mocked(scheduleAppMod.getRuleForSchedule).mockResolvedValue(+ makeRule({ start: '2024-01-01', amount: -1000, frequency: 'weekly' }),+ );++ const actionsMod = await import('./actions');+ vi.mocked(actionsMod.isTrackingBudget).mockReturnValue(false);++ const scheduleTemplateMod = await import('./schedule-template');+const template_lines = [{type: 'schedule',- name: 'YearlyFar',- directive: 'template',+ name: 'Weekly Bill',priority: 0,+ directive: 'template',} as const,];- vi.mocked(db.first).mockResolvedValue({ id: 1, completed: 0 });- vi.mocked(getRuleForSchedule).mockResolvedValue(- makeRule({ start: '2024-12-15', amount: -12000, frequency: 'yearly' }),++ try {+ // Month-shaped, as the real budget engine passes it -- this is what+ // Fix 1 makes safe to pass straight to the AQL query.+ const result = await scheduleTemplateMod.runScheduleForecast(+ template_lines,+ '2024-01',+ 0,+ 0,+ defaultCategory,+ );+ // Re-derive the projection independently to confirm the query result+ // (the unlinked $5 transaction on 2024-01-20) and the weekly+ // schedule's per-occurrence amount were both folded in correctly,+ // rather than asserting a value that could pass by coincidence.+ const { t } = await scheduleTemplateMod.createScheduleList(+ template_lines as ScheduleTemplate[],+ '2024-01',+ defaultCategory,+ );+ const outflow = await scheduleTemplateMod.buildMonthlyOutflow(+ t,+ '2024-01',+ defaultCategory,+ );+ // 5 Mondays in January 2024 x $10 + the $5 unlinked transaction.+ expect(outflow[0]).toBe(5000 + 500);++ let runningBalance = 0;+ let minBalance = Infinity;+ for (let i = 0; i < 60; i++) {+ runningBalance += result.to_budget - outflow[i];+ minBalance = Math.min(minBalance, runningBalance);+ }+ expect(minBalance).toBeGreaterThanOrEqual(0);+ } finally {+ // Restore the file-wide automock and module registry for any tests+ // that run after this one.+ vi.doMock('#server/aql');+ vi.resetModules();+ }+ });+});++describe('solveMonthlyContribution', () => {+ it('finds the minimal whole-cent contribution for a single one-time bill', () => {+ const monthlyOutflow = new Array(60).fill(0);+ monthlyOutflow[30] = 60000; // one bill, due in month 30+ const candidate = solveMonthlyContribution(0, monthlyOutflow, 0);+ // 60000 / 31 months = 1935.48 -> ceil to 1936; verify it actually+ // covers month 30 and is the minimal such whole-cent amount.+ expect(candidate * 31).toBeGreaterThanOrEqual(60000);+ expect((candidate - 1) * 31).toBeLessThan(60000);+ });++ it('picks the month with the larger cumulative threshold, not the one with the larger raw balance', () => {+ // Regression test for a weighting bug in an earlier guess-and-correct+ // version of solveMonthlyContribution (see that function's own doc+ // comment for the derivation). Month 0's threshold is 100 (weight 1);+ // month 59's is higher, at 149, but at any shared candidate near 149+ // its raw shortfall (threshold gap x weight) is *smaller* than month+ // 0's would be, purely because of the (i+1) weighting. The correct+ // answer is governed by whichever month's *threshold* (need / (i+1))+ // is larger — here that's month 59, not whichever month's raw balance+ // looks more negative at some candidate.+ // Month 0's own outflow is 100 (threshold_0 = 100/1 = 100). Month+ // 59's *cumulative* outflow needs to make threshold_59 = 149, i.e.+ // cumsum_59 = 149 * 60 = 8940, with month 0's 100 already part of+ // that cumulative sum.+ const outflow = new Array(60).fill(0);+ outflow[0] = 100;+ outflow[59] = 8940 - 100;++ const candidate = solveMonthlyContribution(0, outflow, 0);+ expect(candidate).toBe(149); // threshold_59, the true max — not threshold_0 (100)++ let runningBalance = 0;+ let minBalance = Infinity;+ for (let i = 0; i < 60; i++) {+ runningBalance += candidate - outflow[i];+ minBalance = Math.min(minBalance, runningBalance);+ }+ expect(minBalance).toBeGreaterThanOrEqual(0);+ });++ // $1,200 due each March and $600 each September, starting in January.+ function yearlyBillsOutflow(startMonth: number) {+ return Array.from({ length: 60 }, (_, i) => {+ const monthOfYear = (startMonth + i) % 12;+ if (monthOfYear === 2) return 120000;+ if (monthOfYear === 8) return 60000;+ return 0;+ });+ }++ it('budgets the steady rate once a category holds exactly what its bills need', () => {+ // The lowest balance the steady $150/month covers is $750 in January.+ expect(solveMonthlyContribution(75000, yearlyBillsOutflow(0), 15000)).toBe(+ 15000,+ );+ });++ it('budgets nothing while the category holds more than its bills need', () => {+ expect(solveMonthlyContribution(500000, yearlyBillsOutflow(0), 15000)).toBe(+ 0,+ );+ });++ it('covers only what a small surplus does not', () => {+ // $50 over the $750 needed: $150 less the $50 surplus.+ expect(solveMonthlyContribution(80000, yearlyBillsOutflow(0), 15000)).toBe(+ 10000,+ );+ });++ it('never asks for less than nothing', () => {+ expect(+ solveMonthlyContribution(10000000, yearlyBillsOutflow(0), 15000),+ ).toBe(0);+ });++ it('uses up a surplus, then settles at the steady rate without going negative', () => {+ let balance = 500000;+ const contributions: number[] = [];+ for (let month = 0; month < 72; month++) {+ const outflow = yearlyBillsOutflow(month);+ const contribution = solveMonthlyContribution(balance, outflow, 15000);+ contributions.push(contribution);+ balance += contribution - outflow[0];+ expect(balance).toBeGreaterThanOrEqual(0);+ }++ const firstPaid = contributions.findIndex(amount => amount > 0);+ expect(firstPaid).toBeGreaterThan(24);+ expect(+ contributions.slice(0, firstPaid).every(amount => amount === 0),+ ).toBe(true);+ // After at most one partial month, every month is the steady rate.+ expect(+ contributions.slice(firstPaid + 1).every(amount => amount === 15000),+ ).toBe(true);+ });++ it('catches up faster than the steady rate when the category is short', () => {+ // Empty in January with $1,200 due in March: $400/month until then.+ expect(solveMonthlyContribution(0, yearlyBillsOutflow(0), 15000)).toBe(+ 40000,);- vi.mocked(isTrackingBudget).mockReturnValue(true);+ });- const result = await runSchedule(+ it('spreads the catch-up evenly up to the first bill when bills start a few months out', () => {+ // $190 a month in bills, first due two months from now. The months+ // before the first bill don't pull the steady rate below $190, so the+ // catch-up is $190 over three months, not nearly $190 up front.+ const outflowFrom = (month: number) =>+ Array.from({ length: 60 }, (_, i) => (month + i >= 2 ? 19000 : 0));+ let balance = 0;+ const contributions: number[] = [];+ for (let month = 0; month < 6; month++) {+ const outflow = outflowFrom(month);+ const contribution = solveMonthlyContribution(balance, outflow, 19000);+ contributions.push(contribution);+ balance += contribution - outflow[0];+ expect(balance).toBeGreaterThanOrEqual(0);+ }+ expect(contributions).toEqual([6334, 6333, 6333, 19000, 19000, 19000]);+ });+});++// Budgets attached to the review of actualbudget/actual#8862.+describe('runScheduleForecast on reviewer budgets', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(db.getAccounts).mockResolvedValue([]);+ vi.mocked(aqlQuery).mockResolvedValue({ data: [], dependencies: [] });+ });++ const template = (name: string) =>+ ({ type: 'schedule', name, priority: 0, directive: 'template' }) as const;++ it('saves up evenly for monthly bills that start a few months out', async () => {+ const template_lines = [template('Bill A'), template('Bill B')];+ mockSchedulesByName({+ 'Bill A': {+ spec: { start: '2026-10-22', amount: -10000, frequency: 'monthly' },+ },+ 'Bill B': {+ spec: { start: '2026-10-22', amount: -9000, frequency: 'monthly' },+ },+ });++ const result = await runScheduleForecast(template_lines,- '2024-01-01',+ '2026-08',0,0,+ defaultCategory,+ );++ // $190 due in October, saved over August, September and October.+ expect(result.to_budget).toBe(6334);+ });++ it('gives the catch-up to the schedules that are behind, not a monthly bill that is on pace', async () => {+ const template_lines = [+ template('Monthly'),+ template('Yearly 1'),+ template('Yearly 2'),+ ];+ mockSchedulesByName({+ Monthly: {+ spec: { start: '2026-10-01', amount: -100000, frequency: 'monthly' },+ },+ 'Yearly 1': {+ spec: { start: '2027-02-01', amount: -500000, frequency: 'yearly' },+ },+ 'Yearly 2': {+ spec: { start: '2027-04-01', amount: -500000, frequency: 'yearly' },+ },+ });++ const result = await runScheduleForecast(+ template_lines,+ '2026-10',0,0,- [],defaultCategory,);- expect(result.to_budget).toBe(0);++ // $17,000 due October through April, over those seven months.+ expect(result.to_budget).toBe(242858);+ expect(result.perScheduleMonthly.get(template_lines[0])).toBe(100000);+ expect(result.perScheduleMonthly.get(template_lines[1])).toBe(71429);+ expect(result.perScheduleMonthly.get(template_lines[2])).toBe(71429);});});diff --git a/packages/loot-core/src/server/budget/schedule-template.ts b/packages/loot-core/src/server/budget/schedule-template.tsindex a636e76002..edc3988e3a 100644--- a/packages/loot-core/src/server/budget/schedule-template.ts+++ b/packages/loot-core/src/server/budget/schedule-template.ts@@ -1,41 +1,49 @@// @ts-strict-ignore+import { aqlQuery } from '#server/aql';import * as db from '#server/db';+import { fromDateRepr } from '#server/models';import { collectFormulasFromActions } from '#server/rules/balanceOfFormula';import { getRuleForSchedule } from '#server/schedules/app';import { prefetchBalanceOfForTransaction } from '#server/transactions/transaction-rules';import * as monthUtils from '#shared/months';+import { q } from '#shared/query';import {extractScheduleConds,getDateWithSkippedWeekend,getNextDate,+ getOccurrencesBetween,} from '#shared/schedules';import { amountToInteger } from '#shared/util';import type { CategoryEntity, TransactionEntity } from '#types/models';import type { ScheduleTemplate, Template } from '#types/models/templates';-import { getSheetValue, isTrackingBudget } from './actions';+import { isTrackingBudget } from './actions';type ScheduleTemplateTarget = {template: ScheduleTemplate;name: string;target: number;+ perOccurrenceAmount: number;next_date_string: string;+ storedNextDate: string | null;+ scheduleId: string;target_interval: number;target_frequency: string | undefined;num_months: number;completed: number;full: boolean;repeat: boolean;+ dateConditions: ReturnType<typeof extractScheduleConds>['date'];+ isPastDue: boolean;};-async function createScheduleList(+export async function createScheduleList(templates: ScheduleTemplate[],current_month: string,category: CategoryEntity,) {const t: Array<ScheduleTemplateTarget> = [];- const errors: string[] = [];const accounts = (await db.getAccounts()) ?? [];const accountsMap = new Map(accounts.map(a => [a.id, a]));@@ -43,16 +51,31 @@ async function createScheduleList(// Prefer scheduleId so renames don't break the lookup; fall back to name// for notes-source templates (and legacy ui-source data) that only carry// the name.+ // next_date mirrors the v_schedules view's computed column.const {id: sid,name: scheduleName,completed,- } = await db.first<Pick<db.DbSchedule, 'id' | 'name' | 'completed'>>(- template.scheduleId- ? 'SELECT id, name, completed FROM schedules WHERE id = ? AND tombstone = 0'- : 'SELECT id, name, completed FROM schedules WHERE TRIM(name) = ? AND tombstone = 0',+ next_date: storedNextDateRepr,+ } = await db.first<+ Pick<db.DbSchedule, 'id' | 'name' | 'completed'> & {+ next_date: number | null;+ }+ >(+ `SELECT s.id, s.name, s.completed,+ CASE+ WHEN nd.local_next_date_ts = nd.base_next_date_ts THEN nd.local_next_date+ ELSE nd.base_next_date+ END AS next_date+ FROM schedules s+ LEFT JOIN schedules_next_date nd ON nd.schedule_id = s.id+ WHERE ${template.scheduleId ? 's.id = ?' : 'TRIM(s.name) = ?'} AND s.tombstone = 0`,[template.scheduleId ?? template.name],);+ const storedNextDate =+ typeof storedNextDateRepr === 'number'+ ? fromDateRepr(storedNextDateRepr)+ : null;const rule = await getRuleForSchedule(sid);const conditions = rule.serialize().conditions;const { date: dateConditions, amount: amountCondition } =@@ -140,279 +163,711 @@ async function createScheduleList(current_month,);const displayName = scheduleName ?? template.name ?? '';- if (num_months < 0) {- //non-repeating schedules could be negative- errors.push(`Schedule ${displayName} is in the Past.`);- } else {- t.push({- template,- target,- next_date_string,- target_interval,- target_frequency,- num_months,- completed,- //started,- full: template.full === null ? false : template.full,- repeat: isRepeating,- name: displayName,- });- if (!completed) {- if (isRepeating) {- let monthlyTarget = 0;- const nextMonth = monthUtils.addMonths(- current_month,- t[t.length - 1].num_months + 1,- );- let nextBaseDate = getNextDate(- dateConditions,- monthUtils._parse(current_month),- true,- );- let nextDate = dateConditions.value.skipWeekend- ? monthUtils.dayFromDate(- getDateWithSkippedWeekend(- monthUtils._parse(nextBaseDate),- dateConditions.value.weekendSolveMode,- ),- )- : nextBaseDate;- while (nextDate < nextMonth) {- monthlyTarget += -target;- const currentDate = nextBaseDate;- const oneDayLater = monthUtils.addDays(nextBaseDate, 1);- nextBaseDate = getNextDate(- dateConditions,- monthUtils._parse(oneDayLater),- true,- );- nextDate = dateConditions.value.skipWeekend- ? monthUtils.dayFromDate(- getDateWithSkippedWeekend(- monthUtils._parse(nextBaseDate),- dateConditions.value.weekendSolveMode,- ),- )- : nextBaseDate;- const diffDays = monthUtils.differenceInCalendarDays(- nextBaseDate,- currentDate,- );- if (!diffDays) {- // This can happen if the schedule has an end condition.- break;- }- }- t[t.length - 1].target = -monthlyTarget;- }- } else {- errors.push(- `Schedule ${displayName} is not active during the month in question.`,+ const isPastDue = num_months < 0;+ t.push({+ template,+ target,+ perOccurrenceAmount: target,+ next_date_string,+ storedNextDate,+ scheduleId: sid,+ target_interval,+ target_frequency,+ num_months,+ completed,+ //started,+ full: template.full === null ? false : template.full,+ repeat: isRepeating,+ name: displayName,+ dateConditions,+ isPastDue,+ });+ if (!completed && isRepeating && !isPastDue) {+ let monthlyTarget = 0;+ const nextMonth = monthUtils.addMonths(+ current_month,+ t[t.length - 1].num_months + 1,+ );+ let nextBaseDate = getNextDate(+ dateConditions,+ monthUtils._parse(current_month),+ true,+ );+ let nextDate = dateConditions.value.skipWeekend+ ? monthUtils.dayFromDate(+ getDateWithSkippedWeekend(+ monthUtils._parse(nextBaseDate),+ dateConditions.value.weekendSolveMode,+ ),+ )+ : nextBaseDate;+ while (nextDate < nextMonth) {+ monthlyTarget += -target;+ const currentDate = nextBaseDate;+ const oneDayLater = monthUtils.addDays(nextBaseDate, 1);+ nextBaseDate = getNextDate(+ dateConditions,+ monthUtils._parse(oneDayLater),+ true,+ );+ nextDate = dateConditions.value.skipWeekend+ ? monthUtils.dayFromDate(+ getDateWithSkippedWeekend(+ monthUtils._parse(nextBaseDate),+ dateConditions.value.weekendSolveMode,+ ),+ )+ : nextBaseDate;+ const diffDays = monthUtils.differenceInCalendarDays(+ nextBaseDate,+ currentDate,);+ if (!diffDays) {+ // This can happen if the schedule has an end condition.+ break;+ }}+ t[t.length - 1].target = -monthlyTarget;}}- return { t: t.filter(c => c.completed === 0), errors };+ return { t };}-function getPayMonthOfTotal(t: ScheduleTemplateTarget[]) {- //return the contribution amounts of full or every month type schedules- let total = 0;- const schedules = t.filter(c => c.num_months === 0);- for (const schedule of schedules) {- total += schedule.target;+const FORECAST_MONTHS = 60;++type PostedTransaction = {+ amount?: number;+ date: string;+ schedule: string | null;+ category?: string | null;+};++// How far either side of a range to look for the occurrence nearest a+// linked payment. It has to reach the occurrence before and after any+// payment, so it covers schedules that recur as rarely as every two years.+const LINKED_PAYMENT_SEARCH_MONTHS = 25;++function linkedSearchStart(rangeStart: string) {+ return `${monthUtils.subMonths(rangeStart, LINKED_PAYMENT_SEARCH_MONTHS)}-01`;+}++function linkedSearchEnd(rangeEnd: string) {+ return `${monthUtils.addMonths(rangeEnd, LINKED_PAYMENT_SEARCH_MONTHS)}-01`;+}++// Index of the first date in ascending `dates` that is not before `day`.+function firstIndexFrom(dates: string[], day: string) {+ let low = 0;+ let high = dates.length;+ while (low < high) {+ const mid = (low + high) >> 1;+ if (dates[mid] < day) low = mid + 1;+ else high = mid;}- return total;+ return low;}-function getSinkingContributionBreakdown(- t: ScheduleTemplateTarget[],- remainder: number,- last_month_balance: number,-) {- // Mirrors getSinkingContributionTotal but also records each schedule's- // contribution so the caller can attribute the batch back to individual- // templates. Total math is unchanged.- let total = 0;- const perSchedule = new Map<ScheduleTemplate, number>();- for (const [index, schedule] of t.entries()) {- remainder =- index === 0- ? schedule.target - last_month_balance- : schedule.target - remainder;- let tg = 0;- if (remainder >= 0) {- tg = remainder;- remainder = 0;- } else {- tg = 0;- remainder = Math.abs(remainder);+// Months from `month` to the month of `day`; both start "YYYY-MM". Same as+// monthUtils.differenceInCalendarMonths, without parsing dates, since it+// runs once per occurrence.+function monthsBetween(month: string, day: string) {+ return (+ (Number(day.slice(0, 4)) - Number(month.slice(0, 4))) * 12 ++ Number(day.slice(5, 7)) -+ Number(month.slice(5, 7))+ );+}++type OccurrencesBetween = (startDay: string, endDay: string) => string[];++// A schedule's occurrences across every range given, generated in one pass+// and sliced per request. Generating occurrences is the expensive part of+// the forecast (thousands for a daily schedule), and the ranges overlap.+// A slice is the same as generating that range on its own; a range outside+// the ones given is generated directly.+function occurrenceLookup(+ entry: ScheduleTemplateTarget,+ ranges: Array<[string, string]>,+): OccurrencesBetween {+ let coveredStart = ranges[0][0];+ let coveredEnd = ranges[0][1];+ for (const [startDay, endDay] of ranges) {+ if (startDay < coveredStart) coveredStart = startDay;+ if (endDay > coveredEnd) coveredEnd = endDay;+ }+ const dates = getOccurrencesBetween(+ entry.dateConditions,+ coveredStart,+ coveredEnd,+ );+ return (startDay, endDay) => {+ if (startDay < coveredStart || endDay > coveredEnd) {+ return getOccurrencesBetween(entry.dateConditions, startDay, endDay);}- const contribution = tg / (schedule.num_months + 1);- total += contribution;- perSchedule.set(- schedule.template,- (perSchedule.get(schedule.template) ?? 0) + contribution,+ return dates.slice(+ firstIndexFrom(dates, startDay),+ firstIndexFrom(dates, endDay),);- }- return { total, perSchedule };+ };}-function getMonthlyBaseContribution(schedule: ScheduleTemplateTarget) {- let prevDate;- let intervalMonths;- switch (schedule.target_frequency) {- case 'yearly':- return schedule.target / schedule.target_interval / 12;- case 'monthly':- return schedule.target / schedule.target_interval;- case 'weekly':- prevDate = monthUtils.subWeeks(- schedule.next_date_string,- schedule.target_interval,+// Which of this schedule's occurrences in [rangeStart, rangeEnd) are+// settled by its linked payments. The link says which schedule a payment+// belongs to; each payment is attributed to that schedule's nearest+// occurrence, so an early payment settles the upcoming occurrence and a+// late one settles the previous occurrence, not the next. Several payments+// nearest the same occurrence (a bill paid in parts) settle it only once.+function settledOccurrences(+ entry: ScheduleTemplateTarget,+ transactions: PostedTransaction[],+ rangeStart: string,+ rangeEnd: string,+ occurrencesBetween: OccurrencesBetween,+): Set<string> {+ const settled = new Set<string>();+ const linked = transactions.filter(+ transaction => transaction.schedule === entry.scheduleId,+ );+ if (linked.length === 0) return settled;++ // Ascending, so the nearest occurrence is one of the two either side of+ // the payment's date; on a tie the later one wins.+ const nearby = occurrencesBetween(+ linkedSearchStart(rangeStart),+ linkedSearchEnd(rangeEnd),+ );+ if (nearby.length === 0) return settled;+ for (const transaction of linked) {+ const low = firstIndexFrom(nearby, transaction.date);+ const distanceTo = (index: number) =>+ Math.abs(+ monthUtils.differenceInCalendarDays(transaction.date, nearby[index]),);- intervalMonths = monthUtils.differenceInCalendarMonths(- schedule.next_date_string,- prevDate,+ const nearest =+ low === nearby.length ||+ (low > 0 && distanceTo(low - 1) < distanceTo(low))+ ? nearby[low - 1]+ : nearby[low];+ if (nearest >= rangeStart && nearest < rangeEnd) {+ settled.add(nearest);+ }+ }+ return settled;+}++export async function buildMonthlyOutflow(+ smoothEntries: ScheduleTemplateTarget[],+ current_month: string,+ category: CategoryEntity,+ // Schedules budgeted in full outside the forecast. Their payments come+ // out of that separate amount, so they aren't this month's spending.+ // Budgeting ahead, their unpaid occurrences before the window are still+ // reserved below like the smooth ones': that money sits in the balance.+ fullEntries: ScheduleTemplateTarget[] = [],+): Promise<number[]> {+ const fullScheduleIds = fullEntries.map(entry => entry.scheduleId);+ const reservedEntries = [...smoothEntries, ...fullEntries];+ const monthlyOutflow = new Array(FORECAST_MONTHS).fill(0);+ const windowStart = monthUtils.firstDayOfMonth(current_month);+ const windowEnd = `${monthUtils.addMonths(current_month, FORECAST_MONTHS)}-01`;+ const today = monthUtils.currentDay();+ const currentMonthStart = monthUtils.firstDayOfMonth(today);+ const isBudgetingAhead = windowStart > currentMonthStart;++ // A completed schedule's rule still yields dates, but nothing after the+ // next date it had when it was completed ever happened. Its occurrences+ // count up to a cutoff: that stored next date, or the last payment+ // linked to it in this category if that is later (a payment entered+ // ahead of time). Up to the cutoff it is treated exactly like an active+ // schedule, so completing it changes nothing about what already+ // happened. With neither a next date nor a payment, nothing counts.+ const occurrenceCutoff = new Map<string, string>();+ const completedEntries = smoothEntries.filter(entry => entry.completed);+ if (completedEntries.length > 0) {+ // A payment only moves a cutoff when it's after that schedule's next+ // date, so when every schedule has one, older payments needn't be read.+ // On an old budget file the full payment history is slow to query.+ const nextDates = completedEntries.map(entry => entry.storedNextDate);+ const earliestNextDate = nextDates.includes(null)+ ? null+ : nextDates.reduce((earliest, date) =>+ date < earliest ? date : earliest,+ );+ const { data: completedPayments } = await aqlQuery(+ q('transactions')+ .filter({+ category: category.id,+ schedule: { $oneof: completedEntries.map(entry => entry.scheduleId) },+ 'account.offbudget': false,+ ...(earliestNextDate ? { date: { $gt: earliestNextDate } } : {}),+ })+ .select(['date', 'schedule']),+ );+ const lastPayment = new Map<string, string>();+ for (const transaction of completedPayments) {+ const previous = lastPayment.get(transaction.schedule) ?? '';+ if (transaction.date > previous) {+ lastPayment.set(transaction.schedule, transaction.date);+ }+ }+ for (const entry of completedEntries) {+ const nextDate = entry.storedNextDate ?? '';+ const paid = lastPayment.get(entry.scheduleId) ?? '';+ occurrenceCutoff.set(entry.scheduleId, paid > nextDate ? paid : nextDate);+ }+ }+ const withinCutoff = (entry: ScheduleTemplateTarget, dates: string[]) => {+ const cutoff = occurrenceCutoff.get(entry.scheduleId);+ return cutoff === undefined ? dates : dates.filter(d => d <= cutoff);+ };++ // next_date only advances once its date has passed, so a payment made+ // early leaves it in place. A linked payment already in the carried-over+ // balance (dated before the budget month) settles its nearest occurrence,+ // whether that is a pending one or one in the budget month itself. Only+ // this category's payments count: one booked elsewhere (or not+ // categorized yet) didn't come out of this balance, and the same+ // schedule can be linked from more than one category.+ const { data: linkedAnywhereBeforeWindow } = await aqlQuery(+ q('transactions')+ .filter({+ schedule: { $oneof: reservedEntries.map(entry => entry.scheduleId) },+ 'account.offbudget': false,+ date: [+ {+ $gte: `${monthUtils.subMonths(windowStart, LINKED_PAYMENT_SEARCH_MONTHS)}-01`,+ },+ { $lt: windowStart },+ ],+ })+ .select(['date', 'schedule', 'category']),+ );+ const linkedBeforeWindow = linkedAnywhereBeforeWindow.filter(+ transaction => transaction.category === category.id,+ );+ // When budgeting the current or a past month, part (or all) of the+ // budget month has already happened. For that part, the category needs+ // whichever is larger: the occurrences due by today, or what was+ // actually spent by today (linked or not). An unlinked transaction can't+ // be told apart from a payment of the schedule, so a bill paid by hand+ // isn't counted twice; a bill that came in higher than scheduled counts+ // at its real amount; one that came in lower still reserves the+ // scheduled amount, since the rest may yet be due. A linked payment marks+ // one of its schedule's occurrences this month as elapsed even if it is+ // due after today, so an early payment isn't counted twice either. An+ // occurrence a payment before the budget month settled is skipped+ // outright: that money is already out of the carried-over balance.+ const tomorrow = monthUtils.addDays(today, 1);+ const budgetMonthEnd = monthUtils.firstDayOfMonth(+ monthUtils.addMonths(current_month, 1),+ );+ const postedEnd = tomorrow < budgetMonthEnd ? tomorrow : budgetMonthEnd;+ const sign = category.is_income ? 1 : -1;++ let postedTransactions: PostedTransaction[] = [];+ if (!isBudgetingAhead) {+ ({ data: postedTransactions } = await aqlQuery(+ q('transactions')+ .filter({+ category: category.id,+ 'account.offbudget': false,+ date: [{ $gte: windowStart }, { $lt: postedEnd }],+ })+ .select(['amount', 'date', 'schedule']),+ ));+ }++ // Every range each schedule's occurrences are needed over below: the+ // forecast window, its pending occurrences, and the search around any+ // linked payments.+ const linkedSchedules = new Set(+ [...linkedAnywhereBeforeWindow, ...postedTransactions].map(+ transaction => transaction.schedule,+ ),+ );+ const lookups = new Map<ScheduleTemplateTarget, OccurrencesBetween>();+ for (const entry of reservedEntries) {+ const ranges: Array<[string, string]> = [[windowStart, windowEnd]];+ if (isBudgetingAhead) {+ ranges.push([currentMonthStart, windowStart]);+ }+ if (linkedSchedules.has(entry.scheduleId)) {+ ranges.push([+ linkedSearchStart(windowStart),+ linkedSearchEnd(budgetMonthEnd),+ ]);+ if (isBudgetingAhead) {+ ranges.push([+ linkedSearchStart(currentMonthStart),+ linkedSearchEnd(windowStart),+ ]);+ }+ }+ lookups.set(entry, occurrenceLookup(entry, ranges));+ }++ // When budgeting ahead (current_month after the real current month), the+ // carried-over balance still holds money for occurrences due between now+ // and the window that haven't come out of this category yet. Count those+ // against month 0 so that money isn't treated as free. That's every+ // occurrence from next_date on, and any before it whose linked payment+ // sits outside this category (not categorized yet, say): next_date moves+ // past an occurrence once any linked payment exists. One next_date moved+ // past with no payment at all was skipped. Occurrences missed before the+ // real current month are ignored, so a long-stale next_date can't pile up.+ if (isBudgetingAhead) {+ for (const entry of reservedEntries) {+ const occurrencesBetween = lookups.get(entry);+ const paidAnywhere = settledOccurrences(+ entry,+ linkedAnywhereBeforeWindow,+ currentMonthStart,+ windowStart,+ occurrencesBetween,);- if (intervalMonths === 0) intervalMonths = 1;- return schedule.target / intervalMonths;- case 'daily':- prevDate = monthUtils.subDays(- schedule.next_date_string,- schedule.target_interval,+ const settledHere = settledOccurrences(+ entry,+ linkedBeforeWindow,+ currentMonthStart,+ windowStart,+ occurrencesBetween,);- intervalMonths = monthUtils.differenceInCalendarMonths(- schedule.next_date_string,- prevDate,+ const pending = withinCutoff(+ entry,+ occurrencesBetween(currentMonthStart, windowStart),+ ).filter(+ date =>+ !settledHere.has(date) &&+ ((entry.storedNextDate && date >= entry.storedNextDate) ||+ paidAnywhere.has(date)),);- if (intervalMonths === 0) intervalMonths = 1;- return schedule.target / intervalMonths;- default:- // default to same math as monthly for now for non-reoccuring- return schedule.target / schedule.target_interval;+ monthlyOutflow[0] += pending.length * entry.perOccurrenceAmount;+ }+ }++ let dueByToday = 0;+ for (const entry of smoothEntries) {+ const occurrencesBetween = lookups.get(entry);+ const occurrences = withinCutoff(+ entry,+ occurrencesBetween(windowStart, windowEnd),+ );+ const settledEarly = settledOccurrences(+ entry,+ linkedBeforeWindow,+ windowStart,+ budgetMonthEnd,+ occurrencesBetween,+ );+ const paidThisMonth = isBudgetingAhead+ ? 0+ : [+ ...settledOccurrences(+ entry,+ postedTransactions,+ windowStart,+ budgetMonthEnd,+ occurrencesBetween,+ ),+ ].filter(date => !settledEarly.has(date)).length;+ let indexInBudgetMonth = 0;+ for (const occurrenceDate of occurrences) {+ if (settledEarly.has(occurrenceDate)) continue;+ const monthIndex = monthsBetween(current_month, occurrenceDate);+ const isElapsed =+ !isBudgetingAhead &&+ monthIndex === 0 &&+ (occurrenceDate < postedEnd || indexInBudgetMonth < paidThisMonth);+ if (monthIndex === 0) indexInBudgetMonth++;+ if (isElapsed) {+ dueByToday += entry.perOccurrenceAmount;+ } else if (monthIndex >= 0 && monthIndex < FORECAST_MONTHS) {+ monthlyOutflow[monthIndex] += entry.perOccurrenceAmount;+ }+ }+ }++ if (!isBudgetingAhead) {+ const spentByToday = postedTransactions+ .filter(transaction => !fullScheduleIds.includes(transaction.schedule))+ .reduce((sum, transaction) => sum + sign * transaction.amount, 0);+ monthlyOutflow[0] += Math.max(dueByToday, spentByToday);+ }++ // Unlinked transactions not covered above count at their own month.+ // Budgeting ahead, that's all of them from the budget month on. Otherwise+ // only future-dated ones count: when re-running a past month, spending+ // posted since then belongs to those later months' own budgets, and+ // counting it here would fund it twice.+ const unlinkedStart = isBudgetingAhead ? windowStart : tomorrow;+ const { data: unlinkedTransactions } = await aqlQuery(+ q('transactions')+ .filter({+ category: category.id,+ schedule: null,+ 'account.offbudget': false,+ date: [{ $gte: unlinkedStart }, { $lt: windowEnd }],+ })+ .select(['amount', 'date']),+ );++ for (const transaction of unlinkedTransactions) {+ const monthIndex = monthsBetween(current_month, transaction.date);+ if (monthIndex >= 0 && monthIndex < FORECAST_MONTHS) {+ monthlyOutflow[monthIndex] += sign * transaction.amount;+ }}++ return monthlyOutflow;}-function getSinkingBaseContributionTotal(t: ScheduleTemplateTarget[]) {- let total = 0;- for (const schedule of t) total += getMonthlyBaseContribution(schedule);- return total;+const DAYS_PER_YEAR = 365.25;++// What a schedule costs a month in the long run; the forecast's steady+// rate is the sum of these. Daily and weekly schedules recur every fixed+// number of days. Monthly and yearly ones count their occurrences over+// whole months, twelve times the interval long: twelve cycles of a monthly+// schedule or one of a yearly one, however the dates fall, so day-of-month+// and weekday patterns (the 1st and 15th, the last Friday) count in full.+// The count starts the month after the next occurrence, so a schedule that+// hasn't started yet still counts at its full rate.+function getMonthlyRate(entry: ScheduleTemplateTarget) {+ if (!entry.repeat || entry.completed) return 0;+ const interval = entry.target_interval;+ switch (entry.target_frequency) {+ case 'daily':+ return (entry.perOccurrenceAmount * DAYS_PER_YEAR) / 12 / interval;+ case 'weekly':+ return (entry.perOccurrenceAmount * DAYS_PER_YEAR) / 7 / 12 / interval;+ default: {+ const months = 12 * interval;+ const from = monthUtils.addMonths(entry.next_date_string, 1);+ const occurrences = getOccurrencesBetween(+ entry.dateConditions,+ `${from}-01`,+ `${monthUtils.addMonths(from, months)}-01`,+ ).length;+ return (entry.perOccurrenceAmount * occurrences) / months;+ }+ }}-function getSinkingTotal(t: ScheduleTemplateTarget[]) {- //sum the total of all upcoming schedules+// Pure, synchronous: given a starting balance, a projected monthly-outflow+// array (an entry can be negative — an unlinked inflow transaction offsets+// that month's need) and the steady rate, returns this month's whole-cent+// contribution, and the last month of the catch-up (see below).+//+// The answer is the smallest of two kinds of plan, each of which keeps+// the projected balance non-negative across the whole window.+//+// Using up a surplus: the required balance is the smallest starting+// balance from which contributing the steady rate every month never lets+// the projected balance go negative. Anything above it is used up before+// anything new is asked for: the steady rate less the surplus, never below+// zero. Nothing is ever taken back out of the category; the user can move+// a surplus elsewhere by hand.+//+// Catching up: a constant contribution c through some month k, then the+// steady rate. Each month i's balance is affine in c:+// balance[i] = startingBalance + (i + 1) * c - cumsum[i]+// so c covers months 0..k when c >= (cumsum[i] - startingBalance) / (i + 1)+// for each i <= k, and leaves the steady rate enough from then on when+// balance[k] is at least what the rest of the window needs at that rate.+// The catch-up ends in a month whose bills reach the steady rate: that's+// what the money is being saved for. Ending it in a quieter month just+// puts off saving and then asks for the steady rate all at once. Money+// already saved toward that month counts toward it, so a catch-up already+// under way carries on at the same pace.+function solveForecast(+ startingBalance: number,+ monthlyOutflow: number[],+ steadyRate: number,+): { contribution: number; catchUpEnd: number } {+ const months = monthlyOutflow.length;+ const cumsum: number[] = [];let total = 0;- for (const schedule of t) {- total += schedule.target;+ for (const outflow of monthlyOutflow) {+ total += outflow;+ cumsum.push(total);}- return total;+ // How far the bills through month i run ahead of the steady rate.+ const ahead = cumsum.map((sum, i) => sum - steadyRate * (i + 1));+ const requiredBalance = Math.max(0, ...ahead);++ const surplus = startingBalance - requiredBalance;+ const best = {+ contribution: surplus > 0 ? Math.max(0, steadyRate - surplus) : Infinity,+ catchUpEnd: 0,+ };++ // The balance the steady rate needs at the end of month i to cover+ // every month after it.+ const neededAfter = new Array<number>(months);+ let laterAhead = -Infinity;+ for (let i = months - 1; i >= 0; i--) {+ neededAfter[i] = Math.max(0, laterAhead - ahead[i]);+ laterAhead = Math.max(laterAhead, ahead[i]);+ }++ const fallback = { contribution: Infinity, catchUpEnd: 0 };+ let coversSoFar = 0;+ for (let k = 0; k < months; k++) {+ coversSoFar = Math.max(+ coversSoFar,+ Math.ceil((cumsum[k] - startingBalance) / (k + 1)),+ );+ const contribution = Math.max(+ coversSoFar,+ Math.ceil((cumsum[k] + neededAfter[k] - startingBalance) / (k + 1)),+ );+ const option = monthlyOutflow[k] >= steadyRate ? best : fallback;+ if (contribution < option.contribution) {+ option.contribution = contribution;+ option.catchUpEnd = k;+ }+ }+ return best.contribution < Infinity ? best : fallback;+}++export function solveMonthlyContribution(+ startingBalance: number,+ monthlyOutflow: number[],+ steadyRate: number,+): number {+ return solveForecast(startingBalance, monthlyOutflow, steadyRate)+ .contribution;}-export async function runSchedule(+export async function runScheduleForecast(template_lines: Template[],current_month: string,balance: number,- remainder: number,- last_month_balance: number,to_budget: number,- errors: string[],category: CategoryEntity,-) {+): Promise<{+ to_budget: number;+ perScheduleMonthly: Map<ScheduleTemplate, number>;+}> {const scheduleTemplates = template_lines.filter(t => t.type === 'schedule');-const t = await createScheduleList(scheduleTemplates,current_month,category,);- errors = errors.concat(t.errors);-- const isPayMonthOf = c =>- c.full ||- ((c.target_frequency === 'monthly' || !c.target_frequency) &&- c.target_interval === 1 &&- c.num_months === 0) ||- (c.target_frequency === 'weekly' && c.target_interval <= 4) ||- (c.target_frequency === 'daily' && c.target_interval <= 31) ||- isTrackingBudget();-- // A schedule only behaves "sub-monthly" when it recurs more often than- // monthly — the same weekly/daily caps `isPayMonthOf` uses. A "repeat every- // 360 days" schedule is daily in shape but yearly in effect: letting it- // count here wrongly switches the category to the steady-accrual shortcut,- // which ignores both the deadline and what has already been saved (#6644).- function isSubMonthly(schedule: ScheduleTemplateTarget) {- return (- (schedule.target_frequency === 'weekly' &&- schedule.target_interval <= 4) ||- (schedule.target_frequency === 'daily' && schedule.target_interval <= 31)- );- }- const t_payMonthOf = t.t.filter(isPayMonthOf);- const t_sinking = t.t- .filter(c => !isPayMonthOf(c))- .sort((a, b) => a.next_date_string.localeCompare(b.next_date_string));- const numSubMonthly = t.t.filter(isSubMonthly).length;- const totalPayMonthOf = getPayMonthOfTotal(t_payMonthOf);- const totalSinking = getSinkingTotal(t_sinking);- const totalSinkingBaseContribution =- getSinkingBaseContributionTotal(t_sinking);- const lastMonthGoal = await getSheetValue(- monthUtils.sheetForMonth(monthUtils.subMonths(current_month, 1)),- `goal-${category.id}`,+ // A tracking budget doesn't carry a category's leftover into the next+ // month, so nothing can be saved ahead for a bill: every schedule is+ // budgeted like a full-flag one, in the month it's due.+ const isTracking = isTrackingBudget();+ // Past-due and completed schedules only matter to the forecast: it+ // reserves the past-due ones still unpaid out of the carried-over+ // balance, and a schedule that completed this month still has its+ // payment in this month's spending.+ const fullEntries = t.t.filter(+ c => (isTracking || c.template.full) && !c.isPastDue && !c.completed,);+ // A completed full-flag schedule has nothing left to budget in full, but+ // its payment this month still has to be covered, so it rides the+ // forecast like a completed smooth one.+ const smoothEntries = isTracking+ ? []+ : t.t.filter(c => !c.template.full || c.completed);- // check and see if we should budget the full amount becaue the previous schedules- // haven't been paid yet, or if we can use the leftover balance for this month- // First option: check if the previous month doesn't have its monthly schedules paid yet- // Second option: check if the previous month needed less than this month and hasn't paid yet- // Accumulate per-schedule contributions, keyed by the source template, so- // callers can attribute the batched to_budget back to individual schedule- // templates for UI projections.const perScheduleMonthly = new Map<ScheduleTemplate, number>();- const addContribution = (template: ScheduleTemplate, amount: number) => {+ // Full-flag schedules are budgeted in full only when due this month,+ // never smoothed and never budgeted ahead of time.+ const fullContribution = fullEntries.reduce((sum, c) => {+ const contribution = c.num_months === 0 ? c.target : 0;perScheduleMonthly.set(- template,- (perScheduleMonthly.get(template) ?? 0) + amount,+ c.template,+ (perScheduleMonthly.get(c.template) ?? 0) + contribution,);- };+ return sum + contribution;+ }, 0);- if (- balance >= totalSinking + totalPayMonthOf ||- (lastMonthGoal < totalSinking + totalPayMonthOf &&- lastMonthGoal !== 0 &&- balance >= lastMonthGoal &&- numSubMonthly > 0)- ) {- to_budget += Math.round(totalPayMonthOf + totalSinkingBaseContribution);- for (const c of t_payMonthOf) {- if (c.num_months === 0) {- addContribution(c.template, c.target);- }- }- for (const c of t_sinking) {- addContribution(c.template, getMonthlyBaseContribution(c));- }- } else {- const { total: totalSinkingContribution, perSchedule: sinkingPerSchedule } =- getSinkingContributionBreakdown(t_sinking, remainder, last_month_balance);- if (t_sinking.length === 0) {- to_budget +=- Math.round(totalPayMonthOf + totalSinkingContribution) -- last_month_balance;- } else {- to_budget += Math.round(totalPayMonthOf + totalSinkingContribution);- }- for (const c of t_payMonthOf) {- if (c.num_months === 0) {- addContribution(c.template, c.target);- }- }- for (const [template, amount] of sinkingPerSchedule) {- addContribution(template, amount);- }+ if (smoothEntries.length === 0) {+ return {+ to_budget: to_budget + fullContribution,+ perScheduleMonthly,+ };}- return { to_budget, errors, remainder, perScheduleMonthly };++ const monthlyOutflow = await buildMonthlyOutflow(+ smoothEntries,+ current_month,+ category,+ fullEntries,+ );+ const steadyRate = Math.max(+ 0,+ Math.ceil(smoothEntries.reduce((s, c) => s + getMonthlyRate(c), 0)),+ );+ // Full-flag bills are paid from fullContribution, which is added on top,+ // so they don't draw on the balance the forecast starts from.+ const { contribution: candidate, catchUpEnd } = solveForecast(+ balance,+ monthlyOutflow,+ steadyRate,+ );++ // Split the single smoothed candidate back out across the smooth+ // schedules that share this category. Each starts from its own monthly+ // rate. A past-due or completed schedule has no rate going forward, so it+ // only shares when nothing else in the category is left to take the+ // amount.+ const upcomingEntries = smoothEntries.filter(+ c => !c.isPastDue && !c.completed,+ );+ const splitEntries =+ upcomingEntries.length > 0 ? upcomingEntries : smoothEntries;+ const weights = splitEntries.map(getMonthlyRate);+ const totalMonthlyWeight = weights.reduce((s, weight) => s + weight, 0);++ // A catch-up above the steady rate goes to the schedules that are behind:+ // each one's shortfall is what falls due through the catch-up beyond what+ // its own monthly rate would have put by. A schedule on pace keeps its+ // monthly rate.+ const catchUp = candidate - totalMonthlyWeight;+ const catchUpMonths = catchUpEnd + 1;+ const catchUpEndDay = monthUtils.firstDayOfMonth(+ monthUtils.addMonths(current_month, catchUpMonths),+ );+ const shortfalls = splitEntries.map((entry, i) =>+ catchUp > 0+ ? Math.max(+ 0,+ getOccurrencesBetween(+ entry.dateConditions,+ monthUtils.firstDayOfMonth(current_month),+ catchUpEndDay,+ ).length *+ entry.perOccurrenceAmount -+ weights[i] * catchUpMonths,+ )+ : 0,+ );+ const totalShortfall = shortfalls.reduce((s, shortfall) => s + shortfall, 0);++ for (const [i, entry] of splitEntries.entries()) {+ // When the smooth schedules sharing this category net to a zero total+ // monthly rate (e.g. two schedules with offsetting signs),+ // dividing by zero would yield NaN or +/-Infinity — never valid for a+ // money-typed map. Fall back to an even split across the entries,+ // which is always finite.+ const share =+ totalShortfall > 0+ ? Math.round(weights[i] + (catchUp * shortfalls[i]) / totalShortfall)+ : totalMonthlyWeight === 0+ ? Math.round(candidate / splitEntries.length)+ : Math.round((weights[i] / totalMonthlyWeight) * candidate) || 0;+ perScheduleMonthly.set(+ entry.template,+ (perScheduleMonthly.get(entry.template) ?? 0) + share,+ );+ }++ return {+ to_budget: to_budget + fullContribution + candidate,+ perScheduleMonthly,+ };}diff --git a/packages/loot-core/src/shared/schedules.test.ts b/packages/loot-core/src/shared/schedules.test.tsindex 5bd000a193..8032368e1f 100644--- a/packages/loot-core/src/shared/schedules.test.ts+++ b/packages/loot-core/src/shared/schedules.test.ts@@ -8,6 +8,7 @@ import {getHasTransactionsQuery,getNextDate,getNextDateAfter,+ getOccurrencesBetween,getScheduleOccurrenceMatchStartDate,getStatus,getUpcomingDays,@@ -642,4 +643,263 @@ describe('schedules', () => {expect(isCustomUpcomingLength(undefined)).toBe(false);});});++ describe('getOccurrencesBetween', () => {+ it('returns every monthly occurrence within the range', () => {+ const dateCond = {+ op: 'is' as const,+ field: 'date' as const,+ value: {+ start: '2024-01-15',+ interval: 1,+ frequency: 'monthly' as const,+ patterns: [],+ skipWeekend: false,+ weekendSolveMode: 'before' as const,+ endMode: 'never' as const,+ endOccurrences: 1,+ endDate: '2099-01-01',+ },+ };+ const result = getOccurrencesBetween(+ dateCond,+ '2024-01-01',+ '2024-04-01',+ );+ expect(result).toEqual(['2024-01-15', '2024-02-15', '2024-03-15']);+ });++ it('returns an empty array when the single non-repeating date is outside the range', () => {+ const dateCond = {+ op: 'is' as const,+ field: 'date' as const,+ value: '2023-06-01',+ };+ expect(+ getOccurrencesBetween(dateCond, '2024-01-01', '2024-04-01'),+ ).toEqual([]);+ });++ it('returns the single date when a non-repeating date is inside the range', () => {+ const dateCond = {+ op: 'is' as const,+ field: 'date' as const,+ value: '2024-02-01',+ };+ expect(+ getOccurrencesBetween(dateCond, '2024-01-01', '2024-04-01'),+ ).toEqual(['2024-02-01']);+ });++ it('excludes an occurrence that falls exactly on the exclusive endDay', () => {+ const dateCond = {+ op: 'is' as const,+ field: 'date' as const,+ value: {+ start: '2024-01-15',+ interval: 1,+ frequency: 'monthly' as const,+ patterns: [],+ skipWeekend: false,+ weekendSolveMode: 'before' as const,+ endMode: 'never' as const,+ endOccurrences: 1,+ endDate: '2099-01-01',+ },+ };+ // The next occurrence after 2024-01-15 is 2024-02-15, which is used+ // as the (exclusive) endDay here, so it should not be included.+ const result = getOccurrencesBetween(+ dateCond,+ '2024-01-01',+ '2024-02-15',+ );+ expect(result).toEqual(['2024-01-15']);+ });++ it('returns an empty array without hanging when a recurring schedule ended before the range', () => {+ const dateCond = {+ op: 'isapprox' as const,+ field: 'date' as const,+ value: {+ start: '2016-01-25',+ interval: 1,+ frequency: 'monthly' as const,+ patterns: [],+ skipWeekend: false,+ weekendSolveMode: 'before' as const,+ endMode: 'on_date' as const,+ endOccurrences: 1,+ endDate: '2016-08-25',+ },+ };+ // getNextDate falls back to the schedule's last-ever occurrence+ // (2016-08-25) when asked for the next occurrence after the schedule+ // has ended. getOccurrencesBetween must recognize that stale fallback+ // date is behind the search cursor and stop, rather than looping+ // forever re-requesting the same date.+ const result = getOccurrencesBetween(+ dateCond,+ '2016-08-26',+ '2026-01-01',+ );+ expect(result).toEqual([]);+ });++ it('does not truncate occurrences when weekendSolveMode "before" shifts a date behind the search cursor', () => {+ // Weekly on Saturday, skipWeekend + weekendSolveMode: 'before' means+ // every occurrence is reported on the Friday before it. Querying with+ // startDay set to a raw Saturday occurrence means getNextDate's+ // adjusted result (the Friday before) lands *behind* the search+ // cursor even though the schedule hasn't ended and more occurrences+ // remain — this must not be mistaken for "the schedule ended".+ const dateCond = {+ op: 'isapprox' as const,+ field: 'date' as const,+ value: {+ start: '2020-12-05', // a Saturday+ interval: 1,+ frequency: 'weekly' as const,+ patterns: [],+ skipWeekend: true,+ weekendSolveMode: 'before' as const,+ endMode: 'never' as const,+ endOccurrences: 1,+ endDate: '2099-01-01',+ },+ };++ const result = getOccurrencesBetween(+ dateCond,+ '2020-12-05',+ '2020-12-26',+ );++ expect(result).toEqual(['2020-12-11', '2020-12-18', '2020-12-25']);+ });++ it('includes a raw occurrence landing exactly on the exclusive endDay when the weekend adjustment shifts it backward into range', () => {+ // Weekly on Saturday, skipWeekend + weekendSolveMode: 'before'.+ // Raw occurrences: 12/5, 12/12, 12/19, 12/26, ...+ // The raw occurrence on 2020-12-26 sits exactly on the (exclusive)+ // endDay, so a naive raw-range query would drop it. But its+ // weekend-adjusted date (2020-12-25, the Friday before) lands inside+ // [startDay, endDay) and must be included.+ const dateCond = {+ op: 'isapprox' as const,+ field: 'date' as const,+ value: {+ start: '2020-12-05',+ interval: 1,+ frequency: 'weekly' as const,+ patterns: [],+ skipWeekend: true,+ weekendSolveMode: 'before' as const,+ endMode: 'never' as const,+ endOccurrences: 1,+ endDate: '2099-01-01',+ },+ };++ const result = getOccurrencesBetween(+ dateCond,+ '2020-12-20',+ '2020-12-26',+ );++ expect(result).toEqual(['2020-12-25']);+ });++ it('excludes a raw occurrence landing exactly on startDay when the weekend adjustment shifts it backward out of range', () => {+ // Same schedule as above. The raw occurrence on 2020-12-19 sits+ // exactly on startDay, so a naive raw-range query would keep it. But+ // its weekend-adjusted date (2020-12-18, the Friday before) lands+ // before startDay and must be excluded.+ const dateCond = {+ op: 'isapprox' as const,+ field: 'date' as const,+ value: {+ start: '2020-12-05',+ interval: 1,+ frequency: 'weekly' as const,+ patterns: [],+ skipWeekend: true,+ weekendSolveMode: 'before' as const,+ endMode: 'never' as const,+ endOccurrences: 1,+ endDate: '2099-01-01',+ },+ };++ const result = getOccurrencesBetween(+ dateCond,+ '2020-12-19',+ '2020-12-26',+ );++ expect(result).toEqual(['2020-12-25']);+ });++ it('includes a raw occurrence landing before startDay when the weekend adjustment shifts it forward into range', () => {+ // Weekly on Saturday, skipWeekend + weekendSolveMode: 'after'.+ // Raw occurrences: 12/5, 12/12, 12/19, 12/26, ...+ // The raw occurrence on 2020-12-05 sits 2 days before startDay, so a+ // naive raw-range query would drop it. But its weekend-adjusted date+ // (2020-12-07, the Monday after) lands exactly on startDay and must+ // be included.+ const dateCond = {+ op: 'isapprox' as const,+ field: 'date' as const,+ value: {+ start: '2020-12-05',+ interval: 1,+ frequency: 'weekly' as const,+ patterns: [],+ skipWeekend: true,+ weekendSolveMode: 'after' as const,+ endMode: 'never' as const,+ endOccurrences: 1,+ endDate: '2099-01-01',+ },+ };++ const result = getOccurrencesBetween(+ dateCond,+ '2020-12-07',+ '2020-12-12',+ );++ expect(result).toEqual(['2020-12-07']);+ });++ it('excludes a raw occurrence landing before endDay when the weekend adjustment shifts it forward out of range', () => {+ // Same schedule as above. The raw occurrence on 2020-12-12 sits+ // before endDay, so a naive raw-range query would keep it. But its+ // weekend-adjusted date (2020-12-14, the Monday after) lands exactly+ // on the exclusive endDay and must be excluded.+ const dateCond = {+ op: 'isapprox' as const,+ field: 'date' as const,+ value: {+ start: '2020-12-05',+ interval: 1,+ frequency: 'weekly' as const,+ patterns: [],+ skipWeekend: true,+ weekendSolveMode: 'after' as const,+ endMode: 'never' as const,+ endOccurrences: 1,+ endDate: '2099-01-01',+ },+ };++ const result = getOccurrencesBetween(+ dateCond,+ '2020-12-05',+ '2020-12-14',+ );++ expect(result).toEqual(['2020-12-07']);+ });+ });});diff --git a/packages/loot-core/src/shared/schedules.ts b/packages/loot-core/src/shared/schedules.tsindex b83cb4b956..d40c2288da 100644--- a/packages/loot-core/src/shared/schedules.ts+++ b/packages/loot-core/src/shared/schedules.ts@@ -419,6 +419,89 @@ export function scheduleIsRecurring(dateCond: Condition | null) {return value.type === 'recur';}+// Two independent effects can put a raw occurrence "in reach" of+// [startDay, endDay) even though its raw timestamp falls outside the exact,+// unpadded window — so the raw-date query below must be padded on both ends+// to compensate for both:+// 1. Weekend adjustment (getDateWithSkippedWeekend) shifts a raw+// occurrence by at most 2 days (Saturday -> Monday for 'after',+// Sunday -> Friday for 'before').+// 2. recurConfigToRSchedule hardcodes `byHourOfDay: [12]`, so every raw+// occurrence is timestamped at *noon*, while queryStart/queryEnd below+// are computed with `d.startOfDay` (*midnight*). A raw occurrence+// dated exactly on endDay therefore has a timestamp (noon) that is+// *after* an unpadded, midnight-aligned queryEnd, and would be missed+// by the range query even before any weekend shift is considered.+// Combined, the minimum integer number of days needed is 3 (2 days of+// weekend shift, plus rounding the extra half-day from the noon offset up+// to a full day) — pad by exactly that much.+const WEEKEND_SHIFT_PAD_DAYS = 3;++// Same output as monthUtils.dayFromDate for a Date, without date-fns+// format: over a multi-year window a daily schedule has thousands of+// occurrences, and formatting them dominated the cost of this function.+function formatOccurrenceDay(date: Date): string {+ const year = String(date.getFullYear()).padStart(4, '0');+ const month = String(date.getMonth() + 1).padStart(2, '0');+ const day = String(date.getDate()).padStart(2, '0');+ return `${year}-${month}-${day}`;+}++export function getOccurrencesBetween(+ dateCond,+ startDay: string,+ endDay: string,+): string[] {+ const cond = new Condition(dateCond.op, 'date', dateCond.value, null);+ const value = cond.getValue();++ if (value.type !== 'recur') {+ const singleDate =+ typeof dateCond.value === 'string' ? dateCond.value : null;+ if (singleDate && singleDate >= startDay && singleDate < endDay) {+ return [singleDate];+ }+ return [];+ }++ // Build the recurrence schedule once — parsing a recurrence rule into an+ // RSchedule is the dominant cost for sub-monthly schedules over a+ // multi-year window when done per-occurrence (see task-6-brief.md for the+ // measured numbers). Pull the whole padded range in a single pass instead+ // of repeatedly probing one occurrence at a time.+ const schedule = value.schedule;++ const queryStart = d.startOfDay(+ monthUtils.parseDate(monthUtils.addDays(startDay, -WEEKEND_SHIFT_PAD_DAYS)),+ );+ const queryEnd = d.startOfDay(+ monthUtils.parseDate(monthUtils.addDays(endDay, WEEKEND_SHIFT_PAD_DAYS)),+ );++ const rawDates = schedule+ .occurrences({ start: queryStart, end: queryEnd })+ .toArray()+ .map(occurrence => formatOccurrenceDay(occurrence.date));++ if (!schedule.data.skipWeekend) {+ return rawDates.filter(dt => dt >= startDay && dt < endDay);+ }++ const dates: string[] = [];+ for (const rawDate of rawDates) {+ const adjustedDate = formatOccurrenceDay(+ getDateWithSkippedWeekend(+ monthUtils.parseDate(rawDate),+ schedule.data.weekendSolve,+ ),+ );+ if (adjustedDate >= startDay && adjustedDate < endDay) {+ dates.push(adjustedDate);+ }+ }+ return dates;+}+export type ScheduleStatusType = ReturnType<typeof getStatus>;export type ScheduleStatuses = Map<ScheduleEntity['id'], ScheduleStatusType>;@@ -463,32 +546,19 @@ export function computeSchedulePreviewTransactions(const isRecurring = scheduleIsRecurring(dateConditions);const dates = [schedule.next_date];- let day = d.startOfDay(monthUtils.parseDate(schedule.next_date));if (isRecurring) {- while (day <= upcomingPeriodEnd) {- const nextDate = getNextDate(dateConditions, day);-- if (nextDate === null) {- break;- }-- if (- d.startOfDay(monthUtils.parseDate(nextDate)) > upcomingPeriodEnd- ) {- break;- }-- if (dates.includes(nextDate)) {- day = d.startOfDay(- monthUtils.parseDate(monthUtils.addDays(day, 1)),- );- continue;- }-- dates.push(nextDate);- day = d.startOfDay(- monthUtils.parseDate(monthUtils.addDays(nextDate, 1)),- );+ const day = d.startOfDay(monthUtils.parseDate(schedule.next_date));+ // getOccurrencesBetween's range is [startDay, endDay) — endDay+ // exclusive — but upcomingPeriodEnd is meant to be an inclusive+ // boundary (an occurrence landing exactly on it should be included),+ // so pass the day after it.+ const occurrences = getOccurrencesBetween(+ dateConditions,+ monthUtils.dayFromDate(day),+ monthUtils.dayFromDate(monthUtils.addDays(upcomingPeriodEnd, 1)),+ );+ for (const occurrence of occurrences) {+ if (!dates.includes(occurrence)) dates.push(occurrence);}}diff --git a/upcoming-release-notes/schedule-forecast-smoothing.md b/upcoming-release-notes/schedule-forecast-smoothing.mdnew file mode 100644index 0000000000..d34de07107--- /dev/null+++ b/upcoming-release-notes/schedule-forecast-smoothing.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [MikeBishop]+---++Budget schedules using a smarter forecast that stops adding to a category once it holds what its upcoming bills need