Three workstreams, all backend+frontend (per scope decisions): Dose logging + real adherence (backend + frontend): * log_dose now returns the created dose (201 + body) instead of an empty 201. * get_adherence implemented for real: queries the medication_doses collection over the last 30 days, counts taken vs total, computes the rate. The previous implementation hardcoded zeros. Removed the dead calculate_adherence stub. * Frontend: fixed DoseLog type to match backend MedicationDose (taken:bool, loggedAt, camelCase); added AdherenceStats + LogDoseRequest types; logDose() + getAdherence() in api.ts; loadAdherence/logDose actions in the medication store (adherence cache keyed by med id); new DoseLogger component (Taken/ Skipped buttons + LinearProgress adherence bar) embedded in each MedicationManager card. Profile management (backend + frontend): * New GET/PUT /api/profiles/me endpoints (ProfileResponse excludes encryption fields; find_by_user_id + update_name on ProfileRepository). * Register auto-creates a default 'patient' profile (deterministic profile_id = profile_<user_id>) — this is the contract the frontend relies on. * Frontend: Profile type; getProfile()/updateProfileName() in api.ts; useProfileStore; new ProfileEditor component (view/edit name, shows role) as a 4th Dashboard tab. * Resolved the MedicationManager profile_id TODO: now derives profile_<user_id> instead of the 'default' fallback. * NOTE: profile name is stored plaintext (the model anticipates encryption via nameIv/nameAuthTag but no crypto layer is implemented yet — TODO). Vitest tests: * Added @testing-library/user-event; setupTests clears localStorage + cleanup between tests; new test/mockStore.ts helper (mocks the co-located stores, handles both selector and no-selector call patterns). * 5 test files, 20 tests: SeverityChip (4), useMedicationStore actions incl. loadMedications/createMedication/logDose (4), MedicationManager render+dialog (5), InteractionsChecker selection+results (4), HealthStats table+dialog (3). Verified: backend cargo fmt/build/clippy 0 warnings, 19 unit tests pass; frontend npm build clean, 20 vitest tests pass. Solaria round-trip confirmed: profile auto-created on register (GET /profiles/me), PUT updates name, dose log returns the dose body, adherence computes 66.7% for 2-taken/1-skipped. KNOWN FOLLOW-UP (separate task): the backend Medication list response is deeply nested + camelCase + stores fields inside medicationData.data; the frontend Medication type assumes flat top-level snake_case fields. This pre-dates Phase 3c and affects the whole MedicationManager — needs a backend serialization fix or a frontend adapter.
351 lines
11 KiB
TypeScript
351 lines
11 KiB
TypeScript
import { useEffect, useState, type FC } from 'react';
|
|
import {
|
|
Box,
|
|
Button,
|
|
Card,
|
|
CardContent,
|
|
CardActions,
|
|
Chip,
|
|
CircularProgress,
|
|
Dialog,
|
|
DialogActions,
|
|
DialogContent,
|
|
DialogTitle,
|
|
Alert,
|
|
IconButton,
|
|
List,
|
|
ListItem,
|
|
ListItemText,
|
|
MenuItem,
|
|
Stack,
|
|
TextField,
|
|
Typography,
|
|
} from '@mui/material';
|
|
import EditIcon from '@mui/icons-material/Edit';
|
|
import DeleteIcon from '@mui/icons-material/Delete';
|
|
import AddIcon from '@mui/icons-material/Add';
|
|
import { useMedicationStore, useAuthStore } from '../../store/useStore';
|
|
import type {
|
|
Medication,
|
|
CreateMedicationRequest,
|
|
UpdateMedicationRequest,
|
|
} from '../../types/api';
|
|
import { DoseLogger } from './DoseLogger';
|
|
|
|
const ROUTES = ['oral', 'topical', 'injection', 'inhalation', 'other'] as const;
|
|
|
|
const emptyCreate: CreateMedicationRequest = {
|
|
name: '',
|
|
dosage: '',
|
|
frequency: '',
|
|
route: 'oral',
|
|
profile_id: 'default',
|
|
};
|
|
|
|
export const MedicationManager: FC = () => {
|
|
const {
|
|
medications,
|
|
isLoading,
|
|
error,
|
|
loadMedications,
|
|
createMedication,
|
|
updateMedication,
|
|
deleteMedication,
|
|
clearError,
|
|
} = useMedicationStore();
|
|
const user = useAuthStore((s) => s.user);
|
|
|
|
const [createOpen, setCreateOpen] = useState(false);
|
|
const [createForm, setCreateForm] = useState<CreateMedicationRequest>(emptyCreate);
|
|
const [editTarget, setEditTarget] = useState<Medication | null>(null);
|
|
const [editForm, setEditForm] = useState<UpdateMedicationRequest>({});
|
|
const [deleteTarget, setDeleteTarget] = useState<Medication | null>(null);
|
|
const [saving, setSaving] = useState(false);
|
|
|
|
useEffect(() => {
|
|
loadMedications();
|
|
}, [loadMedications]);
|
|
|
|
const openCreate = () => {
|
|
// profile_id is deterministic: profile_<user_id>. The backend auto-creates
|
|
// this profile on register, so the id always resolves to a real profile.
|
|
const profileId = user?.profile_id ?? `profile_${user?.user_id ?? 'default'}`;
|
|
setCreateForm({
|
|
...emptyCreate,
|
|
profile_id: profileId,
|
|
});
|
|
setCreateOpen(true);
|
|
};
|
|
|
|
const submitCreate = async () => {
|
|
setSaving(true);
|
|
try {
|
|
await createMedication(createForm);
|
|
setCreateOpen(false);
|
|
} catch {
|
|
/* error surfaced via store */
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
};
|
|
|
|
const openEdit = (med: Medication) => {
|
|
setEditTarget(med);
|
|
setEditForm({
|
|
name: med.name,
|
|
dosage: med.dosage,
|
|
frequency: med.frequency,
|
|
instructions: med.instructions,
|
|
active: med.active,
|
|
});
|
|
};
|
|
|
|
const submitEdit = async () => {
|
|
if (!editTarget?.medication_id) return;
|
|
setSaving(true);
|
|
try {
|
|
await updateMedication(editTarget.medication_id, editForm);
|
|
setEditTarget(null);
|
|
} catch {
|
|
/* error surfaced via store */
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
};
|
|
|
|
const confirmDelete = async () => {
|
|
if (!deleteTarget?.medication_id) return;
|
|
setSaving(true);
|
|
try {
|
|
await deleteMedication(deleteTarget.medication_id);
|
|
setDeleteTarget(null);
|
|
} catch {
|
|
/* error surfaced via store */
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<Box>
|
|
<Stack direction="row" justifyContent="space-between" alignItems="center" sx={{ mb: 2 }}>
|
|
<Typography variant="h6">Medications</Typography>
|
|
<Button variant="contained" startIcon={<AddIcon />} onClick={openCreate}>
|
|
Add
|
|
</Button>
|
|
</Stack>
|
|
|
|
{error && (
|
|
<Alert severity="error" sx={{ mb: 2 }} onClose={clearError}>
|
|
{error}
|
|
</Alert>
|
|
)}
|
|
|
|
{isLoading ? (
|
|
<Box display="flex" justifyContent="center" py={4}>
|
|
<CircularProgress />
|
|
</Box>
|
|
) : medications.length === 0 ? (
|
|
<Typography color="text.secondary" sx={{ py: 4, textAlign: 'center' }}>
|
|
No medications yet — add one.
|
|
</Typography>
|
|
) : (
|
|
<List disablePadding>
|
|
{medications.map((med) => (
|
|
<ListItem
|
|
key={med.medication_id}
|
|
disableGutters
|
|
sx={{ mb: 1.5 }}
|
|
>
|
|
<Card sx={{ width: '100%' }}>
|
|
<CardContent sx={{ pb: 1 }}>
|
|
<Stack direction="row" justifyContent="space-between" alignItems="flex-start">
|
|
<Box>
|
|
<Typography variant="subtitle1" component="span" fontWeight={600}>
|
|
{med.name}
|
|
</Typography>{' '}
|
|
<Typography component="span" color="text.secondary">
|
|
{med.dosage} · {med.frequency}
|
|
</Typography>
|
|
<Box sx={{ mt: 0.5 }}>
|
|
<Chip
|
|
size="small"
|
|
label={med.active ? 'active' : 'inactive'}
|
|
color={med.active ? 'success' : 'default'}
|
|
variant="outlined"
|
|
/>
|
|
</Box>
|
|
{med.instructions && (
|
|
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
|
|
{med.instructions}
|
|
</Typography>
|
|
)}
|
|
{med.medication_id && <DoseLogger medicationId={med.medication_id} />}
|
|
</Box>
|
|
</Stack>
|
|
</CardContent>
|
|
<CardActions sx={{ justifyContent: 'flex-end' }}>
|
|
<IconButton size="small" onClick={() => openEdit(med)} aria-label="edit">
|
|
<EditIcon fontSize="small" />
|
|
</IconButton>
|
|
<IconButton
|
|
size="small"
|
|
onClick={() => setDeleteTarget(med)}
|
|
aria-label="delete"
|
|
color="error"
|
|
>
|
|
<DeleteIcon fontSize="small" />
|
|
</IconButton>
|
|
</CardActions>
|
|
</Card>
|
|
</ListItem>
|
|
))}
|
|
</List>
|
|
)}
|
|
|
|
{/* Create dialog */}
|
|
<Dialog open={createOpen} onClose={() => setCreateOpen(false)} fullWidth maxWidth="sm">
|
|
<DialogTitle>Add medication</DialogTitle>
|
|
<DialogContent>
|
|
<Stack spacing={2} sx={{ mt: 1 }}>
|
|
<TextField
|
|
label="Name"
|
|
required
|
|
fullWidth
|
|
value={createForm.name}
|
|
onChange={(e) => setCreateForm({ ...createForm, name: e.target.value })}
|
|
/>
|
|
<Stack direction="row" spacing={2}>
|
|
<TextField
|
|
label="Dosage"
|
|
required
|
|
fullWidth
|
|
value={createForm.dosage}
|
|
onChange={(e) => setCreateForm({ ...createForm, dosage: e.target.value })}
|
|
/>
|
|
<TextField
|
|
label="Frequency"
|
|
required
|
|
fullWidth
|
|
value={createForm.frequency}
|
|
onChange={(e) => setCreateForm({ ...createForm, frequency: e.target.value })}
|
|
/>
|
|
</Stack>
|
|
<TextField
|
|
select
|
|
label="Route"
|
|
required
|
|
fullWidth
|
|
value={createForm.route}
|
|
onChange={(e) =>
|
|
setCreateForm({ ...createForm, route: e.target.value as CreateMedicationRequest['route'] })
|
|
}
|
|
>
|
|
{ROUTES.map((r) => (
|
|
<MenuItem key={r} value={r}>
|
|
{r}
|
|
</MenuItem>
|
|
))}
|
|
</TextField>
|
|
<TextField
|
|
label="Instructions"
|
|
fullWidth
|
|
multiline
|
|
rows={2}
|
|
value={createForm.instructions ?? ''}
|
|
onChange={(e) =>
|
|
setCreateForm({ ...createForm, instructions: e.target.value || undefined })
|
|
}
|
|
/>
|
|
</Stack>
|
|
</DialogContent>
|
|
<DialogActions>
|
|
<Button onClick={() => setCreateOpen(false)}>Cancel</Button>
|
|
<Button
|
|
variant="contained"
|
|
onClick={submitCreate}
|
|
disabled={saving || !createForm.name || !createForm.dosage || !createForm.frequency}
|
|
>
|
|
{saving ? <CircularProgress size={24} /> : 'Add'}
|
|
</Button>
|
|
</DialogActions>
|
|
</Dialog>
|
|
|
|
{/* Edit dialog */}
|
|
<Dialog
|
|
open={!!editTarget}
|
|
onClose={() => setEditTarget(null)}
|
|
fullWidth
|
|
maxWidth="sm"
|
|
>
|
|
<DialogTitle>Edit medication</DialogTitle>
|
|
<DialogContent>
|
|
<Stack spacing={2} sx={{ mt: 1 }}>
|
|
<TextField
|
|
label="Name"
|
|
fullWidth
|
|
value={editForm.name ?? ''}
|
|
onChange={(e) => setEditForm({ ...editForm, name: e.target.value })}
|
|
/>
|
|
<Stack direction="row" spacing={2}>
|
|
<TextField
|
|
label="Dosage"
|
|
fullWidth
|
|
value={editForm.dosage ?? ''}
|
|
onChange={(e) => setEditForm({ ...editForm, dosage: e.target.value })}
|
|
/>
|
|
<TextField
|
|
label="Frequency"
|
|
fullWidth
|
|
value={editForm.frequency ?? ''}
|
|
onChange={(e) => setEditForm({ ...editForm, frequency: e.target.value })}
|
|
/>
|
|
</Stack>
|
|
<TextField
|
|
label="Instructions"
|
|
fullWidth
|
|
multiline
|
|
rows={2}
|
|
value={editForm.instructions ?? ''}
|
|
onChange={(e) => setEditForm({ ...editForm, instructions: e.target.value })}
|
|
/>
|
|
<TextField
|
|
select
|
|
label="Status"
|
|
fullWidth
|
|
value={editForm.active ? 'active' : 'inactive'}
|
|
onChange={(e) => setEditForm({ ...editForm, active: e.target.value === 'active' })}
|
|
>
|
|
<MenuItem value="active">active</MenuItem>
|
|
<MenuItem value="inactive">inactive</MenuItem>
|
|
</TextField>
|
|
</Stack>
|
|
</DialogContent>
|
|
<DialogActions>
|
|
<Button onClick={() => setEditTarget(null)}>Cancel</Button>
|
|
<Button variant="contained" onClick={submitEdit} disabled={saving}>
|
|
{saving ? <CircularProgress size={24} /> : 'Save'}
|
|
</Button>
|
|
</DialogActions>
|
|
</Dialog>
|
|
|
|
{/* Delete confirm */}
|
|
<Dialog open={!!deleteTarget} onClose={() => setDeleteTarget(null)}>
|
|
<DialogTitle>Delete medication?</DialogTitle>
|
|
<DialogContent>
|
|
<Typography>
|
|
Remove {deleteTarget?.name}? This cannot be undone.
|
|
</Typography>
|
|
</DialogContent>
|
|
<DialogActions>
|
|
<Button onClick={() => setDeleteTarget(null)}>Cancel</Button>
|
|
<Button variant="contained" color="error" onClick={confirmDelete} disabled={saving}>
|
|
{saving ? <CircularProgress size={24} /> : 'Delete'}
|
|
</Button>
|
|
</DialogActions>
|
|
</Dialog>
|
|
</Box>
|
|
);
|
|
};
|
|
|
|
export default MedicationManager;
|