public async Task <IActionResult> Edit(int id, BeveragesCreateViewModel beverages) { if (id != beverages.Id) { return(NotFound()); } if (ModelState.IsValid) { try { var _beverages = await _context.Beverages.AsNoTracking().FirstOrDefaultAsync(t => t.Id == id); _beverages.Title = beverages.Title; _beverages.Description = beverages.Description; _beverages.Price = beverages.Price; _beverages.ProducerId = beverages.ProducerId; _beverages.Category = beverages.Category; _beverages.Qty = beverages.Qty; using (var memoryStream = new MemoryStream()) { if (beverages.Image != null) { await beverages.Image.CopyToAsync(memoryStream); _beverages.Image = memoryStream.ToArray(); } } _context.Attach(_beverages); _context.Entry(_beverages).State = EntityState.Modified; await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!BeveragesExists(beverages.Id)) { return(NotFound()); } else { throw; } } 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)); }