docs: Add comprehensive multi-child implementation plan
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

Added detailed implementation plan covering:
- Frontend: Dynamic UI, child selector, bulk activity logging, comparison analytics
- Backend: Bulk operations, multi-child queries, family statistics
- AI/Voice: Child name detection, context building, clarification flows
- Database: Schema enhancements, user preferences, bulk operation tracking
- State management, API enhancements, real-time sync updates
- Testing strategy: Unit, integration, and E2E tests
- Migration plan with feature flags for phased rollout
- Performance optimizations: Caching, indexes, code splitting

Also includes:
- Security fixes for multi-family data leakage in analytics pages
- ParentFlow branding updates
- Activity tracking navigation improvements
- Backend DTO and error handling fixes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-10-04 21:05:14 +00:00
parent f854fe6fcd
commit 95ef0e5e78
12 changed files with 2778 additions and 321 deletions

View File

@@ -0,0 +1,244 @@
# Multi-Child Support Implementation Guide
## Overview
Implementation specifications for supporting multiple children in the maternal organization app with dynamic UI adaptation based on the number of children registered.
---
## Core Rules Implementation
### Rule 1: Dynamic Dashboard View (1-3 vs 3+ children)
**For 1-3 Children - Tab Implementation:**
- Display horizontal tabs at the top of the dashboard
- Each tab shows one child's name
- Add an "All" tab at the end to view combined summary
- Active tab should be visually distinct (use primary color from Design System)
- Tab transitions should be smooth and instantaneous
- Selected tab state must persist during app session
**For 3+ Children - Stacked Cards Implementation:**
- Display vertically scrollable cards
- Each card represents one child
- Cards should show compact summary (key metrics only)
- Include child's name and age on each card
- Add visual separation between cards (8px spacing)
- Implement pull-to-refresh for updating all cards
### Rule 2: Global Child Selector
**Implementation Requirements:**
- Add dropdown selector to app header (below navigation bar)
- Only display when family has 2+ children
- Show currently selected child(ren) name(s)
- Dropdown options must include:
- Individual child names with profile photos (if available)
- "All Children" option
- Visual indicator for currently selected
- Selector state must persist across all screens
- Update all displayed data when selection changes
---
## Screen-by-Screen Updates
### Dashboard Screen
- Implement view mode detection based on children count
- Add child selector if 2+ children
- Update summary calculations based on selected child(ren)
- For "All" selection, show aggregated statistics
- Ensure real-time sync updates correct child's data
### Activity Logging Screens
- Add child selection step before logging
- Default to last active child
- Allow bulk logging for multiple children (e.g., "both kids napping")
- Update confirmation messages to include child name(s)
- Store child association with each activity
### AI Assistant Screen
- Modify context building to include selected child's data
- Update prompts to specify which child when asking questions
- Allow questions about multiple children comparisons
- Include child name in AI responses for clarity
### Analytics Screen
- Add "Comparison" tab as specified in Rule 4
- Update all charts to filter by selected child(ren)
- Implement side-by-side view for comparing 2 children
- Add legend when showing multiple children's data
- Export reports should specify which child(ren) included
---
## Rule 3: Analytics Comparison Tab
### Comparison View Requirements
- Add new tab in Analytics section labeled "Compare"
- Only show when 2+ children registered
- Default to comparing all children
- Implement following comparison metrics:
- Sleep patterns overlay chart
- Feeding frequency comparison
- Growth curves on same graph
- Development milestones timeline
- Activity patterns heatmap
### Comparison Controls
- Add date range selector (default: last 7 days)
- Include child selector checkboxes
- Implement metric selector (choose what to compare)
- Add export functionality for comparison reports
- Use different colors per child (from a predefined palette)
---
## Rule 4: Voice Command Multi-Child Handling
### Voice Processing Updates
**Child Detection Logic:**
1. Parse voice input for child names
2. If child name detected, associate with that child
3. If no child name detected:
- For single child families: auto-select
- For multi-child families: prompt for selection
4. Support keywords: "both", "all kids", "everyone"
**Clarification Prompts:**
- "Which child is this for?"
- "Did you mean [Child Name]?"
- "Should I log this for all children?"
- Display child selector with voice feedback
- Allow voice response for selection
**Natural Language Patterns to Support:**
- "[Child name] just [activity]"
- "Both kids are [activity]"
- "Log feeding for [child name]"
- "All children went to bed"
- "The twins are napping"
---
## State Management Updates
### Redux Store Modifications
**UI Slice Updates:**
- Add active children IDs array (supports multi-select)
- Store default child ID for quick actions
- Add view mode preference (tabs vs cards)
- Cache last selected child per screen
- Store comparison view preferences
**Activities Slice Updates:**
- Index activities by child ID
- Support filtering by multiple children
- Add bulk operation support
- Update sync to handle multi-child selections
**Analytics Slice Updates:**
- Cache calculations per child
- Store comparison configurations
- Add aggregation logic for "all children" view
---
## API Updates
### Endpoint Modifications
**Activity Endpoints:**
- Accept child_id array for bulk operations
- Return child-specific data in responses
- Support filtering by multiple children
- Add comparison-specific endpoints
**Analytics Endpoints:**
- Add comparison query parameters
- Support multi-child aggregations
- Return child-separated statistics
- Include child identifiers in all responses
### WebSocket Updates
- Include child ID in all real-time events
- Support room-per-child architecture
- Emit updates only for selected children
- Handle bulk activity broadcasts
---
## Database Updates
### Schema Modifications
- Ensure all activity tables include child_id foreign key
- Add indexes on child_id for performance
- Create views for multi-child aggregations
- Add comparison preferences table
### Query Optimizations
- Implement efficient multi-child queries
- Add database functions for aggregations
- Optimize for common comparison queries
- Cache frequently accessed combinations
---
## Testing Requirements
### Unit Tests
- Test view mode selection logic
- Verify child selector state management
- Test voice command child detection
- Validate aggregation calculations
### Integration Tests
- Test multi-child activity logging flow
- Verify real-time sync for multiple children
- Test comparison view data accuracy
- Validate API filtering with multiple children
### E2E Tests
- Complete flow for 2-child family
- Complete flow for 4+ child family
- Voice command with child selection
- Analytics comparison interactions
---
## Migration Plan
### For Existing Users
1. Detect single-child accounts
2. Hide multi-child features initially
3. Enable features when second child added
4. Preserve all existing data associations
5. Default existing activities to first child
### UI Migration
1. Add child selector component globally
2. Update dashboard based on child count
3. Add comparison tab to analytics
4. Update all logging flows
5. Modify voice processing pipeline
---
## Performance Considerations
- Lazy load child data as needed
- Cache per-child calculations
- Implement virtual scrolling for many children
- Optimize database queries for multi-child filters
- Throttle real-time updates when showing multiple children
---
## Accessibility Updates
- Ensure child selector is screen-reader friendly
- Add voice announcements for child selection
- Label all charts with child names
- Support keyboard navigation for tabs
- Provide text alternatives for comparison visualizations

File diff suppressed because it is too large Load Diff

View File

@@ -10,6 +10,7 @@ import {
HttpCode, HttpCode,
HttpStatus, HttpStatus,
Query, Query,
BadRequestException,
} from '@nestjs/common'; } from '@nestjs/common';
import { ChildrenService } from './children.service'; import { ChildrenService } from './children.service';
import { CreateChildDto } from './dto/create-child.dto'; import { CreateChildDto } from './dto/create-child.dto';
@@ -30,13 +31,7 @@ export class ChildrenController {
@Body() createChildDto: CreateChildDto, @Body() createChildDto: CreateChildDto,
) { ) {
if (!familyId) { if (!familyId) {
return { throw new BadRequestException('familyId query parameter is required');
success: false,
error: {
code: 'VALIDATION_ERROR',
message: 'familyId query parameter is required',
},
};
} }
const child = await this.childrenService.create( const child = await this.childrenService.create(
@@ -55,6 +50,7 @@ export class ChildrenController {
birthDate: child.birthDate, birthDate: child.birthDate,
gender: child.gender, gender: child.gender,
photoUrl: child.photoUrl, photoUrl: child.photoUrl,
photoAlt: child.photoAlt,
medicalInfo: child.medicalInfo, medicalInfo: child.medicalInfo,
createdAt: child.createdAt, createdAt: child.createdAt,
}, },
@@ -85,6 +81,7 @@ export class ChildrenController {
birthDate: child.birthDate, birthDate: child.birthDate,
gender: child.gender, gender: child.gender,
photoUrl: child.photoUrl, photoUrl: child.photoUrl,
photoAlt: child.photoAlt,
medicalInfo: child.medicalInfo, medicalInfo: child.medicalInfo,
createdAt: child.createdAt, createdAt: child.createdAt,
})), })),
@@ -107,6 +104,7 @@ export class ChildrenController {
birthDate: child.birthDate, birthDate: child.birthDate,
gender: child.gender, gender: child.gender,
photoUrl: child.photoUrl, photoUrl: child.photoUrl,
photoAlt: child.photoAlt,
medicalInfo: child.medicalInfo, medicalInfo: child.medicalInfo,
createdAt: child.createdAt, createdAt: child.createdAt,
}, },
@@ -152,6 +150,7 @@ export class ChildrenController {
birthDate: child.birthDate, birthDate: child.birthDate,
gender: child.gender, gender: child.gender,
photoUrl: child.photoUrl, photoUrl: child.photoUrl,
photoAlt: child.photoAlt,
medicalInfo: child.medicalInfo, medicalInfo: child.medicalInfo,
createdAt: child.createdAt, createdAt: child.createdAt,
}, },

View File

@@ -32,6 +32,10 @@ export class CreateChildDto {
@IsString() @IsString()
photoUrl?: string; photoUrl?: string;
@IsOptional()
@IsString()
photoAlt?: string;
@IsOptional() @IsOptional()
@IsObject() @IsObject()
medicalInfo?: Record<string, any>; medicalInfo?: Record<string, any>;

View File

@@ -23,6 +23,9 @@ import {
FormControlLabel, FormControlLabel,
FormControl, FormControl,
Grid, Grid,
StepConnector,
stepConnectorClasses,
styled,
} from '@mui/material'; } from '@mui/material';
import { ArrowBack, ArrowForward, Check, Language, Straighten } from '@mui/icons-material'; import { ArrowBack, ArrowForward, Check, Language, Straighten } from '@mui/icons-material';
import { motion, AnimatePresence } from 'framer-motion'; import { motion, AnimatePresence } from 'framer-motion';
@@ -33,9 +36,60 @@ import { useLocale, MeasurementSystem } from '@/hooks/useLocale';
import { useTranslation } from '@/hooks/useTranslation'; import { useTranslation } from '@/hooks/useTranslation';
import { supportedLanguages } from '@/lib/i18n/config'; import { supportedLanguages } from '@/lib/i18n/config';
import { usersApi } from '@/lib/api/users'; import { usersApi } from '@/lib/api/users';
import { useTheme } from '@mui/material/styles';
import { StepIconProps } from '@mui/material/StepIcon';
const steps = ['Welcome', 'Language', 'Measurements', 'Add Child', 'Complete']; const steps = ['Welcome', 'Language', 'Measurements', 'Add Child', 'Complete'];
// Custom connector for mobile-friendly stepper
const CustomConnector = styled(StepConnector)(({ theme }) => ({
[`&.${stepConnectorClasses.active}`]: {
[`& .${stepConnectorClasses.line}`]: {
borderColor: theme.palette.primary.main,
},
},
[`&.${stepConnectorClasses.completed}`]: {
[`& .${stepConnectorClasses.line}`]: {
borderColor: theme.palette.primary.main,
},
},
[`& .${stepConnectorClasses.line}`]: {
borderColor: theme.palette.divider,
borderTopWidth: 2,
borderRadius: 1,
},
}));
// Custom step icon showing numbers
const CustomStepIconRoot = styled('div')<{ ownerState: { active?: boolean; completed?: boolean } }>(
({ theme, ownerState }) => ({
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: 32,
height: 32,
borderRadius: '50%',
backgroundColor: ownerState.completed
? theme.palette.primary.main
: ownerState.active
? theme.palette.primary.main
: theme.palette.grey[300],
color: ownerState.active || ownerState.completed ? '#fff' : theme.palette.text.secondary,
fontWeight: 600,
fontSize: '0.875rem',
})
);
function CustomStepIcon(props: StepIconProps) {
const { active, completed, icon } = props;
return (
<CustomStepIconRoot ownerState={{ active, completed }}>
{completed ? <Check sx={{ fontSize: 18 }} /> : icon}
</CustomStepIconRoot>
);
}
export default function OnboardingPage() { export default function OnboardingPage() {
const [activeStep, setActiveStep] = useState(0); const [activeStep, setActiveStep] = useState(0);
const [selectedLanguage, setSelectedLanguage] = useState('en'); const [selectedLanguage, setSelectedLanguage] = useState('en');
@@ -49,6 +103,7 @@ export default function OnboardingPage() {
const { user, refreshUser } = useAuth(); const { user, refreshUser } = useAuth();
const { setLanguage, setMeasurementSystem } = useLocale(); const { setLanguage, setMeasurementSystem } = useLocale();
const { t } = useTranslation('onboarding'); const { t } = useTranslation('onboarding');
const theme = useTheme();
const handleNext = async () => { const handleNext = async () => {
setError(''); setError('');
@@ -154,7 +209,7 @@ export default function OnboardingPage() {
flexDirection: 'column', flexDirection: 'column',
px: 3, px: 3,
py: 4, py: 4,
background: 'linear-gradient(135deg, #FFE4E1 0%, #FFDAB9 100%)', background: `linear-gradient(135deg, ${theme.palette.primary.light} 0%, ${theme.palette.secondary.light} 100%)`,
}} }}
> >
<Paper <Paper
@@ -163,13 +218,18 @@ export default function OnboardingPage() {
maxWidth: 600, maxWidth: 600,
mx: 'auto', mx: 'auto',
width: '100%', width: '100%',
p: 4, p: { xs: 3, sm: 4 },
borderRadius: 4, borderRadius: 4,
background: 'rgba(255, 255, 255, 0.95)', background: 'rgba(255, 255, 255, 0.95)',
backdropFilter: 'blur(10px)', backdropFilter: 'blur(10px)',
}} }}
> >
<Stepper activeStep={activeStep} sx={{ mb: 4 }}> <Stepper
activeStep={activeStep}
alternativeLabel
connector={<CustomConnector />}
sx={{ mb: 4 }}
>
{steps.map((label, index) => { {steps.map((label, index) => {
let stepLabel = label; let stepLabel = label;
if (index === 0) stepLabel = t('welcome.title').split('!')[0]; if (index === 0) stepLabel = t('welcome.title').split('!')[0];
@@ -178,9 +238,23 @@ export default function OnboardingPage() {
else if (index === 3) stepLabel = t('child.title'); else if (index === 3) stepLabel = t('child.title');
else if (index === 4) stepLabel = t('complete.title').split('!')[0]; else if (index === 4) stepLabel = t('complete.title').split('!')[0];
// Only show label for active step on mobile
const showLabel = activeStep === index;
return ( return (
<Step key={label}> <Step key={label}>
<StepLabel>{stepLabel}</StepLabel> <StepLabel
StepIconComponent={CustomStepIcon}
sx={{
'& .MuiStepLabel-label': {
display: { xs: showLabel ? 'block' : 'none', sm: 'block' },
mt: 1,
fontSize: { xs: '0.75rem', sm: '0.875rem' },
},
}}
>
{stepLabel}
</StepLabel>
</Step> </Step>
); );
})} })}

View File

@@ -1,276 +0,0 @@
'use client';
import { useState, useEffect, useCallback } from 'react';
import {
Box,
Typography,
Paper,
List,
ListItem,
ListItemIcon,
ListItemText,
Chip,
CircularProgress,
Snackbar,
Alert,
} 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 { useLocalizedDate } from '@/hooks/useLocalizedDate';
import { useRealTimeActivities } from '@/hooks/useWebSocket';
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 { format } = useLocalizedDate();
const [children, setChildren] = useState<Child[]>([]);
const [selectedChild, setSelectedChild] = useState<Child | null>(null);
const [activities, setActivities] = useState<Activity[]>([]);
const [loading, setLoading] = useState(true);
const [notification, setNotification] = useState<string | null>(null);
const familyId = user?.families?.[0]?.familyId;
// Real-time activity handlers
const handleActivityCreated = useCallback((activity: Activity) => {
console.log('[ActivitiesPage] Real-time activity created:', activity);
setActivities((prev) => [activity, ...prev]);
setNotification('New activity added by family member');
}, []);
const handleActivityUpdated = useCallback((activity: Activity) => {
console.log('[ActivitiesPage] Real-time activity updated:', activity);
setActivities((prev) =>
prev.map((a) => (a.id === activity.id ? activity : a))
);
setNotification('Activity updated by family member');
}, []);
const handleActivityDeleted = useCallback((data: { activityId: string }) => {
console.log('[ActivitiesPage] Real-time activity deleted:', data);
setActivities((prev) => prev.filter((a) => a.id !== data.activityId));
setNotification('Activity deleted by family member');
}, []);
// Subscribe to real-time updates
useRealTimeActivities(
handleActivityCreated,
handleActivityUpdated,
handleActivityDeleted
);
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" component="h1" 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>
{/* Real-time update notification */}
<Snackbar
open={!!notification}
autoHideDuration={3000}
onClose={() => setNotification(null)}
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
>
<Alert
onClose={() => setNotification(null)}
severity="info"
sx={{ width: '100%' }}
>
{notification}
</Alert>
</Snackbar>
</AppShell>
</ProtectedRoute>
);
}

View File

@@ -40,6 +40,7 @@ import PredictionsCard from '@/components/features/analytics/PredictionsCard';
import GrowthSpurtAlert from '@/components/features/analytics/GrowthSpurtAlert'; import GrowthSpurtAlert from '@/components/features/analytics/GrowthSpurtAlert';
import WeeklyReportCard from '@/components/features/analytics/WeeklyReportCard'; import WeeklyReportCard from '@/components/features/analytics/WeeklyReportCard';
import MonthlyReportCard from '@/components/features/analytics/MonthlyReportCard'; import MonthlyReportCard from '@/components/features/analytics/MonthlyReportCard';
import { useAuth } from '@/lib/auth/AuthContext';
interface TabPanelProps { interface TabPanelProps {
children?: React.ReactNode; children?: React.ReactNode;
@@ -65,6 +66,7 @@ function TabPanel(props: TabPanelProps) {
export default function AnalyticsPage() { export default function AnalyticsPage() {
const theme = useTheme(); const theme = useTheme();
const { user } = useAuth();
const [children, setChildren] = useState<Child[]>([]); const [children, setChildren] = useState<Child[]>([]);
const [selectedChildId, setSelectedChildId] = useState<string>(''); const [selectedChildId, setSelectedChildId] = useState<string>('');
const [tabValue, setTabValue] = useState(0); const [tabValue, setTabValue] = useState(0);
@@ -74,27 +76,54 @@ export default function AnalyticsPage() {
const [insightsLoading, setInsightsLoading] = useState(false); const [insightsLoading, setInsightsLoading] = useState(false);
const [predictionsLoading, setPredictionsLoading] = useState(false); const [predictionsLoading, setPredictionsLoading] = useState(false);
const [days, setDays] = useState<number>(7); const [days, setDays] = useState<number>(7);
const [error, setError] = useState<string>('');
const familyId = user?.families?.[0]?.familyId;
useEffect(() => { useEffect(() => {
loadChildren(); if (familyId) {
}, []); loadChildren();
useEffect(() => {
if (selectedChildId) {
loadInsights();
loadPredictions();
} }
}, [selectedChildId, days]); }, [familyId]);
useEffect(() => {
if (selectedChildId && children.length > 0) {
// Validate that selectedChildId belongs to current user's children
const childExists = children.some(child => child.id === selectedChildId);
if (childExists) {
loadInsights();
loadPredictions();
} else {
console.warn('[AnalyticsPage] Selected child not found in user\'s children, resetting');
setSelectedChildId(children[0].id);
setError('Selected child not found. Showing data for your first child.');
}
}
}, [selectedChildId, days, children]);
const loadChildren = async () => { const loadChildren = async () => {
if (!familyId) {
setLoading(false);
setError('No family found');
return;
}
try { try {
const data = await childrenApi.getChildren(); console.log('[AnalyticsPage] Loading children for familyId:', familyId);
const data = await childrenApi.getChildren(familyId);
console.log('[AnalyticsPage] Loaded children:', data);
setChildren(data); setChildren(data);
if (data.length > 0 && !selectedChildId) {
setSelectedChildId(data[0].id); if (data.length > 0) {
const existingChildStillValid = data.some(child => child.id === selectedChildId);
if (!selectedChildId || !existingChildStillValid) {
setSelectedChildId(data[0].id);
}
} }
setError('');
} catch (error) { } catch (error) {
console.error('Failed to load children:', error); console.error('[AnalyticsPage] Failed to load children:', error);
setError('Failed to load children');
} finally { } finally {
setLoading(false); setLoading(false);
} }

View File

@@ -124,7 +124,7 @@ export default function HomePage() {
{ icon: <Hotel />, label: t('quickActions.sleep'), color: theme.palette.secondary.main, path: '/track/sleep' }, { icon: <Hotel />, label: t('quickActions.sleep'), color: theme.palette.secondary.main, path: '/track/sleep' },
{ icon: <BabyChangingStation />, label: t('quickActions.diaper'), color: theme.palette.warning.main, path: '/track/diaper' }, { icon: <BabyChangingStation />, label: t('quickActions.diaper'), color: theme.palette.warning.main, path: '/track/diaper' },
{ icon: <MedicalServices />, label: t('quickActions.medical'), color: theme.palette.error.main, path: '/track/medicine' }, { icon: <MedicalServices />, label: t('quickActions.medical'), color: theme.palette.error.main, path: '/track/medicine' },
{ icon: <Insights />, label: t('quickActions.activities'), color: theme.palette.success.main, path: '/activities' }, { icon: <Insights />, label: t('quickActions.activities'), color: theme.palette.success.main, path: '/track/activity' },
{ icon: <SmartToy />, label: t('quickActions.aiAssistant'), color: theme.palette.info.main, path: '/ai-assistant' }, { icon: <SmartToy />, label: t('quickActions.aiAssistant'), color: theme.palette.info.main, path: '/ai-assistant' },
]; ];

View File

@@ -44,6 +44,7 @@ import { useLocalizedDate } from '@/hooks/useLocalizedDate';
import { useTranslation } from '@/hooks/useTranslation'; import { useTranslation } from '@/hooks/useTranslation';
import { useFormatting } from '@/hooks/useFormatting'; import { useFormatting } from '@/hooks/useFormatting';
import { BarChart, Bar, LineChart, Line, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'; import { BarChart, Bar, LineChart, Line, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { useAuth } from '@/lib/auth/AuthContext';
type DateRange = '7days' | '30days' | '3months'; type DateRange = '7days' | '30days' | '3months';
@@ -100,6 +101,7 @@ const getActivityColor = (type: ActivityType) => {
export const InsightsDashboard: React.FC = () => { export const InsightsDashboard: React.FC = () => {
const router = useRouter(); const router = useRouter();
const { user } = useAuth();
const { format, formatDistanceToNow } = useLocalizedDate(); const { format, formatDistanceToNow } = useLocalizedDate();
const { t } = useTranslation('insights'); const { t } = useTranslation('insights');
const { formatNumber } = useFormatting(); const { formatNumber } = useFormatting();
@@ -110,30 +112,55 @@ export const InsightsDashboard: React.FC = () => {
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const familyId = user?.families?.[0]?.familyId;
// Fetch children on mount // Fetch children on mount
useEffect(() => { useEffect(() => {
const fetchChildren = async () => { const fetchChildren = async () => {
if (!familyId) {
setError('No family found');
return;
}
try { try {
const childrenData = await childrenApi.getChildren(); console.log('[InsightsDashboard] Loading children for familyId:', familyId);
const childrenData = await childrenApi.getChildren(familyId);
console.log('[InsightsDashboard] Loaded children:', childrenData);
setChildren(childrenData); setChildren(childrenData);
if (childrenData.length > 0) { if (childrenData.length > 0) {
setSelectedChild(childrenData[0].id); // Validate selected child or pick first one
const validChild = childrenData.find(c => c.id === selectedChild);
if (!validChild) {
setSelectedChild(childrenData[0].id);
}
} }
} catch (err: any) { } catch (err: any) {
console.error('[InsightsDashboard] Failed to load children:', err);
setError(err.response?.data?.message || t('errors.loadChildren')); setError(err.response?.data?.message || t('errors.loadChildren'));
} }
}; };
fetchChildren(); fetchChildren();
}, []); }, [familyId]);
// Fetch activities when child or date range changes // Fetch activities when child or date range changes
useEffect(() => { useEffect(() => {
if (!selectedChild) return; if (!selectedChild || children.length === 0) return;
// Validate that selectedChild belongs to current user's children
const childExists = children.some(child => child.id === selectedChild);
if (!childExists) {
console.warn('[InsightsDashboard] Selected child not found in user\'s children, resetting');
setSelectedChild(children[0].id);
setError('Selected child not found. Showing data for your first child.');
return;
}
const fetchActivities = async () => { const fetchActivities = async () => {
setLoading(true); setLoading(true);
setError(null); setError(null);
try { try {
console.log('[InsightsDashboard] Fetching activities for child:', selectedChild);
const days = dateRange === '7days' ? 7 : dateRange === '30days' ? 30 : 90; const days = dateRange === '7days' ? 7 : dateRange === '30days' ? 30 : 90;
const endDate = endOfDay(new Date()); const endDate = endOfDay(new Date());
const startDate = startOfDay(subDays(new Date(), days - 1)); const startDate = startOfDay(subDays(new Date(), days - 1));
@@ -144,8 +171,10 @@ export const InsightsDashboard: React.FC = () => {
startDate.toISOString(), startDate.toISOString(),
endDate.toISOString() endDate.toISOString()
); );
console.log('[InsightsDashboard] Fetched activities:', activitiesData.length);
setActivities(activitiesData); setActivities(activitiesData);
} catch (err: any) { } catch (err: any) {
console.error('[InsightsDashboard] Failed to load activities:', err);
setError(err.response?.data?.message || t('errors.loadActivities')); setError(err.response?.data?.message || t('errors.loadActivities'));
} finally { } finally {
setLoading(false); setLoading(false);
@@ -153,7 +182,7 @@ export const InsightsDashboard: React.FC = () => {
}; };
fetchActivities(); fetchActivities();
}, [selectedChild, dateRange]); }, [selectedChild, dateRange, children]);
// Calculate statistics // Calculate statistics
const calculateStats = () => { const calculateStats = () => {

View File

@@ -21,6 +21,7 @@ import { InsightsDashboard } from './InsightsDashboard';
import PredictionsCard from './PredictionsCard'; import PredictionsCard from './PredictionsCard';
import GrowthSpurtAlert from './GrowthSpurtAlert'; import GrowthSpurtAlert from './GrowthSpurtAlert';
import { motion } from 'framer-motion'; import { motion } from 'framer-motion';
import { useAuth } from '@/lib/auth/AuthContext';
interface TabPanelProps { interface TabPanelProps {
children?: React.ReactNode; children?: React.ReactNode;
@@ -45,6 +46,7 @@ function TabPanel(props: TabPanelProps) {
} }
export function UnifiedInsightsDashboard() { export function UnifiedInsightsDashboard() {
const { user } = useAuth();
const [children, setChildren] = useState<Child[]>([]); const [children, setChildren] = useState<Child[]>([]);
const [selectedChildId, setSelectedChildId] = useState<string>(''); const [selectedChildId, setSelectedChildId] = useState<string>('');
const [tabValue, setTabValue] = useState(0); const [tabValue, setTabValue] = useState(0);
@@ -54,27 +56,56 @@ export function UnifiedInsightsDashboard() {
const [insightsLoading, setInsightsLoading] = useState(false); const [insightsLoading, setInsightsLoading] = useState(false);
const [predictionsLoading, setPredictionsLoading] = useState(false); const [predictionsLoading, setPredictionsLoading] = useState(false);
const [days, setDays] = useState<number>(7); const [days, setDays] = useState<number>(7);
const [error, setError] = useState<string>('');
const familyId = user?.families?.[0]?.familyId;
useEffect(() => { useEffect(() => {
loadChildren(); if (familyId) {
}, []); loadChildren();
useEffect(() => {
if (selectedChildId) {
loadInsights();
loadPredictions();
} }
}, [selectedChildId, days]); }, [familyId]);
useEffect(() => {
if (selectedChildId && children.length > 0) {
// Validate that selectedChildId belongs to current user's children
const childExists = children.some(child => child.id === selectedChildId);
if (childExists) {
loadInsights();
loadPredictions();
} else {
// Invalid child ID - reset to first child
console.warn('[UnifiedInsightsDashboard] Selected child not found in user\'s children, resetting');
setSelectedChildId(children[0].id);
setError('Selected child not found. Showing data for your first child.');
}
}
}, [selectedChildId, days, children]);
const loadChildren = async () => { const loadChildren = async () => {
if (!familyId) {
setLoading(false);
setError('No family found');
return;
}
try { try {
const data = await childrenApi.getChildren(); console.log('[UnifiedInsightsDashboard] Loading children for familyId:', familyId);
const data = await childrenApi.getChildren(familyId);
console.log('[UnifiedInsightsDashboard] Loaded children:', data);
setChildren(data); setChildren(data);
if (data.length > 0 && !selectedChildId) {
setSelectedChildId(data[0].id); // Only set selectedChildId if we don't have one or if it's not in the new list
if (data.length > 0) {
const existingChildStillValid = data.some(child => child.id === selectedChildId);
if (!selectedChildId || !existingChildStillValid) {
setSelectedChildId(data[0].id);
}
} }
setError('');
} catch (error) { } catch (error) {
console.error('Failed to load children:', error); console.error('[UnifiedInsightsDashboard] Failed to load children:', error);
setError('Failed to load children');
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -141,6 +172,13 @@ export function UnifiedInsightsDashboard() {
</Typography> </Typography>
</Box> </Box>
{/* Error Alert */}
{error && (
<Alert severity="warning" sx={{ mb: 3 }} onClose={() => setError('')}>
{error}
</Alert>
)}
{/* Child Selector */} {/* Child Selector */}
{children.length > 1 && ( {children.length > 1 && (
<Box sx={{ mb: 3 }}> <Box sx={{ mb: 3 }}>

View File

@@ -19,10 +19,11 @@ import { TabBar } from '../TabBar/TabBar';
import { useMediaQuery } from '@/hooks/useMediaQuery'; import { useMediaQuery } from '@/hooks/useMediaQuery';
import { ReactNode } from 'react'; import { ReactNode } from 'react';
import { useWebSocket } from '@/hooks/useWebSocket'; import { useWebSocket } from '@/hooks/useWebSocket';
import { Wifi, WifiOff, People, AccountCircle, Settings, ChildCare, Group, Logout, Gavel } from '@mui/icons-material'; import { Wifi, WifiOff, People, AccountCircle, Settings, ChildCare, Group, Logout, Gavel, Favorite } from '@mui/icons-material';
import { useTranslation } from '@/hooks/useTranslation'; import { useTranslation } from '@/hooks/useTranslation';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth/AuthContext'; import { useAuth } from '@/lib/auth/AuthContext';
import Link from 'next/link';
interface AppShellProps { interface AppShellProps {
children: ReactNode; children: ReactNode;
@@ -93,7 +94,7 @@ export const AppShell = ({ children }: AppShellProps) => {
}} }}
> >
{/* Left Side - Family Members Online Indicator */} {/* Left Side - Family Members Online Indicator */}
<Box> <Box sx={{ width: 80, display: 'flex', justifyContent: 'flex-start' }}>
{isConnected && presence.count > 1 && ( {isConnected && presence.count > 1 && (
<Tooltip title={t('connection.familyMembersOnline', { count: presence.count })}> <Tooltip title={t('connection.familyMembersOnline', { count: presence.count })}>
<Chip <Chip
@@ -109,7 +110,47 @@ export const AppShell = ({ children }: AppShellProps) => {
)} )}
</Box> </Box>
{/* Center - Logo */}
<Box
component={Link}
href="/"
sx={{
display: 'flex',
alignItems: 'center',
gap: 1,
textDecoration: 'none',
'&:hover': {
opacity: 0.8,
},
cursor: 'pointer',
}}
>
<Box
component="img"
src="/icon-192x192.png"
alt="ParentFlow logo"
sx={{
width: 32,
height: 32,
borderRadius: 1,
}}
/>
<Box
component="span"
sx={{
fontWeight: 700,
fontSize: { xs: '0.95rem', sm: '1.1rem' },
background: (theme) => `linear-gradient(135deg, ${theme.palette.primary.main} 0%, ${theme.palette.secondary.main} 100%)`,
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
}}
>
ParentFlow
</Box>
</Box>
{/* Right Side - User Menu Button with Status Indicator */} {/* Right Side - User Menu Button with Status Indicator */}
<Box sx={{ width: 80, display: 'flex', justifyContent: 'flex-end' }}>
<Tooltip title={isConnected ? t('connection.syncActive') : t('connection.syncDisconnected')}> <Tooltip title={isConnected ? t('connection.syncActive') : t('connection.syncDisconnected')}>
<IconButton <IconButton
onClick={handleMenuOpen} onClick={handleMenuOpen}
@@ -207,6 +248,7 @@ export const AppShell = ({ children }: AppShellProps) => {
<ListItemText>{t('navigation.logout')}</ListItemText> <ListItemText>{t('navigation.logout')}</ListItemText>
</MenuItem> </MenuItem>
</Menu> </Menu>
</Box>
</Box> </Box>
<Container <Container

File diff suppressed because one or more lines are too long