Implemented automatic unit conversions for feeding and medicine tracking: - Created UnitInput component for automatic ml↔oz conversions - Updated Feeding page to use UnitInput for bottle amounts - Updated Medicine page to use UnitInput for liquid medicine dosages - All values stored in metric (ml) in database - Display values automatically converted based on user's measurement preference - Supports voice input with proper unit handling Component features: - Automatic conversion between metric and imperial - User preference-based display - Consistent metric storage - Type safety with TypeScript 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
582 lines
19 KiB
TypeScript
582 lines
19 KiB
TypeScript
'use client';
|
|
|
|
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,
|
|
Snackbar,
|
|
} from '@mui/material';
|
|
import {
|
|
ArrowBack,
|
|
Save,
|
|
MedicalServices,
|
|
Delete,
|
|
Refresh,
|
|
ChildCare,
|
|
Add,
|
|
} from '@mui/icons-material';
|
|
import { useRouter } from 'next/navigation';
|
|
import { AppShell } from '@/components/layouts/AppShell/AppShell';
|
|
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
|
|
import { withErrorBoundary } from '@/components/common/ErrorFallbacks';
|
|
import { useAuth } from '@/lib/auth/AuthContext';
|
|
import { trackingApi, Activity } from '@/lib/api/tracking';
|
|
import { childrenApi, Child } from '@/lib/api/children';
|
|
import { VoiceInputButton } from '@/components/voice/VoiceInputButton';
|
|
import { FormSkeleton, ActivityListSkeleton } from '@/components/common/LoadingSkeletons';
|
|
import { motion } from 'framer-motion';
|
|
import { useLocalizedDate } from '@/hooks/useLocalizedDate';
|
|
import { useTranslation } from '@/hooks/useTranslation';
|
|
import { UnitInput } from '@/components/forms/UnitInput';
|
|
|
|
interface MedicineData {
|
|
medicineName: string;
|
|
dosage: string;
|
|
unit?: string;
|
|
route?: 'oral' | 'topical' | 'injection' | 'other';
|
|
reason?: string;
|
|
}
|
|
|
|
function MedicineTrackPage() {
|
|
const router = useRouter();
|
|
const { user } = useAuth();
|
|
const { t } = useTranslation('tracking');
|
|
const { formatDistanceToNow } = useLocalizedDate();
|
|
const [children, setChildren] = useState<Child[]>([]);
|
|
const [selectedChild, setSelectedChild] = useState<string>('');
|
|
|
|
// Medicine state
|
|
const [medicineName, setMedicineName] = useState<string>('');
|
|
const [dosage, setDosage] = useState<number>(0); // For ml/liquid - stored in ml
|
|
const [dosageText, setDosageText] = useState<string>(''); // For non-liquid units
|
|
const [unit, setUnit] = useState<string>('ml');
|
|
const [route, setRoute] = useState<'oral' | 'topical' | 'injection' | 'other'>('oral');
|
|
const [reason, setReason] = useState<string>('');
|
|
|
|
// Common state
|
|
const [notes, setNotes] = useState<string>('');
|
|
const [recentMedicines, setRecentMedicines] = useState<Activity[]>([]);
|
|
const [loading, setLoading] = useState(false);
|
|
const [childrenLoading, setChildrenLoading] = useState(true);
|
|
const [medicinesLoading, setMedicinesLoading] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
|
|
|
// Delete confirmation dialog
|
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
|
const [activityToDelete, setActivityToDelete] = useState<string | null>(null);
|
|
|
|
const familyId = user?.families?.[0]?.familyId;
|
|
|
|
// Load children
|
|
useEffect(() => {
|
|
if (familyId) {
|
|
loadChildren();
|
|
}
|
|
}, [familyId]);
|
|
|
|
// Load recent medicines when child is selected
|
|
useEffect(() => {
|
|
if (selectedChild) {
|
|
loadRecentMedicines();
|
|
}
|
|
}, [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 loadRecentMedicines = async () => {
|
|
if (!selectedChild) return;
|
|
|
|
try {
|
|
setMedicinesLoading(true);
|
|
const activities = await trackingApi.getActivities(selectedChild, 'medicine');
|
|
// 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);
|
|
setRecentMedicines(sorted);
|
|
} catch (err: any) {
|
|
console.error('Failed to load recent medicines:', err);
|
|
} finally {
|
|
setMedicinesLoading(false);
|
|
}
|
|
};
|
|
|
|
const handleSubmit = async () => {
|
|
if (!selectedChild) {
|
|
setError('Please select a child');
|
|
return;
|
|
}
|
|
|
|
// Validation
|
|
if (!medicineName) {
|
|
setError('Please enter medicine name');
|
|
return;
|
|
}
|
|
|
|
const dosageValue = unit === 'ml' ? dosage : dosageText;
|
|
if (!dosageValue || (unit === 'ml' && dosage === 0) || (unit !== 'ml' && !dosageText)) {
|
|
setError('Please enter dosage');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
setLoading(true);
|
|
setError(null);
|
|
|
|
const data: MedicineData = {
|
|
medicineName,
|
|
dosage: unit === 'ml' ? dosage.toString() : dosageText,
|
|
unit,
|
|
route,
|
|
reason: reason || undefined,
|
|
};
|
|
|
|
await trackingApi.createActivity(selectedChild, {
|
|
type: 'medicine',
|
|
timestamp: new Date().toISOString(),
|
|
data,
|
|
notes: notes || undefined,
|
|
});
|
|
|
|
setSuccessMessage('Medicine logged successfully!');
|
|
|
|
// Reset form
|
|
resetForm();
|
|
|
|
// Reload recent medicines
|
|
await loadRecentMedicines();
|
|
} catch (err: any) {
|
|
console.error('Failed to save medicine:', err);
|
|
setError(err.response?.data?.message || 'Failed to save medicine');
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const resetForm = () => {
|
|
setMedicineName('');
|
|
setDosage(0);
|
|
setDosageText('');
|
|
setUnit('ml');
|
|
setRoute('oral');
|
|
setReason('');
|
|
setNotes('');
|
|
};
|
|
|
|
const handleDeleteClick = (activityId: string) => {
|
|
setActivityToDelete(activityId);
|
|
setDeleteDialogOpen(true);
|
|
};
|
|
|
|
const handleDeleteConfirm = async () => {
|
|
if (!activityToDelete) return;
|
|
|
|
try {
|
|
setLoading(true);
|
|
await trackingApi.deleteActivity(activityToDelete);
|
|
setSuccessMessage('Medicine deleted successfully');
|
|
setDeleteDialogOpen(false);
|
|
setActivityToDelete(null);
|
|
await loadRecentMedicines();
|
|
} catch (err: any) {
|
|
console.error('Failed to delete medicine:', err);
|
|
setError(err.response?.data?.message || 'Failed to delete medicine');
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const getMedicineDetails = (activity: Activity) => {
|
|
const data = activity.data as MedicineData;
|
|
let details = `${data.dosage} ${data.unit || ''}`;
|
|
if (data.route) {
|
|
details += ` - ${data.route.charAt(0).toUpperCase() + data.route.slice(1)}`;
|
|
}
|
|
if (data.reason) {
|
|
details += ` - ${data.reason}`;
|
|
}
|
|
return details;
|
|
};
|
|
|
|
if (childrenLoading) {
|
|
return (
|
|
<ProtectedRoute>
|
|
<AppShell>
|
|
<Box>
|
|
<Typography variant="h4" fontWeight="600" sx={{ mb: 3 }}>
|
|
{t('activities.medicine')}
|
|
</Typography>
|
|
<Paper sx={{ p: 3, mb: 3 }}>
|
|
<FormSkeleton />
|
|
</Paper>
|
|
<Typography variant="h6" fontWeight="600" sx={{ mb: 2 }}>
|
|
{t('activities.medicine')}
|
|
</Typography>
|
|
<ActivityListSkeleton count={3} />
|
|
</Box>
|
|
</AppShell>
|
|
</ProtectedRoute>
|
|
);
|
|
}
|
|
|
|
if (!familyId || children.length === 0) {
|
|
return (
|
|
<ProtectedRoute>
|
|
<AppShell>
|
|
<Card>
|
|
<CardContent sx={{ textAlign: 'center', py: 8 }}>
|
|
<ChildCare sx={{ fontSize: 64, color: 'text.secondary', mb: 2 }} />
|
|
<Typography variant="h6" color="text.secondary" gutterBottom>
|
|
No Children Added
|
|
</Typography>
|
|
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
|
|
You need to add a child before you can track medicine activities
|
|
</Typography>
|
|
<Button
|
|
variant="contained"
|
|
startIcon={<Add />}
|
|
onClick={() => router.push('/children')}
|
|
>
|
|
Add Child
|
|
</Button>
|
|
</CardContent>
|
|
</Card>
|
|
</AppShell>
|
|
</ProtectedRoute>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<ProtectedRoute>
|
|
<AppShell>
|
|
<Box>
|
|
<Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
|
|
<IconButton onClick={() => router.back()} sx={{ mr: 2 }}>
|
|
<ArrowBack />
|
|
</IconButton>
|
|
<Typography variant="h4" fontWeight="600" sx={{ flex: 1 }}>
|
|
{t('activities.medicine')}
|
|
</Typography>
|
|
<VoiceInputButton
|
|
onTranscript={(transcript) => {
|
|
console.log('[Medicine] Voice transcript:', transcript);
|
|
}}
|
|
onClassifiedIntent={(result) => {
|
|
if (result.intent === 'medicine' && result.structuredData) {
|
|
const data = result.structuredData;
|
|
// Auto-fill form with voice data
|
|
if (data.medicineName) setMedicineName(data.medicineName);
|
|
if (data.unit) setUnit(data.unit);
|
|
if (data.dosage) {
|
|
if (data.unit === 'ml') {
|
|
setDosage(typeof data.dosage === 'number' ? data.dosage : parseFloat(data.dosage));
|
|
} else {
|
|
setDosageText(data.dosage.toString());
|
|
}
|
|
}
|
|
if (data.route) setRoute(data.route);
|
|
if (data.reason) setReason(data.reason);
|
|
}
|
|
}}
|
|
size="medium"
|
|
/>
|
|
</Box>
|
|
|
|
{error && (
|
|
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
|
|
{error}
|
|
</Alert>
|
|
)}
|
|
|
|
<motion.div
|
|
initial={{ opacity: 0, y: 20 }}
|
|
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 sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
|
|
<MedicalServices sx={{ fontSize: 36, color: 'error.main', mr: 2 }} />
|
|
<Typography variant="h6" fontWeight="600">
|
|
Medicine Information
|
|
</Typography>
|
|
</Box>
|
|
|
|
<TextField
|
|
fullWidth
|
|
label="Medicine Name"
|
|
value={medicineName}
|
|
onChange={(e) => setMedicineName(e.target.value)}
|
|
sx={{ mb: 3 }}
|
|
placeholder="e.g., Acetaminophen, Ibuprofen"
|
|
required
|
|
/>
|
|
|
|
<Box sx={{ display: 'flex', gap: 2, mb: 3 }}>
|
|
{unit === 'ml' ? (
|
|
<UnitInput
|
|
fullWidth
|
|
label="Dosage"
|
|
type="volume"
|
|
value={dosage}
|
|
onChange={(metricValue) => setDosage(metricValue)}
|
|
required
|
|
/>
|
|
) : (
|
|
<TextField
|
|
fullWidth
|
|
label="Dosage"
|
|
value={dosageText}
|
|
onChange={(e) => setDosageText(e.target.value)}
|
|
placeholder="e.g., 5, 2.5"
|
|
required
|
|
/>
|
|
)}
|
|
|
|
<FormControl fullWidth>
|
|
<InputLabel>Unit</InputLabel>
|
|
<Select
|
|
value={unit}
|
|
onChange={(e) => {
|
|
const newUnit = e.target.value;
|
|
setUnit(newUnit);
|
|
// Reset dosage when switching units
|
|
if (newUnit === 'ml') {
|
|
setDosageText('');
|
|
} else {
|
|
setDosage(0);
|
|
}
|
|
}}
|
|
label="Unit"
|
|
>
|
|
<MenuItem value="ml">ml</MenuItem>
|
|
<MenuItem value="mg">mg</MenuItem>
|
|
<MenuItem value="tsp">tsp</MenuItem>
|
|
<MenuItem value="tbsp">tbsp</MenuItem>
|
|
<MenuItem value="drops">drops</MenuItem>
|
|
<MenuItem value="tablet">tablet(s)</MenuItem>
|
|
</Select>
|
|
</FormControl>
|
|
</Box>
|
|
|
|
<FormControl fullWidth sx={{ mb: 3 }}>
|
|
<InputLabel>Route</InputLabel>
|
|
<Select
|
|
value={route}
|
|
onChange={(e) => setRoute(e.target.value as 'oral' | 'topical' | 'injection' | 'other')}
|
|
label="Route"
|
|
>
|
|
<MenuItem value="oral">Oral</MenuItem>
|
|
<MenuItem value="topical">Topical</MenuItem>
|
|
<MenuItem value="injection">Injection</MenuItem>
|
|
<MenuItem value="other">Other</MenuItem>
|
|
</Select>
|
|
</FormControl>
|
|
|
|
<TextField
|
|
fullWidth
|
|
label="Reason (optional)"
|
|
value={reason}
|
|
onChange={(e) => setReason(e.target.value)}
|
|
sx={{ mb: 3 }}
|
|
placeholder="e.g., Fever, Pain, Allergy"
|
|
/>
|
|
|
|
<TextField
|
|
fullWidth
|
|
label={t('feeding.notes')}
|
|
multiline
|
|
rows={3}
|
|
value={notes}
|
|
onChange={(e) => setNotes(e.target.value)}
|
|
sx={{ mb: 3 }}
|
|
placeholder={t('feeding.placeholders.notes')}
|
|
/>
|
|
|
|
<Button
|
|
fullWidth
|
|
type="button"
|
|
variant="contained"
|
|
size="large"
|
|
startIcon={<Save />}
|
|
onClick={handleSubmit}
|
|
disabled={loading}
|
|
>
|
|
{loading ? t('activities.medicine') : t('activities.medicine')}
|
|
</Button>
|
|
</Paper>
|
|
|
|
{/* Recent Medicines */}
|
|
<Paper sx={{ p: 3 }}>
|
|
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
|
|
<Typography variant="h6" fontWeight="600">
|
|
{t('activities.medicine')}
|
|
</Typography>
|
|
<IconButton onClick={loadRecentMedicines} disabled={medicinesLoading}>
|
|
<Refresh />
|
|
</IconButton>
|
|
</Box>
|
|
|
|
{medicinesLoading ? (
|
|
<Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
|
|
<CircularProgress size={30} />
|
|
</Box>
|
|
) : recentMedicines.length === 0 ? (
|
|
<Box sx={{ textAlign: 'center', py: 4 }}>
|
|
<Typography variant="body2" color="text.secondary">
|
|
{t('noEntries')}
|
|
</Typography>
|
|
</Box>
|
|
) : (
|
|
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
|
|
{recentMedicines.map((activity, index) => {
|
|
const data = activity.data as MedicineData;
|
|
if (!data || !data.medicineName) {
|
|
console.warn('[Medicine] Activity missing medicineName:', activity);
|
|
return null;
|
|
}
|
|
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 }}>
|
|
<MedicalServices color="error" />
|
|
</Box>
|
|
<Box sx={{ flex: 1 }}>
|
|
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}>
|
|
<Typography variant="body1" fontWeight="600">
|
|
{data.medicineName}
|
|
</Typography>
|
|
<Chip
|
|
label={formatDistanceToNow(new Date(activity.timestamp), { addSuffix: true })}
|
|
size="small"
|
|
variant="outlined"
|
|
/>
|
|
</Box>
|
|
<Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
|
|
{getMedicineDetails(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>{t('deleteEntry')}</DialogTitle>
|
|
<DialogContent>
|
|
<DialogContentText>
|
|
{t('confirmDelete')}
|
|
</DialogContentText>
|
|
</DialogContent>
|
|
<DialogActions>
|
|
<Button onClick={() => setDeleteDialogOpen(false)} disabled={loading}>
|
|
Cancel
|
|
</Button>
|
|
<Button onClick={handleDeleteConfirm} color="error" disabled={loading}>
|
|
{loading ? t('deleteEntry') : t('deleteEntry')}
|
|
</Button>
|
|
</DialogActions>
|
|
</Dialog>
|
|
|
|
{/* Success Snackbar */}
|
|
<Snackbar
|
|
open={!!successMessage}
|
|
autoHideDuration={3000}
|
|
onClose={() => setSuccessMessage(null)}
|
|
message={successMessage}
|
|
/>
|
|
</AppShell>
|
|
</ProtectedRoute>
|
|
);
|
|
}
|
|
|
|
export default withErrorBoundary(MedicineTrackPage, 'form');
|