@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.
- package/README.md +46 -4
- package/dist/{chunk-EDEGIADD.js → chunk-2JVTHJAU.js} +3 -3
- package/dist/{chunk-2ISYBTCE.js → chunk-CEK2GDRY.js} +15 -6
- package/dist/chunk-CEK2GDRY.js.map +1 -0
- package/dist/{chunk-GF3DXCD2.js → chunk-GH452ITO.js} +1 -1
- package/dist/{chunk-GF3DXCD2.js.map → chunk-GH452ITO.js.map} +1 -1
- package/dist/{chunk-MGTROA7K.js → chunk-OAQSGDZ7.js} +11 -7
- package/dist/chunk-OAQSGDZ7.js.map +1 -0
- package/dist/{chunk-OSYB7CVT.js → chunk-P7CRGZGO.js} +2 -2
- package/dist/{chunk-H33BK623.js → chunk-WRYCYXRA.js} +1 -1
- package/dist/{chunk-H33BK623.js.map → chunk-WRYCYXRA.js.map} +1 -1
- package/dist/{chunk-F2PGQVWL.js → chunk-YHSO3476.js} +7 -6
- package/dist/chunk-YHSO3476.js.map +1 -0
- package/dist/{chunk-JVQKJNOC.js → chunk-ZKWVKCGJ.js} +1 -1
- package/dist/chunk-ZKWVKCGJ.js.map +1 -0
- package/dist/{context-CLSMOSuf.d.ts → context-Cyvfr2YB.d.ts} +167 -20
- package/dist/danfe/index.d.ts +7 -0
- package/dist/danfe/index.js +2 -2
- package/dist/documents/index.d.ts +154 -34
- package/dist/documents/index.js +1193 -306
- package/dist/documents/index.js.map +1 -1
- package/dist/engine/index.d.ts +2 -2
- package/dist/http.d.ts +6 -5
- package/dist/http.js +5 -5
- package/dist/issuer/index.d.ts +10 -3
- package/dist/issuer/index.js +27 -4
- package/dist/issuer/index.js.map +1 -1
- package/dist/jobs.d.ts +5 -5
- package/dist/jobs.js +4 -4
- package/dist/manifest/index.d.ts +6 -4
- package/dist/manifest/index.js.map +1 -1
- package/dist/manifest/server.d.ts +5 -5
- package/dist/manifest/server.js +7 -7
- package/dist/notifications.d.ts +4 -4
- package/dist/notifications.js +3 -3
- package/dist/sale/index.d.ts +29 -1
- package/dist/sale/index.js +7 -0
- package/dist/sale/index.js.map +1 -1
- package/dist/{service-hR3tgLpO.d.ts → service-BCK9aXop.d.ts} +99 -6
- package/dist/sidecar/index.d.ts +35 -210
- package/dist/sidecar/index.js +30 -2
- package/dist/sidecar/index.js.map +1 -1
- package/dist/{types-B1b8LIWX.d.ts → types-BLdkww6G.d.ts} +1 -1
- package/dist/{types-BIJqm5GM.d.ts → types-Sk010Em2.d.ts} +25 -4
- package/dist/types-Z5E14EPw.d.ts +254 -0
- package/package.json +2 -1
- package/prisma/fiscal.prisma +50 -1
- package/prisma/migrations/20261118120000_fiscal_link_payment_event/migration.sql +9 -0
- package/prisma/migrations/20261118180000_fiscal_contingency_blocks/migration.sql +64 -0
- package/sidecar/README.md +53 -1
- package/sidecar/bin/check-platform.php +29 -0
- package/sidecar/composer.json +1 -1
- package/sidecar/composer.lock +7 -7
- package/sidecar/extensions.json +12 -0
- package/sidecar/schema/sale-for-document.schema.json +18 -1
- package/sidecar/src/Http/Request.php +6 -1
- package/sidecar/src/Kernel.php +39 -1
- package/sidecar/src/Nfe/DocumentMapper.php +27 -0
- package/sidecar/src/Nfe/Input.php +10 -0
- package/sidecar/src/Nfe/NfeModule.php +1 -0
- package/sidecar/src/Nfe/NfeService.php +120 -0
- package/sidecar/src/Nfe/SefazReply.php +21 -0
- package/sidecar/src/Platform.php +84 -0
- package/src/danfe/render.ts +16 -5
- package/src/documents/contingency-gaps.ts +88 -0
- package/src/documents/contingency-pass.ts +157 -0
- package/src/documents/contingency-xml.ts +136 -0
- package/src/documents/contingency.ts +257 -0
- package/src/documents/errors.ts +8 -1
- package/src/documents/helpers.ts +5 -0
- package/src/documents/index.ts +25 -2
- package/src/documents/machine-steps.ts +12 -2
- package/src/documents/machine.ts +7 -0
- package/src/documents/memory-blocks.ts +118 -0
- package/src/documents/memory.ts +6 -2
- package/src/documents/payment-link.ts +156 -0
- package/src/documents/ports.ts +163 -13
- package/src/documents/service.ts +14 -0
- package/src/documents/sql-blocks.ts +202 -0
- package/src/documents/sql-store.ts +4 -3
- package/src/documents/types.ts +2 -1
- package/src/http.ts +1 -0
- package/src/issuer/port.ts +24 -1
- package/src/issuer/sidecar.ts +37 -3
- package/src/manifest/index.ts +6 -4
- package/src/sale/index.ts +1 -0
- package/src/sale/types.ts +30 -0
- package/src/sidecar/index.ts +2 -0
- package/src/sidecar/platform.ts +55 -0
- package/src/sidecar/types.ts +38 -0
- package/dist/chunk-2ISYBTCE.js.map +0 -1
- package/dist/chunk-F2PGQVWL.js.map +0 -1
- package/dist/chunk-JVQKJNOC.js.map +0 -1
- package/dist/chunk-MGTROA7K.js.map +0 -1
- /package/dist/{chunk-EDEGIADD.js.map → chunk-2JVTHJAU.js.map} +0 -0
- /package/dist/{chunk-OSYB7CVT.js.map → chunk-P7CRGZGO.js.map} +0 -0
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Contingency blocks (FUT-4717): numbers of an issuing point's contingency
|
|
3
|
+
* series handed to a holder in advance, the notes it signed on them recorded
|
|
4
|
+
* as the subjects' `CONTINGENCY` documents (transmitted by the same pass as
|
|
5
|
+
* the server's own), and the known rest of each block voided at SEFAZ.
|
|
6
|
+
*
|
|
7
|
+
* A station-signed note is transmitted from its stored XML exactly as the
|
|
8
|
+
* server's own contingency documents are (`transmit`): nothing rebuilds it
|
|
9
|
+
* from the sale. A rejection keeps its number (the buyer holds its DANFE):
|
|
10
|
+
* `resendContingency` re-signs it under the same number, as for any
|
|
11
|
+
* contingency NFC-e.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { FiscalDocumentError } from "./errors";
|
|
15
|
+
import { assertDraftFits, issuerOf, totalsOf, xmlKeys } from "./helpers";
|
|
16
|
+
import { allBlocks, blockStore } from "./contingency-pass";
|
|
17
|
+
import { type SignedContingencyNote, parseSignedContingencyNote } from "./contingency-xml";
|
|
18
|
+
import type { Deps } from "./service-profile";
|
|
19
|
+
import type {
|
|
20
|
+
ContingencyBlock,
|
|
21
|
+
ContingencyBlockFate,
|
|
22
|
+
ContingencyBlockSource,
|
|
23
|
+
ContingencyBlockState,
|
|
24
|
+
ContingencyBlockStore,
|
|
25
|
+
SaleDraft,
|
|
26
|
+
} from "./ports";
|
|
27
|
+
import type { FiscalDocument, FiscalDocumentEvent } from "./types";
|
|
28
|
+
|
|
29
|
+
/** The block size when the caller names none (decided on FUT-4717: 50, a new block at 10 left). */
|
|
30
|
+
export const DEFAULT_CONTINGENCY_BLOCK_SIZE = 50;
|
|
31
|
+
/** The largest block one call reserves. */
|
|
32
|
+
export const MAX_CONTINGENCY_BLOCK_SIZE = 10_000;
|
|
33
|
+
|
|
34
|
+
function assertHolder(holder: unknown): asserts holder is string {
|
|
35
|
+
if (typeof holder !== "string" || holder.trim() === "" || holder.length > 200) {
|
|
36
|
+
throw new FiscalDocumentError("INVALID_INPUT", "holder must be a non-empty id of at most 200 characters.");
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function refuse(why: string): never {
|
|
41
|
+
throw new FiscalDocumentError("CONTINGENCY_XML_REFUSED", why);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function reserveBlock(deps: Deps, input: Parameters<ContingencyBlockSource["reserveBlock"]>[0]): Promise<ContingencyBlock> {
|
|
45
|
+
const store = blockStore(deps.config.store);
|
|
46
|
+
assertHolder(input.holder);
|
|
47
|
+
const size = input.size ?? DEFAULT_CONTINGENCY_BLOCK_SIZE;
|
|
48
|
+
if (!Number.isInteger(size) || size < 1 || size > MAX_CONTINGENCY_BLOCK_SIZE) {
|
|
49
|
+
throw new FiscalDocumentError("INVALID_INPUT", `size must be a whole number from 1 to ${MAX_CONTINGENCY_BLOCK_SIZE}.`);
|
|
50
|
+
}
|
|
51
|
+
const profile = await deps.ctx.requireProfile(input.ownerId);
|
|
52
|
+
if (profile.documentPolicy !== "ISSUED_HERE") {
|
|
53
|
+
throw new FiscalDocumentError("NOT_ISSUABLE", `owner ${input.ownerId}'s documentPolicy is ${profile.documentPolicy}.`);
|
|
54
|
+
}
|
|
55
|
+
const point = await deps.ctx.requirePoint(input.ownerId, input.issuingPointId);
|
|
56
|
+
if (point.model !== "NFCE" || point.contingencySeries === null) {
|
|
57
|
+
throw new FiscalDocumentError("INVALID_INPUT", `issuing point ${point.id} has no NFC-e contingency series.`);
|
|
58
|
+
}
|
|
59
|
+
return store.reserveContingencyBlock({
|
|
60
|
+
request: {
|
|
61
|
+
ownerId: input.ownerId,
|
|
62
|
+
issuerCnpj: profile.cnpj,
|
|
63
|
+
issuingPointId: point.id,
|
|
64
|
+
environment: profile.environment,
|
|
65
|
+
model: "NFCE",
|
|
66
|
+
seriesKind: "CONTINGENCY",
|
|
67
|
+
series: point.contingencySeries,
|
|
68
|
+
},
|
|
69
|
+
size,
|
|
70
|
+
id: deps.config.newId(),
|
|
71
|
+
holder: input.holder,
|
|
72
|
+
at: deps.ctx.nowIso(),
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The CONTINGENCY document a holder's signed note becomes, owed a transmission now. */
|
|
77
|
+
function signedDocument(
|
|
78
|
+
deps: Deps,
|
|
79
|
+
input: { ownerId: string; subjectId: string; draft: SaleDraft; note: SignedContingencyNote; block: ContingencyBlock; xmlKey: string },
|
|
80
|
+
profile: Parameters<typeof issuerOf>[0],
|
|
81
|
+
): FiscalDocument {
|
|
82
|
+
const { note, draft } = input;
|
|
83
|
+
const at = deps.ctx.nowIso();
|
|
84
|
+
const sale = { ...draft, series: note.series, number: note.number, keyCode: note.keyCode, issuedAt: note.issuedAt, issuer: issuerOf(profile) };
|
|
85
|
+
return {
|
|
86
|
+
id: deps.config.newId(),
|
|
87
|
+
ownerId: input.ownerId,
|
|
88
|
+
issuerCnpj: note.issuerCnpj,
|
|
89
|
+
subjectId: input.subjectId,
|
|
90
|
+
issuingPointId: input.block.issuingPointId,
|
|
91
|
+
model: "NFCE",
|
|
92
|
+
environment: note.environment,
|
|
93
|
+
seriesKind: "CONTINGENCY",
|
|
94
|
+
series: note.series,
|
|
95
|
+
number: note.number,
|
|
96
|
+
keyCode: note.keyCode,
|
|
97
|
+
status: "CONTINGENCY",
|
|
98
|
+
sale,
|
|
99
|
+
// What the buyer's DANFE prints is the XML's: a resend may never change it.
|
|
100
|
+
totals: { ...totalsOf(draft), totalCents: note.totalCents, discountCents: note.discountCents },
|
|
101
|
+
buyerTaxId: note.buyerTaxId,
|
|
102
|
+
accessKey: note.accessKey,
|
|
103
|
+
protocol: null,
|
|
104
|
+
statusCode: null,
|
|
105
|
+
statusReason: null,
|
|
106
|
+
lastErrorClass: null,
|
|
107
|
+
outcomeUnknown: false,
|
|
108
|
+
issuedAt: note.issuedAt,
|
|
109
|
+
authorizedAt: null,
|
|
110
|
+
contingency: note.contingency,
|
|
111
|
+
cancelledAt: null,
|
|
112
|
+
cancelReason: null,
|
|
113
|
+
cancelProtocol: null,
|
|
114
|
+
replacedById: null,
|
|
115
|
+
numberVoid: null,
|
|
116
|
+
xmlKey: input.xmlKey,
|
|
117
|
+
eventXmlKey: null,
|
|
118
|
+
attempts: 0,
|
|
119
|
+
failures: 0,
|
|
120
|
+
nextAttemptAt: at,
|
|
121
|
+
attention: false,
|
|
122
|
+
deadlineWarnedAt: null,
|
|
123
|
+
createdAt: at,
|
|
124
|
+
updatedAt: at,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function signedEvent(document: FiscalDocument, holder: string): FiscalDocumentEvent {
|
|
129
|
+
return {
|
|
130
|
+
documentId: document.id,
|
|
131
|
+
kind: "SIGN_OFFLINE",
|
|
132
|
+
fromStatus: "PENDING",
|
|
133
|
+
toStatus: "CONTINGENCY",
|
|
134
|
+
at: document.createdAt,
|
|
135
|
+
errorClass: null,
|
|
136
|
+
code: null,
|
|
137
|
+
answer: { signedBy: "HOLDER", holder, accessKey: document.accessKey },
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** A replayed upload: the document already recorded under the key, for the same subject. */
|
|
142
|
+
function replayed(existing: FiscalDocument, subjectId: string): FiscalDocument {
|
|
143
|
+
if (existing.subjectId !== subjectId) refuse(`access key ${existing.accessKey ?? ""} is recorded for another subject.`);
|
|
144
|
+
return existing;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function blockOf(store: ContingencyBlockStore, ownerId: string, note: SignedContingencyNote, holder: string): Promise<ContingencyBlock> {
|
|
148
|
+
const block = await store.findContingencyBlock({ ownerId, issuerCnpj: note.issuerCnpj, environment: note.environment, series: note.series, number: note.number });
|
|
149
|
+
if (block === null || block.ownerId !== ownerId || block.holder !== holder) {
|
|
150
|
+
refuse(`number ${note.number} of series ${note.series} is not inside a block held by ${holder}.`);
|
|
151
|
+
}
|
|
152
|
+
// Voided at SEFAZ already (a late hand-in behind a higher number): it can never be authorised, the sale is issued online.
|
|
153
|
+
if (block.voided.some((range) => note.number >= range.from && note.number <= range.to)) {
|
|
154
|
+
refuse(`number ${note.number} of series ${note.series} was voided at SEFAZ.`);
|
|
155
|
+
}
|
|
156
|
+
return block;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The XML must print what the booked sale says: its total and its buyer (a resend could never change them). */
|
|
160
|
+
function assertMatchesSale(note: SignedContingencyNote, draft: SaleDraft): void {
|
|
161
|
+
const totalCents = totalsOf(draft).totalCents;
|
|
162
|
+
if (note.totalCents !== totalCents) refuse(`the XML's total (vNF ${note.totalCents} cents) is not the sale's (${totalCents} cents).`);
|
|
163
|
+
if (note.buyerTaxId !== (draft.buyer?.document.number ?? null)) refuse("the XML's buyer document is not the sale's.");
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The note, parsed and checked against the owner's profile. */
|
|
167
|
+
async function checkedNote(deps: Deps, input: Parameters<ContingencyBlockSource["recordSigned"]>[0]) {
|
|
168
|
+
assertHolder(input.holder);
|
|
169
|
+
if (typeof input.subjectId !== "string" || input.subjectId === "") throw new FiscalDocumentError("INVALID_INPUT", "subjectId is required.");
|
|
170
|
+
const note = parseSignedContingencyNote(input.signedXml);
|
|
171
|
+
const profile = await deps.ctx.requireProfile(input.ownerId);
|
|
172
|
+
if (note.issuerCnpj !== profile.cnpj) refuse("the XML's issuer is not the owner's CNPJ.");
|
|
173
|
+
if (note.environment !== profile.environment) refuse(`the XML was signed for ${note.environment}, the owner issues in ${profile.environment}.`);
|
|
174
|
+
return { note, profile };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Insert the note; a concurrent upload of the same note is answered, a number under another key refused. */
|
|
178
|
+
async function insertNote(store: ContingencyBlockStore, document: FiscalDocument, holder: string, subjectId: string): Promise<FiscalDocument> {
|
|
179
|
+
try {
|
|
180
|
+
return await store.recordSignedDocument(document, signedEvent(document, holder));
|
|
181
|
+
} catch (error) {
|
|
182
|
+
if (!(error instanceof FiscalDocumentError) || error.code !== "CONFLICT") throw error;
|
|
183
|
+
const raced = await store.getDocumentByAccessKey(document.ownerId, document.accessKey ?? "");
|
|
184
|
+
if (raced !== null) return replayed(raced, subjectId);
|
|
185
|
+
return refuse(`number ${document.number} of series ${document.series} is recorded under another key.`);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export async function recordSigned(deps: Deps, input: Parameters<ContingencyBlockSource["recordSigned"]>[0]): Promise<FiscalDocument> {
|
|
190
|
+
const store = blockStore(deps.config.store);
|
|
191
|
+
const { note, profile } = await checkedNote(deps, input);
|
|
192
|
+
const existing = await store.getDocumentByAccessKey(input.ownerId, note.accessKey);
|
|
193
|
+
if (existing !== null) return replayed(existing, input.subjectId);
|
|
194
|
+
const block = await blockOf(store, input.ownerId, note, input.holder);
|
|
195
|
+
const draft = input.sale ?? (await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: input.subjectId, model: "NFCE" }));
|
|
196
|
+
assertDraftFits(draft, "NFCE");
|
|
197
|
+
assertMatchesSale(note, draft);
|
|
198
|
+
const xmlKey = xmlKeys.signed(note.accessKey);
|
|
199
|
+
await deps.config.storage.put(xmlKey, input.signedXml, "application/xml");
|
|
200
|
+
const document = signedDocument(deps, { ownerId: input.ownerId, subjectId: input.subjectId, draft, note, block, xmlKey }, profile);
|
|
201
|
+
return insertNote(store, document, input.holder, input.subjectId);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function heldBlock(
|
|
205
|
+
deps: Deps,
|
|
206
|
+
store: ContingencyBlockStore,
|
|
207
|
+
input: { ownerId: string; holder: string; series: number; from: number },
|
|
208
|
+
): Promise<ContingencyBlockState> {
|
|
209
|
+
const profile = await deps.ctx.requireProfile(input.ownerId);
|
|
210
|
+
const block = await store.findContingencyBlock({
|
|
211
|
+
ownerId: input.ownerId, issuerCnpj: profile.cnpj, environment: profile.environment, series: input.series, number: input.from,
|
|
212
|
+
});
|
|
213
|
+
if (block === null || block.holder !== input.holder || block.from !== input.from) throw new FiscalDocumentError("NOT_FOUND", `${input.holder} holds no block of series ${input.series} from ${input.from}.`);
|
|
214
|
+
return block;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export async function closeBlock(deps: Deps, input: Parameters<ContingencyBlockSource["closeBlock"]>[0]): Promise<ContingencyBlock> {
|
|
218
|
+
const store = blockStore(deps.config.store);
|
|
219
|
+
assertHolder(input.holder);
|
|
220
|
+
const block = await heldBlock(deps, store, input);
|
|
221
|
+
const used = input.sequenceUsed;
|
|
222
|
+
if (!Number.isInteger(used) || used < block.from - 1 || used > block.to) {
|
|
223
|
+
throw new FiscalDocumentError("INVALID_INPUT", `sequenceUsed must be from ${block.from - 1} to ${block.to}.`);
|
|
224
|
+
}
|
|
225
|
+
if (block.fate === "CLOSED" && block.usedUpTo === used) return block;
|
|
226
|
+
if (block.fate !== "OPEN") throw new FiscalDocumentError("TRANSITION_REFUSED", `the block from ${block.from} is ${block.fate}.`);
|
|
227
|
+
const at = deps.ctx.nowIso();
|
|
228
|
+
if (!(await store.closeContingencyBlock({ id: block.id, fate: "CLOSED", usedUpTo: used, at }))) {
|
|
229
|
+
throw new FiscalDocumentError("CONFLICT", `the block from ${block.from} moved while it was closed.`);
|
|
230
|
+
}
|
|
231
|
+
return { ...block, fate: "CLOSED", usedUpTo: used, closedAt: at };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** The holder is gone (a new install took its place): its open blocks are ABANDONED. Answers them. */
|
|
235
|
+
export async function abandonBlocks(deps: Deps, input: { ownerId: string; holder: string }): Promise<ContingencyBlock[]> {
|
|
236
|
+
const store = blockStore(deps.config.store);
|
|
237
|
+
assertHolder(input.holder);
|
|
238
|
+
const open = await allBlocks(store, { ownerId: input.ownerId, holder: input.holder, fates: ["OPEN"] });
|
|
239
|
+
const at = deps.ctx.nowIso();
|
|
240
|
+
const abandoned: ContingencyBlock[] = [];
|
|
241
|
+
for (const block of open) {
|
|
242
|
+
if (await store.closeContingencyBlock({ id: block.id, fate: "ABANDONED", usedUpTo: null, at })) {
|
|
243
|
+
abandoned.push({ ...block, fate: "ABANDONED", closedAt: at });
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return abandoned;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export async function listBlocks(
|
|
250
|
+
deps: Deps,
|
|
251
|
+
input: { ownerId: string; holder?: string; fates?: readonly ContingencyBlockFate[] },
|
|
252
|
+
): Promise<ContingencyBlockState[]> {
|
|
253
|
+
return allBlocks(blockStore(deps.config.store), input);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export { listKnownGaps, listUnknownRanges, voidKnownGaps } from "./contingency-pass";
|
|
257
|
+
export type { GapVoidReport } from "./contingency-pass";
|
package/src/documents/errors.ts
CHANGED
|
@@ -41,7 +41,14 @@ export type FiscalDocumentErrorCode =
|
|
|
41
41
|
* the buyer's return NF-e of entry answers a consumer's NFC-e only; an NF-e
|
|
42
42
|
* past its window is the issuer's own correction, not this path's.
|
|
43
43
|
*/
|
|
44
|
-
| "RETURN_OF_NFCE_ONLY"
|
|
44
|
+
| "RETURN_OF_NFCE_ONLY"
|
|
45
|
+
/**
|
|
46
|
+
* `recordSigned` (FUT-4717): an XML a holder signed offline that the package
|
|
47
|
+
* will not record — another CNPJ or environment, not a model 65, not
|
|
48
|
+
* `tpEmis = 9`, a key whose check digit or fields are wrong, or a number
|
|
49
|
+
* outside every block that holder was given. Nothing was recorded.
|
|
50
|
+
*/
|
|
51
|
+
| "CONTINGENCY_XML_REFUSED";
|
|
45
52
|
|
|
46
53
|
export class FiscalDocumentError extends Error {
|
|
47
54
|
readonly code: FiscalDocumentErrorCode;
|
package/src/documents/helpers.ts
CHANGED
|
@@ -77,8 +77,13 @@ export const xmlKeys = {
|
|
|
77
77
|
`fiscal/${accessKey}/signed-${trimEnd(digest.replace(/\+/g, "-").replace(/\//g, "_"), "=")}.xml`,
|
|
78
78
|
authorized: (accessKey: string) => `fiscal/${accessKey}/authorized.xml`,
|
|
79
79
|
cancel: (accessKey: string) => `fiscal/${accessKey}/cancel.xml`,
|
|
80
|
+
/** The event 110300 of `nSeqEvento` `sequence`. */
|
|
81
|
+
linkPayment: (accessKey: string, sequence: number) => `fiscal/${accessKey}/link-payment-${sequence}.xml`,
|
|
80
82
|
inutilization: (document: FiscalDocument) =>
|
|
81
83
|
`fiscal/inutilization/${document.environment}/${document.model}/${document.ownerId}/${document.series}-${document.number}.xml`,
|
|
84
|
+
/** A range of a contingency block voided at once (FUT-4717). */
|
|
85
|
+
inutilizedRange: (gap: { environment: string; ownerId: string; series: number; from: number; to: number }) =>
|
|
86
|
+
`fiscal/inutilization/${gap.environment}/NFCE/${gap.ownerId}/${gap.series}-${gap.from}-${gap.to}.xml`,
|
|
82
87
|
};
|
|
83
88
|
|
|
84
89
|
/** The IBGE code of each federative unit: the access key's first two digits. */
|
package/src/documents/index.ts
CHANGED
|
@@ -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 {
|
|
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";
|
|
@@ -30,7 +52,8 @@ export {
|
|
|
30
52
|
} from "./context";
|
|
31
53
|
export type { FiscalDocumentsConfig, FiscalNotifyPort, FiscalReasons } from "./context";
|
|
32
54
|
export { CONTINGENCY_WARNING_AFTER_MS, LATE_CANCEL_CODES, createFiscalDocuments } from "./service";
|
|
33
|
-
export type { CancelOrReturnInput, CancelOrReturnResult, CertificateFacts, FiscalDocuments, FiscalDocumentsServiceConfig, IssueInput, SweepReport } from "./service";
|
|
55
|
+
export type { CancelOrReturnInput, CancelOrReturnResult, CertificateFacts, FiscalDocuments, FiscalDocumentsServiceConfig, IssueInput, LinkPaymentInput, LinkPaymentResult, SweepReport } from "./service";
|
|
56
|
+
export { MAX_PAYMENT_LINKS } from "./payment-link";
|
|
34
57
|
export { createMemoryFiscalStore } from "./memory";
|
|
35
58
|
export type { MemoryFiscalStore } from "./memory";
|
|
36
59
|
export { FISCAL_NEXT_NUMBER_SQL } from "./sql";
|
|
@@ -11,9 +11,10 @@ import type {
|
|
|
11
11
|
InutilizedRange,
|
|
12
12
|
IssuedDocument,
|
|
13
13
|
LookedUpDocument,
|
|
14
|
+
RegisteredPaymentLink,
|
|
14
15
|
SidecarErrorBody,
|
|
15
16
|
} from "../sidecar/types";
|
|
16
|
-
import type { SaleForDocument } from "../sale/types";
|
|
17
|
+
import type { LinkedTransaction, SaleForDocument } from "../sale/types";
|
|
17
18
|
import { FiscalDocumentError } from "./errors";
|
|
18
19
|
import { type DocumentEventKind, type DocumentTotals, type FiscalDocument, type NumberVoid, isLive } from "./types";
|
|
19
20
|
|
|
@@ -63,7 +64,15 @@ export type DocumentInput =
|
|
|
63
64
|
/** A person took a document back from `attention`: the sweep may try again. */
|
|
64
65
|
| { readonly kind: "RELEASE" }
|
|
65
66
|
/** The 24-hour contingency deadline warning went out. */
|
|
66
|
-
| { readonly kind: "WARN" }
|
|
67
|
+
| { readonly kind: "WARN" }
|
|
68
|
+
/** SEFAZ registered the event 110300 #`sequence` linking `payment` to the document; its XML is at `eventXmlKey`. */
|
|
69
|
+
| {
|
|
70
|
+
readonly kind: "LINK_PAYMENT";
|
|
71
|
+
readonly answer: RegisteredPaymentLink;
|
|
72
|
+
readonly payment: LinkedTransaction;
|
|
73
|
+
readonly sequence: number;
|
|
74
|
+
readonly eventXmlKey: string | null;
|
|
75
|
+
};
|
|
67
76
|
|
|
68
77
|
type InputOf<K extends DocumentEventKind> = Extract<DocumentInput, { kind: K }>;
|
|
69
78
|
type Step = { readonly [K in DocumentEventKind]: (document: FiscalDocument, input: InputOf<K>) => Partial<FiscalDocument> };
|
|
@@ -257,4 +266,5 @@ export const STEPS: Step = {
|
|
|
257
266
|
},
|
|
258
267
|
// `deadlineWarnedAt` is the transition's own time, set by `transition`.
|
|
259
268
|
WARN: () => ({}),
|
|
269
|
+
LINK_PAYMENT: () => ({}),
|
|
260
270
|
};
|
package/src/documents/machine.ts
CHANGED
|
@@ -21,6 +21,9 @@
|
|
|
21
21
|
* final state. A rejected contingency NFC-e is the one way back: the store
|
|
22
22
|
* corrects it and it is signed again under the same number (`RESIGN`).
|
|
23
23
|
*
|
|
24
|
+
* `LINK_PAYMENT` records an event 110300 SEFAZ registered on an authorised
|
|
25
|
+
* document (a payment transaction linked after the fact); it changes nothing.
|
|
26
|
+
*
|
|
24
27
|
* `DEFER`, `RELEASE` and `WARN` record what the sweep and a person did without
|
|
25
28
|
* changing the state: a failed step counts toward {@link MAX_FAILURES}, after
|
|
26
29
|
* which the document waits for a person (`attention`).
|
|
@@ -52,6 +55,7 @@ export const DOCUMENT_TRANSITIONS: Readonly<Record<DocumentEventKind, readonly F
|
|
|
52
55
|
RESIGN: ["REJECTED"],
|
|
53
56
|
RELEASE: ANY,
|
|
54
57
|
WARN: ["CONTINGENCY"],
|
|
58
|
+
LINK_PAYMENT: ["AUTHORIZED"],
|
|
55
59
|
};
|
|
56
60
|
|
|
57
61
|
/** The states nothing but a lookup, a cancel or an inutilization of the number may follow. */
|
|
@@ -79,6 +83,9 @@ export function scrubSecrets(value: unknown): unknown {
|
|
|
79
83
|
}
|
|
80
84
|
|
|
81
85
|
function answerOf(input: DocumentInput): unknown {
|
|
86
|
+
if (input.kind === "LINK_PAYMENT") {
|
|
87
|
+
return { ...input.answer, payment: input.payment, sequence: input.sequence, eventXmlKey: input.eventXmlKey };
|
|
88
|
+
}
|
|
82
89
|
if ("answer" in input) return input.answer;
|
|
83
90
|
if ("error" in input && input.error !== null) return { error: input.error };
|
|
84
91
|
if (input.kind === "DEFER") return { reason: input.reason };
|
|
@@ -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
|
+
}
|
package/src/documents/memory.ts
CHANGED
|
@@ -8,13 +8,16 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import { FiscalDocumentError } from "./errors";
|
|
11
|
-
import
|
|
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,
|