@12-apps/fiscal 0.0.0-stage → 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 (155) hide show
  1. package/README.md +269 -2
  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-7QVYU63E.js +7 -0
  7. package/dist/chunk-7QVYU63E.js.map +1 -0
  8. package/dist/chunk-ALABGVPO.js +247 -0
  9. package/dist/chunk-ALABGVPO.js.map +1 -0
  10. package/dist/chunk-FOFIN5M7.js +14 -0
  11. package/dist/chunk-FOFIN5M7.js.map +1 -0
  12. package/dist/chunk-HQ2NXSTX.js +85 -0
  13. package/dist/chunk-HQ2NXSTX.js.map +1 -0
  14. package/dist/chunk-PNTKG3DZ.js +47 -0
  15. package/dist/chunk-PNTKG3DZ.js.map +1 -0
  16. package/dist/chunk-RRFKYVLZ.js +192 -0
  17. package/dist/chunk-RRFKYVLZ.js.map +1 -0
  18. package/dist/chunk-V5ZQAAJT.js +210 -0
  19. package/dist/chunk-V5ZQAAJT.js.map +1 -0
  20. package/dist/chunk-X6MRDUYH.js +21 -0
  21. package/dist/chunk-X6MRDUYH.js.map +1 -0
  22. package/dist/chunk-XQGW5HUG.js +30 -0
  23. package/dist/chunk-XQGW5HUG.js.map +1 -0
  24. package/dist/context-ChnWR4Kb.d.ts +455 -0
  25. package/dist/danfe/en-US.d.ts +12 -0
  26. package/dist/danfe/en-US.js +51 -0
  27. package/dist/danfe/en-US.js.map +1 -0
  28. package/dist/danfe/index.d.ts +50 -0
  29. package/dist/danfe/index.js +18 -0
  30. package/dist/danfe/index.js.map +1 -0
  31. package/dist/danfe/pt-BR.d.ts +11 -0
  32. package/dist/danfe/pt-BR.js +51 -0
  33. package/dist/danfe/pt-BR.js.map +1 -0
  34. package/dist/documents/index.d.ts +169 -0
  35. package/dist/documents/index.js +1228 -0
  36. package/dist/documents/index.js.map +1 -0
  37. package/dist/engine/index.d.ts +118 -0
  38. package/dist/engine/index.js +591 -0
  39. package/dist/engine/index.js.map +1 -0
  40. package/dist/http.d.ts +73 -0
  41. package/dist/http.js +16 -0
  42. package/dist/http.js.map +1 -0
  43. package/dist/issuer/index.d.ts +43 -0
  44. package/dist/issuer/index.js +131 -0
  45. package/dist/issuer/index.js.map +1 -0
  46. package/dist/jobs.d.ts +74 -0
  47. package/dist/jobs.js +22 -0
  48. package/dist/jobs.js.map +1 -0
  49. package/dist/labels-BNvflT0h.d.ts +44 -0
  50. package/dist/manifest/index.d.ts +97 -0
  51. package/dist/manifest/index.js +27 -0
  52. package/dist/manifest/index.js.map +1 -0
  53. package/dist/manifest/server.d.ts +57 -0
  54. package/dist/manifest/server.js +25 -0
  55. package/dist/manifest/server.js.map +1 -0
  56. package/dist/notifications.d.ts +93 -0
  57. package/dist/notifications.js +41 -0
  58. package/dist/notifications.js.map +1 -0
  59. package/dist/port-DpRFK56U.d.ts +238 -0
  60. package/dist/sale/index.d.ts +243 -0
  61. package/dist/sale/index.js +1 -0
  62. package/dist/sale/index.js.map +1 -0
  63. package/dist/service-KTjH7AxW.d.ts +139 -0
  64. package/dist/sidecar/index.d.ts +216 -0
  65. package/dist/sidecar/index.js +8 -0
  66. package/dist/sidecar/index.js.map +1 -0
  67. package/dist/types-B1b8LIWX.d.ts +247 -0
  68. package/package.json +126 -4
  69. package/prisma/fiscal.prisma +158 -0
  70. package/prisma/migrations/20261113220000_fiscal_documents/migration.sql +201 -0
  71. package/sidecar/.dockerignore +5 -0
  72. package/sidecar/Dockerfile +68 -0
  73. package/sidecar/README.md +149 -0
  74. package/sidecar/composer.json +30 -0
  75. package/sidecar/composer.lock +2224 -0
  76. package/sidecar/docker/apache.conf +14 -0
  77. package/sidecar/docker/icp-brasil.pem +8031 -0
  78. package/sidecar/docker/mpm.conf +17 -0
  79. package/sidecar/docker/openssl.cnf +16 -0
  80. package/sidecar/docker/php.ini +19 -0
  81. package/sidecar/public/index.php +15 -0
  82. package/sidecar/schema/sale-for-document.schema.json +401 -0
  83. package/sidecar/src/ErrorClass.php +31 -0
  84. package/sidecar/src/Http/Request.php +48 -0
  85. package/sidecar/src/Http/Response.php +32 -0
  86. package/sidecar/src/Http/Router.php +59 -0
  87. package/sidecar/src/Kernel.php +99 -0
  88. package/sidecar/src/Module.php +31 -0
  89. package/sidecar/src/Nfe/Classifier.php +89 -0
  90. package/sidecar/src/Nfe/Credentials.php +52 -0
  91. package/sidecar/src/Nfe/DocumentMapper.php +383 -0
  92. package/sidecar/src/Nfe/DocumentSchema.php +39 -0
  93. package/sidecar/src/Nfe/Input.php +125 -0
  94. package/sidecar/src/Nfe/Model.php +17 -0
  95. package/sidecar/src/Nfe/NfeModule.php +62 -0
  96. package/sidecar/src/Nfe/NfeService.php +504 -0
  97. package/sidecar/src/Nfe/Sefaz.php +49 -0
  98. package/sidecar/src/Nfe/SefazReply.php +81 -0
  99. package/sidecar/src/Nfe/Transport/CurlTransport.php +198 -0
  100. package/sidecar/src/Nfe/Transport/SoapAdapter.php +57 -0
  101. package/sidecar/src/Nfe/Transport/Transport.php +20 -0
  102. package/sidecar/src/Nfe/Transport/TransportFailure.php +42 -0
  103. package/sidecar/src/RequestLog.php +54 -0
  104. package/sidecar/src/ServiceError.php +69 -0
  105. package/src/danfe/en-US.ts +53 -0
  106. package/src/danfe/index.ts +11 -0
  107. package/src/danfe/labels.ts +49 -0
  108. package/src/danfe/pt-BR.ts +52 -0
  109. package/src/danfe/render.ts +265 -0
  110. package/src/danfe/xml.ts +45 -0
  111. package/src/documents/context.ts +260 -0
  112. package/src/documents/errors.ts +41 -0
  113. package/src/documents/helpers.ts +128 -0
  114. package/src/documents/index.ts +39 -0
  115. package/src/documents/lines.ts +63 -0
  116. package/src/documents/machine-steps.ts +260 -0
  117. package/src/documents/machine.ts +128 -0
  118. package/src/documents/memory.ts +138 -0
  119. package/src/documents/nfe-proc.ts +51 -0
  120. package/src/documents/ports.ts +130 -0
  121. package/src/documents/profile-input.ts +168 -0
  122. package/src/documents/profile.ts +98 -0
  123. package/src/documents/service-profile.ts +104 -0
  124. package/src/documents/service.ts +296 -0
  125. package/src/documents/settle.ts +121 -0
  126. package/src/documents/signing.ts +61 -0
  127. package/src/documents/sql-rows.ts +180 -0
  128. package/src/documents/sql-store.ts +242 -0
  129. package/src/documents/sql.ts +18 -0
  130. package/src/documents/steps.ts +173 -0
  131. package/src/documents/tests/integration/pglite.ts +73 -0
  132. package/src/documents/types.ts +193 -0
  133. package/src/engine/compare.ts +68 -0
  134. package/src/engine/compute.ts +40 -0
  135. package/src/engine/errors.ts +28 -0
  136. package/src/engine/index.ts +20 -0
  137. package/src/engine/oracle.ts +81 -0
  138. package/src/engine/plan.ts +268 -0
  139. package/src/engine/rounding.ts +81 -0
  140. package/src/engine/types.ts +270 -0
  141. package/src/engine/validate.ts +222 -0
  142. package/src/http.ts +264 -0
  143. package/src/issuer/index.ts +9 -0
  144. package/src/issuer/port.ts +109 -0
  145. package/src/issuer/sidecar.ts +171 -0
  146. package/src/jobs.ts +115 -0
  147. package/src/manifest/index.ts +46 -0
  148. package/src/manifest/permissions.ts +28 -0
  149. package/src/manifest/server.ts +20 -0
  150. package/src/notifications.ts +120 -0
  151. package/src/sale/index.ts +8 -0
  152. package/src/sale/types.ts +292 -0
  153. package/src/sidecar/index.ts +9 -0
  154. package/src/sidecar/types.ts +243 -0
  155. package/tables/ibs-cbs-2026-11-13.json +156 -0
@@ -0,0 +1,222 @@
1
+ /**
2
+ * Input and table validation. Every check names the field it refused, and
3
+ * every shape is checked before it is read, so a malformed input — a missing
4
+ * object, an `undefined` where `null` is required, a `null` line — is a
5
+ * `FiscalEngineError`, never a TypeError and never a NaN on a document.
6
+ */
7
+
8
+ import { FiscalEngineError } from "./errors";
9
+ import type { FiscalEngineErrorCode } from "./errors";
10
+ import type { IsoDate, RatePeriod, RateTables, TaxClass, TaxClassCode, TaxInput, TaxLineInput, TaxRegime } from "./types";
11
+
12
+ const ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
13
+ const IBGE_MUNICIPALITY = /^\d{7}$/;
14
+ const IBGE_UF = /^\d{2}$/;
15
+ const REGIMES: readonly TaxRegime[] = ["REGIME_REGULAR", "SIMPLES_IBS_CBS_REGULAR", "SIMPLES", "MEI", "NAO_CONTRIBUINTE"];
16
+
17
+ function refuse(code: FiscalEngineErrorCode, message: string): never {
18
+ throw new FiscalEngineError(code, message);
19
+ }
20
+
21
+ function isRecord(value: unknown): value is Record<string, unknown> {
22
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23
+ }
24
+
25
+ /** A real calendar day in `YYYY-MM-DD` — `2026-02-30` is not one. */
26
+ function isIsoDate(value: unknown): value is IsoDate {
27
+ if (typeof value !== "string") return false;
28
+ const match = ISO_DATE.exec(value);
29
+ if (!match) return false;
30
+ const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
31
+ const date = new Date(Date.UTC(year, month - 1, day));
32
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
33
+ }
34
+
35
+ function isCents(value: unknown): value is number {
36
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
37
+ }
38
+
39
+ function isBp(value: unknown): value is number {
40
+ return isCents(value) && value <= 10_000;
41
+ }
42
+
43
+ function isCode(value: unknown): value is string {
44
+ return typeof value === "string" && value !== "";
45
+ }
46
+
47
+ /** Positive, finite, and at most four decimals — what `qCom` can carry. */
48
+ function isQuantity(value: unknown): value is number {
49
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return false;
50
+ const tenThousandths = Math.round(value * 10_000);
51
+ return tenThousandths > 0 && Number.isSafeInteger(tenThousandths) && Math.abs(tenThousandths / 10_000 - value) < 1e-9;
52
+ }
53
+
54
+ function assertInput(ok: boolean, what: string): void {
55
+ if (!ok) refuse("INVALID_INPUT", what);
56
+ }
57
+
58
+ function assertTable(ok: boolean, what: string): void {
59
+ if (!ok) refuse("INVALID_TABLES", what);
60
+ }
61
+
62
+ function assertTaxClass(taxClass: unknown, where: string): asserts taxClass is TaxClass {
63
+ assertInput(isRecord(taxClass), `${where} must be an object`);
64
+ const value = taxClass as Record<string, unknown>;
65
+ assertInput(isCode(value.cClassTrib), `${where}.cClassTrib must be a code`);
66
+ assertInput(isCode(value.cstIbsCbs), `${where}.cstIbsCbs must be a code`);
67
+ assertInput(
68
+ value.regimeEspecifico === null || value.regimeEspecifico === "BARES_RESTAURANTES",
69
+ `${where}.regimeEspecifico must be "BARES_RESTAURANTES" or null`,
70
+ );
71
+ assertInput(isBp(value.reductionBp), `${where}.reductionBp must be integer basis points in 0..10000`);
72
+ }
73
+
74
+ function assertLine(line: unknown, index: number): asserts line is TaxLineInput {
75
+ const where = `lines[${index}]`;
76
+ assertInput(isRecord(line), `${where} must be an object`);
77
+ const value = line as Record<string, unknown>;
78
+ assertInput(isCode(value.id), `${where}.id must be a non-empty string`);
79
+ assertInput(isCents(value.valueCents), `${where}.valueCents must be non-negative integer cents`);
80
+ assertInput(isQuantity(value.quantity), `${where}.quantity must be positive, with at most four decimals`);
81
+ assertInput(typeof value.foodAndDrink === "boolean", `${where}.foodAndDrink must be a boolean`);
82
+ assertTaxClass(value.taxClass, `${where}.taxClass`);
83
+ }
84
+
85
+ function assertServiceCharge(charge: unknown): void {
86
+ if (charge === null) return;
87
+ assertInput(isRecord(charge), "exclusions.serviceCharge must be an object or null");
88
+ const value = charge as Record<string, unknown>;
89
+ assertInput(isCode(value.id), "exclusions.serviceCharge.id must be a non-empty string");
90
+ assertInput(isCents(value.amountCents), "exclusions.serviceCharge.amountCents must be non-negative integer cents");
91
+ assertInput(typeof value.passedToStaff === "boolean", "exclusions.serviceCharge.passedToStaff must be a boolean");
92
+ assertTaxClass(value.taxClass, "exclusions.serviceCharge.taxClass");
93
+ }
94
+
95
+ function assertIntermediation(retained: unknown): void {
96
+ if (retained === null) return;
97
+ assertInput(isRecord(retained), "exclusions.retainedIntermediation must be an object or null");
98
+ const value = retained as Record<string, unknown>;
99
+ assertInput(isCode(value.id), "exclusions.retainedIntermediation.id must be a non-empty string");
100
+ assertInput(isCents(value.amountCents), "exclusions.retainedIntermediation.amountCents must be non-negative integer cents");
101
+ }
102
+
103
+ function assertExclusions(exclusions: unknown): void {
104
+ assertInput(isRecord(exclusions), "exclusions must be an object");
105
+ const value = exclusions as Record<string, unknown>;
106
+ assertInput("serviceCharge" in value, "exclusions.serviceCharge must be given (null when there is none)");
107
+ assertInput("retainedIntermediation" in value, "exclusions.retainedIntermediation must be given (null when there is none)");
108
+ assertServiceCharge(value.serviceCharge);
109
+ assertIntermediation(value.retainedIntermediation);
110
+ }
111
+
112
+ function assertUniqueIds(input: TaxInput): void {
113
+ const ids = input.lines.map((line) => line.id);
114
+ if (input.exclusions.serviceCharge) ids.push(input.exclusions.serviceCharge.id);
115
+ if (input.exclusions.retainedIntermediation) ids.push(input.exclusions.retainedIntermediation.id);
116
+ const seen = new Set<string>();
117
+ for (const id of ids) {
118
+ assertInput(!seen.has(id), `line id "${id}" is used twice`);
119
+ seen.add(id);
120
+ }
121
+ }
122
+
123
+ function assertSeller(seller: unknown): void {
124
+ assertInput(isRecord(seller), "seller must be an object");
125
+ const value = seller as Record<string, unknown>;
126
+ assertInput(REGIMES.includes(value.regime as TaxRegime), `seller.regime must be one of ${REGIMES.join(", ")}`);
127
+ assertInput(isIsoDate(value.regimeEffectiveFrom), "seller.regimeEffectiveFrom must be a YYYY-MM-DD day");
128
+ assertInput(typeof value.restaurantRegime === "boolean", "seller.restaurantRegime must be a boolean");
129
+ }
130
+
131
+ /** Refuse anything the engine cannot compute from. */
132
+ export function assertTaxInput(input: unknown): asserts input is TaxInput {
133
+ assertInput(isRecord(input), "the input must be an object");
134
+ const value = input as Record<string, unknown>;
135
+ assertInput(Array.isArray(value.lines) && value.lines.length > 0, "lines must hold at least one line");
136
+ (value.lines as unknown[]).forEach(assertLine);
137
+ assertSeller(value.seller);
138
+ assertInput(
139
+ typeof value.destinationIbge === "string" && IBGE_MUNICIPALITY.test(value.destinationIbge),
140
+ "destinationIbge must be a 7-digit IBGE municipality code",
141
+ );
142
+ assertExclusions(value.exclusions);
143
+ assertUniqueIds(input as TaxInput);
144
+ assertInput(isIsoDate(value.supplyDate), "supplyDate must be a YYYY-MM-DD day");
145
+ assertRateTables(value.tables);
146
+ }
147
+
148
+ function assertRateMap(map: unknown, keyShape: RegExp, where: string): void {
149
+ assertTable(isRecord(map), `${where} must be an object`);
150
+ for (const [key, bp] of Object.entries(map as Record<string, unknown>)) {
151
+ assertTable(keyShape.test(key), `${where} key "${key}" is not an IBGE code of the right length`);
152
+ assertTable(isBp(bp), `${where}["${key}"] must be integer basis points in 0..10000`);
153
+ }
154
+ }
155
+
156
+ function assertSphere(sphere: unknown, mapKey: "byUf" | "byMunicipality", keyShape: RegExp, where: string): void {
157
+ assertTable(isRecord(sphere), `${where} must be an object`);
158
+ const value = sphere as Record<string, unknown>;
159
+ assertTable(isBp(value.referenceBp), `${where}.referenceBp must be integer basis points in 0..10000`);
160
+ assertRateMap(value[mapKey], keyShape, `${where}.${mapKey}`);
161
+ }
162
+
163
+ function assertPeriodFlags(value: Record<string, unknown>, where: string): void {
164
+ assertTable(value.status === "LAW" || value.status === "ESTIMATE", `${where}.status must be LAW or ESTIMATE`);
165
+ for (const flag of ["informative", "appliesToSimplesNacional", "taxInsidePrice"] as const) {
166
+ assertTable(typeof value[flag] === "boolean", `${where}.${flag} must be a boolean`);
167
+ }
168
+ }
169
+
170
+ function assertPeriod(period: unknown, index: number): asserts period is RatePeriod {
171
+ const where = `periods[${index}]`;
172
+ assertTable(isRecord(period), `${where} must be an object`);
173
+ const value = period as Record<string, unknown>;
174
+ assertTable(isIsoDate(value.from), `${where}.from must be a YYYY-MM-DD day`);
175
+ assertTable(
176
+ value.to === null || (isIsoDate(value.to) && value.to >= (value.from as string)),
177
+ `${where}.to must be null or a day on or after from`,
178
+ );
179
+ assertPeriodFlags(value, where);
180
+ assertTable(isBp(value.cbsBp), `${where}.cbsBp must be integer basis points in 0..10000`);
181
+ assertSphere(value.ibsUf, "byUf", IBGE_UF, `${where}.ibsUf`);
182
+ assertSphere(value.ibsMun, "byMunicipality", IBGE_MUNICIPALITY, `${where}.ibsMun`);
183
+ }
184
+
185
+ function assertClassCode(code: unknown, where: string): asserts code is TaxClassCode {
186
+ assertTable(isRecord(code), `${where} must be an object`);
187
+ const value = code as Record<string, unknown>;
188
+ assertTable(isCode(value.cClassTrib) && isCode(value.cstIbsCbs), `${where} must carry cClassTrib and cstIbsCbs`);
189
+ }
190
+
191
+ function assertTableHeader(value: Record<string, unknown>): void {
192
+ assertTable(isCode(value.version), "version must be a non-empty string");
193
+ assertTable(isBp(value.gorjetaCapBp), "gorjetaCapBp must be integer basis points in 0..10000");
194
+ const special = value.specialRegimes as Record<string, Record<string, unknown> | undefined> | undefined;
195
+ assertTable(isRecord(special) && isRecord(special.BARES_RESTAURANTES), "specialRegimes.BARES_RESTAURANTES must be an object");
196
+ assertTable(isBp(special!.BARES_RESTAURANTES!.reductionBp), "specialRegimes.BARES_RESTAURANTES.reductionBp must be basis points");
197
+ assertTable(isRecord(value.exclusionClasses), "exclusionClasses must be an object");
198
+ const classes = value.exclusionClasses as Record<string, unknown>;
199
+ assertClassCode(classes.GORJETA, "exclusionClasses.GORJETA");
200
+ assertClassCode(classes.INTERMEDIATION, "exclusionClasses.INTERMEDIATION");
201
+ }
202
+
203
+ /** Refuse a table the engine cannot trust: bad rates, bad dates, overlapping periods. */
204
+ export function assertRateTables(tables: unknown): asserts tables is RateTables {
205
+ assertTable(isRecord(tables), "the rate table must be an object");
206
+ const value = tables as Record<string, unknown>;
207
+ assertTableHeader(value);
208
+ assertTable(Array.isArray(value.periods) && value.periods.length > 0, "periods must hold at least one period");
209
+ const periods = value.periods as unknown[];
210
+ periods.forEach(assertPeriod);
211
+ const sorted = [...(periods as RatePeriod[])].sort((a, b) => a.from.localeCompare(b.from));
212
+ for (let i = 1; i < sorted.length; i += 1) {
213
+ const previous = sorted[i - 1]!;
214
+ assertTable(previous.to !== null && previous.to < sorted[i]!.from, `periods starting ${previous.from} and ${sorted[i]!.from} overlap`);
215
+ }
216
+ }
217
+
218
+ /** The period covering `date`, or a refusal. */
219
+ export function periodAt(tables: RateTables, date: IsoDate): RatePeriod {
220
+ const period = tables.periods.find((p) => p.from <= date && (p.to === null || date <= p.to));
221
+ return period ?? refuse("NO_RATE_PERIOD", `table ${tables.version} has no period covering ${date}`);
222
+ }
package/src/http.ts ADDED
@@ -0,0 +1,264 @@
1
+ /**
2
+ * `createApiFiscal` — the fiscal HTTP surface as framework-neutral route
3
+ * descriptors (the wiring contract's `http` capability, restated here
4
+ * structurally: this package imports nothing from the contract at runtime,
5
+ * and its manifest suite pins the twins).
6
+ *
7
+ * The package owns the paths, the bodies it reads (`./documents/profile-input`,
8
+ * unknown keys refused), the `{ data }` envelope, the permission each route
9
+ * needs and the status a refusal earns ({@link FISCAL_ERROR_STATUS}). The host
10
+ * owns resolving WHO is calling into the opaque `ownerId` of its tenant, the
11
+ * guards that check the declared permission, and every word a person reads:
12
+ * an error answers a `code` for the host to word, never a sentence for a user.
13
+ *
14
+ * Nothing secret leaves: the profile answers `hasCertificate` / `hasCsc`, never
15
+ * a ciphertext, and the certificate upload answers the profile view.
16
+ */
17
+
18
+ import { type DanfeNfceLabels } from "./danfe/labels";
19
+ import { type PaperWidth, renderDanfeNfce } from "./danfe/render";
20
+ import { FiscalDocumentError, type FiscalDocumentErrorCode } from "./documents/errors";
21
+ import type { DocumentStorage } from "./documents/ports";
22
+ import { parseCertificateUpload, parseIssuingPointInput, parseProfileInput } from "./documents/profile-input";
23
+ import { viewOf } from "./documents/profile";
24
+ import type { FiscalDocuments } from "./documents/service";
25
+ import { FISCAL_DOCUMENT_MODELS, type FiscalDocumentModel } from "./documents/types";
26
+ import { FISCAL_CANCEL, FISCAL_ISSUE, FISCAL_MANAGE, FISCAL_READ } from "./manifest/permissions";
27
+
28
+ /** The caller, as the host's adapter resolved it. */
29
+ export interface FiscalHttpActor {
30
+ /** The emitter profile's owner: the host's tenant, mapped to an opaque id. */
31
+ readonly ownerId: string;
32
+ }
33
+
34
+ /** Structural twin of the wiring contract's `WireRequest<FiscalHttpActor>`. */
35
+ export interface FiscalHttpRequest {
36
+ actor: FiscalHttpActor;
37
+ params: Record<string, string | undefined>;
38
+ query: Record<string, string | undefined>;
39
+ body?: unknown;
40
+ }
41
+
42
+ /** Structural twin of the wiring contract's `WireResponse`. */
43
+ export interface FiscalHttpResponse {
44
+ status: number;
45
+ body: unknown;
46
+ }
47
+
48
+ /** Structural twin of the wiring contract's `WireRoute<FiscalHttpActor>`. */
49
+ export interface FiscalRoute {
50
+ method: "GET" | "POST" | "PUT";
51
+ path: string;
52
+ permission: string;
53
+ handle(request: FiscalHttpRequest): Promise<FiscalHttpResponse>;
54
+ }
55
+
56
+ export interface FiscalApiConfig {
57
+ readonly documents: FiscalDocuments;
58
+ /** Where the XMLs are, to render a DANFE from. */
59
+ readonly storage: DocumentStorage;
60
+ /** The DANFE's words: the host's, or `@12-apps/fiscal/danfe/pt-BR`. */
61
+ readonly danfeLabels: DanfeNfceLabels;
62
+ }
63
+
64
+ export const FISCAL_ERROR_STATUS = {
65
+ INVALID_INPUT: 400,
66
+ NOT_FOUND: 404,
67
+ NOT_ISSUABLE: 409,
68
+ NOT_SUPPORTED: 501,
69
+ TRANSITION_REFUSED: 409,
70
+ SERIES_EXHAUSTED: 409,
71
+ CONFLICT: 409,
72
+ SUBJECT_HAS_DOCUMENT: 409,
73
+ NOT_PRINTABLE: 409,
74
+ RESEND_CHANGES_PRINTED_FIELDS: 422,
75
+ } as const satisfies Record<FiscalDocumentErrorCode, number>;
76
+
77
+ /**
78
+ * The states with paper: an authorised document, and one signed offline and
79
+ * not yet transmitted (its DANFE is what the buyer takes). A denied,
80
+ * cancelled, rejected or replaced document is not a valid DANFE.
81
+ */
82
+ const PRINTABLE = new Set(["AUTHORIZED", "CONTINGENCY"]);
83
+
84
+ const ok = (data: unknown, status = 200): FiscalHttpResponse => ({ status, body: { data } });
85
+
86
+ async function answering(run: () => Promise<FiscalHttpResponse>): Promise<FiscalHttpResponse> {
87
+ try {
88
+ return await run();
89
+ } catch (error) {
90
+ if (error instanceof FiscalDocumentError) {
91
+ return { status: FISCAL_ERROR_STATUS[error.code], body: { error: error.code, message: error.message } };
92
+ }
93
+ throw error;
94
+ }
95
+ }
96
+
97
+ function record(body: unknown): Record<string, unknown> {
98
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
99
+ throw new FiscalDocumentError("INVALID_INPUT", "the body must be an object.");
100
+ }
101
+ return body as Record<string, unknown>;
102
+ }
103
+
104
+ function stringField(body: Record<string, unknown>, key: string): string {
105
+ const value = body[key];
106
+ if (typeof value !== "string" || value === "") throw new FiscalDocumentError("INVALID_INPUT", `${key} is required.`);
107
+ return value;
108
+ }
109
+
110
+ function param(request: FiscalHttpRequest, key: string): string {
111
+ const value = request.params[key];
112
+ if (value === undefined || value === "") throw new FiscalDocumentError("INVALID_INPUT", `${key} is required.`);
113
+ return value;
114
+ }
115
+
116
+ const ISSUE_KEYS = new Set(["subjectId", "issuingPointId", "model", "offline"]);
117
+
118
+ function issueBody(body: unknown): { subjectId: string; issuingPointId: string; model: FiscalDocumentModel; offline: boolean } {
119
+ const fields = record(body);
120
+ const unknown = Object.keys(fields).filter((key) => !ISSUE_KEYS.has(key));
121
+ if (unknown.length > 0) throw new FiscalDocumentError("INVALID_INPUT", `unknown keys: ${unknown.join(", ")}.`);
122
+ const model = fields["model"];
123
+ if (!FISCAL_DOCUMENT_MODELS.includes(model as FiscalDocumentModel)) throw new FiscalDocumentError("INVALID_INPUT", "model must be NFE or NFCE.");
124
+ const offline = fields["offline"] ?? false;
125
+ if (typeof offline !== "boolean") throw new FiscalDocumentError("INVALID_INPUT", "offline must be a boolean.");
126
+ if (offline && model !== "NFCE") throw new FiscalDocumentError("INVALID_INPUT", "only an NFC-e is issued offline.");
127
+ return { subjectId: stringField(fields, "subjectId"), issuingPointId: stringField(fields, "issuingPointId"), model: model as FiscalDocumentModel, offline };
128
+ }
129
+
130
+ function profileRoutes({ documents }: FiscalApiConfig): FiscalRoute[] {
131
+ return [
132
+ {
133
+ method: "GET",
134
+ path: "/fiscal/profile",
135
+ permission: FISCAL_READ,
136
+ handle: ({ actor }) =>
137
+ answering(async () => {
138
+ const profile = await documents.getProfile(actor.ownerId);
139
+ return ok(profile === null ? null : viewOf(profile));
140
+ }),
141
+ },
142
+ {
143
+ method: "PUT",
144
+ path: "/fiscal/profile",
145
+ permission: FISCAL_MANAGE,
146
+ handle: ({ actor, body }) => answering(async () => ok(viewOf(await documents.saveProfile(actor.ownerId, parseProfileInput(body))))),
147
+ },
148
+ {
149
+ method: "PUT",
150
+ path: "/fiscal/profile/certificate",
151
+ permission: FISCAL_MANAGE,
152
+ handle: ({ actor, body }) =>
153
+ answering(async () => ok(viewOf(await documents.uploadCertificate(actor.ownerId, parseCertificateUpload(body))))),
154
+ },
155
+ {
156
+ method: "GET",
157
+ path: "/fiscal/issuing-points",
158
+ permission: FISCAL_READ,
159
+ handle: ({ actor }) => answering(async () => ok(await documents.listIssuingPoints(actor.ownerId))),
160
+ },
161
+ {
162
+ method: "POST",
163
+ path: "/fiscal/issuing-points",
164
+ permission: FISCAL_MANAGE,
165
+ handle: ({ actor, body }) =>
166
+ answering(async () => ok(await documents.createIssuingPoint(actor.ownerId, parseIssuingPointInput(body)), 201)),
167
+ },
168
+ ];
169
+ }
170
+
171
+ /** The DANFE of a printable document, as ESC/POS-ready lines. */
172
+ function danfeRoute({ documents, storage, danfeLabels }: FiscalApiConfig): FiscalRoute {
173
+ return {
174
+ method: "GET",
175
+ path: "/fiscal/documents/:documentId/danfe",
176
+ permission: FISCAL_READ,
177
+ handle: (request) =>
178
+ answering(async () => {
179
+ const paper = Number(request.query["paper"] ?? "80");
180
+ if (paper !== 58 && paper !== 80) throw new FiscalDocumentError("INVALID_INPUT", "paper must be 58 or 80.");
181
+ const document = await documents.getDocument(request.actor.ownerId, param(request, "documentId"));
182
+ if (!PRINTABLE.has(document.status)) {
183
+ throw new FiscalDocumentError("NOT_PRINTABLE", `document ${document.id} is ${document.status}: only an AUTHORIZED or CONTINGENCY document prints.`);
184
+ }
185
+ const xml = document.model === "NFCE" && document.xmlKey !== null ? await storage.get(document.xmlKey) : null;
186
+ if (xml === null) throw new FiscalDocumentError("NOT_FOUND", `document ${document.id} has no NFC-e XML to print.`);
187
+ return ok(renderDanfeNfce({ xml, paperWidth: paper as PaperWidth, labels: danfeLabels }));
188
+ }),
189
+ };
190
+ }
191
+
192
+ function documentRoutes(config: FiscalApiConfig): FiscalRoute[] {
193
+ const { documents } = config;
194
+ return [
195
+ {
196
+ method: "POST",
197
+ path: "/fiscal/documents",
198
+ permission: FISCAL_ISSUE,
199
+ handle: ({ actor, body }) =>
200
+ answering(async () => {
201
+ const { offline, ...input } = issueBody(body);
202
+ const document = offline
203
+ ? await documents.issueOffline({ ownerId: actor.ownerId, subjectId: input.subjectId, issuingPointId: input.issuingPointId })
204
+ : await documents.issue({ ownerId: actor.ownerId, ...input });
205
+ return ok(document);
206
+ }),
207
+ },
208
+ {
209
+ method: "GET",
210
+ path: "/fiscal/documents/:documentId",
211
+ permission: FISCAL_READ,
212
+ handle: (request) =>
213
+ answering(async () => {
214
+ const documentId = param(request, "documentId");
215
+ const document = await documents.getDocument(request.actor.ownerId, documentId);
216
+ return ok({ document, events: await documents.listEvents(request.actor.ownerId, documentId) });
217
+ }),
218
+ },
219
+ {
220
+ method: "POST",
221
+ path: "/fiscal/documents/:documentId/cancel",
222
+ permission: FISCAL_CANCEL,
223
+ handle: (request) =>
224
+ answering(async () => {
225
+ const reason = stringField(record(request.body), "reason");
226
+ const result = await documents.cancel({ ownerId: request.actor.ownerId, documentId: param(request, "documentId"), reason });
227
+ return result.failure === null
228
+ ? ok(result.document)
229
+ : { status: 422, body: { error: "ISSUER_FAILURE", failure: result.failure, data: result.document } };
230
+ }),
231
+ },
232
+ {
233
+ method: "POST",
234
+ path: "/fiscal/documents/:documentId/resend",
235
+ permission: FISCAL_ISSUE,
236
+ handle: (request) =>
237
+ answering(async () =>
238
+ ok(await documents.resendContingency({ ownerId: request.actor.ownerId, documentId: param(request, "documentId") })),
239
+ ),
240
+ },
241
+ {
242
+ method: "POST",
243
+ path: "/fiscal/documents/:documentId/release",
244
+ permission: FISCAL_ISSUE,
245
+ handle: (request) =>
246
+ answering(async () => ok(await documents.release({ ownerId: request.actor.ownerId, documentId: param(request, "documentId") }))),
247
+ },
248
+ {
249
+ method: "POST",
250
+ path: "/fiscal/documents/:documentId/lookup",
251
+ permission: FISCAL_READ,
252
+ handle: (request) =>
253
+ answering(async () => ok(await documents.lookup({ ownerId: request.actor.ownerId, documentId: param(request, "documentId") }))),
254
+ },
255
+ danfeRoute(config),
256
+ ];
257
+ }
258
+
259
+ export function createApiFiscal(config: FiscalApiConfig): { routes: readonly FiscalRoute[] } {
260
+ if (config?.documents === undefined) throw new TypeError("createApiFiscal needs documents.");
261
+ if (config.storage === undefined) throw new TypeError("createApiFiscal needs storage.");
262
+ if (config.danfeLabels === undefined) throw new TypeError("createApiFiscal needs danfeLabels.");
263
+ return { routes: [...profileRoutes(config), ...documentRoutes(config)] };
264
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * `@12-apps/fiscal/issuer` — the Issuer port and its first adapter, the
3
+ * fiscal service in this package's `sidecar/` folder.
4
+ */
5
+
6
+ export { modelPath } from "./port";
7
+ export type * from "./port";
8
+ export { createSidecarIssuer } from "./sidecar";
9
+ export type { SidecarFetch, SidecarIssuerConfig } from "./sidecar";
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The Issuer port: what the document service asks of whoever talks to SEFAZ.
3
+ * The first (and today only) adapter is the fiscal service in this package's
4
+ * `sidecar/` folder (`./sidecar`). A call never throws for a failure the
5
+ * service classified: it answers `{ ok: false, error }` with the service's
6
+ * class (`REJECTED`, `RETRYABLE`, `CONTINGENCY`, `AUTH`, `INVALID`,
7
+ * `INTERNAL`), and the document service maps that onto the state machine.
8
+ *
9
+ * The certificate and the CSC travel with each call (the service is
10
+ * stateless) inside {@link SigningMaterial}, built by the signing identity
11
+ * for this one call and dropped with it.
12
+ */
13
+
14
+ import type { FiscalDocumentModel } from "../documents/types";
15
+ import type { SaleForDocument } from "../sale/types";
16
+ import type {
17
+ CancelledDocument,
18
+ ContingencyEntry,
19
+ ContingencySignedDocument,
20
+ Csc,
21
+ InutilizedRange,
22
+ IssuedDocument,
23
+ LookedUpDocument,
24
+ SefazEnvironment,
25
+ SidecarErrorBody,
26
+ SidecarHealth,
27
+ SigningCertificate,
28
+ } from "../sidecar/types";
29
+
30
+ /** What signs one call: the A1 and, for an NFC-e, the CSC. Never stored, never logged. */
31
+ export interface SigningMaterial {
32
+ readonly certificate: SigningCertificate;
33
+ readonly csc: Csc | null;
34
+ }
35
+
36
+ /** A failed call, classified. The service's error body, verbatim. */
37
+ export type IssuerFailure = SidecarErrorBody["error"];
38
+
39
+ export type IssuerOutcome<T> = { readonly ok: true; readonly answer: T } | { readonly ok: false; readonly error: IssuerFailure };
40
+
41
+ interface Call {
42
+ readonly environment: SefazEnvironment;
43
+ readonly signing: SigningMaterial;
44
+ }
45
+
46
+ export interface IssueCall extends Call {
47
+ readonly model: FiscalDocumentModel;
48
+ readonly document: SaleForDocument;
49
+ }
50
+
51
+ export interface SignContingencyCall extends Call {
52
+ readonly document: SaleForDocument;
53
+ readonly contingency: ContingencyEntry;
54
+ }
55
+
56
+ export interface TransmitCall extends Call {
57
+ readonly model: FiscalDocumentModel;
58
+ readonly signedXml: string;
59
+ }
60
+
61
+ export interface CancelCall extends Call {
62
+ readonly model: FiscalDocumentModel;
63
+ readonly accessKey: string;
64
+ readonly protocol: string;
65
+ readonly reason: string;
66
+ }
67
+
68
+ /** NFC-e only: cancel an online document whose sale was issued again in contingency (event 110112). */
69
+ export interface CancelBySubstitutionCall extends Call {
70
+ readonly accessKey: string;
71
+ readonly protocol: string;
72
+ readonly reason: string;
73
+ readonly substituteAccessKey: string;
74
+ }
75
+
76
+ export interface LookupCall extends Call {
77
+ readonly model: FiscalDocumentModel;
78
+ readonly accessKey: string;
79
+ }
80
+
81
+ export interface InutilizeCall extends Call {
82
+ readonly model: FiscalDocumentModel;
83
+ readonly uf: string;
84
+ readonly cnpj: string;
85
+ readonly year: number;
86
+ readonly series: number;
87
+ readonly from: number;
88
+ readonly to: number;
89
+ readonly reason: string;
90
+ }
91
+
92
+ export interface Issuer {
93
+ /** Build, sign and transmit. `AUTHORIZED` or `DENIED`. */
94
+ issue(call: IssueCall): Promise<IssuerOutcome<IssuedDocument>>;
95
+ /** NFC-e only: build and sign offline (`tpEmis = 9`); nothing is sent. */
96
+ signContingency(call: SignContingencyCall): Promise<IssuerOutcome<ContingencySignedDocument>>;
97
+ /** Send an already signed XML (a contingency document). */
98
+ transmit(call: TransmitCall): Promise<IssuerOutcome<IssuedDocument>>;
99
+ cancel(call: CancelCall): Promise<IssuerOutcome<CancelledDocument>>;
100
+ cancelBySubstitution(call: CancelBySubstitutionCall): Promise<IssuerOutcome<CancelledDocument>>;
101
+ lookup(call: LookupCall): Promise<IssuerOutcome<LookedUpDocument>>;
102
+ inutilize(call: InutilizeCall): Promise<IssuerOutcome<InutilizedRange>>;
103
+ health(): Promise<SidecarHealth>;
104
+ }
105
+
106
+ /** The path segment of a model on the service's routes. */
107
+ export function modelPath(model: FiscalDocumentModel): "nfe" | "nfce" {
108
+ return model === "NFE" ? "nfe" : "nfce";
109
+ }