@12-apps/fiscal 1.3.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.
package/dist/http.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { D as DanfeNfceLabels } from './labels-BNvflT0h.js';
2
- import { D as DocumentStorage } from './context-yc1C2__K.js';
3
- import { F as FiscalDocuments } from './service-BB9lWdyg.js';
4
- import './port-B1-ipIL4.js';
2
+ import { D as DocumentStorage } 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/http.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  FISCAL_ERROR_STATUS,
3
3
  createApiFiscal
4
- } from "./chunk-V6G2OFLA.js";
4
+ } from "./chunk-F2PGQVWL.js";
5
5
  import "./chunk-MGTROA7K.js";
6
- import "./chunk-GGYJPFBJ.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
10
  import "./chunk-H33BK623.js";
11
11
  import "./chunk-7QVYU63E.js";
@@ -1,5 +1,5 @@
1
- import { I as Issuer } from '../port-B1-ipIL4.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-B1-ipIL4.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-yc1C2__K.js';
3
- import { F as FiscalDocuments } from './service-BB9lWdyg.js';
4
- import './port-B1-ipIL4.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,9 +5,9 @@ import {
5
5
  FISCAL_SWEEP_BATCH,
6
6
  FISCAL_WORST_STEP_MS,
7
7
  daysLeft
8
- } from "./chunk-MEBG7FGG.js";
9
- import "./chunk-GKT3X5CF.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
12
  import "./chunk-H33BK623.js";
13
13
  import "./chunk-7QVYU63E.js";
@@ -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-yc1C2__K.js';
5
- import '../port-B1-ipIL4.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-BB9lWdyg.js';
9
+ import '../service-hR3tgLpO.js';
10
10
  import '../labels-BNvflT0h.js';
11
11
 
12
12
  declare const fiscalServerManifest: {
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  createApiFiscal
3
- } from "../chunk-V6G2OFLA.js";
3
+ } from "../chunk-F2PGQVWL.js";
4
4
  import "../chunk-MGTROA7K.js";
5
- import "../chunk-GGYJPFBJ.js";
5
+ import "../chunk-EDEGIADD.js";
6
6
  import "../chunk-PNTKG3DZ.js";
7
7
  import {
8
8
  FISCAL_JOBS
9
- } from "../chunk-MEBG7FGG.js";
10
- import "../chunk-GKT3X5CF.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
13
  import "../chunk-H33BK623.js";
14
14
  import "../chunk-7QVYU63E.js";
@@ -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-yc1C2__K.js';
2
- import { F as FiscalDocumentModel, g as FiscalDocumentStatus, N as NumberVoid } from './port-B1-ipIL4.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,8 +3,8 @@ import {
3
3
  FISCAL_CONTINGENCY_DEADLINE,
4
4
  FISCAL_DOCUMENT_NEEDS_ATTENTION,
5
5
  FISCAL_DOCUMENT_REJECTED
6
- } from "./chunk-GKT3X5CF.js";
7
- import "./chunk-XQGW5HUG.js";
6
+ } from "./chunk-2ISYBTCE.js";
7
+ import "./chunk-GF3DXCD2.js";
8
8
  import "./chunk-3SDXLSG4.js";
9
9
  import "./chunk-H33BK623.js";
10
10
  import {
@@ -1,8 +1,8 @@
1
- import { F as FiscalDocumentModel, h as FiscalDocument, d as IssuerFailure, i as FiscalDocumentEvent } from './port-B1-ipIL4.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-yc1C2__K.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,31 +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;
93
101
  /** SEFAZ's refusals of a cancel that came too late: "prazo de cancelamento superior ao previsto". */
94
102
  declare const LATE_CANCEL_CODES: readonly ["501"];
95
- interface CancelOrReturnInput {
96
- readonly ownerId: string;
97
- readonly documentId: string;
98
- /** SEFAZ's 15–255 characters, sent with the cancel. */
99
- readonly reason: string;
100
- /** The NF-e (model 55) issuing point a return is numbered on. */
101
- readonly returnPointId: string;
102
- }
103
- interface CancelOrReturnResult {
104
- /**
105
- * `CANCELLED` inside the window; `RETURNED` past it (the return may itself
106
- * still be SUBMITTED: the sweep settles it like any document); `REFUSED`
107
- * when the issuer refused the cancel for any other reason (nothing changed).
108
- */
109
- readonly outcome: "CANCELLED" | "RETURNED" | "REFUSED";
110
- /** The document asked about, as it stands: CANCELLED, or still AUTHORIZED beside its return. */
111
- readonly document: FiscalDocument;
112
- readonly returnDocument: FiscalDocument | null;
113
- readonly failure: IssuerFailure | null;
114
- }
115
103
  declare function createFiscalDocuments(config: FiscalDocumentsServiceConfig): {
116
104
  getProfile: (ownerId: string) => Promise<EmitterProfile | null>;
117
105
  saveProfile: (ownerId: string, input: EmitterProfileInput) => Promise<EmitterProfile>;
@@ -163,4 +151,4 @@ declare function createFiscalDocuments(config: FiscalDocumentsServiceConfig): {
163
151
  };
164
152
  type FiscalDocuments = ReturnType<typeof createFiscalDocuments>;
165
153
 
166
- 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 CancelOrReturnInput as a, type CancelOrReturnResult as b, type CertificateFacts as c, type CertificateUpload as d, type FiscalDocumentsServiceConfig as e, type IssuingPointInput as f, createFiscalDocuments as g, parseIssuingPointInput as h, parseProfileInput as i, 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, SidecarErrorBody, SigningCertificate, Csc, 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.3.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.",
@@ -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. */
@@ -181,28 +193,6 @@ export const LATE_CANCEL_CODES = ["501"] as const;
181
193
 
182
194
  const isLateCancel = (code: string | null): boolean => code !== null && (LATE_CANCEL_CODES as readonly string[]).includes(code);
183
195
 
184
- export interface CancelOrReturnInput {
185
- readonly ownerId: string;
186
- readonly documentId: string;
187
- /** SEFAZ's 15–255 characters, sent with the cancel. */
188
- readonly reason: string;
189
- /** The NF-e (model 55) issuing point a return is numbered on. */
190
- readonly returnPointId: string;
191
- }
192
-
193
- export interface CancelOrReturnResult {
194
- /**
195
- * `CANCELLED` inside the window; `RETURNED` past it (the return may itself
196
- * still be SUBMITTED: the sweep settles it like any document); `REFUSED`
197
- * when the issuer refused the cancel for any other reason (nothing changed).
198
- */
199
- readonly outcome: "CANCELLED" | "RETURNED" | "REFUSED";
200
- /** The document asked about, as it stands: CANCELLED, or still AUTHORIZED beside its return. */
201
- readonly document: FiscalDocument;
202
- readonly returnDocument: FiscalDocument | null;
203
- readonly failure: IssuerFailure | null;
204
- }
205
-
206
196
  /** The subject's live return NF-e that quotes this key, if one was issued already. */
207
197
  async function liveReturnOf(deps: Deps, document: FiscalDocument): Promise<FiscalDocument | null> {
208
198
  const returns = (await deps.config.store.listBySubject(document.ownerId, document.subjectId, "NFE")).filter(isLive);
@@ -12,13 +12,22 @@
12
12
  * An online NFC-e is never sent again past `nfceOnlineToleranceMs` (SEFAZ
13
13
  * refuses a late `dhEmi`): where the point has a contingency series it goes
14
14
  * offline instead.
15
+ *
16
+ * A caller that cannot wait (a counter whose paper waits for the note) gives
17
+ * the send an ONLINE DEADLINE (`issue({ …, onlineDeadlineMs })`): an NFC-e at
18
+ * a point with a contingency series whose send is not answered by then — or is
19
+ * answered with no answer (`RETRYABLE`) — goes offline at once, exactly as a
20
+ * `CONTINGENCY` answer does. The send may still have reached SEFAZ, so the
21
+ * replaced number is marked unknown and looked up before it is voided; its
22
+ * late answer settles nothing.
15
23
  */
16
24
 
17
- import type { IssuerFailure, SigningMaterial } from "../issuer/port";
25
+ import type { IssuerFailure, IssuerOutcome, SigningMaterial } from "../issuer/port";
18
26
  import { FISCAL_ISSUE } from "../manifest/permissions";
19
27
  import type { IssuedDocument } from "../sidecar/types";
20
28
  import { FISCAL_DOCUMENT_REJECTED, type FiscalContext, draftOf, xmlKeys } from "./context";
21
29
  import { FiscalDocumentError } from "./errors";
30
+ import { computeAccessKey } from "./helpers";
22
31
  import { digestOf } from "./nfe-proc";
23
32
  import type { EmitterProfile, IssuingPoint } from "./profile";
24
33
  import type { FiscalDocument } from "./types";
@@ -145,21 +154,89 @@ function staleOnline(ctx: FiscalContext, document: FiscalDocument, point: Issuin
145
154
  return !knownToSefaz && canGoOffline(document, point) && pastOnlineTolerance(ctx, document);
146
155
  }
147
156
 
148
- /** Issue (or re-issue, for a SUBMITTED one) a document on its online series. */
157
+ /** The failure a send not answered by its online deadline counts as: a contingency, its outcome unknown. */
158
+ function pastDeadline(document: FiscalDocument): IssuerFailure {
159
+ return {
160
+ class: "CONTINGENCY",
161
+ code: null,
162
+ message: "SEFAZ did not answer before the online deadline.",
163
+ details: [],
164
+ accessKey: document.accessKey ?? computeAccessKey({ sale: document.sale, model: document.model, seriesKind: "ONLINE" }),
165
+ signedXml: null,
166
+ sefazReply: null,
167
+ outcomeUnknown: true,
168
+ };
169
+ }
170
+
171
+ /** The send, raced against the deadline (`deadlineAt`, epoch ms). A late answer is dropped: the number is looked up instead. */
172
+ async function sendBefore(
173
+ send: Promise<IssuerOutcome<IssuedDocument>>,
174
+ document: FiscalDocument,
175
+ deadlineAt: number,
176
+ ): Promise<IssuerOutcome<IssuedDocument>> {
177
+ send.catch(() => undefined);
178
+ let timer: ReturnType<typeof setTimeout> | undefined;
179
+ const late = new Promise<IssuerOutcome<IssuedDocument>>((resolve) => {
180
+ timer = setTimeout(() => resolve({ ok: false, error: pastDeadline(document) }), Math.max(0, deadlineAt - Date.now()));
181
+ });
182
+ try {
183
+ return await Promise.race([send, late]);
184
+ } finally {
185
+ clearTimeout(timer);
186
+ }
187
+ }
188
+
189
+ /** The online send, bounded by the deadline when there is one. */
190
+ function send(ctx: FiscalContext, document: FiscalDocument, signing: SigningMaterial, deadlineAt: number | null): Promise<IssuerOutcome<IssuedDocument>> {
191
+ const call = ctx.config.issuer.issue({ model: document.model, environment: document.environment, signing, document: document.sale });
192
+ return deadlineAt === null ? call : sendBefore(call, document, deadlineAt);
193
+ }
194
+
195
+ /** Whether a failed send moves the sale offline: a contingency always; with a deadline, an unanswered send too. */
196
+ function goesOffline(error: IssuerFailure, deadlineAt: number | null): boolean {
197
+ return error.class === "CONTINGENCY" || (deadlineAt !== null && error.class === "RETRYABLE");
198
+ }
199
+
200
+ /**
201
+ * Issue (or re-issue, for a SUBMITTED one) a document on its online series.
202
+ * `deadlineAt` (epoch ms): the online deadline, for an NFC-e whose point can
203
+ * go offline (see the module doc); `null`, the send's own timeout rules.
204
+ */
149
205
  export async function submit(
150
206
  ctx: FiscalContext,
151
207
  document: FiscalDocument,
152
208
  profile: EmitterProfile,
153
209
  point: IssuingPoint,
154
210
  signing: SigningMaterial,
211
+ deadlineAt: number | null = null,
155
212
  ): Promise<FiscalDocument> {
156
213
  if (staleOnline(ctx, document, point)) return goOffline(ctx, document, profile, point, signing);
157
214
  const sent = document.status === "PENDING" ? await ctx.advance(document, { kind: "SUBMIT" }) : document;
158
- const outcome = await ctx.config.issuer.issue({ model: sent.model, environment: sent.environment, signing, document: sent.sale });
215
+ const bounded = deadlineAt !== null && canGoOffline(sent, point) ? deadlineAt : null;
216
+ const outcome = await send(ctx, sent, signing, bounded);
159
217
  if (outcome.ok) return accept(ctx, sent, outcome.answer);
160
218
  if (FINAL_FAILURES.has(outcome.error.class)) return reject(ctx, sent, outcome.error);
161
219
  const retried = await ctx.advance(sent, { kind: "RETRY", error: outcome.error, ...(await keepSigned(ctx, sent, outcome.error)) });
162
- return outcome.error.class === "CONTINGENCY" && canGoOffline(retried, point) ? goOffline(ctx, retried, profile, point, signing) : retried;
220
+ return goesOffline(outcome.error, bounded) && canGoOffline(retried, point) ? goOffline(ctx, retried, profile, point, signing) : retried;
221
+ }
222
+
223
+ /**
224
+ * A live online NFC-e the caller's deadline already passed — `onlineDeadlineMs`
225
+ * since it was numbered, still unanswered and not known to SEFAZ — goes offline
226
+ * now, at a point with a contingency series; anything else is answered as it is.
227
+ */
228
+ async function offlineIfOverdue(
229
+ ctx: FiscalContext,
230
+ document: FiscalDocument,
231
+ profile: EmitterProfile,
232
+ point: IssuingPoint,
233
+ signing: SigningMaterial,
234
+ onlineDeadlineMs: number,
235
+ ): Promise<FiscalDocument> {
236
+ const waiting = document.status === "PENDING" || document.status === "SUBMITTED";
237
+ const overdue = ctx.config.now().getTime() - Date.parse(document.createdAt) >= onlineDeadlineMs;
238
+ if (!waiting || !overdue || document.protocol !== null || !canGoOffline(document, point)) return document;
239
+ return goOffline(ctx, document, profile, point, signing);
163
240
  }
164
241
 
165
242
  /** Transmit a document signed offline. */
@@ -171,3 +248,22 @@ export async function transmit(ctx: FiscalContext, document: FiscalDocument, sig
171
248
  if (FINAL_FAILURES.has(outcome.error.class)) return reject(ctx, document, outcome.error);
172
249
  return ctx.advance(document, { kind: "RETRY", error: outcome.error });
173
250
  }
251
+
252
+ /** The live document of a lost race or an earlier call — moved offline when the caller's online deadline already passed. */
253
+ export async function answerLive(
254
+ ctx: FiscalContext,
255
+ existing: FiscalDocument,
256
+ profile: EmitterProfile,
257
+ onlineDeadlineMs: number | undefined,
258
+ ): Promise<FiscalDocument> {
259
+ if (onlineDeadlineMs === undefined || existing.model !== "NFCE" || existing.seriesKind !== "ONLINE") return existing;
260
+ const point = await ctx.requirePoint(existing.ownerId, existing.issuingPointId);
261
+ return offlineIfOverdue(ctx, existing, profile, point, await ctx.material(profile), onlineDeadlineMs);
262
+ }
263
+
264
+ /** `onlineDeadlineMs`, when given, is a whole number of milliseconds, 0 or more. */
265
+ export function assertOnlineDeadline(onlineDeadlineMs: number | undefined): void {
266
+ if (onlineDeadlineMs !== undefined && (!Number.isInteger(onlineDeadlineMs) || onlineDeadlineMs < 0)) {
267
+ throw new FiscalDocumentError("INVALID_INPUT", "onlineDeadlineMs must be a whole number of milliseconds, 0 or more.");
268
+ }
269
+ }
@@ -10,6 +10,7 @@
10
10
  * several orders) is the host's to know, never this package's.
11
11
  */
12
12
 
13
+ import type { IssuerFailure } from "../issuer/port";
13
14
  import type { SaleForDocument } from "../sale/types";
14
15
  import type { SefazEnvironment, SidecarErrorClass } from "../sidecar/types";
15
16
 
@@ -191,3 +192,25 @@ export interface FiscalDocumentEvent {
191
192
  readonly code: string | null;
192
193
  readonly answer: unknown;
193
194
  }
195
+
196
+ export interface CancelOrReturnInput {
197
+ readonly ownerId: string;
198
+ readonly documentId: string;
199
+ /** SEFAZ's 15–255 characters, sent with the cancel. */
200
+ readonly reason: string;
201
+ /** The NF-e (model 55) issuing point a return is numbered on. */
202
+ readonly returnPointId: string;
203
+ }
204
+
205
+ export interface CancelOrReturnResult {
206
+ /**
207
+ * `CANCELLED` inside the window; `RETURNED` past it (the return may itself
208
+ * still be SUBMITTED: the sweep settles it like any document); `REFUSED`
209
+ * when the issuer refused the cancel for any other reason (nothing changed).
210
+ */
211
+ readonly outcome: "CANCELLED" | "RETURNED" | "REFUSED";
212
+ /** The document asked about, as it stands: CANCELLED, or still AUTHORIZED beside its return. */
213
+ readonly document: FiscalDocument;
214
+ readonly returnDocument: FiscalDocument | null;
215
+ readonly failure: IssuerFailure | null;
216
+ }