@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
@@ -415,7 +415,24 @@
415
415
  }
416
416
  ]
417
417
  },
418
- "description": { "oneOf": [{ "type": "null" }, { "type": "string", "minLength": 2, "maxLength": 60 }] }
418
+ "description": { "oneOf": [{ "type": "null" }, { "type": "string", "minLength": 2, "maxLength": 60 }] },
419
+ "linkedTransaction": {
420
+ "description": "gPgtoVinc (NT 2026.006 v1.00): the payment transaction started before the document, linked by its id. Absent or null: no link.",
421
+ "oneOf": [
422
+ { "type": "null" },
423
+ {
424
+ "type": "object",
425
+ "additionalProperties": false,
426
+ "required": ["transactionId", "meansCode", "pspCnpjBase", "receiverCnpj"],
427
+ "properties": {
428
+ "transactionId": { "type": "string", "pattern": "^[\\x21-\\x7E]{2,35}$" },
429
+ "meansCode": { "enum": ["15", "17", "18", "20", "23", "24"] },
430
+ "pspCnpjBase": { "type": "string", "pattern": "^[A-Z0-9]{8}$" },
431
+ "receiverCnpj": { "$ref": "#/definitions/cnpj" }
432
+ }
433
+ }
434
+ ]
435
+ }
419
436
  }
420
437
  }
421
438
  }
@@ -379,6 +379,7 @@ final class DocumentMapper
379
379
  'tpIntegra' => $card === null ? null : ($card['integrated'] ? 1 : 2),
380
380
  ]);
381
381
  }
382
+ $this->paymentLinks($make, $d['payments']);
382
383
  if ($d['intermediary'] !== null) {
383
384
  $make->tagIntermed((object) [
384
385
  'CNPJ' => $d['intermediary']['cnpj'],
@@ -400,6 +401,32 @@ final class DocumentMapper
400
401
  }
401
402
  }
402
403
 
404
+ /**
405
+ * `gPgtoVinc` (NT 2026.006 v1.00, YC01): every payment whose transaction was
406
+ * started before the document, linked by its id. `nPag` is the payment's
407
+ * position among the document's payments. The caller decides whether the
408
+ * environment accepts the group (it is optional in the layout, and the
409
+ * fisco's own production activation is announced for 2027).
410
+ *
411
+ * @param list<array<string, mixed>> $payments
412
+ */
413
+ private function paymentLinks(Make $make, array $payments): void
414
+ {
415
+ foreach (array_values($payments) as $index => $payment) {
416
+ $link = $payment['linkedTransaction'] ?? null;
417
+ if ($link === null) {
418
+ continue;
419
+ }
420
+ $make->tagPgtoVinc((object) [
421
+ 'nPag' => $index + 1,
422
+ 'idTransacao' => $link['transactionId'],
423
+ 'tpMeioPgto' => $link['meansCode'],
424
+ 'CNPJReceb' => $link['receiverCnpj'],
425
+ 'CNPJBasePSP' => $link['pspCnpjBase'],
426
+ ]);
427
+ }
428
+ }
429
+
403
430
  private static function reais(int $cents): string
404
431
  {
405
432
  return number_format($cents / 100, 2, '.', '');
@@ -105,6 +105,16 @@ final class Input
105
105
  return $value;
106
106
  }
107
107
 
108
+ /** @return list<mixed> */
109
+ public function list(string $field): array
110
+ {
111
+ $value = $this->body[$field] ?? null;
112
+ if (!is_array($value) || !array_is_list($value)) {
113
+ throw ServiceError::invalid("$field must be a list.");
114
+ }
115
+ return $value;
116
+ }
117
+
108
118
  public function text(string $field, int $min, int $max): string
109
119
  {
110
120
  $value = $this->body[$field] ?? null;
@@ -33,6 +33,7 @@ final class NfeModule implements Module
33
33
  $router->add('POST', "$prefix/transmit", fn (Request $r): Response => $this->service()->transmit($model, self::in($r)));
34
34
  $router->add('POST', "$prefix/cancel", fn (Request $r): Response => $this->service()->cancel($model, self::in($r)));
35
35
  $router->add('POST', "$prefix/lookup", fn (Request $r): Response => $this->service()->lookup($model, self::in($r)));
36
+ $router->add('POST', "$prefix/link-payment", fn (Request $r): Response => $this->service()->linkPayment($model, self::in($r)));
36
37
  }
37
38
  $router->add('POST', '/nfce/cancel-substitution', fn (Request $r): Response => $this->service()->cancelBySubstitution(self::in($r)));
38
39
  $router->add('POST', '/nfce/sign-contingency', fn (Request $r): Response => $this->service()->signContingency(self::in($r)));
@@ -116,6 +116,126 @@ final class NfeService
116
116
  );
117
117
  }
118
118
 
119
+ /**
120
+ * `POST /<model>/link-payment`: NT 2026.006 v1.00's event 110300
121
+ * "Vinculação Pagamento", one payment transaction linked to an authorised
122
+ * document after the fact. One transaction per event (the schema's single
123
+ * `gPgto`), numbered by the caller's `sequence` (`nSeqEvento`, 1–20).
124
+ *
125
+ * 573 "Duplicidade de Evento" means SEFAZ already holds an event 110300 at
126
+ * that `sequence`: a retry of one whose recording was lost, or another
127
+ * transaction's. The key is looked up and the registered event answered with
128
+ * its own `procEventoNFe` and the `transaction` it carries, which the caller
129
+ * compares with the one it sent. A 573 the lookup cannot show is RETRYABLE.
130
+ */
131
+ public function linkPayment(Model $model, Input $in): Response
132
+ {
133
+ $environment = $in->environment();
134
+ $key = self::keyOf($model, $in);
135
+ $protocol = $in->pattern('protocol', '/^[0-9]{15}$/', 'the 15-digit authorisation protocol');
136
+ $sequence = $in->digits('sequence', 1, 20);
137
+ $transaction = self::paymentOf($in);
138
+ $tagAdic = '<cOrgaoAutor>' . substr($key, 0, 2) . '</cOrgaoAutor><tpAutor>1</tpAutor>'
139
+ . '<verAplic>' . DocumentMapper::PROCESS_VERSION . '</verAplic>'
140
+ . "<nProt>$protocol</nProt>" . self::paymentGroup($transaction);
141
+ $tools = $this->toolsForKey($in, $model, $environment, $key);
142
+ $reply = $this->settled(
143
+ fn (): string => $tools->sefazEvento(UFList::getUFByCode((int) substr($key, 0, 2)), $key, Tools::EVT_VINCULACAO_PAGAMENTO, $sequence, $tagAdic),
144
+ false,
145
+ );
146
+ $status = $reply->status() === '128' ? (string) $reply->value('cStat', 'infEvento') : $reply->status();
147
+ if ($status === '573') {
148
+ return $this->linkSettledByLookup($tools, $key, $sequence, $reply);
149
+ }
150
+ if (!in_array($status, self::EVENT_REGISTERED, true)) {
151
+ throw Classifier::fromStatus($status, self::reasonOf($reply, 'infEvento'), $reply, false);
152
+ }
153
+ return new Response(200, self::answer($reply, $status, 'infEvento') + [
154
+ 'status' => 'REGISTERED',
155
+ 'accessKey' => $key,
156
+ 'protocol' => (string) $reply->value('nProt', 'infEvento'),
157
+ 'registeredAt' => (string) $reply->value('dhRegEvento', 'infEvento'),
158
+ 'eventXml' => self::protocolled($tools->lastRequest, $reply->raw),
159
+ 'transaction' => $transaction,
160
+ ]);
161
+ }
162
+
163
+ /**
164
+ * A 573 settled by the key's own events: the 110300 SEFAZ holds at
165
+ * `$sequence`, with its `procEventoNFe` and the transaction it carries.
166
+ */
167
+ private function linkSettledByLookup(Tools $tools, string $key, int $sequence, SefazReply $duplicate): Response
168
+ {
169
+ try {
170
+ $lookup = $this->exchange(fn (): string => $tools->sefazConsultaChave($key));
171
+ } catch (TransportFailure $failure) {
172
+ throw self::unsettled($failure, false, false);
173
+ }
174
+ foreach ($lookup->all('procEventoNFe') as $xml) {
175
+ $event = SefazReply::parse($xml);
176
+ if ($event->value('tpEvento') !== (string) Tools::EVT_VINCULACAO_PAGAMENTO || (int) $event->value('nSeqEvento') !== $sequence
177
+ || !in_array((string) $event->value('cStat', 'retEvento'), self::EVENT_REGISTERED, true)) {
178
+ continue;
179
+ }
180
+ return new Response(200, self::answer($duplicate, '573', 'infEvento') + [
181
+ 'status' => 'REGISTERED',
182
+ 'accessKey' => $key,
183
+ 'protocol' => $event->value('nProt', 'retEvento'),
184
+ 'registeredAt' => $event->value('dhRegEvento', 'retEvento'),
185
+ 'eventXml' => $xml,
186
+ 'transaction' => [
187
+ 'transactionId' => (string) $event->attribute('gPgto', 'idTransacao'),
188
+ 'meansCode' => (string) $event->value('tpMeioPgto', 'gPgto'),
189
+ 'receiverCnpj' => (string) $event->value('CNPJReceb', 'gPgto'),
190
+ 'pspCnpjBase' => (string) $event->value('CNPJBasePSP', 'gPgto'),
191
+ ],
192
+ ]);
193
+ }
194
+ throw new ServiceError(
195
+ ErrorClass::RETRYABLE,
196
+ "SEFAZ calls the event 110300 #$sequence a duplicate, and the key's lookup does not show it yet: send it again.",
197
+ '573',
198
+ [],
199
+ null,
200
+ null,
201
+ $lookup->raw,
202
+ );
203
+ }
204
+
205
+ /**
206
+ * The one transaction the event links (schema `TEventoPgto`). `payments`
207
+ * holds exactly one entry, since the event's schema carries a single `gPgto`.
208
+ *
209
+ * @return array{transactionId: string, meansCode: string, receiverCnpj: string, pspCnpjBase: string}
210
+ */
211
+ private static function paymentOf(Input $in): array
212
+ {
213
+ $payments = $in->list('payments');
214
+ if (count($payments) !== 1 || !is_array($payments[0])) {
215
+ throw ServiceError::invalid('payments must hold exactly one transaction: the event 110300 carries one gPgto.');
216
+ }
217
+ $one = new Input($payments[0]);
218
+ return [
219
+ 'transactionId' => $one->pattern('transactionId', '/^[\x21-\x7E]{2,35}$/', '2 to 35 printable characters'),
220
+ 'meansCode' => $one->pattern('meansCode', '/^(15|17|18|20|23|24)$/', 'an IT 2026.001 tpMeioPgto (15, 17, 18, 20, 23, 24)'),
221
+ 'receiverCnpj' => $one->pattern('receiverCnpj', '/^[A-Z0-9]{12}[0-9]{2}$/', 'a 14-character CNPJ'),
222
+ 'pspCnpjBase' => $one->pattern('pspCnpjBase', '/^[A-Z0-9]{8}$/', 'an 8-character CNPJ base'),
223
+ ];
224
+ }
225
+
226
+ /**
227
+ * The event's `gPgto`: the transaction id is an attribute, then the means,
228
+ * the receiver, the PSP.
229
+ *
230
+ * @param array{transactionId: string, meansCode: string, receiverCnpj: string, pspCnpjBase: string} $transaction
231
+ */
232
+ private static function paymentGroup(array $transaction): string
233
+ {
234
+ $id = htmlspecialchars($transaction['transactionId'], ENT_XML1 | ENT_QUOTES);
235
+ return "<gPgto idTransacao=\"$id\"><tpMeioPgto>{$transaction['meansCode']}</tpMeioPgto>"
236
+ . "<CNPJReceb>{$transaction['receiverCnpj']}</CNPJReceb><CNPJBasePSP>{$transaction['pspCnpjBase']}</CNPJBasePSP></gPgto>";
237
+ }
238
+
119
239
  /** One cancel event, sent and settled: 218/573 and a request with no answer are looked up. */
120
240
  private function sendCancel(Tools $tools, string $key, callable $send): Response
121
241
  {
@@ -68,6 +68,27 @@ final class SefazReply
68
68
  return $node === null ? null : (string) $this->dom->saveXML($node);
69
69
  }
70
70
 
71
+ /**
72
+ * Every `$tag` element, serialised, in document order.
73
+ *
74
+ * @return list<string>
75
+ */
76
+ public function all(string $tag): array
77
+ {
78
+ $found = [];
79
+ foreach ($this->dom->getElementsByTagName($tag) as $node) {
80
+ $found[] = (string) $this->dom->saveXML($node);
81
+ }
82
+ return $found;
83
+ }
84
+
85
+ /** The attribute `$name` of the first `$tag` element, or null. */
86
+ public function attribute(string $tag, string $name): ?string
87
+ {
88
+ $node = $this->group($tag);
89
+ return $node === null || !$node->hasAttribute($name) ? null : $node->getAttribute($name);
90
+ }
91
+
71
92
  public function has(string $group): bool
72
93
  {
73
94
  return $this->group($group) !== null;
@@ -77,6 +77,8 @@ export const xmlKeys = {
77
77
  `fiscal/${accessKey}/signed-${trimEnd(digest.replace(/\+/g, "-").replace(/\//g, "_"), "=")}.xml`,
78
78
  authorized: (accessKey: string) => `fiscal/${accessKey}/authorized.xml`,
79
79
  cancel: (accessKey: string) => `fiscal/${accessKey}/cancel.xml`,
80
+ /** The event 110300 of `nSeqEvento` `sequence`. */
81
+ linkPayment: (accessKey: string, sequence: number) => `fiscal/${accessKey}/link-payment-${sequence}.xml`,
80
82
  inutilization: (document: FiscalDocument) =>
81
83
  `fiscal/inutilization/${document.environment}/${document.model}/${document.ownerId}/${document.series}-${document.number}.xml`,
82
84
  };
@@ -30,7 +30,8 @@ export {
30
30
  } from "./context";
31
31
  export type { FiscalDocumentsConfig, FiscalNotifyPort, FiscalReasons } from "./context";
32
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
+ export type { CancelOrReturnInput, CancelOrReturnResult, CertificateFacts, FiscalDocuments, FiscalDocumentsServiceConfig, IssueInput, LinkPaymentInput, LinkPaymentResult, SweepReport } from "./service";
34
+ export { MAX_PAYMENT_LINKS } from "./payment-link";
34
35
  export { createMemoryFiscalStore } from "./memory";
35
36
  export type { MemoryFiscalStore } from "./memory";
36
37
  export { FISCAL_NEXT_NUMBER_SQL } from "./sql";
@@ -11,9 +11,10 @@ import type {
11
11
  InutilizedRange,
12
12
  IssuedDocument,
13
13
  LookedUpDocument,
14
+ RegisteredPaymentLink,
14
15
  SidecarErrorBody,
15
16
  } from "../sidecar/types";
16
- import type { SaleForDocument } from "../sale/types";
17
+ import type { LinkedTransaction, SaleForDocument } from "../sale/types";
17
18
  import { FiscalDocumentError } from "./errors";
18
19
  import { type DocumentEventKind, type DocumentTotals, type FiscalDocument, type NumberVoid, isLive } from "./types";
19
20
 
@@ -63,7 +64,15 @@ export type DocumentInput =
63
64
  /** A person took a document back from `attention`: the sweep may try again. */
64
65
  | { readonly kind: "RELEASE" }
65
66
  /** The 24-hour contingency deadline warning went out. */
66
- | { readonly kind: "WARN" };
67
+ | { readonly kind: "WARN" }
68
+ /** SEFAZ registered the event 110300 #`sequence` linking `payment` to the document; its XML is at `eventXmlKey`. */
69
+ | {
70
+ readonly kind: "LINK_PAYMENT";
71
+ readonly answer: RegisteredPaymentLink;
72
+ readonly payment: LinkedTransaction;
73
+ readonly sequence: number;
74
+ readonly eventXmlKey: string | null;
75
+ };
67
76
 
68
77
  type InputOf<K extends DocumentEventKind> = Extract<DocumentInput, { kind: K }>;
69
78
  type Step = { readonly [K in DocumentEventKind]: (document: FiscalDocument, input: InputOf<K>) => Partial<FiscalDocument> };
@@ -257,4 +266,5 @@ export const STEPS: Step = {
257
266
  },
258
267
  // `deadlineWarnedAt` is the transition's own time, set by `transition`.
259
268
  WARN: () => ({}),
269
+ LINK_PAYMENT: () => ({}),
260
270
  };
@@ -21,6 +21,9 @@
21
21
  * final state. A rejected contingency NFC-e is the one way back: the store
22
22
  * corrects it and it is signed again under the same number (`RESIGN`).
23
23
  *
24
+ * `LINK_PAYMENT` records an event 110300 SEFAZ registered on an authorised
25
+ * document (a payment transaction linked after the fact); it changes nothing.
26
+ *
24
27
  * `DEFER`, `RELEASE` and `WARN` record what the sweep and a person did without
25
28
  * changing the state: a failed step counts toward {@link MAX_FAILURES}, after
26
29
  * which the document waits for a person (`attention`).
@@ -52,6 +55,7 @@ export const DOCUMENT_TRANSITIONS: Readonly<Record<DocumentEventKind, readonly F
52
55
  RESIGN: ["REJECTED"],
53
56
  RELEASE: ANY,
54
57
  WARN: ["CONTINGENCY"],
58
+ LINK_PAYMENT: ["AUTHORIZED"],
55
59
  };
56
60
 
57
61
  /** The states nothing but a lookup, a cancel or an inutilization of the number may follow. */
@@ -79,6 +83,9 @@ export function scrubSecrets(value: unknown): unknown {
79
83
  }
80
84
 
81
85
  function answerOf(input: DocumentInput): unknown {
86
+ if (input.kind === "LINK_PAYMENT") {
87
+ return { ...input.answer, payment: input.payment, sequence: input.sequence, eventXmlKey: input.eventXmlKey };
88
+ }
82
89
  if ("answer" in input) return input.answer;
83
90
  if ("error" in input && input.error !== null) return { error: input.error };
84
91
  if (input.kind === "DEFER") return { reason: input.reason };
@@ -0,0 +1,156 @@
1
+ /**
2
+ * The event 110300 "Vinculação Pagamento" (NT 2026.006 v1.00 §5.1): a payment
3
+ * transaction linked to an authorised document after the fact — a Pix QR whose
4
+ * txid was learnt only once the note was out, say. One event per transaction
5
+ * (the event's single `gPgto`), numbered per document (`nSeqEvento`).
6
+ *
7
+ * Idempotent per `(document, transactionId)`: a transaction the document
8
+ * already carries in its own `gPgtoVinc`, or already linked by an earlier
9
+ * event, is skipped with no call to SEFAZ. A refusal answers the issuer's
10
+ * failure and records nothing; the caller may ask again. `nSeqEvento` is the
11
+ * next after the document's own recorded events; a 573 at it is settled by the
12
+ * event SEFAZ holds there (its XML kept, its transaction recorded as its own),
13
+ * and the payment is then sent at the next sequence.
14
+ */
15
+
16
+ import type { IssuerFailure } from "../issuer/port";
17
+ import type { LinkedTransaction, PaymentLinkMeans } from "../sale/types";
18
+ import type { RegisteredPaymentLink } from "../sidecar/types";
19
+ import { xmlKeys } from "./context";
20
+ import { FiscalDocumentError } from "./errors";
21
+ import type { Deps } from "./service-profile";
22
+ import type { FiscalDocument, FiscalDocumentEvent } from "./types";
23
+
24
+ /** `nSeqEvento` runs 1–20 per event type and document. */
25
+ export const MAX_PAYMENT_LINKS = 20;
26
+
27
+ export interface LinkPaymentInput {
28
+ readonly ownerId: string;
29
+ readonly documentId: string;
30
+ readonly payments: readonly LinkedTransaction[];
31
+ }
32
+
33
+ export interface LinkPaymentResult {
34
+ /** The transaction ids SEFAZ registered in this call. */
35
+ readonly linked: readonly string[];
36
+ /** Those the document already carried or an earlier event linked: nothing was sent. */
37
+ readonly alreadyLinked: readonly string[];
38
+ /** The first refusal, if any; the transactions after it were not sent. */
39
+ readonly failure: IssuerFailure | null;
40
+ readonly document: FiscalDocument;
41
+ }
42
+
43
+ /** Each 110300 the document's events record: the transaction and its `nSeqEvento`. */
44
+ function linkedByEvents(events: readonly FiscalDocumentEvent[]): Array<{ transactionId: string; sequence: number }> {
45
+ return events
46
+ .filter((event) => event.kind === "LINK_PAYMENT")
47
+ .map((event, index) => {
48
+ const answer = event.answer as { payment?: { transactionId?: unknown }; sequence?: unknown } | null;
49
+ return {
50
+ transactionId: answer?.payment?.transactionId,
51
+ sequence: typeof answer?.sequence === "number" ? answer.sequence : index + 1,
52
+ };
53
+ })
54
+ .filter((link): link is { transactionId: string; sequence: number } => typeof link.transactionId === "string");
55
+ }
56
+
57
+ /** The transaction ids the document's own `gPgtoVinc` carries. */
58
+ function linkedInDocument(document: FiscalDocument): string[] {
59
+ return document.sale.payments
60
+ .map((payment) => payment.linkedTransaction?.transactionId)
61
+ .filter((id): id is string => typeof id === "string");
62
+ }
63
+
64
+ /** What every event of this document is sent with: its key, its protocol and the issuer's event call. */
65
+ function linkable(deps: Deps, document: FiscalDocument) {
66
+ const { accessKey, protocol } = document;
67
+ if (document.status !== "AUTHORIZED" || accessKey === null || protocol === null) {
68
+ throw new FiscalDocumentError("TRANSITION_REFUSED", `document ${document.id} is ${document.status}; only an authorised document is linked.`);
69
+ }
70
+ const send = deps.config.issuer.linkPayment;
71
+ if (typeof send !== "function") throw new FiscalDocumentError("NOT_SUPPORTED", "this issuer does not register the event 110300.");
72
+ return { accessKey, protocol, send: send.bind(deps.config.issuer) };
73
+ }
74
+
75
+ /**
76
+ * The transaction SEFAZ holds at the sequence just sent. A 135 registered what
77
+ * was sent. A 573 answers the event already there, looked up: the same
78
+ * transaction (a retry whose recording was lost), or another one, which is
79
+ * then recorded as ITS link and never attributed to `sent`.
80
+ */
81
+ function heldTransaction(answer: RegisteredPaymentLink, sent: LinkedTransaction, requested: readonly LinkedTransaction[]): LinkedTransaction {
82
+ if (answer.statusCode !== "573" || answer.transaction.transactionId === sent.transactionId) return sent;
83
+ const held = answer.transaction;
84
+ return (
85
+ requested.find((payment) => payment.transactionId === held.transactionId) ?? {
86
+ transactionId: held.transactionId,
87
+ meansCode: held.meansCode as PaymentLinkMeans,
88
+ pspCnpjBase: held.pspCnpjBase,
89
+ receiverCnpj: held.receiverCnpj,
90
+ }
91
+ );
92
+ }
93
+
94
+ /** One call's progress: the document as last advanced, the next `nSeqEvento`, what is linked. */
95
+ interface LinkRun {
96
+ document: FiscalDocument;
97
+ sequence: number;
98
+ readonly known: Set<string>;
99
+ readonly requested: readonly LinkedTransaction[];
100
+ readonly linked: string[];
101
+ readonly send: (sequence: number, payment: LinkedTransaction) => ReturnType<NonNullable<Deps["config"]["issuer"]["linkPayment"]>>;
102
+ }
103
+
104
+ function refuseOverLimit(document: FiscalDocument): never {
105
+ throw new FiscalDocumentError("INVALID_INPUT", `document ${document.id} cannot take more than ${MAX_PAYMENT_LINKS} payment links.`);
106
+ }
107
+
108
+ /**
109
+ * Sends `payment` at the run's sequence and records what SEFAZ holds there.
110
+ * When that is another transaction (a 573), it is recorded as its own link and
111
+ * `payment` goes out again at the next sequence. Answers the refusal, if any.
112
+ */
113
+ async function sendOne(deps: Deps, run: LinkRun, accessKey: string, payment: LinkedTransaction): Promise<IssuerFailure | null> {
114
+ if (run.sequence > MAX_PAYMENT_LINKS) refuseOverLimit(run.document);
115
+ const sequence = run.sequence;
116
+ const outcome = await run.send(sequence, payment);
117
+ if (!outcome.ok) return outcome.error;
118
+ const held = heldTransaction(outcome.answer, payment, run.requested);
119
+ const { eventXml } = outcome.answer;
120
+ const eventXmlKey = eventXml === null ? null : xmlKeys.linkPayment(accessKey, sequence);
121
+ if (eventXmlKey !== null && eventXml !== null) await deps.config.storage.put(eventXmlKey, eventXml, "application/xml");
122
+ run.document = await deps.ctx.advance(run.document, { kind: "LINK_PAYMENT", answer: outcome.answer, payment: held, sequence, eventXmlKey });
123
+ run.known.add(held.transactionId);
124
+ if (run.requested.some((one) => one.transactionId === held.transactionId)) run.linked.push(held.transactionId);
125
+ run.sequence = sequence + 1;
126
+ return held.transactionId === payment.transactionId ? null : sendOne(deps, run, accessKey, payment);
127
+ }
128
+
129
+ export async function linkPayment(deps: Deps, input: LinkPaymentInput): Promise<LinkPaymentResult> {
130
+ const document = await deps.config.store.getDocument(input.ownerId, input.documentId);
131
+ if (document === null) throw new FiscalDocumentError("NOT_FOUND", `owner ${input.ownerId} has no document ${input.documentId}.`);
132
+ const { accessKey, protocol, send } = linkable(deps, document);
133
+ const byEvents = linkedByEvents(await deps.config.store.listEvents(document.id));
134
+ const known = new Set([...linkedInDocument(document), ...byEvents.map((link) => link.transactionId)]);
135
+ const pending = input.payments.filter((payment) => !known.has(payment.transactionId));
136
+ const alreadyLinked = input.payments.filter((payment) => known.has(payment.transactionId)).map((payment) => payment.transactionId);
137
+ // `nSeqEvento` follows the document's own events, never a count of anything else.
138
+ const sequence = Math.max(0, ...byEvents.map((link) => link.sequence)) + 1;
139
+ if (sequence - 1 + pending.length > MAX_PAYMENT_LINKS) refuseOverLimit(document);
140
+ if (pending.length === 0) return { linked: [], alreadyLinked, failure: null, document };
141
+ const signing = await deps.ctx.material(await deps.ctx.requireProfile(input.ownerId));
142
+ const run: LinkRun = {
143
+ document,
144
+ sequence,
145
+ known,
146
+ requested: pending,
147
+ linked: [],
148
+ send: (at, payment) => send({ model: document.model, environment: document.environment, signing, accessKey, protocol, sequence: at, payments: [payment] }),
149
+ };
150
+ for (const payment of pending) {
151
+ if (run.known.has(payment.transactionId)) continue;
152
+ const failure = await sendOne(deps, run, accessKey, payment);
153
+ if (failure !== null) return { linked: run.linked, alreadyLinked, failure, document: run.document };
154
+ }
155
+ return { linked: run.linked, alreadyLinked, failure: null, document: run.document };
156
+ }
@@ -18,11 +18,13 @@ import { FiscalDocumentError } from "./errors";
18
18
  import { canTransition } from "./machine";
19
19
  import { type Deps, type FiscalDocumentsServiceConfig, createIssuingPoint, saveProfile, uploadCertificate } from "./service-profile";
20
20
  import { settleNumber, settleWithXml, storeNfeProc } from "./settle";
21
+ import { linkPayment } from "./payment-link";
21
22
  import { answerLive, assertOnlineDeadline, signPending, submit, transmit } from "./steps";
22
23
  import { type CancelOrReturnInput, type CancelOrReturnResult, type DocumentTotals, type FiscalDocument, type FiscalDocumentModel, isLive } from "./types";
23
24
 
24
25
  export type { CertificateFacts, FiscalDocumentsServiceConfig } from "./service-profile";
25
26
  export type { CancelOrReturnInput, CancelOrReturnResult } from "./types";
27
+ export type { LinkPaymentInput, LinkPaymentResult } from "./payment-link";
26
28
 
27
29
  export interface SweepReport {
28
30
  readonly advanced: Array<{ readonly documentId: string; readonly status: FiscalDocument["status"] }>;
@@ -356,6 +358,8 @@ export function createFiscalDocuments(config: FiscalDocumentsServiceConfig) {
356
358
  * (501) — issue the buyer's return NF-e of entry quoting it. Idempotent.
357
359
  */
358
360
  cancelOrReturn: cancelOrReturn.bind(null, deps),
361
+ /** Link payment transactions to an authorised document (event 110300), once each. Idempotent. */
362
+ linkPayment: linkPayment.bind(null, deps),
359
363
  /** Ask SEFAZ what it knows of the key; a state the answer moves is recorded. */
360
364
  lookup: lookup.bind(null, deps),
361
365
  /** A person takes a document back from `attention`; the sweep tries it again. */
@@ -175,7 +175,8 @@ export type DocumentEventKind =
175
175
  | "DEFER"
176
176
  | "RESIGN"
177
177
  | "RELEASE"
178
- | "WARN";
178
+ | "WARN"
179
+ | "LINK_PAYMENT";
179
180
 
180
181
  /**
181
182
  * One transition, as stored. `answer` is what the fiscal service answered,
@@ -12,7 +12,7 @@
12
12
  */
13
13
 
14
14
  import type { FiscalDocumentModel } from "../documents/types";
15
- import type { SaleForDocument } from "../sale/types";
15
+ import type { LinkedTransaction, SaleForDocument } from "../sale/types";
16
16
  import type {
17
17
  CancelledDocument,
18
18
  ContingencyEntry,
@@ -21,6 +21,7 @@ import type {
21
21
  InutilizedRange,
22
22
  IssuedDocument,
23
23
  LookedUpDocument,
24
+ RegisteredPaymentLink,
24
25
  SefazEnvironment,
25
26
  SidecarErrorBody,
26
27
  SidecarHealth,
@@ -73,6 +74,21 @@ export interface CancelBySubstitutionCall extends Call {
73
74
  readonly substituteAccessKey: string;
74
75
  }
75
76
 
77
+ /** The event 110300 "Vinculação Pagamento" (NT 2026.006 v1.00): one transaction linked to an authorised document. */
78
+ export interface LinkPaymentCall extends Call {
79
+ readonly model: FiscalDocumentModel;
80
+ readonly accessKey: string;
81
+ readonly protocol: string;
82
+ /** `nSeqEvento`, 1–20. */
83
+ readonly sequence: number;
84
+ /**
85
+ * The transactions the event links. Exactly ONE today: the event's schema
86
+ * (`e110300_v1.00.xsd`) carries a single `gPgto`, so the service refuses any
87
+ * other count as INVALID; the list is the NT group's own shape.
88
+ */
89
+ readonly payments: readonly LinkedTransaction[];
90
+ }
91
+
76
92
  export interface LookupCall extends Call {
77
93
  readonly model: FiscalDocumentModel;
78
94
  readonly accessKey: string;
@@ -99,6 +115,13 @@ export interface Issuer {
99
115
  cancel(call: CancelCall): Promise<IssuerOutcome<CancelledDocument>>;
100
116
  cancelBySubstitution(call: CancelBySubstitutionCall): Promise<IssuerOutcome<CancelledDocument>>;
101
117
  lookup(call: LookupCall): Promise<IssuerOutcome<LookedUpDocument>>;
118
+ /**
119
+ * The event 110300. Optional on the port so an issuer written before it
120
+ * still satisfies the type; one that lacks it cannot link (the document
121
+ * service answers `NOT_SUPPORTED`), and a host may read its presence as
122
+ * "this issuer writes `gPgtoVinc`".
123
+ */
124
+ linkPayment?(call: LinkPaymentCall): Promise<IssuerOutcome<RegisteredPaymentLink>>;
102
125
  inutilize(call: InutilizeCall): Promise<IssuerOutcome<InutilizedRange>>;
103
126
  health(): Promise<SidecarHealth>;
104
127
  }
@@ -17,6 +17,7 @@ import type {
17
17
  CancelRequest,
18
18
  InutilizeRequest,
19
19
  IssueRequest,
20
+ LinkPaymentRequest,
20
21
  LookupRequest,
21
22
  SidecarErrorBody,
22
23
  SidecarHealth,
@@ -143,6 +144,15 @@ export function createSidecarIssuer(config: SidecarIssuerConfig): Issuer {
143
144
  reason,
144
145
  substituteAccessKey,
145
146
  } satisfies CancelBySubstitutionRequest),
147
+ linkPayment: ({ model, environment, signing, accessKey, protocol, sequence, payments }) =>
148
+ call(`/${modelPath(model)}/link-payment`, {
149
+ environment,
150
+ certificate: signing.certificate,
151
+ accessKey,
152
+ protocol,
153
+ sequence,
154
+ payments,
155
+ } satisfies LinkPaymentRequest),
146
156
  lookup: ({ model, environment, signing, accessKey }) =>
147
157
  call(`/${modelPath(model)}/lookup`, { environment, certificate: signing.certificate, accessKey } satisfies LookupRequest),
148
158
  inutilize: ({ model, environment, signing, uf, cnpj, year, series, from, to, reason }) =>
package/src/sale/index.ts CHANGED
@@ -5,4 +5,5 @@
5
5
  * `@12-apps/fiscal/sidecar/schema/sale-for-document.schema.json`.
6
6
  */
7
7
 
8
+ export { PAYMENT_LINK_MEANS } from "./types";
8
9
  export type * from "./types";
package/src/sale/types.ts CHANGED
@@ -208,6 +208,29 @@ export interface CardDetails {
208
208
  readonly authorizationCode: string | null;
209
209
  }
210
210
 
211
+ /**
212
+ * `tpMeioPgto` (Informe Técnico 2026.001 v1.01): the means a linked payment
213
+ * transaction moved by — 15 boleto, 17 Pix QR dinâmico, 18 TED, 20 Pix by key
214
+ * or static QR, 23 Pix automático, 24 TEF. A card and cash have none.
215
+ */
216
+ export const PAYMENT_LINK_MEANS = ["15", "17", "18", "20", "23", "24"] as const;
217
+ export type PaymentLinkMeans = (typeof PAYMENT_LINK_MEANS)[number];
218
+
219
+ /**
220
+ * `gPgtoVinc/gPgto` (NT 2026.006 v1.00): a payment transaction started before
221
+ * the document — a Pix QR raised, a boleto generated — linked by its id, so the
222
+ * split payment can find the document. The event 110300 links one after the fact.
223
+ */
224
+ export interface LinkedTransaction {
225
+ /** `idTransacao`, 2–35 characters: the Pix txid, the boleto's or the transfer's id. */
226
+ readonly transactionId: string;
227
+ readonly meansCode: PaymentLinkMeans;
228
+ /** `CNPJBasePSP`: the 8-character CNPJ base of the receiver's payment institution. */
229
+ readonly pspCnpjBase: string;
230
+ /** `CNPJReceb`: who receives the money (the issuer, or a platform receiving for it). */
231
+ readonly receiverCnpj: string;
232
+ }
233
+
211
234
  export interface SalePayment {
212
235
  readonly method: PaymentMethod;
213
236
  readonly amountCents: number;
@@ -215,6 +238,13 @@ export interface SalePayment {
215
238
  readonly card: CardDetails | null;
216
239
  /** `xPag`: required when `method` is `OTHER`. */
217
240
  readonly description: string | null;
241
+ /**
242
+ * The transaction this payment was started as, written in `gPgtoVinc` with
243
+ * `nPag` = its position. Absent or `null`: no link. The host decides whether
244
+ * the environment accepts the group (optional in the layout; its production
245
+ * activation is the fisco's).
246
+ */
247
+ readonly linkedTransaction?: LinkedTransaction | null;
218
248
  }
219
249
 
220
250
  /** `finNFe` 1–4. */