A local-first personal finance app
[AI] Add getScheduleDates to the API (#9020)
Andrea89384e0b7b50
diff --git a/packages/api/methods.test.ts b/packages/api/methods.test.tsindex 3aa5929764..e5cba328c0 100644--- a/packages/api/methods.test.ts+++ b/packages/api/methods.test.ts@@ -1224,6 +1224,116 @@ test('Schedules: successfully complete schedules operations', async () => {);});+describe('API schedules: getScheduleDates', () => {+ beforeEach(async () => {+ await api.loadBudget(budgetName);+ });++ // apis: createSchedule, getSchedules, getScheduleDates+ test('expands the date of a stored schedule', async () => {+ const id = await api.createSchedule({+ name: 'rent',+ amount: -120000,+ amountOp: 'is',+ posts_transaction: false,+ date: {+ frequency: 'monthly',+ start: '2024-06-01',+ skipWeekend: true,+ weekendSolveMode: 'after',+ endMode: 'never',+ },+ });+ const [schedule] = (await api.getSchedules()).filter(s => s.id === id);++ expect(+ await api.getScheduleDates(schedule.date, {+ start: '2024-06-01',+ end: '2024-09-30',+ }),+ ).toEqual(['2024-06-03', '2024-07-01', '2024-08-01', '2024-09-02']);+ });++ // apis: createSchedule, getSchedules, getScheduleDates+ test('starts at the next date the app shows and never repeats a date', async () => {+ // Tests run with today pinned to Sunday 2017-01-01. The occurrences on+ // Saturday 31 December and Sunday 1 January both move to Monday 2+ // January, which must be listed once and match the stored next_date.+ const id = await api.createSchedule({+ name: 'daily weekdays',+ amount: -500,+ amountOp: 'is',+ posts_transaction: false,+ date: {+ frequency: 'daily',+ start: '2016-12-31',+ skipWeekend: true,+ weekendSolveMode: 'after',+ endMode: 'never',+ },+ });+ const [schedule] = (await api.getSchedules()).filter(s => s.id === id);++ const dates = await api.getScheduleDates(schedule.date, { count: 3 });+ expect(dates[0]).toEqual(schedule.next_date);+ expect(dates).toEqual(['2017-01-02', '2017-01-03', '2017-01-04']);+ });++ // apis: getScheduleDates+ test('expands a single date', async () => {+ expect(+ await api.getScheduleDates('2024-06-13', {+ start: '2024-06-01',+ end: '2024-06-30',+ }),+ ).toEqual(['2024-06-13']);+ });++ // apis: getScheduleDates+ test('starts from today when no start is given', async () => {+ // Tests run with today pinned to 2017-01-01.+ expect(+ await api.getScheduleDates(+ { frequency: 'yearly', start: '2016-03-01' },+ { count: 1 },+ ),+ ).toEqual(['2017-03-01']);+ });++ // apis: getScheduleDates+ test('rejects invalid requests', async () => {+ const daily = { frequency: 'daily', start: '2024-01-01' } as const;++ await expect(+ api.getScheduleDates(daily, { start: '2024-13-01', count: 1 }),+ ).rejects.toThrow('Invalid start date');+ await expect(+ api.getScheduleDates(daily, { start: '2024-02-01', end: '2024-01-01' }),+ ).rejects.toThrow('is before start');+ await expect(+ api.getScheduleDates(daily, { start: '2024-01-01', count: -1 }),+ ).rejects.toThrow('count must be a non-negative integer');+ await expect(+ api.getScheduleDates(daily, { start: '2024-01-01' }),+ ).rejects.toThrow('needs an `end` date or a `count`');+ await expect(+ api.getScheduleDates(+ { ...daily, endMode: 'after_n_occurrences', endOccurrences: 0 },+ { start: '2024-01-01' },+ ),+ ).rejects.toThrow('endOccurrences must be a positive integer');+ await expect(+ api.getScheduleDates(+ { ...daily, endMode: 'on_date', endDate: 'soon' },+ { start: '2024-01-01' },+ ),+ ).rejects.toThrow('Invalid recurrence end date');+ await expect(+ api.getScheduleDates('06/13/2024', { start: '2024-01-01' }),+ ).rejects.toThrow('Invalid schedule date');+ });+});+// apis: getPreferencestest('Preferences: successfully read synced preferences', async () => {await api.loadBudget(budgetName);diff --git a/packages/api/methods.ts b/packages/api/methods.tsindex 86be6597c0..33b0fd76a0 100644--- a/packages/api/methods.ts+++ b/packages/api/methods.ts@@ -433,6 +433,13 @@ export function getSchedules() {return send('api/schedules-get');}+export function getScheduleDates(+ date: APIScheduleEntity['date'],+ options: { start?: string; end?: string; count?: number } = {},+) {+ return send('api/schedule-dates-get', { date, ...options });+}+export function getIDByName(type: 'accounts' | 'schedules' | 'categories' | 'payees',name: string,diff --git a/packages/api/vite.config.mts b/packages/api/vite.config.mtsindex b25877c0e8..cdedef1b30 100644--- a/packages/api/vite.config.mts+++ b/packages/api/vite.config.mts@@ -43,7 +43,17 @@ export default defineConfig({ssr: {noExternal: true,external: ['better-sqlite3'],- resolve: { conditions: ['api'] },+ resolve: {+ conditions: ['api'],+ // Under vitest, `noExternal` inlines the UMD builds of @rschedule, but+ // the `require()` calls inside them still load native copies, so+ // `@rschedule/standard-date-adapter/setup` registers the date adapter+ // and recurrence rules on a different `@rschedule/core` than the one+ // loot-core uses, and every schedule then advances one millisecond at+ // a time. Resolving the ES builds keeps a single instance. The+ // production bundle is unaffected, as Rollup merges the copies.+ ...(process.env.VITEST ? { mainFields: ['module', 'main'] } : {}),+ },},build: {ssr: true,diff --git a/packages/docs/docs/api/reference.md b/packages/docs/docs/api/reference.mdindex 64c1ab8ee0..47ef90c91c 100644--- a/packages/docs/docs/api/reference.md+++ b/packages/docs/docs/api/reference.md@@ -84,7 +84,8 @@ import APIList from './APIList';"getSchedules","createSchedule","updateSchedule",-"deleteSchedule"+"deleteSchedule",+"getScheduleDates"]} /><APIList title="Notes" sections={[@@ -788,6 +789,44 @@ Update fields of a rule. `fields` can specify any field described in [`Schedule`<Method name="deleteSchedule" args={[{ name: 'id', type: 'id' }]} returns="Promise<null>" />+#### `getScheduleDates`++<Method name="getScheduleDates" args={[{ name: 'date', type: 'date | RecurConfig' }, { name: 'options', type: '{ start?: date, end?: date, count?: number }' }]} returns="Promise<date[]>" />++Expands the `date` of a [`Schedule`](#schedule) into the dates it falls on, in ascending order. Pass a schedule's `date` field as returned by `getSchedules`, or any [`RecurConfig`](#recurconfig).++Every recurrence setting is taken into account: `frequency`, `interval`, `patterns` (including the last day or the last weekday of the month), `endMode` and, when `skipWeekend` is set, the move to the Friday before or the Monday after the weekend (`weekendSolveMode`).++- `start`: first date to include. Defaults to today.+- `end`: last date to include.+- `count`: maximum number of dates to return.++The window applies to the dates after the weekend move, so the result matches the dates Actual shows for the schedule. A date that several occurrences move onto (a daily schedule's Saturday and Sunday both landing on Monday) is listed once, and `count` counts distinct dates. A recurrence that never ends needs an `end` or a `count`.++```js+const [rent] = await api.getSchedules();++// Every date the schedule falls on in 2025+await api.getScheduleDates(rent.date, {+ start: '2025-01-01',+ end: '2025-12-31',+});++// The next three dates from today+await api.getScheduleDates(rent.date, { count: 3 });++// The same helper works on a recurrence that is not saved yet+await api.getScheduleDates(+ {+ frequency: 'monthly',+ start: '2025-01-01',+ patterns: [{ type: 'FR', value: -1 }],+ },+ { start: '2025-01-01', count: 2 },+);+// ['2025-01-31', '2025-02-28']+```+## NotesNotes can be attached to any entity (categories, budget months, etc.) by ID. They are also used to define budget templates and savings goals (e.g. `#template 250`, `#goal 1000`).diff --git a/packages/loot-core/src/server/api.ts b/packages/loot-core/src/server/api.tsindex 00215737ec..8939eae493 100644--- a/packages/loot-core/src/server/api.ts+++ b/packages/loot-core/src/server/api.ts@@ -21,6 +21,7 @@ import type { Handlers } from '#types/handlers';import type {AccountEntity,CategoryGroupEntity,+ RecurConfig,ScheduleEntity,} from '#types/models';import type { ServerHandlers } from '#types/server-handlers';@@ -47,6 +48,7 @@ import * as db from './db';import { APIError, withErrorCode } from './errors';import { runMutator } from './mutators';import * as prefs from './prefs';+import { getScheduleDates } from './schedules/occurrences';import * as sheet from './sheet';import { batchMessages, setSyncingMode } from './sync';@@ -120,6 +122,41 @@ async function validateExpenseCategory(debug, id) {}}+function validateDay(name: string, value: string) {+ if (typeof value !== 'string' || !monthUtils.isValidYearMonthDay(value)) {+ throw APIError(`Invalid ${name}, use YYYY-MM-DD: ${value}`);+ }+}++function validateScheduleDate(date: RecurConfig | string) {+ if (typeof date === 'string') {+ validateDay('schedule date', date);+ return;+ }+ if (date == null || typeof date !== 'object') {+ throw APIError('date must be a YYYY-MM-DD string or a RecurConfig');+ }++ validateDay('recurrence start date', date.start);+ if (+ date.interval != null &&+ !(Number.isInteger(date.interval) && date.interval > 0)+ ) {+ throw APIError(`interval must be a positive integer: ${date.interval}`);+ }+ if (date.endMode === 'on_date') {+ validateDay('recurrence end date', date.endDate);+ }+ if (+ date.endMode === 'after_n_occurrences' &&+ !(Number.isInteger(date.endOccurrences) && date.endOccurrences > 0)+ ) {+ throw APIError(+ `endOccurrences must be a positive integer: ${date.endOccurrences}`,+ );+ }+}+function checkFileOpen() {if (!(prefs.getPrefs() || {}).id) {throw APIError('No budget file is open');@@ -932,6 +969,31 @@ handlers['api/schedules-get'] = async function () {return schedules.map(schedule => scheduleModel.toExternal(schedule));};+handlers['api/schedule-dates-get'] = async function ({+ date,+ start = monthUtils.currentDay(),+ end,+ count,+}) {+ validateScheduleDate(date);+ validateDay('start date', start);+ if (end != null) {+ validateDay('end date', end);+ if (end < start) {+ throw APIError(`end (${end}) is before start (${start})`);+ }+ }+ if (count != null && !(Number.isInteger(count) && count >= 0)) {+ throw APIError(`count must be a non-negative integer: ${count}`);+ }++ try {+ return getScheduleDates(date, { start, end, count });+ } catch (error) {+ throw APIError(`Cannot expand schedule date: ${error.message}`);+ }+};+handlers['api/schedule-create'] = withMutation(async function (schedule: Omit<APIScheduleEntity, 'id'>,) {diff --git a/packages/loot-core/src/server/schedules/occurrences.test.ts b/packages/loot-core/src/server/schedules/occurrences.test.tsnew file mode 100644index 0000000000..da7d7ecfd9--- /dev/null+++ b/packages/loot-core/src/server/schedules/occurrences.test.ts@@ -0,0 +1,300 @@+import { describe, expect, it } from 'vitest';++import type { RecurConfig } from '#types/models';++import { getScheduleDates } from './occurrences';++describe('getScheduleDates', () => {+ describe('single dates', () => {+ it('returns the date when it falls inside the window', () => {+ expect(+ getScheduleDates('2024-01-15', {+ start: '2024-01-01',+ end: '2024-01-31',+ }),+ ).toEqual(['2024-01-15']);+ });++ it('returns nothing when the date falls outside the window', () => {+ expect(+ getScheduleDates('2024-02-15', {+ start: '2024-01-01',+ end: '2024-01-31',+ }),+ ).toEqual([]);+ expect(getScheduleDates('2023-12-31', { start: '2024-01-01' })).toEqual(+ [],+ );+ });+ });++ describe('frequencies and intervals', () => {+ it('expands a daily recurrence with an interval', () => {+ expect(+ getScheduleDates(+ { frequency: 'daily', interval: 3, start: '2024-01-01' },+ { start: '2024-01-01', count: 4 },+ ),+ ).toEqual(['2024-01-01', '2024-01-04', '2024-01-07', '2024-01-10']);+ });++ it('expands a weekly recurrence with an interval', () => {+ expect(+ getScheduleDates(+ { frequency: 'weekly', interval: 2, start: '2024-01-01' },+ { start: '2024-01-01', end: '2024-02-01' },+ ),+ ).toEqual(['2024-01-01', '2024-01-15', '2024-01-29']);+ });++ it('expands a yearly recurrence', () => {+ expect(+ getScheduleDates(+ { frequency: 'yearly', start: '2024-03-15' },+ { start: '2024-01-01', count: 3 },+ ),+ ).toEqual(['2024-03-15', '2025-03-15', '2026-03-15']);+ });+ });++ describe('monthly patterns', () => {+ it('expands several days of the month in date order', () => {+ expect(+ getScheduleDates(+ {+ frequency: 'monthly',+ start: '2024-01-01',+ patterns: [+ { type: 'day', value: 15 },+ { type: 'day', value: 1 },+ ],+ },+ { start: '2024-01-01', end: '2024-02-29' },+ ),+ ).toEqual(['2024-01-01', '2024-01-15', '2024-02-01', '2024-02-15']);+ });++ it('expands the last day of the month, including leap years', () => {+ expect(+ getScheduleDates(+ {+ frequency: 'monthly',+ start: '2024-01-01',+ patterns: [{ type: 'day', value: -1 }],+ },+ { start: '2024-01-01', end: '2024-04-30' },+ ),+ ).toEqual(['2024-01-31', '2024-02-29', '2024-03-31', '2024-04-30']);+ });++ it('expands weekday patterns such as the last Friday and second Monday', () => {+ expect(+ getScheduleDates(+ {+ frequency: 'monthly',+ start: '2024-01-01',+ patterns: [+ { type: 'FR', value: -1 },+ { type: 'MO', value: 2 },+ ],+ },+ { start: '2024-01-01', end: '2024-02-29' },+ ),+ ).toEqual(['2024-01-08', '2024-01-26', '2024-02-12', '2024-02-23']);+ });+ });++ describe('windows and end modes', () => {+ it('starts at the window, not at the start of the recurrence', () => {+ expect(+ getScheduleDates(+ { frequency: 'daily', start: '2024-01-01' },+ { start: '2024-03-01', count: 2 },+ ),+ ).toEqual(['2024-03-01', '2024-03-02']);+ });++ it('never returns dates before the recurrence starts', () => {+ expect(+ getScheduleDates(+ { frequency: 'monthly', start: '2024-01-10' },+ { start: '2023-01-01', count: 1 },+ ),+ ).toEqual(['2024-01-10']);+ });++ it('stops after the configured number of occurrences', () => {+ expect(+ getScheduleDates(+ {+ frequency: 'monthly',+ start: '2024-01-10',+ endMode: 'after_n_occurrences',+ endOccurrences: 3,+ },+ { start: '2024-01-01' },+ ),+ ).toEqual(['2024-01-10', '2024-02-10', '2024-03-10']);+ });++ it('stops at the configured end date', () => {+ expect(+ getScheduleDates(+ {+ frequency: 'weekly',+ start: '2024-01-01',+ endMode: 'on_date',+ endDate: '2024-01-20',+ },+ { start: '2024-01-01' },+ ),+ ).toEqual(['2024-01-01', '2024-01-08', '2024-01-15']);+ });++ it('returns at most `count` dates', () => {+ expect(+ getScheduleDates(+ { frequency: 'daily', start: '2024-01-01' },+ { start: '2024-01-01', end: '2024-12-31', count: 2 },+ ),+ ).toEqual(['2024-01-01', '2024-01-02']);+ });++ it('returns nothing for a count of zero', () => {+ expect(+ getScheduleDates(+ { frequency: 'daily', start: '2024-01-01' },+ { start: '2024-01-01', count: 0 },+ ),+ ).toEqual([]);+ expect(+ getScheduleDates('2024-01-01', { start: '2024-01-01', count: 0 }),+ ).toEqual([]);+ });+ });++ describe('weekend handling', () => {+ // 2024-06-01, 2024-09-01 and 2024-12-01 fall on a weekend.+ const firstOfMonth = {+ frequency: 'monthly',+ start: '2024-06-01',+ skipWeekend: true,+ } satisfies RecurConfig;++ it('moves weekend dates to the following Monday', () => {+ expect(+ getScheduleDates(+ { ...firstOfMonth, weekendSolveMode: 'after' },+ { start: '2024-06-01', end: '2024-12-31' },+ ),+ ).toEqual([+ '2024-06-03',+ '2024-07-01',+ '2024-08-01',+ '2024-09-02',+ '2024-10-01',+ '2024-11-01',+ '2024-12-02',+ ]);+ });++ it('moves weekend dates to the previous Friday', () => {+ expect(+ getScheduleDates(+ { ...firstOfMonth, weekendSolveMode: 'before' },+ { start: '2024-05-01', end: '2024-12-31' },+ ),+ ).toEqual([+ '2024-05-31',+ '2024-07-01',+ '2024-08-01',+ '2024-08-30',+ '2024-10-01',+ '2024-11-01',+ '2024-11-29',+ ]);+ });++ it('applies the window to the moved date, not the original one', () => {+ const before = { ...firstOfMonth, weekendSolveMode: 'before' } as const;+ // Saturday 1 June moves back to Friday 31 May.+ expect(+ getScheduleDates(before, { start: '2024-05-01', end: '2024-05-31' }),+ ).toEqual(['2024-05-31']);+ expect(+ getScheduleDates(before, { start: '2024-06-01', end: '2024-06-30' }),+ ).toEqual([]);++ // Sunday 30 June moves forward to Monday 1 July.+ const after = {+ frequency: 'monthly',+ start: '2024-06-30',+ skipWeekend: true,+ weekendSolveMode: 'after',+ } satisfies RecurConfig;+ expect(+ getScheduleDates(after, { start: '2024-06-01', end: '2024-06-30' }),+ ).toEqual([]);+ expect(+ getScheduleDates(after, { start: '2024-07-01', end: '2024-07-01' }),+ ).toEqual(['2024-07-01']);+ });++ it('lists a date once when several occurrences move onto it', () => {+ // Saturday 1 and Sunday 2 June both move to Monday 3 June.+ const daily = {+ frequency: 'daily',+ start: '2024-06-01',+ skipWeekend: true,+ } satisfies RecurConfig;++ expect(+ getScheduleDates(+ { ...daily, weekendSolveMode: 'after' },+ { start: '2024-06-01', count: 3 },+ ),+ ).toEqual(['2024-06-03', '2024-06-04', '2024-06-05']);+ expect(+ getScheduleDates(+ { ...daily, weekendSolveMode: 'before', start: '2024-05-31' },+ { start: '2024-05-31', end: '2024-06-04' },+ ),+ ).toEqual(['2024-05-31', '2024-06-03', '2024-06-04']);+ });++ it('keeps weekend dates when skipWeekend is off', () => {+ expect(+ getScheduleDates(+ { ...firstOfMonth, skipWeekend: false },+ { start: '2024-06-01', count: 1 },+ ),+ ).toEqual(['2024-06-01']);+ });+ });++ describe('invalid requests', () => {+ it('rejects an open-ended recurrence without an end or a count', () => {+ expect(() =>+ getScheduleDates(+ { frequency: 'daily', start: '2024-01-01' },+ { start: '2024-01-01' },+ ),+ ).toThrow('needs an `end` date or a `count`');+ expect(() =>+ getScheduleDates(+ { frequency: 'daily', start: '2024-01-01', endMode: 'never' },+ { start: '2024-01-01' },+ ),+ ).toThrow('needs an `end` date or a `count`');+ });++ it('rejects skipWeekend without a weekendSolveMode', () => {+ expect(() =>+ getScheduleDates(+ { frequency: 'daily', start: '2024-01-01', skipWeekend: true },+ { start: '2024-01-01', count: 1 },+ ),+ ).toThrow('`weekendSolveMode` is required');+ });+ });+});diff --git a/packages/loot-core/src/server/schedules/occurrences.ts b/packages/loot-core/src/server/schedules/occurrences.tsnew file mode 100644index 0000000000..b86f945eff--- /dev/null+++ b/packages/loot-core/src/server/schedules/occurrences.ts@@ -0,0 +1,64 @@+import * as monthUtils from '#shared/months';+import { getNextDateAfter } from '#shared/schedules';+import type { RecurConfig } from '#types/models';++export type ScheduleDatesOptions = {+ start: string;+ end?: string;+ count?: number;+};++/**+ * Expands a schedule date (a single date or a recurrence) into the dates it+ * falls on, as `YYYY-MM-DD` strings in ascending order.+ *+ * Each date is found with `getNextDateAfter`, the same step the app uses to+ * advance a schedule, so the result matches what the app shows: every+ * recurrence setting is honoured, the window applies to the dates after the+ * weekend move, and a date that several occurrences move onto (a daily+ * schedule's Saturday and Sunday both landing on Monday) is listed once.+ *+ * At least one of `end`, `count`, or an ending recurrence must bound the+ * result; an unbounded request throws.+ */+export function getScheduleDates(+ date: RecurConfig | string,+ { start, end, count }: ScheduleDatesOptions,+): string[] {+ if (count === 0) {+ return [];+ }++ if (typeof date === 'string') {+ return isWithin(date, start, end) ? [date] : [];+ }++ const isOpenEnded = date.endMode == null || date.endMode === 'never';+ if (end == null && count == null && isOpenEnded) {+ throw new Error(+ 'An open-ended recurrence needs an `end` date or a `count` to be expanded',+ );+ }++ if (date.skipWeekend && date.weekendSolveMode == null) {+ throw new Error('`weekendSolveMode` is required when `skipWeekend` is set');+ }++ const dateCond = { op: 'is', field: 'date', value: date };+ const dates: string[] = [];++ let next = getNextDateAfter(dateCond, monthUtils.subDays(start, 1));+ while (next != null && (end == null || next <= end)) {+ dates.push(next);+ if (count != null && dates.length >= count) {+ break;+ }+ next = getNextDateAfter(dateCond, next);+ }++ return dates;+}++function isWithin(day: string, start: string, end: string | undefined) {+ return day >= start && (end == null || day <= end);+}diff --git a/packages/loot-core/src/types/api-handlers.ts b/packages/loot-core/src/types/api-handlers.tsindex 679a8c97b3..9a209e55b4 100644--- a/packages/loot-core/src/types/api-handlers.ts+++ b/packages/loot-core/src/types/api-handlers.ts@@ -304,6 +304,14 @@ export type ApiHandlers = {'api/schedule-delete': (id: string) => Promise<void>;'api/schedules-get': () => Promise<APIScheduleEntity[]>;++ 'api/schedule-dates-get': (arg: {+ date: APIScheduleEntity['date'];+ start?: string;+ end?: string;+ count?: number;+ }) => Promise<string[]>;+'api/get-id-by-name': (arg: {type: string;name: string;diff --git a/upcoming-release-notes/api-get-schedule-dates.md b/upcoming-release-notes/api-get-schedule-dates.mdnew file mode 100644index 0000000000..6c122ecd36--- /dev/null+++ b/upcoming-release-notes/api-get-schedule-dates.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [agigante80]+---++Add `getScheduleDates` to the API to list the dates a schedule falls on