@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,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rows of the package's tables (`prisma/migrations`) to the records the
|
|
3
|
+
* service holds, and back. Raw SQL through the host's Prisma client answers
|
|
4
|
+
* snake_case columns, `Date` for a timestamp, a parsed object for a JSONB
|
|
5
|
+
* column, and a `bigint` or a string for a BIGSERIAL; every one is read here.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { EmitterProfile, IssuingPoint } from "./profile";
|
|
9
|
+
import type { FiscalDocument, FiscalDocumentEvent } from "./types";
|
|
10
|
+
|
|
11
|
+
export type Row = Record<string, unknown>;
|
|
12
|
+
|
|
13
|
+
/** A timestamp column as ISO 8601 UTC; the columns are UTC by the Prisma convention. */
|
|
14
|
+
function iso(value: unknown): string | null {
|
|
15
|
+
if (value === null || value === undefined) return null;
|
|
16
|
+
const date = value instanceof Date ? value : new Date(`${String(value).replace(" ", "T")}${/Z|[+-]\d{2}:?\d{2}$/.test(String(value)) ? "" : "Z"}`);
|
|
17
|
+
return date.toISOString();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function requiredIso(value: unknown): string {
|
|
21
|
+
return iso(value) ?? "";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** A DATE column as `YYYY-MM-DD`. */
|
|
25
|
+
function day(value: unknown): string {
|
|
26
|
+
return value instanceof Date ? value.toISOString().slice(0, 10) : String(value).slice(0, 10);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function json<T>(value: unknown): T {
|
|
30
|
+
return (typeof value === "string" ? JSON.parse(value) : value) as T;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const text = (value: unknown): string | null => (value === null || value === undefined ? null : String(value));
|
|
34
|
+
|
|
35
|
+
/** The document's columns, in the order `documentValues` writes them. */
|
|
36
|
+
export const DOCUMENT_COLUMNS = [
|
|
37
|
+
"id", "owner_id", "issuer_cnpj", "subject_id", "issuing_point_id", "model", "environment", "series_kind", "series",
|
|
38
|
+
"number", "key_code", "status", "sale", "totals", "buyer_tax_id", "access_key", "protocol", "status_code",
|
|
39
|
+
"status_reason", "last_error_class", "outcome_unknown", "issued_at", "authorized_at", "contingency", "cancelled_at",
|
|
40
|
+
"cancel_reason", "cancel_protocol", "replaced_by_id", "number_void", "xml_key", "event_xml_key", "attempts",
|
|
41
|
+
"failures", "next_attempt_at", "attention", "deadline_warned_at", "created_at", "updated_at",
|
|
42
|
+
] as const;
|
|
43
|
+
|
|
44
|
+
const JSON_COLUMNS = new Set(["sale", "totals", "contingency"]);
|
|
45
|
+
const TIME_COLUMNS = new Set(["next_attempt_at", "deadline_warned_at", "created_at", "updated_at"]);
|
|
46
|
+
|
|
47
|
+
/** The SQL placeholder of a column, with the cast its type needs. */
|
|
48
|
+
export function placeholder(column: string, index: number): string {
|
|
49
|
+
if (JSON_COLUMNS.has(column)) return `$${index}::jsonb`;
|
|
50
|
+
if (TIME_COLUMNS.has(column)) return `$${index}::timestamp(3)`;
|
|
51
|
+
return `$${index}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function documentValues(d: FiscalDocument): unknown[] {
|
|
55
|
+
return [
|
|
56
|
+
d.id, d.ownerId, d.issuerCnpj, d.subjectId, d.issuingPointId, d.model, d.environment, d.seriesKind, d.series,
|
|
57
|
+
d.number, d.keyCode, d.status, JSON.stringify(d.sale), JSON.stringify(d.totals), d.buyerTaxId, d.accessKey,
|
|
58
|
+
d.protocol, d.statusCode, d.statusReason, d.lastErrorClass, d.outcomeUnknown, d.issuedAt, d.authorizedAt,
|
|
59
|
+
d.contingency === null ? null : JSON.stringify(d.contingency), d.cancelledAt, d.cancelReason, d.cancelProtocol,
|
|
60
|
+
d.replacedById, d.numberVoid, d.xmlKey, d.eventXmlKey, d.attempts, d.failures, d.nextAttemptAt, d.attention,
|
|
61
|
+
d.deadlineWarnedAt, d.createdAt, d.updatedAt,
|
|
62
|
+
];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function documentOf(row: Row): FiscalDocument {
|
|
66
|
+
return {
|
|
67
|
+
id: String(row["id"]),
|
|
68
|
+
ownerId: String(row["owner_id"]),
|
|
69
|
+
issuerCnpj: String(row["issuer_cnpj"]),
|
|
70
|
+
subjectId: String(row["subject_id"]),
|
|
71
|
+
issuingPointId: String(row["issuing_point_id"]),
|
|
72
|
+
model: row["model"] as FiscalDocument["model"],
|
|
73
|
+
environment: row["environment"] as FiscalDocument["environment"],
|
|
74
|
+
seriesKind: row["series_kind"] as FiscalDocument["seriesKind"],
|
|
75
|
+
series: Number(row["series"]),
|
|
76
|
+
number: Number(row["number"]),
|
|
77
|
+
keyCode: String(row["key_code"]),
|
|
78
|
+
status: row["status"] as FiscalDocument["status"],
|
|
79
|
+
sale: json(row["sale"]),
|
|
80
|
+
totals: json(row["totals"]),
|
|
81
|
+
buyerTaxId: text(row["buyer_tax_id"]),
|
|
82
|
+
accessKey: text(row["access_key"]),
|
|
83
|
+
protocol: text(row["protocol"]),
|
|
84
|
+
statusCode: text(row["status_code"]),
|
|
85
|
+
statusReason: text(row["status_reason"]),
|
|
86
|
+
lastErrorClass: text(row["last_error_class"]) as FiscalDocument["lastErrorClass"],
|
|
87
|
+
outcomeUnknown: row["outcome_unknown"] === true,
|
|
88
|
+
issuedAt: String(row["issued_at"]),
|
|
89
|
+
authorizedAt: text(row["authorized_at"]),
|
|
90
|
+
contingency: row["contingency"] === null ? null : json(row["contingency"]),
|
|
91
|
+
cancelledAt: text(row["cancelled_at"]),
|
|
92
|
+
cancelReason: text(row["cancel_reason"]),
|
|
93
|
+
cancelProtocol: text(row["cancel_protocol"]),
|
|
94
|
+
replacedById: text(row["replaced_by_id"]),
|
|
95
|
+
numberVoid: text(row["number_void"]) as FiscalDocument["numberVoid"],
|
|
96
|
+
xmlKey: text(row["xml_key"]),
|
|
97
|
+
eventXmlKey: text(row["event_xml_key"]),
|
|
98
|
+
attempts: Number(row["attempts"]),
|
|
99
|
+
failures: Number(row["failures"]),
|
|
100
|
+
nextAttemptAt: iso(row["next_attempt_at"]),
|
|
101
|
+
attention: row["attention"] === true,
|
|
102
|
+
deadlineWarnedAt: iso(row["deadline_warned_at"]),
|
|
103
|
+
createdAt: requiredIso(row["created_at"]),
|
|
104
|
+
updatedAt: requiredIso(row["updated_at"]),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function eventOf(row: Row): FiscalDocumentEvent {
|
|
109
|
+
return {
|
|
110
|
+
documentId: String(row["document_id"]),
|
|
111
|
+
kind: row["kind"] as FiscalDocumentEvent["kind"],
|
|
112
|
+
fromStatus: row["from_status"] as FiscalDocumentEvent["fromStatus"],
|
|
113
|
+
toStatus: row["to_status"] as FiscalDocumentEvent["toStatus"],
|
|
114
|
+
at: requiredIso(row["at"]),
|
|
115
|
+
errorClass: text(row["error_class"]) as FiscalDocumentEvent["errorClass"],
|
|
116
|
+
code: text(row["code"]),
|
|
117
|
+
answer: row["answer"] === null ? null : json(row["answer"]),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export const PROFILE_COLUMNS = [
|
|
122
|
+
"owner_id", "cnpj", "state_registration", "municipal_registration", "cnae", "legal_name", "trade_name", "tax_regime",
|
|
123
|
+
"regime", "regime_effective_from", "restaurant_regime", "address", "environment", "document_policy",
|
|
124
|
+
"signing_identity", "certificate_ciphertext", "certificate_password_ciphertext", "certificate_expires_at", "csc_id",
|
|
125
|
+
"csc_ciphertext", "consent_recorded_at", "updated_at",
|
|
126
|
+
] as const;
|
|
127
|
+
|
|
128
|
+
export function profilePlaceholder(column: string, index: number): string {
|
|
129
|
+
if (column === "address") return `$${index}::jsonb`;
|
|
130
|
+
if (column === "regime_effective_from") return `$${index}::date`;
|
|
131
|
+
if (column.endsWith("_at")) return `$${index}::timestamp(3)`;
|
|
132
|
+
return `$${index}`;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function profileValues(p: EmitterProfile): unknown[] {
|
|
136
|
+
return [
|
|
137
|
+
p.ownerId, p.cnpj, p.stateRegistration, p.municipalRegistration, p.cnae, p.legalName, p.tradeName, p.taxRegime,
|
|
138
|
+
p.regime, p.regimeEffectiveFrom, p.restaurantRegime, JSON.stringify(p.address), p.environment, p.documentPolicy,
|
|
139
|
+
p.signingIdentity, p.certificateCiphertext, p.certificatePasswordCiphertext, p.certificateExpiresAt, p.cscId,
|
|
140
|
+
p.cscCiphertext, p.consentRecordedAt, p.updatedAt,
|
|
141
|
+
];
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function profileOf(row: Row): EmitterProfile {
|
|
145
|
+
return {
|
|
146
|
+
ownerId: String(row["owner_id"]),
|
|
147
|
+
cnpj: String(row["cnpj"]),
|
|
148
|
+
stateRegistration: String(row["state_registration"]),
|
|
149
|
+
municipalRegistration: text(row["municipal_registration"]),
|
|
150
|
+
cnae: text(row["cnae"]),
|
|
151
|
+
legalName: String(row["legal_name"]),
|
|
152
|
+
tradeName: text(row["trade_name"]),
|
|
153
|
+
taxRegime: row["tax_regime"] as EmitterProfile["taxRegime"],
|
|
154
|
+
regime: row["regime"] as EmitterProfile["regime"],
|
|
155
|
+
regimeEffectiveFrom: day(row["regime_effective_from"]),
|
|
156
|
+
restaurantRegime: row["restaurant_regime"] === true,
|
|
157
|
+
address: json(row["address"]),
|
|
158
|
+
environment: row["environment"] as EmitterProfile["environment"],
|
|
159
|
+
documentPolicy: row["document_policy"] as EmitterProfile["documentPolicy"],
|
|
160
|
+
signingIdentity: row["signing_identity"] as EmitterProfile["signingIdentity"],
|
|
161
|
+
certificateCiphertext: text(row["certificate_ciphertext"]),
|
|
162
|
+
certificatePasswordCiphertext: text(row["certificate_password_ciphertext"]),
|
|
163
|
+
certificateExpiresAt: iso(row["certificate_expires_at"]),
|
|
164
|
+
cscId: text(row["csc_id"]),
|
|
165
|
+
cscCiphertext: text(row["csc_ciphertext"]),
|
|
166
|
+
consentRecordedAt: iso(row["consent_recorded_at"]),
|
|
167
|
+
updatedAt: requiredIso(row["updated_at"]),
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function pointOf(row: Row): IssuingPoint {
|
|
172
|
+
return {
|
|
173
|
+
id: String(row["id"]),
|
|
174
|
+
ownerId: String(row["owner_id"]),
|
|
175
|
+
model: row["model"] as IssuingPoint["model"],
|
|
176
|
+
onlineSeries: Number(row["online_series"]),
|
|
177
|
+
contingencySeries: row["contingency_series"] === null ? null : Number(row["contingency_series"]),
|
|
178
|
+
createdAt: requiredIso(row["created_at"]),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `createPrismaFiscalStore` — the package's own {@link FiscalStore}, over the
|
|
3
|
+
* host's Prisma client and the package's migration. A host passes its client
|
|
4
|
+
* and nothing else: the numbering invariants live here, not in each host.
|
|
5
|
+
*
|
|
6
|
+
* - The draw and the insert are ONE transaction (`FISCAL_NEXT_NUMBER_SQL`):
|
|
7
|
+
* the counter's row lock serialises concurrent draws, and a refused insert
|
|
8
|
+
* gives the number back.
|
|
9
|
+
* - Going offline replaces the online document in that same transaction,
|
|
10
|
+
* before the insert, so a crash leaves exactly one live document.
|
|
11
|
+
* - The per-subject guard is the partial unique index
|
|
12
|
+
* `fiscal_documents_live_subject_key`: a second live document is refused as
|
|
13
|
+
* `SUBJECT_HAS_DOCUMENT`, and nothing is drawn.
|
|
14
|
+
* - A transition is saved only over the row it started from (`updated_at` and
|
|
15
|
+
* `status`), with its event, in one transaction.
|
|
16
|
+
*
|
|
17
|
+
* It speaks raw SQL through the client's `$queryRawUnsafe` /
|
|
18
|
+
* `$executeRawUnsafe` / `$transaction`, so it needs no generated model types
|
|
19
|
+
* and works on the host's client whatever else its schema holds.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { FiscalDocumentError } from "./errors";
|
|
23
|
+
import type { Transition } from "./machine";
|
|
24
|
+
import type { FiscalStore, NumberRequest } from "./ports";
|
|
25
|
+
import { FISCAL_NEXT_NUMBER_SQL } from "./sql";
|
|
26
|
+
import {
|
|
27
|
+
DOCUMENT_COLUMNS,
|
|
28
|
+
PROFILE_COLUMNS,
|
|
29
|
+
type Row,
|
|
30
|
+
documentOf,
|
|
31
|
+
documentValues,
|
|
32
|
+
eventOf,
|
|
33
|
+
placeholder,
|
|
34
|
+
pointOf,
|
|
35
|
+
profileOf,
|
|
36
|
+
profilePlaceholder,
|
|
37
|
+
profileValues,
|
|
38
|
+
} from "./sql-rows";
|
|
39
|
+
import type { FiscalDocument } from "./types";
|
|
40
|
+
|
|
41
|
+
/** The two raw-SQL methods of a Prisma client (or of its transaction client). */
|
|
42
|
+
export interface FiscalSqlClient {
|
|
43
|
+
$queryRawUnsafe<T = unknown>(query: string, ...values: unknown[]): Promise<T>;
|
|
44
|
+
$executeRawUnsafe(query: string, ...values: unknown[]): Promise<number>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A Prisma client: the raw-SQL methods and an interactive transaction. */
|
|
48
|
+
export interface FiscalPrismaClient extends FiscalSqlClient {
|
|
49
|
+
$transaction<T>(run: (tx: FiscalSqlClient) => Promise<T>): Promise<T>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const rows = (client: FiscalSqlClient, query: string, ...values: unknown[]) => client.$queryRawUnsafe<Row[]>(query, ...values);
|
|
53
|
+
|
|
54
|
+
const INSERT_DOCUMENT = `INSERT INTO "fiscal_documents" (${DOCUMENT_COLUMNS.map((c) => `"${c}"`).join(", ")})
|
|
55
|
+
VALUES (${DOCUMENT_COLUMNS.map((c, i) => placeholder(c, i + 1)).join(", ")})`;
|
|
56
|
+
|
|
57
|
+
const MUTABLE = DOCUMENT_COLUMNS.filter((c) => c !== "id" && c !== "created_at");
|
|
58
|
+
// $1 the id, $2... the mutable columns, then the row the transition started from.
|
|
59
|
+
const UPDATE_DOCUMENT = [
|
|
60
|
+
`UPDATE "fiscal_documents" SET ${MUTABLE.map((c, i) => `"${c}" = ${placeholder(c, i + 2)}`).join(", ")}`,
|
|
61
|
+
`WHERE "id" = $1 AND "updated_at" = $${MUTABLE.length + 2}::timestamp(3) AND "status" = $${MUTABLE.length + 3}`,
|
|
62
|
+
`RETURNING "id"`,
|
|
63
|
+
].join("\n");
|
|
64
|
+
|
|
65
|
+
function updateValues(document: FiscalDocument, previous: FiscalDocument): unknown[] {
|
|
66
|
+
const all = documentValues(document);
|
|
67
|
+
const mutable = MUTABLE.map((column) => all[DOCUMENT_COLUMNS.indexOf(column)]);
|
|
68
|
+
return [document.id, ...mutable, previous.updatedAt, previous.status];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const INSERT_EVENT = `INSERT INTO "fiscal_document_events" ("id", "document_id", "kind", "from_status", "to_status", "at", "error_class", "code", "answer")
|
|
72
|
+
VALUES ($1, $2, $3, $4, $5, $6::timestamp(3), $7, $8, $9::jsonb)`;
|
|
73
|
+
|
|
74
|
+
const UPSERT_PROFILE = `INSERT INTO "fiscal_emitter_profiles" (${PROFILE_COLUMNS.map((c) => `"${c}"`).join(", ")})
|
|
75
|
+
VALUES (${PROFILE_COLUMNS.map((c, i) => profilePlaceholder(c, i + 1)).join(", ")})
|
|
76
|
+
ON CONFLICT ("owner_id") DO UPDATE SET ${PROFILE_COLUMNS.filter((c) => c !== "owner_id").map((c) => `"${c}" = EXCLUDED."${c}"`).join(", ")}`;
|
|
77
|
+
|
|
78
|
+
const OWED = `("status" IN ('PENDING', 'SUBMITTED') OR "number_void" IN ('LOOKUP_FIRST', 'INUTILIZE', 'CANCEL'))`;
|
|
79
|
+
|
|
80
|
+
/** A unique-index or CHECK violation, recognised by its constraint's name in whatever error the client raised. */
|
|
81
|
+
function violates(error: unknown, constraint: string): boolean {
|
|
82
|
+
const text = error instanceof Error ? `${error.message} ${JSON.stringify((error as { meta?: unknown }).meta ?? "")}` : String(error);
|
|
83
|
+
return text.includes(constraint);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function saveRow(tx: FiscalSqlClient, previous: FiscalDocument, { document, event }: Transition): Promise<boolean> {
|
|
87
|
+
const updated = await rows(tx, UPDATE_DOCUMENT, ...updateValues(document, previous));
|
|
88
|
+
if (updated.length === 0) return false;
|
|
89
|
+
await tx.$executeRawUnsafe(
|
|
90
|
+
INSERT_EVENT,
|
|
91
|
+
globalThis.crypto.randomUUID(),
|
|
92
|
+
event.documentId,
|
|
93
|
+
event.kind,
|
|
94
|
+
event.fromStatus,
|
|
95
|
+
event.toStatus,
|
|
96
|
+
event.at,
|
|
97
|
+
event.errorClass,
|
|
98
|
+
event.code,
|
|
99
|
+
event.answer === null ? null : JSON.stringify(event.answer),
|
|
100
|
+
);
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function draw(tx: FiscalSqlClient, request: NumberRequest): Promise<number> {
|
|
105
|
+
try {
|
|
106
|
+
const [row] = await rows(tx, FISCAL_NEXT_NUMBER_SQL, request.issuerCnpj, request.environment, request.model, request.series, request.issuingPointId);
|
|
107
|
+
if (row === undefined) {
|
|
108
|
+
throw new FiscalDocumentError("NOT_FOUND", `no counter for series ${request.series} on issuing point ${request.issuingPointId}.`);
|
|
109
|
+
}
|
|
110
|
+
return Number(row["number"]);
|
|
111
|
+
} catch (error) {
|
|
112
|
+
if (violates(error, "fiscal_number_counters_next_number_check")) {
|
|
113
|
+
throw new FiscalDocumentError("SERIES_EXHAUSTED", `series ${request.series} has no number left.`);
|
|
114
|
+
}
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function insertDocument(tx: FiscalSqlClient, document: FiscalDocument): Promise<void> {
|
|
120
|
+
try {
|
|
121
|
+
await tx.$executeRawUnsafe(INSERT_DOCUMENT, ...documentValues(document));
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (violates(error, "fiscal_documents_live_subject_key")) {
|
|
124
|
+
throw new FiscalDocumentError("SUBJECT_HAS_DOCUMENT", `subject ${document.subjectId} already has a live ${document.model}.`);
|
|
125
|
+
}
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function openCounters(tx: FiscalSqlClient, point: { id: string; model: string }, issuerCnpj: string, series: number, kind: string, first: number) {
|
|
131
|
+
for (const environment of ["homologacao", "producao"]) {
|
|
132
|
+
await tx.$executeRawUnsafe(
|
|
133
|
+
`INSERT INTO "fiscal_number_counters" ("issuer_cnpj", "environment", "model", "series", "issuing_point_id", "series_kind", "next_number")
|
|
134
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
|
|
135
|
+
issuerCnpj, environment, point.model, series, point.id, kind, first,
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
type ProfileMethods = Pick<FiscalStore, "getProfile" | "saveProfile" | "getIssuingPoint" | "listIssuingPoints" | "createIssuingPoint" | "listExpiringCertificates">;
|
|
141
|
+
|
|
142
|
+
function profileMethods(db: FiscalPrismaClient): ProfileMethods {
|
|
143
|
+
return {
|
|
144
|
+
async getProfile(ownerId) {
|
|
145
|
+
const [row] = await rows(db, `SELECT * FROM "fiscal_emitter_profiles" WHERE "owner_id" = $1`, ownerId);
|
|
146
|
+
return row === undefined ? null : profileOf(row);
|
|
147
|
+
},
|
|
148
|
+
async saveProfile(profile) {
|
|
149
|
+
await db.$executeRawUnsafe(UPSERT_PROFILE, ...profileValues(profile));
|
|
150
|
+
},
|
|
151
|
+
async getIssuingPoint(ownerId, id) {
|
|
152
|
+
const [row] = await rows(db, `SELECT * FROM "fiscal_issuing_points" WHERE "id" = $1 AND "owner_id" = $2`, id, ownerId);
|
|
153
|
+
return row === undefined ? null : pointOf(row);
|
|
154
|
+
},
|
|
155
|
+
async listIssuingPoints(ownerId) {
|
|
156
|
+
return (await rows(db, `SELECT * FROM "fiscal_issuing_points" WHERE "owner_id" = $1 ORDER BY "created_at", "id"`, ownerId)).map(pointOf);
|
|
157
|
+
},
|
|
158
|
+
createIssuingPoint: (point, issuerCnpj, firstNumber) => createIssuingPoint(db, point, issuerCnpj, firstNumber),
|
|
159
|
+
async listExpiringCertificates(before) {
|
|
160
|
+
return (
|
|
161
|
+
await rows(db, `SELECT * FROM "fiscal_emitter_profiles" WHERE "certificate_expires_at" < $1::timestamp(3) ORDER BY "owner_id"`, before)
|
|
162
|
+
).map(profileOf);
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function createIssuingPoint(db: FiscalPrismaClient, ...[point, issuerCnpj, firstNumber]: Parameters<FiscalStore["createIssuingPoint"]>): Promise<void> {
|
|
168
|
+
try {
|
|
169
|
+
await db.$transaction(async (tx) => {
|
|
170
|
+
await tx.$executeRawUnsafe(
|
|
171
|
+
`INSERT INTO "fiscal_issuing_points" ("id", "owner_id", "model", "online_series", "contingency_series", "created_at")
|
|
172
|
+
VALUES ($1, $2, $3, $4, $5, $6::timestamp(3))`,
|
|
173
|
+
point.id, point.ownerId, point.model, point.onlineSeries, point.contingencySeries, point.createdAt,
|
|
174
|
+
);
|
|
175
|
+
await openCounters(tx, point, issuerCnpj, point.onlineSeries, "ONLINE", firstNumber.online);
|
|
176
|
+
if (point.contingencySeries !== null) {
|
|
177
|
+
await openCounters(tx, point, issuerCnpj, point.contingencySeries, "CONTINGENCY", firstNumber.contingency);
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
} catch (error) {
|
|
181
|
+
if (violates(error, "fiscal_number_counters_pkey")) {
|
|
182
|
+
throw new FiscalDocumentError("INVALID_INPUT", `a series of issuing point ${point.id} already belongs to another issuing point.`);
|
|
183
|
+
}
|
|
184
|
+
if (violates(error, "fiscal_issuing_points_pkey")) throw new FiscalDocumentError("INVALID_INPUT", `issuing point ${point.id} exists.`);
|
|
185
|
+
throw error;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function documentMethods(db: FiscalPrismaClient): Omit<FiscalStore, keyof ProfileMethods> {
|
|
190
|
+
const documents = async (query: string, ...values: unknown[]) => (await rows(db, query, ...values)).map(documentOf);
|
|
191
|
+
return {
|
|
192
|
+
createDocument: (request, build, replace) =>
|
|
193
|
+
db.$transaction(async (tx) => {
|
|
194
|
+
if (replace !== undefined && !(await saveRow(tx, replace.previous, replace.transition))) {
|
|
195
|
+
throw new FiscalDocumentError("CONFLICT", `document ${replace.previous.id} moved before it was replaced.`);
|
|
196
|
+
}
|
|
197
|
+
const document = build(await draw(tx, request));
|
|
198
|
+
await insertDocument(tx, document);
|
|
199
|
+
return document;
|
|
200
|
+
}),
|
|
201
|
+
async getDocument(ownerId, id) {
|
|
202
|
+
const [document] = await documents(`SELECT * FROM "fiscal_documents" WHERE "id" = $1 AND "owner_id" = $2`, id, ownerId);
|
|
203
|
+
return document ?? null;
|
|
204
|
+
},
|
|
205
|
+
listBySubject: (ownerId, subjectId, model) =>
|
|
206
|
+
documents(
|
|
207
|
+
`SELECT * FROM "fiscal_documents" WHERE "owner_id" = $1 AND "subject_id" = $2 AND "model" = $3 ORDER BY "created_at", "id"`,
|
|
208
|
+
ownerId, subjectId, model,
|
|
209
|
+
),
|
|
210
|
+
async listEvents(documentId) {
|
|
211
|
+
return (await rows(db, `SELECT * FROM "fiscal_document_events" WHERE "document_id" = $1 ORDER BY "seq"`, documentId)).map(eventOf);
|
|
212
|
+
},
|
|
213
|
+
saveTransition: (previous, transition) => db.$transaction((tx) => saveRow(tx, previous, transition)),
|
|
214
|
+
listDue: ({ now, limit }) =>
|
|
215
|
+
documents(
|
|
216
|
+
`SELECT * FROM "fiscal_documents" WHERE "attention" = false AND "next_attempt_at" <= $1::timestamp(3) AND ${OWED}
|
|
217
|
+
ORDER BY "next_attempt_at", "id" LIMIT $2`,
|
|
218
|
+
now, limit,
|
|
219
|
+
),
|
|
220
|
+
listContingency: ({ now, limit }) =>
|
|
221
|
+
documents(
|
|
222
|
+
`SELECT * FROM "fiscal_documents" WHERE "attention" = false AND "next_attempt_at" <= $1::timestamp(3) AND "status" = 'CONTINGENCY'
|
|
223
|
+
ORDER BY "next_attempt_at", "id" LIMIT $2`,
|
|
224
|
+
now, limit,
|
|
225
|
+
),
|
|
226
|
+
listContingencyDeadline: ({ signedBefore, limit }) =>
|
|
227
|
+
documents(
|
|
228
|
+
`SELECT * FROM "fiscal_documents" WHERE "status" = 'CONTINGENCY' AND "deadline_warned_at" IS NULL
|
|
229
|
+
AND ("contingency" ->> 'since')::timestamptz < $1::timestamptz
|
|
230
|
+
ORDER BY "created_at", "id" LIMIT $2`,
|
|
231
|
+
signedBefore, limit,
|
|
232
|
+
),
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export function createPrismaFiscalStore(config: { readonly prisma: FiscalPrismaClient }): FiscalStore {
|
|
237
|
+
const db = config?.prisma;
|
|
238
|
+
if (typeof db?.$transaction !== "function" || typeof db.$queryRawUnsafe !== "function") {
|
|
239
|
+
throw new TypeError("createPrismaFiscalStore needs prisma: the host's Prisma client.");
|
|
240
|
+
}
|
|
241
|
+
return { ...profileMethods(db), ...documentMethods(db) };
|
|
242
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The number draw, as one SQL statement over the package's migration
|
|
3
|
+
* (`fiscal_number_counters`). A host's `FiscalStore.createDocument` runs it
|
|
4
|
+
* and the document INSERT in ONE transaction: the row lock this UPDATE takes
|
|
5
|
+
* serialises concurrent draws on a series, and a failed insert rolls the
|
|
6
|
+
* counter back with it, so a series has no gap a failed write made. The only
|
|
7
|
+
* gaps left are numbers SEFAZ never used (a rejection, a replaced document),
|
|
8
|
+
* which the sweep inutilizes.
|
|
9
|
+
*
|
|
10
|
+
* Parameters: `$1` the issuer's CNPJ, `$2` environment, `$3` model, `$4` series,
|
|
11
|
+
* `$5` issuing point id. No row comes back when the series is not that
|
|
12
|
+
* point's; an exhausted series fails the counter's CHECK (at most
|
|
13
|
+
* 1 000 000 000, the next number after 999 999 999), and the transaction with it.
|
|
14
|
+
*/
|
|
15
|
+
export const FISCAL_NEXT_NUMBER_SQL = `UPDATE "fiscal_number_counters"
|
|
16
|
+
SET "next_number" = "next_number" + 1, "updated_at" = CURRENT_TIMESTAMP
|
|
17
|
+
WHERE "issuer_cnpj" = $1 AND "environment" = $2 AND "model" = $3 AND "series" = $4 AND "issuing_point_id" = $5
|
|
18
|
+
RETURNING "next_number" - 1 AS "number"`;
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The steps that issue a document, each one call and the transition its
|
|
3
|
+
* answer earns. The mapping of the service's classes:
|
|
4
|
+
*
|
|
5
|
+
* | answer | on a document being issued | on a contingency document being transmitted |
|
|
6
|
+
* |---|---|---|
|
|
7
|
+
* | `AUTHORIZED` / `DENIED` | AUTHORIZE / DENY | AUTHORIZE / DENY |
|
|
8
|
+
* | `REJECTED`, `INVALID`, `INTERNAL` | REJECT: the number is voided (looked up first if a send went unanswered) | REJECT: kept for the store to correct and resend |
|
|
9
|
+
* | `CONTINGENCY`, NFC-e, point with a contingency series | a second document, offline, replacing this one in one transaction | RETRY |
|
|
10
|
+
* | `CONTINGENCY` otherwise, `RETRYABLE`, `AUTH` | RETRY, with backoff; a person after `MAX_FAILURES` | RETRY |
|
|
11
|
+
*
|
|
12
|
+
* An online NFC-e is never sent again past `nfceOnlineToleranceMs` (SEFAZ
|
|
13
|
+
* refuses a late `dhEmi`): where the point has a contingency series it goes
|
|
14
|
+
* offline instead.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { IssuerFailure, SigningMaterial } from "../issuer/port";
|
|
18
|
+
import { FISCAL_ISSUE } from "../manifest/permissions";
|
|
19
|
+
import type { IssuedDocument } from "../sidecar/types";
|
|
20
|
+
import { FISCAL_DOCUMENT_REJECTED, type FiscalContext, draftOf, xmlKeys } from "./context";
|
|
21
|
+
import { FiscalDocumentError } from "./errors";
|
|
22
|
+
import { digestOf } from "./nfe-proc";
|
|
23
|
+
import type { EmitterProfile, IssuingPoint } from "./profile";
|
|
24
|
+
import type { FiscalDocument } from "./types";
|
|
25
|
+
|
|
26
|
+
const FINAL_FAILURES = new Set<IssuerFailure["class"]>(["REJECTED", "INVALID", "INTERNAL"]);
|
|
27
|
+
|
|
28
|
+
async function reject(ctx: FiscalContext, document: FiscalDocument, error: IssuerFailure): Promise<FiscalDocument> {
|
|
29
|
+
const rejected = await ctx.advance(document, { kind: "REJECT", error });
|
|
30
|
+
await ctx.config.notify.emit({
|
|
31
|
+
type: FISCAL_DOCUMENT_REJECTED,
|
|
32
|
+
recipient: { tenantId: document.ownerId, permission: FISCAL_ISSUE },
|
|
33
|
+
payload: {
|
|
34
|
+
documentId: document.id,
|
|
35
|
+
subjectId: document.subjectId,
|
|
36
|
+
model: document.model,
|
|
37
|
+
series: document.series,
|
|
38
|
+
number: document.number,
|
|
39
|
+
code: error.code,
|
|
40
|
+
reason: error.message,
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
return rejected;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function accept(ctx: FiscalContext, document: FiscalDocument, answer: IssuedDocument): Promise<FiscalDocument> {
|
|
47
|
+
const xmlKey = xmlKeys.authorized(answer.accessKey);
|
|
48
|
+
await ctx.config.storage.put(xmlKey, answer.authorizedXml, "application/xml");
|
|
49
|
+
return ctx.advance(document, { kind: answer.status === "AUTHORIZED" ? "AUTHORIZE" : "DENY", answer, xmlKey });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function canGoOffline(document: FiscalDocument, point: IssuingPoint): boolean {
|
|
53
|
+
return document.model === "NFCE" && document.seriesKind === "ONLINE" && point.contingencySeries !== null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** An online NFC-e whose `dhEmi` SEFAZ would now refuse as late. */
|
|
57
|
+
function pastOnlineTolerance(ctx: FiscalContext, document: FiscalDocument): boolean {
|
|
58
|
+
return ctx.config.now().getTime() - Date.parse(document.createdAt) > ctx.config.nfceOnlineToleranceMs;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Sign a contingency-series document offline. On a failure it is left as it was, for the caller to defer. */
|
|
62
|
+
async function signOffline(
|
|
63
|
+
ctx: FiscalContext,
|
|
64
|
+
document: FiscalDocument,
|
|
65
|
+
profile: EmitterProfile,
|
|
66
|
+
signing: SigningMaterial,
|
|
67
|
+
): Promise<{ document: FiscalDocument; error: IssuerFailure | null }> {
|
|
68
|
+
const contingency = { since: await ctx.localNow(profile.ownerId), reason: ctx.config.reasons.contingency };
|
|
69
|
+
const outcome = await ctx.config.issuer.signContingency({ environment: document.environment, signing, document: document.sale, contingency });
|
|
70
|
+
if (!outcome.ok) return { document, error: outcome.error };
|
|
71
|
+
const xmlKey = xmlKeys.signed(outcome.answer.accessKey);
|
|
72
|
+
await ctx.config.storage.put(xmlKey, outcome.answer.signedXml, "application/xml");
|
|
73
|
+
return { document: await ctx.advance(document, { kind: "SIGN_OFFLINE", answer: outcome.answer, contingency, xmlKey }), error: null };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Sign a PENDING contingency document; a failure is deferred (it stays PENDING, the sweep signs it later). */
|
|
77
|
+
export async function signPending(
|
|
78
|
+
ctx: FiscalContext,
|
|
79
|
+
document: FiscalDocument,
|
|
80
|
+
profile: EmitterProfile,
|
|
81
|
+
signing: SigningMaterial,
|
|
82
|
+
): Promise<FiscalDocument> {
|
|
83
|
+
const signed = await signOffline(ctx, document, profile, signing);
|
|
84
|
+
if (signed.error === null) return signed.document;
|
|
85
|
+
return ctx.advance(document, {
|
|
86
|
+
kind: "DEFER",
|
|
87
|
+
reason: "signing offline failed",
|
|
88
|
+
error: signed.error,
|
|
89
|
+
// Signing is local: a certificate that does not open (AUTH) will not open on the next try either.
|
|
90
|
+
attention: FINAL_FAILURES.has(signed.error.class) || signed.error.class === "AUTH",
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Move the sale offline: number a second document on the contingency series
|
|
96
|
+
* AND replace this one, in ONE transaction, before anything is signed — so a
|
|
97
|
+
* crash can never leave the online document to be sent again beside its twin.
|
|
98
|
+
* Signing follows; if it fails, the new document waits PENDING for the sweep.
|
|
99
|
+
*/
|
|
100
|
+
async function goOffline(
|
|
101
|
+
ctx: FiscalContext,
|
|
102
|
+
document: FiscalDocument,
|
|
103
|
+
profile: EmitterProfile,
|
|
104
|
+
point: IssuingPoint,
|
|
105
|
+
signing: SigningMaterial,
|
|
106
|
+
): Promise<FiscalDocument> {
|
|
107
|
+
const offline = await ctx.createNumbered({
|
|
108
|
+
profile,
|
|
109
|
+
point,
|
|
110
|
+
subjectId: document.subjectId,
|
|
111
|
+
model: document.model,
|
|
112
|
+
seriesKind: "CONTINGENCY",
|
|
113
|
+
draft: draftOf(document.sale),
|
|
114
|
+
replacing: document,
|
|
115
|
+
});
|
|
116
|
+
return signPending(ctx, offline, profile, signing);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* The signed XML a failed call returned, stored UNDER ITS DIGEST and never
|
|
121
|
+
* over another: each send under a key may carry a different XML (a service
|
|
122
|
+
* upgrade between sends changes `verProc`, say), and only the one SEFAZ
|
|
123
|
+
* authorised may become the `nfeProc`. A lookup reads the protocol's `digVal`
|
|
124
|
+
* and fetches exactly that XML (`xmlKeys.signedByDigest`), so pairing is by
|
|
125
|
+
* digest, not by "the last one stored". `xmlKey` points at the latest.
|
|
126
|
+
*/
|
|
127
|
+
async function keepSigned(ctx: FiscalContext, document: FiscalDocument, error: IssuerFailure): Promise<{ xmlKey?: string }> {
|
|
128
|
+
const key = document.accessKey ?? error.accessKey;
|
|
129
|
+
const digest = error.signedXml === null ? null : digestOf(error.signedXml);
|
|
130
|
+
if (error.signedXml === null || key === null || digest === null) return {};
|
|
131
|
+
const xmlKey = xmlKeys.signedByDigest(key, digest);
|
|
132
|
+
await ctx.config.storage.put(xmlKey, error.signedXml, "application/xml");
|
|
133
|
+
return { xmlKey };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* An online NFC-e SEFAZ would now refuse as late, at a point that can go
|
|
138
|
+
* offline. A document a lookup found authorised (its protocol is kept) is
|
|
139
|
+
* SEFAZ's: sending the same call again fetches its XML (the service settles
|
|
140
|
+
* the duplicate by a lookup), and it must never go offline beside its own
|
|
141
|
+
* authorisation.
|
|
142
|
+
*/
|
|
143
|
+
function staleOnline(ctx: FiscalContext, document: FiscalDocument, point: IssuingPoint): boolean {
|
|
144
|
+
const knownToSefaz = document.status === "SUBMITTED" && document.protocol !== null;
|
|
145
|
+
return !knownToSefaz && canGoOffline(document, point) && pastOnlineTolerance(ctx, document);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Issue (or re-issue, for a SUBMITTED one) a document on its online series. */
|
|
149
|
+
export async function submit(
|
|
150
|
+
ctx: FiscalContext,
|
|
151
|
+
document: FiscalDocument,
|
|
152
|
+
profile: EmitterProfile,
|
|
153
|
+
point: IssuingPoint,
|
|
154
|
+
signing: SigningMaterial,
|
|
155
|
+
): Promise<FiscalDocument> {
|
|
156
|
+
if (staleOnline(ctx, document, point)) return goOffline(ctx, document, profile, point, signing);
|
|
157
|
+
const sent = document.status === "PENDING" ? await ctx.advance(document, { kind: "SUBMIT" }) : document;
|
|
158
|
+
const outcome = await ctx.config.issuer.issue({ model: sent.model, environment: sent.environment, signing, document: sent.sale });
|
|
159
|
+
if (outcome.ok) return accept(ctx, sent, outcome.answer);
|
|
160
|
+
if (FINAL_FAILURES.has(outcome.error.class)) return reject(ctx, sent, outcome.error);
|
|
161
|
+
const retried = await ctx.advance(sent, { kind: "RETRY", error: outcome.error, ...(await keepSigned(ctx, sent, outcome.error)) });
|
|
162
|
+
return outcome.error.class === "CONTINGENCY" && canGoOffline(retried, point) ? goOffline(ctx, retried, profile, point, signing) : retried;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Transmit a document signed offline. */
|
|
166
|
+
export async function transmit(ctx: FiscalContext, document: FiscalDocument, signing: SigningMaterial): Promise<FiscalDocument> {
|
|
167
|
+
const signedXml = document.xmlKey === null ? null : await ctx.config.storage.get(document.xmlKey);
|
|
168
|
+
if (signedXml === null) throw new FiscalDocumentError("NOT_FOUND", `document ${document.id} has no signed XML in storage.`);
|
|
169
|
+
const outcome = await ctx.config.issuer.transmit({ model: document.model, environment: document.environment, signing, signedXml });
|
|
170
|
+
if (outcome.ok) return accept(ctx, document, outcome.answer);
|
|
171
|
+
if (FINAL_FAILURES.has(outcome.error.class)) return reject(ctx, document, outcome.error);
|
|
172
|
+
return ctx.advance(document, { kind: "RETRY", error: outcome.error });
|
|
173
|
+
}
|