Browse Source

feat(task): 晚间提醒改走wechat webhook分发(in_app兜底)

Xiaogang Liao 3 hours ago
parent
commit
6bd9b1fa6c

+ 52 - 5
cfc-backend/src/main/java/com/etotem/cfc/task/TaskDailyReminderScheduledTask.java

@@ -94,6 +94,14 @@ public class TaskDailyReminderScheduledTask {
     @Resource
     @Resource
     private TaskReminderConfigService taskReminderConfigService;
     private TaskReminderConfigService taskReminderConfigService;
 
 
+    /** 晚间鼓励文案昵称查询(失败回退"您",不阻塞发送)。 */
+    @Resource
+    private com.etotem.cfc.mapper.UserMapper userMapper;
+
+    /** 通知通道列表(晚间鼓励经 wechat webhook 发送,in_app 兜底)。 */
+    @Resource
+    private java.util.List<com.etotem.cfc.service.notification.NotificationChannel> notificationChannels;
+
     /** 早提醒:07:30 固定 cron(设计契约 §3.4 拍板)。 */
     /** 早提醒:07:30 固定 cron(设计契约 §3.4 拍板)。 */
     @Scheduled(cron = "0 30 7 * * ?")
     @Scheduled(cron = "0 30 7 * * ?")
     public void sendMorningReminder() {
     public void sendMorningReminder() {
@@ -171,17 +179,56 @@ public class TaskDailyReminderScheduledTask {
                 if (alreadySentToday(userId, TYPE_EVENING, dayStart)) {
                 if (alreadySentToday(userId, TYPE_EVENING, dayStart)) {
                     continue;
                     continue;
                 }
                 }
-                String content = buildEveningContent(userTasks, dayStart);
-                notificationDispatchService.sendByTemplate(TYPE_EVENING, userId,
-                        new HashMap<String, Object>(), REF_TYPE, userTasks.get(0).getId(),
-                        "今日任务总结", content);
-                log.info("日提醒-晚:已发送 userId={}, 任务数={}", userId, userTasks.size());
+                String nickname = resolveNickname(userId);
+                String content = buildEveningEncouragement(userTasks, nickname);
+                com.etotem.cfc.dto.NotificationMessage msg = new com.etotem.cfc.dto.NotificationMessage(
+                        userId, TYPE_EVENING, "今日任务总结", content, REF_TYPE,
+                        userTasks.get(0).getId(), "in_app,wechat");
+                dispatchEvening(msg);
+                log.info("日提醒-晚:已发送(含微信webhook) userId={}, 任务数={}, 昵称={}",
+                        userId, userTasks.size(), nickname);
             }
             }
         } catch (Exception e) {
         } catch (Exception e) {
             log.warn("日提醒-晚执行异常: {}", e.getMessage());
             log.warn("日提醒-晚执行异常: {}", e.getMessage());
         }
         }
     }
     }
 
 
+    /** 查用户昵称,null/空/异常 → 回退"您"(不阻塞发送)。 */
+    private String resolveNickname(Long userId) {
+        if (userId == null) return "您";
+        try {
+            if (userMapper != null) {
+                com.etotem.cfc.entity.User u = userMapper.selectById(userId);
+                if (u != null && u.getNickname() != null && !u.getNickname().trim().isEmpty()) {
+                    return u.getNickname();
+                }
+            }
+        } catch (Exception e) {
+            log.warn("日提醒-晚:昵称查询失败 userId={}, error={}", userId, e.getMessage());
+        }
+        return "您";
+    }
+
+    /** 按 channels 分发晚间提醒:in_app + wechat,通道未启用/异常不阻断(仿 TaskCheckinWebhookReminderTask)。 */
+    private void dispatchEvening(com.etotem.cfc.dto.NotificationMessage msg) {
+        if (notificationChannels == null) return;
+        for (String target : msg.getChannels().split(",")) {
+            String c = target.trim();
+            if (c.isEmpty()) continue;
+            for (com.etotem.cfc.service.notification.NotificationChannel channel : notificationChannels) {
+                if (!c.equals(channel.getChannelType())) continue;
+                if (!channel.isEnabled()) continue;
+                try {
+                    channel.send(msg);
+                } catch (Exception e) {
+                    log.warn("日提醒-晚:通道发送失败 channel={}, userId={}, error={}",
+                            c, msg.getUserId(), e.getMessage());
+                }
+                break;
+            }
+        }
+    }
+
     /**
     /**
      * 四档关怀鼓励文案(2026-11-29 增强):按今日到期任务完成率分为
      * 四档关怀鼓励文案(2026-11-29 增强):按今日到期任务完成率分为
      * 100% / ≥80%<100% / 1~79% / 0% 四档,语气从表扬到关怀不指责。
      * 100% / ≥80%<100% / 1~79% / 0% 四档,语气从表扬到关怀不指责。

+ 64 - 16
cfc-backend/src/test/java/com/etotem/cfc/unit/TaskReminderDailyScheduledTaskContractTest.java

@@ -225,17 +225,27 @@ class TaskReminderDailyScheduledTaskContractTest {
     // ==================== 晚总结行为(§四 验收 3) ====================
     // ==================== 晚总结行为(§四 验收 3) ====================
 
 
     @Test
     @Test
-    @DisplayName("晚总结-1:今日到期任务按已完成/未完成分组,未完成含催补打卡文案")
+    @DisplayName("晚总结-1:今日到期任务按完成率发四档鼓励(2026-11-29),经wechat分发")
+    @SuppressWarnings("unchecked")
     void eveningSummary_todayDue_groupedCompletedAndUncompleted() throws Exception {
     void eveningSummary_todayDue_groupedCompletedAndUncompleted() throws Exception {
         Object host = contractHost();
         Object host = contractHost();
         TaskMapper taskMapper = mock(TaskMapper.class);
         TaskMapper taskMapper = mock(TaskMapper.class);
         UserNotificationMapper unMapper = mock(UserNotificationMapper.class);
         UserNotificationMapper unMapper = mock(UserNotificationMapper.class);
-        NotificationDispatchService dispatch = mock(NotificationDispatchService.class);
         inject(host, "taskMapper", taskMapper);
         inject(host, "taskMapper", taskMapper);
         inject(host, "userNotificationMapper", unMapper);
         inject(host, "userNotificationMapper", unMapper);
-        inject(host, "notificationDispatchService", dispatch);
 
 
-        // 今日到期:1 已完成(completedAt 今日)+ 1 未完成(pending)
+        com.etotem.cfc.mapper.UserMapper userMapper = mock(com.etotem.cfc.mapper.UserMapper.class);
+        when(userMapper.selectById(anyLong())).thenReturn(null); // 昵称回退"您"
+        inject(host, "userMapper", userMapper);
+
+        com.etotem.cfc.service.notification.NotificationChannel wechat =
+                mock(com.etotem.cfc.service.notification.NotificationChannel.class);
+        when(wechat.getChannelType()).thenReturn("wechat");
+        when(wechat.isEnabled()).thenReturn(true);
+        inject(host, "notificationChannels",
+                new ArrayList<>(java.util.Collections.singletonList(wechat)));
+
+        // 今日到期:1 已完成(completedAt 今日)+ 1 未完成(pending)→ 50% 部分完成档
         Task done = task(2L, "已完成的今日任务", todayDeadline(9, 0), "completed");
         Task done = task(2L, "已完成的今日任务", todayDeadline(9, 0), "completed");
         done.setCompletedAt(new Date());
         done.setCompletedAt(new Date());
         Task undone = task(3L, "未完成的今日任务", todayDeadline(18, 0), "pending");
         Task undone = task(3L, "未完成的今日任务", todayDeadline(18, 0), "pending");
@@ -245,19 +255,13 @@ class TaskReminderDailyScheduledTaskContractTest {
 
 
         call(host, "sendEveningSummary");
         call(host, "sendEveningSummary");
 
 
-        ArgumentCaptor<String> typeCaptor = ArgumentCaptor.forClass(String.class);
-        ArgumentCaptor<String> contentCaptor = ArgumentCaptor.forClass(String.class);
-        verify(dispatch, atLeastOnce()).sendByTemplate(typeCaptor.capture(), anyLong(), any(),
-                any(), anyLong(), any(), contentCaptor.capture());
-        assertEquals("task_daily_evening", typeCaptor.getValue(),
-                "晚总结通知 type 应为 task_daily_evening(§3.4)");
-        String content = contentCaptor.getValue();
-        // 设计 §3.4 晚总结文案:「今日总结:完成 X/N。✅ 已完成:…;【未完成】⚠ 标题…别忘了打卡哦~」
+        ArgumentCaptor<com.etotem.cfc.dto.NotificationMessage> msgCaptor =
+                ArgumentCaptor.forClass(com.etotem.cfc.dto.NotificationMessage.class);
+        verify(wechat, atLeastOnce()).send(msgCaptor.capture());
+        String content = msgCaptor.getValue().getContent();
         assertNotNull(content, "晚总结内容不应为空");
         assertNotNull(content, "晚总结内容不应为空");
-        if (!content.contains("未完成") || !content.contains("已完成")) {
-            fail("RED[task.reminder.daily] 晚总结应区分「已完成/未完成」两组"
-                    + "(设计契约 §四 验收 3,实际内容=" + content + ")");
-        }
+        assertTrue(content.contains("每一步都算数"), "50%档应为温和加油,实际=" + content);
+        assertTrue(content.contains("您"), "昵称缺失应回退您,实际=" + content);
     }
     }
 
 
     @Test
     @Test
@@ -304,6 +308,50 @@ class TaskReminderDailyScheduledTaskContractTest {
                 any(), anyLong(), any(), any());
                 any(), anyLong(), any(), any());
     }
     }
 
 
+    // ==================== 晚间 webhook 分发(2026-11-29 增强) ====================
+
+    @Test
+    @DisplayName("晚间发送-1:走 wechat 通道,content 为四档鼓励文案(非旧催办文案)")
+    @SuppressWarnings("unchecked")
+    void eveningSummary_dispatchesWechatEncouragement() throws Exception {
+        Object host = contractHost();
+        TaskMapper taskMapper = mock(TaskMapper.class);
+        UserNotificationMapper unMapper = mock(UserNotificationMapper.class);
+        inject(host, "taskMapper", taskMapper);
+        inject(host, "userNotificationMapper", unMapper);
+
+        // 用户 mapper(昵称)
+        com.etotem.cfc.mapper.UserMapper userMapper = mock(com.etotem.cfc.mapper.UserMapper.class);
+        com.etotem.cfc.entity.User user = new com.etotem.cfc.entity.User();
+        user.setId(1L); user.setNickname("小明");
+        when(userMapper.selectById(anyLong())).thenReturn(user);
+        inject(host, "userMapper", userMapper);
+
+        // wechat channel(enabled=true)
+        com.etotem.cfc.service.notification.NotificationChannel wechat =
+                mock(com.etotem.cfc.service.notification.NotificationChannel.class);
+        when(wechat.getChannelType()).thenReturn("wechat");
+        when(wechat.isEnabled()).thenReturn(true);
+        java.util.List<com.etotem.cfc.service.notification.NotificationChannel> channels =
+                new ArrayList<>(java.util.Collections.singletonList(wechat));
+        inject(host, "notificationChannels", channels);
+
+        // 1 已完成 today → 100% 档
+        Task done = doneToday(10L, "喝水");
+        done.setExecutorId(1L);
+        when(taskMapper.selectList(any())).thenReturn(new ArrayList<>(java.util.Collections.singletonList(done)));
+        when(unMapper.selectCount(any())).thenReturn(0L);
+
+        call(host, "sendEveningSummary");
+
+        ArgumentCaptor<com.etotem.cfc.dto.NotificationMessage> msgCaptor =
+                ArgumentCaptor.forClass(com.etotem.cfc.dto.NotificationMessage.class);
+        verify(wechat, atLeastOnce()).send(msgCaptor.capture());
+        com.etotem.cfc.dto.NotificationMessage msg = msgCaptor.getValue();
+        assertTrue(msg.getChannels().contains("wechat"), "晚提醒 channels 应含 wechat,实际=" + msg.getChannels());
+        assertTrue(msg.getContent().contains("全都完成了"), "content 应为四档鼓励文案,实际=" + msg.getContent());
+    }
+
     // ==================== 晚间四档关怀鼓励文案(2026-11-29 增强) ====================
     // ==================== 晚间四档关怀鼓励文案(2026-11-29 增强) ====================
 
 
     /** 反射调用私有 buildEveningEncouragement(List<Task>, String) */
     /** 反射调用私有 buildEveningEncouragement(List<Task>, String) */