| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135 |
- using Application.Abstractions.Cache;
- using Application.Abstractions.Data;
- using Application.Features.Config.Get;
- using Domain.Entities.Common.ValueObject;
- using Domain.Entities.Wallets.ValueObject;
- using Microsoft.EntityFrameworkCore;
- namespace Application.Helpers;
- /// <summary>
- /// 활동 토큰 보상 지급 (게시글/댓글 작성 → Wallet Reward 파티션).
- /// 멱등: WalletTransaction RefID "activity-post:{postID}" / "activity-comment:{commentID}" 가 이미 있으면 재지급하지 않는다.
- /// 게시글/댓글 작성 핸들러에서 호출하며, SaveChangesAsync 는 호출자가 수행한다(작성이 주된 결과, 지급은 부수효과).
- /// </summary>
- public static class ActivityTokenGranter
- {
- public const string PostReason = "ACTIVITY_POST";
- public const string CommentReason = "ACTIVITY_COMMENT";
- private static readonly TimeZoneInfo KstZone = ResolveKst();
- public static string PostRefIDFor(int postID) => $"activity-post:{postID}";
- public static string CommentRefIDFor(int commentID) => $"activity-comment:{commentID}";
- /// <summary>게시글 작성 보상. 설정 토큰이 0 이거나 일일 상한 초과 시 아무것도 하지 않는다.</summary>
- public static Task GrantForPostAsync(IAppDbContext db, ICacheService cache, int memberID, int postID, CancellationToken ct)
- => GrantAsync(db, cache, memberID, PostReason, PostRefIDFor(postID), forPost: true, ct);
- /// <summary>댓글 작성 보상. 설정 토큰이 0 이거나 일일 상한 초과 시 아무것도 하지 않는다.</summary>
- public static Task GrantForCommentAsync(IAppDbContext db, ICacheService cache, int memberID, int commentID, CancellationToken ct)
- => GrantAsync(db, cache, memberID, CommentReason, CommentRefIDFor(commentID), forPost: false, ct);
- private static async Task GrantAsync(IAppDbContext db, ICacheService cache, int memberID, string reason, string refID, bool forPost, CancellationToken ct)
- {
- if (memberID <= 0)
- {
- return;
- }
- var config = await LoadConfigAsync(db, cache, ct);
- if (config is null)
- {
- return;
- }
- var amount = forPost ? config.PostToken : config.CommentToken;
- if (amount <= 0)
- {
- return;
- }
- // 멱등: 동일 게시글/댓글에 대한 활동 토큰 원장이 이미 있으면 재지급 금지
- var alreadyGranted = await db.WalletTransaction.AsNoTracking()
- .AnyAsync(c => c.RefID == refID && c.TxType == WalletTransactionType.RewardEarned, ct);
- if (alreadyGranted)
- {
- return;
- }
- // 일일 상한(DailyTokenCap>0): 오늘(서버 KST 기준) 이미 지급된 활동 토큰 합계를 구해 남은 한도로 clamp.
- // 활동 토큰 원장은 reason ACTIVITY_POST / ACTIVITY_COMMENT 로만 기록되므로 이 두 사유의 오늘 합계를 센다.
- // 별도 일일 카운터 엔티티가 없어(MemberDailyRewardCounter 부재) same-day 합계 방식으로 구현한다.
- if (config.DailyTokenCap > 0)
- {
- // 서버 TZ 무관하게 KST 일 경계(자정~익일 자정)를 UTC 범위로 환산해 오늘 지급분을 집계
- var nowKst = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, KstZone);
- var todayStartUtc = TimeZoneInfo.ConvertTimeToUtc(DateTime.SpecifyKind(nowKst.Date, DateTimeKind.Unspecified), KstZone);
- var tomorrowStartUtc = todayStartUtc.AddDays(1);
- var wallet = await db.Wallet.AsNoTracking().Select(c => new { c.WalletKey, c.MemberID }).FirstOrDefaultAsync(c => c.MemberID == memberID, ct);
- if (wallet is null)
- {
- return;
- }
- var grantedToday = await db.WalletTransaction.AsNoTracking()
- .Where(c => c.WalletKey == wallet.WalletKey
- && c.TxType == WalletTransactionType.RewardEarned
- && (c.Reason == PostReason || c.Reason == CommentReason)
- && c.CreatedAt >= todayStartUtc && c.CreatedAt < tomorrowStartUtc)
- .SumAsync(c => (decimal?)c.Amount.Value, ct) ?? 0m;
- var remaining = config.DailyTokenCap - (int)grantedToday;
- if (remaining <= 0)
- {
- return;
- }
- amount = Math.Min(amount, remaining);
- }
- var walletEntity = await db.Wallet
- .Include(c => c.Balances)
- .FirstOrDefaultAsync(c => c.MemberID == memberID, ct);
- if (walletEntity is not null)
- {
- walletEntity.CreditReward(Money.KRW(amount), reason, refID);
- }
- }
- private static async Task<Domain.Entities.Common.ActivityTokenConfig?> LoadConfigAsync(IAppDbContext db, ICacheService cache, CancellationToken ct)
- {
- var cached = await cache.GetAsync<Response>(CacheKeys.Config, ct);
- if (cached is not null)
- {
- return new Domain.Entities.Common.ActivityTokenConfig
- {
- PostToken = cached.ActivityToken.PostToken,
- CommentToken = cached.ActivityToken.CommentToken,
- DailyTokenCap = cached.ActivityToken.DailyTokenCap
- };
- }
- var entity = await db.Config.AsNoTracking().OrderByDescending(c => c.ID).FirstOrDefaultAsync(ct);
- return entity?.ActivityToken;
- }
- private static TimeZoneInfo ResolveKst()
- {
- if (TimeZoneInfo.TryFindSystemTimeZoneById("Asia/Seoul", out var tz))
- {
- return tz;
- }
- if (TimeZoneInfo.TryFindSystemTimeZoneById("Korea Standard Time", out tz))
- {
- return tz;
- }
- return TimeZoneInfo.CreateCustomTimeZone("KST", TimeSpan.FromHours(9), "KST", "KST");
- }
- }
|