public async Task <IActionResult> CreateOrders([FromBody] CreateStoreOrdersModel model) { if (model == null) { throw new ApiException(400, "Invalid request body", ErrorCode.InvalidRequestFormat); } var purchase = await _storeOrdersService.CreatePurchase(model, _currentUser.Id); return(Created($"/api/purchases/{purchase.Id}", _mapper.Map <MyPurchase>(purchase))); }
public async Task <Purchase> CreatePurchase(CreateStoreOrdersModel model, int currentUserId) { var storeOrder = new StoreOrder { StoreId = model.StoreId, IsSubmitted = false }; var purchase = new Purchase { Type = PurchaseType.Store, CreatorId = currentUserId, IsPayedOff = false, Name = model.Name, CreatedAt = DateTime.Now, StoreOrder = storeOrder }; _db.Purchases.Add(purchase); await _db.SaveChangesAsync(); var userPurchases = model.Users .Union(new List <int> { currentUserId }) .Select(u => new UserPurchase { PurchaseId = purchase.Id, UserId = u, Status = PurchaseStatus.New }); _db.UserPurchases.AddRange(userPurchases); await _db.SaveChangesAsync(); return(await _db.Purchases .Include(up => up.StoreOrder) .Include(up => up.UserPurchases) .ThenInclude(p => p.User) .Include(up => up.UserPurchases) .ThenInclude(p => p.Items) .Where(p => p.Id == purchase.Id) .FirstOrDefaultAsync()); }