Files
DentalManagement09/apps/SeleniumService/selenium_CCA_preAuthCheckWorker.py
GiteadandClaude Opus 5.5 0db69a34b6 feat: CCA Check Preauth approval PDF, merge patients, attachment picker across records
- CCA Check Preauth: searches Authorization Search by auth number, clicks View Auth on the
  result row and saves the PortalAuthReport PDF to the patient's Approval folder
- Merge Patients button above the eligibility page search (admin only): moves appointments,
  claims, payments, PDFs, documents and Cloud Storage folders onto the kept record, fills its
  blank fields, deletes the other records, all in one transaction
- Appointment attachment picker lists files from all of the patient's folders and from the
  patient's other records (same first + last name), labeled by record

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 09:58:57 -05:00

276 lines
13 KiB
Python

from selenium.common.exceptions import TimeoutException
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
import base64
import glob
import os
import time
from selenium_CCA_eligibilityCheckWorker import AutomationCCAEligibilityCheck
AUTH_SEARCH_URL = "https://pwp.sciondental.com/PWP/Dental/AuthorizationSearch"
class AutomationCCAPreAuthCheck(AutomationCCAEligibilityCheck):
"""
CCA (ScionDental) Check PreAuth.
login: same as the eligibility check (persistent browser session and cookies).
step1: open Authorization Search, enter the authorization number, click Search.
step2: click View Auth on the result row and save the popup page as a PDF
(filed under the patient's Approval folder by the backend).
"""
def __init__(self, data):
super().__init__(data)
self.preAuthNumber = str(self.data.get("preAuthNumber") or "").strip()
self.claimNumber = str(self.data.get("claimNumber") or "").strip()
def _auth_number(self):
# CCA preauths keep the authorization number (e.g. A0261012136225) in claimNumber
return self.preAuthNumber or self.claimNumber
def step1(self):
number = self._auth_number()
if not number:
return "ERROR: This record has no authorization number to search for."
wait = WebDriverWait(self.driver, 30)
try:
print(f"[CCA PreAuthCheck step1] Opening {AUTH_SEARCH_URL}")
self.driver.get(AUTH_SEARCH_URL)
number_input = wait.until(EC.element_to_be_clickable((By.ID, "authorizationNumberTextBox")))
number_input.click()
number_input.send_keys(Keys.CONTROL, "a")
number_input.send_keys(Keys.DELETE)
number_input.send_keys(number)
print(f"[CCA PreAuthCheck step1] Entered authorization number: {number}")
# Search stays disabled until the page fills in Insurer, Location and Provider
try:
search_btn = wait.until(EC.element_to_be_clickable((By.ID, "ClaimSearchButton")))
except TimeoutException:
return "ERROR: Search button stayed disabled (Insurer/Location/Provider not set on Authorization Search)."
search_btn.click()
print("[CCA PreAuthCheck step1] Clicked Search")
return "SUCCESS"
except TimeoutException:
return "ERROR: Authorization Search form not found."
except Exception as e:
return f"ERROR: Authorization search failed: {e}"
def _row_status(self, row):
# "Auth Status" column of the result row (e.g. "Determined"). The grid may draw its
# header in a separate table, so match the column by position rather than by table.
try:
th = self.driver.find_element(By.XPATH, "//th[contains(normalize-space(.), 'Auth Status')]")
index = len(th.find_elements(By.XPATH, "./preceding-sibling::th"))
cells = row.find_elements(By.XPATH, "./td")
if index < len(cells) and cells[index].text.strip():
return cells[index].text.strip()
except Exception:
pass
for word in ("Determined", "Approved", "Denied", "Pending", "Pended", "Cancelled", "In Review"):
if word.lower() in row.text.lower():
return word
return ""
def _save_popup_report(self, popup, original_window, pdf_path):
"""Saves the auth report from the popup window: its PDF bytes, else a print of the page."""
try:
self.driver.switch_to.window(popup)
url = self.driver.current_url
print(f"[CCA PreAuthCheck step2] Popup URL: {url}")
if "ErrorHandler" in url or "Error" in self.driver.title:
print("[CCA PreAuthCheck step2] Popup is the portal's error page; not saving it")
return False
if url.startswith("http"):
# Re-request the report in the popup's own session and keep the raw PDF
self.driver.set_script_timeout(60)
data = self.driver.execute_async_script("""
var done = arguments[arguments.length - 1];
fetch(location.href, {credentials: 'include'})
.then(function (r) { return r.arrayBuffer(); })
.then(function (buf) {
var bytes = new Uint8Array(buf), s = '';
for (var i = 0; i < bytes.length; i += 0x8000) {
s += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
}
done(btoa(s));
})
.catch(function (e) { done('ERR:' + e); });
""")
raw = base64.b64decode(data) if data and not data.startswith("ERR:") else b""
if raw.startswith(b"%PDF"):
with open(pdf_path, "wb") as f:
f.write(raw)
print(f"[CCA PreAuthCheck step2] Report PDF fetched: {pdf_path} ({len(raw)} bytes)")
return True
print(f"[CCA PreAuthCheck step2] Fetch did not return a PDF: {(data or '')[:80]}")
pdf = self.driver.execute_cdp_cmd("Page.printToPDF", {
"printBackground": True,
"paperWidth": 8.5,
"paperHeight": 11,
"marginTop": 0.4,
"marginBottom": 0.4,
"marginLeft": 0.4,
"marginRight": 0.4,
})
with open(pdf_path, "wb") as f:
f.write(base64.b64decode(pdf.get("data", "")))
print(f"[CCA PreAuthCheck step2] Popup printed to PDF: {pdf_path}")
return True
return False
except Exception as e:
print(f"[CCA PreAuthCheck step2] Saving popup report failed: {e}")
return False
finally:
try:
self.driver.switch_to.window(original_window)
except Exception:
pass
def _visible_dialog(self):
for el in self.driver.find_elements(By.XPATH,
"//*[@role='dialog' or contains(@class,'modal-dialog') or contains(@class,'k-window')]"):
try:
if el.is_displayed() and el.text.strip():
return el
except Exception:
continue
return None
def step2(self):
number = self._auth_number()
try:
# 1) Wait for the visible result row whose Auth Number cell is this number. The page
# also holds hidden grids, so a row merely containing the number isn't enough.
row_xpath = f"//tbody/tr[td[normalize-space(.)='{number}']]"
def visible_result_row(d):
for r in d.find_elements(By.XPATH, row_xpath):
try:
if r.is_displayed():
return r
except Exception:
continue
return False
try:
row = WebDriverWait(self.driver, 30).until(visible_result_row)
print(f"[CCA PreAuthCheck step2] Result row: {row.text!r}")
except TimeoutException:
body = self.driver.find_element(By.TAG_NAME, "body").text.lower()
if "no records" in body or "no results" in body or "no data" in body:
return {"status": "error", "message": f"CCA found no authorization #{number}."}
return {"status": "error", "message": f"Search result for authorization #{number} did not load."}
status = self._row_status(row)
print(f"[CCA PreAuthCheck step2] Auth Status: {status!r}")
# 2) Click View Auth (page icon in the last column); it opens the auth in a new window
original_window = self.driver.current_window_handle
original_handles = set(self.driver.window_handles)
existing_files = set(glob.glob(os.path.join(self.download_dir, "*")))
# The View Auth page icon in the last column of this same row
icons = [i for i in row.find_elements(By.XPATH, ".//i[@title='View Auth']") if i.is_displayed()]
print(f"[CCA PreAuthCheck step2] View Auth icons in the row: {len(icons)}")
if not icons:
print(f"[CCA PreAuthCheck step2] Row HTML: {row.get_attribute('outerHTML')[:1500]}")
return {"status": "error", "message": f"View Auth icon not found for #{number}."}
view_icon = icons[0]
self.driver.execute_script("arguments[0].scrollIntoView({block:'center'});", view_icon)
try:
view_icon.click()
except Exception as e:
print(f"[CCA PreAuthCheck step2] Normal click failed ({e}); using JS click")
self.driver.execute_script("arguments[0].click();", view_icon)
print("[CCA PreAuthCheck step2] Clicked View Auth")
pdf_path = os.path.join(
self.download_dir, f"cca_preauth_approval_{number}_{int(time.time())}.pdf"
)
# View Auth opens PortalAuthReport.aspx, which serves the auth as a PDF. This browser
# downloads PDFs (always_open_pdf_externally), so wait for the download first; the
# popup window appears before the download finishes.
saved = False
popup = None
popup_seen = 0.0
deadline = time.time() + 45
while time.time() < deadline:
time.sleep(1)
new_files = [
f for f in set(glob.glob(os.path.join(self.download_dir, "*"))) - existing_files
if not f.endswith(".crdownload") and not f.endswith(".tmp")
]
if new_files:
time.sleep(1) # let Chrome finish writing the file
os.replace(new_files[0], pdf_path)
print(f"[CCA PreAuthCheck step2] Auth downloaded: {pdf_path}")
saved = True
break
if popup is None:
new_handles = set(self.driver.window_handles) - original_handles
if new_handles:
popup = new_handles.pop()
popup_seen = time.time()
print("[CCA PreAuthCheck step2] Popup window opened; waiting for the PDF download")
elif time.time() - popup_seen > 15:
# No download: read the PDF straight from the popup
saved = self._save_popup_report(popup, original_window, pdf_path)
popup = None
break
# Or the auth opens as a dialog on the same page
if popup is None and self._visible_dialog() is not None:
time.sleep(2) # let the dialog finish rendering
pdf_b64 = self._capture_popup_pdf()
if pdf_b64:
with open(pdf_path, "wb") as f:
f.write(base64.b64decode(pdf_b64))
print(f"[CCA PreAuthCheck step2] Dialog PDF saved: {pdf_path}")
saved = True
break
# Close the report popup if it's still open
for handle in set(self.driver.window_handles) - original_handles:
try:
self.driver.switch_to.window(handle)
self.driver.close()
except Exception:
pass
self.driver.switch_to.window(original_window)
if not saved:
print(f"[CCA PreAuthCheck step2] Nothing opened. URL={self.driver.current_url} "
f"windows={len(self.driver.window_handles)}")
return {"status": "error", "message": f"View Auth for #{number} did not open a page."}
# Leave the browser idle so the session stays logged in for the next run
try:
self.driver.get("about:blank")
self.driver.minimize_window()
except Exception:
pass
return {
"status": "success",
"message": f"CCA authorization #{number}" + (f": {status}." if status else "."),
"preAuthNumber": number,
"preAuthStatus": status,
"approval_pdf_path": pdf_path,
}
except Exception as e:
print(f"[CCA PreAuthCheck step2] Exception: {e}")
try:
self.driver.switch_to.window(self.driver.window_handles[0])
except Exception:
pass
return {"status": "error", "message": f"CCA pre-auth check failed: {e}"}