@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.
Files changed (140) hide show
  1. package/README.md +152 -7
  2. package/dist/chunk-27B4HNO6.js +574 -0
  3. package/dist/chunk-27B4HNO6.js.map +1 -0
  4. package/dist/chunk-3SDXLSG4.js +24 -0
  5. package/dist/chunk-3SDXLSG4.js.map +1 -0
  6. package/dist/chunk-ALABGVPO.js +247 -0
  7. package/dist/chunk-ALABGVPO.js.map +1 -0
  8. package/dist/chunk-FOFIN5M7.js +14 -0
  9. package/dist/chunk-FOFIN5M7.js.map +1 -0
  10. package/dist/chunk-HQ2NXSTX.js +85 -0
  11. package/dist/chunk-HQ2NXSTX.js.map +1 -0
  12. package/dist/chunk-PNTKG3DZ.js +47 -0
  13. package/dist/chunk-PNTKG3DZ.js.map +1 -0
  14. package/dist/chunk-RRFKYVLZ.js +192 -0
  15. package/dist/chunk-RRFKYVLZ.js.map +1 -0
  16. package/dist/chunk-V5ZQAAJT.js +210 -0
  17. package/dist/chunk-V5ZQAAJT.js.map +1 -0
  18. package/dist/chunk-X6MRDUYH.js +21 -0
  19. package/dist/chunk-X6MRDUYH.js.map +1 -0
  20. package/dist/chunk-XQGW5HUG.js +30 -0
  21. package/dist/chunk-XQGW5HUG.js.map +1 -0
  22. package/dist/context-ChnWR4Kb.d.ts +455 -0
  23. package/dist/danfe/en-US.d.ts +12 -0
  24. package/dist/danfe/en-US.js +51 -0
  25. package/dist/danfe/en-US.js.map +1 -0
  26. package/dist/danfe/index.d.ts +50 -0
  27. package/dist/danfe/index.js +18 -0
  28. package/dist/danfe/index.js.map +1 -0
  29. package/dist/danfe/pt-BR.d.ts +11 -0
  30. package/dist/danfe/pt-BR.js +51 -0
  31. package/dist/danfe/pt-BR.js.map +1 -0
  32. package/dist/documents/index.d.ts +169 -0
  33. package/dist/documents/index.js +1228 -0
  34. package/dist/documents/index.js.map +1 -0
  35. package/dist/engine/index.d.ts +3 -246
  36. package/dist/http.d.ts +73 -0
  37. package/dist/http.js +16 -0
  38. package/dist/http.js.map +1 -0
  39. package/dist/issuer/index.d.ts +43 -0
  40. package/dist/issuer/index.js +131 -0
  41. package/dist/issuer/index.js.map +1 -0
  42. package/dist/jobs.d.ts +74 -0
  43. package/dist/jobs.js +22 -0
  44. package/dist/jobs.js.map +1 -0
  45. package/dist/labels-BNvflT0h.d.ts +44 -0
  46. package/dist/manifest/index.d.ts +30 -16
  47. package/dist/manifest/index.js +11 -17
  48. package/dist/manifest/index.js.map +1 -1
  49. package/dist/manifest/server.d.ts +57 -0
  50. package/dist/manifest/server.js +25 -0
  51. package/dist/manifest/server.js.map +1 -0
  52. package/dist/notifications.d.ts +93 -0
  53. package/dist/notifications.js +41 -0
  54. package/dist/notifications.js.map +1 -0
  55. package/dist/port-DpRFK56U.d.ts +238 -0
  56. package/dist/sale/index.d.ts +243 -0
  57. package/dist/sale/index.js +1 -0
  58. package/dist/sale/index.js.map +1 -0
  59. package/dist/service-KTjH7AxW.d.ts +139 -0
  60. package/dist/sidecar/index.d.ts +216 -0
  61. package/dist/sidecar/index.js +8 -0
  62. package/dist/sidecar/index.js.map +1 -0
  63. package/dist/types-B1b8LIWX.d.ts +247 -0
  64. package/package.json +63 -5
  65. package/prisma/fiscal.prisma +158 -0
  66. package/prisma/migrations/20261113220000_fiscal_documents/migration.sql +201 -0
  67. package/sidecar/.dockerignore +5 -0
  68. package/sidecar/Dockerfile +68 -0
  69. package/sidecar/README.md +149 -0
  70. package/sidecar/composer.json +30 -0
  71. package/sidecar/composer.lock +2224 -0
  72. package/sidecar/docker/apache.conf +14 -0
  73. package/sidecar/docker/icp-brasil.pem +8031 -0
  74. package/sidecar/docker/mpm.conf +17 -0
  75. package/sidecar/docker/openssl.cnf +16 -0
  76. package/sidecar/docker/php.ini +19 -0
  77. package/sidecar/public/index.php +15 -0
  78. package/sidecar/schema/sale-for-document.schema.json +401 -0
  79. package/sidecar/src/ErrorClass.php +31 -0
  80. package/sidecar/src/Http/Request.php +48 -0
  81. package/sidecar/src/Http/Response.php +32 -0
  82. package/sidecar/src/Http/Router.php +59 -0
  83. package/sidecar/src/Kernel.php +99 -0
  84. package/sidecar/src/Module.php +31 -0
  85. package/sidecar/src/Nfe/Classifier.php +89 -0
  86. package/sidecar/src/Nfe/Credentials.php +52 -0
  87. package/sidecar/src/Nfe/DocumentMapper.php +383 -0
  88. package/sidecar/src/Nfe/DocumentSchema.php +39 -0
  89. package/sidecar/src/Nfe/Input.php +125 -0
  90. package/sidecar/src/Nfe/Model.php +17 -0
  91. package/sidecar/src/Nfe/NfeModule.php +62 -0
  92. package/sidecar/src/Nfe/NfeService.php +504 -0
  93. package/sidecar/src/Nfe/Sefaz.php +49 -0
  94. package/sidecar/src/Nfe/SefazReply.php +81 -0
  95. package/sidecar/src/Nfe/Transport/CurlTransport.php +198 -0
  96. package/sidecar/src/Nfe/Transport/SoapAdapter.php +57 -0
  97. package/sidecar/src/Nfe/Transport/Transport.php +20 -0
  98. package/sidecar/src/Nfe/Transport/TransportFailure.php +42 -0
  99. package/sidecar/src/RequestLog.php +54 -0
  100. package/sidecar/src/ServiceError.php +69 -0
  101. package/src/danfe/en-US.ts +53 -0
  102. package/src/danfe/index.ts +11 -0
  103. package/src/danfe/labels.ts +49 -0
  104. package/src/danfe/pt-BR.ts +52 -0
  105. package/src/danfe/render.ts +265 -0
  106. package/src/danfe/xml.ts +45 -0
  107. package/src/documents/context.ts +260 -0
  108. package/src/documents/errors.ts +41 -0
  109. package/src/documents/helpers.ts +128 -0
  110. package/src/documents/index.ts +39 -0
  111. package/src/documents/lines.ts +63 -0
  112. package/src/documents/machine-steps.ts +260 -0
  113. package/src/documents/machine.ts +128 -0
  114. package/src/documents/memory.ts +138 -0
  115. package/src/documents/nfe-proc.ts +51 -0
  116. package/src/documents/ports.ts +130 -0
  117. package/src/documents/profile-input.ts +168 -0
  118. package/src/documents/profile.ts +98 -0
  119. package/src/documents/service-profile.ts +104 -0
  120. package/src/documents/service.ts +296 -0
  121. package/src/documents/settle.ts +121 -0
  122. package/src/documents/signing.ts +61 -0
  123. package/src/documents/sql-rows.ts +180 -0
  124. package/src/documents/sql-store.ts +242 -0
  125. package/src/documents/sql.ts +18 -0
  126. package/src/documents/steps.ts +173 -0
  127. package/src/documents/tests/integration/pglite.ts +73 -0
  128. package/src/documents/types.ts +193 -0
  129. package/src/http.ts +264 -0
  130. package/src/issuer/index.ts +9 -0
  131. package/src/issuer/port.ts +109 -0
  132. package/src/issuer/sidecar.ts +171 -0
  133. package/src/jobs.ts +115 -0
  134. package/src/manifest/index.ts +25 -16
  135. package/src/manifest/server.ts +20 -0
  136. package/src/notifications.ts +120 -0
  137. package/src/sale/index.ts +8 -0
  138. package/src/sale/types.ts +292 -0
  139. package/src/sidecar/index.ts +9 -0
  140. package/src/sidecar/types.ts +243 -0
@@ -0,0 +1,104 @@
1
+ /**
2
+ * The profile half of the document service: the emitter profile, the
3
+ * certificate upload and the issuing points. A secret is encrypted through the
4
+ * host's cipher the moment it arrives, and only its ciphertext is stored.
5
+ */
6
+
7
+ import type { FiscalContext, FiscalDocumentsConfig } from "./context";
8
+ import { FiscalDocumentError } from "./errors";
9
+ import type { Cipher } from "./ports";
10
+ import type { CertificateUpload, EmitterProfileInput, IssuingPointInput } from "./profile-input";
11
+ import type { EmitterProfile, IssuingPoint } from "./profile";
12
+
13
+ /** What the host learns from an A1 without this package parsing PKCS#12. */
14
+ export interface CertificateFacts {
15
+ /** `notAfter`, ISO 8601. */
16
+ readonly expiresAt: string;
17
+ }
18
+
19
+ export interface FiscalDocumentsServiceConfig extends FiscalDocumentsConfig {
20
+ /** Encrypts the certificate, its password and the CSC on arrival. */
21
+ readonly cipher: Cipher;
22
+ /**
23
+ * Reads the expiry out of an uploaded A1; throws when the file does not
24
+ * open with the password. The host's: Node's crypto cannot open every A1
25
+ * (most issued before 2023 use RC2-40), and this package adds no parser.
26
+ */
27
+ readonly readCertificate: (certificate: CertificateUpload) => Promise<CertificateFacts>;
28
+ }
29
+
30
+ export interface Deps {
31
+ readonly ctx: FiscalContext;
32
+ readonly config: FiscalDocumentsServiceConfig;
33
+ }
34
+
35
+ /**
36
+ * The CSC's ciphertext a save leaves: the CSC id and token are one secret, so
37
+ * a new id needs its token, a token needs an id, and no id clears both.
38
+ */
39
+ async function cscCiphertextFor(
40
+ config: FiscalDocumentsServiceConfig,
41
+ stored: EmitterProfile | null,
42
+ input: Pick<EmitterProfileInput, "cscId" | "cscToken">,
43
+ ): Promise<string | null> {
44
+ if (input.cscToken !== null) {
45
+ if (input.cscId === null) throw new FiscalDocumentError("INVALID_INPUT", "cscId is required with cscToken.");
46
+ return config.cipher.encrypt(input.cscToken);
47
+ }
48
+ if (input.cscId === null) return null;
49
+ if (input.cscId !== stored?.cscId) throw new FiscalDocumentError("INVALID_INPUT", "cscToken is required with a new cscId.");
50
+ return stored.cscCiphertext;
51
+ }
52
+
53
+ export async function saveProfile({ ctx, config }: Deps, ownerId: string, input: EmitterProfileInput): Promise<EmitterProfile> {
54
+ const stored = await config.store.getProfile(ownerId);
55
+ const fields = Object.fromEntries(Object.entries(input).filter(([key]) => key !== "cscToken")) as Omit<EmitterProfileInput, "cscToken">;
56
+ const profile: EmitterProfile = {
57
+ ...fields,
58
+ ownerId,
59
+ certificateCiphertext: stored?.certificateCiphertext ?? null,
60
+ certificatePasswordCiphertext: stored?.certificatePasswordCiphertext ?? null,
61
+ certificateExpiresAt: stored?.certificateExpiresAt ?? null,
62
+ cscCiphertext: await cscCiphertextFor(config, stored, input),
63
+ updatedAt: ctx.nowIso(),
64
+ };
65
+ await config.store.saveProfile(profile);
66
+ return profile;
67
+ }
68
+
69
+ export async function uploadCertificate({ ctx, config }: Deps, ownerId: string, certificate: CertificateUpload): Promise<EmitterProfile> {
70
+ const stored = await ctx.requireProfile(ownerId);
71
+ let facts: CertificateFacts;
72
+ try {
73
+ facts = await config.readCertificate(certificate);
74
+ } catch {
75
+ // The reader's own message may quote what it was given; this one never does.
76
+ throw new FiscalDocumentError("INVALID_INPUT", "the certificate does not open with that password.");
77
+ }
78
+ const profile: EmitterProfile = {
79
+ ...stored,
80
+ certificateCiphertext: await config.cipher.encrypt(certificate.pfxBase64),
81
+ certificatePasswordCiphertext: await config.cipher.encrypt(certificate.password),
82
+ certificateExpiresAt: facts.expiresAt,
83
+ updatedAt: ctx.nowIso(),
84
+ };
85
+ await config.store.saveProfile(profile);
86
+ return profile;
87
+ }
88
+
89
+ export async function createIssuingPoint({ ctx, config }: Deps, ownerId: string, input: IssuingPointInput): Promise<IssuingPoint> {
90
+ const profile = await ctx.requireProfile(ownerId);
91
+ if (input.model === "NFE" && input.contingencySeries !== null) {
92
+ throw new FiscalDocumentError("INVALID_INPUT", "an NF-e issuing point has no contingency series: the service has no offline NF-e path.");
93
+ }
94
+ const point: IssuingPoint = {
95
+ id: input.id,
96
+ ownerId,
97
+ model: input.model,
98
+ onlineSeries: input.onlineSeries,
99
+ contingencySeries: input.contingencySeries,
100
+ createdAt: ctx.nowIso(),
101
+ };
102
+ await config.store.createIssuingPoint(point, profile.cnpj, { online: input.firstOnlineNumber, contingency: input.firstContingencyNumber });
103
+ return point;
104
+ }
@@ -0,0 +1,296 @@
1
+ /**
2
+ * `createFiscalDocuments` — the document service: the emitter profile, the
3
+ * issuing points, and issuing, cancelling, looking up and sweeping documents
4
+ * over the host's ports. Every SEFAZ step goes through the Issuer port and
5
+ * every state change through the state machine (`./machine`), persisted with
6
+ * its event and its next attempt.
7
+ *
8
+ * The certificate, its password and the CSC are encrypted through the host's
9
+ * cipher the moment they arrive, decrypted by the signing identity for one
10
+ * call, and never logged, answered or put in an error.
11
+ */
12
+
13
+ import type { IssuerFailure } from "../issuer/port";
14
+ import { FISCAL_ISSUE } from "../manifest/permissions";
15
+ import type { LookedUpDocument } from "../sidecar/types";
16
+ import { FISCAL_CONTINGENCY_DEADLINE, FiscalContext, assertConfig, assertReason, issuerOf, totalsOf, xmlKeys } from "./context";
17
+ import { FiscalDocumentError } from "./errors";
18
+ import { canTransition } from "./machine";
19
+ import { type Deps, type FiscalDocumentsServiceConfig, createIssuingPoint, saveProfile, uploadCertificate } from "./service-profile";
20
+ import { settleNumber, settleWithXml, storeNfeProc } from "./settle";
21
+ import { signPending, submit, transmit } from "./steps";
22
+ import { type DocumentTotals, type FiscalDocument, type FiscalDocumentModel, isLive } from "./types";
23
+
24
+ export type { CertificateFacts, FiscalDocumentsServiceConfig } from "./service-profile";
25
+
26
+ export interface SweepReport {
27
+ readonly advanced: Array<{ readonly documentId: string; readonly status: FiscalDocument["status"] }>;
28
+ readonly failures: Array<{ readonly documentId: string; readonly message: string }>;
29
+ }
30
+
31
+ export interface IssueInput {
32
+ readonly ownerId: string;
33
+ readonly subjectId: string;
34
+ readonly issuingPointId: string;
35
+ readonly model: FiscalDocumentModel;
36
+ }
37
+
38
+ /** How long an NFC-e may wait in contingency before it must be transmitted (24 h); the warning goes out at 20 h. */
39
+ export const CONTINGENCY_WARNING_AFTER_MS = 20 * 3_600_000;
40
+
41
+ /** A step's failure that no retry will cure: the document waits for a person. */
42
+ const NEEDS_A_PERSON = new Set(["NOT_SUPPORTED", "NOT_ISSUABLE", "NOT_FOUND", "INVALID_INPUT", "SERIES_EXHAUSTED"]);
43
+
44
+ async function issuable({ ctx }: Deps, ownerId: string, issuingPointId: string, model: FiscalDocumentModel) {
45
+ const profile = await ctx.requireProfile(ownerId);
46
+ if (profile.documentPolicy !== "ISSUED_HERE") {
47
+ throw new FiscalDocumentError("NOT_ISSUABLE", `owner ${ownerId}'s documentPolicy is ${profile.documentPolicy}.`);
48
+ }
49
+ const point = await ctx.requirePoint(ownerId, issuingPointId);
50
+ if (point.model !== model) throw new FiscalDocumentError("INVALID_INPUT", `issuing point ${point.id} issues ${point.model}, not ${model}.`);
51
+ return { profile, point };
52
+ }
53
+
54
+ async function liveDocument({ config }: Deps, input: Omit<IssueInput, "issuingPointId">): Promise<FiscalDocument | null> {
55
+ const live = (await config.store.listBySubject(input.ownerId, input.subjectId, input.model)).filter(isLive);
56
+ return live[live.length - 1] ?? null;
57
+ }
58
+
59
+ async function requireDocument({ config }: Deps, ownerId: string, documentId: string): Promise<FiscalDocument> {
60
+ const document = await config.store.getDocument(ownerId, documentId);
61
+ if (document === null) throw new FiscalDocumentError("NOT_FOUND", `owner ${ownerId} has no document ${documentId}.`);
62
+ return document;
63
+ }
64
+
65
+ /** Number a new document — or, when the subject already has a live one (a concurrent call won), answer that one. */
66
+ async function numberOrExisting(deps: Deps, input: Omit<IssueInput, "issuingPointId">, create: () => Promise<FiscalDocument>) {
67
+ try {
68
+ return { document: await create(), created: true };
69
+ } catch (error) {
70
+ if (!(error instanceof FiscalDocumentError) || error.code !== "SUBJECT_HAS_DOCUMENT") throw error;
71
+ const existing = await liveDocument(deps, input);
72
+ if (existing === null) throw error;
73
+ return { document: existing, created: false };
74
+ }
75
+ }
76
+
77
+ async function issue(deps: Deps, input: IssueInput): Promise<FiscalDocument> {
78
+ const { profile, point } = await issuable(deps, input.ownerId, input.issuingPointId, input.model);
79
+ const existing = await liveDocument(deps, input);
80
+ if (existing !== null) return existing;
81
+ const signing = await deps.ctx.material(profile);
82
+ const draft = await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: input.subjectId, model: input.model });
83
+ const numbered = await numberOrExisting(deps, input, () =>
84
+ deps.ctx.createNumbered({ profile, point, subjectId: input.subjectId, model: input.model, seriesKind: "ONLINE", draft }),
85
+ );
86
+ return numbered.created ? submit(deps.ctx, numbered.document, profile, point, signing) : numbered.document;
87
+ }
88
+
89
+ /** Sign the sale offline at once (the register knows it is offline). A failure leaves it PENDING for the sweep. */
90
+ async function issueOffline(deps: Deps, input: Omit<IssueInput, "model">): Promise<FiscalDocument> {
91
+ const target = { ...input, model: "NFCE" as const };
92
+ const { profile, point } = await issuable(deps, input.ownerId, input.issuingPointId, "NFCE");
93
+ const existing = await liveDocument(deps, target);
94
+ if (existing !== null) return existing;
95
+ const signing = await deps.ctx.material(profile);
96
+ const draft = await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: input.subjectId, model: "NFCE" });
97
+ const numbered = await numberOrExisting(deps, target, () =>
98
+ deps.ctx.createNumbered({ profile, point, subjectId: input.subjectId, model: "NFCE", seriesKind: "CONTINGENCY", draft }),
99
+ );
100
+ return numbered.created ? signPending(deps.ctx, numbered.document, profile, signing) : numbered.document;
101
+ }
102
+
103
+ /**
104
+ * A contingency NFC-e SEFAZ rejected on transmission: the buyer holds its
105
+ * DANFE, so the number is never voided. The store corrects the sale (the
106
+ * host's `SaleSource` answers the corrected one) and it is signed again
107
+ * under the SAME series, number and key code, then transmitted by the job.
108
+ */
109
+ /** The fields a buyer's DANFE prints and its QR code encodes, which a resend may never change. */
110
+ function printedFieldsChange(document: FiscalDocument, totals: DocumentTotals, buyerTaxId: string | null): boolean {
111
+ return totals.totalCents !== document.totals.totalCents || buyerTaxId !== document.buyerTaxId;
112
+ }
113
+
114
+ /**
115
+ * A contingency NFC-e SEFAZ rejected on transmission: the buyer holds its
116
+ * DANFE, so the number is never voided. The store corrects the sale (the
117
+ * host's `SaleSource` answers the corrected one) and it is signed again
118
+ * under the SAME series, number and key code, then transmitted by the job.
119
+ * A correction that would change the total or the buyer's document — what
120
+ * the DANFE prints and its QR encodes — is refused: that sale needs a new
121
+ * note, issued by a person (decided on FUT-2237).
122
+ */
123
+ async function resendContingency(deps: Deps, input: { ownerId: string; documentId: string }): Promise<FiscalDocument> {
124
+ const document = await requireDocument(deps, input.ownerId, input.documentId);
125
+ if (document.status !== "REJECTED" || document.seriesKind !== "CONTINGENCY" || document.contingency === null) {
126
+ throw new FiscalDocumentError("TRANSITION_REFUSED", `document ${document.id} is not a rejected contingency NFC-e.`);
127
+ }
128
+ const profile = await deps.ctx.requireProfile(input.ownerId);
129
+ const draft = await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: document.subjectId, model: document.model });
130
+ const totals = totalsOf(draft);
131
+ const buyerTaxId = draft.buyer?.document.number ?? null;
132
+ if (printedFieldsChange(document, totals, buyerTaxId)) {
133
+ throw new FiscalDocumentError(
134
+ "RESEND_CHANGES_PRINTED_FIELDS",
135
+ `the correction changes document ${document.id}'s total or buyer, which its DANFE prints: issue a new note.`,
136
+ );
137
+ }
138
+ const sale = { ...draft, series: document.series, number: document.number, keyCode: document.keyCode, issuedAt: document.issuedAt, issuer: issuerOf(profile) };
139
+ const outcome = await deps.config.issuer.signContingency({
140
+ environment: document.environment,
141
+ signing: await deps.ctx.material(profile),
142
+ document: sale,
143
+ contingency: document.contingency,
144
+ });
145
+ if (!outcome.ok) throw new FiscalDocumentError("NOT_ISSUABLE", `the corrected sale could not be signed: ${outcome.error.class} ${outcome.error.code ?? ""}`.trim());
146
+ const xmlKey = xmlKeys.signed(outcome.answer.accessKey);
147
+ await deps.config.storage.put(xmlKey, outcome.answer.signedXml, "application/xml");
148
+ return deps.ctx.advance(document, { kind: "RESIGN", answer: outcome.answer, sale, totals, buyerTaxId, xmlKey });
149
+ }
150
+
151
+ async function cancel(
152
+ deps: Deps,
153
+ input: { ownerId: string; documentId: string; reason: string },
154
+ ): Promise<{ document: FiscalDocument; failure: IssuerFailure | null }> {
155
+ assertReason(input.reason, "reason");
156
+ const document = await requireDocument(deps, input.ownerId, input.documentId);
157
+ if (document.status !== "AUTHORIZED" || document.accessKey === null || document.protocol === null) {
158
+ throw new FiscalDocumentError("TRANSITION_REFUSED", `document ${document.id} is ${document.status}; only an authorised document is cancelled.`);
159
+ }
160
+ const profile = await deps.ctx.requireProfile(input.ownerId);
161
+ const outcome = await deps.config.issuer.cancel({
162
+ model: document.model,
163
+ environment: document.environment,
164
+ signing: await deps.ctx.material(profile),
165
+ accessKey: document.accessKey,
166
+ protocol: document.protocol,
167
+ reason: input.reason,
168
+ });
169
+ if (!outcome.ok) return { document, failure: outcome.error };
170
+ const eventXmlKey = outcome.answer.eventXml === null ? null : xmlKeys.cancel(document.accessKey);
171
+ if (eventXmlKey !== null) await deps.config.storage.put(eventXmlKey, outcome.answer.eventXml ?? "", "application/xml");
172
+ const cancelled = await deps.ctx.advance(document, { kind: "CANCEL", answer: outcome.answer, reason: input.reason, eventXmlKey });
173
+ return { document: cancelled, failure: null };
174
+ }
175
+
176
+ /** Whether a lookup's answer moves this document (a settled number moves only while it is owed one). */
177
+ function lookupMoves(document: FiscalDocument): boolean {
178
+ if (!canTransition(document.status, "LOOKUP")) return false;
179
+ if (document.status === "REPLACED" || document.status === "REJECTED") return document.numberVoid === "LOOKUP_FIRST";
180
+ return true;
181
+ }
182
+
183
+ async function lookup(
184
+ deps: Deps,
185
+ input: { ownerId: string; documentId: string },
186
+ ): Promise<{ document: FiscalDocument; answer: LookedUpDocument | null; failure: IssuerFailure | null }> {
187
+ const document = await requireDocument(deps, input.ownerId, input.documentId);
188
+ if (document.accessKey === null) throw new FiscalDocumentError("NOT_FOUND", `document ${document.id} has no access key yet.`);
189
+ const profile = await deps.ctx.requireProfile(input.ownerId);
190
+ const outcome = await deps.config.issuer.lookup({
191
+ model: document.model,
192
+ environment: document.environment,
193
+ signing: await deps.ctx.material(profile),
194
+ accessKey: document.accessKey,
195
+ });
196
+ if (!outcome.ok) return { document, answer: null, failure: outcome.error };
197
+ if (!lookupMoves(document)) return { document, answer: outcome.answer, failure: null };
198
+ const xmlKey = document.status === "SUBMITTED" ? await storeNfeProc(deps.ctx, document, outcome.answer) : undefined;
199
+ const looked = await deps.ctx.advance(document, { kind: "LOOKUP", answer: outcome.answer, ...(xmlKey === undefined ? {} : { xmlKey }) });
200
+ // A live REJECTED number found SEFAZ's is back to SUBMITTED: settle it now if its XML is held.
201
+ const after = document.status === "REJECTED" ? await settleWithXml(deps.ctx, looked, outcome.answer) : looked;
202
+ return { document: after, answer: outcome.answer, failure: null };
203
+ }
204
+
205
+ /** One step of the sweep on one document: whatever it is owed next. */
206
+ async function step({ ctx }: Deps, document: FiscalDocument): Promise<FiscalDocument> {
207
+ const profile = await ctx.requireProfile(document.ownerId);
208
+ const signing = await ctx.material(profile);
209
+ if (document.numberVoid !== null) return settleNumber(ctx, document, profile, signing);
210
+ if (document.status === "CONTINGENCY") return transmit(ctx, document, signing);
211
+ if (document.seriesKind === "CONTINGENCY") return signPending(ctx, document, profile, signing);
212
+ const point = await ctx.requirePoint(document.ownerId, document.issuingPointId);
213
+ return submit(ctx, document, profile, point, signing);
214
+ }
215
+
216
+ /** A step that threw is never silent: the document is deferred, or handed to a person when no retry will cure it. */
217
+ async function deferThrown(deps: Deps, document: FiscalDocument, error: unknown): Promise<void> {
218
+ if (error instanceof FiscalDocumentError && error.code === "CONFLICT") return;
219
+ const attention = error instanceof FiscalDocumentError && NEEDS_A_PERSON.has(error.code);
220
+ const reason = error instanceof Error ? error.message : "unknown failure";
221
+ const current = (await deps.config.store.getDocument(document.ownerId, document.id)) ?? document;
222
+ await deps.ctx.advance(current, { kind: "DEFER", reason, error: null, attention }).catch(() => undefined);
223
+ }
224
+
225
+ async function run(deps: Deps, documents: readonly FiscalDocument[]): Promise<SweepReport> {
226
+ const report: SweepReport = { advanced: [], failures: [] };
227
+ for (const document of documents) {
228
+ try {
229
+ const after = await step(deps, document);
230
+ report.advanced.push({ documentId: after.id, status: after.status });
231
+ } catch (error) {
232
+ report.failures.push({ documentId: document.id, message: error instanceof Error ? error.message : "unknown failure" });
233
+ await deferThrown(deps, document, error);
234
+ }
235
+ }
236
+ return report;
237
+ }
238
+
239
+ /** Tell the owner of every NFC-e 20 h into contingency (the transmission deadline is 24 h), once each. */
240
+ async function warnContingencyDeadlines(deps: Deps, limit: number): Promise<number> {
241
+ const signedBefore = new Date(deps.config.now().getTime() - CONTINGENCY_WARNING_AFTER_MS).toISOString();
242
+ const due = await deps.config.store.listContingencyDeadline({ signedBefore, limit });
243
+ for (const document of due) {
244
+ const warned = await deps.ctx.advance(document, { kind: "WARN" });
245
+ await deps.config.notify.emit({
246
+ type: FISCAL_CONTINGENCY_DEADLINE,
247
+ recipient: { tenantId: document.ownerId, permission: FISCAL_ISSUE },
248
+ payload: { documentId: warned.id, subjectId: warned.subjectId, series: warned.series, number: warned.number, since: warned.contingency?.since ?? "" },
249
+ });
250
+ }
251
+ return due.length;
252
+ }
253
+
254
+ export function createFiscalDocuments(config: FiscalDocumentsServiceConfig) {
255
+ assertConfig(config);
256
+ if (typeof config.cipher?.encrypt !== "function") throw new TypeError("createFiscalDocuments needs cipher.");
257
+ if (typeof config.readCertificate !== "function") throw new TypeError("createFiscalDocuments needs readCertificate.");
258
+ const deps: Deps = { ctx: new FiscalContext(config), config };
259
+ const { store } = config;
260
+ return {
261
+ getProfile: (ownerId: string) => store.getProfile(ownerId),
262
+ saveProfile: saveProfile.bind(null, deps),
263
+ uploadCertificate: uploadCertificate.bind(null, deps),
264
+ listIssuingPoints: (ownerId: string) => store.listIssuingPoints(ownerId),
265
+ createIssuingPoint: createIssuingPoint.bind(null, deps),
266
+ /** Issue the subject's document, or answer the live one it has. A rejection is final; anything SEFAZ may still answer is the sweep's. */
267
+ issue: issue.bind(null, deps),
268
+ issueOffline: issueOffline.bind(null, deps),
269
+ resendContingency: resendContingency.bind(null, deps),
270
+ /** Cancel an authorised document. A refusal (late, say) answers the issuer's failure and changes nothing. */
271
+ cancel: cancel.bind(null, deps),
272
+ /** Ask SEFAZ what it knows of the key; a state the answer moves is recorded. */
273
+ lookup: lookup.bind(null, deps),
274
+ /** A person takes a document back from `attention`; the sweep tries it again. */
275
+ async release(input: { ownerId: string; documentId: string }): Promise<FiscalDocument> {
276
+ return deps.ctx.advance(await requireDocument(deps, input.ownerId, input.documentId), { kind: "RELEASE" });
277
+ },
278
+ getDocument: requireDocument.bind(null, deps),
279
+ listBySubject: (ownerId: string, subjectId: string, model: FiscalDocumentModel) => store.listBySubject(ownerId, subjectId, model),
280
+ async listEvents(ownerId: string, documentId: string) {
281
+ await requireDocument(deps, ownerId, documentId);
282
+ return store.listEvents(documentId);
283
+ },
284
+ /** One pass of the retry sweep: PENDING/SUBMITTED documents and owed numbers whose next attempt has come. */
285
+ sweep: async (limit: number): Promise<SweepReport> => run(deps, await store.listDue({ now: deps.ctx.nowIso(), limit })),
286
+ /** One pass of the contingency transmission, then the 20-hour deadline warnings. */
287
+ async transmitContingency(limit: number): Promise<SweepReport> {
288
+ const report = await run(deps, await store.listContingency({ now: deps.ctx.nowIso(), limit }));
289
+ await warnContingencyDeadlines(deps, limit);
290
+ return report;
291
+ },
292
+ };
293
+ }
294
+
295
+
296
+ export type FiscalDocuments = ReturnType<typeof createFiscalDocuments>;
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Settling a number SEFAZ never used, so a series has no unexplained gap:
3
+ * look it up first when a send went unanswered, cancel it if SEFAZ authorised
4
+ * it after all (by SUBSTITUTION, event 110112, when a contingency document
5
+ * replaced it), inutilize it otherwise.
6
+ *
7
+ * A call that fails is never silent: it is DEFERRED — one more failure, a
8
+ * later attempt — and a refusal SEFAZ will repeat (241 number used, 256, 501
9
+ * late cancel, a certificate refused) hands the document to a person at once,
10
+ * with the needs-attention notification.
11
+ */
12
+
13
+ import type { IssuerFailure, IssuerOutcome, SigningMaterial } from "../issuer/port";
14
+ import type { CancelledDocument, LookedUpDocument } from "../sidecar/types";
15
+ import { type FiscalContext, xmlKeys } from "./context";
16
+ import { assembleNfeProc, protocolDigestOf } from "./nfe-proc";
17
+ import type { EmitterProfile } from "./profile";
18
+ import type { FiscalDocument, NumberVoid } from "./types";
19
+
20
+ type Settle = (ctx: FiscalContext, document: FiscalDocument, profile: EmitterProfile, signing: SigningMaterial) => Promise<FiscalDocument>;
21
+
22
+ /** A refusal the same call would meet again: a person must look. */
23
+ const REFUSALS = new Set<IssuerFailure["class"]>(["REJECTED", "AUTH", "INVALID", "INTERNAL"]);
24
+
25
+ function defer(ctx: FiscalContext, document: FiscalDocument, what: string, error: IssuerFailure): Promise<FiscalDocument> {
26
+ return ctx.advance(document, { kind: "DEFER", reason: `${what} failed`, error, attention: REFUSALS.has(error.class) });
27
+ }
28
+
29
+ /**
30
+ * A SUBMITTED document a lookup finds authorised or denied: its `nfeProc`,
31
+ * from the signed XML whose digest the protocol's `digVal` names and the
32
+ * protocol itself, stored. `undefined` when either is missing — the document
33
+ * then stays SUBMITTED, owing work, and the sweep sends the same call again
34
+ * for the XML.
35
+ */
36
+ export async function storeNfeProc(ctx: FiscalContext, document: FiscalDocument, answer: LookedUpDocument): Promise<string | undefined> {
37
+ if ((answer.status !== "AUTHORIZED" && answer.status !== "DENIED") || document.accessKey === null) return undefined;
38
+ // The XML the protocol certifies, by its digest; never simply the last one stored.
39
+ const digest = protocolDigestOf(answer.sefazReply);
40
+ if (digest === null) return undefined;
41
+ const signedXml = await ctx.config.storage.get(xmlKeys.signedByDigest(document.accessKey, digest));
42
+ if (signedXml === null) return undefined;
43
+ const nfeProc = assembleNfeProc({ signedXml, sefazReply: answer.sefazReply, accessKey: document.accessKey });
44
+ if (nfeProc === null) return undefined;
45
+ const xmlKey = xmlKeys.authorized(document.accessKey);
46
+ await ctx.config.storage.put(xmlKey, nfeProc, "application/xml");
47
+ return xmlKey;
48
+ }
49
+
50
+ /**
51
+ * A document a lookup just returned to SUBMITTED (a live REJECTED number
52
+ * found SEFAZ's): settled as AUTHORIZED or DENIED with the same answer when
53
+ * the XML the protocol certifies is held. Two steps, never REJECTED →
54
+ * AUTHORIZED in one.
55
+ */
56
+ export async function settleWithXml(ctx: FiscalContext, document: FiscalDocument, answer: LookedUpDocument): Promise<FiscalDocument> {
57
+ if (document.status !== "SUBMITTED") return document;
58
+ const xmlKey = await storeNfeProc(ctx, document, answer);
59
+ return xmlKey === undefined ? document : ctx.advance(document, { kind: "LOOKUP", answer, xmlKey });
60
+ }
61
+
62
+ const lookupFirst: Settle = async (ctx, document, _profile, signing) => {
63
+ if (document.accessKey === null) return ctx.advance(document, { kind: "DEFER", reason: "no access key to look up", error: null, attention: true });
64
+ const outcome = await ctx.config.issuer.lookup({ model: document.model, environment: document.environment, signing, accessKey: document.accessKey });
65
+ if (!outcome.ok) return defer(ctx, document, "the lookup", outcome.error);
66
+ return settleWithXml(ctx, await ctx.advance(document, { kind: "LOOKUP", answer: outcome.answer }), outcome.answer);
67
+ };
68
+
69
+ /** The cancel owed: by substitution when a contingency document replaced it, an ordinary one otherwise. */
70
+ async function sendOwedCancel(ctx: FiscalContext, document: FiscalDocument, signing: SigningMaterial): Promise<IssuerOutcome<CancelledDocument> | null> {
71
+ const { accessKey, protocol, replacedById } = document;
72
+ if (accessKey === null || protocol === null) return null;
73
+ const reason = ctx.config.reasons.substitution;
74
+ const base = { environment: document.environment, signing, accessKey, protocol, reason };
75
+ const substitute = replacedById === null ? null : await ctx.config.store.getDocument(document.ownerId, replacedById);
76
+ if (document.model === "NFCE" && substitute?.accessKey) {
77
+ return ctx.config.issuer.cancelBySubstitution({ ...base, substituteAccessKey: substitute.accessKey });
78
+ }
79
+ return ctx.config.issuer.cancel({ ...base, model: document.model });
80
+ }
81
+
82
+ const cancelOwed: Settle = async (ctx, document, _profile, signing) => {
83
+ const outcome = await sendOwedCancel(ctx, document, signing);
84
+ if (outcome === null) return ctx.advance(document, { kind: "DEFER", reason: "no protocol to cancel with", error: null, attention: true });
85
+ if (!outcome.ok) return defer(ctx, document, "the owed cancel", outcome.error);
86
+ const eventXmlKey = outcome.answer.eventXml === null ? null : xmlKeys.cancel(outcome.answer.accessKey);
87
+ if (eventXmlKey !== null) await ctx.config.storage.put(eventXmlKey, outcome.answer.eventXml ?? "", "application/xml");
88
+ return ctx.advance(document, { kind: "CANCEL", answer: outcome.answer, reason: ctx.config.reasons.substitution, eventXmlKey });
89
+ };
90
+
91
+ const inutilizeOwed: Settle = async (ctx, document, profile, signing) => {
92
+ const outcome = await ctx.config.issuer.inutilize({
93
+ model: document.model,
94
+ environment: document.environment,
95
+ signing,
96
+ uf: profile.address.uf,
97
+ cnpj: document.issuerCnpj,
98
+ year: Number(document.issuedAt.slice(0, 4)),
99
+ series: document.series,
100
+ from: document.number,
101
+ to: document.number,
102
+ reason: ctx.config.reasons.inutilization,
103
+ });
104
+ if (!outcome.ok) return defer(ctx, document, "the inutilization", outcome.error);
105
+ const xml = outcome.answer.inutilizationXml;
106
+ const eventXmlKey = xml === null ? null : xmlKeys.inutilization(document);
107
+ if (eventXmlKey !== null) await ctx.config.storage.put(eventXmlKey, xml ?? "", "application/xml");
108
+ return ctx.advance(document, { kind: "INUTILIZE", answer: outcome.answer, eventXmlKey });
109
+ };
110
+
111
+ const SETTLE: Partial<Record<NumberVoid, Settle>> = {
112
+ LOOKUP_FIRST: lookupFirst,
113
+ CANCEL: cancelOwed,
114
+ INUTILIZE: inutilizeOwed,
115
+ };
116
+
117
+ /** Settle what a replaced or rejected document still owes on its number. */
118
+ export async function settleNumber(ctx: FiscalContext, document: FiscalDocument, profile: EmitterProfile, signing: SigningMaterial): Promise<FiscalDocument> {
119
+ const settle = document.numberVoid === null ? undefined : SETTLE[document.numberVoid];
120
+ return settle === undefined ? document : settle(ctx, document, profile, signing);
121
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The SigningIdentity port: who signs a call. It turns a profile into the
3
+ * {@link SigningMaterial} for ONE call to the issuer; the material is never
4
+ * stored, logged or put in an error.
5
+ *
6
+ * - `STORE_CERTIFICATE` ships now: the store's own A1, decrypted through the
7
+ * host's {@link Cipher} at the moment of the call.
8
+ * - `PLATFORM` is declared and answers `NOT_SUPPORTED` until FUT-2229
9
+ * question 4 says how the platform signs on a store's behalf.
10
+ */
11
+
12
+ import type { SigningMaterial } from "../issuer/port";
13
+ import { FiscalDocumentError } from "./errors";
14
+ import type { Cipher } from "./ports";
15
+ import type { EmitterProfile, SigningIdentityKind } from "./profile";
16
+
17
+ export interface SigningIdentity {
18
+ readonly kind: SigningIdentityKind;
19
+ materialFor(profile: EmitterProfile): Promise<SigningMaterial>;
20
+ }
21
+
22
+ export type SigningIdentities = Readonly<Record<SigningIdentityKind, SigningIdentity>>;
23
+
24
+ export function createStoreCertificateIdentity(config: { readonly cipher: Cipher }): SigningIdentity {
25
+ if (typeof config?.cipher?.decrypt !== "function") throw new TypeError("createStoreCertificateIdentity needs a cipher.");
26
+ const { cipher } = config;
27
+ return {
28
+ kind: "STORE_CERTIFICATE",
29
+ async materialFor(profile) {
30
+ if (profile.certificateCiphertext === null || profile.certificatePasswordCiphertext === null) {
31
+ throw new FiscalDocumentError("NOT_ISSUABLE", `owner ${profile.ownerId} has no certificate.`);
32
+ }
33
+ const [pfxBase64, password] = await Promise.all([
34
+ cipher.decrypt(profile.certificateCiphertext),
35
+ cipher.decrypt(profile.certificatePasswordCiphertext),
36
+ ]);
37
+ const csc =
38
+ profile.cscId !== null && profile.cscCiphertext !== null
39
+ ? { id: profile.cscId, token: await cipher.decrypt(profile.cscCiphertext) }
40
+ : null;
41
+ return { certificate: { pfxBase64, password }, csc };
42
+ },
43
+ };
44
+ }
45
+
46
+ export function createPlatformIdentity(): SigningIdentity {
47
+ return {
48
+ kind: "PLATFORM",
49
+ async materialFor(profile) {
50
+ throw new FiscalDocumentError(
51
+ "NOT_SUPPORTED",
52
+ `owner ${profile.ownerId} signs as PLATFORM, which is declared and not built yet (FUT-2229 q4).`,
53
+ );
54
+ },
55
+ };
56
+ }
57
+
58
+ /** The two identities over one cipher: what a host passes as `signing`. */
59
+ export function createSigningIdentities(config: { readonly cipher: Cipher }): SigningIdentities {
60
+ return { STORE_CERTIFICATE: createStoreCertificateIdentity(config), PLATFORM: createPlatformIdentity() };
61
+ }