Esempio n. 1
0
        public HttpResponseMessage Put([FromBody] Roles rol)
        {
            try
            {
                G.AbrirConexionAPP(out db);

                var Rol = db.Roles.Where(a => a.idRol == rol.idRol).FirstOrDefault();

                if (Rol != null)
                {
                    db.Entry(Rol).State = EntityState.Modified;
                    Rol.NombreRol       = rol.NombreRol;

                    db.SaveChanges();
                }
                else
                {
                    throw new Exception("Rol no existe");
                }
                G.CerrarConexionAPP(db);
                return(Request.CreateResponse(HttpStatusCode.OK, Rol));
            }
            catch (Exception ex)
            {
                G.CerrarConexionAPP(db);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Esempio n. 2
0
        public HttpResponseMessage Put([FromBody] CuentasContables cuenta)
        {
            try
            {
                G.AbrirConexionAPP(out db);

                var Cuenta = db.CuentasContables.Where(a => a.idCuentaContable == cuenta.idCuentaContable).FirstOrDefault();

                if (Cuenta != null)
                {
                    db.Entry(Cuenta).State = EntityState.Modified;
                    Cuenta.CodSAP          = cuenta.CodSAP;
                    Cuenta.Nombre          = cuenta.Nombre;
                    db.SaveChanges();
                }
                else
                {
                    throw new Exception("Cuenta no existe");
                }
                G.CerrarConexionAPP(db);
                return(Request.CreateResponse(HttpStatusCode.OK, Cuenta));
            }
            catch (Exception ex)
            {
                BitacoraErrores be = new BitacoraErrores();
                be.Descripcion = ex.Message;
                be.StackTrace  = ex.StackTrace;
                be.Metodo      = "Actualizar Cuenta Contable";
                be.Fecha       = DateTime.Now;
                db.BitacoraErrores.Add(be);
                db.SaveChanges();
                G.CerrarConexionAPP(db);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
        public HttpResponseMessage Put([FromBody] Dimensiones dimension)
        {
            try
            {
                G.AbrirConexionAPP(out db);

                var Dimension = db.Dimensiones.Where(a => a.id == dimension.id).FirstOrDefault();

                if (Dimension != null)
                {
                    db.Entry(Dimension).State = EntityState.Modified;
                    Dimension.codigoSAP       = dimension.codigoSAP;
                    Dimension.Nombre          = dimension.Nombre;
                    db.SaveChanges();
                }
                else
                {
                    throw new Exception("Dimension no existe");
                }
                G.CerrarConexionAPP(db);
                return(Request.CreateResponse(HttpStatusCode.OK, Dimension));
            }
            catch (Exception ex)
            {
                BitacoraErrores be = new BitacoraErrores();
                be.Descripcion = ex.Message;
                be.StackTrace  = ex.StackTrace;
                be.Metodo      = "Actualizar Dimension";
                be.Fecha       = DateTime.Now;
                db.BitacoraErrores.Add(be);
                db.SaveChanges();
                G.CerrarConexionAPP(db);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
        public HttpResponseMessage Put([FromBody] Gastos gasto)
        {
            try
            {
                G.AbrirConexionAPP(out db);

                var Gasto = db.Gastos.Where(a => a.idTipoGasto == gasto.idTipoGasto).FirstOrDefault();

                if (Gasto != null)
                {
                    db.Entry(Gasto).State  = EntityState.Modified;
                    Gasto.Nombre           = gasto.Nombre;
                    Gasto.PalabrasClave    = gasto.PalabrasClave;
                    Gasto.idCuentaContable = gasto.idCuentaContable;

                    db.SaveChanges();
                }
                else
                {
                    throw new Exception("Gasto no existe");
                }
                G.CerrarConexionAPP(db);
                return(Request.CreateResponse(HttpStatusCode.OK, Gasto));
            }
            catch (Exception ex)
            {
                BitacoraErrores be = new BitacoraErrores();
                be.Descripcion = ex.Message;
                be.StackTrace  = ex.StackTrace;
                be.Metodo      = "Actualizar Gastos";
                be.Fecha       = DateTime.Now;
                db.BitacoraErrores.Add(be);
                db.SaveChanges();
                G.CerrarConexionAPP(db);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
        public HttpResponseMessage Put([FromBody] NormasReparto norma)
        {
            try
            {
                G.AbrirConexionAPP(out db);

                var Normas = db.NormasReparto.Where(a => a.id == norma.id).FirstOrDefault();

                if (Normas != null)
                {
                    db.Entry(Normas).State = EntityState.Modified;
                    Normas.CodSAP          = norma.CodSAP;
                    Normas.Nombre          = norma.Nombre;
                    Normas.idDimension     = norma.idDimension;
                    Normas.idLogin         = norma.idLogin;
                    db.SaveChanges();
                }
                else
                {
                    throw new Exception("Norma no existe");
                }
                G.CerrarConexionAPP(db);
                return(Request.CreateResponse(HttpStatusCode.OK, Normas));
            }
            catch (Exception ex)
            {
                BitacoraErrores be = new BitacoraErrores();
                be.Descripcion = ex.Message;
                be.StackTrace  = ex.StackTrace;
                be.Metodo      = "Actualizar Norma de Reparto";
                be.Fecha       = DateTime.Now;
                db.BitacoraErrores.Add(be);
                db.SaveChanges();
                G.CerrarConexionAPP(db);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
        public HttpResponseMessage GetEstado([FromUri] int id, string Estado, string comentario = "", int idLoginAceptacion = 0)
        {
            try
            {
                G.AbrirConexionAPP(out db);

                var EncCierre = db.EncCierre.Where(a => a.idCierre == id).FirstOrDefault();

                db.Entry(EncCierre).State = EntityState.Modified;

                EncCierre.Estado = Estado;
                if (!string.IsNullOrEmpty(comentario))
                {
                    EncCierre.Observacion = comentario;
                }

                if (Estado == "E")
                {
                    SendGridEmail.EmailSender emailsender = new SendGridEmail.EmailSender();
                    var Roles = db.Roles.Where(a => a.NombreRol.ToUpper().Contains("APROBADOR")).FirstOrDefault();

                    var Login          = db.Login.Where(a => a.idRol == Roles.idRol).ToList();
                    var AsignadoCierre = db.Login.Where(a => a.id == EncCierre.idLogin).FirstOrDefault();
                    var parametros     = db.Parametros.FirstOrDefault();

                    var html = "<h3 style='text-align: center; '><strong>Liquidaci&oacute;n pendiente de revisi&oacute;n</strong></h3>";
                    html += "<p style='text-align: justify; '>Se ha recibido una nueva liquidaci&oacute;n de gastos, a continuaci&oacute;n los detalles:</p>";
                    html += "<ul>";
                    html += "<li style = 'text-align: justify;' ><strong> ID Cierre </strong>: " + EncCierre.idCierre + "</li>";
                    html += "<li style = 'text-align: justify;' ><strong> Nombre </strong>: " + AsignadoCierre.Nombre + "</li>";
                    html += "<li style='text-align: justify; '><strong>Periodo</strong>: " + EncCierre.Periodo + "</li>";
                    html += "<li style='text-align: justify; '><strong>Cantidad de Facturas: </strong>" + EncCierre.CantidadRegistros + "</li>";
                    html += "<li style='text-align: justify; '><strong>Total</strong>: " + decimal.Round(EncCierre.Total.Value, 2) + "</li>";
                    html += "</ul><p></p> ";
                    html += "<p>Favor revisar en la plataforma <a href='" + parametros.UrlSitioPublicado + "'>" + parametros.UrlSitioPublicado + "</a>&nbsp;para aceptar o denegar dicha liquidaci&oacute;n.</p>";

                    foreach (var item in Login)
                    {
                        emailsender.SendV2(item.Email, parametros.RecepcionEmail, "", parametros.RecepcionEmail, "Liquidación", "Liquidación pendiente de revisión", html, parametros.RecepcionHostName, parametros.EnvioPort, parametros.RecepcionUseSSL.Value, parametros.RecepcionEmail, parametros.RecepcionPassword);
                    }
                }


                if (Estado == "A" || Estado == "R")
                {
                    SendGridEmail.EmailSender emailsender = new SendGridEmail.EmailSender();
                    //var Roles = db.Roles.Where(a => a.NombreRol.ToUpper().Contains("APROBADOR")).FirstOrDefault();
                    var login = db.Login.Where(a => a.id == EncCierre.idLogin).FirstOrDefault();
                    var AR    = Estado;

                    var Login          = db.Login.Where(a => a.id == login.id).FirstOrDefault();
                    var AsignadoCierre = db.Login.Where(a => a.id == EncCierre.idLogin).FirstOrDefault();
                    var parametros     = db.Parametros.FirstOrDefault();
                    //&oacute; -> Tilde
                    var html = "";
                    if (AR == "A")
                    {
                        var LoginAceptacion = db.Login.Where(a => a.id == EncCierre.idLoginAceptacion).FirstOrDefault();
                        html  = "<h3 style='text-align: center; '><strong>Liquidaci&oacute;n  Aprobada</strong></h3>";
                        html += "<p style='text-align: justify; '>Se ha aprobado tú liquidaci&oacute;n de gastos, a continuaci&oacute;n los detalles:</p>";
                        html += "<ul>";
                        html += "<li style = 'text-align: justify;' ><strong> ID Cierre </strong>: " + EncCierre.idCierre + "</li>";
                        html += "<li style = 'text-align: justify;' ><strong> Nombre </strong>: " + AsignadoCierre.Nombre + "</li>";
                        html += "<li style='text-align: justify; '><strong>Periodo</strong>: " + EncCierre.Periodo + "</li>";
                        html += "<li style='text-align: justify; '><strong>Cantidad de Facturas: </strong>" + EncCierre.CantidadRegistros + "</li>";
                        html += "<li style='text-align: justify; '><strong>Total</strong>: " + decimal.Round(EncCierre.Total.Value, 2) + "</li>";
                        html += "<li style='text-align: justify; '><strong>Usuario Aprobador</strong>: " + (LoginAceptacion == null ? "" : LoginAceptacion.Nombre) + "</li>";
                        html += "<li style='text-align: justify; '><strong>Comentarios de la Liquidación</strong>: " + EncCierre.Observacion + "</li>";
                        html += "</ul><p></p> ";
                        html += "<p>Favor revisar en la plataforma <a href='" + parametros.UrlSitioPublicado + "'>" + parametros.UrlSitioPublicado + "</a>&nbsp;para ver más detalles de dicha liquidaci&oacute;n.</p>";
                    }
                    else
                    {
                        var LoginAceptacion = db.Login.Where(a => a.id == EncCierre.idLoginAceptacion).FirstOrDefault();
                        html  = "<h3 style='text-align: center; '><strong>Liquidaci&oacute;n  Rechazada</strong></h3>";
                        html += "<p style='text-align: justify; '>Se ha rechazado tú liquidaci&oacute;n de gastos, a continuaci&oacute;n los detalles:</p>";
                        html += "<ul>";
                        html += "<li style = 'text-align: justify;' ><strong> ID Cierre </strong>: " + EncCierre.idCierre + "</li>";
                        html += "<li style = 'text-align: justify;' ><strong> Nombre </strong>: " + AsignadoCierre.Nombre + "</li>";
                        html += "<li style='text-align: justify; '><strong>Periodo</strong>: " + EncCierre.Periodo + "</li>";
                        html += "<li style='text-align: justify; '><strong>Cantidad de Facturas: </strong>" + EncCierre.CantidadRegistros + "</li>";
                        html += "<li style='text-align: justify; '><strong>Total</strong>: " + decimal.Round(EncCierre.Total.Value, 2) + "</li>";
                        html += "<li style='text-align: justify; '><strong>Usuario Aprobador</strong>: " + (LoginAceptacion == null ? "" : LoginAceptacion.Nombre) + "</li>";
                        html += "<li style='text-align: justify; '><strong>Comentarios de la Liquidación</strong>: " + EncCierre.Observacion + "</li>";
                        html += "</ul><p></p> ";
                        html += "<p>Favor revisar en la plataforma <a href='" + parametros.UrlSitioPublicado + "'>" + parametros.UrlSitioPublicado + "</a>&nbsp;para ver más detalles de dicha liquidaci&oacute;n.</p>";
                    }



                    emailsender.SendV2(Login.Email, parametros.RecepcionEmail, "", parametros.RecepcionEmail, "Liquidación", "Respuesta de la liquidación", html, parametros.RecepcionHostName, parametros.EnvioPort, parametros.RecepcionUseSSL.Value, parametros.RecepcionEmail, parametros.RecepcionPassword);
                }



                //EncCierre.idLoginAceptacion = idLoginAceptacion;

                db.SaveChanges();
                G.CerrarConexionAPP(db);
                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                BitacoraErrores be = new BitacoraErrores();
                be.Descripcion = ex.Message;
                be.StackTrace  = ex.StackTrace;
                be.Metodo      = "Cambio de estado";
                be.Fecha       = DateTime.Now;
                db.BitacoraErrores.Add(be);
                db.SaveChanges();


                G.CerrarConexionAPP(db);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Esempio n. 7
0
        public HttpResponseMessage Put([FromBody] LoginViewModel usuario)
        {
            try
            {
                G.AbrirConexionAPP(out db);

                var User    = db.Login.Where(a => a.id == usuario.id).FirstOrDefault(); //a.Email.ToUpper().Contains(usuario.Email.ToUpper())
                var Usuario = dbLogin.LicUsuarios.Where(a => a.Email.ToUpper().Contains(User.Email.ToUpper()) && a.CedulaJuridica == usuario.CedulaJuridica).FirstOrDefault();

                if (Usuario != null && User != null)
                {
                    dbLogin.Entry(Usuario).State = EntityState.Modified;
                    db.Entry(User).State         = EntityState.Modified;

                    if (!string.IsNullOrEmpty(usuario.Clave))
                    {
                        Usuario.Clave     = BCrypt.Net.BCrypt.HashPassword(usuario.Clave);
                        User.Clave        = Usuario.Clave;
                        User.CambiarClave = false;
                    }

                    if (!string.IsNullOrEmpty(usuario.Nombre))
                    {
                        Usuario.Nombre = usuario.Nombre;
                        User.Nombre    = Usuario.Nombre;
                    }

                    if (!string.IsNullOrEmpty(usuario.Email))
                    {
                        Usuario.Email = usuario.Email;
                        User.Email    = Usuario.Email;
                    }

                    if (usuario.idRol > 0)
                    {
                        User.idRol = usuario.idRol;
                    }
                    if (usuario.idLoginAceptacion > 0)
                    {
                        User.idLoginAceptacion = usuario.idLoginAceptacion;
                    }

                    if (!string.IsNullOrEmpty(usuario.CardCode))
                    {
                        User.CardCode = usuario.CardCode;
                    }
                    User.CambioFecha = User.CambioFecha;
                    dbLogin.SaveChanges();
                    db.SaveChanges();
                }
                else
                {
                    throw new Exception("Usuario no existe");
                }
                G.CerrarConexionAPP(db);
                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                BitacoraErrores be = new BitacoraErrores();
                be.Descripcion = ex.Message + " -> " + usuario.CedulaJuridica;
                be.StackTrace  = ex.StackTrace;
                be.Metodo      = "Actualizacion de Usuario";
                be.Fecha       = DateTime.Now;
                db.BitacoraErrores.Add(be);
                db.SaveChanges();

                G.CerrarConexionAPP(db);
                G.GuardarTxt("ErrorEditarUsuario.txt", ex.Message + " => " + ex.StackTrace);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Esempio n. 8
0
        public HttpResponseMessage Post([FromBody] LoginViewModel usuario)
        {
            try
            {
                var Empresa = dbLogin.LicEmpresas.Where(a => a.CedulaJuridica == usuario.CedulaJuridica).FirstOrDefault();
                if (Empresa == null)
                {
                    throw new Exception("Empresa no existe");
                }

                db = new ModelCliente(Empresa.CadenaConexionBD);
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
            }
            var t = db.Database.BeginTransaction();
            var d = dbLogin.Database.BeginTransaction();

            try
            {
                var User     = dbLogin.LicUsuarios.Where(a => a.Email.ToUpper().Contains(usuario.Email.ToUpper()) && a.Activo == true).FirstOrDefault();
                var usuario1 = db.Login.Where(a => a.Email.ToUpper().Contains(usuario.Email.ToUpper()) && a.Activo == true).FirstOrDefault();
                if (usuario1 == null)
                {
                    User                = new LicUsuarios();
                    User.Nombre         = usuario.Nombre;
                    User.Clave          = BCrypt.Net.BCrypt.HashPassword(usuario.Clave);
                    User.Email          = usuario.Email;
                    User.Activo         = true;
                    User.CedulaJuridica = usuario.CedulaJuridica;

                    Login login = new Login();
                    login.Nombre            = User.Nombre;
                    login.Clave             = User.Clave;
                    login.Activo            = true;
                    login.idRol             = usuario.idRol;
                    login.Email             = User.Email;
                    login.CardCode          = usuario.CardCode;
                    login.idLoginAceptacion = usuario.idLoginAceptacion;
                    login.CambiarClave      = true;
                    login.CambioFecha       = false;
                    db.Login.Add(login);

                    dbLogin.LicUsuarios.Add(User);
                    dbLogin.SaveChanges();
                    db.SaveChanges();

                    if (login.idLoginAceptacion == 0)
                    {
                        db.Entry(login).State   = EntityState.Modified;
                        login.idLoginAceptacion = login.id;
                        db.SaveChanges();
                    }

                    d.Commit();
                    t.Commit();
                }
                else
                {
                    throw new Exception("Este usuario YA existe");
                }

                G.CerrarConexionAPP(db);
                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                BitacoraErrores be = new BitacoraErrores();
                be.Descripcion = ex.Message;
                be.StackTrace  = ex.StackTrace;
                be.Metodo      = "Insercion de Usuario";
                be.Fecha       = DateTime.Now;
                db.BitacoraErrores.Add(be);
                db.SaveChanges();

                t.Rollback();
                d.Rollback();
                G.CerrarConexionAPP(db);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
        public HttpResponseMessage GetAsientos([FromUri] int idCierre = 0)
        {
            object  resp;
            decimal imp1  = 0;
            decimal imp2  = 0;
            decimal imp4  = 0;
            decimal imp8  = 0;
            decimal imp13 = 0;

            try
            {
                G.AbrirConexionAPP(out db);
                var Cierre = db.EncCierre.Where(a => a.idCierre == idCierre).FirstOrDefault();
                G.GuardarTxt("ErrorSAP.txt", "Entro");

                var Compañia = G.ObtenerCedulaJuridia();

                var Licencia = dbLogin.LicEmpresas.Where(a => a.CedulaJuridica == Compañia).FirstOrDefault();

                var Pais = Licencia.CadenaConexionSAP;

                if (Cierre.ProcesadaSAP == true)
                {
                    throw new Exception("Esta liquidación ya fue procesada");
                }

                var Detalle = db.DetCierre.Where(a => a.idCierre == Cierre.idCierre).ToList();

                List <EncCompras> enc = new List <EncCompras>();
                var Encabezados       = db.EncCompras.Where(a => a.idCierre == Cierre.idCierre).ToList();
                foreach (var item in Detalle)
                {
                    var compra = Encabezados.Where(a => a.id == item.idFactura).FirstOrDefault();
                    enc.Add(compra);
                }

                var login = db.Login.Where(a => a.id == Cierre.idLogin).FirstOrDefault();
                var param = db.Parametros.FirstOrDefault();



                var oInvoice = (Documents)Conexion.Company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oDrafts);



                oInvoice.DocObjectCode = BoObjectTypes.oPurchaseInvoices;

                oInvoice.CardCode = login.CardCode; //CardCode que viene de login


                if (login.CambioFecha)
                {
                    //int DiferenciaDias = (new DateTime(DateTime.Now.Year, DateTime.Now.Month, 15) - DateTime.Now).Days;
                    //oInvoice.DocDate = DateTime.Now.AddDays(DiferenciaDias); //Fecha que se realiza el asiento
                    //oInvoice.DocDueDate = DateTime.Now.AddDays(DiferenciaDias); //Fecha que se realiza el asiento


                    oInvoice.DocDate    = DateTime.Now; //Fecha que se realiza el asiento
                    oInvoice.DocDueDate = DateTime.Now; //Fecha que se realiza el asiento
                }
                else
                {
                    oInvoice.DocDate    = Cierre.FechaFinal; //Final del periodo de cierre
                    oInvoice.DocDueDate = Cierre.FechaFinal; //Final del periodo de cierre
                }

                oInvoice.DocCurrency = (Cierre.CodMoneda == "CRC" ? "COL" : Cierre.CodMoneda); //Moneda de la liquidacion
                if (Pais == "P")
                {
                    if (Cierre.CodMoneda == "USD")
                    {
                        oInvoice.DocCurrency = "$";
                    }
                }
                oInvoice.DocType   = BoDocumentTypes.dDocument_Service;
                oInvoice.NumAtCard = "Liquidación: " + idCierre.ToString();
                var i = 0;
                foreach (var item in enc)
                {
                    Gastos TipoGasto = new Gastos();
                    //Esto no va para panama
                    if (Pais == "C")
                    {
                        if (item.RegimenSimplificado)
                        {
                            TipoGasto = db.Gastos.Where(a => a.Nombre.ToUpper().Contains("Regimen Simplificado".ToUpper())).FirstOrDefault();
                        }
                        else
                        {
                            TipoGasto = db.Gastos.Where(a => a.idTipoGasto == item.idTipoGasto).FirstOrDefault();
                        }
                    }
                    else //Panama
                    {
                        TipoGasto = db.Gastos.Where(a => a.idTipoGasto == item.idTipoGasto).FirstOrDefault();
                    }


                    var Cuenta    = db.CuentasContables.Where(a => a.idCuentaContable == TipoGasto.idCuentaContable).FirstOrDefault();
                    var Norma     = db.NormasReparto.Where(a => a.id == item.idNormaReparto).FirstOrDefault();
                    var Dimension = db.Dimensiones.Where(a => a.id == Norma.idDimension).FirstOrDefault();

                    oInvoice.Lines.SetCurrentLine(i);
                    if (Pais == "C")
                    {
                        oInvoice.Lines.ItemDescription = item.CodProveedor + "-" + item.NomProveedor;//"3102751358 - D y D Consultores"; // Factura -> Cedula
                    }
                    else
                    {
                        oInvoice.Lines.ItemDescription = item.CodProveedor.Split('[')[0] + " - " + item.CodProveedor.Split('[')[1] + "-" + item.NomProveedor; //"3102751358 - D y D Consultores"; // Factura -> Cedula
                    }
                    oInvoice.Lines.AccountCode = Cuenta.CodSAP;                                                                                               //"6-01-02-05-000"; //Cuenta contable del gasto

                    if (Pais == "C")
                    {
                        oInvoice.Lines.TaxCode = param.IMPEX; //Exento para Panama -> Verificar el codigo C0
                    }
                    else
                    {
                        oInvoice.Lines.VatGroup = param.IMPEX;
                    }

                    //Redifinir para Panama
                    if (Pais == "C")
                    {
                        imp1  += item.Impuesto1;
                        imp2  += item.Impuesto2;
                        imp4  += item.Impuesto4;
                        imp8  += item.Impuesto8;
                        imp13 += item.Impuesto13;
                    }
                    else //Panama
                    {
                        imp1 += item.Impuesto1;
                        imp2 += item.Impuesto2;
                    }



                    //Normas de reparto
                    switch (Dimension.codigoSAP)
                    {
                    case "1":
                    {
                        oInvoice.Lines.CostingCode  = Norma.CodSAP;
                        oInvoice.Lines.CostingCode2 = "";
                        oInvoice.Lines.CostingCode3 = "";
                        oInvoice.Lines.CostingCode4 = "";
                        oInvoice.Lines.CostingCode5 = "";
                        break;
                    }

                    case "2":
                    {
                        oInvoice.Lines.CostingCode  = "";
                        oInvoice.Lines.CostingCode2 = Norma.CodSAP;
                        oInvoice.Lines.CostingCode3 = "";
                        oInvoice.Lines.CostingCode4 = "";
                        oInvoice.Lines.CostingCode5 = "";
                        break;
                    }

                    case "3":
                    {
                        oInvoice.Lines.CostingCode  = "";
                        oInvoice.Lines.CostingCode2 = "";
                        oInvoice.Lines.CostingCode3 = Norma.CodSAP;
                        oInvoice.Lines.CostingCode4 = "";
                        oInvoice.Lines.CostingCode5 = "";
                        break;
                    }

                    case "4":
                    {
                        oInvoice.Lines.CostingCode  = "";
                        oInvoice.Lines.CostingCode2 = "";
                        oInvoice.Lines.CostingCode3 = "";
                        oInvoice.Lines.CostingCode4 = Norma.CodSAP;
                        oInvoice.Lines.CostingCode5 = "";
                        break;
                    }

                    case "5":
                    {
                        oInvoice.Lines.CostingCode  = "";
                        oInvoice.Lines.CostingCode2 = "";
                        oInvoice.Lines.CostingCode3 = "";
                        oInvoice.Lines.CostingCode4 = "";
                        oInvoice.Lines.CostingCode5 = Norma.CodSAP;
                        break;
                    }

                    default:

                    {
                        oInvoice.Lines.CostingCode  = Norma.CodSAP;
                        oInvoice.Lines.CostingCode2 = "";
                        oInvoice.Lines.CostingCode3 = "";
                        oInvoice.Lines.CostingCode4 = "";
                        oInvoice.Lines.CostingCode5 = "";
                        break;
                    }
                    }

                    oInvoice.Lines.LineTotal = Convert.ToDouble(item.TotalComprobante.Value - item.TotalImpuesto);


                    if (Pais == "C")
                    {
                        G.GuardarTxt("ErrorSAP.txt", "Entro en: " + Pais);
                        if (TipoGasto.Nombre.ToUpper().Contains("Combustible".ToUpper()))
                        {
                            var DetalleFac = db.DetCompras.Where(a => a.NumFactura == item.NumFactura && a.ClaveHacienda == item.ClaveHacienda && a.ConsecutivoHacienda == item.ConsecutivoHacienda).FirstOrDefault();

                            oInvoice.Lines.UserFields.Fields.Item("U_CantLitrosKw").Value = int.Parse(Math.Round(DetalleFac.Cantidad.Value).ToString());

                            oInvoice.Lines.UserFields.Fields.Item("U_Tipo").Value = (DetalleFac.NomPro.ToUpper().Contains("Diesel".ToUpper()) ? "Diesel" : QuitarTilde(DetalleFac.NomPro).ToUpper().Contains("Super".ToUpper()) ? "Gasolina Super" : QuitarTilde(DetalleFac.NomPro).ToUpper().Contains("Regular".ToUpper()) ? "Gasolina Regular" : "Diesel");
                        }

                        oInvoice.Lines.UserFields.Fields.Item("U_NumFactura").Value   = item.NumFactura.ToString();
                        oInvoice.Lines.UserFields.Fields.Item("U_FechaFactura").Value = item.FecFactura;
                    }
                    else //Panama
                    {
                        G.GuardarTxt("ErrorSAP.txt", "Entro en: " + Pais);
                        if (TipoGasto.Nombre.ToUpper().Contains("Comb".ToUpper()))
                        {
                            var DetalleFac = db.DetCompras.Where(a => a.NumFactura == item.NumFactura && a.ClaveHacienda == item.ClaveHacienda && a.ConsecutivoHacienda == item.ConsecutivoHacienda).FirstOrDefault();
                            oInvoice.Lines.UserFields.Fields.Item("U_CantLitrosKw").Value = int.Parse(Math.Round(DetalleFac.Cantidad.Value).ToString());
                            oInvoice.Lines.UserFields.Fields.Item("U_Tipo").Value         = (DetalleFac.NomPro.ToUpper().Contains("Diesel".ToUpper()) ? "Diesel" : QuitarTilde(DetalleFac.NomPro).ToUpper().Contains("Gasolina 95".ToUpper()) ? "Gasolina 95" : QuitarTilde(DetalleFac.NomPro).ToUpper().Contains("Gasolina 90".ToUpper()) ? "Gasolina 90" : "Gas LP");
                        }

                        oInvoice.Lines.UserFields.Fields.Item("U_REFFAC").Value   = item.NumFactura.ToString();
                        oInvoice.Lines.UserFields.Fields.Item("U_FechaFac").Value = item.FecFactura;

                        switch (item.CodProveedor.Replace("-", "").Replace("-", "").Length)
                        {
                        case 8:
                        {
                            oInvoice.Lines.UserFields.Fields.Item("U_Tipoid").Value = "1";
                            break;
                        }

                        case 9:
                        {
                            oInvoice.Lines.UserFields.Fields.Item("U_Tipoid").Value = "1";
                            break;
                        }

                        case 10:
                        {
                            oInvoice.Lines.UserFields.Fields.Item("U_Tipoid").Value = "3";
                            break;
                        }

                        case 14:
                        {
                            oInvoice.Lines.UserFields.Fields.Item("U_Tipoid").Value = "2";
                            break;
                        }

                        case 15:
                        {
                            oInvoice.Lines.UserFields.Fields.Item("U_Tipoid").Value = "2";
                            break;
                        }

                        default:
                        {
                            oInvoice.Lines.UserFields.Fields.Item("U_Tipoid").Value = "1";
                            break;
                        }
                        }

                        oInvoice.Lines.UserFields.Fields.Item("U_RUC").Value       = item.CodProveedor.Split('[')[0];
                        oInvoice.Lines.UserFields.Fields.Item("U_DV").Value        = item.CodProveedor.Split('[')[1];
                        oInvoice.Lines.UserFields.Fields.Item("U_Proveedor").Value = item.NomProveedor;
                    }


                    oInvoice.Lines.Add();

                    i++;
                }


                //Preguntar por el pais
                if (Pais == "C")
                {
                    if (imp1 > 0)
                    {
                        oInvoice.Lines.SetCurrentLine(i);
                        oInvoice.Lines.ItemDescription = "Impuesto 1";
                        oInvoice.Lines.LineTotal       = Convert.ToDouble(imp1);
                        oInvoice.Lines.TaxCode         = param.IMPEX;
                        oInvoice.Lines.AccountCode     = param.CI1;

                        oInvoice.Lines.Add();
                        i++;
                    }

                    if (imp2 > 0)
                    {
                        oInvoice.Lines.SetCurrentLine(i);
                        oInvoice.Lines.ItemDescription = "Impuesto 2";
                        oInvoice.Lines.LineTotal       = Convert.ToDouble(imp2);
                        oInvoice.Lines.TaxCode         = param.IMPEX;
                        oInvoice.Lines.AccountCode     = param.CI2;
                        oInvoice.Lines.Add();
                        i++;
                    }

                    if (imp4 > 0)
                    {
                        oInvoice.Lines.SetCurrentLine(i);
                        oInvoice.Lines.ItemDescription = "Impuesto 4";
                        oInvoice.Lines.LineTotal       = Convert.ToDouble(imp4);
                        oInvoice.Lines.TaxCode         = param.IMPEX;
                        oInvoice.Lines.AccountCode     = param.CI4;
                        oInvoice.Lines.Add();
                        i++;
                    }

                    if (imp8 > 0)
                    {
                        oInvoice.Lines.SetCurrentLine(i);
                        oInvoice.Lines.ItemDescription = "Impuesto 8";
                        oInvoice.Lines.LineTotal       = Convert.ToDouble(imp8);
                        oInvoice.Lines.TaxCode         = param.IMPEX;
                        oInvoice.Lines.AccountCode     = param.CI8;
                        oInvoice.Lines.Add();
                        i++;
                    }

                    if (imp13 > 0)
                    {
                        oInvoice.Lines.SetCurrentLine(i);
                        oInvoice.Lines.ItemDescription = "Impuesto 13";
                        oInvoice.Lines.LineTotal       = Convert.ToDouble(imp13);
                        oInvoice.Lines.TaxCode         = param.IMPEX;
                        oInvoice.Lines.AccountCode     = param.CI13;
                        oInvoice.Lines.Add();
                        i++;
                    }
                }
                else //Panama
                {
                    if (imp1 > 0)
                    {
                        oInvoice.Lines.SetCurrentLine(i);
                        oInvoice.Lines.ItemDescription = "ITBMS(7%)";
                        oInvoice.Lines.LineTotal       = Convert.ToDouble(imp1);
                        oInvoice.Lines.VatGroup        = param.IMPEX;
                        //oInvoice.Lines.TaxCode = param.IMPEX;
                        oInvoice.Lines.AccountCode = param.CI1;

                        oInvoice.Lines.Add();
                        i++;
                    }

                    if (imp2 > 0)
                    {
                        oInvoice.Lines.SetCurrentLine(i);
                        oInvoice.Lines.ItemDescription = "ITBMS(10%)";
                        oInvoice.Lines.LineTotal       = Convert.ToDouble(imp2);
                        oInvoice.Lines.VatGroup        = param.IMPEX;
                        // oInvoice.Lines.TaxCode = param.IMPEX;
                        oInvoice.Lines.AccountCode = param.CI2;
                        oInvoice.Lines.Add();
                        i++;
                    }
                }



                var respuesta = oInvoice.Add();
                G.GuardarTxt("ErrorSAP.txt", "Respuesta: " + respuesta.ToString());
                if (respuesta == 0)
                {
                    var docEntry = Conexion.Company.GetNewObjectKey();

                    db.Entry(Cierre).State = EntityState.Modified;
                    Cierre.ProcesadaSAP    = true;
                    db.SaveChanges();
                    resp = new
                    {
                        DocEntry = docEntry,
                        //  Series = pedido.Series.ToString(),
                        Type    = "oPurchaiseInvoice",
                        Status  = 1,
                        Message = "Factura creada exitosamente",
                        User    = Conexion.Company.UserName
                    };
                    G.CerrarConexionAPP(db);
                    Conexion.Desconectar();
                    return(Request.CreateResponse(HttpStatusCode.OK, resp));
                }

                BitacoraErrores be = new BitacoraErrores();
                be.Descripcion = Conexion.Company.GetLastErrorDescription();
                be.StackTrace  = Conexion.Company.UserName;
                be.Metodo      = "Insercion de Asiento";
                be.Fecha       = DateTime.Now;
                db.BitacoraErrores.Add(be);
                db.SaveChanges();
                resp = new
                {
                    //   Series = pedido.Series.ToString(),
                    DocEntry = 0,
                    Type     = "oPurchaiseInvoice",
                    Status   = 0,
                    Message  = Conexion.Company.GetLastErrorDescription(),
                    User     = Conexion.Company.UserName
                };



                Conexion.Desconectar();
                G.CerrarConexionAPP(db);

                return(Request.CreateResponse(HttpStatusCode.OK, resp));
            }
            catch (Exception ex)
            {
                resp = new
                {
                    DocEntry = 0,
                    Type     = "oPurchaiseInvoice",
                    Status   = 0,
                    Message  = "[Stack] -> " + ex.StackTrace + " -- [Message] --> " + ex.Message,
                    User     = Conexion.Company.UserName
                };

                BitacoraErrores be = new BitacoraErrores();
                be.Descripcion = ex.Message;
                be.StackTrace  = ex.StackTrace;
                be.Metodo      = "Insercion de Asiento";
                be.Fecha       = DateTime.Now;
                db.BitacoraErrores.Add(be);
                db.SaveChanges();


                Conexion.Desconectar();
                G.CerrarConexionAPP(db);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, resp));
            }
        }