feat: MetLife Dental eligibility check with persistent session
Mirrors the DDMA flow: persistent Chrome profile + credential-change logout, PingOne login with email MFA selection and OTP from app or browser, Eligibility & Plan Details search (masked Subscriber ID/SSN), family member picked by DOB and re-verified on the plan details page, PDF saved to the patient's Eligibility folder and status set ACTIVE/INACTIVE. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,394 @@
|
||||
/**
|
||||
* Processor for "metlife-eligibility-check" jobs.
|
||||
*
|
||||
* Integrates the MetLife persistent-session flow into the InProcessQueue
|
||||
* (same shape as the DDMA processor):
|
||||
* 1. Start a session on the Python agent (POST /metlife-eligibility)
|
||||
* 2. Emit selenium:metlife_session_started → frontend stores session_id for OTP
|
||||
* 3. Poll agent status, emitting selenium:otp_required when OTP is needed
|
||||
* 4. On completion: save PDF, create/update patient, update eligibility status
|
||||
* 5. Return { pdfFileId, pdfFilename, patientUpdateStatus, pdfUploadStatus }
|
||||
*
|
||||
* The OTP submission endpoint (/api/insurance-status-metlife/selenium/submit-otp)
|
||||
* continues to forward OTPs directly to the Python agent — it does NOT go
|
||||
* through the queue.
|
||||
*/
|
||||
import fs from "fs/promises";
|
||||
import fsSync from "fs";
|
||||
import path from "path";
|
||||
import { storage } from "../../storage";
|
||||
import { emptyFolderContainingFile } from "../../utils/emptyTempFolder";
|
||||
import {
|
||||
forwardToSeleniumMetLifeEligibilityAgent,
|
||||
getSeleniumMetLifeSessionStatus,
|
||||
} from "../../services/seleniumMetLifeEligibilityClient";
|
||||
import {
|
||||
splitName,
|
||||
createOrUpdatePatientByInsuranceId,
|
||||
imageToPdfBuffer,
|
||||
} from "./_shared";
|
||||
import { io } from "../../socket";
|
||||
|
||||
// ─── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
function now() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function log(tag: string, msg: string, ctx?: any) {
|
||||
console.log(`${now()} [${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);
|
||||
log("metlife-processor", `emitted ${event}`, { socketId });
|
||||
}
|
||||
} catch (err: any) {
|
||||
log("metlife-processor", `emit failed for ${event}`, { err: err?.message });
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Types ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface MetLifeEligibilityProcessorInput {
|
||||
enrichedPayload: any;
|
||||
userId: number;
|
||||
insuranceId: string;
|
||||
formFirstName?: string;
|
||||
formLastName?: string;
|
||||
formDob?: string;
|
||||
socketId?: string;
|
||||
}
|
||||
|
||||
export interface MetLifeEligibilityProcessorResult {
|
||||
patientUpdateStatus?: string;
|
||||
pdfUploadStatus?: string;
|
||||
pdfFileId?: number | string | null;
|
||||
pdfFilename?: string | null;
|
||||
}
|
||||
|
||||
// ─── Core DB processing ──────────────────────────────────────────────────────
|
||||
|
||||
async function processMetLifeResult(
|
||||
userId: number,
|
||||
insuranceId: string,
|
||||
formFirstName: string | undefined,
|
||||
formLastName: string | undefined,
|
||||
formDob: string | undefined,
|
||||
seleniumResult: any
|
||||
): Promise<MetLifeEligibilityProcessorResult> {
|
||||
const output: MetLifeEligibilityProcessorResult = {};
|
||||
let createdPdfFileId: number | string | null = null;
|
||||
|
||||
try {
|
||||
// 1) Resolve patient name (prefer selenium extraction → form data)
|
||||
const rawName =
|
||||
typeof seleniumResult?.patientName === "string"
|
||||
? seleniumResult.patientName.trim()
|
||||
: null;
|
||||
|
||||
let firstName: string;
|
||||
let lastName: string;
|
||||
|
||||
if (rawName) {
|
||||
// Strip any trailing bare date e.g. "Christian Rodriguez 04/27/2026"
|
||||
const cleanName = rawName.replace(/\s+\d{1,2}\/\d{1,2}\/\d{2,4}$/, "").trim();
|
||||
|
||||
if (cleanName.includes(",")) {
|
||||
// "LAST, FIRST" format common on insurance portals
|
||||
const [last, ...firstParts] = cleanName.split(",").map((s: string) => s.trim());
|
||||
lastName = last || formLastName || "";
|
||||
firstName = firstParts.join(" ").trim() || formFirstName || "";
|
||||
} else {
|
||||
const parsed = splitName(cleanName);
|
||||
if (!parsed.lastName) {
|
||||
// Single word — treat as last name, pull first name from form
|
||||
lastName = parsed.firstName || formLastName || "";
|
||||
firstName = formFirstName || "";
|
||||
} else {
|
||||
firstName = parsed.firstName || formFirstName || "";
|
||||
lastName = parsed.lastName || formLastName || "";
|
||||
}
|
||||
}
|
||||
} else {
|
||||
firstName = formFirstName ?? "";
|
||||
lastName = formLastName ?? "";
|
||||
}
|
||||
|
||||
// 2) Create / update patient
|
||||
const upsertedPatient = await createOrUpdatePatientByInsuranceId({
|
||||
insuranceId,
|
||||
firstName,
|
||||
lastName,
|
||||
dob: formDob,
|
||||
userId,
|
||||
});
|
||||
|
||||
// 3) Fetch patient (needed for ID)
|
||||
const normalizedInsuranceId = insuranceId.replace(/\s+/g, "");
|
||||
// Use the patient just created/updated (family members share an insuranceId, so an
|
||||
// id-only lookup could return a different member).
|
||||
const dobForLookup = formDob ? new Date(formDob) : null;
|
||||
const patient =
|
||||
upsertedPatient ??
|
||||
(dobForLookup && !isNaN(dobForLookup.getTime())
|
||||
? await storage.getPatientByInsuranceIdAndDob(normalizedInsuranceId, dobForLookup)
|
||||
: await storage.getPatientByInsuranceId(normalizedInsuranceId));
|
||||
log("metlife-processor", `patient lookup after create: ${patient ? `id=${patient.id}` : "NOT FOUND"} for insuranceId="${normalizedInsuranceId}"`);
|
||||
if (!patient?.id) {
|
||||
output.patientUpdateStatus = "Patient not found; no update performed";
|
||||
return output;
|
||||
}
|
||||
|
||||
// 4) Determine and update eligibility status + insurance provider name
|
||||
const eligStatus = (seleniumResult?.eligibility ?? "").toLowerCase();
|
||||
let newStatus = "UNKNOWN";
|
||||
if (eligStatus === "active" || eligStatus === "y") newStatus = "ACTIVE";
|
||||
else if (eligStatus === "inactive" || eligStatus === "n" || eligStatus === "termed") newStatus = "INACTIVE";
|
||||
await storage.updatePatient(patient.id, {
|
||||
status: newStatus,
|
||||
insuranceProvider: "MetLife Dental",
|
||||
});
|
||||
output.patientUpdateStatus = `Patient status updated to ${newStatus}`;
|
||||
|
||||
// 5) Resolve PDF buffer
|
||||
// Worker returns a real PDF via pdf_path / ss_path (.pdf); screenshots are converted.
|
||||
let pdfBuffer: Buffer | null = null;
|
||||
let pdfFilename: string | null = null;
|
||||
|
||||
const pdfPath: string | null =
|
||||
seleniumResult?.pdf_path ?? seleniumResult?.ss_path ?? null;
|
||||
|
||||
if (pdfPath && fsSync.existsSync(pdfPath)) {
|
||||
if (pdfPath.endsWith(".pdf")) {
|
||||
// Already a PDF — read directly
|
||||
try {
|
||||
pdfBuffer = await fs.readFile(pdfPath);
|
||||
pdfFilename = path.basename(pdfPath);
|
||||
log("metlife-processor", "read PDF directly", { pdfPath });
|
||||
} catch (e: any) {
|
||||
output.pdfUploadStatus = `Failed to read PDF: ${e.message}`;
|
||||
}
|
||||
} else if (
|
||||
pdfPath.endsWith(".png") ||
|
||||
pdfPath.endsWith(".jpg") ||
|
||||
pdfPath.endsWith(".jpeg")
|
||||
) {
|
||||
// Legacy screenshot → convert to PDF
|
||||
try {
|
||||
pdfBuffer = await imageToPdfBuffer(pdfPath);
|
||||
pdfFilename = `metlife_eligibility_${insuranceId}_${Date.now()}.pdf`;
|
||||
log("metlife-processor", "converted screenshot to PDF", { pdfPath });
|
||||
} catch (e: any) {
|
||||
output.pdfUploadStatus = `Failed to convert screenshot to PDF: ${e.message}`;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
output.pdfUploadStatus = "No valid file path from Selenium; nothing uploaded.";
|
||||
}
|
||||
|
||||
// 6) Save PDF to patient document group
|
||||
if (pdfBuffer && pdfFilename) {
|
||||
const patientName = `${patient.firstName ?? ""} ${patient.lastName ?? ""}`.trim() || `Patient ${patient.id}`;
|
||||
const cloudFile = await storage.savePdfToCloudStorage(
|
||||
userId,
|
||||
patient.id,
|
||||
patientName,
|
||||
"Eligibility",
|
||||
pdfFilename,
|
||||
pdfBuffer
|
||||
);
|
||||
createdPdfFileId = `cloud:${cloudFile.id}`;
|
||||
output.pdfUploadStatus = "PDF saved to Eligibility folder";
|
||||
output.pdfFilename = pdfFilename;
|
||||
}
|
||||
|
||||
output.pdfFileId = createdPdfFileId;
|
||||
return output;
|
||||
} catch (err: any) {
|
||||
log("metlife-processor", `processMetLifeResult ERROR: ${err?.message ?? String(err)}`, err);
|
||||
return {
|
||||
...output,
|
||||
pdfUploadStatus:
|
||||
output.pdfUploadStatus ?? `Processing failed: ${err?.message ?? String(err)}`,
|
||||
pdfFileId: createdPdfFileId,
|
||||
};
|
||||
} finally {
|
||||
// Always clean up temp files
|
||||
const cleanupPath =
|
||||
seleniumResult?.pdf_path ?? seleniumResult?.ss_path ?? null;
|
||||
if (cleanupPath) {
|
||||
try {
|
||||
await emptyFolderContainingFile(cleanupPath);
|
||||
} catch (e) {
|
||||
log("metlife-processor", "cleanup failed", { cleanupPath });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Polling loop ────────────────────────────────────────────────────────────
|
||||
|
||||
async function pollUntilDone(
|
||||
sessionId: string,
|
||||
socketId: string | undefined,
|
||||
jobId: string,
|
||||
pollTimeoutMs = 5 * 60 * 1000 // 5 min total (includes OTP wait)
|
||||
): Promise<any> {
|
||||
const maxAttempts = 600; // 600 × 500ms = 5 min
|
||||
const pollIntervalMs = 500;
|
||||
const maxTransientErrors = 12;
|
||||
const noProgressLimit = 120; // 60 s of same status → abort
|
||||
|
||||
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(
|
||||
`MetLife polling timeout (${Math.round(pollTimeoutMs / 1000)}s) for session ${sessionId}`
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const st = await getSeleniumMetLifeSessionStatus(sessionId);
|
||||
const status: string = st?.status ?? "unknown";
|
||||
|
||||
log("metlife-processor", `poll attempt=${attempt}`, { sessionId, status });
|
||||
|
||||
transientErrors = 0; // reset on success
|
||||
|
||||
// Track no-progress
|
||||
const isTerminal =
|
||||
status === "completed" || status === "error" || status === "not_found";
|
||||
// waiting_for_otp legitimately sits unchanged while the user finds the code
|
||||
if (status === lastStatus && !isTerminal && status !== "waiting_for_otp") {
|
||||
consecutiveNoProgress++;
|
||||
} else {
|
||||
consecutiveNoProgress = 0;
|
||||
}
|
||||
lastStatus = status;
|
||||
|
||||
if (consecutiveNoProgress >= noProgressLimit) {
|
||||
throw new Error(
|
||||
`No progress from Python agent (status="${status}") after ${consecutiveNoProgress} polls`
|
||||
);
|
||||
}
|
||||
|
||||
// OTP required — notify frontend and keep polling
|
||||
if (status === "waiting_for_otp") {
|
||||
emitToSocket(socketId, "selenium:otp_required", {
|
||||
session_id: sessionId,
|
||||
jobId,
|
||||
message: "OTP required. Please enter the code sent by the MetLife portal.",
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, pollIntervalMs));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (status === "completed") {
|
||||
log("metlife-processor", "session completed", { sessionId });
|
||||
return st.result;
|
||||
}
|
||||
|
||||
if (status === "error" || status === "not_found") {
|
||||
throw new Error(
|
||||
st?.message || `MetLife session ended with status: ${status}`
|
||||
);
|
||||
}
|
||||
|
||||
// Still running / otp_submitted / created — keep polling
|
||||
await new Promise((r) => setTimeout(r, pollIntervalMs));
|
||||
} catch (err: any) {
|
||||
// Propagate terminal errors immediately
|
||||
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;
|
||||
|
||||
// Transient network errors — back off
|
||||
transientErrors++;
|
||||
if (transientErrors > maxTransientErrors) {
|
||||
throw new Error(
|
||||
`Too many transient network errors polling MetLife session ${sessionId}`
|
||||
);
|
||||
}
|
||||
const backoff = Math.min(30_000, 500 * Math.pow(2, transientErrors - 1));
|
||||
log("metlife-processor", `transient error #${transientErrors}, backoff ${backoff}ms`, {
|
||||
err: err?.message,
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, backoff));
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`MetLife polling exhausted all attempts for session ${sessionId}`);
|
||||
}
|
||||
|
||||
// ─── Main processor entry point ───────────────────────────────────────────────
|
||||
|
||||
export async function runMetLifeEligibilityProcessor(
|
||||
input: MetLifeEligibilityProcessorInput,
|
||||
jobId: string
|
||||
): Promise<MetLifeEligibilityProcessorResult> {
|
||||
const {
|
||||
enrichedPayload,
|
||||
userId,
|
||||
insuranceId,
|
||||
formFirstName,
|
||||
formLastName,
|
||||
formDob,
|
||||
socketId,
|
||||
} = input;
|
||||
|
||||
// 1) Tell Python agent to start a MetLife session
|
||||
log("metlife-processor", "starting Python agent session", { insuranceId });
|
||||
const agentResp = await forwardToSeleniumMetLifeEligibilityAgent(enrichedPayload);
|
||||
|
||||
if (!agentResp?.session_id) {
|
||||
throw new Error(
|
||||
"Python agent did not return a session_id for MetLife eligibility"
|
||||
);
|
||||
}
|
||||
|
||||
const sessionId = agentResp.session_id as string;
|
||||
log("metlife-processor", "got session_id", { sessionId });
|
||||
|
||||
// 2) Emit session started so frontend can store session_id for OTP submission
|
||||
emitToSocket(socketId, "selenium:metlife_session_started", {
|
||||
session_id: sessionId,
|
||||
jobId,
|
||||
});
|
||||
|
||||
// 3) Poll until done (handles OTP events internally)
|
||||
const seleniumResult = await pollUntilDone(sessionId, socketId, jobId);
|
||||
|
||||
if (!seleniumResult || seleniumResult.status === "error") {
|
||||
throw new Error(
|
||||
seleniumResult?.message ?? "MetLife session returned an error result"
|
||||
);
|
||||
}
|
||||
|
||||
// 4) Process DB writes and PDF upload
|
||||
log("metlife-processor", "processing DB result", { insuranceId });
|
||||
const result = await processMetLifeResult(
|
||||
userId,
|
||||
insuranceId,
|
||||
formFirstName,
|
||||
formLastName,
|
||||
formDob,
|
||||
seleniumResult
|
||||
);
|
||||
|
||||
log("metlife-processor", "done", { result });
|
||||
return result;
|
||||
}
|
||||
Reference in New Issue
Block a user