// PUT /grupo_empresa/token/ public HttpResponseMessage Put(string token, [FromBody] grupo_empresa 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), "Put", _db); HttpResponseMessage retorno = new HttpResponseMessage(); if (Permissoes.Autenticado(token, _db)) { GatewayGrupoEmpresa.Update(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) { log.codResposta = (int)HttpStatusCode.InternalServerError; log.msgErro = e.Message; Bibliotecas.LogAcaoUsuario.Save(log); throw new HttpResponseException(HttpStatusCode.InternalServerError); } } }
/// <summary> /// Adiciona nova Grupo_empresa /// </summary> /// <param name="param"></param> /// <returns></returns> public static Int32 Add(string token, grupo_empresa param, painel_taxservices_dbContext _dbContext = null) { painel_taxservices_dbContext _db; if (_dbContext == null) { _db = new painel_taxservices_dbContext(); } else { _db = _dbContext; } //DbContextTransaction transaction = _db.Database.BeginTransaction(); // tudo ou nada try { param.id_grupo = -1; param.dt_cadastro = DateTime.Now; param.token = "null"; param.fl_ativo = true; // Verificar se usuário logado é de perfil comercial if (Permissoes.isAtosRoleVendedor(token, _db))//Permissoes.isAtosRole(token) && Permissoes.GetRoleName(token).ToUpper().Equals("COMERCIAL")) // Perfil Comercial tem uma carteira de clientes específica { param.id_vendedor = Permissoes.GetIdUser(token, _db); } _db.grupo_empresa.Add(param); _db.SaveChanges(); //transaction.Commit(); return(param.id_grupo); } catch (Exception e) { //transaction.Rollback(); if (e is DbEntityValidationException) { string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e); throw new Exception(erro.Equals("") ? "Falha ao salvar grupo empresa" : 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 conexão _db.Database.Connection.Close(); _db.Dispose(); } } }
/// <summary> /// Altera webpages_Users /// </summary> /// <param name="param"></param> /// <returns></returns> public static void Update(string token, Models.Object.Usuario param, painel_taxservices_dbContext _dbContext = null) { painel_taxservices_dbContext _db; if (_dbContext == null) { _db = new painel_taxservices_dbContext(); } else { _db = _dbContext; } try { if (param.Id_grupo != 0) { // Altera grupo empresa do usuário logado Int32 IdUser = Permissoes.GetIdUser(token); webpages_Users value = _db.webpages_Users .Where(e => e.id_users == IdUser) .FirstOrDefault <webpages_Users>(); if (value != null) { // VALIDAR PERMISSÂO PARA FUNCIONALIDADE if (param.Id_grupo == -1) { value.id_grupo = null; } else { value.id_grupo = param.Id_grupo; } value.nu_cnpjEmpresa = null; _db.SaveChanges(); } else { throw new Exception("Usuário inválido!"); } } else { if (param.Webpagesusers.id_users == 0) { throw new Exception("Falha ao parâmetro"); } // Altera um usuário que não necessiariamente é o logado webpages_Users value = _db.webpages_Users .Where(e => e.id_users == param.Webpagesusers.id_users) .First <webpages_Users>(); if (value != null) { if (param.Pessoa != null) { param.Pessoa.id_pesssoa = (int)value.id_pessoa; GatewayPessoa.Update(token, param.Pessoa); } if (param.Webpagesusersinroles != null) { foreach (webpages_UsersInRoles item in param.Webpagesusersinroles) { if (item.UserId == -1) { item.UserId = param.Webpagesusers.id_users; GatewayWebpagesUsersInRoles.Delete(token, item); } else { item.UserId = param.Webpagesusers.id_users; webpages_UsersInRoles verificacao = _db.webpages_UsersInRoles.Where(p => p.UserId == item.UserId).Where(p => p.RoleId == item.RoleId).FirstOrDefault(); if (verificacao != null) { webpages_UsersInRoles principal = _db.webpages_UsersInRoles .Where(p => p.UserId == item.UserId) .Where(p => p.RolePrincipal == true).FirstOrDefault(); if (principal != null) { principal.RolePrincipal = false; } verificacao.RolePrincipal = item.RolePrincipal; _db.SaveChanges(); } else { GatewayWebpagesUsersInRoles.Add(token, item); } } } } // Associa grupos empresas ao vendedor if (param.Addidsgrupoempresavendedor != null) { foreach (var idGrupo in param.Addidsgrupoempresavendedor) { grupo_empresa grupo = _db.grupo_empresa.Where(g => g.id_grupo == idGrupo).FirstOrDefault(); if (grupo != null) { grupo.id_vendedor = param.Webpagesusers.id_users; _db.SaveChanges(); } } } // Desassocia grupos empresas if (param.Removeidsgrupoempresavendedor != null) { foreach (var idGrupo in param.Removeidsgrupoempresavendedor) { grupo_empresa grupo = _db.grupo_empresa.Where(g => g.id_grupo == idGrupo).FirstOrDefault(); if (grupo != null) { grupo.id_vendedor = null; _db.SaveChanges(); } } } if (param.Webpagesusers.ds_login != null && param.Webpagesusers.ds_login != value.ds_login) { webpages_Users old = _db.webpages_Users.Where(e => e.ds_login.ToLower().Equals(param.Webpagesusers.ds_login.ToLower())) .FirstOrDefault(); if (old == null || old.id_users == value.id_users) { value.ds_login = param.Webpagesusers.ds_login; } } if (param.Webpagesusers.ds_email != null && param.Webpagesusers.ds_email != value.ds_email) { webpages_Users old = _db.webpages_Users.Where(e => e.ds_email.ToLower().Equals(param.Webpagesusers.ds_email.ToLower())) .FirstOrDefault(); if (old == null || old.id_users == value.id_users) { value.ds_email = param.Webpagesusers.ds_email; } } if (param.Webpagesusers.fl_ativo != value.fl_ativo) { value.fl_ativo = param.Webpagesusers.fl_ativo; } Boolean grupoEmpresaAlterado = false; if (param.Webpagesusers.nu_cnpjEmpresa != null && param.Webpagesusers.nu_cnpjEmpresa != value.nu_cnpjEmpresa) { if (param.Webpagesusers.nu_cnpjEmpresa == "") { value.nu_cnpjEmpresa = null; } else { value.nu_cnpjEmpresa = param.Webpagesusers.nu_cnpjEmpresa; value.id_grupo = _db.empresas.Where(f => f.nu_cnpj.Equals(param.Webpagesusers.nu_cnpjEmpresa)).Select(f => f.id_grupo).FirstOrDefault(); grupoEmpresaAlterado = true; // já forçou o grupo pela filial } }// só pode colocar grupo empresa ao qual a filial está ou sem nenhuma filial if (!grupoEmpresaAlterado && param.Webpagesusers.id_grupo != null && param.Webpagesusers.id_grupo != 0 && param.Webpagesusers.id_grupo != value.id_grupo) { if (param.Webpagesusers.id_grupo == -1) { value.id_grupo = null; value.nu_cnpjEmpresa = null; // Não pode estar associado a uma filial sem estar associado a um grupo } else { value.id_grupo = param.Webpagesusers.id_grupo; // Avalia se tem empresa associado => A filial TEM QUE SER associada ao grupo if (value.nu_cnpjEmpresa != null) { Int32 id_grupo = _db.empresas.Where(f => f.nu_cnpj.Equals(value.nu_cnpjEmpresa)).Select(f => f.id_grupo).FirstOrDefault(); if (id_grupo != value.id_grupo) { value.nu_cnpjEmpresa = null; // filial que estava associado é de um grupo diferente do grupo recém associado } } } } _db.SaveChanges(); } else { throw new Exception("Usuário não cadastrado"); } } } catch (Exception e) { if (e is DbEntityValidationException) { string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e); throw new Exception(erro.Equals("") ? "Falha ao alterar usuário" : 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 conexão _db.Database.Connection.Close(); _db.Dispose(); } } }
/// <summary> /// Adiciona nova Webpages_Users /// </summary> /// <param name="param"></param> /// <returns></returns> public static Int32 Add(string token, Models.Object.Usuario param, painel_taxservices_dbContext _dbContext = null) { painel_taxservices_dbContext _db; if (_dbContext == null) { _db = new painel_taxservices_dbContext(); } else { _db = _dbContext; } DbContextTransaction transaction = _db.Database.BeginTransaction(); try { // Adiciona os dados da pessoa param.Pessoa.id_pesssoa = GatewayPessoa.Add(token, param.Pessoa, _db); //_db.pessoas.Add(param.Pessoa); //_db.SaveChanges(); // Cria a conta com o login informado e a senha padrão "atos123" //WebSecurity.CreateAccount(param.Webpagesusers.ds_login, "atos123", false); WebSecurity.CreateUserAndAccount(param.Webpagesusers.ds_login, "atos123", propertyValues: new { ds_email = param.Webpagesusers.ds_email, fl_ativo = true }, requireConfirmationToken: false); param.Webpagesusers.id_users = WebSecurity.GetUserId(param.Webpagesusers.ds_login); // Cria o usuário webpages_Users usr = _db.webpages_Users.Find(param.Webpagesusers.id_users); //usr.ds_email = param.Webpagesusers.ds_email; usr.id_grupo = param.Webpagesusers.id_grupo; usr.nu_cnpjBaseEmpresa = param.Webpagesusers.nu_cnpjBaseEmpresa; usr.nu_cnpjEmpresa = param.Webpagesusers.nu_cnpjEmpresa; usr.id_pessoa = param.Pessoa.id_pesssoa; //usr.fl_ativo = true; _db.SaveChanges(); transaction.Commit(); foreach (var item in param.Webpagesusersinroles) { if (item.UserId == 0) { item.UserId = param.Webpagesusers.id_users; _db.webpages_UsersInRoles.Add(item); try { _db.SaveChanges(); } catch { } } } // Associa grupos empresas ao vendedor if (param.Addidsgrupoempresavendedor != null) { foreach (var idGrupo in param.Addidsgrupoempresavendedor) { grupo_empresa grupo = _db.grupo_empresa.Where(g => g.id_grupo == idGrupo).FirstOrDefault(); if (grupo != null) { grupo.id_vendedor = param.Webpagesusers.id_users; try { _db.SaveChanges(); } catch { // não é porque não associou algum grupo ao vendedor que deve retornar erro por completo } } } } return(param.Webpagesusers.id_users); } catch (Exception e) { transaction.Rollback(); if (e is DbEntityValidationException) { string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e); throw new Exception(erro.Equals("") ? "Falha ao salvar usuário" : 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 conexão _db.Database.Connection.Close(); _db.Dispose(); } } }
// GET "titulos/baixaautomatica" public static Retorno Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0, Dictionary <string, string> queryString = null, painel_taxservices_dbContext _dbContext = null) { painel_taxservices_dbContext _db; if (_dbContext == null) { _db = new painel_taxservices_dbContext(); } else { _db = _dbContext; } try { //DECLARAÇÕES Retorno retorno = new Retorno(); string outValue = null; // ID EXTRATO Int32 idExtrato = -1; if (!queryString.TryGetValue("" + (int)CAMPOS.IDEXTRATO, out outValue)) { throw new Exception("O identificador da movimentação bancária deve ser informada para a baixa automática!"); } idExtrato = Convert.ToInt32(queryString["" + (int)CAMPOS.IDEXTRATO]); int?cdGrupo = _db.Database.SqlQuery <int>("SELECT C.cdGrupo" + " FROM card.tbExtrato E (NOLOCK)" + " JOIN card.tbContaCorrente C (NOLOCK) ON C.cdContaCorrente = E.cdContaCorrente" + " WHERE E.idExtrato = " + idExtrato) .FirstOrDefault(); if (cdGrupo == null) { throw new Exception("Extrato inexistente!"); } // GRUPO EMPRESA => OBRIGATÓRIO! Int32 IdGrupo = Permissoes.GetIdGrupo(token, _db); if (IdGrupo == 0 && queryString.TryGetValue("" + (int)CAMPOS.ID_GRUPO, out outValue)) { IdGrupo = Convert.ToInt32(queryString["" + (int)CAMPOS.ID_GRUPO]); } if (IdGrupo == 0) { throw new Exception("Um grupo deve ser selecionado como para a baixa automática!"); } if (cdGrupo.Value != IdGrupo) { throw new Exception("Permissão negada! Movimentação bancária informada não se refere ao grupo associado ao usuário."); } 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"); } #region AVALIA SE POSSUI ALGUM TÍTULO CONCILIADO COM MAIS DE UM RECEBÍVEL List <int> idsRecebimentoTitulo = _db.Database.SqlQuery <int>("SELECT P.idRecebimentoTitulo" + " FROM pos.RecebimentoParcela P (NOLOCK)" + " WHERE P.idRecebimentoTitulo IS NOT NULL" + " AND P.idRecebimentoTitulo IN" + " (SELECT P.idRecebimentoTitulo" + " FROM pos.RecebimentoParcela P (NOLOCK)" + " WHERE P.idExtrato = " + idExtrato + " )" + " GROUP BY P.idRecebimentoTitulo" + " HAVING COUNT(*) > 1") .ToList(); if (idsRecebimentoTitulo.Count > 0) { SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["painel_taxservices_dbContext"].ConnectionString); try { connection.Open(); } catch { throw new Exception("Não foi possível estabelecer conexão com a base de dados"); } try { string error = "Há " + idsRecebimentoTitulo.Count + (idsRecebimentoTitulo.Count == 1 ? " título que está conciliado" : " títulos que estão conciliados") + " com mais de um recebível! Essa relação deve ser de um para um." + Environment.NewLine + (idsRecebimentoTitulo.Count == 1 ? " Segue o título e as correspondentes parcelas conciliadas com ele:" : " Seguem os títulos e as correspondentes parcelas conciliadas com cada um deles") + Environment.NewLine; // Reporta os títulos e as parcelas.... foreach (int idRecebimentoTitulo in idsRecebimentoTitulo) { // Obtém as informações da base string script = "SELECT R.dtaVenda AS P_dtVenda" + ", R.nsu AS P_nsu" + ", R.valorVendaBruta AS P_vlVenda" + ", P_filial = UPPER(ER.ds_fantasia + CASE WHEN ER.filial IS NULL THEN '' ELSE ' ' + ER.filial END)" + ", B.dsBandeira AS P_dsBandeira" + ", AAR.nmAdquirente AS P_nmAdquirente" + ", R.numParcelaTotal AS P_qtParcelas" + ", P.numParcela AS P_nrParcela" + ", P.dtaRecebimento AS P_dtRecebimentoPrevisto" + ", P.dtaRecebimentoEfetivo AS P_dtRecebimentoEfetivo" + ", P.flAntecipado AS P_flAntecipado" + ", P.valorParcelaBruta AS P_vlParcela" + ", T.dtVenda AS T_dtVenda" + ", T.nrNSU AS T_nsu" + ", T.vlVenda AS T_vlVenda" + ", T_filial = UPPER(ET.ds_fantasia + CASE WHEN ET.filial IS NULL THEN '' ELSE ' ' + ET.filial END)" + ", T.dsBandeira AS T_dsBandeira" + //", AAT.nmAdquirente AS T_nmAdquirente" + ", T_nmAdquirente = (SELECT TOP 1 UPPER(nmAdquirente) FROM card.tbAdquirente (NOLOCK) WHERE cdAdquirente = CASE WHEN T.cdAdquirente IS NOT NULL THEN T.cdAdquirente ELSE T.cdAdquirenteNew END)" + ", T.qtParcelas AS T_qtParcelas" + ", T.nrParcela AS T_nrParcela" + ", T.dtTitulo AS T_dtRecebimentoPrevisto" + ", T.vlParcela AS T_vlParcela" + " FROM pos.RecebimentoParcela P (NOLOCK)" + " JOIN pos.Recebimento R (NOLOCK) ON R.id = P.idRecebimento" + " JOIN cliente.empresa ER (NOLOCK) ON ER.nu_cnpj = R.cnpj" + " JOIN card.tbBandeira B (NOLOCK) ON B.cdBandeira = R.cdBandeira" + " JOIN card.tbAdquirente AAR (NOLOCK) ON AAR.cdAdquirente = B.cdAdquirente" + " JOIN card.tbRecebimentoTitulo T (NOLOCK) ON T.idRecebimentoTitulo = P.idRecebimentoTitulo" + " JOIN cliente.empresa ET (NOLOCK) ON ET.nu_cnpj = T.nrCNPJ" + //" JOIN card.tbAdquirente AAT (NOLOCK) ON AAT.cdAdquirente = T.cdAdquirente" + " WHERE P.idRecebimentoTitulo = " + idRecebimentoTitulo; List <IDataRecord> resultado = DataBaseQueries.SqlQuery(script, connection); error += Environment.NewLine + "==========TÍTULO========="; if (resultado == null || resultado.Count == 0) { error += Environment.NewLine + " " + idRecebimentoTitulo; } else { IDataRecord t = resultado[0]; DateTime?T_dtVenda = t["T_dtVenda"].Equals(DBNull.Value) ? (DateTime?)null : (DateTime)t["T_dtVenda"]; string T_nsu = Convert.ToString(t["T_nsu"]); decimal? T_vlVenda = t["T_vlVenda"].Equals(DBNull.Value) ? (decimal?)null : Convert.ToDecimal(t["T_vlVenda"]); string T_filial = Convert.ToString(t["T_filial"]); string T_bandeira = Convert.ToString(t["T_dsBandeira"].Equals(DBNull.Value) ? "" : t["T_dsBandeira"]); string T_adquirente = Convert.ToString(t["T_nmAdquirente"].Equals(DBNull.Value) ? "" : t["T_nmAdquirente"]); byte T_qtParcelas = Convert.ToByte(t["T_qtParcelas"].Equals(DBNull.Value) ? 0 : t["T_qtParcelas"]); byte T_nrParcela = Convert.ToByte(t["T_nrParcela"]); DateTime T_dtTitulo = (DateTime)t["T_dtRecebimentoPrevisto"]; Decimal T_vlParcela = Convert.ToDecimal(t["T_vlParcela"]); error += Environment.NewLine + "Adquirente: " + T_adquirente; error += Environment.NewLine + "Bandeira: " + T_bandeira; error += Environment.NewLine + "Filial: " + T_filial; if (T_dtVenda != null) { error += Environment.NewLine + "Venda em " + T_dtVenda.Value.ToShortDateString(); if (T_vlVenda != null) { error += Environment.NewLine + " no valor de " + T_vlVenda.Value.ToString("C"); } } else if (T_vlVenda != null) { error += Environment.NewLine + "Valor da venda: " + T_vlVenda.Value.ToString("C"); } error += Environment.NewLine + "NSU: " + T_nsu; error += Environment.NewLine + "Parcela " + T_nrParcela + (T_qtParcelas > 0 ? " de " + T_qtParcelas : ""); error += Environment.NewLine + "Dt Prevista Recebimento: " + T_dtTitulo; error += Environment.NewLine + "Valor Bruto: " + T_vlParcela.ToString("C"); error += Environment.NewLine; foreach (IDataRecord r in resultado) { DateTime P_dtVenda = (DateTime)r["P_dtVenda"]; string P_nsu = Convert.ToString(r["P_nsu"]); decimal P_vlVenda = Convert.ToDecimal(r["P_vlVenda"]); string P_filial = Convert.ToString(r["P_filial"]); string P_bandeira = Convert.ToString(r["P_dsBandeira"]); string P_adquirente = Convert.ToString(r["P_nmAdquirente"]); int P_qtParcelas = Convert.ToInt32(r["P_qtParcelas"].Equals(DBNull.Value) ? 0 : r["P_qtParcelas"]); int P_nrParcela = Convert.ToInt32(r["P_nrParcela"]); DateTime P_dtRecebimentoPrevisto = (DateTime)r["P_dtRecebimentoPrevisto"]; DateTime?P_dtRecebimentoEfetivo = r["P_dtRecebimentoEfetivo"].Equals(DBNull.Value) ? (DateTime?)null : (DateTime)r["P_dtRecebimentoEfetivo"]; bool P_flAntecipado = Convert.ToBoolean(r["P_flAntecipado"]); Decimal P_vlParcela = Convert.ToDecimal(r["P_vlParcela"]); error += Environment.NewLine + "=> RECEBÍVEL"; error += Environment.NewLine + " Adquirente: " + P_adquirente; error += Environment.NewLine + " Bandeira: " + P_bandeira; error += Environment.NewLine + " Filial: " + P_filial; error += Environment.NewLine + " Venda em " + P_dtVenda.ToShortDateString() + " no valor de " + P_vlVenda.ToString("C"); error += Environment.NewLine + " NSU: " + P_nsu; error += Environment.NewLine + " Parcela " + (P_nrParcela == 0 ? 1 : P_nrParcela) + (P_qtParcelas > 0 ? " de " + P_qtParcelas : ""); error += Environment.NewLine + " Dt Prevista Recebimento: " + P_dtRecebimentoPrevisto; if (P_dtRecebimentoEfetivo != null && !P_dtRecebimentoEfetivo.Value.Equals(P_dtRecebimentoPrevisto)) { error += Environment.NewLine + " Dt Efetiva Recebimento: " + P_dtRecebimentoEfetivo.Value.ToShortDateString() + (P_flAntecipado ? " (ANTECIPAÇÃO)" : ""); } error += Environment.NewLine + " Valor Bruto: " + P_vlParcela.ToString("C"); error += Environment.NewLine; } } } throw new Exception(error); } catch (Exception e) { if (e is DbEntityValidationException) { string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e); throw new Exception(erro.Equals("") ? "Falha ao listar recebimento parcela" : erro); } throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message); } finally { try { connection.Close(); } catch { } } } #endregion string url = "http://" + grupo_empresa.dsAPI + DOMINIO; //string url = "http://localhost:60049/"; string complemento = "titulos/baixaautomatica/" + token + "?" + ("" + (int)CAMPOS.IDEXTRATO) + "=" + idExtrato; HttpClient client = new System.Net.Http.HttpClient(); client.BaseAddress = new Uri(url); client.Timeout = TimeSpan.FromMinutes(30); // 30 minutos de timeout client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); System.Net.Http.HttpResponseMessage response = client.GetAsync(complemento).Result; //se retornar com sucesso busca os dados if (response.IsSuccessStatusCode) { //Pegando os dados do Rest e armazenando na variável retorno retorno = response.Content.ReadAsAsync <Retorno>().Result; } else { string resp = String.Empty; try { resp = response.Content.ReadAsAsync <string>().Result; } catch { throw new Exception("Serviço indisponível no momento"); } if (resp != null && !resp.Trim().Equals("")) { throw new Exception(((int)response.StatusCode) + " - " + resp); } throw new Exception(((int)response.StatusCode) + ""); } return(retorno); } catch (Exception e) { if (e is DbEntityValidationException) { string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e); throw new Exception(erro.Equals("") ? "Falha ao realizar a baixa automática" : erro); } throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message); } }
// PUT "vendas/corrigevendaserp" // JSON : { idsRecebimento [int] } public static void CorrigeVenda(string token, CorrigeVendasErp 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) { throw new Exception("Nenhum recebimento foi informado!"); } //string outValue = null; string script = String.Empty; if (param.idsRecebimento == null || param.idsRecebimento.Count == 0) { if (param.data == null) { throw new Exception("O período deve ser informado!"); } // Obtém os recebíveis conciliados baseadas no filtro DateTime dtIni, dtFim; // Usa outros dados if (param.data.Contains("|")) { string[] dts = param.data.Split('|'); dtIni = DateTime.ParseExact(dts[0] + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture); dtFim = DateTime.ParseExact(dts[1] + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture); } else { dtIni = dtFim = DateTime.ParseExact(param.data + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture); } script = "SELECT R.id" + " FROM pos.Recebimento R (NOLOCK)" + " JOIN card.tbBandeira B (NOLOCK) ON B.cdBandeira = R.cdBandeira" + " JOIN cliente.empresa ER (NOLOCK) ON ER.nu_cnpj = R.cnpj" + " JOIN card.tbRecebimentoVenda V (NOLOCK) ON V.idRecebimentoVenda = R.idRecebimentoVenda" + //" LEFT JOIN card.tbBandeiraSacado BS on BS.cdGrupo = ER.id_grupo and BS.cdBandeira = R.cdBandeira" + " WHERE R.dtaVenda BETWEEN '" + DataBaseQueries.GetDate(dtIni) + "' AND '" + DataBaseQueries.GetDate(dtFim) + " 23:59:00'" + (param.nrCNPJ != null ? " AND R.cnpj = '" + param.nrCNPJ + "'" : "") + " AND V.dtAjuste IS NULL AND (" + " CONVERT(VARCHAR(10), R.dtaVenda, 120) <> V.dtVenda" + " OR (V.cdAdquirente IS NOT NULL AND R.cdSacado IS NOT NULL AND V.cdSacado IS NOT NULL AND V.cdSacado <> R.cdSacado)" + " OR (R.numParcelaTotal IS NOT NULL AND V.qtParcelas <> R.numParcelaTotal)" + " OR V.vlVenda <> R.valorVendaBruta" + " OR (B.cdAdquirente NOT IN (5, 6, 11, 14) AND SUBSTRING('000000000000' + CONVERT(VARCHAR(12), R.nsu), LEN(R.nsu) + 1, 12) <> SUBSTRING('000000000000' + CONVERT(VARCHAR(12), V.nrNSU), LEN(V.nrNSU) + 1, 12))" + ")"; // Obtém os recebíveis conciliados com divergência que respeitam o filtro param.idsRecebimento = _db.Database.SqlQuery <int>(script).ToList(); if (param.idsRecebimento == null || param.idsRecebimento.Count == 0) { throw new Exception("Não há vendas a serem corrigadas " + (dtIni.Equals(dtFim) ? " em " + dtIni.ToShortDateString() : " no período de " + dtIni.ToShortDateString() + " a " + dtFim.ToShortDateString()) + (param.nrCNPJ != null ? " para a empresa " + param.nrCNPJ : "") + "."); } } else { #region DESCOBRE AS VENDAS QUE PRECISAM SER CORRIGIDAS script = "SELECT R.id" + " FROM pos.Recebimento R (NOLOCK)" + " JOIN card.tbBandeira B (NOLOCK) ON B.cdBandeira = R.cdBandeira" + " JOIN cliente.empresa ER (NOLOCK) ON ER.nu_cnpj = R.cnpj" + " JOIN card.tbRecebimentoVenda V (NOLOCK) ON V.idRecebimentoVenda = R.idRecebimentoVenda" + //" LEFT JOIN card.tbBandeiraSacado BS on BS.cdGrupo = ER.id_grupo and BS.cdBandeira = R.cdBandeira" + " WHERE R.id IN (" + string.Join(", ", param.idsRecebimento) + ")" + " AND V.dtAjuste IS NULL AND (" + " CONVERT(VARCHAR(10), R.dtaVenda, 120) <> V.dtVenda" + " OR (V.cdAdquirente IS NOT NULL AND R.cdSacado IS NOT NULL AND V.cdSacado IS NOT NULL AND V.cdSacado <> R.cdSacado)" + " OR (R.numParcelaTotal IS NOT NULL AND V.qtParcelas <> R.numParcelaTotal)" + " OR V.vlVenda <> R.valorVendaBruta" + // POLICARD, GETNET, SODEXO e VALECARD não trazem NSU do sitef " OR (B.cdAdquirente NOT IN (5, 6, 11, 14) AND SUBSTRING('000000000000' + CONVERT(VARCHAR(12), R.nsu), LEN(R.nsu) + 1, 12) <> SUBSTRING('000000000000' + CONVERT(VARCHAR(12), V.nrNSU), LEN(V.nrNSU) + 1, 12))" + ")"; param.idsRecebimento = _db.Database.SqlQuery <int>(script).ToList(); #endregion if (param.idsRecebimento == null || param.idsRecebimento.Count == 0) { throw new Exception("Não há vendas a serem corrigadas!"); } } string idsRecebimento = string.Join(", ", param.idsRecebimento); int[] gruposRecebimentos = _db.Database.SqlQuery <int>("SELECT DISTINCT E.id_grupo" + " FROM pos.Recebimento R (NOLOCK)" + " JOIN cliente.empresa E (NOLOCK) ON E.nu_cnpj = R.cnpj" + " WHERE R.id IN (" + idsRecebimento + ")") .ToArray(); if (gruposRecebimentos == null || gruposRecebimentos.Length == 0) { throw new Exception(param.idsRecebimento.Count == 1 ? "Identificador de recebível inexistente!" : "Identificadores de recebíveis inexistentes!"); } //if (gruposRecebimentos.Length < param.idsRecebimento.Count) // throw new Exception("Há " + (param.idsRecebimento.Count - gruposRecebimentos.Length) + ((param.idsRecebimento.Count - gruposRecebimentos.Length) == 1 ? " identificador de recebível inexistente!" : " identificadores de recebíveis inexistentes!")); // GRUPO EMPRESA => OBRIGATÓRIO! Int32 IdGrupo = Permissoes.GetIdGrupo(token, _db); if (IdGrupo == 0) { throw new Exception("Um grupo deve ser selecionado como para a correção das vendas no ERP!"); } if (gruposRecebimentos.Any(t => t != IdGrupo)) { throw new Exception("Permissão negada! " + (gruposRecebimentos.Length == 1 ? "Recebível informado não se refere" : "Recebíveis informados não se referem") + " ao grupo associado ao usuário."); } 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"); } SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["painel_taxservices_dbContext"].ConnectionString); List <IDataRecord> resultado; //List<int> idsReceb = new List<int>(); try { connection.Open(); } catch { throw new Exception("Não foi possível estabelecer conexão com a base de dados"); } try { #region AVALIA SE POSSUI ALGUM VENDA CONCILIADO COM MAIS DE UM RECEBÍVEL List <int> idsRecebimentoVenda = _db.Database.SqlQuery <int>("SELECT R.idRecebimentoVenda" + " FROM pos.Recebimento R (NOLOCK)" + " WHERE R.idRecebimentoVenda IS NOT NULL" + " AND R.idRecebimentoVenda IN" + " (SELECT R.idRecebimentoVenda" + " FROM pos.Recebimento R (NOLOCK)" + " WHERE R.id IN (" + idsRecebimento + ")" + " )" + " GROUP BY R.idRecebimentoVenda" + " HAVING COUNT(*) > 1") .ToList(); if (idsRecebimentoVenda.Count > 0) { string error = "Há " + idsRecebimentoVenda.Count + (idsRecebimentoVenda.Count == 1 ? " venda que está conciliada" : " vendas que estão conciliadas") + " com mais de um recebível! Essa relação deve ser de um para um." + Environment.NewLine + (idsRecebimentoVenda.Count == 1 ? " Segue a venda e os correspondentes recebíveis conciliados com ele:" : " Seguem as vendas e os correspondentes recebíveis conciliados com cada uma delas") + Environment.NewLine; // Reporta os vendas e as parcelas.... foreach (int idRecebimentoVenda in idsRecebimentoVenda) { // Obtém as informações da base script = "SELECT R.dtaVenda AS R_dtVenda" + ", R.nsu AS R_nsu" + ", R.valorVendaBruta AS R_vlVenda" + ", R_filial = UPPER(ER.ds_fantasia + CASE WHEN ER.filial IS NULL THEN '' ELSE ' ' + ER.filial END)" + ", B.dsBandeira AS R_dsBandeira" + ", AAR.nmAdquirente AS R_nmAdquirente" + ", R.numParcelaTotal AS R_qtParcelas" + ", V.dtVenda AS V_dtVenda" + ", V.nrNSU AS V_nsu" + ", V.vlVenda AS V_vlVenda" + ", V_filial = UPPER(EV.ds_fantasia + CASE WHEN EV.filial IS NULL THEN '' ELSE ' ' + EV.filial END)" + ", V.dsBandeira AS V_dsBandeira" + ", AAV.nmAdquirente AS V_nmAdquirente" + ", V.qtParcelas AS V_qtParcelas" + " FROM pos.Recebimento R (NOLOCK)" + " JOIN cliente.empresa ER (NOLOCK) ON ER.nu_cnpj = R.cnpj" + " JOIN card.tbBandeira B (NOLOCK) ON B.cdBandeira = R.cdBandeira" + " JOIN card.tbAdquirente AAR (NOLOCK) ON AAR.cdAdquirente = B.cdAdquirente" + " JOIN card.tbRecebimentoVenda V (NOLOCK) ON V.idRecebimentoVenda = R.idRecebimentoVenda" + " JOIN cliente.empresa EV (NOLOCK) ON EV.nu_cnpj = V.nrCNPJ" + //" JOIN card.tbAdquirente AAV (NOLOCK) ON AAV.cdAdquirente = V.cdAdquirente" + " LEFT JOIN card.tbBandeiraSacado BS ON BS.cdSacado = V.cdSacado AND EV.id_grupo = BS.cdGrupo" + " JOIN card.tbBandeira BV ON BV.cdBandeira = BS.cdBandeira" + " JOIN card.tbAdquirente AAV ON AAV.cdAdquirente = BV.cdAdquirente" + " WHERE R.idRecebimentoVenda = " + idRecebimentoVenda; resultado = DataBaseQueries.SqlQuery(script, connection); error += Environment.NewLine + "==========VENDA========="; if (resultado == null || resultado.Count == 0) { error += Environment.NewLine + " " + idRecebimentoVenda; } else { IDataRecord v = resultado[0]; DateTime V_dtVenda = (DateTime)v["V_dtVenda"]; string V_nsu = Convert.ToString(v["V_nsu"]); decimal V_vlVenda = Convert.ToDecimal(v["V_vlVenda"]); string V_filial = Convert.ToString(v["V_filial"]); string V_bandeira = Convert.ToString(v["V_dsBandeira"].Equals(DBNull.Value) ? "" : v["V_dsBandeira"]); string V_adquirente = Convert.ToString(v["V_nmAdquirente"]); byte V_qtParcelas = Convert.ToByte(v["V_qtParcelas"].Equals(DBNull.Value) ? 0 : v["V_qtParcelas"]); error += Environment.NewLine + "Adquirente: " + V_adquirente; error += Environment.NewLine + "Bandeira: " + V_bandeira; error += Environment.NewLine + "Filial: " + V_filial; error += Environment.NewLine + "Venda em " + V_dtVenda.ToShortDateString() + " no valor de " + V_vlVenda.ToString("C"); error += Environment.NewLine + "NSU: " + V_nsu; error += Environment.NewLine + "Parcelas: " + V_qtParcelas; error += Environment.NewLine; foreach (IDataRecord r in resultado) { DateTime R_dtVenda = (DateTime)r["R_dtVenda"]; string R_nsu = Convert.ToString(r["R_nsu"]); decimal R_vlVenda = Convert.ToDecimal(r["R_vlVenda"]); string R_filial = Convert.ToString(r["R_filial"]); string R_bandeira = Convert.ToString(r["R_dsBandeira"]); string R_adquirente = Convert.ToString(r["R_nmAdquirente"]); int R_qtParcelas = Convert.ToInt32(r["R_qtParcelas"].Equals(DBNull.Value) ? 1 : r["R_qtParcelas"]); error += Environment.NewLine + "=> RECEBÍVEL"; error += Environment.NewLine + " Adquirente: " + R_adquirente; error += Environment.NewLine + " Bandeira: " + R_bandeira; error += Environment.NewLine + " Filial: " + R_filial; error += Environment.NewLine + " Venda em " + R_dtVenda.ToShortDateString() + " no valor de " + R_vlVenda.ToString("C"); error += Environment.NewLine + " NSU: " + R_nsu; error += Environment.NewLine + " Parcelas: " + R_qtParcelas; error += Environment.NewLine; } } } throw new Exception(error); } #endregion } catch (Exception e) { if (e is DbEntityValidationException) { string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e); throw new Exception(erro.Equals("") ? "Falha ao listar realizar a correção das vendas" : erro); } throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message); } finally { try { connection.Close(); } catch { } } if (param.idsRecebimento == null || param.idsRecebimento.Count == 0) { //if (idsReceb.Count == 0) throw new Exception("Não há nenhuma venda para ser corrigida!"); } string url = "http://" + grupo_empresa.dsAPI + DOMINIO; //string url = "http://localhost:50939"; string complemento = "vendas/corrigevendas/" + token; CorrigeVendaERP o = new CorrigeVendaERP(param.idsRecebimento);//idsReceb); HttpContent json = new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json"); HttpClient client = new System.Net.Http.HttpClient(); client.BaseAddress = new Uri(url); client.Timeout = TimeSpan.FromMinutes(5); // 5 minutos de timeout client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); System.Net.Http.HttpResponseMessage response = client.PutAsync(complemento, json).Result; //se não retornar com sucesso busca os dados if (!response.IsSuccessStatusCode) { string resp = String.Empty; try { resp = response.Content.ReadAsAsync <string>().Result; } catch { throw new Exception("Serviço indisponível no momento"); } if (resp != null && !resp.Trim().Equals("")) { throw new Exception(((int)response.StatusCode) + " - " + resp); } throw new Exception(((int)response.StatusCode) + ""); } // Avalia se alguma venda teve que inserir dados script = "SELECT V.*" + " FROM pos.Recebimento R (NOLOCK)" + " JOIN card.tbRecebimentoVenda V ON R.idRecebimentoVenda = V.idRecebimentoVenda" + " WHERE R.id IN (" + idsRecebimento + ")" + " AND V.dsMensagem IS NOT NULL"; try { tbRecebimentoVenda[] vendas = _db.Database.SqlQuery <tbRecebimentoVenda>(script).ToArray(); if (vendas.Length > 0) { string result = String.Empty; //foreach (tbRecebimentoVenda venda in vendas) //{ // result += "NSU: " + venda.nrNSU + Environment.NewLine + // (venda.cdSacado != null ? "Sacado : " + venda.cdSacado + Environment.NewLine : "") + // "Valor: " + venda.vlVenda.ToString("C") + Environment.NewLine + // "Parcelas: " + venda.qtParcelas + Environment.NewLine + // "Mensagem: '" + venda.dsMensagem + "'" + // Environment.NewLine + Environment.NewLine; //} //throw new Exception("Vendas corrigidas que precisam ser corrigidas manualmente no sistema do cliente: " + // Environment.NewLine + Environment.NewLine + result); if (vendas.Length == 1) { result = "Há 1 venda que precisa ser corrigida manualmente no sistema do cliente."; } else { result = "Há " + vendas.Length + " vendas que precisam ser corrigidas manualmente no sistema do cliente."; } result += Environment.NewLine + "Por favor, acesse a tela ADMINISTRATIVO > INTEGRAÇÃO ERP > VENDAS" + " e seleciono como filtro de TIPO a opção CORREÇÃO MANUAL " + " usando como filtro de data o mesmo período selecionado aqui na Conciliação de Vendas."; throw new Exception(result); } } catch (Exception e) { if (e.Message.StartsWith("Há") && e.Message.Contains("Por favor, acesse a tela ADMINISTRATIVO > INTEGRAÇÃO ERP > VENDAS")) { throw new Exception(e.Message); } throw new Exception("Falha de comunicação com o servidor"); } } catch (Exception e) { if (e is DbEntityValidationException) { string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e); throw new Exception(erro.Equals("") ? "Falha ao realizar a correção das vendas" : erro); } throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message); } }
/// <summary> /// Altera grupo_empresa /// </summary> /// <param name="param"></param> /// <returns></returns> public static void Update(string token, grupo_empresa param, painel_taxservices_dbContext _dbContext = null) { painel_taxservices_dbContext _db; if (_dbContext == null) { _db = new painel_taxservices_dbContext(); } else { _db = _dbContext; } //DbContextTransaction transaction = _db.Database.BeginTransaction(); // tudo ou nada try { grupo_empresa value = _db.grupo_empresa .Where(e => e.id_grupo.Equals(param.id_grupo)) .First <grupo_empresa>(); // OBSERVAÇÂO: VERIFICAR SE EXISTE ALTERAÇÃO NO PARAMETROS //if (param.id_grupo != null && param.id_grupo != value.id_grupo) // value.id_grupo = param.id_grupo; if (param.ds_nome != null && param.ds_nome != value.ds_nome) { value.ds_nome = param.ds_nome; } //if (param.token != null && param.token != value.token) // value.token = param.token; if (param.fl_ativo != value.fl_ativo) { value.fl_ativo = param.fl_ativo; } if (param.fl_cardservices != value.fl_cardservices) { value.fl_cardservices = param.fl_cardservices; } if (param.fl_taxservices != value.fl_taxservices) { value.fl_taxservices = param.fl_taxservices; } if (param.fl_proinfo != value.fl_proinfo) { value.fl_proinfo = param.fl_proinfo; } if (param.dsAPI != null && param.dsAPI != value.dsAPI) { value.dsAPI = param.dsAPI; } //if (param.cdPrioridade != value.cdPrioridade) // não faz alterações pela API! // value.cdPrioridade = param.cdPrioridade; _db.SaveChanges(); //transaction.Commit(); } catch (Exception e) { //transaction.Rollback(); if (e is DbEntityValidationException) { string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e); throw new Exception(erro.Equals("") ? "Falha ao alterar grupo empresa" : 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 conexão _db.Database.Connection.Close(); _db.Dispose(); } } }
// 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(); } } }
/// <summary> /// Retorna Títulos ERP /// </summary> /// <returns></returns> public static Retorno Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0, Dictionary <string, string> queryString = null, painel_taxservices_dbContext _dbContext = null) { painel_taxservices_dbContext _db; if (_dbContext == null) { _db = new painel_taxservices_dbContext(); } else { _db = _dbContext; } DbContextTransaction transaction = _db.Database.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted); try { //DECLARAÇÕES string outValue = null; // DATA string data = String.Empty; string tipoData = "R"; if (!queryString.TryGetValue("" + (int)CAMPOS.DATA, out outValue)) { throw new Exception("A data deve ser informada!"); } if (!queryString.TryGetValue("" + (int)CAMPOS.TIPODATA, out outValue)) { tipoData = queryString["" + (int)CAMPOS.TIPODATA]; if (!tipoData.Equals("V") && !tipoData.Equals("R")) { tipoData = "R"; // default } } data = queryString["" + (int)CAMPOS.DATA]; // GRUPO EMPRESA => OBRIGATÓRIO! Int32 IdGrupo = Permissoes.GetIdGrupo(token, _db); if (IdGrupo == 0 && queryString.TryGetValue("" + (int)CAMPOS.ID_GRUPO, out outValue)) { IdGrupo = Convert.ToInt32(queryString["" + (int)CAMPOS.ID_GRUPO]); } if (IdGrupo == 0) { throw new Exception("Um grupo deve ser selecionado como para a listagem 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"); } // Obtém os títulos Retorno retorno = carregaTitulos(_db, token, grupo_empresa.dsAPI, data, tipoData); // Obtém os registros List <dynamic> titulos = new List <dynamic>(); foreach (dynamic registro in retorno.Registros) { string nrCNPJ = registro.nrCNPJ; int? cdAdquirente = null; try { cdAdquirente = Convert.ToInt32(registro.cdAdquirente); } catch { } string cdSacado = null; try { cdSacado = registro.cdSacado; cdSacado = cdSacado.Trim(); } catch { } var adquirente = _db.tbAdquirentes.Where(a => a.cdAdquirente == (cdAdquirente != null ? cdAdquirente.Value : cdSacado == null ? (int?)null : _db.Database.SqlQuery <int?>("EXEC dbo.FN_cdAdquirente('" + nrCNPJ + "', '" + cdSacado + "')").FirstOrDefault())) .Select(r => new { r.cdAdquirente, r.nmAdquirente }); titulos.Add(new { empresa = _db.empresas.Where(f => f.nu_cnpj.Equals(nrCNPJ)).Select(f => new { f.nu_cnpj, f.ds_fantasia, f.filial }).FirstOrDefault(), nrNSU = registro.nrNSU, dtVenda = registro.dtVenda, tbAdquirente = adquirente, dsBandeira = registro.dsBandeira, vlVenda = registro.vlVenda, qtParcelas = registro.qtParcelas, dtTitulo = registro.dtTitulo, vlParcela = registro.vlParcela, nrParcela = registro.nrParcela, cdERP = registro.cdERP, dtBaixaERP = registro.dtBaixaERP, cdSacado = cdSacado, }); } // PAGINAÇÃO int skipRows = (pageNumber - 1) * pageSize; if (titulos.Count > pageSize && pageNumber > 0 && pageSize > 0) { titulos = titulos.OrderBy(r => r.empresa.ds_fantasia) .ThenBy(r => r.dtVenda) //.ThenBy(r => r.tbAdquirente.nmAdquirente) .ThenBy(r => r.dsBandeira) .ThenBy(r => r.dtTitulo) .Skip(skipRows).Take(pageSize) .ToList <dynamic>(); } else { pageNumber = 1; titulos = titulos.OrderBy(r => r.empresa.ds_fantasia) .ThenBy(r => r.dtVenda) //.ThenBy(r => r.tbAdquirente.nmAdquirente) .ThenBy(r => r.dsBandeira) .ThenBy(r => r.dtTitulo) .ToList <dynamic>(); } transaction.Commit(); retorno.PaginaAtual = pageNumber; retorno.ItensPorPagina = pageSize; retorno.Registros = titulos; return(retorno); } catch (Exception e) { transaction.Rollback(); if (e is DbEntityValidationException) { string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e); throw new Exception(erro.Equals("") ? "Falha ao listar 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(); } } }
/// <summary> /// Retorna Vendas ERP /// </summary> /// <returns></returns> public static Retorno Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0, Dictionary <string, string> queryString = null, painel_taxservices_dbContext _dbContext = null) { painel_taxservices_dbContext _db; if (_dbContext == null) { _db = new painel_taxservices_dbContext(); } else { _db = _dbContext; } DbContextTransaction transaction = _db.Database.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted); try { //DECLARAÇÕES string outValue = null; // DATA string data = String.Empty; if (!queryString.TryGetValue("" + (int)CAMPOS.DATA, out outValue)) { throw new Exception("A data deve ser informada!"); } data = queryString["" + (int)CAMPOS.DATA]; string nrCNPJ = null; if (queryString.TryGetValue("" + (int)CAMPOS.NRCNPJ, out outValue)) { nrCNPJ = queryString["" + (int)CAMPOS.NRCNPJ]; } // GRUPO EMPRESA => OBRIGATÓRIO! Int32 IdGrupo = Permissoes.GetIdGrupo(token, _db); if (IdGrupo == 0 && queryString.TryGetValue("" + (int)CAMPOS.ID_GRUPO, out outValue)) { IdGrupo = Convert.ToInt32(queryString["" + (int)CAMPOS.ID_GRUPO]); } if (IdGrupo == 0) { throw new Exception("Um grupo deve ser selecionado como para a listagem 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"); } // Obtém as vendas Retorno retorno = carregaVendas(_db, token, grupo_empresa.dsAPI, data, nrCNPJ); // Obtém os registros List <dynamic> vendas = new List <dynamic>(); foreach (dynamic registro in retorno.Registros) { nrCNPJ = registro.nrCNPJ; Int32 cdAdquirente = Convert.ToInt32(registro.cdAdquirente); var empresa = _db.empresas.Where(f => f.nu_cnpj.Equals(nrCNPJ)).Select(f => new { f.nu_cnpj, f.ds_fantasia, f.filial, f.id_grupo }).FirstOrDefault(); string cdSacado = null; try { cdSacado = registro.cdSacado; cdSacado = cdSacado.Trim(); } catch { } string dsDetalhe = null; try { dsDetalhe = registro.dsDetalhe; dsDetalhe = dsDetalhe.Trim(); } catch { } //string cdERPPagamento = null; //try //{ // cdERPPagamento = registro.cdERPPagamento; //} //catch { } vendas.Add(new { empresa = new { empresa.nu_cnpj, empresa.ds_fantasia, empresa.filial, }, nrNSU = registro.nrNSU, dtVenda = registro.dtVenda, //tbAdquirente = _db.tbAdquirentes.Where(a => a.cdAdquirente == cdAdquirente).Select(a => new //{ // a.cdAdquirente, // a.nmAdquirente //}).FirstOrDefault(), tbAdquirente = cdSacado == null ? null : _db.tbBandeiraSacados.Where(t => t.cdSacado.Equals(cdSacado) && t.cdGrupo == empresa.id_grupo) .Select(t => new { cdAdquirente = t.tbBandeira.cdAdquirente, nmAdquirente = t.tbBandeira.tbAdquirente.nmAdquirente }) .FirstOrDefault(), cdSacado = cdSacado, dsBandeira = registro.dsBandeira, vlVenda = registro.vlVenda, qtParcelas = registro.qtParcelas, cdERP = registro.cdERP, dsDetalhe = dsDetalhe, dtAjuste = registro.dtAjuste, }); } // PAGINAÇÃO int skipRows = (pageNumber - 1) * pageSize; if (vendas.Count > pageSize && pageNumber > 0 && pageSize > 0) { vendas = vendas.OrderBy(r => r.empresa.ds_fantasia) .ThenBy(r => r.dtVenda) //.ThenBy(r => r.tbAdquirente.nmAdquirente) .ThenBy(r => r.dsBandeira) .Skip(skipRows).Take(pageSize) .ToList <dynamic>(); } else { pageNumber = 1; vendas = vendas.OrderBy(r => r.empresa.ds_fantasia) .ThenBy(r => r.dtVenda) //.ThenBy(r => r.tbAdquirente.nmAdquirente) .ThenBy(r => r.dsBandeira) .ToList <dynamic>(); } transaction.Commit(); retorno.PaginaAtual = pageNumber; retorno.ItensPorPagina = pageSize; retorno.Registros = vendas; return(retorno); } catch (Exception e) { transaction.Rollback(); if (e is DbEntityValidationException) { string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e); throw new Exception(erro.Equals("") ? "Falha ao listar 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(); } } }