@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
package/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0-beta.1 (18-Nov-2026, first release on npm)
4
+
5
+ - **NSDL and CDSL statements:** mutual fund units and ETFs, held as folios or in demat, with units, NAV, value and cost where printed. A holding is read only when its printed units × NAV equals its printed value; the statement's printed total for mutual fund folios is checked (`total.mf_folios`). Shares, bonds and NPS are named in `warnings`, not read. `source.variant` is `"DEMAT"`.
6
+ - `readCas(bytes, { password })` from `@sachfolio/cas-reader/node`, and `createCasReader({ assetsUrl })` from the new `@sachfolio/cas-reader/browser` entry.
7
+ - `sachfolio-cas copy-assets <folder>`: pdf.js's worker and data files for a browser app to serve itself.
8
+ - `toCasparserDemat(cas)`: casparser's NSDL/CDSL JSON shape.
9
+ - App licence codes: `checkAppLicence(code)` and `sachfolio-cas licence <code>`, offline. Reading never depends on them.
10
+ - Recipes for Vite and Next.js; the older plain browser example is replaced by the Vite one.
11
+ - `CAS_ERRORS`: a message, a next step and whether to retry, for every error code.
12
+ - `toHoldingsCsv(cas)` and `toTransactionsCsv(cas)`: CSV with exact decimal strings, ISO dates and a guard against spreadsheet formulas.
13
+ - README: React and Vue examples, and "Using partial results".
14
+
15
+ No breaking changes: CAMS and KFintech results are unchanged.
16
+
17
+ ## 0.1.0-beta.1 (Oct-2026)
18
+
19
+ First release, sent on request: CAMS and KFintech, detailed and summary; casparser-compatible output; command line; Python wrapper.
package/LICENSE ADDED
@@ -0,0 +1,71 @@
1
+ License text copyright (c) 2020 MariaDB Corporation Ab, All Rights Reserved.
2
+ "Business Source License" is a trademark of MariaDB Corporation Ab.
3
+
4
+ Parameters
5
+
6
+ Licensor: Sachfolio (https://sachfolio.com). DRAFT: the Licensor's
7
+ legal name is to be confirmed with counsel before the
8
+ first commercial licence is signed.
9
+ Licensed Work: @sachfolio/cas-reader 0.1.0-beta.1. The Licensed Work is
10
+ (c) 2026 Sachfolio.
11
+ Additional Use Grant: You may use the Licensed Work in production only:
12
+ (a) for your own personal, non-commercial purposes,
13
+ including reading statements of your own family;
14
+ (b) for evaluation, testing and development, provided no
15
+ statements of your customers or clients are processed
16
+ in a live product or service; or
17
+ (c) through the official Sachfolio apps and websites.
18
+ Any other production use, including embedding the
19
+ Licensed Work in a product or service, or processing
20
+ other people's statements for a business, requires a
21
+ commercial licence from the Licensor.
22
+ Change Date: 2029-10-20
23
+ Change License: Apache License, Version 2.0
24
+
25
+ For information about alternative licensing arrangements for the Licensed Work,
26
+ please contact support@sachfolio.com.
27
+
28
+ Notice
29
+
30
+ Business Source License 1.1
31
+
32
+ Terms
33
+
34
+ The Licensor hereby grants you the right to copy, modify, create derivative
35
+ works, redistribute, and make non-production use of the Licensed Work. The
36
+ Licensor may make an Additional Use Grant, above, permitting limited production use.
37
+
38
+ Effective on the Change Date, or the fourth anniversary of the first publicly
39
+ available distribution of a specific version of the Licensed Work under this
40
+ License, whichever comes first, the Licensor hereby grants you rights under
41
+ the terms of the Change License, and the rights granted in the paragraph
42
+ above terminate.
43
+
44
+ If your use of the Licensed Work does not comply with the requirements
45
+ currently in effect as described in this License, you must purchase a
46
+ commercial license from the Licensor, its affiliated entities, or authorized
47
+ resellers, or you must refrain from using the Licensed Work.
48
+
49
+ All copies of the original and modified Licensed Work, and derivative works
50
+ of the Licensed Work, are subject to this License. This License applies
51
+ separately for each version of the Licensed Work and the Change Date may vary
52
+ for each version of the Licensed Work released by Licensor.
53
+
54
+ You must conspicuously display this License on each original or modified copy
55
+ of the Licensed Work. If you receive the Licensed Work in original or
56
+ modified form from a third party, the terms and conditions set forth in this
57
+ License apply to your use of that work.
58
+
59
+ Any use of the Licensed Work in violation of this License will automatically
60
+ terminate your rights under this License for the current and all other
61
+ versions of the Licensed Work.
62
+
63
+ This License does not grant you any right in any trademark or logo of
64
+ Licensor or its affiliates (provided that you may use a trademark or logo of
65
+ Licensor as expressly required by this License).
66
+
67
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
68
+ AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
69
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
70
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
71
+ TITLE.
package/NOTICE ADDED
@@ -0,0 +1,41 @@
1
+ @sachfolio/cas-reader
2
+ Copyright (c) 2026 Sachfolio. Licensed under the Business Source License 1.1
3
+ (see LICENSE).
4
+
5
+ This product includes logic ported from casparser
6
+ (https://github.com/codereverser/casparser), used under the MIT License:
7
+
8
+ The MIT License (MIT)
9
+
10
+ Copyright (c) 2020 Sandeep Somasekharan <codereverser@gmail.com>
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in
20
+ all copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+
30
+ The 31 Jan 2018 NAV data pack (refdata/nav-2018-01-31.json, used for
31
+ grandfathering) is taken from casparser-isin
32
+ (https://github.com/codereverser/casparser-isin), by the same author under
33
+ the same MIT License; the NAVs are as published by AMFI.
34
+
35
+ The casparser-compatible output reproduces the shape of casparser's CASData
36
+ JSON so that code written for casparser can read it.
37
+
38
+ Dependencies installed alongside this package, each under its own licence:
39
+ pdfjs-dist (Apache License 2.0, Mozilla Foundation)
40
+ big.js (MIT, Michael Mclaughlin)
41
+ zod (MIT, Colin McDonnell)
package/README.md CHANGED
@@ -1,3 +1,199 @@
1
- # Temporary Holding Version
1
+ # @sachfolio/cas-reader
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Read Indian mutual fund consolidated account statements (CAS PDFs) inside your own app. The PDF and its password are read where this package runs: in your user's browser, or on your server. They go to no third party, and the package makes no network requests of its own.
4
+
5
+ **Beta.** Tested on invented statements, casparser cross-checks and a small set of real CAMS and KFintech statements. Check `checks` on every result before relying on a number.
6
+
7
+ ## What it reads
8
+
9
+ | Statement | What you get |
10
+ |---|---|
11
+ | CAMS and KFintech, detailed | Holdings, every transaction, checks, returns (XIRR) and capital gains where the history allows |
12
+ | CAMS and KFintech, summary | Holdings |
13
+ | NSDL and CDSL | Mutual fund units and ETFs, with units, NAV, value and cost where printed. Shares, bonds and NPS are named in `warnings`, not read |
14
+ | MF Central, re-printed ("print to PDF") copies, scans | A clear error code |
15
+
16
+ Unsupported files fail with an error code instead of a wrong answer. A holding whose printed numbers don't add up is skipped and counted in `coverage`, never guessed.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install @sachfolio/cas-reader
22
+ ```
23
+
24
+ Node 22.13 or later. Dependencies (`pdfjs-dist`, `big.js`, `zod`) are pinned to exact versions.
25
+
26
+ ## In the browser (recommended)
27
+
28
+ The statement never reaches your servers, which keeps you out of handling the PDF and its password.
29
+
30
+ ```bash
31
+ npx sachfolio-cas copy-assets public/pdfjs
32
+ ```
33
+
34
+ ```js
35
+ import { createCasReader, isCasError } from "@sachfolio/cas-reader/browser";
36
+
37
+ const reader = createCasReader({ assetsUrl: "/pdfjs/" });
38
+ try {
39
+ const cas = await reader.readCas(new Uint8Array(await file.arrayBuffer()), { password });
40
+ } catch (e) {
41
+ if (isCasError(e)) console.log(e.code); // INCORRECT_PASSWORD, UNKNOWN_TEMPLATE, …
42
+ }
43
+ ```
44
+
45
+ `copy-assets` copies pdf.js's worker, fonts, cmaps and wasm decoders, so your site serves them itself. Recipes:
46
+ - **Vite**: `examples/vite` (built by our release tests).
47
+ - **Next.js** (App Router): `examples/nextjs/app/page.jsx`. Import the reader when the user picks a file, not during server rendering. Not yet run in our release tests.
48
+
49
+ **React** (not run in our release tests):
50
+
51
+ ```jsx
52
+ import { useState } from "react";
53
+ import { createCasReader, isCasError } from "@sachfolio/cas-reader/browser";
54
+
55
+ const reader = createCasReader({ assetsUrl: "/pdfjs/" });
56
+
57
+ export function StatementPicker({ password, onRead }) {
58
+ const [error, setError] = useState(null);
59
+ async function onFile(e) {
60
+ const file = e.target.files?.[0];
61
+ if (!file) return;
62
+ try {
63
+ onRead(await reader.readCas(new Uint8Array(await file.arrayBuffer()), { password }));
64
+ setError(null);
65
+ } catch (err) {
66
+ setError(isCasError(err) ? err.code : "UNEXPECTED");
67
+ }
68
+ }
69
+ return (
70
+ <>
71
+ <input type="file" accept="application/pdf" onChange={onFile} />
72
+ {error && <p role="alert">{error}</p>}
73
+ </>
74
+ );
75
+ }
76
+ ```
77
+
78
+ In Next.js, import the reader inside the handler (`await import(...)`), not at module level.
79
+
80
+ **Vue 3** (not run in our release tests):
81
+
82
+ ```vue
83
+ <script setup>
84
+ import { ref } from "vue";
85
+ import { createCasReader, isCasError } from "@sachfolio/cas-reader/browser";
86
+
87
+ const props = defineProps({ password: String });
88
+ const emit = defineEmits(["read"]);
89
+ const error = ref(null);
90
+ const reader = createCasReader({ assetsUrl: "/pdfjs/" });
91
+
92
+ async function onFile(e) {
93
+ const file = e.target.files?.[0];
94
+ if (!file) return;
95
+ try {
96
+ emit("read", await reader.readCas(new Uint8Array(await file.arrayBuffer()), { password: props.password }));
97
+ error.value = null;
98
+ } catch (err) {
99
+ error.value = isCasError(err) ? err.code : "UNEXPECTED";
100
+ }
101
+ }
102
+ </script>
103
+
104
+ <template>
105
+ <input type="file" accept="application/pdf" @change="onFile" />
106
+ <p v-if="error" role="alert">{{ error }}</p>
107
+ </template>
108
+ ```
109
+
110
+ ## CSV for spreadsheets
111
+
112
+ `toHoldingsCsv(cas)` and `toTransactionsCsv(cas)` return CSV text (from the main entry and from `/browser`), one row per holding or per transaction after a header row:
113
+
114
+ ```js
115
+ import { toHoldingsCsv, toTransactionsCsv } from "@sachfolio/cas-reader";
116
+
117
+ const holdings = toHoldingsCsv(cas); // Fund house, Folio, Scheme, ISIN, Plan, Option, Closing units, NAV, NAV date, Value, Value date, Page
118
+ const transactions = toTransactionsCsv(cas); // Fund house, Folio, Scheme, ISIN, Date, Type, Description, Amount, Units, Price, Unit balance, Page
119
+ ```
120
+
121
+ - Numbers are exact decimal strings (`1234.50`, `-5000.00`): ungrouped, never rounded through a float. A value the statement doesn't print is an empty cell, never 0.
122
+ - Dates are ISO (`2026-09-30`).
123
+ - Text cells starting with `=`, `+`, `-` or `@` (or a tab or carriage return) get a leading `'`, so a spreadsheet can't run statement text as a formula. Cells with commas, quotes or line breaks are quoted (RFC 4180); rows end in CRLF.
124
+ - No byte-order mark. For Excel to show `₹` and accented names, save with `"" + csv`.
125
+
126
+ ## In Node
127
+
128
+ ```js
129
+ import { readFile } from "node:fs/promises";
130
+ import { readCas } from "@sachfolio/cas-reader/node";
131
+
132
+ const cas = await readCas(new Uint8Array(await readFile("statement.pdf")), { password });
133
+ ```
134
+
135
+ Passwords: for CAMS and KFintech, the one set on the request form; for NSDL and CDSL, the first holder's PAN in capitals.
136
+
137
+ ## Switching from casparser
138
+
139
+ `toCasparser(cas)` returns casparser's CAMS/KFintech `CASData` JSON; `toCasparserDemat(cas)` returns its NSDL/CDSL `NSDLCASData` JSON (mutual funds only). Code written for casparser's JSON keeps working.
140
+
141
+ Differences to know:
142
+ - `amfi` and `type` are `null` (casparser fills them from its own ISIN database).
143
+ - Transaction types casparser has no name for are folded in: systematic withdrawals and pledge invocations become `REDEMPTION`; bonus units, transfers, pledges and unit adjustments become `MISC`.
144
+ - `parse_warnings` lists every check that failed, not only unit-balance breaks.
145
+ - For NSDL/CDSL, `equities`, `bonds` and `owners` are empty, and an account's `balance` is the mutual fund value read, not the statement's account total.
146
+ - Page references and checks are not in these shapes. Keep the `CasDocument` if you want them.
147
+
148
+ **From Python**, see `examples/python/read_cas.py`: a drop-in `read_cas_pdf(path, password)` that calls the command-line tool. A fuller wrapper with `read_cas(path, password, format)` and `CasError` codes is in `packages/python` (repo only, not yet published). A local MCP server for AI assistants is in `packages/mcp`.
149
+
150
+ ## Command line
151
+
152
+ ```bash
153
+ npx sachfolio-cas statement.pdf --format casparser --out result.json
154
+ echo "$PASSWORD" | npx sachfolio-cas statement.pdf --password-stdin
155
+ npx sachfolio-cas copy-assets public/pdfjs
156
+ npx sachfolio-cas licence SF1.…
157
+ ```
158
+
159
+ There is no `--password` flag on purpose: arguments end up in shell history and the process list. Exit codes: 0 done, 1 the statement could not be read (stderr starts with the error code), 2 usage.
160
+
161
+ ## The output
162
+
163
+ `CasDocument` (schema `cas-document` v1, JSON Schema via `casDocumentJsonSchema`):
164
+ - every printed number as `{ raw, value, scale }`: `value` is an exact decimal string, never a float;
165
+ - every value's `source`: the page and line it was printed on;
166
+ - `checks` on each holding and on the statement, each `pass`, `fail`, `unavailable` or `not_applicable`: units add up, the running balance holds, units × NAV matches the printed value, the ISIN is valid, and the statement's printed total matches;
167
+ - `coverage` and `warnings`: what was seen, read and left out, so nothing disappears silently.
168
+
169
+ Extras: `analyze()`, `returns()` (XIRR), `gains()`, `redactCas()` and `PRIVACY` (the privacy class of every field, so you can keep personal data out of logs).
170
+
171
+ ## Using partial results
172
+
173
+ A statement can be read in part; that is a normal result, not an error. Handle it like this:
174
+ 1. Check `cas.source.engineVersion`, `cas.schemaVersion` (`"1"`) and `analyze(cas).analyticsVersion` against what you built for.
175
+ 2. Read `cas.coverage` (`datedRowsSeen` against `transactionsParsed`, `datedRowsSkipped`, `schemeRegionsUnbuilt`) and `cas.warnings`.
176
+ 3. Show the holdings of `analyze(cas).schemes` where `holdings.eligible` is true.
177
+ 4. Tell the user what was left out and why (`holdings.reasons`), never a total that quietly skips a scheme.
178
+ 5. Show returns and gains only where their own eligibility allows: `returns.schemes[].eligibility`, `gains(cas).schemes[].included`.
179
+ 6. Repeat imports (identity across statements, replacing or merging snapshots) are your app's job; the reader keeps no state.
180
+ 7. `toCasparser()` output has no page tags, checks or coverage: keep the `CasDocument` if you need to say what was left out.
181
+
182
+ Failures throw a `CasError`: `CAS_ERRORS[e.code]` has `message`, `nextStep` and `retry` you can show your user. Questions: developers@sachfolio.com.
183
+
184
+ ## Privacy
185
+
186
+ A parsed statement holds names, PANs, folios, holdings and transactions. Treat it like the PDF: don't log it, don't put it in URLs, and use `redactCas()` before anything leaves your systems.
187
+
188
+ ## Licence
189
+
190
+ Business Source License 1.1 (`LICENSE`, `NOTICE`). Personal use and evaluation are free. Using it in a product or service needs a commercial licence: one flat yearly price per app, with unlimited reads. Write to developers@sachfolio.com.
191
+
192
+ Your licence comes as a code. `checkAppLicence(code)` (or `npx sachfolio-cas licence <code>`) checks it offline against our public key and tells you the app it covers and its dates. Reading statements never depends on it: the package never calls home and never stops working on a date.
193
+
194
+ ## Versions, fixes and support
195
+
196
+ - Releases follow semantic versioning. A breaking change to the output gets 90 days' notice and a new schema version.
197
+ - When CAMS, KFintech, NSDL or CDSL change a layout, a fix ships within 5 working days of a masked copy reaching us. Send the `Copy check summary` counts or a masked copy, never a customer's statement.
198
+ - Support by email, answered within 2 working days: developers@sachfolio.com.
199
+ - An installed copy doesn't get fixes until you upgrade: `npm install @sachfolio/cas-reader@latest`, then read `CHANGELOG.md` for anything to change.
@@ -0,0 +1,110 @@
1
+ /**
2
+ * The analysis contract (docs/architecture/ROADMAP.md M4 "Analysis contract";
3
+ * FEATURES.md B.6; ADR-0007 §6). Every analysis declares, in a manifest:
4
+ *
5
+ * - `requires`: evidence predicates from the registry below, evaluated per
6
+ * scheme into plain-language reasons;
7
+ * - `consumes`: the event kinds (transaction types) it understands. The
8
+ * kernel hands it a view projected to those kinds; anything else is listed
9
+ * as out of scope, never silently dropped;
10
+ * - `regClass`: the regulatory class of what it outputs (fact, computation…);
11
+ *
12
+ * and reports three-state eligibility: `eligible`, `partial` (some schemes or
13
+ * rows left out, each listed with a reason) or `not_available` (why, so the
14
+ * UI can say "Not available for this statement" and how to fix it).
15
+ *
16
+ * This is the in-bundle form of the contract. Modules are plain objects in
17
+ * the engine today; the sandbox, signing and dynamic loading come later
18
+ * (ROADMAP M4/M7) without changing these shapes.
19
+ */
20
+ import type { CasDocument, Folio, Scheme, Source, Transaction, TxnType } from "../model.js";
21
+ /** Regulatory class of anything that computes or presents numbers (FEATURES.md B.5). */
22
+ export type RegClass = "fact" | "computation" | "estimate" | "tax-estimate" | "comparison" | "projection" | "advice";
23
+ export type EligibilityState = "eligible" | "partial" | "not_available";
24
+ /** Points at the evidence a reason is about: a scheme, and optionally one row. */
25
+ export interface EvidenceRef {
26
+ folio: string;
27
+ rtaCode: string;
28
+ /** Transaction.order of the row, when the reason is about one row. */
29
+ order?: number;
30
+ source?: Source;
31
+ }
32
+ /** A machine-readable code with the engine's plain-language wording; the UI maps codes to its own copy. */
33
+ export interface Reason<C extends string = string> {
34
+ code: C;
35
+ text: string;
36
+ ref?: EvidenceRef;
37
+ }
38
+ export interface ModuleEligibility<C extends string = string> {
39
+ state: EligibilityState;
40
+ /** Why it is not available, or (when `partial`) what was left out. Empty when `eligible`. */
41
+ reasons: Reason<C>[];
42
+ }
43
+ /** Evidence predicates the registry knows (FEATURES.md B.6 `Predicate`). */
44
+ export type PredicateId = "statement.detailed" | "history.complete" | "ledger.units.pass" | "valuation.pass"
45
+ /** The closing value is known: the valuation check passes, or the units are exactly zero. */
46
+ | "terminal.value.known"
47
+ /** The running-balance chain passes or there is nothing to chain. */
48
+ | "ledger.running_balance.ok"
49
+ /** Purchase rows match units × price, or there are none. */
50
+ | "rows.purchase_identity.ok";
51
+ export interface Consumes {
52
+ /** Evidence families read. Only the mutual-fund CAS exists today. */
53
+ families: readonly string[];
54
+ instrumentKinds: readonly string[];
55
+ /** Transaction types understood, or "*" for every kind (facts that read rows without interpreting cash). */
56
+ eventKinds: readonly TxnType[] | "*";
57
+ }
58
+ export interface AnalysisManifest {
59
+ /** Reverse-namespaced id, e.g. "analysis.xirr". */
60
+ id: string;
61
+ version: string;
62
+ /** Output kind and major version, e.g. "xirr@1". */
63
+ produces: string;
64
+ regClass: RegClass;
65
+ requires: readonly PredicateId[];
66
+ consumes: Consumes;
67
+ }
68
+ /** One scheme as an analysis sees it: rows projected to its `consumes` kinds. */
69
+ export interface SchemeView {
70
+ folio: Folio;
71
+ scheme: Scheme;
72
+ /** Rows of kinds the analysis consumes, in statement order. */
73
+ rows: Transaction[];
74
+ /** Rows of other kinds: the analysis must list them, never ignore them. */
75
+ outOfScope: Transaction[];
76
+ }
77
+ export interface LedgerView {
78
+ variant: CasDocument["source"]["variant"];
79
+ statementPeriod: CasDocument["statementPeriod"];
80
+ schemes: SchemeView[];
81
+ }
82
+ export interface AnalysisModule<O> {
83
+ manifest: AnalysisManifest;
84
+ eligibility(view: LedgerView): ModuleEligibility;
85
+ compute(view: LedgerView): O;
86
+ }
87
+ /** What `analyze()` reports for each registered module. */
88
+ export interface ModuleReport {
89
+ id: string;
90
+ version: string;
91
+ produces: string;
92
+ regClass: RegClass;
93
+ requires: PredicateId[];
94
+ eventKinds: TxnType[] | "*";
95
+ eligibility: ModuleEligibility;
96
+ }
97
+ /** The kernel's projection: each scheme's rows split by the analysis's `consumes` allowlist. */
98
+ export declare function project(cas: CasDocument, consumes: Consumes): LedgerView;
99
+ export declare function report(module: AnalysisModule<unknown>, view: LedgerView): ModuleReport;
100
+ export declare const checkWhy: (id: string, status: string) => string;
101
+ export type PredicateCode = "summary_statement" | "history_incomplete" | "ledger_units" | "valuation" | "terminal_value" | "running_balance" | "purchase_identity";
102
+ export interface PredicateContext {
103
+ variant: CasDocument["source"]["variant"];
104
+ folio: Folio;
105
+ scheme: Scheme;
106
+ }
107
+ /** Evaluates one predicate for one scheme: null when it holds, else the reason. */
108
+ export declare function evaluatePredicate(id: PredicateId, ctx: PredicateContext): Reason<PredicateCode> | null;
109
+ /** Every failed predicate, in the manifest's order. */
110
+ export declare function evaluateRequires(requires: readonly PredicateId[], ctx: PredicateContext): Reason<PredicateCode>[];
@@ -0,0 +1,79 @@
1
+ import { big } from "../num.js";
2
+ /** The kernel's projection: each scheme's rows split by the analysis's `consumes` allowlist. */
3
+ export function project(cas, consumes) {
4
+ const kinds = consumes.eventKinds === "*" ? null : new Set(consumes.eventKinds);
5
+ return {
6
+ variant: cas.source.variant,
7
+ statementPeriod: cas.statementPeriod,
8
+ schemes: cas.folios.flatMap((folio) => folio.schemes.map((scheme) => ({
9
+ folio, scheme,
10
+ rows: kinds ? scheme.transactions.filter((t) => kinds.has(t.type)) : scheme.transactions,
11
+ outOfScope: kinds ? scheme.transactions.filter((t) => !kinds.has(t.type)) : [],
12
+ }))),
13
+ };
14
+ }
15
+ export function report(module, view) {
16
+ const m = module.manifest;
17
+ return {
18
+ id: m.id, version: m.version, produces: m.produces, regClass: m.regClass, requires: [...m.requires],
19
+ eventKinds: m.consumes.eventKinds === "*" ? "*" : [...m.consumes.eventKinds],
20
+ eligibility: module.eligibility(view),
21
+ };
22
+ }
23
+ /* ---------- predicate registry ---------- */
24
+ const statusOf = (s, id) => s.checks.find((c) => c.id === id)?.status ?? "missing";
25
+ /**
26
+ * Plain-language wording for a check that didn't pass. Kept identical to the
27
+ * M2 eligibility wording (eligibility.ts), which the app already shows.
28
+ */
29
+ const CHECK_WORDS = {
30
+ "ledger.units": "the unit balance doesn't add up",
31
+ "ledger.running_balance": "a printed running balance doesn't match",
32
+ "valuation.units_x_nav": "units × NAV doesn't match the printed value",
33
+ "rows.purchase_identity": "a purchase row's amount doesn't match units × price",
34
+ "history.complete": "the statement doesn't start from the first purchase",
35
+ };
36
+ export const checkWhy = (id, status) => status === "fail" ? CHECK_WORDS[id] ?? `${id} failed` : `${CHECK_WORDS[id]?.replace(/doesn't.*|isn't.*/, "").trim() || id} couldn't be checked`;
37
+ /** Evaluates one predicate for one scheme: null when it holds, else the reason. */
38
+ export function evaluatePredicate(id, ctx) {
39
+ const s = ctx.scheme;
40
+ const ref = { folio: ctx.folio.folio, rtaCode: s.rtaCode };
41
+ const fromCheck = (checkId, code, okStatuses) => {
42
+ const st = statusOf(s, checkId);
43
+ if (okStatuses.includes(st))
44
+ return null;
45
+ // history.complete fails for different causes (mid-history start, gifted
46
+ // or transferred units...); its own detail says which.
47
+ const check = s.checks.find((c) => c.id === checkId);
48
+ const detail = checkId === "history.complete" && st === "fail" ? check?.detail : undefined;
49
+ return { code, text: detail ?? checkWhy(checkId, st), ref: check?.source ? { ...ref, source: check.source } : ref };
50
+ };
51
+ switch (id) {
52
+ case "statement.detailed":
53
+ return ctx.variant === "DETAILED" ? null : { code: "summary_statement", text: "Summary statements have no transactions", ref };
54
+ case "history.complete":
55
+ return fromCheck("history.complete", "history_incomplete", ["pass"]);
56
+ case "ledger.units.pass":
57
+ return fromCheck("ledger.units", "ledger_units", ["pass"]);
58
+ case "valuation.pass":
59
+ return fromCheck("valuation.units_x_nav", "valuation", ["pass"]);
60
+ case "terminal.value.known": {
61
+ // A scheme redeemed to exactly zero units is worth nothing at the end,
62
+ // whether or not a value line is printed, once the ledger adds up. A
63
+ // printed value that contradicts zero units still blocks.
64
+ const zero = s.close !== null && big(s.close).eq(0) && statusOf(s, "ledger.units") === "pass";
65
+ if (zero && statusOf(s, "valuation.units_x_nav") !== "fail")
66
+ return null;
67
+ const r = fromCheck("valuation.units_x_nav", "terminal_value", ["pass"]);
68
+ return r;
69
+ }
70
+ case "ledger.running_balance.ok":
71
+ return fromCheck("ledger.running_balance", "running_balance", ["pass", "not_applicable"]);
72
+ case "rows.purchase_identity.ok":
73
+ return fromCheck("rows.purchase_identity", "purchase_identity", ["pass", "not_applicable"]);
74
+ }
75
+ }
76
+ /** Every failed predicate, in the manifest's order. */
77
+ export function evaluateRequires(requires, ctx) {
78
+ return requires.map((id) => evaluatePredicate(id, ctx)).filter((r) => r !== null);
79
+ }
@@ -0,0 +1,66 @@
1
+ import type { CasDocument, Folio, Scheme, Transaction, TxnType } from "../model.js";
2
+ import { type ModuleReport } from "./contract.js";
3
+ import { type ReturnsAnalysis } from "./returns.js";
4
+ /** "2": adds `modules` (the analysis contract) and `returns` (xirr@1). Everything in "1" is unchanged. */
5
+ export declare const ANALYTICS_VERSION = "2";
6
+ export interface Eligibility {
7
+ eligible: boolean;
8
+ /** Plain-language reasons when not eligible (empty when eligible). */
9
+ reasons: string[];
10
+ }
11
+ export interface OutflowBreakdown {
12
+ order: number;
13
+ date: string;
14
+ type: TxnType;
15
+ /** |units| × price, the value of the units given up. */
16
+ gross: string;
17
+ /** |amount| paid out. */
18
+ net: string;
19
+ /** gross − net: what was deducted (exit load, STT, TDS, rounding). */
20
+ deducted: string;
21
+ /** Same-date STT and TDS rows printed for this scheme. */
22
+ stt: string;
23
+ tds: string;
24
+ /** deducted − stt − tds: usually exit load, or rounding when tiny. */
25
+ unexplained: string;
26
+ source: Transaction["source"];
27
+ }
28
+ export interface SchemeAnalytics {
29
+ folio: string;
30
+ rtaCode: string;
31
+ name: string;
32
+ holdings: Eligibility;
33
+ schemeXirr: Eligibility;
34
+ outflows: OutflowBreakdown[];
35
+ }
36
+ export interface Analytics {
37
+ analyticsVersion: typeof ANALYTICS_VERSION;
38
+ schemes: SchemeAnalytics[];
39
+ portfolio: {
40
+ /** Holdings are shown for the eligible schemes; the rest are listed as excluded. */
41
+ holdings: Eligibility & {
42
+ included: number;
43
+ excluded: number;
44
+ };
45
+ portfolioXirr: Eligibility;
46
+ /** The valuation date most schemes share, or null when none is printed. */
47
+ valuationDate: string | null;
48
+ /** Schemes valued on a different date than `valuationDate`. */
49
+ offDateSchemes: number;
50
+ };
51
+ /** Every registered analysis: manifest summary and three-state eligibility (analytics/contract.ts). */
52
+ modules: ModuleReport[];
53
+ /** XIRR per scheme and for the portfolio, with included / excluded flows (analytics/returns.ts). */
54
+ returns: ReturnsAnalysis;
55
+ }
56
+ export declare function holdingsEligibility(s: Scheme, variant: CasDocument["source"]["variant"]): Eligibility;
57
+ /**
58
+ * Scheme XIRR eligibility in the M2 shape. Since M4 it is xirr@1's own
59
+ * eligibility (analytics/returns.ts), so the two can never disagree: the
60
+ * checks it requires, kinds of rows it can't model (pledged units, unknown
61
+ * wording, gifts out, transfers out, mergers out), and cash rows whose
62
+ * meaning the statement's figures don't settle.
63
+ */
64
+ export declare function schemeXirrEligibility(s: Scheme, variant: CasDocument["source"]["variant"], folio?: Folio): Eligibility;
65
+ export declare function outflowBreakdowns(s: Scheme): OutflowBreakdown[];
66
+ export declare function analyze(cas: CasDocument): Analytics;