private void ubNuevo_Click(object sender, EventArgs e) { try { FrmSelectedEntity FrmSeleccionar = new FrmSelectedEntity(); Existencia servicio = (Existencia)FrmSeleccionar.GetSelectedEntity(typeof(Existencia), "Selección de Servicios"); if (servicio != null) { ItemRendicionCotizacion item = new ItemRendicionCotizacion(); item.Codigo = servicio.Codigo; item.Descripcion = servicio.Nombre; item.CantidadCotizacion = 0; item.PrecioCotizacion = 0; item.TotalCotizacion = 0; item.CantidadReal = 0; item.PrecioReal = 0; item.TotalReal = 0; RendicionCotizacion.Items.Add(item); MostrarItems(); MostrarTotales(); } } catch (Exception ex) { SoftException.Control(ex); } }
private void ObtenerCostoMaterial() { if (ActualizandoIU) { return; } try { Existencia existenciaActualizada = (Existencia)HelperNHibernate.GetEntityByID("Existencia", Item.Material.ID); Decimal costo = 0; if (existenciaActualizada.CostoUltimaCompra > 0) { costo = existenciaActualizada.CostoUltimaCompra; } else { costo = existenciaActualizada.CostoReferencia; } Item.CostoMaterial = (Item.CantidadMaterial * costo) * Item.UnidadMaterial.FactorConversion; SumarTotal(); } catch (Exception) { } Mostrar(); }
private void ubNuevo_Click(object sender, EventArgs e) { if (ItemPlantilla == null) { return; } FrmSelectedEntity FrmSeleccionar = new FrmSelectedEntity(); String Filtro = "ID NOT IN ("; String IDs = ""; foreach (ItemPlantillaServicio Item in ItemPlantilla.Servicios) { IDs = IDs + "'" + Item.Servicio.ID + "',"; } Filtro = (IDs.Length > 0) ? Filtro + IDs.Substring(0, IDs.Length - 1) + ") AND EsServicio = 1" : " EsServicio = 1"; Existencia Existencia = (Existencia)FrmSeleccionar.GetSelectedEntity(typeof(Existencia), "Existencia", Filtro); if (Existencia != null) { Existencia ExistenciaCompleta = (Existencia)HelperNHibernate.GetEntityByID("Existencia", Existencia.ID); UltraGridRow Row = ugServicios.DisplayLayout.Bands[0].AddNew(); Row.Tag = ItemPlantilla.CrearServicio(ExistenciaCompleta); MostrarServicio(Row); } }
public virtual ItemListaPreciosExistencia AddItem(Existencia Existencia) { ItemListaPreciosExistencia Item = new ItemListaPreciosExistencia(); Item.Existencia = Existencia; Items.Add(Item); return(Item); }
public void TesteRetornaExistencia() { DbConsultas dbConsultas = new DbConsultas(); Existencia resultado = dbConsultas.RetornaExistencia(10); Assert.AreEqual(resultado.Classe, "N"); Assert.AreEqual(resultado.Pontos, 10); }
public List <Existencia> obtenerListaExistencias(int desgaste_id) { List <Existencia> existencias = new List <Existencia>(); MySqlDataReader reader = null; String sql = @"select existencia.id,cantidadAnterior,cantidadActual,existencia.obs,desgaste.descripcion,usuario.nombre,unidad,fecha,respo.nombre,IFNULL(ubicacion.nombre,'S/E'),IFNULL(empresa.nombre,'S/E'),existencia.tipo,existencia.cantidad from existencia inner join desgaste on existencia.desgaste_id=desgaste.id inner join responsable as respo on existencia.responsable_id=respo.id inner join responsable as usuario on existencia.usuario_id=usuario.id left join ubicacion on existencia.ubicacion_id=ubicacion.id left join empresa on ubicacion.empresa_id=empresa.id where existencia.desgaste_id=@desgaste_id order by existencia.fecha desc"; try { using (MySqlConnection conex = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySqlConnectionString"].ToString())) { conex.Open(); MySqlCommand comando = new MySqlCommand(sql, conex); comando.Parameters.AddWithValue("@desgaste_id", desgaste_id); reader = comando.ExecuteReader(); while (reader.Read()) { Existencia existencia = new Existencia(); existencia.id = reader.GetInt32(0); existencia.cantidadAnterior = reader.GetFloat(1); existencia.cantidadActual = reader.GetFloat(2); existencia.obs = reader[3] == DBNull.Value ? String.Empty : reader.GetValue(3).ToString(); existencia.desgaste = reader[4] == DBNull.Value ? String.Empty : reader.GetValue(4).ToString(); existencia.usuario = reader[5] == DBNull.Value ? String.Empty : reader.GetValue(5).ToString(); existencia.unidad = reader[6] == DBNull.Value ? String.Empty : reader.GetValue(6).ToString(); existencia.fecha = reader[7] == DBNull.Value ? String.Empty : reader.GetValue(7).ToString(); existencia.responsable = reader[8] == DBNull.Value ? String.Empty : reader.GetValue(8).ToString(); existencia.ubicacion = reader[9] == DBNull.Value ? String.Empty : reader.GetValue(9).ToString(); existencia.empresa = reader[10] == DBNull.Value ? String.Empty : reader.GetValue(10).ToString(); existencia.tipo = reader[11] == DBNull.Value ? String.Empty : reader.GetValue(11).ToString(); existencia.cantidad = reader.GetFloat(12); existencias.Add(existencia); } } } catch { } finally { if (reader != null && !reader.IsClosed) { reader.Close(); } } return(existencias); }
public virtual ItemMaquinaServicio CrearServicio(Existencia Servicio) { ItemMaquinaServicio Item = new ItemMaquinaServicio(); Item.Servicio = Servicio; Item.Unidad = Servicio.UnidadBase; ItemsServicio.Add(Item); return(Item); }
public async Task <bool> ActualizarExistencia(Existencia exsitencia, Movimiento movimiento) { _context.Existencia.Where(f => f.IdProducto == exsitencia.IdProducto && f.IdSucursal == exsitencia.IdSucursal).FirstOrDefault().Cantidad = exsitencia.Cantidad; _context.Movimiento.Add(movimiento); // actualizar movimientos return(await _context.SaveChangesAsync() >= 0); }
public virtual ItemPlantillaServicio CrearServicio(Existencia Servicio) { ItemPlantillaServicio Item = new ItemPlantillaServicio(); Item.Servicio = Servicio; Item.Unidad = Servicio.UnidadBase; Item.Cantidad = 1; Servicios.Add(Item); return(Item); }
public int InsertExistencia(int idProd, decimal cantidad) { var newExis = new Existencia { Cantidad = cantidad, IdProducto = idProd }; dbCtx.Existencias.Add(newExis); return(dbCtx.SaveChanges()); }
public Existencia RetornaExistencia(int nrPontos) { SQLiteManager dbManager = new SQLiteManager(); Existencia resultado = new Existencia(); using (var db = dbManager.CreateDbContext(args)) { resultado = db.TabelaExistencia.Single(x => x.Pontos == nrPontos); } return(resultado); }
public void InsertarExistencia(Existencia existencia) { if (String.IsNullOrWhiteSpace(Convert.ToString(existencia.cantidad)) || string.IsNullOrWhiteSpace(Convert.ToString(existencia.producto)) || string.IsNullOrWhiteSpace(Convert.ToString(existencia.bodega)) || string.IsNullOrWhiteSpace(existencia.ingreso) || string.IsNullOrWhiteSpace(Convert.ToString(existencia.proveedor)) || string.IsNullOrWhiteSpace(Convert.ToString(existencia.marca))) { MessageBox.Show("Hay campos que estan vacios"); //si hace falta algun campo no se realiza la transaccion } else { datos cdatos = new datos(); //Se crea un objeto de capa de datos cdatos.insertarexistencia(existencia.cantidad, existencia.producto, existencia.bodega, existencia.ingreso, existencia.proveedor, existencia.marca); } }
private void ubNuevaExistencia_Click(object sender, EventArgs e) { FrmSelectedEntity FrmSeleccionar = new FrmSelectedEntity(); Existencia Existencia = (Existencia)FrmSeleccionar.GetSelectedEntity(typeof(Existencia), "Existencia", ListaPreciosExistencia.FiltroExistencias); if (Existencia != null) { UltraGridRow Row = grillaExistencias.DisplayLayout.Bands[0].AddNew(); Row.Tag = ListaPreciosExistencia.AddItem(Existencia); ItemListaPreciosExistencia = (ItemListaPreciosExistencia)Row.Tag; MostrarItem(Row); } }
private void guardaRegistroExistencia(MySqlConnection conexion, Existencia registro) { query = "INSERT INTO existencia(idProducto,fecha,cantidad) VALUES(?idProducto,?fecha,?cantidad);"; using (MySqlCommand cmd = new MySqlCommand(query, conexion)) { cmd.Parameters.AddWithValue("?idProducto", registro.IdProducto); cmd.Parameters.AddWithValue("?fecha", registro.Fecha); cmd.Parameters.AddWithValue("?cantidad", registro.Cantidad); cmd.ExecuteNonQuery(); } }
public Existencia[] consultaExistencia(String fecha, int numReg, int opc) { Existencia[] consultasExistencia = new Existencia[numReg]; String query = ""; MySqlConnection conn; Conexion conexion = new Conexion(); conn = conexion.abrirConexion(); int i = 0; switch (opc) { case 0: query = "SELECT * FROM frio WHERE fecha=?fecha;"; break; case 1: query = "SELECT * FROM fresco WHERE fecha=?fecha;"; break; case 2: query = "SELECT * FROM existencia WHERE fecha=?fecha;"; break; } try { MySqlCommand cmd = new MySqlCommand(query, conn); cmd.Parameters.AddWithValue("?fecha", fecha); consulta = cmd.ExecuteReader(); cmd.Dispose(); while (consulta.Read()) { consultasExistencia[i] = new Existencia(); consultasExistencia[i].IdRegistro = consulta.GetInt32(0); consultasExistencia[i].IdProducto = consulta.GetInt32(1); consultasExistencia[i].Fecha = consulta.GetDateTime(2); consultasExistencia[i].Cantidad = consulta.GetDouble(3); i++; } } finally { conexion.cerrarConexion(); } return(consultasExistencia); }
/// <summary> /// Funcion encargada de guardar un nuevo registro en la base de datos /// </summary> /// <param name="nExistencia">variable de tipo modelo Existencias</param> /// <param name="pkProducto">variable de tipo entera</param> /// <param name="pkAlmacen">variable de tipo entera</param> public static void RegistrarNuevaExistencia(Existencia nExistencia, int pkProducto, int pkAlmacen) { try { using (var ctx = new DataModel()) { nExistencia.producto_id = pkProducto; nExistencia.almacen_id = pkAlmacen; ctx.Existencias.Add(nExistencia); ctx.SaveChanges(); } } catch (Exception) { throw; } }
public ActionResult Create([Bind(Include = "Id,Nombre,Precio,ProveedorId")] Producto producto) { if (ModelState.IsValid) { db.Productos.Add(producto); db.SaveChanges(); var idProducto = db.Productos.Max(x => x.Id); Existencia existencia = new Existencia(); existencia.ProductoId = idProducto; existencia.Cantidad = 0; db.Existencias.Add(existencia); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(producto)); }
/// <summary> /// Funcion encargada de eliminar un registro de la base de datos mediante una id /// </summary> /// <param name="pkExistencia">variable de tipo entera</param> public static void Eliminar(int pkExistencia) { try { using (var ctx = new DataModel()) { Existencia nExistencia = ManejoExistencia.getById(pkExistencia); ctx.Entry(nExistencia).State = EntityState.Modified; ctx.SaveChanges(); } } catch (Exception) { throw; } }
/// <summary> /// Funcion encargada de modificar un registro de la base de datos /// </summary> /// <param name="nExistencia">variable de tipo modelo Existencias</param> /// <param name="pkProducto">variable de tipo entera</param> public static void Modificar(Existencia nExistencia, int pkProducto) { Producto producto = ManejoProducto.getById(pkProducto); try { using (var ctx = new DataModel()) { ctx.Productos.Attach(producto); ctx.Entry(nExistencia).State = EntityState.Modified; ctx.SaveChanges(); } } catch (Exception) { throw; } }
private void bussAcabado_Search(object sender, EventArgs e) { if (ActualizandoIU) { return; } try { FrmSelectedEntity FrmSeleccionar = new FrmSelectedEntity(); string filtro = "IDListaPreciosExistencia='" + ordenProduccion.ListaPreciosExistencia.ID + "'"; Existencia servicio = (Existencia)FrmSeleccionar.GetSelectedEntity(typeof(Existencia), "ItemListaPreciosExistencia", filtro); Item.Servicio = (Existencia)HelperNHibernate.GetEntityByID("Existencia", servicio.ID); Mostrar(); } catch (Exception ex) { Soft.Exceptions.SoftException.ShowException(ex); } }
private void bussAcabado_Search(object sender, EventArgs e) { if (ActualizandoIU) { return; } try { FrmSelectedEntity FrmSeleccionar = new FrmSelectedEntity(); string filtro = "IDListaPreciosExistencia='" + cotizacion.ListaPreciosExistencia.ID + "'"; Existencia servicio = (Existencia)FrmSeleccionar.GetSelectedEntity(typeof(Existencia), "ItemListaPreciosExistencia", filtro); Item.Servicio = (Existencia)HelperNHibernate.GetEntityByID("Existencia", servicio.ID); if (Item.Servicio.Codigo.Equals("FILMACION") || Item.Servicio.Codigo.Equals("FILMACION2")) { if (Item.Servicio.Unidades != null) { Item.UnidadServicio = Item.Servicio.UnidadBase; if (ItemElemento.MetodoImpresion == null) { Item.CantidadServicio = 0; } if (ItemElemento.NumeroCambios == 2) { Item.CantidadServicio = (ItemElemento.ImpresoTiraColor + ItemElemento.ImpresoRetiraColor) * ItemElemento.NumeroPliegos; } else { Item.CantidadServicio = ItemElemento.ImpresoTiraColor * ItemElemento.NumeroPliegos; } ObtenerCostoServicio(); } } Mostrar(); } catch (Exception ex) { Soft.Exceptions.SoftException.ShowException(ex); } }
private void txtNombreMaterial_Search(object sender, EventArgs e) { if (ActualizandoIU) { return; } try { String filtro = "Nombre like '%" + txtNombreMaterial.Text + "%'"; FrmSelectedEntity formulario = new FrmSelectedEntity(); Existencia existencia = (Existencia)formulario.GetSelectedEntity(typeof(Existencia), "Existencia", filtro); Item.Material = (Existencia)HelperNHibernate.GetEntityByID("Existencia", existencia.ID); Mostrar(); } catch (Exception ex) { Soft.Exceptions.SoftException.ShowException(ex); } }
public JsonResult Modificar([FromBody] Dictionary <string, object> Parametros) { bool Resultado = false; string Mensaje = ""; Existencia Articulo = JsonSerializer.Deserialize <Existencia>(Parametros["Articulo"].ToString()); bool Tipo = JsonSerializer.Deserialize <bool>(Parametros["Tipo"].ToString().ToLower()); try { bool existeProducto = (Inventario.Productos.Where(p => p.Clave == Articulo.Producto).ToList().Count == 1); bool existeSucursal = (Inventario.Sucursales.Where(s => s.Clave == Articulo.Sucursal).ToList().Count == 1); if (Articulo.Validar() && existeProducto && existeSucursal) { var eProducto = Inventario.Existencias.Where(e => e.Producto == Articulo.Producto && e.Sucursal == Articulo.Sucursal).SingleOrDefault(); if (Tipo)// aumentar cantidad { eProducto.Cantidad += Articulo.Cantidad; } else // disminuir cantidad { eProducto.Cantidad -= Articulo.Cantidad; } Inventario.Existencias.Update(eProducto); Inventario.SaveChanges(); Resultado = true; Mensaje = "Articulo actualizado correctamente"; } else { Mensaje = "Validar que los datos ingresados son correctos y pertenescan a articulos en el inventario."; } } catch { Mensaje = "Ocurrio un error al intentar actualizar el inventario"; } return(Json(new { Resultado, Mensaje })); }
public Boolean AgregarServicios(String Codigo, String Descripcion, UltraGridRow Row) { Collection Productos = new Collection(); FrmSelectedEntity FrmSeleccionar = new FrmSelectedEntity(); ItemSolicitudCotizacionServicio Item = (ItemSolicitudCotizacionServicio)Row.Tag; String Filtro = String.Format(" Codigo LIKE '{0}%' AND Nombre LIKE '{1}%'", Codigo, Descripcion); //if (ItemSolicitudCotizacion.m_FiltroServicios.Length > 0) { Filtro += String.Format(" AND {0}", ItemSolicitudCotizacion.m_FiltroServicios); } Productos = FrmSeleccionar.GetSelectedsEntities(typeof(Existencia), "Selección de Servicios", Filtro); if (Productos.Count == 1) { Existencia Servicio = (Existencia)Productos[1]; Item.Servicio = (Existencia)HelperNHibernate.GetEntityByID("Existencia", Servicio.ID); Item.CantidadFinal = 1; MostrarServicio(Row); return(true); } else if (Productos.Count > 1) { Existencia Producto = (Existencia)Productos[1]; Item.Servicio = (Existencia)HelperNHibernate.GetEntityByID("Existencia", Producto.ID); Item.CantidadFinal = 1; MostrarServicio(Row); for (int i = 2; i <= Productos.Count; i++) { UltraGridRow RowNuevo = ugServicios.DisplayLayout.Bands[0].AddNew(); ItemSolicitudCotizacionServicio ItemNuevo = ItemSolicitudCotizacion.AddServicio(); Existencia ProductoNuevo = (Existencia)Productos[i]; ItemNuevo.Servicio = (Existencia)HelperNHibernate.GetEntityByID("Existencia", ProductoNuevo.ID); ItemNuevo.CantidadFinal = 1; RowNuevo.Tag = ItemNuevo; MostrarServicio(RowNuevo); } return(true); } else { return(false); } }
public int UpdateExistencia(Existencia exist, decimal cantidad) { return(inventarioR.UpdateExistencia(exist, cantidad)); }
public async Task <int> CrearAsync(int usuarioId, IngresoDetalle ingreso) { if (ingreso == null) { throw new ArgumentNullException(nameof(ingreso)); } if (ingreso.Productos == null || ingreso.Productos.Length == 0) { throw new InvalidOperationException("No puede crear un ingreso sin productos."); } var tieneProductosRepetidos = ingreso.Productos.GroupBy(x => new { x.ProductoId, x.MarcaId, x.UnidadId }).Where(x => x.Count() > 1).Any(); if (tieneProductosRepetidos) { throw new InvalidOperationException("Un ingreso no puede tener un producto repetido con la misma marca y unidad de medida (debe crear dos ingresos distintos)"); } var hayProductosSinCantidad = ingreso.Productos.Any(x => x.Cantidad <= 0); if (hayProductosSinCantidad) { throw new InvalidOperationException("Un ingreso no puede contener productos con valores menores o iguales a cero"); } var hayProductosConPrecioNegativo = ingreso.Productos.Any(x => x.Precio < 0); if (hayProductosConPrecioNegativo) { throw new InvalidOperationException("Un ingreso no puede contener productos con precio negativo"); } var existeProveedor = await db.Proveedores.AnyAsync(x => x.Id == ingreso.ProveedorId); if (!existeProveedor) { throw new InvalidOperationException($"No existe el proveedor con id {ingreso.ProveedorId}"); } var existeBodega = await db.Bodegas.AnyAsync(x => x.Id == ingreso.BodegaId); if (!existeBodega) { throw new InvalidOperationException($"No existe una bodega con id {ingreso.BodegaId}"); } var productosIds = ingreso.Productos.Select(x => x.ProductoId).Distinct().ToArray(); var cantidadDeProductos = await db.Productos.CountAsync(x => productosIds.Contains(x.Id)); var existenTodosLosProductos = cantidadDeProductos == productosIds.Length; if (!existenTodosLosProductos) { throw new InvalidOperationException("Al menos uno de los productos indicados no existe"); } var marcasParaLosProductos = await db.ProductoMarcas.Where(x => productosIds.Contains(x.ProductoId)).ToArrayAsync(); var unidadesParaLosProductos = await db.ProductoUnidadesDeMedida.Where(x => productosIds.Contains(x.ProductoId)).ToArrayAsync(); //var caracteristicasParaLosProductos = await db.ProductoCaracteristicas.Where(x => productosIds.Contains(x.ProductoId)).ToArrayAsync(); foreach (var item in ingreso.Productos) { if (!marcasParaLosProductos.Any(x => x.MarcaId == item.MarcaId && x.ProductoId == item.ProductoId)) { throw new InvalidOperationException($"No existe una marca con id {item.MarcaId} o no está asignada al producto con id {item.ProductoId}"); } if (!unidadesParaLosProductos.Any(x => x.UnidadDeMedidaId == item.UnidadId && x.ProductoId == item.ProductoId)) { throw new InvalidOperationException($"No existe una unidad de medida con id {item.UnidadId} o no está asignada al producto con id {item.ProductoId}"); } // TODO: Validar caracteristicas (requeridas, existentes, etc.) } // NOTA: muchas de las validaciones anteriores podrían implementarse como DataAnnotations // para que puedan ser utilizadas por otros controllers y delegar esas tareas de // validación al motor de MVC por medio de atributos en los modelos. if (ingreso.Fecha == default(DateTime)) { ingreso.Fecha = DateTime.UtcNow; } var nuevoIngreso = new Ingreso { Fecha = ingreso.Fecha.ToUniversalTime(), UsuarioId = usuarioId, BodegaId = ingreso.BodegaId, ProveedorId = ingreso.ProveedorId, Productos = ingreso.Productos.Select(producto => new IngresoProducto { ProductoId = producto.ProductoId, MarcaId = producto.MarcaId, UnidadDeMedidaId = producto.UnidadId, Cantidad = producto.Cantidad, Precio = producto.Precio, NumeroDeSerie = producto.Serie, Caracteristicas = producto.Caracteristicas?.Select(caracteristica => new IngresoProductoCaracteristica { CaracteristicaId = caracteristica.Id, ListaValorId = caracteristica.ListaValorId, Valor = caracteristica.Valor }).ToArray() }).ToArray() }; db.Ingresos.Add(nuevoIngreso); var existencias = await db.Existencias.Include(x => x.Cantidades).Where(x => productosIds.Contains(x.ProductoId)).ToListAsync(); foreach (var item in ingreso.Productos) { var productoId = item.ProductoId; var nuevaCantidad = item.Cantidad; var marcaId = item.MarcaId; var unidadId = item.UnidadId; var existencia = existencias.FirstOrDefault(x => x.ProductoId == productoId); if (existencia == null) { existencia = new Existencia { ProductoId = productoId, Cantidades = new List <ExistenciaCantidad> { new ExistenciaCantidad { Cantidad = nuevaCantidad, FechaModificacion = DateTime.UtcNow, MarcaId = marcaId, UnidadDeMedidaId = unidadId } } }; db.Existencias.Add(existencia); existencias.Add(existencia); } else { var cantidad = existencia.Cantidades.FirstOrDefault(x => x.UnidadDeMedidaId == unidadId && x.MarcaId == marcaId); if (cantidad == null) { cantidad = new ExistenciaCantidad { Cantidad = nuevaCantidad, FechaModificacion = DateTime.UtcNow, MarcaId = marcaId, UnidadDeMedidaId = unidadId }; existencia.Cantidades.Add(cantidad); } else { cantidad.Cantidad += nuevaCantidad; } } } await db.SaveChangesAsync(); return(nuevoIngreso.Id); }
public int guardaRegistroFresco(Existencia entrada) { int ans = -1; Boolean existe_registro = false; try { using (var conexion = new MySqlConnection(datasource)) { conexion.Open(); query = "SELECT idRegistro FROM existencia WHERE idProducto = ? idProducto"; using (MySqlCommand cmd = new MySqlCommand(query, conexion)) { cmd.Parameters.AddWithValue("?idProducto", entrada.IdProducto); using (MySqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { existe_registro = true; } } } if (existe_registro) { query = "UPDATE existencia SET cantidad = ? cantidad WHERE idProducto = ?idProducto;"; using (MySqlCommand cmd = new MySqlCommand(query, conexion)) { cmd.Parameters.AddWithValue("?idProducto", entrada.IdProducto); cmd.Parameters.AddWithValue("?cantidad", entrada.Cantidad); cmd.ExecuteNonQuery(); ans = 1; } } else { query = "INSERT INTO existencia(idProducto,fecha,cantidad) VALUES(?idProducto,?fecha,?cantidad);"; using (MySqlCommand cmd = new MySqlCommand(query, conexion)) { cmd.Parameters.AddWithValue("?idProducto", entrada.IdProducto); cmd.Parameters.AddWithValue("?fecha", entrada.Fecha); cmd.Parameters.AddWithValue("?cantidad", entrada.Cantidad); cmd.ExecuteNonQuery(); ans = 1; } } query = "INSERT INTO fresco(idProducto,fecha,cantidad) VALUES(?idProducto,?fecha,?cantidad);"; using (MySqlCommand cmd = new MySqlCommand(query, conexion)) { cmd.Parameters.AddWithValue("?idProducto", entrada.IdProducto); cmd.Parameters.AddWithValue("?fecha", entrada.Fecha); cmd.Parameters.AddWithValue("?cantidad", entrada.Cantidad); cmd.ExecuteNonQuery(); ans = 1; } } } catch (MySqlException e) { e.ToString(); ans = -1; } return(ans); }
private void btn_adicionar_Click(object sender, RoutedEventArgs e) { var nuevo_producto = new Producto { Codigo = tbox_codigo.Text, Descripcion = tbox_descripcion.Text }; using (var db = new TiendaDbContext()) { if (db.Productos.Find(nuevo_producto.Codigo) != null) { MessageBox.Show("Ya existe un producto con ese codigo"); return; } if (nuevo_producto.Codigo == "") { MessageBox.Show("El codigo no puede ser vacio"); return; } if (nuevo_producto.Descripcion == "") { MessageBox.Show("La descripcion no puede estar vacia"); return; } double precioBuenEstado; double precioDefectuoso; if (!double.TryParse(tbox_precioDefectuoso.Text, out precioDefectuoso) || !double.TryParse(tbox_precioBuenEstado.Text, out precioBuenEstado)) { MessageBox.Show("Rectifique los precios"); return; } db.Productos.Add(nuevo_producto); db.SaveChanges(); source_productos.Add(nuevo_producto); int index = dgrid_productos.SelectedIndex; dgrid_productos.ItemsSource = null; dgrid_productos.ItemsSource = source_productos.Where(s => s.Codigo.ToLower().Contains(codigo_src) && s.Descripcion.ToLower().Contains(descrip_src)).ToList(); dgrid_productos.SelectedIndex = index; var tiendas = db.Tiendas.ToList(); foreach (var tienda in tiendas) { var exist = new Existencia { CantidadBuenEstado = 0, CantidadDefectuoso = 0, Producto = nuevo_producto, Tienda = tienda, PrecioBuenEstado = precioBuenEstado, PrecioDefectuoso = precioDefectuoso }; tienda.Productos.Add(exist); db.Existencias.Add(exist); } db.SaveChanges(); } tbox_codigo.Text = ""; tbox_descripcion.Text = ""; tbox_precioBuenEstado.Text = ""; tbox_precioDefectuoso.Text = ""; }
public void copiaRegistroExistencia() { try { DateTime fecha = DateTime.Now; List <Existencia> existencia = new List <Existencia>(); using (var conexion = new MySqlConnection(datasource)) { conexion.Open(); query = "SELECT idRegistro FROM existencia where fecha = current_date() limit 1;"; using (MySqlCommand cmd = new MySqlCommand(query, conexion)) { using (MySqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { return; } } } } using (var conexion = new MySqlConnection(datasource)) { conexion.Open(); query = "SELECT fecha FROM existencia order by idRegistro limit 1;"; using (MySqlCommand cmd = new MySqlCommand(query, conexion)) { using (MySqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { fecha = reader.GetDateTime("fecha"); } } } } using (var conexion = new MySqlConnection(datasource)) { conexion.Open(); query = "SELECT idProducto, cantidad FROM existencia WHERE fecha = ?fecha;"; using (MySqlCommand cmd = new MySqlCommand(query, conexion)) { cmd.Parameters.AddWithValue("?fecha", fecha); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { Existencia registro = new Existencia(); registro.IdProducto = reader.GetInt32("idProducto"); registro.Cantidad = reader.GetDouble("cantidad"); registro.Fecha = DateTime.Now; existencia.Add(registro); } } } } using (var conexion = new MySqlConnection(datasource)) { conexion.Open(); using (MySqlTransaction tx = conexion.BeginTransaction()) { try { foreach (Existencia registro in existencia) { guardaRegistroExistencia(conexion, registro); } tx.Commit(); } catch (MySqlException e) { tx.Rollback(); Console.WriteLine(e.ToString()); } } } } catch (MySqlException e) { Console.WriteLine(e.ToString()); } }
public int guardaRegistroFrio(Existencia salida) { int ans = -1, id_registro = 0; Double existencia_cantidad = 0; try { using (var conexion = new MySqlConnection(datasource)) { conexion.Open(); query = "SELECT idRegistro, cantidad FROM existencia WHERE idProducto = ?idProducto AND fecha = ?fecha;"; using (MySqlCommand cmd = new MySqlCommand(query, conexion)) { cmd.Parameters.AddWithValue("?idProducto", salida.IdProducto); cmd.Parameters.AddWithValue("?fecha", DateTime.Now.Date); using (MySqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { id_registro = reader.GetInt32("idRegistro"); existencia_cantidad = reader.GetDouble("cantidad"); } else { conexion.Close(); return(0); } } } existencia_cantidad -= salida.Cantidad; if (existencia_cantidad < 0) { conexion.Close(); return(1); } query = "UPDATE existencia SET cantidad = ?cantidad WHERE idRegistro = ?idRegistro;"; using (MySqlCommand cmd = new MySqlCommand(query, conexion)) { cmd.Parameters.AddWithValue("?cantidad", existencia_cantidad); cmd.Parameters.AddWithValue("?idRegistro", id_registro); cmd.ExecuteNonQuery(); } query = "INSERT INTO frio(idProducto,fecha,cantidad) VALUES(?idProducto,?fecha,?cantidad);"; using (MySqlCommand cmd = new MySqlCommand(query, conexion)) { cmd.Parameters.AddWithValue("?idProducto", salida.IdProducto); cmd.Parameters.AddWithValue("?fecha", salida.Fecha); cmd.Parameters.AddWithValue("?cantidad", salida.Cantidad); cmd.ExecuteNonQuery(); ans = 2; } } } catch (MySqlException e) { e.ToString(); ans = -1; } return(ans); }