@12-apps/fiscal 1.2.0 → 1.4.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 (40) hide show
  1. package/README.md +17 -0
  2. package/dist/{chunk-N5DCKYFR.js → chunk-2ISYBTCE.js} +3 -3
  3. package/dist/{chunk-G3V7IYNF.js → chunk-EDEGIADD.js} +3 -3
  4. package/dist/{chunk-NVRYAAQ4.js → chunk-F2PGQVWL.js} +7 -6
  5. package/dist/chunk-F2PGQVWL.js.map +1 -0
  6. package/dist/{chunk-XQGW5HUG.js → chunk-GF3DXCD2.js} +1 -1
  7. package/dist/chunk-GF3DXCD2.js.map +1 -0
  8. package/dist/{chunk-2LBQRYPV.js → chunk-H33BK623.js} +1 -1
  9. package/dist/{chunk-2LBQRYPV.js.map → chunk-H33BK623.js.map} +1 -1
  10. package/dist/{chunk-WTGASIZE.js → chunk-MGTROA7K.js} +2 -2
  11. package/dist/{chunk-5S2PJHAE.js → chunk-OSYB7CVT.js} +2 -2
  12. package/dist/{context-ChnWR4Kb.d.ts → context-CLSMOSuf.d.ts} +1 -1
  13. package/dist/danfe/index.js +2 -2
  14. package/dist/documents/index.d.ts +12 -6
  15. package/dist/documents/index.js +118 -9
  16. package/dist/documents/index.js.map +1 -1
  17. package/dist/http.d.ts +4 -3
  18. package/dist/http.js +5 -5
  19. package/dist/issuer/index.d.ts +2 -2
  20. package/dist/jobs.d.ts +3 -3
  21. package/dist/jobs.js +4 -4
  22. package/dist/manifest/server.d.ts +3 -3
  23. package/dist/manifest/server.js +7 -7
  24. package/dist/notifications.d.ts +2 -2
  25. package/dist/notifications.js +3 -3
  26. package/dist/{service-KTjH7AxW.d.ts → service-hR3tgLpO.d.ts} +18 -3
  27. package/dist/{port-DpRFK56U.d.ts → types-BIJqm5GM.d.ts} +105 -85
  28. package/package.json +1 -1
  29. package/src/documents/errors.ts +7 -1
  30. package/src/documents/index.ts +2 -2
  31. package/src/documents/service.ts +88 -4
  32. package/src/documents/steps.ts +100 -4
  33. package/src/documents/types.ts +23 -0
  34. package/src/http.ts +1 -0
  35. package/dist/chunk-NVRYAAQ4.js.map +0 -1
  36. package/dist/chunk-XQGW5HUG.js.map +0 -1
  37. /package/dist/{chunk-N5DCKYFR.js.map → chunk-2ISYBTCE.js.map} +0 -0
  38. /package/dist/{chunk-G3V7IYNF.js.map → chunk-EDEGIADD.js.map} +0 -0
  39. /package/dist/{chunk-WTGASIZE.js.map → chunk-MGTROA7K.js.map} +0 -0
  40. /package/dist/{chunk-5S2PJHAE.js.map → chunk-OSYB7CVT.js.map} +0 -0
@@ -12,13 +12,22 @@
12
12
  * An online NFC-e is never sent again past `nfceOnlineToleranceMs` (SEFAZ
13
13
  * refuses a late `dhEmi`): where the point has a contingency series it goes
14
14
  * offline instead.
15
+ *
16
+ * A caller that cannot wait (a counter whose paper waits for the note) gives
17
+ * the send an ONLINE DEADLINE (`issue({ …, onlineDeadlineMs })`): an NFC-e at
18
+ * a point with a contingency series whose send is not answered by then — or is
19
+ * answered with no answer (`RETRYABLE`) — goes offline at once, exactly as a
20
+ * `CONTINGENCY` answer does. The send may still have reached SEFAZ, so the
21
+ * replaced number is marked unknown and looked up before it is voided; its
22
+ * late answer settles nothing.
15
23
  */
16
24
 
17
- import type { IssuerFailure, SigningMaterial } from "../issuer/port";
25
+ import type { IssuerFailure, IssuerOutcome, SigningMaterial } from "../issuer/port";
18
26
  import { FISCAL_ISSUE } from "../manifest/permissions";
19
27
  import type { IssuedDocument } from "../sidecar/types";
20
28
  import { FISCAL_DOCUMENT_REJECTED, type FiscalContext, draftOf, xmlKeys } from "./context";
21
29
  import { FiscalDocumentError } from "./errors";
30
+ import { computeAccessKey } from "./helpers";
22
31
  import { digestOf } from "./nfe-proc";
23
32
  import type { EmitterProfile, IssuingPoint } from "./profile";
24
33
  import type { FiscalDocument } from "./types";
@@ -145,21 +154,89 @@ function staleOnline(ctx: FiscalContext, document: FiscalDocument, point: Issuin
145
154
  return !knownToSefaz && canGoOffline(document, point) && pastOnlineTolerance(ctx, document);
146
155
  }
147
156
 
148
- /** Issue (or re-issue, for a SUBMITTED one) a document on its online series. */
157
+ /** The failure a send not answered by its online deadline counts as: a contingency, its outcome unknown. */
158
+ function pastDeadline(document: FiscalDocument): IssuerFailure {
159
+ return {
160
+ class: "CONTINGENCY",
161
+ code: null,
162
+ message: "SEFAZ did not answer before the online deadline.",
163
+ details: [],
164
+ accessKey: document.accessKey ?? computeAccessKey({ sale: document.sale, model: document.model, seriesKind: "ONLINE" }),
165
+ signedXml: null,
166
+ sefazReply: null,
167
+ outcomeUnknown: true,
168
+ };
169
+ }
170
+
171
+ /** The send, raced against the deadline (`deadlineAt`, epoch ms). A late answer is dropped: the number is looked up instead. */
172
+ async function sendBefore(
173
+ send: Promise<IssuerOutcome<IssuedDocument>>,
174
+ document: FiscalDocument,
175
+ deadlineAt: number,
176
+ ): Promise<IssuerOutcome<IssuedDocument>> {
177
+ send.catch(() => undefined);
178
+ let timer: ReturnType<typeof setTimeout> | undefined;
179
+ const late = new Promise<IssuerOutcome<IssuedDocument>>((resolve) => {
180
+ timer = setTimeout(() => resolve({ ok: false, error: pastDeadline(document) }), Math.max(0, deadlineAt - Date.now()));
181
+ });
182
+ try {
183
+ return await Promise.race([send, late]);
184
+ } finally {
185
+ clearTimeout(timer);
186
+ }
187
+ }
188
+
189
+ /** The online send, bounded by the deadline when there is one. */
190
+ function send(ctx: FiscalContext, document: FiscalDocument, signing: SigningMaterial, deadlineAt: number | null): Promise<IssuerOutcome<IssuedDocument>> {
191
+ const call = ctx.config.issuer.issue({ model: document.model, environment: document.environment, signing, document: document.sale });
192
+ return deadlineAt === null ? call : sendBefore(call, document, deadlineAt);
193
+ }
194
+
195
+ /** Whether a failed send moves the sale offline: a contingency always; with a deadline, an unanswered send too. */
196
+ function goesOffline(error: IssuerFailure, deadlineAt: number | null): boolean {
197
+ return error.class === "CONTINGENCY" || (deadlineAt !== null && error.class === "RETRYABLE");
198
+ }
199
+
200
+ /**
201
+ * Issue (or re-issue, for a SUBMITTED one) a document on its online series.
202
+ * `deadlineAt` (epoch ms): the online deadline, for an NFC-e whose point can
203
+ * go offline (see the module doc); `null`, the send's own timeout rules.
204
+ */
149
205
  export async function submit(
150
206
  ctx: FiscalContext,
151
207
  document: FiscalDocument,
152
208
  profile: EmitterProfile,
153
209
  point: IssuingPoint,
154
210
  signing: SigningMaterial,
211
+ deadlineAt: number | null = null,
155
212
  ): Promise<FiscalDocument> {
156
213
  if (staleOnline(ctx, document, point)) return goOffline(ctx, document, profile, point, signing);
157
214
  const sent = document.status === "PENDING" ? await ctx.advance(document, { kind: "SUBMIT" }) : document;
158
- const outcome = await ctx.config.issuer.issue({ model: sent.model, environment: sent.environment, signing, document: sent.sale });
215
+ const bounded = deadlineAt !== null && canGoOffline(sent, point) ? deadlineAt : null;
216
+ const outcome = await send(ctx, sent, signing, bounded);
159
217
  if (outcome.ok) return accept(ctx, sent, outcome.answer);
160
218
  if (FINAL_FAILURES.has(outcome.error.class)) return reject(ctx, sent, outcome.error);
161
219
  const retried = await ctx.advance(sent, { kind: "RETRY", error: outcome.error, ...(await keepSigned(ctx, sent, outcome.error)) });
162
- return outcome.error.class === "CONTINGENCY" && canGoOffline(retried, point) ? goOffline(ctx, retried, profile, point, signing) : retried;
220
+ return goesOffline(outcome.error, bounded) && canGoOffline(retried, point) ? goOffline(ctx, retried, profile, point, signing) : retried;
221
+ }
222
+
223
+ /**
224
+ * A live online NFC-e the caller's deadline already passed — `onlineDeadlineMs`
225
+ * since it was numbered, still unanswered and not known to SEFAZ — goes offline
226
+ * now, at a point with a contingency series; anything else is answered as it is.
227
+ */
228
+ async function offlineIfOverdue(
229
+ ctx: FiscalContext,
230
+ document: FiscalDocument,
231
+ profile: EmitterProfile,
232
+ point: IssuingPoint,
233
+ signing: SigningMaterial,
234
+ onlineDeadlineMs: number,
235
+ ): Promise<FiscalDocument> {
236
+ const waiting = document.status === "PENDING" || document.status === "SUBMITTED";
237
+ const overdue = ctx.config.now().getTime() - Date.parse(document.createdAt) >= onlineDeadlineMs;
238
+ if (!waiting || !overdue || document.protocol !== null || !canGoOffline(document, point)) return document;
239
+ return goOffline(ctx, document, profile, point, signing);
163
240
  }
164
241
 
165
242
  /** Transmit a document signed offline. */
@@ -171,3 +248,22 @@ export async function transmit(ctx: FiscalContext, document: FiscalDocument, sig
171
248
  if (FINAL_FAILURES.has(outcome.error.class)) return reject(ctx, document, outcome.error);
172
249
  return ctx.advance(document, { kind: "RETRY", error: outcome.error });
173
250
  }
251
+
252
+ /** The live document of a lost race or an earlier call — moved offline when the caller's online deadline already passed. */
253
+ export async function answerLive(
254
+ ctx: FiscalContext,
255
+ existing: FiscalDocument,
256
+ profile: EmitterProfile,
257
+ onlineDeadlineMs: number | undefined,
258
+ ): Promise<FiscalDocument> {
259
+ if (onlineDeadlineMs === undefined || existing.model !== "NFCE" || existing.seriesKind !== "ONLINE") return existing;
260
+ const point = await ctx.requirePoint(existing.ownerId, existing.issuingPointId);
261
+ return offlineIfOverdue(ctx, existing, profile, point, await ctx.material(profile), onlineDeadlineMs);
262
+ }
263
+
264
+ /** `onlineDeadlineMs`, when given, is a whole number of milliseconds, 0 or more. */
265
+ export function assertOnlineDeadline(onlineDeadlineMs: number | undefined): void {
266
+ if (onlineDeadlineMs !== undefined && (!Number.isInteger(onlineDeadlineMs) || onlineDeadlineMs < 0)) {
267
+ throw new FiscalDocumentError("INVALID_INPUT", "onlineDeadlineMs must be a whole number of milliseconds, 0 or more.");
268
+ }
269
+ }
@@ -10,6 +10,7 @@
10
10
  * several orders) is the host's to know, never this package's.
11
11
  */
12
12
 
13
+ import type { IssuerFailure } from "../issuer/port";
13
14
  import type { SaleForDocument } from "../sale/types";
14
15
  import type { SefazEnvironment, SidecarErrorClass } from "../sidecar/types";
15
16
 
@@ -191,3 +192,25 @@ export interface FiscalDocumentEvent {
191
192
  readonly code: string | null;
192
193
  readonly answer: unknown;
193
194
  }
195
+
196
+ export interface CancelOrReturnInput {
197
+ readonly ownerId: string;
198
+ readonly documentId: string;
199
+ /** SEFAZ's 15–255 characters, sent with the cancel. */
200
+ readonly reason: string;
201
+ /** The NF-e (model 55) issuing point a return is numbered on. */
202
+ readonly returnPointId: string;
203
+ }
204
+
205
+ export interface CancelOrReturnResult {
206
+ /**
207
+ * `CANCELLED` inside the window; `RETURNED` past it (the return may itself
208
+ * still be SUBMITTED: the sweep settles it like any document); `REFUSED`
209
+ * when the issuer refused the cancel for any other reason (nothing changed).
210
+ */
211
+ readonly outcome: "CANCELLED" | "RETURNED" | "REFUSED";
212
+ /** The document asked about, as it stands: CANCELLED, or still AUTHORIZED beside its return. */
213
+ readonly document: FiscalDocument;
214
+ readonly returnDocument: FiscalDocument | null;
215
+ readonly failure: IssuerFailure | null;
216
+ }
package/src/http.ts CHANGED
@@ -74,6 +74,7 @@ export const FISCAL_ERROR_STATUS = {
74
74
  RESEND_CHANGES_PRINTED_FIELDS: 422,
75
75
  RETURN_NEEDS_REFERENCE: 422,
76
76
  RETURN_ON_NFCE: 422,
77
+ RETURN_OF_NFCE_ONLY: 422,
77
78
  } as const satisfies Record<FiscalDocumentErrorCode, number>;
78
79
 
79
80
  /**
@@ -1 +0,0 @@
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} 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: [...profileRoutes(config), ...documentRoutes(config)] };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA+DO,IAAM,sBAAsB;AAAA,EACjC,eAAe;AAAA,EACf,WAAW;AAAA,EACX,cAAc;AAAA,EACd,eAAe;AAAA,EACf,oBAAoB;AAAA,EACpB,kBAAkB;AAAA,EAClB,UAAU;AAAA,EACV,sBAAsB;AAAA,EACtB,eAAe;AAAA,EACf,+BAA+B;AAAA,EAC/B,wBAAwB;AAAA,EACxB,gBAAgB;AAClB;AAOA,IAAM,YAAY,oBAAI,IAAI,CAAC,cAAc,aAAa,CAAC;AAEvD,IAAM,KAAK,wBAAC,MAAe,SAAS,SAA6B,EAAE,QAAQ,MAAM,EAAE,KAAK,EAAE,IAA/E;AAEX,eAAe,UAAU,KAAqE;AAC5F,MAAI;AACF,WAAO,MAAM,IAAI;AAAA,EACnB,SAAS,OAAO;AACd,QAAI,iBAAiB,qBAAqB;AACxC,aAAO,EAAE,QAAQ,oBAAoB,MAAM,IAAI,GAAG,MAAM,EAAE,OAAO,M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ACP,UAAU,YAAY,GAAG,MAAM,UAAU,QAAQ,EAAE,SAAS,QAAQ,MAAM,SAAS,YAAY,MAAM,SAAS,YAAY,EAAE,CAAC,CAAC,CAAC,GADzH;AAAA,IAEV;AAAA,IACA;AAAA,MACE,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,YAAY;AAAA,MACZ,QAAQ,wBAAC,YACP,UAAU,YAAY,GAAG,MAAM,UAAU,OAAO,EAAE,SAAS,QAAQ,MAAM,SAAS,YAAY,MAAM,SAAS,YAAY,EAAE,CAAC,CAAC,CAAC,GADxH;AAAA,IAEV;AAAA,IACA,WAAW,MAAM;AAAA,EACnB;AACF;AAjES;AAmEF,SAAS,gBAAgB,QAA6D;AAC3F,MAAI,QAAQ,cAAc,OAAW,OAAM,IAAI,UAAU,kCAAkC;AAC3F,MAAI,OAAO,YAAY,OAAW,OAAM,IAAI,UAAU,gCAAgC;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 +0,0 @@
1
- {"version":3,"sources":["../src/documents/types.ts"],"sourcesContent":["/**\n * The fiscal document record and its event log — the shape the package's\n * Prisma partial stores (`prisma/fiscal.prisma`, `FiscalDocument` and\n * `FiscalDocumentEvent`) and the state machine (`./machine`) transitions.\n *\n * A document is ONE number: one issuing point, one series, one `nNF`. A sale\n * that goes offline is a second document on the issuing point's contingency\n * series, and the first one is `REPLACED` (see `./machine`). The record is\n * keyed by an opaque `subjectId`: what the subject is (an order, a payment,\n * several orders) is the host's to know, never this package's.\n */\n\nimport type { SaleForDocument } from \"../sale/types\";\nimport type { SefazEnvironment, SidecarErrorClass } from \"../sidecar/types\";\n\n/** The document model: NF-e (55) or NFC-e (65). NFS-e is not a model of this package yet (FUT-2242). */\nexport type FiscalDocumentModel = \"NFE\" | \"NFCE\";\n\nexport const FISCAL_DOCUMENT_MODELS: readonly FiscalDocumentModel[] = [\"NFE\", \"NFCE\"];\n\n/**\n * - `PENDING`: numbered and stored, not yet handed to the issuer.\n * - `SUBMITTED`: handed to the issuer; no final answer yet (a retry is owed).\n * - `AUTHORIZED`: SEFAZ authorised it. The only state a cancel leaves.\n * - `REJECTED`: refused (SEFAZ's `cStat`, or a request the service refuses as\n * malformed). Final; its number was not spent at SEFAZ and is inutilized.\n * - `DENIED`: a denial of use. Final; the number IS spent.\n * - `CONTINGENCY`: signed offline (`tpEmis = 9`), owed a transmission.\n * - `CANCELLED`: an authorised document cancelled at SEFAZ.\n * - `REPLACED`: its sale moved to another document (the contingency one);\n * its number is settled apart (`numberVoid`).\n */\nexport type FiscalDocumentStatus =\n | \"PENDING\"\n | \"SUBMITTED\"\n | \"AUTHORIZED\"\n | \"REJECTED\"\n | \"DENIED\"\n | \"CONTINGENCY\"\n | \"CANCELLED\"\n | \"REPLACED\";\n\nexport const FISCAL_DOCUMENT_STATUSES: readonly FiscalDocumentStatus[] = [\n \"PENDING\",\n \"SUBMITTED\",\n \"AUTHORIZED\",\n \"REJECTED\",\n \"DENIED\",\n \"CONTINGENCY\",\n \"CANCELLED\",\n \"REPLACED\",\n];\n\n/** Which of the issuing point's series the number came from. */\nexport type SeriesKind = \"ONLINE\" | \"CONTINGENCY\";\n\n/**\n * What is still owed on a number SEFAZ never used, so the sequence has no\n * unexplained gap:\n *\n * - `null`: nothing — the number is a document (authorised, denied, owed a\n * transmission) or still in flight.\n * - `LOOKUP_FIRST`: a request went out with no answer before the sale moved\n * to contingency; look the key up before deciding.\n * - `INUTILIZE`: never used at SEFAZ; inutilize it.\n * - `CANCEL`: the lookup found it authorised after all; cancel it.\n * - `INUTILIZED` / `CANCELLED`: settled.\n * - `DENIED`: settled — the lookup found the number denied, which spends it.\n */\nexport type NumberVoid = \"LOOKUP_FIRST\" | \"INUTILIZE\" | \"CANCEL\" | \"INUTILIZED\" | \"CANCELLED\" | \"DENIED\";\n\n/** The `numberVoid` values that still owe the sweep a call. */\nexport const OWED_VOIDS: readonly NumberVoid[] = [\"LOOKUP_FIRST\", \"INUTILIZE\", \"CANCEL\"];\n\n/** The order figures a document carries, in integer cents. */\nexport interface DocumentTotals {\n /** What the buyer pays: Σ line values − Σ discounts. */\n readonly totalCents: number;\n readonly discountCents: number;\n readonly cbsCents: number;\n readonly ibsUfCents: number;\n readonly ibsMunCents: number;\n}\n\n/**\n * Whether the document is the one its subject stands on. At most one live\n * document per (owner, subject, model): a REPLACED one is not, nor an online\n * one SEFAZ rejected (its number is voided and the sale is issued again) —\n * unless a lookup had found it authorised (its protocol is kept). A\n * REJECTED contingency NFC-e stays live: the buyer holds its DANFE, and the\n * store corrects and resends it under the same number.\n */\nexport function isLive(document: Pick<FiscalDocument, \"status\" | \"seriesKind\" | \"protocol\">): boolean {\n if (document.status === \"REPLACED\") return false;\n // An online rejection with a protocol known (a lookup found it SEFAZ's) is still the sale's.\n return !(document.status === \"REJECTED\" && document.seriesKind === \"ONLINE\" && document.protocol === null);\n}\n\n/** One fiscal document. */\nexport interface FiscalDocument {\n readonly id: string;\n /** The emitter profile's owner: an opaque id the host maps (a store, a company). */\n readonly ownerId: string;\n /** The issuer's CNPJ: SEFAZ numbers by CNPJ, model and series, so the counters do too. */\n readonly issuerCnpj: string;\n /** What the document is FOR, opaque: the host links it to its orders. */\n readonly subjectId: string;\n readonly issuingPointId: string;\n readonly model: FiscalDocumentModel;\n readonly environment: SefazEnvironment;\n readonly seriesKind: SeriesKind;\n readonly series: number;\n readonly number: number;\n /** `cNF`, drawn once: a retried call yields the same key. */\n readonly keyCode: string;\n readonly status: FiscalDocumentStatus;\n /** The sale as sent, issuer and number filled in. Never a secret. */\n readonly sale: SaleForDocument;\n readonly totals: DocumentTotals;\n /** The buyer's CPF/CNPJ at issue time, or `null`. */\n readonly buyerTaxId: string | null;\n readonly accessKey: string | null;\n /** The authorisation (or denial) protocol. */\n readonly protocol: string | null;\n /** The last SEFAZ `cStat`, or the service's named code. */\n readonly statusCode: string | null;\n readonly statusReason: string | null;\n /** The class of the last failed call, or `null`. */\n readonly lastErrorClass: SidecarErrorClass | null;\n /** A request went out and neither it nor its lookup was answered. */\n readonly outcomeUnknown: boolean;\n /** `dhEmi`. */\n readonly issuedAt: string;\n readonly authorizedAt: string | null;\n readonly contingency: { readonly since: string; readonly reason: string } | null;\n readonly cancelledAt: string | null;\n readonly cancelReason: string | null;\n readonly cancelProtocol: string | null;\n /** The document this one's sale moved to. */\n readonly replacedById: string | null;\n readonly numberVoid: NumberVoid | null;\n /** Storage keys: the signed or authorised XML, and the cancel or inutilization event's XML. */\n readonly xmlKey: string | null;\n readonly eventXmlKey: string | null;\n /** Calls made to the issuer for this document. */\n readonly attempts: number;\n /** Failed steps in a row (a retry, a deferred settlement); any progress resets it. */\n readonly failures: number;\n /** When the sweep (or the contingency transmission) may take it again; `null` when nothing is owed. */\n readonly nextAttemptAt: string | null;\n /**\n * A person must look: a settlement SEFAZ refused, or too many failures in a\n * row. The sweep leaves it alone until someone releases it.\n */\n readonly attention: boolean;\n /** When the 24-hour contingency deadline warning went out. */\n readonly deadlineWarnedAt: string | null;\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\n/** What the state machine was fed: the kind of the input that made the event. */\nexport type DocumentEventKind =\n | \"SUBMIT\"\n | \"AUTHORIZE\"\n | \"DENY\"\n | \"REJECT\"\n | \"RETRY\"\n | \"SIGN_OFFLINE\"\n | \"REPLACE\"\n | \"CANCEL\"\n | \"LOOKUP\"\n | \"INUTILIZE\"\n | \"DEFER\"\n | \"RESIGN\"\n | \"RELEASE\"\n | \"WARN\";\n\n/**\n * One transition, as stored. `answer` is what the fiscal service answered,\n * verbatim but for any secret-named key (`scrubSecrets`), so the record is the\n * evidence of what SEFAZ said, the `MarketplaceInboxEvent.payload` habit.\n */\nexport interface FiscalDocumentEvent {\n readonly documentId: string;\n readonly kind: DocumentEventKind;\n readonly fromStatus: FiscalDocumentStatus;\n readonly toStatus: FiscalDocumentStatus;\n readonly at: string;\n readonly errorClass: SidecarErrorClass | null;\n readonly code: string | null;\n readonly answer: unknown;\n}\n"],"mappings":";;;;;AAkBO,IAAM,yBAAyD,CAAC,OAAO,MAAM;AAwB7E,IAAM,2BAA4D;AAAA,EACvE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAqBO,IAAM,aAAoC,CAAC,gBAAgB,aAAa,QAAQ;AAoBhF,SAAS,OAAO,UAA+E;AACpG,MAAI,SAAS,WAAW,WAAY,QAAO;AAE3C,SAAO,EAAE,SAAS,WAAW,cAAc,SAAS,eAAe,YAAY,SAAS,aAAa;AACvG;AAJgB;","names":[]}