feat: add BCBS MA eligibility check with OTP flow

- New Selenium worker (fresh Chrome per run, no persistent session)
  login → OTP modal → eTools → ConnectCenter → Verification →
  New Eligibility Request → fill form (NPI, member ID, DOB) →
  Expand All → CDP PDF back to app
- Backend route fetches BCBS_MA credentials + provider NPI from settings
- Frontend OTP modal with 6-digit code entry
- BCBS MA added to insurance credentials dropdown in settings

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
ff
2026-06-01 00:36:11 -04:00
co-authored by Claude Sonnet 4.6
parent 535619c286
commit e644d21cee
12 changed files with 1468 additions and 9 deletions
@@ -0,0 +1,255 @@
import fs from "fs/promises";
import fsSync from "fs";
import path from "path";
import { storage } from "../../storage";
import { emptyFolderContainingFile } from "../../utils/emptyTempFolder";
import {
forwardToSeleniumBcbsMaEligibilityAgent,
getSeleniumBcbsMaSessionStatus,
} from "../../services/seleniumBcbsMaInsuranceEligibilityClient";
import { splitName, createOrUpdatePatientByInsuranceId } from "./_shared";
import { io } from "../../socket";
function log(tag: string, msg: string, ctx?: any) {
console.log(`${new Date().toISOString()} [${tag}] ${msg}`, ctx ?? "");
}
function emitToSocket(socketId: string | undefined, event: string, payload: any) {
if (!socketId || !io) return;
try {
const socket = io.sockets.sockets.get(socketId);
if (socket) socket.emit(event, payload);
} catch (err: any) {
log("bcbs-ma-processor", `emit failed for ${event}`, { err: err?.message });
}
}
export interface BcbsMaEligibilityProcessorInput {
enrichedPayload: any;
userId: number;
insuranceId: string;
formFirstName?: string;
formLastName?: string;
formDob?: string;
socketId?: string;
}
export interface BcbsMaEligibilityProcessorResult {
patientUpdateStatus?: string;
pdfUploadStatus?: string;
pdfFileId?: number | null;
pdfFilename?: string | null;
}
async function processBcbsMaResult(
userId: number,
insuranceId: string,
formFirstName: string | undefined,
formLastName: string | undefined,
formDob: string | undefined,
seleniumResult: any
): Promise<BcbsMaEligibilityProcessorResult> {
const output: BcbsMaEligibilityProcessorResult = {};
let createdPdfFileId: number | null = null;
try {
// Resolve patient name
const rawName =
typeof seleniumResult?.patientName === "string" ? seleniumResult.patientName.trim() : null;
let firstName: string;
let lastName: string;
if (rawName) {
if (rawName.includes(",")) {
const [last, ...firstParts] = rawName.split(",").map((s: string) => s.trim());
lastName = last || formLastName || "";
firstName = firstParts.join(" ").trim() || formFirstName || "";
} else {
const parsed = splitName(rawName);
if (!parsed.lastName) {
lastName = parsed.firstName || formLastName || "";
firstName = formFirstName || "";
} else {
firstName = parsed.firstName || formFirstName || "";
lastName = parsed.lastName || formLastName || "";
}
}
} else {
firstName = formFirstName ?? "";
lastName = formLastName ?? "";
}
await createOrUpdatePatientByInsuranceId({ insuranceId, firstName, lastName, dob: formDob, userId });
const normalizedInsuranceId = insuranceId.replace(/\s+/g, "");
const patient = await storage.getPatientByInsuranceId(normalizedInsuranceId);
if (!patient?.id) {
output.patientUpdateStatus = "Patient not found; no update performed";
return output;
}
const eligStatus = (seleniumResult?.eligibility ?? "").toLowerCase();
const newStatus =
eligStatus === "eligible" || eligStatus === "active" ? "ACTIVE" : "INACTIVE";
await storage.updatePatient(patient.id, {
status: newStatus,
insuranceProvider: "BCBS MA",
});
output.patientUpdateStatus = `Patient status updated to ${newStatus}`;
// Save PDF
let pdfBuffer: Buffer | null = null;
let pdfFilename: string | null = null;
const pdfPath: string | null = seleniumResult?.pdf_path ?? null;
if (pdfPath && fsSync.existsSync(pdfPath)) {
try {
pdfBuffer = await fs.readFile(pdfPath);
pdfFilename = path.basename(pdfPath);
} catch (e: any) {
output.pdfUploadStatus = `Failed to read PDF: ${e.message}`;
}
} else {
output.pdfUploadStatus = "No valid PDF path from Selenium.";
}
if (pdfBuffer && pdfFilename) {
const groupTitleKey = "ELIGIBILITY_STATUS";
const groupTitle = "Eligibility Status";
let group = await storage.findPdfGroupByPatientTitleKey(patient.id, groupTitleKey);
if (!group) group = await storage.createPdfGroup(patient.id, groupTitle, groupTitleKey);
if (!group?.id) throw new Error("PDF group creation failed");
const created = await storage.createPdfFile(group.id, pdfFilename, pdfBuffer);
if (created && typeof created === "object" && "id" in created) {
createdPdfFileId = Number(created.id);
}
output.pdfUploadStatus = `PDF saved to group: ${group.title}`;
output.pdfFilename = pdfFilename;
}
output.pdfFileId = createdPdfFileId;
return output;
} catch (err: any) {
log("bcbs-ma-processor", `processBcbsMaResult ERROR: ${err?.message}`, err);
return {
...output,
pdfUploadStatus: output.pdfUploadStatus ?? `Processing failed: ${err?.message}`,
pdfFileId: createdPdfFileId,
};
} finally {
const cleanupPath = seleniumResult?.pdf_path ?? null;
if (cleanupPath) {
try {
await emptyFolderContainingFile(cleanupPath);
} catch (_) {}
}
}
}
async function pollUntilDone(
sessionId: string,
socketId: string | undefined,
jobId: string,
pollTimeoutMs = 8 * 60 * 1000 // 8 min — accounts for fresh login + OTP wait
): Promise<any> {
const maxAttempts = 960; // 960 × 500ms = 8 min
const pollIntervalMs = 500;
const maxTransientErrors = 12;
const noProgressLimit = 120;
let transientErrors = 0;
let consecutiveNoProgress = 0;
let lastStatus: string | null = null;
const deadline = Date.now() + pollTimeoutMs;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
if (Date.now() > deadline) {
throw new Error(`BCBS MA polling timeout (${Math.round(pollTimeoutMs / 1000)}s) for session ${sessionId}`);
}
try {
const st = await getSeleniumBcbsMaSessionStatus(sessionId);
const status: string = st?.status ?? "unknown";
transientErrors = 0;
const isTerminal = status === "completed" || status === "error" || status === "not_found";
if (status === lastStatus && !isTerminal) consecutiveNoProgress++;
else consecutiveNoProgress = 0;
lastStatus = status;
if (consecutiveNoProgress >= noProgressLimit) {
throw new Error(`No progress from Python agent (status="${status}") after ${consecutiveNoProgress} polls`);
}
if (status === "waiting_for_otp") {
emitToSocket(socketId, "selenium:otp_required", {
session_id: sessionId,
jobId,
message: "OTP required. Please enter the 6-digit code from the BCBS MA email.",
});
await new Promise((r) => setTimeout(r, pollIntervalMs));
continue;
}
if (status === "completed") return st.result;
if (status === "error" || status === "not_found") {
throw new Error(st?.message || `BCBS MA session ended with status: ${status}`);
}
await new Promise((r) => setTimeout(r, pollIntervalMs));
} catch (err: any) {
const isTerminal =
err?.response?.status === 404 ||
(typeof err?.message === "string" &&
(err.message.includes("not_found") ||
err.message.includes("polling timeout") ||
err.message.includes("No progress")));
if (isTerminal) throw err;
transientErrors++;
if (transientErrors > maxTransientErrors) {
throw new Error(`Too many transient network errors polling BCBS MA session ${sessionId}`);
}
const backoff = Math.min(30_000, 500 * Math.pow(2, transientErrors - 1));
await new Promise((r) => setTimeout(r, backoff));
}
}
throw new Error(`BCBS MA polling exhausted all attempts for session ${sessionId}`);
}
export async function runBcbsMaEligibilityProcessor(
input: BcbsMaEligibilityProcessorInput,
jobId: string
): Promise<BcbsMaEligibilityProcessorResult> {
const { enrichedPayload, userId, insuranceId, formFirstName, formLastName, formDob, socketId } = input;
log("bcbs-ma-processor", "starting Python agent session", { insuranceId });
const agentResp = await forwardToSeleniumBcbsMaEligibilityAgent(enrichedPayload);
if (!agentResp?.session_id) {
throw new Error("Python agent did not return a session_id for BCBS MA eligibility");
}
const sessionId = agentResp.session_id as string;
log("bcbs-ma-processor", "got session_id", { sessionId });
emitToSocket(socketId, "selenium:bcbs_ma_session_started", { session_id: sessionId, jobId });
const seleniumResult = await pollUntilDone(sessionId, socketId, jobId);
if (!seleniumResult || seleniumResult.status === "error") {
throw new Error(seleniumResult?.message ?? "BCBS MA session returned an error result");
}
log("bcbs-ma-processor", "processing DB result", { insuranceId });
const result = await processBcbsMaResult(
userId, insuranceId, formFirstName, formLastName, formDob, seleniumResult
);
log("bcbs-ma-processor", "done", { result });
return result;
}