@12-apps/fiscal 1.5.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -4
- package/dist/{chunk-HMTPJWXM.js → chunk-2JVTHJAU.js} +2 -2
- package/dist/{chunk-3E3NBXSW.js → chunk-CEK2GDRY.js} +5 -3
- package/dist/chunk-CEK2GDRY.js.map +1 -0
- package/dist/{chunk-MGTROA7K.js → chunk-OAQSGDZ7.js} +11 -7
- package/dist/chunk-OAQSGDZ7.js.map +1 -0
- package/dist/{chunk-G6QNU4FD.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-TJCUO6D6.js → chunk-YHSO3476.js} +6 -5
- package/dist/chunk-YHSO3476.js.map +1 -0
- package/dist/{context-CwZiHLnY.d.ts → context-Cyvfr2YB.d.ts} +155 -19
- package/dist/danfe/index.d.ts +7 -0
- package/dist/danfe/index.js +2 -2
- package/dist/documents/index.d.ts +152 -34
- package/dist/documents/index.js +1103 -305
- 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 +4 -4
- package/dist/issuer/index.d.ts +10 -3
- package/dist/issuer/index.js +18 -3
- package/dist/issuer/index.js.map +1 -1
- package/dist/jobs.d.ts +5 -5
- package/dist/jobs.js +3 -3
- 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 +6 -6
- package/dist/notifications.d.ts +4 -4
- package/dist/notifications.js +2 -2
- package/dist/{service-Cz2O84Xr.d.ts → service-BCK9aXop.d.ts} +64 -5
- package/dist/sidecar/index.d.ts +38 -249
- package/dist/sidecar/index.js +29 -1
- package/dist/sidecar/index.js.map +1 -1
- package/dist/{types-B1b8LIWX.d.ts → types-BLdkww6G.d.ts} +1 -1
- package/dist/{types-DSYwap42.d.ts → types-Sk010Em2.d.ts} +2 -2
- package/dist/types-Z5E14EPw.d.ts +254 -0
- package/package.json +2 -1
- package/prisma/fiscal.prisma +50 -1
- package/prisma/migrations/20261118180000_fiscal_contingency_blocks/migration.sql +64 -0
- package/sidecar/README.md +52 -1
- package/sidecar/bin/check-platform.php +29 -0
- package/sidecar/extensions.json +12 -0
- package/sidecar/src/Http/Request.php +6 -1
- package/sidecar/src/Kernel.php +39 -1
- 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 +3 -0
- package/src/documents/index.ts +23 -1
- package/src/documents/memory-blocks.ts +118 -0
- package/src/documents/memory.ts +6 -2
- package/src/documents/ports.ts +163 -13
- package/src/documents/service.ts +10 -0
- package/src/documents/sql-blocks.ts +202 -0
- package/src/documents/sql-store.ts +4 -3
- package/src/http.ts +1 -0
- package/src/issuer/sidecar.ts +27 -3
- package/src/manifest/index.ts +6 -4
- package/src/sidecar/index.ts +2 -0
- package/src/sidecar/platform.ts +55 -0
- package/dist/chunk-3E3NBXSW.js.map +0 -1
- package/dist/chunk-MGTROA7K.js.map +0 -1
- package/dist/chunk-TJCUO6D6.js.map +0 -1
- /package/dist/{chunk-HMTPJWXM.js.map → chunk-2JVTHJAU.js.map} +0 -0
- /package/dist/{chunk-G6QNU4FD.js.map → chunk-P7CRGZGO.js.map} +0 -0
package/dist/documents/index.js
CHANGED
|
@@ -5,9 +5,11 @@ import {
|
|
|
5
5
|
parseIssuingPointInput,
|
|
6
6
|
parseProfileInput,
|
|
7
7
|
viewOf
|
|
8
|
-
} from "../chunk-
|
|
8
|
+
} from "../chunk-2JVTHJAU.js";
|
|
9
9
|
import {
|
|
10
|
-
|
|
10
|
+
accessKeyOf,
|
|
11
|
+
element,
|
|
12
|
+
text
|
|
11
13
|
} from "../chunk-PNTKG3DZ.js";
|
|
12
14
|
import {
|
|
13
15
|
DOCUMENT_TRANSITIONS,
|
|
@@ -32,7 +34,7 @@ import {
|
|
|
32
34
|
totalsOf,
|
|
33
35
|
transition,
|
|
34
36
|
xmlKeys
|
|
35
|
-
} from "../chunk-
|
|
37
|
+
} from "../chunk-CEK2GDRY.js";
|
|
36
38
|
import {
|
|
37
39
|
FISCAL_DOCUMENT_MODELS,
|
|
38
40
|
FISCAL_DOCUMENT_STATUSES,
|
|
@@ -44,11 +46,960 @@ import {
|
|
|
44
46
|
} from "../chunk-3SDXLSG4.js";
|
|
45
47
|
import {
|
|
46
48
|
FiscalDocumentError
|
|
47
|
-
} from "../chunk-
|
|
49
|
+
} from "../chunk-WRYCYXRA.js";
|
|
48
50
|
import {
|
|
49
51
|
__name
|
|
50
52
|
} from "../chunk-7QVYU63E.js";
|
|
51
53
|
|
|
54
|
+
// src/documents/ports.ts
|
|
55
|
+
var CONTINGENCY_BLOCK_FATES = ["OPEN", "CLOSED", "ABANDONED"];
|
|
56
|
+
|
|
57
|
+
// src/documents/contingency-gaps.ts
|
|
58
|
+
function rangesOf(numbers) {
|
|
59
|
+
const sorted = [...new Set(numbers)].sort((a, b) => a - b);
|
|
60
|
+
const ranges = [];
|
|
61
|
+
for (const number of sorted) {
|
|
62
|
+
const last = ranges[ranges.length - 1];
|
|
63
|
+
if (last !== void 0 && last.to === number - 1) ranges[ranges.length - 1] = { from: last.from, to: number };
|
|
64
|
+
else ranges.push({ from: number, to: number });
|
|
65
|
+
}
|
|
66
|
+
return ranges;
|
|
67
|
+
}
|
|
68
|
+
__name(rangesOf, "rangesOf");
|
|
69
|
+
function between(from, to, keep) {
|
|
70
|
+
const out = [];
|
|
71
|
+
for (let n = from; n <= to; n += 1) if (keep(n)) out.push(n);
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
__name(between, "between");
|
|
75
|
+
function highestRecorded(block) {
|
|
76
|
+
const inside = block.documented.filter((n) => n >= block.from && n <= block.to);
|
|
77
|
+
return inside.length === 0 ? block.from - 1 : Math.max(...inside);
|
|
78
|
+
}
|
|
79
|
+
__name(highestRecorded, "highestRecorded");
|
|
80
|
+
function accountFor(block) {
|
|
81
|
+
const documented = new Set(block.documented);
|
|
82
|
+
const voided = /* @__PURE__ */ __name((n) => block.voided.some((range) => n >= range.from && n <= range.to), "voided");
|
|
83
|
+
const open = /* @__PURE__ */ __name((n) => !documented.has(n) && !voided(n), "open");
|
|
84
|
+
const highest = highestRecorded(block);
|
|
85
|
+
const known = between(block.from, highest, open);
|
|
86
|
+
let unknown = [];
|
|
87
|
+
if (block.fate === "CLOSED") {
|
|
88
|
+
const used = Math.max(highest, block.usedUpTo ?? block.from - 1);
|
|
89
|
+
known.push(...between(used + 1, block.to, open));
|
|
90
|
+
unknown = between(highest + 1, used, open);
|
|
91
|
+
} else if (block.fate === "ABANDONED") {
|
|
92
|
+
unknown = between(highest + 1, block.to, open);
|
|
93
|
+
}
|
|
94
|
+
return { known: rangesOf(known), unknown: rangesOf(unknown) };
|
|
95
|
+
}
|
|
96
|
+
__name(accountFor, "accountFor");
|
|
97
|
+
function gapOf(block, range) {
|
|
98
|
+
return {
|
|
99
|
+
blockId: block.id,
|
|
100
|
+
ownerId: block.ownerId,
|
|
101
|
+
issuingPointId: block.issuingPointId,
|
|
102
|
+
issuerCnpj: block.issuerCnpj,
|
|
103
|
+
environment: block.environment,
|
|
104
|
+
series: block.series,
|
|
105
|
+
holder: block.holder,
|
|
106
|
+
reservedAt: block.reservedAt,
|
|
107
|
+
from: range.from,
|
|
108
|
+
to: range.to
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
__name(gapOf, "gapOf");
|
|
112
|
+
function isSettled(block) {
|
|
113
|
+
if (block.fate === "OPEN") return false;
|
|
114
|
+
const { known, unknown } = accountFor(block);
|
|
115
|
+
return known.length === 0 && unknown.length === 0;
|
|
116
|
+
}
|
|
117
|
+
__name(isSettled, "isSettled");
|
|
118
|
+
|
|
119
|
+
// src/documents/contingency-pass.ts
|
|
120
|
+
var BLOCK_PAGE_SIZE = 1e3;
|
|
121
|
+
var BLOCK_METHODS = [
|
|
122
|
+
"reserveContingencyBlock",
|
|
123
|
+
"findContingencyBlock",
|
|
124
|
+
"listContingencyBlocks",
|
|
125
|
+
"closeContingencyBlock",
|
|
126
|
+
"settleContingencyBlock",
|
|
127
|
+
"recordContingencyVoid",
|
|
128
|
+
"getDocumentByAccessKey",
|
|
129
|
+
"recordSignedDocument"
|
|
130
|
+
];
|
|
131
|
+
function blockStore(store) {
|
|
132
|
+
const candidate = store;
|
|
133
|
+
if (BLOCK_METHODS.some((name) => typeof candidate[name] !== "function")) {
|
|
134
|
+
throw new FiscalDocumentError("NOT_SUPPORTED", "this FiscalStore does not keep contingency blocks (ContingencyBlockStore).");
|
|
135
|
+
}
|
|
136
|
+
return candidate;
|
|
137
|
+
}
|
|
138
|
+
__name(blockStore, "blockStore");
|
|
139
|
+
async function* blockPages(store, filter) {
|
|
140
|
+
let after2;
|
|
141
|
+
for (; ; ) {
|
|
142
|
+
const page = await store.listContingencyBlocks({ ...filter, ...after2 === void 0 ? {} : { after: after2 }, limit: BLOCK_PAGE_SIZE });
|
|
143
|
+
const last = page[page.length - 1];
|
|
144
|
+
if (last === void 0 || after2 !== void 0 && last.id === after2.id) return;
|
|
145
|
+
yield page;
|
|
146
|
+
after2 = { reservedAt: last.reservedAt, id: last.id };
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
__name(blockPages, "blockPages");
|
|
150
|
+
async function* eachBlock(pages) {
|
|
151
|
+
for await (const page of pages) yield* page;
|
|
152
|
+
}
|
|
153
|
+
__name(eachBlock, "eachBlock");
|
|
154
|
+
async function allBlocks(store, filter) {
|
|
155
|
+
const blocks = [];
|
|
156
|
+
for await (const page of blockPages(store, filter)) blocks.push(...page);
|
|
157
|
+
return blocks;
|
|
158
|
+
}
|
|
159
|
+
__name(allBlocks, "allBlocks");
|
|
160
|
+
var ownerFilter = /* @__PURE__ */ __name((ownerId) => ownerId === void 0 ? {} : { ownerId }, "ownerFilter");
|
|
161
|
+
async function listKnownGaps(deps, input) {
|
|
162
|
+
const blocks = await allBlocks(blockStore(deps.config.store), { ...ownerFilter(input.ownerId), reservedBefore: input.before, unsettledOnly: true });
|
|
163
|
+
return blocks.flatMap((block) => accountFor(block).known.map((range) => gapOf(block, range)));
|
|
164
|
+
}
|
|
165
|
+
__name(listKnownGaps, "listKnownGaps");
|
|
166
|
+
async function listUnknownRanges(deps, input) {
|
|
167
|
+
const blocks = await allBlocks(blockStore(deps.config.store), { ...ownerFilter(input.ownerId), fates: ["CLOSED", "ABANDONED"], unsettledOnly: true });
|
|
168
|
+
return blocks.flatMap((block) => accountFor(block).unknown.map((range) => gapOf(block, range)));
|
|
169
|
+
}
|
|
170
|
+
__name(listUnknownRanges, "listUnknownRanges");
|
|
171
|
+
var NOTHING = { voided: [], failures: [] };
|
|
172
|
+
async function stillUnused(store, gap) {
|
|
173
|
+
const fresh = await store.findContingencyBlock({
|
|
174
|
+
ownerId: gap.ownerId,
|
|
175
|
+
issuerCnpj: gap.issuerCnpj,
|
|
176
|
+
environment: gap.environment,
|
|
177
|
+
series: gap.series,
|
|
178
|
+
number: gap.from
|
|
179
|
+
});
|
|
180
|
+
if (fresh === null || fresh.id !== gap.blockId) return false;
|
|
181
|
+
const inside = /* @__PURE__ */ __name((n) => n >= gap.from && n <= gap.to, "inside");
|
|
182
|
+
return !fresh.documented.some(inside) && !fresh.voided.some((range) => range.from <= gap.to && range.to >= gap.from);
|
|
183
|
+
}
|
|
184
|
+
__name(stillUnused, "stillUnused");
|
|
185
|
+
async function voidGap(deps, store, gap) {
|
|
186
|
+
if (!await stillUnused(store, gap)) return NOTHING;
|
|
187
|
+
const profile = await deps.ctx.requireProfile(gap.ownerId);
|
|
188
|
+
const outcome = await deps.config.issuer.inutilize({
|
|
189
|
+
model: "NFCE",
|
|
190
|
+
environment: gap.environment,
|
|
191
|
+
signing: await deps.ctx.material(profile),
|
|
192
|
+
uf: profile.address.uf,
|
|
193
|
+
cnpj: gap.issuerCnpj,
|
|
194
|
+
year: Number(gap.reservedAt.slice(0, 4)),
|
|
195
|
+
series: gap.series,
|
|
196
|
+
from: gap.from,
|
|
197
|
+
to: gap.to,
|
|
198
|
+
reason: deps.config.reasons.inutilization
|
|
199
|
+
});
|
|
200
|
+
if (!outcome.ok) {
|
|
201
|
+
return { voided: [], failures: [{ ...gap, class: outcome.error.class, code: outcome.error.code, message: outcome.error.message }] };
|
|
202
|
+
}
|
|
203
|
+
const xml = outcome.answer.inutilizationXml;
|
|
204
|
+
const eventXmlKey = xml === null ? null : xmlKeys.inutilizedRange(gap);
|
|
205
|
+
if (eventXmlKey !== null) await deps.config.storage.put(eventXmlKey, xml ?? "", "application/xml");
|
|
206
|
+
await store.recordContingencyVoid({
|
|
207
|
+
id: deps.config.newId(),
|
|
208
|
+
blockId: gap.blockId,
|
|
209
|
+
range: { from: gap.from, to: gap.to },
|
|
210
|
+
protocol: outcome.answer.protocol,
|
|
211
|
+
eventXmlKey,
|
|
212
|
+
at: deps.ctx.nowIso()
|
|
213
|
+
});
|
|
214
|
+
return { voided: [{ ...gap, protocol: outcome.answer.protocol }], failures: [] };
|
|
215
|
+
}
|
|
216
|
+
__name(voidGap, "voidGap");
|
|
217
|
+
async function voidBlock(deps, store, block) {
|
|
218
|
+
const voided = [];
|
|
219
|
+
const failures = [];
|
|
220
|
+
for (const range of accountFor(block).known) {
|
|
221
|
+
const one = await voidGap(deps, store, gapOf(block, range));
|
|
222
|
+
voided.push(...one.voided);
|
|
223
|
+
failures.push(...one.failures);
|
|
224
|
+
}
|
|
225
|
+
const done = voided.map(({ from, to }) => ({ from, to }));
|
|
226
|
+
if (isSettled({ ...block, voided: [...block.voided, ...done] })) await store.settleContingencyBlock({ id: block.id, at: deps.ctx.nowIso() });
|
|
227
|
+
return { voided, failures };
|
|
228
|
+
}
|
|
229
|
+
__name(voidBlock, "voidBlock");
|
|
230
|
+
async function voidKnownGaps(deps, input) {
|
|
231
|
+
const store = blockStore(deps.config.store);
|
|
232
|
+
const report = { voided: [], failures: [] };
|
|
233
|
+
const pages = blockPages(store, { ...ownerFilter(input.ownerId), reservedBefore: input.before, unsettledOnly: true });
|
|
234
|
+
for await (const block of eachBlock(pages)) {
|
|
235
|
+
const one = await voidBlock(deps, store, block);
|
|
236
|
+
report.voided.push(...one.voided);
|
|
237
|
+
report.failures.push(...one.failures);
|
|
238
|
+
}
|
|
239
|
+
return report;
|
|
240
|
+
}
|
|
241
|
+
__name(voidKnownGaps, "voidKnownGaps");
|
|
242
|
+
|
|
243
|
+
// src/documents/contingency-xml.ts
|
|
244
|
+
function refuse(why) {
|
|
245
|
+
throw new FiscalDocumentError("CONTINGENCY_XML_REFUSED", why);
|
|
246
|
+
}
|
|
247
|
+
__name(refuse, "refuse");
|
|
248
|
+
function cents(value) {
|
|
249
|
+
return Math.round(Number(value ?? "0") * 100);
|
|
250
|
+
}
|
|
251
|
+
__name(cents, "cents");
|
|
252
|
+
function required(scope, tag) {
|
|
253
|
+
const value = text(scope, tag);
|
|
254
|
+
if (value === null || value.trim() === "") refuse(`the XML has no ${tag}.`);
|
|
255
|
+
return value.trim();
|
|
256
|
+
}
|
|
257
|
+
__name(required, "required");
|
|
258
|
+
function assertKeyMatches(key, ide, cnpj) {
|
|
259
|
+
const expected = [
|
|
260
|
+
required(ide, "cUF"),
|
|
261
|
+
required(ide, "dhEmi").slice(2, 4) + required(ide, "dhEmi").slice(5, 7),
|
|
262
|
+
cnpj,
|
|
263
|
+
required(ide, "mod"),
|
|
264
|
+
required(ide, "serie").padStart(3, "0"),
|
|
265
|
+
required(ide, "nNF").padStart(9, "0"),
|
|
266
|
+
required(ide, "tpEmis"),
|
|
267
|
+
required(ide, "cNF"),
|
|
268
|
+
required(ide, "cDV")
|
|
269
|
+
].join("");
|
|
270
|
+
if (expected !== key) refuse("the access key does not match the fields it encodes.");
|
|
271
|
+
}
|
|
272
|
+
__name(assertKeyMatches, "assertKeyMatches");
|
|
273
|
+
function assertSignedNote(signedXml) {
|
|
274
|
+
if (typeof signedXml !== "string" || signedXml.trim() === "") refuse("signedXml is empty.");
|
|
275
|
+
if (element(signedXml, "nfeProc") !== null || element(signedXml, "protNFe") !== null) refuse("the XML is authorised already, not a signed note.");
|
|
276
|
+
if (element(signedXml, "Signature") === null) refuse("the XML is not signed.");
|
|
277
|
+
}
|
|
278
|
+
__name(assertSignedNote, "assertSignedNote");
|
|
279
|
+
function partsOf(signedXml) {
|
|
280
|
+
assertSignedNote(signedXml);
|
|
281
|
+
const infNFe = element(signedXml, "infNFe");
|
|
282
|
+
const ide = infNFe === null ? null : element(infNFe, "ide");
|
|
283
|
+
const emit = infNFe === null ? null : element(infNFe, "emit");
|
|
284
|
+
const accessKey = accessKeyOf(signedXml);
|
|
285
|
+
if (infNFe === null || ide === null || emit === null || accessKey === null) refuse("the XML is not an NF-e: no infNFe, ide, emit or access key.");
|
|
286
|
+
return { infNFe, ide, emit, accessKey };
|
|
287
|
+
}
|
|
288
|
+
__name(partsOf, "partsOf");
|
|
289
|
+
function assertOfflineNfce({ ide, accessKey }, issuerCnpj) {
|
|
290
|
+
if (required(ide, "mod") !== "65") refuse("the XML is not an NFC-e (model 65).");
|
|
291
|
+
if (required(ide, "tpEmis") !== "9") refuse("the XML is not signed in offline contingency (tpEmis 9).");
|
|
292
|
+
if (!isValidAccessKey(accessKey)) refuse("the access key's check digit is wrong.");
|
|
293
|
+
assertKeyMatches(accessKey, ide, issuerCnpj);
|
|
294
|
+
}
|
|
295
|
+
__name(assertOfflineNfce, "assertOfflineNfce");
|
|
296
|
+
function buyerOf(infNFe) {
|
|
297
|
+
const dest = element(infNFe, "dest");
|
|
298
|
+
return text(dest, "CPF") ?? text(dest, "CNPJ") ?? text(dest, "idEstrangeiro");
|
|
299
|
+
}
|
|
300
|
+
__name(buyerOf, "buyerOf");
|
|
301
|
+
function parseSignedContingencyNote(signedXml) {
|
|
302
|
+
const parts = partsOf(signedXml);
|
|
303
|
+
const { infNFe, ide, emit, accessKey } = parts;
|
|
304
|
+
const issuerCnpj = required(emit, "CNPJ");
|
|
305
|
+
assertOfflineNfce(parts, issuerCnpj);
|
|
306
|
+
const total = element(infNFe, "ICMSTot");
|
|
307
|
+
return {
|
|
308
|
+
accessKey,
|
|
309
|
+
issuerCnpj,
|
|
310
|
+
environment: required(ide, "tpAmb") === "1" ? "producao" : "homologacao",
|
|
311
|
+
series: Number(required(ide, "serie")),
|
|
312
|
+
number: Number(required(ide, "nNF")),
|
|
313
|
+
keyCode: required(ide, "cNF"),
|
|
314
|
+
issuedAt: required(ide, "dhEmi"),
|
|
315
|
+
contingency: { since: required(ide, "dhCont"), reason: required(ide, "xJust") },
|
|
316
|
+
totalCents: cents(text(total, "vNF")),
|
|
317
|
+
discountCents: cents(text(total, "vDesc")),
|
|
318
|
+
buyerTaxId: buyerOf(infNFe)
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
__name(parseSignedContingencyNote, "parseSignedContingencyNote");
|
|
322
|
+
|
|
323
|
+
// src/documents/contingency.ts
|
|
324
|
+
var DEFAULT_CONTINGENCY_BLOCK_SIZE = 50;
|
|
325
|
+
var MAX_CONTINGENCY_BLOCK_SIZE = 1e4;
|
|
326
|
+
function assertHolder(holder) {
|
|
327
|
+
if (typeof holder !== "string" || holder.trim() === "" || holder.length > 200) {
|
|
328
|
+
throw new FiscalDocumentError("INVALID_INPUT", "holder must be a non-empty id of at most 200 characters.");
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
__name(assertHolder, "assertHolder");
|
|
332
|
+
function refuse2(why) {
|
|
333
|
+
throw new FiscalDocumentError("CONTINGENCY_XML_REFUSED", why);
|
|
334
|
+
}
|
|
335
|
+
__name(refuse2, "refuse");
|
|
336
|
+
async function reserveBlock(deps, input) {
|
|
337
|
+
const store = blockStore(deps.config.store);
|
|
338
|
+
assertHolder(input.holder);
|
|
339
|
+
const size = input.size ?? DEFAULT_CONTINGENCY_BLOCK_SIZE;
|
|
340
|
+
if (!Number.isInteger(size) || size < 1 || size > MAX_CONTINGENCY_BLOCK_SIZE) {
|
|
341
|
+
throw new FiscalDocumentError("INVALID_INPUT", `size must be a whole number from 1 to ${MAX_CONTINGENCY_BLOCK_SIZE}.`);
|
|
342
|
+
}
|
|
343
|
+
const profile = await deps.ctx.requireProfile(input.ownerId);
|
|
344
|
+
if (profile.documentPolicy !== "ISSUED_HERE") {
|
|
345
|
+
throw new FiscalDocumentError("NOT_ISSUABLE", `owner ${input.ownerId}'s documentPolicy is ${profile.documentPolicy}.`);
|
|
346
|
+
}
|
|
347
|
+
const point = await deps.ctx.requirePoint(input.ownerId, input.issuingPointId);
|
|
348
|
+
if (point.model !== "NFCE" || point.contingencySeries === null) {
|
|
349
|
+
throw new FiscalDocumentError("INVALID_INPUT", `issuing point ${point.id} has no NFC-e contingency series.`);
|
|
350
|
+
}
|
|
351
|
+
return store.reserveContingencyBlock({
|
|
352
|
+
request: {
|
|
353
|
+
ownerId: input.ownerId,
|
|
354
|
+
issuerCnpj: profile.cnpj,
|
|
355
|
+
issuingPointId: point.id,
|
|
356
|
+
environment: profile.environment,
|
|
357
|
+
model: "NFCE",
|
|
358
|
+
seriesKind: "CONTINGENCY",
|
|
359
|
+
series: point.contingencySeries
|
|
360
|
+
},
|
|
361
|
+
size,
|
|
362
|
+
id: deps.config.newId(),
|
|
363
|
+
holder: input.holder,
|
|
364
|
+
at: deps.ctx.nowIso()
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
__name(reserveBlock, "reserveBlock");
|
|
368
|
+
function signedDocument(deps, input, profile) {
|
|
369
|
+
const { note, draft } = input;
|
|
370
|
+
const at = deps.ctx.nowIso();
|
|
371
|
+
const sale = { ...draft, series: note.series, number: note.number, keyCode: note.keyCode, issuedAt: note.issuedAt, issuer: issuerOf(profile) };
|
|
372
|
+
return {
|
|
373
|
+
id: deps.config.newId(),
|
|
374
|
+
ownerId: input.ownerId,
|
|
375
|
+
issuerCnpj: note.issuerCnpj,
|
|
376
|
+
subjectId: input.subjectId,
|
|
377
|
+
issuingPointId: input.block.issuingPointId,
|
|
378
|
+
model: "NFCE",
|
|
379
|
+
environment: note.environment,
|
|
380
|
+
seriesKind: "CONTINGENCY",
|
|
381
|
+
series: note.series,
|
|
382
|
+
number: note.number,
|
|
383
|
+
keyCode: note.keyCode,
|
|
384
|
+
status: "CONTINGENCY",
|
|
385
|
+
sale,
|
|
386
|
+
// What the buyer's DANFE prints is the XML's: a resend may never change it.
|
|
387
|
+
totals: { ...totalsOf(draft), totalCents: note.totalCents, discountCents: note.discountCents },
|
|
388
|
+
buyerTaxId: note.buyerTaxId,
|
|
389
|
+
accessKey: note.accessKey,
|
|
390
|
+
protocol: null,
|
|
391
|
+
statusCode: null,
|
|
392
|
+
statusReason: null,
|
|
393
|
+
lastErrorClass: null,
|
|
394
|
+
outcomeUnknown: false,
|
|
395
|
+
issuedAt: note.issuedAt,
|
|
396
|
+
authorizedAt: null,
|
|
397
|
+
contingency: note.contingency,
|
|
398
|
+
cancelledAt: null,
|
|
399
|
+
cancelReason: null,
|
|
400
|
+
cancelProtocol: null,
|
|
401
|
+
replacedById: null,
|
|
402
|
+
numberVoid: null,
|
|
403
|
+
xmlKey: input.xmlKey,
|
|
404
|
+
eventXmlKey: null,
|
|
405
|
+
attempts: 0,
|
|
406
|
+
failures: 0,
|
|
407
|
+
nextAttemptAt: at,
|
|
408
|
+
attention: false,
|
|
409
|
+
deadlineWarnedAt: null,
|
|
410
|
+
createdAt: at,
|
|
411
|
+
updatedAt: at
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
__name(signedDocument, "signedDocument");
|
|
415
|
+
function signedEvent(document, holder) {
|
|
416
|
+
return {
|
|
417
|
+
documentId: document.id,
|
|
418
|
+
kind: "SIGN_OFFLINE",
|
|
419
|
+
fromStatus: "PENDING",
|
|
420
|
+
toStatus: "CONTINGENCY",
|
|
421
|
+
at: document.createdAt,
|
|
422
|
+
errorClass: null,
|
|
423
|
+
code: null,
|
|
424
|
+
answer: { signedBy: "HOLDER", holder, accessKey: document.accessKey }
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
__name(signedEvent, "signedEvent");
|
|
428
|
+
function replayed(existing, subjectId) {
|
|
429
|
+
if (existing.subjectId !== subjectId) refuse2(`access key ${existing.accessKey ?? ""} is recorded for another subject.`);
|
|
430
|
+
return existing;
|
|
431
|
+
}
|
|
432
|
+
__name(replayed, "replayed");
|
|
433
|
+
async function blockOf(store, ownerId, note, holder) {
|
|
434
|
+
const block = await store.findContingencyBlock({ ownerId, issuerCnpj: note.issuerCnpj, environment: note.environment, series: note.series, number: note.number });
|
|
435
|
+
if (block === null || block.ownerId !== ownerId || block.holder !== holder) {
|
|
436
|
+
refuse2(`number ${note.number} of series ${note.series} is not inside a block held by ${holder}.`);
|
|
437
|
+
}
|
|
438
|
+
if (block.voided.some((range) => note.number >= range.from && note.number <= range.to)) {
|
|
439
|
+
refuse2(`number ${note.number} of series ${note.series} was voided at SEFAZ.`);
|
|
440
|
+
}
|
|
441
|
+
return block;
|
|
442
|
+
}
|
|
443
|
+
__name(blockOf, "blockOf");
|
|
444
|
+
function assertMatchesSale(note, draft) {
|
|
445
|
+
const totalCents = totalsOf(draft).totalCents;
|
|
446
|
+
if (note.totalCents !== totalCents) refuse2(`the XML's total (vNF ${note.totalCents} cents) is not the sale's (${totalCents} cents).`);
|
|
447
|
+
if (note.buyerTaxId !== (draft.buyer?.document.number ?? null)) refuse2("the XML's buyer document is not the sale's.");
|
|
448
|
+
}
|
|
449
|
+
__name(assertMatchesSale, "assertMatchesSale");
|
|
450
|
+
async function checkedNote(deps, input) {
|
|
451
|
+
assertHolder(input.holder);
|
|
452
|
+
if (typeof input.subjectId !== "string" || input.subjectId === "") throw new FiscalDocumentError("INVALID_INPUT", "subjectId is required.");
|
|
453
|
+
const note = parseSignedContingencyNote(input.signedXml);
|
|
454
|
+
const profile = await deps.ctx.requireProfile(input.ownerId);
|
|
455
|
+
if (note.issuerCnpj !== profile.cnpj) refuse2("the XML's issuer is not the owner's CNPJ.");
|
|
456
|
+
if (note.environment !== profile.environment) refuse2(`the XML was signed for ${note.environment}, the owner issues in ${profile.environment}.`);
|
|
457
|
+
return { note, profile };
|
|
458
|
+
}
|
|
459
|
+
__name(checkedNote, "checkedNote");
|
|
460
|
+
async function insertNote(store, document, holder, subjectId) {
|
|
461
|
+
try {
|
|
462
|
+
return await store.recordSignedDocument(document, signedEvent(document, holder));
|
|
463
|
+
} catch (error) {
|
|
464
|
+
if (!(error instanceof FiscalDocumentError) || error.code !== "CONFLICT") throw error;
|
|
465
|
+
const raced = await store.getDocumentByAccessKey(document.ownerId, document.accessKey ?? "");
|
|
466
|
+
if (raced !== null) return replayed(raced, subjectId);
|
|
467
|
+
return refuse2(`number ${document.number} of series ${document.series} is recorded under another key.`);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
__name(insertNote, "insertNote");
|
|
471
|
+
async function recordSigned(deps, input) {
|
|
472
|
+
const store = blockStore(deps.config.store);
|
|
473
|
+
const { note, profile } = await checkedNote(deps, input);
|
|
474
|
+
const existing = await store.getDocumentByAccessKey(input.ownerId, note.accessKey);
|
|
475
|
+
if (existing !== null) return replayed(existing, input.subjectId);
|
|
476
|
+
const block = await blockOf(store, input.ownerId, note, input.holder);
|
|
477
|
+
const draft = input.sale ?? await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: input.subjectId, model: "NFCE" });
|
|
478
|
+
assertDraftFits(draft, "NFCE");
|
|
479
|
+
assertMatchesSale(note, draft);
|
|
480
|
+
const xmlKey = xmlKeys.signed(note.accessKey);
|
|
481
|
+
await deps.config.storage.put(xmlKey, input.signedXml, "application/xml");
|
|
482
|
+
const document = signedDocument(deps, { ownerId: input.ownerId, subjectId: input.subjectId, draft, note, block, xmlKey }, profile);
|
|
483
|
+
return insertNote(store, document, input.holder, input.subjectId);
|
|
484
|
+
}
|
|
485
|
+
__name(recordSigned, "recordSigned");
|
|
486
|
+
async function heldBlock(deps, store, input) {
|
|
487
|
+
const profile = await deps.ctx.requireProfile(input.ownerId);
|
|
488
|
+
const block = await store.findContingencyBlock({
|
|
489
|
+
ownerId: input.ownerId,
|
|
490
|
+
issuerCnpj: profile.cnpj,
|
|
491
|
+
environment: profile.environment,
|
|
492
|
+
series: input.series,
|
|
493
|
+
number: input.from
|
|
494
|
+
});
|
|
495
|
+
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}.`);
|
|
496
|
+
return block;
|
|
497
|
+
}
|
|
498
|
+
__name(heldBlock, "heldBlock");
|
|
499
|
+
async function closeBlock(deps, input) {
|
|
500
|
+
const store = blockStore(deps.config.store);
|
|
501
|
+
assertHolder(input.holder);
|
|
502
|
+
const block = await heldBlock(deps, store, input);
|
|
503
|
+
const used = input.sequenceUsed;
|
|
504
|
+
if (!Number.isInteger(used) || used < block.from - 1 || used > block.to) {
|
|
505
|
+
throw new FiscalDocumentError("INVALID_INPUT", `sequenceUsed must be from ${block.from - 1} to ${block.to}.`);
|
|
506
|
+
}
|
|
507
|
+
if (block.fate === "CLOSED" && block.usedUpTo === used) return block;
|
|
508
|
+
if (block.fate !== "OPEN") throw new FiscalDocumentError("TRANSITION_REFUSED", `the block from ${block.from} is ${block.fate}.`);
|
|
509
|
+
const at = deps.ctx.nowIso();
|
|
510
|
+
if (!await store.closeContingencyBlock({ id: block.id, fate: "CLOSED", usedUpTo: used, at })) {
|
|
511
|
+
throw new FiscalDocumentError("CONFLICT", `the block from ${block.from} moved while it was closed.`);
|
|
512
|
+
}
|
|
513
|
+
return { ...block, fate: "CLOSED", usedUpTo: used, closedAt: at };
|
|
514
|
+
}
|
|
515
|
+
__name(closeBlock, "closeBlock");
|
|
516
|
+
async function abandonBlocks(deps, input) {
|
|
517
|
+
const store = blockStore(deps.config.store);
|
|
518
|
+
assertHolder(input.holder);
|
|
519
|
+
const open = await allBlocks(store, { ownerId: input.ownerId, holder: input.holder, fates: ["OPEN"] });
|
|
520
|
+
const at = deps.ctx.nowIso();
|
|
521
|
+
const abandoned = [];
|
|
522
|
+
for (const block of open) {
|
|
523
|
+
if (await store.closeContingencyBlock({ id: block.id, fate: "ABANDONED", usedUpTo: null, at })) {
|
|
524
|
+
abandoned.push({ ...block, fate: "ABANDONED", closedAt: at });
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
return abandoned;
|
|
528
|
+
}
|
|
529
|
+
__name(abandonBlocks, "abandonBlocks");
|
|
530
|
+
async function listBlocks(deps, input) {
|
|
531
|
+
return allBlocks(blockStore(deps.config.store), input);
|
|
532
|
+
}
|
|
533
|
+
__name(listBlocks, "listBlocks");
|
|
534
|
+
|
|
535
|
+
// src/documents/sql-rows.ts
|
|
536
|
+
function iso(value) {
|
|
537
|
+
if (value === null || value === void 0) return null;
|
|
538
|
+
const date = value instanceof Date ? value : /* @__PURE__ */ new Date(`${String(value).replace(" ", "T")}${/Z|[+-]\d{2}:?\d{2}$/.test(String(value)) ? "" : "Z"}`);
|
|
539
|
+
return date.toISOString();
|
|
540
|
+
}
|
|
541
|
+
__name(iso, "iso");
|
|
542
|
+
function requiredIso(value) {
|
|
543
|
+
return iso(value) ?? "";
|
|
544
|
+
}
|
|
545
|
+
__name(requiredIso, "requiredIso");
|
|
546
|
+
function day(value) {
|
|
547
|
+
return value instanceof Date ? value.toISOString().slice(0, 10) : String(value).slice(0, 10);
|
|
548
|
+
}
|
|
549
|
+
__name(day, "day");
|
|
550
|
+
function json(value) {
|
|
551
|
+
return typeof value === "string" ? JSON.parse(value) : value;
|
|
552
|
+
}
|
|
553
|
+
__name(json, "json");
|
|
554
|
+
var text2 = /* @__PURE__ */ __name((value) => value === null || value === void 0 ? null : String(value), "text");
|
|
555
|
+
var DOCUMENT_COLUMNS = [
|
|
556
|
+
"id",
|
|
557
|
+
"owner_id",
|
|
558
|
+
"issuer_cnpj",
|
|
559
|
+
"subject_id",
|
|
560
|
+
"issuing_point_id",
|
|
561
|
+
"model",
|
|
562
|
+
"environment",
|
|
563
|
+
"series_kind",
|
|
564
|
+
"series",
|
|
565
|
+
"number",
|
|
566
|
+
"key_code",
|
|
567
|
+
"status",
|
|
568
|
+
"sale",
|
|
569
|
+
"totals",
|
|
570
|
+
"buyer_tax_id",
|
|
571
|
+
"access_key",
|
|
572
|
+
"protocol",
|
|
573
|
+
"status_code",
|
|
574
|
+
"status_reason",
|
|
575
|
+
"last_error_class",
|
|
576
|
+
"outcome_unknown",
|
|
577
|
+
"issued_at",
|
|
578
|
+
"authorized_at",
|
|
579
|
+
"contingency",
|
|
580
|
+
"cancelled_at",
|
|
581
|
+
"cancel_reason",
|
|
582
|
+
"cancel_protocol",
|
|
583
|
+
"replaced_by_id",
|
|
584
|
+
"number_void",
|
|
585
|
+
"xml_key",
|
|
586
|
+
"event_xml_key",
|
|
587
|
+
"attempts",
|
|
588
|
+
"failures",
|
|
589
|
+
"next_attempt_at",
|
|
590
|
+
"attention",
|
|
591
|
+
"deadline_warned_at",
|
|
592
|
+
"created_at",
|
|
593
|
+
"updated_at"
|
|
594
|
+
];
|
|
595
|
+
var JSON_COLUMNS = /* @__PURE__ */ new Set(["sale", "totals", "contingency"]);
|
|
596
|
+
var TIME_COLUMNS = /* @__PURE__ */ new Set(["next_attempt_at", "deadline_warned_at", "created_at", "updated_at"]);
|
|
597
|
+
function placeholder(column, index) {
|
|
598
|
+
if (JSON_COLUMNS.has(column)) return `$${index}::jsonb`;
|
|
599
|
+
if (TIME_COLUMNS.has(column)) return `$${index}::timestamp(3)`;
|
|
600
|
+
return `$${index}`;
|
|
601
|
+
}
|
|
602
|
+
__name(placeholder, "placeholder");
|
|
603
|
+
function documentValues(d) {
|
|
604
|
+
return [
|
|
605
|
+
d.id,
|
|
606
|
+
d.ownerId,
|
|
607
|
+
d.issuerCnpj,
|
|
608
|
+
d.subjectId,
|
|
609
|
+
d.issuingPointId,
|
|
610
|
+
d.model,
|
|
611
|
+
d.environment,
|
|
612
|
+
d.seriesKind,
|
|
613
|
+
d.series,
|
|
614
|
+
d.number,
|
|
615
|
+
d.keyCode,
|
|
616
|
+
d.status,
|
|
617
|
+
JSON.stringify(d.sale),
|
|
618
|
+
JSON.stringify(d.totals),
|
|
619
|
+
d.buyerTaxId,
|
|
620
|
+
d.accessKey,
|
|
621
|
+
d.protocol,
|
|
622
|
+
d.statusCode,
|
|
623
|
+
d.statusReason,
|
|
624
|
+
d.lastErrorClass,
|
|
625
|
+
d.outcomeUnknown,
|
|
626
|
+
d.issuedAt,
|
|
627
|
+
d.authorizedAt,
|
|
628
|
+
d.contingency === null ? null : JSON.stringify(d.contingency),
|
|
629
|
+
d.cancelledAt,
|
|
630
|
+
d.cancelReason,
|
|
631
|
+
d.cancelProtocol,
|
|
632
|
+
d.replacedById,
|
|
633
|
+
d.numberVoid,
|
|
634
|
+
d.xmlKey,
|
|
635
|
+
d.eventXmlKey,
|
|
636
|
+
d.attempts,
|
|
637
|
+
d.failures,
|
|
638
|
+
d.nextAttemptAt,
|
|
639
|
+
d.attention,
|
|
640
|
+
d.deadlineWarnedAt,
|
|
641
|
+
d.createdAt,
|
|
642
|
+
d.updatedAt
|
|
643
|
+
];
|
|
644
|
+
}
|
|
645
|
+
__name(documentValues, "documentValues");
|
|
646
|
+
function documentOf(row) {
|
|
647
|
+
return {
|
|
648
|
+
id: String(row["id"]),
|
|
649
|
+
ownerId: String(row["owner_id"]),
|
|
650
|
+
issuerCnpj: String(row["issuer_cnpj"]),
|
|
651
|
+
subjectId: String(row["subject_id"]),
|
|
652
|
+
issuingPointId: String(row["issuing_point_id"]),
|
|
653
|
+
model: row["model"],
|
|
654
|
+
environment: row["environment"],
|
|
655
|
+
seriesKind: row["series_kind"],
|
|
656
|
+
series: Number(row["series"]),
|
|
657
|
+
number: Number(row["number"]),
|
|
658
|
+
keyCode: String(row["key_code"]),
|
|
659
|
+
status: row["status"],
|
|
660
|
+
sale: json(row["sale"]),
|
|
661
|
+
totals: json(row["totals"]),
|
|
662
|
+
buyerTaxId: text2(row["buyer_tax_id"]),
|
|
663
|
+
accessKey: text2(row["access_key"]),
|
|
664
|
+
protocol: text2(row["protocol"]),
|
|
665
|
+
statusCode: text2(row["status_code"]),
|
|
666
|
+
statusReason: text2(row["status_reason"]),
|
|
667
|
+
lastErrorClass: text2(row["last_error_class"]),
|
|
668
|
+
outcomeUnknown: row["outcome_unknown"] === true,
|
|
669
|
+
issuedAt: String(row["issued_at"]),
|
|
670
|
+
authorizedAt: text2(row["authorized_at"]),
|
|
671
|
+
contingency: row["contingency"] === null ? null : json(row["contingency"]),
|
|
672
|
+
cancelledAt: text2(row["cancelled_at"]),
|
|
673
|
+
cancelReason: text2(row["cancel_reason"]),
|
|
674
|
+
cancelProtocol: text2(row["cancel_protocol"]),
|
|
675
|
+
replacedById: text2(row["replaced_by_id"]),
|
|
676
|
+
numberVoid: text2(row["number_void"]),
|
|
677
|
+
xmlKey: text2(row["xml_key"]),
|
|
678
|
+
eventXmlKey: text2(row["event_xml_key"]),
|
|
679
|
+
attempts: Number(row["attempts"]),
|
|
680
|
+
failures: Number(row["failures"]),
|
|
681
|
+
nextAttemptAt: iso(row["next_attempt_at"]),
|
|
682
|
+
attention: row["attention"] === true,
|
|
683
|
+
deadlineWarnedAt: iso(row["deadline_warned_at"]),
|
|
684
|
+
createdAt: requiredIso(row["created_at"]),
|
|
685
|
+
updatedAt: requiredIso(row["updated_at"])
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
__name(documentOf, "documentOf");
|
|
689
|
+
function eventOf(row) {
|
|
690
|
+
return {
|
|
691
|
+
documentId: String(row["document_id"]),
|
|
692
|
+
kind: row["kind"],
|
|
693
|
+
fromStatus: row["from_status"],
|
|
694
|
+
toStatus: row["to_status"],
|
|
695
|
+
at: requiredIso(row["at"]),
|
|
696
|
+
errorClass: text2(row["error_class"]),
|
|
697
|
+
code: text2(row["code"]),
|
|
698
|
+
answer: row["answer"] === null ? null : json(row["answer"])
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
__name(eventOf, "eventOf");
|
|
702
|
+
var PROFILE_COLUMNS = [
|
|
703
|
+
"owner_id",
|
|
704
|
+
"cnpj",
|
|
705
|
+
"state_registration",
|
|
706
|
+
"municipal_registration",
|
|
707
|
+
"cnae",
|
|
708
|
+
"legal_name",
|
|
709
|
+
"trade_name",
|
|
710
|
+
"tax_regime",
|
|
711
|
+
"regime",
|
|
712
|
+
"regime_effective_from",
|
|
713
|
+
"restaurant_regime",
|
|
714
|
+
"address",
|
|
715
|
+
"environment",
|
|
716
|
+
"document_policy",
|
|
717
|
+
"signing_identity",
|
|
718
|
+
"certificate_ciphertext",
|
|
719
|
+
"certificate_password_ciphertext",
|
|
720
|
+
"certificate_expires_at",
|
|
721
|
+
"csc_id",
|
|
722
|
+
"csc_ciphertext",
|
|
723
|
+
"consent_recorded_at",
|
|
724
|
+
"updated_at"
|
|
725
|
+
];
|
|
726
|
+
function profilePlaceholder(column, index) {
|
|
727
|
+
if (column === "address") return `$${index}::jsonb`;
|
|
728
|
+
if (column === "regime_effective_from") return `$${index}::date`;
|
|
729
|
+
if (column.endsWith("_at")) return `$${index}::timestamp(3)`;
|
|
730
|
+
return `$${index}`;
|
|
731
|
+
}
|
|
732
|
+
__name(profilePlaceholder, "profilePlaceholder");
|
|
733
|
+
function profileValues(p) {
|
|
734
|
+
return [
|
|
735
|
+
p.ownerId,
|
|
736
|
+
p.cnpj,
|
|
737
|
+
p.stateRegistration,
|
|
738
|
+
p.municipalRegistration,
|
|
739
|
+
p.cnae,
|
|
740
|
+
p.legalName,
|
|
741
|
+
p.tradeName,
|
|
742
|
+
p.taxRegime,
|
|
743
|
+
p.regime,
|
|
744
|
+
p.regimeEffectiveFrom,
|
|
745
|
+
p.restaurantRegime,
|
|
746
|
+
JSON.stringify(p.address),
|
|
747
|
+
p.environment,
|
|
748
|
+
p.documentPolicy,
|
|
749
|
+
p.signingIdentity,
|
|
750
|
+
p.certificateCiphertext,
|
|
751
|
+
p.certificatePasswordCiphertext,
|
|
752
|
+
p.certificateExpiresAt,
|
|
753
|
+
p.cscId,
|
|
754
|
+
p.cscCiphertext,
|
|
755
|
+
p.consentRecordedAt,
|
|
756
|
+
p.updatedAt
|
|
757
|
+
];
|
|
758
|
+
}
|
|
759
|
+
__name(profileValues, "profileValues");
|
|
760
|
+
function profileOf(row) {
|
|
761
|
+
return {
|
|
762
|
+
ownerId: String(row["owner_id"]),
|
|
763
|
+
cnpj: String(row["cnpj"]),
|
|
764
|
+
stateRegistration: String(row["state_registration"]),
|
|
765
|
+
municipalRegistration: text2(row["municipal_registration"]),
|
|
766
|
+
cnae: text2(row["cnae"]),
|
|
767
|
+
legalName: String(row["legal_name"]),
|
|
768
|
+
tradeName: text2(row["trade_name"]),
|
|
769
|
+
taxRegime: row["tax_regime"],
|
|
770
|
+
regime: row["regime"],
|
|
771
|
+
regimeEffectiveFrom: day(row["regime_effective_from"]),
|
|
772
|
+
restaurantRegime: row["restaurant_regime"] === true,
|
|
773
|
+
address: json(row["address"]),
|
|
774
|
+
environment: row["environment"],
|
|
775
|
+
documentPolicy: row["document_policy"],
|
|
776
|
+
signingIdentity: row["signing_identity"],
|
|
777
|
+
certificateCiphertext: text2(row["certificate_ciphertext"]),
|
|
778
|
+
certificatePasswordCiphertext: text2(row["certificate_password_ciphertext"]),
|
|
779
|
+
certificateExpiresAt: iso(row["certificate_expires_at"]),
|
|
780
|
+
cscId: text2(row["csc_id"]),
|
|
781
|
+
cscCiphertext: text2(row["csc_ciphertext"]),
|
|
782
|
+
consentRecordedAt: iso(row["consent_recorded_at"]),
|
|
783
|
+
updatedAt: requiredIso(row["updated_at"])
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
__name(profileOf, "profileOf");
|
|
787
|
+
function pointOf(row) {
|
|
788
|
+
return {
|
|
789
|
+
id: String(row["id"]),
|
|
790
|
+
ownerId: String(row["owner_id"]),
|
|
791
|
+
model: row["model"],
|
|
792
|
+
onlineSeries: Number(row["online_series"]),
|
|
793
|
+
contingencySeries: row["contingency_series"] === null ? null : Number(row["contingency_series"]),
|
|
794
|
+
createdAt: requiredIso(row["created_at"])
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
__name(pointOf, "pointOf");
|
|
798
|
+
|
|
799
|
+
// src/documents/sql-blocks.ts
|
|
800
|
+
var FISCAL_RESERVE_BLOCK_SQL = `UPDATE "fiscal_number_counters"
|
|
801
|
+
SET "next_number" = "next_number" + $6::integer, "updated_at" = CURRENT_TIMESTAMP
|
|
802
|
+
WHERE "issuer_cnpj" = $1 AND "environment" = $2 AND "model" = $3 AND "series" = $4 AND "issuing_point_id" = $5
|
|
803
|
+
AND "series_kind" = 'CONTINGENCY'
|
|
804
|
+
RETURNING "next_number" - $6::integer AS "first"`;
|
|
805
|
+
var rows = /* @__PURE__ */ __name((client, query, ...values) => client.$queryRawUnsafe(query, ...values), "rows");
|
|
806
|
+
function violates(error, constraint) {
|
|
807
|
+
const text3 = error instanceof Error ? `${error.message} ${JSON.stringify(error.meta ?? "")}` : String(error);
|
|
808
|
+
return text3.includes(constraint);
|
|
809
|
+
}
|
|
810
|
+
__name(violates, "violates");
|
|
811
|
+
var iso2 = /* @__PURE__ */ __name((value) => value === null || value === void 0 ? null : new Date(value instanceof Date ? value : `${String(value).replace(" ", "T")}Z`).toISOString(), "iso");
|
|
812
|
+
function blockOf2(row) {
|
|
813
|
+
return {
|
|
814
|
+
id: String(row["id"]),
|
|
815
|
+
ownerId: String(row["owner_id"]),
|
|
816
|
+
issuingPointId: String(row["issuing_point_id"]),
|
|
817
|
+
issuerCnpj: String(row["issuer_cnpj"]),
|
|
818
|
+
environment: row["environment"],
|
|
819
|
+
model: "NFCE",
|
|
820
|
+
series: Number(row["series"]),
|
|
821
|
+
from: Number(row["first_number"]),
|
|
822
|
+
to: Number(row["last_number"]),
|
|
823
|
+
holder: String(row["holder"]),
|
|
824
|
+
fate: row["fate"],
|
|
825
|
+
usedUpTo: row["used_up_to"] === null ? null : Number(row["used_up_to"]),
|
|
826
|
+
reservedAt: iso2(row["reserved_at"]) ?? "",
|
|
827
|
+
closedAt: iso2(row["closed_at"]),
|
|
828
|
+
settledAt: iso2(row["settled_at"])
|
|
829
|
+
};
|
|
830
|
+
}
|
|
831
|
+
__name(blockOf2, "blockOf");
|
|
832
|
+
var INSERT_BLOCK = `INSERT INTO "fiscal_contingency_blocks"
|
|
833
|
+
("id", "owner_id", "issuing_point_id", "issuer_cnpj", "environment", "model", "series", "first_number", "last_number", "holder", "reserved_at")
|
|
834
|
+
VALUES ($1, $2, $3, $4, $5, 'NFCE', $6, $7, $8, $9, $10::timestamp(3))`;
|
|
835
|
+
var INSERT_DOCUMENT = `INSERT INTO "fiscal_documents" (${DOCUMENT_COLUMNS.map((c) => `"${c}"`).join(", ")})
|
|
836
|
+
VALUES (${DOCUMENT_COLUMNS.map((c, i) => placeholder(c, i + 1)).join(", ")})`;
|
|
837
|
+
var INSERT_EVENT = `INSERT INTO "fiscal_document_events" ("id", "document_id", "kind", "from_status", "to_status", "at", "error_class", "code", "answer")
|
|
838
|
+
VALUES ($1, $2, $3, $4, $5, $6::timestamp(3), $7, $8, $9::jsonb)`;
|
|
839
|
+
async function reserve(db, input) {
|
|
840
|
+
const { request, size, id, holder, at } = input;
|
|
841
|
+
try {
|
|
842
|
+
return await db.$transaction(async (tx) => {
|
|
843
|
+
const [row] = await rows(tx, FISCAL_RESERVE_BLOCK_SQL, request.issuerCnpj, request.environment, request.model, request.series, request.issuingPointId, size);
|
|
844
|
+
if (row === void 0) {
|
|
845
|
+
throw new FiscalDocumentError("NOT_FOUND", `no contingency counter for series ${request.series} on issuing point ${request.issuingPointId}.`);
|
|
846
|
+
}
|
|
847
|
+
const first = Number(row["first"]);
|
|
848
|
+
await tx.$executeRawUnsafe(
|
|
849
|
+
INSERT_BLOCK,
|
|
850
|
+
id,
|
|
851
|
+
request.ownerId,
|
|
852
|
+
request.issuingPointId,
|
|
853
|
+
request.issuerCnpj,
|
|
854
|
+
request.environment,
|
|
855
|
+
request.series,
|
|
856
|
+
first,
|
|
857
|
+
first + size - 1,
|
|
858
|
+
holder,
|
|
859
|
+
at
|
|
860
|
+
);
|
|
861
|
+
const [stored] = await rows(tx, `SELECT * FROM "fiscal_contingency_blocks" WHERE "id" = $1`, id);
|
|
862
|
+
return blockOf2(stored ?? {});
|
|
863
|
+
});
|
|
864
|
+
} catch (error) {
|
|
865
|
+
if (violates(error, "fiscal_number_counters_next_number_check") || violates(error, "fiscal_contingency_blocks_range_check")) {
|
|
866
|
+
throw new FiscalDocumentError("SERIES_EXHAUSTED", `series ${request.series} has no ${size} numbers left.`);
|
|
867
|
+
}
|
|
868
|
+
throw error;
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
__name(reserve, "reserve");
|
|
872
|
+
async function insertSigned(db, document, event) {
|
|
873
|
+
try {
|
|
874
|
+
await db.$transaction(async (tx) => {
|
|
875
|
+
await tx.$executeRawUnsafe(INSERT_DOCUMENT, ...documentValues(document));
|
|
876
|
+
await tx.$executeRawUnsafe(
|
|
877
|
+
INSERT_EVENT,
|
|
878
|
+
globalThis.crypto.randomUUID(),
|
|
879
|
+
event.documentId,
|
|
880
|
+
event.kind,
|
|
881
|
+
event.fromStatus,
|
|
882
|
+
event.toStatus,
|
|
883
|
+
event.at,
|
|
884
|
+
event.errorClass,
|
|
885
|
+
event.code,
|
|
886
|
+
JSON.stringify(event.answer)
|
|
887
|
+
);
|
|
888
|
+
});
|
|
889
|
+
return document;
|
|
890
|
+
} catch (error) {
|
|
891
|
+
if (violates(error, "fiscal_documents_live_subject_key")) {
|
|
892
|
+
throw new FiscalDocumentError("SUBJECT_HAS_DOCUMENT", `subject ${document.subjectId} already has a live ${document.model}.`);
|
|
893
|
+
}
|
|
894
|
+
if (violates(error, "fiscal_documents_access_key_key") || violates(error, "fiscal_documents_number_key")) {
|
|
895
|
+
throw new FiscalDocumentError("CONFLICT", `key ${document.accessKey ?? ""} or number ${document.number} is recorded already.`);
|
|
896
|
+
}
|
|
897
|
+
throw error;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
__name(insertSigned, "insertSigned");
|
|
901
|
+
async function withState(db, blocks) {
|
|
902
|
+
if (blocks.length === 0) return [];
|
|
903
|
+
const ids = blocks.map((block) => block.id);
|
|
904
|
+
const documented = await rows(
|
|
905
|
+
db,
|
|
906
|
+
`SELECT b."id" AS "block_id", d."number" FROM "fiscal_contingency_blocks" b
|
|
907
|
+
JOIN "fiscal_documents" d ON d."issuer_cnpj" = b."issuer_cnpj" AND d."environment" = b."environment" AND d."model" = b."model"
|
|
908
|
+
AND d."series" = b."series" AND d."number" BETWEEN b."first_number" AND b."last_number"
|
|
909
|
+
WHERE b."id" = ANY($1::text[]) ORDER BY d."number"`,
|
|
910
|
+
ids
|
|
911
|
+
);
|
|
912
|
+
const voids = await rows(db, `SELECT * FROM "fiscal_contingency_voids" WHERE "block_id" = ANY($1::text[]) ORDER BY "first_number"`, ids);
|
|
913
|
+
return blocks.map((block) => ({
|
|
914
|
+
...block,
|
|
915
|
+
documented: documented.filter((row) => row["block_id"] === block.id).map((row) => Number(row["number"])),
|
|
916
|
+
voided: voids.filter((row) => row["block_id"] === block.id).map((row) => ({ from: Number(row["first_number"]), to: Number(row["last_number"]) }))
|
|
917
|
+
}));
|
|
918
|
+
}
|
|
919
|
+
__name(withState, "withState");
|
|
920
|
+
async function list(db, input) {
|
|
921
|
+
const where = [];
|
|
922
|
+
const values = [];
|
|
923
|
+
const add = /* @__PURE__ */ __name((clause, value) => {
|
|
924
|
+
values.push(value);
|
|
925
|
+
where.push(clause(values.length));
|
|
926
|
+
}, "add");
|
|
927
|
+
if (input.ownerId !== void 0) add((n) => `"owner_id" = $${n}`, input.ownerId);
|
|
928
|
+
if (input.holder !== void 0) add((n) => `"holder" = $${n}`, input.holder);
|
|
929
|
+
if (input.fates !== void 0) add((n) => `"fate" = ANY($${n}::text[])`, [...input.fates]);
|
|
930
|
+
if (input.reservedBefore !== void 0) add((n) => `"reserved_at" < $${n}::timestamp(3)`, input.reservedBefore);
|
|
931
|
+
if (input.unsettledOnly === true) where.push(`"settled_at" IS NULL`);
|
|
932
|
+
if (input.after !== void 0) {
|
|
933
|
+
values.push(input.after.reservedAt, input.after.id);
|
|
934
|
+
where.push(`("reserved_at", "id") > ($${values.length - 1}::timestamp(3), $${values.length})`);
|
|
935
|
+
}
|
|
936
|
+
values.push(input.limit);
|
|
937
|
+
const blocks = (await rows(
|
|
938
|
+
db,
|
|
939
|
+
`SELECT * FROM "fiscal_contingency_blocks" ${where.length === 0 ? "" : `WHERE ${where.join(" AND ")}`}
|
|
940
|
+
ORDER BY "reserved_at", "id" LIMIT $${values.length}`,
|
|
941
|
+
...values
|
|
942
|
+
)).map(blockOf2);
|
|
943
|
+
return withState(db, blocks);
|
|
944
|
+
}
|
|
945
|
+
__name(list, "list");
|
|
946
|
+
function blockMethods(db) {
|
|
947
|
+
return {
|
|
948
|
+
reserveContingencyBlock: /* @__PURE__ */ __name((input) => reserve(db, input), "reserveContingencyBlock"),
|
|
949
|
+
async findContingencyBlock(input) {
|
|
950
|
+
const [row] = await rows(
|
|
951
|
+
db,
|
|
952
|
+
`SELECT * FROM "fiscal_contingency_blocks"
|
|
953
|
+
WHERE "owner_id" = $1 AND "issuer_cnpj" = $2 AND "environment" = $3 AND "model" = 'NFCE' AND "series" = $4
|
|
954
|
+
AND $5::integer BETWEEN "first_number" AND "last_number"`,
|
|
955
|
+
input.ownerId,
|
|
956
|
+
input.issuerCnpj,
|
|
957
|
+
input.environment,
|
|
958
|
+
input.series,
|
|
959
|
+
input.number
|
|
960
|
+
);
|
|
961
|
+
return row === void 0 ? null : (await withState(db, [blockOf2(row)]))[0] ?? null;
|
|
962
|
+
},
|
|
963
|
+
listContingencyBlocks: /* @__PURE__ */ __name((input) => list(db, input), "listContingencyBlocks"),
|
|
964
|
+
async closeContingencyBlock({ id, fate, usedUpTo, at }) {
|
|
965
|
+
const updated = await rows(
|
|
966
|
+
db,
|
|
967
|
+
`UPDATE "fiscal_contingency_blocks" SET "fate" = $2, "used_up_to" = $3, "closed_at" = $4::timestamp(3)
|
|
968
|
+
WHERE "id" = $1 AND "fate" = 'OPEN' RETURNING "id"`,
|
|
969
|
+
id,
|
|
970
|
+
fate,
|
|
971
|
+
usedUpTo,
|
|
972
|
+
at
|
|
973
|
+
);
|
|
974
|
+
return updated.length > 0;
|
|
975
|
+
},
|
|
976
|
+
async settleContingencyBlock({ id, at }) {
|
|
977
|
+
await db.$executeRawUnsafe(`UPDATE "fiscal_contingency_blocks" SET "settled_at" = $2::timestamp(3) WHERE "id" = $1`, id, at);
|
|
978
|
+
},
|
|
979
|
+
async recordContingencyVoid({ id, blockId, range, protocol, eventXmlKey, at }) {
|
|
980
|
+
const inserted = await rows(
|
|
981
|
+
db,
|
|
982
|
+
`INSERT INTO "fiscal_contingency_voids" ("id", "block_id", "first_number", "last_number", "protocol", "event_xml_key", "voided_at")
|
|
983
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7::timestamp(3)) ON CONFLICT ("block_id", "first_number") DO NOTHING RETURNING "id"`,
|
|
984
|
+
id,
|
|
985
|
+
blockId,
|
|
986
|
+
range.from,
|
|
987
|
+
range.to,
|
|
988
|
+
protocol,
|
|
989
|
+
eventXmlKey,
|
|
990
|
+
at
|
|
991
|
+
);
|
|
992
|
+
return inserted.length > 0;
|
|
993
|
+
},
|
|
994
|
+
async getDocumentByAccessKey(ownerId, accessKey) {
|
|
995
|
+
const [row] = await rows(db, `SELECT * FROM "fiscal_documents" WHERE "owner_id" = $1 AND "access_key" = $2`, ownerId, accessKey);
|
|
996
|
+
return row === void 0 ? null : documentOf(row);
|
|
997
|
+
},
|
|
998
|
+
recordSignedDocument: /* @__PURE__ */ __name((document, event) => insertSigned(db, document, event), "recordSignedDocument")
|
|
999
|
+
};
|
|
1000
|
+
}
|
|
1001
|
+
__name(blockMethods, "blockMethods");
|
|
1002
|
+
|
|
52
1003
|
// src/documents/signing.ts
|
|
53
1004
|
function createStoreCertificateIdentity(config) {
|
|
54
1005
|
if (typeof config?.cipher?.decrypt !== "function") throw new TypeError("createStoreCertificateIdentity needs a cipher.");
|
|
@@ -691,8 +1642,8 @@ async function lookup(deps, input) {
|
|
|
691
1642
|
if (!lookupMoves(document)) return { document, answer: outcome.answer, failure: null };
|
|
692
1643
|
const xmlKey = document.status === "SUBMITTED" ? await storeNfeProc(deps.ctx, document, outcome.answer) : void 0;
|
|
693
1644
|
const looked = await deps.ctx.advance(document, { kind: "LOOKUP", answer: outcome.answer, ...xmlKey === void 0 ? {} : { xmlKey } });
|
|
694
|
-
const
|
|
695
|
-
return { document:
|
|
1645
|
+
const after2 = document.status === "REJECTED" ? await settleWithXml(deps.ctx, looked, outcome.answer) : looked;
|
|
1646
|
+
return { document: after2, answer: outcome.answer, failure: null };
|
|
696
1647
|
}
|
|
697
1648
|
__name(lookup, "lookup");
|
|
698
1649
|
async function step({ ctx }, document) {
|
|
@@ -717,8 +1668,8 @@ async function run(deps, documents) {
|
|
|
717
1668
|
const report = { advanced: [], failures: [] };
|
|
718
1669
|
for (const document of documents) {
|
|
719
1670
|
try {
|
|
720
|
-
const
|
|
721
|
-
report.advanced.push({ documentId:
|
|
1671
|
+
const after2 = await step(deps, document);
|
|
1672
|
+
report.advanced.push({ documentId: after2.id, status: after2.status });
|
|
722
1673
|
} catch (error) {
|
|
723
1674
|
report.failures.push({ documentId: document.id, message: error instanceof Error ? error.message : "unknown failure" });
|
|
724
1675
|
await deferThrown(deps, document, error);
|
|
@@ -778,20 +1729,124 @@ function createFiscalDocuments(config) {
|
|
|
778
1729
|
await requireDocument(deps, ownerId, documentId);
|
|
779
1730
|
return store.listEvents(documentId);
|
|
780
1731
|
},
|
|
781
|
-
/** One pass of the retry sweep: PENDING/SUBMITTED documents and owed numbers whose next attempt has come. */
|
|
782
|
-
sweep: /* @__PURE__ */ __name(async (limit) => run(deps, await store.listDue({ now: deps.ctx.nowIso(), limit })), "sweep"),
|
|
783
|
-
/**
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
1732
|
+
/** One pass of the retry sweep: PENDING/SUBMITTED documents and owed numbers whose next attempt has come. */
|
|
1733
|
+
sweep: /* @__PURE__ */ __name(async (limit) => run(deps, await store.listDue({ now: deps.ctx.nowIso(), limit })), "sweep"),
|
|
1734
|
+
/** Contingency blocks (FUT-4717), the ContingencyBlockSource; `NOT_SUPPORTED` over a store without them. */
|
|
1735
|
+
reserveBlock: reserveBlock.bind(null, deps),
|
|
1736
|
+
recordSigned: recordSigned.bind(null, deps),
|
|
1737
|
+
closeBlock: closeBlock.bind(null, deps),
|
|
1738
|
+
abandonBlocks: abandonBlocks.bind(null, deps),
|
|
1739
|
+
listBlocks: listBlocks.bind(null, deps),
|
|
1740
|
+
listKnownGaps: listKnownGaps.bind(null, deps),
|
|
1741
|
+
listUnknownRanges: listUnknownRanges.bind(null, deps),
|
|
1742
|
+
voidKnownGaps: voidKnownGaps.bind(null, deps),
|
|
1743
|
+
/** One pass of the contingency transmission, then the 20-hour deadline warnings. */
|
|
1744
|
+
async transmitContingency(limit) {
|
|
1745
|
+
const report = await run(deps, await store.listContingency({ now: deps.ctx.nowIso(), limit }));
|
|
1746
|
+
await warnContingencyDeadlines(deps, limit);
|
|
1747
|
+
return report;
|
|
1748
|
+
}
|
|
1749
|
+
};
|
|
1750
|
+
}
|
|
1751
|
+
__name(createFiscalDocuments, "createFiscalDocuments");
|
|
1752
|
+
|
|
1753
|
+
// src/documents/memory-blocks.ts
|
|
1754
|
+
var MAX_NUMBER = 999999999;
|
|
1755
|
+
function sameSeries(a, b) {
|
|
1756
|
+
return a.issuerCnpj === b.issuerCnpj && a.environment === b.environment && a.model === b.model && a.series === b.series;
|
|
1757
|
+
}
|
|
1758
|
+
__name(sameSeries, "sameSeries");
|
|
1759
|
+
function stateOf(block, documents, voids) {
|
|
1760
|
+
const documented = [...documents].filter((d) => sameSeries(d, block) && d.number >= block.from && d.number <= block.to).map((d) => d.number).sort((a, b) => a - b);
|
|
1761
|
+
const voided = voids.filter((v) => v.blockId === block.id).map(({ from, to }) => ({ from, to }));
|
|
1762
|
+
return { ...block, documented, voided };
|
|
1763
|
+
}
|
|
1764
|
+
__name(stateOf, "stateOf");
|
|
1765
|
+
function after(block, cursor) {
|
|
1766
|
+
return block.reservedAt > cursor.reservedAt || block.reservedAt === cursor.reservedAt && block.id > cursor.id;
|
|
1767
|
+
}
|
|
1768
|
+
__name(after, "after");
|
|
1769
|
+
function insertSigned2(state, document, event) {
|
|
1770
|
+
const all = [...state.documents.values()];
|
|
1771
|
+
if (all.some((other) => other.accessKey === document.accessKey || sameSeries(other, document) && other.number === document.number)) {
|
|
1772
|
+
throw new FiscalDocumentError("CONFLICT", `key ${document.accessKey ?? ""} or number ${document.number} is recorded already.`);
|
|
1773
|
+
}
|
|
1774
|
+
const live = all.some((o) => o.ownerId === document.ownerId && o.subjectId === document.subjectId && o.model === document.model && isLive(o));
|
|
1775
|
+
if (live) throw new FiscalDocumentError("SUBJECT_HAS_DOCUMENT", `subject ${document.subjectId} already has a live ${document.model}.`);
|
|
1776
|
+
state.documents.set(document.id, document);
|
|
1777
|
+
state.events.push(event);
|
|
1778
|
+
return document;
|
|
1779
|
+
}
|
|
1780
|
+
__name(insertSigned2, "insertSigned");
|
|
1781
|
+
function memoryBlockMethods(state) {
|
|
1782
|
+
const blocks = /* @__PURE__ */ new Map();
|
|
1783
|
+
const voids = [];
|
|
1784
|
+
const update = /* @__PURE__ */ __name((id, patch) => {
|
|
1785
|
+
const block = blocks.get(id);
|
|
1786
|
+
if (block !== void 0) blocks.set(id, { ...block, ...patch });
|
|
1787
|
+
}, "update");
|
|
1788
|
+
return {
|
|
1789
|
+
blocks,
|
|
1790
|
+
async reserveContingencyBlock({ request, size, id, holder, at }) {
|
|
1791
|
+
const key = state.counterKey(request);
|
|
1792
|
+
const first = state.counters.get(key);
|
|
1793
|
+
if (first === void 0 || state.seriesOwner.get(key) !== request.issuingPointId) {
|
|
1794
|
+
throw new FiscalDocumentError("NOT_FOUND", `no counter for series ${request.series} on issuing point ${request.issuingPointId}.`);
|
|
1795
|
+
}
|
|
1796
|
+
if (first + size - 1 > MAX_NUMBER) throw new FiscalDocumentError("SERIES_EXHAUSTED", `series ${request.series} has no ${size} numbers left.`);
|
|
1797
|
+
state.counters.set(key, first + size);
|
|
1798
|
+
const block = {
|
|
1799
|
+
id,
|
|
1800
|
+
ownerId: request.ownerId,
|
|
1801
|
+
issuingPointId: request.issuingPointId,
|
|
1802
|
+
issuerCnpj: request.issuerCnpj,
|
|
1803
|
+
environment: request.environment,
|
|
1804
|
+
model: "NFCE",
|
|
1805
|
+
series: request.series,
|
|
1806
|
+
from: first,
|
|
1807
|
+
to: first + size - 1,
|
|
1808
|
+
holder,
|
|
1809
|
+
fate: "OPEN",
|
|
1810
|
+
usedUpTo: null,
|
|
1811
|
+
reservedAt: at,
|
|
1812
|
+
closedAt: null,
|
|
1813
|
+
settledAt: null
|
|
1814
|
+
};
|
|
1815
|
+
blocks.set(id, block);
|
|
1816
|
+
return block;
|
|
1817
|
+
},
|
|
1818
|
+
async findContingencyBlock(input) {
|
|
1819
|
+
const found = [...blocks.values()].find(
|
|
1820
|
+
(b) => sameSeries(b, { ...input, model: "NFCE" }) && input.number >= b.from && input.number <= b.to
|
|
1821
|
+
);
|
|
1822
|
+
return found === void 0 || found.ownerId !== input.ownerId ? null : stateOf(found, state.documents.values(), voids);
|
|
1823
|
+
},
|
|
1824
|
+
async listContingencyBlocks(input) {
|
|
1825
|
+
return [...blocks.values()].filter((b) => input.ownerId === void 0 || b.ownerId === input.ownerId).filter((b) => input.holder === void 0 || b.holder === input.holder).filter((b) => input.fates === void 0 || input.fates.includes(b.fate)).filter((b) => input.reservedBefore === void 0 || b.reservedAt < input.reservedBefore).filter((b) => !input.unsettledOnly || b.settledAt === null).filter((b) => input.after === void 0 || after(b, input.after)).sort((a, b) => after(a, b) ? 1 : after(b, a) ? -1 : 0).slice(0, input.limit).map((b) => stateOf(b, state.documents.values(), voids));
|
|
1826
|
+
},
|
|
1827
|
+
async closeContingencyBlock({ id, fate, usedUpTo, at }) {
|
|
1828
|
+
if (blocks.get(id)?.fate !== "OPEN") return false;
|
|
1829
|
+
update(id, { fate, usedUpTo, closedAt: at });
|
|
1830
|
+
return true;
|
|
1831
|
+
},
|
|
1832
|
+
async settleContingencyBlock({ id, at }) {
|
|
1833
|
+
update(id, { settledAt: at });
|
|
1834
|
+
},
|
|
1835
|
+
async recordContingencyVoid({ blockId, range }) {
|
|
1836
|
+
if (voids.some((v) => v.blockId === blockId && v.from === range.from)) return false;
|
|
1837
|
+
voids.push({ blockId, ...range });
|
|
1838
|
+
return true;
|
|
1839
|
+
},
|
|
1840
|
+
async getDocumentByAccessKey(ownerId, accessKey) {
|
|
1841
|
+
return [...state.documents.values()].find((d) => d.ownerId === ownerId && d.accessKey === accessKey) ?? null;
|
|
1842
|
+
},
|
|
1843
|
+
recordSignedDocument: /* @__PURE__ */ __name(async (document, event) => insertSigned2(state, document, event), "recordSignedDocument")
|
|
789
1844
|
};
|
|
790
1845
|
}
|
|
791
|
-
__name(
|
|
1846
|
+
__name(memoryBlockMethods, "memoryBlockMethods");
|
|
792
1847
|
|
|
793
1848
|
// src/documents/memory.ts
|
|
794
|
-
var
|
|
1849
|
+
var MAX_NUMBER2 = 999999999;
|
|
795
1850
|
function counterKey(request) {
|
|
796
1851
|
return `${request.issuerCnpj}|${request.environment}|${request.model}|${request.series}`;
|
|
797
1852
|
}
|
|
@@ -836,6 +1891,7 @@ function createMemoryFiscalStore() {
|
|
|
836
1891
|
const state = { counters: /* @__PURE__ */ new Map(), seriesOwner: /* @__PURE__ */ new Map(), documents: /* @__PURE__ */ new Map(), events: [] };
|
|
837
1892
|
const ordered = /* @__PURE__ */ __name((key) => [...state.documents.values()].sort((a, b) => key(a).localeCompare(key(b))), "ordered");
|
|
838
1893
|
return {
|
|
1894
|
+
...memoryBlockMethods({ ...state, counterKey }),
|
|
839
1895
|
events: state.events,
|
|
840
1896
|
counters: state.counters,
|
|
841
1897
|
getProfile: /* @__PURE__ */ __name(async (ownerId) => profiles.get(ownerId) ?? null, "getProfile"),
|
|
@@ -857,7 +1913,7 @@ function createMemoryFiscalStore() {
|
|
|
857
1913
|
if (number === void 0 || state.seriesOwner.get(key) !== request.issuingPointId) {
|
|
858
1914
|
throw new FiscalDocumentError("NOT_FOUND", `no counter for series ${request.series} on issuing point ${request.issuingPointId}.`);
|
|
859
1915
|
}
|
|
860
|
-
if (number >
|
|
1916
|
+
if (number > MAX_NUMBER2) throw new FiscalDocumentError("SERIES_EXHAUSTED", `series ${request.series} has no number left.`);
|
|
861
1917
|
const document = build(number);
|
|
862
1918
|
if (state.documents.has(document.id)) throw new FiscalDocumentError("INVALID_INPUT", `document ${document.id} exists.`);
|
|
863
1919
|
const snapshot = new Map(state.documents);
|
|
@@ -895,273 +1951,9 @@ SET "next_number" = "next_number" + 1, "updated_at" = CURRENT_TIMESTAMP
|
|
|
895
1951
|
WHERE "issuer_cnpj" = $1 AND "environment" = $2 AND "model" = $3 AND "series" = $4 AND "issuing_point_id" = $5
|
|
896
1952
|
RETURNING "next_number" - 1 AS "number"`;
|
|
897
1953
|
|
|
898
|
-
// src/documents/sql-rows.ts
|
|
899
|
-
function iso(value) {
|
|
900
|
-
if (value === null || value === void 0) return null;
|
|
901
|
-
const date = value instanceof Date ? value : /* @__PURE__ */ new Date(`${String(value).replace(" ", "T")}${/Z|[+-]\d{2}:?\d{2}$/.test(String(value)) ? "" : "Z"}`);
|
|
902
|
-
return date.toISOString();
|
|
903
|
-
}
|
|
904
|
-
__name(iso, "iso");
|
|
905
|
-
function requiredIso(value) {
|
|
906
|
-
return iso(value) ?? "";
|
|
907
|
-
}
|
|
908
|
-
__name(requiredIso, "requiredIso");
|
|
909
|
-
function day(value) {
|
|
910
|
-
return value instanceof Date ? value.toISOString().slice(0, 10) : String(value).slice(0, 10);
|
|
911
|
-
}
|
|
912
|
-
__name(day, "day");
|
|
913
|
-
function json(value) {
|
|
914
|
-
return typeof value === "string" ? JSON.parse(value) : value;
|
|
915
|
-
}
|
|
916
|
-
__name(json, "json");
|
|
917
|
-
var text = /* @__PURE__ */ __name((value) => value === null || value === void 0 ? null : String(value), "text");
|
|
918
|
-
var DOCUMENT_COLUMNS = [
|
|
919
|
-
"id",
|
|
920
|
-
"owner_id",
|
|
921
|
-
"issuer_cnpj",
|
|
922
|
-
"subject_id",
|
|
923
|
-
"issuing_point_id",
|
|
924
|
-
"model",
|
|
925
|
-
"environment",
|
|
926
|
-
"series_kind",
|
|
927
|
-
"series",
|
|
928
|
-
"number",
|
|
929
|
-
"key_code",
|
|
930
|
-
"status",
|
|
931
|
-
"sale",
|
|
932
|
-
"totals",
|
|
933
|
-
"buyer_tax_id",
|
|
934
|
-
"access_key",
|
|
935
|
-
"protocol",
|
|
936
|
-
"status_code",
|
|
937
|
-
"status_reason",
|
|
938
|
-
"last_error_class",
|
|
939
|
-
"outcome_unknown",
|
|
940
|
-
"issued_at",
|
|
941
|
-
"authorized_at",
|
|
942
|
-
"contingency",
|
|
943
|
-
"cancelled_at",
|
|
944
|
-
"cancel_reason",
|
|
945
|
-
"cancel_protocol",
|
|
946
|
-
"replaced_by_id",
|
|
947
|
-
"number_void",
|
|
948
|
-
"xml_key",
|
|
949
|
-
"event_xml_key",
|
|
950
|
-
"attempts",
|
|
951
|
-
"failures",
|
|
952
|
-
"next_attempt_at",
|
|
953
|
-
"attention",
|
|
954
|
-
"deadline_warned_at",
|
|
955
|
-
"created_at",
|
|
956
|
-
"updated_at"
|
|
957
|
-
];
|
|
958
|
-
var JSON_COLUMNS = /* @__PURE__ */ new Set(["sale", "totals", "contingency"]);
|
|
959
|
-
var TIME_COLUMNS = /* @__PURE__ */ new Set(["next_attempt_at", "deadline_warned_at", "created_at", "updated_at"]);
|
|
960
|
-
function placeholder(column, index) {
|
|
961
|
-
if (JSON_COLUMNS.has(column)) return `$${index}::jsonb`;
|
|
962
|
-
if (TIME_COLUMNS.has(column)) return `$${index}::timestamp(3)`;
|
|
963
|
-
return `$${index}`;
|
|
964
|
-
}
|
|
965
|
-
__name(placeholder, "placeholder");
|
|
966
|
-
function documentValues(d) {
|
|
967
|
-
return [
|
|
968
|
-
d.id,
|
|
969
|
-
d.ownerId,
|
|
970
|
-
d.issuerCnpj,
|
|
971
|
-
d.subjectId,
|
|
972
|
-
d.issuingPointId,
|
|
973
|
-
d.model,
|
|
974
|
-
d.environment,
|
|
975
|
-
d.seriesKind,
|
|
976
|
-
d.series,
|
|
977
|
-
d.number,
|
|
978
|
-
d.keyCode,
|
|
979
|
-
d.status,
|
|
980
|
-
JSON.stringify(d.sale),
|
|
981
|
-
JSON.stringify(d.totals),
|
|
982
|
-
d.buyerTaxId,
|
|
983
|
-
d.accessKey,
|
|
984
|
-
d.protocol,
|
|
985
|
-
d.statusCode,
|
|
986
|
-
d.statusReason,
|
|
987
|
-
d.lastErrorClass,
|
|
988
|
-
d.outcomeUnknown,
|
|
989
|
-
d.issuedAt,
|
|
990
|
-
d.authorizedAt,
|
|
991
|
-
d.contingency === null ? null : JSON.stringify(d.contingency),
|
|
992
|
-
d.cancelledAt,
|
|
993
|
-
d.cancelReason,
|
|
994
|
-
d.cancelProtocol,
|
|
995
|
-
d.replacedById,
|
|
996
|
-
d.numberVoid,
|
|
997
|
-
d.xmlKey,
|
|
998
|
-
d.eventXmlKey,
|
|
999
|
-
d.attempts,
|
|
1000
|
-
d.failures,
|
|
1001
|
-
d.nextAttemptAt,
|
|
1002
|
-
d.attention,
|
|
1003
|
-
d.deadlineWarnedAt,
|
|
1004
|
-
d.createdAt,
|
|
1005
|
-
d.updatedAt
|
|
1006
|
-
];
|
|
1007
|
-
}
|
|
1008
|
-
__name(documentValues, "documentValues");
|
|
1009
|
-
function documentOf(row) {
|
|
1010
|
-
return {
|
|
1011
|
-
id: String(row["id"]),
|
|
1012
|
-
ownerId: String(row["owner_id"]),
|
|
1013
|
-
issuerCnpj: String(row["issuer_cnpj"]),
|
|
1014
|
-
subjectId: String(row["subject_id"]),
|
|
1015
|
-
issuingPointId: String(row["issuing_point_id"]),
|
|
1016
|
-
model: row["model"],
|
|
1017
|
-
environment: row["environment"],
|
|
1018
|
-
seriesKind: row["series_kind"],
|
|
1019
|
-
series: Number(row["series"]),
|
|
1020
|
-
number: Number(row["number"]),
|
|
1021
|
-
keyCode: String(row["key_code"]),
|
|
1022
|
-
status: row["status"],
|
|
1023
|
-
sale: json(row["sale"]),
|
|
1024
|
-
totals: json(row["totals"]),
|
|
1025
|
-
buyerTaxId: text(row["buyer_tax_id"]),
|
|
1026
|
-
accessKey: text(row["access_key"]),
|
|
1027
|
-
protocol: text(row["protocol"]),
|
|
1028
|
-
statusCode: text(row["status_code"]),
|
|
1029
|
-
statusReason: text(row["status_reason"]),
|
|
1030
|
-
lastErrorClass: text(row["last_error_class"]),
|
|
1031
|
-
outcomeUnknown: row["outcome_unknown"] === true,
|
|
1032
|
-
issuedAt: String(row["issued_at"]),
|
|
1033
|
-
authorizedAt: text(row["authorized_at"]),
|
|
1034
|
-
contingency: row["contingency"] === null ? null : json(row["contingency"]),
|
|
1035
|
-
cancelledAt: text(row["cancelled_at"]),
|
|
1036
|
-
cancelReason: text(row["cancel_reason"]),
|
|
1037
|
-
cancelProtocol: text(row["cancel_protocol"]),
|
|
1038
|
-
replacedById: text(row["replaced_by_id"]),
|
|
1039
|
-
numberVoid: text(row["number_void"]),
|
|
1040
|
-
xmlKey: text(row["xml_key"]),
|
|
1041
|
-
eventXmlKey: text(row["event_xml_key"]),
|
|
1042
|
-
attempts: Number(row["attempts"]),
|
|
1043
|
-
failures: Number(row["failures"]),
|
|
1044
|
-
nextAttemptAt: iso(row["next_attempt_at"]),
|
|
1045
|
-
attention: row["attention"] === true,
|
|
1046
|
-
deadlineWarnedAt: iso(row["deadline_warned_at"]),
|
|
1047
|
-
createdAt: requiredIso(row["created_at"]),
|
|
1048
|
-
updatedAt: requiredIso(row["updated_at"])
|
|
1049
|
-
};
|
|
1050
|
-
}
|
|
1051
|
-
__name(documentOf, "documentOf");
|
|
1052
|
-
function eventOf(row) {
|
|
1053
|
-
return {
|
|
1054
|
-
documentId: String(row["document_id"]),
|
|
1055
|
-
kind: row["kind"],
|
|
1056
|
-
fromStatus: row["from_status"],
|
|
1057
|
-
toStatus: row["to_status"],
|
|
1058
|
-
at: requiredIso(row["at"]),
|
|
1059
|
-
errorClass: text(row["error_class"]),
|
|
1060
|
-
code: text(row["code"]),
|
|
1061
|
-
answer: row["answer"] === null ? null : json(row["answer"])
|
|
1062
|
-
};
|
|
1063
|
-
}
|
|
1064
|
-
__name(eventOf, "eventOf");
|
|
1065
|
-
var PROFILE_COLUMNS = [
|
|
1066
|
-
"owner_id",
|
|
1067
|
-
"cnpj",
|
|
1068
|
-
"state_registration",
|
|
1069
|
-
"municipal_registration",
|
|
1070
|
-
"cnae",
|
|
1071
|
-
"legal_name",
|
|
1072
|
-
"trade_name",
|
|
1073
|
-
"tax_regime",
|
|
1074
|
-
"regime",
|
|
1075
|
-
"regime_effective_from",
|
|
1076
|
-
"restaurant_regime",
|
|
1077
|
-
"address",
|
|
1078
|
-
"environment",
|
|
1079
|
-
"document_policy",
|
|
1080
|
-
"signing_identity",
|
|
1081
|
-
"certificate_ciphertext",
|
|
1082
|
-
"certificate_password_ciphertext",
|
|
1083
|
-
"certificate_expires_at",
|
|
1084
|
-
"csc_id",
|
|
1085
|
-
"csc_ciphertext",
|
|
1086
|
-
"consent_recorded_at",
|
|
1087
|
-
"updated_at"
|
|
1088
|
-
];
|
|
1089
|
-
function profilePlaceholder(column, index) {
|
|
1090
|
-
if (column === "address") return `$${index}::jsonb`;
|
|
1091
|
-
if (column === "regime_effective_from") return `$${index}::date`;
|
|
1092
|
-
if (column.endsWith("_at")) return `$${index}::timestamp(3)`;
|
|
1093
|
-
return `$${index}`;
|
|
1094
|
-
}
|
|
1095
|
-
__name(profilePlaceholder, "profilePlaceholder");
|
|
1096
|
-
function profileValues(p) {
|
|
1097
|
-
return [
|
|
1098
|
-
p.ownerId,
|
|
1099
|
-
p.cnpj,
|
|
1100
|
-
p.stateRegistration,
|
|
1101
|
-
p.municipalRegistration,
|
|
1102
|
-
p.cnae,
|
|
1103
|
-
p.legalName,
|
|
1104
|
-
p.tradeName,
|
|
1105
|
-
p.taxRegime,
|
|
1106
|
-
p.regime,
|
|
1107
|
-
p.regimeEffectiveFrom,
|
|
1108
|
-
p.restaurantRegime,
|
|
1109
|
-
JSON.stringify(p.address),
|
|
1110
|
-
p.environment,
|
|
1111
|
-
p.documentPolicy,
|
|
1112
|
-
p.signingIdentity,
|
|
1113
|
-
p.certificateCiphertext,
|
|
1114
|
-
p.certificatePasswordCiphertext,
|
|
1115
|
-
p.certificateExpiresAt,
|
|
1116
|
-
p.cscId,
|
|
1117
|
-
p.cscCiphertext,
|
|
1118
|
-
p.consentRecordedAt,
|
|
1119
|
-
p.updatedAt
|
|
1120
|
-
];
|
|
1121
|
-
}
|
|
1122
|
-
__name(profileValues, "profileValues");
|
|
1123
|
-
function profileOf(row) {
|
|
1124
|
-
return {
|
|
1125
|
-
ownerId: String(row["owner_id"]),
|
|
1126
|
-
cnpj: String(row["cnpj"]),
|
|
1127
|
-
stateRegistration: String(row["state_registration"]),
|
|
1128
|
-
municipalRegistration: text(row["municipal_registration"]),
|
|
1129
|
-
cnae: text(row["cnae"]),
|
|
1130
|
-
legalName: String(row["legal_name"]),
|
|
1131
|
-
tradeName: text(row["trade_name"]),
|
|
1132
|
-
taxRegime: row["tax_regime"],
|
|
1133
|
-
regime: row["regime"],
|
|
1134
|
-
regimeEffectiveFrom: day(row["regime_effective_from"]),
|
|
1135
|
-
restaurantRegime: row["restaurant_regime"] === true,
|
|
1136
|
-
address: json(row["address"]),
|
|
1137
|
-
environment: row["environment"],
|
|
1138
|
-
documentPolicy: row["document_policy"],
|
|
1139
|
-
signingIdentity: row["signing_identity"],
|
|
1140
|
-
certificateCiphertext: text(row["certificate_ciphertext"]),
|
|
1141
|
-
certificatePasswordCiphertext: text(row["certificate_password_ciphertext"]),
|
|
1142
|
-
certificateExpiresAt: iso(row["certificate_expires_at"]),
|
|
1143
|
-
cscId: text(row["csc_id"]),
|
|
1144
|
-
cscCiphertext: text(row["csc_ciphertext"]),
|
|
1145
|
-
consentRecordedAt: iso(row["consent_recorded_at"]),
|
|
1146
|
-
updatedAt: requiredIso(row["updated_at"])
|
|
1147
|
-
};
|
|
1148
|
-
}
|
|
1149
|
-
__name(profileOf, "profileOf");
|
|
1150
|
-
function pointOf(row) {
|
|
1151
|
-
return {
|
|
1152
|
-
id: String(row["id"]),
|
|
1153
|
-
ownerId: String(row["owner_id"]),
|
|
1154
|
-
model: row["model"],
|
|
1155
|
-
onlineSeries: Number(row["online_series"]),
|
|
1156
|
-
contingencySeries: row["contingency_series"] === null ? null : Number(row["contingency_series"]),
|
|
1157
|
-
createdAt: requiredIso(row["created_at"])
|
|
1158
|
-
};
|
|
1159
|
-
}
|
|
1160
|
-
__name(pointOf, "pointOf");
|
|
1161
|
-
|
|
1162
1954
|
// src/documents/sql-store.ts
|
|
1163
|
-
var
|
|
1164
|
-
var
|
|
1955
|
+
var rows2 = /* @__PURE__ */ __name((client, query, ...values) => client.$queryRawUnsafe(query, ...values), "rows");
|
|
1956
|
+
var INSERT_DOCUMENT2 = `INSERT INTO "fiscal_documents" (${DOCUMENT_COLUMNS.map((c) => `"${c}"`).join(", ")})
|
|
1165
1957
|
VALUES (${DOCUMENT_COLUMNS.map((c, i) => placeholder(c, i + 1)).join(", ")})`;
|
|
1166
1958
|
var MUTABLE = DOCUMENT_COLUMNS.filter((c) => c !== "id" && c !== "created_at");
|
|
1167
1959
|
var UPDATE_DOCUMENT = [
|
|
@@ -1175,22 +1967,22 @@ function updateValues(document, previous) {
|
|
|
1175
1967
|
return [document.id, ...mutable, previous.updatedAt, previous.status];
|
|
1176
1968
|
}
|
|
1177
1969
|
__name(updateValues, "updateValues");
|
|
1178
|
-
var
|
|
1970
|
+
var INSERT_EVENT2 = `INSERT INTO "fiscal_document_events" ("id", "document_id", "kind", "from_status", "to_status", "at", "error_class", "code", "answer")
|
|
1179
1971
|
VALUES ($1, $2, $3, $4, $5, $6::timestamp(3), $7, $8, $9::jsonb)`;
|
|
1180
1972
|
var UPSERT_PROFILE = `INSERT INTO "fiscal_emitter_profiles" (${PROFILE_COLUMNS.map((c) => `"${c}"`).join(", ")})
|
|
1181
1973
|
VALUES (${PROFILE_COLUMNS.map((c, i) => profilePlaceholder(c, i + 1)).join(", ")})
|
|
1182
1974
|
ON CONFLICT ("owner_id") DO UPDATE SET ${PROFILE_COLUMNS.filter((c) => c !== "owner_id").map((c) => `"${c}" = EXCLUDED."${c}"`).join(", ")}`;
|
|
1183
1975
|
var OWED = `("status" IN ('PENDING', 'SUBMITTED') OR "number_void" IN ('LOOKUP_FIRST', 'INUTILIZE', 'CANCEL'))`;
|
|
1184
|
-
function
|
|
1185
|
-
const
|
|
1186
|
-
return
|
|
1976
|
+
function violates2(error, constraint) {
|
|
1977
|
+
const text3 = error instanceof Error ? `${error.message} ${JSON.stringify(error.meta ?? "")}` : String(error);
|
|
1978
|
+
return text3.includes(constraint);
|
|
1187
1979
|
}
|
|
1188
|
-
__name(
|
|
1980
|
+
__name(violates2, "violates");
|
|
1189
1981
|
async function saveRow(tx, previous, { document, event }) {
|
|
1190
|
-
const updated = await
|
|
1982
|
+
const updated = await rows2(tx, UPDATE_DOCUMENT, ...updateValues(document, previous));
|
|
1191
1983
|
if (updated.length === 0) return false;
|
|
1192
1984
|
await tx.$executeRawUnsafe(
|
|
1193
|
-
|
|
1985
|
+
INSERT_EVENT2,
|
|
1194
1986
|
globalThis.crypto.randomUUID(),
|
|
1195
1987
|
event.documentId,
|
|
1196
1988
|
event.kind,
|
|
@@ -1206,13 +1998,13 @@ async function saveRow(tx, previous, { document, event }) {
|
|
|
1206
1998
|
__name(saveRow, "saveRow");
|
|
1207
1999
|
async function draw(tx, request) {
|
|
1208
2000
|
try {
|
|
1209
|
-
const [row] = await
|
|
2001
|
+
const [row] = await rows2(tx, FISCAL_NEXT_NUMBER_SQL, request.issuerCnpj, request.environment, request.model, request.series, request.issuingPointId);
|
|
1210
2002
|
if (row === void 0) {
|
|
1211
2003
|
throw new FiscalDocumentError("NOT_FOUND", `no counter for series ${request.series} on issuing point ${request.issuingPointId}.`);
|
|
1212
2004
|
}
|
|
1213
2005
|
return Number(row["number"]);
|
|
1214
2006
|
} catch (error) {
|
|
1215
|
-
if (
|
|
2007
|
+
if (violates2(error, "fiscal_number_counters_next_number_check")) {
|
|
1216
2008
|
throw new FiscalDocumentError("SERIES_EXHAUSTED", `series ${request.series} has no number left.`);
|
|
1217
2009
|
}
|
|
1218
2010
|
throw error;
|
|
@@ -1221,9 +2013,9 @@ async function draw(tx, request) {
|
|
|
1221
2013
|
__name(draw, "draw");
|
|
1222
2014
|
async function insertDocument(tx, document) {
|
|
1223
2015
|
try {
|
|
1224
|
-
await tx.$executeRawUnsafe(
|
|
2016
|
+
await tx.$executeRawUnsafe(INSERT_DOCUMENT2, ...documentValues(document));
|
|
1225
2017
|
} catch (error) {
|
|
1226
|
-
if (
|
|
2018
|
+
if (violates2(error, "fiscal_documents_live_subject_key")) {
|
|
1227
2019
|
throw new FiscalDocumentError("SUBJECT_HAS_DOCUMENT", `subject ${document.subjectId} already has a live ${document.model}.`);
|
|
1228
2020
|
}
|
|
1229
2021
|
throw error;
|
|
@@ -1249,22 +2041,22 @@ __name(openCounters, "openCounters");
|
|
|
1249
2041
|
function profileMethods(db) {
|
|
1250
2042
|
return {
|
|
1251
2043
|
async getProfile(ownerId) {
|
|
1252
|
-
const [row] = await
|
|
2044
|
+
const [row] = await rows2(db, `SELECT * FROM "fiscal_emitter_profiles" WHERE "owner_id" = $1`, ownerId);
|
|
1253
2045
|
return row === void 0 ? null : profileOf(row);
|
|
1254
2046
|
},
|
|
1255
2047
|
async saveProfile(profile) {
|
|
1256
2048
|
await db.$executeRawUnsafe(UPSERT_PROFILE, ...profileValues(profile));
|
|
1257
2049
|
},
|
|
1258
2050
|
async getIssuingPoint(ownerId, id) {
|
|
1259
|
-
const [row] = await
|
|
2051
|
+
const [row] = await rows2(db, `SELECT * FROM "fiscal_issuing_points" WHERE "id" = $1 AND "owner_id" = $2`, id, ownerId);
|
|
1260
2052
|
return row === void 0 ? null : pointOf(row);
|
|
1261
2053
|
},
|
|
1262
2054
|
async listIssuingPoints(ownerId) {
|
|
1263
|
-
return (await
|
|
2055
|
+
return (await rows2(db, `SELECT * FROM "fiscal_issuing_points" WHERE "owner_id" = $1 ORDER BY "created_at", "id"`, ownerId)).map(pointOf);
|
|
1264
2056
|
},
|
|
1265
2057
|
createIssuingPoint: /* @__PURE__ */ __name((point, issuerCnpj, firstNumber) => createIssuingPoint2(db, point, issuerCnpj, firstNumber), "createIssuingPoint"),
|
|
1266
2058
|
async listExpiringCertificates(before) {
|
|
1267
|
-
return (await
|
|
2059
|
+
return (await rows2(db, `SELECT * FROM "fiscal_emitter_profiles" WHERE "certificate_expires_at" < $1::timestamp(3) ORDER BY "owner_id"`, before)).map(profileOf);
|
|
1268
2060
|
}
|
|
1269
2061
|
};
|
|
1270
2062
|
}
|
|
@@ -1288,16 +2080,16 @@ async function createIssuingPoint2(db, ...[point, issuerCnpj, firstNumber]) {
|
|
|
1288
2080
|
}
|
|
1289
2081
|
});
|
|
1290
2082
|
} catch (error) {
|
|
1291
|
-
if (
|
|
2083
|
+
if (violates2(error, "fiscal_number_counters_pkey")) {
|
|
1292
2084
|
throw new FiscalDocumentError("INVALID_INPUT", `a series of issuing point ${point.id} already belongs to another issuing point.`);
|
|
1293
2085
|
}
|
|
1294
|
-
if (
|
|
2086
|
+
if (violates2(error, "fiscal_issuing_points_pkey")) throw new FiscalDocumentError("INVALID_INPUT", `issuing point ${point.id} exists.`);
|
|
1295
2087
|
throw error;
|
|
1296
2088
|
}
|
|
1297
2089
|
}
|
|
1298
2090
|
__name(createIssuingPoint2, "createIssuingPoint");
|
|
1299
2091
|
function documentMethods(db) {
|
|
1300
|
-
const documents = /* @__PURE__ */ __name(async (query, ...values) => (await
|
|
2092
|
+
const documents = /* @__PURE__ */ __name(async (query, ...values) => (await rows2(db, query, ...values)).map(documentOf), "documents");
|
|
1301
2093
|
return {
|
|
1302
2094
|
createDocument: /* @__PURE__ */ __name((request, build, replace) => db.$transaction(async (tx) => {
|
|
1303
2095
|
if (replace !== void 0 && !await saveRow(tx, replace.previous, replace.transition)) {
|
|
@@ -1318,7 +2110,7 @@ function documentMethods(db) {
|
|
|
1318
2110
|
model
|
|
1319
2111
|
), "listBySubject"),
|
|
1320
2112
|
async listEvents(documentId) {
|
|
1321
|
-
return (await
|
|
2113
|
+
return (await rows2(db, `SELECT * FROM "fiscal_document_events" WHERE "document_id" = $1 ORDER BY "seq"`, documentId)).map(eventOf);
|
|
1322
2114
|
},
|
|
1323
2115
|
saveTransition: /* @__PURE__ */ __name((previous, transition2) => db.$transaction((tx) => saveRow(tx, previous, transition2)), "saveTransition"),
|
|
1324
2116
|
listDue: /* @__PURE__ */ __name(({ now, limit }) => documents(
|
|
@@ -1348,7 +2140,7 @@ function createPrismaFiscalStore(config) {
|
|
|
1348
2140
|
if (typeof db?.$transaction !== "function" || typeof db.$queryRawUnsafe !== "function") {
|
|
1349
2141
|
throw new TypeError("createPrismaFiscalStore needs prisma: the host's Prisma client.");
|
|
1350
2142
|
}
|
|
1351
|
-
return { ...profileMethods(db), ...documentMethods(db) };
|
|
2143
|
+
return { ...profileMethods(db), ...documentMethods(db), ...blockMethods(db) };
|
|
1352
2144
|
}
|
|
1353
2145
|
__name(createPrismaFiscalStore, "createPrismaFiscalStore");
|
|
1354
2146
|
|
|
@@ -1390,7 +2182,9 @@ function documentLines(breakdown, details) {
|
|
|
1390
2182
|
}
|
|
1391
2183
|
__name(documentLines, "documentLines");
|
|
1392
2184
|
export {
|
|
2185
|
+
CONTINGENCY_BLOCK_FATES,
|
|
1393
2186
|
CONTINGENCY_WARNING_AFTER_MS,
|
|
2187
|
+
DEFAULT_CONTINGENCY_BLOCK_SIZE,
|
|
1394
2188
|
DOCUMENT_POLICIES,
|
|
1395
2189
|
DOCUMENT_TRANSITIONS,
|
|
1396
2190
|
FINAL_STATUSES,
|
|
@@ -1401,12 +2195,15 @@ export {
|
|
|
1401
2195
|
FISCAL_DOCUMENT_REJECTED,
|
|
1402
2196
|
FISCAL_DOCUMENT_STATUSES,
|
|
1403
2197
|
FISCAL_NEXT_NUMBER_SQL,
|
|
2198
|
+
FISCAL_RESERVE_BLOCK_SQL,
|
|
1404
2199
|
FiscalDocumentError,
|
|
1405
2200
|
LATE_CANCEL_CODES,
|
|
2201
|
+
MAX_CONTINGENCY_BLOCK_SIZE,
|
|
1406
2202
|
MAX_FAILURES,
|
|
1407
2203
|
MAX_PAYMENT_LINKS,
|
|
1408
2204
|
OWED_VOIDS,
|
|
1409
2205
|
SIGNING_IDENTITY_KINDS,
|
|
2206
|
+
accountFor as accountForContingencyBlock,
|
|
1410
2207
|
canTransition,
|
|
1411
2208
|
computeAccessKey,
|
|
1412
2209
|
createFiscalDocuments,
|
|
@@ -1424,6 +2221,7 @@ export {
|
|
|
1424
2221
|
parseCertificateUpload,
|
|
1425
2222
|
parseIssuingPointInput,
|
|
1426
2223
|
parseProfileInput,
|
|
2224
|
+
parseSignedContingencyNote,
|
|
1427
2225
|
scrubSecrets,
|
|
1428
2226
|
transition,
|
|
1429
2227
|
viewOf,
|