@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,73 @@
|
|
|
1
|
+
import { readFileSync, readdirSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
import { PGlite } from "@electric-sql/pglite";
|
|
5
|
+
|
|
6
|
+
import type { FiscalPrismaClient, FiscalSqlClient } from "../../sql-store";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A real (WASM) Postgres with the package's migrations applied, and the two
|
|
10
|
+
* raw-SQL methods plus `$transaction` a Prisma client offers, over it — so the
|
|
11
|
+
* package's own store runs here exactly as it runs on a host's client.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const MIGRATIONS = join(import.meta.dirname, "../../../../prisma/migrations");
|
|
15
|
+
|
|
16
|
+
async function migrate(): Promise<PGlite> {
|
|
17
|
+
const db = new PGlite();
|
|
18
|
+
for (const dir of readdirSync(MIGRATIONS).filter((name) => /^\d/.test(name)).sort()) {
|
|
19
|
+
await db.exec(readFileSync(join(MIGRATIONS, dir, "migration.sql"), "utf8"));
|
|
20
|
+
}
|
|
21
|
+
return db;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** One migrated database per test file: starting and migrating a PGlite costs about a second each time. */
|
|
25
|
+
let shared: Promise<PGlite> | undefined;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Starts and migrates the file's database once. Call it from a `beforeAll` so
|
|
29
|
+
* the migration is paid under the hook's own timeout, never inside the first
|
|
30
|
+
* case's.
|
|
31
|
+
*/
|
|
32
|
+
export async function warmDatabase(): Promise<void> {
|
|
33
|
+
shared ??= migrate();
|
|
34
|
+
await shared;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The file's migrated database, emptied: every table truncated and every
|
|
39
|
+
* sequence restarted, so each case starts from what a fresh migration leaves
|
|
40
|
+
* (the migrations insert no rows). `close()` on the handle is a no-op; the
|
|
41
|
+
* database lives as long as the file's worker.
|
|
42
|
+
*/
|
|
43
|
+
export async function migratedDatabase(): Promise<PGlite> {
|
|
44
|
+
shared ??= migrate();
|
|
45
|
+
const db = await shared;
|
|
46
|
+
const { rows } = await db.query<{ name: string }>("SELECT tablename AS name FROM pg_tables WHERE schemaname = 'public'");
|
|
47
|
+
if (rows.length > 0) {
|
|
48
|
+
await db.exec(`TRUNCATE ${rows.map(({ name }) => `"${name}"`).join(", ")} RESTART IDENTITY CASCADE`);
|
|
49
|
+
}
|
|
50
|
+
return new Proxy(db, {
|
|
51
|
+
get(target, property) {
|
|
52
|
+
if (property === "close") return async () => {};
|
|
53
|
+
const value: unknown = Reflect.get(target, property, target);
|
|
54
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
type Queryable = Pick<PGlite, "query">;
|
|
60
|
+
|
|
61
|
+
function sqlClient(target: Queryable): FiscalSqlClient {
|
|
62
|
+
return {
|
|
63
|
+
$queryRawUnsafe: async <T>(query: string, ...values: unknown[]) => (await target.query(query, values)).rows as T,
|
|
64
|
+
$executeRawUnsafe: async (query: string, ...values: unknown[]) => (await target.query(query, values)).affectedRows ?? 0,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function prismaOver(db: PGlite): FiscalPrismaClient {
|
|
69
|
+
return {
|
|
70
|
+
...sqlClient(db),
|
|
71
|
+
$transaction: (run) => db.transaction((tx) => run(sqlClient(tx))),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The fiscal document record and its event log — the shape the package's
|
|
3
|
+
* Prisma partial stores (`prisma/fiscal.prisma`, `FiscalDocument` and
|
|
4
|
+
* `FiscalDocumentEvent`) and the state machine (`./machine`) transitions.
|
|
5
|
+
*
|
|
6
|
+
* A document is ONE number: one issuing point, one series, one `nNF`. A sale
|
|
7
|
+
* that goes offline is a second document on the issuing point's contingency
|
|
8
|
+
* series, and the first one is `REPLACED` (see `./machine`). The record is
|
|
9
|
+
* keyed by an opaque `subjectId`: what the subject is (an order, a payment,
|
|
10
|
+
* several orders) is the host's to know, never this package's.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { SaleForDocument } from "../sale/types";
|
|
14
|
+
import type { SefazEnvironment, SidecarErrorClass } from "../sidecar/types";
|
|
15
|
+
|
|
16
|
+
/** The document model: NF-e (55) or NFC-e (65). NFS-e is not a model of this package yet (FUT-2242). */
|
|
17
|
+
export type FiscalDocumentModel = "NFE" | "NFCE";
|
|
18
|
+
|
|
19
|
+
export const FISCAL_DOCUMENT_MODELS: readonly FiscalDocumentModel[] = ["NFE", "NFCE"];
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* - `PENDING`: numbered and stored, not yet handed to the issuer.
|
|
23
|
+
* - `SUBMITTED`: handed to the issuer; no final answer yet (a retry is owed).
|
|
24
|
+
* - `AUTHORIZED`: SEFAZ authorised it. The only state a cancel leaves.
|
|
25
|
+
* - `REJECTED`: refused (SEFAZ's `cStat`, or a request the service refuses as
|
|
26
|
+
* malformed). Final; its number was not spent at SEFAZ and is inutilized.
|
|
27
|
+
* - `DENIED`: a denial of use. Final; the number IS spent.
|
|
28
|
+
* - `CONTINGENCY`: signed offline (`tpEmis = 9`), owed a transmission.
|
|
29
|
+
* - `CANCELLED`: an authorised document cancelled at SEFAZ.
|
|
30
|
+
* - `REPLACED`: its sale moved to another document (the contingency one);
|
|
31
|
+
* its number is settled apart (`numberVoid`).
|
|
32
|
+
*/
|
|
33
|
+
export type FiscalDocumentStatus =
|
|
34
|
+
| "PENDING"
|
|
35
|
+
| "SUBMITTED"
|
|
36
|
+
| "AUTHORIZED"
|
|
37
|
+
| "REJECTED"
|
|
38
|
+
| "DENIED"
|
|
39
|
+
| "CONTINGENCY"
|
|
40
|
+
| "CANCELLED"
|
|
41
|
+
| "REPLACED";
|
|
42
|
+
|
|
43
|
+
export const FISCAL_DOCUMENT_STATUSES: readonly FiscalDocumentStatus[] = [
|
|
44
|
+
"PENDING",
|
|
45
|
+
"SUBMITTED",
|
|
46
|
+
"AUTHORIZED",
|
|
47
|
+
"REJECTED",
|
|
48
|
+
"DENIED",
|
|
49
|
+
"CONTINGENCY",
|
|
50
|
+
"CANCELLED",
|
|
51
|
+
"REPLACED",
|
|
52
|
+
];
|
|
53
|
+
|
|
54
|
+
/** Which of the issuing point's series the number came from. */
|
|
55
|
+
export type SeriesKind = "ONLINE" | "CONTINGENCY";
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* What is still owed on a number SEFAZ never used, so the sequence has no
|
|
59
|
+
* unexplained gap:
|
|
60
|
+
*
|
|
61
|
+
* - `null`: nothing — the number is a document (authorised, denied, owed a
|
|
62
|
+
* transmission) or still in flight.
|
|
63
|
+
* - `LOOKUP_FIRST`: a request went out with no answer before the sale moved
|
|
64
|
+
* to contingency; look the key up before deciding.
|
|
65
|
+
* - `INUTILIZE`: never used at SEFAZ; inutilize it.
|
|
66
|
+
* - `CANCEL`: the lookup found it authorised after all; cancel it.
|
|
67
|
+
* - `INUTILIZED` / `CANCELLED`: settled.
|
|
68
|
+
* - `DENIED`: settled — the lookup found the number denied, which spends it.
|
|
69
|
+
*/
|
|
70
|
+
export type NumberVoid = "LOOKUP_FIRST" | "INUTILIZE" | "CANCEL" | "INUTILIZED" | "CANCELLED" | "DENIED";
|
|
71
|
+
|
|
72
|
+
/** The `numberVoid` values that still owe the sweep a call. */
|
|
73
|
+
export const OWED_VOIDS: readonly NumberVoid[] = ["LOOKUP_FIRST", "INUTILIZE", "CANCEL"];
|
|
74
|
+
|
|
75
|
+
/** The order figures a document carries, in integer cents. */
|
|
76
|
+
export interface DocumentTotals {
|
|
77
|
+
/** What the buyer pays: Σ line values − Σ discounts. */
|
|
78
|
+
readonly totalCents: number;
|
|
79
|
+
readonly discountCents: number;
|
|
80
|
+
readonly cbsCents: number;
|
|
81
|
+
readonly ibsUfCents: number;
|
|
82
|
+
readonly ibsMunCents: number;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Whether the document is the one its subject stands on. At most one live
|
|
87
|
+
* document per (owner, subject, model): a REPLACED one is not, nor an online
|
|
88
|
+
* one SEFAZ rejected (its number is voided and the sale is issued again) —
|
|
89
|
+
* unless a lookup had found it authorised (its protocol is kept). A
|
|
90
|
+
* REJECTED contingency NFC-e stays live: the buyer holds its DANFE, and the
|
|
91
|
+
* store corrects and resends it under the same number.
|
|
92
|
+
*/
|
|
93
|
+
export function isLive(document: Pick<FiscalDocument, "status" | "seriesKind" | "protocol">): boolean {
|
|
94
|
+
if (document.status === "REPLACED") return false;
|
|
95
|
+
// An online rejection with a protocol known (a lookup found it SEFAZ's) is still the sale's.
|
|
96
|
+
return !(document.status === "REJECTED" && document.seriesKind === "ONLINE" && document.protocol === null);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** One fiscal document. */
|
|
100
|
+
export interface FiscalDocument {
|
|
101
|
+
readonly id: string;
|
|
102
|
+
/** The emitter profile's owner: an opaque id the host maps (a store, a company). */
|
|
103
|
+
readonly ownerId: string;
|
|
104
|
+
/** The issuer's CNPJ: SEFAZ numbers by CNPJ, model and series, so the counters do too. */
|
|
105
|
+
readonly issuerCnpj: string;
|
|
106
|
+
/** What the document is FOR, opaque: the host links it to its orders. */
|
|
107
|
+
readonly subjectId: string;
|
|
108
|
+
readonly issuingPointId: string;
|
|
109
|
+
readonly model: FiscalDocumentModel;
|
|
110
|
+
readonly environment: SefazEnvironment;
|
|
111
|
+
readonly seriesKind: SeriesKind;
|
|
112
|
+
readonly series: number;
|
|
113
|
+
readonly number: number;
|
|
114
|
+
/** `cNF`, drawn once: a retried call yields the same key. */
|
|
115
|
+
readonly keyCode: string;
|
|
116
|
+
readonly status: FiscalDocumentStatus;
|
|
117
|
+
/** The sale as sent, issuer and number filled in. Never a secret. */
|
|
118
|
+
readonly sale: SaleForDocument;
|
|
119
|
+
readonly totals: DocumentTotals;
|
|
120
|
+
/** The buyer's CPF/CNPJ at issue time, or `null`. */
|
|
121
|
+
readonly buyerTaxId: string | null;
|
|
122
|
+
readonly accessKey: string | null;
|
|
123
|
+
/** The authorisation (or denial) protocol. */
|
|
124
|
+
readonly protocol: string | null;
|
|
125
|
+
/** The last SEFAZ `cStat`, or the service's named code. */
|
|
126
|
+
readonly statusCode: string | null;
|
|
127
|
+
readonly statusReason: string | null;
|
|
128
|
+
/** The class of the last failed call, or `null`. */
|
|
129
|
+
readonly lastErrorClass: SidecarErrorClass | null;
|
|
130
|
+
/** A request went out and neither it nor its lookup was answered. */
|
|
131
|
+
readonly outcomeUnknown: boolean;
|
|
132
|
+
/** `dhEmi`. */
|
|
133
|
+
readonly issuedAt: string;
|
|
134
|
+
readonly authorizedAt: string | null;
|
|
135
|
+
readonly contingency: { readonly since: string; readonly reason: string } | null;
|
|
136
|
+
readonly cancelledAt: string | null;
|
|
137
|
+
readonly cancelReason: string | null;
|
|
138
|
+
readonly cancelProtocol: string | null;
|
|
139
|
+
/** The document this one's sale moved to. */
|
|
140
|
+
readonly replacedById: string | null;
|
|
141
|
+
readonly numberVoid: NumberVoid | null;
|
|
142
|
+
/** Storage keys: the signed or authorised XML, and the cancel or inutilization event's XML. */
|
|
143
|
+
readonly xmlKey: string | null;
|
|
144
|
+
readonly eventXmlKey: string | null;
|
|
145
|
+
/** Calls made to the issuer for this document. */
|
|
146
|
+
readonly attempts: number;
|
|
147
|
+
/** Failed steps in a row (a retry, a deferred settlement); any progress resets it. */
|
|
148
|
+
readonly failures: number;
|
|
149
|
+
/** When the sweep (or the contingency transmission) may take it again; `null` when nothing is owed. */
|
|
150
|
+
readonly nextAttemptAt: string | null;
|
|
151
|
+
/**
|
|
152
|
+
* A person must look: a settlement SEFAZ refused, or too many failures in a
|
|
153
|
+
* row. The sweep leaves it alone until someone releases it.
|
|
154
|
+
*/
|
|
155
|
+
readonly attention: boolean;
|
|
156
|
+
/** When the 24-hour contingency deadline warning went out. */
|
|
157
|
+
readonly deadlineWarnedAt: string | null;
|
|
158
|
+
readonly createdAt: string;
|
|
159
|
+
readonly updatedAt: string;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** What the state machine was fed: the kind of the input that made the event. */
|
|
163
|
+
export type DocumentEventKind =
|
|
164
|
+
| "SUBMIT"
|
|
165
|
+
| "AUTHORIZE"
|
|
166
|
+
| "DENY"
|
|
167
|
+
| "REJECT"
|
|
168
|
+
| "RETRY"
|
|
169
|
+
| "SIGN_OFFLINE"
|
|
170
|
+
| "REPLACE"
|
|
171
|
+
| "CANCEL"
|
|
172
|
+
| "LOOKUP"
|
|
173
|
+
| "INUTILIZE"
|
|
174
|
+
| "DEFER"
|
|
175
|
+
| "RESIGN"
|
|
176
|
+
| "RELEASE"
|
|
177
|
+
| "WARN";
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* One transition, as stored. `answer` is what the fiscal service answered,
|
|
181
|
+
* verbatim but for any secret-named key (`scrubSecrets`), so the record is the
|
|
182
|
+
* evidence of what SEFAZ said, the `MarketplaceInboxEvent.payload` habit.
|
|
183
|
+
*/
|
|
184
|
+
export interface FiscalDocumentEvent {
|
|
185
|
+
readonly documentId: string;
|
|
186
|
+
readonly kind: DocumentEventKind;
|
|
187
|
+
readonly fromStatus: FiscalDocumentStatus;
|
|
188
|
+
readonly toStatus: FiscalDocumentStatus;
|
|
189
|
+
readonly at: string;
|
|
190
|
+
readonly errorClass: SidecarErrorClass | null;
|
|
191
|
+
readonly code: string | null;
|
|
192
|
+
readonly answer: unknown;
|
|
193
|
+
}
|
package/src/http.ts
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `createApiFiscal` — the fiscal HTTP surface as framework-neutral route
|
|
3
|
+
* descriptors (the wiring contract's `http` capability, restated here
|
|
4
|
+
* structurally: this package imports nothing from the contract at runtime,
|
|
5
|
+
* and its manifest suite pins the twins).
|
|
6
|
+
*
|
|
7
|
+
* The package owns the paths, the bodies it reads (`./documents/profile-input`,
|
|
8
|
+
* unknown keys refused), the `{ data }` envelope, the permission each route
|
|
9
|
+
* needs and the status a refusal earns ({@link FISCAL_ERROR_STATUS}). The host
|
|
10
|
+
* owns resolving WHO is calling into the opaque `ownerId` of its tenant, the
|
|
11
|
+
* guards that check the declared permission, and every word a person reads:
|
|
12
|
+
* an error answers a `code` for the host to word, never a sentence for a user.
|
|
13
|
+
*
|
|
14
|
+
* Nothing secret leaves: the profile answers `hasCertificate` / `hasCsc`, never
|
|
15
|
+
* a ciphertext, and the certificate upload answers the profile view.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { type DanfeNfceLabels } from "./danfe/labels";
|
|
19
|
+
import { type PaperWidth, renderDanfeNfce } from "./danfe/render";
|
|
20
|
+
import { FiscalDocumentError, type FiscalDocumentErrorCode } from "./documents/errors";
|
|
21
|
+
import type { DocumentStorage } from "./documents/ports";
|
|
22
|
+
import { parseCertificateUpload, parseIssuingPointInput, parseProfileInput } from "./documents/profile-input";
|
|
23
|
+
import { viewOf } from "./documents/profile";
|
|
24
|
+
import type { FiscalDocuments } from "./documents/service";
|
|
25
|
+
import { FISCAL_DOCUMENT_MODELS, type FiscalDocumentModel } from "./documents/types";
|
|
26
|
+
import { FISCAL_CANCEL, FISCAL_ISSUE, FISCAL_MANAGE, FISCAL_READ } from "./manifest/permissions";
|
|
27
|
+
|
|
28
|
+
/** The caller, as the host's adapter resolved it. */
|
|
29
|
+
export interface FiscalHttpActor {
|
|
30
|
+
/** The emitter profile's owner: the host's tenant, mapped to an opaque id. */
|
|
31
|
+
readonly ownerId: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Structural twin of the wiring contract's `WireRequest<FiscalHttpActor>`. */
|
|
35
|
+
export interface FiscalHttpRequest {
|
|
36
|
+
actor: FiscalHttpActor;
|
|
37
|
+
params: Record<string, string | undefined>;
|
|
38
|
+
query: Record<string, string | undefined>;
|
|
39
|
+
body?: unknown;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Structural twin of the wiring contract's `WireResponse`. */
|
|
43
|
+
export interface FiscalHttpResponse {
|
|
44
|
+
status: number;
|
|
45
|
+
body: unknown;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Structural twin of the wiring contract's `WireRoute<FiscalHttpActor>`. */
|
|
49
|
+
export interface FiscalRoute {
|
|
50
|
+
method: "GET" | "POST" | "PUT";
|
|
51
|
+
path: string;
|
|
52
|
+
permission: string;
|
|
53
|
+
handle(request: FiscalHttpRequest): Promise<FiscalHttpResponse>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface FiscalApiConfig {
|
|
57
|
+
readonly documents: FiscalDocuments;
|
|
58
|
+
/** Where the XMLs are, to render a DANFE from. */
|
|
59
|
+
readonly storage: DocumentStorage;
|
|
60
|
+
/** The DANFE's words: the host's, or `@12-apps/fiscal/danfe/pt-BR`. */
|
|
61
|
+
readonly danfeLabels: DanfeNfceLabels;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const FISCAL_ERROR_STATUS = {
|
|
65
|
+
INVALID_INPUT: 400,
|
|
66
|
+
NOT_FOUND: 404,
|
|
67
|
+
NOT_ISSUABLE: 409,
|
|
68
|
+
NOT_SUPPORTED: 501,
|
|
69
|
+
TRANSITION_REFUSED: 409,
|
|
70
|
+
SERIES_EXHAUSTED: 409,
|
|
71
|
+
CONFLICT: 409,
|
|
72
|
+
SUBJECT_HAS_DOCUMENT: 409,
|
|
73
|
+
NOT_PRINTABLE: 409,
|
|
74
|
+
RESEND_CHANGES_PRINTED_FIELDS: 422,
|
|
75
|
+
RETURN_NEEDS_REFERENCE: 422,
|
|
76
|
+
RETURN_ON_NFCE: 422,
|
|
77
|
+
} as const satisfies Record<FiscalDocumentErrorCode, number>;
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The states with paper: an authorised document, and one signed offline and
|
|
81
|
+
* not yet transmitted (its DANFE is what the buyer takes). A denied,
|
|
82
|
+
* cancelled, rejected or replaced document is not a valid DANFE.
|
|
83
|
+
*/
|
|
84
|
+
const PRINTABLE = new Set(["AUTHORIZED", "CONTINGENCY"]);
|
|
85
|
+
|
|
86
|
+
const ok = (data: unknown, status = 200): FiscalHttpResponse => ({ status, body: { data } });
|
|
87
|
+
|
|
88
|
+
async function answering(run: () => Promise<FiscalHttpResponse>): Promise<FiscalHttpResponse> {
|
|
89
|
+
try {
|
|
90
|
+
return await run();
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (error instanceof FiscalDocumentError) {
|
|
93
|
+
return { status: FISCAL_ERROR_STATUS[error.code], body: { error: error.code, message: error.message } };
|
|
94
|
+
}
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function record(body: unknown): Record<string, unknown> {
|
|
100
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
101
|
+
throw new FiscalDocumentError("INVALID_INPUT", "the body must be an object.");
|
|
102
|
+
}
|
|
103
|
+
return body as Record<string, unknown>;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function stringField(body: Record<string, unknown>, key: string): string {
|
|
107
|
+
const value = body[key];
|
|
108
|
+
if (typeof value !== "string" || value === "") throw new FiscalDocumentError("INVALID_INPUT", `${key} is required.`);
|
|
109
|
+
return value;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function param(request: FiscalHttpRequest, key: string): string {
|
|
113
|
+
const value = request.params[key];
|
|
114
|
+
if (value === undefined || value === "") throw new FiscalDocumentError("INVALID_INPUT", `${key} is required.`);
|
|
115
|
+
return value;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const ISSUE_KEYS = new Set(["subjectId", "issuingPointId", "model", "offline"]);
|
|
119
|
+
|
|
120
|
+
function issueBody(body: unknown): { subjectId: string; issuingPointId: string; model: FiscalDocumentModel; offline: boolean } {
|
|
121
|
+
const fields = record(body);
|
|
122
|
+
const unknown = Object.keys(fields).filter((key) => !ISSUE_KEYS.has(key));
|
|
123
|
+
if (unknown.length > 0) throw new FiscalDocumentError("INVALID_INPUT", `unknown keys: ${unknown.join(", ")}.`);
|
|
124
|
+
const model = fields["model"];
|
|
125
|
+
if (!FISCAL_DOCUMENT_MODELS.includes(model as FiscalDocumentModel)) throw new FiscalDocumentError("INVALID_INPUT", "model must be NFE or NFCE.");
|
|
126
|
+
const offline = fields["offline"] ?? false;
|
|
127
|
+
if (typeof offline !== "boolean") throw new FiscalDocumentError("INVALID_INPUT", "offline must be a boolean.");
|
|
128
|
+
if (offline && model !== "NFCE") throw new FiscalDocumentError("INVALID_INPUT", "only an NFC-e is issued offline.");
|
|
129
|
+
return { subjectId: stringField(fields, "subjectId"), issuingPointId: stringField(fields, "issuingPointId"), model: model as FiscalDocumentModel, offline };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function profileRoutes({ documents }: FiscalApiConfig): FiscalRoute[] {
|
|
133
|
+
return [
|
|
134
|
+
{
|
|
135
|
+
method: "GET",
|
|
136
|
+
path: "/fiscal/profile",
|
|
137
|
+
permission: FISCAL_READ,
|
|
138
|
+
handle: ({ actor }) =>
|
|
139
|
+
answering(async () => {
|
|
140
|
+
const profile = await documents.getProfile(actor.ownerId);
|
|
141
|
+
return ok(profile === null ? null : viewOf(profile));
|
|
142
|
+
}),
|
|
143
|
+
},
|
|
144
|
+
{
|
|
145
|
+
method: "PUT",
|
|
146
|
+
path: "/fiscal/profile",
|
|
147
|
+
permission: FISCAL_MANAGE,
|
|
148
|
+
handle: ({ actor, body }) => answering(async () => ok(viewOf(await documents.saveProfile(actor.ownerId, parseProfileInput(body))))),
|
|
149
|
+
},
|
|
150
|
+
{
|
|
151
|
+
method: "PUT",
|
|
152
|
+
path: "/fiscal/profile/certificate",
|
|
153
|
+
permission: FISCAL_MANAGE,
|
|
154
|
+
handle: ({ actor, body }) =>
|
|
155
|
+
answering(async () => ok(viewOf(await documents.uploadCertificate(actor.ownerId, parseCertificateUpload(body))))),
|
|
156
|
+
},
|
|
157
|
+
{
|
|
158
|
+
method: "GET",
|
|
159
|
+
path: "/fiscal/issuing-points",
|
|
160
|
+
permission: FISCAL_READ,
|
|
161
|
+
handle: ({ actor }) => answering(async () => ok(await documents.listIssuingPoints(actor.ownerId))),
|
|
162
|
+
},
|
|
163
|
+
{
|
|
164
|
+
method: "POST",
|
|
165
|
+
path: "/fiscal/issuing-points",
|
|
166
|
+
permission: FISCAL_MANAGE,
|
|
167
|
+
handle: ({ actor, body }) =>
|
|
168
|
+
answering(async () => ok(await documents.createIssuingPoint(actor.ownerId, parseIssuingPointInput(body)), 201)),
|
|
169
|
+
},
|
|
170
|
+
];
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The DANFE of a printable document, as ESC/POS-ready lines. */
|
|
174
|
+
function danfeRoute({ documents, storage, danfeLabels }: FiscalApiConfig): FiscalRoute {
|
|
175
|
+
return {
|
|
176
|
+
method: "GET",
|
|
177
|
+
path: "/fiscal/documents/:documentId/danfe",
|
|
178
|
+
permission: FISCAL_READ,
|
|
179
|
+
handle: (request) =>
|
|
180
|
+
answering(async () => {
|
|
181
|
+
const paper = Number(request.query["paper"] ?? "80");
|
|
182
|
+
if (paper !== 58 && paper !== 80) throw new FiscalDocumentError("INVALID_INPUT", "paper must be 58 or 80.");
|
|
183
|
+
const document = await documents.getDocument(request.actor.ownerId, param(request, "documentId"));
|
|
184
|
+
if (!PRINTABLE.has(document.status)) {
|
|
185
|
+
throw new FiscalDocumentError("NOT_PRINTABLE", `document ${document.id} is ${document.status}: only an AUTHORIZED or CONTINGENCY document prints.`);
|
|
186
|
+
}
|
|
187
|
+
const xml = document.model === "NFCE" && document.xmlKey !== null ? await storage.get(document.xmlKey) : null;
|
|
188
|
+
if (xml === null) throw new FiscalDocumentError("NOT_FOUND", `document ${document.id} has no NFC-e XML to print.`);
|
|
189
|
+
return ok(renderDanfeNfce({ xml, paperWidth: paper as PaperWidth, labels: danfeLabels }));
|
|
190
|
+
}),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function documentRoutes(config: FiscalApiConfig): FiscalRoute[] {
|
|
195
|
+
const { documents } = config;
|
|
196
|
+
return [
|
|
197
|
+
{
|
|
198
|
+
method: "POST",
|
|
199
|
+
path: "/fiscal/documents",
|
|
200
|
+
permission: FISCAL_ISSUE,
|
|
201
|
+
handle: ({ actor, body }) =>
|
|
202
|
+
answering(async () => {
|
|
203
|
+
const { offline, ...input } = issueBody(body);
|
|
204
|
+
const document = offline
|
|
205
|
+
? await documents.issueOffline({ ownerId: actor.ownerId, subjectId: input.subjectId, issuingPointId: input.issuingPointId })
|
|
206
|
+
: await documents.issue({ ownerId: actor.ownerId, ...input });
|
|
207
|
+
return ok(document);
|
|
208
|
+
}),
|
|
209
|
+
},
|
|
210
|
+
{
|
|
211
|
+
method: "GET",
|
|
212
|
+
path: "/fiscal/documents/:documentId",
|
|
213
|
+
permission: FISCAL_READ,
|
|
214
|
+
handle: (request) =>
|
|
215
|
+
answering(async () => {
|
|
216
|
+
const documentId = param(request, "documentId");
|
|
217
|
+
const document = await documents.getDocument(request.actor.ownerId, documentId);
|
|
218
|
+
return ok({ document, events: await documents.listEvents(request.actor.ownerId, documentId) });
|
|
219
|
+
}),
|
|
220
|
+
},
|
|
221
|
+
{
|
|
222
|
+
method: "POST",
|
|
223
|
+
path: "/fiscal/documents/:documentId/cancel",
|
|
224
|
+
permission: FISCAL_CANCEL,
|
|
225
|
+
handle: (request) =>
|
|
226
|
+
answering(async () => {
|
|
227
|
+
const reason = stringField(record(request.body), "reason");
|
|
228
|
+
const result = await documents.cancel({ ownerId: request.actor.ownerId, documentId: param(request, "documentId"), reason });
|
|
229
|
+
return result.failure === null
|
|
230
|
+
? ok(result.document)
|
|
231
|
+
: { status: 422, body: { error: "ISSUER_FAILURE", failure: result.failure, data: result.document } };
|
|
232
|
+
}),
|
|
233
|
+
},
|
|
234
|
+
{
|
|
235
|
+
method: "POST",
|
|
236
|
+
path: "/fiscal/documents/:documentId/resend",
|
|
237
|
+
permission: FISCAL_ISSUE,
|
|
238
|
+
handle: (request) =>
|
|
239
|
+
answering(async () =>
|
|
240
|
+
ok(await documents.resendContingency({ ownerId: request.actor.ownerId, documentId: param(request, "documentId") })),
|
|
241
|
+
),
|
|
242
|
+
},
|
|
243
|
+
{
|
|
244
|
+
method: "POST",
|
|
245
|
+
path: "/fiscal/documents/:documentId/release",
|
|
246
|
+
permission: FISCAL_ISSUE,
|
|
247
|
+
handle: (request) =>
|
|
248
|
+
answering(async () => ok(await documents.release({ ownerId: request.actor.ownerId, documentId: param(request, "documentId") }))),
|
|
249
|
+
},
|
|
250
|
+
{
|
|
251
|
+
method: "POST",
|
|
252
|
+
path: "/fiscal/documents/:documentId/lookup",
|
|
253
|
+
permission: FISCAL_READ,
|
|
254
|
+
handle: (request) =>
|
|
255
|
+
answering(async () => ok(await documents.lookup({ ownerId: request.actor.ownerId, documentId: param(request, "documentId") }))),
|
|
256
|
+
},
|
|
257
|
+
danfeRoute(config),
|
|
258
|
+
];
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export function createApiFiscal(config: FiscalApiConfig): { routes: readonly FiscalRoute[] } {
|
|
262
|
+
if (config?.documents === undefined) throw new TypeError("createApiFiscal needs documents.");
|
|
263
|
+
if (config.storage === undefined) throw new TypeError("createApiFiscal needs storage.");
|
|
264
|
+
if (config.danfeLabels === undefined) throw new TypeError("createApiFiscal needs danfeLabels.");
|
|
265
|
+
return { routes: [...profileRoutes(config), ...documentRoutes(config)] };
|
|
266
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/fiscal/issuer` — the Issuer port and its first adapter, the
|
|
3
|
+
* fiscal service in this package's `sidecar/` folder.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export { modelPath } from "./port";
|
|
7
|
+
export type * from "./port";
|
|
8
|
+
export { createSidecarIssuer } from "./sidecar";
|
|
9
|
+
export type { SidecarFetch, SidecarIssuerConfig } from "./sidecar";
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Issuer port: what the document service asks of whoever talks to SEFAZ.
|
|
3
|
+
* The first (and today only) adapter is the fiscal service in this package's
|
|
4
|
+
* `sidecar/` folder (`./sidecar`). A call never throws for a failure the
|
|
5
|
+
* service classified: it answers `{ ok: false, error }` with the service's
|
|
6
|
+
* class (`REJECTED`, `RETRYABLE`, `CONTINGENCY`, `AUTH`, `INVALID`,
|
|
7
|
+
* `INTERNAL`), and the document service maps that onto the state machine.
|
|
8
|
+
*
|
|
9
|
+
* The certificate and the CSC travel with each call (the service is
|
|
10
|
+
* stateless) inside {@link SigningMaterial}, built by the signing identity
|
|
11
|
+
* for this one call and dropped with it.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { FiscalDocumentModel } from "../documents/types";
|
|
15
|
+
import type { SaleForDocument } from "../sale/types";
|
|
16
|
+
import type {
|
|
17
|
+
CancelledDocument,
|
|
18
|
+
ContingencyEntry,
|
|
19
|
+
ContingencySignedDocument,
|
|
20
|
+
Csc,
|
|
21
|
+
InutilizedRange,
|
|
22
|
+
IssuedDocument,
|
|
23
|
+
LookedUpDocument,
|
|
24
|
+
SefazEnvironment,
|
|
25
|
+
SidecarErrorBody,
|
|
26
|
+
SidecarHealth,
|
|
27
|
+
SigningCertificate,
|
|
28
|
+
} from "../sidecar/types";
|
|
29
|
+
|
|
30
|
+
/** What signs one call: the A1 and, for an NFC-e, the CSC. Never stored, never logged. */
|
|
31
|
+
export interface SigningMaterial {
|
|
32
|
+
readonly certificate: SigningCertificate;
|
|
33
|
+
readonly csc: Csc | null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A failed call, classified. The service's error body, verbatim. */
|
|
37
|
+
export type IssuerFailure = SidecarErrorBody["error"];
|
|
38
|
+
|
|
39
|
+
export type IssuerOutcome<T> = { readonly ok: true; readonly answer: T } | { readonly ok: false; readonly error: IssuerFailure };
|
|
40
|
+
|
|
41
|
+
interface Call {
|
|
42
|
+
readonly environment: SefazEnvironment;
|
|
43
|
+
readonly signing: SigningMaterial;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface IssueCall extends Call {
|
|
47
|
+
readonly model: FiscalDocumentModel;
|
|
48
|
+
readonly document: SaleForDocument;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface SignContingencyCall extends Call {
|
|
52
|
+
readonly document: SaleForDocument;
|
|
53
|
+
readonly contingency: ContingencyEntry;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface TransmitCall extends Call {
|
|
57
|
+
readonly model: FiscalDocumentModel;
|
|
58
|
+
readonly signedXml: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface CancelCall extends Call {
|
|
62
|
+
readonly model: FiscalDocumentModel;
|
|
63
|
+
readonly accessKey: string;
|
|
64
|
+
readonly protocol: string;
|
|
65
|
+
readonly reason: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** NFC-e only: cancel an online document whose sale was issued again in contingency (event 110112). */
|
|
69
|
+
export interface CancelBySubstitutionCall extends Call {
|
|
70
|
+
readonly accessKey: string;
|
|
71
|
+
readonly protocol: string;
|
|
72
|
+
readonly reason: string;
|
|
73
|
+
readonly substituteAccessKey: string;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface LookupCall extends Call {
|
|
77
|
+
readonly model: FiscalDocumentModel;
|
|
78
|
+
readonly accessKey: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface InutilizeCall extends Call {
|
|
82
|
+
readonly model: FiscalDocumentModel;
|
|
83
|
+
readonly uf: string;
|
|
84
|
+
readonly cnpj: string;
|
|
85
|
+
readonly year: number;
|
|
86
|
+
readonly series: number;
|
|
87
|
+
readonly from: number;
|
|
88
|
+
readonly to: number;
|
|
89
|
+
readonly reason: string;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface Issuer {
|
|
93
|
+
/** Build, sign and transmit. `AUTHORIZED` or `DENIED`. */
|
|
94
|
+
issue(call: IssueCall): Promise<IssuerOutcome<IssuedDocument>>;
|
|
95
|
+
/** NFC-e only: build and sign offline (`tpEmis = 9`); nothing is sent. */
|
|
96
|
+
signContingency(call: SignContingencyCall): Promise<IssuerOutcome<ContingencySignedDocument>>;
|
|
97
|
+
/** Send an already signed XML (a contingency document). */
|
|
98
|
+
transmit(call: TransmitCall): Promise<IssuerOutcome<IssuedDocument>>;
|
|
99
|
+
cancel(call: CancelCall): Promise<IssuerOutcome<CancelledDocument>>;
|
|
100
|
+
cancelBySubstitution(call: CancelBySubstitutionCall): Promise<IssuerOutcome<CancelledDocument>>;
|
|
101
|
+
lookup(call: LookupCall): Promise<IssuerOutcome<LookedUpDocument>>;
|
|
102
|
+
inutilize(call: InutilizeCall): Promise<IssuerOutcome<InutilizedRange>>;
|
|
103
|
+
health(): Promise<SidecarHealth>;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The path segment of a model on the service's routes. */
|
|
107
|
+
export function modelPath(model: FiscalDocumentModel): "nfe" | "nfce" {
|
|
108
|
+
return model === "NFE" ? "nfe" : "nfce";
|
|
109
|
+
}
|