diff --git a/WeChatApplet/Services/Impl/ClientSideService.cs b/WeChatApplet/Services/Impl/ClientSideService.cs index 95dd642..96b6fc1 100644 --- a/WeChatApplet/Services/Impl/ClientSideService.cs +++ b/WeChatApplet/Services/Impl/ClientSideService.cs @@ -162,25 +162,37 @@ namespace YD_WeChatApplet.Api.Services.Impl /// public async Task PaidCoursesBuy(string redeemCode) { - var paidCoursesList = new List(); - - var paidCourses = await _sportsContext.CurricularTaxonomy.Where(x => x.CurricularType == 2).ToListAsync(); - var userId = UserLoginContext.Current.UserId; - foreach (var paidCourse in paidCourses) - { - paidCoursesList.Add(new Y_CurricularPurchaseRecord() - { - TaxonomyId = paidCourse.Id, - UserId = userId, - RedeemCode = redeemCode, - Remarks = "", - CreateDate = DateTime.Now - }); - } + // 获取用户已经购买的课程 ID(只查类型为2) + var userPurchasedIds = await _sportsContext.CurricularPurchaseRecord + .Where(x => x.UserId == userId) + .Select(x => x.TaxonomyId) + .ToListAsync(); - await _sportsContext.AddRangeAsync(paidCoursesList); + // 获取所有类型为2的课程 + var paidCourses = await _sportsContext.CurricularTaxonomy + .Where(x => x.CurricularType == 2) + .ToListAsync(); + + // 找出用户未购买的课程 + var newCourses = paidCourses + .Where(x => !userPurchasedIds.Contains(x.Id)) + .ToList(); + + if (!newCourses.Any()) + return true; // 全部已购买,无需再加 + + var newRecords = newCourses.Select(course => new Y_CurricularPurchaseRecord + { + TaxonomyId = course.Id, + UserId = userId, + RedeemCode = redeemCode, + Remarks = "", + CreateDate = DateTime.Now + }).ToList(); + + await _sportsContext.AddRangeAsync(newRecords); return await _sportsContext.SaveChangesAsync() > 0; }