Exemple #1
0
        /// <summary>
        /// Busca XML da NFe passada para imprimir o DANFE
        /// </summary>
        /// <param name="idNFe"></param>
        /// <returns></returns>
        internal ProdutosNFe[] GetForDanfe(HttpContext context, string chaveAcesso)
        {
            List <ProdutosNFe> lstProdNFe = new List <ProdutosNFe>();

            // Verifica se NFe existe
            if (!File.Exists(Utils.GetNfeXmlPathInternal(context) + chaveAcesso + "-nfe.xml"))
            {
                throw new Exception("Arquivo da NF-e não encontrado.");
            }

            // Busca arquivo XML da NFe
            XmlDocument xmlNFe = new XmlDocument();

            xmlNFe.Load(Utils.GetNfeXmlPathInternal(context) + chaveAcesso + "-nfe.xml");

            #region Busca produtos da NF-e contidos no XML

            // Busca tags com produtos
            XmlNodeList xmlListProdsNFe = NFeDAO.Instance.GetXmlInfNFe(context, xmlNFe).GetElementsByTagName("det");

            foreach (XmlElement xmlProd in xmlListProdsNFe)
            {
                ProdutosNFe prod = new ProdutosNFe();
                prod.Codigo    = GetNodeValue(xmlProd, "prod", "cProd");
                prod.Descricao = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlProd, "prod", "xProd"));
                prod.NcmSh     = GetNodeValue(xmlProd, "prod", "NCM");
                prod.Cfop      = GetNodeValue(xmlProd, "prod", "CFOP");
                prod.Unidade   = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlProd, "prod", "uCom"));
                prod.Qtd       = Formatacoes.FormataValorDecimal(GetNodeValue(xmlProd, "prod", "qCom"), 4);
                prod.VlrUnit   = Formatacoes.FormataValorDecimal(GetNodeValue(xmlProd, "prod", "vUnCom"), 2);
                prod.VlrTotal  = Formatacoes.FormataValorDecimal(GetNodeValue(xmlProd, "prod", "vProd"), 2);
                prod.Cst       = GetICMSNodeValue(xmlProd, "imposto/ICMS", "orig") + GetICMSNodeValue(xmlProd, "imposto/ICMS", "CST");
                prod.Csosn     = GetICMSNodeValue(xmlProd, "imposto/ICMS", "orig") + GetICMSNodeValue(xmlProd, "imposto/ICMS", "CSOSN");
                prod.BcIcms    = Formatacoes.FormataValorDecimal(GetICMSNodeValue(xmlProd, "imposto/ICMS", "vBC"), 2);
                prod.AliqIcms  = Formatacoes.FormataValorDecimal(GetICMSNodeValue(xmlProd, "imposto/ICMS", "pICMS"), 2);
                prod.VlrIcms   = Formatacoes.FormataValorDecimal(GetICMSNodeValue(xmlProd, "imposto/ICMS", "vICMS"), 2);
                prod.BcIcmsSt  = Formatacoes.FormataValorDecimal(GetICMSNodeValue(xmlProd, "imposto/ICMS", "vBCST"), 2);
                prod.VlrIcmsSt = Formatacoes.FormataValorDecimal(GetICMSNodeValue(xmlProd, "imposto/ICMS", "vICMSST"), 2);
                prod.AliqIpi   = Formatacoes.FormataValorDecimal(GetNodeValue(xmlProd, "imposto/IPI/IPITrib", "pIPI"), 2);
                prod.VlrIpi    = Formatacoes.FormataValorDecimal(GetNodeValue(xmlProd, "imposto/IPI/IPITrib", "vIPI"), 2);

                lstProdNFe.Add(prod);

                if (xmlProd["infAdProd"] != null)
                {
                    ProdutosNFe pNf = new ProdutosNFe();
                    pNf.InfAdic   = true;
                    pNf.Descricao = Formatacoes.RestauraStringDocFiscal(xmlProd["infAdProd"].InnerText);
                    lstProdNFe.Add(pNf);
                }
            }

            #endregion

            return(lstProdNFe.ToArray());
        }
Exemple #2
0
        internal static MDFe ObterParaDAMDFE(HttpContext context, string chaveAcesso)
        {
            MDFe mdfe = new MDFe();

            Glass.Data.Model.ManifestoEletronico _manifestoEletronico = Glass.Data.DAL.ManifestoEletronicoDAO.Instance.ObterPelaChaveAcesso(chaveAcesso);

            // Verifica se o MDFe existe
            if (!File.Exists(Utils.GetMDFeXmlPathInternal(context) + chaveAcesso + "-mdfe.xml"))
            {
                throw new Exception("Arquivo do MDFe não encontrado.");
            }

            // Carrega o arquivo XML
            XmlDocument xmlMDFe = new XmlDocument();

            xmlMDFe.Load(Utils.GetMDFeXmlPathInternal(context) + chaveAcesso + "-mdfe.xml");
            XmlElement xmlInfMDFe = ObterXmlInfMDFe(context, xmlMDFe);

            #region Busca dados do XML do MDFe

            #region IDENTIFICAÇÃO MDF-e

            mdfe.ChaveAcesso = Formatacoes.MascaraChaveAcessoNFe(chaveAcesso);
            mdfe.Modelo      = GetNodeValue(xmlInfMDFe, "ide", "mod");
            mdfe.Serie       = GetNodeValue(xmlInfMDFe, "ide", "serie");
            mdfe.TipoEmissao = GetNodeValue(xmlInfMDFe, "ide", "tpEmis") == "1" ? "Normal" : "Contingência";
            mdfe.NumeroManifestoEletronico = GetNodeValue(xmlInfMDFe, "ide", "nMDF");
            mdfe.TipoAmbiente = Conversoes.StrParaInt(GetNodeValue(xmlInfMDFe, "ide", "tpAmb"));
            mdfe.DataEmissao  = DateTime.Parse(GetNodeValue(xmlInfMDFe, "ide", "dhEmi")).ToString("dd/MM/yyyy HH:mm");
            mdfe.UFInicio     = GetNodeValue(xmlInfMDFe, "ide", "UFIni");
            mdfe.UFFim        = GetNodeValue(xmlInfMDFe, "ide", "UFFim");

            //Protocolo de autorização
            if (xmlMDFe["MDFe"] != null && xmlMDFe["MDFe"]["infProt"] != null) // Sql montado no sistema
            {
                mdfe.ProtocoloAutorizacao = GetNodeValue(xmlMDFe["MDFe"], "infProt", "nProt") + " " +
                                            DateTime.Parse(GetNodeValue(xmlMDFe["MDFe"], "infProt", "dhRecbto")).ToString("dd/MM/yyyy HH:mm");
            }
            else if (xmlMDFe["mdfeProc"] != null && xmlMDFe["mdfeProc"]["protMDFe"] != null) // Sql montado na receita
            {
                mdfe.ProtocoloAutorizacao = GetNodeValue(xmlMDFe["mdfeProc"]["protMDFe"], "infProt", "nProt") + " " +
                                            DateTime.Parse(GetNodeValue(xmlMDFe["mdfeProc"]["protMDFe"], "infProt", "dhRecbto")).ToString("dd/MM/yyyy HH:mm");
            }

            if (mdfe.TipoEmissao == "Contingência" && string.IsNullOrWhiteSpace(mdfe.ProtocoloAutorizacao))
            {
                mdfe.ProtocoloAutorizacao = "Impressão em contingência. Obrigatória a autorização em 168 horas após esta emissão. ("
                                            + mdfe.DataEmissao + ")";
            }

            // Emitente
            mdfe.RazaoSocialEmitente = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfMDFe, "emit", "xNome"));
            mdfe.EnderecoEmitente    = Formatacoes.RestauraStringDocFiscal(ObterEnderecoEmitente(xmlInfMDFe));
            mdfe.CNPJEmitente        = Formatacoes.MascaraCnpj(GetNodeValue(xmlInfMDFe, "emit", "CNPJ"));
            mdfe.InscEstEmitente     = GetNodeValue(xmlInfMDFe, "emit", "IE");

            #endregion

            #region INFORMAÇÕES DO MODAL RODOVIARIO

            if (xmlInfMDFe["infModal"]["rodo"] != null)
            {
                var _RNTRC = string.Empty;

                XmlElement xmlRodo = xmlInfMDFe["infModal"]["rodo"];

                #region Grupo de informações para Agência Reguladora

                if (xmlRodo["infANTT"] != null)
                {
                    var _CIOTs                    = new List <string>();
                    var _ResponsaveisCIOT         = new List <string>();
                    var _CNPJsResponsaveisPedagio = new List <string>();
                    var _CNPJsFornecedoresPedagio = new List <string>();
                    var _NumerosCompraPedagio     = new List <string>();

                    _RNTRC = GetNodeValue(xmlRodo, "infANTT", "RNTRC");

                    var xmlListainfCIOT = xmlRodo["infANTT"].GetElementsByTagName("infCIOT");
                    foreach (XmlElement infCIOT in xmlListainfCIOT)
                    {
                        _CIOTs.Add(infCIOT["CIOT"].InnerXml);
                        _ResponsaveisCIOT.Add(Formatacoes.MascaraCnpj(infCIOT["CNPJ"].InnerXml));
                    }

                    if (xmlRodo["infANTT"]["valePed"] != null)
                    {
                        var xmlListaValePedagio = xmlRodo["infANTT"]["valePed"].GetElementsByTagName("disp");
                        foreach (XmlElement disp in xmlListaValePedagio)
                        {
                            _CNPJsResponsaveisPedagio.Add(disp["CNPJPg"] != null ? Formatacoes.MascaraCnpj(disp["CNPJPg"].InnerXml) : mdfe.CNPJEmitente);
                            _CNPJsFornecedoresPedagio.Add(Formatacoes.MascaraCnpj(disp["CNPJForn"].InnerXml));
                            _NumerosCompraPedagio.Add(disp["nCompra"].InnerXml);
                        }
                    }

                    mdfe.CIOTs                    = string.Join("\n", _CIOTs);
                    mdfe.ResposaveisCIOTs         = string.Join("\n", _ResponsaveisCIOT);
                    mdfe.CNPJsResponsaveisPedagio = string.Join("\n", _CNPJsResponsaveisPedagio);
                    mdfe.CNPJsFornecedoresPedagio = string.Join("\n", _CNPJsFornecedoresPedagio);
                    mdfe.NumerosCompraPedagio     = string.Join("\n", _NumerosCompraPedagio);
                }

                #endregion

                #region Veículos e Condutores

                var _placasVeiculos  = new List <string>();
                var _RNTRCsVeiculos  = new List <string>();
                var _CPFsCondutores  = new List <string>();
                var _NomesCondutores = new List <string>();

                // Dados do Veículo Tração
                _placasVeiculos.Add(GetNodeValue(xmlRodo, "veicTracao", "placa"));
                if (xmlRodo["veicTracao"]["prop"] != null)
                {
                    _RNTRCsVeiculos.Add(GetNodeValue(xmlRodo, "veicTracao/prop", "RNTRC"));
                }
                else
                {
                    _RNTRCsVeiculos.Add(_RNTRC);
                }

                // Informações do(s) Condutor(s) do veículo
                var xmlListaCondutor = xmlRodo["veicTracao"].GetElementsByTagName("condutor");
                foreach (XmlElement condutor in xmlListaCondutor)
                {
                    _CPFsCondutores.Add(Formatacoes.MascaraCpf(condutor["CPF"].InnerXml));
                    _NomesCondutores.Add(condutor["xNome"].InnerXml);
                }

                // Dados do Veículo Reboque
                if (xmlRodo["veicReboque"] != null)
                {
                    var xmlListaVeicReboque = xmlRodo.GetElementsByTagName("veicReboque");
                    foreach (XmlElement veicReboque in xmlListaVeicReboque)
                    {
                        _placasVeiculos.Add(veicReboque["placa"].InnerXml);
                        if (xmlRodo["prop"] != null)
                        {
                            _RNTRCsVeiculos.Add(GetNodeValue(veicReboque, "prop", "RNTRC"));
                        }
                        else
                        {
                            _RNTRCsVeiculos.Add(_RNTRC);
                        }
                    }
                }

                mdfe.PlacasVeiculos  = string.Join("\n", _placasVeiculos);
                mdfe.RNTRCsVeiculos  = string.Join("\n", _RNTRCsVeiculos);
                mdfe.CPFsCondutores  = string.Join("\n", _CPFsCondutores);
                mdfe.NomesCondutores = string.Join("\n", _NomesCondutores);

                #endregion
            }

            #endregion

            #region INFORMAÇÕES DOS DOCUMENTOS FISCAIS VINCULADOS

            if (mdfe.TipoEmissao == "Contingência" && xmlInfMDFe["infDoc"] != null)
            {
                var _documentosVinculados  = new List <string>();
                var xmlListaInfMunDescarga = xmlInfMDFe["infDoc"].GetElementsByTagName("infMunDescarga");
                foreach (XmlElement infMunDescarga in xmlListaInfMunDescarga)
                {
                    // Se Tipo Emitente for Transportador de carga própria
                    if (GetNodeValue(xmlInfMDFe, "ide", "tpEmit") == "2")
                    {
                        var xmlListaInfNFe = infMunDescarga.GetElementsByTagName("infNFe");
                        foreach (XmlElement infNFe in xmlListaInfNFe)
                        {
                            _documentosVinculados.Add("NFe: " + infNFe["chNFe"].InnerXml);
                        }
                    }
                    else
                    {
                        var xmlListaInfCTe = infMunDescarga.GetElementsByTagName("infCTe");
                        foreach (XmlElement infCTe in xmlListaInfCTe)
                        {
                            _documentosVinculados.Add("CTe: " + infCTe["chCTe"].InnerXml);
                        }
                    }
                }

                mdfe.DocumentosFiscaisVinculados = string.Join("\n", _documentosVinculados);
            }

            #endregion

            #region TOTALIZADORES DA CARGA

            mdfe.QuantidadeCTe  = string.IsNullOrWhiteSpace(GetNodeValue(xmlInfMDFe, "tot", "qCTe")) ? "0" : GetNodeValue(xmlInfMDFe, "tot", "qCTe");
            mdfe.QuantidadeNFe  = string.IsNullOrWhiteSpace(GetNodeValue(xmlInfMDFe, "tot", "qNFe")) ? "0" : GetNodeValue(xmlInfMDFe, "tot", "qNFe");
            mdfe.ValorCarga     = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfMDFe, "tot", "vCarga"), 2);
            mdfe.CodigoUnidade  = GetNodeValue(xmlInfMDFe, "tot", "cUnid").StrParaInt() == 1 ? "KG" : "TON";
            mdfe.PesoTotalCarga = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfMDFe, "tot", "qCarga"), 4);

            #endregion

            #region INFORMAÇÕES ADICIONAIS

            mdfe.InformacoesAdicionaisFisco = GetNodeValue(xmlInfMDFe, "infAdic", "infAdFisco");
            mdfe.InformacoesComplementares  = GetNodeValue(xmlInfMDFe, "infAdic", "infCpl");

            #endregion

            #endregion

            return(mdfe);
        }
Exemple #3
0
        /// <summary>
        /// Busca XML da NFe passada para imprimir o DANFE
        /// </summary>
        /// <param name="idNFe"></param>
        /// <returns></returns>
        internal NFe GetForDanfe(HttpContext context, string chaveAcesso)
        {
            NFe nfe = new NFe();

            // Verifica se NFe existe
            if (!File.Exists(Utils.GetNfeXmlPathInternal(context) + chaveAcesso + "-nfe.xml"))
            {
                throw new Exception("Arquivo da NF-e não encontrado.");
            }

            // Busca arquivo XML da NFe
            XmlDocument xmlNFe = new XmlDocument();

            xmlNFe.Load(Utils.GetNfeXmlPathInternal(context) + chaveAcesso + "-nfe.xml");
            XmlElement xmlInfNFe = GetXmlInfNFe(context, xmlNFe);

            var versao = xmlNFe["nfeProc"] != null ?
                         xmlNFe["nfeProc"]["NFe"]["infNFe"].GetAttribute("versao") :
                         xmlNFe["NFe"]["infNFe"].GetAttribute("versao");

            #region Busca dados do XML da NF-e

            // Cabeçalho
            nfe.RazaoSocialEmit = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfNFe, "emit", "xNome"));
            nfe.NumeroNfe       = Formatacoes.MascaraNroNFe(GetNodeValue(xmlInfNFe, "ide", "nNF"));
            nfe.SerieNfe        = GetNodeValue(xmlInfNFe, "ide", "serie");
            nfe.ModeloNfe       = GetNodeValue(xmlInfNFe, "ide", "mod");
            nfe.EnderecoEmit    = Formatacoes.RestauraStringDocFiscal(GetEnderecoEmit(xmlInfNFe));
            nfe.TipoNfe         = GetNodeValue(xmlInfNFe, "ide", "tpNF");
            nfe.TipoAmbiente    = Glass.Conversoes.StrParaInt(GetNodeValue(xmlInfNFe, "ide", "tpAmb"));
            nfe.ChaveAcesso     = Formatacoes.MascaraChaveAcessoNFe(chaveAcesso);
            nfe.UfNfe           = Glass.Conversoes.StrParaInt(GetNodeValue(xmlInfNFe, "ide", "cUF"));
            nfe.TipoEmissao     = Glass.Conversoes.StrParaInt(GetNodeValue(xmlInfNFe, "ide", "tpEmis"));

            // Dados da NF-e
            nfe.NatOperacao   = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfNFe, "ide", "natOp"));
            nfe.InscEstEmit   = GetNodeValue(xmlInfNFe, "emit", "IE");
            nfe.InscEstStEmit = GetNodeValue(xmlInfNFe, "emit", "IEST");
            nfe.CnpjEmit      = Formatacoes.MascaraCnpj(GetNodeValue(xmlInfNFe, "emit", "CNPJ"));

            if (xmlNFe["NFe"] != null && xmlNFe["NFe"]["infProt"] != null) // Sql montado no sistema
            {
                nfe.ProtAutorizacao = GetNodeValue(xmlNFe["NFe"], "infProt", "nProt") + " " + GetNodeValue(xmlNFe["NFe"], "infProt", "dhRecbto").Replace("T", " ");
            }
            else if (xmlNFe["nfeProc"] != null && xmlNFe["nfeProc"]["protNFe"] != null) // Sql montado na receita
            {
                nfe.ProtAutorizacao = GetNodeValue(xmlNFe["nfeProc"]["protNFe"], "infProt", "nProt") + " " + GetNodeValue(xmlNFe["nfeProc"]["protNFe"], "infProt", "dhRecbto").Replace("T", " ");
            }

            // Preencher a partir do banco até mudarmos para baixar o xml direto da receita com o protocolo, caso a nota fique sem após a autorização
            if (string.IsNullOrEmpty(nfe.ProtAutorizacao))
            {
                nfe.ProtAutorizacao = DAL.NotaFiscalDAO.Instance.ObtemValorCampo <string>("NumProtocolo", "ChaveAcesso=?chaveAcesso", new GDA.GDAParameter("?chaveAcesso", chaveAcesso));
            }

            // Esta verificação não pode ser feita ao pré-visualizar nota
            //if (String.IsNullOrEmpty(nfe.ProtAutorizacao))
            //    throw new Exception("Nota sem protocolo.");

            // Destinatário/Remetente
            nfe.RazaoSocialRemet = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfNFe, "dest", "xNome"));
            nfe.CpfCnpjRemet     = Formatacoes.MascaraCpfCnpj(GetNodeValue(xmlInfNFe, "dest", "CNPJ") + GetNodeValue(xmlInfNFe, "dest", "CPF"));
            nfe.EnderecoRemet    = Formatacoes.RestauraStringDocFiscal((GetNodeValue(xmlInfNFe, "dest/enderDest", "xLgr") + ", " + GetNodeValue(xmlInfNFe, "dest/enderDest", "nro") + " " + GetNodeValue(xmlInfNFe, "dest/enderDest", "xCpl")));
            nfe.BairroRemet      = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfNFe, "dest/enderDest", "xBairro"));
            nfe.CepRemet         = GetNodeValue(xmlInfNFe, "dest/enderDest", "CEP");
            nfe.MunicipioRemet   = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfNFe, "dest/enderDest", "xMun"));
            nfe.FoneRemet        = GetNodeValue(xmlInfNFe, "dest/enderDest", "fone");
            nfe.UfRemet          = GetNodeValue(xmlInfNFe, "dest/enderDest", "UF");
            nfe.InscEstRemet     = GetNodeValue(xmlInfNFe, "dest", "IE");
            try
            {
                nfe.DataEmissao         = DateTime.Parse(GetNodeValue(xmlInfNFe, "ide", "dhEmi")).ToString("dd/MM/yyyy HH:mm:ss");
                nfe.DataEmissaoOriginal = GetNodeValue(xmlInfNFe, "ide", "dhEmi");
            }
            catch { }
            try
            {
                nfe.DataEntradaSaida = DateTime.Parse(GetNodeValue(xmlInfNFe, "ide", "dhSaiEnt")).ToString("dd/MM/yyyy HH:mm");
            }
            catch { }

            // Fatura/Duplicatas
            if (DAL.NotaFiscalDAO.Instance.ObtemFormaPagto(chaveAcesso) == Model.NotaFiscal.FormaPagtoEnum.AVista) // Pagamento à vista
            {
                string nFat  = GetNodeValue(xmlInfNFe, "cobr/fat", "nFat");
                string vOrig = GetNodeValue(xmlInfNFe, "cobr/fat", "vOrig");
                string vLiq  = GetNodeValue(xmlInfNFe, "cobr/fat", "vLiq");

                nfe.Fatura = "Pagamento à vista / Num.: " + nFat + " / V. Orig.: " + vOrig.Replace('.', ',') + " / V. Liq.: " + vLiq.Replace('.', ',');
            }
            else if (xmlInfNFe["cobr"] != null) // Pagamento à prazo/outros
            {
                // Busca tags com duplicatas
                XmlNodeList xmlListDup = xmlInfNFe["cobr"].GetElementsByTagName("dup");

                string nFat = xmlInfNFe["cobr"]["fat"] != null?GetNodeValue(xmlInfNFe, "cobr/fat", "nFat") : string.Empty;

                foreach (XmlElement xmlDup in xmlListDup)
                {
                    nfe.Fatura +=
                        "Num.: " + nFat + "-" + xmlDup["nDup"].InnerXml +
                        " Venc.: " + DateTime.Parse(xmlDup["dVenc"].InnerXml).ToString("dd/MM/yyyy") +
                        " Valor: " + xmlDup["vDup"].InnerXml.Replace('.', ',') + "   /   ";
                }

                if (nfe.Fatura != null)
                {
                    nfe.Fatura = nfe.Fatura.TrimEnd(' ').TrimEnd('/');
                }
            }

            // Cálculo do Imposto
            nfe.BcIcms         = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfNFe, "total/ICMSTot", "vBC"), 2);
            nfe.VlrIcms        = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfNFe, "total/ICMSTot", "vICMS"), 2);
            nfe.BcIcmsSt       = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfNFe, "total/ICMSTot", "vBCST"), 2);
            nfe.VlrIcmsSt      = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfNFe, "total/ICMSTot", "vST"), 2);
            nfe.VlrFrete       = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfNFe, "total/ICMSTot", "vFrete"), 2);
            nfe.VlrSeguro      = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfNFe, "total/ICMSTot", "vSeg"), 2);
            nfe.Desconto       = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfNFe, "total/ICMSTot", "vDesc"), 2);
            nfe.OutrasDespesas = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfNFe, "total/ICMSTot", "vOutro"), 2);
            nfe.VlrIpi         = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfNFe, "total/ICMSTot", "vIPI"), 2);
            nfe.VlrTotalProd   = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfNFe, "total/ICMSTot", "vProd"), 2);
            nfe.VlrTotalNota   = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfNFe, "total/ICMSTot", "vNF"), 2);

            // Transportador/Volumes transportados
            string modFrete = GetNodeValue(xmlInfNFe, "transp", "modFrete");
            nfe.RazaoSocialTransp = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfNFe, "transp/transporta", "xNome"));
            nfe.CpfCnpjTransp     = Formatacoes.MascaraCpfCnpj(GetNodeValue(xmlInfNFe, "transp/transporta", "CNPJ") + GetNodeValue(xmlInfNFe, "transp/transporta", "CPF"));

            switch ((Model.ModalidadeFrete)(modFrete.StrParaInt()))
            {
            case Model.ModalidadeFrete.ContaDoRemetente: nfe.FretePorConta = "0 - Rem (CIF)"; break;

            case Model.ModalidadeFrete.ContaDoDestinatario: nfe.FretePorConta = "1 - Dest (FOB)"; break;

            case Model.ModalidadeFrete.ContaDeTerceiros: nfe.FretePorConta = "2 - Terceiros"; break;

            case Model.ModalidadeFrete.ProprioContaDoRemetente: nfe.FretePorConta = "3 - Prop Rem"; break;

            case Model.ModalidadeFrete.ProprioContaDoDestinatario: nfe.FretePorConta = "4 - Prop Dest"; break;

            case Model.ModalidadeFrete.SemTransporte: nfe.FretePorConta = "9 - Sem Ocorr"; break;

            default: break;
            }

            nfe.CodAntt         = GetNodeValue(xmlInfNFe, "transp/veicTransp", "RNTC");
            nfe.PlacaVeiculo    = GetNodeValue(xmlInfNFe, "transp/veicTransp", "placa");
            nfe.UfVeiculo       = GetNodeValue(xmlInfNFe, "transp/veicTransp", "UF");
            nfe.EnderecoTransp  = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfNFe, "transp/transporta", "xEnder"));
            nfe.MunicipioTransp = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfNFe, "transp/transporta", "xMun"));
            nfe.UfTransp        = GetNodeValue(xmlInfNFe, "transp/transporta", "UF");
            nfe.InscEstTransp   = GetNodeValue(xmlInfNFe, "transp/transporta", "IE");
            nfe.QtdTransp       = GetNodeValue(xmlInfNFe, "transp/vol", "qVol");
            nfe.EspecieTransp   = GetNodeValue(xmlInfNFe, "transp/vol", "esp");
            nfe.MarcaTransp     = GetNodeValue(xmlInfNFe, "transp/vol", "marca");
            nfe.NumeracaoTransp = GetNodeValue(xmlInfNFe, "transp/vol", "nVol");
            nfe.PesoLiquido     = GetNodeValue(xmlInfNFe, "transp/vol", "pesoL");
            nfe.PesoBruto       = GetNodeValue(xmlInfNFe, "transp/vol", "pesoB");

            // Cálculo do ISSQN
            nfe.InscMunicIssqn        = GetNodeValue(xmlInfNFe, "emit/enderEmit", "IM");
            nfe.VlrTotalServicosIssqn = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfNFe, "total/ISSQNtot", "vServ"), 2);
            nfe.BcIssqn  = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfNFe, "total/ISSQNtot", "vBC"), 2);
            nfe.VlrIssqn = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfNFe, "total/ISSQNtot", "vISS"), 2);

            // Dados adicionais
            nfe.InformacoesCompl = (!string.IsNullOrEmpty(GetNodeValue(xmlInfNFe, "infAdic", "infAdFisco")) ? GetNodeValue(xmlInfNFe, "infAdic", "infAdFisco") + "\r\n" : "") +
                                   (!string.IsNullOrEmpty(GetNodeValue(xmlInfNFe, "infAdic", "infCpl")) ? Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfNFe, "infAdic", "infCpl")) + "\r\n" : "") +
                                   (ConfigNFe.TipoAmbiente == ConfigNFe.TipoAmbienteNfe.Producao || nfe.ModeloNfe == "65" ? string.Empty : "SEM VALOR FISCAL.");

            // Dados de controle
            nfe.Crt = GetNodeValue(xmlInfNFe, "emit", "CRT");

            //NFC-e
            if (nfe.ModeloNfe == "65")
            {
                var xmlSignature = GetXmlSignature(context, xmlNFe);
                if (xmlSignature != null)
                {
                    nfe.DigestValue = GetNodeValue(xmlSignature, "SignedInfo/Reference", "DigestValue");

                    nfe.LinkQrCode = GetXmlInfNFeSupl(context, xmlNFe)["qrCode"].InnerText;
                    nfe.UrlChave   = GetXmlInfNFeSupl(context, xmlNFe)["urlChave"].InnerText;
                }
            }

            #endregion

            return(nfe);
        }
Exemple #4
0
        /// <summary>
        /// Busca XML do CTe passado para imprimir o DACTE
        /// </summary>
        /// <param name="context"></param>
        /// <param name="chaveAcesso"></param>
        /// <returns></returns>
        internal static CTe GetForDacte(HttpContext context, string chaveAcesso)
        {
            CTe cte = new CTe();

            Glass.Data.Model.Cte.ConhecimentoTransporte _cte = Glass.Data.DAL.CTe.ConhecimentoTransporteDAO.Instance.GetByChaveAcesso(chaveAcesso);

            // Verifica se CTe existe
            if (!File.Exists(Utils.GetCteXmlPathInternal(context) + chaveAcesso + "-cte.xml"))
            {
                throw new Exception("Arquivo do CT-e não encontrado.");
            }

            // Busca arquivo XML do CTe
            XmlDocument xmlCTe = new XmlDocument();

            xmlCTe.Load(Utils.GetCteXmlPathInternal(context) + chaveAcesso + "-cte.xml");
            XmlElement xmlInfCTe = GetXmlInfCTe(context, xmlCTe);

            #region Busca dados do XML do CT-e

            // Identificação do Emitente
            cte.RazaoSocialEmit = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfCTe, "emit", "xNome"));
            cte.EnderecoEmit    = Formatacoes.RestauraStringDocFiscal(GetEnderecoEmit(xmlInfCTe));
            cte.CnpjCpfEmitente = Formatacoes.MascaraCnpj(GetNodeValue(xmlInfCTe, "emit", "CNPJ"));
            cte.InscEstEmitente = GetNodeValue(xmlInfCTe, "emit", "IE");

            //Modal
            cte.Modal = "RODOVIÁRIO";

            //Modelo
            cte.Modelo = GetNodeValue(xmlInfCTe, "ide", "mod");

            //Série
            cte.SerieCte = GetNodeValue(xmlInfCTe, "ide", "serie");

            //Número
            cte.NumeroCte = Formatacoes.MascaraNroCTe(GetNodeValue(xmlInfCTe, "ide", "nCT"));

            //Tipo Ambiente
            cte.TipoAmbiente = Glass.Conversoes.StrParaInt(GetNodeValue(xmlInfCTe, "ide", "tpAmb"));

            //Data e hora de emissão
            cte.DHEmissao = GetNodeValue(xmlInfCTe, "ide", "dhEmi");

            cte.FormaEmissao = GetNodeValue(xmlInfCTe, "ide", "tpEmis");

            //Inscrição Suframa Destinatário
            cte.InscSuframa = GetNodeValue(xmlInfCTe, "dest", "ISUF");

            //Chave de acesso
            cte.ChaveAcesso = Formatacoes.MascaraChaveAcessoCTe(chaveAcesso);

            //Protocolo de autorização
            if (xmlCTe["CTe"] != null && xmlCTe["CTe"]["infProt"] != null) // Sql montado no sistema
            {
                cte.ProtocoloAutorizacao = GetNodeValue(xmlCTe["CTe"], "infProt", "nProt") + " " + GetNodeValue(xmlCTe["CTe"], "infProt", "dhRecbto").Replace("T", " ");
            }
            else if (xmlCTe["cteProc"] != null && xmlCTe["cteProc"]["protCte"] != null) // Sql montado na receita
            {
                cte.ProtocoloAutorizacao = GetNodeValue(xmlCTe["cteProc"]["protCte"], "infProt", "nProt") + " " + GetNodeValue(xmlCTe["cteProc"]["protCte"], "infProt", "dhRecbto").Replace("T", " ");
            }

            //Tipo Cte
            var tipoCte = GetNodeValue(xmlInfCTe, "ide", "tpCTe");
            cte.TipoCte = tipoCte == "0" ? "Normal" : tipoCte == "1" ? "Complemento Valores" : tipoCte == "2" ? "Anulação Valores" : "Substituto";

            //Tipo Servico
            var tipoServico = GetNodeValue(xmlInfCTe, "ide", "tpServ");
            cte.TipoServico = tipoServico == "0" ? "Normal" : tipoServico == "1" ? "Subcontratação" : tipoServico == "2" ? "Redespacho" : "Redespacho Intermediário";

            //CFOP - natureza operação
            cte.NatOperacao = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfCTe, "ide", "natOp"));

            var codInternoCfop = GetNodeValue(xmlInfCTe, "ide", "CFOP");

            var cfop = new GDA.Sql.Query("CodInterno=?codInterno")
                       .Add("?codInterno", codInternoCfop)
                       .First <Glass.Data.Model.Cfop>();

            //Origem prestação
            cte.OrigemPrestacao = GetNodeValue(xmlInfCTe, "ide", "UFIni") + "-" + GetNodeValue(xmlInfCTe, "ide", "xMunIni");

            //Destino prestação
            cte.DestinoPrestacao = GetNodeValue(xmlInfCTe, "ide", "UFFim") + "-" + GetNodeValue(xmlInfCTe, "ide", "xMunFim");

            //Campo de uso livre do contribuinte
            cte.InformacoesAdicionais = GetNodeValue(xmlInfCTe, "compl", "xObs") + "\n" + cfop.Obs;

            //Remetente
            cte.Remetente    = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfCTe, "rem", "xNome"));
            cte.EnderecoRem  = GetEnderecoRem(xmlInfCTe);
            cte.MunicipioRem = GetNodeValue(xmlInfCTe, "rem/enderReme", "xMun");
            cte.CepRem       = GetNodeValue(xmlInfCTe, "rem/enderReme", "CEP");
            cte.CnpjCpfRem   = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "rem", "CPF")) ? Formatacoes.MascaraCpf(GetNodeValue(xmlInfCTe, "rem", "CPF"))
                : Formatacoes.MascaraCnpj(GetNodeValue(xmlInfCTe, "rem", "CNPJ"));
            cte.InscEstRem = GetNodeValue(xmlInfCTe, "rem", "IE");
            cte.UFRem      = GetNodeValue(xmlInfCTe, "rem/enderReme", "UF");
            cte.PaisRem    = GetNodeValue(xmlInfCTe, "rem/enderReme", "xPais");
            cte.FoneRem    = GetNodeValue(xmlInfCTe, "rem", "fone");

            //Destinatário
            cte.Destinatario  = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfCTe, "dest", "xNome"));
            cte.EnderecoDest  = GetEnderecoDest(xmlInfCTe);
            cte.MunicipioDest = GetNodeValue(xmlInfCTe, "dest/enderDest", "xMun");
            cte.CepDest       = GetNodeValue(xmlInfCTe, "dest/enderDest", "CEP");
            cte.CnpjCpfDest   = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "dest", "CPF")) ? Formatacoes.MascaraCpf(GetNodeValue(xmlInfCTe, "dest", "CPF"))
                : Formatacoes.MascaraCnpj(GetNodeValue(xmlInfCTe, "dest", "CNPJ"));
            cte.InscEstDest = GetNodeValue(xmlInfCTe, "dest", "IE");
            cte.UFDest      = GetNodeValue(xmlInfCTe, "dest/enderDest", "UF");
            cte.PaisDest    = GetNodeValue(xmlInfCTe, "dest/enderDest", "xPais");
            cte.FoneDest    = GetNodeValue(xmlInfCTe, "dest", "fone");

            //Expedidor
            cte.Expedidor     = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfCTe, "exped", "xNome"));
            cte.EnderecoExped = GetEnderecoExped(xmlInfCTe);
            cte.MunicipioExpd = GetNodeValue(xmlInfCTe, "exped/enderExped", "xMun");
            cte.CepExped      = GetNodeValue(xmlInfCTe, "exped/enderExped", "CEP");
            cte.CnpjCpfExped  = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "exped", "CPF")) ? Formatacoes.MascaraCpf(GetNodeValue(xmlInfCTe, "exped", "CPF"))
                : Formatacoes.MascaraCnpj(GetNodeValue(xmlInfCTe, "exped", "CNPJ"));
            cte.InscEstExped = GetNodeValue(xmlInfCTe, "exped", "IE");
            cte.UFExped      = GetNodeValue(xmlInfCTe, "exped/enderExped", "UF");
            cte.PaisExped    = GetNodeValue(xmlInfCTe, "exped/enderExped", "xPais");
            cte.FoneExped    = GetNodeValue(xmlInfCTe, "exped", "fone");

            //Recebedor
            cte.Recebedor      = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfCTe, "receb", "xNome"));
            cte.EnderecoReceb  = GetEnderecoReceb(xmlInfCTe);
            cte.MunicipioReceb = GetNodeValue(xmlInfCTe, "receb/enderReceb", "xMun");
            cte.CepReceb       = GetNodeValue(xmlInfCTe, "receb/enderReceb", "CEP");
            cte.CnpjCpfReceb   = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "receb", "CPF")) ? Formatacoes.MascaraCpf(GetNodeValue(xmlInfCTe, "receb", "CPF"))
                : Formatacoes.MascaraCnpj(GetNodeValue(xmlInfCTe, "receb", "CNPJ"));
            cte.InscEstReceb = GetNodeValue(xmlInfCTe, "receb", "IE");
            cte.UFReceb      = GetNodeValue(xmlInfCTe, "receb/enderReceb", "UF");
            cte.PaisReceb    = GetNodeValue(xmlInfCTe, "receb/enderReceb", "xPais");
            cte.FoneReceb    = GetNodeValue(xmlInfCTe, "receb", "fone");

            //Tomador

            var tipoTomador = GetNodeValue(xmlInfCTe, "ide/toma3", "toma");
            cte.TipoTomador = tipoTomador;
            //se tomador for remetente (0)
            if (tipoTomador == "0")
            {
                cte.Tomador       = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfCTe, "rem", "xNome"));
                cte.EnderecoToma  = GetEnderecoRem(xmlInfCTe);
                cte.MunicipioToma = GetNodeValue(xmlInfCTe, "rem/enderReme", "xMun");
                cte.CepToma       = GetNodeValue(xmlInfCTe, "rem/enderReme", "CEP");
                cte.CnpjCpfToma   = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "rem", "CPF")) ? Formatacoes.MascaraCpf(GetNodeValue(xmlInfCTe, "rem", "CPF"))
                    : Formatacoes.MascaraCnpj(GetNodeValue(xmlInfCTe, "rem", "CNPJ"));
                cte.InscEstToma = GetNodeValue(xmlInfCTe, "rem", "IE");
                cte.UFToma      = GetNodeValue(xmlInfCTe, "rem/enderReme", "UF");
                cte.PaisToma    = GetNodeValue(xmlInfCTe, "rem/enderReme", "xPais");
                cte.FoneToma    = GetNodeValue(xmlInfCTe, "rem", "fone");
            }
            //se tomador for expedidor (1)
            else if (tipoTomador == "1")
            {
                cte.Tomador       = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfCTe, "exped", "xNome"));
                cte.EnderecoToma  = GetEnderecoExped(xmlInfCTe);
                cte.MunicipioToma = GetNodeValue(xmlInfCTe, "exped/enderExped", "xMun");
                cte.CepToma       = GetNodeValue(xmlInfCTe, "exped/enderExped", "CEP");
                cte.CnpjCpfToma   = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "exped", "CPF")) ? Formatacoes.MascaraCpf(GetNodeValue(xmlInfCTe, "exped", "CPF"))
                    : Formatacoes.MascaraCnpj(GetNodeValue(xmlInfCTe, "exped", "CNPJ"));
                cte.InscEstToma = GetNodeValue(xmlInfCTe, "exped", "IE");
                cte.UFToma      = GetNodeValue(xmlInfCTe, "exped/enderExped", "UF");
                cte.PaisToma    = GetNodeValue(xmlInfCTe, "exped/enderExped", "xPais");
                cte.FoneToma    = GetNodeValue(xmlInfCTe, "exped", "fone");
            }
            //se tomador for recebedor (2)
            else if (tipoTomador == "2")
            {
                cte.Tomador       = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfCTe, "receb", "xNome"));
                cte.EnderecoToma  = GetEnderecoReceb(xmlInfCTe);
                cte.MunicipioToma = GetNodeValue(xmlInfCTe, "receb/enderReceb", "xMun");
                cte.CepToma       = GetNodeValue(xmlInfCTe, "receb/enderReceb", "CEP");
                cte.CnpjCpfToma   = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "receb", "CPF")) ? Formatacoes.MascaraCpf(GetNodeValue(xmlInfCTe, "receb", "CPF"))
                    : Formatacoes.MascaraCnpj(GetNodeValue(xmlInfCTe, "receb", "CNPJ"));
                cte.InscEstToma = GetNodeValue(xmlInfCTe, "receb", "IE");
                cte.UFToma      = GetNodeValue(xmlInfCTe, "receb/enderReceb", "UF");
                cte.PaisToma    = GetNodeValue(xmlInfCTe, "receb/enderReceb", "xPais");
                cte.FoneToma    = GetNodeValue(xmlInfCTe, "receb", "fone");
            }
            //se tomador for destinatário (3)
            else if (tipoTomador == "3")
            {
                cte.Tomador       = Formatacoes.RestauraStringDocFiscal(GetNodeValue(xmlInfCTe, "dest", "xNome"));
                cte.EnderecoToma  = GetEnderecoDest(xmlInfCTe);
                cte.MunicipioToma = GetNodeValue(xmlInfCTe, "dest/enderDest", "xMun");
                cte.CepToma       = GetNodeValue(xmlInfCTe, "dest/enderDest", "CEP");
                cte.CnpjCpfToma   = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "dest", "CPF")) ? Formatacoes.MascaraCpf(GetNodeValue(xmlInfCTe, "dest", "CPF"))
                    : Formatacoes.MascaraCnpj(GetNodeValue(xmlInfCTe, "dest", "CNPJ"));
                cte.InscEstToma = GetNodeValue(xmlInfCTe, "dest", "IE");
                cte.UFToma      = GetNodeValue(xmlInfCTe, "dest/enderDest", "UF");
                cte.PaisToma    = GetNodeValue(xmlInfCTe, "dest/enderDest", "xPais");
                cte.FoneToma    = GetNodeValue(xmlInfCTe, "dest", "fone");
            }

            // Produto Predominante
            cte.ProdutoPredominante = GetNodeValue(xmlInfCTe, "infCTeNorm/infCarga", "proPred");

            // Outras caracteristicas da carga
            if (GetNodeValue(xmlInfCTe, "infCTeNorm/infCarga", "xOutCat") != null)
            {
                cte.OutCarctCarga = GetNodeValue(xmlInfCTe, "infCTeNorm/infCarga", "xOutCat");
            }

            cte.ValorTotalMercadoria = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfCTe, "infCTeNorm/infCarga", "vCarga"), 2);

            // Produto Predominante
            cte.PesoBruto = GetNodeValue(xmlInfCTe, "infCTeNorm/infCarga", "proPred");

            //infCarga
            //var infCarga = xmlInfCTe["infCTeNorm"].GetElementsByTagName("infCarga");

            XmlNodeList xmlListInfCarga = xmlInfCTe["infCTeNorm"].GetElementsByTagName("infQ");
            if (xmlListInfCarga.Count > 0)
            {
                var listaInfCarga = new List <InfoCargaCte>();

                foreach (XmlElement xmlInfo in xmlListInfCarga)
                {
                    var infoCarga = new InfoCargaCte
                    {
                        Quantidade  = Glass.Conversoes.StrParaFloat(xmlInfo.GetElementsByTagName("qCarga")[0].InnerText),
                        TipoMedida  = xmlInfo.GetElementsByTagName("tpMed")[0].InnerText,
                        TipoUnidade = Glass.Conversoes.StrParaInt(xmlInfo.GetElementsByTagName("cUnid")[0].InnerText)
                    };

                    listaInfCarga.Add(infoCarga);
                }
                cte.ListaInfoCargaCte = listaInfCarga;
            }

            //Seguradoras
            var respSeg = GetNodeValue(xmlInfCTe, "infCTeNorm/seg", "respSeg");
            cte.ResponsavelSeguro = respSeg == "0" ? "Remetente" : respSeg == "1" ? "Expedidor" : respSeg == "2" ? "Recebedor"
                : respSeg == "3" ? "Destinatário" : respSeg == "4" ? "Emitente" : "Tomador";
            cte.NomeSeguradora = GetNodeValue(xmlInfCTe, "infCTeNorm/seg", "xSeg");
            cte.NumApolice     = GetNodeValue(xmlInfCTe, "infCTeNorm/seg", "nApol");
            cte.NumAverbacao   = GetNodeValue(xmlInfCTe, "infCTeNorm/seg", "nAver");

            //Componentes valor
            XmlNodeList xmlListaComponenteValor = xmlInfCTe["vPrest"].GetElementsByTagName("Comp");
            if (xmlListaComponenteValor.Count > 0)
            {
                var listaComponentes = new List <ComponenteValorCte>();

                foreach (XmlElement xmlComp in xmlListaComponenteValor)
                {
                    var componente = new ComponenteValorCte
                    {
                        NomeComponente  = xmlComp.GetElementsByTagName("xNome")[0].InnerText,
                        ValorComponente = Glass.Conversoes.StrParaDecimal(xmlComp.GetElementsByTagName("vComp")[0].InnerText)
                    };
                    listaComponentes.Add(componente);
                }
                cte.ListaComponentes = listaComponentes;
            }

            cte.ValorTotalServicoComponente = Glass.Conversoes.StrParaDecimal(GetNodeValue(xmlInfCTe, "vPrest", "vTPrest"));
            cte.ValorReceberComponente      = Glass.Conversoes.StrParaDecimal(GetNodeValue(xmlInfCTe, "vPrest", "vRec"));

            //Informações relativas ao imposto
            if (!string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "imp/ICMS", "ICMS00")))
            {
                cte.SubstituicaoTributaria = "00 - tributação normal ICMS";
                cte.BaseCalculo            = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfCTe, "imp/ICMS/ICMS00", "vBC"), 2);
                cte.AliquotaIcms           = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfCTe, "imp/ICMS/ICMS00", "pICMS"), 2);
                cte.ValorIcms = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfCTe, "imp/ICMS/ICMS00", "vICMS"), 2);
            }
            else if (!string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "imp/ICMS", "ICMS20")))
            {
                cte.SubstituicaoTributaria = "20 - tributação com BC reduzida do ICMS";
                cte.BaseCalculo            = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfCTe, "imp/ICMS/ICMS20", "vBC"), 2);
                cte.AliquotaIcms           = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfCTe, "imp/ICMS/ICMS20", "pICMS"), 2);
                cte.ValorIcms          = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfCTe, "imp/ICMS/ICMS20", "vICMS"), 2);
                cte.ReducaoBaseCalculo = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfCTe, "imp/ICMS/ICMS20", "pRedBC"), 2);
            }
            else if (!string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "imp/ICMS", "ICMS60")))
            {
                cte.SubstituicaoTributaria = "60 - ICMS cobrado anteriormente por substituição tributária";
                cte.IcmsST = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfCTe, "imp/ICMS/ICMS60", "vICMSSTRet"), 2);
            }
            else if (!string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "imp/ICMS", "ICMS90")))
            {
                cte.SubstituicaoTributaria = "90 - ICMS outros ";
                cte.BaseCalculo            = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfCTe, "imp/ICMS/ICMS90", "vBC"), 2);
                cte.AliquotaIcms           = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfCTe, "imp/ICMS/ICMS90", "pICMS"), 2);
                cte.ValorIcms = Formatacoes.FormataValorDecimal(GetNodeValue(xmlInfCTe, "imp/ICMS/ICMS90", "vICMS"), 2);
            }
            else if (!string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "imp/ICMS", "ICMS45")))
            {
                switch (GetNodeValue(xmlInfCTe, "imp/ICMS/ICMS45", "CST"))
                {
                case "40":
                    cte.SubstituicaoTributaria = "40 - ICMS isenção";
                    break;

                case "41":
                    cte.SubstituicaoTributaria = "41 - ICMS não tributada";
                    break;

                case "51":
                    cte.SubstituicaoTributaria = "51 - ICMS diferido";
                    break;
                }
            }

            if (xmlInfCTe["infCTeNorm"]["infDoc"] != null)
            {
                //Documentos Originários
                if (xmlInfCTe["infCTeNorm"]["infDoc"]["infNF"] != null)
                {
                    var xmlListaDocumentosOriginarios = xmlInfCTe["infCTeNorm"]["infDoc"].GetElementsByTagName("infNF");

                    if (xmlListaDocumentosOriginarios.Count > 0)
                    {
                        var cpfCnpjDocsOriginarios = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "rem", "CPF")) ?
                                                     Formatacoes.MascaraCpf(GetNodeValue(xmlInfCTe, "rem", "CPF")) : Formatacoes.MascaraCnpj(GetNodeValue(xmlInfCTe, "rem", "CNPJ"));

                        var listaDocsOriginarios = new List <NotaFiscalCte>();
                        int cont = 0;

                        foreach (XmlElement xmlDocOriginario in xmlListaDocumentosOriginarios)
                        {
                            var docsOriginarios = new NotaFiscalCte
                            {
                                TipoDoc       = "NF",
                                DocEmitenteNf = cpfCnpjDocsOriginarios,
                                Serie         = xmlDocOriginario.GetElementsByTagName("serie")[cont].InnerText,
                                NumeroDoc     = xmlDocOriginario.GetElementsByTagName("nDoc")[cont].InnerText
                            };

                            cont++;

                            listaDocsOriginarios.Add(docsOriginarios);
                        }
                        cte.ListaDocumentosOriginarios = listaDocsOriginarios;
                    }
                }

                //Documentos Originários
                else if (xmlInfCTe["infCTeNorm"]["infDoc"]["infNFe"] != null &&
                         xmlInfCTe["infCTeNorm"]["infDoc"]["infNFe"]["chave"] != null)
                {
                    var xmlListaDocumentosOriginariosNfe = xmlInfCTe["infCTeNorm"]["infDoc"].GetElementsByTagName("infNFe");
                    if (xmlListaDocumentosOriginariosNfe.Count > 0)
                    {
                        var cpfCnpjDocsOriginarios = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "rem", "CPF")) ?
                                                     Formatacoes.MascaraCpf(GetNodeValue(xmlInfCTe, "rem", "CPF")) : Formatacoes.MascaraCnpj(GetNodeValue(xmlInfCTe, "rem", "CNPJ"));

                        var listaDocsOriginarios = new List <NotaFiscalCte>();

                        foreach (XmlElement xmlDocOriginarioNfe in xmlListaDocumentosOriginariosNfe)
                        {
                            // var nf = Glass.Data.DAL.NotaFiscalDAO.Instance.GetByChaveAcesso(xmlDocOriginarioNfe.InnerText);

                            var docsOriginarios = new NotaFiscalCte
                            {
                                TipoDoc       = "NFe",
                                DocEmitenteNf = xmlDocOriginarioNfe.InnerText
                                                //DocEmitenteNf = nf.CnpjEmitente,
                                                //Serie = nf.Serie,
                                                //NumeroDoc = nf.NumeroNFe.ToString()
                            };

                            listaDocsOriginarios.Add(docsOriginarios);
                        }
                        cte.ListaDocumentosOriginarios = listaDocsOriginarios;
                    }
                }
            }
            //else
            //{
            //    XmlNodeList xmlListaDocumentosOriginarios = xmlInfCTe["rem"].GetElementsByTagName("infNFe");
            //    if (xmlListaDocumentosOriginarios.Count > 0)
            //    {
            //        var cpfCnpjDocsOriginarios = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "rem", "CPF")) ?
            //            Formatacoes.MascaraCpf(GetNodeValue(xmlInfCTe, "rem", "CPF")) : Formatacoes.MascaraCnpj(GetNodeValue(xmlInfCTe, "rem", "CNPJ"));

            //        var listaDocsOriginarios = new List<NotaFiscalCte>();

            //        foreach (XmlElement xmlDocOriginario in xmlListaDocumentosOriginarios)
            //        {
            //            var docsOriginarios = new NotaFiscalCte
            //            {
            //                TipoDoc = xmlDocOriginario.GetElementsByTagName("mod")[0].InnerText,
            //                DocEmitenteNf = cpfCnpjDocsOriginarios,
            //                SerieNumDoc = xmlDocOriginario.GetElementsByTagName("serie")[0].InnerText
            //            };
            //            listaDocsOriginarios.Add(docsOriginarios);
            //        }
            //        cte.ListaDocumentosOriginarios = listaDocsOriginarios;
            //    }
            //}


            //Informações específicas do modal rodoviário lotação

            /*cte.TipoVeiculo = GetNodeValue(xmlInfCTe, "infCTeNorm/infModal/rodo/veic", "tpVeic") == "0" ? "Tração" : "Reboque";
             * cte.Placa = GetNodeValue(xmlInfCTe, "infCTeNorm/infModal/rodo/veic", "placa");
             * cte.UFVeiculo = GetNodeValue(xmlInfCTe, "infCTeNorm/infModal/rodo/veic", "UF");*/

            var veiculosCte = DAL.CTe.VeiculoCteDAO.Instance.GetVeiculosCteByIdCte(_cte.IdCte);

            /* Chamado 44905. */
            if (veiculosCte != null)
            {
                var veiculosTipo         = new List <string>();
                var veiculosPlaca        = new List <string>();
                var veiculosUf           = new List <string>();
                var proprietariosRntrc   = new List <string>();
                var participantes        = DAL.CTe.ParticipanteCteDAO.Instance.GetParticipanteByIdCte(_cte.IdCte);
                var participanteEmitente = participantes.Where(f => f.TipoParticipante == ParticipanteCte.TipoParticipanteEnum.Emitente).First();
                var loja = DAL.LojaDAO.Instance.GetElement(participanteEmitente.IdLoja.Value);

                foreach (var veiculoCte in veiculosCte)
                {
                    var listaProprietarios = DAL.CTe.ProprietarioVeiculo_VeiculoDAO.Instance.GetList(veiculoCte.Placa, 0);
                    var proprietario       = new ProprietarioVeiculo();

                    foreach (var prop in listaProprietarios)
                    {
                        if (Formatacoes.LimpaCpfCnpj(DAL.CTe.ProprietarioVeiculoDAO.Instance.GetElement(prop.IdPropVeic).Cnpj) == Formatacoes.LimpaCpfCnpj(loja.Cnpj))
                        {
                            var rntrc = DAL.CTe.ProprietarioVeiculoDAO.Instance.ObtemValorCampo <string>("RNTRC", "IdPropVeic=" + prop.IdPropVeic);

                            if (!string.IsNullOrEmpty(rntrc))
                            {
                                proprietariosRntrc.Add(rntrc);
                            }

                            break;
                        }
                    }

                    var veiculo = DAL.VeiculoDAO.Instance.GetElement(veiculoCte.Placa);

                    veiculosTipo.Add(veiculo.TipoVeiculo == 0 ? "Tração" : "Reboque");
                    veiculosPlaca.Add(veiculoCte.Placa);
                    veiculosUf.Add(veiculo.UfLicenc);
                }

                cte.TipoVeiculo       = string.Join("\n", veiculosTipo);
                cte.Placa             = string.Join("\n", veiculosPlaca);
                cte.UFVeiculo         = string.Join("\n", veiculosUf);
                cte.RNTRCProprietario = string.Join("\n", proprietariosRntrc);
            }
            else
            {
                cte.TipoVeiculo       = GetNodeValue(xmlInfCTe, "infCTeNorm/infModal/rodo/veic", "tpVeic") == "0" ? "Tração" : "Reboque";
                cte.Placa             = GetNodeValue(xmlInfCTe, "infCTeNorm/infModal/rodo/veic", "placa");
                cte.UFVeiculo         = GetNodeValue(xmlInfCTe, "infCTeNorm/infModal/rodo/veic", "UF");
                cte.RNTRCProprietario = GetNodeValue(xmlInfCTe, "prop", "RNTRC");
            }

            cte.RespValePedCnpj = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "valePed", "CNPJPg")) ?
                                  Formatacoes.MascaraCnpj(GetNodeValue(xmlInfCTe, "valePed", "CNPJPg")) : "";
            cte.FornValePedagioCnpj = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "valePed", "CNPJForn")) ?
                                      Formatacoes.MascaraCnpj(GetNodeValue(xmlInfCTe, "valePed", "CNPJForn")) : "";
            cte.NumeroComprovante = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "valePed", "nCompra")) ? GetNodeValue(xmlInfCTe, "valePed", "nCompra") : "";

            cte.RNTRCRodo = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "infCTeNorm/infModal/rodo", "RNTRC")) ? GetNodeValue(xmlInfCTe, "infCTeNorm/infModal/rodo", "RNTRC") : "";
            cte.Lotacao   = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "infCTeNorm/infModal/rodo", "lota")) ? GetNodeValue(xmlInfCTe, "infCTeNorm/infModal/rodo", "lota") : "";
            cte.CIOT      = !string.IsNullOrEmpty(GetNodeValue(xmlInfCTe, "infCTeNorm/infModal/rodo", "CIOT")) ? GetNodeValue(xmlInfCTe, "infCTeNorm/infModal/rodo", "CIOT") : "";

            XmlNodeList xmlListaLacre = xmlInfCTe["infCTeNorm"].GetElementsByTagName("lacRodo");
            if (xmlListaLacre.Count > 0)
            {
                var listaNumLacre = new List <LacreCteRod>();

                foreach (XmlElement xmlLacre in xmlListaLacre)
                {
                    var lacre = new LacreCteRod
                    {
                        NumeroLacre = xmlLacre.GetElementsByTagName("nLacre")[0].InnerText
                    };
                    listaNumLacre.Add(lacre);
                }
                cte.ListaNumeroLacre = listaNumLacre;
            }

            #endregion

            return(cte);
        }