@12-apps/fiscal 1.0.0 → 1.2.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 +164 -7
- package/dist/chunk-2LBQRYPV.js +21 -0
- package/dist/chunk-2LBQRYPV.js.map +1 -0
- package/dist/chunk-3SDXLSG4.js +24 -0
- package/dist/chunk-3SDXLSG4.js.map +1 -0
- package/dist/chunk-5S2PJHAE.js +85 -0
- package/dist/chunk-5S2PJHAE.js.map +1 -0
- package/dist/chunk-G3V7IYNF.js +192 -0
- package/dist/chunk-G3V7IYNF.js.map +1 -0
- package/dist/chunk-JVQKJNOC.js +14 -0
- package/dist/chunk-JVQKJNOC.js.map +1 -0
- package/dist/chunk-N5DCKYFR.js +610 -0
- package/dist/chunk-N5DCKYFR.js.map +1 -0
- package/dist/chunk-NVRYAAQ4.js +212 -0
- package/dist/chunk-NVRYAAQ4.js.map +1 -0
- package/dist/chunk-PNTKG3DZ.js +47 -0
- package/dist/chunk-PNTKG3DZ.js.map +1 -0
- package/dist/chunk-WTGASIZE.js +247 -0
- package/dist/chunk-WTGASIZE.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 +181 -0
- package/dist/documents/index.js +1234 -0
- package/dist/documents/index.js.map +1 -0
- package/dist/engine/index.d.ts +3 -246
- package/dist/http.d.ts +75 -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 +30 -16
- package/dist/manifest/index.js +11 -17
- package/dist/manifest/index.js.map +1 -1
- 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 +269 -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 +218 -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 +63 -5
- 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 +162 -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 +422 -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 +428 -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 +48 -0
- package/src/documents/helpers.ts +177 -0
- package/src/documents/index.ts +40 -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 +299 -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/http.ts +266 -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 +25 -16
- 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 +318 -0
- package/src/sidecar/index.ts +9 -0
- package/src/sidecar/types.ts +245 -0
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import {
|
|
2
|
+
accessKeyOf,
|
|
3
|
+
element,
|
|
4
|
+
elements,
|
|
5
|
+
text
|
|
6
|
+
} from "./chunk-PNTKG3DZ.js";
|
|
7
|
+
import {
|
|
8
|
+
FiscalDocumentError
|
|
9
|
+
} from "./chunk-2LBQRYPV.js";
|
|
10
|
+
import {
|
|
11
|
+
__name
|
|
12
|
+
} from "./chunk-7QVYU63E.js";
|
|
13
|
+
|
|
14
|
+
// src/danfe/labels.ts
|
|
15
|
+
var DANFE_LABEL_KEYS = [
|
|
16
|
+
"cnpj",
|
|
17
|
+
"stateRegistration",
|
|
18
|
+
"title",
|
|
19
|
+
"itemsHeader",
|
|
20
|
+
"itemCount",
|
|
21
|
+
"totalValue",
|
|
22
|
+
"discounts",
|
|
23
|
+
"amountDue",
|
|
24
|
+
"paymentHeader",
|
|
25
|
+
"change",
|
|
26
|
+
"paymentMethods",
|
|
27
|
+
"lookupByKey",
|
|
28
|
+
"homologation",
|
|
29
|
+
"contingency",
|
|
30
|
+
"pendingAuthorization",
|
|
31
|
+
"consumerCopy",
|
|
32
|
+
"consumer",
|
|
33
|
+
"unidentifiedConsumer",
|
|
34
|
+
"number",
|
|
35
|
+
"series",
|
|
36
|
+
"protocol",
|
|
37
|
+
"authorizedAt",
|
|
38
|
+
"qrCaption",
|
|
39
|
+
"approximateTaxes"
|
|
40
|
+
];
|
|
41
|
+
|
|
42
|
+
// src/danfe/render.ts
|
|
43
|
+
var DANFE_COLUMNS = { 58: 32, 80: 48 };
|
|
44
|
+
function money(value) {
|
|
45
|
+
const cents = Math.round(Number(value ?? "0") * 100);
|
|
46
|
+
const whole = Math.trunc(Math.abs(cents) / 100).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
|
|
47
|
+
return `${cents < 0 ? "-" : ""}${whole},${String(Math.abs(cents) % 100).padStart(2, "0")}`;
|
|
48
|
+
}
|
|
49
|
+
__name(money, "money");
|
|
50
|
+
function quantity(value) {
|
|
51
|
+
return Number(value ?? "0").toLocaleString("en-US", { maximumFractionDigits: 4, useGrouping: false }).replace(".", ",");
|
|
52
|
+
}
|
|
53
|
+
__name(quantity, "quantity");
|
|
54
|
+
function pieces(word, width) {
|
|
55
|
+
const out = [];
|
|
56
|
+
for (let at = 0; at < word.length; at += width) out.push(word.slice(at, at + width));
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
__name(pieces, "pieces");
|
|
60
|
+
function wrap(value, width) {
|
|
61
|
+
const words = value.trim().split(/\s+/).filter((word) => word !== "").flatMap((word) => pieces(word, width));
|
|
62
|
+
const lines = [];
|
|
63
|
+
let current = "";
|
|
64
|
+
for (const word of words) {
|
|
65
|
+
const candidate = current === "" ? word : `${current} ${word}`;
|
|
66
|
+
if (candidate.length <= width) {
|
|
67
|
+
current = candidate;
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (current !== "") lines.push(current);
|
|
71
|
+
current = word;
|
|
72
|
+
}
|
|
73
|
+
if (current !== "") lines.push(current);
|
|
74
|
+
return lines.length > 0 ? lines : [""];
|
|
75
|
+
}
|
|
76
|
+
__name(wrap, "wrap");
|
|
77
|
+
function spread(label, value, width) {
|
|
78
|
+
const gap = width - label.length - value.length;
|
|
79
|
+
return gap >= 1 ? `${label}${" ".repeat(gap)}${value}` : `${label} ${value}`;
|
|
80
|
+
}
|
|
81
|
+
__name(spread, "spread");
|
|
82
|
+
function groupKey(key) {
|
|
83
|
+
return key.replace(/(.{4})/g, "$1 ").trim();
|
|
84
|
+
}
|
|
85
|
+
__name(groupKey, "groupKey");
|
|
86
|
+
var Paper = class {
|
|
87
|
+
constructor(width) {
|
|
88
|
+
this.width = width;
|
|
89
|
+
}
|
|
90
|
+
width;
|
|
91
|
+
static {
|
|
92
|
+
__name(this, "Paper");
|
|
93
|
+
}
|
|
94
|
+
lines = [];
|
|
95
|
+
add(division, value, align = "left", emphasis = "normal") {
|
|
96
|
+
for (const piece of wrap(value, this.width)) this.lines.push({ division, text: piece, align, emphasis });
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* `label ……… value` on one line when it fits; otherwise the label wraps and
|
|
100
|
+
* the value closes its last line, or takes a line of its own, right-aligned.
|
|
101
|
+
* Nothing passes the roll's width.
|
|
102
|
+
*/
|
|
103
|
+
pair(division, label, value, emphasis = "normal") {
|
|
104
|
+
const labelLines = wrap(label, this.width);
|
|
105
|
+
const last = labelLines.pop() ?? "";
|
|
106
|
+
for (const piece of labelLines) this.lines.push({ division, text: piece, align: "left", emphasis });
|
|
107
|
+
const closing = last.length + 1 + value.length <= this.width ? [spread(last, value, this.width)] : [last, value.padStart(this.width)];
|
|
108
|
+
for (const piece of closing) this.lines.push({ division, text: piece, align: "left", emphasis });
|
|
109
|
+
}
|
|
110
|
+
rule(division) {
|
|
111
|
+
this.lines.push({ division, text: "-".repeat(this.width), align: "left", emphasis: "normal" });
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
function parse(xml) {
|
|
115
|
+
const infNFe = element(xml, "infNFe");
|
|
116
|
+
const ide = infNFe === null ? null : element(infNFe, "ide");
|
|
117
|
+
const emit = infNFe === null ? null : element(infNFe, "emit");
|
|
118
|
+
const accessKey = accessKeyOf(xml);
|
|
119
|
+
if (infNFe === null || ide === null || emit === null || accessKey === null) {
|
|
120
|
+
throw new FiscalDocumentError("INVALID_INPUT", "the XML is not an NF-e: no infNFe, ide, emit or access key.");
|
|
121
|
+
}
|
|
122
|
+
if (text(ide, "mod") !== "65") throw new FiscalDocumentError("INVALID_INPUT", "the XML is not an NFC-e (model 65).");
|
|
123
|
+
return {
|
|
124
|
+
infNFe,
|
|
125
|
+
ide,
|
|
126
|
+
emit,
|
|
127
|
+
total: element(infNFe, "ICMSTot") ?? "",
|
|
128
|
+
supl: element(xml, "infNFeSupl") ?? "",
|
|
129
|
+
accessKey,
|
|
130
|
+
contingency: text(ide, "tpEmis") === "9",
|
|
131
|
+
infProt: element(xml, "infProt"),
|
|
132
|
+
homologation: text(ide, "tpAmb") === "2"
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
__name(parse, "parse");
|
|
136
|
+
function issuerPart(paper, doc, labels) {
|
|
137
|
+
const address = element(doc.emit, "enderEmit");
|
|
138
|
+
paper.add("I", text(doc.emit, "xNome") ?? "", "center", "bold");
|
|
139
|
+
paper.add("I", `${labels.cnpj} ${text(doc.emit, "CNPJ") ?? ""} ${labels.stateRegistration} ${text(doc.emit, "IE") ?? ""}`, "center");
|
|
140
|
+
const street = [text(address, "xLgr"), text(address, "nro"), text(address, "xBairro"), text(address, "xMun"), text(address, "UF")];
|
|
141
|
+
paper.add("I", street.filter((part) => part !== null && part !== "").join(", "), "center");
|
|
142
|
+
paper.add("II", labels.title, "center", "bold");
|
|
143
|
+
paper.rule("II");
|
|
144
|
+
}
|
|
145
|
+
__name(issuerPart, "issuerPart");
|
|
146
|
+
function itemsPart(paper, doc, labels) {
|
|
147
|
+
paper.add("III", labels.itemsHeader);
|
|
148
|
+
const items = elements(doc.infNFe, "det");
|
|
149
|
+
for (const det of items) {
|
|
150
|
+
const prod = element(det, "prod");
|
|
151
|
+
paper.add("III", `${text(prod, "cProd") ?? ""} ${text(prod, "xProd") ?? ""}`);
|
|
152
|
+
const amount = `${quantity(text(prod, "qCom"))} ${text(prod, "uCom") ?? ""} x ${money(text(prod, "vUnCom"))}`;
|
|
153
|
+
paper.pair("III", amount, money(text(prod, "vProd")));
|
|
154
|
+
}
|
|
155
|
+
paper.rule("III");
|
|
156
|
+
return items.length;
|
|
157
|
+
}
|
|
158
|
+
__name(itemsPart, "itemsPart");
|
|
159
|
+
function totalsPart(paper, doc, labels, count) {
|
|
160
|
+
paper.pair("IV", labels.itemCount, String(count));
|
|
161
|
+
paper.pair("IV", labels.totalValue, money(text(doc.total, "vProd")));
|
|
162
|
+
const discount = text(doc.total, "vDesc");
|
|
163
|
+
if (discount !== null && Number(discount) > 0) paper.pair("IV", labels.discounts, money(discount));
|
|
164
|
+
paper.pair("IV", labels.amountDue, money(text(doc.total, "vNF")), "bold");
|
|
165
|
+
paper.add("IV", labels.paymentHeader);
|
|
166
|
+
for (const detPag of elements(doc.infNFe, "detPag")) {
|
|
167
|
+
const code = text(detPag, "tPag") ?? "";
|
|
168
|
+
paper.pair("IV", text(detPag, "xPag") ?? labels.paymentMethods[code] ?? code, money(text(detPag, "vPag")));
|
|
169
|
+
}
|
|
170
|
+
const change = text(element(doc.infNFe, "pag"), "vTroco");
|
|
171
|
+
if (change !== null && Number(change) > 0) paper.pair("IV", labels.change, money(change));
|
|
172
|
+
paper.rule("IV");
|
|
173
|
+
}
|
|
174
|
+
__name(totalsPart, "totalsPart");
|
|
175
|
+
function fiscalMessagePart(paper, doc, labels) {
|
|
176
|
+
if (doc.homologation) paper.add("V", labels.homologation, "center", "bold");
|
|
177
|
+
if (doc.contingency) paper.add("V", labels.contingency, "center", "bold");
|
|
178
|
+
if (doc.contingency && doc.infProt === null) {
|
|
179
|
+
paper.add("V", labels.pendingAuthorization, "center", "bold");
|
|
180
|
+
paper.add("V", labels.consumerCopy, "center", "bold");
|
|
181
|
+
}
|
|
182
|
+
paper.add("V", labels.lookupByKey, "center");
|
|
183
|
+
paper.add("V", text(doc.supl, "urlChave") ?? "", "center");
|
|
184
|
+
paper.add("V", groupKey(doc.accessKey), "center");
|
|
185
|
+
paper.rule("V");
|
|
186
|
+
}
|
|
187
|
+
__name(fiscalMessagePart, "fiscalMessagePart");
|
|
188
|
+
function consumerPart(paper, doc, labels) {
|
|
189
|
+
const dest = element(doc.infNFe, "dest");
|
|
190
|
+
const id = text(dest, "CPF") ?? text(dest, "CNPJ") ?? text(dest, "idEstrangeiro");
|
|
191
|
+
if (id === null) {
|
|
192
|
+
paper.add("VI", labels.unidentifiedConsumer, "center");
|
|
193
|
+
} else {
|
|
194
|
+
paper.add("VI", `${labels.consumer} ${id}`, "center");
|
|
195
|
+
const name = text(dest, "xNome");
|
|
196
|
+
if (name !== null) paper.add("VI", name, "center");
|
|
197
|
+
}
|
|
198
|
+
paper.rule("VI");
|
|
199
|
+
}
|
|
200
|
+
__name(consumerPart, "consumerPart");
|
|
201
|
+
function identificationPart(paper, doc, labels) {
|
|
202
|
+
const issued = (text(doc.ide, "dhEmi") ?? "").replace("T", " ").slice(0, 19);
|
|
203
|
+
paper.add("VII", `${labels.number} ${text(doc.ide, "nNF") ?? ""} ${labels.series} ${text(doc.ide, "serie") ?? ""} ${issued}`, "center", "bold");
|
|
204
|
+
const { infProt } = doc;
|
|
205
|
+
if (infProt !== null) {
|
|
206
|
+
paper.add("VII", `${labels.protocol} ${text(infProt, "nProt") ?? ""}`, "center");
|
|
207
|
+
paper.add("VII", `${labels.authorizedAt} ${(text(infProt, "dhRecbto") ?? "").replace("T", " ").slice(0, 19)}`, "center");
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
__name(identificationPart, "identificationPart");
|
|
211
|
+
function qrPart(paper, doc, labels) {
|
|
212
|
+
const qrCode = text(doc.supl, "qrCode");
|
|
213
|
+
if (qrCode === null) throw new FiscalDocumentError("INVALID_INPUT", "the NFC-e XML carries no QR code (infNFeSupl/qrCode).");
|
|
214
|
+
paper.add("VIII", labels.qrCaption, "center");
|
|
215
|
+
paper.lines.push({ division: "VIII", text: "", align: "center", emphasis: "normal", qrCode });
|
|
216
|
+
const message = text(element(doc.infNFe, "infAdic"), "infCpl");
|
|
217
|
+
if (message !== null && message !== "") paper.add("VIII", message);
|
|
218
|
+
const taxes = text(doc.total, "vTotTrib");
|
|
219
|
+
if (taxes !== null && Number(taxes) > 0) paper.add("VIII", `${labels.approximateTaxes} ${money(taxes)}`);
|
|
220
|
+
}
|
|
221
|
+
__name(qrPart, "qrPart");
|
|
222
|
+
function renderDanfeNfce(input) {
|
|
223
|
+
const missing = DANFE_LABEL_KEYS.filter((key) => input.labels?.[key] === void 0);
|
|
224
|
+
if (missing.length > 0) throw new FiscalDocumentError("INVALID_INPUT", `labels is missing: ${missing.join(", ")}.`);
|
|
225
|
+
const width = DANFE_COLUMNS[input.paperWidth];
|
|
226
|
+
if (width === void 0) throw new FiscalDocumentError("INVALID_INPUT", "paperWidth must be 58 or 80.");
|
|
227
|
+
const doc = parse(input.xml);
|
|
228
|
+
const paper = new Paper(width);
|
|
229
|
+
issuerPart(paper, doc, input.labels);
|
|
230
|
+
const count = itemsPart(paper, doc, input.labels);
|
|
231
|
+
totalsPart(paper, doc, input.labels, count);
|
|
232
|
+
fiscalMessagePart(paper, doc, input.labels);
|
|
233
|
+
consumerPart(paper, doc, input.labels);
|
|
234
|
+
identificationPart(paper, doc, input.labels);
|
|
235
|
+
qrPart(paper, doc, input.labels);
|
|
236
|
+
return paper.lines;
|
|
237
|
+
}
|
|
238
|
+
__name(renderDanfeNfce, "renderDanfeNfce");
|
|
239
|
+
|
|
240
|
+
export {
|
|
241
|
+
DANFE_LABEL_KEYS,
|
|
242
|
+
DANFE_COLUMNS,
|
|
243
|
+
money,
|
|
244
|
+
wrap,
|
|
245
|
+
renderDanfeNfce
|
|
246
|
+
};
|
|
247
|
+
//# sourceMappingURL=chunk-WTGASIZE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/danfe/labels.ts","../src/danfe/render.ts"],"sourcesContent":["/**\n * The words a DANFE NFC-e prints. The layout is the Manual do DANFE NFC-e's\n * and the words are the host's language: a host passes them all, or the\n * `./pt-BR` pack, which carries the Manual's own texts. Nothing here defaults.\n */\n\nexport interface DanfeNfceLabels {\n /** Division I. */\n readonly cnpj: string;\n readonly stateRegistration: string;\n /** Division II: the document's own title. */\n readonly title: string;\n /** Division III: the item table's header. */\n readonly itemsHeader: string;\n /** Division IV. */\n readonly itemCount: string;\n readonly totalValue: string;\n readonly discounts: string;\n readonly amountDue: string;\n readonly paymentHeader: string;\n readonly change: string;\n /** `tPag` code (`01`, `17`…) → the method's name; an unknown code prints itself. */\n readonly paymentMethods: Readonly<Record<string, string>>;\n /** Division V. */\n readonly lookupByKey: string;\n readonly homologation: string;\n readonly contingency: string;\n readonly pendingAuthorization: string;\n /** Printed on a paper signed offline and not yet authorised: the one copy, the consumer's. */\n readonly consumerCopy: string;\n /** Division VI. */\n readonly consumer: string;\n readonly unidentifiedConsumer: string;\n /** Division VII. */\n readonly number: string;\n readonly series: string;\n readonly protocol: string;\n readonly authorizedAt: string;\n /** Division VIII and after: the QR code's caption and the approximate tax line (Lei 12.741/2012). */\n readonly qrCaption: string;\n readonly approximateTaxes: string;\n}\n\nexport const DANFE_LABEL_KEYS: readonly (keyof DanfeNfceLabels)[] = [\n \"cnpj\", \"stateRegistration\", \"title\", \"itemsHeader\", \"itemCount\", \"totalValue\", \"discounts\", \"amountDue\",\n \"paymentHeader\", \"change\", \"paymentMethods\", \"lookupByKey\", \"homologation\", \"contingency\", \"pendingAuthorization\",\n \"consumerCopy\",\n \"consumer\", \"unidentifiedConsumer\", \"number\", \"series\", \"protocol\", \"authorizedAt\", \"qrCaption\", \"approximateTaxes\",\n];\n","/**\n * The DANFE NFC-e as ESC/POS-ready lines, read from the document's XML —\n * the authorised `nfeProc`, or the signed XML of a document issued offline,\n * which prints the contingency variant. No provider returns ESC/POS and a\n * register offline has nothing else to print, so the package renders it.\n *\n * The paper follows the Manual do DANFE NFC-e's divisions, in order (the\n * FULL DANFE, items included):\n *\n * I the issuer: name, CNPJ, IE, address\n * II the document's title\n * III the items: code, description, quantity, unit, unit value, total\n * IV the totals: item count, total, discounts, amount due, payments, change\n * V the fiscal message: homologation, contingency, where to look the key up, the key\n * VI the consumer\n * VII the number, series, issue time, and the authorisation protocol\n * VIII the QR code, then the taxpayer's message and the approximate taxes\n *\n * Each line is `{ text, align, emphasis }`, the shape `@12-apps/thermal-printing`\n * encodes, laid out for the column count of the roll (Font A: 32 columns on\n * 58 mm, 48 on 80 mm); the QR line carries `qrCode` for the host to rasterise.\n */\n\nimport { FiscalDocumentError } from \"../documents/errors\";\nimport type { DanfeNfceLabels } from \"./labels\";\nimport { DANFE_LABEL_KEYS } from \"./labels\";\nimport { accessKeyOf, element, elements, text } from \"./xml\";\n\nexport type DanfeDivision = \"I\" | \"II\" | \"III\" | \"IV\" | \"V\" | \"VI\" | \"VII\" | \"VIII\";\n\nexport interface DanfeLine {\n readonly division: DanfeDivision;\n readonly text: string;\n readonly align: \"left\" | \"center\";\n readonly emphasis: \"normal\" | \"bold\";\n /** Present on the QR line only: the URL the code encodes. */\n readonly qrCode?: string;\n}\n\nexport type PaperWidth = 58 | 80;\n\nexport const DANFE_COLUMNS: Readonly<Record<PaperWidth, number>> = { 58: 32, 80: 48 };\n\nexport interface DanfeNfceInput {\n /** The `nfeProc` of an authorised document, or the signed XML of one issued offline. */\n readonly xml: string;\n readonly paperWidth: PaperWidth;\n readonly labels: DanfeNfceLabels;\n}\n\n/** `1234` cents → `12,34`; thousands with a dot, as the DANFE prints money. */\nexport function money(value: string | null): string {\n const cents = Math.round(Number(value ?? \"0\") * 100);\n const whole = Math.trunc(Math.abs(cents) / 100).toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \".\");\n return `${cents < 0 ? \"-\" : \"\"}${whole},${String(Math.abs(cents) % 100).padStart(2, \"0\")}`;\n}\n\nfunction quantity(value: string | null): string {\n return Number(value ?? \"0\").toLocaleString(\"en-US\", { maximumFractionDigits: 4, useGrouping: false }).replace(\".\", \",\");\n}\n\n/** A word longer than the width (a URL) cut into width-long pieces: nothing is dropped. */\nfunction pieces(word: string, width: number): string[] {\n const out: string[] = [];\n for (let at = 0; at < word.length; at += width) out.push(word.slice(at, at + width));\n return out;\n}\n\n/** Wrap a text at the width, breaking on spaces where it can. */\nexport function wrap(value: string, width: number): string[] {\n const words = value\n .trim()\n .split(/\\s+/)\n .filter((word) => word !== \"\")\n .flatMap((word) => pieces(word, width));\n const lines: string[] = [];\n let current = \"\";\n for (const word of words) {\n const candidate = current === \"\" ? word : `${current} ${word}`;\n if (candidate.length <= width) {\n current = candidate;\n continue;\n }\n if (current !== \"\") lines.push(current);\n current = word;\n }\n if (current !== \"\") lines.push(current);\n return lines.length > 0 ? lines : [\"\"];\n}\n\n/** `label ……… value` across the width. */\nfunction spread(label: string, value: string, width: number): string {\n const gap = width - label.length - value.length;\n return gap >= 1 ? `${label}${\" \".repeat(gap)}${value}` : `${label} ${value}`;\n}\n\nfunction groupKey(key: string): string {\n return key.replace(/(.{4})/g, \"$1 \").trim();\n}\n\nclass Paper {\n readonly lines: DanfeLine[] = [];\n constructor(readonly width: number) {}\n\n add(division: DanfeDivision, value: string, align: DanfeLine[\"align\"] = \"left\", emphasis: DanfeLine[\"emphasis\"] = \"normal\"): void {\n for (const piece of wrap(value, this.width)) this.lines.push({ division, text: piece, align, emphasis });\n }\n\n /**\n * `label ……… value` on one line when it fits; otherwise the label wraps and\n * the value closes its last line, or takes a line of its own, right-aligned.\n * Nothing passes the roll's width.\n */\n pair(division: DanfeDivision, label: string, value: string, emphasis: DanfeLine[\"emphasis\"] = \"normal\"): void {\n const labelLines = wrap(label, this.width);\n const last = labelLines.pop() ?? \"\";\n for (const piece of labelLines) this.lines.push({ division, text: piece, align: \"left\", emphasis });\n const closing = last.length + 1 + value.length <= this.width ? [spread(last, value, this.width)] : [last, value.padStart(this.width)];\n for (const piece of closing) this.lines.push({ division, text: piece, align: \"left\", emphasis });\n }\n\n rule(division: DanfeDivision): void {\n this.lines.push({ division, text: \"-\".repeat(this.width), align: \"left\", emphasis: \"normal\" });\n }\n}\n\ninterface Parsed {\n readonly infNFe: string;\n readonly ide: string;\n readonly emit: string;\n readonly total: string;\n /** `infNFeSupl`, beside `infNFe`: the QR code and the lookup URL. */\n readonly supl: string;\n readonly accessKey: string;\n readonly contingency: boolean;\n /** The authorisation protocol, once SEFAZ has answered (the `nfeProc`). */\n readonly infProt: string | null;\n readonly homologation: boolean;\n}\n\nfunction parse(xml: string): Parsed {\n const infNFe = element(xml, \"infNFe\");\n const ide = infNFe === null ? null : element(infNFe, \"ide\");\n const emit = infNFe === null ? null : element(infNFe, \"emit\");\n const accessKey = accessKeyOf(xml);\n if (infNFe === null || ide === null || emit === null || accessKey === null) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", \"the XML is not an NF-e: no infNFe, ide, emit or access key.\");\n }\n if (text(ide, \"mod\") !== \"65\") throw new FiscalDocumentError(\"INVALID_INPUT\", \"the XML is not an NFC-e (model 65).\");\n return {\n infNFe,\n ide,\n emit,\n total: element(infNFe, \"ICMSTot\") ?? \"\",\n supl: element(xml, \"infNFeSupl\") ?? \"\",\n accessKey,\n contingency: text(ide, \"tpEmis\") === \"9\",\n infProt: element(xml, \"infProt\"),\n homologation: text(ide, \"tpAmb\") === \"2\",\n };\n}\n\nfunction issuerPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {\n const address = element(doc.emit, \"enderEmit\");\n paper.add(\"I\", text(doc.emit, \"xNome\") ?? \"\", \"center\", \"bold\");\n paper.add(\"I\", `${labels.cnpj} ${text(doc.emit, \"CNPJ\") ?? \"\"} ${labels.stateRegistration} ${text(doc.emit, \"IE\") ?? \"\"}`, \"center\");\n const street = [text(address, \"xLgr\"), text(address, \"nro\"), text(address, \"xBairro\"), text(address, \"xMun\"), text(address, \"UF\")];\n paper.add(\"I\", street.filter((part) => part !== null && part !== \"\").join(\", \"), \"center\");\n paper.add(\"II\", labels.title, \"center\", \"bold\");\n paper.rule(\"II\");\n}\n\nfunction itemsPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): number {\n paper.add(\"III\", labels.itemsHeader);\n const items = elements(doc.infNFe, \"det\");\n for (const det of items) {\n const prod = element(det, \"prod\");\n paper.add(\"III\", `${text(prod, \"cProd\") ?? \"\"} ${text(prod, \"xProd\") ?? \"\"}`);\n const amount = `${quantity(text(prod, \"qCom\"))} ${text(prod, \"uCom\") ?? \"\"} x ${money(text(prod, \"vUnCom\"))}`;\n paper.pair(\"III\", amount, money(text(prod, \"vProd\")));\n }\n paper.rule(\"III\");\n return items.length;\n}\n\nfunction totalsPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels, count: number): void {\n paper.pair(\"IV\", labels.itemCount, String(count));\n paper.pair(\"IV\", labels.totalValue, money(text(doc.total, \"vProd\")));\n const discount = text(doc.total, \"vDesc\");\n if (discount !== null && Number(discount) > 0) paper.pair(\"IV\", labels.discounts, money(discount));\n paper.pair(\"IV\", labels.amountDue, money(text(doc.total, \"vNF\")), \"bold\");\n paper.add(\"IV\", labels.paymentHeader);\n for (const detPag of elements(doc.infNFe, \"detPag\")) {\n const code = text(detPag, \"tPag\") ?? \"\";\n paper.pair(\"IV\", text(detPag, \"xPag\") ?? labels.paymentMethods[code] ?? code, money(text(detPag, \"vPag\")));\n }\n const change = text(element(doc.infNFe, \"pag\"), \"vTroco\");\n if (change !== null && Number(change) > 0) paper.pair(\"IV\", labels.change, money(change));\n paper.rule(\"IV\");\n}\n\nfunction fiscalMessagePart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {\n if (doc.homologation) paper.add(\"V\", labels.homologation, \"center\", \"bold\");\n if (doc.contingency) paper.add(\"V\", labels.contingency, \"center\", \"bold\");\n // Offline and not yet authorised: ONE copy, the consumer's (reprints are the same paper).\n if (doc.contingency && doc.infProt === null) {\n paper.add(\"V\", labels.pendingAuthorization, \"center\", \"bold\");\n paper.add(\"V\", labels.consumerCopy, \"center\", \"bold\");\n }\n paper.add(\"V\", labels.lookupByKey, \"center\");\n paper.add(\"V\", text(doc.supl, \"urlChave\") ?? \"\", \"center\");\n paper.add(\"V\", groupKey(doc.accessKey), \"center\");\n paper.rule(\"V\");\n}\n\nfunction consumerPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {\n const dest = element(doc.infNFe, \"dest\");\n const id = text(dest, \"CPF\") ?? text(dest, \"CNPJ\") ?? text(dest, \"idEstrangeiro\");\n if (id === null) {\n paper.add(\"VI\", labels.unidentifiedConsumer, \"center\");\n } else {\n paper.add(\"VI\", `${labels.consumer} ${id}`, \"center\");\n const name = text(dest, \"xNome\");\n if (name !== null) paper.add(\"VI\", name, \"center\");\n }\n paper.rule(\"VI\");\n}\n\nfunction identificationPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {\n const issued = (text(doc.ide, \"dhEmi\") ?? \"\").replace(\"T\", \" \").slice(0, 19);\n paper.add(\"VII\", `${labels.number} ${text(doc.ide, \"nNF\") ?? \"\"} ${labels.series} ${text(doc.ide, \"serie\") ?? \"\"} ${issued}`, \"center\", \"bold\");\n const { infProt } = doc;\n if (infProt !== null) {\n paper.add(\"VII\", `${labels.protocol} ${text(infProt, \"nProt\") ?? \"\"}`, \"center\");\n paper.add(\"VII\", `${labels.authorizedAt} ${(text(infProt, \"dhRecbto\") ?? \"\").replace(\"T\", \" \").slice(0, 19)}`, \"center\");\n }\n}\n\nfunction qrPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {\n const qrCode = text(doc.supl, \"qrCode\");\n if (qrCode === null) throw new FiscalDocumentError(\"INVALID_INPUT\", \"the NFC-e XML carries no QR code (infNFeSupl/qrCode).\");\n paper.add(\"VIII\", labels.qrCaption, \"center\");\n paper.lines.push({ division: \"VIII\", text: \"\", align: \"center\", emphasis: \"normal\", qrCode });\n const message = text(element(doc.infNFe, \"infAdic\"), \"infCpl\");\n if (message !== null && message !== \"\") paper.add(\"VIII\", message);\n const taxes = text(doc.total, \"vTotTrib\");\n if (taxes !== null && Number(taxes) > 0) paper.add(\"VIII\", `${labels.approximateTaxes} ${money(taxes)}`);\n}\n\nexport function renderDanfeNfce(input: DanfeNfceInput): DanfeLine[] {\n const missing = DANFE_LABEL_KEYS.filter((key) => input.labels?.[key] === undefined);\n if (missing.length > 0) throw new FiscalDocumentError(\"INVALID_INPUT\", `labels is missing: ${missing.join(\", \")}.`);\n const width = DANFE_COLUMNS[input.paperWidth];\n if (width === undefined) throw new FiscalDocumentError(\"INVALID_INPUT\", \"paperWidth must be 58 or 80.\");\n const doc = parse(input.xml);\n const paper = new Paper(width);\n issuerPart(paper, doc, input.labels);\n const count = itemsPart(paper, doc, input.labels);\n totalsPart(paper, doc, input.labels, count);\n fiscalMessagePart(paper, doc, input.labels);\n consumerPart(paper, doc, input.labels);\n identificationPart(paper, doc, input.labels);\n qrPart(paper, doc, input.labels);\n return paper.lines;\n}\n"],"mappings":";;;;;;;;;;;;;;AA2CO,IAAM,mBAAuD;AAAA,EAClE;AAAA,EAAQ;AAAA,EAAqB;AAAA,EAAS;AAAA,EAAe;AAAA,EAAa;AAAA,EAAc;AAAA,EAAa;AAAA,EAC7F;AAAA,EAAiB;AAAA,EAAU;AAAA,EAAkB;AAAA,EAAe;AAAA,EAAgB;AAAA,EAAe;AAAA,EAC3F;AAAA,EACA;AAAA,EAAY;AAAA,EAAwB;AAAA,EAAU;AAAA,EAAU;AAAA,EAAY;AAAA,EAAgB;AAAA,EAAa;AACnG;;;ACPO,IAAM,gBAAsD,EAAE,IAAI,IAAI,IAAI,GAAG;AAU7E,SAAS,MAAM,OAA8B;AAClD,QAAM,QAAQ,KAAK,MAAM,OAAO,SAAS,GAAG,IAAI,GAAG;AACnD,QAAM,QAAQ,KAAK,MAAM,KAAK,IAAI,KAAK,IAAI,GAAG,EAAE,SAAS,EAAE,QAAQ,yBAAyB,GAAG;AAC/F,SAAO,GAAG,QAAQ,IAAI,MAAM,EAAE,GAAG,KAAK,IAAI,OAAO,KAAK,IAAI,KAAK,IAAI,GAAG,EAAE,SAAS,GAAG,GAAG,CAAC;AAC1F;AAJgB;AAMhB,SAAS,SAAS,OAA8B;AAC9C,SAAO,OAAO,SAAS,GAAG,EAAE,eAAe,SAAS,EAAE,uBAAuB,GAAG,aAAa,MAAM,CAAC,EAAE,QAAQ,KAAK,GAAG;AACxH;AAFS;AAKT,SAAS,OAAO,MAAc,OAAyB;A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,KAAK,MAAM,QAAQ,KAAK;AAC1C,oBAAkB,OAAO,KAAK,MAAM,MAAM;AAC1C,eAAa,OAAO,KAAK,MAAM,MAAM;AACrC,qBAAmB,OAAO,KAAK,MAAM,MAAM;AAC3C,SAAO,OAAO,KAAK,MAAM,MAAM;AAC/B,SAAO,MAAM;AACf;AAfgB;","names":[]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__name
|
|
3
|
+
} from "./chunk-7QVYU63E.js";
|
|
4
|
+
|
|
5
|
+
// src/documents/types.ts
|
|
6
|
+
var FISCAL_DOCUMENT_MODELS = ["NFE", "NFCE"];
|
|
7
|
+
var FISCAL_DOCUMENT_STATUSES = [
|
|
8
|
+
"PENDING",
|
|
9
|
+
"SUBMITTED",
|
|
10
|
+
"AUTHORIZED",
|
|
11
|
+
"REJECTED",
|
|
12
|
+
"DENIED",
|
|
13
|
+
"CONTINGENCY",
|
|
14
|
+
"CANCELLED",
|
|
15
|
+
"REPLACED"
|
|
16
|
+
];
|
|
17
|
+
var OWED_VOIDS = ["LOOKUP_FIRST", "INUTILIZE", "CANCEL"];
|
|
18
|
+
function isLive(document) {
|
|
19
|
+
if (document.status === "REPLACED") return false;
|
|
20
|
+
return !(document.status === "REJECTED" && document.seriesKind === "ONLINE" && document.protocol === null);
|
|
21
|
+
}
|
|
22
|
+
__name(isLive, "isLive");
|
|
23
|
+
|
|
24
|
+
export {
|
|
25
|
+
FISCAL_DOCUMENT_MODELS,
|
|
26
|
+
FISCAL_DOCUMENT_STATUSES,
|
|
27
|
+
OWED_VOIDS,
|
|
28
|
+
isLive
|
|
29
|
+
};
|
|
30
|
+
//# sourceMappingURL=chunk-XQGW5HUG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/documents/types.ts"],"sourcesContent":["/**\n * The fiscal document record and its event log — the shape the package's\n * Prisma partial stores (`prisma/fiscal.prisma`, `FiscalDocument` and\n * `FiscalDocumentEvent`) and the state machine (`./machine`) transitions.\n *\n * A document is ONE number: one issuing point, one series, one `nNF`. A sale\n * that goes offline is a second document on the issuing point's contingency\n * series, and the first one is `REPLACED` (see `./machine`). The record is\n * keyed by an opaque `subjectId`: what the subject is (an order, a payment,\n * several orders) is the host's to know, never this package's.\n */\n\nimport type { SaleForDocument } from \"../sale/types\";\nimport type { SefazEnvironment, SidecarErrorClass } from \"../sidecar/types\";\n\n/** The document model: NF-e (55) or NFC-e (65). NFS-e is not a model of this package yet (FUT-2242). */\nexport type FiscalDocumentModel = \"NFE\" | \"NFCE\";\n\nexport const FISCAL_DOCUMENT_MODELS: readonly FiscalDocumentModel[] = [\"NFE\", \"NFCE\"];\n\n/**\n * - `PENDING`: numbered and stored, not yet handed to the issuer.\n * - `SUBMITTED`: handed to the issuer; no final answer yet (a retry is owed).\n * - `AUTHORIZED`: SEFAZ authorised it. The only state a cancel leaves.\n * - `REJECTED`: refused (SEFAZ's `cStat`, or a request the service refuses as\n * malformed). Final; its number was not spent at SEFAZ and is inutilized.\n * - `DENIED`: a denial of use. Final; the number IS spent.\n * - `CONTINGENCY`: signed offline (`tpEmis = 9`), owed a transmission.\n * - `CANCELLED`: an authorised document cancelled at SEFAZ.\n * - `REPLACED`: its sale moved to another document (the contingency one);\n * its number is settled apart (`numberVoid`).\n */\nexport type FiscalDocumentStatus =\n | \"PENDING\"\n | \"SUBMITTED\"\n | \"AUTHORIZED\"\n | \"REJECTED\"\n | \"DENIED\"\n | \"CONTINGENCY\"\n | \"CANCELLED\"\n | \"REPLACED\";\n\nexport const FISCAL_DOCUMENT_STATUSES: readonly FiscalDocumentStatus[] = [\n \"PENDING\",\n \"SUBMITTED\",\n \"AUTHORIZED\",\n \"REJECTED\",\n \"DENIED\",\n \"CONTINGENCY\",\n \"CANCELLED\",\n \"REPLACED\",\n];\n\n/** Which of the issuing point's series the number came from. */\nexport type SeriesKind = \"ONLINE\" | \"CONTINGENCY\";\n\n/**\n * What is still owed on a number SEFAZ never used, so the sequence has no\n * unexplained gap:\n *\n * - `null`: nothing — the number is a document (authorised, denied, owed a\n * transmission) or still in flight.\n * - `LOOKUP_FIRST`: a request went out with no answer before the sale moved\n * to contingency; look the key up before deciding.\n * - `INUTILIZE`: never used at SEFAZ; inutilize it.\n * - `CANCEL`: the lookup found it authorised after all; cancel it.\n * - `INUTILIZED` / `CANCELLED`: settled.\n * - `DENIED`: settled — the lookup found the number denied, which spends it.\n */\nexport type NumberVoid = \"LOOKUP_FIRST\" | \"INUTILIZE\" | \"CANCEL\" | \"INUTILIZED\" | \"CANCELLED\" | \"DENIED\";\n\n/** The `numberVoid` values that still owe the sweep a call. */\nexport const OWED_VOIDS: readonly NumberVoid[] = [\"LOOKUP_FIRST\", \"INUTILIZE\", \"CANCEL\"];\n\n/** The order figures a document carries, in integer cents. */\nexport interface DocumentTotals {\n /** What the buyer pays: Σ line values − Σ discounts. */\n readonly totalCents: number;\n readonly discountCents: number;\n readonly cbsCents: number;\n readonly ibsUfCents: number;\n readonly ibsMunCents: number;\n}\n\n/**\n * Whether the document is the one its subject stands on. At most one live\n * document per (owner, subject, model): a REPLACED one is not, nor an online\n * one SEFAZ rejected (its number is voided and the sale is issued again) —\n * unless a lookup had found it authorised (its protocol is kept). A\n * REJECTED contingency NFC-e stays live: the buyer holds its DANFE, and the\n * store corrects and resends it under the same number.\n */\nexport function isLive(document: Pick<FiscalDocument, \"status\" | \"seriesKind\" | \"protocol\">): boolean {\n if (document.status === \"REPLACED\") return false;\n // An online rejection with a protocol known (a lookup found it SEFAZ's) is still the sale's.\n return !(document.status === \"REJECTED\" && document.seriesKind === \"ONLINE\" && document.protocol === null);\n}\n\n/** One fiscal document. */\nexport interface FiscalDocument {\n readonly id: string;\n /** The emitter profile's owner: an opaque id the host maps (a store, a company). */\n readonly ownerId: string;\n /** The issuer's CNPJ: SEFAZ numbers by CNPJ, model and series, so the counters do too. */\n readonly issuerCnpj: string;\n /** What the document is FOR, opaque: the host links it to its orders. */\n readonly subjectId: string;\n readonly issuingPointId: string;\n readonly model: FiscalDocumentModel;\n readonly environment: SefazEnvironment;\n readonly seriesKind: SeriesKind;\n readonly series: number;\n readonly number: number;\n /** `cNF`, drawn once: a retried call yields the same key. */\n readonly keyCode: string;\n readonly status: FiscalDocumentStatus;\n /** The sale as sent, issuer and number filled in. Never a secret. */\n readonly sale: SaleForDocument;\n readonly totals: DocumentTotals;\n /** The buyer's CPF/CNPJ at issue time, or `null`. */\n readonly buyerTaxId: string | null;\n readonly accessKey: string | null;\n /** The authorisation (or denial) protocol. */\n readonly protocol: string | null;\n /** The last SEFAZ `cStat`, or the service's named code. */\n readonly statusCode: string | null;\n readonly statusReason: string | null;\n /** The class of the last failed call, or `null`. */\n readonly lastErrorClass: SidecarErrorClass | null;\n /** A request went out and neither it nor its lookup was answered. */\n readonly outcomeUnknown: boolean;\n /** `dhEmi`. */\n readonly issuedAt: string;\n readonly authorizedAt: string | null;\n readonly contingency: { readonly since: string; readonly reason: string } | null;\n readonly cancelledAt: string | null;\n readonly cancelReason: string | null;\n readonly cancelProtocol: string | null;\n /** The document this one's sale moved to. */\n readonly replacedById: string | null;\n readonly numberVoid: NumberVoid | null;\n /** Storage keys: the signed or authorised XML, and the cancel or inutilization event's XML. */\n readonly xmlKey: string | null;\n readonly eventXmlKey: string | null;\n /** Calls made to the issuer for this document. */\n readonly attempts: number;\n /** Failed steps in a row (a retry, a deferred settlement); any progress resets it. */\n readonly failures: number;\n /** When the sweep (or the contingency transmission) may take it again; `null` when nothing is owed. */\n readonly nextAttemptAt: string | null;\n /**\n * A person must look: a settlement SEFAZ refused, or too many failures in a\n * row. The sweep leaves it alone until someone releases it.\n */\n readonly attention: boolean;\n /** When the 24-hour contingency deadline warning went out. */\n readonly deadlineWarnedAt: string | null;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\n/** What the state machine was fed: the kind of the input that made the event. */\nexport type DocumentEventKind =\n | \"SUBMIT\"\n | \"AUTHORIZE\"\n | \"DENY\"\n | \"REJECT\"\n | \"RETRY\"\n | \"SIGN_OFFLINE\"\n | \"REPLACE\"\n | \"CANCEL\"\n | \"LOOKUP\"\n | \"INUTILIZE\"\n | \"DEFER\"\n | \"RESIGN\"\n | \"RELEASE\"\n | \"WARN\";\n\n/**\n * One transition, as stored. `answer` is what the fiscal service answered,\n * verbatim but for any secret-named key (`scrubSecrets`), so the record is the\n * evidence of what SEFAZ said, the `MarketplaceInboxEvent.payload` habit.\n */\nexport interface FiscalDocumentEvent {\n readonly documentId: string;\n readonly kind: DocumentEventKind;\n readonly fromStatus: FiscalDocumentStatus;\n readonly toStatus: FiscalDocumentStatus;\n readonly at: string;\n readonly errorClass: SidecarErrorClass | null;\n readonly code: string | null;\n readonly answer: unknown;\n}\n"],"mappings":";;;;;AAkBO,IAAM,yBAAyD,CAAC,OAAO,MAAM;AAwB7E,IAAM,2BAA4D;AAAA,EACvE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAqBO,IAAM,aAAoC,CAAC,gBAAgB,aAAa,QAAQ;AAoBhF,SAAS,OAAO,UAA+E;AACpG,MAAI,SAAS,WAAW,WAAY,QAAO;AAE3C,SAAO,EAAE,SAAS,WAAW,cAAc,SAAS,eAAe,YAAY,SAAS,aAAa;AACvG;AAJgB;","names":[]}
|