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
+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()