feature: a very minimal patients feature implemented. it needs lots of improvments though
This commit is contained in:
219
frontend/src/app/(dashboard)/patients/page.tsx
Normal file
219
frontend/src/app/(dashboard)/patients/page.tsx
Normal file
@@ -0,0 +1,219 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { patientsApi } from '@/lib/api/patients';
|
||||
import {
|
||||
CreatePatientInput,
|
||||
CreateTreatmentHistoryInput,
|
||||
Patient,
|
||||
TreatmentHistoryItem,
|
||||
} from '@/types/patient';
|
||||
import { PatientSearchSelect } from '@/components/patients/PatientSearchSelect';
|
||||
import { CreatePatientModal } from '@/components/patients/CreatePatientModal';
|
||||
import { PatientSummaryCard } from '@/components/patients/PatientSummaryCard';
|
||||
import { TreatmentHistoryPreview } from '@/components/patients/TreatmentHistoryPreview';
|
||||
|
||||
const EMPTY_PATIENT_FORM: CreatePatientInput = {
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
phone: '',
|
||||
email: '',
|
||||
};
|
||||
|
||||
export default function PatientsPage() {
|
||||
const [search, setSearch] = useState('');
|
||||
const [patients, setPatients] = useState<Patient[]>([]);
|
||||
const [selectedPatient, setSelectedPatient] = useState<Patient | undefined>();
|
||||
const [treatments, setTreatments] = useState<TreatmentHistoryItem[]>([]);
|
||||
const [loadingPatients, setLoadingPatients] = useState(false);
|
||||
const [loadingTreatments, setLoadingTreatments] = useState(false);
|
||||
const [isCreateOpen, setIsCreateOpen] = useState(false);
|
||||
const [savingPatient, setSavingPatient] = useState(false);
|
||||
const [savingTreatment, setSavingTreatment] = useState(false);
|
||||
const [patientForm, setPatientForm] = useState<CreatePatientInput>(EMPTY_PATIENT_FORM);
|
||||
const [errorMessage, setErrorMessage] = useState<string>('');
|
||||
const [successMessage, setSuccessMessage] = useState<string>('');
|
||||
|
||||
const sortedPatients = useMemo(
|
||||
() =>
|
||||
[...patients].sort((a, b) =>
|
||||
`${a.firstName} ${a.lastName}`.localeCompare(`${b.firstName} ${b.lastName}`),
|
||||
),
|
||||
[patients],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => {
|
||||
void loadPatients(search);
|
||||
}, 300);
|
||||
return () => clearTimeout(timeout);
|
||||
}, [search]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadPatients('');
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!successMessage) {
|
||||
return;
|
||||
}
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
setSuccessMessage('');
|
||||
}, 3000);
|
||||
|
||||
return () => clearTimeout(timeout);
|
||||
}, [successMessage]);
|
||||
|
||||
async function loadPatients(q: string) {
|
||||
setLoadingPatients(true);
|
||||
setErrorMessage('');
|
||||
try {
|
||||
const response = await patientsApi.list({ q, page: 1, limit: 25 });
|
||||
const items = response.data.items;
|
||||
setPatients(items);
|
||||
|
||||
if (selectedPatient) {
|
||||
const freshSelected = items.find((item) => item.id === selectedPatient.id);
|
||||
setSelectedPatient(freshSelected);
|
||||
}
|
||||
} catch (error: any) {
|
||||
const message = Array.isArray(error?.message) ? error.message.join(', ') : error?.message;
|
||||
setErrorMessage(message || 'Failed to load patients.');
|
||||
} finally {
|
||||
setLoadingPatients(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadTreatments(patientId: string) {
|
||||
setLoadingTreatments(true);
|
||||
setErrorMessage('');
|
||||
try {
|
||||
const response = await patientsApi.listTreatments(patientId);
|
||||
setTreatments(response.data);
|
||||
} catch (error: any) {
|
||||
const message = Array.isArray(error?.message) ? error.message.join(', ') : error?.message;
|
||||
setErrorMessage(message || 'Failed to load treatment history.');
|
||||
} finally {
|
||||
setLoadingTreatments(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreatePatient() {
|
||||
setSavingPatient(true);
|
||||
setErrorMessage('');
|
||||
setSuccessMessage('');
|
||||
try {
|
||||
const response = await patientsApi.create(patientForm);
|
||||
setIsCreateOpen(false);
|
||||
setPatientForm(EMPTY_PATIENT_FORM);
|
||||
await loadPatients(search);
|
||||
setSelectedPatient(response.data);
|
||||
await loadTreatments(response.data.id);
|
||||
setSuccessMessage(
|
||||
`Patient ${response.data.firstName} ${response.data.lastName} was saved successfully.`,
|
||||
);
|
||||
} catch (error: any) {
|
||||
const message = Array.isArray(error?.message) ? error.message.join(', ') : error?.message;
|
||||
setErrorMessage(message || 'Failed to save patient.');
|
||||
} finally {
|
||||
setSavingPatient(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleQuickAddTreatment() {
|
||||
if (!selectedPatient) {
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: CreateTreatmentHistoryInput = {
|
||||
title: 'Initial consultation',
|
||||
status: 'scheduled',
|
||||
treatmentAt: new Date().toISOString(),
|
||||
notes: 'Created from quick action on patients page.',
|
||||
};
|
||||
|
||||
setSavingTreatment(true);
|
||||
setErrorMessage('');
|
||||
setSuccessMessage('');
|
||||
try {
|
||||
await patientsApi.addTreatment(selectedPatient.id, payload);
|
||||
await loadTreatments(selectedPatient.id);
|
||||
setSuccessMessage('Treatment entry added successfully.');
|
||||
} catch (error: any) {
|
||||
const message = Array.isArray(error?.message) ? error.message.join(', ') : error?.message;
|
||||
setErrorMessage(message || 'Failed to add treatment entry.');
|
||||
} finally {
|
||||
setSavingTreatment(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative space-y-6 pb-20">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-semibold text-text-primary">Patients</h1>
|
||||
<Button variant="primary" className="flex items-center gap-2" onClick={() => setIsCreateOpen(true)}>
|
||||
<Plus className="h-4 w-4 icon-flat" />
|
||||
New Patient
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<CreatePatientModal
|
||||
isOpen={isCreateOpen}
|
||||
formData={patientForm}
|
||||
onChange={(patch) => setPatientForm((prev) => ({ ...prev, ...patch }))}
|
||||
onSubmit={handleCreatePatient}
|
||||
onClose={() => setIsCreateOpen(false)}
|
||||
loading={savingPatient}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
|
||||
<div className="xl:col-span-1">
|
||||
<PatientSearchSelect
|
||||
search={search}
|
||||
onSearchChange={setSearch}
|
||||
patients={sortedPatients}
|
||||
selectedPatientId={selectedPatient?.id}
|
||||
onSelectPatient={(patient) => {
|
||||
setSelectedPatient(patient);
|
||||
void loadTreatments(patient.id);
|
||||
}}
|
||||
loading={loadingPatients}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="xl:col-span-2 space-y-4">
|
||||
<PatientSummaryCard patient={selectedPatient} />
|
||||
<div className="flex">
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={!selectedPatient}
|
||||
isLoading={savingTreatment}
|
||||
onClick={handleQuickAddTreatment}
|
||||
>
|
||||
Add Quick Treatment Entry
|
||||
</Button>
|
||||
</div>
|
||||
<TreatmentHistoryPreview items={treatments} loading={loadingTreatments} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{(errorMessage || successMessage) && (
|
||||
<div className="absolute bottom-0 left-0 right-0 z-50 w-full">
|
||||
{errorMessage && (
|
||||
<div className="rounded-[var(--radius-sm)] border border-red-500/50 bg-red-500/10 px-3 py-2 text-sm text-red-300 shadow-lg">
|
||||
{errorMessage}
|
||||
</div>
|
||||
)}
|
||||
{successMessage && (
|
||||
<div className="rounded-[var(--radius-sm)] border border-emerald-500/50 bg-emerald-500/10 px-3 py-2 text-sm text-emerald-300 shadow-lg">
|
||||
{successMessage}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
69
frontend/src/components/patients/CreatePatientModal.tsx
Normal file
69
frontend/src/components/patients/CreatePatientModal.tsx
Normal file
@@ -0,0 +1,69 @@
|
||||
'use client';
|
||||
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { CreatePatientInput } from '@/types/patient';
|
||||
|
||||
interface CreatePatientModalProps {
|
||||
isOpen: boolean;
|
||||
formData: CreatePatientInput;
|
||||
onChange: (patch: Partial<CreatePatientInput>) => void;
|
||||
onSubmit: () => void;
|
||||
onClose: () => void;
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
export function CreatePatientModal({
|
||||
isOpen,
|
||||
formData,
|
||||
onChange,
|
||||
onSubmit,
|
||||
onClose,
|
||||
loading = false,
|
||||
}: CreatePatientModalProps) {
|
||||
if (!isOpen) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="surface-card p-4 space-y-3">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<Input
|
||||
label="First name"
|
||||
value={formData.firstName || ''}
|
||||
onChange={(e) => onChange({ firstName: e.target.value })}
|
||||
/>
|
||||
<Input
|
||||
label="Last name"
|
||||
value={formData.lastName || ''}
|
||||
onChange={(e) => onChange({ lastName: e.target.value })}
|
||||
/>
|
||||
<Input
|
||||
label="Phone"
|
||||
value={formData.phone || ''}
|
||||
onChange={(e) => onChange({ phone: e.target.value })}
|
||||
/>
|
||||
<Input
|
||||
label="Email"
|
||||
type="email"
|
||||
value={formData.email || ''}
|
||||
onChange={(e) => onChange({ email: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={onSubmit}
|
||||
isLoading={loading}
|
||||
disabled={!formData.firstName || !formData.lastName}
|
||||
>
|
||||
Save Patient
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
63
frontend/src/components/patients/PatientSearchSelect.tsx
Normal file
63
frontend/src/components/patients/PatientSearchSelect.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
'use client';
|
||||
|
||||
import { Search } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { Patient } from '@/types/patient';
|
||||
|
||||
interface PatientSearchSelectProps {
|
||||
search: string;
|
||||
onSearchChange: (value: string) => void;
|
||||
patients: Patient[];
|
||||
selectedPatientId?: string;
|
||||
onSelectPatient: (patient: Patient) => void;
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
export function PatientSearchSelect({
|
||||
search,
|
||||
onSearchChange,
|
||||
patients,
|
||||
selectedPatientId,
|
||||
onSelectPatient,
|
||||
loading = false,
|
||||
}: PatientSearchSelectProps) {
|
||||
return (
|
||||
<div className="surface-card p-4 space-y-4">
|
||||
<Input
|
||||
placeholder="Search patients by name, phone, email"
|
||||
value={search}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
icon={<Search className="h-4 w-4 icon-flat" />}
|
||||
/>
|
||||
|
||||
<div className="space-y-2 max-h-80 overflow-y-auto">
|
||||
{loading && <p className="text-sm text-text-muted">Loading patients...</p>}
|
||||
|
||||
{!loading && patients.length === 0 && (
|
||||
<p className="text-sm text-text-muted">No patients found for this search.</p>
|
||||
)}
|
||||
|
||||
{patients.map((patient) => {
|
||||
const isSelected = selectedPatientId === patient.id;
|
||||
return (
|
||||
<button
|
||||
key={patient.id}
|
||||
type="button"
|
||||
onClick={() => onSelectPatient(patient)}
|
||||
className={`w-full text-left rounded-[var(--radius-sm)] border px-3 py-2 transition-colors ${
|
||||
isSelected
|
||||
? 'bg-primary-soft border-primary/60'
|
||||
: 'border-border/60 hover:bg-background-card/70'
|
||||
}`}
|
||||
>
|
||||
<p className="text-sm font-medium text-text-primary">
|
||||
{patient.firstName} {patient.lastName}
|
||||
</p>
|
||||
<p className="text-xs text-text-muted">{patient.phone || patient.email || 'No contact'}</p>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
28
frontend/src/components/patients/PatientSummaryCard.tsx
Normal file
28
frontend/src/components/patients/PatientSummaryCard.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
import { Patient } from '@/types/patient';
|
||||
|
||||
interface PatientSummaryCardProps {
|
||||
patient?: Patient;
|
||||
}
|
||||
|
||||
export function PatientSummaryCard({ patient }: PatientSummaryCardProps) {
|
||||
if (!patient) {
|
||||
return (
|
||||
<div className="surface-card p-4">
|
||||
<p className="text-sm text-text-muted">Select a patient to view details.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="surface-card p-4 space-y-2">
|
||||
<h2 className="text-lg font-semibold text-text-primary">
|
||||
{patient.firstName} {patient.lastName}
|
||||
</h2>
|
||||
<p className="text-sm text-text-secondary">Phone: {patient.phone || '-'}</p>
|
||||
<p className="text-sm text-text-secondary">Email: {patient.email || '-'}</p>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Status: {patient.isActive ? 'Active' : 'Inactive'}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
37
frontend/src/components/patients/TreatmentHistoryPreview.tsx
Normal file
37
frontend/src/components/patients/TreatmentHistoryPreview.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import { TreatmentHistoryItem } from '@/types/patient';
|
||||
|
||||
interface TreatmentHistoryPreviewProps {
|
||||
items: TreatmentHistoryItem[];
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
export function TreatmentHistoryPreview({ items, loading = false }: TreatmentHistoryPreviewProps) {
|
||||
return (
|
||||
<div className="surface-card p-4 space-y-3">
|
||||
<h3 className="text-base font-semibold text-text-primary">Treatment History</h3>
|
||||
|
||||
{loading && <p className="text-sm text-text-muted">Loading treatment history...</p>}
|
||||
|
||||
{!loading && items.length === 0 && (
|
||||
<p className="text-sm text-text-muted">No treatment history yet.</p>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
{items.map((item) => (
|
||||
<div key={item.id} className="border border-border/60 rounded-[var(--radius-sm)] p-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm font-medium text-text-primary">{item.title}</p>
|
||||
<p className="text-xs text-text-muted">
|
||||
{new Date(item.treatmentAt).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-xs text-text-secondary mt-1">
|
||||
Status: {item.status}
|
||||
{item.tooth ? ` | Tooth: ${item.tooth}` : ''}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
43
frontend/src/lib/api/patients.ts
Normal file
43
frontend/src/lib/api/patients.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { apiClient } from './client';
|
||||
import {
|
||||
CreatePatientInput,
|
||||
CreateTreatmentHistoryInput,
|
||||
Patient,
|
||||
PatientsListResponse,
|
||||
TreatmentHistoryItem,
|
||||
} from '@/types/patient';
|
||||
|
||||
export const patientsApi = {
|
||||
list: async (params?: { q?: string; page?: number; limit?: number }): Promise<PatientsListResponse> => {
|
||||
const response = await apiClient.get('/patients', { params });
|
||||
return response.data;
|
||||
},
|
||||
|
||||
create: async (data: CreatePatientInput): Promise<{ success: boolean; data: Patient }> => {
|
||||
const response = await apiClient.post('/patients', data);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
getOne: async (id: string): Promise<{ success: boolean; data: Patient }> => {
|
||||
const response = await apiClient.get(`/patients/${id}`);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
listTreatments: async (
|
||||
patientId: string,
|
||||
limit = 20,
|
||||
): Promise<{ success: boolean; data: TreatmentHistoryItem[] }> => {
|
||||
const response = await apiClient.get(`/patients/${patientId}/treatments`, {
|
||||
params: { limit },
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
|
||||
addTreatment: async (
|
||||
patientId: string,
|
||||
data: CreateTreatmentHistoryInput,
|
||||
): Promise<{ success: boolean; data: TreatmentHistoryItem }> => {
|
||||
const response = await apiClient.post(`/patients/${patientId}/treatments`, data);
|
||||
return response.data;
|
||||
},
|
||||
};
|
||||
@@ -77,11 +77,18 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const storedOrgId = localStorage.getItem('currentOrganizationId');
|
||||
if (storedOrgId && orgs.length > 0) {
|
||||
const org = orgs.find(o => o.id === storedOrgId);
|
||||
if (org) setCurrentOrganization(org);
|
||||
else setCurrentOrganization(null);
|
||||
if (org) {
|
||||
setCurrentOrganization(org);
|
||||
// Ensure cookie token carries organizationId for org-scoped APIs.
|
||||
await authApi.selectOrganization(org.id);
|
||||
} else {
|
||||
setCurrentOrganization(null);
|
||||
}
|
||||
} else if (orgs.length === 1 && userData) {
|
||||
setCurrentOrganization(orgs[0]);
|
||||
localStorage.setItem('currentOrganizationId', orgs[0].id);
|
||||
// Keep JWT in sync with selected org even for single-org users.
|
||||
await authApi.selectOrganization(orgs[0].id);
|
||||
} else {
|
||||
setCurrentOrganization(null);
|
||||
}
|
||||
@@ -125,6 +132,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
|
||||
if (orgs.length === 1) {
|
||||
const org = orgs[0];
|
||||
await authApi.selectOrganization(org.id);
|
||||
setCurrentOrganization(org);
|
||||
localStorage.setItem('currentOrganizationId', org.id);
|
||||
router.push('/today');
|
||||
@@ -156,6 +164,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
|
||||
if (orgs.length === 1) {
|
||||
const org = orgs[0];
|
||||
await authApi.selectOrganization(org.id);
|
||||
setCurrentOrganization(org);
|
||||
localStorage.setItem('currentOrganizationId', org.id);
|
||||
router.push('/today');
|
||||
|
||||
57
frontend/src/types/patient.ts
Normal file
57
frontend/src/types/patient.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
export interface Patient {
|
||||
id: string;
|
||||
organizationId: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
phone?: string | null;
|
||||
email?: string | null;
|
||||
dateOfBirth?: string | null;
|
||||
notes?: string | null;
|
||||
isActive: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface TreatmentHistoryItem {
|
||||
id: string;
|
||||
patientId: string;
|
||||
title: string;
|
||||
status: string;
|
||||
treatmentAt: string;
|
||||
tooth?: string | null;
|
||||
notes?: string | null;
|
||||
totalCost?: number | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface CreatePatientInput {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
phone?: string;
|
||||
email?: string;
|
||||
dateOfBirth?: string;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export interface CreateTreatmentHistoryInput {
|
||||
title: string;
|
||||
status: string;
|
||||
treatmentAt: string;
|
||||
tooth?: string;
|
||||
notes?: string;
|
||||
totalCost?: number;
|
||||
}
|
||||
|
||||
export interface PatientsListResponse {
|
||||
success: boolean;
|
||||
data: {
|
||||
items: Patient[];
|
||||
pagination: {
|
||||
page: number;
|
||||
limit: number;
|
||||
total: number;
|
||||
totalPages: number;
|
||||
};
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user