@12-apps/fiscal 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Everything the computation decides BEFORE a per-item figure is produced:
3
+ * the regime's treatment on the date, which items are segregated exclusions,
4
+ * each taxed item's reduction and base (`vBC`). Shared by the table mode and
5
+ * the oracle mode, so the two can only ever disagree on the per-item figures —
6
+ * the thing the oracle is there to check.
7
+ */
8
+
9
+ import { FiscalEngineError } from "./errors";
10
+ import { effectiveRate, netUnitValue, splitTaxInclusivePrice } from "./rounding";
11
+ import { assertTaxInput, periodAt } from "./validate";
12
+ import type {
13
+ LineFigures,
14
+ LineSource,
15
+ LineTax,
16
+ RatePeriod,
17
+ TaxBreakdown,
18
+ TaxClass,
19
+ TaxClassCode,
20
+ TaxInput,
21
+ TaxRegime,
22
+ TaxTreatment,
23
+ } from "./types";
24
+
25
+ /** The three nominal rates at the destination. */
26
+ export interface DestinationRates {
27
+ readonly cbsBp: number;
28
+ readonly ibsUfBp: number;
29
+ readonly ibsMunBp: number;
30
+ }
31
+
32
+ export interface PlannedLine {
33
+ readonly lineId: string;
34
+ readonly source: LineSource;
35
+ readonly quantity: number;
36
+ readonly valueCents: number;
37
+ readonly taxClass: TaxClass;
38
+ readonly reductionBp: number;
39
+ /** False for a segregated exclusion and for a line whose rates do not apply. */
40
+ readonly taxed: boolean;
41
+ /** `vBC`: the value, the value less its inside tax, or 0 on an exclusion. */
42
+ readonly taxBaseCents: number;
43
+ }
44
+
45
+ export interface TaxPlan {
46
+ readonly input: TaxInput;
47
+ readonly period: RatePeriod;
48
+ readonly rates: DestinationRates;
49
+ readonly treatment: TaxTreatment;
50
+ readonly informative: boolean;
51
+ readonly lines: readonly PlannedLine[];
52
+ readonly gorjetaExcludedCents: number;
53
+ readonly intermediationExcludedCents: number;
54
+ }
55
+
56
+ const TREATMENT: Readonly<Record<TaxRegime, TaxTreatment>> = {
57
+ REGIME_REGULAR: "FULL",
58
+ SIMPLES_IBS_CBS_REGULAR: "FULL",
59
+ SIMPLES: "INFORMATIVE",
60
+ MEI: "NONE",
61
+ NAO_CONTRIBUINTE: "NONE",
62
+ };
63
+
64
+ function isSimplesOptant(regime: TaxRegime): boolean {
65
+ return regime === "SIMPLES" || regime === "SIMPLES_IBS_CBS_REGULAR";
66
+ }
67
+
68
+ /** The destination's own rate where the table lists one, the reference rate everywhere else. */
69
+ function ownOrReference(rates: Readonly<Record<string, number>>, key: string, referenceBp: number): number {
70
+ return Object.hasOwn(rates, key) ? rates[key]! : referenceBp;
71
+ }
72
+
73
+ /** The three nominal rates of the period at the destination (art. 11 I). */
74
+ export function ratesAt(period: RatePeriod, destinationIbge: string): DestinationRates {
75
+ return {
76
+ cbsBp: period.cbsBp,
77
+ ibsUfBp: ownOrReference(period.ibsUf.byUf, destinationIbge.slice(0, 2), period.ibsUf.referenceBp),
78
+ ibsMunBp: ownOrReference(period.ibsMun.byMunicipality, destinationIbge, period.ibsMun.referenceBp),
79
+ };
80
+ }
81
+
82
+ /** The effective rates of one item, in the order CBS, IBS-UF, IBS-Mun. */
83
+ function effectiveRates(rates: DestinationRates, reductionBp: number): bigint[] {
84
+ return [rates.cbsBp, rates.ibsUfBp, rates.ibsMunBp].map((rate) => effectiveRate(rate, reductionBp));
85
+ }
86
+
87
+ /**
88
+ * The gorjeta is excluded only when it is passed in full to the staff and is
89
+ * at most 15% of the food and drink (art. 274 par. único I, read as a
90
+ * condition): above the ceiling nothing is excluded — the conservative
91
+ * reading, which never under-states the tax. Restaurant regime only.
92
+ */
93
+ function gorjetaIsExcluded(input: TaxInput): boolean {
94
+ const charge = input.exclusions.serviceCharge;
95
+ if (!charge || !charge.passedToStaff || !input.seller.restaurantRegime) return false;
96
+ const foodAndDrink = input.lines.filter((line) => line.foodAndDrink).reduce((sum, line) => sum + line.valueCents, 0);
97
+ return BigInt(charge.amountCents) * 10_000n <= BigInt(foodAndDrink) * BigInt(input.tables.gorjetaCapBp);
98
+ }
99
+
100
+ /** The 40% of art. 275 applies to the special regime's lines in a restaurant store; otherwise the class's own. */
101
+ function reductionFor(input: TaxInput, taxClass: TaxClass): number {
102
+ if (input.seller.restaurantRegime && taxClass.regimeEspecifico === "BARES_RESTAURANTES") {
103
+ return input.tables.specialRegimes.BARES_RESTAURANTES.reductionBp;
104
+ }
105
+ return taxClass.reductionBp;
106
+ }
107
+
108
+ function exclusionClass(code: TaxClassCode): TaxClass {
109
+ return { cClassTrib: code.cClassTrib, cstIbsCbs: code.cstIbsCbs, regimeEspecifico: null, reductionBp: 0 };
110
+ }
111
+
112
+ interface LineDraft {
113
+ readonly lineId: string;
114
+ readonly source: LineSource;
115
+ readonly quantity: number;
116
+ readonly valueCents: number;
117
+ readonly taxClass: TaxClass;
118
+ readonly excluded: boolean;
119
+ }
120
+
121
+ function exclusionDrafts(input: TaxInput, gorjetaExcluded: boolean): LineDraft[] {
122
+ const drafts: LineDraft[] = [];
123
+ const charge = input.exclusions.serviceCharge;
124
+ if (charge) {
125
+ drafts.push({
126
+ lineId: charge.id,
127
+ source: gorjetaExcluded ? "GORJETA_EXCLUDED" : "SERVICE_CHARGE",
128
+ quantity: 1,
129
+ valueCents: charge.amountCents,
130
+ taxClass: gorjetaExcluded ? exclusionClass(input.tables.exclusionClasses.GORJETA) : charge.taxClass,
131
+ excluded: gorjetaExcluded,
132
+ });
133
+ }
134
+ const retained = input.exclusions.retainedIntermediation;
135
+ if (retained) {
136
+ if (!input.seller.restaurantRegime) {
137
+ throw new FiscalEngineError(
138
+ "INVALID_INPUT",
139
+ "a retained intermediation is excluded only when seller.restaurantRegime is set (art. 274 sole paragraph, II); otherwise the amount belongs in the lines",
140
+ );
141
+ }
142
+ drafts.push({
143
+ lineId: retained.id,
144
+ source: "INTERMEDIATION_EXCLUDED",
145
+ quantity: 1,
146
+ valueCents: retained.amountCents,
147
+ taxClass: exclusionClass(input.tables.exclusionClasses.INTERMEDIATION),
148
+ excluded: true,
149
+ });
150
+ }
151
+ return drafts;
152
+ }
153
+
154
+ function planLine(draft: LineDraft, input: TaxInput, context: { ratesApply: boolean; period: RatePeriod; rates: DestinationRates }): PlannedLine {
155
+ const reductionBp = draft.excluded ? 0 : reductionFor(input, draft.taxClass);
156
+ const taxed = !draft.excluded && context.ratesApply;
157
+ let taxBaseCents = draft.excluded ? 0 : draft.valueCents;
158
+ if (taxed && context.period.taxInsidePrice) {
159
+ taxBaseCents = splitTaxInclusivePrice(draft.valueCents, effectiveRates(context.rates, reductionBp)).baseCents;
160
+ }
161
+ return {
162
+ lineId: draft.lineId,
163
+ source: draft.source,
164
+ quantity: draft.quantity,
165
+ valueCents: draft.valueCents,
166
+ taxClass: draft.taxClass,
167
+ reductionBp,
168
+ taxed,
169
+ taxBaseCents,
170
+ };
171
+ }
172
+
173
+ export function planTax(input: TaxInput): TaxPlan {
174
+ assertTaxInput(input);
175
+ const { regime, regimeEffectiveFrom } = input.seller;
176
+ if (input.supplyDate < regimeEffectiveFrom) {
177
+ throw new FiscalEngineError(
178
+ "REGIME_NOT_IN_EFFECT",
179
+ `the supply on ${input.supplyDate} precedes the seller's ${regime} regime, effective ${regimeEffectiveFrom}`,
180
+ );
181
+ }
182
+ const period = periodAt(input.tables, input.supplyDate);
183
+ const rates = ratesAt(period, input.destinationIbge);
184
+ const treatment = TREATMENT[regime];
185
+ const ratesApply = treatment !== "NONE" && (!isSimplesOptant(regime) || period.appliesToSimplesNacional);
186
+ const gorjetaExcluded = gorjetaIsExcluded(input);
187
+ const drafts: LineDraft[] = [
188
+ ...input.lines.map((line) => ({
189
+ lineId: line.id,
190
+ source: "LINE" as const,
191
+ quantity: line.quantity,
192
+ valueCents: line.valueCents,
193
+ taxClass: line.taxClass,
194
+ excluded: false,
195
+ })),
196
+ ...exclusionDrafts(input, gorjetaExcluded),
197
+ ];
198
+ return {
199
+ input,
200
+ period,
201
+ rates,
202
+ treatment,
203
+ informative: treatment === "INFORMATIVE" || (treatment === "FULL" && period.informative),
204
+ lines: drafts.map((draft) => planLine(draft, input, { ratesApply, period, rates })),
205
+ gorjetaExcludedCents: gorjetaExcluded ? input.exclusions.serviceCharge!.amountCents : 0,
206
+ intermediationExcludedCents: input.exclusions.retainedIntermediation?.amountCents ?? 0,
207
+ };
208
+ }
209
+
210
+ /** Zero figures, for an excluded line or one whose rates do not apply. */
211
+ export function zeroFigures(line: PlannedLine): LineFigures {
212
+ return {
213
+ reductionBp: line.reductionBp,
214
+ cbsRateBp: 0,
215
+ cbsCents: 0,
216
+ ibsUfRateBp: 0,
217
+ ibsUfCents: 0,
218
+ ibsMunRateBp: 0,
219
+ ibsMunCents: 0,
220
+ };
221
+ }
222
+
223
+ function lineTax(plan: TaxPlan, line: PlannedLine, figures: LineFigures): LineTax {
224
+ const taxCents = figures.cbsCents + figures.ibsUfCents + figures.ibsMunCents;
225
+ const netValueCents = plan.period.taxInsidePrice ? line.valueCents - taxCents : null;
226
+ return {
227
+ lineId: line.lineId,
228
+ source: line.source,
229
+ quantity: line.quantity,
230
+ valueCents: line.valueCents,
231
+ taxBaseCents: line.taxBaseCents,
232
+ taxClass: line.taxClass,
233
+ ...figures,
234
+ taxCents,
235
+ netValueCents,
236
+ netUnitValue: netValueCents === null ? null : netUnitValue(netValueCents, line.quantity),
237
+ };
238
+ }
239
+
240
+ /** The breakdown: each line with its figures, the order as the sum of its rounded lines. */
241
+ export function assembleBreakdown(plan: TaxPlan, figures: readonly LineFigures[], tablesVersion: string): TaxBreakdown {
242
+ const lines = plan.lines.map((line, index) => lineTax(plan, line, figures[index]!));
243
+ const sum = (pick: (line: LineTax) => number) => lines.reduce((total, line) => total + pick(line), 0);
244
+ const cbsCents = sum((line) => line.cbsCents);
245
+ const ibsUfCents = sum((line) => line.ibsUfCents);
246
+ const ibsMunCents = sum((line) => line.ibsMunCents);
247
+ return {
248
+ lines,
249
+ valueCents: sum((line) => line.valueCents),
250
+ taxBaseCents: sum((line) => line.taxBaseCents),
251
+ cbsCents,
252
+ ibsUfCents,
253
+ ibsMunCents,
254
+ ibsCents: ibsUfCents + ibsMunCents,
255
+ totalTaxCents: cbsCents + ibsUfCents + ibsMunCents,
256
+ netValueCents: plan.period.taxInsidePrice ? sum((line) => line.netValueCents ?? 0) : null,
257
+ gorjetaExcludedCents: plan.gorjetaExcludedCents,
258
+ intermediationExcludedCents: plan.intermediationExcludedCents,
259
+ regime: plan.input.seller.regime,
260
+ treatment: plan.treatment,
261
+ informative: plan.informative,
262
+ provisional: plan.period.status === "ESTIMATE",
263
+ taxInsidePrice: plan.period.taxInsidePrice,
264
+ supplyDate: plan.input.supplyDate,
265
+ destinationIbge: plan.input.destinationIbge,
266
+ tablesVersion,
267
+ };
268
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The NF-e per-item rounding: each tax of each item is rounded to whole cents
3
+ * on its own, and a document total is the sum of its rounded items. The mode
4
+ * is HALF-EVEN (ABNT NBR 5891), the official calculator's: R$ 5,00 × 0,9% =
5
+ * 0,045 → 0,04 and R$ 25,00 × 0,9% = 0,225 → 0,22, recorded from the
6
+ * calculator in `__tests__/fixtures/calculator/half-cent.*`. Never a floor.
7
+ *
8
+ * The reduction applies to the RATE (the layout's `pAliqEfet = pAliq × (1 −
9
+ * pRedAliq)`), and the product is computed exactly in integers: cents × bp ×
10
+ * bp needs up to 10^17 for a large order, past `Number.MAX_SAFE_INTEGER`, so
11
+ * the arithmetic is BigInt and nothing is rounded before the end.
12
+ */
13
+
14
+ const BP = 10_000n;
15
+ /** The denominator of an effective rate: bp × bp. */
16
+ const RATE_SCALE = BP * BP;
17
+
18
+ /** round_half_even(numerator / denominator) for a non-negative numerator. */
19
+ function roundHalfEven(numerator: bigint, denominator: bigint): bigint {
20
+ const quotient = numerator / denominator;
21
+ const twice = (numerator - quotient * denominator) * 2n;
22
+ if (twice > denominator) return quotient + 1n;
23
+ if (twice < denominator) return quotient;
24
+ return quotient % 2n === 0n ? quotient : quotient + 1n;
25
+ }
26
+
27
+ /** The effective rate's numerator over `RATE_SCALE`: rateBp × (10⁴ − reductionBp). */
28
+ export function effectiveRate(rateBp: number, reductionBp: number): bigint {
29
+ return BigInt(rateBp) * (BP - BigInt(reductionBp));
30
+ }
31
+
32
+ /** round_half_even(baseCents × rateBp/10⁴ × (1 − reductionBp/10⁴)), in cents. */
33
+ export function roundTaxCents(baseCents: number, rateBp: number, reductionBp: number): number {
34
+ return Number(roundHalfEven(BigInt(baseCents) * effectiveRate(rateBp, reductionBp), RATE_SCALE));
35
+ }
36
+
37
+ function taxesOn(base: bigint, rates: readonly bigint[]): bigint[] {
38
+ return rates.map((rate) => roundHalfEven(base * rate, RATE_SCALE));
39
+ }
40
+
41
+ /**
42
+ * Take the taxes OUT of a tax-inclusive price. The base (`vBC`) is the
43
+ * largest whole-cent amount whose own rounded taxes, added back, do not pass
44
+ * the price — the exact `price / (1 + Σ rates)` or the cent below it. The
45
+ * taxes are each rounded on that base (so `vBC × pAliqEfet` holds per tax),
46
+ * and the net value (`vProdLiq`) is the
47
+ * price less them, so `net + Σ taxes = price` to the cent.
48
+ */
49
+ export function splitTaxInclusivePrice(
50
+ priceCents: number,
51
+ rates: readonly bigint[],
52
+ ): { baseCents: number; taxCents: number[]; netCents: number } {
53
+ const price = BigInt(priceCents);
54
+ const total = rates.reduce((sum, rate) => sum + rate, 0n);
55
+ // Three cents above the exact base: f(b) = b + Σ round(b × r) ≥ b(1 + r) − 1.5,
56
+ // so from there f(b) is past the price and the walk down meets the answer.
57
+ let base = (price * RATE_SCALE) / (RATE_SCALE + total) + 3n;
58
+ let taxes = taxesOn(base, rates);
59
+ while (base > 0n && base + taxes.reduce((sum, tax) => sum + tax, 0n) > price) {
60
+ base -= 1n;
61
+ taxes = taxesOn(base, rates);
62
+ }
63
+ const taxCents = taxes.map(Number);
64
+ return { baseCents: Number(base), taxCents, netCents: priceCents - taxCents.reduce((sum, tax) => sum + tax, 0) };
65
+ }
66
+
67
+ /** Quantity with at most four decimals (`qCom`), as ten-thousandths. */
68
+ function quantityInTenThousandths(quantity: number): bigint {
69
+ return BigInt(Math.round(quantity * 10_000));
70
+ }
71
+
72
+ /**
73
+ * `vUnComLiq`: the net value per unit, in reais with ten decimals, rounded
74
+ * half-even — far inside the ±0,01 the layout allows between it × `qCom` and
75
+ * `vProdLiq` (rule I11c-20).
76
+ */
77
+ export function netUnitValue(netCents: number, quantity: number): string {
78
+ const scaled = roundHalfEven(BigInt(netCents) * 10n ** 12n, quantityInTenThousandths(quantity));
79
+ const digits = scaled.toString().padStart(11, "0");
80
+ return `${digits.slice(0, -10)}.${digits.slice(-10)}`;
81
+ }
@@ -0,0 +1,270 @@
1
+ /**
2
+ * The engine's vocabulary. Money is integer CENTS, rates are integer BASIS
3
+ * POINTS (1 bp = 0.01%), dates are ISO calendar days (`YYYY-MM-DD`) in the
4
+ * seller's own clock — the fato gerador is the local day of the supply, and the
5
+ * host, which owns the clock, says which day that was.
6
+ *
7
+ * Nothing here has a default. Every field is required, and a value the engine
8
+ * cannot read is refused with a `FiscalEngineError`, never guessed.
9
+ */
10
+
11
+ /** An ISO calendar day, `YYYY-MM-DD`. */
12
+ export type IsoDate = string;
13
+
14
+ /**
15
+ * The seller's IBS/CBS regime (LC 214/2025 art. 41).
16
+ *
17
+ * - `REGIME_REGULAR` — Lucro Presumido/Real: the full breakdown, "por fora".
18
+ * - `SIMPLES_IBS_CBS_REGULAR` — the Simples híbrido (art. 41 §3): a Simples
19
+ * optant that applies the regime regular to IBS/CBS; full breakdown.
20
+ * - `SIMPLES` — inside the DAS (art. 41 §2): an `INFORMATIVE` breakdown, with
21
+ * the figures a regime store would show and no amount charged "por fora".
22
+ * - `MEI` and `NAO_CONTRIBUINTE` — no IBS/CBS on the document: zero.
23
+ */
24
+ export type TaxRegime =
25
+ | "REGIME_REGULAR"
26
+ | "SIMPLES_IBS_CBS_REGULAR"
27
+ | "SIMPLES"
28
+ | "MEI"
29
+ | "NAO_CONTRIBUINTE";
30
+
31
+ /** The special regimes the engine applies. */
32
+ export type RegimeEspecifico = "BARES_RESTAURANTES";
33
+
34
+ /** What the treatment of the seller's regime is on the date of the supply. */
35
+ export type TaxTreatment = "FULL" | "INFORMATIVE" | "NONE";
36
+
37
+ /** The two codes an NF-e item carries for its IBS/CBS classification. */
38
+ export interface TaxClassCode {
39
+ readonly cClassTrib: string;
40
+ readonly cstIbsCbs: string;
41
+ }
42
+
43
+ /**
44
+ * A line's tax class, as the host classified the item. `cClassTrib` and
45
+ * `cstIbsCbs` are carried opaque into the snapshot (the classification table
46
+ * is the host's data, Informe Técnico 2025.002).
47
+ *
48
+ * `regimeEspecifico: "BARES_RESTAURANTES"` marks prepared food and
49
+ * non-alcoholic drinks prepared on the premises (art. 273 caput, §1; the
50
+ * official class is 200047). Alcohol, even prepared on the premises, and food
51
+ * or drink bought from third parties and resold as-is are OUT (art. 273 §2)
52
+ * and must carry `null`.
53
+ */
54
+ export interface TaxClass extends TaxClassCode {
55
+ readonly regimeEspecifico: RegimeEspecifico | null;
56
+ /** The class's own rate reduction (a listed-food reduction, say), 0–10000. */
57
+ readonly reductionBp: number;
58
+ }
59
+
60
+ /** One priced line of the supply. */
61
+ export interface TaxLineInput {
62
+ /** The host's id, echoed on the output line; unique within the input. */
63
+ readonly id: string;
64
+ /**
65
+ * What the line costs the buyer, every unit, AFTER its allocated discount
66
+ * (an unconditional discount is outside the base, art. 12 §2 III). It is
67
+ * the price the shopper sees, so in a period whose table says
68
+ * `taxInsidePrice` the IBS/CBS are INSIDE it and the engine takes them out;
69
+ * otherwise it is the base itself and the tax is computed on top of it.
70
+ */
71
+ readonly valueCents: number;
72
+ /** Units (`qCom`): positive, at most four decimals (weighed goods). */
73
+ readonly quantity: number;
74
+ /**
75
+ * Whether the line is food or drink — what the gorjeta's 15% ceiling is
76
+ * measured against (art. 274 par. único I). A delivery fee is not.
77
+ */
78
+ readonly foodAndDrink: boolean;
79
+ readonly taxClass: TaxClass;
80
+ }
81
+
82
+ /** Who sells, and under which regime since when. */
83
+ export interface SellerProfile {
84
+ readonly regime: TaxRegime;
85
+ /** The first day `regime` applies. A supply before it is refused. */
86
+ readonly regimeEffectiveFrom: IsoDate;
87
+ /** Whether the bares e restaurantes regime (arts. 273–276) applies. */
88
+ readonly restaurantRegime: boolean;
89
+ }
90
+
91
+ /** The service charge (taxa de serviço / gorjeta) on the supply. */
92
+ export interface ServiceChargeInput {
93
+ /** Echoed as the service-charge line's id; unique within the input. */
94
+ readonly id: string;
95
+ readonly amountCents: number;
96
+ /** Whether the charge is passed in full to the staff. */
97
+ readonly passedToStaff: boolean;
98
+ /** The class the WHOLE charge is taxed at when it is not excluded. */
99
+ readonly taxClass: TaxClass;
100
+ }
101
+
102
+ /** What a digital platform retained for delivery and intermediation. */
103
+ export interface RetainedIntermediationInput {
104
+ /** Echoed as the excluded line's id; unique within the input. */
105
+ readonly id: string;
106
+ /** Never passed to the restaurant; NOT included in any line's value. */
107
+ readonly amountCents: number;
108
+ }
109
+
110
+ /**
111
+ * The amounts the restaurant regime keeps out of the base (art. 274 par.
112
+ * único), each segregated on the document as its own item (RCBS art. 399 §2:
113
+ * without the segregation the base is the full value, §4).
114
+ */
115
+ export interface TaxExclusions {
116
+ /**
117
+ * Excluded (its own line, the table's gorjeta class) only when the store is
118
+ * in the restaurant regime, the charge is passed in full to the staff AND it
119
+ * is at most 15% of the food and drink. Otherwise the whole charge is a
120
+ * taxed line under its own class — never a partial exclusion.
121
+ */
122
+ readonly serviceCharge: ServiceChargeInput | null;
123
+ /** Restaurant regime only (art. 274 par. único II); refused elsewhere. */
124
+ readonly retainedIntermediation: RetainedIntermediationInput | null;
125
+ }
126
+
127
+ /** The IBS share of one sphere in one period: the reference and the overrides. */
128
+ export interface IbsSphereRates {
129
+ /** The reference rate, which applies wherever no own rate is listed. */
130
+ readonly referenceBp: number;
131
+ }
132
+
133
+ export interface IbsUfRates extends IbsSphereRates {
134
+ /** State rates keyed by the 2-digit IBGE state code. */
135
+ readonly byUf: Readonly<Record<string, number>>;
136
+ }
137
+
138
+ export interface IbsMunRates extends IbsSphereRates {
139
+ /** Municipal rates keyed by the 7-digit IBGE municipality code. */
140
+ readonly byMunicipality: Readonly<Record<string, number>>;
141
+ }
142
+
143
+ /** One stretch of time with one set of rates. */
144
+ export interface RatePeriod {
145
+ readonly from: IsoDate;
146
+ /** Inclusive; `null` is open-ended. */
147
+ readonly to: IsoDate | null;
148
+ /** `ESTIMATE` stamps every result computed on it `provisional`. */
149
+ readonly status: "LAW" | "ESTIMATE";
150
+ readonly source: string;
151
+ /** The test year: highlighted, payment waived (art. 348 §1). */
152
+ readonly informative: boolean;
153
+ /** `false` in 2026: the test rates are not applied to Simples optants (art. 348 III "c"). */
154
+ readonly appliesToSimplesNacional: boolean;
155
+ /**
156
+ * Whether the IBS/CBS sit INSIDE the item's value on the document (they
157
+ * compose `vProd` and the price without tax travels in `vProdLiq`) — from
158
+ * 2027 by the NF-e layout. When true, a line's `valueCents` is the
159
+ * tax-inclusive price.
160
+ */
161
+ readonly taxInsidePrice: boolean;
162
+ readonly cbsBp: number;
163
+ readonly ibsUf: IbsUfRates;
164
+ readonly ibsMun: IbsMunRates;
165
+ }
166
+
167
+ /** A versioned rate table: DATA, loaded by the host, stamped on every result. */
168
+ export interface RateTables {
169
+ readonly version: string;
170
+ readonly notes?: readonly string[];
171
+ /** The gorjeta's ceiling as a share of food and drink: 1500 (art. 274 par. único I). */
172
+ readonly gorjetaCapBp: number;
173
+ readonly gorjetaCapSource?: string;
174
+ /** The classes the excluded items are segregated under (410019, 410020). */
175
+ readonly exclusionClasses: {
176
+ readonly GORJETA: TaxClassCode;
177
+ readonly INTERMEDIATION: TaxClassCode;
178
+ readonly source?: string;
179
+ };
180
+ readonly specialRegimes: Readonly<
181
+ Record<RegimeEspecifico, { readonly reductionBp: number; readonly source: string }>
182
+ >;
183
+ readonly periods: readonly RatePeriod[];
184
+ }
185
+
186
+ /** Everything one computation needs. */
187
+ export interface TaxInput {
188
+ readonly lines: readonly TaxLineInput[];
189
+ readonly seller: SellerProfile;
190
+ /**
191
+ * The 7-digit IBGE code of the place the IBS goes to: the establishment,
192
+ * or for a delivered good the place of delivery (art. 11 I).
193
+ */
194
+ readonly destinationIbge: string;
195
+ readonly exclusions: TaxExclusions;
196
+ readonly tables: RateTables;
197
+ /** The day of the supply; the rate is the rate of that day. */
198
+ readonly supplyDate: IsoDate;
199
+ }
200
+
201
+ /** Where an output line came from. */
202
+ export type LineSource = "LINE" | "SERVICE_CHARGE" | "GORJETA_EXCLUDED" | "INTERMEDIATION_EXCLUDED";
203
+
204
+ /** The per-tax figures of one line. Rates are nominal; `reductionBp` applies to all three. */
205
+ export interface LineFigures {
206
+ readonly reductionBp: number;
207
+ readonly cbsRateBp: number;
208
+ readonly cbsCents: number;
209
+ readonly ibsUfRateBp: number;
210
+ readonly ibsUfCents: number;
211
+ readonly ibsMunRateBp: number;
212
+ readonly ibsMunCents: number;
213
+ }
214
+
215
+ /** One output line — one NF-e item. */
216
+ export interface LineTax extends LineFigures {
217
+ readonly lineId: string;
218
+ readonly source: LineSource;
219
+ readonly quantity: number;
220
+ /** The value as given (`vProd`). */
221
+ readonly valueCents: number;
222
+ /** The base the taxes are computed on (`vBC`): 0 on an excluded line. */
223
+ readonly taxBaseCents: number;
224
+ /** CBS + IBS-UF + IBS-Mun of the line. */
225
+ readonly taxCents: number;
226
+ /**
227
+ * The value without tax (`vProdLiq` = value − tax) in a `taxInsidePrice`
228
+ * period; `null` when the tax is not inside the value.
229
+ */
230
+ readonly netValueCents: number | null;
231
+ /**
232
+ * The unit value without tax (`vUnComLiq`), in reais with ten decimals as
233
+ * the layout writes it, within ±0,01 of `vProdLiq / qCom` (rule I11c-20);
234
+ * `null` when `netValueCents` is.
235
+ */
236
+ readonly netUnitValue: string | null;
237
+ /** The class snapshot (the table's exclusion class on an excluded line). */
238
+ readonly taxClass: TaxClass;
239
+ }
240
+
241
+ /** The breakdown of one supply. Every order figure is the sum of its rounded lines. */
242
+ export interface TaxBreakdown {
243
+ readonly lines: readonly LineTax[];
244
+ readonly valueCents: number;
245
+ readonly taxBaseCents: number;
246
+ readonly cbsCents: number;
247
+ readonly ibsUfCents: number;
248
+ readonly ibsMunCents: number;
249
+ readonly ibsCents: number;
250
+ readonly totalTaxCents: number;
251
+ /** Σ `netValueCents` (`vProdLiqTot`), or `null` when the tax is not inside the values. */
252
+ readonly netValueCents: number | null;
253
+ readonly gorjetaExcludedCents: number;
254
+ readonly intermediationExcludedCents: number;
255
+ readonly regime: TaxRegime;
256
+ readonly treatment: TaxTreatment;
257
+ /**
258
+ * True when the figures are shown but not charged "por fora": the test year
259
+ * (2026), or a Simples store inside the DAS. False for a `NONE` treatment,
260
+ * which shows nothing.
261
+ */
262
+ readonly informative: boolean;
263
+ /** True when the period's figures are estimates, not law. */
264
+ readonly provisional: boolean;
265
+ /** Whether the line values were taken as tax-inclusive. */
266
+ readonly taxInsidePrice: boolean;
267
+ readonly supplyDate: IsoDate;
268
+ readonly destinationIbge: string;
269
+ readonly tablesVersion: string;
270
+ }