refactor(service): 优化聊天服务代码注释与结构

添加详细中文注释,明确用户配额校验、VIP权限判断及流式响应处理逻辑,提升可维护性。
This commit is contained in:
2025-12-17 16:05:14 +08:00
parent 323baa876f
commit 27a8911b7f

View File

@@ -112,15 +112,28 @@ public class ChatServiceImpl implements ChatService {
} }
// ============ 3. 校验用户免费次数和VIP ============ // ============ 3. 校验用户免费次数和VIP ============
// ============ 获取用户ID ============
Long userId = StpUtil.getLoginIdAsLong(); Long userId = StpUtil.getLoginIdAsLong();
// ============ 查询用户配额信息 ============
KeyboardUserQuotaTotal quota = quotaTotalService.getById(userId); KeyboardUserQuotaTotal quota = quotaTotalService.getById(userId);
// 判断是否有剩余免费次数
boolean hasFreeQuota = quota != null && quota.getUsedQuota() < quota.getTotalQuota(); boolean hasFreeQuota = quota != null && quota.getUsedQuota() < quota.getTotalQuota();
// 使用原子引用记录是否使用了免费次数(用于后续扣减)
AtomicReference<Boolean> usedFreeQuota = new AtomicReference<>(hasFreeQuota); AtomicReference<Boolean> usedFreeQuota = new AtomicReference<>(hasFreeQuota);
// ============ 如果没有免费次数校验VIP权限 ============
if (!hasFreeQuota) { if (!hasFreeQuota) {
// 查询用户信息
KeyboardUser user = userService.getById(userId); KeyboardUser user = userService.getById(userId);
// 判断是否为有效VIP
// 1. 用户存在
// 2. VIP标识为true
// 3. VIP到期时间为空永久VIP或未过期
boolean isValidVip = user != null && user.getIsVip() != null && user.getIsVip() boolean isValidVip = user != null && user.getIsVip() != null && user.getIsVip()
&& (user.getVipExpiry() == null || user.getVipExpiry().after(new Date())); && (user.getVipExpiry() == null || user.getVipExpiry().after(new Date()));
// 如果既无免费次数又非VIP则抛出异常
if (!isValidVip) { if (!isValidVip) {
log.error("用户无免费次数且非VIP用户ID: {}", userId); log.error("用户无免费次数且非VIP用户ID: {}", userId);
throw new BusinessException(ErrorCode.NO_QUOTA_AND_NOT_VIP); throw new BusinessException(ErrorCode.NO_QUOTA_AND_NOT_VIP);