feat: 增强目标管理功能及相关组件
- 在 GoalsListScreen 中新增目标编辑功能,支持用户编辑现有目标 - 更新 CreateGoalModal 组件,支持编辑模式下的目标更新 - 在 NutritionRecordsScreen 中新增删除营养记录功能,允许用户删除不需要的记录 - 更新 NutritionRecordCard 组件,增加操作选项,支持删除记录 - 修改 dietRecords 服务,添加删除营养记录的 API 调用 - 优化 goalsSlice,确保目标更新逻辑与 Redux 状态管理一致
This commit is contained in:
@@ -1,10 +1,12 @@
|
|||||||
import { GoalCard } from '@/components/GoalCard';
|
import { GoalCard } from '@/components/GoalCard';
|
||||||
|
import { CreateGoalModal } from '@/components/model/CreateGoalModal';
|
||||||
|
import { useGlobalDialog } from '@/components/ui/DialogProvider';
|
||||||
import { Colors } from '@/constants/Colors';
|
import { Colors } from '@/constants/Colors';
|
||||||
import { TAB_BAR_BOTTOM_OFFSET, TAB_BAR_HEIGHT } from '@/constants/TabBar';
|
import { TAB_BAR_BOTTOM_OFFSET, TAB_BAR_HEIGHT } from '@/constants/TabBar';
|
||||||
import { useAppDispatch, useAppSelector } from '@/hooks/redux';
|
import { useAppDispatch, useAppSelector } from '@/hooks/redux';
|
||||||
import { useColorScheme } from '@/hooks/useColorScheme';
|
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||||
import { deleteGoal, fetchGoals, loadMoreGoals } from '@/store/goalsSlice';
|
import { deleteGoal, fetchGoals, loadMoreGoals, updateGoal } from '@/store/goalsSlice';
|
||||||
import { GoalListItem } from '@/types/goals';
|
import { CreateGoalRequest, GoalListItem, UpdateGoalRequest } from '@/types/goals';
|
||||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
||||||
import { useFocusEffect } from '@react-navigation/native';
|
import { useFocusEffect } from '@react-navigation/native';
|
||||||
import { LinearGradient } from 'expo-linear-gradient';
|
import { LinearGradient } from 'expo-linear-gradient';
|
||||||
@@ -19,16 +21,24 @@ export default function GoalsListScreen() {
|
|||||||
const dispatch = useAppDispatch();
|
const dispatch = useAppDispatch();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
|
const { showConfirm } = useGlobalDialog();
|
||||||
|
|
||||||
// Redux状态
|
// Redux状态
|
||||||
const {
|
const {
|
||||||
goals,
|
goals,
|
||||||
goalsLoading,
|
goalsLoading,
|
||||||
goalsError,
|
goalsError,
|
||||||
goalsPagination,
|
goalsPagination,
|
||||||
|
updateLoading,
|
||||||
|
updateError,
|
||||||
} = useAppSelector((state) => state.goals);
|
} = useAppSelector((state) => state.goals);
|
||||||
|
|
||||||
const [refreshing, setRefreshing] = useState(false);
|
const [refreshing, setRefreshing] = useState(false);
|
||||||
|
|
||||||
|
// 编辑目标相关状态
|
||||||
|
const [showEditModal, setShowEditModal] = useState(false);
|
||||||
|
const [editingGoal, setEditingGoal] = useState<GoalListItem | null>(null);
|
||||||
|
|
||||||
// 页面聚焦时重新加载数据
|
// 页面聚焦时重新加载数据
|
||||||
useFocusEffect(
|
useFocusEffect(
|
||||||
useCallback(() => {
|
useCallback(() => {
|
||||||
@@ -162,16 +172,11 @@ export default function GoalsListScreen() {
|
|||||||
if (goalsError) {
|
if (goalsError) {
|
||||||
Alert.alert('错误', goalsError);
|
Alert.alert('错误', goalsError);
|
||||||
}
|
}
|
||||||
}, [goalsError]);
|
if (updateError) {
|
||||||
|
Alert.alert('更新失败', updateError);
|
||||||
|
}
|
||||||
|
}, [goalsError, updateError]);
|
||||||
|
|
||||||
// 计算各状态的目标数量
|
|
||||||
const goalCounts = useMemo(() => ({
|
|
||||||
all: goals.length,
|
|
||||||
active: goals.filter(goal => goal.status === 'active').length,
|
|
||||||
paused: goals.filter(goal => goal.status === 'paused').length,
|
|
||||||
completed: goals.filter(goal => goal.status === 'completed').length,
|
|
||||||
cancelled: goals.filter(goal => goal.status === 'cancelled').length,
|
|
||||||
}), [goals]);
|
|
||||||
|
|
||||||
// 根据筛选条件过滤目标
|
// 根据筛选条件过滤目标
|
||||||
const filteredGoals = useMemo(() => {
|
const filteredGoals = useMemo(() => {
|
||||||
@@ -182,6 +187,58 @@ export default function GoalsListScreen() {
|
|||||||
|
|
||||||
// 处理目标点击
|
// 处理目标点击
|
||||||
const handleGoalPress = (goal: GoalListItem) => {
|
const handleGoalPress = (goal: GoalListItem) => {
|
||||||
|
setEditingGoal(goal);
|
||||||
|
setShowEditModal(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 将 GoalListItem 转换为 CreateGoalRequest 格式
|
||||||
|
const convertGoalToModalData = (goal: GoalListItem): Partial<CreateGoalRequest> => {
|
||||||
|
return {
|
||||||
|
title: goal.title,
|
||||||
|
description: goal.description,
|
||||||
|
repeatType: goal.repeatType,
|
||||||
|
frequency: goal.frequency,
|
||||||
|
category: goal.category,
|
||||||
|
priority: goal.priority,
|
||||||
|
hasReminder: goal.hasReminder,
|
||||||
|
reminderTime: goal.reminderTime,
|
||||||
|
customRepeatRule: goal.customRepeatRule,
|
||||||
|
endDate: goal.endDate,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// 处理更新目标
|
||||||
|
const handleUpdateGoal = async (goalId: string, goalData: UpdateGoalRequest) => {
|
||||||
|
try {
|
||||||
|
await dispatch(updateGoal({ goalId, goalData })).unwrap();
|
||||||
|
setShowEditModal(false);
|
||||||
|
setEditingGoal(null);
|
||||||
|
|
||||||
|
// 使用全局弹窗显示成功消息
|
||||||
|
showConfirm(
|
||||||
|
{
|
||||||
|
title: '目标更新成功',
|
||||||
|
message: '恭喜!您的目标已成功更新。',
|
||||||
|
confirmText: '确定',
|
||||||
|
cancelText: '',
|
||||||
|
icon: 'checkmark-circle',
|
||||||
|
iconColor: '#10B981',
|
||||||
|
},
|
||||||
|
() => {
|
||||||
|
console.log('用户确认了目标更新成功');
|
||||||
|
}
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to update goal:', error);
|
||||||
|
Alert.alert('错误', '更新目标失败,请重试');
|
||||||
|
// 更新失败时不关闭弹窗,保持编辑状态
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 处理编辑弹窗关闭
|
||||||
|
const handleCloseEditModal = () => {
|
||||||
|
setShowEditModal(false);
|
||||||
|
setEditingGoal(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
// 渲染目标项
|
// 渲染目标项
|
||||||
@@ -292,6 +349,19 @@ export default function GoalsListScreen() {
|
|||||||
ListFooterComponent={renderLoadMore}
|
ListFooterComponent={renderLoadMore}
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
|
{/* 编辑目标弹窗 */}
|
||||||
|
{editingGoal && (
|
||||||
|
<CreateGoalModal
|
||||||
|
visible={showEditModal}
|
||||||
|
onClose={handleCloseEditModal}
|
||||||
|
onSubmit={() => {}} // 编辑模式下不使用这个回调
|
||||||
|
onUpdate={handleUpdateGoal}
|
||||||
|
loading={updateLoading}
|
||||||
|
initialData={convertGoalToModalData(editingGoal)}
|
||||||
|
editGoalId={editingGoal.id}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</View>
|
</View>
|
||||||
</SafeAreaView>
|
</SafeAreaView>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { NutritionRecordCard } from '@/components/NutritionRecordCard';
|
|||||||
import { HeaderBar } from '@/components/ui/HeaderBar';
|
import { HeaderBar } from '@/components/ui/HeaderBar';
|
||||||
import { Colors } from '@/constants/Colors';
|
import { Colors } from '@/constants/Colors';
|
||||||
import { useColorScheme } from '@/hooks/useColorScheme';
|
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||||
import { DietRecord, getDietRecords } from '@/services/dietRecords';
|
import { DietRecord, deleteDietRecord, getDietRecords } from '@/services/dietRecords';
|
||||||
import { getMonthDaysZh, getMonthTitleZh, getTodayIndexInMonth } from '@/utils/date';
|
import { getMonthDaysZh, getMonthTitleZh, getTodayIndexInMonth } from '@/utils/date';
|
||||||
import { Ionicons } from '@expo/vector-icons';
|
import { Ionicons } from '@expo/vector-icons';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
@@ -136,6 +136,18 @@ export default function NutritionRecordsScreen() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 删除记录
|
||||||
|
const handleDeleteRecord = async (recordId: number) => {
|
||||||
|
try {
|
||||||
|
await deleteDietRecord(recordId);
|
||||||
|
// 从本地状态中移除已删除的记录
|
||||||
|
setRecords(prev => prev.filter(record => record.id !== recordId));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('删除营养记录失败:', error);
|
||||||
|
// 可以添加错误提示
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// 渲染视图模式切换器
|
// 渲染视图模式切换器
|
||||||
const renderViewModeToggle = () => (
|
const renderViewModeToggle = () => (
|
||||||
<View style={[styles.viewModeContainer, { backgroundColor: colorTokens.pageBackgroundEmphasis }]}>
|
<View style={[styles.viewModeContainer, { backgroundColor: colorTokens.pageBackgroundEmphasis }]}>
|
||||||
@@ -275,6 +287,7 @@ export default function NutritionRecordsScreen() {
|
|||||||
showTimeline={true}
|
showTimeline={true}
|
||||||
isFirst={index === 0}
|
isFirst={index === 0}
|
||||||
isLast={index === records.length - 1}
|
isLast={index === records.length - 1}
|
||||||
|
onDelete={() => handleDeleteRecord(item.id)}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,16 @@
|
|||||||
import { ThemedText } from '@/components/ThemedText';
|
import { ThemedText } from '@/components/ThemedText';
|
||||||
|
import { ActionSheet } from '@/components/ui/ActionSheet';
|
||||||
import { useThemeColor } from '@/hooks/useThemeColor';
|
import { useThemeColor } from '@/hooks/useThemeColor';
|
||||||
import { DietRecord } from '@/services/dietRecords';
|
import { DietRecord } from '@/services/dietRecords';
|
||||||
import { Ionicons } from '@expo/vector-icons';
|
import { Ionicons } from '@expo/vector-icons';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import React, { useMemo } from 'react';
|
import React, { useMemo, useState } from 'react';
|
||||||
import { Image, StyleSheet, TouchableOpacity, View } from 'react-native';
|
import { Image, StyleSheet, TouchableOpacity, View } from 'react-native';
|
||||||
|
|
||||||
export type NutritionRecordCardProps = {
|
export type NutritionRecordCardProps = {
|
||||||
record: DietRecord;
|
record: DietRecord;
|
||||||
onPress?: () => void;
|
onPress?: () => void;
|
||||||
|
onDelete?: () => void;
|
||||||
showTimeline?: boolean;
|
showTimeline?: boolean;
|
||||||
isFirst?: boolean;
|
isFirst?: boolean;
|
||||||
isLast?: boolean;
|
isLast?: boolean;
|
||||||
@@ -41,6 +43,7 @@ const MEAL_TYPE_COLORS = {
|
|||||||
export function NutritionRecordCard({
|
export function NutritionRecordCard({
|
||||||
record,
|
record,
|
||||||
onPress,
|
onPress,
|
||||||
|
onDelete,
|
||||||
showTimeline = false,
|
showTimeline = false,
|
||||||
isFirst = false,
|
isFirst = false,
|
||||||
isLast = false
|
isLast = false
|
||||||
@@ -50,6 +53,9 @@ export function NutritionRecordCard({
|
|||||||
const textSecondaryColor = useThemeColor({}, 'textSecondary');
|
const textSecondaryColor = useThemeColor({}, 'textSecondary');
|
||||||
const primaryColor = useThemeColor({}, 'primary');
|
const primaryColor = useThemeColor({}, 'primary');
|
||||||
|
|
||||||
|
// ActionSheet 状态管理
|
||||||
|
const [showActionSheet, setShowActionSheet] = useState(false);
|
||||||
|
|
||||||
// 营养数据统计
|
// 营养数据统计
|
||||||
const nutritionStats = useMemo(() => {
|
const nutritionStats = useMemo(() => {
|
||||||
return [
|
return [
|
||||||
@@ -117,38 +123,36 @@ export function NutritionRecordCard({
|
|||||||
>
|
>
|
||||||
{/* 主要内容区域 */}
|
{/* 主要内容区域 */}
|
||||||
<View style={styles.mainContent}>
|
<View style={styles.mainContent}>
|
||||||
{/* 左侧:食物图片 */}
|
|
||||||
<View style={[styles.foodImageContainer, !record.imageUrl && styles.foodImagePlaceholder]}>
|
|
||||||
{record.imageUrl ? (
|
|
||||||
<Image source={{ uri: record.imageUrl }} style={styles.foodImage} />
|
|
||||||
) : (
|
|
||||||
<Ionicons name="restaurant" size={32} color={textSecondaryColor} />
|
|
||||||
)}
|
|
||||||
</View>
|
|
||||||
|
|
||||||
{/* 右侧:食物信息 */}
|
|
||||||
<View style={styles.foodInfoContainer}>
|
<View style={styles.foodInfoContainer}>
|
||||||
{/* 餐次和操作按钮 */}
|
{/* 餐次和操作按钮 */}
|
||||||
<View style={styles.headerRow}>
|
<View style={styles.headerRow}>
|
||||||
<View style={styles.mealTypeContainer}>
|
<View style={styles.mealTypeContainer}>
|
||||||
<View style={[styles.mealTypeBadge, { backgroundColor: `${mealTypeColor}15` }]}>
|
|
||||||
<ThemedText style={[styles.mealTypeText, { color: mealTypeColor }]}>
|
|
||||||
{mealTypeLabel}
|
|
||||||
</ThemedText>
|
|
||||||
</View>
|
|
||||||
{!showTimeline && (
|
{!showTimeline && (
|
||||||
<ThemedText style={[styles.mealTime, { color: textSecondaryColor }]}>
|
<ThemedText style={[styles.mealTime, { color: textSecondaryColor }]}>
|
||||||
{record.mealTime ? dayjs(record.mealTime).format('HH:mm') : '时间未设置'}
|
{record.mealTime ? dayjs(record.mealTime).format('HH:mm') : '时间未设置'}
|
||||||
</ThemedText>
|
</ThemedText>
|
||||||
)}
|
)}
|
||||||
</View>
|
</View>
|
||||||
<TouchableOpacity style={styles.moreButton}>
|
<TouchableOpacity
|
||||||
|
style={styles.moreButton}
|
||||||
|
onPress={() => setShowActionSheet(true)}
|
||||||
|
>
|
||||||
<Ionicons name="ellipsis-horizontal" size={20} color={textSecondaryColor} />
|
<Ionicons name="ellipsis-horizontal" size={20} color={textSecondaryColor} />
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
{/* 食物名称和分量 */}
|
{/* 食物名称和分量 */}
|
||||||
<View style={styles.foodNameSection}>
|
<View style={styles.foodNameSection}>
|
||||||
|
{/* 左侧:食物图片 */}
|
||||||
|
<View style={[styles.foodImageContainer, !record.imageUrl && styles.foodImagePlaceholder]}>
|
||||||
|
{record.imageUrl ? (
|
||||||
|
<Image source={{ uri: record.imageUrl }} style={styles.foodImage} />
|
||||||
|
) : (
|
||||||
|
<Ionicons name="restaurant" size={12} color={textSecondaryColor} />
|
||||||
|
)}
|
||||||
|
</View>
|
||||||
|
|
||||||
<ThemedText style={[styles.foodName, { color: textColor }]}>
|
<ThemedText style={[styles.foodName, { color: textColor }]}>
|
||||||
{record.foodName}
|
{record.foodName}
|
||||||
</ThemedText>
|
</ThemedText>
|
||||||
@@ -157,19 +161,22 @@ export function NutritionRecordCard({
|
|||||||
{record.portionDescription || `${record.weightGrams}g`}
|
{record.portionDescription || `${record.weightGrams}g`}
|
||||||
</ThemedText>
|
</ThemedText>
|
||||||
)}
|
)}
|
||||||
</View>
|
<View style={[styles.mealTypeBadge, { backgroundColor: `${mealTypeColor}15` }]}>
|
||||||
|
<ThemedText style={[styles.mealTypeText, { color: mealTypeColor }]}>
|
||||||
{/* 营养信息网格 */}
|
{mealTypeLabel}
|
||||||
<View style={styles.nutritionGrid}>
|
|
||||||
{nutritionStats.map((stat) => (
|
|
||||||
<View key={stat.label} style={styles.nutritionItem}>
|
|
||||||
<View style={styles.nutritionItemHeader}>
|
|
||||||
<Ionicons name={stat.icon} size={14} color={stat.color} />
|
|
||||||
<ThemedText style={[styles.nutritionLabel, { color: textSecondaryColor }]}>
|
|
||||||
{stat.label}
|
|
||||||
</ThemedText>
|
</ThemedText>
|
||||||
</View>
|
</View>
|
||||||
<ThemedText style={[styles.nutritionValue, { color: textColor }]}>
|
</View>
|
||||||
|
|
||||||
|
{/* 营养信息 - 紧凑标签布局 */}
|
||||||
|
<View style={styles.nutritionContainer}>
|
||||||
|
{nutritionStats.map((stat, index) => (
|
||||||
|
<View key={stat.label} style={styles.nutritionTag}>
|
||||||
|
<Ionicons name={stat.icon} size={10} color={stat.color} />
|
||||||
|
<ThemedText style={[styles.nutritionText, { color: textSecondaryColor }]} numberOfLines={1}>
|
||||||
|
{stat.label}
|
||||||
|
</ThemedText>
|
||||||
|
<ThemedText style={[styles.nutritionValue, { color: textColor }]} numberOfLines={1}>
|
||||||
{stat.value}
|
{stat.value}
|
||||||
</ThemedText>
|
</ThemedText>
|
||||||
</View>
|
</View>
|
||||||
@@ -187,6 +194,25 @@ export function NutritionRecordCard({
|
|||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
|
|
||||||
|
{/* ActionSheet for more options */}
|
||||||
|
<ActionSheet
|
||||||
|
visible={showActionSheet}
|
||||||
|
onClose={() => setShowActionSheet(false)}
|
||||||
|
title="选择操作"
|
||||||
|
options={[
|
||||||
|
{
|
||||||
|
id: 'delete',
|
||||||
|
title: '删除记录',
|
||||||
|
subtitle: '删除后无法恢复',
|
||||||
|
icon: 'trash-outline',
|
||||||
|
destructive: true,
|
||||||
|
onPress: () => {
|
||||||
|
onDelete?.();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]}
|
||||||
|
/>
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -248,10 +274,10 @@ const styles = StyleSheet.create({
|
|||||||
flexDirection: 'row',
|
flexDirection: 'row',
|
||||||
},
|
},
|
||||||
foodImageContainer: {
|
foodImageContainer: {
|
||||||
width: 80,
|
width: 28,
|
||||||
height: 80,
|
height: 28,
|
||||||
borderRadius: 16,
|
borderRadius: 16,
|
||||||
marginRight: 16,
|
marginRight: 8,
|
||||||
overflow: 'hidden',
|
overflow: 'hidden',
|
||||||
},
|
},
|
||||||
foodImage: {
|
foodImage: {
|
||||||
@@ -271,19 +297,20 @@ const styles = StyleSheet.create({
|
|||||||
justifyContent: 'space-between',
|
justifyContent: 'space-between',
|
||||||
alignItems: 'flex-start',
|
alignItems: 'flex-start',
|
||||||
marginBottom: 8,
|
marginBottom: 8,
|
||||||
|
position: 'absolute',
|
||||||
|
top: 0,
|
||||||
|
right: 0,
|
||||||
},
|
},
|
||||||
mealTypeContainer: {
|
mealTypeContainer: {
|
||||||
flex: 1,
|
flex: 1,
|
||||||
},
|
},
|
||||||
mealTypeBadge: {
|
mealTypeBadge: {
|
||||||
alignSelf: 'flex-start',
|
paddingHorizontal: 4,
|
||||||
paddingHorizontal: 8,
|
|
||||||
paddingVertical: 4,
|
|
||||||
borderRadius: 8,
|
borderRadius: 8,
|
||||||
marginBottom: 4,
|
marginLeft: 4,
|
||||||
},
|
},
|
||||||
mealTypeText: {
|
mealTypeText: {
|
||||||
fontSize: 12,
|
fontSize: 8,
|
||||||
fontWeight: '600',
|
fontWeight: '600',
|
||||||
},
|
},
|
||||||
mealTime: {
|
mealTime: {
|
||||||
@@ -296,6 +323,9 @@ const styles = StyleSheet.create({
|
|||||||
},
|
},
|
||||||
foodNameSection: {
|
foodNameSection: {
|
||||||
marginBottom: 12,
|
marginBottom: 12,
|
||||||
|
flexDirection: 'row',
|
||||||
|
gap: 4,
|
||||||
|
alignItems: 'center',
|
||||||
},
|
},
|
||||||
foodName: {
|
foodName: {
|
||||||
fontSize: 18,
|
fontSize: 18,
|
||||||
@@ -304,32 +334,38 @@ const styles = StyleSheet.create({
|
|||||||
marginBottom: 2,
|
marginBottom: 2,
|
||||||
},
|
},
|
||||||
portionInfo: {
|
portionInfo: {
|
||||||
fontSize: 14,
|
|
||||||
fontWeight: '500',
|
|
||||||
},
|
|
||||||
nutritionGrid: {
|
|
||||||
flexDirection: 'row',
|
|
||||||
flexWrap: 'wrap',
|
|
||||||
marginBottom: 8,
|
|
||||||
},
|
|
||||||
nutritionItem: {
|
|
||||||
width: '50%',
|
|
||||||
marginBottom: 8,
|
|
||||||
paddingRight: 8,
|
|
||||||
},
|
|
||||||
nutritionItemHeader: {
|
|
||||||
flexDirection: 'row',
|
|
||||||
alignItems: 'center',
|
|
||||||
marginBottom: 2,
|
|
||||||
},
|
|
||||||
nutritionLabel: {
|
|
||||||
fontSize: 12,
|
fontSize: 12,
|
||||||
fontWeight: '500',
|
fontWeight: '500',
|
||||||
|
},
|
||||||
|
nutritionContainer: {
|
||||||
|
flexDirection: 'row',
|
||||||
|
flexWrap: 'wrap',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
},
|
||||||
|
nutritionTag: {
|
||||||
|
flexDirection: 'row',
|
||||||
|
alignItems: 'center',
|
||||||
|
backgroundColor: 'rgba(248, 249, 250, 0.8)',
|
||||||
|
borderRadius: 8,
|
||||||
|
paddingHorizontal: 8,
|
||||||
|
paddingVertical: 2,
|
||||||
|
marginBottom: 4,
|
||||||
|
width: '48%',
|
||||||
|
overflow: 'hidden',
|
||||||
|
},
|
||||||
|
nutritionText: {
|
||||||
|
fontSize: 9,
|
||||||
|
fontWeight: '500',
|
||||||
marginLeft: 4,
|
marginLeft: 4,
|
||||||
|
marginRight: 2,
|
||||||
|
flexShrink: 0,
|
||||||
},
|
},
|
||||||
nutritionValue: {
|
nutritionValue: {
|
||||||
fontSize: 14,
|
fontSize: 10,
|
||||||
fontWeight: '700',
|
fontWeight: '700',
|
||||||
|
flexShrink: 1,
|
||||||
|
textAlign: 'right',
|
||||||
|
flex: 1,
|
||||||
},
|
},
|
||||||
notesSection: {
|
notesSection: {
|
||||||
marginTop: 8,
|
marginTop: 8,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Colors } from '@/constants/Colors';
|
import { Colors } from '@/constants/Colors';
|
||||||
import { useColorScheme } from '@/hooks/useColorScheme';
|
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||||
import { CreateGoalRequest, GoalPriority, RepeatType } from '@/types/goals';
|
import { CreateGoalRequest, GoalPriority, RepeatType, UpdateGoalRequest } from '@/types/goals';
|
||||||
import { Ionicons } from '@expo/vector-icons';
|
import { Ionicons } from '@expo/vector-icons';
|
||||||
import DateTimePicker from '@react-native-community/datetimepicker';
|
import DateTimePicker from '@react-native-community/datetimepicker';
|
||||||
import { LinearGradient } from 'expo-linear-gradient';
|
import { LinearGradient } from 'expo-linear-gradient';
|
||||||
@@ -24,9 +24,11 @@ interface CreateGoalModalProps {
|
|||||||
visible: boolean;
|
visible: boolean;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onSubmit: (goalData: CreateGoalRequest) => void;
|
onSubmit: (goalData: CreateGoalRequest) => void;
|
||||||
|
onUpdate?: (goalId: string, goalData: UpdateGoalRequest) => void;
|
||||||
onSuccess?: () => void;
|
onSuccess?: () => void;
|
||||||
loading?: boolean;
|
loading?: boolean;
|
||||||
initialData?: Partial<CreateGoalRequest>;
|
initialData?: Partial<CreateGoalRequest>;
|
||||||
|
editGoalId?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const REPEAT_TYPE_OPTIONS: { value: RepeatType; label: string }[] = [
|
const REPEAT_TYPE_OPTIONS: { value: RepeatType; label: string }[] = [
|
||||||
@@ -41,9 +43,11 @@ export const CreateGoalModal: React.FC<CreateGoalModalProps> = ({
|
|||||||
visible,
|
visible,
|
||||||
onClose,
|
onClose,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
|
onUpdate,
|
||||||
onSuccess,
|
onSuccess,
|
||||||
loading = false,
|
loading = false,
|
||||||
initialData,
|
initialData,
|
||||||
|
editGoalId,
|
||||||
}) => {
|
}) => {
|
||||||
const theme = (useColorScheme() ?? 'light') as 'light' | 'dark';
|
const theme = (useColorScheme() ?? 'light') as 'light' | 'dark';
|
||||||
const colorTokens = Colors[theme];
|
const colorTokens = Colors[theme];
|
||||||
@@ -130,8 +134,29 @@ export const CreateGoalModal: React.FC<CreateGoalModalProps> = ({
|
|||||||
startTime = hours * 60 + minutes;
|
startTime = hours * 60 + minutes;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 根据是否是编辑模式决定数据结构
|
||||||
|
if (editGoalId && onUpdate) {
|
||||||
|
// 更新模式:使用 UpdateGoalRequest 结构
|
||||||
|
const updateData: UpdateGoalRequest = {
|
||||||
|
title: title.trim(),
|
||||||
|
description: description.trim() || undefined,
|
||||||
|
repeatType,
|
||||||
|
frequency,
|
||||||
|
category: category.trim() || undefined,
|
||||||
|
priority,
|
||||||
|
hasReminder,
|
||||||
|
reminderTime: hasReminder ? reminderTime : undefined,
|
||||||
|
customRepeatRule: {
|
||||||
|
weekdays: repeatType === 'weekly' ? selectedWeekdays : [1, 2, 3, 4, 5, 6, 0],
|
||||||
|
dayOfMonth: repeatType === 'monthly' ? selectedMonthDays : undefined,
|
||||||
|
},
|
||||||
|
endDate: endDate || undefined,
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log('updateData', updateData);
|
||||||
|
onUpdate(editGoalId, updateData);
|
||||||
|
} else {
|
||||||
|
// 创建模式:使用 CreateGoalRequest 结构
|
||||||
const goalData: CreateGoalRequest = {
|
const goalData: CreateGoalRequest = {
|
||||||
title: title.trim(),
|
title: title.trim(),
|
||||||
description: description.trim() || undefined,
|
description: description.trim() || undefined,
|
||||||
@@ -142,16 +167,16 @@ export const CreateGoalModal: React.FC<CreateGoalModalProps> = ({
|
|||||||
hasReminder,
|
hasReminder,
|
||||||
reminderTime: hasReminder ? reminderTime : undefined,
|
reminderTime: hasReminder ? reminderTime : undefined,
|
||||||
customRepeatRule: {
|
customRepeatRule: {
|
||||||
weekdays: repeatType === 'weekly' ? selectedWeekdays : [1, 2, 3, 4, 5, 6, 0], // 根据重复类型设置周几
|
weekdays: repeatType === 'weekly' ? selectedWeekdays : [1, 2, 3, 4, 5, 6, 0],
|
||||||
dayOfMonth: repeatType === 'monthly' ? selectedMonthDays : undefined, // 根据重复类型设置月几
|
dayOfMonth: repeatType === 'monthly' ? selectedMonthDays : undefined,
|
||||||
},
|
},
|
||||||
startTime,
|
startTime,
|
||||||
endDate: endDate || undefined,
|
endDate: endDate || undefined,
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log('goalData', goalData);
|
console.log('goalData', goalData);
|
||||||
|
|
||||||
onSubmit(goalData);
|
onSubmit(goalData);
|
||||||
|
}
|
||||||
|
|
||||||
// 通知父组件提交成功
|
// 通知父组件提交成功
|
||||||
if (onSuccess) {
|
if (onSuccess) {
|
||||||
@@ -278,7 +303,7 @@ export const CreateGoalModal: React.FC<CreateGoalModalProps> = ({
|
|||||||
<Ionicons name="close" size={24} color={colorTokens.text} />
|
<Ionicons name="close" size={24} color={colorTokens.text} />
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
<Text style={[styles.title, { color: colorTokens.text }]}>
|
<Text style={[styles.title, { color: colorTokens.text }]}>
|
||||||
创建新目标
|
{editGoalId ? '编辑目标' : '创建新目标'}
|
||||||
</Text>
|
</Text>
|
||||||
<View style={{ width: 24 }} />
|
<View style={{ width: 24 }} />
|
||||||
</View>
|
</View>
|
||||||
@@ -717,7 +742,7 @@ export const CreateGoalModal: React.FC<CreateGoalModalProps> = ({
|
|||||||
disabled={loading || !title.trim()}
|
disabled={loading || !title.trim()}
|
||||||
>
|
>
|
||||||
<Text style={styles.saveButtonText}>
|
<Text style={styles.saveButtonText}>
|
||||||
{loading ? '保存中...' : '保存'}
|
{loading ? (editGoalId ? '更新中...' : '保存中...') : (editGoalId ? '更新' : '保存')}
|
||||||
</Text>
|
</Text>
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
</View>
|
</View>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
"reset-project": "node ./scripts/reset-project.js",
|
"reset-project": "node ./scripts/reset-project.js",
|
||||||
"android": "expo run:android",
|
"android": "expo run:android",
|
||||||
"ios": "expo run:ios",
|
"ios": "expo run:ios",
|
||||||
|
"ios-device": "expo run:ios --device",
|
||||||
"web": "expo start --web",
|
"web": "expo start --web",
|
||||||
"lint": "expo lint"
|
"lint": "expo lint"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -68,6 +68,10 @@ export async function getDietRecords({
|
|||||||
}>(`/users/diet-records${params}`);
|
}>(`/users/diet-records${params}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function deleteDietRecord(recordId: number): Promise<void> {
|
||||||
|
await api.delete(`/users/diet-records/${recordId}`);
|
||||||
|
}
|
||||||
|
|
||||||
export function calculateNutritionSummary(records: DietRecord[]): NutritionSummary {
|
export function calculateNutritionSummary(records: DietRecord[]): NutritionSummary {
|
||||||
if (records?.length === 0) {
|
if (records?.length === 0) {
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -53,8 +53,8 @@ export const getGoalById = async (goalId: string): Promise<ApiResponse<GoalDetai
|
|||||||
/**
|
/**
|
||||||
* 更新目标
|
* 更新目标
|
||||||
*/
|
*/
|
||||||
export const updateGoal = async (goalId: string, goalData: UpdateGoalRequest): Promise<ApiResponse<Goal>> => {
|
export const updateGoal = async (goalId: string, goalData: UpdateGoalRequest): Promise<Goal> => {
|
||||||
return api.put<ApiResponse<Goal>>(`/goals/${goalId}`, goalData);
|
return api.put<Goal>(`/goals/${goalId}`, goalData);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -106,33 +106,6 @@ export const batchOperateGoals = async (operationData: BatchGoalOperationRequest
|
|||||||
return api.post<ApiResponse<BatchGoalOperationResult[]>>('/goals/batch', operationData);
|
return api.post<ApiResponse<BatchGoalOperationResult[]>>('/goals/batch', operationData);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* 暂停目标
|
|
||||||
*/
|
|
||||||
export const pauseGoal = async (goalId: string): Promise<ApiResponse<Goal>> => {
|
|
||||||
return updateGoal(goalId, { status: 'paused' });
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 恢复目标
|
|
||||||
*/
|
|
||||||
export const resumeGoal = async (goalId: string): Promise<ApiResponse<Goal>> => {
|
|
||||||
return updateGoal(goalId, { status: 'active' });
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 完成目标
|
|
||||||
*/
|
|
||||||
export const markGoalCompleted = async (goalId: string): Promise<ApiResponse<Goal>> => {
|
|
||||||
return updateGoal(goalId, { status: 'completed' });
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 取消目标
|
|
||||||
*/
|
|
||||||
export const cancelGoal = async (goalId: string): Promise<ApiResponse<Goal>> => {
|
|
||||||
return updateGoal(goalId, { status: 'cancelled' });
|
|
||||||
};
|
|
||||||
|
|
||||||
// 导出所有API方法
|
// 导出所有API方法
|
||||||
export const goalsApi = {
|
export const goalsApi = {
|
||||||
@@ -145,10 +118,6 @@ export const goalsApi = {
|
|||||||
getGoalCompletions,
|
getGoalCompletions,
|
||||||
getGoalStats,
|
getGoalStats,
|
||||||
batchOperateGoals,
|
batchOperateGoals,
|
||||||
pauseGoal,
|
|
||||||
resumeGoal,
|
|
||||||
markGoalCompleted,
|
|
||||||
cancelGoal,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default goalsApi;
|
export default goalsApi;
|
||||||
@@ -195,7 +195,7 @@ export const updateGoal = createAsyncThunk(
|
|||||||
async ({ goalId, goalData }: { goalId: string; goalData: UpdateGoalRequest }, { rejectWithValue }) => {
|
async ({ goalId, goalData }: { goalId: string; goalData: UpdateGoalRequest }, { rejectWithValue }) => {
|
||||||
try {
|
try {
|
||||||
const response = await goalsApi.updateGoal(goalId, goalData);
|
const response = await goalsApi.updateGoal(goalId, goalData);
|
||||||
return response.data;
|
return response;
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
return rejectWithValue(error.message || '更新目标失败');
|
return rejectWithValue(error.message || '更新目标失败');
|
||||||
}
|
}
|
||||||
@@ -457,10 +457,7 @@ const goalsSlice = createSlice({
|
|||||||
state.updateLoading = false;
|
state.updateLoading = false;
|
||||||
const updatedGoal = action.payload;
|
const updatedGoal = action.payload;
|
||||||
|
|
||||||
// 计算进度百分比
|
console.log('updateGoal.fulfilled', updatedGoal);
|
||||||
const progressPercentage = updatedGoal.targetCount && updatedGoal.targetCount > 0
|
|
||||||
? Math.round((updatedGoal.completedCount / updatedGoal.targetCount) * 100)
|
|
||||||
: 0;
|
|
||||||
|
|
||||||
// 更新目标列表中的目标
|
// 更新目标列表中的目标
|
||||||
const goalIndex = state.goals.findIndex(goal => goal.id === updatedGoal.id);
|
const goalIndex = state.goals.findIndex(goal => goal.id === updatedGoal.id);
|
||||||
@@ -468,7 +465,6 @@ const goalsSlice = createSlice({
|
|||||||
state.goals[goalIndex] = {
|
state.goals[goalIndex] = {
|
||||||
...state.goals[goalIndex],
|
...state.goals[goalIndex],
|
||||||
...updatedGoal,
|
...updatedGoal,
|
||||||
progressPercentage,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -477,7 +473,6 @@ const goalsSlice = createSlice({
|
|||||||
state.currentGoal = {
|
state.currentGoal = {
|
||||||
...state.currentGoal,
|
...state.currentGoal,
|
||||||
...updatedGoal,
|
...updatedGoal,
|
||||||
progressPercentage,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user