Merge branch 'feature/appointment-page' into develop
This commit is contained in:
@@ -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
|
// Get a single appointment by ID
|
||||||
router.get(
|
router.get(
|
||||||
"/:id",
|
"/: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
|
// Create a new appointment
|
||||||
router.post(
|
router.post(
|
||||||
"/upsert",
|
"/upsert",
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ export interface IStorage {
|
|||||||
getPatientByInsuranceId(insuranceId: string): Promise<Patient | null>;
|
getPatientByInsuranceId(insuranceId: string): Promise<Patient | null>;
|
||||||
getPatientsByUserId(userId: number): Promise<Patient[]>;
|
getPatientsByUserId(userId: number): Promise<Patient[]>;
|
||||||
getRecentPatients(limit: number, offset: number): Promise<Patient[]>;
|
getRecentPatients(limit: number, offset: number): Promise<Patient[]>;
|
||||||
getTotalPatientCount(): Promise<number>;
|
getPatientsByIds(ids: number[]): Promise<Patient[]>;
|
||||||
createPatient(patient: InsertPatient): Promise<Patient>;
|
createPatient(patient: InsertPatient): Promise<Patient>;
|
||||||
updatePatient(id: number, patient: UpdatePatient): Promise<Patient>;
|
updatePatient(id: number, patient: UpdatePatient): Promise<Patient>;
|
||||||
deletePatient(id: number): Promise<void>;
|
deletePatient(id: number): Promise<void>;
|
||||||
@@ -62,6 +62,7 @@ export interface IStorage {
|
|||||||
status: string;
|
status: string;
|
||||||
}[]
|
}[]
|
||||||
>;
|
>;
|
||||||
|
getTotalPatientCount(): Promise<number>;
|
||||||
countPatients(filters: any): Promise<number>; // optional but useful
|
countPatients(filters: any): Promise<number>; // optional but useful
|
||||||
|
|
||||||
// Appointment methods
|
// Appointment methods
|
||||||
@@ -70,7 +71,7 @@ export interface IStorage {
|
|||||||
getAppointmentsByUserId(userId: number): Promise<Appointment[]>;
|
getAppointmentsByUserId(userId: number): Promise<Appointment[]>;
|
||||||
getAppointmentsByPatientId(patientId: number): Promise<Appointment[]>;
|
getAppointmentsByPatientId(patientId: number): Promise<Appointment[]>;
|
||||||
getRecentAppointments(limit: number, offset: 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>;
|
createAppointment(appointment: InsertAppointment): Promise<Appointment>;
|
||||||
updateAppointment(
|
updateAppointment(
|
||||||
id: number,
|
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({
|
async searchPatients({
|
||||||
filters,
|
filters,
|
||||||
limit,
|
limit,
|
||||||
@@ -326,30 +373,6 @@ export const storage: IStorage = {
|
|||||||
return db.patient.count({ where: filters });
|
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
|
// Appointment methods
|
||||||
async getAppointment(id: number): Promise<Appointment | undefined> {
|
async getAppointment(id: number): Promise<Appointment | undefined> {
|
||||||
const appointment = await db.appointment.findUnique({ where: { id } });
|
const appointment = await db.appointment.findUnique({ where: { id } });
|
||||||
@@ -368,13 +391,7 @@ export const storage: IStorage = {
|
|||||||
return await db.appointment.findMany({ where: { patientId } });
|
return await db.appointment.findMany({ where: { patientId } });
|
||||||
},
|
},
|
||||||
|
|
||||||
async getAppointmentsOn(date: Date): Promise<Appointment[]> {
|
async getAppointmentsOnRange(start: Date, end: 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);
|
|
||||||
|
|
||||||
return db.appointment.findMany({
|
return db.appointment.findMany({
|
||||||
where: {
|
where: {
|
||||||
date: {
|
date: {
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import { AppointmentForm } from "./appointment-form";
|
|||||||
import {
|
import {
|
||||||
Appointment,
|
Appointment,
|
||||||
InsertAppointment,
|
InsertAppointment,
|
||||||
Patient,
|
|
||||||
UpdateAppointment,
|
UpdateAppointment,
|
||||||
} from "@repo/db/types";
|
} from "@repo/db/types";
|
||||||
|
|
||||||
@@ -19,7 +18,6 @@ interface AddAppointmentModalProps {
|
|||||||
onDelete?: (id: number) => void;
|
onDelete?: (id: number) => void;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
appointment?: Appointment;
|
appointment?: Appointment;
|
||||||
patients: Patient[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AddAppointmentModal({
|
export function AddAppointmentModal({
|
||||||
@@ -29,7 +27,6 @@ export function AddAppointmentModal({
|
|||||||
onDelete,
|
onDelete,
|
||||||
isLoading,
|
isLoading,
|
||||||
appointment,
|
appointment,
|
||||||
patients,
|
|
||||||
}: AddAppointmentModalProps) {
|
}: AddAppointmentModalProps) {
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
@@ -42,7 +39,6 @@ export function AddAppointmentModal({
|
|||||||
<div className="p-1">
|
<div className="p-1">
|
||||||
<AppointmentForm
|
<AppointmentForm
|
||||||
appointment={appointment}
|
appointment={appointment}
|
||||||
patients={patients}
|
|
||||||
onSubmit={(data) => {
|
onSubmit={(data) => {
|
||||||
onSubmit(data);
|
onSubmit(data);
|
||||||
onOpenChange(false);
|
onOpenChange(false);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { format } from "date-fns";
|
import { format } from "date-fns";
|
||||||
@@ -34,10 +34,15 @@ import {
|
|||||||
UpdateAppointment,
|
UpdateAppointment,
|
||||||
} from "@repo/db/types";
|
} from "@repo/db/types";
|
||||||
import { DateInputField } from "@/components/ui/dateInputField";
|
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 {
|
interface AppointmentFormProps {
|
||||||
appointment?: Appointment;
|
appointment?: Appointment;
|
||||||
patients: Patient[];
|
|
||||||
onSubmit: (data: InsertAppointment | UpdateAppointment) => void;
|
onSubmit: (data: InsertAppointment | UpdateAppointment) => void;
|
||||||
onDelete?: (id: number) => void;
|
onDelete?: (id: number) => void;
|
||||||
onOpenChange?: (open: boolean) => void;
|
onOpenChange?: (open: boolean) => void;
|
||||||
@@ -46,7 +51,6 @@ interface AppointmentFormProps {
|
|||||||
|
|
||||||
export function AppointmentForm({
|
export function AppointmentForm({
|
||||||
appointment,
|
appointment,
|
||||||
patients,
|
|
||||||
onSubmit,
|
onSubmit,
|
||||||
onDelete,
|
onDelete,
|
||||||
onOpenChange,
|
onOpenChange,
|
||||||
@@ -54,6 +58,8 @@ export function AppointmentForm({
|
|||||||
}: AppointmentFormProps) {
|
}: AppointmentFormProps) {
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [prefillPatient, setPrefillPatient] = useState<Patient | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const timeout = setTimeout(() => {
|
const timeout = setTimeout(() => {
|
||||||
inputRef.current?.focus();
|
inputRef.current?.focus();
|
||||||
@@ -62,15 +68,14 @@ export function AppointmentForm({
|
|||||||
return () => clearTimeout(timeout);
|
return () => clearTimeout(timeout);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const { data: staffMembersRaw = [] as Staff[], isLoading: isLoadingStaff } =
|
const { data: staffMembersRaw = [] as Staff[] } = useQuery<Staff[]>({
|
||||||
useQuery<Staff[]>({
|
queryKey: ["/api/staffs/"],
|
||||||
queryKey: ["/api/staffs/"],
|
queryFn: async () => {
|
||||||
queryFn: async () => {
|
const res = await apiRequest("GET", "/api/staffs/");
|
||||||
const res = await apiRequest("GET", "/api/staffs/");
|
return res.json();
|
||||||
return res.json();
|
},
|
||||||
},
|
enabled: !!user,
|
||||||
enabled: !!user,
|
});
|
||||||
});
|
|
||||||
|
|
||||||
const colorMap: Record<string, string> = {
|
const colorMap: Record<string, string> = {
|
||||||
"Dr. Kai Gao": "bg-blue-600",
|
"Dr. Kai Gao": "bg-blue-600",
|
||||||
@@ -82,23 +87,6 @@ export function AppointmentForm({
|
|||||||
color: colorMap[staff.name] || "bg-gray-400",
|
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
|
// Get the stored data from session storage
|
||||||
const storedDataString = sessionStorage.getItem("newAppointmentData");
|
const storedDataString = sessionStorage.getItem("newAppointmentData");
|
||||||
let parsedStoredData = null;
|
let parsedStoredData = null;
|
||||||
@@ -169,50 +157,159 @@ export function AppointmentForm({
|
|||||||
defaultValues,
|
defaultValues,
|
||||||
});
|
});
|
||||||
|
|
||||||
const [searchTerm, setSearchTerm] = useState("");
|
// -----------------------------
|
||||||
const [debouncedSearchTerm] = useDebounce(searchTerm, 200); // 1 seconds
|
// PATIENT SEARCH (reuse PatientSearch)
|
||||||
const [filteredPatients, setFilteredPatients] = useState(patients);
|
// -----------------------------
|
||||||
|
const [selectOpen, setSelectOpen] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
// search criteria state (reused from patient page)
|
||||||
if (!debouncedSearchTerm.trim()) {
|
const [searchCriteria, setSearchCriteria] = useState<SearchCriteria | null>(
|
||||||
setFilteredPatients(patients);
|
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!);
|
||||||
|
}
|
||||||
|
|
||||||
|
url = `/api/patients/search?${searchParams.toString()}`;
|
||||||
} else {
|
} else {
|
||||||
const term = debouncedSearchTerm.toLowerCase();
|
url = `/api/patients/recent?limit=${limit}&offset=${offset}`;
|
||||||
setFilteredPatients(
|
|
||||||
patients.filter((p) =>
|
|
||||||
`${p.firstName} ${p.lastName} ${p.phone} ${p.dateOfBirth}`
|
|
||||||
.toLowerCase()
|
|
||||||
.includes(term)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}, [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<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
|
// Force form field values to update and clean up storage
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (parsedStoredData) {
|
if (!parsedStoredData) return;
|
||||||
// Update form field values directly
|
|
||||||
if (parsedStoredData.startTime) {
|
|
||||||
form.setValue("startTime", parsedStoredData.startTime);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (parsedStoredData.endTime) {
|
// set times/staff/date as before
|
||||||
form.setValue("endTime", parsedStoredData.endTime);
|
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) {
|
// ---- patient prefill: check main cache, else fetch once ----
|
||||||
form.setValue("staffId", parsedStoredData.staff);
|
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) {
|
// fetch single patient record (preferred)
|
||||||
const parsedDate =
|
(async () => {
|
||||||
typeof parsedStoredData.date === "string"
|
try {
|
||||||
? parseLocalDate(parsedStoredData.date)
|
const res = await apiRequest("GET", `/api/patients/${pid}`);
|
||||||
: new Date(parsedStoredData.date);
|
if (res.ok) {
|
||||||
form.setValue("date", parsedDate);
|
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 {
|
||||||
// Clean up session storage
|
// no patientId in storage — still remove to avoid stale state
|
||||||
sessionStorage.removeItem("newAppointmentData");
|
sessionStorage.removeItem("newAppointmentData");
|
||||||
}
|
}
|
||||||
}, [form]);
|
}, [form]);
|
||||||
@@ -224,12 +321,6 @@ export function AppointmentForm({
|
|||||||
? parseInt(data.patientId, 10)
|
? parseInt(data.patientId, 10)
|
||||||
: data.patientId;
|
: 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
|
// Auto-create title if it's empty
|
||||||
let title = data.title;
|
let title = data.title;
|
||||||
if (!title || title.trim() === "") {
|
if (!title || title.trim() === "") {
|
||||||
@@ -289,41 +380,109 @@ export function AppointmentForm({
|
|||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
<FormItem>
|
<FormItem>
|
||||||
<FormLabel>Patient</FormLabel>
|
<FormLabel>Patient</FormLabel>
|
||||||
|
|
||||||
<Select
|
<Select
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
onValueChange={(val) => field.onChange(Number(val))}
|
onOpenChange={(open: boolean) => {
|
||||||
value={field.value?.toString()}
|
setSelectOpen(open);
|
||||||
defaultValue={field.value?.toString()}
|
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>
|
<FormControl>
|
||||||
<SelectTrigger>
|
<SelectTrigger>
|
||||||
<SelectValue placeholder="Select a patient" />
|
<SelectValue placeholder="Select a patient" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
|
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
|
{/* Reuse full PatientSearch UI inside dropdown — callbacks update the query */}
|
||||||
<div className="p-2" onKeyDown={(e) => e.stopPropagation()}>
|
<div className="p-2" onKeyDown={(e) => e.stopPropagation()}>
|
||||||
<Input
|
<PatientSearch
|
||||||
ref={inputRef}
|
onSearch={(criteria) => {
|
||||||
placeholder="Search patients..."
|
setSearchCriteria(criteria);
|
||||||
className="w-full"
|
setIsSearchActive(true);
|
||||||
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
|
|
||||||
}
|
|
||||||
}}
|
}}
|
||||||
|
onClearSearch={() => {
|
||||||
|
setSearchCriteria({
|
||||||
|
searchTerm: "",
|
||||||
|
searchBy: "name",
|
||||||
|
});
|
||||||
|
setIsSearchActive(false);
|
||||||
|
}}
|
||||||
|
isSearchActive={isSearchActive}
|
||||||
/>
|
/>
|
||||||
</div>
|
</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">
|
<div className="max-h-60 overflow-y-auto scrollbar-thin scrollbar-thumb-muted-foreground/30">
|
||||||
{filteredPatients.length > 0 ? (
|
{isFetchingPatients ? (
|
||||||
filteredPatients.map((patient) => (
|
<div className="p-2 text-sm text-muted-foreground">
|
||||||
|
Loading...
|
||||||
|
</div>
|
||||||
|
) : patients && patients.length > 0 ? (
|
||||||
|
patients.map((patient) => (
|
||||||
<SelectItem
|
<SelectItem
|
||||||
key={patient.id}
|
key={patient.id}
|
||||||
value={patient.id?.toString() ?? ""}
|
value={patient.id?.toString() ?? ""}
|
||||||
>
|
>
|
||||||
<div className="flex flex-col">
|
<div className="flex flex-col items-start">
|
||||||
<span className="font-medium">
|
<span className="font-medium">
|
||||||
{patient.firstName} {patient.lastName}
|
{patient.firstName} {patient.lastName}
|
||||||
</span>
|
</span>
|
||||||
@@ -345,6 +504,7 @@ export function AppointmentForm({
|
|||||||
</div>
|
</div>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -133,6 +133,10 @@ export function ClaimForm({
|
|||||||
const [serviceDate, setServiceDate] = useState<string>(
|
const [serviceDate, setServiceDate] = useState<string>(
|
||||||
formatLocalDate(new Date())
|
formatLocalDate(new Date())
|
||||||
);
|
);
|
||||||
|
const [serviceDateOpen, setServiceDateOpen] = useState(false);
|
||||||
|
const [openProcedureDateIndex, setOpenProcedureDateIndex] = useState<
|
||||||
|
number | null
|
||||||
|
>(null);
|
||||||
|
|
||||||
// Update service date when calendar date changes
|
// Update service date when calendar date changes
|
||||||
const onServiceDateChange = (date: Date | undefined) => {
|
const onServiceDateChange = (date: Date | undefined) => {
|
||||||
@@ -559,7 +563,10 @@ export function ClaimForm({
|
|||||||
{/* Service Date */}
|
{/* Service Date */}
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Label className="flex items-center">Service Date</Label>
|
<Label className="flex items-center">Service Date</Label>
|
||||||
<Popover>
|
<Popover
|
||||||
|
open={serviceDateOpen}
|
||||||
|
onOpenChange={setServiceDateOpen}
|
||||||
|
>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
@@ -569,11 +576,14 @@ export function ClaimForm({
|
|||||||
{form.serviceDate}
|
{form.serviceDate}
|
||||||
</Button>
|
</Button>
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
<PopoverContent className="w-auto p-0" align="start">
|
<PopoverContent className="w-auto">
|
||||||
<Calendar
|
<Calendar
|
||||||
mode="single"
|
mode="single"
|
||||||
selected={serviceDateValue}
|
selected={serviceDateValue}
|
||||||
onSelect={onServiceDateChange}
|
onSelect={(date) => {
|
||||||
|
onServiceDateChange(date);
|
||||||
|
}}
|
||||||
|
onClose={() => setServiceDateOpen(false)}
|
||||||
/>
|
/>
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>
|
</Popover>
|
||||||
@@ -702,7 +712,12 @@ export function ClaimForm({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Date Picker */}
|
{/* Date Picker */}
|
||||||
<Popover>
|
<Popover
|
||||||
|
open={openProcedureDateIndex === i}
|
||||||
|
onOpenChange={(open) =>
|
||||||
|
setOpenProcedureDateIndex(open ? i : null)
|
||||||
|
}
|
||||||
|
>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
@@ -712,11 +727,16 @@ export function ClaimForm({
|
|||||||
{line.procedureDate || "Pick Date"}
|
{line.procedureDate || "Pick Date"}
|
||||||
</Button>
|
</Button>
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
<PopoverContent className="w-auto p-0">
|
<PopoverContent className="w-auto">
|
||||||
<Calendar
|
<Calendar
|
||||||
mode="single"
|
mode="single"
|
||||||
selected={new Date(line.procedureDate)}
|
selected={
|
||||||
|
line.procedureDate
|
||||||
|
? new Date(line.procedureDate)
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
onSelect={(date) => updateProcedureDate(i, date)}
|
onSelect={(date) => updateProcedureDate(i, date)}
|
||||||
|
onClose={() => setOpenProcedureDateIndex(null)}
|
||||||
/>
|
/>
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>
|
</Popover>
|
||||||
|
|||||||
@@ -43,6 +43,8 @@ export function PatientSearch({
|
|||||||
onClearSearch,
|
onClearSearch,
|
||||||
isSearchActive,
|
isSearchActive,
|
||||||
}: PatientSearchProps) {
|
}: PatientSearchProps) {
|
||||||
|
const [dobOpen, setDobOpen] = useState(false);
|
||||||
|
const [advanceDobOpen, setAdvanceDobOpen] = useState(false);
|
||||||
const [searchTerm, setSearchTerm] = useState("");
|
const [searchTerm, setSearchTerm] = useState("");
|
||||||
const [searchBy, setSearchBy] = useState<SearchCriteria["searchBy"]>("name");
|
const [searchBy, setSearchBy] = useState<SearchCriteria["searchBy"]>("name");
|
||||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||||
@@ -84,7 +86,7 @@ export function PatientSearch({
|
|||||||
<div className="flex gap-2 mb-4">
|
<div className="flex gap-2 mb-4">
|
||||||
<div className="relative flex-1">
|
<div className="relative flex-1">
|
||||||
{searchBy === "dob" ? (
|
{searchBy === "dob" ? (
|
||||||
<Popover>
|
<Popover open={dobOpen} onOpenChange={setDobOpen}>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
@@ -112,6 +114,7 @@ export function PatientSearch({
|
|||||||
if (date) {
|
if (date) {
|
||||||
const formattedDate = format(date, "yyyy-MM-dd");
|
const formattedDate = format(date, "yyyy-MM-dd");
|
||||||
setSearchTerm(String(formattedDate));
|
setSearchTerm(String(formattedDate));
|
||||||
|
setDobOpen(false);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
disabled={(date) => date > new Date()}
|
disabled={(date) => date > new Date()}
|
||||||
@@ -153,9 +156,10 @@ export function PatientSearch({
|
|||||||
|
|
||||||
<Select
|
<Select
|
||||||
value={searchBy}
|
value={searchBy}
|
||||||
onValueChange={(value) =>
|
onValueChange={(value) => {
|
||||||
setSearchBy(value as SearchCriteria["searchBy"])
|
setSearchBy(value as SearchCriteria["searchBy"]);
|
||||||
}
|
setSearchTerm("");
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<SelectTrigger className="w-[180px]">
|
<SelectTrigger className="w-[180px]">
|
||||||
<SelectValue placeholder="Search by..." />
|
<SelectValue placeholder="Search by..." />
|
||||||
@@ -189,12 +193,13 @@ export function PatientSearch({
|
|||||||
</label>
|
</label>
|
||||||
<Select
|
<Select
|
||||||
value={advancedCriteria.searchBy}
|
value={advancedCriteria.searchBy}
|
||||||
onValueChange={(value) =>
|
onValueChange={(value) => {
|
||||||
updateAdvancedCriteria(
|
setAdvancedCriteria((prev) => ({
|
||||||
"searchBy",
|
...prev,
|
||||||
value as SearchCriteria["searchBy"]
|
searchBy: value as SearchCriteria["searchBy"],
|
||||||
)
|
searchTerm: "",
|
||||||
}
|
}));
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<SelectTrigger className="col-span-3">
|
<SelectTrigger className="col-span-3">
|
||||||
<SelectValue placeholder="Name" />
|
<SelectValue placeholder="Name" />
|
||||||
@@ -215,9 +220,13 @@ export function PatientSearch({
|
|||||||
Search term
|
Search term
|
||||||
</label>
|
</label>
|
||||||
{advancedCriteria.searchBy === "dob" ? (
|
{advancedCriteria.searchBy === "dob" ? (
|
||||||
<Popover>
|
<Popover
|
||||||
|
open={advanceDobOpen}
|
||||||
|
onOpenChange={setAdvanceDobOpen}
|
||||||
|
>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
|
type="button"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key === "Enter") handleSearch();
|
if (e.key === "Enter") handleSearch();
|
||||||
@@ -251,6 +260,7 @@ export function PatientSearch({
|
|||||||
"searchTerm",
|
"searchTerm",
|
||||||
String(formattedDate)
|
String(formattedDate)
|
||||||
);
|
);
|
||||||
|
setAdvanceDobOpen(false);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
disabled={(date) => date > new Date()}
|
disabled={(date) => date > new Date()}
|
||||||
|
|||||||
@@ -13,20 +13,34 @@ type CalendarProps =
|
|||||||
mode: "single";
|
mode: "single";
|
||||||
selected?: Date;
|
selected?: Date;
|
||||||
onSelect?: (date: Date | undefined) => void;
|
onSelect?: (date: Date | undefined) => void;
|
||||||
|
closeOnSelect?: boolean /** whether to request closing after selection (default true for single) */;
|
||||||
|
onClose?: () => void;
|
||||||
})
|
})
|
||||||
| (BaseProps & {
|
| (BaseProps & {
|
||||||
mode: "range";
|
mode: "range";
|
||||||
selected?: DateRange;
|
selected?: DateRange;
|
||||||
onSelect?: (range: DateRange | undefined) => void;
|
onSelect?: (range: DateRange | undefined) => void;
|
||||||
|
closeOnSelect?: boolean; // will close only when range is complete
|
||||||
|
onClose?: () => void;
|
||||||
})
|
})
|
||||||
| (BaseProps & {
|
| (BaseProps & {
|
||||||
mode: "multiple";
|
mode: "multiple";
|
||||||
selected?: Date[];
|
selected?: Date[];
|
||||||
onSelect?: (dates: Date[] | undefined) => void;
|
onSelect?: (dates: Date[] | undefined) => void;
|
||||||
|
closeOnSelect?: boolean; // default false for multi
|
||||||
|
onClose?: () => void;
|
||||||
});
|
});
|
||||||
|
|
||||||
export function Calendar(props: CalendarProps) {
|
export function Calendar(props: CalendarProps) {
|
||||||
const { mode, selected, onSelect, className, ...rest } = props;
|
const {
|
||||||
|
mode,
|
||||||
|
selected,
|
||||||
|
onSelect,
|
||||||
|
className,
|
||||||
|
closeOnSelect,
|
||||||
|
onClose,
|
||||||
|
...rest
|
||||||
|
} = props;
|
||||||
|
|
||||||
const [internalSelected, setInternalSelected] =
|
const [internalSelected, setInternalSelected] =
|
||||||
useState<typeof selected>(selected);
|
useState<typeof selected>(selected);
|
||||||
@@ -37,7 +51,30 @@ export function Calendar(props: CalendarProps) {
|
|||||||
|
|
||||||
const handleSelect = (value: typeof selected) => {
|
const handleSelect = (value: typeof selected) => {
|
||||||
setInternalSelected(value);
|
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 (
|
return (
|
||||||
|
|||||||
@@ -19,6 +19,9 @@ interface DateInputProps {
|
|||||||
disablePast?: boolean;
|
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({
|
export function DateInput({
|
||||||
label,
|
label,
|
||||||
value,
|
value,
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ interface DateInputFieldProps {
|
|||||||
disablePast?: boolean;
|
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({
|
export function DateInputField({
|
||||||
control,
|
control,
|
||||||
name,
|
name,
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { useQuery, useMutation } from "@tanstack/react-query";
|
import { useQuery, useMutation } from "@tanstack/react-query";
|
||||||
import { format, addDays, startOfToday, addMinutes } from "date-fns";
|
import { addDays, startOfToday, addMinutes } from "date-fns";
|
||||||
import { parseLocalDate, formatLocalDate } from "@/utils/dateUtils";
|
import {
|
||||||
|
parseLocalDate,
|
||||||
|
formatLocalDate,
|
||||||
|
formatLocalTime,
|
||||||
|
} from "@/utils/dateUtils";
|
||||||
import { AddAppointmentModal } from "@/components/appointments/add-appointment-modal";
|
import { AddAppointmentModal } from "@/components/appointments/add-appointment-modal";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
@@ -9,7 +13,6 @@ import {
|
|||||||
Plus,
|
Plus,
|
||||||
ChevronLeft,
|
ChevronLeft,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
RefreshCw,
|
|
||||||
Move,
|
Move,
|
||||||
Trash2,
|
Trash2,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
@@ -17,13 +20,6 @@ import { useToast } from "@/hooks/use-toast";
|
|||||||
import { Calendar } from "@/components/ui/calendar";
|
import { Calendar } from "@/components/ui/calendar";
|
||||||
import { apiRequest, queryClient } from "@/lib/queryClient";
|
import { apiRequest, queryClient } from "@/lib/queryClient";
|
||||||
import { useAuth } from "@/hooks/use-auth";
|
import { useAuth } from "@/hooks/use-auth";
|
||||||
import {
|
|
||||||
Card,
|
|
||||||
CardContent,
|
|
||||||
CardHeader,
|
|
||||||
CardDescription,
|
|
||||||
CardTitle,
|
|
||||||
} from "@/components/ui/card";
|
|
||||||
import { DndProvider, useDrag, useDrop } from "react-dnd";
|
import { DndProvider, useDrag, useDrop } from "react-dnd";
|
||||||
import { HTML5Backend } from "react-dnd-html5-backend";
|
import { HTML5Backend } from "react-dnd-html5-backend";
|
||||||
import { Menu, Item, useContextMenu } from "react-contexify";
|
import { Menu, Item, useContextMenu } from "react-contexify";
|
||||||
@@ -36,6 +32,12 @@ import {
|
|||||||
Patient,
|
Patient,
|
||||||
UpdateAppointment,
|
UpdateAppointment,
|
||||||
} from "@repo/db/types";
|
} from "@repo/db/types";
|
||||||
|
import {
|
||||||
|
Popover,
|
||||||
|
PopoverContent,
|
||||||
|
PopoverTrigger,
|
||||||
|
} from "@/components/ui/popover";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
|
||||||
// Define types for scheduling
|
// Define types for scheduling
|
||||||
interface TimeSlot {
|
interface TimeSlot {
|
||||||
@@ -65,25 +67,25 @@ interface ScheduledAppointment {
|
|||||||
// Define a unique ID for the appointment context menu
|
// Define a unique ID for the appointment context menu
|
||||||
const APPOINTMENT_CONTEXT_MENU_ID = "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() {
|
export default function AppointmentsPage() {
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const [isAddModalOpen, setIsAddModalOpen] = useState(false);
|
const [isAddModalOpen, setIsAddModalOpen] = useState(false);
|
||||||
const [isClaimModalOpen, setIsClaimModalOpen] = useState(false);
|
const [calendarOpen, setCalendarOpen] = useState(false);
|
||||||
const [claimAppointmentId, setClaimAppointmentId] = useState<number | null>(
|
|
||||||
null
|
|
||||||
);
|
|
||||||
const [claimPatientId, setClaimPatientId] = useState<number | null>(null);
|
|
||||||
const [editingAppointment, setEditingAppointment] = useState<
|
const [editingAppointment, setEditingAppointment] = useState<
|
||||||
Appointment | undefined
|
Appointment | undefined
|
||||||
>(undefined);
|
>(undefined);
|
||||||
const [selectedDate, setSelectedDate] = useState<Date>(startOfToday());
|
const [selectedDate, setSelectedDate] = useState<Date>(startOfToday());
|
||||||
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
|
|
||||||
const [location] = useLocation();
|
const [location] = useLocation();
|
||||||
const [confirmDeleteState, setConfirmDeleteState] = useState<{
|
const [confirmDeleteState, setConfirmDeleteState] = useState<{
|
||||||
open: boolean;
|
open: boolean;
|
||||||
appointmentId?: number;
|
appointmentId?: number;
|
||||||
appointmentTitle?: string;
|
|
||||||
}>({ open: false });
|
}>({ open: false });
|
||||||
|
|
||||||
// Create context menu hook
|
// Create context menu hook
|
||||||
@@ -91,16 +93,51 @@ export default function AppointmentsPage() {
|
|||||||
id: APPOINTMENT_CONTEXT_MENU_ID,
|
id: APPOINTMENT_CONTEXT_MENU_ID,
|
||||||
});
|
});
|
||||||
|
|
||||||
//Fetching staff memebers
|
// ----------------------
|
||||||
const { data: staffMembersRaw = [] as Staff[], isLoading: isLoadingStaff } =
|
// Day-level fetch: appointments + patients for selectedDate (lightweight)
|
||||||
useQuery<Staff[]>({
|
// ----------------------
|
||||||
queryKey: ["/api/staffs/"],
|
const formattedSelectedDate = formatLocalDate(selectedDate);
|
||||||
queryFn: async () => {
|
type DayPayload = { appointments: Appointment[]; patients: Patient[] };
|
||||||
const res = await apiRequest("GET", "/api/staffs/");
|
const {
|
||||||
return res.json();
|
data: dayPayload = {
|
||||||
},
|
appointments: [] as Appointment[],
|
||||||
enabled: !!user,
|
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/");
|
||||||
|
return res.json();
|
||||||
|
},
|
||||||
|
enabled: !!user,
|
||||||
|
});
|
||||||
|
|
||||||
const colors = [
|
const colors = [
|
||||||
"bg-blue-600",
|
"bg-blue-600",
|
||||||
@@ -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
|
// Check for newPatient parameter in URL
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (patients.length === 0 || !user) return;
|
|
||||||
|
|
||||||
// Parse URL search params to check for newPatient
|
// Parse URL search params to check for newPatient
|
||||||
const params = new URLSearchParams(window.location.search);
|
const params = new URLSearchParams(window.location.search);
|
||||||
const newPatientId = params.get("newPatient");
|
const newPatientId = params.get("newPatient");
|
||||||
|
|
||||||
if (newPatientId) {
|
if (newPatientId) {
|
||||||
const patientId = parseInt(newPatientId);
|
const patientId = parseInt(newPatientId);
|
||||||
// Find the patient in our list
|
// Choose first available staff safely (fallback to 1 if none)
|
||||||
const patient = (patients as Patient[]).find((p) => p.id === patientId);
|
const firstStaff =
|
||||||
|
staffMembers && staffMembers.length > 0 ? staffMembers[0] : undefined;
|
||||||
if (patient) {
|
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({
|
toast({
|
||||||
title: "Patient Added",
|
title: "Unable to schedule",
|
||||||
description: `${patient.firstName} ${patient.lastName} was added successfully. You can now schedule an appointment.`,
|
description:
|
||||||
|
"No available time slots to schedule the new patient right now.",
|
||||||
|
variant: "destructive",
|
||||||
});
|
});
|
||||||
|
return;
|
||||||
// Select first available staff member
|
|
||||||
const staffId = staffMembers[0]!.id;
|
|
||||||
|
|
||||||
// Find first time slot today (9:00 AM is a common starting time)
|
|
||||||
const defaultTimeSlot =
|
|
||||||
timeSlots.find((slot) => slot.time === "09:00") || timeSlots[0];
|
|
||||||
|
|
||||||
// Open appointment modal with prefilled patient
|
|
||||||
handleCreateAppointmentAtSlot(defaultTimeSlot!, Number(staffId));
|
|
||||||
|
|
||||||
// Pre-select the patient in the appointment form
|
|
||||||
const patientData = {
|
|
||||||
patientId: patient.id,
|
|
||||||
};
|
|
||||||
|
|
||||||
// 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,
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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,
|
||||||
|
};
|
||||||
|
sessionStorage.setItem(
|
||||||
|
"newAppointmentData",
|
||||||
|
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
|
// Create/upsert appointment mutation
|
||||||
const createAppointmentMutation = useMutation({
|
const createAppointmentMutation = useMutation({
|
||||||
@@ -261,14 +233,15 @@ export default function AppointmentsPage() {
|
|||||||
);
|
);
|
||||||
return await res.json();
|
return await res.json();
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: (appointment) => {
|
||||||
toast({
|
toast({
|
||||||
title: "Success",
|
title: "Appointment Scheduled",
|
||||||
description: "Appointment created successfully.",
|
description: appointment.message || "Appointment created successfully.",
|
||||||
});
|
});
|
||||||
// Invalidate both appointments and patients queries
|
// Invalidate both appointments and patients queries
|
||||||
queryClient.invalidateQueries({ queryKey: ["/api/appointments/all"] });
|
queryClient.invalidateQueries({
|
||||||
queryClient.invalidateQueries({ queryKey: ["/api/patients/"] });
|
queryKey: qkAppointmentsDay(formattedSelectedDate),
|
||||||
|
});
|
||||||
setIsAddModalOpen(false);
|
setIsAddModalOpen(false);
|
||||||
},
|
},
|
||||||
onError: (error: Error) => {
|
onError: (error: Error) => {
|
||||||
@@ -296,13 +269,14 @@ export default function AppointmentsPage() {
|
|||||||
);
|
);
|
||||||
return await res.json();
|
return await res.json();
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: (appointment) => {
|
||||||
toast({
|
toast({
|
||||||
title: "Success",
|
title: "Appointment Scheduled",
|
||||||
description: "Appointment updated successfully.",
|
description: appointment.message || "Appointment created successfully.",
|
||||||
|
});
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: qkAppointmentsDay(formattedSelectedDate),
|
||||||
});
|
});
|
||||||
queryClient.invalidateQueries({ queryKey: ["/api/appointments/all"] });
|
|
||||||
queryClient.invalidateQueries({ queryKey: ["/api/patients/"] });
|
|
||||||
setEditingAppointment(undefined);
|
setEditingAppointment(undefined);
|
||||||
setIsAddModalOpen(false);
|
setIsAddModalOpen(false);
|
||||||
},
|
},
|
||||||
@@ -326,8 +300,9 @@ export default function AppointmentsPage() {
|
|||||||
description: "Appointment deleted successfully.",
|
description: "Appointment deleted successfully.",
|
||||||
});
|
});
|
||||||
// Invalidate both appointments and patients queries
|
// Invalidate both appointments and patients queries
|
||||||
queryClient.invalidateQueries({ queryKey: ["/api/appointments/all"] });
|
queryClient.invalidateQueries({
|
||||||
queryClient.invalidateQueries({ queryKey: ["/api/patients/"] });
|
queryKey: qkAppointmentsDay(formattedSelectedDate),
|
||||||
|
});
|
||||||
setConfirmDeleteState({ open: false });
|
setConfirmDeleteState({ open: false });
|
||||||
},
|
},
|
||||||
onError: (error: Error) => {
|
onError: (error: Error) => {
|
||||||
@@ -344,7 +319,6 @@ export default function AppointmentsPage() {
|
|||||||
appointmentData: InsertAppointment | UpdateAppointment
|
appointmentData: InsertAppointment | UpdateAppointment
|
||||||
) => {
|
) => {
|
||||||
// Converts local date to exact UTC date with no offset issues
|
// Converts local date to exact UTC date with no offset issues
|
||||||
|
|
||||||
const rawDate = parseLocalDate(appointmentData.date);
|
const rawDate = parseLocalDate(appointmentData.date);
|
||||||
|
|
||||||
const updatedData = {
|
const updatedData = {
|
||||||
@@ -386,80 +360,58 @@ export default function AppointmentsPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteAppointment = (id: number) => {
|
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({
|
setConfirmDeleteState({
|
||||||
open: true,
|
open: true,
|
||||||
appointmentId: id,
|
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
|
// Process appointments for the scheduler view
|
||||||
const processedAppointments: ScheduledAppointment[] =
|
const processedAppointments: ScheduledAppointment[] = (
|
||||||
selectedDateAppointments.map((apt) => {
|
appointments ?? []
|
||||||
// Find patient name
|
).map((apt) => {
|
||||||
const patient = patients.find((p) => p.id === apt.patientId);
|
// Find patient name
|
||||||
const patientName = patient
|
const patient = patientsFromDay.find((p) => p.id === apt.patientId);
|
||||||
? `${patient.firstName} ${patient.lastName}`
|
const patientName = patient
|
||||||
: "Unknown Patient";
|
? `${patient.firstName} ${patient.lastName}`
|
||||||
|
: "Unknown Patient";
|
||||||
|
|
||||||
let staffId: number;
|
const staffId = Number(apt.staffId ?? 1);
|
||||||
|
|
||||||
if (
|
const normalizedStart =
|
||||||
staffMembers &&
|
typeof apt.startTime === "string"
|
||||||
staffMembers.length > 0 &&
|
? apt.startTime.substring(0, 5)
|
||||||
staffMembers[0] !== undefined &&
|
: formatLocalTime(apt.startTime);
|
||||||
staffMembers[0].id !== undefined
|
const normalizedEnd =
|
||||||
) {
|
typeof apt.endTime === "string"
|
||||||
staffId = Number(apt.staffId);
|
? apt.endTime.substring(0, 5)
|
||||||
} else {
|
: formatLocalTime(apt.endTime);
|
||||||
staffId = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
const processed = {
|
const processed = {
|
||||||
...apt,
|
...apt,
|
||||||
patientName,
|
patientName,
|
||||||
staffId,
|
staffId,
|
||||||
status: apt.status ?? null,
|
status: apt.status ?? null,
|
||||||
date: formatLocalDate(parseLocalDate(apt.date)),
|
date: formatLocalDate(parseLocalDate(apt.date)),
|
||||||
};
|
startTime: normalizedStart,
|
||||||
|
endTime: normalizedEnd,
|
||||||
|
} as ScheduledAppointment;
|
||||||
|
|
||||||
return processed;
|
return processed;
|
||||||
});
|
});
|
||||||
|
|
||||||
// Check if appointment exists at a specific time slot and staff
|
// Check if appointment exists at a specific time slot and staff
|
||||||
const getAppointmentAtSlot = (timeSlot: TimeSlot, staffId: number) => {
|
const getAppointmentAtSlot = (timeSlot: TimeSlot, staffId: number) => {
|
||||||
if (processedAppointments.length === 0) {
|
if (!processedAppointments || processedAppointments.length === 0)
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
|
||||||
|
|
||||||
// In appointments for a given time slot, we'll just display the first one
|
// 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
|
// In a real application, you might want to show multiple or stack them
|
||||||
const appointmentsAtSlot = processedAppointments.filter((apt) => {
|
const appointmentsAtSlot = processedAppointments.filter((apt) => {
|
||||||
// Fix time format comparison - the database adds ":00" seconds to the time
|
|
||||||
const dbTime =
|
const dbTime =
|
||||||
typeof apt.startTime === "string" ? apt.startTime.substring(0, 5) : "";
|
typeof apt.startTime === "string" ? apt.startTime.substring(0, 5) : "";
|
||||||
|
|
||||||
const timeMatches = dbTime === timeSlot.time;
|
const timeMatches = dbTime === timeSlot.time;
|
||||||
const staffMatches = apt.staffId === staffId;
|
const staffMatches = apt.staffId === staffId;
|
||||||
|
|
||||||
return timeMatches && staffMatches;
|
return timeMatches && staffMatches;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -468,7 +420,6 @@ export default function AppointmentsPage() {
|
|||||||
|
|
||||||
const isLoading =
|
const isLoading =
|
||||||
isLoadingAppointments ||
|
isLoadingAppointments ||
|
||||||
isLoadingPatients ||
|
|
||||||
createAppointmentMutation.isPending ||
|
createAppointmentMutation.isPending ||
|
||||||
updateAppointmentMutation.isPending ||
|
updateAppointmentMutation.isPending ||
|
||||||
deleteAppointmentMutation.isPending;
|
deleteAppointmentMutation.isPending;
|
||||||
@@ -478,6 +429,76 @@ export default function AppointmentsPage() {
|
|||||||
APPOINTMENT: "appointment",
|
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
|
// Handle moving an appointment to a new time slot and staff
|
||||||
const handleMoveAppointment = (
|
const handleMoveAppointment = (
|
||||||
appointmentId: number,
|
appointmentId: number,
|
||||||
@@ -676,10 +697,10 @@ export default function AppointmentsPage() {
|
|||||||
</Item>
|
</Item>
|
||||||
</Menu>
|
</Menu>
|
||||||
|
|
||||||
{/* Main Content - Split into Schedule and Calendar */}
|
{/* Main Content */}
|
||||||
<div className="flex flex-col lg:flex-row gap-6">
|
<div className="flex flex-col lg:flex-row gap-6">
|
||||||
{/* Left side - Schedule Grid */}
|
{/* Schedule Grid */}
|
||||||
<div className="w-full lg:w-3/4 overflow-x-auto bg-white rounded-md shadow">
|
<div className="w-full overflow-x-auto bg-white rounded-md shadow">
|
||||||
<div className="p-4 border-b">
|
<div className="p-4 border-b">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div className="flex items-center space-x-2">
|
<div className="flex items-center space-x-2">
|
||||||
@@ -690,7 +711,9 @@ export default function AppointmentsPage() {
|
|||||||
>
|
>
|
||||||
<ChevronLeft className="h-4 w-4" />
|
<ChevronLeft className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
<h2 className="text-xl font-semibold">{formattedDate}</h2>
|
<h2 className="text-xl font-semibold">
|
||||||
|
{formattedSelectedDate}
|
||||||
|
</h2>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="icon"
|
size="icon"
|
||||||
@@ -699,6 +722,35 @@ export default function AppointmentsPage() {
|
|||||||
<ChevronRight className="h-4 w-4" />
|
<ChevronRight className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</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>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -747,87 +799,6 @@ export default function AppointmentsPage() {
|
|||||||
</div>
|
</div>
|
||||||
</DndProvider>
|
</DndProvider>
|
||||||
</div>
|
</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>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -841,7 +812,6 @@ export default function AppointmentsPage() {
|
|||||||
updateAppointmentMutation.isPending
|
updateAppointmentMutation.isPending
|
||||||
}
|
}
|
||||||
appointment={editingAppointment}
|
appointment={editingAppointment}
|
||||||
patients={patients}
|
|
||||||
onDelete={handleDeleteAppointment}
|
onDelete={handleDeleteAppointment}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -849,7 +819,7 @@ export default function AppointmentsPage() {
|
|||||||
isOpen={confirmDeleteState.open}
|
isOpen={confirmDeleteState.open}
|
||||||
onConfirm={handleConfirmDelete}
|
onConfirm={handleConfirmDelete}
|
||||||
onCancel={() => setConfirmDeleteState({ open: false })}
|
onCancel={() => setConfirmDeleteState({ open: false })}
|
||||||
entityName={confirmDeleteState.appointmentTitle}
|
entityName={String(confirmDeleteState.appointmentId)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -139,3 +139,59 @@ export function convertOCRDate(input: string | number | null | undefined): Date
|
|||||||
|
|
||||||
return new Date(year, month, day);
|
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)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user