chechpoiint only, claim form fixed, apppointmentcreation issue

This commit is contained in:
2025-05-29 19:54:54 +05:30
parent b4b044814b
commit f6d7d9f93b
5 changed files with 553 additions and 180 deletions

View File

@@ -19,10 +19,11 @@ import {
PopoverContent, PopoverContent,
PopoverTrigger, PopoverTrigger,
} from "@/components/ui/popover"; } from "@/components/ui/popover";
import { PatientUncheckedCreateInputObjectSchema } from "@repo/db/usedSchemas"; import { PatientUncheckedCreateInputObjectSchema, AppointmentUncheckedCreateInputObjectSchema} from "@repo/db/usedSchemas";
import { z } from "zod"; import { z } from "zod";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient"; import { apiRequest } from "@/lib/queryClient";
import { MultipleFileUploadZone } from "../file-upload/multiple-file-upload-zone";
const PatientSchema = ( const PatientSchema = (
PatientUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any> PatientUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any>
@@ -31,12 +32,36 @@ const PatientSchema = (
}); });
type Patient = z.infer<typeof PatientSchema>; type Patient = z.infer<typeof PatientSchema>;
//creating types out of schema auto generated.
type Appointment = z.infer<typeof AppointmentUncheckedCreateInputObjectSchema>;
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,
userId: true,
})
.partial();
type UpdateAppointment = z.infer<typeof updateAppointmentSchema>;
interface ServiceLine { interface ServiceLine {
procedureCode: string; procedure_code: string;
procedure_date: string;
oralCavityArea: string;
toothNumber: string; toothNumber: string;
surface: string; toothSurface: string;
quad: string;
authNo: string;
billedAmount: string; billedAmount: string;
} }
@@ -44,12 +69,21 @@ interface ClaimFormProps {
patientId?: number; patientId?: number;
extractedData?: Partial<Patient>; extractedData?: Partial<Patient>;
onSubmit: (claimData: any) => void; onSubmit: (claimData: any) => void;
onHandleAppointmentSubmit: (appointmentData: InsertAppointment | UpdateAppointment) => void;
onClose: () => void; onClose: () => void;
} }
interface Staff {
id: string;
name: string;
role: "doctor" | "hygienist";
color: string;
}
export function ClaimForm({ export function ClaimForm({
patientId, patientId,
extractedData, extractedData,
onHandleAppointmentSubmit,
onSubmit, onSubmit,
onClose, onClose,
}: ClaimFormProps) { }: ClaimFormProps) {
@@ -82,41 +116,61 @@ export function ClaimForm({
} }
}, [fetchedPatient]); }, [fetchedPatient]);
//Fetching staff memebers
const [staff, setStaff] = useState<Staff | null>(null);
const { data: staffMembersRaw = [] as Staff[], isLoading: isLoadingStaff } =
useQuery<Staff[]>({
queryKey: ["/api/staffs/"],
queryFn: async () => {
const res = await apiRequest("GET", "/api/staffs/");
return res.json();
},
});
// Service date state // Service date state
const [serviceDateValue, setServiceDateValue] = useState<Date>(new Date()); const [serviceDateValue, setServiceDateValue] = useState<Date>(new Date());
const [serviceDate, setServiceDate] = useState<string>( const [serviceDate, setServiceDate] = useState<string>(
format(new Date(), "MM/dd/yy") format(new Date(), "MM/dd/yyyy")
); );
useEffect(() => { const formatServiceDate = (date: Date | undefined): string => {
console.log("🚨 extractedData in effect:", extractedData); return date ? format(date, "MM/dd/yyyy") : "";
if (extractedData?.serviceDate) { };
const parsed = new Date(extractedData.serviceDate);
console.log("✅ Parsed serviceDate from extractedData:", parsed); useEffect(() => {
setServiceDateValue(parsed); if (extractedData?.serviceDate) {
setServiceDate(format(parsed, "MM/dd/yy")); const parsed = new Date(extractedData.serviceDate);
} setServiceDateValue(parsed);
}, [extractedData]); setServiceDate(formatServiceDate(parsed));
}
}, [extractedData]);
// used in submit button to send correct date.
function convertToISODate(mmddyyyy: string): string {
const [month, day, year] = mmddyyyy.split("/");
return `${year}-${month?.padStart(2, "0")}-${day?.padStart(2, "0")}`;
}
// Clinical notes state // Remarks state
const [clinicalNotes, setClinicalNotes] = useState<string>(""); const [remarks, setRemarks] = useState<string>("");
// Doctor selection state // Service lines state with one empty default line
const [doctor, setDoctor] = useState("doctor1"); const [serviceLines, setServiceLines] = useState<ServiceLine[]>([]);
useEffect(() => {
// Service lines state with one empty default line,, if (serviceDate) {
// note: this can be MAXIMUM 10 setServiceLines([
const [serviceLines, setServiceLines] = useState<ServiceLine[]>([ {
{ procedure_code: "",
procedureCode: "", procedure_date: serviceDate,
toothNumber: "", oralCavityArea: "",
surface: "", toothNumber: "",
quad: "", toothSurface: "",
authNo: "", billedAmount: "",
billedAmount: "", },
}, ]);
]); }
}, [serviceDate]);
// Update a field in serviceLines at index // Update a field in serviceLines at index
const updateServiceLine = ( const updateServiceLine = (
@@ -133,6 +187,11 @@ useEffect(() => {
}); });
}; };
const updateProcedureDate = (index: number, date: Date | undefined) => {
const formatted = formatServiceDate(date);
updateServiceLine(index, "procedure_date", formatted);
};
// Handle patient field changes (to make inputs controlled and editable) // Handle patient field changes (to make inputs controlled and editable)
const updatePatientField = (field: keyof Patient, value: any) => { const updatePatientField = (field: keyof Patient, value: any) => {
setPatient((prev) => (prev ? { ...prev, [field]: value } : null)); setPatient((prev) => (prev ? { ...prev, [field]: value } : null));
@@ -149,19 +208,44 @@ useEffect(() => {
// Determine patient date of birth format // Determine patient date of birth format
const formatDOB = (dob: string | undefined) => { const formatDOB = (dob: string | undefined) => {
if (!dob) return ""; if (!dob) return "";
if (/^\d{2}\/\d{2}\/\d{4}$/.test(dob)) return dob; // already MM/DD/YYYY if (/^\d{2}\/\d{2}\/\d{4}$/.test(dob)) return dob; // already MM/DD/YYYY
if (/^\d{4}-\d{2}-\d{2}/.test(dob)) { if (/^\d{4}-\d{2}-\d{2}/.test(dob)) {
const datePart = dob?.split("T")[0]; // safe optional chaining const datePart = dob?.split("T")[0]; // safe optional chaining
if (!datePart) return ""; if (!datePart) return "";
const [year, month, day] = datePart.split("-"); const [year, month, day] = datePart.split("-");
return `${month}/${day}/${year}`; return `${month}/${day}/${year}`;
} }
return dob; return dob;
}; };
// FILE UPLOAD ZONE
const [uploadedFiles, setUploadedFiles] = useState<File[]>([]);
const [isUploading, setIsUploading] = useState(false);
const handleFileUpload = (files: File[]) => {
setIsUploading(true);
const validFiles = files.filter((file) => file.type === "application/pdf");
if (validFiles.length > 10) {
toast({
title: "Too Many Files",
description: "You can only upload up to 10 PDFs.",
variant: "destructive",
});
setIsUploading(false);
return;
}
setUploadedFiles(validFiles);
toast({
title: "Files Selected",
description: `${validFiles.length} PDF file(s) ready for processing.`,
});
setIsUploading(false);
};
return ( return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 overflow-y-auto"> <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 overflow-y-auto">
<Card className="w-full max-w-5xl max-h-[90vh] overflow-y-auto bg-white"> <Card className="w-full max-w-5xl max-h-[90vh] overflow-y-auto bg-white">
@@ -225,38 +309,16 @@ useEffect(() => {
{/* Clinical Notes Entry */} {/* Clinical Notes Entry */}
<div className="mb-4 flex items-center gap-2"> <div className="mb-4 flex items-center gap-2">
<Label htmlFor="clinicalNotes" className="whitespace-nowrap"> <Label htmlFor="remarks" className="whitespace-nowrap">
Clinical Notes: Remarks:
</Label> </Label>
<Input <Input
id="clinicalNotes" id="remarks"
className="flex-grow" className="flex-grow"
placeholder="Paste clinical notes here" placeholder="Paste clinical notes here"
value={clinicalNotes} value={remarks}
onChange={(e) => setClinicalNotes(e.target.value)} onChange={(e) => setRemarks(e.target.value)}
/> />
<Button
variant="outline"
size="sm"
onClick={() => {
if (clinicalNotes.trim()) {
toast({
title: "Field Extraction",
description: "Clinical notes have been processed",
});
// Here you would add actual parsing logic to extract values
// from the clinicalNotes and update form fields
} else {
toast({
title: "Empty Input",
description: "Please enter clinical notes to extract",
variant: "destructive",
});
}
}}
>
Extract Fields
</Button>
</div> </div>
{/* Service Lines */} {/* Service Lines */}
@@ -265,13 +327,14 @@ useEffect(() => {
Service Lines Service Lines
</h3> </h3>
<div className="flex justify-end items-center mb-2"> <div className="flex justify-end items-center mb-2">
{/* 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>
<PopoverTrigger asChild> <PopoverTrigger asChild>
<Button <Button
variant="outline" variant="outline"
className="w-[120px] justify-start text-left font-normal" className="w-[140px] justify-start text-left font-normal mr-4"
> >
<CalendarIcon className="mr-2 h-4 w-4" /> <CalendarIcon className="mr-2 h-4 w-4" />
{serviceDate} {serviceDate}
@@ -286,16 +349,28 @@ useEffect(() => {
/> />
</PopoverContent> </PopoverContent>
</Popover> </Popover>
{/* Treating doctor */}
<Label className="flex items-center ml-2"> <Label className="flex items-center ml-2">
Treating Doctor Treating Doctor
</Label> </Label>
<Select value={doctor} onValueChange={setDoctor}> <Select
value={staff?.id || ""}
onValueChange={(id) => {
const selected = staffMembersRaw.find(
(member) => member.id === id
);
if (selected) setStaff(selected);
}}
>
<SelectTrigger className="w-36"> <SelectTrigger className="w-36">
<SelectValue placeholder="Select Doctor" /> <SelectValue placeholder="Select Staff" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="doctor1">Kai Gao</SelectItem> {staffMembersRaw.map((member) => (
<SelectItem value="doctor2">Jane Smith</SelectItem> <SelectItem key={member.id} value={member.id}>
{member.name}
</SelectItem>
))}
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
@@ -303,10 +378,10 @@ useEffect(() => {
<div className="grid grid-cols-6 gap-4 mb-2 font-medium text-sm text-gray-700"> <div className="grid grid-cols-6 gap-4 mb-2 font-medium text-sm text-gray-700">
<span>Procedure Code</span> <span>Procedure Code</span>
<span>Procedure Date</span>
<span>Oral Cavity Area</span>
<span>Tooth Number</span> <span>Tooth Number</span>
<span>Surface</span> <span>Tooth Surface</span>
<span>Quadrant</span>
<span>Auth No.</span>
<span>Billed Amount</span> <span>Billed Amount</span>
</div> </div>
@@ -314,47 +389,52 @@ useEffect(() => {
{serviceLines.map((line, i) => ( {serviceLines.map((line, i) => (
<div key={i} className="grid grid-cols-6 gap-4 mb-2"> <div key={i} className="grid grid-cols-6 gap-4 mb-2">
<Input <Input
placeholder="e.g. D0120" placeholder="eg. D0120"
value={line.procedureCode} value={line.procedure_code}
onChange={(e) => onChange={(e) =>
updateServiceLine(i, "procedureCode", e.target.value) updateServiceLine(i, "procedure_code", e.target.value)
}
/>
{/* Date Picker */}
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
className="w-full text-left font-normal"
>
<CalendarIcon className="mr-2 h-4 w-4" />
{line.procedure_date || "Pick Date"}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Calendar
mode="single"
selected={new Date(line.procedure_date)}
onSelect={(date) => updateProcedureDate(i, date)}
/>
</PopoverContent>
</Popover>
<Input
placeholder="Oral Cavity Area"
value={line.oralCavityArea}
onChange={(e) =>
updateServiceLine(i, "oralCavityArea", e.target.value)
} }
/> />
<Input <Input
placeholder="e.g. 14" placeholder="eg. 14"
value={line.toothNumber} value={line.toothNumber}
onChange={(e) => onChange={(e) =>
updateServiceLine(i, "toothNumber", e.target.value) updateServiceLine(i, "toothNumber", e.target.value)
} }
/> />
<Input <Input
placeholder="e.g. MOD" placeholder="eg. MOD"
value={line.surface} value={line.toothSurface}
onChange={(e) => onChange={(e) =>
updateServiceLine(i, "surface", e.target.value) updateServiceLine(i, "toothSurface", e.target.value)
}
/>
<Select
value={line.quad}
onValueChange={(value) =>
updateServiceLine(i, "quad", value)
}
>
<SelectTrigger>
<SelectValue placeholder="Select" />
</SelectTrigger>
<SelectContent>
<SelectItem value="UR">Upper Right</SelectItem>
<SelectItem value="UL">Upper Left</SelectItem>
<SelectItem value="LR">Lower Right</SelectItem>
<SelectItem value="LL">Lower Left</SelectItem>
</SelectContent>
</Select>
<Input
placeholder="e.g. 123456"
value={line.authNo}
onChange={(e) =>
updateServiceLine(i, "authNo", e.target.value)
} }
/> />
<Input <Input
@@ -366,17 +446,18 @@ useEffect(() => {
/> />
</div> </div>
))} ))}
<Button <Button
variant="outline" variant="outline"
onClick={() => onClick={() =>
setServiceLines([ setServiceLines([
...serviceLines, ...serviceLines,
{ {
procedureCode: "", procedure_code: "",
procedure_date: serviceDate,
oralCavityArea: "",
toothNumber: "", toothNumber: "",
surface: "", toothSurface: "",
quad: "",
authNo: "",
billedAmount: "", billedAmount: "",
}, },
]) ])
@@ -385,38 +466,54 @@ useEffect(() => {
+ Add Service Line + Add Service Line
</Button> </Button>
<div className="flex gap-2 mt-4"> <div className="flex gap-2 mt-10 mb-10">
<Button variant="outline">Child Prophy Codes</Button> <Button variant="outline">Child Prophy Codes</Button>
<Button variant="outline">Adult Prophy Codes</Button> <Button variant="outline">Adult Prophy Codes</Button>
<Button variant="outline">Customized Group Codes</Button> <Button variant="outline">Customized Group Codes</Button>
<Button variant="outline">Map Price</Button> <Button variant="outline">Map Price</Button>
</div> </div>
</div>
{/* File Upload Section */} {/* File Upload Section */}
<div className="mt-4 bg-gray-100 p-3 rounded-md"> <div className="mt-4 bg-gray-100 p-4 rounded-md space-y-4">
<p className="text-sm text-gray-500 mb-2"> <p className="text-sm text-gray-500">
Please note that file types with 4 or more character Only PDF files allowed. You can upload up to 10 files. File
extensions are not allowed, such as .DOCX, .PPTX, or .XLSX types with 4+ character extensions like .DOCX, .PPTX, or .XLSX
</p> are not allowed.
<div className="flex justify-between items-center"> </p>
<div className="flex items-center gap-2">
<Label>Select Field:</Label> <div className="flex flex-wrap gap-4 items-center justify-between">
<Select defaultValue="supportData"> <div className="flex items-center gap-2">
<SelectTrigger className="w-60"> <Label>Select Field:</Label>
<SelectValue /> <Select defaultValue="supportData">
</SelectTrigger> <SelectTrigger className="w-60">
<SelectContent> <SelectValue />
<SelectItem value="supportData"> </SelectTrigger>
Support Data for Claim <SelectContent>
</SelectItem> <SelectItem value="supportData">
<SelectItem value="xrays">X-Ray Images</SelectItem> Support Data for Claim
<SelectItem value="photos">Clinical Photos</SelectItem> </SelectItem>
</SelectContent> <SelectItem value="xrays">X-Ray Images</SelectItem>
</Select> <SelectItem value="photos">Clinical Photos</SelectItem>
</div> </SelectContent>
<Button>Upload Document</Button> </Select>
</div> </div>
</div> </div>
<MultipleFileUploadZone
onFileUpload={handleFileUpload}
isUploading={isUploading}
acceptedFileTypes="application/pdf"
maxFiles={10}
/>
{uploadedFiles.length > 0 && (
<ul className="text-sm text-gray-700 list-disc ml-6">
{uploadedFiles.map((file, index) => (
<li key={index}>{file.name}</li>
))}
</ul>
)}
</div> </div>
{/* Insurance Carriers */} {/* Insurance Carriers */}
@@ -425,7 +522,19 @@ useEffect(() => {
Insurance Carriers Insurance Carriers
</h3> </h3>
<div className="flex justify-between"> <div className="flex justify-between">
<Button className="w-32" variant="outline"> <Button
className="w-32"
variant="outline"
onClick={() => {
const appointmentData = {
patientId: patientId,
date: convertToISODate(serviceDate),
staffId:staff?.id,
};
// 1. Create or update appointment
onHandleAppointmentSubmit(appointmentData);}}
>
Delta MA Delta MA
</Button> </Button>
<Button className="w-32" variant="outline"> <Button className="w-32" variant="outline">

View File

@@ -0,0 +1,181 @@
import React, { useState, useRef, useCallback } from 'react';
import { Upload, File, X, FilePlus } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useToast } from '@/hooks/use-toast';
import { cn } from '@/lib/utils';
interface FileUploadZoneProps {
onFileUpload: (files: File[]) => void;
isUploading: boolean;
acceptedFileTypes?: string;
maxFiles?: number;
}
export function MultipleFileUploadZone({
onFileUpload,
isUploading,
acceptedFileTypes = "application/pdf",
maxFiles = 10,
}: FileUploadZoneProps) {
const { toast } = useToast();
const [isDragging, setIsDragging] = useState(false);
const [uploadedFiles, setUploadedFiles] = useState<File[]>([]);
const fileInputRef = useRef<HTMLInputElement>(null);
const handleDragEnter = useCallback((e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(true);
}, []);
const handleDragLeave = useCallback((e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
}, []);
const handleDragOver = useCallback((e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
e.stopPropagation();
if (!isDragging) {
setIsDragging(true);
}
}, [isDragging]);
const validateFile = (file: File) => {
if (!file.type.match(acceptedFileTypes)) {
toast({
title: "Invalid file type",
description: "Please upload a PDF file.",
variant: "destructive"
});
return false;
}
if (file.size > 5 * 1024 * 1024) {
toast({
title: "File too large",
description: "File size should be less than 5MB.",
variant: "destructive"
});
return false;
}
return true;
};
const handleFiles = (files: FileList | null) => {
if (!files) return;
const newFiles = Array.from(files).filter(validateFile);
const totalFiles = uploadedFiles.length + newFiles.length;
if (totalFiles > maxFiles) {
toast({
title: "Too Many Files",
description: `You can only upload up to ${maxFiles} files.`,
variant: "destructive",
});
return;
}
const updatedFiles = [...uploadedFiles, ...newFiles];
setUploadedFiles(updatedFiles);
onFileUpload(updatedFiles);
};
const handleDrop = useCallback((e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
handleFiles(e.dataTransfer.files);
}, [uploadedFiles]);
const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
handleFiles(e.target.files);
}, [uploadedFiles]);
const handleBrowseClick = () => {
if (fileInputRef.current) {
fileInputRef.current.click();
}
};
const handleRemoveFile = (index: number) => {
const newFiles = [...uploadedFiles];
newFiles.splice(index, 1);
setUploadedFiles(newFiles);
onFileUpload(newFiles);
};
return (
<div className="w-full">
<input
type="file"
ref={fileInputRef}
className="hidden"
onChange={handleFileSelect}
accept={acceptedFileTypes}
multiple
/>
<div
className={cn(
"border-2 border-dashed rounded-lg p-8 flex flex-col items-center justify-center text-center transition-colors",
isDragging ? "border-primary bg-primary/5" : "border-muted-foreground/25",
isUploading && "opacity-50 cursor-not-allowed"
)}
onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave}
onDragOver={handleDragOver}
onDrop={handleDrop}
onClick={!isUploading ? handleBrowseClick : undefined}
style={{ minHeight: "200px" }}
>
{isUploading ? (
<div className="flex flex-col items-center gap-4">
<div className="animate-spin">
<Upload className="h-10 w-10 text-primary" />
</div>
<p className="text-sm font-medium">Uploading files...</p>
</div>
) : uploadedFiles.length > 0 ? (
<div className="flex flex-col items-center gap-4 w-full">
<p className="font-medium text-primary">{uploadedFiles.length} file(s) uploaded</p>
<ul className="w-full text-left space-y-2">
{uploadedFiles.map((file, index) => (
<li key={index} className="flex justify-between items-center border-b pb-1">
<span className="text-sm">{file.name}</span>
<button
className="ml-2 p-1 text-muted-foreground hover:text-red-500"
onClick={(e) => {
e.stopPropagation();
handleRemoveFile(index);
}}
>
<X className="h-4 w-4" />
</button>
</li>
))}
</ul>
</div>
) : (
<div className="flex flex-col items-center gap-4">
<FilePlus className="h-12 w-12 text-primary/70" />
<div>
<p className="font-medium text-primary">Drag and drop PDF files here</p>
<p className="text-sm text-muted-foreground mt-1">Or click to browse files</p>
</div>
<Button type="button" variant="secondary" onClick={(e) => {
e.stopPropagation();
handleBrowseClick();
}}>
Browse files
</Button>
<p className="text-xs text-muted-foreground">Up to {maxFiles} PDF files, 5MB each</p>
</div>
)}
</div>
</div>
);
}

View File

@@ -75,11 +75,7 @@ export default function ClaimsPage() {
const { user } = useAuth(); const { user } = useAuth();
const [claimFormData, setClaimFormData] = useState<any>({ const [claimFormData, setClaimFormData] = useState<any>({
patientId: null, patientId: null,
carrier: "",
doctorName: "",
serviceDate: "", serviceDate: "",
clinicalNotes: "",
serviceLines: [],
}); });
// Fetch patients // Fetch patients
@@ -154,6 +150,99 @@ export default function ClaimsPage() {
}, },
}); });
// 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 handleAppointmentSubmit = (
appointmentData: InsertAppointment | UpdateAppointment
) => {
// Converts local date to exact UTC date with no offset issues
function parseLocalDate(dateInput: Date | string): Date {
if (dateInput instanceof Date) return dateInput;
const parts = dateInput.split("-");
if (parts.length !== 3) {
throw new Error(`Invalid date format: ${dateInput}`);
}
const year = Number(parts[0]);
const month = Number(parts[1]);
const day = Number(parts[2]);
if (Number.isNaN(year) || Number.isNaN(month) || Number.isNaN(day)) {
throw new Error(`Invalid date parts in date string: ${dateInput}`);
}
return new Date(year, month - 1, day); // month is 0-indexed
}
const rawDate = parseLocalDate(appointmentData.date);
const formattedDate = rawDate.toLocaleDateString("en-CA"); // YYYY-MM-DD format
// 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 &&
new Date(a.date).toLocaleDateString("en-CA") === formattedDate
);
if (existingAppointment && typeof existingAppointment.id === 'number') {
// Update appointment with only date
updateAppointmentMutation.mutate({
id: existingAppointment.id,
appointment: minimalData,
});
} else {
// Create new appointment with required fields + defaults
createAppointmentMutation.mutate({
...minimalData,
patientId: appointmentData.patientId,
userId:user?.id,
title: "Scheduled Appointment", // default title
type: "checkup", // default type
} as InsertAppointment);
}
};
const createClaimMutation = useMutation({ const createClaimMutation = useMutation({
mutationFn: async (claimData: any) => { mutationFn: async (claimData: any) => {
const res = await apiRequest("POST", "/api/claims/", claimData); const res = await apiRequest("POST", "/api/claims/", claimData);
@@ -186,7 +275,7 @@ export default function ClaimsPage() {
memberId: params.get("memberId") || "", memberId: params.get("memberId") || "",
dob: params.get("dob") || "", dob: params.get("dob") || "",
}; };
}, [location]); // <== re-run when route changes }, [location]);
const toggleMobileMenu = () => { const toggleMobileMenu = () => {
setIsMobileMenuOpen(!isMobileMenuOpen); setIsMobileMenuOpen(!isMobileMenuOpen);
@@ -209,11 +298,7 @@ export default function ClaimsPage() {
setSelectedAppointment(null); setSelectedAppointment(null);
setClaimFormData({ setClaimFormData({
patientId: null, patientId: null,
carrier: "",
doctorName: "",
serviceDate: "", serviceDate: "",
clinicalNotes: "",
serviceLines: [],
}); });
}; };
@@ -225,13 +310,9 @@ export default function ClaimsPage() {
setClaimFormData((prev: any) => ({ setClaimFormData((prev: any) => ({
...prev, ...prev,
patientId: patient.id, patientId: patient.id,
carrier: patient.insuranceProvider || "",
doctorName: user?.username || "",
serviceDate: lastAppointment serviceDate: lastAppointment
? new Date(lastAppointment.date).toISOString().slice(0, 10) ? new Date(lastAppointment.date).toISOString().slice(0, 10)
: new Date().toISOString().slice(0, 10), : new Date().toISOString().slice(0, 10),
clinicalNotes: "",
serviceLines: [],
})); }));
}; };
@@ -279,16 +360,15 @@ export default function ClaimsPage() {
createClaimMutation.mutate(claimData); createClaimMutation.mutate(claimData);
} }
const getDisplayProvider = (provider: string) => { const getDisplayProvider = (provider: string) => {
const insuranceMap: Record<string, string> = { const insuranceMap: Record<string, string> = {
delta: "Delta Dental", delta: "Delta Dental",
metlife: "MetLife", metlife: "MetLife",
cigna: "Cigna", cigna: "Cigna",
aetna: "Aetna", aetna: "Aetna",
};
return insuranceMap[provider?.toLowerCase()] || provider;
}; };
return insuranceMap[provider?.toLowerCase()] || provider;
};
// Get unique patients with appointments // Get unique patients with appointments
const patientsWithAppointments = appointments.reduce( const patientsWithAppointments = appointments.reduce(
@@ -391,7 +471,10 @@ export default function ClaimsPage() {
<div> <div>
<h3 className="font-medium">{item.patientName}</h3> <h3 className="font-medium">{item.patientName}</h3>
<div className="text-sm text-gray-500"> <div className="text-sm text-gray-500">
<span>Insurance: {getDisplayProvider(item.insuranceProvider)}</span> <span>
Insurance:{" "}
{getDisplayProvider(item.insuranceProvider)}
</span>
<span className="mx-2"></span> <span className="mx-2"></span>
<span>ID: {item.insuranceId}</span> <span>ID: {item.insuranceId}</span>
@@ -435,6 +518,7 @@ export default function ClaimsPage() {
onClose={closeClaim} onClose={closeClaim}
extractedData={claimFormData} extractedData={claimFormData}
onSubmit={handleClaimSubmit} onSubmit={handleClaimSubmit}
onHandleAppointmentSubmit={handleAppointmentSubmit}
/> />
)} )}
</div> </div>

View File

@@ -87,11 +87,6 @@ export default function PatientsPage() {
const [uploadedFile, setUploadedFile] = useState<File | null>(null); const [uploadedFile, setUploadedFile] = useState<File | null>(null);
const [isUploading, setIsUploading] = useState(false); const [isUploading, setIsUploading] = useState(false);
const [isExtracting, setIsExtracting] = useState(false); const [isExtracting, setIsExtracting] = useState(false);
const [formData, setFormData] = useState({
PatientName: "",
PatientMemberId: "",
PatientDob: "",
});
const { mutate: extractPdf } = useExtractPdfData(); const { mutate: extractPdf } = useExtractPdfData();
const [location, navigate] = useLocation(); const [location, navigate] = useLocation();

View File

@@ -81,33 +81,37 @@ model Staff {
phone String? phone String?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
appointments Appointment[] appointments Appointment[]
claims Claim[] @relation("ClaimStaff")
} }
model Claim { model Claim {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
patientId Int patientId Int
appointmentId Int appointmentId Int
clinicalNotes String userId Int
serviceDate DateTime staffId Int
doctorName String remarks String
carrier String // e.g., "Delta MA" serviceDate DateTime
createdAt DateTime @default(now()) insuranceProvider String // e.g., "Delta MA"
updatedAt DateTime @updatedAt createdAt DateTime @default(now())
patient Patient @relation(fields: [patientId], references: [id]) updatedAt DateTime @updatedAt
appointment Appointment @relation(fields: [appointmentId], references: [id]) status String @default("pending") // "pending", "completed", "cancelled", "no-show"
serviceLines ServiceLine[]
User User? @relation(fields: [userId], references: [id]) patient Patient @relation(fields: [patientId], references: [id])
userId Int? appointment Appointment @relation(fields: [appointmentId], references: [id])
user User? @relation(fields: [userId], references: [id])
staff Staff? @relation("ClaimStaff", fields: [staffId], references: [id])
serviceLines ServiceLine[]
} }
model ServiceLine { model ServiceLine {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
claimId Int claimId Int
procedureCode String procedureCode String
toothNumber String? procedureDate DateTime @db.Date
surface String? oralCavityArea String?
quadrant String? toothNumber String?
authNumber String? toothSurface String?
billedAmount Float billedAmount Float
claim Claim @relation(fields: [claimId], references: [id]) claim Claim @relation(fields: [claimId], references: [id])
} }