@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.
- package/README.md +124 -2
- package/dist/chunk-7QVYU63E.js +7 -0
- package/dist/chunk-7QVYU63E.js.map +1 -0
- package/dist/engine/index.d.ts +361 -0
- package/dist/engine/index.js +591 -0
- package/dist/engine/index.js.map +1 -0
- package/dist/manifest/index.d.ts +83 -0
- package/dist/manifest/index.js +33 -0
- package/dist/manifest/index.js.map +1 -0
- package/package.json +68 -4
- package/src/engine/compare.ts +68 -0
- package/src/engine/compute.ts +40 -0
- package/src/engine/errors.ts +28 -0
- package/src/engine/index.ts +20 -0
- package/src/engine/oracle.ts +81 -0
- package/src/engine/plan.ts +268 -0
- package/src/engine/rounding.ts +81 -0
- package/src/engine/types.ts +270 -0
- package/src/engine/validate.ts +222 -0
- package/src/manifest/index.ts +37 -0
- package/src/manifest/permissions.ts +28 -0
- package/tables/ibs-cbs-2026-11-13.json +156 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/engine/errors.ts","../../src/engine/rounding.ts","../../src/engine/validate.ts","../../src/engine/plan.ts","../../src/engine/compute.ts","../../src/engine/oracle.ts","../../src/engine/compare.ts"],"sourcesContent":["/**\n * Every refusal the engine makes. A refusal is a THROW, on purpose: the\n * engine has no fallback for an input it cannot read, and a figure computed\n * from a guess would be printed on a fiscal document as a confession of the\n * tax due (LC 214/2025 art. 60 §1).\n */\n\nexport type FiscalEngineErrorCode =\n /** A field is missing, out of range or of the wrong shape. */\n | \"INVALID_INPUT\"\n /** The rate table is malformed: a bad rate, a bad date, overlapping periods. */\n | \"INVALID_TABLES\"\n /** No period of the table covers the date of the supply. */\n | \"NO_RATE_PERIOD\"\n /** The supply precedes the seller's `regimeEffectiveFrom`. */\n | \"REGIME_NOT_IN_EFFECT\"\n /** The official calculator answered something that is not integer cents and basis points. */\n | \"INVALID_ORACLE_ANSWER\";\n\nexport class FiscalEngineError extends Error {\n readonly code: FiscalEngineErrorCode;\n\n constructor(code: FiscalEngineErrorCode, message: string) {\n super(`[fiscal/engine] ${code}: ${message}`);\n this.name = \"FiscalEngineError\";\n this.code = code;\n }\n}\n","/**\n * The NF-e per-item rounding: each tax of each item is rounded to whole cents\n * on its own, and a document total is the sum of its rounded items. The mode\n * is HALF-EVEN (ABNT NBR 5891), the official calculator's: R$ 5,00 × 0,9% =\n * 0,045 → 0,04 and R$ 25,00 × 0,9% = 0,225 → 0,22, recorded from the\n * calculator in `__tests__/fixtures/calculator/half-cent.*`. Never a floor.\n *\n * The reduction applies to the RATE (the layout's `pAliqEfet = pAliq × (1 −\n * pRedAliq)`), and the product is computed exactly in integers: cents × bp ×\n * bp needs up to 10^17 for a large order, past `Number.MAX_SAFE_INTEGER`, so\n * the arithmetic is BigInt and nothing is rounded before the end.\n */\n\nconst BP = 10_000n;\n/** The denominator of an effective rate: bp × bp. */\nconst RATE_SCALE = BP * BP;\n\n/** round_half_even(numerator / denominator) for a non-negative numerator. */\nfunction roundHalfEven(numerator: bigint, denominator: bigint): bigint {\n const quotient = numerator / denominator;\n const twice = (numerator - quotient * denominator) * 2n;\n if (twice > denominator) return quotient + 1n;\n if (twice < denominator) return quotient;\n return quotient % 2n === 0n ? quotient : quotient + 1n;\n}\n\n/** The effective rate's numerator over `RATE_SCALE`: rateBp × (10⁴ − reductionBp). */\nexport function effectiveRate(rateBp: number, reductionBp: number): bigint {\n return BigInt(rateBp) * (BP - BigInt(reductionBp));\n}\n\n/** round_half_even(baseCents × rateBp/10⁴ × (1 − reductionBp/10⁴)), in cents. */\nexport function roundTaxCents(baseCents: number, rateBp: number, reductionBp: number): number {\n return Number(roundHalfEven(BigInt(baseCents) * effectiveRate(rateBp, reductionBp), RATE_SCALE));\n}\n\nfunction taxesOn(base: bigint, rates: readonly bigint[]): bigint[] {\n return rates.map((rate) => roundHalfEven(base * rate, RATE_SCALE));\n}\n\n/**\n * Take the taxes OUT of a tax-inclusive price. The base (`vBC`) is the\n * largest whole-cent amount whose own rounded taxes, added back, do not pass\n * the price — the exact `price / (1 + Σ rates)` or the cent below it. The\n * taxes are each rounded on that base (so `vBC × pAliqEfet` holds per tax),\n * and the net value (`vProdLiq`) is the\n * price less them, so `net + Σ taxes = price` to the cent.\n */\nexport function splitTaxInclusivePrice(\n priceCents: number,\n rates: readonly bigint[],\n): { baseCents: number; taxCents: number[]; netCents: number } {\n const price = BigInt(priceCents);\n const total = rates.reduce((sum, rate) => sum + rate, 0n);\n // Three cents above the exact base: f(b) = b + Σ round(b × r) ≥ b(1 + r) − 1.5,\n // so from there f(b) is past the price and the walk down meets the answer.\n let base = (price * RATE_SCALE) / (RATE_SCALE + total) + 3n;\n let taxes = taxesOn(base, rates);\n while (base > 0n && base + taxes.reduce((sum, tax) => sum + tax, 0n) > price) {\n base -= 1n;\n taxes = taxesOn(base, rates);\n }\n const taxCents = taxes.map(Number);\n return { baseCents: Number(base), taxCents, netCents: priceCents - taxCents.reduce((sum, tax) => sum + tax, 0) };\n}\n\n/** Quantity with at most four decimals (`qCom`), as ten-thousandths. */\nfunction quantityInTenThousandths(quantity: number): bigint {\n return BigInt(Math.round(quantity * 10_000));\n}\n\n/**\n * `vUnComLiq`: the net value per unit, in reais with ten decimals, rounded\n * half-even — far inside the ±0,01 the layout allows between it × `qCom` and\n * `vProdLiq` (rule I11c-20).\n */\nexport function netUnitValue(netCents: number, quantity: number): string {\n const scaled = roundHalfEven(BigInt(netCents) * 10n ** 12n, quantityInTenThousandths(quantity));\n const digits = scaled.toString().padStart(11, \"0\");\n return `${digits.slice(0, -10)}.${digits.slice(-10)}`;\n}\n","/**\n * Input and table validation. Every check names the field it refused, and\n * every shape is checked before it is read, so a malformed input — a missing\n * object, an `undefined` where `null` is required, a `null` line — is a\n * `FiscalEngineError`, never a TypeError and never a NaN on a document.\n */\n\nimport { FiscalEngineError } from \"./errors\";\nimport type { FiscalEngineErrorCode } from \"./errors\";\nimport type { IsoDate, RatePeriod, RateTables, TaxClass, TaxClassCode, TaxInput, TaxLineInput, TaxRegime } from \"./types\";\n\nconst ISO_DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst IBGE_MUNICIPALITY = /^\\d{7}$/;\nconst IBGE_UF = /^\\d{2}$/;\nconst REGIMES: readonly TaxRegime[] = [\"REGIME_REGULAR\", \"SIMPLES_IBS_CBS_REGULAR\", \"SIMPLES\", \"MEI\", \"NAO_CONTRIBUINTE\"];\n\nfunction refuse(code: FiscalEngineErrorCode, message: string): never {\n throw new FiscalEngineError(code, message);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** A real calendar day in `YYYY-MM-DD` — `2026-02-30` is not one. */\nfunction isIsoDate(value: unknown): value is IsoDate {\n if (typeof value !== \"string\") return false;\n const match = ISO_DATE.exec(value);\n if (!match) return false;\n const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];\n const date = new Date(Date.UTC(year, month - 1, day));\n return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;\n}\n\nfunction isCents(value: unknown): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction isBp(value: unknown): value is number {\n return isCents(value) && value <= 10_000;\n}\n\nfunction isCode(value: unknown): value is string {\n return typeof value === \"string\" && value !== \"\";\n}\n\n/** Positive, finite, and at most four decimals — what `qCom` can carry. */\nfunction isQuantity(value: unknown): value is number {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) return false;\n const tenThousandths = Math.round(value * 10_000);\n return tenThousandths > 0 && Number.isSafeInteger(tenThousandths) && Math.abs(tenThousandths / 10_000 - value) < 1e-9;\n}\n\nfunction assertInput(ok: boolean, what: string): void {\n if (!ok) refuse(\"INVALID_INPUT\", what);\n}\n\nfunction assertTable(ok: boolean, what: string): void {\n if (!ok) refuse(\"INVALID_TABLES\", what);\n}\n\nfunction assertTaxClass(taxClass: unknown, where: string): asserts taxClass is TaxClass {\n assertInput(isRecord(taxClass), `${where} must be an object`);\n const value = taxClass as Record<string, unknown>;\n assertInput(isCode(value.cClassTrib), `${where}.cClassTrib must be a code`);\n assertInput(isCode(value.cstIbsCbs), `${where}.cstIbsCbs must be a code`);\n assertInput(\n value.regimeEspecifico === null || value.regimeEspecifico === \"BARES_RESTAURANTES\",\n `${where}.regimeEspecifico must be \"BARES_RESTAURANTES\" or null`,\n );\n assertInput(isBp(value.reductionBp), `${where}.reductionBp must be integer basis points in 0..10000`);\n}\n\nfunction assertLine(line: unknown, index: number): asserts line is TaxLineInput {\n const where = `lines[${index}]`;\n assertInput(isRecord(line), `${where} must be an object`);\n const value = line as Record<string, unknown>;\n assertInput(isCode(value.id), `${where}.id must be a non-empty string`);\n assertInput(isCents(value.valueCents), `${where}.valueCents must be non-negative integer cents`);\n assertInput(isQuantity(value.quantity), `${where}.quantity must be positive, with at most four decimals`);\n assertInput(typeof value.foodAndDrink === \"boolean\", `${where}.foodAndDrink must be a boolean`);\n assertTaxClass(value.taxClass, `${where}.taxClass`);\n}\n\nfunction assertServiceCharge(charge: unknown): void {\n if (charge === null) return;\n assertInput(isRecord(charge), \"exclusions.serviceCharge must be an object or null\");\n const value = charge as Record<string, unknown>;\n assertInput(isCode(value.id), \"exclusions.serviceCharge.id must be a non-empty string\");\n assertInput(isCents(value.amountCents), \"exclusions.serviceCharge.amountCents must be non-negative integer cents\");\n assertInput(typeof value.passedToStaff === \"boolean\", \"exclusions.serviceCharge.passedToStaff must be a boolean\");\n assertTaxClass(value.taxClass, \"exclusions.serviceCharge.taxClass\");\n}\n\nfunction assertIntermediation(retained: unknown): void {\n if (retained === null) return;\n assertInput(isRecord(retained), \"exclusions.retainedIntermediation must be an object or null\");\n const value = retained as Record<string, unknown>;\n assertInput(isCode(value.id), \"exclusions.retainedIntermediation.id must be a non-empty string\");\n assertInput(isCents(value.amountCents), \"exclusions.retainedIntermediation.amountCents must be non-negative integer cents\");\n}\n\nfunction assertExclusions(exclusions: unknown): void {\n assertInput(isRecord(exclusions), \"exclusions must be an object\");\n const value = exclusions as Record<string, unknown>;\n assertInput(\"serviceCharge\" in value, \"exclusions.serviceCharge must be given (null when there is none)\");\n assertInput(\"retainedIntermediation\" in value, \"exclusions.retainedIntermediation must be given (null when there is none)\");\n assertServiceCharge(value.serviceCharge);\n assertIntermediation(value.retainedIntermediation);\n}\n\nfunction assertUniqueIds(input: TaxInput): void {\n const ids = input.lines.map((line) => line.id);\n if (input.exclusions.serviceCharge) ids.push(input.exclusions.serviceCharge.id);\n if (input.exclusions.retainedIntermediation) ids.push(input.exclusions.retainedIntermediation.id);\n const seen = new Set<string>();\n for (const id of ids) {\n assertInput(!seen.has(id), `line id \"${id}\" is used twice`);\n seen.add(id);\n }\n}\n\nfunction assertSeller(seller: unknown): void {\n assertInput(isRecord(seller), \"seller must be an object\");\n const value = seller as Record<string, unknown>;\n assertInput(REGIMES.includes(value.regime as TaxRegime), `seller.regime must be one of ${REGIMES.join(\", \")}`);\n assertInput(isIsoDate(value.regimeEffectiveFrom), \"seller.regimeEffectiveFrom must be a YYYY-MM-DD day\");\n assertInput(typeof value.restaurantRegime === \"boolean\", \"seller.restaurantRegime must be a boolean\");\n}\n\n/** Refuse anything the engine cannot compute from. */\nexport function assertTaxInput(input: unknown): asserts input is TaxInput {\n assertInput(isRecord(input), \"the input must be an object\");\n const value = input as Record<string, unknown>;\n assertInput(Array.isArray(value.lines) && value.lines.length > 0, \"lines must hold at least one line\");\n (value.lines as unknown[]).forEach(assertLine);\n assertSeller(value.seller);\n assertInput(\n typeof value.destinationIbge === \"string\" && IBGE_MUNICIPALITY.test(value.destinationIbge),\n \"destinationIbge must be a 7-digit IBGE municipality code\",\n );\n assertExclusions(value.exclusions);\n assertUniqueIds(input as TaxInput);\n assertInput(isIsoDate(value.supplyDate), \"supplyDate must be a YYYY-MM-DD day\");\n assertRateTables(value.tables);\n}\n\nfunction assertRateMap(map: unknown, keyShape: RegExp, where: string): void {\n assertTable(isRecord(map), `${where} must be an object`);\n for (const [key, bp] of Object.entries(map as Record<string, unknown>)) {\n assertTable(keyShape.test(key), `${where} key \"${key}\" is not an IBGE code of the right length`);\n assertTable(isBp(bp), `${where}[\"${key}\"] must be integer basis points in 0..10000`);\n }\n}\n\nfunction assertSphere(sphere: unknown, mapKey: \"byUf\" | \"byMunicipality\", keyShape: RegExp, where: string): void {\n assertTable(isRecord(sphere), `${where} must be an object`);\n const value = sphere as Record<string, unknown>;\n assertTable(isBp(value.referenceBp), `${where}.referenceBp must be integer basis points in 0..10000`);\n assertRateMap(value[mapKey], keyShape, `${where}.${mapKey}`);\n}\n\nfunction assertPeriodFlags(value: Record<string, unknown>, where: string): void {\n assertTable(value.status === \"LAW\" || value.status === \"ESTIMATE\", `${where}.status must be LAW or ESTIMATE`);\n for (const flag of [\"informative\", \"appliesToSimplesNacional\", \"taxInsidePrice\"] as const) {\n assertTable(typeof value[flag] === \"boolean\", `${where}.${flag} must be a boolean`);\n }\n}\n\nfunction assertPeriod(period: unknown, index: number): asserts period is RatePeriod {\n const where = `periods[${index}]`;\n assertTable(isRecord(period), `${where} must be an object`);\n const value = period as Record<string, unknown>;\n assertTable(isIsoDate(value.from), `${where}.from must be a YYYY-MM-DD day`);\n assertTable(\n value.to === null || (isIsoDate(value.to) && value.to >= (value.from as string)),\n `${where}.to must be null or a day on or after from`,\n );\n assertPeriodFlags(value, where);\n assertTable(isBp(value.cbsBp), `${where}.cbsBp must be integer basis points in 0..10000`);\n assertSphere(value.ibsUf, \"byUf\", IBGE_UF, `${where}.ibsUf`);\n assertSphere(value.ibsMun, \"byMunicipality\", IBGE_MUNICIPALITY, `${where}.ibsMun`);\n}\n\nfunction assertClassCode(code: unknown, where: string): asserts code is TaxClassCode {\n assertTable(isRecord(code), `${where} must be an object`);\n const value = code as Record<string, unknown>;\n assertTable(isCode(value.cClassTrib) && isCode(value.cstIbsCbs), `${where} must carry cClassTrib and cstIbsCbs`);\n}\n\nfunction assertTableHeader(value: Record<string, unknown>): void {\n assertTable(isCode(value.version), \"version must be a non-empty string\");\n assertTable(isBp(value.gorjetaCapBp), \"gorjetaCapBp must be integer basis points in 0..10000\");\n const special = value.specialRegimes as Record<string, Record<string, unknown> | undefined> | undefined;\n assertTable(isRecord(special) && isRecord(special.BARES_RESTAURANTES), \"specialRegimes.BARES_RESTAURANTES must be an object\");\n assertTable(isBp(special!.BARES_RESTAURANTES!.reductionBp), \"specialRegimes.BARES_RESTAURANTES.reductionBp must be basis points\");\n assertTable(isRecord(value.exclusionClasses), \"exclusionClasses must be an object\");\n const classes = value.exclusionClasses as Record<string, unknown>;\n assertClassCode(classes.GORJETA, \"exclusionClasses.GORJETA\");\n assertClassCode(classes.INTERMEDIATION, \"exclusionClasses.INTERMEDIATION\");\n}\n\n/** Refuse a table the engine cannot trust: bad rates, bad dates, overlapping periods. */\nexport function assertRateTables(tables: unknown): asserts tables is RateTables {\n assertTable(isRecord(tables), \"the rate table must be an object\");\n const value = tables as Record<string, unknown>;\n assertTableHeader(value);\n assertTable(Array.isArray(value.periods) && value.periods.length > 0, \"periods must hold at least one period\");\n const periods = value.periods as unknown[];\n periods.forEach(assertPeriod);\n const sorted = [...(periods as RatePeriod[])].sort((a, b) => a.from.localeCompare(b.from));\n for (let i = 1; i < sorted.length; i += 1) {\n const previous = sorted[i - 1]!;\n assertTable(previous.to !== null && previous.to < sorted[i]!.from, `periods starting ${previous.from} and ${sorted[i]!.from} overlap`);\n }\n}\n\n/** The period covering `date`, or a refusal. */\nexport function periodAt(tables: RateTables, date: IsoDate): RatePeriod {\n const period = tables.periods.find((p) => p.from <= date && (p.to === null || date <= p.to));\n return period ?? refuse(\"NO_RATE_PERIOD\", `table ${tables.version} has no period covering ${date}`);\n}\n","/**\n * Everything the computation decides BEFORE a per-item figure is produced:\n * the regime's treatment on the date, which items are segregated exclusions,\n * each taxed item's reduction and base (`vBC`). Shared by the table mode and\n * the oracle mode, so the two can only ever disagree on the per-item figures —\n * the thing the oracle is there to check.\n */\n\nimport { FiscalEngineError } from \"./errors\";\nimport { effectiveRate, netUnitValue, splitTaxInclusivePrice } from \"./rounding\";\nimport { assertTaxInput, periodAt } from \"./validate\";\nimport type {\n LineFigures,\n LineSource,\n LineTax,\n RatePeriod,\n TaxBreakdown,\n TaxClass,\n TaxClassCode,\n TaxInput,\n TaxRegime,\n TaxTreatment,\n} from \"./types\";\n\n/** The three nominal rates at the destination. */\nexport interface DestinationRates {\n readonly cbsBp: number;\n readonly ibsUfBp: number;\n readonly ibsMunBp: number;\n}\n\nexport interface PlannedLine {\n readonly lineId: string;\n readonly source: LineSource;\n readonly quantity: number;\n readonly valueCents: number;\n readonly taxClass: TaxClass;\n readonly reductionBp: number;\n /** False for a segregated exclusion and for a line whose rates do not apply. */\n readonly taxed: boolean;\n /** `vBC`: the value, the value less its inside tax, or 0 on an exclusion. */\n readonly taxBaseCents: number;\n}\n\nexport interface TaxPlan {\n readonly input: TaxInput;\n readonly period: RatePeriod;\n readonly rates: DestinationRates;\n readonly treatment: TaxTreatment;\n readonly informative: boolean;\n readonly lines: readonly PlannedLine[];\n readonly gorjetaExcludedCents: number;\n readonly intermediationExcludedCents: number;\n}\n\nconst TREATMENT: Readonly<Record<TaxRegime, TaxTreatment>> = {\n REGIME_REGULAR: \"FULL\",\n SIMPLES_IBS_CBS_REGULAR: \"FULL\",\n SIMPLES: \"INFORMATIVE\",\n MEI: \"NONE\",\n NAO_CONTRIBUINTE: \"NONE\",\n};\n\nfunction isSimplesOptant(regime: TaxRegime): boolean {\n return regime === \"SIMPLES\" || regime === \"SIMPLES_IBS_CBS_REGULAR\";\n}\n\n/** The destination's own rate where the table lists one, the reference rate everywhere else. */\nfunction ownOrReference(rates: Readonly<Record<string, number>>, key: string, referenceBp: number): number {\n return Object.hasOwn(rates, key) ? rates[key]! : referenceBp;\n}\n\n/** The three nominal rates of the period at the destination (art. 11 I). */\nexport function ratesAt(period: RatePeriod, destinationIbge: string): DestinationRates {\n return {\n cbsBp: period.cbsBp,\n ibsUfBp: ownOrReference(period.ibsUf.byUf, destinationIbge.slice(0, 2), period.ibsUf.referenceBp),\n ibsMunBp: ownOrReference(period.ibsMun.byMunicipality, destinationIbge, period.ibsMun.referenceBp),\n };\n}\n\n/** The effective rates of one item, in the order CBS, IBS-UF, IBS-Mun. */\nfunction effectiveRates(rates: DestinationRates, reductionBp: number): bigint[] {\n return [rates.cbsBp, rates.ibsUfBp, rates.ibsMunBp].map((rate) => effectiveRate(rate, reductionBp));\n}\n\n/**\n * The gorjeta is excluded only when it is passed in full to the staff and is\n * at most 15% of the food and drink (art. 274 par. único I, read as a\n * condition): above the ceiling nothing is excluded — the conservative\n * reading, which never under-states the tax. Restaurant regime only.\n */\nfunction gorjetaIsExcluded(input: TaxInput): boolean {\n const charge = input.exclusions.serviceCharge;\n if (!charge || !charge.passedToStaff || !input.seller.restaurantRegime) return false;\n const foodAndDrink = input.lines.filter((line) => line.foodAndDrink).reduce((sum, line) => sum + line.valueCents, 0);\n return BigInt(charge.amountCents) * 10_000n <= BigInt(foodAndDrink) * BigInt(input.tables.gorjetaCapBp);\n}\n\n/** The 40% of art. 275 applies to the special regime's lines in a restaurant store; otherwise the class's own. */\nfunction reductionFor(input: TaxInput, taxClass: TaxClass): number {\n if (input.seller.restaurantRegime && taxClass.regimeEspecifico === \"BARES_RESTAURANTES\") {\n return input.tables.specialRegimes.BARES_RESTAURANTES.reductionBp;\n }\n return taxClass.reductionBp;\n}\n\nfunction exclusionClass(code: TaxClassCode): TaxClass {\n return { cClassTrib: code.cClassTrib, cstIbsCbs: code.cstIbsCbs, regimeEspecifico: null, reductionBp: 0 };\n}\n\ninterface LineDraft {\n readonly lineId: string;\n readonly source: LineSource;\n readonly quantity: number;\n readonly valueCents: number;\n readonly taxClass: TaxClass;\n readonly excluded: boolean;\n}\n\nfunction exclusionDrafts(input: TaxInput, gorjetaExcluded: boolean): LineDraft[] {\n const drafts: LineDraft[] = [];\n const charge = input.exclusions.serviceCharge;\n if (charge) {\n drafts.push({\n lineId: charge.id,\n source: gorjetaExcluded ? \"GORJETA_EXCLUDED\" : \"SERVICE_CHARGE\",\n quantity: 1,\n valueCents: charge.amountCents,\n taxClass: gorjetaExcluded ? exclusionClass(input.tables.exclusionClasses.GORJETA) : charge.taxClass,\n excluded: gorjetaExcluded,\n });\n }\n const retained = input.exclusions.retainedIntermediation;\n if (retained) {\n if (!input.seller.restaurantRegime) {\n throw new FiscalEngineError(\n \"INVALID_INPUT\",\n \"a retained intermediation is excluded only when seller.restaurantRegime is set (art. 274 sole paragraph, II); otherwise the amount belongs in the lines\",\n );\n }\n drafts.push({\n lineId: retained.id,\n source: \"INTERMEDIATION_EXCLUDED\",\n quantity: 1,\n valueCents: retained.amountCents,\n taxClass: exclusionClass(input.tables.exclusionClasses.INTERMEDIATION),\n excluded: true,\n });\n }\n return drafts;\n}\n\nfunction planLine(draft: LineDraft, input: TaxInput, context: { ratesApply: boolean; period: RatePeriod; rates: DestinationRates }): PlannedLine {\n const reductionBp = draft.excluded ? 0 : reductionFor(input, draft.taxClass);\n const taxed = !draft.excluded && context.ratesApply;\n let taxBaseCents = draft.excluded ? 0 : draft.valueCents;\n if (taxed && context.period.taxInsidePrice) {\n taxBaseCents = splitTaxInclusivePrice(draft.valueCents, effectiveRates(context.rates, reductionBp)).baseCents;\n }\n return {\n lineId: draft.lineId,\n source: draft.source,\n quantity: draft.quantity,\n valueCents: draft.valueCents,\n taxClass: draft.taxClass,\n reductionBp,\n taxed,\n taxBaseCents,\n };\n}\n\nexport function planTax(input: TaxInput): TaxPlan {\n assertTaxInput(input);\n const { regime, regimeEffectiveFrom } = input.seller;\n if (input.supplyDate < regimeEffectiveFrom) {\n throw new FiscalEngineError(\n \"REGIME_NOT_IN_EFFECT\",\n `the supply on ${input.supplyDate} precedes the seller's ${regime} regime, effective ${regimeEffectiveFrom}`,\n );\n }\n const period = periodAt(input.tables, input.supplyDate);\n const rates = ratesAt(period, input.destinationIbge);\n const treatment = TREATMENT[regime];\n const ratesApply = treatment !== \"NONE\" && (!isSimplesOptant(regime) || period.appliesToSimplesNacional);\n const gorjetaExcluded = gorjetaIsExcluded(input);\n const drafts: LineDraft[] = [\n ...input.lines.map((line) => ({\n lineId: line.id,\n source: \"LINE\" as const,\n quantity: line.quantity,\n valueCents: line.valueCents,\n taxClass: line.taxClass,\n excluded: false,\n })),\n ...exclusionDrafts(input, gorjetaExcluded),\n ];\n return {\n input,\n period,\n rates,\n treatment,\n informative: treatment === \"INFORMATIVE\" || (treatment === \"FULL\" && period.informative),\n lines: drafts.map((draft) => planLine(draft, input, { ratesApply, period, rates })),\n gorjetaExcludedCents: gorjetaExcluded ? input.exclusions.serviceCharge!.amountCents : 0,\n intermediationExcludedCents: input.exclusions.retainedIntermediation?.amountCents ?? 0,\n };\n}\n\n/** Zero figures, for an excluded line or one whose rates do not apply. */\nexport function zeroFigures(line: PlannedLine): LineFigures {\n return {\n reductionBp: line.reductionBp,\n cbsRateBp: 0,\n cbsCents: 0,\n ibsUfRateBp: 0,\n ibsUfCents: 0,\n ibsMunRateBp: 0,\n ibsMunCents: 0,\n };\n}\n\nfunction lineTax(plan: TaxPlan, line: PlannedLine, figures: LineFigures): LineTax {\n const taxCents = figures.cbsCents + figures.ibsUfCents + figures.ibsMunCents;\n const netValueCents = plan.period.taxInsidePrice ? line.valueCents - taxCents : null;\n return {\n lineId: line.lineId,\n source: line.source,\n quantity: line.quantity,\n valueCents: line.valueCents,\n taxBaseCents: line.taxBaseCents,\n taxClass: line.taxClass,\n ...figures,\n taxCents,\n netValueCents,\n netUnitValue: netValueCents === null ? null : netUnitValue(netValueCents, line.quantity),\n };\n}\n\n/** The breakdown: each line with its figures, the order as the sum of its rounded lines. */\nexport function assembleBreakdown(plan: TaxPlan, figures: readonly LineFigures[], tablesVersion: string): TaxBreakdown {\n const lines = plan.lines.map((line, index) => lineTax(plan, line, figures[index]!));\n const sum = (pick: (line: LineTax) => number) => lines.reduce((total, line) => total + pick(line), 0);\n const cbsCents = sum((line) => line.cbsCents);\n const ibsUfCents = sum((line) => line.ibsUfCents);\n const ibsMunCents = sum((line) => line.ibsMunCents);\n return {\n lines,\n valueCents: sum((line) => line.valueCents),\n taxBaseCents: sum((line) => line.taxBaseCents),\n cbsCents,\n ibsUfCents,\n ibsMunCents,\n ibsCents: ibsUfCents + ibsMunCents,\n totalTaxCents: cbsCents + ibsUfCents + ibsMunCents,\n netValueCents: plan.period.taxInsidePrice ? sum((line) => line.netValueCents ?? 0) : null,\n gorjetaExcludedCents: plan.gorjetaExcludedCents,\n intermediationExcludedCents: plan.intermediationExcludedCents,\n regime: plan.input.seller.regime,\n treatment: plan.treatment,\n informative: plan.informative,\n provisional: plan.period.status === \"ESTIMATE\",\n taxInsidePrice: plan.period.taxInsidePrice,\n supplyDate: plan.input.supplyDate,\n destinationIbge: plan.input.destinationIbge,\n tablesVersion,\n };\n}\n","/**\n * `computeTax` — the table mode. Pure: no I/O, no clock, no defaults. The\n * same input gives the same breakdown, stamped with the table's version, so a\n * supply settled in March reproduces its own tax in December after the tables\n * moved.\n */\n\nimport { assembleBreakdown, planTax, zeroFigures } from \"./plan\";\nimport type { PlannedLine, TaxPlan } from \"./plan\";\nimport { roundTaxCents } from \"./rounding\";\nimport type { LineFigures, TaxBreakdown, TaxInput } from \"./types\";\n\n/**\n * Each tax rounded on the item's base. In a tax-inside-price period the base\n * is the one the plan took out of the price, and these are the very taxes it\n * was taken out with.\n */\nfunction tableFigures(plan: TaxPlan, line: PlannedLine): LineFigures {\n if (!line.taxed) return zeroFigures(line);\n const { cbsBp, ibsUfBp, ibsMunBp } = plan.rates;\n return {\n reductionBp: line.reductionBp,\n cbsRateBp: cbsBp,\n cbsCents: roundTaxCents(line.taxBaseCents, cbsBp, line.reductionBp),\n ibsUfRateBp: ibsUfBp,\n ibsUfCents: roundTaxCents(line.taxBaseCents, ibsUfBp, line.reductionBp),\n ibsMunRateBp: ibsMunBp,\n ibsMunCents: roundTaxCents(line.taxBaseCents, ibsMunBp, line.reductionBp),\n };\n}\n\n/** The IBS/CBS breakdown of one supply, from the rate tables it is given. */\nexport function computeTax(input: TaxInput): TaxBreakdown {\n const plan = planTax(input);\n return assembleBreakdown(\n plan,\n plan.lines.map((line) => tableFigures(plan, line)),\n input.tables.version,\n );\n}\n","/**\n * The ORACLE mode: the same interface as `computeTax`, with the per-item\n * figures asked of an injected `OfficialCalculator` — the port a host points\n * at the official IBS/CBS calculator (the Receita Federal's Calculadora de\n * Tributos, open source, with an HTTP API and an embeddable component).\n * Everything else — the regime's treatment, the segregated exclusions, each\n * item's base — is the engine's own plan, so running both modes over one\n * fixture set checks exactly the rates, the reductions and the rounding\n * against the official figures.\n *\n * In a tax-inside-price period the base is taken out of the price with the\n * TABLE's rates (the calculator takes a base, not a price), and the\n * calculator's taxes on that base give the net value.\n */\n\nimport { FiscalEngineError } from \"./errors\";\nimport { assembleBreakdown, planTax, zeroFigures } from \"./plan\";\nimport type { LineFigures, TaxBreakdown, TaxClass, TaxInput } from \"./types\";\n\n\n/** One item, as the calculator is asked about it. */\nexport interface OfficialCalculatorItemRequest {\n readonly supplyDate: string;\n readonly destinationIbge: string;\n readonly cClassTrib: string;\n readonly cstIbsCbs: string;\n /** The base after the engine's exclusions (`vBC`). */\n readonly taxBaseCents: number;\n readonly quantity: number;\n}\n\n/** The calculator's answer for one item: nominal rates, the reduction, and the rounded taxes. */\nexport type OfficialCalculatorItemAnswer = LineFigures;\n\n/** The port. The host's adapter owns the transport, the retries and the unit conversion. */\nexport interface OfficialCalculator {\n /** Stamped on the result next to the tables' version. */\n readonly version: string;\n calculateItem(request: OfficialCalculatorItemRequest): Promise<OfficialCalculatorItemAnswer>;\n}\n\nconst ANSWER_FIELDS = [\"reductionBp\", \"cbsRateBp\", \"cbsCents\", \"ibsUfRateBp\", \"ibsUfCents\", \"ibsMunRateBp\", \"ibsMunCents\"] as const;\n\nfunction assertAnswer(answer: OfficialCalculatorItemAnswer, lineId: string): OfficialCalculatorItemAnswer {\n for (const field of ANSWER_FIELDS) {\n const value = answer?.[field];\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n throw new FiscalEngineError(\n \"INVALID_ORACLE_ANSWER\",\n `the calculator answered ${String(value)} for ${field} of line \"${lineId}\" — expected integer cents or basis points`,\n );\n }\n }\n return answer;\n}\n\nfunction requestFor(input: TaxInput, taxClass: TaxClass, taxBaseCents: number, quantity: number): OfficialCalculatorItemRequest {\n return {\n supplyDate: input.supplyDate,\n destinationIbge: input.destinationIbge,\n cClassTrib: taxClass.cClassTrib,\n cstIbsCbs: taxClass.cstIbsCbs,\n taxBaseCents,\n quantity,\n };\n}\n\n/** `computeTax`, with the per-item figures from the official calculator. */\nexport async function computeTaxWithOracle(input: TaxInput, calculator: OfficialCalculator): Promise<TaxBreakdown> {\n const plan = planTax(input);\n const figures: LineFigures[] = [];\n for (const line of plan.lines) {\n if (!line.taxed) {\n figures.push(zeroFigures(line));\n continue;\n }\n const answer = await calculator.calculateItem(requestFor(input, line.taxClass, line.taxBaseCents, line.quantity));\n figures.push(assertAnswer(answer, line.lineId));\n }\n return assembleBreakdown(plan, figures, `${input.tables.version}+oracle:${calculator.version}`);\n}\n","/**\n * Where two breakdowns of the same supply disagree — the table mode against\n * the oracle mode, or a stored snapshot against a recomputation. Versions are\n * not compared: they differ by construction.\n */\n\nimport type { LineTax, TaxBreakdown } from \"./types\";\n\nexport interface BreakdownDisagreement {\n /** `null` for an order-level field. */\n readonly lineId: string | null;\n readonly field: string;\n readonly left: unknown;\n readonly right: unknown;\n}\n\nconst LINE_FIELDS = [\n \"valueCents\",\n \"taxBaseCents\",\n \"reductionBp\",\n \"cbsRateBp\",\n \"cbsCents\",\n \"ibsUfRateBp\",\n \"ibsUfCents\",\n \"ibsMunRateBp\",\n \"ibsMunCents\",\n \"netValueCents\",\n] as const satisfies readonly (keyof LineTax)[];\n\nconst ORDER_FIELDS = [\n \"taxBaseCents\",\n \"cbsCents\",\n \"ibsUfCents\",\n \"ibsMunCents\",\n \"totalTaxCents\",\n \"netValueCents\",\n \"gorjetaExcludedCents\",\n \"intermediationExcludedCents\",\n \"treatment\",\n \"informative\",\n] as const satisfies readonly (keyof TaxBreakdown)[];\n\nfunction lineDisagreements(left: LineTax, right: LineTax | undefined): BreakdownDisagreement[] {\n if (!right) return [{ lineId: left.lineId, field: \"line\", left: left.lineId, right: undefined }];\n return LINE_FIELDS.filter((field) => left[field] !== right[field]).map((field) => ({\n lineId: left.lineId,\n field,\n left: left[field],\n right: right[field],\n }));\n}\n\n/** Every per-line field that differs, by line id; then the order fields that the lines do not already explain. */\nexport function compareBreakdowns(left: TaxBreakdown, right: TaxBreakdown): BreakdownDisagreement[] {\n const rightById = new Map(right.lines.map((line) => [line.lineId, line]));\n const lines = left.lines.flatMap((line) => lineDisagreements(line, rightById.get(line.lineId)));\n const leftIds = new Set(left.lines.map((line) => line.lineId));\n const extra = right.lines\n .filter((line) => !leftIds.has(line.lineId))\n .map((line) => ({ lineId: line.lineId, field: \"line\", left: undefined, right: line.lineId }));\n const order = ORDER_FIELDS.filter((field) => left[field] !== right[field]).map((field) => ({\n lineId: null,\n field,\n left: left[field],\n right: right[field],\n }));\n return [...lines, ...extra, ...order];\n}\n"],"mappings":";;;;;AAmBO,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAnB7C,OAmB6C;AAAA;AAAA;AAAA,EAClC;AAAA,EAET,YAAY,MAA6B,SAAiB;AACxD,UAAM,mBAAmB,IAAI,KAAK,OAAO,EAAE;AAC3C,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;;;ACdA,IAAM,KAAK;AAEX,IAAM,aAAa,KAAK;AAGxB,SAAS,cAAc,WAAmB,aAA6B;AACrE,QAAM,WAAW,YAAY;AAC7B,QAAM,SAAS,YAAY,WAAW,eAAe;AACrD,MAAI,QAAQ,YAAa,QAAO,WAAW;AAC3C,MAAI,QAAQ,YAAa,QAAO;AAChC,SAAO,WAAW,OAAO,KAAK,WAAW,WAAW;A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K,QAAQ,OAAO,QAAQ,MAAM,QAAW,OAAO,KAAK,OAAO,EAAE;AAC9F,QAAM,QAAQ,aAAa,OAAO,CAAC,UAAU,KAAK,KAAK,MAAM,MAAM,KAAK,CAAC,EAAE,IAAI,CAAC,WAAW;AAAA,IACzF,QAAQ;AAAA,IACR;AAAA,IACA,MAAM,KAAK,KAAK;AAAA,IAChB,OAAO,MAAM,KAAK;AAAA,EACpB,EAAE;AACF,SAAO,CAAC,GAAG,OAAO,GAAG,OAAO,GAAG,KAAK;AACtC;AAdgB;","names":[]}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The package's permissions, declared HERE and nowhere else (the owner's
|
|
3
|
+
* decision on FUT-2237): a host composes them into its RBAC catalog and
|
|
4
|
+
* decides which roles hold them. The ids are mechanism; the words a picker
|
|
5
|
+
* shows are the host's, so no `labels` ship.
|
|
6
|
+
*/
|
|
7
|
+
/** See the fiscal settings and the documents issued. */
|
|
8
|
+
declare const FISCAL_READ = "fiscal:read";
|
|
9
|
+
/** Edit the emitter profile and its certificate. */
|
|
10
|
+
declare const FISCAL_MANAGE = "fiscal:manage";
|
|
11
|
+
/** Issue a fiscal document. */
|
|
12
|
+
declare const FISCAL_ISSUE = "fiscal:issue";
|
|
13
|
+
/** Cancel an issued fiscal document. */
|
|
14
|
+
declare const FISCAL_CANCEL = "fiscal:cancel";
|
|
15
|
+
declare const FISCAL_PERMISSIONS: {
|
|
16
|
+
readonly source: "@12-apps/fiscal";
|
|
17
|
+
readonly ids: readonly ["fiscal:read", "fiscal:manage", "fiscal:issue", "fiscal:cancel"];
|
|
18
|
+
readonly permissions: {
|
|
19
|
+
readonly "fiscal:read": {
|
|
20
|
+
readonly kind: "class";
|
|
21
|
+
};
|
|
22
|
+
readonly "fiscal:manage": {
|
|
23
|
+
readonly kind: "class";
|
|
24
|
+
};
|
|
25
|
+
readonly "fiscal:issue": {
|
|
26
|
+
readonly kind: "class";
|
|
27
|
+
};
|
|
28
|
+
readonly "fiscal:cancel": {
|
|
29
|
+
readonly kind: "class";
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* `@12-apps/fiscal/manifest` — the SHARED wiring manifest, a SKELETON.
|
|
36
|
+
*
|
|
37
|
+
* What it declares today is what exists today:
|
|
38
|
+
*
|
|
39
|
+
* - `permissions` — `fiscal:read`, `fiscal:manage`, `fiscal:issue`,
|
|
40
|
+
* `fiscal:cancel`: data, valid with no route or table behind them yet, and
|
|
41
|
+
* declared now so a host composes the catalog once.
|
|
42
|
+
*
|
|
43
|
+
* The first module, `./engine`, is a pure function a host calls; it has
|
|
44
|
+
* nothing to wire. The document module (FUT-2237) adds, in this manifest:
|
|
45
|
+
* `db` (the emitter profile, the fiscal document and its events, a number
|
|
46
|
+
* counter per issuing point and series), `server: ["http", "jobs"]` (profile,
|
|
47
|
+
* certificate upload, issue, cancel, look up; retry, contingency
|
|
48
|
+
* transmission, certificate-expiry warning), `notifications` (certificate
|
|
49
|
+
* expiring, document rejected) and `web: ["surface"]` (the fiscal settings
|
|
50
|
+
* screen and the documents list), with `observability: { namespace: "fiscal" }`
|
|
51
|
+
* once there is running code to log — declaring it now would only make every
|
|
52
|
+
* host bind a logger for a pure function that throws and never logs. Until then `.wiring-conformance.json`
|
|
53
|
+
* answers each of those with its reason.
|
|
54
|
+
*
|
|
55
|
+
* `@12-apps/wiring` is a TYPE-ONLY dependency: the manifest is a plain
|
|
56
|
+
* `satisfies`-checked value, and the producer's assertions run in this
|
|
57
|
+
* package's own test suite.
|
|
58
|
+
*/
|
|
59
|
+
|
|
60
|
+
declare const fiscalManifest: {
|
|
61
|
+
readonly name: "@12-apps/fiscal";
|
|
62
|
+
readonly contract: 1;
|
|
63
|
+
readonly permissions: {
|
|
64
|
+
readonly source: "@12-apps/fiscal";
|
|
65
|
+
readonly ids: readonly ["fiscal:read", "fiscal:manage", "fiscal:issue", "fiscal:cancel"];
|
|
66
|
+
readonly permissions: {
|
|
67
|
+
readonly "fiscal:read": {
|
|
68
|
+
readonly kind: "class";
|
|
69
|
+
};
|
|
70
|
+
readonly "fiscal:manage": {
|
|
71
|
+
readonly kind: "class";
|
|
72
|
+
};
|
|
73
|
+
readonly "fiscal:issue": {
|
|
74
|
+
readonly kind: "class";
|
|
75
|
+
};
|
|
76
|
+
readonly "fiscal:cancel": {
|
|
77
|
+
readonly kind: "class";
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
};
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
export { FISCAL_CANCEL, FISCAL_ISSUE, FISCAL_MANAGE, FISCAL_PERMISSIONS, FISCAL_READ, fiscalManifest };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import "../chunk-7QVYU63E.js";
|
|
2
|
+
|
|
3
|
+
// src/manifest/permissions.ts
|
|
4
|
+
var FISCAL_READ = "fiscal:read";
|
|
5
|
+
var FISCAL_MANAGE = "fiscal:manage";
|
|
6
|
+
var FISCAL_ISSUE = "fiscal:issue";
|
|
7
|
+
var FISCAL_CANCEL = "fiscal:cancel";
|
|
8
|
+
var FISCAL_PERMISSIONS = {
|
|
9
|
+
source: "@12-apps/fiscal",
|
|
10
|
+
ids: [FISCAL_READ, FISCAL_MANAGE, FISCAL_ISSUE, FISCAL_CANCEL],
|
|
11
|
+
permissions: {
|
|
12
|
+
[FISCAL_READ]: { kind: "class" },
|
|
13
|
+
[FISCAL_MANAGE]: { kind: "class" },
|
|
14
|
+
[FISCAL_ISSUE]: { kind: "class" },
|
|
15
|
+
[FISCAL_CANCEL]: { kind: "class" }
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
// src/manifest/index.ts
|
|
20
|
+
var fiscalManifest = {
|
|
21
|
+
name: "@12-apps/fiscal",
|
|
22
|
+
contract: 1,
|
|
23
|
+
permissions: FISCAL_PERMISSIONS
|
|
24
|
+
};
|
|
25
|
+
export {
|
|
26
|
+
FISCAL_CANCEL,
|
|
27
|
+
FISCAL_ISSUE,
|
|
28
|
+
FISCAL_MANAGE,
|
|
29
|
+
FISCAL_PERMISSIONS,
|
|
30
|
+
FISCAL_READ,
|
|
31
|
+
fiscalManifest
|
|
32
|
+
};
|
|
33
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/manifest/permissions.ts","../../src/manifest/index.ts"],"sourcesContent":["/**\n * The package's permissions, declared HERE and nowhere else (the owner's\n * decision on FUT-2237): a host composes them into its RBAC catalog and\n * decides which roles hold them. The ids are mechanism; the words a picker\n * shows are the host's, so no `labels` ship.\n */\n\nimport type { WirePermissionsContribution } from \"@12-apps/wiring\";\n\n/** See the fiscal settings and the documents issued. */\nexport const FISCAL_READ = \"fiscal:read\";\n/** Edit the emitter profile and its certificate. */\nexport const FISCAL_MANAGE = \"fiscal:manage\";\n/** Issue a fiscal document. */\nexport const FISCAL_ISSUE = \"fiscal:issue\";\n/** Cancel an issued fiscal document. */\nexport const FISCAL_CANCEL = \"fiscal:cancel\";\n\nexport const FISCAL_PERMISSIONS = {\n source: \"@12-apps/fiscal\",\n ids: [FISCAL_READ, FISCAL_MANAGE, FISCAL_ISSUE, FISCAL_CANCEL],\n permissions: {\n [FISCAL_READ]: { kind: \"class\" },\n [FISCAL_MANAGE]: { kind: \"class\" },\n [FISCAL_ISSUE]: { kind: \"class\" },\n [FISCAL_CANCEL]: { kind: \"class\" },\n },\n} as const satisfies WirePermissionsContribution;\n","/**\n * `@12-apps/fiscal/manifest` — the SHARED wiring manifest, a SKELETON.\n *\n * What it declares today is what exists today:\n *\n * - `permissions` — `fiscal:read`, `fiscal:manage`, `fiscal:issue`,\n * `fiscal:cancel`: data, valid with no route or table behind them yet, and\n * declared now so a host composes the catalog once.\n *\n * The first module, `./engine`, is a pure function a host calls; it has\n * nothing to wire. The document module (FUT-2237) adds, in this manifest:\n * `db` (the emitter profile, the fiscal document and its events, a number\n * counter per issuing point and series), `server: [\"http\", \"jobs\"]` (profile,\n * certificate upload, issue, cancel, look up; retry, contingency\n * transmission, certificate-expiry warning), `notifications` (certificate\n * expiring, document rejected) and `web: [\"surface\"]` (the fiscal settings\n * screen and the documents list), with `observability: { namespace: \"fiscal\" }`\n * once there is running code to log — declaring it now would only make every\n * host bind a logger for a pure function that throws and never logs. Until then `.wiring-conformance.json`\n * answers each of those with its reason.\n *\n * `@12-apps/wiring` is a TYPE-ONLY dependency: the manifest is a plain\n * `satisfies`-checked value, and the producer's assertions run in this\n * package's own test suite.\n */\n\nimport type { PackageManifest } from \"@12-apps/wiring\";\n\nimport { FISCAL_PERMISSIONS } from \"./permissions\";\n\nexport { FISCAL_CANCEL, FISCAL_ISSUE, FISCAL_MANAGE, FISCAL_PERMISSIONS, FISCAL_READ } from \"./permissions\";\n\nexport const fiscalManifest = {\n name: \"@12-apps/fiscal\",\n contract: 1,\n permissions: FISCAL_PERMISSIONS,\n} as const satisfies PackageManifest;\n"],"mappings":";;;AAUO,IAAM,cAAc;AAEpB,IAAM,gBAAgB;AAEtB,IAAM,eAAe;AAErB,IAAM,gBAAgB;AAEtB,IAAM,qBAAqB;AAAA,EAChC,QAAQ;AAAA,EACR,KAAK,CAAC,aAAa,eAAe,cAAc,aAAa;AAAA,EAC7D,aAAa;AAAA,IACX,CAAC,WAAW,GAAG,EAAE,MAAM,QAAQ;AAAA,IAC/B,CAAC,aAAa,GAAG,EAAE,MAAM,QAAQ;AAAA,IACjC,CAAC,YAAY,GAAG,EAAE,MAAM,QAAQ;AAAA,IAChC,CAAC,aAAa,GAAG,EAAE,MAAM,QAAQ;AAAA,EACnC;AACF;;;ACKO,IAAM,iBAAiB;AAAA,EAC5B,MAAM;AAAA,EACN,UAAU;AAAA,EACV,aAAa;AACf;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,70 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@12-apps/fiscal",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"sideEffects": false,
|
|
6
|
+
"description": "Brazilian consumption-tax machinery for any host that sells. Its first module is the IBS/CBS engine (./engine): a pure function from priced lines, the seller's regime, the destination, the exclusions, a versioned rate table and the date of the supply to a per-line and per-order breakdown, with the NF-e layout's per-item rounding and an injected official-calculator port for running it as an oracle. Rate tables are versioned data (./tables/*). Implements @12-apps/wiring (./manifest).",
|
|
7
|
+
"exports": {
|
|
8
|
+
"./engine": {
|
|
9
|
+
"types": "./dist/engine/index.d.ts",
|
|
10
|
+
"default": "./dist/engine/index.js"
|
|
11
|
+
},
|
|
12
|
+
"./manifest": {
|
|
13
|
+
"types": "./dist/manifest/index.d.ts",
|
|
14
|
+
"default": "./dist/manifest/index.js"
|
|
15
|
+
},
|
|
16
|
+
"./tables/*": "./tables/*",
|
|
17
|
+
"./package.json": "./package.json"
|
|
18
|
+
},
|
|
19
|
+
"scripts": {
|
|
20
|
+
"build": "rm -rf dist && tsup",
|
|
21
|
+
"clean": "rm -rf node_modules coverage dist",
|
|
22
|
+
"test": "node ../../scripts/vitest-with-teardown.mjs run",
|
|
23
|
+
"test:watch": "vitest watch",
|
|
24
|
+
"lint": "eslint src --max-warnings 0",
|
|
25
|
+
"check-types": "tsc --noEmit",
|
|
26
|
+
"typecheck": "tsc --noEmit"
|
|
27
|
+
},
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"@12-apps/wiring": ">=1.0.0"
|
|
30
|
+
},
|
|
31
|
+
"peerDependenciesMeta": {
|
|
32
|
+
"@12-apps/wiring": {
|
|
33
|
+
"optional": true
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@12-apps/eslint-config": "^1.22.0",
|
|
38
|
+
"@12-apps/typescript-config": "^1.21.0",
|
|
39
|
+
"@12-apps/wiring": "^1.17.0",
|
|
40
|
+
"@types/node": "^22.10.6",
|
|
41
|
+
"eslint": "^9.39.1",
|
|
42
|
+
"eslint-plugin-test-flakiness": "^1.4.0",
|
|
43
|
+
"tsup": "^8.0.0",
|
|
44
|
+
"typescript": "^5.9.2",
|
|
45
|
+
"vitest": "^3.2.4"
|
|
46
|
+
},
|
|
47
|
+
"engines": {
|
|
48
|
+
"node": ">=22.0.0"
|
|
49
|
+
},
|
|
50
|
+
"license": "MIT",
|
|
51
|
+
"publishConfig": {
|
|
52
|
+
"registry": "https://registry.npmjs.org",
|
|
53
|
+
"access": "public"
|
|
54
|
+
},
|
|
55
|
+
"repository": {
|
|
56
|
+
"type": "git",
|
|
57
|
+
"url": "git+https://github.com/12-apps/shared-packages.git",
|
|
58
|
+
"directory": "packages/fiscal"
|
|
59
|
+
},
|
|
60
|
+
"files": [
|
|
61
|
+
"src",
|
|
62
|
+
"dist",
|
|
63
|
+
"tables",
|
|
64
|
+
"*.md",
|
|
65
|
+
"!eslint.config.js",
|
|
66
|
+
"!tsup.config.ts",
|
|
67
|
+
"!**/__tests__/**",
|
|
68
|
+
"!**/*.test.*"
|
|
69
|
+
]
|
|
70
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where two breakdowns of the same supply disagree — the table mode against
|
|
3
|
+
* the oracle mode, or a stored snapshot against a recomputation. Versions are
|
|
4
|
+
* not compared: they differ by construction.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { LineTax, TaxBreakdown } from "./types";
|
|
8
|
+
|
|
9
|
+
export interface BreakdownDisagreement {
|
|
10
|
+
/** `null` for an order-level field. */
|
|
11
|
+
readonly lineId: string | null;
|
|
12
|
+
readonly field: string;
|
|
13
|
+
readonly left: unknown;
|
|
14
|
+
readonly right: unknown;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const LINE_FIELDS = [
|
|
18
|
+
"valueCents",
|
|
19
|
+
"taxBaseCents",
|
|
20
|
+
"reductionBp",
|
|
21
|
+
"cbsRateBp",
|
|
22
|
+
"cbsCents",
|
|
23
|
+
"ibsUfRateBp",
|
|
24
|
+
"ibsUfCents",
|
|
25
|
+
"ibsMunRateBp",
|
|
26
|
+
"ibsMunCents",
|
|
27
|
+
"netValueCents",
|
|
28
|
+
] as const satisfies readonly (keyof LineTax)[];
|
|
29
|
+
|
|
30
|
+
const ORDER_FIELDS = [
|
|
31
|
+
"taxBaseCents",
|
|
32
|
+
"cbsCents",
|
|
33
|
+
"ibsUfCents",
|
|
34
|
+
"ibsMunCents",
|
|
35
|
+
"totalTaxCents",
|
|
36
|
+
"netValueCents",
|
|
37
|
+
"gorjetaExcludedCents",
|
|
38
|
+
"intermediationExcludedCents",
|
|
39
|
+
"treatment",
|
|
40
|
+
"informative",
|
|
41
|
+
] as const satisfies readonly (keyof TaxBreakdown)[];
|
|
42
|
+
|
|
43
|
+
function lineDisagreements(left: LineTax, right: LineTax | undefined): BreakdownDisagreement[] {
|
|
44
|
+
if (!right) return [{ lineId: left.lineId, field: "line", left: left.lineId, right: undefined }];
|
|
45
|
+
return LINE_FIELDS.filter((field) => left[field] !== right[field]).map((field) => ({
|
|
46
|
+
lineId: left.lineId,
|
|
47
|
+
field,
|
|
48
|
+
left: left[field],
|
|
49
|
+
right: right[field],
|
|
50
|
+
}));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Every per-line field that differs, by line id; then the order fields that the lines do not already explain. */
|
|
54
|
+
export function compareBreakdowns(left: TaxBreakdown, right: TaxBreakdown): BreakdownDisagreement[] {
|
|
55
|
+
const rightById = new Map(right.lines.map((line) => [line.lineId, line]));
|
|
56
|
+
const lines = left.lines.flatMap((line) => lineDisagreements(line, rightById.get(line.lineId)));
|
|
57
|
+
const leftIds = new Set(left.lines.map((line) => line.lineId));
|
|
58
|
+
const extra = right.lines
|
|
59
|
+
.filter((line) => !leftIds.has(line.lineId))
|
|
60
|
+
.map((line) => ({ lineId: line.lineId, field: "line", left: undefined, right: line.lineId }));
|
|
61
|
+
const order = ORDER_FIELDS.filter((field) => left[field] !== right[field]).map((field) => ({
|
|
62
|
+
lineId: null,
|
|
63
|
+
field,
|
|
64
|
+
left: left[field],
|
|
65
|
+
right: right[field],
|
|
66
|
+
}));
|
|
67
|
+
return [...lines, ...extra, ...order];
|
|
68
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `computeTax` — the table mode. Pure: no I/O, no clock, no defaults. The
|
|
3
|
+
* same input gives the same breakdown, stamped with the table's version, so a
|
|
4
|
+
* supply settled in March reproduces its own tax in December after the tables
|
|
5
|
+
* moved.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { assembleBreakdown, planTax, zeroFigures } from "./plan";
|
|
9
|
+
import type { PlannedLine, TaxPlan } from "./plan";
|
|
10
|
+
import { roundTaxCents } from "./rounding";
|
|
11
|
+
import type { LineFigures, TaxBreakdown, TaxInput } from "./types";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Each tax rounded on the item's base. In a tax-inside-price period the base
|
|
15
|
+
* is the one the plan took out of the price, and these are the very taxes it
|
|
16
|
+
* was taken out with.
|
|
17
|
+
*/
|
|
18
|
+
function tableFigures(plan: TaxPlan, line: PlannedLine): LineFigures {
|
|
19
|
+
if (!line.taxed) return zeroFigures(line);
|
|
20
|
+
const { cbsBp, ibsUfBp, ibsMunBp } = plan.rates;
|
|
21
|
+
return {
|
|
22
|
+
reductionBp: line.reductionBp,
|
|
23
|
+
cbsRateBp: cbsBp,
|
|
24
|
+
cbsCents: roundTaxCents(line.taxBaseCents, cbsBp, line.reductionBp),
|
|
25
|
+
ibsUfRateBp: ibsUfBp,
|
|
26
|
+
ibsUfCents: roundTaxCents(line.taxBaseCents, ibsUfBp, line.reductionBp),
|
|
27
|
+
ibsMunRateBp: ibsMunBp,
|
|
28
|
+
ibsMunCents: roundTaxCents(line.taxBaseCents, ibsMunBp, line.reductionBp),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The IBS/CBS breakdown of one supply, from the rate tables it is given. */
|
|
33
|
+
export function computeTax(input: TaxInput): TaxBreakdown {
|
|
34
|
+
const plan = planTax(input);
|
|
35
|
+
return assembleBreakdown(
|
|
36
|
+
plan,
|
|
37
|
+
plan.lines.map((line) => tableFigures(plan, line)),
|
|
38
|
+
input.tables.version,
|
|
39
|
+
);
|
|
40
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every refusal the engine makes. A refusal is a THROW, on purpose: the
|
|
3
|
+
* engine has no fallback for an input it cannot read, and a figure computed
|
|
4
|
+
* from a guess would be printed on a fiscal document as a confession of the
|
|
5
|
+
* tax due (LC 214/2025 art. 60 §1).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export type FiscalEngineErrorCode =
|
|
9
|
+
/** A field is missing, out of range or of the wrong shape. */
|
|
10
|
+
| "INVALID_INPUT"
|
|
11
|
+
/** The rate table is malformed: a bad rate, a bad date, overlapping periods. */
|
|
12
|
+
| "INVALID_TABLES"
|
|
13
|
+
/** No period of the table covers the date of the supply. */
|
|
14
|
+
| "NO_RATE_PERIOD"
|
|
15
|
+
/** The supply precedes the seller's `regimeEffectiveFrom`. */
|
|
16
|
+
| "REGIME_NOT_IN_EFFECT"
|
|
17
|
+
/** The official calculator answered something that is not integer cents and basis points. */
|
|
18
|
+
| "INVALID_ORACLE_ANSWER";
|
|
19
|
+
|
|
20
|
+
export class FiscalEngineError extends Error {
|
|
21
|
+
readonly code: FiscalEngineErrorCode;
|
|
22
|
+
|
|
23
|
+
constructor(code: FiscalEngineErrorCode, message: string) {
|
|
24
|
+
super(`[fiscal/engine] ${code}: ${message}`);
|
|
25
|
+
this.name = "FiscalEngineError";
|
|
26
|
+
this.code = code;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/fiscal/engine` — the IBS/CBS engine.
|
|
3
|
+
*
|
|
4
|
+
* Pure TypeScript: no I/O, no clock, no defaults. A host hands it the priced
|
|
5
|
+
* lines, the seller's regime, the destination, the exclusions, a versioned
|
|
6
|
+
* rate table (`@12-apps/fiscal/tables/*.json`, or its own) and the date of the
|
|
7
|
+
* supply, and gets the per-line and per-order breakdown back.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export { computeTax } from "./compute";
|
|
11
|
+
export { ratesAt } from "./plan";
|
|
12
|
+
export { computeTaxWithOracle } from "./oracle";
|
|
13
|
+
export type { OfficialCalculator, OfficialCalculatorItemAnswer, OfficialCalculatorItemRequest } from "./oracle";
|
|
14
|
+
export { compareBreakdowns } from "./compare";
|
|
15
|
+
export type { BreakdownDisagreement } from "./compare";
|
|
16
|
+
export { FiscalEngineError } from "./errors";
|
|
17
|
+
export type { FiscalEngineErrorCode } from "./errors";
|
|
18
|
+
export { roundTaxCents } from "./rounding";
|
|
19
|
+
export { assertRateTables } from "./validate";
|
|
20
|
+
export type * from "./types";
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ORACLE mode: the same interface as `computeTax`, with the per-item
|
|
3
|
+
* figures asked of an injected `OfficialCalculator` — the port a host points
|
|
4
|
+
* at the official IBS/CBS calculator (the Receita Federal's Calculadora de
|
|
5
|
+
* Tributos, open source, with an HTTP API and an embeddable component).
|
|
6
|
+
* Everything else — the regime's treatment, the segregated exclusions, each
|
|
7
|
+
* item's base — is the engine's own plan, so running both modes over one
|
|
8
|
+
* fixture set checks exactly the rates, the reductions and the rounding
|
|
9
|
+
* against the official figures.
|
|
10
|
+
*
|
|
11
|
+
* In a tax-inside-price period the base is taken out of the price with the
|
|
12
|
+
* TABLE's rates (the calculator takes a base, not a price), and the
|
|
13
|
+
* calculator's taxes on that base give the net value.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { FiscalEngineError } from "./errors";
|
|
17
|
+
import { assembleBreakdown, planTax, zeroFigures } from "./plan";
|
|
18
|
+
import type { LineFigures, TaxBreakdown, TaxClass, TaxInput } from "./types";
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
/** One item, as the calculator is asked about it. */
|
|
22
|
+
export interface OfficialCalculatorItemRequest {
|
|
23
|
+
readonly supplyDate: string;
|
|
24
|
+
readonly destinationIbge: string;
|
|
25
|
+
readonly cClassTrib: string;
|
|
26
|
+
readonly cstIbsCbs: string;
|
|
27
|
+
/** The base after the engine's exclusions (`vBC`). */
|
|
28
|
+
readonly taxBaseCents: number;
|
|
29
|
+
readonly quantity: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The calculator's answer for one item: nominal rates, the reduction, and the rounded taxes. */
|
|
33
|
+
export type OfficialCalculatorItemAnswer = LineFigures;
|
|
34
|
+
|
|
35
|
+
/** The port. The host's adapter owns the transport, the retries and the unit conversion. */
|
|
36
|
+
export interface OfficialCalculator {
|
|
37
|
+
/** Stamped on the result next to the tables' version. */
|
|
38
|
+
readonly version: string;
|
|
39
|
+
calculateItem(request: OfficialCalculatorItemRequest): Promise<OfficialCalculatorItemAnswer>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const ANSWER_FIELDS = ["reductionBp", "cbsRateBp", "cbsCents", "ibsUfRateBp", "ibsUfCents", "ibsMunRateBp", "ibsMunCents"] as const;
|
|
43
|
+
|
|
44
|
+
function assertAnswer(answer: OfficialCalculatorItemAnswer, lineId: string): OfficialCalculatorItemAnswer {
|
|
45
|
+
for (const field of ANSWER_FIELDS) {
|
|
46
|
+
const value = answer?.[field];
|
|
47
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
|
|
48
|
+
throw new FiscalEngineError(
|
|
49
|
+
"INVALID_ORACLE_ANSWER",
|
|
50
|
+
`the calculator answered ${String(value)} for ${field} of line "${lineId}" — expected integer cents or basis points`,
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return answer;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function requestFor(input: TaxInput, taxClass: TaxClass, taxBaseCents: number, quantity: number): OfficialCalculatorItemRequest {
|
|
58
|
+
return {
|
|
59
|
+
supplyDate: input.supplyDate,
|
|
60
|
+
destinationIbge: input.destinationIbge,
|
|
61
|
+
cClassTrib: taxClass.cClassTrib,
|
|
62
|
+
cstIbsCbs: taxClass.cstIbsCbs,
|
|
63
|
+
taxBaseCents,
|
|
64
|
+
quantity,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** `computeTax`, with the per-item figures from the official calculator. */
|
|
69
|
+
export async function computeTaxWithOracle(input: TaxInput, calculator: OfficialCalculator): Promise<TaxBreakdown> {
|
|
70
|
+
const plan = planTax(input);
|
|
71
|
+
const figures: LineFigures[] = [];
|
|
72
|
+
for (const line of plan.lines) {
|
|
73
|
+
if (!line.taxed) {
|
|
74
|
+
figures.push(zeroFigures(line));
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const answer = await calculator.calculateItem(requestFor(input, line.taxClass, line.taxBaseCents, line.quantity));
|
|
78
|
+
figures.push(assertAnswer(answer, line.lineId));
|
|
79
|
+
}
|
|
80
|
+
return assembleBreakdown(plan, figures, `${input.tables.version}+oracle:${calculator.version}`);
|
|
81
|
+
}
|