/
daniilsavchenko
/
StockFlow
Обзор
Документация
Войти
/
daniilsavchenko
/
StockFlow
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
Controllers/ProductsController.cs
249 строк
9 KB
StockFlow Student
Finalize StockFlow project
24 май 2026, 18:40
24 май 2026, 18:40
e787c84
Код
Авторство
О чём код?
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using StockFlow.Data; using StockFlow.Models; using StockFlow.Models.ViewModels; namespace StockFlow.Controllers { public class ProductsController : Controller { private readonly AppDbContext _context; private readonly int _lowStockThreshold; public ProductsController(AppDbContext context, IOptions<InventorySettings> inventorySettings) { _context = context; _lowStockThreshold = inventorySettings.Value.LowStockThreshold; } public async Task<IActionResult> Index(string? searchString, string? sortOrder) { IQueryable<Product> query = _context.Products .Include(p => p.Supplier) .Include(p => p.Category) .Include(p => p.UnitOfMeasure) .Include(p => p.Stock) .Include(p => p.CurrentPrice); if (!string.IsNullOrWhiteSpace(searchString)) { query = query.Where(p => p.Name.Contains(searchString) || (p.Description != null && p.Description.Contains(searchString)) || (p.Supplier != null && p.Supplier.Name.Contains(searchString)) || (p.Category != null && p.Category.Name.Contains(searchString))); } query = sortOrder switch { "name_desc" => query.OrderByDescending(p => p.Name), "quantity" => query.OrderBy(p => p.Stock != null ? p.Stock.Quantity : 0), "quantity_desc" => query.OrderByDescending(p => p.Stock != null ? p.Stock.Quantity : 0), "price" => query.OrderBy(p => p.CurrentPrice != null ? p.CurrentPrice.RetailPrice : 0m), "price_desc" => query.OrderByDescending(p => p.CurrentPrice != null ? p.CurrentPrice.RetailPrice : 0m), "supplier" => query.OrderBy(p => p.Supplier != null ? p.Supplier.Name : "Без поставщика").ThenBy(p => p.Name), "supplier_desc" => query.OrderByDescending(p => p.Supplier != null ? p.Supplier.Name : "Без поставщика").ThenBy(p => p.Name), _ => query.OrderBy(p => p.Name) }; var products = await query.ToListAsync(); var viewModel = new ProductIndexViewModel { Products = products, SearchString = searchString, SortOrder = sortOrder, LowStockThreshold = _lowStockThreshold, TotalProducts = products.Count, TotalQuantity = products.Sum(p => p.Quantity), TotalValue = products.Sum(p => p.Quantity * p.Price), LowStockProducts = products .Where(p => p.Quantity <= _lowStockThreshold) .OrderBy(p => p.Quantity) .ThenBy(p => p.Name) .ToList() }; return View(viewModel); } public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var product = await _context.Products .Include(p => p.Supplier) .Include(p => p.Category) .Include(p => p.UnitOfMeasure) .Include(p => p.Stock) .Include(p => p.CurrentPrice) .FirstOrDefaultAsync(m => m.Id == id); if (product == null) { return NotFound(); } ViewBag.LowStockThreshold = _lowStockThreshold; return View(product); } public IActionResult Create() { PopulateProductLookups(); return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,Name,Description,CategoryId,UnitOfMeasureId,Quantity,Price,SupplierId")] Product product) { if (ModelState.IsValid) { _context.Add(product); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } PopulateProductLookups(product.SupplierId, product.CategoryId, product.UnitOfMeasureId); return View(product); } public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var product = await _context.Products .Include(p => p.Stock) .Include(p => p.CurrentPrice) .FirstOrDefaultAsync(p => p.Id == id); if (product == null) { return NotFound(); } PopulateProductLookups(product.SupplierId, product.CategoryId, product.UnitOfMeasureId); return View(product); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Description,CategoryId,UnitOfMeasureId,Quantity,Price,SupplierId")] Product product) { if (id != product.Id) { return NotFound(); } if (ModelState.IsValid) { var productToUpdate = await _context.Products .Include(p => p.Stock) .Include(p => p.CurrentPrice) .FirstOrDefaultAsync(p => p.Id == id); if (productToUpdate == null) { return NotFound(); } try { productToUpdate.Name = product.Name; productToUpdate.Description = product.Description; productToUpdate.CategoryId = product.CategoryId; productToUpdate.UnitOfMeasureId = product.UnitOfMeasureId; productToUpdate.SupplierId = product.SupplierId; productToUpdate.Quantity = product.Quantity; productToUpdate.Price = product.Price; await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(product.Id)) { return NotFound(); } throw; } return RedirectToAction(nameof(Index)); } PopulateProductLookups(product.SupplierId, product.CategoryId, product.UnitOfMeasureId); return View(product); } public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var product = await _context.Products .Include(p => p.Supplier) .Include(p => p.Category) .Include(p => p.UnitOfMeasure) .Include(p => p.Stock) .Include(p => p.CurrentPrice) .FirstOrDefaultAsync(m => m.Id == id); if (product == null) { return NotFound(); } return View(product); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var product = await _context.Products.FindAsync(id); if (product != null) { _context.Products.Remove(product); await _context.SaveChangesAsync(); } return RedirectToAction(nameof(Index)); } private bool ProductExists(int id) { return _context.Products.Any(e => e.Id == id); } private void PopulateProductLookups(object? selectedSupplier = null, object? selectedCategory = null, object? selectedUnit = null) { var suppliers = _context.Suppliers .OrderBy(s => s.Name) .ToList(); var categories = _context.ProductCategories .OrderBy(c => c.Name) .ToList(); var units = _context.UnitsOfMeasure .OrderBy(u => u.Name) .ToList(); ViewBag.SupplierId = new SelectList(suppliers, "Id", "Name", selectedSupplier); ViewBag.CategoryId = new SelectList(categories, "Id", "Name", selectedCategory); ViewBag.UnitOfMeasureId = new SelectList(units, "Id", "ShortName", selectedUnit); } } }