appointment creation fixed
This commit is contained in:
409
apps/Frontend/src/components/claims/claim-form-handler.tsx
Normal file
409
apps/Frontend/src/components/claims/claim-form-handler.tsx
Normal file
@@ -0,0 +1,409 @@
|
||||
import { AppDispatch } from "@/redux/store";
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { TopAppBar } from "@/components/layout/top-app-bar";
|
||||
import { Sidebar } from "@/components/layout/sidebar";
|
||||
import {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
} from "@/components/ui/card";
|
||||
import { ClaimForm } from "@/components/claims/claim-form";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import {
|
||||
PatientUncheckedCreateInputObjectSchema,
|
||||
AppointmentUncheckedCreateInputObjectSchema,
|
||||
ClaimUncheckedCreateInputObjectSchema,
|
||||
} from "@repo/db/usedSchemas";
|
||||
import { FileCheck } from "lucide-react";
|
||||
import { parse } from "date-fns";
|
||||
import { z } from "zod";
|
||||
import { apiRequest, queryClient } from "@/lib/queryClient";
|
||||
import { useLocation } from "wouter";
|
||||
import { useAppDispatch, useAppSelector } from "@/redux/hooks";
|
||||
import {
|
||||
setTaskStatus,
|
||||
clearTaskStatus,
|
||||
} from "@/redux/slices/seleniumClaimSubmitTaskSlice";
|
||||
import { SeleniumTaskBanner } from "@/components/ui/selenium-task-banner";
|
||||
import { formatLocalDate, parseLocalDate } from "@/utils/dateUtils";
|
||||
import ClaimsRecentTable from "@/components/claims/claims-recent-table";
|
||||
import ClaimsOfPatientModal from "@/components/claims/claims-of-patient-table";
|
||||
|
||||
//creating types out of schema auto generated.
|
||||
type Appointment = z.infer<typeof AppointmentUncheckedCreateInputObjectSchema>;
|
||||
type Claim = z.infer<typeof ClaimUncheckedCreateInputObjectSchema>;
|
||||
|
||||
const insertAppointmentSchema = (
|
||||
AppointmentUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any>
|
||||
).omit({
|
||||
id: true,
|
||||
createdAt: true,
|
||||
});
|
||||
type InsertAppointment = z.infer<typeof insertAppointmentSchema>;
|
||||
|
||||
const updateAppointmentSchema = (
|
||||
AppointmentUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any>
|
||||
)
|
||||
.omit({
|
||||
id: true,
|
||||
createdAt: true,
|
||||
})
|
||||
.partial();
|
||||
type UpdateAppointment = z.infer<typeof updateAppointmentSchema>;
|
||||
|
||||
const PatientSchema = (
|
||||
PatientUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any>
|
||||
).omit({
|
||||
appointments: true,
|
||||
});
|
||||
type Patient = z.infer<typeof PatientSchema>;
|
||||
|
||||
const insertPatientSchema = (
|
||||
PatientUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any>
|
||||
).omit({
|
||||
id: true,
|
||||
createdAt: true,
|
||||
});
|
||||
type InsertPatient = z.infer<typeof insertPatientSchema>;
|
||||
|
||||
const updatePatientSchema = (
|
||||
PatientUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any>
|
||||
)
|
||||
.omit({
|
||||
id: true,
|
||||
createdAt: true,
|
||||
userId: true,
|
||||
})
|
||||
.partial();
|
||||
|
||||
type UpdatePatient = z.infer<typeof updatePatientSchema>;
|
||||
|
||||
const { toast } = useToast();
|
||||
|
||||
// Add patient mutation
|
||||
const addPatientMutation = useMutation({
|
||||
mutationFn: async (patient: InsertPatient) => {
|
||||
const res = await apiRequest("POST", "/api/patients/", patient);
|
||||
return res.json();
|
||||
},
|
||||
onSuccess: (newPatient) => {
|
||||
queryClient.invalidateQueries({ queryKey: ["/api/patients/"] });
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Patient added successfully!",
|
||||
variant: "default",
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: `Failed to add patient: ${error.message}`,
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Update patient mutation
|
||||
const updatePatientMutation = useMutation({
|
||||
mutationFn: async ({
|
||||
id,
|
||||
patient,
|
||||
}: {
|
||||
id: number;
|
||||
patient: UpdatePatient;
|
||||
}) => {
|
||||
const res = await apiRequest("PUT", `/api/patients/${id}`, patient);
|
||||
return res.json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["/api/patients/"] });
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Patient updated successfully!",
|
||||
variant: "default",
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: `Failed to update patient: ${error.message}`,
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Create/upsert appointment mutation
|
||||
const createAppointmentMutation = useMutation({
|
||||
mutationFn: async (appointment: InsertAppointment) => {
|
||||
const res = await apiRequest("POST", "/api/appointments/upsert", appointment);
|
||||
return await res.json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Appointment created successfully.",
|
||||
});
|
||||
// Invalidate both appointments and patients queries
|
||||
queryClient.invalidateQueries({ queryKey: ["/api/appointments/all"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["/api/patients/"] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: `Failed to create appointment: ${error.message}`,
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Update appointment mutation
|
||||
const updateAppointmentMutation = useMutation({
|
||||
mutationFn: async ({
|
||||
id,
|
||||
appointment,
|
||||
}: {
|
||||
id: number;
|
||||
appointment: UpdateAppointment;
|
||||
}) => {
|
||||
const res = await apiRequest("PUT", `/api/appointments/${id}`, appointment);
|
||||
return await res.json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Appointment updated successfully.",
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: ["/api/appointments/all"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["/api/patients/"] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: `Failed to update appointment: ${error.message}`,
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const createClaimMutation = useMutation({
|
||||
mutationFn: async (claimData: any) => {
|
||||
const res = await apiRequest("POST", "/api/claims/", claimData);
|
||||
return res.json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast({
|
||||
title: "Claim created successfully",
|
||||
variant: "default",
|
||||
});
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast({
|
||||
title: "Error submitting claim",
|
||||
description: error.message,
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
function handleClaimSubmit(claimData: any): Promise<Claim> {
|
||||
return createClaimMutation.mutateAsync(claimData).then((data) => {
|
||||
return data;
|
||||
});
|
||||
}
|
||||
|
||||
const handleAppointmentSubmit = async (
|
||||
appointmentData: InsertAppointment | UpdateAppointment
|
||||
): Promise<number> => {
|
||||
const rawDate = parseLocalDate(appointmentData.date);
|
||||
const formattedDate = formatLocalDate(rawDate);
|
||||
|
||||
// Prepare minimal data to update/create
|
||||
const minimalData = {
|
||||
date: rawDate.toLocaleDateString("en-CA"), // "YYYY-MM-DD" format
|
||||
startTime: appointmentData.startTime || "09:00",
|
||||
endTime: appointmentData.endTime || "09:30",
|
||||
staffId: appointmentData.staffId,
|
||||
};
|
||||
|
||||
// Find existing appointment for this patient on the same date
|
||||
const existingAppointment = appointments.find(
|
||||
(a) =>
|
||||
a.patientId === appointmentData.patientId &&
|
||||
formatLocalDate(parseLocalDate(a.date)) === formattedDate
|
||||
);
|
||||
|
||||
if (existingAppointment && typeof existingAppointment.id === "number") {
|
||||
// Update appointment with only date
|
||||
updateAppointmentMutation.mutate({
|
||||
id: existingAppointment.id,
|
||||
appointment: minimalData,
|
||||
});
|
||||
return existingAppointment.id;
|
||||
}
|
||||
|
||||
return new Promise<number>((resolve, reject) => {
|
||||
createAppointmentMutation.mutate(
|
||||
{
|
||||
...minimalData,
|
||||
patientId: appointmentData.patientId,
|
||||
userId: user?.id,
|
||||
title: "Scheduled Appointment",
|
||||
type: "checkup",
|
||||
},
|
||||
{
|
||||
onSuccess: (newAppointment) => {
|
||||
resolve(newAppointment.id);
|
||||
},
|
||||
onError: (error) => {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Could not create appointment",
|
||||
variant: "destructive",
|
||||
});
|
||||
reject(error);
|
||||
},
|
||||
}
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
// Update Patient ( for insuranceId and Insurance Provider)
|
||||
const handleUpdatePatient = (patient: UpdatePatient & { id?: number }) => {
|
||||
if (patient) {
|
||||
const { id, ...sanitizedPatient } = patient;
|
||||
updatePatientMutation.mutate({
|
||||
id: Number(patient.id),
|
||||
patient: sanitizedPatient,
|
||||
});
|
||||
} else {
|
||||
console.error("No current patient or user found for update");
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Cannot update patient: No patient or user found",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// handle selenium sybmiting Mass Health claim
|
||||
export const handleMHClaimSubmitSelenium = async (
|
||||
data: any,
|
||||
dispatch: AppDispatch,
|
||||
selectedPatient: number | null
|
||||
) => {
|
||||
const formData = new FormData();
|
||||
formData.append("data", JSON.stringify(data));
|
||||
const uploadedFiles: File[] = data.uploadedFiles ?? [];
|
||||
|
||||
uploadedFiles.forEach((file: File) => {
|
||||
if (file.type === "application/pdf") {
|
||||
formData.append("pdfs", file);
|
||||
} else if (file.type.startsWith("image/")) {
|
||||
formData.append("images", file);
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
status: "pending",
|
||||
message: "Submitting claim to Selenium...",
|
||||
})
|
||||
);
|
||||
const response = await apiRequest("POST", "/api/claims/selenium", formData);
|
||||
const result1 = await response.json();
|
||||
if (result1.error) throw new Error(result1.error);
|
||||
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
status: "pending",
|
||||
message: "Submitted to Selenium. Awaiting PDF...",
|
||||
})
|
||||
);
|
||||
|
||||
toast({
|
||||
title: "Selenium service notified",
|
||||
description:
|
||||
"Your claim data was successfully sent to Selenium, Waitinig for its response.",
|
||||
variant: "default",
|
||||
});
|
||||
|
||||
const result2 = await handleSeleniumPdfDownload(
|
||||
result1,
|
||||
dispatch,
|
||||
selectedPatient
|
||||
);
|
||||
return result2;
|
||||
} catch (error: any) {
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
status: "error",
|
||||
message: error.message || "Selenium submission failed",
|
||||
})
|
||||
);
|
||||
toast({
|
||||
title: "Selenium service error",
|
||||
description: error.message || "An error occurred.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// selenium pdf download handler
|
||||
export const handleSeleniumPdfDownload = async (
|
||||
data: any,
|
||||
dispatch: AppDispatch,
|
||||
selectedPatient: number | null
|
||||
) => {
|
||||
try {
|
||||
if (!selectedPatient) {
|
||||
throw new Error("Missing patientId");
|
||||
}
|
||||
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
status: "pending",
|
||||
message: "Downloading PDF from Selenium...",
|
||||
})
|
||||
);
|
||||
|
||||
const res = await apiRequest("POST", "/api/claims/selenium/fetchpdf", {
|
||||
patientId: selectedPatient,
|
||||
pdf_url: data.pdf_url,
|
||||
});
|
||||
const result = await res.json();
|
||||
if (result.error) throw new Error(result.error);
|
||||
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
status: "success",
|
||||
message: "Claim submitted & PDF downloaded successfully.",
|
||||
})
|
||||
);
|
||||
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Claim Submitted and Pdf Downloaded completed.",
|
||||
});
|
||||
|
||||
// setSelectedPatient(null);
|
||||
|
||||
return result;
|
||||
} catch (error: any) {
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
status: "error",
|
||||
message: error.message || "Failed to download PDF",
|
||||
})
|
||||
);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: error.message || "Failed to fetch PDF",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -22,6 +22,8 @@ import {
|
||||
PatientUncheckedCreateInputObjectSchema,
|
||||
AppointmentUncheckedCreateInputObjectSchema,
|
||||
ClaimUncheckedCreateInputObjectSchema,
|
||||
ClaimStatusSchema,
|
||||
StaffUncheckedCreateInputObjectSchema,
|
||||
} from "@repo/db/usedSchemas";
|
||||
import { z } from "zod";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
@@ -31,7 +33,6 @@ import { useAuth } from "@/hooks/use-auth";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import procedureCodes from "../../assets/data/procedureCodes.json";
|
||||
@@ -57,7 +58,6 @@ const updatePatientSchema = (
|
||||
type UpdatePatient = z.infer<typeof updatePatientSchema>;
|
||||
|
||||
//creating types out of schema auto generated.
|
||||
type Appointment = z.infer<typeof AppointmentUncheckedCreateInputObjectSchema>;
|
||||
|
||||
const insertAppointmentSchema = (
|
||||
AppointmentUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any>
|
||||
@@ -114,35 +114,31 @@ interface ClaimFormProps {
|
||||
appointmentData: InsertAppointment | UpdateAppointment
|
||||
) => void;
|
||||
onHandleUpdatePatient: (patient: UpdatePatient & { id: number }) => void;
|
||||
onHandleForSelenium: (data: ClaimFormData) => void;
|
||||
onHandleForMHSelenium: (data: ClaimFormData) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
interface Staff {
|
||||
id: string;
|
||||
name: string;
|
||||
role: "doctor" | "hygienist";
|
||||
color: string;
|
||||
}
|
||||
export type ClaimStatus = z.infer<typeof ClaimStatusSchema>;
|
||||
type Staff = z.infer<typeof StaffUncheckedCreateInputObjectSchema>;
|
||||
|
||||
export function ClaimForm({
|
||||
patientId,
|
||||
extractedData,
|
||||
onHandleAppointmentSubmit,
|
||||
onHandleUpdatePatient,
|
||||
onHandleForSelenium,
|
||||
onHandleForMHSelenium,
|
||||
onSubmit,
|
||||
onClose,
|
||||
}: ClaimFormProps) {
|
||||
const { toast } = useToast();
|
||||
const { user } = useAuth();
|
||||
|
||||
// Patient state - initialize from extractedData or null (new patient)
|
||||
// Patient state - initialize from extractedData (if given ) or null (new patient)
|
||||
const [patient, setPatient] = useState<Patient | null>(
|
||||
extractedData ? ({ ...extractedData } as Patient) : null
|
||||
);
|
||||
|
||||
// Query patient
|
||||
// Query patient based on given patient id
|
||||
const {
|
||||
data: fetchedPatient,
|
||||
isLoading,
|
||||
@@ -189,7 +185,6 @@ export function ClaimForm({
|
||||
const [serviceDate, setServiceDate] = useState<string>(
|
||||
formatLocalDate(new Date())
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (extractedData?.serviceDate) {
|
||||
const parsed = parseLocalDate(extractedData.serviceDate);
|
||||
@@ -209,6 +204,21 @@ export function ClaimForm({
|
||||
}
|
||||
};
|
||||
|
||||
// when service date is chenged, it will change the each service lines procedure date in sync as well.
|
||||
useEffect(() => {
|
||||
setForm((prevForm) => {
|
||||
const updatedLines = prevForm.serviceLines.map((line) => ({
|
||||
...line,
|
||||
procedureDate: serviceDate, // set all to current serviceDate string
|
||||
}));
|
||||
return {
|
||||
...prevForm,
|
||||
serviceLines: updatedLines,
|
||||
serviceDate, // keep form.serviceDate in sync as well
|
||||
};
|
||||
});
|
||||
}, [serviceDate]);
|
||||
|
||||
// Determine patient date of birth format
|
||||
const formatDOB = (dob: string | undefined) => {
|
||||
if (!dob) return "";
|
||||
@@ -262,20 +272,6 @@ export function ClaimForm({
|
||||
}
|
||||
}, [patient]);
|
||||
|
||||
useEffect(() => {
|
||||
setForm((prevForm) => {
|
||||
const updatedLines = prevForm.serviceLines.map((line) => ({
|
||||
...line,
|
||||
procedureDate: serviceDate, // set all to current serviceDate string
|
||||
}));
|
||||
return {
|
||||
...prevForm,
|
||||
serviceLines: updatedLines,
|
||||
serviceDate, // keep form.serviceDate in sync as well
|
||||
};
|
||||
});
|
||||
}, [serviceDate]);
|
||||
|
||||
// Handle patient field changes (to make inputs controlled and editable)
|
||||
const updatePatientField = (field: keyof Patient, value: any) => {
|
||||
setPatient((prev) => (prev ? { ...prev, [field]: value } : null));
|
||||
@@ -362,15 +358,14 @@ export function ClaimForm({
|
||||
setIsUploading(false);
|
||||
};
|
||||
|
||||
// Mass Health Button Handler
|
||||
// 1st Button workflow - Mass Health Button Handler
|
||||
const handleMHSubmit = async () => {
|
||||
// 1. Create or update appointment
|
||||
const appointmentData = {
|
||||
patientId: patientId,
|
||||
date: serviceDate,
|
||||
staffId: staff?.id,
|
||||
};
|
||||
|
||||
// 1. Create or update appointment
|
||||
const appointmentId = await onHandleAppointmentSubmit(appointmentData);
|
||||
|
||||
// 2. Update patient
|
||||
@@ -395,7 +390,6 @@ export function ClaimForm({
|
||||
const filteredServiceLines = form.serviceLines.filter(
|
||||
(line) => line.procedureCode.trim() !== ""
|
||||
);
|
||||
|
||||
const { uploadedFiles, insuranceSiteKey, ...formToCreateClaim } = form;
|
||||
const createdClaim = await onSubmit({
|
||||
...formToCreateClaim,
|
||||
@@ -407,7 +401,7 @@ export function ClaimForm({
|
||||
});
|
||||
|
||||
// 4. sending form data to selenium service
|
||||
onHandleForSelenium({
|
||||
onHandleForMHSelenium({
|
||||
...form,
|
||||
serviceLines: filteredServiceLines,
|
||||
staffId: Number(staff?.id),
|
||||
@@ -417,7 +411,8 @@ export function ClaimForm({
|
||||
insuranceSiteKey: "MH",
|
||||
claimId: createdClaim.id,
|
||||
});
|
||||
// 4. Close form
|
||||
|
||||
// 5. Close form
|
||||
onClose();
|
||||
};
|
||||
|
||||
@@ -541,10 +536,10 @@ export function ClaimForm({
|
||||
Treating Doctor
|
||||
</Label>
|
||||
<Select
|
||||
value={staff?.id || ""}
|
||||
value={staff?.id?.toString() || ""}
|
||||
onValueChange={(id) => {
|
||||
const selected = staffMembersRaw.find(
|
||||
(member) => member.id === id
|
||||
(member) => member.id?.toString() === id
|
||||
);
|
||||
if (selected) {
|
||||
setStaff(selected);
|
||||
@@ -562,11 +557,18 @@ export function ClaimForm({
|
||||
</SelectTrigger>
|
||||
|
||||
<SelectContent>
|
||||
{staffMembersRaw.map((member) => (
|
||||
<SelectItem key={member.id} value={member.id}>
|
||||
{member.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
{staffMembersRaw.map((member) => {
|
||||
if (member.id === undefined) return null;
|
||||
|
||||
return (
|
||||
<SelectItem
|
||||
key={member.id}
|
||||
value={member.id.toString()}
|
||||
>
|
||||
{member.name}
|
||||
</SelectItem>
|
||||
);
|
||||
})}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
@@ -287,10 +287,10 @@ export default function AppointmentsPage() {
|
||||
}
|
||||
}, [patients, user, location]);
|
||||
|
||||
// Create appointment mutation
|
||||
// Create/upsert appointment mutation
|
||||
const createAppointmentMutation = useMutation({
|
||||
mutationFn: async (appointment: InsertAppointment) => {
|
||||
const res = await apiRequest("POST", "/api/appointments/", appointment);
|
||||
const res = await apiRequest("POST", "/api/appointments/upsert", appointment);
|
||||
return await res.json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
|
||||
@@ -2,7 +2,13 @@ import { useState, useEffect, useMemo } from "react";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { TopAppBar } from "@/components/layout/top-app-bar";
|
||||
import { Sidebar } from "@/components/layout/sidebar";
|
||||
import { Card, CardHeader, CardTitle, CardContent, CardDescription } from "@/components/ui/card";
|
||||
import {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
} from "@/components/ui/card";
|
||||
import { ClaimForm } from "@/components/claims/claim-form";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
@@ -12,7 +18,7 @@ import {
|
||||
ClaimUncheckedCreateInputObjectSchema,
|
||||
} from "@repo/db/usedSchemas";
|
||||
import { FileCheck } from "lucide-react";
|
||||
import { parse, format } from "date-fns";
|
||||
import { parse } from "date-fns";
|
||||
import { z } from "zod";
|
||||
import { apiRequest, queryClient } from "@/lib/queryClient";
|
||||
import { useLocation } from "wouter";
|
||||
@@ -78,7 +84,9 @@ type UpdatePatient = z.infer<typeof updatePatientSchema>;
|
||||
export default function ClaimsPage() {
|
||||
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
|
||||
const [isClaimFormOpen, setIsClaimFormOpen] = useState(false);
|
||||
const [selectedPatient, setSelectedPatient] = useState<number | null>(null);
|
||||
const [selectedPatientId, setSelectedPatientId] = useState<number | null>(
|
||||
null
|
||||
);
|
||||
const dispatch = useAppDispatch();
|
||||
const { status, message, show } = useAppSelector(
|
||||
(state) => state.seleniumClaimSubmitTask
|
||||
@@ -168,10 +176,14 @@ export default function ClaimsPage() {
|
||||
},
|
||||
});
|
||||
|
||||
// Create appointment mutation
|
||||
// Create/upsert appointment mutation
|
||||
const createAppointmentMutation = useMutation({
|
||||
mutationFn: async (appointment: InsertAppointment) => {
|
||||
const res = await apiRequest("POST", "/api/appointments/", appointment);
|
||||
const res = await apiRequest(
|
||||
"POST",
|
||||
"/api/appointments/upsert",
|
||||
appointment
|
||||
);
|
||||
return await res.json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
@@ -228,50 +240,29 @@ export default function ClaimsPage() {
|
||||
const handleAppointmentSubmit = async (
|
||||
appointmentData: InsertAppointment | UpdateAppointment
|
||||
): Promise<number> => {
|
||||
const rawDate = parseLocalDate(appointmentData.date);
|
||||
const formattedDate = formatLocalDate(rawDate);
|
||||
|
||||
// Prepare minimal data to update/create
|
||||
const minimalData = {
|
||||
date: rawDate.toLocaleDateString("en-CA"), // "YYYY-MM-DD" format
|
||||
startTime: appointmentData.startTime || "09:00",
|
||||
endTime: appointmentData.endTime || "09:30",
|
||||
staffId: appointmentData.staffId,
|
||||
};
|
||||
|
||||
// Find existing appointment for this patient on the same date
|
||||
const existingAppointment = appointments.find(
|
||||
(a) =>
|
||||
a.patientId === appointmentData.patientId &&
|
||||
formatLocalDate(parseLocalDate(a.date)) === formattedDate
|
||||
);
|
||||
|
||||
if (existingAppointment && typeof existingAppointment.id === "number") {
|
||||
// Update appointment with only date
|
||||
updateAppointmentMutation.mutate({
|
||||
id: existingAppointment.id,
|
||||
appointment: minimalData,
|
||||
});
|
||||
return existingAppointment.id;
|
||||
}
|
||||
|
||||
return new Promise<number>((resolve, reject) => {
|
||||
console.log("Constructed appointmentData:", appointmentData);
|
||||
|
||||
console.log(appointmentData.date);
|
||||
createAppointmentMutation.mutate(
|
||||
{
|
||||
...minimalData,
|
||||
date: appointmentData.date,
|
||||
startTime: appointmentData.startTime || "09:00",
|
||||
endTime: appointmentData.endTime || "09:30",
|
||||
staffId: appointmentData.staffId,
|
||||
patientId: appointmentData.patientId,
|
||||
userId: user?.id,
|
||||
title: "Scheduled Appointment",
|
||||
type: "checkup",
|
||||
},
|
||||
{
|
||||
onSuccess: (newAppointment) => {
|
||||
resolve(newAppointment.id);
|
||||
onSuccess: (appointment) => {
|
||||
resolve(appointment.id);
|
||||
},
|
||||
onError: (error) => {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Could not create appointment",
|
||||
description: "Could not schedule appointment",
|
||||
variant: "destructive",
|
||||
});
|
||||
reject(error);
|
||||
@@ -324,7 +315,7 @@ export default function ClaimsPage() {
|
||||
};
|
||||
|
||||
const handleNewClaim = (patientId: number) => {
|
||||
setSelectedPatient(patientId);
|
||||
setSelectedPatientId(patientId);
|
||||
setIsClaimFormOpen(true);
|
||||
|
||||
const patient = patients.find((p) => p.id === patientId);
|
||||
@@ -334,6 +325,7 @@ export default function ClaimsPage() {
|
||||
};
|
||||
|
||||
const closeClaim = () => {
|
||||
setSelectedPatientId(null);
|
||||
setIsClaimFormOpen(false);
|
||||
setClaimFormData({
|
||||
patientId: null,
|
||||
@@ -379,7 +371,7 @@ export default function ClaimsPage() {
|
||||
);
|
||||
|
||||
if (matchingPatient) {
|
||||
setSelectedPatient(matchingPatient.id);
|
||||
setSelectedPatientId(matchingPatient.id);
|
||||
prefillClaimForm(matchingPatient);
|
||||
setIsClaimFormOpen(true);
|
||||
} else {
|
||||
@@ -401,7 +393,7 @@ export default function ClaimsPage() {
|
||||
|
||||
addPatientMutation.mutate(newPatient, {
|
||||
onSuccess: (created) => {
|
||||
setSelectedPatient(created.id);
|
||||
setSelectedPatientId(created.id);
|
||||
prefillClaimForm(created);
|
||||
setIsClaimFormOpen(true);
|
||||
},
|
||||
@@ -474,8 +466,8 @@ export default function ClaimsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
// handle selenium
|
||||
const handleSelenium = async (data: any) => {
|
||||
// handle selenium sybmiting Mass Health claim
|
||||
const handleMHClaimSubmitSelenium = async (data: any) => {
|
||||
const formData = new FormData();
|
||||
formData.append("data", JSON.stringify(data));
|
||||
const uploadedFiles: File[] = data.uploadedFiles ?? [];
|
||||
@@ -517,7 +509,7 @@ export default function ClaimsPage() {
|
||||
variant: "default",
|
||||
});
|
||||
|
||||
const result2 = await handleSeleniumPdfDownload(result1);
|
||||
const result2 = await handleMHSeleniumPdfDownload(result1);
|
||||
return result2;
|
||||
} catch (error: any) {
|
||||
dispatch(
|
||||
@@ -535,9 +527,9 @@ export default function ClaimsPage() {
|
||||
};
|
||||
|
||||
// selenium pdf download handler
|
||||
const handleSeleniumPdfDownload = async (data: any) => {
|
||||
const handleMHSeleniumPdfDownload = async (data: any) => {
|
||||
try {
|
||||
if (!selectedPatient) {
|
||||
if (!selectedPatientId) {
|
||||
throw new Error("Missing patientId");
|
||||
}
|
||||
|
||||
@@ -549,7 +541,7 @@ export default function ClaimsPage() {
|
||||
);
|
||||
|
||||
const res = await apiRequest("POST", "/api/claims/selenium/fetchpdf", {
|
||||
patientId: selectedPatient,
|
||||
patientId: selectedPatientId,
|
||||
pdf_url: data.pdf_url,
|
||||
});
|
||||
const result = await res.json();
|
||||
@@ -567,8 +559,6 @@ export default function ClaimsPage() {
|
||||
description: "Claim Submitted and Pdf Downloaded completed.",
|
||||
});
|
||||
|
||||
setSelectedPatient(null);
|
||||
|
||||
return result;
|
||||
} catch (error: any) {
|
||||
dispatch(
|
||||
@@ -705,20 +695,20 @@ export default function ClaimsPage() {
|
||||
|
||||
{/* Recent Claims Section */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Recently Submitted Claims</CardTitle>
|
||||
<CardDescription>
|
||||
View and manage all recent claims information
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ClaimsRecentTable
|
||||
allowEdit={true}
|
||||
allowView={true}
|
||||
allowDelete={true}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Recently Submitted Claims</CardTitle>
|
||||
<CardDescription>
|
||||
View and manage all recent claims information
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ClaimsRecentTable
|
||||
allowEdit={true}
|
||||
allowView={true}
|
||||
allowDelete={true}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Recent Claims by Patients */}
|
||||
<ClaimsOfPatientModal />
|
||||
@@ -726,15 +716,15 @@ export default function ClaimsPage() {
|
||||
</div>
|
||||
|
||||
{/* Claim Form Modal */}
|
||||
{isClaimFormOpen && selectedPatient !== null && (
|
||||
{isClaimFormOpen && selectedPatientId !== null && (
|
||||
<ClaimForm
|
||||
patientId={selectedPatient}
|
||||
patientId={selectedPatientId}
|
||||
onClose={closeClaim}
|
||||
extractedData={claimFormData}
|
||||
onSubmit={handleClaimSubmit}
|
||||
onHandleAppointmentSubmit={handleAppointmentSubmit}
|
||||
onHandleUpdatePatient={handleUpdatePatient}
|
||||
onHandleForSelenium={handleSelenium}
|
||||
onHandleForMHSelenium={handleMHClaimSubmitSelenium}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -153,10 +153,10 @@ export default function Dashboard() {
|
||||
|
||||
const isLoading = isLoadingPatients || addPatientMutation.isPending;
|
||||
|
||||
// Create appointment mutation
|
||||
// Create/upsert appointment mutation
|
||||
const createAppointmentMutation = useMutation({
|
||||
mutationFn: async (appointment: InsertAppointment) => {
|
||||
const res = await apiRequest("POST", "/api/appointments/", appointment);
|
||||
const res = await apiRequest("POST", "/api/appointments/upsert", appointment);
|
||||
return await res.json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
|
||||
Reference in New Issue
Block a user