diff --git a/autorizadores.json b/autorizadores.json index 98a49f6..8d48493 100644 --- a/autorizadores.json +++ b/autorizadores.json @@ -143,6 +143,10 @@ "inutilizacao": { "url_producao": "https://nfe.sefa.pr.gov.br/nfe/NFeInutilizacao4", "url_homologacao": "https://homologacao.nfce.sefa.pr.gov.br/nfce/Nfeinutilizacao4.asmx" + }, + "recepcaoEvento": { + "url_producao": "https://nfce.sefa.pr.gov.br/nfce/NFeRecepcaoEvento4", + "url_homologacao": "https://homologacao.nfce.sefa.pr.gov.br/nfce/NFeRecepcaoEvento4" } } }, diff --git a/autorizadoresNFe.json b/autorizadoresNFe.json index 4833b73..94a27b1 100644 --- a/autorizadoresNFe.json +++ b/autorizadoresNFe.json @@ -149,6 +149,10 @@ "consultarStatusServico": { "url_producao": "https://nfe.sefa.pr.gov.br/nfe/NFeStatusServico4?wsdl", "url_homologacao": "https://homologacao.nfe.sefa.pr.gov.br/nfe/NFeStatusServico4?wsdl" + }, + "recepcaoEvento": { + "url_producao": "https://nfe.sefa.pr.gov.br/nfe/NFeRecepcaoEvento4", + "url_homologacao": "https://homologacao.nfe.sefa.pr.gov.br/nfe/NFeRecepcaoEvento4" } } }, diff --git a/lib/factory/interface/nfe/index.d.ts b/lib/factory/interface/nfe/index.d.ts index 0230c03..f5a4a3b 100644 --- a/lib/factory/interface/nfe/index.d.ts +++ b/lib/factory/interface/nfe/index.d.ts @@ -25,7 +25,9 @@ export interface RetornoProcessamento { xml_recebido: string; status: number; success: boolean; - data: Object; + data: { + retEnviNFe?: Object; + }; error: string; } export interface NFeBase { @@ -66,12 +68,17 @@ export interface DocumentoFiscal { justificativaContingencia: string; isContingenciaOffline: boolean; indIntermed?: string; + NFref?: { + refNFe?: string; + }[]; } export interface Produto { prod: DetalhesProduto; imposto: Imposto; infoAdicional: string; numeroItem: string; + pis: Object | undefined; + cofins: Object | undefined; } export interface DetalhesProduto { codigo: string; @@ -116,6 +123,7 @@ export interface Imposto { pisst: PisST; cofinsst: CofinsST; icmsUfDest: IcmsUfDest; + IBSCBS: any; } export interface Icms { orig: string; @@ -238,10 +246,16 @@ export interface Issqn { nProcesso: string; indIncentivo: string; } +export interface IbsCbsTot { + vIBS: string; + vCBS: string; + vIS: string; +} export interface Total { icmsTot: IcmsTot; issqnTot: IssqnTot; retTrib: RetTrib; + IBSCBSTot?: IbsCbsTot; } export interface IcmsTot { vBC: string; @@ -293,6 +307,8 @@ export interface RetTrib { } export interface Transporte { modalidateFrete: string; + transporta: Object; + vol: Object; } export interface Cobranca { fatura: Fatura; diff --git a/lib/factory/processor/enviaProcessor.js b/lib/factory/processor/enviaProcessor.js index f807c40..74c8dcc 100644 --- a/lib/factory/processor/enviaProcessor.js +++ b/lib/factory/processor/enviaProcessor.js @@ -86,11 +86,9 @@ class EnviaProcessor { } configuraUrlsSefaz() { const { geral: { modelo, ambiente }, empresa } = this.configuracoes; - if (!soapAutorizacao || !soapRetAutorizacao) { - let Sefaz = modelo == '65' ? sefazNfce_1.SefazNFCe : sefazNfe_1.SefazNFe; - soapAutorizacao = Sefaz.getSoapInfo(empresa.endereco.uf, ambiente, nfe_1.ServicosSefaz.autorizacao); - soapRetAutorizacao = Sefaz.getSoapInfo(empresa.endereco.uf, ambiente, nfe_1.ServicosSefaz.retAutorizacao); - } + let Sefaz = modelo == '65' ? sefazNfce_1.SefazNFCe : sefazNfe_1.SefazNFe; + soapAutorizacao = Sefaz.getSoapInfo(empresa.endereco.uf, ambiente, nfe_1.ServicosSefaz.autorizacao); + soapRetAutorizacao = Sefaz.getSoapInfo(empresa.endereco.uf, ambiente, nfe_1.ServicosSefaz.retAutorizacao); } appendQRCodeXML(documento, xmlAssinado) { let qrCode = null; @@ -137,7 +135,7 @@ class EnviaProcessor { log(jsonOneLevel(retornoEnvio), 'retornoEnvio.full'); } catch (e) { - log(`ja deu erro pra logar.......${e.toString()}`, 'retornoEnvio'); + log(`ja deu erro pra logar.......${e === null || e === void 0 ? void 0 : e.toString()}`, 'retornoEnvio'); } if (retornoEnvio && retornoEnvio.data) { const data = Object(retornoEnvio.data); @@ -319,6 +317,7 @@ class EnviaProcessor { dhSaiEnt: documento.dhSaiEnt, dhCont: documento.dhContingencia, xJust: documento.justificativaContingencia, + NFref: documento.NFref, }; if (documento.indIntermed) { ide.indIntermed = Utils.getEnumByValue(schema.TNFeInfNFeIdeIndIntermed, documento.indIntermed); // NT 2020.006 @@ -394,7 +393,7 @@ class EnviaProcessor { prod: this.getDetProd(produtos[i].prod, ambiente, i == 0), imposto: this.getDetImposto(produtos[i].imposto, modelo, produtos[i].prod.CFOP), infAdProd: produtos[i].infoAdicional, - impostoDevol: (produtos[i].prod.percentualDevolucao && (produtos[i].prod.percentualDevolucao > 0)) ? this.getImpostoDevolucao({ pDevol: produtos[i].prod.percentualDevolucao, vIPIDevol: produtos[i].prod.valorIPIDevolucao }) : undefined + impostoDevol: (produtos[i].prod.percentualDevolucao && (produtos[i].prod.percentualDevolucao > 0)) ? this.getImpostoDevolucao({ pDevol: produtos[i].prod.percentualDevolucao, vIPIDevol: produtos[i].prod.valorIPIDevolucao }) : undefined, }); } return det_list; @@ -443,6 +442,7 @@ class EnviaProcessor { II: imposto.ii ? [this.getImpostoII(imposto.ii, cfop)] : [], ICMSUFDest: imposto.icmsUfDest ? [this.getIcmsUfDest(imposto.icmsUfDest)] : [], ISSQN: '', + IBSCBS: imposto.IBSCBS }; return detImposto; } @@ -929,6 +929,7 @@ class EnviaProcessor { CST: pis.CST } }; + break; case '49': case '50': case '51': @@ -965,6 +966,7 @@ class EnviaProcessor { vPIS: pis.vPIS } }; + break; default: result = { PISOutr: { @@ -1158,27 +1160,25 @@ class EnviaProcessor { }; } getTotal(total) { - return { - ICMSTot: total.icmsTot - }; + return Object.assign({ ICMSTot: total.icmsTot }, (total.IBSCBSTot ? { IBSCBSTot: total.IBSCBSTot } : {})); } getIcmsTot(icmsTot) { return icmsTot; } getTransp(transp) { return { - modFrete: transp.modalidateFrete + modFrete: transp.modalidateFrete, + transporta: transp.transporta, /** - * transporta: TNFeInfNFeTranspTransporta; - retTransp: TNFeInfNFeTranspRetTransp; - //balsa - //reboque - //vagao - //veicTransp + * retTransp: TNFeInfNFeTranspRetTransp; + balsa + reboque + vagao + veicTransp items: object[]; itemsElementName: ItemsChoiceType5[]; - vol: TNFeInfNFeTranspVol[]; - */ + */ + vol: transp.vol, }; } getCobr(cobranca) { @@ -1221,13 +1221,13 @@ class EnviaProcessor { detPag = {}; detPag.indPag = Utils.getEnumByValue(schema.TNFeInfNFePagDetPagIndPag, pag.indicadorFormaPagamento); detPag.tPag = Utils.getEnumByValue(schema.TNFeInfNFePagDetPagTPag, pag.formaPagamento); - detPag.vPag = pag.valor; if (pag.descricaoFormaPagamento) { detPag.xPag = pag.descricaoFormaPagamento; // YA02A NT 2020.006 } if (pag.dadosCartao) { detPag.card = this.getDetalhamentoCartao(pag.dadosCartao); } + detPag.vPag = pag.valor; listPagamentos.push(detPag); } return listPagamentos; diff --git a/lib/factory/processor/nfeProcessor.js b/lib/factory/processor/nfeProcessor.js index fbc685a..85c3063 100644 --- a/lib/factory/processor/nfeProcessor.js +++ b/lib/factory/processor/nfeProcessor.js @@ -984,6 +984,7 @@ class NFeProcessor { CST: pis.CST } }; + break; case '49': case '50': case '51': @@ -1020,6 +1021,7 @@ class NFeProcessor { vPIS: pis.vPIS } }; + break; default: result = { PISOutr: { diff --git a/lib/factory/processor/nfeProcessor2.js b/lib/factory/processor/nfeProcessor2.js index 6284af0..813c2f3 100644 --- a/lib/factory/processor/nfeProcessor2.js +++ b/lib/factory/processor/nfeProcessor2.js @@ -49,27 +49,49 @@ class NFeProcessor { return result; } async executar(documento) { + var _a; const { arquivos, geral } = this.configuracoes; let result = {}; try { result = await this.enviaProcessor.executar(documento); let retEnviNFe = null; let retConsReciNFe = null; - let cStat = ''; + let finalResponse = null; // Objeto que conterá o protNFe final if (result.envioNF && result.envioNF.data) { const data = Object(result.envioNF.data); - if (data.retEnviNFe && geral.modelo == '55') { + if (data.retEnviNFe) { retEnviNFe = data.retEnviNFe; - const recibo = retEnviNFe.infRec.nRec; - result.consultaProc = await this.retornoProcessor.executar(recibo); - retConsReciNFe = Object(result.consultaProc.data).retConsReciNFe; - cStat = retConsReciNFe.cStat; + // Lógica Assíncrona (NF-e Modelo 55) + if (geral.modelo == '55') { + if (retEnviNFe.infRec) { + const recibo = retEnviNFe.infRec.nRec; + result.consultaProc = await this.retornoProcessor.executar(recibo); + retConsReciNFe = Object(result.consultaProc.data).retConsReciNFe; + finalResponse = retConsReciNFe; + } + else if (retEnviNFe.protNFe) { + finalResponse = retEnviNFe; + } + } + // Lógica Síncrona (NFC-e Modelo 65) + else { + // Na NFC-e o retorno do envio JÁ É o retorno final com protocolo + finalResponse = retEnviNFe; + } } - if (retEnviNFe && retConsReciNFe) - if (retEnviNFe.cStat == '103' && retConsReciNFe.cStat == '104') { //protNFe.infProt. + // Verificação de Sucesso + if (finalResponse) { + // Sucesso NF-e (Lote Recebido + Lote Processado) + if (geral.modelo == '55' && retEnviNFe.cStat == '103' && finalResponse.cStat == '104') { result.confirmada = true; result.success = true; } + // Sucesso NFC-e (Lote Processado Direto) + if (geral.modelo == '65' && finalResponse.cStat == '104') { + result.confirmada = true; + result.success = true; + } + } if (arquivos && arquivos.salvar) { if (!fs.existsSync(arquivos.pastaEnvio)) fs.mkdirSync(arquivos.pastaEnvio, { recursive: true }); @@ -77,27 +99,36 @@ class NFeProcessor { fs.mkdirSync(arquivos.pastaRetorno, { recursive: true }); if (!fs.existsSync(arquivos.pastaXML)) fs.mkdirSync(arquivos.pastaXML, { recursive: true }); - if ((result.success == true) && (retConsReciNFe.cStat == '104')) { - const filename = `${arquivos.pastaXML}${retConsReciNFe.protNFe.infProt.chNFe}-procNFe.xml`; + // Salvar XML de Processamento (Autorizado) + if ((result.success == true) && (finalResponse && finalResponse.cStat == '104' && finalResponse.protNFe)) { + const filename = `${arquivos.pastaXML}${finalResponse.protNFe.infProt.chNFe}-procNFe.xml`; const nfe_enviada = Object(xmlHelper_1.XmlHelper.deserializeXml(result.envioNF.xml_enviado, { explicitArray: false })); const nfeProc = { - $: { versao: "1.00", xmlns: "http://www.portalfiscal.inf.br/nfe" }, + $: { versao: "4.00", xmlns: "http://www.portalfiscal.inf.br/nfe" }, NFe: nfe_enviada.enviNFe.NFe, - protNFe: retConsReciNFe.protNFe + protNFe: finalResponse.protNFe }; Utils.removeSelfClosedFields(nfeProc); let xmlNfeProc = xmlHelper_1.XmlHelper.serializeXml(nfeProc, 'nfeProc'); fs.writeFileSync(filename, xmlNfeProc); } + // Salvar XMLs de Erro / Logs else { - const filenameEnvio = `${arquivos.pastaEnvio}${retEnviNFe.infRec.nRec}-enviNFe.xml`; - const filenameRetorno = `${arquivos.pastaRetorno}${retEnviNFe.infRec.nRec}-retEnviNFe.xml`; - fs.writeFileSync(filenameEnvio, result.envioNF.xml_enviado); - fs.writeFileSync(filenameRetorno, result.envioNF.xml_recebido); - const filenameConsultaEnvio = `${arquivos.pastaEnvio}${retConsReciNFe.nRec}-consReciNFe.xml`; - const filenameConsultaRetorno = `${arquivos.pastaRetorno}${retConsReciNFe.nRec}-retConsReciNFe.xml`; - fs.writeFileSync(filenameConsultaEnvio, result.consultaProc.xml_enviado); - fs.writeFileSync(filenameConsultaRetorno, result.consultaProc.xml_recebido); + const date = new Date().toISOString().replace(/:/g, '-'); + // Proteção: Se não houver nRec (erro de schema), usa timestamp + const idIdentificador = ((_a = retEnviNFe === null || retEnviNFe === void 0 ? void 0 : retEnviNFe.infRec) === null || _a === void 0 ? void 0 : _a.nRec) || new Date().getTime().toString(); + const filenameEnvio = `${arquivos.pastaEnvio}${date}-${idIdentificador}-enviNFe.xml`; + const filenameRetorno = `${arquivos.pastaRetorno}${date}-${idIdentificador}-retEnviNFe.xml`; + if (result.envioNF.xml_enviado) + fs.writeFileSync(filenameEnvio, result.envioNF.xml_enviado); + if (result.envioNF.xml_recebido) + fs.writeFileSync(filenameRetorno, result.envioNF.xml_recebido); + if (result.consultaProc) { + const filenameConsultaEnvio = `${arquivos.pastaEnvio}${retConsReciNFe.nRec}-consReciNFe.xml`; + const filenameConsultaRetorno = `${arquivos.pastaRetorno}${retConsReciNFe.nRec}-retConsReciNFe.xml`; + fs.writeFileSync(filenameConsultaEnvio, result.consultaProc.xml_enviado); + fs.writeFileSync(filenameConsultaRetorno, result.consultaProc.xml_recebido); + } } } } @@ -115,6 +146,74 @@ class NFeProcessor { } return result; } + // public async executar(documento: NFeDocumento | NFCeDocumento) { + // const { arquivos, geral } = this.configuracoes; + // let result = {}; + // try { + // result = await this.enviaProcessor.executar(documento); + // let retEnviNFe = null; + // let retConsReciNFe = null; + // let cStat = ''; + // if (result.envioNF && result.envioNF.data) { + // const data = Object(result.envioNF.data); + // retEnviNFe = data.retEnviNFe; + // if (data.retEnviNFe) { + // if (geral.modelo == '55' && retEnviNFe.infRec) { + // const recibo = retEnviNFe.infRec.nRec; + // result.consultaProc = await this.retornoProcessor.executar(recibo); + // } + // if (result.envioNF?.data?.retEnviNFe) + // retConsReciNFe = Object(result.envioNF.data.retEnviNFe); + // else + // retConsReciNFe = Object(result.consultaProc.data).retConsReciNFe; + // cStat = retConsReciNFe.cStat; + // } + // if (retEnviNFe && retConsReciNFe) + // if (retEnviNFe.cStat == '103' && retConsReciNFe.cStat == '104') { //protNFe.infProt. + // result.confirmada = true; + // result.success = true; + // } + // if (arquivos && arquivos.salvar) { + // if (!fs.existsSync(arquivos.pastaEnvio)) fs.mkdirSync(arquivos.pastaEnvio, { recursive: true }); + // if (!fs.existsSync(arquivos.pastaRetorno)) fs.mkdirSync(arquivos.pastaRetorno, { recursive: true }); + // if (!fs.existsSync(arquivos.pastaXML)) fs.mkdirSync(arquivos.pastaXML, { recursive: true }); + // if ((result.success == true) && (retConsReciNFe.cStat == '104')) { + // const filename = `${arquivos.pastaXML}${retConsReciNFe.protNFe.infProt.chNFe}-procNFe.xml`; + // const nfe_enviada = Object(XmlHelper.deserializeXml(result.envioNF.xml_enviado, { explicitArray: false })); + // const nfeProc = { + // $: { versao: "1.00", xmlns: "http://www.portalfiscal.inf.br/nfe" }, + // NFe: nfe_enviada.enviNFe.NFe, + // protNFe: retConsReciNFe.protNFe + // }; + // Utils.removeSelfClosedFields(nfeProc); + // let xmlNfeProc = XmlHelper.serializeXml(nfeProc, 'nfeProc'); + // fs.writeFileSync(filename, xmlNfeProc); + // } else { + // const date = new Date().toISOString().replace(/:/g, '-'); + // const filenameEnvio = `${arquivos.pastaEnvio}${date}${retEnviNFe.infRec?.nRec || ''}-enviNFe.xml`; + // const filenameRetorno = `${arquivos.pastaRetorno}${date}${retEnviNFe.infRec?.nRec || ''}-retEnviNFe.xml`; + // fs.writeFileSync(filenameEnvio, result.envioNF.xml_enviado); + // fs.writeFileSync(filenameRetorno, result.envioNF.xml_recebido); + // if (result.consultaProc) { + // const filenameConsultaEnvio = `${arquivos.pastaEnvio}${retConsReciNFe.nRec}-consReciNFe.xml`; + // const filenameConsultaRetorno = `${arquivos.pastaRetorno}${retConsReciNFe.nRec}-retConsReciNFe.xml`; + // fs.writeFileSync(filenameConsultaEnvio, result.consultaProc.xml_enviado); + // fs.writeFileSync(filenameConsultaRetorno, result.consultaProc.xml_recebido); + // } + // } + // } + // } else if (result.retornoContingenciaOffline && result.success) { + // return result; + // } else { + // console.error('nfeProcessor.executar: Erro ao realizar requisição', result); + // throw new Error('Erro ao realizar requisição'); + // } + // } catch (ex) { + // result.success = false; + // result.error = ex; + // } + // return result; + // } async inutilizarNumeracao(dados) { return await this.inutlizacaoProcessor.executar(dados); } diff --git a/lib/factory/schema/index.d.ts b/lib/factory/schema/index.d.ts index f783091..133c4fa 100644 --- a/lib/factory/schema/index.d.ts +++ b/lib/factory/schema/index.d.ts @@ -130,7 +130,7 @@ export interface TNFeInfNFeIde { verProc: string; dhCont: string; xJust: string; - nFref: TNFeInfNFeIdeNFref[]; + NFref?: TNFeInfNFeIdeNFref[]; indIntermed?: TNFeInfNFeIdeIndIntermed; } export declare enum TNFeInfNFeIdeIndIntermed { @@ -203,7 +203,7 @@ export interface TNFeInfNFeIdeNFref { refNF?: TNFeInfNFeIdeNFrefRefNF; refNFP?: TNFeInfNFeIdeNFrefRefNFP; refNFe?: string; - itemElementName: ItemChoiceType1; + itemElementName?: ItemChoiceType1; } export interface TNFeInfNFeIdeNFrefRefECF { mod: TNFeInfNFeIdeNFrefRefECFMod; @@ -440,6 +440,8 @@ export interface TNFeInfNFeDet { imposto: TNFeInfNFeDetImposto; impostoDevol: any; infAdProd: string; + PIS: Object; + COFINS: Object; } export interface TNFeInfNFeDetProd { cProd: string; diff --git a/lib/factory/webservices/webserviceHelper.js b/lib/factory/webservices/webserviceHelper.js index b8e9fa9..9638962 100644 --- a/lib/factory/webservices/webserviceHelper.js +++ b/lib/factory/webservices/webserviceHelper.js @@ -69,7 +69,7 @@ class WebServiceHelper { if (proxy) { result.proxy = proxyToUrl(proxy); } - console.log(result); + // console.log(result) return result; } static buildCertAgentOpt(cert) { diff --git a/src/factory/interface/nfe/index.ts b/src/factory/interface/nfe/index.ts index 30959c0..6361e9c 100644 --- a/src/factory/interface/nfe/index.ts +++ b/src/factory/interface/nfe/index.ts @@ -29,7 +29,7 @@ export interface RetornoProcessamento { xml_recebido: string, status: number, success: boolean, - data: Object, + data: {retEnviNFe?: Object}, error: string } @@ -74,6 +74,7 @@ export interface DocumentoFiscal { justificativaContingencia: string; isContingenciaOffline: boolean; indIntermed?: string; + NFref?: {refNFe?: string}[]; } export interface Produto { @@ -81,6 +82,8 @@ export interface Produto { imposto: Imposto; infoAdicional: string; numeroItem: string; + pis: Object | undefined, + cofins: Object | undefined, } export interface DetalhesProduto { @@ -138,7 +141,8 @@ export interface Imposto { issqn: Issqn; pisst: PisST; cofinsst: CofinsST; - icmsUfDest: IcmsUfDest + icmsUfDest: IcmsUfDest; + IBSCBS: any } export interface Icms { @@ -270,10 +274,17 @@ export interface Issqn { indIncentivo: string } +export interface IbsCbsTot { + vIBS: string; + vCBS: string; + vIS: string; +} + export interface Total { icmsTot: IcmsTot; issqnTot: IssqnTot; retTrib: RetTrib; + IBSCBSTot?: IbsCbsTot; } export interface IcmsTot { @@ -329,6 +340,8 @@ export interface RetTrib { export interface Transporte { modalidateFrete: string; + transporta: Object, + vol: Object, //.. } diff --git a/src/factory/processor/enviaProcessor.ts b/src/factory/processor/enviaProcessor.ts index e0d8d9a..7da6b88 100644 --- a/src/factory/processor/enviaProcessor.ts +++ b/src/factory/processor/enviaProcessor.ts @@ -92,7 +92,7 @@ export class EnviaProcessor { } } catch (ex) { result.success = false; - result.error = ex; + result.error = ex as any; } return result; @@ -100,12 +100,10 @@ export class EnviaProcessor { private configuraUrlsSefaz() { const { geral: { modelo, ambiente }, empresa } = this.configuracoes; - if (!soapAutorizacao || !soapRetAutorizacao) { - let Sefaz = modelo == '65' ? SefazNFCe : SefazNFe; + let Sefaz = modelo == '65' ? SefazNFCe : SefazNFe; - soapAutorizacao = Sefaz.getSoapInfo(empresa.endereco.uf, ambiente, ServicosSefaz.autorizacao); - soapRetAutorizacao = Sefaz.getSoapInfo(empresa.endereco.uf, ambiente, ServicosSefaz.retAutorizacao); - } + soapAutorizacao = Sefaz.getSoapInfo(empresa.endereco.uf, ambiente, ServicosSefaz.autorizacao); + soapRetAutorizacao = Sefaz.getSoapInfo(empresa.endereco.uf, ambiente, ServicosSefaz.retAutorizacao); } private appendQRCodeXML(documento: NFCeDocumento, xmlAssinado: string) { @@ -165,7 +163,7 @@ export class EnviaProcessor { log(jsonOneLevel(retornoEnvio), 'retornoEnvio.full'); } catch (e) { - log(`ja deu erro pra logar.......${e.toString()}`, 'retornoEnvio') + log(`ja deu erro pra logar.......${e?.toString()}`, 'retornoEnvio') } if (retornoEnvio && retornoEnvio.data) { @@ -191,7 +189,7 @@ export class EnviaProcessor { result.envioNF = retornoEnvio; } catch (ex) { result.success = false; - result.error = ex; + result.error = ex as any; } result.success = true; //nao esta confirmada, mas houve sucesso nessa requisicao de envio da nota return result; @@ -387,7 +385,7 @@ export class EnviaProcessor { dhSaiEnt: documento.dhSaiEnt, dhCont: documento.dhContingencia, xJust: documento.justificativaContingencia, - //nFref: schema.TNFeInfNFeIdeNFref[], + NFref: documento.NFref, }; if (documento.indIntermed) { @@ -476,7 +474,7 @@ export class EnviaProcessor { prod: this.getDetProd(produtos[i].prod, ambiente, i == 0), imposto: this.getDetImposto(produtos[i].imposto, modelo, produtos[i].prod.CFOP), infAdProd: produtos[i].infoAdicional, - impostoDevol: (produtos[i].prod.percentualDevolucao && (produtos[i].prod.percentualDevolucao > 0)) ? this.getImpostoDevolucao({ pDevol: produtos[i].prod.percentualDevolucao, vIPIDevol: produtos[i].prod.valorIPIDevolucao }) : undefined + impostoDevol: (produtos[i].prod.percentualDevolucao && (produtos[i].prod.percentualDevolucao > 0)) ? this.getImpostoDevolucao({ pDevol: produtos[i].prod.percentualDevolucao, vIPIDevol: produtos[i].prod.valorIPIDevolucao }) : undefined, }); } @@ -535,6 +533,7 @@ export class EnviaProcessor { II: imposto.ii ? [this.getImpostoII(imposto.ii, cfop)] : [], ICMSUFDest: imposto.icmsUfDest ? [this.getIcmsUfDest(imposto.icmsUfDest)] : [], ISSQN: '', + IBSCBS: imposto.IBSCBS }; return detImposto; @@ -1027,6 +1026,7 @@ export class EnviaProcessor { CST: pis.CST } } + break; case '49': case '50': case '51': @@ -1062,6 +1062,7 @@ export class EnviaProcessor { vPIS: pis.vPIS } } + break; default: result = { PISOutr: { @@ -1262,7 +1263,8 @@ export class EnviaProcessor { private getTotal(total: Total) { return { - ICMSTot: total.icmsTot + ICMSTot: total.icmsTot, + ...(total.IBSCBSTot ? { IBSCBSTot: total.IBSCBSTot } : {}) } } @@ -1273,18 +1275,18 @@ export class EnviaProcessor { private getTransp(transp: Transporte) { return { - modFrete: transp.modalidateFrete + modFrete: transp.modalidateFrete, + transporta: transp.transporta, /** - * transporta: TNFeInfNFeTranspTransporta; - retTransp: TNFeInfNFeTranspRetTransp; - //balsa - //reboque - //vagao - //veicTransp + * retTransp: TNFeInfNFeTranspRetTransp; + balsa + reboque + vagao + veicTransp items: object[]; itemsElementName: ItemsChoiceType5[]; - vol: TNFeInfNFeTranspVol[]; - */ + */ + vol: transp.vol, } } @@ -1339,15 +1341,15 @@ export class EnviaProcessor { detPag.indPag = Utils.getEnumByValue(schema.TNFeInfNFePagDetPagIndPag, pag.indicadorFormaPagamento); detPag.tPag = Utils.getEnumByValue(schema.TNFeInfNFePagDetPagTPag, pag.formaPagamento); - detPag.vPag = pag.valor; - + if (pag.descricaoFormaPagamento) { detPag.xPag = pag.descricaoFormaPagamento; // YA02A NT 2020.006 } - + if (pag.dadosCartao) { detPag.card = this.getDetalhamentoCartao(pag.dadosCartao); } + detPag.vPag = pag.valor; listPagamentos.push(detPag); } diff --git a/src/factory/processor/nfeProcessor.ts b/src/factory/processor/nfeProcessor.ts index f7ff89f..811f5f2 100644 --- a/src/factory/processor/nfeProcessor.ts +++ b/src/factory/processor/nfeProcessor.ts @@ -1109,6 +1109,7 @@ export class NFeProcessor { CST: pis.CST } } + break; case '49': case '50': case '51': @@ -1144,6 +1145,7 @@ export class NFeProcessor { vPIS: pis.vPIS } } + break; default: result = { PISOutr: { diff --git a/src/factory/processor/nfeProcessor2.ts b/src/factory/processor/nfeProcessor2.ts index 530db89..5d86927 100644 --- a/src/factory/processor/nfeProcessor2.ts +++ b/src/factory/processor/nfeProcessor2.ts @@ -65,53 +65,86 @@ export class NFeProcessor { let retEnviNFe = null; let retConsReciNFe = null; - let cStat = ''; + let finalResponse = null; // Objeto que conterá o protNFe final if (result.envioNF && result.envioNF.data) { const data = Object(result.envioNF.data); - if (data.retEnviNFe && geral.modelo == '55') { + + if (data.retEnviNFe) { retEnviNFe = data.retEnviNFe; - const recibo = retEnviNFe.infRec.nRec; - result.consultaProc = await this.retornoProcessor.executar(recibo); - retConsReciNFe = Object(result.consultaProc.data).retConsReciNFe; - cStat = retConsReciNFe.cStat; + + // Lógica Assíncrona (NF-e Modelo 55) + if (geral.modelo == '55') { + if (retEnviNFe.infRec) { + const recibo = retEnviNFe.infRec.nRec; + result.consultaProc = await this.retornoProcessor.executar(recibo); + retConsReciNFe = Object(result.consultaProc.data).retConsReciNFe; + finalResponse = retConsReciNFe; + } else if (retEnviNFe.protNFe) { + finalResponse = retEnviNFe; + } + } + // Lógica Síncrona (NFC-e Modelo 65) + else { + // Na NFC-e o retorno do envio JÁ É o retorno final com protocolo + finalResponse = retEnviNFe; + } } - if (retEnviNFe && retConsReciNFe) - if (retEnviNFe.cStat == '103' && retConsReciNFe.cStat == '104') { //protNFe.infProt. + // Verificação de Sucesso + if (finalResponse) { + // Sucesso NF-e (Lote Recebido + Lote Processado) + if (geral.modelo == '55' && retEnviNFe.cStat == '103' && finalResponse.cStat == '104') { result.confirmada = true; result.success = true; } + // Sucesso NFC-e (Lote Processado Direto) + if (geral.modelo == '65' && finalResponse.cStat == '104') { + result.confirmada = true; + result.success = true; + } + } if (arquivos && arquivos.salvar) { if (!fs.existsSync(arquivos.pastaEnvio)) fs.mkdirSync(arquivos.pastaEnvio, { recursive: true }); if (!fs.existsSync(arquivos.pastaRetorno)) fs.mkdirSync(arquivos.pastaRetorno, { recursive: true }); if (!fs.existsSync(arquivos.pastaXML)) fs.mkdirSync(arquivos.pastaXML, { recursive: true }); - if ((result.success == true) && (retConsReciNFe.cStat == '104')) { - const filename = `${arquivos.pastaXML}${retConsReciNFe.protNFe.infProt.chNFe}-procNFe.xml`; + // Salvar XML de Processamento (Autorizado) + if ((result.success == true) && (finalResponse && finalResponse.cStat == '104' && finalResponse.protNFe)) { + const filename = `${arquivos.pastaXML}${finalResponse.protNFe.infProt.chNFe}-procNFe.xml`; const nfe_enviada = Object(XmlHelper.deserializeXml(result.envioNF.xml_enviado, { explicitArray: false })); + const nfeProc = { - $: { versao: "1.00", xmlns: "http://www.portalfiscal.inf.br/nfe" }, + $: { versao: "4.00", xmlns: "http://www.portalfiscal.inf.br/nfe" }, // Ajustado para 4.00 NFe: nfe_enviada.enviNFe.NFe, - protNFe: retConsReciNFe.protNFe + protNFe: finalResponse.protNFe }; Utils.removeSelfClosedFields(nfeProc); let xmlNfeProc = XmlHelper.serializeXml(nfeProc, 'nfeProc'); fs.writeFileSync(filename, xmlNfeProc); - } else { - const filenameEnvio = `${arquivos.pastaEnvio}${retEnviNFe.infRec.nRec}-enviNFe.xml`; - const filenameRetorno = `${arquivos.pastaRetorno}${retEnviNFe.infRec.nRec}-retEnviNFe.xml`; - fs.writeFileSync(filenameEnvio, result.envioNF.xml_enviado); - fs.writeFileSync(filenameRetorno, result.envioNF.xml_recebido); - - const filenameConsultaEnvio = `${arquivos.pastaEnvio}${retConsReciNFe.nRec}-consReciNFe.xml`; - const filenameConsultaRetorno = `${arquivos.pastaRetorno}${retConsReciNFe.nRec}-retConsReciNFe.xml`; - fs.writeFileSync(filenameConsultaEnvio, result.consultaProc.xml_enviado); - fs.writeFileSync(filenameConsultaRetorno, result.consultaProc.xml_recebido); + } + // Salvar XMLs de Erro / Logs + else { + const date = new Date().toISOString().replace(/:/g, '-'); + // Proteção: Se não houver nRec (erro de schema), usa timestamp + const idIdentificador = retEnviNFe?.infRec?.nRec || new Date().getTime().toString(); + + const filenameEnvio = `${arquivos.pastaEnvio}${date}-${idIdentificador}-enviNFe.xml`; + const filenameRetorno = `${arquivos.pastaRetorno}${date}-${idIdentificador}-retEnviNFe.xml`; + + if (result.envioNF.xml_enviado) fs.writeFileSync(filenameEnvio, result.envioNF.xml_enviado); + if (result.envioNF.xml_recebido) fs.writeFileSync(filenameRetorno, result.envioNF.xml_recebido); + + if (result.consultaProc) { + const filenameConsultaEnvio = `${arquivos.pastaEnvio}${retConsReciNFe.nRec}-consReciNFe.xml`; + const filenameConsultaRetorno = `${arquivos.pastaRetorno}${retConsReciNFe.nRec}-retConsReciNFe.xml`; + fs.writeFileSync(filenameConsultaEnvio, result.consultaProc.xml_enviado); + fs.writeFileSync(filenameConsultaRetorno, result.consultaProc.xml_recebido); + } } } } else if (result.retornoContingenciaOffline && result.success) { @@ -122,12 +155,90 @@ export class NFeProcessor { } } catch (ex) { result.success = false; - result.error = ex; + result.error = ex as any; } return result; } + // public async executar(documento: NFeDocumento | NFCeDocumento) { + // const { arquivos, geral } = this.configuracoes; + // let result = {}; + // try { + // result = await this.enviaProcessor.executar(documento); + + // let retEnviNFe = null; + // let retConsReciNFe = null; + // let cStat = ''; + + // if (result.envioNF && result.envioNF.data) { + // const data = Object(result.envioNF.data); + // retEnviNFe = data.retEnviNFe; + // if (data.retEnviNFe) { + // if (geral.modelo == '55' && retEnviNFe.infRec) { + // const recibo = retEnviNFe.infRec.nRec; + // result.consultaProc = await this.retornoProcessor.executar(recibo); + // } + // if (result.envioNF?.data?.retEnviNFe) + // retConsReciNFe = Object(result.envioNF.data.retEnviNFe); + // else + // retConsReciNFe = Object(result.consultaProc.data).retConsReciNFe; + // cStat = retConsReciNFe.cStat; + // } + + // if (retEnviNFe && retConsReciNFe) + // if (retEnviNFe.cStat == '103' && retConsReciNFe.cStat == '104') { //protNFe.infProt. + // result.confirmada = true; + // result.success = true; + // } + + // if (arquivos && arquivos.salvar) { + // if (!fs.existsSync(arquivos.pastaEnvio)) fs.mkdirSync(arquivos.pastaEnvio, { recursive: true }); + // if (!fs.existsSync(arquivos.pastaRetorno)) fs.mkdirSync(arquivos.pastaRetorno, { recursive: true }); + // if (!fs.existsSync(arquivos.pastaXML)) fs.mkdirSync(arquivos.pastaXML, { recursive: true }); + + // if ((result.success == true) && (retConsReciNFe.cStat == '104')) { + // const filename = `${arquivos.pastaXML}${retConsReciNFe.protNFe.infProt.chNFe}-procNFe.xml`; + + // const nfe_enviada = Object(XmlHelper.deserializeXml(result.envioNF.xml_enviado, { explicitArray: false })); + // const nfeProc = { + // $: { versao: "1.00", xmlns: "http://www.portalfiscal.inf.br/nfe" }, + // NFe: nfe_enviada.enviNFe.NFe, + // protNFe: retConsReciNFe.protNFe + // }; + + // Utils.removeSelfClosedFields(nfeProc); + // let xmlNfeProc = XmlHelper.serializeXml(nfeProc, 'nfeProc'); + + // fs.writeFileSync(filename, xmlNfeProc); + // } else { + // const date = new Date().toISOString().replace(/:/g, '-'); + // const filenameEnvio = `${arquivos.pastaEnvio}${date}${retEnviNFe.infRec?.nRec || ''}-enviNFe.xml`; + // const filenameRetorno = `${arquivos.pastaRetorno}${date}${retEnviNFe.infRec?.nRec || ''}-retEnviNFe.xml`; + // fs.writeFileSync(filenameEnvio, result.envioNF.xml_enviado); + // fs.writeFileSync(filenameRetorno, result.envioNF.xml_recebido); + // if (result.consultaProc) { + // const filenameConsultaEnvio = `${arquivos.pastaEnvio}${retConsReciNFe.nRec}-consReciNFe.xml`; + // const filenameConsultaRetorno = `${arquivos.pastaRetorno}${retConsReciNFe.nRec}-retConsReciNFe.xml`; + // fs.writeFileSync(filenameConsultaEnvio, result.consultaProc.xml_enviado); + // fs.writeFileSync(filenameConsultaRetorno, result.consultaProc.xml_recebido); + // } + // } + // } + // } else if (result.retornoContingenciaOffline && result.success) { + // return result; + // } else { + // console.error('nfeProcessor.executar: Erro ao realizar requisição', result); + // throw new Error('Erro ao realizar requisição'); + // } + // } catch (ex) { + // result.success = false; + // result.error = ex; + // } + + // return result; + // } + public async inutilizarNumeracao( dados: Inutilizar) { return await this.inutlizacaoProcessor.executar( dados ); } diff --git a/src/factory/schema/index.ts b/src/factory/schema/index.ts index 884240e..13eda65 100644 --- a/src/factory/schema/index.ts +++ b/src/factory/schema/index.ts @@ -158,7 +158,7 @@ export interface TNFeInfNFeIde { verProc: string; dhCont: string; xJust: string; - nFref: TNFeInfNFeIdeNFref[]; + NFref?: TNFeInfNFeIdeNFref[]; indIntermed?: TNFeInfNFeIdeIndIntermed; } @@ -253,7 +253,7 @@ export interface TNFeInfNFeIdeNFref { refNF?: TNFeInfNFeIdeNFrefRefNF; refNFP?: TNFeInfNFeIdeNFrefRefNFP; refNFe?: string; - itemElementName: ItemChoiceType1; + itemElementName?: ItemChoiceType1; } //[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://www.portalfiscal.inf.br/nfe")] @@ -560,6 +560,8 @@ export interface TNFeInfNFeDet { imposto: TNFeInfNFeDetImposto; impostoDevol: any; //TNFeInfNFeDetImpostoDevol; infAdProd: string; + PIS: Object, + COFINS: Object, } //[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://www.portalfiscal.inf.br/nfe")] diff --git a/src/factory/webservices/webserviceHelper.ts b/src/factory/webservices/webserviceHelper.ts index cc909f0..6524219 100644 --- a/src/factory/webservices/webserviceHelper.ts +++ b/src/factory/webservices/webserviceHelper.ts @@ -96,7 +96,7 @@ export abstract class WebServiceHelper { if (proxy) { result.proxy = proxyToUrl(proxy) } - console.log(result) + // console.log(result) return result } diff --git a/test.js b/test.js index c023760..598df94 100644 --- a/test.js +++ b/test.js @@ -4,11 +4,13 @@ const lib = require('./lib'); const signUtils = require('./lib/factory/signature'); const XmlHelper = require('./lib/factory/xmlHelper'); +const versao = '4.00' + let cert = { - key: fs.readFileSync('C:\\cert\\newKey.key'), - pem: fs.readFileSync('C:\\cert\\test.pem'), - pfx: fs.readFileSync('C:\\cert\\certificado.pfx'), - password: fs.readFileSync('C:\\cert\\senha.txt') + key: fs.readFileSync('C:\\node-dfe\\cert\\newKey.key'), + pem: fs.readFileSync('C:\\node-dfe\\cert\\test.pem'), + pfx: fs.readFileSync('C:\\node-dfe\\cert\\certificado.pfx'), + password: fs.readFileSync('C:\\node-dfe\\cert\\senha.txt').toString() }; let empresa = { @@ -68,6 +70,7 @@ let documento = { tipoEmissao: '1', tipoImpressao: '4', versaoAplicativoEmissao: 'NODE-NFE TEST 1.0', + NFref: [{refNFe: 'XXXXXXXXXXXXX'}, {refNFe: 'YYYYYYYYYYYYYY'}], }; let dest = { @@ -202,8 +205,25 @@ let nfce = { infoAdicional: infoAdic }; +const configuracoes = { + empresa: empresa, + certificado: cert, + geral: { + ambiente: documento.ambiente, + modelo: documento.modelo, + versao + }, + arquivos: { + salvar: true, + pastaEnvio: 'c:/node-dfe/xmls/envio', + pastaRetorno: 'c:/node-dfe/xmls/retorno', + pastaXML: 'c:/node-dfe/xmls/xml', + }, + responsavelTecnico: responsavelTecnico + } + async function testeEmissaoNFCe() { - const nfeProc = new lib.NFeProcessor(empresa, null); + const nfeProc = new lib.NFeProcessor(configuracoes, null); const ini = new Date(); let result = await nfeProc.processarDocumento(nfce); @@ -279,7 +299,7 @@ function testHashRespTec(){ //testeAssinaturaXML(); //testeConsultaStatusServico(empresa, '2', '65'); //testeDesereliaze(); -//testeEmissaoNFCe(); -testeEmissaoNFCeContingenciaOffline(empresa); +testeEmissaoNFCe(); +// testeEmissaoNFCeContingenciaOffline(empresa); //testeQRcodeNFCe(); //testHashRespTec(); \ No newline at end of file