policyengine-household-wizard 0.2.0 → 0.4.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.
Files changed (80) hide show
  1. package/README.md +30 -4
  2. package/dist/{index-B_OXaS4a.cjs → index-BfoPBFne.cjs} +1 -1
  3. package/dist/index-CIL8FXNR.cjs +1 -0
  4. package/dist/{index-DWM0giHt.js → index-DoD0AXHz.js} +72 -70
  5. package/dist/index-fgLnXugs.js +225 -0
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.ts +2 -2
  8. package/dist/index.js +1 -1
  9. package/dist/primitives/index.d.ts +12 -12
  10. package/dist/primitives/useWizardSteps.d.ts +1 -1
  11. package/dist/primitives.d.ts +1 -1
  12. package/dist/uk-household/adapters/householdImpactRequest.d.ts +91 -0
  13. package/dist/uk-household/adapters/householdImpactRequest.d.ts.map +1 -0
  14. package/dist/uk-household/adapters/index.d.ts +2 -0
  15. package/dist/uk-household/adapters/index.d.ts.map +1 -0
  16. package/dist/uk-household/children.d.ts +18 -0
  17. package/dist/uk-household/children.d.ts.map +1 -0
  18. package/dist/uk-household/codes.d.ts +22 -0
  19. package/dist/uk-household/codes.d.ts.map +1 -0
  20. package/dist/uk-household/defaults.d.ts +56 -0
  21. package/dist/uk-household/defaults.d.ts.map +1 -0
  22. package/dist/uk-household/draft.d.ts +37 -0
  23. package/dist/uk-household/draft.d.ts.map +1 -0
  24. package/dist/uk-household/index.d.ts +10 -0
  25. package/dist/uk-household/index.d.ts.map +1 -0
  26. package/dist/uk-household/serialize.d.ts +4 -0
  27. package/dist/uk-household/serialize.d.ts.map +1 -0
  28. package/dist/uk-household/statePension.d.ts +42 -0
  29. package/dist/uk-household/statePension.d.ts.map +1 -0
  30. package/dist/uk-household/types.d.ts +134 -0
  31. package/dist/uk-household/types.d.ts.map +1 -0
  32. package/dist/uk-household/validate.d.ts +59 -0
  33. package/dist/uk-household/validate.d.ts.map +1 -0
  34. package/dist/uk-household-adapters.cjs +1 -0
  35. package/dist/uk-household-adapters.d.ts +1 -0
  36. package/dist/uk-household-adapters.js +5 -0
  37. package/dist/uk-household.cjs +1 -0
  38. package/dist/uk-household.d.ts +1 -0
  39. package/dist/uk-household.js +220 -0
  40. package/dist/us-household/adapters/index.d.ts +1 -1
  41. package/dist/us-household/adapters/v1Payload.d.ts +1 -1
  42. package/dist/us-household/adapters/v1Payload.d.ts.map +1 -1
  43. package/dist/us-household/draft.d.ts +1 -1
  44. package/dist/us-household/draft.d.ts.map +1 -1
  45. package/dist/us-household/index.d.ts +9 -9
  46. package/dist/us-household/normalize.d.ts +1 -1
  47. package/dist/us-household/normalize.d.ts.map +1 -1
  48. package/dist/us-household/serialize.d.ts +1 -1
  49. package/dist/us-household/serialize.d.ts.map +1 -1
  50. package/dist/us-household/types.d.ts +9 -14
  51. package/dist/us-household/types.d.ts.map +1 -1
  52. package/dist/us-household/validate.d.ts +1 -1
  53. package/dist/us-household/validate.d.ts.map +1 -1
  54. package/dist/us-household-adapters.cjs +1 -1
  55. package/dist/us-household-adapters.d.ts +1 -1
  56. package/dist/us-household-adapters.js +1 -1
  57. package/dist/us-household.cjs +1 -1
  58. package/dist/us-household.d.ts +1 -1
  59. package/dist/us-household.js +213 -200
  60. package/dist/validation.d.ts +16 -0
  61. package/dist/validation.d.ts.map +1 -0
  62. package/package.json +13 -2
  63. package/src/uk-household/adapters/householdImpactRequest.ts +164 -0
  64. package/src/uk-household/adapters/index.ts +9 -0
  65. package/src/uk-household/children.ts +23 -0
  66. package/src/uk-household/codes.ts +67 -0
  67. package/src/uk-household/defaults.ts +101 -0
  68. package/src/uk-household/draft.ts +138 -0
  69. package/src/uk-household/index.ts +75 -0
  70. package/src/uk-household/serialize.ts +189 -0
  71. package/src/uk-household/statePension.ts +69 -0
  72. package/src/uk-household/types.ts +159 -0
  73. package/src/uk-household/validate.ts +190 -0
  74. package/src/us-household/adapters/v1Payload.ts +4 -0
  75. package/src/us-household/draft.ts +1 -0
  76. package/src/us-household/normalize.ts +3 -0
  77. package/src/us-household/serialize.ts +6 -0
  78. package/src/us-household/types.ts +9 -11
  79. package/src/us-household/validate.ts +15 -0
  80. package/src/validation.ts +12 -0
@@ -0,0 +1,189 @@
1
+ import { isUKCouncilTaxBand, isUKRegion, isUKStudentLoanPlan, isUKTenure } from './codes';
2
+ import { createBlankDraft } from './draft';
3
+ import type { UKAdultDraft, UKChildDraft, UKHeadDraft, UKHouseholdDraft } from './types';
4
+
5
+ /**
6
+ * A compact, URL-safe form of a UK household draft, so apps that share the
7
+ * model can link to the same household. The keys are stable:
8
+ *
9
+ * sy=2026&region=LONDON&tenure=RENT_PRIVATELY&rent=1500&band=D&uc=1
10
+ * &you=34:e42000:lPLAN_2&hp=1&partner=33:e28000&c=7,17n
11
+ * &petrol=620&diesel=340&elec=1040&cc=400
12
+ *
13
+ * - `sy`: the salary year; `region`, `tenure`, `band`: codes; `uc`: 1 or 0
14
+ * for claiming Universal Credit. Unanswered choices are left out.
15
+ * - `rent`: monthly rent, left out for the regional average (`null`).
16
+ * - `you` and `partner`: the age (empty when unanswered), then
17
+ * colon-separated tokens, each a letter and a number: `e` employment
18
+ * income, `p` private pension, `s` State Pension (left out for the full
19
+ * rate), and for `you` only `x` salary sacrifice, `d` dividends, `i` savings
20
+ * interest, `r` property income and `l` the student loan plan (a code).
21
+ * Amounts of 0 and a plan of `NONE` are left out. `partner` is written
22
+ * whenever it holds answers, with or without a partner (`hp=1`).
23
+ * - `c`: each child's age (empty when unanswered), comma-separated, with `y`
24
+ * or `n` after it once their education is answered.
25
+ * - `petrol`, `diesel`, `cc` (childcare a month): left out when 0; `elec`:
26
+ * left out for the default (`null`).
27
+ *
28
+ * `extras` are not written, nor is an age, year or amount that is not a
29
+ * finite number: it comes back blank, and the salary year as the default
30
+ * year. A child missing from the list (a hole or `null`) is written as an
31
+ * unanswered child, and an education answer other than true or false is
32
+ * not written. A private pension or electricity left out (`undefined`)
33
+ * comes back as 0 or `null`, which mean the same. Unknown codes in a link
34
+ * are read as unanswered (a plan as `NONE`), and an amount that is not a
35
+ * number keeps its blank value.
36
+ */
37
+
38
+ type NumberKey<T> = { [K in keyof T]-?: T[K] extends number | null | undefined ? K : never }[keyof T];
39
+
40
+ const ADULT_TOKENS: Array<[NumberKey<UKAdultDraft>, string]> = [
41
+ ['employmentIncome', 'e'],
42
+ ['privatePensionIncome', 'p'],
43
+ ['statePension', 's'],
44
+ ];
45
+
46
+ const HEAD_TOKENS: Array<[NumberKey<UKHeadDraft>, string]> = [
47
+ ['salarySacrificePensionContributions', 'x'],
48
+ ['dividendIncome', 'd'],
49
+ ['savingsInterestIncome', 'i'],
50
+ ['propertyIncome', 'r'],
51
+ ];
52
+
53
+ const PLAN_TOKEN = 'l';
54
+
55
+ const blank = createBlankDraft();
56
+
57
+ // Only a finite number is written; anything else reads back blank
58
+ const isFiniteNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);
59
+
60
+ // An age as written: empty when unanswered (or not a finite number)
61
+ const writeAge = (age: unknown) => (isFiniteNumber(age) ? String(age) : '');
62
+
63
+ function writeAdult(adult: UKAdultDraft, tokens: Array<[string, string]>): string {
64
+ const record = adult as unknown as Record<string, unknown>;
65
+ const segments = [writeAge(adult.age)];
66
+ for (const [key, letter] of tokens) {
67
+ const value = record[key];
68
+ if (!isFiniteNumber(value)) continue;
69
+ // The State Pension's blank is null (the full rate), so its 0 is an answer
70
+ if (value === 0 && key !== 'statePension') continue;
71
+ segments.push(`${letter}${value}`);
72
+ }
73
+ return segments.join(':');
74
+ }
75
+
76
+ // A finite number, or undefined; -0 is read as 0, as it is written
77
+ function readNumber(text: string): number | undefined {
78
+ if (text.trim() === '') return undefined;
79
+ const value = Number(text);
80
+ if (!Number.isFinite(value)) return undefined;
81
+ return value === 0 ? 0 : value;
82
+ }
83
+
84
+ function readAdult<T extends UKAdultDraft>(raw: string, base: T, tokens: Array<[string, string]>): T {
85
+ const [ageText = '', ...rest] = raw.split(':');
86
+ const adult = { ...base };
87
+ const fields = adult as unknown as Record<string, unknown>;
88
+ adult.age = readNumber(ageText) ?? null;
89
+ for (const token of rest) {
90
+ const letter = token[0];
91
+ const text = token.slice(1);
92
+ if (letter === PLAN_TOKEN && 'studentLoanPlan' in base) {
93
+ (adult as unknown as UKHeadDraft).studentLoanPlan = isUKStudentLoanPlan(text) ? text : 'NONE';
94
+ continue;
95
+ }
96
+ const match = tokens.find(([, l]) => l === letter);
97
+ const value = readNumber(text);
98
+ if (match && value !== undefined) fields[match[0]] = value;
99
+ }
100
+ return adult;
101
+ }
102
+
103
+ // A missing child (a hole in the list, or null) is written as an unanswered one
104
+ function writeChild(child: UKChildDraft | null | undefined): string {
105
+ const age = writeAge(child?.age);
106
+ const education = child?.inEducation === true ? 'y' : child?.inEducation === false ? 'n' : '';
107
+ return `${age}${education}`;
108
+ }
109
+
110
+ function readChild(raw: string): UKChildDraft {
111
+ const last = raw.slice(-1);
112
+ const answered = last === 'y' || last === 'n';
113
+ const child: UKChildDraft = { age: readNumber(answered ? raw.slice(0, -1) : raw) ?? null };
114
+ if (answered) child.inEducation = last === 'y';
115
+ return child;
116
+ }
117
+
118
+ const sameAdult = (a: UKAdultDraft, b: UKAdultDraft) =>
119
+ a.age === b.age &&
120
+ a.employmentIncome === b.employmentIncome &&
121
+ (a.privatePensionIncome ?? 0) === (b.privatePensionIncome ?? 0) &&
122
+ a.statePension === b.statePension;
123
+
124
+ export function serializeDraft(draft: UKHouseholdDraft): string {
125
+ const params = new URLSearchParams();
126
+ if (isFiniteNumber(draft.salaryYear)) params.set('sy', String(draft.salaryYear));
127
+ if (draft.region) params.set('region', draft.region);
128
+ if (draft.tenure) params.set('tenure', draft.tenure);
129
+ if (isFiniteNumber(draft.monthlyRent)) params.set('rent', String(draft.monthlyRent));
130
+ if (draft.councilTaxBand) params.set('band', draft.councilTaxBand);
131
+ if (typeof draft.claimsUniversalCredit === 'boolean') params.set('uc', draft.claimsUniversalCredit ? '1' : '0');
132
+
133
+ let you = writeAdult(draft.head, [...ADULT_TOKENS, ...HEAD_TOKENS]);
134
+ if (draft.head.studentLoanPlan && draft.head.studentLoanPlan !== 'NONE') {
135
+ you += `:${PLAN_TOKEN}${draft.head.studentLoanPlan}`;
136
+ }
137
+ params.set('you', you);
138
+ if (draft.hasPartner) params.set('hp', '1');
139
+ if (draft.hasPartner || !sameAdult(draft.partner, blank.partner)) {
140
+ params.set('partner', writeAdult(draft.partner, ADULT_TOKENS));
141
+ }
142
+ if (draft.children.length > 0) params.set('c', Array.from(draft.children, writeChild).join(','));
143
+
144
+ const { petrol, diesel, electricity } = draft.spending;
145
+ if (isFiniteNumber(petrol) && petrol !== 0) params.set('petrol', String(petrol));
146
+ if (isFiniteNumber(diesel) && diesel !== 0) params.set('diesel', String(diesel));
147
+ if (isFiniteNumber(electricity)) params.set('elec', String(electricity));
148
+ if (isFiniteNumber(draft.monthlyChildcare) && draft.monthlyChildcare !== 0) {
149
+ params.set('cc', String(draft.monthlyChildcare));
150
+ }
151
+ return params.toString();
152
+ }
153
+
154
+ export function deserializeDraft(query: string | URLSearchParams): UKHouseholdDraft {
155
+ const params = typeof query === 'string' ? new URLSearchParams(query) : query;
156
+ const draft = createBlankDraft();
157
+ const number = (key: string) => {
158
+ const raw = params.get(key);
159
+ return raw === null ? undefined : readNumber(raw);
160
+ };
161
+
162
+ const salaryYear = number('sy');
163
+ if (salaryYear !== undefined) draft.salaryYear = salaryYear;
164
+ const region = params.get('region');
165
+ draft.region = isUKRegion(region) ? region : null;
166
+ const tenure = params.get('tenure');
167
+ draft.tenure = isUKTenure(tenure) ? tenure : null;
168
+ draft.monthlyRent = number('rent') ?? null;
169
+ const band = params.get('band');
170
+ draft.councilTaxBand = isUKCouncilTaxBand(band) ? band : null;
171
+ const uc = params.get('uc');
172
+ draft.claimsUniversalCredit = uc === '1' ? true : uc === '0' ? false : null;
173
+
174
+ const you = params.get('you');
175
+ if (you !== null) draft.head = readAdult(you, draft.head, [...ADULT_TOKENS, ...HEAD_TOKENS]);
176
+ draft.hasPartner = params.get('hp') === '1';
177
+ const partner = params.get('partner');
178
+ if (partner !== null) draft.partner = readAdult(partner, draft.partner, ADULT_TOKENS);
179
+ const children = params.get('c');
180
+ if (children !== null) draft.children = children.split(',').map(readChild);
181
+
182
+ draft.spending = {
183
+ petrol: number('petrol') ?? 0,
184
+ diesel: number('diesel') ?? 0,
185
+ electricity: number('elec') ?? null,
186
+ };
187
+ draft.monthlyChildcare = number('cc') ?? 0;
188
+ return draft;
189
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * State Pension age and the full new State Pension by policy year, as a
3
+ * table of the same shape as the Autumn Budget 2026 dashboard's
4
+ * `src/uk_budget_data/state_pension.json`, so an app can pass its own copy.
5
+ */
6
+ export interface UKStatePensionYear {
7
+ /** The youngest whole age policyengine-uk places over State Pension age in the year. */
8
+ state_pension_age: number;
9
+ /** The full new State Pension, pounds a year. */
10
+ full_new_state_pension: number;
11
+ }
12
+
13
+ export interface UKStatePensionTable {
14
+ years: Readonly<Record<string, UKStatePensionYear>>;
15
+ }
16
+
17
+ /**
18
+ * The default table: the dashboard's state_pension.json at cc15d50e, which
19
+ * its tests/test_household_impact.py checks against policyengine-uk 2.132.6
20
+ * (the version its lockfile pins). The age is the youngest whole age the
21
+ * model's `is_SP_age` counts for a person entered by age alone; the amount is
22
+ * `gov.dwp.state_pension.new_state_pension.amount` times 52, to the penny.
23
+ * Both change with the model: an app that carries a copy checked against its
24
+ * own model should pass that copy instead.
25
+ */
26
+ export const UK_STATE_PENSION: UKStatePensionTable = {
27
+ years: {
28
+ '2026': { state_pension_age: 66, full_new_state_pension: 12547.6 },
29
+ '2027': { state_pension_age: 67, full_new_state_pension: 13036.97 },
30
+ '2028': { state_pension_age: 67, full_new_state_pension: 13362.92 },
31
+ '2029': { state_pension_age: 67, full_new_state_pension: 13696.98 },
32
+ '2030': { state_pension_age: 67, full_new_state_pension: 14039.42 },
33
+ '2031': { state_pension_age: 67, full_new_state_pension: 14390.39 },
34
+ },
35
+ };
36
+
37
+ /**
38
+ * State Pension age and the full new State Pension in `year`: the table's
39
+ * row for that year, else for the first later year it has, else its last.
40
+ * So a year before the table (or 0, which apps use to compare answers without
41
+ * a year) takes its first row.
42
+ */
43
+ export function statePensionFor(
44
+ year: number,
45
+ table: UKStatePensionTable = UK_STATE_PENSION,
46
+ ): { age: number; full: number } {
47
+ const known = Object.keys(table.years)
48
+ .map(Number)
49
+ .sort((a, b) => a - b);
50
+ const nearest = known.find((known) => known >= year) ?? known[known.length - 1];
51
+ const row = table.years[String(nearest)];
52
+ return { age: row.state_pension_age, full: row.full_new_state_pension };
53
+ }
54
+
55
+ /**
56
+ * Whether someone of `age` in `year` is at State Pension age. An unanswered
57
+ * age (`null`) is not.
58
+ */
59
+ export function atStatePensionAge(
60
+ age: number | null | undefined,
61
+ year: number,
62
+ table: UKStatePensionTable = UK_STATE_PENSION,
63
+ ): boolean {
64
+ return (age as number) >= statePensionFor(year, table).age;
65
+ }
66
+
67
+ /** Whether a State Pension amount was entered: a finite number; `null` is the full rate. */
68
+ export const statePensionEntered = (value: unknown): value is number =>
69
+ typeof value === 'number' && Number.isFinite(value);
@@ -0,0 +1,159 @@
1
+ export type { ValidationIssue, ValidationResult } from '../validation';
2
+
3
+ /**
4
+ * policyengine-uk's `Region` codes: the nine English regions, Wales, Scotland
5
+ * and Northern Ireland (its `UNKNOWN` is left out).
6
+ */
7
+ export type UKRegion =
8
+ | 'NORTH_EAST'
9
+ | 'NORTH_WEST'
10
+ | 'YORKSHIRE'
11
+ | 'EAST_MIDLANDS'
12
+ | 'WEST_MIDLANDS'
13
+ | 'EAST_OF_ENGLAND'
14
+ | 'LONDON'
15
+ | 'SOUTH_EAST'
16
+ | 'SOUTH_WEST'
17
+ | 'WALES'
18
+ | 'SCOTLAND'
19
+ | 'NORTHERN_IRELAND';
20
+
21
+ /** policyengine-uk's `TenureType` codes. The first three are renting. */
22
+ export type UKTenure =
23
+ | 'RENT_PRIVATELY'
24
+ | 'RENT_FROM_COUNCIL'
25
+ | 'RENT_FROM_HA'
26
+ | 'OWNED_WITH_MORTGAGE'
27
+ | 'OWNED_OUTRIGHT';
28
+
29
+ /** policyengine-uk's `StudentLoanPlan` codes. */
30
+ export type UKStudentLoanPlan = 'NONE' | 'PLAN_1' | 'PLAN_2' | 'PLAN_4' | 'PLAN_5' | 'POSTGRADUATE';
31
+
32
+ /**
33
+ * policyengine-uk's `CouncilTaxBand` codes; band I is Wales's. Northern
34
+ * Ireland has domestic rates instead, and the household impact API estimates
35
+ * no Council Tax there.
36
+ */
37
+ export type UKCouncilTaxBand = 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I';
38
+
39
+ /**
40
+ * One adult's answers. Amounts are pounds a year.
41
+ *
42
+ * Ages are in the policy year being calculated: a calculation for 2028-29
43
+ * takes the age then, and does not age anyone from another year. Employment
44
+ * income is the other way round: it is entered for the draft's `salaryYear`
45
+ * and grown from there.
46
+ */
47
+ export interface UKAdultDraft {
48
+ /** Age in whole years in the policy year. `null` means not answered. */
49
+ age: number | null;
50
+ /** Gross earnings from employment in the draft's `salaryYear`. */
51
+ employmentIncome: number;
52
+ /**
53
+ * Private and workplace pensions in payment, before tax, not counting the
54
+ * State Pension. `null` or left out means none.
55
+ */
56
+ privatePensionIncome?: number | null;
57
+ /**
58
+ * The State Pension in the policy year (not grown like earnings). `null`
59
+ * means the full new State Pension for that year. Calculations read it only
60
+ * from State Pension age in the policy year (`atStatePensionAge`).
61
+ */
62
+ statePension: number | null;
63
+ /** App-controlled fields; the shared adapters ignore them. */
64
+ extras?: Record<string, unknown>;
65
+ }
66
+
67
+ /**
68
+ * The household's head: the person answering ("you"). The dashboard's form
69
+ * asks these for the head only, so they are not on the partner (the
70
+ * household impact API also takes a partner's student loan plan; the request
71
+ * leaves it out, so the API's default, `NONE`, applies).
72
+ */
73
+ export interface UKHeadDraft extends UKAdultDraft {
74
+ studentLoanPlan: UKStudentLoanPlan;
75
+ /** Pension contributions made by salary sacrifice. */
76
+ salarySacrificePensionContributions: number;
77
+ dividendIncome: number;
78
+ savingsInterestIncome: number;
79
+ /** Net income from property (rent received). */
80
+ propertyIncome: number;
81
+ }
82
+
83
+ export interface UKChildDraft {
84
+ /**
85
+ * Age in whole years in the policy year. policyengine-uk counts a child
86
+ * under 16 as a dependant, and a 16- to 19-year-old only in full-time
87
+ * non-advanced education (`inEducation`). Someone of 20 or over is not a
88
+ * child for Child Benefit or Universal Credit; `validate()` refuses them.
89
+ */
90
+ age: number | null;
91
+ /**
92
+ * From 16 to 19: whether they are in full-time non-advanced education
93
+ * (school or college, not university or an apprenticeship). Anything but
94
+ * `false`, including leaving it out, counts as yes. Not read under 16.
95
+ */
96
+ inEducation?: boolean;
97
+ extras?: Record<string, unknown>;
98
+ }
99
+
100
+ /** Household spending, pounds a year. */
101
+ export interface UKHouseholdSpending {
102
+ petrol: number;
103
+ diesel: number;
104
+ /**
105
+ * Domestic electricity, including VAT. `null` or left out means the
106
+ * calculation's own default, the average UK household's
107
+ * (`UK_DEFAULT_SPENDING.electricity`).
108
+ */
109
+ electricity?: number | null;
110
+ }
111
+
112
+ /**
113
+ * A UK household: a head, an optional partner and their children, as one
114
+ * benefit unit, plus where and how they live.
115
+ *
116
+ * The policy year is not part of the draft. Apps choose it apart from the
117
+ * answers (the Autumn Budget dashboard's year pill reruns the same answers),
118
+ * so `validate()` and the adapters take it as an option.
119
+ */
120
+ export interface UKHouseholdDraft {
121
+ /**
122
+ * The year `employmentIncome` amounts are entered for. The household
123
+ * impact API grows them to the policy year with the OBR average earnings
124
+ * index, so this year must not be after the policy year.
125
+ */
126
+ salaryYear: number;
127
+ /** `null` means not answered. */
128
+ region: UKRegion | null;
129
+ head: UKHeadDraft;
130
+ /** Whether the head lives with a partner. */
131
+ hasPartner: boolean;
132
+ /**
133
+ * The partner's answers. They are kept while `hasPartner` is false, so
134
+ * turning it back on restores them; calculations read them only with a
135
+ * partner.
136
+ */
137
+ partner: UKAdultDraft;
138
+ /** Dependent children, in the order apps show them ("Child 1", ...). */
139
+ children: UKChildDraft[];
140
+ /** `null` means not answered. */
141
+ tenure: UKTenure | null;
142
+ /**
143
+ * Rent a month, read only when renting. `null` means the region's average
144
+ * private rent (`regionalRent`).
145
+ */
146
+ monthlyRent: number | null;
147
+ /** `null` means not answered. */
148
+ councilTaxBand: UKCouncilTaxBand | null;
149
+ /**
150
+ * Whether the household would claim Universal Credit if entitled. `null`
151
+ * means not answered.
152
+ */
153
+ claimsUniversalCredit: boolean | null;
154
+ /** Paid childcare a month, for all children together; read only with children. */
155
+ monthlyChildcare: number;
156
+ spending: UKHouseholdSpending;
157
+ /** App-controlled household-level fields; the shared adapters ignore them. */
158
+ extras?: Record<string, unknown>;
159
+ }
@@ -0,0 +1,190 @@
1
+ import { UK_CHILD_AGE_MESSAGE, UK_OLDEST_CHILD_AGE } from './children';
2
+ import { isRenting, isUKCouncilTaxBand, isUKRegion, isUKStudentLoanPlan, isUKTenure } from './codes';
3
+ import { atStatePensionAge, statePensionEntered, type UKStatePensionTable } from './statePension';
4
+ import type { UKChildDraft, UKHouseholdDraft, ValidationIssue, ValidationResult } from './types';
5
+
6
+ /**
7
+ * The bounds the Autumn Budget 2026 dashboard's household impact API puts on
8
+ * each answer (`HouseholdAnswersRequest` in its src/uk_budget_data/api.py),
9
+ * which `validate()` applies. Amounts are pounds a year unless named monthly.
10
+ */
11
+ export const UK_HOUSEHOLD_LIMITS = {
12
+ adultAge: { min: 16, max: 100 },
13
+ childAge: { min: 0, max: UK_OLDEST_CHILD_AGE },
14
+ maxChildren: 10,
15
+ /** Incomes and salary sacrifice. */
16
+ maxAmount: 10_000_000,
17
+ maxMonthlyRent: 100_000,
18
+ maxMonthlyChildcare: 10_000,
19
+ /** Petrol, diesel and electricity. */
20
+ maxSpending: 100_000,
21
+ maxStatePension: 100_000,
22
+ } as const;
23
+
24
+ /**
25
+ * The policy years the household impact API covers, 2026-27 to 2031-32
26
+ * (`POLICY_YEARS`, from the dashboard's src/uk_budget_data/budget_years.json).
27
+ * Salaries can be entered for these years too.
28
+ */
29
+ export const UK_POLICY_YEARS: readonly number[] = [2026, 2027, 2028, 2029, 2030, 2031];
30
+
31
+ export interface UKValidateOptions {
32
+ /**
33
+ * The policy year (2027 is 2027-28). Ages are taken in this year, State
34
+ * Pension age is this year's, and salaries are grown to it.
35
+ */
36
+ year: number;
37
+ /**
38
+ * The policy years the calculation covers, for the year and the salary
39
+ * year; left out, the household impact API's (`UK_POLICY_YEARS`).
40
+ */
41
+ years?: readonly number[];
42
+ /** State Pension ages by year; left out, `UK_STATE_PENSION`. */
43
+ statePension?: UKStatePensionTable;
44
+ }
45
+
46
+ const isWhole = (value: unknown): value is number => typeof value === 'number' && Number.isInteger(value);
47
+ const isFiniteNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);
48
+ const pounds = (amount: number) => `£${amount.toLocaleString('en-GB')}`;
49
+
50
+ /**
51
+ * Check a draft for the calculation in `options.year`. Every issue is an
52
+ * answer the calculation needs and lacks, or one the household impact API
53
+ * would refuse, so a draft that passes builds a request within the API's
54
+ * bounds (`UK_HOUSEHOLD_LIMITS`) and years (`UK_POLICY_YEARS`), unless
55
+ * `options.years` names others. The request also needs at least one measure
56
+ * the API knows; the draft does not hold the measures, so that is the
57
+ * caller's to check. An answer the calculation does not read
58
+ * (rent when not renting, a partner's answers without a partner, a State
59
+ * Pension under State Pension age) is not checked.
60
+ */
61
+ export function validate(draft: UKHouseholdDraft, options: UKValidateOptions): ValidationResult {
62
+ const { year, years = UK_POLICY_YEARS, statePension } = options;
63
+ const limits = UK_HOUSEHOLD_LIMITS;
64
+ const issues: ValidationIssue[] = [];
65
+ const add = (code: string, path: string, message: string) => issues.push({ code, path, message });
66
+
67
+ if (!isWhole(year) || !years.includes(year)) {
68
+ add('year.unsupported', 'year', `${String(year)} is not a year this calculation covers.`);
69
+ }
70
+ if (!isWhole(draft.salaryYear) || !years.includes(draft.salaryYear)) {
71
+ add('salaryYear.unsupported', 'salaryYear', `Salaries cannot be entered for ${String(draft.salaryYear)}.`);
72
+ } else if (isWhole(year) && draft.salaryYear > year) {
73
+ add(
74
+ 'salaryYear.afterYear',
75
+ 'salaryYear',
76
+ `Salaries are entered for ${draft.salaryYear}, after ${year}; they can only be grown forward.`,
77
+ );
78
+ }
79
+
80
+ const choice = (path: string, label: string, value: unknown, known: (value: unknown) => boolean) => {
81
+ if (value === null || value === undefined) add(`${path}.required`, path, `${label} is required.`);
82
+ else if (!known(value)) add(`${path}.invalid`, path, `Unknown ${label.toLowerCase()} "${String(value)}".`);
83
+ };
84
+ choice('region', 'Region', draft.region, isUKRegion);
85
+ choice('tenure', 'Housing', draft.tenure, isUKTenure);
86
+ choice('councilTaxBand', 'Council Tax band', draft.councilTaxBand, isUKCouncilTaxBand);
87
+ if (typeof draft.claimsUniversalCredit !== 'boolean') {
88
+ add('claimsUniversalCredit.required', 'claimsUniversalCredit', 'Whether the household claims Universal Credit is required.');
89
+ }
90
+
91
+ // An amount the request sends as it is: required, a number, from 0 to max
92
+ const amount = (path: string, label: string, value: unknown, max: number, { optional = false } = {}) => {
93
+ if (value === null || value === undefined) {
94
+ if (!optional) add(`${path}.required`, path, `${label} is required.`);
95
+ } else if (!isFiniteNumber(value)) {
96
+ add(`${path}.notANumber`, path, `${label} must be a number.`);
97
+ } else if (value < 0) {
98
+ add(`${path}.negative`, path, `${label} cannot be negative.`);
99
+ } else if (value > max) {
100
+ add(`${path}.tooLarge`, path, `${label} cannot be more than ${pounds(max)}.`);
101
+ }
102
+ };
103
+
104
+ const age = (path: string, label: string, value: unknown) => {
105
+ if (value === null || value === undefined) add(`${path}.required`, path, `${label} is required.`);
106
+ else if (!isWhole(value)) add(`${path}.notWhole`, path, `${label} must be a whole number of years.`);
107
+ else if (value < limits.adultAge.min || value > limits.adultAge.max) {
108
+ add(`${path}.outOfRange`, path, `${label} must be from ${limits.adultAge.min} to ${limits.adultAge.max}.`);
109
+ }
110
+ };
111
+
112
+ const { head, partner } = draft;
113
+ age('head.age', 'Your age', head.age);
114
+ amount('head.employmentIncome', 'Your salary', head.employmentIncome, limits.maxAmount);
115
+ amount('head.privatePensionIncome', 'Your private pension', head.privatePensionIncome, limits.maxAmount, {
116
+ optional: true,
117
+ });
118
+ amount('head.dividendIncome', 'Dividends', head.dividendIncome, limits.maxAmount);
119
+ amount('head.savingsInterestIncome', 'Savings interest', head.savingsInterestIncome, limits.maxAmount);
120
+ amount('head.propertyIncome', 'Property income', head.propertyIncome, limits.maxAmount);
121
+ amount(
122
+ 'head.salarySacrificePensionContributions',
123
+ 'Salary sacrifice',
124
+ head.salarySacrificePensionContributions,
125
+ limits.maxAmount,
126
+ );
127
+ if (!isUKStudentLoanPlan(head.studentLoanPlan)) {
128
+ add('head.studentLoanPlan.invalid', 'head.studentLoanPlan', `Unknown student loan plan "${String(head.studentLoanPlan)}".`);
129
+ }
130
+ // The State Pension is read only as entered (null is the full rate) and
131
+ // only from State Pension age in the year
132
+ if (statePensionEntered(head.statePension) && atStatePensionAge(head.age, year, statePension)) {
133
+ amount('head.statePension', 'Your State Pension', head.statePension, limits.maxStatePension);
134
+ }
135
+
136
+ if (draft.hasPartner) {
137
+ age('partner.age', "Your partner's age", partner.age);
138
+ amount('partner.employmentIncome', "Your partner's salary", partner.employmentIncome, limits.maxAmount);
139
+ amount(
140
+ 'partner.privatePensionIncome',
141
+ "Your partner's private pension",
142
+ partner.privatePensionIncome,
143
+ limits.maxAmount,
144
+ { optional: true },
145
+ );
146
+ if (statePensionEntered(partner.statePension) && atStatePensionAge(partner.age, year, statePension)) {
147
+ amount('partner.statePension', "Your partner's State Pension", partner.statePension, limits.maxStatePension);
148
+ }
149
+ }
150
+
151
+ if (draft.children.length > limits.maxChildren) {
152
+ add('children.tooMany', 'children', `At most ${limits.maxChildren} children can be entered.`);
153
+ }
154
+ // By index, so a hole in the list (children[1] set before children[0]) is
155
+ // an issue: the request would send it as null, which the API refuses
156
+ for (let index = 0; index < draft.children.length; index++) {
157
+ const child: UKChildDraft | null | undefined = draft.children[index];
158
+ if (child === null || child === undefined) {
159
+ add(`children[${index}].required`, `children[${index}]`, `Child ${index + 1}'s details are missing.`);
160
+ continue;
161
+ }
162
+ const path = `children[${index}].age`;
163
+ const label = `Child ${index + 1}'s age`;
164
+ if (child.age === null || child.age === undefined) add(`${path}.required`, path, `${label} is required.`);
165
+ else if (!isWhole(child.age)) add(`${path}.notWhole`, path, `${label} must be a whole number of years.`);
166
+ else if (child.age < limits.childAge.min) add(`${path}.negative`, path, `${label} cannot be negative.`);
167
+ else if (child.age > limits.childAge.max) add(`${path}.tooOld`, path, UK_CHILD_AGE_MESSAGE);
168
+ }
169
+
170
+ if (isRenting(draft.tenure)) {
171
+ amount('monthlyRent', 'Rent', draft.monthlyRent, limits.maxMonthlyRent, { optional: true });
172
+ }
173
+ if (draft.children.length > 0) {
174
+ amount('monthlyChildcare', 'Childcare', draft.monthlyChildcare, limits.maxMonthlyChildcare);
175
+ }
176
+ amount('spending.petrol', 'Petrol spending', draft.spending?.petrol, limits.maxSpending);
177
+ amount('spending.diesel', 'Diesel spending', draft.spending?.diesel, limits.maxSpending);
178
+ amount('spending.electricity', 'Electricity spending', draft.spending?.electricity, limits.maxSpending, {
179
+ optional: true,
180
+ });
181
+
182
+ if (issues.length === 0) {
183
+ return { ok: true, issues: [] as never[] };
184
+ }
185
+ return { ok: false, issues };
186
+ }
187
+
188
+ export function isComplete(draft: UKHouseholdDraft, options: UKValidateOptions): boolean {
189
+ return validate(draft, options).ok;
190
+ }
@@ -367,6 +367,10 @@ export function toV1HouseholdPayload(
367
367
  const spmUnits: V1GroupCollection = {
368
368
  [keys.spmUnit]: { members: [...memberIds] },
369
369
  };
370
+ const childcare = toAmount(draft.childcareExpenses);
371
+ if (childcare !== undefined) {
372
+ spmUnits[keys.spmUnit].spm_unit_pre_subsidy_childcare_expenses = yearMap(year, childcare);
373
+ }
370
374
  const households: V1GroupCollection = {
371
375
  [keys.household]: householdRecord,
372
376
  };
@@ -46,6 +46,7 @@ export function cloneDraft(draft: USHouseholdDraft): USHouseholdDraft {
46
46
  zip: draft.zip,
47
47
  maritalStatus: draft.maritalStatus,
48
48
  year: draft.year,
49
+ childcareExpenses: draft.childcareExpenses,
49
50
  extras: draft.extras ? structuredClone(draft.extras) : undefined,
50
51
  people: draft.people.map((person) => ({
51
52
  ...person,
@@ -110,6 +110,7 @@ interface LegacyDraftShape {
110
110
  partnerAge?: number | string | null;
111
111
  spouseAge?: number | string | null;
112
112
  year?: number;
113
+ childcareExpenses?: number | string | null;
113
114
  }
114
115
 
115
116
  function coerceAge(value: unknown): number | null {
@@ -233,6 +234,8 @@ export function normalizeLegacyDraft(
233
234
  }
234
235
  const legacy = raw as LegacyDraftShape;
235
236
  const draft = createBlankDraft(options.year ?? legacy.year ?? DEFAULT_HOUSEHOLD_YEAR);
237
+ const childcare = coerceNumber(legacy.childcareExpenses);
238
+ if (childcare !== undefined) draft.childcareExpenses = childcare;
236
239
 
237
240
  // Location.
238
241
  if (typeof legacy.state === 'string' && isUSStateCode(legacy.state)) {
@@ -1,4 +1,5 @@
1
1
  import { createBlankDraft } from './draft';
2
+ import { toAmount } from './amount';
2
3
  import type { USHouseholdDraft, USPersonDraft } from './types';
3
4
 
4
5
  /**
@@ -10,6 +11,7 @@ import type { USHouseholdDraft, USPersonDraft } from './types';
10
11
  * &p=adult:35:e50000,adult:33:e20000,dep:6`
11
12
  *
12
13
  * Fields are pipe-separated within each person; people are comma-separated.
14
+ * `childcare=3000` carries annual household childcare costs, including 0.
13
15
  * Only the keys below are written: other person fields, such as tips,
14
16
  * investment income and expenses, are dropped from links for now.
15
17
  * Income/flag keys are single letters to keep the URL short:
@@ -103,6 +105,8 @@ export function serializeDraft(draft: USHouseholdDraft): string {
103
105
  if (draft.zip) params.set('zip', draft.zip);
104
106
  if (draft.maritalStatus) params.set('marital', draft.maritalStatus);
105
107
  params.set('year', String(draft.year));
108
+ const childcare = toAmount(draft.childcareExpenses);
109
+ if (childcare !== undefined) params.set('childcare', String(childcare));
106
110
  if (draft.people.length > 0) {
107
111
  params.set('p', draft.people.map(serializePerson).join(','));
108
112
  }
@@ -112,6 +116,8 @@ export function serializeDraft(draft: USHouseholdDraft): string {
112
116
  export function deserializeDraft(query: string | URLSearchParams): USHouseholdDraft {
113
117
  const params = typeof query === 'string' ? new URLSearchParams(query) : query;
114
118
  const draft = createBlankDraft();
119
+ const childcare = toAmount(params.get('childcare'));
120
+ if (childcare !== undefined) draft.childcareExpenses = childcare;
115
121
 
116
122
  const state = params.get('state');
117
123
  if (state) draft.state = state;