using Contracts.BindingModels; using Contracts.ViewModels; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace ImplementerApp.Controllers { public class ProductController : Controller { private readonly ILogger _logger; private readonly ImplementerData _data; public ProductController(ILogger logger, ImplementerData data) { _logger = logger; _data = data; } private bool IsLoggedIn { get { return UserImplementer.user != null; } } private int UserId { get { return UserImplementer.user!.Id; } } [HttpGet] public IActionResult IndexProduct() { if (IsLoggedIn) { var products = _data.GetProducts(UserImplementer.user!.Id); return View(products); } return RedirectToAction("IndexNonReg"); } [HttpPost] public IActionResult IndexProduct(int id) { _data.DeleteProduct(id); return RedirectToAction("IndexProduct"); } [HttpGet] public IActionResult CreateProduct(int id) { var details = _data.GetDetails(UserImplementer.user!.Id); ViewBag.AllDetails = details; if (id != 0) { var value = _data.GetProduct(id); if (value != null) return View(value); } return View(new ProductViewModel()); } [HttpPost] public IActionResult CreateProduct(int id, string title, int[] detailIds, int[] counts) { ProductBindingModel model = new ProductBindingModel(); model.Id = id; model.Name = title; model.UserId = UserImplementer.user!.Id; var details = _data.GetDetails(UserImplementer.user!.Id); double sum = 0; for (int i = 0; i < detailIds.Length; i++) { var detail = details!.FirstOrDefault(x => x.Id == detailIds[i])!; if (counts[i] <= 0) continue; model.ProductDetails[detailIds[i]] = (detail, counts[i]); sum += detail.Cost * counts[i]; } if (model.ProductDetails.Count == 0) return RedirectToAction("IndexProduct"); model.Cost = sum; try { if (id != 0) { _data.UpdateProduct(model); } else { _data.CreateProduct(model); } } catch (InvalidOperationException ex) { ViewBag.ErrorMessage = "Такое название изделия уже существует"; return View(); } return RedirectToAction("IndexProduct"); } [HttpGet] public IActionResult ProductMachineAdd(int id) { if (!IsLoggedIn) return RedirectToAction("IndexNonReg"); var product = _data.GetProduct(id); ViewBag.Product = product; var machines = _data.GetMachines(); return View(machines); } [HttpPost] public IActionResult ProductMachineAdd(int productId, int machineId) { if (!IsLoggedIn) return RedirectToAction("IndexNonReg"); var product = _data.GetProduct(productId); if (product == null) return RedirectToAction("Index"); ProductBindingModel productBinding = new() { Id = productId, Cost = product.Cost, Name = product.Name, UserId = product.UserId, ProductDetails = product.DetailProducts, MachineId = machineId }; _data.UpdateProduct(productBinding); return RedirectToAction("IndexProduct"); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(); } } }