@nfewizard/shared 1.0.0 → 1.0.1

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 (83) hide show
  1. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/adapters/SchemaLoader.js +6 -0
  2. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/adapters/SchemaLoader.js.map +1 -1
  3. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/adapters/index.js +16 -0
  4. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/adapters/index.js.map +1 -1
  5. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/base/BaseNFSe.d.ts +42 -0
  6. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/base/BaseNFSe.js +176 -0
  7. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/base/BaseNFSe.js.map +1 -0
  8. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/base/GerarConsulta.js +37 -10
  9. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/base/GerarConsulta.js.map +1 -1
  10. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/base/SaveFiles.js +7 -1
  11. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/base/SaveFiles.js.map +1 -1
  12. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/base/index.d.ts +1 -0
  13. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/base/index.js +17 -0
  14. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/base/index.js.map +1 -1
  15. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/config/NFSeServicosUrl.json +22 -0
  16. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/config/soapMethod.json +20 -0
  17. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/environment/AxiosHttpClient.js +16 -0
  18. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/environment/AxiosHttpClient.js.map +1 -1
  19. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/environment/HttpClientBuilder.js +16 -0
  20. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/environment/HttpClientBuilder.js.map +1 -1
  21. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/environment/LoadCertificate.js +16 -0
  22. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/environment/LoadCertificate.js.map +1 -1
  23. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/environment/ValidateEnvironment.js +16 -0
  24. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/environment/ValidateEnvironment.js.map +1 -1
  25. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/environment/index.js +16 -0
  26. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/environment/index.js.map +1 -1
  27. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/exceptions/ErrorContext.js +16 -0
  28. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/exceptions/ErrorContext.js.map +1 -1
  29. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/exceptions/JsonArrayTransporter.js +16 -0
  30. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/exceptions/JsonArrayTransporter.js.map +1 -1
  31. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/exceptions/index.js +15 -4
  32. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/exceptions/index.js.map +1 -1
  33. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/exceptions/logger.js +16 -0
  34. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/exceptions/logger.js.map +1 -1
  35. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/index.js +16 -0
  36. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/index.js.map +1 -1
  37. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/utils/Utility.d.ts +29 -2
  38. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/utils/Utility.js +92 -1
  39. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/utils/Utility.js.map +1 -1
  40. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/utils/index.js +16 -0
  41. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/src/utils/index.js.map +1 -1
  42. package/.rollup.cache/home/marco/Documents/projetos/NFeWizard/nfewizard-io/packages/shared/dist/tsconfig.tsbuildinfo +1 -1
  43. package/README.md +3 -3
  44. package/dist/index.cjs +462 -13
  45. package/dist/index.cjs.map +1 -1
  46. package/dist/index.mjs +462 -14
  47. package/dist/index.mjs.map +1 -1
  48. package/dist/src/base/BaseNFSe.d.ts +42 -0
  49. package/dist/src/base/index.d.ts +1 -0
  50. package/dist/src/utils/Utility.d.ts +29 -2
  51. package/dist/tsconfig.tsbuildinfo +1 -1
  52. package/package.json +2 -2
  53. package/resources/schemas/CNC_v1.00.xsd +14 -0
  54. package/resources/schemas/DPS_v1.01.xsd +14 -0
  55. package/resources/schemas/NFSe_v1.01.xsd +15 -0
  56. package/resources/schemas/evento_v1.01.xsd +15 -0
  57. package/resources/schemas/nfse/CNC_v1.00.xsd +14 -0
  58. package/resources/schemas/nfse/DPS_v1.01.xsd +14 -0
  59. package/resources/schemas/nfse/NFSe_v1.01.xsd +15 -0
  60. package/resources/schemas/nfse/eventoAtorInteressado_v1.00.xsd +9 -0
  61. package/resources/schemas/nfse/eventoCancNFe_v1.00.xsd +9 -0
  62. package/resources/schemas/nfse/eventoCancSubst_v1.00.xsd +9 -0
  63. package/resources/schemas/nfse/eventoEPEC_v0.01.xsd +267 -0
  64. package/resources/schemas/nfse/eventoRemIndus_v1.00.xsd +9 -0
  65. package/resources/schemas/nfse/evento_v1.01.xsd +15 -0
  66. package/resources/schemas/nfse/pedRegEvento_v1.01.xsd +15 -0
  67. package/resources/schemas/nfse/tiposBasico_v1.03.xsd +834 -0
  68. package/resources/schemas/nfse/tiposBasico_v3.10.xsd +833 -0
  69. package/resources/schemas/nfse/tiposBasico_v4.00.xsd +598 -0
  70. package/resources/schemas/nfse/tiposBasicosCcgConsGTIN_v1.00.xsd +84 -0
  71. package/resources/schemas/nfse/tiposCnc_v1.00.xsd +166 -0
  72. package/resources/schemas/nfse/tiposComplexos_v1.01.xsd +2677 -0
  73. package/resources/schemas/nfse/tiposDistDFe_v1.01.xsd +1 -0
  74. package/resources/schemas/nfse/tiposEventos_v1.01.xsd +780 -0
  75. package/resources/schemas/nfse/tiposSimples_v1.01.xsd +1774 -0
  76. package/resources/schemas/nfse/xmldsig-core-schema.xsd +318 -0
  77. package/resources/schemas/nfse/xmldsig-core-schema_v1.01.xsd +98 -0
  78. package/resources/schemas/pedRegEvento_v1.01.xsd +15 -0
  79. package/resources/schemas/tiposCnc_v1.00.xsd +166 -0
  80. package/resources/schemas/tiposComplexos_v1.01.xsd +2677 -0
  81. package/resources/schemas/tiposEventos_v1.01.xsd +780 -0
  82. package/resources/schemas/tiposSimples_v1.01.xsd +1774 -0
  83. package/resources/schemas/xmldsig-core-schema.xsd +318 -0
package/dist/index.mjs CHANGED
@@ -7,6 +7,7 @@ import { format } from 'date-fns';
7
7
  import xml2js from 'xml2js';
8
8
  import { SignedXml } from 'xml-crypto';
9
9
  import { fileURLToPath } from 'url';
10
+ import crypto from 'crypto';
10
11
  import xsdValidator from 'xsd-schema-validator';
11
12
  import libxmljs from 'libxmljs2';
12
13
  import xsdAssembler from 'xsd-assembler';
@@ -15,6 +16,22 @@ import pem from 'pem';
15
16
  import https from 'https';
16
17
  import forge from 'node-forge';
17
18
 
19
+ /*
20
+ * This file is part of NFeWizard-io.
21
+ *
22
+ * NFeWizard-io is free software: you can redistribute it and/or modify
23
+ * it under the terms of the GNU General Public License as published by
24
+ * the Free Software Foundation, either version 3 of the License, or
25
+ * (at your option) any later version.
26
+ *
27
+ * NFeWizard-io is distributed in the hope that it will be useful,
28
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
29
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30
+ * GNU General Public License for more details.
31
+ *
32
+ * You should have received a copy of the GNU General Public License
33
+ * along with NFeWizard-io. If not, see <https://www.gnu.org/licenses/>.
34
+ */
18
35
  class JsonArrayTransport extends Transport {
19
36
  constructor(options) {
20
37
  super(options);
@@ -95,6 +112,22 @@ class JsonArrayTransport extends Transport {
95
112
  }
96
113
  }
97
114
 
115
+ /*
116
+ * This file is part of NFeWizard-io.
117
+ *
118
+ * NFeWizard-io is free software: you can redistribute it and/or modify
119
+ * it under the terms of the GNU General Public License as published by
120
+ * the Free Software Foundation, either version 3 of the License, or
121
+ * (at your option) any later version.
122
+ *
123
+ * NFeWizard-io is distributed in the hope that it will be useful,
124
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
125
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
126
+ * GNU General Public License for more details.
127
+ *
128
+ * You should have received a copy of the GNU General Public License
129
+ * along with NFeWizard-io. If not, see <https://www.gnu.org/licenses/>.
130
+ */
98
131
  class AppLogger {
99
132
  constructor() {
100
133
  this.isInitialized = false;
@@ -495,6 +528,196 @@ class BaseNFE {
495
528
  }
496
529
  }
497
530
 
531
+ class BaseNFSe {
532
+ constructor(environment, utility, xmlBuilder, metodo, axios, saveFiles, gerarConsulta) {
533
+ this.environment = environment;
534
+ this.utility = utility;
535
+ this.xmlBuilder = xmlBuilder;
536
+ this.metodo = metodo;
537
+ this.axios = axios;
538
+ this.saveFiles = saveFiles;
539
+ this.gerarConsulta = gerarConsulta;
540
+ }
541
+ /**
542
+ * Método de preparação dos dados - Deve ser implementado pelas subclasses
543
+ */
544
+ prepararDados(_data) {
545
+ throw new Error("O método 'prepararDados' não foi implementado na subclasse.");
546
+ }
547
+ /**
548
+ * Método para obter a URL base do webservice
549
+ */
550
+ getWebServiceUrl() {
551
+ return this.utility.getWebServiceUrlNFSe(this.metodo);
552
+ }
553
+ /**
554
+ * Método para obter o método HTTP (GET, POST, etc)
555
+ */
556
+ getHttpMethod() {
557
+ return 'POST'; // Padrão para NFSe
558
+ }
559
+ /**
560
+ * Método para obter o path adicional da URL (ex: /nfse/{chaveAcesso})
561
+ */
562
+ getUrlPath(_data) {
563
+ return '';
564
+ }
565
+ /**
566
+ * Método para obter query parameters
567
+ */
568
+ getQueryParams(_data) {
569
+ return {};
570
+ }
571
+ /**
572
+ * Executa a requisição ao webservice NFSe (REST API)
573
+ * @param {any} [data] - Dados opcionais usados para preparar a requisição.
574
+ * @returns {Promise<any>} A resposta do webservice em JSON.
575
+ */
576
+ async Exec(data) {
577
+ let requestData = null;
578
+ let webServiceUrl = '';
579
+ let responseInJson = undefined;
580
+ let response = {};
581
+ let errorResponse = null;
582
+ try {
583
+ // Prepara dados específicos
584
+ requestData = this.prepararDados(data);
585
+ // Obtém URL base
586
+ const baseUrl = this.getWebServiceUrl();
587
+ const path = this.getUrlPath(data);
588
+ const queryParams = this.getQueryParams(data);
589
+ // Monta URL completa
590
+ webServiceUrl = baseUrl + path;
591
+ if (Object.keys(queryParams).length > 0) {
592
+ const queryString = new URLSearchParams(queryParams).toString();
593
+ webServiceUrl += `?${queryString}`;
594
+ }
595
+ const httpMethod = this.getHttpMethod();
596
+ logger.http('Iniciando comunicação com o webservice NFSe', {
597
+ context: `BaseNFSe`,
598
+ method: this.metodo,
599
+ httpMethod,
600
+ url: webServiceUrl,
601
+ });
602
+ // Executa requisição REST
603
+ // Obtém o agent HTTPS do environment para garantir autenticação mútua TLS
604
+ const agent = this.environment.getHttpAgent();
605
+ const requestConfig = {
606
+ headers: {
607
+ 'Content-Type': 'application/json',
608
+ 'Accept': 'application/json',
609
+ },
610
+ // Garante que o httpsAgent seja usado explicitamente para autenticação mútua TLS
611
+ httpsAgent: agent
612
+ };
613
+ if (httpMethod === 'GET') {
614
+ response = await this.axios.get(webServiceUrl, requestConfig);
615
+ }
616
+ else if (httpMethod === 'POST') {
617
+ response = await this.axios.post(webServiceUrl, requestData, requestConfig);
618
+ }
619
+ else if (httpMethod === 'PUT') {
620
+ response = await this.axios.put(webServiceUrl, requestData, requestConfig);
621
+ }
622
+ else if (httpMethod === 'DELETE') {
623
+ response = await this.axios.delete(webServiceUrl, requestConfig);
624
+ }
625
+ logger.http('Comunicação concluída com sucesso', {
626
+ context: `BaseNFSe`,
627
+ method: this.metodo,
628
+ responseSize: response.data ? JSON.stringify(response.data).length : 0
629
+ });
630
+ // NFSe retorna JSON diretamente
631
+ responseInJson = response.data;
632
+ // Verifica se há erros na resposta
633
+ if (responseInJson) {
634
+ if (responseInJson.erros && Array.isArray(responseInJson.erros) && responseInJson.erros.length > 0) {
635
+ const primeiroErro = responseInJson.erros[0];
636
+ const mensagemErro = primeiroErro.descricao || primeiroErro.Descricao || 'Erro desconhecido';
637
+ throw new Error(mensagemErro);
638
+ }
639
+ if (responseInJson.Erros && Array.isArray(responseInJson.Erros) && responseInJson.Erros.length > 0) {
640
+ const primeiroErro = responseInJson.Erros[0];
641
+ const mensagemErro = primeiroErro.Descricao || primeiroErro.descricao || 'Erro desconhecido';
642
+ throw new Error(mensagemErro);
643
+ }
644
+ }
645
+ return responseInJson || {};
646
+ }
647
+ catch (error) {
648
+ // Armazena a resposta de erro para uso no finally
649
+ errorResponse = error.response;
650
+ // Tenta extrair mais informações do erro
651
+ let errorMessage = error.message || 'Erro desconhecido';
652
+ if (error.response) {
653
+ // Erro de resposta HTTP
654
+ // Tenta extrair mensagem do body da resposta
655
+ if (error.response.data) {
656
+ if (typeof error.response.data === 'string') {
657
+ errorMessage = `HTTP ${error.response.status}: ${error.response.data}`;
658
+ }
659
+ else if (error.response.data.erros && Array.isArray(error.response.data.erros) && error.response.data.erros.length > 0) {
660
+ // NFSe retorna erros em um array
661
+ const primeiroErro = error.response.data.erros[0];
662
+ const codigo = primeiroErro.codigo || primeiroErro.Codigo || '';
663
+ const descricao = primeiroErro.descricao || primeiroErro.Descricao || 'Erro desconhecido';
664
+ errorMessage = codigo ? `${codigo}: ${descricao}` : descricao;
665
+ }
666
+ else if (error.response.data.Erros && Array.isArray(error.response.data.Erros) && error.response.data.Erros.length > 0) {
667
+ // Variação com E maiúsculo
668
+ const primeiroErro = error.response.data.Erros[0];
669
+ const codigo = primeiroErro.Codigo || primeiroErro.codigo || '';
670
+ const descricao = primeiroErro.Descricao || primeiroErro.descricao || 'Erro desconhecido';
671
+ errorMessage = codigo ? `${codigo}: ${descricao}` : descricao;
672
+ }
673
+ else if (error.response.data.message) {
674
+ errorMessage = error.response.data.message;
675
+ }
676
+ else if (error.response.data.descricao) {
677
+ errorMessage = error.response.data.descricao;
678
+ }
679
+ else if (error.response.data.Descricao) {
680
+ errorMessage = error.response.data.Descricao;
681
+ }
682
+ else {
683
+ errorMessage = `HTTP ${error.response.status}: ${JSON.stringify(error.response.data)}`;
684
+ }
685
+ }
686
+ else {
687
+ errorMessage = `HTTP ${error.response.status}: ${error.response.statusText}`;
688
+ }
689
+ }
690
+ logger.error(``, error, {
691
+ context: `BaseNFSe][${this.metodo}`
692
+ });
693
+ throw new Error(errorMessage);
694
+ }
695
+ finally {
696
+ // Salva arquivos (se configurado)
697
+ // Para REST, salva o JSON da requisição
698
+ const xmlConsulta = requestData ? JSON.stringify(requestData, null, 2) : '';
699
+ this.saveFiles.salvaArquivos(xmlConsulta, responseInJson, errorResponse || response, this.metodo, '' // xmlConsultaSoap vazio para REST
700
+ );
701
+ }
702
+ }
703
+ }
704
+
705
+ /*
706
+ * This file is part of NFeWizard-io.
707
+ *
708
+ * NFeWizard-io is free software: you can redistribute it and/or modify
709
+ * it under the terms of the GNU General Public License as published by
710
+ * the Free Software Foundation, either version 3 of the License, or
711
+ * (at your option) any later version.
712
+ *
713
+ * NFeWizard-io is distributed in the hope that it will be useful,
714
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
715
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
716
+ * GNU General Public License for more details.
717
+ *
718
+ * You should have received a copy of the GNU General Public License
719
+ * along with NFeWizard-io. If not, see <https://www.gnu.org/licenses/>.
720
+ */
498
721
  class GerarConsulta {
499
722
  constructor(environment, utility, xmlBuilder) {
500
723
  this.environment = environment;
@@ -518,20 +741,31 @@ class GerarConsulta {
518
741
  async gerarConsulta(xmlConsulta, metodo, ambienteNacional = false, versao = "", mod = "NFe", rootTag = false, tag = "", dadosMsgTag = "nfeDadosMsg") {
519
742
  try {
520
743
  const config = this.environment.getConfig();
521
- // Valida Schema
522
- if (config.lib?.useForSchemaValidation !== 'validateSchemaJsBased') {
523
- logger.info(`Validando XML com xsd-schema-validator`, {
524
- context: 'GerarConsulta',
525
- obs: 'Validação necessita do JAVA instaldo no ambiente',
526
- });
527
- await this.utility.validateSchemaJavaBased(xmlConsulta, metodo);
744
+ // Capturando o schema path
745
+ const { schemaPath } = this.utility.getSchema(metodo);
746
+ // Valida Schema apenas se o schema path estiver definido
747
+ if (schemaPath) {
748
+ if (config.lib?.useForSchemaValidation !== 'validateSchemaJsBased') {
749
+ logger.info(`Validando XML com xsd-schema-validator`, {
750
+ context: 'GerarConsulta',
751
+ obs: 'Validação necessita do JAVA instaldo no ambiente',
752
+ });
753
+ await this.utility.validateSchemaJavaBased(xmlConsulta, metodo);
754
+ }
755
+ else {
756
+ logger.info(`Validando XML com xsd-assembler`, {
757
+ context: 'GerarConsulta',
758
+ obs: 'Validação com nodejs',
759
+ });
760
+ await this.utility.validateSchemaJsBased(xmlConsulta, metodo);
761
+ }
528
762
  }
529
763
  else {
530
- logger.info(`Validando XML com xsd-assembler`, {
764
+ logger.info(`Pulando validação de schema`, {
531
765
  context: 'GerarConsulta',
532
- obs: 'Validação com nodejs',
766
+ metodo,
767
+ obs: 'Schema XSD não disponível para este método',
533
768
  });
534
- await this.utility.validateSchemaJsBased(xmlConsulta, metodo);
535
769
  }
536
770
  // Capturando a url do método para o namespace xmlns
537
771
  const { method, action } = this.utility.getSoapInfo(config.dfe.UF, metodo);
@@ -592,8 +826,14 @@ class SaveFiles {
592
826
  const salvarArquivo = (data, prefix, path, fileType) => {
593
827
  const fileName = createFileName(prefix);
594
828
  const method = fileType === 'xml' ? 'salvaXML' : 'salvaJSON';
829
+ // Para REST API (NFSe), o data pode ser um objeto JSON mesmo quando fileType é 'xml'
830
+ // Neste caso, converte para string JSON
831
+ let dataToSave = data || '';
832
+ if (fileType === 'xml' && typeof data === 'object' && data !== null) {
833
+ dataToSave = JSON.stringify(data, null, 2);
834
+ }
595
835
  this.utility[method]({
596
- data: data || '',
836
+ data: dataToSave,
597
837
  fileName,
598
838
  metodo: metodo,
599
839
  path,
@@ -756,6 +996,12 @@ const getSchema = (metodo) => {
756
996
  NFEInutilizacao: `${pathSchemas}/inutNFe_v4.00.xsd`,
757
997
  NFERetAutorizacao: `${pathSchemas}/consReciNFe_v4.00.xsd`,
758
998
  CTeDistribuicaoDFe: `${pathSchemas}/cte/distDFeInt_v1.00.xsd`,
999
+ // NFSe - Schemas da Nota Fiscal de Serviços Eletrônica
1000
+ NFSe_Autorizacao: `${pathSchemas}/nfse/DPS_v1.01.xsd`,
1001
+ NFSe_Consulta: `${pathSchemas}/nfse/NFSe_v1.01.xsd`,
1002
+ NFSe_Distribuicao: `${pathSchemas}/nfse/NFSe_v1.01.xsd`,
1003
+ NFSe_Eventos: `${pathSchemas}/nfse/pedRegEvento_v1.01.xsd`,
1004
+ NFSe_ParametrosMunicipais: undefined, // API REST - não usa XML schema
759
1005
  };
760
1006
  try {
761
1007
  return {
@@ -2288,6 +2534,31 @@ var CTeServicosUrl = {
2288
2534
  CTe_AN_H: CTe_AN_H
2289
2535
  };
2290
2536
 
2537
+ var NFSe_AN_P = {
2538
+ NFSe_Autorizacao: "https://sefin.nfse.gov.br/SefinNacional/nfse",
2539
+ NFSe_Consulta: "https://sefin.nfse.gov.br/SefinNacional/nfse",
2540
+ NFSe_ConsultaDPS: "https://sefin.nfse.gov.br/SefinNacional/dps",
2541
+ NFSe_Eventos: "https://sefin.nfse.gov.br/SefinNacional/nfse",
2542
+ NFSe_Distribuicao: "https://adn.nfse.gov.br/contribuintes/DFe",
2543
+ NFSe_EventosPorChave: "https://adn.nfse.gov.br/contribuintes/NFSe",
2544
+ NFSe_DANFSe: "https://adn.nfse.gov.br/danfse",
2545
+ NFSe_ParametrosMunicipais: "https://adn.nfse.gov.br/parametrizacao"
2546
+ };
2547
+ var NFSe_AN_H = {
2548
+ NFSe_Autorizacao: "https://sefin.producaorestrita.nfse.gov.br/SefinNacional/nfse",
2549
+ NFSe_Consulta: "https://sefin.producaorestrita.nfse.gov.br/SefinNacional/nfse",
2550
+ NFSe_ConsultaDPS: "https://sefin.producaorestrita.nfse.gov.br/SefinNacional/dps",
2551
+ NFSe_Eventos: "https://sefin.producaorestrita.nfse.gov.br/SefinNacional/nfse",
2552
+ NFSe_Distribuicao: "https://adn.producaorestrita.nfse.gov.br/contribuintes/DFe",
2553
+ NFSe_EventosPorChave: "https://adn.producaorestrita.nfse.gov.br/contribuintes/NFSe",
2554
+ NFSe_DANFSe: "https://adn.producaorestrita.nfse.gov.br/danfse",
2555
+ NFSe_ParametrosMunicipais: "https://adn.producaorestrita.nfse.gov.br/parametrizacao"
2556
+ };
2557
+ var NFSeServicosUrl = {
2558
+ NFSe_AN_P: NFSe_AN_P,
2559
+ NFSe_AN_H: NFSe_AN_H
2560
+ };
2561
+
2291
2562
  var NFEStatusServico = {
2292
2563
  method: "http://www.portalfiscal.inf.br/nfe/wsdl/NFeStatusServico4",
2293
2564
  action: ""
@@ -2332,6 +2603,26 @@ var CTeDistribuicaoDFe = {
2332
2603
  method: "http://www.portalfiscal.inf.br/cte/wsdl/CTeDistribuicaoDFe",
2333
2604
  action: "http://www.portalfiscal.inf.br/cte/wsdl/CTeDistribuicaoDFe/cteDistDFeInteresse"
2334
2605
  };
2606
+ var NFSe_Autorizacao = {
2607
+ method: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeRecepcao",
2608
+ action: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeRecepcao/recepcionar"
2609
+ };
2610
+ var NFSe_Consulta = {
2611
+ method: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeConsulta",
2612
+ action: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeConsulta/consultar"
2613
+ };
2614
+ var NFSe_Distribuicao = {
2615
+ method: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeDistribuicao",
2616
+ action: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeDistribuicao/distribuir"
2617
+ };
2618
+ var NFSe_Eventos = {
2619
+ method: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeRecepcaoEvento",
2620
+ action: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeRecepcaoEvento/recepcionar"
2621
+ };
2622
+ var NFSe_ParametrosMunicipais = {
2623
+ method: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeParametros",
2624
+ action: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeParametros/consultar"
2625
+ };
2335
2626
  var soapMethod = {
2336
2627
  NFEStatusServico: NFEStatusServico,
2337
2628
  NFeDistribuicaoDFe: NFeDistribuicaoDFe,
@@ -2343,7 +2634,12 @@ var soapMethod = {
2343
2634
  NFEConsultaProtocolo: NFEConsultaProtocolo,
2344
2635
  consultarCadastro: consultarCadastro,
2345
2636
  RecepcaoEvento: RecepcaoEvento,
2346
- CTeDistribuicaoDFe: CTeDistribuicaoDFe
2637
+ CTeDistribuicaoDFe: CTeDistribuicaoDFe,
2638
+ NFSe_Autorizacao: NFSe_Autorizacao,
2639
+ NFSe_Consulta: NFSe_Consulta,
2640
+ NFSe_Distribuicao: NFSe_Distribuicao,
2641
+ NFSe_Eventos: NFSe_Eventos,
2642
+ NFSe_ParametrosMunicipais: NFSe_ParametrosMunicipais
2347
2643
  };
2348
2644
 
2349
2645
  /**
@@ -2412,6 +2708,12 @@ class Utility {
2412
2708
  this.environment = environment;
2413
2709
  this.xmlParser = new XmlParser();
2414
2710
  }
2711
+ /**
2712
+ * Retorna schema XSD para validação do XML
2713
+ */
2714
+ getSchema(metodo) {
2715
+ return getSchema(metodo);
2716
+ }
2415
2717
  /**
2416
2718
  * Método utilitário para criar diretórios
2417
2719
  */
@@ -2623,10 +2925,39 @@ class Utility {
2623
2925
  const chaveFilha = `${metodo}_${versaoDF}`;
2624
2926
  return { chaveMae, chaveFilha };
2625
2927
  }
2928
+ /**
2929
+ * Retorna a url correta do webservice NFSe (REST API)
2930
+ */
2931
+ getWebServiceUrlNFSe(metodo) {
2932
+ const nfseUrls = NFSeServicosUrl;
2933
+ const config = this.environment.config;
2934
+ if (!config.nfe.ambiente) {
2935
+ throw new Error('Configuração de ambiente não encontrada. É necessária para operações de NFSe.');
2936
+ }
2937
+ const ambiente = config.nfe.ambiente === 1 ? 'P' : 'H';
2938
+ const chave = `NFSe_AN_${ambiente}`; // AN = Ambiente Nacional
2939
+ const url = nfseUrls[chave] && nfseUrls[chave][metodo];
2940
+ if (!url) {
2941
+ throw new Error(`Não foi possível recuperar a url para o webservice NFSe: ${metodo} no ambiente ${ambiente}`);
2942
+ }
2943
+ return url;
2944
+ }
2626
2945
  /**
2627
2946
  * Retorna a url correta do webservice
2628
2947
  */
2629
2948
  getWebServiceUrl(metodo, ambienteNacional = false, versao = "", mod = "NFe") {
2949
+ // Detecta se é NFSe
2950
+ const isNFSe = metodo.startsWith('NFSe_');
2951
+ if (isNFSe) {
2952
+ const nfseUrls = NFSeServicosUrl;
2953
+ const ambiente = this.environment.config.nfe.ambiente === 1 ? 'P' : 'H';
2954
+ const chave = `NFSe_Nacional_${ambiente}`; // Nacional = ADN (Ambiente de Dados Nacional)
2955
+ const url = nfseUrls[chave] && nfseUrls[chave][metodo];
2956
+ if (!url) {
2957
+ throw new Error(`Não foi possível recuperar a url para o webservice NFSe: ${metodo} no ambiente ${ambiente}`);
2958
+ }
2959
+ return url;
2960
+ }
2630
2961
  // Detecta se é CTe
2631
2962
  const isCTe = metodo.startsWith('CTe');
2632
2963
  if (isCTe) {
@@ -2751,7 +3082,36 @@ class Utility {
2751
3082
  const responseInJson = this.xmlParser.convertXmlToJson(data, metodo);
2752
3083
  // Salva XML de retorno
2753
3084
  this.salvaRetorno(data, responseInJson, metodo, name);
2754
- // Busca todos os xMotivo no objeto
3085
+ // Códigos de status de sucesso/processamento válidos
3086
+ const codigosValidos = [
3087
+ 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
3088
+ 124, 128, 135, 136, 137, 138, 139, 140, 142, 150, 151
3089
+ ];
3090
+ // Busca o cStat no retorno
3091
+ const cStat = this.findInObj(responseInJson, 'cStat');
3092
+ // cStat pode ser: string, number, ou array de strings/numbers
3093
+ let cStatNumber = null;
3094
+ if (cStat !== undefined && cStat !== null) {
3095
+ if (Array.isArray(cStat)) {
3096
+ // Se for array, pega o primeiro elemento
3097
+ cStatNumber = parseInt(String(cStat[0]), 10);
3098
+ }
3099
+ else {
3100
+ // Se for string ou number direto
3101
+ cStatNumber = parseInt(String(cStat), 10);
3102
+ }
3103
+ }
3104
+ // Se existe cStat e não está na lista de códigos válidos, é rejeição
3105
+ if (cStatNumber && !codigosValidos.includes(cStatNumber)) {
3106
+ const xMotivo = this.findInObj(responseInJson, 'xMotivo');
3107
+ let mensagemErro = `Rejeição com código ${cStatNumber}`;
3108
+ if (xMotivo) {
3109
+ // Se xMotivo for array, pega o primeiro elemento; senão, usa diretamente
3110
+ mensagemErro = Array.isArray(xMotivo) ? xMotivo[0] : xMotivo;
3111
+ }
3112
+ throw new Error(mensagemErro);
3113
+ }
3114
+ // Busca todos os xMotivo no objeto (verificação adicional)
2755
3115
  const allXMotivos = this.findAllInObj(responseInJson, 'xMotivo');
2756
3116
  // Verifica se algum xMotivo contém "Rejeição" ou "Rejeicao"
2757
3117
  for (const xMotivo of allXMotivos) {
@@ -2844,6 +3204,30 @@ class Utility {
2844
3204
  }
2845
3205
  }
2846
3206
  }
3207
+ /**
3208
+ * Gera o hashCSRT conforme documentação da SEFAZ
3209
+ *
3210
+ * O hash é gerado a partir da concatenação do CSRT da empresa com a chave de acesso da NF-e/NFC-e.
3211
+ * Utiliza o algoritmo SHA-1 para a geração do hash.
3212
+ *
3213
+ * @param csrt - Código de Segurança do Responsável Técnico (16 a 36 bytes alfanumérico)
3214
+ * @param chaveAcesso - Chave de acesso da NF-e/NFC-e (44 dígitos)
3215
+ * @returns Hash em Base64 com 28 caracteres
3216
+ *
3217
+ * @example
3218
+ * // Exemplo de uso:
3219
+ * const hashCSRT = utility.gerarHashCSRT('G8063VRTNDMO886SFNK5LDUDEI24XJ22YIPO', '41180678393592000146558900000006041028190697');
3220
+ * // Resultado: aWv6LeEM4X6u4+qBI2OYZ8grigw=
3221
+ */
3222
+ gerarHashCSRT(csrt, chaveAcesso) {
3223
+ // Passo 1: Concatenar o CSRT com a chave de acesso
3224
+ const concatenacao = csrt + chaveAcesso;
3225
+ // Passo 2: Aplicar o algoritmo SHA-1 sobre o resultado da concatenação
3226
+ const sha1Hash = crypto.createHash('sha1').update(concatenacao).digest();
3227
+ // Passo 3: Converter o resultado para Base64 (resulta em 28 caracteres)
3228
+ const hashBase64 = sha1Hash.toString('base64');
3229
+ return hashBase64;
3230
+ }
2847
3231
  }
2848
3232
 
2849
3233
  /*
@@ -3272,6 +3656,22 @@ const mountICMS = (icms) => {
3272
3656
  return {};
3273
3657
  };
3274
3658
 
3659
+ /*
3660
+ * This file is part of NFeWizard-io.
3661
+ *
3662
+ * NFeWizard-io is free software: you can redistribute it and/or modify
3663
+ * it under the terms of the GNU General Public License as published by
3664
+ * the Free Software Foundation, either version 3 of the License, or
3665
+ * (at your option) any later version.
3666
+ *
3667
+ * NFeWizard-io is distributed in the hope that it will be useful,
3668
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
3669
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
3670
+ * GNU General Public License for more details.
3671
+ *
3672
+ * You should have received a copy of the GNU General Public License
3673
+ * along with NFeWizard-io. If not, see <https://www.gnu.org/licenses/>.
3674
+ */
3275
3675
  class AxiosHttpClient {
3276
3676
  create(config) {
3277
3677
  return axios.create({
@@ -3282,6 +3682,22 @@ class AxiosHttpClient {
3282
3682
  }
3283
3683
  }
3284
3684
 
3685
+ /*
3686
+ * This file is part of NFeWizard-io.
3687
+ *
3688
+ * NFeWizard-io is free software: you can redistribute it and/or modify
3689
+ * it under the terms of the GNU General Public License as published by
3690
+ * the Free Software Foundation, either version 3 of the License, or
3691
+ * (at your option) any later version.
3692
+ *
3693
+ * NFeWizard-io is distributed in the hope that it will be useful,
3694
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
3695
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
3696
+ * GNU General Public License for more details.
3697
+ *
3698
+ * You should have received a copy of the GNU General Public License
3699
+ * along with NFeWizard-io. If not, see <https://www.gnu.org/licenses/>.
3700
+ */
3285
3701
  class HttpClientBuilder {
3286
3702
  constructor(config, agent, httpClient) {
3287
3703
  this.config = config;
@@ -3309,6 +3725,22 @@ class HttpClientBuilder {
3309
3725
  }
3310
3726
  }
3311
3727
 
3728
+ /*
3729
+ * This file is part of NFeWizard-io.
3730
+ *
3731
+ * NFeWizard-io is free software: you can redistribute it and/or modify
3732
+ * it under the terms of the GNU General Public License as published by
3733
+ * the Free Software Foundation, either version 3 of the License, or
3734
+ * (at your option) any later version.
3735
+ *
3736
+ * NFeWizard-io is distributed in the hope that it will be useful,
3737
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
3738
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
3739
+ * GNU General Public License for more details.
3740
+ *
3741
+ * You should have received a copy of the GNU General Public License
3742
+ * along with NFeWizard-io. If not, see <https://www.gnu.org/licenses/>.
3743
+ */
3312
3744
  class ValidateEnvironment {
3313
3745
  checkRequiredSettings(config) {
3314
3746
  logger.info('Verificando parâmetros de inicialização', {
@@ -3384,6 +3816,22 @@ class ValidateEnvironment {
3384
3816
  }
3385
3817
  }
3386
3818
 
3819
+ /*
3820
+ * This file is part of NFeWizard-io.
3821
+ *
3822
+ * NFeWizard-io is free software: you can redistribute it and/or modify
3823
+ * it under the terms of the GNU General Public License as published by
3824
+ * the Free Software Foundation, either version 3 of the License, or
3825
+ * (at your option) any later version.
3826
+ *
3827
+ * NFeWizard-io is distributed in the hope that it will be useful,
3828
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
3829
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
3830
+ * GNU General Public License for more details.
3831
+ *
3832
+ * You should have received a copy of the GNU General Public License
3833
+ * along with NFeWizard-io. If not, see <https://www.gnu.org/licenses/>.
3834
+ */
3387
3835
  const baseDir = path.dirname(fileURLToPath(import.meta.url));
3388
3836
  // From dist/ to package root, then to resources/certs
3389
3837
  const dir = path.join(baseDir, '../resources/certs');
@@ -3627,5 +4075,5 @@ class Environment {
3627
4075
  }
3628
4076
  }
3629
4077
 
3630
- export { AxiosHttpClient, BaseNFE, Environment, GerarConsulta, HttpClientBuilder, JsonArrayTransport, LoadCertificate, SaveFiles, Utility, ValidaCPFCNPJ, ValidateEnvironment, XmlBuilder, XmlParser, getCodIBGE, getDesTipoPag, getSchema, logger, mountCOFINS, mountICMS, mountPIS };
4078
+ export { AxiosHttpClient, BaseNFE, BaseNFSe, Environment, GerarConsulta, HttpClientBuilder, JsonArrayTransport, LoadCertificate, SaveFiles, Utility, ValidaCPFCNPJ, ValidateEnvironment, XmlBuilder, XmlParser, getCodIBGE, getDesTipoPag, getSchema, logger, mountCOFINS, mountICMS, mountPIS };
3631
4079
  //# sourceMappingURL=index.mjs.map