@12-apps/fiscal 1.2.0 → 1.4.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 (40) hide show
  1. package/README.md +17 -0
  2. package/dist/{chunk-N5DCKYFR.js → chunk-2ISYBTCE.js} +3 -3
  3. package/dist/{chunk-G3V7IYNF.js → chunk-EDEGIADD.js} +3 -3
  4. package/dist/{chunk-NVRYAAQ4.js → chunk-F2PGQVWL.js} +7 -6
  5. package/dist/chunk-F2PGQVWL.js.map +1 -0
  6. package/dist/{chunk-XQGW5HUG.js → chunk-GF3DXCD2.js} +1 -1
  7. package/dist/chunk-GF3DXCD2.js.map +1 -0
  8. package/dist/{chunk-2LBQRYPV.js → chunk-H33BK623.js} +1 -1
  9. package/dist/{chunk-2LBQRYPV.js.map → chunk-H33BK623.js.map} +1 -1
  10. package/dist/{chunk-WTGASIZE.js → chunk-MGTROA7K.js} +2 -2
  11. package/dist/{chunk-5S2PJHAE.js → chunk-OSYB7CVT.js} +2 -2
  12. package/dist/{context-ChnWR4Kb.d.ts → context-CLSMOSuf.d.ts} +1 -1
  13. package/dist/danfe/index.js +2 -2
  14. package/dist/documents/index.d.ts +12 -6
  15. package/dist/documents/index.js +118 -9
  16. package/dist/documents/index.js.map +1 -1
  17. package/dist/http.d.ts +4 -3
  18. package/dist/http.js +5 -5
  19. package/dist/issuer/index.d.ts +2 -2
  20. package/dist/jobs.d.ts +3 -3
  21. package/dist/jobs.js +4 -4
  22. package/dist/manifest/server.d.ts +3 -3
  23. package/dist/manifest/server.js +7 -7
  24. package/dist/notifications.d.ts +2 -2
  25. package/dist/notifications.js +3 -3
  26. package/dist/{service-KTjH7AxW.d.ts → service-hR3tgLpO.d.ts} +18 -3
  27. package/dist/{port-DpRFK56U.d.ts → types-BIJqm5GM.d.ts} +105 -85
  28. package/package.json +1 -1
  29. package/src/documents/errors.ts +7 -1
  30. package/src/documents/index.ts +2 -2
  31. package/src/documents/service.ts +88 -4
  32. package/src/documents/steps.ts +100 -4
  33. package/src/documents/types.ts +23 -0
  34. package/src/http.ts +1 -0
  35. package/dist/chunk-NVRYAAQ4.js.map +0 -1
  36. package/dist/chunk-XQGW5HUG.js.map +0 -1
  37. /package/dist/{chunk-N5DCKYFR.js.map → chunk-2ISYBTCE.js.map} +0 -0
  38. /package/dist/{chunk-G3V7IYNF.js.map → chunk-EDEGIADD.js.map} +0 -0
  39. /package/dist/{chunk-WTGASIZE.js.map → chunk-MGTROA7K.js.map} +0 -0
  40. /package/dist/{chunk-5S2PJHAE.js.map → chunk-OSYB7CVT.js.map} +0 -0
package/dist/http.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  FISCAL_ERROR_STATUS,
3
3
  createApiFiscal
4
- } from "./chunk-NVRYAAQ4.js";
5
- import "./chunk-WTGASIZE.js";
6
- import "./chunk-G3V7IYNF.js";
4
+ } from "./chunk-F2PGQVWL.js";
5
+ import "./chunk-MGTROA7K.js";
6
+ import "./chunk-EDEGIADD.js";
7
7
  import "./chunk-PNTKG3DZ.js";
8
- import "./chunk-XQGW5HUG.js";
8
+ import "./chunk-GF3DXCD2.js";
9
9
  import "./chunk-3SDXLSG4.js";
10
- import "./chunk-2LBQRYPV.js";
10
+ import "./chunk-H33BK623.js";
11
11
  import "./chunk-7QVYU63E.js";
12
12
  export {
13
13
  FISCAL_ERROR_STATUS,
@@ -1,5 +1,5 @@
1
- import { I as Issuer } from '../port-DpRFK56U.js';
2
- export { C as CancelBySubstitutionCall, a as CancelCall, b as InutilizeCall, c as IssueCall, d as IssuerFailure, e as IssuerOutcome, L as LookupCall, S as SignContingencyCall, f as SigningMaterial, T as TransmitCall, m as modelPath } from '../port-DpRFK56U.js';
1
+ import { I as Issuer } from '../types-BIJqm5GM.js';
2
+ export { C as CancelBySubstitutionCall, a as CancelCall, b as InutilizeCall, c as IssueCall, d as IssuerFailure, e as IssuerOutcome, L as LookupCall, S as SignContingencyCall, f as SigningMaterial, T as TransmitCall, m as modelPath } from '../types-BIJqm5GM.js';
3
3
  import '../sale/index.js';
4
4
  import '../sidecar/index.js';
5
5
 
package/dist/jobs.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as _12_apps_wiring from '@12-apps/wiring';
2
- import { F as FiscalStore, a as FiscalNotifyPort } from './context-ChnWR4Kb.js';
3
- import { F as FiscalDocuments } from './service-KTjH7AxW.js';
4
- import './port-DpRFK56U.js';
2
+ import { F as FiscalStore, a as FiscalNotifyPort } from './context-CLSMOSuf.js';
3
+ import { F as FiscalDocuments } from './service-hR3tgLpO.js';
4
+ import './types-BIJqm5GM.js';
5
5
  import './sale/index.js';
6
6
  import './sidecar/index.js';
7
7
  import './types-B1b8LIWX.js';
package/dist/jobs.js CHANGED
@@ -5,11 +5,11 @@ import {
5
5
  FISCAL_SWEEP_BATCH,
6
6
  FISCAL_WORST_STEP_MS,
7
7
  daysLeft
8
- } from "./chunk-5S2PJHAE.js";
9
- import "./chunk-N5DCKYFR.js";
10
- import "./chunk-XQGW5HUG.js";
8
+ } from "./chunk-OSYB7CVT.js";
9
+ import "./chunk-2ISYBTCE.js";
10
+ import "./chunk-GF3DXCD2.js";
11
11
  import "./chunk-3SDXLSG4.js";
12
- import "./chunk-2LBQRYPV.js";
12
+ import "./chunk-H33BK623.js";
13
13
  import "./chunk-7QVYU63E.js";
14
14
  export {
15
15
  CERTIFICATE_WARNING_DAYS,
@@ -1,12 +1,12 @@
1
1
  import * as _12_apps_wiring from '@12-apps/wiring';
2
2
  import { FiscalJobDeps } from '../jobs.js';
3
3
  import { createApiFiscal } from '../http.js';
4
- import '../context-ChnWR4Kb.js';
5
- import '../port-DpRFK56U.js';
4
+ import '../context-CLSMOSuf.js';
5
+ import '../types-BIJqm5GM.js';
6
6
  import '../sale/index.js';
7
7
  import '../sidecar/index.js';
8
8
  import '../types-B1b8LIWX.js';
9
- import '../service-KTjH7AxW.js';
9
+ import '../service-hR3tgLpO.js';
10
10
  import '../labels-BNvflT0h.js';
11
11
 
12
12
  declare const fiscalServerManifest: {
@@ -1,16 +1,16 @@
1
1
  import {
2
2
  createApiFiscal
3
- } from "../chunk-NVRYAAQ4.js";
4
- import "../chunk-WTGASIZE.js";
5
- import "../chunk-G3V7IYNF.js";
3
+ } from "../chunk-F2PGQVWL.js";
4
+ import "../chunk-MGTROA7K.js";
5
+ import "../chunk-EDEGIADD.js";
6
6
  import "../chunk-PNTKG3DZ.js";
7
7
  import {
8
8
  FISCAL_JOBS
9
- } from "../chunk-5S2PJHAE.js";
10
- import "../chunk-N5DCKYFR.js";
11
- import "../chunk-XQGW5HUG.js";
9
+ } from "../chunk-OSYB7CVT.js";
10
+ import "../chunk-2ISYBTCE.js";
11
+ import "../chunk-GF3DXCD2.js";
12
12
  import "../chunk-3SDXLSG4.js";
13
- import "../chunk-2LBQRYPV.js";
13
+ import "../chunk-H33BK623.js";
14
14
  import "../chunk-7QVYU63E.js";
15
15
 
16
16
  // src/manifest/server.ts
@@ -1,5 +1,5 @@
1
- export { b as FISCAL_CERTIFICATE_EXPIRING, c as FISCAL_CONTINGENCY_DEADLINE, d as FISCAL_DOCUMENT_NEEDS_ATTENTION, e as FISCAL_DOCUMENT_REJECTED } from './context-ChnWR4Kb.js';
2
- import { F as FiscalDocumentModel, g as FiscalDocumentStatus, N as NumberVoid } from './port-DpRFK56U.js';
1
+ export { b as FISCAL_CERTIFICATE_EXPIRING, c as FISCAL_CONTINGENCY_DEADLINE, d as FISCAL_DOCUMENT_NEEDS_ATTENTION, e as FISCAL_DOCUMENT_REJECTED } from './context-CLSMOSuf.js';
2
+ import { F as FiscalDocumentModel, g as FiscalDocumentStatus, N as NumberVoid } from './types-BIJqm5GM.js';
3
3
  import './sale/index.js';
4
4
  import './sidecar/index.js';
5
5
  import './types-B1b8LIWX.js';
@@ -3,10 +3,10 @@ import {
3
3
  FISCAL_CONTINGENCY_DEADLINE,
4
4
  FISCAL_DOCUMENT_NEEDS_ATTENTION,
5
5
  FISCAL_DOCUMENT_REJECTED
6
- } from "./chunk-N5DCKYFR.js";
7
- import "./chunk-XQGW5HUG.js";
6
+ } from "./chunk-2ISYBTCE.js";
7
+ import "./chunk-GF3DXCD2.js";
8
8
  import "./chunk-3SDXLSG4.js";
9
- import "./chunk-2LBQRYPV.js";
9
+ import "./chunk-H33BK623.js";
10
10
  import {
11
11
  __name
12
12
  } from "./chunk-7QVYU63E.js";
@@ -1,8 +1,8 @@
1
- import { F as FiscalDocumentModel, h as FiscalDocument, d as IssuerFailure, i as FiscalDocumentEvent } from './port-DpRFK56U.js';
1
+ import { F as FiscalDocumentModel, h as FiscalDocument, d as IssuerFailure, i as CancelOrReturnInput, j as CancelOrReturnResult, k as FiscalDocumentEvent } from './types-BIJqm5GM.js';
2
2
  import { T as TaxRegime } from './types-B1b8LIWX.js';
3
3
  import { IssuerTaxRegime, Address } from './sale/index.js';
4
4
  import { SefazEnvironment, LookedUpDocument } from './sidecar/index.js';
5
- import { f as DocumentPolicy, S as SigningIdentityKind, g as FiscalDocumentsConfig, C as Cipher, E as EmitterProfile, I as IssuingPoint } from './context-ChnWR4Kb.js';
5
+ import { f as DocumentPolicy, S as SigningIdentityKind, g as FiscalDocumentsConfig, C as Cipher, E as EmitterProfile, I as IssuingPoint } from './context-CLSMOSuf.js';
6
6
 
7
7
  /**
8
8
  * Reading the emitter profile and the certificate upload off a request body:
@@ -87,9 +87,19 @@ interface IssueInput {
87
87
  readonly subjectId: string;
88
88
  readonly issuingPointId: string;
89
89
  readonly model: FiscalDocumentModel;
90
+ /**
91
+ * NFC-e only, at a point with a contingency series: how long (ms, from this
92
+ * call) the online send may go unanswered before the sale goes offline on
93
+ * that series — a caller whose paper cannot wait (a counter, 10 s). A live
94
+ * online document numbered this long ago and still unanswered goes offline
95
+ * at once. Absent: the send's own timeout and the sweep's rules.
96
+ */
97
+ readonly onlineDeadlineMs?: number;
90
98
  }
91
99
  /** How long an NFC-e may wait in contingency before it must be transmitted (24 h); the warning goes out at 20 h. */
92
100
  declare const CONTINGENCY_WARNING_AFTER_MS: number;
101
+ /** SEFAZ's refusals of a cancel that came too late: "prazo de cancelamento superior ao previsto". */
102
+ declare const LATE_CANCEL_CODES: readonly ["501"];
93
103
  declare function createFiscalDocuments(config: FiscalDocumentsServiceConfig): {
94
104
  getProfile: (ownerId: string) => Promise<EmitterProfile | null>;
95
105
  saveProfile: (ownerId: string, input: EmitterProfileInput) => Promise<EmitterProfile>;
@@ -112,6 +122,11 @@ declare function createFiscalDocuments(config: FiscalDocumentsServiceConfig): {
112
122
  document: FiscalDocument;
113
123
  failure: IssuerFailure | null;
114
124
  }>;
125
+ /**
126
+ * Cancel an authorised document, or — when SEFAZ says the cancel is too late
127
+ * (501) — issue the buyer's return NF-e of entry quoting it. Idempotent.
128
+ */
129
+ cancelOrReturn: (input: CancelOrReturnInput) => Promise<CancelOrReturnResult>;
115
130
  /** Ask SEFAZ what it knows of the key; a state the answer moves is recorded. */
116
131
  lookup: (input: {
117
132
  ownerId: string;
@@ -136,4 +151,4 @@ declare function createFiscalDocuments(config: FiscalDocumentsServiceConfig): {
136
151
  };
137
152
  type FiscalDocuments = ReturnType<typeof createFiscalDocuments>;
138
153
 
139
- export { CONTINGENCY_WARNING_AFTER_MS as C, type EmitterProfileInput as E, type FiscalDocuments as F, type IssueInput as I, type SweepReport as S, type CertificateFacts as a, type CertificateUpload as b, type FiscalDocumentsServiceConfig as c, type IssuingPointInput as d, createFiscalDocuments as e, parseIssuingPointInput as f, parseProfileInput as g, parseCertificateUpload as p };
154
+ export { CONTINGENCY_WARNING_AFTER_MS as C, type EmitterProfileInput as E, type FiscalDocuments as F, type IssueInput as I, LATE_CANCEL_CODES as L, type SweepReport as S, type CertificateFacts as a, type CertificateUpload as b, type FiscalDocumentsServiceConfig as c, type IssuingPointInput as d, createFiscalDocuments as e, parseIssuingPointInput as f, parseProfileInput as g, parseCertificateUpload as p };
@@ -1,5 +1,91 @@
1
1
  import { SaleForDocument } from './sale/index.js';
2
- import { SefazEnvironment, SidecarErrorClass, SigningCertificate, Csc, SidecarErrorBody, IssuedDocument, ContingencyEntry, ContingencySignedDocument, CancelledDocument, LookedUpDocument, InutilizedRange, SidecarHealth } from './sidecar/index.js';
2
+ import { SidecarErrorBody, SefazEnvironment, SigningCertificate, Csc, IssuedDocument, ContingencyEntry, ContingencySignedDocument, CancelledDocument, LookedUpDocument, InutilizedRange, SidecarHealth, SidecarErrorClass } from './sidecar/index.js';
3
+
4
+ /**
5
+ * The Issuer port: what the document service asks of whoever talks to SEFAZ.
6
+ * The first (and today only) adapter is the fiscal service in this package's
7
+ * `sidecar/` folder (`./sidecar`). A call never throws for a failure the
8
+ * service classified: it answers `{ ok: false, error }` with the service's
9
+ * class (`REJECTED`, `RETRYABLE`, `CONTINGENCY`, `AUTH`, `INVALID`,
10
+ * `INTERNAL`), and the document service maps that onto the state machine.
11
+ *
12
+ * The certificate and the CSC travel with each call (the service is
13
+ * stateless) inside {@link SigningMaterial}, built by the signing identity
14
+ * for this one call and dropped with it.
15
+ */
16
+
17
+ /** What signs one call: the A1 and, for an NFC-e, the CSC. Never stored, never logged. */
18
+ interface SigningMaterial {
19
+ readonly certificate: SigningCertificate;
20
+ readonly csc: Csc | null;
21
+ }
22
+ /** A failed call, classified. The service's error body, verbatim. */
23
+ type IssuerFailure = SidecarErrorBody["error"];
24
+ type IssuerOutcome<T> = {
25
+ readonly ok: true;
26
+ readonly answer: T;
27
+ } | {
28
+ readonly ok: false;
29
+ readonly error: IssuerFailure;
30
+ };
31
+ interface Call {
32
+ readonly environment: SefazEnvironment;
33
+ readonly signing: SigningMaterial;
34
+ }
35
+ interface IssueCall extends Call {
36
+ readonly model: FiscalDocumentModel;
37
+ readonly document: SaleForDocument;
38
+ }
39
+ interface SignContingencyCall extends Call {
40
+ readonly document: SaleForDocument;
41
+ readonly contingency: ContingencyEntry;
42
+ }
43
+ interface TransmitCall extends Call {
44
+ readonly model: FiscalDocumentModel;
45
+ readonly signedXml: string;
46
+ }
47
+ interface CancelCall extends Call {
48
+ readonly model: FiscalDocumentModel;
49
+ readonly accessKey: string;
50
+ readonly protocol: string;
51
+ readonly reason: string;
52
+ }
53
+ /** NFC-e only: cancel an online document whose sale was issued again in contingency (event 110112). */
54
+ interface CancelBySubstitutionCall extends Call {
55
+ readonly accessKey: string;
56
+ readonly protocol: string;
57
+ readonly reason: string;
58
+ readonly substituteAccessKey: string;
59
+ }
60
+ interface LookupCall extends Call {
61
+ readonly model: FiscalDocumentModel;
62
+ readonly accessKey: string;
63
+ }
64
+ interface InutilizeCall extends Call {
65
+ readonly model: FiscalDocumentModel;
66
+ readonly uf: string;
67
+ readonly cnpj: string;
68
+ readonly year: number;
69
+ readonly series: number;
70
+ readonly from: number;
71
+ readonly to: number;
72
+ readonly reason: string;
73
+ }
74
+ interface Issuer {
75
+ /** Build, sign and transmit. `AUTHORIZED` or `DENIED`. */
76
+ issue(call: IssueCall): Promise<IssuerOutcome<IssuedDocument>>;
77
+ /** NFC-e only: build and sign offline (`tpEmis = 9`); nothing is sent. */
78
+ signContingency(call: SignContingencyCall): Promise<IssuerOutcome<ContingencySignedDocument>>;
79
+ /** Send an already signed XML (a contingency document). */
80
+ transmit(call: TransmitCall): Promise<IssuerOutcome<IssuedDocument>>;
81
+ cancel(call: CancelCall): Promise<IssuerOutcome<CancelledDocument>>;
82
+ cancelBySubstitution(call: CancelBySubstitutionCall): Promise<IssuerOutcome<CancelledDocument>>;
83
+ lookup(call: LookupCall): Promise<IssuerOutcome<LookedUpDocument>>;
84
+ inutilize(call: InutilizeCall): Promise<IssuerOutcome<InutilizedRange>>;
85
+ health(): Promise<SidecarHealth>;
86
+ }
87
+ /** The path segment of a model on the service's routes. */
88
+ declare function modelPath(model: FiscalDocumentModel): "nfe" | "nfce";
3
89
 
4
90
  /**
5
91
  * The fiscal document record and its event log — the shape the package's
@@ -148,91 +234,25 @@ interface FiscalDocumentEvent {
148
234
  readonly code: string | null;
149
235
  readonly answer: unknown;
150
236
  }
151
-
152
- /**
153
- * The Issuer port: what the document service asks of whoever talks to SEFAZ.
154
- * The first (and today only) adapter is the fiscal service in this package's
155
- * `sidecar/` folder (`./sidecar`). A call never throws for a failure the
156
- * service classified: it answers `{ ok: false, error }` with the service's
157
- * class (`REJECTED`, `RETRYABLE`, `CONTINGENCY`, `AUTH`, `INVALID`,
158
- * `INTERNAL`), and the document service maps that onto the state machine.
159
- *
160
- * The certificate and the CSC travel with each call (the service is
161
- * stateless) inside {@link SigningMaterial}, built by the signing identity
162
- * for this one call and dropped with it.
163
- */
164
-
165
- /** What signs one call: the A1 and, for an NFC-e, the CSC. Never stored, never logged. */
166
- interface SigningMaterial {
167
- readonly certificate: SigningCertificate;
168
- readonly csc: Csc | null;
169
- }
170
- /** A failed call, classified. The service's error body, verbatim. */
171
- type IssuerFailure = SidecarErrorBody["error"];
172
- type IssuerOutcome<T> = {
173
- readonly ok: true;
174
- readonly answer: T;
175
- } | {
176
- readonly ok: false;
177
- readonly error: IssuerFailure;
178
- };
179
- interface Call {
180
- readonly environment: SefazEnvironment;
181
- readonly signing: SigningMaterial;
182
- }
183
- interface IssueCall extends Call {
184
- readonly model: FiscalDocumentModel;
185
- readonly document: SaleForDocument;
186
- }
187
- interface SignContingencyCall extends Call {
188
- readonly document: SaleForDocument;
189
- readonly contingency: ContingencyEntry;
190
- }
191
- interface TransmitCall extends Call {
192
- readonly model: FiscalDocumentModel;
193
- readonly signedXml: string;
194
- }
195
- interface CancelCall extends Call {
196
- readonly model: FiscalDocumentModel;
197
- readonly accessKey: string;
198
- readonly protocol: string;
199
- readonly reason: string;
200
- }
201
- /** NFC-e only: cancel an online document whose sale was issued again in contingency (event 110112). */
202
- interface CancelBySubstitutionCall extends Call {
203
- readonly accessKey: string;
204
- readonly protocol: string;
205
- readonly reason: string;
206
- readonly substituteAccessKey: string;
207
- }
208
- interface LookupCall extends Call {
209
- readonly model: FiscalDocumentModel;
210
- readonly accessKey: string;
211
- }
212
- interface InutilizeCall extends Call {
213
- readonly model: FiscalDocumentModel;
214
- readonly uf: string;
215
- readonly cnpj: string;
216
- readonly year: number;
217
- readonly series: number;
218
- readonly from: number;
219
- readonly to: number;
237
+ interface CancelOrReturnInput {
238
+ readonly ownerId: string;
239
+ readonly documentId: string;
240
+ /** SEFAZ's 15–255 characters, sent with the cancel. */
220
241
  readonly reason: string;
242
+ /** The NF-e (model 55) issuing point a return is numbered on. */
243
+ readonly returnPointId: string;
221
244
  }
222
- interface Issuer {
223
- /** Build, sign and transmit. `AUTHORIZED` or `DENIED`. */
224
- issue(call: IssueCall): Promise<IssuerOutcome<IssuedDocument>>;
225
- /** NFC-e only: build and sign offline (`tpEmis = 9`); nothing is sent. */
226
- signContingency(call: SignContingencyCall): Promise<IssuerOutcome<ContingencySignedDocument>>;
227
- /** Send an already signed XML (a contingency document). */
228
- transmit(call: TransmitCall): Promise<IssuerOutcome<IssuedDocument>>;
229
- cancel(call: CancelCall): Promise<IssuerOutcome<CancelledDocument>>;
230
- cancelBySubstitution(call: CancelBySubstitutionCall): Promise<IssuerOutcome<CancelledDocument>>;
231
- lookup(call: LookupCall): Promise<IssuerOutcome<LookedUpDocument>>;
232
- inutilize(call: InutilizeCall): Promise<IssuerOutcome<InutilizedRange>>;
233
- health(): Promise<SidecarHealth>;
245
+ interface CancelOrReturnResult {
246
+ /**
247
+ * `CANCELLED` inside the window; `RETURNED` past it (the return may itself
248
+ * still be SUBMITTED: the sweep settles it like any document); `REFUSED`
249
+ * when the issuer refused the cancel for any other reason (nothing changed).
250
+ */
251
+ readonly outcome: "CANCELLED" | "RETURNED" | "REFUSED";
252
+ /** The document asked about, as it stands: CANCELLED, or still AUTHORIZED beside its return. */
253
+ readonly document: FiscalDocument;
254
+ readonly returnDocument: FiscalDocument | null;
255
+ readonly failure: IssuerFailure | null;
234
256
  }
235
- /** The path segment of a model on the service's routes. */
236
- declare function modelPath(model: FiscalDocumentModel): "nfe" | "nfce";
237
257
 
238
- export { type CancelBySubstitutionCall as C, type DocumentEventKind as D, type FiscalDocumentModel as F, type Issuer as I, type LookupCall as L, type NumberVoid as N, OWED_VOIDS as O, type SignContingencyCall as S, type TransmitCall as T, type CancelCall as a, type InutilizeCall as b, type IssueCall as c, type IssuerFailure as d, type IssuerOutcome as e, type SigningMaterial as f, type FiscalDocumentStatus as g, type FiscalDocument as h, type FiscalDocumentEvent as i, type SeriesKind as j, type DocumentTotals as k, FISCAL_DOCUMENT_MODELS as l, modelPath as m, FISCAL_DOCUMENT_STATUSES as n, isLive as o };
258
+ export { type CancelBySubstitutionCall as C, type DocumentEventKind as D, type FiscalDocumentModel as F, type Issuer as I, type LookupCall as L, type NumberVoid as N, OWED_VOIDS as O, type SignContingencyCall as S, type TransmitCall as T, type CancelCall as a, type InutilizeCall as b, type IssueCall as c, type IssuerFailure as d, type IssuerOutcome as e, type SigningMaterial as f, type FiscalDocumentStatus as g, type FiscalDocument as h, type CancelOrReturnInput as i, type CancelOrReturnResult as j, type FiscalDocumentEvent as k, type SeriesKind as l, modelPath as m, type DocumentTotals as n, FISCAL_DOCUMENT_MODELS as o, FISCAL_DOCUMENT_STATUSES as p, isLive as q };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/fiscal",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
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.",
@@ -35,7 +35,13 @@ export type FiscalDocumentErrorCode =
35
35
  * A `RETURN` asked of an NFC-e. An NFC-e has no return purpose: the return is
36
36
  * an NF-e (model 55) of entry that references the NFC-e's key.
37
37
  */
38
- | "RETURN_ON_NFCE";
38
+ | "RETURN_ON_NFCE"
39
+ /**
40
+ * `cancelOrReturn` past SEFAZ's window on a document that is not an NFC-e:
41
+ * the buyer's return NF-e of entry answers a consumer's NFC-e only; an NF-e
42
+ * past its window is the issuer's own correction, not this path's.
43
+ */
44
+ | "RETURN_OF_NFCE_ONLY";
39
45
 
40
46
  export class FiscalDocumentError extends Error {
41
47
  readonly code: FiscalDocumentErrorCode;
@@ -29,8 +29,8 @@ export {
29
29
  xmlKeys,
30
30
  } from "./context";
31
31
  export type { FiscalDocumentsConfig, FiscalNotifyPort, FiscalReasons } from "./context";
32
- export { CONTINGENCY_WARNING_AFTER_MS, createFiscalDocuments } from "./service";
33
- export type { CertificateFacts, FiscalDocuments, FiscalDocumentsServiceConfig, IssueInput, SweepReport } from "./service";
32
+ export { CONTINGENCY_WARNING_AFTER_MS, LATE_CANCEL_CODES, createFiscalDocuments } from "./service";
33
+ export type { CancelOrReturnInput, CancelOrReturnResult, CertificateFacts, FiscalDocuments, FiscalDocumentsServiceConfig, IssueInput, SweepReport } from "./service";
34
34
  export { createMemoryFiscalStore } from "./memory";
35
35
  export type { MemoryFiscalStore } from "./memory";
36
36
  export { FISCAL_NEXT_NUMBER_SQL } from "./sql";
@@ -18,10 +18,11 @@ import { FiscalDocumentError } from "./errors";
18
18
  import { canTransition } from "./machine";
19
19
  import { type Deps, type FiscalDocumentsServiceConfig, createIssuingPoint, saveProfile, uploadCertificate } from "./service-profile";
20
20
  import { settleNumber, settleWithXml, storeNfeProc } from "./settle";
21
- import { signPending, submit, transmit } from "./steps";
22
- import { type DocumentTotals, type FiscalDocument, type FiscalDocumentModel, isLive } from "./types";
21
+ import { answerLive, assertOnlineDeadline, signPending, submit, transmit } from "./steps";
22
+ import { type CancelOrReturnInput, type CancelOrReturnResult, type DocumentTotals, type FiscalDocument, type FiscalDocumentModel, isLive } from "./types";
23
23
 
24
24
  export type { CertificateFacts, FiscalDocumentsServiceConfig } from "./service-profile";
25
+ export type { CancelOrReturnInput, CancelOrReturnResult } from "./types";
25
26
 
26
27
  export interface SweepReport {
27
28
  readonly advanced: Array<{ readonly documentId: string; readonly status: FiscalDocument["status"] }>;
@@ -33,6 +34,14 @@ export interface IssueInput {
33
34
  readonly subjectId: string;
34
35
  readonly issuingPointId: string;
35
36
  readonly model: FiscalDocumentModel;
37
+ /**
38
+ * NFC-e only, at a point with a contingency series: how long (ms, from this
39
+ * call) the online send may go unanswered before the sale goes offline on
40
+ * that series — a caller whose paper cannot wait (a counter, 10 s). A live
41
+ * online document numbered this long ago and still unanswered goes offline
42
+ * at once. Absent: the send's own timeout and the sweep's rules.
43
+ */
44
+ readonly onlineDeadlineMs?: number;
36
45
  }
37
46
 
38
47
  /** How long an NFC-e may wait in contingency before it must be transmitted (24 h); the warning goes out at 20 h. */
@@ -75,16 +84,19 @@ async function numberOrExisting(deps: Deps, input: Omit<IssueInput, "issuingPoin
75
84
  }
76
85
 
77
86
  async function issue(deps: Deps, input: IssueInput): Promise<FiscalDocument> {
87
+ assertOnlineDeadline(input.onlineDeadlineMs);
88
+ const deadlineAt = input.onlineDeadlineMs === undefined ? null : Date.now() + input.onlineDeadlineMs;
78
89
  const { profile, point } = await issuable(deps, input.ownerId, input.issuingPointId, input.model);
79
90
  const existing = await liveDocument(deps, input);
80
- if (existing !== null) return existing;
91
+ if (existing !== null) return answerLive(deps.ctx, existing, profile, input.onlineDeadlineMs);
81
92
  const signing = await deps.ctx.material(profile);
82
93
  const draft = await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: input.subjectId, model: input.model });
83
94
  assertDraftFits(draft, input.model);
84
95
  const numbered = await numberOrExisting(deps, input, () =>
85
96
  deps.ctx.createNumbered({ profile, point, subjectId: input.subjectId, model: input.model, seriesKind: "ONLINE", draft }),
86
97
  );
87
- return numbered.created ? submit(deps.ctx, numbered.document, profile, point, signing) : numbered.document;
98
+ if (!numbered.created) return answerLive(deps.ctx, numbered.document, profile, input.onlineDeadlineMs);
99
+ return submit(deps.ctx, numbered.document, profile, point, signing, deadlineAt);
88
100
  }
89
101
 
90
102
  /** Sign the sale offline at once (the register knows it is offline). A failure leaves it PENDING for the sweep. */
@@ -176,6 +188,73 @@ async function cancel(
176
188
  return { document: cancelled, failure: null };
177
189
  }
178
190
 
191
+ /** SEFAZ's refusals of a cancel that came too late: "prazo de cancelamento superior ao previsto". */
192
+ export const LATE_CANCEL_CODES = ["501"] as const;
193
+
194
+ const isLateCancel = (code: string | null): boolean => code !== null && (LATE_CANCEL_CODES as readonly string[]).includes(code);
195
+
196
+ /** The subject's live return NF-e that quotes this key, if one was issued already. */
197
+ async function liveReturnOf(deps: Deps, document: FiscalDocument): Promise<FiscalDocument | null> {
198
+ const returns = (await deps.config.store.listBySubject(document.ownerId, document.subjectId, "NFE")).filter(isLive);
199
+ const quoting = returns.filter((candidate) => returnsDocument(candidate, document));
200
+ return quoting[quoting.length - 1] ?? null;
201
+ }
202
+
203
+ /**
204
+ * Cancel an authorised document; when SEFAZ refuses the cancel as LATE (501),
205
+ * issue the buyer's return instead: an NF-e of entry on `returnPointId`, the
206
+ * host's `SaleSource` answering the return sale for the document's subject
207
+ * (`model: "NFE"`), which must quote this document's key. The document itself
208
+ * stays AUTHORIZED: a return never cancels it.
209
+ *
210
+ * Idempotent: a document already cancelled, or already answered with a live
211
+ * return, is answered as it stands, with no call to the issuer. A return the
212
+ * sale source does not quote is refused before a number is drawn.
213
+ */
214
+ async function cancelOrReturn(deps: Deps, input: CancelOrReturnInput): Promise<CancelOrReturnResult> {
215
+ assertReason(input.reason, "reason");
216
+ const document = await requireDocument(deps, input.ownerId, input.documentId);
217
+ if (document.status === "CANCELLED") return { outcome: "CANCELLED", document, returnDocument: null, failure: null };
218
+ const existing = document.accessKey === null ? null : await liveReturnOf(deps, document);
219
+ if (existing !== null) return { outcome: "RETURNED", document, returnDocument: existing, failure: null };
220
+ const cancelled = await cancel(deps, input);
221
+ if (cancelled.failure === null) return { outcome: "CANCELLED", document: cancelled.document, returnDocument: null, failure: null };
222
+ const late = cancelled.failure.class === "REJECTED" && isLateCancel(cancelled.failure.code);
223
+ if (!late) return { outcome: "REFUSED", document: cancelled.document, returnDocument: null, failure: cancelled.failure };
224
+ return { outcome: "RETURNED", document: cancelled.document, returnDocument: await issueReturn(deps, document, input.returnPointId), failure: cancelled.failure };
225
+ }
226
+
227
+ /** Whether `candidate` is a buyer's return NF-e of entry quoting `document`. */
228
+ function returnsDocument(candidate: Pick<FiscalDocument, "model" | "sale">, document: FiscalDocument): boolean {
229
+ const quotes = (candidate.sale.referencedDocuments ?? []).some((reference) => reference.accessKey === document.accessKey);
230
+ return candidate.model === "NFE" && candidate.sale.purpose === "RETURN" && quotes;
231
+ }
232
+
233
+ /**
234
+ * The return of a late-cancelled NFC-e. Refused, before any number is drawn,
235
+ * for anything but an NFC-e, for a subject that already holds a live NF-e that
236
+ * is not this return (the live index allows one per subject and model), and
237
+ * for a sale source whose return does not quote the document.
238
+ */
239
+ async function issueReturn(deps: Deps, document: FiscalDocument, returnPointId: string): Promise<FiscalDocument> {
240
+ if (document.model !== "NFCE") {
241
+ throw new FiscalDocumentError("RETURN_OF_NFCE_ONLY", `document ${document.id} is an ${document.model}: only an NFC-e is answered with a buyer's return.`);
242
+ }
243
+ const live = (await deps.config.store.listBySubject(document.ownerId, document.subjectId, "NFE")).filter(isLive);
244
+ if (live.length > 0) {
245
+ throw new FiscalDocumentError("SUBJECT_HAS_DOCUMENT", `subject ${document.subjectId} already holds a live NF-e that is not document ${document.id}'s return.`);
246
+ }
247
+ const draft = await deps.config.sales.saleFor({ ownerId: document.ownerId, subjectId: document.subjectId, model: "NFE" });
248
+ if (!returnsDocument({ model: "NFE", sale: draft as FiscalDocument["sale"] }, document)) {
249
+ throw new FiscalDocumentError("INVALID_INPUT", `the return the sale source answered for subject ${document.subjectId} does not quote document ${document.id}.`);
250
+ }
251
+ const returned = await issue(deps, { ownerId: document.ownerId, subjectId: document.subjectId, issuingPointId: returnPointId, model: "NFE" });
252
+ if (returned.id === document.id || !returnsDocument(returned, document)) {
253
+ throw new FiscalDocumentError("CONFLICT", `subject ${document.subjectId}'s live NF-e is not document ${document.id}'s return.`);
254
+ }
255
+ return returned;
256
+ }
257
+
179
258
  /** Whether a lookup's answer moves this document (a settled number moves only while it is owed one). */
180
259
  function lookupMoves(document: FiscalDocument): boolean {
181
260
  if (!canTransition(document.status, "LOOKUP")) return false;
@@ -272,6 +351,11 @@ export function createFiscalDocuments(config: FiscalDocumentsServiceConfig) {
272
351
  resendContingency: resendContingency.bind(null, deps),
273
352
  /** Cancel an authorised document. A refusal (late, say) answers the issuer's failure and changes nothing. */
274
353
  cancel: cancel.bind(null, deps),
354
+ /**
355
+ * Cancel an authorised document, or — when SEFAZ says the cancel is too late
356
+ * (501) — issue the buyer's return NF-e of entry quoting it. Idempotent.
357
+ */
358
+ cancelOrReturn: cancelOrReturn.bind(null, deps),
275
359
  /** Ask SEFAZ what it knows of the key; a state the answer moves is recorded. */
276
360
  lookup: lookup.bind(null, deps),
277
361
  /** A person takes a document back from `attention`; the sweep tries it again. */