Implement comprehensive tracking system and analytics dashboard
- Add Feeding Tracker with 3 feeding types (breast, bottle, solid) - Built-in timer for breastfeeding sessions - Recent feeding history with delete functionality - Form validation and child selection - Add Sleep Tracker with duration tracking - Start/end time inputs with "Now" quick buttons - Sleep quality and location tracking - Ongoing sleep support with real-time duration - Recent sleep activities list - Add Diaper Tracker with comprehensive monitoring - 4 diaper types (wet, dirty, both, dry) - Multiple condition selectors - Rash monitoring with severity levels - Color-coded visual indicators - Add Insights/Analytics Dashboard - Summary statistics cards (feedings, sleep, diapers) - Interactive charts using Recharts (bar, line, pie) - Date range filtering (7/30/90 days) - Activity timeline and distribution - Recent activities list - Add Settings page with backend integration - Profile update functionality with API integration - Form validation and error handling - Loading states and success notifications - Notification and appearance preferences - Add Users API service for profile management All pages include: - Full CRUD operations with backend APIs - Loading states and error handling - Form validation and user feedback - Framer Motion animations - Material-UI design system - Responsive layouts 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -1,89 +1,337 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
Button,
|
||||
Paper,
|
||||
TextField,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Select,
|
||||
MenuItem,
|
||||
IconButton,
|
||||
Alert,
|
||||
CircularProgress,
|
||||
Card,
|
||||
CardContent,
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
DialogContentText,
|
||||
DialogActions,
|
||||
Chip,
|
||||
FormControl,
|
||||
FormLabel,
|
||||
RadioGroup,
|
||||
FormControlLabel,
|
||||
Radio,
|
||||
Snackbar,
|
||||
ToggleButtonGroup,
|
||||
ToggleButton,
|
||||
FormLabel,
|
||||
} from '@mui/material';
|
||||
import {
|
||||
ArrowBack,
|
||||
Refresh,
|
||||
Save,
|
||||
Mic,
|
||||
Delete,
|
||||
BabyChangingStation,
|
||||
Warning,
|
||||
CheckCircle,
|
||||
} from '@mui/icons-material';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { AppShell } from '@/components/layouts/AppShell/AppShell';
|
||||
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { trackingApi, Activity } from '@/lib/api/tracking';
|
||||
import { childrenApi, Child } from '@/lib/api/children';
|
||||
import { motion } from 'framer-motion';
|
||||
import { useForm, Controller } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as z from 'zod';
|
||||
import { format } from 'date-fns';
|
||||
import { formatDistanceToNow, format } from 'date-fns';
|
||||
|
||||
const diaperSchema = z.object({
|
||||
type: z.enum(['wet', 'dirty', 'both', 'clean']),
|
||||
timestamp: z.string(),
|
||||
rash: z.boolean(),
|
||||
notes: z.string().optional(),
|
||||
});
|
||||
|
||||
type DiaperFormData = z.infer<typeof diaperSchema>;
|
||||
interface DiaperData {
|
||||
diaperType: 'wet' | 'dirty' | 'both' | 'dry';
|
||||
conditions: string[];
|
||||
hasRash: boolean;
|
||||
rashSeverity?: 'mild' | 'moderate' | 'severe';
|
||||
}
|
||||
|
||||
export default function DiaperTrackPage() {
|
||||
const router = useRouter();
|
||||
const { user } = useAuth();
|
||||
const [children, setChildren] = useState<Child[]>([]);
|
||||
const [selectedChild, setSelectedChild] = useState<string>('');
|
||||
|
||||
// Diaper state
|
||||
const [timestamp, setTimestamp] = useState<string>(
|
||||
format(new Date(), "yyyy-MM-dd'T'HH:mm")
|
||||
);
|
||||
const [diaperType, setDiaperType] = useState<'wet' | 'dirty' | 'both' | 'dry'>('wet');
|
||||
const [conditions, setConditions] = useState<string[]>(['normal']);
|
||||
const [hasRash, setHasRash] = useState<boolean>(false);
|
||||
const [rashSeverity, setRashSeverity] = useState<'mild' | 'moderate' | 'severe'>('mild');
|
||||
|
||||
// Common state
|
||||
const [notes, setNotes] = useState<string>('');
|
||||
const [recentDiapers, setRecentDiapers] = useState<Activity[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [childrenLoading, setChildrenLoading] = useState(true);
|
||||
const [diapersLoading, setDiapersLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState(false);
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
setValue,
|
||||
watch,
|
||||
control,
|
||||
formState: { errors },
|
||||
} = useForm<DiaperFormData>({
|
||||
resolver: zodResolver(diaperSchema),
|
||||
defaultValues: {
|
||||
type: 'wet',
|
||||
rash: false,
|
||||
timestamp: format(new Date(), "yyyy-MM-dd'T'HH:mm"),
|
||||
},
|
||||
});
|
||||
// Delete confirmation dialog
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [activityToDelete, setActivityToDelete] = useState<string | null>(null);
|
||||
|
||||
const diaperType = watch('type');
|
||||
const rash = watch('rash');
|
||||
const familyId = user?.families?.[0]?.familyId;
|
||||
|
||||
const setTimeNow = () => {
|
||||
const now = format(new Date(), "yyyy-MM-dd'T'HH:mm");
|
||||
setValue('timestamp', now);
|
||||
};
|
||||
const availableConditions = [
|
||||
'normal',
|
||||
'soft',
|
||||
'hard',
|
||||
'watery',
|
||||
'mucus',
|
||||
'blood',
|
||||
];
|
||||
|
||||
const onSubmit = async (data: DiaperFormData) => {
|
||||
setError(null);
|
||||
// Load children
|
||||
useEffect(() => {
|
||||
if (familyId) {
|
||||
loadChildren();
|
||||
}
|
||||
}, [familyId]);
|
||||
|
||||
// Load recent diapers when child is selected
|
||||
useEffect(() => {
|
||||
if (selectedChild) {
|
||||
loadRecentDiapers();
|
||||
}
|
||||
}, [selectedChild]);
|
||||
|
||||
const loadChildren = async () => {
|
||||
if (!familyId) return;
|
||||
|
||||
try {
|
||||
// TODO: Call API to save diaper data
|
||||
console.log('Diaper data:', data);
|
||||
setSuccess(true);
|
||||
setTimeout(() => router.push('/'), 2000);
|
||||
setChildrenLoading(true);
|
||||
const childrenData = await childrenApi.getChildren(familyId);
|
||||
setChildren(childrenData);
|
||||
if (childrenData.length > 0) {
|
||||
setSelectedChild(childrenData[0].id);
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to log diaper change');
|
||||
console.error('Failed to load children:', err);
|
||||
setError(err.response?.data?.message || 'Failed to load children');
|
||||
} finally {
|
||||
setChildrenLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loadRecentDiapers = async () => {
|
||||
if (!selectedChild) return;
|
||||
|
||||
try {
|
||||
setDiapersLoading(true);
|
||||
const activities = await trackingApi.getActivities(selectedChild, 'diaper');
|
||||
// Sort by timestamp descending and take last 10
|
||||
const sorted = activities.sort((a, b) =>
|
||||
new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
|
||||
).slice(0, 10);
|
||||
setRecentDiapers(sorted);
|
||||
} catch (err: any) {
|
||||
console.error('Failed to load recent diapers:', err);
|
||||
} finally {
|
||||
setDiapersLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const setTimeNow = () => {
|
||||
setTimestamp(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
|
||||
};
|
||||
|
||||
const handleConditionToggle = (condition: string) => {
|
||||
setConditions((prev) => {
|
||||
if (prev.includes(condition)) {
|
||||
// Remove condition, but ensure at least one remains
|
||||
if (prev.length === 1) return prev;
|
||||
return prev.filter((c) => c !== condition);
|
||||
} else {
|
||||
return [...prev, condition];
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!selectedChild) {
|
||||
setError('Please select a child');
|
||||
return;
|
||||
}
|
||||
|
||||
// Validation
|
||||
if (!timestamp) {
|
||||
setError('Please enter timestamp');
|
||||
return;
|
||||
}
|
||||
|
||||
if (conditions.length === 0) {
|
||||
setError('Please select at least one condition');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const data: DiaperData = {
|
||||
diaperType,
|
||||
conditions,
|
||||
hasRash,
|
||||
};
|
||||
|
||||
if (hasRash) {
|
||||
data.rashSeverity = rashSeverity;
|
||||
}
|
||||
|
||||
await trackingApi.createActivity(selectedChild, {
|
||||
type: 'diaper',
|
||||
timestamp,
|
||||
data,
|
||||
notes: notes || undefined,
|
||||
});
|
||||
|
||||
setSuccessMessage('Diaper change logged successfully!');
|
||||
|
||||
// Reset form
|
||||
resetForm();
|
||||
|
||||
// Reload recent diapers
|
||||
await loadRecentDiapers();
|
||||
} catch (err: any) {
|
||||
console.error('Failed to save diaper:', err);
|
||||
setError(err.response?.data?.message || 'Failed to save diaper change');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const resetForm = () => {
|
||||
setTimestamp(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
|
||||
setDiaperType('wet');
|
||||
setConditions(['normal']);
|
||||
setHasRash(false);
|
||||
setRashSeverity('mild');
|
||||
setNotes('');
|
||||
};
|
||||
|
||||
const handleDeleteClick = (activityId: string) => {
|
||||
setActivityToDelete(activityId);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDeleteConfirm = async () => {
|
||||
if (!activityToDelete) return;
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
await trackingApi.deleteActivity(activityToDelete);
|
||||
setSuccessMessage('Diaper change deleted successfully');
|
||||
setDeleteDialogOpen(false);
|
||||
setActivityToDelete(null);
|
||||
await loadRecentDiapers();
|
||||
} catch (err: any) {
|
||||
console.error('Failed to delete diaper:', err);
|
||||
setError(err.response?.data?.message || 'Failed to delete diaper change');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const getDiaperTypeColor = (type: string) => {
|
||||
switch (type) {
|
||||
case 'wet':
|
||||
return '#2196f3'; // blue
|
||||
case 'dirty':
|
||||
return '#795548'; // brown
|
||||
case 'both':
|
||||
return '#ff9800'; // orange
|
||||
case 'dry':
|
||||
return '#4caf50'; // green
|
||||
default:
|
||||
return '#757575'; // grey
|
||||
}
|
||||
};
|
||||
|
||||
const getDiaperTypeIcon = (type: string) => {
|
||||
switch (type) {
|
||||
case 'wet':
|
||||
return '💧';
|
||||
case 'dirty':
|
||||
return '💩';
|
||||
case 'both':
|
||||
return '💧💩';
|
||||
case 'dry':
|
||||
return '✨';
|
||||
default:
|
||||
return '🍼';
|
||||
}
|
||||
};
|
||||
|
||||
const getDiaperDetails = (activity: Activity) => {
|
||||
const data = activity.data as DiaperData;
|
||||
const typeLabel = data.diaperType.charAt(0).toUpperCase() + data.diaperType.slice(1);
|
||||
const conditionsLabel = data.conditions.join(', ');
|
||||
|
||||
let details = `${typeLabel} - ${conditionsLabel}`;
|
||||
|
||||
if (data.hasRash) {
|
||||
details += ` - Rash (${data.rashSeverity})`;
|
||||
}
|
||||
|
||||
return details;
|
||||
};
|
||||
|
||||
const getRashSeverityColor = (severity: string) => {
|
||||
switch (severity) {
|
||||
case 'mild':
|
||||
return 'warning';
|
||||
case 'moderate':
|
||||
return 'error';
|
||||
case 'severe':
|
||||
return 'error';
|
||||
default:
|
||||
return 'default';
|
||||
}
|
||||
};
|
||||
|
||||
if (childrenLoading) {
|
||||
return (
|
||||
<ProtectedRoute>
|
||||
<AppShell>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
</AppShell>
|
||||
</ProtectedRoute>
|
||||
);
|
||||
}
|
||||
|
||||
if (!familyId || children.length === 0) {
|
||||
return (
|
||||
<ProtectedRoute>
|
||||
<AppShell>
|
||||
<Box>
|
||||
<Alert severity="warning">
|
||||
Please add a child first before tracking diaper changes.
|
||||
</Alert>
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={() => router.push('/children')}
|
||||
sx={{ mt: 2 }}
|
||||
>
|
||||
Go to Children Page
|
||||
</Button>
|
||||
</Box>
|
||||
</AppShell>
|
||||
</ProtectedRoute>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ProtectedRoute>
|
||||
<AppShell>
|
||||
@@ -97,14 +345,8 @@ export default function DiaperTrackPage() {
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{success && (
|
||||
<Alert severity="success" sx={{ mb: 3 }}>
|
||||
Diaper change logged successfully!
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 3 }}>
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
@@ -114,150 +356,299 @@ export default function DiaperTrackPage() {
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
{/* Child Selector */}
|
||||
{children.length > 1 && (
|
||||
<Paper sx={{ p: 2, mb: 3 }}>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>Select Child</InputLabel>
|
||||
<Select
|
||||
value={selectedChild}
|
||||
onChange={(e) => setSelectedChild(e.target.value)}
|
||||
label="Select Child"
|
||||
>
|
||||
{children.map((child) => (
|
||||
<MenuItem key={child.id} value={child.id}>
|
||||
{child.name}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Main Form */}
|
||||
<Paper sx={{ p: 3, mb: 3 }}>
|
||||
<Box component="form" onSubmit={handleSubmit(onSubmit)}>
|
||||
{/* Icon Header */}
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', mb: 3 }}>
|
||||
<BabyChangingStation sx={{ fontSize: 64, color: 'primary.main' }} />
|
||||
</Box>
|
||||
|
||||
{/* Time */}
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<FormLabel sx={{ mb: 1, display: 'block' }}>Time</FormLabel>
|
||||
<Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
|
||||
<TextField
|
||||
fullWidth
|
||||
type="datetime-local"
|
||||
{...register('timestamp')}
|
||||
error={!!errors.timestamp}
|
||||
helperText={errors.timestamp?.message}
|
||||
InputLabelProps={{ shrink: true }}
|
||||
/>
|
||||
<Button variant="outlined" onClick={setTimeNow} sx={{ minWidth: 100 }}>
|
||||
Now
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* Diaper Type */}
|
||||
<FormControl component="fieldset" sx={{ mb: 3, width: '100%' }}>
|
||||
<FormLabel component="legend" sx={{ mb: 2 }}>
|
||||
Diaper Type
|
||||
</FormLabel>
|
||||
<Controller
|
||||
name="type"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<ToggleButtonGroup
|
||||
{...field}
|
||||
exclusive
|
||||
fullWidth
|
||||
onChange={(_, value) => {
|
||||
if (value !== null) {
|
||||
field.onChange(value);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ToggleButton value="wet" sx={{ py: 2 }}>
|
||||
<Box sx={{ textAlign: 'center' }}>
|
||||
<Typography variant="h5">💧</Typography>
|
||||
<Typography variant="body2">Wet</Typography>
|
||||
</Box>
|
||||
</ToggleButton>
|
||||
<ToggleButton value="dirty" sx={{ py: 2 }}>
|
||||
<Box sx={{ textAlign: 'center' }}>
|
||||
<Typography variant="h5">💩</Typography>
|
||||
<Typography variant="body2">Dirty</Typography>
|
||||
</Box>
|
||||
</ToggleButton>
|
||||
<ToggleButton value="both" sx={{ py: 2 }}>
|
||||
<Box sx={{ textAlign: 'center' }}>
|
||||
<Typography variant="h5">💧💩</Typography>
|
||||
<Typography variant="body2">Both</Typography>
|
||||
</Box>
|
||||
</ToggleButton>
|
||||
<ToggleButton value="clean" sx={{ py: 2 }}>
|
||||
<Box sx={{ textAlign: 'center' }}>
|
||||
<Typography variant="h5">✨</Typography>
|
||||
<Typography variant="body2">Clean</Typography>
|
||||
</Box>
|
||||
</ToggleButton>
|
||||
</ToggleButtonGroup>
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
{/* Rash Indicator */}
|
||||
<FormControl component="fieldset" sx={{ mb: 3, width: '100%' }}>
|
||||
<FormLabel component="legend" sx={{ mb: 2 }}>
|
||||
Diaper Rash?
|
||||
</FormLabel>
|
||||
<RadioGroup row>
|
||||
<FormControlLabel
|
||||
value="no"
|
||||
control={
|
||||
<Radio
|
||||
checked={!rash}
|
||||
onChange={() => setValue('rash', false)}
|
||||
/>
|
||||
}
|
||||
label="No"
|
||||
/>
|
||||
<FormControlLabel
|
||||
value="yes"
|
||||
control={
|
||||
<Radio
|
||||
checked={rash}
|
||||
onChange={() => setValue('rash', true)}
|
||||
/>
|
||||
}
|
||||
label="Yes"
|
||||
/>
|
||||
</RadioGroup>
|
||||
</FormControl>
|
||||
|
||||
{/* Rash Warning */}
|
||||
{rash && (
|
||||
<Alert severity="warning" sx={{ mb: 3 }}>
|
||||
Consider applying diaper rash cream and consulting your pediatrician if it persists.
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Notes */}
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Notes (optional)"
|
||||
multiline
|
||||
rows={3}
|
||||
{...register('notes')}
|
||||
sx={{ mb: 3 }}
|
||||
placeholder="Color, consistency, or any concerns..."
|
||||
/>
|
||||
|
||||
{/* Voice Input Button */}
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', mb: 3 }}>
|
||||
<Chip
|
||||
icon={<Mic />}
|
||||
label="Use Voice Input"
|
||||
onClick={() => {/* TODO: Implement voice input */}}
|
||||
sx={{ cursor: 'pointer' }}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
{/* Submit Button */}
|
||||
<Button
|
||||
fullWidth
|
||||
type="submit"
|
||||
variant="contained"
|
||||
size="large"
|
||||
startIcon={<Save />}
|
||||
>
|
||||
Save Diaper Change
|
||||
</Button>
|
||||
{/* Icon Header */}
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', mb: 3 }}>
|
||||
<BabyChangingStation sx={{ fontSize: 64, color: 'primary.main' }} />
|
||||
</Box>
|
||||
|
||||
{/* Timestamp */}
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<Typography variant="subtitle1" fontWeight="600" sx={{ mb: 1 }}>
|
||||
Time
|
||||
</Typography>
|
||||
<Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
|
||||
<TextField
|
||||
fullWidth
|
||||
type="datetime-local"
|
||||
value={timestamp}
|
||||
onChange={(e) => setTimestamp(e.target.value)}
|
||||
InputLabelProps={{ shrink: true }}
|
||||
/>
|
||||
<Button variant="outlined" onClick={setTimeNow} sx={{ minWidth: 100 }}>
|
||||
Now
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* Diaper Type */}
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<Typography variant="subtitle1" fontWeight="600" sx={{ mb: 2 }}>
|
||||
Diaper Type
|
||||
</Typography>
|
||||
<ToggleButtonGroup
|
||||
value={diaperType}
|
||||
exclusive
|
||||
onChange={(_, value) => {
|
||||
if (value !== null) {
|
||||
setDiaperType(value);
|
||||
}
|
||||
}}
|
||||
fullWidth
|
||||
>
|
||||
<ToggleButton value="wet" sx={{ py: 2 }}>
|
||||
<Box sx={{ textAlign: 'center' }}>
|
||||
<Typography variant="h5">💧</Typography>
|
||||
<Typography variant="body2">Wet</Typography>
|
||||
</Box>
|
||||
</ToggleButton>
|
||||
<ToggleButton value="dirty" sx={{ py: 2 }}>
|
||||
<Box sx={{ textAlign: 'center' }}>
|
||||
<Typography variant="h5">💩</Typography>
|
||||
<Typography variant="body2">Dirty</Typography>
|
||||
</Box>
|
||||
</ToggleButton>
|
||||
<ToggleButton value="both" sx={{ py: 2 }}>
|
||||
<Box sx={{ textAlign: 'center' }}>
|
||||
<Typography variant="h5">💧💩</Typography>
|
||||
<Typography variant="body2">Both</Typography>
|
||||
</Box>
|
||||
</ToggleButton>
|
||||
<ToggleButton value="dry" sx={{ py: 2 }}>
|
||||
<Box sx={{ textAlign: 'center' }}>
|
||||
<Typography variant="h5">✨</Typography>
|
||||
<Typography variant="body2">Dry</Typography>
|
||||
</Box>
|
||||
</ToggleButton>
|
||||
</ToggleButtonGroup>
|
||||
</Box>
|
||||
|
||||
{/* Condition Selector */}
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<Typography variant="subtitle1" fontWeight="600" sx={{ mb: 1 }}>
|
||||
Condition (select all that apply)
|
||||
</Typography>
|
||||
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
|
||||
{availableConditions.map((condition) => (
|
||||
<Chip
|
||||
key={condition}
|
||||
label={condition.charAt(0).toUpperCase() + condition.slice(1)}
|
||||
onClick={() => handleConditionToggle(condition)}
|
||||
color={conditions.includes(condition) ? 'primary' : 'default'}
|
||||
variant={conditions.includes(condition) ? 'filled' : 'outlined'}
|
||||
sx={{ cursor: 'pointer' }}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* Rash Indicator */}
|
||||
<FormControl fullWidth sx={{ mb: 3 }}>
|
||||
<InputLabel>Diaper Rash?</InputLabel>
|
||||
<Select
|
||||
value={hasRash ? 'yes' : 'no'}
|
||||
onChange={(e) => setHasRash(e.target.value === 'yes')}
|
||||
label="Diaper Rash?"
|
||||
>
|
||||
<MenuItem value="no">No</MenuItem>
|
||||
<MenuItem value="yes">Yes</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
{/* Rash Severity */}
|
||||
{hasRash && (
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<Alert severity="warning" sx={{ mb: 2 }}>
|
||||
<Typography variant="body2" sx={{ mb: 1 }}>
|
||||
Diaper rash detected. Consider applying diaper rash cream and consulting your pediatrician if it persists.
|
||||
</Typography>
|
||||
</Alert>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>Rash Severity</InputLabel>
|
||||
<Select
|
||||
value={rashSeverity}
|
||||
onChange={(e) => setRashSeverity(e.target.value as 'mild' | 'moderate' | 'severe')}
|
||||
label="Rash Severity"
|
||||
>
|
||||
<MenuItem value="mild">Mild</MenuItem>
|
||||
<MenuItem value="moderate">Moderate</MenuItem>
|
||||
<MenuItem value="severe">Severe</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Notes Field */}
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Notes (optional)"
|
||||
multiline
|
||||
rows={3}
|
||||
value={notes}
|
||||
onChange={(e) => setNotes(e.target.value)}
|
||||
sx={{ mb: 3 }}
|
||||
placeholder="Color, consistency, or any concerns..."
|
||||
/>
|
||||
|
||||
{/* Submit Button */}
|
||||
<Button
|
||||
fullWidth
|
||||
type="button"
|
||||
variant="contained"
|
||||
size="large"
|
||||
startIcon={<Save />}
|
||||
onClick={handleSubmit}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? 'Saving...' : 'Save Diaper Change'}
|
||||
</Button>
|
||||
</Paper>
|
||||
|
||||
{/* Recent Diapers */}
|
||||
<Paper sx={{ p: 3 }}>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
|
||||
<Typography variant="h6" fontWeight="600">
|
||||
Recent Diaper Changes
|
||||
</Typography>
|
||||
<IconButton onClick={loadRecentDiapers} disabled={diapersLoading}>
|
||||
<Refresh />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
||||
{diapersLoading ? (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
|
||||
<CircularProgress size={30} />
|
||||
</Box>
|
||||
) : recentDiapers.length === 0 ? (
|
||||
<Box sx={{ textAlign: 'center', py: 4 }}>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
No diaper changes yet
|
||||
</Typography>
|
||||
</Box>
|
||||
) : (
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
{recentDiapers.map((activity, index) => {
|
||||
const data = activity.data as DiaperData;
|
||||
return (
|
||||
<motion.div
|
||||
key={activity.id}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.2, delay: index * 0.05 }}
|
||||
>
|
||||
<Card variant="outlined">
|
||||
<CardContent>
|
||||
<Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 2 }}>
|
||||
<Box sx={{ mt: 0.5, fontSize: '2rem' }}>
|
||||
{getDiaperTypeIcon(data.diaperType)}
|
||||
</Box>
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5, flexWrap: 'wrap' }}>
|
||||
<Typography variant="body1" fontWeight="600">
|
||||
Diaper Change
|
||||
</Typography>
|
||||
<Chip
|
||||
label={data.diaperType.charAt(0).toUpperCase() + data.diaperType.slice(1)}
|
||||
size="small"
|
||||
sx={{
|
||||
bgcolor: getDiaperTypeColor(data.diaperType),
|
||||
color: 'white'
|
||||
}}
|
||||
/>
|
||||
{data.hasRash && (
|
||||
<Chip
|
||||
icon={<Warning sx={{ fontSize: 16 }} />}
|
||||
label={`Rash: ${data.rashSeverity}`}
|
||||
size="small"
|
||||
color={getRashSeverityColor(data.rashSeverity || 'mild') as any}
|
||||
/>
|
||||
)}
|
||||
<Chip
|
||||
label={formatDistanceToNow(new Date(activity.timestamp), { addSuffix: true })}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
/>
|
||||
</Box>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
|
||||
{getDiaperDetails(activity)}
|
||||
</Typography>
|
||||
{activity.notes && (
|
||||
<Typography variant="body2" color="text.secondary" sx={{ fontStyle: 'italic' }}>
|
||||
{activity.notes}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
<Box sx={{ display: 'flex', gap: 0.5 }}>
|
||||
<IconButton
|
||||
size="small"
|
||||
color="error"
|
||||
onClick={() => handleDeleteClick(activity.id)}
|
||||
disabled={loading}
|
||||
>
|
||||
<Delete />
|
||||
</IconButton>
|
||||
</Box>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
)}
|
||||
</Paper>
|
||||
</motion.div>
|
||||
</Box>
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<Dialog
|
||||
open={deleteDialogOpen}
|
||||
onClose={() => setDeleteDialogOpen(false)}
|
||||
>
|
||||
<DialogTitle>Delete Diaper Change?</DialogTitle>
|
||||
<DialogContent>
|
||||
<DialogContentText>
|
||||
Are you sure you want to delete this diaper change? This action cannot be undone.
|
||||
</DialogContentText>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setDeleteDialogOpen(false)} disabled={loading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleDeleteConfirm} color="error" disabled={loading}>
|
||||
{loading ? 'Deleting...' : 'Delete'}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
{/* Success Snackbar */}
|
||||
<Snackbar
|
||||
open={!!successMessage}
|
||||
autoHideDuration={3000}
|
||||
onClose={() => setSuccessMessage(null)}
|
||||
message={successMessage}
|
||||
/>
|
||||
</AppShell>
|
||||
</ProtectedRoute>
|
||||
);
|
||||
|
||||
@@ -8,89 +8,331 @@ import {
|
||||
Paper,
|
||||
TextField,
|
||||
FormControl,
|
||||
FormLabel,
|
||||
RadioGroup,
|
||||
FormControlLabel,
|
||||
Radio,
|
||||
InputLabel,
|
||||
Select,
|
||||
MenuItem,
|
||||
IconButton,
|
||||
Alert,
|
||||
Tabs,
|
||||
Tab,
|
||||
CircularProgress,
|
||||
Card,
|
||||
CardContent,
|
||||
Divider,
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
DialogContentText,
|
||||
DialogActions,
|
||||
Chip,
|
||||
Snackbar,
|
||||
} from '@mui/material';
|
||||
import {
|
||||
ArrowBack,
|
||||
PlayArrow,
|
||||
Stop,
|
||||
Refresh,
|
||||
Save,
|
||||
Mic,
|
||||
Restaurant,
|
||||
LocalCafe,
|
||||
Fastfood,
|
||||
Delete,
|
||||
Edit,
|
||||
} from '@mui/icons-material';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { AppShell } from '@/components/layouts/AppShell/AppShell';
|
||||
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { trackingApi, Activity } from '@/lib/api/tracking';
|
||||
import { childrenApi, Child } from '@/lib/api/children';
|
||||
import { motion } from 'framer-motion';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as z from 'zod';
|
||||
import { formatDistanceToNow } from 'date-fns';
|
||||
|
||||
const feedingSchema = z.object({
|
||||
type: z.enum(['breast_left', 'breast_right', 'breast_both', 'bottle', 'solid']),
|
||||
amount: z.number().min(0).optional(),
|
||||
unit: z.enum(['ml', 'oz']).optional(),
|
||||
notes: z.string().optional(),
|
||||
});
|
||||
|
||||
type FeedingFormData = z.infer<typeof feedingSchema>;
|
||||
interface FeedingData {
|
||||
feedingType: 'breast' | 'bottle' | 'solid';
|
||||
side?: 'left' | 'right' | 'both';
|
||||
duration?: number;
|
||||
amount?: number;
|
||||
bottleType?: 'formula' | 'breastmilk' | 'other';
|
||||
foodDescription?: string;
|
||||
amountDescription?: string;
|
||||
}
|
||||
|
||||
export default function FeedingTrackPage() {
|
||||
const router = useRouter();
|
||||
const { user } = useAuth();
|
||||
const [children, setChildren] = useState<Child[]>([]);
|
||||
const [selectedChild, setSelectedChild] = useState<string>('');
|
||||
const [feedingType, setFeedingType] = useState<'breast' | 'bottle' | 'solid'>('breast');
|
||||
|
||||
// Breastfeeding state
|
||||
const [side, setSide] = useState<'left' | 'right' | 'both'>('left');
|
||||
const [duration, setDuration] = useState<number>(0);
|
||||
const [isTimerRunning, setIsTimerRunning] = useState(false);
|
||||
const [duration, setDuration] = useState(0);
|
||||
const [timerSeconds, setTimerSeconds] = useState(0);
|
||||
|
||||
// Bottle feeding state
|
||||
const [amount, setAmount] = useState<string>('');
|
||||
const [bottleType, setBottleType] = useState<'formula' | 'breastmilk' | 'other'>('formula');
|
||||
|
||||
// Solid food state
|
||||
const [foodDescription, setFoodDescription] = useState<string>('');
|
||||
const [amountDescription, setAmountDescription] = useState<string>('');
|
||||
|
||||
// Common state
|
||||
const [notes, setNotes] = useState<string>('');
|
||||
const [recentFeedings, setRecentFeedings] = useState<Activity[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [childrenLoading, setChildrenLoading] = useState(true);
|
||||
const [feedingsLoading, setFeedingsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState(false);
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
watch,
|
||||
formState: { errors },
|
||||
} = useForm<FeedingFormData>({
|
||||
resolver: zodResolver(feedingSchema),
|
||||
defaultValues: {
|
||||
type: 'breast_left',
|
||||
unit: 'ml',
|
||||
},
|
||||
});
|
||||
// Delete confirmation dialog
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [activityToDelete, setActivityToDelete] = useState<string | null>(null);
|
||||
|
||||
const feedingType = watch('type');
|
||||
const familyId = user?.families?.[0]?.familyId;
|
||||
|
||||
// Load children
|
||||
useEffect(() => {
|
||||
if (familyId) {
|
||||
loadChildren();
|
||||
}
|
||||
}, [familyId]);
|
||||
|
||||
// Load recent feedings when child is selected
|
||||
useEffect(() => {
|
||||
if (selectedChild) {
|
||||
loadRecentFeedings();
|
||||
}
|
||||
}, [selectedChild]);
|
||||
|
||||
// Timer effect
|
||||
useEffect(() => {
|
||||
let interval: NodeJS.Timeout;
|
||||
if (isTimerRunning) {
|
||||
interval = setInterval(() => {
|
||||
setDuration((prev) => prev + 1);
|
||||
setTimerSeconds((prev) => prev + 1);
|
||||
}, 1000);
|
||||
}
|
||||
return () => clearInterval(interval);
|
||||
}, [isTimerRunning]);
|
||||
|
||||
const loadChildren = async () => {
|
||||
if (!familyId) return;
|
||||
|
||||
try {
|
||||
setChildrenLoading(true);
|
||||
const childrenData = await childrenApi.getChildren(familyId);
|
||||
setChildren(childrenData);
|
||||
if (childrenData.length > 0) {
|
||||
setSelectedChild(childrenData[0].id);
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('Failed to load children:', err);
|
||||
setError(err.response?.data?.message || 'Failed to load children');
|
||||
} finally {
|
||||
setChildrenLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loadRecentFeedings = async () => {
|
||||
if (!selectedChild) return;
|
||||
|
||||
try {
|
||||
setFeedingsLoading(true);
|
||||
const activities = await trackingApi.getActivities(selectedChild, 'feeding');
|
||||
// Sort by timestamp descending and take last 10
|
||||
const sorted = activities.sort((a, b) =>
|
||||
new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
|
||||
).slice(0, 10);
|
||||
setRecentFeedings(sorted);
|
||||
} catch (err: any) {
|
||||
console.error('Failed to load recent feedings:', err);
|
||||
} finally {
|
||||
setFeedingsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const formatDuration = (seconds: number) => {
|
||||
const mins = Math.floor(seconds / 60);
|
||||
const secs = seconds % 60;
|
||||
return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
|
||||
};
|
||||
|
||||
const onSubmit = async (data: FeedingFormData) => {
|
||||
setError(null);
|
||||
const startTimer = () => {
|
||||
setIsTimerRunning(true);
|
||||
};
|
||||
|
||||
const stopTimer = () => {
|
||||
setIsTimerRunning(false);
|
||||
setDuration(Math.floor(timerSeconds / 60));
|
||||
};
|
||||
|
||||
const resetTimer = () => {
|
||||
setIsTimerRunning(false);
|
||||
setTimerSeconds(0);
|
||||
setDuration(0);
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!selectedChild) {
|
||||
setError('Please select a child');
|
||||
return;
|
||||
}
|
||||
|
||||
// Validation
|
||||
if (feedingType === 'breast' && duration === 0 && timerSeconds === 0) {
|
||||
setError('Please enter duration or use the timer');
|
||||
return;
|
||||
}
|
||||
|
||||
if (feedingType === 'bottle' && !amount) {
|
||||
setError('Please enter amount');
|
||||
return;
|
||||
}
|
||||
|
||||
if (feedingType === 'solid' && !foodDescription) {
|
||||
setError('Please enter food description');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// TODO: Call API to save feeding data
|
||||
console.log('Feeding data:', { ...data, duration });
|
||||
setSuccess(true);
|
||||
setTimeout(() => router.push('/'), 2000);
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const data: FeedingData = {
|
||||
feedingType,
|
||||
};
|
||||
|
||||
if (feedingType === 'breast') {
|
||||
data.side = side;
|
||||
data.duration = duration || Math.floor(timerSeconds / 60);
|
||||
} else if (feedingType === 'bottle') {
|
||||
data.amount = parseFloat(amount);
|
||||
data.bottleType = bottleType;
|
||||
} else if (feedingType === 'solid') {
|
||||
data.foodDescription = foodDescription;
|
||||
data.amountDescription = amountDescription;
|
||||
}
|
||||
|
||||
await trackingApi.createActivity(selectedChild, {
|
||||
type: 'feeding',
|
||||
timestamp: new Date().toISOString(),
|
||||
data,
|
||||
notes: notes || undefined,
|
||||
});
|
||||
|
||||
setSuccessMessage('Feeding logged successfully!');
|
||||
|
||||
// Reset form
|
||||
resetForm();
|
||||
|
||||
// Reload recent feedings
|
||||
await loadRecentFeedings();
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to log feeding');
|
||||
console.error('Failed to save feeding:', err);
|
||||
setError(err.response?.data?.message || 'Failed to save feeding');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const resetForm = () => {
|
||||
setSide('left');
|
||||
setDuration(0);
|
||||
setTimerSeconds(0);
|
||||
setIsTimerRunning(false);
|
||||
setAmount('');
|
||||
setBottleType('formula');
|
||||
setFoodDescription('');
|
||||
setAmountDescription('');
|
||||
setNotes('');
|
||||
};
|
||||
|
||||
const handleDeleteClick = (activityId: string) => {
|
||||
setActivityToDelete(activityId);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDeleteConfirm = async () => {
|
||||
if (!activityToDelete) return;
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
await trackingApi.deleteActivity(activityToDelete);
|
||||
setSuccessMessage('Feeding deleted successfully');
|
||||
setDeleteDialogOpen(false);
|
||||
setActivityToDelete(null);
|
||||
await loadRecentFeedings();
|
||||
} catch (err: any) {
|
||||
console.error('Failed to delete feeding:', err);
|
||||
setError(err.response?.data?.message || 'Failed to delete feeding');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const getFeedingTypeIcon = (type: string) => {
|
||||
switch (type) {
|
||||
case 'breast':
|
||||
return <LocalCafe />;
|
||||
case 'bottle':
|
||||
return <Restaurant />;
|
||||
case 'solid':
|
||||
return <Fastfood />;
|
||||
default:
|
||||
return <Restaurant />;
|
||||
}
|
||||
};
|
||||
|
||||
const getFeedingDetails = (activity: Activity) => {
|
||||
const data = activity.data as FeedingData;
|
||||
|
||||
if (data.feedingType === 'breast') {
|
||||
return `${data.side?.toUpperCase()} - ${data.duration || 0} min`;
|
||||
} else if (data.feedingType === 'bottle') {
|
||||
return `${data.amount || 0} ml - ${data.bottleType}`;
|
||||
} else if (data.feedingType === 'solid') {
|
||||
return `${data.foodDescription}${data.amountDescription ? ` - ${data.amountDescription}` : ''}`;
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
if (childrenLoading) {
|
||||
return (
|
||||
<ProtectedRoute>
|
||||
<AppShell>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
</AppShell>
|
||||
</ProtectedRoute>
|
||||
);
|
||||
}
|
||||
|
||||
if (!familyId || children.length === 0) {
|
||||
return (
|
||||
<ProtectedRoute>
|
||||
<AppShell>
|
||||
<Box>
|
||||
<Alert severity="warning">
|
||||
Please add a child first before tracking feeding activities.
|
||||
</Alert>
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={() => router.push('/children')}
|
||||
sx={{ mt: 2 }}
|
||||
>
|
||||
Go to Children Page
|
||||
</Button>
|
||||
</Box>
|
||||
</AppShell>
|
||||
</ProtectedRoute>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ProtectedRoute>
|
||||
<AppShell>
|
||||
@@ -104,14 +346,8 @@ export default function FeedingTrackPage() {
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{success && (
|
||||
<Alert severity="success" sx={{ mb: 3 }}>
|
||||
Feeding logged successfully!
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 3 }}>
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
@@ -121,133 +357,291 @@ export default function FeedingTrackPage() {
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
<Paper sx={{ p: 3, mb: 3 }}>
|
||||
{/* Timer Section */}
|
||||
<Box sx={{ textAlign: 'center', mb: 4 }}>
|
||||
<Typography variant="h2" fontWeight="600" sx={{ mb: 2 }}>
|
||||
{formatDuration(duration)}
|
||||
</Typography>
|
||||
<Box sx={{ display: 'flex', gap: 2, justifyContent: 'center' }}>
|
||||
{!isTimerRunning ? (
|
||||
<Button
|
||||
variant="contained"
|
||||
size="large"
|
||||
startIcon={<PlayArrow />}
|
||||
onClick={() => setIsTimerRunning(true)}
|
||||
>
|
||||
Start Timer
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="contained"
|
||||
color="error"
|
||||
size="large"
|
||||
startIcon={<Stop />}
|
||||
onClick={() => setIsTimerRunning(false)}
|
||||
>
|
||||
Stop Timer
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box component="form" onSubmit={handleSubmit(onSubmit)}>
|
||||
{/* Feeding Type */}
|
||||
<FormControl component="fieldset" sx={{ mb: 3, width: '100%' }}>
|
||||
<FormLabel component="legend" sx={{ mb: 2 }}>
|
||||
Feeding Type
|
||||
</FormLabel>
|
||||
<RadioGroup row>
|
||||
<FormControlLabel
|
||||
value="breast_left"
|
||||
control={<Radio {...register('type')} />}
|
||||
label="Left Breast"
|
||||
/>
|
||||
<FormControlLabel
|
||||
value="breast_right"
|
||||
control={<Radio {...register('type')} />}
|
||||
label="Right Breast"
|
||||
/>
|
||||
<FormControlLabel
|
||||
value="breast_both"
|
||||
control={<Radio {...register('type')} />}
|
||||
label="Both"
|
||||
/>
|
||||
<FormControlLabel
|
||||
value="bottle"
|
||||
control={<Radio {...register('type')} />}
|
||||
label="Bottle"
|
||||
/>
|
||||
<FormControlLabel
|
||||
value="solid"
|
||||
control={<Radio {...register('type')} />}
|
||||
label="Solid Food"
|
||||
/>
|
||||
</RadioGroup>
|
||||
{/* Child Selector */}
|
||||
{children.length > 1 && (
|
||||
<Paper sx={{ p: 2, mb: 3 }}>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>Select Child</InputLabel>
|
||||
<Select
|
||||
value={selectedChild}
|
||||
onChange={(e) => setSelectedChild(e.target.value)}
|
||||
label="Select Child"
|
||||
>
|
||||
{children.map((child) => (
|
||||
<MenuItem key={child.id} value={child.id}>
|
||||
{child.name}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Amount (for bottle/solid) */}
|
||||
{(feedingType === 'bottle' || feedingType === 'solid') && (
|
||||
<Box sx={{ display: 'flex', gap: 2, mb: 3 }}>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Amount"
|
||||
type="number"
|
||||
{...register('amount', { valueAsNumber: true })}
|
||||
error={!!errors.amount}
|
||||
helperText={errors.amount?.message}
|
||||
/>
|
||||
<FormControl sx={{ minWidth: 120 }}>
|
||||
<RadioGroup row>
|
||||
<FormControlLabel
|
||||
value="ml"
|
||||
control={<Radio {...register('unit')} />}
|
||||
label="ml"
|
||||
/>
|
||||
<FormControlLabel
|
||||
value="oz"
|
||||
control={<Radio {...register('unit')} />}
|
||||
label="oz"
|
||||
/>
|
||||
</RadioGroup>
|
||||
</FormControl>
|
||||
{/* Main Form */}
|
||||
<Paper sx={{ p: 3, mb: 3 }}>
|
||||
{/* Feeding Type Tabs */}
|
||||
<Tabs
|
||||
value={feedingType}
|
||||
onChange={(_, newValue) => setFeedingType(newValue)}
|
||||
sx={{ mb: 3 }}
|
||||
variant="fullWidth"
|
||||
>
|
||||
<Tab label="Breastfeeding" value="breast" icon={<LocalCafe />} iconPosition="start" />
|
||||
<Tab label="Bottle" value="bottle" icon={<Restaurant />} iconPosition="start" />
|
||||
<Tab label="Solid Food" value="solid" icon={<Fastfood />} iconPosition="start" />
|
||||
</Tabs>
|
||||
|
||||
{/* Breastfeeding Form */}
|
||||
{feedingType === 'breast' && (
|
||||
<Box>
|
||||
{/* Timer Display */}
|
||||
<Box sx={{ textAlign: 'center', mb: 4 }}>
|
||||
<Typography variant="h2" fontWeight="600" sx={{ mb: 2 }}>
|
||||
{formatDuration(timerSeconds)}
|
||||
</Typography>
|
||||
<Box sx={{ display: 'flex', gap: 2, justifyContent: 'center' }}>
|
||||
{!isTimerRunning ? (
|
||||
<Button
|
||||
variant="contained"
|
||||
size="large"
|
||||
startIcon={<PlayArrow />}
|
||||
onClick={startTimer}
|
||||
>
|
||||
Start Timer
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="contained"
|
||||
color="error"
|
||||
size="large"
|
||||
startIcon={<Stop />}
|
||||
onClick={stopTimer}
|
||||
>
|
||||
Stop Timer
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outlined"
|
||||
size="large"
|
||||
startIcon={<Refresh />}
|
||||
onClick={resetTimer}
|
||||
>
|
||||
Reset
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Notes */}
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Notes (optional)"
|
||||
multiline
|
||||
rows={3}
|
||||
{...register('notes')}
|
||||
sx={{ mb: 3 }}
|
||||
/>
|
||||
{/* Side Selector */}
|
||||
<FormControl fullWidth sx={{ mb: 3 }}>
|
||||
<InputLabel>Side</InputLabel>
|
||||
<Select
|
||||
value={side}
|
||||
onChange={(e) => setSide(e.target.value as 'left' | 'right' | 'both')}
|
||||
label="Side"
|
||||
>
|
||||
<MenuItem value="left">Left</MenuItem>
|
||||
<MenuItem value="right">Right</MenuItem>
|
||||
<MenuItem value="both">Both</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
{/* Voice Input Button */}
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', mb: 3 }}>
|
||||
<Chip
|
||||
icon={<Mic />}
|
||||
label="Use Voice Input"
|
||||
onClick={() => {/* TODO: Implement voice input */}}
|
||||
sx={{ cursor: 'pointer' }}
|
||||
{/* Manual Duration Input */}
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Duration (minutes)"
|
||||
type="number"
|
||||
value={duration || ''}
|
||||
onChange={(e) => setDuration(parseInt(e.target.value) || 0)}
|
||||
sx={{ mb: 3 }}
|
||||
helperText="Or use the timer above"
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Submit Button */}
|
||||
<Button
|
||||
fullWidth
|
||||
type="submit"
|
||||
variant="contained"
|
||||
size="large"
|
||||
startIcon={<Save />}
|
||||
>
|
||||
Save Feeding
|
||||
</Button>
|
||||
{/* Bottle Form */}
|
||||
{feedingType === 'bottle' && (
|
||||
<Box>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Amount (ml)"
|
||||
type="number"
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(e.target.value)}
|
||||
sx={{ mb: 3 }}
|
||||
/>
|
||||
|
||||
<FormControl fullWidth sx={{ mb: 3 }}>
|
||||
<InputLabel>Type</InputLabel>
|
||||
<Select
|
||||
value={bottleType}
|
||||
onChange={(e) => setBottleType(e.target.value as 'formula' | 'breastmilk' | 'other')}
|
||||
label="Type"
|
||||
>
|
||||
<MenuItem value="formula">Formula</MenuItem>
|
||||
<MenuItem value="breastmilk">Breast Milk</MenuItem>
|
||||
<MenuItem value="other">Other</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Solid Food Form */}
|
||||
{feedingType === 'solid' && (
|
||||
<Box>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Food Description"
|
||||
value={foodDescription}
|
||||
onChange={(e) => setFoodDescription(e.target.value)}
|
||||
sx={{ mb: 3 }}
|
||||
placeholder="e.g., Mashed banana, Rice cereal"
|
||||
/>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Amount (optional)"
|
||||
value={amountDescription}
|
||||
onChange={(e) => setAmountDescription(e.target.value)}
|
||||
sx={{ mb: 3 }}
|
||||
placeholder="e.g., 2 tablespoons, Half bowl"
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Common Notes Field */}
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Notes (optional)"
|
||||
multiline
|
||||
rows={3}
|
||||
value={notes}
|
||||
onChange={(e) => setNotes(e.target.value)}
|
||||
sx={{ mb: 3 }}
|
||||
placeholder="Any additional notes..."
|
||||
/>
|
||||
|
||||
{/* Submit Button */}
|
||||
<Button
|
||||
fullWidth
|
||||
type="button"
|
||||
variant="contained"
|
||||
size="large"
|
||||
startIcon={<Save />}
|
||||
onClick={handleSubmit}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? 'Saving...' : 'Save Feeding'}
|
||||
</Button>
|
||||
</Paper>
|
||||
|
||||
{/* Recent Feedings */}
|
||||
<Paper sx={{ p: 3 }}>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
|
||||
<Typography variant="h6" fontWeight="600">
|
||||
Recent Feedings
|
||||
</Typography>
|
||||
<IconButton onClick={loadRecentFeedings} disabled={feedingsLoading}>
|
||||
<Refresh />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
||||
{feedingsLoading ? (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
|
||||
<CircularProgress size={30} />
|
||||
</Box>
|
||||
) : recentFeedings.length === 0 ? (
|
||||
<Box sx={{ textAlign: 'center', py: 4 }}>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
No feeding activities yet
|
||||
</Typography>
|
||||
</Box>
|
||||
) : (
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
{recentFeedings.map((activity, index) => {
|
||||
const data = activity.data as FeedingData;
|
||||
return (
|
||||
<motion.div
|
||||
key={activity.id}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.2, delay: index * 0.05 }}
|
||||
>
|
||||
<Card variant="outlined">
|
||||
<CardContent>
|
||||
<Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 2 }}>
|
||||
<Box sx={{ mt: 0.5 }}>
|
||||
{getFeedingTypeIcon(data.feedingType)}
|
||||
</Box>
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}>
|
||||
<Typography variant="body1" fontWeight="600">
|
||||
{data.feedingType.charAt(0).toUpperCase() + data.feedingType.slice(1)}
|
||||
</Typography>
|
||||
<Chip
|
||||
label={formatDistanceToNow(new Date(activity.timestamp), { addSuffix: true })}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
/>
|
||||
</Box>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
|
||||
{getFeedingDetails(activity)}
|
||||
</Typography>
|
||||
{activity.notes && (
|
||||
<Typography variant="body2" color="text.secondary" sx={{ fontStyle: 'italic' }}>
|
||||
{activity.notes}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
<Box sx={{ display: 'flex', gap: 0.5 }}>
|
||||
<IconButton
|
||||
size="small"
|
||||
color="error"
|
||||
onClick={() => handleDeleteClick(activity.id)}
|
||||
disabled={loading}
|
||||
>
|
||||
<Delete />
|
||||
</IconButton>
|
||||
</Box>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
)}
|
||||
</Paper>
|
||||
</motion.div>
|
||||
</Box>
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<Dialog
|
||||
open={deleteDialogOpen}
|
||||
onClose={() => setDeleteDialogOpen(false)}
|
||||
>
|
||||
<DialogTitle>Delete Feeding Activity?</DialogTitle>
|
||||
<DialogContent>
|
||||
<DialogContentText>
|
||||
Are you sure you want to delete this feeding activity? This action cannot be undone.
|
||||
</DialogContentText>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setDeleteDialogOpen(false)} disabled={loading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleDeleteConfirm} color="error" disabled={loading}>
|
||||
{loading ? 'Deleting...' : 'Delete'}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
{/* Success Snackbar */}
|
||||
<Snackbar
|
||||
open={!!successMessage}
|
||||
autoHideDuration={3000}
|
||||
onClose={() => setSuccessMessage(null)}
|
||||
message={successMessage}
|
||||
/>
|
||||
</AppShell>
|
||||
</ProtectedRoute>
|
||||
);
|
||||
|
||||
@@ -1,105 +1,352 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
Button,
|
||||
Paper,
|
||||
TextField,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Select,
|
||||
MenuItem,
|
||||
IconButton,
|
||||
Alert,
|
||||
CircularProgress,
|
||||
Card,
|
||||
CardContent,
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
DialogContentText,
|
||||
DialogActions,
|
||||
Chip,
|
||||
FormControl,
|
||||
FormLabel,
|
||||
RadioGroup,
|
||||
FormControlLabel,
|
||||
Radio,
|
||||
Snackbar,
|
||||
} from '@mui/material';
|
||||
import {
|
||||
ArrowBack,
|
||||
Bedtime,
|
||||
WbSunny,
|
||||
Refresh,
|
||||
Save,
|
||||
Mic,
|
||||
Delete,
|
||||
Bedtime,
|
||||
Hotel,
|
||||
DirectionsCar,
|
||||
Chair,
|
||||
Home,
|
||||
} from '@mui/icons-material';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { AppShell } from '@/components/layouts/AppShell/AppShell';
|
||||
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { trackingApi, Activity } from '@/lib/api/tracking';
|
||||
import { childrenApi, Child } from '@/lib/api/children';
|
||||
import { motion } from 'framer-motion';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as z from 'zod';
|
||||
import { format } from 'date-fns';
|
||||
import { formatDistanceToNow, format } from 'date-fns';
|
||||
|
||||
const sleepSchema = z.object({
|
||||
startTime: z.string(),
|
||||
endTime: z.string(),
|
||||
quality: z.enum(['excellent', 'good', 'fair', 'poor']),
|
||||
notes: z.string().optional(),
|
||||
}).refine((data) => new Date(data.endTime) > new Date(data.startTime), {
|
||||
message: 'End time must be after start time',
|
||||
path: ['endTime'],
|
||||
});
|
||||
|
||||
type SleepFormData = z.infer<typeof sleepSchema>;
|
||||
interface SleepData {
|
||||
startTime: string;
|
||||
endTime?: string;
|
||||
quality: 'excellent' | 'good' | 'fair' | 'poor';
|
||||
location: string;
|
||||
isOngoing?: boolean;
|
||||
}
|
||||
|
||||
export default function SleepTrackPage() {
|
||||
const router = useRouter();
|
||||
const { user } = useAuth();
|
||||
const [children, setChildren] = useState<Child[]>([]);
|
||||
const [selectedChild, setSelectedChild] = useState<string>('');
|
||||
|
||||
// Sleep state
|
||||
const [startTime, setStartTime] = useState<string>(
|
||||
format(new Date(), "yyyy-MM-dd'T'HH:mm")
|
||||
);
|
||||
const [endTime, setEndTime] = useState<string>(
|
||||
format(new Date(), "yyyy-MM-dd'T'HH:mm")
|
||||
);
|
||||
const [quality, setQuality] = useState<'excellent' | 'good' | 'fair' | 'poor'>('good');
|
||||
const [location, setLocation] = useState<string>('crib');
|
||||
const [isOngoing, setIsOngoing] = useState<boolean>(false);
|
||||
|
||||
// Common state
|
||||
const [notes, setNotes] = useState<string>('');
|
||||
const [recentSleeps, setRecentSleeps] = useState<Activity[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [childrenLoading, setChildrenLoading] = useState(true);
|
||||
const [sleepsLoading, setSleepsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState(false);
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
setValue,
|
||||
watch,
|
||||
formState: { errors },
|
||||
} = useForm<SleepFormData>({
|
||||
resolver: zodResolver(sleepSchema),
|
||||
defaultValues: {
|
||||
quality: 'good',
|
||||
},
|
||||
});
|
||||
// Delete confirmation dialog
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [activityToDelete, setActivityToDelete] = useState<string | null>(null);
|
||||
|
||||
const startTime = watch('startTime');
|
||||
const endTime = watch('endTime');
|
||||
const familyId = user?.families?.[0]?.familyId;
|
||||
|
||||
// Load children
|
||||
useEffect(() => {
|
||||
if (familyId) {
|
||||
loadChildren();
|
||||
}
|
||||
}, [familyId]);
|
||||
|
||||
// Load recent sleeps when child is selected
|
||||
useEffect(() => {
|
||||
if (selectedChild) {
|
||||
loadRecentSleeps();
|
||||
}
|
||||
}, [selectedChild]);
|
||||
|
||||
const loadChildren = async () => {
|
||||
if (!familyId) return;
|
||||
|
||||
try {
|
||||
setChildrenLoading(true);
|
||||
const childrenData = await childrenApi.getChildren(familyId);
|
||||
setChildren(childrenData);
|
||||
if (childrenData.length > 0) {
|
||||
setSelectedChild(childrenData[0].id);
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('Failed to load children:', err);
|
||||
setError(err.response?.data?.message || 'Failed to load children');
|
||||
} finally {
|
||||
setChildrenLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loadRecentSleeps = async () => {
|
||||
if (!selectedChild) return;
|
||||
|
||||
try {
|
||||
setSleepsLoading(true);
|
||||
const activities = await trackingApi.getActivities(selectedChild, 'sleep');
|
||||
// Sort by timestamp descending and take last 10
|
||||
const sorted = activities.sort((a, b) =>
|
||||
new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
|
||||
).slice(0, 10);
|
||||
setRecentSleeps(sorted);
|
||||
} catch (err: any) {
|
||||
console.error('Failed to load recent sleeps:', err);
|
||||
} finally {
|
||||
setSleepsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const formatDuration = (start: string, end?: string) => {
|
||||
const startDate = new Date(start);
|
||||
const endDate = end ? new Date(end) : new Date();
|
||||
const diffMs = endDate.getTime() - startDate.getTime();
|
||||
|
||||
if (diffMs < 0) return 'Invalid duration';
|
||||
|
||||
const hours = Math.floor(diffMs / (1000 * 60 * 60));
|
||||
const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
|
||||
|
||||
if (hours === 0) {
|
||||
return `${minutes} minute${minutes !== 1 ? 's' : ''}`;
|
||||
} else if (minutes === 0) {
|
||||
return `${hours} hour${hours !== 1 ? 's' : ''}`;
|
||||
} else {
|
||||
return `${hours} hour${hours !== 1 ? 's' : ''} ${minutes} minute${minutes !== 1 ? 's' : ''}`;
|
||||
}
|
||||
};
|
||||
|
||||
const calculateDuration = () => {
|
||||
if (!startTime || !endTime) return null;
|
||||
if (!startTime) return null;
|
||||
if (isOngoing) {
|
||||
return formatDuration(startTime);
|
||||
}
|
||||
if (!endTime) return null;
|
||||
|
||||
const start = new Date(startTime);
|
||||
const end = new Date(endTime);
|
||||
const diff = end.getTime() - start.getTime();
|
||||
if (diff < 0) return null;
|
||||
|
||||
const hours = Math.floor(diff / (1000 * 60 * 60));
|
||||
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
|
||||
return `${hours}h ${minutes}m`;
|
||||
if (end <= start) return null;
|
||||
|
||||
return formatDuration(startTime, endTime);
|
||||
};
|
||||
|
||||
const setStartNow = () => {
|
||||
const now = format(new Date(), "yyyy-MM-dd'T'HH:mm");
|
||||
setValue('startTime', now);
|
||||
setStartTime(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
|
||||
};
|
||||
|
||||
const setEndNow = () => {
|
||||
const now = format(new Date(), "yyyy-MM-dd'T'HH:mm");
|
||||
setValue('endTime', now);
|
||||
setEndTime(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
|
||||
};
|
||||
|
||||
const onSubmit = async (data: SleepFormData) => {
|
||||
setError(null);
|
||||
const handleSubmit = async () => {
|
||||
if (!selectedChild) {
|
||||
setError('Please select a child');
|
||||
return;
|
||||
}
|
||||
|
||||
// Validation
|
||||
if (!startTime) {
|
||||
setError('Please enter start time');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isOngoing && !endTime) {
|
||||
setError('Please enter end time or mark as ongoing');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isOngoing && endTime) {
|
||||
const start = new Date(startTime);
|
||||
const end = new Date(endTime);
|
||||
if (end <= start) {
|
||||
setError('End time must be after start time');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// TODO: Call API to save sleep data
|
||||
console.log('Sleep data:', data);
|
||||
setSuccess(true);
|
||||
setTimeout(() => router.push('/'), 2000);
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const data: SleepData = {
|
||||
startTime,
|
||||
quality,
|
||||
location,
|
||||
isOngoing,
|
||||
};
|
||||
|
||||
if (!isOngoing && endTime) {
|
||||
data.endTime = endTime;
|
||||
}
|
||||
|
||||
await trackingApi.createActivity(selectedChild, {
|
||||
type: 'sleep',
|
||||
timestamp: startTime,
|
||||
data,
|
||||
notes: notes || undefined,
|
||||
});
|
||||
|
||||
setSuccessMessage('Sleep logged successfully!');
|
||||
|
||||
// Reset form
|
||||
resetForm();
|
||||
|
||||
// Reload recent sleeps
|
||||
await loadRecentSleeps();
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to log sleep');
|
||||
console.error('Failed to save sleep:', err);
|
||||
setError(err.response?.data?.message || 'Failed to save sleep');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const resetForm = () => {
|
||||
setStartTime(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
|
||||
setEndTime(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
|
||||
setQuality('good');
|
||||
setLocation('crib');
|
||||
setIsOngoing(false);
|
||||
setNotes('');
|
||||
};
|
||||
|
||||
const handleDeleteClick = (activityId: string) => {
|
||||
setActivityToDelete(activityId);
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDeleteConfirm = async () => {
|
||||
if (!activityToDelete) return;
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
await trackingApi.deleteActivity(activityToDelete);
|
||||
setSuccessMessage('Sleep deleted successfully');
|
||||
setDeleteDialogOpen(false);
|
||||
setActivityToDelete(null);
|
||||
await loadRecentSleeps();
|
||||
} catch (err: any) {
|
||||
console.error('Failed to delete sleep:', err);
|
||||
setError(err.response?.data?.message || 'Failed to delete sleep');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const getLocationIcon = (loc: string) => {
|
||||
switch (loc) {
|
||||
case 'crib':
|
||||
return <Hotel />;
|
||||
case 'bed':
|
||||
return <Bedtime />;
|
||||
case 'stroller':
|
||||
return <DirectionsCar />;
|
||||
case 'carrier':
|
||||
return <Chair />;
|
||||
case 'other':
|
||||
return <Home />;
|
||||
default:
|
||||
return <Hotel />;
|
||||
}
|
||||
};
|
||||
|
||||
const getQualityColor = (qual: string) => {
|
||||
switch (qual) {
|
||||
case 'excellent':
|
||||
return 'success';
|
||||
case 'good':
|
||||
return 'primary';
|
||||
case 'fair':
|
||||
return 'warning';
|
||||
case 'poor':
|
||||
return 'error';
|
||||
default:
|
||||
return 'default';
|
||||
}
|
||||
};
|
||||
|
||||
const getSleepDetails = (activity: Activity) => {
|
||||
const data = activity.data as SleepData;
|
||||
const duration = data.endTime
|
||||
? formatDuration(data.startTime, data.endTime)
|
||||
: data.isOngoing
|
||||
? `Ongoing - ${formatDuration(data.startTime)}`
|
||||
: 'No end time';
|
||||
|
||||
return `${duration} - ${data.location.charAt(0).toUpperCase() + data.location.slice(1)}`;
|
||||
};
|
||||
|
||||
if (childrenLoading) {
|
||||
return (
|
||||
<ProtectedRoute>
|
||||
<AppShell>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
</AppShell>
|
||||
</ProtectedRoute>
|
||||
);
|
||||
}
|
||||
|
||||
if (!familyId || children.length === 0) {
|
||||
return (
|
||||
<ProtectedRoute>
|
||||
<AppShell>
|
||||
<Box>
|
||||
<Alert severity="warning">
|
||||
Please add a child first before tracking sleep activities.
|
||||
</Alert>
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={() => router.push('/children')}
|
||||
sx={{ mt: 2 }}
|
||||
>
|
||||
Go to Children Page
|
||||
</Button>
|
||||
</Box>
|
||||
</AppShell>
|
||||
</ProtectedRoute>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ProtectedRoute>
|
||||
<AppShell>
|
||||
@@ -113,14 +360,8 @@ export default function SleepTrackPage() {
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{success && (
|
||||
<Alert severity="success" sx={{ mb: 3 }}>
|
||||
Sleep logged successfully!
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 3 }}>
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
@@ -130,46 +371,74 @@ export default function SleepTrackPage() {
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
<Paper sx={{ p: 3, mb: 3 }}>
|
||||
<Box component="form" onSubmit={handleSubmit(onSubmit)}>
|
||||
{/* Start Time */}
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 1 }}>
|
||||
<Bedtime color="primary" />
|
||||
<Typography variant="h6" fontWeight="600">
|
||||
Sleep Start
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
|
||||
<TextField
|
||||
fullWidth
|
||||
type="datetime-local"
|
||||
{...register('startTime')}
|
||||
error={!!errors.startTime}
|
||||
helperText={errors.startTime?.message}
|
||||
InputLabelProps={{ shrink: true }}
|
||||
/>
|
||||
<Button variant="outlined" onClick={setStartNow} sx={{ minWidth: 100 }}>
|
||||
Now
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
{/* Child Selector */}
|
||||
{children.length > 1 && (
|
||||
<Paper sx={{ p: 2, mb: 3 }}>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>Select Child</InputLabel>
|
||||
<Select
|
||||
value={selectedChild}
|
||||
onChange={(e) => setSelectedChild(e.target.value)}
|
||||
label="Select Child"
|
||||
>
|
||||
{children.map((child) => (
|
||||
<MenuItem key={child.id} value={child.id}>
|
||||
{child.name}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* End Time */}
|
||||
{/* Main Form */}
|
||||
<Paper sx={{ p: 3, mb: 3 }}>
|
||||
{/* Start Time */}
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<Typography variant="subtitle1" fontWeight="600" sx={{ mb: 1 }}>
|
||||
Sleep Start Time
|
||||
</Typography>
|
||||
<Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
|
||||
<TextField
|
||||
fullWidth
|
||||
type="datetime-local"
|
||||
value={startTime}
|
||||
onChange={(e) => setStartTime(e.target.value)}
|
||||
InputLabelProps={{ shrink: true }}
|
||||
/>
|
||||
<Button variant="outlined" onClick={setStartNow} sx={{ minWidth: 100 }}>
|
||||
Now
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* Ongoing Checkbox */}
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>Sleep Status</InputLabel>
|
||||
<Select
|
||||
value={isOngoing ? 'ongoing' : 'completed'}
|
||||
onChange={(e) => setIsOngoing(e.target.value === 'ongoing')}
|
||||
label="Sleep Status"
|
||||
>
|
||||
<MenuItem value="completed">Completed (has end time)</MenuItem>
|
||||
<MenuItem value="ongoing">Ongoing (still sleeping)</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Box>
|
||||
|
||||
{/* End Time */}
|
||||
{!isOngoing && (
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 1 }}>
|
||||
<WbSunny color="warning" />
|
||||
<Typography variant="h6" fontWeight="600">
|
||||
Wake Up
|
||||
</Typography>
|
||||
</Box>
|
||||
<Typography variant="subtitle1" fontWeight="600" sx={{ mb: 1 }}>
|
||||
Wake Up Time
|
||||
</Typography>
|
||||
<Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
|
||||
<TextField
|
||||
fullWidth
|
||||
type="datetime-local"
|
||||
{...register('endTime')}
|
||||
error={!!errors.endTime}
|
||||
helperText={errors.endTime?.message}
|
||||
value={endTime}
|
||||
onChange={(e) => setEndTime(e.target.value)}
|
||||
InputLabelProps={{ shrink: true }}
|
||||
/>
|
||||
<Button variant="outlined" onClick={setEndNow} sx={{ minWidth: 100 }}>
|
||||
@@ -177,82 +446,189 @@ export default function SleepTrackPage() {
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Duration Display */}
|
||||
{calculateDuration() && (
|
||||
<Box sx={{ mb: 3, textAlign: 'center' }}>
|
||||
<Chip
|
||||
label={`Duration: ${calculateDuration()}`}
|
||||
color="primary"
|
||||
sx={{ fontSize: '1rem', py: 3 }}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Sleep Quality */}
|
||||
<FormControl component="fieldset" sx={{ mb: 3, width: '100%' }}>
|
||||
<FormLabel component="legend" sx={{ mb: 2 }}>
|
||||
Sleep Quality
|
||||
</FormLabel>
|
||||
<RadioGroup row>
|
||||
<FormControlLabel
|
||||
value="excellent"
|
||||
control={<Radio {...register('quality')} />}
|
||||
label="Excellent"
|
||||
/>
|
||||
<FormControlLabel
|
||||
value="good"
|
||||
control={<Radio {...register('quality')} />}
|
||||
label="Good"
|
||||
/>
|
||||
<FormControlLabel
|
||||
value="fair"
|
||||
control={<Radio {...register('quality')} />}
|
||||
label="Fair"
|
||||
/>
|
||||
<FormControlLabel
|
||||
value="poor"
|
||||
control={<Radio {...register('quality')} />}
|
||||
label="Poor"
|
||||
/>
|
||||
</RadioGroup>
|
||||
</FormControl>
|
||||
|
||||
{/* Notes */}
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Notes (optional)"
|
||||
multiline
|
||||
rows={3}
|
||||
{...register('notes')}
|
||||
sx={{ mb: 3 }}
|
||||
placeholder="Any disruptions, dreams, or observations..."
|
||||
/>
|
||||
|
||||
{/* Voice Input Button */}
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', mb: 3 }}>
|
||||
{/* Duration Display */}
|
||||
{calculateDuration() && (
|
||||
<Box sx={{ mb: 3, textAlign: 'center' }}>
|
||||
<Chip
|
||||
icon={<Mic />}
|
||||
label="Use Voice Input"
|
||||
onClick={() => {/* TODO: Implement voice input */}}
|
||||
sx={{ cursor: 'pointer' }}
|
||||
label={`Duration: ${calculateDuration()}`}
|
||||
color="primary"
|
||||
sx={{ fontSize: '1rem', py: 3 }}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Submit Button */}
|
||||
<Button
|
||||
fullWidth
|
||||
type="submit"
|
||||
variant="contained"
|
||||
size="large"
|
||||
startIcon={<Save />}
|
||||
{/* Sleep Quality */}
|
||||
<FormControl fullWidth sx={{ mb: 3 }}>
|
||||
<InputLabel>Sleep Quality</InputLabel>
|
||||
<Select
|
||||
value={quality}
|
||||
onChange={(e) => setQuality(e.target.value as 'excellent' | 'good' | 'fair' | 'poor')}
|
||||
label="Sleep Quality"
|
||||
>
|
||||
Save Sleep Session
|
||||
</Button>
|
||||
<MenuItem value="excellent">Excellent</MenuItem>
|
||||
<MenuItem value="good">Good</MenuItem>
|
||||
<MenuItem value="fair">Fair</MenuItem>
|
||||
<MenuItem value="poor">Poor</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
{/* Location */}
|
||||
<FormControl fullWidth sx={{ mb: 3 }}>
|
||||
<InputLabel>Location</InputLabel>
|
||||
<Select
|
||||
value={location}
|
||||
onChange={(e) => setLocation(e.target.value)}
|
||||
label="Location"
|
||||
>
|
||||
<MenuItem value="crib">Crib</MenuItem>
|
||||
<MenuItem value="bed">Bed</MenuItem>
|
||||
<MenuItem value="stroller">Stroller</MenuItem>
|
||||
<MenuItem value="carrier">Carrier</MenuItem>
|
||||
<MenuItem value="other">Other</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
{/* Common Notes Field */}
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Notes (optional)"
|
||||
multiline
|
||||
rows={3}
|
||||
value={notes}
|
||||
onChange={(e) => setNotes(e.target.value)}
|
||||
sx={{ mb: 3 }}
|
||||
placeholder="Any disruptions, dreams, or observations..."
|
||||
/>
|
||||
|
||||
{/* Submit Button */}
|
||||
<Button
|
||||
fullWidth
|
||||
type="button"
|
||||
variant="contained"
|
||||
size="large"
|
||||
startIcon={<Save />}
|
||||
onClick={handleSubmit}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? 'Saving...' : 'Save Sleep'}
|
||||
</Button>
|
||||
</Paper>
|
||||
|
||||
{/* Recent Sleeps */}
|
||||
<Paper sx={{ p: 3 }}>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
|
||||
<Typography variant="h6" fontWeight="600">
|
||||
Recent Sleep Activities
|
||||
</Typography>
|
||||
<IconButton onClick={loadRecentSleeps} disabled={sleepsLoading}>
|
||||
<Refresh />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
||||
{sleepsLoading ? (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
|
||||
<CircularProgress size={30} />
|
||||
</Box>
|
||||
) : recentSleeps.length === 0 ? (
|
||||
<Box sx={{ textAlign: 'center', py: 4 }}>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
No sleep activities yet
|
||||
</Typography>
|
||||
</Box>
|
||||
) : (
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
{recentSleeps.map((activity, index) => {
|
||||
const data = activity.data as SleepData;
|
||||
return (
|
||||
<motion.div
|
||||
key={activity.id}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.2, delay: index * 0.05 }}
|
||||
>
|
||||
<Card variant="outlined">
|
||||
<CardContent>
|
||||
<Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 2 }}>
|
||||
<Box sx={{ mt: 0.5 }}>
|
||||
{getLocationIcon(data.location)}
|
||||
</Box>
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5, flexWrap: 'wrap' }}>
|
||||
<Typography variant="body1" fontWeight="600">
|
||||
Sleep
|
||||
</Typography>
|
||||
<Chip
|
||||
label={data.quality.charAt(0).toUpperCase() + data.quality.slice(1)}
|
||||
size="small"
|
||||
color={getQualityColor(data.quality) as any}
|
||||
/>
|
||||
<Chip
|
||||
label={formatDistanceToNow(new Date(activity.timestamp), { addSuffix: true })}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
/>
|
||||
</Box>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
|
||||
{getSleepDetails(activity)}
|
||||
</Typography>
|
||||
{activity.notes && (
|
||||
<Typography variant="body2" color="text.secondary" sx={{ fontStyle: 'italic' }}>
|
||||
{activity.notes}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
<Box sx={{ display: 'flex', gap: 0.5 }}>
|
||||
<IconButton
|
||||
size="small"
|
||||
color="error"
|
||||
onClick={() => handleDeleteClick(activity.id)}
|
||||
disabled={loading}
|
||||
>
|
||||
<Delete />
|
||||
</IconButton>
|
||||
</Box>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
)}
|
||||
</Paper>
|
||||
</motion.div>
|
||||
</Box>
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<Dialog
|
||||
open={deleteDialogOpen}
|
||||
onClose={() => setDeleteDialogOpen(false)}
|
||||
>
|
||||
<DialogTitle>Delete Sleep Activity?</DialogTitle>
|
||||
<DialogContent>
|
||||
<DialogContentText>
|
||||
Are you sure you want to delete this sleep activity? This action cannot be undone.
|
||||
</DialogContentText>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setDeleteDialogOpen(false)} disabled={loading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleDeleteConfirm} color="error" disabled={loading}>
|
||||
{loading ? 'Deleting...' : 'Delete'}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
{/* Success Snackbar */}
|
||||
<Snackbar
|
||||
open={!!successMessage}
|
||||
autoHideDuration={3000}
|
||||
onClose={() => setSuccessMessage(null)}
|
||||
message={successMessage}
|
||||
/>
|
||||
</AppShell>
|
||||
</ProtectedRoute>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user