feat: MassHealth service history extraction, shown in Patient Details

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-05 08:38:13 -05:00
co-authored by Claude Opus 5.5
parent 1ee3b0cfc9
commit 33bea3822c
172 changed files with 4044 additions and 127 deletions
@@ -0,0 +1,75 @@
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
@@ -11,6 +11,7 @@ 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:
@@ -351,6 +352,10 @@ class AutomationCMSPEligibilityHistoryRemainingCheck:
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})