public ActionResult SellStock(string stockCode) { var latestStockDetails = _stockService.GetLatestStockDetails(stockCode); if (latestStockDetails == null) { TempData["Message"] = "You cannot sell selected stock."; TempData["MessageType"] = "error"; return(RedirectToAction("Dashboard", controllerName: "Home")); } SellStockViewModel sellStockModel = Mapper.Map <SellStockViewModel>(latestStockDetails); sellStockModel.AmountAvailable = _stockService.GetUserStockAmountForCode(User.Identity.GetUserId(), stockCode); if (sellStockModel.AmountAvailable == 0) { return(View("SellIsNotPossible")); } ViewBag.SellStockStatus = TempData["SellStockStatus"]; var previousAmountToSell = TempData["SellStockModel.AmountToSell"]; if (previousAmountToSell != null && previousAmountToSell.ToString() != "") { int.TryParse(previousAmountToSell.ToString(), out int amountToSell); sellStockModel.AmountToSell = amountToSell; var validateResult = TryValidateModel(sellStockModel); } return(View(sellStockModel)); }
// GET: StockPortfolios/SellStock public async Task <IActionResult> SellStock(int?id) { if (id == null) { return(NotFound()); } var ownedStocks = from allStocks in _context.Stocks join allSpsMappings in _context.SpsMappings on allStocks.Id equals allSpsMappings.StockId where allSpsMappings.StockPortfolioId == id select allStocks; var ownedStockList = await ownedStocks.Select(s => new SelectListItem() { Text = s.Name, Value = s.Id.ToString() }).ToListAsync(); var sellStockViewModel = new SellStockViewModel() { OwnedStockList = ownedStockList }; ViewBag.PortfolioId = id; TempData["OwnedStockList"] = JsonConvert.SerializeObject(ownedStockList); return(View(sellStockViewModel)); }
public ActionResult SellStock(SellStockViewModel model, int StockPurchaseID) { AppUser user = db.Users.Find(User.Identity.GetUserId()); StockPortfolio stockPortfolio = user.StockPortfolio; model.stockPortfolioID = stockPortfolio.StockPortfolioID; if (ModelState.IsValid) { StockPurchase stockPurchase = db.StockPurchases.Find(StockPurchaseID); if (model.NumberOfSharesToSell > stockPurchase.NumberOfShares) { return(View("Error", new string[] { "You can't sell more shares than what you have." })); } if (model.NumberOfSharesToSell == 0) { return(View("Error", new string[] { "Why are you trying to sell 0 shares...?" })); } if (model.NumberOfSharesToSell < 0) { return(View("Error", new string[] { "You can't sell a negative number of shares." })); } model.stockPurchaseID = StockPurchaseID; model.StockName = stockPurchase.Stock.StockName; model.SellDate = DateTime.Now; model.NumberOfSharesToSell = model.NumberOfSharesToSell; model.NumberOfSharesRemaining = stockPurchase.NumberOfShares - model.NumberOfSharesToSell; model.Fees = stockPurchase.Stock.Fee; model.NetGainLoss = (stockPurchase.Stock.CurrentPrice * model.NumberOfSharesToSell) - (stockPurchase.InitialSharePrice * model.NumberOfSharesToSell); return(RedirectToAction("SellStockSummaryPage", model)); } ViewBag.CustomerStockPurchases = GetCustomerStockPurchases(); return(View(model)); }
//GET: StockPortfolios/SellStock public ActionResult SellStock() { AppUser user = db.Users.Find(User.Identity.GetUserId()); StockPortfolio stockPortfolio = user.StockPortfolio; SellStockViewModel model = new SellStockViewModel { stockPortfolioID = stockPortfolio.StockPortfolioID }; ViewBag.CustomerStockPurchases = GetCustomerStockPurchases(); return(View(model)); }
public IActionResult Sell(long id) { var sellStockViewModel = new SellStockViewModel { Id = id, AmountOfShares = 0, TimeOut = DateTime.Today.AddDays(1), Price = 0 }; return(View(sellStockViewModel)); }
public async Task <IActionResult> Sell([Bind("Id,TimeOut,AmountOfShares,Price")] SellStockViewModel sellStockViewModel) { var(jwtToken, id) = JwtHelper.GetJwtAndIdFromJwt(Request); var sellRequestRequest = new SellRequestRequest { AccountId = id, AmountOfShares = sellStockViewModel.AmountOfShares, TimeOut = sellStockViewModel.TimeOut, Price = sellStockViewModel.Price, StockId = sellStockViewModel.Id }; var validationResult = await _stockShareProviderClient.SetSharesForSale(sellRequestRequest, jwtToken); if (validationResult.Valid) { return(await OwnedStockList()); } ViewBag.ShowErrorDialog = true; ViewBag.ErrorText = validationResult.ErrorMessage; return(View(sellStockViewModel)); }
public ActionResult SellStockConfirmed(SellStockViewModel sellStockModel) { if (ModelState.IsValid == false) { TempData["SellStockModel.AmountToSell"] = sellStockModel.AmountToSell; return(RedirectToAction("sell", new { stockCode = sellStockModel.Code.ToLower() })); } var userId = User.Identity.GetUserId(); var sellStockStatus = _stockService.SellStock(userId, sellStockModel); if (sellStockStatus == Infrastructure.Enum.StockSellStatus.Success) { TempData["Message"] = "You have successfully sold stocks!"; TempData["MessageType"] = "success"; return(RedirectToAction("dashboard", controllerName: "home")); } else { TempData["SellStockStatus"] = sellStockStatus; return(RedirectToAction("Sell", new { stockCode = sellStockModel.Code.ToLower() })); } }
public async Task <IActionResult> SellStock(int id, [Bind("StockId", "NumberOfShares", "OwnedStockList")] SellStockViewModel sellStockViewModel) { var portfolioId = id; var stockId = sellStockViewModel.StockId; var shareBlock = GetShareBlock(portfolioId, stockId); if (shareBlock.NumberOfShares < sellStockViewModel.NumberOfShares) { ModelState.AddModelError("NumberOfShares", "Transaction failed! You don't have that many shares to sell! Please select a smaller number."); } if (ModelState.IsValid) { var stockPortfolio = _context.StockPortfolios.Where(sp => sp.Id == portfolioId).Include("SpsMappings").Single(); var stock = _context.Stocks.Where(s => s.Id == stockId).Single(); if (shareBlock.NumberOfShares == sellStockViewModel.NumberOfShares) { stock.ShareBlocks.Remove(shareBlock); var spsMapping = stockPortfolio.SpsMappings.Where(spsm => spsm.StockId == stockId).Single(); // Unnecessary? Maybe these are removed automatically by Entity Framework? stock.SpsMappings.Remove(spsMapping); stockPortfolio.SpsMappings.Remove(spsMapping); _context.Update(stock); _context.Update(stockPortfolio); _context.Remove(spsMapping); _context.Remove(shareBlock); } else { shareBlock.NumberOfShares -= sellStockViewModel.NumberOfShares; _context.Update(shareBlock); } try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!StockPortfolioExists(stockPortfolio.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction("Content", new { id = id })); } sellStockViewModel.OwnedStockList = JsonConvert.DeserializeObject <IEnumerable <SelectListItem> >(TempData["OwnedStockList"].ToString()); TempData.Keep("OwnedStockList"); return(View(sellStockViewModel)); }
public ActionResult SellStock(SellStockViewModel sellStockModel) { return((ModelState.IsValid) ? View("SellConfirm", sellStockModel) : View("Sell", sellStockModel)); }
public ActionResult SellStockSummaryPage(SellStockViewModel SellInfo, SellStockDecision decision) { switch (decision) { case SellStockDecision.Cancel: { return(RedirectToAction("Details", new { id = SellInfo.stockPortfolioID })); } case SellStockDecision.Confirm: { StockPortfolio stockPortfolio = db.StockPortfolios.Find(SellInfo.stockPortfolioID); StockPurchase stockPurchase = db.StockPurchases.Find(SellInfo.stockPurchaseID); stockPurchase.NumberOfShares = SellInfo.NumberOfSharesRemaining; stockPurchase.TotalStockValue = SellInfo.NumberOfSharesRemaining * stockPurchase.Stock.CurrentPrice; stockPurchase.TotalChange = (SellInfo.NumberOfSharesRemaining * stockPurchase.Stock.CurrentPrice) - (SellInfo.NumberOfSharesRemaining * stockPurchase.InitialSharePrice); stockPurchase.ChangeInPrice = stockPurchase.Stock.CurrentPrice - stockPurchase.InitialSharePrice; stockPurchase.StockPurchaseDisplay = stockPurchase.Stock.StockName + ", Current Price: " + stockPurchase.Stock.CurrentPrice.ToString("c") + ", Number of shares: " + stockPurchase.NumberOfShares.ToString(); stockPortfolio.CashValueBalance += ((SellInfo.NumberOfSharesToSell * stockPurchase.Stock.CurrentPrice) - SellInfo.Fees); stockPortfolio.StockPortionValue -= SellInfo.NumberOfSharesToSell * stockPurchase.Stock.CurrentPrice; Transaction StockTransaction = new Transaction(); StockTransaction.Amount = stockPurchase.Stock.CurrentPrice * SellInfo.NumberOfSharesToSell; StockTransaction.StockPortfolioAffected = stockPortfolio; StockTransaction.Description = "Sell Stock - Stock: " + SellInfo.StockName + ", Number of shares sold: " + SellInfo.NumberOfSharesToSell + ", Initial Share price: " + stockPurchase.InitialSharePrice.ToString("c") + ", Current Share Price: " + stockPurchase.Stock.CurrentPrice.ToString("c") + ", Total Gains/Loss: " + SellInfo.NetGainLoss.ToString("c"); StockTransaction.TransactionDate = SellInfo.SellDate; StockTransaction.TransactionType = "Deposit"; StockTransaction.isBeingDisputed = false; StockTransaction.isPending = false; StockTransaction.EmployeeComments = ""; Transaction TransactionFee = new Transaction(); TransactionFee.Amount = SellInfo.Fees; TransactionFee.StockPortfolioAffected = stockPortfolio; TransactionFee.Description = "Fee for sale of " + stockPurchase.Stock.StockName; TransactionFee.TransactionDate = SellInfo.SellDate; TransactionFee.TransactionType = "Fee"; TransactionFee.isBeingDisputed = false; TransactionFee.isPending = false; TransactionFee.EmployeeComments = ""; int OrdinaryCount = 0; int IndexCount = 0; int MutalCount = 0; foreach (var s in stockPortfolio.StockPurchases) { if (s.Stock.StockType.Equals("Ordinary Stock")) { OrdinaryCount += 1; } else if (s.Stock.StockType.Equals("Index Fund")) { IndexCount += 1; } else if (s.Stock.StockType.Equals("Mutual Fund")) { MutalCount += 1; } } if (OrdinaryCount >= 2 && IndexCount >= 1 && MutalCount >= 1) { stockPortfolio.isBalanced = true; } else { stockPortfolio.isBalanced = false; } stockPortfolio.Transactions.Add(StockTransaction); stockPortfolio.Transactions.Add(TransactionFee); db.Transactions.Add(StockTransaction); db.Transactions.Add(TransactionFee); if (stockPurchase.NumberOfShares == 0) { db.StockPurchases.Remove(stockPurchase); } db.SaveChanges(); return(RedirectToAction("SellStockConfirmation")); } } return(View(SellInfo)); }
//GET: StockPortfolios/SellStockSummaryPage public ActionResult SellStockSummaryPage(SellStockViewModel SellInfo) { return(View(SellInfo)); }
public StockSellStatus SellStock(string userId, SellStockViewModel sellStockModel) { // check if user change the form data, provided stock value has to exists in database StockValue sellingStockValue = GetStockForCodeAndValue( sellStockModel.Code, sellStockModel.Unit, sellStockModel.Price); if (sellingStockValue == null) { return(StockSellStatus.Unknown); } decimal totalCost = sellStockModel.AmountToSell / sellingStockValue.Unit * sellingStockValue.Price; // case 1: User does not have enough stock User seller = _db.UserApp.Where(x => x.Id.Equals(userId)).FirstOrDefault(); UserStocks stockOwnedBySeller = seller.Stocks .Where(x => x.StockID == sellingStockValue.StockID) .FirstOrDefault(); if (stockOwnedBySeller == null || stockOwnedBySeller.Amount < sellStockModel.AmountToSell) { return(StockSellStatus.UserHasNotEnoughStocks); } // case 2: Stock value data have changed - there was an update StockDetails latestStockDetails = GetLatestStockDetails(sellStockModel.Code); bool isSellerSellingStockByLatestPrice = AreDatesTheSameComparisonLikeHuman( latestStockDetails.PublicationDate, sellingStockValue.PublicationDate); if (isSellerSellingStockByLatestPrice == false) { return(StockSellStatus.StockValueDataHaveChanged); } using (var dbContextTransaction = _db.Database.BeginTransaction()) { try { // then 1: Add money to User wallet seller.Money += totalCost; // then 2: Subtract specified amount of stock from UserStocks stockOwnedBySeller.Amount -= sellStockModel.AmountToSell; if (stockOwnedBySeller.Amount == 0) { _db.UserStocks.Remove(stockOwnedBySeller); } //then 3: Increase available stock amount _db.Stock.Attach(sellingStockValue.Stock); _db.Entry(sellingStockValue.Stock).Reload(); sellingStockValue.Stock.AvailableAmount += sellStockModel.AmountToSell; _db.Entry(sellingStockValue.Stock).State = System.Data.Entity.EntityState.Modified; // save and commit _db.SaveChanges(); dbContextTransaction.Commit(); return(StockSellStatus.Success); // everything went well, so finally success } catch (Exception e) { _logger.Error("Transaction error during selling stock. Error " + e.Message); _logger.Error("Rollback..."); dbContextTransaction.Rollback(); } } return(StockSellStatus.Unknown); }