@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.cjs CHANGED
@@ -9,6 +9,7 @@ var dateFns = require('date-fns');
9
9
  var xml2js = require('xml2js');
10
10
  var xmlCrypto = require('xml-crypto');
11
11
  var url = require('url');
12
+ var crypto = require('crypto');
12
13
  var xsdValidator = require('xsd-schema-validator');
13
14
  var libxmljs = require('libxmljs2');
14
15
  var xsdAssembler = require('xsd-assembler');
@@ -37,6 +38,22 @@ function _interopNamespaceDefault(e) {
37
38
 
38
39
  var convert__namespace = /*#__PURE__*/_interopNamespaceDefault(convert);
39
40
 
41
+ /*
42
+ * This file is part of NFeWizard-io.
43
+ *
44
+ * NFeWizard-io is free software: you can redistribute it and/or modify
45
+ * it under the terms of the GNU General Public License as published by
46
+ * the Free Software Foundation, either version 3 of the License, or
47
+ * (at your option) any later version.
48
+ *
49
+ * NFeWizard-io is distributed in the hope that it will be useful,
50
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
51
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
52
+ * GNU General Public License for more details.
53
+ *
54
+ * You should have received a copy of the GNU General Public License
55
+ * along with NFeWizard-io. If not, see <https://www.gnu.org/licenses/>.
56
+ */
40
57
  class JsonArrayTransport extends Transport {
41
58
  constructor(options) {
42
59
  super(options);
@@ -117,6 +134,22 @@ class JsonArrayTransport extends Transport {
117
134
  }
118
135
  }
119
136
 
137
+ /*
138
+ * This file is part of NFeWizard-io.
139
+ *
140
+ * NFeWizard-io is free software: you can redistribute it and/or modify
141
+ * it under the terms of the GNU General Public License as published by
142
+ * the Free Software Foundation, either version 3 of the License, or
143
+ * (at your option) any later version.
144
+ *
145
+ * NFeWizard-io is distributed in the hope that it will be useful,
146
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
147
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
148
+ * GNU General Public License for more details.
149
+ *
150
+ * You should have received a copy of the GNU General Public License
151
+ * along with NFeWizard-io. If not, see <https://www.gnu.org/licenses/>.
152
+ */
120
153
  class AppLogger {
121
154
  constructor() {
122
155
  this.isInitialized = false;
@@ -517,6 +550,196 @@ class BaseNFE {
517
550
  }
518
551
  }
519
552
 
553
+ class BaseNFSe {
554
+ constructor(environment, utility, xmlBuilder, metodo, axios, saveFiles, gerarConsulta) {
555
+ this.environment = environment;
556
+ this.utility = utility;
557
+ this.xmlBuilder = xmlBuilder;
558
+ this.metodo = metodo;
559
+ this.axios = axios;
560
+ this.saveFiles = saveFiles;
561
+ this.gerarConsulta = gerarConsulta;
562
+ }
563
+ /**
564
+ * Método de preparação dos dados - Deve ser implementado pelas subclasses
565
+ */
566
+ prepararDados(_data) {
567
+ throw new Error("O método 'prepararDados' não foi implementado na subclasse.");
568
+ }
569
+ /**
570
+ * Método para obter a URL base do webservice
571
+ */
572
+ getWebServiceUrl() {
573
+ return this.utility.getWebServiceUrlNFSe(this.metodo);
574
+ }
575
+ /**
576
+ * Método para obter o método HTTP (GET, POST, etc)
577
+ */
578
+ getHttpMethod() {
579
+ return 'POST'; // Padrão para NFSe
580
+ }
581
+ /**
582
+ * Método para obter o path adicional da URL (ex: /nfse/{chaveAcesso})
583
+ */
584
+ getUrlPath(_data) {
585
+ return '';
586
+ }
587
+ /**
588
+ * Método para obter query parameters
589
+ */
590
+ getQueryParams(_data) {
591
+ return {};
592
+ }
593
+ /**
594
+ * Executa a requisição ao webservice NFSe (REST API)
595
+ * @param {any} [data] - Dados opcionais usados para preparar a requisição.
596
+ * @returns {Promise<any>} A resposta do webservice em JSON.
597
+ */
598
+ async Exec(data) {
599
+ let requestData = null;
600
+ let webServiceUrl = '';
601
+ let responseInJson = undefined;
602
+ let response = {};
603
+ let errorResponse = null;
604
+ try {
605
+ // Prepara dados específicos
606
+ requestData = this.prepararDados(data);
607
+ // Obtém URL base
608
+ const baseUrl = this.getWebServiceUrl();
609
+ const path = this.getUrlPath(data);
610
+ const queryParams = this.getQueryParams(data);
611
+ // Monta URL completa
612
+ webServiceUrl = baseUrl + path;
613
+ if (Object.keys(queryParams).length > 0) {
614
+ const queryString = new URLSearchParams(queryParams).toString();
615
+ webServiceUrl += `?${queryString}`;
616
+ }
617
+ const httpMethod = this.getHttpMethod();
618
+ logger.http('Iniciando comunicação com o webservice NFSe', {
619
+ context: `BaseNFSe`,
620
+ method: this.metodo,
621
+ httpMethod,
622
+ url: webServiceUrl,
623
+ });
624
+ // Executa requisição REST
625
+ // Obtém o agent HTTPS do environment para garantir autenticação mútua TLS
626
+ const agent = this.environment.getHttpAgent();
627
+ const requestConfig = {
628
+ headers: {
629
+ 'Content-Type': 'application/json',
630
+ 'Accept': 'application/json',
631
+ },
632
+ // Garante que o httpsAgent seja usado explicitamente para autenticação mútua TLS
633
+ httpsAgent: agent
634
+ };
635
+ if (httpMethod === 'GET') {
636
+ response = await this.axios.get(webServiceUrl, requestConfig);
637
+ }
638
+ else if (httpMethod === 'POST') {
639
+ response = await this.axios.post(webServiceUrl, requestData, requestConfig);
640
+ }
641
+ else if (httpMethod === 'PUT') {
642
+ response = await this.axios.put(webServiceUrl, requestData, requestConfig);
643
+ }
644
+ else if (httpMethod === 'DELETE') {
645
+ response = await this.axios.delete(webServiceUrl, requestConfig);
646
+ }
647
+ logger.http('Comunicação concluída com sucesso', {
648
+ context: `BaseNFSe`,
649
+ method: this.metodo,
650
+ responseSize: response.data ? JSON.stringify(response.data).length : 0
651
+ });
652
+ // NFSe retorna JSON diretamente
653
+ responseInJson = response.data;
654
+ // Verifica se há erros na resposta
655
+ if (responseInJson) {
656
+ if (responseInJson.erros && Array.isArray(responseInJson.erros) && responseInJson.erros.length > 0) {
657
+ const primeiroErro = responseInJson.erros[0];
658
+ const mensagemErro = primeiroErro.descricao || primeiroErro.Descricao || 'Erro desconhecido';
659
+ throw new Error(mensagemErro);
660
+ }
661
+ if (responseInJson.Erros && Array.isArray(responseInJson.Erros) && responseInJson.Erros.length > 0) {
662
+ const primeiroErro = responseInJson.Erros[0];
663
+ const mensagemErro = primeiroErro.Descricao || primeiroErro.descricao || 'Erro desconhecido';
664
+ throw new Error(mensagemErro);
665
+ }
666
+ }
667
+ return responseInJson || {};
668
+ }
669
+ catch (error) {
670
+ // Armazena a resposta de erro para uso no finally
671
+ errorResponse = error.response;
672
+ // Tenta extrair mais informações do erro
673
+ let errorMessage = error.message || 'Erro desconhecido';
674
+ if (error.response) {
675
+ // Erro de resposta HTTP
676
+ // Tenta extrair mensagem do body da resposta
677
+ if (error.response.data) {
678
+ if (typeof error.response.data === 'string') {
679
+ errorMessage = `HTTP ${error.response.status}: ${error.response.data}`;
680
+ }
681
+ else if (error.response.data.erros && Array.isArray(error.response.data.erros) && error.response.data.erros.length > 0) {
682
+ // NFSe retorna erros em um array
683
+ const primeiroErro = error.response.data.erros[0];
684
+ const codigo = primeiroErro.codigo || primeiroErro.Codigo || '';
685
+ const descricao = primeiroErro.descricao || primeiroErro.Descricao || 'Erro desconhecido';
686
+ errorMessage = codigo ? `${codigo}: ${descricao}` : descricao;
687
+ }
688
+ else if (error.response.data.Erros && Array.isArray(error.response.data.Erros) && error.response.data.Erros.length > 0) {
689
+ // Variação com E maiúsculo
690
+ const primeiroErro = error.response.data.Erros[0];
691
+ const codigo = primeiroErro.Codigo || primeiroErro.codigo || '';
692
+ const descricao = primeiroErro.Descricao || primeiroErro.descricao || 'Erro desconhecido';
693
+ errorMessage = codigo ? `${codigo}: ${descricao}` : descricao;
694
+ }
695
+ else if (error.response.data.message) {
696
+ errorMessage = error.response.data.message;
697
+ }
698
+ else if (error.response.data.descricao) {
699
+ errorMessage = error.response.data.descricao;
700
+ }
701
+ else if (error.response.data.Descricao) {
702
+ errorMessage = error.response.data.Descricao;
703
+ }
704
+ else {
705
+ errorMessage = `HTTP ${error.response.status}: ${JSON.stringify(error.response.data)}`;
706
+ }
707
+ }
708
+ else {
709
+ errorMessage = `HTTP ${error.response.status}: ${error.response.statusText}`;
710
+ }
711
+ }
712
+ logger.error(``, error, {
713
+ context: `BaseNFSe][${this.metodo}`
714
+ });
715
+ throw new Error(errorMessage);
716
+ }
717
+ finally {
718
+ // Salva arquivos (se configurado)
719
+ // Para REST, salva o JSON da requisição
720
+ const xmlConsulta = requestData ? JSON.stringify(requestData, null, 2) : '';
721
+ this.saveFiles.salvaArquivos(xmlConsulta, responseInJson, errorResponse || response, this.metodo, '' // xmlConsultaSoap vazio para REST
722
+ );
723
+ }
724
+ }
725
+ }
726
+
727
+ /*
728
+ * This file is part of NFeWizard-io.
729
+ *
730
+ * NFeWizard-io is free software: you can redistribute it and/or modify
731
+ * it under the terms of the GNU General Public License as published by
732
+ * the Free Software Foundation, either version 3 of the License, or
733
+ * (at your option) any later version.
734
+ *
735
+ * NFeWizard-io is distributed in the hope that it will be useful,
736
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
737
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
738
+ * GNU General Public License for more details.
739
+ *
740
+ * You should have received a copy of the GNU General Public License
741
+ * along with NFeWizard-io. If not, see <https://www.gnu.org/licenses/>.
742
+ */
520
743
  class GerarConsulta {
521
744
  constructor(environment, utility, xmlBuilder) {
522
745
  this.environment = environment;
@@ -540,20 +763,31 @@ class GerarConsulta {
540
763
  async gerarConsulta(xmlConsulta, metodo, ambienteNacional = false, versao = "", mod = "NFe", rootTag = false, tag = "", dadosMsgTag = "nfeDadosMsg") {
541
764
  try {
542
765
  const config = this.environment.getConfig();
543
- // Valida Schema
544
- if (config.lib?.useForSchemaValidation !== 'validateSchemaJsBased') {
545
- logger.info(`Validando XML com xsd-schema-validator`, {
546
- context: 'GerarConsulta',
547
- obs: 'Validação necessita do JAVA instaldo no ambiente',
548
- });
549
- await this.utility.validateSchemaJavaBased(xmlConsulta, metodo);
766
+ // Capturando o schema path
767
+ const { schemaPath } = this.utility.getSchema(metodo);
768
+ // Valida Schema apenas se o schema path estiver definido
769
+ if (schemaPath) {
770
+ if (config.lib?.useForSchemaValidation !== 'validateSchemaJsBased') {
771
+ logger.info(`Validando XML com xsd-schema-validator`, {
772
+ context: 'GerarConsulta',
773
+ obs: 'Validação necessita do JAVA instaldo no ambiente',
774
+ });
775
+ await this.utility.validateSchemaJavaBased(xmlConsulta, metodo);
776
+ }
777
+ else {
778
+ logger.info(`Validando XML com xsd-assembler`, {
779
+ context: 'GerarConsulta',
780
+ obs: 'Validação com nodejs',
781
+ });
782
+ await this.utility.validateSchemaJsBased(xmlConsulta, metodo);
783
+ }
550
784
  }
551
785
  else {
552
- logger.info(`Validando XML com xsd-assembler`, {
786
+ logger.info(`Pulando validação de schema`, {
553
787
  context: 'GerarConsulta',
554
- obs: 'Validação com nodejs',
788
+ metodo,
789
+ obs: 'Schema XSD não disponível para este método',
555
790
  });
556
- await this.utility.validateSchemaJsBased(xmlConsulta, metodo);
557
791
  }
558
792
  // Capturando a url do método para o namespace xmlns
559
793
  const { method, action } = this.utility.getSoapInfo(config.dfe.UF, metodo);
@@ -614,8 +848,14 @@ class SaveFiles {
614
848
  const salvarArquivo = (data, prefix, path, fileType) => {
615
849
  const fileName = createFileName(prefix);
616
850
  const method = fileType === 'xml' ? 'salvaXML' : 'salvaJSON';
851
+ // Para REST API (NFSe), o data pode ser um objeto JSON mesmo quando fileType é 'xml'
852
+ // Neste caso, converte para string JSON
853
+ let dataToSave = data || '';
854
+ if (fileType === 'xml' && typeof data === 'object' && data !== null) {
855
+ dataToSave = JSON.stringify(data, null, 2);
856
+ }
617
857
  this.utility[method]({
618
- data: data || '',
858
+ data: dataToSave,
619
859
  fileName,
620
860
  metodo: metodo,
621
861
  path,
@@ -778,6 +1018,12 @@ const getSchema = (metodo) => {
778
1018
  NFEInutilizacao: `${pathSchemas}/inutNFe_v4.00.xsd`,
779
1019
  NFERetAutorizacao: `${pathSchemas}/consReciNFe_v4.00.xsd`,
780
1020
  CTeDistribuicaoDFe: `${pathSchemas}/cte/distDFeInt_v1.00.xsd`,
1021
+ // NFSe - Schemas da Nota Fiscal de Serviços Eletrônica
1022
+ NFSe_Autorizacao: `${pathSchemas}/nfse/DPS_v1.01.xsd`,
1023
+ NFSe_Consulta: `${pathSchemas}/nfse/NFSe_v1.01.xsd`,
1024
+ NFSe_Distribuicao: `${pathSchemas}/nfse/NFSe_v1.01.xsd`,
1025
+ NFSe_Eventos: `${pathSchemas}/nfse/pedRegEvento_v1.01.xsd`,
1026
+ NFSe_ParametrosMunicipais: undefined, // API REST - não usa XML schema
781
1027
  };
782
1028
  try {
783
1029
  return {
@@ -2310,6 +2556,31 @@ var CTeServicosUrl = {
2310
2556
  CTe_AN_H: CTe_AN_H
2311
2557
  };
2312
2558
 
2559
+ var NFSe_AN_P = {
2560
+ NFSe_Autorizacao: "https://sefin.nfse.gov.br/SefinNacional/nfse",
2561
+ NFSe_Consulta: "https://sefin.nfse.gov.br/SefinNacional/nfse",
2562
+ NFSe_ConsultaDPS: "https://sefin.nfse.gov.br/SefinNacional/dps",
2563
+ NFSe_Eventos: "https://sefin.nfse.gov.br/SefinNacional/nfse",
2564
+ NFSe_Distribuicao: "https://adn.nfse.gov.br/contribuintes/DFe",
2565
+ NFSe_EventosPorChave: "https://adn.nfse.gov.br/contribuintes/NFSe",
2566
+ NFSe_DANFSe: "https://adn.nfse.gov.br/danfse",
2567
+ NFSe_ParametrosMunicipais: "https://adn.nfse.gov.br/parametrizacao"
2568
+ };
2569
+ var NFSe_AN_H = {
2570
+ NFSe_Autorizacao: "https://sefin.producaorestrita.nfse.gov.br/SefinNacional/nfse",
2571
+ NFSe_Consulta: "https://sefin.producaorestrita.nfse.gov.br/SefinNacional/nfse",
2572
+ NFSe_ConsultaDPS: "https://sefin.producaorestrita.nfse.gov.br/SefinNacional/dps",
2573
+ NFSe_Eventos: "https://sefin.producaorestrita.nfse.gov.br/SefinNacional/nfse",
2574
+ NFSe_Distribuicao: "https://adn.producaorestrita.nfse.gov.br/contribuintes/DFe",
2575
+ NFSe_EventosPorChave: "https://adn.producaorestrita.nfse.gov.br/contribuintes/NFSe",
2576
+ NFSe_DANFSe: "https://adn.producaorestrita.nfse.gov.br/danfse",
2577
+ NFSe_ParametrosMunicipais: "https://adn.producaorestrita.nfse.gov.br/parametrizacao"
2578
+ };
2579
+ var NFSeServicosUrl = {
2580
+ NFSe_AN_P: NFSe_AN_P,
2581
+ NFSe_AN_H: NFSe_AN_H
2582
+ };
2583
+
2313
2584
  var NFEStatusServico = {
2314
2585
  method: "http://www.portalfiscal.inf.br/nfe/wsdl/NFeStatusServico4",
2315
2586
  action: ""
@@ -2354,6 +2625,26 @@ var CTeDistribuicaoDFe = {
2354
2625
  method: "http://www.portalfiscal.inf.br/cte/wsdl/CTeDistribuicaoDFe",
2355
2626
  action: "http://www.portalfiscal.inf.br/cte/wsdl/CTeDistribuicaoDFe/cteDistDFeInteresse"
2356
2627
  };
2628
+ var NFSe_Autorizacao = {
2629
+ method: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeRecepcao",
2630
+ action: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeRecepcao/recepcionar"
2631
+ };
2632
+ var NFSe_Consulta = {
2633
+ method: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeConsulta",
2634
+ action: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeConsulta/consultar"
2635
+ };
2636
+ var NFSe_Distribuicao = {
2637
+ method: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeDistribuicao",
2638
+ action: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeDistribuicao/distribuir"
2639
+ };
2640
+ var NFSe_Eventos = {
2641
+ method: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeRecepcaoEvento",
2642
+ action: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeRecepcaoEvento/recepcionar"
2643
+ };
2644
+ var NFSe_ParametrosMunicipais = {
2645
+ method: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeParametros",
2646
+ action: "http://www.sped.fazenda.gov.br/nfse/wsdl/NFSeParametros/consultar"
2647
+ };
2357
2648
  var soapMethod = {
2358
2649
  NFEStatusServico: NFEStatusServico,
2359
2650
  NFeDistribuicaoDFe: NFeDistribuicaoDFe,
@@ -2365,7 +2656,12 @@ var soapMethod = {
2365
2656
  NFEConsultaProtocolo: NFEConsultaProtocolo,
2366
2657
  consultarCadastro: consultarCadastro,
2367
2658
  RecepcaoEvento: RecepcaoEvento,
2368
- CTeDistribuicaoDFe: CTeDistribuicaoDFe
2659
+ CTeDistribuicaoDFe: CTeDistribuicaoDFe,
2660
+ NFSe_Autorizacao: NFSe_Autorizacao,
2661
+ NFSe_Consulta: NFSe_Consulta,
2662
+ NFSe_Distribuicao: NFSe_Distribuicao,
2663
+ NFSe_Eventos: NFSe_Eventos,
2664
+ NFSe_ParametrosMunicipais: NFSe_ParametrosMunicipais
2369
2665
  };
2370
2666
 
2371
2667
  /**
@@ -2434,6 +2730,12 @@ class Utility {
2434
2730
  this.environment = environment;
2435
2731
  this.xmlParser = new XmlParser();
2436
2732
  }
2733
+ /**
2734
+ * Retorna schema XSD para validação do XML
2735
+ */
2736
+ getSchema(metodo) {
2737
+ return getSchema(metodo);
2738
+ }
2437
2739
  /**
2438
2740
  * Método utilitário para criar diretórios
2439
2741
  */
@@ -2645,10 +2947,39 @@ class Utility {
2645
2947
  const chaveFilha = `${metodo}_${versaoDF}`;
2646
2948
  return { chaveMae, chaveFilha };
2647
2949
  }
2950
+ /**
2951
+ * Retorna a url correta do webservice NFSe (REST API)
2952
+ */
2953
+ getWebServiceUrlNFSe(metodo) {
2954
+ const nfseUrls = NFSeServicosUrl;
2955
+ const config = this.environment.config;
2956
+ if (!config.nfe.ambiente) {
2957
+ throw new Error('Configuração de ambiente não encontrada. É necessária para operações de NFSe.');
2958
+ }
2959
+ const ambiente = config.nfe.ambiente === 1 ? 'P' : 'H';
2960
+ const chave = `NFSe_AN_${ambiente}`; // AN = Ambiente Nacional
2961
+ const url = nfseUrls[chave] && nfseUrls[chave][metodo];
2962
+ if (!url) {
2963
+ throw new Error(`Não foi possível recuperar a url para o webservice NFSe: ${metodo} no ambiente ${ambiente}`);
2964
+ }
2965
+ return url;
2966
+ }
2648
2967
  /**
2649
2968
  * Retorna a url correta do webservice
2650
2969
  */
2651
2970
  getWebServiceUrl(metodo, ambienteNacional = false, versao = "", mod = "NFe") {
2971
+ // Detecta se é NFSe
2972
+ const isNFSe = metodo.startsWith('NFSe_');
2973
+ if (isNFSe) {
2974
+ const nfseUrls = NFSeServicosUrl;
2975
+ const ambiente = this.environment.config.nfe.ambiente === 1 ? 'P' : 'H';
2976
+ const chave = `NFSe_Nacional_${ambiente}`; // Nacional = ADN (Ambiente de Dados Nacional)
2977
+ const url = nfseUrls[chave] && nfseUrls[chave][metodo];
2978
+ if (!url) {
2979
+ throw new Error(`Não foi possível recuperar a url para o webservice NFSe: ${metodo} no ambiente ${ambiente}`);
2980
+ }
2981
+ return url;
2982
+ }
2652
2983
  // Detecta se é CTe
2653
2984
  const isCTe = metodo.startsWith('CTe');
2654
2985
  if (isCTe) {
@@ -2773,7 +3104,36 @@ class Utility {
2773
3104
  const responseInJson = this.xmlParser.convertXmlToJson(data, metodo);
2774
3105
  // Salva XML de retorno
2775
3106
  this.salvaRetorno(data, responseInJson, metodo, name);
2776
- // Busca todos os xMotivo no objeto
3107
+ // Códigos de status de sucesso/processamento válidos
3108
+ const codigosValidos = [
3109
+ 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
3110
+ 124, 128, 135, 136, 137, 138, 139, 140, 142, 150, 151
3111
+ ];
3112
+ // Busca o cStat no retorno
3113
+ const cStat = this.findInObj(responseInJson, 'cStat');
3114
+ // cStat pode ser: string, number, ou array de strings/numbers
3115
+ let cStatNumber = null;
3116
+ if (cStat !== undefined && cStat !== null) {
3117
+ if (Array.isArray(cStat)) {
3118
+ // Se for array, pega o primeiro elemento
3119
+ cStatNumber = parseInt(String(cStat[0]), 10);
3120
+ }
3121
+ else {
3122
+ // Se for string ou number direto
3123
+ cStatNumber = parseInt(String(cStat), 10);
3124
+ }
3125
+ }
3126
+ // Se existe cStat e não está na lista de códigos válidos, é rejeição
3127
+ if (cStatNumber && !codigosValidos.includes(cStatNumber)) {
3128
+ const xMotivo = this.findInObj(responseInJson, 'xMotivo');
3129
+ let mensagemErro = `Rejeição com código ${cStatNumber}`;
3130
+ if (xMotivo) {
3131
+ // Se xMotivo for array, pega o primeiro elemento; senão, usa diretamente
3132
+ mensagemErro = Array.isArray(xMotivo) ? xMotivo[0] : xMotivo;
3133
+ }
3134
+ throw new Error(mensagemErro);
3135
+ }
3136
+ // Busca todos os xMotivo no objeto (verificação adicional)
2777
3137
  const allXMotivos = this.findAllInObj(responseInJson, 'xMotivo');
2778
3138
  // Verifica se algum xMotivo contém "Rejeição" ou "Rejeicao"
2779
3139
  for (const xMotivo of allXMotivos) {
@@ -2866,6 +3226,30 @@ class Utility {
2866
3226
  }
2867
3227
  }
2868
3228
  }
3229
+ /**
3230
+ * Gera o hashCSRT conforme documentação da SEFAZ
3231
+ *
3232
+ * O hash é gerado a partir da concatenação do CSRT da empresa com a chave de acesso da NF-e/NFC-e.
3233
+ * Utiliza o algoritmo SHA-1 para a geração do hash.
3234
+ *
3235
+ * @param csrt - Código de Segurança do Responsável Técnico (16 a 36 bytes alfanumérico)
3236
+ * @param chaveAcesso - Chave de acesso da NF-e/NFC-e (44 dígitos)
3237
+ * @returns Hash em Base64 com 28 caracteres
3238
+ *
3239
+ * @example
3240
+ * // Exemplo de uso:
3241
+ * const hashCSRT = utility.gerarHashCSRT('G8063VRTNDMO886SFNK5LDUDEI24XJ22YIPO', '41180678393592000146558900000006041028190697');
3242
+ * // Resultado: aWv6LeEM4X6u4+qBI2OYZ8grigw=
3243
+ */
3244
+ gerarHashCSRT(csrt, chaveAcesso) {
3245
+ // Passo 1: Concatenar o CSRT com a chave de acesso
3246
+ const concatenacao = csrt + chaveAcesso;
3247
+ // Passo 2: Aplicar o algoritmo SHA-1 sobre o resultado da concatenação
3248
+ const sha1Hash = crypto.createHash('sha1').update(concatenacao).digest();
3249
+ // Passo 3: Converter o resultado para Base64 (resulta em 28 caracteres)
3250
+ const hashBase64 = sha1Hash.toString('base64');
3251
+ return hashBase64;
3252
+ }
2869
3253
  }
2870
3254
 
2871
3255
  /*
@@ -3294,6 +3678,22 @@ const mountICMS = (icms) => {
3294
3678
  return {};
3295
3679
  };
3296
3680
 
3681
+ /*
3682
+ * This file is part of NFeWizard-io.
3683
+ *
3684
+ * NFeWizard-io is free software: you can redistribute it and/or modify
3685
+ * it under the terms of the GNU General Public License as published by
3686
+ * the Free Software Foundation, either version 3 of the License, or
3687
+ * (at your option) any later version.
3688
+ *
3689
+ * NFeWizard-io is distributed in the hope that it will be useful,
3690
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
3691
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
3692
+ * GNU General Public License for more details.
3693
+ *
3694
+ * You should have received a copy of the GNU General Public License
3695
+ * along with NFeWizard-io. If not, see <https://www.gnu.org/licenses/>.
3696
+ */
3297
3697
  class AxiosHttpClient {
3298
3698
  create(config) {
3299
3699
  return axios.create({
@@ -3304,6 +3704,22 @@ class AxiosHttpClient {
3304
3704
  }
3305
3705
  }
3306
3706
 
3707
+ /*
3708
+ * This file is part of NFeWizard-io.
3709
+ *
3710
+ * NFeWizard-io is free software: you can redistribute it and/or modify
3711
+ * it under the terms of the GNU General Public License as published by
3712
+ * the Free Software Foundation, either version 3 of the License, or
3713
+ * (at your option) any later version.
3714
+ *
3715
+ * NFeWizard-io is distributed in the hope that it will be useful,
3716
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
3717
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
3718
+ * GNU General Public License for more details.
3719
+ *
3720
+ * You should have received a copy of the GNU General Public License
3721
+ * along with NFeWizard-io. If not, see <https://www.gnu.org/licenses/>.
3722
+ */
3307
3723
  class HttpClientBuilder {
3308
3724
  constructor(config, agent, httpClient) {
3309
3725
  this.config = config;
@@ -3331,6 +3747,22 @@ class HttpClientBuilder {
3331
3747
  }
3332
3748
  }
3333
3749
 
3750
+ /*
3751
+ * This file is part of NFeWizard-io.
3752
+ *
3753
+ * NFeWizard-io is free software: you can redistribute it and/or modify
3754
+ * it under the terms of the GNU General Public License as published by
3755
+ * the Free Software Foundation, either version 3 of the License, or
3756
+ * (at your option) any later version.
3757
+ *
3758
+ * NFeWizard-io is distributed in the hope that it will be useful,
3759
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
3760
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
3761
+ * GNU General Public License for more details.
3762
+ *
3763
+ * You should have received a copy of the GNU General Public License
3764
+ * along with NFeWizard-io. If not, see <https://www.gnu.org/licenses/>.
3765
+ */
3334
3766
  class ValidateEnvironment {
3335
3767
  checkRequiredSettings(config) {
3336
3768
  logger.info('Verificando parâmetros de inicialização', {
@@ -3406,6 +3838,22 @@ class ValidateEnvironment {
3406
3838
  }
3407
3839
  }
3408
3840
 
3841
+ /*
3842
+ * This file is part of NFeWizard-io.
3843
+ *
3844
+ * NFeWizard-io is free software: you can redistribute it and/or modify
3845
+ * it under the terms of the GNU General Public License as published by
3846
+ * the Free Software Foundation, either version 3 of the License, or
3847
+ * (at your option) any later version.
3848
+ *
3849
+ * NFeWizard-io is distributed in the hope that it will be useful,
3850
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
3851
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
3852
+ * GNU General Public License for more details.
3853
+ *
3854
+ * You should have received a copy of the GNU General Public License
3855
+ * along with NFeWizard-io. If not, see <https://www.gnu.org/licenses/>.
3856
+ */
3409
3857
  const baseDir = path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
3410
3858
  // From dist/ to package root, then to resources/certs
3411
3859
  const dir = path.join(baseDir, '../resources/certs');
@@ -3651,6 +4099,7 @@ class Environment {
3651
4099
 
3652
4100
  exports.AxiosHttpClient = AxiosHttpClient;
3653
4101
  exports.BaseNFE = BaseNFE;
4102
+ exports.BaseNFSe = BaseNFSe;
3654
4103
  exports.Environment = Environment;
3655
4104
  exports.GerarConsulta = GerarConsulta;
3656
4105
  exports.HttpClientBuilder = HttpClientBuilder;