@casomoltd/nhs-pay 0.19.4 → 0.21.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 (90) hide show
  1. package/README.md +95 -18
  2. package/dist/afc-scales.d.ts +14 -7
  3. package/dist/afc-scales.js +19 -19
  4. package/dist/afc-scales.js.map +1 -1
  5. package/dist/bands.d.ts +2 -2
  6. package/dist/commutation.d.ts +49 -5
  7. package/dist/commutation.js +124 -43
  8. package/dist/commutation.js.map +1 -1
  9. package/dist/dates.d.ts +2 -0
  10. package/dist/dates.js +4 -0
  11. package/dist/dates.js.map +1 -1
  12. package/dist/errors.d.ts +70 -12
  13. package/dist/errors.js +85 -19
  14. package/dist/errors.js.map +1 -1
  15. package/dist/factor-basis.d.ts +87 -0
  16. package/dist/factor-basis.js +99 -0
  17. package/dist/factor-basis.js.map +1 -0
  18. package/dist/gad/erf-1-401-2023-06-30.d.ts +47 -0
  19. package/dist/gad/erf-1-401-2023-06-30.js +73 -0
  20. package/dist/gad/erf-1-401-2023-06-30.js.map +1 -0
  21. package/dist/gad/erf-1-402-2023-06-30.d.ts +48 -0
  22. package/dist/gad/erf-1-402-2023-06-30.js +84 -0
  23. package/dist/gad/erf-1-402-2023-06-30.js.map +1 -0
  24. package/dist/gad/erf-1-407-2023-06-30.d.ts +47 -0
  25. package/dist/gad/erf-1-407-2023-06-30.js +73 -0
  26. package/dist/gad/erf-1-407-2023-06-30.js.map +1 -0
  27. package/dist/gad/erf-2023-06-30.d.ts +3 -0
  28. package/dist/gad/erf-2023-06-30.js +1 -0
  29. package/dist/gad/erf-2023-06-30.js.map +1 -1
  30. package/dist/gad/factor-table.d.ts +62 -31
  31. package/dist/gad/factor-table.js +67 -34
  32. package/dist/gad/factor-table.js.map +1 -1
  33. package/dist/gad/lrf-2-416-2023-06-30.d.ts +46 -0
  34. package/dist/gad/lrf-2-416-2023-06-30.js +72 -0
  35. package/dist/gad/lrf-2-416-2023-06-30.js.map +1 -0
  36. package/dist/gad/lrf-2023-06-30.d.ts +3 -0
  37. package/dist/gad/lrf-2023-06-30.js +1 -0
  38. package/dist/gad/lrf-2023-06-30.js.map +1 -1
  39. package/dist/gad/promotional-scale-2020.d.ts +37 -0
  40. package/dist/gad/promotional-scale-2020.js +38 -0
  41. package/dist/gad/promotional-scale-2020.js.map +1 -0
  42. package/dist/index.d.ts +17 -4
  43. package/dist/index.js +22 -13
  44. package/dist/index.js.map +1 -1
  45. package/dist/iso-date.d.ts +7 -0
  46. package/dist/iso-date.js +11 -0
  47. package/dist/iso-date.js.map +1 -1
  48. package/dist/member-benefits.d.ts +237 -0
  49. package/dist/member-benefits.js +440 -0
  50. package/dist/member-benefits.js.map +1 -0
  51. package/dist/pay-path.d.ts +70 -0
  52. package/dist/pay-path.js +155 -0
  53. package/dist/pay-path.js.map +1 -0
  54. package/dist/pension/curve.d.ts +74 -0
  55. package/dist/pension/curve.js +134 -0
  56. package/dist/pension/curve.js.map +1 -0
  57. package/dist/pension/history.js +3 -3
  58. package/dist/pension/history.js.map +1 -1
  59. package/dist/pension/ledger.d.ts +71 -31
  60. package/dist/pension/ledger.js +41 -6
  61. package/dist/pension/ledger.js.map +1 -1
  62. package/dist/pension/money.d.ts +23 -6
  63. package/dist/pension/money.js +23 -1
  64. package/dist/pension/money.js.map +1 -1
  65. package/dist/pension/uplift.d.ts +23 -0
  66. package/dist/pension/uplift.js +34 -1
  67. package/dist/pension/uplift.js.map +1 -1
  68. package/dist/pension-projection.d.ts +54 -52
  69. package/dist/pension-projection.js +65 -219
  70. package/dist/pension-projection.js.map +1 -1
  71. package/dist/scale-point.d.ts +11 -1
  72. package/dist/scales.d.ts +9 -9
  73. package/dist/scales.js +68 -67
  74. package/dist/scales.js.map +1 -1
  75. package/dist/sections/final-salary.d.ts +97 -0
  76. package/dist/sections/final-salary.js +99 -0
  77. package/dist/sections/final-salary.js.map +1 -0
  78. package/dist/sections/section-1995.d.ts +20 -0
  79. package/dist/sections/section-1995.js +52 -0
  80. package/dist/sections/section-1995.js.map +1 -0
  81. package/dist/sections/section-2008.d.ts +16 -0
  82. package/dist/sections/section-2008.js +44 -0
  83. package/dist/sections/section-2008.js.map +1 -0
  84. package/dist/sections/section-2015.d.ts +43 -0
  85. package/dist/sections/section-2015.js +57 -0
  86. package/dist/sections/section-2015.js.map +1 -0
  87. package/dist/values.d.ts +4 -5
  88. package/dist/values.js +4 -5
  89. package/dist/values.js.map +1 -1
  90. package/package.json +9 -5
@@ -0,0 +1,237 @@
1
+ import type { CashChoice, CommutationResult } from './commutation.js';
2
+ import type { FactorOutcome } from './factor-basis.js';
3
+ import type { IsoDate } from './iso-date.js';
4
+ import type { MemberPay, PayPath } from './pay-path.js';
5
+ import type { ProjectionPoint } from './pension/curve.js';
6
+ import type { MemberLedger } from './pension/ledger.js';
7
+ import type { EstimatedHistory } from './pension/history.js';
8
+ import type { ProjectionMoney } from './pension/money.js';
9
+ import type { Prices } from './pension/prices.js';
10
+ import type { FinalSalaryRules, PayMeasure } from './sections/final-salary.js';
11
+ /**
12
+ * One scheme, the NHS Pension Scheme, in three sections. "Scheme" only
13
+ * ever means the whole; each part is a section, as a member's own
14
+ * Annual Benefit Statement prints it.
15
+ */
16
+ export declare const SECTIONS: {
17
+ readonly s1995: "section-1995";
18
+ readonly s2008: "section-2008";
19
+ readonly s2015: "section-2015";
20
+ };
21
+ export type SectionId = (typeof SECTIONS)[keyof typeof SECTIONS];
22
+ /** The two final-salary sections, which McCloud calls the legacy
23
+ * scheme. */
24
+ export type LegacySectionId = Exclude<SectionId, typeof SECTIONS.s2015>;
25
+ /** Joined and left, per section, as the member declared it. */
26
+ export interface DeclaredPeriod {
27
+ readonly section: SectionId;
28
+ readonly joined: IsoDate;
29
+ /** Null while still in service. */
30
+ readonly left: IsoDate | null;
31
+ }
32
+ export interface Member {
33
+ readonly dateOfBirth: IsoDate;
34
+ readonly service: readonly DeclaredPeriod[];
35
+ readonly pay: MemberPay;
36
+ /** A 2015 Section balance read off an Annual Benefit Statement,
37
+ * which seeds its ledger at the statement's date. Null where the
38
+ * member gave none. */
39
+ readonly statement: {
40
+ readonly accruedPension: number;
41
+ readonly asAt: IsoDate;
42
+ } | null;
43
+ }
44
+ /** Fixed for one valuation, and worth disclosing beside it. Pay growth is
45
+ * not here: it is GAD's published curve, the same for everybody. */
46
+ export interface Assumptions {
47
+ readonly assumedCpi: number;
48
+ }
49
+ /**
50
+ * How the remedy window is valued, for a member who has one: as more
51
+ * service in their legacy section, or under the 2015 Section's rules
52
+ * while still paid from the legacy section. There is no default and no
53
+ * preferred answer: which pays more depends on the choices a caller
54
+ * compares, and the library cannot see them.
55
+ */
56
+ export declare const REMEDY_BASES: {
57
+ readonly none: "none";
58
+ readonly legacy: "legacy-basis";
59
+ readonly section2015: "section-2015-basis";
60
+ };
61
+ export type RemedyBasis = (typeof REMEDY_BASES)[keyof typeof REMEDY_BASES];
62
+ export type RemedyElection = {
63
+ readonly kind: RemedyBasis;
64
+ };
65
+ /** One set of choices; a caller comparing options asks once for each. */
66
+ export interface RetirementChoices {
67
+ /** Stops accruing. Accrues the whole scheme year it falls in. */
68
+ readonly leaving: IsoDate;
69
+ /** Every section is drawn on this one date. Drawing sections on
70
+ * different dates, and partial retirement, are deferred:
71
+ * https://github.com/casomoltd/nhs-pay/issues/17 */
72
+ readonly drawing: IsoDate;
73
+ readonly remedy: RemedyElection;
74
+ readonly cash: CashChoice;
75
+ }
76
+ /** What a period is: service in its own right, or the McCloud remedy
77
+ * window, held in the legacy section and valued on either basis. */
78
+ export declare const PERIOD_KINDS: {
79
+ readonly ordinary: "ordinary";
80
+ readonly remedyWindow: "remedy-window";
81
+ };
82
+ /** A window of service between two events, held in one section. */
83
+ export interface ServicePeriod {
84
+ readonly section: SectionId;
85
+ readonly from: IsoDate;
86
+ /** Null while the member is still in service in it; `at()` closes
87
+ * it at the leaving date. */
88
+ readonly to: IsoDate | null;
89
+ readonly kind: (typeof PERIOD_KINDS)[keyof typeof PERIOD_KINDS];
90
+ }
91
+ /** How a section accrues: on final salary, or on a career average. */
92
+ export declare const ACCRUALS: {
93
+ readonly finalSalary: "final-salary";
94
+ readonly careerAverage: "career-average";
95
+ };
96
+ /**
97
+ * One section's benefit on one basis. A legacy section returns two
98
+ * when its remedy window is valued on the 2015 basis: that part is
99
+ * paid from the legacy section but determined under the 2015
100
+ * Section's rules. `provenance` says which rules produced the figure,
101
+ * so a reviewer can check it; nothing computes with it.
102
+ */
103
+ export interface Award {
104
+ /** Where it is held and paid from. */
105
+ readonly section: SectionId;
106
+ readonly periods: readonly ServicePeriod[];
107
+ /** The pension at the drawing before its factor: final salary as
108
+ * measured, or the career average pot as revalued. */
109
+ readonly beforeFactor: ProjectionMoney;
110
+ /** After the factor: what is paid. */
111
+ readonly pension: ProjectionMoney;
112
+ /** Nil rather than absent where the rules pay none, so a caller
113
+ * cannot forget to ask. */
114
+ readonly automaticLumpSum: ProjectionMoney;
115
+ readonly factor: FactorOutcome;
116
+ /** A career average award's year-by-year walk, in cash and in today's
117
+ * money; null for final salary, which keeps no balance to walk. */
118
+ readonly ledgers: {
119
+ readonly cash: MemberLedger;
120
+ readonly todaysMoney: MemberLedger;
121
+ } | null;
122
+ readonly provenance: {
123
+ readonly accrual: typeof ACCRUALS.finalSalary;
124
+ readonly denominator: FinalSalaryRules['denominator'];
125
+ readonly payMeasure: PayMeasure;
126
+ /** The years valued, and the pay they were measured on, in
127
+ * today's money: the two figures a reviewer checks first. */
128
+ readonly membership: number;
129
+ readonly finalPay: number;
130
+ }
131
+ /** The 2015 Section's rule, 1/54 of each year's pay revalued: the
132
+ * accrual names it, so no field restates the rate. */
133
+ | {
134
+ readonly accrual: typeof ACCRUALS.careerAverage;
135
+ };
136
+ }
137
+ /** One answer to `at()`: every option compared is its own. */
138
+ export interface Position {
139
+ readonly choices: RetirementChoices;
140
+ readonly awards: readonly Award[];
141
+ /** Summed across awards, after each award's own factor, before
142
+ * cash. */
143
+ readonly crystallised: {
144
+ readonly pension: ProjectionMoney;
145
+ readonly automaticLumpSum: ProjectionMoney;
146
+ };
147
+ readonly cash: CommutationResult;
148
+ /** The price series the cash reading walked with, for converting an
149
+ * outside figure — a cap, a target — into the same rulers. */
150
+ readonly prices: Prices;
151
+ /** The 2015 Section's ledger as the member reads it on a statement,
152
+ * in cash; and the same walk in today's money. The same objects as
153
+ * the 2015 Section award's own `ledgers`, named here because a
154
+ * statement is read against this one section. */
155
+ readonly ledger: MemberLedger;
156
+ readonly todaysMoneyLedger: MemberLedger;
157
+ /** The 2015 Section's years before a stated balance, estimated in
158
+ * today's money; null where the member gave no statement, or joined
159
+ * in its own year. Calibrated to land exactly on the stated
160
+ * balance. */
161
+ readonly estimatedHistory: EstimatedHistory | null;
162
+ /** The 2015 Section's balance at each scheme year end, both
163
+ * rulers. */
164
+ readonly curve: readonly ProjectionPoint[];
165
+ }
166
+ /** A legacy section's rules, read from its statute. */
167
+ export interface LegacyRules {
168
+ readonly section: LegacySectionId;
169
+ /** The age its pension is payable unreduced, which its factors are
170
+ * measured from. */
171
+ readonly pensionAge: number;
172
+ /** The 80 in "1/80 of final pay for each year". */
173
+ readonly denominator: FinalSalaryRules['denominator'];
174
+ /** The automatic lump sum as a multiple of the pension; null where
175
+ * the section pays none. */
176
+ readonly automaticLumpSum: number | null;
177
+ /** Whether drawing after the pension age raises the pension. */
178
+ readonly lateUplift: boolean;
179
+ }
180
+ /** What the member holds today, per section, with the remedy window
181
+ * on the legacy basis — their position since rollback. */
182
+ export interface Holdings {
183
+ readonly bySection: readonly {
184
+ readonly section: SectionId;
185
+ readonly pension: ProjectionMoney;
186
+ /** The automatic lump sum that comes with it, unreduced; nil where
187
+ * the section pays none. */
188
+ readonly automaticLumpSum: ProjectionMoney;
189
+ }[];
190
+ readonly total: ProjectionMoney;
191
+ }
192
+ export interface MemberBenefits {
193
+ /** What the member holds, derived from their service and checked. */
194
+ readonly periods: readonly ServicePeriod[];
195
+ /** Whether they have a remedy window, and so must pass an election
196
+ * to `at()`. */
197
+ readonly remedy: boolean;
198
+ /** The legacy section they hold and its rules; null where they hold
199
+ * the 2015 Section alone. */
200
+ readonly legacy: LegacyRules | null;
201
+ /** The pay every section reads, built once for the member. */
202
+ readonly payPath: PayPath;
203
+ /** Worth today, before any drawing. */
204
+ now(): Holdings;
205
+ /** Worth when drawn, for one set of choices. */
206
+ at(choices: RetirementChoices): Position;
207
+ }
208
+ /**
209
+ * The dates the McCloud remedy turns on, for a caller that has to read
210
+ * a member's answers against them before it can declare their service.
211
+ */
212
+ export declare const REMEDY: {
213
+ readonly eligibleBy: IsoDate;
214
+ readonly from: IsoDate;
215
+ readonly to: IsoDate;
216
+ readonly rollback: IsoDate;
217
+ };
218
+ /**
219
+ * The day each later section opened: the 2008 Section to new joiners
220
+ * under SI 2008/653, and the 2015 Section, which every member moved to
221
+ * for service from that day, under SI 2015/94. The 1995 Section is
222
+ * absent: no answer a member gives turns on its opening.
223
+ */
224
+ export declare const SECTION_OPENED: {
225
+ readonly "section-2008": IsoDate;
226
+ readonly "section-2015": IsoDate;
227
+ };
228
+ /**
229
+ * Build a member's benefits. Throws `PayPathUnavailable` where there
230
+ * is no current pay to build pay from, `BenefitNotModelled` for service
231
+ * the library does not model, and RangeError for a declaration that
232
+ * cannot be true.
233
+ *
234
+ * `today` is required because it decides which answer comes back: it
235
+ * is the date the figures are as at, so a figure reproduces as at it.
236
+ */
237
+ export declare function memberBenefits(member: Member, assumptions: Assumptions, today: Date): MemberBenefits;
@@ -0,0 +1,440 @@
1
+ /**
2
+ * A member's benefits across every section they hold: built once from
3
+ * what the member told us, then asked one question per set of
4
+ * retirement choices.
5
+ *
6
+ * Everything ABOUT the member goes in once, when the owner is built;
7
+ * each method takes only the question. So a caller never assembles the
8
+ * member again per option, and no section, pay path or ledger is a
9
+ * thing it has to build.
10
+ *
11
+ * Rules come in two tiers. Each section's own — denominator, pay
12
+ * measure, pension age, lump sum, factors — belong to that section;
13
+ * the ones a caller reads are the legacy section's, through
14
+ * `MemberBenefits.legacy`. The rules over the whole set live
15
+ * here: which sections a member holds and whether their service is
16
+ * eligible for the McCloud remedy, then, at the drawing, summing every
17
+ * award into one pension and one automatic lump sum and taking cash
18
+ * across that one total.
19
+ */
20
+ import { cashAt, nhsCommutationLimits } from './commutation.js';
21
+ import { BenefitNotModelled, invariant, NOT_MODELLED } from './errors.js';
22
+ import { isoDate, isoDateOf, isoToDate } from './iso-date.js';
23
+ import { normalPensionAge } from './npa.js';
24
+ import { buildPayPath } from './pay-path.js';
25
+ import { earliest } from './dates.js';
26
+ import { buildCurve, walkThrough } from './pension/curve.js';
27
+ import { seedFromBalanceAt } from './pension/uplift.js';
28
+ import { estimateHistory } from './pension/history.js';
29
+ import { moneyAt, sumMoney } from './pension/money.js';
30
+ import { createPrices } from './pension/prices.js';
31
+ import { schemeYearEndDate, schemeYearEndFor, seedFromJoinDate, } from './pension/seed.js';
32
+ import { finalSalaryBenefit, unreducedPension, } from './sections/final-salary.js';
33
+ import { RULES_1995 } from './sections/section-1995.js';
34
+ import { RULES_2008 } from './sections/section-2008.js';
35
+ import { careerAverage } from './sections/section-2015.js';
36
+ import { npaDate } from './dates.js';
37
+ // ── Vocabulary ──────────────────────────────────────
38
+ /**
39
+ * One scheme, the NHS Pension Scheme, in three sections. "Scheme" only
40
+ * ever means the whole; each part is a section, as a member's own
41
+ * Annual Benefit Statement prints it.
42
+ */
43
+ export const SECTIONS = {
44
+ s1995: 'section-1995',
45
+ s2008: 'section-2008',
46
+ s2015: 'section-2015',
47
+ };
48
+ /**
49
+ * How the remedy window is valued, for a member who has one: as more
50
+ * service in their legacy section, or under the 2015 Section's rules
51
+ * while still paid from the legacy section. There is no default and no
52
+ * preferred answer: which pays more depends on the choices a caller
53
+ * compares, and the library cannot see them.
54
+ */
55
+ export const REMEDY_BASES = {
56
+ none: 'none',
57
+ legacy: 'legacy-basis',
58
+ section2015: 'section-2015-basis',
59
+ };
60
+ // ── What the library answers with ───────────────────
61
+ /** What a period is: service in its own right, or the McCloud remedy
62
+ * window, held in the legacy section and valued on either basis. */
63
+ export const PERIOD_KINDS = {
64
+ ordinary: 'ordinary',
65
+ remedyWindow: 'remedy-window',
66
+ };
67
+ /** How a section accrues: on final salary, or on a career average. */
68
+ export const ACCRUALS = {
69
+ finalSalary: 'final-salary',
70
+ careerAverage: 'career-average',
71
+ };
72
+ /** A legacy section's rules, as `MemberBenefits.legacy` states them. */
73
+ function legacyOf(section) {
74
+ const rules = RULES[section];
75
+ return {
76
+ section,
77
+ pensionAge: rules.pensionAge,
78
+ denominator: rules.denominator,
79
+ automaticLumpSum: rules.automaticLumpSum?.multiple ?? null,
80
+ lateUplift: rules.lateUplift,
81
+ };
82
+ }
83
+ // ── The service, checked ────────────────────────────
84
+ /** The remedy period, 1 April 2015 to 31 March 2022, as PSPJOA 2022
85
+ * s.1 defines it. The days either side are derived from it. */
86
+ const REMEDY_FROM = isoDate('2015-04-01');
87
+ const REMEDY_TO = isoDate('2022-03-31');
88
+ /** PSPJOA 2022 s.1: in pensionable service "on 31 March 2012 or any
89
+ * earlier day". */
90
+ const ELIGIBLE_BY = isoDate('2012-03-31');
91
+ /** Rollback put remedy service back in the legacy section on this
92
+ * date (SI 2023/985), so a statement before it counts the remedy
93
+ * years in the 2015 Section. */
94
+ const ROLLBACK = isoDate('2023-10-01');
95
+ /**
96
+ * The dates the McCloud remedy turns on, for a caller that has to read
97
+ * a member's answers against them before it can declare their service.
98
+ */
99
+ export const REMEDY = {
100
+ eligibleBy: ELIGIBLE_BY,
101
+ from: REMEDY_FROM,
102
+ to: REMEDY_TO,
103
+ rollback: ROLLBACK,
104
+ };
105
+ /**
106
+ * The day each later section opened: the 2008 Section to new joiners
107
+ * under SI 2008/653, and the 2015 Section, which every member moved to
108
+ * for service from that day, under SI 2015/94. The 1995 Section is
109
+ * absent: no answer a member gives turns on its opening.
110
+ */
111
+ export const SECTION_OPENED = {
112
+ [SECTIONS.s2008]: isoDate('2008-04-01'),
113
+ [SECTIONS.s2015]: REMEDY_FROM,
114
+ };
115
+ const on = (d) => isoToDate(d);
116
+ const daysFrom = (d, days) => {
117
+ const date = on(d);
118
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate() + days);
119
+ };
120
+ const dayAfter = (d) => daysFrom(d, 1);
121
+ const LAST_BEFORE_2015 = isoDateOf(daysFrom(REMEDY_FROM, -1));
122
+ const AFTER_REMEDY = isoDateOf(dayAfter(REMEDY_TO));
123
+ /** The last day a period is valued to: its own end, or the leaving
124
+ * date where that comes first or the period is still open. */
125
+ const until = (p, leaving) => p.to === null || on(p.to) > leaving ? leaving : on(p.to);
126
+ const isLegacy = (section) => section !== SECTIONS.s2015;
127
+ /**
128
+ * The periods a member holds, derived from what they declared and
129
+ * refused where it describes something the library does not model.
130
+ *
131
+ * Service is taken as continuous. A break — a gap between one period
132
+ * and the next — decides whether remedy service qualifies, and how a
133
+ * member comes to hold both legacy sections; both are deferred, so a
134
+ * declared break is refused rather than priced as though it were
135
+ * continuous: https://github.com/casomoltd/nhs-pay/issues/16
136
+ *
137
+ * A member with no 2015 Section service after rollback is refused
138
+ * too: https://github.com/casomoltd/nhs-pay/issues/19
139
+ *
140
+ * A declaration that cannot be true — nothing declared, leaving
141
+ * before joining, periods that overlap — is a caller's mistake and
142
+ * throws RangeError.
143
+ */
144
+ function servicePeriods(declared) {
145
+ if (declared.length === 0) {
146
+ throw new RangeError('member: no service declared');
147
+ }
148
+ const sorted = [...declared].sort((a, b) => on(a.joined).getTime() - on(b.joined).getTime());
149
+ sorted.forEach((p, i) => {
150
+ if (p.left !== null && on(p.left) < on(p.joined)) {
151
+ throw new RangeError(`member: ${p.section} left before it was joined`);
152
+ }
153
+ const next = sorted.at(i + 1);
154
+ if (next === undefined)
155
+ return;
156
+ if (p.left === null || on(next.joined) <= on(p.left)) {
157
+ throw new RangeError(`member: ${p.section} overlaps the next period`);
158
+ }
159
+ if (dayAfter(p.left).getTime() !== on(next.joined).getTime()) {
160
+ throw new BenefitNotModelled(NOT_MODELLED.breakInService, 'a break in pensionable service');
161
+ }
162
+ });
163
+ const legacyDeclared = sorted.filter((p) => isLegacy(p.section));
164
+ const reformed = sorted.filter((p) => p.section === SECTIONS.s2015);
165
+ if (legacyDeclared.length > 1) {
166
+ throw new BenefitNotModelled(NOT_MODELLED.bothLegacySections, 'service in both legacy sections');
167
+ }
168
+ const current = reformed.at(0);
169
+ if (current === undefined || reformed.length > 1) {
170
+ throw new BenefitNotModelled(NOT_MODELLED.no2015Section, 'service without the 2015 Section');
171
+ }
172
+ const held = legacyDeclared.at(0);
173
+ const end = current.left;
174
+ const remedy = held !== undefined
175
+ && on(held.joined) <= on(ELIGIBLE_BY)
176
+ && (end === null || on(end) >= on(REMEDY_FROM));
177
+ if (remedy && end !== null && on(end) <= on(REMEDY_TO)) {
178
+ throw new BenefitNotModelled(NOT_MODELLED.remedyMemberLeftEarly, 'a remedy member who left before 1 April 2022');
179
+ }
180
+ let legacy = null;
181
+ if (held !== undefined && isLegacy(held.section)) {
182
+ // A legacy period before a 2015 one has a leaving date: the
183
+ // contiguity check above refused an open one.
184
+ invariant(held.left !== null, 'a legacy period with no end');
185
+ const own = {
186
+ section: held.section,
187
+ from: held.joined,
188
+ to: remedy ? LAST_BEFORE_2015 : held.left,
189
+ kind: PERIOD_KINDS.ordinary,
190
+ };
191
+ legacy = {
192
+ section: held.section,
193
+ periods: remedy
194
+ ? [own, {
195
+ section: held.section, from: REMEDY_FROM, to: REMEDY_TO,
196
+ kind: PERIOD_KINDS.remedyWindow,
197
+ }]
198
+ : [own],
199
+ };
200
+ }
201
+ const periods = [
202
+ ...(legacy?.periods ?? []),
203
+ {
204
+ section: SECTIONS.s2015,
205
+ from: remedy ? AFTER_REMEDY : current.joined,
206
+ to: end,
207
+ kind: PERIOD_KINDS.ordinary,
208
+ },
209
+ ];
210
+ return { periods, legacy };
211
+ }
212
+ // ── The owner ───────────────────────────────────────
213
+ const RULES = {
214
+ [SECTIONS.s1995]: RULES_1995,
215
+ [SECTIONS.s2008]: RULES_2008,
216
+ };
217
+ /** A career average walk over `window`, accruing only inside it. */
218
+ function walk(b, window, seed, { leaving, drawing }, prices) {
219
+ const first = schemeYearEndFor(on(window.from));
220
+ const last = schemeYearEndFor(until(window, leaving));
221
+ return careerAverage({
222
+ seed,
223
+ payIn: (year) => (year >= first && year <= last
224
+ ? b.payPath.payFor(year)
225
+ : null),
226
+ dateOfBirth: b.born,
227
+ leaving,
228
+ drawing,
229
+ prices,
230
+ through: walkThrough(drawing, b.npaOn),
231
+ });
232
+ }
233
+ /** The 2015 Section's own seed: its statement, or its first day. */
234
+ function seed2015(b, { leaving, drawing }, prices) {
235
+ const { statement } = b.member;
236
+ return statement === null
237
+ ? seedFromJoinDate(on(b.ordinary2015.from))
238
+ : seedFromBalanceAt(statement.accruedPension, on(statement.asAt), leaving, drawing, prices);
239
+ }
240
+ /** The legacy windows as final-salary membership, to `leaving`. */
241
+ const membershipOf = (valued, leaving) => valued
242
+ .filter((p) => on(p.from) <= leaving)
243
+ .map((p) => ({ from: on(p.from), to: until(p, leaving) }));
244
+ /** What the member holds today, with the remedy window on the legacy
245
+ * basis: unreduced, since nothing is drawn. */
246
+ function holdings(b) {
247
+ const { today } = b;
248
+ const bySection = [];
249
+ const flat = (x) => moneyAt({ nominal: x, real: x }, today);
250
+ if (b.legacy !== null) {
251
+ const { pension, automaticLumpSum } = unreducedPension(RULES[b.legacy.section], membershipOf(b.legacy.periods, today), b.payPath, schemeYearEndFor(today));
252
+ bySection.push({
253
+ section: b.legacy.section,
254
+ pension: flat(pension),
255
+ automaticLumpSum: flat(automaticLumpSum),
256
+ });
257
+ }
258
+ // Any leaving and drawing after today give the same balance today;
259
+ // these are only where the walk has to stop.
260
+ const leaving = b.ordinary2015.to === null
261
+ ? b.npaOn
262
+ : on(b.ordinary2015.to);
263
+ const dates = { leaving, drawing: leaving < b.npaOn ? b.npaOn : leaving };
264
+ const accrued = walk(b, b.ordinary2015, seed2015(b, dates, b.todaysPrices), dates, b.todaysPrices).ledger.accruedAt(today);
265
+ bySection.push({
266
+ section: SECTIONS.s2015,
267
+ pension: flat(accrued),
268
+ automaticLumpSum: flat(0),
269
+ });
270
+ return {
271
+ bySection, total: sumMoney(bySection.map((x) => x.pension), today),
272
+ };
273
+ }
274
+ /** Refuse choices that cannot be valued, and return their dates. */
275
+ function checked(b, remedy, choices) {
276
+ const leaving = on(choices.leaving);
277
+ const drawing = on(choices.drawing);
278
+ if (drawing < leaving) {
279
+ throw new RangeError('at: drawn before leaving');
280
+ }
281
+ if (b.ordinary2015.to !== null && on(b.ordinary2015.to) < leaving) {
282
+ throw new RangeError(`at: leaving after the member already left, on ${b.ordinary2015.to}`);
283
+ }
284
+ if (remedy !== (choices.remedy.kind !== REMEDY_BASES.none)) {
285
+ throw new RangeError(remedy
286
+ ? 'at: a remedy member needs an election'
287
+ : 'at: an election for a member with no remediable service');
288
+ }
289
+ return { leaving, drawing };
290
+ }
291
+ /** The legacy section's final-salary award over the periods valued on
292
+ * final salary, which the election decides. */
293
+ function legacyAward(b, legacy, valued, dates) {
294
+ const rules = RULES[legacy.section];
295
+ const benefit = finalSalaryBenefit(rules, {
296
+ windows: membershipOf(valued, dates.leaving),
297
+ payPath: b.payPath, dateOfBirth: b.born, ...dates,
298
+ prices: b.cashPrices,
299
+ });
300
+ return {
301
+ section: legacy.section,
302
+ periods: valued,
303
+ beforeFactor: benefit.beforeFactor,
304
+ pension: benefit.pension,
305
+ automaticLumpSum: benefit.automaticLumpSum,
306
+ factor: benefit.factor,
307
+ ledgers: null,
308
+ provenance: {
309
+ accrual: ACCRUALS.finalSalary,
310
+ denominator: rules.denominator,
311
+ payMeasure: rules.payMeasure,
312
+ membership: benefit.membership,
313
+ finalPay: benefit.finalPay,
314
+ },
315
+ };
316
+ }
317
+ /** A career average award over one window, walked in both rulers. */
318
+ function careerAward(b, section, window, seedFor, dates) {
319
+ const cash = walk(b, window, seedFor(b.cashPrices), dates, b.cashPrices);
320
+ const todays = walk(b, window, seedFor(b.todaysPrices), dates, b.todaysPrices);
321
+ return {
322
+ award: {
323
+ section,
324
+ periods: [window],
325
+ beforeFactor: moneyAt({ nominal: cash.revalued, real: todays.revalued }, dates.drawing),
326
+ pension: moneyAt({ nominal: cash.drawn, real: todays.drawn }, dates.drawing),
327
+ automaticLumpSum: moneyAt({ nominal: 0, real: 0 }, dates.drawing),
328
+ factor: cash.factor,
329
+ ledgers: { cash: cash.ledger, todaysMoney: todays.ledger },
330
+ provenance: { accrual: ACCRUALS.careerAverage },
331
+ },
332
+ cash,
333
+ todays,
334
+ };
335
+ }
336
+ /** The 2015 Section's balance, with its estimated run-up before a
337
+ * statement, as the ledgers, history and curve a `Position` carries. */
338
+ function section2015(b, own, { leaving, drawing }) {
339
+ const historyIn = (r, prices) => b.member.statement === null
340
+ ? null
341
+ : estimateHistory({
342
+ joinDate: on(b.ordinary2015.from),
343
+ statedBalance: r.seed.opening,
344
+ statementSchemeYearEnd: r.seed.atSchemeYearEnd,
345
+ prices,
346
+ });
347
+ const cashHistory = historyIn(own.cash, b.cashPrices);
348
+ const todaysHistory = historyIn(own.todays, b.todaysPrices);
349
+ const run = (r, history) => ({
350
+ today: b.today, dateOfBirth: b.born, exitDate: leaving,
351
+ retirementDate: drawing, npa: normalPensionAge(b.born),
352
+ ledger: r.ledger, history,
353
+ curveFrom: earliest(b.today, leaving, schemeYearEndDate(history === null
354
+ ? r.seed.atSchemeYearEnd
355
+ : history.from - 1)),
356
+ });
357
+ return {
358
+ ledger: own.cash.ledger,
359
+ todaysMoneyLedger: own.todays.ledger,
360
+ estimatedHistory: todaysHistory,
361
+ curve: buildCurve(run(own.cash, cashHistory), run(own.todays, todaysHistory)),
362
+ };
363
+ }
364
+ /** Every section's award at one set of choices, summed, with cash taken
365
+ * across the total. */
366
+ function position(b, remedy, choices) {
367
+ const dates = checked(b, remedy, choices);
368
+ const onThe2015Basis = choices.remedy.kind === REMEDY_BASES.section2015;
369
+ const awards = [];
370
+ const { legacy } = b;
371
+ if (legacy !== null) {
372
+ // On the legacy basis every legacy period is final salary; on the
373
+ // 2015 basis the remedy window leaves it for a career average walk.
374
+ const window = legacy.periods.find((p) => p.kind === PERIOD_KINDS.remedyWindow);
375
+ const valued = onThe2015Basis
376
+ ? legacy.periods.filter((p) => p.kind === PERIOD_KINDS.ordinary)
377
+ : legacy.periods;
378
+ awards.push(legacyAward(b, legacy, valued, dates));
379
+ if (onThe2015Basis) {
380
+ // `checked` refused an election for a member with no window.
381
+ invariant(window !== undefined, 'a 2015 basis with no remedy window');
382
+ awards.push(careerAward(b, legacy.section, window, () => seedFromJoinDate(on(window.from)), dates).award);
383
+ }
384
+ }
385
+ const own = careerAward(b, SECTIONS.s2015, b.ordinary2015, (prices) => seed2015(b, dates, prices), dates);
386
+ awards.push(own.award);
387
+ const pension = sumMoney(awards.map((a) => a.pension), dates.drawing);
388
+ const automaticLumpSum = sumMoney(awards.map((a) => a.automaticLumpSum), dates.drawing);
389
+ return {
390
+ choices,
391
+ awards,
392
+ crystallised: { pension, automaticLumpSum },
393
+ cash: cashAt(pension, automaticLumpSum, choices.cash, nhsCommutationLimits(b.cashPrices)),
394
+ prices: b.cashPrices,
395
+ ...section2015(b, own, dates),
396
+ };
397
+ }
398
+ /**
399
+ * Build a member's benefits. Throws `PayPathUnavailable` where there
400
+ * is no current pay to build pay from, `BenefitNotModelled` for service
401
+ * the library does not model, and RangeError for a declaration that
402
+ * cannot be true.
403
+ *
404
+ * `today` is required because it decides which answer comes back: it
405
+ * is the date the figures are as at, so a figure reproduces as at it.
406
+ */
407
+ export function memberBenefits(member, assumptions, today) {
408
+ const { periods, legacy } = servicePeriods(member.service);
409
+ const remedy = periods.some((p) => p.kind === PERIOD_KINDS.remedyWindow);
410
+ // Deferred until the split of a pre-rollback balance is read:
411
+ // https://github.com/casomoltd/nhs-pay/issues/20
412
+ if (remedy && member.statement !== null
413
+ && on(member.statement.asAt) < on(ROLLBACK)) {
414
+ throw new BenefitNotModelled(NOT_MODELLED.statementBeforeRollback, 'a statement from before rollback on 1 October 2023, which '
415
+ + 'counts the remedy years in the 2015 Section');
416
+ }
417
+ const ordinary2015 = periods.at(-1);
418
+ invariant(ordinary2015?.section === SECTIONS.s2015, 'the last period is the 2015 Section\'s');
419
+ const born = on(member.dateOfBirth);
420
+ const built = {
421
+ member,
422
+ today,
423
+ born,
424
+ npaOn: npaDate(born, normalPensionAge(born)),
425
+ payPath: buildPayPath(member.dateOfBirth, member.pay),
426
+ legacy,
427
+ ordinary2015,
428
+ cashPrices: createPrices(assumptions.assumedCpi, today),
429
+ todaysPrices: createPrices(0, today),
430
+ };
431
+ return {
432
+ periods,
433
+ remedy,
434
+ legacy: legacy === null ? null : legacyOf(legacy.section),
435
+ payPath: built.payPath,
436
+ now: () => holdings(built),
437
+ at: (choices) => position(built, remedy, choices),
438
+ };
439
+ }
440
+ //# sourceMappingURL=member-benefits.js.map