@12-apps/fiscal 1.5.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 (71) hide show
  1. package/README.md +46 -4
  2. package/dist/{chunk-HMTPJWXM.js → chunk-2JVTHJAU.js} +2 -2
  3. package/dist/{chunk-3E3NBXSW.js → chunk-CEK2GDRY.js} +5 -3
  4. package/dist/chunk-CEK2GDRY.js.map +1 -0
  5. package/dist/{chunk-MGTROA7K.js → chunk-OAQSGDZ7.js} +11 -7
  6. package/dist/chunk-OAQSGDZ7.js.map +1 -0
  7. package/dist/{chunk-G6QNU4FD.js → chunk-P7CRGZGO.js} +2 -2
  8. package/dist/{chunk-H33BK623.js → chunk-WRYCYXRA.js} +1 -1
  9. package/dist/{chunk-H33BK623.js.map → chunk-WRYCYXRA.js.map} +1 -1
  10. package/dist/{chunk-TJCUO6D6.js → chunk-YHSO3476.js} +6 -5
  11. package/dist/chunk-YHSO3476.js.map +1 -0
  12. package/dist/{context-CwZiHLnY.d.ts → context-Cyvfr2YB.d.ts} +155 -19
  13. package/dist/danfe/index.d.ts +7 -0
  14. package/dist/danfe/index.js +2 -2
  15. package/dist/documents/index.d.ts +152 -34
  16. package/dist/documents/index.js +1103 -305
  17. package/dist/documents/index.js.map +1 -1
  18. package/dist/engine/index.d.ts +2 -2
  19. package/dist/http.d.ts +6 -5
  20. package/dist/http.js +4 -4
  21. package/dist/issuer/index.d.ts +10 -3
  22. package/dist/issuer/index.js +18 -3
  23. package/dist/issuer/index.js.map +1 -1
  24. package/dist/jobs.d.ts +5 -5
  25. package/dist/jobs.js +3 -3
  26. package/dist/manifest/index.d.ts +6 -4
  27. package/dist/manifest/index.js.map +1 -1
  28. package/dist/manifest/server.d.ts +5 -5
  29. package/dist/manifest/server.js +6 -6
  30. package/dist/notifications.d.ts +4 -4
  31. package/dist/notifications.js +2 -2
  32. package/dist/{service-Cz2O84Xr.d.ts → service-BCK9aXop.d.ts} +64 -5
  33. package/dist/sidecar/index.d.ts +38 -249
  34. package/dist/sidecar/index.js +29 -1
  35. package/dist/sidecar/index.js.map +1 -1
  36. package/dist/{types-B1b8LIWX.d.ts → types-BLdkww6G.d.ts} +1 -1
  37. package/dist/{types-DSYwap42.d.ts → types-Sk010Em2.d.ts} +2 -2
  38. package/dist/types-Z5E14EPw.d.ts +254 -0
  39. package/package.json +2 -1
  40. package/prisma/fiscal.prisma +50 -1
  41. package/prisma/migrations/20261118180000_fiscal_contingency_blocks/migration.sql +64 -0
  42. package/sidecar/README.md +52 -1
  43. package/sidecar/bin/check-platform.php +29 -0
  44. package/sidecar/extensions.json +12 -0
  45. package/sidecar/src/Http/Request.php +6 -1
  46. package/sidecar/src/Kernel.php +39 -1
  47. package/sidecar/src/Platform.php +84 -0
  48. package/src/danfe/render.ts +16 -5
  49. package/src/documents/contingency-gaps.ts +88 -0
  50. package/src/documents/contingency-pass.ts +157 -0
  51. package/src/documents/contingency-xml.ts +136 -0
  52. package/src/documents/contingency.ts +257 -0
  53. package/src/documents/errors.ts +8 -1
  54. package/src/documents/helpers.ts +3 -0
  55. package/src/documents/index.ts +23 -1
  56. package/src/documents/memory-blocks.ts +118 -0
  57. package/src/documents/memory.ts +6 -2
  58. package/src/documents/ports.ts +163 -13
  59. package/src/documents/service.ts +10 -0
  60. package/src/documents/sql-blocks.ts +202 -0
  61. package/src/documents/sql-store.ts +4 -3
  62. package/src/http.ts +1 -0
  63. package/src/issuer/sidecar.ts +27 -3
  64. package/src/manifest/index.ts +6 -4
  65. package/src/sidecar/index.ts +2 -0
  66. package/src/sidecar/platform.ts +55 -0
  67. package/dist/chunk-3E3NBXSW.js.map +0 -1
  68. package/dist/chunk-MGTROA7K.js.map +0 -1
  69. package/dist/chunk-TJCUO6D6.js.map +0 -1
  70. /package/dist/{chunk-HMTPJWXM.js.map → chunk-2JVTHJAU.js.map} +0 -0
  71. /package/dist/{chunk-G6QNU4FD.js.map → chunk-P7CRGZGO.js.map} +0 -0
@@ -1,7 +1,7 @@
1
- import { F as FiscalDocumentModel, o as DocumentTotals, D as DocumentEventKind, h as FiscalDocumentStatus, i as FiscalDocument, l as FiscalDocumentEvent, n as SeriesKind, g as SigningMaterial, I as Issuer } from './types-DSYwap42.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
2
  import { IssuerTaxRegime, Address, SaleForDocument, LinkedTransaction } from './sale/index.js';
3
- import { SefazEnvironment, IssuedDocument, SidecarErrorBody, ContingencySignedDocument, ContingencyEntry, CancelledDocument, LookedUpDocument, InutilizedRange, RegisteredPaymentLink } from './sidecar/index.js';
4
- import { T as TaxRegime } from './types-B1b8LIWX.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
@@ -342,38 +342,174 @@ interface FiscalStore {
342
342
  /** Profiles whose certificate expires before `before`, across owners. */
343
343
  listExpiringCertificates(before: string): Promise<EmitterProfile[]>;
344
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[];
358
+ /**
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
+ }
345
402
  /**
346
- * DECLARED, NOT IMPLEMENTED (FUT-4717): what an offline register needs from
347
- * the package that owns every number. A register that cannot reach the server
348
- * signs on a block of its contingency series reserved in advance; back
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
349
478
  * online, it hands in what it signed, and the known rest of a finished block
350
- * is voided — an unknown range never is. The interface is named now so the
351
- * register's ticket builds against it; nothing in this release calls it.
479
+ * is voided — an unknown range never is.
352
480
  */
353
481
  interface ContingencyBlockSource {
354
- /** 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. */
355
483
  reserveBlock(input: {
356
484
  readonly ownerId: string;
357
485
  readonly issuingPointId: string;
358
- readonly size: number;
359
- }): Promise<{
360
- readonly series: number;
361
- readonly from: number;
362
- readonly to: number;
363
- }>;
364
- /** 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
+ */
365
495
  recordSigned(input: {
366
496
  readonly ownerId: string;
367
497
  readonly subjectId: string;
368
498
  readonly signedXml: string;
499
+ readonly holder: string;
500
+ readonly sale?: SaleDraft;
369
501
  }): Promise<FiscalDocument>;
370
- /** 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
+ */
371
506
  closeBlock(input: {
372
507
  readonly ownerId: string;
508
+ readonly holder: string;
373
509
  readonly series: number;
374
510
  readonly from: number;
375
511
  readonly sequenceUsed: number;
376
- }): Promise<void>;
512
+ }): Promise<ContingencyBlock>;
377
513
  }
378
514
 
379
515
  /**
@@ -463,4 +599,4 @@ declare const FISCAL_CERTIFICATE_EXPIRING = "fiscal.certificate-expiring";
463
599
  declare const FISCAL_DOCUMENT_NEEDS_ATTENTION = "fiscal.document-needs-attention";
464
600
  declare const FISCAL_CONTINGENCY_DEADLINE = "fiscal.contingency-deadline";
465
601
 
466
- 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, n as SeriesKind, i as FiscalDocument, l as FiscalDocumentEvent } from '../types-DSYwap42.js';
2
- export { j as CancelOrReturnInput, k as CancelOrReturnResult, D as DocumentEventKind, o 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-DSYwap42.js';
3
- import { h as SaleDraft, F as FiscalStore } from '../context-CwZiHLnY.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-CwZiHLnY.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, 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-Cz2O84Xr.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);
@@ -77,6 +84,14 @@ declare const xmlKeys: {
77
84
  /** The event 110300 of `nSeqEvento` `sequence`. */
78
85
  linkPayment: (accessKey: string, sequence: number) => string;
79
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;
80
95
  };
81
96
  /**
82
97
  * Whether `key` is an access key as the layout writes one: 44 characters, the
@@ -96,37 +111,87 @@ declare function computeAccessKey(input: {
96
111
  }): string;
97
112
 
98
113
  /**
99
- * The reference {@link FiscalStore}: in memory, for tests and harnesses —
100
- * the role `createMemory*Store` plays in the packages that own storage seams.
101
- * It keeps the same promises as the SQL store (`./sql-store`): a draw and the
102
- * insert built from it commit together (a `build` that throws leaves the
103
- * counter untouched), a replaced document is advanced before its replacement
104
- * 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.
105
124
  */
106
125
 
107
- interface MemoryFiscalStore extends FiscalStore {
108
- /** Every event, in order, for assertions. */
109
- readonly events: FiscalDocumentEvent[];
110
- /** The next number each counter would hand out, keyed `cnpj|environment|model|series`. */
111
- 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[];
112
151
  }
113
- declare function createMemoryFiscalStore(): MemoryFiscalStore;
152
+ /** The block's known and unknown ranges (see the module doc). */
153
+ declare function accountFor(block: ContingencyBlockState): BlockAccount;
114
154
 
115
155
  /**
116
- * The number draw, as one SQL statement over the package's migration
117
- * (`fiscal_number_counters`). A host's `FiscalStore.createDocument` runs it
118
- * and the document INSERT in ONE transaction: the row lock this UPDATE takes
119
- * serialises concurrent draws on a series, and a failed insert rolls the
120
- * counter back with it, so a series has no gap a failed write made. The only
121
- * gaps left are numbers SEFAZ never used (a rejection, a replaced document),
122
- * 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.
123
160
  *
124
- * Parameters: `$1` the issuer's CNPJ, `$2` environment, `$3` model, `$4` series,
125
- * `$5` issuing point id. No row comes back when the series is not that
126
- * point's; an exhausted series fails the counter's CHECK (at most
127
- * 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.
128
164
  */
129
- 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;
130
195
 
131
196
  /**
132
197
  * `createPrismaFiscalStore` — the package's own {@link FiscalStore}, over the
@@ -160,7 +225,60 @@ interface FiscalPrismaClient extends FiscalSqlClient {
160
225
  }
161
226
  declare function createPrismaFiscalStore(config: {
162
227
  readonly prisma: FiscalPrismaClient;
163
- }): 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\"";
164
282
 
165
283
  /**
166
284
  * The document mapping's tax half: the engine's breakdown (`computeTax`)
@@ -186,4 +304,4 @@ declare function createPrismaFiscalStore(config: {
186
304
  type LineDetails = Omit<SaleLine, "id" | "quantity" | "valueCents" | "ibsCbs">;
187
305
  declare function documentLines(breakdown: TaxBreakdown, details: Readonly<Record<string, LineDetails>>): SaleLine[];
188
306
 
189
- 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 };