@12-apps/fiscal 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/{chunk-2ISYBTCE.js → chunk-3E3NBXSW.js} +11 -4
  2. package/dist/chunk-3E3NBXSW.js.map +1 -0
  3. package/dist/{chunk-OSYB7CVT.js → chunk-G6QNU4FD.js} +2 -2
  4. package/dist/{chunk-GF3DXCD2.js → chunk-GH452ITO.js} +1 -1
  5. package/dist/{chunk-GF3DXCD2.js.map → chunk-GH452ITO.js.map} +1 -1
  6. package/dist/{chunk-EDEGIADD.js → chunk-HMTPJWXM.js} +2 -2
  7. package/dist/{chunk-F2PGQVWL.js → chunk-TJCUO6D6.js} +3 -3
  8. package/dist/{chunk-JVQKJNOC.js → chunk-ZKWVKCGJ.js} +1 -1
  9. package/dist/chunk-ZKWVKCGJ.js.map +1 -0
  10. package/dist/{context-CLSMOSuf.d.ts → context-CwZiHLnY.d.ts} +14 -3
  11. package/dist/documents/index.d.ts +7 -5
  12. package/dist/documents/index.js +92 -3
  13. package/dist/documents/index.js.map +1 -1
  14. package/dist/http.d.ts +3 -3
  15. package/dist/http.js +3 -3
  16. package/dist/issuer/index.d.ts +2 -2
  17. package/dist/issuer/index.js +9 -1
  18. package/dist/issuer/index.js.map +1 -1
  19. package/dist/jobs.d.ts +3 -3
  20. package/dist/jobs.js +3 -3
  21. package/dist/manifest/server.d.ts +3 -3
  22. package/dist/manifest/server.js +5 -5
  23. package/dist/notifications.d.ts +2 -2
  24. package/dist/notifications.js +2 -2
  25. package/dist/sale/index.d.ts +29 -1
  26. package/dist/sale/index.js +7 -0
  27. package/dist/sale/index.js.map +1 -1
  28. package/dist/{service-hR3tgLpO.d.ts → service-Cz2O84Xr.d.ts} +38 -4
  29. package/dist/sidecar/index.d.ts +37 -1
  30. package/dist/sidecar/index.js +1 -1
  31. package/dist/{types-BIJqm5GM.d.ts → types-DSYwap42.d.ts} +25 -4
  32. package/package.json +1 -1
  33. package/prisma/migrations/20261118120000_fiscal_link_payment_event/migration.sql +9 -0
  34. package/sidecar/README.md +1 -0
  35. package/sidecar/composer.json +1 -1
  36. package/sidecar/composer.lock +7 -7
  37. package/sidecar/schema/sale-for-document.schema.json +18 -1
  38. package/sidecar/src/Nfe/DocumentMapper.php +27 -0
  39. package/sidecar/src/Nfe/Input.php +10 -0
  40. package/sidecar/src/Nfe/NfeModule.php +1 -0
  41. package/sidecar/src/Nfe/NfeService.php +120 -0
  42. package/sidecar/src/Nfe/SefazReply.php +21 -0
  43. package/src/documents/helpers.ts +2 -0
  44. package/src/documents/index.ts +2 -1
  45. package/src/documents/machine-steps.ts +12 -2
  46. package/src/documents/machine.ts +7 -0
  47. package/src/documents/payment-link.ts +156 -0
  48. package/src/documents/service.ts +4 -0
  49. package/src/documents/types.ts +2 -1
  50. package/src/issuer/port.ts +24 -1
  51. package/src/issuer/sidecar.ts +10 -0
  52. package/src/sale/index.ts +1 -0
  53. package/src/sale/types.ts +30 -0
  54. package/src/sidecar/types.ts +38 -0
  55. package/dist/chunk-2ISYBTCE.js.map +0 -1
  56. package/dist/chunk-JVQKJNOC.js.map +0 -1
  57. /package/dist/{chunk-OSYB7CVT.js.map → chunk-G6QNU4FD.js.map} +0 -0
  58. /package/dist/{chunk-EDEGIADD.js.map → chunk-HMTPJWXM.js.map} +0 -0
  59. /package/dist/{chunk-F2PGQVWL.js.map → chunk-TJCUO6D6.js.map} +0 -0
package/dist/http.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { D as DanfeNfceLabels } from './labels-BNvflT0h.js';
2
- import { D as DocumentStorage } from './context-CLSMOSuf.js';
3
- import { F as FiscalDocuments } from './service-hR3tgLpO.js';
4
- import './types-BIJqm5GM.js';
2
+ import { D as DocumentStorage } from './context-CwZiHLnY.js';
3
+ import { F as FiscalDocuments } from './service-Cz2O84Xr.js';
4
+ import './types-DSYwap42.js';
5
5
  import './sale/index.js';
6
6
  import './sidecar/index.js';
7
7
  import './types-B1b8LIWX.js';
package/dist/http.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  FISCAL_ERROR_STATUS,
3
3
  createApiFiscal
4
- } from "./chunk-F2PGQVWL.js";
4
+ } from "./chunk-TJCUO6D6.js";
5
5
  import "./chunk-MGTROA7K.js";
6
- import "./chunk-EDEGIADD.js";
6
+ import "./chunk-HMTPJWXM.js";
7
7
  import "./chunk-PNTKG3DZ.js";
8
- import "./chunk-GF3DXCD2.js";
8
+ import "./chunk-GH452ITO.js";
9
9
  import "./chunk-3SDXLSG4.js";
10
10
  import "./chunk-H33BK623.js";
11
11
  import "./chunk-7QVYU63E.js";
@@ -1,5 +1,5 @@
1
- import { I as Issuer } from '../types-BIJqm5GM.js';
2
- export { C as CancelBySubstitutionCall, a as CancelCall, b as InutilizeCall, c as IssueCall, d as IssuerFailure, e as IssuerOutcome, L as LookupCall, S as SignContingencyCall, f as SigningMaterial, T as TransmitCall, m as modelPath } from '../types-BIJqm5GM.js';
1
+ import { I as Issuer } from '../types-DSYwap42.js';
2
+ export { C as CancelBySubstitutionCall, a as CancelCall, b as InutilizeCall, c as IssueCall, d as IssuerFailure, e as IssuerOutcome, L as LinkPaymentCall, f as LookupCall, S as SignContingencyCall, g as SigningMaterial, T as TransmitCall, m as modelPath } from '../types-DSYwap42.js';
3
3
  import '../sale/index.js';
4
4
  import '../sidecar/index.js';
5
5
 
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  SIDECAR_ERROR_CLASSES
3
- } from "../chunk-JVQKJNOC.js";
3
+ } from "../chunk-ZKWVKCGJ.js";
4
4
  import {
5
5
  __name
6
6
  } from "../chunk-7QVYU63E.js";
@@ -99,6 +99,14 @@ function createSidecarIssuer(config) {
99
99
  reason,
100
100
  substituteAccessKey
101
101
  }), "cancelBySubstitution"),
102
+ linkPayment: /* @__PURE__ */ __name(({ model, environment, signing, accessKey, protocol, sequence, payments }) => call(`/${modelPath(model)}/link-payment`, {
103
+ environment,
104
+ certificate: signing.certificate,
105
+ accessKey,
106
+ protocol,
107
+ sequence,
108
+ payments
109
+ }), "linkPayment"),
102
110
  lookup: /* @__PURE__ */ __name(({ model, environment, signing, accessKey }) => call(`/${modelPath(model)}/lookup`, { environment, certificate: signing.certificate, accessKey }), "lookup"),
103
111
  inutilize: /* @__PURE__ */ __name(({ model, environment, signing, uf, cnpj, year, series, from, to, reason }) => call("/inutilize", {
104
112
  environment,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/issuer/port.ts","../../src/issuer/sidecar.ts"],"sourcesContent":["/**\n * The Issuer port: what the document service asks of whoever talks to SEFAZ.\n * The first (and today only) adapter is the fiscal service in this package's\n * `sidecar/` folder (`./sidecar`). A call never throws for a failure the\n * service classified: it answers `{ ok: false, error }` with the service's\n * class (`REJECTED`, `RETRYABLE`, `CONTINGENCY`, `AUTH`, `INVALID`,\n * `INTERNAL`), and the document service maps that onto the state machine.\n *\n * The certificate and the CSC travel with each call (the service is\n * stateless) inside {@link SigningMaterial}, built by the signing identity\n * for this one call and dropped with it.\n */\n\nimport type { FiscalDocumentModel } from \"../documents/types\";\nimport type { SaleForDocument } from \"../sale/types\";\nimport type {\n CancelledDocument,\n ContingencyEntry,\n ContingencySignedDocument,\n Csc,\n InutilizedRange,\n IssuedDocument,\n LookedUpDocument,\n SefazEnvironment,\n SidecarErrorBody,\n SidecarHealth,\n SigningCertificate,\n} from \"../sidecar/types\";\n\n/** What signs one call: the A1 and, for an NFC-e, the CSC. Never stored, never logged. */\nexport interface SigningMaterial {\n readonly certificate: SigningCertificate;\n readonly csc: Csc | null;\n}\n\n/** A failed call, classified. The service's error body, verbatim. */\nexport type IssuerFailure = SidecarErrorBody[\"error\"];\n\nexport type IssuerOutcome<T> = { readonly ok: true; readonly answer: T } | { readonly ok: false; readonly error: IssuerFailure };\n\ninterface Call {\n readonly environment: SefazEnvironment;\n readonly signing: SigningMaterial;\n}\n\nexport interface IssueCall extends Call {\n readonly model: FiscalDocumentModel;\n readonly document: SaleForDocument;\n}\n\nexport interface SignContingencyCall extends Call {\n readonly document: SaleForDocument;\n readonly contingency: ContingencyEntry;\n}\n\nexport interface TransmitCall extends Call {\n readonly model: FiscalDocumentModel;\n readonly signedXml: string;\n}\n\nexport interface CancelCall extends Call {\n readonly model: FiscalDocumentModel;\n readonly accessKey: string;\n readonly protocol: string;\n readonly reason: string;\n}\n\n/** NFC-e only: cancel an online document whose sale was issued again in contingency (event 110112). */\nexport interface CancelBySubstitutionCall extends Call {\n readonly accessKey: string;\n readonly protocol: string;\n readonly reason: string;\n readonly substituteAccessKey: string;\n}\n\nexport interface LookupCall extends Call {\n readonly model: FiscalDocumentModel;\n readonly accessKey: string;\n}\n\nexport interface InutilizeCall extends Call {\n readonly model: FiscalDocumentModel;\n readonly uf: string;\n readonly cnpj: string;\n readonly year: number;\n readonly series: number;\n readonly from: number;\n readonly to: number;\n readonly reason: string;\n}\n\nexport interface Issuer {\n /** Build, sign and transmit. `AUTHORIZED` or `DENIED`. */\n issue(call: IssueCall): Promise<IssuerOutcome<IssuedDocument>>;\n /** NFC-e only: build and sign offline (`tpEmis = 9`); nothing is sent. */\n signContingency(call: SignContingencyCall): Promise<IssuerOutcome<ContingencySignedDocument>>;\n /** Send an already signed XML (a contingency document). */\n transmit(call: TransmitCall): Promise<IssuerOutcome<IssuedDocument>>;\n cancel(call: CancelCall): Promise<IssuerOutcome<CancelledDocument>>;\n cancelBySubstitution(call: CancelBySubstitutionCall): Promise<IssuerOutcome<CancelledDocument>>;\n lookup(call: LookupCall): Promise<IssuerOutcome<LookedUpDocument>>;\n inutilize(call: InutilizeCall): Promise<IssuerOutcome<InutilizedRange>>;\n health(): Promise<SidecarHealth>;\n}\n\n/** The path segment of a model on the service's routes. */\nexport function modelPath(model: FiscalDocumentModel): \"nfe\" | \"nfce\" {\n return model === \"NFE\" ? \"nfe\" : \"nfce\";\n}\n","/**\n * The Issuer adapter over the fiscal service in this package's `sidecar/`\n * folder, speaking exactly its wire contract (`../sidecar/types`). JSON in,\n * JSON out; a non-2xx answer carries `{ error }` and is handed back\n * classified, never thrown.\n *\n * What the service cannot classify because it never answered — the fetch\n * failed, timed out or got something that is not the service's JSON — is\n * `RETRYABLE` with `outcomeUnknown: true`: the call may have reached SEFAZ, so\n * the next attempt is a retry of the SAME call, which the service settles by\n * looking the key up first. The message names the path and the HTTP status,\n * never the request: the request carries the certificate.\n */\n\nimport type {\n CancelBySubstitutionRequest,\n CancelRequest,\n InutilizeRequest,\n IssueRequest,\n LookupRequest,\n SidecarErrorBody,\n SidecarHealth,\n SignContingencyRequest,\n TransmitRequest,\n} from \"../sidecar/types\";\nimport { SIDECAR_ERROR_CLASSES } from \"../sidecar/types\";\nimport { type Issuer, type IssuerFailure, type IssuerOutcome, modelPath } from \"./port\";\n\n/** The `fetch` the adapter calls: the global one fits. */\nexport type SidecarFetch = (url: string, init: { method: string; headers: Record<string, string>; body?: string; signal?: AbortSignal }) => Promise<{\n readonly status: number;\n text(): Promise<string>;\n}>;\n\nexport interface SidecarIssuerConfig {\n /** Where the service listens, `http://fiscal-sidecar:8080`. No default. */\n readonly baseUrl: string;\n readonly fetch: SidecarFetch;\n /**\n * How long one call may take, in ms. The service gives SEFAZ its connect\n * timeout plus 20 s and may then look the key up, so this is longer than\n * both; a shorter one turns answered calls into unknown outcomes.\n */\n readonly timeoutMs: number;\n}\n\nfunction unanswered(message: string): IssuerFailure {\n return {\n class: \"RETRYABLE\",\n code: null,\n message,\n details: [],\n accessKey: null,\n signedXml: null,\n sefazReply: null,\n outcomeUnknown: true,\n };\n}\n\nfunction isErrorBody(value: unknown): value is SidecarErrorBody {\n if (value === null || typeof value !== \"object\" || !(\"error\" in value)) return false;\n const error = (value as { error: unknown }).error;\n return (\n error !== null &&\n typeof error === \"object\" &&\n SIDECAR_ERROR_CLASSES.includes((error as { class: IssuerFailure[\"class\"] }).class)\n );\n}\n\nfunction parse(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return undefined;\n }\n}\n\n/** One POST to the service, its answer classified; never throws. */\nasync function post<T>(config: SidecarIssuerConfig, base: string, path: string, body: unknown): Promise<IssuerOutcome<T>> {\n let status: number;\n let text: string;\n try {\n const response = await config.fetch(`${base}${path}`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", accept: \"application/json\" },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(config.timeoutMs),\n });\n status = response.status;\n text = await response.text();\n } catch (error) {\n const why = error instanceof Error ? error.name : \"unknown\";\n return { ok: false, error: unanswered(`POST ${path} got no answer from the fiscal service (${why}).`) };\n }\n const parsed = parse(text);\n if (status >= 200 && status < 300 && parsed !== undefined && !isErrorBody(parsed)) return { ok: true, answer: parsed as T };\n if (isErrorBody(parsed)) return { ok: false, error: parsed.error };\n return { ok: false, error: unanswered(`POST ${path} answered HTTP ${status} without the service's error body.`) };\n}\n\nexport function createSidecarIssuer(config: SidecarIssuerConfig): Issuer {\n if (typeof config?.baseUrl !== \"string\" || config.baseUrl === \"\") throw new TypeError(\"createSidecarIssuer needs baseUrl.\");\n if (typeof config.fetch !== \"function\") throw new TypeError(\"createSidecarIssuer needs fetch.\");\n if (!Number.isInteger(config.timeoutMs) || config.timeoutMs <= 0) throw new TypeError(\"createSidecarIssuer needs a positive timeoutMs.\");\n let baseEnd = config.baseUrl.length;\n while (baseEnd > 0 && config.baseUrl[baseEnd - 1] === \"/\") baseEnd -= 1;\n const base = config.baseUrl.slice(0, baseEnd);\n\n const call = <T>(path: string, body: unknown) => post<T>(config, base, path, body);\n\n return {\n issue: ({ model, environment, signing, document }) =>\n call(`/${modelPath(model)}/issue`, {\n environment,\n certificate: signing.certificate,\n csc: model === \"NFCE\" ? signing.csc : null,\n document,\n } satisfies IssueRequest),\n signContingency: ({ environment, signing, document, contingency }) =>\n call(\"/nfce/sign-contingency\", {\n environment,\n certificate: signing.certificate,\n csc: signing.csc,\n document,\n contingency,\n } satisfies SignContingencyRequest),\n transmit: ({ model, environment, signing, signedXml }) =>\n call(`/${modelPath(model)}/transmit`, { environment, certificate: signing.certificate, signedXml } satisfies TransmitRequest),\n cancel: ({ model, environment, signing, accessKey, protocol, reason }) =>\n call(`/${modelPath(model)}/cancel`, {\n environment,\n certificate: signing.certificate,\n accessKey,\n protocol,\n reason,\n } satisfies CancelRequest),\n cancelBySubstitution: ({ environment, signing, accessKey, protocol, reason, substituteAccessKey }) =>\n call(\"/nfce/cancel-substitution\", {\n environment,\n certificate: signing.certificate,\n accessKey,\n protocol,\n reason,\n substituteAccessKey,\n } satisfies CancelBySubstitutionRequest),\n lookup: ({ model, environment, signing, accessKey }) =>\n call(`/${modelPath(model)}/lookup`, { environment, certificate: signing.certificate, accessKey } satisfies LookupRequest),\n inutilize: ({ model, environment, signing, uf, cnpj, year, series, from, to, reason }) =>\n call(\"/inutilize\", {\n environment,\n certificate: signing.certificate,\n model: modelPath(model),\n uf,\n cnpj,\n year,\n series,\n from,\n to,\n reason,\n } satisfies InutilizeRequest),\n async health() {\n const response = await config.fetch(`${base}/health`, {\n method: \"GET\",\n headers: { accept: \"application/json\" },\n signal: AbortSignal.timeout(config.timeoutMs),\n });\n if (response.status !== 200) throw new Error(`The fiscal service's /health answered HTTP ${response.status}.`);\n return JSON.parse(await response.text()) as SidecarHealth;\n },\n };\n}\n"],"mappings":";;;;;;;;AA0GO,SAAS,UAAU,OAA4C;AACpE,SAAO,UAAU,QAAQ,QAAQ;AACnC;AAFgB;;;AC5DhB,SAAS,WAAW,SAAgC;AAClD,SAAO;AAAA,IACL,OAAO;AAAA,IACP,MAAM;AAAA,IACN;AAAA,IACA,SAAS,CAAC;AAAA,IACV,WAAW;AAAA,IACX,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,gBAAgB;AAAA,EAClB;AACF;AAXS;AAaT,SAAS,YAAY,OAA2C;AAC9D,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,EAAE,WAAW,OAAQ,QAAO;AAC/E,QAAM,QAAS,MAA6B;AAC5C,SACE,UAAU,QACV,OA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AuC,GARnB;AAAA,IAStB,QAAQ,wBAAC,EAAE,OAAO,aAAa,SAAS,UAAU,MAChD,KAAK,IAAI,UAAU,KAAK,CAAC,WAAW,EAAE,aAAa,aAAa,QAAQ,aAAa,UAAU,CAAyB,GADlH;AAAA,IAER,WAAW,wBAAC,EAAE,OAAO,aAAa,SAAS,IAAI,MAAM,MAAM,QAAQ,MAAM,IAAI,OAAO,MAClF,KAAK,cAAc;AAAA,MACjB;AAAA,MACA,aAAa,QAAQ;AAAA,MACrB,OAAO,UAAU,KAAK;AAAA,MACtB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAA4B,GAZnB;AAAA,IAaX,MAAM,SAAS;AACb,YAAM,WAAW,MAAM,OAAO,MAAM,GAAG,IAAI,WAAW;AAAA,QACpD,QAAQ;AAAA,QACR,SAAS,EAAE,QAAQ,mBAAmB;AAAA,QACtC,QAAQ,YAAY,QAAQ,OAAO,SAAS;AAAA,MAC9C,CAAC;AACD,UAAI,SAAS,WAAW,IAAK,OAAM,IAAI,MAAM,8CAA8C,SAAS,MAAM,GAAG;AAC7G,aAAO,KAAK,MAAM,MAAM,SAAS,KAAK,CAAC;AAAA,IACzC;AAAA,EACF;AACF;AAtEgB;","names":[]}
1
+ {"version":3,"sources":["../../src/issuer/port.ts","../../src/issuer/sidecar.ts"],"sourcesContent":["/**\n * The Issuer port: what the document service asks of whoever talks to SEFAZ.\n * The first (and today only) adapter is the fiscal service in this package's\n * `sidecar/` folder (`./sidecar`). A call never throws for a failure the\n * service classified: it answers `{ ok: false, error }` with the service's\n * class (`REJECTED`, `RETRYABLE`, `CONTINGENCY`, `AUTH`, `INVALID`,\n * `INTERNAL`), and the document service maps that onto the state machine.\n *\n * The certificate and the CSC travel with each call (the service is\n * stateless) inside {@link SigningMaterial}, built by the signing identity\n * for this one call and dropped with it.\n */\n\nimport type { FiscalDocumentModel } from \"../documents/types\";\nimport type { LinkedTransaction, SaleForDocument } from \"../sale/types\";\nimport type {\n CancelledDocument,\n ContingencyEntry,\n ContingencySignedDocument,\n Csc,\n InutilizedRange,\n IssuedDocument,\n LookedUpDocument,\n RegisteredPaymentLink,\n SefazEnvironment,\n SidecarErrorBody,\n SidecarHealth,\n SigningCertificate,\n} from \"../sidecar/types\";\n\n/** What signs one call: the A1 and, for an NFC-e, the CSC. Never stored, never logged. */\nexport interface SigningMaterial {\n readonly certificate: SigningCertificate;\n readonly csc: Csc | null;\n}\n\n/** A failed call, classified. The service's error body, verbatim. */\nexport type IssuerFailure = SidecarErrorBody[\"error\"];\n\nexport type IssuerOutcome<T> = { readonly ok: true; readonly answer: T } | { readonly ok: false; readonly error: IssuerFailure };\n\ninterface Call {\n readonly environment: SefazEnvironment;\n readonly signing: SigningMaterial;\n}\n\nexport interface IssueCall extends Call {\n readonly model: FiscalDocumentModel;\n readonly document: SaleForDocument;\n}\n\nexport interface SignContingencyCall extends Call {\n readonly document: SaleForDocument;\n readonly contingency: ContingencyEntry;\n}\n\nexport interface TransmitCall extends Call {\n readonly model: FiscalDocumentModel;\n readonly signedXml: string;\n}\n\nexport interface CancelCall extends Call {\n readonly model: FiscalDocumentModel;\n readonly accessKey: string;\n readonly protocol: string;\n readonly reason: string;\n}\n\n/** NFC-e only: cancel an online document whose sale was issued again in contingency (event 110112). */\nexport interface CancelBySubstitutionCall extends Call {\n readonly accessKey: string;\n readonly protocol: string;\n readonly reason: string;\n readonly substituteAccessKey: string;\n}\n\n/** The event 110300 \"Vinculação Pagamento\" (NT 2026.006 v1.00): one transaction linked to an authorised document. */\nexport interface LinkPaymentCall extends Call {\n readonly model: FiscalDocumentModel;\n readonly accessKey: string;\n readonly protocol: string;\n /** `nSeqEvento`, 1–20. */\n readonly sequence: number;\n /**\n * The transactions the event links. Exactly ONE today: the event's schema\n * (`e110300_v1.00.xsd`) carries a single `gPgto`, so the service refuses any\n * other count as INVALID; the list is the NT group's own shape.\n */\n readonly payments: readonly LinkedTransaction[];\n}\n\nexport interface LookupCall extends Call {\n readonly model: FiscalDocumentModel;\n readonly accessKey: string;\n}\n\nexport interface InutilizeCall extends Call {\n readonly model: FiscalDocumentModel;\n readonly uf: string;\n readonly cnpj: string;\n readonly year: number;\n readonly series: number;\n readonly from: number;\n readonly to: number;\n readonly reason: string;\n}\n\nexport interface Issuer {\n /** Build, sign and transmit. `AUTHORIZED` or `DENIED`. */\n issue(call: IssueCall): Promise<IssuerOutcome<IssuedDocument>>;\n /** NFC-e only: build and sign offline (`tpEmis = 9`); nothing is sent. */\n signContingency(call: SignContingencyCall): Promise<IssuerOutcome<ContingencySignedDocument>>;\n /** Send an already signed XML (a contingency document). */\n transmit(call: TransmitCall): Promise<IssuerOutcome<IssuedDocument>>;\n cancel(call: CancelCall): Promise<IssuerOutcome<CancelledDocument>>;\n cancelBySubstitution(call: CancelBySubstitutionCall): Promise<IssuerOutcome<CancelledDocument>>;\n lookup(call: LookupCall): Promise<IssuerOutcome<LookedUpDocument>>;\n /**\n * The event 110300. Optional on the port so an issuer written before it\n * still satisfies the type; one that lacks it cannot link (the document\n * service answers `NOT_SUPPORTED`), and a host may read its presence as\n * \"this issuer writes `gPgtoVinc`\".\n */\n linkPayment?(call: LinkPaymentCall): Promise<IssuerOutcome<RegisteredPaymentLink>>;\n inutilize(call: InutilizeCall): Promise<IssuerOutcome<InutilizedRange>>;\n health(): Promise<SidecarHealth>;\n}\n\n/** The path segment of a model on the service's routes. */\nexport function modelPath(model: FiscalDocumentModel): \"nfe\" | \"nfce\" {\n return model === \"NFE\" ? \"nfe\" : \"nfce\";\n}\n","/**\n * The Issuer adapter over the fiscal service in this package's `sidecar/`\n * folder, speaking exactly its wire contract (`../sidecar/types`). JSON in,\n * JSON out; a non-2xx answer carries `{ error }` and is handed back\n * classified, never thrown.\n *\n * What the service cannot classify because it never answered — the fetch\n * failed, timed out or got something that is not the service's JSON — is\n * `RETRYABLE` with `outcomeUnknown: true`: the call may have reached SEFAZ, so\n * the next attempt is a retry of the SAME call, which the service settles by\n * looking the key up first. The message names the path and the HTTP status,\n * never the request: the request carries the certificate.\n */\n\nimport type {\n CancelBySubstitutionRequest,\n CancelRequest,\n InutilizeRequest,\n IssueRequest,\n LinkPaymentRequest,\n LookupRequest,\n SidecarErrorBody,\n SidecarHealth,\n SignContingencyRequest,\n TransmitRequest,\n} from \"../sidecar/types\";\nimport { SIDECAR_ERROR_CLASSES } from \"../sidecar/types\";\nimport { type Issuer, type IssuerFailure, type IssuerOutcome, modelPath } from \"./port\";\n\n/** The `fetch` the adapter calls: the global one fits. */\nexport type SidecarFetch = (url: string, init: { method: string; headers: Record<string, string>; body?: string; signal?: AbortSignal }) => Promise<{\n readonly status: number;\n text(): Promise<string>;\n}>;\n\nexport interface SidecarIssuerConfig {\n /** Where the service listens, `http://fiscal-sidecar:8080`. No default. */\n readonly baseUrl: string;\n readonly fetch: SidecarFetch;\n /**\n * How long one call may take, in ms. The service gives SEFAZ its connect\n * timeout plus 20 s and may then look the key up, so this is longer than\n * both; a shorter one turns answered calls into unknown outcomes.\n */\n readonly timeoutMs: number;\n}\n\nfunction unanswered(message: string): IssuerFailure {\n return {\n class: \"RETRYABLE\",\n code: null,\n message,\n details: [],\n accessKey: null,\n signedXml: null,\n sefazReply: null,\n outcomeUnknown: true,\n };\n}\n\nfunction isErrorBody(value: unknown): value is SidecarErrorBody {\n if (value === null || typeof value !== \"object\" || !(\"error\" in value)) return false;\n const error = (value as { error: unknown }).error;\n return (\n error !== null &&\n typeof error === \"object\" &&\n SIDECAR_ERROR_CLASSES.includes((error as { class: IssuerFailure[\"class\"] }).class)\n );\n}\n\nfunction parse(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return undefined;\n }\n}\n\n/** One POST to the service, its answer classified; never throws. */\nasync function post<T>(config: SidecarIssuerConfig, base: string, path: string, body: unknown): Promise<IssuerOutcome<T>> {\n let status: number;\n let text: string;\n try {\n const response = await config.fetch(`${base}${path}`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", accept: \"application/json\" },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(config.timeoutMs),\n });\n status = response.status;\n text = await response.text();\n } catch (error) {\n const why = error instanceof Error ? error.name : \"unknown\";\n return { ok: false, error: unanswered(`POST ${path} got no answer from the fiscal service (${why}).`) };\n }\n const parsed = parse(text);\n if (status >= 200 && status < 300 && parsed !== undefined && !isErrorBody(parsed)) return { ok: true, answer: parsed as T };\n if (isErrorBody(parsed)) return { ok: false, error: parsed.error };\n return { ok: false, error: unanswered(`POST ${path} answered HTTP ${status} without the service's error body.`) };\n}\n\nexport function createSidecarIssuer(config: SidecarIssuerConfig): Issuer {\n if (typeof config?.baseUrl !== \"string\" || config.baseUrl === \"\") throw new TypeError(\"createSidecarIssuer needs baseUrl.\");\n if (typeof config.fetch !== \"function\") throw new TypeError(\"createSidecarIssuer needs fetch.\");\n if (!Number.isInteger(config.timeoutMs) || config.timeoutMs <= 0) throw new TypeError(\"createSidecarIssuer needs a positive timeoutMs.\");\n let baseEnd = config.baseUrl.length;\n while (baseEnd > 0 && config.baseUrl[baseEnd - 1] === \"/\") baseEnd -= 1;\n const base = config.baseUrl.slice(0, baseEnd);\n\n const call = <T>(path: string, body: unknown) => post<T>(config, base, path, body);\n\n return {\n issue: ({ model, environment, signing, document }) =>\n call(`/${modelPath(model)}/issue`, {\n environment,\n certificate: signing.certificate,\n csc: model === \"NFCE\" ? signing.csc : null,\n document,\n } satisfies IssueRequest),\n signContingency: ({ environment, signing, document, contingency }) =>\n call(\"/nfce/sign-contingency\", {\n environment,\n certificate: signing.certificate,\n csc: signing.csc,\n document,\n contingency,\n } satisfies SignContingencyRequest),\n transmit: ({ model, environment, signing, signedXml }) =>\n call(`/${modelPath(model)}/transmit`, { environment, certificate: signing.certificate, signedXml } satisfies TransmitRequest),\n cancel: ({ model, environment, signing, accessKey, protocol, reason }) =>\n call(`/${modelPath(model)}/cancel`, {\n environment,\n certificate: signing.certificate,\n accessKey,\n protocol,\n reason,\n } satisfies CancelRequest),\n cancelBySubstitution: ({ environment, signing, accessKey, protocol, reason, substituteAccessKey }) =>\n call(\"/nfce/cancel-substitution\", {\n environment,\n certificate: signing.certificate,\n accessKey,\n protocol,\n reason,\n substituteAccessKey,\n } satisfies CancelBySubstitutionRequest),\n linkPayment: ({ model, environment, signing, accessKey, protocol, sequence, payments }) =>\n call(`/${modelPath(model)}/link-payment`, {\n environment,\n certificate: signing.certificate,\n accessKey,\n protocol,\n sequence,\n payments,\n } satisfies LinkPaymentRequest),\n lookup: ({ model, environment, signing, accessKey }) =>\n call(`/${modelPath(model)}/lookup`, { environment, certificate: signing.certificate, accessKey } satisfies LookupRequest),\n inutilize: ({ model, environment, signing, uf, cnpj, year, series, from, to, reason }) =>\n call(\"/inutilize\", {\n environment,\n certificate: signing.certificate,\n model: modelPath(model),\n uf,\n cnpj,\n year,\n series,\n from,\n to,\n reason,\n } satisfies InutilizeRequest),\n async health() {\n const response = await config.fetch(`${base}/health`, {\n method: \"GET\",\n headers: { accept: \"application/json\" },\n signal: AbortSignal.timeout(config.timeoutMs),\n });\n if (response.status !== 200) throw new Error(`The fiscal service's /health answered HTTP ${response.status}.`);\n return JSON.parse(await response.text()) as SidecarHealth;\n },\n };\n}\n"],"mappings":";;;;;;;;AAiIO,SAAS,UAAU,OAA4C;AACpE,SAAO,UAAU,QAAQ,QAAQ;AACnC;AAFgB;;;AClFhB,SAAS,WAAW,SAAgC;AAClD,SAAO;AAAA,IACL,OAAO;AAAA,IACP,MAAM;AAAA,IACN;AAAA,IACA,SAAS,CAAC;AAAA,IACV,WAAW;AAAA,IACX,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,gBAAgB;AAAA,EAClB;AACF;AAXS;AAaT,SAAS,YAAY,OAA2C;AAC9D,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,EAAE,WAAW,OAAQ,QAAO;AAC/E,QAAM,QAAS,MAA6B;AAC5C,SACE,UAAU,QACV,OAAO,UAAU,YACjB,sBAAsB,SAAU,MA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AC,EAAE,OAAO,aAAa,SAAS,WAAW,UAAU,UAAU,SAAS,MACnF,KAAK,IAAI,UAAU,KAAK,CAAC,iBAAiB;AAAA,MACxC;AAAA,MACA,aAAa,QAAQ;AAAA,MACrB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAA8B,GARnB;AAAA,IASb,QAAQ,wBAAC,EAAE,OAAO,aAAa,SAAS,UAAU,MAChD,KAAK,IAAI,UAAU,KAAK,CAAC,WAAW,EAAE,aAAa,aAAa,QAAQ,aAAa,UAAU,CAAyB,GADlH;AAAA,IAER,WAAW,wBAAC,EAAE,OAAO,aAAa,SAAS,IAAI,MAAM,MAAM,QAAQ,MAAM,IAAI,OAAO,MAClF,KAAK,cAAc;AAAA,MACjB;AAAA,MACA,aAAa,QAAQ;AAAA,MACrB,OAAO,UAAU,KAAK;AAAA,MACtB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAA4B,GAZnB;AAAA,IAaX,MAAM,SAAS;AACb,YAAM,WAAW,MAAM,OAAO,MAAM,GAAG,IAAI,WAAW;AAAA,QACpD,QAAQ;AAAA,QACR,SAAS,EAAE,QAAQ,mBAAmB;AAAA,QACtC,QAAQ,YAAY,QAAQ,OAAO,SAAS;AAAA,MAC9C,CAAC;AACD,UAAI,SAAS,WAAW,IAAK,OAAM,IAAI,MAAM,8CAA8C,SAAS,MAAM,GAAG;AAC7G,aAAO,KAAK,MAAM,MAAM,SAAS,KAAK,CAAC;AAAA,IACzC;AAAA,EACF;AACF;AA/EgB;","names":[]}
package/dist/jobs.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as _12_apps_wiring from '@12-apps/wiring';
2
- import { F as FiscalStore, a as FiscalNotifyPort } from './context-CLSMOSuf.js';
3
- import { F as FiscalDocuments } from './service-hR3tgLpO.js';
4
- import './types-BIJqm5GM.js';
2
+ import { F as FiscalStore, a as FiscalNotifyPort } from './context-CwZiHLnY.js';
3
+ import { F as FiscalDocuments } from './service-Cz2O84Xr.js';
4
+ import './types-DSYwap42.js';
5
5
  import './sale/index.js';
6
6
  import './sidecar/index.js';
7
7
  import './types-B1b8LIWX.js';
package/dist/jobs.js CHANGED
@@ -5,9 +5,9 @@ import {
5
5
  FISCAL_SWEEP_BATCH,
6
6
  FISCAL_WORST_STEP_MS,
7
7
  daysLeft
8
- } from "./chunk-OSYB7CVT.js";
9
- import "./chunk-2ISYBTCE.js";
10
- import "./chunk-GF3DXCD2.js";
8
+ } from "./chunk-G6QNU4FD.js";
9
+ import "./chunk-3E3NBXSW.js";
10
+ import "./chunk-GH452ITO.js";
11
11
  import "./chunk-3SDXLSG4.js";
12
12
  import "./chunk-H33BK623.js";
13
13
  import "./chunk-7QVYU63E.js";
@@ -1,12 +1,12 @@
1
1
  import * as _12_apps_wiring from '@12-apps/wiring';
2
2
  import { FiscalJobDeps } from '../jobs.js';
3
3
  import { createApiFiscal } from '../http.js';
4
- import '../context-CLSMOSuf.js';
5
- import '../types-BIJqm5GM.js';
4
+ import '../context-CwZiHLnY.js';
5
+ import '../types-DSYwap42.js';
6
6
  import '../sale/index.js';
7
7
  import '../sidecar/index.js';
8
8
  import '../types-B1b8LIWX.js';
9
- import '../service-hR3tgLpO.js';
9
+ import '../service-Cz2O84Xr.js';
10
10
  import '../labels-BNvflT0h.js';
11
11
 
12
12
  declare const fiscalServerManifest: {
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  createApiFiscal
3
- } from "../chunk-F2PGQVWL.js";
3
+ } from "../chunk-TJCUO6D6.js";
4
4
  import "../chunk-MGTROA7K.js";
5
- import "../chunk-EDEGIADD.js";
5
+ import "../chunk-HMTPJWXM.js";
6
6
  import "../chunk-PNTKG3DZ.js";
7
7
  import {
8
8
  FISCAL_JOBS
9
- } from "../chunk-OSYB7CVT.js";
10
- import "../chunk-2ISYBTCE.js";
11
- import "../chunk-GF3DXCD2.js";
9
+ } from "../chunk-G6QNU4FD.js";
10
+ import "../chunk-3E3NBXSW.js";
11
+ import "../chunk-GH452ITO.js";
12
12
  import "../chunk-3SDXLSG4.js";
13
13
  import "../chunk-H33BK623.js";
14
14
  import "../chunk-7QVYU63E.js";
@@ -1,5 +1,5 @@
1
- export { b as FISCAL_CERTIFICATE_EXPIRING, c as FISCAL_CONTINGENCY_DEADLINE, d as FISCAL_DOCUMENT_NEEDS_ATTENTION, e as FISCAL_DOCUMENT_REJECTED } from './context-CLSMOSuf.js';
2
- import { F as FiscalDocumentModel, g as FiscalDocumentStatus, N as NumberVoid } from './types-BIJqm5GM.js';
1
+ export { b as FISCAL_CERTIFICATE_EXPIRING, c as FISCAL_CONTINGENCY_DEADLINE, d as FISCAL_DOCUMENT_NEEDS_ATTENTION, e as FISCAL_DOCUMENT_REJECTED } from './context-CwZiHLnY.js';
2
+ import { F as FiscalDocumentModel, h as FiscalDocumentStatus, N as NumberVoid } from './types-DSYwap42.js';
3
3
  import './sale/index.js';
4
4
  import './sidecar/index.js';
5
5
  import './types-B1b8LIWX.js';
@@ -3,8 +3,8 @@ import {
3
3
  FISCAL_CONTINGENCY_DEADLINE,
4
4
  FISCAL_DOCUMENT_NEEDS_ATTENTION,
5
5
  FISCAL_DOCUMENT_REJECTED
6
- } from "./chunk-2ISYBTCE.js";
7
- import "./chunk-GF3DXCD2.js";
6
+ } from "./chunk-3E3NBXSW.js";
7
+ import "./chunk-GH452ITO.js";
8
8
  import "./chunk-3SDXLSG4.js";
9
9
  import "./chunk-H33BK623.js";
10
10
  import {
@@ -173,6 +173,27 @@ interface CardDetails {
173
173
  /** `cAut`. */
174
174
  readonly authorizationCode: string | null;
175
175
  }
176
+ /**
177
+ * `tpMeioPgto` (Informe Técnico 2026.001 v1.01): the means a linked payment
178
+ * transaction moved by — 15 boleto, 17 Pix QR dinâmico, 18 TED, 20 Pix by key
179
+ * or static QR, 23 Pix automático, 24 TEF. A card and cash have none.
180
+ */
181
+ declare const PAYMENT_LINK_MEANS: readonly ["15", "17", "18", "20", "23", "24"];
182
+ type PaymentLinkMeans = (typeof PAYMENT_LINK_MEANS)[number];
183
+ /**
184
+ * `gPgtoVinc/gPgto` (NT 2026.006 v1.00): a payment transaction started before
185
+ * the document — a Pix QR raised, a boleto generated — linked by its id, so the
186
+ * split payment can find the document. The event 110300 links one after the fact.
187
+ */
188
+ interface LinkedTransaction {
189
+ /** `idTransacao`, 2–35 characters: the Pix txid, the boleto's or the transfer's id. */
190
+ readonly transactionId: string;
191
+ readonly meansCode: PaymentLinkMeans;
192
+ /** `CNPJBasePSP`: the 8-character CNPJ base of the receiver's payment institution. */
193
+ readonly pspCnpjBase: string;
194
+ /** `CNPJReceb`: who receives the money (the issuer, or a platform receiving for it). */
195
+ readonly receiverCnpj: string;
196
+ }
176
197
  interface SalePayment {
177
198
  readonly method: PaymentMethod;
178
199
  readonly amountCents: number;
@@ -180,6 +201,13 @@ interface SalePayment {
180
201
  readonly card: CardDetails | null;
181
202
  /** `xPag`: required when `method` is `OTHER`. */
182
203
  readonly description: string | null;
204
+ /**
205
+ * The transaction this payment was started as, written in `gPgtoVinc` with
206
+ * `nPag` = its position. Absent or `null`: no link. The host decides whether
207
+ * the environment accepts the group (optional in the layout; its production
208
+ * activation is the fisco's).
209
+ */
210
+ readonly linkedTransaction?: LinkedTransaction | null;
183
211
  }
184
212
  /** `finNFe` 1–4. */
185
213
  type DocumentPurpose = "NORMAL" | "COMPLEMENTARY" | "ADJUSTMENT" | "RETURN";
@@ -266,4 +294,4 @@ interface SaleForDocument {
266
294
  readonly technicalResponsible: TechnicalResponsible | null;
267
295
  }
268
296
 
269
- export type { Address, BuyerDocument, BuyerPresence, CardDetails, ContributionCst, DocumentBuyer, DocumentIssuer, DocumentOperation, DocumentPurpose, FreightMode, GoodsOrigin, IbsCbsFigures, IcmsSimples, IcmsSimplesWithCredit, IcmsTaxed, IcmsUntaxed, IssuerTaxRegime, LineContribution, LineIbsCbs, LineIcms, OperationDestination, PaymentMethod, ReferencedDocument, SaleForDocument, SaleIntermediary, SaleLine, SalePayment, StateRegistrationStatus, TechnicalResponsible, Uf };
297
+ export { type Address, type BuyerDocument, type BuyerPresence, type CardDetails, type ContributionCst, type DocumentBuyer, type DocumentIssuer, type DocumentOperation, type DocumentPurpose, type FreightMode, type GoodsOrigin, type IbsCbsFigures, type IcmsSimples, type IcmsSimplesWithCredit, type IcmsTaxed, type IcmsUntaxed, type IssuerTaxRegime, type LineContribution, type LineIbsCbs, type LineIcms, type LinkedTransaction, type OperationDestination, PAYMENT_LINK_MEANS, type PaymentLinkMeans, type PaymentMethod, type ReferencedDocument, type SaleForDocument, type SaleIntermediary, type SaleLine, type SalePayment, type StateRegistrationStatus, type TechnicalResponsible, type Uf };
@@ -1 +1,8 @@
1
+ import "../chunk-7QVYU63E.js";
2
+
3
+ // src/sale/types.ts
4
+ var PAYMENT_LINK_MEANS = ["15", "17", "18", "20", "23", "24"];
5
+ export {
6
+ PAYMENT_LINK_MEANS
7
+ };
1
8
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
1
+ {"version":3,"sources":["../../src/sale/types.ts"],"sourcesContent":["/**\n * The neutral document shape: one sale, host-agnostic, as the fiscal service\n * (`sidecar/`) accepts it and as the issuer port maps a host's sale into it.\n *\n * Money is integer CENTS, rates integer BASIS POINTS (1 bp = 0.01%) — the\n * engine's conventions (`@12-apps/fiscal/engine`) — and quantities carry at\n * most four decimals. Every field is required; an absent value is `null`,\n * never a missing key, so a host cannot forget one silently. The two\n * exceptions came with the return document (FUT-2238), `operation` and\n * `referencedDocuments`: they are optional so that a document built before\n * them stays valid and yields the same XML, byte for byte.\n *\n * The JSON schema the service validates against is\n * `@12-apps/fiscal/sidecar/schema/sale-for-document.schema.json`; a test keeps\n * it and these types in step. Whether the sale becomes an NF-e (model 55) or\n * an NFC-e (model 65) is the request path's choice, never this document's.\n */\n\n/** The 27 federative units. */\nexport type Uf =\n | \"AC\" | \"AL\" | \"AM\" | \"AP\" | \"BA\" | \"CE\" | \"DF\" | \"ES\" | \"GO\" | \"MA\" | \"MG\" | \"MS\" | \"MT\" | \"PA\"\n | \"PB\" | \"PE\" | \"PI\" | \"PR\" | \"RJ\" | \"RN\" | \"RO\" | \"RR\" | \"RS\" | \"SC\" | \"SE\" | \"SP\" | \"TO\";\n\n/** A postal address. `postalCode` is required on the issuer's. */\nexport interface Address {\n readonly street: string;\n readonly number: string;\n readonly complement: string | null;\n readonly district: string;\n /** The 7-digit IBGE municipality code. */\n readonly municipalityIbge: string;\n readonly municipalityName: string;\n readonly uf: Uf;\n /** CEP, 8 digits. */\n readonly postalCode: string | null;\n readonly phone: string | null;\n}\n\n/** The issuer's tax regime on the document (`CRT` 1, 2, 3, 4). */\nexport type IssuerTaxRegime = \"SIMPLES\" | \"SIMPLES_EXCESS\" | \"NORMAL\" | \"MEI\";\n\nexport interface DocumentIssuer {\n /** 14 characters; the 2026 alphanumeric CNPJ is accepted. */\n readonly cnpj: string;\n /** IE digits, or `ISENTO`. */\n readonly stateRegistration: string;\n readonly legalName: string;\n readonly tradeName: string | null;\n readonly taxRegime: IssuerTaxRegime;\n readonly address: Address & { readonly postalCode: string };\n}\n\nexport type BuyerDocument =\n | { readonly kind: \"CPF\"; readonly number: string }\n | { readonly kind: \"CNPJ\"; readonly number: string }\n | { readonly kind: \"FOREIGN\"; readonly number: string };\n\n/** `indIEDest` 1, 2, 9. */\nexport type StateRegistrationStatus = \"CONTRIBUTOR\" | \"EXEMPT\" | \"NON_CONTRIBUTOR\";\n\nexport interface DocumentBuyer {\n readonly document: BuyerDocument;\n readonly name: string | null;\n readonly stateRegistrationStatus: StateRegistrationStatus;\n readonly stateRegistration: string | null;\n readonly email: string | null;\n readonly address: Address | null;\n}\n\n/** The goods' origin (`orig`), 0–8. */\nexport type GoodsOrigin = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;\n\n/** ICMS of a Simples Nacional issuer, without a credit. */\nexport interface IcmsSimples {\n readonly regime: \"SIMPLES\";\n readonly origin: GoodsOrigin;\n readonly csosn: \"102\" | \"103\" | \"300\" | \"400\" | \"500\";\n}\n\n/** ICMS of a Simples Nacional issuer that grants the buyer a credit (CSOSN 101). */\nexport interface IcmsSimplesWithCredit {\n readonly regime: \"SIMPLES\";\n readonly origin: GoodsOrigin;\n readonly csosn: \"101\";\n readonly creditRateBp: number;\n readonly creditCents: number;\n}\n\n/** ICMS fully taxed (CST 00). */\nexport interface IcmsTaxed {\n readonly regime: \"NORMAL\";\n readonly origin: GoodsOrigin;\n readonly cst: \"00\";\n readonly baseCents: number;\n readonly rateBp: number;\n readonly amountCents: number;\n}\n\n/** ICMS exempt, not taxed, suspended (40, 41, 50) or collected before by substitution (60). */\nexport interface IcmsUntaxed {\n readonly regime: \"NORMAL\";\n readonly origin: GoodsOrigin;\n readonly cst: \"40\" | \"41\" | \"50\" | \"60\";\n}\n\nexport type LineIcms = IcmsSimples | IcmsSimplesWithCredit | IcmsTaxed | IcmsUntaxed;\n\n/** The PIS and COFINS situation codes the layout accepts on an outgoing document. */\nexport type ContributionCst =\n | \"01\" | \"02\" | \"04\" | \"05\" | \"06\" | \"07\" | \"08\" | \"09\" | \"49\" | \"50\" | \"51\" | \"52\" | \"53\" | \"54\"\n | \"55\" | \"56\" | \"60\" | \"61\" | \"62\" | \"63\" | \"64\" | \"65\" | \"66\" | \"67\" | \"70\" | \"71\" | \"72\" | \"73\"\n | \"74\" | \"75\" | \"98\" | \"99\";\n\n/**\n * PIS or COFINS. CST 01/02 write the base, the rate and the amount; 04–09\n * write none (send zeros); 49–99 write all three.\n */\nexport interface LineContribution {\n readonly cst: ContributionCst;\n readonly baseCents: number;\n readonly rateBp: number;\n readonly amountCents: number;\n}\n\n/**\n * The IBS/CBS figures of one line — what the engine's `LineTax` carries:\n * `vBC` and, per tax, the NOMINAL rate and the amount. `reductionBp` applies\n * to all three rates (`pRedAliq`; the effective rate is written beside it).\n */\nexport interface IbsCbsFigures {\n readonly baseCents: number;\n readonly reductionBp: number;\n readonly cbsRateBp: number;\n readonly cbsCents: number;\n readonly ibsUfRateBp: number;\n readonly ibsUfCents: number;\n readonly ibsMunRateBp: number;\n readonly ibsMunCents: number;\n}\n\n/** The IBS/CBS group of a line. `figures: null` writes the CST and class only (immunity, say). */\nexport interface LineIbsCbs {\n /** `CST` of the IBS/CBS, 3 digits. */\n readonly cst: string;\n /** `cClassTrib`, 6 digits. */\n readonly classCode: string;\n readonly figures: IbsCbsFigures | null;\n}\n\n/** One item of the document. */\nexport interface SaleLine {\n /** The host's id; quoted back in a mapping error. */\n readonly id: string;\n /** `cProd`. */\n readonly code: string;\n /** GTIN/EAN, or `null` for \"SEM GTIN\". */\n readonly gtin: string | null;\n readonly description: string;\n readonly ncm: string;\n readonly cest: string | null;\n readonly cfop: string;\n /** `uCom` and `uTrib`. */\n readonly unit: string;\n /** `qCom` and `qTrib`: positive, at most four decimals. */\n readonly quantity: number;\n /** `vProd`: every unit, BEFORE the line's discount. The unit value is derived. */\n readonly valueCents: number;\n /** `vDesc`. */\n readonly discountCents: number;\n /** `vTotTrib` (the approximate tax of the transparency law), or `null`. */\n readonly approximateTaxCents: number | null;\n /** `infAdProd`. */\n readonly additionalInfo: string | null;\n readonly icms: LineIcms;\n readonly pis: LineContribution;\n readonly cofins: LineContribution;\n /** `null` writes no IBS/CBS group — a regime the engine answered `NONE` for. */\n readonly ibsCbs: LineIbsCbs | null;\n}\n\n/** `tPag`. */\nexport type PaymentMethod =\n | \"CASH\"\n | \"CHECK\"\n | \"CREDIT_CARD\"\n | \"DEBIT_CARD\"\n | \"STORE_CREDIT\"\n | \"FOOD_VOUCHER\"\n | \"MEAL_VOUCHER\"\n | \"GIFT_VOUCHER\"\n | \"FUEL_VOUCHER\"\n | \"BANK_SLIP\"\n | \"BANK_DEPOSIT\"\n | \"PIX_DYNAMIC\"\n | \"TRANSFER\"\n | \"LOYALTY\"\n | \"PIX_STATIC\"\n | \"NO_PAYMENT\"\n | \"OTHER\";\n\nexport interface CardDetails {\n /** `tpIntegra`: whether the payment went through an integrated terminal. */\n readonly integrated: boolean;\n readonly acquirerCnpj: string | null;\n /** `tBand`, 2 digits. */\n readonly brand: string | null;\n /** `cAut`. */\n readonly authorizationCode: string | null;\n}\n\n/**\n * `tpMeioPgto` (Informe Técnico 2026.001 v1.01): the means a linked payment\n * transaction moved by — 15 boleto, 17 Pix QR dinâmico, 18 TED, 20 Pix by key\n * or static QR, 23 Pix automático, 24 TEF. A card and cash have none.\n */\nexport const PAYMENT_LINK_MEANS = [\"15\", \"17\", \"18\", \"20\", \"23\", \"24\"] as const;\nexport type PaymentLinkMeans = (typeof PAYMENT_LINK_MEANS)[number];\n\n/**\n * `gPgtoVinc/gPgto` (NT 2026.006 v1.00): a payment transaction started before\n * the document — a Pix QR raised, a boleto generated — linked by its id, so the\n * split payment can find the document. The event 110300 links one after the fact.\n */\nexport interface LinkedTransaction {\n /** `idTransacao`, 2–35 characters: the Pix txid, the boleto's or the transfer's id. */\n readonly transactionId: string;\n readonly meansCode: PaymentLinkMeans;\n /** `CNPJBasePSP`: the 8-character CNPJ base of the receiver's payment institution. */\n readonly pspCnpjBase: string;\n /** `CNPJReceb`: who receives the money (the issuer, or a platform receiving for it). */\n readonly receiverCnpj: string;\n}\n\nexport interface SalePayment {\n readonly method: PaymentMethod;\n readonly amountCents: number;\n /** Required by the layout for a card and for a Pix; `null` otherwise. */\n readonly card: CardDetails | null;\n /** `xPag`: required when `method` is `OTHER`. */\n readonly description: string | null;\n /**\n * The transaction this payment was started as, written in `gPgtoVinc` with\n * `nPag` = its position. Absent or `null`: no link. The host decides whether\n * the environment accepts the group (optional in the layout; its production\n * activation is the fisco's).\n */\n readonly linkedTransaction?: LinkedTransaction | null;\n}\n\n/** `finNFe` 1–4. */\nexport type DocumentPurpose = \"NORMAL\" | \"COMPLEMENTARY\" | \"ADJUSTMENT\" | \"RETURN\";\n/**\n * `tpNF`: `OUT` (1) a sale or any outgoing document; `IN` (0) an entry, such as\n * a buyer's goods coming back. An NFC-e is always `OUT`.\n */\nexport type DocumentOperation = \"OUT\" | \"IN\";\n/** `NFref/refNFe`: an earlier NF-e or NFC-e this document refers to. */\nexport interface ReferencedDocument {\n /** The 44-character access key (`isValidAccessKey` in `@12-apps/fiscal/documents`). */\n readonly accessKey: string;\n}\n/** `idDest` 1–3. */\nexport type OperationDestination = \"INTERNAL\" | \"INTERSTATE\" | \"FOREIGN\";\n/** `indPres` 1, 2, 3, 4, 5, 9. */\nexport type BuyerPresence =\n | \"IN_PERSON\"\n | \"INTERNET\"\n | \"TELEPHONE\"\n | \"HOME_DELIVERY\"\n | \"IN_PERSON_OFF_PREMISES\"\n | \"OTHER\";\n/** `modFrete` 0, 1, 2, 3, 4, 9. */\nexport type FreightMode =\n | \"BY_ISSUER\"\n | \"BY_RECIPIENT\"\n | \"BY_THIRD_PARTY\"\n | \"OWN_BY_ISSUER\"\n | \"OWN_BY_RECIPIENT\"\n | \"NONE\";\n\n/** `infIntermed`: the third-party platform the sale went through. */\nexport interface SaleIntermediary {\n readonly cnpj: string;\n /** `idCadIntTran`: the seller's id on that platform. */\n readonly userId: string;\n}\n\n/** `infRespTec`: the software house responsible for the issuing system. */\nexport interface TechnicalResponsible {\n readonly cnpj: string;\n readonly contactName: string;\n readonly email: string;\n readonly phone: string;\n}\n\n/** One sale, ready to become an NF-e or an NFC-e. */\nexport interface SaleForDocument {\n readonly version: 1;\n /** `serie`, 0–999. */\n readonly series: number;\n /** `nNF`, 1–999999999. The package's counter owns it. */\n readonly number: number;\n /**\n * `cNF`: the 8-digit code inside the access key. The caller draws it ONCE and\n * keeps it with the document, so a retried call yields the same key.\n */\n readonly keyCode: string;\n /** `dhEmi`: ISO 8601 with the UTC offset, `2026-11-20T12:30:00-03:00`. */\n readonly issuedAt: string;\n /** `natOp`. */\n readonly operationNature: string;\n readonly purpose: DocumentPurpose;\n /**\n * `tpNF`. Absent is `OUT`. A buyer's return is an NF-e (model 55) with\n * `purpose: \"RETURN\"` and `operation: \"IN\"`; an NFC-e has neither.\n */\n readonly operation?: DocumentOperation;\n /**\n * `NFref`, at most 500, in order. Absent is none. A `RETURN` quotes the\n * document it returns here, or it is refused (`RETURN_NEEDS_REFERENCE`); an\n * NFC-e quotes none (SEFAZ 708). For a buyer's return the host sets CFOP\n * 1202 (within the state) or 2202 (between states) on every line, and a\n * single `NO_PAYMENT` payment; the package checks neither.\n */\n readonly referencedDocuments?: readonly ReferencedDocument[];\n readonly destination: OperationDestination;\n readonly presence: BuyerPresence;\n /** `indFinal`. */\n readonly finalConsumer: boolean;\n readonly intermediary: SaleIntermediary | null;\n readonly issuer: DocumentIssuer;\n /** `null` on an NFC-e with no identified buyer. */\n readonly buyer: DocumentBuyer | null;\n /** 1–990 items. */\n readonly lines: readonly SaleLine[];\n readonly freight: FreightMode;\n /** 1–100 payments. */\n readonly payments: readonly SalePayment[];\n /** `vTroco`. */\n readonly changeCents: number;\n readonly additionalInfo: {\n /** `infCpl`. */\n readonly forTaxpayer: string | null;\n /** `infAdFisco`. */\n readonly forTaxAuthority: string | null;\n };\n readonly technicalResponsible: TechnicalResponsible | null;\n}\n"],"mappings":";;;AAuNO,IAAM,qBAAqB,CAAC,MAAM,MAAM,MAAM,MAAM,MAAM,IAAI;","names":[]}
@@ -1,8 +1,8 @@
1
- import { F as FiscalDocumentModel, h as FiscalDocument, d as IssuerFailure, i as CancelOrReturnInput, j as CancelOrReturnResult, k as FiscalDocumentEvent } from './types-BIJqm5GM.js';
1
+ import { F as FiscalDocumentModel, d as IssuerFailure, i as FiscalDocument, j as CancelOrReturnInput, k as CancelOrReturnResult, l as FiscalDocumentEvent } from './types-DSYwap42.js';
2
+ import { IssuerTaxRegime, Address, LinkedTransaction } from './sale/index.js';
2
3
  import { T as TaxRegime } from './types-B1b8LIWX.js';
3
- import { IssuerTaxRegime, Address } from './sale/index.js';
4
4
  import { SefazEnvironment, LookedUpDocument } from './sidecar/index.js';
5
- import { f as DocumentPolicy, S as SigningIdentityKind, g as FiscalDocumentsConfig, C as Cipher, E as EmitterProfile, I as IssuingPoint } from './context-CLSMOSuf.js';
5
+ import { f as DocumentPolicy, S as SigningIdentityKind, g as FiscalDocumentsConfig, C as Cipher, E as EmitterProfile, I as IssuingPoint } from './context-CwZiHLnY.js';
6
6
 
7
7
  /**
8
8
  * Reading the emitter profile and the certificate upload off a request body:
@@ -72,6 +72,38 @@ interface FiscalDocumentsServiceConfig extends FiscalDocumentsConfig {
72
72
  readonly readCertificate: (certificate: CertificateUpload) => Promise<CertificateFacts>;
73
73
  }
74
74
 
75
+ /**
76
+ * The event 110300 "Vinculação Pagamento" (NT 2026.006 v1.00 §5.1): a payment
77
+ * transaction linked to an authorised document after the fact — a Pix QR whose
78
+ * txid was learnt only once the note was out, say. One event per transaction
79
+ * (the event's single `gPgto`), numbered per document (`nSeqEvento`).
80
+ *
81
+ * Idempotent per `(document, transactionId)`: a transaction the document
82
+ * already carries in its own `gPgtoVinc`, or already linked by an earlier
83
+ * event, is skipped with no call to SEFAZ. A refusal answers the issuer's
84
+ * failure and records nothing; the caller may ask again. `nSeqEvento` is the
85
+ * next after the document's own recorded events; a 573 at it is settled by the
86
+ * event SEFAZ holds there (its XML kept, its transaction recorded as its own),
87
+ * and the payment is then sent at the next sequence.
88
+ */
89
+
90
+ /** `nSeqEvento` runs 1–20 per event type and document. */
91
+ declare const MAX_PAYMENT_LINKS = 20;
92
+ interface LinkPaymentInput {
93
+ readonly ownerId: string;
94
+ readonly documentId: string;
95
+ readonly payments: readonly LinkedTransaction[];
96
+ }
97
+ interface LinkPaymentResult {
98
+ /** The transaction ids SEFAZ registered in this call. */
99
+ readonly linked: readonly string[];
100
+ /** Those the document already carried or an earlier event linked: nothing was sent. */
101
+ readonly alreadyLinked: readonly string[];
102
+ /** The first refusal, if any; the transactions after it were not sent. */
103
+ readonly failure: IssuerFailure | null;
104
+ readonly document: FiscalDocument;
105
+ }
106
+
75
107
  interface SweepReport {
76
108
  readonly advanced: Array<{
77
109
  readonly documentId: string;
@@ -127,6 +159,8 @@ declare function createFiscalDocuments(config: FiscalDocumentsServiceConfig): {
127
159
  * (501) — issue the buyer's return NF-e of entry quoting it. Idempotent.
128
160
  */
129
161
  cancelOrReturn: (input: CancelOrReturnInput) => Promise<CancelOrReturnResult>;
162
+ /** Link payment transactions to an authorised document (event 110300), once each. Idempotent. */
163
+ linkPayment: (input: LinkPaymentInput) => Promise<LinkPaymentResult>;
130
164
  /** Ask SEFAZ what it knows of the key; a state the answer moves is recorded. */
131
165
  lookup: (input: {
132
166
  ownerId: string;
@@ -151,4 +185,4 @@ declare function createFiscalDocuments(config: FiscalDocumentsServiceConfig): {
151
185
  };
152
186
  type FiscalDocuments = ReturnType<typeof createFiscalDocuments>;
153
187
 
154
- export { CONTINGENCY_WARNING_AFTER_MS as C, type EmitterProfileInput as E, type FiscalDocuments as F, type IssueInput as I, LATE_CANCEL_CODES as L, type SweepReport as S, type CertificateFacts as a, type CertificateUpload as b, type FiscalDocumentsServiceConfig as c, type IssuingPointInput as d, createFiscalDocuments as e, parseIssuingPointInput as f, parseProfileInput as g, parseCertificateUpload as p };
188
+ export { CONTINGENCY_WARNING_AFTER_MS as C, type EmitterProfileInput as E, type FiscalDocuments as F, type IssueInput as I, LATE_CANCEL_CODES as L, MAX_PAYMENT_LINKS as M, type SweepReport as S, type CertificateFacts as a, type CertificateUpload as b, type FiscalDocumentsServiceConfig as c, type IssuingPointInput as d, type LinkPaymentInput as e, type LinkPaymentResult as f, createFiscalDocuments as g, parseIssuingPointInput as h, parseProfileInput as i, parseCertificateUpload as p };
@@ -69,6 +69,21 @@ interface CancelBySubstitutionRequest extends CancelRequest {
69
69
  /** The contingency document that replaced it (`chNFeRef`). */
70
70
  readonly substituteAccessKey: string;
71
71
  }
72
+ /** `POST /<model>/link-payment`: the event 110300 for one transaction (NT 2026.006 v1.00). */
73
+ interface LinkPaymentRequest extends Authenticated {
74
+ readonly accessKey: string;
75
+ /** The authorisation protocol (`nProt`). */
76
+ readonly protocol: string;
77
+ /** `nSeqEvento`, 1–20: this document's how-manieth 110300. */
78
+ readonly sequence: number;
79
+ /** Exactly one entry: the event's schema carries a single `gPgto`. */
80
+ readonly payments: ReadonlyArray<{
81
+ readonly transactionId: string;
82
+ readonly meansCode: string;
83
+ readonly pspCnpjBase: string;
84
+ readonly receiverCnpj: string;
85
+ }>;
86
+ }
72
87
  /** `POST /<model>/lookup`. */
73
88
  interface LookupRequest extends Authenticated {
74
89
  readonly accessKey: string;
@@ -139,6 +154,27 @@ interface CancelledDocument extends SefazAnswer {
139
154
  /** The `procEventoNFe`. */
140
155
  readonly eventXml: string | null;
141
156
  }
157
+ /**
158
+ * `/link-payment`: the event registered. On 573 "Duplicidade de Evento" the
159
+ * service looks the key up and answers the event SEFAZ already holds at that
160
+ * `nSeqEvento`, with its own XML and the transaction it carries — which may be
161
+ * another transaction than the one sent (`statusCode` "573" tells the two apart).
162
+ */
163
+ interface RegisteredPaymentLink extends SefazAnswer {
164
+ readonly status: "REGISTERED";
165
+ readonly accessKey: string;
166
+ readonly protocol: string | null;
167
+ readonly registeredAt: string | null;
168
+ /** The `procEventoNFe`. */
169
+ readonly eventXml: string | null;
170
+ /** The `gPgto` SEFAZ registered at this `nSeqEvento`. */
171
+ readonly transaction: {
172
+ readonly transactionId: string;
173
+ readonly meansCode: string;
174
+ readonly pspCnpjBase: string;
175
+ readonly receiverCnpj: string;
176
+ };
177
+ }
142
178
  /** `/lookup`: what SEFAZ knows of the key. `NOT_FOUND` is an answer, not an error. */
143
179
  interface LookedUpDocument extends SefazAnswer {
144
180
  readonly status: "AUTHORIZED" | "CANCELLED" | "DENIED" | "NOT_FOUND";
@@ -215,4 +251,4 @@ interface SidecarHealth {
215
251
  readonly sefazTlsVerify: boolean;
216
252
  }
217
253
 
218
- export { type CancelBySubstitutionRequest, type CancelRequest, type CancelledDocument, type ContingencyEntry, type ContingencySignedDocument, type Csc, type DocumentModelPath, type InutilizeRequest, type InutilizedRange, type IssueRequest, type IssuedDocument, type LookedUpDocument, type LookupRequest, SIDECAR_ERROR_CLASSES, type SefazAnswer, type SefazEnvironment, type SidecarErrorBody, type SidecarErrorClass, type SidecarHealth, type SignContingencyRequest, type SigningCertificate, type TransmitRequest };
254
+ export { type CancelBySubstitutionRequest, type CancelRequest, type CancelledDocument, type ContingencyEntry, type ContingencySignedDocument, type Csc, type DocumentModelPath, type InutilizeRequest, type InutilizedRange, type IssueRequest, type IssuedDocument, type LinkPaymentRequest, type LookedUpDocument, type LookupRequest, type RegisteredPaymentLink, SIDECAR_ERROR_CLASSES, type SefazAnswer, type SefazEnvironment, type SidecarErrorBody, type SidecarErrorClass, type SidecarHealth, type SignContingencyRequest, type SigningCertificate, type TransmitRequest };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  SIDECAR_ERROR_CLASSES
3
- } from "../chunk-JVQKJNOC.js";
3
+ } from "../chunk-ZKWVKCGJ.js";
4
4
  import "../chunk-7QVYU63E.js";
5
5
  export {
6
6
  SIDECAR_ERROR_CLASSES
@@ -1,5 +1,5 @@
1
- import { SaleForDocument } from './sale/index.js';
2
- import { SidecarErrorBody, SefazEnvironment, SigningCertificate, Csc, IssuedDocument, ContingencyEntry, ContingencySignedDocument, CancelledDocument, LookedUpDocument, InutilizedRange, SidecarHealth, SidecarErrorClass } from './sidecar/index.js';
1
+ import { SaleForDocument, LinkedTransaction } from './sale/index.js';
2
+ import { SidecarErrorBody, SefazEnvironment, SigningCertificate, Csc, IssuedDocument, ContingencyEntry, ContingencySignedDocument, CancelledDocument, LookedUpDocument, RegisteredPaymentLink, InutilizedRange, SidecarHealth, SidecarErrorClass } from './sidecar/index.js';
3
3
 
4
4
  /**
5
5
  * The Issuer port: what the document service asks of whoever talks to SEFAZ.
@@ -57,6 +57,20 @@ interface CancelBySubstitutionCall extends Call {
57
57
  readonly reason: string;
58
58
  readonly substituteAccessKey: string;
59
59
  }
60
+ /** The event 110300 "Vinculação Pagamento" (NT 2026.006 v1.00): one transaction linked to an authorised document. */
61
+ interface LinkPaymentCall extends Call {
62
+ readonly model: FiscalDocumentModel;
63
+ readonly accessKey: string;
64
+ readonly protocol: string;
65
+ /** `nSeqEvento`, 1–20. */
66
+ readonly sequence: number;
67
+ /**
68
+ * The transactions the event links. Exactly ONE today: the event's schema
69
+ * (`e110300_v1.00.xsd`) carries a single `gPgto`, so the service refuses any
70
+ * other count as INVALID; the list is the NT group's own shape.
71
+ */
72
+ readonly payments: readonly LinkedTransaction[];
73
+ }
60
74
  interface LookupCall extends Call {
61
75
  readonly model: FiscalDocumentModel;
62
76
  readonly accessKey: string;
@@ -81,6 +95,13 @@ interface Issuer {
81
95
  cancel(call: CancelCall): Promise<IssuerOutcome<CancelledDocument>>;
82
96
  cancelBySubstitution(call: CancelBySubstitutionCall): Promise<IssuerOutcome<CancelledDocument>>;
83
97
  lookup(call: LookupCall): Promise<IssuerOutcome<LookedUpDocument>>;
98
+ /**
99
+ * The event 110300. Optional on the port so an issuer written before it
100
+ * still satisfies the type; one that lacks it cannot link (the document
101
+ * service answers `NOT_SUPPORTED`), and a host may read its presence as
102
+ * "this issuer writes `gPgtoVinc`".
103
+ */
104
+ linkPayment?(call: LinkPaymentCall): Promise<IssuerOutcome<RegisteredPaymentLink>>;
84
105
  inutilize(call: InutilizeCall): Promise<IssuerOutcome<InutilizedRange>>;
85
106
  health(): Promise<SidecarHealth>;
86
107
  }
@@ -218,7 +239,7 @@ interface FiscalDocument {
218
239
  readonly updatedAt: string;
219
240
  }
220
241
  /** What the state machine was fed: the kind of the input that made the event. */
221
- type DocumentEventKind = "SUBMIT" | "AUTHORIZE" | "DENY" | "REJECT" | "RETRY" | "SIGN_OFFLINE" | "REPLACE" | "CANCEL" | "LOOKUP" | "INUTILIZE" | "DEFER" | "RESIGN" | "RELEASE" | "WARN";
242
+ type DocumentEventKind = "SUBMIT" | "AUTHORIZE" | "DENY" | "REJECT" | "RETRY" | "SIGN_OFFLINE" | "REPLACE" | "CANCEL" | "LOOKUP" | "INUTILIZE" | "DEFER" | "RESIGN" | "RELEASE" | "WARN" | "LINK_PAYMENT";
222
243
  /**
223
244
  * One transition, as stored. `answer` is what the fiscal service answered,
224
245
  * verbatim but for any secret-named key (`scrubSecrets`), so the record is the
@@ -255,4 +276,4 @@ interface CancelOrReturnResult {
255
276
  readonly failure: IssuerFailure | null;
256
277
  }
257
278
 
258
- export { type CancelBySubstitutionCall as C, type DocumentEventKind as D, type FiscalDocumentModel as F, type Issuer as I, type LookupCall as L, type NumberVoid as N, OWED_VOIDS as O, type SignContingencyCall as S, type TransmitCall as T, type CancelCall as a, type InutilizeCall as b, type IssueCall as c, type IssuerFailure as d, type IssuerOutcome as e, type SigningMaterial as f, type FiscalDocumentStatus as g, type FiscalDocument as h, type CancelOrReturnInput as i, type CancelOrReturnResult as j, type FiscalDocumentEvent as k, type SeriesKind as l, modelPath as m, type DocumentTotals as n, FISCAL_DOCUMENT_MODELS as o, FISCAL_DOCUMENT_STATUSES as p, isLive as q };
279
+ export { type CancelBySubstitutionCall as C, type DocumentEventKind as D, type FiscalDocumentModel as F, type Issuer as I, type LinkPaymentCall as L, type NumberVoid as N, OWED_VOIDS as O, type SignContingencyCall as S, type TransmitCall as T, type CancelCall as a, type InutilizeCall as b, type IssueCall as c, type IssuerFailure as d, type IssuerOutcome as e, type LookupCall as f, type SigningMaterial as g, type FiscalDocumentStatus as h, type FiscalDocument as i, type CancelOrReturnInput as j, type CancelOrReturnResult as k, type FiscalDocumentEvent as l, modelPath as m, type SeriesKind as n, type DocumentTotals as o, FISCAL_DOCUMENT_MODELS as p, FISCAL_DOCUMENT_STATUSES as q, isLive as r };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/fiscal",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "Brazilian consumption-tax machinery and fiscal documents for any host that sells. The IBS/CBS engine (./engine): a pure function from priced lines, the seller's regime, the destination, the exclusions, a versioned rate table and the date of the supply to a per-line and per-order breakdown. The neutral sale document (./sale) and a stateless HTTP service over sped-nfe that issues NF-e and NFC-e, shipped with its Dockerfile in sidecar/ (./sidecar types its wire contract). The fiscal document module (./documents): the state machine, the per-series number counters, the issuer port and its sidecar adapter (./issuer), the signing identity, and the DANFE NFC-e as ESC/POS-ready lines (./danfe). Implements @12-apps/wiring (./manifest): db, http, jobs, permissions.",
@@ -0,0 +1,9 @@
1
+ -- @domains: fiscal
2
+ -- @12-apps/fiscal (FUT-2239): a document's events may record the event 110300
3
+ -- "Vinculação Pagamento" (NT 2026.006 v1.00), kind LINK_PAYMENT. The check only
4
+ -- widens: every row the previous release writes still passes it.
5
+
6
+ ALTER TABLE "fiscal_document_events" DROP CONSTRAINT "fiscal_document_events_kind_check";
7
+ ALTER TABLE "fiscal_document_events" ADD CONSTRAINT "fiscal_document_events_kind_check"
8
+ CHECK ("kind" IN ('SUBMIT', 'AUTHORIZE', 'DENY', 'REJECT', 'RETRY', 'SIGN_OFFLINE', 'REPLACE', 'CANCEL', 'LOOKUP', 'INUTILIZE',
9
+ 'DEFER', 'RESIGN', 'RELEASE', 'WARN', 'LINK_PAYMENT'));
package/sidecar/README.md CHANGED
@@ -29,6 +29,7 @@ SEFAZ carries `environment` (`homologacao` | `producao`) and `certificate`
29
29
  | `POST /<model>/transmit` | `{ environment, certificate, signedXml }` | as `/issue` |
30
30
  | `POST /<model>/cancel` | `{ environment, certificate, accessKey, protocol, reason }` | `CANCELLED`: the event's `protocol`, `registeredAt`, `eventXml` (each `null` when a retried cancel is settled by a lookup that does not carry them) |
31
31
  | `POST /nfce/cancel-substitution` | the cancel's body plus `substituteAccessKey`: the NFC-e "cancelamento por substituição" (event 110112), for an online NFC-e found authorised after its sale was issued again in contingency | as `/cancel` |
32
+ | `POST /<model>/link-payment` | `{ environment, certificate, accessKey, protocol, sequence, payments: [one { transactionId, meansCode, pspCnpjBase, receiverCnpj }] }`: the event 110300 "Vinculação Pagamento" (NT 2026.006) at `nSeqEvento` = `sequence` | `REGISTERED`: `protocol`, `registeredAt`, `eventXml`, `transaction` (the `gPgto` SEFAZ holds at that sequence). On 573 the key is looked up and the event already there is answered, which may carry another transaction; a 573 the lookup does not show is `RETRYABLE` |
32
33
  | `POST /<model>/lookup` | `{ environment, certificate, accessKey }` | `AUTHORIZED`, `CANCELLED`, `DENIED` or `NOT_FOUND`, with the authorisation `protocol` |
33
34
  | `POST /inutilize` | `{ environment, certificate, model, uf, cnpj, year, series, from, to, reason }` | `INUTILIZED`: `protocol`, `registeredAt`, `inutilizationXml` (`protocol` and the XML `null` on a retry SEFAZ answers 563) |
34
35
  | `GET /health` | | `{ status: "ok", libraries, nfeSchemas, sefazTlsVerify }` |
@@ -10,7 +10,7 @@
10
10
  "ext-json": "*",
11
11
  "ext-libxml": "*",
12
12
  "ext-openssl": "*",
13
- "nfephp-org/sped-nfe": "5.2.9"
13
+ "nfephp-org/sped-nfe": "5.2.11"
14
14
  },
15
15
  "require-dev": {
16
16
  "phpunit/phpunit": "^11.5"
@@ -4,7 +4,7 @@
4
4
  "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
5
5
  "This file is @generated automatically"
6
6
  ],
7
- "content-hash": "235b7b4c51e141ac548ff87191f7615c",
7
+ "content-hash": "027ed9316c06b9379e46519353632da5",
8
8
  "packages": [
9
9
  {
10
10
  "name": "justinrainbow/json-schema",
@@ -306,16 +306,16 @@
306
306
  },
307
307
  {
308
308
  "name": "nfephp-org/sped-nfe",
309
- "version": "v5.2.9",
309
+ "version": "v5.2.11",
310
310
  "source": {
311
311
  "type": "git",
312
312
  "url": "https://github.com/nfephp-org/sped-nfe.git",
313
- "reference": "346c14d5b7e59ab9aab92e7a77c499a19d462fba"
313
+ "reference": "4596b89e457d27ad2c114dda2b2ed04043f6327c"
314
314
  },
315
315
  "dist": {
316
316
  "type": "zip",
317
- "url": "https://api.github.com/repos/nfephp-org/sped-nfe/zipball/346c14d5b7e59ab9aab92e7a77c499a19d462fba",
318
- "reference": "346c14d5b7e59ab9aab92e7a77c499a19d462fba",
317
+ "url": "https://api.github.com/repos/nfephp-org/sped-nfe/zipball/4596b89e457d27ad2c114dda2b2ed04043f6327c",
318
+ "reference": "4596b89e457d27ad2c114dda2b2ed04043f6327c",
319
319
  "shasum": ""
320
320
  },
321
321
  "require": {
@@ -382,9 +382,9 @@
382
382
  ],
383
383
  "support": {
384
384
  "issues": "https://github.com/nfephp-org/sped-nfe/issues",
385
- "source": "https://github.com/nfephp-org/sped-nfe/tree/v5.2.9"
385
+ "source": "https://github.com/nfephp-org/sped-nfe/tree/v5.2.11"
386
386
  },
387
- "time": "2026-10-02T12:40:30+00:00"
387
+ "time": "2026-11-13T20:31:48+00:00"
388
388
  },
389
389
  {
390
390
  "name": "psr/log",