Ejemplo n.º 1
0
        private static void bw_DoWork(object sender, DoWorkEventArgs a)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            List <object> args = a.Argument as List <object>;
            painel_taxservices_dbContext _db = args[0] as painel_taxservices_dbContext;
            Semaphore      semaforo          = args[1] as Semaphore;
            Retorno        retorno           = args[2] as Retorno;
            Int32          idGrupo           = Convert.ToInt32(args[3]);
            ImportaTitulos param             = args[4] as ImportaTitulos;

            List <dynamic> Registros = retorno.Registros as List <dynamic>;

            //List<dynamic> grupo = Registros
            //                             .GroupBy(e => new { e.nrCNPJ, e.nrNSU, e.dtTitulo, e.nrParcela })
            //                             .Where(e => e.Count() > 1)
            //                             .Select(e => new
            //                             {
            //                                 e.Key.nrCNPJ,
            //                                 e.Key.nrNSU,
            //                                 e.Key.nrParcela,
            //                                 e.Key.dtTitulo,
            //                                 count = e.Count()
            //                             })
            //                             .OrderByDescending(e => e.count)
            //                             .ToList<dynamic>();
            List <int> idsRecebimentoTitulo = new List <int>();

            for (var k = 0; k < Registros.Count; k++)
            {
                dynamic tit = Registros[k];
                DbContextTransaction transaction = _db.Database.BeginTransaction();
                try
                {
                    string dsBandeira = tit.dsBandeira;
                    if (dsBandeira.Length > 50)
                    {
                        dsBandeira = dsBandeira.Substring(0, 50);
                    }

                    int?cdAdquirente = null;
                    try
                    {
                        cdAdquirente = Convert.ToInt32(tit.cdAdquirente);
                        if (cdAdquirente == 0)
                        {
                            cdAdquirente = null;
                        }
                    }
                    catch { }

                    string cdSacado = null;
                    try
                    {
                        cdSacado = tit.cdSacado;
                        cdSacado = cdSacado.Trim();
                    }
                    catch { }

                    tbRecebimentoTitulo tbRecebimentoTitulo = new tbRecebimentoTitulo
                    {
                        dsBandeira   = dsBandeira,
                        cdAdquirente = cdAdquirente,
                        cdERP        = tit.cdERP,
                        dtBaixaERP   = tit.dtBaixaERP,
                        dtTitulo     = tit.dtTitulo,
                        dtVenda      = tit.dtVenda,
                        nrCNPJ       = tit.nrCNPJ,//tit.empresa.nu_cnpj,
                        nrNSU        = tit.nrNSU != null && !tit.nrNSU.ToString().Trim().Equals("") ? tit.nrNSU : "T" + tit.cdERP,
                        nrParcela    = Convert.ToByte(tit.nrParcela),
                        qtParcelas   = Convert.ToByte(tit.qtParcelas),
                        vlParcela    = Convert.ToDecimal(tit.vlParcela),
                        vlVenda      = Convert.ToDecimal(tit.vlVenda),
                        cdSacado     = cdSacado
                    };

                    tbRecebimentoTitulo titulo = _db.Database.SqlQuery <tbRecebimentoTitulo>("SELECT T.*" +
                                                                                             " FROM card.tbRecebimentoTitulo T (NOLOCK)" +
                                                                                             " WHERE T.nrCNPJ = '" + tbRecebimentoTitulo.nrCNPJ + "'" +
                                                                                             " AND T.nrNSU = '" + tbRecebimentoTitulo.nrNSU + "'" +
                                                                                             " AND T.dtTitulo = '" + DataBaseQueries.GetDate(tbRecebimentoTitulo.dtTitulo) + "'" +
                                                                                             " AND T.nrParcela = " + tbRecebimentoTitulo.nrParcela +
                                                                                             " AND T.cdERP = '" + tbRecebimentoTitulo.cdERP + "'"
                                                                                             )
                                                 .FirstOrDefault();

                    int idRecebimentoTitulo = 0;
                    if (titulo == null)
                    {
                        _db.Database.ExecuteSqlCommand("INSERT INTO card.tbRecebimentoTitulo" +
                                                       " (nrCNPJ, nrNSU, dtTitulo, nrParcela, cdERP, dtVenda" +
                                                       ", cdAdquirente, dsBandeira, vlVenda, qtParcelas, vlParcela, dtBaixaERP, cdSacado)" +
                                                       " VALUES ('" + tbRecebimentoTitulo.nrCNPJ + "'" +
                                                       ", '" + tbRecebimentoTitulo.nrNSU + "'" +
                                                       ", '" + DataBaseQueries.GetDate(tbRecebimentoTitulo.dtTitulo) + "'" +
                                                       ", " + tbRecebimentoTitulo.nrParcela +
                                                       ", " + (tbRecebimentoTitulo.cdERP == null ? "NULL" : "'" + tbRecebimentoTitulo.cdERP + "'") +
                                                       ", " + (tbRecebimentoTitulo.dtVenda == null ? "NULL" : "'" + DataBaseQueries.GetDate(tbRecebimentoTitulo.dtVenda.Value) + "'") +
                                                       ", " + (cdAdquirente == null ? "NULL" : cdAdquirente.Value.ToString()) +
                                                       ", " + (tbRecebimentoTitulo.dsBandeira == null ? "NULL" : "'" + tbRecebimentoTitulo.dsBandeira + "'") +
                                                       ", " + (tbRecebimentoTitulo.vlVenda == null ? "NULL" : tbRecebimentoTitulo.vlVenda.Value.ToString(CultureInfo.GetCultureInfo("en-GB"))) +
                                                       ", " + (tbRecebimentoTitulo.qtParcelas == null ? "NULL" : tbRecebimentoTitulo.qtParcelas.Value.ToString()) +
                                                       ", " + tbRecebimentoTitulo.vlParcela.ToString(CultureInfo.GetCultureInfo("en-GB")) +
                                                       ", " + (tbRecebimentoTitulo.dtBaixaERP == null ? "NULL" : "'" + DataBaseQueries.GetDate(tbRecebimentoTitulo.dtBaixaERP.Value) + "'") +
                                                       ", " + (tbRecebimentoTitulo.cdSacado != null ? "'" + tbRecebimentoTitulo.cdSacado + "'" : "NULL") +
                                                       ")");
                        _db.SaveChanges();
                        transaction.Commit();

                        // Obtém o id do título
                        idRecebimentoTitulo = _db.Database.SqlQuery <int>("SELECT T.idRecebimentoTitulo" +
                                                                          " FROM card.tbRecebimentoTitulo T (NOLOCK)" +
                                                                          " WHERE T.nrCNPJ = '" + tbRecebimentoTitulo.nrCNPJ + "'" +
                                                                          " AND T.nrNSU = '" + tbRecebimentoTitulo.nrNSU + "'" +
                                                                          " AND T.dtTitulo = '" + DataBaseQueries.GetDate(tbRecebimentoTitulo.dtTitulo) + "'" +
                                                                          " AND T.nrParcela = " + tbRecebimentoTitulo.nrParcela +
                                                                          " AND T.cdERP = '" + tbRecebimentoTitulo.cdERP + "'"
                                                                          )
                                              .FirstOrDefault();
                    }
                    else
                    {
                        _db.Database.ExecuteSqlCommand("UPDATE T" +
                                                       " SET T.dtVenda = " + (tbRecebimentoTitulo.dtVenda == null ? "NULL" : "'" + DataBaseQueries.GetDate(tbRecebimentoTitulo.dtVenda.Value) + "'") +
                                                       ", T.cdAdquirente = " + (cdAdquirente == null ? "NULL" : cdAdquirente.Value.ToString()) +
                                                       ", T.dsBandeira = " + (tbRecebimentoTitulo.dsBandeira == null ? "NULL" : "'" + tbRecebimentoTitulo.dsBandeira + "'") +
                                                       ", T.vlVenda = " + (tbRecebimentoTitulo.vlVenda == null ? "NULL" : tbRecebimentoTitulo.vlVenda.Value.ToString(CultureInfo.GetCultureInfo("en-GB"))) +
                                                       ", T.qtParcelas = " + (tbRecebimentoTitulo.qtParcelas == null ? "NULL" : tbRecebimentoTitulo.qtParcelas.Value.ToString()) +
                                                       ", T.vlParcela = " + tbRecebimentoTitulo.vlParcela.ToString(CultureInfo.GetCultureInfo("en-GB")) +
                                                       ", T.dtBaixaERP = " + (tbRecebimentoTitulo.dtBaixaERP == null ? "NULL" : "'" + DataBaseQueries.GetDate(tbRecebimentoTitulo.dtBaixaERP.Value) + "'") +
                                                       ", T.cdSacado = " + (tbRecebimentoTitulo.cdSacado != null ? "'" + tbRecebimentoTitulo.cdSacado + "'" : "NULL") +
                                                       " FROM card.tbRecebimentoTitulo T" +
                                                       " WHERE T.idRecebimentoTitulo = " + titulo.idRecebimentoTitulo);

                        _db.SaveChanges();
                        transaction.Commit();

                        idRecebimentoTitulo = titulo.idRecebimentoTitulo;
                    }

                    // Adiciona
                    //if (!idsRecebimentoTitulo.Contains(idRecebimentoTitulo))
                    idsRecebimentoTitulo.Add(idRecebimentoTitulo);
                }
                catch (Exception e)
                {
                    transaction.Rollback();
                    string json = JsonConvert.SerializeObject(tit);
                    string erro = String.Empty;
                    if (e is DbEntityValidationException)
                    {
                        erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    }
                    else
                    {
                        erro = e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message;
                    }
                    //throw new Exception("Título: " + json + ". Erro: " + erro);
                    // Reporta o erro
                    retorno.Totais = new Dictionary <string, object>();
                    retorno.Totais.Add("erro", "Título: " + json + ". Erro: " + erro);
                    break;
                }
            }

            // Avalia títulos que não foram atualizados
            if (idsRecebimentoTitulo.Count > 0 && param != null)
            {
                idsRecebimentoTitulo = idsRecebimentoTitulo.Distinct().ToList();
                string data     = param.data.Substring(0, 4) + "-" + param.data.Substring(4, 2) + "-" + param.data.Substring(6, 2);
                string tipoData = param.tipoData == null || (!param.tipoData.Equals("V") && !param.tipoData.Equals("R")) ? "R" : param.tipoData;
                string script   = "SELECT T.idRecebimentoTitulo" +
                                  " FROM card.tbRecebimentoTitulo T (NOLOCK)" +
                                  " JOIN cliente.empresa E (NOLOCK) ON E.nu_cnpj = T.nrCNPJ" +
                                  " WHERE " + (tipoData.Equals("V") ? "T.dtVenda" : "T.dtTitulo") + " BETWEEN '" + data + "' AND '" + data + " 23:59:00'" +
                                  " AND E.id_grupo = " + idGrupo +
                                  " AND T.idRecebimentoTitulo NOT IN (" + string.Join(", ", idsRecebimentoTitulo) + ")";
                int[] titulosASeremDeletados = new int[0];
                try
                {
                    titulosASeremDeletados = _db.Database.SqlQuery <int>(script).ToArray();
                }
                catch { }

                if (titulosASeremDeletados != null && titulosASeremDeletados.Length > 0)
                {
                    script = "UPDATE P" +
                             " SET P.idRecebimentoTitulo = NULL" +
                             " FROM pos.RecebimentoParcela P" +
                             " JOIN card.tbRecebimentoVenda T ON P.idRecebimentoTitulo = T.idRecebimentoTitulo" +
                             " WHERE T.idRecebimentoTitulo IN (" + string.Join(", ", titulosASeremDeletados) + ")";
                    try
                    {
                        _db.Database.ExecuteSqlCommand(script);
                        // Deleta
                        script = "DELETE T" +
                                 " FROM card.tbRecebimentoTitulo T" +
                                 " WHERE V.idRecebimentoVenda IN (" + string.Join(", ", titulosASeremDeletados) + ")";
                        _db.Database.ExecuteSqlCommand(script);
                    }
                    catch { }
                }
            }

            semaforo.Release();
        }
Ejemplo n.º 2
0
        // GET "titulos/consultatitulos"
        public static void ImportaTitulos(string token, ImportaTitulos param, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

            if (_dbContext == null)
            {
                _db = new painel_taxservices_dbContext();
            }
            else
            {
                _db = _dbContext;
            }

            try
            {
                if (param != null)
                {
                    // GRUPO EMPRESA => OBRIGATÓRIO!
                    Int32 IdGrupo = Permissoes.GetIdGrupo(token, _db);
                    //if (IdGrupo == 0 && param.id_grupo != 0) IdGrupo = param.id_grupo;
                    if (IdGrupo == 0)
                    {
                        throw new Exception("Um grupo deve ser selecionado como para a importação dos títulos!");
                    }

                    grupo_empresa grupo_empresa = _db.Database.SqlQuery <grupo_empresa>("SELECT G.*" +
                                                                                        " FROM cliente.grupo_empresa G (NOLOCK)" +
                                                                                        " WHERE G.id_grupo = " + IdGrupo)
                                                  .FirstOrDefault();

                    if (grupo_empresa.dsAPI == null || grupo_empresa.dsAPI.Equals(""))
                    {
                        throw new Exception("Permissão negada! Empresa não possui o serviço ativo");
                    }

                    Retorno retorno = carregaTitulos(_db, token, grupo_empresa.dsAPI, param.data, param.tipoData);

                    Semaphore semaforo = new Semaphore(0, 1);

                    BackgroundWorker bw = new BackgroundWorker();
                    bw.WorkerReportsProgress      = false;
                    bw.WorkerSupportsCancellation = false;
                    bw.DoWork += bw_DoWork;
                    List <object> args = new List <object>();
                    args.Add(_db);
                    args.Add(semaforo);
                    args.Add(retorno);
                    args.Add(IdGrupo);
                    args.Add(param);
                    bw.RunWorkerAsync(args);

                    semaforo.WaitOne();

                    // Teve erro?
                    object outValue = null;
                    if (retorno.Totais != null && retorno.Totais.TryGetValue("erro", out outValue))
                    {
                        throw new Exception(retorno.Totais["erro"].ToString());
                    }
                }
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao importar títulos ERP" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
            finally
            {
                if (_dbContext == null)
                {
                    // Fecha a conexão
                    _db.Database.Connection.Close();
                    _db.Dispose();
                }
            }
        }