public async Task <IActionResult> Create(BeveragesCreateViewModel beverages) { if (ModelState.IsValid) { var _beverages = new Beverages { Title = beverages.Title, Description = beverages.Description, Price = beverages.Price, ProducerId = beverages.ProducerId, Category = beverages.Category, Qty = beverages.Qty }; using (var memoryStream = new MemoryStream()) { if (beverages.Image != null) { await beverages.Image.CopyToAsync(memoryStream); _beverages.Image = memoryStream.ToArray(); } } _context.Add(_beverages); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(beverages)); }
public async Task <IActionResult> Create(Payments payments) { if (ModelState.IsValid) { Payments p = payments; p.Beverages = _context.Beverages.AsNoTracking().ToList(); var beverage = await _context.Beverages.FirstOrDefaultAsync(m => m.Id == payments.BeverageId); if (beverage.Qty - 1 < 0) { ViewBag["Error"] = "Error: Отсутствет напиток"; return(View(payments)); } beverage.Qty--; foreach (var coin in payments.Coins) { coin.Count = coin.Count + coin.CurrentCount; coin.CurrentCount = 0; } _context.Update(beverage); _context.Add(payments); //считаю сдачу int change = payments.Change; int count = payments.Coins.Count; foreach (var coin in payments.Coins.OrderByDescending(t => t.Cost)) { if (coin.Count >= 0) { int c = change / coin.Cost; if (c == 0) { continue; } if (c <= coin.Count) { change = change - c * coin.Cost; coin.Count = coin.Count - c; coin.CurrentCount = c; } else { change = change - (coin.Count * coin.Cost); coin.Count = 0; coin.CurrentCount = coin.Count; } _context.Attach(coin); _context.Entry(coin).State = EntityState.Modified; } } if (change > 0) { ModelState.Clear(); ModelState.AddModelError("Error", "Error: Нельзя дать сдачу"); ViewBag.Error = "Error: Нельзя дать сдачу"; return(View(p)); } Payments payments1 = new Payments(); payments1.Coins = _context.Coins.AsNoTracking().ToList(); payments1.Beverages = _context.Beverages.AsNoTracking().ToList(); payments1.Money = payments.Change; payments1.Change = payments.Change; foreach (var coin in payments.Coins) { var c = payments1.Coins.Where(id => id.Id == coin.Id && id.Cost == coin.Cost).FirstOrDefault(); if (c == null) { ViewBag.Error = "Error: Произошла ошибка, пожалуйста, получите сдачу и начните работу сначала"; return(View(p)); } c.CurrentCount = coin.CurrentCount; c.Count = coin.Count; } await _context.SaveChangesAsync(); ModelState.Clear(); return(View("Create", payments1)); } return(View(payments)); }