Files
DentalManagement09/apps/SeleniumService/helpers_bcbs_ma_eligibility.py
T
GiteadandClaude Opus 5.5 13be6e97d5 feat: BCBS MA persistent session, Expand All fix, address/gender extraction
- Persistent Chrome profile (bcbs_ma_browser_manager) reused across patients;
  login probes /myportal/ to skip login + OTP while the session is active
- Expand All: JS-click the expandCollapseViews span, verify sections opened,
  and unclip fixed-height result tables so the PDF includes every row
- Extract patient address and gender from the results page and save to patient
- Uppercase member IDs (XXA...), matching older lowercase records
- Add /clear-bcbs-ma-session endpoint

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:27:46 -04:00

201 lines
8.2 KiB
Python

import os
import time
import asyncio
import uuid
from typing import Dict, Any
from selenium.common.exceptions import WebDriverException
from selenium_BCBS_MA_eligibilityCheckWorker import AutomationBCBSMAEligibilityCheck
from bcbs_ma_browser_manager import get_browser_manager
# 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:
sid = str(uuid.uuid4())
sessions[sid] = {
"status": "created", # created → running → waiting_for_otp → completed / error
"created_at": time.time(),
"last_activity": time.time(),
"bot": None,
"driver": None,
"otp_event": asyncio.Event(),
"otp_value": None,
"result": None,
"message": None,
"type": None,
}
return sid
async def _remove_session_later(sid: str, delay: int = 30):
await asyncio.sleep(delay)
sessions.pop(sid, None)
print(f"[helpers_bcbs_ma] cleaned session {sid}")
async def start_bcbs_ma_run(sid: str, data: dict, url: str):
"""
Full BCBS MA eligibility workflow for one session.
Uses the persistent BCBS MA browser — if the portal login is still
active, login() returns SUCCESS and the OTP step is skipped.
OTP handling (only when the saved login has expired):
a) Accept OTP submitted from the app via /submit-otp (sets otp_value)
b) Poll the browser directly to detect user entry in the open window
"""
s = sessions.get(sid)
if not s:
return {"status": "error", "message": "session not found"}
s["status"] = "running"
s["last_activity"] = time.time()
bot = None
try:
bot = AutomationBCBSMAEligibilityCheck({"data": data})
bot.config_driver()
s["bot"] = bot
s["driver"] = bot.driver
# ── Login ──────────────────────────────────────────────────────────────
try:
login_result = bot.login(url)
except WebDriverException as e:
s["status"] = "error"
s["message"] = f"WebDriver error during login: {e}"
return {"status": "error", "message": s["message"]}
except Exception as e:
s["status"] = "error"
s["message"] = f"Login failed: {e}"
return {"status": "error", "message": s["message"]}
if isinstance(login_result, str) and login_result.startswith("ERROR"):
s["status"] = "error"
s["message"] = login_result
return {"status": "error", "message": login_result}
# ── OTP required (always for BCBS MA) ─────────────────────────────────
if isinstance(login_result, str) and login_result == "OTP_REQUIRED":
s["status"] = "waiting_for_otp"
s["message"] = "OTP required — enter the 6-digit code from the BCBS MA email"
s["last_activity"] = time.time()
driver = bot.driver
login_success = False
print(f"[BCBS MA] Waiting for OTP (up to {SESSION_OTP_TIMEOUT}s)...")
for poll in range(SESSION_OTP_TIMEOUT):
await asyncio.sleep(1)
s["last_activity"] = time.time()
try:
# a) App submitted OTP
otp_value = s.get("otp_value")
if otp_value:
print(f"[BCBS MA OTP poll {poll+1}] Submitting OTP from app...")
otp_result = bot.submit_otp_step(otp_value)
s["otp_value"] = None
if isinstance(otp_result, str) and otp_result == "SUCCESS":
login_success = True
break
elif isinstance(otp_result, str) and otp_result.startswith("ERROR"):
print(f"[BCBS MA OTP] submit_otp_step returned: {otp_result}")
# Don't abort yet — let the poll loop check the browser state
# b) Detect success by browser URL
current_url = driver.current_url.lower()
print(f"[BCBS MA OTP poll {poll+1}/{SESSION_OTP_TIMEOUT}] URL: {current_url[:70]}")
if "authsvc" not in current_url and "/mga/sps/" not in current_url:
# Left the OTP page — login completed (user entered OTP in browser)
print("[BCBS MA OTP] Browser left OTP page — login successful")
login_success = True
break
except Exception as poll_err:
print(f"[BCBS MA OTP poll {poll+1}] Error: {poll_err}")
if not login_success:
s["status"] = "error"
s["message"] = "OTP timeout — login not completed in time"
return {"status": "error", "message": s["message"]}
s["status"] = "running"
s["message"] = "Login successful after OTP"
print("[BCBS MA] OTP accepted, proceeding to eligibility search...")
await asyncio.sleep(2)
# ── Already logged in (no OTP path) ──────────────────────────────────
elif isinstance(login_result, str) and login_result == "SUCCESS":
print("[BCBS MA] Logged in without OTP")
s["status"] = "running"
# Remember which account this browser profile is logged in as
if bot.username:
get_browser_manager().save_credentials_hash(bot.username)
# ── Step 1: search member ──────────────────────────────────────────────
step1_result = bot.step1()
if isinstance(step1_result, str) and step1_result.startswith("ERROR"):
s["status"] = "error"
s["message"] = step1_result
return {"status": "error", "message": step1_result}
# ── Step 2: extract + 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"
s["message"] = step2_result.get("message", "unknown error") if isinstance(step2_result, dict) else str(step2_result)
return {"status": "error", "message": s["message"]}
except Exception as e:
s["status"] = "error"
s["message"] = f"worker exception: {e}"
print(f"[helpers_bcbs_ma] Unexpected error: {e}")
return {"status": "error", "message": s["message"]}
finally:
# Never quit Chrome here — the persistent browser keeps the BCBS MA
# login for the next patient and stays open on the results page
s["driver"] = None
def submit_otp(sid: str, otp: str) -> Dict[str, Any]:
"""Called by /submit-otp to hand OTP to the polling loop."""
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,
}