@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.
Files changed (140) hide show
  1. package/README.md +152 -7
  2. package/dist/chunk-27B4HNO6.js +574 -0
  3. package/dist/chunk-27B4HNO6.js.map +1 -0
  4. package/dist/chunk-3SDXLSG4.js +24 -0
  5. package/dist/chunk-3SDXLSG4.js.map +1 -0
  6. package/dist/chunk-ALABGVPO.js +247 -0
  7. package/dist/chunk-ALABGVPO.js.map +1 -0
  8. package/dist/chunk-FOFIN5M7.js +14 -0
  9. package/dist/chunk-FOFIN5M7.js.map +1 -0
  10. package/dist/chunk-HQ2NXSTX.js +85 -0
  11. package/dist/chunk-HQ2NXSTX.js.map +1 -0
  12. package/dist/chunk-PNTKG3DZ.js +47 -0
  13. package/dist/chunk-PNTKG3DZ.js.map +1 -0
  14. package/dist/chunk-RRFKYVLZ.js +192 -0
  15. package/dist/chunk-RRFKYVLZ.js.map +1 -0
  16. package/dist/chunk-V5ZQAAJT.js +210 -0
  17. package/dist/chunk-V5ZQAAJT.js.map +1 -0
  18. package/dist/chunk-X6MRDUYH.js +21 -0
  19. package/dist/chunk-X6MRDUYH.js.map +1 -0
  20. package/dist/chunk-XQGW5HUG.js +30 -0
  21. package/dist/chunk-XQGW5HUG.js.map +1 -0
  22. package/dist/context-ChnWR4Kb.d.ts +455 -0
  23. package/dist/danfe/en-US.d.ts +12 -0
  24. package/dist/danfe/en-US.js +51 -0
  25. package/dist/danfe/en-US.js.map +1 -0
  26. package/dist/danfe/index.d.ts +50 -0
  27. package/dist/danfe/index.js +18 -0
  28. package/dist/danfe/index.js.map +1 -0
  29. package/dist/danfe/pt-BR.d.ts +11 -0
  30. package/dist/danfe/pt-BR.js +51 -0
  31. package/dist/danfe/pt-BR.js.map +1 -0
  32. package/dist/documents/index.d.ts +169 -0
  33. package/dist/documents/index.js +1228 -0
  34. package/dist/documents/index.js.map +1 -0
  35. package/dist/engine/index.d.ts +3 -246
  36. package/dist/http.d.ts +73 -0
  37. package/dist/http.js +16 -0
  38. package/dist/http.js.map +1 -0
  39. package/dist/issuer/index.d.ts +43 -0
  40. package/dist/issuer/index.js +131 -0
  41. package/dist/issuer/index.js.map +1 -0
  42. package/dist/jobs.d.ts +74 -0
  43. package/dist/jobs.js +22 -0
  44. package/dist/jobs.js.map +1 -0
  45. package/dist/labels-BNvflT0h.d.ts +44 -0
  46. package/dist/manifest/index.d.ts +30 -16
  47. package/dist/manifest/index.js +11 -17
  48. package/dist/manifest/index.js.map +1 -1
  49. package/dist/manifest/server.d.ts +57 -0
  50. package/dist/manifest/server.js +25 -0
  51. package/dist/manifest/server.js.map +1 -0
  52. package/dist/notifications.d.ts +93 -0
  53. package/dist/notifications.js +41 -0
  54. package/dist/notifications.js.map +1 -0
  55. package/dist/port-DpRFK56U.d.ts +238 -0
  56. package/dist/sale/index.d.ts +243 -0
  57. package/dist/sale/index.js +1 -0
  58. package/dist/sale/index.js.map +1 -0
  59. package/dist/service-KTjH7AxW.d.ts +139 -0
  60. package/dist/sidecar/index.d.ts +216 -0
  61. package/dist/sidecar/index.js +8 -0
  62. package/dist/sidecar/index.js.map +1 -0
  63. package/dist/types-B1b8LIWX.d.ts +247 -0
  64. package/package.json +63 -5
  65. package/prisma/fiscal.prisma +158 -0
  66. package/prisma/migrations/20261113220000_fiscal_documents/migration.sql +201 -0
  67. package/sidecar/.dockerignore +5 -0
  68. package/sidecar/Dockerfile +68 -0
  69. package/sidecar/README.md +149 -0
  70. package/sidecar/composer.json +30 -0
  71. package/sidecar/composer.lock +2224 -0
  72. package/sidecar/docker/apache.conf +14 -0
  73. package/sidecar/docker/icp-brasil.pem +8031 -0
  74. package/sidecar/docker/mpm.conf +17 -0
  75. package/sidecar/docker/openssl.cnf +16 -0
  76. package/sidecar/docker/php.ini +19 -0
  77. package/sidecar/public/index.php +15 -0
  78. package/sidecar/schema/sale-for-document.schema.json +401 -0
  79. package/sidecar/src/ErrorClass.php +31 -0
  80. package/sidecar/src/Http/Request.php +48 -0
  81. package/sidecar/src/Http/Response.php +32 -0
  82. package/sidecar/src/Http/Router.php +59 -0
  83. package/sidecar/src/Kernel.php +99 -0
  84. package/sidecar/src/Module.php +31 -0
  85. package/sidecar/src/Nfe/Classifier.php +89 -0
  86. package/sidecar/src/Nfe/Credentials.php +52 -0
  87. package/sidecar/src/Nfe/DocumentMapper.php +383 -0
  88. package/sidecar/src/Nfe/DocumentSchema.php +39 -0
  89. package/sidecar/src/Nfe/Input.php +125 -0
  90. package/sidecar/src/Nfe/Model.php +17 -0
  91. package/sidecar/src/Nfe/NfeModule.php +62 -0
  92. package/sidecar/src/Nfe/NfeService.php +504 -0
  93. package/sidecar/src/Nfe/Sefaz.php +49 -0
  94. package/sidecar/src/Nfe/SefazReply.php +81 -0
  95. package/sidecar/src/Nfe/Transport/CurlTransport.php +198 -0
  96. package/sidecar/src/Nfe/Transport/SoapAdapter.php +57 -0
  97. package/sidecar/src/Nfe/Transport/Transport.php +20 -0
  98. package/sidecar/src/Nfe/Transport/TransportFailure.php +42 -0
  99. package/sidecar/src/RequestLog.php +54 -0
  100. package/sidecar/src/ServiceError.php +69 -0
  101. package/src/danfe/en-US.ts +53 -0
  102. package/src/danfe/index.ts +11 -0
  103. package/src/danfe/labels.ts +49 -0
  104. package/src/danfe/pt-BR.ts +52 -0
  105. package/src/danfe/render.ts +265 -0
  106. package/src/danfe/xml.ts +45 -0
  107. package/src/documents/context.ts +260 -0
  108. package/src/documents/errors.ts +41 -0
  109. package/src/documents/helpers.ts +128 -0
  110. package/src/documents/index.ts +39 -0
  111. package/src/documents/lines.ts +63 -0
  112. package/src/documents/machine-steps.ts +260 -0
  113. package/src/documents/machine.ts +128 -0
  114. package/src/documents/memory.ts +138 -0
  115. package/src/documents/nfe-proc.ts +51 -0
  116. package/src/documents/ports.ts +130 -0
  117. package/src/documents/profile-input.ts +168 -0
  118. package/src/documents/profile.ts +98 -0
  119. package/src/documents/service-profile.ts +104 -0
  120. package/src/documents/service.ts +296 -0
  121. package/src/documents/settle.ts +121 -0
  122. package/src/documents/signing.ts +61 -0
  123. package/src/documents/sql-rows.ts +180 -0
  124. package/src/documents/sql-store.ts +242 -0
  125. package/src/documents/sql.ts +18 -0
  126. package/src/documents/steps.ts +173 -0
  127. package/src/documents/tests/integration/pglite.ts +73 -0
  128. package/src/documents/types.ts +193 -0
  129. package/src/http.ts +264 -0
  130. package/src/issuer/index.ts +9 -0
  131. package/src/issuer/port.ts +109 -0
  132. package/src/issuer/sidecar.ts +171 -0
  133. package/src/jobs.ts +115 -0
  134. package/src/manifest/index.ts +25 -16
  135. package/src/manifest/server.ts +20 -0
  136. package/src/notifications.ts +120 -0
  137. package/src/sale/index.ts +8 -0
  138. package/src/sale/types.ts +292 -0
  139. package/src/sidecar/index.ts +9 -0
  140. package/src/sidecar/types.ts +243 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/documents/machine-steps.ts","../src/documents/machine.ts","../src/documents/helpers.ts","../src/documents/context.ts"],"sourcesContent":["/**\n * What each input does to a document's fields — the state machine's body\n * (`./machine` holds its table and its one entry point). Pure functions; a\n * refusal throws `TRANSITION_REFUSED`.\n */\n\nimport type {\n CancelledDocument,\n ContingencyEntry,\n ContingencySignedDocument,\n InutilizedRange,\n IssuedDocument,\n LookedUpDocument,\n SidecarErrorBody,\n} from \"../sidecar/types\";\nimport type { SaleForDocument } from \"../sale/types\";\nimport { FiscalDocumentError } from \"./errors\";\nimport { type DocumentEventKind, type DocumentTotals, type FiscalDocument, type NumberVoid, isLive } from \"./types\";\n\nexport type SidecarError = SidecarErrorBody[\"error\"];\n\n/** Failures in a row after which a document waits for a person. */\nexport const MAX_FAILURES = 8;\n\n/** What the machine is fed. Each carries the service's answer, which the event keeps. */\nexport type DocumentInput =\n | { readonly kind: \"SUBMIT\" }\n | { readonly kind: \"AUTHORIZE\"; readonly answer: IssuedDocument; readonly xmlKey: string }\n | { readonly kind: \"DENY\"; readonly answer: IssuedDocument; readonly xmlKey: string }\n | { readonly kind: \"REJECT\"; readonly error: SidecarError }\n /** `xmlKey`: where the signed XML the failed call returned was stored, when it returned one. */\n | { readonly kind: \"RETRY\"; readonly error: SidecarError; readonly xmlKey?: string }\n | {\n readonly kind: \"SIGN_OFFLINE\";\n readonly answer: ContingencySignedDocument;\n readonly contingency: ContingencyEntry;\n readonly xmlKey: string;\n }\n | { readonly kind: \"REPLACE\"; readonly replacedById: string }\n | { readonly kind: \"CANCEL\"; readonly answer: CancelledDocument; readonly reason: string; readonly eventXmlKey: string | null }\n /**\n * `xmlKey`: the `nfeProc` assembled from the stored signed XML and the\n * lookup's protocol. Without it a lookup never makes a SUBMITTED document\n * final: an authorised document always has its XML.\n */\n | { readonly kind: \"LOOKUP\"; readonly answer: LookedUpDocument; readonly xmlKey?: string }\n | { readonly kind: \"INUTILIZE\"; readonly answer: InutilizedRange; readonly eventXmlKey: string | null }\n /**\n * A step that made no progress (a settlement refused or unanswered, a step\n * that threw). It counts a failure; `attention` hands the document to a\n * person at once (SEFAZ refused it: retrying would only repeat the refusal).\n */\n | { readonly kind: \"DEFER\"; readonly reason: string; readonly error: SidecarError | null; readonly attention: boolean }\n /** A rejected contingency NFC-e, corrected by the store and signed again under the same number. */\n | {\n readonly kind: \"RESIGN\";\n readonly answer: ContingencySignedDocument;\n readonly sale: SaleForDocument;\n readonly totals: DocumentTotals;\n readonly buyerTaxId: string | null;\n readonly xmlKey: string;\n }\n /** A person took a document back from `attention`: the sweep may try again. */\n | { readonly kind: \"RELEASE\" }\n /** The 24-hour contingency deadline warning went out. */\n | { readonly kind: \"WARN\" };\n\ntype InputOf<K extends DocumentEventKind> = Extract<DocumentInput, { kind: K }>;\ntype Step = { readonly [K in DocumentEventKind]: (document: FiscalDocument, input: InputOf<K>) => Partial<FiscalDocument> };\n\nexport function refuse(document: FiscalDocument, kind: DocumentEventKind, why: string): never {\n throw new FiscalDocumentError(\n \"TRANSITION_REFUSED\",\n `${kind} is refused on document ${document.id} in ${document.status}: ${why}.`,\n );\n}\n\n/** Progress: the failure count, the person's flag and the unknown outcome are settled. */\nconst SETTLED = { failures: 0, attention: false } as const;\n\nfunction issuedFields(answer: IssuedDocument, xmlKey: string): Partial<FiscalDocument> {\n return {\n ...SETTLED,\n accessKey: answer.accessKey,\n protocol: answer.protocol,\n authorizedAt: answer.authorizedAt,\n statusCode: answer.statusCode,\n statusReason: answer.statusReason,\n lastErrorClass: null,\n outcomeUnknown: false,\n xmlKey,\n };\n}\n\n/**\n * A failed call. `outcomeUnknown` is STICKY: once a request may have reached\n * SEFAZ unanswered, only a definitive answer or a lookup clears it — a later\n * \"nothing was sent this time\" says nothing about the first send.\n */\nfunction failedFields(document: FiscalDocument, error: SidecarError): Partial<FiscalDocument> {\n return {\n accessKey: document.accessKey ?? error.accessKey,\n statusCode: error.code,\n statusReason: error.message,\n lastErrorClass: error.class,\n outcomeUnknown: document.outcomeUnknown || error.outcomeUnknown,\n };\n}\n\nfunction failure(document: FiscalDocument, attention: boolean): Partial<FiscalDocument> {\n const failures = document.failures + 1;\n return { failures, attention: attention || failures >= MAX_FAILURES };\n}\n\n/** What a lookup says is owed on a number SEFAZ may hold. */\nfunction voidAfterLookup(answer: LookedUpDocument): NumberVoid {\n if (answer.status === \"AUTHORIZED\") return \"CANCEL\";\n if (answer.status === \"CANCELLED\") return \"CANCELLED\";\n if (answer.status === \"DENIED\") return \"DENIED\";\n return \"INUTILIZE\";\n}\n\nfunction lookupOfSettledNumber(document: FiscalDocument, answer: LookedUpDocument): Partial<FiscalDocument> {\n if (document.numberVoid !== \"LOOKUP_FIRST\") refuse(document, \"LOOKUP\", \"its number is already settled\");\n if (isLive(document) && (answer.status === \"AUTHORIZED\" || answer.status === \"DENIED\")) {\n // The sale's own document, still SEFAZ's: never cancelled, never voided,\n // never left REJECTED. It goes back to SUBMITTED, owing work, with the\n // protocol kept — the next step settles it with its XML (the service does\n // at once when it holds the XML the protocol certifies; otherwise the\n // sweep sends the same call again, which the fiscal service settles).\n // Its failures keep counting, so a loop of refusals reaches a person.\n return {\n status: \"SUBMITTED\",\n numberVoid: null,\n outcomeUnknown: false,\n protocol: answer.protocol ?? document.protocol,\n statusCode: answer.statusCode,\n statusReason: answer.statusReason,\n };\n }\n return {\n ...SETTLED,\n numberVoid: voidAfterLookup(answer),\n outcomeUnknown: false,\n // The protocol SEFAZ answered is what a cancel of this number must quote.\n protocol: answer.protocol ?? document.protocol,\n statusCode: answer.statusCode,\n statusReason: answer.statusReason,\n };\n}\n\n/**\n * A lookup of a SUBMITTED document. It settles it as AUTHORIZED or DENIED\n * only with the XML in hand (`xmlKey`); otherwise it keeps what SEFAZ said —\n * the protocol marks the number as SEFAZ's — and the document stays\n * SUBMITTED, for the sweep to fetch the XML by sending the same call again.\n */\nfunction lookupOfSubmitted(document: FiscalDocument, answer: LookedUpDocument, xmlKey: string | undefined): Partial<FiscalDocument> {\n const known = { statusCode: answer.statusCode, statusReason: answer.statusReason, outcomeUnknown: false };\n // A key found cancelled elsewhere is left to the next issue call, which the service settles: CANCELLED is entered only from AUTHORIZED.\n const settles = answer.status === \"AUTHORIZED\" || answer.status === \"DENIED\";\n if (!settles || answer.protocol === null || document.accessKey === null) return known;\n if (xmlKey === undefined) return { ...known, protocol: answer.protocol };\n return { ...known, ...SETTLED, status: answer.status, protocol: answer.protocol, lastErrorClass: null, xmlKey };\n}\n\nfunction lookupFields(document: FiscalDocument, answer: LookedUpDocument, xmlKey?: string): Partial<FiscalDocument> {\n if (document.status === \"REPLACED\" || document.status === \"REJECTED\") return lookupOfSettledNumber(document, answer);\n if (document.status === \"SUBMITTED\") return lookupOfSubmitted(document, answer, xmlKey);\n if (answer.status === \"CANCELLED\") return { status: \"CANCELLED\", statusCode: answer.statusCode, statusReason: answer.statusReason };\n return { statusCode: answer.statusCode, statusReason: answer.statusReason };\n}\n\nfunction cancelFields(document: FiscalDocument, input: InputOf<\"CANCEL\">): Partial<FiscalDocument> {\n const recorded = {\n ...SETTLED,\n cancelledAt: input.answer.registeredAt,\n cancelReason: input.reason,\n cancelProtocol: input.answer.protocol,\n eventXmlKey: input.eventXmlKey,\n };\n if (document.status === \"AUTHORIZED\") {\n return { ...recorded, status: \"CANCELLED\", statusCode: input.answer.statusCode, statusReason: input.answer.statusReason };\n }\n if (document.numberVoid !== \"CANCEL\") refuse(document, \"CANCEL\", \"a voided number is cancelled only when found authorised\");\n return { ...recorded, numberVoid: \"CANCELLED\" };\n}\n\n/** A rejected online number may have been authorised by an unanswered first send: look it up first. */\n/**\n * A rejected online number may have been authorised by an unanswered first\n * send — or a lookup already found it authorised (its protocol is kept, and\n * a re-send for the XML met a 704 or a different XML under the key): either\n * way it is looked up, never voided blindly.\n */\nfunction rejectFields(document: FiscalDocument, error: SidecarError): Partial<FiscalDocument> {\n const failed = failedFields(document, error);\n if (document.seriesKind === \"CONTINGENCY\") return { status: \"REJECTED\", ...failed, ...SETTLED, numberVoid: null };\n // Known to be SEFAZ's: a refused re-send is one more failure of the same document, not a settlement.\n if (document.protocol !== null) return { status: \"REJECTED\", ...failed, ...failure(document, false), numberVoid: \"LOOKUP_FIRST\" };\n return { status: \"REJECTED\", ...failed, ...SETTLED, numberVoid: failed.outcomeUnknown === true ? \"LOOKUP_FIRST\" : \"INUTILIZE\" };\n}\n\nexport const STEPS: Step = {\n SUBMIT: () => ({ status: \"SUBMITTED\" }),\n AUTHORIZE: (_document, input) => ({ status: \"AUTHORIZED\", ...issuedFields(input.answer, input.xmlKey) }),\n DENY: (_document, input) => ({ status: \"DENIED\", ...issuedFields(input.answer, input.xmlKey) }),\n REJECT: (document, input) => rejectFields(document, input.error),\n RETRY: (document, input) => ({\n ...failedFields(document, input.error),\n ...failure(document, false),\n ...(input.xmlKey === undefined ? {} : { xmlKey: input.xmlKey }),\n }),\n SIGN_OFFLINE: (document, input) => {\n if (document.seriesKind !== \"CONTINGENCY\") refuse(document, input.kind, \"only a contingency-series number is signed offline\");\n return { ...SETTLED, status: \"CONTINGENCY\", accessKey: input.answer.accessKey, contingency: input.contingency, xmlKey: input.xmlKey };\n },\n REPLACE: (document, input) => ({\n ...SETTLED,\n status: \"REPLACED\",\n replacedById: input.replacedById,\n // A SUBMITTED document may have reached SEFAZ whatever was recorded (a process\n // that died mid-call, a receipt with no protocol yet): its key is always\n // known, so it is looked up before its number is voided. Only a PENDING one\n // was never sent.\n numberVoid: document.status === \"SUBMITTED\" ? \"LOOKUP_FIRST\" : \"INUTILIZE\",\n }),\n CANCEL: cancelFields,\n LOOKUP: (document, input) => lookupFields(document, input.answer, input.xmlKey),\n INUTILIZE: (document, input) => {\n if (document.numberVoid !== \"INUTILIZE\") refuse(document, input.kind, \"its number is not owed an inutilization\");\n return { ...SETTLED, numberVoid: \"INUTILIZED\", eventXmlKey: input.eventXmlKey };\n },\n DEFER: (document, input) => ({\n ...failure(document, input.attention),\n ...(input.error === null ? {} : { lastErrorClass: input.error.class, statusCode: input.error.code }),\n statusReason: input.error?.message ?? input.reason,\n }),\n RESIGN: (document, input) => {\n if (document.seriesKind !== \"CONTINGENCY\") refuse(document, input.kind, \"only a rejected contingency NFC-e is resent\");\n return {\n ...SETTLED,\n status: \"CONTINGENCY\",\n sale: input.sale,\n totals: input.totals,\n buyerTaxId: input.buyerTaxId,\n accessKey: input.answer.accessKey,\n xmlKey: input.xmlKey,\n statusCode: null,\n statusReason: null,\n lastErrorClass: null,\n };\n },\n RELEASE: (document) => {\n if (!document.attention) refuse(document, \"RELEASE\", \"it is not waiting for a person\");\n return SETTLED;\n },\n // `deadlineWarnedAt` is the transition's own time, set by `transition`.\n WARN: () => ({}),\n};\n","/**\n * The fiscal document state machine: pure functions from a document and one\n * input to the next document and the event that records the step.\n *\n * ```\n * PENDING ──SUBMIT──▶ SUBMITTED ──AUTHORIZE──▶ AUTHORIZED ──CANCEL──▶ CANCELLED\n * │ │ ├──DENY─────▶ DENIED\n * │ │ ├──REJECT───▶ REJECTED\n * │ │ └──RETRY────▶ SUBMITTED\n * │ └──REPLACE──▶ REPLACED\n * ├──REPLACE──▶ REPLACED\n * └──SIGN_OFFLINE──▶ CONTINGENCY ──AUTHORIZE | DENY | REJECT | RETRY──▶ …\n * ▲ REJECTED (contingency) ──RESIGN──┘\n * ```\n *\n * A document is one number, so going offline is a SECOND document on the\n * issuing point's contingency series (`PENDING → CONTINGENCY`), and the first\n * one is `REPLACED`. Every input yields an event; a refused one throws\n * {@link FiscalDocumentError} `TRANSITION_REFUSED` and changes nothing:\n * `CANCELLED` is entered only from `AUTHORIZED`, and `AUTHORIZED` never from a\n * final state. A rejected contingency NFC-e is the one way back: the store\n * corrects it and it is signed again under the same number (`RESIGN`).\n *\n * `DEFER`, `RELEASE` and `WARN` record what the sweep and a person did without\n * changing the state: a failed step counts toward {@link MAX_FAILURES}, after\n * which the document waits for a person (`attention`).\n */\n\nimport { type DocumentInput, STEPS, refuse } from \"./machine-steps\";\nimport type { DocumentEventKind, FiscalDocument, FiscalDocumentEvent, FiscalDocumentStatus } from \"./types\";\n\nexport { MAX_FAILURES } from \"./machine-steps\";\nexport type { DocumentInput } from \"./machine-steps\";\n\nconst ANY: readonly FiscalDocumentStatus[] = [\n \"PENDING\", \"SUBMITTED\", \"AUTHORIZED\", \"REJECTED\", \"DENIED\", \"CONTINGENCY\", \"CANCELLED\", \"REPLACED\",\n];\n\n/** From which states each input is accepted. */\nexport const DOCUMENT_TRANSITIONS: Readonly<Record<DocumentEventKind, readonly FiscalDocumentStatus[]>> = {\n SUBMIT: [\"PENDING\"],\n AUTHORIZE: [\"SUBMITTED\", \"CONTINGENCY\"],\n DENY: [\"SUBMITTED\", \"CONTINGENCY\"],\n REJECT: [\"SUBMITTED\", \"CONTINGENCY\"],\n RETRY: [\"SUBMITTED\", \"CONTINGENCY\"],\n SIGN_OFFLINE: [\"PENDING\"],\n REPLACE: [\"PENDING\", \"SUBMITTED\"],\n CANCEL: [\"AUTHORIZED\", \"REPLACED\", \"REJECTED\"],\n LOOKUP: [\"SUBMITTED\", \"AUTHORIZED\", \"REPLACED\", \"REJECTED\"],\n INUTILIZE: [\"REJECTED\", \"REPLACED\"],\n DEFER: ANY,\n RESIGN: [\"REJECTED\"],\n RELEASE: ANY,\n WARN: [\"CONTINGENCY\"],\n};\n\n/** The states nothing but a lookup, a cancel or an inutilization of the number may follow. */\nexport const FINAL_STATUSES: readonly FiscalDocumentStatus[] = [\"REJECTED\", \"DENIED\", \"CANCELLED\", \"REPLACED\"];\n\nexport interface Transition {\n readonly document: FiscalDocument;\n readonly event: FiscalDocumentEvent;\n}\n\nconst SECRET_KEY = /^(pfx|pfxBase64|password|passphrase|certificate|csc|token|privateKey)$/i;\n\n/**\n * A copy of an answer with every secret-named key dropped. The service never\n * echoes one; this is the second lock, so an event row can never hold one.\n */\nexport function scrubSecrets(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(scrubSecrets);\n if (value === null || typeof value !== \"object\") return value;\n const out: Record<string, unknown> = {};\n for (const [key, inner] of Object.entries(value)) {\n if (!SECRET_KEY.test(key)) out[key] = scrubSecrets(inner);\n }\n return out;\n}\n\nfunction answerOf(input: DocumentInput): unknown {\n if (\"answer\" in input) return input.answer;\n if (\"error\" in input && input.error !== null) return { error: input.error };\n if (input.kind === \"DEFER\") return { reason: input.reason };\n return null;\n}\n\nfunction eventOf(document: FiscalDocument, input: DocumentInput, toStatus: FiscalDocumentStatus, at: string): FiscalDocumentEvent {\n const error = \"error\" in input ? input.error : null;\n const answer = \"answer\" in input ? input.answer : null;\n return {\n documentId: document.id,\n kind: input.kind,\n fromStatus: document.status,\n toStatus,\n at,\n errorClass: error?.class ?? null,\n code: error?.code ?? (answer !== null && \"statusCode\" in answer ? answer.statusCode : null),\n answer: scrubSecrets(answerOf(input)),\n };\n}\n\nconst COUNTED = new Set<DocumentEventKind>([\"SUBMIT\", \"RETRY\", \"SIGN_OFFLINE\", \"RESIGN\"]);\n\n/**\n * Apply one input. Throws `TRANSITION_REFUSED` (and changes nothing) when the\n * document's state does not accept it. `at` is the caller's clock, ISO 8601.\n */\nexport function transition(document: FiscalDocument, input: DocumentInput, at: string): Transition {\n if (!DOCUMENT_TRANSITIONS[input.kind].includes(document.status)) {\n refuse(document, input.kind, `accepted only from ${DOCUMENT_TRANSITIONS[input.kind].join(\", \")}`);\n }\n const step = STEPS[input.kind] as (document: FiscalDocument, input: DocumentInput) => Partial<FiscalDocument>;\n const updated: FiscalDocument = {\n ...document,\n ...step(document, input),\n ...(input.kind === \"WARN\" ? { deadlineWarnedAt: at } : {}),\n attempts: document.attempts + (COUNTED.has(input.kind) ? 1 : 0),\n updatedAt: at,\n };\n return { document: updated, event: eventOf(document, input, updated.status, at) };\n}\n\n/** Whether an input would be accepted, without applying it. */\nexport function canTransition(status: FiscalDocumentStatus, kind: DocumentEventKind): boolean {\n return DOCUMENT_TRANSITIONS[kind].includes(status);\n}\n\n","/**\n * The pure helpers the document service builds a document with: the local\n * clock, the key code, the access key, the issuer block, the totals, the\n * storage keys. No port, no state.\n */\n\nimport type { DocumentIssuer, SaleForDocument, Uf } from \"../sale/types\";\nimport { FiscalDocumentError } from \"./errors\";\nimport type { SaleDraft } from \"./ports\";\nimport type { EmitterProfile } from \"./profile\";\nimport type { DocumentTotals, FiscalDocument, FiscalDocumentModel, SeriesKind } from \"./types\";\n\n/** `2026-11-20T12:30:00-03:00`: the instant as the owner's wall clock. */\nexport function localIso(at: Date, offset: string): string {\n const match = /^([+-])(\\d{2}):(\\d{2})$/.exec(offset);\n if (match === null) throw new FiscalDocumentError(\"INVALID_INPUT\", `utcOffset answered \"${offset}\", not ±HH:MM.`);\n const minutes = (match[1] === \"-\" ? -1 : 1) * (Number(match[2]) * 60 + Number(match[3]));\n return `${new Date(at.getTime() + minutes * 60_000).toISOString().slice(0, 19)}${offset}`;\n}\n\nconst UNBIASED_LIMIT = Math.floor(2 ** 32 / 100_000_000) * 100_000_000;\n\n/** `cNF`: eight random digits, never equal to the number's own eight (the layout's rule). */\nexport function drawKeyCode(number: number): string {\n const own = String(number % 100_000_000).padStart(8, \"0\");\n for (;;) {\n const [value] = globalThis.crypto.getRandomValues(new Uint32Array(1));\n // Rejection sampling: values at or above the last whole multiple of 10^8 would bias the low codes.\n if (value === undefined || value >= UNBIASED_LIMIT) continue;\n const code = String(value % 100_000_000).padStart(8, \"0\");\n if (code !== own) return code;\n }\n}\n\nconst FILLED_BY_THE_PACKAGE = new Set([\"series\", \"number\", \"keyCode\", \"issuer\", \"issuedAt\"]);\n\n/** A stored sale back to the draft it was built from (for a second document of the same sale). */\nexport function draftOf(sale: SaleForDocument): SaleDraft {\n return Object.fromEntries(Object.entries(sale).filter(([key]) => !FILLED_BY_THE_PACKAGE.has(key))) as unknown as SaleDraft;\n}\n\nexport function issuerOf(profile: EmitterProfile): DocumentIssuer {\n return {\n cnpj: profile.cnpj,\n stateRegistration: profile.stateRegistration,\n legalName: profile.legalName,\n tradeName: profile.tradeName,\n taxRegime: profile.taxRegime,\n address: profile.address,\n };\n}\n\nexport function totalsOf(sale: SaleDraft): DocumentTotals {\n const sum = (pick: (line: SaleDraft[\"lines\"][number]) => number) => sale.lines.reduce((total, line) => total + pick(line), 0);\n const discountCents = sum((line) => line.discountCents);\n return {\n totalCents: sum((line) => line.valueCents) - discountCents,\n discountCents,\n cbsCents: sum((line) => line.ibsCbs?.figures?.cbsCents ?? 0),\n ibsUfCents: sum((line) => line.ibsCbs?.figures?.ibsUfCents ?? 0),\n ibsMunCents: sum((line) => line.ibsCbs?.figures?.ibsMunCents ?? 0),\n };\n}\n\n/** `text` without any trailing run of `char`, in linear time (no regex backtracking). */\nexport function trimEnd(text: string, char: string): string {\n let end = text.length;\n while (end > 0 && text[end - 1] === char) end -= 1;\n return text.slice(0, end);\n}\n\n/** Storage keys, by access key: one folder per document, whatever its owner. */\nexport const xmlKeys = {\n signed: (accessKey: string) => `fiscal/${accessKey}/signed.xml`,\n /** One signed XML per digest: every XML a failed call returned under a key is kept, none overwritten. */\n signedByDigest: (accessKey: string, digest: string) =>\n `fiscal/${accessKey}/signed-${trimEnd(digest.replace(/\\+/g, \"-\").replace(/\\//g, \"_\"), \"=\")}.xml`,\n authorized: (accessKey: string) => `fiscal/${accessKey}/authorized.xml`,\n cancel: (accessKey: string) => `fiscal/${accessKey}/cancel.xml`,\n inutilization: (document: FiscalDocument) =>\n `fiscal/inutilization/${document.environment}/${document.model}/${document.ownerId}/${document.series}-${document.number}.xml`,\n};\n\n/** The IBGE code of each federative unit: the access key's first two digits. */\nconst UF_CODES: Readonly<Record<Uf, string>> = {\n RO: \"11\", AC: \"12\", AM: \"13\", RR: \"14\", PA: \"15\", AP: \"16\", TO: \"17\", MA: \"21\", PI: \"22\", CE: \"23\", RN: \"24\", PB: \"25\",\n PE: \"26\", AL: \"27\", SE: \"28\", BA: \"29\", MG: \"31\", ES: \"32\", RJ: \"33\", SP: \"35\", PR: \"41\", SC: \"42\", RS: \"43\", MS: \"50\",\n MT: \"51\", GO: \"52\", DF: \"53\",\n};\n\n/** The access key's modulo-11 check digit (weights 2–9 from the right). */\nfunction keyCheckDigit(body: string): number {\n let sum = 0;\n let weight = 2;\n for (let i = body.length - 1; i >= 0; i -= 1) {\n sum += (body.charCodeAt(i) - 48) * weight;\n weight = weight === 9 ? 2 : weight + 1;\n }\n const rest = sum % 11;\n return rest < 2 ? 0 : 11 - rest;\n}\n\n/**\n * The 44-character access key a document will carry, computed as the layout\n * does: cUF, AAMM of `dhEmi`, CNPJ, model, series, number, `tpEmis` (1 online,\n * 9 offline NFC-e), `cNF` and the check digit. The package knows a document's\n * key before any call, so an unanswered send can always be looked up.\n */\nexport function computeAccessKey(input: {\n readonly sale: Pick<SaleForDocument, \"issuer\" | \"issuedAt\" | \"series\" | \"number\" | \"keyCode\">;\n readonly model: FiscalDocumentModel;\n readonly seriesKind: SeriesKind;\n}): string {\n const { sale } = input;\n const body = [\n UF_CODES[sale.issuer.address.uf],\n sale.issuedAt.slice(2, 4),\n sale.issuedAt.slice(5, 7),\n sale.issuer.cnpj,\n input.model === \"NFE\" ? \"55\" : \"65\",\n String(sale.series).padStart(3, \"0\"),\n String(sale.number).padStart(9, \"0\"),\n input.seriesKind === \"CONTINGENCY\" ? \"9\" : \"1\",\n sale.keyCode,\n ].join(\"\");\n return `${body}${keyCheckDigit(body)}`;\n}\n\n","/**\n * What every step of the document service shares: the ports, the clock, the\n * host's words written into a document, and the two writes everything goes\n * through — numbering a new document, and persisting one transition with the\n * schedule and the person's flag it implies.\n */\n\nimport type { Issuer, SigningMaterial } from \"../issuer/port\";\nimport { FISCAL_ISSUE } from \"../manifest/permissions\";\nimport { FiscalDocumentError } from \"./errors\";\nimport { computeAccessKey, drawKeyCode, issuerOf, localIso, totalsOf } from \"./helpers\";\nimport { type DocumentInput, type Transition, transition } from \"./machine\";\nimport type { DocumentStorage, FiscalStore, SaleDraft, SaleSource } from \"./ports\";\nimport type { EmitterProfile, IssuingPoint } from \"./profile\";\nimport type { SigningIdentities } from \"./signing\";\nimport { type FiscalDocument, type FiscalDocumentModel, OWED_VOIDS, type SeriesKind } from \"./types\";\n\nexport { computeAccessKey, draftOf, drawKeyCode, issuerOf, localIso, totalsOf, xmlKeys } from \"./helpers\";\n\n/** Twin of `@12-apps/wiring/ports`' `NotifyPort`: never throws. */\nexport interface FiscalNotifyPort {\n emit(event: {\n readonly type: string;\n readonly recipient: { readonly tenantId: string; readonly permission: string };\n readonly payload: unknown;\n }): Promise<unknown>;\n}\n\n/**\n * The words SEFAZ receives in a document, an event or a request — the host's,\n * in the host's language, 15 to 255 characters each. No default: a library\n * that wrote them would be writing a fiscal statement for its host.\n */\nexport interface FiscalReasons {\n /** `xJust` of a document signed offline. */\n readonly contingency: string;\n /** Why an unused number is inutilized. */\n readonly inutilization: string;\n /** Why a document found authorised after its sale moved to contingency is cancelled. */\n readonly substitution: string;\n}\n\nexport interface FiscalDocumentsConfig {\n readonly store: FiscalStore;\n readonly issuer: Issuer;\n readonly signing: SigningIdentities;\n readonly storage: DocumentStorage;\n readonly sales: SaleSource;\n readonly notify: FiscalNotifyPort;\n readonly now: () => Date;\n /** The owner's UTC offset at an instant (`-03:00`): `dhEmi` and `dhCont` are local times. */\n readonly utcOffset: (ownerId: string, at: Date) => string | Promise<string>;\n readonly reasons: FiscalReasons;\n /**\n * How long a document owing a step waits before the sweep takes it again,\n * the base of the backoff: each failure in a row doubles it, up to 64×.\n */\n readonly staleAfterMs: number;\n /**\n * How late an online NFC-e may still be sent with its `dhEmi`. SEFAZ refuses\n * a late one (704, \"data-hora de emissão atrasada\"; five minutes in most\n * states — the host's, per state). Past it, a stale online NFC-e at a point\n * with a contingency series goes offline instead of being sent again.\n */\n readonly nfceOnlineToleranceMs: number;\n /** Ids for new documents. */\n readonly newId: () => string;\n}\n\nexport const FISCAL_DOCUMENT_REJECTED = \"fiscal.document-rejected\";\nexport const FISCAL_CERTIFICATE_EXPIRING = \"fiscal.certificate-expiring\";\nexport const FISCAL_DOCUMENT_NEEDS_ATTENTION = \"fiscal.document-needs-attention\";\nexport const FISCAL_CONTINGENCY_DEADLINE = \"fiscal.contingency-deadline\";\n\nconst REQUIRED_PORTS = [\"store\", \"issuer\", \"signing\", \"storage\", \"sales\", \"notify\"] as const;\nconst REQUIRED_FUNCTIONS = [\"now\", \"utcOffset\", \"newId\"] as const;\nconst REASONS = [\"contingency\", \"inutilization\", \"substitution\"] as const;\nconst DURATIONS = [\"staleAfterMs\", \"nfceOnlineToleranceMs\"] as const;\n\nexport function assertConfig(config: FiscalDocumentsConfig): void {\n const missing = [\n ...REQUIRED_PORTS.filter((port) => config?.[port] === undefined || config[port] === null),\n ...REQUIRED_FUNCTIONS.filter((fn) => typeof config?.[fn] !== \"function\"),\n ...DURATIONS.filter((name) => !Number.isInteger(config?.[name]) || config[name] <= 0),\n ];\n if (missing.length > 0) throw new TypeError(`createFiscalDocuments needs ${missing.join(\", \")}.`);\n for (const name of REASONS) assertReason(config.reasons?.[name], `reasons.${name}`);\n}\n\nexport function assertReason(text: unknown, name: string): asserts text is string {\n if (typeof text !== \"string\" || text.trim().length < 15 || text.length > 255) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `${name} must be 15 to 255 characters.`);\n }\n}\n\n/** The backoff never grows past 64 × `staleAfterMs`. */\nconst MAX_BACKOFF_DOUBLINGS = 6;\n\n/** Whether a document still owes the sweep (or the transmission) a call. */\nfunction owesWork(document: FiscalDocument): boolean {\n if (document.status === \"PENDING\" || document.status === \"SUBMITTED\" || document.status === \"CONTINGENCY\") return true;\n return document.numberVoid !== null && OWED_VOIDS.includes(document.numberVoid);\n}\n\nexport class FiscalContext {\n constructor(readonly config: FiscalDocumentsConfig) {}\n\n nowIso(): string {\n return this.config.now().toISOString();\n }\n\n async localNow(ownerId: string): Promise<string> {\n const at = this.config.now();\n return localIso(at, await this.config.utcOffset(ownerId, at));\n }\n\n /** When a document may be taken again: never, when nothing is owed or a person must look. */\n nextAttemptAt(document: FiscalDocument): string | null {\n if (document.attention || !owesWork(document)) return null;\n const wait = this.config.staleAfterMs * 2 ** Math.min(document.failures, MAX_BACKOFF_DOUBLINGS);\n return new Date(this.config.now().getTime() + wait).toISOString();\n }\n\n /** The machine's step, scheduled. */\n scheduled(document: FiscalDocument, input: DocumentInput): Transition {\n const step = transition(document, input, this.nowIso());\n return { ...step, document: { ...step.document, nextAttemptAt: this.nextAttemptAt(step.document) } };\n }\n\n /**\n * Persist one transition; a lost race is a `CONFLICT`, never a silent\n * overwrite. A document that has just come to need a person is announced.\n */\n async advance(document: FiscalDocument, input: DocumentInput): Promise<FiscalDocument> {\n const step = this.scheduled(document, input);\n if (!(await this.config.store.saveTransition(document, step))) {\n throw new FiscalDocumentError(\"CONFLICT\", `document ${document.id} moved while ${input.kind} was applied.`);\n }\n if (step.document.attention && !document.attention) await this.announceAttention(step.document);\n return step.document;\n }\n\n async announceAttention(document: FiscalDocument): Promise<void> {\n await this.config.notify.emit({\n type: FISCAL_DOCUMENT_NEEDS_ATTENTION,\n recipient: { tenantId: document.ownerId, permission: FISCAL_ISSUE },\n payload: {\n documentId: document.id,\n subjectId: document.subjectId,\n model: document.model,\n status: document.status,\n numberVoid: document.numberVoid,\n series: document.series,\n number: document.number,\n code: document.statusCode,\n reason: document.statusReason ?? \"\",\n failures: document.failures,\n },\n });\n }\n\n material(profile: EmitterProfile): Promise<SigningMaterial> {\n return this.config.signing[profile.signingIdentity].materialFor(profile);\n }\n\n async requireProfile(ownerId: string): Promise<EmitterProfile> {\n const profile = await this.config.store.getProfile(ownerId);\n if (profile === null) throw new FiscalDocumentError(\"NOT_FOUND\", `owner ${ownerId} has no emitter profile.`);\n return profile;\n }\n\n async requirePoint(ownerId: string, issuingPointId: string): Promise<IssuingPoint> {\n const point = await this.config.store.getIssuingPoint(ownerId, issuingPointId);\n if (point === null) throw new FiscalDocumentError(\"NOT_FOUND\", `owner ${ownerId} has no issuing point ${issuingPointId}.`);\n return point;\n }\n\n /**\n * Draw the next number of a series and store the PENDING document built on\n * it, together. With `replacing`, that document is REPLACED by this one in\n * the same transaction (going offline), so a crash leaves exactly one live.\n */\n async createNumbered(input: {\n readonly profile: EmitterProfile;\n readonly point: IssuingPoint;\n readonly subjectId: string;\n readonly model: FiscalDocumentModel;\n readonly seriesKind: SeriesKind;\n readonly draft: SaleDraft;\n readonly replacing?: FiscalDocument;\n }): Promise<FiscalDocument> {\n const { profile, point, draft } = input;\n const series = input.seriesKind === \"ONLINE\" ? point.onlineSeries : point.contingencySeries;\n if (series === null) throw new FiscalDocumentError(\"INVALID_INPUT\", `issuing point ${point.id} has no contingency series.`);\n const issuedAt = await this.localNow(profile.ownerId);\n const at = this.nowIso();\n const id = this.config.newId();\n const replace =\n input.replacing === undefined\n ? undefined\n : { previous: input.replacing, transition: this.scheduled(input.replacing, { kind: \"REPLACE\", replacedById: id }) };\n const request = {\n ownerId: profile.ownerId,\n issuerCnpj: profile.cnpj,\n issuingPointId: point.id,\n environment: profile.environment,\n model: input.model,\n seriesKind: input.seriesKind,\n series,\n };\n return this.config.store.createDocument(\n request,\n (number) => {\n const keyCode = drawKeyCode(number);\n const sale = { ...draft, series, number, keyCode, issuedAt, issuer: issuerOf(profile) };\n return {\n id,\n ownerId: profile.ownerId,\n issuerCnpj: profile.cnpj,\n subjectId: input.subjectId,\n issuingPointId: point.id,\n model: input.model,\n environment: profile.environment,\n seriesKind: input.seriesKind,\n series,\n number,\n keyCode,\n status: \"PENDING\",\n sale,\n totals: totalsOf(draft),\n buyerTaxId: draft.buyer?.document.number ?? null,\n accessKey: computeAccessKey({ sale, model: input.model, seriesKind: input.seriesKind }),\n protocol: null,\n statusCode: null,\n statusReason: null,\n lastErrorClass: null,\n outcomeUnknown: false,\n issuedAt,\n authorizedAt: null,\n contingency: null,\n cancelledAt: null,\n cancelReason: null,\n cancelProtocol: null,\n replacedById: null,\n numberVoid: null,\n xmlKey: null,\n eventXmlKey: null,\n attempts: 0,\n failures: 0,\n nextAttemptAt: new Date(Date.parse(at) + this.config.staleAfterMs).toISOString(),\n attention: false,\n deadlineWarnedAt: null,\n createdAt: at,\n updatedAt: at,\n };\n },\n replace,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsBO,IAAM,eAAe;AAgDrB,SAAS,OAAO,UAA0B,MAAyB,KAAoB;AAC5F,QAAM,IAAI;AAAA,IACR;AAAA,IACA,GAAG,IAAI,2BAA2B,SAAS,EAAE,OAAO,SAAS,MAAM,KAAK,GAAG;AAAA,EAC7E;AACF;AALgB;AAQhB,IAAM,UAAU,EAAE,UAAU,GAAG,WAAW,MAAM;AAEhD,SAAS,aAAa,QAAwB,QAAyC;AACrF,SAAO;AAAA,IACL,GAAG;AAAA,IACH,WAAW,OAAO;AAAA,IAClB,UAAU,OAAO;AAAA,IACjB,cAAc,OAAO;AAAA,IACrB,YAAY,OAAO;AAAA,IACnB,cAAc,OAAO;AAAA,IACrB,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB;AAAA,EACF;AACF;AAZS;AAmBT,SAAS,aAAa,UAA0B,OAA8C;AAC5F,SAAO;AAAA,IACL,WAAW,SAAS,aAAa,MAAM;AAAA,IACvC,YAAY,M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AS,QAAQ;AAAA,UACjB,YAAY,QAAQ;AAAA,UACpB,WAAW,MAAM;AAAA,UACjB,gBAAgB,MAAM;AAAA,UACtB,OAAO,MAAM;AAAA,UACb,aAAa,QAAQ;AAAA,UACrB,YAAY,MAAM;AAAA,UAClB;AAAA,UACA;AAAA,UACA;AAAA,UACA,QAAQ;AAAA,UACR;AAAA,UACA,QAAQ,SAAS,KAAK;AAAA,UACtB,YAAY,MAAM,OAAO,SAAS,UAAU;AAAA,UAC5C,WAAW,iBAAiB,EAAE,MAAM,OAAO,MAAM,OAAO,YAAY,MAAM,WAAW,CAAC;AAAA,UACtF,UAAU;AAAA,UACV,YAAY;AAAA,UACZ,cAAc;AAAA,UACd,gBAAgB;AAAA,UAChB,gBAAgB;AAAA,UAChB;AAAA,UACA,cAAc;AAAA,UACd,aAAa;AAAA,UACb,aAAa;AAAA,UACb,cAAc;AAAA,UACd,gBAAgB;AAAA,UAChB,cAAc;AAAA,UACd,YAAY;AAAA,UACZ,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,UAAU;AAAA,UACV,UAAU;AAAA,UACV,eAAe,IAAI,KAAK,KAAK,MAAM,EAAE,IAAI,KAAK,OAAO,YAAY,EAAE,YAAY;AAAA,UAC/E,WAAW;AAAA,UACX,kBAAkB;AAAA,UAClB,WAAW;AAAA,UACX,WAAW;AAAA,QACb;AAAA,MACF;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,24 @@
1
+ // src/manifest/permissions.ts
2
+ var FISCAL_READ = "fiscal:read";
3
+ var FISCAL_MANAGE = "fiscal:manage";
4
+ var FISCAL_ISSUE = "fiscal:issue";
5
+ var FISCAL_CANCEL = "fiscal:cancel";
6
+ var FISCAL_PERMISSIONS = {
7
+ source: "@12-apps/fiscal",
8
+ ids: [FISCAL_READ, FISCAL_MANAGE, FISCAL_ISSUE, FISCAL_CANCEL],
9
+ permissions: {
10
+ [FISCAL_READ]: { kind: "class" },
11
+ [FISCAL_MANAGE]: { kind: "class" },
12
+ [FISCAL_ISSUE]: { kind: "class" },
13
+ [FISCAL_CANCEL]: { kind: "class" }
14
+ }
15
+ };
16
+
17
+ export {
18
+ FISCAL_READ,
19
+ FISCAL_MANAGE,
20
+ FISCAL_ISSUE,
21
+ FISCAL_CANCEL,
22
+ FISCAL_PERMISSIONS
23
+ };
24
+ //# sourceMappingURL=chunk-3SDXLSG4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/manifest/permissions.ts"],"sourcesContent":["/**\n * The package's permissions, declared HERE and nowhere else (the owner's\n * decision on FUT-2237): a host composes them into its RBAC catalog and\n * decides which roles hold them. The ids are mechanism; the words a picker\n * shows are the host's, so no `labels` ship.\n */\n\nimport type { WirePermissionsContribution } from \"@12-apps/wiring\";\n\n/** See the fiscal settings and the documents issued. */\nexport const FISCAL_READ = \"fiscal:read\";\n/** Edit the emitter profile and its certificate. */\nexport const FISCAL_MANAGE = \"fiscal:manage\";\n/** Issue a fiscal document. */\nexport const FISCAL_ISSUE = \"fiscal:issue\";\n/** Cancel an issued fiscal document. */\nexport const FISCAL_CANCEL = \"fiscal:cancel\";\n\nexport const FISCAL_PERMISSIONS = {\n source: \"@12-apps/fiscal\",\n ids: [FISCAL_READ, FISCAL_MANAGE, FISCAL_ISSUE, FISCAL_CANCEL],\n permissions: {\n [FISCAL_READ]: { kind: \"class\" },\n [FISCAL_MANAGE]: { kind: \"class\" },\n [FISCAL_ISSUE]: { kind: \"class\" },\n [FISCAL_CANCEL]: { kind: \"class\" },\n },\n} as const satisfies WirePermissionsContribution;\n"],"mappings":";AAUO,IAAM,cAAc;AAEpB,IAAM,gBAAgB;AAEtB,IAAM,eAAe;AAErB,IAAM,gBAAgB;AAEtB,IAAM,qBAAqB;AAAA,EAChC,QAAQ;AAAA,EACR,KAAK,CAAC,aAAa,eAAe,cAAc,aAAa;AAAA,EAC7D,aAAa;AAAA,IACX,CAAC,WAAW,GAAG,EAAE,MAAM,QAAQ;AAAA,IAC/B,CAAC,aAAa,GAAG,EAAE,MAAM,QAAQ;AAAA,IACjC,CAAC,YAAY,GAAG,EAAE,MAAM,QAAQ;AAAA,IAChC,CAAC,aAAa,GAAG,EAAE,MAAM,QAAQ;AAAA,EACnC;AACF;","names":[]}
@@ -0,0 +1,247 @@
1
+ import {
2
+ accessKeyOf,
3
+ element,
4
+ elements,
5
+ text
6
+ } from "./chunk-PNTKG3DZ.js";
7
+ import {
8
+ FiscalDocumentError
9
+ } from "./chunk-X6MRDUYH.js";
10
+ import {
11
+ __name
12
+ } from "./chunk-7QVYU63E.js";
13
+
14
+ // src/danfe/labels.ts
15
+ var DANFE_LABEL_KEYS = [
16
+ "cnpj",
17
+ "stateRegistration",
18
+ "title",
19
+ "itemsHeader",
20
+ "itemCount",
21
+ "totalValue",
22
+ "discounts",
23
+ "amountDue",
24
+ "paymentHeader",
25
+ "change",
26
+ "paymentMethods",
27
+ "lookupByKey",
28
+ "homologation",
29
+ "contingency",
30
+ "pendingAuthorization",
31
+ "consumerCopy",
32
+ "consumer",
33
+ "unidentifiedConsumer",
34
+ "number",
35
+ "series",
36
+ "protocol",
37
+ "authorizedAt",
38
+ "qrCaption",
39
+ "approximateTaxes"
40
+ ];
41
+
42
+ // src/danfe/render.ts
43
+ var DANFE_COLUMNS = { 58: 32, 80: 48 };
44
+ function money(value) {
45
+ const cents = Math.round(Number(value ?? "0") * 100);
46
+ const whole = Math.trunc(Math.abs(cents) / 100).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
47
+ return `${cents < 0 ? "-" : ""}${whole},${String(Math.abs(cents) % 100).padStart(2, "0")}`;
48
+ }
49
+ __name(money, "money");
50
+ function quantity(value) {
51
+ return Number(value ?? "0").toLocaleString("en-US", { maximumFractionDigits: 4, useGrouping: false }).replace(".", ",");
52
+ }
53
+ __name(quantity, "quantity");
54
+ function pieces(word, width) {
55
+ const out = [];
56
+ for (let at = 0; at < word.length; at += width) out.push(word.slice(at, at + width));
57
+ return out;
58
+ }
59
+ __name(pieces, "pieces");
60
+ function wrap(value, width) {
61
+ const words = value.trim().split(/\s+/).filter((word) => word !== "").flatMap((word) => pieces(word, width));
62
+ const lines = [];
63
+ let current = "";
64
+ for (const word of words) {
65
+ const candidate = current === "" ? word : `${current} ${word}`;
66
+ if (candidate.length <= width) {
67
+ current = candidate;
68
+ continue;
69
+ }
70
+ if (current !== "") lines.push(current);
71
+ current = word;
72
+ }
73
+ if (current !== "") lines.push(current);
74
+ return lines.length > 0 ? lines : [""];
75
+ }
76
+ __name(wrap, "wrap");
77
+ function spread(label, value, width) {
78
+ const gap = width - label.length - value.length;
79
+ return gap >= 1 ? `${label}${" ".repeat(gap)}${value}` : `${label} ${value}`;
80
+ }
81
+ __name(spread, "spread");
82
+ function groupKey(key) {
83
+ return key.replace(/(.{4})/g, "$1 ").trim();
84
+ }
85
+ __name(groupKey, "groupKey");
86
+ var Paper = class {
87
+ constructor(width) {
88
+ this.width = width;
89
+ }
90
+ width;
91
+ static {
92
+ __name(this, "Paper");
93
+ }
94
+ lines = [];
95
+ add(division, value, align = "left", emphasis = "normal") {
96
+ for (const piece of wrap(value, this.width)) this.lines.push({ division, text: piece, align, emphasis });
97
+ }
98
+ /**
99
+ * `label ……… value` on one line when it fits; otherwise the label wraps and
100
+ * the value closes its last line, or takes a line of its own, right-aligned.
101
+ * Nothing passes the roll's width.
102
+ */
103
+ pair(division, label, value, emphasis = "normal") {
104
+ const labelLines = wrap(label, this.width);
105
+ const last = labelLines.pop() ?? "";
106
+ for (const piece of labelLines) this.lines.push({ division, text: piece, align: "left", emphasis });
107
+ const closing = last.length + 1 + value.length <= this.width ? [spread(last, value, this.width)] : [last, value.padStart(this.width)];
108
+ for (const piece of closing) this.lines.push({ division, text: piece, align: "left", emphasis });
109
+ }
110
+ rule(division) {
111
+ this.lines.push({ division, text: "-".repeat(this.width), align: "left", emphasis: "normal" });
112
+ }
113
+ };
114
+ function parse(xml) {
115
+ const infNFe = element(xml, "infNFe");
116
+ const ide = infNFe === null ? null : element(infNFe, "ide");
117
+ const emit = infNFe === null ? null : element(infNFe, "emit");
118
+ const accessKey = accessKeyOf(xml);
119
+ if (infNFe === null || ide === null || emit === null || accessKey === null) {
120
+ throw new FiscalDocumentError("INVALID_INPUT", "the XML is not an NF-e: no infNFe, ide, emit or access key.");
121
+ }
122
+ if (text(ide, "mod") !== "65") throw new FiscalDocumentError("INVALID_INPUT", "the XML is not an NFC-e (model 65).");
123
+ return {
124
+ infNFe,
125
+ ide,
126
+ emit,
127
+ total: element(infNFe, "ICMSTot") ?? "",
128
+ supl: element(xml, "infNFeSupl") ?? "",
129
+ accessKey,
130
+ contingency: text(ide, "tpEmis") === "9",
131
+ infProt: element(xml, "infProt"),
132
+ homologation: text(ide, "tpAmb") === "2"
133
+ };
134
+ }
135
+ __name(parse, "parse");
136
+ function issuerPart(paper, doc, labels) {
137
+ const address = element(doc.emit, "enderEmit");
138
+ paper.add("I", text(doc.emit, "xNome") ?? "", "center", "bold");
139
+ paper.add("I", `${labels.cnpj} ${text(doc.emit, "CNPJ") ?? ""} ${labels.stateRegistration} ${text(doc.emit, "IE") ?? ""}`, "center");
140
+ const street = [text(address, "xLgr"), text(address, "nro"), text(address, "xBairro"), text(address, "xMun"), text(address, "UF")];
141
+ paper.add("I", street.filter((part) => part !== null && part !== "").join(", "), "center");
142
+ paper.add("II", labels.title, "center", "bold");
143
+ paper.rule("II");
144
+ }
145
+ __name(issuerPart, "issuerPart");
146
+ function itemsPart(paper, doc, labels) {
147
+ paper.add("III", labels.itemsHeader);
148
+ const items = elements(doc.infNFe, "det");
149
+ for (const det of items) {
150
+ const prod = element(det, "prod");
151
+ paper.add("III", `${text(prod, "cProd") ?? ""} ${text(prod, "xProd") ?? ""}`);
152
+ const amount = `${quantity(text(prod, "qCom"))} ${text(prod, "uCom") ?? ""} x ${money(text(prod, "vUnCom"))}`;
153
+ paper.pair("III", amount, money(text(prod, "vProd")));
154
+ }
155
+ paper.rule("III");
156
+ return items.length;
157
+ }
158
+ __name(itemsPart, "itemsPart");
159
+ function totalsPart(paper, doc, labels, count) {
160
+ paper.pair("IV", labels.itemCount, String(count));
161
+ paper.pair("IV", labels.totalValue, money(text(doc.total, "vProd")));
162
+ const discount = text(doc.total, "vDesc");
163
+ if (discount !== null && Number(discount) > 0) paper.pair("IV", labels.discounts, money(discount));
164
+ paper.pair("IV", labels.amountDue, money(text(doc.total, "vNF")), "bold");
165
+ paper.add("IV", labels.paymentHeader);
166
+ for (const detPag of elements(doc.infNFe, "detPag")) {
167
+ const code = text(detPag, "tPag") ?? "";
168
+ paper.pair("IV", text(detPag, "xPag") ?? labels.paymentMethods[code] ?? code, money(text(detPag, "vPag")));
169
+ }
170
+ const change = text(element(doc.infNFe, "pag"), "vTroco");
171
+ if (change !== null && Number(change) > 0) paper.pair("IV", labels.change, money(change));
172
+ paper.rule("IV");
173
+ }
174
+ __name(totalsPart, "totalsPart");
175
+ function fiscalMessagePart(paper, doc, labels) {
176
+ if (doc.homologation) paper.add("V", labels.homologation, "center", "bold");
177
+ if (doc.contingency) paper.add("V", labels.contingency, "center", "bold");
178
+ if (doc.contingency && doc.infProt === null) {
179
+ paper.add("V", labels.pendingAuthorization, "center", "bold");
180
+ paper.add("V", labels.consumerCopy, "center", "bold");
181
+ }
182
+ paper.add("V", labels.lookupByKey, "center");
183
+ paper.add("V", text(doc.supl, "urlChave") ?? "", "center");
184
+ paper.add("V", groupKey(doc.accessKey), "center");
185
+ paper.rule("V");
186
+ }
187
+ __name(fiscalMessagePart, "fiscalMessagePart");
188
+ function consumerPart(paper, doc, labels) {
189
+ const dest = element(doc.infNFe, "dest");
190
+ const id = text(dest, "CPF") ?? text(dest, "CNPJ") ?? text(dest, "idEstrangeiro");
191
+ if (id === null) {
192
+ paper.add("VI", labels.unidentifiedConsumer, "center");
193
+ } else {
194
+ paper.add("VI", `${labels.consumer} ${id}`, "center");
195
+ const name = text(dest, "xNome");
196
+ if (name !== null) paper.add("VI", name, "center");
197
+ }
198
+ paper.rule("VI");
199
+ }
200
+ __name(consumerPart, "consumerPart");
201
+ function identificationPart(paper, doc, labels) {
202
+ const issued = (text(doc.ide, "dhEmi") ?? "").replace("T", " ").slice(0, 19);
203
+ paper.add("VII", `${labels.number} ${text(doc.ide, "nNF") ?? ""} ${labels.series} ${text(doc.ide, "serie") ?? ""} ${issued}`, "center", "bold");
204
+ const { infProt } = doc;
205
+ if (infProt !== null) {
206
+ paper.add("VII", `${labels.protocol} ${text(infProt, "nProt") ?? ""}`, "center");
207
+ paper.add("VII", `${labels.authorizedAt} ${(text(infProt, "dhRecbto") ?? "").replace("T", " ").slice(0, 19)}`, "center");
208
+ }
209
+ }
210
+ __name(identificationPart, "identificationPart");
211
+ function qrPart(paper, doc, labels) {
212
+ const qrCode = text(doc.supl, "qrCode");
213
+ if (qrCode === null) throw new FiscalDocumentError("INVALID_INPUT", "the NFC-e XML carries no QR code (infNFeSupl/qrCode).");
214
+ paper.add("VIII", labels.qrCaption, "center");
215
+ paper.lines.push({ division: "VIII", text: "", align: "center", emphasis: "normal", qrCode });
216
+ const message = text(element(doc.infNFe, "infAdic"), "infCpl");
217
+ if (message !== null && message !== "") paper.add("VIII", message);
218
+ const taxes = text(doc.total, "vTotTrib");
219
+ if (taxes !== null && Number(taxes) > 0) paper.add("VIII", `${labels.approximateTaxes} ${money(taxes)}`);
220
+ }
221
+ __name(qrPart, "qrPart");
222
+ function renderDanfeNfce(input) {
223
+ const missing = DANFE_LABEL_KEYS.filter((key) => input.labels?.[key] === void 0);
224
+ if (missing.length > 0) throw new FiscalDocumentError("INVALID_INPUT", `labels is missing: ${missing.join(", ")}.`);
225
+ const width = DANFE_COLUMNS[input.paperWidth];
226
+ if (width === void 0) throw new FiscalDocumentError("INVALID_INPUT", "paperWidth must be 58 or 80.");
227
+ const doc = parse(input.xml);
228
+ const paper = new Paper(width);
229
+ issuerPart(paper, doc, input.labels);
230
+ const count = itemsPart(paper, doc, input.labels);
231
+ totalsPart(paper, doc, input.labels, count);
232
+ fiscalMessagePart(paper, doc, input.labels);
233
+ consumerPart(paper, doc, input.labels);
234
+ identificationPart(paper, doc, input.labels);
235
+ qrPart(paper, doc, input.labels);
236
+ return paper.lines;
237
+ }
238
+ __name(renderDanfeNfce, "renderDanfeNfce");
239
+
240
+ export {
241
+ DANFE_LABEL_KEYS,
242
+ DANFE_COLUMNS,
243
+ money,
244
+ wrap,
245
+ renderDanfeNfce
246
+ };
247
+ //# sourceMappingURL=chunk-ALABGVPO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/danfe/labels.ts","../src/danfe/render.ts"],"sourcesContent":["/**\n * The words a DANFE NFC-e prints. The layout is the Manual do DANFE NFC-e's\n * and the words are the host's language: a host passes them all, or the\n * `./pt-BR` pack, which carries the Manual's own texts. Nothing here defaults.\n */\n\nexport interface DanfeNfceLabels {\n /** Division I. */\n readonly cnpj: string;\n readonly stateRegistration: string;\n /** Division II: the document's own title. */\n readonly title: string;\n /** Division III: the item table's header. */\n readonly itemsHeader: string;\n /** Division IV. */\n readonly itemCount: string;\n readonly totalValue: string;\n readonly discounts: string;\n readonly amountDue: string;\n readonly paymentHeader: string;\n readonly change: string;\n /** `tPag` code (`01`, `17`…) → the method's name; an unknown code prints itself. */\n readonly paymentMethods: Readonly<Record<string, string>>;\n /** Division V. */\n readonly lookupByKey: string;\n readonly homologation: string;\n readonly contingency: string;\n readonly pendingAuthorization: string;\n /** Printed on a paper signed offline and not yet authorised: the one copy, the consumer's. */\n readonly consumerCopy: string;\n /** Division VI. */\n readonly consumer: string;\n readonly unidentifiedConsumer: string;\n /** Division VII. */\n readonly number: string;\n readonly series: string;\n readonly protocol: string;\n readonly authorizedAt: string;\n /** Division VIII and after: the QR code's caption and the approximate tax line (Lei 12.741/2012). */\n readonly qrCaption: string;\n readonly approximateTaxes: string;\n}\n\nexport const DANFE_LABEL_KEYS: readonly (keyof DanfeNfceLabels)[] = [\n \"cnpj\", \"stateRegistration\", \"title\", \"itemsHeader\", \"itemCount\", \"totalValue\", \"discounts\", \"amountDue\",\n \"paymentHeader\", \"change\", \"paymentMethods\", \"lookupByKey\", \"homologation\", \"contingency\", \"pendingAuthorization\",\n \"consumerCopy\",\n \"consumer\", \"unidentifiedConsumer\", \"number\", \"series\", \"protocol\", \"authorizedAt\", \"qrCaption\", \"approximateTaxes\",\n];\n","/**\n * The DANFE NFC-e as ESC/POS-ready lines, read from the document's XML —\n * the authorised `nfeProc`, or the signed XML of a document issued offline,\n * which prints the contingency variant. No provider returns ESC/POS and a\n * register offline has nothing else to print, so the package renders it.\n *\n * The paper follows the Manual do DANFE NFC-e's divisions, in order (the\n * FULL DANFE, items included):\n *\n * I the issuer: name, CNPJ, IE, address\n * II the document's title\n * III the items: code, description, quantity, unit, unit value, total\n * IV the totals: item count, total, discounts, amount due, payments, change\n * V the fiscal message: homologation, contingency, where to look the key up, the key\n * VI the consumer\n * VII the number, series, issue time, and the authorisation protocol\n * VIII the QR code, then the taxpayer's message and the approximate taxes\n *\n * Each line is `{ text, align, emphasis }`, the shape `@12-apps/thermal-printing`\n * encodes, laid out for the column count of the roll (Font A: 32 columns on\n * 58 mm, 48 on 80 mm); the QR line carries `qrCode` for the host to rasterise.\n */\n\nimport { FiscalDocumentError } from \"../documents/errors\";\nimport type { DanfeNfceLabels } from \"./labels\";\nimport { DANFE_LABEL_KEYS } from \"./labels\";\nimport { accessKeyOf, element, elements, text } from \"./xml\";\n\nexport type DanfeDivision = \"I\" | \"II\" | \"III\" | \"IV\" | \"V\" | \"VI\" | \"VII\" | \"VIII\";\n\nexport interface DanfeLine {\n readonly division: DanfeDivision;\n readonly text: string;\n readonly align: \"left\" | \"center\";\n readonly emphasis: \"normal\" | \"bold\";\n /** Present on the QR line only: the URL the code encodes. */\n readonly qrCode?: string;\n}\n\nexport type PaperWidth = 58 | 80;\n\nexport const DANFE_COLUMNS: Readonly<Record<PaperWidth, number>> = { 58: 32, 80: 48 };\n\nexport interface DanfeNfceInput {\n /** The `nfeProc` of an authorised document, or the signed XML of one issued offline. */\n readonly xml: string;\n readonly paperWidth: PaperWidth;\n readonly labels: DanfeNfceLabels;\n}\n\n/** `1234` cents → `12,34`; thousands with a dot, as the DANFE prints money. */\nexport function money(value: string | null): string {\n const cents = Math.round(Number(value ?? \"0\") * 100);\n const whole = Math.trunc(Math.abs(cents) / 100).toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \".\");\n return `${cents < 0 ? \"-\" : \"\"}${whole},${String(Math.abs(cents) % 100).padStart(2, \"0\")}`;\n}\n\nfunction quantity(value: string | null): string {\n return Number(value ?? \"0\").toLocaleString(\"en-US\", { maximumFractionDigits: 4, useGrouping: false }).replace(\".\", \",\");\n}\n\n/** A word longer than the width (a URL) cut into width-long pieces: nothing is dropped. */\nfunction pieces(word: string, width: number): string[] {\n const out: string[] = [];\n for (let at = 0; at < word.length; at += width) out.push(word.slice(at, at + width));\n return out;\n}\n\n/** Wrap a text at the width, breaking on spaces where it can. */\nexport function wrap(value: string, width: number): string[] {\n const words = value\n .trim()\n .split(/\\s+/)\n .filter((word) => word !== \"\")\n .flatMap((word) => pieces(word, width));\n const lines: string[] = [];\n let current = \"\";\n for (const word of words) {\n const candidate = current === \"\" ? word : `${current} ${word}`;\n if (candidate.length <= width) {\n current = candidate;\n continue;\n }\n if (current !== \"\") lines.push(current);\n current = word;\n }\n if (current !== \"\") lines.push(current);\n return lines.length > 0 ? lines : [\"\"];\n}\n\n/** `label ……… value` across the width. */\nfunction spread(label: string, value: string, width: number): string {\n const gap = width - label.length - value.length;\n return gap >= 1 ? `${label}${\" \".repeat(gap)}${value}` : `${label} ${value}`;\n}\n\nfunction groupKey(key: string): string {\n return key.replace(/(.{4})/g, \"$1 \").trim();\n}\n\nclass Paper {\n readonly lines: DanfeLine[] = [];\n constructor(readonly width: number) {}\n\n add(division: DanfeDivision, value: string, align: DanfeLine[\"align\"] = \"left\", emphasis: DanfeLine[\"emphasis\"] = \"normal\"): void {\n for (const piece of wrap(value, this.width)) this.lines.push({ division, text: piece, align, emphasis });\n }\n\n /**\n * `label ……… value` on one line when it fits; otherwise the label wraps and\n * the value closes its last line, or takes a line of its own, right-aligned.\n * Nothing passes the roll's width.\n */\n pair(division: DanfeDivision, label: string, value: string, emphasis: DanfeLine[\"emphasis\"] = \"normal\"): void {\n const labelLines = wrap(label, this.width);\n const last = labelLines.pop() ?? \"\";\n for (const piece of labelLines) this.lines.push({ division, text: piece, align: \"left\", emphasis });\n const closing = last.length + 1 + value.length <= this.width ? [spread(last, value, this.width)] : [last, value.padStart(this.width)];\n for (const piece of closing) this.lines.push({ division, text: piece, align: \"left\", emphasis });\n }\n\n rule(division: DanfeDivision): void {\n this.lines.push({ division, text: \"-\".repeat(this.width), align: \"left\", emphasis: \"normal\" });\n }\n}\n\ninterface Parsed {\n readonly infNFe: string;\n readonly ide: string;\n readonly emit: string;\n readonly total: string;\n /** `infNFeSupl`, beside `infNFe`: the QR code and the lookup URL. */\n readonly supl: string;\n readonly accessKey: string;\n readonly contingency: boolean;\n /** The authorisation protocol, once SEFAZ has answered (the `nfeProc`). */\n readonly infProt: string | null;\n readonly homologation: boolean;\n}\n\nfunction parse(xml: string): Parsed {\n const infNFe = element(xml, \"infNFe\");\n const ide = infNFe === null ? null : element(infNFe, \"ide\");\n const emit = infNFe === null ? null : element(infNFe, \"emit\");\n const accessKey = accessKeyOf(xml);\n if (infNFe === null || ide === null || emit === null || accessKey === null) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", \"the XML is not an NF-e: no infNFe, ide, emit or access key.\");\n }\n if (text(ide, \"mod\") !== \"65\") throw new FiscalDocumentError(\"INVALID_INPUT\", \"the XML is not an NFC-e (model 65).\");\n return {\n infNFe,\n ide,\n emit,\n total: element(infNFe, \"ICMSTot\") ?? \"\",\n supl: element(xml, \"infNFeSupl\") ?? \"\",\n accessKey,\n contingency: text(ide, \"tpEmis\") === \"9\",\n infProt: element(xml, \"infProt\"),\n homologation: text(ide, \"tpAmb\") === \"2\",\n };\n}\n\nfunction issuerPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {\n const address = element(doc.emit, \"enderEmit\");\n paper.add(\"I\", text(doc.emit, \"xNome\") ?? \"\", \"center\", \"bold\");\n paper.add(\"I\", `${labels.cnpj} ${text(doc.emit, \"CNPJ\") ?? \"\"} ${labels.stateRegistration} ${text(doc.emit, \"IE\") ?? \"\"}`, \"center\");\n const street = [text(address, \"xLgr\"), text(address, \"nro\"), text(address, \"xBairro\"), text(address, \"xMun\"), text(address, \"UF\")];\n paper.add(\"I\", street.filter((part) => part !== null && part !== \"\").join(\", \"), \"center\");\n paper.add(\"II\", labels.title, \"center\", \"bold\");\n paper.rule(\"II\");\n}\n\nfunction itemsPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): number {\n paper.add(\"III\", labels.itemsHeader);\n const items = elements(doc.infNFe, \"det\");\n for (const det of items) {\n const prod = element(det, \"prod\");\n paper.add(\"III\", `${text(prod, \"cProd\") ?? \"\"} ${text(prod, \"xProd\") ?? \"\"}`);\n const amount = `${quantity(text(prod, \"qCom\"))} ${text(prod, \"uCom\") ?? \"\"} x ${money(text(prod, \"vUnCom\"))}`;\n paper.pair(\"III\", amount, money(text(prod, \"vProd\")));\n }\n paper.rule(\"III\");\n return items.length;\n}\n\nfunction totalsPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels, count: number): void {\n paper.pair(\"IV\", labels.itemCount, String(count));\n paper.pair(\"IV\", labels.totalValue, money(text(doc.total, \"vProd\")));\n const discount = text(doc.total, \"vDesc\");\n if (discount !== null && Number(discount) > 0) paper.pair(\"IV\", labels.discounts, money(discount));\n paper.pair(\"IV\", labels.amountDue, money(text(doc.total, \"vNF\")), \"bold\");\n paper.add(\"IV\", labels.paymentHeader);\n for (const detPag of elements(doc.infNFe, \"detPag\")) {\n const code = text(detPag, \"tPag\") ?? \"\";\n paper.pair(\"IV\", text(detPag, \"xPag\") ?? labels.paymentMethods[code] ?? code, money(text(detPag, \"vPag\")));\n }\n const change = text(element(doc.infNFe, \"pag\"), \"vTroco\");\n if (change !== null && Number(change) > 0) paper.pair(\"IV\", labels.change, money(change));\n paper.rule(\"IV\");\n}\n\nfunction fiscalMessagePart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {\n if (doc.homologation) paper.add(\"V\", labels.homologation, \"center\", \"bold\");\n if (doc.contingency) paper.add(\"V\", labels.contingency, \"center\", \"bold\");\n // Offline and not yet authorised: ONE copy, the consumer's (reprints are the same paper).\n if (doc.contingency && doc.infProt === null) {\n paper.add(\"V\", labels.pendingAuthorization, \"center\", \"bold\");\n paper.add(\"V\", labels.consumerCopy, \"center\", \"bold\");\n }\n paper.add(\"V\", labels.lookupByKey, \"center\");\n paper.add(\"V\", text(doc.supl, \"urlChave\") ?? \"\", \"center\");\n paper.add(\"V\", groupKey(doc.accessKey), \"center\");\n paper.rule(\"V\");\n}\n\nfunction consumerPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {\n const dest = element(doc.infNFe, \"dest\");\n const id = text(dest, \"CPF\") ?? text(dest, \"CNPJ\") ?? text(dest, \"idEstrangeiro\");\n if (id === null) {\n paper.add(\"VI\", labels.unidentifiedConsumer, \"center\");\n } else {\n paper.add(\"VI\", `${labels.consumer} ${id}`, \"center\");\n const name = text(dest, \"xNome\");\n if (name !== null) paper.add(\"VI\", name, \"center\");\n }\n paper.rule(\"VI\");\n}\n\nfunction identificationPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {\n const issued = (text(doc.ide, \"dhEmi\") ?? \"\").replace(\"T\", \" \").slice(0, 19);\n paper.add(\"VII\", `${labels.number} ${text(doc.ide, \"nNF\") ?? \"\"} ${labels.series} ${text(doc.ide, \"serie\") ?? \"\"} ${issued}`, \"center\", \"bold\");\n const { infProt } = doc;\n if (infProt !== null) {\n paper.add(\"VII\", `${labels.protocol} ${text(infProt, \"nProt\") ?? \"\"}`, \"center\");\n paper.add(\"VII\", `${labels.authorizedAt} ${(text(infProt, \"dhRecbto\") ?? \"\").replace(\"T\", \" \").slice(0, 19)}`, \"center\");\n }\n}\n\nfunction qrPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {\n const qrCode = text(doc.supl, \"qrCode\");\n if (qrCode === null) throw new FiscalDocumentError(\"INVALID_INPUT\", \"the NFC-e XML carries no QR code (infNFeSupl/qrCode).\");\n paper.add(\"VIII\", labels.qrCaption, \"center\");\n paper.lines.push({ division: \"VIII\", text: \"\", align: \"center\", emphasis: \"normal\", qrCode });\n const message = text(element(doc.infNFe, \"infAdic\"), \"infCpl\");\n if (message !== null && message !== \"\") paper.add(\"VIII\", message);\n const taxes = text(doc.total, \"vTotTrib\");\n if (taxes !== null && Number(taxes) > 0) paper.add(\"VIII\", `${labels.approximateTaxes} ${money(taxes)}`);\n}\n\nexport function renderDanfeNfce(input: DanfeNfceInput): DanfeLine[] {\n const missing = DANFE_LABEL_KEYS.filter((key) => input.labels?.[key] === undefined);\n if (missing.length > 0) throw new FiscalDocumentError(\"INVALID_INPUT\", `labels is missing: ${missing.join(\", \")}.`);\n const width = DANFE_COLUMNS[input.paperWidth];\n if (width === undefined) throw new FiscalDocumentError(\"INVALID_INPUT\", \"paperWidth must be 58 or 80.\");\n const doc = parse(input.xml);\n const paper = new Paper(width);\n issuerPart(paper, doc, input.labels);\n const count = itemsPart(paper, doc, input.labels);\n totalsPart(paper, doc, input.labels, count);\n fiscalMessagePart(paper, doc, input.labels);\n consumerPart(paper, doc, input.labels);\n identificationPart(paper, doc, input.labels);\n qrPart(paper, doc, input.labels);\n return paper.lines;\n}\n"],"mappings":";;;;;;;;;;;;;;AA2CO,IAAM,mBAAuD;AAAA,EAClE;AAAA,EAAQ;AAAA,EAAqB;AAAA,EAAS;AAAA,EAAe;AAAA,EAAa;AAAA,EAAc;AAAA,EAAa;AAAA,EAC7F;AAAA,EAAiB;AAAA,EAAU;AAAA,EAAkB;AAAA,EAAe;AAAA,EAAgB;AAAA,EAAe;AAAA,EAC3F;AAAA,EACA;AAAA,EAAY;AAAA,EAAwB;AAAA,EA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AAI,OAAO,UAAU;AACxC,MAAI,UAAU,QAAQ,OAAO,KAAK,IAAI,EAAG,OAAM,IAAI,QAAQ,GAAG,OAAO,gBAAgB,IAAI,MAAM,KAAK,CAAC,EAAE;AACzG;AATS;AAWF,SAAS,gBAAgB,OAAoC;AAClE,QAAM,UAAU,iBAAiB,OAAO,CAAC,QAAQ,MAAM,SAAS,GAAG,MAAM,MAAS;AAClF,MAAI,QAAQ,SAAS,EAAG,OAAM,IAAI,oBAAoB,iBAAiB,sBAAsB,QAAQ,KAAK,IAAI,CAAC,GAAG;AAClH,QAAM,QAAQ,cAAc,MAAM,UAAU;AAC5C,MAAI,UAAU,OAAW,OAAM,IAAI,oBAAoB,iBAAiB,8BAA8B;AACtG,QAAM,MAAM,MAAM,MAAM,GAAG;AAC3B,QAAM,QAAQ,IAAI,MAAM,KAAK;AAC7B,aAAW,OAAO,KAAK,MAAM,MAAM;AACnC,QAAM,QAAQ,UAAU,OAAO,KAAK,MAAM,MAAM;AAChD,aAAW,OAAO,KAAK,MAAM,QAAQ,KAAK;AAC1C,oBAAkB,OAAO,KAAK,MAAM,MAAM;AAC1C,eAAa,OAAO,KAAK,MAAM,MAAM;AACrC,qBAAmB,OAAO,KAAK,MAAM,MAAM;AAC3C,SAAO,OAAO,KAAK,MAAM,MAAM;AAC/B,SAAO,MAAM;AACf;AAfgB;","names":[]}
@@ -0,0 +1,14 @@
1
+ // src/sidecar/types.ts
2
+ var SIDECAR_ERROR_CLASSES = [
3
+ "REJECTED",
4
+ "RETRYABLE",
5
+ "CONTINGENCY",
6
+ "AUTH",
7
+ "INVALID",
8
+ "INTERNAL"
9
+ ];
10
+
11
+ export {
12
+ SIDECAR_ERROR_CLASSES
13
+ };
14
+ //# sourceMappingURL=chunk-FOFIN5M7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sidecar/types.ts"],"sourcesContent":["/**\n * The wire contract of the fiscal service (`sidecar/` in this package): a\n * stateless HTTP door in front of sped-nfe. JSON in, JSON out.\n *\n * Stateless means every call carries what it needs: the signing certificate\n * (an A1 `.pfx` as base64 and its password) and, for an NFC-e, the CSC. The\n * service keeps nothing between calls, writes nothing to disk and never logs\n * any of the three.\n */\n\nimport type { SaleForDocument } from \"../sale/types\";\n\n/** The path segment of a document model: `nfe` is model 55, `nfce` model 65. */\nexport type DocumentModelPath = \"nfe\" | \"nfce\";\n\n/** The SEFAZ environment (`tpAmb` 2 and 1). */\nexport type SefazEnvironment = \"homologacao\" | \"producao\";\n\n/** The A1 certificate, per call. */\nexport interface SigningCertificate {\n /** The `.pfx` (PKCS#12) bytes, base64. */\n readonly pfxBase64: string;\n readonly password: string;\n}\n\n/** The NFC-e's Código de Segurança do Contribuinte and its id. */\nexport interface Csc {\n readonly id: string;\n readonly token: string;\n}\n\ninterface Authenticated {\n readonly environment: SefazEnvironment;\n readonly certificate: SigningCertificate;\n}\n\n/**\n * `POST /<model>/issue`: builds, signs and transmits. `csc` is required for\n * `nfce` and refused for `nfe`.\n */\nexport interface IssueRequest extends Authenticated {\n readonly csc: Csc | null;\n readonly document: SaleForDocument;\n}\n\n/** Why and since when the caixa issues offline (`dhCont`, `xJust`). */\nexport interface ContingencyEntry {\n /** ISO 8601 with the UTC offset. */\n readonly since: string;\n /** 15–256 characters. */\n readonly reason: string;\n}\n\n/** `POST /nfce/sign-contingency`: builds and signs with `tpEmis = 9`; does NOT transmit. */\nexport interface SignContingencyRequest extends IssueRequest {\n readonly contingency: ContingencyEntry;\n}\n\n/** `POST /<model>/transmit`: an already signed XML (from `/nfce/sign-contingency`, say). */\nexport interface TransmitRequest extends Authenticated {\n readonly signedXml: string;\n}\n\n/** `POST /<model>/cancel`: the UF and the issuer come from the access key. */\nexport interface CancelRequest extends Authenticated {\n readonly accessKey: string;\n /** The authorisation protocol (`nProt`). */\n readonly protocol: string;\n /** 15–255 characters. */\n readonly reason: string;\n}\n\n/**\n * `POST /nfce/cancel-substitution`: the NFC-e \"cancelamento por substituição\"\n * (event 110112) — an online NFC-e found authorised after its sale was issued\n * again in contingency, cancelled naming the substitute. Answers as `/cancel`.\n */\nexport interface CancelBySubstitutionRequest extends CancelRequest {\n /** The contingency document that replaced it (`chNFeRef`). */\n readonly substituteAccessKey: string;\n}\n\n/** `POST /<model>/lookup`. */\nexport interface LookupRequest extends Authenticated {\n readonly accessKey: string;\n}\n\n/** `POST /inutilize`: voids a range of unused numbers. */\nexport interface InutilizeRequest extends Authenticated {\n readonly model: DocumentModelPath;\n readonly uf: string;\n readonly cnpj: string;\n /** The year of the numbers, four digits. */\n readonly year: number;\n readonly series: number;\n readonly from: number;\n readonly to: number;\n /** 15–255 characters. */\n readonly reason: string;\n}\n\n/** What SEFAZ answered, as the service read it. */\nexport interface SefazAnswer {\n /** `cStat`. */\n readonly statusCode: string;\n /** `xMotivo`. */\n readonly statusReason: string;\n /** The SOAP body SEFAZ returned, verbatim. */\n readonly sefazReply: string;\n}\n\n/**\n * `/issue` and `/transmit`: SEFAZ's final answer on the document.\n *\n * - `AUTHORIZED` (100, 120, 150).\n * - `DENIED` (110, 301, 302, 303): a denial of use. The number is SPENT and\n * the denial is kept like an authorisation (its `authorizedXml` carries the\n * denial protocol); it is not a rejection, which leaves the number free.\n *\n * A retried call answers the same: SEFAZ's \"already authorised\" (204) and\n * \"already denied\" (205), and a request sent with no answer, are settled by\n * looking the key up, so a retry never turns an authorised document into an error.\n */\nexport interface IssuedDocument extends SefazAnswer {\n readonly status: \"AUTHORIZED\" | \"DENIED\";\n readonly accessKey: string;\n readonly protocol: string;\n /** `dhRecbto` of the protocol. */\n readonly authorizedAt: string;\n readonly signedXml: string;\n /** The `nfeProc`: the signed XML with its protocol (of authorisation or of denial), what is stored. */\n readonly authorizedXml: string;\n}\n\n/** `/nfce/sign-contingency`. */\nexport interface ContingencySignedDocument {\n readonly status: \"SIGNED\";\n readonly accessKey: string;\n /** Carries `tpEmis = 9` and the QR code; transmit it later through `/nfce/transmit`. */\n readonly signedXml: string;\n}\n\n/**\n * `/cancel`. A retried cancel (SEFAZ's 218 \"already cancelled\" or 573\n * \"duplicate event\", or a cancel sent with no answer) is settled by looking\n * the key up, and answers CANCELLED with what the lookup carries: the event's\n * protocol and XML when SEFAZ returns them, `null` when it does not.\n */\nexport interface CancelledDocument extends SefazAnswer {\n readonly status: \"CANCELLED\";\n readonly accessKey: string;\n /** The event's protocol. */\n readonly protocol: string | null;\n readonly registeredAt: string | null;\n /** The `procEventoNFe`. */\n readonly eventXml: string | null;\n}\n\n/** `/lookup`: what SEFAZ knows of the key. `NOT_FOUND` is an answer, not an error. */\nexport interface LookedUpDocument extends SefazAnswer {\n readonly status: \"AUTHORIZED\" | \"CANCELLED\" | \"DENIED\" | \"NOT_FOUND\";\n readonly accessKey: string;\n readonly protocol: string | null;\n}\n\n/**\n * `/inutilize`. A retried inutilização (563, \"a request for the same range\n * already exists\") answers INUTILIZED too, with `protocol` and\n * `inutilizationXml` `null`: the range is void at SEFAZ, and SEFAZ offers no\n * query that would return the first protocol.\n */\nexport interface InutilizedRange extends SefazAnswer {\n readonly status: \"INUTILIZED\";\n readonly protocol: string | null;\n readonly registeredAt: string | null;\n /** The signed request with its reply (`procInutNFe`). */\n readonly inutilizationXml: string | null;\n}\n\n/**\n * How a failed call is classified — the issuer port's own classes:\n *\n * - `REJECTED`: SEFAZ refused the document or the event; `code` is its `cStat`.\n * The number is NOT spent (a denial is not an error: it answers `DENIED`).\n * - `RETRYABLE`: try the same call again later. When `outcomeUnknown` is true\n * the request went out and neither it nor the lookup that would settle it\n * was answered: look the key up before sending it again.\n * - `CONTINGENCY`: SEFAZ is unavailable. For an NFC-e being issued, nothing\n * reached SEFAZ (or the lookup after an unanswered request could not reach\n * it): go offline through `/nfce/sign-contingency`. For an NF-e (model 55)\n * the service has no offline path (no SVC, no EPEC): treat it as RETRYABLE.\n * - `AUTH`: the certificate is unreadable, the password wrong, the certificate\n * expired, or SEFAZ refused it.\n * - `INVALID`: the request itself is malformed (the schema, a missing CSC, an\n * XML the layout refuses, a document the layout version cannot express).\n * Fix the input; never retry it as is.\n * - `INTERNAL`: a defect of the service, or a 4xx other than 403/408/429 from\n * the verified SEFAZ host (a wrong web-service address). A retry would only repeat it.\n */\nexport type SidecarErrorClass = \"REJECTED\" | \"RETRYABLE\" | \"CONTINGENCY\" | \"AUTH\" | \"INVALID\" | \"INTERNAL\";\n\nexport const SIDECAR_ERROR_CLASSES: readonly SidecarErrorClass[] = [\n \"REJECTED\",\n \"RETRYABLE\",\n \"CONTINGENCY\",\n \"AUTH\",\n \"INVALID\",\n \"INTERNAL\",\n];\n\n/** The body of every non-2xx answer. */\nexport interface SidecarErrorBody {\n readonly error: {\n readonly class: SidecarErrorClass;\n /**\n * The SEFAZ `cStat` when SEFAZ answered (always for `REJECTED`); for\n * `INVALID`, a named code where one applies (`NT_2026_008_NOT_SUPPORTED`:\n * a document issued on or after 2027-01-01, which needs NT 2026.008's\n * `vProdLiq`); `null` otherwise.\n */\n readonly code: string | null;\n readonly message: string;\n /** Per-field problems of an `INVALID` request. */\n readonly details: readonly string[];\n /** When the call got as far as building and signing: keep it, the key is now spoken for. */\n readonly accessKey: string | null;\n readonly signedXml: string | null;\n readonly sefazReply: string | null;\n /** The request went out and its outcome is still unknown: look the key up before sending it again. */\n readonly outcomeUnknown: boolean;\n };\n}\n\n/** `GET /health`. */\nexport interface SidecarHealth {\n readonly status: \"ok\";\n /** The libraries the service runs, by name, with the version installed. */\n readonly libraries: Readonly<Record<string, string>>;\n /** The schema package the NF-e layout is validated against. */\n readonly nfeSchemas: string;\n /** Whether SEFAZ's server certificate is verified; `false` only with `FISCAL_SEFAZ_TLS_VERIFY=off`. */\n readonly sefazTlsVerify: boolean;\n}\n"],"mappings":";AAyMO,IAAM,wBAAsD;AAAA,EACjE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":[]}
@@ -0,0 +1,85 @@
1
+ import {
2
+ FISCAL_CERTIFICATE_EXPIRING
3
+ } from "./chunk-27B4HNO6.js";
4
+ import {
5
+ FISCAL_MANAGE
6
+ } from "./chunk-3SDXLSG4.js";
7
+ import {
8
+ __name
9
+ } from "./chunk-7QVYU63E.js";
10
+
11
+ // src/jobs.ts
12
+ var FISCAL_JOB_LEASE_MS = 30 * 6e4;
13
+ var FISCAL_WORST_STEP_MS = 2 * 9e4;
14
+ var FISCAL_SWEEP_BATCH = Math.floor(FISCAL_JOB_LEASE_MS / FISCAL_WORST_STEP_MS);
15
+ var CERTIFICATE_WARNING_DAYS = [30, 15, 7, 3, 1];
16
+ var DAY_MS = 864e5;
17
+ function report(name, result, logger) {
18
+ if (result.advanced.length > 0 || result.failures.length > 0) {
19
+ logger.info(`fiscal ${name}: ${result.advanced.length} advanced, ${result.failures.length} failed`);
20
+ }
21
+ for (const failure of result.failures) logger.error(`fiscal ${name} failed for document ${failure.documentId}: ${failure.message}`);
22
+ }
23
+ __name(report, "report");
24
+ function daysLeft(expiresAt, now) {
25
+ return Math.ceil((Date.parse(expiresAt) - now.getTime()) / DAY_MS) || 0;
26
+ }
27
+ __name(daysLeft, "daysLeft");
28
+ var FISCAL_JOBS = {
29
+ namespace: "fiscal",
30
+ blueprints: {
31
+ sweep: {
32
+ name: "sweep",
33
+ schedule: { pattern: "*/5 * * * *" },
34
+ /** The batch is sized so a run of worst-case steps ends inside this lease. */
35
+ lease: { ttlMs: FISCAL_JOB_LEASE_MS },
36
+ /** A missed run is caught up by the next tick. */
37
+ attempts: 1,
38
+ async handle(_payload, deps, context) {
39
+ report("sweep", await deps.documents.sweep(FISCAL_SWEEP_BATCH), context.logger);
40
+ }
41
+ },
42
+ transmitContingency: {
43
+ name: "transmit-contingency",
44
+ schedule: { pattern: "2-59/5 * * * *" },
45
+ lease: { ttlMs: FISCAL_JOB_LEASE_MS },
46
+ attempts: 1,
47
+ async handle(_payload, deps, context) {
48
+ report("transmit-contingency", await deps.documents.transmitContingency(FISCAL_SWEEP_BATCH), context.logger);
49
+ }
50
+ },
51
+ certificateExpiry: {
52
+ name: "certificate-expiry",
53
+ schedule: { pattern: "7 10 * * *" },
54
+ lease: { ttlMs: 10 * 6e4 },
55
+ attempts: 1,
56
+ async handle(_payload, deps, context) {
57
+ const now = deps.now();
58
+ const horizon = new Date(now.getTime() + (Math.max(...CERTIFICATE_WARNING_DAYS) + 1) * DAY_MS).toISOString();
59
+ const profiles = await deps.store.listExpiringCertificates(horizon);
60
+ let told = 0;
61
+ for (const profile of profiles) {
62
+ const days = daysLeft(profile.certificateExpiresAt ?? "", now);
63
+ if (days > 0 && !CERTIFICATE_WARNING_DAYS.includes(days)) continue;
64
+ await deps.notify.emit({
65
+ type: FISCAL_CERTIFICATE_EXPIRING,
66
+ recipient: { tenantId: profile.ownerId, permission: FISCAL_MANAGE },
67
+ payload: { ownerId: profile.ownerId, expiresAt: profile.certificateExpiresAt, daysLeft: days }
68
+ });
69
+ told += 1;
70
+ }
71
+ if (told > 0) context.logger.info(`fiscal certificate-expiry: ${told} owner(s) told`);
72
+ }
73
+ }
74
+ }
75
+ };
76
+
77
+ export {
78
+ FISCAL_JOB_LEASE_MS,
79
+ FISCAL_WORST_STEP_MS,
80
+ FISCAL_SWEEP_BATCH,
81
+ CERTIFICATE_WARNING_DAYS,
82
+ daysLeft,
83
+ FISCAL_JOBS
84
+ };
85
+ //# sourceMappingURL=chunk-HQ2NXSTX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/jobs.ts"],"sourcesContent":["/**\n * `@12-apps/fiscal/jobs` — the package's job blueprints, deps left open (the\n * wiring contract's `jobs` capability; `@12-apps/wiring` is a type-only\n * dependency).\n *\n * - `sweep` (every 5 minutes): re-issues PENDING and SUBMITTED documents left\n * stale, and settles every number SEFAZ never used (a lookup, a cancel or\n * an inutilization), so a series has no unexplained gap.\n * - `transmit-contingency` (every 5 minutes, offset): transmits the documents\n * signed offline, and warns the owner of every one still offline after 20\n * hours (SEFAZ's deadline is 24).\n * - `certificate-expiry` (daily, 10:07 UTC): tells each owner whose A1 expires\n * within 30 days, on the 30th, 15th, 7th, 3rd and last day, and every day\n * once it has expired.\n *\n * The host binds the service, its store and its notifier, nothing more.\n */\n\nimport type { JobsContribution } from \"@12-apps/wiring\";\n\nimport { FISCAL_CERTIFICATE_EXPIRING, type FiscalNotifyPort } from \"./documents/context\";\nimport type { FiscalStore } from \"./documents/ports\";\nimport type { FiscalDocuments, SweepReport } from \"./documents/service\";\nimport { FISCAL_MANAGE } from \"./manifest/permissions\";\n\nexport interface FiscalJobDeps {\n readonly documents: Pick<FiscalDocuments, \"sweep\" | \"transmitContingency\">;\n readonly store: Pick<FiscalStore, \"listExpiringCertificates\">;\n readonly notify: FiscalNotifyPort;\n readonly now: () => Date;\n}\n\n/** The single-flight lease a sweep or a transmission run holds. */\nexport const FISCAL_JOB_LEASE_MS = 30 * 60_000;\n\n/**\n * The worst one document can cost a run: an issue call and the offline\n * signing after it, each bounded by the issuer's timeout (90 s recommended\n * for the sidecar adapter, whose own SEFAZ call gets 50 s and a lookup).\n */\nexport const FISCAL_WORST_STEP_MS = 2 * 90_000;\n\n/**\n * At most this many documents per run, derived so that a run of the worst\n * steps still ends inside its lease: a second run can never overlap the\n * first. A backlog drains over several five-minute runs.\n */\nexport const FISCAL_SWEEP_BATCH = Math.floor(FISCAL_JOB_LEASE_MS / FISCAL_WORST_STEP_MS);\n\n/** The days before expiry the owner is told; after expiry, every day. */\nexport const CERTIFICATE_WARNING_DAYS: readonly number[] = [30, 15, 7, 3, 1];\n\nconst DAY_MS = 86_400_000;\n\nfunction report(name: string, result: SweepReport, logger: { info(m: string): void; error(m: string): void }): void {\n if (result.advanced.length > 0 || result.failures.length > 0) {\n logger.info(`fiscal ${name}: ${result.advanced.length} advanced, ${result.failures.length} failed`);\n }\n for (const failure of result.failures) logger.error(`fiscal ${name} failed for document ${failure.documentId}: ${failure.message}`);\n}\n\n/** Whole days from `now` to `expiresAt`, rounded up: 0 is \"today\", negative is \"expired\". */\nexport function daysLeft(expiresAt: string, now: Date): number {\n // `|| 0` turns the -0 of a part-day already gone into \"today\".\n return Math.ceil((Date.parse(expiresAt) - now.getTime()) / DAY_MS) || 0;\n}\n\nexport const FISCAL_JOBS = {\n namespace: \"fiscal\",\n blueprints: {\n sweep: {\n name: \"sweep\",\n schedule: { pattern: \"*/5 * * * *\" },\n /** The batch is sized so a run of worst-case steps ends inside this lease. */\n lease: { ttlMs: FISCAL_JOB_LEASE_MS },\n /** A missed run is caught up by the next tick. */\n attempts: 1,\n async handle(_payload, deps, context) {\n report(\"sweep\", await deps.documents.sweep(FISCAL_SWEEP_BATCH), context.logger);\n },\n },\n transmitContingency: {\n name: \"transmit-contingency\",\n schedule: { pattern: \"2-59/5 * * * *\" },\n lease: { ttlMs: FISCAL_JOB_LEASE_MS },\n attempts: 1,\n async handle(_payload, deps, context) {\n report(\"transmit-contingency\", await deps.documents.transmitContingency(FISCAL_SWEEP_BATCH), context.logger);\n },\n },\n certificateExpiry: {\n name: \"certificate-expiry\",\n schedule: { pattern: \"7 10 * * *\" },\n lease: { ttlMs: 10 * 60_000 },\n attempts: 1,\n async handle(_payload, deps, context) {\n const now = deps.now();\n const horizon = new Date(now.getTime() + (Math.max(...CERTIFICATE_WARNING_DAYS) + 1) * DAY_MS).toISOString();\n const profiles = await deps.store.listExpiringCertificates(horizon);\n let told = 0;\n for (const profile of profiles) {\n const days = daysLeft(profile.certificateExpiresAt ?? \"\", now);\n if (days > 0 && !CERTIFICATE_WARNING_DAYS.includes(days)) continue;\n await deps.notify.emit({\n type: FISCAL_CERTIFICATE_EXPIRING,\n recipient: { tenantId: profile.ownerId, permission: FISCAL_MANAGE },\n payload: { ownerId: profile.ownerId, expiresAt: profile.certificateExpiresAt, daysLeft: days },\n });\n told += 1;\n }\n if (told > 0) context.logger.info(`fiscal certificate-expiry: ${told} owner(s) told`);\n },\n },\n },\n} satisfies JobsContribution<FiscalJobDeps>;\n"],"mappings":";;;;;;;;;;;AAiCO,IAAM,sBAAsB,KAAK;AAOjC,IAAM,uBAAuB,IAAI;AAOjC,IA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