import axios from "axios"; import fs from "fs/promises"; import path from "path"; import { storage } from "../../storage"; import { callPythonSync, sleep } from "./_shared"; import { io } from "../../socket"; const SELENIUM_BASE_URL = process.env.SELENIUM_AGENT_BASE_URL || "http://localhost:5002"; export const PREAUTH_CHECK_SITE_KEYS = ["MH", "UNITED_SCO", "TUFTS_SCO", "CCA"] as const; export type PreAuthCheckSiteKey = (typeof PREAUTH_CHECK_SITE_KEYS)[number]; export const PREAUTH_CHECK_LABELS: Record = { MH: "MassHealth", UNITED_SCO: "United SCO", TUFTS_SCO: "Tufts SCO", CCA: "CCA", }; // Picks the Check PreAuth worker from the claim's insuranceProvider; null if none applies. export function preAuthCheckSiteKeyFor(insuranceProvider?: string | null): PreAuthCheckSiteKey | null { const p = (insuranceProvider ?? "").toLowerCase().trim(); if (p.includes("masshealth") || p.includes("mass health")) return "MH"; if (p === "cca" || p.includes("commonwealth care")) return "CCA"; if (p.includes("tufts") || p.includes("dentaquest")) return "TUFTS_SCO"; // United SCO's portal is DentalHub, so "United/DentalHub" records use it if (p.includes("dentalhub") || (p.includes("united") && p.includes("sco"))) return "UNITED_SCO"; return null; } const ENDPOINTS: Record = { MH: "/mh-preauth-check", UNITED_SCO: "/unitedsco-preauth-check", TUFTS_SCO: "/tuftssco-preauth-check", CCA: "/cca-preauth-check", }; function log(msg: string, ctx?: any) { console.log(`${new Date().toISOString()} [preauth-check-processor] ${msg}`, ctx ?? ""); } function emitToSocket(socketId: string | undefined, event: string, payload: any) { if (!socketId || !io) return; io.sockets.sockets.get(socketId)?.emit(event, payload); } async function pollSession( sessionId: string, socketId: string | undefined, jobId: string, timeoutMs = 5 * 60 * 1000 ): Promise { const deadline = Date.now() + timeoutMs; let transientErrors = 0; while (Date.now() < deadline) { let st: any; try { st = (await axios.get(`${SELENIUM_BASE_URL}/session/${sessionId}/status`)).data; transientErrors = 0; } catch (err: any) { if (err?.response?.status === 404) throw new Error("Selenium session ended unexpectedly"); if (++transientErrors > 10) throw new Error(`Lost contact with Selenium: ${err?.message}`); await sleep(2000); continue; } const status: string = st?.status ?? "unknown"; if (status === "completed") return st.result; if (status === "error") throw new Error(st?.message || "Check PreAuth failed in Selenium"); // Repeated while waiting (like the eligibility checks) so a missed event doesn't hide the popup if (status === "waiting_for_otp") { emitToSocket(socketId, "selenium:otp_required", { session_id: sessionId, jobId, message: "OTP required. Please enter the verification code.", }); } await sleep(1000); } throw new Error(`Check PreAuth timed out after ${Math.round(timeoutMs / 1000)}s`); } // Selenium leaves PDFs/screenshots in its downloads folder; delete them once handled // rather than leave patient documents behind. async function removeDownloadedFiles(result: any) { for (const key of ["pdf_path", "ss_path", "screenshot_path", "approval_pdf_path"]) { const p = result?.[key]; if (typeof p === "string" && p) await fs.unlink(p).catch(() => {}); } } // Files the portal's pre-auth detail page PDF under the claim's patient > Approval. async function saveApprovalPdf(userId: number, claimId: number | undefined, pdfPath: string): Promise { const claim = claimId ? await storage.getClaim(claimId) : undefined; if (!claim?.patientId) { log("approval PDF not saved: claim/patient not found", { claimId }); return false; } const patient = await storage.getPatient(claim.patientId); const patientName = `${patient?.firstName ?? ""} ${patient?.lastName ?? ""}`.trim() || claim.patientName || `Patient ${claim.patientId}`; const buffer = await fs.readFile(pdfPath); await storage.savePdfToCloudStorage(userId, claim.patientId, patientName, "Approval", path.basename(pdfPath), buffer); log("approval PDF saved", { claimId, patientId: claim.patientId }); return true; } // Procedure lines of the pre-auth, shown in the patient's Preauth History async function savePreauthHistory(claimId: number | undefined, preAuthNumber: string, procedures: any[]) { const claim = claimId ? await storage.getClaim(claimId) : undefined; if (!claim?.patientId) { log("preauth history not saved: claim/patient not found", { claimId }); return; } await storage.replacePatientPreauthHistory(claim.patientId, preAuthNumber, procedures); log("preauth history saved", { claimId, patientId: claim.patientId, rows: procedures.length }); } export async function runPreAuthCheckProcessor( input: { siteKey: PreAuthCheckSiteKey; enrichedPayload: any; socketId?: string; userId: number; claimId?: number; }, jobId: string ): Promise<{ siteKey: PreAuthCheckSiteKey; message: string }> { const { siteKey, enrichedPayload, socketId, userId, claimId } = input; log("starting", { siteKey, jobId }); let result: any; if (siteKey === "MH") { result = await callPythonSync(ENDPOINTS.MH, { data: enrichedPayload }); } else { const start = (await axios.post(`${SELENIUM_BASE_URL}${ENDPOINTS[siteKey]}`, { data: enrichedPayload })).data; if (!start?.session_id) throw new Error("Selenium did not return a session_id for Check PreAuth"); emitToSocket(socketId, "selenium:preauth_check_session_started", { session_id: start.session_id, jobId, }); result = await pollSession(start.session_id, socketId, jobId); } if (!result || result.status === "error") { throw new Error(result?.message ?? "Check PreAuth returned an error"); } let message = typeof result.message === "string" ? result.message : "completed"; try { if (result.approval_pdf_path) { const saved = await saveApprovalPdf(userId, claimId, result.approval_pdf_path); message += saved ? " Saved to the patient's Approval folder." : ""; } if (Array.isArray(result.procedures) && result.procedures.length > 0 && result.preAuthNumber) { try { await savePreauthHistory(claimId, String(result.preAuthNumber), result.procedures); } catch (e: any) { log("saving preauth history failed", { claimId, error: e?.message }); } } } finally { await removeDownloadedFiles(result); } log("done", { siteKey, jobId }); return { siteKey, message }; }