using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using AutoMapper; using AutoMapper.QueryableExtensions; using InventoryTraker.Web.ActionResults; using InventoryTraker.Web.Core; using InventoryTraker.Web.Data; using InventoryTraker.Web.Models; namespace InventoryTraker.Web.Controllers { public class InventoryController : ControllerBase { private readonly AppDbContext _context; public InventoryController(AppDbContext context) { _context = context; } public ActionResult Index() { return View(); } public JsonResult All() { var viewModels = AllInventory() .ProjectTo() .ToArray(); return BetterJson(viewModels); } private IQueryable AllInventory() { return _context .Inventories .Where(x => x.Quantity > 0) .OrderBy(x => x.InventoryType.Name); } public JsonResult Add(InventoryAddForm form) { if (!ModelState.IsValid) return GetModelStateErrorListJson(); var inventory = Mapper.Map(form); inventory.InventoryType = _context.InventoryTypes.Find(form.InventoryTypeId); _context.Inventories.Add(inventory); inventory.Transactions = new List { new Transaction { TransactionType = TransactionType.Added, AddedQuantity = inventory.Quantity, CurrentQuantity = inventory.Quantity, Memo = "Arrival", Timestamp = DateTime.Now, TransactionDate = inventory.AddedDate } }; _context.SaveChanges(); var model = Mapper.Map(inventory); return BetterJson(model); } public JsonResult Distribute(InventoryDistributeForm form) { if (!ModelState.IsValid) return GetModelStateErrorListJson(); foreach (var quantityForm in form.InventoryQuantities) { var inventory = _context.Inventories.Find(quantityForm.InventoryId); // check if it's really there if (inventory == null) return BetterJsonResult.Error($"Inventory {quantityForm.InventoryId} not found"); if (inventory.Quantity < quantityForm.Quantity) return BetterJsonResult.Error( $"Inventory {inventory.InventoryType.Name} has only {inventory.Quantity}, trying to remove {quantityForm.Quantity}"); inventory.Quantity -= quantityForm.Quantity; inventory.Transactions.Add(new Transaction { TransactionType = TransactionType.Distributed, RemovedQuantity = quantityForm.Quantity, CurrentQuantity = inventory.Quantity, Memo = "Distributed to " + form.Destination, Timestamp = DateTime.Now, TransactionDate = form.DistributedDate }); } _context.SaveChanges(); return BetterJson(AllInventory() .ProjectTo() .ToArray()); } } }