Files
maternal-app/maternal-web/app/page.tsx
Andrei 788be7cd32
Some checks failed
CI/CD Pipeline / Lint and Test (push) Has been cancelled
CI/CD Pipeline / E2E Tests (push) Has been cancelled
CI/CD Pipeline / Build Application (push) Has been cancelled
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>
2025-10-02 14:46:18 +00:00

253 lines
9.7 KiB
TypeScript

'use client';
import { useState, useEffect } from 'react';
import { Box, Typography, Button, Paper, Grid, CircularProgress } from '@mui/material';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import { EmailVerificationBanner } from '@/components/common/EmailVerificationBanner';
import { ErrorBoundary } from '@/components/common/ErrorBoundary';
import { DataErrorFallback } from '@/components/common/ErrorFallbacks';
import { NetworkStatusIndicator } from '@/components/common/NetworkStatusIndicator';
import { StatGridSkeleton } from '@/components/common/LoadingSkeletons';
import {
Restaurant,
Hotel,
BabyChangingStation,
Insights,
SmartToy,
Analytics,
MedicalServices,
} from '@mui/icons-material';
import { motion } from 'framer-motion';
import { useAuth } from '@/lib/auth/AuthContext';
import { useRouter } from 'next/navigation';
import { trackingApi, DailySummary } from '@/lib/api/tracking';
import { childrenApi, Child } from '@/lib/api/children';
import { format } from 'date-fns';
export default function HomePage() {
const { user, isLoading: authLoading } = useAuth();
const router = useRouter();
const [children, setChildren] = useState<Child[]>([]);
const [selectedChild, setSelectedChild] = useState<Child | null>(null);
const [dailySummary, setDailySummary] = useState<DailySummary | null>(null);
const [loading, setLoading] = useState(true);
const familyId = user?.families?.[0]?.familyId;
// Load children and daily summary
useEffect(() => {
const loadData = async () => {
// Wait for auth to complete before trying to load data
if (authLoading) {
return;
}
if (!familyId) {
console.log('[HomePage] No familyId found');
console.log('[HomePage] User object:', JSON.stringify(user, null, 2));
console.log('[HomePage] User.families:', user?.families);
setLoading(false);
return;
}
console.log('[HomePage] Loading data for familyId:', familyId);
try {
// Load children
const childrenData = await childrenApi.getChildren(familyId);
console.log('[HomePage] Children loaded:', childrenData.length);
setChildren(childrenData);
if (childrenData.length > 0) {
const firstChild = childrenData[0];
setSelectedChild(firstChild);
// 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) {
console.error('[HomePage] Failed to load data:', error);
} finally {
setLoading(false);
}
};
loadData();
}, [familyId, authLoading, user]);
const quickActions = [
{ 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' },
];
const formatSleepHours = (minutes: number) => {
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
if (hours > 0 && mins > 0) {
return `${hours}h ${mins}m`;
} else if (hours > 0) {
return `${hours}h`;
} else {
return `${mins}m`;
}
};
return (
<ProtectedRoute>
<AppShell>
<NetworkStatusIndicator />
<Box>
<EmailVerificationBanner />
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
>
<Typography variant="h4" gutterBottom fontWeight="600" sx={{ mb: 1 }}>
Welcome Back{user?.name ? `, ${user.name}` : ''}! 👋
</Typography>
<Typography variant="body1" color="text.secondary" sx={{ mb: 4 }}>
Track your child's activities and get AI-powered insights
</Typography>
{/* Quick Actions */}
<Typography variant="h6" gutterBottom fontWeight="600" sx={{ mb: 2 }}>
Quick Actions
</Typography>
<Grid container spacing={2} sx={{ mb: 4 }}>
{quickActions.map((action, index) => (
<Grid item xs={6} sm={4} md={2} key={action.label}>
<motion.div
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3, delay: index * 0.1 }}
>
<Paper
onClick={() => router.push(action.path)}
sx={{
p: 3,
textAlign: 'center',
cursor: 'pointer',
bgcolor: action.color,
color: 'white',
transition: 'transform 0.2s',
'&:hover': {
transform: 'scale(1.05)',
},
}}
>
<Box sx={{ fontSize: 48, mb: 1 }}>{action.icon}</Box>
<Typography variant="body1" fontWeight="600">
{action.label}
</Typography>
</Paper>
</motion.div>
</Grid>
))}
</Grid>
{/* Today's Summary */}
<Typography variant="h6" gutterBottom fontWeight="600" sx={{ mb: 2 }}>
Today's Summary{selectedChild ? ` - ${selectedChild.name}` : ''}
</Typography>
<ErrorBoundary
isolate
fallback={<DataErrorFallback error={new Error('Failed to load summary')} />}
>
{loading ? (
<StatGridSkeleton count={3} />
) : (
<Paper sx={{ p: 3 }}>
{!dailySummary ? (
<Box sx={{ textAlign: 'center', py: 4 }}>
<Typography variant="body2" color="text.secondary">
{children.length === 0
? 'Add a child to start tracking'
: 'No activities tracked today'}
</Typography>
</Box>
) : (
<Grid container spacing={3}>
<Grid item xs={6} sm={3}>
<Box textAlign="center">
<Restaurant sx={{ fontSize: 32, color: 'primary.main', mb: 1 }} />
<Typography variant="h5" fontWeight="600">
{dailySummary.feedingCount || 0}
</Typography>
<Typography variant="body2" color="text.secondary">
Feedings
</Typography>
</Box>
</Grid>
<Grid item xs={6} sm={3}>
<Box textAlign="center">
<Hotel sx={{ fontSize: 32, color: 'info.main', mb: 1 }} />
<Typography variant="h5" fontWeight="600">
{dailySummary.sleepTotalMinutes
? formatSleepHours(dailySummary.sleepTotalMinutes)
: '0m'}
</Typography>
<Typography variant="body2" color="text.secondary">
Sleep
</Typography>
</Box>
</Grid>
<Grid item xs={6} sm={3}>
<Box textAlign="center">
<BabyChangingStation sx={{ fontSize: 32, color: 'warning.main', mb: 1 }} />
<Typography variant="h5" fontWeight="600">
{dailySummary.diaperCount || 0}
</Typography>
<Typography variant="body2" color="text.secondary">
Diapers
</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>
)}
</ErrorBoundary>
{/* Next Predicted Activity */}
<Box sx={{ mt: 4 }}>
<Paper sx={{ p: 3, bgcolor: 'primary.light' }}>
<Typography variant="body2" color="text.secondary" gutterBottom>
Next Predicted Activity
</Typography>
<Typography variant="h6" fontWeight="600" gutterBottom>
Nap time in 45 minutes
</Typography>
<Typography variant="body2" color="text.secondary">
Based on your child's sleep patterns
</Typography>
</Paper>
</Box>
</motion.div>
</Box>
</AppShell>
</ProtectedRoute>
);
}