@12-apps/fiscal 1.2.0 → 1.3.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 (35) hide show
  1. package/README.md +14 -0
  2. package/dist/{chunk-G3V7IYNF.js → chunk-GGYJPFBJ.js} +2 -2
  3. package/dist/{chunk-N5DCKYFR.js → chunk-GKT3X5CF.js} +2 -2
  4. package/dist/{chunk-2LBQRYPV.js → chunk-H33BK623.js} +1 -1
  5. package/dist/{chunk-2LBQRYPV.js.map → chunk-H33BK623.js.map} +1 -1
  6. package/dist/{chunk-5S2PJHAE.js → chunk-MEBG7FGG.js} +2 -2
  7. package/dist/{chunk-WTGASIZE.js → chunk-MGTROA7K.js} +2 -2
  8. package/dist/{chunk-NVRYAAQ4.js → chunk-V6G2OFLA.js} +6 -5
  9. package/dist/chunk-V6G2OFLA.js.map +1 -0
  10. package/dist/{context-ChnWR4Kb.d.ts → context-yc1C2__K.d.ts} +1 -1
  11. package/dist/danfe/index.js +2 -2
  12. package/dist/documents/index.d.ts +12 -6
  13. package/dist/documents/index.js +54 -3
  14. package/dist/documents/index.js.map +1 -1
  15. package/dist/http.d.ts +4 -3
  16. package/dist/http.js +4 -4
  17. package/dist/issuer/index.d.ts +2 -2
  18. package/dist/jobs.d.ts +3 -3
  19. package/dist/jobs.js +3 -3
  20. package/dist/manifest/server.d.ts +3 -3
  21. package/dist/manifest/server.js +6 -6
  22. package/dist/notifications.d.ts +2 -2
  23. package/dist/notifications.js +2 -2
  24. package/dist/{port-DpRFK56U.d.ts → port-B1-ipIL4.d.ts} +1 -1
  25. package/dist/{service-KTjH7AxW.d.ts → service-BB9lWdyg.d.ts} +30 -3
  26. package/package.json +1 -1
  27. package/src/documents/errors.ts +7 -1
  28. package/src/documents/index.ts +2 -2
  29. package/src/documents/service.ts +94 -0
  30. package/src/http.ts +1 -0
  31. package/dist/chunk-NVRYAAQ4.js.map +0 -1
  32. /package/dist/{chunk-G3V7IYNF.js.map → chunk-GGYJPFBJ.js.map} +0 -0
  33. /package/dist/{chunk-N5DCKYFR.js.map → chunk-GKT3X5CF.js.map} +0 -0
  34. /package/dist/{chunk-5S2PJHAE.js.map → chunk-MEBG7FGG.js.map} +0 -0
  35. /package/dist/{chunk-WTGASIZE.js.map → chunk-MGTROA7K.js.map} +0 -0
package/README.md CHANGED
@@ -210,6 +210,20 @@ nothing leaves `REJECTED`, `DENIED`, `REPLACED` or `CANCELLED` for `AUTHORIZED`
210
210
  payment; the package checks neither. `isValidAccessKey` checks a typed key: 44
211
211
  characters, the CNPJ inside it alphanumeric or not, the modulo-11 check
212
212
  digit. A sale without the two fields is issued exactly as before.
213
+ - **Cancel, or the return when it is too late.** `cancelOrReturn({ ownerId,
214
+ documentId, reason, returnPointId })` cancels an authorised document; when
215
+ SEFAZ refuses the cancel as late (`LATE_CANCEL_CODES`, cStat 501) it issues
216
+ the buyer's return instead, an NF-e of entry on the NF-e point
217
+ `returnPointId`, from the sale the host's `SaleSource` answers for the
218
+ document's subject with `model: "NFE"` — which must quote the document's
219
+ key, or it is refused before a number is drawn. The document stays
220
+ AUTHORIZED beside its return. It answers `CANCELLED`, `RETURNED` (the
221
+ return may still be SUBMITTED; the sweep settles it like any document) or
222
+ `REFUSED` (the issuer refused the cancel for another reason; nothing
223
+ changed); a document that is not AUTHORIZED throws `TRANSITION_REFUSED`, and
224
+ a late NF-e (not an NFC-e) throws `RETURN_OF_NFCE_ONLY`. It is idempotent: a
225
+ document already cancelled, or already answered by a live return, is
226
+ answered with no call to the issuer.
213
227
  - **An authorised document always has its XML.** A lookup that finds a
214
228
  SUBMITTED document authorised joins the signed XML the service returned to
215
229
  the lookup's `protNFe`; without both, the document stays SUBMITTED (its
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-XQGW5HUG.js";
4
4
  import {
5
5
  FiscalDocumentError
6
- } from "./chunk-2LBQRYPV.js";
6
+ } from "./chunk-H33BK623.js";
7
7
  import {
8
8
  __name
9
9
  } from "./chunk-7QVYU63E.js";
@@ -189,4 +189,4 @@ export {
189
189
  parseCertificateUpload,
190
190
  parseIssuingPointInput
191
191
  };
192
- //# sourceMappingURL=chunk-G3V7IYNF.js.map
192
+ //# sourceMappingURL=chunk-GGYJPFBJ.js.map
@@ -7,7 +7,7 @@ import {
7
7
  } from "./chunk-3SDXLSG4.js";
8
8
  import {
9
9
  FiscalDocumentError
10
- } from "./chunk-2LBQRYPV.js";
10
+ } from "./chunk-H33BK623.js";
11
11
  import {
12
12
  __name
13
13
  } from "./chunk-7QVYU63E.js";
@@ -607,4 +607,4 @@ export {
607
607
  assertReason,
608
608
  FiscalContext
609
609
  };
610
- //# sourceMappingURL=chunk-N5DCKYFR.js.map
610
+ //# sourceMappingURL=chunk-GKT3X5CF.js.map
@@ -18,4 +18,4 @@ var FiscalDocumentError = class extends Error {
18
18
  export {
19
19
  FiscalDocumentError
20
20
  };
21
- //# sourceMappingURL=chunk-2LBQRYPV.js.map
21
+ //# sourceMappingURL=chunk-H33BK623.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/documents/errors.ts"],"sourcesContent":["/**\n * Every refusal the document module makes, as a typed error with a `code`.\n * A message never carries a certificate, a password or a CSC: the module\n * never holds one long enough to quote it.\n */\n\nexport type FiscalDocumentErrorCode =\n /** The state machine has no such transition from the document's state. */\n | \"TRANSITION_REFUSED\"\n /** An input is missing, malformed or out of range. */\n | \"INVALID_INPUT\"\n /** No emitter profile, issuing point or document under that id. */\n | \"NOT_FOUND\"\n /** The profile does not let the package issue (`documentPolicy`), or lacks what issuing needs. */\n | \"NOT_ISSUABLE\"\n /** The signing identity is declared but not built yet (`PLATFORM`). */\n | \"NOT_SUPPORTED\"\n /** A series' counter passed 999 999 999. */\n | \"SERIES_EXHAUSTED\"\n /** Another worker advanced the document first; re-read it. */\n | \"CONFLICT\"\n /** The subject already has a live document of that model (the per-subject guard). */\n | \"SUBJECT_HAS_DOCUMENT\"\n /** The document's state has no paper to print (only AUTHORIZED, or CONTINGENCY awaiting transmission). */\n | \"NOT_PRINTABLE\"\n /**\n * A resend of a rejected contingency NFC-e would change what the buyer's\n * DANFE prints and its QR encodes (the total, the buyer's document): such a\n * sale needs a new note, issued by a person.\n */\n | \"RESEND_CHANGES_PRINTED_FIELDS\"\n /** A `RETURN` quotes no document (`referencedDocuments` is absent or empty). */\n | \"RETURN_NEEDS_REFERENCE\"\n /**\n * A `RETURN` asked of an NFC-e. An NFC-e has no return purpose: the return is\n * an NF-e (model 55) of entry that references the NFC-e's key.\n */\n | \"RETURN_ON_NFCE\";\n\nexport class FiscalDocumentError extends Error {\n readonly code: FiscalDocumentErrorCode;\n\n constructor(code: FiscalDocumentErrorCode, message: string) {\n super(`[fiscal/documents] ${code}: ${message}`);\n this.name = \"FiscalDocumentError\";\n this.code = code;\n }\n}\n"],"mappings":";;;;;AAuCO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAvC/C,OAuC+C;AAAA;AAAA;AAAA,EACpC;AAAA,EAET,YAAY,MAA+B,SAAiB;AAC1D,UAAM,sBAAsB,IAAI,KAAK,OAAO,EAAE;AAC9C,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/documents/errors.ts"],"sourcesContent":["/**\n * Every refusal the document module makes, as a typed error with a `code`.\n * A message never carries a certificate, a password or a CSC: the module\n * never holds one long enough to quote it.\n */\n\nexport type FiscalDocumentErrorCode =\n /** The state machine has no such transition from the document's state. */\n | \"TRANSITION_REFUSED\"\n /** An input is missing, malformed or out of range. */\n | \"INVALID_INPUT\"\n /** No emitter profile, issuing point or document under that id. */\n | \"NOT_FOUND\"\n /** The profile does not let the package issue (`documentPolicy`), or lacks what issuing needs. */\n | \"NOT_ISSUABLE\"\n /** The signing identity is declared but not built yet (`PLATFORM`). */\n | \"NOT_SUPPORTED\"\n /** A series' counter passed 999 999 999. */\n | \"SERIES_EXHAUSTED\"\n /** Another worker advanced the document first; re-read it. */\n | \"CONFLICT\"\n /** The subject already has a live document of that model (the per-subject guard). */\n | \"SUBJECT_HAS_DOCUMENT\"\n /** The document's state has no paper to print (only AUTHORIZED, or CONTINGENCY awaiting transmission). */\n | \"NOT_PRINTABLE\"\n /**\n * A resend of a rejected contingency NFC-e would change what the buyer's\n * DANFE prints and its QR encodes (the total, the buyer's document): such a\n * sale needs a new note, issued by a person.\n */\n | \"RESEND_CHANGES_PRINTED_FIELDS\"\n /** A `RETURN` quotes no document (`referencedDocuments` is absent or empty). */\n | \"RETURN_NEEDS_REFERENCE\"\n /**\n * A `RETURN` asked of an NFC-e. An NFC-e has no return purpose: the return is\n * an NF-e (model 55) of entry that references the NFC-e's key.\n */\n | \"RETURN_ON_NFCE\"\n /**\n * `cancelOrReturn` past SEFAZ's window on a document that is not an NFC-e:\n * the buyer's return NF-e of entry answers a consumer's NFC-e only; an NF-e\n * past its window is the issuer's own correction, not this path's.\n */\n | \"RETURN_OF_NFCE_ONLY\";\n\nexport class FiscalDocumentError extends Error {\n readonly code: FiscalDocumentErrorCode;\n\n constructor(code: FiscalDocumentErrorCode, message: string) {\n super(`[fiscal/documents] ${code}: ${message}`);\n this.name = \"FiscalDocumentError\";\n this.code = code;\n }\n}\n"],"mappings":";;;;;AA6CO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EA7C/C,OA6C+C;AAAA;AAAA;AAAA,EACpC;AAAA,EAET,YAAY,MAA+B,SAAiB;AAC1D,UAAM,sBAAsB,IAAI,KAAK,OAAO,EAAE;AAC9C,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  FISCAL_CERTIFICATE_EXPIRING
3
- } from "./chunk-N5DCKYFR.js";
3
+ } from "./chunk-GKT3X5CF.js";
4
4
  import {
5
5
  FISCAL_MANAGE
6
6
  } from "./chunk-3SDXLSG4.js";
@@ -82,4 +82,4 @@ export {
82
82
  daysLeft,
83
83
  FISCAL_JOBS
84
84
  };
85
- //# sourceMappingURL=chunk-5S2PJHAE.js.map
85
+ //# sourceMappingURL=chunk-MEBG7FGG.js.map
@@ -6,7 +6,7 @@ import {
6
6
  } from "./chunk-PNTKG3DZ.js";
7
7
  import {
8
8
  FiscalDocumentError
9
- } from "./chunk-2LBQRYPV.js";
9
+ } from "./chunk-H33BK623.js";
10
10
  import {
11
11
  __name
12
12
  } from "./chunk-7QVYU63E.js";
@@ -244,4 +244,4 @@ export {
244
244
  wrap,
245
245
  renderDanfeNfce
246
246
  };
247
- //# sourceMappingURL=chunk-WTGASIZE.js.map
247
+ //# sourceMappingURL=chunk-MGTROA7K.js.map
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  renderDanfeNfce
3
- } from "./chunk-WTGASIZE.js";
3
+ } from "./chunk-MGTROA7K.js";
4
4
  import {
5
5
  parseCertificateUpload,
6
6
  parseIssuingPointInput,
7
7
  parseProfileInput,
8
8
  viewOf
9
- } from "./chunk-G3V7IYNF.js";
9
+ } from "./chunk-GGYJPFBJ.js";
10
10
  import {
11
11
  FISCAL_DOCUMENT_MODELS
12
12
  } from "./chunk-XQGW5HUG.js";
@@ -18,7 +18,7 @@ import {
18
18
  } from "./chunk-3SDXLSG4.js";
19
19
  import {
20
20
  FiscalDocumentError
21
- } from "./chunk-2LBQRYPV.js";
21
+ } from "./chunk-H33BK623.js";
22
22
  import {
23
23
  __name
24
24
  } from "./chunk-7QVYU63E.js";
@@ -36,7 +36,8 @@ var FISCAL_ERROR_STATUS = {
36
36
  NOT_PRINTABLE: 409,
37
37
  RESEND_CHANGES_PRINTED_FIELDS: 422,
38
38
  RETURN_NEEDS_REFERENCE: 422,
39
- RETURN_ON_NFCE: 422
39
+ RETURN_ON_NFCE: 422,
40
+ RETURN_OF_NFCE_ONLY: 422
40
41
  };
41
42
  var PRINTABLE = /* @__PURE__ */ new Set(["AUTHORIZED", "CONTINGENCY"]);
42
43
  var ok = /* @__PURE__ */ __name((data, status = 200) => ({ status, body: { data } }), "ok");
@@ -209,4 +210,4 @@ export {
209
210
  FISCAL_ERROR_STATUS,
210
211
  createApiFiscal
211
212
  };
212
- //# sourceMappingURL=chunk-NVRYAAQ4.js.map
213
+ //# sourceMappingURL=chunk-V6G2OFLA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/http.ts"],"sourcesContent":["/**\n * `createApiFiscal` — the fiscal HTTP surface as framework-neutral route\n * descriptors (the wiring contract's `http` capability, restated here\n * structurally: this package imports nothing from the contract at runtime,\n * and its manifest suite pins the twins).\n *\n * The package owns the paths, the bodies it reads (`./documents/profile-input`,\n * unknown keys refused), the `{ data }` envelope, the permission each route\n * needs and the status a refusal earns ({@link FISCAL_ERROR_STATUS}). The host\n * owns resolving WHO is calling into the opaque `ownerId` of its tenant, the\n * guards that check the declared permission, and every word a person reads:\n * an error answers a `code` for the host to word, never a sentence for a user.\n *\n * Nothing secret leaves: the profile answers `hasCertificate` / `hasCsc`, never\n * a ciphertext, and the certificate upload answers the profile view.\n */\n\nimport { type DanfeNfceLabels } from \"./danfe/labels\";\nimport { type PaperWidth, renderDanfeNfce } from \"./danfe/render\";\nimport { FiscalDocumentError, type FiscalDocumentErrorCode } from \"./documents/errors\";\nimport type { DocumentStorage } from \"./documents/ports\";\nimport { parseCertificateUpload, parseIssuingPointInput, parseProfileInput } from \"./documents/profile-input\";\nimport { viewOf } from \"./documents/profile\";\nimport type { FiscalDocuments } from \"./documents/service\";\nimport { FISCAL_DOCUMENT_MODELS, type FiscalDocumentModel } from \"./documents/types\";\nimport { FISCAL_CANCEL, FISCAL_ISSUE, FISCAL_MANAGE, FISCAL_READ } from \"./manifest/permissions\";\n\n/** The caller, as the host's adapter resolved it. */\nexport interface FiscalHttpActor {\n /** The emitter profile's owner: the host's tenant, mapped to an opaque id. */\n readonly ownerId: string;\n}\n\n/** Structural twin of the wiring contract's `WireRequest<FiscalHttpActor>`. */\nexport interface FiscalHttpRequest {\n actor: FiscalHttpActor;\n params: Record<string, string | undefined>;\n query: Record<string, string | undefined>;\n body?: unknown;\n}\n\n/** Structural twin of the wiring contract's `WireResponse`. */\nexport interface FiscalHttpResponse {\n status: number;\n body: unknown;\n}\n\n/** Structural twin of the wiring contract's `WireRoute<FiscalHttpActor>`. */\nexport interface FiscalRoute {\n method: \"GET\" | \"POST\" | \"PUT\";\n path: string;\n permission: string;\n handle(request: FiscalHttpRequest): Promise<FiscalHttpResponse>;\n}\n\nexport interface FiscalApiConfig {\n readonly documents: FiscalDocuments;\n /** Where the XMLs are, to render a DANFE from. */\n readonly storage: DocumentStorage;\n /** The DANFE's words: the host's, or `@12-apps/fiscal/danfe/pt-BR`. */\n readonly danfeLabels: DanfeNfceLabels;\n}\n\nexport const FISCAL_ERROR_STATUS = {\n INVALID_INPUT: 400,\n NOT_FOUND: 404,\n NOT_ISSUABLE: 409,\n NOT_SUPPORTED: 501,\n TRANSITION_REFUSED: 409,\n SERIES_EXHAUSTED: 409,\n CONFLICT: 409,\n SUBJECT_HAS_DOCUMENT: 409,\n NOT_PRINTABLE: 409,\n RESEND_CHANGES_PRINTED_FIELDS: 422,\n RETURN_NEEDS_REFERENCE: 422,\n RETURN_ON_NFCE: 422,\n RETURN_OF_NFCE_ONLY: 422,\n} as const satisfies Record<FiscalDocumentErrorCode, number>;\n\n/**\n * The states with paper: an authorised document, and one signed offline and\n * not yet transmitted (its DANFE is what the buyer takes). A denied,\n * cancelled, rejected or replaced document is not a valid DANFE.\n */\nconst PRINTABLE = new Set([\"AUTHORIZED\", \"CONTINGENCY\"]);\n\nconst ok = (data: unknown, status = 200): FiscalHttpResponse => ({ status, body: { data } });\n\nasync function answering(run: () => Promise<FiscalHttpResponse>): Promise<FiscalHttpResponse> {\n try {\n return await run();\n } catch (error) {\n if (error instanceof FiscalDocumentError) {\n return { status: FISCAL_ERROR_STATUS[error.code], body: { error: error.code, message: error.message } };\n }\n throw error;\n }\n}\n\nfunction record(body: unknown): Record<string, unknown> {\n if (body === null || typeof body !== \"object\" || Array.isArray(body)) {\n throw new FiscalDocumentError(\"INVALID_INPUT\", \"the body must be an object.\");\n }\n return body as Record<string, unknown>;\n}\n\nfunction stringField(body: Record<string, unknown>, key: string): string {\n const value = body[key];\n if (typeof value !== \"string\" || value === \"\") throw new FiscalDocumentError(\"INVALID_INPUT\", `${key} is required.`);\n return value;\n}\n\nfunction param(request: FiscalHttpRequest, key: string): string {\n const value = request.params[key];\n if (value === undefined || value === \"\") throw new FiscalDocumentError(\"INVALID_INPUT\", `${key} is required.`);\n return value;\n}\n\nconst ISSUE_KEYS = new Set([\"subjectId\", \"issuingPointId\", \"model\", \"offline\"]);\n\nfunction issueBody(body: unknown): { subjectId: string; issuingPointId: string; model: FiscalDocumentModel; offline: boolean } {\n const fields = record(body);\n const unknown = Object.keys(fields).filter((key) => !ISSUE_KEYS.has(key));\n if (unknown.length > 0) throw new FiscalDocumentError(\"INVALID_INPUT\", `unknown keys: ${unknown.join(\", \")}.`);\n const model = fields[\"model\"];\n if (!FISCAL_DOCUMENT_MODELS.includes(model as FiscalDocumentModel)) throw new FiscalDocumentError(\"INVALID_INPUT\", \"model must be NFE or NFCE.\");\n const offline = fields[\"offline\"] ?? false;\n if (typeof offline !== \"boolean\") throw new FiscalDocumentError(\"INVALID_INPUT\", \"offline must be a boolean.\");\n if (offline && model !== \"NFCE\") throw new FiscalDocumentError(\"INVALID_INPUT\", \"only an NFC-e is issued offline.\");\n return { subjectId: stringField(fields, \"subjectId\"), issuingPointId: stringField(fields, \"issuingPointId\"), model: model as FiscalDocumentModel, offline };\n}\n\nfunction profileRoutes({ documents }: FiscalApiConfig): FiscalRoute[] {\n return [\n {\n method: \"GET\",\n path: \"/fiscal/profile\",\n permission: FISCAL_READ,\n handle: ({ actor }) =>\n answering(async () => {\n const profile = await documents.getProfile(actor.ownerId);\n return ok(profile === null ? null : viewOf(profile));\n }),\n },\n {\n method: \"PUT\",\n path: \"/fiscal/profile\",\n permission: FISCAL_MANAGE,\n handle: ({ actor, body }) => answering(async () => ok(viewOf(await documents.saveProfile(actor.ownerId, parseProfileInput(body))))),\n },\n {\n method: \"PUT\",\n path: \"/fiscal/profile/certificate\",\n permission: FISCAL_MANAGE,\n handle: ({ actor, body }) =>\n answering(async () => ok(viewOf(await documents.uploadCertificate(actor.ownerId, parseCertificateUpload(body))))),\n },\n {\n method: \"GET\",\n path: \"/fiscal/issuing-points\",\n permission: FISCAL_READ,\n handle: ({ actor }) => answering(async () => ok(await documents.listIssuingPoints(actor.ownerId))),\n },\n {\n method: \"POST\",\n path: \"/fiscal/issuing-points\",\n permission: FISCAL_MANAGE,\n handle: ({ actor, body }) =>\n answering(async () => ok(await documents.createIssuingPoint(actor.ownerId, parseIssuingPointInput(body)), 201)),\n },\n ];\n}\n\n/** The DANFE of a printable document, as ESC/POS-ready lines. */\nfunction danfeRoute({ documents, storage, danfeLabels }: FiscalApiConfig): FiscalRoute {\n return {\n method: \"GET\",\n path: \"/fiscal/documents/:documentId/danfe\",\n permission: FISCAL_READ,\n handle: (request) =>\n answering(async () => {\n const paper = Number(request.query[\"paper\"] ?? \"80\");\n if (paper !== 58 && paper !== 80) throw new FiscalDocumentError(\"INVALID_INPUT\", \"paper must be 58 or 80.\");\n const document = await documents.getDocument(request.actor.ownerId, param(request, \"documentId\"));\n if (!PRINTABLE.has(document.status)) {\n throw new FiscalDocumentError(\"NOT_PRINTABLE\", `document ${document.id} is ${document.status}: only an AUTHORIZED or CONTINGENCY document prints.`);\n }\n const xml = document.model === \"NFCE\" && document.xmlKey !== null ? await storage.get(document.xmlKey) : null;\n if (xml === null) throw new FiscalDocumentError(\"NOT_FOUND\", `document ${document.id} has no NFC-e XML to print.`);\n return ok(renderDanfeNfce({ xml, paperWidth: paper as PaperWidth, labels: danfeLabels }));\n }),\n };\n}\n\nfunction documentRoutes(config: FiscalApiConfig): FiscalRoute[] {\n const { documents } = config;\n return [\n {\n method: \"POST\",\n path: \"/fiscal/documents\",\n permission: FISCAL_ISSUE,\n handle: ({ actor, body }) =>\n answering(async () => {\n const { offline, ...input } = issueBody(body);\n const document = offline\n ? await documents.issueOffline({ ownerId: actor.ownerId, subjectId: input.subjectId, issuingPointId: input.issuingPointId })\n : await documents.issue({ ownerId: actor.ownerId, ...input });\n return ok(document);\n }),\n },\n {\n method: \"GET\",\n path: \"/fiscal/documents/:documentId\",\n permission: FISCAL_READ,\n handle: (request) =>\n answering(async () => {\n const documentId = param(request, \"documentId\");\n const document = await documents.getDocument(request.actor.ownerId, documentId);\n return ok({ document, events: await documents.listEvents(request.actor.ownerId, documentId) });\n }),\n },\n {\n method: \"POST\",\n path: \"/fiscal/documents/:documentId/cancel\",\n permission: FISCAL_CANCEL,\n handle: (request) =>\n answering(async () => {\n const reason = stringField(record(request.body), \"reason\");\n const result = await documents.cancel({ ownerId: request.actor.ownerId, documentId: param(request, \"documentId\"), reason });\n return result.failure === null\n ? ok(result.document)\n : { status: 422, body: { error: \"ISSUER_FAILURE\", failure: result.failure, data: result.document } };\n }),\n },\n {\n method: \"POST\",\n path: \"/fiscal/documents/:documentId/resend\",\n permission: FISCAL_ISSUE,\n handle: (request) =>\n answering(async () =>\n ok(await documents.resendContingency({ ownerId: request.actor.ownerId, documentId: param(request, \"documentId\") })),\n ),\n },\n {\n method: \"POST\",\n path: \"/fiscal/documents/:documentId/release\",\n permission: FISCAL_ISSUE,\n handle: (request) =>\n answering(async () => ok(await documents.release({ ownerId: request.actor.ownerId, documentId: param(request, \"documentId\") }))),\n },\n {\n method: \"POST\",\n path: \"/fiscal/documents/:documentId/lookup\",\n permission: FISCAL_READ,\n handle: (request) =>\n answering(async () => ok(await documents.lookup({ ownerId: request.actor.ownerId, documentId: param(request, \"documentId\") }))),\n },\n danfeRoute(config),\n ];\n}\n\nexport function createApiFiscal(config: FiscalApiConfig): { routes: readonly FiscalRoute[] } {\n if (config?.documents === undefined) throw new TypeError(\"createApiFiscal needs documents.\");\n if (config.storage === undefined) throw new TypeError(\"createApiFiscal needs storage.\");\n if (config.danfeLabels === undefined) throw new TypeError(\"createApiFiscal needs danfeLabels.\");\n return { routes: [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;AACtF,MAAI,OAAO,gBAAgB,OAAW,OAAM,IAAI,UAAU,oCAAoC;AAC9F,SAAO,EAAE,QAAQ,CAAC,GAAG,cAAc,MAAM,GAAG,GAAG,eAAe,MAAM,CAAC,EAAE;AACzE;AALgB;","names":[]}
@@ -1,4 +1,4 @@
1
- import { F as FiscalDocumentModel, k as DocumentTotals, D as DocumentEventKind, g as FiscalDocumentStatus, h as FiscalDocument, i as FiscalDocumentEvent, j as SeriesKind, f as SigningMaterial, I as Issuer } from './port-DpRFK56U.js';
1
+ import { F as FiscalDocumentModel, k as DocumentTotals, D as DocumentEventKind, g as FiscalDocumentStatus, h as FiscalDocument, i as FiscalDocumentEvent, j as SeriesKind, f as SigningMaterial, I as Issuer } from './port-B1-ipIL4.js';
2
2
  import { IssuerTaxRegime, Address, SaleForDocument } from './sale/index.js';
3
3
  import { SefazEnvironment, IssuedDocument, SidecarErrorBody, ContingencySignedDocument, ContingencyEntry, CancelledDocument, LookedUpDocument, InutilizedRange } from './sidecar/index.js';
4
4
  import { T as TaxRegime } from './types-B1b8LIWX.js';
@@ -4,9 +4,9 @@ import {
4
4
  money,
5
5
  renderDanfeNfce,
6
6
  wrap
7
- } from "../chunk-WTGASIZE.js";
7
+ } from "../chunk-MGTROA7K.js";
8
8
  import "../chunk-PNTKG3DZ.js";
9
- import "../chunk-2LBQRYPV.js";
9
+ import "../chunk-H33BK623.js";
10
10
  import "../chunk-7QVYU63E.js";
11
11
  export {
12
12
  DANFE_COLUMNS,
@@ -1,8 +1,8 @@
1
- import { F as FiscalDocumentModel, j as SeriesKind, h as FiscalDocument, i as FiscalDocumentEvent } from '../port-DpRFK56U.js';
2
- export { D as DocumentEventKind, k as DocumentTotals, l as FISCAL_DOCUMENT_MODELS, n as FISCAL_DOCUMENT_STATUSES, g as FiscalDocumentStatus, N as NumberVoid, O as OWED_VOIDS, o as isLive } from '../port-DpRFK56U.js';
3
- import { h as SaleDraft, F as FiscalStore } from '../context-ChnWR4Kb.js';
4
- export { C as Cipher, i as ContingencyBlockSource, j as DOCUMENT_POLICIES, k as DOCUMENT_TRANSITIONS, l as DocumentInput, f as DocumentPolicy, D as DocumentStorage, E as EmitterProfile, m as EmitterProfileView, n as FINAL_STATUSES, b as FISCAL_CERTIFICATE_EXPIRING, c as FISCAL_CONTINGENCY_DEADLINE, d as FISCAL_DOCUMENT_NEEDS_ATTENTION, e as FISCAL_DOCUMENT_REJECTED, g as FiscalDocumentsConfig, a as FiscalNotifyPort, o as FiscalReasons, I as IssuingPoint, M as MAX_FAILURES, N as NumberRequest, p as SIGNING_IDENTITY_KINDS, q as SaleSource, r as SigningIdentities, s as SigningIdentity, S as SigningIdentityKind, T as Transition, t as canTransition, u as createPlatformIdentity, v as createSigningIdentities, w as createStoreCertificateIdentity, x as scrubSecrets, y as transition, z as viewOf } from '../context-ChnWR4Kb.js';
5
- export { C as CONTINGENCY_WARNING_AFTER_MS, a as CertificateFacts, b as CertificateUpload, E as EmitterProfileInput, F as FiscalDocuments, c as FiscalDocumentsServiceConfig, I as IssueInput, d as IssuingPointInput, S as SweepReport, e as createFiscalDocuments, p as parseCertificateUpload, f as parseIssuingPointInput, g as parseProfileInput } from '../service-KTjH7AxW.js';
1
+ import { F as FiscalDocumentModel, j as SeriesKind, h as FiscalDocument, i as FiscalDocumentEvent } from '../port-B1-ipIL4.js';
2
+ export { D as DocumentEventKind, k as DocumentTotals, l as FISCAL_DOCUMENT_MODELS, n as FISCAL_DOCUMENT_STATUSES, g as FiscalDocumentStatus, N as NumberVoid, O as OWED_VOIDS, o as isLive } from '../port-B1-ipIL4.js';
3
+ import { h as SaleDraft, F as FiscalStore } from '../context-yc1C2__K.js';
4
+ export { C as Cipher, i as ContingencyBlockSource, j as DOCUMENT_POLICIES, k as DOCUMENT_TRANSITIONS, l as DocumentInput, f as DocumentPolicy, D as DocumentStorage, E as EmitterProfile, m as EmitterProfileView, n as FINAL_STATUSES, b as FISCAL_CERTIFICATE_EXPIRING, c as FISCAL_CONTINGENCY_DEADLINE, d as FISCAL_DOCUMENT_NEEDS_ATTENTION, e as FISCAL_DOCUMENT_REJECTED, g as FiscalDocumentsConfig, a as FiscalNotifyPort, o as FiscalReasons, I as IssuingPoint, M as MAX_FAILURES, N as NumberRequest, p as SIGNING_IDENTITY_KINDS, q as SaleSource, r as SigningIdentities, s as SigningIdentity, S as SigningIdentityKind, T as Transition, t as canTransition, u as createPlatformIdentity, v as createSigningIdentities, w as createStoreCertificateIdentity, x as scrubSecrets, y as transition, z as viewOf } from '../context-yc1C2__K.js';
5
+ export { C as CONTINGENCY_WARNING_AFTER_MS, a as CancelOrReturnInput, b as CancelOrReturnResult, c as CertificateFacts, d as CertificateUpload, E as EmitterProfileInput, F as FiscalDocuments, e as FiscalDocumentsServiceConfig, I as IssueInput, f as IssuingPointInput, L as LATE_CANCEL_CODES, S as SweepReport, g as createFiscalDocuments, p as parseCertificateUpload, h as parseIssuingPointInput, i as parseProfileInput } from '../service-BB9lWdyg.js';
6
6
  import { a as TaxBreakdown } from '../types-B1b8LIWX.js';
7
7
  import { SaleForDocument, SaleLine } from '../sale/index.js';
8
8
  import '../sidecar/index.js';
@@ -43,7 +43,13 @@ type FiscalDocumentErrorCode =
43
43
  * A `RETURN` asked of an NFC-e. An NFC-e has no return purpose: the return is
44
44
  * an NF-e (model 55) of entry that references the NFC-e's key.
45
45
  */
46
- | "RETURN_ON_NFCE";
46
+ | "RETURN_ON_NFCE"
47
+ /**
48
+ * `cancelOrReturn` past SEFAZ's window on a document that is not an NFC-e:
49
+ * the buyer's return NF-e of entry answers a consumer's NFC-e only; an NF-e
50
+ * past its window is the issuer's own correction, not this path's.
51
+ */
52
+ | "RETURN_OF_NFCE_ONLY";
47
53
  declare class FiscalDocumentError extends Error {
48
54
  readonly code: FiscalDocumentErrorCode;
49
55
  constructor(code: FiscalDocumentErrorCode, message: string);
@@ -5,7 +5,7 @@ import {
5
5
  parseIssuingPointInput,
6
6
  parseProfileInput,
7
7
  viewOf
8
- } from "../chunk-G3V7IYNF.js";
8
+ } from "../chunk-GGYJPFBJ.js";
9
9
  import {
10
10
  element
11
11
  } from "../chunk-PNTKG3DZ.js";
@@ -32,7 +32,7 @@ import {
32
32
  totalsOf,
33
33
  transition,
34
34
  xmlKeys
35
- } from "../chunk-N5DCKYFR.js";
35
+ } from "../chunk-GKT3X5CF.js";
36
36
  import {
37
37
  FISCAL_DOCUMENT_MODELS,
38
38
  FISCAL_DOCUMENT_STATUSES,
@@ -44,7 +44,7 @@ import {
44
44
  } from "../chunk-3SDXLSG4.js";
45
45
  import {
46
46
  FiscalDocumentError
47
- } from "../chunk-2LBQRYPV.js";
47
+ } from "../chunk-H33BK623.js";
48
48
  import {
49
49
  __name
50
50
  } from "../chunk-7QVYU63E.js";
@@ -482,6 +482,51 @@ async function cancel(deps, input) {
482
482
  return { document: cancelled, failure: null };
483
483
  }
484
484
  __name(cancel, "cancel");
485
+ var LATE_CANCEL_CODES = ["501"];
486
+ var isLateCancel = /* @__PURE__ */ __name((code) => code !== null && LATE_CANCEL_CODES.includes(code), "isLateCancel");
487
+ async function liveReturnOf(deps, document) {
488
+ const returns = (await deps.config.store.listBySubject(document.ownerId, document.subjectId, "NFE")).filter(isLive);
489
+ const quoting = returns.filter((candidate) => returnsDocument(candidate, document));
490
+ return quoting[quoting.length - 1] ?? null;
491
+ }
492
+ __name(liveReturnOf, "liveReturnOf");
493
+ async function cancelOrReturn(deps, input) {
494
+ assertReason(input.reason, "reason");
495
+ const document = await requireDocument(deps, input.ownerId, input.documentId);
496
+ if (document.status === "CANCELLED") return { outcome: "CANCELLED", document, returnDocument: null, failure: null };
497
+ const existing = document.accessKey === null ? null : await liveReturnOf(deps, document);
498
+ if (existing !== null) return { outcome: "RETURNED", document, returnDocument: existing, failure: null };
499
+ const cancelled = await cancel(deps, input);
500
+ if (cancelled.failure === null) return { outcome: "CANCELLED", document: cancelled.document, returnDocument: null, failure: null };
501
+ const late = cancelled.failure.class === "REJECTED" && isLateCancel(cancelled.failure.code);
502
+ if (!late) return { outcome: "REFUSED", document: cancelled.document, returnDocument: null, failure: cancelled.failure };
503
+ return { outcome: "RETURNED", document: cancelled.document, returnDocument: await issueReturn(deps, document, input.returnPointId), failure: cancelled.failure };
504
+ }
505
+ __name(cancelOrReturn, "cancelOrReturn");
506
+ function returnsDocument(candidate, document) {
507
+ const quotes = (candidate.sale.referencedDocuments ?? []).some((reference) => reference.accessKey === document.accessKey);
508
+ return candidate.model === "NFE" && candidate.sale.purpose === "RETURN" && quotes;
509
+ }
510
+ __name(returnsDocument, "returnsDocument");
511
+ async function issueReturn(deps, document, returnPointId) {
512
+ if (document.model !== "NFCE") {
513
+ throw new FiscalDocumentError("RETURN_OF_NFCE_ONLY", `document ${document.id} is an ${document.model}: only an NFC-e is answered with a buyer's return.`);
514
+ }
515
+ const live = (await deps.config.store.listBySubject(document.ownerId, document.subjectId, "NFE")).filter(isLive);
516
+ if (live.length > 0) {
517
+ throw new FiscalDocumentError("SUBJECT_HAS_DOCUMENT", `subject ${document.subjectId} already holds a live NF-e that is not document ${document.id}'s return.`);
518
+ }
519
+ const draft = await deps.config.sales.saleFor({ ownerId: document.ownerId, subjectId: document.subjectId, model: "NFE" });
520
+ if (!returnsDocument({ model: "NFE", sale: draft }, document)) {
521
+ throw new FiscalDocumentError("INVALID_INPUT", `the return the sale source answered for subject ${document.subjectId} does not quote document ${document.id}.`);
522
+ }
523
+ const returned = await issue(deps, { ownerId: document.ownerId, subjectId: document.subjectId, issuingPointId: returnPointId, model: "NFE" });
524
+ if (returned.id === document.id || !returnsDocument(returned, document)) {
525
+ throw new FiscalDocumentError("CONFLICT", `subject ${document.subjectId}'s live NF-e is not document ${document.id}'s return.`);
526
+ }
527
+ return returned;
528
+ }
529
+ __name(issueReturn, "issueReturn");
485
530
  function lookupMoves(document) {
486
531
  if (!canTransition(document.status, "LOOKUP")) return false;
487
532
  if (document.status === "REPLACED" || document.status === "REJECTED") return document.numberVoid === "LOOKUP_FIRST";
@@ -570,6 +615,11 @@ function createFiscalDocuments(config) {
570
615
  resendContingency: resendContingency.bind(null, deps),
571
616
  /** Cancel an authorised document. A refusal (late, say) answers the issuer's failure and changes nothing. */
572
617
  cancel: cancel.bind(null, deps),
618
+ /**
619
+ * Cancel an authorised document, or — when SEFAZ says the cancel is too late
620
+ * (501) — issue the buyer's return NF-e of entry quoting it. Idempotent.
621
+ */
622
+ cancelOrReturn: cancelOrReturn.bind(null, deps),
573
623
  /** Ask SEFAZ what it knows of the key; a state the answer moves is recorded. */
574
624
  lookup: lookup.bind(null, deps),
575
625
  /** A person takes a document back from `attention`; the sweep tries it again. */
@@ -1206,6 +1256,7 @@ export {
1206
1256
  FISCAL_DOCUMENT_STATUSES,
1207
1257
  FISCAL_NEXT_NUMBER_SQL,
1208
1258
  FiscalDocumentError,
1259
+ LATE_CANCEL_CODES,
1209
1260
  MAX_FAILURES,
1210
1261
  OWED_VOIDS,
1211
1262
  SIGNING_IDENTITY_KINDS,