Merge branch 'feature/appointment-page' into develop

This commit is contained in:
2025-09-14 18:41:02 +05:30
12 changed files with 756 additions and 636 deletions

View File

@@ -20,6 +20,62 @@ router.get("/all", async (req: Request, res: Response): Promise<any> => {
}
});
/**
* GET /api/appointments/day?date=YYYY-MM-DD
* Response: { appointments: Appointment[], patients: Patient[] }
*/
router.get("/day", async (req: Request, res: Response): Promise<any> => {
function isValidYMD(s: string) {
return /^\d{4}-\d{2}-\d{2}$/.test(s);
}
try {
const rawDate = req.query.date as string | undefined;
if (!rawDate || !isValidYMD(rawDate)) {
return res.status(400).json({ message: "Date query param is required." });
}
if (!req.user) return res.status(401).json({ message: "Unauthorized" });
// Build literal UTC day bounds from the YYYY-MM-DD query string
const start = new Date(`${rawDate}T00:00:00.000Z`);
const end = new Date(`${rawDate}T23:59:59.999Z`);
if (isNaN(start.getTime()) || isNaN(end.getTime())) {
return res.status(400).json({ message: "Invalid date format" });
}
// Call the storage method that takes a start/end range (no change to storage needed)
const appointments = await storage.getAppointmentsOnRange(start, end);
// dedupe patient ids referenced by those appointments
const patientIds = Array.from(
new Set(appointments.map((a) => a.patientId).filter(Boolean))
);
const patients = patientIds.length
? await storage.getPatientsByIds(patientIds)
: [];
return res.json({ appointments, patients });
} catch (err) {
console.error("Error in /api/appointments/day:", err);
res.status(500).json({ message: "Failed to load appointments for date" });
}
});
// Get recent appointments (paginated)
router.get("/recent", async (req: Request, res: Response) => {
try {
const limit = Math.max(1, parseInt(req.query.limit as string) || 10);
const offset = Math.max(0, parseInt(req.query.offset as string) || 0);
const all = await storage.getRecentAppointments(limit, offset);
res.json({ data: all, limit, offset });
} catch (err) {
res.status(500).json({ message: "Failed to get recent appointments" });
}
});
// Get a single appointment by ID
router.get(
"/:id",
@@ -75,44 +131,6 @@ router.get(
}
);
// Get appointments on a specific date
router.get(
"/appointments/on/:date",
async (req: Request, res: Response): Promise<any> => {
try {
const rawDate = req.params.date;
if (!rawDate) {
return res.status(400).json({ message: "Date parameter is required" });
}
const date = new Date(rawDate);
if (isNaN(date.getTime())) {
return res.status(400).json({ message: "Invalid date format" });
}
const all = await storage.getAppointmentsOn(date);
const appointments = all.filter((a) => a.userId === req.user!.id);
res.json(appointments);
} catch (err) {
res.status(500).json({ message: "Failed to get appointments on date" });
}
}
);
// Get recent appointments (paginated)
router.get("/appointments/recent", async (req: Request, res: Response) => {
try {
const limit = Math.max(1, parseInt(req.query.limit as string) || 10);
const offset = Math.max(0, parseInt(req.query.offset as string) || 0);
const all = await storage.getRecentAppointments(limit, offset);
res.json({ data: all, limit, offset });
} catch (err) {
res.status(500).json({ message: "Failed to get recent appointments" });
}
});
// Create a new appointment
router.post(
"/upsert",

View File

@@ -41,7 +41,7 @@ export interface IStorage {
getPatientByInsuranceId(insuranceId: string): Promise<Patient | null>;
getPatientsByUserId(userId: number): Promise<Patient[]>;
getRecentPatients(limit: number, offset: number): Promise<Patient[]>;
getTotalPatientCount(): Promise<number>;
getPatientsByIds(ids: number[]): Promise<Patient[]>;
createPatient(patient: InsertPatient): Promise<Patient>;
updatePatient(id: number, patient: UpdatePatient): Promise<Patient>;
deletePatient(id: number): Promise<void>;
@@ -62,6 +62,7 @@ export interface IStorage {
status: string;
}[]
>;
getTotalPatientCount(): Promise<number>;
countPatients(filters: any): Promise<number>; // optional but useful
// Appointment methods
@@ -70,7 +71,7 @@ export interface IStorage {
getAppointmentsByUserId(userId: number): Promise<Appointment[]>;
getAppointmentsByPatientId(patientId: number): Promise<Appointment[]>;
getRecentAppointments(limit: number, offset: number): Promise<Appointment[]>;
getAppointmentsOn(date: Date): Promise<Appointment[]>;
getAppointmentsOnRange(start: Date, end: Date): Promise<Appointment[]>;
createAppointment(appointment: InsertAppointment): Promise<Appointment>;
updateAppointment(
id: number,
@@ -290,6 +291,52 @@ export const storage: IStorage = {
});
},
async getPatientsByIds(ids: number[]): Promise<Patient[]> {
if (!ids || ids.length === 0) return [];
const uniqueIds = Array.from(new Set(ids));
return db.patient.findMany({
where: { id: { in: uniqueIds } },
select: {
id: true,
firstName: true,
lastName: true,
phone: true,
email: true,
dateOfBirth: true,
gender: true,
insuranceId: true,
insuranceProvider: true,
status: true,
userId: true,
createdAt: true,
},
});
},
async createPatient(patient: InsertPatient): Promise<Patient> {
return await db.patient.create({ data: patient as Patient });
},
async updatePatient(id: number, updateData: UpdatePatient): Promise<Patient> {
try {
return await db.patient.update({
where: { id },
data: updateData,
});
} catch (err) {
throw new Error(`Patient with ID ${id} not found`);
}
},
async deletePatient(id: number): Promise<void> {
try {
await db.patient.delete({ where: { id } });
} catch (err) {
console.error("Error deleting patient:", err);
throw new Error(`Failed to delete patient: ${err}`);
}
},
async searchPatients({
filters,
limit,
@@ -326,30 +373,6 @@ export const storage: IStorage = {
return db.patient.count({ where: filters });
},
async createPatient(patient: InsertPatient): Promise<Patient> {
return await db.patient.create({ data: patient as Patient });
},
async updatePatient(id: number, updateData: UpdatePatient): Promise<Patient> {
try {
return await db.patient.update({
where: { id },
data: updateData,
});
} catch (err) {
throw new Error(`Patient with ID ${id} not found`);
}
},
async deletePatient(id: number): Promise<void> {
try {
await db.patient.delete({ where: { id } });
} catch (err) {
console.error("Error deleting patient:", err);
throw new Error(`Failed to delete patient: ${err}`);
}
},
// Appointment methods
async getAppointment(id: number): Promise<Appointment | undefined> {
const appointment = await db.appointment.findUnique({ where: { id } });
@@ -368,13 +391,7 @@ export const storage: IStorage = {
return await db.appointment.findMany({ where: { patientId } });
},
async getAppointmentsOn(date: Date): Promise<Appointment[]> {
const start = new Date(date);
start.setHours(0, 0, 0, 0);
const end = new Date(date);
end.setHours(23, 59, 59, 999);
async getAppointmentsOnRange(start: Date, end: Date): Promise<Appointment[]> {
return db.appointment.findMany({
where: {
date: {

View File

@@ -8,7 +8,6 @@ import { AppointmentForm } from "./appointment-form";
import {
Appointment,
InsertAppointment,
Patient,
UpdateAppointment,
} from "@repo/db/types";
@@ -19,7 +18,6 @@ interface AddAppointmentModalProps {
onDelete?: (id: number) => void;
isLoading: boolean;
appointment?: Appointment;
patients: Patient[];
}
export function AddAppointmentModal({
@@ -29,7 +27,6 @@ export function AddAppointmentModal({
onDelete,
isLoading,
appointment,
patients,
}: AddAppointmentModalProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -42,7 +39,6 @@ export function AddAppointmentModal({
<div className="p-1">
<AppointmentForm
appointment={appointment}
patients={patients}
onSubmit={(data) => {
onSubmit(data);
onOpenChange(false);

View File

@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { format } from "date-fns";
@@ -34,10 +34,15 @@ import {
UpdateAppointment,
} from "@repo/db/types";
import { DateInputField } from "@/components/ui/dateInputField";
import { parseLocalDate } from "@/utils/dateUtils";
import {
PatientSearch,
SearchCriteria,
} from "@/components/patients/patient-search";
import { toast } from "@/hooks/use-toast";
interface AppointmentFormProps {
appointment?: Appointment;
patients: Patient[];
onSubmit: (data: InsertAppointment | UpdateAppointment) => void;
onDelete?: (id: number) => void;
onOpenChange?: (open: boolean) => void;
@@ -46,7 +51,6 @@ interface AppointmentFormProps {
export function AppointmentForm({
appointment,
patients,
onSubmit,
onDelete,
onOpenChange,
@@ -54,6 +58,8 @@ export function AppointmentForm({
}: AppointmentFormProps) {
const { user } = useAuth();
const inputRef = useRef<HTMLInputElement>(null);
const [prefillPatient, setPrefillPatient] = useState<Patient | null>(null);
useEffect(() => {
const timeout = setTimeout(() => {
inputRef.current?.focus();
@@ -62,8 +68,7 @@ export function AppointmentForm({
return () => clearTimeout(timeout);
}, []);
const { data: staffMembersRaw = [] as Staff[], isLoading: isLoadingStaff } =
useQuery<Staff[]>({
const { data: staffMembersRaw = [] as Staff[] } = useQuery<Staff[]>({
queryKey: ["/api/staffs/"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/staffs/");
@@ -82,23 +87,6 @@ export function AppointmentForm({
color: colorMap[staff.name] || "bg-gray-400",
}));
function parseLocalDate(dateString: string): Date {
const parts = dateString.split("-");
if (parts.length !== 3) {
return new Date();
}
const year = parseInt(parts[0] ?? "", 10);
const month = parseInt(parts[1] ?? "", 10);
const day = parseInt(parts[2] ?? "", 10);
if (isNaN(year) || isNaN(month) || isNaN(day)) {
return new Date();
}
// Create date at UTC midnight instead of local midnight
return new Date(year, month - 1, day);
}
// Get the stored data from session storage
const storedDataString = sessionStorage.getItem("newAppointmentData");
let parsedStoredData = null;
@@ -169,41 +157,108 @@ export function AppointmentForm({
defaultValues,
});
const [searchTerm, setSearchTerm] = useState("");
const [debouncedSearchTerm] = useDebounce(searchTerm, 200); // 1 seconds
const [filteredPatients, setFilteredPatients] = useState(patients);
// -----------------------------
// PATIENT SEARCH (reuse PatientSearch)
// -----------------------------
const [selectOpen, setSelectOpen] = useState(false);
useEffect(() => {
if (!debouncedSearchTerm.trim()) {
setFilteredPatients(patients);
} else {
const term = debouncedSearchTerm.toLowerCase();
setFilteredPatients(
patients.filter((p) =>
`${p.firstName} ${p.lastName} ${p.phone} ${p.dateOfBirth}`
.toLowerCase()
.includes(term)
)
// search criteria state (reused from patient page)
const [searchCriteria, setSearchCriteria] = useState<SearchCriteria | null>(
null
);
const [isSearchActive, setIsSearchActive] = useState(false);
// debounce search criteria so we don't hammer the backend
const [debouncedSearchCriteria] = useDebounce(searchCriteria, 300);
const limit = 50; // dropdown size
const offset = 0; // always first page for dropdown
// compute key used in patient page: recent or trimmed term
const searchKeyPart = useMemo(
() => debouncedSearchCriteria?.searchTerm?.trim() || "recent",
[debouncedSearchCriteria]
);
// Query function mirrors PatientTable logic (so backend contract is identical)
const queryFn = async (): Promise<Patient[]> => {
const trimmedTerm = debouncedSearchCriteria?.searchTerm?.trim();
const isSearch = !!trimmedTerm && trimmedTerm.length > 0;
const rawSearchBy = debouncedSearchCriteria?.searchBy || "name";
const validSearchKeys = [
"name",
"phone",
"insuranceId",
"gender",
"dob",
"all",
];
const searchKey = validSearchKeys.includes(rawSearchBy)
? rawSearchBy
: "name";
let url: string;
if (isSearch) {
const searchParams = new URLSearchParams({
limit: String(limit),
offset: String(offset),
});
if (searchKey === "all") {
searchParams.set("term", trimmedTerm!);
} else {
searchParams.set(searchKey, trimmedTerm!);
}
}, [debouncedSearchTerm, patients]);
url = `/api/patients/search?${searchParams.toString()}`;
} else {
url = `/api/patients/recent?limit=${limit}&offset=${offset}`;
}
const res = await apiRequest("GET", url);
if (!res.ok) {
const err = await res
.json()
.catch(() => ({ message: "Failed to fetch patients" }));
throw new Error(err.message || "Failed to fetch patients");
}
const payload = await res.json();
// Expect payload to be { patients: Patient[], totalCount: number } or just an array.
// Normalize: if payload.patients exists, return it; otherwise assume array of patients.
return Array.isArray(payload) ? payload : (payload.patients ?? []);
};
const {
data: patients = [],
isFetching: isFetchingPatients,
refetch: refetchPatients,
} = useQuery<Patient[], Error>({
queryKey: ["patients-dropdown", searchKeyPart],
queryFn,
enabled: selectOpen || !!debouncedSearchCriteria?.searchTerm,
});
// If select opened and no patients loaded, fetch
useEffect(() => {
if (selectOpen && (!patients || patients.length === 0)) {
refetchPatients();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectOpen]);
// Force form field values to update and clean up storage
useEffect(() => {
if (parsedStoredData) {
// Update form field values directly
if (parsedStoredData.startTime) {
if (!parsedStoredData) return;
// set times/staff/date as before
if (parsedStoredData.startTime)
form.setValue("startTime", parsedStoredData.startTime);
}
if (parsedStoredData.endTime) {
if (parsedStoredData.endTime)
form.setValue("endTime", parsedStoredData.endTime);
}
if (parsedStoredData.staff) {
if (parsedStoredData.staff)
form.setValue("staffId", parsedStoredData.staff);
}
if (parsedStoredData.date) {
const parsedDate =
typeof parsedStoredData.date === "string"
@@ -212,7 +267,49 @@ export function AppointmentForm({
form.setValue("date", parsedDate);
}
// Clean up session storage
// ---- patient prefill: check main cache, else fetch once ----
if (parsedStoredData.patientId) {
const pid = Number(parsedStoredData.patientId);
if (!Number.isNaN(pid)) {
// ensure the form value is set
form.setValue("patientId", pid);
// fetch single patient record (preferred)
(async () => {
try {
const res = await apiRequest("GET", `/api/patients/${pid}`);
if (res.ok) {
const patientRecord = await res.json();
setPrefillPatient(patientRecord);
} else {
// non-OK response: show toast with status / message
let msg = `Failed to load patient (status ${res.status})`;
try {
const body = await res.json().catch(() => null);
if (body && body.message) msg = body.message;
} catch {}
toast({
title: "Could not load patient",
description: msg,
variant: "destructive",
});
}
} catch (err) {
toast({
title: "Error fetching patient",
description:
(err as Error)?.message ||
"An unknown error occurred while fetching patient details.",
variant: "destructive",
});
} finally {
// remove the one-time transport
sessionStorage.removeItem("newAppointmentData");
}
})();
}
} else {
// no patientId in storage — still remove to avoid stale state
sessionStorage.removeItem("newAppointmentData");
}
}, [form]);
@@ -224,12 +321,6 @@ export function AppointmentForm({
? parseInt(data.patientId, 10)
: data.patientId;
// Get patient name for the title
const patient = patients.find((p) => p.id === patientId);
const patientName = patient
? `${patient.firstName} ${patient.lastName}`
: "Patient";
// Auto-create title if it's empty
let title = data.title;
if (!title || title.trim() === "") {
@@ -289,41 +380,109 @@ export function AppointmentForm({
render={({ field }) => (
<FormItem>
<FormLabel>Patient</FormLabel>
<Select
disabled={isLoading}
onValueChange={(val) => field.onChange(Number(val))}
value={field.value?.toString()}
defaultValue={field.value?.toString()}
onOpenChange={(open: boolean) => {
setSelectOpen(open);
if (!open) {
// reset transient search state when the dropdown closes
setSearchCriteria(null);
setIsSearchActive(false);
// Remove transient prefill if the main cached list contains it now
if (
prefillPatient &&
patients &&
patients.some(
(p) => Number(p.id) === Number(prefillPatient.id)
)
) {
setPrefillPatient(null);
}
} else {
// when opened, ensure initial results
if (!patients || patients.length === 0) refetchPatients();
}
}}
value={
field.value == null || // null or undefined
(typeof field.value === "number" &&
!Number.isFinite(field.value)) || // NaN/Infinity
(typeof field.value === "string" &&
field.value.trim() === "") || // empty string
field.value === "NaN" // defensive check
? ""
: String(field.value)
}
onValueChange={(val) =>
field.onChange(val === "" ? undefined : Number(val))
}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select a patient" />
</SelectTrigger>
</FormControl>
<SelectContent>
{/* Reuse full PatientSearch UI inside dropdown — callbacks update the query */}
<div className="p-2" onKeyDown={(e) => e.stopPropagation()}>
<Input
ref={inputRef}
placeholder="Search patients..."
className="w-full"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onKeyDown={(e) => {
const navKeys = ["ArrowDown", "ArrowUp", "Enter"];
if (!navKeys.includes(e.key)) {
e.stopPropagation(); // Only stop keys that affect select state
}
<PatientSearch
onSearch={(criteria) => {
setSearchCriteria(criteria);
setIsSearchActive(true);
}}
onClearSearch={() => {
setSearchCriteria({
searchTerm: "",
searchBy: "name",
});
setIsSearchActive(false);
}}
isSearchActive={isSearchActive}
/>
</div>
{/* Prefill patient only if main list does not already include them */}
{prefillPatient &&
!patients.some(
(p) => Number(p.id) === Number(prefillPatient.id)
) && (
<SelectItem
key={`prefill-${prefillPatient.id}`}
value={prefillPatient.id?.toString() ?? ""}
>
<div className="flex flex-col items-start">
<span className="font-medium">
{prefillPatient.firstName}{" "}
{prefillPatient.lastName}
</span>
<span className="text-xs text-muted-foreground">
DOB:{" "}
{prefillPatient.dateOfBirth
? new Date(
prefillPatient.dateOfBirth
).toLocaleDateString()
: ""}{" "}
{prefillPatient.phone ?? ""}
</span>
</div>
</SelectItem>
)}
<div className="max-h-60 overflow-y-auto scrollbar-thin scrollbar-thumb-muted-foreground/30">
{filteredPatients.length > 0 ? (
filteredPatients.map((patient) => (
{isFetchingPatients ? (
<div className="p-2 text-sm text-muted-foreground">
Loading...
</div>
) : patients && patients.length > 0 ? (
patients.map((patient) => (
<SelectItem
key={patient.id}
value={patient.id?.toString() ?? ""}
>
<div className="flex flex-col">
<div className="flex flex-col items-start">
<span className="font-medium">
{patient.firstName} {patient.lastName}
</span>
@@ -345,6 +504,7 @@ export function AppointmentForm({
</div>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}

View File

@@ -1,169 +0,0 @@
import { format } from "date-fns";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
MoreHorizontal,
Edit,
Trash2,
Eye,
Calendar,
Clock,
} from "lucide-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Appointment, Patient } from "@repo/db/types";
interface AppointmentTableProps {
appointments: Appointment[];
patients: Patient[];
onEdit: (appointment: Appointment) => void;
onDelete: (id: number) => void;
}
export function AppointmentTable({
appointments,
patients,
onEdit,
onDelete,
}: AppointmentTableProps) {
// Helper function to get patient name
const getPatientName = (patientId: number) => {
const patient = patients.find((p) => p.id === patientId);
return patient
? `${patient.firstName} ${patient.lastName}`
: "Unknown Patient";
};
// Helper function to get status badge
const getStatusBadge = (status: string) => {
const statusConfig: Record<
string,
{
variant:
| "default"
| "secondary"
| "destructive"
| "outline"
| "success";
label: string;
}
> = {
scheduled: { variant: "default", label: "Scheduled" },
confirmed: { variant: "secondary", label: "Confirmed" },
completed: { variant: "success", label: "Completed" },
cancelled: { variant: "destructive", label: "Cancelled" },
"no-show": { variant: "outline", label: "No Show" },
};
const config = statusConfig[status] || {
variant: "default",
label: status,
};
return <Badge variant={config.variant as any}>{config.label}</Badge>;
};
// Sort appointments by date and time (newest first)
const sortedAppointments = [...appointments].sort((a, b) => {
const dateComparison =
new Date(b.date).getTime() - new Date(a.date).getTime();
if (dateComparison !== 0) return dateComparison;
return a.startTime.toString().localeCompare(b.startTime.toString());
});
return (
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>Patient</TableHead>
<TableHead>Date</TableHead>
<TableHead>Time</TableHead>
<TableHead>Type</TableHead>
<TableHead>Status</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{sortedAppointments.length === 0 ? (
<TableRow>
<TableCell colSpan={6} className="h-24 text-center">
No appointments found.
</TableCell>
</TableRow>
) : (
sortedAppointments.map((appointment) => (
<TableRow key={appointment.id}>
<TableCell className="font-medium">
{getPatientName(appointment.patientId)}
</TableCell>
<TableCell>
<div className="flex items-center">
<Calendar className="mr-2 h-4 w-4 text-muted-foreground" />
{format(new Date(appointment.date), "MMM d, yyyy")}
</div>
</TableCell>
<TableCell>
<div className="flex items-center">
<Clock className="mr-2 h-4 w-4 text-muted-foreground" />
{appointment.startTime.slice(0, 5)} -{" "}
{appointment.endTime.slice(0, 5)}
</div>
</TableCell>
<TableCell className="capitalize">
{appointment.type.replace("-", " ")}
</TableCell>
<TableCell>{getStatusBadge(appointment.status!)}</TableCell>
<TableCell className="text-right">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Open menu</span>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuItem onClick={() => onEdit(appointment)}>
<Edit className="mr-2 h-4 w-4" />
Edit
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => {
if (typeof appointment.id === "number") {
onDelete(appointment.id);
} else {
console.error("Invalid appointment ID");
}
}}
className="text-destructive focus:text-destructive"
>
<Trash2 className="mr-2 h-4 w-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
);
}

View File

@@ -133,6 +133,10 @@ export function ClaimForm({
const [serviceDate, setServiceDate] = useState<string>(
formatLocalDate(new Date())
);
const [serviceDateOpen, setServiceDateOpen] = useState(false);
const [openProcedureDateIndex, setOpenProcedureDateIndex] = useState<
number | null
>(null);
// Update service date when calendar date changes
const onServiceDateChange = (date: Date | undefined) => {
@@ -559,7 +563,10 @@ export function ClaimForm({
{/* Service Date */}
<div className="flex gap-2">
<Label className="flex items-center">Service Date</Label>
<Popover>
<Popover
open={serviceDateOpen}
onOpenChange={setServiceDateOpen}
>
<PopoverTrigger asChild>
<Button
variant="outline"
@@ -569,11 +576,14 @@ export function ClaimForm({
{form.serviceDate}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<PopoverContent className="w-auto">
<Calendar
mode="single"
selected={serviceDateValue}
onSelect={onServiceDateChange}
onSelect={(date) => {
onServiceDateChange(date);
}}
onClose={() => setServiceDateOpen(false)}
/>
</PopoverContent>
</Popover>
@@ -702,7 +712,12 @@ export function ClaimForm({
</div>
{/* Date Picker */}
<Popover>
<Popover
open={openProcedureDateIndex === i}
onOpenChange={(open) =>
setOpenProcedureDateIndex(open ? i : null)
}
>
<PopoverTrigger asChild>
<Button
variant="outline"
@@ -712,11 +727,16 @@ export function ClaimForm({
{line.procedureDate || "Pick Date"}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<PopoverContent className="w-auto">
<Calendar
mode="single"
selected={new Date(line.procedureDate)}
selected={
line.procedureDate
? new Date(line.procedureDate)
: undefined
}
onSelect={(date) => updateProcedureDate(i, date)}
onClose={() => setOpenProcedureDateIndex(null)}
/>
</PopoverContent>
</Popover>

View File

@@ -43,6 +43,8 @@ export function PatientSearch({
onClearSearch,
isSearchActive,
}: PatientSearchProps) {
const [dobOpen, setDobOpen] = useState(false);
const [advanceDobOpen, setAdvanceDobOpen] = useState(false);
const [searchTerm, setSearchTerm] = useState("");
const [searchBy, setSearchBy] = useState<SearchCriteria["searchBy"]>("name");
const [showAdvanced, setShowAdvanced] = useState(false);
@@ -84,7 +86,7 @@ export function PatientSearch({
<div className="flex gap-2 mb-4">
<div className="relative flex-1">
{searchBy === "dob" ? (
<Popover>
<Popover open={dobOpen} onOpenChange={setDobOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
@@ -112,6 +114,7 @@ export function PatientSearch({
if (date) {
const formattedDate = format(date, "yyyy-MM-dd");
setSearchTerm(String(formattedDate));
setDobOpen(false);
}
}}
disabled={(date) => date > new Date()}
@@ -153,9 +156,10 @@ export function PatientSearch({
<Select
value={searchBy}
onValueChange={(value) =>
setSearchBy(value as SearchCriteria["searchBy"])
}
onValueChange={(value) => {
setSearchBy(value as SearchCriteria["searchBy"]);
setSearchTerm("");
}}
>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Search by..." />
@@ -189,12 +193,13 @@ export function PatientSearch({
</label>
<Select
value={advancedCriteria.searchBy}
onValueChange={(value) =>
updateAdvancedCriteria(
"searchBy",
value as SearchCriteria["searchBy"]
)
}
onValueChange={(value) => {
setAdvancedCriteria((prev) => ({
...prev,
searchBy: value as SearchCriteria["searchBy"],
searchTerm: "",
}));
}}
>
<SelectTrigger className="col-span-3">
<SelectValue placeholder="Name" />
@@ -215,9 +220,13 @@ export function PatientSearch({
Search term
</label>
{advancedCriteria.searchBy === "dob" ? (
<Popover>
<Popover
open={advanceDobOpen}
onOpenChange={setAdvanceDobOpen}
>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
onKeyDown={(e) => {
if (e.key === "Enter") handleSearch();
@@ -251,6 +260,7 @@ export function PatientSearch({
"searchTerm",
String(formattedDate)
);
setAdvanceDobOpen(false);
}
}}
disabled={(date) => date > new Date()}

View File

@@ -13,20 +13,34 @@ type CalendarProps =
mode: "single";
selected?: Date;
onSelect?: (date: Date | undefined) => void;
closeOnSelect?: boolean /** whether to request closing after selection (default true for single) */;
onClose?: () => void;
})
| (BaseProps & {
mode: "range";
selected?: DateRange;
onSelect?: (range: DateRange | undefined) => void;
closeOnSelect?: boolean; // will close only when range is complete
onClose?: () => void;
})
| (BaseProps & {
mode: "multiple";
selected?: Date[];
onSelect?: (dates: Date[] | undefined) => void;
closeOnSelect?: boolean; // default false for multi
onClose?: () => void;
});
export function Calendar(props: CalendarProps) {
const { mode, selected, onSelect, className, ...rest } = props;
const {
mode,
selected,
onSelect,
className,
closeOnSelect,
onClose,
...rest
} = props;
const [internalSelected, setInternalSelected] =
useState<typeof selected>(selected);
@@ -37,7 +51,30 @@ export function Calendar(props: CalendarProps) {
const handleSelect = (value: typeof selected) => {
setInternalSelected(value);
onSelect?.(value as any); // We'll narrow this properly below
// forward original callback
onSelect?.(value as any);
// Decide whether to request closing
const shouldClose =
typeof closeOnSelect !== "undefined"
? closeOnSelect
: mode === "single"
? true
: false;
if (!shouldClose) return;
// For range: only close when both from and to exist
if (mode === "range") {
const range = value as DateRange | undefined;
if (range?.from && range?.to) {
onClose?.();
}
return;
}
// For single or multiple (when allowed), close immediately
onClose?.();
};
return (

View File

@@ -19,6 +19,9 @@ interface DateInputProps {
disablePast?: boolean;
}
// THIS COMPONENT IS MADE FOR GENERAL FIELD IN PAGE.
// Here, User can input/paste date in certain format, and also select via calendar
export function DateInput({
label,
value,

View File

@@ -16,6 +16,8 @@ interface DateInputFieldProps {
disablePast?: boolean;
}
// THIS COMPONENT MADE FOR USING IN FORM FIELD INSIDE ANY FORM CONTROL, NOT AS INPUT FIELD NORMALLY.
// Here, User can input/paste date in certain format, and also select via calendar
export function DateInputField({
control,
name,

View File

@@ -1,7 +1,11 @@
import { useState, useEffect } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { format, addDays, startOfToday, addMinutes } from "date-fns";
import { parseLocalDate, formatLocalDate } from "@/utils/dateUtils";
import { addDays, startOfToday, addMinutes } from "date-fns";
import {
parseLocalDate,
formatLocalDate,
formatLocalTime,
} from "@/utils/dateUtils";
import { AddAppointmentModal } from "@/components/appointments/add-appointment-modal";
import { Button } from "@/components/ui/button";
import {
@@ -9,7 +13,6 @@ import {
Plus,
ChevronLeft,
ChevronRight,
RefreshCw,
Move,
Trash2,
} from "lucide-react";
@@ -17,13 +20,6 @@ import { useToast } from "@/hooks/use-toast";
import { Calendar } from "@/components/ui/calendar";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useAuth } from "@/hooks/use-auth";
import {
Card,
CardContent,
CardHeader,
CardDescription,
CardTitle,
} from "@/components/ui/card";
import { DndProvider, useDrag, useDrop } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import { Menu, Item, useContextMenu } from "react-contexify";
@@ -36,6 +32,12 @@ import {
Patient,
UpdateAppointment,
} from "@repo/db/types";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { Label } from "@/components/ui/label";
// Define types for scheduling
interface TimeSlot {
@@ -65,25 +67,25 @@ interface ScheduledAppointment {
// Define a unique ID for the appointment context menu
const APPOINTMENT_CONTEXT_MENU_ID = "appointment-context-menu";
// 🔑 exported base key
export const QK_APPOINTMENTS_BASE = ["appointments", "day"] as const;
// helper (optional) mirrors the query key structure
export const qkAppointmentsDay = (date: string) =>
[...QK_APPOINTMENTS_BASE, date] as const;
export default function AppointmentsPage() {
const { toast } = useToast();
const { user } = useAuth();
const [isAddModalOpen, setIsAddModalOpen] = useState(false);
const [isClaimModalOpen, setIsClaimModalOpen] = useState(false);
const [claimAppointmentId, setClaimAppointmentId] = useState<number | null>(
null
);
const [claimPatientId, setClaimPatientId] = useState<number | null>(null);
const [calendarOpen, setCalendarOpen] = useState(false);
const [editingAppointment, setEditingAppointment] = useState<
Appointment | undefined
>(undefined);
const [selectedDate, setSelectedDate] = useState<Date>(startOfToday());
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
const [location] = useLocation();
const [confirmDeleteState, setConfirmDeleteState] = useState<{
open: boolean;
appointmentId?: number;
appointmentTitle?: string;
}>({ open: false });
// Create context menu hook
@@ -91,9 +93,44 @@ export default function AppointmentsPage() {
id: APPOINTMENT_CONTEXT_MENU_ID,
});
//Fetching staff memebers
const { data: staffMembersRaw = [] as Staff[], isLoading: isLoadingStaff } =
useQuery<Staff[]>({
// ----------------------
// Day-level fetch: appointments + patients for selectedDate (lightweight)
// ----------------------
const formattedSelectedDate = formatLocalDate(selectedDate);
type DayPayload = { appointments: Appointment[]; patients: Patient[] };
const {
data: dayPayload = {
appointments: [] as Appointment[],
patients: [] as Patient[],
},
isLoading: isLoadingAppointments,
refetch: refetchAppointments,
} = useQuery<
DayPayload,
Error,
DayPayload,
readonly [string, string, string]
>({
queryKey: qkAppointmentsDay(formattedSelectedDate),
queryFn: async () => {
const res = await apiRequest(
"GET",
`/api/appointments/day?date=${formattedSelectedDate}`
);
if (!res.ok) {
throw new Error("Failed to load appointments for date");
}
return res.json();
},
enabled: !!user && !!formattedSelectedDate,
// placeholderData: keepPreviousData,
});
const appointments = dayPayload.appointments ?? [];
const patientsFromDay = dayPayload.patients ?? [];
// Staff memebers
const { data: staffMembersRaw = [] as Staff[] } = useQuery<Staff[]>({
queryKey: ["/api/staffs/"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/staffs/");
@@ -130,126 +167,61 @@ export default function AppointmentsPage() {
}
}
// Fetch appointments
const {
data: appointments = [] as Appointment[],
isLoading: isLoadingAppointments,
refetch: refetchAppointments,
} = useQuery<Appointment[]>({
queryKey: ["/api/appointments/all"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/appointments/all");
return res.json();
},
enabled: !!user,
});
// Fetch patients (needed for the dropdowns)
const { data: patients = [], isLoading: isLoadingPatients } = useQuery<
Patient[]
>({
queryKey: ["/api/patients/"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/patients/");
return res.json();
},
enabled: !!user,
});
// Handle creating a new appointment at a specific time slot and for a specific staff member
const handleCreateAppointmentAtSlot = (
timeSlot: TimeSlot,
staffId: number
) => {
// Calculate end time (30 minutes after start time)
const startHour = parseInt(timeSlot.time.split(":")[0] as string);
const startMinute = parseInt(timeSlot.time.split(":")[1] as string);
const startDate = parseLocalDate(selectedDate);
startDate.setHours(startHour, startMinute, 0);
const endDate = addMinutes(startDate, 30);
const endTime = `${endDate.getHours().toString().padStart(2, "0")}:${endDate.getMinutes().toString().padStart(2, "0")}`;
// Find staff member
const staff = staffMembers.find((s) => Number(s.id) === Number(staffId));
// Pre-fill appointment form with default values
const newAppointment = {
date: format(selectedDate, "yyyy-MM-dd"),
startTime: timeSlot.time, // This is in "HH:MM" format
endTime: endTime,
type: staff?.role === "doctor" ? "checkup" : "cleaning",
status: "scheduled",
title: `Appointment with ${staff?.name}`, // Add staff name in title for easier display
notes: `Appointment with ${staff?.name}`, // Store staff info in notes for processing
staff: staffId, // This matches the 'staff' field in the appointment form schema
};
// For new appointments, set editingAppointment to undefined
// This will ensure we go to the "create" branch in handleAppointmentSubmit
setEditingAppointment(undefined);
// But still pass the pre-filled data to the modal
setIsAddModalOpen(true);
// Store the prefilled values in state or sessionStorage to access in the modal
// Clear any existing data first to ensure we're not using old data
sessionStorage.removeItem("newAppointmentData");
sessionStorage.setItem(
"newAppointmentData",
JSON.stringify(newAppointment)
);
};
// Check for newPatient parameter in URL
useEffect(() => {
if (patients.length === 0 || !user) return;
// Parse URL search params to check for newPatient
const params = new URLSearchParams(window.location.search);
const newPatientId = params.get("newPatient");
if (newPatientId) {
const patientId = parseInt(newPatientId);
// Find the patient in our list
const patient = (patients as Patient[]).find((p) => p.id === patientId);
if (patient) {
toast({
title: "Patient Added",
description: `${patient.firstName} ${patient.lastName} was added successfully. You can now schedule an appointment.`,
});
// Select first available staff member
const staffId = staffMembers[0]!.id;
// Choose first available staff safely (fallback to 1 if none)
const firstStaff =
staffMembers && staffMembers.length > 0 ? staffMembers[0] : undefined;
const staffId = firstStaff ? Number(firstStaff.id) : 1;
// Find first time slot today (9:00 AM is a common starting time)
const defaultTimeSlot =
timeSlots.find((slot) => slot.time === "09:00") || timeSlots[0];
if (!defaultTimeSlot) {
toast({
title: "Unable to schedule",
description:
"No available time slots to schedule the new patient right now.",
variant: "destructive",
});
return;
}
// Open appointment modal with prefilled patient
handleCreateAppointmentAtSlot(defaultTimeSlot!, Number(staffId));
// Pre-select the patient in the appointment form
const patientData = {
patientId: patient.id,
// Merge any existing "newAppointmentData" with the patient info BEFORE opening modal
try {
const existingRaw = sessionStorage.getItem("newAppointmentData");
const existing = existingRaw ? JSON.parse(existingRaw) : {};
const newAppointmentData = {
...existing,
patientId: patientId,
};
// Store info in session storage for the modal to pick up
const existingData = sessionStorage.getItem("newAppointmentData");
if (existingData) {
const parsedData = JSON.parse(existingData);
sessionStorage.setItem(
"newAppointmentData",
JSON.stringify({
...parsedData,
...patientData,
})
JSON.stringify(newAppointmentData)
);
} catch (err) {
// If sessionStorage parsing fails, overwrite with a fresh object
sessionStorage.setItem(
"newAppointmentData",
JSON.stringify({ patientId: patientId })
);
}
// Open/create the appointment modal (will read sessionStorage in the modal)
handleCreateAppointmentAtSlot(defaultTimeSlot, Number(staffId));
// Remove the query param from the URL so this doesn't re-run on navigation/refresh
params.delete("newPatient");
const newSearch = params.toString();
const newUrl = `${window.location.pathname}${newSearch ? `?${newSearch}` : ""}${window.location.hash || ""}`;
window.history.replaceState({}, "", newUrl);
}
}
}, [patients, user, location]);
}, [location]);
// Create/upsert appointment mutation
const createAppointmentMutation = useMutation({
@@ -261,14 +233,15 @@ export default function AppointmentsPage() {
);
return await res.json();
},
onSuccess: () => {
onSuccess: (appointment) => {
toast({
title: "Success",
description: "Appointment created successfully.",
title: "Appointment Scheduled",
description: appointment.message || "Appointment created successfully.",
});
// Invalidate both appointments and patients queries
queryClient.invalidateQueries({ queryKey: ["/api/appointments/all"] });
queryClient.invalidateQueries({ queryKey: ["/api/patients/"] });
queryClient.invalidateQueries({
queryKey: qkAppointmentsDay(formattedSelectedDate),
});
setIsAddModalOpen(false);
},
onError: (error: Error) => {
@@ -296,13 +269,14 @@ export default function AppointmentsPage() {
);
return await res.json();
},
onSuccess: () => {
onSuccess: (appointment) => {
toast({
title: "Success",
description: "Appointment updated successfully.",
title: "Appointment Scheduled",
description: appointment.message || "Appointment created successfully.",
});
queryClient.invalidateQueries({
queryKey: qkAppointmentsDay(formattedSelectedDate),
});
queryClient.invalidateQueries({ queryKey: ["/api/appointments/all"] });
queryClient.invalidateQueries({ queryKey: ["/api/patients/"] });
setEditingAppointment(undefined);
setIsAddModalOpen(false);
},
@@ -326,8 +300,9 @@ export default function AppointmentsPage() {
description: "Appointment deleted successfully.",
});
// Invalidate both appointments and patients queries
queryClient.invalidateQueries({ queryKey: ["/api/appointments/all"] });
queryClient.invalidateQueries({ queryKey: ["/api/patients/"] });
queryClient.invalidateQueries({
queryKey: qkAppointmentsDay(formattedSelectedDate),
});
setConfirmDeleteState({ open: false });
},
onError: (error: Error) => {
@@ -344,7 +319,6 @@ export default function AppointmentsPage() {
appointmentData: InsertAppointment | UpdateAppointment
) => {
// Converts local date to exact UTC date with no offset issues
const rawDate = parseLocalDate(appointmentData.date);
const updatedData = {
@@ -386,52 +360,32 @@ export default function AppointmentsPage() {
};
const handleDeleteAppointment = (id: number) => {
const appointment = appointments.find((a) => a.id === id);
if (!appointment) return;
// Find patient by patientId
const patient = patients.find((p) => p.id === appointment.patientId);
setConfirmDeleteState({
open: true,
appointmentId: id,
appointmentTitle: `${patient?.firstName ?? "Appointment"}`,
});
};
const toggleMobileMenu = () => {
setIsMobileMenuOpen(!isMobileMenuOpen);
};
// Get formatted date string for display
const formattedDate = format(selectedDate, "yyyy-MM-dd");
const selectedDateAppointments = appointments.filter((appointment) => {
const dateObj = parseLocalDate(appointment.date);
return formatLocalDate(dateObj) === formatLocalDate(selectedDate);
});
// Process appointments for the scheduler view
const processedAppointments: ScheduledAppointment[] =
selectedDateAppointments.map((apt) => {
const processedAppointments: ScheduledAppointment[] = (
appointments ?? []
).map((apt) => {
// Find patient name
const patient = patients.find((p) => p.id === apt.patientId);
const patient = patientsFromDay.find((p) => p.id === apt.patientId);
const patientName = patient
? `${patient.firstName} ${patient.lastName}`
: "Unknown Patient";
let staffId: number;
const staffId = Number(apt.staffId ?? 1);
if (
staffMembers &&
staffMembers.length > 0 &&
staffMembers[0] !== undefined &&
staffMembers[0].id !== undefined
) {
staffId = Number(apt.staffId);
} else {
staffId = 1;
}
const normalizedStart =
typeof apt.startTime === "string"
? apt.startTime.substring(0, 5)
: formatLocalTime(apt.startTime);
const normalizedEnd =
typeof apt.endTime === "string"
? apt.endTime.substring(0, 5)
: formatLocalTime(apt.endTime);
const processed = {
...apt,
@@ -439,27 +393,25 @@ export default function AppointmentsPage() {
staffId,
status: apt.status ?? null,
date: formatLocalDate(parseLocalDate(apt.date)),
};
startTime: normalizedStart,
endTime: normalizedEnd,
} as ScheduledAppointment;
return processed;
});
// Check if appointment exists at a specific time slot and staff
const getAppointmentAtSlot = (timeSlot: TimeSlot, staffId: number) => {
if (processedAppointments.length === 0) {
if (!processedAppointments || processedAppointments.length === 0)
return undefined;
}
// In appointments for a given time slot, we'll just display the first one
// In a real application, you might want to show multiple or stack them
const appointmentsAtSlot = processedAppointments.filter((apt) => {
// Fix time format comparison - the database adds ":00" seconds to the time
const dbTime =
typeof apt.startTime === "string" ? apt.startTime.substring(0, 5) : "";
const timeMatches = dbTime === timeSlot.time;
const staffMatches = apt.staffId === staffId;
return timeMatches && staffMatches;
});
@@ -468,7 +420,6 @@ export default function AppointmentsPage() {
const isLoading =
isLoadingAppointments ||
isLoadingPatients ||
createAppointmentMutation.isPending ||
updateAppointmentMutation.isPending ||
deleteAppointmentMutation.isPending;
@@ -478,6 +429,76 @@ export default function AppointmentsPage() {
APPOINTMENT: "appointment",
};
// Handle creating a new appointment at a specific time slot and for a specific staff member
const handleCreateAppointmentAtSlot = (
timeSlot: TimeSlot,
staffId: number
) => {
// Calculate end time (30 minutes after start time)
const startHour = parseInt(timeSlot.time.split(":")[0] as string);
const startMinute = parseInt(timeSlot.time.split(":")[1] as string);
const startDate = parseLocalDate(selectedDate);
startDate.setHours(startHour, startMinute, 0);
const endDate = addMinutes(startDate, 30);
const endTime = `${endDate.getHours().toString().padStart(2, "0")}:${endDate.getMinutes().toString().padStart(2, "0")}`;
// Find staff member
const staff = staffMembers.find((s) => Number(s.id) === Number(staffId));
// Try to read any existing prefill data (may include patientId from the URL handler)
let existingStored: any = null;
try {
const raw = sessionStorage.getItem("newAppointmentData");
existingStored = raw ? JSON.parse(raw) : null;
} catch (e) {
// ignore parse errors and treat as no existing stored data
existingStored = null;
}
// Build the prefill appointment object and merge existing stored data
const newAppointment = {
// base defaults
date: formatLocalDate(selectedDate),
startTime: timeSlot.time, // This is in "HH:MM" format
endTime: endTime,
type: staff?.role === "doctor" ? "checkup" : "cleaning",
status: "scheduled",
title: `Appointment with ${staff?.name}`,
notes: `Appointment with ${staff?.name}`,
staff: Number(staffId), // consistent field name that matches update mutation
// if existingStored has patientId (or other fields) merge them below
...(existingStored || {}),
};
// Ensure explicit values from this function override stale values from storage
// (for example, prefer current slot and staff)
const mergedAppointment = {
...newAppointment,
date: newAppointment.date,
startTime: newAppointment.startTime,
endTime: newAppointment.endTime,
staff: Number(staffId),
};
// Persist merged prefill so the modal/form can read it
try {
sessionStorage.setItem(
"newAppointmentData",
JSON.stringify(mergedAppointment)
);
} catch (e) {
// ignore sessionStorage write failures
console.error("Failed to write newAppointmentData to sessionStorage", e);
}
// For new appointments, set editingAppointment to undefined
setEditingAppointment(undefined);
// Open modal
setIsAddModalOpen(true);
};
// Handle moving an appointment to a new time slot and staff
const handleMoveAppointment = (
appointmentId: number,
@@ -676,10 +697,10 @@ export default function AppointmentsPage() {
</Item>
</Menu>
{/* Main Content - Split into Schedule and Calendar */}
{/* Main Content */}
<div className="flex flex-col lg:flex-row gap-6">
{/* Left side - Schedule Grid */}
<div className="w-full lg:w-3/4 overflow-x-auto bg-white rounded-md shadow">
{/* Schedule Grid */}
<div className="w-full overflow-x-auto bg-white rounded-md shadow">
<div className="p-4 border-b">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-2">
@@ -690,7 +711,9 @@ export default function AppointmentsPage() {
>
<ChevronLeft className="h-4 w-4" />
</Button>
<h2 className="text-xl font-semibold">{formattedDate}</h2>
<h2 className="text-xl font-semibold">
{formattedSelectedDate}
</h2>
<Button
variant="outline"
size="icon"
@@ -699,6 +722,35 @@ export default function AppointmentsPage() {
<ChevronRight className="h-4 w-4" />
</Button>
</div>
{/* Top button with popover calendar */}
<div className="flex items-center gap-2">
<Label className="hidden sm:flex">Selected</Label>
<Popover open={calendarOpen} onOpenChange={setCalendarOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
className="w-[160px] justify-start text-left font-normal"
>
<CalendarIcon className="mr-2 h-4 w-4" />
{selectedDate
? selectedDate.toLocaleDateString()
: "Pick a date"}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto">
<Calendar
mode="single"
selected={selectedDate}
onSelect={(date) => {
if (date) setSelectedDate(date);
}}
onClose={() => setCalendarOpen(false)}
/>
</PopoverContent>
</Popover>
</div>
</div>
</div>
@@ -747,87 +799,6 @@ export default function AppointmentsPage() {
</div>
</DndProvider>
</div>
{/* Right side - Calendar and Stats */}
<div className="w-full lg:w-1/4 space-y-6">
{/* Calendar Card */}
<Card>
<CardHeader className="pb-2">
<CardTitle>Calendar</CardTitle>
<CardDescription>
Select a date to view or schedule appointments
</CardDescription>
</CardHeader>
<CardContent>
<Calendar
mode="single"
selected={selectedDate}
onSelect={(date) => {
if (date) setSelectedDate(date);
}}
/>
</CardContent>
</Card>
{/* Statistics Card */}
<Card>
<CardHeader className="pb-2">
<CardTitle className="flex items-center justify-between">
<span>Appointments</span>
<Button
variant="ghost"
size="icon"
onClick={() => refetchAppointments()}
>
<RefreshCw className="h-4 w-4" />
</Button>
</CardTitle>
<CardDescription>
Statistics for {formattedDate}
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2">
<div className="flex justify-between items-center">
<span className="text-sm text-gray-500">
Total appointments:
</span>
<span className="font-semibold">
{selectedDateAppointments.length}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-sm text-gray-500">With doctors:</span>
<span className="font-semibold">
{
processedAppointments.filter(
(apt) =>
staffMembers.find(
(s) => Number(s.id) === apt.staffId
)?.role === "doctor"
).length
}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-sm text-gray-500">
With hygienists:
</span>
<span className="font-semibold">
{
processedAppointments.filter(
(apt) =>
staffMembers.find(
(s) => Number(s.id) === apt.staffId
)?.role === "hygienist"
).length
}
</span>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
</div>
@@ -841,7 +812,6 @@ export default function AppointmentsPage() {
updateAppointmentMutation.isPending
}
appointment={editingAppointment}
patients={patients}
onDelete={handleDeleteAppointment}
/>
@@ -849,7 +819,7 @@ export default function AppointmentsPage() {
isOpen={confirmDeleteState.open}
onConfirm={handleConfirmDelete}
onCancel={() => setConfirmDeleteState({ open: false })}
entityName={confirmDeleteState.appointmentTitle}
entityName={String(confirmDeleteState.appointmentId)}
/>
</div>
);

View File

@@ -139,3 +139,59 @@ export function convertOCRDate(input: string | number | null | undefined): Date
return new Date(year, month, day);
}
/**
* Format a Date or date string into "HH:mm" (24-hour) string.
*
* Options:
* - By default, hours/minutes are taken in local time.
* - Pass { asUTC: true } to format using UTC hours/minutes.
*
* Examples:
* formatLocalTime(new Date(2025, 6, 15, 9, 5)) → "09:05"
* formatLocalTime("2025-07-15") → "00:00"
* formatLocalTime("2025-07-15T14:30:00Z") → "20:30" (in +06:00)
* formatLocalTime("2025-07-15T14:30:00Z", { asUTC:true }) → "14:30"
*/
export function formatLocalTime(
d: Date | string | undefined,
opts: { asUTC?: boolean } = {}
): string {
if (!d) return "";
const { asUTC = false } = opts;
const pad2 = (n: number) => n.toString().padStart(2, "0");
let dateObj: Date;
if (d instanceof Date) {
if (isNaN(d.getTime())) return "";
dateObj = d;
} else if (typeof d === "string") {
const raw = d.trim();
const isDateOnly = /^\d{4}-\d{2}-\d{2}$/.test(raw);
if (isDateOnly) {
// Parse yyyy-MM-dd safely as local midnight
try {
dateObj = parseLocalDate(raw);
} catch {
dateObj = new Date(raw); // fallback
}
} else {
// For full ISO/timestamp strings, let Date handle TZ
dateObj = new Date(raw);
}
if (isNaN(dateObj.getTime())) return "";
} else {
return "";
}
const hours = asUTC ? dateObj.getUTCHours() : dateObj.getHours();
const minutes = asUTC ? dateObj.getUTCMinutes() : dateObj.getMinutes();
return `${pad2(hours)}:${pad2(minutes)}`;
}