@12-apps/fiscal 0.0.0-stage → 1.1.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 +269 -2
- package/dist/chunk-27B4HNO6.js +574 -0
- package/dist/chunk-27B4HNO6.js.map +1 -0
- package/dist/chunk-3SDXLSG4.js +24 -0
- package/dist/chunk-3SDXLSG4.js.map +1 -0
- package/dist/chunk-7QVYU63E.js +7 -0
- package/dist/chunk-7QVYU63E.js.map +1 -0
- package/dist/chunk-ALABGVPO.js +247 -0
- package/dist/chunk-ALABGVPO.js.map +1 -0
- package/dist/chunk-FOFIN5M7.js +14 -0
- package/dist/chunk-FOFIN5M7.js.map +1 -0
- package/dist/chunk-HQ2NXSTX.js +85 -0
- package/dist/chunk-HQ2NXSTX.js.map +1 -0
- package/dist/chunk-PNTKG3DZ.js +47 -0
- package/dist/chunk-PNTKG3DZ.js.map +1 -0
- package/dist/chunk-RRFKYVLZ.js +192 -0
- package/dist/chunk-RRFKYVLZ.js.map +1 -0
- package/dist/chunk-V5ZQAAJT.js +210 -0
- package/dist/chunk-V5ZQAAJT.js.map +1 -0
- package/dist/chunk-X6MRDUYH.js +21 -0
- package/dist/chunk-X6MRDUYH.js.map +1 -0
- package/dist/chunk-XQGW5HUG.js +30 -0
- package/dist/chunk-XQGW5HUG.js.map +1 -0
- package/dist/context-ChnWR4Kb.d.ts +455 -0
- package/dist/danfe/en-US.d.ts +12 -0
- package/dist/danfe/en-US.js +51 -0
- package/dist/danfe/en-US.js.map +1 -0
- package/dist/danfe/index.d.ts +50 -0
- package/dist/danfe/index.js +18 -0
- package/dist/danfe/index.js.map +1 -0
- package/dist/danfe/pt-BR.d.ts +11 -0
- package/dist/danfe/pt-BR.js +51 -0
- package/dist/danfe/pt-BR.js.map +1 -0
- package/dist/documents/index.d.ts +169 -0
- package/dist/documents/index.js +1228 -0
- package/dist/documents/index.js.map +1 -0
- package/dist/engine/index.d.ts +118 -0
- package/dist/engine/index.js +591 -0
- package/dist/engine/index.js.map +1 -0
- package/dist/http.d.ts +73 -0
- package/dist/http.js +16 -0
- package/dist/http.js.map +1 -0
- package/dist/issuer/index.d.ts +43 -0
- package/dist/issuer/index.js +131 -0
- package/dist/issuer/index.js.map +1 -0
- package/dist/jobs.d.ts +74 -0
- package/dist/jobs.js +22 -0
- package/dist/jobs.js.map +1 -0
- package/dist/labels-BNvflT0h.d.ts +44 -0
- package/dist/manifest/index.d.ts +97 -0
- package/dist/manifest/index.js +27 -0
- package/dist/manifest/index.js.map +1 -0
- package/dist/manifest/server.d.ts +57 -0
- package/dist/manifest/server.js +25 -0
- package/dist/manifest/server.js.map +1 -0
- package/dist/notifications.d.ts +93 -0
- package/dist/notifications.js +41 -0
- package/dist/notifications.js.map +1 -0
- package/dist/port-DpRFK56U.d.ts +238 -0
- package/dist/sale/index.d.ts +243 -0
- package/dist/sale/index.js +1 -0
- package/dist/sale/index.js.map +1 -0
- package/dist/service-KTjH7AxW.d.ts +139 -0
- package/dist/sidecar/index.d.ts +216 -0
- package/dist/sidecar/index.js +8 -0
- package/dist/sidecar/index.js.map +1 -0
- package/dist/types-B1b8LIWX.d.ts +247 -0
- package/package.json +126 -4
- package/prisma/fiscal.prisma +158 -0
- package/prisma/migrations/20261113220000_fiscal_documents/migration.sql +201 -0
- package/sidecar/.dockerignore +5 -0
- package/sidecar/Dockerfile +68 -0
- package/sidecar/README.md +149 -0
- package/sidecar/composer.json +30 -0
- package/sidecar/composer.lock +2224 -0
- package/sidecar/docker/apache.conf +14 -0
- package/sidecar/docker/icp-brasil.pem +8031 -0
- package/sidecar/docker/mpm.conf +17 -0
- package/sidecar/docker/openssl.cnf +16 -0
- package/sidecar/docker/php.ini +19 -0
- package/sidecar/public/index.php +15 -0
- package/sidecar/schema/sale-for-document.schema.json +401 -0
- package/sidecar/src/ErrorClass.php +31 -0
- package/sidecar/src/Http/Request.php +48 -0
- package/sidecar/src/Http/Response.php +32 -0
- package/sidecar/src/Http/Router.php +59 -0
- package/sidecar/src/Kernel.php +99 -0
- package/sidecar/src/Module.php +31 -0
- package/sidecar/src/Nfe/Classifier.php +89 -0
- package/sidecar/src/Nfe/Credentials.php +52 -0
- package/sidecar/src/Nfe/DocumentMapper.php +383 -0
- package/sidecar/src/Nfe/DocumentSchema.php +39 -0
- package/sidecar/src/Nfe/Input.php +125 -0
- package/sidecar/src/Nfe/Model.php +17 -0
- package/sidecar/src/Nfe/NfeModule.php +62 -0
- package/sidecar/src/Nfe/NfeService.php +504 -0
- package/sidecar/src/Nfe/Sefaz.php +49 -0
- package/sidecar/src/Nfe/SefazReply.php +81 -0
- package/sidecar/src/Nfe/Transport/CurlTransport.php +198 -0
- package/sidecar/src/Nfe/Transport/SoapAdapter.php +57 -0
- package/sidecar/src/Nfe/Transport/Transport.php +20 -0
- package/sidecar/src/Nfe/Transport/TransportFailure.php +42 -0
- package/sidecar/src/RequestLog.php +54 -0
- package/sidecar/src/ServiceError.php +69 -0
- package/src/danfe/en-US.ts +53 -0
- package/src/danfe/index.ts +11 -0
- package/src/danfe/labels.ts +49 -0
- package/src/danfe/pt-BR.ts +52 -0
- package/src/danfe/render.ts +265 -0
- package/src/danfe/xml.ts +45 -0
- package/src/documents/context.ts +260 -0
- package/src/documents/errors.ts +41 -0
- package/src/documents/helpers.ts +128 -0
- package/src/documents/index.ts +39 -0
- package/src/documents/lines.ts +63 -0
- package/src/documents/machine-steps.ts +260 -0
- package/src/documents/machine.ts +128 -0
- package/src/documents/memory.ts +138 -0
- package/src/documents/nfe-proc.ts +51 -0
- package/src/documents/ports.ts +130 -0
- package/src/documents/profile-input.ts +168 -0
- package/src/documents/profile.ts +98 -0
- package/src/documents/service-profile.ts +104 -0
- package/src/documents/service.ts +296 -0
- package/src/documents/settle.ts +121 -0
- package/src/documents/signing.ts +61 -0
- package/src/documents/sql-rows.ts +180 -0
- package/src/documents/sql-store.ts +242 -0
- package/src/documents/sql.ts +18 -0
- package/src/documents/steps.ts +173 -0
- package/src/documents/tests/integration/pglite.ts +73 -0
- package/src/documents/types.ts +193 -0
- package/src/engine/compare.ts +68 -0
- package/src/engine/compute.ts +40 -0
- package/src/engine/errors.ts +28 -0
- package/src/engine/index.ts +20 -0
- package/src/engine/oracle.ts +81 -0
- package/src/engine/plan.ts +268 -0
- package/src/engine/rounding.ts +81 -0
- package/src/engine/types.ts +270 -0
- package/src/engine/validate.ts +222 -0
- package/src/http.ts +264 -0
- package/src/issuer/index.ts +9 -0
- package/src/issuer/port.ts +109 -0
- package/src/issuer/sidecar.ts +171 -0
- package/src/jobs.ts +115 -0
- package/src/manifest/index.ts +46 -0
- package/src/manifest/permissions.ts +28 -0
- package/src/manifest/server.ts +20 -0
- package/src/notifications.ts +120 -0
- package/src/sale/index.ts +8 -0
- package/src/sale/types.ts +292 -0
- package/src/sidecar/index.ts +9 -0
- package/src/sidecar/types.ts +243 -0
- package/tables/ibs-cbs-2026-11-13.json +156 -0
|
@@ -0,0 +1,1228 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DOCUMENT_POLICIES,
|
|
3
|
+
SIGNING_IDENTITY_KINDS,
|
|
4
|
+
parseCertificateUpload,
|
|
5
|
+
parseIssuingPointInput,
|
|
6
|
+
parseProfileInput,
|
|
7
|
+
viewOf
|
|
8
|
+
} from "../chunk-RRFKYVLZ.js";
|
|
9
|
+
import {
|
|
10
|
+
element
|
|
11
|
+
} from "../chunk-PNTKG3DZ.js";
|
|
12
|
+
import {
|
|
13
|
+
DOCUMENT_TRANSITIONS,
|
|
14
|
+
FINAL_STATUSES,
|
|
15
|
+
FISCAL_CERTIFICATE_EXPIRING,
|
|
16
|
+
FISCAL_CONTINGENCY_DEADLINE,
|
|
17
|
+
FISCAL_DOCUMENT_NEEDS_ATTENTION,
|
|
18
|
+
FISCAL_DOCUMENT_REJECTED,
|
|
19
|
+
FiscalContext,
|
|
20
|
+
MAX_FAILURES,
|
|
21
|
+
assertConfig,
|
|
22
|
+
assertReason,
|
|
23
|
+
canTransition,
|
|
24
|
+
computeAccessKey,
|
|
25
|
+
draftOf,
|
|
26
|
+
drawKeyCode,
|
|
27
|
+
issuerOf,
|
|
28
|
+
localIso,
|
|
29
|
+
scrubSecrets,
|
|
30
|
+
totalsOf,
|
|
31
|
+
transition,
|
|
32
|
+
xmlKeys
|
|
33
|
+
} from "../chunk-27B4HNO6.js";
|
|
34
|
+
import {
|
|
35
|
+
FISCAL_DOCUMENT_MODELS,
|
|
36
|
+
FISCAL_DOCUMENT_STATUSES,
|
|
37
|
+
OWED_VOIDS,
|
|
38
|
+
isLive
|
|
39
|
+
} from "../chunk-XQGW5HUG.js";
|
|
40
|
+
import {
|
|
41
|
+
FISCAL_ISSUE
|
|
42
|
+
} from "../chunk-3SDXLSG4.js";
|
|
43
|
+
import {
|
|
44
|
+
FiscalDocumentError
|
|
45
|
+
} from "../chunk-X6MRDUYH.js";
|
|
46
|
+
import {
|
|
47
|
+
__name
|
|
48
|
+
} from "../chunk-7QVYU63E.js";
|
|
49
|
+
|
|
50
|
+
// src/documents/signing.ts
|
|
51
|
+
function createStoreCertificateIdentity(config) {
|
|
52
|
+
if (typeof config?.cipher?.decrypt !== "function") throw new TypeError("createStoreCertificateIdentity needs a cipher.");
|
|
53
|
+
const { cipher } = config;
|
|
54
|
+
return {
|
|
55
|
+
kind: "STORE_CERTIFICATE",
|
|
56
|
+
async materialFor(profile) {
|
|
57
|
+
if (profile.certificateCiphertext === null || profile.certificatePasswordCiphertext === null) {
|
|
58
|
+
throw new FiscalDocumentError("NOT_ISSUABLE", `owner ${profile.ownerId} has no certificate.`);
|
|
59
|
+
}
|
|
60
|
+
const [pfxBase64, password] = await Promise.all([
|
|
61
|
+
cipher.decrypt(profile.certificateCiphertext),
|
|
62
|
+
cipher.decrypt(profile.certificatePasswordCiphertext)
|
|
63
|
+
]);
|
|
64
|
+
const csc = profile.cscId !== null && profile.cscCiphertext !== null ? { id: profile.cscId, token: await cipher.decrypt(profile.cscCiphertext) } : null;
|
|
65
|
+
return { certificate: { pfxBase64, password }, csc };
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
__name(createStoreCertificateIdentity, "createStoreCertificateIdentity");
|
|
70
|
+
function createPlatformIdentity() {
|
|
71
|
+
return {
|
|
72
|
+
kind: "PLATFORM",
|
|
73
|
+
async materialFor(profile) {
|
|
74
|
+
throw new FiscalDocumentError(
|
|
75
|
+
"NOT_SUPPORTED",
|
|
76
|
+
`owner ${profile.ownerId} signs as PLATFORM, which is declared and not built yet (FUT-2229 q4).`
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
__name(createPlatformIdentity, "createPlatformIdentity");
|
|
82
|
+
function createSigningIdentities(config) {
|
|
83
|
+
return { STORE_CERTIFICATE: createStoreCertificateIdentity(config), PLATFORM: createPlatformIdentity() };
|
|
84
|
+
}
|
|
85
|
+
__name(createSigningIdentities, "createSigningIdentities");
|
|
86
|
+
|
|
87
|
+
// src/documents/service-profile.ts
|
|
88
|
+
async function cscCiphertextFor(config, stored, input) {
|
|
89
|
+
if (input.cscToken !== null) {
|
|
90
|
+
if (input.cscId === null) throw new FiscalDocumentError("INVALID_INPUT", "cscId is required with cscToken.");
|
|
91
|
+
return config.cipher.encrypt(input.cscToken);
|
|
92
|
+
}
|
|
93
|
+
if (input.cscId === null) return null;
|
|
94
|
+
if (input.cscId !== stored?.cscId) throw new FiscalDocumentError("INVALID_INPUT", "cscToken is required with a new cscId.");
|
|
95
|
+
return stored.cscCiphertext;
|
|
96
|
+
}
|
|
97
|
+
__name(cscCiphertextFor, "cscCiphertextFor");
|
|
98
|
+
async function saveProfile({ ctx, config }, ownerId, input) {
|
|
99
|
+
const stored = await config.store.getProfile(ownerId);
|
|
100
|
+
const fields = Object.fromEntries(Object.entries(input).filter(([key]) => key !== "cscToken"));
|
|
101
|
+
const profile = {
|
|
102
|
+
...fields,
|
|
103
|
+
ownerId,
|
|
104
|
+
certificateCiphertext: stored?.certificateCiphertext ?? null,
|
|
105
|
+
certificatePasswordCiphertext: stored?.certificatePasswordCiphertext ?? null,
|
|
106
|
+
certificateExpiresAt: stored?.certificateExpiresAt ?? null,
|
|
107
|
+
cscCiphertext: await cscCiphertextFor(config, stored, input),
|
|
108
|
+
updatedAt: ctx.nowIso()
|
|
109
|
+
};
|
|
110
|
+
await config.store.saveProfile(profile);
|
|
111
|
+
return profile;
|
|
112
|
+
}
|
|
113
|
+
__name(saveProfile, "saveProfile");
|
|
114
|
+
async function uploadCertificate({ ctx, config }, ownerId, certificate) {
|
|
115
|
+
const stored = await ctx.requireProfile(ownerId);
|
|
116
|
+
let facts;
|
|
117
|
+
try {
|
|
118
|
+
facts = await config.readCertificate(certificate);
|
|
119
|
+
} catch {
|
|
120
|
+
throw new FiscalDocumentError("INVALID_INPUT", "the certificate does not open with that password.");
|
|
121
|
+
}
|
|
122
|
+
const profile = {
|
|
123
|
+
...stored,
|
|
124
|
+
certificateCiphertext: await config.cipher.encrypt(certificate.pfxBase64),
|
|
125
|
+
certificatePasswordCiphertext: await config.cipher.encrypt(certificate.password),
|
|
126
|
+
certificateExpiresAt: facts.expiresAt,
|
|
127
|
+
updatedAt: ctx.nowIso()
|
|
128
|
+
};
|
|
129
|
+
await config.store.saveProfile(profile);
|
|
130
|
+
return profile;
|
|
131
|
+
}
|
|
132
|
+
__name(uploadCertificate, "uploadCertificate");
|
|
133
|
+
async function createIssuingPoint({ ctx, config }, ownerId, input) {
|
|
134
|
+
const profile = await ctx.requireProfile(ownerId);
|
|
135
|
+
if (input.model === "NFE" && input.contingencySeries !== null) {
|
|
136
|
+
throw new FiscalDocumentError("INVALID_INPUT", "an NF-e issuing point has no contingency series: the service has no offline NF-e path.");
|
|
137
|
+
}
|
|
138
|
+
const point = {
|
|
139
|
+
id: input.id,
|
|
140
|
+
ownerId,
|
|
141
|
+
model: input.model,
|
|
142
|
+
onlineSeries: input.onlineSeries,
|
|
143
|
+
contingencySeries: input.contingencySeries,
|
|
144
|
+
createdAt: ctx.nowIso()
|
|
145
|
+
};
|
|
146
|
+
await config.store.createIssuingPoint(point, profile.cnpj, { online: input.firstOnlineNumber, contingency: input.firstContingencyNumber });
|
|
147
|
+
return point;
|
|
148
|
+
}
|
|
149
|
+
__name(createIssuingPoint, "createIssuingPoint");
|
|
150
|
+
|
|
151
|
+
// src/documents/nfe-proc.ts
|
|
152
|
+
var PROTOCOL = /<protNFe\b[^>]*>[\s\S]*?<\/protNFe>/;
|
|
153
|
+
var NFE = /<NFe\b[^>]*>[\s\S]*<\/NFe>/;
|
|
154
|
+
function digestOf(signedXml) {
|
|
155
|
+
return /<DigestValue>([^<]+)<\/DigestValue>/.exec(signedXml)?.[1]?.trim() ?? null;
|
|
156
|
+
}
|
|
157
|
+
__name(digestOf, "digestOf");
|
|
158
|
+
function protocolDigestOf(sefazReply) {
|
|
159
|
+
const protocol = PROTOCOL.exec(sefazReply)?.[0];
|
|
160
|
+
const infProt = protocol === void 0 ? null : element(protocol, "infProt");
|
|
161
|
+
return infProt === null ? null : element(infProt, "digVal")?.trim() ?? null;
|
|
162
|
+
}
|
|
163
|
+
__name(protocolDigestOf, "protocolDigestOf");
|
|
164
|
+
var SETTLING = /* @__PURE__ */ new Set(["100", "150", "110", "301", "302", "303"]);
|
|
165
|
+
function certifies(infProt, nfe, accessKey) {
|
|
166
|
+
const digest = digestOf(nfe);
|
|
167
|
+
return element(infProt, "chNFe") === accessKey && SETTLING.has(element(infProt, "cStat") ?? "") && nfe.includes(`Id="NFe${accessKey}"`) && digest !== null && element(infProt, "digVal")?.trim() === digest;
|
|
168
|
+
}
|
|
169
|
+
__name(certifies, "certifies");
|
|
170
|
+
function assembleNfeProc(input) {
|
|
171
|
+
const protocol = PROTOCOL.exec(input.sefazReply)?.[0];
|
|
172
|
+
const nfe = NFE.exec(input.signedXml)?.[0];
|
|
173
|
+
const infProt = protocol === void 0 ? null : element(protocol, "infProt");
|
|
174
|
+
if (protocol === void 0 || nfe === void 0 || infProt === null || !certifies(infProt, nfe, input.accessKey)) return null;
|
|
175
|
+
return `<?xml version="1.0" encoding="UTF-8"?><nfeProc versao="4.00" xmlns="http://www.portalfiscal.inf.br/nfe">${nfe}${protocol}</nfeProc>`;
|
|
176
|
+
}
|
|
177
|
+
__name(assembleNfeProc, "assembleNfeProc");
|
|
178
|
+
|
|
179
|
+
// src/documents/settle.ts
|
|
180
|
+
var REFUSALS = /* @__PURE__ */ new Set(["REJECTED", "AUTH", "INVALID", "INTERNAL"]);
|
|
181
|
+
function defer(ctx, document, what, error) {
|
|
182
|
+
return ctx.advance(document, { kind: "DEFER", reason: `${what} failed`, error, attention: REFUSALS.has(error.class) });
|
|
183
|
+
}
|
|
184
|
+
__name(defer, "defer");
|
|
185
|
+
async function storeNfeProc(ctx, document, answer) {
|
|
186
|
+
if (answer.status !== "AUTHORIZED" && answer.status !== "DENIED" || document.accessKey === null) return void 0;
|
|
187
|
+
const digest = protocolDigestOf(answer.sefazReply);
|
|
188
|
+
if (digest === null) return void 0;
|
|
189
|
+
const signedXml = await ctx.config.storage.get(xmlKeys.signedByDigest(document.accessKey, digest));
|
|
190
|
+
if (signedXml === null) return void 0;
|
|
191
|
+
const nfeProc = assembleNfeProc({ signedXml, sefazReply: answer.sefazReply, accessKey: document.accessKey });
|
|
192
|
+
if (nfeProc === null) return void 0;
|
|
193
|
+
const xmlKey = xmlKeys.authorized(document.accessKey);
|
|
194
|
+
await ctx.config.storage.put(xmlKey, nfeProc, "application/xml");
|
|
195
|
+
return xmlKey;
|
|
196
|
+
}
|
|
197
|
+
__name(storeNfeProc, "storeNfeProc");
|
|
198
|
+
async function settleWithXml(ctx, document, answer) {
|
|
199
|
+
if (document.status !== "SUBMITTED") return document;
|
|
200
|
+
const xmlKey = await storeNfeProc(ctx, document, answer);
|
|
201
|
+
return xmlKey === void 0 ? document : ctx.advance(document, { kind: "LOOKUP", answer, xmlKey });
|
|
202
|
+
}
|
|
203
|
+
__name(settleWithXml, "settleWithXml");
|
|
204
|
+
var lookupFirst = /* @__PURE__ */ __name(async (ctx, document, _profile, signing) => {
|
|
205
|
+
if (document.accessKey === null) return ctx.advance(document, { kind: "DEFER", reason: "no access key to look up", error: null, attention: true });
|
|
206
|
+
const outcome = await ctx.config.issuer.lookup({ model: document.model, environment: document.environment, signing, accessKey: document.accessKey });
|
|
207
|
+
if (!outcome.ok) return defer(ctx, document, "the lookup", outcome.error);
|
|
208
|
+
return settleWithXml(ctx, await ctx.advance(document, { kind: "LOOKUP", answer: outcome.answer }), outcome.answer);
|
|
209
|
+
}, "lookupFirst");
|
|
210
|
+
async function sendOwedCancel(ctx, document, signing) {
|
|
211
|
+
const { accessKey, protocol, replacedById } = document;
|
|
212
|
+
if (accessKey === null || protocol === null) return null;
|
|
213
|
+
const reason = ctx.config.reasons.substitution;
|
|
214
|
+
const base = { environment: document.environment, signing, accessKey, protocol, reason };
|
|
215
|
+
const substitute = replacedById === null ? null : await ctx.config.store.getDocument(document.ownerId, replacedById);
|
|
216
|
+
if (document.model === "NFCE" && substitute?.accessKey) {
|
|
217
|
+
return ctx.config.issuer.cancelBySubstitution({ ...base, substituteAccessKey: substitute.accessKey });
|
|
218
|
+
}
|
|
219
|
+
return ctx.config.issuer.cancel({ ...base, model: document.model });
|
|
220
|
+
}
|
|
221
|
+
__name(sendOwedCancel, "sendOwedCancel");
|
|
222
|
+
var cancelOwed = /* @__PURE__ */ __name(async (ctx, document, _profile, signing) => {
|
|
223
|
+
const outcome = await sendOwedCancel(ctx, document, signing);
|
|
224
|
+
if (outcome === null) return ctx.advance(document, { kind: "DEFER", reason: "no protocol to cancel with", error: null, attention: true });
|
|
225
|
+
if (!outcome.ok) return defer(ctx, document, "the owed cancel", outcome.error);
|
|
226
|
+
const eventXmlKey = outcome.answer.eventXml === null ? null : xmlKeys.cancel(outcome.answer.accessKey);
|
|
227
|
+
if (eventXmlKey !== null) await ctx.config.storage.put(eventXmlKey, outcome.answer.eventXml ?? "", "application/xml");
|
|
228
|
+
return ctx.advance(document, { kind: "CANCEL", answer: outcome.answer, reason: ctx.config.reasons.substitution, eventXmlKey });
|
|
229
|
+
}, "cancelOwed");
|
|
230
|
+
var inutilizeOwed = /* @__PURE__ */ __name(async (ctx, document, profile, signing) => {
|
|
231
|
+
const outcome = await ctx.config.issuer.inutilize({
|
|
232
|
+
model: document.model,
|
|
233
|
+
environment: document.environment,
|
|
234
|
+
signing,
|
|
235
|
+
uf: profile.address.uf,
|
|
236
|
+
cnpj: document.issuerCnpj,
|
|
237
|
+
year: Number(document.issuedAt.slice(0, 4)),
|
|
238
|
+
series: document.series,
|
|
239
|
+
from: document.number,
|
|
240
|
+
to: document.number,
|
|
241
|
+
reason: ctx.config.reasons.inutilization
|
|
242
|
+
});
|
|
243
|
+
if (!outcome.ok) return defer(ctx, document, "the inutilization", outcome.error);
|
|
244
|
+
const xml = outcome.answer.inutilizationXml;
|
|
245
|
+
const eventXmlKey = xml === null ? null : xmlKeys.inutilization(document);
|
|
246
|
+
if (eventXmlKey !== null) await ctx.config.storage.put(eventXmlKey, xml ?? "", "application/xml");
|
|
247
|
+
return ctx.advance(document, { kind: "INUTILIZE", answer: outcome.answer, eventXmlKey });
|
|
248
|
+
}, "inutilizeOwed");
|
|
249
|
+
var SETTLE = {
|
|
250
|
+
LOOKUP_FIRST: lookupFirst,
|
|
251
|
+
CANCEL: cancelOwed,
|
|
252
|
+
INUTILIZE: inutilizeOwed
|
|
253
|
+
};
|
|
254
|
+
async function settleNumber(ctx, document, profile, signing) {
|
|
255
|
+
const settle = document.numberVoid === null ? void 0 : SETTLE[document.numberVoid];
|
|
256
|
+
return settle === void 0 ? document : settle(ctx, document, profile, signing);
|
|
257
|
+
}
|
|
258
|
+
__name(settleNumber, "settleNumber");
|
|
259
|
+
|
|
260
|
+
// src/documents/steps.ts
|
|
261
|
+
var FINAL_FAILURES = /* @__PURE__ */ new Set(["REJECTED", "INVALID", "INTERNAL"]);
|
|
262
|
+
async function reject(ctx, document, error) {
|
|
263
|
+
const rejected = await ctx.advance(document, { kind: "REJECT", error });
|
|
264
|
+
await ctx.config.notify.emit({
|
|
265
|
+
type: FISCAL_DOCUMENT_REJECTED,
|
|
266
|
+
recipient: { tenantId: document.ownerId, permission: FISCAL_ISSUE },
|
|
267
|
+
payload: {
|
|
268
|
+
documentId: document.id,
|
|
269
|
+
subjectId: document.subjectId,
|
|
270
|
+
model: document.model,
|
|
271
|
+
series: document.series,
|
|
272
|
+
number: document.number,
|
|
273
|
+
code: error.code,
|
|
274
|
+
reason: error.message
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
return rejected;
|
|
278
|
+
}
|
|
279
|
+
__name(reject, "reject");
|
|
280
|
+
async function accept(ctx, document, answer) {
|
|
281
|
+
const xmlKey = xmlKeys.authorized(answer.accessKey);
|
|
282
|
+
await ctx.config.storage.put(xmlKey, answer.authorizedXml, "application/xml");
|
|
283
|
+
return ctx.advance(document, { kind: answer.status === "AUTHORIZED" ? "AUTHORIZE" : "DENY", answer, xmlKey });
|
|
284
|
+
}
|
|
285
|
+
__name(accept, "accept");
|
|
286
|
+
function canGoOffline(document, point) {
|
|
287
|
+
return document.model === "NFCE" && document.seriesKind === "ONLINE" && point.contingencySeries !== null;
|
|
288
|
+
}
|
|
289
|
+
__name(canGoOffline, "canGoOffline");
|
|
290
|
+
function pastOnlineTolerance(ctx, document) {
|
|
291
|
+
return ctx.config.now().getTime() - Date.parse(document.createdAt) > ctx.config.nfceOnlineToleranceMs;
|
|
292
|
+
}
|
|
293
|
+
__name(pastOnlineTolerance, "pastOnlineTolerance");
|
|
294
|
+
async function signOffline(ctx, document, profile, signing) {
|
|
295
|
+
const contingency = { since: await ctx.localNow(profile.ownerId), reason: ctx.config.reasons.contingency };
|
|
296
|
+
const outcome = await ctx.config.issuer.signContingency({ environment: document.environment, signing, document: document.sale, contingency });
|
|
297
|
+
if (!outcome.ok) return { document, error: outcome.error };
|
|
298
|
+
const xmlKey = xmlKeys.signed(outcome.answer.accessKey);
|
|
299
|
+
await ctx.config.storage.put(xmlKey, outcome.answer.signedXml, "application/xml");
|
|
300
|
+
return { document: await ctx.advance(document, { kind: "SIGN_OFFLINE", answer: outcome.answer, contingency, xmlKey }), error: null };
|
|
301
|
+
}
|
|
302
|
+
__name(signOffline, "signOffline");
|
|
303
|
+
async function signPending(ctx, document, profile, signing) {
|
|
304
|
+
const signed = await signOffline(ctx, document, profile, signing);
|
|
305
|
+
if (signed.error === null) return signed.document;
|
|
306
|
+
return ctx.advance(document, {
|
|
307
|
+
kind: "DEFER",
|
|
308
|
+
reason: "signing offline failed",
|
|
309
|
+
error: signed.error,
|
|
310
|
+
// Signing is local: a certificate that does not open (AUTH) will not open on the next try either.
|
|
311
|
+
attention: FINAL_FAILURES.has(signed.error.class) || signed.error.class === "AUTH"
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
__name(signPending, "signPending");
|
|
315
|
+
async function goOffline(ctx, document, profile, point, signing) {
|
|
316
|
+
const offline = await ctx.createNumbered({
|
|
317
|
+
profile,
|
|
318
|
+
point,
|
|
319
|
+
subjectId: document.subjectId,
|
|
320
|
+
model: document.model,
|
|
321
|
+
seriesKind: "CONTINGENCY",
|
|
322
|
+
draft: draftOf(document.sale),
|
|
323
|
+
replacing: document
|
|
324
|
+
});
|
|
325
|
+
return signPending(ctx, offline, profile, signing);
|
|
326
|
+
}
|
|
327
|
+
__name(goOffline, "goOffline");
|
|
328
|
+
async function keepSigned(ctx, document, error) {
|
|
329
|
+
const key = document.accessKey ?? error.accessKey;
|
|
330
|
+
const digest = error.signedXml === null ? null : digestOf(error.signedXml);
|
|
331
|
+
if (error.signedXml === null || key === null || digest === null) return {};
|
|
332
|
+
const xmlKey = xmlKeys.signedByDigest(key, digest);
|
|
333
|
+
await ctx.config.storage.put(xmlKey, error.signedXml, "application/xml");
|
|
334
|
+
return { xmlKey };
|
|
335
|
+
}
|
|
336
|
+
__name(keepSigned, "keepSigned");
|
|
337
|
+
function staleOnline(ctx, document, point) {
|
|
338
|
+
const knownToSefaz = document.status === "SUBMITTED" && document.protocol !== null;
|
|
339
|
+
return !knownToSefaz && canGoOffline(document, point) && pastOnlineTolerance(ctx, document);
|
|
340
|
+
}
|
|
341
|
+
__name(staleOnline, "staleOnline");
|
|
342
|
+
async function submit(ctx, document, profile, point, signing) {
|
|
343
|
+
if (staleOnline(ctx, document, point)) return goOffline(ctx, document, profile, point, signing);
|
|
344
|
+
const sent = document.status === "PENDING" ? await ctx.advance(document, { kind: "SUBMIT" }) : document;
|
|
345
|
+
const outcome = await ctx.config.issuer.issue({ model: sent.model, environment: sent.environment, signing, document: sent.sale });
|
|
346
|
+
if (outcome.ok) return accept(ctx, sent, outcome.answer);
|
|
347
|
+
if (FINAL_FAILURES.has(outcome.error.class)) return reject(ctx, sent, outcome.error);
|
|
348
|
+
const retried = await ctx.advance(sent, { kind: "RETRY", error: outcome.error, ...await keepSigned(ctx, sent, outcome.error) });
|
|
349
|
+
return outcome.error.class === "CONTINGENCY" && canGoOffline(retried, point) ? goOffline(ctx, retried, profile, point, signing) : retried;
|
|
350
|
+
}
|
|
351
|
+
__name(submit, "submit");
|
|
352
|
+
async function transmit(ctx, document, signing) {
|
|
353
|
+
const signedXml = document.xmlKey === null ? null : await ctx.config.storage.get(document.xmlKey);
|
|
354
|
+
if (signedXml === null) throw new FiscalDocumentError("NOT_FOUND", `document ${document.id} has no signed XML in storage.`);
|
|
355
|
+
const outcome = await ctx.config.issuer.transmit({ model: document.model, environment: document.environment, signing, signedXml });
|
|
356
|
+
if (outcome.ok) return accept(ctx, document, outcome.answer);
|
|
357
|
+
if (FINAL_FAILURES.has(outcome.error.class)) return reject(ctx, document, outcome.error);
|
|
358
|
+
return ctx.advance(document, { kind: "RETRY", error: outcome.error });
|
|
359
|
+
}
|
|
360
|
+
__name(transmit, "transmit");
|
|
361
|
+
|
|
362
|
+
// src/documents/service.ts
|
|
363
|
+
var CONTINGENCY_WARNING_AFTER_MS = 20 * 36e5;
|
|
364
|
+
var NEEDS_A_PERSON = /* @__PURE__ */ new Set(["NOT_SUPPORTED", "NOT_ISSUABLE", "NOT_FOUND", "INVALID_INPUT", "SERIES_EXHAUSTED"]);
|
|
365
|
+
async function issuable({ ctx }, ownerId, issuingPointId, model) {
|
|
366
|
+
const profile = await ctx.requireProfile(ownerId);
|
|
367
|
+
if (profile.documentPolicy !== "ISSUED_HERE") {
|
|
368
|
+
throw new FiscalDocumentError("NOT_ISSUABLE", `owner ${ownerId}'s documentPolicy is ${profile.documentPolicy}.`);
|
|
369
|
+
}
|
|
370
|
+
const point = await ctx.requirePoint(ownerId, issuingPointId);
|
|
371
|
+
if (point.model !== model) throw new FiscalDocumentError("INVALID_INPUT", `issuing point ${point.id} issues ${point.model}, not ${model}.`);
|
|
372
|
+
return { profile, point };
|
|
373
|
+
}
|
|
374
|
+
__name(issuable, "issuable");
|
|
375
|
+
async function liveDocument({ config }, input) {
|
|
376
|
+
const live = (await config.store.listBySubject(input.ownerId, input.subjectId, input.model)).filter(isLive);
|
|
377
|
+
return live[live.length - 1] ?? null;
|
|
378
|
+
}
|
|
379
|
+
__name(liveDocument, "liveDocument");
|
|
380
|
+
async function requireDocument({ config }, ownerId, documentId) {
|
|
381
|
+
const document = await config.store.getDocument(ownerId, documentId);
|
|
382
|
+
if (document === null) throw new FiscalDocumentError("NOT_FOUND", `owner ${ownerId} has no document ${documentId}.`);
|
|
383
|
+
return document;
|
|
384
|
+
}
|
|
385
|
+
__name(requireDocument, "requireDocument");
|
|
386
|
+
async function numberOrExisting(deps, input, create) {
|
|
387
|
+
try {
|
|
388
|
+
return { document: await create(), created: true };
|
|
389
|
+
} catch (error) {
|
|
390
|
+
if (!(error instanceof FiscalDocumentError) || error.code !== "SUBJECT_HAS_DOCUMENT") throw error;
|
|
391
|
+
const existing = await liveDocument(deps, input);
|
|
392
|
+
if (existing === null) throw error;
|
|
393
|
+
return { document: existing, created: false };
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
__name(numberOrExisting, "numberOrExisting");
|
|
397
|
+
async function issue(deps, input) {
|
|
398
|
+
const { profile, point } = await issuable(deps, input.ownerId, input.issuingPointId, input.model);
|
|
399
|
+
const existing = await liveDocument(deps, input);
|
|
400
|
+
if (existing !== null) return existing;
|
|
401
|
+
const signing = await deps.ctx.material(profile);
|
|
402
|
+
const draft = await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: input.subjectId, model: input.model });
|
|
403
|
+
const numbered = await numberOrExisting(
|
|
404
|
+
deps,
|
|
405
|
+
input,
|
|
406
|
+
() => deps.ctx.createNumbered({ profile, point, subjectId: input.subjectId, model: input.model, seriesKind: "ONLINE", draft })
|
|
407
|
+
);
|
|
408
|
+
return numbered.created ? submit(deps.ctx, numbered.document, profile, point, signing) : numbered.document;
|
|
409
|
+
}
|
|
410
|
+
__name(issue, "issue");
|
|
411
|
+
async function issueOffline(deps, input) {
|
|
412
|
+
const target = { ...input, model: "NFCE" };
|
|
413
|
+
const { profile, point } = await issuable(deps, input.ownerId, input.issuingPointId, "NFCE");
|
|
414
|
+
const existing = await liveDocument(deps, target);
|
|
415
|
+
if (existing !== null) return existing;
|
|
416
|
+
const signing = await deps.ctx.material(profile);
|
|
417
|
+
const draft = await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: input.subjectId, model: "NFCE" });
|
|
418
|
+
const numbered = await numberOrExisting(
|
|
419
|
+
deps,
|
|
420
|
+
target,
|
|
421
|
+
() => deps.ctx.createNumbered({ profile, point, subjectId: input.subjectId, model: "NFCE", seriesKind: "CONTINGENCY", draft })
|
|
422
|
+
);
|
|
423
|
+
return numbered.created ? signPending(deps.ctx, numbered.document, profile, signing) : numbered.document;
|
|
424
|
+
}
|
|
425
|
+
__name(issueOffline, "issueOffline");
|
|
426
|
+
function printedFieldsChange(document, totals, buyerTaxId) {
|
|
427
|
+
return totals.totalCents !== document.totals.totalCents || buyerTaxId !== document.buyerTaxId;
|
|
428
|
+
}
|
|
429
|
+
__name(printedFieldsChange, "printedFieldsChange");
|
|
430
|
+
async function resendContingency(deps, input) {
|
|
431
|
+
const document = await requireDocument(deps, input.ownerId, input.documentId);
|
|
432
|
+
if (document.status !== "REJECTED" || document.seriesKind !== "CONTINGENCY" || document.contingency === null) {
|
|
433
|
+
throw new FiscalDocumentError("TRANSITION_REFUSED", `document ${document.id} is not a rejected contingency NFC-e.`);
|
|
434
|
+
}
|
|
435
|
+
const profile = await deps.ctx.requireProfile(input.ownerId);
|
|
436
|
+
const draft = await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: document.subjectId, model: document.model });
|
|
437
|
+
const totals = totalsOf(draft);
|
|
438
|
+
const buyerTaxId = draft.buyer?.document.number ?? null;
|
|
439
|
+
if (printedFieldsChange(document, totals, buyerTaxId)) {
|
|
440
|
+
throw new FiscalDocumentError(
|
|
441
|
+
"RESEND_CHANGES_PRINTED_FIELDS",
|
|
442
|
+
`the correction changes document ${document.id}'s total or buyer, which its DANFE prints: issue a new note.`
|
|
443
|
+
);
|
|
444
|
+
}
|
|
445
|
+
const sale = { ...draft, series: document.series, number: document.number, keyCode: document.keyCode, issuedAt: document.issuedAt, issuer: issuerOf(profile) };
|
|
446
|
+
const outcome = await deps.config.issuer.signContingency({
|
|
447
|
+
environment: document.environment,
|
|
448
|
+
signing: await deps.ctx.material(profile),
|
|
449
|
+
document: sale,
|
|
450
|
+
contingency: document.contingency
|
|
451
|
+
});
|
|
452
|
+
if (!outcome.ok) throw new FiscalDocumentError("NOT_ISSUABLE", `the corrected sale could not be signed: ${outcome.error.class} ${outcome.error.code ?? ""}`.trim());
|
|
453
|
+
const xmlKey = xmlKeys.signed(outcome.answer.accessKey);
|
|
454
|
+
await deps.config.storage.put(xmlKey, outcome.answer.signedXml, "application/xml");
|
|
455
|
+
return deps.ctx.advance(document, { kind: "RESIGN", answer: outcome.answer, sale, totals, buyerTaxId, xmlKey });
|
|
456
|
+
}
|
|
457
|
+
__name(resendContingency, "resendContingency");
|
|
458
|
+
async function cancel(deps, input) {
|
|
459
|
+
assertReason(input.reason, "reason");
|
|
460
|
+
const document = await requireDocument(deps, input.ownerId, input.documentId);
|
|
461
|
+
if (document.status !== "AUTHORIZED" || document.accessKey === null || document.protocol === null) {
|
|
462
|
+
throw new FiscalDocumentError("TRANSITION_REFUSED", `document ${document.id} is ${document.status}; only an authorised document is cancelled.`);
|
|
463
|
+
}
|
|
464
|
+
const profile = await deps.ctx.requireProfile(input.ownerId);
|
|
465
|
+
const outcome = await deps.config.issuer.cancel({
|
|
466
|
+
model: document.model,
|
|
467
|
+
environment: document.environment,
|
|
468
|
+
signing: await deps.ctx.material(profile),
|
|
469
|
+
accessKey: document.accessKey,
|
|
470
|
+
protocol: document.protocol,
|
|
471
|
+
reason: input.reason
|
|
472
|
+
});
|
|
473
|
+
if (!outcome.ok) return { document, failure: outcome.error };
|
|
474
|
+
const eventXmlKey = outcome.answer.eventXml === null ? null : xmlKeys.cancel(document.accessKey);
|
|
475
|
+
if (eventXmlKey !== null) await deps.config.storage.put(eventXmlKey, outcome.answer.eventXml ?? "", "application/xml");
|
|
476
|
+
const cancelled = await deps.ctx.advance(document, { kind: "CANCEL", answer: outcome.answer, reason: input.reason, eventXmlKey });
|
|
477
|
+
return { document: cancelled, failure: null };
|
|
478
|
+
}
|
|
479
|
+
__name(cancel, "cancel");
|
|
480
|
+
function lookupMoves(document) {
|
|
481
|
+
if (!canTransition(document.status, "LOOKUP")) return false;
|
|
482
|
+
if (document.status === "REPLACED" || document.status === "REJECTED") return document.numberVoid === "LOOKUP_FIRST";
|
|
483
|
+
return true;
|
|
484
|
+
}
|
|
485
|
+
__name(lookupMoves, "lookupMoves");
|
|
486
|
+
async function lookup(deps, input) {
|
|
487
|
+
const document = await requireDocument(deps, input.ownerId, input.documentId);
|
|
488
|
+
if (document.accessKey === null) throw new FiscalDocumentError("NOT_FOUND", `document ${document.id} has no access key yet.`);
|
|
489
|
+
const profile = await deps.ctx.requireProfile(input.ownerId);
|
|
490
|
+
const outcome = await deps.config.issuer.lookup({
|
|
491
|
+
model: document.model,
|
|
492
|
+
environment: document.environment,
|
|
493
|
+
signing: await deps.ctx.material(profile),
|
|
494
|
+
accessKey: document.accessKey
|
|
495
|
+
});
|
|
496
|
+
if (!outcome.ok) return { document, answer: null, failure: outcome.error };
|
|
497
|
+
if (!lookupMoves(document)) return { document, answer: outcome.answer, failure: null };
|
|
498
|
+
const xmlKey = document.status === "SUBMITTED" ? await storeNfeProc(deps.ctx, document, outcome.answer) : void 0;
|
|
499
|
+
const looked = await deps.ctx.advance(document, { kind: "LOOKUP", answer: outcome.answer, ...xmlKey === void 0 ? {} : { xmlKey } });
|
|
500
|
+
const after = document.status === "REJECTED" ? await settleWithXml(deps.ctx, looked, outcome.answer) : looked;
|
|
501
|
+
return { document: after, answer: outcome.answer, failure: null };
|
|
502
|
+
}
|
|
503
|
+
__name(lookup, "lookup");
|
|
504
|
+
async function step({ ctx }, document) {
|
|
505
|
+
const profile = await ctx.requireProfile(document.ownerId);
|
|
506
|
+
const signing = await ctx.material(profile);
|
|
507
|
+
if (document.numberVoid !== null) return settleNumber(ctx, document, profile, signing);
|
|
508
|
+
if (document.status === "CONTINGENCY") return transmit(ctx, document, signing);
|
|
509
|
+
if (document.seriesKind === "CONTINGENCY") return signPending(ctx, document, profile, signing);
|
|
510
|
+
const point = await ctx.requirePoint(document.ownerId, document.issuingPointId);
|
|
511
|
+
return submit(ctx, document, profile, point, signing);
|
|
512
|
+
}
|
|
513
|
+
__name(step, "step");
|
|
514
|
+
async function deferThrown(deps, document, error) {
|
|
515
|
+
if (error instanceof FiscalDocumentError && error.code === "CONFLICT") return;
|
|
516
|
+
const attention = error instanceof FiscalDocumentError && NEEDS_A_PERSON.has(error.code);
|
|
517
|
+
const reason = error instanceof Error ? error.message : "unknown failure";
|
|
518
|
+
const current = await deps.config.store.getDocument(document.ownerId, document.id) ?? document;
|
|
519
|
+
await deps.ctx.advance(current, { kind: "DEFER", reason, error: null, attention }).catch(() => void 0);
|
|
520
|
+
}
|
|
521
|
+
__name(deferThrown, "deferThrown");
|
|
522
|
+
async function run(deps, documents) {
|
|
523
|
+
const report = { advanced: [], failures: [] };
|
|
524
|
+
for (const document of documents) {
|
|
525
|
+
try {
|
|
526
|
+
const after = await step(deps, document);
|
|
527
|
+
report.advanced.push({ documentId: after.id, status: after.status });
|
|
528
|
+
} catch (error) {
|
|
529
|
+
report.failures.push({ documentId: document.id, message: error instanceof Error ? error.message : "unknown failure" });
|
|
530
|
+
await deferThrown(deps, document, error);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
return report;
|
|
534
|
+
}
|
|
535
|
+
__name(run, "run");
|
|
536
|
+
async function warnContingencyDeadlines(deps, limit) {
|
|
537
|
+
const signedBefore = new Date(deps.config.now().getTime() - CONTINGENCY_WARNING_AFTER_MS).toISOString();
|
|
538
|
+
const due = await deps.config.store.listContingencyDeadline({ signedBefore, limit });
|
|
539
|
+
for (const document of due) {
|
|
540
|
+
const warned = await deps.ctx.advance(document, { kind: "WARN" });
|
|
541
|
+
await deps.config.notify.emit({
|
|
542
|
+
type: FISCAL_CONTINGENCY_DEADLINE,
|
|
543
|
+
recipient: { tenantId: document.ownerId, permission: FISCAL_ISSUE },
|
|
544
|
+
payload: { documentId: warned.id, subjectId: warned.subjectId, series: warned.series, number: warned.number, since: warned.contingency?.since ?? "" }
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
return due.length;
|
|
548
|
+
}
|
|
549
|
+
__name(warnContingencyDeadlines, "warnContingencyDeadlines");
|
|
550
|
+
function createFiscalDocuments(config) {
|
|
551
|
+
assertConfig(config);
|
|
552
|
+
if (typeof config.cipher?.encrypt !== "function") throw new TypeError("createFiscalDocuments needs cipher.");
|
|
553
|
+
if (typeof config.readCertificate !== "function") throw new TypeError("createFiscalDocuments needs readCertificate.");
|
|
554
|
+
const deps = { ctx: new FiscalContext(config), config };
|
|
555
|
+
const { store } = config;
|
|
556
|
+
return {
|
|
557
|
+
getProfile: /* @__PURE__ */ __name((ownerId) => store.getProfile(ownerId), "getProfile"),
|
|
558
|
+
saveProfile: saveProfile.bind(null, deps),
|
|
559
|
+
uploadCertificate: uploadCertificate.bind(null, deps),
|
|
560
|
+
listIssuingPoints: /* @__PURE__ */ __name((ownerId) => store.listIssuingPoints(ownerId), "listIssuingPoints"),
|
|
561
|
+
createIssuingPoint: createIssuingPoint.bind(null, deps),
|
|
562
|
+
/** Issue the subject's document, or answer the live one it has. A rejection is final; anything SEFAZ may still answer is the sweep's. */
|
|
563
|
+
issue: issue.bind(null, deps),
|
|
564
|
+
issueOffline: issueOffline.bind(null, deps),
|
|
565
|
+
resendContingency: resendContingency.bind(null, deps),
|
|
566
|
+
/** Cancel an authorised document. A refusal (late, say) answers the issuer's failure and changes nothing. */
|
|
567
|
+
cancel: cancel.bind(null, deps),
|
|
568
|
+
/** Ask SEFAZ what it knows of the key; a state the answer moves is recorded. */
|
|
569
|
+
lookup: lookup.bind(null, deps),
|
|
570
|
+
/** A person takes a document back from `attention`; the sweep tries it again. */
|
|
571
|
+
async release(input) {
|
|
572
|
+
return deps.ctx.advance(await requireDocument(deps, input.ownerId, input.documentId), { kind: "RELEASE" });
|
|
573
|
+
},
|
|
574
|
+
getDocument: requireDocument.bind(null, deps),
|
|
575
|
+
listBySubject: /* @__PURE__ */ __name((ownerId, subjectId, model) => store.listBySubject(ownerId, subjectId, model), "listBySubject"),
|
|
576
|
+
async listEvents(ownerId, documentId) {
|
|
577
|
+
await requireDocument(deps, ownerId, documentId);
|
|
578
|
+
return store.listEvents(documentId);
|
|
579
|
+
},
|
|
580
|
+
/** One pass of the retry sweep: PENDING/SUBMITTED documents and owed numbers whose next attempt has come. */
|
|
581
|
+
sweep: /* @__PURE__ */ __name(async (limit) => run(deps, await store.listDue({ now: deps.ctx.nowIso(), limit })), "sweep"),
|
|
582
|
+
/** One pass of the contingency transmission, then the 20-hour deadline warnings. */
|
|
583
|
+
async transmitContingency(limit) {
|
|
584
|
+
const report = await run(deps, await store.listContingency({ now: deps.ctx.nowIso(), limit }));
|
|
585
|
+
await warnContingencyDeadlines(deps, limit);
|
|
586
|
+
return report;
|
|
587
|
+
}
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
__name(createFiscalDocuments, "createFiscalDocuments");
|
|
591
|
+
|
|
592
|
+
// src/documents/memory.ts
|
|
593
|
+
var MAX_NUMBER = 999999999;
|
|
594
|
+
function counterKey(request) {
|
|
595
|
+
return `${request.issuerCnpj}|${request.environment}|${request.model}|${request.series}`;
|
|
596
|
+
}
|
|
597
|
+
__name(counterKey, "counterKey");
|
|
598
|
+
function openCounter(state, point, issuerCnpj, series, first) {
|
|
599
|
+
for (const environment of ["homologacao", "producao"]) {
|
|
600
|
+
const key = counterKey({ issuerCnpj, environment, model: point.model, series });
|
|
601
|
+
const owner = state.seriesOwner.get(key);
|
|
602
|
+
if (owner !== void 0 && owner !== point.id) {
|
|
603
|
+
throw new FiscalDocumentError("INVALID_INPUT", `series ${series} already belongs to issuing point ${owner}.`);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
for (const environment of ["homologacao", "producao"]) {
|
|
607
|
+
const key = counterKey({ issuerCnpj, environment, model: point.model, series });
|
|
608
|
+
state.seriesOwner.set(key, point.id);
|
|
609
|
+
state.counters.set(key, first);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
__name(openCounter, "openCounter");
|
|
613
|
+
function isDue(document, now) {
|
|
614
|
+
if (document.attention || document.nextAttemptAt === null || document.nextAttemptAt > now) return false;
|
|
615
|
+
return document.status === "PENDING" || document.status === "SUBMITTED" || OWED_VOIDS.includes(document.numberVoid ?? "INUTILIZED");
|
|
616
|
+
}
|
|
617
|
+
__name(isDue, "isDue");
|
|
618
|
+
function save(state, previous, transition2) {
|
|
619
|
+
const stored = state.documents.get(previous.id);
|
|
620
|
+
if (stored === void 0 || stored.updatedAt !== previous.updatedAt || stored.status !== previous.status) return false;
|
|
621
|
+
state.documents.set(transition2.document.id, transition2.document);
|
|
622
|
+
state.events.push(transition2.event);
|
|
623
|
+
return true;
|
|
624
|
+
}
|
|
625
|
+
__name(save, "save");
|
|
626
|
+
function hasLive(state, document) {
|
|
627
|
+
return [...state.documents.values()].some(
|
|
628
|
+
(other) => other.ownerId === document.ownerId && other.subjectId === document.subjectId && other.model === document.model && isLive(other)
|
|
629
|
+
);
|
|
630
|
+
}
|
|
631
|
+
__name(hasLive, "hasLive");
|
|
632
|
+
function createMemoryFiscalStore() {
|
|
633
|
+
const profiles = /* @__PURE__ */ new Map();
|
|
634
|
+
const points = /* @__PURE__ */ new Map();
|
|
635
|
+
const state = { counters: /* @__PURE__ */ new Map(), seriesOwner: /* @__PURE__ */ new Map(), documents: /* @__PURE__ */ new Map(), events: [] };
|
|
636
|
+
const ordered = /* @__PURE__ */ __name((key) => [...state.documents.values()].sort((a, b) => key(a).localeCompare(key(b))), "ordered");
|
|
637
|
+
return {
|
|
638
|
+
events: state.events,
|
|
639
|
+
counters: state.counters,
|
|
640
|
+
getProfile: /* @__PURE__ */ __name(async (ownerId) => profiles.get(ownerId) ?? null, "getProfile"),
|
|
641
|
+
saveProfile: /* @__PURE__ */ __name(async (profile) => void profiles.set(profile.ownerId, profile), "saveProfile"),
|
|
642
|
+
async getIssuingPoint(ownerId, id) {
|
|
643
|
+
const point = points.get(id);
|
|
644
|
+
return point?.ownerId === ownerId ? point : null;
|
|
645
|
+
},
|
|
646
|
+
listIssuingPoints: /* @__PURE__ */ __name(async (ownerId) => [...points.values()].filter((point) => point.ownerId === ownerId), "listIssuingPoints"),
|
|
647
|
+
async createIssuingPoint(point, issuerCnpj, firstNumber) {
|
|
648
|
+
if (points.has(point.id)) throw new FiscalDocumentError("INVALID_INPUT", `issuing point ${point.id} exists.`);
|
|
649
|
+
openCounter(state, point, issuerCnpj, point.onlineSeries, firstNumber.online);
|
|
650
|
+
if (point.contingencySeries !== null) openCounter(state, point, issuerCnpj, point.contingencySeries, firstNumber.contingency);
|
|
651
|
+
points.set(point.id, point);
|
|
652
|
+
},
|
|
653
|
+
async createDocument(request, build, replace) {
|
|
654
|
+
const key = counterKey(request);
|
|
655
|
+
const number = state.counters.get(key);
|
|
656
|
+
if (number === void 0 || state.seriesOwner.get(key) !== request.issuingPointId) {
|
|
657
|
+
throw new FiscalDocumentError("NOT_FOUND", `no counter for series ${request.series} on issuing point ${request.issuingPointId}.`);
|
|
658
|
+
}
|
|
659
|
+
if (number > MAX_NUMBER) throw new FiscalDocumentError("SERIES_EXHAUSTED", `series ${request.series} has no number left.`);
|
|
660
|
+
const document = build(number);
|
|
661
|
+
if (state.documents.has(document.id)) throw new FiscalDocumentError("INVALID_INPUT", `document ${document.id} exists.`);
|
|
662
|
+
const snapshot = new Map(state.documents);
|
|
663
|
+
if (replace !== void 0 && !save(state, replace.previous, replace.transition)) {
|
|
664
|
+
throw new FiscalDocumentError("CONFLICT", `document ${replace.previous.id} moved before it was replaced.`);
|
|
665
|
+
}
|
|
666
|
+
if (hasLive(state, document)) {
|
|
667
|
+
state.documents.clear();
|
|
668
|
+
for (const [id, kept] of snapshot) state.documents.set(id, kept);
|
|
669
|
+
if (replace !== void 0) state.events.pop();
|
|
670
|
+
throw new FiscalDocumentError("SUBJECT_HAS_DOCUMENT", `subject ${document.subjectId} already has a live ${document.model}.`);
|
|
671
|
+
}
|
|
672
|
+
state.counters.set(key, number + 1);
|
|
673
|
+
state.documents.set(document.id, document);
|
|
674
|
+
return document;
|
|
675
|
+
},
|
|
676
|
+
async getDocument(ownerId, id) {
|
|
677
|
+
const document = state.documents.get(id);
|
|
678
|
+
return document?.ownerId === ownerId ? document : null;
|
|
679
|
+
},
|
|
680
|
+
listBySubject: /* @__PURE__ */ __name(async (ownerId, subjectId, model) => ordered((d) => d.createdAt).filter((d) => d.ownerId === ownerId && d.subjectId === subjectId && d.model === model), "listBySubject"),
|
|
681
|
+
listEvents: /* @__PURE__ */ __name(async (documentId) => state.events.filter((event) => event.documentId === documentId), "listEvents"),
|
|
682
|
+
saveTransition: /* @__PURE__ */ __name(async (previous, transition2) => save(state, previous, transition2), "saveTransition"),
|
|
683
|
+
listDue: /* @__PURE__ */ __name(async ({ now, limit }) => ordered((d) => d.nextAttemptAt ?? "").filter((document) => isDue(document, now)).slice(0, limit), "listDue"),
|
|
684
|
+
listContingency: /* @__PURE__ */ __name(async ({ now, limit }) => ordered((d) => d.nextAttemptAt ?? "").filter((d) => d.status === "CONTINGENCY" && !d.attention && d.nextAttemptAt !== null && d.nextAttemptAt <= now).slice(0, limit), "listContingency"),
|
|
685
|
+
listContingencyDeadline: /* @__PURE__ */ __name(async ({ signedBefore, limit }) => ordered((d) => d.createdAt).filter((d) => d.status === "CONTINGENCY" && d.deadlineWarnedAt === null && Date.parse(d.contingency?.since ?? "") < Date.parse(signedBefore)).slice(0, limit), "listContingencyDeadline"),
|
|
686
|
+
listExpiringCertificates: /* @__PURE__ */ __name(async (before) => [...profiles.values()].filter((p) => p.certificateExpiresAt !== null && p.certificateExpiresAt < before), "listExpiringCertificates")
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
__name(createMemoryFiscalStore, "createMemoryFiscalStore");
|
|
690
|
+
|
|
691
|
+
// src/documents/sql.ts
|
|
692
|
+
var FISCAL_NEXT_NUMBER_SQL = `UPDATE "fiscal_number_counters"
|
|
693
|
+
SET "next_number" = "next_number" + 1, "updated_at" = CURRENT_TIMESTAMP
|
|
694
|
+
WHERE "issuer_cnpj" = $1 AND "environment" = $2 AND "model" = $3 AND "series" = $4 AND "issuing_point_id" = $5
|
|
695
|
+
RETURNING "next_number" - 1 AS "number"`;
|
|
696
|
+
|
|
697
|
+
// src/documents/sql-rows.ts
|
|
698
|
+
function iso(value) {
|
|
699
|
+
if (value === null || value === void 0) return null;
|
|
700
|
+
const date = value instanceof Date ? value : /* @__PURE__ */ new Date(`${String(value).replace(" ", "T")}${/Z|[+-]\d{2}:?\d{2}$/.test(String(value)) ? "" : "Z"}`);
|
|
701
|
+
return date.toISOString();
|
|
702
|
+
}
|
|
703
|
+
__name(iso, "iso");
|
|
704
|
+
function requiredIso(value) {
|
|
705
|
+
return iso(value) ?? "";
|
|
706
|
+
}
|
|
707
|
+
__name(requiredIso, "requiredIso");
|
|
708
|
+
function day(value) {
|
|
709
|
+
return value instanceof Date ? value.toISOString().slice(0, 10) : String(value).slice(0, 10);
|
|
710
|
+
}
|
|
711
|
+
__name(day, "day");
|
|
712
|
+
function json(value) {
|
|
713
|
+
return typeof value === "string" ? JSON.parse(value) : value;
|
|
714
|
+
}
|
|
715
|
+
__name(json, "json");
|
|
716
|
+
var text = /* @__PURE__ */ __name((value) => value === null || value === void 0 ? null : String(value), "text");
|
|
717
|
+
var DOCUMENT_COLUMNS = [
|
|
718
|
+
"id",
|
|
719
|
+
"owner_id",
|
|
720
|
+
"issuer_cnpj",
|
|
721
|
+
"subject_id",
|
|
722
|
+
"issuing_point_id",
|
|
723
|
+
"model",
|
|
724
|
+
"environment",
|
|
725
|
+
"series_kind",
|
|
726
|
+
"series",
|
|
727
|
+
"number",
|
|
728
|
+
"key_code",
|
|
729
|
+
"status",
|
|
730
|
+
"sale",
|
|
731
|
+
"totals",
|
|
732
|
+
"buyer_tax_id",
|
|
733
|
+
"access_key",
|
|
734
|
+
"protocol",
|
|
735
|
+
"status_code",
|
|
736
|
+
"status_reason",
|
|
737
|
+
"last_error_class",
|
|
738
|
+
"outcome_unknown",
|
|
739
|
+
"issued_at",
|
|
740
|
+
"authorized_at",
|
|
741
|
+
"contingency",
|
|
742
|
+
"cancelled_at",
|
|
743
|
+
"cancel_reason",
|
|
744
|
+
"cancel_protocol",
|
|
745
|
+
"replaced_by_id",
|
|
746
|
+
"number_void",
|
|
747
|
+
"xml_key",
|
|
748
|
+
"event_xml_key",
|
|
749
|
+
"attempts",
|
|
750
|
+
"failures",
|
|
751
|
+
"next_attempt_at",
|
|
752
|
+
"attention",
|
|
753
|
+
"deadline_warned_at",
|
|
754
|
+
"created_at",
|
|
755
|
+
"updated_at"
|
|
756
|
+
];
|
|
757
|
+
var JSON_COLUMNS = /* @__PURE__ */ new Set(["sale", "totals", "contingency"]);
|
|
758
|
+
var TIME_COLUMNS = /* @__PURE__ */ new Set(["next_attempt_at", "deadline_warned_at", "created_at", "updated_at"]);
|
|
759
|
+
function placeholder(column, index) {
|
|
760
|
+
if (JSON_COLUMNS.has(column)) return `$${index}::jsonb`;
|
|
761
|
+
if (TIME_COLUMNS.has(column)) return `$${index}::timestamp(3)`;
|
|
762
|
+
return `$${index}`;
|
|
763
|
+
}
|
|
764
|
+
__name(placeholder, "placeholder");
|
|
765
|
+
function documentValues(d) {
|
|
766
|
+
return [
|
|
767
|
+
d.id,
|
|
768
|
+
d.ownerId,
|
|
769
|
+
d.issuerCnpj,
|
|
770
|
+
d.subjectId,
|
|
771
|
+
d.issuingPointId,
|
|
772
|
+
d.model,
|
|
773
|
+
d.environment,
|
|
774
|
+
d.seriesKind,
|
|
775
|
+
d.series,
|
|
776
|
+
d.number,
|
|
777
|
+
d.keyCode,
|
|
778
|
+
d.status,
|
|
779
|
+
JSON.stringify(d.sale),
|
|
780
|
+
JSON.stringify(d.totals),
|
|
781
|
+
d.buyerTaxId,
|
|
782
|
+
d.accessKey,
|
|
783
|
+
d.protocol,
|
|
784
|
+
d.statusCode,
|
|
785
|
+
d.statusReason,
|
|
786
|
+
d.lastErrorClass,
|
|
787
|
+
d.outcomeUnknown,
|
|
788
|
+
d.issuedAt,
|
|
789
|
+
d.authorizedAt,
|
|
790
|
+
d.contingency === null ? null : JSON.stringify(d.contingency),
|
|
791
|
+
d.cancelledAt,
|
|
792
|
+
d.cancelReason,
|
|
793
|
+
d.cancelProtocol,
|
|
794
|
+
d.replacedById,
|
|
795
|
+
d.numberVoid,
|
|
796
|
+
d.xmlKey,
|
|
797
|
+
d.eventXmlKey,
|
|
798
|
+
d.attempts,
|
|
799
|
+
d.failures,
|
|
800
|
+
d.nextAttemptAt,
|
|
801
|
+
d.attention,
|
|
802
|
+
d.deadlineWarnedAt,
|
|
803
|
+
d.createdAt,
|
|
804
|
+
d.updatedAt
|
|
805
|
+
];
|
|
806
|
+
}
|
|
807
|
+
__name(documentValues, "documentValues");
|
|
808
|
+
function documentOf(row) {
|
|
809
|
+
return {
|
|
810
|
+
id: String(row["id"]),
|
|
811
|
+
ownerId: String(row["owner_id"]),
|
|
812
|
+
issuerCnpj: String(row["issuer_cnpj"]),
|
|
813
|
+
subjectId: String(row["subject_id"]),
|
|
814
|
+
issuingPointId: String(row["issuing_point_id"]),
|
|
815
|
+
model: row["model"],
|
|
816
|
+
environment: row["environment"],
|
|
817
|
+
seriesKind: row["series_kind"],
|
|
818
|
+
series: Number(row["series"]),
|
|
819
|
+
number: Number(row["number"]),
|
|
820
|
+
keyCode: String(row["key_code"]),
|
|
821
|
+
status: row["status"],
|
|
822
|
+
sale: json(row["sale"]),
|
|
823
|
+
totals: json(row["totals"]),
|
|
824
|
+
buyerTaxId: text(row["buyer_tax_id"]),
|
|
825
|
+
accessKey: text(row["access_key"]),
|
|
826
|
+
protocol: text(row["protocol"]),
|
|
827
|
+
statusCode: text(row["status_code"]),
|
|
828
|
+
statusReason: text(row["status_reason"]),
|
|
829
|
+
lastErrorClass: text(row["last_error_class"]),
|
|
830
|
+
outcomeUnknown: row["outcome_unknown"] === true,
|
|
831
|
+
issuedAt: String(row["issued_at"]),
|
|
832
|
+
authorizedAt: text(row["authorized_at"]),
|
|
833
|
+
contingency: row["contingency"] === null ? null : json(row["contingency"]),
|
|
834
|
+
cancelledAt: text(row["cancelled_at"]),
|
|
835
|
+
cancelReason: text(row["cancel_reason"]),
|
|
836
|
+
cancelProtocol: text(row["cancel_protocol"]),
|
|
837
|
+
replacedById: text(row["replaced_by_id"]),
|
|
838
|
+
numberVoid: text(row["number_void"]),
|
|
839
|
+
xmlKey: text(row["xml_key"]),
|
|
840
|
+
eventXmlKey: text(row["event_xml_key"]),
|
|
841
|
+
attempts: Number(row["attempts"]),
|
|
842
|
+
failures: Number(row["failures"]),
|
|
843
|
+
nextAttemptAt: iso(row["next_attempt_at"]),
|
|
844
|
+
attention: row["attention"] === true,
|
|
845
|
+
deadlineWarnedAt: iso(row["deadline_warned_at"]),
|
|
846
|
+
createdAt: requiredIso(row["created_at"]),
|
|
847
|
+
updatedAt: requiredIso(row["updated_at"])
|
|
848
|
+
};
|
|
849
|
+
}
|
|
850
|
+
__name(documentOf, "documentOf");
|
|
851
|
+
function eventOf(row) {
|
|
852
|
+
return {
|
|
853
|
+
documentId: String(row["document_id"]),
|
|
854
|
+
kind: row["kind"],
|
|
855
|
+
fromStatus: row["from_status"],
|
|
856
|
+
toStatus: row["to_status"],
|
|
857
|
+
at: requiredIso(row["at"]),
|
|
858
|
+
errorClass: text(row["error_class"]),
|
|
859
|
+
code: text(row["code"]),
|
|
860
|
+
answer: row["answer"] === null ? null : json(row["answer"])
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
__name(eventOf, "eventOf");
|
|
864
|
+
var PROFILE_COLUMNS = [
|
|
865
|
+
"owner_id",
|
|
866
|
+
"cnpj",
|
|
867
|
+
"state_registration",
|
|
868
|
+
"municipal_registration",
|
|
869
|
+
"cnae",
|
|
870
|
+
"legal_name",
|
|
871
|
+
"trade_name",
|
|
872
|
+
"tax_regime",
|
|
873
|
+
"regime",
|
|
874
|
+
"regime_effective_from",
|
|
875
|
+
"restaurant_regime",
|
|
876
|
+
"address",
|
|
877
|
+
"environment",
|
|
878
|
+
"document_policy",
|
|
879
|
+
"signing_identity",
|
|
880
|
+
"certificate_ciphertext",
|
|
881
|
+
"certificate_password_ciphertext",
|
|
882
|
+
"certificate_expires_at",
|
|
883
|
+
"csc_id",
|
|
884
|
+
"csc_ciphertext",
|
|
885
|
+
"consent_recorded_at",
|
|
886
|
+
"updated_at"
|
|
887
|
+
];
|
|
888
|
+
function profilePlaceholder(column, index) {
|
|
889
|
+
if (column === "address") return `$${index}::jsonb`;
|
|
890
|
+
if (column === "regime_effective_from") return `$${index}::date`;
|
|
891
|
+
if (column.endsWith("_at")) return `$${index}::timestamp(3)`;
|
|
892
|
+
return `$${index}`;
|
|
893
|
+
}
|
|
894
|
+
__name(profilePlaceholder, "profilePlaceholder");
|
|
895
|
+
function profileValues(p) {
|
|
896
|
+
return [
|
|
897
|
+
p.ownerId,
|
|
898
|
+
p.cnpj,
|
|
899
|
+
p.stateRegistration,
|
|
900
|
+
p.municipalRegistration,
|
|
901
|
+
p.cnae,
|
|
902
|
+
p.legalName,
|
|
903
|
+
p.tradeName,
|
|
904
|
+
p.taxRegime,
|
|
905
|
+
p.regime,
|
|
906
|
+
p.regimeEffectiveFrom,
|
|
907
|
+
p.restaurantRegime,
|
|
908
|
+
JSON.stringify(p.address),
|
|
909
|
+
p.environment,
|
|
910
|
+
p.documentPolicy,
|
|
911
|
+
p.signingIdentity,
|
|
912
|
+
p.certificateCiphertext,
|
|
913
|
+
p.certificatePasswordCiphertext,
|
|
914
|
+
p.certificateExpiresAt,
|
|
915
|
+
p.cscId,
|
|
916
|
+
p.cscCiphertext,
|
|
917
|
+
p.consentRecordedAt,
|
|
918
|
+
p.updatedAt
|
|
919
|
+
];
|
|
920
|
+
}
|
|
921
|
+
__name(profileValues, "profileValues");
|
|
922
|
+
function profileOf(row) {
|
|
923
|
+
return {
|
|
924
|
+
ownerId: String(row["owner_id"]),
|
|
925
|
+
cnpj: String(row["cnpj"]),
|
|
926
|
+
stateRegistration: String(row["state_registration"]),
|
|
927
|
+
municipalRegistration: text(row["municipal_registration"]),
|
|
928
|
+
cnae: text(row["cnae"]),
|
|
929
|
+
legalName: String(row["legal_name"]),
|
|
930
|
+
tradeName: text(row["trade_name"]),
|
|
931
|
+
taxRegime: row["tax_regime"],
|
|
932
|
+
regime: row["regime"],
|
|
933
|
+
regimeEffectiveFrom: day(row["regime_effective_from"]),
|
|
934
|
+
restaurantRegime: row["restaurant_regime"] === true,
|
|
935
|
+
address: json(row["address"]),
|
|
936
|
+
environment: row["environment"],
|
|
937
|
+
documentPolicy: row["document_policy"],
|
|
938
|
+
signingIdentity: row["signing_identity"],
|
|
939
|
+
certificateCiphertext: text(row["certificate_ciphertext"]),
|
|
940
|
+
certificatePasswordCiphertext: text(row["certificate_password_ciphertext"]),
|
|
941
|
+
certificateExpiresAt: iso(row["certificate_expires_at"]),
|
|
942
|
+
cscId: text(row["csc_id"]),
|
|
943
|
+
cscCiphertext: text(row["csc_ciphertext"]),
|
|
944
|
+
consentRecordedAt: iso(row["consent_recorded_at"]),
|
|
945
|
+
updatedAt: requiredIso(row["updated_at"])
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
__name(profileOf, "profileOf");
|
|
949
|
+
function pointOf(row) {
|
|
950
|
+
return {
|
|
951
|
+
id: String(row["id"]),
|
|
952
|
+
ownerId: String(row["owner_id"]),
|
|
953
|
+
model: row["model"],
|
|
954
|
+
onlineSeries: Number(row["online_series"]),
|
|
955
|
+
contingencySeries: row["contingency_series"] === null ? null : Number(row["contingency_series"]),
|
|
956
|
+
createdAt: requiredIso(row["created_at"])
|
|
957
|
+
};
|
|
958
|
+
}
|
|
959
|
+
__name(pointOf, "pointOf");
|
|
960
|
+
|
|
961
|
+
// src/documents/sql-store.ts
|
|
962
|
+
var rows = /* @__PURE__ */ __name((client, query, ...values) => client.$queryRawUnsafe(query, ...values), "rows");
|
|
963
|
+
var INSERT_DOCUMENT = `INSERT INTO "fiscal_documents" (${DOCUMENT_COLUMNS.map((c) => `"${c}"`).join(", ")})
|
|
964
|
+
VALUES (${DOCUMENT_COLUMNS.map((c, i) => placeholder(c, i + 1)).join(", ")})`;
|
|
965
|
+
var MUTABLE = DOCUMENT_COLUMNS.filter((c) => c !== "id" && c !== "created_at");
|
|
966
|
+
var UPDATE_DOCUMENT = [
|
|
967
|
+
`UPDATE "fiscal_documents" SET ${MUTABLE.map((c, i) => `"${c}" = ${placeholder(c, i + 2)}`).join(", ")}`,
|
|
968
|
+
`WHERE "id" = $1 AND "updated_at" = $${MUTABLE.length + 2}::timestamp(3) AND "status" = $${MUTABLE.length + 3}`,
|
|
969
|
+
`RETURNING "id"`
|
|
970
|
+
].join("\n");
|
|
971
|
+
function updateValues(document, previous) {
|
|
972
|
+
const all = documentValues(document);
|
|
973
|
+
const mutable = MUTABLE.map((column) => all[DOCUMENT_COLUMNS.indexOf(column)]);
|
|
974
|
+
return [document.id, ...mutable, previous.updatedAt, previous.status];
|
|
975
|
+
}
|
|
976
|
+
__name(updateValues, "updateValues");
|
|
977
|
+
var INSERT_EVENT = `INSERT INTO "fiscal_document_events" ("id", "document_id", "kind", "from_status", "to_status", "at", "error_class", "code", "answer")
|
|
978
|
+
VALUES ($1, $2, $3, $4, $5, $6::timestamp(3), $7, $8, $9::jsonb)`;
|
|
979
|
+
var UPSERT_PROFILE = `INSERT INTO "fiscal_emitter_profiles" (${PROFILE_COLUMNS.map((c) => `"${c}"`).join(", ")})
|
|
980
|
+
VALUES (${PROFILE_COLUMNS.map((c, i) => profilePlaceholder(c, i + 1)).join(", ")})
|
|
981
|
+
ON CONFLICT ("owner_id") DO UPDATE SET ${PROFILE_COLUMNS.filter((c) => c !== "owner_id").map((c) => `"${c}" = EXCLUDED."${c}"`).join(", ")}`;
|
|
982
|
+
var OWED = `("status" IN ('PENDING', 'SUBMITTED') OR "number_void" IN ('LOOKUP_FIRST', 'INUTILIZE', 'CANCEL'))`;
|
|
983
|
+
function violates(error, constraint) {
|
|
984
|
+
const text2 = error instanceof Error ? `${error.message} ${JSON.stringify(error.meta ?? "")}` : String(error);
|
|
985
|
+
return text2.includes(constraint);
|
|
986
|
+
}
|
|
987
|
+
__name(violates, "violates");
|
|
988
|
+
async function saveRow(tx, previous, { document, event }) {
|
|
989
|
+
const updated = await rows(tx, UPDATE_DOCUMENT, ...updateValues(document, previous));
|
|
990
|
+
if (updated.length === 0) return false;
|
|
991
|
+
await tx.$executeRawUnsafe(
|
|
992
|
+
INSERT_EVENT,
|
|
993
|
+
globalThis.crypto.randomUUID(),
|
|
994
|
+
event.documentId,
|
|
995
|
+
event.kind,
|
|
996
|
+
event.fromStatus,
|
|
997
|
+
event.toStatus,
|
|
998
|
+
event.at,
|
|
999
|
+
event.errorClass,
|
|
1000
|
+
event.code,
|
|
1001
|
+
event.answer === null ? null : JSON.stringify(event.answer)
|
|
1002
|
+
);
|
|
1003
|
+
return true;
|
|
1004
|
+
}
|
|
1005
|
+
__name(saveRow, "saveRow");
|
|
1006
|
+
async function draw(tx, request) {
|
|
1007
|
+
try {
|
|
1008
|
+
const [row] = await rows(tx, FISCAL_NEXT_NUMBER_SQL, request.issuerCnpj, request.environment, request.model, request.series, request.issuingPointId);
|
|
1009
|
+
if (row === void 0) {
|
|
1010
|
+
throw new FiscalDocumentError("NOT_FOUND", `no counter for series ${request.series} on issuing point ${request.issuingPointId}.`);
|
|
1011
|
+
}
|
|
1012
|
+
return Number(row["number"]);
|
|
1013
|
+
} catch (error) {
|
|
1014
|
+
if (violates(error, "fiscal_number_counters_next_number_check")) {
|
|
1015
|
+
throw new FiscalDocumentError("SERIES_EXHAUSTED", `series ${request.series} has no number left.`);
|
|
1016
|
+
}
|
|
1017
|
+
throw error;
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
__name(draw, "draw");
|
|
1021
|
+
async function insertDocument(tx, document) {
|
|
1022
|
+
try {
|
|
1023
|
+
await tx.$executeRawUnsafe(INSERT_DOCUMENT, ...documentValues(document));
|
|
1024
|
+
} catch (error) {
|
|
1025
|
+
if (violates(error, "fiscal_documents_live_subject_key")) {
|
|
1026
|
+
throw new FiscalDocumentError("SUBJECT_HAS_DOCUMENT", `subject ${document.subjectId} already has a live ${document.model}.`);
|
|
1027
|
+
}
|
|
1028
|
+
throw error;
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
__name(insertDocument, "insertDocument");
|
|
1032
|
+
async function openCounters(tx, point, issuerCnpj, series, kind, first) {
|
|
1033
|
+
for (const environment of ["homologacao", "producao"]) {
|
|
1034
|
+
await tx.$executeRawUnsafe(
|
|
1035
|
+
`INSERT INTO "fiscal_number_counters" ("issuer_cnpj", "environment", "model", "series", "issuing_point_id", "series_kind", "next_number")
|
|
1036
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
|
|
1037
|
+
issuerCnpj,
|
|
1038
|
+
environment,
|
|
1039
|
+
point.model,
|
|
1040
|
+
series,
|
|
1041
|
+
point.id,
|
|
1042
|
+
kind,
|
|
1043
|
+
first
|
|
1044
|
+
);
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
__name(openCounters, "openCounters");
|
|
1048
|
+
function profileMethods(db) {
|
|
1049
|
+
return {
|
|
1050
|
+
async getProfile(ownerId) {
|
|
1051
|
+
const [row] = await rows(db, `SELECT * FROM "fiscal_emitter_profiles" WHERE "owner_id" = $1`, ownerId);
|
|
1052
|
+
return row === void 0 ? null : profileOf(row);
|
|
1053
|
+
},
|
|
1054
|
+
async saveProfile(profile) {
|
|
1055
|
+
await db.$executeRawUnsafe(UPSERT_PROFILE, ...profileValues(profile));
|
|
1056
|
+
},
|
|
1057
|
+
async getIssuingPoint(ownerId, id) {
|
|
1058
|
+
const [row] = await rows(db, `SELECT * FROM "fiscal_issuing_points" WHERE "id" = $1 AND "owner_id" = $2`, id, ownerId);
|
|
1059
|
+
return row === void 0 ? null : pointOf(row);
|
|
1060
|
+
},
|
|
1061
|
+
async listIssuingPoints(ownerId) {
|
|
1062
|
+
return (await rows(db, `SELECT * FROM "fiscal_issuing_points" WHERE "owner_id" = $1 ORDER BY "created_at", "id"`, ownerId)).map(pointOf);
|
|
1063
|
+
},
|
|
1064
|
+
createIssuingPoint: /* @__PURE__ */ __name((point, issuerCnpj, firstNumber) => createIssuingPoint2(db, point, issuerCnpj, firstNumber), "createIssuingPoint"),
|
|
1065
|
+
async listExpiringCertificates(before) {
|
|
1066
|
+
return (await rows(db, `SELECT * FROM "fiscal_emitter_profiles" WHERE "certificate_expires_at" < $1::timestamp(3) ORDER BY "owner_id"`, before)).map(profileOf);
|
|
1067
|
+
}
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
__name(profileMethods, "profileMethods");
|
|
1071
|
+
async function createIssuingPoint2(db, ...[point, issuerCnpj, firstNumber]) {
|
|
1072
|
+
try {
|
|
1073
|
+
await db.$transaction(async (tx) => {
|
|
1074
|
+
await tx.$executeRawUnsafe(
|
|
1075
|
+
`INSERT INTO "fiscal_issuing_points" ("id", "owner_id", "model", "online_series", "contingency_series", "created_at")
|
|
1076
|
+
VALUES ($1, $2, $3, $4, $5, $6::timestamp(3))`,
|
|
1077
|
+
point.id,
|
|
1078
|
+
point.ownerId,
|
|
1079
|
+
point.model,
|
|
1080
|
+
point.onlineSeries,
|
|
1081
|
+
point.contingencySeries,
|
|
1082
|
+
point.createdAt
|
|
1083
|
+
);
|
|
1084
|
+
await openCounters(tx, point, issuerCnpj, point.onlineSeries, "ONLINE", firstNumber.online);
|
|
1085
|
+
if (point.contingencySeries !== null) {
|
|
1086
|
+
await openCounters(tx, point, issuerCnpj, point.contingencySeries, "CONTINGENCY", firstNumber.contingency);
|
|
1087
|
+
}
|
|
1088
|
+
});
|
|
1089
|
+
} catch (error) {
|
|
1090
|
+
if (violates(error, "fiscal_number_counters_pkey")) {
|
|
1091
|
+
throw new FiscalDocumentError("INVALID_INPUT", `a series of issuing point ${point.id} already belongs to another issuing point.`);
|
|
1092
|
+
}
|
|
1093
|
+
if (violates(error, "fiscal_issuing_points_pkey")) throw new FiscalDocumentError("INVALID_INPUT", `issuing point ${point.id} exists.`);
|
|
1094
|
+
throw error;
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
__name(createIssuingPoint2, "createIssuingPoint");
|
|
1098
|
+
function documentMethods(db) {
|
|
1099
|
+
const documents = /* @__PURE__ */ __name(async (query, ...values) => (await rows(db, query, ...values)).map(documentOf), "documents");
|
|
1100
|
+
return {
|
|
1101
|
+
createDocument: /* @__PURE__ */ __name((request, build, replace) => db.$transaction(async (tx) => {
|
|
1102
|
+
if (replace !== void 0 && !await saveRow(tx, replace.previous, replace.transition)) {
|
|
1103
|
+
throw new FiscalDocumentError("CONFLICT", `document ${replace.previous.id} moved before it was replaced.`);
|
|
1104
|
+
}
|
|
1105
|
+
const document = build(await draw(tx, request));
|
|
1106
|
+
await insertDocument(tx, document);
|
|
1107
|
+
return document;
|
|
1108
|
+
}), "createDocument"),
|
|
1109
|
+
async getDocument(ownerId, id) {
|
|
1110
|
+
const [document] = await documents(`SELECT * FROM "fiscal_documents" WHERE "id" = $1 AND "owner_id" = $2`, id, ownerId);
|
|
1111
|
+
return document ?? null;
|
|
1112
|
+
},
|
|
1113
|
+
listBySubject: /* @__PURE__ */ __name((ownerId, subjectId, model) => documents(
|
|
1114
|
+
`SELECT * FROM "fiscal_documents" WHERE "owner_id" = $1 AND "subject_id" = $2 AND "model" = $3 ORDER BY "created_at", "id"`,
|
|
1115
|
+
ownerId,
|
|
1116
|
+
subjectId,
|
|
1117
|
+
model
|
|
1118
|
+
), "listBySubject"),
|
|
1119
|
+
async listEvents(documentId) {
|
|
1120
|
+
return (await rows(db, `SELECT * FROM "fiscal_document_events" WHERE "document_id" = $1 ORDER BY "seq"`, documentId)).map(eventOf);
|
|
1121
|
+
},
|
|
1122
|
+
saveTransition: /* @__PURE__ */ __name((previous, transition2) => db.$transaction((tx) => saveRow(tx, previous, transition2)), "saveTransition"),
|
|
1123
|
+
listDue: /* @__PURE__ */ __name(({ now, limit }) => documents(
|
|
1124
|
+
`SELECT * FROM "fiscal_documents" WHERE "attention" = false AND "next_attempt_at" <= $1::timestamp(3) AND ${OWED}
|
|
1125
|
+
ORDER BY "next_attempt_at", "id" LIMIT $2`,
|
|
1126
|
+
now,
|
|
1127
|
+
limit
|
|
1128
|
+
), "listDue"),
|
|
1129
|
+
listContingency: /* @__PURE__ */ __name(({ now, limit }) => documents(
|
|
1130
|
+
`SELECT * FROM "fiscal_documents" WHERE "attention" = false AND "next_attempt_at" <= $1::timestamp(3) AND "status" = 'CONTINGENCY'
|
|
1131
|
+
ORDER BY "next_attempt_at", "id" LIMIT $2`,
|
|
1132
|
+
now,
|
|
1133
|
+
limit
|
|
1134
|
+
), "listContingency"),
|
|
1135
|
+
listContingencyDeadline: /* @__PURE__ */ __name(({ signedBefore, limit }) => documents(
|
|
1136
|
+
`SELECT * FROM "fiscal_documents" WHERE "status" = 'CONTINGENCY' AND "deadline_warned_at" IS NULL
|
|
1137
|
+
AND ("contingency" ->> 'since')::timestamptz < $1::timestamptz
|
|
1138
|
+
ORDER BY "created_at", "id" LIMIT $2`,
|
|
1139
|
+
signedBefore,
|
|
1140
|
+
limit
|
|
1141
|
+
), "listContingencyDeadline")
|
|
1142
|
+
};
|
|
1143
|
+
}
|
|
1144
|
+
__name(documentMethods, "documentMethods");
|
|
1145
|
+
function createPrismaFiscalStore(config) {
|
|
1146
|
+
const db = config?.prisma;
|
|
1147
|
+
if (typeof db?.$transaction !== "function" || typeof db.$queryRawUnsafe !== "function") {
|
|
1148
|
+
throw new TypeError("createPrismaFiscalStore needs prisma: the host's Prisma client.");
|
|
1149
|
+
}
|
|
1150
|
+
return { ...profileMethods(db), ...documentMethods(db) };
|
|
1151
|
+
}
|
|
1152
|
+
__name(createPrismaFiscalStore, "createPrismaFiscalStore");
|
|
1153
|
+
|
|
1154
|
+
// src/documents/lines.ts
|
|
1155
|
+
var SEGREGATED = /* @__PURE__ */ new Set(["GORJETA_EXCLUDED", "INTERMEDIATION_EXCLUDED"]);
|
|
1156
|
+
function ibsCbsOf(line, breakdown) {
|
|
1157
|
+
if (breakdown.treatment === "NONE") return null;
|
|
1158
|
+
const code = { cst: line.taxClass.cstIbsCbs, classCode: line.taxClass.cClassTrib };
|
|
1159
|
+
if (SEGREGATED.has(line.source)) return { ...code, figures: null };
|
|
1160
|
+
return {
|
|
1161
|
+
...code,
|
|
1162
|
+
figures: {
|
|
1163
|
+
baseCents: line.taxBaseCents,
|
|
1164
|
+
reductionBp: line.reductionBp,
|
|
1165
|
+
cbsRateBp: line.cbsRateBp,
|
|
1166
|
+
cbsCents: line.cbsCents,
|
|
1167
|
+
ibsUfRateBp: line.ibsUfRateBp,
|
|
1168
|
+
ibsUfCents: line.ibsUfCents,
|
|
1169
|
+
ibsMunRateBp: line.ibsMunRateBp,
|
|
1170
|
+
ibsMunCents: line.ibsMunCents
|
|
1171
|
+
}
|
|
1172
|
+
};
|
|
1173
|
+
}
|
|
1174
|
+
__name(ibsCbsOf, "ibsCbsOf");
|
|
1175
|
+
function documentLines(breakdown, details) {
|
|
1176
|
+
return breakdown.lines.map((line) => {
|
|
1177
|
+
const detail = details[line.lineId];
|
|
1178
|
+
if (detail === void 0) {
|
|
1179
|
+
throw new FiscalDocumentError("INVALID_INPUT", `breakdown line ${line.lineId} has no document details.`);
|
|
1180
|
+
}
|
|
1181
|
+
return {
|
|
1182
|
+
...detail,
|
|
1183
|
+
id: line.lineId,
|
|
1184
|
+
quantity: line.quantity,
|
|
1185
|
+
valueCents: line.valueCents,
|
|
1186
|
+
ibsCbs: ibsCbsOf(line, breakdown)
|
|
1187
|
+
};
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
__name(documentLines, "documentLines");
|
|
1191
|
+
export {
|
|
1192
|
+
CONTINGENCY_WARNING_AFTER_MS,
|
|
1193
|
+
DOCUMENT_POLICIES,
|
|
1194
|
+
DOCUMENT_TRANSITIONS,
|
|
1195
|
+
FINAL_STATUSES,
|
|
1196
|
+
FISCAL_CERTIFICATE_EXPIRING,
|
|
1197
|
+
FISCAL_CONTINGENCY_DEADLINE,
|
|
1198
|
+
FISCAL_DOCUMENT_MODELS,
|
|
1199
|
+
FISCAL_DOCUMENT_NEEDS_ATTENTION,
|
|
1200
|
+
FISCAL_DOCUMENT_REJECTED,
|
|
1201
|
+
FISCAL_DOCUMENT_STATUSES,
|
|
1202
|
+
FISCAL_NEXT_NUMBER_SQL,
|
|
1203
|
+
FiscalDocumentError,
|
|
1204
|
+
MAX_FAILURES,
|
|
1205
|
+
OWED_VOIDS,
|
|
1206
|
+
SIGNING_IDENTITY_KINDS,
|
|
1207
|
+
canTransition,
|
|
1208
|
+
computeAccessKey,
|
|
1209
|
+
createFiscalDocuments,
|
|
1210
|
+
createMemoryFiscalStore,
|
|
1211
|
+
createPlatformIdentity,
|
|
1212
|
+
createPrismaFiscalStore,
|
|
1213
|
+
createSigningIdentities,
|
|
1214
|
+
createStoreCertificateIdentity,
|
|
1215
|
+
documentLines,
|
|
1216
|
+
draftOf,
|
|
1217
|
+
drawKeyCode,
|
|
1218
|
+
isLive,
|
|
1219
|
+
localIso,
|
|
1220
|
+
parseCertificateUpload,
|
|
1221
|
+
parseIssuingPointInput,
|
|
1222
|
+
parseProfileInput,
|
|
1223
|
+
scrubSecrets,
|
|
1224
|
+
transition,
|
|
1225
|
+
viewOf,
|
|
1226
|
+
xmlKeys
|
|
1227
|
+
};
|
|
1228
|
+
//# sourceMappingURL=index.js.map
|