public async Task <ActionResult> CreateExchange(ItemExchangeModel itemExchangeModel) { string userId = (string)TempData["UserId"]; itemExchangeModel.NewOwnerAccountId = userId; string jsonString = JsonConvert.SerializeObject(itemExchangeModel); HttpResponseMessage httpResponseMessage = await ApiClient.PostAsync("/Item/exchangeItem", jsonString); httpResponseMessage.EnsureSuccessStatusCode(); string responseResult = httpResponseMessage.Content.ReadAsStringAsync().Result; var itemExchangeResponse = JsonConvert.DeserializeObject <ItemExchangeResponse>(responseResult); TempData["ExchangeErrors"] = itemExchangeResponse.Errors; return(RedirectToAction("Index", new { id = userId })); }
public async Task <IResponse> ExchangeItem([FromBody] ItemExchangeViewModel itemExchangeViewModel) { ItemExchangeResponse itemExchangeResponse = new ItemExchangeResponse(); List <string> errors = new List <string>(); Item item = await _context.Items.Include(x => x.Category).Include(x => x.OwnerAccount).FirstOrDefaultAsync(x => x.Id == itemExchangeViewModel.ItemId); if (item != null) { Account newOwnerAccount = await _userManager.FindByIdAsync(itemExchangeViewModel.NewOwnerAccountId); if (newOwnerAccount != null) { PointsModel points = await _context.Points.SingleOrDefaultAsync(x => x.Account == newOwnerAccount); if (points.Value >= itemExchangeViewModel.PointValue) { await _pointManager.RemoveFromUserAsync(newOwnerAccount, itemExchangeViewModel.PointValue); Account oldOwnerAccount = item.OwnerAccount; item.OwnerAccount = newOwnerAccount; _context.Items.Update(item); await _context.SaveChangesAsync(); ItemExchangeModel itemExchangeModel = new ItemExchangeModel { Item = item, OldOwnerAccount = oldOwnerAccount, NewOwnerAccount = item.OwnerAccount, PointValue = itemExchangeViewModel.PointValue }; ItemExchange itemExchange = new ItemExchange(_context); itemExchange.Set(itemExchangeModel); itemExchangeResponse = await itemExchange.CommitAsync(); errors.Add("Item checked out successfully"); } else { errors.Add($"Not enough points for user :{newOwnerAccount.UserName}"); } } else { errors.Add("User not found."); } } else { errors.Add("Item not found."); } if (errors.Count > 0) { itemExchangeResponse.Errors = errors; } else { itemExchangeResponse.Errors = null; } return(itemExchangeResponse); }