Files
DentalManagement09/apps/SeleniumService/helpers_cca_claim.py
T
GiteadandClaude Opus 5.5 143319909f fix: AI claims/preauths keep all codes past 10; reuse CCA/DentalHub Chrome
- Claim form: AI claim/preauth prefill adds rows beyond the initial 10
  instead of dropping codes 11+
- CDT lookup: "D6010 #5, 9, 11, 12" expands to one line per tooth, and
  the chat graph rebuilds such lists from the message if the LLM drops items
- Eligibility: match an existing patient by name+DOB when the insurance ID
  changed (e.g. MassHealth → CCA) instead of creating a duplicate patient
- CCA PreAuth: services grid scrolls to reach rows 11+
- CCA and Tufts SCO PreAuth: tentative service date = today + 3 days
- CCA (eligibility/claim/preauth) and DentalHub (claim/preauth): keep Chrome
  open, blank and minimized, after a job so the next job reuses it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 01:27:28 -04:00

228 lines
8.1 KiB
Python

import os
import time
import asyncio
from typing import Dict, Any
from selenium.common.exceptions import WebDriverException
from selenium_CCA_claimSubmitWorker import AutomationCCAClaimSubmit
from cca_browser_manager import get_browser_manager
sessions: Dict[str, Dict[str, Any]] = {}
def make_session_entry() -> str:
import uuid
sid = str(uuid.uuid4())
sessions[sid] = {
"status": "created",
"created_at": time.time(),
"last_activity": time.time(),
"bot": None,
"driver": None,
"result": None,
"message": None,
}
return sid
async def cleanup_session(sid: str, message: str | None = None):
s = sessions.get(sid)
if not s:
return
try:
if s.get("status") not in ("completed", "error"):
s["status"] = "error"
if message:
s["message"] = message
finally:
sessions.pop(sid, None)
async def _remove_session_later(sid: str, delay: int = 30):
await asyncio.sleep(delay)
await cleanup_session(sid)
def _close_browser(bot):
try:
bm = get_browser_manager()
try:
bm.save_cookies()
except Exception:
pass
# Keep Chrome open (blank + minimized) so the next CCA job reuses it — faster
# than starting a new browser. get_driver() recreates it if it was closed.
if bot and bot.driver:
try:
bot.driver.get("about:blank")
except Exception:
pass
try:
bot.driver.minimize_window()
print("[CCA Claim] Browser kept open (minimized)")
except Exception:
try:
bot.driver.set_window_position(-10000, -10000)
print("[CCA Claim] Browser kept open (moved off-screen)")
except Exception:
pass
except Exception as e:
print(f"[CCA Claim] Could not close browser: {e}")
async def start_cca_claim_run(sid: str, data: dict, url: str):
"""
Run the CCA claim submission workflow:
1. Login to ScionDental portal
2. Navigate Claims > Submit Claims to open claim entry page
"""
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 = AutomationCCAClaimSubmit(data)
bot.config_driver()
s["bot"] = bot
s["driver"] = bot.driver
s["last_activity"] = time.time()
try:
bot.driver.maximize_window()
except Exception:
pass
# --- Login ---
try:
login_result = bot.login(url)
except WebDriverException as wde:
s["status"] = "error"
s["message"] = f"Selenium driver error during login: {wde}"
s["result"] = {"status": "error", "message": s["message"]}
_close_browser(bot)
asyncio.create_task(_remove_session_later(sid, 30))
return {"status": "error", "message": s["message"]}
except Exception as e:
s["status"] = "error"
s["message"] = f"Unexpected error during login: {e}"
s["result"] = {"status": "error", "message": s["message"]}
_close_browser(bot)
asyncio.create_task(_remove_session_later(sid, 30))
return {"status": "error", "message": s["message"]}
if isinstance(login_result, str) and login_result == "ALREADY_LOGGED_IN":
print("[CCA Claim] Session persisted - skipping login")
get_browser_manager().save_cookies()
elif isinstance(login_result, str) and login_result.startswith("ERROR"):
s["status"] = "error"
s["message"] = login_result
s["result"] = {"status": "error", "message": login_result}
_close_browser(bot)
asyncio.create_task(_remove_session_later(sid, 30))
return {"status": "error", "message": login_result}
elif isinstance(login_result, str) and login_result == "SUCCESS":
print("[CCA Claim] Login succeeded")
get_browser_manager().save_cookies()
# --- Navigate to Submit Claims ---
step1_result = bot.step1_navigate_to_submit_claims()
print(f"[CCA Claim] step1 result: {step1_result}")
if isinstance(step1_result, str) and step1_result.startswith("ERROR"):
s["status"] = "error"
s["message"] = step1_result
s["result"] = {"status": "error", "message": step1_result}
_close_browser(bot)
asyncio.create_task(_remove_session_later(sid, 30))
return {"status": "error", "message": step1_result}
# --- Fill patient eligibility form & verify ---
step2_result = bot.step2_fill_patient_eligibility()
print(f"[CCA Claim] step2 result: {step2_result}")
if isinstance(step2_result, str) and step2_result.startswith("ERROR"):
# Keep browser open — log page state for debugging
try:
url = bot.driver.current_url
body = bot.driver.find_element(__import__('selenium').webdriver.common.by.By.TAG_NAME, "body").text[:600]
print(f"[CCA Claim] step2 error — URL: {url}")
print(f"[CCA Claim] step2 error — page text: {body}")
except Exception:
pass
s["status"] = "error"
s["message"] = step2_result
s["result"] = {"status": "error", "message": step2_result}
_close_browser(bot)
asyncio.create_task(_remove_session_later(sid, 30))
return {"status": "error", "message": step2_result}
# --- Fill Services grid, attach docs, submit ---
step3_result = bot.step3_fill_services_and_submit()
print(f"[CCA Claim] step3 result: {step3_result}")
if isinstance(step3_result, str) and step3_result.startswith("ERROR"):
try:
url = bot.driver.current_url
body = bot.driver.find_element(__import__('selenium').webdriver.common.by.By.TAG_NAME, "body").text[:600]
print(f"[CCA Claim] step3 error — URL: {url}")
print(f"[CCA Claim] step3 error — page text: {body}")
except Exception:
pass
s["status"] = "error"
s["message"] = step3_result
s["result"] = {"status": "error", "message": step3_result}
_close_browser(bot)
asyncio.create_task(_remove_session_later(sid, 30))
return {"status": "error", "message": step3_result}
# --- Capture confirmation PDF + claim number ---
step4_result = bot.step4_capture_confirmation()
print(f"[CCA Claim] step4 claimNumber={step4_result.get('claimNumber')}, "
f"pdfLen={len(step4_result.get('pdfBase64',''))}")
_close_browser(bot)
result = {
"status": "success",
"message": "CCA claim submitted successfully",
"claimNumber": step4_result.get("claimNumber"),
"pdfBase64": step4_result.get("pdfBase64", ""),
"pdfFilename": step4_result.get("pdfFilename", ""),
}
s["status"] = "completed"
s["result"] = result
s["message"] = "completed"
asyncio.create_task(_remove_session_later(sid, 60))
return result
except Exception as e:
if s:
s["status"] = "error"
s["message"] = f"worker exception: {e}"
s["result"] = {"status": "error", "message": s["message"]}
if bot:
_close_browser(bot)
asyncio.create_task(_remove_session_later(sid, 30))
return {"status": "error", "message": f"worker exception: {e}"}
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") in ("completed", "error") else None,
}