@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,265 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The DANFE NFC-e as ESC/POS-ready lines, read from the document's XML —
|
|
3
|
+
* the authorised `nfeProc`, or the signed XML of a document issued offline,
|
|
4
|
+
* which prints the contingency variant. No provider returns ESC/POS and a
|
|
5
|
+
* register offline has nothing else to print, so the package renders it.
|
|
6
|
+
*
|
|
7
|
+
* The paper follows the Manual do DANFE NFC-e's divisions, in order (the
|
|
8
|
+
* FULL DANFE, items included):
|
|
9
|
+
*
|
|
10
|
+
* I the issuer: name, CNPJ, IE, address
|
|
11
|
+
* II the document's title
|
|
12
|
+
* III the items: code, description, quantity, unit, unit value, total
|
|
13
|
+
* IV the totals: item count, total, discounts, amount due, payments, change
|
|
14
|
+
* V the fiscal message: homologation, contingency, where to look the key up, the key
|
|
15
|
+
* VI the consumer
|
|
16
|
+
* VII the number, series, issue time, and the authorisation protocol
|
|
17
|
+
* VIII the QR code, then the taxpayer's message and the approximate taxes
|
|
18
|
+
*
|
|
19
|
+
* Each line is `{ text, align, emphasis }`, the shape `@12-apps/thermal-printing`
|
|
20
|
+
* encodes, laid out for the column count of the roll (Font A: 32 columns on
|
|
21
|
+
* 58 mm, 48 on 80 mm); the QR line carries `qrCode` for the host to rasterise.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { FiscalDocumentError } from "../documents/errors";
|
|
25
|
+
import type { DanfeNfceLabels } from "./labels";
|
|
26
|
+
import { DANFE_LABEL_KEYS } from "./labels";
|
|
27
|
+
import { accessKeyOf, element, elements, text } from "./xml";
|
|
28
|
+
|
|
29
|
+
export type DanfeDivision = "I" | "II" | "III" | "IV" | "V" | "VI" | "VII" | "VIII";
|
|
30
|
+
|
|
31
|
+
export interface DanfeLine {
|
|
32
|
+
readonly division: DanfeDivision;
|
|
33
|
+
readonly text: string;
|
|
34
|
+
readonly align: "left" | "center";
|
|
35
|
+
readonly emphasis: "normal" | "bold";
|
|
36
|
+
/** Present on the QR line only: the URL the code encodes. */
|
|
37
|
+
readonly qrCode?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export type PaperWidth = 58 | 80;
|
|
41
|
+
|
|
42
|
+
export const DANFE_COLUMNS: Readonly<Record<PaperWidth, number>> = { 58: 32, 80: 48 };
|
|
43
|
+
|
|
44
|
+
export interface DanfeNfceInput {
|
|
45
|
+
/** The `nfeProc` of an authorised document, or the signed XML of one issued offline. */
|
|
46
|
+
readonly xml: string;
|
|
47
|
+
readonly paperWidth: PaperWidth;
|
|
48
|
+
readonly labels: DanfeNfceLabels;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** `1234` cents → `12,34`; thousands with a dot, as the DANFE prints money. */
|
|
52
|
+
export function money(value: string | null): string {
|
|
53
|
+
const cents = Math.round(Number(value ?? "0") * 100);
|
|
54
|
+
const whole = Math.trunc(Math.abs(cents) / 100).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
|
|
55
|
+
return `${cents < 0 ? "-" : ""}${whole},${String(Math.abs(cents) % 100).padStart(2, "0")}`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function quantity(value: string | null): string {
|
|
59
|
+
return Number(value ?? "0").toLocaleString("en-US", { maximumFractionDigits: 4, useGrouping: false }).replace(".", ",");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A word longer than the width (a URL) cut into width-long pieces: nothing is dropped. */
|
|
63
|
+
function pieces(word: string, width: number): string[] {
|
|
64
|
+
const out: string[] = [];
|
|
65
|
+
for (let at = 0; at < word.length; at += width) out.push(word.slice(at, at + width));
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Wrap a text at the width, breaking on spaces where it can. */
|
|
70
|
+
export function wrap(value: string, width: number): string[] {
|
|
71
|
+
const words = value
|
|
72
|
+
.trim()
|
|
73
|
+
.split(/\s+/)
|
|
74
|
+
.filter((word) => word !== "")
|
|
75
|
+
.flatMap((word) => pieces(word, width));
|
|
76
|
+
const lines: string[] = [];
|
|
77
|
+
let current = "";
|
|
78
|
+
for (const word of words) {
|
|
79
|
+
const candidate = current === "" ? word : `${current} ${word}`;
|
|
80
|
+
if (candidate.length <= width) {
|
|
81
|
+
current = candidate;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (current !== "") lines.push(current);
|
|
85
|
+
current = word;
|
|
86
|
+
}
|
|
87
|
+
if (current !== "") lines.push(current);
|
|
88
|
+
return lines.length > 0 ? lines : [""];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** `label ……… value` across the width. */
|
|
92
|
+
function spread(label: string, value: string, width: number): string {
|
|
93
|
+
const gap = width - label.length - value.length;
|
|
94
|
+
return gap >= 1 ? `${label}${" ".repeat(gap)}${value}` : `${label} ${value}`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function groupKey(key: string): string {
|
|
98
|
+
return key.replace(/(.{4})/g, "$1 ").trim();
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
class Paper {
|
|
102
|
+
readonly lines: DanfeLine[] = [];
|
|
103
|
+
constructor(readonly width: number) {}
|
|
104
|
+
|
|
105
|
+
add(division: DanfeDivision, value: string, align: DanfeLine["align"] = "left", emphasis: DanfeLine["emphasis"] = "normal"): void {
|
|
106
|
+
for (const piece of wrap(value, this.width)) this.lines.push({ division, text: piece, align, emphasis });
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* `label ……… value` on one line when it fits; otherwise the label wraps and
|
|
111
|
+
* the value closes its last line, or takes a line of its own, right-aligned.
|
|
112
|
+
* Nothing passes the roll's width.
|
|
113
|
+
*/
|
|
114
|
+
pair(division: DanfeDivision, label: string, value: string, emphasis: DanfeLine["emphasis"] = "normal"): void {
|
|
115
|
+
const labelLines = wrap(label, this.width);
|
|
116
|
+
const last = labelLines.pop() ?? "";
|
|
117
|
+
for (const piece of labelLines) this.lines.push({ division, text: piece, align: "left", emphasis });
|
|
118
|
+
const closing = last.length + 1 + value.length <= this.width ? [spread(last, value, this.width)] : [last, value.padStart(this.width)];
|
|
119
|
+
for (const piece of closing) this.lines.push({ division, text: piece, align: "left", emphasis });
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
rule(division: DanfeDivision): void {
|
|
123
|
+
this.lines.push({ division, text: "-".repeat(this.width), align: "left", emphasis: "normal" });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
interface Parsed {
|
|
128
|
+
readonly infNFe: string;
|
|
129
|
+
readonly ide: string;
|
|
130
|
+
readonly emit: string;
|
|
131
|
+
readonly total: string;
|
|
132
|
+
/** `infNFeSupl`, beside `infNFe`: the QR code and the lookup URL. */
|
|
133
|
+
readonly supl: string;
|
|
134
|
+
readonly accessKey: string;
|
|
135
|
+
readonly contingency: boolean;
|
|
136
|
+
/** The authorisation protocol, once SEFAZ has answered (the `nfeProc`). */
|
|
137
|
+
readonly infProt: string | null;
|
|
138
|
+
readonly homologation: boolean;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function parse(xml: string): Parsed {
|
|
142
|
+
const infNFe = element(xml, "infNFe");
|
|
143
|
+
const ide = infNFe === null ? null : element(infNFe, "ide");
|
|
144
|
+
const emit = infNFe === null ? null : element(infNFe, "emit");
|
|
145
|
+
const accessKey = accessKeyOf(xml);
|
|
146
|
+
if (infNFe === null || ide === null || emit === null || accessKey === null) {
|
|
147
|
+
throw new FiscalDocumentError("INVALID_INPUT", "the XML is not an NF-e: no infNFe, ide, emit or access key.");
|
|
148
|
+
}
|
|
149
|
+
if (text(ide, "mod") !== "65") throw new FiscalDocumentError("INVALID_INPUT", "the XML is not an NFC-e (model 65).");
|
|
150
|
+
return {
|
|
151
|
+
infNFe,
|
|
152
|
+
ide,
|
|
153
|
+
emit,
|
|
154
|
+
total: element(infNFe, "ICMSTot") ?? "",
|
|
155
|
+
supl: element(xml, "infNFeSupl") ?? "",
|
|
156
|
+
accessKey,
|
|
157
|
+
contingency: text(ide, "tpEmis") === "9",
|
|
158
|
+
infProt: element(xml, "infProt"),
|
|
159
|
+
homologation: text(ide, "tpAmb") === "2",
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function issuerPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {
|
|
164
|
+
const address = element(doc.emit, "enderEmit");
|
|
165
|
+
paper.add("I", text(doc.emit, "xNome") ?? "", "center", "bold");
|
|
166
|
+
paper.add("I", `${labels.cnpj} ${text(doc.emit, "CNPJ") ?? ""} ${labels.stateRegistration} ${text(doc.emit, "IE") ?? ""}`, "center");
|
|
167
|
+
const street = [text(address, "xLgr"), text(address, "nro"), text(address, "xBairro"), text(address, "xMun"), text(address, "UF")];
|
|
168
|
+
paper.add("I", street.filter((part) => part !== null && part !== "").join(", "), "center");
|
|
169
|
+
paper.add("II", labels.title, "center", "bold");
|
|
170
|
+
paper.rule("II");
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function itemsPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): number {
|
|
174
|
+
paper.add("III", labels.itemsHeader);
|
|
175
|
+
const items = elements(doc.infNFe, "det");
|
|
176
|
+
for (const det of items) {
|
|
177
|
+
const prod = element(det, "prod");
|
|
178
|
+
paper.add("III", `${text(prod, "cProd") ?? ""} ${text(prod, "xProd") ?? ""}`);
|
|
179
|
+
const amount = `${quantity(text(prod, "qCom"))} ${text(prod, "uCom") ?? ""} x ${money(text(prod, "vUnCom"))}`;
|
|
180
|
+
paper.pair("III", amount, money(text(prod, "vProd")));
|
|
181
|
+
}
|
|
182
|
+
paper.rule("III");
|
|
183
|
+
return items.length;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function totalsPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels, count: number): void {
|
|
187
|
+
paper.pair("IV", labels.itemCount, String(count));
|
|
188
|
+
paper.pair("IV", labels.totalValue, money(text(doc.total, "vProd")));
|
|
189
|
+
const discount = text(doc.total, "vDesc");
|
|
190
|
+
if (discount !== null && Number(discount) > 0) paper.pair("IV", labels.discounts, money(discount));
|
|
191
|
+
paper.pair("IV", labels.amountDue, money(text(doc.total, "vNF")), "bold");
|
|
192
|
+
paper.add("IV", labels.paymentHeader);
|
|
193
|
+
for (const detPag of elements(doc.infNFe, "detPag")) {
|
|
194
|
+
const code = text(detPag, "tPag") ?? "";
|
|
195
|
+
paper.pair("IV", text(detPag, "xPag") ?? labels.paymentMethods[code] ?? code, money(text(detPag, "vPag")));
|
|
196
|
+
}
|
|
197
|
+
const change = text(element(doc.infNFe, "pag"), "vTroco");
|
|
198
|
+
if (change !== null && Number(change) > 0) paper.pair("IV", labels.change, money(change));
|
|
199
|
+
paper.rule("IV");
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function fiscalMessagePart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {
|
|
203
|
+
if (doc.homologation) paper.add("V", labels.homologation, "center", "bold");
|
|
204
|
+
if (doc.contingency) paper.add("V", labels.contingency, "center", "bold");
|
|
205
|
+
// Offline and not yet authorised: ONE copy, the consumer's (reprints are the same paper).
|
|
206
|
+
if (doc.contingency && doc.infProt === null) {
|
|
207
|
+
paper.add("V", labels.pendingAuthorization, "center", "bold");
|
|
208
|
+
paper.add("V", labels.consumerCopy, "center", "bold");
|
|
209
|
+
}
|
|
210
|
+
paper.add("V", labels.lookupByKey, "center");
|
|
211
|
+
paper.add("V", text(doc.supl, "urlChave") ?? "", "center");
|
|
212
|
+
paper.add("V", groupKey(doc.accessKey), "center");
|
|
213
|
+
paper.rule("V");
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function consumerPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {
|
|
217
|
+
const dest = element(doc.infNFe, "dest");
|
|
218
|
+
const id = text(dest, "CPF") ?? text(dest, "CNPJ") ?? text(dest, "idEstrangeiro");
|
|
219
|
+
if (id === null) {
|
|
220
|
+
paper.add("VI", labels.unidentifiedConsumer, "center");
|
|
221
|
+
} else {
|
|
222
|
+
paper.add("VI", `${labels.consumer} ${id}`, "center");
|
|
223
|
+
const name = text(dest, "xNome");
|
|
224
|
+
if (name !== null) paper.add("VI", name, "center");
|
|
225
|
+
}
|
|
226
|
+
paper.rule("VI");
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function identificationPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {
|
|
230
|
+
const issued = (text(doc.ide, "dhEmi") ?? "").replace("T", " ").slice(0, 19);
|
|
231
|
+
paper.add("VII", `${labels.number} ${text(doc.ide, "nNF") ?? ""} ${labels.series} ${text(doc.ide, "serie") ?? ""} ${issued}`, "center", "bold");
|
|
232
|
+
const { infProt } = doc;
|
|
233
|
+
if (infProt !== null) {
|
|
234
|
+
paper.add("VII", `${labels.protocol} ${text(infProt, "nProt") ?? ""}`, "center");
|
|
235
|
+
paper.add("VII", `${labels.authorizedAt} ${(text(infProt, "dhRecbto") ?? "").replace("T", " ").slice(0, 19)}`, "center");
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function qrPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {
|
|
240
|
+
const qrCode = text(doc.supl, "qrCode");
|
|
241
|
+
if (qrCode === null) throw new FiscalDocumentError("INVALID_INPUT", "the NFC-e XML carries no QR code (infNFeSupl/qrCode).");
|
|
242
|
+
paper.add("VIII", labels.qrCaption, "center");
|
|
243
|
+
paper.lines.push({ division: "VIII", text: "", align: "center", emphasis: "normal", qrCode });
|
|
244
|
+
const message = text(element(doc.infNFe, "infAdic"), "infCpl");
|
|
245
|
+
if (message !== null && message !== "") paper.add("VIII", message);
|
|
246
|
+
const taxes = text(doc.total, "vTotTrib");
|
|
247
|
+
if (taxes !== null && Number(taxes) > 0) paper.add("VIII", `${labels.approximateTaxes} ${money(taxes)}`);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export function renderDanfeNfce(input: DanfeNfceInput): DanfeLine[] {
|
|
251
|
+
const missing = DANFE_LABEL_KEYS.filter((key) => input.labels?.[key] === undefined);
|
|
252
|
+
if (missing.length > 0) throw new FiscalDocumentError("INVALID_INPUT", `labels is missing: ${missing.join(", ")}.`);
|
|
253
|
+
const width = DANFE_COLUMNS[input.paperWidth];
|
|
254
|
+
if (width === undefined) throw new FiscalDocumentError("INVALID_INPUT", "paperWidth must be 58 or 80.");
|
|
255
|
+
const doc = parse(input.xml);
|
|
256
|
+
const paper = new Paper(width);
|
|
257
|
+
issuerPart(paper, doc, input.labels);
|
|
258
|
+
const count = itemsPart(paper, doc, input.labels);
|
|
259
|
+
totalsPart(paper, doc, input.labels, count);
|
|
260
|
+
fiscalMessagePart(paper, doc, input.labels);
|
|
261
|
+
consumerPart(paper, doc, input.labels);
|
|
262
|
+
identificationPart(paper, doc, input.labels);
|
|
263
|
+
qrPart(paper, doc, input.labels);
|
|
264
|
+
return paper.lines;
|
|
265
|
+
}
|
package/src/danfe/xml.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading the few fields a DANFE prints out of an NF-e XML, with no parser
|
|
3
|
+
* dependency. The XML is SEFAZ's own layout, written by the fiscal service: no
|
|
4
|
+
* attributes are read but `Id`, no namespaces matter, and text is either plain
|
|
5
|
+
* (entity-escaped) or one CDATA section (the QR code).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const ENTITIES: Readonly<Record<string, string>> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
|
9
|
+
|
|
10
|
+
function decode(text: string): string {
|
|
11
|
+
const cdata = /^<!\[CDATA\[([\s\S]*)\]\]>$/.exec(text.trim());
|
|
12
|
+
if (cdata !== null) return cdata[1] ?? "";
|
|
13
|
+
return text.replace(/&(amp|lt|gt|quot|apos|#\d+|#x[0-9a-f]+);/gi, (_, name: string) => {
|
|
14
|
+
if (name.startsWith("#x") || name.startsWith("#X")) return String.fromCodePoint(parseInt(name.slice(2), 16));
|
|
15
|
+
if (name.startsWith("#")) return String.fromCodePoint(Number(name.slice(1)));
|
|
16
|
+
return ENTITIES[name.toLowerCase()] ?? "";
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The inner XML of the first `<tag>` (with or without attributes), or `null`. */
|
|
21
|
+
export function element(xml: string, tag: string): string | null {
|
|
22
|
+
const match = new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`).exec(xml);
|
|
23
|
+
return match === null ? null : (match[1] ?? "");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The decoded text of the first `<tag>`, or `null`. */
|
|
27
|
+
export function text(xml: string | null, tag: string): string | null {
|
|
28
|
+
if (xml === null) return null;
|
|
29
|
+
const inner = element(xml, tag);
|
|
30
|
+
return inner === null ? null : decode(inner);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Every `<tag …>…</tag>` block, in order. */
|
|
34
|
+
export function elements(xml: string, tag: string): string[] {
|
|
35
|
+
return [...xml.matchAll(new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, "g"))].map((match) => match[1] ?? "");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The access key from `<infNFe Id="NFe…">`. */
|
|
39
|
+
export function accessKeyOf(xml: string): string | null {
|
|
40
|
+
const start = xml.indexOf("<infNFe");
|
|
41
|
+
if (start === -1) return null;
|
|
42
|
+
const end = xml.indexOf(">", start);
|
|
43
|
+
const openTag = xml.slice(start, end === -1 ? xml.length : end);
|
|
44
|
+
return /\sId="NFe([0-9A-Z]{44})"/.exec(openTag)?.[1] ?? null;
|
|
45
|
+
}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What every step of the document service shares: the ports, the clock, the
|
|
3
|
+
* host's words written into a document, and the two writes everything goes
|
|
4
|
+
* through — numbering a new document, and persisting one transition with the
|
|
5
|
+
* schedule and the person's flag it implies.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { Issuer, SigningMaterial } from "../issuer/port";
|
|
9
|
+
import { FISCAL_ISSUE } from "../manifest/permissions";
|
|
10
|
+
import { FiscalDocumentError } from "./errors";
|
|
11
|
+
import { computeAccessKey, drawKeyCode, issuerOf, localIso, totalsOf } from "./helpers";
|
|
12
|
+
import { type DocumentInput, type Transition, transition } from "./machine";
|
|
13
|
+
import type { DocumentStorage, FiscalStore, SaleDraft, SaleSource } from "./ports";
|
|
14
|
+
import type { EmitterProfile, IssuingPoint } from "./profile";
|
|
15
|
+
import type { SigningIdentities } from "./signing";
|
|
16
|
+
import { type FiscalDocument, type FiscalDocumentModel, OWED_VOIDS, type SeriesKind } from "./types";
|
|
17
|
+
|
|
18
|
+
export { assertDraftFits, computeAccessKey, draftOf, drawKeyCode, isValidAccessKey, issuerOf, localIso, totalsOf, xmlKeys } from "./helpers";
|
|
19
|
+
|
|
20
|
+
/** Twin of `@12-apps/wiring/ports`' `NotifyPort`: never throws. */
|
|
21
|
+
export interface FiscalNotifyPort {
|
|
22
|
+
emit(event: {
|
|
23
|
+
readonly type: string;
|
|
24
|
+
readonly recipient: { readonly tenantId: string; readonly permission: string };
|
|
25
|
+
readonly payload: unknown;
|
|
26
|
+
}): Promise<unknown>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The words SEFAZ receives in a document, an event or a request — the host's,
|
|
31
|
+
* in the host's language, 15 to 255 characters each. No default: a library
|
|
32
|
+
* that wrote them would be writing a fiscal statement for its host.
|
|
33
|
+
*/
|
|
34
|
+
export interface FiscalReasons {
|
|
35
|
+
/** `xJust` of a document signed offline. */
|
|
36
|
+
readonly contingency: string;
|
|
37
|
+
/** Why an unused number is inutilized. */
|
|
38
|
+
readonly inutilization: string;
|
|
39
|
+
/** Why a document found authorised after its sale moved to contingency is cancelled. */
|
|
40
|
+
readonly substitution: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface FiscalDocumentsConfig {
|
|
44
|
+
readonly store: FiscalStore;
|
|
45
|
+
readonly issuer: Issuer;
|
|
46
|
+
readonly signing: SigningIdentities;
|
|
47
|
+
readonly storage: DocumentStorage;
|
|
48
|
+
readonly sales: SaleSource;
|
|
49
|
+
readonly notify: FiscalNotifyPort;
|
|
50
|
+
readonly now: () => Date;
|
|
51
|
+
/** The owner's UTC offset at an instant (`-03:00`): `dhEmi` and `dhCont` are local times. */
|
|
52
|
+
readonly utcOffset: (ownerId: string, at: Date) => string | Promise<string>;
|
|
53
|
+
readonly reasons: FiscalReasons;
|
|
54
|
+
/**
|
|
55
|
+
* How long a document owing a step waits before the sweep takes it again,
|
|
56
|
+
* the base of the backoff: each failure in a row doubles it, up to 64×.
|
|
57
|
+
*/
|
|
58
|
+
readonly staleAfterMs: number;
|
|
59
|
+
/**
|
|
60
|
+
* How late an online NFC-e may still be sent with its `dhEmi`. SEFAZ refuses
|
|
61
|
+
* a late one (704, "data-hora de emissão atrasada"; five minutes in most
|
|
62
|
+
* states — the host's, per state). Past it, a stale online NFC-e at a point
|
|
63
|
+
* with a contingency series goes offline instead of being sent again.
|
|
64
|
+
*/
|
|
65
|
+
readonly nfceOnlineToleranceMs: number;
|
|
66
|
+
/** Ids for new documents. */
|
|
67
|
+
readonly newId: () => string;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export const FISCAL_DOCUMENT_REJECTED = "fiscal.document-rejected";
|
|
71
|
+
export const FISCAL_CERTIFICATE_EXPIRING = "fiscal.certificate-expiring";
|
|
72
|
+
export const FISCAL_DOCUMENT_NEEDS_ATTENTION = "fiscal.document-needs-attention";
|
|
73
|
+
export const FISCAL_CONTINGENCY_DEADLINE = "fiscal.contingency-deadline";
|
|
74
|
+
|
|
75
|
+
const REQUIRED_PORTS = ["store", "issuer", "signing", "storage", "sales", "notify"] as const;
|
|
76
|
+
const REQUIRED_FUNCTIONS = ["now", "utcOffset", "newId"] as const;
|
|
77
|
+
const REASONS = ["contingency", "inutilization", "substitution"] as const;
|
|
78
|
+
const DURATIONS = ["staleAfterMs", "nfceOnlineToleranceMs"] as const;
|
|
79
|
+
|
|
80
|
+
export function assertConfig(config: FiscalDocumentsConfig): void {
|
|
81
|
+
const missing = [
|
|
82
|
+
...REQUIRED_PORTS.filter((port) => config?.[port] === undefined || config[port] === null),
|
|
83
|
+
...REQUIRED_FUNCTIONS.filter((fn) => typeof config?.[fn] !== "function"),
|
|
84
|
+
...DURATIONS.filter((name) => !Number.isInteger(config?.[name]) || config[name] <= 0),
|
|
85
|
+
];
|
|
86
|
+
if (missing.length > 0) throw new TypeError(`createFiscalDocuments needs ${missing.join(", ")}.`);
|
|
87
|
+
for (const name of REASONS) assertReason(config.reasons?.[name], `reasons.${name}`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function assertReason(text: unknown, name: string): asserts text is string {
|
|
91
|
+
if (typeof text !== "string" || text.trim().length < 15 || text.length > 255) {
|
|
92
|
+
throw new FiscalDocumentError("INVALID_INPUT", `${name} must be 15 to 255 characters.`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The backoff never grows past 64 × `staleAfterMs`. */
|
|
97
|
+
const MAX_BACKOFF_DOUBLINGS = 6;
|
|
98
|
+
|
|
99
|
+
/** Whether a document still owes the sweep (or the transmission) a call. */
|
|
100
|
+
function owesWork(document: FiscalDocument): boolean {
|
|
101
|
+
if (document.status === "PENDING" || document.status === "SUBMITTED" || document.status === "CONTINGENCY") return true;
|
|
102
|
+
return document.numberVoid !== null && OWED_VOIDS.includes(document.numberVoid);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export class FiscalContext {
|
|
106
|
+
constructor(readonly config: FiscalDocumentsConfig) {}
|
|
107
|
+
|
|
108
|
+
nowIso(): string {
|
|
109
|
+
return this.config.now().toISOString();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async localNow(ownerId: string): Promise<string> {
|
|
113
|
+
const at = this.config.now();
|
|
114
|
+
return localIso(at, await this.config.utcOffset(ownerId, at));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** When a document may be taken again: never, when nothing is owed or a person must look. */
|
|
118
|
+
nextAttemptAt(document: FiscalDocument): string | null {
|
|
119
|
+
if (document.attention || !owesWork(document)) return null;
|
|
120
|
+
const wait = this.config.staleAfterMs * 2 ** Math.min(document.failures, MAX_BACKOFF_DOUBLINGS);
|
|
121
|
+
return new Date(this.config.now().getTime() + wait).toISOString();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The machine's step, scheduled. */
|
|
125
|
+
scheduled(document: FiscalDocument, input: DocumentInput): Transition {
|
|
126
|
+
const step = transition(document, input, this.nowIso());
|
|
127
|
+
return { ...step, document: { ...step.document, nextAttemptAt: this.nextAttemptAt(step.document) } };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Persist one transition; a lost race is a `CONFLICT`, never a silent
|
|
132
|
+
* overwrite. A document that has just come to need a person is announced.
|
|
133
|
+
*/
|
|
134
|
+
async advance(document: FiscalDocument, input: DocumentInput): Promise<FiscalDocument> {
|
|
135
|
+
const step = this.scheduled(document, input);
|
|
136
|
+
if (!(await this.config.store.saveTransition(document, step))) {
|
|
137
|
+
throw new FiscalDocumentError("CONFLICT", `document ${document.id} moved while ${input.kind} was applied.`);
|
|
138
|
+
}
|
|
139
|
+
if (step.document.attention && !document.attention) await this.announceAttention(step.document);
|
|
140
|
+
return step.document;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async announceAttention(document: FiscalDocument): Promise<void> {
|
|
144
|
+
await this.config.notify.emit({
|
|
145
|
+
type: FISCAL_DOCUMENT_NEEDS_ATTENTION,
|
|
146
|
+
recipient: { tenantId: document.ownerId, permission: FISCAL_ISSUE },
|
|
147
|
+
payload: {
|
|
148
|
+
documentId: document.id,
|
|
149
|
+
subjectId: document.subjectId,
|
|
150
|
+
model: document.model,
|
|
151
|
+
status: document.status,
|
|
152
|
+
numberVoid: document.numberVoid,
|
|
153
|
+
series: document.series,
|
|
154
|
+
number: document.number,
|
|
155
|
+
code: document.statusCode,
|
|
156
|
+
reason: document.statusReason ?? "",
|
|
157
|
+
failures: document.failures,
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
material(profile: EmitterProfile): Promise<SigningMaterial> {
|
|
163
|
+
return this.config.signing[profile.signingIdentity].materialFor(profile);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async requireProfile(ownerId: string): Promise<EmitterProfile> {
|
|
167
|
+
const profile = await this.config.store.getProfile(ownerId);
|
|
168
|
+
if (profile === null) throw new FiscalDocumentError("NOT_FOUND", `owner ${ownerId} has no emitter profile.`);
|
|
169
|
+
return profile;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async requirePoint(ownerId: string, issuingPointId: string): Promise<IssuingPoint> {
|
|
173
|
+
const point = await this.config.store.getIssuingPoint(ownerId, issuingPointId);
|
|
174
|
+
if (point === null) throw new FiscalDocumentError("NOT_FOUND", `owner ${ownerId} has no issuing point ${issuingPointId}.`);
|
|
175
|
+
return point;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Draw the next number of a series and store the PENDING document built on
|
|
180
|
+
* it, together. With `replacing`, that document is REPLACED by this one in
|
|
181
|
+
* the same transaction (going offline), so a crash leaves exactly one live.
|
|
182
|
+
*/
|
|
183
|
+
async createNumbered(input: {
|
|
184
|
+
readonly profile: EmitterProfile;
|
|
185
|
+
readonly point: IssuingPoint;
|
|
186
|
+
readonly subjectId: string;
|
|
187
|
+
readonly model: FiscalDocumentModel;
|
|
188
|
+
readonly seriesKind: SeriesKind;
|
|
189
|
+
readonly draft: SaleDraft;
|
|
190
|
+
readonly replacing?: FiscalDocument;
|
|
191
|
+
}): Promise<FiscalDocument> {
|
|
192
|
+
const { profile, point, draft } = input;
|
|
193
|
+
const series = input.seriesKind === "ONLINE" ? point.onlineSeries : point.contingencySeries;
|
|
194
|
+
if (series === null) throw new FiscalDocumentError("INVALID_INPUT", `issuing point ${point.id} has no contingency series.`);
|
|
195
|
+
const issuedAt = await this.localNow(profile.ownerId);
|
|
196
|
+
const at = this.nowIso();
|
|
197
|
+
const id = this.config.newId();
|
|
198
|
+
const replace =
|
|
199
|
+
input.replacing === undefined
|
|
200
|
+
? undefined
|
|
201
|
+
: { previous: input.replacing, transition: this.scheduled(input.replacing, { kind: "REPLACE", replacedById: id }) };
|
|
202
|
+
const request = {
|
|
203
|
+
ownerId: profile.ownerId,
|
|
204
|
+
issuerCnpj: profile.cnpj,
|
|
205
|
+
issuingPointId: point.id,
|
|
206
|
+
environment: profile.environment,
|
|
207
|
+
model: input.model,
|
|
208
|
+
seriesKind: input.seriesKind,
|
|
209
|
+
series,
|
|
210
|
+
};
|
|
211
|
+
return this.config.store.createDocument(
|
|
212
|
+
request,
|
|
213
|
+
(number) => {
|
|
214
|
+
const keyCode = drawKeyCode(number);
|
|
215
|
+
const sale = { ...draft, series, number, keyCode, issuedAt, issuer: issuerOf(profile) };
|
|
216
|
+
return {
|
|
217
|
+
id,
|
|
218
|
+
ownerId: profile.ownerId,
|
|
219
|
+
issuerCnpj: profile.cnpj,
|
|
220
|
+
subjectId: input.subjectId,
|
|
221
|
+
issuingPointId: point.id,
|
|
222
|
+
model: input.model,
|
|
223
|
+
environment: profile.environment,
|
|
224
|
+
seriesKind: input.seriesKind,
|
|
225
|
+
series,
|
|
226
|
+
number,
|
|
227
|
+
keyCode,
|
|
228
|
+
status: "PENDING",
|
|
229
|
+
sale,
|
|
230
|
+
totals: totalsOf(draft),
|
|
231
|
+
buyerTaxId: draft.buyer?.document.number ?? null,
|
|
232
|
+
accessKey: computeAccessKey({ sale, model: input.model, seriesKind: input.seriesKind }),
|
|
233
|
+
protocol: null,
|
|
234
|
+
statusCode: null,
|
|
235
|
+
statusReason: null,
|
|
236
|
+
lastErrorClass: null,
|
|
237
|
+
outcomeUnknown: false,
|
|
238
|
+
issuedAt,
|
|
239
|
+
authorizedAt: null,
|
|
240
|
+
contingency: null,
|
|
241
|
+
cancelledAt: null,
|
|
242
|
+
cancelReason: null,
|
|
243
|
+
cancelProtocol: null,
|
|
244
|
+
replacedById: null,
|
|
245
|
+
numberVoid: null,
|
|
246
|
+
xmlKey: null,
|
|
247
|
+
eventXmlKey: null,
|
|
248
|
+
attempts: 0,
|
|
249
|
+
failures: 0,
|
|
250
|
+
nextAttemptAt: new Date(Date.parse(at) + this.config.staleAfterMs).toISOString(),
|
|
251
|
+
attention: false,
|
|
252
|
+
deadlineWarnedAt: null,
|
|
253
|
+
createdAt: at,
|
|
254
|
+
updatedAt: at,
|
|
255
|
+
};
|
|
256
|
+
},
|
|
257
|
+
replace,
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every refusal the document module makes, as a typed error with a `code`.
|
|
3
|
+
* A message never carries a certificate, a password or a CSC: the module
|
|
4
|
+
* never holds one long enough to quote it.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export type FiscalDocumentErrorCode =
|
|
8
|
+
/** The state machine has no such transition from the document's state. */
|
|
9
|
+
| "TRANSITION_REFUSED"
|
|
10
|
+
/** An input is missing, malformed or out of range. */
|
|
11
|
+
| "INVALID_INPUT"
|
|
12
|
+
/** No emitter profile, issuing point or document under that id. */
|
|
13
|
+
| "NOT_FOUND"
|
|
14
|
+
/** The profile does not let the package issue (`documentPolicy`), or lacks what issuing needs. */
|
|
15
|
+
| "NOT_ISSUABLE"
|
|
16
|
+
/** The signing identity is declared but not built yet (`PLATFORM`). */
|
|
17
|
+
| "NOT_SUPPORTED"
|
|
18
|
+
/** A series' counter passed 999 999 999. */
|
|
19
|
+
| "SERIES_EXHAUSTED"
|
|
20
|
+
/** Another worker advanced the document first; re-read it. */
|
|
21
|
+
| "CONFLICT"
|
|
22
|
+
/** The subject already has a live document of that model (the per-subject guard). */
|
|
23
|
+
| "SUBJECT_HAS_DOCUMENT"
|
|
24
|
+
/** The document's state has no paper to print (only AUTHORIZED, or CONTINGENCY awaiting transmission). */
|
|
25
|
+
| "NOT_PRINTABLE"
|
|
26
|
+
/**
|
|
27
|
+
* A resend of a rejected contingency NFC-e would change what the buyer's
|
|
28
|
+
* DANFE prints and its QR encodes (the total, the buyer's document): such a
|
|
29
|
+
* sale needs a new note, issued by a person.
|
|
30
|
+
*/
|
|
31
|
+
| "RESEND_CHANGES_PRINTED_FIELDS"
|
|
32
|
+
/** A `RETURN` quotes no document (`referencedDocuments` is absent or empty). */
|
|
33
|
+
| "RETURN_NEEDS_REFERENCE"
|
|
34
|
+
/**
|
|
35
|
+
* A `RETURN` asked of an NFC-e. An NFC-e has no return purpose: the return is
|
|
36
|
+
* an NF-e (model 55) of entry that references the NFC-e's key.
|
|
37
|
+
*/
|
|
38
|
+
| "RETURN_ON_NFCE";
|
|
39
|
+
|
|
40
|
+
export class FiscalDocumentError extends Error {
|
|
41
|
+
readonly code: FiscalDocumentErrorCode;
|
|
42
|
+
|
|
43
|
+
constructor(code: FiscalDocumentErrorCode, message: string) {
|
|
44
|
+
super(`[fiscal/documents] ${code}: ${message}`);
|
|
45
|
+
this.name = "FiscalDocumentError";
|
|
46
|
+
this.code = code;
|
|
47
|
+
}
|
|
48
|
+
}
|