public async Task <ActionResult> ChangeOwnership([FromRoute] long id, [FromBody] OwnershipObject ownershipObject) { var stock = await _context.Stocks.Where(x => x.Id == id) .Include(s => s.ShareHolders) .Where(s => s.ShareHolders.Any(q => q.ShareholderId == ownershipObject.Seller)).FirstOrDefaultAsync(); if (stock == null) { _logger.LogError("Failed to find the Seller"); return(NotFound("Failed to find the Seller")); } var actionResult = SetSellerAmount(ownershipObject, stock); if (actionResult != null) { return(actionResult); } SetBuyerAmount(ownershipObject, stock); _logger.LogInformation("Changed ownership of {Amount} shares from {Seller} to {Buyer}", ownershipObject.Amount, ownershipObject.Seller, ownershipObject.Buyer); await _context.SaveChangesAsync(); return(Ok()); }
private static void SetBuyerAmount(OwnershipObject ownershipObject, Stock stock) { var shareHolderBuyer = stock.ShareHolders.FirstOrDefault(sh => sh.ShareholderId == ownershipObject.Buyer); if (shareHolderBuyer == null) { shareHolderBuyer = new Shareholder { ShareholderId = ownershipObject.Buyer, Amount = ownershipObject.Amount }; stock.ShareHolders.Add(shareHolderBuyer); } else { shareHolderBuyer.Amount += ownershipObject.Amount; } }
private ActionResult SetSellerAmount(OwnershipObject ownershipObject, Stock stock) { var shareholderSeller = stock.ShareHolders.FirstOrDefault(sh => sh.ShareholderId == ownershipObject.Seller); if (shareholderSeller == null) { _logger.LogError("Failed to find the Seller"); { return(NotFound("Failed to find the Seller")); } } _logger.LogInformation(@"shareholder Seller Amount {shareholderSellerAmount} request amount {requestAmount}", shareholderSeller.Amount, ownershipObject.Amount); shareholderSeller.Amount -= ownershipObject.Amount; if (shareholderSeller.Amount >= 0) { return(null); } _logger.LogError("Seller cannot go below 0 shares"); return(BadRequest("Seller cannot go below 0 shares")); }