feat: MassHealth eligibility on new portal with persistent session and Gmail OTP auto-read
- New MH eligibility worker for providers.masshealth-dental.org (same DentaQuest portal as Tufts SCO): persistent Chrome profile, OTP via app popup, member details PDF, address, service history, plan name and remaining benefit - Reads the OTP from the office Gmail over IMAP (App Password) and types it in; falls back to the manual OTP popup - Insurance credentials: OTP Email / Phone and OTP Email Password fields - New patient status ACTIVE_PLAN_NOT_ACCEPTED (coverage active, plan not accepted) - Removes the old MH eligibility, MH history and CMSP remaining workers/processors; batch appointment check and AI conversation use the new MH processor Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -51,6 +51,8 @@ function getVisuals(status: PatientStatus): { label: string; bg: string } {
|
||||
return { label: "Inactive", bg: "#DC2626" };
|
||||
case "PLAN_NOT_ACCEPTED":
|
||||
return { label: "Plan Not Accepted", bg: "#F59E0B" }; // amber
|
||||
case "ACTIVE_PLAN_NOT_ACCEPTED":
|
||||
return { label: "Active / Plan Not Accepted", bg: "#0D9488" }; // teal
|
||||
default:
|
||||
return { label: "Unknown", bg: "#6B7280" };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { CheckCircle, LoaderCircleIcon, X } from "lucide-react";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { apiRequest, queryClient } from "@/lib/queryClient";
|
||||
import { useAppDispatch } from "@/redux/hooks";
|
||||
import { setTaskStatus } from "@/redux/slices/seleniumTaskSlice";
|
||||
import { formatLocalDate } from "@/utils/dateUtils";
|
||||
import { socket } from "@/lib/socket";
|
||||
import { QK_PATIENTS_BASE } from "@/components/patients/patient-table";
|
||||
|
||||
// ─── OTP Modal ────────────────────────────────────────────────────────────────
|
||||
|
||||
interface MHOtpModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSubmit: (otp: string) => Promise<void> | void;
|
||||
isSubmitting: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
function MHOtpModal({ open, onClose, onSubmit, isSubmitting, message }: MHOtpModalProps) {
|
||||
const [otp, setOtp] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) setOtp("");
|
||||
}, [open]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!otp.trim()) return;
|
||||
await onSubmit(otp.trim());
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
|
||||
<div className="bg-white dark:bg-slate-900 rounded-xl shadow-lg w-full max-w-md p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold">Enter OTP</h2>
|
||||
<button type="button" onClick={onClose} className="text-slate-500 hover:text-slate-800">
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-sm text-slate-500 mb-4">
|
||||
{message ||
|
||||
"We need the verification code sent to your phone or email to complete this check."}
|
||||
</p>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="mh-otp">Verification Code</Label>
|
||||
<Input
|
||||
id="mh-otp"
|
||||
placeholder="Enter verification code"
|
||||
value={otp}
|
||||
onChange={(e) => setOtp(e.target.value)}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-3">
|
||||
<Button type="button" variant="outline" onClick={onClose} disabled={isSubmitting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isSubmitting || !otp.trim()}>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<LoaderCircleIcon className="w-4 h-4 mr-2 animate-spin" />
|
||||
Submitting...
|
||||
</>
|
||||
) : (
|
||||
"Submit Code"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main component ───────────────────────────────────────────────────────────
|
||||
|
||||
interface MHEligibilityButtonProps {
|
||||
memberId: string;
|
||||
dateOfBirth: Date | null;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
isFormIncomplete: boolean;
|
||||
autoTrigger?: boolean;
|
||||
onAutoTriggered?: () => void;
|
||||
onPdfReady: (pdfId: number | string, fallbackFilename: string | null) => void;
|
||||
/** Called with the job result (patientId, pdfFileId, …) when the check succeeds. */
|
||||
onComplete?: (result: any) => void;
|
||||
}
|
||||
|
||||
export function MHEligibilityButton({
|
||||
memberId,
|
||||
dateOfBirth,
|
||||
firstName,
|
||||
lastName,
|
||||
isFormIncomplete,
|
||||
autoTrigger,
|
||||
onAutoTriggered,
|
||||
onPdfReady,
|
||||
onComplete,
|
||||
}: MHEligibilityButtonProps) {
|
||||
const { toast } = useToast();
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const sessionIdRef = useRef<string | null>(null);
|
||||
const autoTriggeredRef = useRef(false);
|
||||
|
||||
const [otpModalOpen, setOtpModalOpen] = useState(false);
|
||||
const [otpMessage, setOtpMessage] = useState("");
|
||||
const [isStarting, setIsStarting] = useState(false);
|
||||
const [isSubmittingOtp, setIsSubmittingOtp] = useState(false);
|
||||
|
||||
const handleStart = async () => {
|
||||
if (!memberId || !dateOfBirth) {
|
||||
toast({
|
||||
title: "Missing fields",
|
||||
description: "Member ID and Date of Birth are required.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const formattedDob = formatLocalDate(dateOfBirth);
|
||||
const payload = {
|
||||
memberId,
|
||||
dateOfBirth: formattedDob,
|
||||
firstName,
|
||||
lastName,
|
||||
insuranceSiteKey: "MH",
|
||||
};
|
||||
|
||||
setIsStarting(true);
|
||||
|
||||
try {
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
key: "eligibilityCheck",
|
||||
status: "pending",
|
||||
message: "Starting MassHealth eligibility check…",
|
||||
})
|
||||
);
|
||||
|
||||
const response = await apiRequest(
|
||||
"POST",
|
||||
"/api/insurance-status-mh/mh-eligibility",
|
||||
{ data: JSON.stringify(payload), socketId: socket.id }
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
if (!response.ok || result.error) {
|
||||
throw new Error(result.error || `Server error (${response.status})`);
|
||||
}
|
||||
|
||||
const jobId: string = result.jobId;
|
||||
if (!jobId) throw new Error("No jobId returned from server");
|
||||
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
key: "eligibilityCheck",
|
||||
status: "pending",
|
||||
message: "MassHealth job queued. Waiting for browser session…",
|
||||
})
|
||||
);
|
||||
|
||||
const onSessionStarted = (data: any) => {
|
||||
if (String(data?.jobId) !== String(jobId)) return;
|
||||
sessionIdRef.current = data.session_id ?? null;
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
key: "eligibilityCheck",
|
||||
status: "pending",
|
||||
message: "Browser session started. Waiting for verification code or result…",
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
const onOtpRequired = (data: any) => {
|
||||
if (String(data?.jobId) !== String(jobId)) return;
|
||||
if (data.session_id) sessionIdRef.current = data.session_id;
|
||||
setOtpMessage(typeof data?.message === "string" ? data.message : "");
|
||||
setOtpModalOpen(true);
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
key: "eligibilityCheck",
|
||||
status: "pending",
|
||||
message: data?.message || "Verification code required. Please enter the code.",
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
const onOtpSubmitted = (data: any) => {
|
||||
if (data?.session_id && data.session_id !== sessionIdRef.current) return;
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
key: "eligibilityCheck",
|
||||
status: "pending",
|
||||
message: "Code submitted. Finishing eligibility check…",
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
socket.on("selenium:mh_session_started", onSessionStarted);
|
||||
socket.on("selenium:otp_required", onOtpRequired);
|
||||
socket.on("selenium:otp_submitted", onOtpSubmitted);
|
||||
|
||||
function cleanup() {
|
||||
clearTimeout(safetyTimer);
|
||||
socket.off("selenium:mh_session_started", onSessionStarted);
|
||||
socket.off("selenium:otp_required", onOtpRequired);
|
||||
socket.off("selenium:otp_submitted", onOtpSubmitted);
|
||||
socket.off("job:update", onJobUpdate);
|
||||
}
|
||||
|
||||
const onJobUpdate = (data: any) => {
|
||||
if (String(data?.jobId) !== String(jobId)) return;
|
||||
|
||||
if (data.status === "active") {
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
key: "eligibilityCheck",
|
||||
status: "pending",
|
||||
message: data.message ?? "Selenium browser starting…",
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
cleanup();
|
||||
|
||||
if (data.status === "completed") {
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
key: "eligibilityCheck",
|
||||
status: "success",
|
||||
message: "MassHealth eligibility updated and PDF attached to patient documents.",
|
||||
})
|
||||
);
|
||||
toast({
|
||||
title: "MassHealth eligibility complete",
|
||||
description: "Patient status was updated and the eligibility PDF was saved.",
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
|
||||
onComplete?.(data.result ?? {});
|
||||
const pdfId = data.result?.pdfFileId;
|
||||
if (pdfId) {
|
||||
onPdfReady(pdfId, data.result?.pdfFilename ?? `mh_eligibility_${memberId}.pdf`);
|
||||
}
|
||||
} else if (data.status === "failed") {
|
||||
const msg = data.error ?? "MassHealth eligibility job failed.";
|
||||
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "error", message: msg }));
|
||||
toast({ title: "MassHealth selenium error", description: msg, variant: "destructive" });
|
||||
}
|
||||
|
||||
setIsStarting(false);
|
||||
setOtpModalOpen(false);
|
||||
};
|
||||
|
||||
socket.on("job:update", onJobUpdate);
|
||||
|
||||
const safetyTimer = setTimeout(() => {
|
||||
cleanup();
|
||||
setIsStarting(false);
|
||||
setOtpModalOpen(false);
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
key: "eligibilityCheck",
|
||||
status: "error",
|
||||
message: "MassHealth job timed out waiting for completion.",
|
||||
})
|
||||
);
|
||||
}, 6 * 60 * 1000);
|
||||
|
||||
} catch (err: any) {
|
||||
console.error("MHEligibilityButton error:", err);
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
key: "eligibilityCheck",
|
||||
status: "error",
|
||||
message: err?.message || "Failed to start MassHealth eligibility",
|
||||
})
|
||||
);
|
||||
toast({
|
||||
title: "MassHealth selenium error",
|
||||
description: err?.message || "Failed to start MassHealth eligibility",
|
||||
variant: "destructive",
|
||||
});
|
||||
setIsStarting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmitOtp = async (otp: string) => {
|
||||
const sessionId = sessionIdRef.current;
|
||||
if (!sessionId) {
|
||||
toast({
|
||||
title: "Session not ready",
|
||||
description: "Cannot submit code — session ID is not available yet.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsSubmittingOtp(true);
|
||||
const resp = await apiRequest("POST", "/api/insurance-status-mh/selenium/submit-otp", {
|
||||
session_id: sessionId,
|
||||
otp,
|
||||
socketId: socket.id,
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (!resp.ok || data.error) {
|
||||
throw new Error(data.error || "Failed to submit code");
|
||||
}
|
||||
setOtpModalOpen(false);
|
||||
} catch (err: any) {
|
||||
console.error("handleSubmitOtp error:", err);
|
||||
toast({
|
||||
title: "Failed to submit code",
|
||||
description: err?.message || "Error forwarding code to selenium agent",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSubmittingOtp(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!autoTrigger) { autoTriggeredRef.current = false; return; }
|
||||
if (autoTriggeredRef.current || isFormIncomplete) return;
|
||||
autoTriggeredRef.current = true;
|
||||
onAutoTriggered?.();
|
||||
handleStart();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [autoTrigger, isFormIncomplete]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
className="w-full"
|
||||
variant="default"
|
||||
disabled={isFormIncomplete || isStarting}
|
||||
onClick={handleStart}
|
||||
>
|
||||
{isStarting ? (
|
||||
<>
|
||||
<LoaderCircleIcon className="h-4 w-4 mr-2 animate-spin" />
|
||||
Processing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle className="h-4 w-4 mr-2" />
|
||||
MH
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<MHOtpModal
|
||||
open={otpModalOpen}
|
||||
onClose={() => setOtpModalOpen(false)}
|
||||
onSubmit={handleSubmitOtp}
|
||||
isSubmitting={isSubmittingOtp}
|
||||
message={otpMessage}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -454,6 +454,7 @@ export const PatientForm = forwardRef<PatientFormRef, PatientFormProps>(
|
||||
) as PatientStatus[]; // ['ACTIVE','INACTIVE','UNKNOWN']
|
||||
const toLabel = (v: PatientStatus) => {
|
||||
if (v === "PLAN_NOT_ACCEPTED") return "Plan Not Accepted";
|
||||
if (v === "ACTIVE_PLAN_NOT_ACCEPTED") return "Active / Plan Not Accepted";
|
||||
return v[0] + v.slice(1).toLowerCase();
|
||||
};
|
||||
|
||||
|
||||
@@ -1160,6 +1160,12 @@ export function PatientTable({
|
||||
Plan Not Accepted
|
||||
</span>
|
||||
)}
|
||||
|
||||
{patient.status === "ACTIVE_PLAN_NOT_ACCEPTED" && (
|
||||
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-teal-100 text-teal-800">
|
||||
Active / Plan Not Accepted
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{patient.updatedAt && (
|
||||
<div className="text-xs text-gray-500 mt-1">
|
||||
@@ -1312,13 +1318,17 @@ export function PatientTable({
|
||||
? "text-red-600"
|
||||
: currentPatient.status === "PLAN_NOT_ACCEPTED"
|
||||
? "text-amber-600"
|
||||
: "text-gray-600",
|
||||
: currentPatient.status === "ACTIVE_PLAN_NOT_ACCEPTED"
|
||||
? "text-teal-600"
|
||||
: "text-gray-600",
|
||||
"font-medium"
|
||||
)}
|
||||
>
|
||||
{currentPatient.status === "PLAN_NOT_ACCEPTED"
|
||||
? "Plan Not Accepted"
|
||||
: currentPatient.status
|
||||
: currentPatient.status === "ACTIVE_PLAN_NOT_ACCEPTED"
|
||||
? "Active / Plan Not Accepted"
|
||||
: currentPatient.status
|
||||
? currentPatient.status.charAt(0).toUpperCase() +
|
||||
currentPatient.status.slice(1).toLowerCase()
|
||||
: "Unknown"}
|
||||
|
||||
@@ -12,6 +12,8 @@ type CredentialFormProps = {
|
||||
siteKey: string;
|
||||
username: string;
|
||||
password: string;
|
||||
otpContact?: string | null;
|
||||
otpContactPassword?: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -34,7 +36,10 @@ export function CredentialForm({ onClose, userId, defaultValues }: CredentialFor
|
||||
const [siteKey, setSiteKey] = useState(defaultValues?.siteKey || "");
|
||||
const [username, setUsername] = useState(defaultValues?.username || "");
|
||||
const [password, setPassword] = useState(defaultValues?.password || "");
|
||||
const [otpContact, setOtpContact] = useState(defaultValues?.otpContact || "");
|
||||
const [otpContactPassword, setOtpContactPassword] = useState(defaultValues?.otpContactPassword || "");
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [showOtpContactPassword, setShowOtpContactPassword] = useState(false);
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
@@ -45,6 +50,8 @@ export function CredentialForm({ onClose, userId, defaultValues }: CredentialFor
|
||||
siteKey: siteKey.trim(),
|
||||
username: username.trim(),
|
||||
password: password.trim(),
|
||||
otpContact: otpContact.trim() || null,
|
||||
otpContactPassword: otpContactPassword.trim() || null,
|
||||
userId,
|
||||
};
|
||||
|
||||
@@ -83,6 +90,8 @@ export function CredentialForm({ onClose, userId, defaultValues }: CredentialFor
|
||||
setSiteKey(defaultValues?.siteKey || "");
|
||||
setUsername(defaultValues?.username || "");
|
||||
setPassword(defaultValues?.password || "");
|
||||
setOtpContact(defaultValues?.otpContact || "");
|
||||
setOtpContactPassword(defaultValues?.otpContactPassword || "");
|
||||
}, [defaultValues]);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
@@ -91,7 +100,7 @@ export function CredentialForm({ onClose, userId, defaultValues }: CredentialFor
|
||||
if (!siteKey || !username || !password) {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "All fields are required.",
|
||||
description: "Insurance, username and password are required.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
@@ -150,6 +159,41 @@ export function CredentialForm({ onClose, userId, defaultValues }: CredentialFor
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium">
|
||||
OTP Email / Phone <span className="text-gray-400 font-normal">(optional)</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={otpContact}
|
||||
onChange={(e) => setOtpContact(e.target.value)}
|
||||
placeholder="Email or phone number that receives the OTP code"
|
||||
className="mt-1 p-2 border rounded w-full"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium">
|
||||
OTP Email Password <span className="text-gray-400 font-normal">(optional)</span>
|
||||
</label>
|
||||
<div className="relative mt-1">
|
||||
<input
|
||||
type={showOtpContactPassword ? "text" : "password"}
|
||||
value={otpContactPassword}
|
||||
onChange={(e) => setOtpContactPassword(e.target.value)}
|
||||
placeholder="Password for the email account above"
|
||||
autoComplete="new-password"
|
||||
className="p-2 border rounded w-full pr-10"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowOtpContactPassword((prev) => !prev)}
|
||||
className="absolute inset-y-0 right-2 flex items-center text-gray-500 hover:text-gray-700"
|
||||
tabIndex={-1}
|
||||
>
|
||||
{showOtpContactPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -12,6 +12,8 @@ type Credential = {
|
||||
siteKey: string;
|
||||
username: string;
|
||||
password: string;
|
||||
otpContact?: string | null;
|
||||
otpContactPassword?: string | null;
|
||||
};
|
||||
|
||||
export function CredentialTable() {
|
||||
@@ -101,25 +103,31 @@ export function CredentialTable() {
|
||||
<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Password
|
||||
</th>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
OTP Email / Phone
|
||||
</th>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
OTP Email Password
|
||||
</th>
|
||||
<th className="px-4 py-2" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{isLoading ? (
|
||||
<tr>
|
||||
<td colSpan={4} className="text-center py-4">
|
||||
<td colSpan={6} className="text-center py-4">
|
||||
Loading credentials...
|
||||
</td>
|
||||
</tr>
|
||||
) : error ? (
|
||||
<tr>
|
||||
<td colSpan={4} className="text-center py-4 text-red-600">
|
||||
<td colSpan={6} className="text-center py-4 text-red-600">
|
||||
Error loading credentials
|
||||
</td>
|
||||
</tr>
|
||||
) : currentCredentials.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={4} className="text-center py-4">
|
||||
<td colSpan={6} className="text-center py-4">
|
||||
No credentials found.
|
||||
</td>
|
||||
</tr>
|
||||
@@ -129,6 +137,8 @@ export function CredentialTable() {
|
||||
<td className="px-4 py-2">{cred.siteKey}</td>
|
||||
<td className="px-4 py-2">{cred.username}</td>
|
||||
<td className="px-4 py-2">••••••••</td>
|
||||
<td className="px-4 py-2">{cred.otpContact || <span className="text-gray-400">—</span>}</td>
|
||||
<td className="px-4 py-2">{cred.otpContactPassword ? "••••••••" : <span className="text-gray-400">—</span>}</td>
|
||||
<td className="px-4 py-2 text-right">
|
||||
<Button
|
||||
variant="ghost"
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { CheckCircle, LoaderCircleIcon, Bot, PhoneCall, ChevronDown, ChevronUp } from "lucide-react";
|
||||
import { CheckCircle, Bot, PhoneCall, ChevronDown, ChevronUp } from "lucide-react";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { PatientTable } from "@/components/patients/patient-table";
|
||||
@@ -29,13 +29,12 @@ import {
|
||||
clearTaskStatus,
|
||||
} from "@/redux/slices/seleniumTaskSlice";
|
||||
import { SeleniumTaskBanner } from "@/components/ui/selenium-task-banner";
|
||||
import { formatLocalDate, parseLocalDate } from "@/utils/dateUtils";
|
||||
import { socket } from "@/lib/socket";
|
||||
import { parseLocalDate } from "@/utils/dateUtils";
|
||||
import { InsertPatient, Patient } from "@repo/db/types";
|
||||
import { DateInput } from "@/components/ui/dateInput";
|
||||
import { QK_PATIENTS_BASE } from "@/components/patients/patient-table";
|
||||
import { PdfPreviewModal } from "@/components/insurance-status/pdf-preview-modal";
|
||||
import { DualPdfPreviewModal } from "@/components/insurance-status/dual-pdf-preview-modal";
|
||||
import { MHEligibilityButton } from "@/components/insurance-status/mh-button-modal";
|
||||
import { useLocation } from "wouter";
|
||||
import { DdmaEligibilityButton } from "@/components/insurance-status/ddma-buton-modal";
|
||||
import { DdwaEligibilityButton } from "@/components/insurance-status/ddwa-button-modal";
|
||||
@@ -50,56 +49,6 @@ import { CCAEligibilityButton } from "@/components/insurance-status/cca-button-m
|
||||
import { BcbsMaEligibilityButton } from "@/components/insurance-status/bcbs-ma-button-modal";
|
||||
import { useLicense } from "@/hooks/use-license";
|
||||
|
||||
/**
|
||||
* Waits for a Selenium job to complete by racing socket.io events against
|
||||
* HTTP polling every 3 seconds. This ensures the result is received even
|
||||
* when the socket reconnects through Cloudflare (changing socket.id).
|
||||
*/
|
||||
function waitForSeleniumJob(
|
||||
jobId: string,
|
||||
onActive?: (message: string) => void,
|
||||
): Promise<any> {
|
||||
return new Promise<any>((resolve, reject) => {
|
||||
let settled = false;
|
||||
|
||||
const settle = (fn: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearInterval(pollInterval);
|
||||
socket.off("job:update", socketHandler);
|
||||
fn();
|
||||
};
|
||||
|
||||
const socketHandler = (payload: any) => {
|
||||
if (String(payload.jobId) !== String(jobId)) return;
|
||||
if (payload.status === "active") {
|
||||
onActive?.(payload.message ?? "Selenium running...");
|
||||
} else if (payload.status === "completed") {
|
||||
settle(() => resolve(payload.result ?? {}));
|
||||
} else if (payload.status === "failed") {
|
||||
settle(() => reject(new Error(payload.error ?? "Selenium job failed")));
|
||||
}
|
||||
};
|
||||
socket.on("job:update", socketHandler);
|
||||
|
||||
const pollInterval = setInterval(async () => {
|
||||
if (settled) return;
|
||||
try {
|
||||
const res = await apiRequest("GET", `/api/insurance-status/job-status/${jobId}`);
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
if (data.status === "completed") {
|
||||
settle(() => resolve(data.result ?? {}));
|
||||
} else if (data.status === "failed") {
|
||||
settle(() => reject(new Error(data.error ?? "Selenium job failed")));
|
||||
}
|
||||
} catch {
|
||||
// ignore transient poll errors
|
||||
}
|
||||
}, 3000);
|
||||
});
|
||||
}
|
||||
|
||||
const PENDING_COPY_AGENT_SCREENSHOTS_KEY = "copy_agent_pending_screenshots";
|
||||
|
||||
export default function InsuranceStatusPage() {
|
||||
@@ -125,15 +74,6 @@ export default function InsuranceStatusPage() {
|
||||
const isDeltaIndivFormIncomplete = !dateOfBirth || !lastName;
|
||||
// Altus searches by Member ID, or by Subscriber Last Name when the ID is unknown; First Name + DOB always required.
|
||||
const isAltusFormIncomplete = !dateOfBirth || !firstName?.trim() || (!memberId && !lastName?.trim());
|
||||
const [isCheckingEligibilityStatus, setIsCheckingEligibilityStatus] =
|
||||
useState(false);
|
||||
const [isCheckingEligibilityAppointment, setIsCheckingEligibilityAppointment] =
|
||||
useState(false);
|
||||
const [isCheckingEligibilityClaimsPreAuth, setIsCheckingEligibilityClaimsPreAuth] =
|
||||
useState(false);
|
||||
const [isCheckingEligibilityHistory, setIsCheckingEligibilityHistory] =
|
||||
useState(false);
|
||||
const [isCheckingCMSP, setIsCheckingCMSP] = useState(false);
|
||||
const [showPdfViewerOnComplete, setShowPdfViewerOnComplete] = useState(false);
|
||||
|
||||
// AI Call Insurance section
|
||||
@@ -162,26 +102,6 @@ export default function InsuranceStatusPage() {
|
||||
string | null
|
||||
>(null);
|
||||
|
||||
// Dual PDF modal state (used by MH Eligibility & History)
|
||||
const [dualPreviewOpen, setDualPreviewOpen] = useState(false);
|
||||
const [dualEligibilityPdfId, setDualEligibilityPdfId] = useState<number | string | null>(null);
|
||||
const [dualEligibilityFilename, setDualEligibilityFilename] = useState<string | null>(null);
|
||||
const [dualMemberDetailsPdfId, setDualMemberDetailsPdfId] = useState<number | string | null>(null);
|
||||
const [dualMemberDetailsFilename, setDualMemberDetailsFilename] = useState<string | null>(null);
|
||||
const [dualHistoryPdfId, setDualHistoryPdfId] = useState<number | string | null>(null);
|
||||
const [dualHistoryFilename, setDualHistoryFilename] = useState<string | null>(null);
|
||||
|
||||
// CMSP PDF modal state (used by CMSP Eligibility & History & Remaining)
|
||||
const [cmspPreviewOpen, setCmspPreviewOpen] = useState(false);
|
||||
const [cmspEligibilityPdfId, setCmspEligibilityPdfId] = useState<number | string | null>(null);
|
||||
const [cmspEligibilityFilename, setCmspEligibilityFilename] = useState<string | null>(null);
|
||||
const [cmspMemberDetailsPdfId, setCmspMemberDetailsPdfId] = useState<number | string | null>(null);
|
||||
const [cmspMemberDetailsFilename, setCmspMemberDetailsFilename] = useState<string | null>(null);
|
||||
const [cmspHistoryPdfId, setCmspHistoryPdfId] = useState<number | string | null>(null);
|
||||
const [cmspHistoryFilename, setCmspHistoryFilename] = useState<string | null>(null);
|
||||
const [cmspAccumulatorPdfId, setCmspAccumulatorPdfId] = useState<number | string | null>(null);
|
||||
const [cmspAccumulatorFilename, setCmspAccumulatorFilename] = useState<string | null>(null);
|
||||
|
||||
const pendingAutoCheck = useRef<"mh" | "mh-history" | "cmsp" | "ddma" | "ddwa" | "delta-ins" | "delta-indiv" | "united-sco" | "united-ucard" | "tufts-sco" | "cca" | "bcbs-ma" | "metlife" | "altus" | null>(null);
|
||||
const [triggerTarget, setTriggerTarget] = useState<string | null>(null);
|
||||
const pendingScrollTo = useRef<string | null>(null);
|
||||
@@ -331,12 +251,6 @@ export default function InsuranceStatusPage() {
|
||||
},
|
||||
});
|
||||
|
||||
const isUnder14 = (dob: Date): boolean => {
|
||||
const cutoff = new Date(dob);
|
||||
cutoff.setFullYear(cutoff.getFullYear() + 14);
|
||||
return new Date() < cutoff;
|
||||
};
|
||||
|
||||
// If the Copy Agent page couldn't read a Member ID/DOB from a screenshot, it stashes the
|
||||
// screenshot(s) here and lets the user complete the check manually. Once that check resolves
|
||||
// to a real patient, attach the originally-captured screenshots to that patient's Attachments.
|
||||
@@ -380,52 +294,6 @@ export default function InsuranceStatusPage() {
|
||||
}
|
||||
};
|
||||
|
||||
// Shared: run MH eligibility selenium job, return jobResult or throw
|
||||
const runMHEligibilitySelenium = async (): Promise<any> => {
|
||||
const formattedDob = dateOfBirth ? formatLocalDate(dateOfBirth) : "";
|
||||
|
||||
const data = {
|
||||
memberId,
|
||||
dateOfBirth: formattedDob,
|
||||
insuranceSiteKey: "MH",
|
||||
firstName: firstName || undefined,
|
||||
lastName: lastName || undefined,
|
||||
};
|
||||
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
key: "eligibilityCheck",
|
||||
status: "pending",
|
||||
message: "Sending Data to Selenium...",
|
||||
}),
|
||||
);
|
||||
|
||||
const response = await apiRequest(
|
||||
"POST",
|
||||
"/api/insurance-status/eligibility-check",
|
||||
{ data: data, socketId: socket.id },
|
||||
);
|
||||
const enqueueResult = await response.json();
|
||||
if (enqueueResult.error) throw new Error(enqueueResult.error);
|
||||
|
||||
const jobId = enqueueResult.jobId;
|
||||
if (!jobId) throw new Error("No jobId returned from server");
|
||||
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
key: "eligibilityCheck",
|
||||
status: "pending",
|
||||
message: "Selenium browser starting...",
|
||||
}),
|
||||
);
|
||||
|
||||
const jobResult = await waitForSeleniumJob(jobId, (msg) =>
|
||||
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: msg }))
|
||||
);
|
||||
await flushPendingCopyAgentScreenshots(jobResult);
|
||||
return jobResult;
|
||||
};
|
||||
|
||||
const handleAddPatient = async () => {
|
||||
const newPatient: InsertPatient = {
|
||||
firstName,
|
||||
@@ -439,333 +307,6 @@ export default function InsuranceStatusPage() {
|
||||
await addPatientMutation.mutateAsync(newPatient);
|
||||
};
|
||||
|
||||
// MH Eligibility — check eligibility, save to DB, open PDF preview
|
||||
const handleMHEligibilityButton = async () => {
|
||||
if (!memberId || !dateOfBirth) {
|
||||
toast({
|
||||
title: "Missing Fields",
|
||||
description: "Please fill in all the required fields: Member ID, Date of Birth.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (isUnder14(dateOfBirth)) {
|
||||
toast({ title: "CMSP Patient", description: "Patient is under 14 — running CMSP Eligibility & History & Remaining instead.", variant: "default" });
|
||||
return handleCMSPButton();
|
||||
}
|
||||
|
||||
setIsCheckingEligibilityStatus(true);
|
||||
try {
|
||||
const jobResult = await runMHEligibilitySelenium();
|
||||
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
key: "eligibilityCheck",
|
||||
status: "success",
|
||||
message: "Patient status is updated, and its eligibility pdf is uploaded at Document Page.",
|
||||
}),
|
||||
);
|
||||
toast({
|
||||
title: "Selenium service done.",
|
||||
description: "Your Patient Eligibility is fetched and updated, Kindly search through the patient.",
|
||||
variant: "default",
|
||||
});
|
||||
|
||||
setSelectedPatient(null);
|
||||
await queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
|
||||
void tryAppointmentFromChatbot();
|
||||
|
||||
if (jobResult.pdfFileId) {
|
||||
setPreviewPdfId(jobResult.pdfFileId);
|
||||
setPreviewFallbackFilename(jobResult.pdfFilename ?? `eligibility_${memberId}.pdf`);
|
||||
setPreviewOpen(true);
|
||||
}
|
||||
processNextInQueue();
|
||||
} catch (error: any) {
|
||||
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "error", message: error.message || "Selenium submission failed" }));
|
||||
toast({ title: "Selenium service error", description: error.message || "An error occurred.", variant: "destructive" });
|
||||
} finally {
|
||||
setIsCheckingEligibilityStatus(false);
|
||||
}
|
||||
};
|
||||
|
||||
// MH Eligibility & Appointment — check eligibility, save to DB, create appointment for today
|
||||
const handleMHEligibilityAppointmentButton = async () => {
|
||||
if (!memberId || !dateOfBirth) {
|
||||
toast({
|
||||
title: "Missing Fields",
|
||||
description: "Please fill in all the required fields: Member ID, Date of Birth.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCheckingEligibilityAppointment(true);
|
||||
try {
|
||||
const jobResult = await runMHEligibilitySelenium();
|
||||
|
||||
const isInactive = jobResult?.patientUpdateStatus?.includes("INACTIVE");
|
||||
|
||||
if (isInactive) {
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
key: "eligibilityCheck",
|
||||
status: "error",
|
||||
message: "Insurance is inactive. No appointment created.",
|
||||
}),
|
||||
);
|
||||
toast({
|
||||
title: "Insurance Inactive",
|
||||
description: "Patient insurance is inactive. No appointment was created.",
|
||||
variant: "destructive",
|
||||
});
|
||||
await queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
|
||||
return;
|
||||
}
|
||||
|
||||
await queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
|
||||
|
||||
// Look up the patient (created/updated by the Selenium worker) then create today's appointment
|
||||
let apptTime: string | null = null;
|
||||
try {
|
||||
const lookupRes = await apiRequest("GET", `/api/patients/by-insurance-id?insuranceId=${encodeURIComponent(memberId)}`);
|
||||
if (lookupRes.ok) {
|
||||
const patient = await lookupRes.json();
|
||||
if (patient?.id) {
|
||||
const apptRes = await apiRequest("POST", "/api/ai/create-appointment-today", { patientId: patient.id });
|
||||
if (apptRes.ok) {
|
||||
const apptData = await apptRes.json();
|
||||
apptTime = apptData.startTime ? `${apptData.startTime} (${apptData.column ?? "Column A"})` : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
key: "eligibilityCheck",
|
||||
status: "success",
|
||||
message: apptTime
|
||||
? `Eligibility checked. Appointment created at ${apptTime}.`
|
||||
: "Eligibility checked. Could not create appointment — please add manually.",
|
||||
}),
|
||||
);
|
||||
toast({
|
||||
title: "Eligibility checked.",
|
||||
description: apptTime
|
||||
? `Patient added to today's schedule at ${apptTime}.`
|
||||
: "Eligibility saved. Could not create appointment — Column A may be full.",
|
||||
variant: "default",
|
||||
});
|
||||
|
||||
setSelectedPatient(null);
|
||||
|
||||
if (jobResult.pdfFileId) {
|
||||
setPreviewPdfId(jobResult.pdfFileId);
|
||||
setPreviewFallbackFilename(jobResult.pdfFilename ?? `eligibility_${memberId}.pdf`);
|
||||
setPreviewOpen(true);
|
||||
}
|
||||
} catch (error: any) {
|
||||
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "error", message: error.message || "Selenium submission failed" }));
|
||||
toast({ title: "Selenium service error", description: error.message || "An error occurred.", variant: "destructive" });
|
||||
} finally {
|
||||
setIsCheckingEligibilityAppointment(false);
|
||||
}
|
||||
};
|
||||
|
||||
// MH Eligibility & Claims/PreAuth — check eligibility, save to DB, navigate to claims
|
||||
const handleMHEligibilityClaimsPreAuthButton = async () => {
|
||||
if (!memberId || !dateOfBirth) {
|
||||
toast({
|
||||
title: "Missing Fields",
|
||||
description: "Please fill in all the required fields: Member ID, Date of Birth.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCheckingEligibilityClaimsPreAuth(true);
|
||||
try {
|
||||
await runMHEligibilitySelenium();
|
||||
|
||||
dispatch(
|
||||
setTaskStatus({
|
||||
key: "eligibilityCheck",
|
||||
status: "success",
|
||||
message: "Eligibility checked and saved. Redirecting to Claims/PreAuth...",
|
||||
}),
|
||||
);
|
||||
toast({
|
||||
title: "Eligibility checked.",
|
||||
description: "Patient eligibility saved. Redirecting to Claims/PreAuth.",
|
||||
variant: "default",
|
||||
});
|
||||
|
||||
setSelectedPatient(null);
|
||||
await queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
|
||||
setLocation("/claims");
|
||||
} catch (error: any) {
|
||||
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "error", message: error.message || "Selenium submission failed" }));
|
||||
toast({ title: "Selenium service error", description: error.message || "An error occurred.", variant: "destructive" });
|
||||
} finally {
|
||||
setIsCheckingEligibilityClaimsPreAuth(false);
|
||||
}
|
||||
};
|
||||
|
||||
// MH Eligibility & History — eligibility check + service history, saves both PDFs, auto-downloads eligibility PDF only
|
||||
const handleMHEligibilityHistoryButton = async () => {
|
||||
if (!memberId || !dateOfBirth) {
|
||||
toast({
|
||||
title: "Missing Fields",
|
||||
description: "Please fill in all the required fields: Member ID, Date of Birth.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (isUnder14(dateOfBirth)) {
|
||||
toast({ title: "CMSP Patient", description: "Patient is under 14 — running CMSP Eligibility & History & Remaining instead.", variant: "default" });
|
||||
return handleCMSPButton();
|
||||
}
|
||||
|
||||
setIsCheckingEligibilityHistory(true);
|
||||
try {
|
||||
const formattedDob = dateOfBirth ? formatLocalDate(dateOfBirth) : "";
|
||||
const data = {
|
||||
memberId,
|
||||
dateOfBirth: formattedDob,
|
||||
insuranceSiteKey: "MH",
|
||||
firstName: firstName || undefined,
|
||||
lastName: lastName || undefined,
|
||||
};
|
||||
|
||||
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: "Sending Data to Selenium..." }));
|
||||
|
||||
const response = await apiRequest(
|
||||
"POST",
|
||||
"/api/insurance-status/eligibility-history-check",
|
||||
{ data, socketId: socket.id },
|
||||
);
|
||||
const enqueueResult = await response.json();
|
||||
if (enqueueResult.error) throw new Error(enqueueResult.error);
|
||||
|
||||
const jobId = enqueueResult.jobId;
|
||||
if (!jobId) throw new Error("No jobId returned from server");
|
||||
|
||||
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: "Selenium browser starting..." }));
|
||||
|
||||
const jobResult = await waitForSeleniumJob(jobId, (msg) =>
|
||||
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: msg }))
|
||||
);
|
||||
|
||||
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "success", message: "Eligibility and service history PDFs saved to Documents." }));
|
||||
toast({
|
||||
title: "Done",
|
||||
description: "Eligibility and service history PDFs saved. Eligibility PDF downloading now.",
|
||||
variant: "default",
|
||||
});
|
||||
|
||||
await queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
|
||||
const claimed = await tryClaimFromChatbot(selectedPatient?.id);
|
||||
void tryAppointmentFromChatbot();
|
||||
if (claimed) return;
|
||||
setSelectedPatient(null);
|
||||
processNextInQueue();
|
||||
|
||||
// Open all PDFs side by side in the modal
|
||||
if (jobResult.pdfFileId || jobResult.memberDetailsPdfFileId || jobResult.historyPdfFileId) {
|
||||
setDualEligibilityPdfId(jobResult.pdfFileId ?? null);
|
||||
setDualEligibilityFilename(jobResult.pdfFilename ?? `eligibility_${memberId}.pdf`);
|
||||
setDualMemberDetailsPdfId(jobResult.memberDetailsPdfFileId ?? null);
|
||||
setDualMemberDetailsFilename(jobResult.memberDetailsPdfFilename ?? `eligibility_member_details_${memberId}.pdf`);
|
||||
setDualHistoryPdfId(jobResult.historyPdfFileId ?? null);
|
||||
setDualHistoryFilename(jobResult.historyPdfFilename ?? `eligibility_history_${memberId}.pdf`);
|
||||
setDualPreviewOpen(true);
|
||||
}
|
||||
} catch (error: any) {
|
||||
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "error", message: error.message || "Selenium submission failed" }));
|
||||
toast({ title: "Selenium service error", description: error.message || "An error occurred.", variant: "destructive" });
|
||||
} finally {
|
||||
setIsCheckingEligibilityHistory(false);
|
||||
}
|
||||
};
|
||||
|
||||
// CMSP Eligibility & History & Remaining — eligibility + service history + accumulator PDFs
|
||||
const handleCMSPButton = async () => {
|
||||
if (!memberId || !dateOfBirth) {
|
||||
toast({
|
||||
title: "Missing Fields",
|
||||
description: "Please fill in Member ID and Date of Birth.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCheckingCMSP(true);
|
||||
try {
|
||||
const formattedDob = dateOfBirth ? formatLocalDate(dateOfBirth) : "";
|
||||
const data = {
|
||||
memberId,
|
||||
dateOfBirth: formattedDob,
|
||||
insuranceSiteKey: "MH",
|
||||
firstName: firstName || undefined,
|
||||
lastName: lastName || undefined,
|
||||
};
|
||||
|
||||
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: "Sending Data to Selenium..." }));
|
||||
|
||||
const response = await apiRequest(
|
||||
"POST",
|
||||
"/api/insurance-status/cmsp-eligibility-history-remaining-check",
|
||||
{ data, socketId: socket.id },
|
||||
);
|
||||
const enqueueResult = await response.json();
|
||||
if (enqueueResult.error) throw new Error(enqueueResult.error);
|
||||
|
||||
const jobId = enqueueResult.jobId;
|
||||
if (!jobId) throw new Error("No jobId returned from server");
|
||||
|
||||
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: "Selenium browser starting..." }));
|
||||
|
||||
const jobResult = await waitForSeleniumJob(jobId, (msg) =>
|
||||
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: msg }))
|
||||
);
|
||||
|
||||
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "success", message: "MH PDFs saved to Documents." }));
|
||||
toast({
|
||||
title: "Done",
|
||||
description: "Eligibility, history, and accumulator PDFs saved.",
|
||||
variant: "default",
|
||||
});
|
||||
|
||||
await queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
|
||||
const claimed = await tryClaimFromChatbot(selectedPatient?.id);
|
||||
void tryAppointmentFromChatbot();
|
||||
if (claimed) return;
|
||||
setSelectedPatient(null);
|
||||
processNextInQueue();
|
||||
|
||||
// Open 4-panel modal
|
||||
if (jobResult.pdfFileId || jobResult.memberDetailsPdfFileId || jobResult.historyPdfFileId || jobResult.accumulatorPdfFileId) {
|
||||
setCmspEligibilityPdfId(jobResult.pdfFileId ?? null);
|
||||
setCmspEligibilityFilename(jobResult.pdfFilename ?? `mh_eligibility_${memberId}.pdf`);
|
||||
setCmspMemberDetailsPdfId(jobResult.memberDetailsPdfFileId ?? null);
|
||||
setCmspMemberDetailsFilename(jobResult.memberDetailsPdfFilename ?? `mh_member_details_${memberId}.pdf`);
|
||||
setCmspHistoryPdfId(jobResult.historyPdfFileId ?? null);
|
||||
setCmspHistoryFilename(jobResult.historyPdfFilename ?? `mh_history_${memberId}.pdf`);
|
||||
setCmspAccumulatorPdfId(jobResult.accumulatorPdfFileId ?? null);
|
||||
setCmspAccumulatorFilename(jobResult.accumulatorPdfFilename ?? `mh_accumulator_${memberId}.pdf`);
|
||||
if (showPdfViewerOnComplete) setCmspPreviewOpen(true);
|
||||
}
|
||||
} catch (error: any) {
|
||||
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "error", message: error.message || "Selenium submission failed" }));
|
||||
toast({ title: "Selenium service error", description: error.message || "An error occurred.", variant: "destructive" });
|
||||
} finally {
|
||||
setIsCheckingCMSP(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Auto-trigger after prefill (from chatbot or schedule page "Check Eligibility")
|
||||
useEffect(() => {
|
||||
if (!pendingAutoCheck.current || !dateOfBirth) return;
|
||||
@@ -776,12 +317,9 @@ export default function InsuranceStatusPage() {
|
||||
) return;
|
||||
const check = pendingAutoCheck.current;
|
||||
pendingAutoCheck.current = null;
|
||||
if (check === "mh" || check === "mh-history") {
|
||||
// Temporarily disabled: selenium_MH_eligibilityHistoryCheckWorker.py is no
|
||||
// longer used — all MH eligibility checks route through the CMSP/MH worker.
|
||||
handleCMSPButton();
|
||||
} else if (check === "cmsp") {
|
||||
handleCMSPButton();
|
||||
if (check === "mh" || check === "mh-history" || check === "cmsp") {
|
||||
// All MH variants run the single MassHealth portal check
|
||||
setTriggerTarget("mh");
|
||||
} else {
|
||||
// Button-component-handled providers: pass target to their autoTrigger prop
|
||||
setTriggerTarget(check);
|
||||
@@ -1352,24 +890,31 @@ export default function InsuranceStatusPage() {
|
||||
|
||||
{/* Row 6 — MH */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 items-center">
|
||||
<Button
|
||||
id="eligibility-cmsp"
|
||||
className="w-full"
|
||||
disabled={isCheckingCMSP}
|
||||
onClick={() => handleCMSPButton()}
|
||||
>
|
||||
{isCheckingCMSP ? (
|
||||
<>
|
||||
<LoaderCircleIcon className="h-4 w-4 mr-2 animate-spin" />
|
||||
Processing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle className="h-4 w-4 mr-2" />
|
||||
MH
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<div id="eligibility-mh">
|
||||
<MHEligibilityButton
|
||||
memberId={memberId}
|
||||
dateOfBirth={dateOfBirth}
|
||||
firstName={firstName}
|
||||
lastName={lastName}
|
||||
isFormIncomplete={isFormIncomplete}
|
||||
autoTrigger={triggerTarget === "mh"}
|
||||
onAutoTriggered={() => setTriggerTarget(null)}
|
||||
onComplete={(result) => {
|
||||
void flushPendingCopyAgentScreenshots(result);
|
||||
}}
|
||||
onPdfReady={async (pdfId, fallbackFilename) => {
|
||||
await queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
|
||||
const claimed = await tryClaimFromChatbot(selectedPatient?.id);
|
||||
void tryAppointmentFromChatbot();
|
||||
if (!claimed && showPdfViewerOnComplete) {
|
||||
setPreviewPdfId(pdfId);
|
||||
setPreviewFallbackFilename(fallbackFilename ?? `mh_eligibility_${memberId}.pdf`);
|
||||
setPreviewOpen(true);
|
||||
}
|
||||
processNextInQueue();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 md:col-span-2">
|
||||
<Switch
|
||||
@@ -1533,76 +1078,6 @@ export default function InsuranceStatusPage() {
|
||||
fallbackFilename={previewFallbackFilename ?? undefined}
|
||||
/>
|
||||
|
||||
{/* 4-panel modal for CMSP — eligibility, member details, history, accumulator */}
|
||||
<DualPdfPreviewModal
|
||||
open={cmspPreviewOpen}
|
||||
onClose={() => {
|
||||
setCmspPreviewOpen(false);
|
||||
setCmspEligibilityPdfId(null);
|
||||
setCmspEligibilityFilename(null);
|
||||
setCmspMemberDetailsPdfId(null);
|
||||
setCmspMemberDetailsFilename(null);
|
||||
setCmspHistoryPdfId(null);
|
||||
setCmspHistoryFilename(null);
|
||||
setCmspAccumulatorPdfId(null);
|
||||
setCmspAccumulatorFilename(null);
|
||||
}}
|
||||
title="MH Eligibility, Remaining & History"
|
||||
panels={[
|
||||
{
|
||||
pdfId: cmspEligibilityPdfId,
|
||||
fallbackFilename: cmspEligibilityFilename,
|
||||
label: "Eligibility",
|
||||
},
|
||||
{
|
||||
pdfId: cmspMemberDetailsPdfId,
|
||||
fallbackFilename: cmspMemberDetailsFilename,
|
||||
label: "Member Details",
|
||||
},
|
||||
{
|
||||
pdfId: cmspHistoryPdfId,
|
||||
fallbackFilename: cmspHistoryFilename,
|
||||
label: "Service History",
|
||||
},
|
||||
{
|
||||
pdfId: cmspAccumulatorPdfId,
|
||||
fallbackFilename: cmspAccumulatorFilename,
|
||||
label: "Accumulator (Remaining)",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
{/* 3-panel modal for MH Eligibility & History */}
|
||||
<DualPdfPreviewModal
|
||||
open={dualPreviewOpen}
|
||||
onClose={() => {
|
||||
setDualPreviewOpen(false);
|
||||
setDualEligibilityPdfId(null);
|
||||
setDualEligibilityFilename(null);
|
||||
setDualMemberDetailsPdfId(null);
|
||||
setDualMemberDetailsFilename(null);
|
||||
setDualHistoryPdfId(null);
|
||||
setDualHistoryFilename(null);
|
||||
}}
|
||||
title="MH Eligibility & Service History"
|
||||
panels={[
|
||||
{
|
||||
pdfId: dualEligibilityPdfId,
|
||||
fallbackFilename: dualEligibilityFilename,
|
||||
label: "Eligibility",
|
||||
},
|
||||
{
|
||||
pdfId: dualMemberDetailsPdfId,
|
||||
fallbackFilename: dualMemberDetailsFilename,
|
||||
label: "Member Details",
|
||||
},
|
||||
{
|
||||
pdfId: dualHistoryPdfId,
|
||||
fallbackFilename: dualHistoryFilename,
|
||||
label: "Service History",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user