Compare commits

...

7 Commits

Author SHA1 Message Date
Gitead
37a0568b5e fix: MH claim submit — wait for socket job:update before fetching PDF and claim number 2026-04-18 09:53:41 -04:00
Gitead
5d1275d628 fix: UnitedSCO status always inactive and missing patient name 2026-04-18 09:25:02 -04:00
Gitead
c8cb649e25 fix: CCA login — proper portal detection, robust field entry, input diagnostics 2026-04-18 09:15:13 -04:00
Gitead
4505d5db85 feat: DentaQuest eligibility — PLAN_NOT_ACCEPTED status, DOB save, no retries
- Add PLAN_NOT_ACCEPTED to PatientStatus enum (prisma schema + db push)
- Selenium: return "plan not accepted" eligibility text instead of collapsing to inactive
- Backend processor: map "plan not accepted" → PLAN_NOT_ACCEPTED, fix insuranceProvider label
- _shared.ts: save DOB for existing patients when field is currently empty
- Frontend: show amber "Plan Not Accepted" badge in patient table and detail panel
- patient-form.tsx: display "Plan Not Accepted" label in status dropdown
- BullMQ: set attempts=1 (no retry on selenium failure)
- DDMA: remove first/last name from search (member ID + DOB only)
- patient-types.ts: allow alphanumeric insurance IDs

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-17 23:47:50 -04:00
Gitead
f5ec4a1480 feat: wire Tufts SCO to DentaQuest portal and fix insurance credential dropdown
- Add /dentaquest-eligibility endpoint in Python agent (Tufts SCO uses providers.dentaquest.com)
- Add backend route, processor, and service client for Tufts SCO (separate from UnitedSCO/DentalHub)
- Fix Tufts SCO button to post to new tuftssco route instead of unitedsco
- Fix credential field names: dentaquestUsername/Password (was tuftsscoUsername/Password)
- Fix socket event: listen for selenium:dentaquest_session_started (was unitedsco)
- Fix error visibility: keep session alive 30s on error so backend reads real message
- Replace free-text Site Key field with dropdown to prevent key mismatches

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-17 00:59:24 -04:00
Gitead
b6700eceee fix: revert Deltains button label 2026-04-17 00:14:46 -04:00
Gitead
a222e22014 feat: reorganize eligibility buttons and update labels 2026-04-16 23:48:02 -04:00
25 changed files with 1032 additions and 263 deletions

View File

@@ -4,7 +4,7 @@
"description": "",
"main": "index.js",
"scripts": {
"dev": "ts-node-dev --respawn --transpile-only src/index.ts",
"dev": "ts-node-dev --respawn --transpile-only --watch ../../packages/db/types src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
},

View File

@@ -14,6 +14,7 @@ import { runOcrProcessor } from "./processors/ocrProcessor";
import { runDdmaEligibilityProcessor } from "./processors/ddmaEligibilityProcessor";
import { runDeltaInsEligibilityProcessor } from "./processors/deltaInsEligibilityProcessor";
import { runUnitedSCOEligibilityProcessor } from "./processors/unitedSCOEligibilityProcessor";
import { runDentaQuestEligibilityProcessor } from "./processors/dentaQuestEligibilityProcessor";
import { runCCAEligibilityProcessor } from "./processors/ccaEligibilityProcessor";
import type { SeleniumJobData, OcrJobData } from "./queues";
@@ -114,6 +115,20 @@ export function enqueueSeleniumJob(data: SeleniumJobData): string {
job.id
);
}
if (jobType === "tuftssco-eligibility-check") {
return runDentaQuestEligibilityProcessor(
{
enrichedPayload: data.enrichedPayload,
userId: data.userId,
insuranceId: data.insuranceId!,
formFirstName: data.formFirstName,
formLastName: data.formLastName,
formDob: data.formDob,
socketId: data.socketId,
},
job.id
);
}
if (jobType === "cca-eligibility-check") {
return runCCAEligibilityProcessor(
{

View File

@@ -105,6 +105,10 @@ export async function createOrUpdatePatientByInsuranceId(options: {
updates.firstName = incomingFirst;
if (incomingLast && String(patient.lastName ?? "").trim() !== incomingLast)
updates.lastName = incomingLast;
if (dob && !patient.dateOfBirth) {
const parsed = new Date(dob);
if (!isNaN(parsed.getTime())) updates.dateOfBirth = parsed;
}
if (Object.keys(updates).length > 0) {
await storage.updatePatient(patient.id, updates);
patient = await storage.getPatientByInsuranceId(insuranceId);
@@ -126,9 +130,15 @@ export async function createOrUpdatePatientByInsuranceId(options: {
try {
patientData = insertPatientSchema.parse(createPayload);
} catch {
// Remove fields that may fail validation (invalid date or alphanumeric insuranceId)
const safePayload = { ...createPayload };
delete safePayload.dateOfBirth;
patientData = insertPatientSchema.parse(safePayload);
try {
patientData = insertPatientSchema.parse(safePayload);
} catch {
// Last resort: skip schema validation and cast directly
patientData = safePayload as InsertPatient;
}
}
await storage.createPatient(patientData);

View File

@@ -0,0 +1,312 @@
import fs from "fs/promises";
import fsSync from "fs";
import path from "path";
import { storage } from "../../storage";
import { emptyFolderContainingFile } from "../../utils/emptyTempFolder";
import {
forwardToSeleniumDentaQuestEligibilityAgent,
getSeleniumDentaQuestSessionStatus,
} from "../../services/seleniumDentaQuestEligibilityClient";
import { splitName, createOrUpdatePatientByInsuranceId, imageToPdfBuffer } from "./_shared";
import { io } from "../../socket";
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("dentaquest-processor", `emitted ${event}`, { socketId });
}
} catch (err: any) {
log("dentaquest-processor", `emit failed for ${event}`, { err: err?.message });
}
}
export interface DentaQuestEligibilityProcessorInput {
enrichedPayload: any;
userId: number;
insuranceId: string;
formFirstName?: string;
formLastName?: string;
formDob?: string;
socketId?: string;
}
export interface DentaQuestEligibilityProcessorResult {
patientUpdateStatus?: string;
pdfUploadStatus?: string;
pdfFileId?: number | null;
pdfFilename?: string | null;
}
async function processDentaQuestResult(
userId: number,
insuranceId: string,
formFirstName: string | undefined,
formLastName: string | undefined,
formDob: string | undefined,
seleniumResult: any
): Promise<DentaQuestEligibilityProcessorResult> {
const output: DentaQuestEligibilityProcessorResult = {};
let createdPdfFileId: number | null = null;
try {
const rawName =
typeof seleniumResult?.patientName === "string"
? seleniumResult.patientName.trim()
: null;
const { firstName, lastName } = rawName
? splitName(rawName)
: { firstName: formFirstName ?? "", lastName: formLastName ?? "" };
await createOrUpdatePatientByInsuranceId({
insuranceId,
firstName,
lastName,
dob: formDob,
userId,
});
const patient = await storage.getPatientByInsuranceId(insuranceId);
if (!patient?.id) {
output.patientUpdateStatus = "Patient not found; no update performed";
return output;
}
const eligStatus = (seleniumResult?.eligibility ?? "").toLowerCase();
const newStatus =
eligStatus === "active" || eligStatus === "y"
? "ACTIVE"
: eligStatus.includes("plan not accepted") || eligStatus.includes("plan_not_accepted")
? "PLAN_NOT_ACCEPTED"
: "INACTIVE";
await storage.updatePatient(patient.id, {
status: newStatus,
insuranceProvider: "DentaQuest",
});
output.patientUpdateStatus = `Patient status updated to ${newStatus}`;
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")) {
try {
pdfBuffer = await fs.readFile(pdfPath);
pdfFilename = path.basename(pdfPath);
log("dentaquest-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")
) {
try {
pdfBuffer = await imageToPdfBuffer(pdfPath);
pdfFilename = `dentaquest_eligibility_${insuranceId}_${Date.now()}.pdf`;
log("dentaquest-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.";
}
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) {
return {
...output,
pdfUploadStatus:
output.pdfUploadStatus ?? `Processing failed: ${err?.message ?? String(err)}`,
pdfFileId: createdPdfFileId,
};
} finally {
const cleanupPath = seleniumResult?.pdf_path ?? seleniumResult?.ss_path ?? null;
if (cleanupPath) {
try {
await emptyFolderContainingFile(cleanupPath);
} catch (e) {
log("dentaquest-processor", "cleanup failed", { cleanupPath });
}
}
}
}
async function pollUntilDone(
sessionId: string,
socketId: string | undefined,
jobId: string,
pollTimeoutMs = 5 * 60 * 1000
): Promise<any> {
const maxAttempts = 600;
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(
`DentaQuest polling timeout (${Math.round(pollTimeoutMs / 1000)}s) for session ${sessionId}`
);
}
try {
const st = await getSeleniumDentaQuestSessionStatus(sessionId);
const status: string = st?.status ?? "unknown";
log("dentaquest-processor", `poll attempt=${attempt}`, { sessionId, status });
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 verification code.",
});
await new Promise((r) => setTimeout(r, pollIntervalMs));
continue;
}
if (status === "completed") {
log("dentaquest-processor", "session completed", { sessionId });
return st.result;
}
if (status === "error" || status === "not_found") {
const terminalErr: any = new Error(st?.message || `DentaQuest session ended with status: ${status}`);
terminalErr.terminal = true;
throw terminalErr;
}
await new Promise((r) => setTimeout(r, pollIntervalMs));
} catch (err: any) {
const isTerminal =
err?.terminal === true ||
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 DentaQuest session ${sessionId}`
);
}
const backoff = Math.min(30_000, 500 * Math.pow(2, transientErrors - 1));
log("dentaquest-processor", `transient error #${transientErrors}, backoff ${backoff}ms`, {
err: err?.message,
});
await new Promise((r) => setTimeout(r, backoff));
}
}
throw new Error(`DentaQuest polling exhausted all attempts for session ${sessionId}`);
}
export async function runDentaQuestEligibilityProcessor(
input: DentaQuestEligibilityProcessorInput,
jobId: string
): Promise<DentaQuestEligibilityProcessorResult> {
const {
enrichedPayload,
userId,
insuranceId,
formFirstName,
formLastName,
formDob,
socketId,
} = input;
log("dentaquest-processor", "starting Python agent session", { insuranceId });
const agentResp = await forwardToSeleniumDentaQuestEligibilityAgent(enrichedPayload);
if (!agentResp?.session_id) {
throw new Error("Python agent did not return a session_id for DentaQuest eligibility");
}
const sessionId = agentResp.session_id as string;
log("dentaquest-processor", "got session_id", { sessionId });
emitToSocket(socketId, "selenium:dentaquest_session_started", {
session_id: sessionId,
jobId,
});
const seleniumResult = await pollUntilDone(sessionId, socketId, jobId);
if (!seleniumResult || seleniumResult.status === "error") {
throw new Error(seleniumResult?.message ?? "DentaQuest session returned an error result");
}
log("dentaquest-processor", "processing DB result", { insuranceId });
const result = await processDentaQuestResult(
userId,
insuranceId,
formFirstName,
formLastName,
formDob,
seleniumResult
);
log("dentaquest-processor", "done", { result });
return result;
}

View File

@@ -37,7 +37,7 @@ export interface OcrJobData {
const defaultOpts = {
removeOnComplete: { count: 100 },
removeOnFail: { count: 50 },
attempts: 2,
attempts: 1,
backoff: { type: "exponential" as const, delay: 5000 },
};

View File

@@ -14,6 +14,7 @@ import insuranceStatusRoutes from "./insuranceStatus";
import insuranceStatusDdmaRoutes from "./insuranceStatusDDMA";
import insuranceStatusDeltaInsRoutes from "./insuranceStatusDeltaIns";
import insuranceStatusUnitedSCORoutes from "./insuranceStatusUnitedSCO";
import insuranceStatusTuftsSCORoutes from "./insuranceStatusTuftsSCO";
import insuranceStatusCCARoutes from "./insuranceStatusCCA";
import paymentsRoutes from "./payments";
import databaseManagementRoutes from "./database-management";
@@ -41,6 +42,7 @@ router.use("/insurance-status", insuranceStatusRoutes);
router.use("/insurance-status-ddma", insuranceStatusDdmaRoutes);
router.use("/insurance-status-deltains", insuranceStatusDeltaInsRoutes);
router.use("/insurance-status-unitedsco", insuranceStatusUnitedSCORoutes);
router.use("/insurance-status-tuftssco", insuranceStatusTuftsSCORoutes);
router.use("/insurance-status-cca", insuranceStatusCCARoutes);
router.use("/payments", paymentsRoutes);
router.use("/database-management", databaseManagementRoutes);

View File

@@ -0,0 +1,108 @@
import { Router, Request, Response } from "express";
import { storage } from "../storage";
import { forwardOtpToSeleniumDentaQuestAgent } from "../services/seleniumDentaQuestEligibilityClient";
import { io } from "../socket";
import { enqueueSeleniumJob } from "../queue/jobRunner";
const router = Router();
function log(tag: string, msg: string, ctx?: any) {
console.log(`${new Date().toISOString()} [${tag}] ${msg}`, ctx ?? "");
}
function emitSafe(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("socket", "emit failed", { socketId, event, err: err?.message });
}
}
router.post(
"/tuftssco-eligibility",
async (req: Request, res: Response): Promise<any> => {
if (!req.body.data) {
return res.status(400).json({ error: "Missing eligibility data for selenium" });
}
if (!req.user?.id) {
return res.status(401).json({ error: "Unauthorized: user info missing" });
}
try {
const rawData =
typeof req.body.data === "string" ? JSON.parse(req.body.data) : req.body.data;
const credentials = await storage.getInsuranceCredentialByUserAndSiteKey(
req.user.id,
rawData.insuranceSiteKey
);
if (!credentials) {
return res.status(404).json({
error: "No credentials found for Tufts SCO. Please add them on the Settings page.",
});
}
const enrichedData = {
...rawData,
dentaquestUsername: credentials.username,
dentaquestPassword: credentials.password,
};
const socketId: string | undefined = req.body.socketId;
const jobId = enqueueSeleniumJob({
jobType: "tuftssco-eligibility-check",
userId: req.user.id,
socketId,
enrichedPayload: enrichedData,
insuranceId: String(rawData.memberId ?? "").trim(),
formFirstName: rawData.firstName,
formLastName: rawData.lastName,
formDob: rawData.dateOfBirth,
});
log("tuftssco-route", "job enqueued", { jobId, insuranceId: rawData.memberId });
return res.json({ status: "queued", jobId });
} catch (err: any) {
console.error("[tuftssco-route] enqueue failed:", err);
return res.status(500).json({
error: err.message || "Failed to enqueue Tufts SCO selenium job",
});
}
}
);
router.post(
"/selenium/submit-otp",
async (req: Request, res: Response): Promise<any> => {
const { session_id: sessionId, otp, socketId } = req.body;
if (!sessionId || !otp) {
return res.status(400).json({ error: "session_id and otp are required" });
}
try {
const r = await forwardOtpToSeleniumDentaQuestAgent(sessionId, otp);
emitSafe(socketId, "selenium:otp_submitted", {
session_id: sessionId,
result: r,
});
return res.json(r);
} catch (err: any) {
console.error(
"[tuftssco-route] submit-otp failed:",
err?.response?.data || err?.message || err
);
return res.status(500).json({
error: "Failed to forward OTP to selenium agent",
detail: err?.message || err,
});
}
}
);
export default router;

View File

@@ -0,0 +1,72 @@
import axios from "axios";
import http from "http";
import https from "https";
import dotenv from "dotenv";
dotenv.config();
const SELENIUM_AGENT_BASE = process.env.SELENIUM_AGENT_BASE_URL;
const httpAgent = new http.Agent({ keepAlive: true, keepAliveMsecs: 60_000 });
const httpsAgent = new https.Agent({ keepAlive: true, keepAliveMsecs: 60_000 });
const client = axios.create({
baseURL: SELENIUM_AGENT_BASE,
timeout: 5 * 60 * 1000,
httpAgent,
httpsAgent,
validateStatus: (s) => s >= 200 && s < 600,
});
async function requestWithRetries(config: any, retries = 4, baseBackoffMs = 300) {
for (let attempt = 1; attempt <= retries; attempt++) {
try {
const r = await client.request(config);
if (![502, 503, 504].includes(r.status)) return r;
console.warn(`[dentaquest-client] retryable HTTP status ${r.status} (attempt ${attempt})`);
} catch (err: any) {
const code = err?.code;
const isTransient =
code === "ECONNRESET" || code === "ECONNREFUSED" || code === "EPIPE" || code === "ETIMEDOUT";
if (!isTransient) throw err;
console.warn(`[dentaquest-client] transient network error ${code} (attempt ${attempt})`);
}
await new Promise((r) => setTimeout(r, baseBackoffMs * attempt));
}
return client.request(config);
}
function log(tag: string, msg: string, ctx?: any) {
console.log(`${new Date().toISOString()} [${tag}] ${msg}`, ctx ?? "");
}
export async function forwardToSeleniumDentaQuestEligibilityAgent(data: any): Promise<any> {
const payload = { data };
const url = `/dentaquest-eligibility`;
log("dentaquest-client", "POST dentaquest-eligibility", { url: SELENIUM_AGENT_BASE + url });
const r = await requestWithRetries({ url, method: "POST", data: payload }, 4);
log("dentaquest-client", "agent response", { status: r.status, dataKeys: r.data ? Object.keys(r.data) : null });
if (r.status >= 500) throw new Error(`Selenium agent server error: ${r.status}`);
return r.data;
}
export async function forwardOtpToSeleniumDentaQuestAgent(sessionId: string, otp: string): Promise<any> {
const url = `/submit-otp`;
log("dentaquest-client", "POST submit-otp", { url: SELENIUM_AGENT_BASE + url, sessionId });
const r = await requestWithRetries({ url, method: "POST", data: { session_id: sessionId, otp } }, 4);
log("dentaquest-client", "submit-otp response", { status: r.status, data: r.data });
if (r.status >= 500) throw new Error(`Selenium agent server error on submit-otp: ${r.status}`);
return r.data;
}
export async function getSeleniumDentaQuestSessionStatus(sessionId: string): Promise<any> {
const url = `/session/${sessionId}/status`;
log("dentaquest-client", "GET session status", { url: SELENIUM_AGENT_BASE + url, sessionId });
const r = await requestWithRetries({ url, method: "GET" }, 4);
log("dentaquest-client", "session status response", { status: r.status, dataKeys: r.data ? Object.keys(r.data) : null });
if (r.status === 404) {
const e: any = new Error("not_found");
e.response = { status: 404, data: r.data };
throw e;
}
return r.data;
}

View File

@@ -48,8 +48,10 @@ function getVisuals(status: PatientStatus): { label: string; bg: string } {
case "ACTIVE":
return { label: "Active", bg: "#16A34A" }; // MEDICAL GREEN (not same as staff green)
case "INACTIVE":
return { label: "Inactive", bg: "#DC2626" }; // ALERT RED (distinct from card red)
return { label: "Inactive", bg: "#DC2626" };
case "PLAN_NOT_ACCEPTED":
return { label: "Plan Not Accepted", bg: "#F59E0B" }; // amber
default:
return { label: "Unknown", bg: "#6B7280" }; // solid gray
return { label: "Unknown", bg: "#6B7280" };
}
}

View File

@@ -337,7 +337,7 @@ export function DeltaInsEligibilityButton({
) : (
<>
<CheckCircle className="h-4 w-4 mr-2" />
Delta Ins Eligibility
Deltains
</>
)}
</Button>

View File

@@ -139,7 +139,7 @@ export function TuftsSCOEligibilityButton({
const response = await apiRequest(
"POST",
"/api/insurance-status-unitedsco/unitedsco-eligibility",
"/api/insurance-status-tuftssco/tuftssco-eligibility",
{ data: JSON.stringify(payload), socketId: socket.id }
);
@@ -195,13 +195,13 @@ export function TuftsSCOEligibilityButton({
);
};
socket.on("selenium:unitedsco_session_started", onSessionStarted);
socket.on("selenium:dentaquest_session_started", onSessionStarted);
socket.on("selenium:otp_required", onOtpRequired);
socket.on("selenium:otp_submitted", onOtpSubmitted);
function cleanup() {
clearTimeout(safetyTimer);
socket.off("selenium:unitedsco_session_started", onSessionStarted);
socket.off("selenium:dentaquest_session_started", onSessionStarted);
socket.off("selenium:otp_required", onOtpRequired);
socket.off("selenium:otp_submitted", onOtpSubmitted);
socket.off("job:update", onJobUpdate);
@@ -296,7 +296,7 @@ export function TuftsSCOEligibilityButton({
try {
setIsSubmittingOtp(true);
const resp = await apiRequest("POST", "/api/insurance-status-unitedsco/selenium/submit-otp", {
const resp = await apiRequest("POST", "/api/insurance-status-tuftssco/selenium/submit-otp", {
session_id: sessionId,
otp,
socketId: socket.id,

View File

@@ -303,8 +303,10 @@ export const PatientForm = forwardRef<PatientFormRef, PatientFormProps>(
const options = Object.values(
patientStatusOptions,
) as PatientStatus[]; // ['ACTIVE','INACTIVE','UNKNOWN']
const toLabel = (v: PatientStatus) =>
v[0] + v.slice(1).toLowerCase(); // ACTIVE -> Active
const toLabel = (v: PatientStatus) => {
if (v === "PLAN_NOT_ACCEPTED") return "Plan Not Accepted";
return v[0] + v.slice(1).toLowerCase();
};
return (
<FormItem>

View File

@@ -1071,6 +1071,12 @@ export function PatientTable({
Unknown
</span>
)}
{patient.status === "PLAN_NOT_ACCEPTED" && (
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-800">
Plan Not Accepted
</span>
)}
</div>
</TableCell>
@@ -1201,14 +1207,18 @@ export function PatientTable({
? "text-green-600"
: currentPatient.status === "INACTIVE"
? "text-red-600"
: "text-gray-600", // UNKNOWN or fallback
: currentPatient.status === "PLAN_NOT_ACCEPTED"
? "text-amber-600"
: "text-gray-600",
"font-medium"
)}
>
{currentPatient.status
? currentPatient.status.charAt(0).toUpperCase() +
currentPatient.status.slice(1).toLowerCase()
: "Unknown"}
{currentPatient.status === "PLAN_NOT_ACCEPTED"
? "Plan Not Accepted"
: currentPatient.status
? currentPatient.status.charAt(0).toUpperCase() +
currentPatient.status.slice(1).toLowerCase()
: "Unknown"}
</span>
</p>
</div>

View File

@@ -15,6 +15,15 @@ type CredentialFormProps = {
};
};
const SITE_KEY_OPTIONS = [
{ value: "MH", label: "MassHealth (MH)" },
{ value: "DDMA", label: "Delta Dental MA (DDMA)" },
{ value: "DELTAINS", label: "Delta Dental Ins (DELTAINS)" },
{ value: "TUFTS_SCO", label: "Tufts SCO (TUFTS_SCO)" },
{ value: "UNITED_SCO", label: "United SCO (UNITED_SCO)" },
{ value: "CCA", label: "CCA (CCA)" },
];
export function CredentialForm({ onClose, userId, defaultValues }: CredentialFormProps) {
const [siteKey, setSiteKey] = useState(defaultValues?.siteKey || "");
const [username, setUsername] = useState(defaultValues?.username || "");
@@ -93,14 +102,19 @@ export function CredentialForm({ onClose, userId, defaultValues }: CredentialFor
</h2>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium">Site Key</label>
<input
type="text"
<label className="block text-sm font-medium">Insurance</label>
<select
value={siteKey}
onChange={(e) => setSiteKey(e.target.value)}
className="mt-1 p-2 border rounded w-full"
placeholder="e.g., MH, Delta MA, (keep the site key exact same)"
/>
className="mt-1 p-2 border rounded w-full bg-white"
>
<option value=""> Select insurance </option>
{SITE_KEY_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium">Username</label>

View File

@@ -1,4 +1,4 @@
import { useState, useEffect, useMemo } from "react";
import { useState, useEffect, useMemo, useRef } from "react";
import { useMutation } from "@tanstack/react-query";
import {
Card,
@@ -18,6 +18,7 @@ import {
clearTaskStatus,
} from "@/redux/slices/seleniumTaskSlice";
import { SeleniumTaskBanner } from "@/components/ui/selenium-task-banner";
import { useJobStatus } from "@/hooks/use-job-status";
import ClaimsRecentTable, {
QK_CLAIMS_BASE,
} from "@/components/claims/claims-recent-table";
@@ -49,6 +50,14 @@ export default function ClaimsPage() {
const { status, message, show } = useAppSelector(
(state) => state.seleniumTasks.claimSubmit
);
// Track pending selenium jobs so we can react to completion via socket
const [pendingClaimJobId, setPendingClaimJobId] = useState<string | null>(null);
const pendingClaimMeta = useRef<{
patientId: number | null;
groupKey: "INSURANCE_CLAIM" | "INSURANCE_CLAIM_PREAUTH";
}>({ patientId: null, groupKey: "INSURANCE_CLAIM" });
const { status: jobStatus, result: jobResult } = useJobStatus(pendingClaimJobId);
const { toast } = useToast();
const { user } = useAuth();
@@ -130,6 +139,24 @@ export default function ClaimsPage() {
},
});
// React to selenium job completing via socket
useEffect(() => {
if (!pendingClaimJobId) return;
if (jobStatus === "completed" && jobResult) {
setPendingClaimJobId(null);
handleMHSeleniumPdfDownload(
jobResult,
pendingClaimMeta.current.patientId,
pendingClaimMeta.current.groupKey
);
queryClient.invalidateQueries({ queryKey: ["claims-recent"] });
} else if (jobStatus === "failed") {
setPendingClaimJobId(null);
dispatch(setTaskStatus({ key: "claimSubmit", status: "error", message: "Selenium job failed" }));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [jobStatus, jobResult, pendingClaimJobId]);
// small helper: remove given query params from the current URL (silent, no reload)
const clearUrlParams = (params: string[]) => {
try {
@@ -331,31 +358,23 @@ export default function ClaimsPage() {
const result1 = await response.json();
if (result1.error) throw new Error(result1.error);
if (result1.claimNumber) {
await queryClient.invalidateQueries({ queryKey: ["claims-recent"] });
}
// Job is queued — wait for socket completion before downloading PDF
pendingClaimMeta.current = { patientId: selectedPatientId, groupKey: "INSURANCE_CLAIM" };
setPendingClaimJobId(result1.jobId);
dispatch(
setTaskStatus({
key: "claimSubmit",
status: "pending",
message: "Submitted to Selenium. Awaiting PDF...",
message: "Submitted to Selenium. Awaiting result...",
})
);
toast({
title: "Selenium service notified",
description:
"Your claim data was successfully sent to Selenium, Waitinig for its response.",
description: "Claim submitted to Selenium. Waiting for confirmation...",
variant: "default",
});
const result2 = await handleMHSeleniumPdfDownload(
result1,
selectedPatientId,
"INSURANCE_CLAIM"
);
return result2;
} catch (error: any) {
dispatch(
setTaskStatus({
@@ -475,27 +494,23 @@ export default function ClaimsPage() {
const result1 = await response.json();
if (result1.error) throw new Error(result1.error);
// Job is queued — wait for socket completion before downloading PDF
pendingClaimMeta.current = { patientId: selectedPatientId, groupKey: "INSURANCE_CLAIM_PREAUTH" };
setPendingClaimJobId(result1.jobId);
dispatch(
setTaskStatus({
key: "claimSubmit",
status: "pending",
message: "Submitted to Selenium. Awaiting PDF...",
message: "Submitted to Selenium. Awaiting result...",
})
);
toast({
title: "Selenium service notified",
description:
"Your claim pre auth data was successfully sent to Selenium, Waitinig for its response.",
description: "Pre-auth submitted to Selenium. Waiting for confirmation...",
variant: "default",
});
const result2 = await handleMHSeleniumPdfDownload(
result1,
selectedPatientId,
"INSURANCE_CLAIM_PREAUTH"
);
return result2;
} catch (error: any) {
dispatch(
setTaskStatus({

View File

@@ -641,20 +641,14 @@ export default function InsuranceStatusPage() {
}}
/>
<CCAEligibilityButton
memberId={memberId}
dateOfBirth={dateOfBirth}
firstName={firstName}
lastName={lastName}
isFormIncomplete={isFormIncomplete}
onPdfReady={(pdfId, fallbackFilename) => {
setPreviewPdfId(pdfId);
setPreviewFallbackFilename(
fallbackFilename ?? `eligibility_cca_${memberId}.pdf`,
);
setPreviewOpen(true);
}}
/>
<Button
className="w-full"
variant="outline"
disabled={isFormIncomplete}
>
<CheckCircle className="h-4 w-4 mr-2" />
BCBS
</Button>
</div>
{/* Row 2 */}
@@ -689,6 +683,24 @@ export default function InsuranceStatusPage() {
}}
/>
<CCAEligibilityButton
memberId={memberId}
dateOfBirth={dateOfBirth}
firstName={firstName}
lastName={lastName}
isFormIncomplete={isFormIncomplete}
onPdfReady={(pdfId, fallbackFilename) => {
setPreviewPdfId(pdfId);
setPreviewFallbackFilename(
fallbackFilename ?? `eligibility_cca_${memberId}.pdf`,
);
setPreviewOpen(true);
}}
/>
</div>
{/* Row 3 */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Button
className="w-full"
variant="outline"
@@ -697,10 +709,7 @@ export default function InsuranceStatusPage() {
<CheckCircle className="h-4 w-4 mr-2" />
United AAPR
</Button>
</div>
{/* Row 3 */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Button
className="w-full"
variant="outline"
@@ -725,6 +734,45 @@ export default function InsuranceStatusPage() {
<CheckCircle className="h-4 w-4 mr-2" />
Metlife Dental
</Button>
<Button
className="w-full"
variant="outline"
disabled={isFormIncomplete}
>
<CheckCircle className="h-4 w-4 mr-2" />
Cigna
</Button>
<Button
className="w-full"
variant="outline"
disabled={isFormIncomplete}
>
<CheckCircle className="h-4 w-4 mr-2" />
Delta WA
</Button>
</div>
{/* Row 5 */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Button
className="w-full"
variant="outline"
disabled={isFormIncomplete}
>
<CheckCircle className="h-4 w-4 mr-2" />
Delta IL
</Button>
<Button
className="w-full"
variant="outline"
disabled={isFormIncomplete}
>
<CheckCircle className="h-4 w-4 mr-2" />
Others
</Button>
</div>
</div>
</CardContent>

View File

@@ -13,12 +13,14 @@ import time
import helpers_ddma_eligibility as hddma
import helpers_deltains_eligibility as hdeltains
import helpers_unitedsco_eligibility as hunitedsco
import helpers_dentaquest_eligibility as hdentaquest
import helpers_cca_eligibility as hcca
# Import startup session-clear functions
from ddma_browser_manager import clear_ddma_session_on_startup
from deltains_browser_manager import clear_deltains_session_on_startup
from unitedsco_browser_manager import clear_unitedsco_session_on_startup
from dentaquest_browser_manager import clear_dentaquest_session_on_startup
from cca_browser_manager import clear_cca_session_on_startup
from dotenv import load_dotenv
@@ -31,6 +33,7 @@ print("=" * 50)
clear_ddma_session_on_startup()
clear_deltains_session_on_startup()
clear_unitedsco_session_on_startup()
clear_dentaquest_session_on_startup()
clear_cca_session_on_startup()
print("=" * 50)
print("SESSION CLEAR COMPLETE")
@@ -341,6 +344,47 @@ async def unitedsco_eligibility(request: Request):
return {"status": "started", "session_id": sid}
async def _dentaquest_worker_wrapper(sid: str, data: dict, url: str):
"""Background worker for DentaQuest (Tufts SCO) — acquires semaphore, updates counters."""
global active_jobs, waiting_jobs
async with semaphore:
async with lock:
waiting_jobs -= 1
active_jobs += 1
try:
await hdentaquest.start_dentaquest_run(sid, data, url)
finally:
async with lock:
active_jobs -= 1
@app.post("/dentaquest-eligibility")
async def dentaquest_eligibility(request: Request):
"""
Starts a DentaQuest (Tufts SCO) eligibility session in the background.
Body: { "data": { ... } }
Returns: { status: "started", session_id: "<uuid>" }
"""
global waiting_jobs
body = await request.json()
data = body.get("data", {})
sid = hdentaquest.make_session_entry()
hdentaquest.sessions[sid]["type"] = "dentaquest_eligibility"
hdentaquest.sessions[sid]["last_activity"] = time.time()
async with lock:
waiting_jobs += 1
asyncio.create_task(_dentaquest_worker_wrapper(
sid, data,
url="https://providers.dentaquest.com/"
))
return {"status": "started", "session_id": sid}
async def _cca_worker_wrapper(sid: str, data: dict, url: str):
"""Background worker for CCA — acquires semaphore, updates counters. No OTP."""
global active_jobs, waiting_jobs
@@ -401,6 +445,8 @@ async def submit_otp(request: Request):
res = hdeltains.submit_otp(sid, otp)
elif sid in hunitedsco.sessions:
res = hunitedsco.submit_otp(sid, otp)
elif sid in hdentaquest.sessions:
res = hdentaquest.submit_otp(sid, otp)
else:
raise HTTPException(status_code=404, detail="session not found")
@@ -418,6 +464,8 @@ async def session_status(sid: str):
s = hdeltains.get_session_status(sid)
elif sid in hunitedsco.sessions:
s = hunitedsco.get_session_status(sid)
elif sid in hdentaquest.sessions:
s = hdentaquest.get_session_status(sid)
elif sid in hcca.sessions:
s = hcca.get_session_status(sid)
else:

View File

@@ -111,7 +111,26 @@ class DentaQuestBrowserManager:
print("[DentaQuest BrowserManager] Cleared IndexedDB")
except Exception as e:
print(f"[DentaQuest BrowserManager] Could not clear IndexedDB: {e}")
# Clear browser caches (prevents Chrome crash from corrupted cache)
cache_dirs = [
os.path.join(self.profile_dir, "Default", "Cache"),
os.path.join(self.profile_dir, "Default", "Code Cache"),
os.path.join(self.profile_dir, "Default", "GPUCache"),
os.path.join(self.profile_dir, "Default", "Service Worker"),
os.path.join(self.profile_dir, "Cache"),
os.path.join(self.profile_dir, "Code Cache"),
os.path.join(self.profile_dir, "GPUCache"),
os.path.join(self.profile_dir, "ShaderCache"),
]
for cache_dir in cache_dirs:
if os.path.exists(cache_dir):
try:
shutil.rmtree(cache_dir)
print(f"[DentaQuest BrowserManager] Cleared {os.path.basename(cache_dir)}")
except Exception as e:
print(f"[DentaQuest BrowserManager] Could not clear {os.path.basename(cache_dir)}: {e}")
# Set flag to clear session via JavaScript after browser opens
self._needs_session_clear = True
@@ -181,13 +200,13 @@ class DentaQuestBrowserManager:
except Exception as e:
pass
# Remove SingletonLock if exists
lock_file = os.path.join(self.profile_dir, "SingletonLock")
try:
if os.path.islink(lock_file) or os.path.exists(lock_file):
os.remove(lock_file)
except:
pass
for lock_file in ["SingletonLock", "SingletonSocket", "SingletonCookie"]:
lock_path = os.path.join(self.profile_dir, lock_file)
try:
if os.path.islink(lock_path) or os.path.exists(lock_path):
os.remove(lock_path)
except Exception:
pass
def get_driver(self, headless=False):
"""Get or create the persistent browser instance."""
@@ -232,7 +251,12 @@ class DentaQuestBrowserManager:
options.add_argument(f"--user-data-dir={self.profile_dir}")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-gpu")
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("useAutomationExtension", False)
options.add_argument("--disable-infobars")
prefs = {
"download.default_directory": self.download_dir,
"plugins.always_open_pdf_externally": True,

View File

@@ -36,41 +36,34 @@ def make_session_entry() -> str:
async def cleanup_session(sid: str, message: str | None = None):
"""
Close driver (if any), wake OTP waiter, set final state, and remove session entry.
Idempotent: safe to call multiple times.
Set final error state and wake OTP waiter. Schedules session removal after a delay
so the backend can read the actual error message before the session disappears.
"""
s = sessions.get(sid)
if not s:
return
try:
# Ensure final state
try:
if s.get("status") not in ("completed", "error", "not_found"):
s["status"] = "error"
if message:
s["message"] = message
except Exception:
pass
if s.get("status") not in ("completed", "error", "not_found"):
s["status"] = "error"
if message:
s["message"] = message
except Exception:
pass
# Wake any OTP waiter (so awaiting coroutines don't hang)
try:
ev = s.get("otp_event")
if ev and not ev.is_set():
ev.set()
except Exception:
pass
try:
ev = s.get("otp_event")
if ev and not ev.is_set():
ev.set()
except Exception:
pass
# NOTE: Do NOT quit driver - keep browser alive for next patient
# Browser manager handles the persistent browser instance
finally:
# Remove session entry from map
sessions.pop(sid, None)
# Keep session for 30s so backend can read the error, then remove
asyncio.create_task(_remove_session_later(sid, 30))
async def _remove_session_later(sid: str, delay: int = 20):
async def _remove_session_later(sid: str, delay: int = 30):
await asyncio.sleep(delay)
await cleanup_session(sid)
sessions.pop(sid, None)
async def start_dentaquest_run(sid: str, data: dict, url: str):
@@ -281,6 +274,9 @@ async def start_dentaquest_run(sid: str, data: dict, url: str):
return {"status": "error", "message": s["message"]}
except Exception as e:
import traceback
print(f"[start_dentaquest_run] EXCEPTION: {e}")
traceback.print_exc()
s["status"] = "error"
s["message"] = f"worker exception: {e}"
await cleanup_session(sid)

View File

@@ -77,6 +77,28 @@ class AutomationCCAEligibilityCheck:
except Exception:
return False
def _set_input_value(self, field, value: str):
"""Set input value in a way that triggers React/Vue/Angular framework state updates."""
try:
self.driver.execute_script(
"""
var el = arguments[0];
var val = arguments[1];
var nativeSetter = Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype, 'value').set;
nativeSetter.call(el, val);
el.dispatchEvent(new Event('input', {bubbles: true}));
el.dispatchEvent(new Event('change', {bubbles: true}));
""",
field, value
)
except Exception:
# Fallback to regular send_keys if JS fails
field.click()
field.send_keys(Keys.CONTROL + "a")
field.send_keys(Keys.DELETE)
field.send_keys(value)
def login(self, url):
"""
Login to ScionDental portal for CCA.
@@ -124,59 +146,96 @@ class AutomationCCAEligibilityCheck:
# Session expired — navigate to login URL
print("[CCA login] Session not valid, navigating to login page...")
self.driver.get(url)
time.sleep(2)
# Wait up to 15s for ANY input to appear, then snapshot the page
try:
WebDriverWait(self.driver, 15).until(
EC.presence_of_element_located((By.XPATH, "//input"))
)
except TimeoutException:
pass
time.sleep(1)
current_url = self.driver.current_url
print(f"[CCA login] After login nav URL: {current_url}")
# Enter username
# Dump all inputs so we can see what's on the page
try:
all_inputs = self.driver.find_elements(By.XPATH, "//input")
print(f"[CCA login] Found {len(all_inputs)} input(s) on page:")
for inp in all_inputs:
try:
print(f" input: type={inp.get_attribute('type')!r} "
f"id={inp.get_attribute('id')!r} "
f"name={inp.get_attribute('name')!r} "
f"visible={inp.is_displayed()}")
except Exception:
pass
except Exception as e:
print(f"[CCA login] Could not enumerate inputs: {e}")
# Enter username — click first to ensure focus, then type
print("[CCA login] Looking for username field...")
username_entered = False
username_field = None
for sel in [
(By.ID, "Username"),
(By.NAME, "Username"),
(By.XPATH, "//input[@type='text']"),
(By.XPATH, "//input[@type='email']"),
]:
try:
field = WebDriverWait(self.driver, 6).until(
EC.presence_of_element_located(sel))
if field.is_displayed():
field.clear()
field.send_keys(self.cca_username)
username_entered = True
print(f"[CCA login] Username entered via {sel}")
break
EC.element_to_be_clickable(sel))
username_field = field
print(f"[CCA login] Found username field via {sel}")
break
except Exception:
continue
if not username_entered:
if not username_field:
if self._page_has_logged_in_content():
return "ALREADY_LOGGED_IN"
return "ERROR: Could not find username field"
username_field.click()
username_field.send_keys(Keys.CONTROL + "a")
username_field.send_keys(Keys.DELETE)
username_field.send_keys(self.cca_username)
time.sleep(0.3)
actual_val = username_field.get_attribute("value")
print(f"[CCA login] Username field value after entry: {actual_val!r}")
time.sleep(0.5)
# Enter password
print("[CCA login] Looking for password field...")
pw_entered = False
pw_field = None
for sel in [
(By.ID, "Password"),
(By.NAME, "Password"),
(By.XPATH, "//input[@type='password']"),
]:
try:
field = self.driver.find_element(*sel)
if field.is_displayed():
field.clear()
field.send_keys(self.cca_password)
pw_entered = True
print(f"[CCA login] Password entered via {sel}")
break
field = WebDriverWait(self.driver, 6).until(
EC.element_to_be_clickable(sel))
pw_field = field
print(f"[CCA login] Found password field via {sel}")
break
except Exception:
continue
if not pw_entered:
if not pw_field:
return "ERROR: Password field not found"
# Click login button
pw_field.click()
pw_field.send_keys(Keys.CONTROL + "a")
pw_field.send_keys(Keys.DELETE)
pw_field.send_keys(self.cca_password)
time.sleep(0.3)
print(f"[CCA login] Password field value length after entry: {len(pw_field.get_attribute('value') or '')}")
# Submit — try button click, fall back to Enter key
submitted = False
for sel in [
(By.XPATH, "//button[@type='submit']"),
(By.XPATH, "//input[@type='submit']"),
@@ -187,45 +246,43 @@ class AutomationCCAEligibilityCheck:
btn = self.driver.find_element(*sel)
if btn.is_displayed():
btn.click()
submitted = True
print(f"[CCA login] Clicked login button via {sel}")
break
except Exception:
continue
if not submitted:
print("[CCA login] No submit button found — pressing Enter on password field")
pw_field.send_keys(Keys.RETURN)
if self.cca_username:
browser_manager.save_credentials_hash(self.cca_username)
# Wait for page to load after login
# Wait for actual portal content — NOT just URL (login page URL also contains "Landing")
try:
WebDriverWait(self.driver, 15).until(
lambda d: "Landing" in d.current_url
or "Dental" in d.current_url
or "Home" in d.current_url
WebDriverWait(self.driver, 20).until(
lambda d: any(x in d.find_element(By.TAG_NAME, "body").text
for x in ["Verify Patient Eligibility", "Patient Management",
"Submit a Claim", "Claim Inquiry"])
)
print("[CCA login] Redirected to portal page")
current_url = self.driver.current_url
print(f"[CCA login] Portal content detected — login successful. URL: {current_url}")
return "SUCCESS"
except TimeoutException:
time.sleep(3)
pass
current_url = self.driver.current_url
print(f"[CCA login] After login submit URL: {current_url}")
# Check for login errors
# Login did not succeed — dump page text for diagnosis
try:
body_text = self.driver.find_element(By.TAG_NAME, "body").text
print(f"[CCA login] Page text after submit (first 600): {body_text[:600]}")
if "invalid" in body_text.lower() and ("password" in body_text.lower() or "username" in body_text.lower()):
return "ERROR: Invalid username or password"
except Exception:
pass
if self._page_has_logged_in_content():
print("[CCA login] Login successful")
return "SUCCESS"
if "Landing" in current_url or "Home" in current_url or "Dental" in current_url:
return "SUCCESS"
# Check for errors
try:
errors = self.driver.find_elements(By.XPATH,
"//*[contains(@class,'error') or contains(@class,'alert-danger') or contains(@class,'validation-summary')]")
for err in errors:
@@ -234,8 +291,7 @@ class AutomationCCAEligibilityCheck:
except Exception:
pass
print("[CCA login] Login completed (assuming success)")
return "SUCCESS"
return "ERROR: Login did not succeed — portal content not found after submit"
except Exception as e:
print(f"[CCA login] Exception: {e}")

View File

@@ -335,32 +335,6 @@ class AutomationDeltaDentalMAEligibilityCheck:
except Exception as e:
print(f"[DDMA step1] Warning: Could not fill DOB: {e}")
# 3. Fill First Name if provided
if self.firstName:
try:
first_name_input = wait.until(EC.presence_of_element_located(
(By.XPATH, '//input[@placeholder="First name - 1 char minimum" or contains(@placeholder,"first name") or contains(@name,"firstName")]')
))
first_name_input.clear()
first_name_input.send_keys(self.firstName)
print(f"[DDMA step1] Entered First Name: {self.firstName}")
time.sleep(0.2)
except Exception as e:
print(f"[DDMA step1] Warning: Could not fill First Name: {e}")
# 4. Fill Last Name if provided
if self.lastName:
try:
last_name_input = wait.until(EC.presence_of_element_located(
(By.XPATH, '//input[@placeholder="Last name - 2 char minimum" or contains(@placeholder,"last name") or contains(@name,"lastName")]')
))
last_name_input.clear()
last_name_input.send_keys(self.lastName)
print(f"[DDMA step1] Entered Last Name: {self.lastName}")
time.sleep(0.2)
except Exception as e:
print(f"[DDMA step1] Warning: Could not fill Last Name: {e}")
time.sleep(0.3)
# Click Search button

View File

@@ -305,65 +305,40 @@ class AutomationDentaQuestEligibilityCheck:
print(f"[DentaQuest step1] Error filling {field_name}: {e}")
return False
# 1. Select Provider from dropdown (required field)
# 1. Select Location from dropdown (required field before search)
try:
print("[DentaQuest step1] Selecting Provider...")
# Try to find and click Provider dropdown
provider_selectors = [
"//label[contains(text(),'Provider')]/following-sibling::*//div[contains(@class,'select')]",
"//div[contains(@data-testid,'provider')]//div[contains(@class,'select')]",
"//*[@aria-label='Provider']",
"//select[contains(@name,'provider') or contains(@id,'provider')]",
"//div[contains(@class,'provider')]//input",
"//label[contains(text(),'Provider')]/..//div[contains(@class,'control')]"
]
provider_clicked = False
for selector in provider_selectors:
print("[DentaQuest step1] Selecting Location...")
# Click the Location dropdown button (stable data-testid)
location_clicked = False
try:
trigger = WebDriverWait(self.driver, 5).until(
EC.element_to_be_clickable((By.XPATH, '//button[@data-testid="member-search_location_select-btn"]'))
)
trigger.click()
print("[DentaQuest step1] Clicked location dropdown button")
time.sleep(0.5)
location_clicked = True
except TimeoutException:
print("[DentaQuest step1] Warning: Location button not found by data-testid")
if location_clicked:
# Wait for options to appear and click the first one (role="option")
try:
provider_dropdown = WebDriverWait(self.driver, 3).until(
EC.element_to_be_clickable((By.XPATH, selector))
first_option = WebDriverWait(self.driver, 5).until(
EC.element_to_be_clickable((By.XPATH, "(//li[@role='option'])[1]"))
)
provider_dropdown.click()
print(f"[DentaQuest step1] Clicked provider dropdown with selector: {selector}")
time.sleep(0.5)
provider_clicked = True
break
opt_text = first_option.get_attribute("aria-label") or first_option.text.strip()
first_option.click()
print(f"[DentaQuest step1] Selected location: {opt_text[:60]}")
time.sleep(0.3)
except TimeoutException:
continue
if provider_clicked:
# Select first available provider option
option_selectors = [
"//div[contains(@class,'option') and not(contains(@class,'disabled'))]",
"//li[contains(@class,'option')]",
"//option[not(@disabled)]",
"//*[@role='option']"
]
for opt_selector in option_selectors:
try:
options = self.driver.find_elements(By.XPATH, opt_selector)
if options:
# Select first non-placeholder option
for opt in options:
opt_text = opt.text.strip()
if opt_text and "select" not in opt_text.lower():
opt.click()
print(f"[DentaQuest step1] Selected provider: {opt_text}")
break
break
except:
continue
# Close dropdown if still open
ActionChains(self.driver).send_keys(Keys.ESCAPE).perform()
time.sleep(0.3)
print("[DentaQuest step1] Warning: Location options did not appear")
else:
print("[DentaQuest step1] Warning: Could not find Provider dropdown")
print("[DentaQuest step1] Warning: Could not find Location dropdown trigger")
except Exception as e:
print(f"[DentaQuest step1] Error selecting provider: {e}")
print(f"[DentaQuest step1] Error selecting location: {e}")
time.sleep(0.3)
@@ -501,29 +476,26 @@ class AutomationDentaQuestEligibilityCheck:
if self.memberId:
foundMemberId = self.memberId
# Extract eligibility status
status_selectors = [
"(//tbody//tr)[1]//a[contains(@href, 'eligibility')]",
"//a[contains(@href,'eligibility')]",
"//*[contains(@class,'status')]",
"//*[contains(text(),'Active') or contains(text(),'Inactive') or contains(text(),'Eligible')]"
]
for selector in status_selectors:
try:
status_elem = self.driver.find_element(By.XPATH, selector)
status_text = status_elem.text.strip().lower()
if status_text:
print(f"[DentaQuest step2] Found status with selector '{selector}': {status_text}")
if "active" in status_text or "eligible" in status_text:
eligibilityText = "active"
break
elif "inactive" in status_text or "ineligible" in status_text:
eligibilityText = "inactive"
break
except:
continue
# Extract eligibility status from first result row
try:
status_elem = self.driver.find_element(By.XPATH,
"(//tbody//tr)[1]//*[self::span or self::a or self::div]["
"contains(text(),'Active') or contains(text(),'Inactive') or "
"contains(text(),'Eligible') or contains(text(),'Ineligible') or "
"contains(text(),'Plan not accepted') or contains(text(),'Not eligible')"
"]"
)
status_text = status_elem.text.strip().lower()
print(f"[DentaQuest step2] Found eligibility status: '{status_text}'")
if "active" in status_text or ("eligible" in status_text and "ineligible" not in status_text):
eligibilityText = "active"
elif "plan not accepted" in status_text:
eligibilityText = "plan not accepted"
else:
eligibilityText = "inactive"
except Exception as e:
print(f"[DentaQuest step2] Could not find eligibility status: {e}")
print(f"[DentaQuest step2] Final eligibility status: {eligibilityText}")
# 2) Find the patient detail link and navigate DIRECTLY to it
@@ -685,6 +657,11 @@ class AutomationDentaQuestEligibilityCheck:
if not patientName:
print("[DentaQuest step2] Could not extract patient name")
else:
# Strip any trailing date (e.g. "PRINCILLA WALKER 01/09/2026")
import re as _re
patientName = _re.sub(r'\s*\d{1,2}/\d{1,2}/\d{2,4}\s*$', '', patientName).strip()
# Also strip "DOB: ..." prefix/suffix
patientName = _re.sub(r'\s*DOB[:\s]*\d{1,2}/\d{1,2}/\d{2,4}\s*', '', patientName, flags=_re.IGNORECASE).strip()
print(f"[DentaQuest step2] Patient name: {patientName}")
# Wait for page to fully load before generating PDF
@@ -721,14 +698,14 @@ class AutomationDentaQuestEligibilityCheck:
f.write(pdf_data)
print(f"[DentaQuest step2] PDF saved: {pdf_path}")
# Close the browser window after PDF generation
# Close browser after PDF (session preserved in profile)
try:
from dentaquest_browser_manager import get_browser_manager
get_browser_manager().quit_driver()
print("[DentaQuest step2] Browser closed")
except Exception as e:
print(f"[DentaQuest step2] Error closing browser: {e}")
output = {
"status": "success",
"eligibility": eligibilityText,

View File

@@ -157,7 +157,22 @@ class AutomationUnitedSCOEligibilityCheck:
# Step 2: Fill in credentials on B2C login page
if "b2clogin.com" in current_url or "login" in current_url.lower():
print("[UnitedSCO login] On B2C login page - filling credentials")
# Check if we're already on the phone verification ("Text Me") page
# This happens if the browser session was left on this page
try:
send_code_btn = self.driver.find_element(By.XPATH,
"//button[@id='sendCode'] | //input[@id='sendCode'] | "
"//button[contains(text(),'Text Me') or contains(text(),'Send Code')]"
)
if send_code_btn.is_displayed():
print("[UnitedSCO login] Already on phone verification page - clicking 'Text Me'")
self.driver.execute_script("arguments[0].click();", send_code_btn)
time.sleep(3)
return "OTP_REQUIRED"
except Exception:
pass
try:
# Find email field by id="signInName" (Azure B2C specific)
email_field = WebDriverWait(self.driver, 10).until(
@@ -231,7 +246,49 @@ class AutomationUnitedSCOEligibilityCheck:
# Click Continue
continue_btn.click()
print("[UnitedSCO login] Clicked 'Continue' on MFA selection page")
time.sleep(5) # Wait for OTP to be sent
time.sleep(3) # Wait for phone verification page to load
# Click "Text Me" button on the phone verification page
# Azure B2C uses id="sendCode" for this button
try:
text_me_btn = WebDriverWait(self.driver, 8).until(
EC.element_to_be_clickable((By.XPATH,
"//button[@id='sendCode'] | "
"//input[@id='sendCode'] | "
"//button[contains(text(),'Text Me') or contains(text(),'Send Code') or contains(text(),'Send me')] | "
"//input[@value='Text Me' or @value='Send Code' or @value='Send me']"
))
)
self.driver.execute_script("arguments[0].scrollIntoView({block:'center'});", text_me_btn)
time.sleep(0.5)
text_me_btn.click()
print("[UnitedSCO login] Clicked 'Text Me' / 'Send Code' button")
time.sleep(3) # Wait for SMS to be sent
except TimeoutException:
print("[UnitedSCO login] No 'Text Me' button found - trying JS fallback")
try:
clicked = self.driver.execute_script("""
var btn = document.getElementById('sendCode');
if (btn) { btn.click(); return 'sendCode clicked'; }
var all = document.querySelectorAll('button, input[type="button"], input[type="submit"]');
for (var i = 0; i < all.length; i++) {
var t = (all[i].textContent || all[i].value || '').toLowerCase();
if (t.includes('text me') || t.includes('send code') || t.includes('send me')) {
all[i].click();
return 'clicked: ' + t;
}
}
return null;
""")
if clicked:
print(f"[UnitedSCO login] JS 'Text Me' click result: {clicked}")
time.sleep(3)
else:
print("[UnitedSCO login] WARNING: Could not find 'Text Me' button via JS either")
except Exception as js_err:
print(f"[UnitedSCO login] JS click error: {js_err}")
except Exception as e:
print(f"[UnitedSCO login] Error clicking 'Text Me': {e}")
except Exception:
pass # No MFA selection page - proceed normally
@@ -784,25 +841,44 @@ class AutomationUnitedSCOEligibilityCheck:
patientName = f"{self.firstName} {self.lastName}".strip()
foundMemberId = self.memberId # Use provided memberId as default
# Extract eligibility status
# Extract eligibility status — try multiple text patterns
try:
status_elem = WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located((By.XPATH,
"//*[contains(text(),'Member Eligible') or contains(text(),'member eligible')]"
"//*[contains(text(),'Member Eligible') or contains(text(),'member eligible') or "
"contains(text(),'Eligible') or contains(text(),'eligible') or "
"contains(text(),'Ineligible') or contains(text(),'ineligible') or "
"contains(text(),'Not Eligible') or contains(text(),'not eligible')]"
))
)
status_text = status_elem.text.strip().lower()
print(f"[UnitedSCO step2] Found status: {status_text}")
if "eligible" in status_text:
eligibilityText = "active"
elif "ineligible" in status_text or "not eligible" in status_text:
print(f"[UnitedSCO step2] Found status element text: {status_text}")
if "ineligible" in status_text or "not eligible" in status_text:
eligibilityText = "inactive"
elif "eligible" in status_text:
eligibilityText = "active"
except TimeoutException:
print("[UnitedSCO step2] Eligibility status badge not found")
print("[UnitedSCO step2] Eligibility status element not found via text — trying page text scan")
except Exception as e:
print(f"[UnitedSCO step2] Error extracting status: {e}")
# Fallback: scan page text for eligibility keywords
if eligibilityText == "unknown":
try:
body_text = self.driver.find_element(By.TAG_NAME, "body").text.lower()
if "member eligible" in body_text or "member is eligible" in body_text:
eligibilityText = "active"
print("[UnitedSCO step2] Status from page text: active (member eligible)")
elif "not eligible" in body_text or "ineligible" in body_text or "member ineligible" in body_text:
eligibilityText = "inactive"
print("[UnitedSCO step2] Status from page text: inactive")
elif "eligible" in body_text:
eligibilityText = "active"
print("[UnitedSCO step2] Status from page text: active (eligible found)")
except Exception as e:
print(f"[UnitedSCO step2] Page text status scan error: {e}")
print(f"[UnitedSCO step2] Eligibility status: {eligibilityText}")
@@ -842,6 +918,10 @@ class AutomationUnitedSCOEligibilityCheck:
"//div[contains(@class,'patient')]//h3 | //div[contains(@class,'patient')]//h4",
"//*[contains(@class,'eligibility__banner')]//h3 | //*[contains(@class,'eligibility__banner')]//h4",
"//*[contains(@class,'banner__patient')]",
# Heading elements near "Selected Patient" label
"//*[contains(text(),'Selected Patient')]/following-sibling::*[self::h1 or self::h2 or self::h3 or self::h4 or self::strong or self::p][1]",
"//*[contains(text(),'Selected Patient')]/..//*[self::h1 or self::h2 or self::h3 or self::h4 or self::strong][1]",
"//*[contains(text(),'Selected Patient')]/parent::*/following-sibling::*[1]//*[self::h3 or self::h4 or self::p or self::span][1]",
]
for sel in name_selectors:
try:
@@ -863,13 +943,16 @@ class AutomationUnitedSCOEligibilityCheck:
# IMPORTANT: Use [^\n] to avoid matching across newlines (e.g. picking up "Member Eligible")
if not name_extracted:
name_patterns = [
# Name on the line right after "Selected Patient"
r'Selected Patient\s*\n\s*([A-Z][A-Za-z\-\']+(?: [A-Z][A-Za-z\-\']+)+)',
# Name on the line right after "Selected Patient" (on same or next line)
r'Selected Patient[:\s]*\n\s*([A-Z][A-Za-z\-\']+(?: [A-Z][A-Za-z\-\']+)+)',
r'Selected Patient[:\s]+([A-Z][A-Za-z\-\']+(?: [A-Z][A-Za-z\-\']+)+)',
r'Patient Name\s*[\n:]\s*([A-Z][A-Za-z\-\']+(?: [A-Z][A-Za-z\-\']+)+)',
# "LASTNAME, FIRSTNAME" format
r'Selected Patient\s*\n\s*([A-Z][A-Za-z\-\']+,\s*[A-Z][A-Za-z\-\']+)',
# Name on the line right before "Member Eligible" or "Member ID"
r'\n([A-Z][A-Za-z\-\']+(?: [A-Z]\.?)? [A-Z][A-Za-z\-\']+)\n(?:Member|Date Of Birth|DOB)',
# Name on the line right before "Member Eligible", "Eligible", "Member ID", or "Date Of Birth"
r'\n([A-Z][A-Za-z\-\']+(?: [A-Z]\.?)? [A-Z][A-Za-z\-\']+)\n(?:Member|Eligible|Date Of Birth|DOB)',
# Name before DOB in any case
r'([A-Z][A-Za-z\-\']+(?:\s+[A-Z][A-Za-z\-\']+)+)\n\d{2}/\d{2}/\d{4}',
]
for pattern in name_patterns:
try:
@@ -877,9 +960,9 @@ class AutomationUnitedSCOEligibilityCheck:
if name_match:
candidate = name_match.group(1).strip()
# Validate: not too long, not a header/label, and doesn't contain "Eligible"/"Member"/"Patient"
skip_words = ("Selected Patient", "Patient Name", "Patient Information",
skip_words = ("Selected Patient", "Patient Name", "Patient Information",
"Member Eligible", "Member ID", "Date Of Birth")
if (len(candidate) < 50 and candidate not in skip_words
if (len(candidate) < 50 and candidate not in skip_words
and "Eligible" not in candidate and "Member" not in candidate):
patientName = candidate
name_extracted = True

View File

@@ -43,7 +43,7 @@ model Patient {
id Int @id @default(autoincrement())
firstName String
lastName String
dateOfBirth DateTime @db.Date
dateOfBirth DateTime? @db.Date
gender String
phone String
email String?
@@ -76,6 +76,7 @@ enum PatientStatus {
ACTIVE
INACTIVE
UNKNOWN
PLAN_NOT_ACCEPTED
}
model Appointment {

View File

@@ -25,7 +25,7 @@ export const insuranceIdSchema = z.preprocess(
// After preprocess, require digits-only string (or optional nullable)
z
.string()
.regex(/^\d+$/, { message: "Insurance ID must contain only digits" })
.regex(/^[A-Za-z0-9]+$/, { message: "Insurance ID must contain only letters and digits" })
.min(1)
.max(32)
.optional()