@12-apps/fiscal 0.0.0-stage → 1.1.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.
Files changed (155) hide show
  1. package/README.md +269 -2
  2. package/dist/chunk-27B4HNO6.js +574 -0
  3. package/dist/chunk-27B4HNO6.js.map +1 -0
  4. package/dist/chunk-3SDXLSG4.js +24 -0
  5. package/dist/chunk-3SDXLSG4.js.map +1 -0
  6. package/dist/chunk-7QVYU63E.js +7 -0
  7. package/dist/chunk-7QVYU63E.js.map +1 -0
  8. package/dist/chunk-ALABGVPO.js +247 -0
  9. package/dist/chunk-ALABGVPO.js.map +1 -0
  10. package/dist/chunk-FOFIN5M7.js +14 -0
  11. package/dist/chunk-FOFIN5M7.js.map +1 -0
  12. package/dist/chunk-HQ2NXSTX.js +85 -0
  13. package/dist/chunk-HQ2NXSTX.js.map +1 -0
  14. package/dist/chunk-PNTKG3DZ.js +47 -0
  15. package/dist/chunk-PNTKG3DZ.js.map +1 -0
  16. package/dist/chunk-RRFKYVLZ.js +192 -0
  17. package/dist/chunk-RRFKYVLZ.js.map +1 -0
  18. package/dist/chunk-V5ZQAAJT.js +210 -0
  19. package/dist/chunk-V5ZQAAJT.js.map +1 -0
  20. package/dist/chunk-X6MRDUYH.js +21 -0
  21. package/dist/chunk-X6MRDUYH.js.map +1 -0
  22. package/dist/chunk-XQGW5HUG.js +30 -0
  23. package/dist/chunk-XQGW5HUG.js.map +1 -0
  24. package/dist/context-ChnWR4Kb.d.ts +455 -0
  25. package/dist/danfe/en-US.d.ts +12 -0
  26. package/dist/danfe/en-US.js +51 -0
  27. package/dist/danfe/en-US.js.map +1 -0
  28. package/dist/danfe/index.d.ts +50 -0
  29. package/dist/danfe/index.js +18 -0
  30. package/dist/danfe/index.js.map +1 -0
  31. package/dist/danfe/pt-BR.d.ts +11 -0
  32. package/dist/danfe/pt-BR.js +51 -0
  33. package/dist/danfe/pt-BR.js.map +1 -0
  34. package/dist/documents/index.d.ts +169 -0
  35. package/dist/documents/index.js +1228 -0
  36. package/dist/documents/index.js.map +1 -0
  37. package/dist/engine/index.d.ts +118 -0
  38. package/dist/engine/index.js +591 -0
  39. package/dist/engine/index.js.map +1 -0
  40. package/dist/http.d.ts +73 -0
  41. package/dist/http.js +16 -0
  42. package/dist/http.js.map +1 -0
  43. package/dist/issuer/index.d.ts +43 -0
  44. package/dist/issuer/index.js +131 -0
  45. package/dist/issuer/index.js.map +1 -0
  46. package/dist/jobs.d.ts +74 -0
  47. package/dist/jobs.js +22 -0
  48. package/dist/jobs.js.map +1 -0
  49. package/dist/labels-BNvflT0h.d.ts +44 -0
  50. package/dist/manifest/index.d.ts +97 -0
  51. package/dist/manifest/index.js +27 -0
  52. package/dist/manifest/index.js.map +1 -0
  53. package/dist/manifest/server.d.ts +57 -0
  54. package/dist/manifest/server.js +25 -0
  55. package/dist/manifest/server.js.map +1 -0
  56. package/dist/notifications.d.ts +93 -0
  57. package/dist/notifications.js +41 -0
  58. package/dist/notifications.js.map +1 -0
  59. package/dist/port-DpRFK56U.d.ts +238 -0
  60. package/dist/sale/index.d.ts +243 -0
  61. package/dist/sale/index.js +1 -0
  62. package/dist/sale/index.js.map +1 -0
  63. package/dist/service-KTjH7AxW.d.ts +139 -0
  64. package/dist/sidecar/index.d.ts +216 -0
  65. package/dist/sidecar/index.js +8 -0
  66. package/dist/sidecar/index.js.map +1 -0
  67. package/dist/types-B1b8LIWX.d.ts +247 -0
  68. package/package.json +126 -4
  69. package/prisma/fiscal.prisma +158 -0
  70. package/prisma/migrations/20261113220000_fiscal_documents/migration.sql +201 -0
  71. package/sidecar/.dockerignore +5 -0
  72. package/sidecar/Dockerfile +68 -0
  73. package/sidecar/README.md +149 -0
  74. package/sidecar/composer.json +30 -0
  75. package/sidecar/composer.lock +2224 -0
  76. package/sidecar/docker/apache.conf +14 -0
  77. package/sidecar/docker/icp-brasil.pem +8031 -0
  78. package/sidecar/docker/mpm.conf +17 -0
  79. package/sidecar/docker/openssl.cnf +16 -0
  80. package/sidecar/docker/php.ini +19 -0
  81. package/sidecar/public/index.php +15 -0
  82. package/sidecar/schema/sale-for-document.schema.json +401 -0
  83. package/sidecar/src/ErrorClass.php +31 -0
  84. package/sidecar/src/Http/Request.php +48 -0
  85. package/sidecar/src/Http/Response.php +32 -0
  86. package/sidecar/src/Http/Router.php +59 -0
  87. package/sidecar/src/Kernel.php +99 -0
  88. package/sidecar/src/Module.php +31 -0
  89. package/sidecar/src/Nfe/Classifier.php +89 -0
  90. package/sidecar/src/Nfe/Credentials.php +52 -0
  91. package/sidecar/src/Nfe/DocumentMapper.php +383 -0
  92. package/sidecar/src/Nfe/DocumentSchema.php +39 -0
  93. package/sidecar/src/Nfe/Input.php +125 -0
  94. package/sidecar/src/Nfe/Model.php +17 -0
  95. package/sidecar/src/Nfe/NfeModule.php +62 -0
  96. package/sidecar/src/Nfe/NfeService.php +504 -0
  97. package/sidecar/src/Nfe/Sefaz.php +49 -0
  98. package/sidecar/src/Nfe/SefazReply.php +81 -0
  99. package/sidecar/src/Nfe/Transport/CurlTransport.php +198 -0
  100. package/sidecar/src/Nfe/Transport/SoapAdapter.php +57 -0
  101. package/sidecar/src/Nfe/Transport/Transport.php +20 -0
  102. package/sidecar/src/Nfe/Transport/TransportFailure.php +42 -0
  103. package/sidecar/src/RequestLog.php +54 -0
  104. package/sidecar/src/ServiceError.php +69 -0
  105. package/src/danfe/en-US.ts +53 -0
  106. package/src/danfe/index.ts +11 -0
  107. package/src/danfe/labels.ts +49 -0
  108. package/src/danfe/pt-BR.ts +52 -0
  109. package/src/danfe/render.ts +265 -0
  110. package/src/danfe/xml.ts +45 -0
  111. package/src/documents/context.ts +260 -0
  112. package/src/documents/errors.ts +41 -0
  113. package/src/documents/helpers.ts +128 -0
  114. package/src/documents/index.ts +39 -0
  115. package/src/documents/lines.ts +63 -0
  116. package/src/documents/machine-steps.ts +260 -0
  117. package/src/documents/machine.ts +128 -0
  118. package/src/documents/memory.ts +138 -0
  119. package/src/documents/nfe-proc.ts +51 -0
  120. package/src/documents/ports.ts +130 -0
  121. package/src/documents/profile-input.ts +168 -0
  122. package/src/documents/profile.ts +98 -0
  123. package/src/documents/service-profile.ts +104 -0
  124. package/src/documents/service.ts +296 -0
  125. package/src/documents/settle.ts +121 -0
  126. package/src/documents/signing.ts +61 -0
  127. package/src/documents/sql-rows.ts +180 -0
  128. package/src/documents/sql-store.ts +242 -0
  129. package/src/documents/sql.ts +18 -0
  130. package/src/documents/steps.ts +173 -0
  131. package/src/documents/tests/integration/pglite.ts +73 -0
  132. package/src/documents/types.ts +193 -0
  133. package/src/engine/compare.ts +68 -0
  134. package/src/engine/compute.ts +40 -0
  135. package/src/engine/errors.ts +28 -0
  136. package/src/engine/index.ts +20 -0
  137. package/src/engine/oracle.ts +81 -0
  138. package/src/engine/plan.ts +268 -0
  139. package/src/engine/rounding.ts +81 -0
  140. package/src/engine/types.ts +270 -0
  141. package/src/engine/validate.ts +222 -0
  142. package/src/http.ts +264 -0
  143. package/src/issuer/index.ts +9 -0
  144. package/src/issuer/port.ts +109 -0
  145. package/src/issuer/sidecar.ts +171 -0
  146. package/src/jobs.ts +115 -0
  147. package/src/manifest/index.ts +46 -0
  148. package/src/manifest/permissions.ts +28 -0
  149. package/src/manifest/server.ts +20 -0
  150. package/src/notifications.ts +120 -0
  151. package/src/sale/index.ts +8 -0
  152. package/src/sale/types.ts +292 -0
  153. package/src/sidecar/index.ts +9 -0
  154. package/src/sidecar/types.ts +243 -0
  155. package/tables/ibs-cbs-2026-11-13.json +156 -0
@@ -0,0 +1,73 @@
1
+ import { readFileSync, readdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ import { PGlite } from "@electric-sql/pglite";
5
+
6
+ import type { FiscalPrismaClient, FiscalSqlClient } from "../../sql-store";
7
+
8
+ /**
9
+ * A real (WASM) Postgres with the package's migrations applied, and the two
10
+ * raw-SQL methods plus `$transaction` a Prisma client offers, over it — so the
11
+ * package's own store runs here exactly as it runs on a host's client.
12
+ */
13
+
14
+ const MIGRATIONS = join(import.meta.dirname, "../../../../prisma/migrations");
15
+
16
+ async function migrate(): Promise<PGlite> {
17
+ const db = new PGlite();
18
+ for (const dir of readdirSync(MIGRATIONS).filter((name) => /^\d/.test(name)).sort()) {
19
+ await db.exec(readFileSync(join(MIGRATIONS, dir, "migration.sql"), "utf8"));
20
+ }
21
+ return db;
22
+ }
23
+
24
+ /** One migrated database per test file: starting and migrating a PGlite costs about a second each time. */
25
+ let shared: Promise<PGlite> | undefined;
26
+
27
+ /**
28
+ * Starts and migrates the file's database once. Call it from a `beforeAll` so
29
+ * the migration is paid under the hook's own timeout, never inside the first
30
+ * case's.
31
+ */
32
+ export async function warmDatabase(): Promise<void> {
33
+ shared ??= migrate();
34
+ await shared;
35
+ }
36
+
37
+ /**
38
+ * The file's migrated database, emptied: every table truncated and every
39
+ * sequence restarted, so each case starts from what a fresh migration leaves
40
+ * (the migrations insert no rows). `close()` on the handle is a no-op; the
41
+ * database lives as long as the file's worker.
42
+ */
43
+ export async function migratedDatabase(): Promise<PGlite> {
44
+ shared ??= migrate();
45
+ const db = await shared;
46
+ const { rows } = await db.query<{ name: string }>("SELECT tablename AS name FROM pg_tables WHERE schemaname = 'public'");
47
+ if (rows.length > 0) {
48
+ await db.exec(`TRUNCATE ${rows.map(({ name }) => `"${name}"`).join(", ")} RESTART IDENTITY CASCADE`);
49
+ }
50
+ return new Proxy(db, {
51
+ get(target, property) {
52
+ if (property === "close") return async () => {};
53
+ const value: unknown = Reflect.get(target, property, target);
54
+ return typeof value === "function" ? value.bind(target) : value;
55
+ },
56
+ });
57
+ }
58
+
59
+ type Queryable = Pick<PGlite, "query">;
60
+
61
+ function sqlClient(target: Queryable): FiscalSqlClient {
62
+ return {
63
+ $queryRawUnsafe: async <T>(query: string, ...values: unknown[]) => (await target.query(query, values)).rows as T,
64
+ $executeRawUnsafe: async (query: string, ...values: unknown[]) => (await target.query(query, values)).affectedRows ?? 0,
65
+ };
66
+ }
67
+
68
+ export function prismaOver(db: PGlite): FiscalPrismaClient {
69
+ return {
70
+ ...sqlClient(db),
71
+ $transaction: (run) => db.transaction((tx) => run(sqlClient(tx))),
72
+ };
73
+ }
@@ -0,0 +1,193 @@
1
+ /**
2
+ * The fiscal document record and its event log — the shape the package's
3
+ * Prisma partial stores (`prisma/fiscal.prisma`, `FiscalDocument` and
4
+ * `FiscalDocumentEvent`) and the state machine (`./machine`) transitions.
5
+ *
6
+ * A document is ONE number: one issuing point, one series, one `nNF`. A sale
7
+ * that goes offline is a second document on the issuing point's contingency
8
+ * series, and the first one is `REPLACED` (see `./machine`). The record is
9
+ * keyed by an opaque `subjectId`: what the subject is (an order, a payment,
10
+ * several orders) is the host's to know, never this package's.
11
+ */
12
+
13
+ import type { SaleForDocument } from "../sale/types";
14
+ import type { SefazEnvironment, SidecarErrorClass } from "../sidecar/types";
15
+
16
+ /** The document model: NF-e (55) or NFC-e (65). NFS-e is not a model of this package yet (FUT-2242). */
17
+ export type FiscalDocumentModel = "NFE" | "NFCE";
18
+
19
+ export const FISCAL_DOCUMENT_MODELS: readonly FiscalDocumentModel[] = ["NFE", "NFCE"];
20
+
21
+ /**
22
+ * - `PENDING`: numbered and stored, not yet handed to the issuer.
23
+ * - `SUBMITTED`: handed to the issuer; no final answer yet (a retry is owed).
24
+ * - `AUTHORIZED`: SEFAZ authorised it. The only state a cancel leaves.
25
+ * - `REJECTED`: refused (SEFAZ's `cStat`, or a request the service refuses as
26
+ * malformed). Final; its number was not spent at SEFAZ and is inutilized.
27
+ * - `DENIED`: a denial of use. Final; the number IS spent.
28
+ * - `CONTINGENCY`: signed offline (`tpEmis = 9`), owed a transmission.
29
+ * - `CANCELLED`: an authorised document cancelled at SEFAZ.
30
+ * - `REPLACED`: its sale moved to another document (the contingency one);
31
+ * its number is settled apart (`numberVoid`).
32
+ */
33
+ export type FiscalDocumentStatus =
34
+ | "PENDING"
35
+ | "SUBMITTED"
36
+ | "AUTHORIZED"
37
+ | "REJECTED"
38
+ | "DENIED"
39
+ | "CONTINGENCY"
40
+ | "CANCELLED"
41
+ | "REPLACED";
42
+
43
+ export const FISCAL_DOCUMENT_STATUSES: readonly FiscalDocumentStatus[] = [
44
+ "PENDING",
45
+ "SUBMITTED",
46
+ "AUTHORIZED",
47
+ "REJECTED",
48
+ "DENIED",
49
+ "CONTINGENCY",
50
+ "CANCELLED",
51
+ "REPLACED",
52
+ ];
53
+
54
+ /** Which of the issuing point's series the number came from. */
55
+ export type SeriesKind = "ONLINE" | "CONTINGENCY";
56
+
57
+ /**
58
+ * What is still owed on a number SEFAZ never used, so the sequence has no
59
+ * unexplained gap:
60
+ *
61
+ * - `null`: nothing — the number is a document (authorised, denied, owed a
62
+ * transmission) or still in flight.
63
+ * - `LOOKUP_FIRST`: a request went out with no answer before the sale moved
64
+ * to contingency; look the key up before deciding.
65
+ * - `INUTILIZE`: never used at SEFAZ; inutilize it.
66
+ * - `CANCEL`: the lookup found it authorised after all; cancel it.
67
+ * - `INUTILIZED` / `CANCELLED`: settled.
68
+ * - `DENIED`: settled — the lookup found the number denied, which spends it.
69
+ */
70
+ export type NumberVoid = "LOOKUP_FIRST" | "INUTILIZE" | "CANCEL" | "INUTILIZED" | "CANCELLED" | "DENIED";
71
+
72
+ /** The `numberVoid` values that still owe the sweep a call. */
73
+ export const OWED_VOIDS: readonly NumberVoid[] = ["LOOKUP_FIRST", "INUTILIZE", "CANCEL"];
74
+
75
+ /** The order figures a document carries, in integer cents. */
76
+ export interface DocumentTotals {
77
+ /** What the buyer pays: Σ line values − Σ discounts. */
78
+ readonly totalCents: number;
79
+ readonly discountCents: number;
80
+ readonly cbsCents: number;
81
+ readonly ibsUfCents: number;
82
+ readonly ibsMunCents: number;
83
+ }
84
+
85
+ /**
86
+ * Whether the document is the one its subject stands on. At most one live
87
+ * document per (owner, subject, model): a REPLACED one is not, nor an online
88
+ * one SEFAZ rejected (its number is voided and the sale is issued again) —
89
+ * unless a lookup had found it authorised (its protocol is kept). A
90
+ * REJECTED contingency NFC-e stays live: the buyer holds its DANFE, and the
91
+ * store corrects and resends it under the same number.
92
+ */
93
+ export function isLive(document: Pick<FiscalDocument, "status" | "seriesKind" | "protocol">): boolean {
94
+ if (document.status === "REPLACED") return false;
95
+ // An online rejection with a protocol known (a lookup found it SEFAZ's) is still the sale's.
96
+ return !(document.status === "REJECTED" && document.seriesKind === "ONLINE" && document.protocol === null);
97
+ }
98
+
99
+ /** One fiscal document. */
100
+ export interface FiscalDocument {
101
+ readonly id: string;
102
+ /** The emitter profile's owner: an opaque id the host maps (a store, a company). */
103
+ readonly ownerId: string;
104
+ /** The issuer's CNPJ: SEFAZ numbers by CNPJ, model and series, so the counters do too. */
105
+ readonly issuerCnpj: string;
106
+ /** What the document is FOR, opaque: the host links it to its orders. */
107
+ readonly subjectId: string;
108
+ readonly issuingPointId: string;
109
+ readonly model: FiscalDocumentModel;
110
+ readonly environment: SefazEnvironment;
111
+ readonly seriesKind: SeriesKind;
112
+ readonly series: number;
113
+ readonly number: number;
114
+ /** `cNF`, drawn once: a retried call yields the same key. */
115
+ readonly keyCode: string;
116
+ readonly status: FiscalDocumentStatus;
117
+ /** The sale as sent, issuer and number filled in. Never a secret. */
118
+ readonly sale: SaleForDocument;
119
+ readonly totals: DocumentTotals;
120
+ /** The buyer's CPF/CNPJ at issue time, or `null`. */
121
+ readonly buyerTaxId: string | null;
122
+ readonly accessKey: string | null;
123
+ /** The authorisation (or denial) protocol. */
124
+ readonly protocol: string | null;
125
+ /** The last SEFAZ `cStat`, or the service's named code. */
126
+ readonly statusCode: string | null;
127
+ readonly statusReason: string | null;
128
+ /** The class of the last failed call, or `null`. */
129
+ readonly lastErrorClass: SidecarErrorClass | null;
130
+ /** A request went out and neither it nor its lookup was answered. */
131
+ readonly outcomeUnknown: boolean;
132
+ /** `dhEmi`. */
133
+ readonly issuedAt: string;
134
+ readonly authorizedAt: string | null;
135
+ readonly contingency: { readonly since: string; readonly reason: string } | null;
136
+ readonly cancelledAt: string | null;
137
+ readonly cancelReason: string | null;
138
+ readonly cancelProtocol: string | null;
139
+ /** The document this one's sale moved to. */
140
+ readonly replacedById: string | null;
141
+ readonly numberVoid: NumberVoid | null;
142
+ /** Storage keys: the signed or authorised XML, and the cancel or inutilization event's XML. */
143
+ readonly xmlKey: string | null;
144
+ readonly eventXmlKey: string | null;
145
+ /** Calls made to the issuer for this document. */
146
+ readonly attempts: number;
147
+ /** Failed steps in a row (a retry, a deferred settlement); any progress resets it. */
148
+ readonly failures: number;
149
+ /** When the sweep (or the contingency transmission) may take it again; `null` when nothing is owed. */
150
+ readonly nextAttemptAt: string | null;
151
+ /**
152
+ * A person must look: a settlement SEFAZ refused, or too many failures in a
153
+ * row. The sweep leaves it alone until someone releases it.
154
+ */
155
+ readonly attention: boolean;
156
+ /** When the 24-hour contingency deadline warning went out. */
157
+ readonly deadlineWarnedAt: string | null;
158
+ readonly createdAt: string;
159
+ readonly updatedAt: string;
160
+ }
161
+
162
+ /** What the state machine was fed: the kind of the input that made the event. */
163
+ export type DocumentEventKind =
164
+ | "SUBMIT"
165
+ | "AUTHORIZE"
166
+ | "DENY"
167
+ | "REJECT"
168
+ | "RETRY"
169
+ | "SIGN_OFFLINE"
170
+ | "REPLACE"
171
+ | "CANCEL"
172
+ | "LOOKUP"
173
+ | "INUTILIZE"
174
+ | "DEFER"
175
+ | "RESIGN"
176
+ | "RELEASE"
177
+ | "WARN";
178
+
179
+ /**
180
+ * One transition, as stored. `answer` is what the fiscal service answered,
181
+ * verbatim but for any secret-named key (`scrubSecrets`), so the record is the
182
+ * evidence of what SEFAZ said, the `MarketplaceInboxEvent.payload` habit.
183
+ */
184
+ export interface FiscalDocumentEvent {
185
+ readonly documentId: string;
186
+ readonly kind: DocumentEventKind;
187
+ readonly fromStatus: FiscalDocumentStatus;
188
+ readonly toStatus: FiscalDocumentStatus;
189
+ readonly at: string;
190
+ readonly errorClass: SidecarErrorClass | null;
191
+ readonly code: string | null;
192
+ readonly answer: unknown;
193
+ }
@@ -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
+ }