@12-apps/fiscal 1.0.0 → 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 (140) hide show
  1. package/README.md +152 -7
  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-ALABGVPO.js +247 -0
  7. package/dist/chunk-ALABGVPO.js.map +1 -0
  8. package/dist/chunk-FOFIN5M7.js +14 -0
  9. package/dist/chunk-FOFIN5M7.js.map +1 -0
  10. package/dist/chunk-HQ2NXSTX.js +85 -0
  11. package/dist/chunk-HQ2NXSTX.js.map +1 -0
  12. package/dist/chunk-PNTKG3DZ.js +47 -0
  13. package/dist/chunk-PNTKG3DZ.js.map +1 -0
  14. package/dist/chunk-RRFKYVLZ.js +192 -0
  15. package/dist/chunk-RRFKYVLZ.js.map +1 -0
  16. package/dist/chunk-V5ZQAAJT.js +210 -0
  17. package/dist/chunk-V5ZQAAJT.js.map +1 -0
  18. package/dist/chunk-X6MRDUYH.js +21 -0
  19. package/dist/chunk-X6MRDUYH.js.map +1 -0
  20. package/dist/chunk-XQGW5HUG.js +30 -0
  21. package/dist/chunk-XQGW5HUG.js.map +1 -0
  22. package/dist/context-ChnWR4Kb.d.ts +455 -0
  23. package/dist/danfe/en-US.d.ts +12 -0
  24. package/dist/danfe/en-US.js +51 -0
  25. package/dist/danfe/en-US.js.map +1 -0
  26. package/dist/danfe/index.d.ts +50 -0
  27. package/dist/danfe/index.js +18 -0
  28. package/dist/danfe/index.js.map +1 -0
  29. package/dist/danfe/pt-BR.d.ts +11 -0
  30. package/dist/danfe/pt-BR.js +51 -0
  31. package/dist/danfe/pt-BR.js.map +1 -0
  32. package/dist/documents/index.d.ts +169 -0
  33. package/dist/documents/index.js +1228 -0
  34. package/dist/documents/index.js.map +1 -0
  35. package/dist/engine/index.d.ts +3 -246
  36. package/dist/http.d.ts +73 -0
  37. package/dist/http.js +16 -0
  38. package/dist/http.js.map +1 -0
  39. package/dist/issuer/index.d.ts +43 -0
  40. package/dist/issuer/index.js +131 -0
  41. package/dist/issuer/index.js.map +1 -0
  42. package/dist/jobs.d.ts +74 -0
  43. package/dist/jobs.js +22 -0
  44. package/dist/jobs.js.map +1 -0
  45. package/dist/labels-BNvflT0h.d.ts +44 -0
  46. package/dist/manifest/index.d.ts +30 -16
  47. package/dist/manifest/index.js +11 -17
  48. package/dist/manifest/index.js.map +1 -1
  49. package/dist/manifest/server.d.ts +57 -0
  50. package/dist/manifest/server.js +25 -0
  51. package/dist/manifest/server.js.map +1 -0
  52. package/dist/notifications.d.ts +93 -0
  53. package/dist/notifications.js +41 -0
  54. package/dist/notifications.js.map +1 -0
  55. package/dist/port-DpRFK56U.d.ts +238 -0
  56. package/dist/sale/index.d.ts +243 -0
  57. package/dist/sale/index.js +1 -0
  58. package/dist/sale/index.js.map +1 -0
  59. package/dist/service-KTjH7AxW.d.ts +139 -0
  60. package/dist/sidecar/index.d.ts +216 -0
  61. package/dist/sidecar/index.js +8 -0
  62. package/dist/sidecar/index.js.map +1 -0
  63. package/dist/types-B1b8LIWX.d.ts +247 -0
  64. package/package.json +63 -5
  65. package/prisma/fiscal.prisma +158 -0
  66. package/prisma/migrations/20261113220000_fiscal_documents/migration.sql +201 -0
  67. package/sidecar/.dockerignore +5 -0
  68. package/sidecar/Dockerfile +68 -0
  69. package/sidecar/README.md +149 -0
  70. package/sidecar/composer.json +30 -0
  71. package/sidecar/composer.lock +2224 -0
  72. package/sidecar/docker/apache.conf +14 -0
  73. package/sidecar/docker/icp-brasil.pem +8031 -0
  74. package/sidecar/docker/mpm.conf +17 -0
  75. package/sidecar/docker/openssl.cnf +16 -0
  76. package/sidecar/docker/php.ini +19 -0
  77. package/sidecar/public/index.php +15 -0
  78. package/sidecar/schema/sale-for-document.schema.json +401 -0
  79. package/sidecar/src/ErrorClass.php +31 -0
  80. package/sidecar/src/Http/Request.php +48 -0
  81. package/sidecar/src/Http/Response.php +32 -0
  82. package/sidecar/src/Http/Router.php +59 -0
  83. package/sidecar/src/Kernel.php +99 -0
  84. package/sidecar/src/Module.php +31 -0
  85. package/sidecar/src/Nfe/Classifier.php +89 -0
  86. package/sidecar/src/Nfe/Credentials.php +52 -0
  87. package/sidecar/src/Nfe/DocumentMapper.php +383 -0
  88. package/sidecar/src/Nfe/DocumentSchema.php +39 -0
  89. package/sidecar/src/Nfe/Input.php +125 -0
  90. package/sidecar/src/Nfe/Model.php +17 -0
  91. package/sidecar/src/Nfe/NfeModule.php +62 -0
  92. package/sidecar/src/Nfe/NfeService.php +504 -0
  93. package/sidecar/src/Nfe/Sefaz.php +49 -0
  94. package/sidecar/src/Nfe/SefazReply.php +81 -0
  95. package/sidecar/src/Nfe/Transport/CurlTransport.php +198 -0
  96. package/sidecar/src/Nfe/Transport/SoapAdapter.php +57 -0
  97. package/sidecar/src/Nfe/Transport/Transport.php +20 -0
  98. package/sidecar/src/Nfe/Transport/TransportFailure.php +42 -0
  99. package/sidecar/src/RequestLog.php +54 -0
  100. package/sidecar/src/ServiceError.php +69 -0
  101. package/src/danfe/en-US.ts +53 -0
  102. package/src/danfe/index.ts +11 -0
  103. package/src/danfe/labels.ts +49 -0
  104. package/src/danfe/pt-BR.ts +52 -0
  105. package/src/danfe/render.ts +265 -0
  106. package/src/danfe/xml.ts +45 -0
  107. package/src/documents/context.ts +260 -0
  108. package/src/documents/errors.ts +41 -0
  109. package/src/documents/helpers.ts +128 -0
  110. package/src/documents/index.ts +39 -0
  111. package/src/documents/lines.ts +63 -0
  112. package/src/documents/machine-steps.ts +260 -0
  113. package/src/documents/machine.ts +128 -0
  114. package/src/documents/memory.ts +138 -0
  115. package/src/documents/nfe-proc.ts +51 -0
  116. package/src/documents/ports.ts +130 -0
  117. package/src/documents/profile-input.ts +168 -0
  118. package/src/documents/profile.ts +98 -0
  119. package/src/documents/service-profile.ts +104 -0
  120. package/src/documents/service.ts +296 -0
  121. package/src/documents/settle.ts +121 -0
  122. package/src/documents/signing.ts +61 -0
  123. package/src/documents/sql-rows.ts +180 -0
  124. package/src/documents/sql-store.ts +242 -0
  125. package/src/documents/sql.ts +18 -0
  126. package/src/documents/steps.ts +173 -0
  127. package/src/documents/tests/integration/pglite.ts +73 -0
  128. package/src/documents/types.ts +193 -0
  129. package/src/http.ts +264 -0
  130. package/src/issuer/index.ts +9 -0
  131. package/src/issuer/port.ts +109 -0
  132. package/src/issuer/sidecar.ts +171 -0
  133. package/src/jobs.ts +115 -0
  134. package/src/manifest/index.ts +25 -16
  135. package/src/manifest/server.ts +20 -0
  136. package/src/notifications.ts +120 -0
  137. package/src/sale/index.ts +8 -0
  138. package/src/sale/types.ts +292 -0
  139. package/src/sidecar/index.ts +9 -0
  140. package/src/sidecar/types.ts +243 -0
package/README.md CHANGED
@@ -1,13 +1,21 @@
1
1
  # @12-apps/fiscal
2
2
 
3
- Brazilian consumption-tax machinery for any host that sells. The package is
4
- built module by module; the first is the **IBS/CBS engine**.
3
+ Brazilian consumption-tax machinery and fiscal documents for any host that
4
+ sells: the **IBS/CBS engine**, the neutral sale document, the fiscal service
5
+ over sped-nfe, and the **fiscal document module** that issues through it.
5
6
 
6
7
  | subpath | what it is |
7
8
  |---|---|
8
9
  | `@12-apps/fiscal/engine` | `computeTax(input) → TaxBreakdown`: pure, no I/O, no clock, no defaults. Plus `computeTaxWithOracle` over an injected `OfficialCalculator` port, and `compareBreakdowns`. |
9
10
  | `@12-apps/fiscal/tables/<file>.json` | Versioned rate tables — DATA, never code. The engine stamps the table's `version` on every result. |
10
- | `@12-apps/fiscal/manifest` | The `@12-apps/wiring` manifest. A skeleton today: the four permissions. |
11
+ | `@12-apps/fiscal/documents` | The fiscal document: its state machine, the emitter profile and issuing points, the ports a host implements (store, storage, cipher, sale source), the signing identity, the per-series number draw (`FISCAL_NEXT_NUMBER_SQL`), the engine-to-document line mapping and `createFiscalDocuments`, the service. |
12
+ | `@12-apps/fiscal/issuer` | The Issuer port and its first adapter, `createSidecarIssuer`, over the fiscal service's HTTP contract. |
13
+ | `@12-apps/fiscal/danfe` | The DANFE NFC-e as ESC/POS-ready lines for 58 and 80 mm; `./danfe/pt-BR` carries the Manual's own words. |
14
+ | `@12-apps/fiscal/http`, `/jobs`, `/notifications` | The wiring capabilities: the routes, the job blueprints, the notification blueprints over host copy. |
15
+ | `@12-apps/fiscal/manifest` | The `@12-apps/wiring` manifest: permissions, db, observability, `server: ["http", "jobs"]` (`./manifest/server`). |
16
+ | `@12-apps/fiscal/sale` | `SaleForDocument`, the neutral document shape: one sale, host-agnostic, as the fiscal service accepts it. Types only; its JSON schema is `@12-apps/fiscal/sidecar/schema/sale-for-document.schema.json`. |
17
+ | `@12-apps/fiscal/sidecar` | The fiscal service's wire contract: each endpoint's request and answer, and the error classes (`REJECTED`, `RETRYABLE`, `CONTINGENCY`, `AUTH`, `INVALID`). |
18
+ | `sidecar/` (folder) | The fiscal service itself: PHP over sped-nfe, stateless, with its `Dockerfile` (images pinned by digest). Issues, signs offline, transmits, cancels, looks up and inutilizes NF-e and NFC-e. See [sidecar/README.md](./sidecar/README.md). |
11
19
 
12
20
  ## The engine
13
21
 
@@ -116,10 +124,147 @@ The package's suite replays REAL recorded calculator answers for 2026
116
124
  calculator has no rates for 2027 and later yet, so those years' goldens are
117
125
  the engine's own estimates, marked `provisional`.
118
126
 
127
+ ## The fiscal documents
128
+
129
+ ```ts
130
+ import { createFiscalDocuments, createPrismaFiscalStore, createSigningIdentities } from "@12-apps/fiscal/documents";
131
+ import { createSidecarIssuer } from "@12-apps/fiscal/issuer";
132
+
133
+ const documents = createFiscalDocuments({
134
+ store: createPrismaFiscalStore({ prisma }), // the package's own store: the host passes its Prisma client
135
+
136
+ issuer: createSidecarIssuer({ baseUrl: "http://fiscal-sidecar:8080", fetch, timeoutMs: 90_000 }),
137
+ signing: createSigningIdentities({ cipher }),
138
+ cipher, // the host's { encrypt, decrypt }: certificate, password and CSC at rest
139
+ readCertificate, // the host's: an A1's expiry, or a throw when it does not open
140
+ storage, // where the XMLs live
141
+ sales, // SaleSource: the host's sale as a SaleDraft (`documentLines` maps the engine's breakdown)
142
+ notify, // the host's notifier (never throws)
143
+ now: () => new Date(),
144
+ utcOffset: (ownerId, at) => "-03:00",
145
+ reasons: { contingency, inutilization, substitution }, // host words SEFAZ receives, 15–255 chars
146
+ staleAfterMs: 5 * 60_000, // the base of the backoff
147
+ nfceOnlineToleranceMs: 5 * 60_000, // SEFAZ's late-dhEmi limit (704), the state's
148
+ newId: () => crypto.randomUUID(),
149
+ });
150
+ await documents.issue({ ownerId, subjectId, issuingPointId, model: "NFCE" });
151
+ ```
152
+
153
+ **One document is one number.** The state machine (`transition`) is pure:
154
+
155
+ ```
156
+ PENDING ─SUBMIT→ SUBMITTED ─AUTHORIZE→ AUTHORIZED ─CANCEL→ CANCELLED
157
+ ├─DENY→ DENIED ├─REJECT→ REJECTED └─RETRY→ SUBMITTED
158
+ PENDING | SUBMITTED ─REPLACE→ REPLACED
159
+ PENDING ─SIGN_OFFLINE→ CONTINGENCY ─AUTHORIZE | DENY | REJECT | RETRY→ …
160
+ ```
161
+
162
+ Every step yields an event carrying the fiscal service's raw answer, with any
163
+ secret-named key scrubbed. `CANCELLED` is reached only from `AUTHORIZED`, and
164
+ nothing leaves `REJECTED`, `DENIED`, `REPLACED` or `CANCELLED` for `AUTHORIZED`
165
+ (a property suite walks random sequences).
166
+
167
+ - **The counters are the package's, and so is their store.**
168
+ `createPrismaFiscalStore({ prisma })` runs over the host's Prisma client
169
+ (raw SQL on the package's migration); a host keeps no counter and writes no
170
+ numbering transaction. A counter is keyed by the issuer's CNPJ, the model
171
+ and the series, as SEFAZ numbers (one CNPJ can serve several owners); a
172
+ series belongs to one issuing point. A number is drawn in the same
173
+ transaction as the document's insert (`FISCAL_NEXT_NUMBER_SQL`), so a failed
174
+ write gives it back.
175
+ - **One live document per subject.** The partial unique index
176
+ `fiscal_documents_live_subject_key` refuses a second live document for an
177
+ (owner, subject, model); `issue()` answers the existing one when a
178
+ concurrent call won.
179
+ - **Going offline is a second document, in one transaction.** When the
180
+ service answers `CONTINGENCY` for an NFC-e at a point with a contingency
181
+ series — or the sweep finds an online NFC-e past `nfceOnlineToleranceMs`,
182
+ which SEFAZ would refuse as late — the sale is numbered on that series AND
183
+ the online document is `REPLACED` in the same transaction, before anything
184
+ is signed. Signing follows (`tpEmis = 9`); the `transmit-contingency` job
185
+ sends it, and warns at 20 hours (the deadline is 24). Offline, the paper is
186
+ ONE copy, the consumer's.
187
+ - **Every number SEFAZ never used is settled.** `numberVoid` says what is
188
+ owed: a lookup first when a send went unanswered (`outcomeUnknown` is
189
+ sticky until a definitive answer or a lookup clears it — the package
190
+ computes every access key, so a lookup is always possible), the NFC-e
191
+ cancel BY SUBSTITUTION (event 110112, naming the contingency twin) when
192
+ SEFAZ authorised it after all, an inutilization otherwise; `DENIED` when
193
+ the lookup finds it denied (the denial spent it).
194
+ - **A rejected contingency NFC-e is never voided.** The buyer holds its
195
+ DANFE: it stays `REJECTED` with SEFAZ's code, the store corrects the sale,
196
+ and `resendContingency` signs it again under the same series, number and
197
+ key code (`POST …/resend`), with the corrected sale's totals. A correction
198
+ that changes the total or the buyer's document — what the DANFE the buyer
199
+ holds prints and its QR encodes — is refused (`RESEND_CHANGES_PRINTED_FIELDS`):
200
+ that sale needs a new note, issued by a person.
201
+ - **An authorised document always has its XML.** A lookup that finds a
202
+ SUBMITTED document authorised joins the signed XML the service returned to
203
+ the lookup's `protNFe`; without both, the document stays SUBMITTED (its
204
+ protocol kept, so it never goes offline) and the sweep sends the same call
205
+ again, which the service settles with the XML. A REPLACED number that was
206
+ ever SUBMITTED is always looked up before it is voided.
207
+ - **Nothing is retried silently.** Each failed step counts (`failures`) and
208
+ backs off (`nextAttemptAt`, doubling to 64 × `staleAfterMs`); the queues
209
+ are ordered by the next attempt, so a failing row never pins their head. A
210
+ refusal SEFAZ will repeat (241, 256, 501, a certificate refused), or
211
+ `MAX_FAILURES` in a row, hands the document to a person (`attention`, the
212
+ `fiscal.document-needs-attention` notification); `POST …/release` gives it
213
+ back to the sweep.
214
+ - **What the classes mean here.** `REJECTED`, `INVALID` and `INTERNAL` reject
215
+ (the same call fails again); `RETRYABLE`, `AUTH` and a `CONTINGENCY` with no
216
+ offline path retry, with the same number and key code.
217
+ - **Who signs** is the profile's `signingIdentity`: `STORE_CERTIFICATE` (the
218
+ store's A1, decrypted for one call) or `PLATFORM`, declared and answering
219
+ `NOT_SUPPORTED` until FUT-2229 q4 says how the platform signs.
220
+ - **Secrets** are encrypted through the host's cipher on arrival, decrypted by
221
+ the signing identity for one call, and never stored in clear, logged,
222
+ answered or put in an error. The CSC's id and token are saved together or
223
+ not at all.
224
+
225
+ **Not in this release** (FUT-4717): an offline register signing on a block of
226
+ the contingency series reserved in advance, recording what it signed, and
227
+ voiding the known rest of a finished block. The port it will build on is
228
+ declared, unimplemented: `ContingencyBlockSource`.
229
+
230
+ NFS-e is not covered: only the platform's own NFS-e is planned (FUT-2242).
231
+
232
+ ## The DANFE NFC-e
233
+
234
+ `renderDanfeNfce({ xml, paperWidth: 58 | 80, labels })` reads the authorised
235
+ XML (or the signed XML of a document issued offline, which prints the
236
+ "EMITIDA EM CONTINGÊNCIA" variant) and answers lines in the Manual do DANFE
237
+ NFC-e's divisions I–VIII: the issuer, the title, every item, the totals and
238
+ payments, the fiscal message and the key, the consumer, the number and
239
+ protocol, and the QR code (a line carrying `qrCode`, for the host to
240
+ rasterise). Each line is `{ text, align, emphasis }`, the shape
241
+ `@12-apps/thermal-printing` encodes, at 32 or 48 columns.
242
+
119
243
  ## The manifest
120
244
 
121
245
  `@12-apps/fiscal/manifest` declares the permissions `fiscal:read`,
122
- `fiscal:manage`, `fiscal:issue` and `fiscal:cancel`, here and nowhere else. The
123
- document module adds `db`, `server: ["http", "jobs"]`, `notifications`,
124
- `web: ["surface"]` and `observability`; until then `.wiring-conformance.json`
125
- answers each with its reason.
246
+ `fiscal:manage`, `fiscal:issue` and `fiscal:cancel`, here and nowhere else;
247
+ the Prisma partial `prisma/fiscal.prisma` and its migrations; the `fiscal`
248
+ observability namespace; and `server: ["http", "jobs"]`:
249
+
250
+ | route (under the host's mount) | permission |
251
+ |---|---|
252
+ | `GET /fiscal/profile`, `GET /fiscal/issuing-points` | `fiscal:read` |
253
+ | `PUT /fiscal/profile`, `PUT /fiscal/profile/certificate`, `POST /fiscal/issuing-points` | `fiscal:manage` |
254
+ | `POST /fiscal/documents` | `fiscal:issue` |
255
+ | `GET /fiscal/documents/:documentId`, `POST …/lookup`, `GET …/danfe?paper=58\|80` (AUTHORIZED or CONTINGENCY only; 409 otherwise) | `fiscal:read` |
256
+ | `POST /fiscal/documents/:documentId/cancel` | `fiscal:cancel` |
257
+ | `POST /fiscal/documents/:documentId/resend` (a rejected contingency NFC-e), `POST …/release` (back from a person) | `fiscal:issue` |
258
+
259
+ The jobs are `fiscal.sweep` and `fiscal.transmit-contingency` (every five
260
+ minutes, a 30-minute lease and a batch sized so the worst run ends inside it) and `fiscal.certificate-expiry` (daily, telling owners on the
261
+ 30th, 15th, 7th, 3rd and last day, and daily once expired). The alerts (certificate expiring, document rejected)
262
+ and the other two (needs attention, contingency deadline) ship as
263
+ `createFiscalNotificationBlueprints(copy)`, over the host's words. The
264
+ settings screen and the documents list (`web: ["surface"]`) come with their
265
+ screen tickets; `.wiring-conformance.json` argues each capability not
266
+ declared.
267
+
268
+ The RBAC bullet of the host's tax docs (which still places the four
269
+ permissions in the host's catalog) is corrected in the host's pull request that
270
+ bumps `@12-apps/fiscal`, not here.