public async Task <ActionResult> Orders()
        {
            Group group = await Db.Groups.Where(x => x.Users.Select(c => c.Id).Contains(CurrentUser.Id)).FirstOrDefaultAsync();

            if (group == null)
            {
                Flash.Error("Error", "Lo Siento pero usted no pertenece a ningún grupo para empezar el modelo de gestión");
                return(RedirectToAction("Index", "Home"));
            }
            if (!group.Section.IsActivedSimulation && group.Section.Periods.Select(x => x.IsLastPeriod).Contains(true))
            {
                Flash.Info("Información", "El modelo de gestión ha finalizado");
                return(RedirectToAction("GroupResults", "Results", new { IsReadyToOrder = false }));
            }
            if (!group.Section.IsActivedSimulation)
            {
                //Tira un error de que el model de gestión aún no ha empezado
                Flash.Error("Error", "El Modelo de gestión aún no ha empezado");
                return(RedirectToAction("Index", "Home"));
            }
            if (group.IsInSimulation == false)
            {
                Flash.Error("Error", "Este Modelo de gestión ya ha iniciado no puede incluirse");
                return(RedirectToAction("Index", "Home"));
            }
            Period lastPeriod = group.Section.Periods.Where(t => t.Demands.Count() > 0).OrderByDescending(x => x.Created).FirstOrDefault();

            if (lastPeriod == null)
            {
                //Tira un error de que no puede llenar ordenes hasta que el profesor ingrese demanda.
                Flash.Error("Error", "El Profesor aún no suministra nuevas demandas");
                return(RedirectToAction("GroupResults", "Results", new { IsReadyToOrder = false }));
            }
            else if (lastPeriod.Orders.Where(x => x.Group == group).Count() != 0)
            {
                //Tira un error de que no puede llenar ordenes hasta que el profesor ingrese demanda.
                Flash.Error("Error", "El Profesor aún no sumistra nuevas demandas");
                return(RedirectToAction("GroupResults", "Results", new { IsReadyToOrder = false }));
            }
            SimulationBL          simulation = new SimulationBL();
            List <Balance>        balances   = group.Balances.Where(x => x.PeriodId == lastPeriod.Id).ToList <Balance>();
            List <OrderViewModel> orders     = balances.Select(x => new OrderViewModel {
                Demand         = x.Demand,
                FinalStock     = x.FinalStock,
                FinalStockCost = x.FinalStockCost,
                InitialStock   = x.InitialStock,
                ReceivedOrders = x.ReceivedOrders,
                ProductName    = x.Product.Name,
                ProductNumber  = x.Product.Number,
                ProductId      = x.ProductId,
                ProductPrice   = group.Section.CaseStudy.InitialCharges.Where(t => t.ProductId == x.ProductId).FirstOrDefault().Price,
                OrderCostTime  = new OrderCostTime {
                    OrdinaryOrderCost = simulation.GetOrderCost(group.Section.CaseStudy.InitialCharges.Where(t => t.ProductId == x.ProductId).FirstOrDefault(), OrderType.Normal),
                    CourierOrderCost  = simulation.GetOrderCost(group.Section.CaseStudy.InitialCharges.Where(t => t.ProductId == x.ProductId).FirstOrDefault(), OrderType.Courier),
                    FastCourierCost   = simulation.GetOrderCost(group.Section.CaseStudy.InitialCharges.Where(t => t.ProductId == x.ProductId).FirstOrDefault(), OrderType.FastCourier),
                    FastOrderCost     = simulation.GetOrderCost(group.Section.CaseStudy.InitialCharges.Where(t => t.ProductId == x.ProductId).FirstOrDefault(), OrderType.Fast),
                    OrdinaryOrderTime = simulation.GetTimeOrder(group.Section.CaseStudy.InitialCharges.Where(t => t.ProductId == x.ProductId).FirstOrDefault(), OrderType.Normal),
                    CourierTime       = simulation.GetTimeOrder(group.Section.CaseStudy.InitialCharges.Where(t => t.ProductId == x.ProductId).FirstOrDefault(), OrderType.Courier),
                    FastOrderTime     = simulation.GetTimeOrder(group.Section.CaseStudy.InitialCharges.Where(t => t.ProductId == x.ProductId).FirstOrDefault(), OrderType.Fast),
                    FastCourierTime   = simulation.GetTimeOrder(group.Section.CaseStudy.InitialCharges.Where(t => t.ProductId == x.ProductId).FirstOrDefault(), OrderType.FastCourier),
                },
                Sells                 = x.Sells,
                UnsatisfiedDemand     = x.DissatisfiedDemand,
                UnsatisfiedDemandCost = x.DissatisfiedCost
            })
                                               .OrderBy(x => x.ProductNumber)
                                               .ToList();
            //Lista de integrantes
            List <User> members = group.Users.Select(x => new User {
                Id = x.Id, Email = x.Email, FirstName = x.FirstName, LastName = x.LastName
            }).ToList();
            PeriodViewModel periodViewModel = new PeriodViewModel {
                CaseStudy    = group.Section.CaseStudy,
                Members      = members,
                Group        = group,
                WeekNumber   = group.Section.Periods.Count(),
                GroupId      = group.Id,
                Orders       = orders,
                IsLastPeriod = lastPeriod.IsLastPeriod,
            };

            return(View(periodViewModel));
        }
        public async Task <ActionResult> RegisterDemands(DemandViewModel model)
        {
            if (ModelState.IsValid)
            {
                Section section = await Db.Sections.Where(x => x.Id == model.SectionId).FirstOrDefaultAsync();

                if (section == null)
                {
                    return(HttpNotFound());
                }
                if (section.IsActivedSimulation == false)
                {
                    Flash.Error("El Modelo de gestión ha finalizado");
                    return(RedirectToAction("Index"));
                }
                Period newPeriod = new Period
                {
                    Created      = DateTime.Now,
                    Id           = Guid.NewGuid(),
                    IsLastPeriod = section.CaseStudy.Periods == section.Periods.Count() ? true : false,
                };
                if (newPeriod.IsLastPeriod)
                {
                    section.IsActivedSimulation = false;
                }
                section.Periods.Add(newPeriod);
                Period period = section.Periods.OrderByDescending(x => x.Created).FirstOrDefault();
                period.Demands = new List <Demand>();
                foreach (var productSell in model.ProductDemands)
                {
                    if (TryValidateModel(productSell))
                    {
                        Demand sale = new Demand
                        {
                            Product  = await Db.Products.Where(x => x.Id == productSell.Product.Id).FirstOrDefaultAsync(),
                            Quantity = productSell.Quantity
                        };
                        period.Demands.Add(sale);
                    }
                    else
                    {
                        Flash.Error("Error", "Ha Ocurrido un error inesperado");
                        return(RedirectToAction("Index"));
                    }
                }
                await Db.SaveChangesAsync();

                //llamada a la simulación
                SimulationBL simulation = new SimulationBL();
                simulation.Simulation(await Db.Sections.Where(x => x.Id == section.Id).FirstOrDefaultAsync());
                //Fin de llamada a la simulación

                await Db.SaveChangesAsync();

                Flash.Success("Ok", "Las ventas del período han sido registradas exitosamente");
                return(RedirectToAction("Index"));
            }
            else
            {
                Flash.Error("Error", "Ha Ocurrido un error registrando las ventas");
                return(RedirectToAction("Index"));
            }
        }