@12-apps/fiscal 1.4.0 → 1.6.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 (96) hide show
  1. package/README.md +46 -4
  2. package/dist/{chunk-EDEGIADD.js → chunk-2JVTHJAU.js} +3 -3
  3. package/dist/{chunk-2ISYBTCE.js → chunk-CEK2GDRY.js} +15 -6
  4. package/dist/chunk-CEK2GDRY.js.map +1 -0
  5. package/dist/{chunk-GF3DXCD2.js → chunk-GH452ITO.js} +1 -1
  6. package/dist/{chunk-GF3DXCD2.js.map → chunk-GH452ITO.js.map} +1 -1
  7. package/dist/{chunk-MGTROA7K.js → chunk-OAQSGDZ7.js} +11 -7
  8. package/dist/chunk-OAQSGDZ7.js.map +1 -0
  9. package/dist/{chunk-OSYB7CVT.js → chunk-P7CRGZGO.js} +2 -2
  10. package/dist/{chunk-H33BK623.js → chunk-WRYCYXRA.js} +1 -1
  11. package/dist/{chunk-H33BK623.js.map → chunk-WRYCYXRA.js.map} +1 -1
  12. package/dist/{chunk-F2PGQVWL.js → chunk-YHSO3476.js} +7 -6
  13. package/dist/chunk-YHSO3476.js.map +1 -0
  14. package/dist/{chunk-JVQKJNOC.js → chunk-ZKWVKCGJ.js} +1 -1
  15. package/dist/chunk-ZKWVKCGJ.js.map +1 -0
  16. package/dist/{context-CLSMOSuf.d.ts → context-Cyvfr2YB.d.ts} +167 -20
  17. package/dist/danfe/index.d.ts +7 -0
  18. package/dist/danfe/index.js +2 -2
  19. package/dist/documents/index.d.ts +154 -34
  20. package/dist/documents/index.js +1193 -306
  21. package/dist/documents/index.js.map +1 -1
  22. package/dist/engine/index.d.ts +2 -2
  23. package/dist/http.d.ts +6 -5
  24. package/dist/http.js +5 -5
  25. package/dist/issuer/index.d.ts +10 -3
  26. package/dist/issuer/index.js +27 -4
  27. package/dist/issuer/index.js.map +1 -1
  28. package/dist/jobs.d.ts +5 -5
  29. package/dist/jobs.js +4 -4
  30. package/dist/manifest/index.d.ts +6 -4
  31. package/dist/manifest/index.js.map +1 -1
  32. package/dist/manifest/server.d.ts +5 -5
  33. package/dist/manifest/server.js +7 -7
  34. package/dist/notifications.d.ts +4 -4
  35. package/dist/notifications.js +3 -3
  36. package/dist/sale/index.d.ts +29 -1
  37. package/dist/sale/index.js +7 -0
  38. package/dist/sale/index.js.map +1 -1
  39. package/dist/{service-hR3tgLpO.d.ts → service-BCK9aXop.d.ts} +99 -6
  40. package/dist/sidecar/index.d.ts +35 -210
  41. package/dist/sidecar/index.js +30 -2
  42. package/dist/sidecar/index.js.map +1 -1
  43. package/dist/{types-B1b8LIWX.d.ts → types-BLdkww6G.d.ts} +1 -1
  44. package/dist/{types-BIJqm5GM.d.ts → types-Sk010Em2.d.ts} +25 -4
  45. package/dist/types-Z5E14EPw.d.ts +254 -0
  46. package/package.json +2 -1
  47. package/prisma/fiscal.prisma +50 -1
  48. package/prisma/migrations/20261118120000_fiscal_link_payment_event/migration.sql +9 -0
  49. package/prisma/migrations/20261118180000_fiscal_contingency_blocks/migration.sql +64 -0
  50. package/sidecar/README.md +53 -1
  51. package/sidecar/bin/check-platform.php +29 -0
  52. package/sidecar/composer.json +1 -1
  53. package/sidecar/composer.lock +7 -7
  54. package/sidecar/extensions.json +12 -0
  55. package/sidecar/schema/sale-for-document.schema.json +18 -1
  56. package/sidecar/src/Http/Request.php +6 -1
  57. package/sidecar/src/Kernel.php +39 -1
  58. package/sidecar/src/Nfe/DocumentMapper.php +27 -0
  59. package/sidecar/src/Nfe/Input.php +10 -0
  60. package/sidecar/src/Nfe/NfeModule.php +1 -0
  61. package/sidecar/src/Nfe/NfeService.php +120 -0
  62. package/sidecar/src/Nfe/SefazReply.php +21 -0
  63. package/sidecar/src/Platform.php +84 -0
  64. package/src/danfe/render.ts +16 -5
  65. package/src/documents/contingency-gaps.ts +88 -0
  66. package/src/documents/contingency-pass.ts +157 -0
  67. package/src/documents/contingency-xml.ts +136 -0
  68. package/src/documents/contingency.ts +257 -0
  69. package/src/documents/errors.ts +8 -1
  70. package/src/documents/helpers.ts +5 -0
  71. package/src/documents/index.ts +25 -2
  72. package/src/documents/machine-steps.ts +12 -2
  73. package/src/documents/machine.ts +7 -0
  74. package/src/documents/memory-blocks.ts +118 -0
  75. package/src/documents/memory.ts +6 -2
  76. package/src/documents/payment-link.ts +156 -0
  77. package/src/documents/ports.ts +163 -13
  78. package/src/documents/service.ts +14 -0
  79. package/src/documents/sql-blocks.ts +202 -0
  80. package/src/documents/sql-store.ts +4 -3
  81. package/src/documents/types.ts +2 -1
  82. package/src/http.ts +1 -0
  83. package/src/issuer/port.ts +24 -1
  84. package/src/issuer/sidecar.ts +37 -3
  85. package/src/manifest/index.ts +6 -4
  86. package/src/sale/index.ts +1 -0
  87. package/src/sale/types.ts +30 -0
  88. package/src/sidecar/index.ts +2 -0
  89. package/src/sidecar/platform.ts +55 -0
  90. package/src/sidecar/types.ts +38 -0
  91. package/dist/chunk-2ISYBTCE.js.map +0 -1
  92. package/dist/chunk-F2PGQVWL.js.map +0 -1
  93. package/dist/chunk-JVQKJNOC.js.map +0 -1
  94. package/dist/chunk-MGTROA7K.js.map +0 -1
  95. /package/dist/{chunk-EDEGIADD.js.map → chunk-2JVTHJAU.js.map} +0 -0
  96. /package/dist/{chunk-OSYB7CVT.js.map → chunk-P7CRGZGO.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sidecar/types.ts"],"sourcesContent":["/**\n * The wire contract of the fiscal service (`sidecar/` in this package): a\n * stateless HTTP door in front of sped-nfe. JSON in, JSON out.\n *\n * Stateless means every call carries what it needs: the signing certificate\n * (an A1 `.pfx` as base64 and its password) and, for an NFC-e, the CSC. The\n * service keeps nothing between calls, writes nothing to disk and never logs\n * any of the three.\n */\n\nimport type { SaleForDocument } from \"../sale/types\";\n\n/** The path segment of a document model: `nfe` is model 55, `nfce` model 65. */\nexport type DocumentModelPath = \"nfe\" | \"nfce\";\n\n/** The SEFAZ environment (`tpAmb` 2 and 1). */\nexport type SefazEnvironment = \"homologacao\" | \"producao\";\n\n/** The A1 certificate, per call. */\nexport interface SigningCertificate {\n /** The `.pfx` (PKCS#12) bytes, base64. */\n readonly pfxBase64: string;\n readonly password: string;\n}\n\n/** The NFC-e's Código de Segurança do Contribuinte and its id. */\nexport interface Csc {\n readonly id: string;\n readonly token: string;\n}\n\ninterface Authenticated {\n readonly environment: SefazEnvironment;\n readonly certificate: SigningCertificate;\n}\n\n/**\n * `POST /<model>/issue`: builds, signs and transmits. `csc` is required for\n * `nfce` and refused for `nfe`.\n */\nexport interface IssueRequest extends Authenticated {\n readonly csc: Csc | null;\n readonly document: SaleForDocument;\n}\n\n/** Why and since when the caixa issues offline (`dhCont`, `xJust`). */\nexport interface ContingencyEntry {\n /** ISO 8601 with the UTC offset. */\n readonly since: string;\n /** 15–256 characters. */\n readonly reason: string;\n}\n\n/** `POST /nfce/sign-contingency`: builds and signs with `tpEmis = 9`; does NOT transmit. */\nexport interface SignContingencyRequest extends IssueRequest {\n readonly contingency: ContingencyEntry;\n}\n\n/** `POST /<model>/transmit`: an already signed XML (from `/nfce/sign-contingency`, say). */\nexport interface TransmitRequest extends Authenticated {\n readonly signedXml: string;\n}\n\n/** `POST /<model>/cancel`: the UF and the issuer come from the access key. */\nexport interface CancelRequest extends Authenticated {\n readonly accessKey: string;\n /** The authorisation protocol (`nProt`). */\n readonly protocol: string;\n /** 15–255 characters. */\n readonly reason: string;\n}\n\n/**\n * `POST /nfce/cancel-substitution`: the NFC-e \"cancelamento por substituição\"\n * (event 110112) — an online NFC-e found authorised after its sale was issued\n * again in contingency, cancelled naming the substitute. Answers as `/cancel`.\n */\nexport interface CancelBySubstitutionRequest extends CancelRequest {\n /** The contingency document that replaced it (`chNFeRef`). */\n readonly substituteAccessKey: string;\n}\n\n/** `POST /<model>/link-payment`: the event 110300 for one transaction (NT 2026.006 v1.00). */\nexport interface LinkPaymentRequest extends Authenticated {\n readonly accessKey: string;\n /** The authorisation protocol (`nProt`). */\n readonly protocol: string;\n /** `nSeqEvento`, 1–20: this document's how-manieth 110300. */\n readonly sequence: number;\n /** Exactly one entry: the event's schema carries a single `gPgto`. */\n readonly payments: ReadonlyArray<{\n readonly transactionId: string;\n readonly meansCode: string;\n readonly pspCnpjBase: string;\n readonly receiverCnpj: string;\n }>;\n}\n\n/** `POST /<model>/lookup`. */\nexport interface LookupRequest extends Authenticated {\n readonly accessKey: string;\n}\n\n/** `POST /inutilize`: voids a range of unused numbers. */\nexport interface InutilizeRequest extends Authenticated {\n readonly model: DocumentModelPath;\n readonly uf: string;\n readonly cnpj: string;\n /** The year of the numbers, four digits. */\n readonly year: number;\n readonly series: number;\n readonly from: number;\n readonly to: number;\n /** 15–255 characters. */\n readonly reason: string;\n}\n\n/** What SEFAZ answered, as the service read it. */\nexport interface SefazAnswer {\n /** `cStat`. */\n readonly statusCode: string;\n /** `xMotivo`. */\n readonly statusReason: string;\n /** The SOAP body SEFAZ returned, verbatim. */\n readonly sefazReply: string;\n}\n\n/**\n * `/issue` and `/transmit`: SEFAZ's final answer on the document.\n *\n * - `AUTHORIZED` (100, 120, 150).\n * - `DENIED` (110, 301, 302, 303): a denial of use. The number is SPENT and\n * the denial is kept like an authorisation (its `authorizedXml` carries the\n * denial protocol); it is not a rejection, which leaves the number free.\n *\n * A retried call answers the same: SEFAZ's \"already authorised\" (204) and\n * \"already denied\" (205), and a request sent with no answer, are settled by\n * looking the key up, so a retry never turns an authorised document into an error.\n */\nexport interface IssuedDocument extends SefazAnswer {\n readonly status: \"AUTHORIZED\" | \"DENIED\";\n readonly accessKey: string;\n readonly protocol: string;\n /** `dhRecbto` of the protocol. */\n readonly authorizedAt: string;\n readonly signedXml: string;\n /** The `nfeProc`: the signed XML with its protocol (of authorisation or of denial), what is stored. */\n readonly authorizedXml: string;\n}\n\n/** `/nfce/sign-contingency`. */\nexport interface ContingencySignedDocument {\n readonly status: \"SIGNED\";\n readonly accessKey: string;\n /** Carries `tpEmis = 9` and the QR code; transmit it later through `/nfce/transmit`. */\n readonly signedXml: string;\n}\n\n/**\n * `/cancel`. A retried cancel (SEFAZ's 218 \"already cancelled\" or 573\n * \"duplicate event\", or a cancel sent with no answer) is settled by looking\n * the key up, and answers CANCELLED with what the lookup carries: the event's\n * protocol and XML when SEFAZ returns them, `null` when it does not.\n */\nexport interface CancelledDocument extends SefazAnswer {\n readonly status: \"CANCELLED\";\n readonly accessKey: string;\n /** The event's protocol. */\n readonly protocol: string | null;\n readonly registeredAt: string | null;\n /** The `procEventoNFe`. */\n readonly eventXml: string | null;\n}\n\n/**\n * `/link-payment`: the event registered. On 573 \"Duplicidade de Evento\" the\n * service looks the key up and answers the event SEFAZ already holds at that\n * `nSeqEvento`, with its own XML and the transaction it carries — which may be\n * another transaction than the one sent (`statusCode` \"573\" tells the two apart).\n */\nexport interface RegisteredPaymentLink extends SefazAnswer {\n readonly status: \"REGISTERED\";\n readonly accessKey: string;\n readonly protocol: string | null;\n readonly registeredAt: string | null;\n /** The `procEventoNFe`. */\n readonly eventXml: string | null;\n /** The `gPgto` SEFAZ registered at this `nSeqEvento`. */\n readonly transaction: {\n readonly transactionId: string;\n readonly meansCode: string;\n readonly pspCnpjBase: string;\n readonly receiverCnpj: string;\n };\n}\n\n/** `/lookup`: what SEFAZ knows of the key. `NOT_FOUND` is an answer, not an error. */\nexport interface LookedUpDocument extends SefazAnswer {\n readonly status: \"AUTHORIZED\" | \"CANCELLED\" | \"DENIED\" | \"NOT_FOUND\";\n readonly accessKey: string;\n readonly protocol: string | null;\n}\n\n/**\n * `/inutilize`. A retried inutilização (563, \"a request for the same range\n * already exists\") answers INUTILIZED too, with `protocol` and\n * `inutilizationXml` `null`: the range is void at SEFAZ, and SEFAZ offers no\n * query that would return the first protocol.\n */\nexport interface InutilizedRange extends SefazAnswer {\n readonly status: \"INUTILIZED\";\n readonly protocol: string | null;\n readonly registeredAt: string | null;\n /** The signed request with its reply (`procInutNFe`). */\n readonly inutilizationXml: string | null;\n}\n\n/**\n * How a failed call is classified — the issuer port's own classes:\n *\n * - `REJECTED`: SEFAZ refused the document or the event; `code` is its `cStat`.\n * The number is NOT spent (a denial is not an error: it answers `DENIED`).\n * - `RETRYABLE`: try the same call again later. When `outcomeUnknown` is true\n * the request went out and neither it nor the lookup that would settle it\n * was answered: look the key up before sending it again.\n * - `CONTINGENCY`: SEFAZ is unavailable. For an NFC-e being issued, nothing\n * reached SEFAZ (or the lookup after an unanswered request could not reach\n * it): go offline through `/nfce/sign-contingency`. For an NF-e (model 55)\n * the service has no offline path (no SVC, no EPEC): treat it as RETRYABLE.\n * - `AUTH`: the certificate is unreadable, the password wrong, the certificate\n * expired, or SEFAZ refused it.\n * - `INVALID`: the request itself is malformed (the schema, a missing CSC, an\n * XML the layout refuses, a document the layout version cannot express).\n * Fix the input; never retry it as is.\n * - `INTERNAL`: a defect of the service, or a 4xx other than 403/408/429 from\n * the verified SEFAZ host (a wrong web-service address). A retry would only repeat it.\n */\nexport type SidecarErrorClass = \"REJECTED\" | \"RETRYABLE\" | \"CONTINGENCY\" | \"AUTH\" | \"INVALID\" | \"INTERNAL\";\n\nexport const SIDECAR_ERROR_CLASSES: readonly SidecarErrorClass[] = [\n \"REJECTED\",\n \"RETRYABLE\",\n \"CONTINGENCY\",\n \"AUTH\",\n \"INVALID\",\n \"INTERNAL\",\n];\n\n/** The body of every non-2xx answer. */\nexport interface SidecarErrorBody {\n readonly error: {\n readonly class: SidecarErrorClass;\n /**\n * The SEFAZ `cStat` when SEFAZ answered (always for `REJECTED`); for\n * `INVALID`, a named code where one applies (`NT_2026_008_NOT_SUPPORTED`:\n * a document issued on or after 2027-01-01, which needs NT 2026.008's\n * `vProdLiq`; `RETURN_ON_NFCE`: a return asked of an NFC-e, which has no\n * return purpose; `RETURN_NEEDS_REFERENCE`: a return quoting no\n * `referencedDocuments`); `null` otherwise.\n */\n readonly code: string | null;\n readonly message: string;\n /** Per-field problems of an `INVALID` request. */\n readonly details: readonly string[];\n /** When the call got as far as building and signing: keep it, the key is now spoken for. */\n readonly accessKey: string | null;\n readonly signedXml: string | null;\n readonly sefazReply: string | null;\n /** The request went out and its outcome is still unknown: look the key up before sending it again. */\n readonly outcomeUnknown: boolean;\n };\n}\n\n/** `GET /health`. */\nexport interface SidecarHealth {\n readonly status: \"ok\";\n /** The libraries the service runs, by name, with the version installed. */\n readonly libraries: Readonly<Record<string, string>>;\n /** The schema package the NF-e layout is validated against. */\n readonly nfeSchemas: string;\n /** Whether SEFAZ's server certificate is verified; `false` only with `FISCAL_SEFAZ_TLS_VERIFY=off`. */\n readonly sefazTlsVerify: boolean;\n}\n"],"mappings":";AA+OO,IAAM,wBAAsD;AAAA,EACjE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":[]}
@@ -1,7 +1,7 @@
1
- import { F as FiscalDocumentModel, n as DocumentTotals, D as DocumentEventKind, g as FiscalDocumentStatus, h as FiscalDocument, k as FiscalDocumentEvent, l as SeriesKind, f as SigningMaterial, I as Issuer } from './types-BIJqm5GM.js';
2
- import { IssuerTaxRegime, Address, SaleForDocument } from './sale/index.js';
3
- import { SefazEnvironment, IssuedDocument, SidecarErrorBody, ContingencySignedDocument, ContingencyEntry, CancelledDocument, LookedUpDocument, InutilizedRange } from './sidecar/index.js';
4
- import { T as TaxRegime } from './types-B1b8LIWX.js';
1
+ import { F as FiscalDocumentModel, D as DocumentTotals, n as DocumentEventKind, h as FiscalDocumentStatus, i as FiscalDocument, l as FiscalDocumentEvent, o as SeriesKind, g as SigningMaterial, I as Issuer } from './types-Sk010Em2.js';
2
+ import { IssuerTaxRegime, Address, SaleForDocument, LinkedTransaction } from './sale/index.js';
3
+ import { l as SefazEnvironment, h as IssuedDocument, m as SidecarErrorBody, d as ContingencySignedDocument, c as ContingencyEntry, b as CancelledDocument, i as LookedUpDocument, f as InutilizedRange, R as RegisteredPaymentLink } from './types-Z5E14EPw.js';
4
+ import { T as TaxRegime } from './types-BLdkww6G.js';
5
5
 
6
6
  /**
7
7
  * The emitter profile and its issuing points — what moved INTO this package
@@ -171,6 +171,14 @@ type DocumentInput = {
171
171
  /** The 24-hour contingency deadline warning went out. */
172
172
  | {
173
173
  readonly kind: "WARN";
174
+ }
175
+ /** SEFAZ registered the event 110300 #`sequence` linking `payment` to the document; its XML is at `eventXmlKey`. */
176
+ | {
177
+ readonly kind: "LINK_PAYMENT";
178
+ readonly answer: RegisteredPaymentLink;
179
+ readonly payment: LinkedTransaction;
180
+ readonly sequence: number;
181
+ readonly eventXmlKey: string | null;
174
182
  };
175
183
 
176
184
  /**
@@ -196,6 +204,9 @@ type DocumentInput = {
196
204
  * final state. A rejected contingency NFC-e is the one way back: the store
197
205
  * corrects it and it is signed again under the same number (`RESIGN`).
198
206
  *
207
+ * `LINK_PAYMENT` records an event 110300 SEFAZ registered on an authorised
208
+ * document (a payment transaction linked after the fact); it changes nothing.
209
+ *
199
210
  * `DEFER`, `RELEASE` and `WARN` record what the sweep and a person did without
200
211
  * changing the state: a failed step counts toward {@link MAX_FAILURES}, after
201
212
  * which the document waits for a person (`attention`).
@@ -331,38 +342,174 @@ interface FiscalStore {
331
342
  /** Profiles whose certificate expires before `before`, across owners. */
332
343
  listExpiringCertificates(before: string): Promise<EmitterProfile[]>;
333
344
  }
345
+ /** A run of numbers of one series, both ends included. */
346
+ interface NumberRange {
347
+ readonly from: number;
348
+ readonly to: number;
349
+ }
350
+ /**
351
+ * - `OPEN`: the holder may still sign on it.
352
+ * - `CLOSED`: the holder said it is done with it and how far it got (`usedUpTo`).
353
+ * - `ABANDONED`: the holder is gone (a new install took its place): what it
354
+ * signed above the highest number it handed in is unknown, never voided.
355
+ */
356
+ type ContingencyBlockFate = "OPEN" | "CLOSED" | "ABANDONED";
357
+ declare const CONTINGENCY_BLOCK_FATES: readonly ContingencyBlockFate[];
334
358
  /**
335
- * DECLARED, NOT IMPLEMENTED (FUT-4717): what an offline register needs from
336
- * the package that owns every number. A register that cannot reach the server
337
- * signs on a block of its contingency series reserved in advance; back
359
+ * Numbers of an issuing point's contingency series reserved for one holder
360
+ * (the host's opaque id of a register that may go offline) to sign on with no
361
+ * server. Drawn from the series' ONE counter — the counter the server's own
362
+ * contingency (`issueOffline`, going offline after a silent SEFAZ) draws from
363
+ * — so nothing else is ever numbered inside a block.
364
+ */
365
+ interface ContingencyBlock extends NumberRange {
366
+ readonly id: string;
367
+ readonly ownerId: string;
368
+ readonly issuingPointId: string;
369
+ readonly issuerCnpj: string;
370
+ readonly environment: SefazEnvironment;
371
+ readonly model: "NFCE";
372
+ readonly series: number;
373
+ readonly holder: string;
374
+ readonly fate: ContingencyBlockFate;
375
+ /** The highest number the holder said it used when it closed the block (`from - 1`: none); `null` otherwise. */
376
+ readonly usedUpTo: number | null;
377
+ readonly reservedAt: string;
378
+ readonly closedAt: string | null;
379
+ /** When every number of the block was accounted for (a document, or voided); `null` while one is not. */
380
+ readonly settledAt: string | null;
381
+ }
382
+ /** A block, with the numbers recorded on it and the ranges voided at SEFAZ. */
383
+ interface ContingencyBlockState extends ContingencyBlock {
384
+ /** Numbers inside the block that carry a document, ascending. */
385
+ readonly documented: readonly number[];
386
+ readonly voided: readonly NumberRange[];
387
+ }
388
+ /**
389
+ * A range of a block with no document: KNOWN unused (voided by
390
+ * `voidKnownGaps`) or UNKNOWN (flagged for the store, never voided).
391
+ */
392
+ interface ContingencyGap extends NumberRange {
393
+ readonly blockId: string;
394
+ readonly ownerId: string;
395
+ readonly issuingPointId: string;
396
+ readonly issuerCnpj: string;
397
+ readonly environment: SefazEnvironment;
398
+ readonly series: number;
399
+ readonly holder: string;
400
+ readonly reservedAt: string;
401
+ }
402
+ /**
403
+ * The rows behind contingency blocks (FUT-4717). Both of the package's stores
404
+ * implement it (`createPrismaFiscalStore`, `createMemoryFiscalStore`); a host
405
+ * with its own `FiscalStore` and without these gets `NOT_SUPPORTED` from the
406
+ * block methods of the service, and everything else as before.
407
+ *
408
+ * - `reserveContingencyBlock` advances the series' counter by `size` and
409
+ * records the block, in one transaction (no row back: not that point's
410
+ * contingency series; past 999 999 999: `SERIES_EXHAUSTED`).
411
+ * - `recordSignedDocument` inserts a document and its event together; a
412
+ * second live document of the subject is `SUBJECT_HAS_DOCUMENT`, a key or
413
+ * number recorded already is `CONFLICT`.
414
+ * - `closeContingencyBlock` moves an OPEN block only (`false` otherwise).
415
+ * - `recordContingencyVoid` records a voided range once (`false` when the
416
+ * range was recorded before).
417
+ */
418
+ interface ContingencyBlockStore {
419
+ reserveContingencyBlock(input: {
420
+ readonly request: NumberRequest;
421
+ readonly size: number;
422
+ readonly id: string;
423
+ readonly holder: string;
424
+ readonly at: string;
425
+ }): Promise<ContingencyBlock>;
426
+ /** The block holding `number` of the series, whoever holds it, with its documents and voids. */
427
+ findContingencyBlock(input: {
428
+ readonly ownerId: string;
429
+ readonly issuerCnpj: string;
430
+ readonly environment: SefazEnvironment;
431
+ readonly series: number;
432
+ readonly number: number;
433
+ }): Promise<ContingencyBlockState | null>;
434
+ /**
435
+ * One page of the blocks a filter selects, ordered by `(reservedAt, id)`;
436
+ * `after` is the last block of the previous page (keyset): the caller reads
437
+ * pages until one comes back empty.
438
+ */
439
+ listContingencyBlocks(input: {
440
+ readonly ownerId?: string;
441
+ readonly holder?: string;
442
+ readonly fates?: readonly ContingencyBlockFate[];
443
+ readonly reservedBefore?: string;
444
+ /** Leave out the blocks whose every number is accounted for. */
445
+ readonly unsettledOnly?: boolean;
446
+ readonly after?: {
447
+ readonly reservedAt: string;
448
+ readonly id: string;
449
+ };
450
+ readonly limit: number;
451
+ }): Promise<ContingencyBlockState[]>;
452
+ closeContingencyBlock(input: {
453
+ readonly id: string;
454
+ readonly fate: "CLOSED" | "ABANDONED";
455
+ readonly usedUpTo: number | null;
456
+ readonly at: string;
457
+ }): Promise<boolean>;
458
+ settleContingencyBlock(input: {
459
+ readonly id: string;
460
+ readonly at: string;
461
+ }): Promise<void>;
462
+ recordContingencyVoid(input: {
463
+ readonly id: string;
464
+ readonly blockId: string;
465
+ readonly range: NumberRange;
466
+ readonly protocol: string | null;
467
+ readonly eventXmlKey: string | null;
468
+ readonly at: string;
469
+ }): Promise<boolean>;
470
+ getDocumentByAccessKey(ownerId: string, accessKey: string): Promise<FiscalDocument | null>;
471
+ recordSignedDocument(document: FiscalDocument, event: FiscalDocumentEvent): Promise<FiscalDocument>;
472
+ }
473
+ /**
474
+ * What an offline register needs from the package that owns every number
475
+ * (FUT-4717), implemented by `createFiscalDocuments` over a store that is
476
+ * also a {@link ContingencyBlockStore}. A register that cannot reach the
477
+ * server signs on a block of its contingency series reserved in advance; back
338
478
  * online, it hands in what it signed, and the known rest of a finished block
339
- * is voided — an unknown range never is. The interface is named now so the
340
- * register's ticket builds against it; nothing in this release calls it.
479
+ * is voided — an unknown range never is.
341
480
  */
342
481
  interface ContingencyBlockSource {
343
- /** Reserve the next `size` numbers of the point's contingency series for one register. */
482
+ /** Reserve the next `size` (default 50) numbers of the point's contingency series for one holder. */
344
483
  reserveBlock(input: {
345
484
  readonly ownerId: string;
346
485
  readonly issuingPointId: string;
347
- readonly size: number;
348
- }): Promise<{
349
- readonly series: number;
350
- readonly from: number;
351
- readonly to: number;
352
- }>;
353
- /** Record an XML the register signed offline as a CONTINGENCY document of the block. */
486
+ readonly holder: string;
487
+ readonly size?: number;
488
+ }): Promise<ContingencyBlock>;
489
+ /**
490
+ * Record an XML the holder signed offline as the subject's `CONTINGENCY`
491
+ * document, owed a transmission now. Idempotent on the access key.
492
+ * `sale`: the sale as the host knows it; absent, the host's `SaleSource`
493
+ * answers it.
494
+ */
354
495
  recordSigned(input: {
355
496
  readonly ownerId: string;
356
497
  readonly subjectId: string;
357
498
  readonly signedXml: string;
499
+ readonly holder: string;
500
+ readonly sale?: SaleDraft;
358
501
  }): Promise<FiscalDocument>;
359
- /** The block is finished: void the numbers known unused (`sequenceUsed` tells which were). */
502
+ /**
503
+ * The holder is done with the block: `sequenceUsed` is the highest number
504
+ * it used (`from - 1`: none). The numbers above it are known unused.
505
+ */
360
506
  closeBlock(input: {
361
507
  readonly ownerId: string;
508
+ readonly holder: string;
362
509
  readonly series: number;
363
510
  readonly from: number;
364
511
  readonly sequenceUsed: number;
365
- }): Promise<void>;
512
+ }): Promise<ContingencyBlock>;
366
513
  }
367
514
 
368
515
  /**
@@ -452,4 +599,4 @@ declare const FISCAL_CERTIFICATE_EXPIRING = "fiscal.certificate-expiring";
452
599
  declare const FISCAL_DOCUMENT_NEEDS_ATTENTION = "fiscal.document-needs-attention";
453
600
  declare const FISCAL_CONTINGENCY_DEADLINE = "fiscal.contingency-deadline";
454
601
 
455
- export { type Cipher as C, type DocumentStorage as D, type EmitterProfile as E, type FiscalStore as F, type IssuingPoint as I, MAX_FAILURES as M, type NumberRequest as N, type SigningIdentityKind as S, type Transition as T, type FiscalNotifyPort as a, FISCAL_CERTIFICATE_EXPIRING as b, FISCAL_CONTINGENCY_DEADLINE as c, FISCAL_DOCUMENT_NEEDS_ATTENTION as d, FISCAL_DOCUMENT_REJECTED as e, type DocumentPolicy as f, type FiscalDocumentsConfig as g, type SaleDraft as h, type ContingencyBlockSource as i, DOCUMENT_POLICIES as j, DOCUMENT_TRANSITIONS as k, type DocumentInput as l, type EmitterProfileView as m, FINAL_STATUSES as n, type FiscalReasons as o, SIGNING_IDENTITY_KINDS as p, type SaleSource as q, type SigningIdentities as r, type SigningIdentity as s, canTransition as t, createPlatformIdentity as u, createSigningIdentities as v, createStoreCertificateIdentity as w, scrubSecrets as x, transition as y, viewOf as z };
602
+ export { canTransition as A, createPlatformIdentity as B, type Cipher as C, type DocumentStorage as D, type EmitterProfile as E, type FiscalStore as F, createSigningIdentities as G, createStoreCertificateIdentity as H, type IssuingPoint as I, scrubSecrets as J, transition as K, viewOf as L, MAX_FAILURES as M, type NumberRange as N, type SigningIdentityKind as S, type Transition as T, type FiscalNotifyPort as a, FISCAL_CERTIFICATE_EXPIRING as b, FISCAL_CONTINGENCY_DEADLINE as c, FISCAL_DOCUMENT_NEEDS_ATTENTION as d, FISCAL_DOCUMENT_REJECTED as e, type DocumentPolicy as f, type FiscalDocumentsConfig as g, type ContingencyGap as h, type ContingencyBlock as i, type SaleDraft as j, type ContingencyBlockFate as k, type ContingencyBlockState as l, type ContingencyBlockStore as m, CONTINGENCY_BLOCK_FATES as n, type ContingencyBlockSource as o, DOCUMENT_POLICIES as p, DOCUMENT_TRANSITIONS as q, type DocumentInput as r, type EmitterProfileView as s, FINAL_STATUSES as t, type FiscalReasons as u, type NumberRequest as v, SIGNING_IDENTITY_KINDS as w, type SaleSource as x, type SigningIdentities as y, type SigningIdentity as z };
@@ -40,6 +40,13 @@ interface DanfeNfceInput {
40
40
  readonly xml: string;
41
41
  readonly paperWidth: PaperWidth;
42
42
  readonly labels: DanfeNfceLabels;
43
+ /**
44
+ * Frame the contingency notice of a note signed offline and not yet
45
+ * authorised in a box (a `=` rule above and below it), the paper a register
46
+ * signing on its own prints (FUT-4717). Off by default: the paper is as it
47
+ * always was.
48
+ */
49
+ readonly contingencyBox?: boolean;
43
50
  }
44
51
  /** `1234` cents → `12,34`; thousands with a dot, as the DANFE prints money. */
45
52
  declare function money(value: string | null): string;
@@ -4,9 +4,9 @@ import {
4
4
  money,
5
5
  renderDanfeNfce,
6
6
  wrap
7
- } from "../chunk-MGTROA7K.js";
7
+ } from "../chunk-OAQSGDZ7.js";
8
8
  import "../chunk-PNTKG3DZ.js";
9
- import "../chunk-H33BK623.js";
9
+ import "../chunk-WRYCYXRA.js";
10
10
  import "../chunk-7QVYU63E.js";
11
11
  export {
12
12
  DANFE_COLUMNS,
@@ -1,11 +1,11 @@
1
- import { F as FiscalDocumentModel, l as SeriesKind, h as FiscalDocument, k as FiscalDocumentEvent } from '../types-BIJqm5GM.js';
2
- export { i as CancelOrReturnInput, j as CancelOrReturnResult, D as DocumentEventKind, n as DocumentTotals, o as FISCAL_DOCUMENT_MODELS, p as FISCAL_DOCUMENT_STATUSES, g as FiscalDocumentStatus, N as NumberVoid, O as OWED_VOIDS, q as isLive } from '../types-BIJqm5GM.js';
3
- import { h as SaleDraft, F as FiscalStore } from '../context-CLSMOSuf.js';
4
- export { C as Cipher, i as ContingencyBlockSource, j as DOCUMENT_POLICIES, k as DOCUMENT_TRANSITIONS, l as DocumentInput, f as DocumentPolicy, D as DocumentStorage, E as EmitterProfile, m as EmitterProfileView, n as FINAL_STATUSES, b as FISCAL_CERTIFICATE_EXPIRING, c as FISCAL_CONTINGENCY_DEADLINE, d as FISCAL_DOCUMENT_NEEDS_ATTENTION, e as FISCAL_DOCUMENT_REJECTED, g as FiscalDocumentsConfig, a as FiscalNotifyPort, o as FiscalReasons, I as IssuingPoint, M as MAX_FAILURES, N as NumberRequest, p as SIGNING_IDENTITY_KINDS, q as SaleSource, r as SigningIdentities, s as SigningIdentity, S as SigningIdentityKind, T as Transition, t as canTransition, u as createPlatformIdentity, v as createSigningIdentities, w as createStoreCertificateIdentity, x as scrubSecrets, y as transition, z as viewOf } from '../context-CLSMOSuf.js';
5
- export { C as CONTINGENCY_WARNING_AFTER_MS, a as CertificateFacts, b as CertificateUpload, E as EmitterProfileInput, F as FiscalDocuments, c as FiscalDocumentsServiceConfig, I as IssueInput, d as IssuingPointInput, L as LATE_CANCEL_CODES, S as SweepReport, e as createFiscalDocuments, p as parseCertificateUpload, f as parseIssuingPointInput, g as parseProfileInput } from '../service-hR3tgLpO.js';
6
- import { a as TaxBreakdown } from '../types-B1b8LIWX.js';
1
+ import { F as FiscalDocumentModel, o as SeriesKind, i as FiscalDocument, l as FiscalDocumentEvent } from '../types-Sk010Em2.js';
2
+ export { j as CancelOrReturnInput, k as CancelOrReturnResult, n as DocumentEventKind, D as DocumentTotals, p as FISCAL_DOCUMENT_MODELS, q as FISCAL_DOCUMENT_STATUSES, h as FiscalDocumentStatus, N as NumberVoid, O as OWED_VOIDS, r as isLive } from '../types-Sk010Em2.js';
3
+ import { j as SaleDraft, N as NumberRange, l as ContingencyBlockState, F as FiscalStore, m as ContingencyBlockStore, i as ContingencyBlock } from '../context-Cyvfr2YB.js';
4
+ export { n as CONTINGENCY_BLOCK_FATES, C as Cipher, k as ContingencyBlockFate, o as ContingencyBlockSource, h as ContingencyGap, p as DOCUMENT_POLICIES, q as DOCUMENT_TRANSITIONS, r as DocumentInput, f as DocumentPolicy, D as DocumentStorage, E as EmitterProfile, s as EmitterProfileView, t as FINAL_STATUSES, b as FISCAL_CERTIFICATE_EXPIRING, c as FISCAL_CONTINGENCY_DEADLINE, d as FISCAL_DOCUMENT_NEEDS_ATTENTION, e as FISCAL_DOCUMENT_REJECTED, g as FiscalDocumentsConfig, a as FiscalNotifyPort, u as FiscalReasons, I as IssuingPoint, M as MAX_FAILURES, v as NumberRequest, w as SIGNING_IDENTITY_KINDS, x as SaleSource, y as SigningIdentities, z as SigningIdentity, S as SigningIdentityKind, T as Transition, A as canTransition, B as createPlatformIdentity, G as createSigningIdentities, H as createStoreCertificateIdentity, J as scrubSecrets, K as transition, L as viewOf } from '../context-Cyvfr2YB.js';
5
+ import { l as SefazEnvironment } from '../types-Z5E14EPw.js';
6
+ export { C as CONTINGENCY_WARNING_AFTER_MS, a as CertificateFacts, b as CertificateUpload, E as EmitterProfileInput, F as FiscalDocuments, c as FiscalDocumentsServiceConfig, G as GapVoidReport, I as IssueInput, d as IssuingPointInput, L as LATE_CANCEL_CODES, e as LinkPaymentInput, f as LinkPaymentResult, M as MAX_PAYMENT_LINKS, S as SweepReport, g as createFiscalDocuments, p as parseCertificateUpload, h as parseIssuingPointInput, i as parseProfileInput } from '../service-BCK9aXop.js';
7
+ import { b as TaxBreakdown } from '../types-BLdkww6G.js';
7
8
  import { SaleForDocument, SaleLine } from '../sale/index.js';
8
- import '../sidecar/index.js';
9
9
 
10
10
  /**
11
11
  * Every refusal the document module makes, as a typed error with a `code`.
@@ -49,7 +49,14 @@ type FiscalDocumentErrorCode =
49
49
  * the buyer's return NF-e of entry answers a consumer's NFC-e only; an NF-e
50
50
  * past its window is the issuer's own correction, not this path's.
51
51
  */
52
- | "RETURN_OF_NFCE_ONLY";
52
+ | "RETURN_OF_NFCE_ONLY"
53
+ /**
54
+ * `recordSigned` (FUT-4717): an XML a holder signed offline that the package
55
+ * will not record — another CNPJ or environment, not a model 65, not
56
+ * `tpEmis = 9`, a key whose check digit or fields are wrong, or a number
57
+ * outside every block that holder was given. Nothing was recorded.
58
+ */
59
+ | "CONTINGENCY_XML_REFUSED";
53
60
  declare class FiscalDocumentError extends Error {
54
61
  readonly code: FiscalDocumentErrorCode;
55
62
  constructor(code: FiscalDocumentErrorCode, message: string);
@@ -74,7 +81,17 @@ declare const xmlKeys: {
74
81
  signedByDigest: (accessKey: string, digest: string) => string;
75
82
  authorized: (accessKey: string) => string;
76
83
  cancel: (accessKey: string) => string;
84
+ /** The event 110300 of `nSeqEvento` `sequence`. */
85
+ linkPayment: (accessKey: string, sequence: number) => string;
77
86
  inutilization: (document: FiscalDocument) => string;
87
+ /** A range of a contingency block voided at once (FUT-4717). */
88
+ inutilizedRange: (gap: {
89
+ environment: string;
90
+ ownerId: string;
91
+ series: number;
92
+ from: number;
93
+ to: number;
94
+ }) => string;
78
95
  };
79
96
  /**
80
97
  * Whether `key` is an access key as the layout writes one: 44 characters, the
@@ -94,37 +111,87 @@ declare function computeAccessKey(input: {
94
111
  }): string;
95
112
 
96
113
  /**
97
- * The reference {@link FiscalStore}: in memory, for tests and harnesses —
98
- * the role `createMemory*Store` plays in the packages that own storage seams.
99
- * It keeps the same promises as the SQL store (`./sql-store`): a draw and the
100
- * insert built from it commit together (a `build` that throws leaves the
101
- * counter untouched), a replaced document is advanced before its replacement
102
- * is inserted, and a subject has at most one live document per model.
114
+ * Contingency blocks (FUT-4717): numbers of an issuing point's contingency
115
+ * series handed to a holder in advance, the notes it signed on them recorded
116
+ * as the subjects' `CONTINGENCY` documents (transmitted by the same pass as
117
+ * the server's own), and the known rest of each block voided at SEFAZ.
118
+ *
119
+ * A station-signed note is transmitted from its stored XML exactly as the
120
+ * server's own contingency documents are (`transmit`): nothing rebuilds it
121
+ * from the sale. A rejection keeps its number (the buyer holds its DANFE):
122
+ * `resendContingency` re-signs it under the same number, as for any
123
+ * contingency NFC-e.
103
124
  */
104
125
 
105
- interface MemoryFiscalStore extends FiscalStore {
106
- /** Every event, in order, for assertions. */
107
- readonly events: FiscalDocumentEvent[];
108
- /** The next number each counter would hand out, keyed `cnpj|environment|model|series`. */
109
- readonly counters: Map<string, number>;
126
+ /** The block size when the caller names none (decided on FUT-4717: 50, a new block at 10 left). */
127
+ declare const DEFAULT_CONTINGENCY_BLOCK_SIZE = 50;
128
+ /** The largest block one call reserves. */
129
+ declare const MAX_CONTINGENCY_BLOCK_SIZE = 10000;
130
+
131
+ /**
132
+ * Which numbers of a contingency block are KNOWN unused and which are
133
+ * UNKNOWN — pure, from the block's state (FUT-4717). A holder signs its block
134
+ * in order and hands its notes in, in order, so:
135
+ *
136
+ * - below the highest number it handed in, a number with no document was
137
+ * never signed: KNOWN;
138
+ * - a CLOSED block's numbers above what the holder said it used are KNOWN;
139
+ * between the highest handed in and `usedUpTo` they were signed and are
140
+ * still to come: UNKNOWN until they arrive;
141
+ * - an ABANDONED block (its holder is gone) above the highest handed in may
142
+ * be on paper a buyer holds: UNKNOWN, flagged, never voided;
143
+ * - an OPEN block above the highest handed in is still in use: neither.
144
+ *
145
+ * A range already voided is neither.
146
+ */
147
+
148
+ interface BlockAccount {
149
+ readonly known: NumberRange[];
150
+ readonly unknown: NumberRange[];
110
151
  }
111
- declare function createMemoryFiscalStore(): MemoryFiscalStore;
152
+ /** The block's known and unknown ranges (see the module doc). */
153
+ declare function accountFor(block: ContingencyBlockState): BlockAccount;
112
154
 
113
155
  /**
114
- * The number draw, as one SQL statement over the package's migration
115
- * (`fiscal_number_counters`). A host's `FiscalStore.createDocument` runs it
116
- * and the document INSERT in ONE transaction: the row lock this UPDATE takes
117
- * serialises concurrent draws on a series, and a failed insert rolls the
118
- * counter back with it, so a series has no gap a failed write made. The only
119
- * gaps left are numbers SEFAZ never used (a rejection, a replaced document),
120
- * which the sweep inutilizes.
156
+ * Reading an NFC-e a holder signed offline (`tpEmis = 9`, no `nfeProc`) for
157
+ * `recordSigned`: the fields the document record keeps, each read from the
158
+ * XML, and every reason to refuse it. The XML is the fiscal service's own
159
+ * layout, so the DANFE's reader (`../danfe/xml`) reads it.
121
160
  *
122
- * Parameters: `$1` the issuer's CNPJ, `$2` environment, `$3` model, `$4` series,
123
- * `$5` issuing point id. No row comes back when the series is not that
124
- * point's; an exhausted series fails the counter's CHECK (at most
125
- * 1 000 000 000, the next number after 999 999 999), and the transaction with it.
161
+ * The access key is checked against the fields it encodes, not only its
162
+ * check digit: a key whose number or series disagrees with `ide` would let a
163
+ * holder record a number outside its block under a key inside it.
126
164
  */
127
- declare const FISCAL_NEXT_NUMBER_SQL = "UPDATE \"fiscal_number_counters\"\nSET \"next_number\" = \"next_number\" + 1, \"updated_at\" = CURRENT_TIMESTAMP\nWHERE \"issuer_cnpj\" = $1 AND \"environment\" = $2 AND \"model\" = $3 AND \"series\" = $4 AND \"issuing_point_id\" = $5\nRETURNING \"next_number\" - 1 AS \"number\"";
165
+
166
+ /** What a station-signed NFC-e says about itself. */
167
+ interface SignedContingencyNote {
168
+ readonly accessKey: string;
169
+ readonly issuerCnpj: string;
170
+ readonly environment: SefazEnvironment;
171
+ readonly series: number;
172
+ readonly number: number;
173
+ /** `cNF`. */
174
+ readonly keyCode: string;
175
+ /** `dhEmi`. */
176
+ readonly issuedAt: string;
177
+ /** `dhCont` and `xJust`. */
178
+ readonly contingency: {
179
+ readonly since: string;
180
+ readonly reason: string;
181
+ };
182
+ readonly totalCents: number;
183
+ readonly discountCents: number;
184
+ /** The consumer's CPF/CNPJ (or foreign id), or `null`. */
185
+ readonly buyerTaxId: string | null;
186
+ }
187
+ /**
188
+ * Parse and check a station-signed NFC-e. Refuses (`CONTINGENCY_XML_REFUSED`)
189
+ * anything but a model 65 signed in offline contingency (`tpEmis = 9`, with
190
+ * `dhCont` and `xJust`), a key whose check digit or fields are wrong, and an
191
+ * XML with no signature. The issuer's CNPJ and the block are the caller's to
192
+ * check against its profile and its blocks.
193
+ */
194
+ declare function parseSignedContingencyNote(signedXml: string): SignedContingencyNote;
128
195
 
129
196
  /**
130
197
  * `createPrismaFiscalStore` — the package's own {@link FiscalStore}, over the
@@ -158,7 +225,60 @@ interface FiscalPrismaClient extends FiscalSqlClient {
158
225
  }
159
226
  declare function createPrismaFiscalStore(config: {
160
227
  readonly prisma: FiscalPrismaClient;
161
- }): FiscalStore;
228
+ }): FiscalStore & ContingencyBlockStore;
229
+
230
+ /**
231
+ * The SQL half of contingency blocks (FUT-4717), over the package's migration
232
+ * (`fiscal_contingency_blocks`, `fiscal_contingency_voids`):
233
+ *
234
+ * - a block is ONE `UPDATE … SET next_number = next_number + size` on the
235
+ * series' counter row (the row `issueOffline` draws from), and its insert,
236
+ * in one transaction: the row lock serialises it with every other draw;
237
+ * - a signed note is its document and its event, in one transaction; the
238
+ * unique indexes on the key and the number make a second copy a `CONFLICT`.
239
+ */
240
+
241
+ /**
242
+ * Advance a contingency series' counter by a block. `$1` CNPJ, `$2`
243
+ * environment, `$3` model, `$4` series, `$5` issuing point, `$6` size. No row:
244
+ * not that point's contingency series; past the ceiling: the counter's CHECK.
245
+ */
246
+ declare const FISCAL_RESERVE_BLOCK_SQL = "UPDATE \"fiscal_number_counters\"\nSET \"next_number\" = \"next_number\" + $6::integer, \"updated_at\" = CURRENT_TIMESTAMP\nWHERE \"issuer_cnpj\" = $1 AND \"environment\" = $2 AND \"model\" = $3 AND \"series\" = $4 AND \"issuing_point_id\" = $5\n AND \"series_kind\" = 'CONTINGENCY'\nRETURNING \"next_number\" - $6::integer AS \"first\"";
247
+
248
+ /**
249
+ * The reference {@link FiscalStore}: in memory, for tests and harnesses —
250
+ * the role `createMemory*Store` plays in the packages that own storage seams.
251
+ * It keeps the same promises as the SQL store (`./sql-store`): a draw and the
252
+ * insert built from it commit together (a `build` that throws leaves the
253
+ * counter untouched), a replaced document is advanced before its replacement
254
+ * is inserted, and a subject has at most one live document per model.
255
+ */
256
+
257
+ interface MemoryFiscalStore extends FiscalStore, ContingencyBlockStore {
258
+ /** The contingency blocks, by id (FUT-4717). */
259
+ readonly blocks: Map<string, ContingencyBlock>;
260
+ /** Every event, in order, for assertions. */
261
+ readonly events: FiscalDocumentEvent[];
262
+ /** The next number each counter would hand out, keyed `cnpj|environment|model|series`. */
263
+ readonly counters: Map<string, number>;
264
+ }
265
+ declare function createMemoryFiscalStore(): MemoryFiscalStore;
266
+
267
+ /**
268
+ * The number draw, as one SQL statement over the package's migration
269
+ * (`fiscal_number_counters`). A host's `FiscalStore.createDocument` runs it
270
+ * and the document INSERT in ONE transaction: the row lock this UPDATE takes
271
+ * serialises concurrent draws on a series, and a failed insert rolls the
272
+ * counter back with it, so a series has no gap a failed write made. The only
273
+ * gaps left are numbers SEFAZ never used (a rejection, a replaced document),
274
+ * which the sweep inutilizes.
275
+ *
276
+ * Parameters: `$1` the issuer's CNPJ, `$2` environment, `$3` model, `$4` series,
277
+ * `$5` issuing point id. No row comes back when the series is not that
278
+ * point's; an exhausted series fails the counter's CHECK (at most
279
+ * 1 000 000 000, the next number after 999 999 999), and the transaction with it.
280
+ */
281
+ declare const FISCAL_NEXT_NUMBER_SQL = "UPDATE \"fiscal_number_counters\"\nSET \"next_number\" = \"next_number\" + 1, \"updated_at\" = CURRENT_TIMESTAMP\nWHERE \"issuer_cnpj\" = $1 AND \"environment\" = $2 AND \"model\" = $3 AND \"series\" = $4 AND \"issuing_point_id\" = $5\nRETURNING \"next_number\" - 1 AS \"number\"";
162
282
 
163
283
  /**
164
284
  * The document mapping's tax half: the engine's breakdown (`computeTax`)
@@ -184,4 +304,4 @@ declare function createPrismaFiscalStore(config: {
184
304
  type LineDetails = Omit<SaleLine, "id" | "quantity" | "valueCents" | "ibsCbs">;
185
305
  declare function documentLines(breakdown: TaxBreakdown, details: Readonly<Record<string, LineDetails>>): SaleLine[];
186
306
 
187
- export { FISCAL_NEXT_NUMBER_SQL, FiscalDocument, FiscalDocumentError, type FiscalDocumentErrorCode, FiscalDocumentEvent, FiscalDocumentModel, type FiscalPrismaClient, type FiscalSqlClient, FiscalStore, type LineDetails, type MemoryFiscalStore, SaleDraft, SeriesKind, computeAccessKey, createMemoryFiscalStore, createPrismaFiscalStore, documentLines, draftOf, drawKeyCode, isValidAccessKey, localIso, xmlKeys };
307
+ export { type BlockAccount, ContingencyBlock, ContingencyBlockState, ContingencyBlockStore, DEFAULT_CONTINGENCY_BLOCK_SIZE, FISCAL_NEXT_NUMBER_SQL, FISCAL_RESERVE_BLOCK_SQL, FiscalDocument, FiscalDocumentError, type FiscalDocumentErrorCode, FiscalDocumentEvent, FiscalDocumentModel, type FiscalPrismaClient, type FiscalSqlClient, FiscalStore, type LineDetails, MAX_CONTINGENCY_BLOCK_SIZE, type MemoryFiscalStore, NumberRange, SaleDraft, SeriesKind, type SignedContingencyNote, accountFor as accountForContingencyBlock, computeAccessKey, createMemoryFiscalStore, createPrismaFiscalStore, documentLines, draftOf, drawKeyCode, isValidAccessKey, localIso, parseSignedContingencyNote, xmlKeys };