@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,171 @@
1
+ /**
2
+ * The Issuer adapter over the fiscal service in this package's `sidecar/`
3
+ * folder, speaking exactly its wire contract (`../sidecar/types`). JSON in,
4
+ * JSON out; a non-2xx answer carries `{ error }` and is handed back
5
+ * classified, never thrown.
6
+ *
7
+ * What the service cannot classify because it never answered — the fetch
8
+ * failed, timed out or got something that is not the service's JSON — is
9
+ * `RETRYABLE` with `outcomeUnknown: true`: the call may have reached SEFAZ, so
10
+ * the next attempt is a retry of the SAME call, which the service settles by
11
+ * looking the key up first. The message names the path and the HTTP status,
12
+ * never the request: the request carries the certificate.
13
+ */
14
+
15
+ import type {
16
+ CancelBySubstitutionRequest,
17
+ CancelRequest,
18
+ InutilizeRequest,
19
+ IssueRequest,
20
+ LookupRequest,
21
+ SidecarErrorBody,
22
+ SidecarHealth,
23
+ SignContingencyRequest,
24
+ TransmitRequest,
25
+ } from "../sidecar/types";
26
+ import { SIDECAR_ERROR_CLASSES } from "../sidecar/types";
27
+ import { type Issuer, type IssuerFailure, type IssuerOutcome, modelPath } from "./port";
28
+
29
+ /** The `fetch` the adapter calls: the global one fits. */
30
+ export type SidecarFetch = (url: string, init: { method: string; headers: Record<string, string>; body?: string; signal?: AbortSignal }) => Promise<{
31
+ readonly status: number;
32
+ text(): Promise<string>;
33
+ }>;
34
+
35
+ export interface SidecarIssuerConfig {
36
+ /** Where the service listens, `http://fiscal-sidecar:8080`. No default. */
37
+ readonly baseUrl: string;
38
+ readonly fetch: SidecarFetch;
39
+ /**
40
+ * How long one call may take, in ms. The service gives SEFAZ its connect
41
+ * timeout plus 20 s and may then look the key up, so this is longer than
42
+ * both; a shorter one turns answered calls into unknown outcomes.
43
+ */
44
+ readonly timeoutMs: number;
45
+ }
46
+
47
+ function unanswered(message: string): IssuerFailure {
48
+ return {
49
+ class: "RETRYABLE",
50
+ code: null,
51
+ message,
52
+ details: [],
53
+ accessKey: null,
54
+ signedXml: null,
55
+ sefazReply: null,
56
+ outcomeUnknown: true,
57
+ };
58
+ }
59
+
60
+ function isErrorBody(value: unknown): value is SidecarErrorBody {
61
+ if (value === null || typeof value !== "object" || !("error" in value)) return false;
62
+ const error = (value as { error: unknown }).error;
63
+ return (
64
+ error !== null &&
65
+ typeof error === "object" &&
66
+ SIDECAR_ERROR_CLASSES.includes((error as { class: IssuerFailure["class"] }).class)
67
+ );
68
+ }
69
+
70
+ function parse(text: string): unknown {
71
+ try {
72
+ return JSON.parse(text) as unknown;
73
+ } catch {
74
+ return undefined;
75
+ }
76
+ }
77
+
78
+ /** One POST to the service, its answer classified; never throws. */
79
+ async function post<T>(config: SidecarIssuerConfig, base: string, path: string, body: unknown): Promise<IssuerOutcome<T>> {
80
+ let status: number;
81
+ let text: string;
82
+ try {
83
+ const response = await config.fetch(`${base}${path}`, {
84
+ method: "POST",
85
+ headers: { "content-type": "application/json", accept: "application/json" },
86
+ body: JSON.stringify(body),
87
+ signal: AbortSignal.timeout(config.timeoutMs),
88
+ });
89
+ status = response.status;
90
+ text = await response.text();
91
+ } catch (error) {
92
+ const why = error instanceof Error ? error.name : "unknown";
93
+ return { ok: false, error: unanswered(`POST ${path} got no answer from the fiscal service (${why}).`) };
94
+ }
95
+ const parsed = parse(text);
96
+ if (status >= 200 && status < 300 && parsed !== undefined && !isErrorBody(parsed)) return { ok: true, answer: parsed as T };
97
+ if (isErrorBody(parsed)) return { ok: false, error: parsed.error };
98
+ return { ok: false, error: unanswered(`POST ${path} answered HTTP ${status} without the service's error body.`) };
99
+ }
100
+
101
+ export function createSidecarIssuer(config: SidecarIssuerConfig): Issuer {
102
+ if (typeof config?.baseUrl !== "string" || config.baseUrl === "") throw new TypeError("createSidecarIssuer needs baseUrl.");
103
+ if (typeof config.fetch !== "function") throw new TypeError("createSidecarIssuer needs fetch.");
104
+ if (!Number.isInteger(config.timeoutMs) || config.timeoutMs <= 0) throw new TypeError("createSidecarIssuer needs a positive timeoutMs.");
105
+ let baseEnd = config.baseUrl.length;
106
+ while (baseEnd > 0 && config.baseUrl[baseEnd - 1] === "/") baseEnd -= 1;
107
+ const base = config.baseUrl.slice(0, baseEnd);
108
+
109
+ const call = <T>(path: string, body: unknown) => post<T>(config, base, path, body);
110
+
111
+ return {
112
+ issue: ({ model, environment, signing, document }) =>
113
+ call(`/${modelPath(model)}/issue`, {
114
+ environment,
115
+ certificate: signing.certificate,
116
+ csc: model === "NFCE" ? signing.csc : null,
117
+ document,
118
+ } satisfies IssueRequest),
119
+ signContingency: ({ environment, signing, document, contingency }) =>
120
+ call("/nfce/sign-contingency", {
121
+ environment,
122
+ certificate: signing.certificate,
123
+ csc: signing.csc,
124
+ document,
125
+ contingency,
126
+ } satisfies SignContingencyRequest),
127
+ transmit: ({ model, environment, signing, signedXml }) =>
128
+ call(`/${modelPath(model)}/transmit`, { environment, certificate: signing.certificate, signedXml } satisfies TransmitRequest),
129
+ cancel: ({ model, environment, signing, accessKey, protocol, reason }) =>
130
+ call(`/${modelPath(model)}/cancel`, {
131
+ environment,
132
+ certificate: signing.certificate,
133
+ accessKey,
134
+ protocol,
135
+ reason,
136
+ } satisfies CancelRequest),
137
+ cancelBySubstitution: ({ environment, signing, accessKey, protocol, reason, substituteAccessKey }) =>
138
+ call("/nfce/cancel-substitution", {
139
+ environment,
140
+ certificate: signing.certificate,
141
+ accessKey,
142
+ protocol,
143
+ reason,
144
+ substituteAccessKey,
145
+ } satisfies CancelBySubstitutionRequest),
146
+ lookup: ({ model, environment, signing, accessKey }) =>
147
+ call(`/${modelPath(model)}/lookup`, { environment, certificate: signing.certificate, accessKey } satisfies LookupRequest),
148
+ inutilize: ({ model, environment, signing, uf, cnpj, year, series, from, to, reason }) =>
149
+ call("/inutilize", {
150
+ environment,
151
+ certificate: signing.certificate,
152
+ model: modelPath(model),
153
+ uf,
154
+ cnpj,
155
+ year,
156
+ series,
157
+ from,
158
+ to,
159
+ reason,
160
+ } satisfies InutilizeRequest),
161
+ async health() {
162
+ const response = await config.fetch(`${base}/health`, {
163
+ method: "GET",
164
+ headers: { accept: "application/json" },
165
+ signal: AbortSignal.timeout(config.timeoutMs),
166
+ });
167
+ if (response.status !== 200) throw new Error(`The fiscal service's /health answered HTTP ${response.status}.`);
168
+ return JSON.parse(await response.text()) as SidecarHealth;
169
+ },
170
+ };
171
+ }
package/src/jobs.ts ADDED
@@ -0,0 +1,115 @@
1
+ /**
2
+ * `@12-apps/fiscal/jobs` — the package's job blueprints, deps left open (the
3
+ * wiring contract's `jobs` capability; `@12-apps/wiring` is a type-only
4
+ * dependency).
5
+ *
6
+ * - `sweep` (every 5 minutes): re-issues PENDING and SUBMITTED documents left
7
+ * stale, and settles every number SEFAZ never used (a lookup, a cancel or
8
+ * an inutilization), so a series has no unexplained gap.
9
+ * - `transmit-contingency` (every 5 minutes, offset): transmits the documents
10
+ * signed offline, and warns the owner of every one still offline after 20
11
+ * hours (SEFAZ's deadline is 24).
12
+ * - `certificate-expiry` (daily, 10:07 UTC): tells each owner whose A1 expires
13
+ * within 30 days, on the 30th, 15th, 7th, 3rd and last day, and every day
14
+ * once it has expired.
15
+ *
16
+ * The host binds the service, its store and its notifier, nothing more.
17
+ */
18
+
19
+ import type { JobsContribution } from "@12-apps/wiring";
20
+
21
+ import { FISCAL_CERTIFICATE_EXPIRING, type FiscalNotifyPort } from "./documents/context";
22
+ import type { FiscalStore } from "./documents/ports";
23
+ import type { FiscalDocuments, SweepReport } from "./documents/service";
24
+ import { FISCAL_MANAGE } from "./manifest/permissions";
25
+
26
+ export interface FiscalJobDeps {
27
+ readonly documents: Pick<FiscalDocuments, "sweep" | "transmitContingency">;
28
+ readonly store: Pick<FiscalStore, "listExpiringCertificates">;
29
+ readonly notify: FiscalNotifyPort;
30
+ readonly now: () => Date;
31
+ }
32
+
33
+ /** The single-flight lease a sweep or a transmission run holds. */
34
+ export const FISCAL_JOB_LEASE_MS = 30 * 60_000;
35
+
36
+ /**
37
+ * The worst one document can cost a run: an issue call and the offline
38
+ * signing after it, each bounded by the issuer's timeout (90 s recommended
39
+ * for the sidecar adapter, whose own SEFAZ call gets 50 s and a lookup).
40
+ */
41
+ export const FISCAL_WORST_STEP_MS = 2 * 90_000;
42
+
43
+ /**
44
+ * At most this many documents per run, derived so that a run of the worst
45
+ * steps still ends inside its lease: a second run can never overlap the
46
+ * first. A backlog drains over several five-minute runs.
47
+ */
48
+ export const FISCAL_SWEEP_BATCH = Math.floor(FISCAL_JOB_LEASE_MS / FISCAL_WORST_STEP_MS);
49
+
50
+ /** The days before expiry the owner is told; after expiry, every day. */
51
+ export const CERTIFICATE_WARNING_DAYS: readonly number[] = [30, 15, 7, 3, 1];
52
+
53
+ const DAY_MS = 86_400_000;
54
+
55
+ function report(name: string, result: SweepReport, logger: { info(m: string): void; error(m: string): void }): void {
56
+ if (result.advanced.length > 0 || result.failures.length > 0) {
57
+ logger.info(`fiscal ${name}: ${result.advanced.length} advanced, ${result.failures.length} failed`);
58
+ }
59
+ for (const failure of result.failures) logger.error(`fiscal ${name} failed for document ${failure.documentId}: ${failure.message}`);
60
+ }
61
+
62
+ /** Whole days from `now` to `expiresAt`, rounded up: 0 is "today", negative is "expired". */
63
+ export function daysLeft(expiresAt: string, now: Date): number {
64
+ // `|| 0` turns the -0 of a part-day already gone into "today".
65
+ return Math.ceil((Date.parse(expiresAt) - now.getTime()) / DAY_MS) || 0;
66
+ }
67
+
68
+ export const FISCAL_JOBS = {
69
+ namespace: "fiscal",
70
+ blueprints: {
71
+ sweep: {
72
+ name: "sweep",
73
+ schedule: { pattern: "*/5 * * * *" },
74
+ /** The batch is sized so a run of worst-case steps ends inside this lease. */
75
+ lease: { ttlMs: FISCAL_JOB_LEASE_MS },
76
+ /** A missed run is caught up by the next tick. */
77
+ attempts: 1,
78
+ async handle(_payload, deps, context) {
79
+ report("sweep", await deps.documents.sweep(FISCAL_SWEEP_BATCH), context.logger);
80
+ },
81
+ },
82
+ transmitContingency: {
83
+ name: "transmit-contingency",
84
+ schedule: { pattern: "2-59/5 * * * *" },
85
+ lease: { ttlMs: FISCAL_JOB_LEASE_MS },
86
+ attempts: 1,
87
+ async handle(_payload, deps, context) {
88
+ report("transmit-contingency", await deps.documents.transmitContingency(FISCAL_SWEEP_BATCH), context.logger);
89
+ },
90
+ },
91
+ certificateExpiry: {
92
+ name: "certificate-expiry",
93
+ schedule: { pattern: "7 10 * * *" },
94
+ lease: { ttlMs: 10 * 60_000 },
95
+ attempts: 1,
96
+ async handle(_payload, deps, context) {
97
+ const now = deps.now();
98
+ const horizon = new Date(now.getTime() + (Math.max(...CERTIFICATE_WARNING_DAYS) + 1) * DAY_MS).toISOString();
99
+ const profiles = await deps.store.listExpiringCertificates(horizon);
100
+ let told = 0;
101
+ for (const profile of profiles) {
102
+ const days = daysLeft(profile.certificateExpiresAt ?? "", now);
103
+ if (days > 0 && !CERTIFICATE_WARNING_DAYS.includes(days)) continue;
104
+ await deps.notify.emit({
105
+ type: FISCAL_CERTIFICATE_EXPIRING,
106
+ recipient: { tenantId: profile.ownerId, permission: FISCAL_MANAGE },
107
+ payload: { ownerId: profile.ownerId, expiresAt: profile.certificateExpiresAt, daysLeft: days },
108
+ });
109
+ told += 1;
110
+ }
111
+ if (told > 0) context.logger.info(`fiscal certificate-expiry: ${told} owner(s) told`);
112
+ },
113
+ },
114
+ },
115
+ } satisfies JobsContribution<FiscalJobDeps>;
@@ -1,23 +1,29 @@
1
1
  /**
2
- * `@12-apps/fiscal/manifest` — the SHARED wiring manifest, a SKELETON.
3
- *
4
- * What it declares today is what exists today:
2
+ * `@12-apps/fiscal/manifest` — the SHARED wiring manifest.
5
3
  *
6
4
  * - `permissions` — `fiscal:read`, `fiscal:manage`, `fiscal:issue`,
7
- * `fiscal:cancel`: data, valid with no route or table behind them yet, and
8
- * declared now so a host composes the catalog once.
5
+ * `fiscal:cancel`, declared here and nowhere else; every route in
6
+ * `../http` names the one it needs.
7
+ * - `db` — the Prisma partial (`prisma/fiscal.prisma`: the emitter profile,
8
+ * issuing points, one number counter per series, documents and their
9
+ * events) and its migrations.
10
+ * - `observability` — `fiscal`: the sweeps log under it.
11
+ * - `server: ["http", "jobs"]` — `./manifest/server`.
12
+ *
13
+ * Narrowings, each argued in `.wiring-conformance.json`:
9
14
  *
10
- * The first module, `./engine`, is a pure function a host calls; it has
11
- * nothing to wire. The document module (FUT-2237) adds, in this manifest:
12
- * `db` (the emitter profile, the fiscal document and its events, a number
13
- * counter per issuing point and series), `server: ["http", "jobs"]` (profile,
14
- * certificate upload, issue, cancel, look up; retry, contingency
15
- * transmission, certificate-expiry warning), `notifications` (certificate
16
- * expiring, document rejected) and `web: ["surface"]` (the fiscal settings
17
- * screen and the documents list), with `observability: { namespace: "fiscal" }`
18
- * once there is running code to log — declaring it now would only make every
19
- * host bind a logger for a pure function that throws and never logs. Until then `.wiring-conformance.json`
20
- * answers each of those with its reason.
15
+ * - **No static `notifications`.** The two alerts (certificate expiring,
16
+ * document rejected) are host words, so they ship as the factory
17
+ * `createFiscalNotificationBlueprints(copy)` (`@12-apps/fiscal/notifications`),
18
+ * which the host feeds to its own mount.
19
+ * - **No `web` surface yet.** The fiscal settings screen and the documents
20
+ * list are built with their screen tickets (FUT-2231, FUT-2238) from the
21
+ * owner's approved prototypes, over these routes.
22
+ * - **No NFS-e.** Only the platform's own NFS-e is planned (FUT-2242).
23
+ * - **No register blocks.** An offline register signing on a reserved block of
24
+ * the contingency series, and the voiding of a finished block's known rest,
25
+ * are FUT-4717's; the port is declared (`ContingencyBlockSource`) and not
26
+ * implemented.
21
27
  *
22
28
  * `@12-apps/wiring` is a TYPE-ONLY dependency: the manifest is a plain
23
29
  * `satisfies`-checked value, and the producer's assertions run in this
@@ -34,4 +40,7 @@ export const fiscalManifest = {
34
40
  name: "@12-apps/fiscal",
35
41
  contract: 1,
36
42
  permissions: FISCAL_PERMISSIONS,
43
+ db: { partial: "prisma/fiscal.prisma", migrations: "prisma/migrations" },
44
+ observability: { namespace: "fiscal" },
45
+ server: ["http", "jobs"],
37
46
  } as const satisfies PackageManifest;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * `@12-apps/fiscal/manifest/server` — the server capabilities.
3
+ *
4
+ * `http.create` IS `createApiFiscal` (`../http`): profile, certificate upload,
5
+ * issuing points, issue, cancel, look up and the DANFE, each route declaring
6
+ * the package permission it needs. `jobs` is `FISCAL_JOBS` (`../jobs`): the
7
+ * retry sweep, the contingency transmission and the certificate-expiry
8
+ * warning. A host binds both or declines each in writing.
9
+ */
10
+
11
+ import type { AnyServerManifest } from "@12-apps/wiring";
12
+
13
+ import { createApiFiscal } from "../http";
14
+ import { FISCAL_JOBS } from "../jobs";
15
+
16
+ export const fiscalServerManifest = {
17
+ name: "@12-apps/fiscal",
18
+ http: { create: createApiFiscal },
19
+ jobs: FISCAL_JOBS,
20
+ } as const satisfies AnyServerManifest;
@@ -0,0 +1,120 @@
1
+ /**
2
+ * `@12-apps/fiscal/notifications` — what the package tells people about,
3
+ * as notification blueprints over the HOST's words (the estate's sanctioned
4
+ * shape for a package alert: a factory over copy, never pre-worded here).
5
+ *
6
+ * - `fiscal.certificate-expiring`, emitted by the `certificate-expiry` job to
7
+ * holders of `fiscal:manage`;
8
+ * - `fiscal.document-rejected`, emitted by the document service to holders of
9
+ * `fiscal:issue` when SEFAZ (or the fiscal service) refuses a document;
10
+ * - `fiscal.document-needs-attention`, to holders of `fiscal:issue` when a
11
+ * document stops being retried: a settlement SEFAZ refused (241, 256, 501, a
12
+ * certificate refused) or too many failures in a row;
13
+ * - `fiscal.contingency-deadline`, to holders of `fiscal:issue` when an NFC-e
14
+ * is still offline 20 hours after it was signed (the deadline is 24).
15
+ *
16
+ * Each blueprint is a structural twin of the wiring contract's
17
+ * `WireNotificationBlueprint`; the host feeds them to its notifications mount.
18
+ */
19
+
20
+ import {
21
+ FISCAL_CERTIFICATE_EXPIRING,
22
+ FISCAL_CONTINGENCY_DEADLINE,
23
+ FISCAL_DOCUMENT_NEEDS_ATTENTION,
24
+ FISCAL_DOCUMENT_REJECTED,
25
+ } from "./documents/context";
26
+ import type { FiscalDocumentModel, FiscalDocumentStatus, NumberVoid } from "./documents/types";
27
+
28
+ export { FISCAL_CERTIFICATE_EXPIRING, FISCAL_CONTINGENCY_DEADLINE, FISCAL_DOCUMENT_NEEDS_ATTENTION, FISCAL_DOCUMENT_REJECTED };
29
+
30
+ export interface CertificateExpiringPayload {
31
+ readonly ownerId: string;
32
+ readonly expiresAt: string;
33
+ /** Whole days left; 0 is today, negative is expired. */
34
+ readonly daysLeft: number;
35
+ }
36
+
37
+ export interface DocumentRejectedPayload {
38
+ readonly documentId: string;
39
+ readonly subjectId: string;
40
+ readonly model: FiscalDocumentModel;
41
+ readonly series: number;
42
+ readonly number: number;
43
+ /** SEFAZ's `cStat`, or the fiscal service's named code. */
44
+ readonly code: string | null;
45
+ /** SEFAZ's own reason, as the service read it. */
46
+ readonly reason: string;
47
+ }
48
+
49
+ export interface DocumentNeedsAttentionPayload {
50
+ readonly documentId: string;
51
+ readonly subjectId: string;
52
+ readonly model: FiscalDocumentModel;
53
+ readonly status: FiscalDocumentStatus;
54
+ readonly numberVoid: NumberVoid | null;
55
+ readonly series: number;
56
+ readonly number: number;
57
+ readonly code: string | null;
58
+ readonly reason: string;
59
+ readonly failures: number;
60
+ }
61
+
62
+ export interface ContingencyDeadlinePayload {
63
+ readonly documentId: string;
64
+ readonly subjectId: string;
65
+ readonly series: number;
66
+ readonly number: number;
67
+ /** When it was signed offline, local time with offset. */
68
+ readonly since: string;
69
+ }
70
+
71
+ export interface FiscalNotificationContent {
72
+ title: string;
73
+ body: string;
74
+ link?: string;
75
+ data?: Readonly<Record<string, unknown>>;
76
+ }
77
+
78
+ export interface FiscalNotificationContext {
79
+ readonly locale?: string | null;
80
+ }
81
+
82
+ /** The host's words for each event, per recipient. */
83
+ export interface FiscalNotificationCopy {
84
+ certificateExpiring(payload: CertificateExpiringPayload, context?: FiscalNotificationContext): FiscalNotificationContent;
85
+ documentRejected(payload: DocumentRejectedPayload, context?: FiscalNotificationContext): FiscalNotificationContent;
86
+ documentNeedsAttention(payload: DocumentNeedsAttentionPayload, context?: FiscalNotificationContext): FiscalNotificationContent;
87
+ contingencyDeadline(payload: ContingencyDeadlinePayload, context?: FiscalNotificationContext): FiscalNotificationContent;
88
+ }
89
+
90
+ export interface FiscalNotificationBlueprint<TPayload> {
91
+ type: string;
92
+ category: string;
93
+ generate(payload: TPayload, context?: FiscalNotificationContext): FiscalNotificationContent;
94
+ }
95
+
96
+ /** The suggested preference category; the host's taxonomy decides. */
97
+ export const FISCAL_NOTIFICATION_CATEGORY = "fiscal";
98
+
99
+ const COPY_KEYS = ["certificateExpiring", "documentRejected", "documentNeedsAttention", "contingencyDeadline"] as const;
100
+
101
+ export function createFiscalNotificationBlueprints(copy: FiscalNotificationCopy): readonly [
102
+ FiscalNotificationBlueprint<CertificateExpiringPayload>,
103
+ FiscalNotificationBlueprint<DocumentRejectedPayload>,
104
+ FiscalNotificationBlueprint<DocumentNeedsAttentionPayload>,
105
+ FiscalNotificationBlueprint<ContingencyDeadlinePayload>,
106
+ ] {
107
+ const missing = COPY_KEYS.filter((key) => typeof copy?.[key] !== "function");
108
+ if (missing.length > 0) throw new TypeError(`createFiscalNotificationBlueprints needs ${missing.join(", ")}.`);
109
+ const blueprint = <T>(type: string, render: (payload: T, context?: FiscalNotificationContext) => FiscalNotificationContent) => ({
110
+ type,
111
+ category: FISCAL_NOTIFICATION_CATEGORY,
112
+ generate: (payload: T, context?: FiscalNotificationContext) => render(payload, context),
113
+ });
114
+ return [
115
+ blueprint(FISCAL_CERTIFICATE_EXPIRING, copy.certificateExpiring),
116
+ blueprint(FISCAL_DOCUMENT_REJECTED, copy.documentRejected),
117
+ blueprint(FISCAL_DOCUMENT_NEEDS_ATTENTION, copy.documentNeedsAttention),
118
+ blueprint(FISCAL_CONTINGENCY_DEADLINE, copy.contingencyDeadline),
119
+ ];
120
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `@12-apps/fiscal/sale` — the neutral document shape (`SaleForDocument`): one
3
+ * sale as the fiscal service accepts it and as the issuer port maps a host's
4
+ * sale into it. Types only; its JSON schema ships beside the service, at
5
+ * `@12-apps/fiscal/sidecar/schema/sale-for-document.schema.json`.
6
+ */
7
+
8
+ export type * from "./types";