@sinete/nfe 0.0.0 → 0.1.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 (101) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +11 -0
  3. package/README.md +147 -1
  4. package/dist/build/build.d.ts +127 -0
  5. package/dist/build/build.d.ts.map +1 -0
  6. package/dist/build/destinatario.d.ts +19 -0
  7. package/dist/build/destinatario.d.ts.map +1 -0
  8. package/dist/build/ibscbs.d.ts +27 -0
  9. package/dist/build/ibscbs.d.ts.map +1 -0
  10. package/dist/build/icms.d.ts +42 -0
  11. package/dist/build/icms.d.ts.map +1 -0
  12. package/dist/build/nfce.d.ts +122 -0
  13. package/dist/build/nfce.d.ts.map +1 -0
  14. package/dist/build/pl.d.ts +19 -0
  15. package/dist/build/pl.d.ts.map +1 -0
  16. package/dist/build/rejeicoes.d.ts +52 -0
  17. package/dist/build/rejeicoes.d.ts.map +1 -0
  18. package/dist/build/tributos.d.ts +45 -0
  19. package/dist/build/tributos.d.ts.map +1 -0
  20. package/dist/build/values.d.ts +48 -0
  21. package/dist/build/values.d.ts.map +1 -0
  22. package/dist/decimal.d.ts +66 -0
  23. package/dist/decimal.d.ts.map +1 -0
  24. package/dist/format.d.ts +48 -0
  25. package/dist/format.d.ts.map +1 -0
  26. package/dist/ibs-cbs.d.ts +14 -0
  27. package/dist/ibs-cbs.d.ts.map +1 -0
  28. package/dist/ibs-cbs.js +43 -0
  29. package/dist/ibs-cbs.js.map +10 -0
  30. package/dist/index.d.ts +37 -0
  31. package/dist/index.d.ts.map +1 -0
  32. package/dist/index.js +4370 -0
  33. package/dist/index.js.map +33 -0
  34. package/dist/issues.d.ts +24 -0
  35. package/dist/issues.d.ts.map +1 -0
  36. package/dist/model.d.ts +861 -0
  37. package/dist/model.d.ts.map +1 -0
  38. package/dist/ports.d.ts +109 -0
  39. package/dist/ports.d.ts.map +1 -0
  40. package/dist/rotulo.d.ts +12 -0
  41. package/dist/rotulo.d.ts.map +1 -0
  42. package/dist/rtc.d.ts +65 -0
  43. package/dist/rtc.d.ts.map +1 -0
  44. package/dist/services/client.d.ts +273 -0
  45. package/dist/services/client.d.ts.map +1 -0
  46. package/dist/services/gzip.d.ts +7 -0
  47. package/dist/services/gzip.d.ts.map +1 -0
  48. package/dist/services/index.d.ts +14 -0
  49. package/dist/services/index.d.ts.map +1 -0
  50. package/dist/services/outcome.d.ts +15 -0
  51. package/dist/services/outcome.d.ts.map +1 -0
  52. package/dist/services/proc.d.ts +41 -0
  53. package/dist/services/proc.d.ts.map +1 -0
  54. package/dist/services/recuperar.d.ts +28 -0
  55. package/dist/services/recuperar.d.ts.map +1 -0
  56. package/dist/services/resolver.d.ts +88 -0
  57. package/dist/services/resolver.d.ts.map +1 -0
  58. package/dist/services/soap.d.ts +43 -0
  59. package/dist/services/soap.d.ts.map +1 -0
  60. package/dist/time.d.ts +12 -0
  61. package/dist/time.d.ts.map +1 -0
  62. package/dist/versao-gerada.d.ts +3 -0
  63. package/dist/versao-gerada.d.ts.map +1 -0
  64. package/package.json +58 -3
  65. package/src/build/build.ts +1486 -0
  66. package/src/build/destinatario.ts +212 -0
  67. package/src/build/ibscbs.ts +131 -0
  68. package/src/build/icms.ts +645 -0
  69. package/src/build/nfce.ts +425 -0
  70. package/src/build/pl.ts +73 -0
  71. package/src/build/rejeicoes.ts +142 -0
  72. package/src/build/tributos.ts +217 -0
  73. package/src/build/values.ts +126 -0
  74. package/src/data/arredondamento.json +30 -0
  75. package/src/data/cstat.json +36 -0
  76. package/src/data/fusos.json +17 -0
  77. package/src/data/nfce-urls.json +170 -0
  78. package/src/data/produtor-rural.json +17 -0
  79. package/src/data/reforma.json +6 -0
  80. package/src/data/resp-tec.json +13 -0
  81. package/src/data/servicos.json +44 -0
  82. package/src/data/suframa.json +7 -0
  83. package/src/decimal.ts +231 -0
  84. package/src/format.ts +64 -0
  85. package/src/ibs-cbs.ts +89 -0
  86. package/src/index.ts +153 -0
  87. package/src/issues.ts +80 -0
  88. package/src/model.ts +1033 -0
  89. package/src/ports.ts +96 -0
  90. package/src/rotulo.ts +137 -0
  91. package/src/rtc.ts +305 -0
  92. package/src/services/client.ts +1085 -0
  93. package/src/services/gzip.ts +26 -0
  94. package/src/services/index.ts +43 -0
  95. package/src/services/outcome.ts +50 -0
  96. package/src/services/proc.ts +164 -0
  97. package/src/services/recuperar.ts +91 -0
  98. package/src/services/resolver.ts +127 -0
  99. package/src/services/soap.ts +133 -0
  100. package/src/time.ts +23 -0
  101. package/src/versao-gerada.ts +3 -0
package/dist/index.js ADDED
@@ -0,0 +1,4370 @@
1
+ // packages/nfe/src/build/build.ts
2
+ import { ConfigError as ConfigError2, fixedClock as fixedClock2, formatarVerProc, isUf as isUf2, tpAmbOf as tpAmbOf2, ufBySigla as ufBySigla2, ValidationError } from "@sinete/core";
3
+ import { base64Encode as base64Encode2, firstChild as firstChild3, parseXml as parseXml3, signXml } from "@sinete/core/xml";
4
+ import { SerializeError, serialize as serialize2, validate as validate3 } from "@sinete/schemas";
5
+ import { TIS as TISCt, TNFe_infNFeSupl, TTribNFe as TTribNFeCt } from "@sinete/schemas/nfe/PL_010f";
6
+ import { buildChaveAcesso, parseChaveAcesso, parseCnpj as parseCnpj3, parseCpf, parseIe } from "@sinete/validators";
7
+ // packages/nfe/src/data/arredondamento.json
8
+ var arredondamento_default = {
9
+ descricao: "Modo de arredondamento dos valores calculados pelo builder, por família de campo. HALF_UP é o arredondamento comercial; HALF_EVEN é o bancário (NBR 5891). Quem emite pode sobrepor por família em BuildNfeOptions.arredondamento.",
10
+ atualizadoEm: "2026-09-26",
11
+ familias: {
12
+ produto: {
13
+ modo: "HALF_UP",
14
+ fonte: "MOC 7.0 Anexo I, nota (*4): o produto de multiplicações arredonda em 2 casas, com tolerância de R$ 0,01; o modo não é fixado. vProd = qCom x vUnCom (I11)."
15
+ },
16
+ icms: {
17
+ modo: "HALF_UP",
18
+ fonte: "MOC 7.0 Anexo I, nota (*4) das regras N17, N16a, N16c, N23d: 2 casas, tolerância de R$ 0,01, modo não fixado."
19
+ },
20
+ ipi: {
21
+ modo: "HALF_UP",
22
+ fonte: "MOC 7.0 Anexo I, nota (*4): 2 casas, tolerância de R$ 0,01."
23
+ },
24
+ pisCofins: {
25
+ modo: "HALF_UP",
26
+ fonte: "MOC 7.0 Anexo I, nota (*4): 2 casas, tolerância de R$ 0,01."
27
+ },
28
+ issqn: {
29
+ modo: "HALF_UP",
30
+ fonte: "MOC 7.0 Anexo I, nota (*4): 2 casas, tolerância de R$ 0,01."
31
+ },
32
+ ibsCbs: {
33
+ modo: "HALF_EVEN",
34
+ fonte: "NT 2025.002 v1.51, RV UB35-10 e seguintes (tolerância de 0,01) e ADR 0007 (a Calculadora da RFB arredonda em HALF_EVEN)."
35
+ }
36
+ }
37
+ };
38
+ // packages/nfe/src/data/produtor-rural.json
39
+ var produtor_rural_default = {
40
+ descricao: "Regras do produtor rural que variam no tempo ou por UF. refNFP: a nota fiscal de produtor em papel (modelo 04) foi extinta; uma NF-e ainda pode referenciar uma nota modelo 04 emitida antes do fim da vigência na UF da nota referenciada. vedadaDesde é o primeiro AAMM em que a UF não aceita mais nota modelo 04 emitida; a referência a nota com AAMM igual ou posterior é recusada pelo builder. series: faixas de série por tipo de emitente na emissão pelo contribuinte (procEmi 0, a única que o buildNfe monta).",
41
+ atualizadoEm: "2026-09-28",
42
+ refNFP: {
43
+ modelo04: {
44
+ vedadaDesde: "2601",
45
+ fonte: "Ajuste SINIEF 10/2022 (extinção da nota fiscal de produtor modelo 4, com prazos prorrogados até 05/01/2026) e avisos das SEFAZ (RS e SP: fim do talão em 05/01/2026)."
46
+ },
47
+ ufs: {}
48
+ },
49
+ series: {
50
+ cpf: [920, 969],
51
+ fonte: "MOC 7.0 Anexo I, RV B07 e BA02-30: séries 920 a 969 reservadas à NF-e emitida por pessoa física (CPF).",
52
+ cnpj: [0, 889],
53
+ fonteCnpj: "MOC 7.0 Anexo I, RV C02-30 (emitente CNPJ: séries 0 a 909, rejeição 503) e B26-10 (emissão pelo contribuinte, procEmi 0: séries 0 a 889 ou 920 a 969, rejeição 244): as duas juntas deixam 0 a 889. A NT 2026.001 v1.02b (PAA, produção em 05/10/2026) abre 980 a 989 na C02-30 e mantém a B26-10, então a faixa continua 0 a 889."
54
+ }
55
+ };
56
+ // packages/nfe/src/data/reforma.json
57
+ var reforma_default = {
58
+ descricao: "Parâmetros da reforma tributária no total do item e da nota. vItemSomaTributosDesde: a partir desta data do fato gerador (Brasília), vItem soma vIBS, vCBS, vIS e os totais monofásicos; antes dela, não soma (exceção de 2025 e 2026).",
59
+ atualizadoEm: "2026-09-26",
60
+ vItemSomaTributosDesde: "2027-01-01",
61
+ fonte: "NT 2025.002 v1.51, RV VB01-10 e VB01-20, Exceção 1: em 2025 e 2026 não somar vIBS, vCBS, vIS, vTotIBSMonoItem e vTotCBSMonoItem."
62
+ };
63
+ // packages/nfe/src/data/resp-tec.json
64
+ var resp_tec_default = {
65
+ descricao: "Exigência do grupo infRespTec e do CSRT por UF do emitente, com vigência por ambiente. infRespTec: 'obrigatorio' faz o builder recusar a nota sem responsável técnico; 'opcional' só o inclui quando informado. csrt: 'obrigatorio' exige idCSRT e hashCSRT (rejeição 975). Datas no formato AAAA-MM-DD, a partir de 00:00 de Brasília. UF ausente usa o padrão. A adesão é de cada UF (NT 2018.005); quem emite pode sobrepor em BuildNfeOptions.",
66
+ atualizadoEm: "2026-09-26",
67
+ fonte: "NT 2018.005 v1.50 (responsável técnico e CSRT, adesão a critério da UF)",
68
+ padrao: { infRespTec: "opcional", csrt: "opcional" },
69
+ ufs: {
70
+ PR: {
71
+ csrt: { homologacao: "2025-03-02", producao: "2025-09-15" },
72
+ infRespTec: { homologacao: "2025-03-02", producao: "2025-09-15" },
73
+ fonte: "SEFAZ-PR, NT 2018.005 v1.50: CSRT obrigatório na NF-e em homologação desde 02/03/2025 e em produção desde 15/09/2025 (aviso da SEFAZ-PR, reproduzido em https://inventti.com.br/nf-e-nfc-e-nt-2018-005-versao-1-50-prorroga-regras-de-validacao-para-uf-do-parana/)."
74
+ }
75
+ }
76
+ };
77
+
78
+ // packages/nfe/src/decimal.ts
79
+ import { ConfigError } from "@sinete/core";
80
+ var DECIMAL_TEXT = /^([+-])?(\d+)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$|^([+-])?\.(\d+)(?:[eE]([+-]?\d+))?$/;
81
+ var MAX_SCALE = 64;
82
+ function pow10(n) {
83
+ return 10n ** BigInt(n);
84
+ }
85
+
86
+ class Decimal {
87
+ coef;
88
+ scale;
89
+ constructor(coef, scale) {
90
+ this.coef = coef;
91
+ this.scale = scale;
92
+ }
93
+ static ZERO = new Decimal(0n, 0);
94
+ static ONE = new Decimal(1n, 0);
95
+ static HUNDRED = new Decimal(100n, 0);
96
+ static fromParts(coef, scale) {
97
+ if (!Number.isInteger(scale) || scale < 0 || scale > MAX_SCALE)
98
+ throw new ConfigError(`escala inválida: ${scale}`);
99
+ return new Decimal(coef, scale);
100
+ }
101
+ static of(input) {
102
+ const d = Decimal.tryOf(input);
103
+ if (d === undefined)
104
+ throw new ConfigError(`número decimal inválido: ${JSON.stringify(String(input))}`);
105
+ return d;
106
+ }
107
+ static tryOf(input) {
108
+ if (input instanceof Decimal)
109
+ return input;
110
+ if (typeof input === "bigint")
111
+ return new Decimal(input, 0);
112
+ if (typeof input === "number") {
113
+ if (!Number.isFinite(input))
114
+ return;
115
+ return Decimal.tryOf(String(input));
116
+ }
117
+ if (typeof input !== "string")
118
+ return;
119
+ const m = DECIMAL_TEXT.exec(input);
120
+ if (!m)
121
+ return;
122
+ const sign = (m[1] ?? m[5]) === "-" ? -1n : 1n;
123
+ const intPart = m[2] ?? "";
124
+ const frac = m[3] ?? m[6] ?? "";
125
+ const exp = Number(m[4] ?? m[7] ?? "0");
126
+ if (!Number.isSafeInteger(exp) || Math.abs(exp) > MAX_SCALE)
127
+ return;
128
+ let coef = BigInt(`${intPart}${frac}` || "0") * sign;
129
+ let scale = frac.length - exp;
130
+ if (scale < 0) {
131
+ coef *= pow10(-scale);
132
+ scale = 0;
133
+ }
134
+ if (scale > MAX_SCALE)
135
+ return;
136
+ return new Decimal(coef, scale);
137
+ }
138
+ aligned(other) {
139
+ if (this.scale === other.scale)
140
+ return [this.coef, other.coef, this.scale];
141
+ if (this.scale > other.scale)
142
+ return [this.coef, other.coef * pow10(this.scale - other.scale), this.scale];
143
+ return [this.coef * pow10(other.scale - this.scale), other.coef, other.scale];
144
+ }
145
+ plus(other) {
146
+ const [a, b, s] = this.aligned(Decimal.of(other));
147
+ return new Decimal(a + b, s);
148
+ }
149
+ minus(other) {
150
+ const [a, b, s] = this.aligned(Decimal.of(other));
151
+ return new Decimal(a - b, s);
152
+ }
153
+ times(other) {
154
+ const o = Decimal.of(other);
155
+ const scale = this.scale + o.scale;
156
+ if (scale > MAX_SCALE) {
157
+ return new Decimal(this.coef * o.coef, scale).round(MAX_SCALE, "HALF_EVEN");
158
+ }
159
+ return new Decimal(this.coef * o.coef, scale);
160
+ }
161
+ dividedBy(other, scale, mode) {
162
+ const o = Decimal.of(other);
163
+ if (o.coef === 0n)
164
+ throw new ConfigError("divisão por zero");
165
+ const shift = o.scale + scale + 1 - this.scale;
166
+ const num = shift >= 0 ? this.coef * pow10(shift) : this.coef;
167
+ const den = shift >= 0 ? o.coef : o.coef * pow10(-shift);
168
+ const q = num / den;
169
+ const exact = q * den === num;
170
+ return roundCoef(q, scale + 1, scale, mode, !exact);
171
+ }
172
+ percent(rate) {
173
+ const product = this.times(rate);
174
+ return new Decimal(product.coef, product.scale + 2);
175
+ }
176
+ negate() {
177
+ return new Decimal(-this.coef, this.scale);
178
+ }
179
+ abs() {
180
+ return this.coef < 0n ? this.negate() : this;
181
+ }
182
+ round(scale, mode) {
183
+ if (!Number.isInteger(scale) || scale < 0)
184
+ throw new ConfigError(`casas decimais inválidas: ${scale}`);
185
+ if (scale >= this.scale)
186
+ return new Decimal(this.coef * pow10(scale - this.scale), scale);
187
+ return roundCoef(this.coef, this.scale, scale, mode, false);
188
+ }
189
+ compare(other) {
190
+ const [a, b] = this.aligned(Decimal.of(other));
191
+ return a < b ? -1 : a > b ? 1 : 0;
192
+ }
193
+ eq(other) {
194
+ return this.compare(other) === 0;
195
+ }
196
+ lt(other) {
197
+ return this.compare(other) < 0;
198
+ }
199
+ gt(other) {
200
+ return this.compare(other) > 0;
201
+ }
202
+ isZero() {
203
+ return this.coef === 0n;
204
+ }
205
+ isNegative() {
206
+ return this.coef < 0n;
207
+ }
208
+ significantScale() {
209
+ if (this.coef === 0n)
210
+ return 0;
211
+ let c = this.coef;
212
+ let s = this.scale;
213
+ while (s > 0 && c % 10n === 0n) {
214
+ c /= 10n;
215
+ s--;
216
+ }
217
+ return s;
218
+ }
219
+ toFixed(scale, mode = "HALF_UP") {
220
+ const r = this.round(scale, mode);
221
+ const neg = r.coef < 0n;
222
+ const digits = (neg ? -r.coef : r.coef).toString().padStart(scale + 1, "0");
223
+ const int = digits.slice(0, digits.length - scale);
224
+ const frac = digits.slice(digits.length - scale);
225
+ return `${neg ? "-" : ""}${int}${scale > 0 ? `.${frac}` : ""}`;
226
+ }
227
+ toString() {
228
+ return this.toFixed(this.significantScale());
229
+ }
230
+ toJSON() {
231
+ return this.toString();
232
+ }
233
+ }
234
+ function roundCoef(coef, from, to, mode, sticky) {
235
+ const div = pow10(from - to);
236
+ const neg = coef < 0n;
237
+ const abs = neg ? -coef : coef;
238
+ let q = abs / div;
239
+ const r = abs % div;
240
+ if (mode !== "DOWN" && (r !== 0n || sticky)) {
241
+ const twice = r * 2n;
242
+ const above = twice > div || twice === div && sticky;
243
+ const tie = twice === div && !sticky;
244
+ if (above || tie && (mode === "HALF_UP" || mode === "HALF_EVEN" && q % 2n === 1n))
245
+ q += 1n;
246
+ }
247
+ return Decimal.fromParts(neg ? -q : q, to);
248
+ }
249
+ function dec(input) {
250
+ return Decimal.of(input);
251
+ }
252
+ function sum(values) {
253
+ let acc = Decimal.ZERO;
254
+ for (const v of values)
255
+ acc = acc.plus(v);
256
+ return acc;
257
+ }
258
+
259
+ // packages/nfe/src/format.ts
260
+ var D1302 = { name: "TDec_1302", min: 2, max: 2, intDigits: 13 };
261
+ var D1302_OPC = { name: "TDec_1302Opc", min: 2, max: 2, intDigits: 13, nonZero: true };
262
+ var D0302A04 = { name: "TDec_0302a04", min: 2, max: 4, intDigits: 3 };
263
+ var D0302A04_OPC = { name: "TDec_0302a04Opc", min: 2, max: 4, intDigits: 3 };
264
+ var D0302 = { name: "TDec_0302Max100", min: 2, max: 2, intDigits: 3 };
265
+ var D1104V = { name: "TDec_1104v", min: 0, max: 4, intDigits: 11 };
266
+ var D1104 = { name: "TDec_1104", min: 4, max: 4, intDigits: 11 };
267
+ var D1110V = { name: "TDec_1110v", min: 0, max: 10, intDigits: 11 };
268
+ var D1204V = { name: "TDec_1204v", min: 0, max: 4, intDigits: 12 };
269
+ var D1204 = { name: "TDec_1204", min: 4, max: 4, intDigits: 12 };
270
+ var D1203 = { name: "TDec_1203", min: 3, max: 3, intDigits: 12 };
271
+ function formatDecimal(value, format, mode = "HALF_UP") {
272
+ const r = value.round(format.max, mode);
273
+ let places = Math.max(format.min, Math.min(format.max, r.significantScale()));
274
+ if (format.minBelowOne !== undefined && !r.isZero() && r.abs().lt(1))
275
+ places = Math.max(places, format.minBelowOne);
276
+ return r.toFixed(places, mode);
277
+ }
278
+ function formatProblem(value, format) {
279
+ if (value.isNegative())
280
+ return "valor negativo";
281
+ if (format.nonZero && value.isZero())
282
+ return "valor zero não é aceito neste campo";
283
+ if (value.significantScale() > format.max)
284
+ return `mais de ${format.max} casas decimais`;
285
+ const intDigits = value.round(0, "DOWN").abs().toString().replace(/^0$/, "").length;
286
+ if (intDigits > format.intDigits)
287
+ return `mais de ${format.intDigits} dígitos inteiros`;
288
+ return;
289
+ }
290
+
291
+ // packages/nfe/src/issues.ts
292
+ var NFE_ISSUE_CODES = [
293
+ "campo_obrigatorio",
294
+ "campo_invalido",
295
+ "campo_fora_do_pl",
296
+ "decimal_invalido",
297
+ "valor_divergente",
298
+ "combinacao_invalida",
299
+ "modelo_nao_suportado",
300
+ "serie_invalida",
301
+ "documento_invalido",
302
+ "ie_invalida",
303
+ "chave_invalida",
304
+ "referencia_vedada",
305
+ "resp_tec_obrigatorio",
306
+ "csrt_obrigatorio",
307
+ "ibscbs_calculo",
308
+ "ibscbs_base_ausente",
309
+ "ibscbs_nao_suportado",
310
+ "ibscbs_redutor_divergente",
311
+ "ibscbs_regra_nt",
312
+ "totais_divergentes",
313
+ "itens_limite",
314
+ "contingencia_invalida",
315
+ "pagamento_igual_total",
316
+ "emitente_difere_do_certificado",
317
+ "grupo_vedado",
318
+ "pagamento_invalido",
319
+ "qrcode_invalido",
320
+ "schema"
321
+ ];
322
+
323
+ class Issues {
324
+ list;
325
+ constructor() {
326
+ this.list = [];
327
+ }
328
+ add(path, code, message, origem = "entrada") {
329
+ this.list.push({ path, code, message, origem });
330
+ }
331
+ montagem(path, code, message) {
332
+ this.add(path, code, message, "montagem");
333
+ }
334
+ get classificadas() {
335
+ return this.list.map((i) => i.origem === undefined ? { ...i, origem: "entrada" } : i);
336
+ }
337
+ addAll(issues, origem = "entrada") {
338
+ this.list.push(...issues.map((i) => i.origem === undefined ? { ...i, origem } : i));
339
+ }
340
+ reclassificarDesde(inicio, origem) {
341
+ for (let k = inicio;k < this.list.length; k++) {
342
+ const i = this.list[k];
343
+ if (i !== undefined)
344
+ this.list[k] = { ...i, origem };
345
+ }
346
+ }
347
+ get empty() {
348
+ return this.list.length === 0;
349
+ }
350
+ }
351
+
352
+ // packages/nfe/src/rtc.ts
353
+ import { fixedClock, isUf, timeContext, ufByCUf } from "@sinete/core";
354
+ import { officialRates, RateUnknownError } from "@sinete/ibs-cbs/aliquotas";
355
+ import { ClassificationError, calculate, UnsupportedRegimeError } from "@sinete/ibs-cbs/calcular";
356
+ import { documentFromRoc, validate } from "@sinete/ibs-cbs/validar";
357
+ var BASE = /^\d{1,13}(\.\d{1,2})?$/;
358
+ function normalizado(v) {
359
+ const [int = "0", frac = ""] = v.split(".");
360
+ const f = frac.replace(/0+$/, "");
361
+ const i = int.replace(/^0+(?=\d)/, "");
362
+ return f === "" ? i : `${i}.${f}`;
363
+ }
364
+ var caminho = (nItem) => `itens[${nItem - 1}].impostos.ibsCbs`;
365
+ function ufDoMunicipio(cMun) {
366
+ return ufByCUf(cMun.slice(0, 2))?.sigla;
367
+ }
368
+ function localDaOperacao(nota) {
369
+ if (nota.cMunFGIBS !== undefined) {
370
+ const uf = ufDoMunicipio(nota.cMunFGIBS);
371
+ if (uf !== undefined)
372
+ return { uf, cMun: nota.cMunFGIBS };
373
+ }
374
+ const d = nota.destino;
375
+ if (d !== undefined && d.UF !== "EX" && isUf(d.UF))
376
+ return { uf: d.UF, cMun: d.cMun };
377
+ return { uf: nota.emitente.UF, cMun: nota.emitente.cMun };
378
+ }
379
+ function grupoDoLeiaute(g, indDoacao) {
380
+ const { gCredPresOper, gCredPresIBSZFM, ...resto } = g;
381
+ return {
382
+ ...resto,
383
+ ...indDoacao === undefined ? {} : { indDoacao },
384
+ ...gCredPresOper === undefined ? {} : { gCredPresOper: { ...gCredPresOper, cCredPres: String(gCredPresOper.cCredPres).padStart(2, "0") } },
385
+ ...gCredPresIBSZFM === undefined ? {} : {
386
+ gCredPresIBSZFM: {
387
+ ...gCredPresIBSZFM,
388
+ tpCredPresIBSZFM: String(gCredPresIBSZFM.tpCredPresIBSZFM)
389
+ }
390
+ }
391
+ };
392
+ }
393
+ function ocorrenciaDoMotor(e, itens) {
394
+ if (e instanceof ClassificationError || e instanceof UnsupportedRegimeError) {
395
+ const path = e.item !== undefined ? caminho(e.item) : caminho(itens[0]?.nItem ?? 1);
396
+ return { path, code: e.code, message: e.message, origem: "entrada" };
397
+ }
398
+ if (e instanceof RateUnknownError)
399
+ return { path: "impostos.ibsCbs", code: e.code, message: e.message, origem: "montagem" };
400
+ return;
401
+ }
402
+ var embarcado;
403
+ function carregarDatasetEmbarcado() {
404
+ embarcado ??= import("@sinete/ibs-cbs-dados/bundled").then((m) => m.bundledDataset(), (e) => {
405
+ embarcado = undefined;
406
+ throw e;
407
+ });
408
+ return embarcado;
409
+ }
410
+ function ibsCbsCalculator(options = {}) {
411
+ const rates = options.rates ?? officialRates();
412
+ const dataset = options.dataset;
413
+ return {
414
+ calcular(request) {
415
+ if (dataset !== undefined)
416
+ return calcularCom(dataset, rates, options, request);
417
+ return carregarDatasetEmbarcado().then((ds) => calcularCom(ds, rates, options, request));
418
+ }
419
+ };
420
+ }
421
+ function calcularCom(dataset, rates, options, {
422
+ nota,
423
+ itens
424
+ }) {
425
+ const issues = [];
426
+ const classificados = [];
427
+ for (const it of itens) {
428
+ if (it.cCredPres !== undefined) {
429
+ issues.push({
430
+ path: caminho(it.nItem),
431
+ code: "ibscbs_nao_suportado",
432
+ message: "crédito presumido (cCredPres) precisa do grupo gCredPresOper pronto (ibsCbs.grupo)",
433
+ origem: "entrada"
434
+ });
435
+ continue;
436
+ }
437
+ const base = it.vBC !== undefined ? it.vBC.toFixed(2) : options.base?.(it, nota);
438
+ if (base === undefined) {
439
+ issues.push({
440
+ path: `${caminho(it.nItem)}.classificacao.vBC`,
441
+ code: "ibscbs_base_ausente",
442
+ message: "informe vBC do IBS/CBS ou IbsCbsCalculatorOptions.base: a composição da base (UB16-10) ainda não tem regra publicada",
443
+ origem: "entrada"
444
+ });
445
+ continue;
446
+ }
447
+ if (!BASE.test(base)) {
448
+ issues.push({
449
+ path: `${caminho(it.nItem)}.classificacao.vBC`,
450
+ code: "decimal_invalido",
451
+ message: base,
452
+ origem: it.vBC !== undefined ? "entrada" : "montagem"
453
+ });
454
+ continue;
455
+ }
456
+ classificados.push({
457
+ n: it.nItem,
458
+ cst: it.CST,
459
+ cClassTrib: it.cClassTrib,
460
+ base,
461
+ quantity: it.qTrib.toString(),
462
+ unit: it.uTrib,
463
+ ...it.gTribRegular === undefined ? {} : { regular: { cst: it.gTribRegular.CSTReg, cClassTrib: it.gTribRegular.cClassTribReg } }
464
+ });
465
+ }
466
+ if (issues.length > 0)
467
+ return { itens: [], issues };
468
+ const op = {
469
+ modelo: Number(nota.mod),
470
+ place: localDaOperacao(nota),
471
+ ...nota.compraGov === undefined ? {} : {
472
+ governmentPurchase: {
473
+ tpEnteGov: Number(nota.compraGov.tpEnteGov),
474
+ ...nota.compraGov.tpOperGov === "1" || nota.compraGov.tpOperGov === "2" ? { tpOperGov: Number(nota.compraGov.tpOperGov) } : {}
475
+ }
476
+ },
477
+ items: classificados
478
+ };
479
+ const time = timeContext({ emissao: fixedClock(nota.emissao), fatoGerador: fixedClock(nota.fatoGerador) });
480
+ let roc;
481
+ try {
482
+ roc = calculate(op, {
483
+ dataset,
484
+ rates,
485
+ time,
486
+ ...options.utcOffsetMinutes === undefined ? {} : { utcOffsetMinutes: options.utcOffsetMinutes }
487
+ });
488
+ } catch (e) {
489
+ const issue = ocorrenciaDoMotor(e, itens);
490
+ if (issue === undefined)
491
+ throw e;
492
+ return { itens: [], issues: [issue] };
493
+ }
494
+ const redutor = roc.oper?.gCompraGov.pRedutor;
495
+ if (nota.compraGov !== undefined && redutor !== undefined && normalizado(nota.compraGov.pRedutor.toString()) !== normalizado(redutor)) {
496
+ issues.push({
497
+ path: "gCompraGov.pRedutor",
498
+ code: "ibscbs_redutor_divergente",
499
+ message: `pRedutor informado (${nota.compraGov.pRedutor.toString()}) difere do vigente no fato gerador (${redutor})`,
500
+ origem: "entrada"
501
+ });
502
+ }
503
+ if (options.regras !== false) {
504
+ const doc = documentFromRoc(roc, {
505
+ modelo: op.modelo,
506
+ crt: Number(nota.emitente.CRT),
507
+ finNFe: Number(nota.finNFe),
508
+ ...nota.tpNFDebito === undefined ? {} : { tpNFDebito: nota.tpNFDebito },
509
+ ...nota.tpNFCredito === undefined ? {} : { tpNFCredito: nota.tpNFCredito },
510
+ emitMun: nota.emitente.cMun,
511
+ ...nota.destino === undefined ? {} : { destMun: nota.destino.cMun },
512
+ items: itens.map((it) => ({ nItem: it.nItem, ncm: it.NCM, vProd: it.vProd.toFixed(2) }))
513
+ });
514
+ const report = validate(doc, {
515
+ dataset,
516
+ time,
517
+ ambiente: nota.ambiente,
518
+ rates,
519
+ ...options.utcOffsetMinutes === undefined ? {} : { utcOffsetMinutes: options.utcOffsetMinutes },
520
+ ...options.regras?.rules === undefined ? {} : { rules: options.regras.rules },
521
+ ...options.regras?.ignoreActivation === undefined ? {} : { ignoreActivation: options.regras.ignoreActivation }
522
+ });
523
+ for (const v of report.violations) {
524
+ issues.push({
525
+ path: v.item === undefined ? "total.IBSCBSTot" : caminho(v.item),
526
+ code: "ibscbs_regra_nt",
527
+ message: `${v.rule} (rejeição ${v.cStat}): ${v.message} [${v.source}]`,
528
+ origem: "montagem"
529
+ });
530
+ }
531
+ }
532
+ const porItem = new Map(itens.map((it) => [it.nItem, it]));
533
+ return {
534
+ itens: roc.items.map((r) => ({
535
+ nItem: r.nItem,
536
+ IBSCBS: grupoDoLeiaute(r.IBSCBS, porItem.get(r.nItem)?.indDoacao)
537
+ })),
538
+ ...issues.length === 0 ? {} : { issues }
539
+ };
540
+ }
541
+
542
+ // packages/nfe/src/time.ts
543
+ import { formatDateTimeOffset } from "@sinete/core";
544
+ // packages/nfe/src/data/fusos.json
545
+ var fusos_default = {
546
+ descricao: "Deslocamento do horário legal de cada UF em relação a UTC, em minutos, usado para formatar dhEmi, dhSaiEnt, dhCont e dhEvento quando quem emite não informa o fuso. Sem horário de verão desde 2019. UFs com mais de um fuso usam o da capital; o emitente de outro fuso informa offsetMinutes.",
547
+ atualizadoEm: "2026-09-26",
548
+ fontes: [
549
+ "Lei 11.662/2008 e Lei 12.876/2013 (fusos horários do Brasil; Acre em UTC-5)",
550
+ "Decreto 9.772/2019 (fim do horário de verão)"
551
+ ],
552
+ padrao: -180,
553
+ ufs: {
554
+ AC: -300,
555
+ AM: -240,
556
+ MS: -240,
557
+ MT: -240,
558
+ RO: -240,
559
+ RR: -240
560
+ }
561
+ };
562
+
563
+ // packages/nfe/src/time.ts
564
+ var UF_OFFSETS = fusos_default.ufs;
565
+ function offsetDaUf(uf) {
566
+ return Object.hasOwn(UF_OFFSETS, uf) ? UF_OFFSETS[uf] : fusos_default.padrao;
567
+ }
568
+ function formatDh(date, offsetMinutes) {
569
+ return formatDateTimeOffset(date, offsetMinutes);
570
+ }
571
+
572
+ // packages/nfe/src/versao-gerada.ts
573
+ var VERSAO_PACOTE = "0.1.0";
574
+
575
+ // packages/nfe/src/build/destinatario.ts
576
+ import { ufBySigla } from "@sinete/core";
577
+ import { parseCnpj } from "@sinete/validators";
578
+ // packages/nfe/src/data/suframa.json
579
+ var suframa_default = {
580
+ descricao: "Onde a inscrição na Suframa do destinatário (ISUF) é aceita na NF-e: UFs inteiras e, no Amapá, só os municípios listados. Fora delas, rejeição 251.",
581
+ atualizadoEm: "2026-09-28",
582
+ fonte: "MOC 7.0 Anexo I, RV E18-30 (rejeição 251, modelo 55, obrigatória)",
583
+ ufs: ["AC", "AM", "RO", "RR"],
584
+ municipios: { AP: ["1600303", "1600600"] }
585
+ };
586
+
587
+ // packages/nfe/src/build/destinatario.ts
588
+ var ID_ESTRANGEIRO = /^[0-9A-Za-z:.+\-/()]*$/;
589
+ var digitos = (s) => s.replace(/\D/g, "");
590
+ function conferirDestinatario(input, ide, issues) {
591
+ const d = input.destinatario;
592
+ if (d === undefined)
593
+ return;
594
+ const nfe = ide.mod === "55";
595
+ const emitUf = input.emitente.endereco.UF;
596
+ const end = d.endereco;
597
+ const exterior = end !== undefined && "exterior" in end && end.exterior === true;
598
+ const destUf = end === undefined ? undefined : exterior ? "EX" : end.UF;
599
+ const idEstrangeiro = "idEstrangeiro" in d ? d.idEstrangeiro : undefined;
600
+ if (nfe && ide.idDest === "3" && idEstrangeiro === undefined) {
601
+ issues.add("destinatario", "campo_obrigatorio", "na operação com o exterior (idDest 3) o destinatário é identificado por idEstrangeiro, mesmo vazio (E03a-10, rejeição 720)");
602
+ }
603
+ if (nfe && idEstrangeiro !== undefined && ide.idDest !== "3" && ide.indFinal !== "1") {
604
+ issues.add("destinatario.idEstrangeiro", "combinacao_invalida", "idEstrangeiro fora da operação com o exterior só com consumidor final, indFinal 1 (E03a-20, rejeição 721)");
605
+ }
606
+ if (idEstrangeiro !== undefined && d.IE !== undefined) {
607
+ issues.add("destinatario.IE", "combinacao_invalida", "destinatário estrangeiro (idEstrangeiro) não informa IE (E03a-30, rejeição 925)");
608
+ }
609
+ if (idEstrangeiro !== undefined && !ID_ESTRANGEIRO.test(idEstrangeiro)) {
610
+ issues.add("destinatario.idEstrangeiro", "campo_invalido", "idEstrangeiro só com algarismos, letras e os caracteres : . + - / ( ) (E03a-60, rejeição 372)");
611
+ }
612
+ if (nfe && ide.producao && (d.xNome === undefined || d.xNome.trim() === "")) {
613
+ issues.add("destinatario.xNome", "campo_obrigatorio", "a NF-e informa o nome do destinatário (E04-10, rejeição 724)");
614
+ }
615
+ if (nfe && end === undefined) {
616
+ issues.add("destinatario.endereco", "campo_obrigatorio", "a NF-e informa o endereço do destinatário (E05-10, rejeição 726)");
617
+ }
618
+ if (end !== undefined && !exterior) {
619
+ const e = end;
620
+ const cUF = ufBySigla(e.UF)?.cUF;
621
+ if (cUF !== undefined && digitos(e.cMun).slice(0, 2) !== cUF) {
622
+ issues.add("destinatario.endereco.cMun", "combinacao_invalida", `município ${e.cMun} não é da UF ${e.UF} do destinatário (E10-20, rejeição 275)`);
623
+ }
624
+ }
625
+ if (nfe && destUf !== undefined && destUf !== "EX") {
626
+ const caminho = ide.idDestInformado ? "idDest" : "destinatario.endereco.UF";
627
+ const ufsCons = input.itens.flatMap((it) => {
628
+ const esp = it.produto.especifico;
629
+ return esp !== undefined && "comb" in esp ? [String(esp.comb.UFCons)] : [];
630
+ });
631
+ const entrega = input.entrega?.UF;
632
+ const retirada = input.retirada?.UF;
633
+ const saida = ide.tpNF === "1";
634
+ const [ufEntrega, ufRetirada] = saida ? [emitUf, destUf] : [destUf, emitUf];
635
+ if (ide.idDest === "2" && destUf === emitUf) {
636
+ const cnpj = (v) => {
637
+ if (v === undefined)
638
+ return;
639
+ const r = parseCnpj(v);
640
+ return r.ok ? r.value : undefined;
641
+ };
642
+ const cnpjDest = "CNPJ" in d ? cnpj(d.CNPJ) : undefined;
643
+ const mesmoCnpj = cnpjDest !== undefined && cnpjDest === cnpj(input.emitente.CNPJ);
644
+ const excecao = ufsCons.some((u) => u !== emitUf) || entrega !== undefined && retirada === undefined && entrega !== ufEntrega || retirada !== undefined && entrega === undefined && retirada !== ufRetirada || entrega !== undefined && retirada !== undefined && entrega !== retirada;
645
+ if (!mesmoCnpj && !excecao) {
646
+ issues.add(caminho, "combinacao_invalida", `operação interestadual (idDest 2) com o destinatário na UF do emitente (${emitUf}) (${saida ? "E12-30" : "E12-50"}, rejeição 772)`);
647
+ }
648
+ }
649
+ if (ide.idDest === "1" && destUf !== emitUf && ide.indFinal !== "1") {
650
+ const excecao = ufsCons.some((u) => u === emitUf) || entrega !== undefined && retirada === undefined && entrega === ufEntrega || retirada !== undefined && entrega === undefined && retirada === ufRetirada || entrega !== undefined && retirada !== undefined && entrega === retirada;
651
+ if (!excecao) {
652
+ issues.add(caminho, "combinacao_invalida", `operação interna (idDest 1) com o destinatário em ${destUf}, fora da UF do emitente (${emitUf}) (${saida ? "E12-40" : "E12-60"}, rejeição 773)`);
653
+ }
654
+ }
655
+ }
656
+ if (exterior && Number(digitos(end.cPais)) === 1058) {
657
+ issues.add("destinatario.endereco.cPais", "campo_invalido", "destinatário no exterior com o país Brasil, 1058 (E14-30, rejeição 926)");
658
+ }
659
+ if (!nfe)
660
+ return;
661
+ if (ide.idDest === "3" && d.indIEDest !== "9") {
662
+ issues.add("destinatario.indIEDest", "combinacao_invalida", "na operação com o exterior o destinatário é não contribuinte, indIEDest 9 (E16a-20, rejeição 790)");
663
+ }
664
+ if (d.indIEDest === "9" && ide.indFinal !== "1" && ide.tpNF === "1" && ide.idDest !== "3") {
665
+ issues.add("indFinal", "combinacao_invalida", "saída para não contribuinte (indIEDest 9) é operação com consumidor final, indFinal 1 (E16a-40, rejeição 696)");
666
+ }
667
+ if (d.indIEDest === "1" && d.IE === undefined) {
668
+ issues.add("destinatario.IE", "campo_obrigatorio", "destinatário contribuinte (indIEDest 1) informa a IE (E17-20, rejeição 728)");
669
+ }
670
+ if (d.indIEDest === "2" && d.IE !== undefined) {
671
+ issues.add("destinatario.IE", "combinacao_invalida", "destinatário contribuinte isento (indIEDest 2) não informa a IE (E17-30, rejeição 791)");
672
+ }
673
+ if (exterior && d.IE !== undefined) {
674
+ issues.add("destinatario.IE", "combinacao_invalida", "destinatário no exterior não informa a IE (E17-40, rejeição 792)");
675
+ }
676
+ if (d.ISUF !== undefined && destUf !== undefined) {
677
+ const cMun = exterior ? "" : digitos(end.cMun);
678
+ const municipios = suframa_default.municipios[destUf];
679
+ const aceita = suframa_default.ufs.includes(destUf) || (municipios?.includes(cMun) ?? false);
680
+ if (!aceita) {
681
+ const onde = exterior ? "no exterior" : `${destUf}, município ${end.cMun}`;
682
+ issues.add("destinatario.ISUF", "combinacao_invalida", `inscrição na Suframa com o destinatário fora da área incentivada (${onde}) (E18-30, rejeição 251)`);
683
+ }
684
+ }
685
+ }
686
+
687
+ // packages/nfe/src/build/ibscbs.ts
688
+ import { firstChild, parseXml } from "@sinete/core/xml";
689
+ import { serialize, validate as validate2 } from "@sinete/schemas";
690
+ var NFE_NS = "http://www.portalfiscal.inf.br/nfe";
691
+ function grupoInvalido(ct, nome, value, path, issues) {
692
+ if (value === undefined)
693
+ return false;
694
+ try {
695
+ const doc = parseXml(`<w xmlns="${NFE_NS}">${serialize(ct, nome, value, NFE_NS)}</w>`);
696
+ const el = firstChild(doc.root, nome, NFE_NS);
697
+ const erros = el === undefined ? [{ path: "", code: "modelo_de_conteudo", message: "grupo vazio" }] : validate2(ct, el);
698
+ for (const e of erros)
699
+ issues.add(`${path}${e.path.replace(/^\/[^/]+/, "").replace(/\//g, ".")}`, "schema", `${e.code}: ${e.message}`);
700
+ return erros.length > 0;
701
+ } catch (e) {
702
+ issues.add(path, "schema", `grupo malformado: ${e.message}`);
703
+ return true;
704
+ }
705
+ }
706
+ var NUMERICO = /^(v|p|q|adRem)[A-Z]/;
707
+ function decimaisInvalidos(value, path, issues) {
708
+ if (typeof value !== "object" || value === null)
709
+ return;
710
+ for (const [k, v] of Object.entries(value)) {
711
+ const p = `${path}.${k}`;
712
+ if (typeof v === "string" && NUMERICO.test(k) && Decimal.tryOf(v) === undefined) {
713
+ issues.add(p, "decimal_invalido", "número decimal inválido");
714
+ } else if (typeof v === "object")
715
+ decimaisInvalidos(v, p, issues);
716
+ }
717
+ }
718
+ function somaCampo(value, name) {
719
+ if (typeof value !== "object" || value === null)
720
+ return Decimal.ZERO;
721
+ let acc = Decimal.ZERO;
722
+ for (const [k, v] of Object.entries(value)) {
723
+ if (k === name && typeof v === "string")
724
+ acc = acc.plus(Decimal.of(v));
725
+ else if (typeof v === "object")
726
+ acc = acc.plus(somaCampo(v, name));
727
+ }
728
+ return acc;
729
+ }
730
+ function ibsCbsDoItem(g) {
731
+ const s = (x) => x === undefined ? Decimal.ZERO : Decimal.of(x);
732
+ return {
733
+ vIBS: s(g.gIBSCBS?.vIBS),
734
+ vCBS: s(g.gIBSCBS?.gCBS.vCBS),
735
+ vTotIBSMonoItem: s(g.gIBSCBSMono?.vTotIBSMonoItem),
736
+ vTotCBSMonoItem: s(g.gIBSCBSMono?.vTotCBSMonoItem)
737
+ };
738
+ }
739
+ function totalIbsCbs(grupos) {
740
+ const f = (d) => d.toFixed(2);
741
+ const sum = (pick, name) => grupos.reduce((acc, g) => acc.plus(somaCampo(pick(g), name)), Decimal.ZERO);
742
+ const regulares = grupos.filter((g) => g.gIBSCBS !== undefined || g.gCredPresOper !== undefined);
743
+ const total = {
744
+ vBCIBSCBS: f(sum((g) => g.gIBSCBS && { vBC: g.gIBSCBS.vBC }, "vBC"))
745
+ };
746
+ if (regulares.length > 0) {
747
+ const credIbs = (g) => g.gCredPresOper?.gIBSCredPres;
748
+ const credCbs = (g) => g.gCredPresOper?.gCBSCredPres;
749
+ total.gIBS = {
750
+ gIBSUF: {
751
+ vDif: f(sum((g) => g.gIBSCBS?.gIBSUF.gDif, "vDif")),
752
+ vDevTrib: f(sum((g) => g.gIBSCBS?.gIBSUF.gDevTrib, "vDevTrib")),
753
+ vIBSUF: f(sum((g) => g.gIBSCBS && { v: g.gIBSCBS.gIBSUF.vIBSUF }, "v"))
754
+ },
755
+ gIBSMun: {
756
+ vDif: f(sum((g) => g.gIBSCBS?.gIBSMun.gDif, "vDif")),
757
+ vDevTrib: f(sum((g) => g.gIBSCBS?.gIBSMun.gDevTrib, "vDevTrib")),
758
+ vIBSMun: f(sum((g) => g.gIBSCBS && { v: g.gIBSCBS.gIBSMun.vIBSMun }, "v"))
759
+ },
760
+ vIBS: f(sum((g) => g.gIBSCBS && { v: g.gIBSCBS.vIBS }, "v")),
761
+ vCredPres: f(sum(credIbs, "vCredPres")),
762
+ vCredPresCondSus: f(sum(credIbs, "vCredPresCondSus"))
763
+ };
764
+ total.gCBS = {
765
+ vDif: f(sum((g) => g.gIBSCBS?.gCBS.gDif, "vDif")),
766
+ vDevTrib: f(sum((g) => g.gIBSCBS?.gCBS.gDevTrib, "vDevTrib")),
767
+ vCBS: f(sum((g) => g.gIBSCBS && { v: g.gIBSCBS.gCBS.vCBS }, "v")),
768
+ vCredPres: f(sum(credCbs, "vCredPres")),
769
+ vCredPresCondSus: f(sum(credCbs, "vCredPresCondSus"))
770
+ };
771
+ }
772
+ if (grupos.some((g) => g.gIBSCBSMono !== undefined)) {
773
+ const mono = (n) => f(sum((g) => g.gIBSCBSMono, n));
774
+ total.gMono = {
775
+ vIBSMono: mono("vIBSMono"),
776
+ vCBSMono: mono("vCBSMono"),
777
+ vIBSMonoReten: mono("vIBSMonoReten"),
778
+ vCBSMonoReten: mono("vCBSMonoReten"),
779
+ vIBSMonoRet: mono("vIBSMonoRet"),
780
+ vCBSMonoRet: mono("vCBSMonoRet")
781
+ };
782
+ }
783
+ if (grupos.some((g) => g.gEstornoCred !== undefined)) {
784
+ total.gEstornoCred = {
785
+ vIBSEstCred: f(sum((g) => g.gEstornoCred, "vIBSEstCred")),
786
+ vCBSEstCred: f(sum((g) => g.gEstornoCred, "vCBSEstCred"))
787
+ };
788
+ }
789
+ return total;
790
+ }
791
+
792
+ // packages/nfe/src/build/values.ts
793
+ var TOLERANCIA = Decimal.of("0.01");
794
+
795
+ class Ctx {
796
+ issues;
797
+ modes;
798
+ conferir;
799
+ constructor(issues, modes, conferir = true) {
800
+ this.issues = issues;
801
+ this.modes = modes;
802
+ this.conferir = conferir;
803
+ }
804
+ opt(value, path, format) {
805
+ if (value === undefined)
806
+ return;
807
+ const d = Decimal.tryOf(value);
808
+ if (d === undefined) {
809
+ this.issues.add(path, "decimal_invalido", "número decimal inválido (use ponto como separador, sem milhar)");
810
+ return;
811
+ }
812
+ const problem = formatProblem(d, format);
813
+ if (problem !== undefined) {
814
+ this.issues.add(path, "decimal_invalido", `${problem} (${format.name})`);
815
+ return;
816
+ }
817
+ return d;
818
+ }
819
+ req(value, path, format) {
820
+ if (value === undefined) {
821
+ this.issues.add(path, "campo_obrigatorio", "campo obrigatório");
822
+ return Decimal.ZERO;
823
+ }
824
+ return this.opt(value, path, format) ?? Decimal.ZERO;
825
+ }
826
+ round(value, format, familia) {
827
+ return value.round(format.max, this.modes[familia]);
828
+ }
829
+ base(given, padrao, path, format, familia) {
830
+ return this.opt(given, path, format) ?? this.round(padrao, format, familia);
831
+ }
832
+ calc(given, computed, path, format, familia) {
833
+ const r = this.round(computed, format, familia);
834
+ if (given === undefined)
835
+ return r;
836
+ const g = this.opt(given, path, format);
837
+ if (g === undefined)
838
+ return r;
839
+ if (this.conferir && g.minus(r).abs().gt(TOLERANCIA)) {
840
+ this.issues.add(path, "valor_divergente", `valor informado difere do calculado (${r.toFixed(format.max)}) em mais de ${TOLERANCIA.toString()}`);
841
+ }
842
+ return g;
843
+ }
844
+ s(value, format) {
845
+ return formatDecimal(value, format);
846
+ }
847
+ so(value, format) {
848
+ if (value === undefined)
849
+ return;
850
+ if (format.nonZero && value.isZero())
851
+ return;
852
+ return formatDecimal(value, format);
853
+ }
854
+ }
855
+ function clean(o) {
856
+ const out = {};
857
+ for (const [k, v] of Object.entries(o))
858
+ if (v !== undefined)
859
+ out[k] = v;
860
+ return out;
861
+ }
862
+ function digits(s) {
863
+ return s.replace(/\D/g, "");
864
+ }
865
+
866
+ // packages/nfe/src/build/icms.ts
867
+ function zeroIcmsTotais() {
868
+ const z = Decimal.ZERO;
869
+ return {
870
+ vBC: z,
871
+ vICMS: z,
872
+ vICMSDeson: z,
873
+ vICMSDesonDeduz: z,
874
+ vFCP: z,
875
+ vBCST: z,
876
+ vST: z,
877
+ vFCPST: z,
878
+ vFCPSTRet: z,
879
+ qBCMono: z,
880
+ vICMSMono: z,
881
+ qBCMonoReten: z,
882
+ vICMSMonoReten: z,
883
+ qBCMonoRet: z,
884
+ vICMSMonoRet: z,
885
+ mono: false
886
+ };
887
+ }
888
+ var M = D1302;
889
+ var P = D0302A04;
890
+ var PO = D0302A04_OPC;
891
+ function nonNeg(d) {
892
+ return d.isNegative() ? Decimal.ZERO : d;
893
+ }
894
+ function buildIcms(ctx, input, base, path) {
895
+ const t = zeroIcmsTotais();
896
+ const S = (d) => ctx.s(d, M);
897
+ const proprio = (i, pRedBC, required) => {
898
+ const pICMS = required ? ctx.req(i.pICMS, `${path}.pICMS`, P) : ctx.opt(i.pICMS, `${path}.pICMS`, P);
899
+ if (pICMS === undefined && i.vBC === undefined && i.vICMS === undefined)
900
+ return;
901
+ const reduzida = pRedBC === undefined ? base.vOp : base.vOp.times(Decimal.HUNDRED.minus(pRedBC)).dividedBy(100, 10, "HALF_EVEN");
902
+ const vBC = ctx.base(i.vBC, reduzida, `${path}.vBC`, M, "icms");
903
+ const aliq = pICMS ?? Decimal.ZERO;
904
+ const vICMS = ctx.calc(i.vICMS, vBC.percent(aliq), `${path}.vICMS`, M, "icms");
905
+ t.vBC = t.vBC.plus(vBC);
906
+ t.vICMS = t.vICMS.plus(vICMS);
907
+ return {
908
+ out: { modBC: i.modBC ?? "3", vBC: S(vBC), pICMS: ctx.s(aliq, P), vICMS: S(vICMS) },
909
+ vBC,
910
+ vICMS
911
+ };
912
+ };
913
+ const orfao = (valor, presente, campo, exige, base = path) => {
914
+ if (valor !== undefined && !presente) {
915
+ ctx.issues.add(`${base}.${exige}`, "campo_obrigatorio", `${campo} informado exige ${exige}`);
916
+ }
917
+ };
918
+ const fcp = (i, vBC, withBase) => {
919
+ const pFCP = ctx.opt(i.pFCP, `${path}.pFCP`, PO);
920
+ orfao(i.vBCFCP, i.pFCP !== undefined || i.vFCP !== undefined, "vBCFCP", "pFCP");
921
+ if (pFCP === undefined && i.vFCP === undefined)
922
+ return {};
923
+ const vBCFCP = ctx.base(i.vBCFCP, vBC, `${path}.vBCFCP`, M, "icms");
924
+ const vFCP = ctx.calc(i.vFCP, vBCFCP.percent(pFCP ?? Decimal.ZERO), `${path}.vFCP`, M, "icms");
925
+ t.vFCP = t.vFCP.plus(vFCP);
926
+ return { ...withBase ? { vBCFCP: S(vBCFCP) } : {}, pFCP: ctx.so(pFCP, PO), vFCP: S(vFCP) };
927
+ };
928
+ const st = (i, vICMSProprio, vFCPProprio) => {
929
+ const sp = `${path}.st`;
930
+ const pMVAST = ctx.opt(i.pMVAST, `${sp}.pMVAST`, PO);
931
+ const pRedBCST = ctx.opt(i.pRedBCST, `${sp}.pRedBCST`, PO);
932
+ const pICMSST = ctx.req(i.pICMSST, `${sp}.pICMSST`, P);
933
+ if (i.modBCST === "4" && pMVAST === undefined) {
934
+ ctx.issues.add(`${sp}.pMVAST`, "campo_obrigatorio", "modBCST 4 (MVA) exige pMVAST");
935
+ }
936
+ if (i.modBCST !== "4" && pMVAST !== undefined) {
937
+ ctx.issues.add(`${sp}.pMVAST`, "combinacao_invalida", "pMVAST só pode ser informado com modBCST 4 (MVA)");
938
+ }
939
+ let vBCST;
940
+ if (i.vBCST === undefined && i.modBCST === "4") {
941
+ const bruta = base.vOp.plus(base.vIPI).times(Decimal.HUNDRED.plus(pMVAST ?? Decimal.ZERO)).dividedBy(100, 12, "HALF_EVEN");
942
+ const reduzida = pRedBCST === undefined ? bruta : bruta.times(Decimal.HUNDRED.minus(pRedBCST)).dividedBy(100, 12, "HALF_EVEN");
943
+ vBCST = ctx.round(reduzida, M, "icms");
944
+ } else {
945
+ vBCST = ctx.req(i.vBCST, `${sp}.vBCST`, M);
946
+ }
947
+ const deducao = ctx.opt(i.vICMSDeducaoST, `${sp}.vICMSDeducaoST`, M) ?? vICMSProprio;
948
+ const vICMSST = ctx.calc(i.vICMSST, nonNeg(ctx.round(vBCST.percent(pICMSST), M, "icms").minus(deducao)), `${sp}.vICMSST`, M, "icms");
949
+ t.vBCST = t.vBCST.plus(vBCST);
950
+ t.vST = t.vST.plus(vICMSST);
951
+ const out = {
952
+ modBCST: i.modBCST,
953
+ pMVAST: ctx.so(pMVAST, PO),
954
+ pRedBCST: ctx.so(pRedBCST, PO),
955
+ vBCST: S(vBCST),
956
+ pICMSST: ctx.s(pICMSST, P),
957
+ vICMSST: S(vICMSST)
958
+ };
959
+ const pFCPST = ctx.opt(i.pFCPST, `${sp}.pFCPST`, PO);
960
+ orfao(i.vBCFCPST, i.pFCPST !== undefined || i.vFCPST !== undefined, "vBCFCPST", "pFCPST", sp);
961
+ if (pFCPST !== undefined || i.vFCPST !== undefined) {
962
+ const vBCFCPST = ctx.base(i.vBCFCPST, vBCST, `${sp}.vBCFCPST`, M, "icms");
963
+ const vFCPST = ctx.calc(i.vFCPST, nonNeg(ctx.round(vBCFCPST.percent(pFCPST ?? Decimal.ZERO), M, "icms").minus(vFCPProprio)), `${sp}.vFCPST`, M, "icms");
964
+ t.vFCPST = t.vFCPST.plus(vFCPST);
965
+ Object.assign(out, { vBCFCPST: S(vBCFCPST), pFCPST: ctx.so(pFCPST, PO), vFCPST: S(vFCPST) });
966
+ }
967
+ return out;
968
+ };
969
+ const deson = (d) => {
970
+ if (d === undefined)
971
+ return {};
972
+ const v = ctx.req(d.vICMSDeson, `${path}.desoneracao.vICMSDeson`, M);
973
+ t.vICMSDeson = t.vICMSDeson.plus(v);
974
+ if (d.indDeduzDeson === "1")
975
+ t.vICMSDesonDeduz = t.vICMSDesonDeduz.plus(v);
976
+ return { vICMSDeson: S(v), motDesICMS: d.motDesICMS, indDeduzDeson: d.indDeduzDeson };
977
+ };
978
+ const desonSt = (d) => {
979
+ if (d === undefined)
980
+ return {};
981
+ const v = ctx.req(d.vICMSSTDeson, `${path}.desoneracaoSt.vICMSSTDeson`, M);
982
+ return { vICMSSTDeson: S(v), motDesICMSST: d.motDesICMSST };
983
+ };
984
+ const retido = (i) => {
985
+ const o = (k, f) => ctx.so(ctx.opt(i[k], `${path}.${k}`, f), f);
986
+ const vFCPSTRet = ctx.opt(i.vFCPSTRet, `${path}.vFCPSTRet`, M);
987
+ if (vFCPSTRet !== undefined)
988
+ t.vFCPSTRet = t.vFCPSTRet.plus(vFCPSTRet);
989
+ return {
990
+ vBCSTRet: o("vBCSTRet", M),
991
+ pST: o("pST", PO),
992
+ vICMSSubstituto: o("vICMSSubstituto", M),
993
+ vICMSSTRet: o("vICMSSTRet", M),
994
+ vBCFCPSTRet: o("vBCFCPSTRet", M),
995
+ pFCPSTRet: o("pFCPSTRet", PO),
996
+ vFCPSTRet: ctx.so(vFCPSTRet, M),
997
+ pRedBCEfet: o("pRedBCEfet", PO),
998
+ vBCEfet: o("vBCEfet", M),
999
+ pICMSEfet: o("pICMSEfet", PO),
1000
+ vICMSEfet: o("vICMSEfet", M)
1001
+ };
1002
+ };
1003
+ const diferimento = (i, redFormat, triade) => {
1004
+ const pRedBC = ctx.opt(i.pRedBC, `${path}.pRedBC`, redFormat);
1005
+ const pICMS = ctx.opt(i.pICMS, `${path}.pICMS`, P);
1006
+ const out = {};
1007
+ let vBC;
1008
+ if (pICMS !== undefined || i.vBC !== undefined) {
1009
+ const reduzida = pRedBC === undefined ? base.vOp : base.vOp.times(Decimal.HUNDRED.minus(pRedBC)).dividedBy(100, 10, "HALF_EVEN");
1010
+ vBC = ctx.base(i.vBC, reduzida, `${path}.vBC`, M, "icms");
1011
+ out.modBC = i.modBC ?? "3";
1012
+ out.vBC = S(vBC);
1013
+ }
1014
+ out.pRedBC = ctx.so(pRedBC, redFormat);
1015
+ out.cBenefRBC = i.cBenefRBC;
1016
+ if (pICMS !== undefined && vBC !== undefined) {
1017
+ out.pICMS = ctx.s(pICMS, P);
1018
+ const vICMSOp = ctx.calc(i.vICMSOp, vBC.percent(pICMS), `${path}.vICMSOp`, M, "icms");
1019
+ const pDif = ctx.opt(i.pDif, `${path}.pDif`, P);
1020
+ const vICMSDif = ctx.calc(i.vICMSDif, vICMSOp.percent(pDif ?? Decimal.ZERO), `${path}.vICMSDif`, M, "icms");
1021
+ const vICMS = ctx.calc(i.vICMS, vICMSOp.minus(vICMSDif), `${path}.vICMS`, M, "icms");
1022
+ const temDif = pDif !== undefined || i.vICMSDif !== undefined || i.vICMSOp !== undefined;
1023
+ if (triade) {
1024
+ if (temDif)
1025
+ Object.assign(out, { vICMSOp: S(vICMSOp), pDif: ctx.s(pDif ?? Decimal.ZERO, P), vICMSDif: S(vICMSDif) });
1026
+ } else {
1027
+ Object.assign(out, {
1028
+ vICMSOp: S(vICMSOp),
1029
+ pDif: ctx.so(pDif, P),
1030
+ vICMSDif: pDif === undefined && i.vICMSDif === undefined ? undefined : S(vICMSDif)
1031
+ });
1032
+ }
1033
+ Object.assign(out, {
1034
+ vICMS: S(vICMS)
1035
+ });
1036
+ t.vBC = t.vBC.plus(vBC);
1037
+ t.vICMS = t.vICMS.plus(vICMS);
1038
+ } else {
1039
+ const informados = [i.vBC, i.vICMS, i.vICMSOp, i.pDif, i.vICMSDif, i.pRedBC].some((x) => x !== undefined);
1040
+ if (triade && informados) {
1041
+ ctx.issues.add(`${path}.pICMS`, "campo_obrigatorio", "o ICMS próprio do CST 90 (vBC, vICMS, diferimento) exige pICMS");
1042
+ }
1043
+ if (!triade) {
1044
+ Object.assign(out, {
1045
+ modBC: out.modBC ?? i.modBC,
1046
+ vICMSOp: ctx.so(ctx.opt(i.vICMSOp, `${path}.vICMSOp`, M), M),
1047
+ pDif: ctx.so(ctx.opt(i.pDif, `${path}.pDif`, P), P),
1048
+ vICMSDif: ctx.so(ctx.opt(i.vICMSDif, `${path}.vICMSDif`, M), M)
1049
+ });
1050
+ }
1051
+ const vICMS = ctx.opt(i.vICMS, `${path}.vICMS`, M);
1052
+ if (vICMS !== undefined) {
1053
+ out.vICMS = S(vICMS);
1054
+ t.vICMS = t.vICMS.plus(vICMS);
1055
+ }
1056
+ if (vBC !== undefined)
1057
+ t.vBC = t.vBC.plus(vBC);
1058
+ }
1059
+ const pFCP = ctx.opt(i.pFCP, `${path}.pFCP`, PO);
1060
+ const temFcp = i.pFCP !== undefined || i.vFCP !== undefined;
1061
+ for (const k of ["vBCFCP", "pFCPDif", "vFCPDif", "vFCPEfet"])
1062
+ orfao(i[k], temFcp, k, "pFCP");
1063
+ orfao(i.vFCPEfet, !temFcp || i.pFCPDif !== undefined || i.vFCPDif !== undefined, "vFCPEfet", "pFCPDif");
1064
+ if (pFCP !== undefined || i.vFCP !== undefined) {
1065
+ const vBCFCP = ctx.base(i.vBCFCP, vBC ?? Decimal.ZERO, `${path}.vBCFCP`, M, "icms");
1066
+ const vFCP = ctx.calc(i.vFCP, vBCFCP.percent(pFCP ?? Decimal.ZERO), `${path}.vFCP`, M, "icms");
1067
+ const pFCPDif = ctx.opt(i.pFCPDif, `${path}.pFCPDif`, PO);
1068
+ const vFCPDif = ctx.calc(i.vFCPDif, vFCP.percent(pFCPDif ?? Decimal.ZERO), `${path}.vFCPDif`, M, "icms");
1069
+ const vFCPEfet = ctx.calc(i.vFCPEfet, vFCP.minus(vFCPDif), `${path}.vFCPEfet`, M, "icms");
1070
+ t.vFCP = t.vFCP.plus(vFCP);
1071
+ const temDif = pFCPDif !== undefined || i.vFCPDif !== undefined;
1072
+ Object.assign(out, {
1073
+ vBCFCP: S(vBCFCP),
1074
+ pFCP: ctx.so(pFCP, PO),
1075
+ vFCP: S(vFCP),
1076
+ pFCPDif: ctx.so(pFCPDif, PO),
1077
+ vFCPDif: temDif ? S(vFCPDif) : undefined,
1078
+ vFCPEfet: temDif ? S(vFCPEfet) : undefined
1079
+ });
1080
+ }
1081
+ return out;
1082
+ };
1083
+ const q = (v, k) => ctx.opt(v, `${path}.${k}`, D1104V);
1084
+ const mono = (qtd, adRem, given, k) => ctx.base(given, (qtd ?? Decimal.ZERO).times(adRem ?? Decimal.ZERO), `${path}.${k}`, M, "icms");
1085
+ let grupo;
1086
+ if ("CSOSN" in input) {
1087
+ const orig = input.orig;
1088
+ switch (input.CSOSN) {
1089
+ case "101": {
1090
+ const pCredSN = ctx.req(input.pCredSN, `${path}.pCredSN`, P);
1091
+ const v = ctx.calc(input.vCredICMSSN, base.vOp.percent(pCredSN), `${path}.vCredICMSSN`, M, "icms");
1092
+ grupo = { ICMSSN101: { orig, CSOSN: "101", pCredSN: ctx.s(pCredSN, P), vCredICMSSN: S(v) } };
1093
+ break;
1094
+ }
1095
+ case "102":
1096
+ case "103":
1097
+ case "300":
1098
+ case "400":
1099
+ grupo = { ICMSSN102: { orig, CSOSN: input.CSOSN } };
1100
+ break;
1101
+ case "201": {
1102
+ const stOut = st(input.st, Decimal.ZERO, Decimal.ZERO);
1103
+ const pCredSN = ctx.req(input.pCredSN, `${path}.pCredSN`, P);
1104
+ const v = ctx.calc(input.vCredICMSSN, base.vOp.percent(pCredSN), `${path}.vCredICMSSN`, M, "icms");
1105
+ grupo = { ICMSSN201: { orig, CSOSN: "201", ...stOut, pCredSN: ctx.s(pCredSN, P), vCredICMSSN: S(v) } };
1106
+ break;
1107
+ }
1108
+ case "202":
1109
+ case "203":
1110
+ grupo = { ICMSSN202: { orig, CSOSN: input.CSOSN, ...st(input.st, Decimal.ZERO, Decimal.ZERO) } };
1111
+ break;
1112
+ case "500":
1113
+ grupo = { ICMSSN500: { orig, CSOSN: "500", ...retido(input) } };
1114
+ break;
1115
+ case "900": {
1116
+ const pRedBC = ctx.opt(input.pRedBC, `${path}.pRedBC`, PO);
1117
+ const p = proprio(input, pRedBC, false);
1118
+ const out = { orig, CSOSN: "900" };
1119
+ if (p)
1120
+ Object.assign(out, {
1121
+ modBC: p.out.modBC,
1122
+ vBC: p.out.vBC,
1123
+ pRedBC: ctx.so(pRedBC, PO),
1124
+ pICMS: p.out.pICMS,
1125
+ vICMS: p.out.vICMS
1126
+ });
1127
+ if (input.st)
1128
+ Object.assign(out, st(input.st, p?.vICMS ?? Decimal.ZERO, Decimal.ZERO));
1129
+ const pCredSN = ctx.opt(input.pCredSN, `${path}.pCredSN`, P);
1130
+ orfao(input.vCredICMSSN, input.pCredSN !== undefined, "vCredICMSSN", "pCredSN");
1131
+ if (pCredSN !== undefined) {
1132
+ const v = ctx.calc(input.vCredICMSSN, base.vOp.percent(pCredSN), `${path}.vCredICMSSN`, M, "icms");
1133
+ Object.assign(out, { pCredSN: ctx.s(pCredSN, P), vCredICMSSN: S(v) });
1134
+ }
1135
+ grupo = { ICMSSN900: out };
1136
+ break;
1137
+ }
1138
+ }
1139
+ } else if (input.grupo === "Part") {
1140
+ const pRedBC = ctx.opt(input.pRedBC, `${path}.pRedBC`, PO);
1141
+ const p = proprio(input, pRedBC, true);
1142
+ const pBCOp = ctx.req(input.pBCOp, `${path}.pBCOp`, PO);
1143
+ grupo = {
1144
+ ICMSPart: {
1145
+ orig: input.orig,
1146
+ CST: input.CST,
1147
+ modBC: input.modBC,
1148
+ vBC: p.out.vBC,
1149
+ pRedBC: ctx.so(pRedBC, PO),
1150
+ pICMS: p.out.pICMS,
1151
+ vICMS: p.out.vICMS,
1152
+ ...st(input.st, p.vICMS, Decimal.ZERO),
1153
+ pBCOp: ctx.s(pBCOp, PO),
1154
+ UFST: input.UFST,
1155
+ ...deson(input.desoneracao)
1156
+ }
1157
+ };
1158
+ } else if (input.grupo === "ST") {
1159
+ grupo = {
1160
+ ICMSST: {
1161
+ orig: input.orig,
1162
+ CST: input.CST,
1163
+ ...retido(input),
1164
+ vBCSTRet: S(ctx.req(input.vBCSTRet, `${path}.vBCSTRet`, M)),
1165
+ vICMSSTRet: S(ctx.req(input.vICMSSTRet, `${path}.vICMSSTRet`, M)),
1166
+ vBCSTDest: S(ctx.req(input.vBCSTDest, `${path}.vBCSTDest`, M)),
1167
+ vICMSSTDest: S(ctx.req(input.vICMSSTDest, `${path}.vICMSSTDest`, M))
1168
+ }
1169
+ };
1170
+ } else {
1171
+ const orig = input.orig;
1172
+ switch (input.CST) {
1173
+ case "00": {
1174
+ const p = proprio(input, undefined, true);
1175
+ grupo = { ICMS00: { orig, CST: "00", ...p.out, ...fcp(input, p.vBC, false) } };
1176
+ break;
1177
+ }
1178
+ case "02": {
1179
+ const qBCMono = q(input.qBCMono, "qBCMono");
1180
+ const adRem = ctx.req(input.adRemICMS, `${path}.adRemICMS`, P);
1181
+ const v = mono(qBCMono, adRem, input.vICMSMono, "vICMSMono");
1182
+ t.mono = true;
1183
+ t.qBCMono = t.qBCMono.plus(qBCMono ?? Decimal.ZERO);
1184
+ t.vICMSMono = t.vICMSMono.plus(v);
1185
+ grupo = {
1186
+ ICMS02: {
1187
+ orig,
1188
+ CST: "02",
1189
+ qBCMono: ctx.so(qBCMono, D1104V),
1190
+ adRemICMS: ctx.s(adRem, P),
1191
+ vICMSMono: S(v)
1192
+ }
1193
+ };
1194
+ break;
1195
+ }
1196
+ case "10": {
1197
+ const p = proprio(input, undefined, true);
1198
+ const f = fcp(input, p.vBC, true);
1199
+ const vFCP = f.vFCP === undefined ? Decimal.ZERO : Decimal.of(f.vFCP);
1200
+ grupo = {
1201
+ ICMS10: { orig, CST: "10", ...p.out, ...f, ...st(input.st, p.vICMS, vFCP), ...desonSt(input.desoneracaoSt) }
1202
+ };
1203
+ break;
1204
+ }
1205
+ case "15": {
1206
+ const qBCMono = q(input.qBCMono, "qBCMono");
1207
+ const adRem = ctx.req(input.adRemICMS, `${path}.adRemICMS`, P);
1208
+ const v = mono(qBCMono, adRem, input.vICMSMono, "vICMSMono");
1209
+ const qReten = q(input.qBCMonoReten, "qBCMonoReten");
1210
+ const adRemReten = ctx.req(input.adRemICMSReten, `${path}.adRemICMSReten`, P);
1211
+ if (input.pRedAdRem !== undefined) {
1212
+ if (input.vICMSMono === undefined)
1213
+ ctx.issues.add(`${path}.vICMSMono`, "campo_obrigatorio", "com pRedAdRem, informe vICMSMono");
1214
+ if (input.vICMSMonoReten === undefined) {
1215
+ ctx.issues.add(`${path}.vICMSMonoReten`, "campo_obrigatorio", "com pRedAdRem, informe vICMSMonoReten");
1216
+ }
1217
+ }
1218
+ const vReten = mono(qReten, adRemReten, input.vICMSMonoReten, "vICMSMonoReten");
1219
+ t.mono = true;
1220
+ t.qBCMono = t.qBCMono.plus(qBCMono ?? Decimal.ZERO);
1221
+ t.vICMSMono = t.vICMSMono.plus(v);
1222
+ t.qBCMonoReten = t.qBCMonoReten.plus(qReten ?? Decimal.ZERO);
1223
+ t.vICMSMonoReten = t.vICMSMonoReten.plus(vReten);
1224
+ grupo = {
1225
+ ICMS15: {
1226
+ orig,
1227
+ CST: "15",
1228
+ qBCMono: ctx.so(qBCMono, D1104V),
1229
+ adRemICMS: ctx.s(adRem, P),
1230
+ vICMSMono: S(v),
1231
+ qBCMonoReten: ctx.so(qReten, D1104V),
1232
+ adRemICMSReten: ctx.s(adRemReten, P),
1233
+ vICMSMonoReten: S(vReten),
1234
+ pRedAdRem: ctx.so(ctx.opt(input.pRedAdRem, `${path}.pRedAdRem`, D0302A04), D0302A04),
1235
+ motRedAdRem: input.motRedAdRem
1236
+ }
1237
+ };
1238
+ break;
1239
+ }
1240
+ case "20": {
1241
+ const pRedBC = ctx.req(input.pRedBC, `${path}.pRedBC`, P);
1242
+ const p = proprio(input, pRedBC, true);
1243
+ grupo = {
1244
+ ICMS20: {
1245
+ orig,
1246
+ CST: "20",
1247
+ modBC: p.out.modBC,
1248
+ pRedBC: ctx.s(pRedBC, P),
1249
+ vBC: p.out.vBC,
1250
+ pICMS: p.out.pICMS,
1251
+ vICMS: p.out.vICMS,
1252
+ ...fcp(input, p.vBC, true),
1253
+ ...deson(input.desoneracao)
1254
+ }
1255
+ };
1256
+ break;
1257
+ }
1258
+ case "30":
1259
+ grupo = {
1260
+ ICMS30: { orig, CST: "30", ...st(input.st, Decimal.ZERO, Decimal.ZERO), ...deson(input.desoneracao) }
1261
+ };
1262
+ break;
1263
+ case "40":
1264
+ case "41":
1265
+ case "50":
1266
+ grupo = { ICMS40: { orig, CST: input.CST, ...deson(input.desoneracao) } };
1267
+ break;
1268
+ case "51":
1269
+ grupo = { ICMS51: { orig, CST: "51", ...diferimento(input, P, false) } };
1270
+ break;
1271
+ case "53": {
1272
+ const qBCMono = q(input.qBCMono, "qBCMono");
1273
+ const adRem = ctx.opt(input.adRemICMS, `${path}.adRemICMS`, P);
1274
+ const vOp = mono(qBCMono, adRem, input.vICMSMonoOp, "vICMSMonoOp");
1275
+ const pDif = ctx.opt(input.pDif, `${path}.pDif`, P);
1276
+ const vDif = ctx.calc(input.vICMSMonoDif, vOp.percent(pDif ?? Decimal.ZERO), `${path}.vICMSMonoDif`, M, "icms");
1277
+ const v = ctx.calc(input.vICMSMono, vOp.minus(vDif), `${path}.vICMSMono`, M, "icms");
1278
+ const qDif = q(input.qBCMonoDif, "qBCMonoDif");
1279
+ const adRemDif = ctx.opt(input.adRemICMSDif, `${path}.adRemICMSDif`, P);
1280
+ t.mono = true;
1281
+ t.qBCMono = t.qBCMono.plus(qBCMono ?? Decimal.ZERO);
1282
+ t.vICMSMono = t.vICMSMono.plus(v);
1283
+ grupo = {
1284
+ ICMS53: {
1285
+ orig,
1286
+ CST: "53",
1287
+ qBCMono: ctx.so(qBCMono, D1104V),
1288
+ adRemICMS: ctx.so(adRem, P),
1289
+ vICMSMonoOp: adRem === undefined && input.vICMSMonoOp === undefined ? undefined : S(vOp),
1290
+ pDif: ctx.so(pDif, P),
1291
+ vICMSMonoDif: pDif === undefined && input.vICMSMonoDif === undefined ? undefined : S(vDif),
1292
+ vICMSMono: adRem === undefined && input.vICMSMono === undefined ? undefined : S(v),
1293
+ qBCMonoDif: ctx.so(qDif, D1104V),
1294
+ adRemICMSDif: ctx.so(adRemDif, P)
1295
+ }
1296
+ };
1297
+ break;
1298
+ }
1299
+ case "60":
1300
+ grupo = { ICMS60: { orig, CST: "60", ...retido(input) } };
1301
+ break;
1302
+ case "61": {
1303
+ const qRet = q(input.qBCMonoRet, "qBCMonoRet");
1304
+ const adRem = ctx.req(input.adRemICMSRet, `${path}.adRemICMSRet`, P);
1305
+ const v = mono(qRet, adRem, input.vICMSMonoRet, "vICMSMonoRet");
1306
+ t.mono = true;
1307
+ t.qBCMonoRet = t.qBCMonoRet.plus(qRet ?? Decimal.ZERO);
1308
+ t.vICMSMonoRet = t.vICMSMonoRet.plus(v);
1309
+ grupo = {
1310
+ ICMS61: {
1311
+ orig,
1312
+ CST: "61",
1313
+ qBCMonoRet: ctx.so(qRet, D1104V),
1314
+ adRemICMSRet: ctx.s(adRem, P),
1315
+ vICMSMonoRet: S(v)
1316
+ }
1317
+ };
1318
+ break;
1319
+ }
1320
+ case "70": {
1321
+ const pRedBC = ctx.req(input.pRedBC, `${path}.pRedBC`, P);
1322
+ const p = proprio(input, pRedBC, true);
1323
+ const f = fcp(input, p.vBC, true);
1324
+ const vFCP = f.vFCP === undefined ? Decimal.ZERO : Decimal.of(f.vFCP);
1325
+ grupo = {
1326
+ ICMS70: {
1327
+ orig,
1328
+ CST: "70",
1329
+ modBC: p.out.modBC,
1330
+ pRedBC: ctx.s(pRedBC, P),
1331
+ vBC: p.out.vBC,
1332
+ pICMS: p.out.pICMS,
1333
+ vICMS: p.out.vICMS,
1334
+ ...f,
1335
+ ...st(input.st, p.vICMS, vFCP),
1336
+ ...deson(input.desoneracao),
1337
+ ...desonSt(input.desoneracaoSt)
1338
+ }
1339
+ };
1340
+ break;
1341
+ }
1342
+ case "90": {
1343
+ const d = diferimento(input, PO, true);
1344
+ const vICMS = d.vICMS === undefined ? Decimal.ZERO : Decimal.of(d.vICMS);
1345
+ const vFCP = d.vFCP;
1346
+ grupo = {
1347
+ ICMS90: {
1348
+ orig,
1349
+ CST: "90",
1350
+ ...d,
1351
+ ...input.st ? st(input.st, vICMS, vFCP === undefined ? Decimal.ZERO : Decimal.of(vFCP)) : {},
1352
+ ...deson(input.desoneracao),
1353
+ ...desonSt(input.desoneracaoSt)
1354
+ }
1355
+ };
1356
+ break;
1357
+ }
1358
+ }
1359
+ }
1360
+ const [name, body] = Object.entries(grupo)[0];
1361
+ return { grupo: { [name]: clean(body) }, totais: t };
1362
+ }
1363
+
1364
+ // packages/nfe/src/build/nfce.ts
1365
+ import { tpAmbOf } from "@sinete/core";
1366
+ import { base64Encode, c14n, firstChild as firstChild2, parseXml as parseXml2, SHA1_DIGEST_INFO_PREFIX } from "@sinete/core/xml";
1367
+ import { parseCnpj as parseCnpj2 } from "@sinete/validators";
1368
+ // packages/nfe/src/data/nfce-urls.json
1369
+ var nfce_urls_default = {
1370
+ descricao: "Endereços da NFC-e (modelo 65) por UF e ambiente: a consulta via QR Code (1ª parte da URL do infNFeSupl/qrCode, sem o '?p=' que o builder acrescenta) e a consulta por chave de acesso (infNFeSupl/urlChave, impressa no DANFC-e). Cada UF tem uma lista de endereços com a data de início ('desde', AAAA-MM-DD, 00:00 de Brasília); vale o mais recente cujo início não passou da data de emissão. As tabelas do ENCAT foram transcritas como publicadas, com três ajustes: o '?' final e o exemplo de parâmetros (AM: '?chNFe=1315....') foram retirados, porque o builder monta a query; o espaço dentro do endereço de homologação do MA ('homolog acao') foi juntado; e o endereço de MG por chave de acesso vem da página de web services da própria SEFAZ-MG, mais nova que a do ENCAT. Onde a tabela não dá o protocolo ('http://' ou 'https://'), a URL do QR Code fica null: o schema exige o protocolo e não há fonte para escolher um; informe BuildNfeOptions.urlQrCode. A regra ZX02-20 (rejeição 395) compara o endereço sem diferenciar maiúsculas e minúsculas; ZX03-20 (rejeição 878) é opcional por UF.",
1371
+ atualizadoEm: "2026-09-26",
1372
+ fontes: [
1373
+ "Portal Nacional da NFC-e (ENCAT), URL por UF utilizada QR code: https://nfce.encat.org/desenvolvedor/qrcode/ (coletada em 26/09/2026)",
1374
+ "Portal Nacional da NFC-e (ENCAT), URL por UF utilizada para consulta chave, QR Code versão 2.0: https://nfce.encat.org/desenvolvedor/httpnfce-encat-orgconsulte-sua-nota-qr-code-versao-2-0/ (coletada em 26/09/2026)",
1375
+ "SEFAZ-MG, web services da NFC-e: https://portalsped.fazenda.mg.gov.br/spedmg/nfce/web-services/ (a mesma fonte do nfceConsultaUrls do @sinete/transport) (coletada em 26/09/2026)",
1376
+ "MOC 7.0 Anexo I, regras ZX02-20 e ZX03-20; NT 2025.001 v1.03, grupo ZX (campos ZX02 qrCode e ZX03 urlChave)"
1377
+ ],
1378
+ qrCode: {
1379
+ producao: {
1380
+ AC: [{ url: "http://www.sefaznet.ac.gov.br/nfce/qrcode" }],
1381
+ AL: [{ url: "http://nfce.sefaz.al.gov.br/QRCode/consultarNFCe.jsp" }],
1382
+ AP: [{ url: "https://www.sefaz.ap.gov.br/nfce/nfcep.php" }],
1383
+ AM: [
1384
+ { url: null, nota: "tabela do ENCAT sem protocolo: sistemas.sefaz.am.gov.br/nfceweb/consultarNFCe.jsp" }
1385
+ ],
1386
+ BA: [{ url: "http://nfe.sefaz.ba.gov.br/servicos/nfce/qrcode.aspx" }],
1387
+ CE: [{ url: "http://nfce.sefaz.ce.gov.br/pages/ShowNFCe.html" }],
1388
+ DF: [{ url: "http://www.fazenda.df.gov.br/nfce/qrcode" }],
1389
+ ES: [{ url: "http://app.sefaz.es.gov.br/ConsultaNFCe/" }],
1390
+ GO: [
1391
+ { url: "http://nfe.sefaz.go.gov.br/nfeweb/sites/nfce/danfeNFCe" },
1392
+ { url: "https://nfeweb.sefaz.go.gov.br/nfeweb/sites/nfce/danfeNFCe", desde: "2025-06-16" }
1393
+ ],
1394
+ MA: [{ url: null, nota: "tabela do ENCAT sem protocolo: nfce.sefaz.ma.gov.br/portal/consultarNFCe.jsp" }],
1395
+ MT: [{ url: "http://www.sefaz.mt.gov.br/nfce/consultanfce" }],
1396
+ MS: [{ url: "http://www.dfe.ms.gov.br/nfce/qrcode" }],
1397
+ MG: [
1398
+ { url: "https://nfce.fazenda.mg.gov.br/portalnfce/sistema/qrcode.xhtml" },
1399
+ { url: "https://portalsped.fazenda.mg.gov.br/portalnfce/sistema/qrcode.xhtml", desde: "2022-03-21" }
1400
+ ],
1401
+ PA: [{ url: "https://appnfc.sefa.pa.gov.br/portal/view/consultas/nfce/nfceForm.seam" }],
1402
+ PB: [{ url: "http://www.sefaz.pb.gov.br/nfce" }],
1403
+ PR: [{ url: "http://www.fazenda.pr.gov.br/nfce/qrcode" }],
1404
+ PE: [{ url: "http://nfce.sefaz.pe.gov.br/nfce/consulta" }],
1405
+ PI: [{ url: "http://www.sefaz.pi.gov.br/nfce/qrcode" }],
1406
+ RJ: [
1407
+ { url: "http://www4.fazenda.rj.gov.br/consultaNFCe/QRCode" },
1408
+ { url: "https://consultadfe.fazenda.rj.gov.br/consultaNFCe/QRCode", desde: "2023-12-19" }
1409
+ ],
1410
+ RN: [
1411
+ { url: "http://nfce.set.rn.gov.br/consultarNFCe.aspx" },
1412
+ { url: "https://nfce.sefaz.rn.gov.br/consultarNFCe.aspx", desde: "2026-05-25" }
1413
+ ],
1414
+ RS: [{ url: "https://www.sefaz.rs.gov.br/NFCE/NFCE-COM.aspx" }],
1415
+ RO: [{ url: "http://www.nfce.sefin.ro.gov.br/consultanfce/consulta.jsp" }],
1416
+ RR: [{ url: "https://www.sefaz.rr.gov.br/nfce/servlet/qrcode" }],
1417
+ SC: [{ url: "https://sat.sef.sc.gov.br/nfce/consulta" }],
1418
+ SP: [
1419
+ {
1420
+ url: "https://www.nfce.fazenda.sp.gov.br/NFCeConsultaPublica/Paginas/ConsultaQRCode.aspx",
1421
+ nota: "a tabela do ENCAT lista também https://www.nfce.fazenda.sp.gov.br/qrcode"
1422
+ }
1423
+ ],
1424
+ SE: [{ url: "http://www.nfce.se.gov.br/nfce/qrcode" }],
1425
+ TO: [{ url: "http://www.sefaz.to.gov.br/nfce/qrcode" }]
1426
+ },
1427
+ homologacao: {
1428
+ AC: [{ url: "http://www.hml.sefaznet.ac.gov.br/nfce/qrcode" }],
1429
+ AL: [{ url: "http://nfce.sefaz.al.gov.br/QRCode/consultarNFCe.jsp" }],
1430
+ AP: [{ url: "https://www.sefaz.ap.gov.br/nfcehml/nfce.php" }],
1431
+ AM: [
1432
+ { url: null, nota: "tabela do ENCAT sem protocolo: homnfce.sefaz.am.gov.br/nfceweb/consultarNFCe.jsp" }
1433
+ ],
1434
+ BA: [{ url: "http://hnfe.sefaz.ba.gov.br/servicos/nfce/qrcode.aspx" }],
1435
+ CE: [{ url: "http://nfceh.sefaz.ce.gov.br/pages/ShowNFCe.html" }],
1436
+ DF: [{ url: "http://www.fazenda.df.gov.br/nfce/qrcode" }],
1437
+ ES: [{ url: "http://homologacao.sefaz.es.gov.br/ConsultaNFCe/" }],
1438
+ GO: [
1439
+ { url: "http://homolog.sefaz.go.gov.br/nfeweb/sites/nfce/danfeNFCe" },
1440
+ { url: "https://nfewebhomolog.sefaz.go.gov.br/nfeweb/sites/nfce/danfeNFCe", desde: "2025-06-16" }
1441
+ ],
1442
+ MA: [
1443
+ { url: null, nota: "tabela do ENCAT sem protocolo: homologacao.sefaz.ma.gov.br/portal/consultarNFCe.jsp" }
1444
+ ],
1445
+ MT: [{ url: "http://homologacao.sefaz.mt.gov.br/nfce/consultanfce" }],
1446
+ MS: [{ url: "http://www.dfe.ms.gov.br/nfce/qrcode" }],
1447
+ MG: [
1448
+ { url: "https://nfce.fazenda.mg.gov.br/portalnfce/sistema/qrcode.xhtml" },
1449
+ { url: "https://portalsped.fazenda.mg.gov.br/portalnfce/sistema/qrcode.xhtml", desde: "2022-03-21" }
1450
+ ],
1451
+ PA: [{ url: "https://appnfc.sefa.pa.gov.br/portal-homologacao/view/consultas/nfce/nfceForm.seam" }],
1452
+ PB: [{ url: "http://www.sefaz.pb.gov.br/nfcehom" }],
1453
+ PR: [{ url: "http://www.fazenda.pr.gov.br/nfce/qrcode" }],
1454
+ PE: [{ url: "http://nfcehomolog.sefaz.pe.gov.br/nfce/consulta" }],
1455
+ PI: [{ url: "http://www.sefaz.pi.gov.br/nfce/qrcode" }],
1456
+ RJ: [
1457
+ { url: "http://www4.fazenda.rj.gov.br/consultaNFCe/QRCode" },
1458
+ { url: "https://consultadfe.fazenda.rj.gov.br/consultaNFCe/QRCode", desde: "2023-12-19" }
1459
+ ],
1460
+ RN: [
1461
+ { url: "http://hom.nfce.set.rn.gov.br/consultarNFCe.aspx" },
1462
+ { url: "https://hom.nfce.sefaz.rn.gov.br/consultarNFCe.aspx", desde: "2026-05-25" }
1463
+ ],
1464
+ RS: [{ url: "https://www.sefaz.rs.gov.br/NFCE/NFCE-COM.aspx" }],
1465
+ RO: [{ url: "http://www.nfce.sefin.ro.gov.br/consultanfce/consulta.jsp" }],
1466
+ RR: [{ url: "http://200.174.88.103:8080/nfce/servlet/qrcode" }],
1467
+ SC: [{ url: "https://hom.sat.sef.sc.gov.br/nfce/consulta" }],
1468
+ SP: [
1469
+ {
1470
+ url: "https://www.homologacao.nfce.fazenda.sp.gov.br/NFCeConsultaPublica/Paginas/ConsultaQRCode.aspx",
1471
+ nota: "a tabela do ENCAT lista também https://www.homologacao.nfce.fazenda.sp.gov.br/qrcode"
1472
+ }
1473
+ ],
1474
+ SE: [{ url: "http://www.hom.nfe.se.gov.br/nfce/qrcode" }],
1475
+ TO: [{ url: "http://homologacao.sefaz.to.gov.br/nfce/qrcode" }]
1476
+ }
1477
+ },
1478
+ urlChave: {
1479
+ producao: {
1480
+ AC: [{ url: "www.sefaznet.ac.gov.br/nfce/consulta" }],
1481
+ AL: [{ url: "www.sefaz.al.gov.br/nfce/consulta" }],
1482
+ AP: [{ url: "www.sefaz.ap.gov.br/nfce/consulta" }],
1483
+ AM: [{ url: "www.sefaz.am.gov.br/nfce/consulta" }],
1484
+ BA: [{ url: "www.sefaz.ba.gov.br/nfce/consulta" }],
1485
+ CE: [{ url: "www.sefaz.ce.gov.br/nfce/consulta" }],
1486
+ DF: [{ url: "www.fazenda.df.gov.br/nfce/consulta" }],
1487
+ ES: [{ url: "www.sefaz.es.gov.br/nfce/consulta" }],
1488
+ GO: [{ url: "www.sefaz.go.gov.br/nfce/consulta" }],
1489
+ MA: [{ url: "www.sefaz.ma.gov.br/nfce/consulta" }],
1490
+ MT: [{ url: "http://www.sefaz.mt.gov.br/nfce/consultanfce" }],
1491
+ MS: [{ url: "www.dfe.ms.gov.br/nfce/consulta" }],
1492
+ MG: [{ url: "https://portalsped.fazenda.mg.gov.br/portalnfce" }],
1493
+ PA: [{ url: "www.sefa.pa.gov.br/nfce/consulta" }],
1494
+ PB: [{ url: "www.receita.pb.gov.br/nfce/consulta" }],
1495
+ PR: [{ url: "http://www.fazenda.pr.gov.br/nfce/consulta" }],
1496
+ PE: [{ url: "nfce.sefaz.pe.gov.br/nfce/consulta" }],
1497
+ PI: [{ url: "www.sefaz.pi.gov.br/nfce/consulta" }],
1498
+ RJ: [{ url: "www.fazenda.rj.gov.br/nfce/consulta" }],
1499
+ RN: [{ url: "www.set.rn.gov.br/nfce/consulta" }],
1500
+ RS: [{ url: "www.sefaz.rs.gov.br/nfce/consulta" }],
1501
+ RO: [{ url: "www.sefin.ro.gov.br/nfce/consulta" }],
1502
+ RR: [{ url: "www.sefaz.rr.gov.br/nfce/consulta" }],
1503
+ SC: [{ url: "https://sat.sef.sc.gov.br/nfce/consulta" }],
1504
+ SP: [{ url: "https://www.nfce.fazenda.sp.gov.br/consulta" }],
1505
+ SE: [{ url: "http://www.nfce.se.gov.br/nfce/consulta" }],
1506
+ TO: [{ url: "www.sefaz.to.gov.br/nfce/consulta" }]
1507
+ },
1508
+ homologacao: {
1509
+ AC: [{ url: "www.sefaznet.ac.gov.br/nfce/consulta" }],
1510
+ AL: [{ url: "www.sefaz.al.gov.br/nfce/consulta" }],
1511
+ AP: [{ url: "www.sefaz.ap.gov.br/nfce/consulta" }],
1512
+ AM: [{ url: "www.sefaz.am.gov.br/nfce/consulta" }],
1513
+ BA: [{ url: "http://hinternet.sefaz.ba.gov.br/nfce/consulta" }],
1514
+ CE: [{ url: "www.sefaz.ce.gov.br/nfce/consulta" }],
1515
+ DF: [{ url: "www.fazenda.df.gov.br/nfce/consulta" }],
1516
+ ES: [{ url: "www.sefaz.es.gov.br/nfce/consulta" }],
1517
+ GO: [{ url: "www.sefaz.go.gov.br/nfce/consulta" }],
1518
+ MA: [{ url: "www.sefaz.ma.gov.br/nfce/consulta" }],
1519
+ MT: [{ url: "http://homologacao.sefaz.mt.gov.br/nfce/consultanfce" }],
1520
+ MS: [{ url: "www.dfe.ms.gov.br/nfce/consulta" }],
1521
+ MG: [{ url: "https://hportalsped.fazenda.mg.gov.br/portalnfce" }],
1522
+ PA: [{ url: "www.sefa.pa.gov.br/nfce/consulta" }],
1523
+ PB: [{ url: "www.receita.pb.gov.br/nfcehom" }],
1524
+ PR: [{ url: "http://www.fazenda.pr.gov.br/nfce/consulta" }],
1525
+ PE: [{ url: "nfce.sefaz.pe.gov.br/nfce/consulta" }],
1526
+ PI: [{ url: "www.sefaz.pi.gov.br/nfce/consulta" }],
1527
+ RJ: [{ url: "www.fazenda.rj.gov.br/nfce/consulta" }],
1528
+ RN: [{ url: "www.set.rn.gov.br/nfce/consulta" }],
1529
+ RS: [{ url: "www.sefaz.rs.gov.br/nfce/consulta" }],
1530
+ RO: [{ url: "www.sefin.ro.gov.br/nfce/consulta" }],
1531
+ RR: [{ url: "www.sefaz.rr.gov.br/nfce/consulta" }],
1532
+ SC: [{ url: "https://hom.sat.sef.sc.gov.br/nfce/consulta" }],
1533
+ SP: [{ url: "https://www.homologacao.nfce.fazenda.sp.gov.br/consulta" }],
1534
+ SE: [{ url: "http://www.hom.nfe.se.gov.br/nfce/consulta" }],
1535
+ TO: [{ url: "http://homologacao.sefaz.to.gov.br/nfce/consulta.jsf" }]
1536
+ }
1537
+ }
1538
+ };
1539
+
1540
+ // packages/nfe/src/build/nfce.ts
1541
+ function vigente(lista, dia) {
1542
+ let achado;
1543
+ for (const e of lista ?? []) {
1544
+ if ((e.desde ?? "") <= dia && (achado === undefined || (e.desde ?? "") >= (achado.desde ?? "")))
1545
+ achado = e;
1546
+ }
1547
+ return achado;
1548
+ }
1549
+ function urlsNfce(uf, ambiente, dia) {
1550
+ const q = vigente(nfce_urls_default.qrCode[ambiente][uf], dia);
1551
+ const c = vigente(nfce_urls_default.urlChave[ambiente][uf], dia);
1552
+ return { qrCode: q?.url ?? undefined, urlChave: c?.url ?? undefined };
1553
+ }
1554
+ var te = new TextEncoder;
1555
+ var NFE_NS2 = "http://www.portalfiscal.inf.br/nfe";
1556
+ async function sha1(bytes) {
1557
+ return new Uint8Array(await globalThis.crypto.subtle.digest("SHA-1", bytes));
1558
+ }
1559
+ var hex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
1560
+ async function digValHex(xml) {
1561
+ const doc = parseXml2(xml);
1562
+ const inf = firstChild2(doc.root, "infNFe", NFE_NS2);
1563
+ if (inf === undefined)
1564
+ throw new Error("NF-e montada sem infNFe");
1565
+ return hexDoDigestValue(base64Encode(await sha1(te.encode(c14n(inf)))));
1566
+ }
1567
+ function hexDoDigestValue(digestValue) {
1568
+ return hex(te.encode(digestValue));
1569
+ }
1570
+ async function hashQrCodeV2(parametros, csc) {
1571
+ return hex(await sha1(te.encode(parametros + csc))).toUpperCase();
1572
+ }
1573
+ async function parametrosQrCode(d, qr) {
1574
+ const tpAmb = tpAmbOf(d.ambiente);
1575
+ const offline = d.tpEmis === "9";
1576
+ const dia = d.dhEmi.slice(8, 10);
1577
+ if (qr.versao === "3") {
1578
+ if (!offline)
1579
+ return { parametros: `${d.chave}|3|${tpAmb}`, assinar: false };
1580
+ const dest = d.dest;
1581
+ const [tp, id] = dest?.CNPJ !== undefined ? ["1", dest.CNPJ] : dest?.CPF !== undefined ? ["2", dest.CPF] : dest?.idEstrangeiro !== undefined ? ["3", ""] : ["", ""];
1582
+ return { parametros: `${d.chave}|3|${tpAmb}|${dia}|${d.vNF}|${tp}|${id}`, assinar: true };
1583
+ }
1584
+ const idCSC = String(Number(qr.idCSC));
1585
+ const antes = offline ? `${d.chave}|2|${tpAmb}|${dia}|${d.vNF}|${await digValHex(d.xml)}|${idCSC}` : `${d.chave}|2|${tpAmb}|${idCSC}`;
1586
+ return { parametros: `${antes}|${await hashQrCodeV2(antes, qr.CSC)}`, assinar: false };
1587
+ }
1588
+ async function assinarParametros(parametros, signer) {
1589
+ const bytes = te.encode(parametros);
1590
+ if (signer.kind === "data")
1591
+ return base64Encode(await signer.sign(bytes, "SHA-1"));
1592
+ const h = await sha1(bytes);
1593
+ const di = new Uint8Array(SHA1_DIGEST_INFO_PREFIX.length + h.length);
1594
+ di.set(SHA1_DIGEST_INFO_PREFIX);
1595
+ di.set(h, SHA1_DIGEST_INFO_PREFIX.length);
1596
+ return base64Encode(await signer.signDigestInfo(di));
1597
+ }
1598
+ var CFOP_ISSQN = "5933";
1599
+ var NFCE_LIMITE_SEM_DESTINATARIO = "10000.00";
1600
+ var TPAG_VEDADOS = {
1601
+ "14": "duplicata mercantil não é meio de pagamento da NFC-e (YA02-10, rejeição 857)",
1602
+ "90": "a NFC-e sempre tem pagamento: tPag 90 (sem pagamento) é recusado (YA02-40, rejeição 899)",
1603
+ "99": "tPag 99 (outros) não é aceito na NFC-e (YA02-50, rejeição 436, NT 2020.006)"
1604
+ };
1605
+ function conferirNfce(input, ide, issues) {
1606
+ const vedado = (path, msg) => issues.add(path, "grupo_vedado", `NFC-e ${msg}`);
1607
+ const invalido = (path, msg) => issues.add(path, "campo_invalido", `NFC-e ${msg}`);
1608
+ if (input.dhSaiEnt !== undefined)
1609
+ vedado("dhSaiEnt", "sem data de entrada ou saída (B10-10, rejeição 705)");
1610
+ if (input.dPrevEntrega !== undefined) {
1611
+ vedado("dPrevEntrega", "sem data de previsão de entrega (NT 2025.002, B10a-10, rejeição 1153)");
1612
+ }
1613
+ if (ide.tpNF !== "1")
1614
+ invalido("tpNF", "só de saída, tpNF 1 (B11-10, rejeição 706)");
1615
+ if (ide.idDest !== "1") {
1616
+ invalido("idDest", "só em operação interna, idDest 1 (B11a-10, rejeição 707)");
1617
+ }
1618
+ if (ide.tpImp !== "4" && ide.tpImp !== "5") {
1619
+ invalido("tpImp", "com DANFC-e: tpImp 4 (impresso) ou 5 (mensagem eletrônica) (B21-10, rejeição 709)");
1620
+ }
1621
+ if (ide.finNFe !== "1")
1622
+ invalido("finNFe", "só com finalidade normal, finNFe 1 (B25-20, rejeição 715)");
1623
+ if (ide.indFinal !== "1")
1624
+ invalido("indFinal", "só com consumidor final, indFinal 1 (B25a-10, rejeição 716)");
1625
+ if (!["1", "4", "5"].includes(ide.indPres)) {
1626
+ invalido("indPres", "só presencial: indPres 1, 4 (entrega a domicílio) ou 5 (NT 2025.002, B25b-20, rejeição 717)");
1627
+ }
1628
+ if (input.cMunFGIBS !== undefined && ide.indPres !== "5") {
1629
+ invalido("cMunFGIBS", "com cMunFGIBS só em operação presencial fora do estabelecimento, indPres 5 (NT 2025.002, B25b-60, rejeição 1000)");
1630
+ }
1631
+ if (input.cMunFGIBS === undefined && ide.indPres === "5") {
1632
+ issues.add("cMunFGIBS", "campo_obrigatorio", "NFC-e presencial fora do estabelecimento (indPres 5) informa cMunFGIBS (NT 2025.002, B25b-70, rejeição 1005)");
1633
+ }
1634
+ if (input.referenciadas !== undefined && input.referenciadas.length > 0) {
1635
+ vedado("referenciadas", "não referencia documento fiscal (BA01-10, rejeição 708)");
1636
+ }
1637
+ if (input.gCompraGov !== undefined)
1638
+ vedado("gCompraGov", "sem compra governamental (NT 2025.002, BB01-10, rejeição 1006)");
1639
+ if (input.emitente.IEST !== undefined)
1640
+ vedado("emitente.IEST", "sem IE de substituto tributário (C18-10, rejeição 718)");
1641
+ const d = input.destinatario;
1642
+ if (ide.indPres === "4" && d === undefined) {
1643
+ issues.add("destinatario", "campo_obrigatorio", "NFC-e com entrega a domicílio identifica o destinatário (E01-20, rejeição 787)");
1644
+ }
1645
+ if (ide.indPres === "4" && d !== undefined && d.endereco === undefined) {
1646
+ issues.add("destinatario.endereco", "campo_obrigatorio", "NFC-e com entrega a domicílio informa o endereço do destinatário (E05-20, rejeição 788)");
1647
+ }
1648
+ if (d !== undefined) {
1649
+ if (d.CNPJ !== undefined && input.emitente.CNPJ !== undefined && digitos2(d.CNPJ) === digitos2(input.emitente.CNPJ)) {
1650
+ invalido("destinatario.CNPJ", "com destinatário igual ao emitente (E02-20, rejeição 220)");
1651
+ }
1652
+ if (d.indIEDest !== "9") {
1653
+ invalido("destinatario.indIEDest", "só para não contribuinte, indIEDest 9 (E16a-10, rejeição 789)");
1654
+ }
1655
+ if (d.ISUF !== undefined)
1656
+ vedado("destinatario.ISUF", "sem inscrição na Suframa (E18-10, rejeição 730)");
1657
+ }
1658
+ input.itens.forEach((it, n) => {
1659
+ const p = `itens[${n}]`;
1660
+ const esp = it.produto.especifico ?? {};
1661
+ if (esp.veicProd !== undefined)
1662
+ vedado(`${p}.produto.especifico.veicProd`, "sem veículo novo (J01-10, rejeição 736)");
1663
+ if (esp.arma !== undefined)
1664
+ vedado(`${p}.produto.especifico.arma`, "sem armamento (L01-10, rejeição 738)");
1665
+ if (esp.nRECOPI !== undefined)
1666
+ vedado(`${p}.produto.especifico.nRECOPI`, "sem papel imune RECOPI (LB01-10, rejeição 348)");
1667
+ if (it.produto.tpCredPresIBSZFM !== undefined) {
1668
+ vedado(`${p}.produto.tpCredPresIBSZFM`, "sem classificação para subapuração do IBS na ZFM (NT 2025.002, I05k-10, rejeição 1165)");
1669
+ }
1670
+ const cfop = it.produto.CFOP.replace(/\D/g, "");
1671
+ const imp = it.impostos;
1672
+ if (cfop === CFOP_ISSQN && imp.issqn === undefined) {
1673
+ issues.add(`${p}.impostos.issqn`, "combinacao_invalida", "NFC-e com CFOP 5.933 tem o grupo do ISSQN (I08-160, rejeição 374)");
1674
+ }
1675
+ if (cfop !== CFOP_ISSQN && imp.issqn !== undefined) {
1676
+ issues.add(`${p}.produto.CFOP`, "combinacao_invalida", "NFC-e com ISSQN usa o CFOP 5.933 (I08-170, rejeição 374)");
1677
+ }
1678
+ const icms = imp.icms;
1679
+ if (icms?.grupo === "Part")
1680
+ vedado(`${p}.impostos.icms`, "sem partilha do ICMS entre UF (N12-50, rejeição 741)");
1681
+ if (icms?.grupo === "ST")
1682
+ vedado(`${p}.impostos.icms`, "sem repasse do ICMS-ST retido (N12-60, rejeição 740)");
1683
+ if (icms?.grupo === undefined && icms?.CST === "90" && icms.st !== undefined) {
1684
+ vedado(`${p}.impostos.icms.st`, "com CST 90 sem os dados do ICMS-ST (N12-34, rejeição 381)");
1685
+ }
1686
+ if (imp.icmsUfDest !== undefined)
1687
+ vedado(`${p}.impostos.icmsUfDest`, "sem ICMS da UF de destino (NA01-10, rejeição 807)");
1688
+ if (imp.ipi !== undefined)
1689
+ vedado(`${p}.impostos.ipi`, "sem IPI (O01-10, rejeição 742)");
1690
+ if (imp.ii !== undefined)
1691
+ vedado(`${p}.impostos.ii`, "sem imposto de importação (P01-10, rejeição 743)");
1692
+ if (imp.pisSt !== undefined)
1693
+ vedado(`${p}.impostos.pisSt`, "sem PIS-ST (R01-10, rejeição 746)");
1694
+ if (imp.cofinsSt !== undefined)
1695
+ vedado(`${p}.impostos.cofinsSt`, "sem COFINS-ST (T01-10, rejeição 749)");
1696
+ if (it.impostoDevol !== undefined)
1697
+ vedado(`${p}.impostoDevol`, "sem devolução de tributos (UA01-20, rejeição 390)");
1698
+ });
1699
+ const tr = input.transporte;
1700
+ const entrega = ide.indPres === "4";
1701
+ if (tr !== undefined && tr.modFrete !== "9" && !entrega) {
1702
+ invalido("transporte.modFrete", "sem frete fora da entrega a domicílio: modFrete 9 (X02-10, rejeição 753)");
1703
+ }
1704
+ if (tr?.transportador !== undefined && !entrega) {
1705
+ vedado("transporte.transportador", "só tem transportador na entrega a domicílio (X03-10, rejeição 754)");
1706
+ }
1707
+ if (entrega && tr?.transportador === undefined) {
1708
+ issues.add("transporte.transportador", "campo_obrigatorio", "NFC-e com entrega a domicílio identifica o transportador (X03-20, rejeição 786)");
1709
+ }
1710
+ if (tr?.retTransp !== undefined)
1711
+ vedado("transporte.retTransp", "sem retenção do ICMS no transporte (X11-10, rejeição 755)");
1712
+ if (tr?.veicTransp !== undefined)
1713
+ vedado("transporte.veicTransp", "sem veículo de transporte (X18-10, rejeição 756)");
1714
+ if (tr?.reboque !== undefined)
1715
+ vedado("transporte.reboque", "sem reboque (X22-10, rejeição 757)");
1716
+ if (input.cobranca !== undefined)
1717
+ vedado("cobranca", "sem fatura nem duplicata (Y01-10, rejeição 760)");
1718
+ if (input.pagamento === undefined || input.pagamento.detPag.length === 0) {
1719
+ issues.add("pagamento", "campo_obrigatorio", "a NFC-e informa o pagamento: tPag 90 (sem pagamento) é recusado (YA02-40, rejeição 899)");
1720
+ } else {
1721
+ input.pagamento.detPag.forEach((p, n) => {
1722
+ const motivo = TPAG_VEDADOS[p.tPag];
1723
+ if (motivo !== undefined)
1724
+ issues.add(`pagamento.detPag[${n}].tPag`, "pagamento_invalido", motivo);
1725
+ if (["03", "04", "17"].includes(p.tPag) && p.card === undefined) {
1726
+ issues.add(`pagamento.detPag[${n}].card`, "campo_obrigatorio", "pagamento com cartão (tPag 03 ou 04) ou PIX (17) informa o grupo card (NT 2025.001, YA04-10, rejeição 391)");
1727
+ }
1728
+ });
1729
+ }
1730
+ if (input.exporta !== undefined)
1731
+ vedado("exporta", "sem comércio exterior (ZA01-30, rejeição 814)");
1732
+ if (input.compra !== undefined)
1733
+ vedado("compra", "sem dados de compra (ZB01-10, rejeição 762)");
1734
+ if (input.cana !== undefined)
1735
+ vedado("cana", "sem aquisição de cana (ZC01-10, rejeição 763)");
1736
+ }
1737
+ function pagamentoNfce(pag, vNF, issues) {
1738
+ const total = pag.detPag.reduce((a, p) => a.plus(Decimal.of(p.vPag)), Decimal.ZERO);
1739
+ const troco = total.minus(vNF);
1740
+ const posterior = pag.detPag.some((p) => p.tPag === "91");
1741
+ pag.detPag.forEach((p, n) => {
1742
+ if (p.tPag === "91" && !Decimal.of(p.vPag).isZero()) {
1743
+ issues.add(`pagamento.detPag[${n}].vPag`, "pagamento_invalido", "pagamento posterior (tPag 91) tem vPag zero (NT 2025.001 v1.03, YA03-30, rejeição 904)");
1744
+ }
1745
+ });
1746
+ if (troco.isNegative() && !posterior) {
1747
+ issues.add("pagamento.detPag", "pagamento_invalido", `pagamentos (${total.toFixed(2)}) abaixo do total da NFC-e (${vNF.toFixed(2)}) (NT 2025.001 v1.03, YA03-10, rejeição 865)`);
1748
+ }
1749
+ if (pag.vTroco === undefined) {
1750
+ if (!troco.isNegative() && !troco.isZero())
1751
+ pag.vTroco = troco.toFixed(2);
1752
+ } else if (!Decimal.of(pag.vTroco).eq(troco)) {
1753
+ issues.add("pagamento.vTroco", "valor_divergente", `troco ${pag.vTroco} difere de pagamentos menos o total (${troco.toFixed(2)}) (YA09-10, rejeição 869)`);
1754
+ }
1755
+ pag.detPag.forEach((p, n) => {
1756
+ const c = p.card;
1757
+ if (c === undefined)
1758
+ return;
1759
+ const path = `pagamento.detPag[${n}].card`;
1760
+ if (c.tpIntegra === "1" && (c.CNPJ === undefined || c.cAut === undefined)) {
1761
+ issues.add(path, "campo_obrigatorio", "cartão integrado à automação (tpIntegra 1) informa o CNPJ da credenciadora e o cAut (NT 2025.001, YA05-10, rejeição 392)");
1762
+ }
1763
+ if (c.CNPJ !== undefined) {
1764
+ const r = parseCnpj2(c.CNPJ, { path: `${path}.CNPJ` });
1765
+ if (!r.ok)
1766
+ issues.list.push(r.error);
1767
+ }
1768
+ });
1769
+ }
1770
+ var digitos2 = (s) => s.replace(/[^0-9A-Za-z]/g, "").toUpperCase();
1771
+
1772
+ // packages/nfe/src/build/pl.ts
1773
+ import { UnsupportedError } from "@sinete/core";
1774
+ import { isComplexType, isElementParticle, isWildcard, selecionarPl } from "@sinete/schemas";
1775
+ import { TNFe_infNFe as Inf010e } from "@sinete/schemas/nfe/PL_010e";
1776
+ import { TNFe_infNFe as Inf010f } from "@sinete/schemas/nfe/PL_010f";
1777
+ var INF_NFE = {
1778
+ "nfe/PL_010e": Inf010e,
1779
+ "nfe/PL_010f": Inf010f
1780
+ };
1781
+ function escolherPl(ambiente, emissao) {
1782
+ const vigencia = selecionarPl("nfe", ambiente, emissao);
1783
+ const infNFe = INF_NFE[vigencia.modulo];
1784
+ if (infNFe === undefined) {
1785
+ throw new UnsupportedError(`@sinete/nfe não conhece o módulo ${vigencia.modulo}; atualize o pacote`);
1786
+ }
1787
+ return { vigencia, infNFe };
1788
+ }
1789
+ function memberNames(p, acc) {
1790
+ if (isWildcard(p))
1791
+ acc.add("$any");
1792
+ else if (isElementParticle(p))
1793
+ acc.add(p.e);
1794
+ else
1795
+ for (const i of p.i)
1796
+ memberNames(i, acc);
1797
+ return acc;
1798
+ }
1799
+ function elementTypes(p, acc) {
1800
+ if (isWildcard(p))
1801
+ return acc;
1802
+ if (isElementParticle(p)) {
1803
+ if (isComplexType(p.t))
1804
+ acc.set(p.e, p.t);
1805
+ } else
1806
+ for (const i of p.i)
1807
+ elementTypes(i, acc);
1808
+ return acc;
1809
+ }
1810
+ function camposForaDoPl(ct, value, path, pl, issues) {
1811
+ if (typeof value !== "object" || value === null)
1812
+ return;
1813
+ const allowed = new Set(["$attrs", "$text"]);
1814
+ for (const a of ct.a ?? [])
1815
+ allowed.add(a.a);
1816
+ if (ct.c)
1817
+ memberNames(ct.c, allowed);
1818
+ const children = ct.c ? elementTypes(ct.c, new Map) : new Map;
1819
+ for (const [k, v] of Object.entries(value)) {
1820
+ if (v === undefined)
1821
+ continue;
1822
+ if (!allowed.has(k)) {
1823
+ issues.montagem(`${path}.${k}`, "campo_fora_do_pl", `o campo não existe no ${pl} vigente para esta emissão`);
1824
+ continue;
1825
+ }
1826
+ const child = children.get(k);
1827
+ if (!child)
1828
+ continue;
1829
+ if (Array.isArray(v)) {
1830
+ for (const [n, x] of v.entries())
1831
+ camposForaDoPl(child, x, `${path}.${k}[${n}]`, pl, issues);
1832
+ } else
1833
+ camposForaDoPl(child, v, `${path}.${k}`, pl, issues);
1834
+ }
1835
+ }
1836
+
1837
+ // packages/nfe/src/build/rejeicoes.ts
1838
+ var CFOP_CST50_ISENTO = new Set([
1839
+ "1915",
1840
+ "1916",
1841
+ "2915",
1842
+ "2916",
1843
+ "5915",
1844
+ "5916",
1845
+ "6915",
1846
+ "6916",
1847
+ "1912",
1848
+ "1913",
1849
+ "5912",
1850
+ "5913"
1851
+ ]);
1852
+ function cstComIsento(input, idDest, issues) {
1853
+ const d = input.destinatario;
1854
+ if (d?.indIEDest !== "2")
1855
+ return;
1856
+ input.itens.forEach((it, n) => {
1857
+ const icms = it.impostos.icms;
1858
+ if (icms === undefined || !("CST" in icms))
1859
+ return;
1860
+ const cst = icms.CST;
1861
+ if (cst === "50" && CFOP_CST50_ISENTO.has(it.produto.CFOP.replace(/\D/g, "")))
1862
+ return;
1863
+ if (cst === "51" && idDest === "1")
1864
+ return;
1865
+ if (cst !== "50" && cst !== "51")
1866
+ return;
1867
+ issues.add(`itens[${n}].impostos.icms.CST`, "combinacao_invalida", `CST ${cst} não se usa com destinatário contribuinte isento de IE (indIEDest 2) (N12-80, rejeição 529)`);
1868
+ });
1869
+ }
1870
+ var dataNoFuso = (instante, offsetMinutes) => formatDh(instante, offsetMinutes).slice(0, 10);
1871
+ var OFFSET_BRASILIA = -180;
1872
+ function vencimentos(input, emissao, issues) {
1873
+ const dups = input.cobranca?.duplicatas;
1874
+ if (dups === undefined || dups.length !== 1)
1875
+ return;
1876
+ const unica = dups[0]?.dVenc;
1877
+ if (unica === undefined)
1878
+ return;
1879
+ const local = emissao.dhEmi.slice(0, 10);
1880
+ const datas = new Set([local, dataNoFuso(emissao.instante, OFFSET_BRASILIA), dataNoFuso(emissao.instante, 0)]);
1881
+ if (datas.size === 1 && datas.has(unica)) {
1882
+ issues.add("cobranca.duplicatas", "combinacao_invalida", "uma parcela só, vencendo na data de emissão, é pagamento à vista: não informe a cobrança (Y09-40, rejeição 853)");
1883
+ }
1884
+ }
1885
+ var soDocumento = (s) => s.replace(/[^0-9A-Za-z]/g, "").toUpperCase();
1886
+ function conferirEmitenteDoCertificado(nfe, titular) {
1887
+ const e = nfe.emitente;
1888
+ if (e.CNPJ !== undefined && titular.cnpj !== undefined) {
1889
+ const base = soDocumento(e.CNPJ).slice(0, 8);
1890
+ if (base !== soDocumento(titular.cnpj).slice(0, 8)) {
1891
+ return [
1892
+ {
1893
+ path: "emitente.CNPJ",
1894
+ code: "emitente_difere_do_certificado",
1895
+ message: `CNPJ-base ${base} do emitente difere do CNPJ-base do certificado (F03, rejeição 213)`,
1896
+ origem: "entrada"
1897
+ }
1898
+ ];
1899
+ }
1900
+ }
1901
+ if (e.CPF !== undefined && titular.cpf !== undefined && soDocumento(e.CPF) !== soDocumento(titular.cpf)) {
1902
+ return [
1903
+ {
1904
+ path: "emitente.CPF",
1905
+ code: "emitente_difere_do_certificado",
1906
+ message: "CPF do emitente difere do CPF do certificado (F03A, rejeição 227)",
1907
+ origem: "entrada"
1908
+ }
1909
+ ];
1910
+ }
1911
+ return [];
1912
+ }
1913
+
1914
+ // packages/nfe/src/build/tributos.ts
1915
+ function buildIpi(ctx, input, vOp, path) {
1916
+ const head = {
1917
+ CNPJProd: input.CNPJProd === undefined ? undefined : input.CNPJProd.replace(/[./-]/g, "").toUpperCase(),
1918
+ cSelo: input.cSelo,
1919
+ qSelo: input.qSelo,
1920
+ cEnq: input.cEnq
1921
+ };
1922
+ if (!["00", "49", "50", "99"].includes(input.CST)) {
1923
+ return { grupo: { ...clean(head), IPINT: { CST: input.CST } }, vIPI: Decimal.ZERO };
1924
+ }
1925
+ const i = input;
1926
+ let trib;
1927
+ let vIPI;
1928
+ if (i.qUnid !== undefined || i.vUnid !== undefined) {
1929
+ const qUnid = ctx.req(i.qUnid, `${path}.qUnid`, D1204V);
1930
+ const vUnid = ctx.req(i.vUnid, `${path}.vUnid`, D1104);
1931
+ vIPI = ctx.calc(i.vIPI, qUnid.times(vUnid), `${path}.vIPI`, D1302, "ipi");
1932
+ trib = { CST: i.CST, qUnid: ctx.s(qUnid, D1204V), vUnid: ctx.s(vUnid, D1104), vIPI: ctx.s(vIPI, D1302) };
1933
+ } else {
1934
+ const pIPI = ctx.req(i.pIPI, `${path}.pIPI`, D0302A04);
1935
+ const vBC = ctx.base(i.vBC, vOp, `${path}.vBC`, D1302, "ipi");
1936
+ vIPI = ctx.calc(i.vIPI, vBC.percent(pIPI), `${path}.vIPI`, D1302, "ipi");
1937
+ trib = { CST: i.CST, vBC: ctx.s(vBC, D1302), pIPI: ctx.s(pIPI, D0302A04), vIPI: ctx.s(vIPI, D1302) };
1938
+ }
1939
+ return { grupo: { ...clean(head), IPITrib: clean(trib) }, vIPI };
1940
+ }
1941
+ function buildIi(ctx, input, path) {
1942
+ const vII = ctx.req(input.vII, `${path}.vII`, D1302);
1943
+ return {
1944
+ grupo: {
1945
+ vBC: ctx.s(ctx.req(input.vBC, `${path}.vBC`, D1302), D1302),
1946
+ vDespAdu: ctx.s(ctx.req(input.vDespAdu, `${path}.vDespAdu`, D1302), D1302),
1947
+ vII: ctx.s(vII, D1302),
1948
+ vIOF: ctx.s(ctx.req(input.vIOF, `${path}.vIOF`, D1302), D1302)
1949
+ },
1950
+ vII
1951
+ };
1952
+ }
1953
+ function buildPisCofins(ctx, input, tag, path) {
1954
+ const p = `p${tag}`;
1955
+ const v = `v${tag}`;
1956
+ const cst = input.CST;
1957
+ if (!("vBC" in input) && !("qBCProd" in input)) {
1958
+ return { grupo: { [`${tag}NT`]: { CST: cst } }, valor: Decimal.ZERO };
1959
+ }
1960
+ const i = input;
1961
+ let body;
1962
+ let valor;
1963
+ if (i.qBCProd !== undefined) {
1964
+ const q = ctx.req(i.qBCProd, `${path}.qBCProd`, D1204V);
1965
+ const a = ctx.req(i.vAliqProd, `${path}.vAliqProd`, D1104V);
1966
+ valor = ctx.calc(i.valor, q.times(a), `${path}.valor`, D1302, "pisCofins");
1967
+ body = { CST: cst, qBCProd: ctx.s(q, D1204V), vAliqProd: ctx.s(a, D1104V), [v]: ctx.s(valor, D1302) };
1968
+ } else {
1969
+ const vBC = ctx.req(i.vBC, `${path}.vBC`, D1302);
1970
+ const a = ctx.req(i.aliquota, `${path}.aliquota`, D0302A04);
1971
+ valor = ctx.calc(i.valor, vBC.percent(a), `${path}.valor`, D1302, "pisCofins");
1972
+ body = { CST: cst, vBC: ctx.s(vBC, D1302), [p]: ctx.s(a, D0302A04), [v]: ctx.s(valor, D1302) };
1973
+ }
1974
+ const nome = cst === "01" || cst === "02" ? "Aliq" : cst === "03" ? "Qtde" : "Outr";
1975
+ return { grupo: { [`${tag}${nome}`]: body }, valor };
1976
+ }
1977
+ function buildPisCofinsSt(ctx, input, tag, path) {
1978
+ let body;
1979
+ let valor;
1980
+ if (input.qBCProd !== undefined) {
1981
+ const q = ctx.req(input.qBCProd, `${path}.qBCProd`, D1204);
1982
+ const a = ctx.req(input.vAliqProd, `${path}.vAliqProd`, D1104);
1983
+ valor = ctx.calc(input.valor, q.times(a), `${path}.valor`, D1302, "pisCofins");
1984
+ body = { qBCProd: ctx.s(q, D1204), vAliqProd: ctx.s(a, D1104) };
1985
+ } else {
1986
+ const fBC = tag === "PIS" ? D1302_OPC : D1302;
1987
+ const vBC = ctx.req(input.vBC, `${path}.vBC`, fBC);
1988
+ const a = ctx.req(input.aliquota, `${path}.aliquota`, D0302A04);
1989
+ valor = ctx.calc(input.valor, vBC.percent(a), `${path}.valor`, D1302, "pisCofins");
1990
+ body = { vBC: ctx.s(vBC, fBC), [`p${tag}`]: ctx.s(a, D0302A04) };
1991
+ }
1992
+ body[`v${tag}`] = ctx.s(valor, D1302);
1993
+ body[`indSoma${tag}ST`] = input.indSoma;
1994
+ return { grupo: clean(body), valor, soma: input.indSoma === "1" };
1995
+ }
1996
+ function buildIssqn(ctx, input, path) {
1997
+ const vBC = ctx.req(input.vBC, `${path}.vBC`, D1302);
1998
+ const vAliq = ctx.req(input.vAliq, `${path}.vAliq`, D0302A04);
1999
+ const vISSQN = ctx.calc(input.vISSQN, vBC.percent(vAliq), `${path}.vISSQN`, D1302, "issqn");
2000
+ const opcionais = {};
2001
+ const opt = (k) => {
2002
+ const d = ctx.opt(input[k], `${path}.${k}`, D1302);
2003
+ if (d !== undefined)
2004
+ opcionais[k] = d;
2005
+ return ctx.so(d, D1302_OPC);
2006
+ };
2007
+ return {
2008
+ grupo: clean({
2009
+ vBC: ctx.s(vBC, D1302),
2010
+ vAliq: ctx.s(vAliq, D0302A04),
2011
+ vISSQN: ctx.s(vISSQN, D1302),
2012
+ cMunFG: input.cMunFG,
2013
+ cListServ: input.cListServ,
2014
+ vDeducao: opt("vDeducao"),
2015
+ vOutro: opt("vOutro"),
2016
+ vDescIncond: opt("vDescIncond"),
2017
+ vDescCond: opt("vDescCond"),
2018
+ vISSRet: opt("vISSRet"),
2019
+ indISS: input.indISS,
2020
+ cServico: input.cServico,
2021
+ cMun: input.cMun,
2022
+ cPais: input.cPais === undefined ? undefined : digits(input.cPais),
2023
+ nProcesso: input.nProcesso,
2024
+ indIncentivo: input.indIncentivo
2025
+ }),
2026
+ vBC,
2027
+ vISSQN,
2028
+ opcionais
2029
+ };
2030
+ }
2031
+ function buildIcmsUfDest(ctx, input, path) {
2032
+ const pFCPUFDest = ctx.opt(input.pFCPUFDest, `${path}.pFCPUFDest`, D0302A04);
2033
+ const vFCPUFDest = ctx.opt(input.vFCPUFDest, `${path}.vFCPUFDest`, D1302);
2034
+ if (pFCPUFDest !== undefined && vFCPUFDest === undefined) {
2035
+ ctx.issues.add(`${path}.vFCPUFDest`, "campo_obrigatorio", "pFCPUFDest informado exige vFCPUFDest");
2036
+ }
2037
+ const vICMSUFDest = ctx.req(input.vICMSUFDest, `${path}.vICMSUFDest`, D1302);
2038
+ const vICMSUFRemet = ctx.opt(input.vICMSUFRemet, `${path}.vICMSUFRemet`, D1302) ?? Decimal.ZERO;
2039
+ const vBCFCPUFDest = ctx.opt(input.vBCFCPUFDest, `${path}.vBCFCPUFDest`, D1302);
2040
+ return {
2041
+ grupo: clean({
2042
+ vBCUFDest: ctx.s(ctx.req(input.vBCUFDest, `${path}.vBCUFDest`, D1302), D1302),
2043
+ vBCFCPUFDest: ctx.so(vBCFCPUFDest, D1302),
2044
+ pFCPUFDest: ctx.so(pFCPUFDest, D0302A04),
2045
+ pICMSUFDest: ctx.s(ctx.req(input.pICMSUFDest, `${path}.pICMSUFDest`, D0302A04), D0302A04),
2046
+ pICMSInter: input.pICMSInter,
2047
+ pICMSInterPart: ctx.s(ctx.opt(input.pICMSInterPart, `${path}.pICMSInterPart`, D0302A04) ?? Decimal.HUNDRED, D0302A04),
2048
+ vFCPUFDest: ctx.so(vFCPUFDest, D1302),
2049
+ vICMSUFDest: ctx.s(vICMSUFDest, D1302),
2050
+ vICMSUFRemet: ctx.s(vICMSUFRemet, D1302)
2051
+ }),
2052
+ vFCPUFDest: vFCPUFDest ?? Decimal.ZERO,
2053
+ vICMSUFDest,
2054
+ vICMSUFRemet
2055
+ };
2056
+ }
2057
+
2058
+ // packages/nfe/src/build/build.ts
2059
+ var padrao;
2060
+ function calculadoraPadrao() {
2061
+ padrao ??= ibsCbsCalculator();
2062
+ return padrao;
2063
+ }
2064
+ var NFE_NS3 = "http://www.portalfiscal.inf.br/nfe";
2065
+ var XNOME_HOMOLOGACAO = "NF-E EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL";
2066
+ var XPROD_HOMOLOGACAO_NFCE = "NOTA FISCAL EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL";
2067
+ var MODES = Object.fromEntries(Object.entries(arredondamento_default.familias).map(([k, v]) => [k, v.modo]));
2068
+ var SEM_GTIN = "SEM GTIN";
2069
+ var BRASILIA = -180;
2070
+ function diaBrasilia(d) {
2071
+ return formatDh(d, BRASILIA).slice(0, 10);
2072
+ }
2073
+ function exigenciaRespTec(uf, ambiente, data) {
2074
+ const dia = diaBrasilia(data);
2075
+ const ufs = resp_tec_default.ufs;
2076
+ const regra = Object.hasOwn(ufs, uf) ? ufs[uf] : undefined;
2077
+ const vale = (r, padrao) => {
2078
+ const desde = r?.[ambiente];
2079
+ if (desde !== undefined)
2080
+ return dia >= desde ? "obrigatorio" : padrao;
2081
+ return padrao;
2082
+ };
2083
+ return {
2084
+ infRespTec: vale(regra?.infRespTec, resp_tec_default.padrao.infRespTec),
2085
+ csrt: vale(regra?.csrt, resp_tec_default.padrao.csrt)
2086
+ };
2087
+ }
2088
+ async function hashCsrt(csrt, chave) {
2089
+ const d = await globalThis.crypto.subtle.digest("SHA-1", new TextEncoder().encode(csrt + chave));
2090
+ return base64Encode2(new Uint8Array(d));
2091
+ }
2092
+ function documento(doc, path, issues) {
2093
+ if (doc.CNPJ !== undefined) {
2094
+ const r = parseCnpj3(doc.CNPJ, { path: `${path}.CNPJ` });
2095
+ if (!r.ok)
2096
+ issues.list.push(r.error);
2097
+ return { CNPJ: r.ok ? r.value : doc.CNPJ };
2098
+ }
2099
+ const r = parseCpf(doc.CPF ?? "", { path: `${path}.CPF` });
2100
+ if (!r.ok)
2101
+ issues.list.push(r.error);
2102
+ return { CPF: r.ok ? r.value : doc.CPF ?? "" };
2103
+ }
2104
+ function ie(value, uf, path, issues, allowIsento) {
2105
+ if (value === undefined)
2106
+ return;
2107
+ const r = parseIe(value, uf, { path, allowIsento });
2108
+ if (!r.ok) {
2109
+ issues.list.push(r.error);
2110
+ return value;
2111
+ }
2112
+ return r.value.value;
2113
+ }
2114
+ function endereco(e) {
2115
+ return {
2116
+ xLgr: e.xLgr,
2117
+ nro: e.nro,
2118
+ xCpl: e.xCpl,
2119
+ xBairro: e.xBairro,
2120
+ cMun: e.cMun,
2121
+ xMun: e.xMun,
2122
+ UF: e.UF,
2123
+ CEP: e.CEP === undefined ? undefined : digits(e.CEP),
2124
+ fone: e.fone === undefined ? undefined : digits(e.fone)
2125
+ };
2126
+ }
2127
+ function isExterior(e) {
2128
+ return e !== undefined && "exterior" in e && e.exterior === true;
2129
+ }
2130
+ function gerarChave(parts, cNFInformado, random, issues) {
2131
+ const tentar = (cNF) => {
2132
+ const chave = buildChaveAcesso({ ...parts, cNF });
2133
+ const r = parseChaveAcesso(chave, { emissao: true, path: "chave" });
2134
+ return r.ok ? { chave, ok: true } : { chave, ok: false, issue: r.error };
2135
+ };
2136
+ if (cNFInformado !== undefined) {
2137
+ if (!/^\d{8}$/.test(cNFInformado)) {
2138
+ issues.add("cNF", "campo_invalido", "cNF tem 8 algarismos");
2139
+ return;
2140
+ }
2141
+ const r = tentar(cNFInformado);
2142
+ if (!r.ok && r.issue) {
2143
+ const doCnf = r.issue.code === "chave_cnf_invalido";
2144
+ issues.list.push({
2145
+ ...r.issue,
2146
+ path: doCnf ? "cNF" : r.issue.path,
2147
+ code: "chave_invalida",
2148
+ message: `${r.issue.message} (${r.issue.code})`,
2149
+ origem: doCnf ? "entrada" : "montagem"
2150
+ });
2151
+ }
2152
+ return r.ok ? { chave: r.chave, cNF: cNFInformado } : undefined;
2153
+ }
2154
+ for (let n = 0;n < 32; n++) {
2155
+ const b = random(new Uint8Array(4));
2156
+ const v = ((b[0] ?? 0) * 2 ** 24 + (b[1] ?? 0) * 2 ** 16 + (b[2] ?? 0) * 2 ** 8 + (b[3] ?? 0)) % 1e8;
2157
+ const cNF = String(v).padStart(8, "0");
2158
+ const r = tentar(cNF);
2159
+ if (r.ok)
2160
+ return { chave: r.chave, cNF };
2161
+ if (r.issue && r.issue.code !== "chave_cnf_invalido") {
2162
+ issues.list.push({
2163
+ ...r.issue,
2164
+ code: "chave_invalida",
2165
+ message: `${r.issue.message} (${r.issue.code})`,
2166
+ origem: "montagem"
2167
+ });
2168
+ return;
2169
+ }
2170
+ }
2171
+ issues.montagem("cNF", "chave_invalida", "não foi possível gerar um cNF válido");
2172
+ return;
2173
+ }
2174
+ function referencia(ref, path, issues) {
2175
+ const chave = (c, p) => {
2176
+ const r = parseChaveAcesso(c, { path: p });
2177
+ if (!r.ok)
2178
+ issues.list.push(r.error);
2179
+ return r.ok ? r.value.chave : c;
2180
+ };
2181
+ if ("refNFe" in ref)
2182
+ return { refNFe: chave(ref.refNFe, `${path}.refNFe`) };
2183
+ if ("refNFeSig" in ref) {
2184
+ const c = ref.refNFeSig.replace(/\s/g, "").toUpperCase();
2185
+ if (!/^[0-9]{6}[0-9A-Z]{12}[0-9]{2}55[0-9]{22}$/.test(c) || c.slice(35, 43) !== "00000000") {
2186
+ issues.add(`${path}.refNFeSig`, "chave_invalida", "chave de NF-e (modelo 55) com o código numérico (cNF) zerado");
2187
+ }
2188
+ return { refNFeSig: c };
2189
+ }
2190
+ if ("refCTe" in ref)
2191
+ return { refCTe: chave(ref.refCTe, `${path}.refCTe`) };
2192
+ if ("refNF" in ref)
2193
+ return { refNF: ref.refNF };
2194
+ if ("refECF" in ref)
2195
+ return { refECF: ref.refECF };
2196
+ const nfp = ref.refNFP;
2197
+ if (nfp.mod === "04") {
2198
+ const porUf = produtor_rural_default.refNFP.ufs;
2199
+ const cUfSigla = Object.keys(porUf).find((k) => ufBySigla2(k)?.cUF === nfp.cUF);
2200
+ const vedadaDesde = cUfSigla ? porUf[cUfSigla]?.vedadaDesde ?? "" : produtor_rural_default.refNFP.modelo04.vedadaDesde;
2201
+ if (nfp.AAMM >= vedadaDesde) {
2202
+ issues.add(`${path}.refNFP.AAMM`, "referencia_vedada", `nota de produtor modelo 04 emitida em ${nfp.AAMM}, depois do fim do modelo (${vedadaDesde}; ${produtor_rural_default.refNFP.modelo04.fonte})`);
2203
+ }
2204
+ }
2205
+ const doc = documento(nfp, `${path}.refNFP`, issues);
2206
+ return {
2207
+ refNFP: {
2208
+ cUF: nfp.cUF,
2209
+ AAMM: nfp.AAMM,
2210
+ ...doc,
2211
+ IE: nfp.IE,
2212
+ mod: nfp.mod,
2213
+ serie: String(Number(nfp.serie)),
2214
+ nNF: String(Number(nfp.nNF))
2215
+ }
2216
+ };
2217
+ }
2218
+ function textoXmlValido(texto) {
2219
+ for (const ch of texto) {
2220
+ const c = ch.codePointAt(0) ?? 0;
2221
+ const ok = c === 9 || c === 10 || c === 13 || c >= 32 && c <= 55295 || c >= 57344 && c <= 65533 || c >= 65536 && c <= 1114111;
2222
+ if (!ok)
2223
+ return false;
2224
+ }
2225
+ return true;
2226
+ }
2227
+ function textosForaDoXml(value, path, issues) {
2228
+ if (typeof value === "string") {
2229
+ if (!textoXmlValido(value))
2230
+ issues.montagem(path, "campo_invalido", "texto com caractere não permitido em XML");
2231
+ } else if (Array.isArray(value)) {
2232
+ for (const [n, v] of value.entries())
2233
+ textosForaDoXml(v, `${path}[${n}]`, issues);
2234
+ } else if (typeof value === "object" && value !== null) {
2235
+ for (const [k, v] of Object.entries(value))
2236
+ textosForaDoXml(v, `${path}.${k}`, issues);
2237
+ }
2238
+ }
2239
+ function montarItem(ctx, item, n, normal) {
2240
+ const path = `itens[${n}]`;
2241
+ const p = item.produto;
2242
+ const pp = `${path}.produto`;
2243
+ const qCom = ctx.req(p.qCom, `${pp}.qCom`, D1104V);
2244
+ const vUnCom = ctx.req(p.vUnCom, `${pp}.vUnCom`, D1110V);
2245
+ const vProd = (normal ? ctx.calc : ctx.base).call(ctx, p.vProd, qCom.times(vUnCom), `${pp}.vProd`, D1302, "produto");
2246
+ const uTrib = p.uTrib ?? p.uCom;
2247
+ const qTrib = p.qTrib === undefined ? qCom : ctx.req(p.qTrib, `${pp}.qTrib`, D1104V);
2248
+ let vUnTrib;
2249
+ if (p.vUnTrib !== undefined)
2250
+ vUnTrib = ctx.req(p.vUnTrib, `${pp}.vUnTrib`, D1110V);
2251
+ else if (uTrib === p.uCom && qTrib.eq(qCom))
2252
+ vUnTrib = vUnCom;
2253
+ else if (qTrib.isZero())
2254
+ vUnTrib = Decimal.ZERO;
2255
+ else
2256
+ vUnTrib = vProd.dividedBy(qTrib, 10, ctx.modes.produto);
2257
+ if (normal) {
2258
+ const trib = ctx.round(qTrib.times(vUnTrib), D1302, "produto");
2259
+ if (trib.minus(vProd).abs().gt(TOLERANCIA)) {
2260
+ ctx.issues.add(`${pp}.vUnTrib`, "valor_divergente", `qTrib × vUnTrib (${trib.toFixed(2)}) difere de vProd (${vProd.toFixed(2)}) em mais de ${TOLERANCIA.toString()}`);
2261
+ }
2262
+ }
2263
+ const opt = (v, k) => ctx.opt(v, `${pp}.${k}`, D1302) ?? Decimal.ZERO;
2264
+ const vFrete = opt(p.vFrete, "vFrete");
2265
+ const vSeg = opt(p.vSeg, "vSeg");
2266
+ const vDesc = opt(p.vDesc, "vDesc");
2267
+ const vOutro = opt(p.vOutro, "vOutro");
2268
+ const vOp = vProd.plus(vFrete).plus(vSeg).plus(vOutro).minus(vDesc);
2269
+ const cEAN = p.cEAN ?? SEM_GTIN;
2270
+ const especifico = p.especifico ?? {};
2271
+ const prod = clean({
2272
+ cProd: p.cProd,
2273
+ cEAN,
2274
+ cBarra: p.cBarra,
2275
+ xProd: p.xProd,
2276
+ NCM: digits(p.NCM),
2277
+ NVE: p.NVE,
2278
+ CEST: p.CEST === undefined ? undefined : digits(p.CEST),
2279
+ indEscala: p.indEscala,
2280
+ CNPJFab: p.CNPJFab,
2281
+ cBenef: p.cBenef,
2282
+ gCred: p.gCred,
2283
+ tpCredPresIBSZFM: p.tpCredPresIBSZFM,
2284
+ EXTIPI: p.EXTIPI,
2285
+ CFOP: digits(p.CFOP),
2286
+ uCom: p.uCom,
2287
+ qCom: ctx.s(qCom, D1104V),
2288
+ vUnCom: ctx.s(vUnCom, D1110V),
2289
+ vProd: ctx.s(vProd, D1302),
2290
+ cEANTrib: p.cEANTrib ?? cEAN,
2291
+ cBarraTrib: p.cBarraTrib,
2292
+ uTrib,
2293
+ qTrib: ctx.s(qTrib, D1104V),
2294
+ vUnTrib: ctx.s(vUnTrib, D1110V),
2295
+ vFrete: ctx.so(vFrete, D1302_OPC),
2296
+ vSeg: ctx.so(vSeg, D1302_OPC),
2297
+ vDesc: ctx.so(vDesc, D1302_OPC),
2298
+ vOutro: ctx.so(vOutro, D1302_OPC),
2299
+ indTot: p.indTot ?? "1",
2300
+ indBemMovelUsado: p.indBemMovelUsado,
2301
+ DI: p.DI,
2302
+ detExport: p.detExport,
2303
+ xPed: p.xPed,
2304
+ nItemPed: p.nItemPed,
2305
+ nFCI: p.nFCI,
2306
+ rastro: p.rastro,
2307
+ infProdNFF: p.infProdNFF,
2308
+ infProdEmb: p.infProdEmb,
2309
+ ...especifico
2310
+ });
2311
+ const imp = item.impostos;
2312
+ const ip = `${path}.impostos`;
2313
+ const imposto = {};
2314
+ const z = Decimal.ZERO;
2315
+ const v = {
2316
+ vProd,
2317
+ vFrete,
2318
+ vSeg,
2319
+ vDesc,
2320
+ vOutro,
2321
+ vII: z,
2322
+ vIPI: z,
2323
+ vIPIDevol: z,
2324
+ vPIS: z,
2325
+ vCOFINS: z,
2326
+ vPISST: z,
2327
+ vCOFINSST: z,
2328
+ vFCPUFDest: z,
2329
+ vICMSUFDest: z,
2330
+ vICMSUFRemet: z,
2331
+ vTotTrib: z,
2332
+ vISSQN: z,
2333
+ vBCISS: z
2334
+ };
2335
+ let issqnOpcionais = {};
2336
+ const vTotTrib = ctx.opt(imp.vTotTrib, `${ip}.vTotTrib`, D1302);
2337
+ if (vTotTrib !== undefined) {
2338
+ imposto.vTotTrib = ctx.s(vTotTrib, D1302);
2339
+ v.vTotTrib = vTotTrib;
2340
+ }
2341
+ if (imp.icms !== undefined && imp.issqn !== undefined) {
2342
+ ctx.issues.add(ip, "combinacao_invalida", "o item tem ICMS ou ISSQN, nunca os dois");
2343
+ }
2344
+ if (imp.ipi !== undefined) {
2345
+ const r = buildIpi(ctx, imp.ipi, vOp, `${ip}.ipi`);
2346
+ imposto.IPI = r.grupo;
2347
+ v.vIPI = r.vIPI;
2348
+ }
2349
+ let icms = zeroIcmsTotais();
2350
+ if (imp.icms !== undefined) {
2351
+ const r = buildIcms(ctx, imp.icms, { vOp, vIPI: v.vIPI }, `${ip}.icms`);
2352
+ imposto.ICMS = r.grupo;
2353
+ icms = r.totais;
2354
+ } else if (imp.issqn === undefined && imp.ibsCbs === undefined) {
2355
+ ctx.issues.add(`${ip}.icms`, "campo_obrigatorio", "o item precisa de ICMS (ou ISSQN, na NF-e conjugada)");
2356
+ }
2357
+ if (imp.ii !== undefined) {
2358
+ const r = buildIi(ctx, imp.ii, `${ip}.ii`);
2359
+ imposto.II = r.grupo;
2360
+ v.vII = r.vII;
2361
+ }
2362
+ if (imp.issqn !== undefined) {
2363
+ const r = buildIssqn(ctx, imp.issqn, `${ip}.issqn`);
2364
+ imposto.ISSQN = r.grupo;
2365
+ v.vISSQN = r.vISSQN;
2366
+ v.vBCISS = r.vBC;
2367
+ issqnOpcionais = r.opcionais;
2368
+ }
2369
+ if (imp.pis !== undefined) {
2370
+ const r = buildPisCofins(ctx, imp.pis, "PIS", `${ip}.pis`);
2371
+ imposto.PIS = r.grupo;
2372
+ v.vPIS = r.valor;
2373
+ }
2374
+ if (imp.pisSt !== undefined) {
2375
+ const r = buildPisCofinsSt(ctx, imp.pisSt, "PIS", `${ip}.pisSt`);
2376
+ imposto.PISST = r.grupo;
2377
+ if (r.soma)
2378
+ v.vPISST = r.valor;
2379
+ }
2380
+ if (imp.cofins !== undefined) {
2381
+ const r = buildPisCofins(ctx, imp.cofins, "COFINS", `${ip}.cofins`);
2382
+ imposto.COFINS = r.grupo;
2383
+ v.vCOFINS = r.valor;
2384
+ }
2385
+ if (imp.cofinsSt !== undefined) {
2386
+ const r = buildPisCofinsSt(ctx, imp.cofinsSt, "COFINS", `${ip}.cofinsSt`);
2387
+ imposto.COFINSST = r.grupo;
2388
+ if (r.soma)
2389
+ v.vCOFINSST = r.valor;
2390
+ }
2391
+ if (imp.icmsUfDest !== undefined) {
2392
+ const r = buildIcmsUfDest(ctx, imp.icmsUfDest, `${ip}.icmsUfDest`);
2393
+ imposto.ICMSUFDest = r.grupo;
2394
+ v.vFCPUFDest = r.vFCPUFDest;
2395
+ v.vICMSUFDest = r.vICMSUFDest;
2396
+ v.vICMSUFRemet = r.vICMSUFRemet;
2397
+ }
2398
+ if (imp.is !== undefined)
2399
+ imposto.IS = imp.is;
2400
+ if (imp.ibsCbs?.grupo !== undefined)
2401
+ imposto.IBSCBS = imp.ibsCbs.grupo;
2402
+ const det = {
2403
+ nItem: String(n + 1),
2404
+ prod,
2405
+ imposto
2406
+ };
2407
+ if (item.impostoDevol !== undefined) {
2408
+ const pDevol = ctx.req(item.impostoDevol.pDevol, `${path}.impostoDevol.pDevol`, D0302);
2409
+ const vIPIDevol = ctx.req(item.impostoDevol.vIPIDevol, `${path}.impostoDevol.vIPIDevol`, D1302);
2410
+ det.impostoDevol = { pDevol: ctx.s(pDevol, D0302), IPI: { vIPIDevol: ctx.s(vIPIDevol, D1302) } };
2411
+ v.vIPIDevol = vIPIDevol;
2412
+ }
2413
+ if (item.infAdProd !== undefined)
2414
+ det.infAdProd = item.infAdProd;
2415
+ if (item.obsItem !== undefined)
2416
+ det.obsItem = item.obsItem;
2417
+ if (item.DFeReferenciado !== undefined) {
2418
+ const r = parseChaveAcesso(item.DFeReferenciado.chaveAcesso, { path: `${path}.DFeReferenciado.chaveAcesso` });
2419
+ if (!r.ok)
2420
+ ctx.issues.list.push(r.error);
2421
+ det.DFeReferenciado = clean({
2422
+ chaveAcesso: r.ok ? r.value.chave : item.DFeReferenciado.chaveAcesso,
2423
+ nItem: item.DFeReferenciado.nItem === undefined ? undefined : String(item.DFeReferenciado.nItem)
2424
+ });
2425
+ }
2426
+ return {
2427
+ det,
2428
+ icms,
2429
+ indTot: (p.indTot ?? "1") === "1",
2430
+ issqn: imp.issqn !== undefined,
2431
+ faturamentoDireto: especifico.veicProd?.tpOp === "2",
2432
+ v,
2433
+ temUfDest: imp.icmsUfDest !== undefined,
2434
+ temTotTrib: vTotTrib !== undefined,
2435
+ issqnOpcionais
2436
+ };
2437
+ }
2438
+ function composicao(m, incluirProd) {
2439
+ const v = m.v;
2440
+ let total = (incluirProd ? v.vProd : Decimal.ZERO).minus(v.vDesc).minus(m.icms.vICMSDesonDeduz).plus(v.vFrete).plus(v.vSeg).plus(v.vOutro).plus(v.vII).plus(v.vIPI).plus(v.vPISST).plus(v.vCOFINSST);
2441
+ if (!m.faturamentoDireto) {
2442
+ total = total.plus(m.icms.vST).plus(m.icms.vICMSMonoReten).plus(m.icms.vFCPST).plus(v.vIPIDevol);
2443
+ }
2444
+ return total;
2445
+ }
2446
+ async function buildNfe(input, options) {
2447
+ const issues = new Issues;
2448
+ const finNFeIn = input.finNFe ?? "1";
2449
+ const mod = input.modelo ?? "55";
2450
+ if (mod !== "55" && mod !== "65") {
2451
+ issues.add("modelo", "modelo_nao_suportado", `modelo ${String(mod)}: o builder monta NF-e (55) e NFC-e (65)`);
2452
+ return { ok: false, issues: issues.classificadas };
2453
+ }
2454
+ const nfce = mod === "65";
2455
+ const indPres = input.indPres ?? (nfce ? "1" : finNFeIn === "2" || finNFeIn === "3" ? "0" : "9");
2456
+ const indFinal = input.indFinal ?? (nfce || input.destinatario?.indIEDest === "9" ? "1" : "0");
2457
+ const ctx = new Ctx(issues, { ...MODES, ...options.arredondamento }, finNFeIn !== "2" && finNFeIn !== "3");
2458
+ const pRedutorGov = input.gCompraGov && ctx.req(input.gCompraGov.pRedutor, "gCompraGov.pRedutor", D0302A04);
2459
+ const emitUf = input.emitente.endereco.UF;
2460
+ if (!isUf2(emitUf)) {
2461
+ issues.add("emitente.endereco.UF", "campo_invalido", "UF do emitente inválida");
2462
+ return { ok: false, issues: issues.classificadas };
2463
+ }
2464
+ const cUF = ufBySigla2(emitUf)?.cUF ?? "";
2465
+ const offset = options.offsetMinutes ?? offsetDaUf(emitUf);
2466
+ const agora = options.time.emissao.now();
2467
+ const fatoGerador = options.time.fatoGerador.now();
2468
+ const dhEmi = formatDh(agora, offset);
2469
+ const aamm = dhEmi.slice(2, 4) + dhEmi.slice(5, 7);
2470
+ const tpAmb = tpAmbOf2(options.ambiente);
2471
+ const pl = escolherPl(options.ambiente, fixedClock2(agora));
2472
+ const e = input.emitente;
2473
+ const emitDoc = documento(e, "emitente", issues);
2474
+ const serie = Number(input.serie);
2475
+ const nNF = Number(input.nNF);
2476
+ if (!Number.isInteger(serie) || serie < 0 || serie > 999)
2477
+ issues.add("serie", "serie_invalida", "série de 0 a 999");
2478
+ if (!Number.isInteger(nNF) || nNF < 1 || nNF > 999999999)
2479
+ issues.add("nNF", "campo_invalido", "nNF de 1 a 999999999");
2480
+ const [cpfIni, cpfFim] = produtor_rural_default.series.cpf;
2481
+ const [cnpjIni, cnpjFim] = produtor_rural_default.series.cnpj;
2482
+ if ("CPF" in emitDoc && (serie < cpfIni || serie > cpfFim)) {
2483
+ issues.add("serie", "serie_invalida", `emitente pessoa física usa as séries ${cpfIni} a ${cpfFim} (${produtor_rural_default.series.fonte})`);
2484
+ } else if ("CNPJ" in emitDoc && Number.isInteger(serie) && serie >= 0 && (serie < cnpjIni || serie > cnpjFim)) {
2485
+ issues.add("serie", "serie_invalida", `emitente CNPJ usa as séries ${cnpjIni} a ${cnpjFim} (${produtor_rural_default.series.fonteCnpj})`);
2486
+ }
2487
+ const emit = clean({
2488
+ ...emitDoc,
2489
+ xNome: e.xNome,
2490
+ xFant: e.xFant,
2491
+ enderEmit: clean({ ...endereco(e.endereco), cPais: "1058", xPais: "BRASIL" }),
2492
+ IE: ie(e.IE, emitUf, "emitente.IE", issues, true),
2493
+ IEST: e.IEST,
2494
+ IM: e.IM,
2495
+ CNAE: e.CNAE,
2496
+ CRT: e.CRT,
2497
+ ISUFEmit: e.ISUFEmit
2498
+ });
2499
+ const d = input.destinatario;
2500
+ let dest;
2501
+ let destUf;
2502
+ if (d === undefined) {
2503
+ if (!nfce)
2504
+ issues.add("destinatario", "campo_obrigatorio", "a NF-e exige o destinatário (E01-10, rejeição 719)");
2505
+ } else {
2506
+ const docDest = "idEstrangeiro" in d && d.idEstrangeiro !== undefined ? { idEstrangeiro: d.idEstrangeiro } : documento(d, "destinatario", issues);
2507
+ let enderDest;
2508
+ if (isExterior(d.endereco)) {
2509
+ destUf = "EX";
2510
+ enderDest = clean({
2511
+ xLgr: d.endereco.xLgr,
2512
+ nro: d.endereco.nro,
2513
+ xCpl: d.endereco.xCpl,
2514
+ xBairro: d.endereco.xBairro,
2515
+ cMun: "9999999",
2516
+ xMun: "EXTERIOR",
2517
+ UF: "EX",
2518
+ cPais: d.endereco.cPais,
2519
+ xPais: d.endereco.xPais,
2520
+ fone: d.endereco.fone === undefined ? undefined : digits(d.endereco.fone)
2521
+ });
2522
+ } else if (d.endereco !== undefined) {
2523
+ destUf = d.endereco.UF;
2524
+ enderDest = clean({ ...endereco(d.endereco), cPais: "1058", xPais: "BRASIL" });
2525
+ }
2526
+ const destIe = d.IE !== undefined && destUf !== undefined && destUf !== "EX" ? ie(d.IE, destUf, "destinatario.IE", issues, false) : d.IE;
2527
+ dest = clean({
2528
+ ...docDest,
2529
+ xNome: options.ambiente === "homologacao" ? XNOME_HOMOLOGACAO : d.xNome,
2530
+ enderDest,
2531
+ indIEDest: d.indIEDest,
2532
+ IE: destIe,
2533
+ ISUF: d.ISUF,
2534
+ IM: d.IM,
2535
+ email: d.email
2536
+ });
2537
+ }
2538
+ const cont = input.contingencia;
2539
+ const tpEmis = cont?.tpEmis ?? "1";
2540
+ if (cont !== undefined) {
2541
+ if (cont.xJust.length < 15 || cont.xJust.length > 256) {
2542
+ issues.add("contingencia.xJust", "contingencia_invalida", "justificativa da contingência com 15 a 256 caracteres");
2543
+ }
2544
+ if (cont.dhCont.getTime() > agora.getTime()) {
2545
+ issues.add("contingencia.dhCont", "contingencia_invalida", "entrada em contingência posterior à emissão");
2546
+ }
2547
+ if (!nfce && tpEmis === "9") {
2548
+ issues.add("contingencia.tpEmis", "contingencia_invalida", "contingência off-line (tpEmis 9) é só da NFC-e (B22-10, rejeição 711)");
2549
+ }
2550
+ if (nfce && (tpEmis === "6" || tpEmis === "7")) {
2551
+ issues.add("contingencia.tpEmis", "contingencia_invalida", "a NFC-e não é autorizada pela SVC; a contingência dela é off-line, tpEmis 9 (B22-70, rejeição 783)");
2552
+ }
2553
+ }
2554
+ const idDest = input.idDest ?? (nfce ? "1" : destUf === "EX" ? "3" : destUf !== undefined && destUf !== emitUf ? "2" : "1");
2555
+ const tpImp = input.tpImp ?? (nfce ? "4" : "1");
2556
+ conferirDestinatario(input, {
2557
+ mod,
2558
+ tpNF: input.tpNF,
2559
+ idDest,
2560
+ idDestInformado: input.idDest !== undefined,
2561
+ indFinal,
2562
+ producao: options.ambiente === "producao"
2563
+ }, issues);
2564
+ if (nfce) {
2565
+ conferirNfce(input, {
2566
+ tpNF: input.tpNF,
2567
+ idDest,
2568
+ tpImp,
2569
+ finNFe: finNFeIn,
2570
+ indFinal,
2571
+ indPres
2572
+ }, issues);
2573
+ } else if (tpImp === "4" || tpImp === "5") {
2574
+ issues.add("tpImp", "campo_invalido", "tpImp 4 e 5 (DANFC-e) são da NFC-e (B21-20, rejeição 710)");
2575
+ }
2576
+ const qr = options.qrCode ?? { versao: "3" };
2577
+ if (nfce && qr.versao === "2") {
2578
+ if (!/^\d{1,6}$/.test(qr.idCSC) || Number(qr.idCSC) === 0) {
2579
+ issues.montagem("qrCode.idCSC", "qrcode_invalido", "idCSC tem de 1 a 6 algarismos, diferente de zero (Manual do DANFE NFC-e 6.0, 4.6)");
2580
+ }
2581
+ if (qr.CSC.length < 16 || qr.CSC.length > 36) {
2582
+ issues.montagem("qrCode.CSC", "qrcode_invalido", "o CSC tem de 16 a 36 caracteres (Manual do DANFE NFC-e 6.0, 4.6)");
2583
+ }
2584
+ if ("CPF" in emitDoc) {
2585
+ issues.montagem("qrCode.versao", "qrcode_invalido", "emitente pessoa física usa o QR Code versão 3 (NT 2025.001, ZX02-222, rejeição 444)");
2586
+ }
2587
+ }
2588
+ const random = options.random ?? ((b) => globalThis.crypto.getRandomValues(b));
2589
+ const emitente14 = "CNPJ" in emitDoc ? emitDoc.CNPJ : emitDoc.CPF;
2590
+ const gerada = issues.empty ? gerarChave({ cUF, aamm, emitente: emitente14, mod, serie: String(serie), nNF: String(nNF), tpEmis }, input.cNF, random, issues) : undefined;
2591
+ const chave = gerada?.chave ?? "0".repeat(44);
2592
+ const cNF = gerada?.cNF ?? "00000000";
2593
+ const cDV = chave.slice(43);
2594
+ if (input.itens.length === 0 || input.itens.length > 990) {
2595
+ issues.add("itens", "itens_limite", "a NF-e tem de 1 a 990 itens");
2596
+ }
2597
+ const itens = input.itens.map((it, n) => montarItem(ctx, it, n, finNFeIn === "1"));
2598
+ const primeiro = itens[0];
2599
+ if (nfce && options.ambiente === "homologacao" && primeiro !== undefined) {
2600
+ primeiro.det.prod.xProd = XPROD_HOMOLOGACAO_NFCE;
2601
+ }
2602
+ const classificados = input.itens.map((it, n) => ({ it, n })).filter(({ it }) => it.impostos.ibsCbs?.classificacao !== undefined);
2603
+ if (classificados.length > 0) {
2604
+ const calculadora = options.ibsCbs ?? calculadoraPadrao();
2605
+ const reqs = classificados.map(({ it, n }) => {
2606
+ const c = it.impostos.ibsCbs?.classificacao;
2607
+ const m = itens[n];
2608
+ const vBC = ctx.opt(c.vBC, `itens[${n}].impostos.ibsCbs.classificacao.vBC`, D1302);
2609
+ const qTrib = Decimal.of(m.det.prod.qTrib);
2610
+ return {
2611
+ nItem: n + 1,
2612
+ CST: c.CST,
2613
+ cClassTrib: c.cClassTrib,
2614
+ ...c.indDoacao ? { indDoacao: c.indDoacao } : {},
2615
+ ...c.cCredPres ? { cCredPres: c.cCredPres } : {},
2616
+ ...c.gTribRegular ? { gTribRegular: c.gTribRegular } : {},
2617
+ ...vBC ? { vBC } : {},
2618
+ NCM: m.det.prod.NCM,
2619
+ CFOP: m.det.prod.CFOP,
2620
+ uTrib: m.det.prod.uTrib,
2621
+ qTrib,
2622
+ vProd: m.v.vProd,
2623
+ vDesc: m.v.vDesc,
2624
+ vFrete: m.v.vFrete,
2625
+ vSeg: m.v.vSeg,
2626
+ vOutro: m.v.vOutro,
2627
+ vICMS: m.icms.vICMS,
2628
+ vICMSST: m.icms.vST,
2629
+ vFCP: m.icms.vFCP,
2630
+ vFCPST: m.icms.vFCPST,
2631
+ vIPI: m.v.vIPI,
2632
+ vPIS: m.v.vPIS,
2633
+ vCOFINS: m.v.vCOFINS,
2634
+ vII: m.v.vII,
2635
+ vISSQN: m.v.vISSQN,
2636
+ vICMSUFDest: m.v.vICMSUFDest,
2637
+ vFCPUFDest: m.v.vFCPUFDest
2638
+ };
2639
+ });
2640
+ const destino = input.entrega !== undefined ? { UF: input.entrega.UF, cMun: input.entrega.cMun } : d?.endereco !== undefined ? isExterior(d.endereco) ? { UF: "EX", cMun: "9999999" } : { UF: d.endereco.UF, cMun: d.endereco.cMun } : undefined;
2641
+ const compra = input.gCompraGov;
2642
+ const resp = await calculadora.calcular({
2643
+ nota: {
2644
+ fatoGerador,
2645
+ emissao: agora,
2646
+ ambiente: options.ambiente,
2647
+ mod,
2648
+ tpNF: input.tpNF,
2649
+ finNFe: finNFeIn,
2650
+ ...input.tpNFDebito ? { tpNFDebito: input.tpNFDebito } : {},
2651
+ ...input.tpNFCredito ? { tpNFCredito: input.tpNFCredito } : {},
2652
+ indFinal,
2653
+ indPres,
2654
+ emitente: { UF: emitUf, cMun: e.endereco.cMun, CRT: e.CRT },
2655
+ ...destino ? { destino } : {},
2656
+ ...input.cMunFGIBS ? { cMunFGIBS: input.cMunFGIBS } : {},
2657
+ ...compra && pRedutorGov ? {
2658
+ compraGov: {
2659
+ tpEnteGov: compra.tpEnteGov,
2660
+ pRedutor: pRedutorGov,
2661
+ tpOperGov: compra.tpOperGov
2662
+ }
2663
+ } : {}
2664
+ },
2665
+ itens: reqs
2666
+ });
2667
+ issues.addAll(resp.issues ?? [], "montagem");
2668
+ for (const { n } of classificados) {
2669
+ const g = resp.itens.find((x) => x.nItem === n + 1);
2670
+ if (g === undefined) {
2671
+ issues.montagem(`itens[${n}].impostos.ibsCbs`, "ibscbs_calculo", "a calculadora não devolveu o grupo IBSCBS do item");
2672
+ continue;
2673
+ }
2674
+ itens[n].det.imposto.IBSCBS = g.IBSCBS;
2675
+ }
2676
+ }
2677
+ itens.forEach((m, n) => {
2678
+ const imp = m.det.imposto;
2679
+ const ib = `itens[${n}].impostos.ibsCbs`;
2680
+ const is = `itens[${n}].impostos.is`;
2681
+ const ibsDaCalculadora = input.itens[n]?.impostos.ibsCbs?.grupo === undefined;
2682
+ const antes = issues.list.length;
2683
+ decimaisInvalidos(imp.IBSCBS, ib, issues);
2684
+ if (ibsDaCalculadora)
2685
+ issues.reclassificarDesde(antes, "montagem");
2686
+ decimaisInvalidos(imp.IS, is, issues);
2687
+ if (issues.list.length === antes) {
2688
+ grupoInvalido(TTribNFeCt, "IBSCBS", imp.IBSCBS, ib, issues);
2689
+ if (ibsDaCalculadora)
2690
+ issues.reclassificarDesde(antes, "montagem");
2691
+ grupoInvalido(TISCt, "IS", imp.IS, is, issues);
2692
+ }
2693
+ });
2694
+ if (!issues.empty)
2695
+ return { ok: false, issues: issues.classificadas };
2696
+ const gruposIbsCbs = itens.map((m) => m.det.imposto.IBSCBS).filter((g) => g !== undefined);
2697
+ const somaTributosNoItem = diaBrasilia(fatoGerador) >= reforma_default.vItemSomaTributosDesde;
2698
+ let vNFTot = Decimal.ZERO;
2699
+ const temReforma = gruposIbsCbs.length > 0 || itens.some((m) => m.det.imposto.IS !== undefined);
2700
+ if (temReforma) {
2701
+ for (const m of itens) {
2702
+ let vItem = composicao(m, m.indTot);
2703
+ const g = m.det.imposto.IBSCBS;
2704
+ if (somaTributosNoItem) {
2705
+ const is = m.det.imposto.IS?.vIS;
2706
+ if (is !== undefined)
2707
+ vItem = vItem.plus(Decimal.of(is));
2708
+ }
2709
+ if (g !== undefined && somaTributosNoItem) {
2710
+ const t = ibsCbsDoItem(g);
2711
+ vItem = vItem.plus(t.vIBS).plus(t.vCBS);
2712
+ if (!m.faturamentoDireto)
2713
+ vItem = vItem.plus(t.vTotIBSMonoItem).plus(t.vTotCBSMonoItem);
2714
+ }
2715
+ m.det.vItem = ctx.s(vItem, D1302);
2716
+ vNFTot = vNFTot.plus(vItem);
2717
+ }
2718
+ }
2719
+ const soma = (f, filtro = () => true) => itens.filter(filtro).reduce((acc, m) => acc.plus(f(m)), Decimal.ZERO);
2720
+ const icmsItens = (m) => !m.issqn;
2721
+ const icmsSoma = (k) => soma((m) => m.icms[k]);
2722
+ const vProdTot = soma((m) => m.v.vProd, (m) => m.indTot && !m.issqn);
2723
+ const vServ = soma((m) => m.v.vProd, (m) => m.indTot && m.issqn);
2724
+ const vNF = itens.reduce((acc, m) => acc.plus(composicao(m, m.indTot && !m.issqn)), Decimal.ZERO).plus(vServ);
2725
+ const S = (x) => ctx.s(x, D1302);
2726
+ const mono = itens.some((m) => m.icms.mono);
2727
+ const ufDest = itens.some((m) => m.temUfDest);
2728
+ const ICMSTot = clean({
2729
+ vBC: S(icmsSoma("vBC")),
2730
+ vICMS: S(icmsSoma("vICMS")),
2731
+ vICMSDeson: S(icmsSoma("vICMSDeson")),
2732
+ vFCPUFDest: ufDest ? S(soma((m) => m.v.vFCPUFDest)) : undefined,
2733
+ vICMSUFDest: ufDest ? S(soma((m) => m.v.vICMSUFDest)) : undefined,
2734
+ vICMSUFRemet: ufDest ? S(soma((m) => m.v.vICMSUFRemet)) : undefined,
2735
+ vFCP: S(icmsSoma("vFCP")),
2736
+ vBCST: S(icmsSoma("vBCST")),
2737
+ vST: S(icmsSoma("vST")),
2738
+ vFCPST: S(icmsSoma("vFCPST")),
2739
+ vFCPSTRet: S(icmsSoma("vFCPSTRet")),
2740
+ qBCMono: mono ? S(ctx.round(icmsSoma("qBCMono"), D1302, "icms")) : undefined,
2741
+ vICMSMono: mono ? S(icmsSoma("vICMSMono")) : undefined,
2742
+ qBCMonoReten: mono ? S(ctx.round(icmsSoma("qBCMonoReten"), D1302, "icms")) : undefined,
2743
+ vICMSMonoReten: mono ? S(icmsSoma("vICMSMonoReten")) : undefined,
2744
+ qBCMonoRet: mono ? S(ctx.round(icmsSoma("qBCMonoRet"), D1302, "icms")) : undefined,
2745
+ vICMSMonoRet: mono ? S(icmsSoma("vICMSMonoRet")) : undefined,
2746
+ vProd: S(vProdTot),
2747
+ vFrete: S(soma((m) => m.v.vFrete)),
2748
+ vSeg: S(soma((m) => m.v.vSeg)),
2749
+ vDesc: S(soma((m) => m.v.vDesc)),
2750
+ vII: S(soma((m) => m.v.vII)),
2751
+ vIPI: S(soma((m) => m.v.vIPI)),
2752
+ vIPIDevol: S(soma((m) => m.v.vIPIDevol)),
2753
+ vPIS: S(soma((m) => m.v.vPIS, icmsItens)),
2754
+ vCOFINS: S(soma((m) => m.v.vCOFINS, icmsItens)),
2755
+ vOutro: S(soma((m) => m.v.vOutro)),
2756
+ vNF: S(vNF),
2757
+ vTotTrib: itens.some((m) => m.temTotTrib) ? S(soma((m) => m.v.vTotTrib)) : undefined
2758
+ });
2759
+ const total = { ICMSTot };
2760
+ if (itens.some((m) => m.issqn)) {
2761
+ const iss = itens.filter((m) => m.issqn);
2762
+ const so = (x) => ctx.so(x, D1302_OPC);
2763
+ const opc = (k) => so(iss.reduce((a, m) => a.plus(m.issqnOpcionais[k] ?? Decimal.ZERO), Decimal.ZERO));
2764
+ total.ISSQNtot = clean({
2765
+ vServ: so(vServ),
2766
+ vBC: so(soma((m) => m.v.vBCISS, (m) => m.issqn)),
2767
+ vISS: so(soma((m) => m.v.vISSQN, (m) => m.issqn)),
2768
+ vPIS: so(soma((m) => m.v.vPIS, (m) => m.issqn)),
2769
+ vCOFINS: so(soma((m) => m.v.vCOFINS, (m) => m.issqn)),
2770
+ dCompet: dhEmi.slice(0, 10),
2771
+ vDeducao: opc("vDeducao"),
2772
+ vOutro: opc("vOutro"),
2773
+ vDescIncond: opc("vDescIncond"),
2774
+ vDescCond: opc("vDescCond"),
2775
+ vISSRet: opc("vISSRet")
2776
+ });
2777
+ }
2778
+ const comIs = itens.filter((m) => m.det.imposto.IS !== undefined);
2779
+ if (comIs.length > 0) {
2780
+ total.ISTot = {
2781
+ vIS: S(comIs.reduce((a, m) => a.plus(Decimal.of(m.det.imposto.IS.vIS ?? "0")), Decimal.ZERO))
2782
+ };
2783
+ }
2784
+ if (gruposIbsCbs.length > 0)
2785
+ total.IBSCBSTot = totalIbsCbs(gruposIbsCbs);
2786
+ if (temReforma)
2787
+ total.vNFTot = S(vNFTot);
2788
+ const finNFe = finNFeIn;
2789
+ const ide = clean({
2790
+ cUF,
2791
+ cNF,
2792
+ natOp: input.natOp,
2793
+ mod,
2794
+ serie: String(serie),
2795
+ nNF: String(nNF),
2796
+ dhEmi,
2797
+ dhSaiEnt: input.dhSaiEnt === undefined ? undefined : formatDh(input.dhSaiEnt, offset),
2798
+ dPrevEntrega: input.dPrevEntrega,
2799
+ tpNF: input.tpNF,
2800
+ idDest,
2801
+ cMunFG: input.cMunFG ?? e.endereco.cMun,
2802
+ cMunFGIBS: input.cMunFGIBS,
2803
+ tpImp,
2804
+ tpEmis,
2805
+ cDV,
2806
+ tpAmb,
2807
+ finNFe,
2808
+ tpNFDebito: input.tpNFDebito,
2809
+ tpNFCredito: input.tpNFCredito,
2810
+ indFinal,
2811
+ indPres,
2812
+ indIntermed: input.indIntermed ?? (["2", "3", "4", "9"].includes(indPres) ? "0" : undefined),
2813
+ procEmi: "0",
2814
+ verProc: options.verProc ?? formatarVerProc("sinete", VERSAO_PACOTE),
2815
+ dhCont: cont === undefined ? undefined : formatDh(cont.dhCont, offset),
2816
+ xJust: cont?.xJust,
2817
+ NFref: input.referenciadas?.map((r, n) => referencia(r, `referenciadas[${n}]`, issues)),
2818
+ gCompraGov: input.gCompraGov === undefined ? undefined : clean({
2819
+ tpEnteGov: input.gCompraGov.tpEnteGov,
2820
+ pRedutor: ctx.s(pRedutorGov ?? Decimal.ZERO, D0302A04),
2821
+ tpOperGov: input.gCompraGov.tpOperGov,
2822
+ refDFeAnt: input.gCompraGov.refDFeAnt
2823
+ }),
2824
+ gPagAntecipado: input.gPagAntecipado === undefined ? undefined : { refNFe: [...input.gPagAntecipado] }
2825
+ });
2826
+ const local = (l, path) => l === undefined ? undefined : clean({
2827
+ ...documento(l, path, issues),
2828
+ xNome: l.xNome,
2829
+ ...endereco(l),
2830
+ cPais: "1058",
2831
+ xPais: "BRASIL",
2832
+ email: l.email,
2833
+ IE: l.IE
2834
+ });
2835
+ if ((input.autXML?.length ?? 0) > 10)
2836
+ issues.add("autXML", "campo_invalido", "no máximo 10 autorizados");
2837
+ const autXML = input.autXML?.map((a, n) => documento(a, `autXML[${n}]`, issues));
2838
+ const tr = input.transporte;
2839
+ const transp = { modFrete: tr?.modFrete ?? "9" };
2840
+ if (tr?.transportador !== undefined) {
2841
+ const t = tr.transportador;
2842
+ const docT = t.CNPJ !== undefined || t.CPF !== undefined ? documento(t, "transporte.transportador", issues) : {};
2843
+ transp.transporta = clean({ ...docT, xNome: t.xNome, IE: t.IE, xEnder: t.xEnder, xMun: t.xMun, UF: t.UF });
2844
+ }
2845
+ if (tr?.retTransp !== undefined) {
2846
+ const r = tr.retTransp;
2847
+ const vBCRet = ctx.req(r.vBCRet, "transporte.retTransp.vBCRet", D1302);
2848
+ const pICMSRet = ctx.req(r.pICMSRet, "transporte.retTransp.pICMSRet", D0302A04);
2849
+ const vICMSRet = ctx.calc(r.vICMSRet, vBCRet.percent(pICMSRet), "transporte.retTransp.vICMSRet", D1302, "icms");
2850
+ transp.retTransp = {
2851
+ vServ: S(ctx.req(r.vServ, "transporte.retTransp.vServ", D1302)),
2852
+ vBCRet: S(vBCRet),
2853
+ pICMSRet: ctx.s(pICMSRet, D0302A04),
2854
+ vICMSRet: S(vICMSRet),
2855
+ CFOP: r.CFOP,
2856
+ cMunFG: r.cMunFG
2857
+ };
2858
+ }
2859
+ if (tr?.veicTransp !== undefined)
2860
+ transp.veicTransp = tr.veicTransp;
2861
+ if (tr?.reboque !== undefined)
2862
+ transp.reboque = tr.reboque;
2863
+ if (tr?.vagao !== undefined)
2864
+ transp.vagao = tr.vagao;
2865
+ if (tr?.balsa !== undefined)
2866
+ transp.balsa = tr.balsa;
2867
+ if (tr?.volumes !== undefined) {
2868
+ transp.vol = tr.volumes.map((vol, n) => clean({
2869
+ qVol: vol.qVol === undefined ? undefined : String(vol.qVol),
2870
+ esp: vol.esp,
2871
+ marca: vol.marca,
2872
+ nVol: vol.nVol,
2873
+ pesoL: ctx.so(ctx.opt(vol.pesoL, `transporte.volumes[${n}].pesoL`, D1203), D1203),
2874
+ pesoB: ctx.so(ctx.opt(vol.pesoB, `transporte.volumes[${n}].pesoB`, D1203), D1203),
2875
+ lacres: vol.lacres?.map((nLacre) => ({ nLacre }))
2876
+ }));
2877
+ }
2878
+ let cobr;
2879
+ if (input.cobranca !== undefined) {
2880
+ const c = input.cobranca;
2881
+ cobr = {};
2882
+ if (c.fatura !== undefined) {
2883
+ const f = c.fatura;
2884
+ const vOrig = ctx.opt(f.vOrig, "cobranca.fatura.vOrig", D1302);
2885
+ const vDescF = ctx.opt(f.vDesc, "cobranca.fatura.vDesc", D1302);
2886
+ const vLiq = vOrig === undefined ? ctx.opt(f.vLiq, "cobranca.fatura.vLiq", D1302) : ctx.calc(f.vLiq, vOrig.minus(vDescF ?? Decimal.ZERO), "cobranca.fatura.vLiq", D1302, "produto");
2887
+ cobr.fat = clean({
2888
+ nFat: f.nFat,
2889
+ vOrig: ctx.so(vOrig, D1302),
2890
+ vDesc: ctx.so(vDescF, D1302),
2891
+ vLiq: ctx.so(vLiq, D1302)
2892
+ });
2893
+ }
2894
+ if (c.duplicatas !== undefined) {
2895
+ if (c.duplicatas.length > 120)
2896
+ issues.add("cobranca.duplicatas", "campo_invalido", "no máximo 120 duplicatas");
2897
+ cobr.dup = c.duplicatas.map((dup, n) => clean({
2898
+ nDup: dup.nDup ?? String(n + 1).padStart(3, "0"),
2899
+ dVenc: dup.dVenc,
2900
+ vDup: ctx.s(ctx.req(dup.vDup, `cobranca.duplicatas[${n}].vDup`, D1302_OPC), D1302_OPC)
2901
+ }));
2902
+ }
2903
+ }
2904
+ const pagIn = input.pagamento ?? { detPag: [{ tPag: "90", vPag: "0" }] };
2905
+ const igualTotal = options.pagamentoIgualTotal === true;
2906
+ if (igualTotal) {
2907
+ const unico = input.pagamento?.detPag.length === 1 ? input.pagamento.detPag[0] : undefined;
2908
+ if (unico === undefined) {
2909
+ issues.add("pagamento.detPag", "pagamento_igual_total", "pagamentoIgualTotal pede exatamente um detPag");
2910
+ } else if (unico.tPag === "90") {
2911
+ issues.add("pagamento.detPag[0].tPag", "pagamento_igual_total", "tPag 90 (sem pagamento) não recebe o total");
2912
+ }
2913
+ }
2914
+ const pag = clean({
2915
+ detPag: pagIn.detPag.map((p, n) => clean({
2916
+ indPag: p.indPag,
2917
+ tPag: p.tPag,
2918
+ xPag: p.xPag,
2919
+ vPag: igualTotal ? S(vNF) : S(ctx.req(p.vPag, `pagamento.detPag[${n}].vPag`, D1302)),
2920
+ dPag: p.dPag,
2921
+ CNPJPag: p.CNPJPag,
2922
+ UFPag: p.UFPag,
2923
+ card: p.card
2924
+ })),
2925
+ vTroco: ctx.so(ctx.opt(pagIn.vTroco, "pagamento.vTroco", D1302), D1302)
2926
+ });
2927
+ if (nfce && input.pagamento !== undefined && input.pagamento.detPag.length > 0 && issues.empty) {
2928
+ pagamentoNfce(pag, vNF, issues);
2929
+ }
2930
+ if (nfce && vNF.gt(Decimal.of(NFCE_LIMITE_SEM_DESTINATARIO)) && dest === undefined) {
2931
+ issues.add("destinatario", "campo_obrigatorio", `NFC-e acima de R$ ${NFCE_LIMITE_SEM_DESTINATARIO} identifica o destinatário (W16-40, rejeição 750)`);
2932
+ }
2933
+ const ia = input.informacoesAdicionais;
2934
+ const infAdic = ia === undefined || Object.values(ia).every((x) => x === undefined) ? undefined : clean({
2935
+ infAdFisco: ia.infAdFisco,
2936
+ infCpl: ia.infCpl,
2937
+ obsCont: ia.obsCont,
2938
+ obsFisco: ia.obsFisco,
2939
+ procRef: ia.procRef
2940
+ });
2941
+ const exig = { ...exigenciaRespTec(emitUf, options.ambiente, agora), ...options.exigencias };
2942
+ const rt = input.respTec ?? options.respTec;
2943
+ let infRespTec;
2944
+ if (rt === undefined) {
2945
+ if (exig.infRespTec === "obrigatorio") {
2946
+ issues.add("respTec", "resp_tec_obrigatorio", `a UF ${emitUf} exige o responsável técnico (rejeição 972)`);
2947
+ }
2948
+ } else {
2949
+ const cnpjRt = parseCnpj3(rt.CNPJ, { path: "respTec.CNPJ" });
2950
+ if (!cnpjRt.ok)
2951
+ issues.list.push(cnpjRt.error);
2952
+ infRespTec = {
2953
+ CNPJ: cnpjRt.ok ? cnpjRt.value : rt.CNPJ,
2954
+ xContato: rt.xContato,
2955
+ email: rt.email,
2956
+ fone: digits(rt.fone)
2957
+ };
2958
+ if (rt.csrt !== undefined) {
2959
+ infRespTec.idCSRT = rt.csrt.idCSRT;
2960
+ infRespTec.hashCSRT = await hashCsrt(rt.csrt.CSRT, chave);
2961
+ } else if (exig.csrt === "obrigatorio") {
2962
+ issues.add("respTec.csrt", "csrt_obrigatorio", `a UF ${emitUf} exige idCSRT e hashCSRT (rejeição 975)`);
2963
+ }
2964
+ }
2965
+ const inf = clean({
2966
+ versao: "4.00",
2967
+ Id: `NFe${chave}`,
2968
+ ide,
2969
+ emit,
2970
+ dest,
2971
+ retirada: local(input.retirada, "retirada"),
2972
+ entrega: local(input.entrega, "entrega"),
2973
+ autXML,
2974
+ det: itens.map((m) => m.det),
2975
+ total,
2976
+ transp,
2977
+ cobr,
2978
+ pag,
2979
+ infIntermed: input.infIntermed,
2980
+ infAdic,
2981
+ exporta: input.exporta,
2982
+ compra: input.compra,
2983
+ cana: input.cana,
2984
+ infRespTec,
2985
+ agropecuario: input.agropecuario
2986
+ });
2987
+ cstComIsento(input, idDest, issues);
2988
+ vencimentos(input, { dhEmi, instante: agora }, issues);
2989
+ camposForaDoPl(pl.infNFe, inf, "infNFe", pl.vigencia.pl, issues);
2990
+ textosForaDoXml(inf, "infNFe", issues);
2991
+ if (!issues.empty)
2992
+ return { ok: false, issues: issues.classificadas };
2993
+ let xml;
2994
+ try {
2995
+ xml = `<NFe xmlns="${NFE_NS3}">${serialize2(pl.infNFe, "infNFe", inf, NFE_NS3)}</NFe>`;
2996
+ } catch (e) {
2997
+ if (!(e instanceof SerializeError))
2998
+ throw e;
2999
+ return { ok: false, issues: [{ path: e.path, code: "schema", message: e.message, origem: "montagem" }] };
3000
+ }
3001
+ const doc = parseXml3(xml);
3002
+ const infEl = firstChild3(doc.root, "infNFe", NFE_NS3);
3003
+ const schemaIssues = infEl === undefined ? [] : validate3(pl.infNFe, infEl);
3004
+ if (schemaIssues.length > 0) {
3005
+ return {
3006
+ ok: false,
3007
+ issues: schemaIssues.map((i) => ({
3008
+ path: i.path,
3009
+ code: "schema",
3010
+ message: `${i.code}: ${i.message}`,
3011
+ origem: "montagem"
3012
+ }))
3013
+ };
3014
+ }
3015
+ let supl;
3016
+ if (nfce) {
3017
+ const tabela = urlsNfce(emitUf, options.ambiente, diaBrasilia(agora));
3018
+ const urlQr = options.urlQrCode ?? tabela.qrCode;
3019
+ const urlChave = options.urlChave ?? tabela.urlChave;
3020
+ if (urlQr === undefined || !/^https?:\/\//i.test(urlQr)) {
3021
+ issues.montagem("urlQrCode", "qrcode_invalido", `sem endereço completo do QR Code da NFC-e para ${emitUf} em ${options.ambiente}: informe urlQrCode (data/nfce-urls.json)`);
3022
+ }
3023
+ if (urlChave === undefined) {
3024
+ issues.montagem("urlChave", "qrcode_invalido", `sem URL de consulta por chave da NFC-e para ${emitUf}: informe urlChave`);
3025
+ }
3026
+ if (urlQr === undefined || urlChave === undefined || !issues.empty)
3027
+ return { ok: false, issues: issues.classificadas };
3028
+ const p = await parametrosQrCode({
3029
+ chave,
3030
+ ambiente: options.ambiente,
3031
+ tpEmis,
3032
+ dhEmi,
3033
+ vNF: inf.total.ICMSTot.vNF,
3034
+ ...dest === undefined ? {} : { dest },
3035
+ xml
3036
+ }, qr);
3037
+ supl = { versao: qr.versao, urlChave, base: `${urlQr.replace(/\?+$/, "")}?p=`, ...p };
3038
+ const suplIssues = conferirSupl(inserirSupl({ xml, nfce: supl }, supl.assinar ? ASSINATURA_2048 : undefined));
3039
+ if (suplIssues.length > 0)
3040
+ return { ok: false, issues: suplIssues };
3041
+ }
3042
+ return {
3043
+ ok: true,
3044
+ value: {
3045
+ chave,
3046
+ id: `NFe${chave}`,
3047
+ cNF,
3048
+ cDV,
3049
+ mod,
3050
+ tpEmis,
3051
+ dhEmi,
3052
+ ...supl === undefined ? {} : { nfce: supl },
3053
+ pl: pl.vigencia,
3054
+ infNFe: inf,
3055
+ xml
3056
+ }
3057
+ };
3058
+ }
3059
+ var ASSINATURA_2048 = base64Encode2(new Uint8Array(256));
3060
+ function conferirSupl(xml) {
3061
+ const el = firstChild3(parseXml3(xml).root, "infNFeSupl", NFE_NS3);
3062
+ const erros = el === undefined ? [] : validate3(TNFe_infNFeSupl, el);
3063
+ return erros.map((i) => ({ path: i.path, code: "schema", message: `${i.code}: ${i.message}`, origem: "montagem" }));
3064
+ }
3065
+ var escapeXml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
3066
+ async function assinaturaQrCode(built, signer) {
3067
+ return built.nfce?.assinar === true ? assinarParametros(built.nfce.parametros, signer) : undefined;
3068
+ }
3069
+ function comQrCode(built, assinatura) {
3070
+ const xml = inserirSupl(built, assinatura);
3071
+ if (assinatura !== undefined) {
3072
+ const issues = conferirSupl(xml);
3073
+ if (issues.length > 0)
3074
+ throw new ValidationError("o QR Code da NFC-e não passou no schema", issues);
3075
+ }
3076
+ return xml;
3077
+ }
3078
+ function inserirSupl(built, assinatura) {
3079
+ const s = built.nfce;
3080
+ if (s === undefined) {
3081
+ if (assinatura !== undefined)
3082
+ throw new ConfigError2("a NF-e (modelo 55) não tem QR Code");
3083
+ return built.xml;
3084
+ }
3085
+ if (s.assinar && assinatura === undefined) {
3086
+ throw new ConfigError2("NFC-e em contingência off-line com QR Code versão 3 precisa da assinatura (ZX02-334, rejeição 474)");
3087
+ }
3088
+ if (!s.assinar && assinatura !== undefined) {
3089
+ throw new ConfigError2("este QR Code não leva assinatura (ZX02-330, rejeição 445)");
3090
+ }
3091
+ const fim = "</NFe>";
3092
+ if (!built.xml.endsWith(fim))
3093
+ throw new ConfigError2("NFC-e montada fora da forma esperada");
3094
+ const qrCode = `${s.base}${s.parametros}${assinatura === undefined ? "" : `|${assinatura}`}`;
3095
+ const supl = `<infNFeSupl><qrCode>${escapeXml(qrCode)}</qrCode><urlChave>${escapeXml(s.urlChave)}</urlChave></infNFeSupl>`;
3096
+ return built.xml.slice(0, -fim.length) + supl + fim;
3097
+ }
3098
+ async function signNfe(built, signer) {
3099
+ return signXml(comQrCode(built, await assinaturaQrCode(built, signer)), { id: built.id }, signer);
3100
+ }
3101
+ // packages/nfe/src/model.ts
3102
+ var MotivoDesoneracaoIcms = {
3103
+ TAXI: "1",
3104
+ AGROPECUARIA: "3",
3105
+ FROTISTA_LOCADORA: "4",
3106
+ DIPLOMATICO_CONSULAR: "5",
3107
+ UTILITARIOS_MOTOCICLETAS_AMAZONIA_ALC: "6",
3108
+ SUFRAMA: "7",
3109
+ VENDA_ORGAO_PUBLICO: "8",
3110
+ OUTROS: "9",
3111
+ DEFICIENTE_CONDUTOR: "10",
3112
+ DEFICIENTE_NAO_CONDUTOR: "11",
3113
+ FOMENTO_AGROPECUARIO: "12",
3114
+ OLIMPIADAS_RIO_2016: "16",
3115
+ SOLICITADO_PELO_FISCO: "90"
3116
+ };
3117
+ var TipoPagamento = {
3118
+ DINHEIRO: "01",
3119
+ CHEQUE: "02",
3120
+ CARTAO_CREDITO: "03",
3121
+ CARTAO_DEBITO: "04",
3122
+ CREDITO_LOJA: "05",
3123
+ VALE_ALIMENTACAO: "10",
3124
+ VALE_REFEICAO: "11",
3125
+ VALE_PRESENTE: "12",
3126
+ VALE_COMBUSTIVEL: "13",
3127
+ BOLETO: "15",
3128
+ DEPOSITO: "16",
3129
+ PIX_DINAMICO: "17",
3130
+ TRANSFERENCIA_CARTEIRA_DIGITAL: "18",
3131
+ FIDELIDADE_CASHBACK: "19",
3132
+ PIX_ESTATICO: "20",
3133
+ CREDITO_EM_LOJA: "21",
3134
+ FALHA_HARDWARE: "22",
3135
+ SEM_PAGAMENTO: "90",
3136
+ PAGAMENTO_POSTERIOR: "91",
3137
+ OUTROS: "99"
3138
+ };
3139
+ // packages/nfe/src/rotulo.ts
3140
+ import { criarRotuloDoCaminho } from "@sinete/core";
3141
+ var item = (prefixo) => (n) => `${prefixo} ${n}`;
3142
+ var GRUPOS = [
3143
+ { padrao: /^emitente\b/, rotulo: "Emitente" },
3144
+ { padrao: /^destinatario\b/, rotulo: "Destinatário" },
3145
+ { padrao: /^retirada\b/, rotulo: "Local de retirada" },
3146
+ { padrao: /^entrega\b/, rotulo: "Local de entrega" },
3147
+ { padrao: /^autXML\b/, rotulo: "Autorizados a baixar o XML" },
3148
+ { padrao: /^referenciadas\b/, rotulo: "Nota referenciada" },
3149
+ { padrao: /^itens\[(\d+)\]\.impostos\.icms\b/, rotulo: item("ICMS do item") },
3150
+ { padrao: /^itens\[(\d+)\]\.impostos\.ibsCbs\b/, rotulo: item("IBS/CBS do item") },
3151
+ { padrao: /^itens\[(\d+)\]\.impostos\b/, rotulo: item("Impostos do item") },
3152
+ { padrao: /^itens\[(\d+)\]/, rotulo: item("Item") },
3153
+ { padrao: /^itens\b/, rotulo: "Itens" },
3154
+ { padrao: /^transporte\b/, rotulo: "Transporte" },
3155
+ { padrao: /^cobranca\b/, rotulo: "Cobrança" },
3156
+ { padrao: /^pagamento\b/, rotulo: "Pagamento" },
3157
+ { padrao: /^informacoesAdicionais\b/, rotulo: "Informações adicionais" },
3158
+ { padrao: /^agropecuario\b/, rotulo: "Produtos agropecuários" },
3159
+ { padrao: /^respTec\b/, rotulo: "Responsável técnico" },
3160
+ { padrao: /^contingencia\b/, rotulo: "Contingência" },
3161
+ { padrao: /^gCompraGov\b/, rotulo: "Compra governamental" },
3162
+ { padrao: /^exporta\b/, rotulo: "Exportação" },
3163
+ { padrao: /^(?:qrCode|urlQrCode|urlChave)\b/, rotulo: "QR Code da NFC-e" },
3164
+ { padrao: /^(?:NFe\.)?infNFeSupl\b/, rotulo: "QR Code da NFC-e" },
3165
+ { padrao: /^infNFe\.ide\.NFref\b/, rotulo: "Nota referenciada" },
3166
+ { padrao: /^infNFe\.ide\b/, rotulo: "Identificação da nota" },
3167
+ { padrao: /^infNFe\.emit\b/, rotulo: "Emitente" },
3168
+ { padrao: /^infNFe\.dest\b/, rotulo: "Destinatário" },
3169
+ { padrao: /^infNFe\.retirada\b/, rotulo: "Local de retirada" },
3170
+ { padrao: /^infNFe\.entrega\b/, rotulo: "Local de entrega" },
3171
+ { padrao: /^infNFe\.autXML\b/, rotulo: "Autorizados a baixar o XML" },
3172
+ { padrao: /^infNFe\.det(?:\[(\d+)\])?\.imposto\.ICMS\b/, rotulo: item("ICMS do item") },
3173
+ { padrao: /^infNFe\.det(?:\[(\d+)\])?\.imposto\.IBSCBS\b/, rotulo: item("IBS/CBS do item") },
3174
+ { padrao: /^infNFe\.det(?:\[(\d+)\])?\.imposto\b/, rotulo: item("Impostos do item") },
3175
+ { padrao: /^infNFe\.det(?:\[(\d+)\])?/, rotulo: item("Item") },
3176
+ { padrao: /^infNFe\.total\b/, rotulo: "Totais da nota" },
3177
+ { padrao: /^infNFe\.transp\b/, rotulo: "Transporte" },
3178
+ { padrao: /^infNFe\.cobr\b/, rotulo: "Cobrança" },
3179
+ { padrao: /^infNFe\.pag\b/, rotulo: "Pagamento" },
3180
+ { padrao: /^infNFe\.infAdic\b/, rotulo: "Informações adicionais" },
3181
+ { padrao: /^infNFe\.agropecuario\b/, rotulo: "Produtos agropecuários" },
3182
+ { padrao: /^infNFe\.infRespTec\b/, rotulo: "Responsável técnico" },
3183
+ { padrao: /^infNFe\.exporta\b/, rotulo: "Exportação" }
3184
+ ];
3185
+ var CAMPOS = {
3186
+ IE: "Inscrição estadual",
3187
+ IEST: "Inscrição estadual do substituto tributário",
3188
+ IM: "Inscrição municipal",
3189
+ CNPJ: "CNPJ",
3190
+ CPF: "CPF",
3191
+ idEstrangeiro: "Identificação do estrangeiro",
3192
+ xNome: "Nome",
3193
+ xFant: "Nome fantasia",
3194
+ xLgr: "Logradouro",
3195
+ nro: "Número",
3196
+ xCpl: "Complemento",
3197
+ xBairro: "Bairro",
3198
+ cMun: "Município",
3199
+ xMun: "Município",
3200
+ UF: "UF",
3201
+ CEP: "CEP",
3202
+ fone: "Telefone",
3203
+ email: "E-mail",
3204
+ natOp: "Natureza da operação",
3205
+ serie: "Série",
3206
+ nNF: "Número da nota",
3207
+ cProd: "Código do produto",
3208
+ cEAN: "GTIN",
3209
+ cEANTrib: "GTIN da unidade tributável",
3210
+ xProd: "Descrição do produto",
3211
+ NCM: "NCM",
3212
+ CEST: "CEST",
3213
+ cBenef: "Código de benefício fiscal",
3214
+ CFOP: "CFOP",
3215
+ uCom: "Unidade comercial",
3216
+ qCom: "Quantidade comercial",
3217
+ vUnCom: "Valor unitário comercial",
3218
+ uTrib: "Unidade tributável",
3219
+ qTrib: "Quantidade tributável",
3220
+ vUnTrib: "Valor unitário tributável",
3221
+ vProd: "Valor do produto",
3222
+ vDesc: "Desconto",
3223
+ vFrete: "Frete",
3224
+ vSeg: "Seguro",
3225
+ vOutro: "Outras despesas",
3226
+ CST: "CST",
3227
+ CSOSN: "CSOSN",
3228
+ cClassTrib: "Classificação tributária (cClassTrib)",
3229
+ vBC: "Base de cálculo",
3230
+ refNFe: "Chave da NF-e referenciada",
3231
+ refNFP: "Nota de produtor referenciada",
3232
+ AAMM: "Mês de emissão da nota referenciada",
3233
+ modFrete: "Modalidade do frete",
3234
+ placa: "Placa",
3235
+ RNTC: "RNTC",
3236
+ tPag: "Meio de pagamento",
3237
+ vPag: "Valor do pagamento",
3238
+ vTroco: "Troco",
3239
+ card: "Cartão",
3240
+ CSC: "CSC",
3241
+ idCSC: "Identificador do CSC",
3242
+ versao: "Versão",
3243
+ xJust: "Justificativa",
3244
+ dhCont: "Entrada em contingência",
3245
+ infCpl: "Informações complementares",
3246
+ infAdFisco: "Informações de interesse do fisco"
3247
+ };
3248
+ var rotular = criarRotuloDoCaminho({ grupos: GRUPOS, campos: CAMPOS, padrao: "Dados da NF-e" });
3249
+ function rotuloDoCaminho(path) {
3250
+ return rotular(path);
3251
+ }
3252
+ // packages/nfe/src/services/client.ts
3253
+ import {
3254
+ authorized,
3255
+ ConfigError as ConfigError4,
3256
+ denied,
3257
+ noopLogger,
3258
+ ProtocolError as ProtocolError4,
3259
+ pending,
3260
+ tpAmbOf as tpAmbOf3,
3261
+ ufByCUf as ufByCUf2,
3262
+ ufBySigla as ufBySigla3,
3263
+ ValidationError as ValidationError2
3264
+ } from "@sinete/core";
3265
+ import { childElements as childElements2, firstChild as firstChild5, parseXml as parseXml6, signXml as signXml2, textOf as textOf2 } from "@sinete/core/xml";
3266
+ import { decode, decodeXml, serialize as serialize3, serializeRoot, validate as validate4 } from "@sinete/schemas";
3267
+ import { ConsCadElement, TRetConsCad } from "@sinete/schemas/nfe/consulta-cadastro/PL_010d";
3268
+ import { consSitNFeElement, TProtNFe, TRetConsSitNFe } from "@sinete/schemas/nfe/consulta-protocolo/PL_010d";
3269
+ import {
3270
+ distDFeIntElement,
3271
+ resEventoElement,
3272
+ resNFeElement,
3273
+ retDistDFeInt
3274
+ } from "@sinete/schemas/nfe/dist-dfe/PL_NFeDistDFe_104";
3275
+ import { TEvento_infEvento as TEventoCanc, TRetEnvEvento } from "@sinete/schemas/nfe/evento-cancelamento/PL_010d";
3276
+ import { TEvento_infEvento as TEventoCancSubst } from "@sinete/schemas/nfe/evento-cancelamento-substituicao/PL_010d";
3277
+ import { TEvento_infEvento as TEventoCce } from "@sinete/schemas/nfe/evento-cce/PL_010d";
3278
+ import { TEvento_infEvento as TEventoCiencia } from "@sinete/schemas/nfe/evento-ciencia-operacao/PL_010d";
3279
+ import { TEvento_infEvento as TEventoConfirmacao } from "@sinete/schemas/nfe/evento-confirmacao-operacao/PL_010d";
3280
+ import { TEvento_infEvento as TEventoDesconhecimento } from "@sinete/schemas/nfe/evento-desconhecimento-operacao/PL_010d";
3281
+ import { TEvento_infEvento as TEventoNaoRealizada } from "@sinete/schemas/nfe/evento-operacao-nao-realizada/PL_010d";
3282
+ import { TInutNFe_infInut, TRetInutNFe } from "@sinete/schemas/nfe/inutilizacao/PL_010d";
3283
+ import { TRetConsReciNFe, TRetEnviNFe } from "@sinete/schemas/nfe/PL_010f";
3284
+ import { consStatServElement, TRetConsStatServ } from "@sinete/schemas/nfe/status-servico/PL_009q";
3285
+ import { nfceEndpoint, nfeContingenciaDaUf, nfeEndpoint } from "@sinete/transport";
3286
+ import { parseChaveAcesso as parseChaveAcesso2, parseCnpj as parseCnpj4, parseCpf as parseCpf2 } from "@sinete/validators";
3287
+
3288
+ // packages/nfe/src/services/gzip.ts
3289
+ import { ProtocolError, UnsupportedError as UnsupportedError2 } from "@sinete/core";
3290
+ import { base64Decode } from "@sinete/core/xml";
3291
+ async function gunzipBase64(b64) {
3292
+ const Ds = globalThis.DecompressionStream;
3293
+ if (Ds === undefined)
3294
+ throw new UnsupportedError2("DecompressionStream indisponível nesta runtime; docZip não pode ser lido");
3295
+ let bytes;
3296
+ try {
3297
+ bytes = base64Decode(b64.trim());
3298
+ } catch (cause) {
3299
+ throw new ProtocolError("docZip com base64 inválido", { cause });
3300
+ }
3301
+ try {
3302
+ const stream = new Blob([bytes]).stream().pipeThrough(new Ds("gzip"));
3303
+ return await new Response(stream).text();
3304
+ } catch (cause) {
3305
+ throw new ProtocolError("docZip não é um gzip válido", { cause });
3306
+ }
3307
+ }
3308
+
3309
+ // packages/nfe/src/services/outcome.ts
3310
+ import { rejected } from "@sinete/core";
3311
+ import { enrichRejected } from "@sinete/rejeicoes";
3312
+ // packages/nfe/src/data/cstat.json
3313
+ var cstat_default = {
3314
+ descricao: "Códigos de status de sucesso e de processamento (MOC 7.0 Anexo I, tabela 4.4.1) e os códigos que o @sinete/nfe trata de forma própria. Rejeições e denegações com mensagem oficial estão no @sinete/rejeicoes; aqui fica só o desfecho de cada código por serviço.",
3315
+ fonte: "MOC 7.0 Anexo I, tabela 4.4.1 (códigos de sucesso) e 4.4.2 (denegação 301, 302, 303); NT 2014.002 (Distribuição DF-e, 137 e 138); NT 2011.004 (lote em processamento, 105); MOC 7.0 Anexo I, consulta protocolo J03 a J06 (561, 562 e 613: a numeração da chave consultada tem outra NF-e)",
3316
+ atualizadoEm: "2026-09-26",
3317
+ autorizada: ["100", "150"],
3318
+ denegada: ["110", "301", "302", "303"],
3319
+ cancelada: ["101", "151", "155"],
3320
+ loteRecebido: ["103"],
3321
+ loteProcessado: ["104"],
3322
+ loteEmProcessamento: ["105"],
3323
+ loteNaoLocalizado: ["106"],
3324
+ servicoEmOperacao: ["107"],
3325
+ inutilizacaoHomologada: ["102"],
3326
+ eventoRegistrado: ["135", "136", "155"],
3327
+ loteEventoProcessado: ["128"],
3328
+ cadastroEncontrado: ["111", "112"],
3329
+ distribuicaoNenhumDocumento: ["137"],
3330
+ distribuicaoDocumentos: ["138"],
3331
+ duplicidade: ["204"],
3332
+ duplicidadeChaveDiferente: ["539"],
3333
+ naoConsta: ["217"],
3334
+ outraNfeNoNumero: ["561", "562", "613"],
3335
+ consumoIndevido: ["656"],
3336
+ dicas: {
3337
+ "656": {
3338
+ probableCause: "Consumo indevido: consultas repetidas à Distribuição DF-e sem documento novo (ultNSU igual a maxNSU) ou acima do limite de requisições por hora.",
3339
+ suggestedFix: "Aguardar uma hora antes de consultar de novo e só repetir a consulta quando ultNSU for menor que maxNSU; guardar o ultNSU devolvido e continuar dele.",
3340
+ source: "NT 2014.002 v1.02 (Distribuição DF-e), regras de consumo indevido"
3341
+ },
3342
+ "217": {
3343
+ probableCause: "A chave consultada não consta na base do autorizador consultado: a nota não foi recebida, ou foi autorizada em outro ambiente ou autorizador (SVC).",
3344
+ suggestedFix: "Se o envio ficou sem resposta, reenviar exatamente o mesmo XML assinado; se foi emitida em contingência SVC, consultar no SVC.",
3345
+ source: "MOC 7.0 Anexo I, serviço de consulta protocolo"
3346
+ }
3347
+ }
3348
+ };
3349
+
3350
+ // packages/nfe/src/services/outcome.ts
3351
+ var CLASSES = cstat_default;
3352
+ var DICAS = cstat_default.dicas;
3353
+ function cstatEm(cStat, classe) {
3354
+ return CLASSES[classe].includes(cStat);
3355
+ }
3356
+ function rejeitado(status) {
3357
+ const r = enrichRejected(rejected(status));
3358
+ if (r.hint !== undefined)
3359
+ return r;
3360
+ const dica = Object.hasOwn(DICAS, status.cStat) ? DICAS[status.cStat] : undefined;
3361
+ return dica === undefined ? r : rejected(status, dica);
3362
+ }
3363
+
3364
+ // packages/nfe/src/services/proc.ts
3365
+ import { ConfigError as ConfigError3, ProtocolError as ProtocolError2 } from "@sinete/core";
3366
+ import {
3367
+ attributeOf,
3368
+ descendants,
3369
+ firstChild as firstChild4,
3370
+ inScopeNamespaces,
3371
+ parseXml as parseXml4,
3372
+ textOf,
3373
+ XMLDSIG_NS
3374
+ } from "@sinete/core/xml";
3375
+ var NFE_NS4 = "http://www.portalfiscal.inf.br/nfe";
3376
+ var XML_DECL = /^?<\?xml[^?]*\?>\s*/;
3377
+ function sliceElement(doc, el, parentDefaultNs = NFE_NS4) {
3378
+ const slice = doc.source.slice(el.start, el.end);
3379
+ const used = new Set;
3380
+ const cobertoDentro = (d, p) => {
3381
+ for (let e = d;e; e = e === el ? null : e.parent)
3382
+ if (e.namespaces.has(p))
3383
+ return true;
3384
+ return false;
3385
+ };
3386
+ for (const d of descendants(el)) {
3387
+ const prefixos = [d.prefix, ...d.attributes.map((a) => a.prefix)].filter((p) => p !== "" && p !== "xml");
3388
+ for (const p of prefixos)
3389
+ if (!cobertoDentro(d, p))
3390
+ used.add(p);
3391
+ }
3392
+ const extra = [];
3393
+ const inScope = new Map;
3394
+ for (let e = el.parent;e; e = e.parent) {
3395
+ for (const [p, u] of e.namespaces)
3396
+ if (!inScope.has(p))
3397
+ inScope.set(p, u);
3398
+ }
3399
+ const herdado = inScope.get("") ?? "";
3400
+ if (herdado !== parentDefaultNs && usaDefaultHerdado(el))
3401
+ extra.push(` xmlns="${herdado}"`);
3402
+ for (const p of [...used].sort()) {
3403
+ const uri = inScope.get(p);
3404
+ if (uri === undefined)
3405
+ throw new ProtocolError2(`prefixo ${p} sem declaração no recorte de ${el.name}`);
3406
+ extra.push(` xmlns:${p}="${uri}"`);
3407
+ }
3408
+ if (extra.length === 0)
3409
+ return slice;
3410
+ const at = 1 + el.name.length;
3411
+ return slice.slice(0, at) + extra.join("") + slice.slice(at);
3412
+ }
3413
+ function usaDefaultHerdado(raiz) {
3414
+ for (const d of descendants(raiz)) {
3415
+ if (d.prefix !== "")
3416
+ continue;
3417
+ let coberto = false;
3418
+ for (let e = d;e; e = e === raiz ? null : e.parent) {
3419
+ if (e.namespaces.has("")) {
3420
+ coberto = true;
3421
+ break;
3422
+ }
3423
+ }
3424
+ if (!coberto)
3425
+ return true;
3426
+ }
3427
+ return false;
3428
+ }
3429
+ function documentoAssinado(xml, raiz, elemento) {
3430
+ const text = xml.replace(XML_DECL, "");
3431
+ let doc;
3432
+ try {
3433
+ doc = parseXml4(text);
3434
+ } catch (cause) {
3435
+ throw new ConfigError3(`${raiz} assinado malformado`, { cause });
3436
+ }
3437
+ if (doc.root.local !== raiz || doc.root.ns !== NFE_NS4) {
3438
+ throw new ConfigError3(`esperado <${raiz}> no namespace da NF-e, veio <${doc.root.name}>`);
3439
+ }
3440
+ if (doc.root.namespaces.get("") !== NFE_NS4) {
3441
+ throw new ConfigError3(`<${raiz}> assinado precisa declarar xmlns="${NFE_NS4}" na própria raiz`);
3442
+ }
3443
+ const alvo = firstChild4(doc.root, elemento, NFE_NS4);
3444
+ const id = alvo ? attributeOf(alvo, "Id") : undefined;
3445
+ const sig = firstChild4(doc.root, "Signature", XMLDSIG_NS);
3446
+ const digest = sig && descendantText(sig, "DigestValue");
3447
+ if (!id || digest === undefined)
3448
+ throw new ConfigError3(`${raiz} sem ${elemento} identificado ou sem assinatura`);
3449
+ return { xml: text, id, digestValue: digest, doc };
3450
+ }
3451
+ function descendantText(el, local) {
3452
+ for (const d of descendants(el))
3453
+ if (d.local === local && d.ns === XMLDSIG_NS)
3454
+ return textOf(d).trim();
3455
+ return;
3456
+ }
3457
+ function nfeAssinadaDoProc(xml) {
3458
+ const text = xml.replace(XML_DECL, "");
3459
+ let doc;
3460
+ try {
3461
+ doc = parseXml4(text);
3462
+ } catch (cause) {
3463
+ throw new ConfigError3("nfeProc malformado", { cause });
3464
+ }
3465
+ const noProc = doc.root.local === "nfeProc" && doc.root.ns === NFE_NS4 ? firstChild4(doc.root, "NFe", NFE_NS4) : undefined;
3466
+ const el = noProc ?? (doc.root.local === "NFe" && doc.root.ns === NFE_NS4 ? doc.root : undefined);
3467
+ if (el === undefined)
3468
+ throw new ConfigError3(`esperado <nfeProc> ou <NFe> assinada, veio <${doc.root.name}>`);
3469
+ const fatia = doc.source.slice(el.start, el.end);
3470
+ const herdados = [...inScopeNamespaces(el)].filter(([p]) => p !== "xml" && !el.namespaces.has(p));
3471
+ const decl = herdados.map(([p, uri]) => ` ${p === "" ? "xmlns" : `xmlns:${p}`}="${uri.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/"/g, "&quot;")}"`).join("");
3472
+ const at = 1 + el.name.length;
3473
+ const assinado = decl === "" ? fatia : fatia.slice(0, at) + decl + fatia.slice(at);
3474
+ return documentoAssinado(assinado, "NFe", "infNFe").xml;
3475
+ }
3476
+ function envelope(raiz, versao, partes) {
3477
+ return `<${raiz} xmlns="${NFE_NS4}" versao="${versao}">${partes.join("")}</${raiz}>`;
3478
+ }
3479
+
3480
+ // packages/nfe/src/services/soap.ts
3481
+ import { ProtocolError as ProtocolError3 } from "@sinete/core";
3482
+ import { childElements, descendants as descendants2, parseXml as parseXml5 } from "@sinete/core/xml";
3483
+ import { soap12ContentType, soap12Envelope, soapFault } from "@sinete/transport";
3484
+ // packages/nfe/src/data/servicos.json
3485
+ var servicos_default = {
3486
+ descricao: "Web services SOAP 1.2 da NF-e 4.00: namespace do WSDL e operação (a action do Content-Type é <namespace>/<operação>). Na NF-e 4.00 não existe cabeçalho nfeCabecMsg; a mensagem vai em nfeDadosMsg no namespace do WSDL, e a resposta volta em nfeResultMsg. A Distribuição DF-e usa o envelope do WSDL próprio, com nfeDadosMsg dentro de nfeDistDFeInteresse.",
3487
+ fonte: "MOC 7.0, Visão Geral, item 3 (padrão de comunicação e WSDL dos serviços) e WSDLs do portal da NF-e; NT 2014.002 (Distribuição DF-e)",
3488
+ atualizadoEm: "2026-09-28",
3489
+ servicos: {
3490
+ NfeStatusServico: {
3491
+ namespace: "http://www.portalfiscal.inf.br/nfe/wsdl/NFeStatusServico4",
3492
+ operacao: "nfeStatusServicoNF"
3493
+ },
3494
+ NFeAutorizacao: {
3495
+ namespace: "http://www.portalfiscal.inf.br/nfe/wsdl/NFeAutorizacao4",
3496
+ operacao: "nfeAutorizacaoLote"
3497
+ },
3498
+ NFeRetAutorizacao: {
3499
+ namespace: "http://www.portalfiscal.inf.br/nfe/wsdl/NFeRetAutorizacao4",
3500
+ operacao: "nfeRetAutorizacaoLote"
3501
+ },
3502
+ NfeConsultaProtocolo: {
3503
+ namespace: "http://www.portalfiscal.inf.br/nfe/wsdl/NFeConsultaProtocolo4",
3504
+ operacao: "nfeConsultaNF"
3505
+ },
3506
+ NfeInutilizacao: {
3507
+ namespace: "http://www.portalfiscal.inf.br/nfe/wsdl/NFeInutilizacao4",
3508
+ operacao: "nfeInutilizacaoNF"
3509
+ },
3510
+ RecepcaoEvento: {
3511
+ namespace: "http://www.portalfiscal.inf.br/nfe/wsdl/NFeRecepcaoEvento4",
3512
+ operacao: "nfeRecepcaoEvento"
3513
+ },
3514
+ NfeConsultaCadastro: {
3515
+ namespace: "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro4",
3516
+ operacao: "consultaCadastro",
3517
+ envelopeNoAutorizador: {
3518
+ MT: "operacao"
3519
+ },
3520
+ fonteEnvelope: "Resposta da SEFAZ-MT em homologação em 28/09/2026: com a mensagem só em nfeDadosMsg, o MT responde 215 (falha no schema) e devolve o retorno dentro de consultaCadastroResult; com nfeDadosMsg dentro de consultaCadastro (o elemento da operação do WSDL), responde a consulta (259)."
3521
+ },
3522
+ NFeDistribuicaoDFe: {
3523
+ namespace: "http://www.portalfiscal.inf.br/nfe/wsdl/NFeDistribuicaoDFe",
3524
+ operacao: "nfeDistDFeInteresse",
3525
+ envelope: "distDFeInteresse"
3526
+ }
3527
+ }
3528
+ };
3529
+
3530
+ // packages/nfe/src/services/soap.ts
3531
+ var SERVICOS = servicos_default.servicos;
3532
+ function servicoInfo(servico) {
3533
+ const s = SERVICOS[servico];
3534
+ if (!s)
3535
+ throw new ProtocolError3(`serviço sem descrição em data/servicos.json: ${servico}`);
3536
+ return s;
3537
+ }
3538
+ function soapBodyFor(servico, mensagem, autorizador) {
3539
+ const s = servicoInfo(servico);
3540
+ if (s.envelope === "distDFeInteresse" || autorizador && s.envelopeNoAutorizador?.[autorizador] === "operacao") {
3541
+ return `<${s.operacao} xmlns="${s.namespace}"><nfeDadosMsg>${mensagem}</nfeDadosMsg></${s.operacao}>`;
3542
+ }
3543
+ return `<nfeDadosMsg xmlns="${s.namespace}">${mensagem}</nfeDadosMsg>`;
3544
+ }
3545
+ async function chamar(c) {
3546
+ const s = servicoInfo(c.servico);
3547
+ const started = { servico: c.servico, autorizador: c.endpoint.autorizador, host: c.endpoint.host };
3548
+ const res = await c.transport.send({
3549
+ url: c.endpoint.url,
3550
+ endpoint: c.endpoint,
3551
+ method: "POST",
3552
+ headers: { "content-type": soap12ContentType(`${s.namespace}/${s.operacao}`) },
3553
+ body: soap12Envelope(soapBodyFor(c.servico, c.mensagem, c.endpoint.autorizador)),
3554
+ ...c.timeoutMs === undefined ? {} : { timeoutMs: c.timeoutMs },
3555
+ ...c.signal === undefined ? {} : { signal: c.signal }
3556
+ });
3557
+ const text = res.text();
3558
+ const fault = soapFault(text);
3559
+ if (fault) {
3560
+ c.logger.warn("nfe.soap.fault", { ...started, status: res.status, code: fault.code });
3561
+ throw new ProtocolError3(`SOAP fault de ${c.endpoint.host}: ${fault.reason ?? fault.code ?? "sem motivo"}`, {
3562
+ details: { status: res.status, code: fault.code, reason: fault.reason, servico: c.servico }
3563
+ });
3564
+ }
3565
+ let doc;
3566
+ try {
3567
+ doc = parseXml5(text.replace(/^/, ""));
3568
+ } catch (cause) {
3569
+ throw new ProtocolError3(`resposta de ${c.endpoint.host} não é XML (HTTP ${res.status})`, {
3570
+ cause,
3571
+ details: { status: res.status, servico: c.servico }
3572
+ });
3573
+ }
3574
+ let ret;
3575
+ for (const el of descendants2(doc.root)) {
3576
+ if (el.local === c.retorno && el.ns === NFE_NS4) {
3577
+ ret = el;
3578
+ break;
3579
+ }
3580
+ }
3581
+ if (!ret)
3582
+ ret = retornoForaDoNamespace(doc.root, c.retorno);
3583
+ if (ret && ret.ns !== NFE_NS4) {
3584
+ c.logger.warn("nfe.soap.retorno_fora_do_namespace", { ...started, retorno: c.retorno, ns: ret.ns });
3585
+ }
3586
+ if (!ret) {
3587
+ throw new ProtocolError3(`resposta de ${c.endpoint.host} sem <${c.retorno}> (HTTP ${res.status})`, {
3588
+ details: { status: res.status, servico: c.servico }
3589
+ });
3590
+ }
3591
+ if (!Array.from(descendants2(ret)).some((el) => el.local === "cStat" && el.ns === NFE_NS4)) {
3592
+ throw new ProtocolError3(`<${c.retorno}> de ${c.endpoint.host} sem cStat (HTTP ${res.status})`, {
3593
+ details: { status: res.status, servico: c.servico }
3594
+ });
3595
+ }
3596
+ c.logger.debug("nfe.soap.resposta", { ...started, status: res.status });
3597
+ return { doc, ret, status: res.status };
3598
+ }
3599
+ function retornoForaDoNamespace(root, retorno) {
3600
+ for (const el of descendants2(root)) {
3601
+ if (el.local !== retorno)
3602
+ continue;
3603
+ const filhos = childElements(el);
3604
+ if (filhos.length > 0 && filhos.every((f) => f.ns === NFE_NS4))
3605
+ return el;
3606
+ }
3607
+ return;
3608
+ }
3609
+
3610
+ // packages/nfe/src/services/client.ts
3611
+ function autorizadorContingencia(uf, ambiente) {
3612
+ const autorizador = nfeContingenciaDaUf(uf, ambiente);
3613
+ return { autorizador, tpEmis: autorizador === "SVC-AN" ? "6" : "7" };
3614
+ }
3615
+ var defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
3616
+ if (signal?.aborted) {
3617
+ reject(signal.reason);
3618
+ return;
3619
+ }
3620
+ const onAbort = () => {
3621
+ clearTimeout(t);
3622
+ reject(signal?.reason);
3623
+ };
3624
+ const t = setTimeout(() => {
3625
+ signal?.removeEventListener("abort", onAbort);
3626
+ resolve();
3627
+ }, ms);
3628
+ signal?.addEventListener("abort", onAbort, { once: true });
3629
+ });
3630
+ function chaveValida(chave, path) {
3631
+ const r = parseChaveAcesso2(chave, { path });
3632
+ if (!r.ok)
3633
+ throw new ValidationError2(`chave de acesso inválida: ${r.error.message}`, [r.error]);
3634
+ return r.value;
3635
+ }
3636
+ function schemaIssues(what, issues) {
3637
+ if (issues.length > 0)
3638
+ throw new ValidationError2(`${what} não confere com o schema`, issues);
3639
+ }
3640
+ function documentoAutor(a, path) {
3641
+ if (a.CNPJ !== undefined) {
3642
+ const r = parseCnpj4(a.CNPJ, { path: `${path}.CNPJ` });
3643
+ if (!r.ok)
3644
+ throw new ValidationError2("CNPJ do autor inválido", [r.error]);
3645
+ return { CNPJ: r.value };
3646
+ }
3647
+ const r = parseCpf2(a.CPF ?? "", { path: `${path}.CPF` });
3648
+ if (!r.ok)
3649
+ throw new ValidationError2("CPF do autor inválido", [r.error]);
3650
+ return { CPF: r.value };
3651
+ }
3652
+ function autorDaChave(c) {
3653
+ return c.cnpj !== undefined ? { CNPJ: c.cnpj } : { CPF: c.cpf ?? c.emitente.slice(3) };
3654
+ }
3655
+ function autorDoEmitente(a, c) {
3656
+ const daChave = autorDaChave(c);
3657
+ if (a === undefined)
3658
+ return daChave;
3659
+ const autor = documentoAutor(a, "autor");
3660
+ const [campo, valor] = "CNPJ" in autor ? ["CNPJ", autor.CNPJ] : ["CPF", autor.CPF];
3661
+ if (valor !== ("CNPJ" in daChave ? daChave.CNPJ : daChave.CPF) || campo !== ("CNPJ" in daChave ? "CNPJ" : "CPF")) {
3662
+ throw new ValidationError2("o autor do evento não é o emitente da NF-e", [
3663
+ {
3664
+ path: `autor.${campo}`,
3665
+ code: "autor_difere_do_emitente",
3666
+ message: `o autor de um evento do emitente é o ${"CNPJ" in daChave ? "CNPJ" : "CPF"} da chave (P12-44, rejeição 574)`,
3667
+ origem: "entrada"
3668
+ }
3669
+ ]);
3670
+ }
3671
+ return autor;
3672
+ }
3673
+ var SVC_DO_TPEMIS = { "6": "SVC-AN", "7": "SVC-RS" };
3674
+ function chaveDoDocumento(a) {
3675
+ const r = parseChaveAcesso2(a.id.slice(3), { path: "infNFe.Id", checkEmitente: false });
3676
+ if (!r.ok)
3677
+ throw new ConfigError4(`Id da NF-e assinada não é uma chave de acesso: ${r.error.message}`);
3678
+ return r.value;
3679
+ }
3680
+ function avulso(doc, el) {
3681
+ return sliceElement(doc, el, "");
3682
+ }
3683
+ function lerProtocolo(doc, el) {
3684
+ const { value } = decode(TProtNFe, el, doc.source);
3685
+ const inf = value.infProt;
3686
+ if (!inf)
3687
+ throw new ProtocolError4("protNFe sem infProt");
3688
+ const p = {
3689
+ chNFe: inf.chNFe,
3690
+ cStat: inf.cStat,
3691
+ xMotivo: inf.xMotivo,
3692
+ dhRecbto: inf.dhRecbto,
3693
+ verAplic: inf.verAplic,
3694
+ protNFe: avulso(doc, el),
3695
+ ...inf.nProt === undefined ? {} : { nProt: inf.nProt },
3696
+ ...inf.digVal === undefined ? {} : { digVal: inf.digVal }
3697
+ };
3698
+ return { p, embutido: sliceElement(doc, el) };
3699
+ }
3700
+ function desfechoDoProtocolo({ p, embutido }, a) {
3701
+ const status = { cStat: p.cStat, xMotivo: p.xMotivo };
3702
+ const autorizada = cstatEm(p.cStat, "autorizada");
3703
+ const denegada = cstatEm(p.cStat, "denegada");
3704
+ if (!autorizada && !denegada)
3705
+ return rejeitado(status);
3706
+ let full = p;
3707
+ if (a) {
3708
+ if (`NFe${p.chNFe}` !== a.id) {
3709
+ throw new ProtocolError4("protocolo de outra chave de acesso", { details: { chNFe: p.chNFe } });
3710
+ }
3711
+ if (p.digVal !== undefined && p.digVal !== a.digestValue) {
3712
+ throw new ProtocolError4("digVal do protocolo difere do DigestValue da NF-e enviada", {
3713
+ details: { chNFe: p.chNFe, cStat: p.cStat }
3714
+ });
3715
+ }
3716
+ if (p.digVal !== undefined)
3717
+ full = { ...p, nfeProc: envelope("nfeProc", "4.00", [a.xml, embutido]) };
3718
+ }
3719
+ return autorizada ? authorized(status, full) : denied(status, full);
3720
+ }
3721
+ function protNFeDaChave(parent, a) {
3722
+ const prots = childElements2(parent).filter((e) => e.local === "protNFe" && e.ns === NFE_NS4);
3723
+ if (!a)
3724
+ return prots[0];
3725
+ const chave = a.id.slice(3);
3726
+ return prots.find((e) => {
3727
+ const inf = firstChild5(e, "infProt", NFE_NS4);
3728
+ const ch = inf && firstChild5(inf, "chNFe", NFE_NS4);
3729
+ return ch !== undefined && textOf2(ch).trim() === chave;
3730
+ }) ?? (prots.length === 1 ? prots[0] : undefined);
3731
+ }
3732
+ var EVENTO_VERSAO = "1.00";
3733
+ var XCONDUSO = "A Carta de Correção é disciplinada pelo § 1º-A do art. 7º do Convênio S/N, de 15 de dezembro de 1970 e pode ser utilizada para regularização de erro ocorrido na emissão de documento fiscal, desde que o erro não esteja relacionado com: I - as variáveis que determinam o valor do imposto tais como: base de cálculo, alíquota, diferença de preço, quantidade, valor da operação ou da prestação; II - a correção de dados cadastrais que implique mudança do remetente ou do destinatário; III - a data de emissão ou de saída.";
3734
+ var MANIFESTACOES = {
3735
+ confirmacao: { tpEvento: "210200", descEvento: "Confirmacao da Operacao", ct: TEventoConfirmacao },
3736
+ ciencia: { tpEvento: "210210", descEvento: "Ciencia da Operacao", ct: TEventoCiencia },
3737
+ desconhecimento: { tpEvento: "210220", descEvento: "Desconhecimento da Operacao", ct: TEventoDesconhecimento },
3738
+ "nao-realizada": { tpEvento: "210240", descEvento: "Operacao nao Realizada", ct: TEventoNaoRealizada }
3739
+ };
3740
+ function createNfeClient(options) {
3741
+ const logger = (options.logger ?? noopLogger).child({ modulo: "nfe", ambiente: options.ambiente });
3742
+ const sleep = options.sleep ?? defaultSleep;
3743
+ const tpAmb = tpAmbOf3(options.ambiente);
3744
+ const ufInfo = options.uf === undefined ? undefined : ufBySigla3(options.uf);
3745
+ if (options.uf !== undefined && !ufInfo)
3746
+ throw new ConfigError4(`UF inválida: ${String(options.uf)}`);
3747
+ const ufPadrao = (servico) => {
3748
+ if (options.uf === undefined || ufInfo === undefined) {
3749
+ throw new ConfigError4(`${servico} precisa da UF: informe NfeClientOptions.uf`);
3750
+ }
3751
+ return { uf: options.uf, cUF: ufInfo.cUF };
3752
+ };
3753
+ const offsetDe = (uf) => options.offsetMinutes ?? offsetDaUf(uf);
3754
+ const idLote = () => {
3755
+ const id = options.idLote ? options.idLote() : String(options.clock.now().getTime()).slice(-15);
3756
+ if (!/^[0-9]{1,15}$/.test(id))
3757
+ throw new ConfigError4(`idLote inválido: ${id}`);
3758
+ return id;
3759
+ };
3760
+ const endpointNfce = (servico, uf) => options.nfceEndpoint ? options.nfceEndpoint(servico, uf) : nfceEndpoint({ ambiente: options.ambiente, servico, uf });
3761
+ const endpoint = (servico, mod = "55") => {
3762
+ const { uf } = ufPadrao(servico);
3763
+ if (mod === "65")
3764
+ return endpointNfce(servico, uf);
3765
+ return nfeEndpoint({
3766
+ ambiente: options.ambiente,
3767
+ servico,
3768
+ uf,
3769
+ ...options.contingencia === undefined ? {} : { contingencia: options.contingencia }
3770
+ });
3771
+ };
3772
+ const endpointDaChave = (servico, c, naUf = false) => {
3773
+ if (c.mod === "65")
3774
+ return endpointNfce(servico, c.uf);
3775
+ const svc = naUf || c.tpEmis === undefined ? undefined : SVC_DO_TPEMIS[c.tpEmis];
3776
+ return nfeEndpoint({
3777
+ ambiente: options.ambiente,
3778
+ servico,
3779
+ ...svc === undefined ? { uf: c.uf } : { autorizador: svc }
3780
+ });
3781
+ };
3782
+ const call = (ep, servico, mensagem, retorno, signal) => chamar({
3783
+ transport: options.transport,
3784
+ endpoint: ep,
3785
+ servico,
3786
+ mensagem,
3787
+ retorno,
3788
+ logger,
3789
+ ...options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs },
3790
+ ...signal === undefined ? {} : { signal }
3791
+ });
3792
+ const autorPadrao = (a, path) => {
3793
+ const autor = a ?? options.autor;
3794
+ if (!autor)
3795
+ throw new ConfigError4(`informe o CNPJ ou CPF do autor (${path} ou NfeClientOptions.autor)`);
3796
+ return documentoAutor(autor, path);
3797
+ };
3798
+ async function consultarRecibo(nRec, nfeAssinada, opcoes = {}) {
3799
+ if (!/^[0-9]{15}$/.test(nRec))
3800
+ throw new ConfigError4(`número de recibo inválido: ${nRec}`);
3801
+ const a = nfeAssinada === undefined ? undefined : documentoAssinado(nfeAssinada, "NFe", "infNFe");
3802
+ const c = a === undefined ? undefined : chaveDoDocumento(a);
3803
+ if (c !== undefined && opcoes.mod !== undefined && opcoes.mod !== c.mod) {
3804
+ throw new ConfigError4(`mod ${opcoes.mod} não é o da NF-e assinada (${c.mod})`);
3805
+ }
3806
+ const msg = envelope("consReciNFe", "4.00", [`<tpAmb>${tpAmb}</tpAmb><nRec>${nRec}</nRec>`]);
3807
+ const ep = c === undefined ? endpoint("NFeRetAutorizacao", opcoes.mod ?? "55") : endpointDaChave("NFeRetAutorizacao", c);
3808
+ const r = await call(ep, "NFeRetAutorizacao", msg, "retConsReciNFe", opcoes.signal);
3809
+ const v = decode(TRetConsReciNFe, r.ret, r.doc.source).value;
3810
+ if (v.nRec !== undefined && v.nRec !== nRec) {
3811
+ throw new ProtocolError4("retorno de outro recibo", { details: { nRec: v.nRec } });
3812
+ }
3813
+ const status = { cStat: v.cStat, xMotivo: v.xMotivo };
3814
+ logger.info("nfe.recibo", { nRec, cStat: v.cStat });
3815
+ if (cstatEm(v.cStat, "loteEmProcessamento") || cstatEm(v.cStat, "loteRecebido"))
3816
+ return pending(status, { ref: nRec });
3817
+ if (cstatEm(v.cStat, "loteProcessado")) {
3818
+ const el = protNFeDaChave(r.ret, a);
3819
+ if (!el)
3820
+ throw new ProtocolError4("lote processado sem o protNFe da NF-e", { details: { nRec } });
3821
+ return desfechoDoProtocolo(lerProtocolo(r.doc, el), a);
3822
+ }
3823
+ return rejeitado(status);
3824
+ }
3825
+ async function consultar(chave, nfeAssinada) {
3826
+ const c = chaveValida(chave, "chNFe");
3827
+ const a = nfeAssinada === undefined ? undefined : documentoAssinado(nfeAssinada, "NFe", "infNFe");
3828
+ if (a && a.id !== `NFe${c.chave}`)
3829
+ throw new ConfigError4("a NF-e assinada não é a da chave consultada");
3830
+ const msg = serializeRoot(consSitNFeElement, { versao: "4.00", tpAmb, xServ: "CONSULTAR", chNFe: c.chave });
3831
+ const ep = endpointDaChave("NfeConsultaProtocolo", c);
3832
+ const r = await call(ep, "NfeConsultaProtocolo", msg, "retConsSitNFe");
3833
+ const v = decode(TRetConsSitNFe, r.ret, r.doc.source).value;
3834
+ const status = { cStat: v.cStat, xMotivo: v.xMotivo };
3835
+ logger.info("nfe.consulta", { chNFe: c.chave, cStat: v.cStat });
3836
+ const situacao = cstatEm(v.cStat, "autorizada") ? "autorizada" : cstatEm(v.cStat, "cancelada") ? "cancelada" : cstatEm(v.cStat, "denegada") ? "denegada" : undefined;
3837
+ if (situacao === undefined)
3838
+ return rejeitado(status);
3839
+ const protEl = firstChild5(r.ret, "protNFe", NFE_NS4);
3840
+ const eventos = childElements2(r.ret).filter((e) => e.local === "procEventoNFe" && e.ns === NFE_NS4).map((e) => avulso(r.doc, e));
3841
+ let protocolo;
3842
+ let digValConfere;
3843
+ if (protEl) {
3844
+ const { p, embutido } = lerProtocolo(r.doc, protEl);
3845
+ if (p.chNFe !== c.chave) {
3846
+ throw new ProtocolError4("protocolo de outra chave de acesso na consulta", { details: { chNFe: p.chNFe } });
3847
+ }
3848
+ protocolo = p;
3849
+ if (a) {
3850
+ digValConfere = p.digVal !== undefined && p.digVal === a.digestValue;
3851
+ if (digValConfere)
3852
+ protocolo = { ...p, nfeProc: envelope("nfeProc", "4.00", [a.xml, embutido]) };
3853
+ }
3854
+ }
3855
+ const value = {
3856
+ chNFe: c.chave,
3857
+ situacao,
3858
+ eventos,
3859
+ ...protocolo === undefined ? {} : { protocolo },
3860
+ ...digValConfere === undefined ? {} : { digValConfere }
3861
+ };
3862
+ return situacao === "denegada" ? denied(status, value) : authorized(status, value);
3863
+ }
3864
+ async function enviarEvento(p) {
3865
+ const nSeq = p.nSeqEvento;
3866
+ if (!Number.isInteger(nSeq) || nSeq < 1 || nSeq > 99)
3867
+ throw new ConfigError4(`nSeqEvento inválido: ${nSeq}`);
3868
+ const nSeqEvento = String(nSeq);
3869
+ const id = `ID${p.tpEvento}${p.chave}${nSeqEvento.padStart(2, "0")}`;
3870
+ const inf = {
3871
+ Id: id,
3872
+ cOrgao: p.cOrgao,
3873
+ tpAmb,
3874
+ ...p.autor,
3875
+ chNFe: p.chave,
3876
+ dhEvento: formatDh(options.clock.now(), p.offsetMinutes),
3877
+ tpEvento: p.tpEvento,
3878
+ nSeqEvento,
3879
+ verEvento: EVENTO_VERSAO,
3880
+ detEvento: p.detEvento
3881
+ };
3882
+ const infXml = serialize3(p.ct, "infEvento", inf, NFE_NS4);
3883
+ const evento = `<evento xmlns="${NFE_NS4}" versao="${EVENTO_VERSAO}">${infXml}</evento>`;
3884
+ const infEl = firstChild5(parseXml6(evento).root, "infEvento", NFE_NS4);
3885
+ schemaIssues("evento", validate4(p.ct, infEl));
3886
+ const assinado = await signXml2(evento, { id }, options.signer);
3887
+ const msg = envelope("envEvento", EVENTO_VERSAO, [`<idLote>${idLote()}</idLote>`, assinado]);
3888
+ const r = await call(p.endpoint, "RecepcaoEvento", msg, "retEnvEvento");
3889
+ const v = decode(TRetEnvEvento, r.ret, r.doc.source).value;
3890
+ logger.info("nfe.evento", { chNFe: p.chave, tpEvento: p.tpEvento, cStat: v.cStat });
3891
+ if (!cstatEm(v.cStat, "loteEventoProcessado"))
3892
+ return rejeitado({ cStat: v.cStat, xMotivo: v.xMotivo });
3893
+ const retEl = childElements2(r.ret).find((e) => e.local === "retEvento" && e.ns === NFE_NS4);
3894
+ const ret = v.retEvento?.[0]?.infEvento;
3895
+ if (!retEl || !ret)
3896
+ throw new ProtocolError4("lote de evento processado sem retEvento");
3897
+ const divergentes = [
3898
+ ["chNFe", ret.chNFe, p.chave],
3899
+ ["tpEvento", ret.tpEvento, p.tpEvento],
3900
+ ["nSeqEvento", ret.nSeqEvento === undefined ? undefined : String(Number(ret.nSeqEvento)), nSeqEvento]
3901
+ ].filter(([, veio, enviado]) => veio !== undefined && veio !== enviado);
3902
+ if (divergentes.length > 0) {
3903
+ throw new ProtocolError4("retEvento de outro evento", {
3904
+ details: Object.fromEntries(divergentes.map(([k, veio]) => [k, veio]))
3905
+ });
3906
+ }
3907
+ const status = { cStat: ret.cStat, xMotivo: ret.xMotivo };
3908
+ if (!cstatEm(ret.cStat, "eventoRegistrado"))
3909
+ return rejeitado(status);
3910
+ return authorized(status, {
3911
+ chNFe: p.chave,
3912
+ tpEvento: p.tpEvento,
3913
+ nSeqEvento,
3914
+ dhRegEvento: ret.dhRegEvento,
3915
+ retEvento: avulso(r.doc, retEl),
3916
+ procEventoNFe: envelope("procEventoNFe", EVENTO_VERSAO, [assinado, sliceElement(r.doc, retEl)]),
3917
+ ...ret.nProt === undefined ? {} : { nProt: ret.nProt }
3918
+ });
3919
+ }
3920
+ const client = {
3921
+ options,
3922
+ async statusServico(opcoes) {
3923
+ const { cUF } = ufPadrao("NfeStatusServico");
3924
+ const msg = serializeRoot(consStatServElement, { versao: "4.00", tpAmb, cUF, xServ: "STATUS" });
3925
+ const r = await call(endpoint("NfeStatusServico", opcoes?.mod), "NfeStatusServico", msg, "retConsStatServ");
3926
+ const v = decode(TRetConsStatServ, r.ret, r.doc.source).value;
3927
+ const status = { cStat: v.cStat, xMotivo: v.xMotivo };
3928
+ logger.info("nfe.status", { cStat: v.cStat });
3929
+ if (!cstatEm(v.cStat, "servicoEmOperacao"))
3930
+ return rejeitado(status);
3931
+ return authorized(status, {
3932
+ cUF: v.cUF,
3933
+ verAplic: v.verAplic,
3934
+ dhRecbto: v.dhRecbto,
3935
+ ...v.tMed === undefined ? {} : { tMed: v.tMed },
3936
+ ...v.dhRetorno === undefined ? {} : { dhRetorno: v.dhRetorno },
3937
+ ...v.xObs === undefined ? {} : { xObs: v.xObs }
3938
+ });
3939
+ },
3940
+ async autorizar(nfeAssinada, opcoes = {}) {
3941
+ const a = documentoAssinado(nfeAssinada, "NFe", "infNFe");
3942
+ const sincrono = opcoes.sincrono ?? true;
3943
+ const msg = envelope("enviNFe", "4.00", [
3944
+ `<idLote>${idLote()}</idLote><indSinc>${sincrono ? "1" : "0"}</indSinc>`,
3945
+ a.xml
3946
+ ]);
3947
+ const ep = endpointDaChave("NFeAutorizacao", chaveDoDocumento(a));
3948
+ const r = await call(ep, "NFeAutorizacao", msg, "retEnviNFe", opcoes.signal);
3949
+ const v = decode(TRetEnviNFe, r.ret, r.doc.source).value;
3950
+ const status = { cStat: v.cStat, xMotivo: v.xMotivo };
3951
+ logger.info("nfe.autorizacao", { chNFe: a.id.slice(3), cStat: v.cStat, sincrono });
3952
+ if (cstatEm(v.cStat, "loteRecebido")) {
3953
+ const nRec = v.infRec?.nRec;
3954
+ if (!nRec)
3955
+ throw new ProtocolError4("lote recebido sem número de recibo");
3956
+ const tMed = Number(v.infRec?.tMed ?? "0");
3957
+ return pending(status, { ref: nRec, retryAfterMs: Math.max(1, tMed) * 1000 });
3958
+ }
3959
+ const protEl = protNFeDaChave(r.ret, a);
3960
+ if (protEl)
3961
+ return desfechoDoProtocolo(lerProtocolo(r.doc, protEl), a);
3962
+ return rejeitado(status);
3963
+ },
3964
+ consultarRecibo,
3965
+ async aguardarRecibo(nRec, nfeAssinada, politica = {}) {
3966
+ const max = politica.maxTentativas ?? 10;
3967
+ const minimo = politica.esperaMinimaMs ?? 2000;
3968
+ const mult = politica.multiplicador ?? 1.5;
3969
+ const teto = politica.esperaMaximaMs ?? 30000;
3970
+ if (!(max >= 1) || !(minimo >= 0) || !(mult >= 1) || !(teto >= minimo)) {
3971
+ throw new ConfigError4("política de consulta do recibo inválida", { details: { max, minimo, mult, teto } });
3972
+ }
3973
+ let espera = minimo;
3974
+ let ultimo;
3975
+ for (let i = 0;i < max; i++) {
3976
+ await sleep(espera, politica.signal);
3977
+ ultimo = await consultarRecibo(nRec, nfeAssinada, politica);
3978
+ if (ultimo.status !== "pending")
3979
+ return ultimo;
3980
+ espera = Math.min(teto, Math.max(minimo, Math.round(espera * mult), ultimo.retryAfterMs ?? 0));
3981
+ }
3982
+ return ultimo;
3983
+ },
3984
+ consultar,
3985
+ async cancelar(p) {
3986
+ const c = chaveValida(p.chave, "chave");
3987
+ return enviarEvento({
3988
+ ct: TEventoCanc,
3989
+ tpEvento: "110111",
3990
+ chave: c.chave,
3991
+ nSeqEvento: 1,
3992
+ cOrgao: c.cUF,
3993
+ autor: autorDoEmitente(p.autor, c),
3994
+ detEvento: { versao: EVENTO_VERSAO, descEvento: "Cancelamento", nProt: p.nProt, xJust: p.xJust },
3995
+ endpoint: endpointDaChave("RecepcaoEvento", c),
3996
+ offsetMinutes: offsetDe(c.uf)
3997
+ });
3998
+ },
3999
+ async cancelarPorSubstituicao(p) {
4000
+ const c = chaveValida(p.chave, "chave");
4001
+ if (c.mod !== "65") {
4002
+ throw new ValidationError2("cancelamento por substituição só existe para NFC-e", [
4003
+ {
4004
+ path: "chave",
4005
+ code: "modelo_nao_suportado",
4006
+ message: "O evento 110112 é exclusivo da NFC-e (modelo 65)"
4007
+ }
4008
+ ]);
4009
+ }
4010
+ const ref = chaveValida(p.chNFeRef, "chNFeRef");
4011
+ const detEvento = {
4012
+ versao: EVENTO_VERSAO,
4013
+ descEvento: "Cancelamento por substituicao",
4014
+ cOrgaoAutor: p.cOrgaoAutor,
4015
+ tpAutor: p.tpAutor ?? "1",
4016
+ verAplic: p.verAplic,
4017
+ nProt: p.nProt,
4018
+ xJust: p.xJust,
4019
+ chNFeRef: ref.chave
4020
+ };
4021
+ return enviarEvento({
4022
+ ct: TEventoCancSubst,
4023
+ tpEvento: "110112",
4024
+ chave: c.chave,
4025
+ nSeqEvento: 1,
4026
+ cOrgao: c.cUF,
4027
+ autor: autorDoEmitente(p.autor, c),
4028
+ detEvento,
4029
+ endpoint: endpointDaChave("RecepcaoEvento", c),
4030
+ offsetMinutes: offsetDe(c.uf)
4031
+ });
4032
+ },
4033
+ async cartaCorrecao(p) {
4034
+ const c = chaveValida(p.chave, "chave");
4035
+ if (!Number.isInteger(p.nSeqEvento) || p.nSeqEvento < 1 || p.nSeqEvento > 20) {
4036
+ throw new ConfigError4(`nSeqEvento da CC-e vai de 1 a 20: ${p.nSeqEvento}`);
4037
+ }
4038
+ return enviarEvento({
4039
+ ct: TEventoCce,
4040
+ tpEvento: "110110",
4041
+ chave: c.chave,
4042
+ nSeqEvento: p.nSeqEvento,
4043
+ cOrgao: c.cUF,
4044
+ autor: autorDoEmitente(p.autor, c),
4045
+ detEvento: {
4046
+ versao: EVENTO_VERSAO,
4047
+ descEvento: "Carta de Correção",
4048
+ xCorrecao: p.xCorrecao,
4049
+ xCondUso: XCONDUSO
4050
+ },
4051
+ endpoint: endpointDaChave("RecepcaoEvento", c, true),
4052
+ offsetMinutes: offsetDe(c.uf)
4053
+ });
4054
+ },
4055
+ async manifestar(p) {
4056
+ const c = chaveValida(p.chave, "chave");
4057
+ const m = MANIFESTACOES[p.tipo];
4058
+ if (!m)
4059
+ throw new ConfigError4(`tipo de manifestação desconhecido: ${String(p.tipo)}`);
4060
+ return enviarEvento({
4061
+ ct: m.ct,
4062
+ tpEvento: m.tpEvento,
4063
+ chave: c.chave,
4064
+ nSeqEvento: 1,
4065
+ cOrgao: "91",
4066
+ autor: autorPadrao(p.autor, "autor"),
4067
+ detEvento: {
4068
+ versao: EVENTO_VERSAO,
4069
+ descEvento: m.descEvento,
4070
+ ...p.xJust === undefined ? {} : { xJust: p.xJust }
4071
+ },
4072
+ endpoint: nfeEndpoint({ ambiente: options.ambiente, servico: "RecepcaoEvento", autorizador: "AN" }),
4073
+ offsetMinutes: offsetDe(options.uf ?? c.uf)
4074
+ });
4075
+ },
4076
+ async inutilizar(p) {
4077
+ const autor = autorPadrao(p.autor, "autor");
4078
+ if (!("CNPJ" in autor)) {
4079
+ throw new ValidationError2("inutilização não se aplica ao emitente pessoa física", [
4080
+ {
4081
+ path: "autor.CPF",
4082
+ code: "inutilizacao_emitente_cpf",
4083
+ message: "O pedido de inutilização só existe para emitente CNPJ (NT 2018.001 v1.10, item 6.1)"
4084
+ }
4085
+ ]);
4086
+ }
4087
+ const cnpj = autor.CNPJ;
4088
+ const { uf, cUF } = ufPadrao("NfeInutilizacao");
4089
+ const anoTxt = String(p.ano);
4090
+ const ano = anoTxt.length === 4 ? anoTxt.slice(2) : anoTxt.padStart(2, "0");
4091
+ const mod = p.mod ?? "55";
4092
+ const serie = String(p.serie);
4093
+ const ini = String(p.nNFIni);
4094
+ const fin = String(p.nNFFin);
4095
+ for (const [k, x, re] of [
4096
+ ["ano", ano, /^[0-9]{2}$/],
4097
+ ["serie", serie, /^(0|[1-9][0-9]{0,2})$/],
4098
+ ["nNFIni", ini, /^[1-9][0-9]{0,8}$/],
4099
+ ["nNFFin", fin, /^[1-9][0-9]{0,8}$/]
4100
+ ]) {
4101
+ if (!re.test(x))
4102
+ throw new ConfigError4(`${k} inválido para inutilização: ${x}`);
4103
+ }
4104
+ if (Number(fin) < Number(ini))
4105
+ throw new ConfigError4("nNFFin menor que nNFIni");
4106
+ if (Number(serie) >= 910 && Number(serie) <= 969) {
4107
+ throw new ValidationError2("série de emitente pessoa física não se inutiliza", [
4108
+ {
4109
+ path: "serie",
4110
+ code: "inutilizacao_serie_cpf",
4111
+ message: "Série 910 a 969 identifica emitente CPF: a SEFAZ rejeita com 266 (NT 2018.001 v1.10, regra I02a)"
4112
+ }
4113
+ ]);
4114
+ }
4115
+ const id = `ID${cUF}${ano}${cnpj}${mod}${serie.padStart(3, "0")}${ini.padStart(9, "0")}${fin.padStart(9, "0")}`;
4116
+ const inf = {
4117
+ Id: id,
4118
+ tpAmb,
4119
+ xServ: "INUTILIZAR",
4120
+ cUF,
4121
+ ano,
4122
+ CNPJ: cnpj,
4123
+ mod,
4124
+ serie,
4125
+ nNFIni: ini,
4126
+ nNFFin: fin,
4127
+ xJust: p.xJust
4128
+ };
4129
+ const infXml = serialize3(TInutNFe_infInut, "infInut", inf, NFE_NS4);
4130
+ const inut = envelope("inutNFe", "4.00", [infXml]);
4131
+ const infEl = firstChild5(parseXml6(inut).root, "infInut", NFE_NS4);
4132
+ schemaIssues("pedido de inutilização", validate4(TInutNFe_infInut, infEl));
4133
+ const assinado = await signXml2(inut, { id }, options.signer);
4134
+ const ep = mod === "65" ? endpointNfce("NfeInutilizacao", uf) : nfeEndpoint({ ambiente: options.ambiente, servico: "NfeInutilizacao", uf });
4135
+ const r = await call(ep, "NfeInutilizacao", assinado, "retInutNFe");
4136
+ const v = decode(TRetInutNFe, r.ret, r.doc.source).value;
4137
+ const status = { cStat: v.infInut.cStat, xMotivo: v.infInut.xMotivo };
4138
+ logger.info("nfe.inutilizacao", { id, cStat: status.cStat });
4139
+ if (!cstatEm(status.cStat, "inutilizacaoHomologada"))
4140
+ return rejeitado(status);
4141
+ const r0 = v.infInut;
4142
+ const n = (x) => x === undefined ? undefined : String(Number(x));
4143
+ const confere = [
4144
+ ["ano", r0.ano, ano],
4145
+ ["CNPJ", r0.CNPJ ?? r0.CPF, cnpj],
4146
+ ["mod", r0.mod, mod],
4147
+ ["serie", n(r0.serie), String(Number(serie))],
4148
+ ["nNFIni", n(r0.nNFIni), String(Number(ini))],
4149
+ ["nNFFin", n(r0.nNFFin), String(Number(fin))]
4150
+ ];
4151
+ const fora = confere.filter(([, veio, pedido]) => veio !== undefined && veio !== pedido);
4152
+ if (fora.length > 0) {
4153
+ throw new ProtocolError4("retInutNFe de outra faixa", {
4154
+ details: Object.fromEntries(fora.map(([k, v]) => [k, v]))
4155
+ });
4156
+ }
4157
+ return authorized(status, {
4158
+ dhRecbto: v.infInut.dhRecbto,
4159
+ retInutNFe: avulso(r.doc, r.ret),
4160
+ procInutNFe: envelope("ProcInutNFe", "4.00", [assinado, sliceElement(r.doc, r.ret)]),
4161
+ ...v.infInut.nProt === undefined ? {} : { nProt: v.infInut.nProt }
4162
+ });
4163
+ },
4164
+ async consultarCadastro(p) {
4165
+ const doc = "CNPJ" in p ? documentoAutor({ CNPJ: p.CNPJ }, "CNPJ") : ("CPF" in p) ? documentoAutor({ CPF: p.CPF }, "CPF") : { IE: p.IE.replace(/[^0-9A-Za-z]/g, "").toUpperCase() };
4166
+ const msg = serializeRoot(ConsCadElement, { versao: "2.00", infCons: { xServ: "CONS-CAD", UF: p.uf, ...doc } });
4167
+ const ep = nfeEndpoint({ ambiente: options.ambiente, servico: "NfeConsultaCadastro", uf: p.uf });
4168
+ const r = await call(ep, "NfeConsultaCadastro", msg, "retConsCad");
4169
+ const v = decode(TRetConsCad, r.ret, r.doc.source).value;
4170
+ const i = v.infCons;
4171
+ const status = { cStat: i.cStat, xMotivo: i.xMotivo };
4172
+ logger.info("nfe.cadastro", { uf: p.uf, cStat: i.cStat });
4173
+ if (!cstatEm(i.cStat, "cadastroEncontrado"))
4174
+ return rejeitado(status);
4175
+ return authorized(status, { UF: i.UF, dhCons: i.dhCons, infCad: i.infCad ?? [] });
4176
+ },
4177
+ async distribuicaoDFe(consulta, opcoes = {}) {
4178
+ const autor = autorPadrao(opcoes.autor, "autor");
4179
+ const nsu = (x, k) => {
4180
+ const s = String(x);
4181
+ if (!/^[0-9]{1,15}$/.test(s))
4182
+ throw new ConfigError4(`${k} inválido: ${s}`);
4183
+ return s.padStart(15, "0");
4184
+ };
4185
+ const grupo = "ultNSU" in consulta ? { distNSU: { ultNSU: nsu(consulta.ultNSU, "ultNSU") } } : ("NSU" in consulta) ? { consNSU: { NSU: nsu(consulta.NSU, "NSU") } } : { consChNFe: { chNFe: chaveValida(consulta.chNFe, "chNFe").chave } };
4186
+ const cUFAutor = opcoes.cUFAutor ?? ufPadrao("NFeDistribuicaoDFe").cUF;
4187
+ if (ufByCUf2(cUFAutor) === undefined)
4188
+ throw new ConfigError4(`cUFAutor inválido: ${cUFAutor}`);
4189
+ const msg = serializeRoot(distDFeIntElement, {
4190
+ versao: "1.01",
4191
+ tpAmb,
4192
+ cUFAutor,
4193
+ ...autor,
4194
+ ...grupo
4195
+ });
4196
+ const ep = nfeEndpoint({ ambiente: options.ambiente, servico: "NFeDistribuicaoDFe" });
4197
+ const r = await call(ep, "NFeDistribuicaoDFe", msg, "retDistDFeInt");
4198
+ const v = decode(retDistDFeInt, r.ret, r.doc.source).value;
4199
+ const status = { cStat: v.cStat, xMotivo: v.xMotivo };
4200
+ logger.info("nfe.distribuicao", { cStat: v.cStat, ultNSU: v.ultNSU, maxNSU: v.maxNSU });
4201
+ const base = { ultNSU: v.ultNSU, maxNSU: v.maxNSU, dhResp: v.dhResp };
4202
+ if (cstatEm(v.cStat, "distribuicaoNenhumDocumento"))
4203
+ return authorized(status, { ...base, documentos: [] });
4204
+ if (!cstatEm(v.cStat, "distribuicaoDocumentos"))
4205
+ return rejeitado(status);
4206
+ const documentos = [];
4207
+ for (const z of v.loteDistDFeInt?.docZip ?? []) {
4208
+ const xml = await gunzipBase64(z.$text);
4209
+ documentos.push(documentoDistribuido(z.NSU ?? "", z.schema, xml));
4210
+ }
4211
+ return authorized(status, { ...base, documentos });
4212
+ }
4213
+ };
4214
+ return client;
4215
+ }
4216
+ function documentoDistribuido(NSU, schema, xml) {
4217
+ const nome = schema.replace(/_v?\d.*$/, "");
4218
+ const base = { NSU, schema, xml };
4219
+ if (nome === "resNFe")
4220
+ return { ...base, tipo: "resNFe", resNFe: decodeXml(resNFeElement, xml).value };
4221
+ if (nome === "resEvento")
4222
+ return { ...base, tipo: "resEvento", resEvento: decodeXml(resEventoElement, xml).value };
4223
+ if (nome === "procNFe")
4224
+ return { ...base, tipo: "procNFe" };
4225
+ if (nome === "procEventoNFe")
4226
+ return { ...base, tipo: "procEventoNFe" };
4227
+ return { ...base, tipo: "outro" };
4228
+ }
4229
+ // packages/nfe/src/services/recuperar.ts
4230
+ import { firstChild as firstChild6, parseXml as parseXml7, textOf as textOf3 } from "@sinete/core/xml";
4231
+ function campo(el, local) {
4232
+ const c = firstChild6(el, local, NFE_NS4);
4233
+ return c === undefined ? undefined : textOf3(c).trim();
4234
+ }
4235
+ function lerProcEvento(xml) {
4236
+ let doc;
4237
+ try {
4238
+ doc = parseXml7(xml);
4239
+ } catch {
4240
+ return;
4241
+ }
4242
+ const evento = firstChild6(doc.root, "evento", NFE_NS4);
4243
+ const pedido = evento === undefined ? undefined : firstChild6(evento, "infEvento", NFE_NS4);
4244
+ const retEl = firstChild6(doc.root, "retEvento", NFE_NS4);
4245
+ const ret = retEl === undefined ? undefined : firstChild6(retEl, "infEvento", NFE_NS4);
4246
+ if (doc.root.local !== "procEventoNFe" || pedido === undefined || retEl === undefined || ret === undefined) {
4247
+ return;
4248
+ }
4249
+ const cStat = campo(ret, "cStat");
4250
+ const chNFe = campo(ret, "chNFe");
4251
+ const tpEvento = campo(ret, "tpEvento");
4252
+ const nSeq = campo(ret, "nSeqEvento");
4253
+ const dhRegEvento = campo(ret, "dhRegEvento");
4254
+ if (cStat === undefined || !cstatEm(cStat, "eventoRegistrado"))
4255
+ return;
4256
+ if (chNFe === undefined || tpEvento === undefined || nSeq === undefined)
4257
+ return;
4258
+ const nSeqPedido = campo(pedido, "nSeqEvento");
4259
+ if (campo(pedido, "chNFe") !== chNFe || campo(pedido, "tpEvento") !== tpEvento)
4260
+ return;
4261
+ if (nSeqPedido === undefined || Number(nSeqPedido) !== Number(nSeq))
4262
+ return;
4263
+ if (chNFe === undefined || tpEvento === undefined || nSeq === undefined || dhRegEvento === undefined)
4264
+ return;
4265
+ const nProt = campo(ret, "nProt");
4266
+ return {
4267
+ chNFe,
4268
+ tpEvento,
4269
+ nSeqEvento: String(Number(nSeq)),
4270
+ dhRegEvento,
4271
+ retEvento: sliceElement(doc, retEl, ""),
4272
+ procEventoNFe: xml,
4273
+ ...nProt === undefined ? {} : { nProt }
4274
+ };
4275
+ }
4276
+ async function recuperarEventoRegistrado(client, chave, tpEvento) {
4277
+ const consulta = await client.consultar(chave);
4278
+ if (consulta.status !== "authorized" && consulta.status !== "denied")
4279
+ return { registrado: false, consulta };
4280
+ let achado;
4281
+ for (const xml of consulta.value.eventos) {
4282
+ const e = lerProcEvento(xml);
4283
+ if (e === undefined || e.chNFe !== consulta.value.chNFe || e.tpEvento !== tpEvento)
4284
+ continue;
4285
+ if (achado === undefined || Number(e.nSeqEvento) > Number(achado.nSeqEvento))
4286
+ achado = e;
4287
+ }
4288
+ return achado === undefined ? { registrado: false, consulta } : { registrado: true, evento: achado, consulta };
4289
+ }
4290
+ // packages/nfe/src/services/resolver.ts
4291
+ import { authorized as authorized2, denied as denied2 } from "@sinete/core";
4292
+ var CHAVE_NO_MOTIVO = /\[\s*chNFe\s*:\s*([0-9]{6}[0-9A-Z]{12}[0-9]{26})\s*\]/i;
4293
+ function chaveDaDuplicidade(xMotivo) {
4294
+ return CHAVE_NO_MOTIVO.exec(xMotivo)?.[1]?.toUpperCase();
4295
+ }
4296
+ async function resolverEnvioSemResposta(client, nfeAssinada, anterior) {
4297
+ const a = documentoAssinado(nfeAssinada, "NFe", "infNFe");
4298
+ const chave = a.id.slice(3);
4299
+ if (anterior && anterior.status === "rejected" && cstatEm(anterior.cStat, "duplicidadeChaveDiferente")) {
4300
+ const outra = chaveDaDuplicidade(anterior.xMotivo);
4301
+ return { acao: "divergente", motivo: anterior, ...outra === undefined ? {} : { chNFe: outra } };
4302
+ }
4303
+ const consulta = await client.consultar(chave, nfeAssinada);
4304
+ if (consulta.status === "rejected") {
4305
+ if (cstatEm(consulta.cStat, "naoConsta"))
4306
+ return { acao: "reenviar", nfeAssinada: a.xml };
4307
+ if (cstatEm(consulta.cStat, "outraNfeNoNumero")) {
4308
+ const outra = chaveDaDuplicidade(consulta.xMotivo);
4309
+ return { acao: "divergente", motivo: consulta, ...outra === undefined ? {} : { chNFe: outra } };
4310
+ }
4311
+ return { acao: "indefinida", outcome: consulta };
4312
+ }
4313
+ if (consulta.status === "pending")
4314
+ return { acao: "indefinida", outcome: consulta };
4315
+ const v = consulta.value;
4316
+ const p = v.protocolo;
4317
+ if (!p)
4318
+ return { acao: "indefinida", outcome: consulta };
4319
+ const conteudo = p.digVal === undefined ? "sem-digval" : v.digValConfere === true ? "confere" : "difere";
4320
+ const protStatus = { cStat: p.cStat, xMotivo: p.xMotivo };
4321
+ if (v.situacao === "denegada")
4322
+ return { acao: "concluida", situacao: "denegada", conteudo, outcome: denied2(protStatus, p) };
4323
+ if (conteudo === "difere")
4324
+ return { acao: "divergente", chNFe: chave, consulta, motivo: consulta };
4325
+ if (conteudo === "sem-digval")
4326
+ return { acao: "sem-prova", situacao: v.situacao, consulta };
4327
+ if (p.nfeProc === undefined)
4328
+ return { acao: "indefinida", outcome: consulta };
4329
+ return { acao: "concluida", situacao: v.situacao, conteudo, outcome: authorized2(protStatus, p) };
4330
+ }
4331
+ export {
4332
+ Decimal,
4333
+ MotivoDesoneracaoIcms,
4334
+ NFCE_LIMITE_SEM_DESTINATARIO,
4335
+ NFE_ISSUE_CODES,
4336
+ NFE_NS3 as NFE_NS,
4337
+ TipoPagamento,
4338
+ XNOME_HOMOLOGACAO,
4339
+ XPROD_HOMOLOGACAO_NFCE,
4340
+ assinaturaQrCode,
4341
+ autorizadorContingencia,
4342
+ buildNfe,
4343
+ carregarDatasetEmbarcado,
4344
+ chaveDaDuplicidade,
4345
+ comQrCode,
4346
+ conferirEmitenteDoCertificado,
4347
+ createNfeClient,
4348
+ dec,
4349
+ documentoAssinado,
4350
+ exigenciaRespTec,
4351
+ formatDecimal,
4352
+ formatDh,
4353
+ formatProblem,
4354
+ gunzipBase64,
4355
+ hashCsrt,
4356
+ ibsCbsCalculator,
4357
+ localDaOperacao,
4358
+ nfeAssinadaDoProc,
4359
+ offsetDaUf,
4360
+ recuperarEventoRegistrado,
4361
+ resolverEnvioSemResposta,
4362
+ rotuloDoCaminho,
4363
+ signNfe,
4364
+ sliceElement,
4365
+ sum,
4366
+ urlsNfce
4367
+ };
4368
+
4369
+ //# debugId=91E6FDD0B4D20CBD64756E2164756E21
4370
+ //# sourceMappingURL=index.js.map