Implement Family page with full backend integration

Features:
- Fetch and display family details and members
- Family share code with copy-to-clipboard functionality
- Invite family members via email with role selection
- Join another family using share code
- Remove family members with confirmation
- Visual indicators for current user
- Role-based chip colors (Parent/Caregiver/Viewer)
- Loading states and error handling
- Empty state when no members exist
- Success notifications via Snackbar

Components Created:
- components/family/InviteMemberDialog.tsx: Invite form with email and role
- components/family/JoinFamilyDialog.tsx: Join family via share code
- components/family/RemoveMemberDialog.tsx: Remove member confirmation

All features fully integrated with backend API using familiesApi

🤖 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:14:56 +03:00
parent 6894fa8edf
commit 286887440e
4 changed files with 603 additions and 102 deletions

View File

@@ -1,126 +1,354 @@
'use client';
import { Box, Typography, Grid, Card, CardContent, Button, Avatar, Chip } from '@mui/material';
import { PersonAdd, ContentCopy, People } from '@mui/icons-material';
import { useState, useEffect } from 'react';
import {
Box,
Typography,
Grid,
Card,
CardContent,
Button,
Avatar,
Chip,
CircularProgress,
Alert,
IconButton,
Divider,
Snackbar,
} from '@mui/material';
import { PersonAdd, ContentCopy, People, Delete, GroupAdd } from '@mui/icons-material';
import { useAuth } from '@/lib/auth/AuthContext';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import { familiesApi, Family, FamilyMember, InviteMemberData, JoinFamilyData } from '@/lib/api/families';
import { InviteMemberDialog } from '@/components/family/InviteMemberDialog';
import { JoinFamilyDialog } from '@/components/family/JoinFamilyDialog';
import { RemoveMemberDialog } from '@/components/family/RemoveMemberDialog';
import { motion } from 'framer-motion';
export default function FamilyPage() {
const { user } = useAuth();
const { user, refreshUser } = useAuth();
const [family, setFamily] = useState<Family | null>(null);
const [members, setMembers] = useState<FamilyMember[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string>('');
const [inviteDialogOpen, setInviteDialogOpen] = useState(false);
const [joinDialogOpen, setJoinDialogOpen] = useState(false);
const [removeDialogOpen, setRemoveDialogOpen] = useState(false);
const [memberToRemove, setMemberToRemove] = useState<FamilyMember | null>(null);
const [actionLoading, setActionLoading] = useState(false);
const [snackbar, setSnackbar] = useState({ open: false, message: '' });
const handleInvite = () => {
// Invite functionality to be implemented
alert('Family invitation feature coming soon!');
// Get familyId from user
const familyId = user?.families?.[0]?.familyId;
useEffect(() => {
if (familyId) {
fetchFamilyData();
} else {
setLoading(false);
setError('No family found. Please complete onboarding first.');
}
}, [familyId]);
const fetchFamilyData = async () => {
if (!familyId) return;
try {
setLoading(true);
setError('');
const [familyData, membersData] = await Promise.all([
familiesApi.getFamily(familyId),
familiesApi.getFamilyMembers(familyId),
]);
setFamily(familyData);
setMembers(membersData);
} catch (err: any) {
console.error('Failed to fetch family data:', err);
setError(err.response?.data?.message || 'Failed to load family information');
} finally {
setLoading(false);
}
};
const handleCopyCode = () => {
// Copy share code to clipboard
navigator.clipboard.writeText('FAMILY-CODE-123');
alert('Family code copied to clipboard!');
const handleCopyCode = async () => {
if (!family?.shareCode) return;
try {
await navigator.clipboard.writeText(family.shareCode);
setSnackbar({ open: true, message: 'Share code copied to clipboard!' });
} catch (err) {
setSnackbar({ open: true, message: 'Failed to copy share code' });
}
};
const handleInviteMember = async (data: InviteMemberData) => {
if (!familyId) {
throw new Error('No family ID found');
}
try {
setActionLoading(true);
await familiesApi.inviteMember(familyId, data);
setSnackbar({ open: true, message: 'Invitation sent successfully!' });
await fetchFamilyData();
setInviteDialogOpen(false);
} catch (err: any) {
console.error('Failed to invite member:', err);
throw new Error(err.response?.data?.message || 'Failed to send invitation');
} finally {
setActionLoading(false);
}
};
const handleJoinFamily = async (data: JoinFamilyData) => {
try {
setActionLoading(true);
await familiesApi.joinFamily(data);
setSnackbar({ open: true, message: 'Successfully joined family!' });
await refreshUser();
await fetchFamilyData();
setJoinDialogOpen(false);
} catch (err: any) {
console.error('Failed to join family:', err);
throw new Error(err.response?.data?.message || 'Failed to join family');
} finally {
setActionLoading(false);
}
};
const handleRemoveClick = (member: FamilyMember) => {
setMemberToRemove(member);
setRemoveDialogOpen(true);
};
const handleRemoveConfirm = async () => {
if (!familyId || !memberToRemove) return;
try {
setActionLoading(true);
await familiesApi.removeMember(familyId, memberToRemove.userId);
setSnackbar({ open: true, message: 'Member removed successfully' });
await fetchFamilyData();
setRemoveDialogOpen(false);
setMemberToRemove(null);
} catch (err: any) {
console.error('Failed to remove member:', err);
setError(err.response?.data?.message || 'Failed to remove member');
} finally {
setActionLoading(false);
}
};
const getRoleColor = (role: string): 'primary' | 'secondary' | 'default' | 'success' | 'warning' | 'info' => {
switch (role) {
case 'parent':
return 'primary';
case 'caregiver':
return 'secondary';
case 'viewer':
return 'info';
default:
return 'default';
}
};
const isCurrentUser = (userId: string) => {
return user?.id === userId;
};
return (
<ProtectedRoute>
<AppShell>
<Box>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
<Box>
<Typography variant="h4" fontWeight="600" gutterBottom>
Family
</Typography>
<Typography variant="body1" color="text.secondary">
Manage your family members and share access
</Typography>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
<Box>
<Typography variant="h4" fontWeight="600" gutterBottom>
Family
</Typography>
<Typography variant="body1" color="text.secondary">
Manage your family members and share access
</Typography>
</Box>
<Box sx={{ display: 'flex', gap: 1 }}>
<Button
variant="outlined"
startIcon={<GroupAdd />}
onClick={() => setJoinDialogOpen(true)}
disabled={loading}
>
Join Family
</Button>
<Button
variant="contained"
startIcon={<PersonAdd />}
onClick={() => setInviteDialogOpen(true)}
disabled={loading || !familyId}
>
Invite Member
</Button>
</Box>
</Box>
{error && (
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError('')}>
{error}
</Alert>
)}
{loading ? (
<Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
<CircularProgress />
</Box>
) : (
<Grid container spacing={3}>
{/* Family Share Code */}
{family && (
<Grid item xs={12}>
<Card>
<CardContent>
<Typography variant="h6" fontWeight="600" gutterBottom>
Family Share Code
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
Share this code with family members to give them access to your family's data
</Typography>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2, flexWrap: 'wrap' }}>
<Chip
label={family.shareCode}
sx={{
fontSize: '1.1rem',
fontWeight: 600,
py: 2.5,
px: 1,
}}
color="primary"
/>
<Button
variant="outlined"
startIcon={<ContentCopy />}
onClick={handleCopyCode}
>
Copy Code
</Button>
</Box>
</CardContent>
</Card>
</Grid>
)}
{/* Family Members */}
<Grid item xs={12}>
<Card>
<CardContent>
<Typography variant="h6" fontWeight="600" gutterBottom sx={{ mb: 3 }}>
Family Members ({members.length})
</Typography>
{members.length === 0 ? (
<Box sx={{ textAlign: 'center', py: 4 }}>
<People sx={{ fontSize: 48, color: 'text.secondary', mb: 2 }} />
<Typography variant="body2" color="text.secondary" gutterBottom>
No family members yet
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
Invite family members to collaborate on child care
</Typography>
<Button
variant="outlined"
startIcon={<PersonAdd />}
onClick={() => setInviteDialogOpen(true)}
>
Invite First Member
</Button>
</Box>
) : (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
{members.map((member, index) => (
<motion.div
key={member.id}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.2, delay: index * 0.05 }}
>
<Box>
{index > 0 && <Divider sx={{ mb: 2 }} />}
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
<Avatar
sx={{
bgcolor: isCurrentUser(member.userId) ? 'primary.main' : 'secondary.main',
}}
>
{member.user?.name?.charAt(0).toUpperCase() || 'U'}
</Avatar>
<Box sx={{ flex: 1 }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography variant="body1" fontWeight="600">
{member.user?.name || 'Unknown User'}
</Typography>
{isCurrentUser(member.userId) && (
<Chip label="You" size="small" color="success" />
)}
</Box>
<Typography variant="body2" color="text.secondary">
{member.user?.email || 'No email'}
</Typography>
</Box>
<Chip
label={member.role.charAt(0).toUpperCase() + member.role.slice(1)}
color={getRoleColor(member.role)}
size="small"
/>
{!isCurrentUser(member.userId) && (
<IconButton
size="small"
onClick={() => handleRemoveClick(member)}
color="error"
>
<Delete />
</IconButton>
)}
</Box>
</Box>
</motion.div>
))}
</Box>
)}
</CardContent>
</Card>
</Grid>
</Grid>
)}
</Box>
<Button
variant="contained"
startIcon={<PersonAdd />}
onClick={handleInvite}
>
Invite Member
</Button>
</Box>
<Grid container spacing={3}>
{/* Family Share Code */}
<Grid item xs={12}>
<Card>
<CardContent>
<Typography variant="h6" fontWeight="600" gutterBottom>
Family Share Code
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
Share this code with family members to give them access to your family's data
</Typography>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
<Chip
label="FAMILY-CODE-123"
sx={{
fontSize: '1.1rem',
fontWeight: 600,
py: 2.5,
px: 1,
}}
/>
<Button
variant="outlined"
startIcon={<ContentCopy />}
onClick={handleCopyCode}
>
Copy Code
</Button>
</Box>
</CardContent>
</Card>
</Grid>
<InviteMemberDialog
open={inviteDialogOpen}
onClose={() => setInviteDialogOpen(false)}
onSubmit={handleInviteMember}
isLoading={actionLoading}
/>
{/* Family Members */}
<Grid item xs={12}>
<Card>
<CardContent>
<Typography variant="h6" fontWeight="600" gutterBottom sx={{ mb: 3 }}>
Family Members
</Typography>
<JoinFamilyDialog
open={joinDialogOpen}
onClose={() => setJoinDialogOpen(false)}
onSubmit={handleJoinFamily}
isLoading={actionLoading}
/>
{/* Current User */}
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
<Avatar sx={{ bgcolor: 'primary.main' }}>
{user?.name?.charAt(0).toUpperCase()}
</Avatar>
<Box sx={{ flex: 1 }}>
<Typography variant="body1" fontWeight="600">
{user?.name}
</Typography>
<Typography variant="body2" color="text.secondary">
{user?.email}
</Typography>
</Box>
<Chip label="Admin" color="primary" size="small" />
</Box>
<RemoveMemberDialog
open={removeDialogOpen}
onClose={() => setRemoveDialogOpen(false)}
onConfirm={handleRemoveConfirm}
memberName={memberToRemove?.user?.name || ''}
isLoading={actionLoading}
/>
{/* Empty State */}
<Box sx={{ textAlign: 'center', py: 4, borderTop: '1px solid', borderColor: 'divider' }}>
<People sx={{ fontSize: 48, color: 'text.secondary', mb: 2 }} />
<Typography variant="body2" color="text.secondary" gutterBottom>
No other family members yet
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
Invite family members to collaborate on child care
</Typography>
<Button
variant="outlined"
startIcon={<PersonAdd />}
onClick={handleInvite}
>
Invite First Member
</Button>
</Box>
</CardContent>
</Card>
</Grid>
</Grid>
</Box>
<Snackbar
open={snackbar.open}
autoHideDuration={4000}
onClose={() => setSnackbar({ ...snackbar, open: false })}
message={snackbar.message}
/>
</AppShell>
</ProtectedRoute>
);

View File

@@ -0,0 +1,126 @@
'use client';
import { useState, useEffect } from 'react';
import {
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
TextField,
MenuItem,
Box,
Alert,
} from '@mui/material';
import { InviteMemberData } from '@/lib/api/families';
interface InviteMemberDialogProps {
open: boolean;
onClose: () => void;
onSubmit: (data: InviteMemberData) => Promise<void>;
isLoading?: boolean;
}
export function InviteMemberDialog({
open,
onClose,
onSubmit,
isLoading = false,
}: InviteMemberDialogProps) {
const [formData, setFormData] = useState<InviteMemberData>({
email: '',
role: 'viewer',
});
const [error, setError] = useState<string>('');
useEffect(() => {
if (open) {
setFormData({
email: '',
role: 'viewer',
});
setError('');
}
}, [open]);
const handleChange = (field: keyof InviteMemberData) => (
e: React.ChangeEvent<HTMLInputElement>
) => {
setFormData({ ...formData, [field]: e.target.value });
};
const handleSubmit = async () => {
setError('');
// Validation
if (!formData.email.trim()) {
setError('Please enter an email address');
return;
}
// Basic email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(formData.email)) {
setError('Please enter a valid email address');
return;
}
try {
await onSubmit(formData);
onClose();
} catch (err: any) {
setError(err.message || 'Failed to invite member');
}
};
return (
<Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
<DialogTitle>Invite Family Member</DialogTitle>
<DialogContent>
<Box sx={{ pt: 2, display: 'flex', flexDirection: 'column', gap: 2 }}>
{error && (
<Alert severity="error" onClose={() => setError('')}>
{error}
</Alert>
)}
<TextField
label="Email Address"
type="email"
value={formData.email}
onChange={handleChange('email')}
fullWidth
required
autoFocus
disabled={isLoading}
placeholder="member@example.com"
helperText="Enter the email address of the person you want to invite"
/>
<TextField
label="Role"
value={formData.role}
onChange={handleChange('role')}
fullWidth
required
select
disabled={isLoading}
helperText="Select the access level for this member"
>
<MenuItem value="parent">Parent - Full access to all features</MenuItem>
<MenuItem value="caregiver">Caregiver - Can manage daily activities</MenuItem>
<MenuItem value="viewer">Viewer - Can only view information</MenuItem>
</TextField>
</Box>
</DialogContent>
<DialogActions>
<Button onClick={onClose} disabled={isLoading}>
Cancel
</Button>
<Button onClick={handleSubmit} variant="contained" disabled={isLoading}>
{isLoading ? 'Sending...' : 'Send Invitation'}
</Button>
</DialogActions>
</Dialog>
);
}

View File

@@ -0,0 +1,95 @@
'use client';
import { useState, useEffect } from 'react';
import {
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
TextField,
Box,
Alert,
Typography,
} from '@mui/material';
import { JoinFamilyData } from '@/lib/api/families';
interface JoinFamilyDialogProps {
open: boolean;
onClose: () => void;
onSubmit: (data: JoinFamilyData) => Promise<void>;
isLoading?: boolean;
}
export function JoinFamilyDialog({
open,
onClose,
onSubmit,
isLoading = false,
}: JoinFamilyDialogProps) {
const [shareCode, setShareCode] = useState<string>('');
const [error, setError] = useState<string>('');
useEffect(() => {
if (open) {
setShareCode('');
setError('');
}
}, [open]);
const handleSubmit = async () => {
setError('');
// Validation
if (!shareCode.trim()) {
setError('Please enter a share code');
return;
}
try {
await onSubmit({ shareCode: shareCode.trim() });
onClose();
} catch (err: any) {
setError(err.message || 'Failed to join family');
}
};
return (
<Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
<DialogTitle>Join a Family</DialogTitle>
<DialogContent>
<Box sx={{ pt: 2, display: 'flex', flexDirection: 'column', gap: 2 }}>
{error && (
<Alert severity="error" onClose={() => setError('')}>
{error}
</Alert>
)}
<Typography variant="body2" color="text.secondary">
Enter the share code provided by the family administrator to join their family.
</Typography>
<TextField
label="Share Code"
value={shareCode}
onChange={(e) => setShareCode(e.target.value)}
fullWidth
required
autoFocus
disabled={isLoading}
placeholder="Enter family share code"
helperText="Ask a family member for their share code"
/>
</Box>
</DialogContent>
<DialogActions>
<Button onClick={onClose} disabled={isLoading}>
Cancel
</Button>
<Button onClick={handleSubmit} variant="contained" disabled={isLoading}>
{isLoading ? 'Joining...' : 'Join Family'}
</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 RemoveMemberDialogProps {
open: boolean;
onClose: () => void;
onConfirm: () => void;
memberName: string;
isLoading?: boolean;
}
export function RemoveMemberDialog({
open,
onClose,
onConfirm,
memberName,
isLoading = false,
}: RemoveMemberDialogProps) {
return (
<Dialog open={open} onClose={onClose} maxWidth="xs" fullWidth>
<DialogTitle sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Warning color="warning" />
Remove Family Member
</DialogTitle>
<DialogContent>
<Typography variant="body1">
Are you sure you want to remove <strong>{memberName}</strong> from your family?
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mt: 2 }}>
This member will lose access to all family data and activities.
</Typography>
</DialogContent>
<DialogActions>
<Button onClick={onClose} disabled={isLoading}>
Cancel
</Button>
<Button onClick={onConfirm} color="error" variant="contained" disabled={isLoading}>
{isLoading ? 'Removing...' : 'Remove Member'}
</Button>
</DialogActions>
</Dialog>
);
}