feat: Check Preauth from claim details, Tufts SCO approval PDF, all-folder appointment picker

- Same patient may be booked at the same time in different columns (appointment + preauth)
- New preauths save service lines and attachments so the details view shows them
- Claim/Preauth Details: renamed, Check Preauth button picks the worker from the claim's
  insurance (MassHealth, United SCO, Tufts SCO, CCA); OTP popup survives closing the window,
  window closes after a successful check
- Tufts SCO Check Preauth: searches Submitted by pre-auth number, saves the detail page PDF
  to the patient's new Approval folder (PdfTitleKey PREAUTH_APPROVAL migration)
- Appointment attachment picker lists files from all of the patient's folders

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-06 23:01:20 -05:00
co-authored by Claude Opus 5.5
parent 33bea3822c
commit 4cd780e9b2
40 changed files with 1003 additions and 113 deletions
@@ -242,7 +242,7 @@ export function AppointmentAttachments({ appointmentId, patientId }: Appointment
type="button"
variant="ghost"
size="icon"
title="Choose from scanned attachments"
title="Choose from patient files"
onClick={() => setPickerOpen(true)}
>
<ImageIcon className="h-4 w-4" />
@@ -315,6 +315,7 @@ export function AppointmentAttachments({ appointmentId, patientId }: Appointment
open={pickerOpen}
onClose={() => setPickerOpen(false)}
patientId={patientId}
allFolders
onFilesSelected={handleServerFilesSelected}
/>
@@ -0,0 +1,178 @@
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 } 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 ?? "" });
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>
);
}
@@ -1132,6 +1132,8 @@ export function ClaimForm({
return;
}
const preAuthFilesMeta = await savePreAuthAttachments(f.uploadedFiles);
// sending form data to selenium service
onHandleForMHSeleniumClaimPreAuth({
...f,
@@ -1143,6 +1145,7 @@ export function ClaimForm({
insuranceProvider: "Mass Health",
insuranceSiteKey: "MH",
appointmentId: appointmentId ?? 0,
claimFiles: mergeWithExistingAttachments(preAuthFilesMeta),
});
// 5. Close form
@@ -1698,6 +1701,8 @@ export function ClaimForm({
return;
}
const preAuthFilesMeta = await savePreAuthAttachments(form.uploadedFiles);
onHandleForCCASeleniumPreAuth({
...form,
serviceLines: filteredServiceLines,
@@ -1706,6 +1711,7 @@ export function ClaimForm({
insuranceProvider: "CCA",
insuranceSiteKey: "CCA",
appointmentId: appointmentId ?? 0,
claimFiles: mergeWithExistingAttachments(preAuthFilesMeta),
});
onClose();
@@ -1849,6 +1855,21 @@ export function ClaimForm({
return (data.data ?? []) as ClaimFileMeta[];
};
// MH and CCA send the files to Selenium in the request itself, so saving a copy for the
// claim's details must not block the submission if it fails (e.g. over the 5MB limit).
const savePreAuthAttachments = async (files?: File[]): Promise<ClaimFileMeta[]> => {
try {
return await uploadAttachmentsToLocalFolder(files ?? []);
} catch (err: any) {
toast({
title: "Attachments not saved to the PreAuth record",
description: err?.message ?? "They will still be sent with the PreAuth.",
variant: "destructive",
});
return [];
}
};
const handleSave = async () => {
const filteredServiceLines = form.serviceLines.filter(
(line) => (line.procedureCode ?? "").trim() !== "",
@@ -6,12 +6,13 @@ import {
DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import React from "react";
import React, { useEffect, useRef } from "react";
import { formatDateToHumanReadable } from "@/utils/dateUtils";
import { ClaimFileMeta, ClaimWithServiceLines } from "@repo/db/types";
import { FileText, Paperclip, Printer } from "lucide-react";
import { toast } from "@/hooks/use-toast";
import { openPendingTab, showAdaClaimForm } from "@/utils/adaClaimForm";
import { CheckPreauthButton } from "./check-preauth-button";
import {
safeParseMissingTeeth,
splitTeeth,
@@ -68,11 +69,23 @@ export default function ClaimViewModal({
const claimFiles = getClaimFilesArray(claim);
// Check PreAuth finishes after a delay; only close this window if it is still open.
const mountedRef = useRef(true);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const closeAfterPreauthCheck = () => {
if (mountedRef.current) onOpenChange(false);
};
return (
<Dialog open={isOpen} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Claim Details</DialogTitle>
<DialogTitle>Claim/Preauth Details</DialogTitle>
<DialogDescription>
Detailed view of the selected claim.
</DialogDescription>
@@ -379,6 +392,7 @@ export default function ClaimViewModal({
<Printer className="mr-2 h-4 w-4" /> Print ADA Form
</Button>
)}
{claim.id != null && <CheckPreauthButton claimId={claim.id} onCompleted={closeAfterPreauthCheck} />}
<Button
onClick={() => {
onOpenChange(false);
@@ -12,9 +12,14 @@ interface ServerAttachmentsPickerModalProps {
// When set, lists only this patient's saved attachments. When omitted, lists
// recently saved attachments across all patients (used where no patient is in scope yet).
patientId?: number;
// With patientId: list files from all of the patient's folders (Approval, Eligibility, ...)
// instead of only Attachments, with a filter per folder.
allFolders?: boolean;
onFilesSelected: (files: File[]) => void;
}
type PickerFile = CloudFile & { folderName?: string };
function fileIcon(mime: string | undefined | null) {
if (mime?.startsWith("image/")) return ImageIcon;
if (mime === "application/pdf") return FileText;
@@ -59,36 +64,50 @@ export function ServerAttachmentsPickerModal({
open,
onClose,
patientId,
allFolders = false,
onFilesSelected,
}: ServerAttachmentsPickerModalProps) {
const { toast } = useToast();
const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
const [isAdding, setIsAdding] = useState(false);
const [folderFilter, setFolderFilter] = useState<string | null>(null);
const endpoint = patientId
? `/api/claims/patient-attachments?patientId=${patientId}`
: `/api/claims/recent-attachments?limit=40`;
const showAllFolders = allFolders && !!patientId;
const endpoint = showAllFolders
? `/api/claims/patient-files?patientId=${patientId}`
: patientId
? `/api/claims/patient-attachments?patientId=${patientId}`
: `/api/claims/recent-attachments?limit=40`;
const { data, isLoading, isError } = useQuery<CloudFile[]>({
queryKey: ["/api/claims/attachments-picker", patientId ?? "recent"],
const { data, isLoading, isError } = useQuery<PickerFile[]>({
queryKey: ["/api/claims/attachments-picker", patientId ?? "recent", showAllFolders],
queryFn: async () => {
const res = await apiRequest("GET", endpoint);
const json = await res.json();
if (!res.ok || json.error) {
throw new Error(json.message || "Failed to load attachments");
}
return (json.data ?? []) as CloudFile[];
return (json.data ?? []) as PickerFile[];
},
enabled: open,
});
useEffect(() => {
if (!open) setSelectedIds(new Set());
if (!open) {
setSelectedIds(new Set());
setFolderFilter(null);
}
}, [open]);
if (!open) return null;
const files = data ?? [];
const allFiles = data ?? [];
const folderNames = showAllFolders
? [...new Set(allFiles.map((f) => f.folderName || "Other"))].sort()
: [];
const files = folderFilter
? allFiles.filter((f) => (f.folderName || "Other") === folderFilter)
: allFiles;
const toggleSelected = (id: number) => {
setSelectedIds((prev) => {
@@ -103,7 +122,7 @@ export function ServerAttachmentsPickerModal({
if (selectedIds.size === 0) return;
setIsAdding(true);
try {
const selectedFiles = files.filter((f) => selectedIds.has(f.id as number));
const selectedFiles = allFiles.filter((f) => selectedIds.has(f.id as number));
const built = await Promise.all(
selectedFiles.map(async (f) => {
const res = await apiRequest("GET", `/api/cloud-storage/files/${f.id}/content`);
@@ -135,12 +154,31 @@ export function ServerAttachmentsPickerModal({
<div className="relative w-full max-w-2xl mx-4 bg-white rounded-lg shadow-lg flex flex-col max-h-[80vh]">
<div className="p-4 border-b">
<h3 className="text-lg font-medium">Choose from Server Attachments</h3>
<h3 className="text-lg font-medium">
{showAllFolders ? "Choose from Patient Files" : "Choose from Server Attachments"}
</h3>
<p className="text-sm text-muted-foreground mt-1">
{patientId
? "Previously saved screenshots and files for this patient."
: "Recently saved screenshots and files across all patients."}
{showAllFolders
? "Files saved in any of this patient's folders (Approval, Eligibility, Attachments, ...)."
: patientId
? "Previously saved screenshots and files for this patient."
: "Recently saved screenshots and files across all patients."}
</p>
{folderNames.length > 1 && (
<div className="flex flex-wrap gap-2 mt-3">
{[null, ...folderNames].map((name) => (
<Button
key={name ?? "__all"}
type="button"
size="sm"
variant={folderFilter === name ? "default" : "outline"}
onClick={() => setFolderFilter(name)}
>
{name ?? "All"}
</Button>
))}
</div>
)}
</div>
<div className="p-4 overflow-y-auto flex-1" style={{ minHeight: "200px" }}>
@@ -154,7 +192,9 @@ export function ServerAttachmentsPickerModal({
</p>
) : files.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-8">
{patientId
{showAllFolders
? "No files saved yet for this patient."
: patientId
? "No screenshots saved yet for this patient."
: "No screenshots saved yet."}
</p>
@@ -175,7 +215,10 @@ export function ServerAttachmentsPickerModal({
<AttachmentThumbnail file={file} />
</div>
<div className="p-2">
<p className="text-xs font-medium truncate">{file.name}</p>
<p className="text-xs font-medium truncate" title={file.name}>{file.name}</p>
{showAllFolders && file.folderName && (
<p className="text-[11px] text-muted-foreground truncate">{file.folderName}</p>
)}
</div>
{isSelected && (
<div className="absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5">