diff --git a/apps/Backend/src/routes/appointments.ts b/apps/Backend/src/routes/appointments.ts index f910f44..72e34c4 100644 --- a/apps/Backend/src/routes/appointments.ts +++ b/apps/Backend/src/routes/appointments.ts @@ -20,6 +20,62 @@ router.get("/all", async (req: Request, res: Response): Promise => { } }); +/** + * GET /api/appointments/day?date=YYYY-MM-DD + * Response: { appointments: Appointment[], patients: Patient[] } + */ +router.get("/day", async (req: Request, res: Response): Promise => { + 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 => { - 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", diff --git a/apps/Backend/src/storage/index.ts b/apps/Backend/src/storage/index.ts index d5c8670..d806ae4 100644 --- a/apps/Backend/src/storage/index.ts +++ b/apps/Backend/src/storage/index.ts @@ -41,7 +41,7 @@ export interface IStorage { getPatientByInsuranceId(insuranceId: string): Promise; getPatientsByUserId(userId: number): Promise; getRecentPatients(limit: number, offset: number): Promise; - getTotalPatientCount(): Promise; + getPatientsByIds(ids: number[]): Promise; createPatient(patient: InsertPatient): Promise; updatePatient(id: number, patient: UpdatePatient): Promise; deletePatient(id: number): Promise; @@ -62,6 +62,7 @@ export interface IStorage { status: string; }[] >; + getTotalPatientCount(): Promise; countPatients(filters: any): Promise; // optional but useful // Appointment methods @@ -70,7 +71,7 @@ export interface IStorage { getAppointmentsByUserId(userId: number): Promise; getAppointmentsByPatientId(patientId: number): Promise; getRecentAppointments(limit: number, offset: number): Promise; - getAppointmentsOn(date: Date): Promise; + getAppointmentsOnRange(start: Date, end: Date): Promise; createAppointment(appointment: InsertAppointment): Promise; updateAppointment( id: number, @@ -290,6 +291,52 @@ export const storage: IStorage = { }); }, + async getPatientsByIds(ids: number[]): Promise { + 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 { + return await db.patient.create({ data: patient as Patient }); + }, + + async updatePatient(id: number, updateData: UpdatePatient): Promise { + 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 { + 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 { - return await db.patient.create({ data: patient as Patient }); - }, - - async updatePatient(id: number, updateData: UpdatePatient): Promise { - 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 { - 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 { 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 { - 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 { return db.appointment.findMany({ where: { date: { diff --git a/apps/Frontend/src/components/appointments/add-appointment-modal.tsx b/apps/Frontend/src/components/appointments/add-appointment-modal.tsx index ae1810b..ec9f641 100644 --- a/apps/Frontend/src/components/appointments/add-appointment-modal.tsx +++ b/apps/Frontend/src/components/appointments/add-appointment-modal.tsx @@ -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 ( @@ -42,7 +39,6 @@ export function AddAppointmentModal({
{ onSubmit(data); onOpenChange(false); diff --git a/apps/Frontend/src/components/appointments/appointment-form.tsx b/apps/Frontend/src/components/appointments/appointment-form.tsx index 5e43337..b451731 100644 --- a/apps/Frontend/src/components/appointments/appointment-form.tsx +++ b/apps/Frontend/src/components/appointments/appointment-form.tsx @@ -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(null); + const [prefillPatient, setPrefillPatient] = useState(null); + useEffect(() => { const timeout = setTimeout(() => { inputRef.current?.focus(); @@ -62,15 +68,14 @@ export function AppointmentForm({ return () => clearTimeout(timeout); }, []); - const { data: staffMembersRaw = [] as Staff[], isLoading: isLoadingStaff } = - useQuery({ - queryKey: ["/api/staffs/"], - queryFn: async () => { - const res = await apiRequest("GET", "/api/staffs/"); - return res.json(); - }, - enabled: !!user, - }); + const { data: staffMembersRaw = [] as Staff[] } = useQuery({ + queryKey: ["/api/staffs/"], + queryFn: async () => { + const res = await apiRequest("GET", "/api/staffs/"); + return res.json(); + }, + enabled: !!user, + }); const colorMap: Record = { "Dr. Kai Gao": "bg-blue-600", @@ -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,50 +157,159 @@ 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); + // search criteria state (reused from patient page) + const [searchCriteria, setSearchCriteria] = useState( + 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 => { + 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!); + } + + url = `/api/patients/search?${searchParams.toString()}`; } else { - const term = debouncedSearchTerm.toLowerCase(); - setFilteredPatients( - patients.filter((p) => - `${p.firstName} ${p.lastName} ${p.phone} ${p.dateOfBirth}` - .toLowerCase() - .includes(term) - ) - ); + url = `/api/patients/recent?limit=${limit}&offset=${offset}`; } - }, [debouncedSearchTerm, patients]); + + 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({ + 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) { - form.setValue("startTime", parsedStoredData.startTime); - } + if (!parsedStoredData) return; - if (parsedStoredData.endTime) { - form.setValue("endTime", parsedStoredData.endTime); - } + // set times/staff/date as before + if (parsedStoredData.startTime) + form.setValue("startTime", parsedStoredData.startTime); + if (parsedStoredData.endTime) + form.setValue("endTime", parsedStoredData.endTime); + if (parsedStoredData.staff) + form.setValue("staffId", parsedStoredData.staff); + if (parsedStoredData.date) { + const parsedDate = + typeof parsedStoredData.date === "string" + ? parseLocalDate(parsedStoredData.date) + : new Date(parsedStoredData.date); + form.setValue("date", parsedDate); + } - if (parsedStoredData.staff) { - form.setValue("staffId", parsedStoredData.staff); - } + // ---- 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); - if (parsedStoredData.date) { - const parsedDate = - typeof parsedStoredData.date === "string" - ? parseLocalDate(parsedStoredData.date) - : new Date(parsedStoredData.date); - form.setValue("date", parsedDate); + // 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"); + } + })(); } - - // Clean up session storage + } 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 }) => ( Patient + 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 - } + { + setSearchCriteria(criteria); + setIsSearchActive(true); }} + onClearSearch={() => { + setSearchCriteria({ + searchTerm: "", + searchBy: "name", + }); + setIsSearchActive(false); + }} + isSearchActive={isSearchActive} />
+ + {/* Prefill patient only if main list does not already include them */} + {prefillPatient && + !patients.some( + (p) => Number(p.id) === Number(prefillPatient.id) + ) && ( + +
+ + {prefillPatient.firstName}{" "} + {prefillPatient.lastName} + + + DOB:{" "} + {prefillPatient.dateOfBirth + ? new Date( + prefillPatient.dateOfBirth + ).toLocaleDateString() + : ""}{" "} + • {prefillPatient.phone ?? ""} + +
+
+ )} +
- {filteredPatients.length > 0 ? ( - filteredPatients.map((patient) => ( + {isFetchingPatients ? ( +
+ Loading... +
+ ) : patients && patients.length > 0 ? ( + patients.map((patient) => ( -
+
{patient.firstName} {patient.lastName} @@ -345,6 +504,7 @@ export function AppointmentForm({
+ )} diff --git a/apps/Frontend/src/components/appointments/appointment-table.tsx b/apps/Frontend/src/components/appointments/appointment-table.tsx deleted file mode 100644 index 13e8ec7..0000000 --- a/apps/Frontend/src/components/appointments/appointment-table.tsx +++ /dev/null @@ -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 {config.label}; - }; - - // 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 ( -
- - - - Patient - Date - Time - Type - Status - Actions - - - - {sortedAppointments.length === 0 ? ( - - - No appointments found. - - - ) : ( - sortedAppointments.map((appointment) => ( - - - {getPatientName(appointment.patientId)} - - -
- - {format(new Date(appointment.date), "MMM d, yyyy")} -
-
- -
- - {appointment.startTime.slice(0, 5)} -{" "} - {appointment.endTime.slice(0, 5)} -
-
- - {appointment.type.replace("-", " ")} - - {getStatusBadge(appointment.status!)} - - - - - - - Actions - onEdit(appointment)}> - - Edit - - - { - if (typeof appointment.id === "number") { - onDelete(appointment.id); - } else { - console.error("Invalid appointment ID"); - } - }} - className="text-destructive focus:text-destructive" - > - - Delete - - - - -
- )) - )} -
-
-
- ); -} diff --git a/apps/Frontend/src/components/claims/claim-form.tsx b/apps/Frontend/src/components/claims/claim-form.tsx index 8d0de24..92a79bb 100644 --- a/apps/Frontend/src/components/claims/claim-form.tsx +++ b/apps/Frontend/src/components/claims/claim-form.tsx @@ -133,6 +133,10 @@ export function ClaimForm({ const [serviceDate, setServiceDate] = useState( 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 */}
- +
{/* Date Picker */} - + + setOpenProcedureDateIndex(open ? i : null) + } + > -

{formattedDate}

+

+ {formattedSelectedDate} +

+ + {/* Top button with popover calendar */} +
+ + + + + + + + { + if (date) setSelectedDate(date); + }} + onClose={() => setCalendarOpen(false)} + /> + + +
@@ -747,87 +799,6 @@ export default function AppointmentsPage() { - - {/* Right side - Calendar and Stats */} -
- {/* Calendar Card */} - - - Calendar - - Select a date to view or schedule appointments - - - - { - if (date) setSelectedDate(date); - }} - /> - - - - {/* Statistics Card */} - - - - Appointments - - - - Statistics for {formattedDate} - - - -
-
- - Total appointments: - - - {selectedDateAppointments.length} - -
-
- With doctors: - - { - processedAppointments.filter( - (apt) => - staffMembers.find( - (s) => Number(s.id) === apt.staffId - )?.role === "doctor" - ).length - } - -
-
- - With hygienists: - - - { - processedAppointments.filter( - (apt) => - staffMembers.find( - (s) => Number(s.id) === apt.staffId - )?.role === "hygienist" - ).length - } - -
-
-
-
-
@@ -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)} /> ); diff --git a/apps/Frontend/src/utils/dateUtils.ts b/apps/Frontend/src/utils/dateUtils.ts index 8eb6bfa..54e8ab6 100644 --- a/apps/Frontend/src/utils/dateUtils.ts +++ b/apps/Frontend/src/utils/dateUtils.ts @@ -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)}`; +} +