Files
DentalManagement09/apps/Frontend/src/components/claims/check-preauth-button.tsx
T
GiteadandClaude Opus 5.5 b95196f4c8 feat: Check PreAuth sets claim Approved/Denied from portal status, Tufts SCO denied preauth PDF
- Add DENIED claim status (migration) and show it in claims list, view and edit
- Check PreAuth updates the claim status from the portal result and refreshes the claims list
- Tufts SCO: read Status column from any cell type, sturdier click into the
  pre-auth detail page (JS fallback, new tab), procedure section optional,
  status in the saved PDF filename, log failures

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 11:44:53 -05:00

181 lines
6.5 KiB
TypeScript

import { useState, useSyncExternalStore } from "react";
import { LoaderCircleIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { toast } from "@/hooks/use-toast";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { socket } from "@/lib/socket";
// Runs the Check PreAuth worker matching the claim's insurance (the backend picks it:
// MassHealth, United SCO, Tufts SCO or CCA).
//
// Running checks live in this module, not in the button, so a check (and its OTP popup)
// keeps going after the Claim/Preauth Details window that started it is closed.
// <PreauthCheckHost /> renders the OTP popup and must stay mounted on the page.
type OtpRequest = { jobId: string; sessionId: string; label: string };
type State = { runningClaimIds: number[]; otp: OtpRequest | null };
let state: State = { runningClaimIds: [], otp: null };
const subscribers = new Set<() => void>();
// Jobs whose OTP popup was answered or dismissed; the backend keeps repeating
// "otp required" while it waits, which must not reopen the popup.
const otpHandledJobIds = new Set<string>();
function setState(patch: Partial<State>) {
state = { ...state, ...patch };
subscribers.forEach((fn) => fn());
}
function subscribe(fn: () => void) {
subscribers.add(fn);
return () => subscribers.delete(fn);
}
const usePreauthCheckState = () => useSyncExternalStore(subscribe, () => state);
async function startPreauthCheck(claimId: number, onCompleted?: () => void) {
if (state.runningClaimIds.includes(claimId)) return;
setState({ runningClaimIds: [...state.runningClaimIds, claimId] });
let jobId = "";
let sessionId: string | null = null;
let label = "";
const handlers: Record<string, (ev: any) => void> = {
"selenium:preauth_check_session_started": (ev) => {
if (String(ev?.jobId) === jobId) sessionId = ev.session_id ?? null;
},
"selenium:otp_required": (ev) => {
if (String(ev?.jobId) !== jobId) return;
sessionId = ev.session_id ?? sessionId;
if (sessionId && !otpHandledJobIds.has(jobId) && state.otp?.jobId !== jobId) setState({ otp: { jobId, sessionId, label } });
},
"job:update": (ev) => {
if (String(ev?.jobId) !== jobId || ev.status === "active") return;
if (ev.status === "completed") {
toast({ title: `${label} Check PreAuth complete`, description: ev.result?.message ?? "" });
// The check may have set the claim to Approved/Denied (QK_CLAIMS_BASE in claims-recent-table)
queryClient.invalidateQueries({ queryKey: ["claims-recent"] });
onCompleted?.();
} else {
toast({
title: `${label} Check PreAuth failed`,
description: ev.error ?? "The check did not finish.",
variant: "destructive",
});
}
finish();
},
};
const finish = () => {
Object.entries(handlers).forEach(([event, fn]) => socket.off(event, fn));
otpHandledJobIds.delete(jobId);
setState({
runningClaimIds: state.runningClaimIds.filter((id) => id !== claimId),
otp: state.otp?.jobId === jobId ? null : state.otp,
});
};
// Listen before the request so no event from a fast job is missed.
Object.entries(handlers).forEach(([event, fn]) => socket.on(event, fn));
try {
const res = await apiRequest("POST", "/api/claims/preauth-check", {
claimId,
socketId: socket.id,
});
const body = await res.json();
if (!res.ok || body.error) throw new Error(body.error || `Server error (${res.status})`);
jobId = String(body.jobId);
label = body.label ?? "";
toast({ title: `${label} Check PreAuth started`, description: "The browser will open shortly." });
} catch (err: any) {
toast({ title: "Check PreAuth error", description: err?.message ?? "Failed to start.", variant: "destructive" });
finish();
}
}
// onCompleted runs after a successful check (the PDF is saved by then); it may fire after the
// details window has closed, so callers must guard against acting on a stale window.
export function CheckPreauthButton({ claimId, onCompleted }: { claimId: number; onCompleted?: () => void }) {
const { runningClaimIds } = usePreauthCheckState();
const running = runningClaimIds.includes(claimId);
return (
<Button variant="outline" disabled={running} onClick={() => void startPreauthCheck(claimId, onCompleted)}>
{running ? (
<>
<LoaderCircleIcon className="mr-2 h-4 w-4 animate-spin" /> Checking…
</>
) : (
"Check Preauth"
)}
</Button>
);
}
export function PreauthCheckHost() {
const { otp: request } = usePreauthCheckState();
const [otp, setOtp] = useState("");
const [submitting, setSubmitting] = useState(false);
const close = () => {
if (request) otpHandledJobIds.add(request.jobId);
setOtp("");
setState({ otp: null });
};
const submitOtp = async () => {
if (!otp.trim() || !request) return;
setSubmitting(true);
try {
const res = await apiRequest("POST", "/api/claims/preauth-check/submit-otp", {
session_id: request.sessionId,
otp: otp.trim(),
socketId: socket.id,
});
const body = await res.json().catch(() => ({}));
if (!res.ok || body.error) throw new Error(body.error || "Failed to submit the code");
close();
} catch (err: any) {
toast({ title: "Code not accepted", description: err?.message, variant: "destructive" });
} finally {
setSubmitting(false);
}
};
return (
<Dialog open={!!request} onOpenChange={(open) => !open && close()}>
<DialogContent className="sm:max-w-[400px]">
<DialogHeader>
<DialogTitle>Enter verification code</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground">
{request?.label} sent a verification code. Enter it here, or type it directly in the browser window.
</p>
<Input
value={otp}
onChange={(e) => setOtp(e.target.value)}
placeholder="Verification code"
onKeyDown={(e) => e.key === "Enter" && void submitOtp()}
autoFocus
/>
<DialogFooter>
<Button variant="outline" onClick={close}>
Cancel
</Button>
<Button onClick={() => void submitOtp()} disabled={submitting || !otp.trim()}>
{submitting ? "Submitting…" : "Submit"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}