@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/README.md +3 -0
- package/dist/{chunk-GKT3X5CF.js → chunk-2ISYBTCE.js} +2 -2
- package/dist/{chunk-GGYJPFBJ.js → chunk-EDEGIADD.js} +2 -2
- package/dist/{chunk-V6G2OFLA.js → chunk-F2PGQVWL.js} +3 -3
- package/dist/{chunk-XQGW5HUG.js → chunk-GF3DXCD2.js} +1 -1
- package/dist/chunk-GF3DXCD2.js.map +1 -0
- package/dist/{chunk-MEBG7FGG.js → chunk-OSYB7CVT.js} +2 -2
- package/dist/{context-yc1C2__K.d.ts → context-CLSMOSuf.d.ts} +1 -1
- package/dist/documents/index.d.ts +5 -5
- package/dist/documents/index.js +66 -8
- package/dist/documents/index.js.map +1 -1
- package/dist/http.d.ts +3 -3
- package/dist/http.js +3 -3
- package/dist/issuer/index.d.ts +2 -2
- package/dist/jobs.d.ts +3 -3
- package/dist/jobs.js +3 -3
- package/dist/manifest/server.d.ts +3 -3
- package/dist/manifest/server.js +5 -5
- package/dist/notifications.d.ts +2 -2
- package/dist/notifications.js +2 -2
- package/dist/{service-BB9lWdyg.d.ts → service-hR3tgLpO.d.ts} +11 -23
- package/dist/{port-B1-ipIL4.d.ts → types-BIJqm5GM.d.ts} +105 -85
- package/package.json +1 -1
- package/src/documents/service.ts +16 -26
- package/src/documents/steps.ts +100 -4
- package/src/documents/types.ts +23 -0
- package/dist/chunk-XQGW5HUG.js.map +0 -1
- /package/dist/{chunk-GKT3X5CF.js.map → chunk-2ISYBTCE.js.map} +0 -0
- /package/dist/{chunk-GGYJPFBJ.js.map → chunk-EDEGIADD.js.map} +0 -0
- /package/dist/{chunk-V6G2OFLA.js.map → chunk-F2PGQVWL.js.map} +0 -0
- /package/dist/{chunk-MEBG7FGG.js.map → chunk-OSYB7CVT.js.map} +0 -0
package/README.md
CHANGED
|
@@ -148,6 +148,9 @@ const documents = createFiscalDocuments({
|
|
|
148
148
|
newId: () => crypto.randomUUID(),
|
|
149
149
|
});
|
|
150
150
|
await documents.issue({ ownerId, subjectId, issuingPointId, model: "NFCE" });
|
|
151
|
+
// A counter whose paper cannot wait gives the send an online deadline: unanswered by then
|
|
152
|
+
// (or answered with no answer), the NFC-e goes offline on the point's contingency series.
|
|
153
|
+
await documents.issue({ ownerId, subjectId, issuingPointId, model: "NFCE", onlineDeadlineMs: 10_000 });
|
|
151
154
|
```
|
|
152
155
|
|
|
153
156
|
**One document is one number.** The state machine (`transition`) is pure:
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
OWED_VOIDS,
|
|
3
3
|
isLive
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-GF3DXCD2.js";
|
|
5
5
|
import {
|
|
6
6
|
FISCAL_ISSUE
|
|
7
7
|
} from "./chunk-3SDXLSG4.js";
|
|
@@ -607,4 +607,4 @@ export {
|
|
|
607
607
|
assertReason,
|
|
608
608
|
FiscalContext
|
|
609
609
|
};
|
|
610
|
-
//# sourceMappingURL=chunk-
|
|
610
|
+
//# sourceMappingURL=chunk-2ISYBTCE.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
FISCAL_DOCUMENT_MODELS
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-GF3DXCD2.js";
|
|
4
4
|
import {
|
|
5
5
|
FiscalDocumentError
|
|
6
6
|
} from "./chunk-H33BK623.js";
|
|
@@ -189,4 +189,4 @@ export {
|
|
|
189
189
|
parseCertificateUpload,
|
|
190
190
|
parseIssuingPointInput
|
|
191
191
|
};
|
|
192
|
-
//# sourceMappingURL=chunk-
|
|
192
|
+
//# sourceMappingURL=chunk-EDEGIADD.js.map
|
|
@@ -6,10 +6,10 @@ import {
|
|
|
6
6
|
parseIssuingPointInput,
|
|
7
7
|
parseProfileInput,
|
|
8
8
|
viewOf
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-EDEGIADD.js";
|
|
10
10
|
import {
|
|
11
11
|
FISCAL_DOCUMENT_MODELS
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-GF3DXCD2.js";
|
|
13
13
|
import {
|
|
14
14
|
FISCAL_CANCEL,
|
|
15
15
|
FISCAL_ISSUE,
|
|
@@ -210,4 +210,4 @@ export {
|
|
|
210
210
|
FISCAL_ERROR_STATUS,
|
|
211
211
|
createApiFiscal
|
|
212
212
|
};
|
|
213
|
-
//# sourceMappingURL=chunk-
|
|
213
|
+
//# sourceMappingURL=chunk-F2PGQVWL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/documents/types.ts"],"sourcesContent":["/**\n * The fiscal document record and its event log — the shape the package's\n * Prisma partial stores (`prisma/fiscal.prisma`, `FiscalDocument` and\n * `FiscalDocumentEvent`) and the state machine (`./machine`) transitions.\n *\n * A document is ONE number: one issuing point, one series, one `nNF`. A sale\n * that goes offline is a second document on the issuing point's contingency\n * series, and the first one is `REPLACED` (see `./machine`). The record is\n * keyed by an opaque `subjectId`: what the subject is (an order, a payment,\n * several orders) is the host's to know, never this package's.\n */\n\nimport type { IssuerFailure } from \"../issuer/port\";\nimport type { SaleForDocument } from \"../sale/types\";\nimport type { SefazEnvironment, SidecarErrorClass } from \"../sidecar/types\";\n\n/** The document model: NF-e (55) or NFC-e (65). NFS-e is not a model of this package yet (FUT-2242). */\nexport type FiscalDocumentModel = \"NFE\" | \"NFCE\";\n\nexport const FISCAL_DOCUMENT_MODELS: readonly FiscalDocumentModel[] = [\"NFE\", \"NFCE\"];\n\n/**\n * - `PENDING`: numbered and stored, not yet handed to the issuer.\n * - `SUBMITTED`: handed to the issuer; no final answer yet (a retry is owed).\n * - `AUTHORIZED`: SEFAZ authorised it. The only state a cancel leaves.\n * - `REJECTED`: refused (SEFAZ's `cStat`, or a request the service refuses as\n * malformed). Final; its number was not spent at SEFAZ and is inutilized.\n * - `DENIED`: a denial of use. Final; the number IS spent.\n * - `CONTINGENCY`: signed offline (`tpEmis = 9`), owed a transmission.\n * - `CANCELLED`: an authorised document cancelled at SEFAZ.\n * - `REPLACED`: its sale moved to another document (the contingency one);\n * its number is settled apart (`numberVoid`).\n */\nexport type FiscalDocumentStatus =\n | \"PENDING\"\n | \"SUBMITTED\"\n | \"AUTHORIZED\"\n | \"REJECTED\"\n | \"DENIED\"\n | \"CONTINGENCY\"\n | \"CANCELLED\"\n | \"REPLACED\";\n\nexport const FISCAL_DOCUMENT_STATUSES: readonly FiscalDocumentStatus[] = [\n \"PENDING\",\n \"SUBMITTED\",\n \"AUTHORIZED\",\n \"REJECTED\",\n \"DENIED\",\n \"CONTINGENCY\",\n \"CANCELLED\",\n \"REPLACED\",\n];\n\n/** Which of the issuing point's series the number came from. */\nexport type SeriesKind = \"ONLINE\" | \"CONTINGENCY\";\n\n/**\n * What is still owed on a number SEFAZ never used, so the sequence has no\n * unexplained gap:\n *\n * - `null`: nothing — the number is a document (authorised, denied, owed a\n * transmission) or still in flight.\n * - `LOOKUP_FIRST`: a request went out with no answer before the sale moved\n * to contingency; look the key up before deciding.\n * - `INUTILIZE`: never used at SEFAZ; inutilize it.\n * - `CANCEL`: the lookup found it authorised after all; cancel it.\n * - `INUTILIZED` / `CANCELLED`: settled.\n * - `DENIED`: settled — the lookup found the number denied, which spends it.\n */\nexport type NumberVoid = \"LOOKUP_FIRST\" | \"INUTILIZE\" | \"CANCEL\" | \"INUTILIZED\" | \"CANCELLED\" | \"DENIED\";\n\n/** The `numberVoid` values that still owe the sweep a call. */\nexport const OWED_VOIDS: readonly NumberVoid[] = [\"LOOKUP_FIRST\", \"INUTILIZE\", \"CANCEL\"];\n\n/** The order figures a document carries, in integer cents. */\nexport interface DocumentTotals {\n /** What the buyer pays: Σ line values − Σ discounts. */\n readonly totalCents: number;\n readonly discountCents: number;\n readonly cbsCents: number;\n readonly ibsUfCents: number;\n readonly ibsMunCents: number;\n}\n\n/**\n * Whether the document is the one its subject stands on. At most one live\n * document per (owner, subject, model): a REPLACED one is not, nor an online\n * one SEFAZ rejected (its number is voided and the sale is issued again) —\n * unless a lookup had found it authorised (its protocol is kept). A\n * REJECTED contingency NFC-e stays live: the buyer holds its DANFE, and the\n * store corrects and resends it under the same number.\n */\nexport function isLive(document: Pick<FiscalDocument, \"status\" | \"seriesKind\" | \"protocol\">): boolean {\n if (document.status === \"REPLACED\") return false;\n // An online rejection with a protocol known (a lookup found it SEFAZ's) is still the sale's.\n return !(document.status === \"REJECTED\" && document.seriesKind === \"ONLINE\" && document.protocol === null);\n}\n\n/** One fiscal document. */\nexport interface FiscalDocument {\n readonly id: string;\n /** The emitter profile's owner: an opaque id the host maps (a store, a company). */\n readonly ownerId: string;\n /** The issuer's CNPJ: SEFAZ numbers by CNPJ, model and series, so the counters do too. */\n readonly issuerCnpj: string;\n /** What the document is FOR, opaque: the host links it to its orders. */\n readonly subjectId: string;\n readonly issuingPointId: string;\n readonly model: FiscalDocumentModel;\n readonly environment: SefazEnvironment;\n readonly seriesKind: SeriesKind;\n readonly series: number;\n readonly number: number;\n /** `cNF`, drawn once: a retried call yields the same key. */\n readonly keyCode: string;\n readonly status: FiscalDocumentStatus;\n /** The sale as sent, issuer and number filled in. Never a secret. */\n readonly sale: SaleForDocument;\n readonly totals: DocumentTotals;\n /** The buyer's CPF/CNPJ at issue time, or `null`. */\n readonly buyerTaxId: string | null;\n readonly accessKey: string | null;\n /** The authorisation (or denial) protocol. */\n readonly protocol: string | null;\n /** The last SEFAZ `cStat`, or the service's named code. */\n readonly statusCode: string | null;\n readonly statusReason: string | null;\n /** The class of the last failed call, or `null`. */\n readonly lastErrorClass: SidecarErrorClass | null;\n /** A request went out and neither it nor its lookup was answered. */\n readonly outcomeUnknown: boolean;\n /** `dhEmi`. */\n readonly issuedAt: string;\n readonly authorizedAt: string | null;\n readonly contingency: { readonly since: string; readonly reason: string } | null;\n readonly cancelledAt: string | null;\n readonly cancelReason: string | null;\n readonly cancelProtocol: string | null;\n /** The document this one's sale moved to. */\n readonly replacedById: string | null;\n readonly numberVoid: NumberVoid | null;\n /** Storage keys: the signed or authorised XML, and the cancel or inutilization event's XML. */\n readonly xmlKey: string | null;\n readonly eventXmlKey: string | null;\n /** Calls made to the issuer for this document. */\n readonly attempts: number;\n /** Failed steps in a row (a retry, a deferred settlement); any progress resets it. */\n readonly failures: number;\n /** When the sweep (or the contingency transmission) may take it again; `null` when nothing is owed. */\n readonly nextAttemptAt: string | null;\n /**\n * A person must look: a settlement SEFAZ refused, or too many failures in a\n * row. The sweep leaves it alone until someone releases it.\n */\n readonly attention: boolean;\n /** When the 24-hour contingency deadline warning went out. */\n readonly deadlineWarnedAt: string | null;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\n/** What the state machine was fed: the kind of the input that made the event. */\nexport type DocumentEventKind =\n | \"SUBMIT\"\n | \"AUTHORIZE\"\n | \"DENY\"\n | \"REJECT\"\n | \"RETRY\"\n | \"SIGN_OFFLINE\"\n | \"REPLACE\"\n | \"CANCEL\"\n | \"LOOKUP\"\n | \"INUTILIZE\"\n | \"DEFER\"\n | \"RESIGN\"\n | \"RELEASE\"\n | \"WARN\";\n\n/**\n * One transition, as stored. `answer` is what the fiscal service answered,\n * verbatim but for any secret-named key (`scrubSecrets`), so the record is the\n * evidence of what SEFAZ said, the `MarketplaceInboxEvent.payload` habit.\n */\nexport interface FiscalDocumentEvent {\n readonly documentId: string;\n readonly kind: DocumentEventKind;\n readonly fromStatus: FiscalDocumentStatus;\n readonly toStatus: FiscalDocumentStatus;\n readonly at: string;\n readonly errorClass: SidecarErrorClass | null;\n readonly code: string | null;\n readonly answer: unknown;\n}\n\nexport interface CancelOrReturnInput {\n readonly ownerId: string;\n readonly documentId: string;\n /** SEFAZ's 15–255 characters, sent with the cancel. */\n readonly reason: string;\n /** The NF-e (model 55) issuing point a return is numbered on. */\n readonly returnPointId: string;\n}\n\nexport interface CancelOrReturnResult {\n /**\n * `CANCELLED` inside the window; `RETURNED` past it (the return may itself\n * still be SUBMITTED: the sweep settles it like any document); `REFUSED`\n * when the issuer refused the cancel for any other reason (nothing changed).\n */\n readonly outcome: \"CANCELLED\" | \"RETURNED\" | \"REFUSED\";\n /** The document asked about, as it stands: CANCELLED, or still AUTHORIZED beside its return. */\n readonly document: FiscalDocument;\n readonly returnDocument: FiscalDocument | null;\n readonly failure: IssuerFailure | null;\n}\n"],"mappings":";;;;;AAmBO,IAAM,yBAAyD,CAAC,OAAO,MAAM;AAwB7E,IAAM,2BAA4D;AAAA,EACvE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAqBO,IAAM,aAAoC,CAAC,gBAAgB,aAAa,QAAQ;AAoBhF,SAAS,OAAO,UAA+E;AACpG,MAAI,SAAS,WAAW,WAAY,QAAO;AAE3C,SAAO,EAAE,SAAS,WAAW,cAAc,SAAS,eAAe,YAAY,SAAS,aAAa;AACvG;AAJgB;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
FISCAL_CERTIFICATE_EXPIRING
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-2ISYBTCE.js";
|
|
4
4
|
import {
|
|
5
5
|
FISCAL_MANAGE
|
|
6
6
|
} from "./chunk-3SDXLSG4.js";
|
|
@@ -82,4 +82,4 @@ export {
|
|
|
82
82
|
daysLeft,
|
|
83
83
|
FISCAL_JOBS
|
|
84
84
|
};
|
|
85
|
-
//# sourceMappingURL=chunk-
|
|
85
|
+
//# sourceMappingURL=chunk-OSYB7CVT.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { F as FiscalDocumentModel,
|
|
1
|
+
import { F as FiscalDocumentModel, n as DocumentTotals, D as DocumentEventKind, g as FiscalDocumentStatus, h as FiscalDocument, k as FiscalDocumentEvent, l as SeriesKind, f as SigningMaterial, I as Issuer } from './types-BIJqm5GM.js';
|
|
2
2
|
import { IssuerTaxRegime, Address, SaleForDocument } from './sale/index.js';
|
|
3
3
|
import { SefazEnvironment, IssuedDocument, SidecarErrorBody, ContingencySignedDocument, ContingencyEntry, CancelledDocument, LookedUpDocument, InutilizedRange } from './sidecar/index.js';
|
|
4
4
|
import { T as TaxRegime } from './types-B1b8LIWX.js';
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { F as FiscalDocumentModel,
|
|
2
|
-
export { D as DocumentEventKind,
|
|
3
|
-
import { h as SaleDraft, F as FiscalStore } from '../context-
|
|
4
|
-
export { C as Cipher, i as ContingencyBlockSource, j as DOCUMENT_POLICIES, k as DOCUMENT_TRANSITIONS, l as DocumentInput, f as DocumentPolicy, D as DocumentStorage, E as EmitterProfile, m as EmitterProfileView, n as FINAL_STATUSES, b as FISCAL_CERTIFICATE_EXPIRING, c as FISCAL_CONTINGENCY_DEADLINE, d as FISCAL_DOCUMENT_NEEDS_ATTENTION, e as FISCAL_DOCUMENT_REJECTED, g as FiscalDocumentsConfig, a as FiscalNotifyPort, o as FiscalReasons, I as IssuingPoint, M as MAX_FAILURES, N as NumberRequest, p as SIGNING_IDENTITY_KINDS, q as SaleSource, r as SigningIdentities, s as SigningIdentity, S as SigningIdentityKind, T as Transition, t as canTransition, u as createPlatformIdentity, v as createSigningIdentities, w as createStoreCertificateIdentity, x as scrubSecrets, y as transition, z as viewOf } from '../context-
|
|
5
|
-
export { C as CONTINGENCY_WARNING_AFTER_MS, a as
|
|
1
|
+
import { F as FiscalDocumentModel, l as SeriesKind, h as FiscalDocument, k as FiscalDocumentEvent } from '../types-BIJqm5GM.js';
|
|
2
|
+
export { i as CancelOrReturnInput, j as CancelOrReturnResult, D as DocumentEventKind, n as DocumentTotals, o as FISCAL_DOCUMENT_MODELS, p as FISCAL_DOCUMENT_STATUSES, g as FiscalDocumentStatus, N as NumberVoid, O as OWED_VOIDS, q as isLive } from '../types-BIJqm5GM.js';
|
|
3
|
+
import { h as SaleDraft, F as FiscalStore } from '../context-CLSMOSuf.js';
|
|
4
|
+
export { C as Cipher, i as ContingencyBlockSource, j as DOCUMENT_POLICIES, k as DOCUMENT_TRANSITIONS, l as DocumentInput, f as DocumentPolicy, D as DocumentStorage, E as EmitterProfile, m as EmitterProfileView, n as FINAL_STATUSES, b as FISCAL_CERTIFICATE_EXPIRING, c as FISCAL_CONTINGENCY_DEADLINE, d as FISCAL_DOCUMENT_NEEDS_ATTENTION, e as FISCAL_DOCUMENT_REJECTED, g as FiscalDocumentsConfig, a as FiscalNotifyPort, o as FiscalReasons, I as IssuingPoint, M as MAX_FAILURES, N as NumberRequest, p as SIGNING_IDENTITY_KINDS, q as SaleSource, r as SigningIdentities, s as SigningIdentity, S as SigningIdentityKind, T as Transition, t as canTransition, u as createPlatformIdentity, v as createSigningIdentities, w as createStoreCertificateIdentity, x as scrubSecrets, y as transition, z as viewOf } from '../context-CLSMOSuf.js';
|
|
5
|
+
export { C as CONTINGENCY_WARNING_AFTER_MS, a as CertificateFacts, b as CertificateUpload, E as EmitterProfileInput, F as FiscalDocuments, c as FiscalDocumentsServiceConfig, I as IssueInput, d as IssuingPointInput, L as LATE_CANCEL_CODES, S as SweepReport, e as createFiscalDocuments, p as parseCertificateUpload, f as parseIssuingPointInput, g as parseProfileInput } from '../service-hR3tgLpO.js';
|
|
6
6
|
import { a as TaxBreakdown } from '../types-B1b8LIWX.js';
|
|
7
7
|
import { SaleForDocument, SaleLine } from '../sale/index.js';
|
|
8
8
|
import '../sidecar/index.js';
|
package/dist/documents/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
parseIssuingPointInput,
|
|
6
6
|
parseProfileInput,
|
|
7
7
|
viewOf
|
|
8
|
-
} from "../chunk-
|
|
8
|
+
} from "../chunk-EDEGIADD.js";
|
|
9
9
|
import {
|
|
10
10
|
element
|
|
11
11
|
} from "../chunk-PNTKG3DZ.js";
|
|
@@ -32,13 +32,13 @@ import {
|
|
|
32
32
|
totalsOf,
|
|
33
33
|
transition,
|
|
34
34
|
xmlKeys
|
|
35
|
-
} from "../chunk-
|
|
35
|
+
} from "../chunk-2ISYBTCE.js";
|
|
36
36
|
import {
|
|
37
37
|
FISCAL_DOCUMENT_MODELS,
|
|
38
38
|
FISCAL_DOCUMENT_STATUSES,
|
|
39
39
|
OWED_VOIDS,
|
|
40
40
|
isLive
|
|
41
|
-
} from "../chunk-
|
|
41
|
+
} from "../chunk-GF3DXCD2.js";
|
|
42
42
|
import {
|
|
43
43
|
FISCAL_ISSUE
|
|
44
44
|
} from "../chunk-3SDXLSG4.js";
|
|
@@ -341,16 +341,59 @@ function staleOnline(ctx, document, point) {
|
|
|
341
341
|
return !knownToSefaz && canGoOffline(document, point) && pastOnlineTolerance(ctx, document);
|
|
342
342
|
}
|
|
343
343
|
__name(staleOnline, "staleOnline");
|
|
344
|
-
|
|
344
|
+
function pastDeadline(document) {
|
|
345
|
+
return {
|
|
346
|
+
class: "CONTINGENCY",
|
|
347
|
+
code: null,
|
|
348
|
+
message: "SEFAZ did not answer before the online deadline.",
|
|
349
|
+
details: [],
|
|
350
|
+
accessKey: document.accessKey ?? computeAccessKey({ sale: document.sale, model: document.model, seriesKind: "ONLINE" }),
|
|
351
|
+
signedXml: null,
|
|
352
|
+
sefazReply: null,
|
|
353
|
+
outcomeUnknown: true
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
__name(pastDeadline, "pastDeadline");
|
|
357
|
+
async function sendBefore(send2, document, deadlineAt) {
|
|
358
|
+
send2.catch(() => void 0);
|
|
359
|
+
let timer;
|
|
360
|
+
const late = new Promise((resolve) => {
|
|
361
|
+
timer = setTimeout(() => resolve({ ok: false, error: pastDeadline(document) }), Math.max(0, deadlineAt - Date.now()));
|
|
362
|
+
});
|
|
363
|
+
try {
|
|
364
|
+
return await Promise.race([send2, late]);
|
|
365
|
+
} finally {
|
|
366
|
+
clearTimeout(timer);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
__name(sendBefore, "sendBefore");
|
|
370
|
+
function send(ctx, document, signing, deadlineAt) {
|
|
371
|
+
const call = ctx.config.issuer.issue({ model: document.model, environment: document.environment, signing, document: document.sale });
|
|
372
|
+
return deadlineAt === null ? call : sendBefore(call, document, deadlineAt);
|
|
373
|
+
}
|
|
374
|
+
__name(send, "send");
|
|
375
|
+
function goesOffline(error, deadlineAt) {
|
|
376
|
+
return error.class === "CONTINGENCY" || deadlineAt !== null && error.class === "RETRYABLE";
|
|
377
|
+
}
|
|
378
|
+
__name(goesOffline, "goesOffline");
|
|
379
|
+
async function submit(ctx, document, profile, point, signing, deadlineAt = null) {
|
|
345
380
|
if (staleOnline(ctx, document, point)) return goOffline(ctx, document, profile, point, signing);
|
|
346
381
|
const sent = document.status === "PENDING" ? await ctx.advance(document, { kind: "SUBMIT" }) : document;
|
|
347
|
-
const
|
|
382
|
+
const bounded = deadlineAt !== null && canGoOffline(sent, point) ? deadlineAt : null;
|
|
383
|
+
const outcome = await send(ctx, sent, signing, bounded);
|
|
348
384
|
if (outcome.ok) return accept(ctx, sent, outcome.answer);
|
|
349
385
|
if (FINAL_FAILURES.has(outcome.error.class)) return reject(ctx, sent, outcome.error);
|
|
350
386
|
const retried = await ctx.advance(sent, { kind: "RETRY", error: outcome.error, ...await keepSigned(ctx, sent, outcome.error) });
|
|
351
|
-
return outcome.error
|
|
387
|
+
return goesOffline(outcome.error, bounded) && canGoOffline(retried, point) ? goOffline(ctx, retried, profile, point, signing) : retried;
|
|
352
388
|
}
|
|
353
389
|
__name(submit, "submit");
|
|
390
|
+
async function offlineIfOverdue(ctx, document, profile, point, signing, onlineDeadlineMs) {
|
|
391
|
+
const waiting = document.status === "PENDING" || document.status === "SUBMITTED";
|
|
392
|
+
const overdue = ctx.config.now().getTime() - Date.parse(document.createdAt) >= onlineDeadlineMs;
|
|
393
|
+
if (!waiting || !overdue || document.protocol !== null || !canGoOffline(document, point)) return document;
|
|
394
|
+
return goOffline(ctx, document, profile, point, signing);
|
|
395
|
+
}
|
|
396
|
+
__name(offlineIfOverdue, "offlineIfOverdue");
|
|
354
397
|
async function transmit(ctx, document, signing) {
|
|
355
398
|
const signedXml = document.xmlKey === null ? null : await ctx.config.storage.get(document.xmlKey);
|
|
356
399
|
if (signedXml === null) throw new FiscalDocumentError("NOT_FOUND", `document ${document.id} has no signed XML in storage.`);
|
|
@@ -360,6 +403,18 @@ async function transmit(ctx, document, signing) {
|
|
|
360
403
|
return ctx.advance(document, { kind: "RETRY", error: outcome.error });
|
|
361
404
|
}
|
|
362
405
|
__name(transmit, "transmit");
|
|
406
|
+
async function answerLive(ctx, existing, profile, onlineDeadlineMs) {
|
|
407
|
+
if (onlineDeadlineMs === void 0 || existing.model !== "NFCE" || existing.seriesKind !== "ONLINE") return existing;
|
|
408
|
+
const point = await ctx.requirePoint(existing.ownerId, existing.issuingPointId);
|
|
409
|
+
return offlineIfOverdue(ctx, existing, profile, point, await ctx.material(profile), onlineDeadlineMs);
|
|
410
|
+
}
|
|
411
|
+
__name(answerLive, "answerLive");
|
|
412
|
+
function assertOnlineDeadline(onlineDeadlineMs) {
|
|
413
|
+
if (onlineDeadlineMs !== void 0 && (!Number.isInteger(onlineDeadlineMs) || onlineDeadlineMs < 0)) {
|
|
414
|
+
throw new FiscalDocumentError("INVALID_INPUT", "onlineDeadlineMs must be a whole number of milliseconds, 0 or more.");
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
__name(assertOnlineDeadline, "assertOnlineDeadline");
|
|
363
418
|
|
|
364
419
|
// src/documents/service.ts
|
|
365
420
|
var CONTINGENCY_WARNING_AFTER_MS = 20 * 36e5;
|
|
@@ -397,9 +452,11 @@ async function numberOrExisting(deps, input, create) {
|
|
|
397
452
|
}
|
|
398
453
|
__name(numberOrExisting, "numberOrExisting");
|
|
399
454
|
async function issue(deps, input) {
|
|
455
|
+
assertOnlineDeadline(input.onlineDeadlineMs);
|
|
456
|
+
const deadlineAt = input.onlineDeadlineMs === void 0 ? null : Date.now() + input.onlineDeadlineMs;
|
|
400
457
|
const { profile, point } = await issuable(deps, input.ownerId, input.issuingPointId, input.model);
|
|
401
458
|
const existing = await liveDocument(deps, input);
|
|
402
|
-
if (existing !== null) return existing;
|
|
459
|
+
if (existing !== null) return answerLive(deps.ctx, existing, profile, input.onlineDeadlineMs);
|
|
403
460
|
const signing = await deps.ctx.material(profile);
|
|
404
461
|
const draft = await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: input.subjectId, model: input.model });
|
|
405
462
|
assertDraftFits(draft, input.model);
|
|
@@ -408,7 +465,8 @@ async function issue(deps, input) {
|
|
|
408
465
|
input,
|
|
409
466
|
() => deps.ctx.createNumbered({ profile, point, subjectId: input.subjectId, model: input.model, seriesKind: "ONLINE", draft })
|
|
410
467
|
);
|
|
411
|
-
|
|
468
|
+
if (!numbered.created) return answerLive(deps.ctx, numbered.document, profile, input.onlineDeadlineMs);
|
|
469
|
+
return submit(deps.ctx, numbered.document, profile, point, signing, deadlineAt);
|
|
412
470
|
}
|
|
413
471
|
__name(issue, "issue");
|
|
414
472
|
async function issueOffline(deps, input) {
|