@12-apps/fiscal 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +26 -0
  2. package/dist/{chunk-RRFKYVLZ.js → chunk-GGYJPFBJ.js} +2 -2
  3. package/dist/{chunk-27B4HNO6.js → chunk-GKT3X5CF.js} +38 -2
  4. package/dist/chunk-GKT3X5CF.js.map +1 -0
  5. package/dist/{chunk-X6MRDUYH.js → chunk-H33BK623.js} +1 -1
  6. package/dist/{chunk-X6MRDUYH.js.map → chunk-H33BK623.js.map} +1 -1
  7. package/dist/{chunk-FOFIN5M7.js → chunk-JVQKJNOC.js} +1 -1
  8. package/dist/{chunk-FOFIN5M7.js.map → chunk-JVQKJNOC.js.map} +1 -1
  9. package/dist/{chunk-HQ2NXSTX.js → chunk-MEBG7FGG.js} +2 -2
  10. package/dist/{chunk-ALABGVPO.js → chunk-MGTROA7K.js} +2 -2
  11. package/dist/{chunk-V5ZQAAJT.js → chunk-V6G2OFLA.js} +8 -5
  12. package/dist/chunk-V6G2OFLA.js.map +1 -0
  13. package/dist/{context-ChnWR4Kb.d.ts → context-yc1C2__K.d.ts} +1 -1
  14. package/dist/danfe/index.js +2 -2
  15. package/dist/documents/index.d.ts +25 -7
  16. package/dist/documents/index.js +60 -3
  17. package/dist/documents/index.js.map +1 -1
  18. package/dist/http.d.ts +6 -3
  19. package/dist/http.js +4 -4
  20. package/dist/issuer/index.d.ts +2 -2
  21. package/dist/issuer/index.js +1 -1
  22. package/dist/jobs.d.ts +3 -3
  23. package/dist/jobs.js +3 -3
  24. package/dist/manifest/server.d.ts +3 -3
  25. package/dist/manifest/server.js +6 -6
  26. package/dist/notifications.d.ts +2 -2
  27. package/dist/notifications.js +2 -2
  28. package/dist/{port-DpRFK56U.d.ts → port-B1-ipIL4.d.ts} +1 -1
  29. package/dist/sale/index.d.ts +28 -2
  30. package/dist/{service-KTjH7AxW.d.ts → service-BB9lWdyg.d.ts} +30 -3
  31. package/dist/sidecar/index.d.ts +3 -1
  32. package/dist/sidecar/index.js +1 -1
  33. package/package.json +1 -1
  34. package/sidecar/README.md +13 -0
  35. package/sidecar/schema/sale-for-document.schema.json +21 -0
  36. package/sidecar/src/Nfe/DocumentMapper.php +46 -1
  37. package/src/documents/context.ts +1 -1
  38. package/src/documents/errors.ts +14 -1
  39. package/src/documents/helpers.ts +49 -0
  40. package/src/documents/index.ts +3 -2
  41. package/src/documents/service.ts +98 -1
  42. package/src/http.ts +3 -0
  43. package/src/sale/types.ts +27 -1
  44. package/src/sidecar/types.ts +3 -1
  45. package/dist/chunk-27B4HNO6.js.map +0 -1
  46. package/dist/chunk-V5ZQAAJT.js.map +0 -1
  47. /package/dist/{chunk-RRFKYVLZ.js.map → chunk-GGYJPFBJ.js.map} +0 -0
  48. /package/dist/{chunk-HQ2NXSTX.js.map → chunk-MEBG7FGG.js.map} +0 -0
  49. /package/dist/{chunk-ALABGVPO.js.map → chunk-MGTROA7K.js.map} +0 -0
package/dist/http.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  FISCAL_ERROR_STATUS,
3
3
  createApiFiscal
4
- } from "./chunk-V5ZQAAJT.js";
5
- import "./chunk-ALABGVPO.js";
6
- import "./chunk-RRFKYVLZ.js";
4
+ } from "./chunk-V6G2OFLA.js";
5
+ import "./chunk-MGTROA7K.js";
6
+ import "./chunk-GGYJPFBJ.js";
7
7
  import "./chunk-PNTKG3DZ.js";
8
8
  import "./chunk-XQGW5HUG.js";
9
9
  import "./chunk-3SDXLSG4.js";
10
- import "./chunk-X6MRDUYH.js";
10
+ import "./chunk-H33BK623.js";
11
11
  import "./chunk-7QVYU63E.js";
12
12
  export {
13
13
  FISCAL_ERROR_STATUS,
@@ -1,5 +1,5 @@
1
- import { I as Issuer } from '../port-DpRFK56U.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 '../port-DpRFK56U.js';
1
+ import { I as Issuer } from '../port-B1-ipIL4.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 '../port-B1-ipIL4.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-FOFIN5M7.js";
3
+ } from "../chunk-JVQKJNOC.js";
4
4
  import {
5
5
  __name
6
6
  } from "../chunk-7QVYU63E.js";
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-ChnWR4Kb.js';
3
- import { F as FiscalDocuments } from './service-KTjH7AxW.js';
4
- import './port-DpRFK56U.js';
2
+ import { F as FiscalStore, a as FiscalNotifyPort } from './context-yc1C2__K.js';
3
+ import { F as FiscalDocuments } from './service-BB9lWdyg.js';
4
+ import './port-B1-ipIL4.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,11 +5,11 @@ import {
5
5
  FISCAL_SWEEP_BATCH,
6
6
  FISCAL_WORST_STEP_MS,
7
7
  daysLeft
8
- } from "./chunk-HQ2NXSTX.js";
9
- import "./chunk-27B4HNO6.js";
8
+ } from "./chunk-MEBG7FGG.js";
9
+ import "./chunk-GKT3X5CF.js";
10
10
  import "./chunk-XQGW5HUG.js";
11
11
  import "./chunk-3SDXLSG4.js";
12
- import "./chunk-X6MRDUYH.js";
12
+ import "./chunk-H33BK623.js";
13
13
  import "./chunk-7QVYU63E.js";
14
14
  export {
15
15
  CERTIFICATE_WARNING_DAYS,
@@ -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-ChnWR4Kb.js';
5
- import '../port-DpRFK56U.js';
4
+ import '../context-yc1C2__K.js';
5
+ import '../port-B1-ipIL4.js';
6
6
  import '../sale/index.js';
7
7
  import '../sidecar/index.js';
8
8
  import '../types-B1b8LIWX.js';
9
- import '../service-KTjH7AxW.js';
9
+ import '../service-BB9lWdyg.js';
10
10
  import '../labels-BNvflT0h.js';
11
11
 
12
12
  declare const fiscalServerManifest: {
@@ -1,16 +1,16 @@
1
1
  import {
2
2
  createApiFiscal
3
- } from "../chunk-V5ZQAAJT.js";
4
- import "../chunk-ALABGVPO.js";
5
- import "../chunk-RRFKYVLZ.js";
3
+ } from "../chunk-V6G2OFLA.js";
4
+ import "../chunk-MGTROA7K.js";
5
+ import "../chunk-GGYJPFBJ.js";
6
6
  import "../chunk-PNTKG3DZ.js";
7
7
  import {
8
8
  FISCAL_JOBS
9
- } from "../chunk-HQ2NXSTX.js";
10
- import "../chunk-27B4HNO6.js";
9
+ } from "../chunk-MEBG7FGG.js";
10
+ import "../chunk-GKT3X5CF.js";
11
11
  import "../chunk-XQGW5HUG.js";
12
12
  import "../chunk-3SDXLSG4.js";
13
- import "../chunk-X6MRDUYH.js";
13
+ import "../chunk-H33BK623.js";
14
14
  import "../chunk-7QVYU63E.js";
15
15
 
16
16
  // src/manifest/server.ts
@@ -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-ChnWR4Kb.js';
2
- import { F as FiscalDocumentModel, g as FiscalDocumentStatus, N as NumberVoid } from './port-DpRFK56U.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-yc1C2__K.js';
2
+ import { F as FiscalDocumentModel, g as FiscalDocumentStatus, N as NumberVoid } from './port-B1-ipIL4.js';
3
3
  import './sale/index.js';
4
4
  import './sidecar/index.js';
5
5
  import './types-B1b8LIWX.js';
@@ -3,10 +3,10 @@ import {
3
3
  FISCAL_CONTINGENCY_DEADLINE,
4
4
  FISCAL_DOCUMENT_NEEDS_ATTENTION,
5
5
  FISCAL_DOCUMENT_REJECTED
6
- } from "./chunk-27B4HNO6.js";
6
+ } from "./chunk-GKT3X5CF.js";
7
7
  import "./chunk-XQGW5HUG.js";
8
8
  import "./chunk-3SDXLSG4.js";
9
- import "./chunk-X6MRDUYH.js";
9
+ import "./chunk-H33BK623.js";
10
10
  import {
11
11
  __name
12
12
  } from "./chunk-7QVYU63E.js";
@@ -1,5 +1,5 @@
1
1
  import { SaleForDocument } from './sale/index.js';
2
- import { SefazEnvironment, SidecarErrorClass, SigningCertificate, Csc, SidecarErrorBody, IssuedDocument, ContingencyEntry, ContingencySignedDocument, CancelledDocument, LookedUpDocument, InutilizedRange, SidecarHealth } from './sidecar/index.js';
2
+ import { SefazEnvironment, SidecarErrorClass, SidecarErrorBody, SigningCertificate, Csc, IssuedDocument, ContingencyEntry, ContingencySignedDocument, CancelledDocument, LookedUpDocument, InutilizedRange, SidecarHealth } from './sidecar/index.js';
3
3
 
4
4
  /**
5
5
  * The fiscal document record and its event log — the shape the package's
@@ -5,7 +5,10 @@
5
5
  * Money is integer CENTS, rates integer BASIS POINTS (1 bp = 0.01%) — the
6
6
  * engine's conventions (`@12-apps/fiscal/engine`) — and quantities carry at
7
7
  * most four decimals. Every field is required; an absent value is `null`,
8
- * never a missing key, so a host cannot forget one silently.
8
+ * never a missing key, so a host cannot forget one silently. The two
9
+ * exceptions came with the return document (FUT-2238), `operation` and
10
+ * `referencedDocuments`: they are optional so that a document built before
11
+ * them stays valid and yields the same XML, byte for byte.
9
12
  *
10
13
  * The JSON schema the service validates against is
11
14
  * `@12-apps/fiscal/sidecar/schema/sale-for-document.schema.json`; a test keeps
@@ -180,6 +183,16 @@ interface SalePayment {
180
183
  }
181
184
  /** `finNFe` 1–4. */
182
185
  type DocumentPurpose = "NORMAL" | "COMPLEMENTARY" | "ADJUSTMENT" | "RETURN";
186
+ /**
187
+ * `tpNF`: `OUT` (1) a sale or any outgoing document; `IN` (0) an entry, such as
188
+ * a buyer's goods coming back. An NFC-e is always `OUT`.
189
+ */
190
+ type DocumentOperation = "OUT" | "IN";
191
+ /** `NFref/refNFe`: an earlier NF-e or NFC-e this document refers to. */
192
+ interface ReferencedDocument {
193
+ /** The 44-character access key (`isValidAccessKey` in `@12-apps/fiscal/documents`). */
194
+ readonly accessKey: string;
195
+ }
183
196
  /** `idDest` 1–3. */
184
197
  type OperationDestination = "INTERNAL" | "INTERSTATE" | "FOREIGN";
185
198
  /** `indPres` 1, 2, 3, 4, 5, 9. */
@@ -216,6 +229,19 @@ interface SaleForDocument {
216
229
  /** `natOp`. */
217
230
  readonly operationNature: string;
218
231
  readonly purpose: DocumentPurpose;
232
+ /**
233
+ * `tpNF`. Absent is `OUT`. A buyer's return is an NF-e (model 55) with
234
+ * `purpose: "RETURN"` and `operation: "IN"`; an NFC-e has neither.
235
+ */
236
+ readonly operation?: DocumentOperation;
237
+ /**
238
+ * `NFref`, at most 500, in order. Absent is none. A `RETURN` quotes the
239
+ * document it returns here, or it is refused (`RETURN_NEEDS_REFERENCE`); an
240
+ * NFC-e quotes none (SEFAZ 708). For a buyer's return the host sets CFOP
241
+ * 1202 (within the state) or 2202 (between states) on every line, and a
242
+ * single `NO_PAYMENT` payment; the package checks neither.
243
+ */
244
+ readonly referencedDocuments?: readonly ReferencedDocument[];
219
245
  readonly destination: OperationDestination;
220
246
  readonly presence: BuyerPresence;
221
247
  /** `indFinal`. */
@@ -240,4 +266,4 @@ interface SaleForDocument {
240
266
  readonly technicalResponsible: TechnicalResponsible | null;
241
267
  }
242
268
 
243
- export type { Address, BuyerDocument, BuyerPresence, CardDetails, ContributionCst, DocumentBuyer, DocumentIssuer, DocumentPurpose, FreightMode, GoodsOrigin, IbsCbsFigures, IcmsSimples, IcmsSimplesWithCredit, IcmsTaxed, IcmsUntaxed, IssuerTaxRegime, LineContribution, LineIbsCbs, LineIcms, OperationDestination, PaymentMethod, SaleForDocument, SaleIntermediary, SaleLine, SalePayment, StateRegistrationStatus, TechnicalResponsible, Uf };
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 };
@@ -1,8 +1,8 @@
1
- import { F as FiscalDocumentModel, h as FiscalDocument, d as IssuerFailure, i as FiscalDocumentEvent } from './port-DpRFK56U.js';
1
+ import { F as FiscalDocumentModel, h as FiscalDocument, d as IssuerFailure, i as FiscalDocumentEvent } from './port-B1-ipIL4.js';
2
2
  import { T as TaxRegime } from './types-B1b8LIWX.js';
3
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-ChnWR4Kb.js';
5
+ import { f as DocumentPolicy, S as SigningIdentityKind, g as FiscalDocumentsConfig, C as Cipher, E as EmitterProfile, I as IssuingPoint } from './context-yc1C2__K.js';
6
6
 
7
7
  /**
8
8
  * Reading the emitter profile and the certificate upload off a request body:
@@ -90,6 +90,28 @@ interface IssueInput {
90
90
  }
91
91
  /** How long an NFC-e may wait in contingency before it must be transmitted (24 h); the warning goes out at 20 h. */
92
92
  declare const CONTINGENCY_WARNING_AFTER_MS: number;
93
+ /** SEFAZ's refusals of a cancel that came too late: "prazo de cancelamento superior ao previsto". */
94
+ declare const LATE_CANCEL_CODES: readonly ["501"];
95
+ interface CancelOrReturnInput {
96
+ readonly ownerId: string;
97
+ readonly documentId: string;
98
+ /** SEFAZ's 15–255 characters, sent with the cancel. */
99
+ readonly reason: string;
100
+ /** The NF-e (model 55) issuing point a return is numbered on. */
101
+ readonly returnPointId: string;
102
+ }
103
+ interface CancelOrReturnResult {
104
+ /**
105
+ * `CANCELLED` inside the window; `RETURNED` past it (the return may itself
106
+ * still be SUBMITTED: the sweep settles it like any document); `REFUSED`
107
+ * when the issuer refused the cancel for any other reason (nothing changed).
108
+ */
109
+ readonly outcome: "CANCELLED" | "RETURNED" | "REFUSED";
110
+ /** The document asked about, as it stands: CANCELLED, or still AUTHORIZED beside its return. */
111
+ readonly document: FiscalDocument;
112
+ readonly returnDocument: FiscalDocument | null;
113
+ readonly failure: IssuerFailure | null;
114
+ }
93
115
  declare function createFiscalDocuments(config: FiscalDocumentsServiceConfig): {
94
116
  getProfile: (ownerId: string) => Promise<EmitterProfile | null>;
95
117
  saveProfile: (ownerId: string, input: EmitterProfileInput) => Promise<EmitterProfile>;
@@ -112,6 +134,11 @@ declare function createFiscalDocuments(config: FiscalDocumentsServiceConfig): {
112
134
  document: FiscalDocument;
113
135
  failure: IssuerFailure | null;
114
136
  }>;
137
+ /**
138
+ * Cancel an authorised document, or — when SEFAZ says the cancel is too late
139
+ * (501) — issue the buyer's return NF-e of entry quoting it. Idempotent.
140
+ */
141
+ cancelOrReturn: (input: CancelOrReturnInput) => Promise<CancelOrReturnResult>;
115
142
  /** Ask SEFAZ what it knows of the key; a state the answer moves is recorded. */
116
143
  lookup: (input: {
117
144
  ownerId: string;
@@ -136,4 +163,4 @@ declare function createFiscalDocuments(config: FiscalDocumentsServiceConfig): {
136
163
  };
137
164
  type FiscalDocuments = ReturnType<typeof createFiscalDocuments>;
138
165
 
139
- export { CONTINGENCY_WARNING_AFTER_MS as C, type EmitterProfileInput as E, type FiscalDocuments as F, type IssueInput as I, 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 };
166
+ 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 CancelOrReturnInput as a, type CancelOrReturnResult as b, type CertificateFacts as c, type CertificateUpload as d, type FiscalDocumentsServiceConfig as e, type IssuingPointInput as f, createFiscalDocuments as g, parseIssuingPointInput as h, parseProfileInput as i, parseCertificateUpload as p };
@@ -188,7 +188,9 @@ interface SidecarErrorBody {
188
188
  * The SEFAZ `cStat` when SEFAZ answered (always for `REJECTED`); for
189
189
  * `INVALID`, a named code where one applies (`NT_2026_008_NOT_SUPPORTED`:
190
190
  * a document issued on or after 2027-01-01, which needs NT 2026.008's
191
- * `vProdLiq`); `null` otherwise.
191
+ * `vProdLiq`; `RETURN_ON_NFCE`: a return asked of an NFC-e, which has no
192
+ * return purpose; `RETURN_NEEDS_REFERENCE`: a return quoting no
193
+ * `referencedDocuments`); `null` otherwise.
192
194
  */
193
195
  readonly code: string | null;
194
196
  readonly message: string;
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  SIDECAR_ERROR_CLASSES
3
- } from "../chunk-FOFIN5M7.js";
3
+ } from "../chunk-JVQKJNOC.js";
4
4
  import "../chunk-7QVYU63E.js";
5
5
  export {
6
6
  SIDECAR_ERROR_CLASSES
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/fiscal",
3
- "version": "1.1.0",
3
+ "version": "1.3.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.",
package/sidecar/README.md CHANGED
@@ -56,6 +56,19 @@ contingency could put a second document on the same sale.
56
56
  inside `vProd` and the net price travels in NT 2026.008's `vProdLiq`, which
57
57
  sped-nfe 5.2.9 cannot write.
58
58
 
59
+ **A return document.** `operation` maps to `tpNF` (`OUT` 1, `IN` 0) and
60
+ `referencedDocuments[].accessKey` to `NFref/refNFe`, in order. Both are
61
+ optional: a document without them is `tpNF` 1 with no `NFref`, byte for byte
62
+ what it built before they existed. A buyer's return is an NF-e of entry
63
+ (`/nfe/issue`, `purpose: "RETURN"`, `operation: "IN"`) that references the
64
+ NFC-e. `INVALID` with code `RETURN_ON_NFCE` refuses a return asked of an NFC-e
65
+ (an NFC-e has no return purpose), and with code `RETURN_NEEDS_REFERENCE` a
66
+ return quoting no document; an NFC-e of entry, and an NFC-e with any
67
+ `referencedDocuments` (SEFAZ rejects `NFref` on a model 65 with 708), are
68
+ `INVALID` too. The caller sets CFOP 1202 (within the state) or 2202 (between
69
+ states) on every line, and a single `NO_PAYMENT` payment; the service checks
70
+ neither.
71
+
59
72
  ## Errors
60
73
 
61
74
  Every failure is `{ error: { class, code, message, details, accessKey, signedXml, sefazReply, outcomeUnknown } }`:
@@ -41,6 +41,27 @@
41
41
  },
42
42
  "operationNature": { "type": "string", "minLength": 1, "maxLength": 60 },
43
43
  "purpose": { "enum": ["NORMAL", "COMPLEMENTARY", "ADJUSTMENT", "RETURN"] },
44
+ "operation": {
45
+ "description": "tpNF: OUT (1) for a sale or any outgoing document, IN (0) for an entry, such as a buyer's goods coming back. Optional: absent is OUT, so a document written before the field existed is unchanged. An NFC-e is always OUT.",
46
+ "enum": ["OUT", "IN"]
47
+ },
48
+ "referencedDocuments": {
49
+ "description": "NFref/refNFe: the earlier NF-e or NFC-e this document refers to, by access key. Optional: absent is none. A RETURN needs at least one.",
50
+ "type": "array",
51
+ "maxItems": 500,
52
+ "items": {
53
+ "type": "object",
54
+ "additionalProperties": false,
55
+ "required": ["accessKey"],
56
+ "properties": {
57
+ "accessKey": {
58
+ "description": "44 characters: cUF, AAMM, the issuer's CNPJ (alphanumeric from July 2026), model, series, number, tpEmis, cNF and the modulo-11 check digit.",
59
+ "type": "string",
60
+ "pattern": "^[0-9]{6}[0-9A-Z]{12}[0-9]{26}$"
61
+ }
62
+ }
63
+ }
64
+ },
44
65
  "destination": { "enum": ["INTERNAL", "INTERSTATE", "FOREIGN"] },
45
66
  "presence": {
46
67
  "enum": ["IN_PERSON", "INTERNET", "TELEPHONE", "HOME_DELIVERY", "IN_PERSON_OFF_PREMISES", "OTHER"]
@@ -21,6 +21,8 @@ use Throwable;
21
21
  final class DocumentMapper
22
22
  {
23
23
  private const PURPOSE = ['NORMAL' => 1, 'COMPLEMENTARY' => 2, 'ADJUSTMENT' => 3, 'RETURN' => 4];
24
+ /** `tpNF`. An absent `operation` is `OUT`: a document built before the field existed is unchanged. */
25
+ private const OPERATION = ['IN' => 0, 'OUT' => 1];
24
26
  private const DESTINATION = ['INTERNAL' => 1, 'INTERSTATE' => 2, 'FOREIGN' => 3];
25
27
  private const PRESENCE = [
26
28
  'IN_PERSON' => 1,
@@ -77,6 +79,15 @@ final class DocumentMapper
77
79
  public const LAYOUT_LIMIT = '2027-01-01';
78
80
  public const LAYOUT_LIMIT_CODE = 'NT_2026_008_NOT_SUPPORTED';
79
81
 
82
+ /** A return (`finNFe` 4) quotes the document it returns (`NFref`); one without a reference is refused. */
83
+ public const RETURN_NEEDS_REFERENCE_CODE = 'RETURN_NEEDS_REFERENCE';
84
+
85
+ /**
86
+ * An NFC-e has no return purpose: a buyer's goods come back on an NF-e
87
+ * (model 55) of entry that references the NFC-e's key.
88
+ */
89
+ public const RETURN_ON_NFCE_CODE = 'RETURN_ON_NFCE';
90
+
80
91
  /**
81
92
  * @param array<string, mixed> $document
82
93
  * @param array{since: string, reason: string}|null $contingency an NFC-e signed offline (`tpEmis = 9`)
@@ -86,6 +97,7 @@ final class DocumentMapper
86
97
  public function build(array $document, Model $model, int $environment, ?array $contingency = null): array
87
98
  {
88
99
  self::refuseWhatThisLayoutCannotSay($document);
100
+ self::refuseAReturnItCannotBe($document, $model);
89
101
  $make = new Make(NfeModule::SCHEMES);
90
102
  $make->setOnlyAscii(false);
91
103
  $make->setCheckGtin(true);
@@ -135,6 +147,36 @@ final class DocumentMapper
135
147
  }
136
148
  }
137
149
 
150
+ /**
151
+ * @param array<string, mixed> $document
152
+ * @throws ServiceError INVALID, coded, when the purpose and the model or the references disagree
153
+ */
154
+ private static function refuseAReturnItCannotBe(array $document, Model $model): void
155
+ {
156
+ $isReturn = $document['purpose'] === 'RETURN';
157
+ if ($model === Model::NFCE && $isReturn) {
158
+ throw new ServiceError(
159
+ \Fiscal\Sidecar\ErrorClass::INVALID,
160
+ 'An NFC-e has no return purpose: a return is an NF-e (model 55) of entry referencing the NFC-e.',
161
+ self::RETURN_ON_NFCE_CODE,
162
+ );
163
+ }
164
+ if ($model === Model::NFCE && ($document['operation'] ?? 'OUT') === 'IN') {
165
+ throw ServiceError::invalid('An NFC-e is an outgoing document.', ['operation: an NFC-e takes "OUT" (tpNF 1)']);
166
+ }
167
+ if ($model === Model::NFCE && ($document['referencedDocuments'] ?? []) !== []) {
168
+ // SEFAZ rejects NFref on a model 65 with 708, after the number is spent.
169
+ throw ServiceError::invalid('An NFC-e references no document.', ['referencedDocuments: an NFC-e takes none (708)']);
170
+ }
171
+ if ($isReturn && ($document['referencedDocuments'] ?? []) === []) {
172
+ throw new ServiceError(
173
+ \Fiscal\Sidecar\ErrorClass::INVALID,
174
+ 'A return must reference the document it returns (referencedDocuments).',
175
+ self::RETURN_NEEDS_REFERENCE_CODE,
176
+ );
177
+ }
178
+ }
179
+
138
180
  /** @param array<string, mixed> $d */
139
181
  private function header(Make $make, array $d, Model $model, int $environment, ?array $contingency): void
140
182
  {
@@ -149,7 +191,7 @@ final class DocumentMapper
149
191
  'nNF' => $d['number'],
150
192
  'dhEmi' => $d['issuedAt'],
151
193
  'dhSaiEnt' => null,
152
- 'tpNF' => 1,
194
+ 'tpNF' => self::OPERATION[$d['operation'] ?? 'OUT'],
153
195
  'idDest' => self::DESTINATION[$d['destination']],
154
196
  'cMunFG' => $d['issuer']['address']['municipalityIbge'],
155
197
  'tpImp' => $model === Model::NFCE ? 4 : 1,
@@ -167,6 +209,9 @@ final class DocumentMapper
167
209
  'dhCont' => $contingency['since'] ?? null,
168
210
  'xJust' => $contingency['reason'] ?? null,
169
211
  ]);
212
+ foreach ($d['referencedDocuments'] ?? [] as $referenced) {
213
+ $make->tagrefNFe((object) ['refNFe' => $referenced['accessKey']]);
214
+ }
170
215
  }
171
216
 
172
217
  /** @param array<string, mixed> $d */
@@ -15,7 +15,7 @@ import type { EmitterProfile, IssuingPoint } from "./profile";
15
15
  import type { SigningIdentities } from "./signing";
16
16
  import { type FiscalDocument, type FiscalDocumentModel, OWED_VOIDS, type SeriesKind } from "./types";
17
17
 
18
- export { computeAccessKey, draftOf, drawKeyCode, issuerOf, localIso, totalsOf, xmlKeys } from "./helpers";
18
+ export { assertDraftFits, computeAccessKey, draftOf, drawKeyCode, isValidAccessKey, issuerOf, localIso, totalsOf, xmlKeys } from "./helpers";
19
19
 
20
20
  /** Twin of `@12-apps/wiring/ports`' `NotifyPort`: never throws. */
21
21
  export interface FiscalNotifyPort {
@@ -28,7 +28,20 @@ export type FiscalDocumentErrorCode =
28
28
  * DANFE prints and its QR encodes (the total, the buyer's document): such a
29
29
  * sale needs a new note, issued by a person.
30
30
  */
31
- | "RESEND_CHANGES_PRINTED_FIELDS";
31
+ | "RESEND_CHANGES_PRINTED_FIELDS"
32
+ /** A `RETURN` quotes no document (`referencedDocuments` is absent or empty). */
33
+ | "RETURN_NEEDS_REFERENCE"
34
+ /**
35
+ * A `RETURN` asked of an NFC-e. An NFC-e has no return purpose: the return is
36
+ * an NF-e (model 55) of entry that references the NFC-e's key.
37
+ */
38
+ | "RETURN_ON_NFCE"
39
+ /**
40
+ * `cancelOrReturn` past SEFAZ's window on a document that is not an NFC-e:
41
+ * the buyer's return NF-e of entry answers a consumer's NFC-e only; an NF-e
42
+ * past its window is the issuer's own correction, not this path's.
43
+ */
44
+ | "RETURN_OF_NFCE_ONLY";
32
45
 
33
46
  export class FiscalDocumentError extends Error {
34
47
  readonly code: FiscalDocumentErrorCode;
@@ -100,6 +100,55 @@ function keyCheckDigit(body: string): number {
100
100
  return rest < 2 ? 0 : 11 - rest;
101
101
  }
102
102
 
103
+ /** cUF and AAMM, the issuer's CNPJ (alphanumeric from July 2026), then model to `cDV`, all digits. */
104
+ const ACCESS_KEY_SHAPE = /^[0-9]{6}[0-9A-Z]{12}[0-9]{26}$/;
105
+ /** `NFref` occurs at most 500 times. */
106
+ const MAX_REFERENCED_DOCUMENTS = 500;
107
+
108
+ /**
109
+ * Whether `key` is an access key as the layout writes one: 44 characters, the
110
+ * CNPJ inside it alphanumeric or not, and its modulo-11 check digit right.
111
+ */
112
+ export function isValidAccessKey(key: string): boolean {
113
+ if (!ACCESS_KEY_SHAPE.test(key)) return false;
114
+ return keyCheckDigit(key.slice(0, 43)) === Number(key.slice(43));
115
+ }
116
+
117
+ /**
118
+ * Refuses a sale the model cannot carry, before a number is drawn: a return on
119
+ * an NFC-e, an NFC-e of entry, an NFC-e quoting another document (SEFAZ
120
+ * rejects `NFref` on a model 65 with 708, and the number would be burned), a
121
+ * return quoting nothing, or a reference that is not an access key. A document without `operation` and
122
+ * `referencedDocuments` passes as it always did.
123
+ */
124
+ export function assertDraftFits(draft: Pick<SaleDraft, "purpose" | "operation" | "referencedDocuments">, model: FiscalDocumentModel): void {
125
+ const references = draft.referencedDocuments ?? [];
126
+ if (model === "NFCE") assertNfceDraftFits(draft, references.length);
127
+ if (draft.purpose === "RETURN" && references.length === 0) {
128
+ throw new FiscalDocumentError("RETURN_NEEDS_REFERENCE", "a return must reference the document it returns (referencedDocuments).");
129
+ }
130
+ if (references.length > MAX_REFERENCED_DOCUMENTS) {
131
+ throw new FiscalDocumentError("INVALID_INPUT", `at most ${MAX_REFERENCED_DOCUMENTS} referenced documents, not ${references.length}.`);
132
+ }
133
+ const bad = references.findIndex((reference) => !isValidAccessKey(reference.accessKey));
134
+ if (bad !== -1) {
135
+ throw new FiscalDocumentError("INVALID_INPUT", `referencedDocuments[${bad}].accessKey is not a 44-character access key.`);
136
+ }
137
+ }
138
+
139
+ /** The NFC-e half of `assertDraftFits`: no return, no entry, no reference. */
140
+ function assertNfceDraftFits(draft: Pick<SaleDraft, "purpose" | "operation">, referenceCount: number): void {
141
+ if (draft.purpose === "RETURN") {
142
+ throw new FiscalDocumentError("RETURN_ON_NFCE", "an NFC-e has no return purpose: issue an NF-e (model 55) of entry referencing it.");
143
+ }
144
+ if (draft.operation === "IN") {
145
+ throw new FiscalDocumentError("INVALID_INPUT", 'an NFC-e is an outgoing document: operation must be "OUT".');
146
+ }
147
+ if (referenceCount > 0) {
148
+ throw new FiscalDocumentError("INVALID_INPUT", "an NFC-e references no document (SEFAZ 708): referencedDocuments must be empty.");
149
+ }
150
+ }
151
+
103
152
  /**
104
153
  * The 44-character access key a document will carry, computed as the layout
105
154
  * does: cUF, AAMM of `dhEmi`, CNPJ, model, series, number, `tpEmis` (1 online,
@@ -24,12 +24,13 @@ export {
24
24
  computeAccessKey,
25
25
  draftOf,
26
26
  drawKeyCode,
27
+ isValidAccessKey,
27
28
  localIso,
28
29
  xmlKeys,
29
30
  } from "./context";
30
31
  export type { FiscalDocumentsConfig, FiscalNotifyPort, FiscalReasons } from "./context";
31
- export { CONTINGENCY_WARNING_AFTER_MS, createFiscalDocuments } from "./service";
32
- export type { CertificateFacts, FiscalDocuments, FiscalDocumentsServiceConfig, IssueInput, SweepReport } from "./service";
32
+ export { CONTINGENCY_WARNING_AFTER_MS, LATE_CANCEL_CODES, createFiscalDocuments } from "./service";
33
+ export type { CancelOrReturnInput, CancelOrReturnResult, CertificateFacts, FiscalDocuments, FiscalDocumentsServiceConfig, IssueInput, SweepReport } from "./service";
33
34
  export { createMemoryFiscalStore } from "./memory";
34
35
  export type { MemoryFiscalStore } from "./memory";
35
36
  export { FISCAL_NEXT_NUMBER_SQL } from "./sql";