@12-apps/fiscal 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +152 -7
- package/dist/chunk-27B4HNO6.js +574 -0
- package/dist/chunk-27B4HNO6.js.map +1 -0
- package/dist/chunk-3SDXLSG4.js +24 -0
- package/dist/chunk-3SDXLSG4.js.map +1 -0
- package/dist/chunk-ALABGVPO.js +247 -0
- package/dist/chunk-ALABGVPO.js.map +1 -0
- package/dist/chunk-FOFIN5M7.js +14 -0
- package/dist/chunk-FOFIN5M7.js.map +1 -0
- package/dist/chunk-HQ2NXSTX.js +85 -0
- package/dist/chunk-HQ2NXSTX.js.map +1 -0
- package/dist/chunk-PNTKG3DZ.js +47 -0
- package/dist/chunk-PNTKG3DZ.js.map +1 -0
- package/dist/chunk-RRFKYVLZ.js +192 -0
- package/dist/chunk-RRFKYVLZ.js.map +1 -0
- package/dist/chunk-V5ZQAAJT.js +210 -0
- package/dist/chunk-V5ZQAAJT.js.map +1 -0
- package/dist/chunk-X6MRDUYH.js +21 -0
- package/dist/chunk-X6MRDUYH.js.map +1 -0
- package/dist/chunk-XQGW5HUG.js +30 -0
- package/dist/chunk-XQGW5HUG.js.map +1 -0
- package/dist/context-ChnWR4Kb.d.ts +455 -0
- package/dist/danfe/en-US.d.ts +12 -0
- package/dist/danfe/en-US.js +51 -0
- package/dist/danfe/en-US.js.map +1 -0
- package/dist/danfe/index.d.ts +50 -0
- package/dist/danfe/index.js +18 -0
- package/dist/danfe/index.js.map +1 -0
- package/dist/danfe/pt-BR.d.ts +11 -0
- package/dist/danfe/pt-BR.js +51 -0
- package/dist/danfe/pt-BR.js.map +1 -0
- package/dist/documents/index.d.ts +169 -0
- package/dist/documents/index.js +1228 -0
- package/dist/documents/index.js.map +1 -0
- package/dist/engine/index.d.ts +3 -246
- package/dist/http.d.ts +73 -0
- package/dist/http.js +16 -0
- package/dist/http.js.map +1 -0
- package/dist/issuer/index.d.ts +43 -0
- package/dist/issuer/index.js +131 -0
- package/dist/issuer/index.js.map +1 -0
- package/dist/jobs.d.ts +74 -0
- package/dist/jobs.js +22 -0
- package/dist/jobs.js.map +1 -0
- package/dist/labels-BNvflT0h.d.ts +44 -0
- package/dist/manifest/index.d.ts +30 -16
- package/dist/manifest/index.js +11 -17
- package/dist/manifest/index.js.map +1 -1
- package/dist/manifest/server.d.ts +57 -0
- package/dist/manifest/server.js +25 -0
- package/dist/manifest/server.js.map +1 -0
- package/dist/notifications.d.ts +93 -0
- package/dist/notifications.js +41 -0
- package/dist/notifications.js.map +1 -0
- package/dist/port-DpRFK56U.d.ts +238 -0
- package/dist/sale/index.d.ts +243 -0
- package/dist/sale/index.js +1 -0
- package/dist/sale/index.js.map +1 -0
- package/dist/service-KTjH7AxW.d.ts +139 -0
- package/dist/sidecar/index.d.ts +216 -0
- package/dist/sidecar/index.js +8 -0
- package/dist/sidecar/index.js.map +1 -0
- package/dist/types-B1b8LIWX.d.ts +247 -0
- package/package.json +63 -5
- package/prisma/fiscal.prisma +158 -0
- package/prisma/migrations/20261113220000_fiscal_documents/migration.sql +201 -0
- package/sidecar/.dockerignore +5 -0
- package/sidecar/Dockerfile +68 -0
- package/sidecar/README.md +149 -0
- package/sidecar/composer.json +30 -0
- package/sidecar/composer.lock +2224 -0
- package/sidecar/docker/apache.conf +14 -0
- package/sidecar/docker/icp-brasil.pem +8031 -0
- package/sidecar/docker/mpm.conf +17 -0
- package/sidecar/docker/openssl.cnf +16 -0
- package/sidecar/docker/php.ini +19 -0
- package/sidecar/public/index.php +15 -0
- package/sidecar/schema/sale-for-document.schema.json +401 -0
- package/sidecar/src/ErrorClass.php +31 -0
- package/sidecar/src/Http/Request.php +48 -0
- package/sidecar/src/Http/Response.php +32 -0
- package/sidecar/src/Http/Router.php +59 -0
- package/sidecar/src/Kernel.php +99 -0
- package/sidecar/src/Module.php +31 -0
- package/sidecar/src/Nfe/Classifier.php +89 -0
- package/sidecar/src/Nfe/Credentials.php +52 -0
- package/sidecar/src/Nfe/DocumentMapper.php +383 -0
- package/sidecar/src/Nfe/DocumentSchema.php +39 -0
- package/sidecar/src/Nfe/Input.php +125 -0
- package/sidecar/src/Nfe/Model.php +17 -0
- package/sidecar/src/Nfe/NfeModule.php +62 -0
- package/sidecar/src/Nfe/NfeService.php +504 -0
- package/sidecar/src/Nfe/Sefaz.php +49 -0
- package/sidecar/src/Nfe/SefazReply.php +81 -0
- package/sidecar/src/Nfe/Transport/CurlTransport.php +198 -0
- package/sidecar/src/Nfe/Transport/SoapAdapter.php +57 -0
- package/sidecar/src/Nfe/Transport/Transport.php +20 -0
- package/sidecar/src/Nfe/Transport/TransportFailure.php +42 -0
- package/sidecar/src/RequestLog.php +54 -0
- package/sidecar/src/ServiceError.php +69 -0
- package/src/danfe/en-US.ts +53 -0
- package/src/danfe/index.ts +11 -0
- package/src/danfe/labels.ts +49 -0
- package/src/danfe/pt-BR.ts +52 -0
- package/src/danfe/render.ts +265 -0
- package/src/danfe/xml.ts +45 -0
- package/src/documents/context.ts +260 -0
- package/src/documents/errors.ts +41 -0
- package/src/documents/helpers.ts +128 -0
- package/src/documents/index.ts +39 -0
- package/src/documents/lines.ts +63 -0
- package/src/documents/machine-steps.ts +260 -0
- package/src/documents/machine.ts +128 -0
- package/src/documents/memory.ts +138 -0
- package/src/documents/nfe-proc.ts +51 -0
- package/src/documents/ports.ts +130 -0
- package/src/documents/profile-input.ts +168 -0
- package/src/documents/profile.ts +98 -0
- package/src/documents/service-profile.ts +104 -0
- package/src/documents/service.ts +296 -0
- package/src/documents/settle.ts +121 -0
- package/src/documents/signing.ts +61 -0
- package/src/documents/sql-rows.ts +180 -0
- package/src/documents/sql-store.ts +242 -0
- package/src/documents/sql.ts +18 -0
- package/src/documents/steps.ts +173 -0
- package/src/documents/tests/integration/pglite.ts +73 -0
- package/src/documents/types.ts +193 -0
- package/src/http.ts +264 -0
- package/src/issuer/index.ts +9 -0
- package/src/issuer/port.ts +109 -0
- package/src/issuer/sidecar.ts +171 -0
- package/src/jobs.ts +115 -0
- package/src/manifest/index.ts +25 -16
- package/src/manifest/server.ts +20 -0
- package/src/notifications.ts +120 -0
- package/src/sale/index.ts +8 -0
- package/src/sale/types.ts +292 -0
- package/src/sidecar/index.ts +9 -0
- package/src/sidecar/types.ts +243 -0
|
@@ -0,0 +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, 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 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 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 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/** 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 /** 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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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"]}
|
package/dist/engine/index.d.ts
CHANGED
|
@@ -1,248 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* POINTS (1 bp = 0.01%), dates are ISO calendar days (`YYYY-MM-DD`) in the
|
|
4
|
-
* seller's own clock — the fato gerador is the local day of the supply, and the
|
|
5
|
-
* host, which owns the clock, says which day that was.
|
|
6
|
-
*
|
|
7
|
-
* Nothing here has a default. Every field is required, and a value the engine
|
|
8
|
-
* cannot read is refused with a `FiscalEngineError`, never guessed.
|
|
9
|
-
*/
|
|
10
|
-
/** An ISO calendar day, `YYYY-MM-DD`. */
|
|
11
|
-
type IsoDate = string;
|
|
12
|
-
/**
|
|
13
|
-
* The seller's IBS/CBS regime (LC 214/2025 art. 41).
|
|
14
|
-
*
|
|
15
|
-
* - `REGIME_REGULAR` — Lucro Presumido/Real: the full breakdown, "por fora".
|
|
16
|
-
* - `SIMPLES_IBS_CBS_REGULAR` — the Simples híbrido (art. 41 §3): a Simples
|
|
17
|
-
* optant that applies the regime regular to IBS/CBS; full breakdown.
|
|
18
|
-
* - `SIMPLES` — inside the DAS (art. 41 §2): an `INFORMATIVE` breakdown, with
|
|
19
|
-
* the figures a regime store would show and no amount charged "por fora".
|
|
20
|
-
* - `MEI` and `NAO_CONTRIBUINTE` — no IBS/CBS on the document: zero.
|
|
21
|
-
*/
|
|
22
|
-
type TaxRegime = "REGIME_REGULAR" | "SIMPLES_IBS_CBS_REGULAR" | "SIMPLES" | "MEI" | "NAO_CONTRIBUINTE";
|
|
23
|
-
/** The special regimes the engine applies. */
|
|
24
|
-
type RegimeEspecifico = "BARES_RESTAURANTES";
|
|
25
|
-
/** What the treatment of the seller's regime is on the date of the supply. */
|
|
26
|
-
type TaxTreatment = "FULL" | "INFORMATIVE" | "NONE";
|
|
27
|
-
/** The two codes an NF-e item carries for its IBS/CBS classification. */
|
|
28
|
-
interface TaxClassCode {
|
|
29
|
-
readonly cClassTrib: string;
|
|
30
|
-
readonly cstIbsCbs: string;
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* A line's tax class, as the host classified the item. `cClassTrib` and
|
|
34
|
-
* `cstIbsCbs` are carried opaque into the snapshot (the classification table
|
|
35
|
-
* is the host's data, Informe Técnico 2025.002).
|
|
36
|
-
*
|
|
37
|
-
* `regimeEspecifico: "BARES_RESTAURANTES"` marks prepared food and
|
|
38
|
-
* non-alcoholic drinks prepared on the premises (art. 273 caput, §1; the
|
|
39
|
-
* official class is 200047). Alcohol, even prepared on the premises, and food
|
|
40
|
-
* or drink bought from third parties and resold as-is are OUT (art. 273 §2)
|
|
41
|
-
* and must carry `null`.
|
|
42
|
-
*/
|
|
43
|
-
interface TaxClass extends TaxClassCode {
|
|
44
|
-
readonly regimeEspecifico: RegimeEspecifico | null;
|
|
45
|
-
/** The class's own rate reduction (a listed-food reduction, say), 0–10000. */
|
|
46
|
-
readonly reductionBp: number;
|
|
47
|
-
}
|
|
48
|
-
/** One priced line of the supply. */
|
|
49
|
-
interface TaxLineInput {
|
|
50
|
-
/** The host's id, echoed on the output line; unique within the input. */
|
|
51
|
-
readonly id: string;
|
|
52
|
-
/**
|
|
53
|
-
* What the line costs the buyer, every unit, AFTER its allocated discount
|
|
54
|
-
* (an unconditional discount is outside the base, art. 12 §2 III). It is
|
|
55
|
-
* the price the shopper sees, so in a period whose table says
|
|
56
|
-
* `taxInsidePrice` the IBS/CBS are INSIDE it and the engine takes them out;
|
|
57
|
-
* otherwise it is the base itself and the tax is computed on top of it.
|
|
58
|
-
*/
|
|
59
|
-
readonly valueCents: number;
|
|
60
|
-
/** Units (`qCom`): positive, at most four decimals (weighed goods). */
|
|
61
|
-
readonly quantity: number;
|
|
62
|
-
/**
|
|
63
|
-
* Whether the line is food or drink — what the gorjeta's 15% ceiling is
|
|
64
|
-
* measured against (art. 274 par. único I). A delivery fee is not.
|
|
65
|
-
*/
|
|
66
|
-
readonly foodAndDrink: boolean;
|
|
67
|
-
readonly taxClass: TaxClass;
|
|
68
|
-
}
|
|
69
|
-
/** Who sells, and under which regime since when. */
|
|
70
|
-
interface SellerProfile {
|
|
71
|
-
readonly regime: TaxRegime;
|
|
72
|
-
/** The first day `regime` applies. A supply before it is refused. */
|
|
73
|
-
readonly regimeEffectiveFrom: IsoDate;
|
|
74
|
-
/** Whether the bares e restaurantes regime (arts. 273–276) applies. */
|
|
75
|
-
readonly restaurantRegime: boolean;
|
|
76
|
-
}
|
|
77
|
-
/** The service charge (taxa de serviço / gorjeta) on the supply. */
|
|
78
|
-
interface ServiceChargeInput {
|
|
79
|
-
/** Echoed as the service-charge line's id; unique within the input. */
|
|
80
|
-
readonly id: string;
|
|
81
|
-
readonly amountCents: number;
|
|
82
|
-
/** Whether the charge is passed in full to the staff. */
|
|
83
|
-
readonly passedToStaff: boolean;
|
|
84
|
-
/** The class the WHOLE charge is taxed at when it is not excluded. */
|
|
85
|
-
readonly taxClass: TaxClass;
|
|
86
|
-
}
|
|
87
|
-
/** What a digital platform retained for delivery and intermediation. */
|
|
88
|
-
interface RetainedIntermediationInput {
|
|
89
|
-
/** Echoed as the excluded line's id; unique within the input. */
|
|
90
|
-
readonly id: string;
|
|
91
|
-
/** Never passed to the restaurant; NOT included in any line's value. */
|
|
92
|
-
readonly amountCents: number;
|
|
93
|
-
}
|
|
94
|
-
/**
|
|
95
|
-
* The amounts the restaurant regime keeps out of the base (art. 274 par.
|
|
96
|
-
* único), each segregated on the document as its own item (RCBS art. 399 §2:
|
|
97
|
-
* without the segregation the base is the full value, §4).
|
|
98
|
-
*/
|
|
99
|
-
interface TaxExclusions {
|
|
100
|
-
/**
|
|
101
|
-
* Excluded (its own line, the table's gorjeta class) only when the store is
|
|
102
|
-
* in the restaurant regime, the charge is passed in full to the staff AND it
|
|
103
|
-
* is at most 15% of the food and drink. Otherwise the whole charge is a
|
|
104
|
-
* taxed line under its own class — never a partial exclusion.
|
|
105
|
-
*/
|
|
106
|
-
readonly serviceCharge: ServiceChargeInput | null;
|
|
107
|
-
/** Restaurant regime only (art. 274 par. único II); refused elsewhere. */
|
|
108
|
-
readonly retainedIntermediation: RetainedIntermediationInput | null;
|
|
109
|
-
}
|
|
110
|
-
/** The IBS share of one sphere in one period: the reference and the overrides. */
|
|
111
|
-
interface IbsSphereRates {
|
|
112
|
-
/** The reference rate, which applies wherever no own rate is listed. */
|
|
113
|
-
readonly referenceBp: number;
|
|
114
|
-
}
|
|
115
|
-
interface IbsUfRates extends IbsSphereRates {
|
|
116
|
-
/** State rates keyed by the 2-digit IBGE state code. */
|
|
117
|
-
readonly byUf: Readonly<Record<string, number>>;
|
|
118
|
-
}
|
|
119
|
-
interface IbsMunRates extends IbsSphereRates {
|
|
120
|
-
/** Municipal rates keyed by the 7-digit IBGE municipality code. */
|
|
121
|
-
readonly byMunicipality: Readonly<Record<string, number>>;
|
|
122
|
-
}
|
|
123
|
-
/** One stretch of time with one set of rates. */
|
|
124
|
-
interface RatePeriod {
|
|
125
|
-
readonly from: IsoDate;
|
|
126
|
-
/** Inclusive; `null` is open-ended. */
|
|
127
|
-
readonly to: IsoDate | null;
|
|
128
|
-
/** `ESTIMATE` stamps every result computed on it `provisional`. */
|
|
129
|
-
readonly status: "LAW" | "ESTIMATE";
|
|
130
|
-
readonly source: string;
|
|
131
|
-
/** The test year: highlighted, payment waived (art. 348 §1). */
|
|
132
|
-
readonly informative: boolean;
|
|
133
|
-
/** `false` in 2026: the test rates are not applied to Simples optants (art. 348 III "c"). */
|
|
134
|
-
readonly appliesToSimplesNacional: boolean;
|
|
135
|
-
/**
|
|
136
|
-
* Whether the IBS/CBS sit INSIDE the item's value on the document (they
|
|
137
|
-
* compose `vProd` and the price without tax travels in `vProdLiq`) — from
|
|
138
|
-
* 2027 by the NF-e layout. When true, a line's `valueCents` is the
|
|
139
|
-
* tax-inclusive price.
|
|
140
|
-
*/
|
|
141
|
-
readonly taxInsidePrice: boolean;
|
|
142
|
-
readonly cbsBp: number;
|
|
143
|
-
readonly ibsUf: IbsUfRates;
|
|
144
|
-
readonly ibsMun: IbsMunRates;
|
|
145
|
-
}
|
|
146
|
-
/** A versioned rate table: DATA, loaded by the host, stamped on every result. */
|
|
147
|
-
interface RateTables {
|
|
148
|
-
readonly version: string;
|
|
149
|
-
readonly notes?: readonly string[];
|
|
150
|
-
/** The gorjeta's ceiling as a share of food and drink: 1500 (art. 274 par. único I). */
|
|
151
|
-
readonly gorjetaCapBp: number;
|
|
152
|
-
readonly gorjetaCapSource?: string;
|
|
153
|
-
/** The classes the excluded items are segregated under (410019, 410020). */
|
|
154
|
-
readonly exclusionClasses: {
|
|
155
|
-
readonly GORJETA: TaxClassCode;
|
|
156
|
-
readonly INTERMEDIATION: TaxClassCode;
|
|
157
|
-
readonly source?: string;
|
|
158
|
-
};
|
|
159
|
-
readonly specialRegimes: Readonly<Record<RegimeEspecifico, {
|
|
160
|
-
readonly reductionBp: number;
|
|
161
|
-
readonly source: string;
|
|
162
|
-
}>>;
|
|
163
|
-
readonly periods: readonly RatePeriod[];
|
|
164
|
-
}
|
|
165
|
-
/** Everything one computation needs. */
|
|
166
|
-
interface TaxInput {
|
|
167
|
-
readonly lines: readonly TaxLineInput[];
|
|
168
|
-
readonly seller: SellerProfile;
|
|
169
|
-
/**
|
|
170
|
-
* The 7-digit IBGE code of the place the IBS goes to: the establishment,
|
|
171
|
-
* or for a delivered good the place of delivery (art. 11 I).
|
|
172
|
-
*/
|
|
173
|
-
readonly destinationIbge: string;
|
|
174
|
-
readonly exclusions: TaxExclusions;
|
|
175
|
-
readonly tables: RateTables;
|
|
176
|
-
/** The day of the supply; the rate is the rate of that day. */
|
|
177
|
-
readonly supplyDate: IsoDate;
|
|
178
|
-
}
|
|
179
|
-
/** Where an output line came from. */
|
|
180
|
-
type LineSource = "LINE" | "SERVICE_CHARGE" | "GORJETA_EXCLUDED" | "INTERMEDIATION_EXCLUDED";
|
|
181
|
-
/** The per-tax figures of one line. Rates are nominal; `reductionBp` applies to all three. */
|
|
182
|
-
interface LineFigures {
|
|
183
|
-
readonly reductionBp: number;
|
|
184
|
-
readonly cbsRateBp: number;
|
|
185
|
-
readonly cbsCents: number;
|
|
186
|
-
readonly ibsUfRateBp: number;
|
|
187
|
-
readonly ibsUfCents: number;
|
|
188
|
-
readonly ibsMunRateBp: number;
|
|
189
|
-
readonly ibsMunCents: number;
|
|
190
|
-
}
|
|
191
|
-
/** One output line — one NF-e item. */
|
|
192
|
-
interface LineTax extends LineFigures {
|
|
193
|
-
readonly lineId: string;
|
|
194
|
-
readonly source: LineSource;
|
|
195
|
-
readonly quantity: number;
|
|
196
|
-
/** The value as given (`vProd`). */
|
|
197
|
-
readonly valueCents: number;
|
|
198
|
-
/** The base the taxes are computed on (`vBC`): 0 on an excluded line. */
|
|
199
|
-
readonly taxBaseCents: number;
|
|
200
|
-
/** CBS + IBS-UF + IBS-Mun of the line. */
|
|
201
|
-
readonly taxCents: number;
|
|
202
|
-
/**
|
|
203
|
-
* The value without tax (`vProdLiq` = value − tax) in a `taxInsidePrice`
|
|
204
|
-
* period; `null` when the tax is not inside the value.
|
|
205
|
-
*/
|
|
206
|
-
readonly netValueCents: number | null;
|
|
207
|
-
/**
|
|
208
|
-
* The unit value without tax (`vUnComLiq`), in reais with ten decimals as
|
|
209
|
-
* the layout writes it, within ±0,01 of `vProdLiq / qCom` (rule I11c-20);
|
|
210
|
-
* `null` when `netValueCents` is.
|
|
211
|
-
*/
|
|
212
|
-
readonly netUnitValue: string | null;
|
|
213
|
-
/** The class snapshot (the table's exclusion class on an excluded line). */
|
|
214
|
-
readonly taxClass: TaxClass;
|
|
215
|
-
}
|
|
216
|
-
/** The breakdown of one supply. Every order figure is the sum of its rounded lines. */
|
|
217
|
-
interface TaxBreakdown {
|
|
218
|
-
readonly lines: readonly LineTax[];
|
|
219
|
-
readonly valueCents: number;
|
|
220
|
-
readonly taxBaseCents: number;
|
|
221
|
-
readonly cbsCents: number;
|
|
222
|
-
readonly ibsUfCents: number;
|
|
223
|
-
readonly ibsMunCents: number;
|
|
224
|
-
readonly ibsCents: number;
|
|
225
|
-
readonly totalTaxCents: number;
|
|
226
|
-
/** Σ `netValueCents` (`vProdLiqTot`), or `null` when the tax is not inside the values. */
|
|
227
|
-
readonly netValueCents: number | null;
|
|
228
|
-
readonly gorjetaExcludedCents: number;
|
|
229
|
-
readonly intermediationExcludedCents: number;
|
|
230
|
-
readonly regime: TaxRegime;
|
|
231
|
-
readonly treatment: TaxTreatment;
|
|
232
|
-
/**
|
|
233
|
-
* True when the figures are shown but not charged "por fora": the test year
|
|
234
|
-
* (2026), or a Simples store inside the DAS. False for a `NONE` treatment,
|
|
235
|
-
* which shows nothing.
|
|
236
|
-
*/
|
|
237
|
-
readonly informative: boolean;
|
|
238
|
-
/** True when the period's figures are estimates, not law. */
|
|
239
|
-
readonly provisional: boolean;
|
|
240
|
-
/** Whether the line values were taken as tax-inclusive. */
|
|
241
|
-
readonly taxInsidePrice: boolean;
|
|
242
|
-
readonly supplyDate: IsoDate;
|
|
243
|
-
readonly destinationIbge: string;
|
|
244
|
-
readonly tablesVersion: string;
|
|
245
|
-
}
|
|
1
|
+
import { b as TaxInput, a as TaxBreakdown, R as RatePeriod, L as LineFigures, c as RateTables } from '../types-B1b8LIWX.js';
|
|
2
|
+
export { I as IbsMunRates, d as IbsSphereRates, e as IbsUfRates, f as IsoDate, g as LineSource, h as LineTax, i as RegimeEspecifico, j as RetainedIntermediationInput, S as SellerProfile, k as ServiceChargeInput, l as TaxClass, m as TaxClassCode, n as TaxExclusions, o as TaxLineInput, T as TaxRegime, p as TaxTreatment } from '../types-B1b8LIWX.js';
|
|
246
3
|
|
|
247
4
|
/**
|
|
248
5
|
* `computeTax` — the table mode. Pure: no I/O, no clock, no defaults. The
|
|
@@ -358,4 +115,4 @@ declare function roundTaxCents(baseCents: number, rateBp: number, reductionBp: n
|
|
|
358
115
|
/** Refuse a table the engine cannot trust: bad rates, bad dates, overlapping periods. */
|
|
359
116
|
declare function assertRateTables(tables: unknown): asserts tables is RateTables;
|
|
360
117
|
|
|
361
|
-
export { type BreakdownDisagreement, FiscalEngineError, type FiscalEngineErrorCode,
|
|
118
|
+
export { type BreakdownDisagreement, FiscalEngineError, type FiscalEngineErrorCode, LineFigures, type OfficialCalculator, type OfficialCalculatorItemAnswer, type OfficialCalculatorItemRequest, RatePeriod, RateTables, TaxBreakdown, TaxInput, assertRateTables, compareBreakdowns, computeTax, computeTaxWithOracle, ratesAt, roundTaxCents };
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { D as DanfeNfceLabels } from './labels-BNvflT0h.js';
|
|
2
|
+
import { D as DocumentStorage } from './context-ChnWR4Kb.js';
|
|
3
|
+
import { F as FiscalDocuments } from './service-KTjH7AxW.js';
|
|
4
|
+
import './port-DpRFK56U.js';
|
|
5
|
+
import './sale/index.js';
|
|
6
|
+
import './sidecar/index.js';
|
|
7
|
+
import './types-B1b8LIWX.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* `createApiFiscal` — the fiscal HTTP surface as framework-neutral route
|
|
11
|
+
* descriptors (the wiring contract's `http` capability, restated here
|
|
12
|
+
* structurally: this package imports nothing from the contract at runtime,
|
|
13
|
+
* and its manifest suite pins the twins).
|
|
14
|
+
*
|
|
15
|
+
* The package owns the paths, the bodies it reads (`./documents/profile-input`,
|
|
16
|
+
* unknown keys refused), the `{ data }` envelope, the permission each route
|
|
17
|
+
* needs and the status a refusal earns ({@link FISCAL_ERROR_STATUS}). The host
|
|
18
|
+
* owns resolving WHO is calling into the opaque `ownerId` of its tenant, the
|
|
19
|
+
* guards that check the declared permission, and every word a person reads:
|
|
20
|
+
* an error answers a `code` for the host to word, never a sentence for a user.
|
|
21
|
+
*
|
|
22
|
+
* Nothing secret leaves: the profile answers `hasCertificate` / `hasCsc`, never
|
|
23
|
+
* a ciphertext, and the certificate upload answers the profile view.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/** The caller, as the host's adapter resolved it. */
|
|
27
|
+
interface FiscalHttpActor {
|
|
28
|
+
/** The emitter profile's owner: the host's tenant, mapped to an opaque id. */
|
|
29
|
+
readonly ownerId: string;
|
|
30
|
+
}
|
|
31
|
+
/** Structural twin of the wiring contract's `WireRequest<FiscalHttpActor>`. */
|
|
32
|
+
interface FiscalHttpRequest {
|
|
33
|
+
actor: FiscalHttpActor;
|
|
34
|
+
params: Record<string, string | undefined>;
|
|
35
|
+
query: Record<string, string | undefined>;
|
|
36
|
+
body?: unknown;
|
|
37
|
+
}
|
|
38
|
+
/** Structural twin of the wiring contract's `WireResponse`. */
|
|
39
|
+
interface FiscalHttpResponse {
|
|
40
|
+
status: number;
|
|
41
|
+
body: unknown;
|
|
42
|
+
}
|
|
43
|
+
/** Structural twin of the wiring contract's `WireRoute<FiscalHttpActor>`. */
|
|
44
|
+
interface FiscalRoute {
|
|
45
|
+
method: "GET" | "POST" | "PUT";
|
|
46
|
+
path: string;
|
|
47
|
+
permission: string;
|
|
48
|
+
handle(request: FiscalHttpRequest): Promise<FiscalHttpResponse>;
|
|
49
|
+
}
|
|
50
|
+
interface FiscalApiConfig {
|
|
51
|
+
readonly documents: FiscalDocuments;
|
|
52
|
+
/** Where the XMLs are, to render a DANFE from. */
|
|
53
|
+
readonly storage: DocumentStorage;
|
|
54
|
+
/** The DANFE's words: the host's, or `@12-apps/fiscal/danfe/pt-BR`. */
|
|
55
|
+
readonly danfeLabels: DanfeNfceLabels;
|
|
56
|
+
}
|
|
57
|
+
declare const FISCAL_ERROR_STATUS: {
|
|
58
|
+
readonly INVALID_INPUT: 400;
|
|
59
|
+
readonly NOT_FOUND: 404;
|
|
60
|
+
readonly NOT_ISSUABLE: 409;
|
|
61
|
+
readonly NOT_SUPPORTED: 501;
|
|
62
|
+
readonly TRANSITION_REFUSED: 409;
|
|
63
|
+
readonly SERIES_EXHAUSTED: 409;
|
|
64
|
+
readonly CONFLICT: 409;
|
|
65
|
+
readonly SUBJECT_HAS_DOCUMENT: 409;
|
|
66
|
+
readonly NOT_PRINTABLE: 409;
|
|
67
|
+
readonly RESEND_CHANGES_PRINTED_FIELDS: 422;
|
|
68
|
+
};
|
|
69
|
+
declare function createApiFiscal(config: FiscalApiConfig): {
|
|
70
|
+
routes: readonly FiscalRoute[];
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
export { FISCAL_ERROR_STATUS, type FiscalApiConfig, type FiscalHttpActor, type FiscalHttpRequest, type FiscalHttpResponse, type FiscalRoute, createApiFiscal };
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import {
|
|
2
|
+
FISCAL_ERROR_STATUS,
|
|
3
|
+
createApiFiscal
|
|
4
|
+
} from "./chunk-V5ZQAAJT.js";
|
|
5
|
+
import "./chunk-ALABGVPO.js";
|
|
6
|
+
import "./chunk-RRFKYVLZ.js";
|
|
7
|
+
import "./chunk-PNTKG3DZ.js";
|
|
8
|
+
import "./chunk-XQGW5HUG.js";
|
|
9
|
+
import "./chunk-3SDXLSG4.js";
|
|
10
|
+
import "./chunk-X6MRDUYH.js";
|
|
11
|
+
import "./chunk-7QVYU63E.js";
|
|
12
|
+
export {
|
|
13
|
+
FISCAL_ERROR_STATUS,
|
|
14
|
+
createApiFiscal
|
|
15
|
+
};
|
|
16
|
+
//# sourceMappingURL=http.js.map
|
package/dist/http.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|