import { CurrencyCode } from "@classytic/primitives/currency"; //#region src/resolver.d.ts interface TaxClassRate { /** Country-defined rate code — 'STANDARD' in BD, 'GST' in CA, 'GST_18' in IN. */ rateCode: string; /** Percentage rate (0 for zero-rated and exempt classes). */ rate: number; /** Whether this class allows input credit / ITC on purchases. */ inputCreditAllowed: boolean; /** * Grid line on the country's periodic return form, when one applies. * Historically named for Bangladesh's Mushak 9.1 (the first * implementation); read it as "the country's return-grid line" — * GST34 box in CA, VAT100 box in UK. */ mushakGridOutput?: number | undefined; /** Additional audit metadata — country-specific (service codes, SRO refs…). */ meta?: Record | undefined; } /** * Result of resolving a fiscal position: exports, SRO-exempt buyers, * bonded warehouses, inter-province rules — anything that remaps a * product's default tax class for a specific transaction pair. Carries * its own audit trail because auditors ask "WHY was this invoice * zero-rated" years later. */ interface FiscalPositionResult { /** Country-defined position code ('INTERNATIONAL', 'EXEMPT', 'DEFAULT', …). */ position: string; /** SRO / certificate / export-manifest reference — empty only for defaults. */ reference?: string | undefined; /** Human-readable explanation for the audit log. */ reason: string; /** Remap a product's tax class to the effective class for this transaction. */ mapTaxClass: (productClass: string) => string; } /** Which side of the tax posting an account is being resolved for. */ type PostingDirection = 'input' | 'output'; /** * The taxpayer's registration regime, as the country defines it — * 'standard' | 'tot' | 'importer' in BD; 'registrant' | 'small-supplier' * in CA. A string on purpose: regimes are jurisdiction vocabulary, and * consumers narrow with their pack's exported union. */ type AccountingRegime = string; /** * A single tax applied to a line — one entry per distinct tax (VAT + SD for * BD, state + local for US, GST + PST for CA). The `rateCode` + `direction` * feed straight back into {@link TaxResolver.accountFor} so the host posts each * component to the right GL account. */ interface TaxLineComponent { /** Rate code this component posts under — pass to `accountFor(rateCode, …)`. */ readonly rateCode: string; /** Human label for UI / JE line ('VAT', 'Supplementary Duty', 'State Sales Tax'). */ readonly name?: string; /** Effective rate as a fraction (0.15 = 15%). */ readonly rate: number; /** Tax amount in integer minor units (paisa / cents). */ readonly amount: number; /** * The assessable amount this component was computed ON, integer minor units. * * The ORIGIN of a fact the rest of the stack cannot reconstruct. A statutory return reports each * taxable supply in two places — the value on one line and the tax on another — and only the pack * that ran the cascade knows which value fed which tax. Downstream that base is persisted to the * journal item and rolled up per return field, which is what lets a return be derived from the * LEDGER instead of re-derived from whichever document still exists. * * ## Why nobody downstream can compute it * * - `amount / rate` divides by zero for a zero-rated or exempt component, and those lines have a * real assessable value that must still reach the return's value fields. It is also a rounded * integer divided by a rate, so the quotient is the base ± the rounding error; * - `= input.subtotal` is right only when ONE component applies to a fully taxable line. In a * CASCADE the bases differ by construction — BD levies SD on the value and VAT on value + SD, * so at most one component's base equals the subtotal, and no consumer can tell which. * * OPTIONAL because a pack may not model an assessable base separately (a fixed per-unit duty, a * pack that predates this field). Absence means UNKNOWN and MUST propagate as such: consumers * report the row as unsplit rather than substituting `0`, which would put a zero value on a real * taxable supply while the tax still ties. */ readonly base?: number; /** Posting direction for this component (echoes the input's direction). */ readonly direction: PostingDirection; /** * What the component IS, for every reader that must tell the headline tax from a levy beside it: * `primary` is the jurisdiction's main consumption tax (VAT, GST, sales tax), printed as "the" rate; * `duty` is a levy charged beside it (a supplementary duty, an excise). Set by the pack — a reader * never infers it from `name`, which is display text. */ readonly role: TaxComponentRole; } type TaxComponentRole = 'primary' | 'duty'; /** The full per-line tax breakdown returned by {@link TaxResolver.computeLine}. */ interface TaxLineComputation { /** Total tax on the line = Σ `taxes[].amount`, integer minor units. */ readonly taxAmount: number; /** Every tax that applies to the line. Empty for exempt/zero-rated lines. */ readonly taxes: readonly TaxLineComponent[]; } /** * The OUTCOME of rating a line — three cases, because two of them are not the same answer. * * ## Why this replaced `TaxLineComputation | null` * * `computeLine` used to return `null` for an unrecognised tax class, and its own docblock told callers * to "treat as untaxed". Both real callers did exactly that: `spine-invoice`'s adapter ran * `if (!computed) return untaxed(taxClass)` and `spine-contract`'s upgrade flow left `taxAmount` * undefined. So a typo — `STANDRAD` for `STANDARD` — produced a **legally plausible zero-tax invoice** * with nothing anywhere reporting a problem. That is this codebase's signature failure: a specific * instruction (rate this line) silently defeated by a general default (no tax). * * **`exempt` and `zero-rated` are legal classifications, never fallbacks.** A pack that means "no tax * applies" says so with `not-taxable` and a reason; a pack that does not recognise the class says * `unknown`. A caller on a money path must REFUSE `unknown` — see {@link taxLineOrThrow}. * * A discriminated union rather than a nullable value because the compiler then forces every caller to * decide, which is where a rule this important belongs (FAIL LOUD rule 4). */ type TaxLineResolution = /** The class was recognised and rated. `value.taxes` may still be empty for a genuine zero. */ { readonly kind: 'resolved'; readonly value: TaxLineComputation; } | /** * The class was recognised AND carries no tax by law (exempt, zero-rated, out of scope). * * `reason` is required: an operator reading a zero-tax line needs the legal basis, and a pack that * cannot state one is really returning `unknown`. */ { readonly kind: 'not-taxable'; readonly taxClass: string; readonly reason: string; } | /** The pack does not recognise this class. NOT a zero — the caller must refuse it. */ { readonly kind: 'unknown'; readonly taxClass: string; }; /** Thrown when a money path is handed a tax class its pack does not recognise. */ declare class UnknownTaxClassError extends Error { readonly taxClass: string; readonly code = "UNKNOWN_TAX_CLASS"; constructor(taxClass: string); } /** * The call shape for a money path: rated computation, or `null` for a lawful zero — and a THROW for an * unrecognised class. * * Collapsing `not-taxable` to `null` is safe in a way collapsing `unknown` is not: `null` here means "a * pack examined this class and said no tax applies", which is a decision. `unknown` means nobody * decided, and the only correct response on an invoice, a POS sale or a subscription charge is to stop. */ declare function taxLineOrThrow(resolution: TaxLineResolution): TaxLineComputation | null; /** Country-neutral input to {@link TaxResolver.computeLine}. */ interface TaxLineInput { /** * The line's consideration after every discount, integer minor units, on the basis `extra.priceMode` * names: tax-INCLUSIVE (`'inclusive'`, the tax is backed out of it) or tax-EXCLUSIVE (the tax is added). */ readonly subtotal: number; readonly quantity: number; /** Country-neutral tax class ('STANDARD' | 'REDUCED' | 'ZERO' | 'EXEMPT' | …). */ readonly taxClass: string; /** 'output' for sales/customer documents, 'input' for purchases/vendor bills. */ readonly direction: PostingDirection; /** * Pack-specific extras that don't belong in the neutral core — e.g. BD's * `sdRate`, US's `localRate` / jurisdiction, price-inclusive flag. Packs read * what they know and ignore the rest. */ readonly extra?: Record; readonly asOf?: Date; /** * A supply to a related person (an associate, a connected person): its open market value, in the same * terms as `subtotal`, and whether the recipient may deduct all the input tax on it. The pack decides * whether its law values the supply at market value (BD VAT Act s.32(3), EU VAT Directive art. 80). */ readonly relatedParty?: RelatedPartySupply; } interface RelatedPartySupply { /** Open market value, integer minor units. */ readonly marketValue: number; /** The recipient is entitled to deduct all the input tax on this supply. */ readonly recipientFullDeduction: boolean; } /** One withholding retained from a supplier payment. Amount is POSITIVE (the withheld slice). */ interface WithholdingComponent { /** Withholding code — 'TDS', 'VDS', 'BACKUP_1099', … — pass to any code-keyed routing. */ readonly code: string; /** Human label for UI / JE line ('Tax Deducted at Source', 'VAT Deducted at Source'). */ readonly name?: string; /** Effective rate as a fraction (0.05 = 5%). */ readonly rate: number; /** Withheld amount in integer minor units — always positive. */ readonly amount: number; /** * GL account the withholding LIABILITY posts to (we now owe the authority). * Pack-resolved because withholding heads (BD 2135 TDS / 2136 VDS) are not * keyed like `accountFor(rateCode, direction)`. `undefined` → the host falls * back to its default withholding-payable account. */ readonly account?: string; /** * When the jurisdiction takes it: when the bill is booked (`'invoice'`, the default) or when the * supplier is paid (`'payment'` — BD VDS). A payment-point component is deducted from each payment, * apportioned by what that payment settles. */ readonly point?: WithholdingPoint; /** * The deduction is certified against the COUNTERPARTY's own document (BD VDS: the supplier's * Mushak 6.3), so the bill must carry that document's number before it posts. */ readonly requiresCounterpartyDocument?: boolean; } type WithholdingPoint = 'invoice' | 'payment'; /** Country-neutral input to {@link TaxResolver.computeWithholding}. */ interface WithholdingInput { /** Base subject to income-style withholding (net of tax), integer minor units. */ readonly baseAmount: number; /** VAT portion of the bill, for VAT-withholding (BD VDS). Omit when none. */ readonly vatAmount?: number; /** Payee classification the pack keys rates off (BD payee category, US 1099 vendor type). */ readonly payeeCategory?: string; /** Nature of the payment (BD payment type: goods/services/rent/…; US 1099 box). */ readonly paymentType?: string; /** Pack-specific extras (e.g. BD `vdsApplicable`, a VDS deduction-rate override). */ readonly extra?: Record; readonly asOf?: Date; } /** * How a host books one import charge, WITHOUT knowing the pack's code: * - `landed_cost` — capitalizes into inventory cost (duties: CD/RD/SD…). * - `recoverable_tax` — claimable input credit (import VAT/GST); the host * decides per regime whether to claim it or fold to cost. * - `prepaid_tax` — a tax advance booked as an asset/receivable, adjustable * in a later return (BD Advance Tax + Advance Income Tax). */ type ImportChargeRole = 'landed_cost' | 'recoverable_tax' | 'prepaid_tax'; /** One charge in an import customs stack. `amount` is POSITIVE integer minor units. */ interface ImportChargeComponent { /** Pack vocabulary — 'CD', 'RD', 'SD', 'VAT', 'AT', 'AIT', … for code-keyed routing. */ readonly code: string; /** Human label for UI / JE line ('Customs Duty', 'Advance Income Tax'). */ readonly name?: string; /** Effective rate as a fraction (0.15 = 15%), when the charge is rate-based. */ readonly rate?: number; /** Charge amount in integer minor units — always positive. */ readonly amount: number; /** How the host should book it (see {@link ImportChargeRole}). */ readonly role: ImportChargeRole; /** * GL account hint the pack suggests. `undefined` → the host maps by `role` * against its own chart (import heads aren't keyed like `accountFor`). */ readonly account?: string; } /** Country-neutral input to {@link TaxResolver.computeImportStack}. */ interface ImportStackInput { /** Customs assessable value (CIF + statutory uplifts, post-FX), integer minor units. */ readonly assessableValue: number; /** * Pack-specific rate parameters — BD reads `cdRate` / `rdRate` / `sdRate` / * `atRate` / `vatRate` / `aitRate`; other packs their own. Packs read what * they know and ignore the rest. */ readonly extra?: Record; readonly asOf?: Date; } /** The customs-stack breakdown returned by {@link TaxResolver.computeImportStack}. */ interface ImportStackComputation { /** The assessable value the stack was computed on, echoed (integer minor units). */ readonly assessableValue: number; /** * Inventory cost basis = assessableValue + Σ(`landed_cost` charges), integer * minor units — what the host debits to inventory (before any non-recoverable * tax fold-in it decides on per regime). */ readonly landedCost: number; /** Σ(`recoverable_tax`) — the claimable import tax (import VAT), integer minor units. */ readonly recoverableTax: number; /** * The base the recoverable tax was computed ON, integer minor units — for a customs cascade this is * NOT the assessable value (BD: AV + CD + RD + SD). Carried so a ledger-derived return can attribute * the import input credit; see `TaxLineComponent.base` for why no consumer may re-derive it. * Optional: a pack that predates it sends nothing, and absence means UNKNOWN, never zero. */ readonly vatBase?: number; /** Σ(`prepaid_tax`) — tax advances booked as an asset, integer minor units. */ readonly prepaidTax: number; /** Total payable at the customs point = Σ every charge, integer minor units. */ readonly totalPayable: number; /** Every charge, tagged with its booking role (itemized posting / audit). */ readonly components: readonly ImportChargeComponent[]; } interface TaxResolver { /** ISO 3166-1 alpha-2-ish code — 'BD', 'CA', 'US', 'EU-DE'. */ readonly countryCode: string; /** * Resolve a country-neutral tax class to its rate metadata as of a date. * Returns `null` for unknown classes. */ resolveClass(taxClass: string, asOf?: Date): TaxClassRate | null; /** Enumerate every known tax class (UI dropdowns / validation). */ listClasses(): readonly string[]; /** * Resolve the fiscal position for a buyer/seller pair. Contexts are * country-shaped; the contract keys them loosely and packs narrow * internally (unknown fields are ignored, never fatal). */ resolveFiscalPosition(buyer: Record, seller: Record, asOf?: Date): FiscalPositionResult; /** * Map a rate code + posting direction + regime to a GL account code. * Returns `null` when no posting is needed (exempt, non-claimable * input). Account codes are strings — the HOST resolves them to real * account ids (see `./obligation`'s `resolveAccount`). */ accountFor(rateCode: string, direction: PostingDirection, regime: AccountingRegime, asOf?: Date): string | null; /** * OPTIONAL — compute the FULL per-line tax breakdown (every tax that applies: * VAT + SD for BD, state + local for US, GST + PST for CA). Input is * country-neutral (a taxable line); output is country-specific (the set of * taxes). This is the port that makes a country-agnostic invoice/POS tax * pipeline possible: the host calls `resolver.computeLine(...)` and posts each * returned component via `accountFor(component.rateCode, component.direction, * regime)` — never branching on `countryCode`. * * Optional so packs adopt it incrementally; callers guard with * `typeof resolver.computeLine === 'function'`. * * Returns a {@link TaxLineResolution} — three outcomes, and an unrecognised class is `unknown`, NOT a * zero. It used to return `TaxLineComputation | null` with "caller treats as untaxed" written into * this very docblock, which is how a misspelled class produced a zero-tax invoice. Money paths call * {@link taxLineOrThrow}. */ computeLine?(input: TaxLineInput): TaxLineResolution; /** * OPTIONAL — compute withholdings retained from a supplier payment (BD * TDS + VDS, US 1099 backup withholding, …). Returns one entry per applicable * withholding, each POSITIVE; the host reduces the payable by their sum and * posts each to its `account` as a liability to the authority. Country-neutral * in, country-specific out — same shape as `computeLine`, different surface. * * Optional so packs adopt it incrementally; callers guard with * `typeof resolver.computeWithholding === 'function'`. Returns `[]` when * nothing is withheld (below threshold, wrong payee type, no VAT for VDS). */ computeWithholding?(input: WithholdingInput): readonly WithholdingComponent[]; /** * OPTIONAL — compute the import customs charge stack for goods entering the * country (BD: CD/RD/SD/VAT/AT/AIT in NBR sequence; other packs their own * cascade). Country-neutral in (assessable value + a pack-specific rate bag); * country-specific out — each charge tagged with a booking role * ({@link ImportChargeRole}) so the host posts inventory cost / recoverable * import VAT / prepaid tax WITHOUT branching on `countryCode`. * * Optional so packs adopt it incrementally; callers guard with * `typeof resolver.computeImportStack === 'function'`. Returns `null` when the * pack has no import-duty regime. */ computeImportStack?(input: ImportStackInput): ImportStackComputation | null; } /** * Static descriptor a jurisdiction pack exports alongside its factories — * lets multi-country hosts (and AI agents via MCP introspection) discover * what a pack covers without importing its internals. */ interface TaxPackDescriptor { /** Matches `TaxResolver.countryCode`. */ countryCode: string; /** Human name — 'Bangladesh (NBR)', 'Canada (CRA)'. */ name: string; /** ISO 4217 base currency the pack computes in (primitives' `CurrencyCode` accepted). */ currency: CurrencyCode | string; /** * Minor units per major (100 for paisa/cents). MUST equal primitives' * `minorUnitFactor(currency)` — duplicated here only so the descriptor * stays a dependency-free static literal; a drift is a pack bug. */ minorUnitsPerMajor: number; /** First month of the fiscal year (1-12; BD = 7, CA = 1 personal / configurable corporate). */ fiscalYearStartMonth: number; /** Tax categories the pack covers — 'vat', 'gst-hst', 'tds', 'income', 'payroll', … */ categories: readonly string[]; /** Authority names for display/audit — ['NBR'], ['CRA', 'Revenu Québec']. */ authorities: readonly string[]; } //#endregion export { AccountingRegime, FiscalPositionResult, ImportChargeComponent, ImportChargeRole, ImportStackComputation, ImportStackInput, PostingDirection, RelatedPartySupply, TaxClassRate, TaxComponentRole, TaxLineComponent, TaxLineComputation, TaxLineInput, TaxLineResolution, TaxPackDescriptor, TaxResolver, UnknownTaxClassError, WithholdingComponent, WithholdingInput, WithholdingPoint, taxLineOrThrow };