@12-apps/fiscal 1.5.0 → 1.7.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 (80) 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-ZKWVKCGJ.js → chunk-P5EDTNWE.js} +1 -1
  8. package/dist/{chunk-ZKWVKCGJ.js.map → chunk-P5EDTNWE.js.map} +1 -1
  9. package/dist/{chunk-G6QNU4FD.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-TJCUO6D6.js → chunk-YHSO3476.js} +6 -5
  13. package/dist/chunk-YHSO3476.js.map +1 -0
  14. package/dist/{context-CwZiHLnY.d.ts → context-D71ETH--.d.ts} +155 -19
  15. package/dist/danfe/index.d.ts +7 -0
  16. package/dist/danfe/index.js +2 -2
  17. package/dist/documents/index.d.ts +157 -36
  18. package/dist/documents/index.js +1104 -305
  19. package/dist/documents/index.js.map +1 -1
  20. package/dist/engine/index.d.ts +2 -2
  21. package/dist/http.d.ts +6 -5
  22. package/dist/http.js +4 -4
  23. package/dist/issuer/index.d.ts +10 -3
  24. package/dist/issuer/index.js +19 -4
  25. package/dist/issuer/index.js.map +1 -1
  26. package/dist/jobs.d.ts +5 -5
  27. package/dist/jobs.js +3 -3
  28. package/dist/manifest/index.d.ts +6 -4
  29. package/dist/manifest/index.js.map +1 -1
  30. package/dist/manifest/server.d.ts +5 -5
  31. package/dist/manifest/server.js +6 -6
  32. package/dist/notifications.d.ts +4 -4
  33. package/dist/notifications.js +2 -2
  34. package/dist/sale/index.d.ts +17 -4
  35. package/dist/sale/index.js.map +1 -1
  36. package/dist/{service-Cz2O84Xr.d.ts → service-DyA64Jc6.d.ts} +64 -5
  37. package/dist/sidecar/index.d.ts +38 -249
  38. package/dist/sidecar/index.js +30 -2
  39. package/dist/sidecar/index.js.map +1 -1
  40. package/dist/{types-DSYwap42.d.ts → types-6OiBrmZy.d.ts} +2 -2
  41. package/dist/{types-B1b8LIWX.d.ts → types-BLdkww6G.d.ts} +1 -1
  42. package/dist/types-BbTxBzsv.d.ts +252 -0
  43. package/package.json +2 -1
  44. package/prisma/fiscal.prisma +50 -1
  45. package/prisma/migrations/20261118180000_fiscal_contingency_blocks/migration.sql +64 -0
  46. package/sidecar/README.md +70 -10
  47. package/sidecar/bin/check-platform.php +29 -0
  48. package/sidecar/extensions.json +12 -0
  49. package/sidecar/schema/sale-for-document.schema.json +4 -0
  50. package/sidecar/src/Http/Request.php +6 -1
  51. package/sidecar/src/Kernel.php +39 -1
  52. package/sidecar/src/Nfe/DocumentMapper.php +27 -22
  53. package/sidecar/src/Platform.php +84 -0
  54. package/src/danfe/render.ts +16 -5
  55. package/src/documents/contingency-gaps.ts +88 -0
  56. package/src/documents/contingency-pass.ts +157 -0
  57. package/src/documents/contingency-xml.ts +136 -0
  58. package/src/documents/contingency.ts +257 -0
  59. package/src/documents/errors.ts +8 -1
  60. package/src/documents/helpers.ts +3 -0
  61. package/src/documents/index.ts +23 -1
  62. package/src/documents/lines.ts +6 -2
  63. package/src/documents/memory-blocks.ts +118 -0
  64. package/src/documents/memory.ts +6 -2
  65. package/src/documents/ports.ts +163 -13
  66. package/src/documents/service.ts +10 -0
  67. package/src/documents/sql-blocks.ts +202 -0
  68. package/src/documents/sql-store.ts +4 -3
  69. package/src/http.ts +1 -0
  70. package/src/issuer/sidecar.ts +27 -3
  71. package/src/manifest/index.ts +6 -4
  72. package/src/sale/types.ts +17 -4
  73. package/src/sidecar/index.ts +2 -0
  74. package/src/sidecar/platform.ts +55 -0
  75. package/src/sidecar/types.ts +1 -3
  76. package/dist/chunk-3E3NBXSW.js.map +0 -1
  77. package/dist/chunk-MGTROA7K.js.map +0 -1
  78. package/dist/chunk-TJCUO6D6.js.map +0 -1
  79. /package/dist/{chunk-HMTPJWXM.js.map → chunk-2JVTHJAU.js.map} +0 -0
  80. /package/dist/{chunk-G6QNU4FD.js.map → chunk-P7CRGZGO.js.map} +0 -0
@@ -11,7 +11,29 @@ export { DOCUMENT_TRANSITIONS, FINAL_STATUSES, MAX_FAILURES, canTransition, scru
11
11
  export type { DocumentInput, Transition } from "./machine";
12
12
  export { FiscalDocumentError } from "./errors";
13
13
  export type { FiscalDocumentErrorCode } from "./errors";
14
- export type { Cipher, ContingencyBlockSource, DocumentStorage, FiscalStore, NumberRequest, SaleDraft, SaleSource } from "./ports";
14
+ export type {
15
+ Cipher,
16
+ ContingencyBlock,
17
+ ContingencyBlockFate,
18
+ ContingencyBlockSource,
19
+ ContingencyBlockState,
20
+ ContingencyBlockStore,
21
+ ContingencyGap,
22
+ DocumentStorage,
23
+ FiscalStore,
24
+ NumberRange,
25
+ NumberRequest,
26
+ SaleDraft,
27
+ SaleSource,
28
+ } from "./ports";
29
+ export { CONTINGENCY_BLOCK_FATES } from "./ports";
30
+ export { DEFAULT_CONTINGENCY_BLOCK_SIZE, MAX_CONTINGENCY_BLOCK_SIZE } from "./contingency";
31
+ export type { GapVoidReport } from "./contingency";
32
+ export { accountFor as accountForContingencyBlock } from "./contingency-gaps";
33
+ export type { BlockAccount } from "./contingency-gaps";
34
+ export { parseSignedContingencyNote } from "./contingency-xml";
35
+ export type { SignedContingencyNote } from "./contingency-xml";
36
+ export { FISCAL_RESERVE_BLOCK_SQL } from "./sql-blocks";
15
37
  export { createPlatformIdentity, createSigningIdentities, createStoreCertificateIdentity } from "./signing";
16
38
  export type { SigningIdentities, SigningIdentity } from "./signing";
17
39
  export { parseCertificateUpload, parseIssuingPointInput, parseProfileInput } from "./profile-input";
@@ -11,7 +11,10 @@
11
11
  * taxed item under the class the host passed;
12
12
  * - the IBS/CBS group from the line's figures (`vBC`, the nominal rates, the
13
13
  * reduction, the amounts), or no group at all where the engine answered
14
- * `NONE` (MEI, não contribuinte).
14
+ * `NONE` (MEI, não contribuinte);
15
+ * - the net value (`vProdLiq`, NT 2026.008) where the period puts the tax
16
+ * inside the price (from 2027), and no key at all where it does not, so a
17
+ * 2026 document is the one it was before the field existed.
15
18
  *
16
19
  * What the engine does not know — the product code, NCM, CFOP, unit, the
17
20
  * ICMS, PIS and COFINS — arrives per line id from the host. A breakdown line
@@ -23,7 +26,7 @@ import type { LineIbsCbs, SaleLine } from "../sale/types";
23
26
  import { FiscalDocumentError } from "./errors";
24
27
 
25
28
  /** Everything a document line needs that the breakdown does not carry. */
26
- export type LineDetails = Omit<SaleLine, "id" | "quantity" | "valueCents" | "ibsCbs">;
29
+ export type LineDetails = Omit<SaleLine, "id" | "quantity" | "valueCents" | "netValueCents" | "ibsCbs">;
27
30
 
28
31
  const SEGREGATED = new Set<LineTax["source"]>(["GORJETA_EXCLUDED", "INTERMEDIATION_EXCLUDED"]);
29
32
 
@@ -57,6 +60,7 @@ export function documentLines(breakdown: TaxBreakdown, details: Readonly<Record<
57
60
  id: line.lineId,
58
61
  quantity: line.quantity,
59
62
  valueCents: line.valueCents,
63
+ ...(line.netValueCents === null ? {} : { netValueCents: line.netValueCents }),
60
64
  ibsCbs: ibsCbsOf(line, breakdown),
61
65
  };
62
66
  });
@@ -0,0 +1,118 @@
1
+ /**
2
+ * The memory store's contingency blocks (FUT-4717): the same promises as the
3
+ * SQL store's — a block advances the series' counter and is recorded
4
+ * together, a signed note and its event are inserted together, a key or a
5
+ * number recorded twice is a `CONFLICT`, and a subject keeps one live
6
+ * document.
7
+ */
8
+
9
+ import { FiscalDocumentError } from "./errors";
10
+ import type { ContingencyBlock, ContingencyBlockState, ContingencyBlockStore, NumberRange, NumberRequest } from "./ports";
11
+ import { type FiscalDocument, type FiscalDocumentEvent, isLive } from "./types";
12
+
13
+ const MAX_NUMBER = 999_999_999;
14
+
15
+ interface MemoryBlockState {
16
+ readonly counters: Map<string, number>;
17
+ readonly seriesOwner: Map<string, string>;
18
+ readonly documents: Map<string, FiscalDocument>;
19
+ readonly events: FiscalDocumentEvent[];
20
+ readonly counterKey: (request: Pick<NumberRequest, "issuerCnpj" | "environment" | "model" | "series">) => string;
21
+ }
22
+
23
+ interface Void extends NumberRange {
24
+ readonly blockId: string;
25
+ }
26
+
27
+ function sameSeries(a: Pick<FiscalDocument, "issuerCnpj" | "environment" | "model" | "series">, b: typeof a): boolean {
28
+ return a.issuerCnpj === b.issuerCnpj && a.environment === b.environment && a.model === b.model && a.series === b.series;
29
+ }
30
+
31
+ function stateOf(block: ContingencyBlock, documents: Iterable<FiscalDocument>, voids: readonly Void[]): ContingencyBlockState {
32
+ const documented = [...documents]
33
+ .filter((d) => sameSeries(d, block) && d.number >= block.from && d.number <= block.to)
34
+ .map((d) => d.number)
35
+ .sort((a, b) => a - b);
36
+ const voided = voids.filter((v) => v.blockId === block.id).map(({ from, to }) => ({ from, to }));
37
+ return { ...block, documented, voided };
38
+ }
39
+
40
+ /** Whether `block` sorts after `cursor` in the `(reservedAt, id)` keyset order. */
41
+ function after(block: Pick<ContingencyBlock, "reservedAt" | "id">, cursor: Pick<ContingencyBlock, "reservedAt" | "id">): boolean {
42
+ return block.reservedAt > cursor.reservedAt || (block.reservedAt === cursor.reservedAt && block.id > cursor.id);
43
+ }
44
+
45
+ function insertSigned(state: MemoryBlockState, document: FiscalDocument, event: FiscalDocumentEvent): FiscalDocument {
46
+ const all = [...state.documents.values()];
47
+ if (all.some((other) => other.accessKey === document.accessKey || (sameSeries(other, document) && other.number === document.number))) {
48
+ throw new FiscalDocumentError("CONFLICT", `key ${document.accessKey ?? ""} or number ${document.number} is recorded already.`);
49
+ }
50
+ const live = all.some((o) => o.ownerId === document.ownerId && o.subjectId === document.subjectId && o.model === document.model && isLive(o));
51
+ if (live) throw new FiscalDocumentError("SUBJECT_HAS_DOCUMENT", `subject ${document.subjectId} already has a live ${document.model}.`);
52
+ state.documents.set(document.id, document);
53
+ state.events.push(event);
54
+ return document;
55
+ }
56
+
57
+ export function memoryBlockMethods(state: MemoryBlockState): ContingencyBlockStore & { readonly blocks: Map<string, ContingencyBlock> } {
58
+ const blocks = new Map<string, ContingencyBlock>();
59
+ const voids: Void[] = [];
60
+ const update = (id: string, patch: Partial<ContingencyBlock>) => {
61
+ const block = blocks.get(id);
62
+ if (block !== undefined) blocks.set(id, { ...block, ...patch });
63
+ };
64
+ return {
65
+ blocks,
66
+ async reserveContingencyBlock({ request, size, id, holder, at }) {
67
+ const key = state.counterKey(request);
68
+ const first = state.counters.get(key);
69
+ if (first === undefined || state.seriesOwner.get(key) !== request.issuingPointId) {
70
+ throw new FiscalDocumentError("NOT_FOUND", `no counter for series ${request.series} on issuing point ${request.issuingPointId}.`);
71
+ }
72
+ if (first + size - 1 > MAX_NUMBER) throw new FiscalDocumentError("SERIES_EXHAUSTED", `series ${request.series} has no ${size} numbers left.`);
73
+ state.counters.set(key, first + size);
74
+ const block: ContingencyBlock = {
75
+ id, ownerId: request.ownerId, issuingPointId: request.issuingPointId, issuerCnpj: request.issuerCnpj,
76
+ environment: request.environment, model: "NFCE", series: request.series, from: first, to: first + size - 1, holder,
77
+ fate: "OPEN", usedUpTo: null, reservedAt: at, closedAt: null, settledAt: null,
78
+ };
79
+ blocks.set(id, block);
80
+ return block;
81
+ },
82
+ async findContingencyBlock(input) {
83
+ const found = [...blocks.values()].find(
84
+ (b) => sameSeries(b, { ...input, model: "NFCE" }) && input.number >= b.from && input.number <= b.to,
85
+ );
86
+ return found === undefined || found.ownerId !== input.ownerId ? null : stateOf(found, state.documents.values(), voids);
87
+ },
88
+ async listContingencyBlocks(input) {
89
+ return [...blocks.values()]
90
+ .filter((b) => input.ownerId === undefined || b.ownerId === input.ownerId)
91
+ .filter((b) => input.holder === undefined || b.holder === input.holder)
92
+ .filter((b) => input.fates === undefined || input.fates.includes(b.fate))
93
+ .filter((b) => input.reservedBefore === undefined || b.reservedAt < input.reservedBefore)
94
+ .filter((b) => !input.unsettledOnly || b.settledAt === null)
95
+ .filter((b) => input.after === undefined || after(b, input.after))
96
+ .sort((a, b) => (after(a, b) ? 1 : after(b, a) ? -1 : 0))
97
+ .slice(0, input.limit)
98
+ .map((b) => stateOf(b, state.documents.values(), voids));
99
+ },
100
+ async closeContingencyBlock({ id, fate, usedUpTo, at }) {
101
+ if (blocks.get(id)?.fate !== "OPEN") return false;
102
+ update(id, { fate, usedUpTo, closedAt: at });
103
+ return true;
104
+ },
105
+ async settleContingencyBlock({ id, at }) {
106
+ update(id, { settledAt: at });
107
+ },
108
+ async recordContingencyVoid({ blockId, range }) {
109
+ if (voids.some((v) => v.blockId === blockId && v.from === range.from)) return false;
110
+ voids.push({ blockId, ...range });
111
+ return true;
112
+ },
113
+ async getDocumentByAccessKey(ownerId, accessKey) {
114
+ return [...state.documents.values()].find((d) => d.ownerId === ownerId && d.accessKey === accessKey) ?? null;
115
+ },
116
+ recordSignedDocument: async (document, event) => insertSigned(state, document, event),
117
+ };
118
+ }
@@ -8,13 +8,16 @@
8
8
  */
9
9
 
10
10
  import { FiscalDocumentError } from "./errors";
11
- import type { FiscalStore, NumberRequest } from "./ports";
11
+ import { memoryBlockMethods } from "./memory-blocks";
12
+ import type { ContingencyBlock, ContingencyBlockStore, FiscalStore, NumberRequest } from "./ports";
12
13
  import type { EmitterProfile, IssuingPoint } from "./profile";
13
14
  import { type FiscalDocument, type FiscalDocumentEvent, OWED_VOIDS, isLive } from "./types";
14
15
 
15
16
  const MAX_NUMBER = 999_999_999;
16
17
 
17
- export interface MemoryFiscalStore extends FiscalStore {
18
+ export interface MemoryFiscalStore extends FiscalStore, ContingencyBlockStore {
19
+ /** The contingency blocks, by id (FUT-4717). */
20
+ readonly blocks: Map<string, ContingencyBlock>;
18
21
  /** Every event, in order, for assertions. */
19
22
  readonly events: FiscalDocumentEvent[];
20
23
  /** The next number each counter would hand out, keyed `cnpj|environment|model|series`. */
@@ -75,6 +78,7 @@ export function createMemoryFiscalStore(): MemoryFiscalStore {
75
78
  [...state.documents.values()].sort((a, b) => key(a).localeCompare(key(b)));
76
79
 
77
80
  return {
81
+ ...memoryBlockMethods({ ...state, counterKey }),
78
82
  events: state.events,
79
83
  counters: state.counters,
80
84
  getProfile: async (ownerId) => profiles.get(ownerId) ?? null,
@@ -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
  }
@@ -19,6 +19,7 @@ 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
21
  import { linkPayment } from "./payment-link";
22
+ import { abandonBlocks, closeBlock, listBlocks, listKnownGaps, listUnknownRanges, recordSigned, reserveBlock, voidKnownGaps } from "./contingency";
22
23
  import { answerLive, assertOnlineDeadline, signPending, submit, transmit } from "./steps";
23
24
  import { type CancelOrReturnInput, type CancelOrReturnResult, type DocumentTotals, type FiscalDocument, type FiscalDocumentModel, isLive } from "./types";
24
25
 
@@ -374,6 +375,15 @@ export function createFiscalDocuments(config: FiscalDocumentsServiceConfig) {
374
375
  },
375
376
  /** One pass of the retry sweep: PENDING/SUBMITTED documents and owed numbers whose next attempt has come. */
376
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),
377
387
  /** One pass of the contingency transmission, then the 20-hour deadline warnings. */
378
388
  async transmitContingency(limit: number): Promise<SweepReport> {
379
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
  }
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
  /**