feat: add United Ucard claim worker and fix batch-column site-key routing
Adds a "United Ucard Claim" button (claims/preauth insurance form) that submits through a full Selenium pipeline mirroring the Tufts SCO claim worker: frontend handler -> backend route/queue processor -> Python agent, reusing the persistent login/OTP session from the existing United Ucard eligibility check. Implements the UHC Dental claim wizard end-to-end (Provider Information, Patient Information search/select, Claim Information procedures + questions, Upload Documents, Review and Sign, Submit); the final confirmation-page PDF/claim-number capture is still a TODO stub pending that page's DOM. Also wires United Ucard into the AI chatbot's eligibility flow (insuranceAliases.json, siteKeyToAutoCheck, clarification options), and fixes a bug where the AI-column batch claim feature silently defaulted United Ucard patients to MassHealth because batchColumnDeriveSiteKey had no matching branch and no job-dispatch case for UNITED_UCARD. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -24,6 +24,7 @@ import { runUnitedDHClaimProcessor } from "./processors/unitedDHClaimProcessor";
|
||||
import { runUnitedDHPreAuthProcessor } from "./processors/unitedDHPreAuthProcessor";
|
||||
import { runTuftsSCOPreAuthProcessor } from "./processors/tuftsSCOPreAuthProcessor";
|
||||
import { runTuftsSCOClaimProcessor } from "./processors/tuftsSCOClaimProcessor";
|
||||
import { runUnitedUcardClaimProcessor } from "./processors/unitedUcardClaimProcessor";
|
||||
import { runEligibilityHistoryProcessor } from "./processors/eligibilityHistoryProcessor";
|
||||
import { runCmspEligibilityHistoryRemainingProcessor } from "./processors/cmspEligibilityHistoryRemainingProcessor";
|
||||
import { runBcbsMaEligibilityProcessor } from "./processors/bcbsMaEligibilityProcessor";
|
||||
@@ -234,6 +235,17 @@ export function enqueueSeleniumJob(data: SeleniumJobData): string {
|
||||
job.id
|
||||
);
|
||||
}
|
||||
if (jobType === "uniteducard-claim-submit") {
|
||||
return runUnitedUcardClaimProcessor(
|
||||
{
|
||||
enrichedPayload: data.enrichedPayload,
|
||||
userId: data.userId,
|
||||
claimId: data.claimId,
|
||||
socketId: data.socketId,
|
||||
},
|
||||
job.id
|
||||
);
|
||||
}
|
||||
if (jobType === "cca-eligibility-check") {
|
||||
return runCCAEligibilityProcessor(
|
||||
{
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* Processor for "uniteducard-claim-submit" jobs.
|
||||
* Opens a claim on the United Ucard (UHC Dental) provider portal via Selenium.
|
||||
*
|
||||
* Flow:
|
||||
* 1. POST /uniteducard-claim to Python agent → get session_id
|
||||
* 2. Emit selenium:uniteducard_claim_started to frontend
|
||||
* 3. Poll until completed/error
|
||||
* 4. Emit result
|
||||
*/
|
||||
import {
|
||||
forwardToSeleniumUnitedUcardClaimAgent,
|
||||
getSeleniumUnitedUcardClaimSessionStatus,
|
||||
} from "../../services/seleniumUnitedUcardClaimClient";
|
||||
import { io } from "../../socket";
|
||||
import { storage } from "../../storage";
|
||||
import axios from "axios";
|
||||
import path from "path";
|
||||
|
||||
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 (_) {}
|
||||
}
|
||||
|
||||
async function pollUntilDone(
|
||||
sessionId: string,
|
||||
socketId: string | undefined,
|
||||
jobId: string,
|
||||
pollTimeoutMs = 10 * 60 * 1000
|
||||
): Promise<any> {
|
||||
const maxAttempts = 1200;
|
||||
const pollIntervalMs = 500;
|
||||
const maxTransientErrors = 12;
|
||||
let transientErrors = 0;
|
||||
let lastOtpEmit = 0;
|
||||
const deadline = Date.now() + pollTimeoutMs;
|
||||
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
if (Date.now() > deadline) {
|
||||
throw new Error(`United Ucard claim polling timeout for session ${sessionId}`);
|
||||
}
|
||||
try {
|
||||
const st = await getSeleniumUnitedUcardClaimSessionStatus(sessionId);
|
||||
const status: string = st?.status ?? "unknown";
|
||||
log("uniteducard-claim-processor", `poll attempt=${attempt}`, { sessionId, status });
|
||||
transientErrors = 0;
|
||||
|
||||
if (status === "waiting_for_otp") {
|
||||
if (Date.now() - lastOtpEmit > 5000) {
|
||||
emitToSocket(socketId, "selenium:otp_required", {
|
||||
session_id: sessionId,
|
||||
jobId,
|
||||
message: "OTP required. Please enter the OTP shown by the United Ucard portal.",
|
||||
});
|
||||
lastOtpEmit = Date.now();
|
||||
}
|
||||
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 || `United Ucard claim 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")));
|
||||
if (isTerminal) throw err;
|
||||
transientErrors++;
|
||||
if (transientErrors > maxTransientErrors) {
|
||||
throw new Error(`Too many transient errors polling United Ucard claim session ${sessionId}`);
|
||||
}
|
||||
const backoff = Math.min(30_000, 500 * Math.pow(2, transientErrors - 1));
|
||||
await new Promise((r) => setTimeout(r, backoff));
|
||||
}
|
||||
}
|
||||
throw new Error(`United Ucard claim polling exhausted all attempts for session ${sessionId}`);
|
||||
}
|
||||
|
||||
async function savePdfFromSelenium(pdf_url: string, patientId: number, userId: number) {
|
||||
try {
|
||||
const filename = path.basename(new URL(pdf_url).pathname);
|
||||
const seleniumPort = process.env.SELENIUM_PORT || "5002";
|
||||
const localUrl = `http://localhost:${seleniumPort}/downloads/${filename}`;
|
||||
const resp = await axios.get(localUrl, { responseType: "arraybuffer", timeout: 30000 });
|
||||
const patient = await storage.getPatient(patientId);
|
||||
const patientName = patient ? `${patient.firstName ?? ""} ${patient.lastName ?? ""}`.trim() : "";
|
||||
await storage.savePdfToCloudStorage(
|
||||
userId,
|
||||
patientId,
|
||||
patientName || `Patient ${patientId}`,
|
||||
"Claims",
|
||||
filename,
|
||||
Buffer.from(resp.data)
|
||||
);
|
||||
log("uniteducard-claim-processor", "PDF saved", { patientId, filename });
|
||||
} catch (err: any) {
|
||||
log("uniteducard-claim-processor", "failed to save PDF (non-fatal)", { error: err?.message ?? err });
|
||||
}
|
||||
}
|
||||
|
||||
export interface UnitedUcardClaimProcessorInput {
|
||||
enrichedPayload: any;
|
||||
userId: number;
|
||||
claimId?: number;
|
||||
socketId?: string;
|
||||
}
|
||||
|
||||
export async function runUnitedUcardClaimProcessor(
|
||||
input: UnitedUcardClaimProcessorInput,
|
||||
jobId: string
|
||||
): Promise<{ status: string; pdf_url?: string; claimNumber?: string }> {
|
||||
const { enrichedPayload, userId, claimId, socketId } = input;
|
||||
|
||||
log("uniteducard-claim-processor", "starting Python agent session", { claimId });
|
||||
const agentResp = await forwardToSeleniumUnitedUcardClaimAgent(enrichedPayload);
|
||||
|
||||
if (!agentResp?.session_id) {
|
||||
throw new Error("Python agent did not return a session_id for United Ucard claim");
|
||||
}
|
||||
|
||||
const sessionId = agentResp.session_id as string;
|
||||
log("uniteducard-claim-processor", "got session_id", { sessionId });
|
||||
|
||||
emitToSocket(socketId, "selenium:uniteducard_claim_started", { session_id: sessionId, jobId });
|
||||
|
||||
const seleniumResult = await pollUntilDone(sessionId, socketId, jobId);
|
||||
|
||||
if (!seleniumResult || seleniumResult.status === "error") {
|
||||
throw new Error(seleniumResult?.message ?? "United Ucard claim session returned an error");
|
||||
}
|
||||
|
||||
const claimNumber: string | undefined = seleniumResult.claimNumber ?? undefined;
|
||||
const pdf_url: string | undefined = seleniumResult.pdf_url ?? undefined;
|
||||
|
||||
if (claimId) {
|
||||
try {
|
||||
const updates: Record<string, any> = { status: "REVIEW" };
|
||||
if (claimNumber) updates.claimNumber = claimNumber;
|
||||
await storage.updateClaim(claimId, updates);
|
||||
log("uniteducard-claim-processor", "claim record updated", { claimId, claimNumber });
|
||||
} catch (e) {
|
||||
log("uniteducard-claim-processor", "failed to update claim record (non-fatal)", { error: e });
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-save PDF for batch-column calls (no socketId = no frontend listener)
|
||||
if (pdf_url && !socketId) {
|
||||
const claim = claimId ? await storage.getClaim(claimId).catch(() => null) : null;
|
||||
const patientId = claim?.patientId ?? enrichedPayload?.claim?.patientId ?? enrichedPayload?.patientId;
|
||||
if (patientId) await savePdfFromSelenium(pdf_url, Number(patientId), userId);
|
||||
}
|
||||
|
||||
emitToSocket(socketId, "selenium:uniteducard_claim_completed", {
|
||||
jobId,
|
||||
claimId,
|
||||
claimNumber,
|
||||
pdf_url,
|
||||
message: claimNumber
|
||||
? `United Ucard claim submitted — Claim #: ${claimNumber}`
|
||||
: (seleniumResult?.message ?? "United Ucard claim submitted successfully"),
|
||||
});
|
||||
|
||||
log("uniteducard-claim-processor", "done", { claimId, claimNumber });
|
||||
return { status: "success", pdf_url, claimNumber };
|
||||
}
|
||||
@@ -16,6 +16,7 @@ export type SeleniumJobType =
|
||||
| "cca-preauth-submit"
|
||||
| "ddma-claim-submit"
|
||||
| "tuftssco-claim-submit"
|
||||
| "uniteducard-claim-submit"
|
||||
| "uniteddh-claim-submit"
|
||||
| "uniteddh-preauth-submit"
|
||||
| "tuftssco-preauth-submit"
|
||||
|
||||
Reference in New Issue
Block a user