@12-apps/fiscal 1.0.0 → 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 +152 -7
- 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-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 +3 -246
- 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 +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 +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 +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 +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/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 +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 +292 -0
- package/src/sidecar/index.ts +9 -0
- package/src/sidecar/types.ts +243 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__name
|
|
3
|
+
} from "./chunk-7QVYU63E.js";
|
|
4
|
+
|
|
5
|
+
// src/danfe/xml.ts
|
|
6
|
+
var ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
|
7
|
+
function decode(text2) {
|
|
8
|
+
const cdata = /^<!\[CDATA\[([\s\S]*)\]\]>$/.exec(text2.trim());
|
|
9
|
+
if (cdata !== null) return cdata[1] ?? "";
|
|
10
|
+
return text2.replace(/&(amp|lt|gt|quot|apos|#\d+|#x[0-9a-f]+);/gi, (_, name) => {
|
|
11
|
+
if (name.startsWith("#x") || name.startsWith("#X")) return String.fromCodePoint(parseInt(name.slice(2), 16));
|
|
12
|
+
if (name.startsWith("#")) return String.fromCodePoint(Number(name.slice(1)));
|
|
13
|
+
return ENTITIES[name.toLowerCase()] ?? "";
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
__name(decode, "decode");
|
|
17
|
+
function element(xml, tag) {
|
|
18
|
+
const match = new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`).exec(xml);
|
|
19
|
+
return match === null ? null : match[1] ?? "";
|
|
20
|
+
}
|
|
21
|
+
__name(element, "element");
|
|
22
|
+
function text(xml, tag) {
|
|
23
|
+
if (xml === null) return null;
|
|
24
|
+
const inner = element(xml, tag);
|
|
25
|
+
return inner === null ? null : decode(inner);
|
|
26
|
+
}
|
|
27
|
+
__name(text, "text");
|
|
28
|
+
function elements(xml, tag) {
|
|
29
|
+
return [...xml.matchAll(new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, "g"))].map((match) => match[1] ?? "");
|
|
30
|
+
}
|
|
31
|
+
__name(elements, "elements");
|
|
32
|
+
function accessKeyOf(xml) {
|
|
33
|
+
const start = xml.indexOf("<infNFe");
|
|
34
|
+
if (start === -1) return null;
|
|
35
|
+
const end = xml.indexOf(">", start);
|
|
36
|
+
const openTag = xml.slice(start, end === -1 ? xml.length : end);
|
|
37
|
+
return /\sId="NFe([0-9A-Z]{44})"/.exec(openTag)?.[1] ?? null;
|
|
38
|
+
}
|
|
39
|
+
__name(accessKeyOf, "accessKeyOf");
|
|
40
|
+
|
|
41
|
+
export {
|
|
42
|
+
element,
|
|
43
|
+
text,
|
|
44
|
+
elements,
|
|
45
|
+
accessKeyOf
|
|
46
|
+
};
|
|
47
|
+
//# sourceMappingURL=chunk-PNTKG3DZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/danfe/xml.ts"],"sourcesContent":["/**\n * Reading the few fields a DANFE prints out of an NF-e XML, with no parser\n * dependency. The XML is SEFAZ's own layout, written by the fiscal service: no\n * attributes are read but `Id`, no namespaces matter, and text is either plain\n * (entity-escaped) or one CDATA section (the QR code).\n */\n\nconst ENTITIES: Readonly<Record<string, string>> = { amp: \"&\", lt: \"<\", gt: \">\", quot: '\"', apos: \"'\" };\n\nfunction decode(text: string): string {\n const cdata = /^<!\\[CDATA\\[([\\s\\S]*)\\]\\]>$/.exec(text.trim());\n if (cdata !== null) return cdata[1] ?? \"\";\n return text.replace(/&(amp|lt|gt|quot|apos|#\\d+|#x[0-9a-f]+);/gi, (_, name: string) => {\n if (name.startsWith(\"#x\") || name.startsWith(\"#X\")) return String.fromCodePoint(parseInt(name.slice(2), 16));\n if (name.startsWith(\"#\")) return String.fromCodePoint(Number(name.slice(1)));\n return ENTITIES[name.toLowerCase()] ?? \"\";\n });\n}\n\n/** The inner XML of the first `<tag>` (with or without attributes), or `null`. */\nexport function element(xml: string, tag: string): string | null {\n const match = new RegExp(`<${tag}(?:\\\\s[^>]*)?>([\\\\s\\\\S]*?)</${tag}>`).exec(xml);\n return match === null ? null : (match[1] ?? \"\");\n}\n\n/** The decoded text of the first `<tag>`, or `null`. */\nexport function text(xml: string | null, tag: string): string | null {\n if (xml === null) return null;\n const inner = element(xml, tag);\n return inner === null ? null : decode(inner);\n}\n\n/** Every `<tag …>…</tag>` block, in order. */\nexport function elements(xml: string, tag: string): string[] {\n return [...xml.matchAll(new RegExp(`<${tag}(?:\\\\s[^>]*)?>([\\\\s\\\\S]*?)</${tag}>`, \"g\"))].map((match) => match[1] ?? \"\");\n}\n\n/** The access key from `<infNFe Id=\"NFe…\">`. */\nexport function accessKeyOf(xml: string): string | null {\n const start = xml.indexOf(\"<infNFe\");\n if (start === -1) return null;\n const end = xml.indexOf(\">\", start);\n const openTag = xml.slice(start, end === -1 ? xml.length : end);\n return /\\sId=\"NFe([0-9A-Z]{44})\"/.exec(openTag)?.[1] ?? null;\n}\n"],"mappings":";;;;;AAOA,IAAM,WAA6C,EAAE,KAAK,KAAK,IAAI,KAAK,IAAI,KAAK,MAAM,KAAK,MAAM,IAAI;AAEtG,SAAS,OAAOA,OAAsB;AACpC,QAAM,QAAQ,8BAA8B,KAAKA,MAAK,KAAK,CAAC;AAC5D,MAAI,UAAU,KAAM,QAAO,MAAM,CAAC,KAAK;AACvC,SAAOA,MAAK,QAAQ,8CAA8C,CAAC,GAAG,SAAiB;AACrF,QAAI,KAAK,WAAW,IAAI,KAAK,KAAK,WAAW,IAAI,EAAG,QAAO,OAAO,cAAc,SAAS,KAAK,MAAM,CAAC,GAAG,EAAE,CAAC;AAC3G,QAAI,KAAK,WAAW,GAAG,EAAG,QAAO,OAAO,cAAc,OAAO,KAAK,MAAM,CAAC,CAAC,CAAC;AAC3E,WAAO,SAAS,KAAK,YAAY,CAAC,KAAK;AAAA,EACzC,CAAC;AACH;AARS;AAWF,SAAS,QAAQ,KAAa,KAA4B;AAC/D,QAAM,QAAQ,IAAI,OAAO,IAAI,GAAG,+BAA+B,GAAG,GAAG,EAAE,KAAK,GAAG;AAC/E,SAAO,UAAU,OAAO,OAAQ,MAAM,CAAC,KAAK;AAC9C;AAHgB;AAMT,SAAS,KAAK,KAAoB,KAA4B;AACnE,MAAI,QAAQ,KAAM,QAAO;AACzB,QAAM,QAAQ,QAAQ,KAAK,GAAG;AAC9B,SAAO,UAAU,OAAO,OAAO,OAAO,KAAK;AAC7C;AAJgB;AAOT,SAAS,SAAS,KAAa,KAAuB;AAC3D,SAAO,CAAC,GAAG,IAAI,SAAS,IAAI,OAAO,IAAI,GAAG,+BAA+B,GAAG,KAAK,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,UAAU,MAAM,CAAC,KAAK,EAAE;AACvH;AAFgB;AAKT,SAAS,YAAY,KAA4B;AACtD,QAAM,QAAQ,IAAI,QAAQ,SAAS;AACnC,MAAI,UAAU,GAAI,QAAO;AACzB,QAAM,MAAM,IAAI,QAAQ,KAAK,KAAK;AAClC,QAAM,UAAU,IAAI,MAAM,OAAO,QAAQ,KAAK,IAAI,SAAS,GAAG;AAC9D,SAAO,2BAA2B,KAAK,OAAO,IAAI,CAAC,KAAK;AAC1D;AANgB;","names":["text"]}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import {
|
|
2
|
+
FISCAL_DOCUMENT_MODELS
|
|
3
|
+
} from "./chunk-XQGW5HUG.js";
|
|
4
|
+
import {
|
|
5
|
+
FiscalDocumentError
|
|
6
|
+
} from "./chunk-X6MRDUYH.js";
|
|
7
|
+
import {
|
|
8
|
+
__name
|
|
9
|
+
} from "./chunk-7QVYU63E.js";
|
|
10
|
+
|
|
11
|
+
// src/documents/profile.ts
|
|
12
|
+
var DOCUMENT_POLICIES = ["ISSUED_HERE", "ISSUED_ELSEWHERE", "NONE"];
|
|
13
|
+
var SIGNING_IDENTITY_KINDS = ["STORE_CERTIFICATE", "PLATFORM"];
|
|
14
|
+
function viewOf(profile) {
|
|
15
|
+
const { certificateCiphertext, certificatePasswordCiphertext, cscCiphertext, ...rest } = profile;
|
|
16
|
+
return {
|
|
17
|
+
...rest,
|
|
18
|
+
hasCertificate: certificateCiphertext !== null && certificatePasswordCiphertext !== null,
|
|
19
|
+
hasCsc: cscCiphertext !== null && profile.cscId !== null
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
__name(viewOf, "viewOf");
|
|
23
|
+
|
|
24
|
+
// src/documents/profile-input.ts
|
|
25
|
+
var UFS = [
|
|
26
|
+
"AC",
|
|
27
|
+
"AL",
|
|
28
|
+
"AM",
|
|
29
|
+
"AP",
|
|
30
|
+
"BA",
|
|
31
|
+
"CE",
|
|
32
|
+
"DF",
|
|
33
|
+
"ES",
|
|
34
|
+
"GO",
|
|
35
|
+
"MA",
|
|
36
|
+
"MG",
|
|
37
|
+
"MS",
|
|
38
|
+
"MT",
|
|
39
|
+
"PA",
|
|
40
|
+
"PB",
|
|
41
|
+
"PE",
|
|
42
|
+
"PI",
|
|
43
|
+
"PR",
|
|
44
|
+
"RJ",
|
|
45
|
+
"RN",
|
|
46
|
+
"RO",
|
|
47
|
+
"RR",
|
|
48
|
+
"RS",
|
|
49
|
+
"SC",
|
|
50
|
+
"SE",
|
|
51
|
+
"SP",
|
|
52
|
+
"TO"
|
|
53
|
+
];
|
|
54
|
+
var TAX_REGIMES = ["SIMPLES", "SIMPLES_EXCESS", "NORMAL", "MEI"];
|
|
55
|
+
var ENGINE_REGIMES = ["SIMPLES", "SIMPLES_IBS_CBS_REGULAR", "REGIME_REGULAR", "MEI", "NAO_CONTRIBUINTE"];
|
|
56
|
+
var ENVIRONMENTS = ["homologacao", "producao"];
|
|
57
|
+
function invalid(field, why) {
|
|
58
|
+
throw new FiscalDocumentError("INVALID_INPUT", `${field} ${why}.`);
|
|
59
|
+
}
|
|
60
|
+
__name(invalid, "invalid");
|
|
61
|
+
function objectOf(value, field, keys) {
|
|
62
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) invalid(field, "must be an object");
|
|
63
|
+
const unknown = Object.keys(value).filter((key) => !keys.includes(key));
|
|
64
|
+
if (unknown.length > 0) invalid(field, `has unknown keys: ${unknown.join(", ")}`);
|
|
65
|
+
const missing = keys.filter((key) => !(key in value));
|
|
66
|
+
if (missing.length > 0) invalid(field, `is missing: ${missing.join(", ")}`);
|
|
67
|
+
return value;
|
|
68
|
+
}
|
|
69
|
+
__name(objectOf, "objectOf");
|
|
70
|
+
function text(body, key, pattern = /^.{1,200}$/s) {
|
|
71
|
+
const value = body[key];
|
|
72
|
+
if (typeof value !== "string" || !pattern.test(value)) invalid(key, "is not valid");
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
__name(text, "text");
|
|
76
|
+
function nullableText(body, key, pattern) {
|
|
77
|
+
return body[key] === null ? null : text(body, key, pattern);
|
|
78
|
+
}
|
|
79
|
+
__name(nullableText, "nullableText");
|
|
80
|
+
function oneOf(body, key, values) {
|
|
81
|
+
const value = body[key];
|
|
82
|
+
if (typeof value !== "string" || !values.includes(value)) invalid(key, `must be one of ${values.join(", ")}`);
|
|
83
|
+
return value;
|
|
84
|
+
}
|
|
85
|
+
__name(oneOf, "oneOf");
|
|
86
|
+
function integer(body, key, min, max) {
|
|
87
|
+
const value = body[key];
|
|
88
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) invalid(key, `must be an integer from ${min} to ${max}`);
|
|
89
|
+
return value;
|
|
90
|
+
}
|
|
91
|
+
__name(integer, "integer");
|
|
92
|
+
var DATE = /^\d{4}-\d{2}-\d{2}$/;
|
|
93
|
+
var INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
|
|
94
|
+
var ADDRESS_KEYS = ["street", "number", "complement", "district", "municipalityIbge", "municipalityName", "uf", "postalCode", "phone"];
|
|
95
|
+
function addressOf(value) {
|
|
96
|
+
const body = objectOf(value, "address", ADDRESS_KEYS);
|
|
97
|
+
return {
|
|
98
|
+
street: text(body, "street"),
|
|
99
|
+
number: text(body, "number", /^.{1,60}$/),
|
|
100
|
+
complement: nullableText(body, "complement"),
|
|
101
|
+
district: text(body, "district"),
|
|
102
|
+
municipalityIbge: text(body, "municipalityIbge", /^\d{7}$/),
|
|
103
|
+
municipalityName: text(body, "municipalityName"),
|
|
104
|
+
uf: oneOf(body, "uf", UFS),
|
|
105
|
+
postalCode: text(body, "postalCode", /^\d{8}$/),
|
|
106
|
+
phone: nullableText(body, "phone", /^\d{6,14}$/)
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
__name(addressOf, "addressOf");
|
|
110
|
+
var PROFILE_KEYS = [
|
|
111
|
+
"cnpj",
|
|
112
|
+
"stateRegistration",
|
|
113
|
+
"municipalRegistration",
|
|
114
|
+
"cnae",
|
|
115
|
+
"legalName",
|
|
116
|
+
"tradeName",
|
|
117
|
+
"taxRegime",
|
|
118
|
+
"regime",
|
|
119
|
+
"regimeEffectiveFrom",
|
|
120
|
+
"restaurantRegime",
|
|
121
|
+
"address",
|
|
122
|
+
"environment",
|
|
123
|
+
"documentPolicy",
|
|
124
|
+
"signingIdentity",
|
|
125
|
+
"cscId",
|
|
126
|
+
"cscToken",
|
|
127
|
+
"consentRecordedAt"
|
|
128
|
+
];
|
|
129
|
+
function parseProfileInput(value) {
|
|
130
|
+
const body = objectOf(value, "profile", PROFILE_KEYS);
|
|
131
|
+
if (typeof body["restaurantRegime"] !== "boolean") invalid("restaurantRegime", "must be a boolean");
|
|
132
|
+
return {
|
|
133
|
+
cnpj: text(body, "cnpj", /^[0-9A-Z]{12}\d{2}$/),
|
|
134
|
+
stateRegistration: text(body, "stateRegistration", /^(\d{2,14}|ISENTO)$/),
|
|
135
|
+
municipalRegistration: nullableText(body, "municipalRegistration", /^[0-9A-Za-z]{1,15}$/),
|
|
136
|
+
cnae: nullableText(body, "cnae", /^\d{7}$/),
|
|
137
|
+
legalName: text(body, "legalName", /^.{2,60}$/s),
|
|
138
|
+
tradeName: nullableText(body, "tradeName", /^.{1,60}$/s),
|
|
139
|
+
taxRegime: oneOf(body, "taxRegime", TAX_REGIMES),
|
|
140
|
+
regime: oneOf(body, "regime", ENGINE_REGIMES),
|
|
141
|
+
regimeEffectiveFrom: text(body, "regimeEffectiveFrom", DATE),
|
|
142
|
+
restaurantRegime: body["restaurantRegime"],
|
|
143
|
+
address: addressOf(body["address"]),
|
|
144
|
+
environment: oneOf(body, "environment", ENVIRONMENTS),
|
|
145
|
+
documentPolicy: oneOf(body, "documentPolicy", DOCUMENT_POLICIES),
|
|
146
|
+
signingIdentity: oneOf(body, "signingIdentity", SIGNING_IDENTITY_KINDS),
|
|
147
|
+
cscId: nullableText(body, "cscId", /^\d{1,6}$/),
|
|
148
|
+
cscToken: nullableText(body, "cscToken", /^[0-9A-Za-z]{16,36}$/),
|
|
149
|
+
consentRecordedAt: nullableText(body, "consentRecordedAt", INSTANT)
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
__name(parseProfileInput, "parseProfileInput");
|
|
153
|
+
function parseCertificateUpload(value) {
|
|
154
|
+
const body = objectOf(value, "certificate", ["pfxBase64", "password"]);
|
|
155
|
+
return {
|
|
156
|
+
pfxBase64: text(body, "pfxBase64", /^[A-Za-z0-9+/]{100,}={0,2}$/),
|
|
157
|
+
password: text(body, "password", /^.{1,200}$/s)
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
__name(parseCertificateUpload, "parseCertificateUpload");
|
|
161
|
+
function parseIssuingPointInput(value) {
|
|
162
|
+
const body = objectOf(value, "issuingPoint", [
|
|
163
|
+
"id",
|
|
164
|
+
"model",
|
|
165
|
+
"onlineSeries",
|
|
166
|
+
"contingencySeries",
|
|
167
|
+
"firstOnlineNumber",
|
|
168
|
+
"firstContingencyNumber"
|
|
169
|
+
]);
|
|
170
|
+
const onlineSeries = integer(body, "onlineSeries", 0, 889);
|
|
171
|
+
const contingencySeries = body["contingencySeries"] === null ? null : integer(body, "contingencySeries", 0, 889);
|
|
172
|
+
if (contingencySeries === onlineSeries) invalid("contingencySeries", "must differ from onlineSeries");
|
|
173
|
+
return {
|
|
174
|
+
id: text(body, "id", /^[A-Za-z0-9_-]{1,64}$/),
|
|
175
|
+
model: oneOf(body, "model", FISCAL_DOCUMENT_MODELS),
|
|
176
|
+
onlineSeries,
|
|
177
|
+
contingencySeries,
|
|
178
|
+
firstOnlineNumber: integer(body, "firstOnlineNumber", 1, 999999999),
|
|
179
|
+
firstContingencyNumber: integer(body, "firstContingencyNumber", 1, 999999999)
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
__name(parseIssuingPointInput, "parseIssuingPointInput");
|
|
183
|
+
|
|
184
|
+
export {
|
|
185
|
+
DOCUMENT_POLICIES,
|
|
186
|
+
SIGNING_IDENTITY_KINDS,
|
|
187
|
+
viewOf,
|
|
188
|
+
parseProfileInput,
|
|
189
|
+
parseCertificateUpload,
|
|
190
|
+
parseIssuingPointInput
|
|
191
|
+
};
|
|
192
|
+
//# sourceMappingURL=chunk-RRFKYVLZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/documents/profile.ts","../src/documents/profile-input.ts"],"sourcesContent":["/**\n * The emitter profile and its issuing points — what moved INTO this package\n * from the host's tax profile (FUT-2231's decision block): the company data,\n * the address, the regime, the environment, the document policy, who signs,\n * the certificate (as ciphertext), the CSC (as ciphertext) and the series.\n *\n * Keyed by an opaque `ownerId` the host maps to its own tenant. What stays in\n * the host: the link to its tenant, where the settings screen sits, the CNPJ\n * lookup, the accountant, and the plan-driven DEFAULT of `documentPolicy`\n * (this package knows no plans, so it takes the value and never invents it).\n */\n\nimport type { TaxRegime } from \"../engine/types\";\nimport type { Address, IssuerTaxRegime } from \"../sale/types\";\nimport type { SefazEnvironment } from \"../sidecar/types\";\nimport type { FiscalDocumentModel } from \"./types\";\n\n/**\n * - `ISSUED_HERE`: this package issues the store's documents.\n * - `ISSUED_ELSEWHERE`: the store issues in its own system and the host\n * records the access key it types.\n * - `NONE`: no document.\n */\nexport type DocumentPolicy = \"ISSUED_HERE\" | \"ISSUED_ELSEWHERE\" | \"NONE\";\nexport const DOCUMENT_POLICIES: readonly DocumentPolicy[] = [\"ISSUED_HERE\", \"ISSUED_ELSEWHERE\", \"NONE\"];\n\n/**\n * Who signs. `STORE_CERTIFICATE`: the store's own A1, held encrypted through\n * the host's cipher. `PLATFORM`: the platform signing on the store's behalf\n * (LC 214/2025 art. 22 §12) — declared, answering `NOT_SUPPORTED` until it is\n * decided how that signature works (FUT-2229 q4). Its own field from the start,\n * so enabling it is an adapter, not a migration.\n */\nexport type SigningIdentityKind = \"STORE_CERTIFICATE\" | \"PLATFORM\";\nexport const SIGNING_IDENTITY_KINDS: readonly SigningIdentityKind[] = [\"STORE_CERTIFICATE\", \"PLATFORM\"];\n\nexport interface EmitterProfile {\n readonly ownerId: string;\n /** 14 characters; the 2026 alphanumeric CNPJ is accepted. */\n readonly cnpj: string;\n /** IE digits, or `ISENTO`. */\n readonly stateRegistration: string;\n readonly municipalRegistration: string | null;\n readonly cnae: string | null;\n readonly legalName: string;\n readonly tradeName: string | null;\n /** `CRT` on the document. */\n readonly taxRegime: IssuerTaxRegime;\n /** The IBS/CBS engine's regime, and the day it took effect (the Simples option is by semester). */\n readonly regime: TaxRegime;\n readonly regimeEffectiveFrom: string;\n /** LC 214/2025 arts. 273–276 apply to the store's prepared food. */\n readonly restaurantRegime: boolean;\n readonly address: Address & { readonly postalCode: string };\n readonly environment: SefazEnvironment;\n readonly documentPolicy: DocumentPolicy;\n readonly signingIdentity: SigningIdentityKind;\n /** The `.pfx` bytes (base64) through the host's cipher. Never in clear, never on the wire. */\n readonly certificateCiphertext: string | null;\n readonly certificatePasswordCiphertext: string | null;\n readonly certificateExpiresAt: string | null;\n readonly cscId: string | null;\n /** The CSC token through the host's cipher. */\n readonly cscCiphertext: string | null;\n /** The store's consent to `PLATFORM` signing (art. 22 §12). */\n readonly consentRecordedAt: string | null;\n readonly updatedAt: string;\n}\n\n/**\n * Where documents are issued from: an opaque id the host maps (a register, the\n * online store). A register has an ONLINE and a CONTINGENCY series; a point\n * that never goes offline has no contingency series. The package owns every\n * series' counter; no host keeps a second one.\n */\nexport interface IssuingPoint {\n readonly id: string;\n readonly ownerId: string;\n readonly model: FiscalDocumentModel;\n readonly onlineSeries: number;\n readonly contingencySeries: number | null;\n readonly createdAt: string;\n}\n\n/** The profile as the HTTP surface answers it: no ciphertext leaves the server. */\nexport type EmitterProfileView = Omit<\n EmitterProfile,\n \"certificateCiphertext\" | \"certificatePasswordCiphertext\" | \"cscCiphertext\"\n> & { readonly hasCertificate: boolean; readonly hasCsc: boolean };\n\nexport function viewOf(profile: EmitterProfile): EmitterProfileView {\n const { certificateCiphertext, certificatePasswordCiphertext, cscCiphertext, ...rest } = profile;\n return {\n ...rest,\n hasCertificate: certificateCiphertext !== null && certificatePasswordCiphertext !== null,\n hasCsc: cscCiphertext !== null && profile.cscId !== null,\n };\n}\n","/**\n * Reading the emitter profile and the certificate upload off a request body:\n * every field required (an absent value is `null`), unknown keys refused, and\n * every refusal a {@link FiscalDocumentError} `INVALID_INPUT` naming the\n * field — never its value, since the certificate upload carries secrets.\n */\n\nimport type { TaxRegime } from \"../engine/types\";\nimport type { Address, IssuerTaxRegime, Uf } from \"../sale/types\";\nimport type { SefazEnvironment } from \"../sidecar/types\";\nimport { FiscalDocumentError } from \"./errors\";\nimport { DOCUMENT_POLICIES, type DocumentPolicy, SIGNING_IDENTITY_KINDS, type SigningIdentityKind } from \"./profile\";\nimport { FISCAL_DOCUMENT_MODELS, type FiscalDocumentModel } from \"./types\";\n\n/** The profile fields a host writes; the secrets arrive through their own calls. */\nexport interface EmitterProfileInput {\n readonly cnpj: string;\n readonly stateRegistration: string;\n readonly municipalRegistration: string | null;\n readonly cnae: string | null;\n readonly legalName: string;\n readonly tradeName: string | null;\n readonly taxRegime: IssuerTaxRegime;\n readonly regime: TaxRegime;\n readonly regimeEffectiveFrom: string;\n readonly restaurantRegime: boolean;\n readonly address: Address & { readonly postalCode: string };\n readonly environment: SefazEnvironment;\n readonly documentPolicy: DocumentPolicy;\n readonly signingIdentity: SigningIdentityKind;\n readonly cscId: string | null;\n /** The CSC token in clear, encrypted on arrival; `null` keeps the stored one. */\n readonly cscToken: string | null;\n readonly consentRecordedAt: string | null;\n}\n\nexport interface CertificateUpload {\n readonly pfxBase64: string;\n readonly password: string;\n}\n\nexport interface IssuingPointInput {\n readonly id: string;\n readonly model: FiscalDocumentModel;\n readonly onlineSeries: number;\n readonly contingencySeries: number | null;\n readonly firstOnlineNumber: number;\n readonly firstContingencyNumber: number;\n}\n\ntype Body = Record<string, unknown>;\n\nconst UFS: readonly Uf[] = [\n \"AC\", \"AL\", \"AM\", \"AP\", \"BA\", \"CE\", \"DF\", \"ES\", \"GO\", \"MA\", \"MG\", \"MS\", \"MT\", \"PA\",\n \"PB\", \"PE\", \"PI\", \"PR\", \"RJ\", \"RN\", \"RO\", \"RR\", \"RS\", \"SC\", \"SE\", \"SP\", \"TO\",\n];\nconst TAX_REGIMES: readonly IssuerTaxRegime[] = [\"SIMPLES\", \"SIMPLES_EXCESS\", \"NORMAL\", \"MEI\"];\nconst ENGINE_REGIMES: readonly TaxRegime[] = [\"SIMPLES\", \"SIMPLES_IBS_CBS_REGULAR\", \"REGIME_REGULAR\", \"MEI\", \"NAO_CONTRIBUINTE\"];\nconst ENVIRONMENTS: readonly SefazEnvironment[] = [\"homologacao\", \"producao\"];\n\nfunction invalid(field: string, why: string): never {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `${field} ${why}.`);\n}\n\nfunction objectOf(value: unknown, field: string, keys: readonly string[]): Body {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) invalid(field, \"must be an object\");\n const unknown = Object.keys(value).filter((key) => !keys.includes(key));\n if (unknown.length > 0) invalid(field, `has unknown keys: ${unknown.join(\", \")}`);\n const missing = keys.filter((key) => !(key in value));\n if (missing.length > 0) invalid(field, `is missing: ${missing.join(\", \")}`);\n return value as Body;\n}\n\nfunction text(body: Body, key: string, pattern = /^.{1,200}$/s): string {\n const value = body[key];\n if (typeof value !== \"string\" || !pattern.test(value)) invalid(key, \"is not valid\");\n return value;\n}\n\nfunction nullableText(body: Body, key: string, pattern?: RegExp): string | null {\n return body[key] === null ? null : text(body, key, pattern);\n}\n\nfunction oneOf<T extends string>(body: Body, key: string, values: readonly T[]): T {\n const value = body[key];\n if (typeof value !== \"string\" || !values.includes(value as T)) invalid(key, `must be one of ${values.join(\", \")}`);\n return value as T;\n}\n\nfunction integer(body: Body, key: string, min: number, max: number): number {\n const value = body[key];\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < min || value > max) invalid(key, `must be an integer from ${min} to ${max}`);\n return value;\n}\n\nconst DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst INSTANT = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/;\nconst ADDRESS_KEYS = [\"street\", \"number\", \"complement\", \"district\", \"municipalityIbge\", \"municipalityName\", \"uf\", \"postalCode\", \"phone\"];\n\nfunction addressOf(value: unknown): Address & { readonly postalCode: string } {\n const body = objectOf(value, \"address\", ADDRESS_KEYS);\n return {\n street: text(body, \"street\"),\n number: text(body, \"number\", /^.{1,60}$/),\n complement: nullableText(body, \"complement\"),\n district: text(body, \"district\"),\n municipalityIbge: text(body, \"municipalityIbge\", /^\\d{7}$/),\n municipalityName: text(body, \"municipalityName\"),\n uf: oneOf(body, \"uf\", UFS),\n postalCode: text(body, \"postalCode\", /^\\d{8}$/),\n phone: nullableText(body, \"phone\", /^\\d{6,14}$/),\n };\n}\n\nconst PROFILE_KEYS = [\n \"cnpj\", \"stateRegistration\", \"municipalRegistration\", \"cnae\", \"legalName\", \"tradeName\", \"taxRegime\", \"regime\",\n \"regimeEffectiveFrom\", \"restaurantRegime\", \"address\", \"environment\", \"documentPolicy\", \"signingIdentity\", \"cscId\",\n \"cscToken\", \"consentRecordedAt\",\n];\n\nexport function parseProfileInput(value: unknown): EmitterProfileInput {\n const body = objectOf(value, \"profile\", PROFILE_KEYS);\n if (typeof body[\"restaurantRegime\"] !== \"boolean\") invalid(\"restaurantRegime\", \"must be a boolean\");\n return {\n cnpj: text(body, \"cnpj\", /^[0-9A-Z]{12}\\d{2}$/),\n stateRegistration: text(body, \"stateRegistration\", /^(\\d{2,14}|ISENTO)$/),\n municipalRegistration: nullableText(body, \"municipalRegistration\", /^[0-9A-Za-z]{1,15}$/),\n cnae: nullableText(body, \"cnae\", /^\\d{7}$/),\n legalName: text(body, \"legalName\", /^.{2,60}$/s),\n tradeName: nullableText(body, \"tradeName\", /^.{1,60}$/s),\n taxRegime: oneOf(body, \"taxRegime\", TAX_REGIMES),\n regime: oneOf(body, \"regime\", ENGINE_REGIMES),\n regimeEffectiveFrom: text(body, \"regimeEffectiveFrom\", DATE),\n restaurantRegime: body[\"restaurantRegime\"],\n address: addressOf(body[\"address\"]),\n environment: oneOf(body, \"environment\", ENVIRONMENTS),\n documentPolicy: oneOf(body, \"documentPolicy\", DOCUMENT_POLICIES),\n signingIdentity: oneOf(body, \"signingIdentity\", SIGNING_IDENTITY_KINDS),\n cscId: nullableText(body, \"cscId\", /^\\d{1,6}$/),\n cscToken: nullableText(body, \"cscToken\", /^[0-9A-Za-z]{16,36}$/),\n consentRecordedAt: nullableText(body, \"consentRecordedAt\", INSTANT),\n };\n}\n\nexport function parseCertificateUpload(value: unknown): CertificateUpload {\n const body = objectOf(value, \"certificate\", [\"pfxBase64\", \"password\"]);\n return {\n pfxBase64: text(body, \"pfxBase64\", /^[A-Za-z0-9+/]{100,}={0,2}$/),\n password: text(body, \"password\", /^.{1,200}$/s),\n };\n}\n\nexport function parseIssuingPointInput(value: unknown): IssuingPointInput {\n const body = objectOf(value, \"issuingPoint\", [\n \"id\", \"model\", \"onlineSeries\", \"contingencySeries\", \"firstOnlineNumber\", \"firstContingencyNumber\",\n ]);\n const onlineSeries = integer(body, \"onlineSeries\", 0, 889);\n const contingencySeries = body[\"contingencySeries\"] === null ? null : integer(body, \"contingencySeries\", 0, 889);\n if (contingencySeries === onlineSeries) invalid(\"contingencySeries\", \"must differ from onlineSeries\");\n return {\n id: text(body, \"id\", /^[A-Za-z0-9_-]{1,64}$/),\n model: oneOf(body, \"model\", FISCAL_DOCUMENT_MODELS),\n onlineSeries,\n contingencySeries,\n firstOnlineNumber: integer(body, \"firstOnlineNumber\", 1, 999_999_999),\n firstContingencyNumber: integer(body, \"firstContingencyNumber\", 1, 999_999_999),\n };\n}\n"],"mappings":";;;;;;;;;;;AAwBO,IAAM,oBAA+C,CAAC,eAAe,oBAAoB,MAAM;AAU/F,IAAM,yBAAyD,CAAC,qBAAqB,UAAU;AAwD/F,SAAS,OAAO,SAA6C;AAClE,QAAM,EAAE,uBAAuB,+BAA+B,eAAe,GAAG,KAAK,IAAI;AACzF,SAAO;AAAA,IACL,GAAG;AAAA,IACH,gBAAgB,0BAA0B,QAAQ,kCAAkC;AAAA,IACpF,QAAQ,kBAAkB,QAAQ,QAAQ,UAAU;AAAA,EACtD;AACF;AAPgB;;;ACtChB,IAAM,MAAqB;AAAA,EACzB;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAC9E;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAC1E;AACA,IAAM,cAA0C,CAAC,WAAW,kBAAkB,UAAU,KAAK;AAC7F,IAAM,iBAAuC,CAAC,WAAW,2BAA2B,kBAAkB,OAAO,kBAAkB;AAC/H,IAAM,eAA4C,CAAC,eAAe,UAAU;AAE5E,SAAS,QAAQ,OAAe,KAAoB;AAClD,QAAM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SAAS,sBAAsB;AAAA,IAClD;AAAA,IACA;AAAA,IACA,mBAAmB,QAAQ,MAAM,qBAAqB,GAAG,SAAW;AAAA,IACpE,wBAAwB,QAAQ,MAAM,0BAA0B,GAAG,SAAW;AAAA,EAChF;AACF;AAfgB;","names":[]}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import {
|
|
2
|
+
renderDanfeNfce
|
|
3
|
+
} from "./chunk-ALABGVPO.js";
|
|
4
|
+
import {
|
|
5
|
+
parseCertificateUpload,
|
|
6
|
+
parseIssuingPointInput,
|
|
7
|
+
parseProfileInput,
|
|
8
|
+
viewOf
|
|
9
|
+
} from "./chunk-RRFKYVLZ.js";
|
|
10
|
+
import {
|
|
11
|
+
FISCAL_DOCUMENT_MODELS
|
|
12
|
+
} from "./chunk-XQGW5HUG.js";
|
|
13
|
+
import {
|
|
14
|
+
FISCAL_CANCEL,
|
|
15
|
+
FISCAL_ISSUE,
|
|
16
|
+
FISCAL_MANAGE,
|
|
17
|
+
FISCAL_READ
|
|
18
|
+
} from "./chunk-3SDXLSG4.js";
|
|
19
|
+
import {
|
|
20
|
+
FiscalDocumentError
|
|
21
|
+
} from "./chunk-X6MRDUYH.js";
|
|
22
|
+
import {
|
|
23
|
+
__name
|
|
24
|
+
} from "./chunk-7QVYU63E.js";
|
|
25
|
+
|
|
26
|
+
// src/http.ts
|
|
27
|
+
var FISCAL_ERROR_STATUS = {
|
|
28
|
+
INVALID_INPUT: 400,
|
|
29
|
+
NOT_FOUND: 404,
|
|
30
|
+
NOT_ISSUABLE: 409,
|
|
31
|
+
NOT_SUPPORTED: 501,
|
|
32
|
+
TRANSITION_REFUSED: 409,
|
|
33
|
+
SERIES_EXHAUSTED: 409,
|
|
34
|
+
CONFLICT: 409,
|
|
35
|
+
SUBJECT_HAS_DOCUMENT: 409,
|
|
36
|
+
NOT_PRINTABLE: 409,
|
|
37
|
+
RESEND_CHANGES_PRINTED_FIELDS: 422
|
|
38
|
+
};
|
|
39
|
+
var PRINTABLE = /* @__PURE__ */ new Set(["AUTHORIZED", "CONTINGENCY"]);
|
|
40
|
+
var ok = /* @__PURE__ */ __name((data, status = 200) => ({ status, body: { data } }), "ok");
|
|
41
|
+
async function answering(run) {
|
|
42
|
+
try {
|
|
43
|
+
return await run();
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if (error instanceof FiscalDocumentError) {
|
|
46
|
+
return { status: FISCAL_ERROR_STATUS[error.code], body: { error: error.code, message: error.message } };
|
|
47
|
+
}
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
__name(answering, "answering");
|
|
52
|
+
function record(body) {
|
|
53
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
54
|
+
throw new FiscalDocumentError("INVALID_INPUT", "the body must be an object.");
|
|
55
|
+
}
|
|
56
|
+
return body;
|
|
57
|
+
}
|
|
58
|
+
__name(record, "record");
|
|
59
|
+
function stringField(body, key) {
|
|
60
|
+
const value = body[key];
|
|
61
|
+
if (typeof value !== "string" || value === "") throw new FiscalDocumentError("INVALID_INPUT", `${key} is required.`);
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
__name(stringField, "stringField");
|
|
65
|
+
function param(request, key) {
|
|
66
|
+
const value = request.params[key];
|
|
67
|
+
if (value === void 0 || value === "") throw new FiscalDocumentError("INVALID_INPUT", `${key} is required.`);
|
|
68
|
+
return value;
|
|
69
|
+
}
|
|
70
|
+
__name(param, "param");
|
|
71
|
+
var ISSUE_KEYS = /* @__PURE__ */ new Set(["subjectId", "issuingPointId", "model", "offline"]);
|
|
72
|
+
function issueBody(body) {
|
|
73
|
+
const fields = record(body);
|
|
74
|
+
const unknown = Object.keys(fields).filter((key) => !ISSUE_KEYS.has(key));
|
|
75
|
+
if (unknown.length > 0) throw new FiscalDocumentError("INVALID_INPUT", `unknown keys: ${unknown.join(", ")}.`);
|
|
76
|
+
const model = fields["model"];
|
|
77
|
+
if (!FISCAL_DOCUMENT_MODELS.includes(model)) throw new FiscalDocumentError("INVALID_INPUT", "model must be NFE or NFCE.");
|
|
78
|
+
const offline = fields["offline"] ?? false;
|
|
79
|
+
if (typeof offline !== "boolean") throw new FiscalDocumentError("INVALID_INPUT", "offline must be a boolean.");
|
|
80
|
+
if (offline && model !== "NFCE") throw new FiscalDocumentError("INVALID_INPUT", "only an NFC-e is issued offline.");
|
|
81
|
+
return { subjectId: stringField(fields, "subjectId"), issuingPointId: stringField(fields, "issuingPointId"), model, offline };
|
|
82
|
+
}
|
|
83
|
+
__name(issueBody, "issueBody");
|
|
84
|
+
function profileRoutes({ documents }) {
|
|
85
|
+
return [
|
|
86
|
+
{
|
|
87
|
+
method: "GET",
|
|
88
|
+
path: "/fiscal/profile",
|
|
89
|
+
permission: FISCAL_READ,
|
|
90
|
+
handle: /* @__PURE__ */ __name(({ actor }) => answering(async () => {
|
|
91
|
+
const profile = await documents.getProfile(actor.ownerId);
|
|
92
|
+
return ok(profile === null ? null : viewOf(profile));
|
|
93
|
+
}), "handle")
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
method: "PUT",
|
|
97
|
+
path: "/fiscal/profile",
|
|
98
|
+
permission: FISCAL_MANAGE,
|
|
99
|
+
handle: /* @__PURE__ */ __name(({ actor, body }) => answering(async () => ok(viewOf(await documents.saveProfile(actor.ownerId, parseProfileInput(body))))), "handle")
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
method: "PUT",
|
|
103
|
+
path: "/fiscal/profile/certificate",
|
|
104
|
+
permission: FISCAL_MANAGE,
|
|
105
|
+
handle: /* @__PURE__ */ __name(({ actor, body }) => answering(async () => ok(viewOf(await documents.uploadCertificate(actor.ownerId, parseCertificateUpload(body))))), "handle")
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
method: "GET",
|
|
109
|
+
path: "/fiscal/issuing-points",
|
|
110
|
+
permission: FISCAL_READ,
|
|
111
|
+
handle: /* @__PURE__ */ __name(({ actor }) => answering(async () => ok(await documents.listIssuingPoints(actor.ownerId))), "handle")
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
method: "POST",
|
|
115
|
+
path: "/fiscal/issuing-points",
|
|
116
|
+
permission: FISCAL_MANAGE,
|
|
117
|
+
handle: /* @__PURE__ */ __name(({ actor, body }) => answering(async () => ok(await documents.createIssuingPoint(actor.ownerId, parseIssuingPointInput(body)), 201)), "handle")
|
|
118
|
+
}
|
|
119
|
+
];
|
|
120
|
+
}
|
|
121
|
+
__name(profileRoutes, "profileRoutes");
|
|
122
|
+
function danfeRoute({ documents, storage, danfeLabels }) {
|
|
123
|
+
return {
|
|
124
|
+
method: "GET",
|
|
125
|
+
path: "/fiscal/documents/:documentId/danfe",
|
|
126
|
+
permission: FISCAL_READ,
|
|
127
|
+
handle: /* @__PURE__ */ __name((request) => answering(async () => {
|
|
128
|
+
const paper = Number(request.query["paper"] ?? "80");
|
|
129
|
+
if (paper !== 58 && paper !== 80) throw new FiscalDocumentError("INVALID_INPUT", "paper must be 58 or 80.");
|
|
130
|
+
const document = await documents.getDocument(request.actor.ownerId, param(request, "documentId"));
|
|
131
|
+
if (!PRINTABLE.has(document.status)) {
|
|
132
|
+
throw new FiscalDocumentError("NOT_PRINTABLE", `document ${document.id} is ${document.status}: only an AUTHORIZED or CONTINGENCY document prints.`);
|
|
133
|
+
}
|
|
134
|
+
const xml = document.model === "NFCE" && document.xmlKey !== null ? await storage.get(document.xmlKey) : null;
|
|
135
|
+
if (xml === null) throw new FiscalDocumentError("NOT_FOUND", `document ${document.id} has no NFC-e XML to print.`);
|
|
136
|
+
return ok(renderDanfeNfce({ xml, paperWidth: paper, labels: danfeLabels }));
|
|
137
|
+
}), "handle")
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
__name(danfeRoute, "danfeRoute");
|
|
141
|
+
function documentRoutes(config) {
|
|
142
|
+
const { documents } = config;
|
|
143
|
+
return [
|
|
144
|
+
{
|
|
145
|
+
method: "POST",
|
|
146
|
+
path: "/fiscal/documents",
|
|
147
|
+
permission: FISCAL_ISSUE,
|
|
148
|
+
handle: /* @__PURE__ */ __name(({ actor, body }) => answering(async () => {
|
|
149
|
+
const { offline, ...input } = issueBody(body);
|
|
150
|
+
const document = offline ? await documents.issueOffline({ ownerId: actor.ownerId, subjectId: input.subjectId, issuingPointId: input.issuingPointId }) : await documents.issue({ ownerId: actor.ownerId, ...input });
|
|
151
|
+
return ok(document);
|
|
152
|
+
}), "handle")
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
method: "GET",
|
|
156
|
+
path: "/fiscal/documents/:documentId",
|
|
157
|
+
permission: FISCAL_READ,
|
|
158
|
+
handle: /* @__PURE__ */ __name((request) => answering(async () => {
|
|
159
|
+
const documentId = param(request, "documentId");
|
|
160
|
+
const document = await documents.getDocument(request.actor.ownerId, documentId);
|
|
161
|
+
return ok({ document, events: await documents.listEvents(request.actor.ownerId, documentId) });
|
|
162
|
+
}), "handle")
|
|
163
|
+
},
|
|
164
|
+
{
|
|
165
|
+
method: "POST",
|
|
166
|
+
path: "/fiscal/documents/:documentId/cancel",
|
|
167
|
+
permission: FISCAL_CANCEL,
|
|
168
|
+
handle: /* @__PURE__ */ __name((request) => answering(async () => {
|
|
169
|
+
const reason = stringField(record(request.body), "reason");
|
|
170
|
+
const result = await documents.cancel({ ownerId: request.actor.ownerId, documentId: param(request, "documentId"), reason });
|
|
171
|
+
return result.failure === null ? ok(result.document) : { status: 422, body: { error: "ISSUER_FAILURE", failure: result.failure, data: result.document } };
|
|
172
|
+
}), "handle")
|
|
173
|
+
},
|
|
174
|
+
{
|
|
175
|
+
method: "POST",
|
|
176
|
+
path: "/fiscal/documents/:documentId/resend",
|
|
177
|
+
permission: FISCAL_ISSUE,
|
|
178
|
+
handle: /* @__PURE__ */ __name((request) => answering(
|
|
179
|
+
async () => ok(await documents.resendContingency({ ownerId: request.actor.ownerId, documentId: param(request, "documentId") }))
|
|
180
|
+
), "handle")
|
|
181
|
+
},
|
|
182
|
+
{
|
|
183
|
+
method: "POST",
|
|
184
|
+
path: "/fiscal/documents/:documentId/release",
|
|
185
|
+
permission: FISCAL_ISSUE,
|
|
186
|
+
handle: /* @__PURE__ */ __name((request) => answering(async () => ok(await documents.release({ ownerId: request.actor.ownerId, documentId: param(request, "documentId") }))), "handle")
|
|
187
|
+
},
|
|
188
|
+
{
|
|
189
|
+
method: "POST",
|
|
190
|
+
path: "/fiscal/documents/:documentId/lookup",
|
|
191
|
+
permission: FISCAL_READ,
|
|
192
|
+
handle: /* @__PURE__ */ __name((request) => answering(async () => ok(await documents.lookup({ ownerId: request.actor.ownerId, documentId: param(request, "documentId") }))), "handle")
|
|
193
|
+
},
|
|
194
|
+
danfeRoute(config)
|
|
195
|
+
];
|
|
196
|
+
}
|
|
197
|
+
__name(documentRoutes, "documentRoutes");
|
|
198
|
+
function createApiFiscal(config) {
|
|
199
|
+
if (config?.documents === void 0) throw new TypeError("createApiFiscal needs documents.");
|
|
200
|
+
if (config.storage === void 0) throw new TypeError("createApiFiscal needs storage.");
|
|
201
|
+
if (config.danfeLabels === void 0) throw new TypeError("createApiFiscal needs danfeLabels.");
|
|
202
|
+
return { routes: [...profileRoutes(config), ...documentRoutes(config)] };
|
|
203
|
+
}
|
|
204
|
+
__name(createApiFiscal, "createApiFiscal");
|
|
205
|
+
|
|
206
|
+
export {
|
|
207
|
+
FISCAL_ERROR_STATUS,
|
|
208
|
+
createApiFiscal
|
|
209
|
+
};
|
|
210
|
+
//# sourceMappingURL=chunk-V5ZQAAJT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/http.ts"],"sourcesContent":["/**\n * `createApiFiscal` — the fiscal HTTP surface as framework-neutral route\n * descriptors (the wiring contract's `http` capability, restated here\n * structurally: this package imports nothing from the contract at runtime,\n * and its manifest suite pins the twins).\n *\n * The package owns the paths, the bodies it reads (`./documents/profile-input`,\n * unknown keys refused), the `{ data }` envelope, the permission each route\n * needs and the status a refusal earns ({@link FISCAL_ERROR_STATUS}). The host\n * owns resolving WHO is calling into the opaque `ownerId` of its tenant, the\n * guards that check the declared permission, and every word a person reads:\n * an error answers a `code` for the host to word, never a sentence for a user.\n *\n * Nothing secret leaves: the profile answers `hasCertificate` / `hasCsc`, never\n * a ciphertext, and the certificate upload answers the profile view.\n */\n\nimport { type DanfeNfceLabels } from \"./danfe/labels\";\nimport { type PaperWidth, renderDanfeNfce } from \"./danfe/render\";\nimport { FiscalDocumentError, type FiscalDocumentErrorCode } from \"./documents/errors\";\nimport type { DocumentStorage } from \"./documents/ports\";\nimport { parseCertificateUpload, parseIssuingPointInput, parseProfileInput } from \"./documents/profile-input\";\nimport { viewOf } from \"./documents/profile\";\nimport type { FiscalDocuments } from \"./documents/service\";\nimport { FISCAL_DOCUMENT_MODELS, type FiscalDocumentModel } from \"./documents/types\";\nimport { FISCAL_CANCEL, FISCAL_ISSUE, FISCAL_MANAGE, FISCAL_READ } from \"./manifest/permissions\";\n\n/** The caller, as the host's adapter resolved it. */\nexport interface FiscalHttpActor {\n /** The emitter profile's owner: the host's tenant, mapped to an opaque id. */\n readonly ownerId: string;\n}\n\n/** Structural twin of the wiring contract's `WireRequest<FiscalHttpActor>`. */\nexport interface FiscalHttpRequest {\n actor: FiscalHttpActor;\n params: Record<string, string | undefined>;\n query: Record<string, string | undefined>;\n body?: unknown;\n}\n\n/** Structural twin of the wiring contract's `WireResponse`. */\nexport interface FiscalHttpResponse {\n status: number;\n body: unknown;\n}\n\n/** Structural twin of the wiring contract's `WireRoute<FiscalHttpActor>`. */\nexport interface FiscalRoute {\n method: \"GET\" | \"POST\" | \"PUT\";\n path: string;\n permission: string;\n handle(request: FiscalHttpRequest): Promise<FiscalHttpResponse>;\n}\n\nexport interface FiscalApiConfig {\n readonly documents: FiscalDocuments;\n /** Where the XMLs are, to render a DANFE from. */\n readonly storage: DocumentStorage;\n /** The DANFE's words: the host's, or `@12-apps/fiscal/danfe/pt-BR`. */\n readonly danfeLabels: DanfeNfceLabels;\n}\n\nexport const FISCAL_ERROR_STATUS = {\n INVALID_INPUT: 400,\n NOT_FOUND: 404,\n NOT_ISSUABLE: 409,\n NOT_SUPPORTED: 501,\n TRANSITION_REFUSED: 409,\n SERIES_EXHAUSTED: 409,\n CONFLICT: 409,\n SUBJECT_HAS_DOCUMENT: 409,\n NOT_PRINTABLE: 409,\n RESEND_CHANGES_PRINTED_FIELDS: 422,\n} as const satisfies Record<FiscalDocumentErrorCode, number>;\n\n/**\n * The states with paper: an authorised document, and one signed offline and\n * not yet transmitted (its DANFE is what the buyer takes). A denied,\n * cancelled, rejected or replaced document is not a valid DANFE.\n */\nconst PRINTABLE = new Set([\"AUTHORIZED\", \"CONTINGENCY\"]);\n\nconst ok = (data: unknown, status = 200): FiscalHttpResponse => ({ status, body: { data } });\n\nasync function answering(run: () => Promise<FiscalHttpResponse>): Promise<FiscalHttpResponse> {\n try {\n return await run();\n } catch (error) {\n if (error instanceof FiscalDocumentError) {\n return { status: FISCAL_ERROR_STATUS[error.code], body: { error: error.code, message: error.message } };\n }\n throw error;\n }\n}\n\nfunction record(body: unknown): Record<string, unknown> {\n if (body === null || typeof body !== \"object\" || Array.isArray(body)) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", \"the body must be an object.\");\n }\n return body as Record<string, unknown>;\n}\n\nfunction stringField(body: Record<string, unknown>, key: string): string {\n const value = body[key];\n if (typeof value !== \"string\" || value === \"\") throw new FiscalDocumentError(\"INVALID_INPUT\", `${key} is required.`);\n return value;\n}\n\nfunction param(request: FiscalHttpRequest, key: string): string {\n const value = request.params[key];\n if (value === undefined || value === \"\") throw new FiscalDocumentError(\"INVALID_INPUT\", `${key} is required.`);\n return value;\n}\n\nconst ISSUE_KEYS = new Set([\"subjectId\", \"issuingPointId\", \"model\", \"offline\"]);\n\nfunction issueBody(body: unknown): { subjectId: string; issuingPointId: string; model: FiscalDocumentModel; offline: boolean } {\n const fields = record(body);\n const unknown = Object.keys(fields).filter((key) => !ISSUE_KEYS.has(key));\n if (unknown.length > 0) throw new FiscalDocumentError(\"INVALID_INPUT\", `unknown keys: ${unknown.join(\", \")}.`);\n const model = fields[\"model\"];\n if (!FISCAL_DOCUMENT_MODELS.includes(model as FiscalDocumentModel)) throw new FiscalDocumentError(\"INVALID_INPUT\", \"model must be NFE or NFCE.\");\n const offline = fields[\"offline\"] ?? false;\n if (typeof offline !== \"boolean\") throw new FiscalDocumentError(\"INVALID_INPUT\", \"offline must be a boolean.\");\n if (offline && model !== \"NFCE\") throw new FiscalDocumentError(\"INVALID_INPUT\", \"only an NFC-e is issued offline.\");\n return { subjectId: stringField(fields, \"subjectId\"), issuingPointId: stringField(fields, \"issuingPointId\"), model: model as FiscalDocumentModel, offline };\n}\n\nfunction profileRoutes({ documents }: FiscalApiConfig): FiscalRoute[] {\n return [\n {\n method: \"GET\",\n path: \"/fiscal/profile\",\n permission: FISCAL_READ,\n handle: ({ actor }) =>\n answering(async () => {\n const profile = await documents.getProfile(actor.ownerId);\n return ok(profile === null ? null : viewOf(profile));\n }),\n },\n {\n method: \"PUT\",\n path: \"/fiscal/profile\",\n permission: FISCAL_MANAGE,\n handle: ({ actor, body }) => answering(async () => ok(viewOf(await documents.saveProfile(actor.ownerId, parseProfileInput(body))))),\n },\n {\n method: \"PUT\",\n path: \"/fiscal/profile/certificate\",\n permission: FISCAL_MANAGE,\n handle: ({ actor, body }) =>\n answering(async () => ok(viewOf(await documents.uploadCertificate(actor.ownerId, parseCertificateUpload(body))))),\n },\n {\n method: \"GET\",\n path: \"/fiscal/issuing-points\",\n permission: FISCAL_READ,\n handle: ({ actor }) => answering(async () => ok(await documents.listIssuingPoints(actor.ownerId))),\n },\n {\n method: \"POST\",\n path: \"/fiscal/issuing-points\",\n permission: FISCAL_MANAGE,\n handle: ({ actor, body }) =>\n answering(async () => ok(await documents.createIssuingPoint(actor.ownerId, parseIssuingPointInput(body)), 201)),\n },\n ];\n}\n\n/** The DANFE of a printable document, as ESC/POS-ready lines. */\nfunction danfeRoute({ documents, storage, danfeLabels }: FiscalApiConfig): FiscalRoute {\n return {\n method: \"GET\",\n path: \"/fiscal/documents/:documentId/danfe\",\n permission: FISCAL_READ,\n handle: (request) =>\n answering(async () => {\n const paper = Number(request.query[\"paper\"] ?? \"80\");\n if (paper !== 58 && paper !== 80) throw new FiscalDocumentError(\"INVALID_INPUT\", \"paper must be 58 or 80.\");\n const document = await documents.getDocument(request.actor.ownerId, param(request, \"documentId\"));\n if (!PRINTABLE.has(document.status)) {\n throw new FiscalDocumentError(\"NOT_PRINTABLE\", `document ${document.id} is ${document.status}: only an AUTHORIZED or CONTINGENCY document prints.`);\n }\n const xml = document.model === \"NFCE\" && document.xmlKey !== null ? await storage.get(document.xmlKey) : null;\n if (xml === null) throw new FiscalDocumentError(\"NOT_FOUND\", `document ${document.id} has no NFC-e XML to print.`);\n return ok(renderDanfeNfce({ xml, paperWidth: paper as PaperWidth, labels: danfeLabels }));\n }),\n };\n}\n\nfunction documentRoutes(config: FiscalApiConfig): FiscalRoute[] {\n const { documents } = config;\n return [\n {\n method: \"POST\",\n path: \"/fiscal/documents\",\n permission: FISCAL_ISSUE,\n handle: ({ actor, body }) =>\n answering(async () => {\n const { offline, ...input } = issueBody(body);\n const document = offline\n ? await documents.issueOffline({ ownerId: actor.ownerId, subjectId: input.subjectId, issuingPointId: input.issuingPointId })\n : await documents.issue({ ownerId: actor.ownerId, ...input });\n return ok(document);\n }),\n },\n {\n method: \"GET\",\n path: \"/fiscal/documents/:documentId\",\n permission: FISCAL_READ,\n handle: (request) =>\n answering(async () => {\n const documentId = param(request, \"documentId\");\n const document = await documents.getDocument(request.actor.ownerId, documentId);\n return ok({ document, events: await documents.listEvents(request.actor.ownerId, documentId) });\n }),\n },\n {\n method: \"POST\",\n path: \"/fiscal/documents/:documentId/cancel\",\n permission: FISCAL_CANCEL,\n handle: (request) =>\n answering(async () => {\n const reason = stringField(record(request.body), \"reason\");\n const result = await documents.cancel({ ownerId: request.actor.ownerId, documentId: param(request, \"documentId\"), reason });\n return result.failure === null\n ? ok(result.document)\n : { status: 422, body: { error: \"ISSUER_FAILURE\", failure: result.failure, data: result.document } };\n }),\n },\n {\n method: \"POST\",\n path: \"/fiscal/documents/:documentId/resend\",\n permission: FISCAL_ISSUE,\n handle: (request) =>\n answering(async () =>\n ok(await documents.resendContingency({ ownerId: request.actor.ownerId, documentId: param(request, \"documentId\") })),\n ),\n },\n {\n method: \"POST\",\n path: \"/fiscal/documents/:documentId/release\",\n permission: FISCAL_ISSUE,\n handle: (request) =>\n answering(async () => ok(await documents.release({ ownerId: request.actor.ownerId, documentId: param(request, \"documentId\") }))),\n },\n {\n method: \"POST\",\n path: \"/fiscal/documents/:documentId/lookup\",\n permission: FISCAL_READ,\n handle: (request) =>\n answering(async () => ok(await documents.lookup({ ownerId: request.actor.ownerId, documentId: param(request, \"documentId\") }))),\n },\n danfeRoute(config),\n ];\n}\n\nexport function createApiFiscal(config: FiscalApiConfig): { routes: readonly FiscalRoute[] } {\n if (config?.documents === undefined) throw new TypeError(\"createApiFiscal needs documents.\");\n if (config.storage === undefined) throw new TypeError(\"createApiFiscal needs storage.\");\n if (config.danfeLabels === undefined) throw new TypeError(\"createApiFiscal needs danfeLabels.\");\n return { routes: [...profileRoutes(config), ...documentRoutes(config)] };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA+DO,IAAM,sBAAsB;AAAA,EACjC,eAAe;AAAA,EACf,WAAW;AAAA,EACX,cAAc;AAAA,EACd,eAAe;AAAA,EACf,oBAAoB;AAAA,EACpB,kBAAkB;AAAA,EAClB,UAAU;AAAA,EACV,sBAAsB;AAAA,EACtB,eAAe;AAAA,EACf,+BAA+B;AACjC;AAOA,IAAM,YAAY,oBAAI,IAAI,CAAC,cAAc,aAAa,CAAC;AAEvD,IAAM,KAAK,wBAAC,MAAe,SAAS,SAA6B,EAAE,QAAQ,MAAM,EAAE,KAAK,EAAE,IAA/E;AAEX,eAAe,UAAU,KAAqE;AAC5F,MAAI;AACF,WAAO,MAAM,IAAI;A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;AAAA,MACpH,GAHM;AAAA,IAIV;AAAA,IACA;AAAA,MACE,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,YAAY;AAAA,MACZ,QAAQ,wBAAC,YACP,UAAU,YAAY,GAAG,MAAM,UAAU,QAAQ,EAAE,SAAS,QAAQ,MAAM,SAAS,YAAY,MAAM,SAAS,YAAY,EAAE,CAAC,CAAC,CAAC,GADzH;AAAA,IAEV;AAAA,IACA;AAAA,MACE,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,YAAY;AAAA,MACZ,QAAQ,wBAAC,YACP,UAAU,YAAY,GAAG,MAAM,UAAU,OAAO,EAAE,SAAS,QAAQ,MAAM,SAAS,YAAY,MAAM,SAAS,YAAY,EAAE,CAAC,CAAC,CAAC,GADxH;AAAA,IAEV;AAAA,IACA,WAAW,MAAM;AAAA,EACnB;AACF;AAjES;AAmEF,SAAS,gBAAgB,QAA6D;AAC3F,MAAI,QAAQ,cAAc,OAAW,OAAM,IAAI,UAAU,kCAAkC;AAC3F,MAAI,OAAO,YAAY,OAAW,OAAM,IAAI,UAAU,gCAAgC;AACtF,MAAI,OAAO,gBAAgB,OAAW,OAAM,IAAI,UAAU,oCAAoC;AAC9F,SAAO,EAAE,QAAQ,CAAC,GAAG,cAAc,MAAM,GAAG,GAAG,eAAe,MAAM,CAAC,EAAE;AACzE;AALgB;","names":[]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__name
|
|
3
|
+
} from "./chunk-7QVYU63E.js";
|
|
4
|
+
|
|
5
|
+
// src/documents/errors.ts
|
|
6
|
+
var FiscalDocumentError = class extends Error {
|
|
7
|
+
static {
|
|
8
|
+
__name(this, "FiscalDocumentError");
|
|
9
|
+
}
|
|
10
|
+
code;
|
|
11
|
+
constructor(code, message) {
|
|
12
|
+
super(`[fiscal/documents] ${code}: ${message}`);
|
|
13
|
+
this.name = "FiscalDocumentError";
|
|
14
|
+
this.code = code;
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export {
|
|
19
|
+
FiscalDocumentError
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=chunk-X6MRDUYH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/documents/errors.ts"],"sourcesContent":["/**\n * Every refusal the document module makes, as a typed error with a `code`.\n * A message never carries a certificate, a password or a CSC: the module\n * never holds one long enough to quote it.\n */\n\nexport type FiscalDocumentErrorCode =\n /** The state machine has no such transition from the document's state. */\n | \"TRANSITION_REFUSED\"\n /** An input is missing, malformed or out of range. */\n | \"INVALID_INPUT\"\n /** No emitter profile, issuing point or document under that id. */\n | \"NOT_FOUND\"\n /** The profile does not let the package issue (`documentPolicy`), or lacks what issuing needs. */\n | \"NOT_ISSUABLE\"\n /** The signing identity is declared but not built yet (`PLATFORM`). */\n | \"NOT_SUPPORTED\"\n /** A series' counter passed 999 999 999. */\n | \"SERIES_EXHAUSTED\"\n /** Another worker advanced the document first; re-read it. */\n | \"CONFLICT\"\n /** The subject already has a live document of that model (the per-subject guard). */\n | \"SUBJECT_HAS_DOCUMENT\"\n /** The document's state has no paper to print (only AUTHORIZED, or CONTINGENCY awaiting transmission). */\n | \"NOT_PRINTABLE\"\n /**\n * A resend of a rejected contingency NFC-e would change what the buyer's\n * DANFE prints and its QR encodes (the total, the buyer's document): such a\n * sale needs a new note, issued by a person.\n */\n | \"RESEND_CHANGES_PRINTED_FIELDS\";\n\nexport class FiscalDocumentError extends Error {\n readonly code: FiscalDocumentErrorCode;\n\n constructor(code: FiscalDocumentErrorCode, message: string) {\n super(`[fiscal/documents] ${code}: ${message}`);\n this.name = \"FiscalDocumentError\";\n this.code = code;\n }\n}\n"],"mappings":";;;;;AAgCO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAhC/C,OAgC+C;AAAA;AAAA;AAAA,EACpC;AAAA,EAET,YAAY,MAA+B,SAAiB;AAC1D,UAAM,sBAAsB,IAAI,KAAK,OAAO,EAAE;AAC9C,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;","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":[]}
|