@12-apps/fiscal 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +3 -0
  2. package/dist/{chunk-GKT3X5CF.js → chunk-3E3NBXSW.js} +11 -4
  3. package/dist/chunk-3E3NBXSW.js.map +1 -0
  4. package/dist/{chunk-MEBG7FGG.js → chunk-G6QNU4FD.js} +2 -2
  5. package/dist/{chunk-XQGW5HUG.js → chunk-GH452ITO.js} +1 -1
  6. package/dist/chunk-GH452ITO.js.map +1 -0
  7. package/dist/{chunk-GGYJPFBJ.js → chunk-HMTPJWXM.js} +2 -2
  8. package/dist/{chunk-V6G2OFLA.js → chunk-TJCUO6D6.js} +3 -3
  9. package/dist/{chunk-JVQKJNOC.js → chunk-ZKWVKCGJ.js} +1 -1
  10. package/dist/chunk-ZKWVKCGJ.js.map +1 -0
  11. package/dist/{context-yc1C2__K.d.ts → context-CwZiHLnY.d.ts} +14 -3
  12. package/dist/documents/index.d.ts +7 -5
  13. package/dist/documents/index.js +155 -8
  14. package/dist/documents/index.js.map +1 -1
  15. package/dist/http.d.ts +3 -3
  16. package/dist/http.js +3 -3
  17. package/dist/issuer/index.d.ts +2 -2
  18. package/dist/issuer/index.js +9 -1
  19. package/dist/issuer/index.js.map +1 -1
  20. package/dist/jobs.d.ts +3 -3
  21. package/dist/jobs.js +3 -3
  22. package/dist/manifest/server.d.ts +3 -3
  23. package/dist/manifest/server.js +5 -5
  24. package/dist/notifications.d.ts +2 -2
  25. package/dist/notifications.js +2 -2
  26. package/dist/sale/index.d.ts +29 -1
  27. package/dist/sale/index.js +7 -0
  28. package/dist/sale/index.js.map +1 -1
  29. package/dist/{service-BB9lWdyg.d.ts → service-Cz2O84Xr.d.ts} +46 -24
  30. package/dist/sidecar/index.d.ts +37 -1
  31. package/dist/sidecar/index.js +1 -1
  32. package/dist/{port-B1-ipIL4.d.ts → types-DSYwap42.d.ts} +128 -87
  33. package/package.json +1 -1
  34. package/prisma/migrations/20261118120000_fiscal_link_payment_event/migration.sql +9 -0
  35. package/sidecar/README.md +1 -0
  36. package/sidecar/composer.json +1 -1
  37. package/sidecar/composer.lock +7 -7
  38. package/sidecar/schema/sale-for-document.schema.json +18 -1
  39. package/sidecar/src/Nfe/DocumentMapper.php +27 -0
  40. package/sidecar/src/Nfe/Input.php +10 -0
  41. package/sidecar/src/Nfe/NfeModule.php +1 -0
  42. package/sidecar/src/Nfe/NfeService.php +120 -0
  43. package/sidecar/src/Nfe/SefazReply.php +21 -0
  44. package/src/documents/helpers.ts +2 -0
  45. package/src/documents/index.ts +2 -1
  46. package/src/documents/machine-steps.ts +12 -2
  47. package/src/documents/machine.ts +7 -0
  48. package/src/documents/payment-link.ts +156 -0
  49. package/src/documents/service.ts +20 -26
  50. package/src/documents/steps.ts +100 -4
  51. package/src/documents/types.ts +25 -1
  52. package/src/issuer/port.ts +24 -1
  53. package/src/issuer/sidecar.ts +10 -0
  54. package/src/sale/index.ts +1 -0
  55. package/src/sale/types.ts +30 -0
  56. package/src/sidecar/types.ts +38 -0
  57. package/dist/chunk-GKT3X5CF.js.map +0 -1
  58. package/dist/chunk-JVQKJNOC.js.map +0 -1
  59. package/dist/chunk-XQGW5HUG.js.map +0 -1
  60. /package/dist/{chunk-MEBG7FGG.js.map → chunk-G6QNU4FD.js.map} +0 -0
  61. /package/dist/{chunk-GGYJPFBJ.js.map → chunk-HMTPJWXM.js.map} +0 -0
  62. /package/dist/{chunk-V6G2OFLA.js.map → chunk-TJCUO6D6.js.map} +0 -0
@@ -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/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 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\nimport type { IssuerFailure, 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 { 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/** Issue (or re-issue, for a SUBMITTED one) a document on its online series. */\nexport async function submit(\n ctx: FiscalContext,\n document: FiscalDocument,\n profile: EmitterProfile,\n point: IssuingPoint,\n signing: SigningMaterial,\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 outcome = await ctx.config.issuer.issue({ model: sent.model, environment: sent.environment, signing, document: sent.sale });\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 outcome.error.class === \"CONTINGENCY\" && canGoOffline(retried, point) ? goOffline(ctx, retried, profile, point, signing) : retried;\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 * `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 { signPending, submit, transmit } from \"./steps\";\nimport { type DocumentTotals, type FiscalDocument, type FiscalDocumentModel, isLive } from \"./types\";\n\nexport type { CertificateFacts, FiscalDocumentsServiceConfig } from \"./service-profile\";\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\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 const { profile, point } = await issuable(deps, input.ownerId, input.issuingPointId, input.model);\n const existing = await liveDocument(deps, input);\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: 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 return numbered.created ? submit(deps.ctx, numbered.document, profile, point, signing) : numbered.document;\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\nexport interface CancelOrReturnInput {\n readonly ownerId: string;\n readonly documentId: string;\n /** SEFAZ's 15–255 characters, sent with the cancel. */\n readonly reason: string;\n /** The NF-e (model 55) issuing point a return is numbered on. */\n readonly returnPointId: string;\n}\n\nexport interface CancelOrReturnResult {\n /**\n * `CANCELLED` inside the window; `RETURNED` past it (the return may itself\n * still be SUBMITTED: the sweep settles it like any document); `REFUSED`\n * when the issuer refused the cancel for any other reason (nothing changed).\n */\n readonly outcome: \"CANCELLED\" | \"RETURNED\" | \"REFUSED\";\n /** The document asked about, as it stands: CANCELLED, or still AUTHORIZED beside its return. */\n readonly document: FiscalDocument;\n readonly returnDocument: FiscalDocument | null;\n readonly failure: IssuerFailure | null;\n}\n\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 /** 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;AACnG,MAAI,OAAO,QAAQ,QAAQ,YAAY,WAAY,OAAM,IAAI,UAAU,gDAAgD;AACvH,QAAM,EAAE,OAAO,IAAI;AACnB,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM,YAAY,SAAS;AACzB,UAAI,QAAQ,0BAA0B,QAAQ,QAAQ,kCAAkC,MAAM;AAC5F,cAAM,IAAI,oBAAoB,gBAAgB,SAAS,QAAQ,OAAO,sBAAsB;AAAA,MAC9F;AACA,YAAM,CAAC,WAAW,QAAQ,IAAI,MAAM,QAAQ,IAAI;AAAA,QAC9C,OAAO,QAAQ,QAAQ,qBAAqB;AAAA,QAC5C,OAAO,QAAQ,QAAQ,6BAA6B;AAAA,MACtD,CAAC;AACD,YAAM,MACJ,QAAQ,UAAU,QAAQ,QAAQ,kBAAkB,OAChD,EAAE,IAAI,QAAQ,OAAO,OAAO,MAAM,OAAO,QAAQ,QAAQ,aAAa,EAAE,IACxE;AACN,aAAO,EAAE,aAAa,EAAE,WAAW,SAAS,GAAG,IAAI;AAAA,IACrD;AAAA,EACF;AACF;AApBgB;AAsBT,SAAS,yBAA0C;AACxD,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM,YAAY,SAAS;AACzB,YAAM,IAAI;AAAA,QACR;AAAA,QACA,SAAS,QAAQ,OAAO;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACF;AAVgB;AA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C3E,MAAI,UAAU,cAAc,OAAQ,QAAO;AAC3C,QAAM,OAAO,EAAE,KAAK,KAAK,SAAS,WAAW,WAAW,KAAK,SAAS,WAAW;AACjF,MAAI,WAAW,IAAI,KAAK,MAAM,EAAG,QAAO,EAAE,GAAG,MAAM,SAAS,KAAK;AACjE,SAAO;AAAA,IACL,GAAG;AAAA,IACH,SAAS;AAAA,MACP,WAAW,KAAK;AAAA,MAChB,aAAa,KAAK;AAAA,MAClB,WAAW,KAAK;AAAA,MAChB,UAAU,KAAK;AAAA,MACf,aAAa,KAAK;AAAA,MAClB,YAAY,KAAK;AAAA,MACjB,cAAc,KAAK;AAAA,MACnB,aAAa,KAAK;AAAA,IACpB;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,QAAQ,SAAS,MAAM,SAAS;AAAA,IAClC;AAAA,EACF,CAAC;AACH;AAdgB;","names":["transition","text","createIssuingPoint","transition"]}
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;AACnG,MAAI,OAAO,QAAQ,QAAQ,YAAY,WAAY,OAAM,IAAI,UAAU,gDAAgD;AACvH,QAAM,EAAE,OAAO,IAAI;AACnB,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM,YAAY,SAAS;AACzB,UAAI,QAAQ,0BAA0B,QAAQ,QAAQ,kCAAkC,MAAM;AAC5F,cAAM,IAAI,oBAAoB,gBAAgB,SAAS,QAAQ,OAAO,sBAAsB;AAAA,MAC9F;AACA,YAAM,CAAC,WAAW,QAAQ,IAAI,MAAM,QAAQ,IAAI;AAAA,QAC9C,OAAO,QAAQ,QAAQ,qBAAqB;AAAA,QAC5C,OAAO,QAAQ,QAAQ,6BAA6B;AAAA,MACtD,CAAC;AACD,YAAM,MACJ,QAAQ,UAAU,QAAQ,QAAQ,kBAA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