feat: 新增喝水提醒功能,支持定期提醒和目标检查

This commit is contained in:
richarjiang
2025-09-02 18:56:40 +08:00
parent ccbc3417bc
commit 70e3152158
6 changed files with 569 additions and 61 deletions

View File

@@ -81,6 +81,78 @@ export const createNotificationCheckTask = (): BackgroundTask => ({
},
});
// 喝水提醒检查任务
export const createWaterReminderTask = (): BackgroundTask => ({
id: 'water-reminder-task',
name: '喝水提醒检查任务',
handler: async (data?: any) => {
console.log('开始执行喝水提醒检查任务');
try {
// 导入必要的模块
const { WaterNotificationHelpers } = await import('@/utils/notificationHelpers');
const { getTodayWaterStats } = await import('@/services/waterRecords');
const AsyncStorage = (await import('@react-native-async-storage/async-storage')).default;
// 获取用户信息
const userProfileJson = await AsyncStorage.getItem('@user_profile');
const userProfile = userProfileJson ? JSON.parse(userProfileJson) : null;
const userName = userProfile?.name || '朋友';
// 检查时间限制早上9点以前和晚上9点以后不通知
const currentHour = new Date().getHours();
if (currentHour < 9 || currentHour >= 21) {
console.log(`当前时间${currentHour}不在通知时间范围内9:00-21:00跳过喝水提醒检查`);
return;
}
// 获取今日喝水统计数据
let todayStats;
try {
todayStats = await getTodayWaterStats();
} catch (error) {
console.log('获取喝水统计数据失败,可能用户未登录或无网络连接:', error);
return;
}
if (!todayStats || !todayStats.dailyGoal || todayStats.dailyGoal <= 0) {
console.log('没有设置喝水目标或目标无效,跳过喝水检查');
return;
}
// 构造今日统计数据
const waterStatsForCheck = {
totalAmount: todayStats.totalAmount || 0,
dailyGoal: todayStats.dailyGoal,
completionRate: todayStats.completionRate || 0
};
// 调用喝水通知检查函数
const notificationSent = await WaterNotificationHelpers.checkWaterGoalAndNotify(
userName,
waterStatsForCheck,
currentHour
);
if (notificationSent) {
console.log('喝水提醒通知已发送');
} else {
console.log('无需发送喝水提醒通知');
}
console.log('喝水提醒检查任务执行完成');
} catch (error) {
console.error('喝水提醒检查任务执行失败:', error);
throw error;
}
},
options: {
minimumInterval: 60, // 60分钟最小间隔
stopOnTerminate: false,
startOnBoot: true,
},
});
// 示例任务:缓存清理任务
export const createCacheCleanupTask = (): BackgroundTask => ({
id: 'cache-cleanup-task',
@@ -142,6 +214,7 @@ export const registerDefaultTasks = async (): Promise<void> => {
createDataSyncTask(),
createHealthDataUpdateTask(),
createNotificationCheckTask(),
createWaterReminderTask(),
createCacheCleanupTask(),
createUserAnalyticsTask(),
];

View File

@@ -170,6 +170,13 @@ export class NotificationService {
if (data?.url) {
router.push(data.url as any);
}
} else if (data?.type === 'water_reminder' || data?.type === 'regular_water_reminder') {
// 处理喝水提醒通知
console.log('用户点击了喝水提醒通知', data);
// 跳转到统计页面查看喝水进度
if (data?.url) {
router.push(data.url as any);
}
}
}
@@ -446,6 +453,8 @@ export const NotificationTypes = {
LUNCH_REMINDER: 'lunch_reminder',
DINNER_REMINDER: 'dinner_reminder',
MOOD_REMINDER: 'mood_reminder',
WATER_REMINDER: 'water_reminder',
REGULAR_WATER_REMINDER: 'regular_water_reminder',
} as const;
// 便捷方法