@wickermoney/plugin-sdk 0.1.0-rc.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,158 @@
1
+ # @wickermoney/plugin-sdk
2
+
3
+ The contract between [Wicker Money](https://github.com/WickerMoney/wicker-money)
4
+ and its plugins. The host and every plugin build against this package: it
5
+ defines the plugin manifest and validates it, and it declares the props and
6
+ context a plugin's React components receive.
7
+
8
+ Wicker Money is self-hostable personal finance built as a thin core plus
9
+ installable plugins. Budgets, insights, importers and forecasting are all
10
+ plugins. Full documentation lives at [wickermoney.dev](https://wickermoney.dev).
11
+
12
+ > **Pre-1.0.** `SDK_MAJOR_VERSION` is `0`, so the contract can still change
13
+ > between minor releases. A host refuses any manifest built against a different
14
+ > SDK major version.
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ npm install @wickermoney/plugin-sdk
20
+ # or: pnpm add @wickermoney/plugin-sdk
21
+ ```
22
+
23
+ Browser-side plugin code also needs `react` 19, which the host shares with every
24
+ plugin as a Module Federation singleton.
25
+
26
+ ## Entry points
27
+
28
+ | Import | Use it for | Contents |
29
+ |---|---|---|
30
+ | `@wickermoney/plugin-sdk/runtime` | Plugin UI code (browser) | Types for the React components a plugin exports (`PluginWidgetProps`, `PluginPageProps`, `PluginContext`, ...), and `adoptPluginStyles` |
31
+ | `@wickermoney/plugin-sdk/recurrence` | Anything (browser or Node) | Recurring-item date maths and projections: `occurrences`, `nextOccurrence`, `nextPayday`, `monthlyEquivalent`, `dailyBalances`, `flowTotals` |
32
+ | `@wickermoney/plugin-sdk` | Hosts, tooling, tests (Node) | Everything above, plus the Zod manifest schemas, `parseManifest`, dashboard-range helpers and constants |
33
+
34
+ Import from `/runtime` (and `/recurrence` if you need it) in plugin UI code.
35
+ The package root re-exports the Zod manifest schemas, which add about 85 kB to
36
+ a plugin bundle that never uses them.
37
+
38
+ ## Recurring items
39
+
40
+ `/recurrence` is pure and dependency-free: calendar dates in and out as
41
+ `YYYY-MM-DD`, money as decimal strings (never `number`), and no clock. Work out
42
+ the user's today once, in their time zone, and pass it in. Ranges are
43
+ half-open, like `DashboardRange`: `from` inclusive, `to` exclusive.
44
+
45
+ ```ts
46
+ import { dailyBalances, nextPayday, occurrences } from '@wickermoney/plugin-sdk/recurrence'
47
+
48
+ const rent = {
49
+ frequency: 'monthly',
50
+ seriesStartDate: '2026-01-31', // immutable anchor
51
+ legs: [{ accountId: 'checking', amount: '-1550.0000' }],
52
+ } as const
53
+
54
+ occurrences(rent, '2026-02-01', '2026-04-01') // ['2026-02-28', '2026-03-31']
55
+
56
+ const payday = nextPayday(items, today) // strictly after today, or null
57
+ const series = dailyBalances(items, { checking: '812.4000' }, tomorrow, payday ?? fallback)
58
+ ```
59
+
60
+ Monthly, quarterly and annual items clamp to the end of short months, computed
61
+ from the anchor each time (Jan 31 → Feb 28 → Mar 31). `semimonthly` takes two
62
+ days (`semimonthlyDays`, default `[1, 15]`). An unknown frequency throws rather
63
+ than dropping an item from a forecast.
64
+
65
+ ## A plugin, in brief
66
+
67
+ A plugin is a **manifest** plus a **Module Federation remote** whose exposed
68
+ modules default-export React components.
69
+
70
+ ### Manifest
71
+
72
+ ```ts
73
+ import { parseManifest, SDK_MAJOR_VERSION } from '@wickermoney/plugin-sdk'
74
+
75
+ const result = parseManifest({
76
+ id: 'example.cash-runway', // reverse-domain
77
+ name: 'Cash Runway',
78
+ version: '0.1.0',
79
+ sdkVersion: SDK_MAJOR_VERSION,
80
+ requiredTables: [{ table: 'transactions', access: 'read' }],
81
+ permissions: [],
82
+ remoteEntry: '/plugins/cash-runway/remoteEntry.js',
83
+ contributes: {
84
+ widgets: [
85
+ {
86
+ id: 'runway',
87
+ slot: 'dashboard.secondary', // dashboard.primary | dashboard.secondary | account.detail
88
+ title: 'Cash runway',
89
+ defaultSize: 'md', // sm | md | lg | full
90
+ module: './RunwayWidget',
91
+ },
92
+ ],
93
+ },
94
+ })
95
+
96
+ if ('error' in result) throw new Error(result.error)
97
+ ```
98
+
99
+ `requiredTables` is enforced by PostgreSQL, not only by the app. Each plugin
100
+ runs under its own database role, which is granted exactly the tables its
101
+ manifest lists. A query against any other table is refused.
102
+
103
+ ### Widget
104
+
105
+ ```tsx
106
+ import type { PluginWidgetProps } from '@wickermoney/plugin-sdk/runtime'
107
+
108
+ export default function RunwayWidget({ ctx, size, range }: PluginWidgetProps) {
109
+ // ctx.api is scoped to your plugin and the tables your manifest grants;
110
+ // the host attaches credentials, so the plugin never sees a token.
111
+ // Paths are relative to the API root; don't prefix /api/v1 yourself.
112
+ // ...
113
+ return <p>{ctx.formatMoney('1234.5600')}</p>
114
+ }
115
+ ```
116
+
117
+ Money crosses the contract as a **decimal string**, never a JavaScript
118
+ `number`. Use `ctx.formatMoney` to display it.
119
+
120
+ ## Two rules that fail at runtime, not build time
121
+
122
+ 1. **The remote entry must be an ES module.** The host loads remotes with a
123
+ dynamic `import()`. A remote built as a classic script fails when each widget
124
+ mounts, with *"Cannot use import statement outside a module"*.
125
+ 2. **Inject CSS; don't import it for its side effect.** A remote has no HTML
126
+ document, so the host never requests the stylesheet the bundler emits. Import
127
+ the CSS as text and adopt it instead:
128
+
129
+ ```ts
130
+ import { adoptPluginStyles } from '@wickermoney/plugin-sdk/runtime'
131
+ import css from './widget.css?inline'
132
+
133
+ adoptPluginStyles('example.cash-runway', css)
134
+ ```
135
+
136
+ This is not a style sandbox. Scope your selectors under a class your plugin
137
+ owns.
138
+
139
+ ## Server-side code
140
+
141
+ Only bundled plugins may contribute server endpoints (`contributes.endpoints`).
142
+ The host has no sandbox for third-party server code yet. Third-party plugins are
143
+ UI-only and use core endpoints through `ctx.api`.
144
+
145
+ ## Related
146
+
147
+ - [`@wickermoney/ui-kit`](https://www.npmjs.com/package/@wickermoney/ui-kit):
148
+ the host's components and design tokens, so a plugin looks native.
149
+ - [Writing a plugin](https://github.com/WickerMoney/wicker-money#writing-a-plugin)
150
+ in the main repo README.
151
+ - The bundled plugins in
152
+ [`plugins/`](https://github.com/WickerMoney/wicker-money/tree/main/plugins)
153
+ are working examples.
154
+
155
+ ## License
156
+
157
+ [Apache-2.0](./LICENSE). The Wicker Money application is licensed separately
158
+ (AGPL-3.0); see the [main repository](https://github.com/WickerMoney/wicker-money).
package/dist/index.d.ts CHANGED
@@ -13,4 +13,6 @@ export { adoptPluginStyles } from './runtime.js';
13
13
  export type { PluginApi, PluginContext, PluginModule, PluginPage, PluginPageProps, PluginSession, PluginWidget, PluginWidgetProps, } from './runtime.js';
14
14
  export { RANGE_KEYS, DEFAULT_RANGE_KEY, isRangeKey, rangeLabel, resolveRange, monthsInRange, } from './range.js';
15
15
  export type { DashboardRange, RangeKey } from './range.js';
16
+ export { DEFAULT_SEMIMONTHLY_DAYS, RECURRENCE_FREQUENCIES, dailyBalances, flowTotals, monthlyEquivalent, nextOccurrence, nextPayday, occurrences, } from './recurrence/index.js';
17
+ export type { DailyBalance, FlowTotals, RecurrenceFrequency, RecurrenceSchedule, RecurringItem, RecurringLeg, } from './recurrence/index.js';
16
18
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EACL,WAAW,EACX,gBAAgB,EAChB,iBAAiB,EACjB,WAAW,EACX,iBAAiB,EACjB,iBAAiB,EACjB,YAAY,EACZ,YAAY,EACZ,cAAc,EACd,YAAY,EACZ,QAAQ,EACR,aAAa,EACb,sBAAsB,EACtB,oBAAoB,EACpB,gBAAgB,EAChB,wBAAwB,GACzB,MAAM,qBAAqB,CAAA;AAC5B,YAAY,EACV,aAAa,EACb,mBAAmB,EACnB,gBAAgB,EAChB,UAAU,EACV,cAAc,EACd,UAAU,EACV,kBAAkB,EAClB,UAAU,EACV,UAAU,GACX,MAAM,qBAAqB,CAAA;AAE5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA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AAE,WAAW,GACtF,MAAM,uBAAuB,CAAA;AAC9B,YAAY,EACV,YAAY,EAAE,UAAU,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,aAAa,EAAE,YAAY,GAC/F,MAAM,uBAAuB,CAAA"}
package/dist/index.js CHANGED
@@ -10,4 +10,5 @@
10
10
  export { CORE_TABLES, checkRemoteEntry, remoteEntrySchema, PERMISSIONS, REMOTE_ENTRY_TYPE, SDK_MAJOR_VERSION, WIDGET_SIZES, WIDGET_SLOTS, federationName, isCompatible, pagePath, parseManifest, pageContributionSchema, pluginManifestSchema, tableGrantSchema, widgetContributionSchema, } from './manifest/index.js';
11
11
  export { adoptPluginStyles } from './runtime.js';
12
12
  export { RANGE_KEYS, DEFAULT_RANGE_KEY, isRangeKey, rangeLabel, resolveRange, monthsInRange, } from './range.js';
13
+ export { DEFAULT_SEMIMONTHLY_DAYS, RECURRENCE_FREQUENCIES, dailyBalances, flowTotals, monthlyEquivalent, nextOccurrence, nextPayday, occurrences, } from './recurrence/index.js';
13
14
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EACL,WAAW,EACX,gBAAgB,EAChB,iBAAiB,EACjB,WAAW,EACX,iBAAiB,EACjB,iBAAiB,EACjB,YAAY,EACZ,YAAY,EACZ,cAAc,EACd,YAAY,EACZ,QAAQ,EACR,aAAa,EACb,sBAAsB,EACtB,oBAAoB,EACpB,gBAAgB,EAChB,wBAAwB,GACzB,MAAM,qBAAqB,CAAA;AAa5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAYhD,OAAO,EACL,UAAU,EAAE,iBAAiB,EAAE,UAAU,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,GACnF,MAAM,YAAY,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EACL,WAAW,EACX,gBAAgB,EAChB,iBAAiB,EACjB,WAAW,EACX,iBAAiB,EACjB,iBAAiB,EACjB,YAAY,EACZ,YAAY,EACZ,cAAc,EACd,YAAY,EACZ,QAAQ,EACR,aAAa,EACb,sBAAsB,EACtB,oBAAoB,EACpB,gBAAgB,EAChB,wBAAwB,GACzB,MAAM,qBAAqB,CAAA;AAa5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAYhD,OAAO,EACL,UAAU,EAAE,iBAAiB,EAAE,UAAU,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,GACnF,MAAM,YAAY,CAAA;AAGnB,OAAO,EACL,wBAAwB,EAAE,sBAAsB,EAChD,aAAa,EAAE,UAAU,EAAE,iBAAiB,EAAE,cAAc,EAAE,UAAU,EAAE,WAAW,GACtF,MAAM,uBAAuB,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"CORE_TABLES.d.ts","sourceRoot":"","sources":["../../src/manifest/CORE_TABLES.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,eAAO,MAAM,WAAW,4IAQd,CAAA"}
1
+ {"version":3,"file":"CORE_TABLES.d.ts","sourceRoot":"","sources":["../../src/manifest/CORE_TABLES.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,eAAO,MAAM,WAAW,4IAUd,CAAA"}
@@ -11,6 +11,8 @@ export const CORE_TABLES = [
11
11
  'categories',
12
12
  'category_rules',
13
13
  'category_rule_conditions',
14
+ // Also grants `recurring_item_legs`: an item is its schedule plus its legs,
15
+ // and neither is usable without the other.
14
16
  'recurring_items',
15
17
  ];
16
18
  //# sourceMappingURL=CORE_TABLES.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"CORE_TABLES.js","sourceRoot":"","sources":["../../src/manifest/CORE_TABLES.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,UAAU;IACV,cAAc;IACd,oBAAoB;IACpB,YAAY;IACZ,gBAAgB;IAChB,0BAA0B;IAC1B,iBAAiB;CACT,CAAA"}
1
+ {"version":3,"file":"CORE_TABLES.js","sourceRoot":"","sources":["../../src/manifest/CORE_TABLES.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,UAAU;IACV,cAAc;IACd,oBAAoB;IACpB,YAAY;IACZ,gBAAgB;IAChB,0BAA0B;IAC1B,4EAA4E;IAC5E,2CAA2C;IAC3C,iBAAiB;CACT,CAAA"}
@@ -0,0 +1,81 @@
1
+ /**
2
+ * @module
3
+ * Calendar-date arithmetic on `YYYY-MM-DD` strings. Internal to the SDK.
4
+ *
5
+ * Dates here are calendar days, not instants: there is no time of day and no
6
+ * time zone, so nothing can shift a day across midnight or a DST change. The
7
+ * day number is a count of days since 1970-01-01 computed with `Date.UTC`,
8
+ * which is only ever used as an integer calendar and never read back in local
9
+ * time.
10
+ */
11
+ /**
12
+ * Parses a `YYYY-MM-DD` string into its parts, rejecting impossible dates.
13
+ *
14
+ * `Date.UTC(2026, 1, 30)` silently rolls over to March 2nd, so the parts are
15
+ * checked against the month's real length rather than trusted.
16
+ *
17
+ * @param value - The date string.
18
+ * @param label - What the value is, for the error message.
19
+ * @returns Year, month (1-12) and day.
20
+ * @throws {RangeError} If `value` is not a real calendar date in `YYYY-MM-DD` form.
21
+ */
22
+ export declare function parseDate(value: string, label?: string): {
23
+ year: number;
24
+ month: number;
25
+ day: number;
26
+ };
27
+ /**
28
+ * Converts a `YYYY-MM-DD` string to a day number (days since 1970-01-01).
29
+ *
30
+ * @param value - The date string.
31
+ * @param label - What the value is, for the error message.
32
+ * @returns The day number.
33
+ * @throws {RangeError} If `value` is not a valid date.
34
+ */
35
+ export declare function toDayNumber(value: string, label?: string): number;
36
+ /**
37
+ * Converts a day number back to `YYYY-MM-DD`.
38
+ *
39
+ * @param dayNumber - Days since 1970-01-01.
40
+ * @returns The date string.
41
+ */
42
+ export declare function fromDayNumber(dayNumber: number): string;
43
+ /**
44
+ * Formats date parts as `YYYY-MM-DD`.
45
+ *
46
+ * @param year - Four-digit year.
47
+ * @param month - Month, 1-12.
48
+ * @param day - Day of month.
49
+ * @returns The date string.
50
+ */
51
+ export declare function formatDate(year: number, month: number, day: number): string;
52
+ /**
53
+ * The number of days in a month, accounting for leap years.
54
+ *
55
+ * @param year - Four-digit year.
56
+ * @param month - Month, 1-12.
57
+ * @returns 28 to 31.
58
+ */
59
+ export declare function daysInMonth(year: number, month: number): number;
60
+ /**
61
+ * The date `months` whole months after a year and month, on `day` clamped to
62
+ * that month's last day.
63
+ *
64
+ * @param year - Starting year.
65
+ * @param month - Starting month, 1-12.
66
+ * @param months - Whole months to add; may be zero.
67
+ * @param day - The wanted day of month, 1-31.
68
+ * @returns The clamped date as `YYYY-MM-DD`.
69
+ */
70
+ export declare function clampedMonthDate(year: number, month: number, months: number, day: number): string;
71
+ /**
72
+ * Whole months from one year/month to another (`to - from`), ignoring days.
73
+ *
74
+ * @param fromYear - Year of the earlier month.
75
+ * @param fromMonth - Earlier month, 1-12.
76
+ * @param toYear - Year of the later month.
77
+ * @param toMonth - Later month, 1-12.
78
+ * @returns The month difference; negative when `to` is earlier.
79
+ */
80
+ export declare function monthsBetween(fromYear: number, fromMonth: number, toYear: number, toMonth: number): number;
81
+ //# sourceMappingURL=calendar.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calendar.d.ts","sourceRoot":"","sources":["../../src/recurrence/calendar.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAKH;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,SAAS,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAUrG;AAED;;;;;;;GAOG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,SAAS,GAAG,MAAM,CAGjE;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAGvD;AAED;;;;;;;GAOG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAE3E;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAG/D;AAED;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAKjG;AAED;;;;;;;;GAQG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAE1G"}
@@ -0,0 +1,108 @@
1
+ /**
2
+ * @module
3
+ * Calendar-date arithmetic on `YYYY-MM-DD` strings. Internal to the SDK.
4
+ *
5
+ * Dates here are calendar days, not instants: there is no time of day and no
6
+ * time zone, so nothing can shift a day across midnight or a DST change. The
7
+ * day number is a count of days since 1970-01-01 computed with `Date.UTC`,
8
+ * which is only ever used as an integer calendar and never read back in local
9
+ * time.
10
+ */
11
+ const ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
12
+ const MS_PER_DAY = 86_400_000;
13
+ /**
14
+ * Parses a `YYYY-MM-DD` string into its parts, rejecting impossible dates.
15
+ *
16
+ * `Date.UTC(2026, 1, 30)` silently rolls over to March 2nd, so the parts are
17
+ * checked against the month's real length rather than trusted.
18
+ *
19
+ * @param value - The date string.
20
+ * @param label - What the value is, for the error message.
21
+ * @returns Year, month (1-12) and day.
22
+ * @throws {RangeError} If `value` is not a real calendar date in `YYYY-MM-DD` form.
23
+ */
24
+ export function parseDate(value, label = 'date') {
25
+ const match = ISO_DATE.exec(value);
26
+ if (!match)
27
+ throw new RangeError(`Invalid ${label}: ${JSON.stringify(value)} (expected YYYY-MM-DD)`);
28
+ const year = Number(match[1]);
29
+ const month = Number(match[2]);
30
+ const day = Number(match[3]);
31
+ if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) {
32
+ throw new RangeError(`Invalid ${label}: ${JSON.stringify(value)} is not a calendar date`);
33
+ }
34
+ return { year, month, day };
35
+ }
36
+ /**
37
+ * Converts a `YYYY-MM-DD` string to a day number (days since 1970-01-01).
38
+ *
39
+ * @param value - The date string.
40
+ * @param label - What the value is, for the error message.
41
+ * @returns The day number.
42
+ * @throws {RangeError} If `value` is not a valid date.
43
+ */
44
+ export function toDayNumber(value, label = 'date') {
45
+ const { year, month, day } = parseDate(value, label);
46
+ return Date.UTC(year, month - 1, day) / MS_PER_DAY;
47
+ }
48
+ /**
49
+ * Converts a day number back to `YYYY-MM-DD`.
50
+ *
51
+ * @param dayNumber - Days since 1970-01-01.
52
+ * @returns The date string.
53
+ */
54
+ export function fromDayNumber(dayNumber) {
55
+ const d = new Date(dayNumber * MS_PER_DAY);
56
+ return formatDate(d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate());
57
+ }
58
+ /**
59
+ * Formats date parts as `YYYY-MM-DD`.
60
+ *
61
+ * @param year - Four-digit year.
62
+ * @param month - Month, 1-12.
63
+ * @param day - Day of month.
64
+ * @returns The date string.
65
+ */
66
+ export function formatDate(year, month, day) {
67
+ return `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
68
+ }
69
+ /**
70
+ * The number of days in a month, accounting for leap years.
71
+ *
72
+ * @param year - Four-digit year.
73
+ * @param month - Month, 1-12.
74
+ * @returns 28 to 31.
75
+ */
76
+ export function daysInMonth(year, month) {
77
+ // Day 0 of the following month is the last day of this one.
78
+ return new Date(Date.UTC(year, month, 0)).getUTCDate();
79
+ }
80
+ /**
81
+ * The date `months` whole months after a year and month, on `day` clamped to
82
+ * that month's last day.
83
+ *
84
+ * @param year - Starting year.
85
+ * @param month - Starting month, 1-12.
86
+ * @param months - Whole months to add; may be zero.
87
+ * @param day - The wanted day of month, 1-31.
88
+ * @returns The clamped date as `YYYY-MM-DD`.
89
+ */
90
+ export function clampedMonthDate(year, month, months, day) {
91
+ const absolute = year * 12 + (month - 1) + months;
92
+ const y = Math.floor(absolute / 12);
93
+ const m = (absolute % 12) + 1;
94
+ return formatDate(y, m, Math.min(day, daysInMonth(y, m)));
95
+ }
96
+ /**
97
+ * Whole months from one year/month to another (`to - from`), ignoring days.
98
+ *
99
+ * @param fromYear - Year of the earlier month.
100
+ * @param fromMonth - Earlier month, 1-12.
101
+ * @param toYear - Year of the later month.
102
+ * @param toMonth - Later month, 1-12.
103
+ * @returns The month difference; negative when `to` is earlier.
104
+ */
105
+ export function monthsBetween(fromYear, fromMonth, toYear, toMonth) {
106
+ return (toYear * 12 + toMonth) - (fromYear * 12 + fromMonth);
107
+ }
108
+ //# sourceMappingURL=calendar.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calendar.js","sourceRoot":"","sources":["../../src/recurrence/calendar.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,MAAM,QAAQ,GAAG,2BAA2B,CAAA;AAC5C,MAAM,UAAU,GAAG,UAAU,CAAA;AAE7B;;;;;;;;;;GAUG;AACH,MAAM,UAAU,SAAS,CAAC,KAAa,EAAE,KAAK,GAAG,MAAM;IACrD,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;IAClC,IAAI,CAAC,KAAK;QAAE,MAAM,IAAI,UAAU,CAAC,WAAW,KAAK,KAAK,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAAA;IACpG,MAAM,IAAI,GAAG,MAAM,CAAC,KA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GAAG,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAA;AAC7G,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAC,IAAY,EAAE,KAAa;IACrD,4DAA4D;IAC5D,OAAO,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,UAAU,EAAE,CAAA;AACxD,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,gBAAgB,CAAC,IAAY,EAAE,KAAa,EAAE,MAAc,EAAE,GAAW;IACvF,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAE,GAAG,CAAC,KAAK,GAAG,CAAC,CAAC,GAAG,MAAM,CAAA;IACjD,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,GAAG,EAAE,CAAC,CAAA;IACnC,MAAM,CAAC,GAAG,CAAC,QAAQ,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;IAC7B,OAAO,UAAU,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;AAC3D,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,aAAa,CAAC,QAAgB,EAAE,SAAiB,EAAE,MAAc,EAAE,OAAe;IAChG,OAAO,CAAC,MAAM,GAAG,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,EAAE,GAAG,SAAS,CAAC,CAAA;AAC9D,CAAC"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @module
3
+ * Recurring-item date maths and projections: when an item occurs, what it
4
+ * costs per month, when the household is next paid, and what each account's
5
+ * balance does in between.
6
+ *
7
+ * Pure and dependency-free: calendar dates in and out as `YYYY-MM-DD`
8
+ * strings, money as `numeric(19,4)` decimal strings, no clock and no time
9
+ * zone. The caller works out the user's today once, in their zone, and passes
10
+ * it in. Ranges are half-open (`from` inclusive, `to` exclusive), like
11
+ * `DashboardRange`.
12
+ */
13
+ export { DEFAULT_SEMIMONTHLY_DAYS, RECURRENCE_FREQUENCIES } from './types.js';
14
+ export type { DailyBalance, FlowTotals, RecurrenceFrequency, RecurrenceSchedule, RecurringItem, RecurringLeg, } from './types.js';
15
+ export { nextOccurrence, occurrences } from './schedule.js';
16
+ export { dailyBalances, flowTotals, monthlyEquivalent, nextPayday, } from './projection.js';
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/recurrence/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAA;AAC7E,YAAY,EACV,YAAY,EAAE,UAAU,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,aAAa,EAAE,YAAY,GAC/F,MAAM,YAAY,CAAA;AACnB,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA;AAC3D,OAAO,EACL,aAAa,EAAE,UAAU,EAAE,iBAAiB,EAAE,UAAU,GACzD,MAAM,iBAAiB,CAAA"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @module
3
+ * Recurring-item date maths and projections: when an item occurs, what it
4
+ * costs per month, when the household is next paid, and what each account's
5
+ * balance does in between.
6
+ *
7
+ * Pure and dependency-free: calendar dates in and out as `YYYY-MM-DD`
8
+ * strings, money as `numeric(19,4)` decimal strings, no clock and no time
9
+ * zone. The caller works out the user's today once, in their zone, and passes
10
+ * it in. Ranges are half-open (`from` inclusive, `to` exclusive), like
11
+ * `DashboardRange`.
12
+ */
13
+ export { DEFAULT_SEMIMONTHLY_DAYS, RECURRENCE_FREQUENCIES } from './types.js';
14
+ export { nextOccurrence, occurrences } from './schedule.js';
15
+ export { dailyBalances, flowTotals, monthlyEquivalent, nextPayday, } from './projection.js';
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/recurrence/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAA;AAI7E,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA;AAC3D,OAAO,EACL,aAAa,EAAE,UAAU,EAAE,iBAAiB,EAAE,UAAU,GACzD,MAAM,iBAAiB,CAAA"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @module
3
+ * Fixed-point money for the recurrence module. Internal to the SDK.
4
+ *
5
+ * Same rules as the budgets plugin's `shared/money.ts`: amounts are
6
+ * `numeric(19,4)` strings at every boundary and `bigint` units of 1/10,000 in
7
+ * between, never `number`. Kept private for now so this module does not also
8
+ * commit the SDK to a public money API; promoting it (and deleting the plugin
9
+ * copies) is a separate decision.
10
+ */
11
+ /** Integer units per whole currency unit. */
12
+ export declare const UNIT = 10000n;
13
+ /**
14
+ * Parses a decimal string into units of 1/10,000.
15
+ *
16
+ * @param value - A plain decimal string such as `'-81.2'` or `'2850.0000'`.
17
+ * @param label - What the value is, for the error message.
18
+ * @returns The scaled amount. Digits beyond the fourth decimal place are
19
+ * truncated, since the column holds four.
20
+ * @throws {RangeError} If `value` is not a plain decimal number.
21
+ */
22
+ export declare function parseMoney(value: string, label?: string): bigint;
23
+ /**
24
+ * Formats units of 1/10,000 as a four-decimal string.
25
+ *
26
+ * @param units - The scaled amount.
27
+ * @returns A string such as `'-81.2000'`; zero is always `'0.0000'`, never `'-0.0000'`.
28
+ */
29
+ export declare function formatMoney(units: bigint): string;
30
+ /**
31
+ * Divides and rounds half away from zero, so a value and its negation round
32
+ * to mirror images (`-801.66665` and `801.66665` both move away from zero).
33
+ *
34
+ * @param numerator - Dividend.
35
+ * @param denominator - Divisor; must be positive.
36
+ * @returns The rounded quotient.
37
+ */
38
+ export declare function divideRounded(numerator: bigint, denominator: bigint): bigint;
39
+ //# sourceMappingURL=money.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"money.d.ts","sourceRoot":"","sources":["../../src/recurrence/money.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,6CAA6C;AAC7C,eAAO,MAAM,IAAI,SAAU,CAAA;AAI3B;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,SAAW,GAAG,MAAM,CAOlE;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAKjD;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAK5E"}
@@ -0,0 +1,58 @@
1
+ /**
2
+ * @module
3
+ * Fixed-point money for the recurrence module. Internal to the SDK.
4
+ *
5
+ * Same rules as the budgets plugin's `shared/money.ts`: amounts are
6
+ * `numeric(19,4)` strings at every boundary and `bigint` units of 1/10,000 in
7
+ * between, never `number`. Kept private for now so this module does not also
8
+ * commit the SDK to a public money API; promoting it (and deleting the plugin
9
+ * copies) is a separate decision.
10
+ */
11
+ /** Integer units per whole currency unit. */
12
+ export const UNIT = 10000n;
13
+ const NUMERIC = /^-?\d+(\.\d+)?$/;
14
+ /**
15
+ * Parses a decimal string into units of 1/10,000.
16
+ *
17
+ * @param value - A plain decimal string such as `'-81.2'` or `'2850.0000'`.
18
+ * @param label - What the value is, for the error message.
19
+ * @returns The scaled amount. Digits beyond the fourth decimal place are
20
+ * truncated, since the column holds four.
21
+ * @throws {RangeError} If `value` is not a plain decimal number.
22
+ */
23
+ export function parseMoney(value, label = 'amount') {
24
+ const text = typeof value === 'string' ? value.trim() : '';
25
+ if (!NUMERIC.test(text))
26
+ throw new RangeError(`Invalid ${label}: ${JSON.stringify(value)}`);
27
+ const negative = text.startsWith('-');
28
+ const [whole = '0', fraction = ''] = (negative ? text.slice(1) : text).split('.');
29
+ const units = BigInt(whole) * UNIT + BigInt((fraction + '0000').slice(0, 4));
30
+ return negative ? -units : units;
31
+ }
32
+ /**
33
+ * Formats units of 1/10,000 as a four-decimal string.
34
+ *
35
+ * @param units - The scaled amount.
36
+ * @returns A string such as `'-81.2000'`; zero is always `'0.0000'`, never `'-0.0000'`.
37
+ */
38
+ export function formatMoney(units) {
39
+ const negative = units < 0n;
40
+ const absolute = negative ? -units : units;
41
+ const fraction = (absolute % UNIT).toString().padStart(4, '0');
42
+ return `${negative ? '-' : ''}${absolute / UNIT}.${fraction}`;
43
+ }
44
+ /**
45
+ * Divides and rounds half away from zero, so a value and its negation round
46
+ * to mirror images (`-801.66665` and `801.66665` both move away from zero).
47
+ *
48
+ * @param numerator - Dividend.
49
+ * @param denominator - Divisor; must be positive.
50
+ * @returns The rounded quotient.
51
+ */
52
+ export function divideRounded(numerator, denominator) {
53
+ const negative = numerator < 0n;
54
+ const absolute = negative ? -numerator : numerator;
55
+ const q = (absolute * 2n + denominator) / (denominator * 2n);
56
+ return negative ? -q : q;
57
+ }
58
+ //# sourceMappingURL=money.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"money.js","sourceRoot":"","sources":["../../src/recurrence/money.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,6CAA6C;AAC7C,MAAM,CAAC,MAAM,IAAI,GAAG,MAAO,CAAA;AAE3B,MAAM,OAAO,GAAG,iBAAiB,CAAA;AAEjC;;;;;;;;GAQG;AACH,MAAM,UAAU,UAAU,CAAC,KAAa,EAAE,KAAK,GAAG,QAAQ;IACxD,MAAM,IAAI,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,C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IAClE,MAAM,QAAQ,GAAG,SAAS,GAAG,EAAE,CAAA;IAC/B,MAAM,QAAQ,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAA;IAClD,MAAM,CAAC,GAAG,CAAC,QAAQ,GAAG,EAAE,GAAG,WAAW,CAAC,GAAG,CAAC,WAAW,GAAG,EAAE,CAAC,CAAA;IAC5D,OAAO,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AAC1B,CAAC"}
@@ -0,0 +1,71 @@
1
+ import type { DailyBalance, FlowTotals, RecurrenceFrequency, RecurringItem } from './types.js';
2
+ /**
3
+ * What an amount on a schedule costs (or earns) per month, for summaries.
4
+ *
5
+ * Used for "per month" tiles, where a quarterly bill and a weekly one need a
6
+ * common unit. It is a rate, not a forecast: a month with three biweekly
7
+ * paydays still really gets three.
8
+ *
9
+ * @param amount - Signed amount per occurrence, as a decimal string. For an
10
+ * item with several legs, pass the total of the legs you want counted.
11
+ * @param frequency - How often it occurs.
12
+ * @returns The signed monthly amount as a four-decimal string, rounded half
13
+ * away from zero. `'0.0000'` for `once`, which has no monthly rate.
14
+ * @throws {RangeError} If `amount` is not a decimal or `frequency` is unknown.
15
+ */
16
+ export declare function monthlyEquivalent(amount: string, frequency: RecurrenceFrequency): string;
17
+ /**
18
+ * The household's next payday: the earliest income, into any account, after today.
19
+ *
20
+ * Strictly after `today`, because today's actual balance already includes
21
+ * anything that landed today. Every income item counts, so two people paid
22
+ * biweekly on offset weeks give a payday every week.
23
+ *
24
+ * @param items - All of the user's recurring items; non-income items are ignored.
25
+ * @param today - The user's today, `YYYY-MM-DD`, in their time zone.
26
+ * @returns The date, or `null` when no income occurs after today (the caller
27
+ * chooses a fallback window).
28
+ * @throws {RangeError} If any item or date is invalid.
29
+ */
30
+ export declare function nextPayday(items: readonly RecurringItem[], today: string): string | null;
31
+ /**
32
+ * Projects end-of-day balances for a set of accounts over a half-open range.
33
+ *
34
+ * Each account starts from its balance at the end of the day before `from` —
35
+ * for the widget, today's actual balance with `from` set to tomorrow, so
36
+ * nothing that already posted is counted twice. Every leg that lands on a
37
+ * listed account is applied, including both sides of a transfer; legs on
38
+ * accounts not listed are ignored. Balances may go negative.
39
+ *
40
+ * Every day in the range is present for every account, including days with
41
+ * no activity, so a chart can plot the series directly. Each day also carries
42
+ * its `low`: the balance after that day's outflows but before its inflows.
43
+ *
44
+ * @param items - Recurring items to apply.
45
+ * @param startingBalances - Balance per account id at the end of the day
46
+ * before `from`, as decimal strings. Only these accounts are projected.
47
+ * @param from - First day to project, inclusive, `YYYY-MM-DD`.
48
+ * @param to - First day not projected, `YYYY-MM-DD`.
49
+ * @returns Each listed account id mapped to one `DailyBalance` per day, ascending.
50
+ * @throws {RangeError} If any item, amount or date is invalid, or `to` is before `from`.
51
+ */
52
+ export declare function dailyBalances(items: readonly RecurringItem[], startingBalances: Readonly<Record<string, string>>, from: string, to: string): Record<string, DailyBalance[]>;
53
+ /**
54
+ * Totals the money entering and leaving a set of accounts over a half-open range.
55
+ *
56
+ * Only legs on the listed accounts count, and each occurrence is netted
57
+ * across them before it is classed as in or out. So a transfer between two
58
+ * listed accounts (checking to savings, with both listed) nets to zero and is
59
+ * never spending, while the same transfer measured on checking alone is an
60
+ * outflow. A payment from checking to a loan, with only cash accounts listed,
61
+ * is an outflow.
62
+ *
63
+ * @param items - Recurring items to total.
64
+ * @param accountIds - The accounts that make up "the household" for this total.
65
+ * @param from - First day, inclusive, `YYYY-MM-DD`.
66
+ * @param to - First day excluded, `YYYY-MM-DD`.
67
+ * @returns Inflow, outflow and net as four-decimal strings.
68
+ * @throws {RangeError} If any item, amount or date is invalid, or `to` is before `from`.
69
+ */
70
+ export declare function flowTotals(items: readonly RecurringItem[], accountIds: readonly string[], from: string, to: string): FlowTotals;
71
+ //# sourceMappingURL=projection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"projection.d.ts","sourceRoot":"","sources":["../../src/recurrence/projection.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,YAAY,EAAE,UAAU,EAAE,mBAAmB,EAAE,aAAa,EAC7D,MAAM,YAAY,CAAA;AAoBnB;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,mBAAmB,GAAG,MAAM,CAMxF;AAcD;;;;;;;;;;;;GAYG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,SAAS,aAAa,EAAE,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CASxF;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,aAAa,CAC3B,KAAK,EAAE,SAAS,aAAa,EAAE,EAC/B,gBAAgB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,EAClD,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,GACT,MAAM,CAAC,MAAM,EAAE,YAAY,EAAE,CAAC,CA8ChC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,UAAU,CACxB,KAAK,EAAE,SAAS,aAAa,EAAE,EAC/B,UAAU,EAAE,SAAS,MAAM,EAAE,EAC7B,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,GACT,UAAU,CAgBZ"}
@@ -0,0 +1,181 @@
1
+ import { fromDayNumber, toDayNumber } from './calendar.js';
2
+ import { divideRounded, formatMoney, parseMoney } from './money.js';
3
+ import { nextOccurrence, occurrences } from './schedule.js';
4
+ /**
5
+ * Occurrences per month for each frequency, as an exact fraction.
6
+ *
7
+ * Exact rather than rounded: the old app used ×2.17 for biweekly, which put a
8
+ * $370 item at $802.90 a month instead of $801.67. Daily uses a 365-day year,
9
+ * matching weekly's 52 weeks. A one-off has no monthly rate.
10
+ */
11
+ const PER_MONTH = {
12
+ once: [0n, 1n],
13
+ daily: [365n, 12n],
14
+ weekly: [52n, 12n],
15
+ biweekly: [26n, 12n],
16
+ semimonthly: [24n, 12n],
17
+ monthly: [1n, 1n],
18
+ quarterly: [1n, 3n],
19
+ annual: [1n, 12n],
20
+ };
21
+ /**
22
+ * What an amount on a schedule costs (or earns) per month, for summaries.
23
+ *
24
+ * Used for "per month" tiles, where a quarterly bill and a weekly one need a
25
+ * common unit. It is a rate, not a forecast: a month with three biweekly
26
+ * paydays still really gets three.
27
+ *
28
+ * @param amount - Signed amount per occurrence, as a decimal string. For an
29
+ * item with several legs, pass the total of the legs you want counted.
30
+ * @param frequency - How often it occurs.
31
+ * @returns The signed monthly amount as a four-decimal string, rounded half
32
+ * away from zero. `'0.0000'` for `once`, which has no monthly rate.
33
+ * @throws {RangeError} If `amount` is not a decimal or `frequency` is unknown.
34
+ */
35
+ export function monthlyEquivalent(amount, frequency) {
36
+ if (!Object.hasOwn(PER_MONTH, frequency)) {
37
+ throw new RangeError(`Unknown recurrence frequency: ${JSON.stringify(frequency)}`);
38
+ }
39
+ const [numerator, denominator] = PER_MONTH[frequency];
40
+ return formatMoney(divideRounded(parseMoney(amount) * numerator, denominator));
41
+ }
42
+ /**
43
+ * Whether an item brings money into the household: it has legs and every leg
44
+ * is positive. A bill has a negative leg and a transfer's legs net to zero, so
45
+ * neither counts, while a paycheck split across accounts does.
46
+ *
47
+ * @param item - The item to test.
48
+ * @returns `true` for income.
49
+ */
50
+ function isIncome(item) {
51
+ return item.legs.length > 0 && item.legs.every((leg) => parseMoney(leg.amount, 'leg amount') > 0n);
52
+ }
53
+ /**
54
+ * The household's next payday: the earliest income, into any account, after today.
55
+ *
56
+ * Strictly after `today`, because today's actual balance already includes
57
+ * anything that landed today. Every income item counts, so two people paid
58
+ * biweekly on offset weeks give a payday every week.
59
+ *
60
+ * @param items - All of the user's recurring items; non-income items are ignored.
61
+ * @param today - The user's today, `YYYY-MM-DD`, in their time zone.
62
+ * @returns The date, or `null` when no income occurs after today (the caller
63
+ * chooses a fallback window).
64
+ * @throws {RangeError} If any item or date is invalid.
65
+ */
66
+ export function nextPayday(items, today) {
67
+ const tomorrow = fromDayNumber(toDayNumber(today, 'today') + 1);
68
+ let earliest = null;
69
+ for (const item of items) {
70
+ if (!isIncome(item))
71
+ continue;
72
+ const next = nextOccurrence(item, tomorrow);
73
+ if (next !== null && (earliest === null || next < earliest))
74
+ earliest = next;
75
+ }
76
+ return earliest;
77
+ }
78
+ /**
79
+ * Projects end-of-day balances for a set of accounts over a half-open range.
80
+ *
81
+ * Each account starts from its balance at the end of the day before `from` —
82
+ * for the widget, today's actual balance with `from` set to tomorrow, so
83
+ * nothing that already posted is counted twice. Every leg that lands on a
84
+ * listed account is applied, including both sides of a transfer; legs on
85
+ * accounts not listed are ignored. Balances may go negative.
86
+ *
87
+ * Every day in the range is present for every account, including days with
88
+ * no activity, so a chart can plot the series directly. Each day also carries
89
+ * its `low`: the balance after that day's outflows but before its inflows.
90
+ *
91
+ * @param items - Recurring items to apply.
92
+ * @param startingBalances - Balance per account id at the end of the day
93
+ * before `from`, as decimal strings. Only these accounts are projected.
94
+ * @param from - First day to project, inclusive, `YYYY-MM-DD`.
95
+ * @param to - First day not projected, `YYYY-MM-DD`.
96
+ * @returns Each listed account id mapped to one `DailyBalance` per day, ascending.
97
+ * @throws {RangeError} If any item, amount or date is invalid, or `to` is before `from`.
98
+ */
99
+ export function dailyBalances(items, startingBalances, from, to) {
100
+ const first = toDayNumber(from, 'from');
101
+ const last = toDayNumber(to, 'to');
102
+ if (last < first)
103
+ throw new RangeError(`Range end ${to} is before its start ${from}`);
104
+ const accounts = new Map();
105
+ for (const [accountId, balance] of Object.entries(startingBalances)) {
106
+ accounts.set(accountId, parseMoney(balance, `starting balance for ${accountId}`));
107
+ }
108
+ // Per account, the money out and the money in on each day offset from
109
+ // `first`, kept apart so a day's low point can apply outflows first.
110
+ const outs = new Map();
111
+ const ins = new Map();
112
+ for (const accountId of accounts.keys()) {
113
+ outs.set(accountId, new Array(last - first).fill(0n));
114
+ ins.set(accountId, new Array(last - first).fill(0n));
115
+ }
116
+ for (const item of items) {
117
+ const dates = occurrences(item, from, to);
118
+ for (const leg of item.legs) {
119
+ const amount = parseMoney(leg.amount, 'leg amount');
120
+ const series = (amount < 0n ? outs : ins).get(leg.accountId);
121
+ if (!series)
122
+ continue;
123
+ for (const date of dates) {
124
+ const offset = toDayNumber(date) - first;
125
+ series[offset] = (series[offset] ?? 0n) + amount;
126
+ }
127
+ }
128
+ }
129
+ const result = [];
130
+ for (const [accountId, start] of accounts) {
131
+ let running = start;
132
+ const days = [];
133
+ const out = outs.get(accountId) ?? [];
134
+ const into = ins.get(accountId) ?? [];
135
+ for (let offset = 0; offset < last - first; offset += 1) {
136
+ const low = running + (out[offset] ?? 0n);
137
+ running = low + (into[offset] ?? 0n);
138
+ days.push({ date: fromDayNumber(first + offset), balance: formatMoney(running), low: formatMoney(low) });
139
+ }
140
+ result.push([accountId, days]);
141
+ }
142
+ return Object.fromEntries(result);
143
+ }
144
+ /**
145
+ * Totals the money entering and leaving a set of accounts over a half-open range.
146
+ *
147
+ * Only legs on the listed accounts count, and each occurrence is netted
148
+ * across them before it is classed as in or out. So a transfer between two
149
+ * listed accounts (checking to savings, with both listed) nets to zero and is
150
+ * never spending, while the same transfer measured on checking alone is an
151
+ * outflow. A payment from checking to a loan, with only cash accounts listed,
152
+ * is an outflow.
153
+ *
154
+ * @param items - Recurring items to total.
155
+ * @param accountIds - The accounts that make up "the household" for this total.
156
+ * @param from - First day, inclusive, `YYYY-MM-DD`.
157
+ * @param to - First day excluded, `YYYY-MM-DD`.
158
+ * @returns Inflow, outflow and net as four-decimal strings.
159
+ * @throws {RangeError} If any item, amount or date is invalid, or `to` is before `from`.
160
+ */
161
+ export function flowTotals(items, accountIds, from, to) {
162
+ const inSet = new Set(accountIds);
163
+ let inflow = 0n;
164
+ let outflow = 0n;
165
+ for (const item of items) {
166
+ const dates = occurrences(item, from, to);
167
+ let perOccurrence = 0n;
168
+ for (const leg of item.legs) {
169
+ const amount = parseMoney(leg.amount, 'leg amount');
170
+ if (inSet.has(leg.accountId))
171
+ perOccurrence += amount;
172
+ }
173
+ const total = perOccurrence * BigInt(dates.length);
174
+ if (total > 0n)
175
+ inflow += total;
176
+ else
177
+ outflow += total;
178
+ }
179
+ return { inflow: formatMoney(inflow), outflow: formatMoney(outflow), net: formatMoney(inflow + outflow) };
180
+ }
181
+ //# sourceMappingURL=projection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"projection.js","sourceRoot":"","sources":["../../src/recurrence/projection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA;AAC1D,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AACnE,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA;AAK3D;;;;;;GAMG;AACH,MAAM,SAAS,GAAmF;IAChG,IAAI,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IACd,KAAK,EAAE,CAAC,IAAI,EAAE,GAAG,CAAC;IAClB,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,CAAC;IAClB,QAAQ,EAAE,CAAC,GAAG,EAAE,GAAG,CAAC;IACpB,WAAW,EAAE,CAAC,GAAG,EAAE,GAAG,CAAC;IACvB,OAAO,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IACjB,SAAS,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IACnB,MAAM,EAAE,CAAC,EAAE,EAAE,GAAG,CAAC;CAClB,CAAA;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,iBAAiB,CAAC,MAAc,EAAE,SAA8B;IAC9E,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,EAAE,CAAC;QACzC,MAAM,IAAI,UAAU,CAAC,iCAAiC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,CAAC,CAAA;IACpF,CAAC;IACD,M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CAAC;IACD,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,CAAA;AACnC,CAAC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,UAAU,CACxB,KAA+B,EAC/B,UAA6B,EAC7B,IAAY,EACZ,EAAU;IAEV,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,CAAA;IACjC,IAAI,MAAM,GAAG,EAAE,CAAA;IACf,IAAI,OAAO,GAAG,EAAE,CAAA;IAChB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,KAAK,GAAG,WAAW,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,CAAA;QACzC,IAAI,aAAa,GAAG,EAAE,CAAA;QACtB,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YAC5B,MAAM,MAAM,GAAG,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAA;YACnD,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC;gBAAE,aAAa,IAAI,MAAM,CAAA;QACvD,CAAC;QACD,MAAM,KAAK,GAAG,aAAa,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;QAClD,IAAI,KAAK,GAAG,EAAE;YAAE,MAAM,IAAI,KAAK,CAAA;;YAC1B,OAAO,IAAI,KAAK,CAAA;IACvB,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,WAAW,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,WAAW,CAAC,MAAM,GAAG,OAAO,CAAC,EAAE,CAAA;AAC3G,CAAC"}
@@ -0,0 +1,28 @@
1
+ import { type RecurrenceSchedule } from './types.js';
2
+ /**
3
+ * Lists a schedule's nominal occurrence dates in a half-open range.
4
+ *
5
+ * Nominal means the date the schedule says, before any weekend or holiday
6
+ * shift; `(item, nominal date)` is what identifies an occurrence.
7
+ *
8
+ * @param schedule - The item's schedule (a whole `RecurringItem` works).
9
+ * @param from - First day to include, `YYYY-MM-DD`.
10
+ * @param to - First day to exclude, `YYYY-MM-DD`. Equal to `from` gives an empty list.
11
+ * @returns Dates as `YYYY-MM-DD`, ascending, each at most once.
12
+ * @throws {RangeError} If the schedule is invalid (see `RecurrenceSchedule`), a
13
+ * date is malformed, or `to` is before `from`.
14
+ */
15
+ export declare function occurrences(schedule: RecurrenceSchedule, from: string, to: string): string[];
16
+ /**
17
+ * The first occurrence on or after a date: an item's "next due" date.
18
+ *
19
+ * Pass the user's today to include something due today; pass tomorrow for the
20
+ * first occurrence the balance does not already reflect.
21
+ *
22
+ * @param schedule - The item's schedule.
23
+ * @param from - Earliest date to consider, inclusive, `YYYY-MM-DD`.
24
+ * @returns The date, or `null` if the series has ended by then.
25
+ * @throws {RangeError} If the schedule or `from` is invalid.
26
+ */
27
+ export declare function nextOccurrence(schedule: RecurrenceSchedule, from: string): string | null;
28
+ //# sourceMappingURL=schedule.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schedule.d.ts","sourceRoot":"","sources":["../../src/recurrence/schedule.ts"],"names":[],"mappings":"AAGA,OAAO,EAA4B,KAAK,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAiI9E;;;;;;;;;;;;GAYG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,kBAAkB,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,CAY5F;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,kBAAkB,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAIxF"}
@@ -0,0 +1,160 @@
1
+ import { clampedMonthDate, fromDayNumber, monthsBetween, parseDate, toDayNumber, } from './calendar.js';
2
+ import { DEFAULT_SEMIMONTHLY_DAYS } from './types.js';
3
+ /** Frequencies that step a fixed number of days from the anchor. */
4
+ const DAY_STEPS = { daily: 1, weekly: 7, biweekly: 14 };
5
+ /** Frequencies that step a fixed number of months from the anchor, clamped to month end. */
6
+ const MONTH_STEPS = { monthly: 1, quarterly: 3, annual: 12 };
7
+ /**
8
+ * Validates a schedule, throwing on anything a forecast could not honour.
9
+ *
10
+ * @param schedule - The schedule to check.
11
+ * @returns The schedule with its anchor and end as day numbers.
12
+ * @throws {RangeError} On an unknown frequency, an invalid date, an end before
13
+ * the start, or semimonthly days that are out of range or can land on the same date.
14
+ */
15
+ function normalize(schedule) {
16
+ const { frequency } = schedule;
17
+ // Object.hasOwn, not `in`: `'toString' in DAY_STEPS` is true via the prototype.
18
+ if (!Object.hasOwn(DAY_STEPS, frequency) && !Object.hasOwn(MONTH_STEPS, frequency)
19
+ && frequency !== 'once' && frequency !== 'semimonthly') {
20
+ throw new RangeError(`Unknown recurrence frequency: ${JSON.stringify(frequency)}`);
21
+ }
22
+ const start = toDayNumber(schedule.seriesStartDate, 'seriesStartDate');
23
+ const end = schedule.endDate == null ? Infinity : toDayNumber(schedule.endDate, 'endDate');
24
+ if (end < start) {
25
+ throw new RangeError(`endDate ${schedule.endDate} is before seriesStartDate ${schedule.seriesStartDate}`);
26
+ }
27
+ if (frequency === 'semimonthly')
28
+ semimonthlyDays(schedule);
29
+ return { schedule, start, end };
30
+ }
31
+ /**
32
+ * The two semimonthly days, validated and in ascending order.
33
+ *
34
+ * Two days that are both 28 or later collapse onto one date in February
35
+ * (29 and 31 both clamp to the 28th), and an occurrence is identified by its
36
+ * item and date, so the pair would silently become one payment. That is
37
+ * refused rather than deduplicated.
38
+ *
39
+ * @param schedule - A semimonthly schedule.
40
+ * @returns `[earlier, later]`.
41
+ * @throws {RangeError} If a day is not an integer 1-31, the days are equal, or both are 28 or later.
42
+ */
43
+ function semimonthlyDays(schedule) {
44
+ const days = schedule.semimonthlyDays ?? DEFAULT_SEMIMONTHLY_DAYS;
45
+ for (const d of days) {
46
+ if (!Number.isInteger(d) || d < 1 || d > 31) {
47
+ throw new RangeError(`Invalid semimonthly day: ${d} (expected an integer 1-31)`);
48
+ }
49
+ }
50
+ const earlier = Math.min(days[0], days[1]);
51
+ const later = Math.max(days[0], days[1]);
52
+ if (earlier === later)
53
+ throw new RangeError(`Semimonthly days must differ, got ${earlier} twice`);
54
+ if (earlier >= 28) {
55
+ throw new RangeError(`Semimonthly days ${earlier} and ${later} land on the same date in February; the earlier day must be 27 or less`);
56
+ }
57
+ return [earlier, later];
58
+ }
59
+ /**
60
+ * Yields a schedule's occurrences as day numbers, ascending, starting at the
61
+ * first one on or after `lower` and ending at the series end (or never).
62
+ *
63
+ * Every occurrence is computed from the anchor, not from the one before it,
64
+ * so a clamp in a short month never carries forward: Jan 31 → Feb 28 → Mar 31.
65
+ *
66
+ * @param n - A normalized schedule.
67
+ * @param lower - Earliest day number wanted, inclusive.
68
+ * @returns A generator of day numbers.
69
+ */
70
+ function* iterate(n, lower) {
71
+ const { schedule, start, end } = n;
72
+ const from = Math.max(lower, start);
73
+ const { frequency } = schedule;
74
+ if (frequency === 'once') {
75
+ if (start >= from && start <= end)
76
+ yield start;
77
+ return;
78
+ }
79
+ if (frequency === 'daily' || frequency === 'weekly' || frequency === 'biweekly') {
80
+ const step = DAY_STEPS[frequency];
81
+ for (let day = start + Math.ceil((from - start) / step) * step; day <= end; day += step) {
82
+ yield day;
83
+ }
84
+ return;
85
+ }
86
+ const anchor = parseDate(schedule.seriesStartDate);
87
+ const lowerDate = parseDate(fromDayNumber(from));
88
+ // Start a month early: a clamped or earlier day in `from`'s month can still
89
+ // be on or after `from` only in that month, and one extra month is cheap.
90
+ const firstMonth = Math.max(0, monthsBetween(anchor.year, anchor.month, lowerDate.year, lowerDate.month) - 1);
91
+ if (frequency === 'semimonthly') {
92
+ const days = semimonthlyDays(schedule);
93
+ for (let m = firstMonth;; m += 1) {
94
+ for (const d of days) {
95
+ const day = toDayNumber(clampedMonthDate(anchor.year, anchor.month, m, d));
96
+ if (day > end)
97
+ return;
98
+ if (day >= from)
99
+ yield day;
100
+ }
101
+ }
102
+ }
103
+ if (frequency === 'monthly' || frequency === 'quarterly' || frequency === 'annual') {
104
+ const step = MONTH_STEPS[frequency];
105
+ for (let k = Math.floor(firstMonth / step);; k += 1) {
106
+ const day = toDayNumber(clampedMonthDate(anchor.year, anchor.month, k * step, anchor.day));
107
+ if (day > end)
108
+ return;
109
+ if (day >= from)
110
+ yield day;
111
+ }
112
+ }
113
+ // Unreachable after normalize(); kept so a frequency added to the type
114
+ // without a branch here fails loudly instead of yielding nothing.
115
+ throw new RangeError(`Unknown recurrence frequency: ${JSON.stringify(frequency)}`);
116
+ }
117
+ /**
118
+ * Lists a schedule's nominal occurrence dates in a half-open range.
119
+ *
120
+ * Nominal means the date the schedule says, before any weekend or holiday
121
+ * shift; `(item, nominal date)` is what identifies an occurrence.
122
+ *
123
+ * @param schedule - The item's schedule (a whole `RecurringItem` works).
124
+ * @param from - First day to include, `YYYY-MM-DD`.
125
+ * @param to - First day to exclude, `YYYY-MM-DD`. Equal to `from` gives an empty list.
126
+ * @returns Dates as `YYYY-MM-DD`, ascending, each at most once.
127
+ * @throws {RangeError} If the schedule is invalid (see `RecurrenceSchedule`), a
128
+ * date is malformed, or `to` is before `from`.
129
+ */
130
+ export function occurrences(schedule, from, to) {
131
+ const n = normalize(schedule);
132
+ const lower = toDayNumber(from, 'from');
133
+ const upper = toDayNumber(to, 'to');
134
+ if (upper < lower)
135
+ throw new RangeError(`Range end ${to} is before its start ${from}`);
136
+ const out = [];
137
+ for (const day of iterate(n, lower)) {
138
+ if (day >= upper)
139
+ break;
140
+ out.push(fromDayNumber(day));
141
+ }
142
+ return out;
143
+ }
144
+ /**
145
+ * The first occurrence on or after a date: an item's "next due" date.
146
+ *
147
+ * Pass the user's today to include something due today; pass tomorrow for the
148
+ * first occurrence the balance does not already reflect.
149
+ *
150
+ * @param schedule - The item's schedule.
151
+ * @param from - Earliest date to consider, inclusive, `YYYY-MM-DD`.
152
+ * @returns The date, or `null` if the series has ended by then.
153
+ * @throws {RangeError} If the schedule or `from` is invalid.
154
+ */
155
+ export function nextOccurrence(schedule, from) {
156
+ const n = normalize(schedule);
157
+ const first = iterate(n, toDayNumber(from, 'from')).next();
158
+ return first.done ? null : fromDayNumber(first.value);
159
+ }
160
+ //# sourceMappingURL=schedule.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schedule.js","sourceRoot":"","sources":["../../src/recurrence/schedule.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAAE,aAAa,EAAE,aAAa,EAAE,SAAS,EAAE,WAAW,GACvE,MAAM,eAAe,CAAA;AACtB,OAAO,EAAE,wBAAwB,EAA2B,MAAM,YAAY,CAAA;AAU9E,oEAAoE;AACpE,MAAM,SAAS,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAW,CAAA;AAChE,4FAA4F;AAC5F,MAAM,WAAW,GAAG,EAAE,OAAO,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,MAAM,EAAE,EAAE,EAAW,CAAA;AAErE;;;;;;;GAOG;AACH,SAAS,SAAS,CAAC,QAA4B;IAC7C,MAAM,EAAE,SAAS,EAAE,GAAG,QAAQ,CAAA;IAC9B,gFAAgF;IAChF,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE,SAAS,CAAC;WAC7E,SAAS,KAAK,MAAM,IAAI,SAAS,KAAK,aAAa,EAAE,CAAC;QACzD,MAAM,IAAI,UAAU,CAAC,iCAAiC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,CAAC,CAAA;IACpF,CAAC;IACD,MAAM,KAAK,GAAG,WAAW,CAAC,QAAQ,CAAC,eAAe,EAAE,iBAAiB,CAAC,CAAA;IACtE,MAAM,GAAG,GAAG,QAAQ,CAAC,OAAO,IAAI,IAAI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,EAAU;IAChF,MAAM,CAAC,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAA;IAC7B,MAAM,KAAK,GAAG,WAAW,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;IACvC,MAAM,KAAK,GAAG,WAAW,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;IACnC,IAAI,KAAK,GAAG,KAAK;QAAE,MAAM,IAAI,UAAU,CAAC,aAAa,EAAE,wBAAwB,IAAI,EAAE,CAAC,CAAA;IAEtF,MAAM,GAAG,GAAa,EAAE,CAAA;IACxB,KAAK,MAAM,GAAG,IAAI,OAAO,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,CAAC;QACpC,IAAI,GAAG,IAAI,KAAK;YAAE,MAAK;QACvB,GAAG,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAA;IAC9B,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,cAAc,CAAC,QAA4B,EAAE,IAAY;IACvE,MAAM,CAAC,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAA;IAC7B,MAAM,KAAK,GAAG,OAAO,CAAC,CAAC,EAAE,WAAW,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;IAC1D,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,aAAa,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;AACvD,CAAC"}
@@ -0,0 +1,91 @@
1
+ /**
2
+ * How often a recurring item repeats, in declaration order.
3
+ *
4
+ * Mirrors `core.recurrence_frequency` plus `once`, the one-off future item.
5
+ * Every function in this module throws on a value outside this list rather
6
+ * than skipping the item, so an unknown frequency can never silently drop out
7
+ * of a forecast.
8
+ */
9
+ export declare const RECURRENCE_FREQUENCIES: readonly ["once", "daily", "weekly", "biweekly", "semimonthly", "monthly", "quarterly", "annual"];
10
+ /** One of the values in `RECURRENCE_FREQUENCIES`. */
11
+ export type RecurrenceFrequency = (typeof RECURRENCE_FREQUENCIES)[number];
12
+ /** The two days a `semimonthly` item uses when none are given: the 1st and the 15th. */
13
+ export declare const DEFAULT_SEMIMONTHLY_DAYS: readonly [number, number];
14
+ /**
15
+ * When a recurring item happens. Only the schedule; no amounts or accounts.
16
+ *
17
+ * All dates are calendar dates as `YYYY-MM-DD`, with no time or time zone.
18
+ */
19
+ export interface RecurrenceSchedule {
20
+ /** How often it repeats. */
21
+ readonly frequency: RecurrenceFrequency;
22
+ /**
23
+ * The immutable anchor every occurrence is computed from; never advanced.
24
+ *
25
+ * For every frequency except `semimonthly` this is the first occurrence, and
26
+ * its day of month (or weekday) sets all the others. For `semimonthly` it is
27
+ * only the earliest date an occurrence may fall on; the days come from
28
+ * `semimonthlyDays`.
29
+ */
30
+ readonly seriesStartDate: string;
31
+ /**
32
+ * Last date an occurrence may fall on, inclusive. An occurrence exactly on
33
+ * this date happens. `null` or absent for a series with no planned end.
34
+ */
35
+ readonly endDate?: string | null;
36
+ /**
37
+ * The two days of the month a `semimonthly` item falls on, each 1-31.
38
+ * A day past the end of a short month clamps to its last day, so `[15, 31]`
39
+ * means "the 15th and the last day". Defaults to `DEFAULT_SEMIMONTHLY_DAYS`;
40
+ * ignored for every other frequency.
41
+ */
42
+ readonly semimonthlyDays?: readonly [number, number] | null;
43
+ }
44
+ /** Where one part of a recurring item's money lands. */
45
+ export interface RecurringLeg {
46
+ /** The account the amount is applied to. */
47
+ readonly accountId: string;
48
+ /**
49
+ * Signed amount as a `numeric(19,4)` decimal string, with the same sign
50
+ * convention as transactions: negative leaves the account, positive arrives.
51
+ */
52
+ readonly amount: string;
53
+ }
54
+ /**
55
+ * A recurring item as the projection functions need it: a schedule plus the
56
+ * legs it applies on every occurrence.
57
+ *
58
+ * A bill is one negative leg, income (including a split paycheck) is one or
59
+ * more positive legs, and a transfer is two legs that net to zero. Any object
60
+ * with these fields works; extra fields are ignored.
61
+ */
62
+ export interface RecurringItem extends RecurrenceSchedule {
63
+ /** The legs applied on each occurrence. */
64
+ readonly legs: readonly RecurringLeg[];
65
+ }
66
+ /** One day of a projected balance series. */
67
+ export interface DailyBalance {
68
+ /** The day, `YYYY-MM-DD`. */
69
+ readonly date: string;
70
+ /** Balance at the end of that day, as a four-decimal string. May be negative. */
71
+ readonly balance: string;
72
+ /**
73
+ * The lowest the balance gets that day, assuming the day's outflows clear
74
+ * before its inflows land: the previous day's balance plus every negative
75
+ * amount due that day. Equal to `balance` on a day with no inflow.
76
+ *
77
+ * Conservative on purpose. Rent due on payday is a real risk if the
78
+ * paycheck lands late in the day, and an end-of-day figure would hide it.
79
+ */
80
+ readonly low: string;
81
+ }
82
+ /** Money coming into and going out of a set of accounts over a period. */
83
+ export interface FlowTotals {
84
+ /** Sum of occurrences that add money to the set, as a four-decimal string (zero or positive). */
85
+ readonly inflow: string;
86
+ /** Sum of occurrences that take money out of the set, as a four-decimal string (zero or negative). */
87
+ readonly outflow: string;
88
+ /** `inflow + outflow`. */
89
+ readonly net: string;
90
+ }
91
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/recurrence/types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,eAAO,MAAM,sBAAsB,mGAEzB,CAAA;AACV,qDAAqD;AACrD,MAAM,MAAM,mBAAmB,GAAG,CAAC,OAAO,sBAAsB,CAAC,CAAC,MAAM,CAAC,CAAA;AAEzE,wFAAwF;AACxF,eAAO,MAAM,wBAAwB,EAAE,SAAS,CAAC,MAAM,EAAE,MAAM,CAAW,CAAA;AAE1E;;;;GAIG;AACH,MAAM,WAAW,kBAAkB;IACjC,4BAA4B;IAC5B,QAAQ,CAAC,SAAS,EAAE,mBAAmB,CAAA;IACvC;;;;;;;OAOG;IACH,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAA;IAChC;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAChC;;;;;OAKG;IACH,QAAQ,CAAC,eAAe,CAAC,EAAE,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAAA;CAC5D;AAED,wDAAwD;AACxD,MAAM,WAAW,YAAY;IAC3B,4CAA4C;IAC5C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B;;;OAGG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CACxB;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,aAAc,SAAQ,kBAAkB;IACvD,2CAA2C;IAC3C,QAAQ,CAAC,IAAI,EAAE,SAAS,YAAY,EAAE,CAAA;CACvC;AAED,6CAA6C;AAC7C,MAAM,WAAW,YAAY;IAC3B,6BAA6B;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,iFAAiF;IACjF,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB;;;;;;;OAOG;IACH,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;CACrB;AAED,0EAA0E;AAC1E,MAAM,WAAW,UAAU;IACzB,iGAAiG;IACjG,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,sGAAsG;IACtG,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,0BAA0B;IAC1B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;CACrB"}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * How often a recurring item repeats, in declaration order.
3
+ *
4
+ * Mirrors `core.recurrence_frequency` plus `once`, the one-off future item.
5
+ * Every function in this module throws on a value outside this list rather
6
+ * than skipping the item, so an unknown frequency can never silently drop out
7
+ * of a forecast.
8
+ */
9
+ export const RECURRENCE_FREQUENCIES = [
10
+ 'once', 'daily', 'weekly', 'biweekly', 'semimonthly', 'monthly', 'quarterly', 'annual',
11
+ ];
12
+ /** The two days a `semimonthly` item uses when none are given: the 1st and the 15th. */
13
+ export const DEFAULT_SEMIMONTHLY_DAYS = [1, 15];
14
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/recurrence/types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACpC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,aAAa,EAAE,SAAS,EAAE,WAAW,EAAE,QAAQ;CAC9E,CAAA;AAIV,wFAAwF;AACxF,MAAM,CAAC,MAAM,wBAAwB,GAA8B,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA"}
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@wickermoney/plugin-sdk",
3
- "version": "0.1.0-rc.4",
3
+ "version": "0.2.0",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/WickerMoney/wicker-money.git",
8
8
  "directory": "packages/plugin-sdk"
9
9
  },
10
- "homepage": "https://github.com/WickerMoney/wicker-money#readme",
10
+ "homepage": "https://github.com/WickerMoney/wicker-money/tree/main/packages/plugin-sdk#readme",
11
11
  "bugs": {
12
12
  "url": "https://github.com/WickerMoney/wicker-money/issues"
13
13
  },
@@ -22,6 +22,10 @@
22
22
  "./runtime": {
23
23
  "types": "./dist/runtime.d.ts",
24
24
  "default": "./dist/runtime.js"
25
+ },
26
+ "./recurrence": {
27
+ "types": "./dist/recurrence/index.d.ts",
28
+ "default": "./dist/recurrence/index.js"
25
29
  }
26
30
  },
27
31
  "files": [