Esempio n. 1
0
        // POST /VendasErp/token/
        public HttpResponseMessage Post(string token, [FromBody] ImportaVendas param)
        {
            // Abre nova conexão
            using (painel_taxservices_dbContext _db = new painel_taxservices_dbContext())
            {
                tbLogAcessoUsuario log = new tbLogAcessoUsuario();
                try
                {
                    log = Bibliotecas.LogAcaoUsuario.New(token, JsonConvert.SerializeObject(param), "Post", _db);

                    HttpResponseMessage retorno = new HttpResponseMessage();
                    if (Permissoes.Autenticado(token, _db))
                    {
                        GatewayVendasErp.ImportaVendas(token, param, _db);
                        log.codResposta = (int)HttpStatusCode.OK;
                        Bibliotecas.LogAcaoUsuario.Save(log, _db);
                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else
                    {
                        log.codResposta = (int)HttpStatusCode.Unauthorized;
                        Bibliotecas.LogAcaoUsuario.Save(log, _db);
                        return(Request.CreateResponse(HttpStatusCode.Unauthorized));
                    }
                }
                catch (Exception e)
                {
                    HttpStatusCode httpStatus = e.Message.StartsWith("Permissão negada") || e.Message.StartsWith("401") ? HttpStatusCode.Unauthorized : HttpStatusCode.InternalServerError;
                    log.codResposta = (int)httpStatus;
                    log.msgErro     = e.Message;
                    Bibliotecas.LogAcaoUsuario.Save(log);
                    //throw new HttpResponseException(HttpStatusCode.InternalServerError);
                    return(Request.CreateResponse(httpStatus, e.Message));
                }
            }
        }
Esempio n. 2
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]);
            ImportaVendas param = args[4] as ImportaVendas;

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

            //List<dynamic> test = Registros.Where(t => Convert.ToString(t.nrCNPJ).Equals("08297710000480")).ToList();

            List <int> idsRecebimentoVenda = new List <int>();

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

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

                    string dsDetalhe = null;
                    try
                    {
                        dsDetalhe = vd.dsDetalhe;
                        dsDetalhe = dsDetalhe.Trim();
                    }
                    catch { }

                    if (cdSacado != null)
                    {
                        if (cdSacado.Equals(""))
                        {
                            cdSacado = null;
                        }
                        else if (cdSacado.Length > 10)
                        {
                            throw new Exception("Sacado '" + cdSacado + "' com mais de 10 caracteres!");
                        }
                    }

                    string nrCNPJ = vd.nrCNPJ;
                    //if (nrCNPJ.Equals("08297710000480"))
                    //    nrCNPJ += "";

                    tbRecebimentoVenda tbRecebimentoVenda = new tbRecebimentoVenda
                    {
                        dsBandeira = dsBandeira,
                        //cdAdquirente = vd.cdAdquirente,
                        cdERP      = vd.cdERP,
                        dtVenda    = vd.dtVenda,
                        nrCNPJ     = nrCNPJ,
                        nrNSU      = vd.nrNSU != null && !vd.nrNSU.ToString().Trim().Equals("") ? vd.nrNSU : "T" + vd.cdERP,
                        vlVenda    = Convert.ToDecimal(vd.vlVenda),
                        cdSacado   = cdSacado,
                        qtParcelas = Convert.ToByte(vd.qtParcelas),
                        dsDetalhe  = dsDetalhe,
                    };

                    tbRecebimentoVenda venda = _db.Database.SqlQuery <tbRecebimentoVenda>("SELECT V.*" +
                                                                                          " FROM card.tbRecebimentoVenda V (NOLOCK)" +
                                                                                          " WHERE V.nrCNPJ = '" + tbRecebimentoVenda.nrCNPJ + "'" +
                                                                                          " AND V.nrNSU = '" + tbRecebimentoVenda.nrNSU + "'" +
                                                                                          " AND V.dtVenda = '" + DataBaseQueries.GetDate(tbRecebimentoVenda.dtVenda) + "'" +
                                                                                          " AND V.cdERP = '" + tbRecebimentoVenda.cdERP + "'"
                                                                                          )
                                               .FirstOrDefault();

                    int idRecebimentoVenda = 0;
                    if (venda == null)
                    {
                        _db.Database.ExecuteSqlCommand("INSERT INTO card.tbRecebimentoVenda" +
                                                       " (nrCNPJ, nrNSU, cdERP, dtVenda, dsBandeira, vlVenda, qtParcelas, cdSacado, dsDetalhe)" +
                                                       " VALUES ('" + tbRecebimentoVenda.nrCNPJ + "'" +
                                                       ", '" + tbRecebimentoVenda.nrNSU + "'" +
                                                       ", '" + tbRecebimentoVenda.cdERP + "'" +
                                                       ", '" + DataBaseQueries.GetDate(tbRecebimentoVenda.dtVenda) + "'" +
                                                       //", " + tbRecebimentoVenda.cdAdquirente +
                                                       ", " + (tbRecebimentoVenda.dsBandeira == null ? "NULL" : "'" + tbRecebimentoVenda.dsBandeira + "'") +
                                                       ", " + tbRecebimentoVenda.vlVenda.ToString(CultureInfo.GetCultureInfo("en-GB")) +
                                                       ", " + tbRecebimentoVenda.qtParcelas +
                                                       ", " + (tbRecebimentoVenda.cdSacado != null ? "'" + tbRecebimentoVenda.cdSacado + "'" : "NULL") +
                                                       ", " + (tbRecebimentoVenda.dsDetalhe != null ? "'" + tbRecebimentoVenda.dsDetalhe + "'" : "NULL") +
                                                       ")");
                        _db.SaveChanges();
                        transaction.Commit();

                        // Obtém o id da venda
                        idRecebimentoVenda = _db.Database.SqlQuery <int>("SELECT V.idRecebimentoVenda" +
                                                                         " FROM card.tbRecebimentoVenda V (NOLOCK)" +
                                                                         " WHERE V.nrCNPJ = '" + tbRecebimentoVenda.nrCNPJ + "'" +
                                                                         " AND V.nrNSU = '" + tbRecebimentoVenda.nrNSU + "'" +
                                                                         " AND V.dtVenda = '" + DataBaseQueries.GetDate(tbRecebimentoVenda.dtVenda) + "'" +
                                                                         " AND V.cdERP = '" + tbRecebimentoVenda.cdERP + "'"
                                                                         )
                                             .FirstOrDefault();
                    }
                    else
                    {
                        _db.Database.ExecuteSqlCommand("UPDATE V" +
                                                       " SET V.dsBandeira = " + (tbRecebimentoVenda.dsBandeira == null ? "NULL" : "'" + tbRecebimentoVenda.dsBandeira + "'") +
                                                       //", V.nrNSU = '" + tbRecebimentoVenda.nrNSU + "'" +
                                                       ", V.vlVenda = " + tbRecebimentoVenda.vlVenda.ToString(CultureInfo.GetCultureInfo("en-GB")) +
                                                       ", V.qtParcelas = " + tbRecebimentoVenda.qtParcelas +
                                                       ", V.cdSacado = " + (tbRecebimentoVenda.cdSacado != null ? "'" + tbRecebimentoVenda.cdSacado + "'" : "NULL") +
                                                       ", V.dsDetalhe = " + (tbRecebimentoVenda.dsDetalhe != null ? "'" + tbRecebimentoVenda.dsDetalhe + "'" : "NULL") +
                                                       ", V.dsMensagem = NULL" +
                                                       ", V.dtAjuste = NULL" +
                                                       " FROM card.tbRecebimentoVenda V" +
                                                       " WHERE V.idRecebimentoVenda = " + venda.idRecebimentoVenda);
                        _db.SaveChanges();
                        transaction.Commit();

                        idRecebimentoVenda = venda.idRecebimentoVenda;
                    }

                    // Adiciona
                    //if (!idsRecebimentoVenda.Contains(idRecebimentoVenda))
                    idsRecebimentoVenda.Add(idRecebimentoVenda);
                }
                catch (Exception e)
                {
                    transaction.Rollback();
                    string json = JsonConvert.SerializeObject(vd);
                    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("Venda: " + json + ". Erro: " + erro);
                    // Reporta o erro
                    retorno.Totais = new Dictionary <string, object>();
                    retorno.Totais.Add("erro", "Venda: " + json + ". Erro: " + erro);
                    break;
                }
            }


            // Avalia vendas que não foram atualizadas
            if (idsRecebimentoVenda.Count > 0 && param != null)
            {
                idsRecebimentoVenda = idsRecebimentoVenda.Distinct().ToList();
                string dtVenda = param.data.Substring(0, 4) + "-" + param.data.Substring(4, 2) + "-" + param.data.Substring(6, 2);
                string script  = "SELECT V.idRecebimentoVenda" +
                                 " FROM card.tbRecebimentoVenda V (NOLOCK)" +
                                 " JOIN cliente.empresa E (NOLOCK) ON E.nu_cnpj = V.nrCNPJ" +
                                 " WHERE V.dtVenda BETWEEN '" + dtVenda + "' AND '" + dtVenda + " 23:59:00'" +
                                 " AND " + (param.nrCNPJ == null ? "E.id_grupo = " + idGrupo : "V.nrCNPJ = '" + param.nrCNPJ + "'") +
                                 " AND V.idRecebimentoVenda NOT IN (" + string.Join(", ", idsRecebimentoVenda) + ")";
                int[] vendasASeremDeletadas = new int[0];
                try
                {
                    vendasASeremDeletadas = _db.Database.SqlQuery <int>(script).ToArray();
                }
                catch { }

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

            semaforo.Release();
        }
Esempio n. 3
0
        // GET "vendas/consultavendas"
        public static void ImportaVendas(string token, ImportaVendas 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 das vendas!");
                    }

                    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 = carregaVendas(_db, token, grupo_empresa.dsAPI, param.data, param.nrCNPJ);

                    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 vendas 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();
                }
            }
        }