feat: secondary insurance; SCO primary + MassHealth secondary rule; United SCO service history
- Patient: new secondaryInsuranceProvider / secondaryInsuranceId (form section, Patient Details, merge fill) - MassHealth check on an SCO patient (Tufts SCO / United SCO primary), matched by MassHealth ID on file as secondary or by the single SCO patient with the same DOB (name must share a word when the portal returns one): MassHealth saved as secondary, primary plan/ID/status unchanged, MassHealth history not imported, PDF still saved to Eligibility documents. Prevents the name+DOB fallback from overwriting the SCO ID - United SCO check: a MassHealth patient moved to United SCO keeps the old MassHealth ID as secondary; reads Dental Hub Service History and saves it - Service history saves drop duplicate identical lines - Chatbot: bare 100… member ID + DOB with no patient/insurance defaults to MassHealth Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,158 @@
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
|
||||
from selenium.webdriver.common.by import By
|
||||
|
||||
from dentaquest_service_history import parse_page_text, parse_row_cells
|
||||
|
||||
# Service History on the Dental Hub (United SCO) Selected Patient page. It sits next to
|
||||
# the "Eligibility" and "Benefit Summary" buttons. The column order isn't known for sure,
|
||||
# so columns are mapped by header name when the table has headers; otherwise rows are
|
||||
# read like DentaQuest's (code cell, then description / tooth / place).
|
||||
_CLICK_JS = """
|
||||
const btn = document.getElementById('service-history-link') ||
|
||||
Array.from(document.querySelectorAll('button, a, [role="tab"]'))
|
||||
.find(el => /^\\s*Service History\\s*$/i.test(el.textContent || ''));
|
||||
if (!btn) return false;
|
||||
btn.scrollIntoView({block: 'center'});
|
||||
btn.click();
|
||||
return true;
|
||||
"""
|
||||
|
||||
_TABLES_JS = """
|
||||
const cellText = (el) => (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim();
|
||||
const out = [];
|
||||
for (const table of document.querySelectorAll('table, [role="table"], [role="grid"]')) {
|
||||
const headers = Array.from(table.querySelectorAll('th, [role="columnheader"]')).map(cellText);
|
||||
const rows = [];
|
||||
for (const row of table.querySelectorAll('tr, [role="row"]')) {
|
||||
const cells = Array.from(row.querySelectorAll('td, [role="cell"], [role="gridcell"]')).map(cellText);
|
||||
if (cells.some(t => /^D\\d{4}$/.test(t))) rows.push(cells);
|
||||
}
|
||||
if (rows.length) out.push({headers, rows});
|
||||
}
|
||||
return out;
|
||||
"""
|
||||
|
||||
_DATE_RE = re.compile(r"^\d{1,2}/\d{1,2}/\d{4}$")
|
||||
|
||||
_HEADER_KEYS = [
|
||||
# (field, header must contain one of these, checked in this order)
|
||||
("serviceDate", ("date",)),
|
||||
("description", ("description", "desc")),
|
||||
("procedureCode", ("procedure", "code", "cdt")),
|
||||
("toothQuadArchSurface", ("tooth", "surface", "quad", "arch", "area")),
|
||||
("placeOfService", ("place", "location", "pos")),
|
||||
]
|
||||
|
||||
|
||||
def _map_headers(headers):
|
||||
"""Column index per field from header names, or None when the headers don't fit."""
|
||||
cols = {}
|
||||
for i, h in enumerate(h.lower() for h in headers):
|
||||
for field, keys in _HEADER_KEYS:
|
||||
if field not in cols and any(k in h for k in keys):
|
||||
cols[field] = i
|
||||
break
|
||||
return cols if "procedureCode" in cols else None
|
||||
|
||||
|
||||
def parse_tables(tables):
|
||||
result = []
|
||||
for t in tables:
|
||||
cols = _map_headers(t.get("headers") or [])
|
||||
if not cols:
|
||||
result.extend(parse_row_cells(t["rows"]))
|
||||
continue
|
||||
for cells in t["rows"]:
|
||||
get = lambda f: cells[cols[f]] if f in cols and cols[f] < len(cells) else ""
|
||||
code = get("procedureCode")
|
||||
if not re.match(r"^D\d{4}$", code):
|
||||
continue
|
||||
date = get("serviceDate")
|
||||
if not _DATE_RE.match(date):
|
||||
date = next((c for c in cells if _DATE_RE.match(c)), date)
|
||||
result.append({
|
||||
"procedureCode": code,
|
||||
"description": get("description"),
|
||||
"toothQuadArchSurface": get("toothQuadArchSurface"),
|
||||
"placeOfService": get("placeOfService"),
|
||||
"serviceDate": date,
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def _dedupe(rows):
|
||||
seen, out = set(), []
|
||||
for r in rows:
|
||||
key = tuple(r.get(k, "") for k in
|
||||
("procedureCode", "description", "toothQuadArchSurface", "placeOfService", "serviceDate"))
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
def _dump_page(driver, debug_dir):
|
||||
"""Save the page so the reader can be fixed when it finds nothing."""
|
||||
try:
|
||||
os.makedirs(debug_dir, exist_ok=True)
|
||||
stamp = int(time.time())
|
||||
with open(os.path.join(debug_dir, f"dentalhub_service_history_{stamp}.html"), "w") as f:
|
||||
f.write(driver.page_source or "")
|
||||
print(f"[dentalhub service history] nothing found; page saved to {debug_dir}")
|
||||
except Exception as e:
|
||||
print(f"[dentalhub service history] saving debug page failed: {e}")
|
||||
|
||||
|
||||
def read_service_history(driver, debug_dir, timeout=15):
|
||||
"""Click "Service History" on the Selected Patient page and read its rows.
|
||||
|
||||
Returns [] when nothing was found — that can't tell "no history" from "the page was
|
||||
slow", so callers must not treat it as "no history". Never raises.
|
||||
"""
|
||||
original = driver.current_window_handle
|
||||
before = set(driver.window_handles)
|
||||
try:
|
||||
if not driver.execute_script(_CLICK_JS):
|
||||
print("[dentalhub service history] 'Service History' button not found")
|
||||
_dump_page(driver, debug_dir)
|
||||
return []
|
||||
except Exception as e:
|
||||
print(f"[dentalhub service history] click failed: {e}")
|
||||
return []
|
||||
|
||||
time.sleep(2)
|
||||
new_tabs = list(set(driver.window_handles) - before)
|
||||
if new_tabs:
|
||||
driver.switch_to.window(new_tabs[0])
|
||||
|
||||
history = []
|
||||
deadline = time.time() + timeout
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
history = parse_tables(driver.execute_script(_TABLES_JS) or [])
|
||||
if not history:
|
||||
text = driver.find_element(By.TAG_NAME, "body").get_attribute("innerText") or ""
|
||||
history = parse_page_text(text)
|
||||
if history:
|
||||
break
|
||||
except Exception as e:
|
||||
print(f"[dentalhub service history] reading page failed: {e}")
|
||||
if time.time() >= deadline:
|
||||
_dump_page(driver, debug_dir)
|
||||
break
|
||||
time.sleep(1)
|
||||
finally:
|
||||
if new_tabs:
|
||||
try:
|
||||
driver.close()
|
||||
except Exception:
|
||||
pass
|
||||
driver.switch_to.window(original)
|
||||
|
||||
history = _dedupe(history)
|
||||
print(f"[dentalhub service history] {len(history)} row(s)")
|
||||
return history
|
||||
@@ -12,6 +12,7 @@ import re
|
||||
import base64
|
||||
|
||||
from unitedsco_browser_manager import get_browser_manager
|
||||
from dentalhub_service_history import read_service_history
|
||||
|
||||
class AutomationUnitedSCOEligibilityCheck:
|
||||
def __init__(self, data):
|
||||
@@ -1135,6 +1136,15 @@ class AutomationUnitedSCOEligibilityCheck:
|
||||
|
||||
print(f"[UnitedSCO step2] PDF saved: {pdf_path}")
|
||||
|
||||
# 4) Service History (button next to "Eligibility") — never fails the check
|
||||
service_history = []
|
||||
try:
|
||||
service_history = read_service_history(
|
||||
self.driver, os.path.join(self.download_dir, "debug_service_history")
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"[UnitedSCO step2] Service history read failed: {e}")
|
||||
|
||||
# Hide browser window after completion
|
||||
self._hide_browser()
|
||||
|
||||
@@ -1146,7 +1156,8 @@ class AutomationUnitedSCOEligibilityCheck:
|
||||
"ss_path": pdf_path,
|
||||
"pdf_path": pdf_path,
|
||||
"patientName": patientName,
|
||||
"memberId": foundMemberId
|
||||
"memberId": foundMemberId,
|
||||
"service_history": service_history,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
||||
Reference in New Issue
Block a user