@sachfolio/cas-reader 0.0.0-stage → 0.2.0-beta.1

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 (84) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +71 -0
  3. package/NOTICE +41 -0
  4. package/README.md +198 -2
  5. package/dist/analytics/contract.d.ts +110 -0
  6. package/dist/analytics/contract.js +79 -0
  7. package/dist/analytics/eligibility.d.ts +66 -0
  8. package/dist/analytics/eligibility.js +93 -0
  9. package/dist/analytics/gains-schema.d.ts +898 -0
  10. package/dist/analytics/gains-schema.js +170 -0
  11. package/dist/analytics/gains.d.ts +319 -0
  12. package/dist/analytics/gains.js +649 -0
  13. package/dist/analytics/modules.d.ts +33 -0
  14. package/dist/analytics/modules.js +74 -0
  15. package/dist/analytics/returns-schema.d.ts +931 -0
  16. package/dist/analytics/returns-schema.js +152 -0
  17. package/dist/analytics/returns.d.ts +126 -0
  18. package/dist/analytics/returns.js +453 -0
  19. package/dist/analytics/schedule112a.d.ts +77 -0
  20. package/dist/analytics/schedule112a.js +134 -0
  21. package/dist/analytics/xirr.d.ts +75 -0
  22. package/dist/analytics/xirr.js +314 -0
  23. package/dist/bin/cas.d.ts +2 -0
  24. package/dist/bin/cas.js +137 -0
  25. package/dist/checks.d.ts +49 -0
  26. package/dist/checks.js +227 -0
  27. package/dist/compat/casparser.d.ts +121 -0
  28. package/dist/compat/casparser.js +193 -0
  29. package/dist/detect.d.ts +10 -0
  30. package/dist/detect.js +69 -0
  31. package/dist/errors.d.ts +26 -0
  32. package/dist/errors.js +95 -0
  33. package/dist/export/csv.d.ts +21 -0
  34. package/dist/export/csv.js +49 -0
  35. package/dist/extract/browser.d.ts +17 -0
  36. package/dist/extract/browser.js +34 -0
  37. package/dist/extract/budget.d.ts +46 -0
  38. package/dist/extract/budget.js +88 -0
  39. package/dist/extract/node.d.ts +11 -0
  40. package/dist/extract/node.js +31 -0
  41. package/dist/extract/pdfjs.d.ts +71 -0
  42. package/dist/extract/pdfjs.js +244 -0
  43. package/dist/extract/types.d.ts +106 -0
  44. package/dist/extract/types.js +11 -0
  45. package/dist/index.d.ts +27 -0
  46. package/dist/index.js +26 -0
  47. package/dist/layout/lines.d.ts +51 -0
  48. package/dist/layout/lines.js +115 -0
  49. package/dist/licence/app-licence.d.ts +53 -0
  50. package/dist/licence/app-licence.js +139 -0
  51. package/dist/licence/ed25519.d.ts +2 -0
  52. package/dist/licence/ed25519.js +103 -0
  53. package/dist/model.d.ts +148 -0
  54. package/dist/model.js +1 -0
  55. package/dist/num.d.ts +19 -0
  56. package/dist/num.js +27 -0
  57. package/dist/parse.d.ts +4 -0
  58. package/dist/parse.js +13 -0
  59. package/dist/parsers/cams/classify.d.ts +25 -0
  60. package/dist/parsers/cams/classify.js +103 -0
  61. package/dist/parsers/cams/detailed.d.ts +15 -0
  62. package/dist/parsers/cams/detailed.js +343 -0
  63. package/dist/parsers/cams/header.d.ts +47 -0
  64. package/dist/parsers/cams/header.js +170 -0
  65. package/dist/parsers/cams/investor.d.ts +28 -0
  66. package/dist/parsers/cams/investor.js +139 -0
  67. package/dist/parsers/cams/summary.d.ts +29 -0
  68. package/dist/parsers/cams/summary.js +413 -0
  69. package/dist/parsers/cams/table.d.ts +55 -0
  70. package/dist/parsers/cams/table.js +144 -0
  71. package/dist/parsers/cams/total.d.ts +17 -0
  72. package/dist/parsers/cams/total.js +105 -0
  73. package/dist/parsers/depository/mf.d.ts +22 -0
  74. package/dist/parsers/depository/mf.js +438 -0
  75. package/dist/privacy.d.ts +243 -0
  76. package/dist/privacy.js +256 -0
  77. package/dist/schema.d.ts +779 -0
  78. package/dist/schema.js +214 -0
  79. package/examples/nextjs/app/page.jsx +34 -0
  80. package/examples/node/server.mjs +45 -0
  81. package/examples/python/read_cas.py +67 -0
  82. package/examples/vite/index.html +14 -0
  83. package/examples/vite/main.js +22 -0
  84. package/package.json +54 -4
@@ -0,0 +1,453 @@
1
+ import { productBound } from "../checks.js";
2
+ import { big } from "../num.js";
3
+ import { evaluateRequires, project } from "./contract.js";
4
+ import { daysBetween, solveXirr } from "./xirr.js";
5
+ export const XIRR_MANIFEST = {
6
+ id: "analysis.xirr",
7
+ version: "1.0.0",
8
+ produces: "xirr@1",
9
+ regClass: "computation",
10
+ requires: ["statement.detailed", "history.complete", "ledger.units.pass", "terminal.value.known", "ledger.running_balance.ok", "rows.purchase_identity.ok"],
11
+ consumes: {
12
+ families: ["mf-cas"],
13
+ instrumentKinds: ["mutual-fund-scheme"],
14
+ eventKinds: [
15
+ "PURCHASE", "PURCHASE_SIP", "REDEMPTION", "SWP", "SWITCH_IN", "SWITCH_OUT", "DIVIDEND_PAYOUT", "DIVIDEND_REINVEST",
16
+ "REVERSAL", "STAMP_DUTY_TAX", "STT_TAX", "TDS_TAX", "MISC", "PLEDGE", "PLEDGE_RELEASE",
17
+ ],
18
+ },
19
+ };
20
+ /* ---------- wording ---------- */
21
+ /** Kinds outside xirr@1's allowlist, with the M2 wording where one existed. */
22
+ const UNSUPPORTED_WORDS = {
23
+ UNKNOWN: "a transaction whose wording isn't recognised",
24
+ PLEDGE: "units moved out under a pledge",
25
+ PLEDGE_RELEASE: "units moved back from a pledge",
26
+ PLEDGE_INVOKED: "units redeemed by a lender under a pledge",
27
+ SEGREGATION: "a segregated portfolio",
28
+ GIFT_OUT: "units given away as a gift",
29
+ TRANSFER_OUT: "units transferred out to another folio or holder",
30
+ SWITCH_OUT_MERGER: "units moved out by a scheme merger",
31
+ };
32
+ /** Kinds whose history is outside the statement: history.complete already names them. */
33
+ const LINEAGE_WORDS = {
34
+ GIFT_IN: "gifted units",
35
+ SWITCH_IN_MERGER: "units from a scheme merger",
36
+ TRANSFER_IN: "units transferred in from another folio or holder",
37
+ BONUS: "bonus units",
38
+ UNIT_ADJUSTMENT: "a unit adjustment",
39
+ };
40
+ const SOLVER_WORDS = {
41
+ no_flows: "there are no cash flows to compute a rate from",
42
+ single_date: "every cash flow falls on one date, so there is no period to compute a rate over",
43
+ one_sided_flows: "the cash flows all go one way, so no rate fits them",
44
+ no_root: "no rate between −99.9999% and +100,000,000% a year fits these cash flows",
45
+ multiple_roots: "more than one rate could fit these cash flows, so none is shown",
46
+ no_convergence: "the rate could not be pinned down to the required precision",
47
+ residual_too_large: "the rate found doesn't reproduce the cash flows closely enough",
48
+ };
49
+ /* ---------- per scheme ---------- */
50
+ const PURCHASE_LIKE = new Set(["PURCHASE", "PURCHASE_SIP", "SWITCH_IN"]);
51
+ const OUTFLOW_LIKE = new Set(["REDEMPTION", "SWP", "SWITCH_OUT"]);
52
+ const STAMP_PARENTS = new Set([...PURCHASE_LIKE, "DIVIDEND_REINVEST", "SWITCH_IN_MERGER"]);
53
+ const TDS_PARENTS = new Set([...OUTFLOW_LIKE, "DIVIDEND_PAYOUT", "DIVIDEND_REINVEST"]);
54
+ const TRANSFER_WORDS_RE = /switch|lateral\s+shift|\bs\s*t\s*p\b|systematic\s+transfer/i;
55
+ const PAISA = big("0.01");
56
+ const fixed2 = (b) => b.toFixed(2);
57
+ const isZero = (n) => !n || big(n).eq(0);
58
+ /** The same-date row of one of `types` nearest before `row` (else nearest after), in statement order. */
59
+ function attach(rows, row, types) {
60
+ const same = rows.filter((t) => t !== row && t.date === row.date && types.has(t.type));
61
+ const before = same.filter((t) => t.order < row.order).sort((a, b) => b.order - a.order)[0];
62
+ return before ?? same.filter((t) => t.order > row.order).sort((a, b) => a.order - b.order)[0] ?? null;
63
+ }
64
+ function buildFlows(v) {
65
+ const { folio, scheme } = v;
66
+ const all = scheme.transactions;
67
+ const ref = (t) => ({ folio: folio.folio, rtaCode: scheme.rtaCode, ...(t ? { order: t.order, source: t.source } : {}) });
68
+ const reasons = [];
69
+ const once = new Set();
70
+ const block = (code, text, t) => {
71
+ const key = `${code}:${text}`;
72
+ if (once.has(key))
73
+ return;
74
+ once.add(key);
75
+ reasons.push({ code, text, ref: ref(t) });
76
+ };
77
+ const flows = [];
78
+ const legs = [];
79
+ const base = (t) => ({ order: t.order, date: t.date, type: t.type, source: t.source, parentOrder: null });
80
+ const include = (t, amount, role, parentOrder = null) => {
81
+ const f = { ...base(t), included: true, amount: fixed2(amount), role, exclusion: null, parentOrder };
82
+ flows.push(f);
83
+ return f;
84
+ };
85
+ const exclude = (t, exclusion, parentOrder = null) => {
86
+ flows.push({ ...base(t), included: false, amount: "0.00", role: null, exclusion, parentOrder });
87
+ };
88
+ const historyFailed = scheme.checks.some((c) => c.id === "history.complete" && c.status === "fail");
89
+ const outOfScope = new Set(v.outOfScope);
90
+ for (const t of all) {
91
+ if (outOfScope.has(t)) {
92
+ exclude(t, "not_supported");
93
+ const lineage = LINEAGE_WORDS[t.type];
94
+ if (lineage) {
95
+ if (!historyFailed)
96
+ block("event_not_supported", `it holds ${lineage}`, t);
97
+ }
98
+ else
99
+ block("event_not_supported", `it holds ${UNSUPPORTED_WORDS[t.type] ?? `a ${t.type.toLowerCase().replace(/_/g, " ")} row`}`, t);
100
+ continue;
101
+ }
102
+ const amount = t.amount ? big(t.amount) : null;
103
+ const units = t.units ? big(t.units) : null;
104
+ switch (t.type) {
105
+ case "PURCHASE":
106
+ case "PURCHASE_SIP":
107
+ case "SWITCH_IN": {
108
+ if (!amount) {
109
+ block("amount_missing", "a purchase row prints no amount", t);
110
+ exclude(t, "not_supported");
111
+ break;
112
+ }
113
+ if (amount.lte(0) || (units && units.lte(0))) {
114
+ block("sign_mismatch", "a purchase row's amount or units carry the wrong sign", t);
115
+ exclude(t, "not_supported");
116
+ break;
117
+ }
118
+ const f = include(t, amount.neg(), t.type === "SWITCH_IN" ? "switch_in" : "purchase");
119
+ if (t.type === "SWITCH_IN")
120
+ legs.push({ flow: f, txn: t, kind: "in" });
121
+ break;
122
+ }
123
+ case "REDEMPTION":
124
+ case "SWP":
125
+ case "SWITCH_OUT": {
126
+ if (!amount) {
127
+ block("amount_missing", "a redemption row prints no amount", t);
128
+ exclude(t, "not_supported");
129
+ break;
130
+ }
131
+ if (amount.gt(0) || (units && units.gte(0))) {
132
+ block("sign_mismatch", "a redemption row's amount or units carry the wrong sign", t);
133
+ exclude(t, "not_supported");
134
+ break;
135
+ }
136
+ const f = include(t, amount.abs(), t.type === "SWITCH_OUT" ? "switch_out" : "redemption");
137
+ if (t.type === "SWITCH_OUT")
138
+ legs.push({ flow: f, txn: t, kind: "out" });
139
+ break;
140
+ }
141
+ case "REVERSAL": {
142
+ if (!amount || !units) {
143
+ block("amount_missing", "a reversal row prints no amount or units", t);
144
+ exclude(t, "not_supported");
145
+ break;
146
+ }
147
+ if (!amount.eq(0) && amount.gt(0) !== units.gt(0)) {
148
+ block("sign_mismatch", "a reversal row's amount and units carry different signs", t);
149
+ exclude(t, "not_supported");
150
+ break;
151
+ }
152
+ const f = include(t, amount.neg(), "reversal");
153
+ if (TRANSFER_WORDS_RE.test(t.description))
154
+ legs.push({ flow: f, txn: t, kind: "reversed" });
155
+ break;
156
+ }
157
+ case "DIVIDEND_PAYOUT":
158
+ if (!amount) {
159
+ block("amount_missing", "an IDCW payout row prints no amount", t);
160
+ exclude(t, "not_supported");
161
+ }
162
+ else
163
+ include(t, amount.abs(), "idcw_payout");
164
+ break;
165
+ case "DIVIDEND_REINVEST":
166
+ exclude(t, "idcw_reinvested");
167
+ break;
168
+ case "STAMP_DUTY_TAX": {
169
+ const parent = attach(all, t, STAMP_PARENTS);
170
+ if (!parent)
171
+ block("stamp_unattributed", "a stamp duty row has no purchase on the same date", t);
172
+ else if (!amount)
173
+ block("amount_missing", "a stamp duty row prints no amount", t);
174
+ if (!parent || !amount)
175
+ exclude(t, "not_supported");
176
+ else if (parent.type === "DIVIDEND_REINVEST" || parent.type === "SWITCH_IN_MERGER")
177
+ exclude(t, "stamp_on_reinvestment", parent.order);
178
+ else
179
+ include(t, amount.abs().neg(), "stamp_duty", parent.order);
180
+ break;
181
+ }
182
+ case "STT_TAX":
183
+ exclude(t, "stt_inside_amount", attach(all, t, OUTFLOW_LIKE)?.order ?? null);
184
+ break;
185
+ case "TDS_TAX": {
186
+ const parent = attach(all, t, TDS_PARENTS);
187
+ const verdict = parent && amount ? tdsVerdict(scheme, parent, amount.abs()) : "unknown";
188
+ if (verdict === "withheld")
189
+ include(t, amount.abs(), "tds_withheld", parent.order);
190
+ else if (verdict === "inside")
191
+ exclude(t, "tds_inside_amount", parent.order);
192
+ else {
193
+ block("tds_unattributed", "the statement's figures don't show which payment a TDS row was withheld from", t);
194
+ exclude(t, "not_supported", parent?.order ?? null);
195
+ }
196
+ break;
197
+ }
198
+ case "MISC":
199
+ if (isZero(t.amount))
200
+ exclude(t, "informational_row");
201
+ else {
202
+ block("cash_row_unclassified", "a row without units carries an amount whose meaning isn't recognised", t);
203
+ exclude(t, "not_supported");
204
+ }
205
+ break;
206
+ case "PLEDGE":
207
+ case "PLEDGE_RELEASE":
208
+ // xirr@1 models these only as lien markers (KFintech prints zero units):
209
+ // units that actually move under a pledge have no cash meaning yet.
210
+ if (units && !units.eq(0)) {
211
+ block("event_not_supported", `it holds ${UNSUPPORTED_WORDS[t.type]}`, t);
212
+ exclude(t, "not_supported");
213
+ }
214
+ else if (!isZero(t.amount)) {
215
+ block("cash_row_unclassified", "a pledge row carries an amount", t);
216
+ exclude(t, "not_supported");
217
+ }
218
+ else
219
+ exclude(t, "lien_only");
220
+ break;
221
+ default:
222
+ exclude(t, "not_supported");
223
+ block("event_not_supported", `it holds a ${t.type.toLowerCase().replace(/_/g, " ")} row`, t);
224
+ }
225
+ }
226
+ // Terminal value: the printed market value, for a scheme with units left.
227
+ if (scheme.close && !big(scheme.close).eq(0) && scheme.valuation) {
228
+ const end = scheme.valuation.date;
229
+ const late = all.find((t) => t.date > end && flows.some((f) => f.order === t.order && f.included));
230
+ if (late)
231
+ block("flow_after_valuation", "a transaction is dated after the valuation date", late);
232
+ flows.push({
233
+ order: null, date: end, type: "TERMINAL_VALUE", included: true, amount: fixed2(big(scheme.valuation.value)), role: "terminal_value",
234
+ exclusion: null, parentOrder: null, source: scheme.footerSource,
235
+ });
236
+ }
237
+ return { flows, reasons, legs };
238
+ }
239
+ /**
240
+ * Was this TDS withheld from `parent`'s payment (add it back), already inside
241
+ * a printed gross amount (leave it out), or can't the figures tell?
242
+ */
243
+ function tdsVerdict(scheme, parent, tds) {
244
+ if (OUTFLOW_LIKE.has(parent.type)) {
245
+ if (!parent.amount || !parent.units || !parent.price || parent.price.raw === "derived")
246
+ return "unknown";
247
+ const gross = big(parent.units).abs().times(big(parent.price));
248
+ const net = big(parent.amount).abs();
249
+ const stt = scheme.transactions
250
+ .filter((t) => t.type === "STT_TAX" && t.date === parent.date && t.amount)
251
+ .reduce((acc, t) => acc.plus(big(t.amount).abs()), big(0));
252
+ // The deduction units × price − amount must cover STT and this TDS, within printed precision.
253
+ return gross.minus(net).plus(productBound(parent.units, parent.price, parent.amount)).gte(stt.plus(tds)) ? "withheld" : "unknown";
254
+ }
255
+ // IDCW: gross = rate × units held when it was paid.
256
+ if (!parent.dividendRate || !parent.amount || !scheme.open)
257
+ return "unknown";
258
+ const held = scheme.transactions
259
+ .filter((t) => t.order < parent.order && t.units)
260
+ .reduce((acc, t) => acc.plus(big(t.units)), big(scheme.open));
261
+ const gross = big(parent.dividendRate).times(held).round(2, 1);
262
+ const amount = big(parent.amount).abs();
263
+ if (amount.plus(tds).minus(gross).abs().lte(PAISA))
264
+ return "withheld";
265
+ if (parent.type === "DIVIDEND_PAYOUT" && amount.minus(gross).abs().lte(PAISA))
266
+ return "inside";
267
+ return "unknown";
268
+ }
269
+ function totalsOf(flows) {
270
+ let paidIn = big(0);
271
+ let received = big(0);
272
+ let terminal = big(0);
273
+ for (const f of flows) {
274
+ if (!f.included)
275
+ continue;
276
+ const a = big(f.amount);
277
+ if (f.role === "terminal_value")
278
+ terminal = terminal.plus(a);
279
+ else if (a.lt(0))
280
+ paidIn = paidIn.minus(a);
281
+ else
282
+ received = received.plus(a);
283
+ }
284
+ return { paidIn: fixed2(paidIn), received: fixed2(received), terminalValue: fixed2(terminal), net: fixed2(received.plus(terminal).minus(paidIn)) };
285
+ }
286
+ function solve(flows) {
287
+ const r = solveXirr(flows.filter((f) => f.included).map((f) => ({ date: f.date, amount: f.amount })));
288
+ if (r.status === "unavailable")
289
+ return { status: "unavailable", reason: { code: r.failure, text: SOLVER_WORDS[r.failure] } };
290
+ const method = r.iterations === 0 ? "grid" : r.bisectionSteps === 0 ? "newton" : r.newtonSteps === 0 ? "bisection" : "newton+bisection";
291
+ return {
292
+ status: "computed", rate: r.rate, percent: big(r.rate).times(100).round(2, 1).toFixed(2),
293
+ from: r.from, to: r.to, days: r.days, underOneYear: r.days < 365, iterations: r.iterations, method, residual: r.residual,
294
+ };
295
+ }
296
+ /**
297
+ * Predicates in manifest order, then what the rows themselves block. A summary
298
+ * statement stops at the first predicate: nothing else can be said.
299
+ */
300
+ function schemeEligibility(view, variant) {
301
+ const ctx = { variant, folio: view.folio, scheme: view.scheme };
302
+ const detailed = evaluateRequires(["statement.detailed"], ctx);
303
+ if (detailed.length)
304
+ return { eligibility: { state: "not_available", reasons: detailed }, built: { flows: [], reasons: [], legs: [] } };
305
+ const built = buildFlows(view);
306
+ const reasons = [...evaluateRequires(XIRR_MANIFEST.requires.slice(1), ctx), ...built.reasons];
307
+ return { eligibility: { state: reasons.length ? "not_available" : "eligible", reasons }, built };
308
+ }
309
+ function schemeWork(view, variant, solveRates) {
310
+ const { folio, scheme } = view;
311
+ const { eligibility, built } = schemeEligibility(view, variant);
312
+ const eligible = eligibility.state === "eligible";
313
+ return {
314
+ view, built,
315
+ out: {
316
+ folio: folio.folio, amc: folio.amc, rtaCode: scheme.rtaCode, name: scheme.name,
317
+ eligibility,
318
+ flows: built.flows,
319
+ totals: eligible ? totalsOf(built.flows) : null,
320
+ result: eligible && solveRates ? solve(built.flows) : null,
321
+ },
322
+ };
323
+ }
324
+ /* ---------- portfolio ---------- */
325
+ const MAX_TRANSFER_GAP_DAYS = 7;
326
+ function legOf(w, t) {
327
+ return { folio: w.view.folio.folio, rtaCode: w.view.scheme.rtaCode, order: t.order, date: t.date, amount: fixed2(big(t.amount).abs()), source: t.source };
328
+ }
329
+ function matchTransfers(works) {
330
+ const outs = [];
331
+ const ins = [];
332
+ const unmatched = [];
333
+ let idx = 0;
334
+ for (const w of works) {
335
+ for (const l of w.built.legs) {
336
+ const leg = { w, flow: l.flow, txn: l.txn, idx: idx++ };
337
+ if (l.kind === "out")
338
+ outs.push(leg);
339
+ else if (l.kind === "in")
340
+ ins.push(leg);
341
+ else
342
+ unmatched.push({ ...legOf(w, l.txn), type: l.txn.type });
343
+ }
344
+ }
345
+ const stampOf = (leg) => leg.w.built.flows.find((f) => f.role === "stamp_duty" && f.parentOrder === leg.txn.order) ?? null;
346
+ const used = new Set();
347
+ const matched = [];
348
+ const eliminated = new Set();
349
+ outs.sort((a, b) => a.txn.date.localeCompare(b.txn.date) || a.idx - b.idx);
350
+ for (const out of outs) {
351
+ const outAmount = big(out.txn.amount).abs();
352
+ let best = null;
353
+ for (const cand of ins) {
354
+ if (used.has(cand) || cand.w === out.w || cand.w.view.folio.amc !== out.w.view.folio.amc)
355
+ continue;
356
+ const gap = daysBetween(out.txn.date, cand.txn.date);
357
+ if (gap < 0 || gap > MAX_TRANSFER_GAP_DAYS)
358
+ continue;
359
+ const inAmount = big(cand.txn.amount);
360
+ const stamp = stampOf(cand);
361
+ let useStamp;
362
+ if (stamp && inAmount.plus(big(stamp.amount).abs()).eq(outAmount))
363
+ useStamp = stamp;
364
+ else if (inAmount.eq(outAmount))
365
+ useStamp = null;
366
+ if (useStamp === undefined)
367
+ continue;
368
+ if (!best || gap < best.gap || (gap === best.gap && cand.idx < best.leg.idx))
369
+ best = { leg: cand, gap, stamp: useStamp };
370
+ }
371
+ if (!best) {
372
+ unmatched.push({ ...legOf(out.w, out.txn), type: out.txn.type });
373
+ continue;
374
+ }
375
+ used.add(best.leg);
376
+ eliminated.add(out.flow).add(best.leg.flow);
377
+ if (best.stamp)
378
+ eliminated.add(best.stamp);
379
+ matched.push({
380
+ out: legOf(out.w, out.txn), in: legOf(best.leg.w, best.leg.txn),
381
+ stampDuty: best.stamp ? fixed2(big(best.stamp.amount).abs()) : "0.00", stampOrder: best.stamp?.order ?? null, gapDays: best.gap,
382
+ });
383
+ }
384
+ for (const leg of ins)
385
+ if (!used.has(leg))
386
+ unmatched.push({ ...legOf(leg.w, leg.txn), type: leg.txn.type });
387
+ unmatched.sort((a, b) => a.date.localeCompare(b.date) || a.order - b.order);
388
+ return { matched, unmatched, eliminated };
389
+ }
390
+ function portfolioReturns(works, variant, solveRates) {
391
+ const empty = (reasons) => ({
392
+ eligibility: { state: "not_available", reasons }, included: [], excluded: [], transfers: [], unmatched: [], valuationDate: null, flows: [], totals: null, result: null,
393
+ });
394
+ if (variant !== "DETAILED")
395
+ return empty([{ code: "summary_statement", text: "Summary statements have no transactions" }]);
396
+ if (works.length === 0)
397
+ return empty([{ code: "no_schemes", text: "The statement holds no schemes" }]);
398
+ const reasons = [];
399
+ const blocked = works.filter((w) => w.out.eligibility.state !== "eligible");
400
+ // Wording kept from M2 (eligibility.ts), which the coverage report shows.
401
+ if (blocked.length) {
402
+ reasons.push({ code: "scheme_not_eligible", text: `${blocked.length} of ${works.length} scheme(s) lack the history returns need (fully redeemed schemes count too)` });
403
+ }
404
+ const { matched, unmatched, eliminated } = matchTransfers(works);
405
+ for (const u of unmatched) {
406
+ reasons.push({
407
+ code: "unmatched_transfer", text: `a ${u.type === "SWITCH_OUT" ? "switch-out" : u.type === "SWITCH_IN" ? "switch-in" : "reversed switch"} on ${u.date} has no matching leg in this statement`,
408
+ ref: { folio: u.folio, rtaCode: u.rtaCode, order: u.order, source: u.source },
409
+ });
410
+ }
411
+ const terminalDates = new Set(works.flatMap((w) => w.built.flows.filter((f) => f.role === "terminal_value").map((f) => f.date)));
412
+ if (terminalDates.size > 1)
413
+ reasons.push({ code: "valuation_dates_differ", text: `schemes are valued on ${terminalDates.size} different dates, so there is no common end date` });
414
+ const valuationDate = terminalDates.size === 1 ? [...terminalDates][0] : null;
415
+ const eligible = reasons.length === 0;
416
+ const flows = eligible
417
+ ? works.flatMap((w) => w.built.flows.filter((f) => f.included && !eliminated.has(f)).map((f) => ({ ...f, folio: w.view.folio.folio, rtaCode: w.view.scheme.rtaCode })))
418
+ : [];
419
+ flows.sort((a, b) => a.date.localeCompare(b.date));
420
+ return {
421
+ eligibility: { state: eligible ? "eligible" : "not_available", reasons },
422
+ included: works.filter((w) => w.out.eligibility.state === "eligible").map((w) => ({ folio: w.out.folio, rtaCode: w.out.rtaCode, name: w.out.name })),
423
+ excluded: blocked.map((w) => ({ folio: w.out.folio, rtaCode: w.out.rtaCode, name: w.out.name, reasons: w.out.eligibility.reasons })),
424
+ transfers: matched,
425
+ unmatched,
426
+ valuationDate,
427
+ flows,
428
+ totals: eligible ? totalsOf(flows) : null,
429
+ result: eligible && solveRates ? solve(flows) : null,
430
+ };
431
+ }
432
+ /* ---------- the module ---------- */
433
+ /** xirr@1 over a projected view. With `solveRates` false, eligibility and flows only (results null). */
434
+ export function returnsFromView(view, solveRates = true) {
435
+ const works = view.schemes.map((s) => schemeWork(s, view.variant, solveRates));
436
+ return { produces: "xirr@1", dayCount: "Actual/365", schemes: works.map((w) => w.out), portfolio: portfolioReturns(works, view.variant, solveRates) };
437
+ }
438
+ export const xirrModule = {
439
+ manifest: XIRR_MANIFEST,
440
+ /** The portfolio's eligibility; each scheme's is in the output. */
441
+ eligibility: (view) => returnsFromView(view, false).portfolio.eligibility,
442
+ compute: (view) => returnsFromView(view),
443
+ };
444
+ /** xirr@1 for a parsed statement. */
445
+ export function returns(cas) {
446
+ return returnsFromView(project(cas, XIRR_MANIFEST.consumes));
447
+ }
448
+ /** One scheme's xirr@1 eligibility, without solving. */
449
+ export function schemeReturnsEligibility(folio, scheme, variant) {
450
+ const kinds = new Set(XIRR_MANIFEST.consumes.eventKinds);
451
+ const view = { folio, scheme, rows: scheme.transactions.filter((t) => kinds.has(t.type)), outOfScope: scheme.transactions.filter((t) => !kinds.has(t.type)) };
452
+ return schemeEligibility(view, variant).eligibility;
453
+ }
@@ -0,0 +1,77 @@
1
+ import { type Bucket, type GainsOutput } from "./gains.js";
2
+ export declare const CONSOLIDATED_ISIN = "INNOTREQUIRD";
3
+ export declare const CONSOLIDATED_NAME = "CONSOLIDATED";
4
+ /** The utility's ISIN for a unit without one (Schedule 112A CSV instructions, column 2). */
5
+ export declare const NO_ISIN = "INNOTAVAILAB";
6
+ export interface LotRef {
7
+ folio: string;
8
+ rtaCode: string;
9
+ saleOrder: number;
10
+ buyOrder: number;
11
+ }
12
+ export interface Row112A {
13
+ /** 1a: acquired on or before 31 Jan 2018 ("BE") or after ("AE"). */
14
+ acquired: "BE" | "AE";
15
+ /** 1b, FY 2024-25 only: transferred before 23 Jul 2024 ("BE") or on or after ("AE"); null other years. */
16
+ transferred: "BE" | "AE" | null;
17
+ isin: string;
18
+ name: string;
19
+ /** 4. "0" on the consolidated row. */
20
+ units: string;
21
+ /** 5. Printed sale price per unit (BE), sale value ÷ units (merged AE), "0" consolidated. */
22
+ salePrice: string;
23
+ /** 6 = sale value. */
24
+ fullValue: string;
25
+ /** 7 = higher of 8 and 9. */
26
+ costWithoutIndexation: string;
27
+ /** 8 = cost of acquisition, stamp duty included. */
28
+ cost: string;
29
+ /** 9 = lower of 6 and 11 (BE only, else "0"). */
30
+ lowerOfSaleAndFmv: string;
31
+ /** 10 = NAV on 31 Jan 2018 (BE only, else "0"). */
32
+ fmvPerUnit: string;
33
+ /** 11 = 4 × 10 (BE only, else "0"). */
34
+ fmvTotal: string;
35
+ /** 12. */
36
+ expenditure: string;
37
+ /** 13 = 7 + 12. */
38
+ deductions: string;
39
+ /** 14 = 6 − 13. */
40
+ balance: string;
41
+ /** A BE lot not grandfathered here (no 31 Jan 2018 NAV in the data pack, or units merged after that date): columns 9–11 are "0" and 14 is before grandfathering. */
42
+ fmvMissing: boolean;
43
+ lots: LotRef[];
44
+ }
45
+ export interface Schedule112A {
46
+ financialYear: string;
47
+ /** Column 1b is used (FY 2024-25 only). */
48
+ transferColumn: boolean;
49
+ /** AE rows merged into one (FY 2025-26 onward). */
50
+ consolidated: boolean;
51
+ /** Sales from 1 Apr 2026 fall under the Income-tax Act, 2025 (s.198 replaces s.112A). */
52
+ act2025: boolean;
53
+ rows: Row112A[];
54
+ /** Σ column 14. */
55
+ total: string;
56
+ /** Lots left out because their scheme's fund type isn't known yet. */
57
+ lotsWaitingForFundType: number;
58
+ }
59
+ /** Financial years with at least one long-term equity-oriented sale from 1 Apr 2018 (when s.112A began), newest first. */
60
+ export declare function years112A(out: GainsOutput): string[];
61
+ export declare function schedule112A(out: GainsOutput, fy: string): Schedule112A;
62
+ export { QUARTERS, quarterOf, type Quarter } from "./gains.js";
63
+ export interface QuarterlyRow {
64
+ bucket: Bucket;
65
+ /** Gain by window, in QUARTERS order: equity long term after grandfathering; other long term after indexation when it applied. */
66
+ amounts: string[];
67
+ total: string;
68
+ }
69
+ export declare function quarterlyGains(out: GainsOutput, fy: string): QuarterlyRow[];
70
+ export declare const HEADER_112A: readonly ["Share/Unit acquired(1a)", "ISIN Code(2)", "Name of the Share/Unit(3)", "No. of Shares/Units(4)", "Sale-price per Share/Unit(5)", "Full Value of Consideration(Total Sale Value)(6) = 4 * 5", "Cost of acquisition without indexation(7)", "Cost of acquisition(8)", "If the long term capital asset was acquired before 01.02.2018(9)", "Fair Market Value per share/unit as on 31st January 2018(10)", "Total Fair Market Value of capital asset as per section 55(2)(ac)(11) = 4 * 10", "Expenditure wholly and exclusively in connection with transfer(12)", "Total deductions(13) = 7 + 12", "Balance(14) = 6 - 13"];
71
+ /** Whole rupees, half up: the utility rejects decimals in amount fields. */
72
+ export declare const rupees: (v: string) => string;
73
+ /** The schedule as the ITR utility's CSV columns (column 1b inserted for FY 2024-25). Plain text cells; the caller quotes them. */
74
+ export declare function schedule112ACells(s: Schedule112A): {
75
+ header: string[];
76
+ rows: string[][];
77
+ };
@@ -0,0 +1,134 @@
1
+ import { big } from "../num.js";
2
+ import { GRANDFATHER_BUY_BY, GRANDFATHER_SELL_FROM, QUARTERS, REGIME_2024, windowAmount } from "./gains.js";
3
+ export const CONSOLIDATED_ISIN = "INNOTREQUIRD";
4
+ export const CONSOLIDATED_NAME = "CONSOLIDATED";
5
+ /** The utility's ISIN for a unit without one (Schedule 112A CSV instructions, column 2). */
6
+ export const NO_ISIN = "INNOTAVAILAB";
7
+ const r2 = (b) => b.round(2, 1);
8
+ const fyStart = (fy) => Number(fy.slice(0, 4));
9
+ function row(acquired, transferred, isin, name, units, salePrice, sale, cost, fmvPerUnit, fmvMissing, lots) {
10
+ const fmvTotal = fmvPerUnit ? r2(units.times(fmvPerUnit)) : big(0);
11
+ const col9 = acquired === "BE" && fmvPerUnit ? (fmvTotal.lt(sale) ? fmvTotal : sale) : big(0);
12
+ const col7 = cost.gt(col9) ? cost : col9;
13
+ return {
14
+ acquired, transferred, isin, name, units: units.toString(), salePrice: salePrice.toString(),
15
+ fullValue: sale.toFixed(2), costWithoutIndexation: col7.toFixed(2), cost: cost.toFixed(2), lowerOfSaleAndFmv: col9.toFixed(2),
16
+ fmvPerUnit: fmvPerUnit ? fmvPerUnit.toString() : "0", fmvTotal: fmvTotal.toFixed(2), expenditure: "0.00",
17
+ deductions: col7.toFixed(2), balance: sale.minus(col7).toFixed(2), fmvMissing, lots,
18
+ };
19
+ }
20
+ const ref = (s, l) => ({ folio: s.folio, rtaCode: s.rtaCode, saleOrder: l.saleOrder, buyOrder: l.buyOrder });
21
+ /** Financial years with at least one long-term equity-oriented sale from 1 Apr 2018 (when s.112A began), newest first. */
22
+ export function years112A(out) {
23
+ const ys = new Set(out.schemes.filter((s) => s.included && s.fundType === "equity_oriented").flatMap((s) => s.realised.filter((l) => l.term === "long" && l.saleDate >= GRANDFATHER_SELL_FROM).map((l) => l.financialYear)));
24
+ return [...ys].sort().reverse();
25
+ }
26
+ export function schedule112A(out, fy) {
27
+ const transferColumn = fyStart(fy) === 2024;
28
+ const consolidated = fyStart(fy) >= 2025;
29
+ const rows = [];
30
+ let waiting = 0;
31
+ for (const s of out.schemes.filter((x) => x.included)) {
32
+ const inYear = s.realised.filter((l) => l.financialYear === fy);
33
+ if (s.fundType === null) {
34
+ waiting += inYear.length;
35
+ continue;
36
+ }
37
+ if (s.fundType !== "equity_oriented")
38
+ continue;
39
+ const ae = new Map();
40
+ // s.112A applies to transfers from 1 Apr 2018; earlier long-term gains were under s.10(38).
41
+ for (const l of inYear.filter((x) => x.term === "long" && x.saleDate >= GRANDFATHER_SELL_FROM)) {
42
+ const transferred = transferColumn ? (l.saleDate < REGIME_2024 ? "BE" : "AE") : null;
43
+ if (l.buyDate <= GRANDFATHER_BUY_BY) {
44
+ const nav = l.grandfathering ? big(l.grandfathering.navOn31Jan2018) : null;
45
+ const price = l.salePrice ? big(l.salePrice) : big(l.saleValue).div(l.units).round(4, 1);
46
+ rows.push(row("BE", transferred, s.isin ?? NO_ISIN, s.scheme, big(l.units), price, big(l.saleValue), big(l.cost), nav, l.grandfatheringMissing || l.flags.includes("grandfathering_merged_after_31jan2018"), [ref(s, l)]));
47
+ }
48
+ else {
49
+ const key = transferred ?? "";
50
+ const m = ae.get(key) ?? { units: big(0), sale: big(0), cost: big(0), lots: [] };
51
+ m.units = m.units.plus(l.units);
52
+ m.sale = m.sale.plus(l.saleValue);
53
+ m.cost = m.cost.plus(l.cost);
54
+ m.lots.push(ref(s, l));
55
+ ae.set(key, m);
56
+ }
57
+ }
58
+ for (const [key, m] of ae) {
59
+ rows.push(row("AE", transferColumn ? key : null, s.isin ?? NO_ISIN, s.scheme, m.units, m.sale.div(m.units).round(3, 1), m.sale, m.cost, null, false, m.lots));
60
+ }
61
+ }
62
+ let final = rows;
63
+ if (consolidated && rows.some((r) => r.acquired === "AE")) {
64
+ const ae = rows.filter((r) => r.acquired === "AE");
65
+ const sum = (k) => ae.reduce((a, r) => a.plus(r[k]), big(0));
66
+ final = [
67
+ ...rows.filter((r) => r.acquired === "BE"),
68
+ { ...row("AE", null, CONSOLIDATED_ISIN, CONSOLIDATED_NAME, big(0), big(0), sum("fullValue"), sum("cost"), null, false, ae.flatMap((r) => r.lots)), units: "0", salePrice: "0" },
69
+ ];
70
+ }
71
+ return {
72
+ financialYear: fy, transferColumn, consolidated, act2025: fyStart(fy) >= 2026, rows: final,
73
+ total: final.reduce((a, r) => a.plus(r.balance), big(0)).toFixed(2), lotsWaitingForFundType: waiting,
74
+ };
75
+ }
76
+ /* ---------- quarterly split ---------- */
77
+ export { QUARTERS, quarterOf } from "./gains.js";
78
+ export function quarterlyGains(out, fy) {
79
+ const map = new Map();
80
+ for (const s of out.schemes.filter((x) => x.included)) {
81
+ for (const l of s.realised.filter((x) => x.financialYear === fy)) {
82
+ const bucket = !l.term || !s.fundType ? "depends" : `${s.fundType === "equity_oriented" ? "equity" : "other"}_${l.term}`;
83
+ const amount = windowAmount(bucket, l);
84
+ const q = QUARTERS.indexOf(l.window);
85
+ const row = map.get(bucket) ?? QUARTERS.map(() => big(0));
86
+ row[q] = row[q].plus(amount);
87
+ map.set(bucket, row);
88
+ }
89
+ }
90
+ const order = ["equity_short", "equity_long", "other_short", "other_long", "depends"];
91
+ return order.filter((b) => map.has(b)).map((b) => {
92
+ const xs = map.get(b);
93
+ return { bucket: b, amounts: xs.map((x) => x.toFixed(2)), total: xs.reduce((a, x) => a.plus(x), big(0)).toFixed(2) };
94
+ });
95
+ }
96
+ /* ---------- CSV ---------- */
97
+ export const HEADER_112A = [
98
+ "Share/Unit acquired(1a)",
99
+ "ISIN Code(2)",
100
+ "Name of the Share/Unit(3)",
101
+ "No. of Shares/Units(4)",
102
+ "Sale-price per Share/Unit(5)",
103
+ "Full Value of Consideration(Total Sale Value)(6) = 4 * 5",
104
+ "Cost of acquisition without indexation(7)",
105
+ "Cost of acquisition(8)",
106
+ "If the long term capital asset was acquired before 01.02.2018(9)",
107
+ "Fair Market Value per share/unit as on 31st January 2018(10)",
108
+ "Total Fair Market Value of capital asset as per section 55(2)(ac)(11) = 4 * 10",
109
+ "Expenditure wholly and exclusively in connection with transfer(12)",
110
+ "Total deductions(13) = 7 + 12",
111
+ "Balance(14) = 6 - 13",
112
+ ];
113
+ /** Whole rupees, half up: the utility rejects decimals in amount fields. */
114
+ export const rupees = (v) => big(v).round(0, 1).toFixed(0);
115
+ /** The schedule as the ITR utility's CSV columns (column 1b inserted for FY 2024-25). Plain text cells; the caller quotes them. */
116
+ export function schedule112ACells(s) {
117
+ const header = [...HEADER_112A];
118
+ if (s.transferColumn)
119
+ header.splice(1, 0, "Share/Unit Transferred(1b)");
120
+ const rows = s.rows.map((r) => {
121
+ // Merged after-2018 rows: the utility takes 6, 8 and 12; 4 and 5 are 0 there.
122
+ const ae = r.acquired === "AE";
123
+ const cells = [
124
+ r.acquired, r.isin, r.name, ae ? "0" : r.units, ae ? "0" : r.salePrice, rupees(r.fullValue), rupees(r.costWithoutIndexation), rupees(r.cost),
125
+ rupees(r.lowerOfSaleAndFmv), r.fmvPerUnit, rupees(r.fmvTotal), rupees(r.expenditure), rupees(r.deductions),
126
+ // 14 from the rounded 6 and 13, so the row adds up as printed.
127
+ big(rupees(r.fullValue)).minus(rupees(r.deductions)).toFixed(0),
128
+ ];
129
+ if (s.transferColumn)
130
+ cells.splice(1, 0, r.transferred ?? "");
131
+ return cells;
132
+ });
133
+ return { header, rows };
134
+ }