@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,247 @@
1
+ /**
2
+ * The engine's vocabulary. Money is integer CENTS, rates are integer BASIS
3
+ * POINTS (1 bp = 0.01%), dates are ISO calendar days (`YYYY-MM-DD`) in the
4
+ * seller's own clock — the fato gerador is the local day of the supply, and the
5
+ * host, which owns the clock, says which day that was.
6
+ *
7
+ * Nothing here has a default. Every field is required, and a value the engine
8
+ * cannot read is refused with a `FiscalEngineError`, never guessed.
9
+ */
10
+ /** An ISO calendar day, `YYYY-MM-DD`. */
11
+ type IsoDate = string;
12
+ /**
13
+ * The seller's IBS/CBS regime (LC 214/2025 art. 41).
14
+ *
15
+ * - `REGIME_REGULAR` — Lucro Presumido/Real: the full breakdown, "por fora".
16
+ * - `SIMPLES_IBS_CBS_REGULAR` — the Simples híbrido (art. 41 §3): a Simples
17
+ * optant that applies the regime regular to IBS/CBS; full breakdown.
18
+ * - `SIMPLES` — inside the DAS (art. 41 §2): an `INFORMATIVE` breakdown, with
19
+ * the figures a regime store would show and no amount charged "por fora".
20
+ * - `MEI` and `NAO_CONTRIBUINTE` — no IBS/CBS on the document: zero.
21
+ */
22
+ type TaxRegime = "REGIME_REGULAR" | "SIMPLES_IBS_CBS_REGULAR" | "SIMPLES" | "MEI" | "NAO_CONTRIBUINTE";
23
+ /** The special regimes the engine applies. */
24
+ type RegimeEspecifico = "BARES_RESTAURANTES";
25
+ /** What the treatment of the seller's regime is on the date of the supply. */
26
+ type TaxTreatment = "FULL" | "INFORMATIVE" | "NONE";
27
+ /** The two codes an NF-e item carries for its IBS/CBS classification. */
28
+ interface TaxClassCode {
29
+ readonly cClassTrib: string;
30
+ readonly cstIbsCbs: string;
31
+ }
32
+ /**
33
+ * A line's tax class, as the host classified the item. `cClassTrib` and
34
+ * `cstIbsCbs` are carried opaque into the snapshot (the classification table
35
+ * is the host's data, Informe Técnico 2025.002).
36
+ *
37
+ * `regimeEspecifico: "BARES_RESTAURANTES"` marks prepared food and
38
+ * non-alcoholic drinks prepared on the premises (art. 273 caput, §1; the
39
+ * official class is 200047). Alcohol, even prepared on the premises, and food
40
+ * or drink bought from third parties and resold as-is are OUT (art. 273 §2)
41
+ * and must carry `null`.
42
+ */
43
+ interface TaxClass extends TaxClassCode {
44
+ readonly regimeEspecifico: RegimeEspecifico | null;
45
+ /** The class's own rate reduction (a listed-food reduction, say), 0–10000. */
46
+ readonly reductionBp: number;
47
+ }
48
+ /** One priced line of the supply. */
49
+ interface TaxLineInput {
50
+ /** The host's id, echoed on the output line; unique within the input. */
51
+ readonly id: string;
52
+ /**
53
+ * What the line costs the buyer, every unit, AFTER its allocated discount
54
+ * (an unconditional discount is outside the base, art. 12 §2 III). It is
55
+ * the price the shopper sees, so in a period whose table says
56
+ * `taxInsidePrice` the IBS/CBS are INSIDE it and the engine takes them out;
57
+ * otherwise it is the base itself and the tax is computed on top of it.
58
+ */
59
+ readonly valueCents: number;
60
+ /** Units (`qCom`): positive, at most four decimals (weighed goods). */
61
+ readonly quantity: number;
62
+ /**
63
+ * Whether the line is food or drink — what the gorjeta's 15% ceiling is
64
+ * measured against (art. 274 par. único I). A delivery fee is not.
65
+ */
66
+ readonly foodAndDrink: boolean;
67
+ readonly taxClass: TaxClass;
68
+ }
69
+ /** Who sells, and under which regime since when. */
70
+ interface SellerProfile {
71
+ readonly regime: TaxRegime;
72
+ /** The first day `regime` applies. A supply before it is refused. */
73
+ readonly regimeEffectiveFrom: IsoDate;
74
+ /** Whether the bares e restaurantes regime (arts. 273–276) applies. */
75
+ readonly restaurantRegime: boolean;
76
+ }
77
+ /** The service charge (taxa de serviço / gorjeta) on the supply. */
78
+ interface ServiceChargeInput {
79
+ /** Echoed as the service-charge line's id; unique within the input. */
80
+ readonly id: string;
81
+ readonly amountCents: number;
82
+ /** Whether the charge is passed in full to the staff. */
83
+ readonly passedToStaff: boolean;
84
+ /** The class the WHOLE charge is taxed at when it is not excluded. */
85
+ readonly taxClass: TaxClass;
86
+ }
87
+ /** What a digital platform retained for delivery and intermediation. */
88
+ interface RetainedIntermediationInput {
89
+ /** Echoed as the excluded line's id; unique within the input. */
90
+ readonly id: string;
91
+ /** Never passed to the restaurant; NOT included in any line's value. */
92
+ readonly amountCents: number;
93
+ }
94
+ /**
95
+ * The amounts the restaurant regime keeps out of the base (art. 274 par.
96
+ * único), each segregated on the document as its own item (RCBS art. 399 §2:
97
+ * without the segregation the base is the full value, §4).
98
+ */
99
+ interface TaxExclusions {
100
+ /**
101
+ * Excluded (its own line, the table's gorjeta class) only when the store is
102
+ * in the restaurant regime, the charge is passed in full to the staff AND it
103
+ * is at most 15% of the food and drink. Otherwise the whole charge is a
104
+ * taxed line under its own class — never a partial exclusion.
105
+ */
106
+ readonly serviceCharge: ServiceChargeInput | null;
107
+ /** Restaurant regime only (art. 274 par. único II); refused elsewhere. */
108
+ readonly retainedIntermediation: RetainedIntermediationInput | null;
109
+ }
110
+ /** The IBS share of one sphere in one period: the reference and the overrides. */
111
+ interface IbsSphereRates {
112
+ /** The reference rate, which applies wherever no own rate is listed. */
113
+ readonly referenceBp: number;
114
+ }
115
+ interface IbsUfRates extends IbsSphereRates {
116
+ /** State rates keyed by the 2-digit IBGE state code. */
117
+ readonly byUf: Readonly<Record<string, number>>;
118
+ }
119
+ interface IbsMunRates extends IbsSphereRates {
120
+ /** Municipal rates keyed by the 7-digit IBGE municipality code. */
121
+ readonly byMunicipality: Readonly<Record<string, number>>;
122
+ }
123
+ /** One stretch of time with one set of rates. */
124
+ interface RatePeriod {
125
+ readonly from: IsoDate;
126
+ /** Inclusive; `null` is open-ended. */
127
+ readonly to: IsoDate | null;
128
+ /** `ESTIMATE` stamps every result computed on it `provisional`. */
129
+ readonly status: "LAW" | "ESTIMATE";
130
+ readonly source: string;
131
+ /** The test year: highlighted, payment waived (art. 348 §1). */
132
+ readonly informative: boolean;
133
+ /** `false` in 2026: the test rates are not applied to Simples optants (art. 348 III "c"). */
134
+ readonly appliesToSimplesNacional: boolean;
135
+ /**
136
+ * Whether the IBS/CBS sit INSIDE the item's value on the document (they
137
+ * compose `vProd` and the price without tax travels in `vProdLiq`) — from
138
+ * 2027 by the NF-e layout. When true, a line's `valueCents` is the
139
+ * tax-inclusive price.
140
+ */
141
+ readonly taxInsidePrice: boolean;
142
+ readonly cbsBp: number;
143
+ readonly ibsUf: IbsUfRates;
144
+ readonly ibsMun: IbsMunRates;
145
+ }
146
+ /** A versioned rate table: DATA, loaded by the host, stamped on every result. */
147
+ interface RateTables {
148
+ readonly version: string;
149
+ readonly notes?: readonly string[];
150
+ /** The gorjeta's ceiling as a share of food and drink: 1500 (art. 274 par. único I). */
151
+ readonly gorjetaCapBp: number;
152
+ readonly gorjetaCapSource?: string;
153
+ /** The classes the excluded items are segregated under (410019, 410020). */
154
+ readonly exclusionClasses: {
155
+ readonly GORJETA: TaxClassCode;
156
+ readonly INTERMEDIATION: TaxClassCode;
157
+ readonly source?: string;
158
+ };
159
+ readonly specialRegimes: Readonly<Record<RegimeEspecifico, {
160
+ readonly reductionBp: number;
161
+ readonly source: string;
162
+ }>>;
163
+ readonly periods: readonly RatePeriod[];
164
+ }
165
+ /** Everything one computation needs. */
166
+ interface TaxInput {
167
+ readonly lines: readonly TaxLineInput[];
168
+ readonly seller: SellerProfile;
169
+ /**
170
+ * The 7-digit IBGE code of the place the IBS goes to: the establishment,
171
+ * or for a delivered good the place of delivery (art. 11 I).
172
+ */
173
+ readonly destinationIbge: string;
174
+ readonly exclusions: TaxExclusions;
175
+ readonly tables: RateTables;
176
+ /** The day of the supply; the rate is the rate of that day. */
177
+ readonly supplyDate: IsoDate;
178
+ }
179
+ /** Where an output line came from. */
180
+ type LineSource = "LINE" | "SERVICE_CHARGE" | "GORJETA_EXCLUDED" | "INTERMEDIATION_EXCLUDED";
181
+ /** The per-tax figures of one line. Rates are nominal; `reductionBp` applies to all three. */
182
+ interface LineFigures {
183
+ readonly reductionBp: number;
184
+ readonly cbsRateBp: number;
185
+ readonly cbsCents: number;
186
+ readonly ibsUfRateBp: number;
187
+ readonly ibsUfCents: number;
188
+ readonly ibsMunRateBp: number;
189
+ readonly ibsMunCents: number;
190
+ }
191
+ /** One output line — one NF-e item. */
192
+ interface LineTax extends LineFigures {
193
+ readonly lineId: string;
194
+ readonly source: LineSource;
195
+ readonly quantity: number;
196
+ /** The value as given (`vProd`). */
197
+ readonly valueCents: number;
198
+ /** The base the taxes are computed on (`vBC`): 0 on an excluded line. */
199
+ readonly taxBaseCents: number;
200
+ /** CBS + IBS-UF + IBS-Mun of the line. */
201
+ readonly taxCents: number;
202
+ /**
203
+ * The value without tax (`vProdLiq` = value − tax) in a `taxInsidePrice`
204
+ * period; `null` when the tax is not inside the value.
205
+ */
206
+ readonly netValueCents: number | null;
207
+ /**
208
+ * The unit value without tax (`vUnComLiq`), in reais with ten decimals as
209
+ * the layout writes it, within ±0,01 of `vProdLiq / qCom` (rule I11c-20);
210
+ * `null` when `netValueCents` is.
211
+ */
212
+ readonly netUnitValue: string | null;
213
+ /** The class snapshot (the table's exclusion class on an excluded line). */
214
+ readonly taxClass: TaxClass;
215
+ }
216
+ /** The breakdown of one supply. Every order figure is the sum of its rounded lines. */
217
+ interface TaxBreakdown {
218
+ readonly lines: readonly LineTax[];
219
+ readonly valueCents: number;
220
+ readonly taxBaseCents: number;
221
+ readonly cbsCents: number;
222
+ readonly ibsUfCents: number;
223
+ readonly ibsMunCents: number;
224
+ readonly ibsCents: number;
225
+ readonly totalTaxCents: number;
226
+ /** Σ `netValueCents` (`vProdLiqTot`), or `null` when the tax is not inside the values. */
227
+ readonly netValueCents: number | null;
228
+ readonly gorjetaExcludedCents: number;
229
+ readonly intermediationExcludedCents: number;
230
+ readonly regime: TaxRegime;
231
+ readonly treatment: TaxTreatment;
232
+ /**
233
+ * True when the figures are shown but not charged "por fora": the test year
234
+ * (2026), or a Simples store inside the DAS. False for a `NONE` treatment,
235
+ * which shows nothing.
236
+ */
237
+ readonly informative: boolean;
238
+ /** True when the period's figures are estimates, not law. */
239
+ readonly provisional: boolean;
240
+ /** Whether the line values were taken as tax-inclusive. */
241
+ readonly taxInsidePrice: boolean;
242
+ readonly supplyDate: IsoDate;
243
+ readonly destinationIbge: string;
244
+ readonly tablesVersion: string;
245
+ }
246
+
247
+ export type { IbsMunRates as I, LineFigures as L, RatePeriod as R, SellerProfile as S, TaxRegime as T, TaxBreakdown as a, TaxInput as b, RateTables as c, IbsSphereRates as d, IbsUfRates as e, IsoDate as f, LineSource as g, LineTax as h, RegimeEspecifico as i, RetainedIntermediationInput as j, ServiceChargeInput as k, TaxClass as l, TaxClassCode as m, TaxExclusions as n, TaxLineInput as o, TaxTreatment as p };
package/package.json CHANGED
@@ -1,6 +1,128 @@
1
1
  {
2
2
  "name": "@12-apps/fiscal",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "type": "module",
5
+ "sideEffects": false,
6
+ "description": "Brazilian consumption-tax machinery and fiscal documents for any host that sells. The IBS/CBS engine (./engine): a pure function from priced lines, the seller's regime, the destination, the exclusions, a versioned rate table and the date of the supply to a per-line and per-order breakdown. The neutral sale document (./sale) and a stateless HTTP service over sped-nfe that issues NF-e and NFC-e, shipped with its Dockerfile in sidecar/ (./sidecar types its wire contract). The fiscal document module (./documents): the state machine, the per-series number counters, the issuer port and its sidecar adapter (./issuer), the signing identity, and the DANFE NFC-e as ESC/POS-ready lines (./danfe). Implements @12-apps/wiring (./manifest): db, http, jobs, permissions.",
7
+ "exports": {
8
+ "./danfe": {
9
+ "types": "./dist/danfe/index.d.ts",
10
+ "default": "./dist/danfe/index.js"
11
+ },
12
+ "./danfe/en-US": {
13
+ "types": "./dist/danfe/en-US.d.ts",
14
+ "default": "./dist/danfe/en-US.js"
15
+ },
16
+ "./danfe/pt-BR": {
17
+ "types": "./dist/danfe/pt-BR.d.ts",
18
+ "default": "./dist/danfe/pt-BR.js"
19
+ },
20
+ "./documents": {
21
+ "types": "./dist/documents/index.d.ts",
22
+ "default": "./dist/documents/index.js"
23
+ },
24
+ "./engine": {
25
+ "types": "./dist/engine/index.d.ts",
26
+ "default": "./dist/engine/index.js"
27
+ },
28
+ "./http": {
29
+ "types": "./dist/http.d.ts",
30
+ "default": "./dist/http.js"
31
+ },
32
+ "./issuer": {
33
+ "types": "./dist/issuer/index.d.ts",
34
+ "default": "./dist/issuer/index.js"
35
+ },
36
+ "./jobs": {
37
+ "types": "./dist/jobs.d.ts",
38
+ "default": "./dist/jobs.js"
39
+ },
40
+ "./manifest": {
41
+ "types": "./dist/manifest/index.d.ts",
42
+ "default": "./dist/manifest/index.js"
43
+ },
44
+ "./manifest/server": {
45
+ "types": "./dist/manifest/server.d.ts",
46
+ "default": "./dist/manifest/server.js"
47
+ },
48
+ "./notifications": {
49
+ "types": "./dist/notifications.d.ts",
50
+ "default": "./dist/notifications.js"
51
+ },
52
+ "./sale": {
53
+ "types": "./dist/sale/index.d.ts",
54
+ "default": "./dist/sale/index.js"
55
+ },
56
+ "./sidecar": {
57
+ "types": "./dist/sidecar/index.d.ts",
58
+ "default": "./dist/sidecar/index.js"
59
+ },
60
+ "./sidecar/schema/*": "./sidecar/schema/*",
61
+ "./tables/*": "./tables/*",
62
+ "./package.json": "./package.json"
63
+ },
64
+ "scripts": {
65
+ "build": "rm -rf dist && tsup",
66
+ "clean": "rm -rf node_modules coverage dist",
67
+ "test": "node ../../scripts/vitest-with-teardown.mjs run",
68
+ "test:watch": "vitest watch",
69
+ "lint": "eslint src --max-warnings 0",
70
+ "check-types": "tsc --noEmit",
71
+ "typecheck": "tsc --noEmit"
72
+ },
73
+ "peerDependencies": {
74
+ "@12-apps/wiring": ">=1.3.0"
75
+ },
76
+ "peerDependenciesMeta": {
77
+ "@12-apps/wiring": {
78
+ "optional": true
79
+ }
80
+ },
81
+ "devDependencies": {
82
+ "@12-apps/eslint-config": "^1.22.0",
83
+ "@12-apps/typescript-config": "^1.21.0",
84
+ "@12-apps/wiring": "^1.17.0",
85
+ "@electric-sql/pglite": "0.2.17",
86
+ "@types/node": "^22.10.6",
87
+ "eslint": "^9.39.1",
88
+ "eslint-plugin-test-flakiness": "^1.4.0",
89
+ "tsup": "^8.0.0",
90
+ "typescript": "^5.9.2",
91
+ "vitest": "^3.2.4"
92
+ },
93
+ "engines": {
94
+ "node": ">=22.0.0"
95
+ },
96
+ "license": "MIT",
97
+ "publishConfig": {
98
+ "registry": "https://registry.npmjs.org",
99
+ "access": "public"
100
+ },
101
+ "repository": {
102
+ "type": "git",
103
+ "url": "git+https://github.com/12-apps/shared-packages.git",
104
+ "directory": "packages/fiscal"
105
+ },
106
+ "files": [
107
+ "src",
108
+ "dist",
109
+ "tables",
110
+ "sidecar",
111
+ "prisma",
112
+ "*.md",
113
+ "!eslint.config.js",
114
+ "!tsup.config.ts",
115
+ "!**/__tests__/**",
116
+ "!**/*.test.*",
117
+ "!sidecar/vendor",
118
+ "!sidecar/tests",
119
+ "!sidecar/phpunit.xml",
120
+ "!sidecar/.phpunit.cache"
121
+ ],
122
+ "wiring": {
123
+ "db": {
124
+ "partial": "prisma/fiscal.prisma",
125
+ "migrations": "prisma/migrations"
126
+ }
127
+ }
128
+ }
@@ -0,0 +1,158 @@
1
+ // @12-apps/fiscal — canonical host-agnostic Prisma partial (FUT-2237).
2
+ //
3
+ // The emitter profile, its issuing points, one number counter per issuing
4
+ // point and series, the fiscal documents and their events. Every host id (the
5
+ // profile's owner, a document's subject) is stored BY VALUE: what an owner or
6
+ // a subject is stays the host's to map, and the links to its orders live in
7
+ // the host. The package migration adds the CHECKs Prisma cannot express.
8
+ //
9
+ // Secrets are never stored in clear: the certificate, its password and the
10
+ // CSC token are ciphertext from the host's cipher.
11
+
12
+ model FiscalEmitterProfile {
13
+ ownerId String @id @map("owner_id")
14
+ cnpj String
15
+ stateRegistration String @map("state_registration")
16
+ municipalRegistration String? @map("municipal_registration")
17
+ cnae String?
18
+ legalName String @map("legal_name")
19
+ tradeName String? @map("trade_name")
20
+ // CRT on the document: SIMPLES | SIMPLES_EXCESS | NORMAL | MEI.
21
+ taxRegime String @map("tax_regime")
22
+ // The IBS/CBS engine's regime, and the day it took effect.
23
+ regime String
24
+ regimeEffectiveFrom DateTime @map("regime_effective_from") @db.Date
25
+ restaurantRegime Boolean @map("restaurant_regime")
26
+ // { street, number, complement, district, municipalityIbge, municipalityName, uf, postalCode, phone }
27
+ address Json
28
+ // homologacao | producao
29
+ environment String
30
+ // ISSUED_HERE | ISSUED_ELSEWHERE | NONE — the host sets the default.
31
+ documentPolicy String @map("document_policy")
32
+ // STORE_CERTIFICATE | PLATFORM (declared, NOT_SUPPORTED until FUT-2229 q4).
33
+ signingIdentity String @map("signing_identity")
34
+ certificateCiphertext String? @map("certificate_ciphertext")
35
+ certificatePasswordCiphertext String? @map("certificate_password_ciphertext")
36
+ certificateExpiresAt DateTime? @map("certificate_expires_at")
37
+ cscId String? @map("csc_id")
38
+ cscCiphertext String? @map("csc_ciphertext")
39
+ consentRecordedAt DateTime? @map("consent_recorded_at")
40
+ updatedAt DateTime @updatedAt @map("updated_at")
41
+
42
+ @@index([certificateExpiresAt])
43
+ @@map("fiscal_emitter_profiles")
44
+ }
45
+
46
+ // Where documents are issued from: an opaque id the host maps (a register, the
47
+ // online store). A register has an online and a contingency series.
48
+ model FiscalIssuingPoint {
49
+ id String @id
50
+ ownerId String @map("owner_id")
51
+ // NFE | NFCE
52
+ model String
53
+ onlineSeries Int @map("online_series")
54
+ contingencySeries Int? @map("contingency_series")
55
+ createdAt DateTime @default(now()) @map("created_at")
56
+
57
+ counters FiscalNumberCounter[]
58
+
59
+ @@index([ownerId])
60
+ @@map("fiscal_issuing_points")
61
+ }
62
+
63
+ // The ONE counter of a series. SEFAZ numbers by CNPJ, model and series, and
64
+ // one CNPJ can serve several owners, so the primary key is the CNPJ's: a
65
+ // series belongs to one issuing point. `nextNumber` is drawn with
66
+ // FISCAL_NEXT_NUMBER_SQL in the same transaction as the document's insert.
67
+ model FiscalNumberCounter {
68
+ issuerCnpj String @map("issuer_cnpj")
69
+ environment String
70
+ model String
71
+ series Int
72
+ issuingPointId String @map("issuing_point_id")
73
+ // ONLINE | CONTINGENCY
74
+ seriesKind String @map("series_kind")
75
+ nextNumber Int @map("next_number")
76
+ updatedAt DateTime @default(now()) @map("updated_at")
77
+ issuingPoint FiscalIssuingPoint @relation(fields: [issuingPointId], references: [id], onDelete: Restrict)
78
+
79
+ @@id([issuerCnpj, environment, model, series])
80
+ @@index([issuingPointId])
81
+ @@map("fiscal_number_counters")
82
+ }
83
+
84
+ model FiscalDocument {
85
+ id String @id
86
+ ownerId String @map("owner_id")
87
+ issuerCnpj String @map("issuer_cnpj")
88
+ // What the document is for, opaque: the host links it to its orders.
89
+ subjectId String @map("subject_id")
90
+ issuingPointId String @map("issuing_point_id")
91
+ model String
92
+ environment String
93
+ seriesKind String @map("series_kind")
94
+ series Int
95
+ number Int
96
+ keyCode String @map("key_code")
97
+ // PENDING | SUBMITTED | AUTHORIZED | REJECTED | DENIED | CONTINGENCY | CANCELLED | REPLACED
98
+ status String
99
+ // The SaleForDocument as sent. Never a secret.
100
+ sale Json
101
+ // { totalCents, discountCents, cbsCents, ibsUfCents, ibsMunCents }
102
+ totals Json
103
+ buyerTaxId String? @map("buyer_tax_id")
104
+ accessKey String? @unique @map("access_key")
105
+ protocol String?
106
+ statusCode String? @map("status_code")
107
+ statusReason String? @map("status_reason")
108
+ lastErrorClass String? @map("last_error_class")
109
+ outcomeUnknown Boolean @default(false) @map("outcome_unknown")
110
+ issuedAt String @map("issued_at")
111
+ authorizedAt String? @map("authorized_at")
112
+ // { since, reason } of a document signed offline.
113
+ contingency Json?
114
+ cancelledAt String? @map("cancelled_at")
115
+ cancelReason String? @map("cancel_reason")
116
+ cancelProtocol String? @map("cancel_protocol")
117
+ replacedById String? @map("replaced_by_id")
118
+ // LOOKUP_FIRST | INUTILIZE | CANCEL | INUTILIZED | CANCELLED | DENIED
119
+ numberVoid String? @map("number_void")
120
+ xmlKey String? @map("xml_key")
121
+ eventXmlKey String? @map("event_xml_key")
122
+ attempts Int @default(0)
123
+ // Failed steps in a row; the backoff and the person's flag follow from it.
124
+ failures Int @default(0)
125
+ nextAttemptAt DateTime? @map("next_attempt_at")
126
+ attention Boolean @default(false)
127
+ deadlineWarnedAt DateTime? @map("deadline_warned_at")
128
+ createdAt DateTime @map("created_at")
129
+ updatedAt DateTime @map("updated_at")
130
+
131
+ events FiscalDocumentEvent[]
132
+
133
+ // The per-subject guard (one live document) and the sweep's queue index are
134
+ // partial indexes, in the migration: Prisma cannot express them.
135
+ @@unique([issuerCnpj, environment, model, series, number], map: "fiscal_documents_number_key")
136
+ @@index([ownerId, subjectId, model])
137
+ @@map("fiscal_documents")
138
+ }
139
+
140
+ // One transition, with the fiscal service's raw answer (secret-named keys
141
+ // scrubbed). Append-only.
142
+ model FiscalDocumentEvent {
143
+ id String @id
144
+ // Insertion order: two events of one millisecond keep theirs.
145
+ seq BigInt @unique @default(autoincrement())
146
+ documentId String @map("document_id")
147
+ kind String
148
+ fromStatus String @map("from_status")
149
+ toStatus String @map("to_status")
150
+ at DateTime
151
+ errorClass String? @map("error_class")
152
+ code String?
153
+ answer Json?
154
+ document FiscalDocument @relation(fields: [documentId], references: [id], onDelete: Restrict)
155
+
156
+ @@index([documentId, at])
157
+ @@map("fiscal_document_events")
158
+ }