public async Task <IHttpActionResult> CreateOne(string giftId) { var gift = await _dbContext.CouponGifts.FindAsync(giftId); if (gift == null) { return(NotFound()); } if (DateTime.Now >= gift.EndTime) { return(this.BadRequest(nameof(giftId), Errors.GiftOffTheMarket)); } var userId = User.Identity.GetUserId(); var user = await _userManager.FindByIdAsync(userId); if (user.Coupon < gift.Price) { return(this.BadRequest(nameof(giftId), Errors.NotEnoughCoupon)); } try { GiftProcessor processor; switch (gift.Type) { case CouponGiftType.Custom: processor = new CustomProcessor(); break; case CouponGiftType.SteamCnCredit: processor = new SteamCnCreditProcessor(_dbContext, _userManager, _coupon); break; case CouponGiftType.SteamGiftCard: processor = new SteamGiftCardProcessor(_dbContext, _coupon); break; default: throw new ArgumentOutOfRangeException(); } processor.Initialize(user, gift); await processor.RedeemAsync(); return(Ok()); } catch (Exception e) { return(this.BadRequest(nameof(giftId), e.Message)); } }
/// <summary> /// 创建 <see cref="CouponGiftList"/> /// </summary> /// <param name="currentUserId">当前用户Id</param> /// <param name="dbContext"><see cref="KeylolDbContext"/></param> /// <param name="cachedData"><see cref="CachedDataProvider"/></param> /// <param name="userManager"><see cref="KeylolUserManager"/></param> /// <param name="coupon"><see cref="CouponProvider"/></param> public static async Task <CouponGiftList> CreateAsync(string currentUserId, KeylolDbContext dbContext, CachedDataProvider cachedData, KeylolUserManager userManager, CouponProvider coupon) { var queryResult = await dbContext.CouponGifts.Where(g => DateTime.Now < g.EndTime) .OrderByDescending(g => g.CreateTime) .ToListAsync(); var currentUser = await userManager.FindByIdAsync(currentUserId); var result = new CouponGiftList(queryResult.Count); foreach (var g in queryResult) { GiftProcessor processor; switch (g.Type) { case CouponGiftType.Custom: processor = new CustomProcessor(); break; case CouponGiftType.SteamCnCredit: processor = new SteamCnCreditProcessor(dbContext, userManager, coupon); break; case CouponGiftType.SteamGiftCard: processor = new SteamGiftCardProcessor(dbContext, coupon); break; default: throw new ArgumentOutOfRangeException(); } var stateTreeGift = new CouponGift { Id = g.Id, Name = g.Name, Descriptions = Helpers.SafeDeserialize <List <string> >(g.Descriptions), Price = g.Price, ThumbnailImage = g.ThumbnailImage, Type = g.Type }; processor.Initialize(currentUser, g); await processor.FillPropertiesAsync(stateTreeGift); result.Add(stateTreeGift); } return(result); }