@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
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,23 +34,972 @@ 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,
|
|
39
41
|
OWED_VOIDS,
|
|
40
42
|
isLive
|
|
41
|
-
} from "../chunk-
|
|
43
|
+
} from "../chunk-GH452ITO.js";
|
|
42
44
|
import {
|
|
43
45
|
FISCAL_ISSUE
|
|
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.");
|
|
@@ -259,6 +1210,92 @@ async function settleNumber(ctx, document, profile, signing) {
|
|
|
259
1210
|
}
|
|
260
1211
|
__name(settleNumber, "settleNumber");
|
|
261
1212
|
|
|
1213
|
+
// src/documents/payment-link.ts
|
|
1214
|
+
var MAX_PAYMENT_LINKS = 20;
|
|
1215
|
+
function linkedByEvents(events) {
|
|
1216
|
+
return events.filter((event) => event.kind === "LINK_PAYMENT").map((event, index) => {
|
|
1217
|
+
const answer = event.answer;
|
|
1218
|
+
return {
|
|
1219
|
+
transactionId: answer?.payment?.transactionId,
|
|
1220
|
+
sequence: typeof answer?.sequence === "number" ? answer.sequence : index + 1
|
|
1221
|
+
};
|
|
1222
|
+
}).filter((link) => typeof link.transactionId === "string");
|
|
1223
|
+
}
|
|
1224
|
+
__name(linkedByEvents, "linkedByEvents");
|
|
1225
|
+
function linkedInDocument(document) {
|
|
1226
|
+
return document.sale.payments.map((payment) => payment.linkedTransaction?.transactionId).filter((id) => typeof id === "string");
|
|
1227
|
+
}
|
|
1228
|
+
__name(linkedInDocument, "linkedInDocument");
|
|
1229
|
+
function linkable(deps, document) {
|
|
1230
|
+
const { accessKey, protocol } = document;
|
|
1231
|
+
if (document.status !== "AUTHORIZED" || accessKey === null || protocol === null) {
|
|
1232
|
+
throw new FiscalDocumentError("TRANSITION_REFUSED", `document ${document.id} is ${document.status}; only an authorised document is linked.`);
|
|
1233
|
+
}
|
|
1234
|
+
const send2 = deps.config.issuer.linkPayment;
|
|
1235
|
+
if (typeof send2 !== "function") throw new FiscalDocumentError("NOT_SUPPORTED", "this issuer does not register the event 110300.");
|
|
1236
|
+
return { accessKey, protocol, send: send2.bind(deps.config.issuer) };
|
|
1237
|
+
}
|
|
1238
|
+
__name(linkable, "linkable");
|
|
1239
|
+
function heldTransaction(answer, sent, requested) {
|
|
1240
|
+
if (answer.statusCode !== "573" || answer.transaction.transactionId === sent.transactionId) return sent;
|
|
1241
|
+
const held = answer.transaction;
|
|
1242
|
+
return requested.find((payment) => payment.transactionId === held.transactionId) ?? {
|
|
1243
|
+
transactionId: held.transactionId,
|
|
1244
|
+
meansCode: held.meansCode,
|
|
1245
|
+
pspCnpjBase: held.pspCnpjBase,
|
|
1246
|
+
receiverCnpj: held.receiverCnpj
|
|
1247
|
+
};
|
|
1248
|
+
}
|
|
1249
|
+
__name(heldTransaction, "heldTransaction");
|
|
1250
|
+
function refuseOverLimit(document) {
|
|
1251
|
+
throw new FiscalDocumentError("INVALID_INPUT", `document ${document.id} cannot take more than ${MAX_PAYMENT_LINKS} payment links.`);
|
|
1252
|
+
}
|
|
1253
|
+
__name(refuseOverLimit, "refuseOverLimit");
|
|
1254
|
+
async function sendOne(deps, run2, accessKey, payment) {
|
|
1255
|
+
if (run2.sequence > MAX_PAYMENT_LINKS) refuseOverLimit(run2.document);
|
|
1256
|
+
const sequence = run2.sequence;
|
|
1257
|
+
const outcome = await run2.send(sequence, payment);
|
|
1258
|
+
if (!outcome.ok) return outcome.error;
|
|
1259
|
+
const held = heldTransaction(outcome.answer, payment, run2.requested);
|
|
1260
|
+
const { eventXml } = outcome.answer;
|
|
1261
|
+
const eventXmlKey = eventXml === null ? null : xmlKeys.linkPayment(accessKey, sequence);
|
|
1262
|
+
if (eventXmlKey !== null && eventXml !== null) await deps.config.storage.put(eventXmlKey, eventXml, "application/xml");
|
|
1263
|
+
run2.document = await deps.ctx.advance(run2.document, { kind: "LINK_PAYMENT", answer: outcome.answer, payment: held, sequence, eventXmlKey });
|
|
1264
|
+
run2.known.add(held.transactionId);
|
|
1265
|
+
if (run2.requested.some((one) => one.transactionId === held.transactionId)) run2.linked.push(held.transactionId);
|
|
1266
|
+
run2.sequence = sequence + 1;
|
|
1267
|
+
return held.transactionId === payment.transactionId ? null : sendOne(deps, run2, accessKey, payment);
|
|
1268
|
+
}
|
|
1269
|
+
__name(sendOne, "sendOne");
|
|
1270
|
+
async function linkPayment(deps, input) {
|
|
1271
|
+
const document = await deps.config.store.getDocument(input.ownerId, input.documentId);
|
|
1272
|
+
if (document === null) throw new FiscalDocumentError("NOT_FOUND", `owner ${input.ownerId} has no document ${input.documentId}.`);
|
|
1273
|
+
const { accessKey, protocol, send: send2 } = linkable(deps, document);
|
|
1274
|
+
const byEvents = linkedByEvents(await deps.config.store.listEvents(document.id));
|
|
1275
|
+
const known = /* @__PURE__ */ new Set([...linkedInDocument(document), ...byEvents.map((link) => link.transactionId)]);
|
|
1276
|
+
const pending = input.payments.filter((payment) => !known.has(payment.transactionId));
|
|
1277
|
+
const alreadyLinked = input.payments.filter((payment) => known.has(payment.transactionId)).map((payment) => payment.transactionId);
|
|
1278
|
+
const sequence = Math.max(0, ...byEvents.map((link) => link.sequence)) + 1;
|
|
1279
|
+
if (sequence - 1 + pending.length > MAX_PAYMENT_LINKS) refuseOverLimit(document);
|
|
1280
|
+
if (pending.length === 0) return { linked: [], alreadyLinked, failure: null, document };
|
|
1281
|
+
const signing = await deps.ctx.material(await deps.ctx.requireProfile(input.ownerId));
|
|
1282
|
+
const run2 = {
|
|
1283
|
+
document,
|
|
1284
|
+
sequence,
|
|
1285
|
+
known,
|
|
1286
|
+
requested: pending,
|
|
1287
|
+
linked: [],
|
|
1288
|
+
send: /* @__PURE__ */ __name((at, payment) => send2({ model: document.model, environment: document.environment, signing, accessKey, protocol, sequence: at, payments: [payment] }), "send")
|
|
1289
|
+
};
|
|
1290
|
+
for (const payment of pending) {
|
|
1291
|
+
if (run2.known.has(payment.transactionId)) continue;
|
|
1292
|
+
const failure = await sendOne(deps, run2, accessKey, payment);
|
|
1293
|
+
if (failure !== null) return { linked: run2.linked, alreadyLinked, failure, document: run2.document };
|
|
1294
|
+
}
|
|
1295
|
+
return { linked: run2.linked, alreadyLinked, failure: null, document: run2.document };
|
|
1296
|
+
}
|
|
1297
|
+
__name(linkPayment, "linkPayment");
|
|
1298
|
+
|
|
262
1299
|
// src/documents/steps.ts
|
|
263
1300
|
var FINAL_FAILURES = /* @__PURE__ */ new Set(["REJECTED", "INVALID", "INTERNAL"]);
|
|
264
1301
|
async function reject(ctx, document, error) {
|
|
@@ -605,8 +1642,8 @@ async function lookup(deps, input) {
|
|
|
605
1642
|
if (!lookupMoves(document)) return { document, answer: outcome.answer, failure: null };
|
|
606
1643
|
const xmlKey = document.status === "SUBMITTED" ? await storeNfeProc(deps.ctx, document, outcome.answer) : void 0;
|
|
607
1644
|
const looked = await deps.ctx.advance(document, { kind: "LOOKUP", answer: outcome.answer, ...xmlKey === void 0 ? {} : { xmlKey } });
|
|
608
|
-
const
|
|
609
|
-
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 };
|
|
610
1647
|
}
|
|
611
1648
|
__name(lookup, "lookup");
|
|
612
1649
|
async function step({ ctx }, document) {
|
|
@@ -631,8 +1668,8 @@ async function run(deps, documents) {
|
|
|
631
1668
|
const report = { advanced: [], failures: [] };
|
|
632
1669
|
for (const document of documents) {
|
|
633
1670
|
try {
|
|
634
|
-
const
|
|
635
|
-
report.advanced.push({ documentId:
|
|
1671
|
+
const after2 = await step(deps, document);
|
|
1672
|
+
report.advanced.push({ documentId: after2.id, status: after2.status });
|
|
636
1673
|
} catch (error) {
|
|
637
1674
|
report.failures.push({ documentId: document.id, message: error instanceof Error ? error.message : "unknown failure" });
|
|
638
1675
|
await deferThrown(deps, document, error);
|
|
@@ -678,6 +1715,8 @@ function createFiscalDocuments(config) {
|
|
|
678
1715
|
* (501) — issue the buyer's return NF-e of entry quoting it. Idempotent.
|
|
679
1716
|
*/
|
|
680
1717
|
cancelOrReturn: cancelOrReturn.bind(null, deps),
|
|
1718
|
+
/** Link payment transactions to an authorised document (event 110300), once each. Idempotent. */
|
|
1719
|
+
linkPayment: linkPayment.bind(null, deps),
|
|
681
1720
|
/** Ask SEFAZ what it knows of the key; a state the answer moves is recorded. */
|
|
682
1721
|
lookup: lookup.bind(null, deps),
|
|
683
1722
|
/** A person takes a document back from `attention`; the sweep tries it again. */
|
|
@@ -690,20 +1729,124 @@ function createFiscalDocuments(config) {
|
|
|
690
1729
|
await requireDocument(deps, ownerId, documentId);
|
|
691
1730
|
return store.listEvents(documentId);
|
|
692
1731
|
},
|
|
693
|
-
/** One pass of the retry sweep: PENDING/SUBMITTED documents and owed numbers whose next attempt has come. */
|
|
694
|
-
sweep: /* @__PURE__ */ __name(async (limit) => run(deps, await store.listDue({ now: deps.ctx.nowIso(), limit })), "sweep"),
|
|
695
|
-
/**
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
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")
|
|
701
1844
|
};
|
|
702
1845
|
}
|
|
703
|
-
__name(
|
|
1846
|
+
__name(memoryBlockMethods, "memoryBlockMethods");
|
|
704
1847
|
|
|
705
1848
|
// src/documents/memory.ts
|
|
706
|
-
var
|
|
1849
|
+
var MAX_NUMBER2 = 999999999;
|
|
707
1850
|
function counterKey(request) {
|
|
708
1851
|
return `${request.issuerCnpj}|${request.environment}|${request.model}|${request.series}`;
|
|
709
1852
|
}
|
|
@@ -748,6 +1891,7 @@ function createMemoryFiscalStore() {
|
|
|
748
1891
|
const state = { counters: /* @__PURE__ */ new Map(), seriesOwner: /* @__PURE__ */ new Map(), documents: /* @__PURE__ */ new Map(), events: [] };
|
|
749
1892
|
const ordered = /* @__PURE__ */ __name((key) => [...state.documents.values()].sort((a, b) => key(a).localeCompare(key(b))), "ordered");
|
|
750
1893
|
return {
|
|
1894
|
+
...memoryBlockMethods({ ...state, counterKey }),
|
|
751
1895
|
events: state.events,
|
|
752
1896
|
counters: state.counters,
|
|
753
1897
|
getProfile: /* @__PURE__ */ __name(async (ownerId) => profiles.get(ownerId) ?? null, "getProfile"),
|
|
@@ -769,7 +1913,7 @@ function createMemoryFiscalStore() {
|
|
|
769
1913
|
if (number === void 0 || state.seriesOwner.get(key) !== request.issuingPointId) {
|
|
770
1914
|
throw new FiscalDocumentError("NOT_FOUND", `no counter for series ${request.series} on issuing point ${request.issuingPointId}.`);
|
|
771
1915
|
}
|
|
772
|
-
if (number >
|
|
1916
|
+
if (number > MAX_NUMBER2) throw new FiscalDocumentError("SERIES_EXHAUSTED", `series ${request.series} has no number left.`);
|
|
773
1917
|
const document = build(number);
|
|
774
1918
|
if (state.documents.has(document.id)) throw new FiscalDocumentError("INVALID_INPUT", `document ${document.id} exists.`);
|
|
775
1919
|
const snapshot = new Map(state.documents);
|
|
@@ -807,273 +1951,9 @@ SET "next_number" = "next_number" + 1, "updated_at" = CURRENT_TIMESTAMP
|
|
|
807
1951
|
WHERE "issuer_cnpj" = $1 AND "environment" = $2 AND "model" = $3 AND "series" = $4 AND "issuing_point_id" = $5
|
|
808
1952
|
RETURNING "next_number" - 1 AS "number"`;
|
|
809
1953
|
|
|
810
|
-
// src/documents/sql-rows.ts
|
|
811
|
-
function iso(value) {
|
|
812
|
-
if (value === null || value === void 0) return null;
|
|
813
|
-
const date = value instanceof Date ? value : /* @__PURE__ */ new Date(`${String(value).replace(" ", "T")}${/Z|[+-]\d{2}:?\d{2}$/.test(String(value)) ? "" : "Z"}`);
|
|
814
|
-
return date.toISOString();
|
|
815
|
-
}
|
|
816
|
-
__name(iso, "iso");
|
|
817
|
-
function requiredIso(value) {
|
|
818
|
-
return iso(value) ?? "";
|
|
819
|
-
}
|
|
820
|
-
__name(requiredIso, "requiredIso");
|
|
821
|
-
function day(value) {
|
|
822
|
-
return value instanceof Date ? value.toISOString().slice(0, 10) : String(value).slice(0, 10);
|
|
823
|
-
}
|
|
824
|
-
__name(day, "day");
|
|
825
|
-
function json(value) {
|
|
826
|
-
return typeof value === "string" ? JSON.parse(value) : value;
|
|
827
|
-
}
|
|
828
|
-
__name(json, "json");
|
|
829
|
-
var text = /* @__PURE__ */ __name((value) => value === null || value === void 0 ? null : String(value), "text");
|
|
830
|
-
var DOCUMENT_COLUMNS = [
|
|
831
|
-
"id",
|
|
832
|
-
"owner_id",
|
|
833
|
-
"issuer_cnpj",
|
|
834
|
-
"subject_id",
|
|
835
|
-
"issuing_point_id",
|
|
836
|
-
"model",
|
|
837
|
-
"environment",
|
|
838
|
-
"series_kind",
|
|
839
|
-
"series",
|
|
840
|
-
"number",
|
|
841
|
-
"key_code",
|
|
842
|
-
"status",
|
|
843
|
-
"sale",
|
|
844
|
-
"totals",
|
|
845
|
-
"buyer_tax_id",
|
|
846
|
-
"access_key",
|
|
847
|
-
"protocol",
|
|
848
|
-
"status_code",
|
|
849
|
-
"status_reason",
|
|
850
|
-
"last_error_class",
|
|
851
|
-
"outcome_unknown",
|
|
852
|
-
"issued_at",
|
|
853
|
-
"authorized_at",
|
|
854
|
-
"contingency",
|
|
855
|
-
"cancelled_at",
|
|
856
|
-
"cancel_reason",
|
|
857
|
-
"cancel_protocol",
|
|
858
|
-
"replaced_by_id",
|
|
859
|
-
"number_void",
|
|
860
|
-
"xml_key",
|
|
861
|
-
"event_xml_key",
|
|
862
|
-
"attempts",
|
|
863
|
-
"failures",
|
|
864
|
-
"next_attempt_at",
|
|
865
|
-
"attention",
|
|
866
|
-
"deadline_warned_at",
|
|
867
|
-
"created_at",
|
|
868
|
-
"updated_at"
|
|
869
|
-
];
|
|
870
|
-
var JSON_COLUMNS = /* @__PURE__ */ new Set(["sale", "totals", "contingency"]);
|
|
871
|
-
var TIME_COLUMNS = /* @__PURE__ */ new Set(["next_attempt_at", "deadline_warned_at", "created_at", "updated_at"]);
|
|
872
|
-
function placeholder(column, index) {
|
|
873
|
-
if (JSON_COLUMNS.has(column)) return `$${index}::jsonb`;
|
|
874
|
-
if (TIME_COLUMNS.has(column)) return `$${index}::timestamp(3)`;
|
|
875
|
-
return `$${index}`;
|
|
876
|
-
}
|
|
877
|
-
__name(placeholder, "placeholder");
|
|
878
|
-
function documentValues(d) {
|
|
879
|
-
return [
|
|
880
|
-
d.id,
|
|
881
|
-
d.ownerId,
|
|
882
|
-
d.issuerCnpj,
|
|
883
|
-
d.subjectId,
|
|
884
|
-
d.issuingPointId,
|
|
885
|
-
d.model,
|
|
886
|
-
d.environment,
|
|
887
|
-
d.seriesKind,
|
|
888
|
-
d.series,
|
|
889
|
-
d.number,
|
|
890
|
-
d.keyCode,
|
|
891
|
-
d.status,
|
|
892
|
-
JSON.stringify(d.sale),
|
|
893
|
-
JSON.stringify(d.totals),
|
|
894
|
-
d.buyerTaxId,
|
|
895
|
-
d.accessKey,
|
|
896
|
-
d.protocol,
|
|
897
|
-
d.statusCode,
|
|
898
|
-
d.statusReason,
|
|
899
|
-
d.lastErrorClass,
|
|
900
|
-
d.outcomeUnknown,
|
|
901
|
-
d.issuedAt,
|
|
902
|
-
d.authorizedAt,
|
|
903
|
-
d.contingency === null ? null : JSON.stringify(d.contingency),
|
|
904
|
-
d.cancelledAt,
|
|
905
|
-
d.cancelReason,
|
|
906
|
-
d.cancelProtocol,
|
|
907
|
-
d.replacedById,
|
|
908
|
-
d.numberVoid,
|
|
909
|
-
d.xmlKey,
|
|
910
|
-
d.eventXmlKey,
|
|
911
|
-
d.attempts,
|
|
912
|
-
d.failures,
|
|
913
|
-
d.nextAttemptAt,
|
|
914
|
-
d.attention,
|
|
915
|
-
d.deadlineWarnedAt,
|
|
916
|
-
d.createdAt,
|
|
917
|
-
d.updatedAt
|
|
918
|
-
];
|
|
919
|
-
}
|
|
920
|
-
__name(documentValues, "documentValues");
|
|
921
|
-
function documentOf(row) {
|
|
922
|
-
return {
|
|
923
|
-
id: String(row["id"]),
|
|
924
|
-
ownerId: String(row["owner_id"]),
|
|
925
|
-
issuerCnpj: String(row["issuer_cnpj"]),
|
|
926
|
-
subjectId: String(row["subject_id"]),
|
|
927
|
-
issuingPointId: String(row["issuing_point_id"]),
|
|
928
|
-
model: row["model"],
|
|
929
|
-
environment: row["environment"],
|
|
930
|
-
seriesKind: row["series_kind"],
|
|
931
|
-
series: Number(row["series"]),
|
|
932
|
-
number: Number(row["number"]),
|
|
933
|
-
keyCode: String(row["key_code"]),
|
|
934
|
-
status: row["status"],
|
|
935
|
-
sale: json(row["sale"]),
|
|
936
|
-
totals: json(row["totals"]),
|
|
937
|
-
buyerTaxId: text(row["buyer_tax_id"]),
|
|
938
|
-
accessKey: text(row["access_key"]),
|
|
939
|
-
protocol: text(row["protocol"]),
|
|
940
|
-
statusCode: text(row["status_code"]),
|
|
941
|
-
statusReason: text(row["status_reason"]),
|
|
942
|
-
lastErrorClass: text(row["last_error_class"]),
|
|
943
|
-
outcomeUnknown: row["outcome_unknown"] === true,
|
|
944
|
-
issuedAt: String(row["issued_at"]),
|
|
945
|
-
authorizedAt: text(row["authorized_at"]),
|
|
946
|
-
contingency: row["contingency"] === null ? null : json(row["contingency"]),
|
|
947
|
-
cancelledAt: text(row["cancelled_at"]),
|
|
948
|
-
cancelReason: text(row["cancel_reason"]),
|
|
949
|
-
cancelProtocol: text(row["cancel_protocol"]),
|
|
950
|
-
replacedById: text(row["replaced_by_id"]),
|
|
951
|
-
numberVoid: text(row["number_void"]),
|
|
952
|
-
xmlKey: text(row["xml_key"]),
|
|
953
|
-
eventXmlKey: text(row["event_xml_key"]),
|
|
954
|
-
attempts: Number(row["attempts"]),
|
|
955
|
-
failures: Number(row["failures"]),
|
|
956
|
-
nextAttemptAt: iso(row["next_attempt_at"]),
|
|
957
|
-
attention: row["attention"] === true,
|
|
958
|
-
deadlineWarnedAt: iso(row["deadline_warned_at"]),
|
|
959
|
-
createdAt: requiredIso(row["created_at"]),
|
|
960
|
-
updatedAt: requiredIso(row["updated_at"])
|
|
961
|
-
};
|
|
962
|
-
}
|
|
963
|
-
__name(documentOf, "documentOf");
|
|
964
|
-
function eventOf(row) {
|
|
965
|
-
return {
|
|
966
|
-
documentId: String(row["document_id"]),
|
|
967
|
-
kind: row["kind"],
|
|
968
|
-
fromStatus: row["from_status"],
|
|
969
|
-
toStatus: row["to_status"],
|
|
970
|
-
at: requiredIso(row["at"]),
|
|
971
|
-
errorClass: text(row["error_class"]),
|
|
972
|
-
code: text(row["code"]),
|
|
973
|
-
answer: row["answer"] === null ? null : json(row["answer"])
|
|
974
|
-
};
|
|
975
|
-
}
|
|
976
|
-
__name(eventOf, "eventOf");
|
|
977
|
-
var PROFILE_COLUMNS = [
|
|
978
|
-
"owner_id",
|
|
979
|
-
"cnpj",
|
|
980
|
-
"state_registration",
|
|
981
|
-
"municipal_registration",
|
|
982
|
-
"cnae",
|
|
983
|
-
"legal_name",
|
|
984
|
-
"trade_name",
|
|
985
|
-
"tax_regime",
|
|
986
|
-
"regime",
|
|
987
|
-
"regime_effective_from",
|
|
988
|
-
"restaurant_regime",
|
|
989
|
-
"address",
|
|
990
|
-
"environment",
|
|
991
|
-
"document_policy",
|
|
992
|
-
"signing_identity",
|
|
993
|
-
"certificate_ciphertext",
|
|
994
|
-
"certificate_password_ciphertext",
|
|
995
|
-
"certificate_expires_at",
|
|
996
|
-
"csc_id",
|
|
997
|
-
"csc_ciphertext",
|
|
998
|
-
"consent_recorded_at",
|
|
999
|
-
"updated_at"
|
|
1000
|
-
];
|
|
1001
|
-
function profilePlaceholder(column, index) {
|
|
1002
|
-
if (column === "address") return `$${index}::jsonb`;
|
|
1003
|
-
if (column === "regime_effective_from") return `$${index}::date`;
|
|
1004
|
-
if (column.endsWith("_at")) return `$${index}::timestamp(3)`;
|
|
1005
|
-
return `$${index}`;
|
|
1006
|
-
}
|
|
1007
|
-
__name(profilePlaceholder, "profilePlaceholder");
|
|
1008
|
-
function profileValues(p) {
|
|
1009
|
-
return [
|
|
1010
|
-
p.ownerId,
|
|
1011
|
-
p.cnpj,
|
|
1012
|
-
p.stateRegistration,
|
|
1013
|
-
p.municipalRegistration,
|
|
1014
|
-
p.cnae,
|
|
1015
|
-
p.legalName,
|
|
1016
|
-
p.tradeName,
|
|
1017
|
-
p.taxRegime,
|
|
1018
|
-
p.regime,
|
|
1019
|
-
p.regimeEffectiveFrom,
|
|
1020
|
-
p.restaurantRegime,
|
|
1021
|
-
JSON.stringify(p.address),
|
|
1022
|
-
p.environment,
|
|
1023
|
-
p.documentPolicy,
|
|
1024
|
-
p.signingIdentity,
|
|
1025
|
-
p.certificateCiphertext,
|
|
1026
|
-
p.certificatePasswordCiphertext,
|
|
1027
|
-
p.certificateExpiresAt,
|
|
1028
|
-
p.cscId,
|
|
1029
|
-
p.cscCiphertext,
|
|
1030
|
-
p.consentRecordedAt,
|
|
1031
|
-
p.updatedAt
|
|
1032
|
-
];
|
|
1033
|
-
}
|
|
1034
|
-
__name(profileValues, "profileValues");
|
|
1035
|
-
function profileOf(row) {
|
|
1036
|
-
return {
|
|
1037
|
-
ownerId: String(row["owner_id"]),
|
|
1038
|
-
cnpj: String(row["cnpj"]),
|
|
1039
|
-
stateRegistration: String(row["state_registration"]),
|
|
1040
|
-
municipalRegistration: text(row["municipal_registration"]),
|
|
1041
|
-
cnae: text(row["cnae"]),
|
|
1042
|
-
legalName: String(row["legal_name"]),
|
|
1043
|
-
tradeName: text(row["trade_name"]),
|
|
1044
|
-
taxRegime: row["tax_regime"],
|
|
1045
|
-
regime: row["regime"],
|
|
1046
|
-
regimeEffectiveFrom: day(row["regime_effective_from"]),
|
|
1047
|
-
restaurantRegime: row["restaurant_regime"] === true,
|
|
1048
|
-
address: json(row["address"]),
|
|
1049
|
-
environment: row["environment"],
|
|
1050
|
-
documentPolicy: row["document_policy"],
|
|
1051
|
-
signingIdentity: row["signing_identity"],
|
|
1052
|
-
certificateCiphertext: text(row["certificate_ciphertext"]),
|
|
1053
|
-
certificatePasswordCiphertext: text(row["certificate_password_ciphertext"]),
|
|
1054
|
-
certificateExpiresAt: iso(row["certificate_expires_at"]),
|
|
1055
|
-
cscId: text(row["csc_id"]),
|
|
1056
|
-
cscCiphertext: text(row["csc_ciphertext"]),
|
|
1057
|
-
consentRecordedAt: iso(row["consent_recorded_at"]),
|
|
1058
|
-
updatedAt: requiredIso(row["updated_at"])
|
|
1059
|
-
};
|
|
1060
|
-
}
|
|
1061
|
-
__name(profileOf, "profileOf");
|
|
1062
|
-
function pointOf(row) {
|
|
1063
|
-
return {
|
|
1064
|
-
id: String(row["id"]),
|
|
1065
|
-
ownerId: String(row["owner_id"]),
|
|
1066
|
-
model: row["model"],
|
|
1067
|
-
onlineSeries: Number(row["online_series"]),
|
|
1068
|
-
contingencySeries: row["contingency_series"] === null ? null : Number(row["contingency_series"]),
|
|
1069
|
-
createdAt: requiredIso(row["created_at"])
|
|
1070
|
-
};
|
|
1071
|
-
}
|
|
1072
|
-
__name(pointOf, "pointOf");
|
|
1073
|
-
|
|
1074
1954
|
// src/documents/sql-store.ts
|
|
1075
|
-
var
|
|
1076
|
-
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(", ")})
|
|
1077
1957
|
VALUES (${DOCUMENT_COLUMNS.map((c, i) => placeholder(c, i + 1)).join(", ")})`;
|
|
1078
1958
|
var MUTABLE = DOCUMENT_COLUMNS.filter((c) => c !== "id" && c !== "created_at");
|
|
1079
1959
|
var UPDATE_DOCUMENT = [
|
|
@@ -1087,22 +1967,22 @@ function updateValues(document, previous) {
|
|
|
1087
1967
|
return [document.id, ...mutable, previous.updatedAt, previous.status];
|
|
1088
1968
|
}
|
|
1089
1969
|
__name(updateValues, "updateValues");
|
|
1090
|
-
var
|
|
1970
|
+
var INSERT_EVENT2 = `INSERT INTO "fiscal_document_events" ("id", "document_id", "kind", "from_status", "to_status", "at", "error_class", "code", "answer")
|
|
1091
1971
|
VALUES ($1, $2, $3, $4, $5, $6::timestamp(3), $7, $8, $9::jsonb)`;
|
|
1092
1972
|
var UPSERT_PROFILE = `INSERT INTO "fiscal_emitter_profiles" (${PROFILE_COLUMNS.map((c) => `"${c}"`).join(", ")})
|
|
1093
1973
|
VALUES (${PROFILE_COLUMNS.map((c, i) => profilePlaceholder(c, i + 1)).join(", ")})
|
|
1094
1974
|
ON CONFLICT ("owner_id") DO UPDATE SET ${PROFILE_COLUMNS.filter((c) => c !== "owner_id").map((c) => `"${c}" = EXCLUDED."${c}"`).join(", ")}`;
|
|
1095
1975
|
var OWED = `("status" IN ('PENDING', 'SUBMITTED') OR "number_void" IN ('LOOKUP_FIRST', 'INUTILIZE', 'CANCEL'))`;
|
|
1096
|
-
function
|
|
1097
|
-
const
|
|
1098
|
-
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);
|
|
1099
1979
|
}
|
|
1100
|
-
__name(
|
|
1980
|
+
__name(violates2, "violates");
|
|
1101
1981
|
async function saveRow(tx, previous, { document, event }) {
|
|
1102
|
-
const updated = await
|
|
1982
|
+
const updated = await rows2(tx, UPDATE_DOCUMENT, ...updateValues(document, previous));
|
|
1103
1983
|
if (updated.length === 0) return false;
|
|
1104
1984
|
await tx.$executeRawUnsafe(
|
|
1105
|
-
|
|
1985
|
+
INSERT_EVENT2,
|
|
1106
1986
|
globalThis.crypto.randomUUID(),
|
|
1107
1987
|
event.documentId,
|
|
1108
1988
|
event.kind,
|
|
@@ -1118,13 +1998,13 @@ async function saveRow(tx, previous, { document, event }) {
|
|
|
1118
1998
|
__name(saveRow, "saveRow");
|
|
1119
1999
|
async function draw(tx, request) {
|
|
1120
2000
|
try {
|
|
1121
|
-
const [row] = await
|
|
2001
|
+
const [row] = await rows2(tx, FISCAL_NEXT_NUMBER_SQL, request.issuerCnpj, request.environment, request.model, request.series, request.issuingPointId);
|
|
1122
2002
|
if (row === void 0) {
|
|
1123
2003
|
throw new FiscalDocumentError("NOT_FOUND", `no counter for series ${request.series} on issuing point ${request.issuingPointId}.`);
|
|
1124
2004
|
}
|
|
1125
2005
|
return Number(row["number"]);
|
|
1126
2006
|
} catch (error) {
|
|
1127
|
-
if (
|
|
2007
|
+
if (violates2(error, "fiscal_number_counters_next_number_check")) {
|
|
1128
2008
|
throw new FiscalDocumentError("SERIES_EXHAUSTED", `series ${request.series} has no number left.`);
|
|
1129
2009
|
}
|
|
1130
2010
|
throw error;
|
|
@@ -1133,9 +2013,9 @@ async function draw(tx, request) {
|
|
|
1133
2013
|
__name(draw, "draw");
|
|
1134
2014
|
async function insertDocument(tx, document) {
|
|
1135
2015
|
try {
|
|
1136
|
-
await tx.$executeRawUnsafe(
|
|
2016
|
+
await tx.$executeRawUnsafe(INSERT_DOCUMENT2, ...documentValues(document));
|
|
1137
2017
|
} catch (error) {
|
|
1138
|
-
if (
|
|
2018
|
+
if (violates2(error, "fiscal_documents_live_subject_key")) {
|
|
1139
2019
|
throw new FiscalDocumentError("SUBJECT_HAS_DOCUMENT", `subject ${document.subjectId} already has a live ${document.model}.`);
|
|
1140
2020
|
}
|
|
1141
2021
|
throw error;
|
|
@@ -1161,22 +2041,22 @@ __name(openCounters, "openCounters");
|
|
|
1161
2041
|
function profileMethods(db) {
|
|
1162
2042
|
return {
|
|
1163
2043
|
async getProfile(ownerId) {
|
|
1164
|
-
const [row] = await
|
|
2044
|
+
const [row] = await rows2(db, `SELECT * FROM "fiscal_emitter_profiles" WHERE "owner_id" = $1`, ownerId);
|
|
1165
2045
|
return row === void 0 ? null : profileOf(row);
|
|
1166
2046
|
},
|
|
1167
2047
|
async saveProfile(profile) {
|
|
1168
2048
|
await db.$executeRawUnsafe(UPSERT_PROFILE, ...profileValues(profile));
|
|
1169
2049
|
},
|
|
1170
2050
|
async getIssuingPoint(ownerId, id) {
|
|
1171
|
-
const [row] = await
|
|
2051
|
+
const [row] = await rows2(db, `SELECT * FROM "fiscal_issuing_points" WHERE "id" = $1 AND "owner_id" = $2`, id, ownerId);
|
|
1172
2052
|
return row === void 0 ? null : pointOf(row);
|
|
1173
2053
|
},
|
|
1174
2054
|
async listIssuingPoints(ownerId) {
|
|
1175
|
-
return (await
|
|
2055
|
+
return (await rows2(db, `SELECT * FROM "fiscal_issuing_points" WHERE "owner_id" = $1 ORDER BY "created_at", "id"`, ownerId)).map(pointOf);
|
|
1176
2056
|
},
|
|
1177
2057
|
createIssuingPoint: /* @__PURE__ */ __name((point, issuerCnpj, firstNumber) => createIssuingPoint2(db, point, issuerCnpj, firstNumber), "createIssuingPoint"),
|
|
1178
2058
|
async listExpiringCertificates(before) {
|
|
1179
|
-
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);
|
|
1180
2060
|
}
|
|
1181
2061
|
};
|
|
1182
2062
|
}
|
|
@@ -1200,16 +2080,16 @@ async function createIssuingPoint2(db, ...[point, issuerCnpj, firstNumber]) {
|
|
|
1200
2080
|
}
|
|
1201
2081
|
});
|
|
1202
2082
|
} catch (error) {
|
|
1203
|
-
if (
|
|
2083
|
+
if (violates2(error, "fiscal_number_counters_pkey")) {
|
|
1204
2084
|
throw new FiscalDocumentError("INVALID_INPUT", `a series of issuing point ${point.id} already belongs to another issuing point.`);
|
|
1205
2085
|
}
|
|
1206
|
-
if (
|
|
2086
|
+
if (violates2(error, "fiscal_issuing_points_pkey")) throw new FiscalDocumentError("INVALID_INPUT", `issuing point ${point.id} exists.`);
|
|
1207
2087
|
throw error;
|
|
1208
2088
|
}
|
|
1209
2089
|
}
|
|
1210
2090
|
__name(createIssuingPoint2, "createIssuingPoint");
|
|
1211
2091
|
function documentMethods(db) {
|
|
1212
|
-
const documents = /* @__PURE__ */ __name(async (query, ...values) => (await
|
|
2092
|
+
const documents = /* @__PURE__ */ __name(async (query, ...values) => (await rows2(db, query, ...values)).map(documentOf), "documents");
|
|
1213
2093
|
return {
|
|
1214
2094
|
createDocument: /* @__PURE__ */ __name((request, build, replace) => db.$transaction(async (tx) => {
|
|
1215
2095
|
if (replace !== void 0 && !await saveRow(tx, replace.previous, replace.transition)) {
|
|
@@ -1230,7 +2110,7 @@ function documentMethods(db) {
|
|
|
1230
2110
|
model
|
|
1231
2111
|
), "listBySubject"),
|
|
1232
2112
|
async listEvents(documentId) {
|
|
1233
|
-
return (await
|
|
2113
|
+
return (await rows2(db, `SELECT * FROM "fiscal_document_events" WHERE "document_id" = $1 ORDER BY "seq"`, documentId)).map(eventOf);
|
|
1234
2114
|
},
|
|
1235
2115
|
saveTransition: /* @__PURE__ */ __name((previous, transition2) => db.$transaction((tx) => saveRow(tx, previous, transition2)), "saveTransition"),
|
|
1236
2116
|
listDue: /* @__PURE__ */ __name(({ now, limit }) => documents(
|
|
@@ -1260,7 +2140,7 @@ function createPrismaFiscalStore(config) {
|
|
|
1260
2140
|
if (typeof db?.$transaction !== "function" || typeof db.$queryRawUnsafe !== "function") {
|
|
1261
2141
|
throw new TypeError("createPrismaFiscalStore needs prisma: the host's Prisma client.");
|
|
1262
2142
|
}
|
|
1263
|
-
return { ...profileMethods(db), ...documentMethods(db) };
|
|
2143
|
+
return { ...profileMethods(db), ...documentMethods(db), ...blockMethods(db) };
|
|
1264
2144
|
}
|
|
1265
2145
|
__name(createPrismaFiscalStore, "createPrismaFiscalStore");
|
|
1266
2146
|
|
|
@@ -1302,7 +2182,9 @@ function documentLines(breakdown, details) {
|
|
|
1302
2182
|
}
|
|
1303
2183
|
__name(documentLines, "documentLines");
|
|
1304
2184
|
export {
|
|
2185
|
+
CONTINGENCY_BLOCK_FATES,
|
|
1305
2186
|
CONTINGENCY_WARNING_AFTER_MS,
|
|
2187
|
+
DEFAULT_CONTINGENCY_BLOCK_SIZE,
|
|
1306
2188
|
DOCUMENT_POLICIES,
|
|
1307
2189
|
DOCUMENT_TRANSITIONS,
|
|
1308
2190
|
FINAL_STATUSES,
|
|
@@ -1313,11 +2195,15 @@ export {
|
|
|
1313
2195
|
FISCAL_DOCUMENT_REJECTED,
|
|
1314
2196
|
FISCAL_DOCUMENT_STATUSES,
|
|
1315
2197
|
FISCAL_NEXT_NUMBER_SQL,
|
|
2198
|
+
FISCAL_RESERVE_BLOCK_SQL,
|
|
1316
2199
|
FiscalDocumentError,
|
|
1317
2200
|
LATE_CANCEL_CODES,
|
|
2201
|
+
MAX_CONTINGENCY_BLOCK_SIZE,
|
|
1318
2202
|
MAX_FAILURES,
|
|
2203
|
+
MAX_PAYMENT_LINKS,
|
|
1319
2204
|
OWED_VOIDS,
|
|
1320
2205
|
SIGNING_IDENTITY_KINDS,
|
|
2206
|
+
accountFor as accountForContingencyBlock,
|
|
1321
2207
|
canTransition,
|
|
1322
2208
|
computeAccessKey,
|
|
1323
2209
|
createFiscalDocuments,
|
|
@@ -1335,6 +2221,7 @@ export {
|
|
|
1335
2221
|
parseCertificateUpload,
|
|
1336
2222
|
parseIssuingPointInput,
|
|
1337
2223
|
parseProfileInput,
|
|
2224
|
+
parseSignedContingencyNote,
|
|
1338
2225
|
scrubSecrets,
|
|
1339
2226
|
transition,
|
|
1340
2227
|
viewOf,
|