public async Task <ActionResult> BuySecurities([FromBody] BuySecurity security) { var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); //retuns the userId security.UserId = Guid.Parse(userId); security.SecurityId = Guid.NewGuid(); await busClient.PublishAsync(security); return(Accepted($"BuySecurities/{security.SecurityId}")); }
public async Task BuySecurityAsync(BuySecurity security) { if (security == null) { throw new CustomException("empty_security", $"Security is empty."); } var portfolio = await repository.FindAsync(p => p.UserId.Equals(security.UserId) && p.PortfolioId.Equals(security.PortfolioId)); if (portfolio == null) { throw new CustomException("portfolio_not_found", $"Portfolio not found for user: {security.UserId}"); } var securityEntity = portfolio.Securities.FirstOrDefault(i => i.Symbol.Equals(security.Symbol)); if (securityEntity != null) { securityEntity.AverageValue = CalculateAverageValue(securityEntity.Quantity, securityEntity.AverageValue, security.Quantity, security.CurrentValue); securityEntity.Quantity += security.Quantity; } else { securityEntity = new Security { Name = security.Name, Symbol = security.Symbol, CurrentValue = security.CurrentValue, AverageValue = security.CurrentValue, Quantity = security.Quantity, }; } portfolio.Securities.Add(securityEntity); var saved = await repository.SaveAsync(); if (!saved) { throw new CustomException("problem_buying_securities", $"Could not buy the security: {security.Symbol}."); } }