GoalProgressByToken.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using Application.Abstractions.Data;
  2. using Web.Api.Common;
  3. using MediatR;
  4. using Microsoft.EntityFrameworkCore;
  5. namespace Web.Api.Endpoints.Widget;
  6. /// <summary>WidgetToken + configID 기반 후원 목표 진행 상태 (위젯 초기 로드용, 인증 불필요).
  7. /// configID 미지정 시 활성 첫 번째 자동 선택.</summary>
  8. internal sealed class GoalProgressByToken : IEndpoint
  9. {
  10. public void MapEndpoint(IEndpointRouteBuilder app)
  11. {
  12. app.MapGet("api/widget/goal/by-token/{widgetToken}", async (
  13. string widgetToken,
  14. int? configID,
  15. IAppDbContext db,
  16. ISender sender,
  17. CancellationToken ct
  18. ) => {
  19. var channelID = await db.Channel.AsNoTracking()
  20. .Where(c => c.WidgetToken == widgetToken && c.IsActive)
  21. .Select(c => c.ID)
  22. .FirstOrDefaultAsync(ct);
  23. if (channelID == 0)
  24. {
  25. return ApiResponse.Ok((object?)null);
  26. }
  27. int? targetGoalConfigID;
  28. if (configID.HasValue)
  29. {
  30. targetGoalConfigID = await db.DonationGoalConfig.AsNoTracking()
  31. .Where(g => g.ChannelID == channelID && g.ID == configID.Value)
  32. .Select(g => (int?)g.ID)
  33. .FirstOrDefaultAsync(ct);
  34. }
  35. else
  36. {
  37. targetGoalConfigID = await db.DonationGoalConfig.AsNoTracking()
  38. .Where(g => g.ChannelID == channelID && g.IsActive)
  39. .OrderByDescending(g => g.ID)
  40. .Select(g => (int?)g.ID)
  41. .FirstOrDefaultAsync(ct);
  42. }
  43. if (targetGoalConfigID is null)
  44. {
  45. return ApiResponse.Ok((object?)null);
  46. }
  47. var result = await sender.Send(new Application.Features.Api.DonationGoal.GetProgress.Query(channelID, targetGoalConfigID.Value), ct);
  48. if (result.IsFailure)
  49. {
  50. return ApiResponse.Ok((object?)null);
  51. }
  52. var data = result.Value;
  53. return ApiResponse.Ok(new
  54. {
  55. goalConfigID = data.GoalConfigID,
  56. title = data.Title,
  57. startAmount = data.StartAmount,
  58. targetAmount = data.TargetAmount,
  59. currentAmount = data.CurrentAmount,
  60. percent = data.Percent
  61. });
  62. })
  63. .WithTags("Widget")
  64. .AllowAnonymous();
  65. }
  66. }