feat: MassHealth eligibility on new portal with persistent session and Gmail OTP auto-read

- New MH eligibility worker for providers.masshealth-dental.org (same DentaQuest
  portal as Tufts SCO): persistent Chrome profile, OTP via app popup, member
  details PDF, address, service history, plan name and remaining benefit
- Reads the OTP from the office Gmail over IMAP (App Password) and types it in;
  falls back to the manual OTP popup
- Insurance credentials: OTP Email / Phone and OTP Email Password fields
- New patient status ACTIVE_PLAN_NOT_ACCEPTED (coverage active, plan not accepted)
- Removes the old MH eligibility, MH history and CMSP remaining workers/processors;
  batch appointment check and AI conversation use the new MH processor

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-05 16:47:22 -05:00
co-authored by Claude Opus 5.5
parent 4661c30c9f
commit f5b91a75d4
85 changed files with 3086 additions and 2835 deletions
@@ -14,7 +14,7 @@ import {
timeLabel,
} from "./reschedule-graph";
import { getLlm, type AiProvider } from "./llm-factory";
import { runEligibilityProcessor } from "../queue/processors/eligibilityProcessor";
import { runMHEligibilityProcessor } from "../queue/processors/mhEligibilityProcessor";
import { sendAppointmentConfirmationSms } from "./confirmationSms";
import {
getPendingReschedule, setPendingReschedule, clearPendingReschedule,
@@ -135,18 +135,23 @@ async function runMassHealthCheckAndNotify(
const telnyxSettings = await storage.getTelnyxSettings(patient.userId);
if (!telnyxSettings || !patient.phone) return;
await runEligibilityProcessor({
userId: patient.userId,
insuranceId: memberId,
formDob: dob,
enrichedPayload: {
memberId,
dateOfBirth: dob,
insuranceSiteKey: "MH",
massdhpUsername: credentials.username,
massdhpPassword: credentials.password,
await runMHEligibilityProcessor(
{
userId: patient.userId,
insuranceId: memberId,
formDob: dob,
enrichedPayload: {
memberId,
dateOfBirth: dob,
insuranceSiteKey: "MH",
mhUsername: credentials.username,
mhPassword: credentials.password,
otpEmail: credentials.otpContact ?? null,
otpEmailPassword: credentials.otpContactPassword ?? null,
},
},
});
`ai-${patient.id}`
);
const updated = await db.patient.findUnique({
where: { id: patient.id },
+14 -32
View File
@@ -7,7 +7,6 @@
*/
import { InProcessQueue } from "./inProcessQueue";
import { io } from "../socket";
import { runEligibilityProcessor } from "./processors/eligibilityProcessor";
import { runClaimStatusProcessor } from "./processors/claimStatusProcessor";
import { runClaimSubmitProcessor } from "./processors/claimSubmitProcessor";
import { runOcrProcessor } from "./processors/ocrProcessor";
@@ -30,8 +29,7 @@ import { runUnitedDHPreAuthProcessor } from "./processors/unitedDHPreAuthProcess
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 { runMHEligibilityProcessor } from "./processors/mhEligibilityProcessor";
import { runBcbsMaEligibilityProcessor } from "./processors/bcbsMaEligibilityProcessor";
import { runMetLifeEligibilityProcessor } from "./processors/metlifeEligibilityProcessor";
import { runAltusEligibilityProcessor } from "./processors/altusEligibilityProcessor";
@@ -69,16 +67,6 @@ export function enqueueSeleniumJob(data: SeleniumJobData): string {
message: "Selenium browser starting…",
});
if (jobType === "eligibility-check") {
return runEligibilityProcessor({
enrichedPayload: data.enrichedPayload,
userId: data.userId,
insuranceId: data.insuranceId!,
formFirstName: data.formFirstName,
formLastName: data.formLastName,
formDob: data.formDob,
});
}
if (jobType === "claim-status-check") {
return runClaimStatusProcessor({
enrichedPayload: data.enrichedPayload,
@@ -342,25 +330,19 @@ export function enqueueSeleniumJob(data: SeleniumJobData): string {
job.id
);
}
if (jobType === "cmsp-eligibility-history-remaining-check") {
return runCmspEligibilityHistoryRemainingProcessor({
enrichedPayload: data.enrichedPayload,
userId: data.userId,
insuranceId: data.insuranceId!,
formFirstName: data.formFirstName,
formLastName: data.formLastName,
formDob: data.formDob,
});
}
if (jobType === "mh-eligibility-history-check") {
return runEligibilityHistoryProcessor({
enrichedPayload: data.enrichedPayload,
userId: data.userId,
insuranceId: data.insuranceId!,
formFirstName: data.formFirstName,
formLastName: data.formLastName,
formDob: data.formDob,
});
if (jobType === "mh-eligibility-check") {
return runMHEligibilityProcessor(
{
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 === "bcbs-ma-eligibility-check") {
return runBcbsMaEligibilityProcessor(
@@ -1,206 +0,0 @@
/**
* Processor for "cmsp-eligibility-history-remaining-check" jobs.
* Saves eligibility PDF, service history PDF, and accumulator PDF
* to the patient's ELIGIBILITY_STATUS document group.
*/
import fs from "fs/promises";
import path from "path";
import { storage } from "../../storage";
import { emptyFolderContainingFile } from "../../utils/emptyTempFolder";
import forwardToPatientDataExtractorService from "../../services/patientDataExtractorService";
import {
callPythonSync,
splitName,
createOrUpdatePatientByInsuranceId,
memberDetailDemographics,
} from "./_shared";
export interface CmspEligibilityHistoryRemainingProcessorInput {
enrichedPayload: any;
userId: number;
insuranceId: string;
formFirstName?: string;
formLastName?: string;
formDob?: string;
}
export interface CmspEligibilityHistoryRemainingProcessorResult {
patientUpdateStatus?: string;
pdfUploadStatus?: string;
pdfFileId?: number | string | null;
pdfFilename?: string | null;
memberDetailsPdfFileId?: number | string | null;
memberDetailsPdfFilename?: string | null;
historyPdfFileId?: number | string | null;
historyPdfFilename?: string | null;
accumulatorPdfFileId?: number | string | null;
accumulatorPdfFilename?: string | null;
remainingBenefit?: string | null;
thirdPartyInsurance?: string | null;
}
export async function runCmspEligibilityHistoryRemainingProcessor(
input: CmspEligibilityHistoryRemainingProcessorInput
): Promise<CmspEligibilityHistoryRemainingProcessorResult> {
const { enrichedPayload, userId, insuranceId, formFirstName, formLastName, formDob } = input;
const seleniumResult = await callPythonSync("/cmsp-eligibility-history-remaining-check", {
data: enrichedPayload,
});
const outputResult: CmspEligibilityHistoryRemainingProcessorResult = {};
// Extract patient name
const seleniumFirst = seleniumResult.firstName?.trim() || null;
const seleniumLast = seleniumResult.lastName?.trim() || null;
const seleniumName = seleniumResult.name?.trim() || null;
const seleniumInsurance = seleniumResult.insurance?.trim() || null;
const extracted: { firstName?: string | null; lastName?: string | null } = {};
if (seleniumFirst || seleniumLast) {
extracted.firstName = seleniumFirst;
extracted.lastName = seleniumLast;
} else if (seleniumName) {
const parts = splitName(seleniumName);
extracted.firstName = parts.firstName || null;
extracted.lastName = parts.lastName || null;
}
if (!extracted.firstName && !extracted.lastName && seleniumResult?.pdf_path?.endsWith(".pdf")) {
try {
const pdfBuffer = await fs.readFile(seleniumResult.pdf_path);
const extraction = await forwardToPatientDataExtractorService({
buffer: pdfBuffer,
originalname: path.basename(seleniumResult.pdf_path),
mimetype: "application/pdf",
} as any);
if (extraction.name) {
const parts = splitName(extraction.name);
extracted.firstName = parts.firstName || null;
extracted.lastName = parts.lastName || null;
}
} catch (e) {
console.error("[cmspProcessor] PDF name extraction failed:", e);
}
}
const preferFirst = extracted.firstName || formFirstName || null;
const preferLast = extracted.lastName || formLastName || null;
let patient;
try {
patient = await createOrUpdatePatientByInsuranceId({
insuranceId,
firstName: preferFirst,
lastName: preferLast,
dob: formDob,
userId,
});
} catch (e: any) {
throw new Error(`Failed to create/update patient: ${e.message}`);
}
if (patient && patient.id !== undefined) {
// eligibility is null when extraction found no matching row (e.g. the
// AngularJS grid didn't finish rendering in time). Leave status untouched
// in that case rather than forcing UNKNOWN, so a failed run can't clobber
// a correct ACTIVE/INACTIVE status set by another (e.g. concurrent) run.
let newStatus: string | null = null;
if (seleniumResult.eligibility === "Y") newStatus = "ACTIVE";
else if (seleniumResult.eligibility === "N") newStatus = "INACTIVE";
const updates: any = {};
if (newStatus) updates.status = newStatus;
if (seleniumInsurance) updates.insuranceProvider = seleniumInsurance;
Object.assign(updates, memberDetailDemographics(seleniumResult, patient.phone));
const remainingBenefit = seleniumResult.remaining_amount?.trim() || null;
if (remainingBenefit) updates.remainingBenefit = remainingBenefit;
// third_party_insurance is present (even as null) whenever the Third Party
// Liability table was found — null means the member has no 2nd insurance,
// so we still write it to clear any stale value from a prior check.
if (Object.prototype.hasOwnProperty.call(seleniumResult, "third_party_insurance")) {
updates.thirdPartyInsurance = seleniumResult.third_party_insurance?.trim() || null;
}
if (Object.keys(updates).length > 0) {
await storage.updatePatient(patient.id, updates);
}
// Only replace when rows came back — an empty read may just mean the portal
// was slow, and shouldn't wipe history saved by an earlier check.
if (Array.isArray(seleniumResult.service_history) && seleniumResult.service_history.length > 0) {
try {
await storage.replacePatientServiceHistory(patient.id, seleniumResult.service_history);
} catch (e: any) {
console.error("[cmspProcessor] saving service history failed:", e.message);
}
}
outputResult.patientUpdateStatus = newStatus
? `Patient status updated to ${newStatus}`
: "Eligibility unknown — status not changed";
outputResult.remainingBenefit = remainingBenefit;
outputResult.thirdPartyInsurance = updates.thirdPartyInsurance ?? null;
// Helper: save a single PDF to the patient's Cloud Storage Eligibility folder
const patientName = `${patient!.firstName ?? ""} ${patient!.lastName ?? ""}`.trim() || `Patient ${patient!.id}`;
const saveToGroup = async (pdfPath: string): Promise<number | string | null> => {
try {
const buffer = await fs.readFile(pdfPath);
const cloudFile = await storage.savePdfToCloudStorage(
userId,
patient!.id,
patientName,
"Eligibility",
path.basename(pdfPath),
buffer
);
return `cloud:${cloudFile.id}`;
} catch (e: any) {
console.error("[cmspProcessor] saveToGroup failed:", e.message);
return null;
}
};
// Save eligibility PDF
if (seleniumResult.pdf_path?.endsWith(".pdf")) {
outputResult.pdfFileId = await saveToGroup(seleniumResult.pdf_path);
outputResult.pdfFilename = path.basename(seleniumResult.pdf_path);
outputResult.pdfUploadStatus = outputResult.pdfFileId ? "Eligibility PDF saved" : "Eligibility PDF upload failed";
} else {
outputResult.pdfUploadStatus = "No eligibility PDF returned by Selenium";
}
// Save member details PDF
if (seleniumResult.member_details_pdf_path?.endsWith(".pdf")) {
outputResult.memberDetailsPdfFileId = await saveToGroup(seleniumResult.member_details_pdf_path);
outputResult.memberDetailsPdfFilename = path.basename(seleniumResult.member_details_pdf_path);
}
// Save history PDF
if (seleniumResult.history_pdf_path?.endsWith(".pdf")) {
outputResult.historyPdfFileId = await saveToGroup(seleniumResult.history_pdf_path);
outputResult.historyPdfFilename = path.basename(seleniumResult.history_pdf_path);
}
// Save accumulator PDF
if (seleniumResult.accumulator_pdf_path?.endsWith(".pdf")) {
outputResult.accumulatorPdfFileId = await saveToGroup(seleniumResult.accumulator_pdf_path);
outputResult.accumulatorPdfFilename = path.basename(seleniumResult.accumulator_pdf_path);
}
} else {
outputResult.patientUpdateStatus = "Patient not found or missing ID; no update performed";
}
// Cleanup temp files
try {
if (seleniumResult.pdf_path) await emptyFolderContainingFile(seleniumResult.pdf_path);
} catch (e) {
console.error("[cmspProcessor] cleanup failed:", e);
}
return outputResult;
}
@@ -1,169 +0,0 @@
/**
* Processor for "mh-eligibility-history-check" jobs.
* Runs MH eligibility + service history selenium flow and saves both PDFs
* to the patient's ELIGIBILITY_STATUS document group.
*/
import fs from "fs/promises";
import path from "path";
import { storage } from "../../storage";
import { emptyFolderContainingFile } from "../../utils/emptyTempFolder";
import forwardToPatientDataExtractorService from "../../services/patientDataExtractorService";
import {
callPythonSync,
splitName,
createOrUpdatePatientByInsuranceId,
memberDetailDemographics,
} from "./_shared";
export interface EligibilityHistoryProcessorInput {
enrichedPayload: any;
userId: number;
insuranceId: string;
formFirstName?: string;
formLastName?: string;
formDob?: string;
}
export interface EligibilityHistoryProcessorResult {
patientUpdateStatus?: string;
pdfUploadStatus?: string;
pdfFileId?: number | string | null;
pdfFilename?: string | null;
memberDetailsPdfFileId?: number | string | null;
memberDetailsPdfFilename?: string | null;
historyPdfFileId?: number | string | null;
historyPdfFilename?: string | null;
}
export async function runEligibilityHistoryProcessor(
input: EligibilityHistoryProcessorInput
): Promise<EligibilityHistoryProcessorResult> {
const { enrichedPayload, userId, insuranceId, formFirstName, formLastName, formDob } = input;
const seleniumResult = await callPythonSync("/mh-eligibility-history-check", {
data: enrichedPayload,
});
const outputResult: EligibilityHistoryProcessorResult = {};
// Extract patient name
const seleniumFirst = seleniumResult.firstName?.trim() || null;
const seleniumLast = seleniumResult.lastName?.trim() || null;
const seleniumName = seleniumResult.name?.trim() || null;
const seleniumInsurance = seleniumResult.insurance?.trim() || null;
const extracted: { firstName?: string | null; lastName?: string | null } = {};
if (seleniumFirst || seleniumLast) {
extracted.firstName = seleniumFirst;
extracted.lastName = seleniumLast;
} else if (seleniumName) {
const parts = splitName(seleniumName);
extracted.firstName = parts.firstName || null;
extracted.lastName = parts.lastName || null;
}
if (!extracted.firstName && !extracted.lastName && seleniumResult?.pdf_path?.endsWith(".pdf")) {
try {
const pdfBuffer = await fs.readFile(seleniumResult.pdf_path);
const extraction = await forwardToPatientDataExtractorService({
buffer: pdfBuffer,
originalname: path.basename(seleniumResult.pdf_path),
mimetype: "application/pdf",
} as any);
if (extraction.name) {
const parts = splitName(extraction.name);
extracted.firstName = parts.firstName || null;
extracted.lastName = parts.lastName || null;
}
} catch (e) {
console.error("[eligibilityHistoryProcessor] PDF name extraction failed:", e);
}
}
const preferFirst = extracted.firstName || formFirstName || null;
const preferLast = extracted.lastName || formLastName || null;
let patient;
try {
patient = await createOrUpdatePatientByInsuranceId({
insuranceId,
firstName: preferFirst,
lastName: preferLast,
dob: formDob,
userId,
});
} catch (e: any) {
throw new Error(`Failed to create/update patient: ${e.message}`);
}
if (patient && patient.id !== undefined) {
let newStatus = "UNKNOWN";
if (seleniumResult.eligibility === "Y") newStatus = "ACTIVE";
else if (seleniumResult.eligibility === "N") newStatus = "INACTIVE";
const updates: any = { status: newStatus };
if (seleniumInsurance) updates.insuranceProvider = seleniumInsurance;
Object.assign(updates, memberDetailDemographics(seleniumResult, patient.phone));
await storage.updatePatient(patient.id, updates);
outputResult.patientUpdateStatus = `Patient status updated to ${newStatus}`;
// Helper: save a PDF buffer to the patient's Cloud Storage Eligibility folder
const patientName = `${patient!.firstName ?? ""} ${patient!.lastName ?? ""}`.trim() || `Patient ${patient!.id}`;
const saveToGroup = async (pdfPath: string): Promise<number | string | null> => {
try {
const buffer = await fs.readFile(pdfPath);
const cloudFile = await storage.savePdfToCloudStorage(
userId,
patient!.id,
patientName,
"Eligibility",
path.basename(pdfPath),
buffer
);
return `cloud:${cloudFile.id}`;
} catch (e: any) {
console.error("[eligibilityHistoryProcessor] saveToGroup failed:", e.message);
return null;
}
};
// Save eligibility PDF
let eligibilityPdfFileId: number | string | null = null;
if (seleniumResult.pdf_path?.endsWith(".pdf")) {
eligibilityPdfFileId = await saveToGroup(seleniumResult.pdf_path);
outputResult.pdfUploadStatus = eligibilityPdfFileId
? "Eligibility PDF saved"
: "Eligibility PDF upload failed";
outputResult.pdfFilename = path.basename(seleniumResult.pdf_path);
} else {
outputResult.pdfUploadStatus = "No eligibility PDF returned by Selenium";
}
outputResult.pdfFileId = eligibilityPdfFileId;
// Save member details PDF
if (seleniumResult.member_details_pdf_path?.endsWith(".pdf")) {
outputResult.memberDetailsPdfFileId = await saveToGroup(seleniumResult.member_details_pdf_path);
outputResult.memberDetailsPdfFilename = path.basename(seleniumResult.member_details_pdf_path);
}
// Save history PDF
let historyPdfFileId: number | string | null = null;
if (seleniumResult.history_pdf_path?.endsWith(".pdf")) {
historyPdfFileId = await saveToGroup(seleniumResult.history_pdf_path);
outputResult.historyPdfFilename = path.basename(seleniumResult.history_pdf_path);
}
outputResult.historyPdfFileId = historyPdfFileId;
} else {
outputResult.patientUpdateStatus = "Patient not found or missing ID; no update performed";
}
// Cleanup temp files
try {
if (seleniumResult.pdf_path) await emptyFolderContainingFile(seleniumResult.pdf_path);
} catch (e) {
console.error("[eligibilityHistoryProcessor] cleanup failed:", e);
}
return outputResult;
}
@@ -1,180 +0,0 @@
/**
* Processor for "eligibility-check" jobs.
*
* Replicates the logic from routes/insuranceStatus.ts /eligibility-check
* so it can run inside a BullMQ worker without blocking the HTTP server.
*/
import fs from "fs/promises";
import fsSync from "fs";
import path from "path";
import { storage } from "../../storage";
import { emptyFolderContainingFile } from "../../utils/emptyTempFolder";
import forwardToPatientDataExtractorService from "../../services/patientDataExtractorService";
import {
callPythonSync,
splitName,
createOrUpdatePatientByInsuranceId,
} from "./_shared";
export interface EligibilityProcessorInput {
/** Enriched payload (includes credentials) */
enrichedPayload: any;
userId: number;
insuranceId: string;
formFirstName?: string;
formLastName?: string;
formDob?: string;
}
export interface EligibilityProcessorResult {
patientUpdateStatus?: string;
pdfUploadStatus?: string;
pdfFileId?: number | string | null;
patientId?: number | null;
}
export async function runEligibilityProcessor(
input: EligibilityProcessorInput
): Promise<EligibilityProcessorResult> {
const {
enrichedPayload,
userId,
insuranceId,
formFirstName,
formLastName,
formDob,
} = input;
// 1) Call the Python service synchronously (BullMQ worker handles async)
const seleniumResult = await callPythonSync("/eligibility-check", {
data: enrichedPayload,
});
const outputResult: EligibilityProcessorResult = {};
// 3) Extract name: prefer selenium extraction → PDF extractor → form input
// Normalize: treat empty strings from Python the same as null
const seleniumFirst = seleniumResult.firstName?.trim() || null;
const seleniumLast = seleniumResult.lastName?.trim() || null;
const seleniumName = seleniumResult.name?.trim() || null;
const seleniumInsurance = seleniumResult.insurance?.trim() || null;
const extracted: { firstName?: string | null; lastName?: string | null } = {};
if (seleniumFirst || seleniumLast) {
extracted.firstName = seleniumFirst;
extracted.lastName = seleniumLast;
} else if (seleniumName) {
const parts = splitName(seleniumName);
extracted.firstName = parts.firstName || null;
extracted.lastName = parts.lastName || null;
}
if (
!extracted.firstName &&
!extracted.lastName &&
seleniumResult?.pdf_path?.endsWith(".pdf")
) {
try {
const pdfBuffer = await fs.readFile(seleniumResult.pdf_path);
const extraction = await forwardToPatientDataExtractorService({
buffer: pdfBuffer,
originalname: path.basename(seleniumResult.pdf_path),
mimetype: "application/pdf",
} as any);
if (extraction.name) {
const parts = splitName(extraction.name);
extracted.firstName = parts.firstName || null;
extracted.lastName = parts.lastName || null;
}
} catch (e) {
console.error("[eligibilityProcessor] PDF name extraction failed:", e);
}
}
// Final fallback: use form data sent by the frontend
const preferFirst = extracted.firstName || formFirstName || null;
const preferLast = extracted.lastName || formLastName || null;
// 4) Create / update patient
let patient;
try {
patient = await createOrUpdatePatientByInsuranceId({
insuranceId,
firstName: preferFirst,
lastName: preferLast,
dob: formDob,
userId,
});
} catch (e: any) {
throw new Error(`Failed to create/update patient: ${e.message}`);
}
outputResult.patientId = patient?.id ?? null;
// 5) Update patient status
if (patient && patient.id !== undefined) {
let newStatus = "UNKNOWN";
if (seleniumResult.eligibility === "Y") newStatus = "ACTIVE";
else if (seleniumResult.eligibility === "N") newStatus = "INACTIVE";
const updates: any = { status: newStatus };
if (seleniumInsurance) updates.insuranceProvider = seleniumInsurance;
await storage.updatePatient(patient.id, updates);
outputResult.patientUpdateStatus = `Patient status updated to ${newStatus}`;
// Rename the Copy Agent page's temp folder ("PID-<id>") to the real name now that we know
// it — only touches folders still using that placeholder pattern, never a normal patient's.
const patientName = `${patient.firstName ?? ""} ${patient.lastName ?? ""}`.trim() || `Patient ${patient.id}`;
try {
const existingFolder = await storage.getPatientFolder(patient.id);
if (existingFolder && /^PID-\d+$/.test(existingFolder.name) && patientName) {
await storage.updateFolder((existingFolder as any).id, { name: patientName });
}
} catch (e) {
console.error("[eligibilityProcessor] temp folder rename failed:", e);
}
// 6) Save PDF
let createdPdfFileId: number | string | null = null;
if (seleniumResult.pdf_path?.endsWith(".pdf")) {
try {
const pdfBuffer = await fs.readFile(seleniumResult.pdf_path);
const cloudFile = await storage.savePdfToCloudStorage(
userId,
patient.id,
patientName,
"Eligibility",
path.basename(seleniumResult.pdf_path),
pdfBuffer
);
createdPdfFileId = `cloud:${cloudFile.id}`;
outputResult.pdfUploadStatus = "PDF saved to Eligibility folder";
} catch (e: any) {
outputResult.pdfUploadStatus = `PDF upload failed: ${e.message}`;
}
} else {
outputResult.pdfUploadStatus =
"No valid PDF path provided by Selenium; nothing uploaded.";
}
outputResult.pdfFileId = createdPdfFileId;
} else {
outputResult.patientUpdateStatus =
"Patient not found or missing ID; no update performed";
}
// 7) Cleanup temp files
try {
if (seleniumResult.pdf_path) {
await emptyFolderContainingFile(seleniumResult.pdf_path);
}
} catch (e) {
console.error("[eligibilityProcessor] cleanup failed:", e);
}
return outputResult;
}
@@ -0,0 +1,346 @@
/**
* Processor for "mh-eligibility-check" jobs — MassHealth on providers.masshealth-dental.org
* (same DentaQuest portal + persistent-session flow as Tufts SCO).
*/
import fs from "fs/promises";
import fsSync from "fs";
import path from "path";
import { storage } from "../../storage";
import { emptyFolderContainingFile } from "../../utils/emptyTempFolder";
import {
forwardToSeleniumMHEligibilityAgent,
getSeleniumMHSessionStatus,
} from "../../services/seleniumMHEligibilityClient";
import {
splitName,
createOrUpdatePatientByInsuranceId,
imageToPdfBuffer,
memberDetailDemographics,
} 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("mh-processor", `emitted ${event}`, { socketId });
}
} catch (err: any) {
log("mh-processor", `emit failed for ${event}`, { err: err?.message });
}
}
export interface MHEligibilityProcessorInput {
enrichedPayload: any;
userId: number;
insuranceId: string;
formFirstName?: string;
formLastName?: string;
formDob?: string;
socketId?: string;
}
export interface MHEligibilityProcessorResult {
patientUpdateStatus?: string;
pdfUploadStatus?: string;
pdfFileId?: number | string | null;
pdfFilename?: string | null;
patientId?: number | null;
}
async function processMHResult(
userId: number,
insuranceId: string,
formFirstName: string | undefined,
formLastName: string | undefined,
formDob: string | undefined,
seleniumResult: any
): Promise<MHEligibilityProcessorResult> {
const output: MHEligibilityProcessorResult = {};
let createdPdfFileId: number | string | 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;
}
output.patientId = patient.id;
const eligStatus = (seleniumResult?.eligibility ?? "").toLowerCase();
const newStatus =
eligStatus === "active" || eligStatus === "y"
? "ACTIVE"
: eligStatus.includes("active plan not accepted")
? "ACTIVE_PLAN_NOT_ACCEPTED"
: eligStatus.includes("plan not accepted") || eligStatus.includes("plan_not_accepted")
? "PLAN_NOT_ACCEPTED"
: "INACTIVE";
// Plan name from member details, e.g. "MA MassHealth - Adult HSN Limited Wrap".
// Provider routing matches on "masshealth", so only use names that contain it.
const planName =
typeof seleniumResult?.planName === "string" ? seleniumResult.planName.trim() : "";
const remainingBenefit =
typeof seleniumResult?.remainingBenefit === "string"
? seleniumResult.remainingBenefit.trim()
: "";
await storage.updatePatient(patient.id, {
status: newStatus,
insuranceProvider: /masshealth/i.test(planName) ? planName : "MassHealth",
...(remainingBenefit ? { remainingBenefit } : {}),
...memberDetailDemographics(seleniumResult, patient.phone),
});
// Only replace when rows came back — an empty read may just mean the portal
// was slow, and shouldn't wipe history saved by an earlier check.
if (Array.isArray(seleniumResult?.service_history) && seleniumResult.service_history.length > 0) {
try {
await storage.replacePatientServiceHistory(patient.id, seleniumResult.service_history);
} catch (e: any) {
console.error("[mh-processor] saving service history failed:", e.message);
}
}
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("mh-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 = `mh_eligibility_${insuranceId}_${Date.now()}.pdf`;
log("mh-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 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) {
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("mh-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(
`MH polling timeout (${Math.round(pollTimeoutMs / 1000)}s) for session ${sessionId}`
);
}
try {
const st = await getSeleniumMHSessionStatus(sessionId);
const status: string = st?.status ?? "unknown";
log("mh-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: st?.message || "OTP required. Please enter the verification code.",
});
await new Promise((r) => setTimeout(r, pollIntervalMs));
continue;
}
if (status === "completed") {
log("mh-processor", "session completed", { sessionId });
return st.result;
}
if (status === "error" || status === "not_found") {
const terminalErr: any = new Error(st?.message || `MH 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 MH session ${sessionId}`
);
}
const backoff = Math.min(30_000, 500 * Math.pow(2, transientErrors - 1));
log("mh-processor", `transient error #${transientErrors}, backoff ${backoff}ms`, {
err: err?.message,
});
await new Promise((r) => setTimeout(r, backoff));
}
}
throw new Error(`MH polling exhausted all attempts for session ${sessionId}`);
}
export async function runMHEligibilityProcessor(
input: MHEligibilityProcessorInput,
jobId: string
): Promise<MHEligibilityProcessorResult> {
const {
enrichedPayload,
userId,
insuranceId,
formFirstName,
formLastName,
formDob,
socketId,
} = input;
log("mh-processor", "starting Python agent session", { insuranceId });
const agentResp = await forwardToSeleniumMHEligibilityAgent(enrichedPayload);
if (!agentResp?.session_id) {
throw new Error("Python agent did not return a session_id for MH eligibility");
}
const sessionId = agentResp.session_id as string;
log("mh-processor", "got session_id", { sessionId });
emitToSocket(socketId, "selenium:mh_session_started", {
session_id: sessionId,
jobId,
});
const seleniumResult = await pollUntilDone(sessionId, socketId, jobId);
if (!seleniumResult || seleniumResult.status === "error") {
throw new Error(seleniumResult?.message ?? "MH session returned an error result");
}
log("mh-processor", "processing DB result", { insuranceId });
const result = await processMHResult(
userId,
insuranceId,
formFirstName,
formLastName,
formDob,
seleniumResult
);
log("mh-processor", "done", { result });
return result;
}
+1 -3
View File
@@ -3,7 +3,6 @@ import { redisConnection } from "./connection";
/** Job types dispatched to the selenium Python worker. */
export type SeleniumJobType =
| "eligibility-check"
| "claim-status-check"
| "claim-submit"
| "claim-pre-auth"
@@ -26,8 +25,7 @@ export type SeleniumJobType =
| "uniteddh-preauth-submit"
| "tuftssco-preauth-submit"
| "tuftssco-eligibility-check"
| "mh-eligibility-history-check"
| "cmsp-eligibility-history-remaining-check"
| "mh-eligibility-check"
| "bcbs-ma-eligibility-check"
| "metlife-eligibility-check"
| "altus-eligibility-check"
@@ -2,7 +2,6 @@ import { Worker, Job } from "bullmq";
import { redisConnection } from "../connection";
import { SeleniumJobData } from "../queues";
import { io } from "../../socket";
import { runEligibilityProcessor } from "../processors/eligibilityProcessor";
import { runClaimStatusProcessor } from "../processors/claimStatusProcessor";
import { runClaimSubmitProcessor } from "../processors/claimSubmitProcessor";
@@ -37,16 +36,7 @@ async function processSeleniumJob(job: Job<SeleniumJobData>) {
try {
let result: any;
if (jobType === "eligibility-check") {
result = await runEligibilityProcessor({
enrichedPayload,
userId,
insuranceId: job.data.insuranceId!,
formFirstName: job.data.formFirstName,
formLastName: job.data.formLastName,
formDob: job.data.formDob,
});
} else if (jobType === "claim-status-check") {
if (jobType === "claim-status-check") {
result = await runClaimStatusProcessor({
enrichedPayload,
insuranceId: job.data.insuranceId!,
+2
View File
@@ -18,6 +18,7 @@ import insuranceStatusDeltaInsRoutes from "./insuranceStatusDeltaIns";
import insuranceStatusUnitedSCORoutes from "./insuranceStatusUnitedSCO";
import insuranceStatusUnitedUcardRoutes from "./insuranceStatusUnitedUcard";
import insuranceStatusTuftsSCORoutes from "./insuranceStatusTuftsSCO";
import insuranceStatusMHRoutes from "./insuranceStatusMH";
import insuranceStatusCCARoutes from "./insuranceStatusCCA";
import insuranceStatusCCAClaimRoutes from "./insuranceStatusCCAClaim";
import insuranceStatusCCAPreAuthRoutes from "./insuranceStatusCCAPreAuth";
@@ -79,6 +80,7 @@ router.use("/insurance-status-deltaindiv", insuranceStatusDeltaIndivRoutes);
router.use("/insurance-status-unitedsco", insuranceStatusUnitedSCORoutes);
router.use("/insurance-status-uniteducard", insuranceStatusUnitedUcardRoutes);
router.use("/insurance-status-tuftssco", insuranceStatusTuftsSCORoutes);
router.use("/insurance-status-mh", insuranceStatusMHRoutes);
router.use("/insurance-status-cca", insuranceStatusCCARoutes);
router.use("/insurance-status-bcbs-ma", insuranceStatusBcbsMaRoutes);
router.use("/insurance-status-metlife", insuranceStatusMetLifeRoutes);
+52 -350
View File
@@ -1,7 +1,7 @@
import { Router } from "express";
import { Request, Response } from "express";
import { storage } from "../storage";
import { forwardToSeleniumInsuranceEligibilityAgent } from "../services/seleniumInsuranceEligibilityClient";
import { runMHEligibilityProcessor } from "../queue/processors/mhEligibilityProcessor";
import fs from "fs/promises";
import path from "path";
import PDFDocument from "pdfkit";
@@ -113,160 +113,6 @@ async function createOrUpdatePatientByInsuranceId(options: {
}
}
/**
* /eligibility-check
* - run selenium
* - if pdf created -> call extractor -> get name
* - create or update patient (by memberId)
* - attach PDF to patient (create pdf group/file)
* - return { patient, pdfFileId, extractedName ... }
*/
router.post(
"/eligibility-check",
async (req: Request, res: Response): Promise<any> => {
if (!req.body.data) {
return res
.status(400)
.json({ error: "Missing Insurance Eligibility data for selenium" });
}
if (!req.user || !req.user.id) {
return res.status(401).json({ error: "Unauthorized: user info missing" });
}
const insuranceEligibilityData =
typeof req.body.data === "string"
? JSON.parse(req.body.data)
: req.body.data;
const credentials = await storage.getInsuranceCredentialByUserAndSiteKey(
req.user.id,
insuranceEligibilityData.insuranceSiteKey
);
if (!credentials) {
return res.status(404).json({
error:
"No insurance credentials found for this provider, Kindly Update this at Settings Page.",
});
}
const insuranceId = String(insuranceEligibilityData.memberId ?? "").trim();
if (!insuranceId) {
return res.status(400).json({ error: "Missing memberId" });
}
const enrichedData = {
...insuranceEligibilityData,
massdhpUsername: credentials.username,
massdhpPassword: credentials.password,
};
const job = await seleniumQueue.add("eligibility-check", {
jobType: "eligibility-check",
userId: req.user.id,
socketId: req.body.socketId,
enrichedPayload: enrichedData,
insuranceId,
formFirstName: insuranceEligibilityData.firstName,
formLastName: insuranceEligibilityData.lastName,
formDob: insuranceEligibilityData.dateOfBirth,
});
return res.json({ jobId: job.id, status: "queued" });
}
);
router.post(
"/eligibility-history-check",
async (req: Request, res: Response): Promise<any> => {
if (!req.body.data) {
return res.status(400).json({ error: "Missing Insurance Eligibility data for selenium" });
}
if (!req.user || !req.user.id) {
return res.status(401).json({ error: "Unauthorized: user info missing" });
}
const data =
typeof req.body.data === "string" ? JSON.parse(req.body.data) : req.body.data;
const credentials = await storage.getInsuranceCredentialByUserAndSiteKey(req.user.id, "MH");
if (!credentials) {
return res.status(404).json({
error: "No MassHealth credentials found. Please update them in Settings.",
});
}
const insuranceId = String(data.memberId ?? "").trim();
if (!insuranceId) {
return res.status(400).json({ error: "Missing memberId" });
}
const enrichedData = {
...data,
massdhpUsername: credentials.username,
massdhpPassword: credentials.password,
};
const jobId = enqueueSeleniumJob({
jobType: "mh-eligibility-history-check",
userId: req.user.id,
socketId: req.body.socketId,
enrichedPayload: enrichedData,
insuranceId,
formFirstName: data.firstName,
formLastName: data.lastName,
formDob: data.dateOfBirth,
});
return res.json({ jobId, status: "queued" });
}
);
router.post(
"/cmsp-eligibility-history-remaining-check",
async (req: Request, res: Response): Promise<any> => {
if (!req.body.data) {
return res.status(400).json({ error: "Missing data for selenium" });
}
if (!req.user || !req.user.id) {
return res.status(401).json({ error: "Unauthorized: user info missing" });
}
const data =
typeof req.body.data === "string" ? JSON.parse(req.body.data) : req.body.data;
const credentials = await storage.getInsuranceCredentialByUserAndSiteKey(req.user.id, "MH");
if (!credentials) {
return res.status(404).json({
error: "No MassHealth credentials found. Please update them in Settings.",
});
}
const insuranceId = String(data.memberId ?? "").trim();
if (!insuranceId) {
return res.status(400).json({ error: "Missing memberId" });
}
const enrichedData = {
...data,
massdhpUsername: credentials.username,
massdhpPassword: credentials.password,
};
const jobId = enqueueSeleniumJob({
jobType: "cmsp-eligibility-history-remaining-check",
userId: req.user.id,
socketId: req.body.socketId,
enrichedPayload: enrichedData,
insuranceId,
formFirstName: data.firstName,
formLastName: data.lastName,
formDob: data.dateOfBirth,
});
return res.json({ jobId, status: "queued" });
}
);
router.post(
"/claim-status-check",
async (req: Request, res: Response): Promise<any> => {
@@ -333,11 +179,7 @@ router.post(
return res.status(401).json({ error: "Unauthorized: user info missing" });
}
// Track any paths that couldn't be cleaned immediately so we can try again at the end
const remainingCleanupPaths = new Set<string>();
try {
// 1) fetch appointments for the day (reuse your storage API)
const allDayAppointments = await storage.getAppointmentsByDateForUser(
date,
req.user.id
@@ -353,13 +195,15 @@ router.post(
? allDayAppointments.filter((a) => staffIdFilter.has(Number(a.staffId)))
: allDayAppointments;
const credentials = await storage.getInsuranceCredentialByUserAndSiteKey(
req.user.id,
"MH"
);
const results: Array<any> = [];
// process sequentially so selenium agent / python semaphore isn't overwhelmed
// Sequential: the MH portal runs in one persistent browser
for (const apt of dayAppointments) {
// For each appointment we keep a per-appointment seleniumResult so we can cleanup its files
let seleniumResult: any = undefined;
const resultItem: any = {
appointmentId: apt.id,
patientId: apt.patientId ?? null,
@@ -370,20 +214,17 @@ router.post(
warning: null,
};
const aptLabel = `appointment#${apt.id}${apt.date ? ` (${apt.date}${apt.startTime ? ` ${apt.startTime}` : ""})` : ""}`;
try {
// fetch patient record (use getPatient or getPatientById depending on your storage)
const patient = apt.patientId
? await storage.getPatient(apt.patientId)
: null;
const memberId = (patient?.insuranceId ?? "").toString().trim();
// create a readable patient label for error messages
const patientLabel = patient
? `${patient.firstName ?? ""} ${patient.lastName ?? ""}`.trim() ||
`patient#${patient.id}`
: `patient#${apt.patientId ?? "unknown"}`;
const aptLabel = `appointment#${apt.id}${apt.date ? ` (${apt.date}${apt.startTime ? ` ${apt.startTime}` : ""})` : ""}`;
const memberId = (patient?.insuranceId ?? "").toString().trim();
if (!memberId) {
resultItem.error = `Missing insuranceId for ${patientLabel} — skipping ${aptLabel}`;
@@ -391,225 +232,86 @@ router.post(
continue;
}
// prepare eligibility data; prefer patient DOB + name if present
const dob = patient?.dateOfBirth;
if (!dob) {
resultItem.error = `Missing dob for ${patientLabel} — skipping ${aptLabel}`;
results.push(resultItem);
continue;
}
// Convert Date object → YYYY-MM-DD string - req for selenium agent.
const dobStr = formatDobForAgent(dob);
const dobStr = patient?.dateOfBirth ? formatDobForAgent(patient.dateOfBirth) : null;
if (!dobStr) {
resultItem.error = `Invalid or missing DOB for ${patientLabel} — skipping ${aptLabel}`;
results.push(resultItem);
continue;
}
const payload = {
memberId,
dateOfBirth: dobStr,
insuranceSiteKey: "MH",
};
// Get credentials for this user+site
const credentials =
await storage.getInsuranceCredentialByUserAndSiteKey(
req.user.id,
payload.insuranceSiteKey
);
if (!credentials) {
resultItem.error = `No insurance credentials found for siteKey — skipping ${aptLabel} for ${patientLabel}`;
resultItem.error = `No MassHealth credentials found — skipping ${aptLabel} for ${patientLabel}`;
results.push(resultItem);
continue;
}
// enrich payload
const enriched = {
...payload,
massdhpUsername: credentials.username,
massdhpPassword: credentials.password,
};
// forward to selenium agent (sequential)
let mhResult;
try {
seleniumResult =
await forwardToSeleniumInsuranceEligibilityAgent(enriched);
mhResult = await runMHEligibilityProcessor(
{
enrichedPayload: {
memberId,
dateOfBirth: dobStr,
insuranceSiteKey: "MH",
mhUsername: credentials.username,
mhPassword: credentials.password,
otpEmail: credentials.otpContact ?? null,
otpEmailPassword: credentials.otpContactPassword ?? null,
},
userId: req.user.id,
insuranceId: memberId,
formFirstName: patient?.firstName ?? undefined,
formLastName: patient?.lastName ?? undefined,
formDob: dobStr,
},
`batch-${apt.id}`
);
} catch (seleniumErr: any) {
resultItem.error = `Selenium agent failed for ${patientLabel} (${aptLabel}): ${seleniumErr?.message ?? String(seleniumErr)}`;
results.push(resultItem);
continue;
}
// Attempt extraction (if pdf_path present)
const extracted: any = {};
if (
seleniumResult?.pdf_path &&
seleniumResult.pdf_path.endsWith(".pdf")
) {
resultItem.patientUpdateStatus = mhResult.patientUpdateStatus ?? null;
resultItem.pdfFileId = mhResult.pdfFileId ?? null;
if (mhResult.pdfUploadStatus && !mhResult.pdfFileId) {
resultItem.warning = mhResult.pdfUploadStatus;
}
// Mirror the patient's new status onto the appointment (appointments page badge)
const updatedPatient = await storage.getPatientByInsuranceId(memberId);
if (updatedPatient?.status) {
try {
const pdfPath = seleniumResult.pdf_path;
const pdfBuffer = await fs.readFile(pdfPath);
const extraction = await forwardToPatientDataExtractorService({
buffer: pdfBuffer,
originalname: path.basename(pdfPath),
mimetype: "application/pdf",
} as any);
if (extraction.name) {
const parts = splitName(extraction.name);
extracted.firstName = parts.firstName;
extracted.lastName = parts.lastName;
}
} catch (extractErr: any) {
resultItem.warning = `Extraction failed: ${extractErr?.message ?? String(extractErr)}`;
await storage.updateAppointment(Number(apt.id), {
eligibilityStatus: updatedPatient.status as any,
});
resultItem.appointmentUpdateStatus = `Appointment eligibility set to ${updatedPatient.status}`;
} catch (apptUpdateErr: any) {
resultItem.warning =
(resultItem.warning ? resultItem.warning + " | " : "") +
`Failed to update appointment eligibility: ${apptUpdateErr?.message ?? String(apptUpdateErr)}`;
}
}
// create or update patient by insuranceId — prefer extracted name
const preferFirst = extracted.firstName ?? null;
const preferLast = extracted.lastName ?? null;
try {
await createOrUpdatePatientByInsuranceId({
insuranceId: memberId,
firstName: preferFirst,
lastName: preferLast,
dob: payload.dateOfBirth,
userId: req.user.id,
});
} catch (patientOpErr: any) {
resultItem.error = `Failed to create/update patient ${patientLabel} for ${aptLabel}: ${patientOpErr?.message ?? String(patientOpErr)}`;
results.push(resultItem);
continue;
}
// fetch patient again
const updatedPatient =
await storage.getPatientByInsuranceId(memberId);
if (!updatedPatient || !updatedPatient.id) {
resultItem.error = `Patient not found after create/update for ${patientLabel} (${aptLabel})`;
results.push(resultItem);
continue;
}
// Update patient status based on seleniumResult.eligibility
const newStatus =
seleniumResult?.eligibility === "Y" ? "ACTIVE" : "INACTIVE";
// 1. updating patient
await storage.updatePatient(updatedPatient.id, { status: newStatus });
resultItem.patientUpdateStatus = `Patient status updated to ${newStatus}`;
// 2. updating appointment status - for aptmnt page
try {
await storage.updateAppointment(Number(apt.id), {
eligibilityStatus: newStatus,
});
resultItem.appointmentUpdateStatus = `Appointment eligibility set to ${newStatus}`;
} catch (apptUpdateErr: any) {
resultItem.warning =
(resultItem.warning ? resultItem.warning + " | " : "") +
`Failed to update appointment eligibility: ${apptUpdateErr?.message ?? String(apptUpdateErr)}`;
}
// If PDF exists, upload to PdfGroup (ELIGIBILITY_STATUS)
if (
seleniumResult?.pdf_path &&
seleniumResult.pdf_path.endsWith(".pdf")
) {
try {
const pdfBuf = await fs.readFile(seleniumResult.pdf_path);
const patientName = `${updatedPatient.firstName ?? ""} ${updatedPatient.lastName ?? ""}`.trim();
const cloudFile = await storage.savePdfToCloudStorage(
req.user.id,
updatedPatient.id,
patientName || `Patient ${updatedPatient.id}`,
"Eligibility",
path.basename(seleniumResult.pdf_path),
pdfBuf
);
resultItem.pdfFileId = `cloud:${cloudFile.id}`;
resultItem.processed = true;
} catch (pdfErr: any) {
resultItem.warning = `PDF upload failed for ${patientLabel} (${aptLabel}): ${pdfErr?.message ?? String(pdfErr)}`;
}
} else {
// no pdf; still mark processed true (status updated)
resultItem.processed = true;
resultItem.pdfFileId = null;
}
resultItem.processed = true;
results.push(resultItem);
} catch (err: any) {
resultItem.error = `Unexpected error for appointment#${apt.id}: ${err?.message ?? String(err)}`;
results.push(resultItem);
console.error(
"[batch eligibility] unexpected error for appointment",
apt.id,
err
);
} finally {
// Per-appointment cleanup: always try to remove selenium temp files for this appointment
try {
if (
seleniumResult &&
(seleniumResult.pdf_path || seleniumResult.ss_path)
) {
// prefer pdf_path, fallback to ss_path
const candidatePath =
seleniumResult.pdf_path ?? seleniumResult.ss_path;
try {
await emptyFolderContainingFile(candidatePath);
} catch (cleanupErr: any) {
console.warn(
`[batch cleanup] failed to clean ${candidatePath} for appointment ${apt.id}`,
cleanupErr
);
// remember path for final cleanup attempt
remainingCleanupPaths.add(candidatePath);
}
}
} catch (cleanupOuterErr: any) {
console.warn(
"[batch cleanup] unexpected error during per-appointment cleanup",
cleanupOuterErr
);
// don't throw — we want to continue processing next appointments
}
} // end try/catch/finally per appointment
} // end for appointments
}
}
// return summary
return res.json({ date, count: results.length, results });
} catch (err: any) {
console.error("[check-all-eligibilities] error", err);
return res
.status(500)
.json({ error: err?.message ?? "Internal server error" });
} finally {
// Final cleanup attempt for any remaining paths we couldn't delete earlier
try {
if (remainingCleanupPaths.size > 0) {
for (const p of remainingCleanupPaths) {
try {
await emptyFolderContainingFile(p);
} catch (finalCleanupErr: any) {
console.error(`[final cleanup] failed for ${p}`, finalCleanupErr);
}
}
}
} catch (outerFinalErr: any) {
console.error(
"[check-all-eligibilities final cleanup] unexpected error",
outerFinalErr
);
}
}
}
);
@@ -0,0 +1,116 @@
/**
* MassHealth eligibility — providers.masshealth-dental.org.
* Same DentaQuest portal as Tufts SCO: persistent browser session in the Python
* agent, OTP only when the portal asks for it.
*/
import { Router, Request, Response } from "express";
import { storage } from "../storage";
import { forwardOtpToSeleniumMHAgent } from "../services/seleniumMHEligibilityClient";
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(
"/mh-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 insuranceId = String(rawData.memberId ?? "").trim();
if (!insuranceId) {
return res.status(400).json({ error: "Missing memberId" });
}
const credentials = await storage.getInsuranceCredentialByUserAndSiteKey(req.user.id, "MH");
if (!credentials) {
return res.status(404).json({
error: "No MassHealth credentials found. Please add them on the Settings page.",
});
}
const enrichedData = {
...rawData,
insuranceSiteKey: "MH",
mhUsername: credentials.username,
mhPassword: credentials.password,
otpEmail: credentials.otpContact ?? null,
otpEmailPassword: credentials.otpContactPassword ?? null,
};
const jobId = enqueueSeleniumJob({
jobType: "mh-eligibility-check",
userId: req.user.id,
socketId: req.body.socketId,
enrichedPayload: enrichedData,
insuranceId,
formFirstName: rawData.firstName,
formLastName: rawData.lastName,
formDob: rawData.dateOfBirth,
});
log("mh-route", "job enqueued", { jobId, insuranceId });
return res.json({ status: "queued", jobId });
} catch (err: any) {
console.error("[mh-route] enqueue failed:", err);
return res.status(500).json({
error: err.message || "Failed to enqueue MassHealth 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 forwardOtpToSeleniumMHAgent(sessionId, otp);
emitSafe(socketId, "selenium:otp_submitted", {
session_id: sessionId,
result: r,
});
return res.json(r);
} catch (err: any) {
console.error(
"[mh-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;
@@ -1,27 +0,0 @@
import axios from "axios";
export interface SeleniumPayload {
data: any;
}
export async function forwardToSeleniumInsuranceEligibilityAgent(
insuranceEligibilityData: any
): Promise<any> {
const payload: SeleniumPayload = {
data: insuranceEligibilityData,
};
const result = await axios.post(
"http://localhost:5002/eligibility-check",
payload
);
if (result.data.status === "error") {
const errorMsg =
typeof result.data.message === "string"
? result.data.message
: result.data.message?.msg || "Selenium agent error";
throw new Error(errorMsg);
}
return result.data;
}
@@ -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(`[mh-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(`[mh-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 forwardToSeleniumMHEligibilityAgent(data: any): Promise<any> {
const payload = { data };
const url = `/mh-eligibility`;
log("mh-client", "POST mh-eligibility", { url: SELENIUM_AGENT_BASE + url });
const r = await requestWithRetries({ url, method: "POST", data: payload }, 4);
log("mh-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 forwardOtpToSeleniumMHAgent(sessionId: string, otp: string): Promise<any> {
const url = `/submit-otp`;
log("mh-client", "POST submit-otp", { url: SELENIUM_AGENT_BASE + url, sessionId });
const r = await requestWithRetries({ url, method: "POST", data: { session_id: sessionId, otp } }, 4);
log("mh-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 getSeleniumMHSessionStatus(sessionId: string): Promise<any> {
const url = `/session/${sessionId}/status`;
log("mh-client", "GET session status", { url: SELENIUM_AGENT_BASE + url, sessionId });
const r = await requestWithRetries({ url, method: "GET" }, 4);
log("mh-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;
}
@@ -51,6 +51,8 @@ function getVisuals(status: PatientStatus): { label: string; bg: string } {
return { label: "Inactive", bg: "#DC2626" };
case "PLAN_NOT_ACCEPTED":
return { label: "Plan Not Accepted", bg: "#F59E0B" }; // amber
case "ACTIVE_PLAN_NOT_ACCEPTED":
return { label: "Active / Plan Not Accepted", bg: "#0D9488" }; // teal
default:
return { label: "Unknown", bg: "#6B7280" };
}
@@ -0,0 +1,373 @@
import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { CheckCircle, LoaderCircleIcon, X } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useAppDispatch } from "@/redux/hooks";
import { setTaskStatus } from "@/redux/slices/seleniumTaskSlice";
import { formatLocalDate } from "@/utils/dateUtils";
import { socket } from "@/lib/socket";
import { QK_PATIENTS_BASE } from "@/components/patients/patient-table";
// ─── OTP Modal ────────────────────────────────────────────────────────────────
interface MHOtpModalProps {
open: boolean;
onClose: () => void;
onSubmit: (otp: string) => Promise<void> | void;
isSubmitting: boolean;
message?: string;
}
function MHOtpModal({ open, onClose, onSubmit, isSubmitting, message }: MHOtpModalProps) {
const [otp, setOtp] = useState("");
useEffect(() => {
if (!open) setOtp("");
}, [open]);
if (!open) return null;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!otp.trim()) return;
await onSubmit(otp.trim());
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
<div className="bg-white dark:bg-slate-900 rounded-xl shadow-lg w-full max-w-md p-6">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold">Enter OTP</h2>
<button type="button" onClick={onClose} className="text-slate-500 hover:text-slate-800">
<X className="w-4 h-4" />
</button>
</div>
<p className="text-sm text-slate-500 mb-4">
{message ||
"We need the verification code sent to your phone or email to complete this check."}
</p>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="mh-otp">Verification Code</Label>
<Input
id="mh-otp"
placeholder="Enter verification code"
value={otp}
onChange={(e) => setOtp(e.target.value)}
autoFocus
/>
</div>
<div className="flex justify-end gap-3">
<Button type="button" variant="outline" onClick={onClose} disabled={isSubmitting}>
Cancel
</Button>
<Button type="submit" disabled={isSubmitting || !otp.trim()}>
{isSubmitting ? (
<>
<LoaderCircleIcon className="w-4 h-4 mr-2 animate-spin" />
Submitting...
</>
) : (
"Submit Code"
)}
</Button>
</div>
</form>
</div>
</div>
);
}
// ─── Main component ───────────────────────────────────────────────────────────
interface MHEligibilityButtonProps {
memberId: string;
dateOfBirth: Date | null;
firstName?: string;
lastName?: string;
isFormIncomplete: boolean;
autoTrigger?: boolean;
onAutoTriggered?: () => void;
onPdfReady: (pdfId: number | string, fallbackFilename: string | null) => void;
/** Called with the job result (patientId, pdfFileId, …) when the check succeeds. */
onComplete?: (result: any) => void;
}
export function MHEligibilityButton({
memberId,
dateOfBirth,
firstName,
lastName,
isFormIncomplete,
autoTrigger,
onAutoTriggered,
onPdfReady,
onComplete,
}: MHEligibilityButtonProps) {
const { toast } = useToast();
const dispatch = useAppDispatch();
const sessionIdRef = useRef<string | null>(null);
const autoTriggeredRef = useRef(false);
const [otpModalOpen, setOtpModalOpen] = useState(false);
const [otpMessage, setOtpMessage] = useState("");
const [isStarting, setIsStarting] = useState(false);
const [isSubmittingOtp, setIsSubmittingOtp] = useState(false);
const handleStart = async () => {
if (!memberId || !dateOfBirth) {
toast({
title: "Missing fields",
description: "Member ID and Date of Birth are required.",
variant: "destructive",
});
return;
}
const formattedDob = formatLocalDate(dateOfBirth);
const payload = {
memberId,
dateOfBirth: formattedDob,
firstName,
lastName,
insuranceSiteKey: "MH",
};
setIsStarting(true);
try {
dispatch(
setTaskStatus({
key: "eligibilityCheck",
status: "pending",
message: "Starting MassHealth eligibility check…",
})
);
const response = await apiRequest(
"POST",
"/api/insurance-status-mh/mh-eligibility",
{ data: JSON.stringify(payload), socketId: socket.id }
);
const result = await response.json();
if (!response.ok || result.error) {
throw new Error(result.error || `Server error (${response.status})`);
}
const jobId: string = result.jobId;
if (!jobId) throw new Error("No jobId returned from server");
dispatch(
setTaskStatus({
key: "eligibilityCheck",
status: "pending",
message: "MassHealth job queued. Waiting for browser session…",
})
);
const onSessionStarted = (data: any) => {
if (String(data?.jobId) !== String(jobId)) return;
sessionIdRef.current = data.session_id ?? null;
dispatch(
setTaskStatus({
key: "eligibilityCheck",
status: "pending",
message: "Browser session started. Waiting for verification code or result…",
})
);
};
const onOtpRequired = (data: any) => {
if (String(data?.jobId) !== String(jobId)) return;
if (data.session_id) sessionIdRef.current = data.session_id;
setOtpMessage(typeof data?.message === "string" ? data.message : "");
setOtpModalOpen(true);
dispatch(
setTaskStatus({
key: "eligibilityCheck",
status: "pending",
message: data?.message || "Verification code required. Please enter the code.",
})
);
};
const onOtpSubmitted = (data: any) => {
if (data?.session_id && data.session_id !== sessionIdRef.current) return;
dispatch(
setTaskStatus({
key: "eligibilityCheck",
status: "pending",
message: "Code submitted. Finishing eligibility check…",
})
);
};
socket.on("selenium:mh_session_started", onSessionStarted);
socket.on("selenium:otp_required", onOtpRequired);
socket.on("selenium:otp_submitted", onOtpSubmitted);
function cleanup() {
clearTimeout(safetyTimer);
socket.off("selenium:mh_session_started", onSessionStarted);
socket.off("selenium:otp_required", onOtpRequired);
socket.off("selenium:otp_submitted", onOtpSubmitted);
socket.off("job:update", onJobUpdate);
}
const onJobUpdate = (data: any) => {
if (String(data?.jobId) !== String(jobId)) return;
if (data.status === "active") {
dispatch(
setTaskStatus({
key: "eligibilityCheck",
status: "pending",
message: data.message ?? "Selenium browser starting…",
})
);
return;
}
cleanup();
if (data.status === "completed") {
dispatch(
setTaskStatus({
key: "eligibilityCheck",
status: "success",
message: "MassHealth eligibility updated and PDF attached to patient documents.",
})
);
toast({
title: "MassHealth eligibility complete",
description: "Patient status was updated and the eligibility PDF was saved.",
});
queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
onComplete?.(data.result ?? {});
const pdfId = data.result?.pdfFileId;
if (pdfId) {
onPdfReady(pdfId, data.result?.pdfFilename ?? `mh_eligibility_${memberId}.pdf`);
}
} else if (data.status === "failed") {
const msg = data.error ?? "MassHealth eligibility job failed.";
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "error", message: msg }));
toast({ title: "MassHealth selenium error", description: msg, variant: "destructive" });
}
setIsStarting(false);
setOtpModalOpen(false);
};
socket.on("job:update", onJobUpdate);
const safetyTimer = setTimeout(() => {
cleanup();
setIsStarting(false);
setOtpModalOpen(false);
dispatch(
setTaskStatus({
key: "eligibilityCheck",
status: "error",
message: "MassHealth job timed out waiting for completion.",
})
);
}, 6 * 60 * 1000);
} catch (err: any) {
console.error("MHEligibilityButton error:", err);
dispatch(
setTaskStatus({
key: "eligibilityCheck",
status: "error",
message: err?.message || "Failed to start MassHealth eligibility",
})
);
toast({
title: "MassHealth selenium error",
description: err?.message || "Failed to start MassHealth eligibility",
variant: "destructive",
});
setIsStarting(false);
}
};
const handleSubmitOtp = async (otp: string) => {
const sessionId = sessionIdRef.current;
if (!sessionId) {
toast({
title: "Session not ready",
description: "Cannot submit code — session ID is not available yet.",
variant: "destructive",
});
return;
}
try {
setIsSubmittingOtp(true);
const resp = await apiRequest("POST", "/api/insurance-status-mh/selenium/submit-otp", {
session_id: sessionId,
otp,
socketId: socket.id,
});
const data = await resp.json();
if (!resp.ok || data.error) {
throw new Error(data.error || "Failed to submit code");
}
setOtpModalOpen(false);
} catch (err: any) {
console.error("handleSubmitOtp error:", err);
toast({
title: "Failed to submit code",
description: err?.message || "Error forwarding code to selenium agent",
variant: "destructive",
});
} finally {
setIsSubmittingOtp(false);
}
};
useEffect(() => {
if (!autoTrigger) { autoTriggeredRef.current = false; return; }
if (autoTriggeredRef.current || isFormIncomplete) return;
autoTriggeredRef.current = true;
onAutoTriggered?.();
handleStart();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [autoTrigger, isFormIncomplete]);
return (
<>
<Button
className="w-full"
variant="default"
disabled={isFormIncomplete || isStarting}
onClick={handleStart}
>
{isStarting ? (
<>
<LoaderCircleIcon className="h-4 w-4 mr-2 animate-spin" />
Processing...
</>
) : (
<>
<CheckCircle className="h-4 w-4 mr-2" />
MH
</>
)}
</Button>
<MHOtpModal
open={otpModalOpen}
onClose={() => setOtpModalOpen(false)}
onSubmit={handleSubmitOtp}
isSubmitting={isSubmittingOtp}
message={otpMessage}
/>
</>
);
}
@@ -454,6 +454,7 @@ export const PatientForm = forwardRef<PatientFormRef, PatientFormProps>(
) as PatientStatus[]; // ['ACTIVE','INACTIVE','UNKNOWN']
const toLabel = (v: PatientStatus) => {
if (v === "PLAN_NOT_ACCEPTED") return "Plan Not Accepted";
if (v === "ACTIVE_PLAN_NOT_ACCEPTED") return "Active / Plan Not Accepted";
return v[0] + v.slice(1).toLowerCase();
};
@@ -1160,6 +1160,12 @@ export function PatientTable({
Plan Not Accepted
</span>
)}
{patient.status === "ACTIVE_PLAN_NOT_ACCEPTED" && (
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-teal-100 text-teal-800">
Active / Plan Not Accepted
</span>
)}
</div>
{patient.updatedAt && (
<div className="text-xs text-gray-500 mt-1">
@@ -1312,13 +1318,17 @@ export function PatientTable({
? "text-red-600"
: currentPatient.status === "PLAN_NOT_ACCEPTED"
? "text-amber-600"
: "text-gray-600",
: currentPatient.status === "ACTIVE_PLAN_NOT_ACCEPTED"
? "text-teal-600"
: "text-gray-600",
"font-medium"
)}
>
{currentPatient.status === "PLAN_NOT_ACCEPTED"
? "Plan Not Accepted"
: currentPatient.status
: currentPatient.status === "ACTIVE_PLAN_NOT_ACCEPTED"
? "Active / Plan Not Accepted"
: currentPatient.status
? currentPatient.status.charAt(0).toUpperCase() +
currentPatient.status.slice(1).toLowerCase()
: "Unknown"}
@@ -12,6 +12,8 @@ type CredentialFormProps = {
siteKey: string;
username: string;
password: string;
otpContact?: string | null;
otpContactPassword?: string | null;
};
};
@@ -34,7 +36,10 @@ export function CredentialForm({ onClose, userId, defaultValues }: CredentialFor
const [siteKey, setSiteKey] = useState(defaultValues?.siteKey || "");
const [username, setUsername] = useState(defaultValues?.username || "");
const [password, setPassword] = useState(defaultValues?.password || "");
const [otpContact, setOtpContact] = useState(defaultValues?.otpContact || "");
const [otpContactPassword, setOtpContactPassword] = useState(defaultValues?.otpContactPassword || "");
const [showPassword, setShowPassword] = useState(false);
const [showOtpContactPassword, setShowOtpContactPassword] = useState(false);
const queryClient = useQueryClient();
@@ -45,6 +50,8 @@ export function CredentialForm({ onClose, userId, defaultValues }: CredentialFor
siteKey: siteKey.trim(),
username: username.trim(),
password: password.trim(),
otpContact: otpContact.trim() || null,
otpContactPassword: otpContactPassword.trim() || null,
userId,
};
@@ -83,6 +90,8 @@ export function CredentialForm({ onClose, userId, defaultValues }: CredentialFor
setSiteKey(defaultValues?.siteKey || "");
setUsername(defaultValues?.username || "");
setPassword(defaultValues?.password || "");
setOtpContact(defaultValues?.otpContact || "");
setOtpContactPassword(defaultValues?.otpContactPassword || "");
}, [defaultValues]);
const handleSubmit = (e: React.FormEvent) => {
@@ -91,7 +100,7 @@ export function CredentialForm({ onClose, userId, defaultValues }: CredentialFor
if (!siteKey || !username || !password) {
toast({
title: "Error",
description: "All fields are required.",
description: "Insurance, username and password are required.",
variant: "destructive",
});
return;
@@ -150,6 +159,41 @@ export function CredentialForm({ onClose, userId, defaultValues }: CredentialFor
</button>
</div>
</div>
<div>
<label className="block text-sm font-medium">
OTP Email / Phone <span className="text-gray-400 font-normal">(optional)</span>
</label>
<input
type="text"
value={otpContact}
onChange={(e) => setOtpContact(e.target.value)}
placeholder="Email or phone number that receives the OTP code"
className="mt-1 p-2 border rounded w-full"
/>
</div>
<div>
<label className="block text-sm font-medium">
OTP Email Password <span className="text-gray-400 font-normal">(optional)</span>
</label>
<div className="relative mt-1">
<input
type={showOtpContactPassword ? "text" : "password"}
value={otpContactPassword}
onChange={(e) => setOtpContactPassword(e.target.value)}
placeholder="Password for the email account above"
autoComplete="new-password"
className="p-2 border rounded w-full pr-10"
/>
<button
type="button"
onClick={() => setShowOtpContactPassword((prev) => !prev)}
className="absolute inset-y-0 right-2 flex items-center text-gray-500 hover:text-gray-700"
tabIndex={-1}
>
{showOtpContactPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</button>
</div>
</div>
<div className="flex justify-end gap-2">
<button
type="button"
@@ -12,6 +12,8 @@ type Credential = {
siteKey: string;
username: string;
password: string;
otpContact?: string | null;
otpContactPassword?: string | null;
};
export function CredentialTable() {
@@ -101,25 +103,31 @@ export function CredentialTable() {
<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Password
</th>
<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
OTP Email / Phone
</th>
<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
OTP Email Password
</th>
<th className="px-4 py-2" />
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{isLoading ? (
<tr>
<td colSpan={4} className="text-center py-4">
<td colSpan={6} className="text-center py-4">
Loading credentials...
</td>
</tr>
) : error ? (
<tr>
<td colSpan={4} className="text-center py-4 text-red-600">
<td colSpan={6} className="text-center py-4 text-red-600">
Error loading credentials
</td>
</tr>
) : currentCredentials.length === 0 ? (
<tr>
<td colSpan={4} className="text-center py-4">
<td colSpan={6} className="text-center py-4">
No credentials found.
</td>
</tr>
@@ -129,6 +137,8 @@ export function CredentialTable() {
<td className="px-4 py-2">{cred.siteKey}</td>
<td className="px-4 py-2">{cred.username}</td>
<td className="px-4 py-2">••••••••</td>
<td className="px-4 py-2">{cred.otpContact || <span className="text-gray-400">—</span>}</td>
<td className="px-4 py-2">{cred.otpContactPassword ? "••••••••" : <span className="text-gray-400">—</span>}</td>
<td className="px-4 py-2 text-right">
<Button
variant="ghost"
+31 -556
View File
@@ -18,7 +18,7 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { CheckCircle, LoaderCircleIcon, Bot, PhoneCall, ChevronDown, ChevronUp } from "lucide-react";
import { CheckCircle, Bot, PhoneCall, ChevronDown, ChevronUp } from "lucide-react";
import { useAuth } from "@/hooks/use-auth";
import { useToast } from "@/hooks/use-toast";
import { PatientTable } from "@/components/patients/patient-table";
@@ -29,13 +29,12 @@ import {
clearTaskStatus,
} from "@/redux/slices/seleniumTaskSlice";
import { SeleniumTaskBanner } from "@/components/ui/selenium-task-banner";
import { formatLocalDate, parseLocalDate } from "@/utils/dateUtils";
import { socket } from "@/lib/socket";
import { parseLocalDate } from "@/utils/dateUtils";
import { InsertPatient, Patient } from "@repo/db/types";
import { DateInput } from "@/components/ui/dateInput";
import { QK_PATIENTS_BASE } from "@/components/patients/patient-table";
import { PdfPreviewModal } from "@/components/insurance-status/pdf-preview-modal";
import { DualPdfPreviewModal } from "@/components/insurance-status/dual-pdf-preview-modal";
import { MHEligibilityButton } from "@/components/insurance-status/mh-button-modal";
import { useLocation } from "wouter";
import { DdmaEligibilityButton } from "@/components/insurance-status/ddma-buton-modal";
import { DdwaEligibilityButton } from "@/components/insurance-status/ddwa-button-modal";
@@ -50,56 +49,6 @@ import { CCAEligibilityButton } from "@/components/insurance-status/cca-button-m
import { BcbsMaEligibilityButton } from "@/components/insurance-status/bcbs-ma-button-modal";
import { useLicense } from "@/hooks/use-license";
/**
* Waits for a Selenium job to complete by racing socket.io events against
* HTTP polling every 3 seconds. This ensures the result is received even
* when the socket reconnects through Cloudflare (changing socket.id).
*/
function waitForSeleniumJob(
jobId: string,
onActive?: (message: string) => void,
): Promise<any> {
return new Promise<any>((resolve, reject) => {
let settled = false;
const settle = (fn: () => void) => {
if (settled) return;
settled = true;
clearInterval(pollInterval);
socket.off("job:update", socketHandler);
fn();
};
const socketHandler = (payload: any) => {
if (String(payload.jobId) !== String(jobId)) return;
if (payload.status === "active") {
onActive?.(payload.message ?? "Selenium running...");
} else if (payload.status === "completed") {
settle(() => resolve(payload.result ?? {}));
} else if (payload.status === "failed") {
settle(() => reject(new Error(payload.error ?? "Selenium job failed")));
}
};
socket.on("job:update", socketHandler);
const pollInterval = setInterval(async () => {
if (settled) return;
try {
const res = await apiRequest("GET", `/api/insurance-status/job-status/${jobId}`);
if (!res.ok) return;
const data = await res.json();
if (data.status === "completed") {
settle(() => resolve(data.result ?? {}));
} else if (data.status === "failed") {
settle(() => reject(new Error(data.error ?? "Selenium job failed")));
}
} catch {
// ignore transient poll errors
}
}, 3000);
});
}
const PENDING_COPY_AGENT_SCREENSHOTS_KEY = "copy_agent_pending_screenshots";
export default function InsuranceStatusPage() {
@@ -125,15 +74,6 @@ export default function InsuranceStatusPage() {
const isDeltaIndivFormIncomplete = !dateOfBirth || !lastName;
// Altus searches by Member ID, or by Subscriber Last Name when the ID is unknown; First Name + DOB always required.
const isAltusFormIncomplete = !dateOfBirth || !firstName?.trim() || (!memberId && !lastName?.trim());
const [isCheckingEligibilityStatus, setIsCheckingEligibilityStatus] =
useState(false);
const [isCheckingEligibilityAppointment, setIsCheckingEligibilityAppointment] =
useState(false);
const [isCheckingEligibilityClaimsPreAuth, setIsCheckingEligibilityClaimsPreAuth] =
useState(false);
const [isCheckingEligibilityHistory, setIsCheckingEligibilityHistory] =
useState(false);
const [isCheckingCMSP, setIsCheckingCMSP] = useState(false);
const [showPdfViewerOnComplete, setShowPdfViewerOnComplete] = useState(false);
// AI Call Insurance section
@@ -162,26 +102,6 @@ export default function InsuranceStatusPage() {
string | null
>(null);
// Dual PDF modal state (used by MH Eligibility & History)
const [dualPreviewOpen, setDualPreviewOpen] = useState(false);
const [dualEligibilityPdfId, setDualEligibilityPdfId] = useState<number | string | null>(null);
const [dualEligibilityFilename, setDualEligibilityFilename] = useState<string | null>(null);
const [dualMemberDetailsPdfId, setDualMemberDetailsPdfId] = useState<number | string | null>(null);
const [dualMemberDetailsFilename, setDualMemberDetailsFilename] = useState<string | null>(null);
const [dualHistoryPdfId, setDualHistoryPdfId] = useState<number | string | null>(null);
const [dualHistoryFilename, setDualHistoryFilename] = useState<string | null>(null);
// CMSP PDF modal state (used by CMSP Eligibility & History & Remaining)
const [cmspPreviewOpen, setCmspPreviewOpen] = useState(false);
const [cmspEligibilityPdfId, setCmspEligibilityPdfId] = useState<number | string | null>(null);
const [cmspEligibilityFilename, setCmspEligibilityFilename] = useState<string | null>(null);
const [cmspMemberDetailsPdfId, setCmspMemberDetailsPdfId] = useState<number | string | null>(null);
const [cmspMemberDetailsFilename, setCmspMemberDetailsFilename] = useState<string | null>(null);
const [cmspHistoryPdfId, setCmspHistoryPdfId] = useState<number | string | null>(null);
const [cmspHistoryFilename, setCmspHistoryFilename] = useState<string | null>(null);
const [cmspAccumulatorPdfId, setCmspAccumulatorPdfId] = useState<number | string | null>(null);
const [cmspAccumulatorFilename, setCmspAccumulatorFilename] = useState<string | null>(null);
const pendingAutoCheck = useRef<"mh" | "mh-history" | "cmsp" | "ddma" | "ddwa" | "delta-ins" | "delta-indiv" | "united-sco" | "united-ucard" | "tufts-sco" | "cca" | "bcbs-ma" | "metlife" | "altus" | null>(null);
const [triggerTarget, setTriggerTarget] = useState<string | null>(null);
const pendingScrollTo = useRef<string | null>(null);
@@ -331,12 +251,6 @@ export default function InsuranceStatusPage() {
},
});
const isUnder14 = (dob: Date): boolean => {
const cutoff = new Date(dob);
cutoff.setFullYear(cutoff.getFullYear() + 14);
return new Date() < cutoff;
};
// If the Copy Agent page couldn't read a Member ID/DOB from a screenshot, it stashes the
// screenshot(s) here and lets the user complete the check manually. Once that check resolves
// to a real patient, attach the originally-captured screenshots to that patient's Attachments.
@@ -380,52 +294,6 @@ export default function InsuranceStatusPage() {
}
};
// Shared: run MH eligibility selenium job, return jobResult or throw
const runMHEligibilitySelenium = async (): Promise<any> => {
const formattedDob = dateOfBirth ? formatLocalDate(dateOfBirth) : "";
const data = {
memberId,
dateOfBirth: formattedDob,
insuranceSiteKey: "MH",
firstName: firstName || undefined,
lastName: lastName || undefined,
};
dispatch(
setTaskStatus({
key: "eligibilityCheck",
status: "pending",
message: "Sending Data to Selenium...",
}),
);
const response = await apiRequest(
"POST",
"/api/insurance-status/eligibility-check",
{ data: data, socketId: socket.id },
);
const enqueueResult = await response.json();
if (enqueueResult.error) throw new Error(enqueueResult.error);
const jobId = enqueueResult.jobId;
if (!jobId) throw new Error("No jobId returned from server");
dispatch(
setTaskStatus({
key: "eligibilityCheck",
status: "pending",
message: "Selenium browser starting...",
}),
);
const jobResult = await waitForSeleniumJob(jobId, (msg) =>
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: msg }))
);
await flushPendingCopyAgentScreenshots(jobResult);
return jobResult;
};
const handleAddPatient = async () => {
const newPatient: InsertPatient = {
firstName,
@@ -439,333 +307,6 @@ export default function InsuranceStatusPage() {
await addPatientMutation.mutateAsync(newPatient);
};
// MH Eligibility — check eligibility, save to DB, open PDF preview
const handleMHEligibilityButton = async () => {
if (!memberId || !dateOfBirth) {
toast({
title: "Missing Fields",
description: "Please fill in all the required fields: Member ID, Date of Birth.",
variant: "destructive",
});
return;
}
if (isUnder14(dateOfBirth)) {
toast({ title: "CMSP Patient", description: "Patient is under 14 — running CMSP Eligibility & History & Remaining instead.", variant: "default" });
return handleCMSPButton();
}
setIsCheckingEligibilityStatus(true);
try {
const jobResult = await runMHEligibilitySelenium();
dispatch(
setTaskStatus({
key: "eligibilityCheck",
status: "success",
message: "Patient status is updated, and its eligibility pdf is uploaded at Document Page.",
}),
);
toast({
title: "Selenium service done.",
description: "Your Patient Eligibility is fetched and updated, Kindly search through the patient.",
variant: "default",
});
setSelectedPatient(null);
await queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
void tryAppointmentFromChatbot();
if (jobResult.pdfFileId) {
setPreviewPdfId(jobResult.pdfFileId);
setPreviewFallbackFilename(jobResult.pdfFilename ?? `eligibility_${memberId}.pdf`);
setPreviewOpen(true);
}
processNextInQueue();
} catch (error: any) {
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "error", message: error.message || "Selenium submission failed" }));
toast({ title: "Selenium service error", description: error.message || "An error occurred.", variant: "destructive" });
} finally {
setIsCheckingEligibilityStatus(false);
}
};
// MH Eligibility & Appointment — check eligibility, save to DB, create appointment for today
const handleMHEligibilityAppointmentButton = async () => {
if (!memberId || !dateOfBirth) {
toast({
title: "Missing Fields",
description: "Please fill in all the required fields: Member ID, Date of Birth.",
variant: "destructive",
});
return;
}
setIsCheckingEligibilityAppointment(true);
try {
const jobResult = await runMHEligibilitySelenium();
const isInactive = jobResult?.patientUpdateStatus?.includes("INACTIVE");
if (isInactive) {
dispatch(
setTaskStatus({
key: "eligibilityCheck",
status: "error",
message: "Insurance is inactive. No appointment created.",
}),
);
toast({
title: "Insurance Inactive",
description: "Patient insurance is inactive. No appointment was created.",
variant: "destructive",
});
await queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
return;
}
await queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
// Look up the patient (created/updated by the Selenium worker) then create today's appointment
let apptTime: string | null = null;
try {
const lookupRes = await apiRequest("GET", `/api/patients/by-insurance-id?insuranceId=${encodeURIComponent(memberId)}`);
if (lookupRes.ok) {
const patient = await lookupRes.json();
if (patient?.id) {
const apptRes = await apiRequest("POST", "/api/ai/create-appointment-today", { patientId: patient.id });
if (apptRes.ok) {
const apptData = await apptRes.json();
apptTime = apptData.startTime ? `${apptData.startTime} (${apptData.column ?? "Column A"})` : null;
}
}
}
} catch {}
dispatch(
setTaskStatus({
key: "eligibilityCheck",
status: "success",
message: apptTime
? `Eligibility checked. Appointment created at ${apptTime}.`
: "Eligibility checked. Could not create appointment — please add manually.",
}),
);
toast({
title: "Eligibility checked.",
description: apptTime
? `Patient added to today's schedule at ${apptTime}.`
: "Eligibility saved. Could not create appointment — Column A may be full.",
variant: "default",
});
setSelectedPatient(null);
if (jobResult.pdfFileId) {
setPreviewPdfId(jobResult.pdfFileId);
setPreviewFallbackFilename(jobResult.pdfFilename ?? `eligibility_${memberId}.pdf`);
setPreviewOpen(true);
}
} catch (error: any) {
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "error", message: error.message || "Selenium submission failed" }));
toast({ title: "Selenium service error", description: error.message || "An error occurred.", variant: "destructive" });
} finally {
setIsCheckingEligibilityAppointment(false);
}
};
// MH Eligibility & Claims/PreAuth — check eligibility, save to DB, navigate to claims
const handleMHEligibilityClaimsPreAuthButton = async () => {
if (!memberId || !dateOfBirth) {
toast({
title: "Missing Fields",
description: "Please fill in all the required fields: Member ID, Date of Birth.",
variant: "destructive",
});
return;
}
setIsCheckingEligibilityClaimsPreAuth(true);
try {
await runMHEligibilitySelenium();
dispatch(
setTaskStatus({
key: "eligibilityCheck",
status: "success",
message: "Eligibility checked and saved. Redirecting to Claims/PreAuth...",
}),
);
toast({
title: "Eligibility checked.",
description: "Patient eligibility saved. Redirecting to Claims/PreAuth.",
variant: "default",
});
setSelectedPatient(null);
await queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
setLocation("/claims");
} catch (error: any) {
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "error", message: error.message || "Selenium submission failed" }));
toast({ title: "Selenium service error", description: error.message || "An error occurred.", variant: "destructive" });
} finally {
setIsCheckingEligibilityClaimsPreAuth(false);
}
};
// MH Eligibility & History — eligibility check + service history, saves both PDFs, auto-downloads eligibility PDF only
const handleMHEligibilityHistoryButton = async () => {
if (!memberId || !dateOfBirth) {
toast({
title: "Missing Fields",
description: "Please fill in all the required fields: Member ID, Date of Birth.",
variant: "destructive",
});
return;
}
if (isUnder14(dateOfBirth)) {
toast({ title: "CMSP Patient", description: "Patient is under 14 — running CMSP Eligibility & History & Remaining instead.", variant: "default" });
return handleCMSPButton();
}
setIsCheckingEligibilityHistory(true);
try {
const formattedDob = dateOfBirth ? formatLocalDate(dateOfBirth) : "";
const data = {
memberId,
dateOfBirth: formattedDob,
insuranceSiteKey: "MH",
firstName: firstName || undefined,
lastName: lastName || undefined,
};
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: "Sending Data to Selenium..." }));
const response = await apiRequest(
"POST",
"/api/insurance-status/eligibility-history-check",
{ data, socketId: socket.id },
);
const enqueueResult = await response.json();
if (enqueueResult.error) throw new Error(enqueueResult.error);
const jobId = enqueueResult.jobId;
if (!jobId) throw new Error("No jobId returned from server");
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: "Selenium browser starting..." }));
const jobResult = await waitForSeleniumJob(jobId, (msg) =>
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: msg }))
);
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "success", message: "Eligibility and service history PDFs saved to Documents." }));
toast({
title: "Done",
description: "Eligibility and service history PDFs saved. Eligibility PDF downloading now.",
variant: "default",
});
await queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
const claimed = await tryClaimFromChatbot(selectedPatient?.id);
void tryAppointmentFromChatbot();
if (claimed) return;
setSelectedPatient(null);
processNextInQueue();
// Open all PDFs side by side in the modal
if (jobResult.pdfFileId || jobResult.memberDetailsPdfFileId || jobResult.historyPdfFileId) {
setDualEligibilityPdfId(jobResult.pdfFileId ?? null);
setDualEligibilityFilename(jobResult.pdfFilename ?? `eligibility_${memberId}.pdf`);
setDualMemberDetailsPdfId(jobResult.memberDetailsPdfFileId ?? null);
setDualMemberDetailsFilename(jobResult.memberDetailsPdfFilename ?? `eligibility_member_details_${memberId}.pdf`);
setDualHistoryPdfId(jobResult.historyPdfFileId ?? null);
setDualHistoryFilename(jobResult.historyPdfFilename ?? `eligibility_history_${memberId}.pdf`);
setDualPreviewOpen(true);
}
} catch (error: any) {
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "error", message: error.message || "Selenium submission failed" }));
toast({ title: "Selenium service error", description: error.message || "An error occurred.", variant: "destructive" });
} finally {
setIsCheckingEligibilityHistory(false);
}
};
// CMSP Eligibility & History & Remaining — eligibility + service history + accumulator PDFs
const handleCMSPButton = async () => {
if (!memberId || !dateOfBirth) {
toast({
title: "Missing Fields",
description: "Please fill in Member ID and Date of Birth.",
variant: "destructive",
});
return;
}
setIsCheckingCMSP(true);
try {
const formattedDob = dateOfBirth ? formatLocalDate(dateOfBirth) : "";
const data = {
memberId,
dateOfBirth: formattedDob,
insuranceSiteKey: "MH",
firstName: firstName || undefined,
lastName: lastName || undefined,
};
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: "Sending Data to Selenium..." }));
const response = await apiRequest(
"POST",
"/api/insurance-status/cmsp-eligibility-history-remaining-check",
{ data, socketId: socket.id },
);
const enqueueResult = await response.json();
if (enqueueResult.error) throw new Error(enqueueResult.error);
const jobId = enqueueResult.jobId;
if (!jobId) throw new Error("No jobId returned from server");
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: "Selenium browser starting..." }));
const jobResult = await waitForSeleniumJob(jobId, (msg) =>
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "pending", message: msg }))
);
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "success", message: "MH PDFs saved to Documents." }));
toast({
title: "Done",
description: "Eligibility, history, and accumulator PDFs saved.",
variant: "default",
});
await queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
const claimed = await tryClaimFromChatbot(selectedPatient?.id);
void tryAppointmentFromChatbot();
if (claimed) return;
setSelectedPatient(null);
processNextInQueue();
// Open 4-panel modal
if (jobResult.pdfFileId || jobResult.memberDetailsPdfFileId || jobResult.historyPdfFileId || jobResult.accumulatorPdfFileId) {
setCmspEligibilityPdfId(jobResult.pdfFileId ?? null);
setCmspEligibilityFilename(jobResult.pdfFilename ?? `mh_eligibility_${memberId}.pdf`);
setCmspMemberDetailsPdfId(jobResult.memberDetailsPdfFileId ?? null);
setCmspMemberDetailsFilename(jobResult.memberDetailsPdfFilename ?? `mh_member_details_${memberId}.pdf`);
setCmspHistoryPdfId(jobResult.historyPdfFileId ?? null);
setCmspHistoryFilename(jobResult.historyPdfFilename ?? `mh_history_${memberId}.pdf`);
setCmspAccumulatorPdfId(jobResult.accumulatorPdfFileId ?? null);
setCmspAccumulatorFilename(jobResult.accumulatorPdfFilename ?? `mh_accumulator_${memberId}.pdf`);
if (showPdfViewerOnComplete) setCmspPreviewOpen(true);
}
} catch (error: any) {
dispatch(setTaskStatus({ key: "eligibilityCheck", status: "error", message: error.message || "Selenium submission failed" }));
toast({ title: "Selenium service error", description: error.message || "An error occurred.", variant: "destructive" });
} finally {
setIsCheckingCMSP(false);
}
};
// Auto-trigger after prefill (from chatbot or schedule page "Check Eligibility")
useEffect(() => {
if (!pendingAutoCheck.current || !dateOfBirth) return;
@@ -776,12 +317,9 @@ export default function InsuranceStatusPage() {
) return;
const check = pendingAutoCheck.current;
pendingAutoCheck.current = null;
if (check === "mh" || check === "mh-history") {
// Temporarily disabled: selenium_MH_eligibilityHistoryCheckWorker.py is no
// longer used — all MH eligibility checks route through the CMSP/MH worker.
handleCMSPButton();
} else if (check === "cmsp") {
handleCMSPButton();
if (check === "mh" || check === "mh-history" || check === "cmsp") {
// All MH variants run the single MassHealth portal check
setTriggerTarget("mh");
} else {
// Button-component-handled providers: pass target to their autoTrigger prop
setTriggerTarget(check);
@@ -1352,24 +890,31 @@ export default function InsuranceStatusPage() {
{/* Row 6 — MH */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 items-center">
<Button
id="eligibility-cmsp"
className="w-full"
disabled={isCheckingCMSP}
onClick={() => handleCMSPButton()}
>
{isCheckingCMSP ? (
<>
<LoaderCircleIcon className="h-4 w-4 mr-2 animate-spin" />
Processing...
</>
) : (
<>
<CheckCircle className="h-4 w-4 mr-2" />
MH
</>
)}
</Button>
<div id="eligibility-mh">
<MHEligibilityButton
memberId={memberId}
dateOfBirth={dateOfBirth}
firstName={firstName}
lastName={lastName}
isFormIncomplete={isFormIncomplete}
autoTrigger={triggerTarget === "mh"}
onAutoTriggered={() => setTriggerTarget(null)}
onComplete={(result) => {
void flushPendingCopyAgentScreenshots(result);
}}
onPdfReady={async (pdfId, fallbackFilename) => {
await queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
const claimed = await tryClaimFromChatbot(selectedPatient?.id);
void tryAppointmentFromChatbot();
if (!claimed && showPdfViewerOnComplete) {
setPreviewPdfId(pdfId);
setPreviewFallbackFilename(fallbackFilename ?? `mh_eligibility_${memberId}.pdf`);
setPreviewOpen(true);
}
processNextInQueue();
}}
/>
</div>
<div className="flex items-center gap-2 md:col-span-2">
<Switch
@@ -1533,76 +1078,6 @@ export default function InsuranceStatusPage() {
fallbackFilename={previewFallbackFilename ?? undefined}
/>
{/* 4-panel modal for CMSP — eligibility, member details, history, accumulator */}
<DualPdfPreviewModal
open={cmspPreviewOpen}
onClose={() => {
setCmspPreviewOpen(false);
setCmspEligibilityPdfId(null);
setCmspEligibilityFilename(null);
setCmspMemberDetailsPdfId(null);
setCmspMemberDetailsFilename(null);
setCmspHistoryPdfId(null);
setCmspHistoryFilename(null);
setCmspAccumulatorPdfId(null);
setCmspAccumulatorFilename(null);
}}
title="MH Eligibility, Remaining &amp; History"
panels={[
{
pdfId: cmspEligibilityPdfId,
fallbackFilename: cmspEligibilityFilename,
label: "Eligibility",
},
{
pdfId: cmspMemberDetailsPdfId,
fallbackFilename: cmspMemberDetailsFilename,
label: "Member Details",
},
{
pdfId: cmspHistoryPdfId,
fallbackFilename: cmspHistoryFilename,
label: "Service History",
},
{
pdfId: cmspAccumulatorPdfId,
fallbackFilename: cmspAccumulatorFilename,
label: "Accumulator (Remaining)",
},
]}
/>
{/* 3-panel modal for MH Eligibility & History */}
<DualPdfPreviewModal
open={dualPreviewOpen}
onClose={() => {
setDualPreviewOpen(false);
setDualEligibilityPdfId(null);
setDualEligibilityFilename(null);
setDualMemberDetailsPdfId(null);
setDualMemberDetailsFilename(null);
setDualHistoryPdfId(null);
setDualHistoryFilename(null);
}}
title="MH Eligibility &amp; Service History"
panels={[
{
pdfId: dualEligibilityPdfId,
fallbackFilename: dualEligibilityFilename,
label: "Eligibility",
},
{
pdfId: dualMemberDetailsPdfId,
fallbackFilename: dualMemberDetailsFilename,
label: "Member Details",
},
{
pdfId: dualHistoryPdfId,
fallbackFilename: dualHistoryFilename,
label: "Service History",
},
]}
/>
</div>
);
}
+56 -115
View File
@@ -5,9 +5,6 @@ from fastapi.staticfiles import StaticFiles
import uvicorn
import asyncio
from selenium_claimSubmitWorker import AutomationMassHealthClaimsLogin
from selenium_eligibilityCheckWorker import AutomationMassHealthEligibilityCheck
from selenium_MH_eligibilityHistoryCheckWorker import AutomationMassHealthEligibilityHistoryCheck
from selenium_CMSP_eligibilityHistoryRemainingCheckWorker import AutomationCMSPEligibilityHistoryRemainingCheck
from selenium_claimStatusCheckWorker import AutomationMassHealthClaimStatusCheck
from selenium_preAuthWorker import AutomationMassHealthPreAuth
from selenium_MHSinglePaymentCheckWorker import AutomationMassHealthSinglePaymentCheck
@@ -26,6 +23,7 @@ import helpers_deltains_eligibility as hdeltains
import helpers_unitedsco_eligibility as hunitedsco
import helpers_uniteducard_eligibility as huniteducard
import helpers_dentaquest_eligibility as hdentaquest
import helpers_mh_eligibility as hmh
import helpers_cca_eligibility as hcca
import helpers_cca_claim as hcca_claim
import helpers_cca_preauth as hcca_preauth
@@ -50,6 +48,7 @@ from deltains_browser_manager import clear_deltains_session_on_startup
from unitedsco_browser_manager import clear_unitedsco_session_on_startup
from uniteducard_browser_manager import clear_uniteducard_session_on_startup
from dentaquest_browser_manager import clear_dentaquest_session_on_startup
from mh_browser_manager import clear_mh_session_on_startup
from cca_browser_manager import clear_cca_session_on_startup
from metlife_browser_manager import clear_metlife_session_on_startup
@@ -69,6 +68,7 @@ clear_deltains_session_on_startup()
clear_unitedsco_session_on_startup()
clear_uniteducard_session_on_startup()
clear_dentaquest_session_on_startup()
clear_mh_session_on_startup()
clear_cca_session_on_startup()
clear_metlife_session_on_startup()
print("=" * 50)
@@ -135,79 +135,6 @@ async def start_workflow(request: Request):
async with lock:
active_jobs -= 1
# Endpoint: 2 — Start the automation of cheking eligibility
@app.post("/eligibility-check")
async def start_workflow(request: Request):
global active_jobs, waiting_jobs
data = await request.json()
async with lock:
waiting_jobs += 1
async with semaphore:
async with lock:
waiting_jobs -= 1
active_jobs += 1
try:
bot = AutomationMassHealthEligibilityCheck(data)
result = bot.main_workflow("https://provider.masshealth-dental.org/mh_provider_login")
if result.get("status") != "success":
return {"status": "error", "message": result.get("message")}
# Convert pdf_path to pdf_url
if result.get("pdf_path"):
filename = os.path.basename(result["pdf_path"])
port = os.getenv("PORT", "5002")
url_host = os.getenv("HOST", "localhost")
result["pdf_url"] = f"http://{url_host}:{port}/downloads/{filename}"
print(f"DEBUG: Generated pdf_url = {result['pdf_url']}")
return result
except Exception as e:
return {"status": "error", "message": str(e)}
finally:
async with lock:
active_jobs -= 1
# Endpoint: 2a — MH Eligibility + Service History
@app.post("/mh-eligibility-history-check")
async def mh_eligibility_history_check(request: Request):
global active_jobs, waiting_jobs
data = await request.json()
async with lock:
waiting_jobs += 1
async with semaphore:
async with lock:
waiting_jobs -= 1
active_jobs += 1
try:
bot = AutomationMassHealthEligibilityHistoryCheck(data)
result = bot.main_workflow("https://provider.masshealth-dental.org/mh_provider_login")
if result.get("status") == "error":
return {"status": "error", "message": result.get("message")}
port = os.getenv("PORT", "5002")
url_host = os.getenv("HOST", "localhost")
if result.get("pdf_path"):
filename = os.path.basename(result["pdf_path"])
result["pdf_url"] = f"http://{url_host}:{port}/downloads/{filename}"
if result.get("history_pdf_path"):
filename = os.path.basename(result["history_pdf_path"])
result["history_pdf_url"] = f"http://{url_host}:{port}/downloads/{filename}"
return result
except Exception as e:
return {"status": "error", "message": str(e)}
finally:
async with lock:
active_jobs -= 1
# Endpoint: 2c — Altus Dental eligibility (no OTP, fresh browser per run)
@app.post("/altus-eligibility-check")
async def altus_eligibility_check(request: Request):
@@ -244,45 +171,6 @@ async def altus_eligibility_check(request: Request):
async with lock:
active_jobs -= 1
# Endpoint: 2b — CMSP Eligibility + Service History + Accumulator (Remaining)
@app.post("/cmsp-eligibility-history-remaining-check")
async def cmsp_eligibility_history_remaining_check(request: Request):
global active_jobs, waiting_jobs
data = await request.json()
async with lock:
waiting_jobs += 1
async with semaphore:
async with lock:
waiting_jobs -= 1
active_jobs += 1
try:
bot = AutomationCMSPEligibilityHistoryRemainingCheck(data)
result = bot.main_workflow("https://provider.masshealth-dental.org/mh_provider_login")
if result.get("status") == "error":
return {"status": "error", "message": result.get("message")}
port = os.getenv("PORT", "5002")
url_host = os.getenv("HOST", "localhost")
for key, url_key in [
("pdf_path", "pdf_url"),
("history_pdf_path", "history_pdf_url"),
("accumulator_pdf_path", "accumulator_pdf_url"),
]:
if result.get(key):
filename = os.path.basename(result[key])
result[url_key] = f"http://{url_host}:{port}/downloads/{filename}"
return result
except Exception as e:
return {"status": "error", "message": str(e)}
finally:
async with lock:
active_jobs -= 1
# Endpoint: 2.1 — Start the automation for Claims login (open browser and log in)
@app.post("/claims-login")
async def start_claims_login(request: Request):
@@ -839,6 +727,45 @@ async def dentaquest_eligibility(request: Request):
return {"status": "started", "session_id": sid}
async def _mh_worker_wrapper(sid: str, data: dict, url: str):
"""Background worker for MassHealth eligibility — acquires semaphore, updates counters."""
global active_jobs, waiting_jobs
async with semaphore:
async with lock:
waiting_jobs -= 1
active_jobs += 1
try:
await hmh.start_mh_run(sid, data, url)
finally:
async with lock:
active_jobs -= 1
@app.post("/mh-eligibility")
async def mh_eligibility(request: Request):
"""
Starts a MassHealth eligibility session in the background
(providers.masshealth-dental.org — same DentaQuest portal as Tufts SCO).
Body: { "data": { ... } }
Returns: { status: "started", session_id: "<uuid>" }
"""
global waiting_jobs
body = await request.json()
data = body.get("data", {})
sid = hmh.make_session_entry()
hmh.sessions[sid]["type"] = "mh_eligibility"
hmh.sessions[sid]["last_activity"] = time.time()
async with lock:
waiting_jobs += 1
asyncio.create_task(_mh_worker_wrapper(sid, data, url=hmh.MH_BASE_URL))
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
@@ -1412,6 +1339,8 @@ async def submit_otp(request: Request):
res = huniteducard.submit_otp(sid, otp)
elif sid in hdentaquest.sessions:
res = hdentaquest.submit_otp(sid, otp)
elif sid in hmh.sessions:
res = hmh.submit_otp(sid, otp)
elif sid in hddma_claim.sessions:
res = hddma_claim.submit_otp(sid, otp)
elif sid in hddma_payment.sessions:
@@ -1459,6 +1388,8 @@ async def session_status(sid: str):
s = huniteducard.get_session_status(sid)
elif sid in hdentaquest.sessions:
s = hdentaquest.get_session_status(sid)
elif sid in hmh.sessions:
s = hmh.get_session_status(sid)
elif sid in hcca.sessions:
s = hcca.get_session_status(sid)
elif sid in hcca_claim.sessions:
@@ -1566,6 +1497,16 @@ async def clear_uniteducard_session_endpoint():
return {"status": "error", "message": str(e)}
@app.post("/clear-mh-session")
async def clear_mh_session_endpoint():
"""Clears the MassHealth browser session. Call when credentials are deleted or changed."""
try:
clear_mh_session_on_startup()
return {"status": "success", "message": "MH session cleared"}
except Exception as e:
return {"status": "error", "message": str(e)}
@app.post("/clear-cca-session")
async def clear_cca_session_endpoint():
"""Clears the CCA browser session. Call when credentials are deleted or changed."""
+184
View File
@@ -0,0 +1,184 @@
"""Read a one-time passcode from an email inbox over IMAP (Gmail by default).
Used when a portal sends its OTP to the email saved as "OTP Email / Phone" in
Settings -> Insurance Credentials. The "OTP Email Password" must be a Gmail
App Password (16 characters); a normal Gmail password is rejected over IMAP.
Read-only: messages are fetched with BODY.PEEK so they are not marked as read.
"""
import email
import email.message
import imaplib
import os
import re
import time
from email.header import decode_header, make_header
from html import unescape
from typing import Iterable, Optional
IMAP_HOST = os.getenv("OTP_IMAP_HOST", "imap.gmail.com")
IMAP_PORT = int(os.getenv("OTP_IMAP_PORT", "993"))
MAILBOXES = ("INBOX", "[Gmail]/Spam")
_KEYWORD_CODE = re.compile(
r"(?:code|passcode|pass code|otp|one[- ]time|verification|verify|pin)"
r"[^0-9]{0,60}?\b(\d{4,8})\b",
re.I,
)
_CODE_COLON = re.compile(
r"\b(?:code|passcode|otp)(?:\s+(?:instead|is))?\s*[:\-]?\s*(?:is\s+)?(\d{4,8})\b", re.I
)
_SIX_DIGITS = re.compile(r"(?<![\d$.,/-])\b(\d{6})\b(?![\d.,/-])")
# Codes already used this process, so a retry never re-types an old code
_used_codes: set = set()
def looks_like_email(value: Optional[str]) -> bool:
return bool(value) and "@" in value
def _decode(value) -> str:
try:
return str(make_header(decode_header(value or "")))
except Exception:
return value or ""
def _body_text(msg: email.message.Message) -> str:
plain, html = [], []
for part in msg.walk() if msg.is_multipart() else [msg]:
ctype = part.get_content_type()
if ctype not in ("text/plain", "text/html"):
continue
try:
payload = part.get_payload(decode=True) or b""
text = payload.decode(part.get_content_charset() or "utf-8", errors="replace")
except Exception:
continue
(plain if ctype == "text/plain" else html).append(text)
if plain:
return "\n".join(plain)
text = "\n".join(html)
text = re.sub(r"(?is)<(script|style).*?</\1>", " ", text)
text = re.sub(r"<[^>]+>", " ", text)
return unescape(text)
def extract_code(subject: str, body: str) -> Optional[str]:
# Most specific first: "Enter a code instead: 081914" / "code: 081914"
for text in (subject, body):
m = _CODE_COLON.search(text or "")
if m:
return m.group(1)
for text in (subject, body):
m = _KEYWORD_CODE.search(text or "")
if m:
return m.group(1)
for text in (subject, body):
m = _SIX_DIGITS.search(text or "")
if m:
return m.group(1)
return None
def _matches(sender: str, subject: str, body: str, keywords: Iterable[str]) -> bool:
haystack = f"{sender}\n{subject}\n{body}".lower()
return any(k.lower() in haystack for k in keywords)
def _search_mailbox(conn, mailbox: str, since_ts: float, keywords) -> Optional[str]:
typ, _ = conn.select(f'"{mailbox}"', readonly=True)
if typ != "OK":
return None
since = time.strftime("%d-%b-%Y", time.gmtime(since_ts - 86400))
typ, data = conn.uid("SEARCH", None, "SINCE", since)
if typ != "OK" or not data or not data[0]:
return None
uids = data[0].split()[-15:] # newest 15 is plenty
for uid in reversed(uids):
typ, msg_data = conn.uid("FETCH", uid, "(INTERNALDATE BODY.PEEK[])")
if typ != "OK" or not msg_data or not isinstance(msg_data[0], tuple):
continue
meta, raw = msg_data[0]
received = imaplib.Internaldate2tuple(meta)
if received and time.mktime(received) < since_ts:
continue # older than this login attempt
msg = email.message_from_bytes(raw)
sender = _decode(msg.get("From"))
subject = _decode(msg.get("Subject"))
body = _body_text(msg)
if not _matches(sender, subject, body, keywords):
continue
code = extract_code(subject, body)
if code and code not in _used_codes:
print(f"[email OTP] Found code in '{subject[:60]}' from {sender[:60]}")
return code
return None
def check_email_login(address: str, password: str) -> Optional[str]:
"""Return None when the login works, else an error message."""
try:
conn = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT, timeout=20)
conn.login(address.strip(), "".join((password or "").split()))
conn.logout()
return None
except Exception as e:
return f"{type(e).__name__}: {e}"
def fetch_otp_from_email(
address: str,
password: str,
since_ts: float,
keywords: Iterable[str],
timeout: int = 120,
poll_every: int = 5,
should_stop=None,
) -> Optional[str]:
"""Poll the inbox until an OTP email received after `since_ts` arrives.
Blocking; run it with asyncio.to_thread. Returns the code or None.
`should_stop` is an optional callable checked between polls.
"""
address = (address or "").strip()
password = "".join((password or "").split()) # app passwords are shown with spaces
if not looks_like_email(address) or not password:
return None
deadline = time.time() + timeout
conn = None
while time.time() < deadline:
if should_stop and should_stop():
break
try:
if conn is None:
conn = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT, timeout=20)
conn.login(address, password)
print(f"[email OTP] Logged in to {IMAP_HOST}, waiting for code...")
for mailbox in MAILBOXES:
try:
code = _search_mailbox(conn, mailbox, since_ts, keywords)
except imaplib.IMAP4.error:
code = None # e.g. Spam folder name differs
if code:
_used_codes.add(code)
return code
except imaplib.IMAP4.error as e:
print(f"[email OTP] IMAP login/search failed: {e}")
if "AUTHENTICATIONFAILED" in str(e).upper() or "credentials" in str(e).lower():
break # wrong address / app password; retrying won't help
conn = None
except Exception as e:
print(f"[email OTP] Error: {type(e).__name__}: {e}")
conn = None
time.sleep(poll_every)
try:
if conn is not None:
conn.logout()
except Exception:
pass
print("[email OTP] No code found")
return None
@@ -0,0 +1,357 @@
"""Session store + run loop for MassHealth eligibility (persistent browser, OTP via app or browser)."""
import os
import time
import asyncio
from typing import Dict, Any
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import WebDriverException, TimeoutException
from selenium_MH_eligibilityCheckWorker import AutomationMHEligibilityCheck, MH_BASE_URL
from helpers_email_otp import fetch_otp_from_email, looks_like_email
# Text that identifies the MassHealth / DentaQuest OTP email
MH_OTP_EMAIL_KEYWORDS = ("masshealth-dental.org", "masshealth dental program")
MH_MEMBERS_URL = MH_BASE_URL + "members"
# In-memory session store
sessions: Dict[str, Dict[str, Any]] = {}
SESSION_OTP_TIMEOUT = int(os.getenv("SESSION_OTP_TIMEOUT", "120")) # seconds
def make_session_entry() -> str:
"""Create a new session entry and return its ID."""
import uuid
sid = str(uuid.uuid4())
sessions[sid] = {
"status": "created", # created -> running -> waiting_for_otp -> otp_submitted -> completed / error
"created_at": time.time(),
"last_activity": time.time(),
"bot": None, # worker instance
"driver": None, # selenium webdriver
"otp_event": asyncio.Event(),
"otp_value": None,
"result": None,
"message": None,
"type": None,
}
return sid
async def cleanup_session(sid: str, message: str | None = None):
"""
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:
if s.get("status") not in ("completed", "error", "not_found"):
s["status"] = "error"
if message:
s["message"] = message
except Exception:
pass
try:
ev = s.get("otp_event")
if ev and not ev.is_set():
ev.set()
except Exception:
pass
# 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 = 30):
await asyncio.sleep(delay)
sessions.pop(sid, None)
async def start_mh_run(sid: str, data: dict, url: str, worker_cls=None):
"""
Run the MassHealth eligibility workflow for a session (WITHOUT managing semaphore/counters).
Called by agent.py inside a wrapper that handles queue/counters.
"""
s = sessions.get(sid)
if not s:
return {"status": "error", "message": "session not found"}
s["status"] = "running"
s["last_activity"] = time.time()
try:
# worker_cls lets Check PreAuth reuse this flow with its own worker
bot = (worker_cls or AutomationMHEligibilityCheck)({"data": data})
bot.config_driver()
s["bot"] = bot
s["driver"] = bot.driver
s["last_activity"] = time.time()
# Navigate to login URL
try:
if not url:
raise ValueError("URL not provided for MH run")
bot.driver.maximize_window()
bot.driver.get(url)
await asyncio.sleep(1)
except Exception as e:
s["status"] = "error"
s["message"] = f"Navigation failed: {e}"
await cleanup_session(sid)
return {"status": "error", "message": s["message"]}
# Login (remember when, so only OTP emails sent after this are used)
login_started_at = time.time() - 60
try:
login_result = bot.login(url)
except WebDriverException as wde:
s["status"] = "error"
s["message"] = f"Selenium driver error during login: {wde}"
await cleanup_session(sid, s["message"])
return {"status": "error", "message": s["message"]}
except Exception as e:
s["status"] = "error"
s["message"] = f"Unexpected error during login: {e}"
await cleanup_session(sid, s["message"])
return {"status": "error", "message": s["message"]}
# Already logged in - session persisted from profile, skip to step1
if isinstance(login_result, str) and login_result == "ALREADY_LOGGED_IN":
s["status"] = "running"
s["message"] = "Session persisted"
# Continue to step1 below
# OTP required path - POLL THE BROWSER to detect when user enters OTP
elif isinstance(login_result, str) and login_result == "OTP_REQUIRED":
s["status"] = "waiting_for_otp"
s["message"] = "OTP required for login - please enter OTP in browser"
s["last_activity"] = time.time()
driver = s["driver"]
# Read the code from the OTP email inbox automatically, if one is saved.
# The app / browser entry below still works as a fallback.
otp_email = (data.get("otpEmail") or "").strip()
otp_email_password = data.get("otpEmailPassword") or ""
if looks_like_email(otp_email) and otp_email_password:
s["message"] = f"Reading the verification code from {otp_email} automatically... You can also type it here."
async def _auto_fill_otp_from_email():
code = await asyncio.to_thread(
fetch_otp_from_email,
otp_email,
otp_email_password,
login_started_at,
MH_OTP_EMAIL_KEYWORDS,
SESSION_OTP_TIMEOUT - 10,
5,
lambda: s.get("status") != "waiting_for_otp",
)
if code and s.get("status") == "waiting_for_otp" and not s.get("otp_value"):
print("[MH OTP] Code read from email, submitting")
s["otp_value"] = code
s["message"] = "OTP read from email - verifying..."
elif not code and s.get("status") == "waiting_for_otp":
s["message"] = "Could not read the OTP from email - please enter it manually"
asyncio.create_task(_auto_fill_otp_from_email())
# Poll the browser to detect when OTP is completed (user enters it directly)
# We check every 1 second for up to SESSION_OTP_TIMEOUT seconds (faster response)
max_polls = SESSION_OTP_TIMEOUT
login_success = False
print(f"[MH OTP] Waiting for user to enter OTP (polling browser for {SESSION_OTP_TIMEOUT}s)...")
for poll in range(max_polls):
await asyncio.sleep(1)
s["last_activity"] = time.time()
try:
# Check if OTP was submitted via API (from app)
otp_value = s.get("otp_value")
if otp_value:
print(f"[MH OTP] OTP received from app: {otp_value}")
try:
otp_input = driver.find_element(By.XPATH,
"//input[@data-testid='passcode'] | "
"//input[contains(@name,'otp') or contains(@name,'code') or @type='tel' or contains(@aria-label,'Verification') or contains(@placeholder,'verification code')]"
)
otp_input.click()
otp_input.send_keys(Keys.CONTROL, "a")
otp_input.send_keys(Keys.DELETE)
otp_input.send_keys(otp_value)
await asyncio.sleep(0.5)
# Click "Verify" in the popup (the text is inside a <span>)
try:
verify_btn = driver.find_element(By.XPATH,
"//button[normalize-space(.)='Verify'] | //button[@aria-label='Verify']")
driver.execute_script("arguments[0].click();", verify_btn)
print("[MH OTP] Clicked Verify")
except Exception:
otp_input.send_keys(Keys.ENTER)
print("[MH OTP] Verify button not found, pressed Enter")
print("[MH OTP] OTP typed and submitted via app")
s["otp_value"] = None # Clear so we don't submit again
await asyncio.sleep(3) # Wait for verification
except Exception as type_err:
print(f"[MH OTP] Failed to type OTP from app: {type_err}")
# Check current URL - if we're on dashboard/member page, login succeeded
current_url = driver.current_url.lower()
print(f"[MH OTP Poll {poll+1}/{max_polls}] URL: {current_url[:60]}...")
# Logged in once the member search box shows (home page has it at any URL)
if driver.find_elements(By.XPATH, '//input[@data-testid="member-search_member-id_input" or @placeholder="Search by member ID"]'):
print("[MH OTP] Member search box found - login successful!")
login_success = True
break
# Check if we've navigated away from login/OTP pages
if "member" in current_url or "dashboard" in current_url or "eligibility" in current_url:
# Verify by checking for member search input
try:
member_search = WebDriverWait(driver, 5).until(
EC.presence_of_element_located((By.XPATH, '//input[@placeholder="Search by member ID"]'))
)
print("[MH OTP] Member search input found - login successful!")
login_success = True
break
except TimeoutException:
print("[MH OTP] On member page but search input not found, continuing to poll...")
# Also check if OTP input is still visible
try:
otp_input = driver.find_element(By.XPATH,
"//input[@data-testid='passcode'] | "
"//input[contains(@name,'otp') or contains(@name,'code') or @type='tel' or contains(@aria-label,'Verification') or contains(@placeholder,'code') or contains(@placeholder,'Code')]"
)
# OTP input still visible - user hasn't entered OTP yet
print(f"[MH OTP Poll {poll+1}] OTP input still visible - waiting...")
except:
# OTP input not found - might mean login is in progress or succeeded
# Try navigating to members page (like Delta MA)
if "onboarding" in current_url or "start" in current_url or "login" in current_url:
print("[MH OTP] OTP input gone, trying to navigate to members page...")
try:
driver.get(MH_MEMBERS_URL)
await asyncio.sleep(2)
except:
pass
except Exception as poll_err:
print(f"[MH OTP Poll {poll+1}] Error: {poll_err}")
if not login_success:
# Final attempt - navigate to members page and check (like Delta MA)
try:
print("[MH OTP] Final attempt - navigating to members page...")
driver.get(MH_MEMBERS_URL)
await asyncio.sleep(3)
member_search = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, '//input[@placeholder="Search by member ID"]'))
)
print("[MH OTP] Member search input found - login successful!")
login_success = True
except TimeoutException:
s["status"] = "error"
s["message"] = "OTP timeout - login not completed"
await cleanup_session(sid)
return {"status": "error", "message": "OTP not completed in time"}
except Exception as final_err:
s["status"] = "error"
s["message"] = f"OTP verification failed: {final_err}"
await cleanup_session(sid)
return {"status": "error", "message": s["message"]}
if login_success:
s["status"] = "running"
s["message"] = "Login successful after OTP"
print("[MH OTP] Proceeding to step1...")
elif isinstance(login_result, str) and login_result.startswith("ERROR"):
s["status"] = "error"
s["message"] = login_result
await cleanup_session(sid)
return {"status": "error", "message": login_result}
# Login succeeded without OTP (SUCCESS)
elif isinstance(login_result, str) and login_result == "SUCCESS":
print("[start_mh_run] Login succeeded without OTP")
s["status"] = "running"
s["message"] = "Login succeeded"
# Continue to step1 below
# Step 1
step1_result = bot.step1()
if isinstance(step1_result, str) and step1_result.startswith("ERROR"):
s["status"] = "error"
s["message"] = step1_result
await cleanup_session(sid)
return {"status": "error", "message": step1_result}
# Step 2 (PDF)
step2_result = bot.step2()
if isinstance(step2_result, dict) and step2_result.get("status") == "success":
s["status"] = "completed"
s["result"] = step2_result
s["message"] = "completed"
asyncio.create_task(_remove_session_later(sid, 30))
return step2_result
else:
s["status"] = "error"
if isinstance(step2_result, dict):
s["message"] = step2_result.get("message", "unknown error")
else:
s["message"] = str(step2_result)
await cleanup_session(sid)
return {"status": "error", "message": s["message"]}
except Exception as e:
import traceback
print(f"[start_mh_run] EXCEPTION: {e}")
traceback.print_exc()
s["status"] = "error"
s["message"] = f"worker exception: {e}"
await cleanup_session(sid)
return {"status": "error", "message": s["message"]}
def submit_otp(sid: str, otp: str) -> Dict[str, Any]:
"""Set OTP for a session and wake waiting runner."""
s = sessions.get(sid)
if not s:
return {"status": "error", "message": "session not found"}
if s.get("status") != "waiting_for_otp":
return {"status": "error", "message": f"session not waiting for otp (state={s.get('status')})"}
s["otp_value"] = otp
s["last_activity"] = time.time()
try:
s["otp_event"].set()
except Exception:
pass
return {"status": "ok", "message": "otp accepted"}
def get_session_status(sid: str) -> Dict[str, Any]:
s = sessions.get(sid)
if not s:
return {"status": "not_found"}
return {
"session_id": sid,
"status": s.get("status"),
"message": s.get("message"),
"created_at": s.get("created_at"),
"last_activity": s.get("last_activity"),
"result": s.get("result") if s.get("status") == "completed" else None,
}
+226
View File
@@ -0,0 +1,226 @@
"""
Minimal browser manager for MassHealth (DentaQuest portal at providers.masshealth-dental.org) - only handles persistent profile and keeping browser alive.
Clears session cookies on startup (after PC restart) to force fresh login.
Tracks credentials to detect changes mid-session.
"""
import os
import shutil
import hashlib
import threading
import subprocess
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
# Ensure DISPLAY is set for Chrome to work (needed when running from SSH/background)
if not os.environ.get("DISPLAY"):
os.environ["DISPLAY"] = ":0"
class MHBrowserManager:
"""
Singleton that manages a persistent Chrome browser instance for MassHealth.
- Uses --user-data-dir for persistent profile (device trust tokens)
- Clears session cookies on startup (after PC restart)
- Tracks credentials to detect changes mid-session
"""
_instance = None
_lock = threading.Lock()
def __new__(cls):
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._driver = None
cls._instance.profile_dir = os.path.abspath("chrome_profile_mh")
cls._instance.download_dir = os.path.abspath("seleniumDownloads")
cls._instance._credentials_file = os.path.join(cls._instance.profile_dir, ".last_credentials")
cls._instance._needs_session_clear = False # Flag to clear session on next driver creation
os.makedirs(cls._instance.profile_dir, exist_ok=True)
os.makedirs(cls._instance.download_dir, exist_ok=True)
return cls._instance
def clear_session_on_startup(self):
"""
On startup, reset only the credentials tracking file so that credential-change
detection still works. Cookies are intentionally NOT deleted — the portal stores
its MFA/OTP trust as a persistent cookie, so wiping cookies would force OTP on
every restart. If the session cookie is still valid the browser auto-logs in; if
it has expired the user re-enters credentials but OTP is skipped because the
MFA trust cookie is intact. Credential changes are handled by _force_logout()
which calls delete_all_cookies() explicitly.
"""
print("[MH BrowserManager] Startup: preserving all cookies (OTP trust cookie must survive restart)...")
try:
if os.path.exists(self._credentials_file):
os.remove(self._credentials_file)
print("[MH BrowserManager] Cleared credentials tracking file")
self._needs_session_clear = False
print("[MH BrowserManager] Startup done — cookies preserved, OTP trust intact")
except Exception as e:
print(f"[MH BrowserManager] Error on startup: {e}")
def _hash_credentials(self, username: str) -> str:
"""Create a hash of the username to track credential changes."""
return hashlib.sha256(username.encode()).hexdigest()[:16]
def get_last_credentials_hash(self) -> str | None:
"""Get the hash of the last-used credentials."""
try:
if os.path.exists(self._credentials_file):
with open(self._credentials_file, 'r') as f:
return f.read().strip()
except Exception:
pass
return None
def save_credentials_hash(self, username: str):
"""Save the hash of the current credentials."""
try:
cred_hash = self._hash_credentials(username)
with open(self._credentials_file, 'w') as f:
f.write(cred_hash)
except Exception as e:
print(f"[MH BrowserManager] Failed to save credentials hash: {e}")
def credentials_changed(self, username: str) -> bool:
"""Check if the credentials have changed since last login."""
last_hash = self.get_last_credentials_hash()
if last_hash is None:
return False # No previous credentials, not a change
current_hash = self._hash_credentials(username)
changed = last_hash != current_hash
if changed:
print(f"[MH BrowserManager] Credentials changed - logout required")
return changed
def clear_credentials_hash(self):
"""Clear the saved credentials hash (used after logout)."""
try:
if os.path.exists(self._credentials_file):
os.remove(self._credentials_file)
except Exception as e:
print(f"[MH BrowserManager] Failed to clear credentials hash: {e}")
def _kill_existing_chrome_for_profile(self):
"""Kill any existing Chrome processes using this profile."""
try:
# Find and kill Chrome processes using this profile
result = subprocess.run(
["pgrep", "-f", f"user-data-dir={self.profile_dir}"],
capture_output=True, text=True
)
if result.stdout.strip():
pids = result.stdout.strip().split('\n')
for pid in pids:
try:
subprocess.run(["kill", "-9", pid], check=False)
except:
pass
time.sleep(1)
except Exception as e:
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."""
with self._lock:
if self._driver is None:
print("[MH BrowserManager] Driver is None, creating new driver")
self._kill_existing_chrome_for_profile()
self._create_driver(headless)
elif not self._is_alive():
print("[MH BrowserManager] Driver not alive, recreating")
self._kill_existing_chrome_for_profile()
self._create_driver(headless)
else:
print("[MH BrowserManager] Reusing existing driver")
return self._driver
def _is_alive(self):
"""Check if browser is still responsive."""
try:
if self._driver is None:
return False
url = self._driver.current_url
return True
except Exception as e:
return False
def _create_driver(self, headless=False):
"""Create browser with persistent profile."""
if self._driver:
try:
self._driver.quit()
except:
pass
self._driver = None
time.sleep(1)
options = webdriver.ChromeOptions()
if headless:
options.add_argument("--headless")
# Persistent profile - THIS IS THE KEY for device trust
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,
"download.prompt_for_download": False,
"download.directory_upgrade": True
}
options.add_experimental_option("prefs", prefs)
service = Service(ChromeDriverManager().install())
self._driver = webdriver.Chrome(service=service, options=options)
self._driver.maximize_window()
# Reset the session clear flag (file-based clearing is done on startup)
self._needs_session_clear = False
def quit_driver(self):
"""Quit browser (only call on shutdown)."""
with self._lock:
if self._driver:
try:
self._driver.quit()
except:
pass
self._driver = None
# Also clean up any orphaned processes
self._kill_existing_chrome_for_profile()
# Singleton accessor
_manager = None
def get_browser_manager():
global _manager
if _manager is None:
_manager = MHBrowserManager()
return _manager
def clear_mh_session_on_startup():
"""Called by agent.py on startup to clear session."""
manager = get_browser_manager()
manager.clear_session_on_startup()
-74
View File
@@ -1,74 +0,0 @@
import re
from selenium.webdriver.common.by import By
# Labels shown in the MassHealth Member Detail block, e.g.
# Date of Birth: 4/21/1958
# Gender: Female
# Address: 169 CYPRESS ST, NEWTON, MA 02459
# Home Phone: 6036789376
# Registered Not Registered in Member Community
_LABELS = ("Date of Birth", "Gender", "Address", "Home Phone", "Phone", "Registered")
def _label_value(text, label):
"""Value next to "Label:" — same line or the next line (innerText of a
two-column layout can put the value on its own line). Empty when the
portal leaves the field blank."""
m = re.search(rf"(?:^|\n)[ \t]*{re.escape(label)}:[ \t]*\n?[ \t]*([^\n]*)", text)
if not m:
return ""
value = m.group(1).strip()
# Blank field — we grabbed the next row's label instead of a value
if value.endswith(":") or any(value.startswith(f"{l}:") or value == l for l in _LABELS):
return ""
return value
def extract_member_demographics(driver):
"""Read gender, address and phone from the MassHealth Member Detail page.
Returns only the fields that were found:
gender — "Female" / "Male" as shown by the portal
address, city, state, zipCode — split from "STREET, CITY, ST 12345"
phone — 10 digits
memberName — the heading above "Date of Birth:" (e.g. "OLHA SVYSHCH")
"""
result = {}
try:
text = driver.find_element(By.TAG_NAME, "body").get_attribute("innerText") or ""
# Name is the last non-empty line before the "Date of Birth:" row
dob = re.search(r"(?:^|\n)[ \t]*Date of Birth:", text)
if dob:
lines = [l.strip() for l in text[:dob.start()].split("\n") if l.strip()]
if lines and ":" not in lines[-1]:
result["memberName"] = lines[-1]
gender = _label_value(text, "Gender")
if gender:
result["gender"] = gender
address = _label_value(text, "Address")
if address:
# "169 CYPRESS ST, NEWTON, MA 02459" — street may itself contain commas (APT 2)
m = re.match(r"^(.*),\s*([^,]+?),?\s+([A-Z]{2})\s+(\d{5})(?:-?\d{4})?$", address)
if m:
result["address"] = m.group(1).strip()
result["city"] = m.group(2).strip()
result["state"] = m.group(3)
result["zipCode"] = m.group(4)
else:
result["address"] = address
phone = _label_value(text, "Home Phone") or _label_value(text, "Phone")
digits = re.sub(r"\D", "", phone)
if len(digits) == 11 and digits.startswith("1"):
digits = digits[1:]
if len(digits) == 10:
result["phone"] = digits
print(f"[extract_member_demographics] {result}")
except Exception as e:
print(f"[extract_member_demographics] failed: {e}")
return result
+52
View File
@@ -0,0 +1,52 @@
"""Plan name, remaining annual benefit and phone from the MassHealth Dental
(providers.masshealth-dental.org) member details page."""
import re
import time
from selenium.webdriver.common.by import By
# "Plan:" (not "Plan/Group number:" or "Plan year:"); value on the same line or the next
_PLAN_RE = re.compile(r"^[ \t]*Plan:[ \t]*(?:\n[ \t]*)?([^\n\t]+)", re.M)
# "$1,638.00 before Individual annual maximum (All Networks) is met"
_REMAINING_RE = re.compile(r"(\$\s?[\d,]+(?:\.\d{2})?)\s*before\s+[^\n]*?maximum", re.I)
# Coverage status in the "Employee & family information" table (the member's own row)
_FAMILY_SECTION_RE = re.compile(r"Employee\s*&\s*family information(.*?)(?:Dental plan information|$)", re.S | re.I)
_PHONE_RE = re.compile(r"Phone number:\s*\(?(\d{3})\)?[\s.-]*(\d{3})[\s.-]*(\d{4})")
def parse_mh_plan_details(text):
result = {}
m = _PLAN_RE.search(text or "")
if m and m.group(1).strip():
result["planName"] = m.group(1).strip()
m = _REMAINING_RE.search(text or "")
if m:
result["remainingBenefit"] = re.sub(r"\s", "", m.group(1))
sec = _FAMILY_SECTION_RE.search(text or "")
if sec:
# Case-sensitive whole word, so "Inactive" never counts as "Active"
if re.search(r"\bActive\b", sec.group(1)):
result["coverageStatus"] = "active"
elif re.search(r"\b(Inactive|Terminated)\b", sec.group(1)):
result["coverageStatus"] = "inactive"
m = _PHONE_RE.search(text or "")
if m:
result["phone"] = "-".join(m.groups())
return result
def extract_mh_plan_details(driver, timeout=10):
"""Poll because "Deductibles & maximums" fills in after the rest of the page."""
result = {}
try:
deadline = time.time() + timeout
while True:
text = driver.find_element(By.TAG_NAME, "body").get_attribute("innerText") or ""
result = parse_mh_plan_details(text)
if ("planName" in result and "remainingBenefit" in result) or time.time() >= deadline:
break
time.sleep(1)
print(f"[extract_mh_plan_details] {result}")
except Exception as e:
print(f"[extract_mh_plan_details] failed: {e}")
return result
@@ -1,75 +0,0 @@
import time
# Service history table: header cells plus the cell texts of every row.
# innerText (not .text) so cells rendered off-screen still return their text.
_TABLE_JS = """
for (const table of document.querySelectorAll('table')) {
const headers = Array.from(table.querySelectorAll('thead th, thead td'))
.map(th => (th.innerText || th.textContent || '').toLowerCase().replace(/[^a-z]/g, ''));
if (!headers.some(h => h.includes('procedurecode')) || !headers.some(h => h.includes('servicedate'))) continue;
const rows = Array.from(table.querySelectorAll('tbody tr'))
.map(tr => Array.from(tr.querySelectorAll('td'))
.map(td => (td.innerText || td.textContent || '').replace(/\\s+/g, ' ').trim()));
return {headers, rows, paged: !!document.querySelector('.pagination, [class*="paginat"]')};
}
return null;
"""
def _column_indexes(headers):
def find(match):
return next((i for i, h in enumerate(headers) if match(h)), None)
return {
"procedureCode": find(lambda h: "procedurecode" in h and "description" not in h),
"description": find(lambda h: "description" in h),
"toothQuadArchSurface": find(lambda h: "tooth" in h),
"placeOfService": find(lambda h: "placeofservice" in h),
"serviceDate": find(lambda h: "servicedate" in h),
}
def parse_service_history(headers, rows):
"""Map raw table cells to row dicts, dropping placeholder rows (e.g. a
single "no records" cell) and rows without a procedure code."""
columns = _column_indexes(headers)
result = []
for cells in rows:
if len(cells) < len(headers):
continue
row = {
key: cells[i] if i is not None and i < len(cells) else ""
for key, i in columns.items()
}
if row["procedureCode"]:
result.append(row)
return result
def extract_service_history(driver, timeout=15):
"""Read the MassHealth Service History table.
AngularJS adds the rows after the page loads, so keep polling until every
row has its procedure code. A member with no history waits the full
timeout. Returns [] when nothing was found — this can't tell "no history"
from "the page was too slow", so callers must not treat it as "no history".
"""
deadline = time.time() + timeout
history = []
while True:
try:
table = driver.execute_script(_TABLE_JS)
if table:
history = parse_service_history(table["headers"], table["rows"])
if history and len(history) == len(table["rows"]):
if table["paged"]:
print("[extract_service_history] pagination found — only the current page was read")
break
except Exception as e:
print(f"[extract_service_history] reading table failed: {e}")
if time.time() >= deadline:
break
time.sleep(1)
print(f"[extract_service_history] {len(history)} row(s)")
return history
@@ -1,532 +0,0 @@
from selenium import webdriver
from selenium.common import TimeoutException
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import time
import os
import base64
from mh_eligibility_results import extract_eligibility_row
from mh_member_details import extract_member_demographics
from mh_service_history import extract_service_history
class AutomationCMSPEligibilityHistoryRemainingCheck:
def __init__(self, data):
self.headless = False
self.driver = None
self.extracted_data = {}
self.eligibility_tab = None
self.member_details_tab = None
self.accumulator_tab = None
self.data = data.get("data")
self.massdhp_username = self.data.get("massdhpUsername", "")
self.massdhp_password = self.data.get("massdhpPassword", "")
self.dateOfBirth = self.data.get("dateOfBirth", "")
self.memberId = self.data.get("memberId", "")
self.firstName = self.data.get("firstName", "")
self.lastName = self.data.get("lastName", "")
# Convert dateOfBirth from YYYY-MM-DD to MMDDYYYY
if self.dateOfBirth and "-" in self.dateOfBirth:
parts = self.dateOfBirth.split("-")
if len(parts) == 3:
year, month, day = parts
self.dateOfBirth = f"{month.zfill(2)}{day.zfill(2)}{year}"
self.download_dir = os.path.abspath("downloads")
os.makedirs(self.download_dir, exist_ok=True)
# ── driver ──────────────────────────────────────────────────────────────────
def config_driver(self):
options = webdriver.ChromeOptions()
if self.headless:
options.add_argument("--headless")
prefs = {
"download.default_directory": self.download_dir,
"plugins.always_open_pdf_externally": False,
"download.prompt_for_download": False,
"download.directory_upgrade": True,
}
options.add_experimental_option("prefs", prefs)
s = Service(ChromeDriverManager().install())
self.driver = webdriver.Chrome(service=s, options=options)
# ── login (same MassHealth credentials) ─────────────────────────────────────
def login(self):
wait = WebDriverWait(self.driver, 30)
try:
signin_button = wait.until(
EC.element_to_be_clickable(
(By.CSS_SELECTOR, "a.btn.btn-block.btn-primary[href='https://connectsso.masshealth-dental.org/mhprovider/index.html']")
)
)
signin_button.click()
time.sleep(3)
email_field = wait.until(EC.presence_of_element_located((By.ID, "User")))
email_field.clear()
email_field.send_keys(self.massdhp_username)
password_field = wait.until(EC.presence_of_element_located((By.ID, "Password")))
password_field.clear()
password_field.send_keys(self.massdhp_password)
login_button = wait.until(
EC.element_to_be_clickable(
(By.CSS_SELECTOR, "input[type='submit'][name='submit'][value='Login']")
)
)
login_button.click()
return "Success"
except Exception as e:
print(f"[login] Error: {e}")
return "ERROR:LOGIN FAILED"
# ── step 1 — search member, extract eligibility data ────────────────────────
def step1(self):
wait = WebDriverWait(self.driver, 30)
substep = "init"
try:
substep = "patient_management"
patient_mgmt = wait.until(
EC.presence_of_element_located(
(By.XPATH, "//strong[@translate='Patient Management']")
)
)
self.driver.execute_script("arguments[0].scrollIntoView(true);", patient_mgmt)
self.driver.execute_script("arguments[0].click();", patient_mgmt)
time.sleep(2)
substep = "member_eligibility_link"
eligibility_link = wait.until(
EC.presence_of_element_located(
(By.XPATH, "//a[@translate='Member Eligibility']")
)
)
self.driver.execute_script("arguments[0].click();", eligibility_link)
time.sleep(2)
substep = "provider_dropdown"
provider_dropdown = wait.until(
EC.presence_of_element_located((By.NAME, "provider"))
)
select_provider = Select(provider_dropdown)
first_option = next(
(o for o in select_provider.options if o.get_attribute("value").strip()),
select_provider.options[0]
)
select_provider.select_by_value(first_option.get_attribute("value"))
time.sleep(2)
substep = "member_dob"
member_dob = wait.until(
EC.presence_of_all_elements_located((By.NAME, "dateInput"))
)[1]
member_dob.clear()
member_dob.send_keys(self.dateOfBirth)
substep = "member_number"
member_number = wait.until(
EC.presence_of_element_located((By.NAME, "memberNumber"))
)
member_number.clear()
member_number.send_keys(self.memberId)
substep = "search_button"
search_button = wait.until(
EC.element_to_be_clickable((By.XPATH, "//button[contains(@class,'btn-primary')]"))
)
search_button.click()
substep = "wait_results"
wait.until(
EC.presence_of_element_located(
(By.XPATH, "//h4[text()='Eligible' or text()='Ineligible']")
)
)
self.extracted_data = self._extract_data_from_page()
print(f"[step1] data extracted: {self.extracted_data}")
return "Success"
except Exception as e:
print(f"[step1] FAILED at substep='{substep}': {e}")
return f"ERROR:STEP1:{substep}"
# ── helpers ─────────────────────────────────────────────────────────────────
def _extract_data_from_page(self):
# Waits until the matching row's name and plan are filled in
return extract_eligibility_row(self.driver, self.memberId)
# ── step 2 — print eligibility PDF, return to results tab ───────────────────
def step2_eligibility_pdf(self):
wait = WebDriverWait(self.driver, 30)
self.eligibility_tab = self.driver.current_window_handle
try:
download_button = wait.until(
EC.element_to_be_clickable(
(By.XPATH, "//button[contains(.,'Printer Friendly Format')]")
)
)
download_button.click()
try:
WebDriverWait(self.driver, 10).until(lambda d: len(d.window_handles) > 1)
new_tabs = [t for t in self.driver.window_handles if t != self.eligibility_tab]
self.driver.switch_to.window(new_tabs[0])
wait.until(lambda d: d.execute_script("return document.readyState") == "complete")
wait.until(EC.presence_of_element_located((By.TAG_NAME, "body")))
time.sleep(2)
except TimeoutException:
print("No new tab for eligibility; printing current page directly")
safe_member = "".join(c for c in str(self.memberId) if c.isalnum() or c in "-_.")
pdf_filename = f"mh_eligibility_{safe_member}.pdf"
pdf_data = self.driver.execute_cdp_cmd("Page.printToPDF", {"printBackground": True})
pdf_bytes = base64.b64decode(pdf_data["data"])
pdf_path = os.path.join(self.download_dir, pdf_filename)
with open(pdf_path, "wb") as f:
f.write(pdf_bytes)
print("Eligibility PDF saved at:", pdf_path)
if self.driver.current_window_handle != self.eligibility_tab:
self.driver.close()
self.driver.switch_to.window(self.eligibility_tab)
time.sleep(1)
return pdf_path
except Exception as e:
print(f"[step2_eligibility_pdf] failed: {e}")
if self.eligibility_tab and self.driver.current_window_handle != self.eligibility_tab:
try:
self.driver.close()
self.driver.switch_to.window(self.eligibility_tab)
except Exception:
pass
raise
# ── step 3 — click member ID link → member details ──────────────────────────
def step3_click_member_id(self):
wait = WebDriverWait(self.driver, 30)
substep = "ng_bind_link"
try:
member_link = wait.until(
EC.element_to_be_clickable(
(By.CSS_SELECTOR, "a[ng-bind='member.memberNumber']")
)
)
self.driver.execute_script("arguments[0].click();", member_link)
time.sleep(2)
print(f"[step3] clicked member ID link, URL: {self.driver.current_url}")
return "Success"
except Exception as e:
print(f"[step3] FAILED at substep='{substep}': {e}")
return f"ERROR:STEP3:{substep}"
# ── step 3b — print member details page as PDF via CDP ───────────────────────
def extract_third_party_insurance(self):
"""Reads the "Third Party Liability" table (Policy Number | Coverage Type |
Effective Date | Termination Date | Insurer Name | Insurer Payment Order)
and returns the Insurer Name(s), or None if the table has no rows
(i.e. the member has no third-party/2nd insurance).
"""
try:
tables = self.driver.find_elements(By.TAG_NAME, "table")
for table in tables:
rows = table.find_elements(By.TAG_NAME, "tr")
if not rows:
continue
header_cells = [
c.text.strip().lower()
for c in (rows[0].find_elements(By.TAG_NAME, "th") or rows[0].find_elements(By.TAG_NAME, "td"))
]
if "insurer name" not in header_cells:
continue
insurer_idx = header_cells.index("insurer name")
insurers = []
for row in rows[1:]:
cells = row.find_elements(By.TAG_NAME, "td")
if len(cells) <= insurer_idx:
continue
name = cells[insurer_idx].text.strip()
if name:
insurers.append(name)
third_party = ", ".join(insurers) if insurers else None
self.extracted_data["third_party_insurance"] = third_party
print(f"[extract_third_party_insurance] {third_party!r}")
return third_party
print("[extract_third_party_insurance] No 'Third Party Liability' table found")
return None
except Exception as e:
print(f"[extract_third_party_insurance] failed: {e}")
return None
def step3b_member_details_pdf(self):
wait = WebDriverWait(self.driver, 30)
try:
wait.until(lambda d: d.execute_script("return document.readyState") == "complete")
time.sleep(2)
self.extract_third_party_insurance()
# Gender, address and phone from the Member Detail block
details = extract_member_demographics(self.driver)
member_name = details.pop("memberName", "")
# Results table never filled the name in — use the Member Detail heading
if member_name and not self.extracted_data.get("firstName"):
parts = member_name.split()
details["firstName"] = parts[0]
details["lastName"] = " ".join(parts[1:])
self.extracted_data.update(details)
safe_member = "".join(c for c in str(self.memberId) if c.isalnum() or c in "-_.")
pdf_filename = f"mh_member_details_{safe_member}.pdf"
pdf_data = self.driver.execute_cdp_cmd("Page.printToPDF", {"printBackground": True})
pdf_bytes = base64.b64decode(pdf_data["data"])
pdf_path = os.path.join(self.download_dir, pdf_filename)
with open(pdf_path, "wb") as f:
f.write(pdf_bytes)
print("Member details PDF saved at:", pdf_path)
return pdf_path
except Exception as e:
print(f"[step3b_member_details_pdf] failed: {e}")
return None
# ── step 4 — duplicate member details tab ───────────────────────────────────
# Opens the same member details URL in a new tab so that Tab A can navigate
# to service history while Tab B navigates to accumulator independently.
def step4_open_duplicate_tab(self):
try:
self.member_details_tab = self.driver.current_window_handle
member_details_url = self.driver.current_url
self.driver.execute_script("window.open(arguments[0]);", member_details_url)
time.sleep(3)
all_tabs = self.driver.window_handles
self.accumulator_tab = next(
t for t in all_tabs
if t not in [self.eligibility_tab, self.member_details_tab]
)
print(f"[step4] duplicate tab opened: {self.accumulator_tab}")
return "Success"
except Exception as e:
print(f"[step4] FAILED: {e}")
return f"ERROR:STEP4:open_duplicate_tab"
# ── step 5 — Tab A: service history → CDP print ──────────────────────────────
def step5_service_history_pdf(self):
wait = WebDriverWait(self.driver, 30)
try:
self.driver.switch_to.window(self.member_details_tab)
history_link = wait.until(
EC.element_to_be_clickable(
(By.CSS_SELECTOR, "a.btn.btn-primary[href*='service-history']")
)
)
self.driver.execute_script("arguments[0].scrollIntoView(true);", history_link)
self.driver.execute_script("arguments[0].click();", history_link)
time.sleep(2)
wait.until(lambda d: d.execute_script("return document.readyState") == "complete")
time.sleep(3)
service_history = extract_service_history(self.driver)
if service_history:
self.extracted_data["service_history"] = service_history
safe_member = "".join(c for c in str(self.memberId) if c.isalnum() or c in "-_.")
pdf_filename = f"mh_history_{safe_member}.pdf"
pdf_data = self.driver.execute_cdp_cmd("Page.printToPDF", {"printBackground": True})
pdf_bytes = base64.b64decode(pdf_data["data"])
pdf_path = os.path.join(self.download_dir, pdf_filename)
with open(pdf_path, "wb") as f:
f.write(pdf_bytes)
print("History PDF saved at:", pdf_path)
return pdf_path
except Exception as e:
print(f"[step5_service_history_pdf] failed: {e}")
return None
# ── step 6 — Tab B: accumulator → extract remaining → CDP print ─────────────
def extract_remaining_amount(self):
"""Reads the accumulator benefits table and returns the Remaining amount.
Layout (see sample PDF "Accumulator Details"):
Type | Level | Network | Benefit Period | Period | Limit | Applied | Remaining
Prefers the Type="Maximum", Level="Individual" row; falls back to the
first data row with a non-empty Remaining cell if that combination
isn't found (payer may only return one row, or reorder columns).
"""
try:
wait = WebDriverWait(self.driver, 15)
wait.until(EC.presence_of_element_located((By.TAG_NAME, "table")))
tables = self.driver.find_elements(By.TAG_NAME, "table")
for table in tables:
rows = table.find_elements(By.TAG_NAME, "tr")
if not rows:
continue
header_cells = [
c.text.strip().lower()
for c in (rows[0].find_elements(By.TAG_NAME, "th") or rows[0].find_elements(By.TAG_NAME, "td"))
]
if "remaining" not in header_cells:
continue
remaining_idx = header_cells.index("remaining")
type_idx = header_cells.index("type") if "type" in header_cells else None
level_idx = header_cells.index("level") if "level" in header_cells else None
fallback_value = None
best_value = None
for row in rows[1:]:
cells = row.find_elements(By.TAG_NAME, "td")
if len(cells) <= remaining_idx:
continue
cell_texts = [c.text.strip() for c in cells]
value = cell_texts[remaining_idx]
if not value:
continue
if fallback_value is None:
fallback_value = value
type_ok = type_idx is None or "maximum" in cell_texts[type_idx].lower()
level_ok = level_idx is None or "individual" in cell_texts[level_idx].lower()
if type_ok and level_ok:
best_value = value
break
remaining_value = best_value or fallback_value
if remaining_value:
self.extracted_data["remaining_amount"] = remaining_value
print(f"[extract_remaining_amount] Remaining: {remaining_value}")
return remaining_value
print("[extract_remaining_amount] No accumulator table with a 'Remaining' column found")
return None
except Exception as e:
print(f"[extract_remaining_amount] failed: {e}")
return None
def step6_accumulator_pdf(self):
wait = WebDriverWait(self.driver, 30)
try:
self.driver.switch_to.window(self.accumulator_tab)
# Wait for the duplicate member details page to fully load
wait.until(lambda d: d.execute_script("return document.readyState") == "complete")
time.sleep(2)
# Click View Accumulator
accumulator_link = wait.until(
EC.element_to_be_clickable(
(By.CSS_SELECTOR, "a.btn.btn-primary[ng-if='vm.showAccumulator']")
)
)
self.driver.execute_script("arguments[0].scrollIntoView(true);", accumulator_link)
self.driver.execute_script("arguments[0].click();", accumulator_link)
time.sleep(2)
# Wait for accumulator page to load then print whatever is on screen —
# member info is always present even when there are no dollar amounts
wait.until(lambda d: d.execute_script("return document.readyState") == "complete")
time.sleep(4)
self.extract_remaining_amount()
safe_member = "".join(c for c in str(self.memberId) if c.isalnum() or c in "-_.")
pdf_filename = f"mh_accumulator_{safe_member}.pdf"
pdf_data = self.driver.execute_cdp_cmd("Page.printToPDF", {"printBackground": True})
pdf_bytes = base64.b64decode(pdf_data["data"])
pdf_path = os.path.join(self.download_dir, pdf_filename)
with open(pdf_path, "wb") as f:
f.write(pdf_bytes)
print("Accumulator PDF saved at:", pdf_path)
return pdf_path
except Exception as e:
print(f"[step6_accumulator_pdf] failed: {e}")
return None
# ── main workflow ────────────────────────────────────────────────────────────
def main_workflow(self, url):
try:
self.config_driver()
self.driver.maximize_window()
self.driver.get(url)
time.sleep(3)
login_result = self.login()
if login_result.startswith("ERROR"):
return {"status": "error", "message": login_result}
step1_result = self.step1()
if step1_result.startswith("ERROR"):
return {"status": "error", "message": step1_result}
eligibility_pdf_path = self.step2_eligibility_pdf()
step3_result = self.step3_click_member_id()
if step3_result.startswith("ERROR"):
return {"status": "partial", "message": step3_result,
"pdf_path": eligibility_pdf_path, "file_type": "pdf"}
member_details_pdf_path = self.step3b_member_details_pdf()
# Duplicate the member details tab so service history and accumulator
# can be opened independently without back-navigation
step4_result = self.step4_open_duplicate_tab()
if step4_result.startswith("ERROR"):
return {"status": "partial", "message": step4_result,
"pdf_path": eligibility_pdf_path,
"member_details_pdf_path": member_details_pdf_path,
"file_type": "pdf"}
# Tab A: service history PDF
history_pdf_path = self.step5_service_history_pdf()
# Tab B: accumulator PDF
accumulator_pdf_path = self.step6_accumulator_pdf()
result = {
"status": "success",
"pdf_path": eligibility_pdf_path,
"member_details_pdf_path": member_details_pdf_path,
"history_pdf_path": history_pdf_path,
"accumulator_pdf_path": accumulator_pdf_path,
"file_type": "pdf",
"message": "Eligibility, member details, service history, and accumulator PDFs captured",
}
if self.extracted_data:
result.update(self.extracted_data)
return result
except Exception as e:
return {"status": "error", "message": str(e)}
finally:
if self.driver:
self.driver.quit()
@@ -0,0 +1,847 @@
from selenium import webdriver
from selenium.common.exceptions import WebDriverException, TimeoutException
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import time
import os
import re
import base64
from mh_browser_manager import get_browser_manager
# Same DentaQuest provider portal as Tufts SCO, so the page readers are shared
from dentaquest_member_details import extract_member_address
from dentaquest_service_history import extract_service_history
from mh_member_plan import extract_mh_plan_details
MH_BASE_URL = "https://providers.masshealth-dental.org/"
class AutomationMHEligibilityCheck:
"""
MassHealth eligibility on providers.masshealth-dental.org (DentaQuest portal,
same layout as Tufts SCO). Persistent browser profile keeps the login and the
OTP trust cookie between runs.
"""
def __init__(self, data):
self.headless = False
self.driver = None
self.data = data.get("data", {}) if isinstance(data, dict) else {}
# Flatten values for convenience
self.memberId = self.data.get("memberId", "")
self.dateOfBirth = self.data.get("dateOfBirth", "")
self.firstName = self.data.get("firstName", "")
self.lastName = self.data.get("lastName", "")
self.mh_username = self.data.get("mhUsername", "")
self.mh_password = self.data.get("mhPassword", "")
# Use browser manager's download dir
self.download_dir = get_browser_manager().download_dir
os.makedirs(self.download_dir, exist_ok=True)
def config_driver(self):
# Use persistent browser from manager (keeps device trust tokens)
self.driver = get_browser_manager().get_driver(self.headless)
def _force_logout(self):
"""Force logout by clearing cookies for the MassHealth portal."""
try:
print("[MH login] Forcing logout due to credential change...")
browser_manager = get_browser_manager()
# First try to click logout button if visible
try:
self.driver.get(MH_BASE_URL)
time.sleep(2)
logout_selectors = [
"//button[contains(text(), 'Log out') or contains(text(), 'Logout') or contains(text(), 'Sign out')]",
"//a[contains(text(), 'Log out') or contains(text(), 'Logout') or contains(text(), 'Sign out')]",
"//button[@aria-label='Log out' or @aria-label='Logout' or @aria-label='Sign out']",
"//*[contains(@class, 'logout') or contains(@class, 'signout')]"
]
for selector in logout_selectors:
try:
logout_btn = WebDriverWait(self.driver, 3).until(
EC.element_to_be_clickable((By.XPATH, selector))
)
logout_btn.click()
print("[MH login] Clicked logout button")
time.sleep(2)
break
except TimeoutException:
continue
except Exception as e:
print(f"[MH login] Could not click logout button: {e}")
# Clear cookies as backup
try:
self.driver.delete_all_cookies()
print("[MH login] Cleared all cookies")
except Exception as e:
print(f"[MH login] Error clearing cookies: {e}")
browser_manager.clear_credentials_hash()
print("[MH login] Logout complete")
return True
except Exception as e:
print(f"[MH login] Error during forced logout: {e}")
return False
def _is_maintenance_page(self) -> bool:
"""Return True if the current page is the portal's maintenance/capacity error page."""
try:
body = self.driver.find_element(By.TAG_NAME, "body").text
markers = [
"temporarily unable to service",
"maintenance downtime",
"capacity problems",
"Please try again later",
]
body_lower = body.lower()
return any(m.lower() in body_lower for m in markers)
except Exception:
return False
def login(self, url):
wait = WebDriverWait(self.driver, 30)
browser_manager = get_browser_manager()
try:
# Check if credentials have changed - if so, force logout first
if self.mh_username and browser_manager.credentials_changed(self.mh_username):
self._force_logout()
self.driver.get(url)
time.sleep(2)
# First check if we're already on a logged-in page (from previous run)
try:
current_url = self.driver.current_url
print(f"[MH login] Current URL: {current_url}")
# Check if we're already on dashboard with member search
if "dashboard" in current_url.lower() or "member" in current_url.lower():
try:
member_search = WebDriverWait(self.driver, 3).until(
EC.presence_of_element_located((By.XPATH, '//input[@placeholder="Search by member ID"]'))
)
print("[MH login] Already on dashboard with member search")
return "ALREADY_LOGGED_IN"
except TimeoutException:
pass
except Exception as e:
print(f"[MH login] Error checking current state: {e}")
# Navigate to login URL
self.driver.get(url)
time.sleep(3)
if self._is_maintenance_page():
print("[MH login] Maintenance page detected")
return "ERROR: MassHealth portal is temporarily unavailable (maintenance). Please try again later."
current_url = self.driver.current_url
print(f"[MH login] After navigation URL: {current_url}")
# If already on dashboard, we're logged in
if "dashboard" in current_url.lower():
print("[MH login] Already on dashboard")
return "ALREADY_LOGGED_IN"
# Try to dismiss the modal by clicking OK
try:
ok_button = WebDriverWait(self.driver, 5).until(
EC.element_to_be_clickable((By.XPATH, "//button[normalize-space(text())='Ok' or normalize-space(text())='OK' or normalize-space(text())='Continue']"))
)
ok_button.click()
print("[MH login] Clicked OK modal button")
time.sleep(3)
except TimeoutException:
print("[MH login] No OK modal button found")
# Check if we're now on dashboard (session was valid)
current_url = self.driver.current_url
print(f"[MH login] After modal click URL: {current_url}")
if "dashboard" in current_url.lower():
# Check for member search input to confirm logged in
try:
member_search = WebDriverWait(self.driver, 5).until(
EC.presence_of_element_located((By.XPATH, '//input[@placeholder="Search by member ID"]'))
)
print("[MH login] Session valid - on dashboard with member search")
return "ALREADY_LOGGED_IN"
except TimeoutException:
pass
# Check if OTP is required (popup window or OTP input)
if len(self.driver.window_handles) > 1:
original_window = self.driver.current_window_handle
for window in self.driver.window_handles:
if window != original_window:
self.driver.switch_to.window(window)
print("[MH login] Switched to popup window")
break
try:
otp_input = WebDriverWait(self.driver, 5).until(
EC.presence_of_element_located((By.XPATH, "//input[@type='tel' or contains(@placeholder,'code') or contains(@aria-label,'Verification')]"))
)
print("[MH login] OTP input found in popup")
return "OTP_REQUIRED"
except TimeoutException:
self.driver.switch_to.window(original_window)
# Check for OTP input on main page
try:
otp_input = WebDriverWait(self.driver, 3).until(
EC.presence_of_element_located((By.XPATH, "//input[@type='tel' or contains(@placeholder,'code') or contains(@aria-label,'Verification')]"))
)
print("[MH login] OTP input found")
return "OTP_REQUIRED"
except TimeoutException:
pass
# On the sign-in page? (detect by URL or by the username box itself)
on_login_page = "onboarding" in current_url.lower() or "login" in current_url.lower()
if not on_login_page:
on_login_page = bool(self.driver.find_elements(
By.XPATH, "//input[@data-testid='username' or @name='username']"))
if on_login_page:
print("[MH login] Need to fill login credentials")
try:
username_field = WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable((By.XPATH,
"//input[@data-testid='username'] | //input[@name='username']"))
)
username_field.click()
username_field.send_keys(Keys.CONTROL, "a")
username_field.send_keys(Keys.DELETE)
username_field.send_keys(self.mh_username)
password_field = wait.until(EC.element_to_be_clickable((By.XPATH,
"//input[@data-testid='password'] | //input[@name='password'] | //input[@type='password']")))
password_field.click()
password_field.send_keys(Keys.CONTROL, "a")
password_field.send_keys(Keys.DELETE)
password_field.send_keys(self.mh_password)
# Tick "Remember me" (only if not already ticked) so the portal remembers this browser
try:
remember_label = WebDriverWait(self.driver, 3).until(
EC.presence_of_element_located((By.XPATH,
"//label[contains(normalize-space(.),'Remember me')]"))
)
checkbox = remember_label.find_elements(By.XPATH, ".//input[@type='checkbox']")
already = False
if checkbox:
already = checkbox[0].is_selected()
else:
already = remember_label.get_attribute("data-selected") == "true"
if already:
print("[MH login] 'Remember me' already checked")
else:
self.driver.execute_script("arguments[0].click();", remember_label)
print("[MH login] Checked 'Remember me'")
except Exception:
print("[MH login] No 'Remember me' found on login page (continuing)")
# Click "Sign in"
login_button = wait.until(EC.element_to_be_clickable((By.XPATH,
"//button[normalize-space(.)='Sign in'] | //button[@type='submit']")))
login_button.click()
print("[MH login] Submitted login form")
# Save credentials hash after login attempt
if self.mh_username:
browser_manager.save_credentials_hash(self.mh_username)
# OTP detection - wait up to 30 seconds for OTP input to appear (like Delta MA)
# Use comprehensive XPath to detect various OTP input patterns
try:
otp_input = WebDriverWait(self.driver, 30).until(
EC.presence_of_element_located((By.XPATH,
"//input[@type='tel' or contains(@placeholder,'code') or contains(@placeholder,'Code') or "
"contains(@aria-label,'Verification') or contains(@aria-label,'verification') or "
"contains(@aria-label,'Code') or contains(@aria-label,'code') or "
"contains(@placeholder,'verification') or contains(@placeholder,'Verification') or "
"contains(@name,'otp') or contains(@name,'code') or contains(@id,'otp') or contains(@id,'code')]"
))
)
print("[MH login] OTP input detected -> OTP_REQUIRED")
return "OTP_REQUIRED"
except TimeoutException:
print("[MH login] No OTP input detected in 30 seconds")
# Check if login succeeded (redirected to dashboard or member search)
current_url_after_login = self.driver.current_url.lower()
print(f"[MH login] After login URL: {current_url_after_login}")
if "dashboard" in current_url_after_login or "member" in current_url_after_login:
# Verify by checking for member search input
try:
member_search = WebDriverWait(self.driver, 5).until(
EC.presence_of_element_located((By.XPATH, '//input[@placeholder="Search by member ID"]'))
)
print("[MH login] Login successful - now on member search page")
return "SUCCESS"
except TimeoutException:
pass
# Still on login page - login failed
still_on_form = bool(self.driver.find_elements(
By.XPATH, "//input[@data-testid='password']"))
if still_on_form or "onboarding" in current_url_after_login or "login" in current_url_after_login:
print("[MH login] Login failed - still on login page")
return "ERROR: Login failed - check credentials"
except TimeoutException:
print("[MH login] Login form elements not found")
return "ERROR: Login form not found"
# If we got here without going through login, we're already logged in
return "SUCCESS"
except Exception as e:
print(f"[MH login] Exception: {e}")
return f"ERROR:LOGIN FAILED: {e}"
def step1(self):
"""Navigate to member search - fills all available fields (Member ID, First Name, Last Name, DOB)"""
wait = WebDriverWait(self.driver, 30)
try:
# Log what fields are available for search
fields = []
if self.memberId:
fields.append(f"ID: {self.memberId}")
if self.firstName:
fields.append(f"FirstName: {self.firstName}")
if self.lastName:
fields.append(f"LastName: {self.lastName}")
fields.append(f"DOB: {self.dateOfBirth}")
print(f"[MH step1] Starting member search with: {', '.join(fields)}")
if self._is_maintenance_page():
print("[MH step1] Maintenance page detected")
return "ERROR: MassHealth portal is temporarily unavailable (maintenance). Please try again later."
# Wait for page to be ready
time.sleep(2)
# Parse DOB - format: YYYY-MM-DD
try:
dob_parts = self.dateOfBirth.split("-")
dob_year = dob_parts[0]
dob_month = dob_parts[1].zfill(2)
dob_day = dob_parts[2].zfill(2)
print(f"[MH step1] Parsed DOB: {dob_month}/{dob_day}/{dob_year}")
except Exception as e:
print(f"[MH step1] Error parsing DOB: {e}")
return "ERROR: PARSING DOB"
# Helper function to fill contenteditable date spans within a specific container
def fill_date_by_testid(testid, month_val, day_val, year_val, field_name):
try:
container = self.driver.find_element(By.XPATH, f"//div[@data-testid='{testid}']")
month_elem = container.find_element(By.XPATH, ".//span[@data-type='month' and @contenteditable='true']")
day_elem = container.find_element(By.XPATH, ".//span[@data-type='day' and @contenteditable='true']")
year_elem = container.find_element(By.XPATH, ".//span[@data-type='year' and @contenteditable='true']")
def replace_with_sendkeys(el, value):
el.click()
time.sleep(0.05)
el.send_keys(Keys.CONTROL, "a")
el.send_keys(Keys.BACKSPACE)
el.send_keys(value)
replace_with_sendkeys(month_elem, month_val)
time.sleep(0.1)
replace_with_sendkeys(day_elem, day_val)
time.sleep(0.1)
replace_with_sendkeys(year_elem, year_val)
print(f"[MH step1] Filled {field_name}: {month_val}/{day_val}/{year_val}")
return True
except Exception as e:
print(f"[MH step1] Error filling {field_name}: {e}")
return False
# 1. Select Location from dropdown (required field before search)
try:
print("[MH 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"]'))
)
current_loc = (trigger.text or "").strip()
if current_loc and "select" not in current_loc.lower():
# Portal already pre-selected the practice location - keep it
print(f"[MH step1] Location already selected: {current_loc[:60]}")
raise StopIteration
trigger.click()
print("[MH step1] Clicked location dropdown button")
time.sleep(0.5)
location_clicked = True
except StopIteration:
location_clicked = None # already selected
except TimeoutException:
print("[MH 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:
first_option = WebDriverWait(self.driver, 5).until(
EC.element_to_be_clickable((By.XPATH, "(//li[@role='option'])[1]"))
)
opt_text = first_option.get_attribute("aria-label") or first_option.text.strip()
first_option.click()
print(f"[MH step1] Selected location: {opt_text[:60]}")
time.sleep(0.3)
except TimeoutException:
print("[MH step1] Warning: Location options did not appear")
elif location_clicked is False:
print("[MH step1] Warning: Could not find Location dropdown trigger")
except Exception as e:
print(f"[MH step1] Error selecting location: {e}")
time.sleep(0.3)
# 2. Fill Date of Birth with patient's DOB using specific data-testid
fill_date_by_testid("member-search_date-of-birth", dob_month, dob_day, dob_year, "Date of Birth")
time.sleep(0.3)
# 3. Fill Member ID only (search by member ID + DOB only)
if self.memberId:
try:
member_id_input = wait.until(EC.element_to_be_clickable(
(By.XPATH, '//input[@data-testid="member-search_member-id_input"] | //input[@placeholder="Search by member ID"]')
))
member_id_input.click()
member_id_input.send_keys(Keys.CONTROL, "a")
member_id_input.send_keys(Keys.DELETE)
member_id_input.send_keys(self.memberId)
print(f"[MH step1] Entered member ID: {self.memberId}")
time.sleep(0.2)
except Exception as e:
print(f"[MH step1] Warning: Could not fill member ID: {e}")
time.sleep(0.3)
# 4. Click Search button
try:
search_btn = wait.until(EC.element_to_be_clickable(
(By.XPATH, '//button[@data-testid="member-search_search-button"]')
))
search_btn.click()
print("[MH step1] Clicked search button")
except TimeoutException:
# Fallback
try:
search_btn = self.driver.find_element(By.XPATH, '//button[contains(text(),"Search")]')
search_btn.click()
print("[MH step1] Clicked search button (fallback)")
except:
# Press Enter on the last input field
ActionChains(self.driver).send_keys(Keys.RETURN).perform()
print("[MH step1] Pressed Enter to search")
time.sleep(5)
# Check for "no results" error
try:
error_msg = WebDriverWait(self.driver, 3).until(EC.presence_of_element_located(
(By.XPATH, '//*[contains(@data-testid,"no-results") or contains(@class,"no-results") or contains(text(),"No results") or contains(text(),"not found") or contains(text(),"No member found") or contains(text(),"Nothing was found")]')
))
if error_msg and error_msg.is_displayed():
print("[MH step1] No results found")
return "ERROR: INVALID SEARCH CRITERIA"
except TimeoutException:
pass
print("[MH step1] Search completed successfully")
return "Success"
except Exception as e:
print(f"[MH step1] Exception: {e}")
return f"ERROR:STEP1 - {e}"
def step2(self):
"""Get eligibility status, navigate to detail page, and capture PDF"""
wait = WebDriverWait(self.driver, 90)
try:
print("[MH step2] Starting eligibility capture")
# Wait for results table to load (use explicit wait instead of fixed sleep)
try:
WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located((By.XPATH, "//tbody//tr"))
)
except TimeoutException:
print("[MH step2] Warning: Results table not found within timeout")
# 1) Find and extract eligibility status and Member ID from search results
eligibilityText = "unknown"
foundMemberId = ""
# Try to extract Member ID from the first row of search results
# Row format: "NAME\nDOB: MM/DD/YYYY\nMEMBER_ID\n..."
import re
try:
first_row = self.driver.find_element(By.XPATH, "(//tbody//tr)[1]")
row_text = first_row.text.strip()
if row_text:
lines = row_text.split('\n')
# Member ID is typically the 3rd line (index 2) - a pure number
for line in lines:
line = line.strip()
# Member ID is usually a number, could be alphanumeric
# It should be after DOB line and be mostly digits
if line and re.match(r'^[A-Z0-9]{5,}$', line) and re.search(r'\d{5,}', line) and not line.startswith('DOB'):
foundMemberId = line
print(f"[MH step2] Extracted Member ID from row: {foundMemberId}")
break
# Fallback: if we have self.memberId from input, use that
if not foundMemberId and self.memberId:
foundMemberId = self.memberId
print(f"[MH step2] Using input Member ID: {foundMemberId}")
except Exception as e:
print(f"[MH step2] Error extracting Member ID: {e}")
# Fallback to input memberId
if self.memberId:
foundMemberId = self.memberId
# Extract eligibility status from the first result row's "Status" column.
# The badge text sits next to an icon in nested elements, so read the
# whole cell's text instead of matching a single text node.
try:
status_text = self.driver.execute_script("""
const table = document.querySelector('table');
if (!table) return '';
const heads = [...table.querySelectorAll('thead th')].map(
th => (th.innerText || '').trim().toLowerCase());
const idx = heads.findIndex(h => h.startsWith('status'));
const row = table.querySelector('tbody tr');
if (!row) return '';
const cells = row.querySelectorAll('td');
if (idx >= 0 && cells[idx]) return cells[idx].innerText || '';
return row.innerText || '';
""") or ""
status_text = " ".join(status_text.split()).lower()
print(f"[MH step2] Status cell text: '{status_text}'")
# Check negatives first: "inactive" contains "active" and
# "not eligible"/"ineligible" contain "eligible".
if "plan not accepted" in status_text:
eligibilityText = "plan not accepted"
elif re.search(r"\b(inactive|ineligible|not eligible|not active|terminated)\b", status_text):
eligibilityText = "inactive"
elif re.search(r"\b(active|eligible)\b", status_text):
eligibilityText = "active"
except Exception as e:
print(f"[MH step2] Could not read eligibility status: {e}")
print(f"[MH step2] Final eligibility status: {eligibilityText}")
# 2) Find the patient detail link and navigate DIRECTLY to it
print("[MH step2] Looking for patient detail link...")
patient_name_clicked = False
patientName = ""
detail_url = None
current_url_before = self.driver.current_url
print(f"[MH step2] Current URL before: {current_url_before}")
# Find all links in first row and log them
try:
all_links = self.driver.find_elements(By.XPATH, "(//tbody//tr)[1]//a")
print(f"[MH step2] Found {len(all_links)} links in first row:")
for i, link in enumerate(all_links):
href = link.get_attribute("href") or "no-href"
text = link.text.strip() or "(empty text)"
print(f" Link {i}: href={href[:80]}..., text={text}")
except Exception as e:
print(f"[MH step2] Error listing links: {e}")
# Find the patient detail link and extract patient name from row
patient_link_selectors = [
"(//table//tbody//tr)[1]//td[1]//a", # First column link
"(//tbody//tr)[1]//a[contains(@href, 'member-details')]", # member-details link
"(//tbody//tr)[1]//a[contains(@href, 'member')]", # Any member link
]
# First, try to extract patient name from the row text (not the link)
try:
first_row = self.driver.find_element(By.XPATH, "(//tbody//tr)[1]")
row_text = first_row.text.strip()
print(f"[MH step2] First row text: {row_text[:100]}...")
# The name is typically the first line, before "DOB:"
if row_text:
lines = row_text.split('\n')
if lines:
# First line is usually the patient name
potential_name = lines[0].strip()
# Make sure it's not a date or ID
if potential_name and not potential_name.startswith('DOB') and not potential_name.isdigit():
patientName = potential_name
print(f"[MH step2] Extracted patient name from row: '{patientName}'")
except Exception as e:
print(f"[MH step2] Error extracting name from row: {e}")
# Now find the detail link
for selector in patient_link_selectors:
try:
patient_link = WebDriverWait(self.driver, 5).until(
EC.presence_of_element_located((By.XPATH, selector))
)
link_text = patient_link.text.strip()
href = patient_link.get_attribute("href")
print(f"[MH step2] Found patient link: text='{link_text}', href={href}")
# If link has text and we don't have patientName yet, use it
if link_text and not patientName:
patientName = link_text
if href and ("member-details" in href or "member" in href):
detail_url = href
patient_name_clicked = True
print(f"[MH step2] Will navigate directly to: {detail_url}")
break
except Exception as e:
print(f"[MH step2] Selector '{selector}' failed: {e}")
continue
if not detail_url:
# Fallback: Try to find ANY link to member-details
try:
all_links = self.driver.find_elements(By.XPATH, "//a[contains(@href, 'member')]")
if all_links:
detail_url = all_links[0].get_attribute("href")
patient_name_clicked = True
print(f"[MH step2] Found member link: {detail_url}")
except Exception as e:
print(f"[MH step2] Could not find member link: {e}")
# Navigate to detail page DIRECTLY
if patient_name_clicked and detail_url:
print(f"[MH step2] Navigating directly to detail page: {detail_url}")
self.driver.get(detail_url)
time.sleep(3) # Wait for page to load
current_url_after = self.driver.current_url
print(f"[MH step2] Current URL after navigation: {current_url_after}")
if "member-details" in current_url_after or "member" in current_url_after:
print("[MH step2] Successfully navigated to member details page!")
else:
print(f"[MH step2] WARNING: Navigation might have redirected. Current URL: {current_url_after}")
# Wait for page to be ready
try:
WebDriverWait(self.driver, 30).until(
lambda d: d.execute_script("return document.readyState") == "complete"
)
except Exception:
print("[MH step2] Warning: document.readyState did not become 'complete'")
# Wait for member details content to load
print("[MH step2] Waiting for member details content to fully load...")
content_loaded = False
content_selectors = [
"//div[contains(@class,'member') or contains(@class,'detail') or contains(@class,'patient')]",
"//h1",
"//h2",
"//table",
"//*[contains(text(),'Member ID') or contains(text(),'Name') or contains(text(),'Date of Birth')]",
]
for selector in content_selectors:
try:
WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located((By.XPATH, selector))
)
content_loaded = True
print(f"[MH step2] Content element found: {selector}")
break
except:
continue
if not content_loaded:
print("[MH step2] Warning: Could not verify content loaded, waiting extra time...")
# Additional wait for dynamic content
time.sleep(5)
# Try to extract patient name from detailed page if not already found
if not patientName:
detail_name_selectors = [
"//h1",
"//h2",
"//*[contains(@class,'patient-name') or contains(@class,'member-name')]",
"//div[contains(@class,'header')]//span",
]
for selector in detail_name_selectors:
try:
name_elem = self.driver.find_element(By.XPATH, selector)
name_text = name_elem.text.strip()
if name_text and len(name_text) > 1:
if not any(x in name_text.lower() for x in ['active', 'inactive', 'eligible', 'search', 'date', 'print', 'member id']):
patientName = name_text
print(f"[MH step2] Found patient name on detail page: {patientName}")
break
except:
continue
else:
print("[MH step2] Warning: Could not find detail URL, capturing search results page")
# Still try to get patient name from search results
try:
name_elem = self.driver.find_element(By.XPATH, "(//tbody//tr)[1]//td[1]")
patientName = name_elem.text.strip()
except:
pass
if not patientName:
print("[MH 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"[MH step2] Patient name: {patientName}")
# Address from the Member's information block (empty on the search results page)
member_address = extract_member_address(self.driver) if detail_url else {}
service_history = extract_service_history(self.driver) if detail_url else []
plan_details = extract_mh_plan_details(self.driver) if detail_url else {}
# "Plan not accepted" only means this office can't bill the plan;
# the member can still have active coverage.
if eligibilityText == "plan not accepted" and plan_details.get("coverageStatus") == "active":
eligibilityText = "active plan not accepted"
print("[MH step2] Coverage active but plan not accepted -> 'active plan not accepted'")
elif eligibilityText == "unknown" and plan_details.get("coverageStatus"):
# Results badge unreadable: fall back to the member details coverage status
eligibilityText = plan_details["coverageStatus"]
print(f"[MH step2] Status from member details coverage: {eligibilityText}")
# Wait for page to fully load before generating PDF
try:
WebDriverWait(self.driver, 30).until(
lambda d: d.execute_script("return document.readyState") == "complete"
)
except Exception:
pass
time.sleep(1)
# Generate PDF of the detailed patient page using Chrome DevTools Protocol
print("[MH step2] Generating PDF of patient detail page...")
pdf_options = {
"landscape": True,
"displayHeaderFooter": False,
"printBackground": True,
"preferCSSPageSize": False,
"paperWidth": 11,
"paperHeight": 8.5,
"marginTop": 0.3,
"marginBottom": 0.3,
"marginLeft": 0.3,
"marginRight": 0.3,
"scale": 0.7,
}
result = self.driver.execute_cdp_cmd("Page.printToPDF", pdf_options)
pdf_data = base64.b64decode(result.get('data', ''))
pdf_path = os.path.join(self.download_dir, f"mh_eligibility_{self.memberId}_{int(time.time())}.pdf")
with open(pdf_path, "wb") as f:
f.write(pdf_data)
print(f"[MH step2] PDF saved: {pdf_path}")
# Navigate away and minimize — keeps session cookie in memory so next
# run detects ALREADY_LOGGED_IN and skips OTP entirely.
# (OTP is only needed once per app startup, not on every check.)
try:
self.driver.get("about:blank")
try:
self.driver.minimize_window()
except Exception:
try:
self.driver.set_window_position(-10000, -10000)
except Exception:
pass
print("[MH step2] Browser minimized - session preserved for next run")
except Exception as e:
print(f"[MH step2] Error minimizing browser (non-fatal): {e}")
output = {
"status": "success",
"eligibility": eligibilityText,
"ss_path": pdf_path, # Keep key as ss_path for backward compatibility
"pdf_path": pdf_path, # Also add explicit pdf_path
"patientName": patientName,
"memberId": foundMemberId, # Member ID extracted from the page
**member_address, # address, city, state, zipCode
**plan_details, # planName, remainingBenefit, phone
"service_history": service_history,
}
print(f"[MH step2] Success: { {k: v for k, v in output.items() if k != 'service_history'} }")
return output
except Exception as e:
print(f"[MH step2] Exception: {e}")
# Cleanup download folder on error
try:
dl = os.path.abspath(self.download_dir)
if os.path.isdir(dl):
for name in os.listdir(dl):
item = os.path.join(dl, name)
try:
if os.path.isfile(item) or os.path.islink(item):
os.remove(item)
except Exception:
pass
except Exception:
pass
return {"status": "error", "message": str(e)}
def main_workflow(self, url):
try:
self.config_driver()
self.driver.maximize_window()
time.sleep(3)
login_result = self.login(url)
if login_result.startswith("ERROR"):
return {"status": "error", "message": login_result}
if login_result == "OTP_REQUIRED":
return {"status": "otp_required", "message": "OTP required after login"}
step1_result = self.step1()
if step1_result.startswith("ERROR"):
return {"status": "error", "message": step1_result}
step2_result = self.step2()
if step2_result.get("status") == "error":
return {"status": "error", "message": step2_result.get("message")}
return step2_result
except Exception as e:
return {
"status": "error",
"message": str(e)
}
@@ -1,426 +0,0 @@
from selenium import webdriver
from selenium.common import TimeoutException
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import time
import os
import base64
from mh_eligibility_results import extract_eligibility_row
from mh_member_details import extract_member_demographics
class AutomationMassHealthEligibilityHistoryCheck:
def __init__(self, data):
self.headless = False
self.driver = None
self.extracted_data = {}
self.eligibility_tab = None # handle to the eligibility results tab
self.data = data.get("data")
self.massdhp_username = self.data.get("massdhpUsername", "")
self.massdhp_password = self.data.get("massdhpPassword", "")
self.dateOfBirth = self.data.get("dateOfBirth", "")
self.memberId = self.data.get("memberId", "")
self.firstName = self.data.get("firstName", "")
self.lastName = self.data.get("lastName", "")
# Convert dateOfBirth from YYYY-MM-DD to MMDDYYYY
if self.dateOfBirth and "-" in self.dateOfBirth:
parts = self.dateOfBirth.split("-")
if len(parts) == 3:
year, month, day = parts
self.dateOfBirth = f"{month.zfill(2)}{day.zfill(2)}{year}"
self.download_dir = os.path.abspath("downloads")
os.makedirs(self.download_dir, exist_ok=True)
# ── driver ──────────────────────────────────────────────────────────────────
def config_driver(self):
options = webdriver.ChromeOptions()
if self.headless:
options.add_argument("--headless")
prefs = {
"download.default_directory": self.download_dir,
"plugins.always_open_pdf_externally": False,
"download.prompt_for_download": False,
"download.directory_upgrade": True,
}
options.add_experimental_option("prefs", prefs)
s = Service(ChromeDriverManager().install())
self.driver = webdriver.Chrome(service=s, options=options)
# ── login ───────────────────────────────────────────────────────────────────
def login(self):
wait = WebDriverWait(self.driver, 30)
try:
signin_button = wait.until(
EC.element_to_be_clickable(
(By.CSS_SELECTOR, "a.btn.btn-block.btn-primary[href='https://connectsso.masshealth-dental.org/mhprovider/index.html']")
)
)
signin_button.click()
time.sleep(3)
email_field = wait.until(EC.presence_of_element_located((By.ID, "User")))
email_field.clear()
email_field.send_keys(self.massdhp_username)
password_field = wait.until(EC.presence_of_element_located((By.ID, "Password")))
password_field.clear()
password_field.send_keys(self.massdhp_password)
login_button = wait.until(
EC.element_to_be_clickable(
(By.CSS_SELECTOR, "input[type='submit'][name='submit'][value='Login']")
)
)
login_button.click()
# Wait for the SSO redirect. On some machines Chrome opens the dashboard
# in a new tab and closes the SSO tab — poll ALL window handles.
print("[login] Waiting for SSO redirect to provider.masshealth-dental.org ...")
deadline = time.time() + 30
found = False
while time.time() < deadline:
time.sleep(0.5)
for handle in self.driver.window_handles:
try:
self.driver.switch_to.window(handle)
if self.driver.current_url.startswith("https://provider.masshealth-dental.org"):
print(f"[login] Redirect complete. URL: {self.driver.current_url}")
found = True
break
except Exception:
continue
if found:
break
if not found:
print("[login] Redirect timeout — portal window not found in any tab.")
return "ERROR: Login redirect timed out — check credentials or portal availability."
return "Success"
except Exception as e:
print(f"[login] Error: {e}")
return "ERROR:LOGIN FAILED"
# ── step 1 — search member, extract eligibility data ────────────────────────
def step1(self):
wait = WebDriverWait(self.driver, 30)
substep = "init"
try:
print(f"[step1] URL: {self.driver.current_url}")
substep = "patient_management"
patient_mgmt = wait.until(
EC.presence_of_element_located(
(By.XPATH, "//strong[@translate='Patient Management']")
)
)
self.driver.execute_script("arguments[0].scrollIntoView(true);", patient_mgmt)
self.driver.execute_script("arguments[0].click();", patient_mgmt)
time.sleep(2)
substep = "member_eligibility_link"
eligibility_link = wait.until(
EC.presence_of_element_located(
(By.XPATH, "//a[@translate='Member Eligibility']")
)
)
self.driver.execute_script("arguments[0].click();", eligibility_link)
time.sleep(2)
substep = "provider_dropdown"
provider_dropdown = wait.until(
EC.presence_of_element_located((By.NAME, "provider"))
)
select_provider = Select(provider_dropdown)
options = [o.text for o in select_provider.options]
print(f"[step1] provider options: {options}")
substep = "select_provider"
first_option = next(
(o for o in select_provider.options if o.get_attribute("value").strip()),
select_provider.options[0]
)
print(f"[step1] selecting provider: '{first_option.text}'")
select_provider.select_by_value(first_option.get_attribute("value"))
time.sleep(2)
substep = "member_dob"
member_dob = wait.until(
EC.presence_of_all_elements_located((By.NAME, "dateInput"))
)[1]
member_dob.clear()
member_dob.send_keys(self.dateOfBirth)
substep = "member_number"
member_number = wait.until(
EC.presence_of_element_located((By.NAME, "memberNumber"))
)
member_number.clear()
member_number.send_keys(self.memberId)
substep = "search_button"
search_button = wait.until(
EC.element_to_be_clickable((By.XPATH, "//button[contains(@class,'btn-primary')]"))
)
search_button.click()
substep = "wait_results"
wait.until(
EC.presence_of_element_located(
(By.XPATH, "//h4[text()='Eligible' or text()='Ineligible']")
)
)
self.extracted_data = self._extract_data_from_page()
print(f"[step1] data extracted: {self.extracted_data}")
return "Success"
except Exception as e:
print(f"[step1] FAILED at substep='{substep}': {e}")
print(f"[step1] URL at failure: {self.driver.current_url}")
return f"ERROR:STEP1:{substep}"
# ── helpers ─────────────────────────────────────────────────────────────────
def _extract_data_from_page(self):
# Waits until the matching row's name and plan are filled in
return extract_eligibility_row(self.driver, self.memberId)
# ── step 2 — print eligibility PDF, stay on results tab ─────────────────────
def step2_eligibility_pdf(self):
wait = WebDriverWait(self.driver, 30)
self.eligibility_tab = self.driver.current_window_handle
try:
download_button = wait.until(
EC.element_to_be_clickable(
(By.XPATH, "//button[contains(.,'Printer Friendly Format')]")
)
)
download_button.click()
try:
WebDriverWait(self.driver, 10).until(lambda d: len(d.window_handles) > 1)
new_tabs = [t for t in self.driver.window_handles if t != self.eligibility_tab]
self.driver.switch_to.window(new_tabs[0])
wait.until(lambda d: d.execute_script("return document.readyState") == "complete")
wait.until(EC.presence_of_element_located((By.TAG_NAME, "body")))
time.sleep(2)
print("Printer-friendly tab opened:", self.driver.current_url)
except TimeoutException:
print("No new tab for eligibility; printing current page directly")
safe_member = "".join(c for c in str(self.memberId) if c.isalnum() or c in "-_.")
pdf_filename = f"eligibility_{safe_member}.pdf"
pdf_data = self.driver.execute_cdp_cmd("Page.printToPDF", {"printBackground": True})
pdf_bytes = base64.b64decode(pdf_data["data"])
pdf_path = os.path.join(self.download_dir, pdf_filename)
with open(pdf_path, "wb") as f:
f.write(pdf_bytes)
print("Eligibility PDF saved at:", pdf_path)
# Close printer-friendly tab and return to eligibility results
if self.driver.current_window_handle != self.eligibility_tab:
self.driver.close()
self.driver.switch_to.window(self.eligibility_tab)
time.sleep(1)
return pdf_path
except Exception as e:
print(f"[step2_eligibility_pdf] failed: {e}")
# Ensure we are back on the eligibility results tab even on error
if self.eligibility_tab and self.driver.current_window_handle != self.eligibility_tab:
try:
self.driver.close()
self.driver.switch_to.window(self.eligibility_tab)
except Exception:
pass
raise
# ── step 3 — click member ID link → member details page ─────────────────────
def step3_click_member_id(self):
wait = WebDriverWait(self.driver, 30)
substep = "init"
try:
substep = "ng_bind_link"
member_link = wait.until(
EC.element_to_be_clickable(
(By.CSS_SELECTOR, "a[ng-bind='member.memberNumber']")
)
)
self.driver.execute_script("arguments[0].click();", member_link)
time.sleep(2)
print(f"[step3] clicked member ID link, URL: {self.driver.current_url}")
return "Success"
except Exception as e:
print(f"[step3] FAILED at substep='{substep}': {e}")
return f"ERROR:STEP3:{substep}"
# ── step 3b — print member details page as PDF via CDP ───────────────────────
def step3b_member_details_pdf(self):
wait = WebDriverWait(self.driver, 30)
try:
wait.until(lambda d: d.execute_script("return document.readyState") == "complete")
time.sleep(2)
# Gender, address and phone from the Member Detail block
details = extract_member_demographics(self.driver)
member_name = details.pop("memberName", "")
# Results table never filled the name in — use the Member Detail heading
if member_name and not self.extracted_data.get("firstName"):
parts = member_name.split()
details["firstName"] = parts[0]
details["lastName"] = " ".join(parts[1:])
self.extracted_data.update(details)
safe_member = "".join(c for c in str(self.memberId) if c.isalnum() or c in "-_.")
pdf_filename = f"eligibility_member_details_{safe_member}.pdf"
pdf_data = self.driver.execute_cdp_cmd("Page.printToPDF", {"printBackground": True})
pdf_bytes = base64.b64decode(pdf_data["data"])
pdf_path = os.path.join(self.download_dir, pdf_filename)
with open(pdf_path, "wb") as f:
f.write(pdf_bytes)
print("Member details PDF saved at:", pdf_path)
return pdf_path
except Exception as e:
print(f"[step3b_member_details_pdf] failed: {e}")
return None
# ── step 4 — click "View Service History" on member details page ─────────────
def step4_view_service_history(self):
wait = WebDriverWait(self.driver, 30)
substep = "init"
try:
# Primary: href contains /service-history and has btn-primary class
substep = "service_history_link"
history_link = wait.until(
EC.element_to_be_clickable(
(By.CSS_SELECTOR, "a.btn.btn-primary[href*='service-history']")
)
)
self.driver.execute_script("arguments[0].scrollIntoView(true);", history_link)
self.driver.execute_script("arguments[0].click();", history_link)
time.sleep(2)
print(f"[step4] navigated to service history, URL: {self.driver.current_url}")
return "Success"
except Exception as e:
print(f"[step4] FAILED at substep='{substep}': {e}")
return f"ERROR:STEP4:{substep}"
# ── step 5 — print service history PDF ──────────────────────────────────────
def step5_history_pdf(self):
wait = WebDriverWait(self.driver, 30)
current_tab = self.driver.current_window_handle
try:
print_button = wait.until(
EC.element_to_be_clickable(
(By.CSS_SELECTOR, "button.btn.btn-primary[ng-click='vm.printPage()']")
)
)
print_button.click()
try:
WebDriverWait(self.driver, 10).until(lambda d: len(d.window_handles) > 1)
new_tabs = [t for t in self.driver.window_handles if t != current_tab]
self.driver.switch_to.window(new_tabs[0])
wait.until(lambda d: d.execute_script("return document.readyState") == "complete")
wait.until(EC.presence_of_element_located((By.TAG_NAME, "body")))
time.sleep(2)
print("History printer-friendly tab opened:", self.driver.current_url)
except TimeoutException:
print("No new tab for history; printing current page directly")
safe_member = "".join(c for c in str(self.memberId) if c.isalnum() or c in "-_.")
pdf_filename = f"eligibility_history_{safe_member}.pdf"
pdf_data = self.driver.execute_cdp_cmd("Page.printToPDF", {"printBackground": True})
pdf_bytes = base64.b64decode(pdf_data["data"])
pdf_path = os.path.join(self.download_dir, pdf_filename)
with open(pdf_path, "wb") as f:
f.write(pdf_bytes)
print("History PDF saved at:", pdf_path)
return pdf_path
except Exception as e:
print(f"[step5_history_pdf] failed: {e}")
return None
# ── main workflow ────────────────────────────────────────────────────────────
def main_workflow(self, url):
try:
self.config_driver()
self.driver.maximize_window()
self.driver.get(url)
time.sleep(3)
login_result = self.login()
if login_result.startswith("ERROR"):
return {"status": "error", "message": login_result}
step1_result = self.step1()
if step1_result.startswith("ERROR"):
return {"status": "error", "message": step1_result}
# Print eligibility PDF; stays on results tab afterwards
eligibility_pdf_path = self.step2_eligibility_pdf()
# Click the member ID link → member details
step3_result = self.step3_click_member_id()
if step3_result.startswith("ERROR"):
return {
"status": "partial",
"message": step3_result,
"pdf_path": eligibility_pdf_path,
"file_type": "pdf",
}
# Print member details page
member_details_pdf_path = self.step3b_member_details_pdf()
# Click "View Service History"
step4_result = self.step4_view_service_history()
if step4_result.startswith("ERROR"):
return {
"status": "partial",
"message": step4_result,
"pdf_path": eligibility_pdf_path,
"member_details_pdf_path": member_details_pdf_path,
"file_type": "pdf",
}
# Print history PDF
history_pdf_path = self.step5_history_pdf()
result = {
"status": "success",
"pdf_path": eligibility_pdf_path,
"member_details_pdf_path": member_details_pdf_path,
"history_pdf_path": history_pdf_path,
"file_type": "pdf",
"message": "Eligibility, member details, and service history PDFs captured",
}
if self.extracted_data:
result.update(self.extracted_data)
return result
except Exception as e:
return {"status": "error", "message": str(e)}
finally:
if self.driver:
self.driver.quit()
File diff suppressed because one or more lines are too long
@@ -285,7 +285,9 @@ exports.Prisma.InsuranceCredentialScalarFieldEnum = {
userId: 'userId',
siteKey: 'siteKey',
username: 'username',
password: 'password'
password: 'password',
otpContact: 'otpContact',
otpContactPassword: 'otpContactPassword'
};
exports.Prisma.ShoppingVendorScalarFieldEnum = {
@@ -622,7 +624,8 @@ exports.PatientStatus = exports.$Enums.PatientStatus = {
ACTIVE: 'ACTIVE',
INACTIVE: 'INACTIVE',
UNKNOWN: 'UNKNOWN',
PLAN_NOT_ACCEPTED: 'PLAN_NOT_ACCEPTED'
PLAN_NOT_ACCEPTED: 'PLAN_NOT_ACCEPTED',
ACTIVE_PLAN_NOT_ACCEPTED: 'ACTIVE_PLAN_NOT_ACCEPTED'
};
exports.ProcedureSource = exports.$Enums.ProcedureSource = {
+76 -3
View File
@@ -217,7 +217,8 @@ export namespace $Enums {
ACTIVE: 'ACTIVE',
INACTIVE: 'INACTIVE',
UNKNOWN: 'UNKNOWN',
PLAN_NOT_ACCEPTED: 'PLAN_NOT_ACCEPTED'
PLAN_NOT_ACCEPTED: 'PLAN_NOT_ACCEPTED',
ACTIVE_PLAN_NOT_ACCEPTED: 'ACTIVE_PLAN_NOT_ACCEPTED'
};
export type PatientStatus = (typeof PatientStatus)[keyof typeof PatientStatus]
@@ -18922,6 +18923,8 @@ export namespace Prisma {
siteKey: string | null
username: string | null
password: string | null
otpContact: string | null
otpContactPassword: string | null
}
export type InsuranceCredentialMaxAggregateOutputType = {
@@ -18930,6 +18933,8 @@ export namespace Prisma {
siteKey: string | null
username: string | null
password: string | null
otpContact: string | null
otpContactPassword: string | null
}
export type InsuranceCredentialCountAggregateOutputType = {
@@ -18938,6 +18943,8 @@ export namespace Prisma {
siteKey: number
username: number
password: number
otpContact: number
otpContactPassword: number
_all: number
}
@@ -18958,6 +18965,8 @@ export namespace Prisma {
siteKey?: true
username?: true
password?: true
otpContact?: true
otpContactPassword?: true
}
export type InsuranceCredentialMaxAggregateInputType = {
@@ -18966,6 +18975,8 @@ export namespace Prisma {
siteKey?: true
username?: true
password?: true
otpContact?: true
otpContactPassword?: true
}
export type InsuranceCredentialCountAggregateInputType = {
@@ -18974,6 +18985,8 @@ export namespace Prisma {
siteKey?: true
username?: true
password?: true
otpContact?: true
otpContactPassword?: true
_all?: true
}
@@ -19069,6 +19082,8 @@ export namespace Prisma {
siteKey: string
username: string
password: string
otpContact: string | null
otpContactPassword: string | null
_count: InsuranceCredentialCountAggregateOutputType | null
_avg: InsuranceCredentialAvgAggregateOutputType | null
_sum: InsuranceCredentialSumAggregateOutputType | null
@@ -19096,6 +19111,8 @@ export namespace Prisma {
siteKey?: boolean
username?: boolean
password?: boolean
otpContact?: boolean
otpContactPassword?: boolean
user?: boolean | UserDefaultArgs<ExtArgs>
}, ExtArgs["result"]["insuranceCredential"]>
@@ -19105,6 +19122,8 @@ export namespace Prisma {
siteKey?: boolean
username?: boolean
password?: boolean
otpContact?: boolean
otpContactPassword?: boolean
user?: boolean | UserDefaultArgs<ExtArgs>
}, ExtArgs["result"]["insuranceCredential"]>
@@ -19114,6 +19133,8 @@ export namespace Prisma {
siteKey?: boolean
username?: boolean
password?: boolean
otpContact?: boolean
otpContactPassword?: boolean
user?: boolean | UserDefaultArgs<ExtArgs>
}, ExtArgs["result"]["insuranceCredential"]>
@@ -19123,9 +19144,11 @@ export namespace Prisma {
siteKey?: boolean
username?: boolean
password?: boolean
otpContact?: boolean
otpContactPassword?: boolean
}
export type InsuranceCredentialOmit<ExtArgs extends $Extensions.InternalArgs = $Extensions.DefaultArgs> = $Extensions.GetOmit<"id" | "userId" | "siteKey" | "username" | "password", ExtArgs["result"]["insuranceCredential"]>
export type InsuranceCredentialOmit<ExtArgs extends $Extensions.InternalArgs = $Extensions.DefaultArgs> = $Extensions.GetOmit<"id" | "userId" | "siteKey" | "username" | "password" | "otpContact" | "otpContactPassword", ExtArgs["result"]["insuranceCredential"]>
export type InsuranceCredentialInclude<ExtArgs extends $Extensions.InternalArgs = $Extensions.DefaultArgs> = {
user?: boolean | UserDefaultArgs<ExtArgs>
}
@@ -19147,6 +19170,8 @@ export namespace Prisma {
siteKey: string
username: string
password: string
otpContact: string | null
otpContactPassword: string | null
}, ExtArgs["result"]["insuranceCredential"]>
composites: {}
}
@@ -19576,6 +19601,8 @@ export namespace Prisma {
readonly siteKey: FieldRef<"InsuranceCredential", 'String'>
readonly username: FieldRef<"InsuranceCredential", 'String'>
readonly password: FieldRef<"InsuranceCredential", 'String'>
readonly otpContact: FieldRef<"InsuranceCredential", 'String'>
readonly otpContactPassword: FieldRef<"InsuranceCredential", 'String'>
}
@@ -52385,7 +52412,9 @@ export namespace Prisma {
userId: 'userId',
siteKey: 'siteKey',
username: 'username',
password: 'password'
password: 'password',
otpContact: 'otpContact',
otpContactPassword: 'otpContactPassword'
};
export type InsuranceCredentialScalarFieldEnum = (typeof InsuranceCredentialScalarFieldEnum)[keyof typeof InsuranceCredentialScalarFieldEnum]
@@ -54287,6 +54316,8 @@ export namespace Prisma {
siteKey?: StringFilter<"InsuranceCredential"> | string
username?: StringFilter<"InsuranceCredential"> | string
password?: StringFilter<"InsuranceCredential"> | string
otpContact?: StringNullableFilter<"InsuranceCredential"> | string | null
otpContactPassword?: StringNullableFilter<"InsuranceCredential"> | string | null
user?: XOR<UserScalarRelationFilter, UserWhereInput>
}
@@ -54296,6 +54327,8 @@ export namespace Prisma {
siteKey?: SortOrder
username?: SortOrder
password?: SortOrder
otpContact?: SortOrderInput | SortOrder
otpContactPassword?: SortOrderInput | SortOrder
user?: UserOrderByWithRelationInput
}
@@ -54309,6 +54342,8 @@ export namespace Prisma {
siteKey?: StringFilter<"InsuranceCredential"> | string
username?: StringFilter<"InsuranceCredential"> | string
password?: StringFilter<"InsuranceCredential"> | string
otpContact?: StringNullableFilter<"InsuranceCredential"> | string | null
otpContactPassword?: StringNullableFilter<"InsuranceCredential"> | string | null
user?: XOR<UserScalarRelationFilter, UserWhereInput>
}, "id" | "userId_siteKey">
@@ -54318,6 +54353,8 @@ export namespace Prisma {
siteKey?: SortOrder
username?: SortOrder
password?: SortOrder
otpContact?: SortOrderInput | SortOrder
otpContactPassword?: SortOrderInput | SortOrder
_count?: InsuranceCredentialCountOrderByAggregateInput
_avg?: InsuranceCredentialAvgOrderByAggregateInput
_max?: InsuranceCredentialMaxOrderByAggregateInput
@@ -54334,6 +54371,8 @@ export namespace Prisma {
siteKey?: StringWithAggregatesFilter<"InsuranceCredential"> | string
username?: StringWithAggregatesFilter<"InsuranceCredential"> | string
password?: StringWithAggregatesFilter<"InsuranceCredential"> | string
otpContact?: StringNullableWithAggregatesFilter<"InsuranceCredential"> | string | null
otpContactPassword?: StringNullableWithAggregatesFilter<"InsuranceCredential"> | string | null
}
export type ShoppingVendorWhereInput = {
@@ -57642,6 +57681,8 @@ export namespace Prisma {
siteKey: string
username: string
password: string
otpContact?: string | null
otpContactPassword?: string | null
user: UserCreateNestedOneWithoutInsuranceCredentialsInput
}
@@ -57651,12 +57692,16 @@ export namespace Prisma {
siteKey: string
username: string
password: string
otpContact?: string | null
otpContactPassword?: string | null
}
export type InsuranceCredentialUpdateInput = {
siteKey?: StringFieldUpdateOperationsInput | string
username?: StringFieldUpdateOperationsInput | string
password?: StringFieldUpdateOperationsInput | string
otpContact?: NullableStringFieldUpdateOperationsInput | string | null
otpContactPassword?: NullableStringFieldUpdateOperationsInput | string | null
user?: UserUpdateOneRequiredWithoutInsuranceCredentialsNestedInput
}
@@ -57666,6 +57711,8 @@ export namespace Prisma {
siteKey?: StringFieldUpdateOperationsInput | string
username?: StringFieldUpdateOperationsInput | string
password?: StringFieldUpdateOperationsInput | string
otpContact?: NullableStringFieldUpdateOperationsInput | string | null
otpContactPassword?: NullableStringFieldUpdateOperationsInput | string | null
}
export type InsuranceCredentialCreateManyInput = {
@@ -57674,12 +57721,16 @@ export namespace Prisma {
siteKey: string
username: string
password: string
otpContact?: string | null
otpContactPassword?: string | null
}
export type InsuranceCredentialUpdateManyMutationInput = {
siteKey?: StringFieldUpdateOperationsInput | string
username?: StringFieldUpdateOperationsInput | string
password?: StringFieldUpdateOperationsInput | string
otpContact?: NullableStringFieldUpdateOperationsInput | string | null
otpContactPassword?: NullableStringFieldUpdateOperationsInput | string | null
}
export type InsuranceCredentialUncheckedUpdateManyInput = {
@@ -57688,6 +57739,8 @@ export namespace Prisma {
siteKey?: StringFieldUpdateOperationsInput | string
username?: StringFieldUpdateOperationsInput | string
password?: StringFieldUpdateOperationsInput | string
otpContact?: NullableStringFieldUpdateOperationsInput | string | null
otpContactPassword?: NullableStringFieldUpdateOperationsInput | string | null
}
export type ShoppingVendorCreateInput = {
@@ -61084,6 +61137,8 @@ export namespace Prisma {
siteKey?: SortOrder
username?: SortOrder
password?: SortOrder
otpContact?: SortOrder
otpContactPassword?: SortOrder
}
export type InsuranceCredentialAvgOrderByAggregateInput = {
@@ -61097,6 +61152,8 @@ export namespace Prisma {
siteKey?: SortOrder
username?: SortOrder
password?: SortOrder
otpContact?: SortOrder
otpContactPassword?: SortOrder
}
export type InsuranceCredentialMinOrderByAggregateInput = {
@@ -61105,6 +61162,8 @@ export namespace Prisma {
siteKey?: SortOrder
username?: SortOrder
password?: SortOrder
otpContact?: SortOrder
otpContactPassword?: SortOrder
}
export type InsuranceCredentialSumOrderByAggregateInput = {
@@ -66749,6 +66808,8 @@ export namespace Prisma {
siteKey: string
username: string
password: string
otpContact?: string | null
otpContactPassword?: string | null
}
export type InsuranceCredentialUncheckedCreateWithoutUserInput = {
@@ -66756,6 +66817,8 @@ export namespace Prisma {
siteKey: string
username: string
password: string
otpContact?: string | null
otpContactPassword?: string | null
}
export type InsuranceCredentialCreateOrConnectWithoutUserInput = {
@@ -67488,6 +67551,8 @@ export namespace Prisma {
siteKey?: StringFilter<"InsuranceCredential"> | string
username?: StringFilter<"InsuranceCredential"> | string
password?: StringFilter<"InsuranceCredential"> | string
otpContact?: StringNullableFilter<"InsuranceCredential"> | string | null
otpContactPassword?: StringNullableFilter<"InsuranceCredential"> | string | null
}
export type ShoppingVendorUpsertWithWhereUniqueWithoutUserInput = {
@@ -77898,6 +77963,8 @@ export namespace Prisma {
siteKey: string
username: string
password: string
otpContact?: string | null
otpContactPassword?: string | null
}
export type ShoppingVendorCreateManyUserInput = {
@@ -78319,6 +78386,8 @@ export namespace Prisma {
siteKey?: StringFieldUpdateOperationsInput | string
username?: StringFieldUpdateOperationsInput | string
password?: StringFieldUpdateOperationsInput | string
otpContact?: NullableStringFieldUpdateOperationsInput | string | null
otpContactPassword?: NullableStringFieldUpdateOperationsInput | string | null
}
export type InsuranceCredentialUncheckedUpdateWithoutUserInput = {
@@ -78326,6 +78395,8 @@ export namespace Prisma {
siteKey?: StringFieldUpdateOperationsInput | string
username?: StringFieldUpdateOperationsInput | string
password?: StringFieldUpdateOperationsInput | string
otpContact?: NullableStringFieldUpdateOperationsInput | string | null
otpContactPassword?: NullableStringFieldUpdateOperationsInput | string | null
}
export type InsuranceCredentialUncheckedUpdateManyWithoutUserInput = {
@@ -78333,6 +78404,8 @@ export namespace Prisma {
siteKey?: StringFieldUpdateOperationsInput | string
username?: StringFieldUpdateOperationsInput | string
password?: StringFieldUpdateOperationsInput | string
otpContact?: NullableStringFieldUpdateOperationsInput | string | null
otpContactPassword?: NullableStringFieldUpdateOperationsInput | string | null
}
export type ShoppingVendorUpdateWithoutUserInput = {
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1,5 +1,5 @@
{
"name": "prisma-client-10fc1ba8a148de6853a1176026aec60e3b4091a8567504245e0a6db7141aa614",
"name": "prisma-client-c71d49d3d4500cd9341fb5c74b30d2251bfc7d138df9c3f85254a27afe7793b1",
"main": "index.js",
"types": "index.d.ts",
"browser": "default.js",
+10 -5
View File
@@ -107,6 +107,7 @@ enum PatientStatus {
INACTIVE
UNKNOWN
PLAN_NOT_ACCEPTED
ACTIVE_PLAN_NOT_ACCEPTED // coverage active, but the plan isn't accepted at this office
}
model Appointment {
@@ -316,11 +317,15 @@ model ClaimFile {
}
model InsuranceCredential {
id Int @id @default(autoincrement())
userId Int
siteKey String
username String
password String
id Int @id @default(autoincrement())
userId Int
siteKey String
username String
password String
// Email or phone number the portal sends OTP codes to (optional)
otpContact String?
// Password for the OTP email account (optional)
otpContactPassword String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "InsuranceCredential" ADD COLUMN "otpContact" TEXT;
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "InsuranceCredential" ADD COLUMN "otpContactPassword" TEXT;
@@ -0,0 +1 @@
ALTER TYPE "PatientStatus" ADD VALUE IF NOT EXISTS 'ACTIVE_PLAN_NOT_ACCEPTED';
+5
View File
@@ -107,6 +107,7 @@ enum PatientStatus {
INACTIVE
UNKNOWN
PLAN_NOT_ACCEPTED
ACTIVE_PLAN_NOT_ACCEPTED // coverage active, but the plan isn't accepted at this office
}
model Appointment {
@@ -321,6 +322,10 @@ model InsuranceCredential {
siteKey String
username String
password String
// Email or phone number the portal sends OTP codes to (optional)
otpContact String?
// Password for the OTP email account (optional)
otpContactPassword String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@ -1,7 +1,7 @@
{
"version": "1.0",
"generatorVersion": "1.0.0",
"generatedAt": "2026-11-26T19:00:45.737Z",
"generatedAt": "2026-12-05T04:32:03.732Z",
"outputPath": "/home/ee/Desktop/DentalManagement09/packages/db/shared",
"files": [
"schemas/enums/TransactionIsolationLevel.schema.ts",
@@ -1,5 +1,5 @@
import * as z from 'zod';
export const InsuranceCredentialScalarFieldEnumSchema = z.enum(['id', 'userId', 'siteKey', 'username', 'password'])
export const InsuranceCredentialScalarFieldEnumSchema = z.enum(['id', 'userId', 'siteKey', 'username', 'password', 'otpContact', 'otpContactPassword'])
export type InsuranceCredentialScalarFieldEnum = z.infer<typeof InsuranceCredentialScalarFieldEnumSchema>;
@@ -1,5 +1,5 @@
import * as z from 'zod';
export const PatientStatusSchema = z.enum(['ACTIVE', 'INACTIVE', 'UNKNOWN', 'PLAN_NOT_ACCEPTED'])
export const PatientStatusSchema = z.enum(['ACTIVE', 'INACTIVE', 'UNKNOWN', 'PLAN_NOT_ACCEPTED', 'ACTIVE_PLAN_NOT_ACCEPTED'])
export type PatientStatus = z.infer<typeof PatientStatusSchema>;
@@ -15,6 +15,8 @@ export const InsuranceCredentialFindFirstSelectSchema: z.ZodType<Prisma.Insuranc
siteKey: z.boolean().optional(),
username: z.boolean().optional(),
password: z.boolean().optional(),
otpContact: z.boolean().optional(),
otpContactPassword: z.boolean().optional(),
user: z.boolean().optional()
}).strict() as unknown as z.ZodType<Prisma.InsuranceCredentialSelect>;
@@ -24,6 +26,8 @@ export const InsuranceCredentialFindFirstSelectZodSchema = z.object({
siteKey: z.boolean().optional(),
username: z.boolean().optional(),
password: z.boolean().optional(),
otpContact: z.boolean().optional(),
otpContactPassword: z.boolean().optional(),
user: z.boolean().optional()
}).strict();
@@ -15,6 +15,8 @@ export const InsuranceCredentialFindFirstOrThrowSelectSchema: z.ZodType<Prisma.I
siteKey: z.boolean().optional(),
username: z.boolean().optional(),
password: z.boolean().optional(),
otpContact: z.boolean().optional(),
otpContactPassword: z.boolean().optional(),
user: z.boolean().optional()
}).strict() as unknown as z.ZodType<Prisma.InsuranceCredentialSelect>;
@@ -24,6 +26,8 @@ export const InsuranceCredentialFindFirstOrThrowSelectZodSchema = z.object({
siteKey: z.boolean().optional(),
username: z.boolean().optional(),
password: z.boolean().optional(),
otpContact: z.boolean().optional(),
otpContactPassword: z.boolean().optional(),
user: z.boolean().optional()
}).strict();
@@ -15,6 +15,8 @@ export const InsuranceCredentialFindManySelectSchema: z.ZodType<Prisma.Insurance
siteKey: z.boolean().optional(),
username: z.boolean().optional(),
password: z.boolean().optional(),
otpContact: z.boolean().optional(),
otpContactPassword: z.boolean().optional(),
user: z.boolean().optional()
}).strict() as unknown as z.ZodType<Prisma.InsuranceCredentialSelect>;
@@ -24,6 +26,8 @@ export const InsuranceCredentialFindManySelectZodSchema = z.object({
siteKey: z.boolean().optional(),
username: z.boolean().optional(),
password: z.boolean().optional(),
otpContact: z.boolean().optional(),
otpContactPassword: z.boolean().optional(),
user: z.boolean().optional()
}).strict();
@@ -8,6 +8,8 @@ const makeSchema = () => z.object({
siteKey: z.literal(true).optional(),
username: z.literal(true).optional(),
password: z.literal(true).optional(),
otpContact: z.literal(true).optional(),
otpContactPassword: z.literal(true).optional(),
_all: z.literal(true).optional()
}).strict();
export const InsuranceCredentialCountAggregateInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialCountAggregateInputType> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialCountAggregateInputType>;
@@ -7,7 +7,9 @@ const makeSchema = () => z.object({
userId: SortOrderSchema.optional(),
siteKey: SortOrderSchema.optional(),
username: SortOrderSchema.optional(),
password: SortOrderSchema.optional()
password: SortOrderSchema.optional(),
otpContact: SortOrderSchema.optional(),
otpContactPassword: SortOrderSchema.optional()
}).strict();
export const InsuranceCredentialCountOrderByAggregateInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialCountOrderByAggregateInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialCountOrderByAggregateInput>;
export const InsuranceCredentialCountOrderByAggregateInputObjectZodSchema = makeSchema();
@@ -6,6 +6,8 @@ const makeSchema = () => z.object({
siteKey: z.string(),
username: z.string(),
password: z.string(),
otpContact: z.string().optional().nullable(),
otpContactPassword: z.string().optional().nullable(),
user: z.lazy(() => UserCreateNestedOneWithoutInsuranceCredentialsInputObjectSchema)
}).strict();
export const InsuranceCredentialCreateInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialCreateInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialCreateInput>;
@@ -7,7 +7,9 @@ const makeSchema = () => z.object({
userId: z.number().int(),
siteKey: z.string(),
username: z.string(),
password: z.string()
password: z.string(),
otpContact: z.string().optional().nullable(),
otpContactPassword: z.string().optional().nullable()
}).strict();
export const InsuranceCredentialCreateManyInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialCreateManyInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialCreateManyInput>;
export const InsuranceCredentialCreateManyInputObjectZodSchema = makeSchema();
@@ -6,7 +6,9 @@ const makeSchema = () => z.object({
id: z.number().int().optional(),
siteKey: z.string(),
username: z.string(),
password: z.string()
password: z.string(),
otpContact: z.string().optional().nullable(),
otpContactPassword: z.string().optional().nullable()
}).strict();
export const InsuranceCredentialCreateManyUserInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialCreateManyUserInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialCreateManyUserInput>;
export const InsuranceCredentialCreateManyUserInputObjectZodSchema = makeSchema();
@@ -5,7 +5,9 @@ import type { Prisma } from '../../../generated/prisma';
const makeSchema = () => z.object({
siteKey: z.string(),
username: z.string(),
password: z.string()
password: z.string(),
otpContact: z.string().optional().nullable(),
otpContactPassword: z.string().optional().nullable()
}).strict();
export const InsuranceCredentialCreateWithoutUserInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialCreateWithoutUserInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialCreateWithoutUserInput>;
export const InsuranceCredentialCreateWithoutUserInputObjectZodSchema = makeSchema();
@@ -7,7 +7,9 @@ const makeSchema = () => z.object({
userId: z.literal(true).optional(),
siteKey: z.literal(true).optional(),
username: z.literal(true).optional(),
password: z.literal(true).optional()
password: z.literal(true).optional(),
otpContact: z.literal(true).optional(),
otpContactPassword: z.literal(true).optional()
}).strict();
export const InsuranceCredentialMaxAggregateInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialMaxAggregateInputType> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialMaxAggregateInputType>;
export const InsuranceCredentialMaxAggregateInputObjectZodSchema = makeSchema();
@@ -7,7 +7,9 @@ const makeSchema = () => z.object({
userId: SortOrderSchema.optional(),
siteKey: SortOrderSchema.optional(),
username: SortOrderSchema.optional(),
password: SortOrderSchema.optional()
password: SortOrderSchema.optional(),
otpContact: SortOrderSchema.optional(),
otpContactPassword: SortOrderSchema.optional()
}).strict();
export const InsuranceCredentialMaxOrderByAggregateInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialMaxOrderByAggregateInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialMaxOrderByAggregateInput>;
export const InsuranceCredentialMaxOrderByAggregateInputObjectZodSchema = makeSchema();
@@ -7,7 +7,9 @@ const makeSchema = () => z.object({
userId: z.literal(true).optional(),
siteKey: z.literal(true).optional(),
username: z.literal(true).optional(),
password: z.literal(true).optional()
password: z.literal(true).optional(),
otpContact: z.literal(true).optional(),
otpContactPassword: z.literal(true).optional()
}).strict();
export const InsuranceCredentialMinAggregateInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialMinAggregateInputType> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialMinAggregateInputType>;
export const InsuranceCredentialMinAggregateInputObjectZodSchema = makeSchema();
@@ -7,7 +7,9 @@ const makeSchema = () => z.object({
userId: SortOrderSchema.optional(),
siteKey: SortOrderSchema.optional(),
username: SortOrderSchema.optional(),
password: SortOrderSchema.optional()
password: SortOrderSchema.optional(),
otpContact: SortOrderSchema.optional(),
otpContactPassword: SortOrderSchema.optional()
}).strict();
export const InsuranceCredentialMinOrderByAggregateInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialMinOrderByAggregateInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialMinOrderByAggregateInput>;
export const InsuranceCredentialMinOrderByAggregateInputObjectZodSchema = makeSchema();
@@ -1,6 +1,7 @@
import * as z from 'zod';
import type { Prisma } from '../../../generated/prisma';
import { SortOrderSchema } from '../enums/SortOrder.schema';
import { SortOrderInputObjectSchema as SortOrderInputObjectSchema } from './SortOrderInput.schema';
import { InsuranceCredentialCountOrderByAggregateInputObjectSchema as InsuranceCredentialCountOrderByAggregateInputObjectSchema } from './InsuranceCredentialCountOrderByAggregateInput.schema';
import { InsuranceCredentialAvgOrderByAggregateInputObjectSchema as InsuranceCredentialAvgOrderByAggregateInputObjectSchema } from './InsuranceCredentialAvgOrderByAggregateInput.schema';
import { InsuranceCredentialMaxOrderByAggregateInputObjectSchema as InsuranceCredentialMaxOrderByAggregateInputObjectSchema } from './InsuranceCredentialMaxOrderByAggregateInput.schema';
@@ -13,6 +14,8 @@ const makeSchema = () => z.object({
siteKey: SortOrderSchema.optional(),
username: SortOrderSchema.optional(),
password: SortOrderSchema.optional(),
otpContact: z.union([SortOrderSchema, z.lazy(() => SortOrderInputObjectSchema)]).optional(),
otpContactPassword: z.union([SortOrderSchema, z.lazy(() => SortOrderInputObjectSchema)]).optional(),
_count: z.lazy(() => InsuranceCredentialCountOrderByAggregateInputObjectSchema).optional(),
_avg: z.lazy(() => InsuranceCredentialAvgOrderByAggregateInputObjectSchema).optional(),
_max: z.lazy(() => InsuranceCredentialMaxOrderByAggregateInputObjectSchema).optional(),
@@ -1,6 +1,7 @@
import * as z from 'zod';
import type { Prisma } from '../../../generated/prisma';
import { SortOrderSchema } from '../enums/SortOrder.schema';
import { SortOrderInputObjectSchema as SortOrderInputObjectSchema } from './SortOrderInput.schema';
import { UserOrderByWithRelationInputObjectSchema as UserOrderByWithRelationInputObjectSchema } from './UserOrderByWithRelationInput.schema'
const makeSchema = () => z.object({
@@ -9,6 +10,8 @@ const makeSchema = () => z.object({
siteKey: SortOrderSchema.optional(),
username: SortOrderSchema.optional(),
password: SortOrderSchema.optional(),
otpContact: z.union([SortOrderSchema, z.lazy(() => SortOrderInputObjectSchema)]).optional(),
otpContactPassword: z.union([SortOrderSchema, z.lazy(() => SortOrderInputObjectSchema)]).optional(),
user: z.lazy(() => UserOrderByWithRelationInputObjectSchema).optional()
}).strict();
export const InsuranceCredentialOrderByWithRelationInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialOrderByWithRelationInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialOrderByWithRelationInput>;
@@ -1,7 +1,8 @@
import * as z from 'zod';
import type { Prisma } from '../../../generated/prisma';
import { IntFilterObjectSchema as IntFilterObjectSchema } from './IntFilter.schema';
import { StringFilterObjectSchema as StringFilterObjectSchema } from './StringFilter.schema'
import { StringFilterObjectSchema as StringFilterObjectSchema } from './StringFilter.schema';
import { StringNullableFilterObjectSchema as StringNullableFilterObjectSchema } from './StringNullableFilter.schema'
const insurancecredentialscalarwhereinputSchema = z.object({
AND: z.union([z.lazy(() => InsuranceCredentialScalarWhereInputObjectSchema), z.lazy(() => InsuranceCredentialScalarWhereInputObjectSchema).array()]).optional(),
@@ -11,7 +12,9 @@ const insurancecredentialscalarwhereinputSchema = z.object({
userId: z.union([z.lazy(() => IntFilterObjectSchema), z.number().int()]).optional(),
siteKey: z.union([z.lazy(() => StringFilterObjectSchema), z.string()]).optional(),
username: z.union([z.lazy(() => StringFilterObjectSchema), z.string()]).optional(),
password: z.union([z.lazy(() => StringFilterObjectSchema), z.string()]).optional()
password: z.union([z.lazy(() => StringFilterObjectSchema), z.string()]).optional(),
otpContact: z.union([z.lazy(() => StringNullableFilterObjectSchema), z.string()]).optional().nullable(),
otpContactPassword: z.union([z.lazy(() => StringNullableFilterObjectSchema), z.string()]).optional().nullable()
}).strict();
export const InsuranceCredentialScalarWhereInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialScalarWhereInput> = insurancecredentialscalarwhereinputSchema as unknown as z.ZodType<Prisma.InsuranceCredentialScalarWhereInput>;
export const InsuranceCredentialScalarWhereInputObjectZodSchema = insurancecredentialscalarwhereinputSchema;
@@ -1,7 +1,8 @@
import * as z from 'zod';
import type { Prisma } from '../../../generated/prisma';
import { IntWithAggregatesFilterObjectSchema as IntWithAggregatesFilterObjectSchema } from './IntWithAggregatesFilter.schema';
import { StringWithAggregatesFilterObjectSchema as StringWithAggregatesFilterObjectSchema } from './StringWithAggregatesFilter.schema'
import { StringWithAggregatesFilterObjectSchema as StringWithAggregatesFilterObjectSchema } from './StringWithAggregatesFilter.schema';
import { StringNullableWithAggregatesFilterObjectSchema as StringNullableWithAggregatesFilterObjectSchema } from './StringNullableWithAggregatesFilter.schema'
const insurancecredentialscalarwherewithaggregatesinputSchema = z.object({
AND: z.union([z.lazy(() => InsuranceCredentialScalarWhereWithAggregatesInputObjectSchema), z.lazy(() => InsuranceCredentialScalarWhereWithAggregatesInputObjectSchema).array()]).optional(),
@@ -11,7 +12,9 @@ const insurancecredentialscalarwherewithaggregatesinputSchema = z.object({
userId: z.union([z.lazy(() => IntWithAggregatesFilterObjectSchema), z.number().int()]).optional(),
siteKey: z.union([z.lazy(() => StringWithAggregatesFilterObjectSchema), z.string()]).optional(),
username: z.union([z.lazy(() => StringWithAggregatesFilterObjectSchema), z.string()]).optional(),
password: z.union([z.lazy(() => StringWithAggregatesFilterObjectSchema), z.string()]).optional()
password: z.union([z.lazy(() => StringWithAggregatesFilterObjectSchema), z.string()]).optional(),
otpContact: z.union([z.lazy(() => StringNullableWithAggregatesFilterObjectSchema), z.string()]).optional().nullable(),
otpContactPassword: z.union([z.lazy(() => StringNullableWithAggregatesFilterObjectSchema), z.string()]).optional().nullable()
}).strict();
export const InsuranceCredentialScalarWhereWithAggregatesInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialScalarWhereWithAggregatesInput> = insurancecredentialscalarwherewithaggregatesinputSchema as unknown as z.ZodType<Prisma.InsuranceCredentialScalarWhereWithAggregatesInput>;
export const InsuranceCredentialScalarWhereWithAggregatesInputObjectZodSchema = insurancecredentialscalarwherewithaggregatesinputSchema;
@@ -8,6 +8,8 @@ const makeSchema = () => z.object({
siteKey: z.boolean().optional(),
username: z.boolean().optional(),
password: z.boolean().optional(),
otpContact: z.boolean().optional(),
otpContactPassword: z.boolean().optional(),
user: z.union([z.boolean(), z.lazy(() => UserArgsObjectSchema)]).optional()
}).strict();
export const InsuranceCredentialSelectObjectSchema: z.ZodType<Prisma.InsuranceCredentialSelect> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialSelect>;
@@ -7,7 +7,9 @@ const makeSchema = () => z.object({
userId: z.number().int(),
siteKey: z.string(),
username: z.string(),
password: z.string()
password: z.string(),
otpContact: z.string().optional().nullable(),
otpContactPassword: z.string().optional().nullable()
}).strict();
export const InsuranceCredentialUncheckedCreateInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialUncheckedCreateInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialUncheckedCreateInput>;
export const InsuranceCredentialUncheckedCreateInputObjectZodSchema = makeSchema();
@@ -6,7 +6,9 @@ const makeSchema = () => z.object({
id: z.number().int().optional(),
siteKey: z.string(),
username: z.string(),
password: z.string()
password: z.string(),
otpContact: z.string().optional().nullable(),
otpContactPassword: z.string().optional().nullable()
}).strict();
export const InsuranceCredentialUncheckedCreateWithoutUserInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialUncheckedCreateWithoutUserInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialUncheckedCreateWithoutUserInput>;
export const InsuranceCredentialUncheckedCreateWithoutUserInputObjectZodSchema = makeSchema();
@@ -1,14 +1,17 @@
import * as z from 'zod';
import type { Prisma } from '../../../generated/prisma';
import { IntFieldUpdateOperationsInputObjectSchema as IntFieldUpdateOperationsInputObjectSchema } from './IntFieldUpdateOperationsInput.schema';
import { StringFieldUpdateOperationsInputObjectSchema as StringFieldUpdateOperationsInputObjectSchema } from './StringFieldUpdateOperationsInput.schema'
import { StringFieldUpdateOperationsInputObjectSchema as StringFieldUpdateOperationsInputObjectSchema } from './StringFieldUpdateOperationsInput.schema';
import { NullableStringFieldUpdateOperationsInputObjectSchema as NullableStringFieldUpdateOperationsInputObjectSchema } from './NullableStringFieldUpdateOperationsInput.schema'
const makeSchema = () => z.object({
id: z.union([z.number().int(), z.lazy(() => IntFieldUpdateOperationsInputObjectSchema)]).optional(),
userId: z.union([z.number().int(), z.lazy(() => IntFieldUpdateOperationsInputObjectSchema)]).optional(),
siteKey: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
username: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
password: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional()
password: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
otpContact: z.union([z.string(), z.lazy(() => NullableStringFieldUpdateOperationsInputObjectSchema)]).optional().nullable(),
otpContactPassword: z.union([z.string(), z.lazy(() => NullableStringFieldUpdateOperationsInputObjectSchema)]).optional().nullable()
}).strict();
export const InsuranceCredentialUncheckedUpdateInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialUncheckedUpdateInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialUncheckedUpdateInput>;
export const InsuranceCredentialUncheckedUpdateInputObjectZodSchema = makeSchema();
@@ -1,14 +1,17 @@
import * as z from 'zod';
import type { Prisma } from '../../../generated/prisma';
import { IntFieldUpdateOperationsInputObjectSchema as IntFieldUpdateOperationsInputObjectSchema } from './IntFieldUpdateOperationsInput.schema';
import { StringFieldUpdateOperationsInputObjectSchema as StringFieldUpdateOperationsInputObjectSchema } from './StringFieldUpdateOperationsInput.schema'
import { StringFieldUpdateOperationsInputObjectSchema as StringFieldUpdateOperationsInputObjectSchema } from './StringFieldUpdateOperationsInput.schema';
import { NullableStringFieldUpdateOperationsInputObjectSchema as NullableStringFieldUpdateOperationsInputObjectSchema } from './NullableStringFieldUpdateOperationsInput.schema'
const makeSchema = () => z.object({
id: z.union([z.number().int(), z.lazy(() => IntFieldUpdateOperationsInputObjectSchema)]).optional(),
userId: z.union([z.number().int(), z.lazy(() => IntFieldUpdateOperationsInputObjectSchema)]).optional(),
siteKey: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
username: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
password: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional()
password: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
otpContact: z.union([z.string(), z.lazy(() => NullableStringFieldUpdateOperationsInputObjectSchema)]).optional().nullable(),
otpContactPassword: z.union([z.string(), z.lazy(() => NullableStringFieldUpdateOperationsInputObjectSchema)]).optional().nullable()
}).strict();
export const InsuranceCredentialUncheckedUpdateManyInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialUncheckedUpdateManyInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialUncheckedUpdateManyInput>;
export const InsuranceCredentialUncheckedUpdateManyInputObjectZodSchema = makeSchema();
@@ -1,13 +1,16 @@
import * as z from 'zod';
import type { Prisma } from '../../../generated/prisma';
import { IntFieldUpdateOperationsInputObjectSchema as IntFieldUpdateOperationsInputObjectSchema } from './IntFieldUpdateOperationsInput.schema';
import { StringFieldUpdateOperationsInputObjectSchema as StringFieldUpdateOperationsInputObjectSchema } from './StringFieldUpdateOperationsInput.schema'
import { StringFieldUpdateOperationsInputObjectSchema as StringFieldUpdateOperationsInputObjectSchema } from './StringFieldUpdateOperationsInput.schema';
import { NullableStringFieldUpdateOperationsInputObjectSchema as NullableStringFieldUpdateOperationsInputObjectSchema } from './NullableStringFieldUpdateOperationsInput.schema'
const makeSchema = () => z.object({
id: z.union([z.number().int(), z.lazy(() => IntFieldUpdateOperationsInputObjectSchema)]).optional(),
siteKey: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
username: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
password: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional()
password: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
otpContact: z.union([z.string(), z.lazy(() => NullableStringFieldUpdateOperationsInputObjectSchema)]).optional().nullable(),
otpContactPassword: z.union([z.string(), z.lazy(() => NullableStringFieldUpdateOperationsInputObjectSchema)]).optional().nullable()
}).strict();
export const InsuranceCredentialUncheckedUpdateManyWithoutUserInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialUncheckedUpdateManyWithoutUserInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialUncheckedUpdateManyWithoutUserInput>;
export const InsuranceCredentialUncheckedUpdateManyWithoutUserInputObjectZodSchema = makeSchema();
@@ -1,13 +1,16 @@
import * as z from 'zod';
import type { Prisma } from '../../../generated/prisma';
import { IntFieldUpdateOperationsInputObjectSchema as IntFieldUpdateOperationsInputObjectSchema } from './IntFieldUpdateOperationsInput.schema';
import { StringFieldUpdateOperationsInputObjectSchema as StringFieldUpdateOperationsInputObjectSchema } from './StringFieldUpdateOperationsInput.schema'
import { StringFieldUpdateOperationsInputObjectSchema as StringFieldUpdateOperationsInputObjectSchema } from './StringFieldUpdateOperationsInput.schema';
import { NullableStringFieldUpdateOperationsInputObjectSchema as NullableStringFieldUpdateOperationsInputObjectSchema } from './NullableStringFieldUpdateOperationsInput.schema'
const makeSchema = () => z.object({
id: z.union([z.number().int(), z.lazy(() => IntFieldUpdateOperationsInputObjectSchema)]).optional(),
siteKey: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
username: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
password: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional()
password: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
otpContact: z.union([z.string(), z.lazy(() => NullableStringFieldUpdateOperationsInputObjectSchema)]).optional().nullable(),
otpContactPassword: z.union([z.string(), z.lazy(() => NullableStringFieldUpdateOperationsInputObjectSchema)]).optional().nullable()
}).strict();
export const InsuranceCredentialUncheckedUpdateWithoutUserInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialUncheckedUpdateWithoutUserInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialUncheckedUpdateWithoutUserInput>;
export const InsuranceCredentialUncheckedUpdateWithoutUserInputObjectZodSchema = makeSchema();
@@ -1,12 +1,15 @@
import * as z from 'zod';
import type { Prisma } from '../../../generated/prisma';
import { StringFieldUpdateOperationsInputObjectSchema as StringFieldUpdateOperationsInputObjectSchema } from './StringFieldUpdateOperationsInput.schema';
import { NullableStringFieldUpdateOperationsInputObjectSchema as NullableStringFieldUpdateOperationsInputObjectSchema } from './NullableStringFieldUpdateOperationsInput.schema';
import { UserUpdateOneRequiredWithoutInsuranceCredentialsNestedInputObjectSchema as UserUpdateOneRequiredWithoutInsuranceCredentialsNestedInputObjectSchema } from './UserUpdateOneRequiredWithoutInsuranceCredentialsNestedInput.schema'
const makeSchema = () => z.object({
siteKey: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
username: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
password: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
otpContact: z.union([z.string(), z.lazy(() => NullableStringFieldUpdateOperationsInputObjectSchema)]).optional().nullable(),
otpContactPassword: z.union([z.string(), z.lazy(() => NullableStringFieldUpdateOperationsInputObjectSchema)]).optional().nullable(),
user: z.lazy(() => UserUpdateOneRequiredWithoutInsuranceCredentialsNestedInputObjectSchema).optional()
}).strict();
export const InsuranceCredentialUpdateInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialUpdateInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialUpdateInput>;
@@ -1,11 +1,14 @@
import * as z from 'zod';
import type { Prisma } from '../../../generated/prisma';
import { StringFieldUpdateOperationsInputObjectSchema as StringFieldUpdateOperationsInputObjectSchema } from './StringFieldUpdateOperationsInput.schema'
import { StringFieldUpdateOperationsInputObjectSchema as StringFieldUpdateOperationsInputObjectSchema } from './StringFieldUpdateOperationsInput.schema';
import { NullableStringFieldUpdateOperationsInputObjectSchema as NullableStringFieldUpdateOperationsInputObjectSchema } from './NullableStringFieldUpdateOperationsInput.schema'
const makeSchema = () => z.object({
siteKey: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
username: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
password: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional()
password: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
otpContact: z.union([z.string(), z.lazy(() => NullableStringFieldUpdateOperationsInputObjectSchema)]).optional().nullable(),
otpContactPassword: z.union([z.string(), z.lazy(() => NullableStringFieldUpdateOperationsInputObjectSchema)]).optional().nullable()
}).strict();
export const InsuranceCredentialUpdateManyMutationInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialUpdateManyMutationInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialUpdateManyMutationInput>;
export const InsuranceCredentialUpdateManyMutationInputObjectZodSchema = makeSchema();
@@ -1,11 +1,14 @@
import * as z from 'zod';
import type { Prisma } from '../../../generated/prisma';
import { StringFieldUpdateOperationsInputObjectSchema as StringFieldUpdateOperationsInputObjectSchema } from './StringFieldUpdateOperationsInput.schema'
import { StringFieldUpdateOperationsInputObjectSchema as StringFieldUpdateOperationsInputObjectSchema } from './StringFieldUpdateOperationsInput.schema';
import { NullableStringFieldUpdateOperationsInputObjectSchema as NullableStringFieldUpdateOperationsInputObjectSchema } from './NullableStringFieldUpdateOperationsInput.schema'
const makeSchema = () => z.object({
siteKey: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
username: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
password: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional()
password: z.union([z.string(), z.lazy(() => StringFieldUpdateOperationsInputObjectSchema)]).optional(),
otpContact: z.union([z.string(), z.lazy(() => NullableStringFieldUpdateOperationsInputObjectSchema)]).optional().nullable(),
otpContactPassword: z.union([z.string(), z.lazy(() => NullableStringFieldUpdateOperationsInputObjectSchema)]).optional().nullable()
}).strict();
export const InsuranceCredentialUpdateWithoutUserInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialUpdateWithoutUserInput> = makeSchema() as unknown as z.ZodType<Prisma.InsuranceCredentialUpdateWithoutUserInput>;
export const InsuranceCredentialUpdateWithoutUserInputObjectZodSchema = makeSchema();
@@ -2,6 +2,7 @@ import * as z from 'zod';
import type { Prisma } from '../../../generated/prisma';
import { IntFilterObjectSchema as IntFilterObjectSchema } from './IntFilter.schema';
import { StringFilterObjectSchema as StringFilterObjectSchema } from './StringFilter.schema';
import { StringNullableFilterObjectSchema as StringNullableFilterObjectSchema } from './StringNullableFilter.schema';
import { UserScalarRelationFilterObjectSchema as UserScalarRelationFilterObjectSchema } from './UserScalarRelationFilter.schema';
import { UserWhereInputObjectSchema as UserWhereInputObjectSchema } from './UserWhereInput.schema'
@@ -14,6 +15,8 @@ const insurancecredentialwhereinputSchema = z.object({
siteKey: z.union([z.lazy(() => StringFilterObjectSchema), z.string()]).optional(),
username: z.union([z.lazy(() => StringFilterObjectSchema), z.string()]).optional(),
password: z.union([z.lazy(() => StringFilterObjectSchema), z.string()]).optional(),
otpContact: z.union([z.lazy(() => StringNullableFilterObjectSchema), z.string()]).optional().nullable(),
otpContactPassword: z.union([z.lazy(() => StringNullableFilterObjectSchema), z.string()]).optional().nullable(),
user: z.union([z.lazy(() => UserScalarRelationFilterObjectSchema), z.lazy(() => UserWhereInputObjectSchema)]).optional()
}).strict();
export const InsuranceCredentialWhereInputObjectSchema: z.ZodType<Prisma.InsuranceCredentialWhereInput> = insurancecredentialwhereinputSchema as unknown as z.ZodType<Prisma.InsuranceCredentialWhereInput>;
@@ -5,6 +5,8 @@ export const InsuranceCredentialAggregateResultSchema = z.object({ _count: z.ob
siteKey: z.number(),
username: z.number(),
password: z.number(),
otpContact: z.number(),
otpContactPassword: z.number(),
user: z.number()
}).optional(),
_sum: z.object({
@@ -20,12 +22,16 @@ export const InsuranceCredentialAggregateResultSchema = z.object({ _count: z.ob
userId: z.number().int().nullable(),
siteKey: z.string().nullable(),
username: z.string().nullable(),
password: z.string().nullable()
password: z.string().nullable(),
otpContact: z.string().nullable(),
otpContactPassword: z.string().nullable()
}).nullable().optional(),
_max: z.object({
id: z.number().int().nullable(),
userId: z.number().int().nullable(),
siteKey: z.string().nullable(),
username: z.string().nullable(),
password: z.string().nullable()
password: z.string().nullable(),
otpContact: z.string().nullable(),
otpContactPassword: z.string().nullable()
}).nullable().optional()});
@@ -5,5 +5,7 @@ export const InsuranceCredentialCreateResultSchema = z.object({
siteKey: z.string(),
username: z.string(),
password: z.string(),
otpContact: z.string().optional(),
otpContactPassword: z.string().optional(),
user: z.unknown()
});
@@ -5,5 +5,7 @@ export const InsuranceCredentialDeleteResultSchema = z.nullable(z.object({
siteKey: z.string(),
username: z.string(),
password: z.string(),
otpContact: z.string().optional(),
otpContactPassword: z.string().optional(),
user: z.unknown()
}));
@@ -5,5 +5,7 @@ export const InsuranceCredentialFindFirstResultSchema = z.nullable(z.object({
siteKey: z.string(),
username: z.string(),
password: z.string(),
otpContact: z.string().optional(),
otpContactPassword: z.string().optional(),
user: z.unknown()
}));
@@ -6,6 +6,8 @@ export const InsuranceCredentialFindManyResultSchema = z.object({
siteKey: z.string(),
username: z.string(),
password: z.string(),
otpContact: z.string().optional(),
otpContactPassword: z.string().optional(),
user: z.unknown()
})),
pagination: z.object({
@@ -5,5 +5,7 @@ export const InsuranceCredentialFindUniqueResultSchema = z.nullable(z.object({
siteKey: z.string(),
username: z.string(),
password: z.string(),
otpContact: z.string().optional(),
otpContactPassword: z.string().optional(),
user: z.unknown()
}));
@@ -5,12 +5,16 @@ export const InsuranceCredentialGroupByResultSchema = z.array(z.object({
siteKey: z.string(),
username: z.string(),
password: z.string(),
otpContact: z.string(),
otpContactPassword: z.string(),
_count: z.object({
id: z.number(),
userId: z.number(),
siteKey: z.number(),
username: z.number(),
password: z.number(),
otpContact: z.number(),
otpContactPassword: z.number(),
user: z.number()
}).optional(),
_sum: z.object({
@@ -26,13 +30,17 @@ export const InsuranceCredentialGroupByResultSchema = z.array(z.object({
userId: z.number().int().nullable(),
siteKey: z.string().nullable(),
username: z.string().nullable(),
password: z.string().nullable()
password: z.string().nullable(),
otpContact: z.string().nullable(),
otpContactPassword: z.string().nullable()
}).nullable().optional(),
_max: z.object({
id: z.number().int().nullable(),
userId: z.number().int().nullable(),
siteKey: z.string().nullable(),
username: z.string().nullable(),
password: z.string().nullable()
password: z.string().nullable(),
otpContact: z.string().nullable(),
otpContactPassword: z.string().nullable()
}).nullable().optional()
}));
@@ -5,5 +5,7 @@ export const InsuranceCredentialUpdateResultSchema = z.nullable(z.object({
siteKey: z.string(),
username: z.string(),
password: z.string(),
otpContact: z.string().optional(),
otpContactPassword: z.string().optional(),
user: z.unknown()
}));
@@ -5,5 +5,7 @@ export const InsuranceCredentialUpsertResultSchema = z.object({
siteKey: z.string(),
username: z.string(),
password: z.string(),
otpContact: z.string().optional(),
otpContactPassword: z.string().optional(),
user: z.unknown()
});
@@ -6,6 +6,8 @@ export const InsuranceCredentialInputSchema = z.object({
siteKey: z.string(),
username: z.string(),
password: z.string(),
otpContact: z.string().optional().nullable(),
otpContactPassword: z.string().optional().nullable(),
user: z.unknown()
}).strict();
@@ -6,6 +6,8 @@ export const InsuranceCredentialModelSchema = z.object({
siteKey: z.string(),
username: z.string(),
password: z.string(),
otpContact: z.string().nullable(),
otpContactPassword: z.string().nullable(),
user: z.unknown()
}).strict();
@@ -6,6 +6,8 @@ export const InsuranceCredentialResultSchema = z.object({
siteKey: z.string(),
username: z.string(),
password: z.string(),
otpContact: z.string().nullable(),
otpContactPassword: z.string().nullable(),
user: z.unknown()
}).strict();
+4 -4
View File
@@ -1,5 +1,5 @@
import * as z from "zod";
export declare const PatientStatusSchema: z.ZodEnum<["ACTIVE", "INACTIVE", "UNKNOWN", "PLAN_NOT_ACCEPTED"]>;
export declare const PatientStatusSchema: z.ZodEnum<["ACTIVE", "INACTIVE", "UNKNOWN", "PLAN_NOT_ACCEPTED", "ACTIVE_PLAN_NOT_ACCEPTED"]>;
export type PatientStatus = z.infer<typeof PatientStatusSchema>;
export declare const ClaimStatusSchema: z.ZodEnum<["PENDING", "APPROVED", "CANCELLED", "REVIEW", "VOID"]>;
export type ClaimStatus = z.infer<typeof ClaimStatusSchema>;
@@ -51,14 +51,14 @@ export declare const PatientUncheckedCreateInputObjectSchema: z.ZodObject<{
allergies: z.ZodNullable<z.ZodOptional<z.ZodString>>;
medicalConditions: z.ZodNullable<z.ZodOptional<z.ZodString>>;
preferredLanguage: z.ZodNullable<z.ZodOptional<z.ZodString>>;
status: z.ZodOptional<z.ZodEnum<["ACTIVE", "INACTIVE", "UNKNOWN", "PLAN_NOT_ACCEPTED"]>>;
status: z.ZodOptional<z.ZodEnum<["ACTIVE", "INACTIVE", "UNKNOWN", "PLAN_NOT_ACCEPTED", "ACTIVE_PLAN_NOT_ACCEPTED"]>>;
userId: z.ZodOptional<z.ZodNumber>;
createdAt: z.ZodOptional<z.ZodDate>;
}, "strip", z.ZodTypeAny, {
dateOfBirth: string;
firstName: string;
lastName: string;
status?: "ACTIVE" | "INACTIVE" | "UNKNOWN" | "PLAN_NOT_ACCEPTED" | undefined;
status?: "ACTIVE" | "INACTIVE" | "UNKNOWN" | "PLAN_NOT_ACCEPTED" | "ACTIVE_PLAN_NOT_ACCEPTED" | undefined;
id?: number | undefined;
createdAt?: Date | undefined;
userId?: number | undefined;
@@ -80,7 +80,7 @@ export declare const PatientUncheckedCreateInputObjectSchema: z.ZodObject<{
dateOfBirth: string;
firstName: string;
lastName: string;
status?: "ACTIVE" | "INACTIVE" | "UNKNOWN" | "PLAN_NOT_ACCEPTED" | undefined;
status?: "ACTIVE" | "INACTIVE" | "UNKNOWN" | "PLAN_NOT_ACCEPTED" | "ACTIVE_PLAN_NOT_ACCEPTED" | undefined;
id?: number | undefined;
createdAt?: Date | undefined;
userId?: number | undefined;
+1 -1
View File
@@ -2,7 +2,7 @@ import * as z from "zod";
// ─── Enums ────────────────────────────────────────────────────────────────────
export const PatientStatusSchema = z.enum(["ACTIVE", "INACTIVE", "UNKNOWN", "PLAN_NOT_ACCEPTED"]);
export const PatientStatusSchema = z.enum(["ACTIVE", "INACTIVE", "UNKNOWN", "PLAN_NOT_ACCEPTED", "ACTIVE_PLAN_NOT_ACCEPTED"]);
export type PatientStatus = z.infer<typeof PatientStatusSchema>;
export const ClaimStatusSchema = z.enum([