예제 #1
0
        private void btnGuardar_Click(object sender, EventArgs e)
        {
            try {
                EVenta datosVenta = new EVenta();

                datosVenta.IdCartelera.Id_Cartelera       = Convert.ToInt32(txtCartelera.Tag);
                datosVenta.IdCartelera.Id_Pelicula.Nombre = txtCartelera.Text;
                datosVenta.Fecha             = Convert.ToDateTime(dtpFecha.Text);
                datosVenta.Hora              = TimeSpan.Parse(dtpHora.Text);
                datosVenta.NumTicket         = Convert.ToInt32(nudNumTicket.Text);
                datosVenta.CostoTotal        = Convert.ToDecimal(txtCostoTotal.Text);
                datosVenta.IdCartelera.valor = Convert.ToDecimal(txtCostoTotal.Tag);
                NVenta agregarVenta = new NVenta();
                agregarVenta.agregarVenta(datosVenta);
                MessageBox.Show("Se guardo correctamente", "Venta Realizada", MessageBoxButtons.OK, MessageBoxIcon.Information);

                actulizarVenta();
                Limpiar();
                Deshabilitar();
                btncancelar.Enabled  = false;
                btnCartelera.Enabled = false;
                btnGuardar.Enabled   = false;
                btnImprimir.Enabled  = true;
                btnnuevo.Enabled     = true;
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }
        }
예제 #2
0
        public int Insertar(EVenta beventa)
        {
            try
            {
                if (beventa == null)
                {
                    return(0);
                }

                if (String.IsNullOrEmpty(beventa.Dni))
                {
                    throw new WebFaultException <string>("Debe ingresar el Cliente", HttpStatusCode.InternalServerError);
                }

                if (beventa.Monto == 0)
                {
                    throw new WebFaultException <string>("El monto debe ser mayor a Cero", HttpStatusCode.InternalServerError);
                }


                int idventa;
                idventa = dao.Insertar(beventa);
                return(idventa);
            }
            catch (WebException ex)
            {
                throw new WebFaultException <string>(ex.ToString(), HttpStatusCode.InternalServerError);
            }
        }
예제 #3
0
        public List <EVenta> Listar()
        {
            List <EVenta> List = new List <EVenta>();

            try
            {
                DataTable data = new DataTable();
                data = Conexion.ExecuteProcedureD("USP_S_ListarVentas").Tables[0];
                foreach (DataRow row in data.Rows)
                {
                    EVenta be = new EVenta
                    {
                        ID              = Convert.ToInt32(row[0]),
                        Cliente         = Convert.ToInt32(row[1]),
                        Empleado        = Convert.ToInt32(row[2]),
                        TipoComprobante = row[3].ToString(),
                        Serie           = row[4].ToString(),
                        Numero          = row[5].ToString(),
                        Fecha           = Convert.ToDateTime(row[6]),
                        //Hora = Convert.ToDateTime(row[7]),
                        SubTotal = Convert.ToDouble(row[8]),
                        Igv      = Convert.ToDouble(row[9]),
                        Total    = Convert.ToDouble(row[10]),
                        Estado   = Convert.ToInt32(row[11])
                    };
                    List.Add(be);
                }
            }
            catch
            {
                Console.WriteLine("No se encontro Procedimiento Almacenado");
            }
            return(List);
        }
예제 #4
0
        public void agregarVenta(EVenta nuevaVenta)
        {
            if (nuevaVenta.IdCartelera.Id_Cartelera == 0)
            {
                throw new ArgumentException("Ingresa el Id de la cartelera");
            }
            if (nuevaVenta.Fecha == null)
            {
                throw new ArgumentException("Seleccione la fecha de la venta");
            }
            if (nuevaVenta.Hora == null)
            {
                throw new ArgumentException("Selecciona la hora de la venta");
            }
            if (nuevaVenta.NumTicket == 0)
            {
                throw new ArgumentException("Defina la cantidad de boletos a vender");
            }
            if (nuevaVenta.CostoTotal == 0)
            {
                throw new ArgumentException("Defina el monto de la venta");
            }

            DVenta gestionVenta = new DVenta();

            gestionVenta.agregarVenta(nuevaVenta);
        }
예제 #5
0
        public List <EVenta> BuscarEntreFechas(DateTime fecInicio, DateTime fecFinal)
        {
            var cadena = ConfigurationManager.ConnectionStrings["Cnn"].ConnectionString;
            var lista  = new List <EVenta>();

            using (var cn = new SqlConnection(cadena))
            {
                try
                {
                    if (cn.State == ConnectionState.Closed)
                    {
                        cn.Open();
                    }
                    using (var cmd = cn.CreateCommand())
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = "BuscarEntreFechasVentas";

                        cmd.Parameters.AddWithValue("@FecInicio", fecInicio);
                        cmd.Parameters.AddWithValue("@FecFin", fecFinal);

                        var drd = cmd.ExecuteReader();

                        while (drd.Read())
                        {
                            var enti = new EVenta()
                            {
                                IdVenta         = drd.GetInt32(drd.GetOrdinal("IdVenta")),
                                IdCliente       = drd.GetInt32(drd.GetOrdinal("IdCliente")),
                                Cliente         = drd.GetString(drd.GetOrdinal("Cliente")),
                                IdTrabajador    = drd.GetInt32(drd.GetOrdinal("IdTrabajador")),
                                Trabajador      = drd.GetString(drd.GetOrdinal("Trabajador")),
                                Fecha           = drd.GetDateTime(drd.GetOrdinal("Fecha")),
                                TipoComprobante = drd.GetString(drd.GetOrdinal("TipoComprobante")),
                                Serie           = drd.GetString(drd.GetOrdinal("Serie")),
                                Correlativo     = drd.GetString(drd.GetOrdinal("Correlativo")),
                                Igv             = drd.GetDecimal(drd.GetOrdinal("Igv")),
                                Total           = drd.GetDecimal(drd.GetOrdinal("Total"))
                            };
                            lista.Add(enti);
                        }
                    }
                }
                catch (SqlException e)
                {
                    MessageBox.Show(e.Message, "SQL Error Buscar Venta por fechas", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (cn.State == ConnectionState.Open)
                    {
                        cn.Close();
                    }
                }
            }
            return(lista);
        }
예제 #6
0
파일: BVenta.cs 프로젝트: Jmezas/express
 public string RegistrarPost(EVenta oDatos, List <EPago> pago, List <EVentaDetalle> Detalle, string Usuario)
 {
     try
     {
         return(Data.RegistrarPost(oDatos, pago, Detalle, Usuario));
     }
     catch (Exception ex)
     {
         return(ex.Message);
     }
 }
예제 #7
0
 public int RegistrarVenta(EVenta entidad)
 {
     if (Validar(entidad))
     {
         return(venta.Registrar(entidad));
     }
     else
     {
         return(0);
     }
 }
예제 #8
0
 public string elimiarVenta(EVenta oDatos, List <EVentaDetalle> Detalle, string usuario)
 {
     try
     {
         return(Data.elimiarVenta(oDatos, Detalle, usuario));
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
예제 #9
0
 public string RegistrarVenta(EVenta oDatos, List <EVentaDetalle> Detalle, string Usuario, string tipoSistema, string rutaComprobantes, string rutaServidor, string claveCertificado)
 {
     try
     {
         return(Data.RegistrarVenta(oDatos, Detalle, Usuario, tipoSistema, rutaComprobantes, rutaServidor, claveCertificado));
     }
     catch (Exception ex)
     {
         return(ex.Message);;
     }
 }
예제 #10
0
        public List <EVenta> ListarBoletaResumen(int Comienzo, int Medida, int empresa, int Sucursal, string FechaEmi)
        {
            List <EVenta> oDatos = new List <EVenta>();

            using (var Connection = GetConnection(BaseDeDatos))
            {
                try
                {
                    Connection.Open();
                    SetQuery("FAC_ResumenComprobantePorSerie");
                    CreateHelper(Connection);
                    AddInParameter("@iComienzo", Comienzo);
                    AddInParameter("@iMedida", Medida);
                    AddInParameter("@iSucursal", Sucursal);
                    AddInParameter("@iEmpresa", empresa);
                    AddInParameter("@fechaEmi", FechaEmi);
                    using (var Reader = ExecuteReader())
                    {
                        while (Reader.Read())
                        {
                            EVenta oComprobante = new EVenta();
                            oComprobante.Id               = int.Parse(Reader["iidVenta"].ToString());
                            oComprobante.serie            = (Reader["sSerie"].ToString());
                            oComprobante.numero           = (Reader["iNumero"].ToString());
                            oComprobante.Documento.Nombre = (Reader["stipoDocumento"].ToString());
                            oComprobante.grabada          = float.Parse(Reader["OpeGrabada"].ToString());
                            oComprobante.inafecta         = float.Parse(Reader["OpeInafecta"].ToString());
                            oComprobante.exonerada        = float.Parse(Reader["OpeExoneradas"].ToString());
                            oComprobante.gratuita         = float.Parse(Reader["OpeGratuita"].ToString());
                            oComprobante.descuento        = float.Parse(Reader["TotalDescuento"].ToString());
                            oComprobante.igv              = float.Parse(Reader["nIgvCab"].ToString());
                            oComprobante.total            = float.Parse(Reader["nTotalCab"].ToString());
                            oComprobante.fechaEmision     = (Reader["dFecEmision"].ToString());
                            oComprobante.TotalR           = int.Parse(Reader["Total"].ToString());
                            oDatos.Add(oComprobante);
                        }
                    }
                }
                catch (Exception Exception)
                {
                    throw Exception;
                }
                finally
                {
                    Connection.Close();
                }
                return(oDatos);
            }
        }
        public void CalcularTotalPorIngresoDeProducto()
        {
            EDetalleVenta        detalleProducto      = new EDetalleVenta();
            List <EDetalleVenta> listaDetalleProducto = new List <EDetalleVenta>();
            EVenta lineaDeVenta = new EVenta();

            detalleProducto.Precio   = 20;
            detalleProducto.Cantidad = 5;
            double valorEsperado = 100;

            listaDetalleProducto.Add(detalleProducto);
            lineaDeVenta.ListaDetalleProducto = listaDetalleProducto;

            double total = lineaDeVenta.CalcularTotalPorIngresoDeProducto();

            Assert.AreEqual(valorEsperado, total);
        }
예제 #12
0
 public bool Agregar(EVenta obj)
 {
     SQLParameter[] parameters = new SQLParameter[11];
     parameters[0]  = new SQLParameter("@Cliente", obj.Cliente, SqlDbType.Int);
     parameters[1]  = new SQLParameter("@Empleado", obj.Empleado, SqlDbType.Int);
     parameters[2]  = new SQLParameter("@TipoComprobante", obj.TipoComprobante, SqlDbType.VarChar);
     parameters[3]  = new SQLParameter("@Serie", obj.Serie, SqlDbType.VarChar);
     parameters[4]  = new SQLParameter("@Numero", obj.Numero, SqlDbType.VarChar);
     parameters[5]  = new SQLParameter("@Fecha", obj.Fecha, SqlDbType.Date);
     parameters[6]  = new SQLParameter("@Hora", DBNull.Value, SqlDbType.Time);
     parameters[7]  = new SQLParameter("@SubTotal", obj.SubTotal, SqlDbType.Decimal);
     parameters[8]  = new SQLParameter("@Igv", obj.Igv, SqlDbType.Decimal);
     parameters[9]  = new SQLParameter("@Total", obj.Total, SqlDbType.Decimal);
     parameters[10] = new SQLParameter("@Estado", obj.Estado, SqlDbType.Int);
     Response       = Conexion.ExecuteProcedureB("USP_I_AgregarVenta", parameters);
     return(Response);
 }
예제 #13
0
        public int Registrar(EVenta entidad)
        {
            var cadena   = ConfigurationManager.ConnectionStrings["Cnn"].ConnectionString;
            int idUltimo = 0;

            using (var cn = new SqlConnection(cadena))
            {
                try
                {
                    if (cn.State == ConnectionState.Closed)
                    {
                        cn.Open();
                    }
                    using (var cmd = cn.CreateCommand())
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = "RegistrarVenta";

                        cmd.Parameters.AddWithValue("@IdCliente", entidad.IdCliente);
                        cmd.Parameters.AddWithValue("@IdTrabajador", entidad.IdTrabajador);
                        cmd.Parameters.AddWithValue("@Fecha", entidad.Fecha);
                        cmd.Parameters.AddWithValue("@TipoComprobante", entidad.TipoComprobante);
                        cmd.Parameters.AddWithValue("@Serie", entidad.Serie);
                        cmd.Parameters.AddWithValue("@Correlativo", entidad.Correlativo);
                        cmd.Parameters.AddWithValue("@Igv", entidad.Igv);
                        cmd.Parameters.Add("@IdUltimo", SqlDbType.Int).Direction = ParameterDirection.Output;

                        cmd.ExecuteNonQuery();

                        idUltimo = int.Parse(cmd.Parameters["@IdUltimo"].Value.ToString());
                    }
                }
                catch (SqlException e)
                {
                    MessageBox.Show(e.Message, "SQL Error Registrar Venta", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (cn.State == ConnectionState.Open)
                    {
                        cn.Close();
                    }
                }
            }
            return(idUltimo);
        }
예제 #14
0
        public List <EVenta> ListarBoletaResumen(int Comienzo, int Medida, int empresa, int Sucursal, string FechaEmi, int tipo)
        {
            List <EVenta> oDatos = new List <EVenta>();

            using (var Connection = GetConnection(BaseDeDatos))
            {
                try
                {
                    Connection.Open();
                    SetQuery("FAC_FiltrarBoleta");
                    CreateHelper(Connection);
                    AddInParameter("@iComienzo", Comienzo);
                    AddInParameter("@iMedida", Medida);
                    AddInParameter("@iSucursal", Sucursal);
                    AddInParameter("@iEmpresa", empresa);
                    AddInParameter("@fechaEmi", FechaEmi);
                    AddInParameter("@Tipo", tipo);
                    using (var Reader = ExecuteReader())
                    {
                        while (Reader.Read())
                        {
                            EVenta oComprobante = new EVenta();
                            oComprobante.Id               = int.Parse(Reader["iIdVenta"].ToString());
                            oComprobante.empresa.RUC      = Reader["sRuc"].ToString();
                            oComprobante.Documento.Nombre = Reader["stipoDocumento"].ToString();
                            oComprobante.serie            = Reader["serie"].ToString();
                            oComprobante.fechaEmision     = Reader["dFecEmision"].ToString();
                            oComprobante.tipo             = int.Parse(Reader["tipo"].ToString());
                            oComprobante.total            = float.Parse(Reader["nTotalCab"].ToString());
                            oComprobante.TotalR           = int.Parse(Reader["Total"].ToString());
                            oDatos.Add(oComprobante);
                        }
                    }
                }
                catch (Exception Exception)
                {
                    throw Exception;
                }
                finally
                {
                    Connection.Close();
                }
                return(oDatos);
            }
        }
예제 #15
0
        public int Insertar(EVenta venta)
        {
            string sql = "insert into Venta ([Dni],[Fecha],[TipoDoc],[NroDoc],[Serie],[Monto],[Estado],[Cliente],[FormaPago]) values (@dni,GETDATE(),@tipodoc,@nrodoc,@serie,@monto,@estado,@cliente,@formapago)";

            int idventa = 0;

            try
            {
                using (SqlConnection con = new SqlConnection(cadenaconexion))
                {
                    con.Open();
                    using (SqlCommand com = new SqlCommand(sql, con))
                    {
                        com.Parameters.Add(new SqlParameter("@dni", venta.Dni));
                        com.Parameters.Add(new SqlParameter("@tipodoc", venta.TipoDoc));
                        com.Parameters.Add(new SqlParameter("@nrodoc", venta.NroDoc));
                        com.Parameters.Add(new SqlParameter("@serie", venta.Serie));
                        com.Parameters.Add(new SqlParameter("@monto", venta.Monto));
                        com.Parameters.Add(new SqlParameter("@estado", venta.Estado));
                        com.Parameters.Add(new SqlParameter("@cliente", venta.Cliente));
                        com.Parameters.Add(new SqlParameter("@formapago", venta.FormaPago));
                        com.ExecuteNonQuery();
                    }

                    using (SqlCommand com = new SqlCommand("select max(idventa) from venta", con))
                    {
                        using (SqlDataReader dr = com.ExecuteReader())
                        {
                            while (dr.Read())
                            {
                                idventa = Convert.ToInt32(dr[0]);
                            }
                            dr.Close();
                        }
                    }
                }
                return(idventa);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #16
0
        private bool Validar(EVenta entidad)
        {
            builder.Clear();

            if (string.IsNullOrEmpty(entidad.Serie))
            {
                builder.Append("Ingrese la serie");
            }
            if (string.IsNullOrEmpty(entidad.Correlativo))
            {
                builder.Append("\nIngrese el correlativo");
            }
            if (entidad.Igv < 0)
            {
                builder.Append("\nIngrese un IGV válido");
            }

            return(builder.Length == 0);
        }
예제 #17
0
        public List <EVenta> Modificar(EVenta beventa)
        {
            /*
             * Estados:
             * 0: Venta
             * 1: Contabilizado
             * 2: Anulado
             */
            if (beventa == null)
            {
                beventa = new EVenta {
                    IdVenta = 0, Estado = 0
                };
            }

            List <EVenta> obobVenta = new List <EVenta>();

            obobVenta = dao.Listar("4", beventa.IdVenta.ToString(), beventa.Fecha.ToString("yyyyMMdd"));

            if (obobVenta.Count() == 0)
            {
                throw new WebFaultException <string>("No Existe la Venta según los parámetros ingresados", HttpStatusCode.InternalServerError);
            }

            string estado = obobVenta[0].Estado.ToString();

            if (estado.Equals("1"))
            {
                throw new WebFaultException <string>("No se puede Anular una Venta con estado Contabilizado", HttpStatusCode.InternalServerError);
            }
            if (estado.Equals("2"))
            {
                throw new WebFaultException <string>("No se puede anular una venta ya anulada", HttpStatusCode.InternalServerError);
            }

            List <EVenta> obobVentaresult = new List <EVenta>();

            obobVentaresult = dao.Modificar(beventa);


            return(obobVentaresult);
        }
예제 #18
0
파일: NVenta.cs 프로젝트: sammymdp/Ordeeno
 public void Editar(EVenta d)
 {
     try
     {
         using (this.dt = new DatoSistemasDataContext())
         {
             this.dt.sp_ven_edit(d.Ven_codigo, d.Per_codigo, d.Ven_estado, d.Ven_descuento, d.Ven_date);
         }
     }
     catch (System.Data.SqlClient.SqlException ex)
     {
         Datos.Excepciones.Gestionar(ex, "Venta");
         throw new Exception(Datos.Excepciones.MensajePersonalizado);
     }
     catch (Exception ex)
     {
         Datos.Excepciones.Gestionar(ex);
         throw new Exception(Datos.Excepciones.MensajePersonalizado);
     }
 }
예제 #19
0
 public void agregarVenta(EVenta nuevaVenta)
 {
     try {
         SqlConnection conexion = new SqlConnection(Properties.Settings.Default.CadenaConexion);
         SqlCommand    comando  = new SqlCommand();
         comando.CommandType = CommandType.StoredProcedure;
         comando.CommandText = "INSERTAR_VENTAS";
         comando.Parameters.AddWithValue("@Id_Cartelera", nuevaVenta.IdCartelera.Id_Cartelera);
         comando.Parameters.AddWithValue("@Fecha", nuevaVenta.Fecha);
         comando.Parameters.AddWithValue("@Hora", nuevaVenta.Hora);
         comando.Parameters.AddWithValue("@Num_ticket", nuevaVenta.NumTicket);
         comando.Parameters.AddWithValue("@Costo_total", nuevaVenta.CostoTotal);
         comando.Connection = conexion;
         conexion.Open();
         comando.ExecuteNonQuery();
         conexion.Close();
     }
     catch (Exception ex) {
         throw ex;
     }
 }
예제 #20
0
        public List <EVenta> Modificar(EVenta venta)
        {
            /*
             * Estados:
             * 0: Venta
             * 1: Contabilizado
             * 2: Anulado
             */
            List <EVenta> resultado = new List <EVenta>();
            string        sql       = "update venta set Estado=@estado where Idventa=@idventa ";

            /*
             * string sql = "";
             * if (venta.Estado ==0)
             *  sql = "update venta set Estado=2 where Idventa=@idventa ";
             * else
             *  sql = "update venta set Estado=@estado where Idventa=@idventa ";*/
            try
            {
                using (SqlConnection con = new SqlConnection(cadenaconexion))
                {
                    con.Open();
                    using (SqlCommand com = new SqlCommand(sql, con))
                    {
                        com.Parameters.Add(new SqlParameter("@idventa", venta.IdVenta));
                        com.Parameters.Add(new SqlParameter("@estado", venta.Estado));
                        com.ExecuteNonQuery();
                    }
                }
                resultado = Listar("4", venta.IdVenta.ToString(), venta.Fecha.ToString("yyyyMMdd"));
                return(resultado);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #21
0
        public List <EVenta> BuscarxFecha(DateTime FirstDate, DateTime LastDate)
        {
            List <EVenta> List = new List <EVenta>();

            try
            {
                SQLParameter[] parameters = new SQLParameter[2];
                parameters[0] = new SQLParameter("@FirstDate", FirstDate, SqlDbType.Date);
                parameters[1] = new SQLParameter("@LastDate", LastDate, SqlDbType.Date);
                DataTable data = new DataTable();
                data = Conexion.ExecuteProcedureD("USP_S_ListarVentaxFecha", parameters).Tables[0];
                foreach (DataRow row in data.Rows)
                {
                    EVenta be = new EVenta
                    {
                        ID              = Convert.ToInt32(row[0]),
                        Cliente         = Convert.ToInt32(row[1]),
                        Empleado        = Convert.ToInt32(row[2]),
                        TipoComprobante = row[3].ToString(),
                        Serie           = row[4].ToString(),
                        Numero          = row[5].ToString(),
                        Fecha           = Convert.ToDateTime(row[6]),
                        //Hora = Convert.ToDateTime(row[7]),
                        SubTotal = Convert.ToDouble(row[8]),
                        Igv      = Convert.ToDouble(row[9]),
                        Total    = Convert.ToDouble(row[10]),
                        Estado   = Convert.ToInt32(row[11])
                    };
                    List.Add(be);
                }
            }
            catch
            {
                Console.WriteLine("No se encontro Procedimiento Almacenado");
            }
            return(List);
        }
        private void GuardarVenta()
        {
            string tipocomprobante  = CbxTipoComprobante.SelectedValue.ToString();
            string ventaserie       = "####";
            string ventacorrelativo = "########";
            NVenta venta            = new NVenta();

            if (venta.ObtenerSerieCorrelativo(tipocomprobante) != null)
            {
                DataRow row = venta.ObtenerSerieCorrelativo(tipocomprobante);
                ventaserie       = row["Serie"].ToString();
                ventacorrelativo = row["Correlativo"].ToString();
            }
            EVenta beVenta = new EVenta
            {
                Cliente         = Convert.ToInt32(LblIDCliente.Text),
                Empleado        = Frm_Principal.AccesoUsernameID,
                TipoComprobante = tipocomprobante,
                Serie           = ventaserie,
                Numero          = ventacorrelativo,
                Fecha           = Convert.ToDateTime(DateTime.Now),
                Hora            = Convert.ToDateTime(DateTime.Now),
                SubTotal        = Venta_SubTotal,
                Igv             = Venta_Igv,
                Total           = Venta_Total,
                Estado          = 1
            };
            NVenta boVenta = new NVenta();

            if (boVenta.Agregar(beVenta) == true)
            {
                if (MLVDetalle.Items.Count > 0)
                {
                    NDetalleVenta boDetalleVenta = new NDetalleVenta();
                    foreach (ListViewItem items in MLVDetalle.Items)
                    {
                        EDetalleVenta beDetalleVenta = new EDetalleVenta
                        {
                            Serie    = beVenta.Serie,
                            Numero   = beVenta.Numero,
                            Producto = items.SubItems[0].Text,
                            Precio   = Convert.ToDouble(items.SubItems[3].Text),
                            Cantidad = Convert.ToInt32(items.SubItems[4].Text),
                            Importe  = Convert.ToDouble(items.SubItems[5].Text)
                        };
                        //Agregar dettalle compra
                        if (boDetalleVenta.Agregar(beDetalleVenta) == true)
                        {
                            int    cantidadfinal      = 0;
                            double costounitariofinal = 0;
                            double costototalfinal    = 0;
                            //Obteniendo Ultimo Movimiento
                            NMovimiento boM   = new NMovimiento();
                            EMovimiento datos = boM.SeleccionarUltimoMovimientoProducto(beDetalleVenta.Producto);
                            if (!string.IsNullOrEmpty(datos.Producto))
                            {
                                //Si hay datos
                                cantidadfinal      = datos.CantidadFinal - beDetalleVenta.Cantidad;
                                costounitariofinal = datos.CostoUnitarioFinal;
                                double costofinaly = Math.Round((costounitariofinal * beDetalleVenta.Cantidad), 2);
                                costototalfinal = datos.CostoTotalFinal - costofinaly;
                                //Movimiento
                                EMovimiento beMovimiento = new EMovimiento
                                {
                                    Fecha                = DateTime.Now,
                                    TipoComprobante      = beVenta.TipoComprobante,
                                    Serie                = beVenta.Serie,
                                    Numero               = beVenta.Numero,
                                    TipoOperacion        = "01",
                                    Producto             = beDetalleVenta.Producto,
                                    CantidadEntrada      = 0,
                                    CostoUnitarioEntrada = 0,
                                    CostoTotalEntrada    = 0,

                                    CantidadSalida      = beDetalleVenta.Cantidad,
                                    CostoUnitarioSalida = costounitariofinal,
                                    CostoTotalSalida    = costofinaly,

                                    CantidadFinal      = cantidadfinal,
                                    CostoUnitarioFinal = costounitariofinal,
                                    CostoTotalFinal    = costototalfinal
                                };
                                NMovimiento boMovimiento = new NMovimiento();
                                if (boMovimiento.Agregar(beMovimiento) == true)
                                {
                                    EInventario beInventario = new EInventario
                                    {
                                        Producto        = beMovimiento.Producto,
                                        ValorUnitario   = beMovimiento.CostoUnitarioFinal,
                                        Existencias     = beMovimiento.CantidadFinal,
                                        ValorInventario = beMovimiento.CostoTotalFinal
                                    };
                                    NInventario boInventario = new NInventario();
                                    boInventario.Modificar(beInventario);
                                }
                            }
                        }
                    }
                }
                //message
                Frm_Buscar_venta frm = Owner as Frm_Buscar_venta;
                frm.Listar();
                Close();
                Frm_Principal.Main.ChangeMessage("La Venta se ingreso correctamente", "Success");
            }
            else
            {
                Frm_Principal.Main.ChangeMessage("Algo salio mal", "Failed");
            }
        }
예제 #23
0
        /// <summary>
        ///
        /// </summary>
        public override void Ejecutar()
        {
            log.Info("[CmdPagarVenta] Pago Ingresado: " + solicitud.ValorEntrada);

            bool implementaImpuestoCompuesto = Entorno.Instancia.Parametros.ObtenerValorParametro <bool>("pdv.definicion_impuesto_compuesta");
            bool obligaIngresarValor         = Entorno.Instancia.Parametros.ObtenerValorParametro <bool>("pdv.pago.obliga_ingresar_valor");

            //copia de seguridad de venta por si algo falla.
            string jsonCopiaVenta = JsonConvert.SerializeObject(Entorno.Instancia.Venta, Formatting.Indented);

            //string jsonCopiaImpuestos = JsonConvert.SerializeObject(Entorno.Instancia.Venta.ImpuestosIncluidos, Formatting.Indented);
            var copiaImpuestosIncluidos = Entorno.Instancia.Venta.ImpuestosIncluidos;

            try
            {
                #region valida entrada de pago

                //obtiene el valor ingresado para pagar la venta.
                decimal pago    = -1;
                string  entrada = solicitud.ValorEntrada;

                if (string.IsNullOrEmpty(entrada))
                {
                    if (this.solicitud.Pago != null)
                    {
                        pago = this.solicitud.Pago.Valor;
                        if (pago == 0)
                        {
                            pago = Entorno.Instancia.Vista.PanelPago.VisorCliente.Total;
                            this.solicitud.Pago.Valor = pago;
                        }
                    }
                    else
                    {
                        if (obligaIngresarValor)
                        {
                            Entorno.Instancia.Vista.PanelOperador.MensajeOperador = "Debe ingresar un valor a pagar.";
                            log.Warn("Se obliga a ingresar un valor a pagar.");

                            //
                            Solicitudes.SolicitudPanelPago solVolver = new Solicitudes.SolicitudPanelPago(Enums.Solicitud.Pagar, "Debe ingresar un valor a pagar.");
                            Reactor.Instancia.Procesar(solVolver);
                            return;
                        }
                        else
                        {
                            //Toma el total de la venta.
                            pago = Entorno.Instancia.Vista.PanelPago.VisorCliente.Total;
                        }
                    }
                }
                else
                {
                    if (entrada == "VentaPagada")
                    {
                        //Se calcula el total ($) de artículos cancelados + el total de pagos realizados.
                        log.Info("La venta ha sido pagada, se finaliza de la venta.");
                        decimal totalPagos = (Entorno.Instancia.Venta.Pagos.Sum(p => p.Valor));
                        pago = totalPagos;
                    }
                    else if (!decimal.TryParse(entrada, out pago))
                    {
                        log.Warn("El valor ingresado no es válido");
                        Entorno.Instancia.Vista.PanelPago.VisorMensaje = "El valor ingresado no es válido";
                    }
                }

                if (pago <= 0)
                {
                    log.WarnFormat("Monto no válido [{0}]", pago);
                    Entorno.Instancia.Vista.PanelPago.VisorMensaje = "Monto no válido";
                    //
                    SolicitudPanelPago volver = new SolicitudPanelPago(Enums.Solicitud.Pagar, "Monto no válido");
                    Reactor.Instancia.Procesar(volver);
                    return;
                }
                else
                {
                    this.ValorPago = pago;
                }

                #endregion


                //valida el total de la venta.

                //pago total de la venta
                Respuesta respuesta = new Respuesta();
                if (this.ValorPago == Entorno.Instancia.Venta.PorPagar)
                {
                    //
                    EMedioPago medioPago = null;
                    EPago      ePago     = null;
                    if (this.solicitud.Pago != null)
                    {
                        ePago     = this.solicitud.Pago;
                        medioPago = ePago.MedioPago;
                    }
                    else
                    {
                        if (this.solicitud.TipoSolicitud == Solicitud.PagoEfectivo)
                        {
                            if (entrada != "VentaPagada")
                            {
                                var medioPagoEfectivo = Entorno.Instancia.MediosPago.Where(m => m.MedioPago == MediosPago.Efectivo);
                                if (!medioPagoEfectivo.IsNullOrEmptyList())
                                {
                                    medioPago = new PMediosPago().GetAllMediosPago().MedioPago(medioPagoEfectivo.FirstOrDefault().CodigoMedioPago);
                                    ePago     = new EPago(medioPago, this.ValorPago);
                                }
                                else
                                {
                                    throw new Exception($"No se encontró medio de pago {MediosPago.Efectivo} configurado en entorno");
                                }
                            }
                        }
                        else
                        {
                            log.Error($"La solicitud contiene un pago nulo o vacío y el medio de pago no efectivo. Solicitud: {this.solicitud}");
                            throw new Exception($"No se encontró medio de pago {MediosPago.Efectivo} configurado en entorno");
                        }
                    }

                    if (entrada != "VentaPagada")
                    {
                        Entorno.Instancia.Venta.AgregarPago(medioPago, ePago, out respuesta);
                        if (respuesta.Valida)
                        {
                            Telemetria.Instancia.AgregaMetrica(new Evento("AgregarPago").AgregarPropiedad("Transaccion", (Entorno.Instancia.Terminal.NumeroUltimaTransaccion + 1)).AgregarPropiedad("Factura", (Entorno.Instancia.Terminal.NumeroUltimaFactura + 1)).AgregarPropiedad("Valor", (ePago.Valor)));
                            log.InfoFormat("[CmdPagarVenta] Pago Agregado: {0}, Transaccion: {1}, Factura {2}", ePago.Valor, (Entorno.Instancia.Terminal.NumeroUltimaTransaccion + 1), (Entorno.Instancia.Terminal.NumeroUltimaFactura + 1));
                        }
                        else
                        {
                            log.WarnFormat("[CmdPagarVenta.Ejecutar] {0}", respuesta.Mensaje);
                            return;
                        }
                    }
                    else
                    {
                        Entorno.Instancia.Venta.PorPagar = 0;
                    }

                    //Validar saldo pendiente por pagar.
                    if (Entorno.Instancia.Venta.PorPagar == 0)
                    {
                        Dictionary <string, string> idsAcumulados = Entorno.Instancia.IdsAcumulados;
                        string factura         = ProcesarPlantilla.Factura(Entorno.Instancia.Venta, Entorno.Instancia.Terminal, Entorno.Instancia.Usuario);
                        string modeloImpresora = Entorno.Instancia.Impresora.Marca ?? "impresora";
                        PVenta venta           = new PVenta();

                        //Log a azure

                        string tirillaActual = "";
                        iu.PanelVentas.Tirilla.ForEach(x =>
                        {
                            tirillaActual += Environment.NewLine;
                            tirillaActual += String.Format("Código: {0}, Descripción: {1} ({4}), Cantidad: {2}, Precio: {3} ", x.Codigo, x.Descripcion, x.Cantidad, x.Subtotal, x.PrecioVentaUnidad);
                        });
                        log.Info("Items tirilla:" + tirillaActual + Environment.NewLine + "Total: " + Entorno.Instancia.Venta.TotalVenta + Environment.NewLine + "Totales Impuestos: " + Entorno.Instancia.Venta.ImpuestosIncluidos.Sum(x => x.Value[2]) + Environment.NewLine + "Cant Artículos Vendidos: " + Entorno.Instancia.Venta.NumeroDeItemsVenta + Environment.NewLine);

                        //
                        log.InfoFormat("[CmdPagarVenta] Venta Finalizada, Transaccion: {0}, Factura {1}", (Entorno.Instancia.Terminal.NumeroUltimaTransaccion + 1), (Entorno.Instancia.Terminal.NumeroUltimaFactura + 1));

                        var tiempoGuardarVenta = new MetricaTemporizador("TerminarVentaFinalizada");

                        venta.GuardarVenta(Entorno.Instancia.Venta, ref idsAcumulados, Entorno.Instancia.Terminal, Entorno.Instancia.Usuario, ((int)TipoTransaccion.Venta).ToString(), factura, modeloImpresora, implementaImpuestoCompuesto, out respuesta);
                        if (respuesta.Valida == false)
                        {
                            Telemetria.Instancia.AgregaMetrica(tiempoGuardarVenta.Para().AgregarPropiedad("Exitoso", false).AgregarPropiedad("Transaccion", (Entorno.Instancia.Terminal.NumeroUltimaTransaccion + 1)).AgregarPropiedad("Factura", (Entorno.Instancia.Terminal.NumeroUltimaFactura + 1)).AgregarPropiedad("TotalVenta", Entorno.Instancia.Venta.TotalVenta).AgregarPropiedad("TotalImpuestoVenta", Entorno.Instancia.Venta.ImpuestosIncluidos.Sum(x => x.Value[2])).AgregarPropiedad("NroArticulosVenta", Entorno.Instancia.Venta.NumeroDeItemsVenta).AgregarPropiedad("Error", respuesta.Mensaje));
                            throw new Exception(respuesta.Mensaje);
                        }
                        else
                        {
                            Telemetria.Instancia.AgregaMetrica(tiempoGuardarVenta.Para().AgregarPropiedad("Exitoso", true).AgregarPropiedad("Transaccion", (Entorno.Instancia.Terminal.NumeroUltimaTransaccion + 1)).AgregarPropiedad("Factura", (Entorno.Instancia.Terminal.NumeroUltimaFactura + 1)).AgregarPropiedad("TotalVenta", Entorno.Instancia.Venta.TotalVenta).AgregarPropiedad("TotalImpuestoVenta", Entorno.Instancia.Venta.ImpuestosIncluidos.Sum(x => x.Value[2])).AgregarPropiedad("NroArticulosVenta", Entorno.Instancia.Venta.NumeroDeItemsVenta));
                            Entorno.Instancia.IdsAcumulados = idsAcumulados;
                            //
                            Entorno.Instancia.Venta.EstaAbierta = false;


                            //
                            respuesta = new Respuesta(false);
                            ETerminal terminal = new PTerminal().BuscarTerminalPorCodigo(Common.Config.Terminal, out respuesta);
                            if (respuesta.Valida)
                            {
                                Entorno.Instancia.Terminal = terminal;

                                string mensaje = string.Empty;

                                //Valida si debe abrir cajón monedero.
                                bool abreCajon         = false;
                                var  mediosPagoEntorno = new PMediosPago().GetAllMediosPago().ListaMediosPago;
                                var  mediosPagoVenta   = (from m in mediosPagoEntorno
                                                          join mp in Entorno.Instancia.Venta.Pagos on m.Codigo.ToLower() equals mp.MedioPago.Codigo.ToLower()
                                                          select m);


                                //Verifica si hay algún medio de pago configurado para abrir cajón entre los pagos realizados.
                                var mediosPagoAbreCajon = mediosPagoVenta.Where(m => m.AbreCajon);
                                if (!mediosPagoAbreCajon.IsNullOrEmptyList())
                                {
                                    abreCajon = true;
                                }
                                else
                                {
                                    if (medioPago != null)
                                    {
                                        abreCajon = medioPago.AbreCajon;
                                    }
                                }

                                //Imprimir
                                Respuesta resImpresion = Entorno.Instancia.Impresora.Imprimir(factura, true, abreCajon);

                                //
                                LimpiarVentaFinalizada();

                                //
                                if (!resImpresion.Valida)
                                {
                                    Entorno.Vista.PanelOperador.MensajeOperador = resImpresion.Mensaje;
                                }


                                //
                                log.Info("[CmdPagarVenta.Ejecutar] --> Transaccion finalizada.");

                                //
                                iu.PanelOperador.CodigoCliente = "";

                                //
                                decimal valorCambio = Entorno.Instancia.Venta.PorPagar * -1;
                                iu.PanelVentas.VisorCliente.Total = 0;
                                iu.PanelVentas.VisorMensaje       = string.Format("Cambio: {0}", valorCambio.ToCustomCurrencyFormat());
                                try
                                {
                                    Respuesta respuesta2;

                                    bool checkFactura = Entorno.Instancia.Terminal.VerificarLimiteNumeracion(out respuesta);
                                    bool checkFecha   = Entorno.Instancia.Terminal.VerificarFechaAutorizacion(out respuesta2);

                                    if (respuesta.Valida && !(respuesta.Mensaje.Equals("")))
                                    {
                                        iu.PanelVentas.VisorMensaje = string.Format("Cambio: {0} - " + respuesta.Mensaje, valorCambio.ToCustomCurrencyFormat());
                                    }
                                    else if (respuesta2.Valida && !(respuesta2.Mensaje.Equals("")))
                                    {
                                        iu.PanelVentas.VisorMensaje = string.Format("Cambio: {0} - " + respuesta2.Mensaje, valorCambio.ToCustomCurrencyFormat());
                                    }

                                    decimal valorLimite = Entorno.Instancia.Parametros.ObtenerValorParametro <Decimal>("pdv.aviso_monto_max_en_caja");
                                    decimal valorCaja   = venta.DineroEnCaja(Entorno.Instancia.Terminal.Codigo, Entorno.Instancia.Usuario.IdUsuario, out respuesta);
                                    log.InfoFormat("[CmdPagarVenta.Ejecutar] --> Valor en caja : {0}, Valor máximo: {1}", valorCaja.ToCustomCurrencyFormat(), valorLimite.ToCustomCurrencyFormat());
                                    if (valorCaja > valorLimite)
                                    {
                                        iu.PanelVentas.VisorMensaje = string.Format("Cambio: {0} - Tope máximo en caja excedido", valorCambio.ToCustomCurrencyFormat());
                                    }
                                }
                                catch (Exception e)
                                {
                                    log.ErrorFormat("[CmdPagarVenta] {0}", e.Message);
                                    Telemetria.Instancia.AgregaMetrica(new Excepcion(e));
                                }

                                //
                                iu.MostrarPanelVenta();
                            }
                        }
                    }
                }
                else if (this.ValorPago < Entorno.Instancia.Venta.PorPagar)
                {
                    //
                    EMedioPago medioPago = null;
                    EPago      ePago     = null;
                    if (this.solicitud.Pago != null)
                    {
                        ePago     = this.solicitud.Pago;
                        medioPago = ePago.MedioPago;
                    }
                    else
                    {
                        medioPago = new PMediosPago().GetAllMediosPago().MedioPago("1");
                        ePago     = new EPago(medioPago, this.ValorPago);
                    }
                    Entorno.Instancia.Venta.AgregarPago(medioPago, ePago, out respuesta);
                    if (!respuesta.Valida)
                    {
                        log.WarnFormat("[CmdPagarVenta.Ejecutar.277] {0}", respuesta.Mensaje);
                        return;
                    }
                    else
                    {
                        // agregar a lista de medio de pago
                        Entorno.Instancia.Vista.PanelPago.AgregarMedioPagoUI(new DTOs.DItemMedioPago {
                            CodigoMedioPago = ePago.MedioPago.Codigo, NombreMedioPago = ePago.MedioPago.Tipo, ValorMedioPago = ePago.Valor
                        });

                        //
                        iu.PanelVentas.VisorCliente.Total = Entorno.Instancia.Venta.PorPagar;
                        iu.PanelPago.VisorCliente.Total   = Entorno.Instancia.Venta.PorPagar;
                        iu.PanelPago.VisorEntrada         = string.Empty;
                        iu.PanelPago.VisorMensaje         = "";

                        //
                        log.InfoFormat("[CmdPagarVenta] Medio de pago agregado. Valor: [{0}]", this.ValorPago.ToCustomCurrencyFormat());

                        if (Reactor.Instancia.EstadoFSMActual != EstadosFSM.Pago)
                        {
                            Solicitudes.SolicitudPanelPago solicitud = new Solicitudes.SolicitudPanelPago(Solicitud.Pagar);
                            Reactor.Instancia.Procesar(solicitud);
                        }

                        //Valida si no está el panel de pago activo.
                        if (!(iu.PanelActivo is IPanelPago))
                        {
                            if (iu.PanelPagoManual != null)
                            {
                                iu.PanelPagoManual.LimpiarPagoFinalizado();
                            }

                            if (Reactor.Instancia.EstadoFSMActual != EstadosFSM.Pago)
                            {
                                Solicitudes.SolicitudPanelPago solicitud = new Solicitudes.SolicitudPanelPago(Solicitud.Pagar);
                                Reactor.Instancia.Procesar(solicitud);
                            }
                        }
                    }
                }
                else if (this.ValorPago > Entorno.Instancia.Venta.PorPagar)
                {
                    //
                    EMedioPago medioPago = null;
                    EPago      ePago     = null;
                    if (this.solicitud.Pago != null)
                    {
                        ePago     = this.solicitud.Pago;
                        medioPago = ePago.MedioPago;
                    }
                    else
                    {
                        medioPago = new PMediosPago().GetAllMediosPago().MedioPago("1");
                        ePago     = new EPago(medioPago, this.ValorPago);
                    }
                    Entorno.Instancia.Venta.AgregarPago(medioPago, ePago, out respuesta);
                    if (!respuesta.Valida)
                    {
                        log.WarnFormat("[CmdPagarVenta.Ejecutar.329] {0}", respuesta.Mensaje);
                        return;
                    }
                    else
                    {
                        //Validar saldo pendiente por pagar.
                        if (Entorno.Instancia.Venta.PorPagar < 0)
                        {
                            Dictionary <string, string> idsAcumulados = Entorno.Instancia.IdsAcumulados;
                            PVenta venta = new PVenta();
                            respuesta = new Respuesta();

                            //
                            string factura         = ProcesarPlantilla.Factura(Entorno.Instancia.Venta, Entorno.Instancia.Terminal, Entorno.Instancia.Usuario);
                            string modeloImpresora = Entorno.Instancia.Impresora.Marca ?? "impresora";

                            //
                            log.InfoFormat("[CmdPagarVenta] Venta Finalizada, Transaccion: {0}, Factura {1}", (Entorno.Instancia.Terminal.NumeroUltimaTransaccion + 1), (Entorno.Instancia.Terminal.NumeroUltimaFactura + 1));

                            string tirillaActual = "";
                            iu.PanelVentas.Tirilla.ForEach(x =>
                            {
                                tirillaActual += Environment.NewLine;
                                tirillaActual += String.Format("Codigo: {0}, Descripción: {1} ({4}), Cantidad: {2}, Precio: {3} ", x.Codigo, x.Descripcion, x.Cantidad, x.Subtotal, x.PrecioVentaUnidad);
                            });
                            log.Info("Items tirilla:" + tirillaActual + Environment.NewLine + "Total: " + Entorno.Instancia.Venta.TotalVenta + Environment.NewLine + "Totales Impuestos: " + Entorno.Instancia.Venta.ImpuestosIncluidos.Sum(x => x.Value[2]) + Environment.NewLine + "Cant Artículos Vendidos: " + Entorno.Instancia.Venta.NumeroDeItemsVenta + Environment.NewLine);

                            var tiempoGuardarVenta = new MetricaTemporizador("TerminarVentaFinalizada");

                            venta.GuardarVenta(Entorno.Instancia.Venta, ref idsAcumulados, Entorno.Instancia.Terminal, Entorno.Instancia.Usuario, ((int)TipoTransaccion.Venta).ToString(), factura, modeloImpresora, implementaImpuestoCompuesto, out respuesta);
                            if (respuesta.Valida == false)
                            {
                                Telemetria.Instancia.AgregaMetrica(tiempoGuardarVenta.Para().AgregarPropiedad("Exitoso", false).AgregarPropiedad("Transaccion", (Entorno.Instancia.Terminal.NumeroUltimaTransaccion + 1)).AgregarPropiedad("Factura", (Entorno.Instancia.Terminal.NumeroUltimaFactura + 1)).AgregarPropiedad("TotalVenta", Entorno.Instancia.Venta.TotalVenta).AgregarPropiedad("TotalImpuestoVenta", Entorno.Instancia.Venta.ImpuestosIncluidos.Sum(x => x.Value[2])).AgregarPropiedad("NroArticulosVenta", Entorno.Instancia.Venta.NumeroDeItemsVenta));
                                throw new Exception(respuesta.Mensaje);
                            }

                            //Log a azure
                            Telemetria.Instancia.AgregaMetrica(tiempoGuardarVenta.Para().AgregarPropiedad("Exitoso", true).AgregarPropiedad("Transaccion", (Entorno.Instancia.Terminal.NumeroUltimaTransaccion + 1)).AgregarPropiedad("Factura", (Entorno.Instancia.Terminal.NumeroUltimaFactura + 1)).AgregarPropiedad("TotalVenta", Entorno.Instancia.Venta.TotalVenta).AgregarPropiedad("TotalImpuestoVenta", Entorno.Instancia.Venta.ImpuestosIncluidos.Sum(x => x.Value[2])).AgregarPropiedad("NroArticulosVenta", Entorno.Instancia.Venta.NumeroDeItemsVenta));

                            //
                            decimal valorCambio = Entorno.Instancia.Venta.PorPagar * -1;

                            //
                            Entorno.Instancia.Impresora.Imprimir(factura, true, medioPago.AbreCajon);

                            //
                            Entorno.Instancia.Venta.EstaAbierta = false;
                            Entorno.Instancia.IdsAcumulados     = idsAcumulados;

                            //
                            respuesta = new Respuesta(false);
                            ETerminal terminal = new PTerminal().BuscarTerminalPorCodigo(Common.Config.Terminal, out respuesta);
                            Entorno.Instancia.Terminal = terminal;

                            //
                            LimpiarVentaFinalizada();

                            //
                            iu.PanelOperador.CodigoCliente = "";

                            //
                            iu.PanelVentas.VisorCliente.Total = 0;
                            iu.PanelVentas.VisorMensaje       = string.Format("Cambio: {0}", valorCambio.ToCustomCurrencyFormat());
                            try
                            {
                                decimal valorLimite = Entorno.Instancia.Parametros.ObtenerValorParametro <Decimal>("pdv.aviso_monto_max_en_caja");
                                decimal valorCaja   = venta.DineroEnCaja(Entorno.Instancia.Terminal.Codigo, Entorno.Instancia.Usuario.IdUsuario, out respuesta);
                                log.InfoFormat("[CmdPagarVenta.Ejecutar] --> Valor en caja : {0}, Valor máximo: {1}", valorCaja.ToCustomCurrencyFormat(), valorLimite.ToCustomCurrencyFormat());
                                if (valorCaja > valorLimite)
                                {
                                    iu.PanelVentas.VisorMensaje = string.Format("Cambio: {0} - Tope máximo en caja excedido", valorCambio.ToCustomCurrencyFormat());
                                }
                            }
                            catch (Exception e)
                            {
                                log.ErrorFormat("[CmdPagarVenta] {0}", e.Message);
                                Telemetria.Instancia.AgregaMetrica(new Excepcion(e));
                            }

                            //
                            log.InfoFormat("[CmdPagarVenta] --> Transaccion finalizada, cambio {0}", valorCambio.ToCustomCurrencyFormat());

                            iu.MostrarPanelVenta();
                        }
                    }
                }
                else if (this.ValorPago == -1)
                {
                    Dictionary <string, string> idsAcumulados = Entorno.Instancia.IdsAcumulados;
                    PVenta venta = new PVenta();
                    respuesta = new Respuesta();
                    //
                    string factura         = ProcesarPlantilla.Factura(Entorno.Instancia.Venta, Entorno.Instancia.Terminal, Entorno.Instancia.Usuario);
                    string modeloImpresora = Entorno.Instancia.Impresora.Marca ?? "impresora";


                    //
                    log.InfoFormat("[CmdPagarVenta] Venta Finalizada, Transaccion: {0}, Factura {1}", (Entorno.Instancia.Terminal.NumeroUltimaTransaccion + 1), (Entorno.Instancia.Terminal.NumeroUltimaFactura + 1));

                    string tirillaActual = "";
                    iu.PanelVentas.Tirilla.ForEach(x =>
                    {
                        tirillaActual += Environment.NewLine;
                        tirillaActual += String.Format("Codigo: {0}, Descripción: {1} ({4}), Cantidad: {2}, Precio: {3} ", x.Codigo, x.Descripcion, x.Cantidad, x.Subtotal, x.PrecioVentaUnidad);
                    });
                    log.Info("Items tirilla:" + tirillaActual + Environment.NewLine + "Total: " + Entorno.Instancia.Venta.TotalVenta + Environment.NewLine + "Totales Impuestos: " + Entorno.Instancia.Venta.ImpuestosIncluidos.Sum(x => x.Value[2]) + Environment.NewLine + "Cant Artículos Vendidos: " + Entorno.Instancia.Venta.NumeroDeItemsVenta + Environment.NewLine);

                    var tiempoGuardarVenta = new MetricaTemporizador("TerminarVentaFinalizada");

                    venta.GuardarVenta(Entorno.Instancia.Venta, ref idsAcumulados, Entorno.Instancia.Terminal, Entorno.Instancia.Usuario, ((int)TipoTransaccion.Venta).ToString(), factura, modeloImpresora, implementaImpuestoCompuesto, out respuesta);
                    if (respuesta.Valida == false)
                    {
                        Telemetria.Instancia.AgregaMetrica(tiempoGuardarVenta.Para().AgregarPropiedad("Exitoso", false).AgregarPropiedad("Transaccion", (Entorno.Instancia.Terminal.NumeroUltimaTransaccion + 1)).AgregarPropiedad("Factura", (Entorno.Instancia.Terminal.NumeroUltimaFactura + 1)).AgregarPropiedad("TotalVenta", Entorno.Instancia.Venta.TotalVenta).AgregarPropiedad("TotalImpuestoVenta", Entorno.Instancia.Venta.ImpuestosIncluidos.Sum(x => x.Value[2])).AgregarPropiedad("NroArticulosVenta", Entorno.Instancia.Venta.NumeroDeItemsVenta));
                        throw new Exception(respuesta.Mensaje);
                    }

                    //Log a azure
                    Telemetria.Instancia.AgregaMetrica(tiempoGuardarVenta.Para().AgregarPropiedad("Exitoso", true).AgregarPropiedad("Transaccion", (Entorno.Instancia.Terminal.NumeroUltimaTransaccion + 1)).AgregarPropiedad("Factura", (Entorno.Instancia.Terminal.NumeroUltimaFactura + 1)).AgregarPropiedad("TotalVenta", Entorno.Instancia.Venta.TotalVenta).AgregarPropiedad("TotalImpuestoVenta", Entorno.Instancia.Venta.ImpuestosIncluidos.Sum(x => x.Value[2])).AgregarPropiedad("NroArticulosVenta", Entorno.Instancia.Venta.NumeroDeItemsVenta));

                    //
                    Entorno.Instancia.Impresora.Imprimir(factura, true, true);


                    if (!string.IsNullOrEmpty(respuesta.Mensaje))
                    {
                        Entorno.Vista.PanelOperador.MensajeOperador = respuesta.Mensaje;
                        log.ErrorFormat("[CmdPagarVenta]: {0}", respuesta.Mensaje);
                    }

                    Entorno.Instancia.IdsAcumulados = idsAcumulados;

                    //
                    Entorno.Instancia.Venta.EstaAbierta = false;

                    //
                    respuesta = new Respuesta(false);
                    ETerminal terminal = new PTerminal().BuscarTerminalPorCodigo(Common.Config.Terminal, out respuesta);
                    Entorno.Instancia.Terminal = terminal;

                    //
                    LimpiarVentaFinalizada();

                    //
                    decimal valorCambio = Entorno.Instancia.Venta.PorPagar * -1;
                    iu.PanelVentas.VisorCliente.Total = 0;
                    iu.PanelVentas.VisorMensaje       = string.Format("Cambio: {0}", valorCambio.ToCustomCurrencyFormat());

                    try
                    {
                        decimal valorLimite = Entorno.Instancia.Parametros.ObtenerValorParametro <Decimal>("pdv.aviso_monto_max_en_caja");
                        decimal valorCaja   = venta.DineroEnCaja(Entorno.Instancia.Terminal.Codigo, Entorno.Instancia.Usuario.IdUsuario, out respuesta);
                        log.InfoFormat("[CmdPagarVenta.Ejecutar] --> Valor en caja : {0}, Valor máximo: {1}", valorCaja.ToCustomCurrencyFormat(), valorLimite.ToCustomCurrencyFormat());
                        if (valorCaja > valorLimite)
                        {
                            iu.PanelVentas.VisorMensaje = string.Format("Cambio: {0} - Tope máximo en caja excedido", valorCambio.ToCustomCurrencyFormat());
                        }
                    }
                    catch (Exception e)
                    {
                        log.ErrorFormat("[CmdPagarVenta] {0}", e.Message);
                        Telemetria.Instancia.AgregaMetrica(new Excepcion(e));
                    }

                    log.InfoFormat("[CmdPagarVenta] --> Transaccion finalizada, cambio {0}", valorCambio.ToCustomCurrencyFormat());

                    //
                    iu.PanelOperador.CodigoCliente = "";

                    iu.MostrarPanelVenta();
                }

                if (respuesta.Valida)
                {
                    iu.MostrarDisplayCliente(DisplayCliente.FinVenta);
                }
            }
            catch (Exception ex)
            {
                //
                Telemetria.Instancia.AgregaMetrica(new Excepcion(ex));
                log.ErrorFormat("[CmdPagarVenta] {0}", ex.Message);

                //
                iu.PanelOperador.MensajeOperador = ex.Message;
                EVenta copiaVenta = JsonConvert.DeserializeObject <EVenta>(jsonCopiaVenta);
                Entorno.Instancia.Venta = copiaVenta;
                Entorno.Instancia.Venta.ImpuestosIncluidos = copiaImpuestosIncluidos;

                //
                Solicitudes.SolicitudPagarVenta solVolver = new Solicitudes.SolicitudPagarVenta(Enums.Solicitud.Pagar, Entorno.Instancia.Vista.PanelPago.VisorEntrada);
                Reactor.Instancia.Procesar(solVolver);
            }
        }
예제 #24
0
        //private string cadenaconexion = "Data Source=LAPTOP-C3204AHJ\\SQLEXPRESS;Initial Catalog=CFFLORESDB;Integrated Security=True";

        public List <EVenta> Listar(string busqueda, string Valor, string fecha)
        {
            List <EVenta> lista = new List <EVenta>();

            string sql = "";

            if (busqueda.Equals("1")) //Listar
            {
                sql = "SELECT * FROM venta where convert(nvarchar(8), fecha, 112) = " + fecha;
            }
            else if (busqueda.Equals("2")) //Por Dni
            {
                sql = "SELECT * FROM venta where dni = " + Valor;
            }
            else if (busqueda.Equals("20")) //Por Dni y fecha
            {
                sql = "SELECT * FROM venta where convert(nvarchar(8), fecha, 112) = " + fecha + " and dni = " + Valor;
            }
            else if (busqueda.Equals("3")) //Por NroVenta
            {
                sql = "SELECT * FROM venta where  NroDoc = " + Valor;
            }
            else if (busqueda.Equals("30")) //Por NroVenta y fecha
            {
                sql = "SELECT * FROM venta where convert(nvarchar(8), fecha, 112) = " + fecha + " and NroDoc = " + Valor;
            }
            else if (busqueda.Equals("4")) //Por idVenta
            {
                sql = "SELECT * FROM venta where  IdVenta = " + Valor;
            }

            try
            {
                using (SqlConnection con = new SqlConnection(cadenaconexion))
                {
                    con.Open();
                    using (SqlCommand com = new SqlCommand(sql, con))
                    {
                        using (SqlDataReader dr = com.ExecuteReader())
                        {
                            while (dr.Read())
                            {
                                EVenta ve = new EVenta();

                                ve.IdVenta   = Convert.ToInt32(dr[0]);
                                ve.Dni       = dr[1].ToString();
                                ve.Fecha     = Convert.ToDateTime(dr[2]);
                                ve.TipoDoc   = dr[3].ToString();
                                ve.NroDoc    = dr[4].ToString();
                                ve.Serie     = dr[5].ToString();
                                ve.Monto     = Convert.ToDecimal(dr[6].ToString());
                                ve.Estado    = Convert.ToInt32(dr[7].ToString());
                                ve.Cliente   = dr[8].ToString();
                                ve.FormaPago = dr[9].ToString();
                                lista.Add(ve);
                            }
                            dr.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(lista);
        }
예제 #25
0
        public override void Ejecutar()
        {
            string jsonCopiaVenta          = JsonConvert.SerializeObject(Entorno.Instancia.Venta, Formatting.Indented);
            var    copiaImpuestosIncluidos = Entorno.Instancia.Venta.ImpuestosIncluidos;

            try
            {
                Respuesta respuesta = new Respuesta(false);
                Core.Solicitudes.SolicitudVolver volver = new Core.Solicitudes.SolicitudVolver(Core.Enums.Solicitud.Volver);

                if (Entorno.Instancia.Venta.Pagos.IsNullOrEmptyList())
                {
                    Reactor.Instancia.Procesar(volver);
                    return;
                }

                if (Entorno.Instancia.Venta.Pagos.Sum(x => x.Valor) == 0)
                {
                    Reactor.Instancia.Procesar(volver);
                    return;
                }

                if (Pago == null)
                {
                    return;
                }

                //
                decimal valorCancelado = Pago.ValorMedioPago;

                if (valorCancelado < 0)
                {
                    Entorno.Instancia.Vista.PanelPago.VisorMensaje = "No se puede cancelar el último pago";
                    //
                    Reactor.Instancia.Procesar(volver);
                    return;
                }
                else if (valorCancelado > 0)
                {
                    decimal valor = Entorno.Instancia.Venta.PorPagar + valorCancelado;
                    if (valor > Entorno.Instancia.Venta.TotalVenta)
                    {
                        Entorno.Instancia.Vista.PanelPago.VisorMensaje = "No se puede cancelar el pago seleccionado";
                        Reactor.Instancia.Procesar(volver);
                        return;
                    }
                }

                //
                EMedioPago medioPago = null;
                EPago      ePago     = null;

                if (Pago != null)
                {
                    medioPago = new PMediosPago().GetAllMediosPago().MedioPago(Pago.CodigoMedioPago);
                }
                else
                {
                    medioPago = new PMediosPago().GetAllMediosPago().MedioPago("1");
                }


                ePago = new EPago(medioPago, -valorCancelado);

                Entorno.Instancia.Venta.AgregarPago(medioPago, ePago, out respuesta);

                // agregar a lista de .medio de pago
                Entorno.Instancia.Vista.PanelPago.AgregarMedioPagoUI(new DTOs.DItemMedioPago {
                    CodigoMedioPago = ePago.MedioPago.Codigo, NombreMedioPago = ePago.MedioPago.Tipo, ValorMedioPago = ePago.Valor
                });

                //
                Telemetria.Instancia.AgregaMetrica(new Evento("CancelarPago").AgregarPropiedad("Transaccion", (Entorno.Instancia.Terminal.NumeroUltimaTransaccion + 1)).AgregarPropiedad("Factura", (Entorno.Instancia.Terminal.NumeroUltimaFactura + 1)).AgregarPropiedad("Valor", (ePago.Valor)));

                log.InfoFormat("[CmdCancelarPago] Pago Cancelado: {0}, Transacción: {1}, Factura {2}", ePago.Valor, (Entorno.Instancia.Terminal.NumeroUltimaTransaccion + 1), (Entorno.Instancia.Terminal.NumeroUltimaFactura + 1));
                if (!respuesta.Valida)
                {
                    throw new Exception(respuesta.Mensaje);
                }
                //
                iu.PanelVentas.VisorCliente.Total = Entorno.Instancia.Venta.PorPagar;
                iu.PanelPago.VisorCliente.Total   = Entorno.Instancia.Venta.PorPagar;
                iu.PanelPago.VisorEntrada         = string.Empty;
                iu.PanelPago.VisorMensaje         = "";

                //
                Reactor.Instancia.Procesar(volver);

                if (respuesta.Valida)
                {
                    iu.MostrarDisplayCliente(DisplayCliente.FinVenta);
                }
            }
            catch (Exception ex)
            {
                //
                Telemetria.Instancia.AgregaMetrica(new Excepcion(ex));
                log.ErrorFormat("[CmdCancelarPago] {0}", ex.Message);

                //
                iu.PanelOperador.MensajeOperador = ex.Message;
                EVenta copiaVenta = JsonConvert.DeserializeObject <EVenta>(jsonCopiaVenta);
                Entorno.Instancia.Venta = copiaVenta;
                Entorno.Instancia.Venta.ImpuestosIncluidos = copiaImpuestosIncluidos;
            }
        }
예제 #26
0
 private Entorno()
 {
     Venta      = new EVenta();
     MediosPago = new List <DMedioPago>();
     //Impresora = new DImpresora();
 }
예제 #27
0
        public List <EVenta> ObtenerLista()
        {
            try {
                SqlConnection conexion = new SqlConnection(Properties.Settings.Default.CadenaConexion);
                SqlCommand    comando  = new SqlCommand();
                comando.CommandType = CommandType.StoredProcedure;
                comando.CommandText = "BUSCAR_VENTAS";
                comando.Connection  = conexion;
                conexion.Open();

                SqlDataReader leer       = comando.ExecuteReader();
                List <EVenta> listaVenta = new List <EVenta>();
                while (leer.Read())
                {
                    EVenta listaventa = new EVenta();
                    listaventa.IdVenta = leer.GetInt32(0);

                    if (leer.IsDBNull(1))
                    {
                        listaventa.IdCartelera = null;
                    }
                    else
                    {
                        listaventa.IdCartelera.Id_Cartelera = leer.GetInt32(1);
                    }
                    if (leer.IsDBNull(2))
                    {
                        listaventa.IdCartelera.Id_Pelicula.Nombre = null;
                    }
                    else
                    {
                        listaventa.IdCartelera.Id_Pelicula.Nombre = leer.GetString(2);
                    }
                    if (leer.IsDBNull(3))
                    {
                        listaventa.IdCartelera.Id_Sala.nombre = null;
                    }
                    else
                    {
                        listaventa.IdCartelera.Id_Sala.nombre = leer.GetString(3);
                    }
                    if (leer.IsDBNull(4))
                    {
                        listaventa.Fecha = null;
                    }
                    else
                    {
                        listaventa.Fecha = leer.GetDateTime(4);
                    }
                    if (leer.IsDBNull(5))
                    {
                        listaventa.Hora = null;
                    }
                    else
                    {
                        listaventa.Hora = leer.GetTimeSpan(5);
                    }
                    if (leer.IsDBNull(6))
                    {
                        listaventa.NumTicket = null;
                    }
                    else
                    {
                        listaventa.NumTicket = leer.GetInt32(6);
                    }

                    if (leer.IsDBNull(7))
                    {
                        listaventa.IdCartelera.valor = null;
                    }
                    else
                    {
                        listaventa.IdCartelera.valor = leer.GetDecimal(7);
                    }

                    if (leer.IsDBNull(8))
                    {
                        listaventa.CostoTotal = null;
                    }
                    else
                    {
                        listaventa.CostoTotal = leer.GetDecimal(8);
                    }
                    listaVenta.Add(listaventa);
                }
                conexion.Close();
                leer.Close();
                return(listaVenta);
            }
            catch (Exception ex) {
                throw ex;
            }
        }
예제 #28
0
파일: DReportes.cs 프로젝트: Jmezas/express
        public List <EVenta> VentasGeneralesRegular(string filtro, int Empresa, int sucursal, string FechaIncio, string FechaFin, int numPag, int allReg, int Cant)
        {
            List <EVenta> oDatos = new List <EVenta>();

            using (var Connection = GetConnection(BaseDeDatos))
            {
                try
                {
                    Connection.Open();
                    SetQuery("REP_ventasRegulares");
                    CreateHelper(Connection);
                    AddInParameter("@Filltro", filtro);
                    AddInParameter("@IdEmpresa", Empresa);
                    AddInParameter("@IdSucursal", sucursal);
                    AddInParameter("@FechaInicio", FechaIncio);
                    AddInParameter("@FechaFin", FechaFin);
                    AddInParameter("@numPagina", numPag);
                    AddInParameter("@allReg", allReg);
                    AddInParameter("@iCantFilas", Cant);

                    using (var Reader = ExecuteReader())
                    {
                        while (Reader.Read())
                        {
                            EVenta obj = new EVenta();
                            obj.IdVenta              = int.Parse(Reader["iIdVenta"].ToString());
                            obj.serie                = Reader["sSerie"].ToString();
                            obj.numero               = Reader["numero"].ToString();
                            obj.cliente.Nombre       = Reader["sCliente"].ToString();
                            obj.cliente.NroDocumento = Reader["sRucCliente"].ToString();
                            obj.cliente.Direccion    = Reader["sDireccion"].ToString();
                            obj.cliente.Email        = Reader["sEmail"].ToString();
                            obj.cliente.Telefono     = Reader["sTelefono"].ToString();
                            obj.moneda.Nombre        = Reader["sCodigoISOMoneda"].ToString();
                            obj.Documento.Nombre     = Reader["sNombreDoc"].ToString();
                            obj.fechaEmision         = Reader["dFechaEmision"].ToString();
                            obj.cantidad             = float.Parse(Reader["fCantidadCab"].ToString());
                            obj.grabada              = float.Parse(Reader["opeGrabada"].ToString());
                            obj.inafecta             = float.Parse(Reader["OpeInafecta"].ToString());
                            obj.exonerada            = float.Parse(Reader["OpeExoneradas"].ToString());
                            obj.igv                = float.Parse(Reader["nIgvCab"].ToString());
                            obj.total              = float.Parse(Reader["nTotalCab"].ToString());
                            obj.descuento          = float.Parse(Reader["TotalDescuento"].ToString());
                            obj.TotalR             = int.Parse(Reader["Total"].ToString());
                            obj.item               = int.Parse(Reader["item"].ToString());
                            obj.TotalPagina        = int.Parse(Reader["totalPaginas"].ToString());
                            obj.Nombre             = Reader["sNombreCompletoCobrador"].ToString();
                            obj.CostoEnvio         = float.Parse(Reader["fCostoEnvio"].ToString());
                            obj.Text               = Reader["TipoPago"].ToString();//tipo de pago -- efecto, credito etc
                            obj.observacion        = Reader["Observacion"].ToString();
                            obj.Comprobante.Nombre = Reader["Serie"].ToString();
                            obj.sCanalesVenta      = Reader["CanalVenta"].ToString();//Canal venta

                            oDatos.Add(obj);
                        }
                    }
                }
                catch (Exception Exception)
                {
                    throw Exception;
                }
                finally
                {
                    Connection.Close();
                }
                return(oDatos);
            }
        }
예제 #29
0
        private void BtnGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                if (entiVenta == null)
                {
                    entiVenta = new EVenta();
                }

                entiVenta.IdCliente       = Convert.ToInt32(lblIdCliente.Text);
                entiVenta.IdTrabajador    = UserCache.IdTrabajador;
                entiVenta.Fecha           = dtpFecha.Value;
                entiVenta.TipoComprobante = cmbComprobante.Text;
                entiVenta.Serie           = txtSerie.Text.Trim();
                entiVenta.Correlativo     = txtCorrelativo.Text.Trim();
                entiVenta.Igv             = Convert.ToDecimal(txtIgv.Text.Trim());

                //Capturamos el IdUltimo
                int idUltimo = venta.RegistrarVenta(entiVenta);
                if (idUltimo > 0)
                {
                    MessageBox.Show("¡Registro de venta con éxito!", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    //Registramos el Detalle ingreso
                    if (entiDetalle == null)
                    {
                        entiDetalle = new EDetalleVenta();
                    }
                    int numFilas = dgvDetalleVentas.Rows.Count;
                    int contador = 0;

                    for (int i = 0; i < numFilas; i++)
                    {
                        entiDetalle.IdVenta      = idUltimo;
                        entiDetalle.IdDetIngreso = Convert.ToInt32(dgvDetalleVentas.Rows[i].Cells[0].Value.ToString());
                        entiDetalle.Cantidad     = Convert.ToInt32(dgvDetalleVentas.Rows[i].Cells[2].Value.ToString());
                        entiDetalle.PrecioVenta  = Convert.ToDecimal(dgvDetalleVentas.Rows[i].Cells[3].Value.ToString());
                        entiDetalle.Descuento    = Convert.ToInt32(dgvDetalleVentas.Rows[i].Cells[4].Value.ToString());

                        int idDetIngreso = Convert.ToInt32(dgvDetalleVentas.Rows[i].Cells[0].Value.ToString());
                        int cantidad     = Convert.ToInt32(dgvDetalleVentas.Rows[i].Cells[2].Value.ToString());

                        if (detalle.RegistrarDetalleVenta(entiDetalle))
                        {
                            venta.DisminuirStockPorVenta(idDetIngreso, cantidad);
                        }
                        else
                        {
                            contador++;
                        }
                    }

                    if (contador == 0)
                    {
                        MessageBox.Show("¡Detalle de venta registrado con éxito!", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }

                if (venta.builder.Length != 0)
                {
                    MessageBox.Show(venta.builder.ToString(), "VENTA: Para continuar", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    if (detalle.builder.Length != 0)
                    {
                        MessageBox.Show(detalle.builder.ToString(), "DETALLE VENTA: Para continuar", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error inesperado", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                MostrarVenta();
                LimpiarVenta();
                Deshabilitar();
                btnNuevo.Enabled = true;
                EliminarFilaDetalleVenta();
            }
        }
예제 #30
0
        public List <EVenta> FAC_ArmarXMLResumen(int idResumen)
        {
            List <EVenta> oDatos = new List <EVenta>();

            using (var Connection = GetConnection(BaseDeDatos))
            {
                try
                {
                    Connection.Open();
                    SetQuery("FAC_ArmarXMLResumen");
                    CreateHelper(Connection);
                    AddInParameter("@IdResumen", idResumen);
                    using (var Reader = ExecuteReader())
                    {
                        while (Reader.Read())
                        {
                            EVenta obj = new EVenta();
                            obj.empresa.RUC          = Reader["sRuc"].ToString();
                            obj.empresa.RazonSocial  = Reader["sRazonSocialE"].ToString();
                            obj.empresa.Direccion    = Reader["sDirecion"].ToString();
                            obj.empresa.Telefono     = Reader["sTelefono"].ToString();
                            obj.empresa.Ubigeo       = Reader["sUbigeo"].ToString();
                            obj.empresa.Departamento = Reader["Departamentoemi"].ToString();
                            obj.empresa.Provincia    = Reader["Provinciaemi"].ToString();
                            obj.empresa.Distrito     = Reader["Distritoemi"].ToString();

                            obj.sCodigo          = Reader["sIdentificadorRe"].ToString();
                            obj.Documento.codigo = Reader["tipodocumento"].ToString();
                            obj.fechaEmision     = Reader["dFechaRegistro"].ToString();

                            obj.cliente.Id           = int.Parse(Reader["stipoDocumentocli"].ToString());
                            obj.cliente.NroDocumento = Reader["sDocumentoCli"].ToString();
                            obj.estadoComprobante    = Reader["iTipoEstado"].ToString();
                            obj.serie         = Reader["sSerie"].ToString();
                            obj.numero        = Reader["inumero"].ToString();
                            obj.moneda.Nombre = Reader["sMoneda"].ToString();
                            obj.total         = float.Parse(Reader["fTotal"].ToString());
                            obj.descuento     = float.Parse(Reader["fDescuento"].ToString());
                            obj.igv           = float.Parse(Reader["fIGV"].ToString());
                            obj.isc           = float.Parse(Reader["ftotalIsc"].ToString());
                            obj.otros         = float.Parse(Reader["ftotalOtrosImpuestos"].ToString());
                            obj.grabada       = float.Parse(Reader["fGrabada"].ToString());
                            obj.exonerada     = float.Parse(Reader["fExonerada"].ToString());
                            obj.inafecta      = float.Parse(Reader["fInafecta"].ToString());
                            obj.gratuita      = float.Parse(Reader["fGratuita"].ToString());

                            oDatos.Add(obj);
                        }
                    }
                }
                catch (Exception Exception)
                {
                    throw Exception;
                }
                finally
                {
                    Connection.Close();
                }
                return(oDatos);
            }
        }