Beispiel #1
0
        public dynamic GetPreco([FromUri] int PRODUTO = 0, DateTime?DATA = null, string CEMP = "0", int CONDICAO_PAGAMENTO = 0, int COD_CLIENTE = 0)
        {
            string pdata = "01.01.2000";

            if (DATA != null)
            {
                pdata = DATA.Value.ToUniversalTime().ToShortDateString();
                pdata = pdata.Replace("/", ".");
            }

            double PAVI = 0;
            var    sql  = new FuncoesBanco(db);
            string x    = " SELECT PAVI, CLIENTE FROM SP_LISTA_PRECO (" + PRODUTO
                          + ", '" + pdata + "', '" + CEMP + "', " + CONDICAO_PAGAMENTO + ", " + COD_CLIENTE + ") ";

            List <dynamic> MyList = sql.CollectionFromSql(x,
                                                          new Dictionary <string, object> {
            }).ToList();

            foreach (dynamic item in MyList)
            {
                PAVI = item.PAVI;
                if (item.CLIENTE == "S")
                {
                    PAVI = item.PAVI;
                    break;
                }
            }

            return(PAVI);
        }
        public dynamic Localizar(int id)
        {
            funcdb         = new FuncoesBanco(dblocal);
            retorno.CODIGO = 0;
            retorno.id     = id;
            GetParamOperador();
            GetProximaLigacao();
            GetDadosLigacao(retorno.CODIGO);

            return(Json(retorno));
        }
        protected override IHttpActionResult ExecutarAntesPost(FAT_NF_SERVICO item)
        {
            string Generator = "FAT_NF_SERVICO_" + item.SERIE + "_" + item.CEMP;

            try
            {
                var fb = new FuncoesBanco(db);
                item.NUMERO = fb.BuscarPKRegistro(Generator);
                return(null);
            }
            catch
            {
                return(Content(HttpStatusCode.Accepted, new { mensagem_erro = "Problema com generator da tabela " + Generator }));
            }
        }
Beispiel #4
0
        protected override void BeforeSaveChanges(FAT_ROMANEIO_PAO item)
        {
            var itens = db.Set <FAT_ROMANEIO_PAO_ITEM>()
                        .Where(i => i.COD_FATROMANEIOPAO == item.id);

            foreach (FAT_ROMANEIO_PAO_ITEM i in itens)
            {
                db.Set <FAT_ROMANEIO_PAO_ITEM>().Remove(i);
            }

            if (item.Itens != null)
            {
                for (int i = 0; i < item.Itens.Count; i++)
                {
                    FAT_ROMANEIO_PAO_ITEM novo = new FAT_ROMANEIO_PAO_ITEM();

                    if (item.Itens[i].id == null)
                    {
                        var fb = new FuncoesBanco(new Context());
                        novo.id = fb.BuscarPKRegistro("FAT_ROMANEIO_PAO_ITEM");
                    }
                    else
                    {
                        novo.id = item.Itens[i].id;
                    }

                    novo.COD_FATROMANEIOPAO = item.id;
                    novo.COD_CADPRODUTO     = item.Itens[i].COD_CADPRODUTO;
                    novo.COD_CADUNIDADE     = item.Itens[i].COD_CADUNIDADE;

                    if (item.Itens[i].COD_FATOPERACAOSAIDA == null)
                    {
                        novo.COD_FATOPERACAOSAIDA = this.GetOperacao((int)item.Itens[i].COD_CADPRODUTO);
                    }
                    else
                    {
                        novo.COD_FATOPERACAOSAIDA = item.Itens[i].COD_FATOPERACAOSAIDA;
                    }

                    novo.ITEM             = item.Itens[i].ITEM;
                    novo.PRODUTO          = item.Itens[i].PRODUTO;
                    novo.QUANTIDADE       = item.Itens[i].QUANTIDADE;
                    novo.QUANTIDADE_TROCA = item.Itens[i].QUANTIDADE_TROCA;
                    novo.VALOR_UNITARIO   = item.Itens[i].VALOR_UNITARIO;
                    db.Set <FAT_ROMANEIO_PAO_ITEM>().Add(novo);
                }
            }
        }
        public IHttpActionResult ConfirmarPedido([FromUri] Pedido dados)
        {
            FuncoesBanco f  = new FuncoesBanco(dblocal);
            var          id = f.ExecSql("select id from SP_GRAVAR_PEDIDO_WEB(" + dados.id + ", " + dados.CodUsr
                                        + ", " + dados.Mesa + ", '" + dados.Total.ToString().Replace(",", ".") + "')");

            if (id != null && id.Count > 0)
            {
                dados.id = Convert.ToInt32(id[0]);
            }

            int ii = 0;

            if (dados.Produtos is string)
            {
                PRODUTO i = JsonConvert.DeserializeObject <PRODUTO>(dados.Produtos);
                f.ExecSql("select id from SP_GRAVAR_PEDIDO_ITEM_WEB(" + dados.id + ", " + dados.CodUsr
                          + ", " + dados.Mesa + ", '" + i.PRODN3VLRVENDA.ToString().Replace(",", ".")
                          + "', " + i.QTD.ToString()
                          + "," + ii
                          + ", " + i.id
                          + ")");
            }
            else
            {
                foreach (dynamic item in dados.Produtos)
                {
                    ii++;
                    PRODUTO i = JsonConvert.DeserializeObject <PRODUTO>(item);
                    f.ExecSql("select id from SP_GRAVAR_PEDIDO_ITEM_WEB(" + dados.id + ", " + dados.CodUsr
                              + ", " + dados.Mesa + ", '" + i.PRODN3VLRVENDA.ToString().Replace(",", ".")
                              + "', " + i.QTD.ToString()
                              + "," + ii
                              + ", " + i.id
                              + ")");
                }
            }

            retorno.id = dados.id;
            return(CreatedAtRoute("DefaultApi", new { id = retorno.id }, retorno));
            // return Ok(retorno);
        }
        public IHttpActionResult PedidoMesa([FromUri] Pedido mesa)
        {
            Pedido item = new Pedido();

            item.Mesa = mesa.id;
            item.id   = 0;

            FuncoesBanco f = new FuncoesBanco(dblocal);

            List <dynamic> dt = f.CollectionFromSql("select first(1) PRVDICOD, VENDICOD, PRVDN2TOTITENS, CLIENTEOBS from prevenda where mesaicod = "
                                                    + mesa.id + " order by PRVDICOD desc ",
                                                    new Dictionary <string, object> {
            }).ToList();

            foreach (dynamic d in dt)
            {
                item.id     = Convert.ToInt32(d.PRVDICOD);
                item.CodUsr = Convert.ToInt32(d.VENDICOD);
                item.Total  = Convert.ToDouble(d.PRVDN2TOTITENS);
                item.OBS    = d.CLIENTEOBS;

                List <dynamic> lista = f.CollectionFromSql(
                    "select a.PRODICOD,a.PVITN3QTD,a.PVITN3VLRUNIT, b.proda60descr, b.grupicod "
                    + " from prevendaitem a inner join produto b on b.prodicod = a.prodicod "
                    + " where a.PRVDICOD = " + item.id,
                    new Dictionary <string, object> {
                }).ToList();

                item.Produtos = lista;
            }

            if (item.id == 0)
            {
                item = null;
            }

            return(Ok(item));
        }
        private void GetValores(int id, DateTime?datainicial, DateTime?datafinal)
        {
            if (datainicial == null)
            {
                datainicial = DateTime.Now;
            }

            if (datafinal == null)
            {
                datafinal = DateTime.Now;
            }

            var x = " select (AVG(XX.PRODUTIVIDADE)) PRODUTIVIDADE, SUM(XX.DISCADAS) DISCADAS, "
                    + " SUM(XX.CONTATOS) CONTATOS,  AVG(XX.CONTATOS * 100 / XX.DISCADAS) APROVEITAMENTO, SUM(XX.PEDIDOS) PEDIDOS FROM "
                    + " (SELECT ((( (if ((select sum(time_to_sec(cr.LIGACAO_FINALIZADA) - time_to_sec(cr.LIGACAO_RECEBIDA)) "
                    + "          from chamadas_receptivo cr where cr.operador = o.codigo and DATE(cr.LIGACAO_RECEBIDA) between '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' "
                    + "        ) + ( "
                    + "          select(sum(time_to_sec(data_hora_fim) - time_to_sec(data_hora_lig))) as tempo_falando "
                    + "            from campanhas_clientes "
                    + "            where "
                    + "          OPERADOR_LIGACAO = o.codigo "
                    + "          and DATE(data_hora_lig)between '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' "
                    + "        ) "
                    + "        is null,if ( "
                    + "            (select sum(time_to_sec(cr.LIGACAO_FINALIZADA) - time_to_sec(cr.LIGACAO_RECEBIDA)) "
                    + "              from chamadas_receptivo cr "
                    + "             where cr.operador = o.codigo "
                    + "              and DATE(cr.LIGACAO_RECEBIDA)between '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' "
                    + "            ) is null,(select(sum(time_to_sec(data_hora_fim) - time_to_sec(data_hora_lig))) as tempo_falando "
                    + "            from campanhas_clientes where OPERADOR_LIGACAO = o.codigo "
                    + "          and DATE(data_hora_lig)between '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' "
                    + "        ),( "
                    + "              select sum(time_to_sec(cr.LIGACAO_FINALIZADA) - time_to_sec(cr.LIGACAO_RECEBIDA)) "
                    + "              from chamadas_receptivo cr "
                    + "              where cr.operador = o.codigo "
                    + "              and DATE(cr.LIGACAO_RECEBIDA)between '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' "
                    + "            )),( "
                    + "          select sum(time_to_sec(cr.LIGACAO_FINALIZADA) - time_to_sec(cr.LIGACAO_RECEBIDA)) "
                    + "          from chamadas_receptivo cr "
                    + "          where cr.operador = o.codigo "
                    + "          and DATE(cr.LIGACAO_RECEBIDA)between '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' "
                    + "        ) + ( "
                    + "          select(sum(time_to_sec(data_hora_fim) - time_to_sec(data_hora_lig))) as tempo_falando "
                    + "            from campanhas_clientes  where "
                    + "          OPERADOR_LIGACAO = o.codigo "
                    + "          and DATE(data_hora_lig)between '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "')))))*100)/ "
                    + "    (if (((select sum(time_to_sec(l.tempo_logado)) as tempo_logado from login_ativo_receptivo l "
                    + "      where "
                    + "        o.codigo = l.operador "
                    + "        and modulo = 'Ativo' "
                    + "        and DATE(entrada)between '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' "
                    + "    ) -(( "
                    + "      select sum(ligacoes_ok) "
                    + "      from login_ativo_receptivo l "
                    + "      where modulo ='Ativo' "
                    + "      and l.OPERADOR = o.codigo "
                    + "      and DATE(entrada)between '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' "
                    + "       ) *1)) is null,0,(( "
                    + "     select "
                    + "        sum(time_to_sec(l.tempo_logado)) as tempo_logado from login_ativo_receptivo l "
                    + "      where "
                    + "        o.codigo = l.operador "
                    + "        and modulo = 'Ativo' "
                    + "       and DATE(entrada)between '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' "
                    + "    ) -(( "
                    + "      select sum(ligacoes_ok) "
                    + "      from login_ativo_receptivo l "
                    + "      where modulo = 'Ativo' "
                    + "      and l.OPERADOR = o.codigo "
                    + "      and DATE(entrada)between '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' "
                    + "       ) *1))) + if ((select "
                    + "        sum(time_to_sec(l.tempo_logado)) as tempo_logado from login_ativo_receptivo l "
                    + "      where  o.codigo = l.operador "
                    + "        and modulo = 'Receptivo' "
                    + "        and DATE(entrada)between '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "')is null,0,(select "
                    + "        sum(time_to_sec(l.tempo_logado)) as tempo_logado from login_ativo_receptivo l "
                    + "      where  o.codigo = l.operador "
                    + "        and modulo = 'Receptivo' "
                    + "        and DATE(entrada)between '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "')) "
                    + "        - (SELECT IFNULL(SUM(TIME_TO_SEC(p.DATA_HORA_FIM) - TIME_TO_SEC(p.DATA_HORA)), 0) AS TEMPO_PAUSA FROM pausas_realizadas p inner join motivos_pausa mp on mp.CODIGO = p.COD_PAUSA and mp.PRODUTIVIDADE = 'SIM'  WHERE DATE(p.DATA_HORA)between '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' and p.OPERADOR = o.codigo)  "
                    + "        ) AS PRODUTIVIDADE, "
                    + " CAST(COUNT(distinct cc.CODIGO) AS CHAR) AS DISCADAS, "
                    + " CAST(SUM(IF(r.ECONTATO = 'SIM', 1, 0)) AS CHAR) AS CONTATOS, "
                    + "      CAST(SUM(IF(r.EPEDIDO = 'SIM', 1, 0)) AS CHAR) AS PEDIDOS FROM operadores o "
                    + "   LEFT JOIN campanhas_clientes cc ON (cc.OPERADOR_LIGACAO = o.CODIGO  AND cc.OPERADOR_LIGACAO > 0 "
                    + "   AND DATE(cc.DT_RESULTADO) BETWEEN '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "') "
                    + "  LEFT JOIN resultados r ON(r.CODIGO = cc.RESULTADO) "
                    + "  LEFT JOIN campanhas c ON(c.CODIGO = cc.CAMPANHA) "
                    + " WHERE o.CODIGO = " + id.ToString() + ") as XX ";

            FuncoesBanco   f      = new FuncoesBanco(dblocal);
            List <dynamic> MyList = f.CollectionFromSql(x,
                                                        new Dictionary <string, object> {
            }).ToList();

            foreach (dynamic item in MyList)
            {
                if (!DBNull.Equals(item.PRODUTIVIDADE, DBNull.Value))
                {
                    PRODUTIVIDADE = Convert.ToDouble(item.PRODUTIVIDADE);
                }
                else
                {
                    PRODUTIVIDADE = 0;
                }
                if (!DBNull.Equals(item.DISCADAS, DBNull.Value))
                {
                    DISCADAS = Convert.ToInt32(item.DISCADAS);
                }
                else
                {
                    DISCADAS = 0;
                }
                if (!DBNull.Equals(item.CONTATOS, DBNull.Value))
                {
                    CONTATOS = Convert.ToInt32(item.CONTATOS);
                }
                else
                {
                    CONTATOS = 0;
                }
                if (!DBNull.Equals(item.APROVEITAMENTO, DBNull.Value))
                {
                    APROVEITAMENTO = Convert.ToDouble(item.APROVEITAMENTO);
                }
                else
                {
                    APROVEITAMENTO = 0;
                }
                if (!DBNull.Equals(item.PEDIDOS, DBNull.Value))
                {
                    PEDIDOS = Convert.ToInt32(item.PEDIDOS);
                }
                else
                {
                    PEDIDOS = 0;
                }
            }

            x = "SELECT cli.ESTADO, SUM(cc.VALOR) as VALOR FROM compras cc "
                + " JOIN clientes cli on cli.CODIGO = cc.CLIENTE AND cli.ESTADO <> '' "
                + " WHERE cc.OPERADOR > 0 AND cc.DATA BETWEEN '" + String.Format("{0:yyyy-MM-dd}", datainicial)
                + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' "
                + " group by cli.ESTADO having SUM(cc.VALOR) > 0 ORDER BY COUNT(cc.CODIGO) DESC ";

            if (VendasPorEstado == null)
            {
                MyList = f.CollectionFromSql(x,
                                             new Dictionary <string, object> {
                }).ToList();

                VendasPorEstado = MyList;
            }

            x = "SELECT meta.OPERADOR,o.LOGIN, sum(meta.VALOR_META) as META "
                + " FROM operadores_meta meta JOIN operadores o on o.CODIGO = meta.OPERADOR WHERE CAST(CONCAT(meta.ANO, '-', meta.MES, '-01') AS DATE) BETWEEN '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' "
                + " group by meta.OPERADOR,o.LOGIN ";

            if (MetasXVendas == null)
            {
                MyList = f.CollectionFromSql(x,
                                             new Dictionary <string, object> {
                }).ToList();

                MetasXVendas = MyList;

                foreach (var m in MetasXVendas)
                {
                    x = "SELECT SUM(cc.VALOR) as VALOR FROM compras cc "
                        + " WHERE cc.OPERADOR = " + m.OPERADOR + " AND cc.DATA BETWEEN '" + String.Format("{0:yyyy-MM-dd}", datainicial)
                        + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' ";

                    var valor = f.ExecSql(x);

                    if (valor != null && valor.Count > 0)
                    {
                        m.VALOR_VENDA = Convert.ToDouble(valor[0]);
                    }
                    else
                    {
                        m.VALOR_VENDA = 0;
                    }

                    x = " select p.VALOR from campanhas_clientes a inner join propostas p on p.LIGACAO = a.CODIGO "
                        + " WHERE a.OPERADOR = " + m.OPERADOR + " AND a.DT_RESULTADO BETWEEN '" + String.Format("{0:yyyy-MM-dd}", datainicial)
                        + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' ";
                    valor = f.ExecSql(x);

                    if (valor != null && valor.Count > 0)
                    {
                        m.VALOR_PROPOSTA = Convert.ToDouble(valor[0]);
                    }
                    else
                    {
                        m.VALOR_PROPOSTA = 0;
                    }
                }
            }
        }
        private void GetValores(int id, DateTime?datainicial, DateTime?datafinal)
        {
            if (datainicial == null)
            {
                datainicial = DateTime.Now;
            }

            if (datafinal == null)
            {
                datafinal = DateTime.Now;
            }

            FuncoesBanco f = new FuncoesBanco(dblocal);

            var x = GetSQLProcutividade(id, datainicial, datafinal);

            List <dynamic> MyList = f.CollectionFromSql(x,
                                                        new Dictionary <string, object> {
            }).ToList();

            foreach (dynamic item in MyList)
            {
                if (!DBNull.Equals(item.PRODUTIVIDADE, DBNull.Value))
                {
                    PRODUTIVIDADE = Convert.ToDouble(item.PRODUTIVIDADE);
                }
                else
                {
                    PRODUTIVIDADE = 0;
                }

                if (!DBNull.Equals(item.DISCADAS, DBNull.Value))
                {
                    DISCADAS = Convert.ToInt32(item.DISCADAS);
                }
                else
                {
                    DISCADAS = 0;
                }
                if (!DBNull.Equals(item.CONTATOS, DBNull.Value))
                {
                    CONTATOS = Convert.ToInt32(item.CONTATOS);
                }
                else
                {
                    CONTATOS = 0;
                }
                if (!DBNull.Equals(item.APROVEITAMENTO, DBNull.Value))
                {
                    APROVEITAMENTO = Convert.ToDouble(item.APROVEITAMENTO);
                }
                else
                {
                    APROVEITAMENTO = 0;
                }
                if (!DBNull.Equals(item.PEDIDOS, DBNull.Value))
                {
                    PEDIDOS = Convert.ToInt32(item.PEDIDOS);
                }
                else
                {
                    PEDIDOS = 0;
                }
            }

            x = "SELECT cli.ESTADO, SUM(cc.VALOR) as VALOR FROM compras cc "
                + " JOIN clientes cli on cli.CODIGO = cc.CLIENTE AND cli.ESTADO <> '' "
                + " WHERE cc.OPERADOR > 0 AND cc.DATA BETWEEN '" + String.Format("{0:yyyy-MM-dd}", datainicial)
                + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' "
                + " group by cli.ESTADO having SUM(cc.VALOR) > 0 ORDER BY COUNT(cc.CODIGO) DESC ";

            if (VendasPorEstado == null)
            {
                MyList = f.CollectionFromSql(x,
                                             new Dictionary <string, object> {
                }).ToList();

                VendasPorEstado = MyList;
            }

            x = "SELECT meta.OPERADOR,o.LOGIN, sum(meta.VALOR_META) as META "
                + " FROM operadores_meta meta JOIN operadores o on o.CODIGO = meta.OPERADOR WHERE CAST(CONCAT(meta.ANO, '-', meta.MES, '-01') AS DATE) BETWEEN '" + String.Format("{0:yyyy-MM-dd}", datainicial) + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' "
                + " group by meta.OPERADOR,o.LOGIN ";

            if (MetasXVendas == null)
            {
                MyList = f.CollectionFromSql(x,
                                             new Dictionary <string, object> {
                }).ToList();

                MetasXVendas = MyList;

                foreach (var m in MetasXVendas)
                {
                    x = "SELECT SUM(cc.VALOR) as VALOR FROM compras cc "
                        + " WHERE cc.OPERADOR = " + m.OPERADOR + " AND cc.DATA BETWEEN '" + String.Format("{0:yyyy-MM-dd}", datainicial)
                        + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' ";

                    var valor = f.ExecSql(x);

                    if (valor != null && valor.Count > 0)
                    {
                        m.VALOR_VENDA = Convert.ToDouble(valor[0]);
                    }
                    else
                    {
                        m.VALOR_VENDA = 0;
                    }

                    x = " select p.VALOR from campanhas_clientes a inner join propostas p on p.LIGACAO = a.CODIGO "
                        + " WHERE a.OPERADOR = " + m.OPERADOR + " AND a.DT_RESULTADO BETWEEN '" + String.Format("{0:yyyy-MM-dd}", datainicial)
                        + "' AND '" + String.Format("{0:yyyy-MM-dd}", datafinal) + "' ";
                    valor = f.ExecSql(x);

                    if (valor != null && valor.Count > 0)
                    {
                        m.VALOR_PROPOSTA = Convert.ToDouble(valor[0]);
                    }
                    else
                    {
                        m.VALOR_PROPOSTA = 0;
                    }
                }
            }
        }
        // POST: api/T
        //[ResponseType(typeof(T))]
        //[ResponseType(typeof(void))]
        public IHttpActionResult Post(T item)
        {
            //if (typeof(IRaizDeAgregacao).IsAssignableFrom(typeof(T)))
            //{
            //    ((IRaizDeAgregacao)item).Flag = true;
            //    ModelState["item.Flag"].Errors.Clear();
            //}

            var resultpost = ExecutarAntesPost(item);

            if (resultpost != null)
            {
                return(resultpost);
            }

            if (item.id == 0)
            {
                try
                {
                    var fb = new FuncoesBanco(db);
                    item.id = fb.BuscarPKRegistro(item.GetType().Name);
                }
                catch
                {
                    return(Content(HttpStatusCode.Accepted, new { mensagem_erro = "Problema com generator da tabela " + item.GetType().Name }));
                }
            }

            ConfCEMP(item);

            if (!ModelState.IsValid)
            {
                return(TestarModelState(ModelState));
            }

            var result = ValidarEntidade(item);

            if (result != null)
            {
                return(Content(HttpStatusCode.Accepted, new { mensagem_erro = result }));
            }

            db.Set <T>().Add(item);

            InternalUpdate(item);
            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    BeforeSaveChanges(item);
                    db.SaveChanges();
                    dbContextTransaction.Commit();
                }
                catch (DbUpdateException e)
                {
                    dbContextTransaction.Rollback();
                    if (ItemExiste(item.id))
                    {
                        return(Content(HttpStatusCode.Accepted, new { mensagem_erro = "Registro já existe!" }));
                        //return Conflict();
                    }
                    else
                    {
                        if (e.InnerException != null)
                        {
                            return(Content(HttpStatusCode.Accepted, new { mensagem_erro = e.InnerException.InnerException.Message }));
                        }
                        else
                        {
                            return(Content(HttpStatusCode.Accepted, new { mensagem_erro = e.Message }));
                        }
                    }
                }
                catch (DbEntityValidationException e)
                {
                    dbContextTransaction.Rollback();

                    if (e.InnerException != null)
                    {
                        return(Content(HttpStatusCode.Accepted, new { mensagem_erro = e.InnerException.InnerException.Message }));
                    }
                    else
                    {
                        return(Content(HttpStatusCode.Accepted, new { mensagem_erro = e.Message }));
                    }
                }
                catch (InvalidOperationException e)
                {
                    dbContextTransaction.Rollback();

                    if (e.InnerException != null)
                    {
                        return(Content(HttpStatusCode.Accepted, new { mensagem_erro = e.InnerException.InnerException.Message }));
                    }
                    else
                    {
                        return(Content(HttpStatusCode.Accepted, new { mensagem_erro = e.Message }));
                    }
                }
            }

            BeforeReturn(item);
            return(CreatedAtRoute("DefaultApi", new { id = item.id }, item));
        }
        public dynamic ConfirmarPedido(Pedido dados)
        {
            FuncoesBanco f = new FuncoesBanco(dblocal);

            if (dados.id < 0)
            {
                dados.id = 0;
            }

            var id = f.ExecSql("select id from SP_GRAVAR_PEDIDO_WEB(" + dados.id + ", " + dados.CodUsr
                               + ", " + dados.Mesa + ", '" + dados.Total.ToString().Replace(",", ".")
                               + "' , '" + dados.OBS.Trim()
                               + "')");

            if (id != null && id.Count > 0)
            {
                dados.id = Convert.ToInt32(id[0]);
            }

            int ii = 0;

            if (dados.Produtos is string)
            {
                PRODUTO i = JsonConvert.DeserializeObject <PRODUTO>(dados.Produtos);
                f.ExecSql("select id from SP_GRAVAR_PEDIDO_ITEM_WEB(" + dados.id + ", " + dados.CodUsr
                          + ", " + dados.Mesa + ", '" + i.PRODN3VLRVENDA.ToString().Replace(",", ".")
                          + "', " + i.QTD.ToString()
                          + "," + ii
                          + ", " + i.id
                          + ")");
            }
            else
            {
                PRODUTO i = new PRODUTO();
                foreach (dynamic item in dados.Produtos)
                {
                    foreach (dynamic filho in item)
                    {
                        foreach (dynamic campo in filho)
                        {
                            if (filho.Name == "id")
                            {
                                i.id = (int)campo.Value;
                            }
                            else
                            if (filho.Name == "PRODN3VLRVENDA")
                            {
                                i.PRODN3VLRVENDA = campo.Value;
                            }
                            else
                            if (filho.Name == "QTD")
                            {
                                i.QTD = (int)campo.Value;
                            }
                        }
                    }

                    ii++;
                    //item;//JsonConvert.DeserializeObject<PRODUTO>(item);
                    f.ExecSql("select id from SP_GRAVAR_PEDIDO_ITEM_WEB(" + dados.id + ", " + dados.CodUsr
                              + ", " + dados.Mesa + ", '" + i.PRODN3VLRVENDA.ToString().Replace(",", ".")
                              + "', " + i.QTD.ToString()
                              + "," + ii
                              + ", " + i.id
                              + ")");
                }
            }

            //retorno.id = dados.id;
            return(dados);
        }
        protected override IHttpActionResult ExecutarAntesPost(MOV_ENTRADA item)
        {
            CAD_PESSOA pessoa = null;
            var        fb     = new FuncoesBanco(db);

            if (item.COD_CADPESSOA == null)
            {
                pessoa             = new CAD_PESSOA();
                pessoa.id          = fb.BuscarPKRegistro(pessoa.GetType().Name);
                item.COD_CADPESSOA = pessoa.id;
                pessoa.ATIVO       = "S";
                pessoa.CEMP        = "01";
                pessoa.DOCUMENTO   = item.DOCUMENTO_PESSOA;
                pessoa.NOME        = item.NOME_PESSOA;
                pessoa.TIPO        = "1";

                //if (item.NOME_PESSOA_AP != null)
                //{
                //    pessoa.TIPO = "1";
                //}
                //else
                //    if (item.NOME_PESSOA_AP != item.NOME_PESSOA)
                //{
                //    pessoa.TIPO = "2";
                //}
            }

            CAD_VEICULO veiculo = null;

            if (item.COD_CADVEICULO == null)
            {
                veiculo               = new CAD_VEICULO();
                veiculo.id            = fb.BuscarPKRegistro(veiculo.GetType().Name);
                veiculo.PLACA         = item.PLACA.ToUpper();
                veiculo.COD_CADPESSOA = item.COD_CADPESSOA;
                item.COD_CADVEICULO   = veiculo.id;
                veiculo.CEMP          = "01";
                //if (pessoa == null)
                //{
                //    veiculo.VISITANTE = "S";
                //}
            }

            bool fezInsert = false;

            if (pessoa != null)
            {
                db.CAD_PESSOA.Add(pessoa);
                fezInsert = true;
            }

            if (veiculo != null)
            {
                db.CAD_VEICULO.Add(veiculo);
                fezInsert = true;
            }

            if (fezInsert == true)
            {
                db.SaveChanges();
            }

            var ap = db.CAD_APARTAMENTO.Where(w => w.id == item.COD_CADAPARTAMENTO).FirstOrDefault();

            if (ap == null)
            {
                ap               = new CAD_APARTAMENTO();
                ap.id            = item.COD_CADAPARTAMENTO;
                ap.GARAGEM       = item.GARAGEM;
                ap.TORRE         = item.TORRE;
                ap.COD_CADPESSOA = item.COD_CADPESSOA;
                ap.CEMP          = "01";
                db.CAD_APARTAMENTO.Add(ap);
                db.SaveChanges();
            }

            if (pessoa != null)
            {
                pessoa.COD_CADAPARTAMENTO = item.COD_CADAPARTAMENTO;
                db.Entry(pessoa).State    = EntityState.Modified;
            }

            if (ap != null)
            {
                ap.COD_CADPESSOA   = item.COD_CADPESSOA;
                db.Entry(ap).State = EntityState.Modified;
            }

            if (veiculo != null)
            {
                veiculo.COD_CADPESSOA   = item.COD_CADPESSOA;
                db.Entry(veiculo).State = EntityState.Modified;
            }

            if (fezInsert == true)
            {
                db.SaveChanges();
            }

            return(null);
        }