@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,156 @@
1
+ /**
2
+ * The event 110300 "Vinculação Pagamento" (NT 2026.006 v1.00 §5.1): a payment
3
+ * transaction linked to an authorised document after the fact — a Pix QR whose
4
+ * txid was learnt only once the note was out, say. One event per transaction
5
+ * (the event's single `gPgto`), numbered per document (`nSeqEvento`).
6
+ *
7
+ * Idempotent per `(document, transactionId)`: a transaction the document
8
+ * already carries in its own `gPgtoVinc`, or already linked by an earlier
9
+ * event, is skipped with no call to SEFAZ. A refusal answers the issuer's
10
+ * failure and records nothing; the caller may ask again. `nSeqEvento` is the
11
+ * next after the document's own recorded events; a 573 at it is settled by the
12
+ * event SEFAZ holds there (its XML kept, its transaction recorded as its own),
13
+ * and the payment is then sent at the next sequence.
14
+ */
15
+
16
+ import type { IssuerFailure } from "../issuer/port";
17
+ import type { LinkedTransaction, PaymentLinkMeans } from "../sale/types";
18
+ import type { RegisteredPaymentLink } from "../sidecar/types";
19
+ import { xmlKeys } from "./context";
20
+ import { FiscalDocumentError } from "./errors";
21
+ import type { Deps } from "./service-profile";
22
+ import type { FiscalDocument, FiscalDocumentEvent } from "./types";
23
+
24
+ /** `nSeqEvento` runs 1–20 per event type and document. */
25
+ export const MAX_PAYMENT_LINKS = 20;
26
+
27
+ export interface LinkPaymentInput {
28
+ readonly ownerId: string;
29
+ readonly documentId: string;
30
+ readonly payments: readonly LinkedTransaction[];
31
+ }
32
+
33
+ export interface LinkPaymentResult {
34
+ /** The transaction ids SEFAZ registered in this call. */
35
+ readonly linked: readonly string[];
36
+ /** Those the document already carried or an earlier event linked: nothing was sent. */
37
+ readonly alreadyLinked: readonly string[];
38
+ /** The first refusal, if any; the transactions after it were not sent. */
39
+ readonly failure: IssuerFailure | null;
40
+ readonly document: FiscalDocument;
41
+ }
42
+
43
+ /** Each 110300 the document's events record: the transaction and its `nSeqEvento`. */
44
+ function linkedByEvents(events: readonly FiscalDocumentEvent[]): Array<{ transactionId: string; sequence: number }> {
45
+ return events
46
+ .filter((event) => event.kind === "LINK_PAYMENT")
47
+ .map((event, index) => {
48
+ const answer = event.answer as { payment?: { transactionId?: unknown }; sequence?: unknown } | null;
49
+ return {
50
+ transactionId: answer?.payment?.transactionId,
51
+ sequence: typeof answer?.sequence === "number" ? answer.sequence : index + 1,
52
+ };
53
+ })
54
+ .filter((link): link is { transactionId: string; sequence: number } => typeof link.transactionId === "string");
55
+ }
56
+
57
+ /** The transaction ids the document's own `gPgtoVinc` carries. */
58
+ function linkedInDocument(document: FiscalDocument): string[] {
59
+ return document.sale.payments
60
+ .map((payment) => payment.linkedTransaction?.transactionId)
61
+ .filter((id): id is string => typeof id === "string");
62
+ }
63
+
64
+ /** What every event of this document is sent with: its key, its protocol and the issuer's event call. */
65
+ function linkable(deps: Deps, document: FiscalDocument) {
66
+ const { accessKey, protocol } = document;
67
+ if (document.status !== "AUTHORIZED" || accessKey === null || protocol === null) {
68
+ throw new FiscalDocumentError("TRANSITION_REFUSED", `document ${document.id} is ${document.status}; only an authorised document is linked.`);
69
+ }
70
+ const send = deps.config.issuer.linkPayment;
71
+ if (typeof send !== "function") throw new FiscalDocumentError("NOT_SUPPORTED", "this issuer does not register the event 110300.");
72
+ return { accessKey, protocol, send: send.bind(deps.config.issuer) };
73
+ }
74
+
75
+ /**
76
+ * The transaction SEFAZ holds at the sequence just sent. A 135 registered what
77
+ * was sent. A 573 answers the event already there, looked up: the same
78
+ * transaction (a retry whose recording was lost), or another one, which is
79
+ * then recorded as ITS link and never attributed to `sent`.
80
+ */
81
+ function heldTransaction(answer: RegisteredPaymentLink, sent: LinkedTransaction, requested: readonly LinkedTransaction[]): LinkedTransaction {
82
+ if (answer.statusCode !== "573" || answer.transaction.transactionId === sent.transactionId) return sent;
83
+ const held = answer.transaction;
84
+ return (
85
+ requested.find((payment) => payment.transactionId === held.transactionId) ?? {
86
+ transactionId: held.transactionId,
87
+ meansCode: held.meansCode as PaymentLinkMeans,
88
+ pspCnpjBase: held.pspCnpjBase,
89
+ receiverCnpj: held.receiverCnpj,
90
+ }
91
+ );
92
+ }
93
+
94
+ /** One call's progress: the document as last advanced, the next `nSeqEvento`, what is linked. */
95
+ interface LinkRun {
96
+ document: FiscalDocument;
97
+ sequence: number;
98
+ readonly known: Set<string>;
99
+ readonly requested: readonly LinkedTransaction[];
100
+ readonly linked: string[];
101
+ readonly send: (sequence: number, payment: LinkedTransaction) => ReturnType<NonNullable<Deps["config"]["issuer"]["linkPayment"]>>;
102
+ }
103
+
104
+ function refuseOverLimit(document: FiscalDocument): never {
105
+ throw new FiscalDocumentError("INVALID_INPUT", `document ${document.id} cannot take more than ${MAX_PAYMENT_LINKS} payment links.`);
106
+ }
107
+
108
+ /**
109
+ * Sends `payment` at the run's sequence and records what SEFAZ holds there.
110
+ * When that is another transaction (a 573), it is recorded as its own link and
111
+ * `payment` goes out again at the next sequence. Answers the refusal, if any.
112
+ */
113
+ async function sendOne(deps: Deps, run: LinkRun, accessKey: string, payment: LinkedTransaction): Promise<IssuerFailure | null> {
114
+ if (run.sequence > MAX_PAYMENT_LINKS) refuseOverLimit(run.document);
115
+ const sequence = run.sequence;
116
+ const outcome = await run.send(sequence, payment);
117
+ if (!outcome.ok) return outcome.error;
118
+ const held = heldTransaction(outcome.answer, payment, run.requested);
119
+ const { eventXml } = outcome.answer;
120
+ const eventXmlKey = eventXml === null ? null : xmlKeys.linkPayment(accessKey, sequence);
121
+ if (eventXmlKey !== null && eventXml !== null) await deps.config.storage.put(eventXmlKey, eventXml, "application/xml");
122
+ run.document = await deps.ctx.advance(run.document, { kind: "LINK_PAYMENT", answer: outcome.answer, payment: held, sequence, eventXmlKey });
123
+ run.known.add(held.transactionId);
124
+ if (run.requested.some((one) => one.transactionId === held.transactionId)) run.linked.push(held.transactionId);
125
+ run.sequence = sequence + 1;
126
+ return held.transactionId === payment.transactionId ? null : sendOne(deps, run, accessKey, payment);
127
+ }
128
+
129
+ export async function linkPayment(deps: Deps, input: LinkPaymentInput): Promise<LinkPaymentResult> {
130
+ const document = await deps.config.store.getDocument(input.ownerId, input.documentId);
131
+ if (document === null) throw new FiscalDocumentError("NOT_FOUND", `owner ${input.ownerId} has no document ${input.documentId}.`);
132
+ const { accessKey, protocol, send } = linkable(deps, document);
133
+ const byEvents = linkedByEvents(await deps.config.store.listEvents(document.id));
134
+ const known = new Set([...linkedInDocument(document), ...byEvents.map((link) => link.transactionId)]);
135
+ const pending = input.payments.filter((payment) => !known.has(payment.transactionId));
136
+ const alreadyLinked = input.payments.filter((payment) => known.has(payment.transactionId)).map((payment) => payment.transactionId);
137
+ // `nSeqEvento` follows the document's own events, never a count of anything else.
138
+ const sequence = Math.max(0, ...byEvents.map((link) => link.sequence)) + 1;
139
+ if (sequence - 1 + pending.length > MAX_PAYMENT_LINKS) refuseOverLimit(document);
140
+ if (pending.length === 0) return { linked: [], alreadyLinked, failure: null, document };
141
+ const signing = await deps.ctx.material(await deps.ctx.requireProfile(input.ownerId));
142
+ const run: LinkRun = {
143
+ document,
144
+ sequence,
145
+ known,
146
+ requested: pending,
147
+ linked: [],
148
+ send: (at, payment) => send({ model: document.model, environment: document.environment, signing, accessKey, protocol, sequence: at, payments: [payment] }),
149
+ };
150
+ for (const payment of pending) {
151
+ if (run.known.has(payment.transactionId)) continue;
152
+ const failure = await sendOne(deps, run, accessKey, payment);
153
+ if (failure !== null) return { linked: run.linked, alreadyLinked, failure, document: run.document };
154
+ }
155
+ return { linked: run.linked, alreadyLinked, failure: null, document: run.document };
156
+ }
@@ -108,23 +108,173 @@ export interface FiscalStore {
108
108
  listExpiringCertificates(before: string): Promise<EmitterProfile[]>;
109
109
  }
110
110
 
111
+ /** A run of numbers of one series, both ends included. */
112
+ export interface NumberRange {
113
+ readonly from: number;
114
+ readonly to: number;
115
+ }
116
+
117
+ /**
118
+ * - `OPEN`: the holder may still sign on it.
119
+ * - `CLOSED`: the holder said it is done with it and how far it got (`usedUpTo`).
120
+ * - `ABANDONED`: the holder is gone (a new install took its place): what it
121
+ * signed above the highest number it handed in is unknown, never voided.
122
+ */
123
+ export type ContingencyBlockFate = "OPEN" | "CLOSED" | "ABANDONED";
124
+
125
+ export const CONTINGENCY_BLOCK_FATES: readonly ContingencyBlockFate[] = ["OPEN", "CLOSED", "ABANDONED"];
126
+
127
+ /**
128
+ * Numbers of an issuing point's contingency series reserved for one holder
129
+ * (the host's opaque id of a register that may go offline) to sign on with no
130
+ * server. Drawn from the series' ONE counter — the counter the server's own
131
+ * contingency (`issueOffline`, going offline after a silent SEFAZ) draws from
132
+ * — so nothing else is ever numbered inside a block.
133
+ */
134
+ export interface ContingencyBlock extends NumberRange {
135
+ readonly id: string;
136
+ readonly ownerId: string;
137
+ readonly issuingPointId: string;
138
+ readonly issuerCnpj: string;
139
+ readonly environment: SefazEnvironment;
140
+ readonly model: "NFCE";
141
+ readonly series: number;
142
+ readonly holder: string;
143
+ readonly fate: ContingencyBlockFate;
144
+ /** The highest number the holder said it used when it closed the block (`from - 1`: none); `null` otherwise. */
145
+ readonly usedUpTo: number | null;
146
+ readonly reservedAt: string;
147
+ readonly closedAt: string | null;
148
+ /** When every number of the block was accounted for (a document, or voided); `null` while one is not. */
149
+ readonly settledAt: string | null;
150
+ }
151
+
152
+ /** A block, with the numbers recorded on it and the ranges voided at SEFAZ. */
153
+ export interface ContingencyBlockState extends ContingencyBlock {
154
+ /** Numbers inside the block that carry a document, ascending. */
155
+ readonly documented: readonly number[];
156
+ readonly voided: readonly NumberRange[];
157
+ }
158
+
159
+ /**
160
+ * A range of a block with no document: KNOWN unused (voided by
161
+ * `voidKnownGaps`) or UNKNOWN (flagged for the store, never voided).
162
+ */
163
+ export interface ContingencyGap extends NumberRange {
164
+ readonly blockId: string;
165
+ readonly ownerId: string;
166
+ readonly issuingPointId: string;
167
+ readonly issuerCnpj: string;
168
+ readonly environment: SefazEnvironment;
169
+ readonly series: number;
170
+ readonly holder: string;
171
+ readonly reservedAt: string;
172
+ }
173
+
111
174
  /**
112
- * DECLARED, NOT IMPLEMENTED (FUT-4717): what an offline register needs from
113
- * the package that owns every number. A register that cannot reach the server
114
- * signs on a block of its contingency series reserved in advance; back
175
+ * The rows behind contingency blocks (FUT-4717). Both of the package's stores
176
+ * implement it (`createPrismaFiscalStore`, `createMemoryFiscalStore`); a host
177
+ * with its own `FiscalStore` and without these gets `NOT_SUPPORTED` from the
178
+ * block methods of the service, and everything else as before.
179
+ *
180
+ * - `reserveContingencyBlock` advances the series' counter by `size` and
181
+ * records the block, in one transaction (no row back: not that point's
182
+ * contingency series; past 999 999 999: `SERIES_EXHAUSTED`).
183
+ * - `recordSignedDocument` inserts a document and its event together; a
184
+ * second live document of the subject is `SUBJECT_HAS_DOCUMENT`, a key or
185
+ * number recorded already is `CONFLICT`.
186
+ * - `closeContingencyBlock` moves an OPEN block only (`false` otherwise).
187
+ * - `recordContingencyVoid` records a voided range once (`false` when the
188
+ * range was recorded before).
189
+ */
190
+ export interface ContingencyBlockStore {
191
+ reserveContingencyBlock(input: {
192
+ readonly request: NumberRequest;
193
+ readonly size: number;
194
+ readonly id: string;
195
+ readonly holder: string;
196
+ readonly at: string;
197
+ }): Promise<ContingencyBlock>;
198
+ /** The block holding `number` of the series, whoever holds it, with its documents and voids. */
199
+ findContingencyBlock(input: {
200
+ readonly ownerId: string;
201
+ readonly issuerCnpj: string;
202
+ readonly environment: SefazEnvironment;
203
+ readonly series: number;
204
+ readonly number: number;
205
+ }): Promise<ContingencyBlockState | null>;
206
+ /**
207
+ * One page of the blocks a filter selects, ordered by `(reservedAt, id)`;
208
+ * `after` is the last block of the previous page (keyset): the caller reads
209
+ * pages until one comes back empty.
210
+ */
211
+ listContingencyBlocks(input: {
212
+ readonly ownerId?: string;
213
+ readonly holder?: string;
214
+ readonly fates?: readonly ContingencyBlockFate[];
215
+ readonly reservedBefore?: string;
216
+ /** Leave out the blocks whose every number is accounted for. */
217
+ readonly unsettledOnly?: boolean;
218
+ readonly after?: { readonly reservedAt: string; readonly id: string };
219
+ readonly limit: number;
220
+ }): Promise<ContingencyBlockState[]>;
221
+ closeContingencyBlock(input: {
222
+ readonly id: string;
223
+ readonly fate: "CLOSED" | "ABANDONED";
224
+ readonly usedUpTo: number | null;
225
+ readonly at: string;
226
+ }): Promise<boolean>;
227
+ settleContingencyBlock(input: { readonly id: string; readonly at: string }): Promise<void>;
228
+ recordContingencyVoid(input: {
229
+ readonly id: string;
230
+ readonly blockId: string;
231
+ readonly range: NumberRange;
232
+ readonly protocol: string | null;
233
+ readonly eventXmlKey: string | null;
234
+ readonly at: string;
235
+ }): Promise<boolean>;
236
+ getDocumentByAccessKey(ownerId: string, accessKey: string): Promise<FiscalDocument | null>;
237
+ recordSignedDocument(document: FiscalDocument, event: FiscalDocumentEvent): Promise<FiscalDocument>;
238
+ }
239
+
240
+ /**
241
+ * What an offline register needs from the package that owns every number
242
+ * (FUT-4717), implemented by `createFiscalDocuments` over a store that is
243
+ * also a {@link ContingencyBlockStore}. A register that cannot reach the
244
+ * server signs on a block of its contingency series reserved in advance; back
115
245
  * online, it hands in what it signed, and the known rest of a finished block
116
- * is voided — an unknown range never is. The interface is named now so the
117
- * register's ticket builds against it; nothing in this release calls it.
246
+ * is voided — an unknown range never is.
118
247
  */
119
248
  export interface ContingencyBlockSource {
120
- /** Reserve the next `size` numbers of the point's contingency series for one register. */
121
- reserveBlock(input: { readonly ownerId: string; readonly issuingPointId: string; readonly size: number }): Promise<{
249
+ /** Reserve the next `size` (default 50) numbers of the point's contingency series for one holder. */
250
+ reserveBlock(input: {
251
+ readonly ownerId: string;
252
+ readonly issuingPointId: string;
253
+ readonly holder: string;
254
+ readonly size?: number;
255
+ }): Promise<ContingencyBlock>;
256
+ /**
257
+ * Record an XML the holder signed offline as the subject's `CONTINGENCY`
258
+ * document, owed a transmission now. Idempotent on the access key.
259
+ * `sale`: the sale as the host knows it; absent, the host's `SaleSource`
260
+ * answers it.
261
+ */
262
+ recordSigned(input: {
263
+ readonly ownerId: string;
264
+ readonly subjectId: string;
265
+ readonly signedXml: string;
266
+ readonly holder: string;
267
+ readonly sale?: SaleDraft;
268
+ }): Promise<FiscalDocument>;
269
+ /**
270
+ * The holder is done with the block: `sequenceUsed` is the highest number
271
+ * it used (`from - 1`: none). The numbers above it are known unused.
272
+ */
273
+ closeBlock(input: {
274
+ readonly ownerId: string;
275
+ readonly holder: string;
122
276
  readonly series: number;
123
277
  readonly from: number;
124
- readonly to: number;
125
- }>;
126
- /** Record an XML the register signed offline as a CONTINGENCY document of the block. */
127
- recordSigned(input: { readonly ownerId: string; readonly subjectId: string; readonly signedXml: string }): Promise<FiscalDocument>;
128
- /** The block is finished: void the numbers known unused (`sequenceUsed` tells which were). */
129
- closeBlock(input: { readonly ownerId: string; readonly series: number; readonly from: number; readonly sequenceUsed: number }): Promise<void>;
278
+ readonly sequenceUsed: number;
279
+ }): Promise<ContingencyBlock>;
130
280
  }
@@ -18,11 +18,14 @@ import { FiscalDocumentError } from "./errors";
18
18
  import { canTransition } from "./machine";
19
19
  import { type Deps, type FiscalDocumentsServiceConfig, createIssuingPoint, saveProfile, uploadCertificate } from "./service-profile";
20
20
  import { settleNumber, settleWithXml, storeNfeProc } from "./settle";
21
+ import { linkPayment } from "./payment-link";
22
+ import { abandonBlocks, closeBlock, listBlocks, listKnownGaps, listUnknownRanges, recordSigned, reserveBlock, voidKnownGaps } from "./contingency";
21
23
  import { answerLive, assertOnlineDeadline, signPending, submit, transmit } from "./steps";
22
24
  import { type CancelOrReturnInput, type CancelOrReturnResult, type DocumentTotals, type FiscalDocument, type FiscalDocumentModel, isLive } from "./types";
23
25
 
24
26
  export type { CertificateFacts, FiscalDocumentsServiceConfig } from "./service-profile";
25
27
  export type { CancelOrReturnInput, CancelOrReturnResult } from "./types";
28
+ export type { LinkPaymentInput, LinkPaymentResult } from "./payment-link";
26
29
 
27
30
  export interface SweepReport {
28
31
  readonly advanced: Array<{ readonly documentId: string; readonly status: FiscalDocument["status"] }>;
@@ -356,6 +359,8 @@ export function createFiscalDocuments(config: FiscalDocumentsServiceConfig) {
356
359
  * (501) — issue the buyer's return NF-e of entry quoting it. Idempotent.
357
360
  */
358
361
  cancelOrReturn: cancelOrReturn.bind(null, deps),
362
+ /** Link payment transactions to an authorised document (event 110300), once each. Idempotent. */
363
+ linkPayment: linkPayment.bind(null, deps),
359
364
  /** Ask SEFAZ what it knows of the key; a state the answer moves is recorded. */
360
365
  lookup: lookup.bind(null, deps),
361
366
  /** A person takes a document back from `attention`; the sweep tries it again. */
@@ -370,6 +375,15 @@ export function createFiscalDocuments(config: FiscalDocumentsServiceConfig) {
370
375
  },
371
376
  /** One pass of the retry sweep: PENDING/SUBMITTED documents and owed numbers whose next attempt has come. */
372
377
  sweep: async (limit: number): Promise<SweepReport> => run(deps, await store.listDue({ now: deps.ctx.nowIso(), limit })),
378
+ /** Contingency blocks (FUT-4717), the ContingencyBlockSource; `NOT_SUPPORTED` over a store without them. */
379
+ reserveBlock: reserveBlock.bind(null, deps),
380
+ recordSigned: recordSigned.bind(null, deps),
381
+ closeBlock: closeBlock.bind(null, deps),
382
+ abandonBlocks: abandonBlocks.bind(null, deps),
383
+ listBlocks: listBlocks.bind(null, deps),
384
+ listKnownGaps: listKnownGaps.bind(null, deps),
385
+ listUnknownRanges: listUnknownRanges.bind(null, deps),
386
+ voidKnownGaps: voidKnownGaps.bind(null, deps),
373
387
  /** One pass of the contingency transmission, then the 20-hour deadline warnings. */
374
388
  async transmitContingency(limit: number): Promise<SweepReport> {
375
389
  const report = await run(deps, await store.listContingency({ now: deps.ctx.nowIso(), limit }));
@@ -0,0 +1,202 @@
1
+ /**
2
+ * The SQL half of contingency blocks (FUT-4717), over the package's migration
3
+ * (`fiscal_contingency_blocks`, `fiscal_contingency_voids`):
4
+ *
5
+ * - a block is ONE `UPDATE … SET next_number = next_number + size` on the
6
+ * series' counter row (the row `issueOffline` draws from), and its insert,
7
+ * in one transaction: the row lock serialises it with every other draw;
8
+ * - a signed note is its document and its event, in one transaction; the
9
+ * unique indexes on the key and the number make a second copy a `CONFLICT`.
10
+ */
11
+
12
+ import { FiscalDocumentError } from "./errors";
13
+ import type { ContingencyBlock, ContingencyBlockState, ContingencyBlockStore } from "./ports";
14
+ import type { FiscalPrismaClient, FiscalSqlClient } from "./sql-store";
15
+ import { DOCUMENT_COLUMNS, type Row, documentOf, documentValues, placeholder } from "./sql-rows";
16
+ import type { FiscalDocument, FiscalDocumentEvent } from "./types";
17
+
18
+ /**
19
+ * Advance a contingency series' counter by a block. `$1` CNPJ, `$2`
20
+ * environment, `$3` model, `$4` series, `$5` issuing point, `$6` size. No row:
21
+ * not that point's contingency series; past the ceiling: the counter's CHECK.
22
+ */
23
+ export const FISCAL_RESERVE_BLOCK_SQL = `UPDATE "fiscal_number_counters"
24
+ SET "next_number" = "next_number" + $6::integer, "updated_at" = CURRENT_TIMESTAMP
25
+ WHERE "issuer_cnpj" = $1 AND "environment" = $2 AND "model" = $3 AND "series" = $4 AND "issuing_point_id" = $5
26
+ AND "series_kind" = 'CONTINGENCY'
27
+ RETURNING "next_number" - $6::integer AS "first"`;
28
+
29
+ const rows = (client: FiscalSqlClient, query: string, ...values: unknown[]) => client.$queryRawUnsafe<Row[]>(query, ...values);
30
+
31
+ function violates(error: unknown, constraint: string): boolean {
32
+ const text = error instanceof Error ? `${error.message} ${JSON.stringify((error as { meta?: unknown }).meta ?? "")}` : String(error);
33
+ return text.includes(constraint);
34
+ }
35
+
36
+ const iso = (value: unknown): string | null => (value === null || value === undefined ? null : new Date(value instanceof Date ? value : `${String(value).replace(" ", "T")}Z`).toISOString());
37
+
38
+ function blockOf(row: Row): ContingencyBlock {
39
+ return {
40
+ id: String(row["id"]),
41
+ ownerId: String(row["owner_id"]),
42
+ issuingPointId: String(row["issuing_point_id"]),
43
+ issuerCnpj: String(row["issuer_cnpj"]),
44
+ environment: row["environment"] as ContingencyBlock["environment"],
45
+ model: "NFCE",
46
+ series: Number(row["series"]),
47
+ from: Number(row["first_number"]),
48
+ to: Number(row["last_number"]),
49
+ holder: String(row["holder"]),
50
+ fate: row["fate"] as ContingencyBlock["fate"],
51
+ usedUpTo: row["used_up_to"] === null ? null : Number(row["used_up_to"]),
52
+ reservedAt: iso(row["reserved_at"]) ?? "",
53
+ closedAt: iso(row["closed_at"]),
54
+ settledAt: iso(row["settled_at"]),
55
+ };
56
+ }
57
+
58
+ const INSERT_BLOCK = `INSERT INTO "fiscal_contingency_blocks"
59
+ ("id", "owner_id", "issuing_point_id", "issuer_cnpj", "environment", "model", "series", "first_number", "last_number", "holder", "reserved_at")
60
+ VALUES ($1, $2, $3, $4, $5, 'NFCE', $6, $7, $8, $9, $10::timestamp(3))`;
61
+
62
+ const INSERT_DOCUMENT = `INSERT INTO "fiscal_documents" (${DOCUMENT_COLUMNS.map((c) => `"${c}"`).join(", ")})
63
+ VALUES (${DOCUMENT_COLUMNS.map((c, i) => placeholder(c, i + 1)).join(", ")})`;
64
+
65
+ const INSERT_EVENT = `INSERT INTO "fiscal_document_events" ("id", "document_id", "kind", "from_status", "to_status", "at", "error_class", "code", "answer")
66
+ VALUES ($1, $2, $3, $4, $5, $6::timestamp(3), $7, $8, $9::jsonb)`;
67
+
68
+ async function reserve(db: FiscalPrismaClient, input: Parameters<ContingencyBlockStore["reserveContingencyBlock"]>[0]): Promise<ContingencyBlock> {
69
+ const { request, size, id, holder, at } = input;
70
+ try {
71
+ return await db.$transaction(async (tx) => {
72
+ const [row] = await rows(tx, FISCAL_RESERVE_BLOCK_SQL, request.issuerCnpj, request.environment, request.model, request.series, request.issuingPointId, size);
73
+ if (row === undefined) {
74
+ throw new FiscalDocumentError("NOT_FOUND", `no contingency counter for series ${request.series} on issuing point ${request.issuingPointId}.`);
75
+ }
76
+ const first = Number(row["first"]);
77
+ await tx.$executeRawUnsafe(
78
+ INSERT_BLOCK, id, request.ownerId, request.issuingPointId, request.issuerCnpj, request.environment, request.series, first, first + size - 1, holder, at,
79
+ );
80
+ const [stored] = await rows(tx, `SELECT * FROM "fiscal_contingency_blocks" WHERE "id" = $1`, id);
81
+ return blockOf(stored ?? {});
82
+ });
83
+ } catch (error) {
84
+ if (violates(error, "fiscal_number_counters_next_number_check") || violates(error, "fiscal_contingency_blocks_range_check")) {
85
+ throw new FiscalDocumentError("SERIES_EXHAUSTED", `series ${request.series} has no ${size} numbers left.`);
86
+ }
87
+ throw error;
88
+ }
89
+ }
90
+
91
+ async function insertSigned(db: FiscalPrismaClient, document: FiscalDocument, event: FiscalDocumentEvent): Promise<FiscalDocument> {
92
+ try {
93
+ await db.$transaction(async (tx) => {
94
+ await tx.$executeRawUnsafe(INSERT_DOCUMENT, ...documentValues(document));
95
+ await tx.$executeRawUnsafe(
96
+ INSERT_EVENT, globalThis.crypto.randomUUID(), event.documentId, event.kind, event.fromStatus, event.toStatus, event.at,
97
+ event.errorClass, event.code, JSON.stringify(event.answer),
98
+ );
99
+ });
100
+ return document;
101
+ } catch (error) {
102
+ if (violates(error, "fiscal_documents_live_subject_key")) {
103
+ throw new FiscalDocumentError("SUBJECT_HAS_DOCUMENT", `subject ${document.subjectId} already has a live ${document.model}.`);
104
+ }
105
+ if (violates(error, "fiscal_documents_access_key_key") || violates(error, "fiscal_documents_number_key")) {
106
+ throw new FiscalDocumentError("CONFLICT", `key ${document.accessKey ?? ""} or number ${document.number} is recorded already.`);
107
+ }
108
+ throw error;
109
+ }
110
+ }
111
+
112
+ /** The blocks, each with its documented numbers and voided ranges: two reads. */
113
+ async function withState(db: FiscalPrismaClient, blocks: readonly ContingencyBlock[]): Promise<ContingencyBlockState[]> {
114
+ if (blocks.length === 0) return [];
115
+ const ids = blocks.map((block) => block.id);
116
+ const documented = await rows(
117
+ db,
118
+ `SELECT b."id" AS "block_id", d."number" FROM "fiscal_contingency_blocks" b
119
+ JOIN "fiscal_documents" d ON d."issuer_cnpj" = b."issuer_cnpj" AND d."environment" = b."environment" AND d."model" = b."model"
120
+ AND d."series" = b."series" AND d."number" BETWEEN b."first_number" AND b."last_number"
121
+ WHERE b."id" = ANY($1::text[]) ORDER BY d."number"`,
122
+ ids,
123
+ );
124
+ const voids = await rows(db, `SELECT * FROM "fiscal_contingency_voids" WHERE "block_id" = ANY($1::text[]) ORDER BY "first_number"`, ids);
125
+ return blocks.map((block) => ({
126
+ ...block,
127
+ documented: documented.filter((row) => row["block_id"] === block.id).map((row) => Number(row["number"])),
128
+ voided: voids.filter((row) => row["block_id"] === block.id).map((row) => ({ from: Number(row["first_number"]), to: Number(row["last_number"]) })),
129
+ }));
130
+ }
131
+
132
+ /** One keyset page of the blocks a filter selects, ordered by `(reserved_at, id)`, with their state. */
133
+ async function list(db: FiscalPrismaClient, input: Parameters<ContingencyBlockStore["listContingencyBlocks"]>[0]): Promise<ContingencyBlockState[]> {
134
+ const where: string[] = [];
135
+ const values: unknown[] = [];
136
+ const add = (clause: (n: number) => string, value: unknown) => {
137
+ values.push(value);
138
+ where.push(clause(values.length));
139
+ };
140
+ if (input.ownerId !== undefined) add((n) => `"owner_id" = $${n}`, input.ownerId);
141
+ if (input.holder !== undefined) add((n) => `"holder" = $${n}`, input.holder);
142
+ if (input.fates !== undefined) add((n) => `"fate" = ANY($${n}::text[])`, [...input.fates]);
143
+ if (input.reservedBefore !== undefined) add((n) => `"reserved_at" < $${n}::timestamp(3)`, input.reservedBefore);
144
+ if (input.unsettledOnly === true) where.push(`"settled_at" IS NULL`);
145
+ if (input.after !== undefined) {
146
+ values.push(input.after.reservedAt, input.after.id);
147
+ where.push(`("reserved_at", "id") > ($${values.length - 1}::timestamp(3), $${values.length})`);
148
+ }
149
+ values.push(input.limit);
150
+ const blocks = (
151
+ await rows(
152
+ db,
153
+ `SELECT * FROM "fiscal_contingency_blocks" ${where.length === 0 ? "" : `WHERE ${where.join(" AND ")}`}
154
+ ORDER BY "reserved_at", "id" LIMIT $${values.length}`,
155
+ ...values,
156
+ )
157
+ ).map(blockOf);
158
+ return withState(db, blocks);
159
+ }
160
+
161
+ export function blockMethods(db: FiscalPrismaClient): ContingencyBlockStore {
162
+ return {
163
+ reserveContingencyBlock: (input) => reserve(db, input),
164
+ async findContingencyBlock(input) {
165
+ const [row] = await rows(
166
+ db,
167
+ `SELECT * FROM "fiscal_contingency_blocks"
168
+ WHERE "owner_id" = $1 AND "issuer_cnpj" = $2 AND "environment" = $3 AND "model" = 'NFCE' AND "series" = $4
169
+ AND $5::integer BETWEEN "first_number" AND "last_number"`,
170
+ input.ownerId, input.issuerCnpj, input.environment, input.series, input.number,
171
+ );
172
+ return row === undefined ? null : ((await withState(db, [blockOf(row)]))[0] ?? null);
173
+ },
174
+ listContingencyBlocks: (input) => list(db, input),
175
+ async closeContingencyBlock({ id, fate, usedUpTo, at }) {
176
+ const updated = await rows(
177
+ db,
178
+ `UPDATE "fiscal_contingency_blocks" SET "fate" = $2, "used_up_to" = $3, "closed_at" = $4::timestamp(3)
179
+ WHERE "id" = $1 AND "fate" = 'OPEN' RETURNING "id"`,
180
+ id, fate, usedUpTo, at,
181
+ );
182
+ return updated.length > 0;
183
+ },
184
+ async settleContingencyBlock({ id, at }) {
185
+ await db.$executeRawUnsafe(`UPDATE "fiscal_contingency_blocks" SET "settled_at" = $2::timestamp(3) WHERE "id" = $1`, id, at);
186
+ },
187
+ async recordContingencyVoid({ id, blockId, range, protocol, eventXmlKey, at }) {
188
+ const inserted = await rows(
189
+ db,
190
+ `INSERT INTO "fiscal_contingency_voids" ("id", "block_id", "first_number", "last_number", "protocol", "event_xml_key", "voided_at")
191
+ VALUES ($1, $2, $3, $4, $5, $6, $7::timestamp(3)) ON CONFLICT ("block_id", "first_number") DO NOTHING RETURNING "id"`,
192
+ id, blockId, range.from, range.to, protocol, eventXmlKey, at,
193
+ );
194
+ return inserted.length > 0;
195
+ },
196
+ async getDocumentByAccessKey(ownerId, accessKey) {
197
+ const [row] = await rows(db, `SELECT * FROM "fiscal_documents" WHERE "owner_id" = $1 AND "access_key" = $2`, ownerId, accessKey);
198
+ return row === undefined ? null : documentOf(row);
199
+ },
200
+ recordSignedDocument: (document, event) => insertSigned(db, document, event),
201
+ };
202
+ }
@@ -21,7 +21,8 @@
21
21
 
22
22
  import { FiscalDocumentError } from "./errors";
23
23
  import type { Transition } from "./machine";
24
- import type { FiscalStore, NumberRequest } from "./ports";
24
+ import type { ContingencyBlockStore, FiscalStore, NumberRequest } from "./ports";
25
+ import { blockMethods } from "./sql-blocks";
25
26
  import { FISCAL_NEXT_NUMBER_SQL } from "./sql";
26
27
  import {
27
28
  DOCUMENT_COLUMNS,
@@ -233,10 +234,10 @@ function documentMethods(db: FiscalPrismaClient): Omit<FiscalStore, keyof Profil
233
234
  };
234
235
  }
235
236
 
236
- export function createPrismaFiscalStore(config: { readonly prisma: FiscalPrismaClient }): FiscalStore {
237
+ export function createPrismaFiscalStore(config: { readonly prisma: FiscalPrismaClient }): FiscalStore & ContingencyBlockStore {
237
238
  const db = config?.prisma;
238
239
  if (typeof db?.$transaction !== "function" || typeof db.$queryRawUnsafe !== "function") {
239
240
  throw new TypeError("createPrismaFiscalStore needs prisma: the host's Prisma client.");
240
241
  }
241
- return { ...profileMethods(db), ...documentMethods(db) };
242
+ return { ...profileMethods(db), ...documentMethods(db), ...blockMethods(db) };
242
243
  }
@@ -175,7 +175,8 @@ export type DocumentEventKind =
175
175
  | "DEFER"
176
176
  | "RESIGN"
177
177
  | "RELEASE"
178
- | "WARN";
178
+ | "WARN"
179
+ | "LINK_PAYMENT";
179
180
 
180
181
  /**
181
182
  * One transition, as stored. `answer` is what the fiscal service answered,
package/src/http.ts CHANGED
@@ -75,6 +75,7 @@ export const FISCAL_ERROR_STATUS = {
75
75
  RETURN_NEEDS_REFERENCE: 422,
76
76
  RETURN_ON_NFCE: 422,
77
77
  RETURN_OF_NFCE_ONLY: 422,
78
+ CONTINGENCY_XML_REFUSED: 422,
78
79
  } as const satisfies Record<FiscalDocumentErrorCode, number>;
79
80
 
80
81
  /**