@12-apps/fiscal 1.3.0 → 1.5.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-3E3NBXSW.js} +11 -4
- package/dist/chunk-3E3NBXSW.js.map +1 -0
- package/dist/{chunk-MEBG7FGG.js → chunk-G6QNU4FD.js} +2 -2
- package/dist/{chunk-XQGW5HUG.js → chunk-GH452ITO.js} +1 -1
- package/dist/chunk-GH452ITO.js.map +1 -0
- package/dist/{chunk-GGYJPFBJ.js → chunk-HMTPJWXM.js} +2 -2
- package/dist/{chunk-V6G2OFLA.js → chunk-TJCUO6D6.js} +3 -3
- package/dist/{chunk-JVQKJNOC.js → chunk-ZKWVKCGJ.js} +1 -1
- package/dist/chunk-ZKWVKCGJ.js.map +1 -0
- package/dist/{context-yc1C2__K.d.ts → context-CwZiHLnY.d.ts} +14 -3
- package/dist/documents/index.d.ts +7 -5
- package/dist/documents/index.js +155 -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/issuer/index.js +9 -1
- package/dist/issuer/index.js.map +1 -1
- 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/sale/index.d.ts +29 -1
- package/dist/sale/index.js +7 -0
- package/dist/sale/index.js.map +1 -1
- package/dist/{service-BB9lWdyg.d.ts → service-Cz2O84Xr.d.ts} +46 -24
- package/dist/sidecar/index.d.ts +37 -1
- package/dist/sidecar/index.js +1 -1
- package/dist/{port-B1-ipIL4.d.ts → types-DSYwap42.d.ts} +128 -87
- package/package.json +1 -1
- package/prisma/migrations/20261118120000_fiscal_link_payment_event/migration.sql +9 -0
- package/sidecar/README.md +1 -0
- package/sidecar/composer.json +1 -1
- package/sidecar/composer.lock +7 -7
- package/sidecar/schema/sale-for-document.schema.json +18 -1
- package/sidecar/src/Nfe/DocumentMapper.php +27 -0
- package/sidecar/src/Nfe/Input.php +10 -0
- package/sidecar/src/Nfe/NfeModule.php +1 -0
- package/sidecar/src/Nfe/NfeService.php +120 -0
- package/sidecar/src/Nfe/SefazReply.php +21 -0
- package/src/documents/helpers.ts +2 -0
- package/src/documents/index.ts +2 -1
- package/src/documents/machine-steps.ts +12 -2
- package/src/documents/machine.ts +7 -0
- package/src/documents/payment-link.ts +156 -0
- package/src/documents/service.ts +20 -26
- package/src/documents/steps.ts +100 -4
- package/src/documents/types.ts +25 -1
- package/src/issuer/port.ts +24 -1
- package/src/issuer/sidecar.ts +10 -0
- package/src/sale/index.ts +1 -0
- package/src/sale/types.ts +30 -0
- package/src/sidecar/types.ts +38 -0
- package/dist/chunk-GKT3X5CF.js.map +0 -1
- package/dist/chunk-JVQKJNOC.js.map +0 -1
- package/dist/chunk-XQGW5HUG.js.map +0 -1
- /package/dist/{chunk-MEBG7FGG.js.map → chunk-G6QNU4FD.js.map} +0 -0
- /package/dist/{chunk-GGYJPFBJ.js.map → chunk-HMTPJWXM.js.map} +0 -0
- /package/dist/{chunk-V6G2OFLA.js.map → chunk-TJCUO6D6.js.map} +0 -0
package/src/documents/machine.ts
CHANGED
|
@@ -21,6 +21,9 @@
|
|
|
21
21
|
* final state. A rejected contingency NFC-e is the one way back: the store
|
|
22
22
|
* corrects it and it is signed again under the same number (`RESIGN`).
|
|
23
23
|
*
|
|
24
|
+
* `LINK_PAYMENT` records an event 110300 SEFAZ registered on an authorised
|
|
25
|
+
* document (a payment transaction linked after the fact); it changes nothing.
|
|
26
|
+
*
|
|
24
27
|
* `DEFER`, `RELEASE` and `WARN` record what the sweep and a person did without
|
|
25
28
|
* changing the state: a failed step counts toward {@link MAX_FAILURES}, after
|
|
26
29
|
* which the document waits for a person (`attention`).
|
|
@@ -52,6 +55,7 @@ export const DOCUMENT_TRANSITIONS: Readonly<Record<DocumentEventKind, readonly F
|
|
|
52
55
|
RESIGN: ["REJECTED"],
|
|
53
56
|
RELEASE: ANY,
|
|
54
57
|
WARN: ["CONTINGENCY"],
|
|
58
|
+
LINK_PAYMENT: ["AUTHORIZED"],
|
|
55
59
|
};
|
|
56
60
|
|
|
57
61
|
/** The states nothing but a lookup, a cancel or an inutilization of the number may follow. */
|
|
@@ -79,6 +83,9 @@ export function scrubSecrets(value: unknown): unknown {
|
|
|
79
83
|
}
|
|
80
84
|
|
|
81
85
|
function answerOf(input: DocumentInput): unknown {
|
|
86
|
+
if (input.kind === "LINK_PAYMENT") {
|
|
87
|
+
return { ...input.answer, payment: input.payment, sequence: input.sequence, eventXmlKey: input.eventXmlKey };
|
|
88
|
+
}
|
|
82
89
|
if ("answer" in input) return input.answer;
|
|
83
90
|
if ("error" in input && input.error !== null) return { error: input.error };
|
|
84
91
|
if (input.kind === "DEFER") return { reason: input.reason };
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The event 110300 "Vinculação Pagamento" (NT 2026.006 v1.00 §5.1): a payment
|
|
3
|
+
* transaction linked to an authorised document after the fact — a Pix QR whose
|
|
4
|
+
* txid was learnt only once the note was out, say. One event per transaction
|
|
5
|
+
* (the event's single `gPgto`), numbered per document (`nSeqEvento`).
|
|
6
|
+
*
|
|
7
|
+
* Idempotent per `(document, transactionId)`: a transaction the document
|
|
8
|
+
* already carries in its own `gPgtoVinc`, or already linked by an earlier
|
|
9
|
+
* event, is skipped with no call to SEFAZ. A refusal answers the issuer's
|
|
10
|
+
* failure and records nothing; the caller may ask again. `nSeqEvento` is the
|
|
11
|
+
* next after the document's own recorded events; a 573 at it is settled by the
|
|
12
|
+
* event SEFAZ holds there (its XML kept, its transaction recorded as its own),
|
|
13
|
+
* and the payment is then sent at the next sequence.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type { IssuerFailure } from "../issuer/port";
|
|
17
|
+
import type { LinkedTransaction, PaymentLinkMeans } from "../sale/types";
|
|
18
|
+
import type { RegisteredPaymentLink } from "../sidecar/types";
|
|
19
|
+
import { xmlKeys } from "./context";
|
|
20
|
+
import { FiscalDocumentError } from "./errors";
|
|
21
|
+
import type { Deps } from "./service-profile";
|
|
22
|
+
import type { FiscalDocument, FiscalDocumentEvent } from "./types";
|
|
23
|
+
|
|
24
|
+
/** `nSeqEvento` runs 1–20 per event type and document. */
|
|
25
|
+
export const MAX_PAYMENT_LINKS = 20;
|
|
26
|
+
|
|
27
|
+
export interface LinkPaymentInput {
|
|
28
|
+
readonly ownerId: string;
|
|
29
|
+
readonly documentId: string;
|
|
30
|
+
readonly payments: readonly LinkedTransaction[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface LinkPaymentResult {
|
|
34
|
+
/** The transaction ids SEFAZ registered in this call. */
|
|
35
|
+
readonly linked: readonly string[];
|
|
36
|
+
/** Those the document already carried or an earlier event linked: nothing was sent. */
|
|
37
|
+
readonly alreadyLinked: readonly string[];
|
|
38
|
+
/** The first refusal, if any; the transactions after it were not sent. */
|
|
39
|
+
readonly failure: IssuerFailure | null;
|
|
40
|
+
readonly document: FiscalDocument;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Each 110300 the document's events record: the transaction and its `nSeqEvento`. */
|
|
44
|
+
function linkedByEvents(events: readonly FiscalDocumentEvent[]): Array<{ transactionId: string; sequence: number }> {
|
|
45
|
+
return events
|
|
46
|
+
.filter((event) => event.kind === "LINK_PAYMENT")
|
|
47
|
+
.map((event, index) => {
|
|
48
|
+
const answer = event.answer as { payment?: { transactionId?: unknown }; sequence?: unknown } | null;
|
|
49
|
+
return {
|
|
50
|
+
transactionId: answer?.payment?.transactionId,
|
|
51
|
+
sequence: typeof answer?.sequence === "number" ? answer.sequence : index + 1,
|
|
52
|
+
};
|
|
53
|
+
})
|
|
54
|
+
.filter((link): link is { transactionId: string; sequence: number } => typeof link.transactionId === "string");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The transaction ids the document's own `gPgtoVinc` carries. */
|
|
58
|
+
function linkedInDocument(document: FiscalDocument): string[] {
|
|
59
|
+
return document.sale.payments
|
|
60
|
+
.map((payment) => payment.linkedTransaction?.transactionId)
|
|
61
|
+
.filter((id): id is string => typeof id === "string");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** What every event of this document is sent with: its key, its protocol and the issuer's event call. */
|
|
65
|
+
function linkable(deps: Deps, document: FiscalDocument) {
|
|
66
|
+
const { accessKey, protocol } = document;
|
|
67
|
+
if (document.status !== "AUTHORIZED" || accessKey === null || protocol === null) {
|
|
68
|
+
throw new FiscalDocumentError("TRANSITION_REFUSED", `document ${document.id} is ${document.status}; only an authorised document is linked.`);
|
|
69
|
+
}
|
|
70
|
+
const send = deps.config.issuer.linkPayment;
|
|
71
|
+
if (typeof send !== "function") throw new FiscalDocumentError("NOT_SUPPORTED", "this issuer does not register the event 110300.");
|
|
72
|
+
return { accessKey, protocol, send: send.bind(deps.config.issuer) };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The transaction SEFAZ holds at the sequence just sent. A 135 registered what
|
|
77
|
+
* was sent. A 573 answers the event already there, looked up: the same
|
|
78
|
+
* transaction (a retry whose recording was lost), or another one, which is
|
|
79
|
+
* then recorded as ITS link and never attributed to `sent`.
|
|
80
|
+
*/
|
|
81
|
+
function heldTransaction(answer: RegisteredPaymentLink, sent: LinkedTransaction, requested: readonly LinkedTransaction[]): LinkedTransaction {
|
|
82
|
+
if (answer.statusCode !== "573" || answer.transaction.transactionId === sent.transactionId) return sent;
|
|
83
|
+
const held = answer.transaction;
|
|
84
|
+
return (
|
|
85
|
+
requested.find((payment) => payment.transactionId === held.transactionId) ?? {
|
|
86
|
+
transactionId: held.transactionId,
|
|
87
|
+
meansCode: held.meansCode as PaymentLinkMeans,
|
|
88
|
+
pspCnpjBase: held.pspCnpjBase,
|
|
89
|
+
receiverCnpj: held.receiverCnpj,
|
|
90
|
+
}
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** One call's progress: the document as last advanced, the next `nSeqEvento`, what is linked. */
|
|
95
|
+
interface LinkRun {
|
|
96
|
+
document: FiscalDocument;
|
|
97
|
+
sequence: number;
|
|
98
|
+
readonly known: Set<string>;
|
|
99
|
+
readonly requested: readonly LinkedTransaction[];
|
|
100
|
+
readonly linked: string[];
|
|
101
|
+
readonly send: (sequence: number, payment: LinkedTransaction) => ReturnType<NonNullable<Deps["config"]["issuer"]["linkPayment"]>>;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function refuseOverLimit(document: FiscalDocument): never {
|
|
105
|
+
throw new FiscalDocumentError("INVALID_INPUT", `document ${document.id} cannot take more than ${MAX_PAYMENT_LINKS} payment links.`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Sends `payment` at the run's sequence and records what SEFAZ holds there.
|
|
110
|
+
* When that is another transaction (a 573), it is recorded as its own link and
|
|
111
|
+
* `payment` goes out again at the next sequence. Answers the refusal, if any.
|
|
112
|
+
*/
|
|
113
|
+
async function sendOne(deps: Deps, run: LinkRun, accessKey: string, payment: LinkedTransaction): Promise<IssuerFailure | null> {
|
|
114
|
+
if (run.sequence > MAX_PAYMENT_LINKS) refuseOverLimit(run.document);
|
|
115
|
+
const sequence = run.sequence;
|
|
116
|
+
const outcome = await run.send(sequence, payment);
|
|
117
|
+
if (!outcome.ok) return outcome.error;
|
|
118
|
+
const held = heldTransaction(outcome.answer, payment, run.requested);
|
|
119
|
+
const { eventXml } = outcome.answer;
|
|
120
|
+
const eventXmlKey = eventXml === null ? null : xmlKeys.linkPayment(accessKey, sequence);
|
|
121
|
+
if (eventXmlKey !== null && eventXml !== null) await deps.config.storage.put(eventXmlKey, eventXml, "application/xml");
|
|
122
|
+
run.document = await deps.ctx.advance(run.document, { kind: "LINK_PAYMENT", answer: outcome.answer, payment: held, sequence, eventXmlKey });
|
|
123
|
+
run.known.add(held.transactionId);
|
|
124
|
+
if (run.requested.some((one) => one.transactionId === held.transactionId)) run.linked.push(held.transactionId);
|
|
125
|
+
run.sequence = sequence + 1;
|
|
126
|
+
return held.transactionId === payment.transactionId ? null : sendOne(deps, run, accessKey, payment);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export async function linkPayment(deps: Deps, input: LinkPaymentInput): Promise<LinkPaymentResult> {
|
|
130
|
+
const document = await deps.config.store.getDocument(input.ownerId, input.documentId);
|
|
131
|
+
if (document === null) throw new FiscalDocumentError("NOT_FOUND", `owner ${input.ownerId} has no document ${input.documentId}.`);
|
|
132
|
+
const { accessKey, protocol, send } = linkable(deps, document);
|
|
133
|
+
const byEvents = linkedByEvents(await deps.config.store.listEvents(document.id));
|
|
134
|
+
const known = new Set([...linkedInDocument(document), ...byEvents.map((link) => link.transactionId)]);
|
|
135
|
+
const pending = input.payments.filter((payment) => !known.has(payment.transactionId));
|
|
136
|
+
const alreadyLinked = input.payments.filter((payment) => known.has(payment.transactionId)).map((payment) => payment.transactionId);
|
|
137
|
+
// `nSeqEvento` follows the document's own events, never a count of anything else.
|
|
138
|
+
const sequence = Math.max(0, ...byEvents.map((link) => link.sequence)) + 1;
|
|
139
|
+
if (sequence - 1 + pending.length > MAX_PAYMENT_LINKS) refuseOverLimit(document);
|
|
140
|
+
if (pending.length === 0) return { linked: [], alreadyLinked, failure: null, document };
|
|
141
|
+
const signing = await deps.ctx.material(await deps.ctx.requireProfile(input.ownerId));
|
|
142
|
+
const run: LinkRun = {
|
|
143
|
+
document,
|
|
144
|
+
sequence,
|
|
145
|
+
known,
|
|
146
|
+
requested: pending,
|
|
147
|
+
linked: [],
|
|
148
|
+
send: (at, payment) => send({ model: document.model, environment: document.environment, signing, accessKey, protocol, sequence: at, payments: [payment] }),
|
|
149
|
+
};
|
|
150
|
+
for (const payment of pending) {
|
|
151
|
+
if (run.known.has(payment.transactionId)) continue;
|
|
152
|
+
const failure = await sendOne(deps, run, accessKey, payment);
|
|
153
|
+
if (failure !== null) return { linked: run.linked, alreadyLinked, failure, document: run.document };
|
|
154
|
+
}
|
|
155
|
+
return { linked: run.linked, alreadyLinked, failure: null, document: run.document };
|
|
156
|
+
}
|
package/src/documents/service.ts
CHANGED
|
@@ -18,10 +18,13 @@ 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 {
|
|
22
|
-
import {
|
|
21
|
+
import { linkPayment } from "./payment-link";
|
|
22
|
+
import { answerLive, assertOnlineDeadline, signPending, submit, transmit } from "./steps";
|
|
23
|
+
import { type CancelOrReturnInput, type CancelOrReturnResult, type DocumentTotals, type FiscalDocument, type FiscalDocumentModel, isLive } from "./types";
|
|
23
24
|
|
|
24
25
|
export type { CertificateFacts, FiscalDocumentsServiceConfig } from "./service-profile";
|
|
26
|
+
export type { CancelOrReturnInput, CancelOrReturnResult } from "./types";
|
|
27
|
+
export type { LinkPaymentInput, LinkPaymentResult } from "./payment-link";
|
|
25
28
|
|
|
26
29
|
export interface SweepReport {
|
|
27
30
|
readonly advanced: Array<{ readonly documentId: string; readonly status: FiscalDocument["status"] }>;
|
|
@@ -33,6 +36,14 @@ export interface IssueInput {
|
|
|
33
36
|
readonly subjectId: string;
|
|
34
37
|
readonly issuingPointId: string;
|
|
35
38
|
readonly model: FiscalDocumentModel;
|
|
39
|
+
/**
|
|
40
|
+
* NFC-e only, at a point with a contingency series: how long (ms, from this
|
|
41
|
+
* call) the online send may go unanswered before the sale goes offline on
|
|
42
|
+
* that series — a caller whose paper cannot wait (a counter, 10 s). A live
|
|
43
|
+
* online document numbered this long ago and still unanswered goes offline
|
|
44
|
+
* at once. Absent: the send's own timeout and the sweep's rules.
|
|
45
|
+
*/
|
|
46
|
+
readonly onlineDeadlineMs?: number;
|
|
36
47
|
}
|
|
37
48
|
|
|
38
49
|
/** 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 +86,19 @@ async function numberOrExisting(deps: Deps, input: Omit<IssueInput, "issuingPoin
|
|
|
75
86
|
}
|
|
76
87
|
|
|
77
88
|
async function issue(deps: Deps, input: IssueInput): Promise<FiscalDocument> {
|
|
89
|
+
assertOnlineDeadline(input.onlineDeadlineMs);
|
|
90
|
+
const deadlineAt = input.onlineDeadlineMs === undefined ? null : Date.now() + input.onlineDeadlineMs;
|
|
78
91
|
const { profile, point } = await issuable(deps, input.ownerId, input.issuingPointId, input.model);
|
|
79
92
|
const existing = await liveDocument(deps, input);
|
|
80
|
-
if (existing !== null) return existing;
|
|
93
|
+
if (existing !== null) return answerLive(deps.ctx, existing, profile, input.onlineDeadlineMs);
|
|
81
94
|
const signing = await deps.ctx.material(profile);
|
|
82
95
|
const draft = await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: input.subjectId, model: input.model });
|
|
83
96
|
assertDraftFits(draft, input.model);
|
|
84
97
|
const numbered = await numberOrExisting(deps, input, () =>
|
|
85
98
|
deps.ctx.createNumbered({ profile, point, subjectId: input.subjectId, model: input.model, seriesKind: "ONLINE", draft }),
|
|
86
99
|
);
|
|
87
|
-
|
|
100
|
+
if (!numbered.created) return answerLive(deps.ctx, numbered.document, profile, input.onlineDeadlineMs);
|
|
101
|
+
return submit(deps.ctx, numbered.document, profile, point, signing, deadlineAt);
|
|
88
102
|
}
|
|
89
103
|
|
|
90
104
|
/** Sign the sale offline at once (the register knows it is offline). A failure leaves it PENDING for the sweep. */
|
|
@@ -181,28 +195,6 @@ export const LATE_CANCEL_CODES = ["501"] as const;
|
|
|
181
195
|
|
|
182
196
|
const isLateCancel = (code: string | null): boolean => code !== null && (LATE_CANCEL_CODES as readonly string[]).includes(code);
|
|
183
197
|
|
|
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
198
|
/** The subject's live return NF-e that quotes this key, if one was issued already. */
|
|
207
199
|
async function liveReturnOf(deps: Deps, document: FiscalDocument): Promise<FiscalDocument | null> {
|
|
208
200
|
const returns = (await deps.config.store.listBySubject(document.ownerId, document.subjectId, "NFE")).filter(isLive);
|
|
@@ -366,6 +358,8 @@ export function createFiscalDocuments(config: FiscalDocumentsServiceConfig) {
|
|
|
366
358
|
* (501) — issue the buyer's return NF-e of entry quoting it. Idempotent.
|
|
367
359
|
*/
|
|
368
360
|
cancelOrReturn: cancelOrReturn.bind(null, deps),
|
|
361
|
+
/** Link payment transactions to an authorised document (event 110300), once each. Idempotent. */
|
|
362
|
+
linkPayment: linkPayment.bind(null, deps),
|
|
369
363
|
/** Ask SEFAZ what it knows of the key; a state the answer moves is recorded. */
|
|
370
364
|
lookup: lookup.bind(null, deps),
|
|
371
365
|
/** A person takes a document back from `attention`; the sweep tries it again. */
|
package/src/documents/steps.ts
CHANGED
|
@@ -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
|
-
/**
|
|
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
|
|
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
|
|
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
|
+
}
|
package/src/documents/types.ts
CHANGED
|
@@ -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
|
|
|
@@ -174,7 +175,8 @@ export type DocumentEventKind =
|
|
|
174
175
|
| "DEFER"
|
|
175
176
|
| "RESIGN"
|
|
176
177
|
| "RELEASE"
|
|
177
|
-
| "WARN"
|
|
178
|
+
| "WARN"
|
|
179
|
+
| "LINK_PAYMENT";
|
|
178
180
|
|
|
179
181
|
/**
|
|
180
182
|
* One transition, as stored. `answer` is what the fiscal service answered,
|
|
@@ -191,3 +193,25 @@ export interface FiscalDocumentEvent {
|
|
|
191
193
|
readonly code: string | null;
|
|
192
194
|
readonly answer: unknown;
|
|
193
195
|
}
|
|
196
|
+
|
|
197
|
+
export interface CancelOrReturnInput {
|
|
198
|
+
readonly ownerId: string;
|
|
199
|
+
readonly documentId: string;
|
|
200
|
+
/** SEFAZ's 15–255 characters, sent with the cancel. */
|
|
201
|
+
readonly reason: string;
|
|
202
|
+
/** The NF-e (model 55) issuing point a return is numbered on. */
|
|
203
|
+
readonly returnPointId: string;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export interface CancelOrReturnResult {
|
|
207
|
+
/**
|
|
208
|
+
* `CANCELLED` inside the window; `RETURNED` past it (the return may itself
|
|
209
|
+
* still be SUBMITTED: the sweep settles it like any document); `REFUSED`
|
|
210
|
+
* when the issuer refused the cancel for any other reason (nothing changed).
|
|
211
|
+
*/
|
|
212
|
+
readonly outcome: "CANCELLED" | "RETURNED" | "REFUSED";
|
|
213
|
+
/** The document asked about, as it stands: CANCELLED, or still AUTHORIZED beside its return. */
|
|
214
|
+
readonly document: FiscalDocument;
|
|
215
|
+
readonly returnDocument: FiscalDocument | null;
|
|
216
|
+
readonly failure: IssuerFailure | null;
|
|
217
|
+
}
|
package/src/issuer/port.ts
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
14
|
import type { FiscalDocumentModel } from "../documents/types";
|
|
15
|
-
import type { SaleForDocument } from "../sale/types";
|
|
15
|
+
import type { LinkedTransaction, SaleForDocument } from "../sale/types";
|
|
16
16
|
import type {
|
|
17
17
|
CancelledDocument,
|
|
18
18
|
ContingencyEntry,
|
|
@@ -21,6 +21,7 @@ import type {
|
|
|
21
21
|
InutilizedRange,
|
|
22
22
|
IssuedDocument,
|
|
23
23
|
LookedUpDocument,
|
|
24
|
+
RegisteredPaymentLink,
|
|
24
25
|
SefazEnvironment,
|
|
25
26
|
SidecarErrorBody,
|
|
26
27
|
SidecarHealth,
|
|
@@ -73,6 +74,21 @@ export interface CancelBySubstitutionCall extends Call {
|
|
|
73
74
|
readonly substituteAccessKey: string;
|
|
74
75
|
}
|
|
75
76
|
|
|
77
|
+
/** The event 110300 "Vinculação Pagamento" (NT 2026.006 v1.00): one transaction linked to an authorised document. */
|
|
78
|
+
export interface LinkPaymentCall extends Call {
|
|
79
|
+
readonly model: FiscalDocumentModel;
|
|
80
|
+
readonly accessKey: string;
|
|
81
|
+
readonly protocol: string;
|
|
82
|
+
/** `nSeqEvento`, 1–20. */
|
|
83
|
+
readonly sequence: number;
|
|
84
|
+
/**
|
|
85
|
+
* The transactions the event links. Exactly ONE today: the event's schema
|
|
86
|
+
* (`e110300_v1.00.xsd`) carries a single `gPgto`, so the service refuses any
|
|
87
|
+
* other count as INVALID; the list is the NT group's own shape.
|
|
88
|
+
*/
|
|
89
|
+
readonly payments: readonly LinkedTransaction[];
|
|
90
|
+
}
|
|
91
|
+
|
|
76
92
|
export interface LookupCall extends Call {
|
|
77
93
|
readonly model: FiscalDocumentModel;
|
|
78
94
|
readonly accessKey: string;
|
|
@@ -99,6 +115,13 @@ export interface Issuer {
|
|
|
99
115
|
cancel(call: CancelCall): Promise<IssuerOutcome<CancelledDocument>>;
|
|
100
116
|
cancelBySubstitution(call: CancelBySubstitutionCall): Promise<IssuerOutcome<CancelledDocument>>;
|
|
101
117
|
lookup(call: LookupCall): Promise<IssuerOutcome<LookedUpDocument>>;
|
|
118
|
+
/**
|
|
119
|
+
* The event 110300. Optional on the port so an issuer written before it
|
|
120
|
+
* still satisfies the type; one that lacks it cannot link (the document
|
|
121
|
+
* service answers `NOT_SUPPORTED`), and a host may read its presence as
|
|
122
|
+
* "this issuer writes `gPgtoVinc`".
|
|
123
|
+
*/
|
|
124
|
+
linkPayment?(call: LinkPaymentCall): Promise<IssuerOutcome<RegisteredPaymentLink>>;
|
|
102
125
|
inutilize(call: InutilizeCall): Promise<IssuerOutcome<InutilizedRange>>;
|
|
103
126
|
health(): Promise<SidecarHealth>;
|
|
104
127
|
}
|
package/src/issuer/sidecar.ts
CHANGED
|
@@ -17,6 +17,7 @@ import type {
|
|
|
17
17
|
CancelRequest,
|
|
18
18
|
InutilizeRequest,
|
|
19
19
|
IssueRequest,
|
|
20
|
+
LinkPaymentRequest,
|
|
20
21
|
LookupRequest,
|
|
21
22
|
SidecarErrorBody,
|
|
22
23
|
SidecarHealth,
|
|
@@ -143,6 +144,15 @@ export function createSidecarIssuer(config: SidecarIssuerConfig): Issuer {
|
|
|
143
144
|
reason,
|
|
144
145
|
substituteAccessKey,
|
|
145
146
|
} satisfies CancelBySubstitutionRequest),
|
|
147
|
+
linkPayment: ({ model, environment, signing, accessKey, protocol, sequence, payments }) =>
|
|
148
|
+
call(`/${modelPath(model)}/link-payment`, {
|
|
149
|
+
environment,
|
|
150
|
+
certificate: signing.certificate,
|
|
151
|
+
accessKey,
|
|
152
|
+
protocol,
|
|
153
|
+
sequence,
|
|
154
|
+
payments,
|
|
155
|
+
} satisfies LinkPaymentRequest),
|
|
146
156
|
lookup: ({ model, environment, signing, accessKey }) =>
|
|
147
157
|
call(`/${modelPath(model)}/lookup`, { environment, certificate: signing.certificate, accessKey } satisfies LookupRequest),
|
|
148
158
|
inutilize: ({ model, environment, signing, uf, cnpj, year, series, from, to, reason }) =>
|
package/src/sale/index.ts
CHANGED
package/src/sale/types.ts
CHANGED
|
@@ -208,6 +208,29 @@ export interface CardDetails {
|
|
|
208
208
|
readonly authorizationCode: string | null;
|
|
209
209
|
}
|
|
210
210
|
|
|
211
|
+
/**
|
|
212
|
+
* `tpMeioPgto` (Informe Técnico 2026.001 v1.01): the means a linked payment
|
|
213
|
+
* transaction moved by — 15 boleto, 17 Pix QR dinâmico, 18 TED, 20 Pix by key
|
|
214
|
+
* or static QR, 23 Pix automático, 24 TEF. A card and cash have none.
|
|
215
|
+
*/
|
|
216
|
+
export const PAYMENT_LINK_MEANS = ["15", "17", "18", "20", "23", "24"] as const;
|
|
217
|
+
export type PaymentLinkMeans = (typeof PAYMENT_LINK_MEANS)[number];
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* `gPgtoVinc/gPgto` (NT 2026.006 v1.00): a payment transaction started before
|
|
221
|
+
* the document — a Pix QR raised, a boleto generated — linked by its id, so the
|
|
222
|
+
* split payment can find the document. The event 110300 links one after the fact.
|
|
223
|
+
*/
|
|
224
|
+
export interface LinkedTransaction {
|
|
225
|
+
/** `idTransacao`, 2–35 characters: the Pix txid, the boleto's or the transfer's id. */
|
|
226
|
+
readonly transactionId: string;
|
|
227
|
+
readonly meansCode: PaymentLinkMeans;
|
|
228
|
+
/** `CNPJBasePSP`: the 8-character CNPJ base of the receiver's payment institution. */
|
|
229
|
+
readonly pspCnpjBase: string;
|
|
230
|
+
/** `CNPJReceb`: who receives the money (the issuer, or a platform receiving for it). */
|
|
231
|
+
readonly receiverCnpj: string;
|
|
232
|
+
}
|
|
233
|
+
|
|
211
234
|
export interface SalePayment {
|
|
212
235
|
readonly method: PaymentMethod;
|
|
213
236
|
readonly amountCents: number;
|
|
@@ -215,6 +238,13 @@ export interface SalePayment {
|
|
|
215
238
|
readonly card: CardDetails | null;
|
|
216
239
|
/** `xPag`: required when `method` is `OTHER`. */
|
|
217
240
|
readonly description: string | null;
|
|
241
|
+
/**
|
|
242
|
+
* The transaction this payment was started as, written in `gPgtoVinc` with
|
|
243
|
+
* `nPag` = its position. Absent or `null`: no link. The host decides whether
|
|
244
|
+
* the environment accepts the group (optional in the layout; its production
|
|
245
|
+
* activation is the fisco's).
|
|
246
|
+
*/
|
|
247
|
+
readonly linkedTransaction?: LinkedTransaction | null;
|
|
218
248
|
}
|
|
219
249
|
|
|
220
250
|
/** `finNFe` 1–4. */
|
package/src/sidecar/types.ts
CHANGED
|
@@ -80,6 +80,22 @@ export interface CancelBySubstitutionRequest extends CancelRequest {
|
|
|
80
80
|
readonly substituteAccessKey: string;
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
+
/** `POST /<model>/link-payment`: the event 110300 for one transaction (NT 2026.006 v1.00). */
|
|
84
|
+
export interface LinkPaymentRequest extends Authenticated {
|
|
85
|
+
readonly accessKey: string;
|
|
86
|
+
/** The authorisation protocol (`nProt`). */
|
|
87
|
+
readonly protocol: string;
|
|
88
|
+
/** `nSeqEvento`, 1–20: this document's how-manieth 110300. */
|
|
89
|
+
readonly sequence: number;
|
|
90
|
+
/** Exactly one entry: the event's schema carries a single `gPgto`. */
|
|
91
|
+
readonly payments: ReadonlyArray<{
|
|
92
|
+
readonly transactionId: string;
|
|
93
|
+
readonly meansCode: string;
|
|
94
|
+
readonly pspCnpjBase: string;
|
|
95
|
+
readonly receiverCnpj: string;
|
|
96
|
+
}>;
|
|
97
|
+
}
|
|
98
|
+
|
|
83
99
|
/** `POST /<model>/lookup`. */
|
|
84
100
|
export interface LookupRequest extends Authenticated {
|
|
85
101
|
readonly accessKey: string;
|
|
@@ -156,6 +172,28 @@ export interface CancelledDocument extends SefazAnswer {
|
|
|
156
172
|
readonly eventXml: string | null;
|
|
157
173
|
}
|
|
158
174
|
|
|
175
|
+
/**
|
|
176
|
+
* `/link-payment`: the event registered. On 573 "Duplicidade de Evento" the
|
|
177
|
+
* service looks the key up and answers the event SEFAZ already holds at that
|
|
178
|
+
* `nSeqEvento`, with its own XML and the transaction it carries — which may be
|
|
179
|
+
* another transaction than the one sent (`statusCode` "573" tells the two apart).
|
|
180
|
+
*/
|
|
181
|
+
export interface RegisteredPaymentLink extends SefazAnswer {
|
|
182
|
+
readonly status: "REGISTERED";
|
|
183
|
+
readonly accessKey: string;
|
|
184
|
+
readonly protocol: string | null;
|
|
185
|
+
readonly registeredAt: string | null;
|
|
186
|
+
/** The `procEventoNFe`. */
|
|
187
|
+
readonly eventXml: string | null;
|
|
188
|
+
/** The `gPgto` SEFAZ registered at this `nSeqEvento`. */
|
|
189
|
+
readonly transaction: {
|
|
190
|
+
readonly transactionId: string;
|
|
191
|
+
readonly meansCode: string;
|
|
192
|
+
readonly pspCnpjBase: string;
|
|
193
|
+
readonly receiverCnpj: string;
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
159
197
|
/** `/lookup`: what SEFAZ knows of the key. `NOT_FOUND` is an answer, not an error. */
|
|
160
198
|
export interface LookedUpDocument extends SefazAnswer {
|
|
161
199
|
readonly status: "AUTHORIZED" | "CANCELLED" | "DENIED" | "NOT_FOUND";
|