@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.
Files changed (62) hide show
  1. package/README.md +3 -0
  2. package/dist/{chunk-GKT3X5CF.js → chunk-3E3NBXSW.js} +11 -4
  3. package/dist/chunk-3E3NBXSW.js.map +1 -0
  4. package/dist/{chunk-MEBG7FGG.js → chunk-G6QNU4FD.js} +2 -2
  5. package/dist/{chunk-XQGW5HUG.js → chunk-GH452ITO.js} +1 -1
  6. package/dist/chunk-GH452ITO.js.map +1 -0
  7. package/dist/{chunk-GGYJPFBJ.js → chunk-HMTPJWXM.js} +2 -2
  8. package/dist/{chunk-V6G2OFLA.js → chunk-TJCUO6D6.js} +3 -3
  9. package/dist/{chunk-JVQKJNOC.js → chunk-ZKWVKCGJ.js} +1 -1
  10. package/dist/chunk-ZKWVKCGJ.js.map +1 -0
  11. package/dist/{context-yc1C2__K.d.ts → context-CwZiHLnY.d.ts} +14 -3
  12. package/dist/documents/index.d.ts +7 -5
  13. package/dist/documents/index.js +155 -8
  14. package/dist/documents/index.js.map +1 -1
  15. package/dist/http.d.ts +3 -3
  16. package/dist/http.js +3 -3
  17. package/dist/issuer/index.d.ts +2 -2
  18. package/dist/issuer/index.js +9 -1
  19. package/dist/issuer/index.js.map +1 -1
  20. package/dist/jobs.d.ts +3 -3
  21. package/dist/jobs.js +3 -3
  22. package/dist/manifest/server.d.ts +3 -3
  23. package/dist/manifest/server.js +5 -5
  24. package/dist/notifications.d.ts +2 -2
  25. package/dist/notifications.js +2 -2
  26. package/dist/sale/index.d.ts +29 -1
  27. package/dist/sale/index.js +7 -0
  28. package/dist/sale/index.js.map +1 -1
  29. package/dist/{service-BB9lWdyg.d.ts → service-Cz2O84Xr.d.ts} +46 -24
  30. package/dist/sidecar/index.d.ts +37 -1
  31. package/dist/sidecar/index.js +1 -1
  32. package/dist/{port-B1-ipIL4.d.ts → types-DSYwap42.d.ts} +128 -87
  33. package/package.json +1 -1
  34. package/prisma/migrations/20261118120000_fiscal_link_payment_event/migration.sql +9 -0
  35. package/sidecar/README.md +1 -0
  36. package/sidecar/composer.json +1 -1
  37. package/sidecar/composer.lock +7 -7
  38. package/sidecar/schema/sale-for-document.schema.json +18 -1
  39. package/sidecar/src/Nfe/DocumentMapper.php +27 -0
  40. package/sidecar/src/Nfe/Input.php +10 -0
  41. package/sidecar/src/Nfe/NfeModule.php +1 -0
  42. package/sidecar/src/Nfe/NfeService.php +120 -0
  43. package/sidecar/src/Nfe/SefazReply.php +21 -0
  44. package/src/documents/helpers.ts +2 -0
  45. package/src/documents/index.ts +2 -1
  46. package/src/documents/machine-steps.ts +12 -2
  47. package/src/documents/machine.ts +7 -0
  48. package/src/documents/payment-link.ts +156 -0
  49. package/src/documents/service.ts +20 -26
  50. package/src/documents/steps.ts +100 -4
  51. package/src/documents/types.ts +25 -1
  52. package/src/issuer/port.ts +24 -1
  53. package/src/issuer/sidecar.ts +10 -0
  54. package/src/sale/index.ts +1 -0
  55. package/src/sale/types.ts +30 -0
  56. package/src/sidecar/types.ts +38 -0
  57. package/dist/chunk-GKT3X5CF.js.map +0 -1
  58. package/dist/chunk-JVQKJNOC.js.map +0 -1
  59. package/dist/chunk-XQGW5HUG.js.map +0 -1
  60. /package/dist/{chunk-MEBG7FGG.js.map → chunk-G6QNU4FD.js.map} +0 -0
  61. /package/dist/{chunk-GGYJPFBJ.js.map → chunk-HMTPJWXM.js.map} +0 -0
  62. /package/dist/{chunk-V6G2OFLA.js.map → chunk-TJCUO6D6.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-XQGW5HUG.js";
4
+ } from "./chunk-GH452ITO.js";
5
5
  import {
6
6
  FISCAL_ISSUE
7
7
  } from "./chunk-3SDXLSG4.js";
@@ -173,7 +173,8 @@ var STEPS = {
173
173
  return SETTLED;
174
174
  }, "RELEASE"),
175
175
  // `deadlineWarnedAt` is the transition's own time, set by `transition`.
176
- WARN: /* @__PURE__ */ __name(() => ({}), "WARN")
176
+ WARN: /* @__PURE__ */ __name(() => ({}), "WARN"),
177
+ LINK_PAYMENT: /* @__PURE__ */ __name(() => ({}), "LINK_PAYMENT")
177
178
  };
178
179
 
179
180
  // src/documents/machine.ts
@@ -201,7 +202,8 @@ var DOCUMENT_TRANSITIONS = {
201
202
  DEFER: ANY,
202
203
  RESIGN: ["REJECTED"],
203
204
  RELEASE: ANY,
204
- WARN: ["CONTINGENCY"]
205
+ WARN: ["CONTINGENCY"],
206
+ LINK_PAYMENT: ["AUTHORIZED"]
205
207
  };
206
208
  var FINAL_STATUSES = ["REJECTED", "DENIED", "CANCELLED", "REPLACED"];
207
209
  var SECRET_KEY = /^(pfx|pfxBase64|password|passphrase|certificate|csc|token|privateKey)$/i;
@@ -216,6 +218,9 @@ function scrubSecrets(value) {
216
218
  }
217
219
  __name(scrubSecrets, "scrubSecrets");
218
220
  function answerOf(input) {
221
+ if (input.kind === "LINK_PAYMENT") {
222
+ return { ...input.answer, payment: input.payment, sequence: input.sequence, eventXmlKey: input.eventXmlKey };
223
+ }
219
224
  if ("answer" in input) return input.answer;
220
225
  if ("error" in input && input.error !== null) return { error: input.error };
221
226
  if (input.kind === "DEFER") return { reason: input.reason };
@@ -317,6 +322,8 @@ var xmlKeys = {
317
322
  signedByDigest: /* @__PURE__ */ __name((accessKey, digest) => `fiscal/${accessKey}/signed-${trimEnd(digest.replace(/\+/g, "-").replace(/\//g, "_"), "=")}.xml`, "signedByDigest"),
318
323
  authorized: /* @__PURE__ */ __name((accessKey) => `fiscal/${accessKey}/authorized.xml`, "authorized"),
319
324
  cancel: /* @__PURE__ */ __name((accessKey) => `fiscal/${accessKey}/cancel.xml`, "cancel"),
325
+ /** The event 110300 of `nSeqEvento` `sequence`. */
326
+ linkPayment: /* @__PURE__ */ __name((accessKey, sequence) => `fiscal/${accessKey}/link-payment-${sequence}.xml`, "linkPayment"),
320
327
  inutilization: /* @__PURE__ */ __name((document) => `fiscal/inutilization/${document.environment}/${document.model}/${document.ownerId}/${document.series}-${document.number}.xml`, "inutilization")
321
328
  };
322
329
  var UF_CODES = {
@@ -607,4 +614,4 @@ export {
607
614
  assertReason,
608
615
  FiscalContext
609
616
  };
610
- //# sourceMappingURL=chunk-GKT3X5CF.js.map
617
+ //# sourceMappingURL=chunk-3E3NBXSW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/documents/machine-steps.ts","../src/documents/machine.ts","../src/documents/helpers.ts","../src/documents/context.ts"],"sourcesContent":["/**\n * What each input does to a document's fields — the state machine's body\n * (`./machine` holds its table and its one entry point). Pure functions; a\n * refusal throws `TRANSITION_REFUSED`.\n */\n\nimport type {\n CancelledDocument,\n ContingencyEntry,\n ContingencySignedDocument,\n InutilizedRange,\n IssuedDocument,\n LookedUpDocument,\n RegisteredPaymentLink,\n SidecarErrorBody,\n} from \"../sidecar/types\";\nimport type { LinkedTransaction, SaleForDocument } from \"../sale/types\";\nimport { FiscalDocumentError } from \"./errors\";\nimport { type DocumentEventKind, type DocumentTotals, type FiscalDocument, type NumberVoid, isLive } from \"./types\";\n\nexport type SidecarError = SidecarErrorBody[\"error\"];\n\n/** Failures in a row after which a document waits for a person. */\nexport const MAX_FAILURES = 8;\n\n/** What the machine is fed. Each carries the service's answer, which the event keeps. */\nexport type DocumentInput =\n | { readonly kind: \"SUBMIT\" }\n | { readonly kind: \"AUTHORIZE\"; readonly answer: IssuedDocument; readonly xmlKey: string }\n | { readonly kind: \"DENY\"; readonly answer: IssuedDocument; readonly xmlKey: string }\n | { readonly kind: \"REJECT\"; readonly error: SidecarError }\n /** `xmlKey`: where the signed XML the failed call returned was stored, when it returned one. */\n | { readonly kind: \"RETRY\"; readonly error: SidecarError; readonly xmlKey?: string }\n | {\n readonly kind: \"SIGN_OFFLINE\";\n readonly answer: ContingencySignedDocument;\n readonly contingency: ContingencyEntry;\n readonly xmlKey: string;\n }\n | { readonly kind: \"REPLACE\"; readonly replacedById: string }\n | { readonly kind: \"CANCEL\"; readonly answer: CancelledDocument; readonly reason: string; readonly eventXmlKey: string | null }\n /**\n * `xmlKey`: the `nfeProc` assembled from the stored signed XML and the\n * lookup's protocol. Without it a lookup never makes a SUBMITTED document\n * final: an authorised document always has its XML.\n */\n | { readonly kind: \"LOOKUP\"; readonly answer: LookedUpDocument; readonly xmlKey?: string }\n | { readonly kind: \"INUTILIZE\"; readonly answer: InutilizedRange; readonly eventXmlKey: string | null }\n /**\n * A step that made no progress (a settlement refused or unanswered, a step\n * that threw). It counts a failure; `attention` hands the document to a\n * person at once (SEFAZ refused it: retrying would only repeat the refusal).\n */\n | { readonly kind: \"DEFER\"; readonly reason: string; readonly error: SidecarError | null; readonly attention: boolean }\n /** A rejected contingency NFC-e, corrected by the store and signed again under the same number. */\n | {\n readonly kind: \"RESIGN\";\n readonly answer: ContingencySignedDocument;\n readonly sale: SaleForDocument;\n readonly totals: DocumentTotals;\n readonly buyerTaxId: string | null;\n readonly xmlKey: string;\n }\n /** A person took a document back from `attention`: the sweep may try again. */\n | { readonly kind: \"RELEASE\" }\n /** The 24-hour contingency deadline warning went out. */\n | { readonly kind: \"WARN\" }\n /** SEFAZ registered the event 110300 #`sequence` linking `payment` to the document; its XML is at `eventXmlKey`. */\n | {\n readonly kind: \"LINK_PAYMENT\";\n readonly answer: RegisteredPaymentLink;\n readonly payment: LinkedTransaction;\n readonly sequence: number;\n readonly eventXmlKey: string | null;\n };\n\ntype InputOf<K extends DocumentEventKind> = Extract<DocumentInput, { kind: K }>;\ntype Step = { readonly [K in DocumentEventKind]: (document: FiscalDocument, input: InputOf<K>) => Partial<FiscalDocument> };\n\nexport function refuse(document: FiscalDocument, kind: DocumentEventKind, why: string): never {\n throw new FiscalDocumentError(\n \"TRANSITION_REFUSED\",\n `${kind} is refused on document ${document.id} in ${document.status}: ${why}.`,\n );\n}\n\n/** Progress: the failure count, the person's flag and the unknown outcome are settled. */\nconst SETTLED = { failures: 0, attention: false } as const;\n\nfunction issuedFields(answer: IssuedDocument, xmlKey: string): Partial<FiscalDocument> {\n return {\n ...SETTLED,\n accessKey: answer.accessKey,\n protocol: answer.protocol,\n authorizedAt: answer.authorizedAt,\n statusCode: answer.statusCode,\n statusReason: answer.statusReason,\n lastErrorClass: null,\n outcomeUnknown: false,\n xmlKey,\n };\n}\n\n/**\n * A failed call. `outcomeUnknown` is STICKY: once a request may have reached\n * SEFAZ unanswered, only a definitive answer or a lookup clears it — a later\n * \"nothing was sent this time\" says nothing about the first send.\n */\nfunction failedFields(document: FiscalDocument, error: SidecarError): Partial<FiscalDocument> {\n return {\n accessKey: document.accessKey ?? error.accessKey,\n statusCode: error.code,\n statusReason: error.message,\n lastErrorClass: error.class,\n outcomeUnknown: document.outcomeUnknown || error.outcomeUnknown,\n };\n}\n\nfunction failure(document: FiscalDocument, attention: boolean): Partial<FiscalDocument> {\n const failures = document.failures + 1;\n return { failures, attention: attention || failures >= MAX_FAILURES };\n}\n\n/** What a lookup says is owed on a number SEFAZ may hold. */\nfunction voidAfterLookup(answer: LookedUpDocument): NumberVoid {\n if (answer.status === \"AUTHORIZED\") return \"CANCEL\";\n if (answer.status === \"CANCELLED\") return \"CANCELLED\";\n if (answer.status === \"DENIED\") return \"DENIED\";\n return \"INUTILIZE\";\n}\n\nfunction lookupOfSettledNumber(document: FiscalDocument, answer: LookedUpDocument): Partial<FiscalDocument> {\n if (document.numberVoid !== \"LOOKUP_FIRST\") refuse(document, \"LOOKUP\", \"its number is already settled\");\n if (isLive(document) && (answer.status === \"AUTHORIZED\" || answer.status === \"DENIED\")) {\n // The sale's own document, still SEFAZ's: never cancelled, never voided,\n // never left REJECTED. It goes back to SUBMITTED, owing work, with the\n // protocol kept — the next step settles it with its XML (the service does\n // at once when it holds the XML the protocol certifies; otherwise the\n // sweep sends the same call again, which the fiscal service settles).\n // Its failures keep counting, so a loop of refusals reaches a person.\n return {\n status: \"SUBMITTED\",\n numberVoid: null,\n outcomeUnknown: false,\n protocol: answer.protocol ?? document.protocol,\n statusCode: answer.statusCode,\n statusReason: answer.statusReason,\n };\n }\n return {\n ...SETTLED,\n numberVoid: voidAfterLookup(answer),\n outcomeUnknown: false,\n // The protocol SEFAZ answered is what a cancel of this number must quote.\n protocol: answer.protocol ?? document.protocol,\n statusCode: answer.statusCode,\n statusReason: answer.statusReason,\n };\n}\n\n/**\n * A lookup of a SUBMITTED document. It settles it as AUTHORIZED or DENIED\n * only with the XML in hand (`xmlKey`); otherwise it keeps what SEFAZ said —\n * the protocol marks the number as SEFAZ's — and the document stays\n * SUBMITTED, for the sweep to fetch the XML by sending the same call again.\n */\nfunction lookupOfSubmitted(document: FiscalDocument, answer: LookedUpDocument, xmlKey: string | undefined): Partial<FiscalDocument> {\n const known = { statusCode: answer.statusCode, statusReason: answer.statusReason, outcomeUnknown: false };\n // A key found cancelled elsewhere is left to the next issue call, which the service settles: CANCELLED is entered only from AUTHORIZED.\n const settles = answer.status === \"AUTHORIZED\" || answer.status === \"DENIED\";\n if (!settles || answer.protocol === null || document.accessKey === null) return known;\n if (xmlKey === undefined) return { ...known, protocol: answer.protocol };\n return { ...known, ...SETTLED, status: answer.status, protocol: answer.protocol, lastErrorClass: null, xmlKey };\n}\n\nfunction lookupFields(document: FiscalDocument, answer: LookedUpDocument, xmlKey?: string): Partial<FiscalDocument> {\n if (document.status === \"REPLACED\" || document.status === \"REJECTED\") return lookupOfSettledNumber(document, answer);\n if (document.status === \"SUBMITTED\") return lookupOfSubmitted(document, answer, xmlKey);\n if (answer.status === \"CANCELLED\") return { status: \"CANCELLED\", statusCode: answer.statusCode, statusReason: answer.statusReason };\n return { statusCode: answer.statusCode, statusReason: answer.statusReason };\n}\n\nfunction cancelFields(document: FiscalDocument, input: InputOf<\"CANCEL\">): Partial<FiscalDocument> {\n const recorded = {\n ...SETTLED,\n cancelledAt: input.answer.registeredAt,\n cancelReason: input.reason,\n cancelProtocol: input.answer.protocol,\n eventXmlKey: input.eventXmlKey,\n };\n if (document.status === \"AUTHORIZED\") {\n return { ...recorded, status: \"CANCELLED\", statusCode: input.answer.statusCode, statusReason: input.answer.statusReason };\n }\n if (document.numberVoid !== \"CANCEL\") refuse(document, \"CANCEL\", \"a voided number is cancelled only when found authorised\");\n return { ...recorded, numberVoid: \"CANCELLED\" };\n}\n\n/** A rejected online number may have been authorised by an unanswered first send: look it up first. */\n/**\n * A rejected online number may have been authorised by an unanswered first\n * send — or a lookup already found it authorised (its protocol is kept, and\n * a re-send for the XML met a 704 or a different XML under the key): either\n * way it is looked up, never voided blindly.\n */\nfunction rejectFields(document: FiscalDocument, error: SidecarError): Partial<FiscalDocument> {\n const failed = failedFields(document, error);\n if (document.seriesKind === \"CONTINGENCY\") return { status: \"REJECTED\", ...failed, ...SETTLED, numberVoid: null };\n // Known to be SEFAZ's: a refused re-send is one more failure of the same document, not a settlement.\n if (document.protocol !== null) return { status: \"REJECTED\", ...failed, ...failure(document, false), numberVoid: \"LOOKUP_FIRST\" };\n return { status: \"REJECTED\", ...failed, ...SETTLED, numberVoid: failed.outcomeUnknown === true ? \"LOOKUP_FIRST\" : \"INUTILIZE\" };\n}\n\nexport const STEPS: Step = {\n SUBMIT: () => ({ status: \"SUBMITTED\" }),\n AUTHORIZE: (_document, input) => ({ status: \"AUTHORIZED\", ...issuedFields(input.answer, input.xmlKey) }),\n DENY: (_document, input) => ({ status: \"DENIED\", ...issuedFields(input.answer, input.xmlKey) }),\n REJECT: (document, input) => rejectFields(document, input.error),\n RETRY: (document, input) => ({\n ...failedFields(document, input.error),\n ...failure(document, false),\n ...(input.xmlKey === undefined ? {} : { xmlKey: input.xmlKey }),\n }),\n SIGN_OFFLINE: (document, input) => {\n if (document.seriesKind !== \"CONTINGENCY\") refuse(document, input.kind, \"only a contingency-series number is signed offline\");\n return { ...SETTLED, status: \"CONTINGENCY\", accessKey: input.answer.accessKey, contingency: input.contingency, xmlKey: input.xmlKey };\n },\n REPLACE: (document, input) => ({\n ...SETTLED,\n status: \"REPLACED\",\n replacedById: input.replacedById,\n // A SUBMITTED document may have reached SEFAZ whatever was recorded (a process\n // that died mid-call, a receipt with no protocol yet): its key is always\n // known, so it is looked up before its number is voided. Only a PENDING one\n // was never sent.\n numberVoid: document.status === \"SUBMITTED\" ? \"LOOKUP_FIRST\" : \"INUTILIZE\",\n }),\n CANCEL: cancelFields,\n LOOKUP: (document, input) => lookupFields(document, input.answer, input.xmlKey),\n INUTILIZE: (document, input) => {\n if (document.numberVoid !== \"INUTILIZE\") refuse(document, input.kind, \"its number is not owed an inutilization\");\n return { ...SETTLED, numberVoid: \"INUTILIZED\", eventXmlKey: input.eventXmlKey };\n },\n DEFER: (document, input) => ({\n ...failure(document, input.attention),\n ...(input.error === null ? {} : { lastErrorClass: input.error.class, statusCode: input.error.code }),\n statusReason: input.error?.message ?? input.reason,\n }),\n RESIGN: (document, input) => {\n if (document.seriesKind !== \"CONTINGENCY\") refuse(document, input.kind, \"only a rejected contingency NFC-e is resent\");\n return {\n ...SETTLED,\n status: \"CONTINGENCY\",\n sale: input.sale,\n totals: input.totals,\n buyerTaxId: input.buyerTaxId,\n accessKey: input.answer.accessKey,\n xmlKey: input.xmlKey,\n statusCode: null,\n statusReason: null,\n lastErrorClass: null,\n };\n },\n RELEASE: (document) => {\n if (!document.attention) refuse(document, \"RELEASE\", \"it is not waiting for a person\");\n return SETTLED;\n },\n // `deadlineWarnedAt` is the transition's own time, set by `transition`.\n WARN: () => ({}),\n LINK_PAYMENT: () => ({}),\n};\n","/**\n * The fiscal document state machine: pure functions from a document and one\n * input to the next document and the event that records the step.\n *\n * ```\n * PENDING ──SUBMIT──▶ SUBMITTED ──AUTHORIZE──▶ AUTHORIZED ──CANCEL──▶ CANCELLED\n * │ │ ├──DENY─────▶ DENIED\n * │ │ ├──REJECT───▶ REJECTED\n * │ │ └──RETRY────▶ SUBMITTED\n * │ └──REPLACE──▶ REPLACED\n * ├──REPLACE──▶ REPLACED\n * └──SIGN_OFFLINE──▶ CONTINGENCY ──AUTHORIZE | DENY | REJECT | RETRY──▶ …\n * ▲ REJECTED (contingency) ──RESIGN──┘\n * ```\n *\n * A document is one number, so going offline is a SECOND document on the\n * issuing point's contingency series (`PENDING → CONTINGENCY`), and the first\n * one is `REPLACED`. Every input yields an event; a refused one throws\n * {@link FiscalDocumentError} `TRANSITION_REFUSED` and changes nothing:\n * `CANCELLED` is entered only from `AUTHORIZED`, and `AUTHORIZED` never from a\n * final state. A rejected contingency NFC-e is the one way back: the store\n * corrects it and it is signed again under the same number (`RESIGN`).\n *\n * `LINK_PAYMENT` records an event 110300 SEFAZ registered on an authorised\n * document (a payment transaction linked after the fact); it changes nothing.\n *\n * `DEFER`, `RELEASE` and `WARN` record what the sweep and a person did without\n * changing the state: a failed step counts toward {@link MAX_FAILURES}, after\n * which the document waits for a person (`attention`).\n */\n\nimport { type DocumentInput, STEPS, refuse } from \"./machine-steps\";\nimport type { DocumentEventKind, FiscalDocument, FiscalDocumentEvent, FiscalDocumentStatus } from \"./types\";\n\nexport { MAX_FAILURES } from \"./machine-steps\";\nexport type { DocumentInput } from \"./machine-steps\";\n\nconst ANY: readonly FiscalDocumentStatus[] = [\n \"PENDING\", \"SUBMITTED\", \"AUTHORIZED\", \"REJECTED\", \"DENIED\", \"CONTINGENCY\", \"CANCELLED\", \"REPLACED\",\n];\n\n/** From which states each input is accepted. */\nexport const DOCUMENT_TRANSITIONS: Readonly<Record<DocumentEventKind, readonly FiscalDocumentStatus[]>> = {\n SUBMIT: [\"PENDING\"],\n AUTHORIZE: [\"SUBMITTED\", \"CONTINGENCY\"],\n DENY: [\"SUBMITTED\", \"CONTINGENCY\"],\n REJECT: [\"SUBMITTED\", \"CONTINGENCY\"],\n RETRY: [\"SUBMITTED\", \"CONTINGENCY\"],\n SIGN_OFFLINE: [\"PENDING\"],\n REPLACE: [\"PENDING\", \"SUBMITTED\"],\n CANCEL: [\"AUTHORIZED\", \"REPLACED\", \"REJECTED\"],\n LOOKUP: [\"SUBMITTED\", \"AUTHORIZED\", \"REPLACED\", \"REJECTED\"],\n INUTILIZE: [\"REJECTED\", \"REPLACED\"],\n DEFER: ANY,\n RESIGN: [\"REJECTED\"],\n RELEASE: ANY,\n WARN: [\"CONTINGENCY\"],\n LINK_PAYMENT: [\"AUTHORIZED\"],\n};\n\n/** The states nothing but a lookup, a cancel or an inutilization of the number may follow. */\nexport const FINAL_STATUSES: readonly FiscalDocumentStatus[] = [\"REJECTED\", \"DENIED\", \"CANCELLED\", \"REPLACED\"];\n\nexport interface Transition {\n readonly document: FiscalDocument;\n readonly event: FiscalDocumentEvent;\n}\n\nconst SECRET_KEY = /^(pfx|pfxBase64|password|passphrase|certificate|csc|token|privateKey)$/i;\n\n/**\n * A copy of an answer with every secret-named key dropped. The service never\n * echoes one; this is the second lock, so an event row can never hold one.\n */\nexport function scrubSecrets(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(scrubSecrets);\n if (value === null || typeof value !== \"object\") return value;\n const out: Record<string, unknown> = {};\n for (const [key, inner] of Object.entries(value)) {\n if (!SECRET_KEY.test(key)) out[key] = scrubSecrets(inner);\n }\n return out;\n}\n\nfunction answerOf(input: DocumentInput): unknown {\n if (input.kind === \"LINK_PAYMENT\") {\n return { ...input.answer, payment: input.payment, sequence: input.sequence, eventXmlKey: input.eventXmlKey };\n }\n if (\"answer\" in input) return input.answer;\n if (\"error\" in input && input.error !== null) return { error: input.error };\n if (input.kind === \"DEFER\") return { reason: input.reason };\n return null;\n}\n\nfunction eventOf(document: FiscalDocument, input: DocumentInput, toStatus: FiscalDocumentStatus, at: string): FiscalDocumentEvent {\n const error = \"error\" in input ? input.error : null;\n const answer = \"answer\" in input ? input.answer : null;\n return {\n documentId: document.id,\n kind: input.kind,\n fromStatus: document.status,\n toStatus,\n at,\n errorClass: error?.class ?? null,\n code: error?.code ?? (answer !== null && \"statusCode\" in answer ? answer.statusCode : null),\n answer: scrubSecrets(answerOf(input)),\n };\n}\n\nconst COUNTED = new Set<DocumentEventKind>([\"SUBMIT\", \"RETRY\", \"SIGN_OFFLINE\", \"RESIGN\"]);\n\n/**\n * Apply one input. Throws `TRANSITION_REFUSED` (and changes nothing) when the\n * document's state does not accept it. `at` is the caller's clock, ISO 8601.\n */\nexport function transition(document: FiscalDocument, input: DocumentInput, at: string): Transition {\n if (!DOCUMENT_TRANSITIONS[input.kind].includes(document.status)) {\n refuse(document, input.kind, `accepted only from ${DOCUMENT_TRANSITIONS[input.kind].join(\", \")}`);\n }\n const step = STEPS[input.kind] as (document: FiscalDocument, input: DocumentInput) => Partial<FiscalDocument>;\n const updated: FiscalDocument = {\n ...document,\n ...step(document, input),\n ...(input.kind === \"WARN\" ? { deadlineWarnedAt: at } : {}),\n attempts: document.attempts + (COUNTED.has(input.kind) ? 1 : 0),\n updatedAt: at,\n };\n return { document: updated, event: eventOf(document, input, updated.status, at) };\n}\n\n/** Whether an input would be accepted, without applying it. */\nexport function canTransition(status: FiscalDocumentStatus, kind: DocumentEventKind): boolean {\n return DOCUMENT_TRANSITIONS[kind].includes(status);\n}\n\n","/**\n * The pure helpers the document service builds a document with: the local\n * clock, the key code, the access key, the issuer block, the totals, the\n * storage keys. No port, no state.\n */\n\nimport type { DocumentIssuer, SaleForDocument, Uf } from \"../sale/types\";\nimport { FiscalDocumentError } from \"./errors\";\nimport type { SaleDraft } from \"./ports\";\nimport type { EmitterProfile } from \"./profile\";\nimport type { DocumentTotals, FiscalDocument, FiscalDocumentModel, SeriesKind } from \"./types\";\n\n/** `2026-11-20T12:30:00-03:00`: the instant as the owner's wall clock. */\nexport function localIso(at: Date, offset: string): string {\n const match = /^([+-])(\\d{2}):(\\d{2})$/.exec(offset);\n if (match === null) throw new FiscalDocumentError(\"INVALID_INPUT\", `utcOffset answered \"${offset}\", not ±HH:MM.`);\n const minutes = (match[1] === \"-\" ? -1 : 1) * (Number(match[2]) * 60 + Number(match[3]));\n return `${new Date(at.getTime() + minutes * 60_000).toISOString().slice(0, 19)}${offset}`;\n}\n\nconst UNBIASED_LIMIT = Math.floor(2 ** 32 / 100_000_000) * 100_000_000;\n\n/** `cNF`: eight random digits, never equal to the number's own eight (the layout's rule). */\nexport function drawKeyCode(number: number): string {\n const own = String(number % 100_000_000).padStart(8, \"0\");\n for (;;) {\n const [value] = globalThis.crypto.getRandomValues(new Uint32Array(1));\n // Rejection sampling: values at or above the last whole multiple of 10^8 would bias the low codes.\n if (value === undefined || value >= UNBIASED_LIMIT) continue;\n const code = String(value % 100_000_000).padStart(8, \"0\");\n if (code !== own) return code;\n }\n}\n\nconst FILLED_BY_THE_PACKAGE = new Set([\"series\", \"number\", \"keyCode\", \"issuer\", \"issuedAt\"]);\n\n/** A stored sale back to the draft it was built from (for a second document of the same sale). */\nexport function draftOf(sale: SaleForDocument): SaleDraft {\n return Object.fromEntries(Object.entries(sale).filter(([key]) => !FILLED_BY_THE_PACKAGE.has(key))) as unknown as SaleDraft;\n}\n\nexport function issuerOf(profile: EmitterProfile): DocumentIssuer {\n return {\n cnpj: profile.cnpj,\n stateRegistration: profile.stateRegistration,\n legalName: profile.legalName,\n tradeName: profile.tradeName,\n taxRegime: profile.taxRegime,\n address: profile.address,\n };\n}\n\nexport function totalsOf(sale: SaleDraft): DocumentTotals {\n const sum = (pick: (line: SaleDraft[\"lines\"][number]) => number) => sale.lines.reduce((total, line) => total + pick(line), 0);\n const discountCents = sum((line) => line.discountCents);\n return {\n totalCents: sum((line) => line.valueCents) - discountCents,\n discountCents,\n cbsCents: sum((line) => line.ibsCbs?.figures?.cbsCents ?? 0),\n ibsUfCents: sum((line) => line.ibsCbs?.figures?.ibsUfCents ?? 0),\n ibsMunCents: sum((line) => line.ibsCbs?.figures?.ibsMunCents ?? 0),\n };\n}\n\n/** `text` without any trailing run of `char`, in linear time (no regex backtracking). */\nexport function trimEnd(text: string, char: string): string {\n let end = text.length;\n while (end > 0 && text[end - 1] === char) end -= 1;\n return text.slice(0, end);\n}\n\n/** Storage keys, by access key: one folder per document, whatever its owner. */\nexport const xmlKeys = {\n signed: (accessKey: string) => `fiscal/${accessKey}/signed.xml`,\n /** One signed XML per digest: every XML a failed call returned under a key is kept, none overwritten. */\n signedByDigest: (accessKey: string, digest: string) =>\n `fiscal/${accessKey}/signed-${trimEnd(digest.replace(/\\+/g, \"-\").replace(/\\//g, \"_\"), \"=\")}.xml`,\n authorized: (accessKey: string) => `fiscal/${accessKey}/authorized.xml`,\n cancel: (accessKey: string) => `fiscal/${accessKey}/cancel.xml`,\n /** The event 110300 of `nSeqEvento` `sequence`. */\n linkPayment: (accessKey: string, sequence: number) => `fiscal/${accessKey}/link-payment-${sequence}.xml`,\n inutilization: (document: FiscalDocument) =>\n `fiscal/inutilization/${document.environment}/${document.model}/${document.ownerId}/${document.series}-${document.number}.xml`,\n};\n\n/** The IBGE code of each federative unit: the access key's first two digits. */\nconst UF_CODES: Readonly<Record<Uf, string>> = {\n RO: \"11\", AC: \"12\", AM: \"13\", RR: \"14\", PA: \"15\", AP: \"16\", TO: \"17\", MA: \"21\", PI: \"22\", CE: \"23\", RN: \"24\", PB: \"25\",\n PE: \"26\", AL: \"27\", SE: \"28\", BA: \"29\", MG: \"31\", ES: \"32\", RJ: \"33\", SP: \"35\", PR: \"41\", SC: \"42\", RS: \"43\", MS: \"50\",\n MT: \"51\", GO: \"52\", DF: \"53\",\n};\n\n/** The access key's modulo-11 check digit (weights 2–9 from the right). */\nfunction keyCheckDigit(body: string): number {\n let sum = 0;\n let weight = 2;\n for (let i = body.length - 1; i >= 0; i -= 1) {\n sum += (body.charCodeAt(i) - 48) * weight;\n weight = weight === 9 ? 2 : weight + 1;\n }\n const rest = sum % 11;\n return rest < 2 ? 0 : 11 - rest;\n}\n\n/** cUF and AAMM, the issuer's CNPJ (alphanumeric from July 2026), then model to `cDV`, all digits. */\nconst ACCESS_KEY_SHAPE = /^[0-9]{6}[0-9A-Z]{12}[0-9]{26}$/;\n/** `NFref` occurs at most 500 times. */\nconst MAX_REFERENCED_DOCUMENTS = 500;\n\n/**\n * Whether `key` is an access key as the layout writes one: 44 characters, the\n * CNPJ inside it alphanumeric or not, and its modulo-11 check digit right.\n */\nexport function isValidAccessKey(key: string): boolean {\n if (!ACCESS_KEY_SHAPE.test(key)) return false;\n return keyCheckDigit(key.slice(0, 43)) === Number(key.slice(43));\n}\n\n/**\n * Refuses a sale the model cannot carry, before a number is drawn: a return on\n * an NFC-e, an NFC-e of entry, an NFC-e quoting another document (SEFAZ\n * rejects `NFref` on a model 65 with 708, and the number would be burned), a\n * return quoting nothing, or a reference that is not an access key. A document without `operation` and\n * `referencedDocuments` passes as it always did.\n */\nexport function assertDraftFits(draft: Pick<SaleDraft, \"purpose\" | \"operation\" | \"referencedDocuments\">, model: FiscalDocumentModel): void {\n const references = draft.referencedDocuments ?? [];\n if (model === \"NFCE\") assertNfceDraftFits(draft, references.length);\n if (draft.purpose === \"RETURN\" && references.length === 0) {\n throw new FiscalDocumentError(\"RETURN_NEEDS_REFERENCE\", \"a return must reference the document it returns (referencedDocuments).\");\n }\n if (references.length > MAX_REFERENCED_DOCUMENTS) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `at most ${MAX_REFERENCED_DOCUMENTS} referenced documents, not ${references.length}.`);\n }\n const bad = references.findIndex((reference) => !isValidAccessKey(reference.accessKey));\n if (bad !== -1) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `referencedDocuments[${bad}].accessKey is not a 44-character access key.`);\n }\n}\n\n/** The NFC-e half of `assertDraftFits`: no return, no entry, no reference. */\nfunction assertNfceDraftFits(draft: Pick<SaleDraft, \"purpose\" | \"operation\">, referenceCount: number): void {\n if (draft.purpose === \"RETURN\") {\n throw new FiscalDocumentError(\"RETURN_ON_NFCE\", \"an NFC-e has no return purpose: issue an NF-e (model 55) of entry referencing it.\");\n }\n if (draft.operation === \"IN\") {\n throw new FiscalDocumentError(\"INVALID_INPUT\", 'an NFC-e is an outgoing document: operation must be \"OUT\".');\n }\n if (referenceCount > 0) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", \"an NFC-e references no document (SEFAZ 708): referencedDocuments must be empty.\");\n }\n}\n\n/**\n * The 44-character access key a document will carry, computed as the layout\n * does: cUF, AAMM of `dhEmi`, CNPJ, model, series, number, `tpEmis` (1 online,\n * 9 offline NFC-e), `cNF` and the check digit. The package knows a document's\n * key before any call, so an unanswered send can always be looked up.\n */\nexport function computeAccessKey(input: {\n readonly sale: Pick<SaleForDocument, \"issuer\" | \"issuedAt\" | \"series\" | \"number\" | \"keyCode\">;\n readonly model: FiscalDocumentModel;\n readonly seriesKind: SeriesKind;\n}): string {\n const { sale } = input;\n const body = [\n UF_CODES[sale.issuer.address.uf],\n sale.issuedAt.slice(2, 4),\n sale.issuedAt.slice(5, 7),\n sale.issuer.cnpj,\n input.model === \"NFE\" ? \"55\" : \"65\",\n String(sale.series).padStart(3, \"0\"),\n String(sale.number).padStart(9, \"0\"),\n input.seriesKind === \"CONTINGENCY\" ? \"9\" : \"1\",\n sale.keyCode,\n ].join(\"\");\n return `${body}${keyCheckDigit(body)}`;\n}\n\n","/**\n * What every step of the document service shares: the ports, the clock, the\n * host's words written into a document, and the two writes everything goes\n * through — numbering a new document, and persisting one transition with the\n * schedule and the person's flag it implies.\n */\n\nimport type { Issuer, SigningMaterial } from \"../issuer/port\";\nimport { FISCAL_ISSUE } from \"../manifest/permissions\";\nimport { FiscalDocumentError } from \"./errors\";\nimport { computeAccessKey, drawKeyCode, issuerOf, localIso, totalsOf } from \"./helpers\";\nimport { type DocumentInput, type Transition, transition } from \"./machine\";\nimport type { DocumentStorage, FiscalStore, SaleDraft, SaleSource } from \"./ports\";\nimport type { EmitterProfile, IssuingPoint } from \"./profile\";\nimport type { SigningIdentities } from \"./signing\";\nimport { type FiscalDocument, type FiscalDocumentModel, OWED_VOIDS, type SeriesKind } from \"./types\";\n\nexport { assertDraftFits, computeAccessKey, draftOf, drawKeyCode, isValidAccessKey, issuerOf, localIso, totalsOf, xmlKeys } from \"./helpers\";\n\n/** Twin of `@12-apps/wiring/ports`' `NotifyPort`: never throws. */\nexport interface FiscalNotifyPort {\n emit(event: {\n readonly type: string;\n readonly recipient: { readonly tenantId: string; readonly permission: string };\n readonly payload: unknown;\n }): Promise<unknown>;\n}\n\n/**\n * The words SEFAZ receives in a document, an event or a request — the host's,\n * in the host's language, 15 to 255 characters each. No default: a library\n * that wrote them would be writing a fiscal statement for its host.\n */\nexport interface FiscalReasons {\n /** `xJust` of a document signed offline. */\n readonly contingency: string;\n /** Why an unused number is inutilized. */\n readonly inutilization: string;\n /** Why a document found authorised after its sale moved to contingency is cancelled. */\n readonly substitution: string;\n}\n\nexport interface FiscalDocumentsConfig {\n readonly store: FiscalStore;\n readonly issuer: Issuer;\n readonly signing: SigningIdentities;\n readonly storage: DocumentStorage;\n readonly sales: SaleSource;\n readonly notify: FiscalNotifyPort;\n readonly now: () => Date;\n /** The owner's UTC offset at an instant (`-03:00`): `dhEmi` and `dhCont` are local times. */\n readonly utcOffset: (ownerId: string, at: Date) => string | Promise<string>;\n readonly reasons: FiscalReasons;\n /**\n * How long a document owing a step waits before the sweep takes it again,\n * the base of the backoff: each failure in a row doubles it, up to 64×.\n */\n readonly staleAfterMs: number;\n /**\n * How late an online NFC-e may still be sent with its `dhEmi`. SEFAZ refuses\n * a late one (704, \"data-hora de emissão atrasada\"; five minutes in most\n * states — the host's, per state). Past it, a stale online NFC-e at a point\n * with a contingency series goes offline instead of being sent again.\n */\n readonly nfceOnlineToleranceMs: number;\n /** Ids for new documents. */\n readonly newId: () => string;\n}\n\nexport const FISCAL_DOCUMENT_REJECTED = \"fiscal.document-rejected\";\nexport const FISCAL_CERTIFICATE_EXPIRING = \"fiscal.certificate-expiring\";\nexport const FISCAL_DOCUMENT_NEEDS_ATTENTION = \"fiscal.document-needs-attention\";\nexport const FISCAL_CONTINGENCY_DEADLINE = \"fiscal.contingency-deadline\";\n\nconst REQUIRED_PORTS = [\"store\", \"issuer\", \"signing\", \"storage\", \"sales\", \"notify\"] as const;\nconst REQUIRED_FUNCTIONS = [\"now\", \"utcOffset\", \"newId\"] as const;\nconst REASONS = [\"contingency\", \"inutilization\", \"substitution\"] as const;\nconst DURATIONS = [\"staleAfterMs\", \"nfceOnlineToleranceMs\"] as const;\n\nexport function assertConfig(config: FiscalDocumentsConfig): void {\n const missing = [\n ...REQUIRED_PORTS.filter((port) => config?.[port] === undefined || config[port] === null),\n ...REQUIRED_FUNCTIONS.filter((fn) => typeof config?.[fn] !== \"function\"),\n ...DURATIONS.filter((name) => !Number.isInteger(config?.[name]) || config[name] <= 0),\n ];\n if (missing.length > 0) throw new TypeError(`createFiscalDocuments needs ${missing.join(\", \")}.`);\n for (const name of REASONS) assertReason(config.reasons?.[name], `reasons.${name}`);\n}\n\nexport function assertReason(text: unknown, name: string): asserts text is string {\n if (typeof text !== \"string\" || text.trim().length < 15 || text.length > 255) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `${name} must be 15 to 255 characters.`);\n }\n}\n\n/** The backoff never grows past 64 × `staleAfterMs`. */\nconst MAX_BACKOFF_DOUBLINGS = 6;\n\n/** Whether a document still owes the sweep (or the transmission) a call. */\nfunction owesWork(document: FiscalDocument): boolean {\n if (document.status === \"PENDING\" || document.status === \"SUBMITTED\" || document.status === \"CONTINGENCY\") return true;\n return document.numberVoid !== null && OWED_VOIDS.includes(document.numberVoid);\n}\n\nexport class FiscalContext {\n constructor(readonly config: FiscalDocumentsConfig) {}\n\n nowIso(): string {\n return this.config.now().toISOString();\n }\n\n async localNow(ownerId: string): Promise<string> {\n const at = this.config.now();\n return localIso(at, await this.config.utcOffset(ownerId, at));\n }\n\n /** When a document may be taken again: never, when nothing is owed or a person must look. */\n nextAttemptAt(document: FiscalDocument): string | null {\n if (document.attention || !owesWork(document)) return null;\n const wait = this.config.staleAfterMs * 2 ** Math.min(document.failures, MAX_BACKOFF_DOUBLINGS);\n return new Date(this.config.now().getTime() + wait).toISOString();\n }\n\n /** The machine's step, scheduled. */\n scheduled(document: FiscalDocument, input: DocumentInput): Transition {\n const step = transition(document, input, this.nowIso());\n return { ...step, document: { ...step.document, nextAttemptAt: this.nextAttemptAt(step.document) } };\n }\n\n /**\n * Persist one transition; a lost race is a `CONFLICT`, never a silent\n * overwrite. A document that has just come to need a person is announced.\n */\n async advance(document: FiscalDocument, input: DocumentInput): Promise<FiscalDocument> {\n const step = this.scheduled(document, input);\n if (!(await this.config.store.saveTransition(document, step))) {\n throw new FiscalDocumentError(\"CONFLICT\", `document ${document.id} moved while ${input.kind} was applied.`);\n }\n if (step.document.attention && !document.attention) await this.announceAttention(step.document);\n return step.document;\n }\n\n async announceAttention(document: FiscalDocument): Promise<void> {\n await this.config.notify.emit({\n type: FISCAL_DOCUMENT_NEEDS_ATTENTION,\n recipient: { tenantId: document.ownerId, permission: FISCAL_ISSUE },\n payload: {\n documentId: document.id,\n subjectId: document.subjectId,\n model: document.model,\n status: document.status,\n numberVoid: document.numberVoid,\n series: document.series,\n number: document.number,\n code: document.statusCode,\n reason: document.statusReason ?? \"\",\n failures: document.failures,\n },\n });\n }\n\n material(profile: EmitterProfile): Promise<SigningMaterial> {\n return this.config.signing[profile.signingIdentity].materialFor(profile);\n }\n\n async requireProfile(ownerId: string): Promise<EmitterProfile> {\n const profile = await this.config.store.getProfile(ownerId);\n if (profile === null) throw new FiscalDocumentError(\"NOT_FOUND\", `owner ${ownerId} has no emitter profile.`);\n return profile;\n }\n\n async requirePoint(ownerId: string, issuingPointId: string): Promise<IssuingPoint> {\n const point = await this.config.store.getIssuingPoint(ownerId, issuingPointId);\n if (point === null) throw new FiscalDocumentError(\"NOT_FOUND\", `owner ${ownerId} has no issuing point ${issuingPointId}.`);\n return point;\n }\n\n /**\n * Draw the next number of a series and store the PENDING document built on\n * it, together. With `replacing`, that document is REPLACED by this one in\n * the same transaction (going offline), so a crash leaves exactly one live.\n */\n async createNumbered(input: {\n readonly profile: EmitterProfile;\n readonly point: IssuingPoint;\n readonly subjectId: string;\n readonly model: FiscalDocumentModel;\n readonly seriesKind: SeriesKind;\n readonly draft: SaleDraft;\n readonly replacing?: FiscalDocument;\n }): Promise<FiscalDocument> {\n const { profile, point, draft } = input;\n const series = input.seriesKind === \"ONLINE\" ? point.onlineSeries : point.contingencySeries;\n if (series === null) throw new FiscalDocumentError(\"INVALID_INPUT\", `issuing point ${point.id} has no contingency series.`);\n const issuedAt = await this.localNow(profile.ownerId);\n const at = this.nowIso();\n const id = this.config.newId();\n const replace =\n input.replacing === undefined\n ? undefined\n : { previous: input.replacing, transition: this.scheduled(input.replacing, { kind: \"REPLACE\", replacedById: id }) };\n const request = {\n ownerId: profile.ownerId,\n issuerCnpj: profile.cnpj,\n issuingPointId: point.id,\n environment: profile.environment,\n model: input.model,\n seriesKind: input.seriesKind,\n series,\n };\n return this.config.store.createDocument(\n request,\n (number) => {\n const keyCode = drawKeyCode(number);\n const sale = { ...draft, series, number, keyCode, issuedAt, issuer: issuerOf(profile) };\n return {\n id,\n ownerId: profile.ownerId,\n issuerCnpj: profile.cnpj,\n subjectId: input.subjectId,\n issuingPointId: point.id,\n model: input.model,\n environment: profile.environment,\n seriesKind: input.seriesKind,\n series,\n number,\n keyCode,\n status: \"PENDING\",\n sale,\n totals: totalsOf(draft),\n buyerTaxId: draft.buyer?.document.number ?? null,\n accessKey: computeAccessKey({ sale, model: input.model, seriesKind: input.seriesKind }),\n protocol: null,\n statusCode: null,\n statusReason: null,\n lastErrorClass: null,\n outcomeUnknown: false,\n issuedAt,\n authorizedAt: null,\n contingency: null,\n cancelledAt: null,\n cancelReason: null,\n cancelProtocol: null,\n replacedById: null,\n numberVoid: null,\n xmlKey: null,\n eventXmlKey: null,\n attempts: 0,\n failures: 0,\n nextAttemptAt: new Date(Date.parse(at) + this.config.staleAfterMs).toISOString(),\n attention: false,\n deadlineWarnedAt: null,\n createdAt: at,\n updatedAt: at,\n };\n },\n replace,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuBO,IAAM,eAAe;AAwDrB,SAAS,OAAO,UAA0B,MAAyB,KAAoB;AAC5F,QAAM,IAAI;AAAA,IACR;AAAA,IACA,GAAG,IAAI,2BAA2B,SAAS,EAAE,OAAO,SAAS,MAAM,KAAK,GAAG;AAAA,EAC7E;AACF;AALgB;AAQhB,IAAM,UAAU,EAAE,UAAU,GAAG,WAAW,MAAM;AAEhD,SAAS,aAAa,QAAwB,QAAyC;AACrF,SAAO;AAAA,IACL,GAAG;AAAA,IACH,WAAW,OAAO;AAAA,IAClB,UAAU,OAAO;AAAA,IACjB,cAAc,OAAO;AAAA,IACrB,YAAY,OAAO;AAAA,IACnB,cAAc,OAAO;AAAA,IACrB,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB;AAAA,EACF;AACF;AAZS;AAmBT,SAAS,aAAa,UAA0B,OAA8C;AAC5F,SAAO;AAAA,IACL,WAAW,SAAS,aAAa,MAAM;AAAA,IACvC,YAAY,MAAM;AAAA,IAClB,cAAc,MAAM;AAAA,IACpB,gBAAgB,MAAM;AAAA,IACtB,gBAAgB,SAAS,kBAAkB,MAAM;AAAA,EACnD;AACF;AARS;AAUT,SAAS,QAAQ,UAA0B,WAA6C;AACtF,QAAM,WAAW,SAAS,WAAW;AACrC,SAAO,EAAE,UAAU,WAAW,aAAa,YAAY,aAAa;AACtE;AAHS;AAMT,SAAS,gBAAgB,QAAsC;AAC7D,MAAI,OAAO,WAAW,aAAc,QAAO;AAC3C,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,MAAI,OAAO,WAAW,SAAU,QAAO;AACvC,SAAO;AACT;AALS;AAOT,SAAS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,iBAAiB,EAAE,MAAM,OAAO,MAAM,OAAO,YAAY,MAAM,WAAW,CAAC;AAAA,UACtF,UAAU;AAAA,UACV,YAAY;AAAA,UACZ,cAAc;AAAA,UACd,gBAAgB;AAAA,UAChB,gBAAgB;AAAA,UAChB;AAAA,UACA,cAAc;AAAA,UACd,aAAa;AAAA,UACb,aAAa;AAAA,UACb,cAAc;AAAA,UACd,gBAAgB;AAAA,UAChB,cAAc;AAAA,UACd,YAAY;AAAA,UACZ,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,UAAU;AAAA,UACV,UAAU;AAAA,UACV,eAAe,IAAI,KAAK,KAAK,MAAM,EAAE,IAAI,KAAK,OAAO,YAAY,EAAE,YAAY;AAAA,UAC/E,WAAW;AAAA,UACX,kBAAkB;AAAA,UAClB,WAAW;AAAA,UACX,WAAW;AAAA,QACb;AAAA,MACF;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  FISCAL_CERTIFICATE_EXPIRING
3
- } from "./chunk-GKT3X5CF.js";
3
+ } from "./chunk-3E3NBXSW.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-MEBG7FGG.js.map
85
+ //# sourceMappingURL=chunk-G6QNU4FD.js.map
@@ -27,4 +27,4 @@ export {
27
27
  OWED_VOIDS,
28
28
  isLive
29
29
  };
30
- //# sourceMappingURL=chunk-XQGW5HUG.js.map
30
+ //# sourceMappingURL=chunk-GH452ITO.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 | \"LINK_PAYMENT\";\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_DOCUMENT_MODELS
3
- } from "./chunk-XQGW5HUG.js";
3
+ } from "./chunk-GH452ITO.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-GGYJPFBJ.js.map
192
+ //# sourceMappingURL=chunk-HMTPJWXM.js.map
@@ -6,10 +6,10 @@ import {
6
6
  parseIssuingPointInput,
7
7
  parseProfileInput,
8
8
  viewOf
9
- } from "./chunk-GGYJPFBJ.js";
9
+ } from "./chunk-HMTPJWXM.js";
10
10
  import {
11
11
  FISCAL_DOCUMENT_MODELS
12
- } from "./chunk-XQGW5HUG.js";
12
+ } from "./chunk-GH452ITO.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-V6G2OFLA.js.map
213
+ //# sourceMappingURL=chunk-TJCUO6D6.js.map
@@ -11,4 +11,4 @@ var SIDECAR_ERROR_CLASSES = [
11
11
  export {
12
12
  SIDECAR_ERROR_CLASSES
13
13
  };
14
- //# sourceMappingURL=chunk-JVQKJNOC.js.map
14
+ //# sourceMappingURL=chunk-ZKWVKCGJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sidecar/types.ts"],"sourcesContent":["/**\n * The wire contract of the fiscal service (`sidecar/` in this package): a\n * stateless HTTP door in front of sped-nfe. JSON in, JSON out.\n *\n * Stateless means every call carries what it needs: the signing certificate\n * (an A1 `.pfx` as base64 and its password) and, for an NFC-e, the CSC. The\n * service keeps nothing between calls, writes nothing to disk and never logs\n * any of the three.\n */\n\nimport type { SaleForDocument } from \"../sale/types\";\n\n/** The path segment of a document model: `nfe` is model 55, `nfce` model 65. */\nexport type DocumentModelPath = \"nfe\" | \"nfce\";\n\n/** The SEFAZ environment (`tpAmb` 2 and 1). */\nexport type SefazEnvironment = \"homologacao\" | \"producao\";\n\n/** The A1 certificate, per call. */\nexport interface SigningCertificate {\n /** The `.pfx` (PKCS#12) bytes, base64. */\n readonly pfxBase64: string;\n readonly password: string;\n}\n\n/** The NFC-e's Código de Segurança do Contribuinte and its id. */\nexport interface Csc {\n readonly id: string;\n readonly token: string;\n}\n\ninterface Authenticated {\n readonly environment: SefazEnvironment;\n readonly certificate: SigningCertificate;\n}\n\n/**\n * `POST /<model>/issue`: builds, signs and transmits. `csc` is required for\n * `nfce` and refused for `nfe`.\n */\nexport interface IssueRequest extends Authenticated {\n readonly csc: Csc | null;\n readonly document: SaleForDocument;\n}\n\n/** Why and since when the caixa issues offline (`dhCont`, `xJust`). */\nexport interface ContingencyEntry {\n /** ISO 8601 with the UTC offset. */\n readonly since: string;\n /** 15–256 characters. */\n readonly reason: string;\n}\n\n/** `POST /nfce/sign-contingency`: builds and signs with `tpEmis = 9`; does NOT transmit. */\nexport interface SignContingencyRequest extends IssueRequest {\n readonly contingency: ContingencyEntry;\n}\n\n/** `POST /<model>/transmit`: an already signed XML (from `/nfce/sign-contingency`, say). */\nexport interface TransmitRequest extends Authenticated {\n readonly signedXml: string;\n}\n\n/** `POST /<model>/cancel`: the UF and the issuer come from the access key. */\nexport interface CancelRequest extends Authenticated {\n readonly accessKey: string;\n /** The authorisation protocol (`nProt`). */\n readonly protocol: string;\n /** 15–255 characters. */\n readonly reason: string;\n}\n\n/**\n * `POST /nfce/cancel-substitution`: the NFC-e \"cancelamento por substituição\"\n * (event 110112) — an online NFC-e found authorised after its sale was issued\n * again in contingency, cancelled naming the substitute. Answers as `/cancel`.\n */\nexport interface CancelBySubstitutionRequest extends CancelRequest {\n /** The contingency document that replaced it (`chNFeRef`). */\n readonly substituteAccessKey: string;\n}\n\n/** `POST /<model>/link-payment`: the event 110300 for one transaction (NT 2026.006 v1.00). */\nexport interface LinkPaymentRequest extends Authenticated {\n readonly accessKey: string;\n /** The authorisation protocol (`nProt`). */\n readonly protocol: string;\n /** `nSeqEvento`, 1–20: this document's how-manieth 110300. */\n readonly sequence: number;\n /** Exactly one entry: the event's schema carries a single `gPgto`. */\n readonly payments: ReadonlyArray<{\n readonly transactionId: string;\n readonly meansCode: string;\n readonly pspCnpjBase: string;\n readonly receiverCnpj: string;\n }>;\n}\n\n/** `POST /<model>/lookup`. */\nexport interface LookupRequest extends Authenticated {\n readonly accessKey: string;\n}\n\n/** `POST /inutilize`: voids a range of unused numbers. */\nexport interface InutilizeRequest extends Authenticated {\n readonly model: DocumentModelPath;\n readonly uf: string;\n readonly cnpj: string;\n /** The year of the numbers, four digits. */\n readonly year: number;\n readonly series: number;\n readonly from: number;\n readonly to: number;\n /** 15–255 characters. */\n readonly reason: string;\n}\n\n/** What SEFAZ answered, as the service read it. */\nexport interface SefazAnswer {\n /** `cStat`. */\n readonly statusCode: string;\n /** `xMotivo`. */\n readonly statusReason: string;\n /** The SOAP body SEFAZ returned, verbatim. */\n readonly sefazReply: string;\n}\n\n/**\n * `/issue` and `/transmit`: SEFAZ's final answer on the document.\n *\n * - `AUTHORIZED` (100, 120, 150).\n * - `DENIED` (110, 301, 302, 303): a denial of use. The number is SPENT and\n * the denial is kept like an authorisation (its `authorizedXml` carries the\n * denial protocol); it is not a rejection, which leaves the number free.\n *\n * A retried call answers the same: SEFAZ's \"already authorised\" (204) and\n * \"already denied\" (205), and a request sent with no answer, are settled by\n * looking the key up, so a retry never turns an authorised document into an error.\n */\nexport interface IssuedDocument extends SefazAnswer {\n readonly status: \"AUTHORIZED\" | \"DENIED\";\n readonly accessKey: string;\n readonly protocol: string;\n /** `dhRecbto` of the protocol. */\n readonly authorizedAt: string;\n readonly signedXml: string;\n /** The `nfeProc`: the signed XML with its protocol (of authorisation or of denial), what is stored. */\n readonly authorizedXml: string;\n}\n\n/** `/nfce/sign-contingency`. */\nexport interface ContingencySignedDocument {\n readonly status: \"SIGNED\";\n readonly accessKey: string;\n /** Carries `tpEmis = 9` and the QR code; transmit it later through `/nfce/transmit`. */\n readonly signedXml: string;\n}\n\n/**\n * `/cancel`. A retried cancel (SEFAZ's 218 \"already cancelled\" or 573\n * \"duplicate event\", or a cancel sent with no answer) is settled by looking\n * the key up, and answers CANCELLED with what the lookup carries: the event's\n * protocol and XML when SEFAZ returns them, `null` when it does not.\n */\nexport interface CancelledDocument extends SefazAnswer {\n readonly status: \"CANCELLED\";\n readonly accessKey: string;\n /** The event's protocol. */\n readonly protocol: string | null;\n readonly registeredAt: string | null;\n /** The `procEventoNFe`. */\n readonly eventXml: string | null;\n}\n\n/**\n * `/link-payment`: the event registered. On 573 \"Duplicidade de Evento\" the\n * service looks the key up and answers the event SEFAZ already holds at that\n * `nSeqEvento`, with its own XML and the transaction it carries — which may be\n * another transaction than the one sent (`statusCode` \"573\" tells the two apart).\n */\nexport interface RegisteredPaymentLink extends SefazAnswer {\n readonly status: \"REGISTERED\";\n readonly accessKey: string;\n readonly protocol: string | null;\n readonly registeredAt: string | null;\n /** The `procEventoNFe`. */\n readonly eventXml: string | null;\n /** The `gPgto` SEFAZ registered at this `nSeqEvento`. */\n readonly transaction: {\n readonly transactionId: string;\n readonly meansCode: string;\n readonly pspCnpjBase: string;\n readonly receiverCnpj: string;\n };\n}\n\n/** `/lookup`: what SEFAZ knows of the key. `NOT_FOUND` is an answer, not an error. */\nexport interface LookedUpDocument extends SefazAnswer {\n readonly status: \"AUTHORIZED\" | \"CANCELLED\" | \"DENIED\" | \"NOT_FOUND\";\n readonly accessKey: string;\n readonly protocol: string | null;\n}\n\n/**\n * `/inutilize`. A retried inutilização (563, \"a request for the same range\n * already exists\") answers INUTILIZED too, with `protocol` and\n * `inutilizationXml` `null`: the range is void at SEFAZ, and SEFAZ offers no\n * query that would return the first protocol.\n */\nexport interface InutilizedRange extends SefazAnswer {\n readonly status: \"INUTILIZED\";\n readonly protocol: string | null;\n readonly registeredAt: string | null;\n /** The signed request with its reply (`procInutNFe`). */\n readonly inutilizationXml: string | null;\n}\n\n/**\n * How a failed call is classified — the issuer port's own classes:\n *\n * - `REJECTED`: SEFAZ refused the document or the event; `code` is its `cStat`.\n * The number is NOT spent (a denial is not an error: it answers `DENIED`).\n * - `RETRYABLE`: try the same call again later. When `outcomeUnknown` is true\n * the request went out and neither it nor the lookup that would settle it\n * was answered: look the key up before sending it again.\n * - `CONTINGENCY`: SEFAZ is unavailable. For an NFC-e being issued, nothing\n * reached SEFAZ (or the lookup after an unanswered request could not reach\n * it): go offline through `/nfce/sign-contingency`. For an NF-e (model 55)\n * the service has no offline path (no SVC, no EPEC): treat it as RETRYABLE.\n * - `AUTH`: the certificate is unreadable, the password wrong, the certificate\n * expired, or SEFAZ refused it.\n * - `INVALID`: the request itself is malformed (the schema, a missing CSC, an\n * XML the layout refuses, a document the layout version cannot express).\n * Fix the input; never retry it as is.\n * - `INTERNAL`: a defect of the service, or a 4xx other than 403/408/429 from\n * the verified SEFAZ host (a wrong web-service address). A retry would only repeat it.\n */\nexport type SidecarErrorClass = \"REJECTED\" | \"RETRYABLE\" | \"CONTINGENCY\" | \"AUTH\" | \"INVALID\" | \"INTERNAL\";\n\nexport const SIDECAR_ERROR_CLASSES: readonly SidecarErrorClass[] = [\n \"REJECTED\",\n \"RETRYABLE\",\n \"CONTINGENCY\",\n \"AUTH\",\n \"INVALID\",\n \"INTERNAL\",\n];\n\n/** The body of every non-2xx answer. */\nexport interface SidecarErrorBody {\n readonly error: {\n readonly class: SidecarErrorClass;\n /**\n * The SEFAZ `cStat` when SEFAZ answered (always for `REJECTED`); for\n * `INVALID`, a named code where one applies (`NT_2026_008_NOT_SUPPORTED`:\n * a document issued on or after 2027-01-01, which needs NT 2026.008's\n * `vProdLiq`; `RETURN_ON_NFCE`: a return asked of an NFC-e, which has no\n * return purpose; `RETURN_NEEDS_REFERENCE`: a return quoting no\n * `referencedDocuments`); `null` otherwise.\n */\n readonly code: string | null;\n readonly message: string;\n /** Per-field problems of an `INVALID` request. */\n readonly details: readonly string[];\n /** When the call got as far as building and signing: keep it, the key is now spoken for. */\n readonly accessKey: string | null;\n readonly signedXml: string | null;\n readonly sefazReply: string | null;\n /** The request went out and its outcome is still unknown: look the key up before sending it again. */\n readonly outcomeUnknown: boolean;\n };\n}\n\n/** `GET /health`. */\nexport interface SidecarHealth {\n readonly status: \"ok\";\n /** The libraries the service runs, by name, with the version installed. */\n readonly libraries: Readonly<Record<string, string>>;\n /** The schema package the NF-e layout is validated against. */\n readonly nfeSchemas: string;\n /** Whether SEFAZ's server certificate is verified; `false` only with `FISCAL_SEFAZ_TLS_VERIFY=off`. */\n readonly sefazTlsVerify: boolean;\n}\n"],"mappings":";AA+OO,IAAM,wBAAsD;AAAA,EACjE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
- import { F as FiscalDocumentModel, k as DocumentTotals, D as DocumentEventKind, g as FiscalDocumentStatus, h as FiscalDocument, i as FiscalDocumentEvent, j as SeriesKind, f as SigningMaterial, I as Issuer } from './port-B1-ipIL4.js';
2
- import { IssuerTaxRegime, Address, SaleForDocument } from './sale/index.js';
3
- import { SefazEnvironment, IssuedDocument, SidecarErrorBody, ContingencySignedDocument, ContingencyEntry, CancelledDocument, LookedUpDocument, InutilizedRange } from './sidecar/index.js';
1
+ import { F as FiscalDocumentModel, o as DocumentTotals, D as DocumentEventKind, h as FiscalDocumentStatus, i as FiscalDocument, l as FiscalDocumentEvent, n as SeriesKind, g as SigningMaterial, I as Issuer } from './types-DSYwap42.js';
2
+ import { IssuerTaxRegime, Address, SaleForDocument, LinkedTransaction } from './sale/index.js';
3
+ import { SefazEnvironment, IssuedDocument, SidecarErrorBody, ContingencySignedDocument, ContingencyEntry, CancelledDocument, LookedUpDocument, InutilizedRange, RegisteredPaymentLink } from './sidecar/index.js';
4
4
  import { T as TaxRegime } from './types-B1b8LIWX.js';
5
5
 
6
6
  /**
@@ -171,6 +171,14 @@ type DocumentInput = {
171
171
  /** The 24-hour contingency deadline warning went out. */
172
172
  | {
173
173
  readonly kind: "WARN";
174
+ }
175
+ /** SEFAZ registered the event 110300 #`sequence` linking `payment` to the document; its XML is at `eventXmlKey`. */
176
+ | {
177
+ readonly kind: "LINK_PAYMENT";
178
+ readonly answer: RegisteredPaymentLink;
179
+ readonly payment: LinkedTransaction;
180
+ readonly sequence: number;
181
+ readonly eventXmlKey: string | null;
174
182
  };
175
183
 
176
184
  /**
@@ -196,6 +204,9 @@ type DocumentInput = {
196
204
  * final state. A rejected contingency NFC-e is the one way back: the store
197
205
  * corrects it and it is signed again under the same number (`RESIGN`).
198
206
  *
207
+ * `LINK_PAYMENT` records an event 110300 SEFAZ registered on an authorised
208
+ * document (a payment transaction linked after the fact); it changes nothing.
209
+ *
199
210
  * `DEFER`, `RELEASE` and `WARN` record what the sweep and a person did without
200
211
  * changing the state: a failed step counts toward {@link MAX_FAILURES}, after
201
212
  * which the document waits for a person (`attention`).
@@ -1,8 +1,8 @@
1
- import { F as FiscalDocumentModel, j as SeriesKind, h as FiscalDocument, i as FiscalDocumentEvent } from '../port-B1-ipIL4.js';
2
- export { D as DocumentEventKind, k as DocumentTotals, l as FISCAL_DOCUMENT_MODELS, n as FISCAL_DOCUMENT_STATUSES, g as FiscalDocumentStatus, N as NumberVoid, O as OWED_VOIDS, o as isLive } from '../port-B1-ipIL4.js';
3
- import { h as SaleDraft, F as FiscalStore } from '../context-yc1C2__K.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-yc1C2__K.js';
5
- export { C as CONTINGENCY_WARNING_AFTER_MS, a as CancelOrReturnInput, b as CancelOrReturnResult, c as CertificateFacts, d as CertificateUpload, E as EmitterProfileInput, F as FiscalDocuments, e as FiscalDocumentsServiceConfig, I as IssueInput, f as IssuingPointInput, L as LATE_CANCEL_CODES, S as SweepReport, g as createFiscalDocuments, p as parseCertificateUpload, h as parseIssuingPointInput, i as parseProfileInput } from '../service-BB9lWdyg.js';
1
+ import { F as FiscalDocumentModel, n as SeriesKind, i as FiscalDocument, l as FiscalDocumentEvent } from '../types-DSYwap42.js';
2
+ export { j as CancelOrReturnInput, k as CancelOrReturnResult, D as DocumentEventKind, o as DocumentTotals, p as FISCAL_DOCUMENT_MODELS, q as FISCAL_DOCUMENT_STATUSES, h as FiscalDocumentStatus, N as NumberVoid, O as OWED_VOIDS, r as isLive } from '../types-DSYwap42.js';
3
+ import { h as SaleDraft, F as FiscalStore } from '../context-CwZiHLnY.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-CwZiHLnY.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, e as LinkPaymentInput, f as LinkPaymentResult, M as MAX_PAYMENT_LINKS, S as SweepReport, g as createFiscalDocuments, p as parseCertificateUpload, h as parseIssuingPointInput, i as parseProfileInput } from '../service-Cz2O84Xr.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';
@@ -74,6 +74,8 @@ declare const xmlKeys: {
74
74
  signedByDigest: (accessKey: string, digest: string) => string;
75
75
  authorized: (accessKey: string) => string;
76
76
  cancel: (accessKey: string) => string;
77
+ /** The event 110300 of `nSeqEvento` `sequence`. */
78
+ linkPayment: (accessKey: string, sequence: number) => string;
77
79
  inutilization: (document: FiscalDocument) => string;
78
80
  };
79
81
  /**
@@ -5,7 +5,7 @@ import {
5
5
  parseIssuingPointInput,
6
6
  parseProfileInput,
7
7
  viewOf
8
- } from "../chunk-GGYJPFBJ.js";
8
+ } from "../chunk-HMTPJWXM.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-GKT3X5CF.js";
35
+ } from "../chunk-3E3NBXSW.js";
36
36
  import {
37
37
  FISCAL_DOCUMENT_MODELS,
38
38
  FISCAL_DOCUMENT_STATUSES,
39
39
  OWED_VOIDS,
40
40
  isLive
41
- } from "../chunk-XQGW5HUG.js";
41
+ } from "../chunk-GH452ITO.js";
42
42
  import {
43
43
  FISCAL_ISSUE
44
44
  } from "../chunk-3SDXLSG4.js";
@@ -259,6 +259,92 @@ async function settleNumber(ctx, document, profile, signing) {
259
259
  }
260
260
  __name(settleNumber, "settleNumber");
261
261
 
262
+ // src/documents/payment-link.ts
263
+ var MAX_PAYMENT_LINKS = 20;
264
+ function linkedByEvents(events) {
265
+ return events.filter((event) => event.kind === "LINK_PAYMENT").map((event, index) => {
266
+ const answer = event.answer;
267
+ return {
268
+ transactionId: answer?.payment?.transactionId,
269
+ sequence: typeof answer?.sequence === "number" ? answer.sequence : index + 1
270
+ };
271
+ }).filter((link) => typeof link.transactionId === "string");
272
+ }
273
+ __name(linkedByEvents, "linkedByEvents");
274
+ function linkedInDocument(document) {
275
+ return document.sale.payments.map((payment) => payment.linkedTransaction?.transactionId).filter((id) => typeof id === "string");
276
+ }
277
+ __name(linkedInDocument, "linkedInDocument");
278
+ function linkable(deps, document) {
279
+ const { accessKey, protocol } = document;
280
+ if (document.status !== "AUTHORIZED" || accessKey === null || protocol === null) {
281
+ throw new FiscalDocumentError("TRANSITION_REFUSED", `document ${document.id} is ${document.status}; only an authorised document is linked.`);
282
+ }
283
+ const send2 = deps.config.issuer.linkPayment;
284
+ if (typeof send2 !== "function") throw new FiscalDocumentError("NOT_SUPPORTED", "this issuer does not register the event 110300.");
285
+ return { accessKey, protocol, send: send2.bind(deps.config.issuer) };
286
+ }
287
+ __name(linkable, "linkable");
288
+ function heldTransaction(answer, sent, requested) {
289
+ if (answer.statusCode !== "573" || answer.transaction.transactionId === sent.transactionId) return sent;
290
+ const held = answer.transaction;
291
+ return requested.find((payment) => payment.transactionId === held.transactionId) ?? {
292
+ transactionId: held.transactionId,
293
+ meansCode: held.meansCode,
294
+ pspCnpjBase: held.pspCnpjBase,
295
+ receiverCnpj: held.receiverCnpj
296
+ };
297
+ }
298
+ __name(heldTransaction, "heldTransaction");
299
+ function refuseOverLimit(document) {
300
+ throw new FiscalDocumentError("INVALID_INPUT", `document ${document.id} cannot take more than ${MAX_PAYMENT_LINKS} payment links.`);
301
+ }
302
+ __name(refuseOverLimit, "refuseOverLimit");
303
+ async function sendOne(deps, run2, accessKey, payment) {
304
+ if (run2.sequence > MAX_PAYMENT_LINKS) refuseOverLimit(run2.document);
305
+ const sequence = run2.sequence;
306
+ const outcome = await run2.send(sequence, payment);
307
+ if (!outcome.ok) return outcome.error;
308
+ const held = heldTransaction(outcome.answer, payment, run2.requested);
309
+ const { eventXml } = outcome.answer;
310
+ const eventXmlKey = eventXml === null ? null : xmlKeys.linkPayment(accessKey, sequence);
311
+ if (eventXmlKey !== null && eventXml !== null) await deps.config.storage.put(eventXmlKey, eventXml, "application/xml");
312
+ run2.document = await deps.ctx.advance(run2.document, { kind: "LINK_PAYMENT", answer: outcome.answer, payment: held, sequence, eventXmlKey });
313
+ run2.known.add(held.transactionId);
314
+ if (run2.requested.some((one) => one.transactionId === held.transactionId)) run2.linked.push(held.transactionId);
315
+ run2.sequence = sequence + 1;
316
+ return held.transactionId === payment.transactionId ? null : sendOne(deps, run2, accessKey, payment);
317
+ }
318
+ __name(sendOne, "sendOne");
319
+ async function linkPayment(deps, input) {
320
+ const document = await deps.config.store.getDocument(input.ownerId, input.documentId);
321
+ if (document === null) throw new FiscalDocumentError("NOT_FOUND", `owner ${input.ownerId} has no document ${input.documentId}.`);
322
+ const { accessKey, protocol, send: send2 } = linkable(deps, document);
323
+ const byEvents = linkedByEvents(await deps.config.store.listEvents(document.id));
324
+ const known = /* @__PURE__ */ new Set([...linkedInDocument(document), ...byEvents.map((link) => link.transactionId)]);
325
+ const pending = input.payments.filter((payment) => !known.has(payment.transactionId));
326
+ const alreadyLinked = input.payments.filter((payment) => known.has(payment.transactionId)).map((payment) => payment.transactionId);
327
+ const sequence = Math.max(0, ...byEvents.map((link) => link.sequence)) + 1;
328
+ if (sequence - 1 + pending.length > MAX_PAYMENT_LINKS) refuseOverLimit(document);
329
+ if (pending.length === 0) return { linked: [], alreadyLinked, failure: null, document };
330
+ const signing = await deps.ctx.material(await deps.ctx.requireProfile(input.ownerId));
331
+ const run2 = {
332
+ document,
333
+ sequence,
334
+ known,
335
+ requested: pending,
336
+ linked: [],
337
+ send: /* @__PURE__ */ __name((at, payment) => send2({ model: document.model, environment: document.environment, signing, accessKey, protocol, sequence: at, payments: [payment] }), "send")
338
+ };
339
+ for (const payment of pending) {
340
+ if (run2.known.has(payment.transactionId)) continue;
341
+ const failure = await sendOne(deps, run2, accessKey, payment);
342
+ if (failure !== null) return { linked: run2.linked, alreadyLinked, failure, document: run2.document };
343
+ }
344
+ return { linked: run2.linked, alreadyLinked, failure: null, document: run2.document };
345
+ }
346
+ __name(linkPayment, "linkPayment");
347
+
262
348
  // src/documents/steps.ts
263
349
  var FINAL_FAILURES = /* @__PURE__ */ new Set(["REJECTED", "INVALID", "INTERNAL"]);
264
350
  async function reject(ctx, document, error) {
@@ -341,16 +427,59 @@ function staleOnline(ctx, document, point) {
341
427
  return !knownToSefaz && canGoOffline(document, point) && pastOnlineTolerance(ctx, document);
342
428
  }
343
429
  __name(staleOnline, "staleOnline");
344
- async function submit(ctx, document, profile, point, signing) {
430
+ function pastDeadline(document) {
431
+ return {
432
+ class: "CONTINGENCY",
433
+ code: null,
434
+ message: "SEFAZ did not answer before the online deadline.",
435
+ details: [],
436
+ accessKey: document.accessKey ?? computeAccessKey({ sale: document.sale, model: document.model, seriesKind: "ONLINE" }),
437
+ signedXml: null,
438
+ sefazReply: null,
439
+ outcomeUnknown: true
440
+ };
441
+ }
442
+ __name(pastDeadline, "pastDeadline");
443
+ async function sendBefore(send2, document, deadlineAt) {
444
+ send2.catch(() => void 0);
445
+ let timer;
446
+ const late = new Promise((resolve) => {
447
+ timer = setTimeout(() => resolve({ ok: false, error: pastDeadline(document) }), Math.max(0, deadlineAt - Date.now()));
448
+ });
449
+ try {
450
+ return await Promise.race([send2, late]);
451
+ } finally {
452
+ clearTimeout(timer);
453
+ }
454
+ }
455
+ __name(sendBefore, "sendBefore");
456
+ function send(ctx, document, signing, deadlineAt) {
457
+ const call = ctx.config.issuer.issue({ model: document.model, environment: document.environment, signing, document: document.sale });
458
+ return deadlineAt === null ? call : sendBefore(call, document, deadlineAt);
459
+ }
460
+ __name(send, "send");
461
+ function goesOffline(error, deadlineAt) {
462
+ return error.class === "CONTINGENCY" || deadlineAt !== null && error.class === "RETRYABLE";
463
+ }
464
+ __name(goesOffline, "goesOffline");
465
+ async function submit(ctx, document, profile, point, signing, deadlineAt = null) {
345
466
  if (staleOnline(ctx, document, point)) return goOffline(ctx, document, profile, point, signing);
346
467
  const sent = document.status === "PENDING" ? await ctx.advance(document, { kind: "SUBMIT" }) : document;
347
- const outcome = await ctx.config.issuer.issue({ model: sent.model, environment: sent.environment, signing, document: sent.sale });
468
+ const bounded = deadlineAt !== null && canGoOffline(sent, point) ? deadlineAt : null;
469
+ const outcome = await send(ctx, sent, signing, bounded);
348
470
  if (outcome.ok) return accept(ctx, sent, outcome.answer);
349
471
  if (FINAL_FAILURES.has(outcome.error.class)) return reject(ctx, sent, outcome.error);
350
472
  const retried = await ctx.advance(sent, { kind: "RETRY", error: outcome.error, ...await keepSigned(ctx, sent, outcome.error) });
351
- return outcome.error.class === "CONTINGENCY" && canGoOffline(retried, point) ? goOffline(ctx, retried, profile, point, signing) : retried;
473
+ return goesOffline(outcome.error, bounded) && canGoOffline(retried, point) ? goOffline(ctx, retried, profile, point, signing) : retried;
352
474
  }
353
475
  __name(submit, "submit");
476
+ async function offlineIfOverdue(ctx, document, profile, point, signing, onlineDeadlineMs) {
477
+ const waiting = document.status === "PENDING" || document.status === "SUBMITTED";
478
+ const overdue = ctx.config.now().getTime() - Date.parse(document.createdAt) >= onlineDeadlineMs;
479
+ if (!waiting || !overdue || document.protocol !== null || !canGoOffline(document, point)) return document;
480
+ return goOffline(ctx, document, profile, point, signing);
481
+ }
482
+ __name(offlineIfOverdue, "offlineIfOverdue");
354
483
  async function transmit(ctx, document, signing) {
355
484
  const signedXml = document.xmlKey === null ? null : await ctx.config.storage.get(document.xmlKey);
356
485
  if (signedXml === null) throw new FiscalDocumentError("NOT_FOUND", `document ${document.id} has no signed XML in storage.`);
@@ -360,6 +489,18 @@ async function transmit(ctx, document, signing) {
360
489
  return ctx.advance(document, { kind: "RETRY", error: outcome.error });
361
490
  }
362
491
  __name(transmit, "transmit");
492
+ async function answerLive(ctx, existing, profile, onlineDeadlineMs) {
493
+ if (onlineDeadlineMs === void 0 || existing.model !== "NFCE" || existing.seriesKind !== "ONLINE") return existing;
494
+ const point = await ctx.requirePoint(existing.ownerId, existing.issuingPointId);
495
+ return offlineIfOverdue(ctx, existing, profile, point, await ctx.material(profile), onlineDeadlineMs);
496
+ }
497
+ __name(answerLive, "answerLive");
498
+ function assertOnlineDeadline(onlineDeadlineMs) {
499
+ if (onlineDeadlineMs !== void 0 && (!Number.isInteger(onlineDeadlineMs) || onlineDeadlineMs < 0)) {
500
+ throw new FiscalDocumentError("INVALID_INPUT", "onlineDeadlineMs must be a whole number of milliseconds, 0 or more.");
501
+ }
502
+ }
503
+ __name(assertOnlineDeadline, "assertOnlineDeadline");
363
504
 
364
505
  // src/documents/service.ts
365
506
  var CONTINGENCY_WARNING_AFTER_MS = 20 * 36e5;
@@ -397,9 +538,11 @@ async function numberOrExisting(deps, input, create) {
397
538
  }
398
539
  __name(numberOrExisting, "numberOrExisting");
399
540
  async function issue(deps, input) {
541
+ assertOnlineDeadline(input.onlineDeadlineMs);
542
+ const deadlineAt = input.onlineDeadlineMs === void 0 ? null : Date.now() + input.onlineDeadlineMs;
400
543
  const { profile, point } = await issuable(deps, input.ownerId, input.issuingPointId, input.model);
401
544
  const existing = await liveDocument(deps, input);
402
- if (existing !== null) return existing;
545
+ if (existing !== null) return answerLive(deps.ctx, existing, profile, input.onlineDeadlineMs);
403
546
  const signing = await deps.ctx.material(profile);
404
547
  const draft = await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: input.subjectId, model: input.model });
405
548
  assertDraftFits(draft, input.model);
@@ -408,7 +551,8 @@ async function issue(deps, input) {
408
551
  input,
409
552
  () => deps.ctx.createNumbered({ profile, point, subjectId: input.subjectId, model: input.model, seriesKind: "ONLINE", draft })
410
553
  );
411
- return numbered.created ? submit(deps.ctx, numbered.document, profile, point, signing) : numbered.document;
554
+ if (!numbered.created) return answerLive(deps.ctx, numbered.document, profile, input.onlineDeadlineMs);
555
+ return submit(deps.ctx, numbered.document, profile, point, signing, deadlineAt);
412
556
  }
413
557
  __name(issue, "issue");
414
558
  async function issueOffline(deps, input) {
@@ -620,6 +764,8 @@ function createFiscalDocuments(config) {
620
764
  * (501) — issue the buyer's return NF-e of entry quoting it. Idempotent.
621
765
  */
622
766
  cancelOrReturn: cancelOrReturn.bind(null, deps),
767
+ /** Link payment transactions to an authorised document (event 110300), once each. Idempotent. */
768
+ linkPayment: linkPayment.bind(null, deps),
623
769
  /** Ask SEFAZ what it knows of the key; a state the answer moves is recorded. */
624
770
  lookup: lookup.bind(null, deps),
625
771
  /** A person takes a document back from `attention`; the sweep tries it again. */
@@ -1258,6 +1404,7 @@ export {
1258
1404
  FiscalDocumentError,
1259
1405
  LATE_CANCEL_CODES,
1260
1406
  MAX_FAILURES,
1407
+ MAX_PAYMENT_LINKS,
1261
1408
  OWED_VOIDS,
1262
1409
  SIGNING_IDENTITY_KINDS,
1263
1410
  canTransition,