@startsimpli/integrations 0.2.148 → 0.2.149
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/package.json +5 -5
- package/src/__tests__/liabilities.test.ts +224 -0
- package/src/__tests__/liability-plan-page.test.tsx +46 -0
- package/src/components/index.ts +1 -0
- package/src/components/pages/LiabilityPlanPage.tsx +203 -0
- package/src/corpus/client.ts +3 -0
- package/src/corpus/index.ts +4 -0
- package/src/corpus/liabilities.ts +238 -0
- package/src/corpus/liability-client.ts +101 -0
- package/src/corpus/liability-plan.ts +40 -0
- package/src/corpus/planning.ts +8 -0
- package/src/corpus/types.ts +9 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@startsimpli/integrations",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.149",
|
|
4
4
|
"description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://startsimpli.com",
|
|
@@ -51,8 +51,8 @@
|
|
|
51
51
|
"@startsimpli/ui-native": ">=0.1.12",
|
|
52
52
|
"react-native-safe-area-context": ">=4.0.0",
|
|
53
53
|
"@startsimpli/auth": "^0.4.50",
|
|
54
|
-
"@startsimpli/utils": "^0.4.
|
|
55
|
-
"@startsimpli/ui": "^0.4.
|
|
54
|
+
"@startsimpli/utils": "^0.4.18",
|
|
55
|
+
"@startsimpli/ui": "^0.4.172"
|
|
56
56
|
},
|
|
57
57
|
"peerDependenciesMeta": {
|
|
58
58
|
"react": {
|
|
@@ -99,10 +99,10 @@
|
|
|
99
99
|
"react-native": "0.85.3",
|
|
100
100
|
"react-native-safe-area-context": "~5.7.0",
|
|
101
101
|
"@startsimpli/llm": "0.4.31",
|
|
102
|
-
"@startsimpli/ui": "0.4.
|
|
102
|
+
"@startsimpli/ui": "0.4.172",
|
|
103
103
|
"@startsimpli/ui-native": "0.1.14",
|
|
104
104
|
"@startsimpli/auth": "0.4.50",
|
|
105
|
-
"@startsimpli/utils": "0.4.
|
|
105
|
+
"@startsimpli/utils": "0.4.18"
|
|
106
106
|
},
|
|
107
107
|
"scripts": {
|
|
108
108
|
"type-check": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Liabilities as generic entities, and a payoff scenario as a focus variant
|
|
3
|
+
* (bd startsim-a01ps.8).
|
|
4
|
+
*
|
|
5
|
+
* One `liability` type with a free-text subtype maps onto the payoff engine's
|
|
6
|
+
* `PayoffDebt`; a scenario is a `focus` with subtype `payoff_scenario` whose
|
|
7
|
+
* `params` the engine reads. Nothing here is stored that can be computed.
|
|
8
|
+
*/
|
|
9
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
10
|
+
import {
|
|
11
|
+
LIABILITY_TYPE,
|
|
12
|
+
PAYOFF_SCENARIO,
|
|
13
|
+
liabilitiesToPayoffDebts,
|
|
14
|
+
liabilityToEntity,
|
|
15
|
+
liabilityToPayoffDebt,
|
|
16
|
+
scenarioFocusDraft,
|
|
17
|
+
scenarioParamsFromFocus,
|
|
18
|
+
toLiability,
|
|
19
|
+
} from '../corpus/liabilities';
|
|
20
|
+
import { runPayoffScenario } from '../corpus/liability-plan';
|
|
21
|
+
import { createLiabilityApi } from '../corpus/liability-client';
|
|
22
|
+
import { createPlanningApi } from '../corpus/client';
|
|
23
|
+
import { focusToEntity, toFocus } from '../corpus/planning';
|
|
24
|
+
|
|
25
|
+
const SCOPE = { orgId: 'o' } as never;
|
|
26
|
+
|
|
27
|
+
function row(over: Record<string, unknown> = {}) {
|
|
28
|
+
return {
|
|
29
|
+
id: 'l1', entity_type: LIABILITY_TYPE, external_id: 'liability:l1', name: 'Visa',
|
|
30
|
+
data: { title: 'Visa', subtype: 'credit_card', status: 'active', balance: 5000, apr: 21.99, min_payment: 125, ...over },
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
describe('toLiability / liabilityToEntity', () => {
|
|
35
|
+
it('reads the shared fields and keeps the kind a free string', () => {
|
|
36
|
+
const l = toLiability(row({ subtype: 'boat_loan', credit_limit: 9000 }), { orgId: 'o' });
|
|
37
|
+
expect(l).toMatchObject({ title: 'Visa', subtype: 'boat_loan', status: 'active', balance: 5000, apr: 21.99, minPayment: 125, creditLimit: 9000 });
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('leaves an absent balance absent, never 0', () => {
|
|
41
|
+
const l = toLiability(row({ balance: undefined }), { orgId: 'o' });
|
|
42
|
+
expect(l.balance).toBeUndefined();
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('accepts numbers that arrive as strings', () => {
|
|
46
|
+
const l = toLiability(row({ balance: '5000.50', apr: '21.99' }), { orgId: 'o' });
|
|
47
|
+
expect([l.balance, l.apr]).toEqual([5000.5, 21.99]);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('falls back to active for a status that did not survive the round trip', () => {
|
|
51
|
+
expect(toLiability(row({ status: 'weird' }), { orgId: 'o' }).status).toBe('active');
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('writes the upsert payload under the liability type, with an authored origin', () => {
|
|
55
|
+
const e = liabilityToEntity({ title: 'Visa', subtype: 'credit_card', balance: 5000, apr: 21.99, minPayment: 125 }, 'liability:abc');
|
|
56
|
+
expect(e).toMatchObject({
|
|
57
|
+
entity_type: 'liability', external_id: 'liability:abc', name: 'Visa',
|
|
58
|
+
data: { title: 'Visa', subtype: 'credit_card', status: 'active', balance: 5000, apr: 21.99, min_payment: 125, _origin: 'human' },
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('omits what was not given instead of writing nulls', () => {
|
|
63
|
+
const { data } = liabilityToEntity({ title: 'Visa', subtype: 'credit_card' }, 'liability:abc');
|
|
64
|
+
expect(Object.keys(data)).not.toContain('balance');
|
|
65
|
+
expect(Object.keys(data)).not.toContain('apr');
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
describe('liabilityToPayoffDebt', () => {
|
|
70
|
+
it('maps balance, apr and minimum payment onto the engine shape', () => {
|
|
71
|
+
const l = toLiability(row(), { orgId: 'o' });
|
|
72
|
+
expect(liabilityToPayoffDebt(l)).toEqual({ id: 'l1', name: 'Visa', balance: 5000, apr: 21.99, minPayment: 125 });
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('leaves out debts the plan cannot pay down: paid off, closed, deferred or no balance', () => {
|
|
76
|
+
const mk = (over: Record<string, unknown>) => toLiability(row(over), { orgId: 'o' });
|
|
77
|
+
expect(liabilityToPayoffDebt(mk({ status: 'paid_off' }))).toBeNull();
|
|
78
|
+
expect(liabilityToPayoffDebt(mk({ status: 'closed' }))).toBeNull();
|
|
79
|
+
expect(liabilityToPayoffDebt(mk({ status: 'deferred' }))).toBeNull();
|
|
80
|
+
expect(liabilityToPayoffDebt(mk({ balance: 0 }))).toBeNull();
|
|
81
|
+
expect(liabilityToPayoffDebt(mk({ balance: undefined }))).toBeNull();
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('treats a missing apr or minimum as zero rather than dropping the debt', () => {
|
|
85
|
+
const l = toLiability(row({ apr: undefined, min_payment: undefined }), { orgId: 'o' });
|
|
86
|
+
expect(liabilityToPayoffDebt(l)).toMatchObject({ apr: 0, minPayment: 0 });
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('maps a list and skips the ineligible', () => {
|
|
90
|
+
const ls = [toLiability(row(), { orgId: 'o' }), toLiability(row({ status: 'closed' }), { orgId: 'o' })];
|
|
91
|
+
expect(liabilitiesToPayoffDebts(ls)).toHaveLength(1);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
describe('a payoff scenario is a focus variant', () => {
|
|
96
|
+
const params = { strategy: 'avalanche' as const, monthlyPayment: 600, startDate: '2026-12-01' };
|
|
97
|
+
|
|
98
|
+
it('builds a focus draft with the subtype, params and a parent', () => {
|
|
99
|
+
const draft = scenarioFocusDraft('Avalanche $600', params, { parentId: 'plan1' });
|
|
100
|
+
expect(draft).toMatchObject({ title: 'Avalanche $600', subtype: PAYOFF_SCENARIO, params: { strategy: 'avalanche', monthly_payment: 600, start_date: '2026-12-01' }, parentId: 'plan1' });
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it('round-trips through the focus entity', () => {
|
|
104
|
+
const draft = scenarioFocusDraft('Avalanche $600', params);
|
|
105
|
+
const e = focusToEntity(draft, 'focus:s1');
|
|
106
|
+
expect(e.data.subtype).toBe('payoff_scenario');
|
|
107
|
+
const focus = toFocus({ id: 'f1', entity_type: 'focus', external_id: 'focus:s1', name: 'x', data: e.data } as never, { orgId: 'o' });
|
|
108
|
+
expect(scenarioParamsFromFocus(focus)).toEqual(params);
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it('is not a scenario when the subtype is something else or the params are unusable', () => {
|
|
112
|
+
const base = toFocus({ id: 'f', entity_type: 'focus', external_id: 'focus:x', name: 'x', data: { title: 'x' } } as never, { orgId: 'o' });
|
|
113
|
+
expect(scenarioParamsFromFocus(base)).toBeNull();
|
|
114
|
+
expect(scenarioParamsFromFocus({ ...base, subtype: PAYOFF_SCENARIO, params: { strategy: 'nope' } })).toBeNull();
|
|
115
|
+
expect(scenarioParamsFromFocus({ ...base, subtype: PAYOFF_SCENARIO, params: { strategy: 'snowball', monthly_payment: -5 } })).toBeNull();
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it('an ordinary focus entity carries no subtype or params keys', () => {
|
|
119
|
+
expect(Object.keys(focusToEntity({ title: 'Plain' }).data)).not.toContain('subtype');
|
|
120
|
+
expect(Object.keys(focusToEntity({ title: 'Plain' }).data)).not.toContain('params');
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
describe('runPayoffScenario', () => {
|
|
125
|
+
const ls = [
|
|
126
|
+
toLiability(row({ title: 'Visa', balance: 5000, apr: 21.99, min_payment: 125 }), { orgId: 'o' }),
|
|
127
|
+
toLiability({ ...row(), id: 'l2', external_id: 'liability:l2', name: 'Car', data: { title: 'Car', subtype: 'auto_loan', balance: 8000, apr: 5, min_payment: 200 } }, { orgId: 'o' }),
|
|
128
|
+
];
|
|
129
|
+
|
|
130
|
+
it('runs the shared engine over the eligible liabilities', () => {
|
|
131
|
+
const r = runPayoffScenario(ls, { strategy: 'avalanche', monthlyPayment: 600, startDate: '2026-12-01' });
|
|
132
|
+
expect(r.debts.map((d) => d.id)).toEqual(['l1', 'l2']);
|
|
133
|
+
expect(r.schedule.paidOff).toBe(true);
|
|
134
|
+
expect(r.schedule.strategy).toBe('avalanche');
|
|
135
|
+
expect(r.labels).toEqual([{ id: 'l1', name: 'Visa' }, { id: 'l2', name: 'Car' }]);
|
|
136
|
+
expect(r.startingBalance).toBe(13000);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it('avalanche costs no more interest than snowball here', () => {
|
|
140
|
+
const a = runPayoffScenario(ls, { strategy: 'avalanche', monthlyPayment: 600 });
|
|
141
|
+
const s = runPayoffScenario(ls, { strategy: 'snowball', monthlyPayment: 600 });
|
|
142
|
+
expect(a.schedule.totalInterest).toBeLessThanOrEqual(s.schedule.totalInterest);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it('defaults the budget to the sum of minimums when none is given', () => {
|
|
146
|
+
const r = runPayoffScenario(ls, { strategy: 'avalanche' });
|
|
147
|
+
expect(r.monthlyPayment).toBe(325);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it('answers an empty plan without throwing when nothing is eligible', () => {
|
|
151
|
+
const r = runPayoffScenario([], { strategy: 'avalanche', monthlyPayment: 100 });
|
|
152
|
+
expect(r.debts).toEqual([]);
|
|
153
|
+
expect(r.schedule.months).toEqual([]);
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
describe('the liability client', () => {
|
|
158
|
+
function tenant() {
|
|
159
|
+
const gets: Array<{ path: string; params: Record<string, unknown> }> = [];
|
|
160
|
+
const posts: Array<{ path: string; body: unknown }> = [];
|
|
161
|
+
const http = {
|
|
162
|
+
get: vi.fn(async (path: string, o?: { params?: Record<string, unknown> }) => {
|
|
163
|
+
gets.push({ path, params: o?.params ?? {} });
|
|
164
|
+
return { count: 1, next: null, previous: null, results: [row()] };
|
|
165
|
+
}),
|
|
166
|
+
post: vi.fn(async (path: string, body: unknown) => {
|
|
167
|
+
posts.push({ path, body });
|
|
168
|
+
return { ...row(), data: (body as { data: object }).data };
|
|
169
|
+
}),
|
|
170
|
+
};
|
|
171
|
+
return { gets, posts, api: createLiabilityApi({ http: http as never, scope: SCOPE }) };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
it('lists liabilities server-side, active first by default, one page at a time', async () => {
|
|
175
|
+
const { api, gets } = tenant();
|
|
176
|
+
const page = await api.listLiabilities({ pageSize: 50 });
|
|
177
|
+
expect(page.results[0].title).toBe('Visa');
|
|
178
|
+
expect(gets[0].params).toMatchObject({ type: 'liability', page: 1, page_size: 50 });
|
|
179
|
+
expect(gets[0].params['attr.status']).toBeUndefined();
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
it('filters by status and subtype only when asked', async () => {
|
|
183
|
+
const { api, gets } = tenant();
|
|
184
|
+
await api.listLiabilities({ status: 'active', subtype: 'credit_card' });
|
|
185
|
+
expect(gets[0].params).toMatchObject({ 'attr.status': 'active', 'attr.subtype': 'credit_card' });
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it('creates through the shallow-merging upsert', async () => {
|
|
189
|
+
const { api, posts } = tenant();
|
|
190
|
+
const made = await api.createLiability({ title: 'Visa', subtype: 'credit_card', balance: 5000 });
|
|
191
|
+
expect(posts[0].path).toBe('api/v1/entities/upsert');
|
|
192
|
+
expect(made.title).toBe('Visa');
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
it('updates only the keys it was given, so an edit cannot resurrect a closed debt', async () => {
|
|
196
|
+
const { api, posts } = tenant();
|
|
197
|
+
const l = toLiability(row({ status: 'closed' }), { orgId: 'o' });
|
|
198
|
+
await api.updateLiability(l, { balance: 4000 });
|
|
199
|
+
const body = posts[0].body as { data: Record<string, unknown>; external_id: string };
|
|
200
|
+
expect(body.external_id).toBe('liability:l1');
|
|
201
|
+
expect(body.data).toEqual({ title: 'Visa', balance: 4000 });
|
|
202
|
+
});
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
describe('listing focuses on a tenant that never declared a subtype', () => {
|
|
206
|
+
it('sends no attr.subtype unless the caller asks, so a live tenant cannot 400', async () => {
|
|
207
|
+
const gets: Array<Record<string, unknown>> = [];
|
|
208
|
+
const http = { get: vi.fn(async (_p: string, o?: { params?: Record<string, unknown> }) => { gets.push(o?.params ?? {}); return { count: 0, results: [] }; }) };
|
|
209
|
+
const api = createPlanningApi({ http: http as never, scope: SCOPE });
|
|
210
|
+
await api.listFocuses({});
|
|
211
|
+
expect(Object.keys(gets[0])).not.toContain('attr.subtype');
|
|
212
|
+
await api.listFocuses({ subtype: 'payoff_scenario' });
|
|
213
|
+
expect(gets[1]['attr.subtype']).toBe('payoff_scenario');
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
it('patches subtype and params through updateFocus', async () => {
|
|
217
|
+
const posts: Array<{ data: Record<string, unknown> }> = [];
|
|
218
|
+
const http = { get: vi.fn(), post: vi.fn(async (_p: string, b: { data: Record<string, unknown> }) => { posts.push(b); return { id: 'f', entity_type: 'focus', external_id: 'focus:s', name: 's', data: b.data }; }) };
|
|
219
|
+
const api = createPlanningApi({ http: http as never, scope: SCOPE });
|
|
220
|
+
const focus = toFocus({ id: 'f', entity_type: 'focus', external_id: 'focus:s', name: 's', data: { title: 's' } } as never, { orgId: 'o' });
|
|
221
|
+
await api.updateFocus!(focus, { params: { strategy: 'snowball', monthly_payment: 400 } });
|
|
222
|
+
expect(posts[0].data.params).toEqual({ strategy: 'snowball', monthly_payment: 400 });
|
|
223
|
+
});
|
|
224
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** The Debt plan composer: lists liabilities, runs the scenario, saves it as a focus (bd startsim-a01ps.8). */
|
|
2
|
+
import { render, screen, waitFor } from '@testing-library/react';
|
|
3
|
+
import userEvent from '@testing-library/user-event';
|
|
4
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
5
|
+
import { LiabilityPlanPage } from '../components/pages/LiabilityPlanPage';
|
|
6
|
+
import { toLiability } from '../corpus/liabilities';
|
|
7
|
+
|
|
8
|
+
const mk = (id: string, title: string, balance: number, apr: number, min: number) => toLiability(
|
|
9
|
+
{ id, entity_type: 'liability', external_id: `liability:${id}`, name: title, data: { title, subtype: 'credit_card', status: 'active', balance, apr, min_payment: min } } as never,
|
|
10
|
+
{ orgId: 'o' },
|
|
11
|
+
);
|
|
12
|
+
|
|
13
|
+
function setup() {
|
|
14
|
+
const createFocus = vi.fn(async (d: { title: string }) => ({ id: 'f', title: d.title }) as never);
|
|
15
|
+
const api = {
|
|
16
|
+
listLiabilities: vi.fn(async () => ({ count: 2, next: null, previous: null, results: [mk('a', 'Visa', 5000, 22, 125), mk('b', 'Auto', 8000, 5, 200)] })),
|
|
17
|
+
listFocuses: vi.fn(async () => ({ count: 0, next: null, previous: null, results: [] })),
|
|
18
|
+
createFocus,
|
|
19
|
+
};
|
|
20
|
+
render(<LiabilityPlanPage api={api as never} now={Date.parse('2026-11-07T00:00:00Z')} />);
|
|
21
|
+
return { api, createFocus };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
describe('LiabilityPlanPage', () => {
|
|
25
|
+
it('shows what is owed and a debt-free summary', async () => {
|
|
26
|
+
setup();
|
|
27
|
+
expect(await screen.findByText('2 liabilities · $13,000 owed')).toBeTruthy();
|
|
28
|
+
expect(screen.getAllByTestId('liability-row')).toHaveLength(2);
|
|
29
|
+
expect(screen.getByTestId('payoff-summary')).toBeTruthy();
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('asks for scenario focuses only by subtype', async () => {
|
|
33
|
+
const { api } = setup();
|
|
34
|
+
await screen.findByTestId('liability-plan');
|
|
35
|
+
expect(api.listFocuses).toHaveBeenCalledWith({ subtype: 'payoff_scenario', pageSize: 50 });
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('saves a scenario only on click', async () => {
|
|
39
|
+
const { createFocus } = setup();
|
|
40
|
+
await screen.findByTestId('save-scenario');
|
|
41
|
+
expect(createFocus).not.toHaveBeenCalled();
|
|
42
|
+
await userEvent.click(screen.getByTestId('save-scenario'));
|
|
43
|
+
await waitFor(() => expect(createFocus).toHaveBeenCalledTimes(1));
|
|
44
|
+
expect(createFocus.mock.calls[0][0]).toMatchObject({ subtype: 'payoff_scenario', params: { strategy: 'avalanche' } });
|
|
45
|
+
});
|
|
46
|
+
});
|
package/src/components/index.ts
CHANGED
|
@@ -53,6 +53,7 @@ export { ExternalLinkChip } from './pages/task-tracker/ExternalLinkChip';
|
|
|
53
53
|
// row, the honesty banner, the overdue/changed predicates — so two views over
|
|
54
54
|
// one list cannot drift into disagreeing about what they mean.
|
|
55
55
|
export * from './pages/PlanningPage';
|
|
56
|
+
export * from './pages/LiabilityPlanPage';
|
|
56
57
|
export {
|
|
57
58
|
PRIORITY_LABELS,
|
|
58
59
|
UnfilteredNotice,
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* LIABILITY PLAN — what is owed, and how fast a payoff scenario clears it
|
|
5
|
+
* (bd startsim-a01ps.8).
|
|
6
|
+
*
|
|
7
|
+
* A composer over two shared things and adds almost nothing of its own: the
|
|
8
|
+
* tenant's generic `liability` rows (via `LiabilityApi`) and the payoff UI in
|
|
9
|
+
* `@startsimpli/ui/payoff`, fed by `runPayoffScenario` (the shared engine).
|
|
10
|
+
*
|
|
11
|
+
* A SCENARIO IS A FOCUS. "Save scenario" writes a `focus` with subtype
|
|
12
|
+
* `payoff_scenario`; saved ones are listed back with `listFocuses({subtype})`.
|
|
13
|
+
* Saving is an explicit click and NEVER an effect: a render that wrote would be
|
|
14
|
+
* the write-loop recorded on `TrackerPageProps.now`.
|
|
15
|
+
*/
|
|
16
|
+
import * as React from 'react';
|
|
17
|
+
import {
|
|
18
|
+
PayoffBalanceChart,
|
|
19
|
+
PayoffScheduleTable,
|
|
20
|
+
PayoffSummaryCards,
|
|
21
|
+
RangeSlider,
|
|
22
|
+
ScenarioCompare,
|
|
23
|
+
moneyWhole,
|
|
24
|
+
} from '@startsimpli/ui/payoff';
|
|
25
|
+
import type { PayoffStrategy } from '@startsimpli/utils';
|
|
26
|
+
|
|
27
|
+
import type { LiabilityApi } from '../../corpus/liability-client';
|
|
28
|
+
import { runPayoffScenario } from '../../corpus/liability-plan';
|
|
29
|
+
import {
|
|
30
|
+
PAYOFF_SCENARIO,
|
|
31
|
+
scenarioFocusDraft,
|
|
32
|
+
scenarioParamsFromFocus,
|
|
33
|
+
type Liability,
|
|
34
|
+
type PayoffScenarioParams,
|
|
35
|
+
} from '../../corpus/liabilities';
|
|
36
|
+
import type { Focus, PlanningApi } from '../../corpus/types';
|
|
37
|
+
|
|
38
|
+
export interface LiabilityPlanPageProps {
|
|
39
|
+
api: LiabilityApi & Partial<Pick<PlanningApi, 'listFocuses' | 'createFocus'>>;
|
|
40
|
+
/** Epoch ms. Injected so a render never reads the clock. */
|
|
41
|
+
now: number;
|
|
42
|
+
/** Nest saved scenarios under this focus (the plan they vary). */
|
|
43
|
+
parentFocusId?: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const KINDS = ['credit_card', 'mortgage', 'student_loan', 'auto_loan', 'personal_loan', 'line_of_credit', 'other'];
|
|
47
|
+
const label = (s: string) => s.replace(/_/g, ' ');
|
|
48
|
+
const strategyName = (s: PayoffStrategy) => (s === 'avalanche' ? 'Avalanche' : 'Snowball');
|
|
49
|
+
|
|
50
|
+
/** First day of the month after `now`, as the engine's `startDate`. */
|
|
51
|
+
function nextMonthStart(now: number): string {
|
|
52
|
+
const d = new Date(now);
|
|
53
|
+
return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1)).toISOString().slice(0, 10);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function LiabilityPlanPage({ api, now, parentFocusId }: LiabilityPlanPageProps) {
|
|
57
|
+
const [liabilities, setLiabilities] = React.useState<Liability[] | null>(null);
|
|
58
|
+
const [saved, setSaved] = React.useState<Array<{ focus: Focus; params: PayoffScenarioParams }>>([]);
|
|
59
|
+
const [error, setError] = React.useState<string | null>(null);
|
|
60
|
+
const [strategy, setStrategy] = React.useState<PayoffStrategy>('avalanche');
|
|
61
|
+
const [extra, setExtra] = React.useState(300);
|
|
62
|
+
const startDate = React.useMemo(() => nextMonthStart(now), [now]);
|
|
63
|
+
|
|
64
|
+
const apiRef = React.useRef(api);
|
|
65
|
+
apiRef.current = api;
|
|
66
|
+
|
|
67
|
+
const load = React.useCallback(async () => {
|
|
68
|
+
try {
|
|
69
|
+
const page = await apiRef.current.listLiabilities({ pageSize: 200 });
|
|
70
|
+
setLiabilities(page.results);
|
|
71
|
+
const focuses = await apiRef.current.listFocuses?.({ subtype: PAYOFF_SCENARIO, pageSize: 50 });
|
|
72
|
+
setSaved((focuses?.results ?? []).flatMap((focus) => {
|
|
73
|
+
const params = scenarioParamsFromFocus(focus);
|
|
74
|
+
return params ? [{ focus, params }] : [];
|
|
75
|
+
}));
|
|
76
|
+
} catch (e) {
|
|
77
|
+
setError(e instanceof Error ? e.message : 'Could not load liabilities.');
|
|
78
|
+
}
|
|
79
|
+
}, []);
|
|
80
|
+
React.useEffect(() => { void load(); }, [load]);
|
|
81
|
+
|
|
82
|
+
const base = React.useMemo(
|
|
83
|
+
() => runPayoffScenario(liabilities ?? [], { strategy, startDate }),
|
|
84
|
+
[liabilities, strategy, startDate],
|
|
85
|
+
);
|
|
86
|
+
const minimums = base.monthlyPayment;
|
|
87
|
+
const payment = minimums + extra;
|
|
88
|
+
const params: PayoffScenarioParams = { strategy, monthlyPayment: payment, startDate };
|
|
89
|
+
const current = React.useMemo(() => runPayoffScenario(liabilities ?? [], params), [liabilities, strategy, payment, startDate]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
90
|
+
|
|
91
|
+
const scenarios = React.useMemo(() => {
|
|
92
|
+
const L = liabilities ?? [];
|
|
93
|
+
const other: PayoffStrategy = strategy === 'avalanche' ? 'snowball' : 'avalanche';
|
|
94
|
+
return [
|
|
95
|
+
{ id: 'minimums', label: 'Minimums only', schedule: runPayoffScenario(L, { strategy, monthlyPayment: minimums, startDate }).schedule },
|
|
96
|
+
{ id: 'current', label: `${strategyName(strategy)} at ${moneyWhole(payment)}/mo`, schedule: current.schedule },
|
|
97
|
+
{ id: 'other', label: `${strategyName(other)} at ${moneyWhole(payment)}/mo`, schedule: runPayoffScenario(L, { strategy: other, monthlyPayment: payment, startDate }).schedule },
|
|
98
|
+
...saved.map((s) => ({
|
|
99
|
+
id: s.focus.id,
|
|
100
|
+
label: `${s.focus.title} (saved)`,
|
|
101
|
+
schedule: runPayoffScenario(L, { startDate, ...s.params }).schedule,
|
|
102
|
+
})),
|
|
103
|
+
];
|
|
104
|
+
}, [liabilities, strategy, minimums, payment, startDate, current, saved]);
|
|
105
|
+
|
|
106
|
+
async function addLiability(form: HTMLFormElement) {
|
|
107
|
+
const f = new FormData(form);
|
|
108
|
+
const n = (k: string) => (String(f.get(k) ?? '').trim() === '' ? undefined : Number(f.get(k)));
|
|
109
|
+
try {
|
|
110
|
+
await apiRef.current.createLiability?.({
|
|
111
|
+
title: String(f.get('title') ?? '').trim(),
|
|
112
|
+
subtype: String(f.get('subtype') ?? 'other'),
|
|
113
|
+
balance: n('balance'), apr: n('apr'), minPayment: n('minPayment'),
|
|
114
|
+
});
|
|
115
|
+
form.reset();
|
|
116
|
+
await load();
|
|
117
|
+
} catch (e) {
|
|
118
|
+
setError(e instanceof Error ? e.message : 'Could not add the liability.');
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function saveScenario() {
|
|
123
|
+
try {
|
|
124
|
+
await apiRef.current.createFocus?.(
|
|
125
|
+
scenarioFocusDraft(`${strategyName(strategy)} at ${moneyWhole(payment)}/mo`, params, { parentId: parentFocusId }),
|
|
126
|
+
);
|
|
127
|
+
await load();
|
|
128
|
+
} catch (e) {
|
|
129
|
+
setError(e instanceof Error ? e.message : 'Could not save the scenario.');
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (liabilities === null && !error) return <p data-testid="liabilities-loading">Loading liabilities…</p>;
|
|
134
|
+
|
|
135
|
+
const total = (liabilities ?? []).reduce((s, l) => s + (l.status === 'active' ? l.balance ?? 0 : 0), 0);
|
|
136
|
+
return (
|
|
137
|
+
<div className="space-y-8" data-testid="liability-plan">
|
|
138
|
+
<header className="space-y-1">
|
|
139
|
+
<h1 className="text-2xl font-semibold">Debt plan</h1>
|
|
140
|
+
<p className="text-sm text-muted-foreground" data-testid="liability-total">
|
|
141
|
+
{liabilities?.length ?? 0} liabilities · {moneyWhole(total)} owed
|
|
142
|
+
</p>
|
|
143
|
+
</header>
|
|
144
|
+
{error ? <p role="alert" className="text-sm text-red-600">{error}</p> : null}
|
|
145
|
+
|
|
146
|
+
<section className="space-y-2">
|
|
147
|
+
<h2 className="text-lg font-medium">Liabilities</h2>
|
|
148
|
+
{liabilities?.length ? (
|
|
149
|
+
<table className="w-full text-sm" data-testid="liability-table">
|
|
150
|
+
<thead><tr className="text-left text-muted-foreground"><th>Name</th><th>Kind</th><th className="text-right">Balance</th><th className="text-right">APR</th><th className="text-right">Minimum</th></tr></thead>
|
|
151
|
+
<tbody>
|
|
152
|
+
{liabilities.map((l) => (
|
|
153
|
+
<tr key={l.id} data-testid="liability-row">
|
|
154
|
+
<td>{l.title}</td><td className="capitalize">{label(l.subtype)}</td>
|
|
155
|
+
<td className="text-right tabular-nums">{l.balance !== undefined ? moneyWhole(l.balance) : '—'}</td>
|
|
156
|
+
<td className="text-right tabular-nums">{l.apr !== undefined ? `${l.apr}%` : '—'}</td>
|
|
157
|
+
<td className="text-right tabular-nums">{l.minPayment !== undefined ? moneyWhole(l.minPayment) : '—'}</td>
|
|
158
|
+
</tr>
|
|
159
|
+
))}
|
|
160
|
+
</tbody>
|
|
161
|
+
</table>
|
|
162
|
+
) : <p className="text-sm text-muted-foreground">Nothing owed yet. Add a liability below.</p>}
|
|
163
|
+
{api.createLiability ? (
|
|
164
|
+
<form className="flex flex-wrap items-end gap-2" onSubmit={(e) => { e.preventDefault(); void addLiability(e.currentTarget); }} data-testid="liability-form">
|
|
165
|
+
<input name="title" required placeholder="Name" aria-label="Name" className="rounded-md border px-2 py-1" />
|
|
166
|
+
<select name="subtype" aria-label="Kind" className="rounded-md border px-2 py-1">{KINDS.map((k) => <option key={k} value={k}>{label(k)}</option>)}</select>
|
|
167
|
+
<input name="balance" type="number" min="0" step="any" placeholder="Balance" aria-label="Balance" className="w-28 rounded-md border px-2 py-1" />
|
|
168
|
+
<input name="apr" type="number" min="0" max="100" step="any" placeholder="APR %" aria-label="APR" className="w-24 rounded-md border px-2 py-1" />
|
|
169
|
+
<input name="minPayment" type="number" min="0" step="any" placeholder="Minimum" aria-label="Minimum payment" className="w-28 rounded-md border px-2 py-1" />
|
|
170
|
+
<button type="submit" className="rounded-md border px-3 py-1">Add liability</button>
|
|
171
|
+
</form>
|
|
172
|
+
) : null}
|
|
173
|
+
</section>
|
|
174
|
+
|
|
175
|
+
{current.debts.length ? (
|
|
176
|
+
<>
|
|
177
|
+
<section className="grid gap-6 sm:grid-cols-2">
|
|
178
|
+
<RangeSlider label="Extra per month" min={0} max={1500} step={25} value={extra} onChange={setExtra} format={moneyWhole} />
|
|
179
|
+
<div className="space-y-2">
|
|
180
|
+
<p className="text-sm font-medium">Strategy</p>
|
|
181
|
+
<div className="flex gap-2">
|
|
182
|
+
{(['avalanche', 'snowball'] as const).map((s) => (
|
|
183
|
+
<button key={s} type="button" onClick={() => setStrategy(s)} aria-pressed={strategy === s}
|
|
184
|
+
className={'rounded-md border px-3 py-1.5 text-sm capitalize ' + (strategy === s ? 'bg-primary text-primary-foreground' : '')}>{s}</button>
|
|
185
|
+
))}
|
|
186
|
+
</div>
|
|
187
|
+
</div>
|
|
188
|
+
</section>
|
|
189
|
+
<PayoffSummaryCards schedule={current.schedule} startingBalance={current.startingBalance} currentBalance={current.startingBalance} />
|
|
190
|
+
<PayoffBalanceChart schedule={current.schedule} debts={current.labels} />
|
|
191
|
+
<section className="space-y-2">
|
|
192
|
+
<div className="flex items-center justify-between">
|
|
193
|
+
<h2 className="text-lg font-medium">Scenarios</h2>
|
|
194
|
+
{api.createFocus ? <button type="button" onClick={() => void saveScenario()} className="rounded-md border px-3 py-1 text-sm" data-testid="save-scenario">Save this scenario</button> : null}
|
|
195
|
+
</div>
|
|
196
|
+
<ScenarioCompare scenarios={scenarios} />
|
|
197
|
+
</section>
|
|
198
|
+
<section className="space-y-2"><h2 className="text-lg font-medium">Payment schedule</h2><PayoffScheduleTable schedule={current.schedule} debts={current.labels} /></section>
|
|
199
|
+
</>
|
|
200
|
+
) : null}
|
|
201
|
+
</div>
|
|
202
|
+
);
|
|
203
|
+
}
|
package/src/corpus/client.ts
CHANGED
|
@@ -1164,6 +1164,8 @@ const FOCUS_PATCH_KEYS: Record<string, keyof FocusDraft> = {
|
|
|
1164
1164
|
detail: 'detail',
|
|
1165
1165
|
status: 'status',
|
|
1166
1166
|
category: 'category',
|
|
1167
|
+
subtype: 'subtype',
|
|
1168
|
+
params: 'params',
|
|
1167
1169
|
time_frame: 'timeFrame',
|
|
1168
1170
|
year: 'year',
|
|
1169
1171
|
start_date: 'startDate',
|
|
@@ -1234,6 +1236,7 @@ export function createPlanningApi(options: CreateCorpusApiOptions): PlanningApi
|
|
|
1234
1236
|
if (statuses.length === 1) out['attr.status'] = statuses[0];
|
|
1235
1237
|
else if (statuses.length > 1) out['attr.status__in'] = statuses.join(',');
|
|
1236
1238
|
if (query.category) out['attr.category'] = query.category;
|
|
1239
|
+
if (query.subtype) out['attr.subtype'] = query.subtype;
|
|
1237
1240
|
if (query.timeFrame) out['attr.time_frame'] = query.timeFrame;
|
|
1238
1241
|
if (query.year !== undefined) out['attr.year'] = query.year;
|
|
1239
1242
|
if (query.owner) out['attr.owner_sub'] = query.owner;
|
package/src/corpus/index.ts
CHANGED
|
@@ -313,3 +313,7 @@ export * from './questions';
|
|
|
313
313
|
export { patchEditedItem } from './commitment-edit';
|
|
314
314
|
export * from './owner-link';
|
|
315
315
|
export * from './owner-backfill';
|
|
316
|
+
// Liabilities as generic entities + a payoff scenario as a focus variant (bd startsim-a01ps.8).
|
|
317
|
+
export * from './liabilities';
|
|
318
|
+
export * from './liability-plan';
|
|
319
|
+
export * from './liability-client';
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LIABILITIES — one generic entity for anything owed, and the mapping from it to
|
|
3
|
+
* the payoff engine (bd startsim-a01ps.8, under startsim-a01ps).
|
|
4
|
+
*
|
|
5
|
+
* THE SHAPE. A tenant stores a `liability` entity with a FREE-TEXT `subtype`
|
|
6
|
+
* (credit_card, mortgage, student_loan, auto_loan, ...), so a new kind of debt
|
|
7
|
+
* costs a string and not a table. Everything the payoff engine needs is on the
|
|
8
|
+
* entity itself: balance, apr, min_payment. Kind-specific remainder (escrow,
|
|
9
|
+
* PMI, servicer address) lives in one `details` bag that no shared logic reads.
|
|
10
|
+
*
|
|
11
|
+
* A SCENARIO IS A FOCUS, not a new type: a `focus` with subtype
|
|
12
|
+
* `payoff_scenario` whose `params` are {strategy, monthly_payment, start_date}.
|
|
13
|
+
* Variants of a plan are child focuses (the existing `sub_focus` edge). The
|
|
14
|
+
* schedule itself is never stored; `runPayoffScenario` computes it.
|
|
15
|
+
*
|
|
16
|
+
* PURE and React-free: this file is reachable from the native build through the
|
|
17
|
+
* corpus barrel. The engine call lives in `liability-plan.ts`.
|
|
18
|
+
*/
|
|
19
|
+
import type { PayoffDebt, PayoffStrategy } from '@startsimpli/utils';
|
|
20
|
+
import { ORIGIN, ORIGIN_KEY, type TenantEntity } from './entities';
|
|
21
|
+
import type { CorpusScope, Focus, FocusDraft } from './types';
|
|
22
|
+
|
|
23
|
+
/** The entity type key, matching `scripts/schemas/liabilities.json`. */
|
|
24
|
+
export const LIABILITY_TYPE = 'liability';
|
|
25
|
+
/** The focus subtype that makes a focus a payoff scenario. */
|
|
26
|
+
export const PAYOFF_SCENARIO = 'payoff_scenario';
|
|
27
|
+
|
|
28
|
+
export type LiabilityStatus = 'active' | 'deferred' | 'paid_off' | 'closed';
|
|
29
|
+
const STATUSES: readonly LiabilityStatus[] = ['active', 'deferred', 'paid_off', 'closed'];
|
|
30
|
+
const STRATEGIES: readonly PayoffStrategy[] = ['avalanche', 'snowball'];
|
|
31
|
+
|
|
32
|
+
export interface Liability {
|
|
33
|
+
id: string;
|
|
34
|
+
externalId: string;
|
|
35
|
+
title: string;
|
|
36
|
+
/** Free text. Nothing but display branches on it. */
|
|
37
|
+
subtype: string;
|
|
38
|
+
status: LiabilityStatus;
|
|
39
|
+
institution?: string;
|
|
40
|
+
currency?: string;
|
|
41
|
+
/** Absent means unknown, which is not the same as 0 (paid). */
|
|
42
|
+
balance?: number;
|
|
43
|
+
/** Annual percent, e.g. 19.99. */
|
|
44
|
+
apr?: number;
|
|
45
|
+
minPayment?: number;
|
|
46
|
+
nextDueDate?: string;
|
|
47
|
+
lastPaymentAmount?: number;
|
|
48
|
+
lastPaymentDate?: string;
|
|
49
|
+
creditLimit?: number;
|
|
50
|
+
originalPrincipal?: number;
|
|
51
|
+
originationDate?: string;
|
|
52
|
+
maturityDate?: string;
|
|
53
|
+
pastDueAmount?: number;
|
|
54
|
+
details?: Record<string, unknown>;
|
|
55
|
+
scope: CorpusScope;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export type LiabilityDraft = Partial<Omit<Liability, 'id' | 'externalId' | 'scope'>> & { title: string };
|
|
59
|
+
|
|
60
|
+
// ---------------------------------------------------------------------------
|
|
61
|
+
// reading
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
|
|
64
|
+
function bag(entity: TenantEntity): Record<string, unknown> {
|
|
65
|
+
const data = entity.data;
|
|
66
|
+
return data && typeof data === 'object' ? (data as Record<string, unknown>) : {};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** snake_case first, camelCase second: the api client may have converted keys. */
|
|
70
|
+
function pick(data: Record<string, unknown>, snake: string): unknown {
|
|
71
|
+
const camel = snake.replace(/_([a-z])/g, (_m, c: string) => c.toUpperCase());
|
|
72
|
+
for (const key of [snake, camel]) {
|
|
73
|
+
const value = data[key];
|
|
74
|
+
if (value !== undefined && value !== null && value !== '') return value;
|
|
75
|
+
}
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function text(value: unknown): string | undefined {
|
|
80
|
+
return typeof value === 'string' && value ? value : undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function num(value: unknown): number | undefined {
|
|
84
|
+
if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;
|
|
85
|
+
if (typeof value === 'string' && value.trim()) {
|
|
86
|
+
const parsed = Number(value);
|
|
87
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
88
|
+
}
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function defined<T extends object>(obj: T): Partial<T> {
|
|
93
|
+
return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined)) as Partial<T>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function toLiability(entity: TenantEntity, fallbackScope: CorpusScope): Liability {
|
|
97
|
+
const d = bag(entity);
|
|
98
|
+
const status = text(pick(d, 'status'));
|
|
99
|
+
const details = pick(d, 'details');
|
|
100
|
+
return {
|
|
101
|
+
id: String(entity.id),
|
|
102
|
+
externalId: String(entity.external_id ?? entity.externalId ?? `${LIABILITY_TYPE}:${entity.id}`),
|
|
103
|
+
title: text(pick(d, 'title')) || entity.name || 'Untitled liability',
|
|
104
|
+
subtype: text(pick(d, 'subtype')) || 'other',
|
|
105
|
+
// `active` is the floor: a debt whose status did not survive a round trip is
|
|
106
|
+
// still owed, and hiding it from the plan would understate what is owed.
|
|
107
|
+
status: (STATUSES as readonly string[]).includes(status ?? '') ? (status as LiabilityStatus) : 'active',
|
|
108
|
+
...defined({
|
|
109
|
+
institution: text(pick(d, 'institution')),
|
|
110
|
+
currency: text(pick(d, 'currency')),
|
|
111
|
+
balance: num(pick(d, 'balance')),
|
|
112
|
+
apr: num(pick(d, 'apr')),
|
|
113
|
+
minPayment: num(pick(d, 'min_payment')),
|
|
114
|
+
nextDueDate: text(pick(d, 'next_due_date')),
|
|
115
|
+
lastPaymentAmount: num(pick(d, 'last_payment_amount')),
|
|
116
|
+
lastPaymentDate: text(pick(d, 'last_payment_date')),
|
|
117
|
+
creditLimit: num(pick(d, 'credit_limit')),
|
|
118
|
+
originalPrincipal: num(pick(d, 'original_principal')),
|
|
119
|
+
originationDate: text(pick(d, 'origination_date')),
|
|
120
|
+
maturityDate: text(pick(d, 'maturity_date')),
|
|
121
|
+
pastDueAmount: num(pick(d, 'past_due_amount')),
|
|
122
|
+
details: details && typeof details === 'object' && !Array.isArray(details)
|
|
123
|
+
? (details as Record<string, unknown>) : undefined,
|
|
124
|
+
}),
|
|
125
|
+
scope: { orgId: String(entity.org_id ?? entity.orgId ?? fallbackScope.orgId), ...(fallbackScope.ownerSub ? { ownerSub: fallbackScope.ownerSub } : {}) },
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ---------------------------------------------------------------------------
|
|
130
|
+
// writing
|
|
131
|
+
// ---------------------------------------------------------------------------
|
|
132
|
+
|
|
133
|
+
/** Draft key -> the declared attribute that carries it. The write AND the patch map. */
|
|
134
|
+
export const LIABILITY_ATTRIBUTES: Record<string, keyof LiabilityDraft> = {
|
|
135
|
+
subtype: 'subtype',
|
|
136
|
+
status: 'status',
|
|
137
|
+
institution: 'institution',
|
|
138
|
+
currency: 'currency',
|
|
139
|
+
balance: 'balance',
|
|
140
|
+
apr: 'apr',
|
|
141
|
+
min_payment: 'minPayment',
|
|
142
|
+
next_due_date: 'nextDueDate',
|
|
143
|
+
last_payment_amount: 'lastPaymentAmount',
|
|
144
|
+
last_payment_date: 'lastPaymentDate',
|
|
145
|
+
credit_limit: 'creditLimit',
|
|
146
|
+
original_principal: 'originalPrincipal',
|
|
147
|
+
origination_date: 'originationDate',
|
|
148
|
+
maturity_date: 'maturityDate',
|
|
149
|
+
past_due_amount: 'pastDueAmount',
|
|
150
|
+
details: 'details',
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
export function liabilityToEntity(draft: LiabilityDraft, externalId: string, options: { create?: boolean } = {}): {
|
|
154
|
+
entity_type: string;
|
|
155
|
+
external_id: string;
|
|
156
|
+
name: string;
|
|
157
|
+
data: Record<string, unknown>;
|
|
158
|
+
} {
|
|
159
|
+
const title = draft.title.trim() || 'Untitled liability';
|
|
160
|
+
const data: Record<string, unknown> = { title };
|
|
161
|
+
for (const [attr, key] of Object.entries(LIABILITY_ATTRIBUTES)) {
|
|
162
|
+
const value = draft[key];
|
|
163
|
+
if (value !== undefined && value !== null) data[attr] = value;
|
|
164
|
+
}
|
|
165
|
+
if (options.create !== false) {
|
|
166
|
+
// Defaults only on create: merging them into a patch would reopen a closed debt.
|
|
167
|
+
data.status ??= 'active';
|
|
168
|
+
data.subtype ??= 'other';
|
|
169
|
+
data[ORIGIN_KEY] = ORIGIN.authored;
|
|
170
|
+
}
|
|
171
|
+
return { entity_type: LIABILITY_TYPE, external_id: externalId, name: title.slice(0, 200), data };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// ---------------------------------------------------------------------------
|
|
175
|
+
// -> the payoff engine
|
|
176
|
+
// ---------------------------------------------------------------------------
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* One liability as the engine's debt, or `null` when a plan cannot pay it down:
|
|
180
|
+
* not `active`, or nothing owed. A missing apr/minimum is 0 rather than a reason
|
|
181
|
+
* to drop the debt, because dropping it would make the plan finish early.
|
|
182
|
+
*/
|
|
183
|
+
export function liabilityToPayoffDebt(l: Liability): PayoffDebt | null {
|
|
184
|
+
if (l.status !== 'active') return null;
|
|
185
|
+
if (l.balance === undefined || !(l.balance > 0)) return null;
|
|
186
|
+
return { id: l.id, name: l.title, balance: l.balance, apr: l.apr ?? 0, minPayment: l.minPayment ?? 0 };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function liabilitiesToPayoffDebts(ls: readonly Liability[]): PayoffDebt[] {
|
|
190
|
+
return ls.map(liabilityToPayoffDebt).filter((d): d is PayoffDebt => d !== null);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// ---------------------------------------------------------------------------
|
|
194
|
+
// scenario <-> focus
|
|
195
|
+
// ---------------------------------------------------------------------------
|
|
196
|
+
|
|
197
|
+
export interface PayoffScenarioParams {
|
|
198
|
+
strategy: PayoffStrategy;
|
|
199
|
+
/** Total per month across all debts; absent means "just the minimums". */
|
|
200
|
+
monthlyPayment?: number;
|
|
201
|
+
/** ISO date of the first payment month. */
|
|
202
|
+
startDate?: string;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** A scenario as the focus draft that stores it. `parentId` nests it under the plan it varies. */
|
|
206
|
+
export function scenarioFocusDraft(
|
|
207
|
+
title: string,
|
|
208
|
+
params: PayoffScenarioParams,
|
|
209
|
+
options: { parentId?: string } = {},
|
|
210
|
+
): FocusDraft {
|
|
211
|
+
return {
|
|
212
|
+
title,
|
|
213
|
+
category: 'financial',
|
|
214
|
+
subtype: PAYOFF_SCENARIO,
|
|
215
|
+
params: {
|
|
216
|
+
strategy: params.strategy,
|
|
217
|
+
...(params.monthlyPayment !== undefined ? { monthly_payment: params.monthlyPayment } : {}),
|
|
218
|
+
...(params.startDate ? { start_date: params.startDate } : {}),
|
|
219
|
+
},
|
|
220
|
+
...(options.parentId ? { parentId: options.parentId } : {}),
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** The scenario a focus describes, or `null` when it is not one or its params are unusable. */
|
|
225
|
+
export function scenarioParamsFromFocus(focus: Pick<Focus, 'subtype' | 'params'>): PayoffScenarioParams | null {
|
|
226
|
+
if (focus.subtype !== PAYOFF_SCENARIO || !focus.params) return null;
|
|
227
|
+
const strategy = text(pick(focus.params, 'strategy'));
|
|
228
|
+
if (!strategy || !(STRATEGIES as readonly string[]).includes(strategy)) return null;
|
|
229
|
+
const raw = pick(focus.params, 'monthly_payment');
|
|
230
|
+
const monthlyPayment = num(raw);
|
|
231
|
+
if (raw !== undefined && (monthlyPayment === undefined || monthlyPayment < 0)) return null;
|
|
232
|
+
const startDate = text(pick(focus.params, 'start_date'));
|
|
233
|
+
return {
|
|
234
|
+
strategy: strategy as PayoffStrategy,
|
|
235
|
+
...(monthlyPayment !== undefined ? { monthlyPayment } : {}),
|
|
236
|
+
...(startDate ? { startDate } : {}),
|
|
237
|
+
};
|
|
238
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tenant client for liabilities (bd startsim-a01ps.8).
|
|
3
|
+
*
|
|
4
|
+
* Its own file because `client.ts` is already past the size budget, and a
|
|
5
|
+
* deployment can have planning with no liabilities schema at all. Every write is
|
|
6
|
+
* the shallow-merging upsert keyed on `external_id`, the one tenant verb that
|
|
7
|
+
* preserves keys the caller did not send.
|
|
8
|
+
*/
|
|
9
|
+
import { authoredId } from './planning';
|
|
10
|
+
import type { CorpusHttp, CreateCorpusApiOptions } from './client';
|
|
11
|
+
import type { TenantEntity } from './entities';
|
|
12
|
+
import {
|
|
13
|
+
LIABILITY_TYPE,
|
|
14
|
+
liabilityToEntity,
|
|
15
|
+
toLiability,
|
|
16
|
+
type Liability,
|
|
17
|
+
type LiabilityDraft,
|
|
18
|
+
type LiabilityStatus,
|
|
19
|
+
} from './liabilities';
|
|
20
|
+
import type { CorpusPage } from './types';
|
|
21
|
+
|
|
22
|
+
export interface LiabilityQuery {
|
|
23
|
+
status?: LiabilityStatus | LiabilityStatus[];
|
|
24
|
+
subtype?: string;
|
|
25
|
+
search?: string;
|
|
26
|
+
page?: number;
|
|
27
|
+
pageSize?: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface LiabilityApi {
|
|
31
|
+
listLiabilities(query?: LiabilityQuery): Promise<CorpusPage<Liability>>;
|
|
32
|
+
createLiability?(draft: LiabilityDraft): Promise<Liability>;
|
|
33
|
+
/** Takes the row so the external id is the row's own; sends only the keys in `patch`. */
|
|
34
|
+
updateLiability?(liability: Liability, patch: Partial<LiabilityDraft>): Promise<Liability>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface Page {
|
|
38
|
+
count?: number;
|
|
39
|
+
next?: string | null;
|
|
40
|
+
previous?: string | null;
|
|
41
|
+
results?: TenantEntity[];
|
|
42
|
+
applied_filters?: string[];
|
|
43
|
+
appliedFilters?: string[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function createLiabilityApi(options: Pick<CreateCorpusApiOptions, 'http' | 'scope' | 'paths'>): LiabilityApi {
|
|
47
|
+
const { http, scope } = options;
|
|
48
|
+
const entities = options.paths?.entities ?? 'api/v1/entities';
|
|
49
|
+
const writer = (): NonNullable<CorpusHttp['post']> => {
|
|
50
|
+
if (!http.post) throw new Error('This liability client is read-only — no write method was supplied.');
|
|
51
|
+
return http.post.bind(http);
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
async listLiabilities(query: LiabilityQuery = {}) {
|
|
56
|
+
const statuses = Array.isArray(query.status) ? query.status : query.status ? [query.status] : [];
|
|
57
|
+
const params: Record<string, unknown> = {
|
|
58
|
+
type: LIABILITY_TYPE,
|
|
59
|
+
page: query.page ?? 1,
|
|
60
|
+
// Largest balance first: the debts that matter most lead the page.
|
|
61
|
+
order: '-attr.balance',
|
|
62
|
+
...(query.pageSize ? { page_size: Math.min(query.pageSize, 200) } : {}),
|
|
63
|
+
};
|
|
64
|
+
if (statuses.length === 1) params['attr.status'] = statuses[0];
|
|
65
|
+
else if (statuses.length > 1) params['attr.status__in'] = statuses.join(',');
|
|
66
|
+
if (query.subtype) params['attr.subtype'] = query.subtype;
|
|
67
|
+
if (query.search) params.search = query.search.slice(0, 200);
|
|
68
|
+
const response = await http.get<Page>(entities, { params });
|
|
69
|
+
return {
|
|
70
|
+
count: response.count ?? response.results?.length ?? 0,
|
|
71
|
+
next: response.next ?? null,
|
|
72
|
+
previous: response.previous ?? null,
|
|
73
|
+
results: (response.results ?? []).map((e) => toLiability(e, scope)),
|
|
74
|
+
appliedFilters: response.applied_filters ?? response.appliedFilters ?? [],
|
|
75
|
+
};
|
|
76
|
+
},
|
|
77
|
+
|
|
78
|
+
async createLiability(draft) {
|
|
79
|
+
const created = await writer()<TenantEntity>(
|
|
80
|
+
`${entities}/upsert`,
|
|
81
|
+
liabilityToEntity(draft, `${LIABILITY_TYPE}:${authoredId()}`),
|
|
82
|
+
);
|
|
83
|
+
return toLiability(created, scope);
|
|
84
|
+
},
|
|
85
|
+
|
|
86
|
+
async updateLiability(liability, patch) {
|
|
87
|
+
const body = liabilityToEntity(
|
|
88
|
+
{ ...patch, title: patch.title ?? liability.title },
|
|
89
|
+
liability.externalId,
|
|
90
|
+
{ create: false },
|
|
91
|
+
);
|
|
92
|
+
const updated = await writer()<TenantEntity>(`${entities}/upsert`, {
|
|
93
|
+
entity_type: LIABILITY_TYPE,
|
|
94
|
+
external_id: liability.externalId,
|
|
95
|
+
...(patch.title ? { name: body.name } : {}),
|
|
96
|
+
data: body.data,
|
|
97
|
+
});
|
|
98
|
+
return toLiability(updated, scope);
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs a payoff scenario over liabilities with the SHARED engine
|
|
3
|
+
* (`buildPayoffSchedule`, @startsimpli/utils). Nothing is reimplemented here:
|
|
4
|
+
* this is the join between the tenant's rows and the engine's input.
|
|
5
|
+
*/
|
|
6
|
+
import { buildPayoffSchedule } from '@startsimpli/utils';
|
|
7
|
+
import type { PayoffDebt, PayoffSchedule } from '@startsimpli/utils';
|
|
8
|
+
import { liabilitiesToPayoffDebts, type Liability, type PayoffScenarioParams } from './liabilities';
|
|
9
|
+
|
|
10
|
+
export interface PayoffScenarioRun {
|
|
11
|
+
debts: PayoffDebt[];
|
|
12
|
+
/** `{id, name}` pairs in the shape `@startsimpli/ui/payoff` takes. */
|
|
13
|
+
labels: Array<{ id: string; name: string }>;
|
|
14
|
+
schedule: PayoffSchedule;
|
|
15
|
+
/** The budget actually used: the scenario's, or the sum of minimums. */
|
|
16
|
+
monthlyPayment: number;
|
|
17
|
+
startingBalance: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function runPayoffScenario(
|
|
21
|
+
liabilities: readonly Liability[],
|
|
22
|
+
params: PayoffScenarioParams,
|
|
23
|
+
): PayoffScenarioRun {
|
|
24
|
+
const debts = liabilitiesToPayoffDebts(liabilities);
|
|
25
|
+
const minimums = debts.reduce((sum, d) => sum + d.minPayment, 0);
|
|
26
|
+
const monthlyPayment = params.monthlyPayment ?? minimums;
|
|
27
|
+
const schedule = buildPayoffSchedule({
|
|
28
|
+
debts,
|
|
29
|
+
monthlyPayment,
|
|
30
|
+
strategy: params.strategy,
|
|
31
|
+
...(params.startDate ? { startDate: params.startDate } : {}),
|
|
32
|
+
});
|
|
33
|
+
return {
|
|
34
|
+
debts,
|
|
35
|
+
labels: debts.map((d) => ({ id: d.id, name: d.name ?? d.id })),
|
|
36
|
+
schedule,
|
|
37
|
+
monthlyPayment,
|
|
38
|
+
startingBalance: debts.reduce((sum, d) => sum + d.balance, 0),
|
|
39
|
+
};
|
|
40
|
+
}
|
package/src/corpus/planning.ts
CHANGED
|
@@ -120,6 +120,10 @@ function num(value: unknown): number | undefined {
|
|
|
120
120
|
return undefined;
|
|
121
121
|
}
|
|
122
122
|
|
|
123
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
124
|
+
return !!value && typeof value === 'object' && !Array.isArray(value);
|
|
125
|
+
}
|
|
126
|
+
|
|
123
127
|
function oneOf<T extends string>(value: unknown, allowed: readonly T[]): T | undefined {
|
|
124
128
|
const raw = text(value);
|
|
125
129
|
return (allowed as readonly string[]).includes(raw) ? (raw as T) : undefined;
|
|
@@ -147,6 +151,8 @@ export function toFocus(entity: TenantEntity, fallbackScope: CorpusScope): Focus
|
|
|
147
151
|
status: oneOf(pick(data, 'status'), FOCUS_STATUSES) ?? 'draft',
|
|
148
152
|
...(oneOf(pick(data, 'category'), FOCUS_CATEGORIES)
|
|
149
153
|
? { category: oneOf(pick(data, 'category'), FOCUS_CATEGORIES) } : {}),
|
|
154
|
+
...(pick(data, 'subtype') ? { subtype: text(pick(data, 'subtype')) } : {}),
|
|
155
|
+
...(isPlainObject(data.params) ? { params: data.params } : {}),
|
|
150
156
|
...(oneOf(pick(data, 'time_frame', 'timeFrame'), FOCUS_TIME_FRAMES)
|
|
151
157
|
? { timeFrame: oneOf(pick(data, 'time_frame', 'timeFrame'), FOCUS_TIME_FRAMES) } : {}),
|
|
152
158
|
...(year !== undefined ? { year } : {}),
|
|
@@ -186,6 +192,8 @@ export function focusToEntity(draft: FocusDraft, externalId?: string): {
|
|
|
186
192
|
...(draft.detail ? { detail: draft.detail } : {}),
|
|
187
193
|
status: draft.status ?? 'active',
|
|
188
194
|
...(draft.category ? { category: draft.category } : {}),
|
|
195
|
+
...(draft.subtype ? { subtype: draft.subtype } : {}),
|
|
196
|
+
...(draft.params ? { params: draft.params } : {}),
|
|
189
197
|
...(draft.timeFrame ? { time_frame: draft.timeFrame } : {}),
|
|
190
198
|
...(draft.year !== undefined && draft.year !== null ? { year: draft.year } : {}),
|
|
191
199
|
...(draft.startDate ? { start_date: draft.startDate } : {}),
|
package/src/corpus/types.ts
CHANGED
|
@@ -1397,6 +1397,10 @@ export interface Focus {
|
|
|
1397
1397
|
detail: string;
|
|
1398
1398
|
status: FocusStatus;
|
|
1399
1399
|
category?: FocusCategory;
|
|
1400
|
+
/** What KIND of focus: free text, absent for an ordinary one (bd startsim-a01ps.8). */
|
|
1401
|
+
subtype?: string;
|
|
1402
|
+
/** The subtype's own inputs, one JSON object. Read by a pure function, never filtered on. */
|
|
1403
|
+
params?: Record<string, unknown>;
|
|
1400
1404
|
timeFrame?: FocusTimeFrame;
|
|
1401
1405
|
year?: number | null;
|
|
1402
1406
|
startDate?: string | null;
|
|
@@ -1434,6 +1438,8 @@ export interface FocusDraft {
|
|
|
1434
1438
|
detail?: string;
|
|
1435
1439
|
status?: FocusStatus;
|
|
1436
1440
|
category?: FocusCategory;
|
|
1441
|
+
subtype?: string;
|
|
1442
|
+
params?: Record<string, unknown>;
|
|
1437
1443
|
timeFrame?: FocusTimeFrame;
|
|
1438
1444
|
year?: number | null;
|
|
1439
1445
|
startDate?: string | null;
|
|
@@ -1450,6 +1456,9 @@ export interface FocusDraft {
|
|
|
1450
1456
|
export interface FocusQuery {
|
|
1451
1457
|
status?: FocusStatus | FocusStatus[];
|
|
1452
1458
|
category?: FocusCategory;
|
|
1459
|
+
/** Only sent when set: a tenant that never declared `subtype` answers an
|
|
1460
|
+
* undeclared attribute filter with a 400. */
|
|
1461
|
+
subtype?: string;
|
|
1453
1462
|
timeFrame?: FocusTimeFrame;
|
|
1454
1463
|
year?: number;
|
|
1455
1464
|
owner?: string;
|