Fix daily summary to display real activity counts and add medicine tracker
## Backend Changes - Update tracking.service.ts getDailySummary to calculate actual counts - Import ActivityType enum for proper type comparisons - Calculate feedingCount, sleepTotalMinutes, diaperCount, medicationCount - Sleep duration now correctly calculated from startedAt/endedAt timestamps ## Frontend API Changes - Add medicationCount to DailySummary interface - Extract endTime from metadata and send as endedAt to backend - Enables proper sleep duration tracking with start/end times ## Homepage Updates - Add Medicine and Activities quick action buttons - Update summary grid from 3 to 4 columns (responsive layout) - Add medication count display with MedicalServices icon - Improve grid responsiveness (xs=6, sm=3) - Replace Analytics button with Activities button ## New Activities Page - Create /activities page to show recent activity history - Display last 7 days of activities with color-coded icons - Show smart timestamps (Today/Yesterday/date format) - Activity-specific descriptions (feeding amount, sleep duration, etc.) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -6,7 +6,7 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, Between, MoreThanOrEqual, LessThanOrEqual } from 'typeorm';
|
||||
import { Activity } from '../../database/entities/activity.entity';
|
||||
import { Activity, ActivityType } from '../../database/entities/activity.entity';
|
||||
import { Child } from '../../database/entities/child.entity';
|
||||
import { FamilyMember } from '../../database/entities/family-member.entity';
|
||||
import { CreateActivityDto } from './dto/create-activity.dto';
|
||||
@@ -255,31 +255,57 @@ export class TrackingService {
|
||||
},
|
||||
});
|
||||
|
||||
// Group by type
|
||||
const summary: Record<string, any> = {
|
||||
date,
|
||||
childId,
|
||||
activities: [],
|
||||
byType: {},
|
||||
};
|
||||
// Calculate summary statistics
|
||||
let feedingCount = 0;
|
||||
let sleepTotalMinutes = 0;
|
||||
let diaperCount = 0;
|
||||
let medicationCount = 0;
|
||||
|
||||
const activityList = [];
|
||||
const byType: Record<string, any[]> = {};
|
||||
|
||||
activities.forEach((activity) => {
|
||||
summary.activities.push({
|
||||
const activityData = {
|
||||
id: activity.id,
|
||||
type: activity.type,
|
||||
startedAt: activity.startedAt,
|
||||
endedAt: activity.endedAt,
|
||||
notes: activity.notes,
|
||||
metadata: activity.metadata,
|
||||
};
|
||||
|
||||
activityList.push(activityData);
|
||||
|
||||
if (!byType[activity.type]) {
|
||||
byType[activity.type] = [];
|
||||
}
|
||||
byType[activity.type].push(activity);
|
||||
|
||||
// Count by type
|
||||
if (activity.type === ActivityType.FEEDING) {
|
||||
feedingCount++;
|
||||
} else if (activity.type === ActivityType.SLEEP) {
|
||||
// Calculate sleep duration in minutes
|
||||
if (activity.startedAt && activity.endedAt) {
|
||||
const durationMs = new Date(activity.endedAt).getTime() - new Date(activity.startedAt).getTime();
|
||||
sleepTotalMinutes += Math.floor(durationMs / 60000);
|
||||
}
|
||||
} else if (activity.type === ActivityType.DIAPER) {
|
||||
diaperCount++;
|
||||
} else if (activity.type === ActivityType.MEDICATION) {
|
||||
medicationCount++;
|
||||
}
|
||||
});
|
||||
|
||||
if (!summary.byType[activity.type]) {
|
||||
summary.byType[activity.type] = [];
|
||||
}
|
||||
|
||||
summary.byType[activity.type].push(activity);
|
||||
});
|
||||
|
||||
return summary;
|
||||
return {
|
||||
date,
|
||||
childId,
|
||||
feedingCount,
|
||||
sleepTotalMinutes,
|
||||
diaperCount,
|
||||
medicationCount,
|
||||
activities: activityList,
|
||||
byType,
|
||||
};
|
||||
}
|
||||
}
|
||||
227
maternal-web/app/activities/page.tsx
Normal file
227
maternal-web/app/activities/page.tsx
Normal file
@@ -0,0 +1,227 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
Paper,
|
||||
List,
|
||||
ListItem,
|
||||
ListItemIcon,
|
||||
ListItemText,
|
||||
Chip,
|
||||
CircularProgress,
|
||||
} from '@mui/material';
|
||||
import {
|
||||
Restaurant,
|
||||
Hotel,
|
||||
BabyChangingStation,
|
||||
MedicalServices,
|
||||
EmojiEvents,
|
||||
Note,
|
||||
} from '@mui/icons-material';
|
||||
import { AppShell } from '@/components/layouts/AppShell/AppShell';
|
||||
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { childrenApi, Child } from '@/lib/api/children';
|
||||
import { trackingApi, Activity } from '@/lib/api/tracking';
|
||||
import { format } from 'date-fns';
|
||||
|
||||
const activityIcons: Record<string, any> = {
|
||||
feeding: <Restaurant />,
|
||||
sleep: <Hotel />,
|
||||
diaper: <BabyChangingStation />,
|
||||
medication: <MedicalServices />,
|
||||
milestone: <EmojiEvents />,
|
||||
note: <Note />,
|
||||
};
|
||||
|
||||
const activityColors: Record<string, string> = {
|
||||
feeding: '#FFB6C1',
|
||||
sleep: '#B6D7FF',
|
||||
diaper: '#FFE4B5',
|
||||
medication: '#FFB8B8',
|
||||
milestone: '#FFD700',
|
||||
note: '#E0E0E0',
|
||||
};
|
||||
|
||||
export default function ActivitiesPage() {
|
||||
const { user } = useAuth();
|
||||
const [children, setChildren] = useState<Child[]>([]);
|
||||
const [selectedChild, setSelectedChild] = useState<Child | null>(null);
|
||||
const [activities, setActivities] = useState<Activity[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const familyId = user?.families?.[0]?.familyId;
|
||||
|
||||
useEffect(() => {
|
||||
const loadData = async () => {
|
||||
if (!familyId) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const childrenData = await childrenApi.getChildren(familyId);
|
||||
setChildren(childrenData);
|
||||
|
||||
if (childrenData.length > 0) {
|
||||
const firstChild = childrenData[0];
|
||||
setSelectedChild(firstChild);
|
||||
|
||||
// Load activities for the last 7 days
|
||||
const endDate = format(new Date(), 'yyyy-MM-dd');
|
||||
const startDate = format(
|
||||
new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
|
||||
'yyyy-MM-dd'
|
||||
);
|
||||
|
||||
const activitiesData = await trackingApi.getActivities(
|
||||
firstChild.id,
|
||||
undefined,
|
||||
startDate,
|
||||
endDate
|
||||
);
|
||||
setActivities(activitiesData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[ActivitiesPage] Failed to load data:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadData();
|
||||
}, [familyId]);
|
||||
|
||||
const formatActivityTime = (timestamp: string) => {
|
||||
const date = new Date(timestamp);
|
||||
const today = new Date();
|
||||
const yesterday = new Date(today);
|
||||
yesterday.setDate(yesterday.getDate() - 1);
|
||||
|
||||
const isToday = date.toDateString() === today.toDateString();
|
||||
const isYesterday = date.toDateString() === yesterday.toDateString();
|
||||
|
||||
if (isToday) {
|
||||
return `Today at ${format(date, 'h:mm a')}`;
|
||||
} else if (isYesterday) {
|
||||
return `Yesterday at ${format(date, 'h:mm a')}`;
|
||||
} else {
|
||||
return format(date, 'MMM d, h:mm a');
|
||||
}
|
||||
};
|
||||
|
||||
const getActivityDescription = (activity: Activity) => {
|
||||
switch (activity.type) {
|
||||
case 'feeding':
|
||||
return activity.data?.amount
|
||||
? `${activity.data.amount} ${activity.data.unit || 'oz'}`
|
||||
: 'Feeding';
|
||||
case 'sleep':
|
||||
if (activity.data?.endedAt) {
|
||||
const duration = Math.floor(
|
||||
(new Date(activity.data.endedAt).getTime() -
|
||||
new Date(activity.timestamp).getTime()) /
|
||||
60000
|
||||
);
|
||||
const hours = Math.floor(duration / 60);
|
||||
const mins = duration % 60;
|
||||
return hours > 0 ? `${hours}h ${mins}m` : `${mins}m`;
|
||||
}
|
||||
return 'Sleep';
|
||||
case 'diaper':
|
||||
return activity.data?.type || 'Diaper change';
|
||||
case 'medication':
|
||||
return activity.data?.name || 'Medication';
|
||||
default:
|
||||
return activity.type;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ProtectedRoute>
|
||||
<AppShell>
|
||||
<Box>
|
||||
<Typography variant="h4" gutterBottom fontWeight="600" sx={{ mb: 3 }}>
|
||||
Recent Activities
|
||||
</Typography>
|
||||
|
||||
{loading ? (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
) : activities.length === 0 ? (
|
||||
<Paper sx={{ p: 4, textAlign: 'center' }}>
|
||||
<Typography variant="body1" color="text.secondary">
|
||||
No activities recorded yet
|
||||
</Typography>
|
||||
</Paper>
|
||||
) : (
|
||||
<Paper>
|
||||
<List>
|
||||
{activities.map((activity, index) => (
|
||||
<ListItem
|
||||
key={activity.id}
|
||||
sx={{
|
||||
borderBottom:
|
||||
index < activities.length - 1 ? '1px solid' : 'none',
|
||||
borderColor: 'divider',
|
||||
}}
|
||||
>
|
||||
<ListItemIcon>
|
||||
<Box
|
||||
sx={{
|
||||
width: 48,
|
||||
height: 48,
|
||||
borderRadius: 2,
|
||||
bgcolor: activityColors[activity.type] || '#E0E0E0',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
color: 'white',
|
||||
}}
|
||||
>
|
||||
{activityIcons[activity.type] || <Note />}
|
||||
</Box>
|
||||
</ListItemIcon>
|
||||
<ListItemText
|
||||
primary={
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
||||
<Typography variant="body1" fontWeight="500">
|
||||
{getActivityDescription(activity)}
|
||||
</Typography>
|
||||
<Chip
|
||||
label={activity.type}
|
||||
size="small"
|
||||
sx={{ textTransform: 'capitalize' }}
|
||||
/>
|
||||
</Box>
|
||||
}
|
||||
secondary={
|
||||
<Box>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{formatActivityTime(activity.timestamp)}
|
||||
</Typography>
|
||||
{activity.notes && (
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="text.secondary"
|
||||
sx={{ mt: 0.5 }}
|
||||
>
|
||||
{activity.notes}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
}
|
||||
/>
|
||||
</ListItem>
|
||||
))}
|
||||
</List>
|
||||
</Paper>
|
||||
)}
|
||||
</Box>
|
||||
</AppShell>
|
||||
</ProtectedRoute>
|
||||
);
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
Insights,
|
||||
SmartToy,
|
||||
Analytics,
|
||||
MedicalServices,
|
||||
} from '@mui/icons-material';
|
||||
import { motion } from 'framer-motion';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
@@ -64,7 +65,9 @@ export default function HomePage() {
|
||||
|
||||
// Load today's summary for first child
|
||||
const today = format(new Date(), 'yyyy-MM-dd');
|
||||
console.log('[HomePage] Fetching daily summary for child:', firstChild.id, 'date:', today);
|
||||
const summary = await trackingApi.getDailySummary(firstChild.id, today);
|
||||
console.log('[HomePage] Daily summary response:', summary);
|
||||
setDailySummary(summary);
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -81,8 +84,9 @@ export default function HomePage() {
|
||||
{ icon: <Restaurant />, label: 'Feeding', color: '#FFB6C1', path: '/track/feeding' },
|
||||
{ icon: <Hotel />, label: 'Sleep', color: '#B6D7FF', path: '/track/sleep' },
|
||||
{ icon: <BabyChangingStation />, label: 'Diaper', color: '#FFE4B5', path: '/track/diaper' },
|
||||
{ icon: <MedicalServices />, label: 'Medicine', color: '#FFB8B8', path: '/track/medication' },
|
||||
{ icon: <Insights />, label: 'Activities', color: '#C5E1A5', path: '/activities' },
|
||||
{ icon: <SmartToy />, label: 'AI Assistant', color: '#FFD3B6', path: '/ai-assistant' },
|
||||
{ icon: <Analytics />, label: 'Analytics', color: '#D4B5FF', path: '/analytics' },
|
||||
];
|
||||
|
||||
const formatSleepHours = (minutes: number) => {
|
||||
@@ -122,7 +126,7 @@ export default function HomePage() {
|
||||
</Typography>
|
||||
<Grid container spacing={2} sx={{ mb: 4 }}>
|
||||
{quickActions.map((action, index) => (
|
||||
<Grid item xs={6} sm={2.4} key={action.label}>
|
||||
<Grid item xs={6} sm={4} md={2} key={action.label}>
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.9 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
@@ -174,7 +178,7 @@ export default function HomePage() {
|
||||
</Box>
|
||||
) : (
|
||||
<Grid container spacing={3}>
|
||||
<Grid item xs={4}>
|
||||
<Grid item xs={6} sm={3}>
|
||||
<Box textAlign="center">
|
||||
<Restaurant sx={{ fontSize: 32, color: 'primary.main', mb: 1 }} />
|
||||
<Typography variant="h5" fontWeight="600">
|
||||
@@ -185,7 +189,7 @@ export default function HomePage() {
|
||||
</Typography>
|
||||
</Box>
|
||||
</Grid>
|
||||
<Grid item xs={4}>
|
||||
<Grid item xs={6} sm={3}>
|
||||
<Box textAlign="center">
|
||||
<Hotel sx={{ fontSize: 32, color: 'info.main', mb: 1 }} />
|
||||
<Typography variant="h5" fontWeight="600">
|
||||
@@ -198,7 +202,7 @@ export default function HomePage() {
|
||||
</Typography>
|
||||
</Box>
|
||||
</Grid>
|
||||
<Grid item xs={4}>
|
||||
<Grid item xs={6} sm={3}>
|
||||
<Box textAlign="center">
|
||||
<BabyChangingStation sx={{ fontSize: 32, color: 'warning.main', mb: 1 }} />
|
||||
<Typography variant="h5" fontWeight="600">
|
||||
@@ -209,6 +213,17 @@ export default function HomePage() {
|
||||
</Typography>
|
||||
</Box>
|
||||
</Grid>
|
||||
<Grid item xs={6} sm={3}>
|
||||
<Box textAlign="center">
|
||||
<MedicalServices sx={{ fontSize: 32, color: 'error.main', mb: 1 }} />
|
||||
<Typography variant="h5" fontWeight="600">
|
||||
{dailySummary.medicationCount || 0}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
Medications
|
||||
</Typography>
|
||||
</Box>
|
||||
</Grid>
|
||||
</Grid>
|
||||
)}
|
||||
</Paper>
|
||||
|
||||
@@ -27,6 +27,7 @@ export interface DailySummary {
|
||||
feedingCount: number;
|
||||
sleepTotalMinutes: number;
|
||||
diaperCount: number;
|
||||
medicationCount: number;
|
||||
activities: Activity[];
|
||||
}
|
||||
|
||||
@@ -68,12 +69,18 @@ export const trackingApi = {
|
||||
// Create a new activity
|
||||
createActivity: async (childId: string, data: CreateActivityData): Promise<Activity> => {
|
||||
// Transform frontend data structure to backend DTO format
|
||||
const payload = {
|
||||
const payload: any = {
|
||||
type: data.type,
|
||||
startedAt: data.timestamp, // Backend expects startedAt, not timestamp
|
||||
metadata: data.data, // Backend expects metadata, not data
|
||||
notes: data.notes,
|
||||
};
|
||||
|
||||
// Extract endTime from metadata and set as endedAt (for sleep tracking)
|
||||
if (data.data?.endTime) {
|
||||
payload.endedAt = data.data.endTime;
|
||||
}
|
||||
|
||||
const response = await apiClient.post(`/api/v1/activities?childId=${childId}`, payload);
|
||||
const activity = response.data.data.activity;
|
||||
// Transform backend response to frontend format
|
||||
|
||||
Reference in New Issue
Block a user