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 }); 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( export async function runPreAuthCheckProcessor(
input: { input: {
siteKey: PreAuthCheckSiteKey; siteKey: PreAuthCheckSiteKey;
@@ -149,6 +157,15 @@ export async function runPreAuthCheckProcessor(
throw new Error(result?.message ?? "Check PreAuth returned an error"); throw new Error(result?.message ?? "Check PreAuth returned an error");
} }
let message = typeof result.message === "string" ? result.message : "completed"; 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 { try {
if (result.approval_pdf_path) { if (result.approval_pdf_path) {
const saved = await saveApprovalPdf(userId, claimId, result.approval_pdf_path); const saved = await saveApprovalPdf(userId, claimId, result.approval_pdf_path);
@@ -10,7 +10,7 @@ import {
DialogTitle, DialogTitle,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { toast } from "@/hooks/use-toast"; import { toast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient"; import { apiRequest, queryClient } from "@/lib/queryClient";
import { socket } from "@/lib/socket"; import { socket } from "@/lib/socket";
// Runs the Check PreAuth worker matching the claim's insurance (the backend picks it: // 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 (String(ev?.jobId) !== jobId || ev.status === "active") return;
if (ev.status === "completed") { if (ev.status === "completed") {
toast({ title: `${label} Check PreAuth complete`, description: ev.result?.message ?? "" }); 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?.(); onCompleted?.();
} else { } else {
toast({ toast({
@@ -136,6 +136,7 @@ export default function ClaimEditModal({
<SelectItem value="PENDING">Pending</SelectItem> <SelectItem value="PENDING">Pending</SelectItem>
<SelectItem value="REVIEW">Review</SelectItem> <SelectItem value="REVIEW">Review</SelectItem>
<SelectItem value="APPROVED">Approved</SelectItem> <SelectItem value="APPROVED">Approved</SelectItem>
<SelectItem value="DENIED">Denied</SelectItem>
<SelectItem value="CANCELLED">Cancelled</SelectItem> <SelectItem value="CANCELLED">Cancelled</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
@@ -126,7 +126,8 @@ export default function ClaimViewModal({
className={`font-medium ${ className={`font-medium ${
claim.status === "APPROVED" claim.status === "APPROVED"
? "text-green-600" ? "text-green-600"
: claim.status === "CANCELLED" : claim.status === "CANCELLED" ||
claim.status === "DENIED"
? "text-red-600" ? "text-red-600"
: claim.status === "REVIEW" : claim.status === "REVIEW"
? "text-yellow-600" ? "text-yellow-600"
@@ -293,6 +293,12 @@ export default function ClaimsRecentTable({
color: "bg-blue-100 text-blue-800", color: "bg-blue-100 text-blue-800",
icon: <Clock className="h-3 w-3 mr-1" />, 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: default:
return { return {
label: status label: status
@@ -5,6 +5,7 @@ from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support import expected_conditions as EC
import base64 import base64
import os import os
import re
import time import time
from selenium_DentaQuest_eligibilityCheckWorker import AutomationDentaQuestEligibilityCheck 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"Tufts SCO found no pre-auth/claim #{number}."}
return {"status": "error", "message": f"Search result for #{number} did not load."} 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 # 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 = "" status = ""
try: try:
headers = [h.text.strip().lower() for h in self.driver.find_elements(By.XPATH, "//thead//th")] 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]/td") cells = self.driver.find_elements(By.XPATH, "//tbody//tr[1]/*")
if "status" in headers and headers.index("status") < len(cells): idx = next((i for i, h in enumerate(headers) if h.startswith("status")), -1)
status = cells[headers.index("status")].text.strip() if 0 <= idx < len(cells):
except Exception: status = cells[idx].text.strip()
pass 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}") print(f"[TuftsSCO PreAuthCheck step2] Status: {status!r}")
id_link.click() # A plain click can be intercepted (banner over the row) or hit a re-rendered link
print(f"[TuftsSCO PreAuthCheck step2] Opened #{number}") 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>") # 2) Wait for the detail page ("Pre-authorization <number> for <name>")
try: try:
WebDriverWait(self.driver, 30).until(EC.presence_of_element_located( 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}')]") (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')]") (By.XPATH, "//*[contains(normalize-space(.), 'Procedure information')]")
)) ))
except TimeoutException: 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 time.sleep(2) # let the procedure table finish rendering
# Procedure lines for the patient's Preauth History # Procedure lines for the patient's Preauth History
@@ -127,8 +156,9 @@ class AutomationTuftsSCOPreAuthCheck(AutomationDentaQuestEligibilityCheck):
"marginLeft": 0.4, "marginLeft": 0.4,
"marginRight": 0.4, "marginRight": 0.4,
}) })
status_slug = re.sub(r"[^a-z0-9]+", "_", status.lower()).strip("_") or "approval"
pdf_path = os.path.join( 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: with open(pdf_path, "wb") as f:
f.write(base64.b64decode(pdf.get("data", ""))) 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 # Leave the browser idle so the session stays logged in for the next run
try: try:
if new_windows:
self.driver.close()
self.driver.switch_to.window(next(iter(windows_before)))
self.driver.get("about:blank") self.driver.get("about:blank")
self.driver.minimize_window() self.driver.minimize_window()
except Exception: except Exception:
@@ -150,4 +183,5 @@ class AutomationTuftsSCOPreAuthCheck(AutomationDentaQuestEligibilityCheck):
"approval_pdf_path": pdf_path, "approval_pdf_path": pdf_path,
} }
except Exception as e: except Exception as e:
print(f"[TuftsSCO PreAuthCheck step2] Failed: {e}")
return {"status": "error", "message": f"Tufts SCO pre-auth check failed: {e}"} return {"status": "error", "message": f"Tufts SCO pre-auth check failed: {e}"}
File diff suppressed because one or more lines are too long
@@ -639,7 +639,8 @@ exports.ClaimStatus = exports.$Enums.ClaimStatus = {
CANCELLED: 'CANCELLED', CANCELLED: 'CANCELLED',
REVIEW: 'REVIEW', REVIEW: 'REVIEW',
VOID: 'VOID', VOID: 'VOID',
PREAUTH: 'PREAUTH' PREAUTH: 'PREAUTH',
DENIED: 'DENIED'
}; };
exports.ServiceLineStatus = exports.$Enums.ServiceLineStatus = { exports.ServiceLineStatus = exports.$Enums.ServiceLineStatus = {
+2 -1
View File
@@ -237,7 +237,8 @@ export const ClaimStatus: {
CANCELLED: 'CANCELLED', CANCELLED: 'CANCELLED',
REVIEW: 'REVIEW', REVIEW: 'REVIEW',
VOID: 'VOID', VOID: 'VOID',
PREAUTH: 'PREAUTH' PREAUTH: 'PREAUTH',
DENIED: 'DENIED'
}; };
export type ClaimStatus = (typeof ClaimStatus)[keyof typeof ClaimStatus] export type ClaimStatus = (typeof ClaimStatus)[keyof typeof ClaimStatus]
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1,5 +1,5 @@
{ {
"name": "prisma-client-32b9f11a0c5c7afdeeb154c1948bfe50de9e1462e57080389ada2ebd794fa5e4", "name": "prisma-client-5ef9a1d7eab38844c979ecf827cfa9b9b5ebfdee813a113aab886483d3d210c6",
"main": "index.js", "main": "index.js",
"types": "index.d.ts", "types": "index.d.ts",
"browser": "default.js", "browser": "default.js",
@@ -258,6 +258,7 @@ enum ClaimStatus {
REVIEW REVIEW
VOID VOID
PREAUTH PREAUTH
DENIED
} }
enum MissingTeethStatus { enum MissingTeethStatus {
@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "ClaimStatus" ADD VALUE 'DENIED';
+1
View File
@@ -259,6 +259,7 @@ enum ClaimStatus {
REVIEW REVIEW
VOID VOID
PREAUTH PREAUTH
DENIED
} }
enum MissingTeethStatus { enum MissingTeethStatus {
@@ -1,7 +1,7 @@
{ {
"version": "1.0", "version": "1.0",
"generatorVersion": "1.0.0", "generatorVersion": "1.0.0",
"generatedAt": "2026-11-09T16:51:33.389Z", "generatedAt": "2026-11-10T15:57:34.274Z",
"outputPath": "/home/ee/Desktop/DentalManagement09/packages/db/shared", "outputPath": "/home/ee/Desktop/DentalManagement09/packages/db/shared",
"files": [ "files": [
"schemas/enums/TransactionIsolationLevel.schema.ts", "schemas/enums/TransactionIsolationLevel.schema.ts",
@@ -1,5 +1,5 @@
import * as z from 'zod'; import * as z from 'zod';
export const ClaimStatusSchema = z.enum(['PENDING', 'APPROVED', 'CANCELLED', 'REVIEW', 'VOID', 'PREAUTH']) export const ClaimStatusSchema = z.enum(['PENDING', 'APPROVED', 'CANCELLED', 'REVIEW', 'VOID', 'PREAUTH', 'DENIED'])
export type ClaimStatus = z.infer<typeof ClaimStatusSchema>; export type ClaimStatus = z.infer<typeof ClaimStatusSchema>;