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>
This commit is contained in:
2026-11-10 11:44:53 -05:00
co-authored by Claude Opus 5.5
parent 108c72e570
commit b95196f4c8
16 changed files with 91 additions and 22 deletions
@@ -119,6 +119,14 @@ async function savePreauthHistory(claimId: number | undefined, preAuthNumber: st
log("preauth history saved", { claimId, patientId: claim.patientId, rows: procedures.length });
}
// Portal status text (e.g. "Approved", "Denied") -> claim status; null leaves the claim as is.
function claimStatusForPortalStatus(portalStatus: unknown): "APPROVED" | "DENIED" | null {
const s = String(portalStatus ?? "").toLowerCase();
if (s.includes("denied") || s.includes("rejected")) return "DENIED";
if (s.includes("approved")) return "APPROVED";
return null;
}
export async function runPreAuthCheckProcessor(
input: {
siteKey: PreAuthCheckSiteKey;
@@ -149,6 +157,15 @@ export async function runPreAuthCheckProcessor(
throw new Error(result?.message ?? "Check PreAuth returned an error");
}
let message = typeof result.message === "string" ? result.message : "completed";
const newStatus = claimStatusForPortalStatus(result.preAuthStatus);
if (newStatus && claimId) {
try {
await storage.updateClaimStatus(claimId, newStatus);
message += ` Status set to ${newStatus === "DENIED" ? "Denied" : "Approved"}.`;
} catch (e: any) {
log("updating claim status failed", { claimId, error: e?.message });
}
}
try {
if (result.approval_pdf_path) {
const saved = await saveApprovalPdf(userId, claimId, result.approval_pdf_path);
@@ -10,7 +10,7 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { toast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
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:
@@ -61,6 +61,8 @@ async function startPreauthCheck(claimId: number, onCompleted?: () => void) {
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({
@@ -136,6 +136,7 @@ export default function ClaimEditModal({
<SelectItem value="PENDING">Pending</SelectItem>
<SelectItem value="REVIEW">Review</SelectItem>
<SelectItem value="APPROVED">Approved</SelectItem>
<SelectItem value="DENIED">Denied</SelectItem>
<SelectItem value="CANCELLED">Cancelled</SelectItem>
</SelectContent>
</Select>
@@ -126,7 +126,8 @@ export default function ClaimViewModal({
className={`font-medium ${
claim.status === "APPROVED"
? "text-green-600"
: claim.status === "CANCELLED"
: claim.status === "CANCELLED" ||
claim.status === "DENIED"
? "text-red-600"
: claim.status === "REVIEW"
? "text-yellow-600"
@@ -293,6 +293,12 @@ export default function ClaimsRecentTable({
color: "bg-blue-100 text-blue-800",
icon: <Clock className="h-3 w-3 mr-1" />,
};
case "DENIED":
return {
label: "Denied",
color: "bg-red-100 text-red-800",
icon: <AlertCircle className="h-3 w-3 mr-1" />,
};
default:
return {
label: status
@@ -5,6 +5,7 @@ from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import base64
import os
import re
import time
from selenium_DentaQuest_eligibilityCheckWorker import AutomationDentaQuestEligibilityCheck
@@ -88,29 +89,57 @@ class AutomationTuftsSCOPreAuthCheck(AutomationDentaQuestEligibilityCheck):
return {"status": "error", "message": f"Tufts SCO found no pre-auth/claim #{number}."}
return {"status": "error", "message": f"Search result for #{number} did not load."}
# Status column of the result row (e.g. "Approved"), read before leaving the page
# (cells may be <th> or <td>, and header text may carry sort-icon text)
status = ""
try:
headers = [h.text.strip().lower() for h in self.driver.find_elements(By.XPATH, "//thead//th")]
cells = self.driver.find_elements(By.XPATH, "//tbody//tr[1]/td")
if "status" in headers and headers.index("status") < len(cells):
status = cells[headers.index("status")].text.strip()
except Exception:
pass
headers = [h.text.strip().lower() for h in self.driver.find_elements(By.XPATH, "//thead//tr[1]/*")]
cells = self.driver.find_elements(By.XPATH, "//tbody//tr[1]/*")
idx = next((i for i, h in enumerate(headers) if h.startswith("status")), -1)
if 0 <= idx < len(cells):
status = cells[idx].text.strip()
if not status:
row_text = " ".join(c.text for c in cells).lower()
for word in ("Partially approved", "Approved", "Denied","Pending", "In review", "Rejected"):
if word.lower() in row_text:
status = word
break
except Exception as e:
print(f"[TuftsSCO PreAuthCheck step2] Reading status failed: {e}")
print(f"[TuftsSCO PreAuthCheck step2] Status: {status!r}")
id_link.click()
print(f"[TuftsSCO PreAuthCheck step2] Opened #{number}")
# A plain click can be intercepted (banner over the row) or hit a re-rendered link
link_xpath = f"//tbody//tr[1]/*[1]//*[self::a or self::button][contains(normalize-space(.), '{number}')]"
windows_before = set(self.driver.window_handles)
try:
id_link = self.driver.find_element(By.XPATH, link_xpath)
self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", id_link)
id_link.click()
except Exception as e:
print(f"[TuftsSCO PreAuthCheck step2] Click failed ({type(e).__name__}), using JS click")
self.driver.execute_script("arguments[0].click();", self.driver.find_element(By.XPATH, link_xpath))
# The detail page may open in a new tab
time.sleep(1)
new_windows = [w for w in self.driver.window_handles if w not in windows_before]
if new_windows:
self.driver.switch_to.window(new_windows[0])
print("[TuftsSCO PreAuthCheck step2] Detail page opened in a new tab")
print(f"[TuftsSCO PreAuthCheck step2] Opened #{number}: {self.driver.current_url}")
# 2) Wait for the detail page ("Pre-authorization <number> for <name>")
try:
WebDriverWait(self.driver, 30).until(EC.presence_of_element_located(
(By.XPATH, f"//h1[contains(., '{number}')] | //*[self::h1 or self::h2][contains(., 'for ')][contains(., '{number}')]")
))
WebDriverWait(self.driver, 30).until(EC.presence_of_element_located(
except TimeoutException:
print(f"[TuftsSCO PreAuthCheck step2] Detail page not found. URL: {self.driver.current_url}")
return {"status": "error", "message": f"Detail page for #{number} did not load."}
# Denied pre-auths may have no procedure section; still save the page as a PDF
try:
WebDriverWait(self.driver, 15).until(EC.presence_of_element_located(
(By.XPATH, "//*[contains(normalize-space(.), 'Procedure information')]")
))
except TimeoutException:
return {"status": "error", "message": f"Detail page for #{number} did not load."}
print("[TuftsSCO PreAuthCheck step2] No 'Procedure information' section")
time.sleep(2) # let the procedure table finish rendering
# Procedure lines for the patient's Preauth History
@@ -127,8 +156,9 @@ class AutomationTuftsSCOPreAuthCheck(AutomationDentaQuestEligibilityCheck):
"marginLeft": 0.4,
"marginRight": 0.4,
})
status_slug = re.sub(r"[^a-z0-9]+", "_", status.lower()).strip("_") or "approval"
pdf_path = os.path.join(
self.download_dir, f"tuftssco_preauth_approval_{number}_{int(time.time())}.pdf"
self.download_dir, f"tuftssco_preauth_{status_slug}_{number}_{int(time.time())}.pdf"
)
with open(pdf_path, "wb") as f:
f.write(base64.b64decode(pdf.get("data", "")))
@@ -136,6 +166,9 @@ class AutomationTuftsSCOPreAuthCheck(AutomationDentaQuestEligibilityCheck):
# Leave the browser idle so the session stays logged in for the next run
try:
if new_windows:
self.driver.close()
self.driver.switch_to.window(next(iter(windows_before)))
self.driver.get("about:blank")
self.driver.minimize_window()
except Exception:
@@ -150,4 +183,5 @@ class AutomationTuftsSCOPreAuthCheck(AutomationDentaQuestEligibilityCheck):
"approval_pdf_path": pdf_path,
}
except Exception as e:
print(f"[TuftsSCO PreAuthCheck step2] Failed: {e}")
return {"status": "error", "message": f"Tufts SCO pre-auth check failed: {e}"}