public async Task <IActionResult> PostProduct(ATITransactionDto newTransaction) { var userId = HttpContext.GetUserId(); var isSuccess = await _repo.AddProduct(newTransaction, userId, newTransaction.Content.ProductId == -1); if (isSuccess) { return(RedirectToAction("Index", "Products")); } return(RedirectToAction("Error", "Home")); }
public async Task <bool> AddProduct(ATITransactionDto tAtiTransactionDto, int userId, bool isNew) { var user = await _context.Users .FirstOrDefaultAsync(u => u.Id == userId); if (user == null) { return(false); } var price = tAtiTransactionDto.Content.ProductionPrice; var salePrice = tAtiTransactionDto.Content.SalePrice; var transaction = new Transaction { Date = DateTime.Now, Description = tAtiTransactionDto.Description, FromId = userId, ToId = userId, Type = TransactionType.Addition, TotalAmount = tAtiTransactionDto.Content.Count * price }; if (isNew) { var product = new Product { Name = tAtiTransactionDto.Content.Name, Packaging = tAtiTransactionDto.Content.Packaging, ExpirationDate = tAtiTransactionDto.Content.ExpirationDate, ProductionDate = tAtiTransactionDto.Content.ProductionDate, SalePrice = salePrice, StockCount = tAtiTransactionDto.Content.Count, OwnerId = userId, ProductionPrices = new List <Price> { new Price { Value = price, AdditionDate = DateTime.Now } } }; var transactionProduct = new Transaction_Product { Transaction = transaction, Product = product, Count = tAtiTransactionDto.Content.Count, SalePrice = salePrice }; await _context.TransactionProducts.AddAsync(transactionProduct); Console.WriteLine("ADDED AS NEW PRODUCT"); } else { var transactionProduct = new Transaction_Product { Transaction = transaction, ProductId = tAtiTransactionDto.Content.ProductId, Count = tAtiTransactionDto.Content.Count, SalePrice = salePrice }; var product = await _context.Products .Include(p => p.ProductionPrices) .FirstOrDefaultAsync(p => p.Id == tAtiTransactionDto.Content.ProductId); product.StockCount += tAtiTransactionDto.Content.Count; product.ProductionPrices.Add(new Price { ProductId = product.Id, Value = price, AdditionDate = DateTime.Now }); await _context.TransactionProducts.AddAsync(transactionProduct); } var dbRes = await _context.SaveChangesAsync(); return(dbRes > 0); }