Add backend API integration for Children, Family, and Tracking

API Services Created:
- lib/api/children.ts: Full CRUD operations for children management
- lib/api/families.ts: Family member management and invitations
- lib/api/tracking.ts: Activity tracking (feeding, sleep, diaper, etc.)

Children Page Implementation:
- Fetch and display children from backend API
- Add/Edit child with modal dialog (ChildDialog component)
- Delete child with confirmation (DeleteConfirmDialog component)
- Age calculation from birthDate
- Loading states and error handling
- Responsive card grid layout
- Gender-based avatar colors
- Empty state for no children

AuthContext Updates:
- Added families array to User interface
- Includes familyId for API calls

Components:
- components/children/ChildDialog.tsx: Form for add/edit child
- components/children/DeleteConfirmDialog.tsx: Delete confirmation

All components use Material-UI theme and include proper TypeScript types

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
andupetcu
2025-09-30 22:10:00 +03:00
parent b62342fe2d
commit 6894fa8edf
7 changed files with 712 additions and 43 deletions

View File

@@ -1,13 +1,150 @@
'use client';
import { Box, Typography, Grid, Card, CardContent, Button } from '@mui/material';
import { Add, ChildCare } from '@mui/icons-material';
import { useRouter } from 'next/navigation';
import { useState, useEffect } from 'react';
import {
Box,
Typography,
Grid,
Card,
CardContent,
Button,
Avatar,
IconButton,
CircularProgress,
Alert,
Chip,
CardActions,
} from '@mui/material';
import { Add, ChildCare, Edit, Delete, Cake } 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, CreateChildData } from '@/lib/api/children';
import { ChildDialog } from '@/components/children/ChildDialog';
import { DeleteConfirmDialog } from '@/components/children/DeleteConfirmDialog';
import { motion } from 'framer-motion';
export default function ChildrenPage() {
const router = useRouter();
const { user } = useAuth();
const [children, setChildren] = useState<Child[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string>('');
const [dialogOpen, setDialogOpen] = useState(false);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [selectedChild, setSelectedChild] = useState<Child | null>(null);
const [childToDelete, setChildToDelete] = useState<Child | null>(null);
const [actionLoading, setActionLoading] = useState(false);
// Get familyId from user
const familyId = user?.families?.[0]?.familyId;
useEffect(() => {
if (familyId) {
fetchChildren();
} else {
setLoading(false);
setError('No family found. Please complete onboarding first.');
}
}, [familyId]);
const fetchChildren = async () => {
if (!familyId) return;
try {
setLoading(true);
setError('');
const data = await childrenApi.getChildren(familyId);
setChildren(data);
} catch (err: any) {
console.error('Failed to fetch children:', err);
setError(err.response?.data?.message || 'Failed to load children');
} finally {
setLoading(false);
}
};
const handleAddChild = () => {
setSelectedChild(null);
setDialogOpen(true);
};
const handleEditChild = (child: Child) => {
setSelectedChild(child);
setDialogOpen(true);
};
const handleDeleteClick = (child: Child) => {
setChildToDelete(child);
setDeleteDialogOpen(true);
};
const handleSubmit = async (data: CreateChildData) => {
if (!familyId) {
throw new Error('No family ID found');
}
try {
setActionLoading(true);
if (selectedChild) {
await childrenApi.updateChild(selectedChild.id, data);
} else {
await childrenApi.createChild(familyId, data);
}
await fetchChildren();
setDialogOpen(false);
} catch (err: any) {
console.error('Failed to save child:', err);
throw new Error(err.response?.data?.message || 'Failed to save child');
} finally {
setActionLoading(false);
}
};
const handleDeleteConfirm = async () => {
if (!childToDelete) return;
try {
setActionLoading(true);
await childrenApi.deleteChild(childToDelete.id);
await fetchChildren();
setDeleteDialogOpen(false);
setChildToDelete(null);
} catch (err: any) {
console.error('Failed to delete child:', err);
setError(err.response?.data?.message || 'Failed to delete child');
} finally {
setActionLoading(false);
}
};
const calculateAge = (birthDate: string): string => {
const birth = new Date(birthDate);
const today = new Date();
let years = today.getFullYear() - birth.getFullYear();
let months = today.getMonth() - birth.getMonth();
if (months < 0) {
years--;
months += 12;
}
if (today.getDate() < birth.getDate()) {
months--;
if (months < 0) {
years--;
months += 12;
}
}
if (years === 0) {
return `${months} month${months !== 1 ? 's' : ''}`;
} else if (months === 0) {
return `${years} year${years !== 1 ? 's' : ''}`;
} else {
return `${years} year${years !== 1 ? 's' : ''}, ${months} month${months !== 1 ? 's' : ''}`;
}
};
return (
<ProtectedRoute>
@@ -25,12 +162,24 @@ export default function ChildrenPage() {
<Button
variant="contained"
startIcon={<Add />}
onClick={() => router.push('/children/new')}
onClick={handleAddChild}
disabled={loading || !familyId}
>
Add Child
</Button>
</Box>
{error && (
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError('')}>
{error}
</Alert>
)}
{loading ? (
<Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
<CircularProgress />
</Box>
) : children.length === 0 ? (
<Grid container spacing={3}>
<Grid item xs={12}>
<Card>
@@ -45,7 +194,8 @@ export default function ChildrenPage() {
<Button
variant="contained"
startIcon={<Add />}
onClick={() => router.push('/children/new')}
onClick={handleAddChild}
disabled={!familyId}
>
Add First Child
</Button>
@@ -53,7 +203,103 @@ export default function ChildrenPage() {
</Card>
</Grid>
</Grid>
) : (
<Grid container spacing={3}>
{children.map((child, index) => (
<Grid item xs={12} sm={6} md={4} key={child.id}>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: index * 0.1 }}
>
<Card
sx={{
height: '100%',
display: 'flex',
flexDirection: 'column',
}}
>
<CardContent sx={{ flexGrow: 1 }}>
<Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
<Avatar
src={child.photoUrl}
sx={{
width: 60,
height: 60,
bgcolor: child.gender === 'male' ? '#B6D7FF' : '#FFB6C1',
mr: 2,
}}
>
<ChildCare sx={{ fontSize: 32 }} />
</Avatar>
<Box sx={{ flexGrow: 1 }}>
<Typography variant="h6" fontWeight="600">
{child.name}
</Typography>
<Chip
label={child.gender}
size="small"
sx={{ textTransform: 'capitalize', mt: 0.5 }}
/>
</Box>
</Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
<Cake sx={{ fontSize: 20, color: 'text.secondary' }} />
<Typography variant="body2" color="text.secondary">
{new Date(child.birthDate).toLocaleDateString()}
</Typography>
</Box>
<Typography
variant="body2"
color="primary"
fontWeight="600"
sx={{ mt: 1 }}
>
Age: {calculateAge(child.birthDate)}
</Typography>
</CardContent>
<CardActions sx={{ justifyContent: 'flex-end', pt: 0 }}>
<IconButton
size="small"
onClick={() => handleEditChild(child)}
color="primary"
>
<Edit />
</IconButton>
<IconButton
size="small"
onClick={() => handleDeleteClick(child)}
color="error"
>
<Delete />
</IconButton>
</CardActions>
</Card>
</motion.div>
</Grid>
))}
</Grid>
)}
</Box>
<ChildDialog
open={dialogOpen}
onClose={() => setDialogOpen(false)}
onSubmit={handleSubmit}
child={selectedChild}
isLoading={actionLoading}
/>
<DeleteConfirmDialog
open={deleteDialogOpen}
onClose={() => setDeleteDialogOpen(false)}
onConfirm={handleDeleteConfirm}
childName={childToDelete?.name || ''}
isLoading={actionLoading}
/>
</AppShell>
</ProtectedRoute>
);

View File

@@ -0,0 +1,157 @@
'use client';
import { useState, useEffect } from 'react';
import {
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
TextField,
MenuItem,
Box,
Alert,
} from '@mui/material';
import { Child, CreateChildData } from '@/lib/api/children';
interface ChildDialogProps {
open: boolean;
onClose: () => void;
onSubmit: (data: CreateChildData) => Promise<void>;
child?: Child | null;
isLoading?: boolean;
}
export function ChildDialog({ open, onClose, onSubmit, child, isLoading = false }: ChildDialogProps) {
const [formData, setFormData] = useState<CreateChildData>({
name: '',
birthDate: '',
gender: 'male',
photoUrl: '',
});
const [error, setError] = useState<string>('');
useEffect(() => {
if (child) {
setFormData({
name: child.name,
birthDate: child.birthDate.split('T')[0], // Convert to YYYY-MM-DD format
gender: child.gender,
photoUrl: child.photoUrl || '',
});
} else {
setFormData({
name: '',
birthDate: '',
gender: 'male',
photoUrl: '',
});
}
setError('');
}, [child, open]);
const handleChange = (field: keyof CreateChildData) => (
e: React.ChangeEvent<HTMLInputElement>
) => {
setFormData({ ...formData, [field]: e.target.value });
};
const handleSubmit = async () => {
setError('');
// Validation
if (!formData.name.trim()) {
setError('Please enter a name');
return;
}
if (!formData.birthDate) {
setError('Please select a birth date');
return;
}
// Check if birth date is in the future
const selectedDate = new Date(formData.birthDate);
const today = new Date();
today.setHours(0, 0, 0, 0);
if (selectedDate > today) {
setError('Birth date cannot be in the future');
return;
}
try {
await onSubmit(formData);
onClose();
} catch (err: any) {
setError(err.message || 'Failed to save child');
}
};
return (
<Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
<DialogTitle>{child ? 'Edit Child' : 'Add Child'}</DialogTitle>
<DialogContent>
<Box sx={{ pt: 2, display: 'flex', flexDirection: 'column', gap: 2 }}>
{error && (
<Alert severity="error" onClose={() => setError('')}>
{error}
</Alert>
)}
<TextField
label="Name"
value={formData.name}
onChange={handleChange('name')}
fullWidth
required
autoFocus
disabled={isLoading}
/>
<TextField
label="Birth Date"
type="date"
value={formData.birthDate}
onChange={handleChange('birthDate')}
fullWidth
required
InputLabelProps={{
shrink: true,
}}
disabled={isLoading}
/>
<TextField
label="Gender"
value={formData.gender}
onChange={handleChange('gender')}
fullWidth
required
select
disabled={isLoading}
>
<MenuItem value="male">Male</MenuItem>
<MenuItem value="female">Female</MenuItem>
<MenuItem value="other">Other</MenuItem>
</TextField>
<TextField
label="Photo URL (Optional)"
value={formData.photoUrl}
onChange={handleChange('photoUrl')}
fullWidth
placeholder="https://example.com/photo.jpg"
disabled={isLoading}
/>
</Box>
</DialogContent>
<DialogActions>
<Button onClick={onClose} disabled={isLoading}>
Cancel
</Button>
<Button onClick={handleSubmit} variant="contained" disabled={isLoading}>
{isLoading ? 'Saving...' : child ? 'Update' : 'Add'}
</Button>
</DialogActions>
</Dialog>
);
}

View File

@@ -0,0 +1,52 @@
'use client';
import {
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
Typography,
} from '@mui/material';
import { Warning } from '@mui/icons-material';
interface DeleteConfirmDialogProps {
open: boolean;
onClose: () => void;
onConfirm: () => void;
childName: string;
isLoading?: boolean;
}
export function DeleteConfirmDialog({
open,
onClose,
onConfirm,
childName,
isLoading = false,
}: DeleteConfirmDialogProps) {
return (
<Dialog open={open} onClose={onClose} maxWidth="xs" fullWidth>
<DialogTitle sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Warning color="warning" />
Confirm Delete
</DialogTitle>
<DialogContent>
<Typography variant="body1">
Are you sure you want to delete <strong>{childName}</strong>?
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mt: 2 }}>
This action cannot be undone. All associated data will be permanently removed.
</Typography>
</DialogContent>
<DialogActions>
<Button onClick={onClose} disabled={isLoading}>
Cancel
</Button>
<Button onClick={onConfirm} color="error" variant="contained" disabled={isLoading}>
{isLoading ? 'Deleting...' : 'Delete'}
</Button>
</DialogActions>
</Dialog>
);
}

View File

@@ -0,0 +1,60 @@
import apiClient from './client';
export interface Child {
id: string;
familyId: string;
name: string;
birthDate: string;
gender: 'male' | 'female' | 'other';
photoUrl?: string;
medicalInfo?: any;
createdAt: string;
}
export interface CreateChildData {
name: string;
birthDate: string;
gender: 'male' | 'female' | 'other';
photoUrl?: string;
medicalInfo?: any;
}
export interface UpdateChildData extends Partial<CreateChildData> {}
export const childrenApi = {
// Get all children for the authenticated user
getChildren: async (familyId?: string): Promise<Child[]> => {
const params = familyId ? { familyId } : {};
const response = await apiClient.get('/api/v1/children', { params });
return response.data.data.children;
},
// Get a specific child
getChild: async (id: string): Promise<Child> => {
const response = await apiClient.get(`/api/v1/children/${id}`);
return response.data.data.child;
},
// Create a new child
createChild: async (familyId: string, data: CreateChildData): Promise<Child> => {
const response = await apiClient.post(`/api/v1/children?familyId=${familyId}`, data);
return response.data.data.child;
},
// Update a child
updateChild: async (id: string, data: UpdateChildData): Promise<Child> => {
const response = await apiClient.patch(`/api/v1/children/${id}`, data);
return response.data.data.child;
},
// Delete a child
deleteChild: async (id: string): Promise<void> => {
await apiClient.delete(`/api/v1/children/${id}`);
},
// Get child's age
getChildAge: async (id: string): Promise<{ ageInMonths: number; ageInYears: number; remainingMonths: number }> => {
const response = await apiClient.get(`/api/v1/children/${id}/age`);
return response.data.data;
},
};

View File

@@ -0,0 +1,69 @@
import apiClient from './client';
export interface Family {
id: string;
name: string;
shareCode: string;
createdBy: string;
subscriptionTier: string;
members?: FamilyMember[];
}
export interface FamilyMember {
id: string;
userId: string;
familyId: string;
role: 'parent' | 'caregiver' | 'viewer';
permissions: any;
user?: {
id: string;
name: string;
email: string;
};
}
export interface InviteMemberData {
email: string;
role: 'parent' | 'caregiver' | 'viewer';
}
export interface JoinFamilyData {
shareCode: string;
}
export const familiesApi = {
// Get a specific family
getFamily: async (familyId: string): Promise<Family> => {
const response = await apiClient.get(`/api/v1/families/${familyId}`);
return response.data.data.family;
},
// Get family members
getFamilyMembers: async (familyId: string): Promise<FamilyMember[]> => {
const response = await apiClient.get(`/api/v1/families/${familyId}/members`);
return response.data.data.members;
},
// Invite a family member
inviteMember: async (familyId: string, data: InviteMemberData): Promise<any> => {
const response = await apiClient.post(`/api/v1/families/invite?familyId=${familyId}`, data);
return response.data.data.invitation;
},
// Join a family using share code
joinFamily: async (data: JoinFamilyData): Promise<FamilyMember> => {
const response = await apiClient.post('/api/v1/families/join', data);
return response.data.data.member;
},
// Update member role
updateMemberRole: async (familyId: string, userId: string, role: string): Promise<FamilyMember> => {
const response = await apiClient.patch(`/api/v1/families/${familyId}/members/${userId}/role`, { role });
return response.data.data.member;
},
// Remove a family member
removeMember: async (familyId: string, userId: string): Promise<void> => {
await apiClient.delete(`/api/v1/families/${familyId}/members/${userId}`);
},
};

View File

@@ -0,0 +1,80 @@
import apiClient from './client';
export type ActivityType = 'feeding' | 'sleep' | 'diaper' | 'medication' | 'milestone' | 'note';
export interface Activity {
id: string;
childId: string;
type: ActivityType;
timestamp: string;
data: any;
notes?: string;
loggedBy: string;
createdAt: string;
}
export interface CreateActivityData {
type: ActivityType;
timestamp: string;
data: any;
notes?: string;
}
export interface UpdateActivityData extends Partial<CreateActivityData> {}
export interface DailySummary {
date: string;
feedingCount: number;
sleepTotalMinutes: number;
diaperCount: number;
activities: Activity[];
}
export const trackingApi = {
// Get all activities for a child
getActivities: async (
childId: string,
type?: ActivityType,
startDate?: string,
endDate?: string
): Promise<Activity[]> => {
const params: any = { childId };
if (type) params.type = type;
if (startDate) params.startDate = startDate;
if (endDate) params.endDate = endDate;
const response = await apiClient.get('/api/v1/activities', { params });
return response.data.data.activities;
},
// Get a specific activity
getActivity: async (id: string): Promise<Activity> => {
const response = await apiClient.get(`/api/v1/activities/${id}`);
return response.data.data.activity;
},
// Create a new activity
createActivity: async (childId: string, data: CreateActivityData): Promise<Activity> => {
const response = await apiClient.post(`/api/v1/activities?childId=${childId}`, data);
return response.data.data.activity;
},
// Update an activity
updateActivity: async (id: string, data: UpdateActivityData): Promise<Activity> => {
const response = await apiClient.patch(`/api/v1/activities/${id}`, data);
return response.data.data.activity;
},
// Delete an activity
deleteActivity: async (id: string): Promise<void> => {
await apiClient.delete(`/api/v1/activities/${id}`);
},
// Get daily summary
getDailySummary: async (childId: string, date: string): Promise<DailySummary> => {
const response = await apiClient.get('/api/v1/activities/daily-summary', {
params: { childId, date },
});
return response.data.data;
},
};

View File

@@ -10,6 +10,11 @@ export interface User {
email: string;
name: string;
role: string;
families?: Array<{
id: string;
familyId: string;
role: string;
}>;
}
export interface LoginCredentials {