feat(认证/通知): 单设备登录互踢 + 站内通知铃铛系统
- 单设备登录:登录成功即 last-login-wins 绑定 users.machine;非超管旧 token 在下一次受保护请求抛 4011 下线,超管豁免;仅认 token 内签名 deviceId,不用请求头。 前端两端接入踢下线跳转(?kicked=1 提示),V118 清空历史 machine - 站内通知:新增 notification 模块(任务失败扫描 / 密钥欠费 / 下游服务探测三类来源), 前后台铃铛组件 + 轮询;后台列表按主管数据范围(UserDataScopeSupport)过滤;V116 建表 均已于 2026-09-13 部署上线,此次补提交源码(此前仅存在于已部署 JAR/构建产物中)
This commit is contained in:
+74
@@ -0,0 +1,74 @@
|
||||
package com.nanri.aiimage.modules.notification.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.modules.admin.support.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationPageVo;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationSummaryVo;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationService;
|
||||
import com.nanri.aiimage.modules.permission.model.entity.AdminUserEntity;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 后台站内通知(铃铛):超管与管理员共用,按登录管理员维度读写 audience=admin 的通知;
|
||||
* 可见范围(全量 or 分组内成员)在通知生成时已按数据权限过滤。
|
||||
*/
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/admin/notifications")
|
||||
@Tag(name = "站内通知(后台)", description = "管理端铃铛未读数、通知列表与已读标记。")
|
||||
public class AdminNotificationController {
|
||||
|
||||
private final NotificationService notificationService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
|
||||
@GetMapping("/summary")
|
||||
@Operation(summary = "未读数与最新通知 id")
|
||||
public ApiResponse<NotificationSummaryVo> summary(HttpServletRequest request) {
|
||||
Long userId = currentAdminId(request);
|
||||
return ApiResponse.success(notificationService.summary(userId, NotificationService.AUDIENCE_ADMIN));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "通知分页列表")
|
||||
public ApiResponse<NotificationPageVo> page(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(defaultValue = "20") Long pageSize,
|
||||
@Parameter(description = "只看未读") @RequestParam(required = false, defaultValue = "false") Boolean onlyUnread) {
|
||||
Long userId = currentAdminId(request);
|
||||
return ApiResponse.success(notificationService.page(
|
||||
userId, NotificationService.AUDIENCE_ADMIN, page, pageSize, Boolean.TRUE.equals(onlyUnread)));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/read")
|
||||
@Operation(summary = "标记单条已读")
|
||||
public ApiResponse<Boolean> markRead(HttpServletRequest request,
|
||||
@Parameter(description = "通知ID", required = true) @PathVariable Long id) {
|
||||
Long userId = currentAdminId(request);
|
||||
return ApiResponse.success("已标记已读",
|
||||
notificationService.markRead(userId, NotificationService.AUDIENCE_ADMIN, id));
|
||||
}
|
||||
|
||||
@PostMapping("/read-all")
|
||||
@Operation(summary = "全部标记已读")
|
||||
public ApiResponse<Integer> markAllRead(HttpServletRequest request) {
|
||||
Long userId = currentAdminId(request);
|
||||
int updated = notificationService.markAllRead(userId, NotificationService.AUDIENCE_ADMIN);
|
||||
return ApiResponse.success("已全部标记已读", updated);
|
||||
}
|
||||
|
||||
private Long currentAdminId(HttpServletRequest request) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdmin(request);
|
||||
return operator.getId();
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.nanri.aiimage.modules.notification.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.modules.admin.support.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationPageVo;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationSummaryVo;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationService;
|
||||
import com.nanri.aiimage.modules.permission.model.entity.AdminUserEntity;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 桌面端站内通知(铃铛):当前登录用户维度,用户身份一律从 JWT 解析;
|
||||
* 只读写 audience=user 的通知,不感知后台管理员通知。
|
||||
*/
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/notifications")
|
||||
@Tag(name = "站内通知(桌面端)", description = "铃铛未读数、通知列表与已读标记。")
|
||||
public class NotificationController {
|
||||
|
||||
private final NotificationService notificationService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
|
||||
@GetMapping("/summary")
|
||||
@Operation(summary = "未读数与最新通知 id", description = "桌面端铃铛轮询用;latestId 增大表示有新通知。")
|
||||
public ApiResponse<NotificationSummaryVo> summary(HttpServletRequest request) {
|
||||
Long userId = currentUserId(request);
|
||||
return ApiResponse.success(notificationService.summary(userId, NotificationService.AUDIENCE_USER));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "通知分页列表", description = "onlyUnread=true 时只返回未读;附带未读总数。")
|
||||
public ApiResponse<NotificationPageVo> page(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(defaultValue = "20") Long pageSize,
|
||||
@Parameter(description = "只看未读") @RequestParam(required = false, defaultValue = "false") Boolean onlyUnread) {
|
||||
Long userId = currentUserId(request);
|
||||
return ApiResponse.success(notificationService.page(
|
||||
userId, NotificationService.AUDIENCE_USER, page, pageSize, Boolean.TRUE.equals(onlyUnread)));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/read")
|
||||
@Operation(summary = "标记单条已读")
|
||||
public ApiResponse<Boolean> markRead(HttpServletRequest request,
|
||||
@Parameter(description = "通知ID", required = true) @PathVariable Long id) {
|
||||
Long userId = currentUserId(request);
|
||||
return ApiResponse.success("已标记已读",
|
||||
notificationService.markRead(userId, NotificationService.AUDIENCE_USER, id));
|
||||
}
|
||||
|
||||
@PostMapping("/read-all")
|
||||
@Operation(summary = "全部标记已读")
|
||||
public ApiResponse<Integer> markAllRead(HttpServletRequest request) {
|
||||
Long userId = currentUserId(request);
|
||||
int updated = notificationService.markAllRead(userId, NotificationService.AUDIENCE_USER);
|
||||
return ApiResponse.success("已全部标记已读", updated);
|
||||
}
|
||||
|
||||
private Long currentUserId(HttpServletRequest request) {
|
||||
AdminUserEntity me = adminAuthSupport.requireUser(request);
|
||||
return me.getId();
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.nanri.aiimage.modules.notification.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.nanri.aiimage.modules.notification.model.entity.UserNotificationEntity;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface UserNotificationMapper extends BaseMapper<UserNotificationEntity> {
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.nanri.aiimage.modules.notification.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("biz_user_notification")
|
||||
public class UserNotificationEntity {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
private Long userId;
|
||||
private String audience;
|
||||
private String scene;
|
||||
private String level;
|
||||
private String title;
|
||||
private String content;
|
||||
private String dedupeKey;
|
||||
private LocalDateTime readAt;
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.nanri.aiimage.modules.notification.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 单条通知(桌面端与后台共用结构)。 */
|
||||
@Data
|
||||
public class NotificationItemVo {
|
||||
|
||||
private Long id;
|
||||
/** 场景:secret_balance/secret_invalid/task_failed/service_down/system */
|
||||
private String scene;
|
||||
/** 级别:info/warning/error */
|
||||
private String level;
|
||||
private String title;
|
||||
private String content;
|
||||
/** 是否已读(前端展示用,等价于 readAt 非空) */
|
||||
private Boolean read;
|
||||
private LocalDateTime readAt;
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.nanri.aiimage.modules.notification.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 通知分页结果(含未读总数,供铃铛徽标刷新)。 */
|
||||
@Data
|
||||
public class NotificationPageVo {
|
||||
|
||||
private List<NotificationItemVo> items;
|
||||
private Long total;
|
||||
private Long page;
|
||||
private Long pageSize;
|
||||
private Long unreadCount;
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.nanri.aiimage.modules.notification.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/** 通知摘要:未读数 + 最新通知 id(前端轮询用,发现 latestId 增大即弹提醒)。 */
|
||||
@Data
|
||||
public class NotificationSummaryVo {
|
||||
|
||||
private Long unreadCount;
|
||||
private Long latestId;
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package com.nanri.aiimage.modules.notification.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.modules.admin.support.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.permission.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.modules.permission.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.modules.permission.support.UserDataScopeSupport;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 通知分发:按受众把通知落到具体接收者。
|
||||
* - 桌面端用户:直接推送该用户(audience=user);
|
||||
* - 后台管理员:全部超管 + 管理员,subjectUserId 非空时按数据权限过滤
|
||||
* (超管全量;管理员仅看自己管辖分组内用户的事件,与后台密钥管理页一致)。
|
||||
* 批量场景(任务失败扫描)先用 {@link #prepareAdminAudience()} 解析一次受众,循环内复用避免重复查库。
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class NotificationDispatchService {
|
||||
|
||||
private static final int ADMIN_LIMIT = 500;
|
||||
|
||||
private final NotificationService notificationService;
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final UserDataScopeSupport userDataScopeSupport;
|
||||
|
||||
/** 推给某个桌面端用户。 */
|
||||
public boolean pushToUser(Long userId, String scene, String level, String title, String content, String dedupeKey) {
|
||||
return notificationService.pushOrRefresh(userId, NotificationService.AUDIENCE_USER, scene, level, title, content, dedupeKey);
|
||||
}
|
||||
|
||||
/** 单次推送管理员(内部解析一次受众;扫描 job 批量场景请用 prepareAdminAudience 复用)。 */
|
||||
public int pushToAdmins(String scene, String level, String title, String content,
|
||||
String dedupeKeyBase, Long subjectUserId) {
|
||||
return pushToAdmins(prepareAdminAudience(), scene, level, title, content, dedupeKeyBase, subjectUserId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 推送管理员(复用已解析受众)。
|
||||
*
|
||||
* @param subjectUserId 事件主体用户;非空时按数据权限过滤,null 表示全局事件(如服务异常)所有管理员可见
|
||||
* @return 实际落库条数
|
||||
*/
|
||||
public int pushToAdmins(AdminAudience audience, String scene, String level, String title, String content,
|
||||
String dedupeKeyBase, Long subjectUserId) {
|
||||
int pushed = 0;
|
||||
int filtered = 0;
|
||||
for (AdminUserEntity admin : audience.admins()) {
|
||||
if (!audience.canReceive(admin.getId(), subjectUserId)) {
|
||||
filtered++;
|
||||
continue;
|
||||
}
|
||||
String key = dedupeKeyBase + ":" + admin.getId();
|
||||
if (notificationService.pushOrRefresh(admin.getId(), NotificationService.AUDIENCE_ADMIN,
|
||||
scene, level, title, content, key)) {
|
||||
pushed++;
|
||||
}
|
||||
}
|
||||
log.info("[notification] 管理员分发完成 scene={} subjectUserId={} 受众={} 权限过滤={} 落库={}",
|
||||
scene, subjectUserId, audience.admins().size(), filtered, pushed);
|
||||
return pushed;
|
||||
}
|
||||
|
||||
/** 解析管理员受众:全部超管 + 管理员(非管理员角色一律排除),并预取各管理员可见用户集。 */
|
||||
public AdminAudience prepareAdminAudience() {
|
||||
List<AdminUserEntity> candidates = adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>()
|
||||
.eq(AdminUserEntity::getIsAdmin, 1)
|
||||
.last("limit " + ADMIN_LIMIT));
|
||||
List<AdminUserEntity> admins = new ArrayList<>();
|
||||
Set<Long> superAdminIds = new HashSet<>();
|
||||
Map<Long, Set<Long>> visibleByAdmin = new HashMap<>();
|
||||
for (AdminUserEntity candidate : candidates) {
|
||||
String role = adminAuthSupport.currentRole(candidate);
|
||||
if (role == null) {
|
||||
continue;
|
||||
}
|
||||
admins.add(candidate);
|
||||
if ("super_admin".equals(role)) {
|
||||
superAdminIds.add(candidate.getId());
|
||||
} else {
|
||||
visibleByAdmin.put(candidate.getId(), new HashSet<>(userDataScopeSupport.resolveVisibleUserIds(candidate.getId())));
|
||||
}
|
||||
}
|
||||
log.info("[notification] 管理员受众解析完成 管理员数={} 超管={} 需按分组过滤={}",
|
||||
admins.size(), superAdminIds.size(), visibleByAdmin.size());
|
||||
return new AdminAudience(admins, superAdminIds, visibleByAdmin);
|
||||
}
|
||||
|
||||
/** 用户名(通知文案用):查不到时回退「用户#id」。 */
|
||||
public String displayNameOf(Long userId) {
|
||||
if (userId == null) {
|
||||
return "未知用户";
|
||||
}
|
||||
AdminUserEntity user = adminUserMapper.selectById(userId);
|
||||
String username = user == null ? null : user.getUsername();
|
||||
if (username == null || username.isBlank()) {
|
||||
return "用户#" + userId;
|
||||
}
|
||||
return username;
|
||||
}
|
||||
|
||||
/** 一次解析好的管理员受众(admins + 超管集合 + 各管理员可见用户集),可跨多条事件复用。 */
|
||||
public record AdminAudience(List<AdminUserEntity> admins,
|
||||
Set<Long> superAdminIds,
|
||||
Map<Long, Set<Long>> visibleByAdmin) {
|
||||
|
||||
/** 该管理员是否可接收主体用户为 subjectUserId 的事件;subjectUserId=null 为全局事件。 */
|
||||
public boolean canReceive(Long adminId, Long subjectUserId) {
|
||||
if (subjectUserId == null || superAdminIds.contains(adminId)) {
|
||||
return true;
|
||||
}
|
||||
Set<Long> visible = visibleByAdmin.get(adminId);
|
||||
return visible != null && visible.contains(subjectUserId);
|
||||
}
|
||||
}
|
||||
}
|
||||
+374
@@ -0,0 +1,374 @@
|
||||
package com.nanri.aiimage.modules.notification.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.config.HttpClientPool;
|
||||
import com.nanri.aiimage.config.NotificationProperties;
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
import com.nanri.aiimage.modules.brand.mapper.BrandCrawlTaskMapper;
|
||||
import com.nanri.aiimage.modules.brand.model.entity.BrandCrawlTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.usersecret.client.JikipProxyClient;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBalanceVo;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestClient;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 站内通知扫描:任务失败聚合提醒 + 下游服务健康探测。
|
||||
*
|
||||
* <p>任务失败:回看窗口内进入失败终态的任务(biz_file_task / brand_crawl_tasks),
|
||||
* 按「用户 × 模块 × 小时」聚合,同一小时桶内增量刷新同一条通知(不刷屏);
|
||||
* 用户侧推给任务创建者,管理员侧按数据权限推给管辖该用户的管理员。
|
||||
*
|
||||
* <p>服务探测:品牌检测服务(15126) / 跟价任务 API(18960) / jikip 代理接口,
|
||||
* 失败立即重试一次(过滤瞬抖),两次都失败才告警;同服务每小时最多一条。
|
||||
*
|
||||
* <p>双实例经 Redis 分布式锁互斥;所有分支留中文日志便于线上排查。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class NotificationScanScheduler {
|
||||
|
||||
private static final String LOCK_NAME = "notification-scan";
|
||||
|
||||
private static final String STATUS_FAILED = "FAILED";
|
||||
private static final String BRAND_STATUS_FAILED = "failed";
|
||||
private static final String BRAND_MODULE_TYPE = "BRAND";
|
||||
|
||||
private static final int MAX_TASK_NO_PREVIEW = 5;
|
||||
private static final int REASON_MAX_LENGTH = 120;
|
||||
private static final int PROBE_READ_TIMEOUT_MILLIS = 8_000;
|
||||
|
||||
private static final DateTimeFormatter HOUR_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHH");
|
||||
|
||||
/** 任务模块类型 → 中文名(与 TaskHeartbeatService 的模块常量对齐)。 */
|
||||
private static final Map<String, String> MODULE_LABELS = Map.ofEntries(
|
||||
Map.entry("APPEARANCE_PATENT", "外观专利检测"),
|
||||
Map.entry("SIMILAR_ASIN", "货源查询"),
|
||||
Map.entry("PATROL_DELETE", "巡店删除"),
|
||||
Map.entry("PRICE_TRACK", "跟价"),
|
||||
Map.entry("PRODUCT_RISK_RESOLVE", "商品风险解决"),
|
||||
Map.entry("QUERY_ASIN", "查询ASIN"),
|
||||
Map.entry("WITHDRAW", "取款"),
|
||||
Map.entry("SHOP_DATA_CRAWL", "店铺数据抓取"),
|
||||
Map.entry("SHOP_MATCH", "定时匹配"),
|
||||
Map.entry("BRAND", "品牌检测"),
|
||||
Map.entry("COLLECT_DATA", "采集数据"),
|
||||
Map.entry("DELETE_BRAND", "删除ASIN"),
|
||||
Map.entry("SPLIT", "数据拆分"),
|
||||
Map.entry("CONVERT", "格式转换"),
|
||||
Map.entry("PUBLISH", "上架"),
|
||||
Map.entry("DEDUPE", "数据去重"));
|
||||
|
||||
private final FileTaskMapper fileTaskMapper;
|
||||
private final BrandCrawlTaskMapper brandCrawlTaskMapper;
|
||||
private final NotificationService notificationService;
|
||||
private final NotificationDispatchService notificationDispatchService;
|
||||
private final DistributedJobLockService distributedJobLockService;
|
||||
private final NotificationProperties properties;
|
||||
private final JikipProxyClient jikipProxyClient;
|
||||
|
||||
/** 上次清理日期(每天最多清理一次;双节点由分布式锁保证只有一个实例执行)。 */
|
||||
private volatile LocalDate lastCleanupDate;
|
||||
|
||||
@Scheduled(fixedDelayString = "${aiimage.notification.scan-interval-ms:300000}",
|
||||
initialDelayString = "${aiimage.notification.scan-initial-delay-ms:120000}")
|
||||
public void scan() {
|
||||
if (!properties.isScanEnabled()) {
|
||||
log.info("[notification-scan] 扫描已关闭(scan-enabled=false),跳过本轮");
|
||||
return;
|
||||
}
|
||||
var lock = distributedJobLockService.tryLock(LOCK_NAME, Duration.ofMinutes(5));
|
||||
if (lock == null) {
|
||||
log.info("[notification-scan] 另一实例持有扫描锁,跳过本轮");
|
||||
return;
|
||||
}
|
||||
try (lock) {
|
||||
if (properties.isTaskScanEnabled()) {
|
||||
scanFailedTasks();
|
||||
}
|
||||
if (properties.isServiceProbeEnabled()) {
|
||||
probeServices();
|
||||
}
|
||||
cleanupExpiredIfNeeded();
|
||||
} catch (Exception ex) {
|
||||
log.warn("[notification-scan] 扫描异常终止 err={}", ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/** 任务失败聚合扫描:窗口内失败终态任务按「用户 × 模块 × 小时」聚合成一条通知。 */
|
||||
void scanFailedTasks() {
|
||||
LocalDateTime cutoff = LocalDateTime.now()
|
||||
.minusMinutes(Math.max(1, properties.getTaskFailedWindowMinutes()));
|
||||
int limit = Math.max(1, properties.getTaskScanMaxRows());
|
||||
|
||||
List<FailedTask> failed = new ArrayList<>();
|
||||
List<FileTaskEntity> fileTasks = fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
|
||||
.select(FileTaskEntity::getId, FileTaskEntity::getTaskNo, FileTaskEntity::getModuleType,
|
||||
FileTaskEntity::getUserId, FileTaskEntity::getErrorMessage, FileTaskEntity::getUpdatedAt)
|
||||
.eq(FileTaskEntity::getStatus, STATUS_FAILED)
|
||||
.gt(FileTaskEntity::getUpdatedAt, cutoff)
|
||||
.orderByDesc(FileTaskEntity::getId)
|
||||
.last("limit " + limit));
|
||||
for (FileTaskEntity task : fileTasks) {
|
||||
if (task.getUserId() == null || task.getUserId() <= 0) {
|
||||
continue;
|
||||
}
|
||||
failed.add(new FailedTask(task.getId(), displayTaskNo(task.getTaskNo(), task.getId()),
|
||||
task.getModuleType(), task.getUserId(), task.getErrorMessage()));
|
||||
}
|
||||
List<BrandCrawlTaskEntity> brandTasks = brandCrawlTaskMapper.selectList(new LambdaQueryWrapper<BrandCrawlTaskEntity>()
|
||||
.select(BrandCrawlTaskEntity::getId, BrandCrawlTaskEntity::getUserId,
|
||||
BrandCrawlTaskEntity::getErrorMessage, BrandCrawlTaskEntity::getUpdatedAt)
|
||||
.eq(BrandCrawlTaskEntity::getStatus, BRAND_STATUS_FAILED)
|
||||
.gt(BrandCrawlTaskEntity::getUpdatedAt, cutoff)
|
||||
.orderByDesc(BrandCrawlTaskEntity::getId)
|
||||
.last("limit " + limit));
|
||||
for (BrandCrawlTaskEntity task : brandTasks) {
|
||||
if (task.getUserId() == null || task.getUserId() <= 0) {
|
||||
continue;
|
||||
}
|
||||
failed.add(new FailedTask(task.getId(), "#" + task.getId(),
|
||||
BRAND_MODULE_TYPE, task.getUserId(), task.getErrorMessage()));
|
||||
}
|
||||
if (failed.isEmpty()) {
|
||||
log.info("[notification-scan] 近 {} 分钟无失败任务", properties.getTaskFailedWindowMinutes());
|
||||
return;
|
||||
}
|
||||
|
||||
String hour = LocalDateTime.now().format(HOUR_FORMAT);
|
||||
Map<BucketKey, List<FailedTask>> buckets = new LinkedHashMap<>();
|
||||
for (FailedTask task : failed) {
|
||||
String moduleType = normalizeModuleType(task.moduleType());
|
||||
buckets.computeIfAbsent(new BucketKey(task.userId(), moduleType, hour), key -> new ArrayList<>())
|
||||
.add(task);
|
||||
}
|
||||
|
||||
NotificationDispatchService.AdminAudience audience = notificationDispatchService.prepareAdminAudience();
|
||||
int userPushed = 0;
|
||||
int adminPushed = 0;
|
||||
for (Map.Entry<BucketKey, List<FailedTask>> entry : buckets.entrySet()) {
|
||||
BucketKey key = entry.getKey();
|
||||
List<FailedTask> tasks = entry.getValue();
|
||||
String label = MODULE_LABELS.getOrDefault(key.moduleType(), key.moduleType());
|
||||
String preview = taskNoPreview(tasks);
|
||||
String reason = latestReason(tasks);
|
||||
|
||||
String userContent = "最近 " + properties.getTaskFailedWindowMinutes() + " 分钟内有 " + tasks.size()
|
||||
+ " 个" + label + "任务失败"
|
||||
+ (preview.isEmpty() ? "" : "(" + preview + ")")
|
||||
+ (reason.isEmpty() ? "" : ";最近失败原因:" + reason)
|
||||
+ ",详情请查看对应工具页的「历史任务」。";
|
||||
if (notificationService.pushOrRefresh(key.userId(), NotificationService.AUDIENCE_USER,
|
||||
NotificationService.SCENE_TASK_FAILED, NotificationService.LEVEL_WARNING,
|
||||
label + "任务失败", userContent, dedupeKeyOf(key))) {
|
||||
userPushed++;
|
||||
}
|
||||
|
||||
String username = notificationDispatchService.displayNameOf(key.userId());
|
||||
String adminContent = "用户 " + username + "(uid=" + key.userId() + ")有 " + tasks.size()
|
||||
+ " 个" + label + "任务失败"
|
||||
+ (preview.isEmpty() ? "" : "(" + preview + ")")
|
||||
+ (reason.isEmpty() ? "" : ";最近失败原因:" + reason);
|
||||
adminPushed += notificationDispatchService.pushToAdmins(audience,
|
||||
NotificationService.SCENE_TASK_FAILED, NotificationService.LEVEL_WARNING,
|
||||
"用户任务失败:" + username, adminContent,
|
||||
"task_failed_admin:" + key.userId() + ":" + key.moduleType() + ":" + key.hour(),
|
||||
key.userId());
|
||||
}
|
||||
log.info("[notification-scan] 任务失败扫描完成 窗口={}分钟 失败任务={} 聚合桶={} 用户通知={} 管理员通知={}",
|
||||
properties.getTaskFailedWindowMinutes(), failed.size(), buckets.size(), userPushed, adminPushed);
|
||||
}
|
||||
|
||||
/** 下游服务健康探测:品牌检测服务 / 跟价任务 API / jikip 代理接口。 */
|
||||
void probeServices() {
|
||||
if (hasText(properties.getBrandServiceUrl())) {
|
||||
reportProbe("brand-service", "品牌检测服务",
|
||||
probeHttpWithRetry(joinUrl(properties.getBrandServiceUrl(), "/api/version")));
|
||||
} else {
|
||||
log.info("[notification-scan] 品牌检测服务探测地址未配置,跳过");
|
||||
}
|
||||
if (hasText(properties.getPriceTrackApiUrl())) {
|
||||
reportProbe("price-track-api", "跟价任务 API",
|
||||
probeHttpWithRetry(joinUrl(properties.getPriceTrackApiUrl(), "/")));
|
||||
} else {
|
||||
log.info("[notification-scan] 跟价任务 API 探测地址未配置,跳过");
|
||||
}
|
||||
if (properties.isJikipProbeEnabled()) {
|
||||
reportProbe("jikip", "jikip 代理接口", probeJikip());
|
||||
}
|
||||
}
|
||||
|
||||
/** HTTP 探测:失败立即重试一次,两次都失败才算故障(过滤瞬时抖动)。 */
|
||||
private ProbeOutcome probeHttpWithRetry(String url) {
|
||||
ProbeOutcome first = probeHttpOnce(url);
|
||||
if (first.ok()) {
|
||||
return first;
|
||||
}
|
||||
log.warn("[notification-scan] 服务探测第一次失败,重试一次 url={} detail={}", url, first.detail());
|
||||
return probeHttpOnce(url);
|
||||
}
|
||||
|
||||
private ProbeOutcome probeHttpOnce(String url) {
|
||||
long startMillis = System.currentTimeMillis();
|
||||
try {
|
||||
Integer status = RestClient.builder()
|
||||
.requestFactory(HttpClientPool.requestFactory(PROBE_READ_TIMEOUT_MILLIS))
|
||||
.build()
|
||||
.get()
|
||||
.uri(url)
|
||||
.exchange((request, response) -> response.getStatusCode().value());
|
||||
long latency = System.currentTimeMillis() - startMillis;
|
||||
// 任意 HTTP < 500 视为存活(4xx 说明服务在线,仅路径/鉴权问题)
|
||||
if (status != null && status < 500) {
|
||||
return new ProbeOutcome(true, "HTTP " + status + "(" + latency + "ms)");
|
||||
}
|
||||
return new ProbeOutcome(false, "HTTP " + status + "(" + latency + "ms)");
|
||||
} catch (Exception ex) {
|
||||
long latency = System.currentTimeMillis() - startMillis;
|
||||
return new ProbeOutcome(false, rootCauseMessage(ex) + "(" + latency + "ms)");
|
||||
}
|
||||
}
|
||||
|
||||
/** jikip 探测:复用余额查询接口;未配置套餐信息时跳过(返回 null 不告警)。 */
|
||||
private ProbeOutcome probeJikip() {
|
||||
try {
|
||||
UserApiSecretBalanceVo balance = jikipProxyClient.fetchBalance();
|
||||
if (Boolean.TRUE.equals(balance.getAvailable())) {
|
||||
return new ProbeOutcome(true, "余额接口可用 surplus=" + balance.getSurplus()
|
||||
+ " balance=" + balance.getBalance());
|
||||
}
|
||||
String message = balance.getMessage() == null ? "" : balance.getMessage();
|
||||
if (message.contains("未配置")) {
|
||||
log.info("[notification-scan] jikip 探测跳过:{}", message);
|
||||
return null;
|
||||
}
|
||||
return new ProbeOutcome(false, message.isEmpty() ? "余额接口不可用" : message);
|
||||
} catch (Exception ex) {
|
||||
return new ProbeOutcome(false, rootCauseMessage(ex));
|
||||
}
|
||||
}
|
||||
|
||||
/** 探测结果上报:正常记 info;故障按小时去重推管理员通知;outcome=null 表示跳过。 */
|
||||
private void reportProbe(String serviceKey, String serviceLabel, ProbeOutcome outcome) {
|
||||
if (outcome == null) {
|
||||
return;
|
||||
}
|
||||
if (outcome.ok()) {
|
||||
log.info("[notification-scan] 服务探测正常 service={} detail={}", serviceLabel, outcome.detail());
|
||||
return;
|
||||
}
|
||||
log.warn("[notification-scan] 服务探测失败 service={} detail={}", serviceLabel, outcome.detail());
|
||||
String hour = LocalDateTime.now().format(HOUR_FORMAT);
|
||||
notificationDispatchService.pushToAdmins(NotificationService.SCENE_SERVICE_DOWN,
|
||||
NotificationService.LEVEL_ERROR,
|
||||
serviceLabel + "不可用",
|
||||
serviceLabel + "探测失败:" + outcome.detail() + "。该服务相关任务可能大面积失败,请尽快排查。",
|
||||
"service_down:" + serviceKey + ":" + hour, null);
|
||||
}
|
||||
|
||||
/** 已读通知保留期清理:每天最多一次。 */
|
||||
private void cleanupExpiredIfNeeded() {
|
||||
LocalDate today = LocalDate.now();
|
||||
if (today.equals(lastCleanupDate)) {
|
||||
return;
|
||||
}
|
||||
lastCleanupDate = today;
|
||||
LocalDateTime cutoff = LocalDateTime.now().minusDays(Math.max(1, properties.getReadRetentionDays()));
|
||||
notificationService.cleanupReadBefore(cutoff);
|
||||
}
|
||||
|
||||
private String dedupeKeyOf(BucketKey key) {
|
||||
return "task_failed:" + key.userId() + ":" + key.moduleType() + ":" + key.hour();
|
||||
}
|
||||
|
||||
private String taskNoPreview(List<FailedTask> tasks) {
|
||||
List<String> previews = new ArrayList<>(MAX_TASK_NO_PREVIEW);
|
||||
for (FailedTask task : tasks) {
|
||||
if (task.taskNo() == null || task.taskNo().isBlank()) {
|
||||
continue;
|
||||
}
|
||||
previews.add(task.taskNo());
|
||||
if (previews.size() >= MAX_TASK_NO_PREVIEW) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (previews.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
String text = String.join("、", previews);
|
||||
return tasks.size() > previews.size() ? text + " 等" : text;
|
||||
}
|
||||
|
||||
private String latestReason(List<FailedTask> tasks) {
|
||||
for (FailedTask task : tasks) {
|
||||
if (task.errorMessage() != null && !task.errorMessage().isBlank()) {
|
||||
String reason = task.errorMessage().trim().replaceAll("\\s+", " ");
|
||||
return reason.length() <= REASON_MAX_LENGTH ? reason : reason.substring(0, REASON_MAX_LENGTH) + "…";
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private String displayTaskNo(String taskNo, Long id) {
|
||||
return taskNo == null || taskNo.isBlank() ? "#" + id : taskNo;
|
||||
}
|
||||
|
||||
private String normalizeModuleType(String moduleType) {
|
||||
String normalized = moduleType == null ? "" : moduleType.trim();
|
||||
if (normalized.isEmpty()) {
|
||||
return "UNKNOWN";
|
||||
}
|
||||
// 历史小写值(legacy collectdata)统一成大写常量
|
||||
return normalized.equalsIgnoreCase("collectdata") ? "COLLECT_DATA" : normalized.toUpperCase();
|
||||
}
|
||||
|
||||
private boolean hasText(String value) {
|
||||
return value != null && !value.trim().isEmpty();
|
||||
}
|
||||
|
||||
private String joinUrl(String baseUrl, String path) {
|
||||
String base = baseUrl == null ? "" : baseUrl.trim();
|
||||
if (base.endsWith("/")) {
|
||||
base = base.substring(0, base.length() - 1);
|
||||
}
|
||||
return base + path;
|
||||
}
|
||||
|
||||
private String rootCauseMessage(Throwable throwable) {
|
||||
Throwable current = throwable;
|
||||
while (current.getCause() != null && current.getCause() != current) {
|
||||
current = current.getCause();
|
||||
}
|
||||
String message = current.getMessage();
|
||||
if (message == null || message.isBlank()) {
|
||||
return current.getClass().getSimpleName();
|
||||
}
|
||||
return current.getClass().getSimpleName() + ": " + message;
|
||||
}
|
||||
|
||||
/** 聚合桶键:用户 × 模块 × 小时。 */
|
||||
record BucketKey(Long userId, String moduleType, String hour) {
|
||||
}
|
||||
|
||||
/** 统一视图的失败任务(两类表归一)。 */
|
||||
record FailedTask(Long id, String taskNo, String moduleType, Long userId, String errorMessage) {
|
||||
}
|
||||
|
||||
/** 探测结果。 */
|
||||
record ProbeOutcome(boolean ok, String detail) {
|
||||
}
|
||||
}
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
package com.nanri.aiimage.modules.notification.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.modules.notification.mapper.UserNotificationMapper;
|
||||
import com.nanri.aiimage.modules.notification.model.entity.UserNotificationEntity;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationItemVo;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationPageVo;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationSummaryVo;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 站内通知存取:桌面端用户(audience=user)与后台管理员(audience=admin)共用一张表,
|
||||
* 按 user_id + audience 隔离;push 前按 dedupe_key 精确查重(键自带时间粒度,见各来源生成规则)。
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class NotificationService {
|
||||
|
||||
public static final String AUDIENCE_USER = "user";
|
||||
public static final String AUDIENCE_ADMIN = "admin";
|
||||
|
||||
public static final String LEVEL_INFO = "info";
|
||||
public static final String LEVEL_WARNING = "warning";
|
||||
public static final String LEVEL_ERROR = "error";
|
||||
|
||||
public static final String SCENE_SECRET_BALANCE = "secret_balance";
|
||||
public static final String SCENE_SECRET_INVALID = "secret_invalid";
|
||||
public static final String SCENE_TASK_FAILED = "task_failed";
|
||||
public static final String SCENE_SERVICE_DOWN = "service_down";
|
||||
public static final String SCENE_SYSTEM = "system";
|
||||
|
||||
private static final long MAX_PAGE_SIZE = 100L;
|
||||
private static final int TITLE_MAX_LENGTH = 128;
|
||||
private static final int CONTENT_MAX_LENGTH = 512;
|
||||
private static final int DEDUPE_KEY_MAX_LENGTH = 160;
|
||||
|
||||
private final UserNotificationMapper userNotificationMapper;
|
||||
|
||||
/**
|
||||
* 推送一条通知。dedupeKey 非空且库中已存在同键记录时跳过(返回 false),
|
||||
* 用于「同一异常在时间窗内只提醒一次」;dedupeKey 为空则不去重。
|
||||
*/
|
||||
public boolean push(Long userId, String audience, String scene, String level,
|
||||
String title, String content, String dedupeKey) {
|
||||
if (userId == null || userId <= 0) {
|
||||
log.warn("[notification] 推送被跳过:接收者无效 userId={} scene={}", userId, scene);
|
||||
return false;
|
||||
}
|
||||
String key = normalize(dedupeKey);
|
||||
if (!key.isEmpty() && existsByDedupeKey(key)) {
|
||||
log.info("[notification] 去重命中,跳过推送 userId={} audience={} scene={} dedupeKey={}",
|
||||
userId, audience, scene, key);
|
||||
return false;
|
||||
}
|
||||
UserNotificationEntity row = new UserNotificationEntity();
|
||||
row.setUserId(userId);
|
||||
row.setAudience(normalize(audience).isEmpty() ? AUDIENCE_USER : audience);
|
||||
row.setScene(normalize(scene).isEmpty() ? SCENE_SYSTEM : scene);
|
||||
row.setLevel(normalize(level).isEmpty() ? LEVEL_WARNING : level);
|
||||
row.setTitle(truncate(title, TITLE_MAX_LENGTH));
|
||||
row.setContent(truncate(content == null ? "" : content, CONTENT_MAX_LENGTH));
|
||||
row.setDedupeKey(truncate(key, DEDUPE_KEY_MAX_LENGTH));
|
||||
row.setCreatedAt(LocalDateTime.now());
|
||||
try {
|
||||
userNotificationMapper.insert(row);
|
||||
} catch (Exception ex) {
|
||||
// 通知失败不阻断业务主流程(巡检/扫描 job 的调用方也不应因此中断)
|
||||
log.warn("[notification] 推送落库失败 userId={} scene={} err={}", userId, scene, ex.getMessage(), ex);
|
||||
return false;
|
||||
}
|
||||
log.info("[notification] 已推送 id={} userId={} audience={} scene={} level={} title={}",
|
||||
row.getId(), userId, row.getAudience(), row.getScene(), row.getLevel(), row.getTitle());
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 同键推送或刷新:不存在则新建;已存在且内容有变化时更新内容并重置为未读
|
||||
* (用于小时桶聚合的增量更新:同小时内新增失败任务时刷新计数与明细)。
|
||||
*
|
||||
* @return true=新建或内容有更新(用户有新信息),false=无变化或去重未命中变化
|
||||
*/
|
||||
public boolean pushOrRefresh(Long userId, String audience, String scene, String level,
|
||||
String title, String content, String dedupeKey) {
|
||||
String key = normalize(dedupeKey);
|
||||
if (key.isEmpty()) {
|
||||
return push(userId, audience, scene, level, title, content, key);
|
||||
}
|
||||
UserNotificationEntity existing = selectByDedupeKey(key);
|
||||
if (existing == null) {
|
||||
return push(userId, audience, scene, level, title, content, key);
|
||||
}
|
||||
String nextTitle = truncate(title, TITLE_MAX_LENGTH);
|
||||
String nextContent = truncate(content == null ? "" : content, CONTENT_MAX_LENGTH);
|
||||
if (nextContent.equals(existing.getContent()) && nextTitle.equals(existing.getTitle())) {
|
||||
return false;
|
||||
}
|
||||
userNotificationMapper.update(null, new LambdaUpdateWrapper<UserNotificationEntity>()
|
||||
.eq(UserNotificationEntity::getId, existing.getId())
|
||||
.set(UserNotificationEntity::getTitle, nextTitle)
|
||||
.set(UserNotificationEntity::getContent, nextContent)
|
||||
.set(UserNotificationEntity::getLevel, normalize(level).isEmpty() ? LEVEL_WARNING : level)
|
||||
.set(UserNotificationEntity::getReadAt, null));
|
||||
log.info("[notification] 同键通知已刷新 id={} userId={} scene={} dedupeKey={}",
|
||||
existing.getId(), userId, scene, key);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 分页查询(id 倒序);onlyUnread=true 时只返回未读。 */ public NotificationPageVo page(Long userId, String audience, long page, long pageSize, boolean onlyUnread) {
|
||||
long safePage = page < 1 ? 1L : page;
|
||||
long safeSize = pageSize < 1 ? 20L : Math.min(pageSize, MAX_PAGE_SIZE);
|
||||
LambdaQueryWrapper<UserNotificationEntity> countWrapper = baseWrapper(userId, audience, onlyUnread);
|
||||
Long totalValue = userNotificationMapper.selectCount(countWrapper);
|
||||
long total = totalValue == null ? 0L : totalValue;
|
||||
|
||||
long offset = Math.max(0L, (safePage - 1) * safeSize);
|
||||
List<UserNotificationEntity> rows = total == 0 ? List.of()
|
||||
: userNotificationMapper.selectList(baseWrapper(userId, audience, onlyUnread)
|
||||
.orderByDesc(UserNotificationEntity::getId)
|
||||
.last("limit " + offset + "," + safeSize));
|
||||
|
||||
NotificationPageVo vo = new NotificationPageVo();
|
||||
List<NotificationItemVo> items = new ArrayList<>(rows.size());
|
||||
for (UserNotificationEntity row : rows) {
|
||||
items.add(toItem(row));
|
||||
}
|
||||
vo.setItems(items);
|
||||
vo.setTotal(total);
|
||||
vo.setPage(safePage);
|
||||
vo.setPageSize(safeSize);
|
||||
vo.setUnreadCount(unreadCount(userId, audience));
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 摘要:未读数 + 最新通知 id(前端轮询判断是否有新通知)。 */
|
||||
public NotificationSummaryVo summary(Long userId, String audience) {
|
||||
NotificationSummaryVo vo = new NotificationSummaryVo();
|
||||
vo.setUnreadCount(unreadCount(userId, audience));
|
||||
UserNotificationEntity latest = userNotificationMapper.selectOne(
|
||||
new LambdaQueryWrapper<UserNotificationEntity>()
|
||||
.select(UserNotificationEntity::getId)
|
||||
.eq(UserNotificationEntity::getUserId, userId)
|
||||
.eq(UserNotificationEntity::getAudience, audience)
|
||||
.orderByDesc(UserNotificationEntity::getId)
|
||||
.last("limit 1"));
|
||||
vo.setLatestId(latest == null ? 0L : latest.getId());
|
||||
return vo;
|
||||
}
|
||||
|
||||
public long unreadCount(Long userId, String audience) {
|
||||
Long count = userNotificationMapper.selectCount(new LambdaQueryWrapper<UserNotificationEntity>()
|
||||
.eq(UserNotificationEntity::getUserId, userId)
|
||||
.eq(UserNotificationEntity::getAudience, audience)
|
||||
.isNull(UserNotificationEntity::getReadAt));
|
||||
return count == null ? 0L : count;
|
||||
}
|
||||
|
||||
/** 标记单条已读(仅限本人、本人接收端)。 */
|
||||
public boolean markRead(Long userId, String audience, Long id) {
|
||||
if (id == null || id <= 0) {
|
||||
log.warn("[notification] 标记已读参数无效 userId={} id={}", userId, id);
|
||||
return false;
|
||||
}
|
||||
int updated = userNotificationMapper.update(null, new LambdaUpdateWrapper<UserNotificationEntity>()
|
||||
.eq(UserNotificationEntity::getId, id)
|
||||
.eq(UserNotificationEntity::getUserId, userId)
|
||||
.eq(UserNotificationEntity::getAudience, audience)
|
||||
.isNull(UserNotificationEntity::getReadAt)
|
||||
.set(UserNotificationEntity::getReadAt, LocalDateTime.now()));
|
||||
if (updated == 0) {
|
||||
log.info("[notification] 标记已读未生效(不存在/非本人/已读) userId={} audience={} id={}",
|
||||
userId, audience, id);
|
||||
return false;
|
||||
}
|
||||
log.info("[notification] 已标记已读 userId={} audience={} id={}", userId, audience, id);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 全部标记已读,返回受影响条数。 */
|
||||
public int markAllRead(Long userId, String audience) {
|
||||
int updated = userNotificationMapper.update(null, new LambdaUpdateWrapper<UserNotificationEntity>()
|
||||
.eq(UserNotificationEntity::getUserId, userId)
|
||||
.eq(UserNotificationEntity::getAudience, audience)
|
||||
.isNull(UserNotificationEntity::getReadAt)
|
||||
.set(UserNotificationEntity::getReadAt, LocalDateTime.now()));
|
||||
if (updated > 0) {
|
||||
log.info("[notification] 全部已读 userId={} audience={} 更新={} 条", userId, audience, updated);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
/** 清理指定时间之前已读的通知(保留期由调用方决定)。 */
|
||||
public int cleanupReadBefore(LocalDateTime cutoff) {
|
||||
int deleted = userNotificationMapper.delete(new LambdaQueryWrapper<UserNotificationEntity>()
|
||||
.isNotNull(UserNotificationEntity::getReadAt)
|
||||
.lt(UserNotificationEntity::getCreatedAt, cutoff));
|
||||
if (deleted > 0) {
|
||||
log.info("[notification] 清理历史已读通知 cutoff={} 删除={} 条", cutoff, deleted);
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
private LambdaQueryWrapper<UserNotificationEntity> baseWrapper(Long userId, String audience, boolean onlyUnread) {
|
||||
LambdaQueryWrapper<UserNotificationEntity> wrapper = new LambdaQueryWrapper<UserNotificationEntity>()
|
||||
.eq(UserNotificationEntity::getUserId, userId)
|
||||
.eq(UserNotificationEntity::getAudience, audience);
|
||||
if (onlyUnread) {
|
||||
wrapper.isNull(UserNotificationEntity::getReadAt);
|
||||
}
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
private boolean existsByDedupeKey(String dedupeKey) {
|
||||
return selectByDedupeKey(dedupeKey) != null;
|
||||
}
|
||||
|
||||
private UserNotificationEntity selectByDedupeKey(String dedupeKey) {
|
||||
return userNotificationMapper.selectOne(new LambdaQueryWrapper<UserNotificationEntity>()
|
||||
.eq(UserNotificationEntity::getDedupeKey, dedupeKey)
|
||||
.orderByAsc(UserNotificationEntity::getId)
|
||||
.last("limit 1"));
|
||||
}
|
||||
|
||||
private NotificationItemVo toItem(UserNotificationEntity row) {
|
||||
NotificationItemVo vo = new NotificationItemVo();
|
||||
vo.setId(row.getId());
|
||||
vo.setScene(row.getScene());
|
||||
vo.setLevel(row.getLevel());
|
||||
vo.setTitle(row.getTitle());
|
||||
vo.setContent(row.getContent());
|
||||
vo.setRead(row.getReadAt() != null);
|
||||
vo.setReadAt(row.getReadAt());
|
||||
vo.setCreatedAt(row.getCreatedAt());
|
||||
return vo;
|
||||
}
|
||||
|
||||
private String normalize(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
|
||||
private String truncate(String value, int maxLength) {
|
||||
String normalized = value == null ? "" : value.trim();
|
||||
return normalized.length() <= maxLength ? normalized : normalized.substring(0, maxLength);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user