Пример #1
0
        public gia(string mes, string ano, string cliente, Form1 form)
        {
            InitializeComponent();

            this.mes     = mes;
            this.ano     = ano;
            this.cliente = cliente;

            Classes.Auxiliar aux = new Classes.Auxiliar();
            cliente_cnpj = aux.GetCNPJByCliente(cliente);

            this.form = form;
        }
Пример #2
0
        public string Associar(string mes, string ano, string par_cliente, string conexao)
        {
            string  ret = "Gerando arquivo...";
            long    COD_ENQUADRAMENTO_1  = 0;
            long    COD_ENQUADRAMENTO_2  = 0;
            long    COD_ENQUADRAMENTO_5  = 0;
            long    COD_ENQUADRAMENTO_6  = 0;
            long    COD_ENQUADRAMENTO_9  = 0;
            long    COD_ENQUADRAMENTO_10 = 0;
            long    COD_ENQUADRAMENTO_11 = 0;
            decimal icms_total           = 0;
            decimal icms_gera            = 0;
            decimal valor_crd_out        = 0;

            string[]         lista_cfop = { "6109", "6110" };
            Classes.Auxiliar aux        = new Auxiliar();
            List <string>    lista_cnpj = aux.GetCNPJ(mes, ano, conexao);

            string[] lista_uf_1 = { "AM", "RR", "AP", "PA", "TO", "RO", "AC", "MA", "PI", "CE", "RN", "PE", "PB", "SE", "AL", "BA", "ES" };
            string[] lista_uf_2 = { "RJ", "MG", "PR", "RS", "SC" };

            CAT_207.DAL.Bloco0.Enquadramento class_enquadramento = new CAT_207.DAL.Bloco0.Enquadramento();
            CAT_207.DAL.Bloco0.Enquadramento.st_enquadramento st_enquadramento;
            EnqOp class_enq_op = new EnqOp();

            EnqOp.st_enq_op st_enq_op;

            using (var cnx = new EF.ef_dbContainer())
            {
                cnx.Database.Connection.ConnectionString = aux.GetEFCnxByCliente(par_cliente);

                string periodo = mes + ano;

                string CNAE = aux.GetCNAEByCliente(par_cliente);

                #region CALCULA IVA e PMC

                decimal saidas      = 0;
                decimal entradas    = 0;
                decimal pmc         = 0;
                decimal iva_mediana = 0;

                #region Listas

                string[] lista_cfop_s1 = { "5.101", "5.102", "5.103", "5.104", "5.105", "5.106",
                                           "5.109", "5.110", "5.115", "5.116", "5.117", "5.118","5.119",  "5.120", "5.122", "5.123", "5.917", "5.151", "5.152", "5.153", "5.155", "5.156", "5.251", "5.252",
                                           "5.253", "5.254", "5.255", "5.256", "5.257", "5.258","5.301",  "5.302", "5.303", "5.304", "5.305", "5.306", "5.307", "5.351", "5.352", "5.353", "5.354", "5.355",
                                           "5.356", "5.357", "5.359", "5.360", "5.401", "5.402","5.403",  "5.405", "5.651", "5.652", "5.653", "5.654", "5.655", "5.656", "5.408", "5.409", "5.658", "5.659",
                                           "5.501", "5.502", "5.928", "5.910", "5.124", "5.125","6.101",  "6.102", "6.103", "6.104", "6.105", "6.106", "6.107", "6.108", "6.109", "6.110", "6.115", "6.116",
                                           "6.117", "6.118", "6.119", "6.120", "6.122", "6.123","6.917",  "6.151", "6.152", "6.153", "6.155", "6.156", "6.251", "6.252", "6.253", "6.254", "6.255", "6.256",
                                           "6.257", "6.258", "6.301", "6.302", "6.303", "6.304","6.305",  "6.306", "6.307", "6.351", "6.352", "6.353", "6.354", "6.355", "6.356", "6.357", "6.359", "6.401",
                                           "6.402", "6.403", "6.404", "6.651", "6.652", "6.653","6.654",  "6.655", "6.656", "6.408", "6.409", "6.658", "6.659", "6.501", "6.502", "6.910", "6.124", "6.125",
                                           "7.101", "7.102", "7.105", "7.106", "7.127", "7.651","7.654",  "7.251", "7.301", "7.358" };

                string[] lista_cfop_s2 = { "1.201", "1.202", "1.203", "1.204", "1.205", "1.206", "1.207", "1.208", "1.209",
                                           "1.918", "1.410", "1.411", "1.660", "1.661", "1.662", "1.503", "1.504", "2.201","2.202",  "2.203", "2.204", "2.205", "2.206", "2.207", "2.208", "2.209", "2.918",
                                           "2.410", "2.411", "2.660", "2.661", "2.662", "2.503", "2.504", "3.201", "3.202","3.205",  "3.206", "3.207", "3.211" };

                string[] lista_cfop_e1 = { "1.101", "1.102", "1.116", "1.117", "1.118", "1.120", "1.121",
                                           "1.122", "1.126", "1.917", "1.151", "1.152", "1.153", "1.154","1.351",  "1.352", "1.353", "1.354", "1.355", "1.356", "1.360", "1.931", "1.932", "1.401", "1.403",
                                           "1.651", "1.652", "1.408", "1.409", "1.658", "1.659", "1.910","1.124",  "1.125", "2.101", "2.102", "2.116", "2.117", "2.118", "2.120", "2.121", "2.122", "2.126",
                                           "2.917", "2.151", "2.152", "2.153", "2.154", "2.351", "2.352","2.353",  "2.354", "2.355", "2.356", "2.931", "2.932", "2.401", "2.403", "2.651", "2.652", "2.408",
                                           "2.409", "2.658", "2.659", "2.910", "2.124", "2.125", "3.101","3.102",  "3.126", "3.127", "3.651", "3.652", "3.351", "3.352", "3.353", "3.354", "3.355", "3.356", "3.930" };

                string[] lista_cfop_e2 = { "1.251", "1.252", "1.253", "1.254", "1.255",
                                           "1.256", "1.257", "1.301", "1.302", "1.303","1.304",  "1.305", "1.306", "1.653", "2.251", "2.252", "2.253", "2.254", "2.255", "2.256", "2.257", "2.301", "2.302",
                                           "2.303", "2.304", "2.305", "2.306", "2.653","3.251",  "3.301", "3.653" };

                string[] lista_cfop_e3 = { "5.201", "5.202", "5.205", "5.206", "5.207", "5.208", "5.209",
                                           "5.210", "5.918", "5.410", "5.411", "5.660", "5.661", "6.201","6.202",  "6.205", "6.206", "6.207", "6.208", "6.209", "6.210", "6.918", "6.410", "6.411", "6.660",
                                           "6.661", "7.201", "7.202", "7.205", "7.206", "7.207", "7.210","7.211",  "7.930" };

                string[] lista_cfop_e4 = { "5.662", "6.662" };

                string[] lista_cfop_pmc1 = { "1.101", "1.102", "1.116", "1.117", "1.118", "1.120",
                                             "1.121", "1.122", "1.126", "1.917", "1.151", "1.152","1.153",  "1.154", "1.251", "1.252", "1.253", "1.254", "1.255", "1.256", "1.257", "1.301", "1.302", "1.303",
                                             "1.304", "1.305", "1.306", "1.351", "1.352", "1.353","1.354",  "1.355", "1.356", "1.360", "1.931", "1.932", "1.401", "1.403", "1.651", "1.652", "1.408", "1.409",
                                             "1.658", "1.659", "1.653", "1.910", "1.124", "1.125","2.101",  "2.102", "2.116", "2.117", "2.118", "2.120", "2.121", "2.122", "2.126", "2.917", "2.151", "2.152",
                                             "2.153", "2.154", "2.251", "2.252", "2.253", "2.254","2.255",  "2.256", "2.257", "2.301", "2.302", "2.303", "2.304", "2.305", "2.306", "2.351", "2.352", "2.353",
                                             "2.354", "2.355", "2.356", "2.931", "2.932", "2.401","2.403",  "2.651", "2.652", "2.408", "2.409", "2.658", "2.659", "2.653", "2.910", "2.124", "2.125", "3.101",
                                             "3.102", "3.126", "3.127", "3.651", "3.652", "3.251","3.301",  "3.351", "3.352", "3.353", "3.354", "3.355", "3.356", "3.653", "3.930" };

                string[] lista_cfop_pmc2 = { "5.201", "5.202", "5.205", "5.206", "5.207", "5.208", "5.209", "5.210", "5.918",
                                             "5.410", "5.411", "5.660", "5.661", "5.662", "6.201", "6.202", "6.205", "6.206","6.207",  "6.208", "6.209", "6.210", "6.918", "6.410", "6.411", "6.660", "6.661",
                                             "6.662", "7.201", "7.202", "7.205", "7.206", "7.207", "7.210", "7.211", "7.930" };

                #endregion

                decimal saida1   = Convert.ToDecimal(cnx.GIA.Where(p => p.PERIODO_ARQUIVO == periodo && lista_cfop_s1.Contains(p.CFOP)).Sum(p => p.VALOR_CONTABIL));
                decimal saida2   = Convert.ToDecimal(cnx.GIA.Where(p => p.PERIODO_ARQUIVO == periodo && lista_cfop_s2.Contains(p.CFOP)).Sum(p => p.VALOR_CONTABIL));
                decimal entrada1 = Convert.ToDecimal(cnx.GIA.Where(p => p.PERIODO_ARQUIVO == periodo && lista_cfop_e1.Contains(p.CFOP)).Sum(p => p.VALOR_CONTABIL));
                decimal entrada2 = Convert.ToDecimal(cnx.GIA.Where(p => p.PERIODO_ARQUIVO == periodo && lista_cfop_e2.Contains(p.CFOP)).Sum(p => p.BASE_CALCULO));
                decimal entrada3 = Convert.ToDecimal(cnx.GIA.Where(p => p.PERIODO_ARQUIVO == periodo && lista_cfop_e3.Contains(p.CFOP)).Sum(p => p.VALOR_CONTABIL));
                decimal entrada4 = Convert.ToDecimal(cnx.GIA.Where(p => p.PERIODO_ARQUIVO == periodo && lista_cfop_e4.Contains(p.CFOP)).Sum(p => p.BASE_CALCULO));
                decimal pmc1     = Convert.ToDecimal(cnx.GIA.Where(p => p.PERIODO_ARQUIVO == periodo && lista_cfop_pmc1.Contains(p.CFOP)).Sum(p => p.IMPOSTO));
                decimal pmc2     = Convert.ToDecimal(cnx.GIA.Where(p => p.PERIODO_ARQUIVO == periodo && lista_cfop_pmc2.Contains(p.CFOP)).Sum(p => p.IMPOSTO));

                try
                {
                    iva_mediana = aux.GetIVAMediana(CNAE, conexao);
                }
                catch (Exception erro)
                {
                    iva_mediana = 0;
                }


                saidas   = saida1 - saida2;
                entradas = (entrada1 + entrada2) - (entrada3 + entrada4);

                if (entradas == 0)
                {
                    pmc = 0;
                }
                else
                {
                    pmc = Math.Round(((pmc1 - pmc2) / entradas) * 100, 4);
                }

                decimal iva_proprio = (entradas == 0) ? 0 : Math.Round((saidas - entradas) / entradas, 4);

                decimal iva = 0;

                if (iva_mediana > iva_proprio)
                {
                    iva = iva_mediana;
                }
                else
                {
                    iva = iva_proprio;
                }

                #endregion



                var op_ger_cred = cnx.v_150_C100_C190_ENQ_OP.Where(p => p.PERIODO == periodo);


                if (class_enq_op.DeleteEnqOpByPeriodo(periodo, conexao))
                {
                    if (class_enquadramento.DeleteEnquadramentoByPeriodo(periodo, conexao))
                    {
                        try
                        {
                            foreach (var item in op_ger_cred)
                            {
                                if (item != null)
                                {
                                    st_enquadramento = new CAT_207.DAL.Bloco0.Enquadramento.st_enquadramento();
                                    st_enq_op        = new EnqOp.st_enq_op();

                                    decimal cred_est_icms = Math.Round((Convert.ToDecimal(item.VL_DOC) / (1 + Convert.ToDecimal(iva))) * Convert.ToDecimal(pmc) / 100, 2);

                                    if (item.ALIQ_ICMS != null && item.UF != null)
                                    {
                                        if (/*REGRA DE NEGOCIO 9*/)
                                        {
                                            if (COD_ENQUADRAMENTO_9 == 0)
                                            {
                                                st_enquadramento.COD_HIP_GER = 9;
                                                st_enquadramento.ANEXO       = "I";
                                                st_enquadramento.ARTIGO      = "84";
                                                st_enquadramento.OBS         = "Demonstrativo (Portaria CAT 63/2010) - Venda para Zona Franca de Manaus";
                                                st_enquadramento.PERIODO     = periodo;

                                                COD_ENQUADRAMENTO_9 = class_enquadramento.InsertEnquadramento(st_enquadramento, conexao);
                                            }

                                            if (COD_ENQUADRAMENTO_9 != 0)
                                            {
                                                st_enq_op.COD_ENQUADRAMENTO = COD_ENQUADRAMENTO_9;
                                                st_enq_op.NUM_DOC           = item.NUM_DOC;
                                                st_enq_op.SER        = item.SER;
                                                st_enq_op.PERIODO    = periodo;
                                                st_enq_op.COMPROV_OP = true;

                                                class_enq_op.InsertEnqOp(st_enq_op, conexao);
                                            }
                                        }
                                        else if (/*REGRA DE NEGOCIO 1 E 5*/)
                                        {
                                            icms_total = cred_est_icms + valor_crd_out;
                                            icms_gera  = icms_total - Convert.ToDecimal(item.VL_ICMS);

                                            if (icms_gera >= 0)
                                            {
                                                if (item.ALIQ_ICMS == 7)
                                                {
                                                    if (COD_ENQUADRAMENTO_1 == 0)
                                                    {
                                                        st_enquadramento.COD_HIP_GER = 1;
                                                        st_enquadramento.ARTIGO      = "52";
                                                        st_enquadramento.INCISO      = "II";
                                                        st_enquadramento.PERIODO     = periodo;

                                                        COD_ENQUADRAMENTO_1 = class_enquadramento.InsertEnquadramento(st_enquadramento, conexao);
                                                    }

                                                    if (COD_ENQUADRAMENTO_1 != 0)
                                                    {
                                                        st_enq_op.COD_ENQUADRAMENTO = COD_ENQUADRAMENTO_1;
                                                        st_enq_op.NUM_DOC           = item.NUM_DOC;
                                                        st_enq_op.SER        = item.SER;
                                                        st_enq_op.PERIODO    = periodo;
                                                        st_enq_op.COMPROV_OP = false;

                                                        class_enq_op.InsertEnqOp(st_enq_op, conexao);
                                                    }
                                                }
                                                else if (item.ALIQ_ICMS == 4)
                                                {
                                                    if (COD_ENQUADRAMENTO_5 == 0)
                                                    {
                                                        st_enquadramento.COD_HIP_GER = 5;
                                                        st_enquadramento.ARTIGO      = "52";
                                                        st_enquadramento.INCISO      = "IV";
                                                        st_enquadramento.PERIODO     = periodo;

                                                        COD_ENQUADRAMENTO_5 = class_enquadramento.InsertEnquadramento(st_enquadramento, conexao);
                                                    }

                                                    if (COD_ENQUADRAMENTO_5 != 0)
                                                    {
                                                        st_enq_op.COD_ENQUADRAMENTO = COD_ENQUADRAMENTO_5;
                                                        st_enq_op.NUM_DOC           = item.NUM_DOC;
                                                        st_enq_op.SER        = item.SER;
                                                        st_enq_op.PERIODO    = periodo;
                                                        st_enq_op.COMPROV_OP = false;

                                                        class_enq_op.InsertEnqOp(st_enq_op, conexao);
                                                    }
                                                }
                                            }
                                        }
                                        else if (/*REGRA DE NEGOCIO 2 E 5*/)
                                        {
                                            icms_total = cred_est_icms + valor_crd_out;
                                            icms_gera  = icms_total - Convert.ToDecimal(item.VL_ICMS);

                                            if (icms_gera >= 0)
                                            {
                                                if (item.ALIQ_ICMS == 12)
                                                {
                                                    if (COD_ENQUADRAMENTO_2 == 0)
                                                    {
                                                        st_enquadramento.COD_HIP_GER = 2;
                                                        st_enquadramento.ARTIGO      = "52";
                                                        st_enquadramento.INCISO      = "III";
                                                        st_enquadramento.PERIODO     = periodo;

                                                        COD_ENQUADRAMENTO_2 = class_enquadramento.InsertEnquadramento(st_enquadramento, conexao);
                                                    }

                                                    if (COD_ENQUADRAMENTO_2 != 0)
                                                    {
                                                        st_enq_op.COD_ENQUADRAMENTO = COD_ENQUADRAMENTO_2;
                                                        st_enq_op.NUM_DOC           = item.NUM_DOC;
                                                        st_enq_op.SER        = item.SER;
                                                        st_enq_op.PERIODO    = periodo;
                                                        st_enq_op.COMPROV_OP = false;

                                                        class_enq_op.InsertEnqOp(st_enq_op, conexao);
                                                    }
                                                }
                                                else if (item.ALIQ_ICMS == 4)
                                                {
                                                    if (COD_ENQUADRAMENTO_5 == 0)
                                                    {
                                                        st_enquadramento.COD_HIP_GER = 5;
                                                        st_enquadramento.ARTIGO      = "52";
                                                        st_enquadramento.INCISO      = "IV";
                                                        st_enquadramento.PERIODO     = periodo;

                                                        COD_ENQUADRAMENTO_5 = class_enquadramento.InsertEnquadramento(st_enquadramento, conexao);
                                                    }

                                                    if (COD_ENQUADRAMENTO_5 != 0)
                                                    {
                                                        st_enq_op.COD_ENQUADRAMENTO = COD_ENQUADRAMENTO_5;
                                                        st_enq_op.NUM_DOC           = item.NUM_DOC;
                                                        st_enq_op.SER        = item.SER;
                                                        st_enq_op.PERIODO    = periodo;
                                                        st_enq_op.COMPROV_OP = false;

                                                        class_enq_op.InsertEnqOp(st_enq_op, conexao);
                                                    }
                                                }
                                            }
                                        }
                                        else if (/*REGRA DE NEGOCIO 10*/)
                                        {
                                            if (COD_ENQUADRAMENTO_10 == 0)
                                            {
                                                st_enquadramento.COD_HIP_GER = 10;
                                                st_enquadramento.ITEM        = "II";
                                                st_enquadramento.ARTIGO      = "396";
                                                st_enquadramento.OBS         = "Demonstrativo (Portaria CAT 63/2010) - Operações com Componentes de equipamentos do Sistema Eletrônico de Processamento de dados";
                                                st_enquadramento.PERIODO     = periodo;

                                                COD_ENQUADRAMENTO_10 = class_enquadramento.InsertEnquadramento(st_enquadramento, conexao);
                                            }

                                            if (COD_ENQUADRAMENTO_10 != 0)
                                            {
                                                st_enq_op.COD_ENQUADRAMENTO = COD_ENQUADRAMENTO_10;
                                                st_enq_op.NUM_DOC           = item.NUM_DOC;
                                                st_enq_op.SER        = item.SER;
                                                st_enq_op.PERIODO    = periodo;
                                                st_enq_op.COMPROV_OP = false;

                                                class_enq_op.InsertEnqOp(st_enq_op, conexao);
                                            }
                                        }
                                        else if (/*REGRA DE NEGOCIO 11*/)
                                        {
                                            if (COD_ENQUADRAMENTO_11 == 0)
                                            {
                                                st_enquadramento.COD_HIP_GER = 11;
                                                st_enquadramento.ANEXO       = "I";
                                                st_enquadramento.ARTIGO      = "41";
                                                st_enquadramento.PERIODO     = periodo;

                                                COD_ENQUADRAMENTO_11 = class_enquadramento.InsertEnquadramento(st_enquadramento, conexao);
                                            }

                                            if (COD_ENQUADRAMENTO_11 != 0)
                                            {
                                                st_enq_op.COD_ENQUADRAMENTO = COD_ENQUADRAMENTO_11;
                                                st_enq_op.NUM_DOC           = item.NUM_DOC;
                                                st_enq_op.SER        = item.SER;
                                                st_enq_op.PERIODO    = periodo;
                                                st_enq_op.COMPROV_OP = false;

                                                class_enq_op.InsertEnqOp(st_enq_op, conexao);
                                            }
                                        }
                                        else if (/*REGRA DE NEGOCIO 6*/)
                                        {
                                            icms_total = cred_est_icms + valor_crd_out;
                                            icms_gera  = icms_total - Convert.ToDecimal(item.VL_ICMS);

                                            if (icms_gera >= 0)
                                            {
                                                if (COD_ENQUADRAMENTO_6 == 0)
                                                {
                                                    st_enquadramento.COD_HIP_GER = 6;
                                                    st_enquadramento.ANEXO       = "II";
                                                    st_enquadramento.ARTIGO      = "9";
                                                    st_enquadramento.PERIODO     = periodo;

                                                    COD_ENQUADRAMENTO_6 = class_enquadramento.InsertEnquadramento(st_enquadramento, conexao);
                                                }

                                                if (COD_ENQUADRAMENTO_6 != 0)
                                                {
                                                    st_enq_op.COD_ENQUADRAMENTO = COD_ENQUADRAMENTO_6;
                                                    st_enq_op.NUM_DOC           = item.NUM_DOC;
                                                    st_enq_op.SER        = item.SER;
                                                    st_enq_op.PERIODO    = periodo;
                                                    st_enq_op.COMPROV_OP = false;

                                                    class_enq_op.InsertEnqOp(st_enq_op, conexao);
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            Classes.Gerador gerador = new Classes.Gerador();
                            ret = gerador.GeraArquivo(mes, ano, par_cliente, conexao, iva, pmc, CNAE);
                        }
                        catch (Exception ex)
                        {
                            ret = "Erro na associação do arquivo";
                        }
                    }
                    else
                    {
                        ret = "Erro na associação do arquivo";
                    }
                }
                else
                {
                    ret = "Erro na associação do arquivo";
                }
            }

            return(ret);
        }
Пример #3
0
        private string Salvar()
        {
            trataComponentes();

            string ret = Validar();

            if (ret != "")
            {
                return(ret);
            }

            string periodo       = mes + ano;
            string periodo_gia   = "";
            bool   limpa_gia     = false;
            var    gia_select    = "SELECT ValorContábil AS VALOR_CONTABIL, BaseCálculo AS BASE_CALCULO, Imposto AS IMPOSTO, CFOP FROM tblDetalhesCFOPs";
            string query_periodo = "SELECT Ref1 FROM tblGIA";

            Classes.Auxiliar aux = new Classes.Auxiliar();

            try
            {
                foreach (var gia in ofd1.FileNames)
                {
                    using (OleDbConnection conection = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" + "data source=" + gia + ";Jet OLEDB:Database Password=kamisama2"))
                    {
                        using (DataTable dt = new DataTable())
                        {
                            using (OleDbDataAdapter da = new OleDbDataAdapter(gia_select, conection))
                            {
                                conection.Open();
                                da.Fill(dt);

                                da.SelectCommand.CommandText = query_periodo;
                                using (OleDbDataReader dr = da.SelectCommand.ExecuteReader())
                                {
                                    dr.Read();
                                    if (dr.HasRows)
                                    {
                                        periodo_gia = (dr["Ref1"] == DBNull.Value) ? "" : Convert.ToDateTime(dr["Ref1"]).ToString("MMyyyy");
                                    }

                                    using (var cnx = new EF.ef_dbContainer())
                                    {
                                        cnx.Database.Connection.ConnectionString = aux.GetEFCnxByCliente(cliente);

                                        EF.GIA par = new EF.GIA();

                                        for (int i = 0; i < dt.Rows.Count; i++)
                                        {
                                            par.VALOR_CONTABIL  = Convert.ToDecimal(dt.Rows[i]["VALOR_CONTABIL"]);
                                            par.BASE_CALCULO    = Convert.ToDecimal(dt.Rows[i]["BASE_CALCULO"]);
                                            par.IMPOSTO         = Convert.ToDecimal(dt.Rows[i]["IMPOSTO"]);
                                            par.CFOP            = dt.Rows[i]["CFOP"].ToString();
                                            par.PERIODO_GIA     = periodo_gia;
                                            par.PERIODO_ARQUIVO = periodo;

                                            if (!limpa_gia)
                                            {
                                                cnx.Database.ExecuteSqlCommand("DELETE FROM GIA WHERE PERIODO_ARQUIVO = @PERIODO", new SqlParameter("@PERIODO", periodo));
                                                //cnx.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('ITENS_DOC_C170', RESEED, 0)");
                                                limpa_gia = true;
                                            }

                                            cnx.Entry(par).State = System.Data.Entity.EntityState.Added;
                                            cnx.SaveChanges();
                                        }
                                    }
                                }

                                dt.Clear();
                                conection.Close();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ret = ex.Message;
            }

            trataComponentes();

            return(ret);
        }
Пример #4
0
 private void cbox_cliente_SelectedIndexChanged(object sender, EventArgs e)
 {
     Classes.Auxiliar aux = new Classes.Auxiliar();
     conexao.cnx.ConnectionString = aux.GetCnxByCliente(cbox_cliente.SelectedItem.ToString());
 }
Пример #5
0
        private string Salvar()
        {
            trataComponentes();

            string ret = Validar();

            if (ret != "")
            {
                return(ret);
            }

            string registro   = null;
            string periodo    = "";
            bool   limpa_0000 = false;
            bool   limpa_0005 = false;
            bool   limpa_0150 = false;
            bool   limpa_0200 = false;
            bool   limpa_C100 = false;
            bool   limpa_C113 = false;
            bool   limpa_C170 = false;
            bool   limpa_C190 = false;
            string num_doc    = "";

            StreamReader sr = new StreamReader(txt_sourcefolder.Text, Encoding.Default);

            Classes.Auxiliar aux = new Classes.Auxiliar();

            try
            {
                while ((registro = sr.ReadLine()) != null)
                {
                    //txt_obs.Text += registro + Environment.NewLine;

                    if (registro.Contains("|0000|"))
                    {
                        string[] campo = registro.Split('|');

                        if (campo[1] == "0000")
                        {
                            using (var cnx = new EF.ef_dbContainer())
                            {
                                cnx.Database.Connection.ConnectionString = aux.GetEFCnxByCliente(cliente);

                                EF.ENTIDADE_0000 par = new EF.ENTIDADE_0000();

                                #region Parametros

                                par.REG        = campo[1];
                                par.COD_VER    = campo[2];
                                par.COD_FIN    = campo[3];
                                par.DT_INI     = campo[4];
                                par.DT_FIN     = campo[5];
                                par.NOME       = campo[6];
                                par.CNPJ       = campo[7];
                                par.CPF        = campo[8];
                                par.UF         = campo[9];
                                par.IE         = campo[10];
                                par.COD_MUN    = campo[11];
                                par.IM         = campo[12];
                                par.SUFRAMA    = campo[13];
                                par.IND_PERFIL = campo[14];
                                par.IND_ATIV   = campo[15];
                                periodo        = campo[4].Remove(0, 2);
                                par.PERIODO    = periodo;

                                #endregion

                                if (!limpa_0000)
                                {
                                    cnx.Database.ExecuteSqlCommand("DELETE FROM ENTIDADE_0000 WHERE PERIODO = @PERIODO", new SqlParameter("@PERIODO", periodo));
                                    //cnx.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('ENTIDADE_0000', RESEED, 0)");
                                    limpa_0000 = true;
                                }

                                cnx.Entry(par).State = System.Data.Entity.EntityState.Added;
                                cnx.SaveChanges();
                            }
                        }
                    }
                    else if (registro.Contains("|0005|"))
                    {
                        string[] campo = registro.Split('|');

                        if (campo[1] == "0005")
                        {
                            using (var cnx = new EF.ef_dbContainer())
                            {
                                cnx.Database.Connection.ConnectionString = aux.GetEFCnxByCliente(cliente);

                                EF.ENTIDADE_COMPL_0005 par = new EF.ENTIDADE_COMPL_0005();

                                #region Parametros

                                par.REG = campo[1];

                                if (!string.IsNullOrEmpty(campo[2]))
                                {
                                    par.FANTASIA = campo[2];
                                }

                                if (!string.IsNullOrEmpty(campo[3]))
                                {
                                    par.CEP = campo[3];
                                }

                                if (!string.IsNullOrEmpty(campo[4]))
                                {
                                    par.END = campo[4];
                                }

                                if (!string.IsNullOrEmpty(campo[5]))
                                {
                                    par.NUM = campo[5];
                                }

                                if (!string.IsNullOrEmpty(campo[6]))
                                {
                                    par.COMPL = campo[6];
                                }

                                if (!string.IsNullOrEmpty(campo[7]))
                                {
                                    par.BAIRRO = campo[7];
                                }

                                if (!string.IsNullOrEmpty(campo[8]))
                                {
                                    par.FONE = campo[8];
                                }

                                if (!string.IsNullOrEmpty(campo[9]))
                                {
                                    par.FAX = campo[9];
                                }

                                if (!string.IsNullOrEmpty(campo[10]))
                                {
                                    par.EMAIL = campo[10];
                                }

                                par.PERIODO = periodo;

                                #endregion

                                if (!limpa_0005)
                                {
                                    cnx.Database.ExecuteSqlCommand("DELETE FROM ENTIDADE_COMPL_0005 WHERE PERIODO = @PERIODO", new SqlParameter("@PERIODO", periodo));
                                    //cnx.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('ENTIDADE_COMPL_0005', RESEED, 0)");
                                    limpa_0005 = true;
                                }

                                cnx.Entry(par).State = System.Data.Entity.EntityState.Added;
                                cnx.SaveChanges();
                            }
                        }
                    }
                    else if (registro.Contains("|0150|"))
                    {
                        string[] campo = registro.Split('|');

                        if (campo[1] == "0150")
                        {
                            using (var cnx = new EF.ef_dbContainer())
                            {
                                cnx.Database.Connection.ConnectionString = aux.GetEFCnxByCliente(cliente);

                                EF.PARTICIPANTE_0150 par = new EF.PARTICIPANTE_0150();

                                #region Parametros

                                par.REG = campo[1];

                                if (!string.IsNullOrEmpty(campo[2]))
                                {
                                    par.COD_PART = campo[2];
                                }

                                if (!string.IsNullOrEmpty(campo[3]))
                                {
                                    par.NOME = campo[3];
                                }

                                if (!string.IsNullOrEmpty(campo[4]))
                                {
                                    par.COD_PAIS = campo[4];
                                }

                                if (!string.IsNullOrEmpty(campo[5]))
                                {
                                    par.CNPJ = campo[5];
                                }

                                if (!string.IsNullOrEmpty(campo[6]))
                                {
                                    par.CPF = campo[6];
                                }

                                if (!string.IsNullOrEmpty(campo[7]))
                                {
                                    par.IE = campo[7];
                                }

                                if (!string.IsNullOrEmpty(campo[8]))
                                {
                                    par.COD_MUN = campo[8];
                                }

                                if (!string.IsNullOrEmpty(campo[9]))
                                {
                                    par.SUFRAMA = campo[9];
                                }

                                if (!string.IsNullOrEmpty(campo[10]))
                                {
                                    par.END = campo[10];
                                }

                                if (!string.IsNullOrEmpty(campo[11]))
                                {
                                    par.NUM = campo[11];
                                }

                                if (!string.IsNullOrEmpty(campo[12]))
                                {
                                    par.COMPL = campo[12];
                                }

                                if (!string.IsNullOrEmpty(campo[13]))
                                {
                                    par.BAIRRO = campo[13];
                                }

                                par.PERIODO = periodo;

                                #endregion

                                if (!limpa_0150)
                                {
                                    cnx.Database.ExecuteSqlCommand("DELETE FROM PARTICIPANTE_0150 WHERE PERIODO = @PERIODO", new SqlParameter("@PERIODO", periodo));
                                    //cnx.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('PARTICIPANTE_0150', RESEED, 0)");
                                    limpa_0150 = true;
                                }

                                cnx.Entry(par).State = System.Data.Entity.EntityState.Added;
                                cnx.SaveChanges();
                            }
                        }
                    }
                    else if (registro.Contains("|0200|"))
                    {
                        string[] campo = registro.Split('|');

                        if (campo[1] == "0200")
                        {
                            using (var cnx = new EF.ef_dbContainer())
                            {
                                cnx.Database.Connection.ConnectionString = aux.GetEFCnxByCliente(cliente);

                                EF.ITEM_0200 par = new EF.ITEM_0200();

                                #region Parametros

                                par.REG = campo[1];

                                if (!string.IsNullOrEmpty(campo[2]))
                                {
                                    par.COD_ITEM = campo[2];
                                }

                                if (!string.IsNullOrEmpty(campo[3]))
                                {
                                    par.DESCR_ITEM = campo[3];
                                }

                                if (!string.IsNullOrEmpty(campo[4]))
                                {
                                    par.COD_BARRA = campo[4];
                                }

                                if (!string.IsNullOrEmpty(campo[5]))
                                {
                                    par.COD_ANT_ITEM = campo[5];
                                }

                                if (!string.IsNullOrEmpty(campo[6]))
                                {
                                    par.UNID_INV = campo[6];
                                }

                                if (!string.IsNullOrEmpty(campo[7]))
                                {
                                    par.TIPO_ITEM = campo[7];
                                }

                                if (!string.IsNullOrEmpty(campo[8]))
                                {
                                    par.COD_NCM = campo[8];
                                }

                                if (!string.IsNullOrEmpty(campo[9]))
                                {
                                    par.EX_IPI = campo[9];
                                }

                                if (!string.IsNullOrEmpty(campo[10]))
                                {
                                    par.COD_GEN = campo[10];
                                }

                                if (!string.IsNullOrEmpty(campo[11]))
                                {
                                    par.COD_LST = campo[11];
                                }

                                if (!string.IsNullOrEmpty(campo[12]))
                                {
                                    par.ALIQ_ICMS = Convert.ToDecimal(campo[12]);
                                }

                                par.PERIODO = periodo;

                                #endregion

                                if (!limpa_0200)
                                {
                                    cnx.Database.ExecuteSqlCommand("DELETE FROM ITEM_0200 WHERE PERIODO = @PERIODO", new SqlParameter("@PERIODO", periodo));
                                    //cnx.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('ITEM_0200', RESEED, 0)");
                                    limpa_0200 = true;
                                }

                                cnx.Entry(par).State = System.Data.Entity.EntityState.Added;
                                cnx.SaveChanges();
                            }
                        }
                    }
                    else if (registro.Contains("|C100|"))
                    {
                        string[] campo = registro.Split('|');

                        if (campo[1] == "C100")
                        {
                            num_doc = campo[8];
                            using (var cnx = new EF.ef_dbContainer())
                            {
                                cnx.Database.Connection.ConnectionString = aux.GetEFCnxByCliente(cliente);

                                EF.DOC_FISCAL_C100 par = new EF.DOC_FISCAL_C100();

                                #region Parametros

                                par.REG = campo[1];

                                if (!string.IsNullOrEmpty(campo[2]))
                                {
                                    par.IND_OPER = campo[2];
                                }

                                if (!string.IsNullOrEmpty(campo[3]))
                                {
                                    par.IND_EMIT = campo[3];
                                }

                                if (!string.IsNullOrEmpty(campo[4]))
                                {
                                    par.COD_PART = campo[4];
                                }

                                if (!string.IsNullOrEmpty(campo[5]))
                                {
                                    par.COD_MOD = campo[5];
                                }

                                if (!string.IsNullOrEmpty(campo[6]))
                                {
                                    par.COD_SIT = campo[6];
                                }

                                if (!string.IsNullOrEmpty(campo[7]))
                                {
                                    par.SER = campo[7];
                                }

                                if (!string.IsNullOrEmpty(campo[8]))
                                {
                                    par.NUM_DOC = campo[8];
                                }

                                if (!string.IsNullOrEmpty(campo[9]))
                                {
                                    par.CHV_NFE = campo[9];
                                }

                                if (!string.IsNullOrEmpty(campo[10]))
                                {
                                    par.DT_DOC = campo[10];
                                }

                                if (!string.IsNullOrEmpty(campo[11]))
                                {
                                    par.DT_E_S = campo[11];
                                }

                                if (!string.IsNullOrEmpty(campo[12]))
                                {
                                    par.VL_DOC = Convert.ToDecimal(campo[12]);
                                }

                                if (!string.IsNullOrEmpty(campo[13]))
                                {
                                    par.IND_PGTO = campo[13];
                                }

                                if (!string.IsNullOrEmpty(campo[14]))
                                {
                                    par.VL_DESC = Convert.ToDecimal(campo[14]);
                                }

                                if (!string.IsNullOrEmpty(campo[15]))
                                {
                                    par.VL_ABAT_NT = Convert.ToDecimal(campo[15]);
                                }

                                if (!string.IsNullOrEmpty(campo[16]))
                                {
                                    par.VL_MERC = Convert.ToDecimal(campo[16]);
                                }

                                if (!string.IsNullOrEmpty(campo[17]))
                                {
                                    par.IND_FRT = campo[17];
                                }

                                if (!string.IsNullOrEmpty(campo[18]))
                                {
                                    par.VL_FRT = Convert.ToDecimal(campo[18]);
                                }

                                if (!string.IsNullOrEmpty(campo[19]))
                                {
                                    par.VL_SEG = Convert.ToDecimal(campo[19]);
                                }

                                if (!string.IsNullOrEmpty(campo[20]))
                                {
                                    par.VL_OUT_DA = Convert.ToDecimal(campo[20]);
                                }

                                if (!string.IsNullOrEmpty(campo[21]))
                                {
                                    par.VL_BC_ICMS = Convert.ToDecimal(campo[21]);
                                }

                                if (!string.IsNullOrEmpty(campo[22]))
                                {
                                    par.VL_ICMS = Convert.ToDecimal(campo[22]);
                                }

                                if (!string.IsNullOrEmpty(campo[23]))
                                {
                                    par.VL_BC_ICMS_ST = Convert.ToDecimal(campo[23]);
                                }

                                if (!string.IsNullOrEmpty(campo[24]))
                                {
                                    par.VL_ICMS_ST = Convert.ToDecimal(campo[24]);
                                }

                                if (!string.IsNullOrEmpty(campo[25]))
                                {
                                    par.VL_IPI = Convert.ToDecimal(campo[25]);
                                }

                                if (!string.IsNullOrEmpty(campo[26]))
                                {
                                    par.VL_PIS = Convert.ToDecimal(campo[26]);
                                }

                                if (!string.IsNullOrEmpty(campo[27]))
                                {
                                    par.VL_COFINS = Convert.ToDecimal(campo[27]);
                                }

                                if (!string.IsNullOrEmpty(campo[28]))
                                {
                                    par.VL_PIS_ST = Convert.ToDecimal(campo[28]);
                                }

                                if (!string.IsNullOrEmpty(campo[29]))
                                {
                                    par.VL_COFINS_ST = Convert.ToDecimal(campo[29]);
                                }

                                par.PERIODO = periodo;

                                #endregion

                                if (!limpa_C100)
                                {
                                    cnx.Database.ExecuteSqlCommand("DELETE FROM DOC_FISCAL_C100 WHERE PERIODO = @PERIODO", new SqlParameter("@PERIODO", periodo));
                                    //cnx.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('DOC_FISCAL_C100', RESEED, 0)");
                                    limpa_C100 = true;
                                }

                                cnx.Entry(par).State = System.Data.Entity.EntityState.Added;
                                cnx.SaveChanges();
                            }
                        }
                    }
                    else if (registro.Contains("|C113|"))
                    {
                        string[] campo = registro.Split('|');

                        if (campo[1] == "C113")
                        {
                            using (var cnx = new EF.ef_dbContainer())
                            {
                                cnx.Database.Connection.ConnectionString = aux.GetEFCnxByCliente(cliente);

                                EF.DEVOLUCAO_C113 par = new EF.DEVOLUCAO_C113();

                                #region Parametros

                                par.REG = campo[1];

                                if (!string.IsNullOrEmpty(campo[2]))
                                {
                                    par.IND_OPER = campo[2];
                                }

                                if (!string.IsNullOrEmpty(campo[3]))
                                {
                                    par.IND_EMIT = campo[3];
                                }

                                if (!string.IsNullOrEmpty(campo[4]))
                                {
                                    par.COD_PART = campo[4];
                                }

                                if (!string.IsNullOrEmpty(campo[5]))
                                {
                                    par.COD_MOD = campo[5];
                                }

                                if (!string.IsNullOrEmpty(campo[6]))
                                {
                                    par.SER = campo[6];
                                }

                                if (!string.IsNullOrEmpty(campo[7]))
                                {
                                    par.SUB = campo[7];
                                }

                                if (!string.IsNullOrEmpty(campo[8]))
                                {
                                    par.NUM_DOC = campo[8];
                                }

                                if (!string.IsNullOrEmpty(campo[9]))
                                {
                                    par.DT_DOC = campo[9];
                                }

                                par.PERIODO = periodo;

                                #endregion

                                if (!limpa_C113)
                                {
                                    cnx.Database.ExecuteSqlCommand("DELETE FROM DEVOLUCAO_C113 WHERE PERIODO = @PERIODO", new SqlParameter("@PERIODO", periodo));
                                    //cnx.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('DOC_FISCAL_C100', RESEED, 0)");
                                    limpa_C113 = true;
                                }

                                cnx.Entry(par).State = System.Data.Entity.EntityState.Added;
                                cnx.SaveChanges();
                            }
                        }
                    }
                    else if (registro.Contains("|C170|"))
                    {
                        string[] campo = registro.Split('|');

                        if (campo[1] == "C170")
                        {
                            using (var cnx = new EF.ef_dbContainer())
                            {
                                cnx.Database.Connection.ConnectionString = aux.GetEFCnxByCliente(cliente);

                                EF.ITENS_DOC_C170 par = new EF.ITENS_DOC_C170();

                                #region Parametros

                                par.REG = campo[1];

                                if (!string.IsNullOrEmpty(campo[2]))
                                {
                                    par.NUM_ITEM = campo[2];
                                }

                                if (!string.IsNullOrEmpty(campo[3]))
                                {
                                    par.COD_ITEM = campo[3];
                                }

                                if (!string.IsNullOrEmpty(campo[4]))
                                {
                                    par.DESCR_COMPL = campo[4];
                                }

                                if (!string.IsNullOrEmpty(campo[5]))
                                {
                                    par.QTD = Convert.ToDecimal(campo[5]);
                                }

                                if (!string.IsNullOrEmpty(campo[6]))
                                {
                                    par.UNID = campo[6];
                                }

                                if (!string.IsNullOrEmpty(campo[7]))
                                {
                                    par.VL_ITEM = Convert.ToDecimal(campo[7]);
                                }

                                if (!string.IsNullOrEmpty(campo[8]))
                                {
                                    par.VL_DESC = Convert.ToDecimal(campo[8]);
                                }

                                if (!string.IsNullOrEmpty(campo[9]))
                                {
                                    par.IND_MOV = campo[9];
                                }

                                if (!string.IsNullOrEmpty(campo[10]))
                                {
                                    par.CST_ICMS = campo[10];
                                }

                                if (!string.IsNullOrEmpty(campo[11]))
                                {
                                    par.CFOP = campo[11];
                                }

                                if (!string.IsNullOrEmpty(campo[12]))
                                {
                                    par.COD_NAT = campo[12];
                                }

                                if (!string.IsNullOrEmpty(campo[13]))
                                {
                                    par.VL_BC_ICMS = Convert.ToDecimal(campo[13]);
                                }

                                if (!string.IsNullOrEmpty(campo[14]))
                                {
                                    par.ALIQ_ICMS = Convert.ToDecimal(campo[14]);
                                }

                                if (!string.IsNullOrEmpty(campo[15]))
                                {
                                    par.VL_ICMS = Convert.ToDecimal(campo[15]);
                                }

                                if (!string.IsNullOrEmpty(campo[16]))
                                {
                                    par.VL_BC_ICMS_ST = Convert.ToDecimal(campo[16]);
                                }

                                if (!string.IsNullOrEmpty(campo[17]))
                                {
                                    par.ALIQ_ST = Convert.ToDecimal(campo[17]);
                                }

                                if (!string.IsNullOrEmpty(campo[18]))
                                {
                                    par.VL_ICMS_ST = Convert.ToDecimal(campo[18]);
                                }

                                if (!string.IsNullOrEmpty(campo[19]))
                                {
                                    par.IND_APUR = campo[19];
                                }

                                if (!string.IsNullOrEmpty(campo[20]))
                                {
                                    par.CST_IPI = campo[20];
                                }

                                if (!string.IsNullOrEmpty(campo[21]))
                                {
                                    par.COD_ENQ = campo[21];
                                }

                                if (!string.IsNullOrEmpty(campo[22]))
                                {
                                    par.VL_BC_IPI = Convert.ToDecimal(campo[22]);
                                }

                                if (!string.IsNullOrEmpty(campo[23]))
                                {
                                    par.ALIQ_IPI = Convert.ToDecimal(campo[23]);
                                }

                                if (!string.IsNullOrEmpty(campo[24]))
                                {
                                    par.VL_IPI = Convert.ToDecimal(campo[24]);
                                }

                                if (!string.IsNullOrEmpty(campo[25]))
                                {
                                    par.CST_PIS = campo[25];
                                }

                                if (!string.IsNullOrEmpty(campo[26]))
                                {
                                    par.VL_BC_PIS = Convert.ToDecimal(campo[26]);
                                }

                                if (!string.IsNullOrEmpty(campo[27]))
                                {
                                    par.ALIQ_PIS_PCT = Convert.ToDecimal(campo[27]);
                                }

                                if (!string.IsNullOrEmpty(campo[28]))
                                {
                                    par.QUANT_BC_PIS = Convert.ToDecimal(campo[28]);
                                }

                                if (!string.IsNullOrEmpty(campo[29]))
                                {
                                    par.ALIQ_PIS = Convert.ToDecimal(campo[29]);
                                }

                                if (!string.IsNullOrEmpty(campo[30]))
                                {
                                    par.VL_PIS = Convert.ToDecimal(campo[30]);
                                }

                                if (!string.IsNullOrEmpty(campo[31]))
                                {
                                    par.CST_COFINS = campo[31];
                                }

                                if (!string.IsNullOrEmpty(campo[32]))
                                {
                                    par.VL_BC_COFINS = Convert.ToDecimal(campo[32]);
                                }

                                if (!string.IsNullOrEmpty(campo[33]))
                                {
                                    par.ALIQ_COFINS_PCT = Convert.ToDecimal(campo[33]);
                                }

                                if (!string.IsNullOrEmpty(campo[34]))
                                {
                                    par.QUANT_BC_COFINS = Convert.ToDecimal(campo[34]);
                                }

                                if (!string.IsNullOrEmpty(campo[35]))
                                {
                                    par.ALIQ_COFINS = Convert.ToDecimal(campo[35]);
                                }

                                if (!string.IsNullOrEmpty(campo[36]))
                                {
                                    par.VL_COFINS = Convert.ToDecimal(campo[36]);
                                }

                                if (!string.IsNullOrEmpty(campo[37]))
                                {
                                    par.COD_CTA = campo[37];
                                }

                                par.PERIODO = periodo;

                                par.NUM_DOC = num_doc;

                                #endregion

                                if (!limpa_C170)
                                {
                                    cnx.Database.ExecuteSqlCommand("DELETE FROM ITENS_DOC_C170 WHERE PERIODO = @PERIODO", new SqlParameter("@PERIODO", periodo));
                                    //cnx.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('ITENS_DOC_C170', RESEED, 0)");
                                    limpa_C170 = true;
                                }

                                cnx.Entry(par).State = System.Data.Entity.EntityState.Added;
                                cnx.SaveChanges();
                            }
                        }
                    }
                    else if (registro.Contains("|C190|"))
                    {
                        string[] campo = registro.Split('|');

                        if (campo[1] == "C190")
                        {
                            using (var cnx = new EF.ef_dbContainer())
                            {
                                cnx.Database.Connection.ConnectionString = aux.GetEFCnxByCliente(cliente);

                                EF.ANAL_DOC_C190 par = new EF.ANAL_DOC_C190();

                                #region Parametros

                                par.REG = campo[1];

                                if (!string.IsNullOrEmpty(campo[2]))
                                {
                                    par.CST_ICMS = campo[2];
                                }

                                if (!string.IsNullOrEmpty(campo[3]))
                                {
                                    par.CFOP = campo[3];
                                }

                                if (!string.IsNullOrEmpty(campo[4]))
                                {
                                    par.ALIQ_ICMS = Convert.ToDecimal(campo[4]);
                                }

                                if (!string.IsNullOrEmpty(campo[5]))
                                {
                                    par.VL_OPR = Convert.ToDecimal(campo[5]);
                                }

                                if (!string.IsNullOrEmpty(campo[6]))
                                {
                                    par.VL_BC_ICMS = Convert.ToDecimal(campo[6]);
                                }

                                if (!string.IsNullOrEmpty(campo[7]))
                                {
                                    par.VL_ICMS = Convert.ToDecimal(campo[7]);
                                }

                                if (!string.IsNullOrEmpty(campo[8]))
                                {
                                    par.VL_BC_ICMS_ST = Convert.ToDecimal(campo[8]);
                                }

                                if (!string.IsNullOrEmpty(campo[9]))
                                {
                                    par.VL_ICMS_ST = Convert.ToDecimal(campo[9]);
                                }

                                if (!string.IsNullOrEmpty(campo[10]))
                                {
                                    par.VL_RED_BC = Convert.ToDecimal(campo[10]);
                                }

                                if (!string.IsNullOrEmpty(campo[11]))
                                {
                                    par.VL_IPI = Convert.ToDecimal(campo[11]);
                                }

                                if (!string.IsNullOrEmpty(campo[12]))
                                {
                                    par.COD_OBS = campo[12];
                                }

                                par.PERIODO = periodo;

                                par.NUM_DOC = num_doc;

                                #endregion

                                if (!limpa_C190)
                                {
                                    cnx.Database.ExecuteSqlCommand("DELETE FROM ANAL_DOC_C190 WHERE PERIODO = @PERIODO", new SqlParameter("@PERIODO", periodo));
                                    //cnx.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('ANAL_DOC_C190', RESEED, 0)");
                                    limpa_C190 = true;
                                }

                                cnx.Entry(par).State = System.Data.Entity.EntityState.Added;
                                cnx.SaveChanges();
                            }
                        }
                    }
                }

                sr.Close();
            }
            catch (Exception ex)
            {
                ret = ex.Message;

                sr.Close();
            }

            trataComponentes();

            return(ret);
        }
Пример #6
0
        public string GeraArquivo(string par_mes, string par_ano, string par_cliente, string conexao, decimal iva, decimal pmc, string CNAE)
        {
            string     ret = "Arquivo gerado com sucesso!";
            TextWriter tw  = null;

            Classes.Auxiliar aux = new Auxiliar();

            try
            {
                StringBuilder sb = new StringBuilder();

                string periodo = par_mes + par_ano;
                string path    = Path.GetDirectoryName(Application.ExecutablePath).Replace(@"\bin\Debug", @"\Classes\Arquivos Gerados\");

                if (System.IO.File.Exists(path + periodo + "_cat207.txt"))
                {
                    System.IO.File.Delete(path + periodo + "_cat207.txt");
                }

                tw = new StreamWriter(path + periodo + "_cat207.txt");

                using (var cnx = new EF.ef_dbContainer())
                {
                    cnx.Database.Connection.ConnectionString = aux.GetEFCnxByCliente(par_cliente);

                    // BLOCO 0
                    #region BLOCO_0

                    #region Gets_0

                    int    count_0             = 0;
                    string tem_dados_0         = "1";
                    int    count_0000          = 0;
                    int    count_0001          = 0;
                    int    count_0150          = 0;
                    int    count_0300          = 0;
                    int    count_0990          = 0;
                    bool   entidade_cadastrada = false;

                    #endregion

                    var entidade       = cnx.ENTIDADE_0000.Where(p => p.PERIODO == periodo).FirstOrDefault();
                    var entidade_compl = cnx.ENTIDADE_COMPL_0005.Where(p => p.PERIODO == periodo).FirstOrDefault();

                    // REGISTRO 0000: ABERTURA DO ARQUIVO DIGITAL E IDENTIFICAÇÃO DO CONTRIBUINTE
                    sb.AppendFormat("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}", "0000", "LASIMCA", "01", "01", periodo, entidade.NOME, entidade.CNPJ, entidade.IE, CNAE, entidade.COD_MUN, entidade.IE);
                    sb.Append("\r\n");
                    count_0++;
                    count_0000++;

                    int qtd_participantes = cnx.PARTICIPANTE_0150.Count();

                    if (qtd_participantes > 0)
                    {
                        tem_dados_0 = "0";
                    }
                    else
                    {
                        tem_dados_0 = "1";
                    }

                    // REGISTRO 0001: ABERTURA DO BLOCO 0
                    sb.AppendFormat("{0}|{1}", "0001", tem_dados_0);
                    sb.Append("\r\n");
                    count_0++;
                    count_0001++;

                    DAL.Bloco0.Participante part = new DAL.Bloco0.Participante();
                    DataTable dt_participante    = part.GetParticipantes(periodo, conexao);


                    for (int k = 0; k < dt_participante.Rows.Count; k++)
                    {
                        // REGISTRO 0150: CADASTRO DE PARTICIPANTES DE OPERAÇÕES E PRESTAÇÕES

                        if (dt_participante.Rows[k]["COD_PART"].ToString() != "" && dt_participante.Rows[k]["NOME"].ToString() != "" && dt_participante.Rows[k]["COD_PAIS"].ToString() != null)
                        {
                            string cod_pais = dt_participante.Rows[k]["COD_PAIS"].ToString();
                            if (cod_pais.Length < 5)
                            {
                                for (int i = 0; i < 5 - dt_participante.Rows[k]["COD_PAIS"].ToString().Length; i++)
                                {
                                    cod_pais = "0" + cod_pais;
                                }
                            }

                            string cnpj_cpf = dt_participante.Rows[k]["CNPJ"].ToString();
                            if (cnpj_cpf == null || cnpj_cpf.Trim() == "")
                            {
                                cnpj_cpf = dt_participante.Rows[k]["CPF"].ToString();

                                if (cnpj_cpf != null || cnpj_cpf == "")
                                {
                                    if (cnpj_cpf.Length < 11)
                                    {
                                        for (int i = 0; i < 11 - dt_participante.Rows[k]["CPF"].ToString().Length; i++)
                                        {
                                            cnpj_cpf = "0" + cnpj_cpf;
                                        }
                                    }
                                }
                                else
                                {
                                    cnpj_cpf = "";
                                }
                            }
                            else if (cnpj_cpf.Length < 14)
                            {
                                for (int i = 0; i < 14 - dt_participante.Rows[k]["CNPJ"].ToString().Length; i++)
                                {
                                    cnpj_cpf = "0" + cnpj_cpf;
                                }
                            }

                            string NUM = "";
                            if (dt_participante.Rows[k]["NUM"].ToString() == null || dt_participante.Rows[k]["NUM"].ToString().Trim() == "")
                            {
                                NUM = "S/N";
                            }
                            else
                            {
                                NUM = dt_participante.Rows[k]["NUM"].ToString();
                            }

                            string CEP = "";
                            if (dt_participante.Rows[k]["CEP"].ToString() == null || dt_participante.Rows[k]["CEP"].ToString().Trim() == "")
                            {
                                CEP = "00000000";
                            }
                            else
                            {
                                CEP = dt_participante.Rows[k]["CEP"].ToString();
                            }

                            CEP = CEP.Trim();

                            string IE = "";
                            if (dt_participante.Rows[k]["IE"].ToString() == null || dt_participante.Rows[k]["IE"].ToString().Trim() == "")
                            {
                                IE = "000000000000";
                            }
                            else
                            {
                                IE = dt_participante.Rows[k]["IE"].ToString();
                            }

                            IE = IE.Trim();

                            if (cod_pais == "01058")
                            {
                                sb.AppendFormat("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}|{11}|{12}|{13}CRLF",
                                                "0150", dt_participante.Rows[k]["COD_PART"].ToString(), dt_participante.Rows[k]["NOME"].ToString(), cod_pais, cnpj_cpf, IE, dt_participante.Rows[k]["UF"].ToString(),
                                                CEP, dt_participante.Rows[k]["END"].ToString(), NUM, dt_participante.Rows[k]["COMPL"].ToString(), dt_participante.Rows[k]["BAIRRO"].ToString(),
                                                dt_participante.Rows[k]["COD_MUN"].ToString(), "");
                            }
                            else
                            {
                                sb.AppendFormat("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}|{11}|{12}|{13}",
                                                "0150", dt_participante.Rows[k]["COD_PART"].ToString(), dt_participante.Rows[k]["NOME"].ToString(), cod_pais, "", "", "",
                                                "", "", "", "", "", "", "");
                            }

                            sb.Append("\r\n");
                            count_0++;
                            count_0150++;

                            if (dt_participante.Rows[k]["CNPJ"].ToString() == entidade.CNPJ)
                            {
                                entidade_cadastrada = true;
                            }
                        }
                    }

                    if (!entidade_cadastrada)
                    {
                        string NUM = "";
                        if (entidade_compl.NUM == null || entidade_compl.NUM.Trim() == "")
                        {
                            NUM = "S/N";
                        }
                        else
                        {
                            NUM = entidade_compl.NUM;
                        }

                        // ENTIDADE
                        sb.AppendFormat("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}|{11}|{12}|{13}CRLF",
                                        "0150", "0000000001", entidade.NOME, "01058", entidade.CNPJ, entidade.IE, entidade.UF,
                                        entidade_compl.CEP, entidade_compl.END, NUM, entidade_compl.COMPL, entidade_compl.BAIRRO, entidade.COD_MUN, entidade_compl.FONE);
                        sb.Append("\r\n");
                        count_0++;
                        count_0150++;
                    }

                    var qtd_enquadramento = cnx.ENQUADRAMENTO_5D.Count();
                    var enquadramento     = cnx.ENQUADRAMENTO_5D.Where(p => p.PERIODO == periodo);

                    foreach (var item in enquadramento)
                    {
                        string cod_enq = item.COD_ENQUADRAMENTO.ToString();
                        if (cod_enq.Length < 4)
                        {
                            for (int i = 0; i < 4 - item.COD_ENQUADRAMENTO.ToString().Length; i++)
                            {
                                cod_enq = "0" + cod_enq;
                            }
                        }

                        string desc = item.COD_HIP_GER.ToString();
                        if (desc.Length < 2)
                        {
                            desc = "0" + desc;
                        }

                        // REGISTRO 0300: ENQUADRAMENTO LEGAL DA OPERAÇÃO/PRESTAÇÃO GERADORA DE CRÉDITO ACUMULADO DO ICMS
                        sb.AppendFormat("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}CRLF",
                                        "0300", cod_enq, desc, item.ANEXO, item.ARTIGO,
                                        item.INCISO, item.ALINEA, item.PARAGRAFO, item.ITEM, item.LETRA, item.OBS);

                        sb.Append("\r\n");
                        count_0++;
                        count_0300++;
                    }

                    // REGISTRO 0990: ENCERRAMENTO DO BLOCO 0
                    count_0++;
                    sb.AppendFormat("{0}|{1}", "0990", count_0.ToString());
                    sb.Append("\r\n");
                    count_0990++;

                    #endregion

                    // BLOCO 5

                    #region BLOCO_5

                    #region Gets_5

                    int     count_5          = 0;
                    int     count_5001       = 0;
                    int     count_5315       = 0;
                    int     count_5320       = 0;
                    int     count_5325       = 0;
                    int     count_5330       = 0;
                    int     count_5335       = 0;
                    int     count_5340       = 0;
                    int     count_5350       = 0;
                    int     count_5990       = 0;
                    string  tem_dados_5      = "1";
                    decimal perc_crd_out     = 0;
                    decimal valor_crd_out    = 0;
                    decimal icms_total       = 0;
                    string  st_perc_crdout   = "0,00";
                    string  st_valor_crdout  = "0,00";
                    string  comprov_op       = "1";
                    string  num_decl_exp_ind = "";

                    // REGISTRO 5315: OPERAÇÕES DE SAÍDA
                    var c100 = cnx.v_150_C100_C190_ENQ_OP.Where(p => p.PERIODO == periodo);

                    // REGISTRO 5320 DEVOLUÇÃO DE SAÍDA
                    string[] cfop_devolucao = { "52", "53", "54", "55", "56", "59" };
                    var      c190_devolucao = cnx.ANAL_DOC_C190.Where(p => p.PERIODO == periodo && cfop_devolucao.Contains(p.CFOP)).Select(p => p.NUM_DOC);
                    var      c100_devolucao = cnx.DOC_FISCAL_C100.Where(p => p.PERIODO == periodo && p.IND_OPER == "0" && c190_devolucao.Contains(p.NUM_DOC));
                    var      c113           = cnx.DEVOLUCAO_C113.Where(p => p.PERIODO == periodo);

                    #endregion

                    // REGISTRO 5001: ABERTURA DO BLOCO 5
                    if (c100.Count() > 0)
                    {
                        tem_dados_5 = "0";
                    }
                    else
                    {
                        tem_dados_5 = "1";
                    }

                    sb.AppendFormat("{0}|{1}", "5001", tem_dados_5);
                    sb.Append("\r\n");
                    count_5++;
                    count_5001++;

                    foreach (var item in c100)
                    {
                        if (item != null)
                        {
                            // REGISTRO 5315: OPERAÇÕES DE SAÍDA
                            string tip_doc = item.COD_MOD;
                            if (item.COD_MOD == "55")
                            {
                                tip_doc = "31";
                            }

                            if ((item.DT_DOC != "" && item.DT_DOC != null) && (item.COD_PART != "" && item.COD_PART != null) && (item.VL_DOC.ToString() != "" && item.VL_DOC != null))
                            {
                                string SER = item.SER;
                                if (SER == null)
                                {
                                    SER = "1";
                                }

                                sb.AppendFormat("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}",
                                                "5315", item.DT_DOC, tip_doc, SER, item.NUM_DOC, item.COD_PART, item.VL_DOC.ToString().Replace(".", ","), st_perc_crdout.ToString().Replace(".", ","),
                                                st_valor_crdout.ToString().Replace(".", ","));
                                sb.Append("\r\n");
                                count_5++;
                                count_5315++;

                                // REGISTRO 5320 DEVOLUÇÃO DE SAÍDA
                                foreach (var item_devolucao in c100_devolucao)
                                {
                                    if (item.NUM_DOC == item_devolucao.NUM_DOC)
                                    {
                                        sb.AppendFormat("{0}|{1}|{2}|{3}|{4}CRLF", "5320", item_devolucao.DT_DOC, item_devolucao.COD_MOD, item_devolucao.SER, item_devolucao.NUM_DOC);
                                        sb.Append("\r\n");
                                        count_5++;
                                        count_5320++;
                                    }
                                }

                                foreach (var item_c113 in c113)
                                {
                                    if (item.NUM_DOC == item_c113.NUM_DOC)
                                    {
                                        sb.AppendFormat("{0}|{1}|{2}|{3}|{4}CRLF", "5320", item_c113.DT_DOC, item_c113.COD_MOD, item_c113.SER, item_c113.NUM_DOC);
                                        sb.Append("\r\n");
                                        count_5++;
                                        count_5320++;
                                    }
                                }


                                decimal cred_est_icms = Math.Round((Convert.ToDecimal(item.VL_DOC) / (1 + Convert.ToDecimal(iva))) * Convert.ToDecimal(pmc) / 100, 2);
                                decimal icms_gera     = 0;
                                string  cod_legal     = "";

                                var enq_op = cnx.ENQ_OP.Where(p => p.PERIODO == periodo && p.NUM_DOC == item.NUM_DOC && p.SER == item.SER).FirstOrDefault();

                                if (enq_op == null)
                                {
                                    cod_legal = "";
                                }
                                else
                                {
                                    if (enq_op.COD_ENQUADRAMENTO == null)
                                    {
                                        cod_legal = "";
                                    }
                                    else
                                    {
                                        cod_legal = enq_op.COD_ENQUADRAMENTO.ToString();

                                        if (cod_legal.Length < 4)
                                        {
                                            for (int i = 0; i < 4 - enq_op.COD_ENQUADRAMENTO.ToString().Length; i++)
                                            {
                                                cod_legal = "0" + cod_legal;
                                            }
                                        }
                                    }
                                }

                                if (item.COD_HIP_GER == 9 && item.ALIQ_ICMS == 0)
                                {
                                    int enq_op_count = cnx.ENQ_OP.Where(p => p.PERIODO == periodo && p.NUM_DOC == item.NUM_DOC && p.SER == item.SER).Count();

                                    if (enq_op_count > 0)
                                    {
                                        if (enq_op.COMPROV_OP == true)
                                        {
                                            icms_gera  = cred_est_icms + valor_crd_out;
                                            comprov_op = "0";
                                        }
                                        else
                                        {
                                            icms_gera  = Math.Round(Convert.ToDecimal("0"), 2);
                                            comprov_op = "1";
                                        }
                                    }

                                    // REGISTRO 5325 OPERAÇÕES GERADORAS DE CRÉDITO ACUMULADO
                                    sb.AppendFormat("{0}|{1}|{2}|{3}|{4}|{5}", "5325", cod_legal, String.Format("{0:0.0000}", iva).ToString().Replace(".", ","), pmc.ToString().Replace(".", ","),
                                                    cred_est_icms.ToString().Replace(".", ","), icms_gera.ToString().Replace(".", ","));
                                    sb.Append("\r\n");
                                    count_5++;
                                    count_5325++;


                                    // REGISTRO 5335 OPERAÇÕES GERADORAS APURADAS NA FICHA 6C OU 6D
                                    sb.AppendFormat("{0}|{1}|{2}", "5335", "", comprov_op);
                                    sb.Append("\r\n");
                                    count_5++;
                                    count_5335++;
                                }
                                else if (item.COD_HIP_GER == 10 || item.COD_HIP_GER == 11)
                                {
                                    icms_gera = cred_est_icms + valor_crd_out;

                                    // REGISTRO 5325 OPERAÇÕES GERADORAS DE CRÉDITO ACUMULADO
                                    sb.AppendFormat("{0}|{1}|{2}|{3}|{4}|{5}", "5325", cod_legal, String.Format("{0:0.0000}", iva).ToString().Replace(".", ","), pmc.ToString().Replace(".", ","),
                                                    cred_est_icms.ToString().Replace(".", ","), icms_gera.ToString().Replace(".", ","));
                                    sb.Append("\r\n");
                                    count_5++;
                                    count_5325++;
                                }
                                else if (item.COD_HIP_GER == 1 || item.COD_HIP_GER == 2 || item.COD_HIP_GER == 5 || item.COD_HIP_GER == 6)
                                {
                                    string VL_BC_ICMS = item.VL_BC_ICMS.ToString().Replace(".", ",");
                                    if (VL_BC_ICMS == "")
                                    {
                                        VL_BC_ICMS = "0,00";
                                    }

                                    string VL_ICMS = item.VL_ICMS.ToString().Replace(".", ",");
                                    if (VL_ICMS == "")
                                    {
                                        VL_ICMS = "0,00";
                                    }
                                    else
                                    {
                                        VL_ICMS = String.Format("{0:0.00}", (Convert.ToDecimal(VL_BC_ICMS) * (Convert.ToDecimal(item.ALIQ_ICMS) / 100))).ToString().Replace(".", ",");
                                    }

                                    icms_total = cred_est_icms + valor_crd_out;
                                    icms_gera  = icms_total - (Convert.ToDecimal(VL_BC_ICMS) * (Convert.ToDecimal(item.ALIQ_ICMS) / 100));

                                    if (icms_gera >= 0 && (item.ALIQ_ICMS == 4 || item.ALIQ_ICMS == 7 || item.ALIQ_ICMS == 12) && (VL_BC_ICMS != "0,00" && VL_ICMS != "0,00"))
                                    {
                                        // 6A
                                        // REGISTRO 5325 OPERAÇÕES GERADORAS DE CRÉDITO ACUMULADO - FICHA 6A
                                        sb.AppendFormat("{0}|{1}|{2}|{3}|{4}|{5}",
                                                        "5325", cod_legal, String.Format("{0:0.0000}", iva).ToString().Replace(".", ","), pmc.ToString().Replace(".", ","), cred_est_icms.ToString().Replace(".", ","),
                                                        String.Format("{0:0.00}", icms_gera).ToString().Replace(".", ","));
                                        sb.Append("\r\n");
                                        count_5++;
                                        count_5325++;

                                        // REGISTRO 5330 OPERAÇÕES GERADORAS APURADAS NAS FICHAS 6A OU 6B
                                        sb.AppendFormat("{0}|{1}|{2}", "5330", VL_BC_ICMS, VL_ICMS);
                                        sb.Append("\r\n");
                                        count_5++;
                                        count_5330++;
                                    }
                                    else
                                    {
                                        // REGISTRO 5350: OPERAÇÕES NÃO GERADORAS DE CRÉDITO ACUMULADO – FICHA 6A -> FICHA 6F
                                        sb.AppendFormat("{0}|{1}|{2}|{3}CRLF", "5350", VL_BC_ICMS, VL_ICMS, num_decl_exp_ind);
                                        sb.Append("\r\n");
                                        count_5++;
                                        count_5350++;
                                    }
                                }
                                else
                                {
                                    string VL_BC_ICMS = item.VL_BC_ICMS.ToString().Replace(".", ",");
                                    if (VL_BC_ICMS == "")
                                    {
                                        VL_BC_ICMS = "0,00";
                                    }

                                    string VL_ICMS = item.VL_ICMS.ToString().Replace(".", ",");
                                    if (VL_ICMS == "")
                                    {
                                        VL_ICMS = "0,00";
                                    }
                                    else
                                    {
                                        VL_ICMS = String.Format("{0:0.00}", (Convert.ToDecimal(VL_BC_ICMS) * (Convert.ToDecimal(item.ALIQ_ICMS) / 100))).ToString().Replace(".", ",");
                                    }

                                    // REGISTRO 5350: OPERAÇÕES NÃO GERADORAS DE CRÉDITO ACUMULADO – FICHA 6F
                                    sb.AppendFormat("{0}|{1}|{2}|{3}CRLF", "5350", VL_BC_ICMS, VL_ICMS, num_decl_exp_ind);
                                    sb.Append("\r\n");
                                    count_5++;
                                    count_5350++;
                                }
                            }
                        }
                    }

                    // REGISTRO 5990: ENCERRAMENTO DO BLOCO 5
                    count_5++;
                    sb.AppendFormat("{0}|{1}", "5990", count_5.ToString());
                    sb.Append("\r\n");
                    count_5990++;


                    #endregion


                    // BLOCO 9

                    #region BLOCO_9

                    int    count_9     = 0;
                    string tem_dados_9 = "0";

                    // REGISTRO 9001: ABERTURA DO BLOCO 9
                    sb.AppendFormat("{0}|{1}", "9001", tem_dados_9);
                    sb.Append("\r\n");
                    count_9++;

                    ArrayList registros       = new ArrayList();
                    ArrayList count_registros = new ArrayList();

                    registros.Add("0000");
                    registros.Add("0001");
                    registros.Add("0150");

                    if (count_0300 > 0)
                    {
                        registros.Add("0300");
                    }

                    registros.Add("0990");
                    registros.Add("5001");
                    registros.Add("5315");

                    if (count_5320 > 0)
                    {
                        registros.Add("5320");
                    }

                    if (count_5325 > 0)
                    {
                        registros.Add("5325");
                    }

                    if (count_5330 > 0)
                    {
                        registros.Add("5330");
                    }

                    if (count_5335 > 0)
                    {
                        registros.Add("5335");
                    }

                    if (count_5350 > 0)
                    {
                        registros.Add("5350");
                    }

                    registros.Add("5990");
                    registros.Add("9001");
                    registros.Add("9900");
                    registros.Add("9990");
                    registros.Add("9999");
                    count_registros.Add(count_0000);
                    count_registros.Add(count_0001);
                    count_registros.Add(count_0150);

                    if (count_0300 > 0)
                    {
                        count_registros.Add(count_0300);
                    }

                    count_registros.Add(count_0990);
                    count_registros.Add(count_5001);
                    count_registros.Add(count_5315);

                    if (count_5320 > 0)
                    {
                        count_registros.Add(count_5320);
                    }

                    if (count_5325 > 0)
                    {
                        count_registros.Add(count_5325);
                    }

                    if (count_5330 > 0)
                    {
                        count_registros.Add(count_5330);
                    }

                    if (count_5335 > 0)
                    {
                        count_registros.Add(count_5335);
                    }

                    if (count_5350 > 0)
                    {
                        count_registros.Add(count_5350);
                    }

                    count_registros.Add(count_5990);
                    count_registros.Add(1);
                    count_registros.Add(0);
                    count_registros.Add(1);
                    count_registros.Add(1);



                    for (int i = 0; i < registros.Count; i++)
                    {
                        if (registros[i] != "9900")
                        {
                            sb.AppendFormat("{0}|{1}|{2}", "9900", registros[i], count_registros[i].ToString());
                        }
                        else
                        {
                            sb.AppendFormat("{0}|{1}|{2}", "9900", registros[i], registros.Count.ToString());
                        }

                        sb.Append("\r\n");
                        count_9++;
                    }


                    // REGISTRO 9990: ENCERRAMENTO DO BLOCO 9
                    count_9++;
                    sb.AppendFormat("{0}|{1}", "9990", (count_9 + 1).ToString());
                    sb.Append("\r\n");


                    // REGISTRO 9999: ENCERRAMENTO DO ARQUIVO DIGITAL
                    sb.AppendFormat("{0}|{1}", "9999", (count_0 + count_5 + count_9 + 1).ToString());


                    #endregion

                    tw.Write(sb);
                    sb.Clear();
                    tw.Close();

                    bool arq_ger_existe = true;
                    var  arq_ger        = cnx.ARQUIVOS_GERADOS.Where(p => p.PERIODO_ARQUIVO == periodo).FirstOrDefault();

                    if (arq_ger == null)
                    {
                        arq_ger_existe = false;
                        arq_ger        = new EF.ARQUIVOS_GERADOS();
                    }

                    arq_ger.ARQUIVO         = path + periodo + "_cat207.txt";
                    arq_ger.IVA             = iva;
                    arq_ger.PMC             = pmc;
                    arq_ger.PERIODO_ARQUIVO = periodo;
                    arq_ger.PERIODO_GERACAO = DateTime.Now.ToString("MMyyyy");

                    if (!arq_ger_existe)
                    {
                        cnx.Entry(arq_ger).State = System.Data.Entity.EntityState.Added;
                    }

                    cnx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                ret = "Erro na geração do arquivo";
                tw.Close();
            }

            return(ret);
        }