@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.
- package/CHANGELOG.md +19 -0
- package/LICENSE +71 -0
- package/NOTICE +41 -0
- package/README.md +198 -2
- package/dist/analytics/contract.d.ts +110 -0
- package/dist/analytics/contract.js +79 -0
- package/dist/analytics/eligibility.d.ts +66 -0
- package/dist/analytics/eligibility.js +93 -0
- package/dist/analytics/gains-schema.d.ts +898 -0
- package/dist/analytics/gains-schema.js +170 -0
- package/dist/analytics/gains.d.ts +319 -0
- package/dist/analytics/gains.js +649 -0
- package/dist/analytics/modules.d.ts +33 -0
- package/dist/analytics/modules.js +74 -0
- package/dist/analytics/returns-schema.d.ts +931 -0
- package/dist/analytics/returns-schema.js +152 -0
- package/dist/analytics/returns.d.ts +126 -0
- package/dist/analytics/returns.js +453 -0
- package/dist/analytics/schedule112a.d.ts +77 -0
- package/dist/analytics/schedule112a.js +134 -0
- package/dist/analytics/xirr.d.ts +75 -0
- package/dist/analytics/xirr.js +314 -0
- package/dist/bin/cas.d.ts +2 -0
- package/dist/bin/cas.js +137 -0
- package/dist/checks.d.ts +49 -0
- package/dist/checks.js +227 -0
- package/dist/compat/casparser.d.ts +121 -0
- package/dist/compat/casparser.js +193 -0
- package/dist/detect.d.ts +10 -0
- package/dist/detect.js +69 -0
- package/dist/errors.d.ts +26 -0
- package/dist/errors.js +95 -0
- package/dist/export/csv.d.ts +21 -0
- package/dist/export/csv.js +49 -0
- package/dist/extract/browser.d.ts +17 -0
- package/dist/extract/browser.js +34 -0
- package/dist/extract/budget.d.ts +46 -0
- package/dist/extract/budget.js +88 -0
- package/dist/extract/node.d.ts +11 -0
- package/dist/extract/node.js +31 -0
- package/dist/extract/pdfjs.d.ts +71 -0
- package/dist/extract/pdfjs.js +244 -0
- package/dist/extract/types.d.ts +106 -0
- package/dist/extract/types.js +11 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +26 -0
- package/dist/layout/lines.d.ts +51 -0
- package/dist/layout/lines.js +115 -0
- package/dist/licence/app-licence.d.ts +53 -0
- package/dist/licence/app-licence.js +139 -0
- package/dist/licence/ed25519.d.ts +2 -0
- package/dist/licence/ed25519.js +103 -0
- package/dist/model.d.ts +148 -0
- package/dist/model.js +1 -0
- package/dist/num.d.ts +19 -0
- package/dist/num.js +27 -0
- package/dist/parse.d.ts +4 -0
- package/dist/parse.js +13 -0
- package/dist/parsers/cams/classify.d.ts +25 -0
- package/dist/parsers/cams/classify.js +103 -0
- package/dist/parsers/cams/detailed.d.ts +15 -0
- package/dist/parsers/cams/detailed.js +343 -0
- package/dist/parsers/cams/header.d.ts +47 -0
- package/dist/parsers/cams/header.js +170 -0
- package/dist/parsers/cams/investor.d.ts +28 -0
- package/dist/parsers/cams/investor.js +139 -0
- package/dist/parsers/cams/summary.d.ts +29 -0
- package/dist/parsers/cams/summary.js +413 -0
- package/dist/parsers/cams/table.d.ts +55 -0
- package/dist/parsers/cams/table.js +144 -0
- package/dist/parsers/cams/total.d.ts +17 -0
- package/dist/parsers/cams/total.js +105 -0
- package/dist/parsers/depository/mf.d.ts +22 -0
- package/dist/parsers/depository/mf.js +438 -0
- package/dist/privacy.d.ts +243 -0
- package/dist/privacy.js +256 -0
- package/dist/schema.d.ts +779 -0
- package/dist/schema.js +214 -0
- package/examples/nextjs/app/page.jsx +34 -0
- package/examples/node/server.mjs +45 -0
- package/examples/python/read_cas.py +67 -0
- package/examples/vite/index.html +14 -0
- package/examples/vite/main.js +22 -0
- package/package.json +54 -4
|
@@ -0,0 +1,649 @@
|
|
|
1
|
+
import { big } from "../num.js";
|
|
2
|
+
import { evaluateRequires, project } from "./contract.js";
|
|
3
|
+
export const GAINS_MANIFEST = {
|
|
4
|
+
id: "analysis.gains",
|
|
5
|
+
version: "1.1.0",
|
|
6
|
+
produces: "gains@1",
|
|
7
|
+
regClass: "computation",
|
|
8
|
+
requires: ["statement.detailed", "history.complete", "ledger.units.pass", "rows.purchase_identity.ok"],
|
|
9
|
+
consumes: {
|
|
10
|
+
families: ["mf-cas"],
|
|
11
|
+
instrumentKinds: ["mutual-fund-scheme"],
|
|
12
|
+
eventKinds: [
|
|
13
|
+
"PURCHASE", "PURCHASE_SIP", "SWITCH_IN", "DIVIDEND_REINVEST", "REDEMPTION", "SWP", "SWITCH_OUT",
|
|
14
|
+
"REVERSAL", "STAMP_DUTY_TAX", "STT_TAX", "TDS_TAX", "DIVIDEND_PAYOUT", "MISC", "PLEDGE", "PLEDGE_RELEASE",
|
|
15
|
+
"SWITCH_IN_MERGER", "SWITCH_OUT_MERGER", "BONUS",
|
|
16
|
+
],
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
/* ---------- dates and rule constants ---------- */
|
|
20
|
+
/** Sales on or after this date: 36 months for funds other than equity-oriented; earlier, 12 months (Finance (No. 2) Act 2014). */
|
|
21
|
+
export const REGIME_2014 = "2014-07-11";
|
|
22
|
+
/** Units bought on or after this date in a specified fund are always short term. */
|
|
23
|
+
export const SPECIFIED_FROM = "2023-04-01";
|
|
24
|
+
/** Sales on or after this date: 24 months for other funds, no indexation (Finance (No. 2) Act 2024). */
|
|
25
|
+
export const REGIME_2024 = "2024-07-23";
|
|
26
|
+
/** Sales on or after this date use the narrower "specified fund" definition (> 65% debt). */
|
|
27
|
+
export const SPECIFIED_REDEFINED = "2025-04-01";
|
|
28
|
+
/** Grandfathering applies to lots bought on or before this date… */
|
|
29
|
+
export const GRANDFATHER_BUY_BY = "2018-01-31";
|
|
30
|
+
/** …and sold on or after this date (earlier long-term equity gains were exempt). */
|
|
31
|
+
export const GRANDFATHER_SELL_FROM = "2018-04-01";
|
|
32
|
+
/** IDCW became taxable in the investor's hands from this date (Finance Act 2020), which ends s.94(7) for it. */
|
|
33
|
+
export const IDCW_TAXABLE_FROM = "2020-04-01";
|
|
34
|
+
/** The Income-tax Act, 2025 applies to transfers from this date (s.196/198 replace s.111A/112A). */
|
|
35
|
+
export const ACT_2025_FROM = "2026-04-01";
|
|
36
|
+
/** The 2001-02 base index applies to transfers from this date (Finance Act 2017); earlier sales used the 1981-82 base. */
|
|
37
|
+
export const CII_2001_FROM = "2017-04-01";
|
|
38
|
+
/** Cost Inflation Index, base 2001-02 = 100, by financial year's first calendar year. */
|
|
39
|
+
export const CII = {
|
|
40
|
+
2001: 100, 2002: 105, 2003: 109, 2004: 113, 2005: 117, 2006: 122, 2007: 129, 2008: 137, 2009: 148, 2010: 167, 2011: 184,
|
|
41
|
+
2012: 200, 2013: 220, 2014: 240, 2015: 254, 2016: 264, 2017: 272, 2018: 280, 2019: 289, 2020: 301, 2021: 317, 2022: 331,
|
|
42
|
+
2023: 348, 2024: 363,
|
|
43
|
+
};
|
|
44
|
+
const ALL_TYPES = ["equity_oriented", "debt", "low_equity", "mid_equity"];
|
|
45
|
+
/** "2024-25" for any date from 1 Apr 2024 to 31 Mar 2025. */
|
|
46
|
+
export function financialYear(iso) {
|
|
47
|
+
const y = Number(iso.slice(0, 4));
|
|
48
|
+
const start = Number(iso.slice(5, 7)) >= 4 ? y : y - 1;
|
|
49
|
+
return `${start}-${String((start + 1) % 100).padStart(2, "0")}`;
|
|
50
|
+
}
|
|
51
|
+
const fyStart = (iso) => Number(financialYear(iso).slice(0, 4));
|
|
52
|
+
/** The same calendar date `months` later; 29 Feb and month ends clamp to the last day. */
|
|
53
|
+
export function addMonths(iso, months) {
|
|
54
|
+
const y = Number(iso.slice(0, 4)), m = Number(iso.slice(5, 7)), d = Number(iso.slice(8, 10));
|
|
55
|
+
const total = y * 12 + (m - 1) + months;
|
|
56
|
+
const ny = Math.floor(total / 12), nm = (total % 12) + 1;
|
|
57
|
+
const last = new Date(Date.UTC(ny, nm, 0)).getUTCDate();
|
|
58
|
+
return `${ny}-${String(nm).padStart(2, "0")}-${String(Math.min(d, last)).padStart(2, "0")}`;
|
|
59
|
+
}
|
|
60
|
+
/* ---------- advance-tax windows (ITR Schedule CG, table F) ---------- */
|
|
61
|
+
export const QUARTERS = ["up_to_15jun", "16jun_15sep", "16sep_15dec", "16dec_15mar", "16mar_31mar"];
|
|
62
|
+
/** The advance-tax window a sale on `iso` falls in: up to 15 Jun, 16 Jun–15 Sep, 16 Sep–15 Dec, 16 Dec–15 Mar, 16 Mar–31 Mar. */
|
|
63
|
+
export function quarterOf(iso) {
|
|
64
|
+
const md = iso.slice(5);
|
|
65
|
+
if (md >= "04-01" && md <= "06-15")
|
|
66
|
+
return "up_to_15jun";
|
|
67
|
+
if (md >= "06-16" && md <= "09-15")
|
|
68
|
+
return "16jun_15sep";
|
|
69
|
+
if (md >= "09-16" && md <= "12-15")
|
|
70
|
+
return "16sep_15dec";
|
|
71
|
+
if (md >= "03-16" && md <= "03-31")
|
|
72
|
+
return "16mar_31mar";
|
|
73
|
+
return "16dec_15mar";
|
|
74
|
+
}
|
|
75
|
+
const daysHeld = (from, to) => Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 86_400_000);
|
|
76
|
+
/** Is this fund "specified" (s.50AA) for a sale on `saleDate`? */
|
|
77
|
+
function isSpecified(type, saleDate) {
|
|
78
|
+
if (type === "debt")
|
|
79
|
+
return true;
|
|
80
|
+
if (type === "low_equity")
|
|
81
|
+
return saleDate < SPECIFIED_REDEFINED;
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
/** The term of one lot and the rule that decided it. */
|
|
85
|
+
export function termOf(type, buyDate, saleDate) {
|
|
86
|
+
if (type === "equity_oriented")
|
|
87
|
+
return { term: saleDate > addMonths(buyDate, 12) ? "long" : "short", rule: "equity_12m" };
|
|
88
|
+
if (buyDate >= SPECIFIED_FROM && isSpecified(type, saleDate))
|
|
89
|
+
return { term: "short", rule: "specified_always_short" };
|
|
90
|
+
if (saleDate < REGIME_2014)
|
|
91
|
+
return { term: saleDate > addMonths(buyDate, 12) ? "long" : "short", rule: "other_12m" };
|
|
92
|
+
if (saleDate < REGIME_2024)
|
|
93
|
+
return { term: saleDate > addMonths(buyDate, 36) ? "long" : "short", rule: "other_36m" };
|
|
94
|
+
return { term: saleDate > addMonths(buyDate, 24) ? "long" : "short", rule: "other_24m" };
|
|
95
|
+
}
|
|
96
|
+
/* ---------- per scheme ---------- */
|
|
97
|
+
const BUY_TYPES = new Set(["PURCHASE", "PURCHASE_SIP", "SWITCH_IN", "DIVIDEND_REINVEST"]);
|
|
98
|
+
const SELL_TYPES = new Set(["REDEMPTION", "SWP", "SWITCH_OUT"]);
|
|
99
|
+
/** Rows that start lots: purchases, bonus units (nil cost) and units arriving by a merger (their old lots). */
|
|
100
|
+
const LOT_TYPES = new Set([...BUY_TYPES, "BONUS", "SWITCH_IN_MERGER"]);
|
|
101
|
+
const UNSUPPORTED_WORDS = {
|
|
102
|
+
UNKNOWN: "a transaction whose wording isn't recognised",
|
|
103
|
+
PLEDGE_INVOKED: "units redeemed by a lender under a pledge",
|
|
104
|
+
SEGREGATION: "a segregated portfolio",
|
|
105
|
+
GIFT_IN: "gifted units (their cost is on the giver's statement)",
|
|
106
|
+
GIFT_OUT: "units given away as a gift",
|
|
107
|
+
TRANSFER_IN: "units transferred in from another folio or holder",
|
|
108
|
+
TRANSFER_OUT: "units transferred out to another folio or holder",
|
|
109
|
+
UNIT_ADJUSTMENT: "a unit adjustment",
|
|
110
|
+
};
|
|
111
|
+
/** Rows whose units come from outside the statement (checks.ts LINEAGE), other than mergers and bonus units. */
|
|
112
|
+
const LINEAGE_ELSEWHERE = new Set(["GIFT_IN", "SEGREGATION", "TRANSFER_IN", "UNIT_ADJUSTMENT", "UNKNOWN"]);
|
|
113
|
+
const PAISA = "0.01";
|
|
114
|
+
const HALF_MILLI_UNIT = big("0.0005");
|
|
115
|
+
const r2 = (b) => b.round(2, 1);
|
|
116
|
+
/** s.47(xviii) (consolidation of schemes is not a transfer) applies from AY 2016-17 (Finance Act 2015). */
|
|
117
|
+
export const MERGER_EXEMPT_FROM = "2015-04-01";
|
|
118
|
+
/** A merger-in row may be dated up to this many days after its merger-out row. */
|
|
119
|
+
const MERGER_GAP_DAYS = 7;
|
|
120
|
+
const NO_OLD_SCHEME = "units came from a scheme merger, and the old scheme's history isn't on this statement";
|
|
121
|
+
/** The part/whole share of `total`, to the paisa; the last part takes what is left so the parts add up exactly. */
|
|
122
|
+
function share(total, part, whole, last, given) {
|
|
123
|
+
return last ? total.minus(given) : r2(total.times(part).div(whole));
|
|
124
|
+
}
|
|
125
|
+
function schemeGains(v, variant, opt, ctx) {
|
|
126
|
+
const { folio, scheme } = v;
|
|
127
|
+
const carries = new Map();
|
|
128
|
+
const ref = (t) => ({ folio: folio.folio, rtaCode: scheme.rtaCode, ...(t ? { order: t.order, source: t.source } : {}) });
|
|
129
|
+
const reasons = evaluateRequires(GAINS_MANIFEST.requires.filter((r) => r !== "history.complete"), { variant, folio, scheme });
|
|
130
|
+
// history.complete also fails on merger and bonus rows, whose lineage gains follows itself (below); any other
|
|
131
|
+
// cause (a mid-history start, gifts, transfers, unrecognised rows) still leaves the scheme out.
|
|
132
|
+
const own = new Set(["SWITCH_IN_MERGER", "BONUS"]);
|
|
133
|
+
const history = evaluateRequires(["history.complete"], { variant, folio, scheme });
|
|
134
|
+
const followed = scheme.open !== null && big(scheme.open).eq(0) && scheme.transactions.some((t) => own.has(t.type)) && !scheme.transactions.some((t) => LINEAGE_ELSEWHERE.has(t.type));
|
|
135
|
+
if (!followed)
|
|
136
|
+
reasons.push(...history);
|
|
137
|
+
const seen = new Set();
|
|
138
|
+
const block = (code, text, t) => {
|
|
139
|
+
if (seen.has(`${code}:${text}`))
|
|
140
|
+
return;
|
|
141
|
+
seen.add(`${code}:${text}`);
|
|
142
|
+
reasons.push({ code, text, ref: ref(t) });
|
|
143
|
+
};
|
|
144
|
+
const base = {
|
|
145
|
+
folio: folio.folio, amc: folio.amc, rtaCode: scheme.rtaCode, scheme: scheme.name, isin: scheme.isin, included: false, reasons,
|
|
146
|
+
fundType: null, fundTypeBasis: "no_sales", fundTypeSource: null, realised: [], saleNotes: [], open: [],
|
|
147
|
+
};
|
|
148
|
+
const finish = () => {
|
|
149
|
+
base.included = reasons.length === 0;
|
|
150
|
+
if (!base.included) {
|
|
151
|
+
base.realised = [];
|
|
152
|
+
base.saleNotes = [];
|
|
153
|
+
base.open = [];
|
|
154
|
+
carries.clear();
|
|
155
|
+
}
|
|
156
|
+
return { gains: base, carries };
|
|
157
|
+
};
|
|
158
|
+
// Rows outside the allowlist, and pledge rows that move units, block.
|
|
159
|
+
for (const t of v.outOfScope)
|
|
160
|
+
block("event_not_supported", `it holds ${UNSUPPORTED_WORDS[t.type] ?? `a ${t.type.toLowerCase().replace(/_/g, " ")} row`}`, t);
|
|
161
|
+
for (const t of v.rows)
|
|
162
|
+
if ((t.type === "PLEDGE" || t.type === "PLEDGE_RELEASE") && t.units && !big(t.units).eq(0))
|
|
163
|
+
block("event_not_supported", "it holds units moved under a pledge", t);
|
|
164
|
+
// Units that arrived by a merger need the old scheme's lots.
|
|
165
|
+
const mergedIn = new Map();
|
|
166
|
+
for (const t of v.rows.filter((x) => x.type === "SWITCH_IN_MERGER")) {
|
|
167
|
+
const src = ctx.sourceOf(t);
|
|
168
|
+
if (!src.ok) {
|
|
169
|
+
block(src.code, src.text, t);
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
const got = ctx.carried(src.from, src.out);
|
|
173
|
+
if ("reason" in got)
|
|
174
|
+
block("merger_source_left_out", `the scheme it merged from is left out: ${got.reason}`, t);
|
|
175
|
+
else
|
|
176
|
+
mergedIn.set(t, { lots: got.lots, from: src.from, out: src.out });
|
|
177
|
+
}
|
|
178
|
+
// Lots can't be matched once the history is known to be incomplete: say why once, not again as a unit shortfall.
|
|
179
|
+
if (reasons.length)
|
|
180
|
+
return finish();
|
|
181
|
+
// Fund type.
|
|
182
|
+
const sells = v.rows.filter((t) => SELL_TYPES.has(t.type));
|
|
183
|
+
const stt = v.rows.find((t) => t.type === "STT_TAX");
|
|
184
|
+
const chosen = opt.fundTypes?.[`${folio.folio}|${scheme.rtaCode}`];
|
|
185
|
+
if (stt)
|
|
186
|
+
Object.assign(base, { fundType: "equity_oriented", fundTypeBasis: "stt_on_redemption", fundTypeSource: stt.source });
|
|
187
|
+
else if (chosen)
|
|
188
|
+
Object.assign(base, { fundType: chosen, fundTypeBasis: "caller" });
|
|
189
|
+
else if (sells.length)
|
|
190
|
+
base.fundTypeBasis = "no_stt_on_redemption";
|
|
191
|
+
// Reversals cancel the nearest earlier row with the same units and amount.
|
|
192
|
+
const cancelled = new Set();
|
|
193
|
+
for (const r of v.rows.filter((t) => t.type === "REVERSAL")) {
|
|
194
|
+
if (!r.units || !r.amount) {
|
|
195
|
+
block("amount_missing", "a reversal row prints no amount or units", r);
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
const u = big(r.units), a = big(r.amount);
|
|
199
|
+
const target = v.rows
|
|
200
|
+
.filter((t) => (BUY_TYPES.has(t.type) || SELL_TYPES.has(t.type)) && !cancelled.has(t) && t.order < r.order && t.date <= r.date && t.units && t.amount)
|
|
201
|
+
.filter((t) => big(t.units).eq(u.neg()) && big(t.amount).abs().eq(a.abs()))
|
|
202
|
+
.sort((x, y) => y.order - x.order)[0];
|
|
203
|
+
if (target) {
|
|
204
|
+
cancelled.add(target);
|
|
205
|
+
cancelled.add(r);
|
|
206
|
+
}
|
|
207
|
+
else
|
|
208
|
+
block("reversal_unmatched", "a reversal row doesn't match an earlier purchase or sale", r);
|
|
209
|
+
}
|
|
210
|
+
// Stamp duty rows fold into the purchase they follow (same date). Bonus and merger rows pay none.
|
|
211
|
+
const stampOf = new Map();
|
|
212
|
+
for (const s of v.rows.filter((t) => t.type === "STAMP_DUTY_TAX")) {
|
|
213
|
+
if (!s.amount) {
|
|
214
|
+
block("amount_missing", "a stamp duty row prints no amount", s);
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
// A negative stamp row on a reversal's date gives back a reversed purchase's stamp duty.
|
|
218
|
+
if (big(s.amount).lt(0) && v.rows.some((r) => r.type === "REVERSAL" && cancelled.has(r) && r.date === s.date))
|
|
219
|
+
continue;
|
|
220
|
+
// Reversed purchases stay candidates, so their stamp duty leaves with them.
|
|
221
|
+
const same = v.rows.filter((t) => BUY_TYPES.has(t.type) && t.date === s.date && !stampOf.has(t));
|
|
222
|
+
const parent = same.filter((t) => t.order < s.order).sort((a, b) => b.order - a.order)[0] ?? same.sort((a, b) => a.order - b.order)[0];
|
|
223
|
+
if (!parent) {
|
|
224
|
+
block("stamp_unattributed", "a stamp duty row has no purchase on the same date", s);
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
stampOf.set(parent, s);
|
|
228
|
+
}
|
|
229
|
+
// STT and TDS by sale, for the unexplained-deduction note.
|
|
230
|
+
const taxOf = new Map();
|
|
231
|
+
for (const t of v.rows.filter((x) => x.type === "STT_TAX" || x.type === "TDS_TAX")) {
|
|
232
|
+
const same = sells.filter((s) => s.date === t.date);
|
|
233
|
+
const parent = same.filter((s) => s.order < t.order).sort((a, b) => b.order - a.order)[0] ?? same[0];
|
|
234
|
+
if (parent && t.amount)
|
|
235
|
+
taxOf.set(parent, (taxOf.get(parent) ?? big(0)).plus(big(t.amount).abs()));
|
|
236
|
+
}
|
|
237
|
+
const sttOf = new Map();
|
|
238
|
+
for (const t of v.rows.filter((x) => x.type === "STT_TAX")) {
|
|
239
|
+
const same = sells.filter((s) => s.date === t.date);
|
|
240
|
+
const parent = same.filter((s) => s.order < t.order).sort((a, b) => b.order - a.order)[0] ?? same[0];
|
|
241
|
+
if (parent && t.amount)
|
|
242
|
+
sttOf.set(parent, (sttOf.get(parent) ?? big(0)).plus(big(t.amount).abs()));
|
|
243
|
+
}
|
|
244
|
+
// FIFO over lots and sales in statement order. A merger-out row moves the open lots out; it is not a sale.
|
|
245
|
+
const events = v.rows
|
|
246
|
+
.filter((t) => (LOT_TYPES.has(t.type) || SELL_TYPES.has(t.type) || t.type === "SWITCH_OUT_MERGER") && !cancelled.has(t))
|
|
247
|
+
.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : a.order - b.order));
|
|
248
|
+
const queue = [];
|
|
249
|
+
const done = new Set();
|
|
250
|
+
const home = { folio: folio.folio, rtaCode: scheme.rtaCode };
|
|
251
|
+
// The old scheme's lots, units scaled to the new scheme; cost and purchase date kept (s.49(2AD), s.2(42A)).
|
|
252
|
+
const mergeIn = (t, units) => {
|
|
253
|
+
const m = mergedIn.get(t);
|
|
254
|
+
const earliest = m.lots.map((l) => l.t.date).sort()[0];
|
|
255
|
+
if (earliest && queue.some((l) => l.units.gt(HALF_MILLI_UNIT) && l.t.date > earliest)) {
|
|
256
|
+
return block("merger_order_unclear", "units from a merger mix with units already held, and the order they leave in isn't settled", t);
|
|
257
|
+
}
|
|
258
|
+
const from = ctx.sourceScheme(m.from);
|
|
259
|
+
if (t.date < MERGER_EXEMPT_FROM)
|
|
260
|
+
return block("merger_not_covered", "a scheme merger before 1 Apr 2015, when a merger still counted as a sale", t);
|
|
261
|
+
// s.47(xviii) covers equity-oriented into equity-oriented, or other into other: refuse a known mix.
|
|
262
|
+
const nowType = stt ? "equity_oriented" : chosen ?? null;
|
|
263
|
+
if (from.fundType && nowType && (from.fundType === "equity_oriented") !== (nowType === "equity_oriented")) {
|
|
264
|
+
return block("merger_not_covered", "a scheme merger between an equity-oriented fund and another kind of fund", t);
|
|
265
|
+
}
|
|
266
|
+
const before = m.lots.reduce((a, l) => a.plus(l.units), big(0));
|
|
267
|
+
// Each lot gets the rounded running total minus what earlier lots got, so no part goes negative and the
|
|
268
|
+
// parts add up to the merger-in row exactly.
|
|
269
|
+
let seenOld = big(0), given = big(0), tooSmall = false;
|
|
270
|
+
const carried = [];
|
|
271
|
+
m.lots.forEach((l, i) => {
|
|
272
|
+
seenOld = seenOld.plus(l.units);
|
|
273
|
+
const upTo = i === m.lots.length - 1 ? units : seenOld.times(units).div(before).round(3, 1);
|
|
274
|
+
const u = upTo.minus(given);
|
|
275
|
+
given = upTo;
|
|
276
|
+
if (u.lte(0))
|
|
277
|
+
tooSmall = true;
|
|
278
|
+
const step = {
|
|
279
|
+
date: t.date, fromFolio: from.folio, fromRtaCode: from.rtaCode, fromScheme: from.scheme, fromIsin: from.isin,
|
|
280
|
+
outOrder: m.out.order, outSource: m.out.source, inOrder: t.order, inSource: t.source, unitsBefore: l.units.toString(),
|
|
281
|
+
};
|
|
282
|
+
carried.push({ ...l, units: u, mergers: [...l.mergers, step] });
|
|
283
|
+
});
|
|
284
|
+
if (tooSmall)
|
|
285
|
+
return block("merger_units_too_small", "the units a merger gave are too few to share out the old lots", t);
|
|
286
|
+
queue.push(...carried);
|
|
287
|
+
};
|
|
288
|
+
const addLot = (t) => {
|
|
289
|
+
done.add(t);
|
|
290
|
+
if (!t.units)
|
|
291
|
+
return block("amount_missing", "a purchase row prints no amount or units", t);
|
|
292
|
+
const units = big(t.units);
|
|
293
|
+
if (units.lte(0))
|
|
294
|
+
return block("sign_mismatch", "a purchase row's amount or units carry the wrong sign", t);
|
|
295
|
+
if (t.type === "BONUS")
|
|
296
|
+
return void queue.push({ t, stamp: null, units, cost: big(0), stampLeft: big(0), home, mergers: [] });
|
|
297
|
+
if (t.type === "SWITCH_IN_MERGER")
|
|
298
|
+
return mergeIn(t, units);
|
|
299
|
+
if (!t.amount)
|
|
300
|
+
return block("amount_missing", "a purchase row prints no amount or units", t);
|
|
301
|
+
const amount = big(t.amount);
|
|
302
|
+
if (amount.lt(0))
|
|
303
|
+
return block("sign_mismatch", "a purchase row's amount or units carry the wrong sign", t);
|
|
304
|
+
const stamp = stampOf.get(t) ?? null;
|
|
305
|
+
const stampAmt = stamp ? big(stamp.amount).abs() : big(0);
|
|
306
|
+
queue.push({ t, stamp, units, cost: amount.plus(stampAmt), stampLeft: stampAmt, home, mergers: [] });
|
|
307
|
+
};
|
|
308
|
+
/** Takes `want` units first in, first out; each part keeps its share of cost and stamp duty. */
|
|
309
|
+
const take = (want, t) => {
|
|
310
|
+
const out = [];
|
|
311
|
+
let left = want, reordered = false;
|
|
312
|
+
while (left.gt(HALF_MILLI_UNIT)) {
|
|
313
|
+
if (!queue[0]) {
|
|
314
|
+
const later = events.find((x) => !done.has(x) && x.date === t.date && LOT_TYPES.has(x.type));
|
|
315
|
+
if (later?.type === "SWITCH_IN_MERGER" && out.length) {
|
|
316
|
+
block("merger_order_unclear", "a sale on the merger date took units already held, then units from the merger, and the order isn't settled", t);
|
|
317
|
+
break;
|
|
318
|
+
}
|
|
319
|
+
if (later) {
|
|
320
|
+
reordered = true;
|
|
321
|
+
addLot(later);
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
const lot = queue[0];
|
|
326
|
+
if (!lot) {
|
|
327
|
+
block("units_short", "a sale takes more units than the purchases before it hold", t);
|
|
328
|
+
break;
|
|
329
|
+
}
|
|
330
|
+
const units = lot.units.lte(left) ? lot.units : left;
|
|
331
|
+
const whole = units.eq(lot.units);
|
|
332
|
+
const cost = whole ? lot.cost : r2(lot.cost.times(units).div(lot.units));
|
|
333
|
+
const stampPart = whole ? lot.stampLeft : r2(lot.stampLeft.times(units).div(lot.units));
|
|
334
|
+
out.push({ ...lot, units, cost, stampLeft: stampPart, reordered });
|
|
335
|
+
if (whole)
|
|
336
|
+
queue.shift();
|
|
337
|
+
else {
|
|
338
|
+
lot.units = lot.units.minus(units);
|
|
339
|
+
lot.cost = lot.cost.minus(cost);
|
|
340
|
+
lot.stampLeft = lot.stampLeft.minus(stampPart);
|
|
341
|
+
}
|
|
342
|
+
left = left.minus(units);
|
|
343
|
+
}
|
|
344
|
+
return out;
|
|
345
|
+
};
|
|
346
|
+
for (const t of events) {
|
|
347
|
+
if (done.has(t))
|
|
348
|
+
continue;
|
|
349
|
+
if (LOT_TYPES.has(t.type)) {
|
|
350
|
+
addLot(t);
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
done.add(t);
|
|
354
|
+
if (!t.units) {
|
|
355
|
+
block("amount_missing", "a sale row prints no amount or units", t);
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
const units = big(t.units);
|
|
359
|
+
if (t.type === "SWITCH_OUT_MERGER") {
|
|
360
|
+
if (units.gte(0)) {
|
|
361
|
+
block("sign_mismatch", "a merger row's units carry the wrong sign", t);
|
|
362
|
+
continue;
|
|
363
|
+
}
|
|
364
|
+
carries.set(t, take(units.abs(), t).map(({ reordered: _, ...l }) => l));
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
if (!t.amount) {
|
|
368
|
+
block("amount_missing", "a sale row prints no amount or units", t);
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
const amount = big(t.amount);
|
|
372
|
+
if (units.gte(0) || amount.gt(0)) {
|
|
373
|
+
block("sign_mismatch", "a sale row's amount or units carry the wrong sign", t);
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
const sold = units.abs();
|
|
377
|
+
const fetched = amount.abs().plus(taxOf.get(t) ?? big(0));
|
|
378
|
+
const atPrice = t.price ? r2(sold.times(big(t.price))) : null;
|
|
379
|
+
// A printed amount that already includes STT and TDS would push `fetched` above units × price: cap it there.
|
|
380
|
+
const saleValue = atPrice && atPrice.lt(fetched) ? atPrice : fetched;
|
|
381
|
+
if (atPrice && atPrice.minus(saleValue).gt(PAISA))
|
|
382
|
+
base.saleNotes.push({ saleOrder: t.order, unexplainedDeduction: atPrice.minus(saleValue).toFixed(2) });
|
|
383
|
+
const sttTotal = sttOf.get(t) ?? big(0);
|
|
384
|
+
let givenValue = big(0), givenStt = big(0);
|
|
385
|
+
const parts = take(sold, t);
|
|
386
|
+
parts.forEach((p, i) => {
|
|
387
|
+
const last = i === parts.length - 1;
|
|
388
|
+
const value = share(saleValue, p.units, sold, last, givenValue);
|
|
389
|
+
const sttPart = share(sttTotal, p.units, sold, last, givenStt);
|
|
390
|
+
givenValue = givenValue.plus(value);
|
|
391
|
+
givenStt = givenStt.plus(sttPart);
|
|
392
|
+
base.realised.push({ ...realise(p, t, value, sttPart, base.fundType, scheme.isin, opt), sameDayReordered: p.reordered });
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
// Flags for a chartered accountant; the lot is still worked out. Bought within ~3 months before the record
|
|
396
|
+
// date and sold at a loss within ~9 months after it. The statement prints the allotment or payment date, not
|
|
397
|
+
// the record date, so the window opens a month earlier.
|
|
398
|
+
const bonuses = v.rows.filter((t) => t.type === "BONUS");
|
|
399
|
+
// s.94(7) needs the IDCW to be exempt, which it was until 31 Mar 2020.
|
|
400
|
+
const idcw = v.rows.filter((t) => (t.type === "DIVIDEND_PAYOUT" || t.type === "DIVIDEND_REINVEST") && !cancelled.has(t) && t.date < IDCW_TAXABLE_FROM);
|
|
401
|
+
const inWindow = (l, at) => l.buyDate >= addMonths(at.date, -4) && l.buyDate <= at.date && l.saleDate >= at.date && l.saleDate <= addMonths(at.date, 9);
|
|
402
|
+
const stripBonus = new Set();
|
|
403
|
+
for (const l of base.realised) {
|
|
404
|
+
if (big(l.gain).gte(0) || l.buyType === "BONUS")
|
|
405
|
+
continue;
|
|
406
|
+
const b = bonuses.filter((x) => inWindow(l, x));
|
|
407
|
+
if (b.length) {
|
|
408
|
+
l.flags.push("s94_8_bonus_stripping");
|
|
409
|
+
for (const x of b)
|
|
410
|
+
stripBonus.add(x.order);
|
|
411
|
+
}
|
|
412
|
+
if (idcw.some((d) => d.order !== l.buyOrder && inWindow(l, d)))
|
|
413
|
+
l.flags.push("s94_7_dividend_stripping");
|
|
414
|
+
}
|
|
415
|
+
// s.94(8) moves an ignored loss into the cost of the bonus units kept: their sales share the flag.
|
|
416
|
+
for (const l of base.realised)
|
|
417
|
+
if (l.buyType === "BONUS" && stripBonus.has(l.buyOrder))
|
|
418
|
+
l.flags.push("s94_8_bonus_stripping");
|
|
419
|
+
// What's left: open lots, valued at the statement's NAV.
|
|
420
|
+
const valuationDate = scheme.valuation?.date ?? scheme.nav?.date ?? null;
|
|
421
|
+
for (const lot of queue) {
|
|
422
|
+
if (lot.units.lte(HALF_MILLI_UNIT))
|
|
423
|
+
continue;
|
|
424
|
+
const term = valuationDate ? openTerm(base.fundType, lot.t.date, valuationDate) : null;
|
|
425
|
+
base.open.push({
|
|
426
|
+
buyOrder: lot.t.order, buyDate: lot.t.date, buyType: lot.t.type, buySource: lot.t.source, buyFolio: lot.home.folio, buyRtaCode: lot.home.rtaCode,
|
|
427
|
+
mergers: lot.mergers, units: lot.units.toString(), cost: lot.cost.toFixed(2),
|
|
428
|
+
value: scheme.nav ? r2(lot.units.times(big(scheme.nav.value))).toFixed(2) : null, termOnValuationDate: term,
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
return finish();
|
|
432
|
+
}
|
|
433
|
+
function openTerm(type, buy, on) {
|
|
434
|
+
if (type)
|
|
435
|
+
return termOf(type, buy, on).term;
|
|
436
|
+
const terms = new Set(ALL_TYPES.map((f) => termOf(f, buy, on).term));
|
|
437
|
+
return terms.size === 1 ? [...terms][0] : null;
|
|
438
|
+
}
|
|
439
|
+
function realise(part, sale, saleValue, stt, type, isin, opt) {
|
|
440
|
+
const { units, cost, stampLeft: stamp } = part;
|
|
441
|
+
const buyDate = part.t.date, saleDate = sale.date;
|
|
442
|
+
const flags = [];
|
|
443
|
+
let term = null, rule = null, termIf = null;
|
|
444
|
+
if (type)
|
|
445
|
+
({ term, rule } = termOf(type, buyDate, saleDate));
|
|
446
|
+
else {
|
|
447
|
+
const each = Object.fromEntries(ALL_TYPES.map((f) => [f, termOf(f, buyDate, saleDate)]));
|
|
448
|
+
// The term may be the same for every type; equity and other gains are still reported apart.
|
|
449
|
+
if (new Set(Object.values(each).map((x) => x.term)).size === 1)
|
|
450
|
+
term = each.debt.term;
|
|
451
|
+
termIf = each;
|
|
452
|
+
}
|
|
453
|
+
const lastMerger = part.mergers.at(-1)?.date ?? null;
|
|
454
|
+
if (lastMerger && type !== "equity_oriented" && buyDate < SPECIFIED_FROM && lastMerger >= SPECIFIED_FROM)
|
|
455
|
+
flags.push("s50aa_merged_after_1apr2023");
|
|
456
|
+
const gain = saleValue.minus(cost);
|
|
457
|
+
let grandfathering = null, missing = false;
|
|
458
|
+
if (type === "equity_oriented" && term === "long" && buyDate <= GRANDFATHER_BUY_BY && saleDate >= GRANDFATHER_SELL_FROM) {
|
|
459
|
+
// Units merged after 31 Jan 2018 were other units on that date: which NAV applies is a question for a CA.
|
|
460
|
+
if (part.mergers.some((m) => m.date > GRANDFATHER_BUY_BY))
|
|
461
|
+
flags.push("grandfathering_merged_after_31jan2018");
|
|
462
|
+
else {
|
|
463
|
+
const nav = isin && opt.fmv2018 ? opt.fmv2018.lookup(isin) : null;
|
|
464
|
+
if (nav) {
|
|
465
|
+
const fmv = r2(units.times(big(nav)));
|
|
466
|
+
const lower = fmv.lt(saleValue) ? fmv : saleValue;
|
|
467
|
+
const used = cost.gt(lower) ? cost : lower;
|
|
468
|
+
grandfathering = { navOn31Jan2018: nav, valueOn31Jan2018: fmv.toFixed(2), costUsed: used.toFixed(2) };
|
|
469
|
+
}
|
|
470
|
+
else
|
|
471
|
+
missing = true;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
let indexedCost = null;
|
|
475
|
+
if (type && type !== "equity_oriented" && term === "long" && saleDate < REGIME_2024) {
|
|
476
|
+
if (saleDate < CII_2001_FROM)
|
|
477
|
+
flags.push("indexation_before_apr2017");
|
|
478
|
+
else {
|
|
479
|
+
const from = CII[Math.max(2001, fyStart(buyDate))], to = CII[fyStart(saleDate)];
|
|
480
|
+
if (from && to)
|
|
481
|
+
indexedCost = r2(cost.times(to).div(from)).toFixed(2);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
return {
|
|
485
|
+
saleOrder: sale.order, saleDate, saleType: sale.type, saleSource: sale.source, salePrice: sale.price ? big(sale.price).toString() : null,
|
|
486
|
+
buyOrder: part.t.order, buyDate, buyType: part.t.type, buySource: part.t.source, buyFolio: part.home.folio, buyRtaCode: part.home.rtaCode,
|
|
487
|
+
mergers: part.mergers, flags, window: quarterOf(saleDate), stampOrder: part.stamp?.order ?? null,
|
|
488
|
+
units: units.toString(), cost: cost.toFixed(2), stampDuty: stamp.toFixed(2), saleValue: saleValue.toFixed(2), stt: stt.toFixed(2),
|
|
489
|
+
gain: gain.toFixed(2), daysHeld: daysHeld(buyDate, saleDate), financialYear: financialYear(saleDate),
|
|
490
|
+
onOrAfter23Jul2024: saleDate >= REGIME_2024, act: saleDate >= ACT_2025_FROM ? "2025" : "1961",
|
|
491
|
+
term, rule, termIf, grandfathering, grandfatheringMissing: missing, boughtBefore1Apr2001: buyDate < "2001-04-01", sameDayReordered: false,
|
|
492
|
+
gainAfterGrandfathering: grandfathering ? saleValue.minus(big(grandfathering.costUsed)).toFixed(2) : gain.toFixed(2),
|
|
493
|
+
indexedCost,
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
/* ---------- mergers across schemes ---------- */
|
|
497
|
+
/**
|
|
498
|
+
* Pairs each merger-in row with the merger-out row it came from: same fund
|
|
499
|
+
* house, dated 0–7 days earlier, the same rupee value within ₹1 or 0.1% when
|
|
500
|
+
* both rows print one, and no other candidate (the same folio breaks a tie).
|
|
501
|
+
* A pairing that isn't one-to-one is refused rather than guessed.
|
|
502
|
+
*/
|
|
503
|
+
function pairMergers(view) {
|
|
504
|
+
const legs = (type) => view.schemes.flatMap((s, i) => s.rows.filter((t) => t.type === type).map((t) => ({ i, t, s })));
|
|
505
|
+
const outs = legs("SWITCH_OUT_MERGER"), ins = legs("SWITCH_IN_MERGER");
|
|
506
|
+
const amc = (s) => s.folio.amc.trim().toLowerCase();
|
|
507
|
+
const close = (a, b) => {
|
|
508
|
+
if (!a.amount || !b.amount)
|
|
509
|
+
return true;
|
|
510
|
+
const gap = big(a.amount).abs().minus(big(b.amount).abs()).abs();
|
|
511
|
+
return gap.lte(1) || gap.lte(big(b.amount).abs().times("0.001"));
|
|
512
|
+
};
|
|
513
|
+
const candidates = (inn) => {
|
|
514
|
+
const all = outs.filter((o) => o.i !== inn.i && amc(o.s) === amc(inn.s) && o.t.date <= inn.t.date && daysHeld(o.t.date, inn.t.date) <= MERGER_GAP_DAYS && close(o.t, inn.t));
|
|
515
|
+
const sameFolio = all.filter((o) => o.s.folio.folio === inn.s.folio.folio);
|
|
516
|
+
return all.length > 1 && sameFolio.length >= 1 ? sameFolio : all;
|
|
517
|
+
};
|
|
518
|
+
const picked = new Map(ins.map((inn) => [inn, candidates(inn)]));
|
|
519
|
+
const uses = new Map();
|
|
520
|
+
for (const c of picked.values())
|
|
521
|
+
if (c.length === 1)
|
|
522
|
+
uses.set(c[0].t, (uses.get(c[0].t) ?? 0) + 1);
|
|
523
|
+
const result = new Map();
|
|
524
|
+
for (const [inn, c] of picked) {
|
|
525
|
+
if (c.length === 1 && uses.get(c[0].t) === 1)
|
|
526
|
+
result.set(inn.t, { ok: true, from: c[0].i, out: c[0].t });
|
|
527
|
+
else if (c.length === 0)
|
|
528
|
+
result.set(inn.t, { ok: false, code: "merger_unmatched", text: NO_OLD_SCHEME });
|
|
529
|
+
else
|
|
530
|
+
result.set(inn.t, { ok: false, code: "merger_unmatched", text: "units came from a scheme merger, and the old scheme can't be told apart from another merged the same week" });
|
|
531
|
+
}
|
|
532
|
+
return result;
|
|
533
|
+
}
|
|
534
|
+
/* ---------- totals ---------- */
|
|
535
|
+
function bucketOf(s, l) {
|
|
536
|
+
if (!l.term || !s.fundType)
|
|
537
|
+
return "depends";
|
|
538
|
+
const equity = s.fundType === "equity_oriented";
|
|
539
|
+
return `${equity ? "equity" : "other"}_${l.term}`;
|
|
540
|
+
}
|
|
541
|
+
const periodOf = (l) => (l.financialYear === "2024-25" ? (l.onOrAfter23Jul2024 ? "from_23jul2024" : "before_23jul2024") : "whole");
|
|
542
|
+
const BUCKET_ORDER = ["equity_short", "equity_long", "other_short", "other_long", "depends"];
|
|
543
|
+
const byYearPeriodBucket = (a, b) => b.financialYear.localeCompare(a.financialYear) || a.period.localeCompare(b.period) || BUCKET_ORDER.indexOf(a.bucket) - BUCKET_ORDER.indexOf(b.bucket);
|
|
544
|
+
function yearTotals(schemes) {
|
|
545
|
+
const map = new Map();
|
|
546
|
+
for (const s of schemes) {
|
|
547
|
+
for (const l of s.realised) {
|
|
548
|
+
const period = periodOf(l);
|
|
549
|
+
const bucket = bucketOf(s, l);
|
|
550
|
+
const key = `${l.financialYear}|${period}|${bucket}`;
|
|
551
|
+
const row = map.get(key) ?? { financialYear: l.financialYear, period, bucket, lots: 0, lotsMissing2018Nav: 0, lotsFlagged: 0, saleValue: "", cost: "", gain: "", gainAfterGrandfathering: "", gainAfterIndexation: null, _v: big(0), _c: big(0), _g: big(0), _a: big(0), _i: big(0), _n: 0 };
|
|
552
|
+
row.lots++;
|
|
553
|
+
if (l.grandfatheringMissing)
|
|
554
|
+
row.lotsMissing2018Nav++;
|
|
555
|
+
if (l.flags.length)
|
|
556
|
+
row.lotsFlagged++;
|
|
557
|
+
row._v = row._v.plus(big(l.saleValue));
|
|
558
|
+
row._c = row._c.plus(big(l.cost));
|
|
559
|
+
row._g = row._g.plus(big(l.gain));
|
|
560
|
+
row._a = row._a.plus(big(l.gainAfterGrandfathering));
|
|
561
|
+
row._i = row._i.plus(windowAmount(bucket, l));
|
|
562
|
+
if (l.indexedCost)
|
|
563
|
+
row._n++;
|
|
564
|
+
map.set(key, row);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
return [...map.values()]
|
|
568
|
+
.sort(byYearPeriodBucket)
|
|
569
|
+
.map(({ _v, _c, _g, _a, _i, _n, ...r }) => ({
|
|
570
|
+
...r, saleValue: _v.toFixed(2), cost: _c.toFixed(2), gain: _g.toFixed(2), gainAfterGrandfathering: _a.toFixed(2),
|
|
571
|
+
gainAfterIndexation: r.bucket === "other_long" && _n > 0 ? _i.toFixed(2) : null,
|
|
572
|
+
}));
|
|
573
|
+
}
|
|
574
|
+
/** What a lot adds to its advance-tax window: equity long term after grandfathering, other long term after indexation where it applied, else the gain. */
|
|
575
|
+
export function windowAmount(bucket, l) {
|
|
576
|
+
if (bucket === "equity_long")
|
|
577
|
+
return big(l.gainAfterGrandfathering);
|
|
578
|
+
return l.indexedCost ? big(l.saleValue).minus(l.indexedCost) : big(l.gain);
|
|
579
|
+
}
|
|
580
|
+
function quarterTotals(schemes) {
|
|
581
|
+
const map = new Map();
|
|
582
|
+
for (const s of schemes) {
|
|
583
|
+
for (const l of s.realised) {
|
|
584
|
+
const period = periodOf(l), bucket = bucketOf(s, l);
|
|
585
|
+
const key = `${l.financialYear}|${period}|${bucket}`;
|
|
586
|
+
const row = map.get(key) ?? { financialYear: l.financialYear, period, bucket, lots: 0, lotsWithNote: 0, w: QUARTERS.map(() => big(0)) };
|
|
587
|
+
if (l.flags.length || l.grandfatheringMissing)
|
|
588
|
+
row.lotsWithNote++;
|
|
589
|
+
const q = QUARTERS.indexOf(l.window);
|
|
590
|
+
row.w[q] = row.w[q].plus(windowAmount(bucket, l));
|
|
591
|
+
row.lots++;
|
|
592
|
+
map.set(key, row);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return [...map.values()].sort(byYearPeriodBucket).map(({ w, ...r }) => ({ ...r, windows: w.map((x) => x.toFixed(2)), total: w.reduce((a, x) => a.plus(x), big(0)).toFixed(2) }));
|
|
596
|
+
}
|
|
597
|
+
/** The `fmv2018` option from the data pack. */
|
|
598
|
+
export function fmv2018FromPack(pack) {
|
|
599
|
+
if (pack.id !== "nav-2018-01-31" || Object.keys(pack.navs).length !== pack.count)
|
|
600
|
+
throw new Error("not a 31 Jan 2018 NAV pack");
|
|
601
|
+
return { version: pack.version, lookup: (isin) => pack.navs[isin] ?? null };
|
|
602
|
+
}
|
|
603
|
+
/** Capital gains for every scheme in the statement. */
|
|
604
|
+
export function gains(cas, opt = {}) {
|
|
605
|
+
const view = project(cas, GAINS_MANIFEST.consumes);
|
|
606
|
+
return computeGains(view, opt);
|
|
607
|
+
}
|
|
608
|
+
function computeGains(view, opt) {
|
|
609
|
+
const sources = pairMergers(view);
|
|
610
|
+
const runs = [];
|
|
611
|
+
// An old scheme runs before the scheme it merged into; a loop (A into B into A) is refused, not followed.
|
|
612
|
+
const run = (i) => {
|
|
613
|
+
const r = runs[i];
|
|
614
|
+
if (r === "running")
|
|
615
|
+
return null;
|
|
616
|
+
if (r)
|
|
617
|
+
return r;
|
|
618
|
+
runs[i] = "running";
|
|
619
|
+
return (runs[i] = schemeGains(view.schemes[i], view.variant, opt, ctx));
|
|
620
|
+
};
|
|
621
|
+
const ctx = {
|
|
622
|
+
sourceOf: (t) => sources.get(t) ?? { ok: false, code: "merger_unmatched", text: NO_OLD_SCHEME },
|
|
623
|
+
carried: (from, out) => {
|
|
624
|
+
const r = run(from);
|
|
625
|
+
if (!r)
|
|
626
|
+
return { reason: "the schemes merge into each other in a loop" };
|
|
627
|
+
if (!r.gains.included)
|
|
628
|
+
return { reason: r.gains.reasons[0]?.text ?? "its history can't be read" };
|
|
629
|
+
const lots = r.carries.get(out);
|
|
630
|
+
return lots ? { lots } : { reason: "its merger row can't be read" };
|
|
631
|
+
},
|
|
632
|
+
sourceScheme: (i) => runs[i].gains,
|
|
633
|
+
};
|
|
634
|
+
const schemes = view.schemes.map((_, i) => run(i).gains);
|
|
635
|
+
const included = schemes.filter((s) => s.included);
|
|
636
|
+
return { schemes, years: yearTotals(included), quarters: quarterTotals(included), fmvPack: opt.fmv2018?.version ?? null };
|
|
637
|
+
}
|
|
638
|
+
export const gainsModule = {
|
|
639
|
+
manifest: GAINS_MANIFEST,
|
|
640
|
+
eligibility(view) {
|
|
641
|
+
const out = computeGains(view, {});
|
|
642
|
+
const reasons = out.schemes.flatMap((s) => s.reasons);
|
|
643
|
+
const included = out.schemes.filter((s) => s.included).length;
|
|
644
|
+
if (included === 0)
|
|
645
|
+
return { state: "not_available", reasons: reasons.length ? reasons : [{ code: "no_schemes", text: "The statement holds no schemes" }] };
|
|
646
|
+
return included < out.schemes.length ? { state: "partial", reasons } : { state: "eligible", reasons: [] };
|
|
647
|
+
},
|
|
648
|
+
compute: (view) => computeGains(view, {}),
|
|
649
|
+
};
|