Ejemplo n.º 1
0
        public override string WriteXmlRps(NotaServico nota, bool identado = true, bool showDeclaration = true)
        {
            var xmlDoc = new XDocument(new XDeclaration("1.0", "UTF-8", null));

            xmlDoc.Add(WriteRps(nota));
            return(xmlDoc.AsString(identado, showDeclaration));
        }
Ejemplo n.º 2
0
        public override string WriteXmlRps(NotaServico nota, bool identado = true, bool showDeclaration = true)
        {
            valoresTipo30 = new List <decimal>();

            var xmlDoc = new XDocument(new XDeclaration("1.0", "UTF-8", null));

            var sdt = new XElement("SDTRPS");

            xmlDoc.AddChild(sdt);

            var tipoTrib = 1;

            if (nota.RegimeEspecialTributacao == RegimeEspecialTributacao.SimplesNacional)
            {
                tipoTrib = 4;
            }

            switch (nota.TipoTributacao)
            {
            case TipoTributacao.Isenta:
                tipoTrib = 2;
                break;

            case TipoTributacao.Suspensa:
                tipoTrib = 3;
                break;

            case TipoTributacao.TributavelFixo:
                tipoTrib = 5;
                break;
            }

            sdt.AddChild(AdicionarTag(TipoCampo.Int, "", "Ano", 0, 0, Ocorrencia.Obrigatoria, nota.Competencia.Year));
            sdt.AddChild(AdicionarTag(TipoCampo.Int, "", "Mes", 0, 0, Ocorrencia.Obrigatoria, nota.Competencia.Month.ZeroFill(2)));
            sdt.AddChild(AdicionarTag(TipoCampo.Str, "", "CPFCNPJ", 0, 0, Ocorrencia.Obrigatoria, nota.Prestador.CpfCnpj.ZeroFill(14)));
            sdt.AddChild(AdicionarTag(TipoCampo.Str, "", "DTIni", 0, 0, Ocorrencia.Obrigatoria, nota.Competencia.ToString("01/MM/yyyy")));
            sdt.AddChild(AdicionarTag(TipoCampo.Str, "", "DTFin", 0, 0, Ocorrencia.Obrigatoria, DateTime.Parse(nota.Competencia.AddMonths(1).ToString("01/MM/yyyy")).AddDays(-1).ToString("dd/MM/yyyy")));
            sdt.AddChild(AdicionarTag(TipoCampo.Int, "", "TipoTrib", 0, 0, Ocorrencia.Obrigatoria, tipoTrib));
            sdt.AddChild(AdicionarTag(TipoCampo.Str, "", "DtAdeSN", 0, 0, Ocorrencia.Obrigatoria, nota.DataOptanteSimplesNacional == DateTime.MinValue || tipoTrib != 4 ? "" : nota.DataOptanteSimplesNacional.ToString("dd/MM/yyyy")));
            sdt.AddChild(AdicionarTag(TipoCampo.Str, "", "AlqIssSN_IP", 0, 0, Ocorrencia.Obrigatoria, tipoTrib != 4 ? "" :  nota.Servico.Valores.Aliquota.ToString("##0.00")));
            sdt.AddChild(AdicionarTag(TipoCampo.Str, "", "Versao", 0, 0, Ocorrencia.Obrigatoria, "2.00"));

            sdt.Add(WriteREG20(nota));

            if (
                nota.Servico.Valores.ValorCofins > 0 ||
                nota.Servico.Valores.ValorCsll > 0 ||
                nota.Servico.Valores.ValorInss > 0 ||
                nota.Servico.Valores.ValorIr > 0 ||
                nota.Servico.Valores.IssRetido == SituacaoTributaria.Retencao ||
                nota.Servico.Valores.ValorPis > 0
                )
            {
                sdt.Add(WriteREG30(nota));
            }

            sdt.Add(WriteREG90(nota));

            return(xmlDoc.AsString(identado, showDeclaration));
        }
Ejemplo n.º 3
0
        public override string GetXmlRps(NotaFiscal nota, bool identado = true, bool showDeclaration = true)
        {
            var xmlDoc = new XDocument(new XDeclaration("1.0", "UTF-8", null));

            xmlDoc.Add(GenerateRps(nota));
            return(xmlDoc.AsString(identado, showDeclaration));
        }
        /// <summary>
        /// Carrega a NFSe/RPS do XMLDocument.
        /// </summary>
        /// <param name="xml">XMLDocument da NFSe/RPS.</param>
        /// <returns>NotaServico carregada.</returns>
        public NotaServico Load(XDocument xml)
        {
            Guard.Against <ACBrException>(config?.Parent?.provider == null, "ERRO: Nenhuma cidade informada.");

            var nota = config?.Parent?.provider.LoadXml(xml);

            nota.XmlOriginal = xml.AsString();
            Add(nota);
            return(nota);
        }
Ejemplo n.º 5
0
        public override string GetXmlNFSe(NotaFiscal nota, bool identado = true, bool showDeclaration = true)
        {
            var xmlDoc   = new XDocument(new XDeclaration("1.0", "UTF-8", null));
            var compNfse = new XElement("CompNfse");

            compNfse.AddChild(GenerateNFSe(nota));
            compNfse.AddChild(GenerateNFSeCancelamento(nota));
            compNfse.AddChild(GenerateNFSeSubstituicao(nota));

            xmlDoc.AddChild(compNfse);
            return(xmlDoc.AsString(identado, showDeclaration));
        }
Ejemplo n.º 6
0
        public override string WriteXmlRps(NotaFiscal nota, bool identado, bool showDeclaration)
        {
            string tipoRps;

            switch (nota.IdentificacaoRps.Tipo)
            {
            case TipoRps.RPS:
                tipoRps = "RPS";
                break;

            case TipoRps.NFConjugada:
                tipoRps = "RPS-M";
                break;

            case TipoRps.Cupom:
                tipoRps = "RPS-C";
                break;

            default:
                tipoRps = "";
                break;
            }

            string tipoTributacao;

            switch (nota.TipoTributacao)
            {
            case TipoTributacao.Tributavel:
                tipoTributacao = "T";
                break;

            case TipoTributacao.ForaMun:
                tipoTributacao = "F";
                break;

            case TipoTributacao.Isenta:
                tipoTributacao = "A";
                break;

            case TipoTributacao.ForaMunIsento:
                tipoTributacao = "B";
                break;

            case TipoTributacao.Imune:
                tipoTributacao = "M";
                break;

            case TipoTributacao.ForaMunImune:
                tipoTributacao = "N";
                break;

            case TipoTributacao.Suspensa:
                tipoTributacao = "X";
                break;

            case TipoTributacao.ForaMunSuspensa:
                tipoTributacao = "V";
                break;

            case TipoTributacao.ExpServicos:
                tipoTributacao = "P";
                break;

            default:
                tipoTributacao = "";
                break;
            }

            var situacao = nota.Situacao == SituacaoNFSeRps.Normal ? "N" : "C";

            var issRetido = nota.Servico.Valores.IssRetido == SituacaoTributaria.Retencao ? "true" : "false";

            // RPS
            XNamespace ns = "";

            var xmlDoc = new XDocument(new XDeclaration("1.0", "UTF-8", null));
            var rps    = new XElement(ns + "RPS");

            xmlDoc.Add(rps);

            var hashRps = GetHashRps(nota);

            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "Assinatura", 1, 2000, Ocorrencia.Obrigatoria, hashRps));

            var chaveRPS = new XElement("ChaveRPS");

            rps.Add(chaveRPS);
            chaveRPS.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "InscricaoPrestador", 1, 15, Ocorrencia.Obrigatoria, nota.Prestador.InscricaoMunicipal));
            chaveRPS.AddChild(AdicionarTag(TipoCampo.Int, "", "SerieRPS", 1, 5, Ocorrencia.Obrigatoria, nota.IdentificacaoRps.Serie));
            chaveRPS.AddChild(AdicionarTag(TipoCampo.Int, "", "NumeroRPS", 1, 15, Ocorrencia.Obrigatoria, nota.IdentificacaoRps.Numero));

            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "TipoRPS", 1, 1, Ocorrencia.Obrigatoria, tipoRps));
            rps.AddChild(AdicionarTag(TipoCampo.Dat, "", "DataEmissao", 20, 20, Ocorrencia.Obrigatoria, nota.IdentificacaoRps.DataEmissao));
            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "StatusRPS", 1, 1, Ocorrencia.Obrigatoria, situacao));
            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "TributacaoRPS", 1, 1, Ocorrencia.Obrigatoria, tipoTributacao));

            rps.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorServicos", 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorServicos));
            rps.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorDeducoes", 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorDeducoes));
            rps.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorPIS", 1, 15, Ocorrencia.NaoObrigatoria, nota.Servico.Valores.ValorPis));
            rps.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorCOFINS", 1, 15, Ocorrencia.NaoObrigatoria, nota.Servico.Valores.ValorCofins));
            rps.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorINSS", 1, 15, Ocorrencia.NaoObrigatoria, nota.Servico.Valores.ValorInss));
            rps.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorIR", 1, 15, Ocorrencia.NaoObrigatoria, nota.Servico.Valores.ValorIr));
            rps.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorCSLL", 1, 15, Ocorrencia.NaoObrigatoria, nota.Servico.Valores.ValorCsll));

            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "CodigoServico", 1, 5, Ocorrencia.Obrigatoria, nota.Servico.ItemListaServico));
            rps.AddChild(AdicionarTag(TipoCampo.De4, "", "AliquotaServicos", 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.Aliquota / 100));  // Valor Percentual - Exemplos: 1% => 0.01   /   25,5% => 0.255   /   100% => 1
            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "ISSRetido", 1, 4, Ocorrencia.Obrigatoria, issRetido));

            var tomadorCpfCnpj = new XElement("CPFCNPJTomador");

            rps.Add(tomadorCpfCnpj);
            tomadorCpfCnpj.AddChild(AdicionarTagCNPJCPF("", "CPF", "CNPJ", nota.Tomador.CpfCnpj));

            rps.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "InscricaoMunicipalTomador", 1, 8, Ocorrencia.NaoObrigatoria, nota.Tomador.InscricaoMunicipal));
            rps.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "InscricaoEstadualTomador", 1, 19, Ocorrencia.NaoObrigatoria, nota.Tomador.InscricaoEstadual));
            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "RazaoSocialTomador", 1, 115, Ocorrencia.NaoObrigatoria, nota.Tomador.RazaoSocial));

            if (!nota.Tomador.Endereco.Logradouro.IsEmpty())
            {
                var endereco = new XElement("EnderecoTomador");
                rps.AddChild(endereco);
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "TipoLogradouro", 1, 3, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.TipoLogradouro));
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "Logradouro", 1, 125, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Logradouro));
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "NumeroEndereco", 1, 10, Ocorrencia.Obrigatoria, nota.Tomador.Endereco.Numero));
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "ComplementoEndereco", 1, 10, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Complemento));
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "Bairro", 1, 60, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Bairro));
                endereco.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "Cidade", 1, 7, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.CodigoMunicipio));
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "UF", 2, 2, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Uf));
                endereco.AddChild(AdicionarTag(TipoCampo.StrNumberFill, "", "CEP", 8, 8, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Cep));
            }

            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "EmailTomador", 1, 75, Ocorrencia.NaoObrigatoria, nota.Tomador.DadosContato.Email));

            if (!nota.Intermediario.CpfCnpj.IsEmpty())
            {
                var intermediarioCpfCnpj = new XElement("CPFCNPJIntermediario");
                rps.Add(intermediarioCpfCnpj);
                intermediarioCpfCnpj.AddChild(AdicionarTagCNPJCPF("", "CPF", "CNPJ", nota.Intermediario.CpfCnpj));

                rps.AddChild(AdicionarTag(TipoCampo.Str, "", "InscricaoMunicipalIntermediario", 1, 8, 0, nota.Intermediario.InscricaoMunicipal));
                rps.AddChild(AdicionarTag(TipoCampo.Str, "", "RazaoSocialIntermediario", 1, 115, 0, nota.Intermediario.RazaoSocial));

                var issRetidoIntermediario = nota.Intermediario.IssRetido == SituacaoTributaria.Retencao ? "true" : "false";
                rps.AddChild(AdicionarTag(TipoCampo.Str, "", "ISSRetidoIntermediario", 1, 4, Ocorrencia.Obrigatoria, issRetidoIntermediario));
                rps.AddChild(AdicionarTag(TipoCampo.Str, "", "EmailIntermediario", 1, 75, Ocorrencia.NaoObrigatoria, nota.Intermediario.EMail));
            }

            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "Discriminacao", 1, 2000, Ocorrencia.Obrigatoria, nota.Servico.Discriminacao));

            rps.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorCargaTributaria", 1, 15, Ocorrencia.NaoObrigatoria, nota.Servico.Valores.ValorCargaTributaria));
            rps.AddChild(AdicionarTag(TipoCampo.De4, "", "PercentualCargaTributaria", 1, 15, Ocorrencia.NaoObrigatoria, nota.Servico.Valores.AliquotaCargaTributaria / 100));
            rps.AddChild(AdicionarTag(TipoCampo.Str, "", "FonteCargaTributaria", 1, 10, Ocorrencia.NaoObrigatoria, nota.Servico.Valores.FonteCargaTributaria));

            rps.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "CodigoCEI", 1, 12, Ocorrencia.NaoObrigatoria, nota.ConstrucaoCivil.CodigoCEI));
            rps.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "MatriculaObra", 1, 12, Ocorrencia.NaoObrigatoria, nota.ConstrucaoCivil.Matricula));
            //rps.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "MunicipioPrestacao", 1, 7, Ocorrencia.MaiorQueZero, nota.Servico.CodigoMunicipio));
            rps.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "NumeroEncapsulamento", 1, 7, Ocorrencia.NaoObrigatoria, nota.Material.NumeroEncapsulamento));

            return(xmlDoc.AsString(identado, showDeclaration, Encoding.UTF8));
        }
Ejemplo n.º 7
0
        private string GetXmlRps(NotaFiscal nota, bool identado, bool showDeclaration, bool withPrefix)
        {
            var    incentivadorCultural = (nota.IncentivadorCultural == NFSeSimNao.Sim) ? 1 : 2;
            string tipoRps;

            switch (nota.IdentificacaoRps.Tipo)
            {
            case TipoRps.RPS:
                tipoRps = "1";
                break;

            case TipoRps.NFConjugada:
                tipoRps = "2";
                break;

            case TipoRps.Cupom:
                tipoRps = "3";
                break;

            default:
                tipoRps = "0";
                break;
            }

            string tipoRpsSubstituido;

            switch (nota.RpsSubstituido.Tipo)
            {
            case TipoRps.RPS:
                tipoRpsSubstituido = "1";
                break;

            case TipoRps.NFConjugada:
                tipoRpsSubstituido = "2";
                break;

            case TipoRps.Cupom:
                tipoRpsSubstituido = "3";
                break;

            default:
                tipoRpsSubstituido = "0";
                break;
            }

            int exigibilidade = 1;

            switch (nota.Servico.ExigibilidadeIss)
            {
            case ExigibilidadeIss.Exigivel:
                exigibilidade = 1;
                break;

            case ExigibilidadeIss.NaoIncidencia:
                exigibilidade = 2;
                break;

            case ExigibilidadeIss.Isencao:
                exigibilidade = 3;
                break;

            case ExigibilidadeIss.Exportacao:
                exigibilidade = 4;
                break;

            case ExigibilidadeIss.Imunidade:
                exigibilidade = 5;
                break;

            case ExigibilidadeIss.SuspensaDecisaoJudicial:
                exigibilidade = 6;
                break;

            case ExigibilidadeIss.SuspensaProcessoAdministrativo:
                exigibilidade = 7;
                break;
            }

            string regimeET, optanteSN;

            if (nota.RegimeEspecialTributacao == RegimeEspecialTributacao.SimplesNacional)
            {
                regimeET  = "6";
                optanteSN = "1";
            }
            else
            {
                var regime = (int)nota.RegimeEspecialTributacao;
                regimeET  = (regime == 0) ? string.Empty : regime.ToString();
                optanteSN = "2";
            }


            var situacao  = (nota.Situacao == SituacaoNFSeRps.Normal) ? "1" : "2";
            var issRetido = (nota.Servico.Valores.IssRetidoSimNao == NFSeSimNao.Sim) ? "1" : "2";

            var xmlDoc = new XDocument(new XDeclaration("1.0", "UTF-8", null));

            XNamespace ns = "";

            var rps = withPrefix ? new XElement(ns + "Rps") : new XElement("Rps");

            xmlDoc.Add(rps);

            var infoRps = new XElement(ns + "InfDeclaracaoPrestacaoServico", new XAttribute("Id", "RPS" + nota.IdentificacaoRps.Numero));

            rps.Add(infoRps);

            var rpsInfo = new XElement(ns + "Rps");

            infoRps.Add(rpsInfo);

            var ideRps = new XElement(ns + "IdentificacaoRps");

            rpsInfo.Add(ideRps);

            ideRps.AddChild(AdicionarTag(TipoCampo.Int, "", "Numero", ns, 1, 15, Ocorrencia.Obrigatoria, nota.IdentificacaoRps.Numero));
            ideRps.AddChild(AdicionarTag(TipoCampo.Str, "", "Serie", ns, 1, 5, Ocorrencia.Obrigatoria, nota.IdentificacaoRps.Serie));
            ideRps.AddChild(AdicionarTag(TipoCampo.Int, "", "Tipo", ns, 1, 1, Ocorrencia.Obrigatoria, tipoRps));

            rpsInfo.AddChild(AdicionarTag(TipoCampo.Dat, "", "DataEmissao", ns, 20, 20, Ocorrencia.Obrigatoria, nota.IdentificacaoRps.DataEmissao));
            rpsInfo.AddChild(AdicionarTag(TipoCampo.Int, "", "Status", ns, 1, 1, Ocorrencia.Obrigatoria, situacao));

            //infoRps.AddChild(AdicionarTag(TipoCampo.Int, "", "NaturezaOperacao", ns, 1, 1, Ocorrencia.Obrigatoria, naturezaOperacao));
            //infoRps.AddChild(AdicionarTag(TipoCampo.Int, "", "RegimeEspecialTributacao", ns, 1, 1, Ocorrencia.NaoObrigatoria, regimeEspecialTributacao));

            if (!string.IsNullOrWhiteSpace(nota.RpsSubstituido.NumeroRps))
            {
                var rpsSubstituido = new XElement(ns + "RpsSubstituido");

                rpsSubstituido.AddChild(AdicionarTag(TipoCampo.Int, "", "Numero", ns, 1, 15, Ocorrencia.Obrigatoria, nota.RpsSubstituido.NumeroRps));
                rpsSubstituido.AddChild(AdicionarTag(TipoCampo.Int, "", "Serie", ns, 1, 5, Ocorrencia.Obrigatoria, nota.RpsSubstituido.Serie));
                rpsSubstituido.AddChild(AdicionarTag(TipoCampo.Int, "", "Tipo", ns, 1, 1, Ocorrencia.Obrigatoria, tipoRpsSubstituido));

                infoRps.AddChild(rpsSubstituido);
            }

            infoRps.AddChild(AdicionarTag(TipoCampo.Dat, "", "Competencia", ns, 20, 20, Ocorrencia.Obrigatoria, nota.Competencia));

            var servico = new XElement(ns + "Servico");

            infoRps.AddChild(servico);

            var valores = new XElement(ns + "Valores");

            servico.AddChild(valores);

            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorServicos", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorServicos));

            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorDeducoes", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorDeducoes));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorPis", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorPis));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorCofins", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorCofins));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorInss", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorInss));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorIr", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorIr));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorCsll", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorCsll));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "OutrasRetencoes", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.OutrasRetencoes));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorIss", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorIss));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "Aliquota", ns, 1, 7, Ocorrencia.Obrigatoria, nota.Servico.Valores.Aliquota));  // Valor Percentual - Exemplos: 1% => 0.01   /   25,5% => 0.255   /   100% => 1
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "DescontoIncondicionado", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.DescontoIncondicionado));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "DescontoCondicionado", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.DescontoCondicionado));

            servico.AddChild(AdicionarTag(TipoCampo.Int, "", "IssRetido", ns, 1, 1, Ocorrencia.Obrigatoria, issRetido));
            //ResponsavelRetencao (Ausente)
            servico.AddChild(AdicionarTag(TipoCampo.Str, "", "ItemListaServico", ns, 1, 5, Ocorrencia.Obrigatoria, nota.Servico.ItemListaServico));
            servico.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "CodigoCnae", ns, 1, 7, Ocorrencia.NaoObrigatoria, nota.Servico.CodigoCnae));
            servico.AddChild(AdicionarTag(TipoCampo.Str, "", "CodigoTributacaoMunicipio", ns, 1, 20, Ocorrencia.NaoObrigatoria, nota.Servico.CodigoTributacaoMunicipio));
            servico.AddChild(AdicionarTag(TipoCampo.Str, "", "Discriminacao", ns, 1, 2000, Ocorrencia.Obrigatoria, nota.Servico.Discriminacao));
            servico.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "CodigoMunicipio", ns, 1, 7, Ocorrencia.Obrigatoria, nota.Servico.CodigoMunicipio == 9999999 ? 99999 : nota.Servico.CodigoMunicipio)); // Ginfes: No IBGE, o código de cidade do exterior é 9999999, mas no Ginfes é 99999
            servico.AddChild(AdicionarTag(TipoCampo.Str, "", "CodigoPais", ns, 4, 4, Ocorrencia.NaoObrigatoria, nota.Servico.CodigoPais));
            servico.AddChild(AdicionarTag(TipoCampo.Int, "", "ExigibilidadeISS", ns, 1, 1, Ocorrencia.Obrigatoria, exigibilidade));
            //MunicipioIncidencia (Ausente)
            //NumeroProcesso (Ausente)

            var prestador = new XElement(ns + "Prestador");

            infoRps.AddChild(prestador);

            var cpfcnpj = new XElement(ns + "CpfCnpj");

            prestador.Add(cpfcnpj);
            cpfcnpj.AddChild(AdicionarTagCNPJCPF("", "Cpf", "Cnpj", nota.Prestador.CpfCnpj.ZeroFill(14), ns));
            prestador.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "InscricaoMunicipal", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Prestador.InscricaoMunicipal));

            var tomador = new XElement(ns + "Tomador");

            infoRps.AddChild(tomador);

            if (!nota.Tomador.CpfCnpj.IsEmpty() || !nota.Tomador.InscricaoMunicipal.IsEmpty())
            {
                var ideTomador = new XElement(ns + "IdentificacaoTomador");
                tomador.AddChild(ideTomador);

                if (!nota.Tomador.CpfCnpj.IsEmpty())
                {
                    var cpfCnpj = new XElement(ns + "CpfCnpj");
                    ideTomador.AddChild(cpfCnpj);
                    cpfCnpj.AddChild(AdicionarTagCNPJCPF("", "Cpf", "Cnpj", nota.Tomador.CpfCnpj, ns));
                }

                if (!string.IsNullOrWhiteSpace(nota.Tomador.InscricaoMunicipal))
                {
                    ideTomador.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "InscricaoMunicipal", ns, 1, 15, Ocorrencia.NaoObrigatoria, nota.Tomador.InscricaoMunicipal));
                }
            }

            tomador.AddChild(AdicionarTag(TipoCampo.Str, "", "RazaoSocial", ns, 1, 115, Ocorrencia.NaoObrigatoria, nota.Tomador.RazaoSocial));
            if (!nota.Tomador.Endereco.Logradouro.IsEmpty())
            {
                var endereco = new XElement(ns + "Endereco");
                tomador.AddChild(endereco);

                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "Endereco", ns, 1, 125, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Logradouro));
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "Numero", ns, 1, 10, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Numero.IsEmpty() ? "SN" : nota.Tomador.Endereco.Numero));
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "Complemento", ns, 1, 10, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Complemento));
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "Bairro", ns, 1, 60, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Bairro));
                endereco.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "CodigoMunicipio", ns, 1, 7, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.CodigoMunicipio == 9999999 ? 99999 : nota.Tomador.Endereco.CodigoMunicipio)); // Ginfes: No IBGE, o código de cidade do exterior é 9999999, mas no Ginfes é 99999
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "Uf", ns, 2, 2, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Uf));
                endereco.AddChild(AdicionarTag(TipoCampo.StrNumberFill, "", "Cep", ns, 8, 8, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Cep));
            }

            if (!nota.Tomador.DadosContato.Telefone.IsEmpty() || !nota.Tomador.DadosContato.Email.IsEmpty())
            {
                var contato = new XElement(ns + "Contato");
                tomador.AddChild(contato);

                contato.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "Telefone", ns, 1, 11, Ocorrencia.NaoObrigatoria, nota.Tomador.DadosContato.DDD + nota.Tomador.DadosContato.Telefone));
                contato.AddChild(AdicionarTag(TipoCampo.Str, "", "Email", ns, 1, 80, Ocorrencia.NaoObrigatoria, nota.Tomador.DadosContato.Email));
            }

            if (!nota.Intermediario.RazaoSocial.IsEmpty())
            {
                var intServico = new XElement(ns + "IntermediarioServico");
                infoRps.AddChild(intServico);

                intServico.AddChild(AdicionarTag(TipoCampo.Str, "", "RazaoSocial", ns, 1, 115, 0, nota.Intermediario.RazaoSocial));

                var intServicoCpfCnpj = new XElement(ns + "CpfCnpj");
                intServico.AddChild(intServicoCpfCnpj);

                intServicoCpfCnpj.AddChild(AdicionarTagCNPJCPF("", "Cpf", "Cnpj", nota.Intermediario.CpfCnpj, ns));

                intServico.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "InscricaoMunicipal", ns, 1, 15, 0, nota.Intermediario.InscricaoMunicipal));
            }

            if (!nota.ConstrucaoCivil.CodigoObra.IsEmpty())
            {
                var conCivil = new XElement(ns + "ConstrucaoCivil");
                infoRps.AddChild(conCivil);

                conCivil.AddChild(AdicionarTag(TipoCampo.Str, "", "CodigoObra", ns, 1, 15, Ocorrencia.Obrigatoria, nota.ConstrucaoCivil.CodigoObra));
                conCivil.AddChild(AdicionarTag(TipoCampo.Str, "", "Art", ns, 1, 15, Ocorrencia.Obrigatoria, nota.ConstrucaoCivil.ArtObra));
            }

            return(xmlDoc.AsString(identado, showDeclaration, Encoding.UTF8));
        }
Ejemplo n.º 8
0
        public override string GetXmlRps(NotaFiscal nota, bool identado = true, bool showDeclaration = true)
        {
            var xmlDoc  = new XDocument(new XDeclaration("1.0", "UTF-8", null));
            var rootRps = new XElement("Rps");

            xmlDoc.Add(rootRps);

            var infServico = new XElement("InfDeclaracaoPrestacaoServico", new XAttribute("Id", $"{nota.IdentificacaoRps.Numero.OnlyNumbers()}"));

            rootRps.Add(infServico);

            var rps = new XElement("Rps");

            infServico.Add(rps);

            var indRps = new XElement("IdentificacaoRps");

            rps.Add(indRps);

            indRps.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "Numero", 1, 15, Ocorrencia.Obrigatoria, nota.IdentificacaoRps.Numero));
            indRps.AddChild(AdicionarTag(TipoCampo.Str, "", "Serie", 1, 5, Ocorrencia.Obrigatoria, nota.IdentificacaoRps.Serie));
            indRps.AddChild(AdicionarTag(TipoCampo.Int, "", "Tipo", 1, 1, Ocorrencia.Obrigatoria, (int)nota.IdentificacaoRps.Tipo++));

            rps.AddChild(AdicionarTag(TipoCampo.Dat, "", "DataEmissao", 10, 10, Ocorrencia.Obrigatoria, nota.IdentificacaoRps.DataEmissao));
            rps.AddChild(AdicionarTag(TipoCampo.Int, "", "Status", 1, 1, Ocorrencia.Obrigatoria, (int)nota.Situacao++));

            infServico.AddChild(AdicionarTag(TipoCampo.Dat, "", "Competencia", 10, 10, Ocorrencia.Obrigatoria, nota.Competencia));

            var servico = GenerateServicosValoresRps(nota);

            infServico.Add(servico);

            var prestador = GeneratePrestadorRps(nota);

            infServico.Add(prestador);

            if (!nota.Tomador.CpfCnpj.IsEmpty())
            {
                var tomador = GenerateTomadorRps(nota);
                infServico.Add(tomador);
            }

            if (!nota.Intermediario.CpfCnpj.IsEmpty())
            {
                var intermediario = GenerateIntermediarioRps(nota);
                infServico.Add(intermediario);
            }

            if (!nota.ConstrucaoCivil.ArtObra.IsEmpty())
            {
                var construcao = GenerateConstrucaoCivilRps(nota);
                infServico.Add(construcao);
            }

            if (nota.RegimeEspecialTributacao != RegimeEspecialTributacao.Nenhum)
            {
                infServico.AddChild(AdicionarTag(TipoCampo.Int, "", "RegimeEspecialTributacao", 1, 1, Ocorrencia.NaoObrigatoria,
                                                 (int)nota.RegimeEspecialTributacao));
            }

            infServico.AddChild(AdicionarTag(TipoCampo.Int, "", "OptanteSimplesNacional", 1, 1, Ocorrencia.Obrigatoria,
                                             nota.RegimeEspecialTributacao == RegimeEspecialTributacao.SimplesNacional ? 1 : 2));
            infServico.AddChild(AdicionarTag(TipoCampo.Int, "", "IncentivoFiscal", 1, 1, Ocorrencia.Obrigatoria,
                                             nota.IncentivadorCultural == NFSeSimNao.Sim ? 1 : 2));

            return(xmlDoc.AsString(identado, showDeclaration));
        }
Ejemplo n.º 9
0
        public bool ConvertToTUGVehicles(string strVehicleTemplateFile,
                                         string strSignatureFile,
                                         string strAxleTemplateFile,
                                         string strVectoXsd,
                                         bool bEnsureSignatureIsPresent,
                                         RoadmapGroup group,
                                         Roadmap map,
                                         DatabaseContext dbx,
                                         string strFailedWinsLogFile,
                                         string strPatchListFile)
        {
            int nCount = 0;

            try
            {
                Log.Debug("=>ConvertToTUGVehicles");
                XNamespace ns = Reco3Common.Reco3_Defines.DeclarationNamespace;
                XElement   signatureTemplate = XElement.Load(strSignatureFile);
                XElement   signatureNode     = signatureTemplate.Descendants(ns + "Signature").FirstOrDefault();

                XElement axleTemplate     = XElement.Load(strAxleTemplateFile);
                XElement axleTemplateNode = axleTemplate.Descendants(ns + "Axle").FirstOrDefault();


                XElement vehicleTemplate = XElement.Load(strVehicleTemplateFile);

                /*
                 * Roadmap previousmap = group.Roadmaps
                 *                          .OrderByDescending(x => x.CurrentYear)
                 *                          .Where(x => x.CurrentYear < map.CurrentYear)
                 *                          .First();
                 */

                Log.Debug("=>ConvertToTUGVehicles.Initialize");
                if (true == Converter.Initialize(ns, signatureNode, axleTemplateNode, DBContext, bEnsureSignatureIsPresent, map.CurrentYear))
                {
                    using (XmlReader schemaReader = XmlReader.Create(strVectoXsd))
                    {
                        // Prepare schemaset
                        XmlSchemaSet schemaSet = new XmlSchemaSet();
                        schemaSet.Add(XmlSchema.Read(schemaReader,
                                                     new ValidationEventHandler(
                                                         delegate(Object sender, ValidationEventArgs e) { }
                                                         )));

                        DateTime dtStart = DateTime.Now;

                        // Protect the roadmap for the time we process it, will change the status afterwards but the protection remains.
                        map.ImprovedVehicleCount         = 0;
                        map.ConvertToVehicleInput_Status = Reco3_Enums.ConvertToVehicleInputStatus.Processing;
                        map.Validation_Status            = Reco3_Enums.ValidationStatus.ValidatedWithSuccess;
                        map.Protected = true;
                        dbx.SaveChanges();


                        Log.Debug("=>ConvertToTUGVehicles.Initialized. B4 vehicle-iteration");
                        List <Scania.Baseline.FailedPds.vehiclesVehicle> vehicleList = new List <Scania.Baseline.FailedPds.vehiclesVehicle>();
                        List <vehiclesVehicle> vehicles      = Vehicles.vehicle.ToList();
                        List <Vehicle>         readyVehicles = new List <Vehicle>();

                        // If we have a filtered VIN-list, then filter out the ones not listed
                        List <string> strlVinList = GetVINList(strPatchListFile);
                        if (strlVinList != null)
                        {
                            DateTime dtb4Filter = DateTime.Now;
                            var      hset       = new HashSet <string>(strlVinList);
                            vehicles = vehicles.Where(elem => hset.Contains(elem.VIN)).ToList();
                            DateTime dtafterFilter = DateTime.Now;

                            TimeSpan span = dtafterFilter.Subtract(dtb4Filter);
                        }


                        foreach (vehiclesVehicle vehicle in vehicles)
                        {
                            // Thread.Sleep(10);

                            nCount++;
                            Log.Debug("=>ConvertToTUGVehicles.Initialized. B4 conversion: " + nCount + " VIN: " + vehicle.VIN);
                            // 1: Make a copy of the template
                            XElement currentVehicle = new XElement(vehicleTemplate);

                            Console.WriteLine("=>ConvertToTUGVehicles.Initialized. B4 conversion: " + nCount + " VIN: " + vehicle.VIN);

                            // 2: Construct the vehicle.xml
                            bool bContainsImprovements = false;
                            if (true == Converter.Convert2TUGVehicle(ref currentVehicle, vehicle, ref bContainsImprovements))
                            {
                                // 3: Validate against the schema from TUG
                                Log.Debug("=>ConvertToTUGVehicles.Initialized. B4 validating against schema.");
                                bool      errors = false;
                                XDocument doc    = new XDocument(currentVehicle);
                                doc.Validate(schemaSet, (o, e) =>
                                {
                                    Log.Information("Schemafailure, vehicle: " + vehicle.VIN + ". " + e.Message);
                                    errors = true;
                                }, true);
                                if (errors == true)
                                {
                                    Log.Debug("=>ConvertToTUGVehicles.Initialized. Schema validated, with failures...");

                                    /*
                                     * // Failures in the schema?
                                     * Scania.Baseline.FailedPds.vehiclesVehicle VIN = new Scania.Baseline.FailedPds.vehiclesVehicle();
                                     * VIN.VIN = vehicle.VIN;
                                     * VIN.SchemaFailures = new Scania.Baseline.FailedPds.vehiclesVehicleSchemaFailure[strErrorList.Count];
                                     * int n = 0;
                                     * foreach (string strError in strErrorList)
                                     * {
                                     *  vehiclesVehicleSchemaFailure failure = new vehiclesVehicleSchemaFailure();
                                     *  failure.description = strError;
                                     *  VIN.SchemaFailures[n++] = failure;
                                     * }
                                     *
                                     * vehicleList.Add(VIN);
                                     */
                                }
                                else
                                {
                                    try
                                    {
                                        Vehicle v = null;
                                        if (strlVinList != null)
                                        {
                                            v = dbx.Vehicle
                                                .Where(x => x.VIN == vehicle.VIN)
                                                .Where(x => x.GroupId == map.RoadmapId)
                                                .First();
                                        }
                                        if (v != null)
                                        {
                                            // Update the existing vehicle
                                            v.XML = doc.AsString();
                                            dbx.Entry(v).State = System.Data.Entity.EntityState.Modified;
                                            dbx.SaveChanges();

                                            // Update the report for this vehicle too
                                            var pRoadmapGroupId = new SqlParameter("@pRoadmapGroupId", group.RoadmapGroupId);
                                            var pRoadmapId      = new SqlParameter("@pRoadmapId", map.RoadmapId);
                                            var pVehicleId      = new SqlParameter("@pVehicleId", v.VehicleId);

                                            // I know!!!! This is fu##ing ugly but hey, if it offends you, stop reading, ok?
                                            dbx.Database.ExecuteSqlCommand("exec GenerateRoadmapReportForVehicleId @pRoadmapGroupId , @pRoadmapId , @pVehicleId", pRoadmapGroupId, pRoadmapId, pVehicleId);
                                        }
                                        else
                                        {
                                            dbx.AddVehicle(doc.AsString(), vehicle.VIN, Reco3_Enums.VehicleMode.VectoDeclaration, map.RoadmapId);
                                        }

                                        /*
                                         * Vehicle v = new Vehicle(doc.AsString(), map.RoadmapId);
                                         * v.Vehicle_Mode = Reco3_Enums.VehicleMode.VectoDeclaration;
                                         * v.GroupId = map.RoadmapId;
                                         * dbx.Vehicle.Add(v);
                                         */
                                        if (bContainsImprovements == true)
                                        {
                                            map.ImprovedVehicleCount += 1;
                                        }
                                        // dbx.SaveChanges();
                                        //TriggerEvent(v);
                                        GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
                                        GC.Collect();



/*
 *                                      // 2.1: If no improvements where added,...
 *                                      if (bContainsImprovements == false)
 *                                      {
 *
 *                                          // ...and we have the previous map,...
 *                                          if (previousmap != null)
 *                                          {
 *                                              Log.Debug("=>ConvertToTUGVehicles.Initialized. Schema validated, with success, no changes and we have a previous version, so making a copy.");
 *                                              // ...then fetch the previous version of the vehicle...
 *                                              Vehicle oldVehicle = dbx.Vehicle
 *                                                                      .Where(x => x.VIN == vehicle.VIN)
 *                                                                      .Where(x => x.GroupId == previousmap.RoadmapId)
 *                                                                      .First();
 *
 *                                              Vehicle clonedVehicle = oldVehicle.Clone();
 *                                              clonedVehicle.VehicleId = -1;
 *                                              clonedVehicle.GroupId = map.RoadmapId;
 *                                              dbx.Vehicle.Add(clonedVehicle);
 *                                              dbx.SaveChanges();
 *
 *                                              // ..and copy the vsum...
 *                                              List<VSumRecord> results = dbx.VSum.Where(x => x.VehicleId == oldVehicle.VehicleId).ToList();
 *                                              foreach (VSumRecord res in results)
 *                                              {
 *                                                  // ...clone the result, patch with the new vehicle-id and roadmap-id
 *                                                  VSumRecord resCopy = res.Clone();
 *                                                  resCopy.VehicleId = clonedVehicle.VehicleId;
 *                                                  resCopy.SimulationId = map.RoadmapId;
 *                                                  dbx.VSum.Add(resCopy);
 *                                              }
 *                                          }
 *                                          else
 *                                          {
 *                                              map.ImprovedVehicleCount += 1;
 *                                              Log.Debug("=>ConvertToTUGVehicles.Initialized. Schema validated, with success, no changes but we dont have a previous version, so making a fresh vehicle.");
 *                                              // ...and we dont have the previous map so just add it as a new one...
 *                                              //dbx.AddVehicle(doc.AsString(), vehicle.VIN, Reco3_Enums.VehicleMode.VectoDeclaration, map.RoadmapId);
 *                                          }
 *
 *                                      }
 *                                      else
 *                                      {
 *                                          map.ImprovedVehicleCount += 1;
 *                                          Log.Debug("=>ConvertToTUGVehicles.Initialized. Schema validated, with success, has changes so making a fresh vehicle.");
 *                                          // ...(has changes) so just add it as a new one...
 *                                          //dbx.AddVehicle(doc.AsString(), vehicle.VIN, Reco3_Enums.VehicleMode.VectoDeclaration, map.RoadmapId);
 *                                      }
 *                                      // ...and persist the changes...
 *                                      dbx.SaveChanges();
 *
 *                                      GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
 *                                      GC.Collect();
 */
                                    }
                                    catch (Exception ex)
                                    {
                                        Log.Fatal(ex, "ConvertToTUGVehicles.Exception while updating db:");
                                        Console.WriteLine("Exception while updating db: " + ex.Message);
                                    }
                                }
                                doc = null;
                            }
                            else
                            {
                                using (StreamWriter w = File.AppendText(strFailedWinsLogFile))
                                {
                                    w.WriteLine(vehicle.VIN);
                                }
                                Console.WriteLine("  ConvertToTUGVehicles==>Convert2TUGVehicle failed." + " (VIN: " + vehicle.VIN + ")");
                                Log.Debug("=>ConvertToTUGVehicles.Convert2TUGVehicle failed." + " (VIN: " + vehicle.VIN + ")");
                            }
                            currentVehicle = null;
                            GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
                            GC.Collect();
                        }

                        map.ConvertToVehicleInput_Status = Reco3_Enums.ConvertToVehicleInputStatus.ConvertedWithSuccess;
                        dbx.SaveChanges();
                        // Add the new failures,....
                        if (Converter.PDFailures.vehicle != null)
                        {
                            List <Scania.Baseline.FailedPds.vehiclesVehicle> tmpList = Converter.PDFailures.vehicle.ToList();
                            tmpList.AddRange(vehicleList);
                            Converter.PDFailures.vehicle = tmpList.ToArray();
                        }
                        else
                        {
                            Converter.PDFailures.vehicle = vehicleList.ToArray();
                        }

                        DateTime dtEnd = DateTime.Now;

                        Console.WriteLine("Conversion started: " + dtStart.ToShortDateString() + " " + dtStart.ToShortTimeString());
                        Console.WriteLine("Conversion done: " + dtEnd.ToShortDateString() + " " + dtEnd.ToShortTimeString());

                        Log.Debug("<=ConvertToTUGVehicles");
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "ConvertToTUGVehicles.OverallException");
                Console.WriteLine(ex);
            }
            Log.Debug("<=ConvertToTUGVehicles");
            return(false);
        }
Ejemplo n.º 10
0
        private string GetXmlRps(NotaFiscal nota, bool identado, bool showDeclaration, bool withPrefix)
        {
            var incentivadorCultural = nota.IncentivadorCultural == NFSeSimNao.Sim ? 1 : 2;

            string tipoRps;

            switch (nota.IdentificacaoRps.Tipo)
            {
            case TipoRps.RPS:
                tipoRps = "1";
                break;

            case TipoRps.NFConjugada:
                tipoRps = "2";
                break;

            case TipoRps.Cupom:
                tipoRps = "3";
                break;

            default:
                tipoRps = "0";
                break;
            }

            string tipoRpsSubstituido;

            switch (nota.RpsSubstituido.Tipo)
            {
            case TipoRps.RPS:
                tipoRpsSubstituido = "1";
                break;

            case TipoRps.NFConjugada:
                tipoRpsSubstituido = "2";
                break;

            case TipoRps.Cupom:
                tipoRpsSubstituido = "3";
                break;

            default:
                tipoRpsSubstituido = "0";
                break;
            }

            string naturezaOperacao;

            switch (nota.NaturezaOperacao)
            {
            case NaturezaOperacao.NT01:
                naturezaOperacao = "1";
                break;

            case NaturezaOperacao.NT02:
                naturezaOperacao = "2";
                break;

            case NaturezaOperacao.NT03:
                naturezaOperacao = "3";
                break;

            case NaturezaOperacao.NT04:
                naturezaOperacao = "4";
                break;

            case NaturezaOperacao.NT05:
                naturezaOperacao = "5";
                break;

            case NaturezaOperacao.NT06:
                naturezaOperacao = "6";
                break;

            default:
                naturezaOperacao = "0";
                break;
            }

            string regimeEspecialTributacao;

            string optanteSimplesNacional;

            if (nota.RegimeEspecialTributacao == RegimeEspecialTributacao.SimplesNacional)
            {
                regimeEspecialTributacao = "6";
                optanteSimplesNacional   = "1";
            }
            else
            {
                var regime = (int)nota.RegimeEspecialTributacao;
                regimeEspecialTributacao = regime == 0 ? string.Empty : regime.ToString();
                optanteSimplesNacional   = "2";
            }

            var situacao  = nota.Situacao == SituacaoNFSeRps.Normal ? "1" : "2";
            var issRetido = nota.Servico.Valores.IssRetido == SituacaoTributaria.Retencao ? 1 : 2;

            var xmlDoc = new XDocument(new XDeclaration("1.0", "UTF-8", null));

            XNamespace ns  = "http://www.ginfes.com.br/tipos";
            var        rps = withPrefix ? new XElement(ns + "Rps", new XAttribute(XNamespace.Xmlns + "tipos", ns)) :
                             new XElement("Rps", new XAttribute(XNamespace.Xmlns + "tipos", ns));

            xmlDoc.Add(rps);

            var infoRps = new XElement(ns + "InfRps", new XAttribute("Id", nota.IdentificacaoRps.Numero));

            rps.Add(infoRps);

            var ideRps = new XElement(ns + "IdentificacaoRps");

            infoRps.Add(ideRps);

            ideRps.AddChild(AdicionarTag(TipoCampo.Int, "", "Numero", ns, 1, 15, Ocorrencia.Obrigatoria, nota.IdentificacaoRps.Numero));
            ideRps.AddChild(AdicionarTag(TipoCampo.Int, "", "Serie", ns, 1, 5, Ocorrencia.Obrigatoria, nota.IdentificacaoRps.Serie));
            ideRps.AddChild(AdicionarTag(TipoCampo.Int, "", "Tipo", ns, 1, 1, Ocorrencia.Obrigatoria, tipoRps));

            infoRps.AddChild(AdicionarTag(TipoCampo.DatHor, "", "DataEmissao", ns, 20, 20, Ocorrencia.Obrigatoria, nota.IdentificacaoRps.DataEmissao));
            infoRps.AddChild(AdicionarTag(TipoCampo.Int, "", "NaturezaOperacao", ns, 1, 1, Ocorrencia.Obrigatoria, naturezaOperacao));
            infoRps.AddChild(AdicionarTag(TipoCampo.Int, "", "RegimeEspecialTributacao", ns, 1, 1, Ocorrencia.NaoObrigatoria, regimeEspecialTributacao));
            infoRps.AddChild(AdicionarTag(TipoCampo.Int, "", "OptanteSimplesNacional", ns, 1, 1, Ocorrencia.Obrigatoria, optanteSimplesNacional));
            infoRps.AddChild(AdicionarTag(TipoCampo.Int, "", "IncentivadorCultural", ns, 1, 1, Ocorrencia.Obrigatoria, incentivadorCultural));
            infoRps.AddChild(AdicionarTag(TipoCampo.Int, "", "Status", ns, 1, 1, Ocorrencia.Obrigatoria, situacao));

            if (!string.IsNullOrWhiteSpace(nota.RpsSubstituido.NumeroRps))
            {
                var rpsSubstituido = new XElement(ns + "RpsSubstituido");

                rpsSubstituido.AddChild(AdicionarTag(TipoCampo.Int, "", "Numero", ns, 1, 15, Ocorrencia.Obrigatoria, nota.RpsSubstituido.NumeroRps));
                rpsSubstituido.AddChild(AdicionarTag(TipoCampo.Int, "", "Serie", ns, 1, 5, Ocorrencia.Obrigatoria, nota.RpsSubstituido.Serie));
                rpsSubstituido.AddChild(AdicionarTag(TipoCampo.Int, "", "Tipo", ns, 1, 1, Ocorrencia.Obrigatoria, tipoRpsSubstituido));

                infoRps.AddChild(rpsSubstituido);
            }

            var servico = new XElement(ns + "Servico");

            infoRps.AddChild(servico);

            var valores = new XElement(ns + "Valores");

            servico.AddChild(valores);

            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorServicos", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorServicos));

            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorDeducoes", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorDeducoes));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorPis", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorPis));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorCofins", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorCofins));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorInss", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorInss));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorIr", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorIr));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorCsll", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorCsll));

            valores.AddChild(AdicionarTag(TipoCampo.Int, "", "IssRetido", ns, 1, 1, Ocorrencia.Obrigatoria, issRetido));

            Ocorrencia TipoOcorrenciaValorIss = Ocorrencia.MaiorQueZero;

            if (regimeEspecialTributacao == "2")
            {
                // Se o regime for "Estimativa", obrigatório informar as tags "ValorIss" e "Aliquota"
                TipoOcorrenciaValorIss = Ocorrencia.Obrigatoria;
            }

            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorIss", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorIss));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorIssRetido", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorIssRetido));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "OutrasRetencoes", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.OutrasRetencoes));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "BaseCalculo", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.BaseCalculo));
            // Valor Percentual - Exemplos: 1% => 0.01   /   25,5% => 0.255   /   100% => 1
            valores.AddChild(AdicionarTag(TipoCampo.De4, "", "Aliquota", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.Aliquota / 100));  // Valor Percentual - Exemplos: 1% => 0.01   /   25,5% => 0.255   /   100% => 1
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "ValorLiquidoNfse", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.ValorLiquidoNfse));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "DescontoIncondicionado", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.DescontoIncondicionado));
            valores.AddChild(AdicionarTag(TipoCampo.De2, "", "DescontoCondicionado", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Servico.Valores.DescontoCondicionado));

            servico.AddChild(AdicionarTag(TipoCampo.Str, "", "ItemListaServico", ns, 1, 5, Ocorrencia.Obrigatoria, nota.Servico.ItemListaServico));

            servico.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "CodigoCnae", ns, 1, 7, Ocorrencia.NaoObrigatoria, nota.Servico.CodigoCnae));

            servico.AddChild(AdicionarTag(TipoCampo.Str, "", "CodigoTributacaoMunicipio", ns, 1, 20, Ocorrencia.NaoObrigatoria, nota.Servico.CodigoTributacaoMunicipio));
            servico.AddChild(AdicionarTag(TipoCampo.Str, "", "Discriminacao", ns, 1, 2000, Ocorrencia.Obrigatoria, nota.Servico.Discriminacao));
            servico.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "CodigoMunicipio", ns, 1, 7, Ocorrencia.Obrigatoria, nota.Servico.CodigoMunicipio == 9999999 ? 99999 : nota.Servico.CodigoMunicipio)); // Ginfes: No IBGE, o código de cidade do exterior é 9999999, mas no Ginfes é 99999

            var prestador = new XElement(ns + "Prestador");

            infoRps.AddChild(prestador);

            prestador.AddChild(AdicionarTagCNPJCPF("", "Cpf", "Cnpj", nota.Prestador.CpfCnpj.ZeroFill(14), ns));
            prestador.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "InscricaoMunicipal", ns, 1, 15, Ocorrencia.Obrigatoria, nota.Prestador.InscricaoMunicipal));

            var tomador = new XElement(ns + "Tomador");

            infoRps.AddChild(tomador);

            if (!nota.Tomador.CpfCnpj.IsEmpty() || !nota.Tomador.InscricaoMunicipal.IsEmpty())
            {
                var ideTomador = new XElement(ns + "IdentificacaoTomador");
                tomador.AddChild(ideTomador);

                if (!nota.Tomador.CpfCnpj.IsEmpty())
                {
                    var cpfCnpj = new XElement(ns + "CpfCnpj");
                    ideTomador.AddChild(cpfCnpj);
                    cpfCnpj.AddChild(AdicionarTagCNPJCPF("", "Cpf", "Cnpj", nota.Tomador.CpfCnpj, ns));
                }

                if (!string.IsNullOrWhiteSpace(nota.Tomador.InscricaoMunicipal))
                {
                    ideTomador.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "InscricaoMunicipal", ns, 1, 15, Ocorrencia.NaoObrigatoria, nota.Tomador.InscricaoMunicipal));
                }
            }

            tomador.AddChild(AdicionarTag(TipoCampo.Str, "", "RazaoSocial", ns, 1, 115, Ocorrencia.NaoObrigatoria, nota.Tomador.RazaoSocial));
            if (!nota.Tomador.Endereco.Logradouro.IsEmpty())
            {
                var endereco = new XElement(ns + "Endereco");
                tomador.AddChild(endereco);

                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "Endereco", ns, 1, 125, Ocorrencia.Obrigatoria, nota.Tomador.Endereco.Logradouro));
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "Numero", ns, 1, 10, Ocorrencia.Obrigatoria, nota.Tomador.Endereco.Numero));
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "Complemento", ns, 1, 10, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Complemento));
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "Bairro", ns, 1, 60, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Bairro));
                endereco.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "CodigoMunicipio", ns, 1, 7, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.CodigoMunicipio == 9999999 ? 99999 : nota.Tomador.Endereco.CodigoMunicipio)); // Ginfes: No IBGE, o código de cidade do exterior é 9999999, mas no Ginfes é 99999
                endereco.AddChild(AdicionarTag(TipoCampo.Str, "", "Uf", ns, 2, 2, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Uf));
                endereco.AddChild(AdicionarTag(TipoCampo.StrNumberFill, "", "Cep", ns, 8, 8, Ocorrencia.NaoObrigatoria, nota.Tomador.Endereco.Cep));
            }

            if (!nota.Tomador.DadosContato.Telefone.IsEmpty() || !nota.Tomador.DadosContato.Email.IsEmpty())
            {
                var contato = new XElement(ns + "Contato");
                tomador.AddChild(contato);

                contato.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "Telefone", ns, 1, 11, Ocorrencia.NaoObrigatoria, nota.Tomador.DadosContato.DDD + nota.Tomador.DadosContato.Telefone));
                contato.AddChild(AdicionarTag(TipoCampo.Str, "", "Email", ns, 1, 80, Ocorrencia.NaoObrigatoria, nota.Tomador.DadosContato.Email));
            }

            if (!nota.Intermediario.RazaoSocial.IsEmpty())
            {
                var intServico = new XElement(ns + "IntermediarioServico");
                infoRps.AddChild(intServico);

                intServico.AddChild(AdicionarTag(TipoCampo.Str, "", "RazaoSocial", ns, 1, 115, 0, nota.Intermediario.RazaoSocial));

                var intServicoCpfCnpj = new XElement(ns + "CpfCnpj");
                intServico.AddChild(intServicoCpfCnpj);

                intServicoCpfCnpj.AddChild(AdicionarTagCNPJCPF("", "Cpf", "Cnpj", nota.Intermediario.CpfCnpj, ns));

                intServico.AddChild(AdicionarTag(TipoCampo.StrNumber, "", "InscricaoMunicipal", ns, 1, 15, 0, nota.Intermediario.InscricaoMunicipal));
            }

            if (!nota.ConstrucaoCivil.CodigoObra.IsEmpty())
            {
                var conCivil = new XElement(ns + "ConstrucaoCivil");
                infoRps.AddChild(conCivil);

                conCivil.AddChild(AdicionarTag(TipoCampo.Str, "", "CodigoObra", ns, 1, 15, Ocorrencia.Obrigatoria, nota.ConstrucaoCivil.CodigoObra));
                conCivil.AddChild(AdicionarTag(TipoCampo.Str, "", "Art", ns, 1, 15, Ocorrencia.Obrigatoria, nota.ConstrucaoCivil.ArtObra));
            }

            return(xmlDoc.AsString(identado, showDeclaration, Encoding.UTF8));
        }