@12-apps/fiscal 1.5.0 → 1.7.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 +46 -4
- package/dist/{chunk-HMTPJWXM.js → chunk-2JVTHJAU.js} +2 -2
- package/dist/{chunk-3E3NBXSW.js → chunk-CEK2GDRY.js} +5 -3
- package/dist/chunk-CEK2GDRY.js.map +1 -0
- package/dist/{chunk-MGTROA7K.js → chunk-OAQSGDZ7.js} +11 -7
- package/dist/chunk-OAQSGDZ7.js.map +1 -0
- package/dist/{chunk-ZKWVKCGJ.js → chunk-P5EDTNWE.js} +1 -1
- package/dist/{chunk-ZKWVKCGJ.js.map → chunk-P5EDTNWE.js.map} +1 -1
- package/dist/{chunk-G6QNU4FD.js → chunk-P7CRGZGO.js} +2 -2
- package/dist/{chunk-H33BK623.js → chunk-WRYCYXRA.js} +1 -1
- package/dist/{chunk-H33BK623.js.map → chunk-WRYCYXRA.js.map} +1 -1
- package/dist/{chunk-TJCUO6D6.js → chunk-YHSO3476.js} +6 -5
- package/dist/chunk-YHSO3476.js.map +1 -0
- package/dist/{context-CwZiHLnY.d.ts → context-D71ETH--.d.ts} +155 -19
- package/dist/danfe/index.d.ts +7 -0
- package/dist/danfe/index.js +2 -2
- package/dist/documents/index.d.ts +157 -36
- package/dist/documents/index.js +1104 -305
- package/dist/documents/index.js.map +1 -1
- package/dist/engine/index.d.ts +2 -2
- package/dist/http.d.ts +6 -5
- package/dist/http.js +4 -4
- package/dist/issuer/index.d.ts +10 -3
- package/dist/issuer/index.js +19 -4
- package/dist/issuer/index.js.map +1 -1
- package/dist/jobs.d.ts +5 -5
- package/dist/jobs.js +3 -3
- package/dist/manifest/index.d.ts +6 -4
- package/dist/manifest/index.js.map +1 -1
- package/dist/manifest/server.d.ts +5 -5
- package/dist/manifest/server.js +6 -6
- package/dist/notifications.d.ts +4 -4
- package/dist/notifications.js +2 -2
- package/dist/sale/index.d.ts +17 -4
- package/dist/sale/index.js.map +1 -1
- package/dist/{service-Cz2O84Xr.d.ts → service-DyA64Jc6.d.ts} +64 -5
- package/dist/sidecar/index.d.ts +38 -249
- package/dist/sidecar/index.js +30 -2
- package/dist/sidecar/index.js.map +1 -1
- package/dist/{types-DSYwap42.d.ts → types-6OiBrmZy.d.ts} +2 -2
- package/dist/{types-B1b8LIWX.d.ts → types-BLdkww6G.d.ts} +1 -1
- package/dist/types-BbTxBzsv.d.ts +252 -0
- package/package.json +2 -1
- package/prisma/fiscal.prisma +50 -1
- package/prisma/migrations/20261118180000_fiscal_contingency_blocks/migration.sql +64 -0
- package/sidecar/README.md +70 -10
- package/sidecar/bin/check-platform.php +29 -0
- package/sidecar/extensions.json +12 -0
- package/sidecar/schema/sale-for-document.schema.json +4 -0
- package/sidecar/src/Http/Request.php +6 -1
- package/sidecar/src/Kernel.php +39 -1
- package/sidecar/src/Nfe/DocumentMapper.php +27 -22
- package/sidecar/src/Platform.php +84 -0
- package/src/danfe/render.ts +16 -5
- package/src/documents/contingency-gaps.ts +88 -0
- package/src/documents/contingency-pass.ts +157 -0
- package/src/documents/contingency-xml.ts +136 -0
- package/src/documents/contingency.ts +257 -0
- package/src/documents/errors.ts +8 -1
- package/src/documents/helpers.ts +3 -0
- package/src/documents/index.ts +23 -1
- package/src/documents/lines.ts +6 -2
- package/src/documents/memory-blocks.ts +118 -0
- package/src/documents/memory.ts +6 -2
- package/src/documents/ports.ts +163 -13
- package/src/documents/service.ts +10 -0
- package/src/documents/sql-blocks.ts +202 -0
- package/src/documents/sql-store.ts +4 -3
- package/src/http.ts +1 -0
- package/src/issuer/sidecar.ts +27 -3
- package/src/manifest/index.ts +6 -4
- package/src/sale/types.ts +17 -4
- package/src/sidecar/index.ts +2 -0
- package/src/sidecar/platform.ts +55 -0
- package/src/sidecar/types.ts +1 -3
- package/dist/chunk-3E3NBXSW.js.map +0 -1
- package/dist/chunk-MGTROA7K.js.map +0 -1
- package/dist/chunk-TJCUO6D6.js.map +0 -1
- /package/dist/{chunk-HMTPJWXM.js.map → chunk-2JVTHJAU.js.map} +0 -0
- /package/dist/{chunk-G6QNU4FD.js.map → chunk-P7CRGZGO.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/documents/signing.ts","../../src/documents/service-profile.ts","../../src/documents/nfe-proc.ts","../../src/documents/settle.ts","../../src/documents/payment-link.ts","../../src/documents/steps.ts","../../src/documents/service.ts","../../src/documents/memory.ts","../../src/documents/sql.ts","../../src/documents/sql-rows.ts","../../src/documents/sql-store.ts","../../src/documents/lines.ts"],"sourcesContent":["/**\n * The SigningIdentity port: who signs a call. It turns a profile into the\n * {@link SigningMaterial} for ONE call to the issuer; the material is never\n * stored, logged or put in an error.\n *\n * - `STORE_CERTIFICATE` ships now: the store's own A1, decrypted through the\n * host's {@link Cipher} at the moment of the call.\n * - `PLATFORM` is declared and answers `NOT_SUPPORTED` until FUT-2229\n * question 4 says how the platform signs on a store's behalf.\n */\n\nimport type { SigningMaterial } from \"../issuer/port\";\nimport { FiscalDocumentError } from \"./errors\";\nimport type { Cipher } from \"./ports\";\nimport type { EmitterProfile, SigningIdentityKind } from \"./profile\";\n\nexport interface SigningIdentity {\n readonly kind: SigningIdentityKind;\n materialFor(profile: EmitterProfile): Promise<SigningMaterial>;\n}\n\nexport type SigningIdentities = Readonly<Record<SigningIdentityKind, SigningIdentity>>;\n\nexport function createStoreCertificateIdentity(config: { readonly cipher: Cipher }): SigningIdentity {\n if (typeof config?.cipher?.decrypt !== \"function\") throw new TypeError(\"createStoreCertificateIdentity needs a cipher.\");\n const { cipher } = config;\n return {\n kind: \"STORE_CERTIFICATE\",\n async materialFor(profile) {\n if (profile.certificateCiphertext === null || profile.certificatePasswordCiphertext === null) {\n throw new FiscalDocumentError(\"NOT_ISSUABLE\", `owner ${profile.ownerId} has no certificate.`);\n }\n const [pfxBase64, password] = await Promise.all([\n cipher.decrypt(profile.certificateCiphertext),\n cipher.decrypt(profile.certificatePasswordCiphertext),\n ]);\n const csc =\n profile.cscId !== null && profile.cscCiphertext !== null\n ? { id: profile.cscId, token: await cipher.decrypt(profile.cscCiphertext) }\n : null;\n return { certificate: { pfxBase64, password }, csc };\n },\n };\n}\n\nexport function createPlatformIdentity(): SigningIdentity {\n return {\n kind: \"PLATFORM\",\n async materialFor(profile) {\n throw new FiscalDocumentError(\n \"NOT_SUPPORTED\",\n `owner ${profile.ownerId} signs as PLATFORM, which is declared and not built yet (FUT-2229 q4).`,\n );\n },\n };\n}\n\n/** The two identities over one cipher: what a host passes as `signing`. */\nexport function createSigningIdentities(config: { readonly cipher: Cipher }): SigningIdentities {\n return { STORE_CERTIFICATE: createStoreCertificateIdentity(config), PLATFORM: createPlatformIdentity() };\n}\n","/**\n * The profile half of the document service: the emitter profile, the\n * certificate upload and the issuing points. A secret is encrypted through the\n * host's cipher the moment it arrives, and only its ciphertext is stored.\n */\n\nimport type { FiscalContext, FiscalDocumentsConfig } from \"./context\";\nimport { FiscalDocumentError } from \"./errors\";\nimport type { Cipher } from \"./ports\";\nimport type { CertificateUpload, EmitterProfileInput, IssuingPointInput } from \"./profile-input\";\nimport type { EmitterProfile, IssuingPoint } from \"./profile\";\n\n/** What the host learns from an A1 without this package parsing PKCS#12. */\nexport interface CertificateFacts {\n /** `notAfter`, ISO 8601. */\n readonly expiresAt: string;\n}\n\nexport interface FiscalDocumentsServiceConfig extends FiscalDocumentsConfig {\n /** Encrypts the certificate, its password and the CSC on arrival. */\n readonly cipher: Cipher;\n /**\n * Reads the expiry out of an uploaded A1; throws when the file does not\n * open with the password. The host's: Node's crypto cannot open every A1\n * (most issued before 2023 use RC2-40), and this package adds no parser.\n */\n readonly readCertificate: (certificate: CertificateUpload) => Promise<CertificateFacts>;\n}\n\nexport interface Deps {\n readonly ctx: FiscalContext;\n readonly config: FiscalDocumentsServiceConfig;\n}\n\n/**\n * The CSC's ciphertext a save leaves: the CSC id and token are one secret, so\n * a new id needs its token, a token needs an id, and no id clears both.\n */\nasync function cscCiphertextFor(\n config: FiscalDocumentsServiceConfig,\n stored: EmitterProfile | null,\n input: Pick<EmitterProfileInput, \"cscId\" | \"cscToken\">,\n): Promise<string | null> {\n if (input.cscToken !== null) {\n if (input.cscId === null) throw new FiscalDocumentError(\"INVALID_INPUT\", \"cscId is required with cscToken.\");\n return config.cipher.encrypt(input.cscToken);\n }\n if (input.cscId === null) return null;\n if (input.cscId !== stored?.cscId) throw new FiscalDocumentError(\"INVALID_INPUT\", \"cscToken is required with a new cscId.\");\n return stored.cscCiphertext;\n}\n\nexport async function saveProfile({ ctx, config }: Deps, ownerId: string, input: EmitterProfileInput): Promise<EmitterProfile> {\n const stored = await config.store.getProfile(ownerId);\n const fields = Object.fromEntries(Object.entries(input).filter(([key]) => key !== \"cscToken\")) as Omit<EmitterProfileInput, \"cscToken\">;\n const profile: EmitterProfile = {\n ...fields,\n ownerId,\n certificateCiphertext: stored?.certificateCiphertext ?? null,\n certificatePasswordCiphertext: stored?.certificatePasswordCiphertext ?? null,\n certificateExpiresAt: stored?.certificateExpiresAt ?? null,\n cscCiphertext: await cscCiphertextFor(config, stored, input),\n updatedAt: ctx.nowIso(),\n };\n await config.store.saveProfile(profile);\n return profile;\n}\n\nexport async function uploadCertificate({ ctx, config }: Deps, ownerId: string, certificate: CertificateUpload): Promise<EmitterProfile> {\n const stored = await ctx.requireProfile(ownerId);\n let facts: CertificateFacts;\n try {\n facts = await config.readCertificate(certificate);\n } catch {\n // The reader's own message may quote what it was given; this one never does.\n throw new FiscalDocumentError(\"INVALID_INPUT\", \"the certificate does not open with that password.\");\n }\n const profile: EmitterProfile = {\n ...stored,\n certificateCiphertext: await config.cipher.encrypt(certificate.pfxBase64),\n certificatePasswordCiphertext: await config.cipher.encrypt(certificate.password),\n certificateExpiresAt: facts.expiresAt,\n updatedAt: ctx.nowIso(),\n };\n await config.store.saveProfile(profile);\n return profile;\n}\n\nexport async function createIssuingPoint({ ctx, config }: Deps, ownerId: string, input: IssuingPointInput): Promise<IssuingPoint> {\n const profile = await ctx.requireProfile(ownerId);\n if (input.model === \"NFE\" && input.contingencySeries !== null) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", \"an NF-e issuing point has no contingency series: the service has no offline NF-e path.\");\n }\n const point: IssuingPoint = {\n id: input.id,\n ownerId,\n model: input.model,\n onlineSeries: input.onlineSeries,\n contingencySeries: input.contingencySeries,\n createdAt: ctx.nowIso(),\n };\n await config.store.createIssuingPoint(point, profile.cnpj, { online: input.firstOnlineNumber, contingency: input.firstContingencyNumber });\n return point;\n}\n","/**\n * The `nfeProc` — what an authorised document is stored as — assembled from\n * the signed XML the service built and the `protNFe` a lookup answered, for a\n * document whose sending went unanswered and was then found authorised.\n */\n\nimport { element } from \"../danfe/xml\";\n\nconst PROTOCOL = /<protNFe\\b[^>]*>[\\s\\S]*?<\\/protNFe>/;\nconst NFE = /<NFe\\b[^>]*>[\\s\\S]*<\\/NFe>/;\n/** The signed XML's own digest (`DigestValue`), which SEFAZ quotes back as the protocol's `digVal`. */\nexport function digestOf(signedXml: string): string | null {\n return /<DigestValue>([^<]+)<\\/DigestValue>/.exec(signedXml)?.[1]?.trim() ?? null;\n}\n\n/** The protocol a SEFAZ reply carries, with its `digVal`, or `null`. */\nexport function protocolDigestOf(sefazReply: string): string | null {\n const protocol = PROTOCOL.exec(sefazReply)?.[0];\n const infProt = protocol === undefined ? null : element(protocol, \"infProt\");\n return infProt === null ? null : (element(infProt, \"digVal\")?.trim() ?? null);\n}\n\n/** The `cStat`s of a protocol that authorises (100, 150 late) or denies (110, 301–303) the use of the key. */\nconst SETTLING = new Set([\"100\", \"150\", \"110\", \"301\", \"302\", \"303\"]);\n\n/**\n * `null` unless the reply carries a protocol for exactly this key with a\n * settling status, the signed XML is the document's, AND the protocol's\n * `digVal` is that XML's `DigestValue` — the protocol certifies THAT XML and\n * no other built under the same key (the fiscal service's own `issued()`\n * refuses the same mismatch). Never a guess.\n */\n/** Whether this protocol certifies this signed XML under this key, with a settling status. */\nfunction certifies(infProt: string, nfe: string, accessKey: string): boolean {\n const digest = digestOf(nfe);\n return (\n element(infProt, \"chNFe\") === accessKey &&\n SETTLING.has(element(infProt, \"cStat\") ?? \"\") &&\n nfe.includes(`Id=\"NFe${accessKey}\"`) &&\n digest !== null &&\n element(infProt, \"digVal\")?.trim() === digest\n );\n}\n\nexport function assembleNfeProc(input: { readonly signedXml: string; readonly sefazReply: string; readonly accessKey: string }): string | null {\n const protocol = PROTOCOL.exec(input.sefazReply)?.[0];\n const nfe = NFE.exec(input.signedXml)?.[0];\n const infProt = protocol === undefined ? null : element(protocol, \"infProt\");\n if (protocol === undefined || nfe === undefined || infProt === null || !certifies(infProt, nfe, input.accessKey)) return null;\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?><nfeProc versao=\"4.00\" xmlns=\"http://www.portalfiscal.inf.br/nfe\">${nfe}${protocol}</nfeProc>`;\n}\n","/**\n * Settling a number SEFAZ never used, so a series has no unexplained gap:\n * look it up first when a send went unanswered, cancel it if SEFAZ authorised\n * it after all (by SUBSTITUTION, event 110112, when a contingency document\n * replaced it), inutilize it otherwise.\n *\n * A call that fails is never silent: it is DEFERRED — one more failure, a\n * later attempt — and a refusal SEFAZ will repeat (241 number used, 256, 501\n * late cancel, a certificate refused) hands the document to a person at once,\n * with the needs-attention notification.\n */\n\nimport type { IssuerFailure, IssuerOutcome, SigningMaterial } from \"../issuer/port\";\nimport type { CancelledDocument, LookedUpDocument } from \"../sidecar/types\";\nimport { type FiscalContext, xmlKeys } from \"./context\";\nimport { assembleNfeProc, protocolDigestOf } from \"./nfe-proc\";\nimport type { EmitterProfile } from \"./profile\";\nimport type { FiscalDocument, NumberVoid } from \"./types\";\n\ntype Settle = (ctx: FiscalContext, document: FiscalDocument, profile: EmitterProfile, signing: SigningMaterial) => Promise<FiscalDocument>;\n\n/** A refusal the same call would meet again: a person must look. */\nconst REFUSALS = new Set<IssuerFailure[\"class\"]>([\"REJECTED\", \"AUTH\", \"INVALID\", \"INTERNAL\"]);\n\nfunction defer(ctx: FiscalContext, document: FiscalDocument, what: string, error: IssuerFailure): Promise<FiscalDocument> {\n return ctx.advance(document, { kind: \"DEFER\", reason: `${what} failed`, error, attention: REFUSALS.has(error.class) });\n}\n\n/**\n * A SUBMITTED document a lookup finds authorised or denied: its `nfeProc`,\n * from the signed XML whose digest the protocol's `digVal` names and the\n * protocol itself, stored. `undefined` when either is missing — the document\n * then stays SUBMITTED, owing work, and the sweep sends the same call again\n * for the XML.\n */\nexport async function storeNfeProc(ctx: FiscalContext, document: FiscalDocument, answer: LookedUpDocument): Promise<string | undefined> {\n if ((answer.status !== \"AUTHORIZED\" && answer.status !== \"DENIED\") || document.accessKey === null) return undefined;\n // The XML the protocol certifies, by its digest; never simply the last one stored.\n const digest = protocolDigestOf(answer.sefazReply);\n if (digest === null) return undefined;\n const signedXml = await ctx.config.storage.get(xmlKeys.signedByDigest(document.accessKey, digest));\n if (signedXml === null) return undefined;\n const nfeProc = assembleNfeProc({ signedXml, sefazReply: answer.sefazReply, accessKey: document.accessKey });\n if (nfeProc === null) return undefined;\n const xmlKey = xmlKeys.authorized(document.accessKey);\n await ctx.config.storage.put(xmlKey, nfeProc, \"application/xml\");\n return xmlKey;\n}\n\n/**\n * A document a lookup just returned to SUBMITTED (a live REJECTED number\n * found SEFAZ's): settled as AUTHORIZED or DENIED with the same answer when\n * the XML the protocol certifies is held. Two steps, never REJECTED →\n * AUTHORIZED in one.\n */\nexport async function settleWithXml(ctx: FiscalContext, document: FiscalDocument, answer: LookedUpDocument): Promise<FiscalDocument> {\n if (document.status !== \"SUBMITTED\") return document;\n const xmlKey = await storeNfeProc(ctx, document, answer);\n return xmlKey === undefined ? document : ctx.advance(document, { kind: \"LOOKUP\", answer, xmlKey });\n}\n\nconst lookupFirst: Settle = async (ctx, document, _profile, signing) => {\n if (document.accessKey === null) return ctx.advance(document, { kind: \"DEFER\", reason: \"no access key to look up\", error: null, attention: true });\n const outcome = await ctx.config.issuer.lookup({ model: document.model, environment: document.environment, signing, accessKey: document.accessKey });\n if (!outcome.ok) return defer(ctx, document, \"the lookup\", outcome.error);\n return settleWithXml(ctx, await ctx.advance(document, { kind: \"LOOKUP\", answer: outcome.answer }), outcome.answer);\n};\n\n/** The cancel owed: by substitution when a contingency document replaced it, an ordinary one otherwise. */\nasync function sendOwedCancel(ctx: FiscalContext, document: FiscalDocument, signing: SigningMaterial): Promise<IssuerOutcome<CancelledDocument> | null> {\n const { accessKey, protocol, replacedById } = document;\n if (accessKey === null || protocol === null) return null;\n const reason = ctx.config.reasons.substitution;\n const base = { environment: document.environment, signing, accessKey, protocol, reason };\n const substitute = replacedById === null ? null : await ctx.config.store.getDocument(document.ownerId, replacedById);\n if (document.model === \"NFCE\" && substitute?.accessKey) {\n return ctx.config.issuer.cancelBySubstitution({ ...base, substituteAccessKey: substitute.accessKey });\n }\n return ctx.config.issuer.cancel({ ...base, model: document.model });\n}\n\nconst cancelOwed: Settle = async (ctx, document, _profile, signing) => {\n const outcome = await sendOwedCancel(ctx, document, signing);\n if (outcome === null) return ctx.advance(document, { kind: \"DEFER\", reason: \"no protocol to cancel with\", error: null, attention: true });\n if (!outcome.ok) return defer(ctx, document, \"the owed cancel\", outcome.error);\n const eventXmlKey = outcome.answer.eventXml === null ? null : xmlKeys.cancel(outcome.answer.accessKey);\n if (eventXmlKey !== null) await ctx.config.storage.put(eventXmlKey, outcome.answer.eventXml ?? \"\", \"application/xml\");\n return ctx.advance(document, { kind: \"CANCEL\", answer: outcome.answer, reason: ctx.config.reasons.substitution, eventXmlKey });\n};\n\nconst inutilizeOwed: Settle = async (ctx, document, profile, signing) => {\n const outcome = await ctx.config.issuer.inutilize({\n model: document.model,\n environment: document.environment,\n signing,\n uf: profile.address.uf,\n cnpj: document.issuerCnpj,\n year: Number(document.issuedAt.slice(0, 4)),\n series: document.series,\n from: document.number,\n to: document.number,\n reason: ctx.config.reasons.inutilization,\n });\n if (!outcome.ok) return defer(ctx, document, \"the inutilization\", outcome.error);\n const xml = outcome.answer.inutilizationXml;\n const eventXmlKey = xml === null ? null : xmlKeys.inutilization(document);\n if (eventXmlKey !== null) await ctx.config.storage.put(eventXmlKey, xml ?? \"\", \"application/xml\");\n return ctx.advance(document, { kind: \"INUTILIZE\", answer: outcome.answer, eventXmlKey });\n};\n\nconst SETTLE: Partial<Record<NumberVoid, Settle>> = {\n LOOKUP_FIRST: lookupFirst,\n CANCEL: cancelOwed,\n INUTILIZE: inutilizeOwed,\n};\n\n/** Settle what a replaced or rejected document still owes on its number. */\nexport async function settleNumber(ctx: FiscalContext, document: FiscalDocument, profile: EmitterProfile, signing: SigningMaterial): Promise<FiscalDocument> {\n const settle = document.numberVoid === null ? undefined : SETTLE[document.numberVoid];\n return settle === undefined ? document : settle(ctx, document, profile, signing);\n}\n","/**\n * The event 110300 \"Vinculação Pagamento\" (NT 2026.006 v1.00 §5.1): a payment\n * transaction linked to an authorised document after the fact — a Pix QR whose\n * txid was learnt only once the note was out, say. One event per transaction\n * (the event's single `gPgto`), numbered per document (`nSeqEvento`).\n *\n * Idempotent per `(document, transactionId)`: a transaction the document\n * already carries in its own `gPgtoVinc`, or already linked by an earlier\n * event, is skipped with no call to SEFAZ. A refusal answers the issuer's\n * failure and records nothing; the caller may ask again. `nSeqEvento` is the\n * next after the document's own recorded events; a 573 at it is settled by the\n * event SEFAZ holds there (its XML kept, its transaction recorded as its own),\n * and the payment is then sent at the next sequence.\n */\n\nimport type { IssuerFailure } from \"../issuer/port\";\nimport type { LinkedTransaction, PaymentLinkMeans } from \"../sale/types\";\nimport type { RegisteredPaymentLink } from \"../sidecar/types\";\nimport { xmlKeys } from \"./context\";\nimport { FiscalDocumentError } from \"./errors\";\nimport type { Deps } from \"./service-profile\";\nimport type { FiscalDocument, FiscalDocumentEvent } from \"./types\";\n\n/** `nSeqEvento` runs 1–20 per event type and document. */\nexport const MAX_PAYMENT_LINKS = 20;\n\nexport interface LinkPaymentInput {\n readonly ownerId: string;\n readonly documentId: string;\n readonly payments: readonly LinkedTransaction[];\n}\n\nexport interface LinkPaymentResult {\n /** The transaction ids SEFAZ registered in this call. */\n readonly linked: readonly string[];\n /** Those the document already carried or an earlier event linked: nothing was sent. */\n readonly alreadyLinked: readonly string[];\n /** The first refusal, if any; the transactions after it were not sent. */\n readonly failure: IssuerFailure | null;\n readonly document: FiscalDocument;\n}\n\n/** Each 110300 the document's events record: the transaction and its `nSeqEvento`. */\nfunction linkedByEvents(events: readonly FiscalDocumentEvent[]): Array<{ transactionId: string; sequence: number }> {\n return events\n .filter((event) => event.kind === \"LINK_PAYMENT\")\n .map((event, index) => {\n const answer = event.answer as { payment?: { transactionId?: unknown }; sequence?: unknown } | null;\n return {\n transactionId: answer?.payment?.transactionId,\n sequence: typeof answer?.sequence === \"number\" ? answer.sequence : index + 1,\n };\n })\n .filter((link): link is { transactionId: string; sequence: number } => typeof link.transactionId === \"string\");\n}\n\n/** The transaction ids the document's own `gPgtoVinc` carries. */\nfunction linkedInDocument(document: FiscalDocument): string[] {\n return document.sale.payments\n .map((payment) => payment.linkedTransaction?.transactionId)\n .filter((id): id is string => typeof id === \"string\");\n}\n\n/** What every event of this document is sent with: its key, its protocol and the issuer's event call. */\nfunction linkable(deps: Deps, document: FiscalDocument) {\n const { accessKey, protocol } = document;\n if (document.status !== \"AUTHORIZED\" || accessKey === null || protocol === null) {\n throw new FiscalDocumentError(\"TRANSITION_REFUSED\", `document ${document.id} is ${document.status}; only an authorised document is linked.`);\n }\n const send = deps.config.issuer.linkPayment;\n if (typeof send !== \"function\") throw new FiscalDocumentError(\"NOT_SUPPORTED\", \"this issuer does not register the event 110300.\");\n return { accessKey, protocol, send: send.bind(deps.config.issuer) };\n}\n\n/**\n * The transaction SEFAZ holds at the sequence just sent. A 135 registered what\n * was sent. A 573 answers the event already there, looked up: the same\n * transaction (a retry whose recording was lost), or another one, which is\n * then recorded as ITS link and never attributed to `sent`.\n */\nfunction heldTransaction(answer: RegisteredPaymentLink, sent: LinkedTransaction, requested: readonly LinkedTransaction[]): LinkedTransaction {\n if (answer.statusCode !== \"573\" || answer.transaction.transactionId === sent.transactionId) return sent;\n const held = answer.transaction;\n return (\n requested.find((payment) => payment.transactionId === held.transactionId) ?? {\n transactionId: held.transactionId,\n meansCode: held.meansCode as PaymentLinkMeans,\n pspCnpjBase: held.pspCnpjBase,\n receiverCnpj: held.receiverCnpj,\n }\n );\n}\n\n/** One call's progress: the document as last advanced, the next `nSeqEvento`, what is linked. */\ninterface LinkRun {\n document: FiscalDocument;\n sequence: number;\n readonly known: Set<string>;\n readonly requested: readonly LinkedTransaction[];\n readonly linked: string[];\n readonly send: (sequence: number, payment: LinkedTransaction) => ReturnType<NonNullable<Deps[\"config\"][\"issuer\"][\"linkPayment\"]>>;\n}\n\nfunction refuseOverLimit(document: FiscalDocument): never {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `document ${document.id} cannot take more than ${MAX_PAYMENT_LINKS} payment links.`);\n}\n\n/**\n * Sends `payment` at the run's sequence and records what SEFAZ holds there.\n * When that is another transaction (a 573), it is recorded as its own link and\n * `payment` goes out again at the next sequence. Answers the refusal, if any.\n */\nasync function sendOne(deps: Deps, run: LinkRun, accessKey: string, payment: LinkedTransaction): Promise<IssuerFailure | null> {\n if (run.sequence > MAX_PAYMENT_LINKS) refuseOverLimit(run.document);\n const sequence = run.sequence;\n const outcome = await run.send(sequence, payment);\n if (!outcome.ok) return outcome.error;\n const held = heldTransaction(outcome.answer, payment, run.requested);\n const { eventXml } = outcome.answer;\n const eventXmlKey = eventXml === null ? null : xmlKeys.linkPayment(accessKey, sequence);\n if (eventXmlKey !== null && eventXml !== null) await deps.config.storage.put(eventXmlKey, eventXml, \"application/xml\");\n run.document = await deps.ctx.advance(run.document, { kind: \"LINK_PAYMENT\", answer: outcome.answer, payment: held, sequence, eventXmlKey });\n run.known.add(held.transactionId);\n if (run.requested.some((one) => one.transactionId === held.transactionId)) run.linked.push(held.transactionId);\n run.sequence = sequence + 1;\n return held.transactionId === payment.transactionId ? null : sendOne(deps, run, accessKey, payment);\n}\n\nexport async function linkPayment(deps: Deps, input: LinkPaymentInput): Promise<LinkPaymentResult> {\n const document = await deps.config.store.getDocument(input.ownerId, input.documentId);\n if (document === null) throw new FiscalDocumentError(\"NOT_FOUND\", `owner ${input.ownerId} has no document ${input.documentId}.`);\n const { accessKey, protocol, send } = linkable(deps, document);\n const byEvents = linkedByEvents(await deps.config.store.listEvents(document.id));\n const known = new Set([...linkedInDocument(document), ...byEvents.map((link) => link.transactionId)]);\n const pending = input.payments.filter((payment) => !known.has(payment.transactionId));\n const alreadyLinked = input.payments.filter((payment) => known.has(payment.transactionId)).map((payment) => payment.transactionId);\n // `nSeqEvento` follows the document's own events, never a count of anything else.\n const sequence = Math.max(0, ...byEvents.map((link) => link.sequence)) + 1;\n if (sequence - 1 + pending.length > MAX_PAYMENT_LINKS) refuseOverLimit(document);\n if (pending.length === 0) return { linked: [], alreadyLinked, failure: null, document };\n const signing = await deps.ctx.material(await deps.ctx.requireProfile(input.ownerId));\n const run: LinkRun = {\n document,\n sequence,\n known,\n requested: pending,\n linked: [],\n send: (at, payment) => send({ model: document.model, environment: document.environment, signing, accessKey, protocol, sequence: at, payments: [payment] }),\n };\n for (const payment of pending) {\n if (run.known.has(payment.transactionId)) continue;\n const failure = await sendOne(deps, run, accessKey, payment);\n if (failure !== null) return { linked: run.linked, alreadyLinked, failure, document: run.document };\n }\n return { linked: run.linked, alreadyLinked, failure: null, document: run.document };\n}\n","/**\n * The steps that issue a document, each one call and the transition its\n * answer earns. The mapping of the service's classes:\n *\n * | answer | on a document being issued | on a contingency document being transmitted |\n * |---|---|---|\n * | `AUTHORIZED` / `DENIED` | AUTHORIZE / DENY | AUTHORIZE / DENY |\n * | `REJECTED`, `INVALID`, `INTERNAL` | REJECT: the number is voided (looked up first if a send went unanswered) | REJECT: kept for the store to correct and resend |\n * | `CONTINGENCY`, NFC-e, point with a contingency series | a second document, offline, replacing this one in one transaction | RETRY |\n * | `CONTINGENCY` otherwise, `RETRYABLE`, `AUTH` | RETRY, with backoff; a person after `MAX_FAILURES` | RETRY |\n *\n * An online NFC-e is never sent again past `nfceOnlineToleranceMs` (SEFAZ\n * refuses a late `dhEmi`): where the point has a contingency series it goes\n * offline instead.\n *\n * A caller that cannot wait (a counter whose paper waits for the note) gives\n * the send an ONLINE DEADLINE (`issue({ …, onlineDeadlineMs })`): an NFC-e at\n * a point with a contingency series whose send is not answered by then — or is\n * answered with no answer (`RETRYABLE`) — goes offline at once, exactly as a\n * `CONTINGENCY` answer does. The send may still have reached SEFAZ, so the\n * replaced number is marked unknown and looked up before it is voided; its\n * late answer settles nothing.\n */\n\nimport type { IssuerFailure, IssuerOutcome, SigningMaterial } from \"../issuer/port\";\nimport { FISCAL_ISSUE } from \"../manifest/permissions\";\nimport type { IssuedDocument } from \"../sidecar/types\";\nimport { FISCAL_DOCUMENT_REJECTED, type FiscalContext, draftOf, xmlKeys } from \"./context\";\nimport { FiscalDocumentError } from \"./errors\";\nimport { computeAccessKey } from \"./helpers\";\nimport { digestOf } from \"./nfe-proc\";\nimport type { EmitterProfile, IssuingPoint } from \"./profile\";\nimport type { FiscalDocument } from \"./types\";\n\nconst FINAL_FAILURES = new Set<IssuerFailure[\"class\"]>([\"REJECTED\", \"INVALID\", \"INTERNAL\"]);\n\nasync function reject(ctx: FiscalContext, document: FiscalDocument, error: IssuerFailure): Promise<FiscalDocument> {\n const rejected = await ctx.advance(document, { kind: \"REJECT\", error });\n await ctx.config.notify.emit({\n type: FISCAL_DOCUMENT_REJECTED,\n recipient: { tenantId: document.ownerId, permission: FISCAL_ISSUE },\n payload: {\n documentId: document.id,\n subjectId: document.subjectId,\n model: document.model,\n series: document.series,\n number: document.number,\n code: error.code,\n reason: error.message,\n },\n });\n return rejected;\n}\n\nasync function accept(ctx: FiscalContext, document: FiscalDocument, answer: IssuedDocument): Promise<FiscalDocument> {\n const xmlKey = xmlKeys.authorized(answer.accessKey);\n await ctx.config.storage.put(xmlKey, answer.authorizedXml, \"application/xml\");\n return ctx.advance(document, { kind: answer.status === \"AUTHORIZED\" ? \"AUTHORIZE\" : \"DENY\", answer, xmlKey });\n}\n\nfunction canGoOffline(document: FiscalDocument, point: IssuingPoint): boolean {\n return document.model === \"NFCE\" && document.seriesKind === \"ONLINE\" && point.contingencySeries !== null;\n}\n\n/** An online NFC-e whose `dhEmi` SEFAZ would now refuse as late. */\nfunction pastOnlineTolerance(ctx: FiscalContext, document: FiscalDocument): boolean {\n return ctx.config.now().getTime() - Date.parse(document.createdAt) > ctx.config.nfceOnlineToleranceMs;\n}\n\n/** Sign a contingency-series document offline. On a failure it is left as it was, for the caller to defer. */\nasync function signOffline(\n ctx: FiscalContext,\n document: FiscalDocument,\n profile: EmitterProfile,\n signing: SigningMaterial,\n): Promise<{ document: FiscalDocument; error: IssuerFailure | null }> {\n const contingency = { since: await ctx.localNow(profile.ownerId), reason: ctx.config.reasons.contingency };\n const outcome = await ctx.config.issuer.signContingency({ environment: document.environment, signing, document: document.sale, contingency });\n if (!outcome.ok) return { document, error: outcome.error };\n const xmlKey = xmlKeys.signed(outcome.answer.accessKey);\n await ctx.config.storage.put(xmlKey, outcome.answer.signedXml, \"application/xml\");\n return { document: await ctx.advance(document, { kind: \"SIGN_OFFLINE\", answer: outcome.answer, contingency, xmlKey }), error: null };\n}\n\n/** Sign a PENDING contingency document; a failure is deferred (it stays PENDING, the sweep signs it later). */\nexport async function signPending(\n ctx: FiscalContext,\n document: FiscalDocument,\n profile: EmitterProfile,\n signing: SigningMaterial,\n): Promise<FiscalDocument> {\n const signed = await signOffline(ctx, document, profile, signing);\n if (signed.error === null) return signed.document;\n return ctx.advance(document, {\n kind: \"DEFER\",\n reason: \"signing offline failed\",\n error: signed.error,\n // Signing is local: a certificate that does not open (AUTH) will not open on the next try either.\n attention: FINAL_FAILURES.has(signed.error.class) || signed.error.class === \"AUTH\",\n });\n}\n\n/**\n * Move the sale offline: number a second document on the contingency series\n * AND replace this one, in ONE transaction, before anything is signed — so a\n * crash can never leave the online document to be sent again beside its twin.\n * Signing follows; if it fails, the new document waits PENDING for the sweep.\n */\nasync function goOffline(\n ctx: FiscalContext,\n document: FiscalDocument,\n profile: EmitterProfile,\n point: IssuingPoint,\n signing: SigningMaterial,\n): Promise<FiscalDocument> {\n const offline = await ctx.createNumbered({\n profile,\n point,\n subjectId: document.subjectId,\n model: document.model,\n seriesKind: \"CONTINGENCY\",\n draft: draftOf(document.sale),\n replacing: document,\n });\n return signPending(ctx, offline, profile, signing);\n}\n\n/**\n * The signed XML a failed call returned, stored UNDER ITS DIGEST and never\n * over another: each send under a key may carry a different XML (a service\n * upgrade between sends changes `verProc`, say), and only the one SEFAZ\n * authorised may become the `nfeProc`. A lookup reads the protocol's `digVal`\n * and fetches exactly that XML (`xmlKeys.signedByDigest`), so pairing is by\n * digest, not by \"the last one stored\". `xmlKey` points at the latest.\n */\nasync function keepSigned(ctx: FiscalContext, document: FiscalDocument, error: IssuerFailure): Promise<{ xmlKey?: string }> {\n const key = document.accessKey ?? error.accessKey;\n const digest = error.signedXml === null ? null : digestOf(error.signedXml);\n if (error.signedXml === null || key === null || digest === null) return {};\n const xmlKey = xmlKeys.signedByDigest(key, digest);\n await ctx.config.storage.put(xmlKey, error.signedXml, \"application/xml\");\n return { xmlKey };\n}\n\n/**\n * An online NFC-e SEFAZ would now refuse as late, at a point that can go\n * offline. A document a lookup found authorised (its protocol is kept) is\n * SEFAZ's: sending the same call again fetches its XML (the service settles\n * the duplicate by a lookup), and it must never go offline beside its own\n * authorisation.\n */\nfunction staleOnline(ctx: FiscalContext, document: FiscalDocument, point: IssuingPoint): boolean {\n const knownToSefaz = document.status === \"SUBMITTED\" && document.protocol !== null;\n return !knownToSefaz && canGoOffline(document, point) && pastOnlineTolerance(ctx, document);\n}\n\n/** The failure a send not answered by its online deadline counts as: a contingency, its outcome unknown. */\nfunction pastDeadline(document: FiscalDocument): IssuerFailure {\n return {\n class: \"CONTINGENCY\",\n code: null,\n message: \"SEFAZ did not answer before the online deadline.\",\n details: [],\n accessKey: document.accessKey ?? computeAccessKey({ sale: document.sale, model: document.model, seriesKind: \"ONLINE\" }),\n signedXml: null,\n sefazReply: null,\n outcomeUnknown: true,\n };\n}\n\n/** The send, raced against the deadline (`deadlineAt`, epoch ms). A late answer is dropped: the number is looked up instead. */\nasync function sendBefore(\n send: Promise<IssuerOutcome<IssuedDocument>>,\n document: FiscalDocument,\n deadlineAt: number,\n): Promise<IssuerOutcome<IssuedDocument>> {\n send.catch(() => undefined);\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<IssuerOutcome<IssuedDocument>>((resolve) => {\n timer = setTimeout(() => resolve({ ok: false, error: pastDeadline(document) }), Math.max(0, deadlineAt - Date.now()));\n });\n try {\n return await Promise.race([send, late]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** The online send, bounded by the deadline when there is one. */\nfunction send(ctx: FiscalContext, document: FiscalDocument, signing: SigningMaterial, deadlineAt: number | null): Promise<IssuerOutcome<IssuedDocument>> {\n const call = ctx.config.issuer.issue({ model: document.model, environment: document.environment, signing, document: document.sale });\n return deadlineAt === null ? call : sendBefore(call, document, deadlineAt);\n}\n\n/** Whether a failed send moves the sale offline: a contingency always; with a deadline, an unanswered send too. */\nfunction goesOffline(error: IssuerFailure, deadlineAt: number | null): boolean {\n return error.class === \"CONTINGENCY\" || (deadlineAt !== null && error.class === \"RETRYABLE\");\n}\n\n/**\n * Issue (or re-issue, for a SUBMITTED one) a document on its online series.\n * `deadlineAt` (epoch ms): the online deadline, for an NFC-e whose point can\n * go offline (see the module doc); `null`, the send's own timeout rules.\n */\nexport async function submit(\n ctx: FiscalContext,\n document: FiscalDocument,\n profile: EmitterProfile,\n point: IssuingPoint,\n signing: SigningMaterial,\n deadlineAt: number | null = null,\n): Promise<FiscalDocument> {\n if (staleOnline(ctx, document, point)) return goOffline(ctx, document, profile, point, signing);\n const sent = document.status === \"PENDING\" ? await ctx.advance(document, { kind: \"SUBMIT\" }) : document;\n const bounded = deadlineAt !== null && canGoOffline(sent, point) ? deadlineAt : null;\n const outcome = await send(ctx, sent, signing, bounded);\n if (outcome.ok) return accept(ctx, sent, outcome.answer);\n if (FINAL_FAILURES.has(outcome.error.class)) return reject(ctx, sent, outcome.error);\n const retried = await ctx.advance(sent, { kind: \"RETRY\", error: outcome.error, ...(await keepSigned(ctx, sent, outcome.error)) });\n return goesOffline(outcome.error, bounded) && canGoOffline(retried, point) ? goOffline(ctx, retried, profile, point, signing) : retried;\n}\n\n/**\n * A live online NFC-e the caller's deadline already passed — `onlineDeadlineMs`\n * since it was numbered, still unanswered and not known to SEFAZ — goes offline\n * now, at a point with a contingency series; anything else is answered as it is.\n */\nasync function offlineIfOverdue(\n ctx: FiscalContext,\n document: FiscalDocument,\n profile: EmitterProfile,\n point: IssuingPoint,\n signing: SigningMaterial,\n onlineDeadlineMs: number,\n): Promise<FiscalDocument> {\n const waiting = document.status === \"PENDING\" || document.status === \"SUBMITTED\";\n const overdue = ctx.config.now().getTime() - Date.parse(document.createdAt) >= onlineDeadlineMs;\n if (!waiting || !overdue || document.protocol !== null || !canGoOffline(document, point)) return document;\n return goOffline(ctx, document, profile, point, signing);\n}\n\n/** Transmit a document signed offline. */\nexport async function transmit(ctx: FiscalContext, document: FiscalDocument, signing: SigningMaterial): Promise<FiscalDocument> {\n const signedXml = document.xmlKey === null ? null : await ctx.config.storage.get(document.xmlKey);\n if (signedXml === null) throw new FiscalDocumentError(\"NOT_FOUND\", `document ${document.id} has no signed XML in storage.`);\n const outcome = await ctx.config.issuer.transmit({ model: document.model, environment: document.environment, signing, signedXml });\n if (outcome.ok) return accept(ctx, document, outcome.answer);\n if (FINAL_FAILURES.has(outcome.error.class)) return reject(ctx, document, outcome.error);\n return ctx.advance(document, { kind: \"RETRY\", error: outcome.error });\n}\n\n/** The live document of a lost race or an earlier call — moved offline when the caller's online deadline already passed. */\nexport async function answerLive(\n ctx: FiscalContext,\n existing: FiscalDocument,\n profile: EmitterProfile,\n onlineDeadlineMs: number | undefined,\n): Promise<FiscalDocument> {\n if (onlineDeadlineMs === undefined || existing.model !== \"NFCE\" || existing.seriesKind !== \"ONLINE\") return existing;\n const point = await ctx.requirePoint(existing.ownerId, existing.issuingPointId);\n return offlineIfOverdue(ctx, existing, profile, point, await ctx.material(profile), onlineDeadlineMs);\n}\n\n/** `onlineDeadlineMs`, when given, is a whole number of milliseconds, 0 or more. */\nexport function assertOnlineDeadline(onlineDeadlineMs: number | undefined): void {\n if (onlineDeadlineMs !== undefined && (!Number.isInteger(onlineDeadlineMs) || onlineDeadlineMs < 0)) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", \"onlineDeadlineMs must be a whole number of milliseconds, 0 or more.\");\n }\n}\n","/**\n * `createFiscalDocuments` — the document service: the emitter profile, the\n * issuing points, and issuing, cancelling, looking up and sweeping documents\n * over the host's ports. Every SEFAZ step goes through the Issuer port and\n * every state change through the state machine (`./machine`), persisted with\n * its event and its next attempt.\n *\n * The certificate, its password and the CSC are encrypted through the host's\n * cipher the moment they arrive, decrypted by the signing identity for one\n * call, and never logged, answered or put in an error.\n */\n\nimport type { IssuerFailure } from \"../issuer/port\";\nimport { FISCAL_ISSUE } from \"../manifest/permissions\";\nimport type { LookedUpDocument } from \"../sidecar/types\";\nimport { FISCAL_CONTINGENCY_DEADLINE, FiscalContext, assertConfig, assertDraftFits, assertReason, issuerOf, totalsOf, xmlKeys } from \"./context\";\nimport { FiscalDocumentError } from \"./errors\";\nimport { canTransition } from \"./machine\";\nimport { type Deps, type FiscalDocumentsServiceConfig, createIssuingPoint, saveProfile, uploadCertificate } from \"./service-profile\";\nimport { settleNumber, settleWithXml, storeNfeProc } from \"./settle\";\nimport { linkPayment } from \"./payment-link\";\nimport { answerLive, assertOnlineDeadline, signPending, submit, transmit } from \"./steps\";\nimport { type CancelOrReturnInput, type CancelOrReturnResult, type DocumentTotals, type FiscalDocument, type FiscalDocumentModel, isLive } from \"./types\";\n\nexport type { CertificateFacts, FiscalDocumentsServiceConfig } from \"./service-profile\";\nexport type { CancelOrReturnInput, CancelOrReturnResult } from \"./types\";\nexport type { LinkPaymentInput, LinkPaymentResult } from \"./payment-link\";\n\nexport interface SweepReport {\n readonly advanced: Array<{ readonly documentId: string; readonly status: FiscalDocument[\"status\"] }>;\n readonly failures: Array<{ readonly documentId: string; readonly message: string }>;\n}\n\nexport interface IssueInput {\n readonly ownerId: string;\n readonly subjectId: string;\n readonly issuingPointId: string;\n readonly model: FiscalDocumentModel;\n /**\n * NFC-e only, at a point with a contingency series: how long (ms, from this\n * call) the online send may go unanswered before the sale goes offline on\n * that series — a caller whose paper cannot wait (a counter, 10 s). A live\n * online document numbered this long ago and still unanswered goes offline\n * at once. Absent: the send's own timeout and the sweep's rules.\n */\n readonly onlineDeadlineMs?: number;\n}\n\n/** How long an NFC-e may wait in contingency before it must be transmitted (24 h); the warning goes out at 20 h. */\nexport const CONTINGENCY_WARNING_AFTER_MS = 20 * 3_600_000;\n\n/** A step's failure that no retry will cure: the document waits for a person. */\nconst NEEDS_A_PERSON = new Set([\"NOT_SUPPORTED\", \"NOT_ISSUABLE\", \"NOT_FOUND\", \"INVALID_INPUT\", \"SERIES_EXHAUSTED\"]);\n\nasync function issuable({ ctx }: Deps, ownerId: string, issuingPointId: string, model: FiscalDocumentModel) {\n const profile = await ctx.requireProfile(ownerId);\n if (profile.documentPolicy !== \"ISSUED_HERE\") {\n throw new FiscalDocumentError(\"NOT_ISSUABLE\", `owner ${ownerId}'s documentPolicy is ${profile.documentPolicy}.`);\n }\n const point = await ctx.requirePoint(ownerId, issuingPointId);\n if (point.model !== model) throw new FiscalDocumentError(\"INVALID_INPUT\", `issuing point ${point.id} issues ${point.model}, not ${model}.`);\n return { profile, point };\n}\n\nasync function liveDocument({ config }: Deps, input: Omit<IssueInput, \"issuingPointId\">): Promise<FiscalDocument | null> {\n const live = (await config.store.listBySubject(input.ownerId, input.subjectId, input.model)).filter(isLive);\n return live[live.length - 1] ?? null;\n}\n\nasync function requireDocument({ config }: Deps, ownerId: string, documentId: string): Promise<FiscalDocument> {\n const document = await config.store.getDocument(ownerId, documentId);\n if (document === null) throw new FiscalDocumentError(\"NOT_FOUND\", `owner ${ownerId} has no document ${documentId}.`);\n return document;\n}\n\n/** Number a new document — or, when the subject already has a live one (a concurrent call won), answer that one. */\nasync function numberOrExisting(deps: Deps, input: Omit<IssueInput, \"issuingPointId\">, create: () => Promise<FiscalDocument>) {\n try {\n return { document: await create(), created: true };\n } catch (error) {\n if (!(error instanceof FiscalDocumentError) || error.code !== \"SUBJECT_HAS_DOCUMENT\") throw error;\n const existing = await liveDocument(deps, input);\n if (existing === null) throw error;\n return { document: existing, created: false };\n }\n}\n\nasync function issue(deps: Deps, input: IssueInput): Promise<FiscalDocument> {\n assertOnlineDeadline(input.onlineDeadlineMs);\n const deadlineAt = input.onlineDeadlineMs === undefined ? null : Date.now() + input.onlineDeadlineMs;\n const { profile, point } = await issuable(deps, input.ownerId, input.issuingPointId, input.model);\n const existing = await liveDocument(deps, input);\n if (existing !== null) return answerLive(deps.ctx, existing, profile, input.onlineDeadlineMs);\n const signing = await deps.ctx.material(profile);\n const draft = await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: input.subjectId, model: input.model });\n assertDraftFits(draft, input.model);\n const numbered = await numberOrExisting(deps, input, () =>\n deps.ctx.createNumbered({ profile, point, subjectId: input.subjectId, model: input.model, seriesKind: \"ONLINE\", draft }),\n );\n if (!numbered.created) return answerLive(deps.ctx, numbered.document, profile, input.onlineDeadlineMs);\n return submit(deps.ctx, numbered.document, profile, point, signing, deadlineAt);\n}\n\n/** Sign the sale offline at once (the register knows it is offline). A failure leaves it PENDING for the sweep. */\nasync function issueOffline(deps: Deps, input: Omit<IssueInput, \"model\">): Promise<FiscalDocument> {\n const target = { ...input, model: \"NFCE\" as const };\n const { profile, point } = await issuable(deps, input.ownerId, input.issuingPointId, \"NFCE\");\n const existing = await liveDocument(deps, target);\n if (existing !== null) return existing;\n const signing = await deps.ctx.material(profile);\n const draft = await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: input.subjectId, model: \"NFCE\" });\n assertDraftFits(draft, \"NFCE\");\n const numbered = await numberOrExisting(deps, target, () =>\n deps.ctx.createNumbered({ profile, point, subjectId: input.subjectId, model: \"NFCE\", seriesKind: \"CONTINGENCY\", draft }),\n );\n return numbered.created ? signPending(deps.ctx, numbered.document, profile, signing) : numbered.document;\n}\n\n/**\n * A contingency NFC-e SEFAZ rejected on transmission: the buyer holds its\n * DANFE, so the number is never voided. The store corrects the sale (the\n * host's `SaleSource` answers the corrected one) and it is signed again\n * under the SAME series, number and key code, then transmitted by the job.\n */\n/** The fields a buyer's DANFE prints and its QR code encodes, which a resend may never change. */\nfunction printedFieldsChange(document: FiscalDocument, totals: DocumentTotals, buyerTaxId: string | null): boolean {\n return totals.totalCents !== document.totals.totalCents || buyerTaxId !== document.buyerTaxId;\n}\n\n/**\n * A contingency NFC-e SEFAZ rejected on transmission: the buyer holds its\n * DANFE, so the number is never voided. The store corrects the sale (the\n * host's `SaleSource` answers the corrected one) and it is signed again\n * under the SAME series, number and key code, then transmitted by the job.\n * A correction that would change the total or the buyer's document — what\n * the DANFE prints and its QR encodes — is refused: that sale needs a new\n * note, issued by a person (decided on FUT-2237).\n */\nasync function resendContingency(deps: Deps, input: { ownerId: string; documentId: string }): Promise<FiscalDocument> {\n const document = await requireDocument(deps, input.ownerId, input.documentId);\n if (document.status !== \"REJECTED\" || document.seriesKind !== \"CONTINGENCY\" || document.contingency === null) {\n throw new FiscalDocumentError(\"TRANSITION_REFUSED\", `document ${document.id} is not a rejected contingency NFC-e.`);\n }\n const profile = await deps.ctx.requireProfile(input.ownerId);\n const draft = await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: document.subjectId, model: document.model });\n assertDraftFits(draft, document.model);\n const totals = totalsOf(draft);\n const buyerTaxId = draft.buyer?.document.number ?? null;\n if (printedFieldsChange(document, totals, buyerTaxId)) {\n throw new FiscalDocumentError(\n \"RESEND_CHANGES_PRINTED_FIELDS\",\n `the correction changes document ${document.id}'s total or buyer, which its DANFE prints: issue a new note.`,\n );\n }\n const sale = { ...draft, series: document.series, number: document.number, keyCode: document.keyCode, issuedAt: document.issuedAt, issuer: issuerOf(profile) };\n const outcome = await deps.config.issuer.signContingency({\n environment: document.environment,\n signing: await deps.ctx.material(profile),\n document: sale,\n contingency: document.contingency,\n });\n if (!outcome.ok) throw new FiscalDocumentError(\"NOT_ISSUABLE\", `the corrected sale could not be signed: ${outcome.error.class} ${outcome.error.code ?? \"\"}`.trim());\n const xmlKey = xmlKeys.signed(outcome.answer.accessKey);\n await deps.config.storage.put(xmlKey, outcome.answer.signedXml, \"application/xml\");\n return deps.ctx.advance(document, { kind: \"RESIGN\", answer: outcome.answer, sale, totals, buyerTaxId, xmlKey });\n}\n\nasync function cancel(\n deps: Deps,\n input: { ownerId: string; documentId: string; reason: string },\n): Promise<{ document: FiscalDocument; failure: IssuerFailure | null }> {\n assertReason(input.reason, \"reason\");\n const document = await requireDocument(deps, input.ownerId, input.documentId);\n if (document.status !== \"AUTHORIZED\" || document.accessKey === null || document.protocol === null) {\n throw new FiscalDocumentError(\"TRANSITION_REFUSED\", `document ${document.id} is ${document.status}; only an authorised document is cancelled.`);\n }\n const profile = await deps.ctx.requireProfile(input.ownerId);\n const outcome = await deps.config.issuer.cancel({\n model: document.model,\n environment: document.environment,\n signing: await deps.ctx.material(profile),\n accessKey: document.accessKey,\n protocol: document.protocol,\n reason: input.reason,\n });\n if (!outcome.ok) return { document, failure: outcome.error };\n const eventXmlKey = outcome.answer.eventXml === null ? null : xmlKeys.cancel(document.accessKey);\n if (eventXmlKey !== null) await deps.config.storage.put(eventXmlKey, outcome.answer.eventXml ?? \"\", \"application/xml\");\n const cancelled = await deps.ctx.advance(document, { kind: \"CANCEL\", answer: outcome.answer, reason: input.reason, eventXmlKey });\n return { document: cancelled, failure: null };\n}\n\n/** SEFAZ's refusals of a cancel that came too late: \"prazo de cancelamento superior ao previsto\". */\nexport const LATE_CANCEL_CODES = [\"501\"] as const;\n\nconst isLateCancel = (code: string | null): boolean => code !== null && (LATE_CANCEL_CODES as readonly string[]).includes(code);\n\n/** The subject's live return NF-e that quotes this key, if one was issued already. */\nasync function liveReturnOf(deps: Deps, document: FiscalDocument): Promise<FiscalDocument | null> {\n const returns = (await deps.config.store.listBySubject(document.ownerId, document.subjectId, \"NFE\")).filter(isLive);\n const quoting = returns.filter((candidate) => returnsDocument(candidate, document));\n return quoting[quoting.length - 1] ?? null;\n}\n\n/**\n * Cancel an authorised document; when SEFAZ refuses the cancel as LATE (501),\n * issue the buyer's return instead: an NF-e of entry on `returnPointId`, the\n * host's `SaleSource` answering the return sale for the document's subject\n * (`model: \"NFE\"`), which must quote this document's key. The document itself\n * stays AUTHORIZED: a return never cancels it.\n *\n * Idempotent: a document already cancelled, or already answered with a live\n * return, is answered as it stands, with no call to the issuer. A return the\n * sale source does not quote is refused before a number is drawn.\n */\nasync function cancelOrReturn(deps: Deps, input: CancelOrReturnInput): Promise<CancelOrReturnResult> {\n assertReason(input.reason, \"reason\");\n const document = await requireDocument(deps, input.ownerId, input.documentId);\n if (document.status === \"CANCELLED\") return { outcome: \"CANCELLED\", document, returnDocument: null, failure: null };\n const existing = document.accessKey === null ? null : await liveReturnOf(deps, document);\n if (existing !== null) return { outcome: \"RETURNED\", document, returnDocument: existing, failure: null };\n const cancelled = await cancel(deps, input);\n if (cancelled.failure === null) return { outcome: \"CANCELLED\", document: cancelled.document, returnDocument: null, failure: null };\n const late = cancelled.failure.class === \"REJECTED\" && isLateCancel(cancelled.failure.code);\n if (!late) return { outcome: \"REFUSED\", document: cancelled.document, returnDocument: null, failure: cancelled.failure };\n return { outcome: \"RETURNED\", document: cancelled.document, returnDocument: await issueReturn(deps, document, input.returnPointId), failure: cancelled.failure };\n}\n\n/** Whether `candidate` is a buyer's return NF-e of entry quoting `document`. */\nfunction returnsDocument(candidate: Pick<FiscalDocument, \"model\" | \"sale\">, document: FiscalDocument): boolean {\n const quotes = (candidate.sale.referencedDocuments ?? []).some((reference) => reference.accessKey === document.accessKey);\n return candidate.model === \"NFE\" && candidate.sale.purpose === \"RETURN\" && quotes;\n}\n\n/**\n * The return of a late-cancelled NFC-e. Refused, before any number is drawn,\n * for anything but an NFC-e, for a subject that already holds a live NF-e that\n * is not this return (the live index allows one per subject and model), and\n * for a sale source whose return does not quote the document.\n */\nasync function issueReturn(deps: Deps, document: FiscalDocument, returnPointId: string): Promise<FiscalDocument> {\n if (document.model !== \"NFCE\") {\n throw new FiscalDocumentError(\"RETURN_OF_NFCE_ONLY\", `document ${document.id} is an ${document.model}: only an NFC-e is answered with a buyer's return.`);\n }\n const live = (await deps.config.store.listBySubject(document.ownerId, document.subjectId, \"NFE\")).filter(isLive);\n if (live.length > 0) {\n throw new FiscalDocumentError(\"SUBJECT_HAS_DOCUMENT\", `subject ${document.subjectId} already holds a live NF-e that is not document ${document.id}'s return.`);\n }\n const draft = await deps.config.sales.saleFor({ ownerId: document.ownerId, subjectId: document.subjectId, model: \"NFE\" });\n if (!returnsDocument({ model: \"NFE\", sale: draft as FiscalDocument[\"sale\"] }, document)) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `the return the sale source answered for subject ${document.subjectId} does not quote document ${document.id}.`);\n }\n const returned = await issue(deps, { ownerId: document.ownerId, subjectId: document.subjectId, issuingPointId: returnPointId, model: \"NFE\" });\n if (returned.id === document.id || !returnsDocument(returned, document)) {\n throw new FiscalDocumentError(\"CONFLICT\", `subject ${document.subjectId}'s live NF-e is not document ${document.id}'s return.`);\n }\n return returned;\n}\n\n/** Whether a lookup's answer moves this document (a settled number moves only while it is owed one). */\nfunction lookupMoves(document: FiscalDocument): boolean {\n if (!canTransition(document.status, \"LOOKUP\")) return false;\n if (document.status === \"REPLACED\" || document.status === \"REJECTED\") return document.numberVoid === \"LOOKUP_FIRST\";\n return true;\n}\n\nasync function lookup(\n deps: Deps,\n input: { ownerId: string; documentId: string },\n): Promise<{ document: FiscalDocument; answer: LookedUpDocument | null; failure: IssuerFailure | null }> {\n const document = await requireDocument(deps, input.ownerId, input.documentId);\n if (document.accessKey === null) throw new FiscalDocumentError(\"NOT_FOUND\", `document ${document.id} has no access key yet.`);\n const profile = await deps.ctx.requireProfile(input.ownerId);\n const outcome = await deps.config.issuer.lookup({\n model: document.model,\n environment: document.environment,\n signing: await deps.ctx.material(profile),\n accessKey: document.accessKey,\n });\n if (!outcome.ok) return { document, answer: null, failure: outcome.error };\n if (!lookupMoves(document)) return { document, answer: outcome.answer, failure: null };\n const xmlKey = document.status === \"SUBMITTED\" ? await storeNfeProc(deps.ctx, document, outcome.answer) : undefined;\n const looked = await deps.ctx.advance(document, { kind: \"LOOKUP\", answer: outcome.answer, ...(xmlKey === undefined ? {} : { xmlKey }) });\n // A live REJECTED number found SEFAZ's is back to SUBMITTED: settle it now if its XML is held.\n const after = document.status === \"REJECTED\" ? await settleWithXml(deps.ctx, looked, outcome.answer) : looked;\n return { document: after, answer: outcome.answer, failure: null };\n}\n\n/** One step of the sweep on one document: whatever it is owed next. */\nasync function step({ ctx }: Deps, document: FiscalDocument): Promise<FiscalDocument> {\n const profile = await ctx.requireProfile(document.ownerId);\n const signing = await ctx.material(profile);\n if (document.numberVoid !== null) return settleNumber(ctx, document, profile, signing);\n if (document.status === \"CONTINGENCY\") return transmit(ctx, document, signing);\n if (document.seriesKind === \"CONTINGENCY\") return signPending(ctx, document, profile, signing);\n const point = await ctx.requirePoint(document.ownerId, document.issuingPointId);\n return submit(ctx, document, profile, point, signing);\n}\n\n/** A step that threw is never silent: the document is deferred, or handed to a person when no retry will cure it. */\nasync function deferThrown(deps: Deps, document: FiscalDocument, error: unknown): Promise<void> {\n if (error instanceof FiscalDocumentError && error.code === \"CONFLICT\") return;\n const attention = error instanceof FiscalDocumentError && NEEDS_A_PERSON.has(error.code);\n const reason = error instanceof Error ? error.message : \"unknown failure\";\n const current = (await deps.config.store.getDocument(document.ownerId, document.id)) ?? document;\n await deps.ctx.advance(current, { kind: \"DEFER\", reason, error: null, attention }).catch(() => undefined);\n}\n\nasync function run(deps: Deps, documents: readonly FiscalDocument[]): Promise<SweepReport> {\n const report: SweepReport = { advanced: [], failures: [] };\n for (const document of documents) {\n try {\n const after = await step(deps, document);\n report.advanced.push({ documentId: after.id, status: after.status });\n } catch (error) {\n report.failures.push({ documentId: document.id, message: error instanceof Error ? error.message : \"unknown failure\" });\n await deferThrown(deps, document, error);\n }\n }\n return report;\n}\n\n/** Tell the owner of every NFC-e 20 h into contingency (the transmission deadline is 24 h), once each. */\nasync function warnContingencyDeadlines(deps: Deps, limit: number): Promise<number> {\n const signedBefore = new Date(deps.config.now().getTime() - CONTINGENCY_WARNING_AFTER_MS).toISOString();\n const due = await deps.config.store.listContingencyDeadline({ signedBefore, limit });\n for (const document of due) {\n const warned = await deps.ctx.advance(document, { kind: \"WARN\" });\n await deps.config.notify.emit({\n type: FISCAL_CONTINGENCY_DEADLINE,\n recipient: { tenantId: document.ownerId, permission: FISCAL_ISSUE },\n payload: { documentId: warned.id, subjectId: warned.subjectId, series: warned.series, number: warned.number, since: warned.contingency?.since ?? \"\" },\n });\n }\n return due.length;\n}\n\nexport function createFiscalDocuments(config: FiscalDocumentsServiceConfig) {\n assertConfig(config);\n if (typeof config.cipher?.encrypt !== \"function\") throw new TypeError(\"createFiscalDocuments needs cipher.\");\n if (typeof config.readCertificate !== \"function\") throw new TypeError(\"createFiscalDocuments needs readCertificate.\");\n const deps: Deps = { ctx: new FiscalContext(config), config };\n const { store } = config;\n return {\n getProfile: (ownerId: string) => store.getProfile(ownerId),\n saveProfile: saveProfile.bind(null, deps),\n uploadCertificate: uploadCertificate.bind(null, deps),\n listIssuingPoints: (ownerId: string) => store.listIssuingPoints(ownerId),\n createIssuingPoint: createIssuingPoint.bind(null, deps),\n /** Issue the subject's document, or answer the live one it has. A rejection is final; anything SEFAZ may still answer is the sweep's. */\n issue: issue.bind(null, deps),\n issueOffline: issueOffline.bind(null, deps),\n resendContingency: resendContingency.bind(null, deps),\n /** Cancel an authorised document. A refusal (late, say) answers the issuer's failure and changes nothing. */\n cancel: cancel.bind(null, deps),\n /**\n * Cancel an authorised document, or — when SEFAZ says the cancel is too late\n * (501) — issue the buyer's return NF-e of entry quoting it. Idempotent.\n */\n cancelOrReturn: cancelOrReturn.bind(null, deps),\n /** Link payment transactions to an authorised document (event 110300), once each. Idempotent. */\n linkPayment: linkPayment.bind(null, deps),\n /** Ask SEFAZ what it knows of the key; a state the answer moves is recorded. */\n lookup: lookup.bind(null, deps),\n /** A person takes a document back from `attention`; the sweep tries it again. */\n async release(input: { ownerId: string; documentId: string }): Promise<FiscalDocument> {\n return deps.ctx.advance(await requireDocument(deps, input.ownerId, input.documentId), { kind: \"RELEASE\" });\n },\n getDocument: requireDocument.bind(null, deps),\n listBySubject: (ownerId: string, subjectId: string, model: FiscalDocumentModel) => store.listBySubject(ownerId, subjectId, model),\n async listEvents(ownerId: string, documentId: string) {\n await requireDocument(deps, ownerId, documentId);\n return store.listEvents(documentId);\n },\n /** One pass of the retry sweep: PENDING/SUBMITTED documents and owed numbers whose next attempt has come. */\n sweep: async (limit: number): Promise<SweepReport> => run(deps, await store.listDue({ now: deps.ctx.nowIso(), limit })),\n /** One pass of the contingency transmission, then the 20-hour deadline warnings. */\n async transmitContingency(limit: number): Promise<SweepReport> {\n const report = await run(deps, await store.listContingency({ now: deps.ctx.nowIso(), limit }));\n await warnContingencyDeadlines(deps, limit);\n return report;\n },\n };\n}\n\n\nexport type FiscalDocuments = ReturnType<typeof createFiscalDocuments>;\n","/**\n * The reference {@link FiscalStore}: in memory, for tests and harnesses —\n * the role `createMemory*Store` plays in the packages that own storage seams.\n * It keeps the same promises as the SQL store (`./sql-store`): a draw and the\n * insert built from it commit together (a `build` that throws leaves the\n * counter untouched), a replaced document is advanced before its replacement\n * is inserted, and a subject has at most one live document per model.\n */\n\nimport { FiscalDocumentError } from \"./errors\";\nimport type { FiscalStore, NumberRequest } from \"./ports\";\nimport type { EmitterProfile, IssuingPoint } from \"./profile\";\nimport { type FiscalDocument, type FiscalDocumentEvent, OWED_VOIDS, isLive } from \"./types\";\n\nconst MAX_NUMBER = 999_999_999;\n\nexport interface MemoryFiscalStore extends FiscalStore {\n /** Every event, in order, for assertions. */\n readonly events: FiscalDocumentEvent[];\n /** The next number each counter would hand out, keyed `cnpj|environment|model|series`. */\n readonly counters: Map<string, number>;\n}\n\nfunction counterKey(request: Pick<NumberRequest, \"issuerCnpj\" | \"environment\" | \"model\" | \"series\">): string {\n return `${request.issuerCnpj}|${request.environment}|${request.model}|${request.series}`;\n}\n\ninterface State {\n readonly counters: Map<string, number>;\n readonly seriesOwner: Map<string, string>;\n readonly documents: Map<string, FiscalDocument>;\n readonly events: FiscalDocumentEvent[];\n}\n\n/** Open a series' counter in both environments; a series belongs to one issuing point. */\nfunction openCounter(state: State, point: IssuingPoint, issuerCnpj: string, series: number, first: number): void {\n for (const environment of [\"homologacao\", \"producao\"] as const) {\n const key = counterKey({ issuerCnpj, environment, model: point.model, series });\n const owner = state.seriesOwner.get(key);\n if (owner !== undefined && owner !== point.id) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `series ${series} already belongs to issuing point ${owner}.`);\n }\n }\n for (const environment of [\"homologacao\", \"producao\"] as const) {\n const key = counterKey({ issuerCnpj, environment, model: point.model, series });\n state.seriesOwner.set(key, point.id);\n state.counters.set(key, first);\n }\n}\n\nfunction isDue(document: FiscalDocument, now: string): boolean {\n if (document.attention || document.nextAttemptAt === null || document.nextAttemptAt > now) return false;\n return document.status === \"PENDING\" || document.status === \"SUBMITTED\" || OWED_VOIDS.includes(document.numberVoid ?? \"INUTILIZED\");\n}\n\nfunction save(state: State, previous: FiscalDocument, transition: { document: FiscalDocument; event: FiscalDocumentEvent }): boolean {\n const stored = state.documents.get(previous.id);\n if (stored === undefined || stored.updatedAt !== previous.updatedAt || stored.status !== previous.status) return false;\n state.documents.set(transition.document.id, transition.document);\n state.events.push(transition.event);\n return true;\n}\n\nfunction hasLive(state: State, document: FiscalDocument): boolean {\n return [...state.documents.values()].some(\n (other) => other.ownerId === document.ownerId && other.subjectId === document.subjectId && other.model === document.model && isLive(other),\n );\n}\n\nexport function createMemoryFiscalStore(): MemoryFiscalStore {\n const profiles = new Map<string, EmitterProfile>();\n const points = new Map<string, IssuingPoint>();\n const state: State = { counters: new Map(), seriesOwner: new Map(), documents: new Map(), events: [] };\n const ordered = (key: (d: FiscalDocument) => string) =>\n [...state.documents.values()].sort((a, b) => key(a).localeCompare(key(b)));\n\n return {\n events: state.events,\n counters: state.counters,\n getProfile: async (ownerId) => profiles.get(ownerId) ?? null,\n saveProfile: async (profile) => void profiles.set(profile.ownerId, profile),\n async getIssuingPoint(ownerId, id) {\n const point = points.get(id);\n return point?.ownerId === ownerId ? point : null;\n },\n listIssuingPoints: async (ownerId) => [...points.values()].filter((point) => point.ownerId === ownerId),\n async createIssuingPoint(point, issuerCnpj, firstNumber) {\n if (points.has(point.id)) throw new FiscalDocumentError(\"INVALID_INPUT\", `issuing point ${point.id} exists.`);\n openCounter(state, point, issuerCnpj, point.onlineSeries, firstNumber.online);\n if (point.contingencySeries !== null) openCounter(state, point, issuerCnpj, point.contingencySeries, firstNumber.contingency);\n points.set(point.id, point);\n },\n async createDocument(request, build, replace) {\n const key = counterKey(request);\n const number = state.counters.get(key);\n if (number === undefined || state.seriesOwner.get(key) !== request.issuingPointId) {\n throw new FiscalDocumentError(\"NOT_FOUND\", `no counter for series ${request.series} on issuing point ${request.issuingPointId}.`);\n }\n if (number > MAX_NUMBER) throw new FiscalDocumentError(\"SERIES_EXHAUSTED\", `series ${request.series} has no number left.`);\n const document = build(number);\n if (state.documents.has(document.id)) throw new FiscalDocumentError(\"INVALID_INPUT\", `document ${document.id} exists.`);\n const snapshot = new Map(state.documents);\n if (replace !== undefined && !save(state, replace.previous, replace.transition)) {\n throw new FiscalDocumentError(\"CONFLICT\", `document ${replace.previous.id} moved before it was replaced.`);\n }\n if (hasLive(state, document)) {\n // The replace and the insert are one transaction: undo the replace.\n state.documents.clear();\n for (const [id, kept] of snapshot) state.documents.set(id, kept);\n if (replace !== undefined) state.events.pop();\n throw new FiscalDocumentError(\"SUBJECT_HAS_DOCUMENT\", `subject ${document.subjectId} already has a live ${document.model}.`);\n }\n state.counters.set(key, number + 1);\n state.documents.set(document.id, document);\n return document;\n },\n async getDocument(ownerId, id) {\n const document = state.documents.get(id);\n return document?.ownerId === ownerId ? document : null;\n },\n listBySubject: async (ownerId, subjectId, model) =>\n ordered((d) => d.createdAt).filter((d) => d.ownerId === ownerId && d.subjectId === subjectId && d.model === model),\n listEvents: async (documentId) => state.events.filter((event) => event.documentId === documentId),\n saveTransition: async (previous, transition) => save(state, previous, transition),\n listDue: async ({ now, limit }) =>\n ordered((d) => d.nextAttemptAt ?? \"\").filter((document) => isDue(document, now)).slice(0, limit),\n listContingency: async ({ now, limit }) =>\n ordered((d) => d.nextAttemptAt ?? \"\")\n .filter((d) => d.status === \"CONTINGENCY\" && !d.attention && d.nextAttemptAt !== null && d.nextAttemptAt <= now)\n .slice(0, limit),\n listContingencyDeadline: async ({ signedBefore, limit }) =>\n ordered((d) => d.createdAt)\n .filter((d) => d.status === \"CONTINGENCY\" && d.deadlineWarnedAt === null && Date.parse(d.contingency?.since ?? \"\") < Date.parse(signedBefore))\n .slice(0, limit),\n listExpiringCertificates: async (before) =>\n [...profiles.values()].filter((p) => p.certificateExpiresAt !== null && p.certificateExpiresAt < before),\n };\n}\n","/**\n * The number draw, as one SQL statement over the package's migration\n * (`fiscal_number_counters`). A host's `FiscalStore.createDocument` runs it\n * and the document INSERT in ONE transaction: the row lock this UPDATE takes\n * serialises concurrent draws on a series, and a failed insert rolls the\n * counter back with it, so a series has no gap a failed write made. The only\n * gaps left are numbers SEFAZ never used (a rejection, a replaced document),\n * which the sweep inutilizes.\n *\n * Parameters: `$1` the issuer's CNPJ, `$2` environment, `$3` model, `$4` series,\n * `$5` issuing point id. No row comes back when the series is not that\n * point's; an exhausted series fails the counter's CHECK (at most\n * 1 000 000 000, the next number after 999 999 999), and the transaction with it.\n */\nexport const FISCAL_NEXT_NUMBER_SQL = `UPDATE \"fiscal_number_counters\"\nSET \"next_number\" = \"next_number\" + 1, \"updated_at\" = CURRENT_TIMESTAMP\nWHERE \"issuer_cnpj\" = $1 AND \"environment\" = $2 AND \"model\" = $3 AND \"series\" = $4 AND \"issuing_point_id\" = $5\nRETURNING \"next_number\" - 1 AS \"number\"`;\n","/**\n * Rows of the package's tables (`prisma/migrations`) to the records the\n * service holds, and back. Raw SQL through the host's Prisma client answers\n * snake_case columns, `Date` for a timestamp, a parsed object for a JSONB\n * column, and a `bigint` or a string for a BIGSERIAL; every one is read here.\n */\n\nimport type { EmitterProfile, IssuingPoint } from \"./profile\";\nimport type { FiscalDocument, FiscalDocumentEvent } from \"./types\";\n\nexport type Row = Record<string, unknown>;\n\n/** A timestamp column as ISO 8601 UTC; the columns are UTC by the Prisma convention. */\nfunction iso(value: unknown): string | null {\n if (value === null || value === undefined) return null;\n const date = value instanceof Date ? value : new Date(`${String(value).replace(\" \", \"T\")}${/Z|[+-]\\d{2}:?\\d{2}$/.test(String(value)) ? \"\" : \"Z\"}`);\n return date.toISOString();\n}\n\nfunction requiredIso(value: unknown): string {\n return iso(value) ?? \"\";\n}\n\n/** A DATE column as `YYYY-MM-DD`. */\nfunction day(value: unknown): string {\n return value instanceof Date ? value.toISOString().slice(0, 10) : String(value).slice(0, 10);\n}\n\nfunction json<T>(value: unknown): T {\n return (typeof value === \"string\" ? JSON.parse(value) : value) as T;\n}\n\nconst text = (value: unknown): string | null => (value === null || value === undefined ? null : String(value));\n\n/** The document's columns, in the order `documentValues` writes them. */\nexport const DOCUMENT_COLUMNS = [\n \"id\", \"owner_id\", \"issuer_cnpj\", \"subject_id\", \"issuing_point_id\", \"model\", \"environment\", \"series_kind\", \"series\",\n \"number\", \"key_code\", \"status\", \"sale\", \"totals\", \"buyer_tax_id\", \"access_key\", \"protocol\", \"status_code\",\n \"status_reason\", \"last_error_class\", \"outcome_unknown\", \"issued_at\", \"authorized_at\", \"contingency\", \"cancelled_at\",\n \"cancel_reason\", \"cancel_protocol\", \"replaced_by_id\", \"number_void\", \"xml_key\", \"event_xml_key\", \"attempts\",\n \"failures\", \"next_attempt_at\", \"attention\", \"deadline_warned_at\", \"created_at\", \"updated_at\",\n] as const;\n\nconst JSON_COLUMNS = new Set([\"sale\", \"totals\", \"contingency\"]);\nconst TIME_COLUMNS = new Set([\"next_attempt_at\", \"deadline_warned_at\", \"created_at\", \"updated_at\"]);\n\n/** The SQL placeholder of a column, with the cast its type needs. */\nexport function placeholder(column: string, index: number): string {\n if (JSON_COLUMNS.has(column)) return `$${index}::jsonb`;\n if (TIME_COLUMNS.has(column)) return `$${index}::timestamp(3)`;\n return `$${index}`;\n}\n\nexport function documentValues(d: FiscalDocument): unknown[] {\n return [\n d.id, d.ownerId, d.issuerCnpj, d.subjectId, d.issuingPointId, d.model, d.environment, d.seriesKind, d.series,\n d.number, d.keyCode, d.status, JSON.stringify(d.sale), JSON.stringify(d.totals), d.buyerTaxId, d.accessKey,\n d.protocol, d.statusCode, d.statusReason, d.lastErrorClass, d.outcomeUnknown, d.issuedAt, d.authorizedAt,\n d.contingency === null ? null : JSON.stringify(d.contingency), d.cancelledAt, d.cancelReason, d.cancelProtocol,\n d.replacedById, d.numberVoid, d.xmlKey, d.eventXmlKey, d.attempts, d.failures, d.nextAttemptAt, d.attention,\n d.deadlineWarnedAt, d.createdAt, d.updatedAt,\n ];\n}\n\nexport function documentOf(row: Row): FiscalDocument {\n return {\n id: String(row[\"id\"]),\n ownerId: String(row[\"owner_id\"]),\n issuerCnpj: String(row[\"issuer_cnpj\"]),\n subjectId: String(row[\"subject_id\"]),\n issuingPointId: String(row[\"issuing_point_id\"]),\n model: row[\"model\"] as FiscalDocument[\"model\"],\n environment: row[\"environment\"] as FiscalDocument[\"environment\"],\n seriesKind: row[\"series_kind\"] as FiscalDocument[\"seriesKind\"],\n series: Number(row[\"series\"]),\n number: Number(row[\"number\"]),\n keyCode: String(row[\"key_code\"]),\n status: row[\"status\"] as FiscalDocument[\"status\"],\n sale: json(row[\"sale\"]),\n totals: json(row[\"totals\"]),\n buyerTaxId: text(row[\"buyer_tax_id\"]),\n accessKey: text(row[\"access_key\"]),\n protocol: text(row[\"protocol\"]),\n statusCode: text(row[\"status_code\"]),\n statusReason: text(row[\"status_reason\"]),\n lastErrorClass: text(row[\"last_error_class\"]) as FiscalDocument[\"lastErrorClass\"],\n outcomeUnknown: row[\"outcome_unknown\"] === true,\n issuedAt: String(row[\"issued_at\"]),\n authorizedAt: text(row[\"authorized_at\"]),\n contingency: row[\"contingency\"] === null ? null : json(row[\"contingency\"]),\n cancelledAt: text(row[\"cancelled_at\"]),\n cancelReason: text(row[\"cancel_reason\"]),\n cancelProtocol: text(row[\"cancel_protocol\"]),\n replacedById: text(row[\"replaced_by_id\"]),\n numberVoid: text(row[\"number_void\"]) as FiscalDocument[\"numberVoid\"],\n xmlKey: text(row[\"xml_key\"]),\n eventXmlKey: text(row[\"event_xml_key\"]),\n attempts: Number(row[\"attempts\"]),\n failures: Number(row[\"failures\"]),\n nextAttemptAt: iso(row[\"next_attempt_at\"]),\n attention: row[\"attention\"] === true,\n deadlineWarnedAt: iso(row[\"deadline_warned_at\"]),\n createdAt: requiredIso(row[\"created_at\"]),\n updatedAt: requiredIso(row[\"updated_at\"]),\n };\n}\n\nexport function eventOf(row: Row): FiscalDocumentEvent {\n return {\n documentId: String(row[\"document_id\"]),\n kind: row[\"kind\"] as FiscalDocumentEvent[\"kind\"],\n fromStatus: row[\"from_status\"] as FiscalDocumentEvent[\"fromStatus\"],\n toStatus: row[\"to_status\"] as FiscalDocumentEvent[\"toStatus\"],\n at: requiredIso(row[\"at\"]),\n errorClass: text(row[\"error_class\"]) as FiscalDocumentEvent[\"errorClass\"],\n code: text(row[\"code\"]),\n answer: row[\"answer\"] === null ? null : json(row[\"answer\"]),\n };\n}\n\nexport const PROFILE_COLUMNS = [\n \"owner_id\", \"cnpj\", \"state_registration\", \"municipal_registration\", \"cnae\", \"legal_name\", \"trade_name\", \"tax_regime\",\n \"regime\", \"regime_effective_from\", \"restaurant_regime\", \"address\", \"environment\", \"document_policy\",\n \"signing_identity\", \"certificate_ciphertext\", \"certificate_password_ciphertext\", \"certificate_expires_at\", \"csc_id\",\n \"csc_ciphertext\", \"consent_recorded_at\", \"updated_at\",\n] as const;\n\nexport function profilePlaceholder(column: string, index: number): string {\n if (column === \"address\") return `$${index}::jsonb`;\n if (column === \"regime_effective_from\") return `$${index}::date`;\n if (column.endsWith(\"_at\")) return `$${index}::timestamp(3)`;\n return `$${index}`;\n}\n\nexport function profileValues(p: EmitterProfile): unknown[] {\n return [\n p.ownerId, p.cnpj, p.stateRegistration, p.municipalRegistration, p.cnae, p.legalName, p.tradeName, p.taxRegime,\n p.regime, p.regimeEffectiveFrom, p.restaurantRegime, JSON.stringify(p.address), p.environment, p.documentPolicy,\n p.signingIdentity, p.certificateCiphertext, p.certificatePasswordCiphertext, p.certificateExpiresAt, p.cscId,\n p.cscCiphertext, p.consentRecordedAt, p.updatedAt,\n ];\n}\n\nexport function profileOf(row: Row): EmitterProfile {\n return {\n ownerId: String(row[\"owner_id\"]),\n cnpj: String(row[\"cnpj\"]),\n stateRegistration: String(row[\"state_registration\"]),\n municipalRegistration: text(row[\"municipal_registration\"]),\n cnae: text(row[\"cnae\"]),\n legalName: String(row[\"legal_name\"]),\n tradeName: text(row[\"trade_name\"]),\n taxRegime: row[\"tax_regime\"] as EmitterProfile[\"taxRegime\"],\n regime: row[\"regime\"] as EmitterProfile[\"regime\"],\n regimeEffectiveFrom: day(row[\"regime_effective_from\"]),\n restaurantRegime: row[\"restaurant_regime\"] === true,\n address: json(row[\"address\"]),\n environment: row[\"environment\"] as EmitterProfile[\"environment\"],\n documentPolicy: row[\"document_policy\"] as EmitterProfile[\"documentPolicy\"],\n signingIdentity: row[\"signing_identity\"] as EmitterProfile[\"signingIdentity\"],\n certificateCiphertext: text(row[\"certificate_ciphertext\"]),\n certificatePasswordCiphertext: text(row[\"certificate_password_ciphertext\"]),\n certificateExpiresAt: iso(row[\"certificate_expires_at\"]),\n cscId: text(row[\"csc_id\"]),\n cscCiphertext: text(row[\"csc_ciphertext\"]),\n consentRecordedAt: iso(row[\"consent_recorded_at\"]),\n updatedAt: requiredIso(row[\"updated_at\"]),\n };\n}\n\nexport function pointOf(row: Row): IssuingPoint {\n return {\n id: String(row[\"id\"]),\n ownerId: String(row[\"owner_id\"]),\n model: row[\"model\"] as IssuingPoint[\"model\"],\n onlineSeries: Number(row[\"online_series\"]),\n contingencySeries: row[\"contingency_series\"] === null ? null : Number(row[\"contingency_series\"]),\n createdAt: requiredIso(row[\"created_at\"]),\n };\n}\n","/**\n * `createPrismaFiscalStore` — the package's own {@link FiscalStore}, over the\n * host's Prisma client and the package's migration. A host passes its client\n * and nothing else: the numbering invariants live here, not in each host.\n *\n * - The draw and the insert are ONE transaction (`FISCAL_NEXT_NUMBER_SQL`):\n * the counter's row lock serialises concurrent draws, and a refused insert\n * gives the number back.\n * - Going offline replaces the online document in that same transaction,\n * before the insert, so a crash leaves exactly one live document.\n * - The per-subject guard is the partial unique index\n * `fiscal_documents_live_subject_key`: a second live document is refused as\n * `SUBJECT_HAS_DOCUMENT`, and nothing is drawn.\n * - A transition is saved only over the row it started from (`updated_at` and\n * `status`), with its event, in one transaction.\n *\n * It speaks raw SQL through the client's `$queryRawUnsafe` /\n * `$executeRawUnsafe` / `$transaction`, so it needs no generated model types\n * and works on the host's client whatever else its schema holds.\n */\n\nimport { FiscalDocumentError } from \"./errors\";\nimport type { Transition } from \"./machine\";\nimport type { FiscalStore, NumberRequest } from \"./ports\";\nimport { FISCAL_NEXT_NUMBER_SQL } from \"./sql\";\nimport {\n DOCUMENT_COLUMNS,\n PROFILE_COLUMNS,\n type Row,\n documentOf,\n documentValues,\n eventOf,\n placeholder,\n pointOf,\n profileOf,\n profilePlaceholder,\n profileValues,\n} from \"./sql-rows\";\nimport type { FiscalDocument } from \"./types\";\n\n/** The two raw-SQL methods of a Prisma client (or of its transaction client). */\nexport interface FiscalSqlClient {\n $queryRawUnsafe<T = unknown>(query: string, ...values: unknown[]): Promise<T>;\n $executeRawUnsafe(query: string, ...values: unknown[]): Promise<number>;\n}\n\n/** A Prisma client: the raw-SQL methods and an interactive transaction. */\nexport interface FiscalPrismaClient extends FiscalSqlClient {\n $transaction<T>(run: (tx: FiscalSqlClient) => Promise<T>): Promise<T>;\n}\n\nconst rows = (client: FiscalSqlClient, query: string, ...values: unknown[]) => client.$queryRawUnsafe<Row[]>(query, ...values);\n\nconst INSERT_DOCUMENT = `INSERT INTO \"fiscal_documents\" (${DOCUMENT_COLUMNS.map((c) => `\"${c}\"`).join(\", \")})\nVALUES (${DOCUMENT_COLUMNS.map((c, i) => placeholder(c, i + 1)).join(\", \")})`;\n\nconst MUTABLE = DOCUMENT_COLUMNS.filter((c) => c !== \"id\" && c !== \"created_at\");\n// $1 the id, $2... the mutable columns, then the row the transition started from.\nconst UPDATE_DOCUMENT = [\n `UPDATE \"fiscal_documents\" SET ${MUTABLE.map((c, i) => `\"${c}\" = ${placeholder(c, i + 2)}`).join(\", \")}`,\n `WHERE \"id\" = $1 AND \"updated_at\" = $${MUTABLE.length + 2}::timestamp(3) AND \"status\" = $${MUTABLE.length + 3}`,\n `RETURNING \"id\"`,\n].join(\"\\n\");\n\nfunction updateValues(document: FiscalDocument, previous: FiscalDocument): unknown[] {\n const all = documentValues(document);\n const mutable = MUTABLE.map((column) => all[DOCUMENT_COLUMNS.indexOf(column)]);\n return [document.id, ...mutable, previous.updatedAt, previous.status];\n}\n\nconst INSERT_EVENT = `INSERT INTO \"fiscal_document_events\" (\"id\", \"document_id\", \"kind\", \"from_status\", \"to_status\", \"at\", \"error_class\", \"code\", \"answer\")\nVALUES ($1, $2, $3, $4, $5, $6::timestamp(3), $7, $8, $9::jsonb)`;\n\nconst UPSERT_PROFILE = `INSERT INTO \"fiscal_emitter_profiles\" (${PROFILE_COLUMNS.map((c) => `\"${c}\"`).join(\", \")})\nVALUES (${PROFILE_COLUMNS.map((c, i) => profilePlaceholder(c, i + 1)).join(\", \")})\nON CONFLICT (\"owner_id\") DO UPDATE SET ${PROFILE_COLUMNS.filter((c) => c !== \"owner_id\").map((c) => `\"${c}\" = EXCLUDED.\"${c}\"`).join(\", \")}`;\n\nconst OWED = `(\"status\" IN ('PENDING', 'SUBMITTED') OR \"number_void\" IN ('LOOKUP_FIRST', 'INUTILIZE', 'CANCEL'))`;\n\n/** A unique-index or CHECK violation, recognised by its constraint's name in whatever error the client raised. */\nfunction violates(error: unknown, constraint: string): boolean {\n const text = error instanceof Error ? `${error.message} ${JSON.stringify((error as { meta?: unknown }).meta ?? \"\")}` : String(error);\n return text.includes(constraint);\n}\n\nasync function saveRow(tx: FiscalSqlClient, previous: FiscalDocument, { document, event }: Transition): Promise<boolean> {\n const updated = await rows(tx, UPDATE_DOCUMENT, ...updateValues(document, previous));\n if (updated.length === 0) return false;\n await tx.$executeRawUnsafe(\n INSERT_EVENT,\n globalThis.crypto.randomUUID(),\n event.documentId,\n event.kind,\n event.fromStatus,\n event.toStatus,\n event.at,\n event.errorClass,\n event.code,\n event.answer === null ? null : JSON.stringify(event.answer),\n );\n return true;\n}\n\nasync function draw(tx: FiscalSqlClient, request: NumberRequest): Promise<number> {\n try {\n const [row] = await rows(tx, FISCAL_NEXT_NUMBER_SQL, request.issuerCnpj, request.environment, request.model, request.series, request.issuingPointId);\n if (row === undefined) {\n throw new FiscalDocumentError(\"NOT_FOUND\", `no counter for series ${request.series} on issuing point ${request.issuingPointId}.`);\n }\n return Number(row[\"number\"]);\n } catch (error) {\n if (violates(error, \"fiscal_number_counters_next_number_check\")) {\n throw new FiscalDocumentError(\"SERIES_EXHAUSTED\", `series ${request.series} has no number left.`);\n }\n throw error;\n }\n}\n\nasync function insertDocument(tx: FiscalSqlClient, document: FiscalDocument): Promise<void> {\n try {\n await tx.$executeRawUnsafe(INSERT_DOCUMENT, ...documentValues(document));\n } catch (error) {\n if (violates(error, \"fiscal_documents_live_subject_key\")) {\n throw new FiscalDocumentError(\"SUBJECT_HAS_DOCUMENT\", `subject ${document.subjectId} already has a live ${document.model}.`);\n }\n throw error;\n }\n}\n\nasync function openCounters(tx: FiscalSqlClient, point: { id: string; model: string }, issuerCnpj: string, series: number, kind: string, first: number) {\n for (const environment of [\"homologacao\", \"producao\"]) {\n await tx.$executeRawUnsafe(\n `INSERT INTO \"fiscal_number_counters\" (\"issuer_cnpj\", \"environment\", \"model\", \"series\", \"issuing_point_id\", \"series_kind\", \"next_number\")\n VALUES ($1, $2, $3, $4, $5, $6, $7)`,\n issuerCnpj, environment, point.model, series, point.id, kind, first,\n );\n }\n}\n\ntype ProfileMethods = Pick<FiscalStore, \"getProfile\" | \"saveProfile\" | \"getIssuingPoint\" | \"listIssuingPoints\" | \"createIssuingPoint\" | \"listExpiringCertificates\">;\n\nfunction profileMethods(db: FiscalPrismaClient): ProfileMethods {\n return {\n async getProfile(ownerId) {\n const [row] = await rows(db, `SELECT * FROM \"fiscal_emitter_profiles\" WHERE \"owner_id\" = $1`, ownerId);\n return row === undefined ? null : profileOf(row);\n },\n async saveProfile(profile) {\n await db.$executeRawUnsafe(UPSERT_PROFILE, ...profileValues(profile));\n },\n async getIssuingPoint(ownerId, id) {\n const [row] = await rows(db, `SELECT * FROM \"fiscal_issuing_points\" WHERE \"id\" = $1 AND \"owner_id\" = $2`, id, ownerId);\n return row === undefined ? null : pointOf(row);\n },\n async listIssuingPoints(ownerId) {\n return (await rows(db, `SELECT * FROM \"fiscal_issuing_points\" WHERE \"owner_id\" = $1 ORDER BY \"created_at\", \"id\"`, ownerId)).map(pointOf);\n },\n createIssuingPoint: (point, issuerCnpj, firstNumber) => createIssuingPoint(db, point, issuerCnpj, firstNumber),\n async listExpiringCertificates(before) {\n return (\n await rows(db, `SELECT * FROM \"fiscal_emitter_profiles\" WHERE \"certificate_expires_at\" < $1::timestamp(3) ORDER BY \"owner_id\"`, before)\n ).map(profileOf);\n },\n };\n}\n\nasync function createIssuingPoint(db: FiscalPrismaClient, ...[point, issuerCnpj, firstNumber]: Parameters<FiscalStore[\"createIssuingPoint\"]>): Promise<void> {\n try {\n await db.$transaction(async (tx) => {\n await tx.$executeRawUnsafe(\n `INSERT INTO \"fiscal_issuing_points\" (\"id\", \"owner_id\", \"model\", \"online_series\", \"contingency_series\", \"created_at\")\n VALUES ($1, $2, $3, $4, $5, $6::timestamp(3))`,\n point.id, point.ownerId, point.model, point.onlineSeries, point.contingencySeries, point.createdAt,\n );\n await openCounters(tx, point, issuerCnpj, point.onlineSeries, \"ONLINE\", firstNumber.online);\n if (point.contingencySeries !== null) {\n await openCounters(tx, point, issuerCnpj, point.contingencySeries, \"CONTINGENCY\", firstNumber.contingency);\n }\n });\n } catch (error) {\n if (violates(error, \"fiscal_number_counters_pkey\")) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `a series of issuing point ${point.id} already belongs to another issuing point.`);\n }\n if (violates(error, \"fiscal_issuing_points_pkey\")) throw new FiscalDocumentError(\"INVALID_INPUT\", `issuing point ${point.id} exists.`);\n throw error;\n }\n}\n\nfunction documentMethods(db: FiscalPrismaClient): Omit<FiscalStore, keyof ProfileMethods> {\n const documents = async (query: string, ...values: unknown[]) => (await rows(db, query, ...values)).map(documentOf);\n return {\n createDocument: (request, build, replace) =>\n db.$transaction(async (tx) => {\n if (replace !== undefined && !(await saveRow(tx, replace.previous, replace.transition))) {\n throw new FiscalDocumentError(\"CONFLICT\", `document ${replace.previous.id} moved before it was replaced.`);\n }\n const document = build(await draw(tx, request));\n await insertDocument(tx, document);\n return document;\n }),\n async getDocument(ownerId, id) {\n const [document] = await documents(`SELECT * FROM \"fiscal_documents\" WHERE \"id\" = $1 AND \"owner_id\" = $2`, id, ownerId);\n return document ?? null;\n },\n listBySubject: (ownerId, subjectId, model) =>\n documents(\n `SELECT * FROM \"fiscal_documents\" WHERE \"owner_id\" = $1 AND \"subject_id\" = $2 AND \"model\" = $3 ORDER BY \"created_at\", \"id\"`,\n ownerId, subjectId, model,\n ),\n async listEvents(documentId) {\n return (await rows(db, `SELECT * FROM \"fiscal_document_events\" WHERE \"document_id\" = $1 ORDER BY \"seq\"`, documentId)).map(eventOf);\n },\n saveTransition: (previous, transition) => db.$transaction((tx) => saveRow(tx, previous, transition)),\n listDue: ({ now, limit }) =>\n documents(\n `SELECT * FROM \"fiscal_documents\" WHERE \"attention\" = false AND \"next_attempt_at\" <= $1::timestamp(3) AND ${OWED}\n ORDER BY \"next_attempt_at\", \"id\" LIMIT $2`,\n now, limit,\n ),\n listContingency: ({ now, limit }) =>\n documents(\n `SELECT * FROM \"fiscal_documents\" WHERE \"attention\" = false AND \"next_attempt_at\" <= $1::timestamp(3) AND \"status\" = 'CONTINGENCY'\n ORDER BY \"next_attempt_at\", \"id\" LIMIT $2`,\n now, limit,\n ),\n listContingencyDeadline: ({ signedBefore, limit }) =>\n documents(\n `SELECT * FROM \"fiscal_documents\" WHERE \"status\" = 'CONTINGENCY' AND \"deadline_warned_at\" IS NULL\n AND (\"contingency\" ->> 'since')::timestamptz < $1::timestamptz\n ORDER BY \"created_at\", \"id\" LIMIT $2`,\n signedBefore, limit,\n ),\n };\n}\n\nexport function createPrismaFiscalStore(config: { readonly prisma: FiscalPrismaClient }): FiscalStore {\n const db = config?.prisma;\n if (typeof db?.$transaction !== \"function\" || typeof db.$queryRawUnsafe !== \"function\") {\n throw new TypeError(\"createPrismaFiscalStore needs prisma: the host's Prisma client.\");\n }\n return { ...profileMethods(db), ...documentMethods(db) };\n}\n","/**\n * The document mapping's tax half: the engine's breakdown (`computeTax`)\n * onto the `SaleForDocument` lines a host's `SaleSource` answers. The engine\n * decides; this writes what it decided:\n *\n * - one document line per breakdown line, in the breakdown's order — so an\n * exclusion the engine segregated (the service charge passed to the staff\n * at most 15% of the food and drink, class 410019; a platform's retained\n * intermediation, 410020) IS its own item, with its class and no tax\n * (RCBS art. 399 §2), and a service charge the engine did not exclude is a\n * taxed item under the class the host passed;\n * - the IBS/CBS group from the line's figures (`vBC`, the nominal rates, the\n * reduction, the amounts), or no group at all where the engine answered\n * `NONE` (MEI, não contribuinte).\n *\n * What the engine does not know — the product code, NCM, CFOP, unit, the\n * ICMS, PIS and COFINS — arrives per line id from the host. A breakdown line\n * with no details is refused, never invented.\n */\n\nimport type { LineTax, TaxBreakdown } from \"../engine/types\";\nimport type { LineIbsCbs, SaleLine } from \"../sale/types\";\nimport { FiscalDocumentError } from \"./errors\";\n\n/** Everything a document line needs that the breakdown does not carry. */\nexport type LineDetails = Omit<SaleLine, \"id\" | \"quantity\" | \"valueCents\" | \"ibsCbs\">;\n\nconst SEGREGATED = new Set<LineTax[\"source\"]>([\"GORJETA_EXCLUDED\", \"INTERMEDIATION_EXCLUDED\"]);\n\nfunction ibsCbsOf(line: LineTax, breakdown: TaxBreakdown): LineIbsCbs | null {\n if (breakdown.treatment === \"NONE\") return null;\n const code = { cst: line.taxClass.cstIbsCbs, classCode: line.taxClass.cClassTrib };\n if (SEGREGATED.has(line.source)) return { ...code, figures: null };\n return {\n ...code,\n figures: {\n baseCents: line.taxBaseCents,\n reductionBp: line.reductionBp,\n cbsRateBp: line.cbsRateBp,\n cbsCents: line.cbsCents,\n ibsUfRateBp: line.ibsUfRateBp,\n ibsUfCents: line.ibsUfCents,\n ibsMunRateBp: line.ibsMunRateBp,\n ibsMunCents: line.ibsMunCents,\n },\n };\n}\n\nexport function documentLines(breakdown: TaxBreakdown, details: Readonly<Record<string, LineDetails>>): SaleLine[] {\n return breakdown.lines.map((line) => {\n const detail = details[line.lineId];\n if (detail === undefined) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `breakdown line ${line.lineId} has no document details.`);\n }\n return {\n ...detail,\n id: line.lineId,\n quantity: line.quantity,\n valueCents: line.valueCents,\n ibsCbs: ibsCbsOf(line, breakdown),\n };\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBO,SAAS,+BAA+B,QAAsD;A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iBAAiB,kBAAkB,KAAK,MAAM,2BAA2B;AAAA,IACzG;AACA,WAAO;AAAA,MACL,GAAG;AAAA,MACH,IAAI,KAAK;AAAA,MACT,UAAU,KAAK;AAAA,MACf,YAAY,KAAK;AAAA,MACjB,QAAQ,SAAS,MAAM,SAAS;AAAA,IAClC;AAAA,EACF,CAAC;AACH;AAdgB;","names":["send","run","send","transition","text","createIssuingPoint","transition"]}
|
|
1
|
+
{"version":3,"sources":["../../src/documents/ports.ts","../../src/documents/contingency-gaps.ts","../../src/documents/contingency-pass.ts","../../src/documents/contingency-xml.ts","../../src/documents/contingency.ts","../../src/documents/sql-rows.ts","../../src/documents/sql-blocks.ts","../../src/documents/signing.ts","../../src/documents/service-profile.ts","../../src/documents/nfe-proc.ts","../../src/documents/settle.ts","../../src/documents/payment-link.ts","../../src/documents/steps.ts","../../src/documents/service.ts","../../src/documents/memory-blocks.ts","../../src/documents/memory.ts","../../src/documents/sql.ts","../../src/documents/sql-store.ts","../../src/documents/lines.ts"],"sourcesContent":["/**\n * The ports a host implements for the document module. None has a default:\n * where the bytes live, how a secret is encrypted, what a sale is and where\n * the rows are stored are the host's answers, asked for by name.\n */\n\nimport type { SaleForDocument } from \"../sale/types\";\nimport type { SefazEnvironment } from \"../sidecar/types\";\nimport type { EmitterProfile, IssuingPoint } from \"./profile\";\nimport type { FiscalDocument, FiscalDocumentEvent, FiscalDocumentModel, SeriesKind } from \"./types\";\nimport type { Transition } from \"./machine\";\n\n/**\n * Encrypts the certificate, its password and the CSC at rest — the\n * `{ encrypt, decrypt }` shape `@12-apps/payments-backend` takes. Synchronous\n * or not, as the host's cipher is.\n */\nexport interface Cipher {\n encrypt(plaintext: string): string | Promise<string>;\n decrypt(ciphertext: string): string | Promise<string>;\n}\n\n/** Where the XMLs live (object storage, retained as the law asks: five years). */\nexport interface DocumentStorage {\n put(key: string, body: string, contentType: string): Promise<void>;\n get(key: string): Promise<string | null>;\n}\n\n/**\n * The host's sale in the package's neutral shape — everything but what the\n * package fills: the issuer (from the profile), the series and number (from\n * its counter), the key code and the issue time.\n */\nexport type SaleDraft = Omit<SaleForDocument, \"series\" | \"number\" | \"keyCode\" | \"issuer\" | \"issuedAt\">;\n\nexport interface SaleSource {\n saleFor(input: { readonly ownerId: string; readonly subjectId: string; readonly model: FiscalDocumentModel }): Promise<SaleDraft>;\n}\n\n/**\n * Which counter a new document draws from. SEFAZ numbers by the issuer's\n * CNPJ, the model and the series, so the counter is keyed by them: one CNPJ\n * can serve several owners, and they share its series.\n */\nexport interface NumberRequest {\n readonly ownerId: string;\n readonly issuerCnpj: string;\n readonly issuingPointId: string;\n readonly environment: SefazEnvironment;\n readonly model: FiscalDocumentModel;\n readonly seriesKind: SeriesKind;\n readonly series: number;\n}\n\n/**\n * The rows. `createPrismaFiscalStore` (`./sql-store`) is the package's own\n * implementation over the host's Prisma client; `createMemoryFiscalStore`\n * the reference for tests. Every method that writes is one transaction:\n *\n * - `createDocument` draws the next number of the series AND inserts the\n * document built from it, together — a refused insert gives the number\n * back, so the sequence has no gap a failed write made. With `replace`, the\n * document it replaces is advanced in the SAME transaction, before the\n * insert, so a crash can never leave both live. A second LIVE document for\n * the same (owner, subject, model) is refused with `SUBJECT_HAS_DOCUMENT`\n * (`isLive`), and nothing is drawn;\n * - `saveTransition` writes the document and appends its event, and refuses\n * (`false`) when the stored row's `updatedAt` or `status` is no longer the\n * one the transition started from, so two workers never both advance it.\n */\nexport interface FiscalStore {\n getProfile(ownerId: string): Promise<EmitterProfile | null>;\n saveProfile(profile: EmitterProfile): Promise<void>;\n getIssuingPoint(ownerId: string, issuingPointId: string): Promise<IssuingPoint | null>;\n listIssuingPoints(ownerId: string): Promise<IssuingPoint[]>;\n /**\n * Creates the point and its counters under the issuer's CNPJ, in both\n * environments, starting at `firstNumber` (a store moving from another\n * system continues its sequence). A series another point holds is refused.\n */\n createIssuingPoint(\n point: IssuingPoint,\n issuerCnpj: string,\n firstNumber: { readonly online: number; readonly contingency: number },\n ): Promise<void>;\n createDocument(\n request: NumberRequest,\n build: (number: number) => FiscalDocument,\n replace?: { readonly previous: FiscalDocument; readonly transition: Transition },\n ): Promise<FiscalDocument>;\n getDocument(ownerId: string, documentId: string): Promise<FiscalDocument | null>;\n /** The subject's documents of a model, oldest first. */\n listBySubject(ownerId: string, subjectId: string, model: FiscalDocumentModel): Promise<FiscalDocument[]>;\n listEvents(documentId: string): Promise<FiscalDocumentEvent[]>;\n saveTransition(previous: FiscalDocument, transition: Transition): Promise<boolean>;\n /**\n * Documents the sweep owes a step, across owners, whose `nextAttemptAt` has\n * come: `PENDING` or `SUBMITTED`, and those whose `numberVoid` is still owed.\n * Never one waiting for a person. Ordered by `nextAttemptAt`, so a row that\n * keeps failing moves back and never pins the head. At most `limit`.\n */\n listDue(input: { readonly now: string; readonly limit: number }): Promise<FiscalDocument[]>;\n /** `CONTINGENCY` documents owed a transmission, the same way. */\n listContingency(input: { readonly now: string; readonly limit: number }): Promise<FiscalDocument[]>;\n /** `CONTINGENCY` documents signed before `signedBefore` whose deadline warning has not gone out. */\n listContingencyDeadline(input: { readonly signedBefore: string; readonly limit: number }): Promise<FiscalDocument[]>;\n /** Profiles whose certificate expires before `before`, across owners. */\n listExpiringCertificates(before: string): Promise<EmitterProfile[]>;\n}\n\n/** A run of numbers of one series, both ends included. */\nexport interface NumberRange {\n readonly from: number;\n readonly to: number;\n}\n\n/**\n * - `OPEN`: the holder may still sign on it.\n * - `CLOSED`: the holder said it is done with it and how far it got (`usedUpTo`).\n * - `ABANDONED`: the holder is gone (a new install took its place): what it\n * signed above the highest number it handed in is unknown, never voided.\n */\nexport type ContingencyBlockFate = \"OPEN\" | \"CLOSED\" | \"ABANDONED\";\n\nexport const CONTINGENCY_BLOCK_FATES: readonly ContingencyBlockFate[] = [\"OPEN\", \"CLOSED\", \"ABANDONED\"];\n\n/**\n * Numbers of an issuing point's contingency series reserved for one holder\n * (the host's opaque id of a register that may go offline) to sign on with no\n * server. Drawn from the series' ONE counter — the counter the server's own\n * contingency (`issueOffline`, going offline after a silent SEFAZ) draws from\n * — so nothing else is ever numbered inside a block.\n */\nexport interface ContingencyBlock extends NumberRange {\n readonly id: string;\n readonly ownerId: string;\n readonly issuingPointId: string;\n readonly issuerCnpj: string;\n readonly environment: SefazEnvironment;\n readonly model: \"NFCE\";\n readonly series: number;\n readonly holder: string;\n readonly fate: ContingencyBlockFate;\n /** The highest number the holder said it used when it closed the block (`from - 1`: none); `null` otherwise. */\n readonly usedUpTo: number | null;\n readonly reservedAt: string;\n readonly closedAt: string | null;\n /** When every number of the block was accounted for (a document, or voided); `null` while one is not. */\n readonly settledAt: string | null;\n}\n\n/** A block, with the numbers recorded on it and the ranges voided at SEFAZ. */\nexport interface ContingencyBlockState extends ContingencyBlock {\n /** Numbers inside the block that carry a document, ascending. */\n readonly documented: readonly number[];\n readonly voided: readonly NumberRange[];\n}\n\n/**\n * A range of a block with no document: KNOWN unused (voided by\n * `voidKnownGaps`) or UNKNOWN (flagged for the store, never voided).\n */\nexport interface ContingencyGap extends NumberRange {\n readonly blockId: string;\n readonly ownerId: string;\n readonly issuingPointId: string;\n readonly issuerCnpj: string;\n readonly environment: SefazEnvironment;\n readonly series: number;\n readonly holder: string;\n readonly reservedAt: string;\n}\n\n/**\n * The rows behind contingency blocks (FUT-4717). Both of the package's stores\n * implement it (`createPrismaFiscalStore`, `createMemoryFiscalStore`); a host\n * with its own `FiscalStore` and without these gets `NOT_SUPPORTED` from the\n * block methods of the service, and everything else as before.\n *\n * - `reserveContingencyBlock` advances the series' counter by `size` and\n * records the block, in one transaction (no row back: not that point's\n * contingency series; past 999 999 999: `SERIES_EXHAUSTED`).\n * - `recordSignedDocument` inserts a document and its event together; a\n * second live document of the subject is `SUBJECT_HAS_DOCUMENT`, a key or\n * number recorded already is `CONFLICT`.\n * - `closeContingencyBlock` moves an OPEN block only (`false` otherwise).\n * - `recordContingencyVoid` records a voided range once (`false` when the\n * range was recorded before).\n */\nexport interface ContingencyBlockStore {\n reserveContingencyBlock(input: {\n readonly request: NumberRequest;\n readonly size: number;\n readonly id: string;\n readonly holder: string;\n readonly at: string;\n }): Promise<ContingencyBlock>;\n /** The block holding `number` of the series, whoever holds it, with its documents and voids. */\n findContingencyBlock(input: {\n readonly ownerId: string;\n readonly issuerCnpj: string;\n readonly environment: SefazEnvironment;\n readonly series: number;\n readonly number: number;\n }): Promise<ContingencyBlockState | null>;\n /**\n * One page of the blocks a filter selects, ordered by `(reservedAt, id)`;\n * `after` is the last block of the previous page (keyset): the caller reads\n * pages until one comes back empty.\n */\n listContingencyBlocks(input: {\n readonly ownerId?: string;\n readonly holder?: string;\n readonly fates?: readonly ContingencyBlockFate[];\n readonly reservedBefore?: string;\n /** Leave out the blocks whose every number is accounted for. */\n readonly unsettledOnly?: boolean;\n readonly after?: { readonly reservedAt: string; readonly id: string };\n readonly limit: number;\n }): Promise<ContingencyBlockState[]>;\n closeContingencyBlock(input: {\n readonly id: string;\n readonly fate: \"CLOSED\" | \"ABANDONED\";\n readonly usedUpTo: number | null;\n readonly at: string;\n }): Promise<boolean>;\n settleContingencyBlock(input: { readonly id: string; readonly at: string }): Promise<void>;\n recordContingencyVoid(input: {\n readonly id: string;\n readonly blockId: string;\n readonly range: NumberRange;\n readonly protocol: string | null;\n readonly eventXmlKey: string | null;\n readonly at: string;\n }): Promise<boolean>;\n getDocumentByAccessKey(ownerId: string, accessKey: string): Promise<FiscalDocument | null>;\n recordSignedDocument(document: FiscalDocument, event: FiscalDocumentEvent): Promise<FiscalDocument>;\n}\n\n/**\n * What an offline register needs from the package that owns every number\n * (FUT-4717), implemented by `createFiscalDocuments` over a store that is\n * also a {@link ContingencyBlockStore}. A register that cannot reach the\n * server signs on a block of its contingency series reserved in advance; back\n * online, it hands in what it signed, and the known rest of a finished block\n * is voided — an unknown range never is.\n */\nexport interface ContingencyBlockSource {\n /** Reserve the next `size` (default 50) numbers of the point's contingency series for one holder. */\n reserveBlock(input: {\n readonly ownerId: string;\n readonly issuingPointId: string;\n readonly holder: string;\n readonly size?: number;\n }): Promise<ContingencyBlock>;\n /**\n * Record an XML the holder signed offline as the subject's `CONTINGENCY`\n * document, owed a transmission now. Idempotent on the access key.\n * `sale`: the sale as the host knows it; absent, the host's `SaleSource`\n * answers it.\n */\n recordSigned(input: {\n readonly ownerId: string;\n readonly subjectId: string;\n readonly signedXml: string;\n readonly holder: string;\n readonly sale?: SaleDraft;\n }): Promise<FiscalDocument>;\n /**\n * The holder is done with the block: `sequenceUsed` is the highest number\n * it used (`from - 1`: none). The numbers above it are known unused.\n */\n closeBlock(input: {\n readonly ownerId: string;\n readonly holder: string;\n readonly series: number;\n readonly from: number;\n readonly sequenceUsed: number;\n }): Promise<ContingencyBlock>;\n}\n","/**\n * Which numbers of a contingency block are KNOWN unused and which are\n * UNKNOWN — pure, from the block's state (FUT-4717). A holder signs its block\n * in order and hands its notes in, in order, so:\n *\n * - below the highest number it handed in, a number with no document was\n * never signed: KNOWN;\n * - a CLOSED block's numbers above what the holder said it used are KNOWN;\n * between the highest handed in and `usedUpTo` they were signed and are\n * still to come: UNKNOWN until they arrive;\n * - an ABANDONED block (its holder is gone) above the highest handed in may\n * be on paper a buyer holds: UNKNOWN, flagged, never voided;\n * - an OPEN block above the highest handed in is still in use: neither.\n *\n * A range already voided is neither.\n */\n\nimport type { ContingencyBlockState, ContingencyGap, NumberRange } from \"./ports\";\n\n/** Consecutive numbers as ranges, ascending. */\nfunction rangesOf(numbers: readonly number[]): NumberRange[] {\n const sorted = [...new Set(numbers)].sort((a, b) => a - b);\n const ranges: NumberRange[] = [];\n for (const number of sorted) {\n const last = ranges[ranges.length - 1];\n if (last !== undefined && last.to === number - 1) ranges[ranges.length - 1] = { from: last.from, to: number };\n else ranges.push({ from: number, to: number });\n }\n return ranges;\n}\n\nfunction between(from: number, to: number, keep: (n: number) => boolean): number[] {\n const out: number[] = [];\n for (let n = from; n <= to; n += 1) if (keep(n)) out.push(n);\n return out;\n}\n\n/** The highest number of the block a document was recorded on (`from - 1`: none). */\nfunction highestRecorded(block: ContingencyBlockState): number {\n const inside = block.documented.filter((n) => n >= block.from && n <= block.to);\n return inside.length === 0 ? block.from - 1 : Math.max(...inside);\n}\n\nexport interface BlockAccount {\n readonly known: NumberRange[];\n readonly unknown: NumberRange[];\n}\n\n/** The block's known and unknown ranges (see the module doc). */\nexport function accountFor(block: ContingencyBlockState): BlockAccount {\n const documented = new Set(block.documented);\n const voided = (n: number) => block.voided.some((range) => n >= range.from && n <= range.to);\n const open = (n: number) => !documented.has(n) && !voided(n);\n const highest = highestRecorded(block);\n const known = between(block.from, highest, open);\n let unknown: number[] = [];\n if (block.fate === \"CLOSED\") {\n const used = Math.max(highest, block.usedUpTo ?? block.from - 1);\n known.push(...between(used + 1, block.to, open));\n unknown = between(highest + 1, used, open);\n } else if (block.fate === \"ABANDONED\") {\n unknown = between(highest + 1, block.to, open);\n }\n return { known: rangesOf(known), unknown: rangesOf(unknown) };\n}\n\n/** A range of a block, as the gap the service reports. */\nexport function gapOf(block: ContingencyBlockState, range: NumberRange): ContingencyGap {\n return {\n blockId: block.id,\n ownerId: block.ownerId,\n issuingPointId: block.issuingPointId,\n issuerCnpj: block.issuerCnpj,\n environment: block.environment,\n series: block.series,\n holder: block.holder,\n reservedAt: block.reservedAt,\n from: range.from,\n to: range.to,\n };\n}\n\n/** Whether every number is a document or voided, with nothing left to come: the block needs no more work. */\nexport function isSettled(block: ContingencyBlockState): boolean {\n if (block.fate === \"OPEN\") return false;\n const { known, unknown } = accountFor(block);\n return known.length === 0 && unknown.length === 0;\n}\n","/**\n * The gap pass over contingency blocks (FUT-4717): every block read in keyset\n * pages to the end (a block that never settles — an OPEN one, an ABANDONED\n * one with an unknown rest — must not hide the ones reserved after it), its\n * KNOWN unused ranges voided at SEFAZ once, its UNKNOWN ones only reported.\n */\n\nimport { FiscalDocumentError } from \"./errors\";\nimport { xmlKeys } from \"./helpers\";\nimport { accountFor, gapOf, isSettled } from \"./contingency-gaps\";\nimport type { Deps } from \"./service-profile\";\nimport type { ContingencyBlockState, ContingencyBlockStore, ContingencyGap, FiscalStore } from \"./ports\";\n\n/** How many blocks one read of a pass asks for; the pass reads pages until one comes back empty. */\nconst BLOCK_PAGE_SIZE = 1_000;\n\nconst BLOCK_METHODS = [\n \"reserveContingencyBlock\",\n \"findContingencyBlock\",\n \"listContingencyBlocks\",\n \"closeContingencyBlock\",\n \"settleContingencyBlock\",\n \"recordContingencyVoid\",\n \"getDocumentByAccessKey\",\n \"recordSignedDocument\",\n] as const;\n\nexport function blockStore(store: FiscalStore): FiscalStore & ContingencyBlockStore {\n const candidate = store as FiscalStore & Partial<ContingencyBlockStore>;\n if (BLOCK_METHODS.some((name) => typeof candidate[name] !== \"function\")) {\n throw new FiscalDocumentError(\"NOT_SUPPORTED\", \"this FiscalStore does not keep contingency blocks (ContingencyBlockStore).\");\n }\n return candidate as FiscalStore & ContingencyBlockStore;\n}\n\ntype BlockFilter = Omit<Parameters<ContingencyBlockStore[\"listContingencyBlocks\"]>[0], \"limit\" | \"after\">;\n\n/** Every page of the blocks a filter selects, in `(reservedAt, id)` order, to exhaustion. */\nasync function* blockPages(store: ContingencyBlockStore, filter: BlockFilter): AsyncGenerator<ContingencyBlockState[]> {\n let after: { reservedAt: string; id: string } | undefined;\n for (;;) {\n const page = await store.listContingencyBlocks({ ...filter, ...(after === undefined ? {} : { after }), limit: BLOCK_PAGE_SIZE });\n const last = page[page.length - 1];\n // An empty page ends the read; a page that does not move the cursor would loop for ever.\n if (last === undefined || (after !== undefined && last.id === after.id)) return;\n yield page;\n after = { reservedAt: last.reservedAt, id: last.id };\n }\n}\n\n/** The blocks of the pages, one by one. */\nasync function* eachBlock(pages: AsyncGenerator<ContingencyBlockState[]>): AsyncGenerator<ContingencyBlockState> {\n for await (const page of pages) yield* page;\n}\n\nexport async function allBlocks(store: ContingencyBlockStore, filter: BlockFilter): Promise<ContingencyBlockState[]> {\n const blocks: ContingencyBlockState[] = [];\n for await (const page of blockPages(store, filter)) blocks.push(...page);\n return blocks;\n}\n\nconst ownerFilter = (ownerId: string | undefined) => (ownerId === undefined ? {} : { ownerId });\n\n/** Known unused ranges of blocks reserved before `before` (ISO 8601), across owners unless one is named. */\nexport async function listKnownGaps(deps: Deps, input: { before: string; ownerId?: string }): Promise<ContingencyGap[]> {\n const blocks = await allBlocks(blockStore(deps.config.store), { ...ownerFilter(input.ownerId), reservedBefore: input.before, unsettledOnly: true });\n return blocks.flatMap((block) => accountFor(block).known.map((range) => gapOf(block, range)));\n}\n\n/** Ranges whose fate is unknown — flagged for the store, never voided. */\nexport async function listUnknownRanges(deps: Deps, input: { ownerId?: string }): Promise<ContingencyGap[]> {\n const blocks = await allBlocks(blockStore(deps.config.store), { ...ownerFilter(input.ownerId), fates: [\"CLOSED\", \"ABANDONED\"], unsettledOnly: true });\n return blocks.flatMap((block) => accountFor(block).unknown.map((range) => gapOf(block, range)));\n}\n\nexport interface GapVoidReport {\n readonly voided: ReadonlyArray<ContingencyGap & { readonly protocol: string | null }>;\n readonly failures: ReadonlyArray<ContingencyGap & { readonly class: string; readonly code: string | null; readonly message: string }>;\n}\n\nconst NOTHING: GapVoidReport = { voided: [], failures: [] };\n\n/** Whether the gap is still unused right now: no note recorded and nothing voided inside it since the pass read it. */\nasync function stillUnused(store: ContingencyBlockStore, gap: ContingencyGap): Promise<boolean> {\n const fresh = await store.findContingencyBlock({\n ownerId: gap.ownerId, issuerCnpj: gap.issuerCnpj, environment: gap.environment, series: gap.series, number: gap.from,\n });\n if (fresh === null || fresh.id !== gap.blockId) return false;\n const inside = (n: number) => n >= gap.from && n <= gap.to;\n return !fresh.documented.some(inside) && !fresh.voided.some((range) => range.from <= gap.to && range.to >= gap.from);\n}\n\nasync function voidGap(deps: Deps, store: ContingencyBlockStore, gap: ContingencyGap): Promise<GapVoidReport> {\n // A note handed in late since the page was read takes its number: leave the range for the next pass.\n if (!(await stillUnused(store, gap))) return NOTHING;\n const profile = await deps.ctx.requireProfile(gap.ownerId);\n const outcome = await deps.config.issuer.inutilize({\n model: \"NFCE\",\n environment: gap.environment,\n signing: await deps.ctx.material(profile),\n uf: profile.address.uf,\n cnpj: gap.issuerCnpj,\n year: Number(gap.reservedAt.slice(0, 4)),\n series: gap.series,\n from: gap.from,\n to: gap.to,\n reason: deps.config.reasons.inutilization,\n });\n if (!outcome.ok) {\n return { voided: [], failures: [{ ...gap, class: outcome.error.class, code: outcome.error.code, message: outcome.error.message }] };\n }\n const xml = outcome.answer.inutilizationXml;\n const eventXmlKey = xml === null ? null : xmlKeys.inutilizedRange(gap);\n if (eventXmlKey !== null) await deps.config.storage.put(eventXmlKey, xml ?? \"\", \"application/xml\");\n await store.recordContingencyVoid({\n id: deps.config.newId(),\n blockId: gap.blockId,\n range: { from: gap.from, to: gap.to },\n protocol: outcome.answer.protocol,\n eventXmlKey,\n at: deps.ctx.nowIso(),\n });\n return { voided: [{ ...gap, protocol: outcome.answer.protocol }], failures: [] };\n}\n\n/** Void one block's known ranges; settle it when nothing is left to account for. */\nasync function voidBlock(deps: Deps, store: ContingencyBlockStore, block: ContingencyBlockState): Promise<GapVoidReport> {\n const voided: GapVoidReport[\"voided\"][number][] = [];\n const failures: GapVoidReport[\"failures\"][number][] = [];\n for (const range of accountFor(block).known) {\n const one = await voidGap(deps, store, gapOf(block, range));\n voided.push(...one.voided);\n failures.push(...one.failures);\n }\n const done = voided.map(({ from, to }) => ({ from, to }));\n if (isSettled({ ...block, voided: [...block.voided, ...done] })) await store.settleContingencyBlock({ id: block.id, at: deps.ctx.nowIso() });\n return { voided, failures };\n}\n\n/**\n * One pass of the gap job: every KNOWN unused range of a block reserved\n * before `before` is inutilized once (one call per range); a failure is\n * reported and tried again on the next pass. A block left with nothing to\n * account for is settled and read no more. Unknown ranges are never voided.\n * Every unsettled block is read, page after page.\n */\nexport async function voidKnownGaps(deps: Deps, input: { before: string; ownerId?: string }): Promise<GapVoidReport> {\n const store = blockStore(deps.config.store);\n const report = { voided: [] as GapVoidReport[\"voided\"][number][], failures: [] as GapVoidReport[\"failures\"][number][] };\n const pages = blockPages(store, { ...ownerFilter(input.ownerId), reservedBefore: input.before, unsettledOnly: true });\n for await (const block of eachBlock(pages)) {\n const one = await voidBlock(deps, store, block);\n report.voided.push(...one.voided);\n report.failures.push(...one.failures);\n }\n return report;\n}\n","/**\n * Reading an NFC-e a holder signed offline (`tpEmis = 9`, no `nfeProc`) for\n * `recordSigned`: the fields the document record keeps, each read from the\n * XML, and every reason to refuse it. The XML is the fiscal service's own\n * layout, so the DANFE's reader (`../danfe/xml`) reads it.\n *\n * The access key is checked against the fields it encodes, not only its\n * check digit: a key whose number or series disagrees with `ide` would let a\n * holder record a number outside its block under a key inside it.\n */\n\nimport type { SefazEnvironment } from \"../sidecar/types\";\nimport { accessKeyOf, element, text } from \"../danfe/xml\";\nimport { FiscalDocumentError } from \"./errors\";\nimport { isValidAccessKey } from \"./helpers\";\n\n/** What a station-signed NFC-e says about itself. */\nexport interface SignedContingencyNote {\n readonly accessKey: string;\n readonly issuerCnpj: string;\n readonly environment: SefazEnvironment;\n readonly series: number;\n readonly number: number;\n /** `cNF`. */\n readonly keyCode: string;\n /** `dhEmi`. */\n readonly issuedAt: string;\n /** `dhCont` and `xJust`. */\n readonly contingency: { readonly since: string; readonly reason: string };\n readonly totalCents: number;\n readonly discountCents: number;\n /** The consumer's CPF/CNPJ (or foreign id), or `null`. */\n readonly buyerTaxId: string | null;\n}\n\nfunction refuse(why: string): never {\n throw new FiscalDocumentError(\"CONTINGENCY_XML_REFUSED\", why);\n}\n\nfunction cents(value: string | null): number {\n return Math.round(Number(value ?? \"0\") * 100);\n}\n\nfunction required(scope: string | null, tag: string): string {\n const value = text(scope, tag);\n if (value === null || value.trim() === \"\") refuse(`the XML has no ${tag}.`);\n return value.trim();\n}\n\n/** The key's own fields: cUF(2) AAMM(4) CNPJ(14) mod(2) serie(3) nNF(9) tpEmis(1) cNF(8) cDV(1). */\nfunction assertKeyMatches(key: string, ide: string, cnpj: string): void {\n const expected = [\n required(ide, \"cUF\"),\n required(ide, \"dhEmi\").slice(2, 4) + required(ide, \"dhEmi\").slice(5, 7),\n cnpj,\n required(ide, \"mod\"),\n required(ide, \"serie\").padStart(3, \"0\"),\n required(ide, \"nNF\").padStart(9, \"0\"),\n required(ide, \"tpEmis\"),\n required(ide, \"cNF\"),\n required(ide, \"cDV\"),\n ].join(\"\");\n if (expected !== key) refuse(\"the access key does not match the fields it encodes.\");\n}\n\n/**\n * Parse and check a station-signed NFC-e. Refuses (`CONTINGENCY_XML_REFUSED`)\n * anything but a model 65 signed in offline contingency (`tpEmis = 9`, with\n * `dhCont` and `xJust`), a key whose check digit or fields are wrong, and an\n * XML with no signature. The issuer's CNPJ and the block are the caller's to\n * check against its profile and its blocks.\n */\ninterface Parts {\n readonly infNFe: string;\n readonly ide: string;\n readonly emit: string;\n readonly accessKey: string;\n}\n\n/** The blocks every check reads, or a refusal naming what is missing. */\nfunction assertSignedNote(signedXml: string): void {\n if (typeof signedXml !== \"string\" || signedXml.trim() === \"\") refuse(\"signedXml is empty.\");\n if (element(signedXml, \"nfeProc\") !== null || element(signedXml, \"protNFe\") !== null) refuse(\"the XML is authorised already, not a signed note.\");\n if (element(signedXml, \"Signature\") === null) refuse(\"the XML is not signed.\");\n}\n\nfunction partsOf(signedXml: string): Parts {\n assertSignedNote(signedXml);\n const infNFe = element(signedXml, \"infNFe\");\n const ide = infNFe === null ? null : element(infNFe, \"ide\");\n const emit = infNFe === null ? null : element(infNFe, \"emit\");\n const accessKey = accessKeyOf(signedXml);\n if (infNFe === null || ide === null || emit === null || accessKey === null) refuse(\"the XML is not an NF-e: no infNFe, ide, emit or access key.\");\n return { infNFe, ide, emit, accessKey };\n}\n\n/** An NFC-e (65) signed offline (`tpEmis` 9) under a key whose check digit and fields hold. */\nfunction assertOfflineNfce({ ide, accessKey }: Parts, issuerCnpj: string): void {\n if (required(ide, \"mod\") !== \"65\") refuse(\"the XML is not an NFC-e (model 65).\");\n if (required(ide, \"tpEmis\") !== \"9\") refuse(\"the XML is not signed in offline contingency (tpEmis 9).\");\n if (!isValidAccessKey(accessKey)) refuse(\"the access key's check digit is wrong.\");\n assertKeyMatches(accessKey, ide, issuerCnpj);\n}\n\nfunction buyerOf(infNFe: string): string | null {\n const dest = element(infNFe, \"dest\");\n return text(dest, \"CPF\") ?? text(dest, \"CNPJ\") ?? text(dest, \"idEstrangeiro\");\n}\n\n/**\n * Parse and check a station-signed NFC-e. Refuses (`CONTINGENCY_XML_REFUSED`)\n * anything but a model 65 signed in offline contingency (`tpEmis = 9`, with\n * `dhCont` and `xJust`), a key whose check digit or fields are wrong, and an\n * XML with no signature. The issuer's CNPJ and the block are the caller's to\n * check against its profile and its blocks.\n */\nexport function parseSignedContingencyNote(signedXml: string): SignedContingencyNote {\n const parts = partsOf(signedXml);\n const { infNFe, ide, emit, accessKey } = parts;\n const issuerCnpj = required(emit, \"CNPJ\");\n assertOfflineNfce(parts, issuerCnpj);\n const total = element(infNFe, \"ICMSTot\");\n return {\n accessKey,\n issuerCnpj,\n environment: required(ide, \"tpAmb\") === \"1\" ? \"producao\" : \"homologacao\",\n series: Number(required(ide, \"serie\")),\n number: Number(required(ide, \"nNF\")),\n keyCode: required(ide, \"cNF\"),\n issuedAt: required(ide, \"dhEmi\"),\n contingency: { since: required(ide, \"dhCont\"), reason: required(ide, \"xJust\") },\n totalCents: cents(text(total, \"vNF\")),\n discountCents: cents(text(total, \"vDesc\")),\n buyerTaxId: buyerOf(infNFe),\n };\n}\n","/**\n * Contingency blocks (FUT-4717): numbers of an issuing point's contingency\n * series handed to a holder in advance, the notes it signed on them recorded\n * as the subjects' `CONTINGENCY` documents (transmitted by the same pass as\n * the server's own), and the known rest of each block voided at SEFAZ.\n *\n * A station-signed note is transmitted from its stored XML exactly as the\n * server's own contingency documents are (`transmit`): nothing rebuilds it\n * from the sale. A rejection keeps its number (the buyer holds its DANFE):\n * `resendContingency` re-signs it under the same number, as for any\n * contingency NFC-e.\n */\n\nimport { FiscalDocumentError } from \"./errors\";\nimport { assertDraftFits, issuerOf, totalsOf, xmlKeys } from \"./helpers\";\nimport { allBlocks, blockStore } from \"./contingency-pass\";\nimport { type SignedContingencyNote, parseSignedContingencyNote } from \"./contingency-xml\";\nimport type { Deps } from \"./service-profile\";\nimport type {\n ContingencyBlock,\n ContingencyBlockFate,\n ContingencyBlockSource,\n ContingencyBlockState,\n ContingencyBlockStore,\n SaleDraft,\n} from \"./ports\";\nimport type { FiscalDocument, FiscalDocumentEvent } from \"./types\";\n\n/** The block size when the caller names none (decided on FUT-4717: 50, a new block at 10 left). */\nexport const DEFAULT_CONTINGENCY_BLOCK_SIZE = 50;\n/** The largest block one call reserves. */\nexport const MAX_CONTINGENCY_BLOCK_SIZE = 10_000;\n\nfunction assertHolder(holder: unknown): asserts holder is string {\n if (typeof holder !== \"string\" || holder.trim() === \"\" || holder.length > 200) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", \"holder must be a non-empty id of at most 200 characters.\");\n }\n}\n\nfunction refuse(why: string): never {\n throw new FiscalDocumentError(\"CONTINGENCY_XML_REFUSED\", why);\n}\n\nexport async function reserveBlock(deps: Deps, input: Parameters<ContingencyBlockSource[\"reserveBlock\"]>[0]): Promise<ContingencyBlock> {\n const store = blockStore(deps.config.store);\n assertHolder(input.holder);\n const size = input.size ?? DEFAULT_CONTINGENCY_BLOCK_SIZE;\n if (!Number.isInteger(size) || size < 1 || size > MAX_CONTINGENCY_BLOCK_SIZE) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `size must be a whole number from 1 to ${MAX_CONTINGENCY_BLOCK_SIZE}.`);\n }\n const profile = await deps.ctx.requireProfile(input.ownerId);\n if (profile.documentPolicy !== \"ISSUED_HERE\") {\n throw new FiscalDocumentError(\"NOT_ISSUABLE\", `owner ${input.ownerId}'s documentPolicy is ${profile.documentPolicy}.`);\n }\n const point = await deps.ctx.requirePoint(input.ownerId, input.issuingPointId);\n if (point.model !== \"NFCE\" || point.contingencySeries === null) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `issuing point ${point.id} has no NFC-e contingency series.`);\n }\n return store.reserveContingencyBlock({\n request: {\n ownerId: input.ownerId,\n issuerCnpj: profile.cnpj,\n issuingPointId: point.id,\n environment: profile.environment,\n model: \"NFCE\",\n seriesKind: \"CONTINGENCY\",\n series: point.contingencySeries,\n },\n size,\n id: deps.config.newId(),\n holder: input.holder,\n at: deps.ctx.nowIso(),\n });\n}\n\n/** The CONTINGENCY document a holder's signed note becomes, owed a transmission now. */\nfunction signedDocument(\n deps: Deps,\n input: { ownerId: string; subjectId: string; draft: SaleDraft; note: SignedContingencyNote; block: ContingencyBlock; xmlKey: string },\n profile: Parameters<typeof issuerOf>[0],\n): FiscalDocument {\n const { note, draft } = input;\n const at = deps.ctx.nowIso();\n const sale = { ...draft, series: note.series, number: note.number, keyCode: note.keyCode, issuedAt: note.issuedAt, issuer: issuerOf(profile) };\n return {\n id: deps.config.newId(),\n ownerId: input.ownerId,\n issuerCnpj: note.issuerCnpj,\n subjectId: input.subjectId,\n issuingPointId: input.block.issuingPointId,\n model: \"NFCE\",\n environment: note.environment,\n seriesKind: \"CONTINGENCY\",\n series: note.series,\n number: note.number,\n keyCode: note.keyCode,\n status: \"CONTINGENCY\",\n sale,\n // What the buyer's DANFE prints is the XML's: a resend may never change it.\n totals: { ...totalsOf(draft), totalCents: note.totalCents, discountCents: note.discountCents },\n buyerTaxId: note.buyerTaxId,\n accessKey: note.accessKey,\n protocol: null,\n statusCode: null,\n statusReason: null,\n lastErrorClass: null,\n outcomeUnknown: false,\n issuedAt: note.issuedAt,\n authorizedAt: null,\n contingency: note.contingency,\n cancelledAt: null,\n cancelReason: null,\n cancelProtocol: null,\n replacedById: null,\n numberVoid: null,\n xmlKey: input.xmlKey,\n eventXmlKey: null,\n attempts: 0,\n failures: 0,\n nextAttemptAt: at,\n attention: false,\n deadlineWarnedAt: null,\n createdAt: at,\n updatedAt: at,\n };\n}\n\nfunction signedEvent(document: FiscalDocument, holder: string): FiscalDocumentEvent {\n return {\n documentId: document.id,\n kind: \"SIGN_OFFLINE\",\n fromStatus: \"PENDING\",\n toStatus: \"CONTINGENCY\",\n at: document.createdAt,\n errorClass: null,\n code: null,\n answer: { signedBy: \"HOLDER\", holder, accessKey: document.accessKey },\n };\n}\n\n/** A replayed upload: the document already recorded under the key, for the same subject. */\nfunction replayed(existing: FiscalDocument, subjectId: string): FiscalDocument {\n if (existing.subjectId !== subjectId) refuse(`access key ${existing.accessKey ?? \"\"} is recorded for another subject.`);\n return existing;\n}\n\nasync function blockOf(store: ContingencyBlockStore, ownerId: string, note: SignedContingencyNote, holder: string): Promise<ContingencyBlock> {\n const block = await store.findContingencyBlock({ ownerId, issuerCnpj: note.issuerCnpj, environment: note.environment, series: note.series, number: note.number });\n if (block === null || block.ownerId !== ownerId || block.holder !== holder) {\n refuse(`number ${note.number} of series ${note.series} is not inside a block held by ${holder}.`);\n }\n // Voided at SEFAZ already (a late hand-in behind a higher number): it can never be authorised, the sale is issued online.\n if (block.voided.some((range) => note.number >= range.from && note.number <= range.to)) {\n refuse(`number ${note.number} of series ${note.series} was voided at SEFAZ.`);\n }\n return block;\n}\n\n/** The XML must print what the booked sale says: its total and its buyer (a resend could never change them). */\nfunction assertMatchesSale(note: SignedContingencyNote, draft: SaleDraft): void {\n const totalCents = totalsOf(draft).totalCents;\n if (note.totalCents !== totalCents) refuse(`the XML's total (vNF ${note.totalCents} cents) is not the sale's (${totalCents} cents).`);\n if (note.buyerTaxId !== (draft.buyer?.document.number ?? null)) refuse(\"the XML's buyer document is not the sale's.\");\n}\n\n/** The note, parsed and checked against the owner's profile. */\nasync function checkedNote(deps: Deps, input: Parameters<ContingencyBlockSource[\"recordSigned\"]>[0]) {\n assertHolder(input.holder);\n if (typeof input.subjectId !== \"string\" || input.subjectId === \"\") throw new FiscalDocumentError(\"INVALID_INPUT\", \"subjectId is required.\");\n const note = parseSignedContingencyNote(input.signedXml);\n const profile = await deps.ctx.requireProfile(input.ownerId);\n if (note.issuerCnpj !== profile.cnpj) refuse(\"the XML's issuer is not the owner's CNPJ.\");\n if (note.environment !== profile.environment) refuse(`the XML was signed for ${note.environment}, the owner issues in ${profile.environment}.`);\n return { note, profile };\n}\n\n/** Insert the note; a concurrent upload of the same note is answered, a number under another key refused. */\nasync function insertNote(store: ContingencyBlockStore, document: FiscalDocument, holder: string, subjectId: string): Promise<FiscalDocument> {\n try {\n return await store.recordSignedDocument(document, signedEvent(document, holder));\n } catch (error) {\n if (!(error instanceof FiscalDocumentError) || error.code !== \"CONFLICT\") throw error;\n const raced = await store.getDocumentByAccessKey(document.ownerId, document.accessKey ?? \"\");\n if (raced !== null) return replayed(raced, subjectId);\n return refuse(`number ${document.number} of series ${document.series} is recorded under another key.`);\n }\n}\n\nexport async function recordSigned(deps: Deps, input: Parameters<ContingencyBlockSource[\"recordSigned\"]>[0]): Promise<FiscalDocument> {\n const store = blockStore(deps.config.store);\n const { note, profile } = await checkedNote(deps, input);\n const existing = await store.getDocumentByAccessKey(input.ownerId, note.accessKey);\n if (existing !== null) return replayed(existing, input.subjectId);\n const block = await blockOf(store, input.ownerId, note, input.holder);\n const draft = input.sale ?? (await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: input.subjectId, model: \"NFCE\" }));\n assertDraftFits(draft, \"NFCE\");\n assertMatchesSale(note, draft);\n const xmlKey = xmlKeys.signed(note.accessKey);\n await deps.config.storage.put(xmlKey, input.signedXml, \"application/xml\");\n const document = signedDocument(deps, { ownerId: input.ownerId, subjectId: input.subjectId, draft, note, block, xmlKey }, profile);\n return insertNote(store, document, input.holder, input.subjectId);\n}\n\nasync function heldBlock(\n deps: Deps,\n store: ContingencyBlockStore,\n input: { ownerId: string; holder: string; series: number; from: number },\n): Promise<ContingencyBlockState> {\n const profile = await deps.ctx.requireProfile(input.ownerId);\n const block = await store.findContingencyBlock({\n ownerId: input.ownerId, issuerCnpj: profile.cnpj, environment: profile.environment, series: input.series, number: input.from,\n });\n if (block === null || block.holder !== input.holder || block.from !== input.from) throw new FiscalDocumentError(\"NOT_FOUND\", `${input.holder} holds no block of series ${input.series} from ${input.from}.`);\n return block;\n}\n\nexport async function closeBlock(deps: Deps, input: Parameters<ContingencyBlockSource[\"closeBlock\"]>[0]): Promise<ContingencyBlock> {\n const store = blockStore(deps.config.store);\n assertHolder(input.holder);\n const block = await heldBlock(deps, store, input);\n const used = input.sequenceUsed;\n if (!Number.isInteger(used) || used < block.from - 1 || used > block.to) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `sequenceUsed must be from ${block.from - 1} to ${block.to}.`);\n }\n if (block.fate === \"CLOSED\" && block.usedUpTo === used) return block;\n if (block.fate !== \"OPEN\") throw new FiscalDocumentError(\"TRANSITION_REFUSED\", `the block from ${block.from} is ${block.fate}.`);\n const at = deps.ctx.nowIso();\n if (!(await store.closeContingencyBlock({ id: block.id, fate: \"CLOSED\", usedUpTo: used, at }))) {\n throw new FiscalDocumentError(\"CONFLICT\", `the block from ${block.from} moved while it was closed.`);\n }\n return { ...block, fate: \"CLOSED\", usedUpTo: used, closedAt: at };\n}\n\n/** The holder is gone (a new install took its place): its open blocks are ABANDONED. Answers them. */\nexport async function abandonBlocks(deps: Deps, input: { ownerId: string; holder: string }): Promise<ContingencyBlock[]> {\n const store = blockStore(deps.config.store);\n assertHolder(input.holder);\n const open = await allBlocks(store, { ownerId: input.ownerId, holder: input.holder, fates: [\"OPEN\"] });\n const at = deps.ctx.nowIso();\n const abandoned: ContingencyBlock[] = [];\n for (const block of open) {\n if (await store.closeContingencyBlock({ id: block.id, fate: \"ABANDONED\", usedUpTo: null, at })) {\n abandoned.push({ ...block, fate: \"ABANDONED\", closedAt: at });\n }\n }\n return abandoned;\n}\n\nexport async function listBlocks(\n deps: Deps,\n input: { ownerId: string; holder?: string; fates?: readonly ContingencyBlockFate[] },\n): Promise<ContingencyBlockState[]> {\n return allBlocks(blockStore(deps.config.store), input);\n}\n\nexport { listKnownGaps, listUnknownRanges, voidKnownGaps } from \"./contingency-pass\";\nexport type { GapVoidReport } from \"./contingency-pass\";\n","/**\n * Rows of the package's tables (`prisma/migrations`) to the records the\n * service holds, and back. Raw SQL through the host's Prisma client answers\n * snake_case columns, `Date` for a timestamp, a parsed object for a JSONB\n * column, and a `bigint` or a string for a BIGSERIAL; every one is read here.\n */\n\nimport type { EmitterProfile, IssuingPoint } from \"./profile\";\nimport type { FiscalDocument, FiscalDocumentEvent } from \"./types\";\n\nexport type Row = Record<string, unknown>;\n\n/** A timestamp column as ISO 8601 UTC; the columns are UTC by the Prisma convention. */\nfunction iso(value: unknown): string | null {\n if (value === null || value === undefined) return null;\n const date = value instanceof Date ? value : new Date(`${String(value).replace(\" \", \"T\")}${/Z|[+-]\\d{2}:?\\d{2}$/.test(String(value)) ? \"\" : \"Z\"}`);\n return date.toISOString();\n}\n\nfunction requiredIso(value: unknown): string {\n return iso(value) ?? \"\";\n}\n\n/** A DATE column as `YYYY-MM-DD`. */\nfunction day(value: unknown): string {\n return value instanceof Date ? value.toISOString().slice(0, 10) : String(value).slice(0, 10);\n}\n\nfunction json<T>(value: unknown): T {\n return (typeof value === \"string\" ? JSON.parse(value) : value) as T;\n}\n\nconst text = (value: unknown): string | null => (value === null || value === undefined ? null : String(value));\n\n/** The document's columns, in the order `documentValues` writes them. */\nexport const DOCUMENT_COLUMNS = [\n \"id\", \"owner_id\", \"issuer_cnpj\", \"subject_id\", \"issuing_point_id\", \"model\", \"environment\", \"series_kind\", \"series\",\n \"number\", \"key_code\", \"status\", \"sale\", \"totals\", \"buyer_tax_id\", \"access_key\", \"protocol\", \"status_code\",\n \"status_reason\", \"last_error_class\", \"outcome_unknown\", \"issued_at\", \"authorized_at\", \"contingency\", \"cancelled_at\",\n \"cancel_reason\", \"cancel_protocol\", \"replaced_by_id\", \"number_void\", \"xml_key\", \"event_xml_key\", \"attempts\",\n \"failures\", \"next_attempt_at\", \"attention\", \"deadline_warned_at\", \"created_at\", \"updated_at\",\n] as const;\n\nconst JSON_COLUMNS = new Set([\"sale\", \"totals\", \"contingency\"]);\nconst TIME_COLUMNS = new Set([\"next_attempt_at\", \"deadline_warned_at\", \"created_at\", \"updated_at\"]);\n\n/** The SQL placeholder of a column, with the cast its type needs. */\nexport function placeholder(column: string, index: number): string {\n if (JSON_COLUMNS.has(column)) return `$${index}::jsonb`;\n if (TIME_COLUMNS.has(column)) return `$${index}::timestamp(3)`;\n return `$${index}`;\n}\n\nexport function documentValues(d: FiscalDocument): unknown[] {\n return [\n d.id, d.ownerId, d.issuerCnpj, d.subjectId, d.issuingPointId, d.model, d.environment, d.seriesKind, d.series,\n d.number, d.keyCode, d.status, JSON.stringify(d.sale), JSON.stringify(d.totals), d.buyerTaxId, d.accessKey,\n d.protocol, d.statusCode, d.statusReason, d.lastErrorClass, d.outcomeUnknown, d.issuedAt, d.authorizedAt,\n d.contingency === null ? null : JSON.stringify(d.contingency), d.cancelledAt, d.cancelReason, d.cancelProtocol,\n d.replacedById, d.numberVoid, d.xmlKey, d.eventXmlKey, d.attempts, d.failures, d.nextAttemptAt, d.attention,\n d.deadlineWarnedAt, d.createdAt, d.updatedAt,\n ];\n}\n\nexport function documentOf(row: Row): FiscalDocument {\n return {\n id: String(row[\"id\"]),\n ownerId: String(row[\"owner_id\"]),\n issuerCnpj: String(row[\"issuer_cnpj\"]),\n subjectId: String(row[\"subject_id\"]),\n issuingPointId: String(row[\"issuing_point_id\"]),\n model: row[\"model\"] as FiscalDocument[\"model\"],\n environment: row[\"environment\"] as FiscalDocument[\"environment\"],\n seriesKind: row[\"series_kind\"] as FiscalDocument[\"seriesKind\"],\n series: Number(row[\"series\"]),\n number: Number(row[\"number\"]),\n keyCode: String(row[\"key_code\"]),\n status: row[\"status\"] as FiscalDocument[\"status\"],\n sale: json(row[\"sale\"]),\n totals: json(row[\"totals\"]),\n buyerTaxId: text(row[\"buyer_tax_id\"]),\n accessKey: text(row[\"access_key\"]),\n protocol: text(row[\"protocol\"]),\n statusCode: text(row[\"status_code\"]),\n statusReason: text(row[\"status_reason\"]),\n lastErrorClass: text(row[\"last_error_class\"]) as FiscalDocument[\"lastErrorClass\"],\n outcomeUnknown: row[\"outcome_unknown\"] === true,\n issuedAt: String(row[\"issued_at\"]),\n authorizedAt: text(row[\"authorized_at\"]),\n contingency: row[\"contingency\"] === null ? null : json(row[\"contingency\"]),\n cancelledAt: text(row[\"cancelled_at\"]),\n cancelReason: text(row[\"cancel_reason\"]),\n cancelProtocol: text(row[\"cancel_protocol\"]),\n replacedById: text(row[\"replaced_by_id\"]),\n numberVoid: text(row[\"number_void\"]) as FiscalDocument[\"numberVoid\"],\n xmlKey: text(row[\"xml_key\"]),\n eventXmlKey: text(row[\"event_xml_key\"]),\n attempts: Number(row[\"attempts\"]),\n failures: Number(row[\"failures\"]),\n nextAttemptAt: iso(row[\"next_attempt_at\"]),\n attention: row[\"attention\"] === true,\n deadlineWarnedAt: iso(row[\"deadline_warned_at\"]),\n createdAt: requiredIso(row[\"created_at\"]),\n updatedAt: requiredIso(row[\"updated_at\"]),\n };\n}\n\nexport function eventOf(row: Row): FiscalDocumentEvent {\n return {\n documentId: String(row[\"document_id\"]),\n kind: row[\"kind\"] as FiscalDocumentEvent[\"kind\"],\n fromStatus: row[\"from_status\"] as FiscalDocumentEvent[\"fromStatus\"],\n toStatus: row[\"to_status\"] as FiscalDocumentEvent[\"toStatus\"],\n at: requiredIso(row[\"at\"]),\n errorClass: text(row[\"error_class\"]) as FiscalDocumentEvent[\"errorClass\"],\n code: text(row[\"code\"]),\n answer: row[\"answer\"] === null ? null : json(row[\"answer\"]),\n };\n}\n\nexport const PROFILE_COLUMNS = [\n \"owner_id\", \"cnpj\", \"state_registration\", \"municipal_registration\", \"cnae\", \"legal_name\", \"trade_name\", \"tax_regime\",\n \"regime\", \"regime_effective_from\", \"restaurant_regime\", \"address\", \"environment\", \"document_policy\",\n \"signing_identity\", \"certificate_ciphertext\", \"certificate_password_ciphertext\", \"certificate_expires_at\", \"csc_id\",\n \"csc_ciphertext\", \"consent_recorded_at\", \"updated_at\",\n] as const;\n\nexport function profilePlaceholder(column: string, index: number): string {\n if (column === \"address\") return `$${index}::jsonb`;\n if (column === \"regime_effective_from\") return `$${index}::date`;\n if (column.endsWith(\"_at\")) return `$${index}::timestamp(3)`;\n return `$${index}`;\n}\n\nexport function profileValues(p: EmitterProfile): unknown[] {\n return [\n p.ownerId, p.cnpj, p.stateRegistration, p.municipalRegistration, p.cnae, p.legalName, p.tradeName, p.taxRegime,\n p.regime, p.regimeEffectiveFrom, p.restaurantRegime, JSON.stringify(p.address), p.environment, p.documentPolicy,\n p.signingIdentity, p.certificateCiphertext, p.certificatePasswordCiphertext, p.certificateExpiresAt, p.cscId,\n p.cscCiphertext, p.consentRecordedAt, p.updatedAt,\n ];\n}\n\nexport function profileOf(row: Row): EmitterProfile {\n return {\n ownerId: String(row[\"owner_id\"]),\n cnpj: String(row[\"cnpj\"]),\n stateRegistration: String(row[\"state_registration\"]),\n municipalRegistration: text(row[\"municipal_registration\"]),\n cnae: text(row[\"cnae\"]),\n legalName: String(row[\"legal_name\"]),\n tradeName: text(row[\"trade_name\"]),\n taxRegime: row[\"tax_regime\"] as EmitterProfile[\"taxRegime\"],\n regime: row[\"regime\"] as EmitterProfile[\"regime\"],\n regimeEffectiveFrom: day(row[\"regime_effective_from\"]),\n restaurantRegime: row[\"restaurant_regime\"] === true,\n address: json(row[\"address\"]),\n environment: row[\"environment\"] as EmitterProfile[\"environment\"],\n documentPolicy: row[\"document_policy\"] as EmitterProfile[\"documentPolicy\"],\n signingIdentity: row[\"signing_identity\"] as EmitterProfile[\"signingIdentity\"],\n certificateCiphertext: text(row[\"certificate_ciphertext\"]),\n certificatePasswordCiphertext: text(row[\"certificate_password_ciphertext\"]),\n certificateExpiresAt: iso(row[\"certificate_expires_at\"]),\n cscId: text(row[\"csc_id\"]),\n cscCiphertext: text(row[\"csc_ciphertext\"]),\n consentRecordedAt: iso(row[\"consent_recorded_at\"]),\n updatedAt: requiredIso(row[\"updated_at\"]),\n };\n}\n\nexport function pointOf(row: Row): IssuingPoint {\n return {\n id: String(row[\"id\"]),\n ownerId: String(row[\"owner_id\"]),\n model: row[\"model\"] as IssuingPoint[\"model\"],\n onlineSeries: Number(row[\"online_series\"]),\n contingencySeries: row[\"contingency_series\"] === null ? null : Number(row[\"contingency_series\"]),\n createdAt: requiredIso(row[\"created_at\"]),\n };\n}\n","/**\n * The SQL half of contingency blocks (FUT-4717), over the package's migration\n * (`fiscal_contingency_blocks`, `fiscal_contingency_voids`):\n *\n * - a block is ONE `UPDATE … SET next_number = next_number + size` on the\n * series' counter row (the row `issueOffline` draws from), and its insert,\n * in one transaction: the row lock serialises it with every other draw;\n * - a signed note is its document and its event, in one transaction; the\n * unique indexes on the key and the number make a second copy a `CONFLICT`.\n */\n\nimport { FiscalDocumentError } from \"./errors\";\nimport type { ContingencyBlock, ContingencyBlockState, ContingencyBlockStore } from \"./ports\";\nimport type { FiscalPrismaClient, FiscalSqlClient } from \"./sql-store\";\nimport { DOCUMENT_COLUMNS, type Row, documentOf, documentValues, placeholder } from \"./sql-rows\";\nimport type { FiscalDocument, FiscalDocumentEvent } from \"./types\";\n\n/**\n * Advance a contingency series' counter by a block. `$1` CNPJ, `$2`\n * environment, `$3` model, `$4` series, `$5` issuing point, `$6` size. No row:\n * not that point's contingency series; past the ceiling: the counter's CHECK.\n */\nexport const FISCAL_RESERVE_BLOCK_SQL = `UPDATE \"fiscal_number_counters\"\nSET \"next_number\" = \"next_number\" + $6::integer, \"updated_at\" = CURRENT_TIMESTAMP\nWHERE \"issuer_cnpj\" = $1 AND \"environment\" = $2 AND \"model\" = $3 AND \"series\" = $4 AND \"issuing_point_id\" = $5\n AND \"series_kind\" = 'CONTINGENCY'\nRETURNING \"next_number\" - $6::integer AS \"first\"`;\n\nconst rows = (client: FiscalSqlClient, query: string, ...values: unknown[]) => client.$queryRawUnsafe<Row[]>(query, ...values);\n\nfunction violates(error: unknown, constraint: string): boolean {\n const text = error instanceof Error ? `${error.message} ${JSON.stringify((error as { meta?: unknown }).meta ?? \"\")}` : String(error);\n return text.includes(constraint);\n}\n\nconst iso = (value: unknown): string | null => (value === null || value === undefined ? null : new Date(value instanceof Date ? value : `${String(value).replace(\" \", \"T\")}Z`).toISOString());\n\nfunction blockOf(row: Row): ContingencyBlock {\n return {\n id: String(row[\"id\"]),\n ownerId: String(row[\"owner_id\"]),\n issuingPointId: String(row[\"issuing_point_id\"]),\n issuerCnpj: String(row[\"issuer_cnpj\"]),\n environment: row[\"environment\"] as ContingencyBlock[\"environment\"],\n model: \"NFCE\",\n series: Number(row[\"series\"]),\n from: Number(row[\"first_number\"]),\n to: Number(row[\"last_number\"]),\n holder: String(row[\"holder\"]),\n fate: row[\"fate\"] as ContingencyBlock[\"fate\"],\n usedUpTo: row[\"used_up_to\"] === null ? null : Number(row[\"used_up_to\"]),\n reservedAt: iso(row[\"reserved_at\"]) ?? \"\",\n closedAt: iso(row[\"closed_at\"]),\n settledAt: iso(row[\"settled_at\"]),\n };\n}\n\nconst INSERT_BLOCK = `INSERT INTO \"fiscal_contingency_blocks\"\n (\"id\", \"owner_id\", \"issuing_point_id\", \"issuer_cnpj\", \"environment\", \"model\", \"series\", \"first_number\", \"last_number\", \"holder\", \"reserved_at\")\nVALUES ($1, $2, $3, $4, $5, 'NFCE', $6, $7, $8, $9, $10::timestamp(3))`;\n\nconst INSERT_DOCUMENT = `INSERT INTO \"fiscal_documents\" (${DOCUMENT_COLUMNS.map((c) => `\"${c}\"`).join(\", \")})\nVALUES (${DOCUMENT_COLUMNS.map((c, i) => placeholder(c, i + 1)).join(\", \")})`;\n\nconst INSERT_EVENT = `INSERT INTO \"fiscal_document_events\" (\"id\", \"document_id\", \"kind\", \"from_status\", \"to_status\", \"at\", \"error_class\", \"code\", \"answer\")\nVALUES ($1, $2, $3, $4, $5, $6::timestamp(3), $7, $8, $9::jsonb)`;\n\nasync function reserve(db: FiscalPrismaClient, input: Parameters<ContingencyBlockStore[\"reserveContingencyBlock\"]>[0]): Promise<ContingencyBlock> {\n const { request, size, id, holder, at } = input;\n try {\n return await db.$transaction(async (tx) => {\n const [row] = await rows(tx, FISCAL_RESERVE_BLOCK_SQL, request.issuerCnpj, request.environment, request.model, request.series, request.issuingPointId, size);\n if (row === undefined) {\n throw new FiscalDocumentError(\"NOT_FOUND\", `no contingency counter for series ${request.series} on issuing point ${request.issuingPointId}.`);\n }\n const first = Number(row[\"first\"]);\n await tx.$executeRawUnsafe(\n INSERT_BLOCK, id, request.ownerId, request.issuingPointId, request.issuerCnpj, request.environment, request.series, first, first + size - 1, holder, at,\n );\n const [stored] = await rows(tx, `SELECT * FROM \"fiscal_contingency_blocks\" WHERE \"id\" = $1`, id);\n return blockOf(stored ?? {});\n });\n } catch (error) {\n if (violates(error, \"fiscal_number_counters_next_number_check\") || violates(error, \"fiscal_contingency_blocks_range_check\")) {\n throw new FiscalDocumentError(\"SERIES_EXHAUSTED\", `series ${request.series} has no ${size} numbers left.`);\n }\n throw error;\n }\n}\n\nasync function insertSigned(db: FiscalPrismaClient, document: FiscalDocument, event: FiscalDocumentEvent): Promise<FiscalDocument> {\n try {\n await db.$transaction(async (tx) => {\n await tx.$executeRawUnsafe(INSERT_DOCUMENT, ...documentValues(document));\n await tx.$executeRawUnsafe(\n INSERT_EVENT, globalThis.crypto.randomUUID(), event.documentId, event.kind, event.fromStatus, event.toStatus, event.at,\n event.errorClass, event.code, JSON.stringify(event.answer),\n );\n });\n return document;\n } catch (error) {\n if (violates(error, \"fiscal_documents_live_subject_key\")) {\n throw new FiscalDocumentError(\"SUBJECT_HAS_DOCUMENT\", `subject ${document.subjectId} already has a live ${document.model}.`);\n }\n if (violates(error, \"fiscal_documents_access_key_key\") || violates(error, \"fiscal_documents_number_key\")) {\n throw new FiscalDocumentError(\"CONFLICT\", `key ${document.accessKey ?? \"\"} or number ${document.number} is recorded already.`);\n }\n throw error;\n }\n}\n\n/** The blocks, each with its documented numbers and voided ranges: two reads. */\nasync function withState(db: FiscalPrismaClient, blocks: readonly ContingencyBlock[]): Promise<ContingencyBlockState[]> {\n if (blocks.length === 0) return [];\n const ids = blocks.map((block) => block.id);\n const documented = await rows(\n db,\n `SELECT b.\"id\" AS \"block_id\", d.\"number\" FROM \"fiscal_contingency_blocks\" b\n JOIN \"fiscal_documents\" d ON d.\"issuer_cnpj\" = b.\"issuer_cnpj\" AND d.\"environment\" = b.\"environment\" AND d.\"model\" = b.\"model\"\n AND d.\"series\" = b.\"series\" AND d.\"number\" BETWEEN b.\"first_number\" AND b.\"last_number\"\n WHERE b.\"id\" = ANY($1::text[]) ORDER BY d.\"number\"`,\n ids,\n );\n const voids = await rows(db, `SELECT * FROM \"fiscal_contingency_voids\" WHERE \"block_id\" = ANY($1::text[]) ORDER BY \"first_number\"`, ids);\n return blocks.map((block) => ({\n ...block,\n documented: documented.filter((row) => row[\"block_id\"] === block.id).map((row) => Number(row[\"number\"])),\n voided: voids.filter((row) => row[\"block_id\"] === block.id).map((row) => ({ from: Number(row[\"first_number\"]), to: Number(row[\"last_number\"]) })),\n }));\n}\n\n/** One keyset page of the blocks a filter selects, ordered by `(reserved_at, id)`, with their state. */\nasync function list(db: FiscalPrismaClient, input: Parameters<ContingencyBlockStore[\"listContingencyBlocks\"]>[0]): Promise<ContingencyBlockState[]> {\n const where: string[] = [];\n const values: unknown[] = [];\n const add = (clause: (n: number) => string, value: unknown) => {\n values.push(value);\n where.push(clause(values.length));\n };\n if (input.ownerId !== undefined) add((n) => `\"owner_id\" = $${n}`, input.ownerId);\n if (input.holder !== undefined) add((n) => `\"holder\" = $${n}`, input.holder);\n if (input.fates !== undefined) add((n) => `\"fate\" = ANY($${n}::text[])`, [...input.fates]);\n if (input.reservedBefore !== undefined) add((n) => `\"reserved_at\" < $${n}::timestamp(3)`, input.reservedBefore);\n if (input.unsettledOnly === true) where.push(`\"settled_at\" IS NULL`);\n if (input.after !== undefined) {\n values.push(input.after.reservedAt, input.after.id);\n where.push(`(\"reserved_at\", \"id\") > ($${values.length - 1}::timestamp(3), $${values.length})`);\n }\n values.push(input.limit);\n const blocks = (\n await rows(\n db,\n `SELECT * FROM \"fiscal_contingency_blocks\" ${where.length === 0 ? \"\" : `WHERE ${where.join(\" AND \")}`}\n ORDER BY \"reserved_at\", \"id\" LIMIT $${values.length}`,\n ...values,\n )\n ).map(blockOf);\n return withState(db, blocks);\n}\n\nexport function blockMethods(db: FiscalPrismaClient): ContingencyBlockStore {\n return {\n reserveContingencyBlock: (input) => reserve(db, input),\n async findContingencyBlock(input) {\n const [row] = await rows(\n db,\n `SELECT * FROM \"fiscal_contingency_blocks\"\n WHERE \"owner_id\" = $1 AND \"issuer_cnpj\" = $2 AND \"environment\" = $3 AND \"model\" = 'NFCE' AND \"series\" = $4\n AND $5::integer BETWEEN \"first_number\" AND \"last_number\"`,\n input.ownerId, input.issuerCnpj, input.environment, input.series, input.number,\n );\n return row === undefined ? null : ((await withState(db, [blockOf(row)]))[0] ?? null);\n },\n listContingencyBlocks: (input) => list(db, input),\n async closeContingencyBlock({ id, fate, usedUpTo, at }) {\n const updated = await rows(\n db,\n `UPDATE \"fiscal_contingency_blocks\" SET \"fate\" = $2, \"used_up_to\" = $3, \"closed_at\" = $4::timestamp(3)\n WHERE \"id\" = $1 AND \"fate\" = 'OPEN' RETURNING \"id\"`,\n id, fate, usedUpTo, at,\n );\n return updated.length > 0;\n },\n async settleContingencyBlock({ id, at }) {\n await db.$executeRawUnsafe(`UPDATE \"fiscal_contingency_blocks\" SET \"settled_at\" = $2::timestamp(3) WHERE \"id\" = $1`, id, at);\n },\n async recordContingencyVoid({ id, blockId, range, protocol, eventXmlKey, at }) {\n const inserted = await rows(\n db,\n `INSERT INTO \"fiscal_contingency_voids\" (\"id\", \"block_id\", \"first_number\", \"last_number\", \"protocol\", \"event_xml_key\", \"voided_at\")\n VALUES ($1, $2, $3, $4, $5, $6, $7::timestamp(3)) ON CONFLICT (\"block_id\", \"first_number\") DO NOTHING RETURNING \"id\"`,\n id, blockId, range.from, range.to, protocol, eventXmlKey, at,\n );\n return inserted.length > 0;\n },\n async getDocumentByAccessKey(ownerId, accessKey) {\n const [row] = await rows(db, `SELECT * FROM \"fiscal_documents\" WHERE \"owner_id\" = $1 AND \"access_key\" = $2`, ownerId, accessKey);\n return row === undefined ? null : documentOf(row);\n },\n recordSignedDocument: (document, event) => insertSigned(db, document, event),\n };\n}\n","/**\n * The SigningIdentity port: who signs a call. It turns a profile into the\n * {@link SigningMaterial} for ONE call to the issuer; the material is never\n * stored, logged or put in an error.\n *\n * - `STORE_CERTIFICATE` ships now: the store's own A1, decrypted through the\n * host's {@link Cipher} at the moment of the call.\n * - `PLATFORM` is declared and answers `NOT_SUPPORTED` until FUT-2229\n * question 4 says how the platform signs on a store's behalf.\n */\n\nimport type { SigningMaterial } from \"../issuer/port\";\nimport { FiscalDocumentError } from \"./errors\";\nimport type { Cipher } from \"./ports\";\nimport type { EmitterProfile, SigningIdentityKind } from \"./profile\";\n\nexport interface SigningIdentity {\n readonly kind: SigningIdentityKind;\n materialFor(profile: EmitterProfile): Promise<SigningMaterial>;\n}\n\nexport type SigningIdentities = Readonly<Record<SigningIdentityKind, SigningIdentity>>;\n\nexport function createStoreCertificateIdentity(config: { readonly cipher: Cipher }): SigningIdentity {\n if (typeof config?.cipher?.decrypt !== \"function\") throw new TypeError(\"createStoreCertificateIdentity needs a cipher.\");\n const { cipher } = config;\n return {\n kind: \"STORE_CERTIFICATE\",\n async materialFor(profile) {\n if (profile.certificateCiphertext === null || profile.certificatePasswordCiphertext === null) {\n throw new FiscalDocumentError(\"NOT_ISSUABLE\", `owner ${profile.ownerId} has no certificate.`);\n }\n const [pfxBase64, password] = await Promise.all([\n cipher.decrypt(profile.certificateCiphertext),\n cipher.decrypt(profile.certificatePasswordCiphertext),\n ]);\n const csc =\n profile.cscId !== null && profile.cscCiphertext !== null\n ? { id: profile.cscId, token: await cipher.decrypt(profile.cscCiphertext) }\n : null;\n return { certificate: { pfxBase64, password }, csc };\n },\n };\n}\n\nexport function createPlatformIdentity(): SigningIdentity {\n return {\n kind: \"PLATFORM\",\n async materialFor(profile) {\n throw new FiscalDocumentError(\n \"NOT_SUPPORTED\",\n `owner ${profile.ownerId} signs as PLATFORM, which is declared and not built yet (FUT-2229 q4).`,\n );\n },\n };\n}\n\n/** The two identities over one cipher: what a host passes as `signing`. */\nexport function createSigningIdentities(config: { readonly cipher: Cipher }): SigningIdentities {\n return { STORE_CERTIFICATE: createStoreCertificateIdentity(config), PLATFORM: createPlatformIdentity() };\n}\n","/**\n * The profile half of the document service: the emitter profile, the\n * certificate upload and the issuing points. A secret is encrypted through the\n * host's cipher the moment it arrives, and only its ciphertext is stored.\n */\n\nimport type { FiscalContext, FiscalDocumentsConfig } from \"./context\";\nimport { FiscalDocumentError } from \"./errors\";\nimport type { Cipher } from \"./ports\";\nimport type { CertificateUpload, EmitterProfileInput, IssuingPointInput } from \"./profile-input\";\nimport type { EmitterProfile, IssuingPoint } from \"./profile\";\n\n/** What the host learns from an A1 without this package parsing PKCS#12. */\nexport interface CertificateFacts {\n /** `notAfter`, ISO 8601. */\n readonly expiresAt: string;\n}\n\nexport interface FiscalDocumentsServiceConfig extends FiscalDocumentsConfig {\n /** Encrypts the certificate, its password and the CSC on arrival. */\n readonly cipher: Cipher;\n /**\n * Reads the expiry out of an uploaded A1; throws when the file does not\n * open with the password. The host's: Node's crypto cannot open every A1\n * (most issued before 2023 use RC2-40), and this package adds no parser.\n */\n readonly readCertificate: (certificate: CertificateUpload) => Promise<CertificateFacts>;\n}\n\nexport interface Deps {\n readonly ctx: FiscalContext;\n readonly config: FiscalDocumentsServiceConfig;\n}\n\n/**\n * The CSC's ciphertext a save leaves: the CSC id and token are one secret, so\n * a new id needs its token, a token needs an id, and no id clears both.\n */\nasync function cscCiphertextFor(\n config: FiscalDocumentsServiceConfig,\n stored: EmitterProfile | null,\n input: Pick<EmitterProfileInput, \"cscId\" | \"cscToken\">,\n): Promise<string | null> {\n if (input.cscToken !== null) {\n if (input.cscId === null) throw new FiscalDocumentError(\"INVALID_INPUT\", \"cscId is required with cscToken.\");\n return config.cipher.encrypt(input.cscToken);\n }\n if (input.cscId === null) return null;\n if (input.cscId !== stored?.cscId) throw new FiscalDocumentError(\"INVALID_INPUT\", \"cscToken is required with a new cscId.\");\n return stored.cscCiphertext;\n}\n\nexport async function saveProfile({ ctx, config }: Deps, ownerId: string, input: EmitterProfileInput): Promise<EmitterProfile> {\n const stored = await config.store.getProfile(ownerId);\n const fields = Object.fromEntries(Object.entries(input).filter(([key]) => key !== \"cscToken\")) as Omit<EmitterProfileInput, \"cscToken\">;\n const profile: EmitterProfile = {\n ...fields,\n ownerId,\n certificateCiphertext: stored?.certificateCiphertext ?? null,\n certificatePasswordCiphertext: stored?.certificatePasswordCiphertext ?? null,\n certificateExpiresAt: stored?.certificateExpiresAt ?? null,\n cscCiphertext: await cscCiphertextFor(config, stored, input),\n updatedAt: ctx.nowIso(),\n };\n await config.store.saveProfile(profile);\n return profile;\n}\n\nexport async function uploadCertificate({ ctx, config }: Deps, ownerId: string, certificate: CertificateUpload): Promise<EmitterProfile> {\n const stored = await ctx.requireProfile(ownerId);\n let facts: CertificateFacts;\n try {\n facts = await config.readCertificate(certificate);\n } catch {\n // The reader's own message may quote what it was given; this one never does.\n throw new FiscalDocumentError(\"INVALID_INPUT\", \"the certificate does not open with that password.\");\n }\n const profile: EmitterProfile = {\n ...stored,\n certificateCiphertext: await config.cipher.encrypt(certificate.pfxBase64),\n certificatePasswordCiphertext: await config.cipher.encrypt(certificate.password),\n certificateExpiresAt: facts.expiresAt,\n updatedAt: ctx.nowIso(),\n };\n await config.store.saveProfile(profile);\n return profile;\n}\n\nexport async function createIssuingPoint({ ctx, config }: Deps, ownerId: string, input: IssuingPointInput): Promise<IssuingPoint> {\n const profile = await ctx.requireProfile(ownerId);\n if (input.model === \"NFE\" && input.contingencySeries !== null) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", \"an NF-e issuing point has no contingency series: the service has no offline NF-e path.\");\n }\n const point: IssuingPoint = {\n id: input.id,\n ownerId,\n model: input.model,\n onlineSeries: input.onlineSeries,\n contingencySeries: input.contingencySeries,\n createdAt: ctx.nowIso(),\n };\n await config.store.createIssuingPoint(point, profile.cnpj, { online: input.firstOnlineNumber, contingency: input.firstContingencyNumber });\n return point;\n}\n","/**\n * The `nfeProc` — what an authorised document is stored as — assembled from\n * the signed XML the service built and the `protNFe` a lookup answered, for a\n * document whose sending went unanswered and was then found authorised.\n */\n\nimport { element } from \"../danfe/xml\";\n\nconst PROTOCOL = /<protNFe\\b[^>]*>[\\s\\S]*?<\\/protNFe>/;\nconst NFE = /<NFe\\b[^>]*>[\\s\\S]*<\\/NFe>/;\n/** The signed XML's own digest (`DigestValue`), which SEFAZ quotes back as the protocol's `digVal`. */\nexport function digestOf(signedXml: string): string | null {\n return /<DigestValue>([^<]+)<\\/DigestValue>/.exec(signedXml)?.[1]?.trim() ?? null;\n}\n\n/** The protocol a SEFAZ reply carries, with its `digVal`, or `null`. */\nexport function protocolDigestOf(sefazReply: string): string | null {\n const protocol = PROTOCOL.exec(sefazReply)?.[0];\n const infProt = protocol === undefined ? null : element(protocol, \"infProt\");\n return infProt === null ? null : (element(infProt, \"digVal\")?.trim() ?? null);\n}\n\n/** The `cStat`s of a protocol that authorises (100, 150 late) or denies (110, 301–303) the use of the key. */\nconst SETTLING = new Set([\"100\", \"150\", \"110\", \"301\", \"302\", \"303\"]);\n\n/**\n * `null` unless the reply carries a protocol for exactly this key with a\n * settling status, the signed XML is the document's, AND the protocol's\n * `digVal` is that XML's `DigestValue` — the protocol certifies THAT XML and\n * no other built under the same key (the fiscal service's own `issued()`\n * refuses the same mismatch). Never a guess.\n */\n/** Whether this protocol certifies this signed XML under this key, with a settling status. */\nfunction certifies(infProt: string, nfe: string, accessKey: string): boolean {\n const digest = digestOf(nfe);\n return (\n element(infProt, \"chNFe\") === accessKey &&\n SETTLING.has(element(infProt, \"cStat\") ?? \"\") &&\n nfe.includes(`Id=\"NFe${accessKey}\"`) &&\n digest !== null &&\n element(infProt, \"digVal\")?.trim() === digest\n );\n}\n\nexport function assembleNfeProc(input: { readonly signedXml: string; readonly sefazReply: string; readonly accessKey: string }): string | null {\n const protocol = PROTOCOL.exec(input.sefazReply)?.[0];\n const nfe = NFE.exec(input.signedXml)?.[0];\n const infProt = protocol === undefined ? null : element(protocol, \"infProt\");\n if (protocol === undefined || nfe === undefined || infProt === null || !certifies(infProt, nfe, input.accessKey)) return null;\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?><nfeProc versao=\"4.00\" xmlns=\"http://www.portalfiscal.inf.br/nfe\">${nfe}${protocol}</nfeProc>`;\n}\n","/**\n * Settling a number SEFAZ never used, so a series has no unexplained gap:\n * look it up first when a send went unanswered, cancel it if SEFAZ authorised\n * it after all (by SUBSTITUTION, event 110112, when a contingency document\n * replaced it), inutilize it otherwise.\n *\n * A call that fails is never silent: it is DEFERRED — one more failure, a\n * later attempt — and a refusal SEFAZ will repeat (241 number used, 256, 501\n * late cancel, a certificate refused) hands the document to a person at once,\n * with the needs-attention notification.\n */\n\nimport type { IssuerFailure, IssuerOutcome, SigningMaterial } from \"../issuer/port\";\nimport type { CancelledDocument, LookedUpDocument } from \"../sidecar/types\";\nimport { type FiscalContext, xmlKeys } from \"./context\";\nimport { assembleNfeProc, protocolDigestOf } from \"./nfe-proc\";\nimport type { EmitterProfile } from \"./profile\";\nimport type { FiscalDocument, NumberVoid } from \"./types\";\n\ntype Settle = (ctx: FiscalContext, document: FiscalDocument, profile: EmitterProfile, signing: SigningMaterial) => Promise<FiscalDocument>;\n\n/** A refusal the same call would meet again: a person must look. */\nconst REFUSALS = new Set<IssuerFailure[\"class\"]>([\"REJECTED\", \"AUTH\", \"INVALID\", \"INTERNAL\"]);\n\nfunction defer(ctx: FiscalContext, document: FiscalDocument, what: string, error: IssuerFailure): Promise<FiscalDocument> {\n return ctx.advance(document, { kind: \"DEFER\", reason: `${what} failed`, error, attention: REFUSALS.has(error.class) });\n}\n\n/**\n * A SUBMITTED document a lookup finds authorised or denied: its `nfeProc`,\n * from the signed XML whose digest the protocol's `digVal` names and the\n * protocol itself, stored. `undefined` when either is missing — the document\n * then stays SUBMITTED, owing work, and the sweep sends the same call again\n * for the XML.\n */\nexport async function storeNfeProc(ctx: FiscalContext, document: FiscalDocument, answer: LookedUpDocument): Promise<string | undefined> {\n if ((answer.status !== \"AUTHORIZED\" && answer.status !== \"DENIED\") || document.accessKey === null) return undefined;\n // The XML the protocol certifies, by its digest; never simply the last one stored.\n const digest = protocolDigestOf(answer.sefazReply);\n if (digest === null) return undefined;\n const signedXml = await ctx.config.storage.get(xmlKeys.signedByDigest(document.accessKey, digest));\n if (signedXml === null) return undefined;\n const nfeProc = assembleNfeProc({ signedXml, sefazReply: answer.sefazReply, accessKey: document.accessKey });\n if (nfeProc === null) return undefined;\n const xmlKey = xmlKeys.authorized(document.accessKey);\n await ctx.config.storage.put(xmlKey, nfeProc, \"application/xml\");\n return xmlKey;\n}\n\n/**\n * A document a lookup just returned to SUBMITTED (a live REJECTED number\n * found SEFAZ's): settled as AUTHORIZED or DENIED with the same answer when\n * the XML the protocol certifies is held. Two steps, never REJECTED →\n * AUTHORIZED in one.\n */\nexport async function settleWithXml(ctx: FiscalContext, document: FiscalDocument, answer: LookedUpDocument): Promise<FiscalDocument> {\n if (document.status !== \"SUBMITTED\") return document;\n const xmlKey = await storeNfeProc(ctx, document, answer);\n return xmlKey === undefined ? document : ctx.advance(document, { kind: \"LOOKUP\", answer, xmlKey });\n}\n\nconst lookupFirst: Settle = async (ctx, document, _profile, signing) => {\n if (document.accessKey === null) return ctx.advance(document, { kind: \"DEFER\", reason: \"no access key to look up\", error: null, attention: true });\n const outcome = await ctx.config.issuer.lookup({ model: document.model, environment: document.environment, signing, accessKey: document.accessKey });\n if (!outcome.ok) return defer(ctx, document, \"the lookup\", outcome.error);\n return settleWithXml(ctx, await ctx.advance(document, { kind: \"LOOKUP\", answer: outcome.answer }), outcome.answer);\n};\n\n/** The cancel owed: by substitution when a contingency document replaced it, an ordinary one otherwise. */\nasync function sendOwedCancel(ctx: FiscalContext, document: FiscalDocument, signing: SigningMaterial): Promise<IssuerOutcome<CancelledDocument> | null> {\n const { accessKey, protocol, replacedById } = document;\n if (accessKey === null || protocol === null) return null;\n const reason = ctx.config.reasons.substitution;\n const base = { environment: document.environment, signing, accessKey, protocol, reason };\n const substitute = replacedById === null ? null : await ctx.config.store.getDocument(document.ownerId, replacedById);\n if (document.model === \"NFCE\" && substitute?.accessKey) {\n return ctx.config.issuer.cancelBySubstitution({ ...base, substituteAccessKey: substitute.accessKey });\n }\n return ctx.config.issuer.cancel({ ...base, model: document.model });\n}\n\nconst cancelOwed: Settle = async (ctx, document, _profile, signing) => {\n const outcome = await sendOwedCancel(ctx, document, signing);\n if (outcome === null) return ctx.advance(document, { kind: \"DEFER\", reason: \"no protocol to cancel with\", error: null, attention: true });\n if (!outcome.ok) return defer(ctx, document, \"the owed cancel\", outcome.error);\n const eventXmlKey = outcome.answer.eventXml === null ? null : xmlKeys.cancel(outcome.answer.accessKey);\n if (eventXmlKey !== null) await ctx.config.storage.put(eventXmlKey, outcome.answer.eventXml ?? \"\", \"application/xml\");\n return ctx.advance(document, { kind: \"CANCEL\", answer: outcome.answer, reason: ctx.config.reasons.substitution, eventXmlKey });\n};\n\nconst inutilizeOwed: Settle = async (ctx, document, profile, signing) => {\n const outcome = await ctx.config.issuer.inutilize({\n model: document.model,\n environment: document.environment,\n signing,\n uf: profile.address.uf,\n cnpj: document.issuerCnpj,\n year: Number(document.issuedAt.slice(0, 4)),\n series: document.series,\n from: document.number,\n to: document.number,\n reason: ctx.config.reasons.inutilization,\n });\n if (!outcome.ok) return defer(ctx, document, \"the inutilization\", outcome.error);\n const xml = outcome.answer.inutilizationXml;\n const eventXmlKey = xml === null ? null : xmlKeys.inutilization(document);\n if (eventXmlKey !== null) await ctx.config.storage.put(eventXmlKey, xml ?? \"\", \"application/xml\");\n return ctx.advance(document, { kind: \"INUTILIZE\", answer: outcome.answer, eventXmlKey });\n};\n\nconst SETTLE: Partial<Record<NumberVoid, Settle>> = {\n LOOKUP_FIRST: lookupFirst,\n CANCEL: cancelOwed,\n INUTILIZE: inutilizeOwed,\n};\n\n/** Settle what a replaced or rejected document still owes on its number. */\nexport async function settleNumber(ctx: FiscalContext, document: FiscalDocument, profile: EmitterProfile, signing: SigningMaterial): Promise<FiscalDocument> {\n const settle = document.numberVoid === null ? undefined : SETTLE[document.numberVoid];\n return settle === undefined ? document : settle(ctx, document, profile, signing);\n}\n","/**\n * The event 110300 \"Vinculação Pagamento\" (NT 2026.006 v1.00 §5.1): a payment\n * transaction linked to an authorised document after the fact — a Pix QR whose\n * txid was learnt only once the note was out, say. One event per transaction\n * (the event's single `gPgto`), numbered per document (`nSeqEvento`).\n *\n * Idempotent per `(document, transactionId)`: a transaction the document\n * already carries in its own `gPgtoVinc`, or already linked by an earlier\n * event, is skipped with no call to SEFAZ. A refusal answers the issuer's\n * failure and records nothing; the caller may ask again. `nSeqEvento` is the\n * next after the document's own recorded events; a 573 at it is settled by the\n * event SEFAZ holds there (its XML kept, its transaction recorded as its own),\n * and the payment is then sent at the next sequence.\n */\n\nimport type { IssuerFailure } from \"../issuer/port\";\nimport type { LinkedTransaction, PaymentLinkMeans } from \"../sale/types\";\nimport type { RegisteredPaymentLink } from \"../sidecar/types\";\nimport { xmlKeys } from \"./context\";\nimport { FiscalDocumentError } from \"./errors\";\nimport type { Deps } from \"./service-profile\";\nimport type { FiscalDocument, FiscalDocumentEvent } from \"./types\";\n\n/** `nSeqEvento` runs 1–20 per event type and document. */\nexport const MAX_PAYMENT_LINKS = 20;\n\nexport interface LinkPaymentInput {\n readonly ownerId: string;\n readonly documentId: string;\n readonly payments: readonly LinkedTransaction[];\n}\n\nexport interface LinkPaymentResult {\n /** The transaction ids SEFAZ registered in this call. */\n readonly linked: readonly string[];\n /** Those the document already carried or an earlier event linked: nothing was sent. */\n readonly alreadyLinked: readonly string[];\n /** The first refusal, if any; the transactions after it were not sent. */\n readonly failure: IssuerFailure | null;\n readonly document: FiscalDocument;\n}\n\n/** Each 110300 the document's events record: the transaction and its `nSeqEvento`. */\nfunction linkedByEvents(events: readonly FiscalDocumentEvent[]): Array<{ transactionId: string; sequence: number }> {\n return events\n .filter((event) => event.kind === \"LINK_PAYMENT\")\n .map((event, index) => {\n const answer = event.answer as { payment?: { transactionId?: unknown }; sequence?: unknown } | null;\n return {\n transactionId: answer?.payment?.transactionId,\n sequence: typeof answer?.sequence === \"number\" ? answer.sequence : index + 1,\n };\n })\n .filter((link): link is { transactionId: string; sequence: number } => typeof link.transactionId === \"string\");\n}\n\n/** The transaction ids the document's own `gPgtoVinc` carries. */\nfunction linkedInDocument(document: FiscalDocument): string[] {\n return document.sale.payments\n .map((payment) => payment.linkedTransaction?.transactionId)\n .filter((id): id is string => typeof id === \"string\");\n}\n\n/** What every event of this document is sent with: its key, its protocol and the issuer's event call. */\nfunction linkable(deps: Deps, document: FiscalDocument) {\n const { accessKey, protocol } = document;\n if (document.status !== \"AUTHORIZED\" || accessKey === null || protocol === null) {\n throw new FiscalDocumentError(\"TRANSITION_REFUSED\", `document ${document.id} is ${document.status}; only an authorised document is linked.`);\n }\n const send = deps.config.issuer.linkPayment;\n if (typeof send !== \"function\") throw new FiscalDocumentError(\"NOT_SUPPORTED\", \"this issuer does not register the event 110300.\");\n return { accessKey, protocol, send: send.bind(deps.config.issuer) };\n}\n\n/**\n * The transaction SEFAZ holds at the sequence just sent. A 135 registered what\n * was sent. A 573 answers the event already there, looked up: the same\n * transaction (a retry whose recording was lost), or another one, which is\n * then recorded as ITS link and never attributed to `sent`.\n */\nfunction heldTransaction(answer: RegisteredPaymentLink, sent: LinkedTransaction, requested: readonly LinkedTransaction[]): LinkedTransaction {\n if (answer.statusCode !== \"573\" || answer.transaction.transactionId === sent.transactionId) return sent;\n const held = answer.transaction;\n return (\n requested.find((payment) => payment.transactionId === held.transactionId) ?? {\n transactionId: held.transactionId,\n meansCode: held.meansCode as PaymentLinkMeans,\n pspCnpjBase: held.pspCnpjBase,\n receiverCnpj: held.receiverCnpj,\n }\n );\n}\n\n/** One call's progress: the document as last advanced, the next `nSeqEvento`, what is linked. */\ninterface LinkRun {\n document: FiscalDocument;\n sequence: number;\n readonly known: Set<string>;\n readonly requested: readonly LinkedTransaction[];\n readonly linked: string[];\n readonly send: (sequence: number, payment: LinkedTransaction) => ReturnType<NonNullable<Deps[\"config\"][\"issuer\"][\"linkPayment\"]>>;\n}\n\nfunction refuseOverLimit(document: FiscalDocument): never {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `document ${document.id} cannot take more than ${MAX_PAYMENT_LINKS} payment links.`);\n}\n\n/**\n * Sends `payment` at the run's sequence and records what SEFAZ holds there.\n * When that is another transaction (a 573), it is recorded as its own link and\n * `payment` goes out again at the next sequence. Answers the refusal, if any.\n */\nasync function sendOne(deps: Deps, run: LinkRun, accessKey: string, payment: LinkedTransaction): Promise<IssuerFailure | null> {\n if (run.sequence > MAX_PAYMENT_LINKS) refuseOverLimit(run.document);\n const sequence = run.sequence;\n const outcome = await run.send(sequence, payment);\n if (!outcome.ok) return outcome.error;\n const held = heldTransaction(outcome.answer, payment, run.requested);\n const { eventXml } = outcome.answer;\n const eventXmlKey = eventXml === null ? null : xmlKeys.linkPayment(accessKey, sequence);\n if (eventXmlKey !== null && eventXml !== null) await deps.config.storage.put(eventXmlKey, eventXml, \"application/xml\");\n run.document = await deps.ctx.advance(run.document, { kind: \"LINK_PAYMENT\", answer: outcome.answer, payment: held, sequence, eventXmlKey });\n run.known.add(held.transactionId);\n if (run.requested.some((one) => one.transactionId === held.transactionId)) run.linked.push(held.transactionId);\n run.sequence = sequence + 1;\n return held.transactionId === payment.transactionId ? null : sendOne(deps, run, accessKey, payment);\n}\n\nexport async function linkPayment(deps: Deps, input: LinkPaymentInput): Promise<LinkPaymentResult> {\n const document = await deps.config.store.getDocument(input.ownerId, input.documentId);\n if (document === null) throw new FiscalDocumentError(\"NOT_FOUND\", `owner ${input.ownerId} has no document ${input.documentId}.`);\n const { accessKey, protocol, send } = linkable(deps, document);\n const byEvents = linkedByEvents(await deps.config.store.listEvents(document.id));\n const known = new Set([...linkedInDocument(document), ...byEvents.map((link) => link.transactionId)]);\n const pending = input.payments.filter((payment) => !known.has(payment.transactionId));\n const alreadyLinked = input.payments.filter((payment) => known.has(payment.transactionId)).map((payment) => payment.transactionId);\n // `nSeqEvento` follows the document's own events, never a count of anything else.\n const sequence = Math.max(0, ...byEvents.map((link) => link.sequence)) + 1;\n if (sequence - 1 + pending.length > MAX_PAYMENT_LINKS) refuseOverLimit(document);\n if (pending.length === 0) return { linked: [], alreadyLinked, failure: null, document };\n const signing = await deps.ctx.material(await deps.ctx.requireProfile(input.ownerId));\n const run: LinkRun = {\n document,\n sequence,\n known,\n requested: pending,\n linked: [],\n send: (at, payment) => send({ model: document.model, environment: document.environment, signing, accessKey, protocol, sequence: at, payments: [payment] }),\n };\n for (const payment of pending) {\n if (run.known.has(payment.transactionId)) continue;\n const failure = await sendOne(deps, run, accessKey, payment);\n if (failure !== null) return { linked: run.linked, alreadyLinked, failure, document: run.document };\n }\n return { linked: run.linked, alreadyLinked, failure: null, document: run.document };\n}\n","/**\n * The steps that issue a document, each one call and the transition its\n * answer earns. The mapping of the service's classes:\n *\n * | answer | on a document being issued | on a contingency document being transmitted |\n * |---|---|---|\n * | `AUTHORIZED` / `DENIED` | AUTHORIZE / DENY | AUTHORIZE / DENY |\n * | `REJECTED`, `INVALID`, `INTERNAL` | REJECT: the number is voided (looked up first if a send went unanswered) | REJECT: kept for the store to correct and resend |\n * | `CONTINGENCY`, NFC-e, point with a contingency series | a second document, offline, replacing this one in one transaction | RETRY |\n * | `CONTINGENCY` otherwise, `RETRYABLE`, `AUTH` | RETRY, with backoff; a person after `MAX_FAILURES` | RETRY |\n *\n * An online NFC-e is never sent again past `nfceOnlineToleranceMs` (SEFAZ\n * refuses a late `dhEmi`): where the point has a contingency series it goes\n * offline instead.\n *\n * A caller that cannot wait (a counter whose paper waits for the note) gives\n * the send an ONLINE DEADLINE (`issue({ …, onlineDeadlineMs })`): an NFC-e at\n * a point with a contingency series whose send is not answered by then — or is\n * answered with no answer (`RETRYABLE`) — goes offline at once, exactly as a\n * `CONTINGENCY` answer does. The send may still have reached SEFAZ, so the\n * replaced number is marked unknown and looked up before it is voided; its\n * late answer settles nothing.\n */\n\nimport type { IssuerFailure, IssuerOutcome, SigningMaterial } from \"../issuer/port\";\nimport { FISCAL_ISSUE } from \"../manifest/permissions\";\nimport type { IssuedDocument } from \"../sidecar/types\";\nimport { FISCAL_DOCUMENT_REJECTED, type FiscalContext, draftOf, xmlKeys } from \"./context\";\nimport { FiscalDocumentError } from \"./errors\";\nimport { computeAccessKey } from \"./helpers\";\nimport { digestOf } from \"./nfe-proc\";\nimport type { EmitterProfile, IssuingPoint } from \"./profile\";\nimport type { FiscalDocument } from \"./types\";\n\nconst FINAL_FAILURES = new Set<IssuerFailure[\"class\"]>([\"REJECTED\", \"INVALID\", \"INTERNAL\"]);\n\nasync function reject(ctx: FiscalContext, document: FiscalDocument, error: IssuerFailure): Promise<FiscalDocument> {\n const rejected = await ctx.advance(document, { kind: \"REJECT\", error });\n await ctx.config.notify.emit({\n type: FISCAL_DOCUMENT_REJECTED,\n recipient: { tenantId: document.ownerId, permission: FISCAL_ISSUE },\n payload: {\n documentId: document.id,\n subjectId: document.subjectId,\n model: document.model,\n series: document.series,\n number: document.number,\n code: error.code,\n reason: error.message,\n },\n });\n return rejected;\n}\n\nasync function accept(ctx: FiscalContext, document: FiscalDocument, answer: IssuedDocument): Promise<FiscalDocument> {\n const xmlKey = xmlKeys.authorized(answer.accessKey);\n await ctx.config.storage.put(xmlKey, answer.authorizedXml, \"application/xml\");\n return ctx.advance(document, { kind: answer.status === \"AUTHORIZED\" ? \"AUTHORIZE\" : \"DENY\", answer, xmlKey });\n}\n\nfunction canGoOffline(document: FiscalDocument, point: IssuingPoint): boolean {\n return document.model === \"NFCE\" && document.seriesKind === \"ONLINE\" && point.contingencySeries !== null;\n}\n\n/** An online NFC-e whose `dhEmi` SEFAZ would now refuse as late. */\nfunction pastOnlineTolerance(ctx: FiscalContext, document: FiscalDocument): boolean {\n return ctx.config.now().getTime() - Date.parse(document.createdAt) > ctx.config.nfceOnlineToleranceMs;\n}\n\n/** Sign a contingency-series document offline. On a failure it is left as it was, for the caller to defer. */\nasync function signOffline(\n ctx: FiscalContext,\n document: FiscalDocument,\n profile: EmitterProfile,\n signing: SigningMaterial,\n): Promise<{ document: FiscalDocument; error: IssuerFailure | null }> {\n const contingency = { since: await ctx.localNow(profile.ownerId), reason: ctx.config.reasons.contingency };\n const outcome = await ctx.config.issuer.signContingency({ environment: document.environment, signing, document: document.sale, contingency });\n if (!outcome.ok) return { document, error: outcome.error };\n const xmlKey = xmlKeys.signed(outcome.answer.accessKey);\n await ctx.config.storage.put(xmlKey, outcome.answer.signedXml, \"application/xml\");\n return { document: await ctx.advance(document, { kind: \"SIGN_OFFLINE\", answer: outcome.answer, contingency, xmlKey }), error: null };\n}\n\n/** Sign a PENDING contingency document; a failure is deferred (it stays PENDING, the sweep signs it later). */\nexport async function signPending(\n ctx: FiscalContext,\n document: FiscalDocument,\n profile: EmitterProfile,\n signing: SigningMaterial,\n): Promise<FiscalDocument> {\n const signed = await signOffline(ctx, document, profile, signing);\n if (signed.error === null) return signed.document;\n return ctx.advance(document, {\n kind: \"DEFER\",\n reason: \"signing offline failed\",\n error: signed.error,\n // Signing is local: a certificate that does not open (AUTH) will not open on the next try either.\n attention: FINAL_FAILURES.has(signed.error.class) || signed.error.class === \"AUTH\",\n });\n}\n\n/**\n * Move the sale offline: number a second document on the contingency series\n * AND replace this one, in ONE transaction, before anything is signed — so a\n * crash can never leave the online document to be sent again beside its twin.\n * Signing follows; if it fails, the new document waits PENDING for the sweep.\n */\nasync function goOffline(\n ctx: FiscalContext,\n document: FiscalDocument,\n profile: EmitterProfile,\n point: IssuingPoint,\n signing: SigningMaterial,\n): Promise<FiscalDocument> {\n const offline = await ctx.createNumbered({\n profile,\n point,\n subjectId: document.subjectId,\n model: document.model,\n seriesKind: \"CONTINGENCY\",\n draft: draftOf(document.sale),\n replacing: document,\n });\n return signPending(ctx, offline, profile, signing);\n}\n\n/**\n * The signed XML a failed call returned, stored UNDER ITS DIGEST and never\n * over another: each send under a key may carry a different XML (a service\n * upgrade between sends changes `verProc`, say), and only the one SEFAZ\n * authorised may become the `nfeProc`. A lookup reads the protocol's `digVal`\n * and fetches exactly that XML (`xmlKeys.signedByDigest`), so pairing is by\n * digest, not by \"the last one stored\". `xmlKey` points at the latest.\n */\nasync function keepSigned(ctx: FiscalContext, document: FiscalDocument, error: IssuerFailure): Promise<{ xmlKey?: string }> {\n const key = document.accessKey ?? error.accessKey;\n const digest = error.signedXml === null ? null : digestOf(error.signedXml);\n if (error.signedXml === null || key === null || digest === null) return {};\n const xmlKey = xmlKeys.signedByDigest(key, digest);\n await ctx.config.storage.put(xmlKey, error.signedXml, \"application/xml\");\n return { xmlKey };\n}\n\n/**\n * An online NFC-e SEFAZ would now refuse as late, at a point that can go\n * offline. A document a lookup found authorised (its protocol is kept) is\n * SEFAZ's: sending the same call again fetches its XML (the service settles\n * the duplicate by a lookup), and it must never go offline beside its own\n * authorisation.\n */\nfunction staleOnline(ctx: FiscalContext, document: FiscalDocument, point: IssuingPoint): boolean {\n const knownToSefaz = document.status === \"SUBMITTED\" && document.protocol !== null;\n return !knownToSefaz && canGoOffline(document, point) && pastOnlineTolerance(ctx, document);\n}\n\n/** The failure a send not answered by its online deadline counts as: a contingency, its outcome unknown. */\nfunction pastDeadline(document: FiscalDocument): IssuerFailure {\n return {\n class: \"CONTINGENCY\",\n code: null,\n message: \"SEFAZ did not answer before the online deadline.\",\n details: [],\n accessKey: document.accessKey ?? computeAccessKey({ sale: document.sale, model: document.model, seriesKind: \"ONLINE\" }),\n signedXml: null,\n sefazReply: null,\n outcomeUnknown: true,\n };\n}\n\n/** The send, raced against the deadline (`deadlineAt`, epoch ms). A late answer is dropped: the number is looked up instead. */\nasync function sendBefore(\n send: Promise<IssuerOutcome<IssuedDocument>>,\n document: FiscalDocument,\n deadlineAt: number,\n): Promise<IssuerOutcome<IssuedDocument>> {\n send.catch(() => undefined);\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<IssuerOutcome<IssuedDocument>>((resolve) => {\n timer = setTimeout(() => resolve({ ok: false, error: pastDeadline(document) }), Math.max(0, deadlineAt - Date.now()));\n });\n try {\n return await Promise.race([send, late]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** The online send, bounded by the deadline when there is one. */\nfunction send(ctx: FiscalContext, document: FiscalDocument, signing: SigningMaterial, deadlineAt: number | null): Promise<IssuerOutcome<IssuedDocument>> {\n const call = ctx.config.issuer.issue({ model: document.model, environment: document.environment, signing, document: document.sale });\n return deadlineAt === null ? call : sendBefore(call, document, deadlineAt);\n}\n\n/** Whether a failed send moves the sale offline: a contingency always; with a deadline, an unanswered send too. */\nfunction goesOffline(error: IssuerFailure, deadlineAt: number | null): boolean {\n return error.class === \"CONTINGENCY\" || (deadlineAt !== null && error.class === \"RETRYABLE\");\n}\n\n/**\n * Issue (or re-issue, for a SUBMITTED one) a document on its online series.\n * `deadlineAt` (epoch ms): the online deadline, for an NFC-e whose point can\n * go offline (see the module doc); `null`, the send's own timeout rules.\n */\nexport async function submit(\n ctx: FiscalContext,\n document: FiscalDocument,\n profile: EmitterProfile,\n point: IssuingPoint,\n signing: SigningMaterial,\n deadlineAt: number | null = null,\n): Promise<FiscalDocument> {\n if (staleOnline(ctx, document, point)) return goOffline(ctx, document, profile, point, signing);\n const sent = document.status === \"PENDING\" ? await ctx.advance(document, { kind: \"SUBMIT\" }) : document;\n const bounded = deadlineAt !== null && canGoOffline(sent, point) ? deadlineAt : null;\n const outcome = await send(ctx, sent, signing, bounded);\n if (outcome.ok) return accept(ctx, sent, outcome.answer);\n if (FINAL_FAILURES.has(outcome.error.class)) return reject(ctx, sent, outcome.error);\n const retried = await ctx.advance(sent, { kind: \"RETRY\", error: outcome.error, ...(await keepSigned(ctx, sent, outcome.error)) });\n return goesOffline(outcome.error, bounded) && canGoOffline(retried, point) ? goOffline(ctx, retried, profile, point, signing) : retried;\n}\n\n/**\n * A live online NFC-e the caller's deadline already passed — `onlineDeadlineMs`\n * since it was numbered, still unanswered and not known to SEFAZ — goes offline\n * now, at a point with a contingency series; anything else is answered as it is.\n */\nasync function offlineIfOverdue(\n ctx: FiscalContext,\n document: FiscalDocument,\n profile: EmitterProfile,\n point: IssuingPoint,\n signing: SigningMaterial,\n onlineDeadlineMs: number,\n): Promise<FiscalDocument> {\n const waiting = document.status === \"PENDING\" || document.status === \"SUBMITTED\";\n const overdue = ctx.config.now().getTime() - Date.parse(document.createdAt) >= onlineDeadlineMs;\n if (!waiting || !overdue || document.protocol !== null || !canGoOffline(document, point)) return document;\n return goOffline(ctx, document, profile, point, signing);\n}\n\n/** Transmit a document signed offline. */\nexport async function transmit(ctx: FiscalContext, document: FiscalDocument, signing: SigningMaterial): Promise<FiscalDocument> {\n const signedXml = document.xmlKey === null ? null : await ctx.config.storage.get(document.xmlKey);\n if (signedXml === null) throw new FiscalDocumentError(\"NOT_FOUND\", `document ${document.id} has no signed XML in storage.`);\n const outcome = await ctx.config.issuer.transmit({ model: document.model, environment: document.environment, signing, signedXml });\n if (outcome.ok) return accept(ctx, document, outcome.answer);\n if (FINAL_FAILURES.has(outcome.error.class)) return reject(ctx, document, outcome.error);\n return ctx.advance(document, { kind: \"RETRY\", error: outcome.error });\n}\n\n/** The live document of a lost race or an earlier call — moved offline when the caller's online deadline already passed. */\nexport async function answerLive(\n ctx: FiscalContext,\n existing: FiscalDocument,\n profile: EmitterProfile,\n onlineDeadlineMs: number | undefined,\n): Promise<FiscalDocument> {\n if (onlineDeadlineMs === undefined || existing.model !== \"NFCE\" || existing.seriesKind !== \"ONLINE\") return existing;\n const point = await ctx.requirePoint(existing.ownerId, existing.issuingPointId);\n return offlineIfOverdue(ctx, existing, profile, point, await ctx.material(profile), onlineDeadlineMs);\n}\n\n/** `onlineDeadlineMs`, when given, is a whole number of milliseconds, 0 or more. */\nexport function assertOnlineDeadline(onlineDeadlineMs: number | undefined): void {\n if (onlineDeadlineMs !== undefined && (!Number.isInteger(onlineDeadlineMs) || onlineDeadlineMs < 0)) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", \"onlineDeadlineMs must be a whole number of milliseconds, 0 or more.\");\n }\n}\n","/**\n * `createFiscalDocuments` — the document service: the emitter profile, the\n * issuing points, and issuing, cancelling, looking up and sweeping documents\n * over the host's ports. Every SEFAZ step goes through the Issuer port and\n * every state change through the state machine (`./machine`), persisted with\n * its event and its next attempt.\n *\n * The certificate, its password and the CSC are encrypted through the host's\n * cipher the moment they arrive, decrypted by the signing identity for one\n * call, and never logged, answered or put in an error.\n */\n\nimport type { IssuerFailure } from \"../issuer/port\";\nimport { FISCAL_ISSUE } from \"../manifest/permissions\";\nimport type { LookedUpDocument } from \"../sidecar/types\";\nimport { FISCAL_CONTINGENCY_DEADLINE, FiscalContext, assertConfig, assertDraftFits, assertReason, issuerOf, totalsOf, xmlKeys } from \"./context\";\nimport { FiscalDocumentError } from \"./errors\";\nimport { canTransition } from \"./machine\";\nimport { type Deps, type FiscalDocumentsServiceConfig, createIssuingPoint, saveProfile, uploadCertificate } from \"./service-profile\";\nimport { settleNumber, settleWithXml, storeNfeProc } from \"./settle\";\nimport { linkPayment } from \"./payment-link\";\nimport { abandonBlocks, closeBlock, listBlocks, listKnownGaps, listUnknownRanges, recordSigned, reserveBlock, voidKnownGaps } from \"./contingency\";\nimport { answerLive, assertOnlineDeadline, signPending, submit, transmit } from \"./steps\";\nimport { type CancelOrReturnInput, type CancelOrReturnResult, type DocumentTotals, type FiscalDocument, type FiscalDocumentModel, isLive } from \"./types\";\n\nexport type { CertificateFacts, FiscalDocumentsServiceConfig } from \"./service-profile\";\nexport type { CancelOrReturnInput, CancelOrReturnResult } from \"./types\";\nexport type { LinkPaymentInput, LinkPaymentResult } from \"./payment-link\";\n\nexport interface SweepReport {\n readonly advanced: Array<{ readonly documentId: string; readonly status: FiscalDocument[\"status\"] }>;\n readonly failures: Array<{ readonly documentId: string; readonly message: string }>;\n}\n\nexport interface IssueInput {\n readonly ownerId: string;\n readonly subjectId: string;\n readonly issuingPointId: string;\n readonly model: FiscalDocumentModel;\n /**\n * NFC-e only, at a point with a contingency series: how long (ms, from this\n * call) the online send may go unanswered before the sale goes offline on\n * that series — a caller whose paper cannot wait (a counter, 10 s). A live\n * online document numbered this long ago and still unanswered goes offline\n * at once. Absent: the send's own timeout and the sweep's rules.\n */\n readonly onlineDeadlineMs?: number;\n}\n\n/** How long an NFC-e may wait in contingency before it must be transmitted (24 h); the warning goes out at 20 h. */\nexport const CONTINGENCY_WARNING_AFTER_MS = 20 * 3_600_000;\n\n/** A step's failure that no retry will cure: the document waits for a person. */\nconst NEEDS_A_PERSON = new Set([\"NOT_SUPPORTED\", \"NOT_ISSUABLE\", \"NOT_FOUND\", \"INVALID_INPUT\", \"SERIES_EXHAUSTED\"]);\n\nasync function issuable({ ctx }: Deps, ownerId: string, issuingPointId: string, model: FiscalDocumentModel) {\n const profile = await ctx.requireProfile(ownerId);\n if (profile.documentPolicy !== \"ISSUED_HERE\") {\n throw new FiscalDocumentError(\"NOT_ISSUABLE\", `owner ${ownerId}'s documentPolicy is ${profile.documentPolicy}.`);\n }\n const point = await ctx.requirePoint(ownerId, issuingPointId);\n if (point.model !== model) throw new FiscalDocumentError(\"INVALID_INPUT\", `issuing point ${point.id} issues ${point.model}, not ${model}.`);\n return { profile, point };\n}\n\nasync function liveDocument({ config }: Deps, input: Omit<IssueInput, \"issuingPointId\">): Promise<FiscalDocument | null> {\n const live = (await config.store.listBySubject(input.ownerId, input.subjectId, input.model)).filter(isLive);\n return live[live.length - 1] ?? null;\n}\n\nasync function requireDocument({ config }: Deps, ownerId: string, documentId: string): Promise<FiscalDocument> {\n const document = await config.store.getDocument(ownerId, documentId);\n if (document === null) throw new FiscalDocumentError(\"NOT_FOUND\", `owner ${ownerId} has no document ${documentId}.`);\n return document;\n}\n\n/** Number a new document — or, when the subject already has a live one (a concurrent call won), answer that one. */\nasync function numberOrExisting(deps: Deps, input: Omit<IssueInput, \"issuingPointId\">, create: () => Promise<FiscalDocument>) {\n try {\n return { document: await create(), created: true };\n } catch (error) {\n if (!(error instanceof FiscalDocumentError) || error.code !== \"SUBJECT_HAS_DOCUMENT\") throw error;\n const existing = await liveDocument(deps, input);\n if (existing === null) throw error;\n return { document: existing, created: false };\n }\n}\n\nasync function issue(deps: Deps, input: IssueInput): Promise<FiscalDocument> {\n assertOnlineDeadline(input.onlineDeadlineMs);\n const deadlineAt = input.onlineDeadlineMs === undefined ? null : Date.now() + input.onlineDeadlineMs;\n const { profile, point } = await issuable(deps, input.ownerId, input.issuingPointId, input.model);\n const existing = await liveDocument(deps, input);\n if (existing !== null) return answerLive(deps.ctx, existing, profile, input.onlineDeadlineMs);\n const signing = await deps.ctx.material(profile);\n const draft = await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: input.subjectId, model: input.model });\n assertDraftFits(draft, input.model);\n const numbered = await numberOrExisting(deps, input, () =>\n deps.ctx.createNumbered({ profile, point, subjectId: input.subjectId, model: input.model, seriesKind: \"ONLINE\", draft }),\n );\n if (!numbered.created) return answerLive(deps.ctx, numbered.document, profile, input.onlineDeadlineMs);\n return submit(deps.ctx, numbered.document, profile, point, signing, deadlineAt);\n}\n\n/** Sign the sale offline at once (the register knows it is offline). A failure leaves it PENDING for the sweep. */\nasync function issueOffline(deps: Deps, input: Omit<IssueInput, \"model\">): Promise<FiscalDocument> {\n const target = { ...input, model: \"NFCE\" as const };\n const { profile, point } = await issuable(deps, input.ownerId, input.issuingPointId, \"NFCE\");\n const existing = await liveDocument(deps, target);\n if (existing !== null) return existing;\n const signing = await deps.ctx.material(profile);\n const draft = await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: input.subjectId, model: \"NFCE\" });\n assertDraftFits(draft, \"NFCE\");\n const numbered = await numberOrExisting(deps, target, () =>\n deps.ctx.createNumbered({ profile, point, subjectId: input.subjectId, model: \"NFCE\", seriesKind: \"CONTINGENCY\", draft }),\n );\n return numbered.created ? signPending(deps.ctx, numbered.document, profile, signing) : numbered.document;\n}\n\n/**\n * A contingency NFC-e SEFAZ rejected on transmission: the buyer holds its\n * DANFE, so the number is never voided. The store corrects the sale (the\n * host's `SaleSource` answers the corrected one) and it is signed again\n * under the SAME series, number and key code, then transmitted by the job.\n */\n/** The fields a buyer's DANFE prints and its QR code encodes, which a resend may never change. */\nfunction printedFieldsChange(document: FiscalDocument, totals: DocumentTotals, buyerTaxId: string | null): boolean {\n return totals.totalCents !== document.totals.totalCents || buyerTaxId !== document.buyerTaxId;\n}\n\n/**\n * A contingency NFC-e SEFAZ rejected on transmission: the buyer holds its\n * DANFE, so the number is never voided. The store corrects the sale (the\n * host's `SaleSource` answers the corrected one) and it is signed again\n * under the SAME series, number and key code, then transmitted by the job.\n * A correction that would change the total or the buyer's document — what\n * the DANFE prints and its QR encodes — is refused: that sale needs a new\n * note, issued by a person (decided on FUT-2237).\n */\nasync function resendContingency(deps: Deps, input: { ownerId: string; documentId: string }): Promise<FiscalDocument> {\n const document = await requireDocument(deps, input.ownerId, input.documentId);\n if (document.status !== \"REJECTED\" || document.seriesKind !== \"CONTINGENCY\" || document.contingency === null) {\n throw new FiscalDocumentError(\"TRANSITION_REFUSED\", `document ${document.id} is not a rejected contingency NFC-e.`);\n }\n const profile = await deps.ctx.requireProfile(input.ownerId);\n const draft = await deps.config.sales.saleFor({ ownerId: input.ownerId, subjectId: document.subjectId, model: document.model });\n assertDraftFits(draft, document.model);\n const totals = totalsOf(draft);\n const buyerTaxId = draft.buyer?.document.number ?? null;\n if (printedFieldsChange(document, totals, buyerTaxId)) {\n throw new FiscalDocumentError(\n \"RESEND_CHANGES_PRINTED_FIELDS\",\n `the correction changes document ${document.id}'s total or buyer, which its DANFE prints: issue a new note.`,\n );\n }\n const sale = { ...draft, series: document.series, number: document.number, keyCode: document.keyCode, issuedAt: document.issuedAt, issuer: issuerOf(profile) };\n const outcome = await deps.config.issuer.signContingency({\n environment: document.environment,\n signing: await deps.ctx.material(profile),\n document: sale,\n contingency: document.contingency,\n });\n if (!outcome.ok) throw new FiscalDocumentError(\"NOT_ISSUABLE\", `the corrected sale could not be signed: ${outcome.error.class} ${outcome.error.code ?? \"\"}`.trim());\n const xmlKey = xmlKeys.signed(outcome.answer.accessKey);\n await deps.config.storage.put(xmlKey, outcome.answer.signedXml, \"application/xml\");\n return deps.ctx.advance(document, { kind: \"RESIGN\", answer: outcome.answer, sale, totals, buyerTaxId, xmlKey });\n}\n\nasync function cancel(\n deps: Deps,\n input: { ownerId: string; documentId: string; reason: string },\n): Promise<{ document: FiscalDocument; failure: IssuerFailure | null }> {\n assertReason(input.reason, \"reason\");\n const document = await requireDocument(deps, input.ownerId, input.documentId);\n if (document.status !== \"AUTHORIZED\" || document.accessKey === null || document.protocol === null) {\n throw new FiscalDocumentError(\"TRANSITION_REFUSED\", `document ${document.id} is ${document.status}; only an authorised document is cancelled.`);\n }\n const profile = await deps.ctx.requireProfile(input.ownerId);\n const outcome = await deps.config.issuer.cancel({\n model: document.model,\n environment: document.environment,\n signing: await deps.ctx.material(profile),\n accessKey: document.accessKey,\n protocol: document.protocol,\n reason: input.reason,\n });\n if (!outcome.ok) return { document, failure: outcome.error };\n const eventXmlKey = outcome.answer.eventXml === null ? null : xmlKeys.cancel(document.accessKey);\n if (eventXmlKey !== null) await deps.config.storage.put(eventXmlKey, outcome.answer.eventXml ?? \"\", \"application/xml\");\n const cancelled = await deps.ctx.advance(document, { kind: \"CANCEL\", answer: outcome.answer, reason: input.reason, eventXmlKey });\n return { document: cancelled, failure: null };\n}\n\n/** SEFAZ's refusals of a cancel that came too late: \"prazo de cancelamento superior ao previsto\". */\nexport const LATE_CANCEL_CODES = [\"501\"] as const;\n\nconst isLateCancel = (code: string | null): boolean => code !== null && (LATE_CANCEL_CODES as readonly string[]).includes(code);\n\n/** The subject's live return NF-e that quotes this key, if one was issued already. */\nasync function liveReturnOf(deps: Deps, document: FiscalDocument): Promise<FiscalDocument | null> {\n const returns = (await deps.config.store.listBySubject(document.ownerId, document.subjectId, \"NFE\")).filter(isLive);\n const quoting = returns.filter((candidate) => returnsDocument(candidate, document));\n return quoting[quoting.length - 1] ?? null;\n}\n\n/**\n * Cancel an authorised document; when SEFAZ refuses the cancel as LATE (501),\n * issue the buyer's return instead: an NF-e of entry on `returnPointId`, the\n * host's `SaleSource` answering the return sale for the document's subject\n * (`model: \"NFE\"`), which must quote this document's key. The document itself\n * stays AUTHORIZED: a return never cancels it.\n *\n * Idempotent: a document already cancelled, or already answered with a live\n * return, is answered as it stands, with no call to the issuer. A return the\n * sale source does not quote is refused before a number is drawn.\n */\nasync function cancelOrReturn(deps: Deps, input: CancelOrReturnInput): Promise<CancelOrReturnResult> {\n assertReason(input.reason, \"reason\");\n const document = await requireDocument(deps, input.ownerId, input.documentId);\n if (document.status === \"CANCELLED\") return { outcome: \"CANCELLED\", document, returnDocument: null, failure: null };\n const existing = document.accessKey === null ? null : await liveReturnOf(deps, document);\n if (existing !== null) return { outcome: \"RETURNED\", document, returnDocument: existing, failure: null };\n const cancelled = await cancel(deps, input);\n if (cancelled.failure === null) return { outcome: \"CANCELLED\", document: cancelled.document, returnDocument: null, failure: null };\n const late = cancelled.failure.class === \"REJECTED\" && isLateCancel(cancelled.failure.code);\n if (!late) return { outcome: \"REFUSED\", document: cancelled.document, returnDocument: null, failure: cancelled.failure };\n return { outcome: \"RETURNED\", document: cancelled.document, returnDocument: await issueReturn(deps, document, input.returnPointId), failure: cancelled.failure };\n}\n\n/** Whether `candidate` is a buyer's return NF-e of entry quoting `document`. */\nfunction returnsDocument(candidate: Pick<FiscalDocument, \"model\" | \"sale\">, document: FiscalDocument): boolean {\n const quotes = (candidate.sale.referencedDocuments ?? []).some((reference) => reference.accessKey === document.accessKey);\n return candidate.model === \"NFE\" && candidate.sale.purpose === \"RETURN\" && quotes;\n}\n\n/**\n * The return of a late-cancelled NFC-e. Refused, before any number is drawn,\n * for anything but an NFC-e, for a subject that already holds a live NF-e that\n * is not this return (the live index allows one per subject and model), and\n * for a sale source whose return does not quote the document.\n */\nasync function issueReturn(deps: Deps, document: FiscalDocument, returnPointId: string): Promise<FiscalDocument> {\n if (document.model !== \"NFCE\") {\n throw new FiscalDocumentError(\"RETURN_OF_NFCE_ONLY\", `document ${document.id} is an ${document.model}: only an NFC-e is answered with a buyer's return.`);\n }\n const live = (await deps.config.store.listBySubject(document.ownerId, document.subjectId, \"NFE\")).filter(isLive);\n if (live.length > 0) {\n throw new FiscalDocumentError(\"SUBJECT_HAS_DOCUMENT\", `subject ${document.subjectId} already holds a live NF-e that is not document ${document.id}'s return.`);\n }\n const draft = await deps.config.sales.saleFor({ ownerId: document.ownerId, subjectId: document.subjectId, model: \"NFE\" });\n if (!returnsDocument({ model: \"NFE\", sale: draft as FiscalDocument[\"sale\"] }, document)) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `the return the sale source answered for subject ${document.subjectId} does not quote document ${document.id}.`);\n }\n const returned = await issue(deps, { ownerId: document.ownerId, subjectId: document.subjectId, issuingPointId: returnPointId, model: \"NFE\" });\n if (returned.id === document.id || !returnsDocument(returned, document)) {\n throw new FiscalDocumentError(\"CONFLICT\", `subject ${document.subjectId}'s live NF-e is not document ${document.id}'s return.`);\n }\n return returned;\n}\n\n/** Whether a lookup's answer moves this document (a settled number moves only while it is owed one). */\nfunction lookupMoves(document: FiscalDocument): boolean {\n if (!canTransition(document.status, \"LOOKUP\")) return false;\n if (document.status === \"REPLACED\" || document.status === \"REJECTED\") return document.numberVoid === \"LOOKUP_FIRST\";\n return true;\n}\n\nasync function lookup(\n deps: Deps,\n input: { ownerId: string; documentId: string },\n): Promise<{ document: FiscalDocument; answer: LookedUpDocument | null; failure: IssuerFailure | null }> {\n const document = await requireDocument(deps, input.ownerId, input.documentId);\n if (document.accessKey === null) throw new FiscalDocumentError(\"NOT_FOUND\", `document ${document.id} has no access key yet.`);\n const profile = await deps.ctx.requireProfile(input.ownerId);\n const outcome = await deps.config.issuer.lookup({\n model: document.model,\n environment: document.environment,\n signing: await deps.ctx.material(profile),\n accessKey: document.accessKey,\n });\n if (!outcome.ok) return { document, answer: null, failure: outcome.error };\n if (!lookupMoves(document)) return { document, answer: outcome.answer, failure: null };\n const xmlKey = document.status === \"SUBMITTED\" ? await storeNfeProc(deps.ctx, document, outcome.answer) : undefined;\n const looked = await deps.ctx.advance(document, { kind: \"LOOKUP\", answer: outcome.answer, ...(xmlKey === undefined ? {} : { xmlKey }) });\n // A live REJECTED number found SEFAZ's is back to SUBMITTED: settle it now if its XML is held.\n const after = document.status === \"REJECTED\" ? await settleWithXml(deps.ctx, looked, outcome.answer) : looked;\n return { document: after, answer: outcome.answer, failure: null };\n}\n\n/** One step of the sweep on one document: whatever it is owed next. */\nasync function step({ ctx }: Deps, document: FiscalDocument): Promise<FiscalDocument> {\n const profile = await ctx.requireProfile(document.ownerId);\n const signing = await ctx.material(profile);\n if (document.numberVoid !== null) return settleNumber(ctx, document, profile, signing);\n if (document.status === \"CONTINGENCY\") return transmit(ctx, document, signing);\n if (document.seriesKind === \"CONTINGENCY\") return signPending(ctx, document, profile, signing);\n const point = await ctx.requirePoint(document.ownerId, document.issuingPointId);\n return submit(ctx, document, profile, point, signing);\n}\n\n/** A step that threw is never silent: the document is deferred, or handed to a person when no retry will cure it. */\nasync function deferThrown(deps: Deps, document: FiscalDocument, error: unknown): Promise<void> {\n if (error instanceof FiscalDocumentError && error.code === \"CONFLICT\") return;\n const attention = error instanceof FiscalDocumentError && NEEDS_A_PERSON.has(error.code);\n const reason = error instanceof Error ? error.message : \"unknown failure\";\n const current = (await deps.config.store.getDocument(document.ownerId, document.id)) ?? document;\n await deps.ctx.advance(current, { kind: \"DEFER\", reason, error: null, attention }).catch(() => undefined);\n}\n\nasync function run(deps: Deps, documents: readonly FiscalDocument[]): Promise<SweepReport> {\n const report: SweepReport = { advanced: [], failures: [] };\n for (const document of documents) {\n try {\n const after = await step(deps, document);\n report.advanced.push({ documentId: after.id, status: after.status });\n } catch (error) {\n report.failures.push({ documentId: document.id, message: error instanceof Error ? error.message : \"unknown failure\" });\n await deferThrown(deps, document, error);\n }\n }\n return report;\n}\n\n/** Tell the owner of every NFC-e 20 h into contingency (the transmission deadline is 24 h), once each. */\nasync function warnContingencyDeadlines(deps: Deps, limit: number): Promise<number> {\n const signedBefore = new Date(deps.config.now().getTime() - CONTINGENCY_WARNING_AFTER_MS).toISOString();\n const due = await deps.config.store.listContingencyDeadline({ signedBefore, limit });\n for (const document of due) {\n const warned = await deps.ctx.advance(document, { kind: \"WARN\" });\n await deps.config.notify.emit({\n type: FISCAL_CONTINGENCY_DEADLINE,\n recipient: { tenantId: document.ownerId, permission: FISCAL_ISSUE },\n payload: { documentId: warned.id, subjectId: warned.subjectId, series: warned.series, number: warned.number, since: warned.contingency?.since ?? \"\" },\n });\n }\n return due.length;\n}\n\nexport function createFiscalDocuments(config: FiscalDocumentsServiceConfig) {\n assertConfig(config);\n if (typeof config.cipher?.encrypt !== \"function\") throw new TypeError(\"createFiscalDocuments needs cipher.\");\n if (typeof config.readCertificate !== \"function\") throw new TypeError(\"createFiscalDocuments needs readCertificate.\");\n const deps: Deps = { ctx: new FiscalContext(config), config };\n const { store } = config;\n return {\n getProfile: (ownerId: string) => store.getProfile(ownerId),\n saveProfile: saveProfile.bind(null, deps),\n uploadCertificate: uploadCertificate.bind(null, deps),\n listIssuingPoints: (ownerId: string) => store.listIssuingPoints(ownerId),\n createIssuingPoint: createIssuingPoint.bind(null, deps),\n /** Issue the subject's document, or answer the live one it has. A rejection is final; anything SEFAZ may still answer is the sweep's. */\n issue: issue.bind(null, deps),\n issueOffline: issueOffline.bind(null, deps),\n resendContingency: resendContingency.bind(null, deps),\n /** Cancel an authorised document. A refusal (late, say) answers the issuer's failure and changes nothing. */\n cancel: cancel.bind(null, deps),\n /**\n * Cancel an authorised document, or — when SEFAZ says the cancel is too late\n * (501) — issue the buyer's return NF-e of entry quoting it. Idempotent.\n */\n cancelOrReturn: cancelOrReturn.bind(null, deps),\n /** Link payment transactions to an authorised document (event 110300), once each. Idempotent. */\n linkPayment: linkPayment.bind(null, deps),\n /** Ask SEFAZ what it knows of the key; a state the answer moves is recorded. */\n lookup: lookup.bind(null, deps),\n /** A person takes a document back from `attention`; the sweep tries it again. */\n async release(input: { ownerId: string; documentId: string }): Promise<FiscalDocument> {\n return deps.ctx.advance(await requireDocument(deps, input.ownerId, input.documentId), { kind: \"RELEASE\" });\n },\n getDocument: requireDocument.bind(null, deps),\n listBySubject: (ownerId: string, subjectId: string, model: FiscalDocumentModel) => store.listBySubject(ownerId, subjectId, model),\n async listEvents(ownerId: string, documentId: string) {\n await requireDocument(deps, ownerId, documentId);\n return store.listEvents(documentId);\n },\n /** One pass of the retry sweep: PENDING/SUBMITTED documents and owed numbers whose next attempt has come. */\n sweep: async (limit: number): Promise<SweepReport> => run(deps, await store.listDue({ now: deps.ctx.nowIso(), limit })),\n /** Contingency blocks (FUT-4717), the ContingencyBlockSource; `NOT_SUPPORTED` over a store without them. */\n reserveBlock: reserveBlock.bind(null, deps),\n recordSigned: recordSigned.bind(null, deps),\n closeBlock: closeBlock.bind(null, deps),\n abandonBlocks: abandonBlocks.bind(null, deps),\n listBlocks: listBlocks.bind(null, deps),\n listKnownGaps: listKnownGaps.bind(null, deps),\n listUnknownRanges: listUnknownRanges.bind(null, deps),\n voidKnownGaps: voidKnownGaps.bind(null, deps),\n /** One pass of the contingency transmission, then the 20-hour deadline warnings. */\n async transmitContingency(limit: number): Promise<SweepReport> {\n const report = await run(deps, await store.listContingency({ now: deps.ctx.nowIso(), limit }));\n await warnContingencyDeadlines(deps, limit);\n return report;\n },\n };\n}\n\n\nexport type FiscalDocuments = ReturnType<typeof createFiscalDocuments>;\n","/**\n * The memory store's contingency blocks (FUT-4717): the same promises as the\n * SQL store's — a block advances the series' counter and is recorded\n * together, a signed note and its event are inserted together, a key or a\n * number recorded twice is a `CONFLICT`, and a subject keeps one live\n * document.\n */\n\nimport { FiscalDocumentError } from \"./errors\";\nimport type { ContingencyBlock, ContingencyBlockState, ContingencyBlockStore, NumberRange, NumberRequest } from \"./ports\";\nimport { type FiscalDocument, type FiscalDocumentEvent, isLive } from \"./types\";\n\nconst MAX_NUMBER = 999_999_999;\n\ninterface MemoryBlockState {\n readonly counters: Map<string, number>;\n readonly seriesOwner: Map<string, string>;\n readonly documents: Map<string, FiscalDocument>;\n readonly events: FiscalDocumentEvent[];\n readonly counterKey: (request: Pick<NumberRequest, \"issuerCnpj\" | \"environment\" | \"model\" | \"series\">) => string;\n}\n\ninterface Void extends NumberRange {\n readonly blockId: string;\n}\n\nfunction sameSeries(a: Pick<FiscalDocument, \"issuerCnpj\" | \"environment\" | \"model\" | \"series\">, b: typeof a): boolean {\n return a.issuerCnpj === b.issuerCnpj && a.environment === b.environment && a.model === b.model && a.series === b.series;\n}\n\nfunction stateOf(block: ContingencyBlock, documents: Iterable<FiscalDocument>, voids: readonly Void[]): ContingencyBlockState {\n const documented = [...documents]\n .filter((d) => sameSeries(d, block) && d.number >= block.from && d.number <= block.to)\n .map((d) => d.number)\n .sort((a, b) => a - b);\n const voided = voids.filter((v) => v.blockId === block.id).map(({ from, to }) => ({ from, to }));\n return { ...block, documented, voided };\n}\n\n/** Whether `block` sorts after `cursor` in the `(reservedAt, id)` keyset order. */\nfunction after(block: Pick<ContingencyBlock, \"reservedAt\" | \"id\">, cursor: Pick<ContingencyBlock, \"reservedAt\" | \"id\">): boolean {\n return block.reservedAt > cursor.reservedAt || (block.reservedAt === cursor.reservedAt && block.id > cursor.id);\n}\n\nfunction insertSigned(state: MemoryBlockState, document: FiscalDocument, event: FiscalDocumentEvent): FiscalDocument {\n const all = [...state.documents.values()];\n if (all.some((other) => other.accessKey === document.accessKey || (sameSeries(other, document) && other.number === document.number))) {\n throw new FiscalDocumentError(\"CONFLICT\", `key ${document.accessKey ?? \"\"} or number ${document.number} is recorded already.`);\n }\n const live = all.some((o) => o.ownerId === document.ownerId && o.subjectId === document.subjectId && o.model === document.model && isLive(o));\n if (live) throw new FiscalDocumentError(\"SUBJECT_HAS_DOCUMENT\", `subject ${document.subjectId} already has a live ${document.model}.`);\n state.documents.set(document.id, document);\n state.events.push(event);\n return document;\n}\n\nexport function memoryBlockMethods(state: MemoryBlockState): ContingencyBlockStore & { readonly blocks: Map<string, ContingencyBlock> } {\n const blocks = new Map<string, ContingencyBlock>();\n const voids: Void[] = [];\n const update = (id: string, patch: Partial<ContingencyBlock>) => {\n const block = blocks.get(id);\n if (block !== undefined) blocks.set(id, { ...block, ...patch });\n };\n return {\n blocks,\n async reserveContingencyBlock({ request, size, id, holder, at }) {\n const key = state.counterKey(request);\n const first = state.counters.get(key);\n if (first === undefined || state.seriesOwner.get(key) !== request.issuingPointId) {\n throw new FiscalDocumentError(\"NOT_FOUND\", `no counter for series ${request.series} on issuing point ${request.issuingPointId}.`);\n }\n if (first + size - 1 > MAX_NUMBER) throw new FiscalDocumentError(\"SERIES_EXHAUSTED\", `series ${request.series} has no ${size} numbers left.`);\n state.counters.set(key, first + size);\n const block: ContingencyBlock = {\n id, ownerId: request.ownerId, issuingPointId: request.issuingPointId, issuerCnpj: request.issuerCnpj,\n environment: request.environment, model: \"NFCE\", series: request.series, from: first, to: first + size - 1, holder,\n fate: \"OPEN\", usedUpTo: null, reservedAt: at, closedAt: null, settledAt: null,\n };\n blocks.set(id, block);\n return block;\n },\n async findContingencyBlock(input) {\n const found = [...blocks.values()].find(\n (b) => sameSeries(b, { ...input, model: \"NFCE\" }) && input.number >= b.from && input.number <= b.to,\n );\n return found === undefined || found.ownerId !== input.ownerId ? null : stateOf(found, state.documents.values(), voids);\n },\n async listContingencyBlocks(input) {\n return [...blocks.values()]\n .filter((b) => input.ownerId === undefined || b.ownerId === input.ownerId)\n .filter((b) => input.holder === undefined || b.holder === input.holder)\n .filter((b) => input.fates === undefined || input.fates.includes(b.fate))\n .filter((b) => input.reservedBefore === undefined || b.reservedAt < input.reservedBefore)\n .filter((b) => !input.unsettledOnly || b.settledAt === null)\n .filter((b) => input.after === undefined || after(b, input.after))\n .sort((a, b) => (after(a, b) ? 1 : after(b, a) ? -1 : 0))\n .slice(0, input.limit)\n .map((b) => stateOf(b, state.documents.values(), voids));\n },\n async closeContingencyBlock({ id, fate, usedUpTo, at }) {\n if (blocks.get(id)?.fate !== \"OPEN\") return false;\n update(id, { fate, usedUpTo, closedAt: at });\n return true;\n },\n async settleContingencyBlock({ id, at }) {\n update(id, { settledAt: at });\n },\n async recordContingencyVoid({ blockId, range }) {\n if (voids.some((v) => v.blockId === blockId && v.from === range.from)) return false;\n voids.push({ blockId, ...range });\n return true;\n },\n async getDocumentByAccessKey(ownerId, accessKey) {\n return [...state.documents.values()].find((d) => d.ownerId === ownerId && d.accessKey === accessKey) ?? null;\n },\n recordSignedDocument: async (document, event) => insertSigned(state, document, event),\n };\n}\n","/**\n * The reference {@link FiscalStore}: in memory, for tests and harnesses —\n * the role `createMemory*Store` plays in the packages that own storage seams.\n * It keeps the same promises as the SQL store (`./sql-store`): a draw and the\n * insert built from it commit together (a `build` that throws leaves the\n * counter untouched), a replaced document is advanced before its replacement\n * is inserted, and a subject has at most one live document per model.\n */\n\nimport { FiscalDocumentError } from \"./errors\";\nimport { memoryBlockMethods } from \"./memory-blocks\";\nimport type { ContingencyBlock, ContingencyBlockStore, FiscalStore, NumberRequest } from \"./ports\";\nimport type { EmitterProfile, IssuingPoint } from \"./profile\";\nimport { type FiscalDocument, type FiscalDocumentEvent, OWED_VOIDS, isLive } from \"./types\";\n\nconst MAX_NUMBER = 999_999_999;\n\nexport interface MemoryFiscalStore extends FiscalStore, ContingencyBlockStore {\n /** The contingency blocks, by id (FUT-4717). */\n readonly blocks: Map<string, ContingencyBlock>;\n /** Every event, in order, for assertions. */\n readonly events: FiscalDocumentEvent[];\n /** The next number each counter would hand out, keyed `cnpj|environment|model|series`. */\n readonly counters: Map<string, number>;\n}\n\nfunction counterKey(request: Pick<NumberRequest, \"issuerCnpj\" | \"environment\" | \"model\" | \"series\">): string {\n return `${request.issuerCnpj}|${request.environment}|${request.model}|${request.series}`;\n}\n\ninterface State {\n readonly counters: Map<string, number>;\n readonly seriesOwner: Map<string, string>;\n readonly documents: Map<string, FiscalDocument>;\n readonly events: FiscalDocumentEvent[];\n}\n\n/** Open a series' counter in both environments; a series belongs to one issuing point. */\nfunction openCounter(state: State, point: IssuingPoint, issuerCnpj: string, series: number, first: number): void {\n for (const environment of [\"homologacao\", \"producao\"] as const) {\n const key = counterKey({ issuerCnpj, environment, model: point.model, series });\n const owner = state.seriesOwner.get(key);\n if (owner !== undefined && owner !== point.id) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `series ${series} already belongs to issuing point ${owner}.`);\n }\n }\n for (const environment of [\"homologacao\", \"producao\"] as const) {\n const key = counterKey({ issuerCnpj, environment, model: point.model, series });\n state.seriesOwner.set(key, point.id);\n state.counters.set(key, first);\n }\n}\n\nfunction isDue(document: FiscalDocument, now: string): boolean {\n if (document.attention || document.nextAttemptAt === null || document.nextAttemptAt > now) return false;\n return document.status === \"PENDING\" || document.status === \"SUBMITTED\" || OWED_VOIDS.includes(document.numberVoid ?? \"INUTILIZED\");\n}\n\nfunction save(state: State, previous: FiscalDocument, transition: { document: FiscalDocument; event: FiscalDocumentEvent }): boolean {\n const stored = state.documents.get(previous.id);\n if (stored === undefined || stored.updatedAt !== previous.updatedAt || stored.status !== previous.status) return false;\n state.documents.set(transition.document.id, transition.document);\n state.events.push(transition.event);\n return true;\n}\n\nfunction hasLive(state: State, document: FiscalDocument): boolean {\n return [...state.documents.values()].some(\n (other) => other.ownerId === document.ownerId && other.subjectId === document.subjectId && other.model === document.model && isLive(other),\n );\n}\n\nexport function createMemoryFiscalStore(): MemoryFiscalStore {\n const profiles = new Map<string, EmitterProfile>();\n const points = new Map<string, IssuingPoint>();\n const state: State = { counters: new Map(), seriesOwner: new Map(), documents: new Map(), events: [] };\n const ordered = (key: (d: FiscalDocument) => string) =>\n [...state.documents.values()].sort((a, b) => key(a).localeCompare(key(b)));\n\n return {\n ...memoryBlockMethods({ ...state, counterKey }),\n events: state.events,\n counters: state.counters,\n getProfile: async (ownerId) => profiles.get(ownerId) ?? null,\n saveProfile: async (profile) => void profiles.set(profile.ownerId, profile),\n async getIssuingPoint(ownerId, id) {\n const point = points.get(id);\n return point?.ownerId === ownerId ? point : null;\n },\n listIssuingPoints: async (ownerId) => [...points.values()].filter((point) => point.ownerId === ownerId),\n async createIssuingPoint(point, issuerCnpj, firstNumber) {\n if (points.has(point.id)) throw new FiscalDocumentError(\"INVALID_INPUT\", `issuing point ${point.id} exists.`);\n openCounter(state, point, issuerCnpj, point.onlineSeries, firstNumber.online);\n if (point.contingencySeries !== null) openCounter(state, point, issuerCnpj, point.contingencySeries, firstNumber.contingency);\n points.set(point.id, point);\n },\n async createDocument(request, build, replace) {\n const key = counterKey(request);\n const number = state.counters.get(key);\n if (number === undefined || state.seriesOwner.get(key) !== request.issuingPointId) {\n throw new FiscalDocumentError(\"NOT_FOUND\", `no counter for series ${request.series} on issuing point ${request.issuingPointId}.`);\n }\n if (number > MAX_NUMBER) throw new FiscalDocumentError(\"SERIES_EXHAUSTED\", `series ${request.series} has no number left.`);\n const document = build(number);\n if (state.documents.has(document.id)) throw new FiscalDocumentError(\"INVALID_INPUT\", `document ${document.id} exists.`);\n const snapshot = new Map(state.documents);\n if (replace !== undefined && !save(state, replace.previous, replace.transition)) {\n throw new FiscalDocumentError(\"CONFLICT\", `document ${replace.previous.id} moved before it was replaced.`);\n }\n if (hasLive(state, document)) {\n // The replace and the insert are one transaction: undo the replace.\n state.documents.clear();\n for (const [id, kept] of snapshot) state.documents.set(id, kept);\n if (replace !== undefined) state.events.pop();\n throw new FiscalDocumentError(\"SUBJECT_HAS_DOCUMENT\", `subject ${document.subjectId} already has a live ${document.model}.`);\n }\n state.counters.set(key, number + 1);\n state.documents.set(document.id, document);\n return document;\n },\n async getDocument(ownerId, id) {\n const document = state.documents.get(id);\n return document?.ownerId === ownerId ? document : null;\n },\n listBySubject: async (ownerId, subjectId, model) =>\n ordered((d) => d.createdAt).filter((d) => d.ownerId === ownerId && d.subjectId === subjectId && d.model === model),\n listEvents: async (documentId) => state.events.filter((event) => event.documentId === documentId),\n saveTransition: async (previous, transition) => save(state, previous, transition),\n listDue: async ({ now, limit }) =>\n ordered((d) => d.nextAttemptAt ?? \"\").filter((document) => isDue(document, now)).slice(0, limit),\n listContingency: async ({ now, limit }) =>\n ordered((d) => d.nextAttemptAt ?? \"\")\n .filter((d) => d.status === \"CONTINGENCY\" && !d.attention && d.nextAttemptAt !== null && d.nextAttemptAt <= now)\n .slice(0, limit),\n listContingencyDeadline: async ({ signedBefore, limit }) =>\n ordered((d) => d.createdAt)\n .filter((d) => d.status === \"CONTINGENCY\" && d.deadlineWarnedAt === null && Date.parse(d.contingency?.since ?? \"\") < Date.parse(signedBefore))\n .slice(0, limit),\n listExpiringCertificates: async (before) =>\n [...profiles.values()].filter((p) => p.certificateExpiresAt !== null && p.certificateExpiresAt < before),\n };\n}\n","/**\n * The number draw, as one SQL statement over the package's migration\n * (`fiscal_number_counters`). A host's `FiscalStore.createDocument` runs it\n * and the document INSERT in ONE transaction: the row lock this UPDATE takes\n * serialises concurrent draws on a series, and a failed insert rolls the\n * counter back with it, so a series has no gap a failed write made. The only\n * gaps left are numbers SEFAZ never used (a rejection, a replaced document),\n * which the sweep inutilizes.\n *\n * Parameters: `$1` the issuer's CNPJ, `$2` environment, `$3` model, `$4` series,\n * `$5` issuing point id. No row comes back when the series is not that\n * point's; an exhausted series fails the counter's CHECK (at most\n * 1 000 000 000, the next number after 999 999 999), and the transaction with it.\n */\nexport const FISCAL_NEXT_NUMBER_SQL = `UPDATE \"fiscal_number_counters\"\nSET \"next_number\" = \"next_number\" + 1, \"updated_at\" = CURRENT_TIMESTAMP\nWHERE \"issuer_cnpj\" = $1 AND \"environment\" = $2 AND \"model\" = $3 AND \"series\" = $4 AND \"issuing_point_id\" = $5\nRETURNING \"next_number\" - 1 AS \"number\"`;\n","/**\n * `createPrismaFiscalStore` — the package's own {@link FiscalStore}, over the\n * host's Prisma client and the package's migration. A host passes its client\n * and nothing else: the numbering invariants live here, not in each host.\n *\n * - The draw and the insert are ONE transaction (`FISCAL_NEXT_NUMBER_SQL`):\n * the counter's row lock serialises concurrent draws, and a refused insert\n * gives the number back.\n * - Going offline replaces the online document in that same transaction,\n * before the insert, so a crash leaves exactly one live document.\n * - The per-subject guard is the partial unique index\n * `fiscal_documents_live_subject_key`: a second live document is refused as\n * `SUBJECT_HAS_DOCUMENT`, and nothing is drawn.\n * - A transition is saved only over the row it started from (`updated_at` and\n * `status`), with its event, in one transaction.\n *\n * It speaks raw SQL through the client's `$queryRawUnsafe` /\n * `$executeRawUnsafe` / `$transaction`, so it needs no generated model types\n * and works on the host's client whatever else its schema holds.\n */\n\nimport { FiscalDocumentError } from \"./errors\";\nimport type { Transition } from \"./machine\";\nimport type { ContingencyBlockStore, FiscalStore, NumberRequest } from \"./ports\";\nimport { blockMethods } from \"./sql-blocks\";\nimport { FISCAL_NEXT_NUMBER_SQL } from \"./sql\";\nimport {\n DOCUMENT_COLUMNS,\n PROFILE_COLUMNS,\n type Row,\n documentOf,\n documentValues,\n eventOf,\n placeholder,\n pointOf,\n profileOf,\n profilePlaceholder,\n profileValues,\n} from \"./sql-rows\";\nimport type { FiscalDocument } from \"./types\";\n\n/** The two raw-SQL methods of a Prisma client (or of its transaction client). */\nexport interface FiscalSqlClient {\n $queryRawUnsafe<T = unknown>(query: string, ...values: unknown[]): Promise<T>;\n $executeRawUnsafe(query: string, ...values: unknown[]): Promise<number>;\n}\n\n/** A Prisma client: the raw-SQL methods and an interactive transaction. */\nexport interface FiscalPrismaClient extends FiscalSqlClient {\n $transaction<T>(run: (tx: FiscalSqlClient) => Promise<T>): Promise<T>;\n}\n\nconst rows = (client: FiscalSqlClient, query: string, ...values: unknown[]) => client.$queryRawUnsafe<Row[]>(query, ...values);\n\nconst INSERT_DOCUMENT = `INSERT INTO \"fiscal_documents\" (${DOCUMENT_COLUMNS.map((c) => `\"${c}\"`).join(\", \")})\nVALUES (${DOCUMENT_COLUMNS.map((c, i) => placeholder(c, i + 1)).join(\", \")})`;\n\nconst MUTABLE = DOCUMENT_COLUMNS.filter((c) => c !== \"id\" && c !== \"created_at\");\n// $1 the id, $2... the mutable columns, then the row the transition started from.\nconst UPDATE_DOCUMENT = [\n `UPDATE \"fiscal_documents\" SET ${MUTABLE.map((c, i) => `\"${c}\" = ${placeholder(c, i + 2)}`).join(\", \")}`,\n `WHERE \"id\" = $1 AND \"updated_at\" = $${MUTABLE.length + 2}::timestamp(3) AND \"status\" = $${MUTABLE.length + 3}`,\n `RETURNING \"id\"`,\n].join(\"\\n\");\n\nfunction updateValues(document: FiscalDocument, previous: FiscalDocument): unknown[] {\n const all = documentValues(document);\n const mutable = MUTABLE.map((column) => all[DOCUMENT_COLUMNS.indexOf(column)]);\n return [document.id, ...mutable, previous.updatedAt, previous.status];\n}\n\nconst INSERT_EVENT = `INSERT INTO \"fiscal_document_events\" (\"id\", \"document_id\", \"kind\", \"from_status\", \"to_status\", \"at\", \"error_class\", \"code\", \"answer\")\nVALUES ($1, $2, $3, $4, $5, $6::timestamp(3), $7, $8, $9::jsonb)`;\n\nconst UPSERT_PROFILE = `INSERT INTO \"fiscal_emitter_profiles\" (${PROFILE_COLUMNS.map((c) => `\"${c}\"`).join(\", \")})\nVALUES (${PROFILE_COLUMNS.map((c, i) => profilePlaceholder(c, i + 1)).join(\", \")})\nON CONFLICT (\"owner_id\") DO UPDATE SET ${PROFILE_COLUMNS.filter((c) => c !== \"owner_id\").map((c) => `\"${c}\" = EXCLUDED.\"${c}\"`).join(\", \")}`;\n\nconst OWED = `(\"status\" IN ('PENDING', 'SUBMITTED') OR \"number_void\" IN ('LOOKUP_FIRST', 'INUTILIZE', 'CANCEL'))`;\n\n/** A unique-index or CHECK violation, recognised by its constraint's name in whatever error the client raised. */\nfunction violates(error: unknown, constraint: string): boolean {\n const text = error instanceof Error ? `${error.message} ${JSON.stringify((error as { meta?: unknown }).meta ?? \"\")}` : String(error);\n return text.includes(constraint);\n}\n\nasync function saveRow(tx: FiscalSqlClient, previous: FiscalDocument, { document, event }: Transition): Promise<boolean> {\n const updated = await rows(tx, UPDATE_DOCUMENT, ...updateValues(document, previous));\n if (updated.length === 0) return false;\n await tx.$executeRawUnsafe(\n INSERT_EVENT,\n globalThis.crypto.randomUUID(),\n event.documentId,\n event.kind,\n event.fromStatus,\n event.toStatus,\n event.at,\n event.errorClass,\n event.code,\n event.answer === null ? null : JSON.stringify(event.answer),\n );\n return true;\n}\n\nasync function draw(tx: FiscalSqlClient, request: NumberRequest): Promise<number> {\n try {\n const [row] = await rows(tx, FISCAL_NEXT_NUMBER_SQL, request.issuerCnpj, request.environment, request.model, request.series, request.issuingPointId);\n if (row === undefined) {\n throw new FiscalDocumentError(\"NOT_FOUND\", `no counter for series ${request.series} on issuing point ${request.issuingPointId}.`);\n }\n return Number(row[\"number\"]);\n } catch (error) {\n if (violates(error, \"fiscal_number_counters_next_number_check\")) {\n throw new FiscalDocumentError(\"SERIES_EXHAUSTED\", `series ${request.series} has no number left.`);\n }\n throw error;\n }\n}\n\nasync function insertDocument(tx: FiscalSqlClient, document: FiscalDocument): Promise<void> {\n try {\n await tx.$executeRawUnsafe(INSERT_DOCUMENT, ...documentValues(document));\n } catch (error) {\n if (violates(error, \"fiscal_documents_live_subject_key\")) {\n throw new FiscalDocumentError(\"SUBJECT_HAS_DOCUMENT\", `subject ${document.subjectId} already has a live ${document.model}.`);\n }\n throw error;\n }\n}\n\nasync function openCounters(tx: FiscalSqlClient, point: { id: string; model: string }, issuerCnpj: string, series: number, kind: string, first: number) {\n for (const environment of [\"homologacao\", \"producao\"]) {\n await tx.$executeRawUnsafe(\n `INSERT INTO \"fiscal_number_counters\" (\"issuer_cnpj\", \"environment\", \"model\", \"series\", \"issuing_point_id\", \"series_kind\", \"next_number\")\n VALUES ($1, $2, $3, $4, $5, $6, $7)`,\n issuerCnpj, environment, point.model, series, point.id, kind, first,\n );\n }\n}\n\ntype ProfileMethods = Pick<FiscalStore, \"getProfile\" | \"saveProfile\" | \"getIssuingPoint\" | \"listIssuingPoints\" | \"createIssuingPoint\" | \"listExpiringCertificates\">;\n\nfunction profileMethods(db: FiscalPrismaClient): ProfileMethods {\n return {\n async getProfile(ownerId) {\n const [row] = await rows(db, `SELECT * FROM \"fiscal_emitter_profiles\" WHERE \"owner_id\" = $1`, ownerId);\n return row === undefined ? null : profileOf(row);\n },\n async saveProfile(profile) {\n await db.$executeRawUnsafe(UPSERT_PROFILE, ...profileValues(profile));\n },\n async getIssuingPoint(ownerId, id) {\n const [row] = await rows(db, `SELECT * FROM \"fiscal_issuing_points\" WHERE \"id\" = $1 AND \"owner_id\" = $2`, id, ownerId);\n return row === undefined ? null : pointOf(row);\n },\n async listIssuingPoints(ownerId) {\n return (await rows(db, `SELECT * FROM \"fiscal_issuing_points\" WHERE \"owner_id\" = $1 ORDER BY \"created_at\", \"id\"`, ownerId)).map(pointOf);\n },\n createIssuingPoint: (point, issuerCnpj, firstNumber) => createIssuingPoint(db, point, issuerCnpj, firstNumber),\n async listExpiringCertificates(before) {\n return (\n await rows(db, `SELECT * FROM \"fiscal_emitter_profiles\" WHERE \"certificate_expires_at\" < $1::timestamp(3) ORDER BY \"owner_id\"`, before)\n ).map(profileOf);\n },\n };\n}\n\nasync function createIssuingPoint(db: FiscalPrismaClient, ...[point, issuerCnpj, firstNumber]: Parameters<FiscalStore[\"createIssuingPoint\"]>): Promise<void> {\n try {\n await db.$transaction(async (tx) => {\n await tx.$executeRawUnsafe(\n `INSERT INTO \"fiscal_issuing_points\" (\"id\", \"owner_id\", \"model\", \"online_series\", \"contingency_series\", \"created_at\")\n VALUES ($1, $2, $3, $4, $5, $6::timestamp(3))`,\n point.id, point.ownerId, point.model, point.onlineSeries, point.contingencySeries, point.createdAt,\n );\n await openCounters(tx, point, issuerCnpj, point.onlineSeries, \"ONLINE\", firstNumber.online);\n if (point.contingencySeries !== null) {\n await openCounters(tx, point, issuerCnpj, point.contingencySeries, \"CONTINGENCY\", firstNumber.contingency);\n }\n });\n } catch (error) {\n if (violates(error, \"fiscal_number_counters_pkey\")) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `a series of issuing point ${point.id} already belongs to another issuing point.`);\n }\n if (violates(error, \"fiscal_issuing_points_pkey\")) throw new FiscalDocumentError(\"INVALID_INPUT\", `issuing point ${point.id} exists.`);\n throw error;\n }\n}\n\nfunction documentMethods(db: FiscalPrismaClient): Omit<FiscalStore, keyof ProfileMethods> {\n const documents = async (query: string, ...values: unknown[]) => (await rows(db, query, ...values)).map(documentOf);\n return {\n createDocument: (request, build, replace) =>\n db.$transaction(async (tx) => {\n if (replace !== undefined && !(await saveRow(tx, replace.previous, replace.transition))) {\n throw new FiscalDocumentError(\"CONFLICT\", `document ${replace.previous.id} moved before it was replaced.`);\n }\n const document = build(await draw(tx, request));\n await insertDocument(tx, document);\n return document;\n }),\n async getDocument(ownerId, id) {\n const [document] = await documents(`SELECT * FROM \"fiscal_documents\" WHERE \"id\" = $1 AND \"owner_id\" = $2`, id, ownerId);\n return document ?? null;\n },\n listBySubject: (ownerId, subjectId, model) =>\n documents(\n `SELECT * FROM \"fiscal_documents\" WHERE \"owner_id\" = $1 AND \"subject_id\" = $2 AND \"model\" = $3 ORDER BY \"created_at\", \"id\"`,\n ownerId, subjectId, model,\n ),\n async listEvents(documentId) {\n return (await rows(db, `SELECT * FROM \"fiscal_document_events\" WHERE \"document_id\" = $1 ORDER BY \"seq\"`, documentId)).map(eventOf);\n },\n saveTransition: (previous, transition) => db.$transaction((tx) => saveRow(tx, previous, transition)),\n listDue: ({ now, limit }) =>\n documents(\n `SELECT * FROM \"fiscal_documents\" WHERE \"attention\" = false AND \"next_attempt_at\" <= $1::timestamp(3) AND ${OWED}\n ORDER BY \"next_attempt_at\", \"id\" LIMIT $2`,\n now, limit,\n ),\n listContingency: ({ now, limit }) =>\n documents(\n `SELECT * FROM \"fiscal_documents\" WHERE \"attention\" = false AND \"next_attempt_at\" <= $1::timestamp(3) AND \"status\" = 'CONTINGENCY'\n ORDER BY \"next_attempt_at\", \"id\" LIMIT $2`,\n now, limit,\n ),\n listContingencyDeadline: ({ signedBefore, limit }) =>\n documents(\n `SELECT * FROM \"fiscal_documents\" WHERE \"status\" = 'CONTINGENCY' AND \"deadline_warned_at\" IS NULL\n AND (\"contingency\" ->> 'since')::timestamptz < $1::timestamptz\n ORDER BY \"created_at\", \"id\" LIMIT $2`,\n signedBefore, limit,\n ),\n };\n}\n\nexport function createPrismaFiscalStore(config: { readonly prisma: FiscalPrismaClient }): FiscalStore & ContingencyBlockStore {\n const db = config?.prisma;\n if (typeof db?.$transaction !== \"function\" || typeof db.$queryRawUnsafe !== \"function\") {\n throw new TypeError(\"createPrismaFiscalStore needs prisma: the host's Prisma client.\");\n }\n return { ...profileMethods(db), ...documentMethods(db), ...blockMethods(db) };\n}\n","/**\n * The document mapping's tax half: the engine's breakdown (`computeTax`)\n * onto the `SaleForDocument` lines a host's `SaleSource` answers. The engine\n * decides; this writes what it decided:\n *\n * - one document line per breakdown line, in the breakdown's order — so an\n * exclusion the engine segregated (the service charge passed to the staff\n * at most 15% of the food and drink, class 410019; a platform's retained\n * intermediation, 410020) IS its own item, with its class and no tax\n * (RCBS art. 399 §2), and a service charge the engine did not exclude is a\n * taxed item under the class the host passed;\n * - the IBS/CBS group from the line's figures (`vBC`, the nominal rates, the\n * reduction, the amounts), or no group at all where the engine answered\n * `NONE` (MEI, não contribuinte);\n * - the net value (`vProdLiq`, NT 2026.008) where the period puts the tax\n * inside the price (from 2027), and no key at all where it does not, so a\n * 2026 document is the one it was before the field existed.\n *\n * What the engine does not know — the product code, NCM, CFOP, unit, the\n * ICMS, PIS and COFINS — arrives per line id from the host. A breakdown line\n * with no details is refused, never invented.\n */\n\nimport type { LineTax, TaxBreakdown } from \"../engine/types\";\nimport type { LineIbsCbs, SaleLine } from \"../sale/types\";\nimport { FiscalDocumentError } from \"./errors\";\n\n/** Everything a document line needs that the breakdown does not carry. */\nexport type LineDetails = Omit<SaleLine, \"id\" | \"quantity\" | \"valueCents\" | \"netValueCents\" | \"ibsCbs\">;\n\nconst SEGREGATED = new Set<LineTax[\"source\"]>([\"GORJETA_EXCLUDED\", \"INTERMEDIATION_EXCLUDED\"]);\n\nfunction ibsCbsOf(line: LineTax, breakdown: TaxBreakdown): LineIbsCbs | null {\n if (breakdown.treatment === \"NONE\") return null;\n const code = { cst: line.taxClass.cstIbsCbs, classCode: line.taxClass.cClassTrib };\n if (SEGREGATED.has(line.source)) return { ...code, figures: null };\n return {\n ...code,\n figures: {\n baseCents: line.taxBaseCents,\n reductionBp: line.reductionBp,\n cbsRateBp: line.cbsRateBp,\n cbsCents: line.cbsCents,\n ibsUfRateBp: line.ibsUfRateBp,\n ibsUfCents: line.ibsUfCents,\n ibsMunRateBp: line.ibsMunRateBp,\n ibsMunCents: line.ibsMunCents,\n },\n };\n}\n\nexport function documentLines(breakdown: TaxBreakdown, details: Readonly<Record<string, LineDetails>>): SaleLine[] {\n return breakdown.lines.map((line) => {\n const detail = details[line.lineId];\n if (detail === undefined) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `breakdown line ${line.lineId} has no document details.`);\n }\n return {\n ...detail,\n id: line.lineId,\n quantity: line.quantity,\n valueCents: line.valueCents,\n ...(line.netValueCents === null ? {} : { netValueCents: line.netValueCents }),\n ibsCbs: ibsCbsOf(line, breakdown),\n };\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4HO,IAAM,0BAA2D,CAAC,QAAQ,UAAU,WAAW;;;ACxGtG,SAAS,SAAS,SAA2C;AAC3D,QAAM,SAAS,CAAC,GAAG,IAAI,IAAI,OAAO,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AACzD,QAAM,SAAwB,CAAC;AAC/B,aAAW,UA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B;AAAA,EACF;AACF;AAjBS;AAmBF,SAAS,cAAc,WAAyB,SAA4D;AACjH,SAAO,UAAU,MAAM,IAAI,CAAC,SAAS;AACnC,UAAM,SAAS,QAAQ,KAAK,MAAM;AAClC,QAAI,WAAW,QAAW;AACxB,YAAM,IAAI,oBAAoB,iBAAiB,kBAAkB,KAAK,MAAM,2BAA2B;AAAA,IACzG;AACA,WAAO;AAAA,MACL,GAAG;AAAA,MACH,IAAI,KAAK;AAAA,MACT,UAAU,KAAK;AAAA,MACf,YAAY,KAAK;AAAA,MACjB,GAAI,KAAK,kBAAkB,OAAO,CAAC,IAAI,EAAE,eAAe,KAAK,cAAc;AAAA,MAC3E,QAAQ,SAAS,MAAM,SAAS;AAAA,IAClC;AAAA,EACF,CAAC;AACH;AAfgB;","names":["after","refuse","text","text","iso","blockOf","send","run","send","after","insertSigned","MAX_NUMBER","transition","rows","INSERT_DOCUMENT","INSERT_EVENT","violates","text","createIssuingPoint","transition"]}
|