feat(optimised query) - main route setup and updated at page
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: {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { useQuery, useMutation } from "@tanstack/react-query";
|
import { useQuery, useMutation, keepPreviousData } from "@tanstack/react-query";
|
||||||
import { format, addDays, startOfToday, addMinutes } from "date-fns";
|
import { format, addDays, startOfToday, addMinutes } from "date-fns";
|
||||||
import { parseLocalDate, formatLocalDate } from "@/utils/dateUtils";
|
import { parseLocalDate, formatLocalDate } from "@/utils/dateUtils";
|
||||||
import { AddAppointmentModal } from "@/components/appointments/add-appointment-modal";
|
import { AddAppointmentModal } from "@/components/appointments/add-appointment-modal";
|
||||||
@@ -69,16 +69,10 @@ 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 [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;
|
||||||
@@ -91,9 +85,8 @@ export default function AppointmentsPage() {
|
|||||||
id: APPOINTMENT_CONTEXT_MENU_ID,
|
id: APPOINTMENT_CONTEXT_MENU_ID,
|
||||||
});
|
});
|
||||||
|
|
||||||
//Fetching staff memebers
|
// Staff memebers
|
||||||
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/");
|
||||||
@@ -130,20 +123,44 @@ export default function AppointmentsPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch appointments
|
// ----------------------
|
||||||
|
// Day-level fetch: appointments + patients for selectedDate (lightweight)
|
||||||
|
// ----------------------
|
||||||
|
const formattedSelectedDate = formatLocalDate(selectedDate);
|
||||||
|
type DayPayload = { appointments: Appointment[]; patients: Patient[] };
|
||||||
|
const queryKey = ["appointments", "day", formattedSelectedDate] as const;
|
||||||
|
|
||||||
const {
|
const {
|
||||||
data: appointments = [] as Appointment[],
|
data: dayPayload = {
|
||||||
|
appointments: [] as Appointment[],
|
||||||
|
patients: [] as Patient[],
|
||||||
|
},
|
||||||
isLoading: isLoadingAppointments,
|
isLoading: isLoadingAppointments,
|
||||||
refetch: refetchAppointments,
|
refetch: refetchAppointments,
|
||||||
} = useQuery<Appointment[]>({
|
} = useQuery<
|
||||||
queryKey: ["/api/appointments/all"],
|
DayPayload,
|
||||||
|
Error,
|
||||||
|
DayPayload,
|
||||||
|
readonly [string, string, string]
|
||||||
|
>({
|
||||||
|
queryKey,
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const res = await apiRequest("GET", "/api/appointments/all");
|
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();
|
return res.json();
|
||||||
},
|
},
|
||||||
enabled: !!user,
|
enabled: !!user && !!formattedSelectedDate,
|
||||||
|
placeholderData: keepPreviousData,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const appointments = dayPayload.appointments ?? [];
|
||||||
|
const patientsFromDay = dayPayload.patients ?? [];
|
||||||
|
|
||||||
// Fetch patients (needed for the dropdowns)
|
// Fetch patients (needed for the dropdowns)
|
||||||
const { data: patients = [], isLoading: isLoadingPatients } = useQuery<
|
const { data: patients = [], isLoading: isLoadingPatients } = useQuery<
|
||||||
Patient[]
|
Patient[]
|
||||||
@@ -344,7 +361,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 = {
|
||||||
@@ -399,12 +415,7 @@ export default function AppointmentsPage() {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const toggleMobileMenu = () => {
|
|
||||||
setIsMobileMenuOpen(!isMobileMenuOpen);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Get formatted date string for display
|
// Get formatted date string for display
|
||||||
const formattedDate = format(selectedDate, "yyyy-MM-dd");
|
|
||||||
|
|
||||||
const selectedDateAppointments = appointments.filter((appointment) => {
|
const selectedDateAppointments = appointments.filter((appointment) => {
|
||||||
const dateObj = parseLocalDate(appointment.date);
|
const dateObj = parseLocalDate(appointment.date);
|
||||||
@@ -690,7 +701,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"
|
||||||
@@ -783,7 +796,7 @@ export default function AppointmentsPage() {
|
|||||||
</Button>
|
</Button>
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
Statistics for {formattedDate}
|
Statistics for {formattedSelectedDate}
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
|
|||||||
Reference in New Issue
Block a user