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 os import re import time from selenium_UnitedSCO_eligibilityCheckWorker import AutomationUnitedSCOEligibilityCheck AUTH_SEARCH_URL = "https://app.dentalhub.com/app/claims-auths/auths/search" PAYER_NAME = "UnitedHealthcare Massachusetts" class AutomationUnitedSCOPreAuthCheck(AutomationUnitedSCOEligibilityCheck): """ United SCO (DentalHub) Check PreAuth. login: same as the eligibility check (persistent browser session, OTP if asked). step1: open Claims & Auths > Auths search, choose Payer "UnitedHealthcare Massachusetts", pick the "Authorization Number" option, enter the preauth number, click Search. step2: read the result row's status, Options > View Summary, and save the Authorization Summary page as a PDF (filed under the patient's Approval folder). """ def __init__(self, data): super().__init__(data) self.preAuthNumber = str(self.data.get("preAuthNumber") or "").strip() def _select_payer(self, wait): payer_select = wait.until(EC.presence_of_element_located((By.XPATH, "//label[contains(normalize-space(.),'Payer')]/following-sibling::ng-select" " | //label[contains(normalize-space(.),'Payer')]/..//ng-select" " | //ng-select[.//input[contains(@placeholder,'Payer')] or .//*[contains(normalize-space(.),'Search by Payer')]]" ))) self.driver.execute_script("arguments[0].scrollIntoView({block:'center'});", payer_select) time.sleep(0.5) payer_select.click() time.sleep(1) try: search_input = payer_select.find_element(By.XPATH, ".//input") search_input.send_keys(PAYER_NAME) time.sleep(2) except Exception as e: print(f"[UnitedSCO PreAuthCheck step1] Could not type payer name ({e}), using first option") # Prefer the UnitedHealthcare Massachusetts option, otherwise the first one listed try: option = WebDriverWait(self.driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//ng-dropdown-panel//div[contains(@class,'ng-option')][contains(normalize-space(.),'Massachusetts')]" ))) except TimeoutException: option = WebDriverWait(self.driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//ng-dropdown-panel//div[contains(@class,'ng-option')]" ))) option_text = option.text.strip() option.click() print(f"[UnitedSCO PreAuthCheck step1] Selected Payer: {option_text}") time.sleep(1) def _choose_authorization_number_option(self, wait): # The radio sits in front of the "Authorization Number" label radio_xpath = ( "//label[normalize-space(.)='Authorization Number']//input[@type='radio']" " | //label[normalize-space(.)='Authorization Number']/preceding-sibling::input[@type='radio'][1]" " | //input[@type='radio'][following-sibling::*[1][normalize-space(.)='Authorization Number']]" " | //input[@type='radio'][@id=//label[normalize-space(.)='Authorization Number']/@for]" ) try: radio = wait.until(EC.presence_of_element_located((By.XPATH, radio_xpath))) except TimeoutException: # Fall back to clicking the label text itself radio = wait.until(EC.element_to_be_clickable((By.XPATH, "//*[self::label or self::span][normalize-space(.)='Authorization Number']" ))) self.driver.execute_script("arguments[0].scrollIntoView({block:'center'});", radio) try: radio.click() except Exception: self.driver.execute_script("arguments[0].click();", radio) print("[UnitedSCO PreAuthCheck step1] Chose 'Authorization Number'") time.sleep(1) def _find_auth_number_input(self, wait): selectors = [ "//input[contains(translate(@id,'AUTHORIZATION','authorization'),'auth')][not(@type='radio')]", "//input[contains(translate(@formcontrolname,'AUTHORIZATION','authorization'),'auth')][not(@type='radio')]", "//label[contains(normalize-space(.),'Authorization Number') and not(.//input[@type='radio'])]" "/following::input[not(@type='radio') and not(@type='hidden')][1]", "//label[normalize-space(.)='Authorization Number']/following::input[not(@type='radio') and not(@type='hidden')][1]", ] def find(_): for sel in selectors: for el in self.driver.find_elements(By.XPATH, sel): if el.is_displayed() and el.is_enabled(): return el return False return wait.until(find) def step1(self): if not self.preAuthNumber: return "ERROR: This claim has no preauth (authorization) number to search for." wait = WebDriverWait(self.driver, 30) try: print(f"[UnitedSCO PreAuthCheck step1] Opening {AUTH_SEARCH_URL}") self.driver.get(AUTH_SEARCH_URL) time.sleep(3) try: self._select_payer(wait) except TimeoutException: return "ERROR: Payer dropdown not found on the DentalHub authorization search page." try: self._choose_authorization_number_option(wait) except TimeoutException: return "ERROR: 'Authorization Number' option not found on the DentalHub authorization search page." try: auth_input = self._find_auth_number_input(WebDriverWait(self.driver, 10)) except TimeoutException: return "ERROR: Authorization Number field did not appear after choosing that option." auth_input.click() auth_input.send_keys(Keys.CONTROL, "a") auth_input.send_keys(Keys.DELETE) auth_input.send_keys(self.preAuthNumber) print(f"[UnitedSCO PreAuthCheck step1] Entered authorization number: {self.preAuthNumber}") search_btn = wait.until(EC.element_to_be_clickable((By.ID, "search"))) self.driver.execute_script("arguments[0].scrollIntoView({block:'center'});", search_btn) search_btn.click() print("[UnitedSCO PreAuthCheck step1] Clicked Search") time.sleep(3) error_result = self._check_for_error_dialog() if error_result: return error_result return "SUCCESS" except TimeoutException: return "ERROR: DentalHub authorization search page did not load." except Exception as e: return f"ERROR: Authorization search failed: {e}" def step2(self): number = self.preAuthNumber row_xpath = f"//tbody//tr[contains(normalize-space(.), '{number}')]" try: # 1) Wait for the result row try: WebDriverWait(self.driver, 30).until(EC.presence_of_element_located((By.XPATH, row_xpath))) except TimeoutException: body = self.driver.find_element(By.TAG_NAME, "body").text.lower() if "no record" in body or "no results" in body or "0 records" in body or "no authorization" in body: return {"status": "error", "message": f"United SCO found no authorization #{number}."} return {"status": "error", "message": f"Search result for authorization #{number} did not load."} # Status column of the row (e.g. "Processed"), read by its header status = "" try: row = self.driver.find_element(By.XPATH, row_xpath) table = row.find_element(By.XPATH, "./ancestor::table[1]") headers = [h.text.strip().lower() for h in table.find_elements(By.XPATH, ".//thead//tr[1]/*")] cells = row.find_elements(By.XPATH, "./*") idx = next((i for i, h in enumerate(headers) if h.startswith("status")), -1) if 0 <= idx < len(cells): status = cells[idx].text.strip() except Exception as e: print(f"[UnitedSCO PreAuthCheck step2] Reading status failed: {e}") print(f"[UnitedSCO PreAuthCheck step2] Status: {status!r}") # 2) Options button on that row, then the first menu item ("View Summary") options_xpath = f"{row_xpath}//button[@id='btnGroupDrop' or contains(normalize-space(.),'Options')]" options_btn = WebDriverWait(self.driver, 15).until(EC.element_to_be_clickable((By.XPATH, options_xpath))) self.driver.execute_script("arguments[0].scrollIntoView({block:'center'});", options_btn) try: options_btn.click() except Exception: self.driver.execute_script("arguments[0].click();", options_btn) print("[UnitedSCO PreAuthCheck step2] Opened Options menu") menu_item_xpath = ( f"{row_xpath}//*[contains(@class,'dropdown-menu')]//*[self::a or self::button]" "[contains(translate(normalize-space(.),'VIEWSUMARY','viewsumary'),'view summary')]" " | //*[contains(@class,'dropdown-menu') and contains(@class,'show')]//*[self::a or self::button]" "[contains(translate(normalize-space(.),'VIEWSUMARY','viewsumary'),'view summary')]" ) try: view_summary = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable((By.XPATH, menu_item_xpath))) except TimeoutException: # Fall back to the first item of the opened menu view_summary = WebDriverWait(self.driver, 5).until(EC.element_to_be_clickable((By.XPATH, f"({row_xpath}//*[contains(@class,'dropdown-menu')]//*[self::a or self::button])[1]" ))) windows_before = set(self.driver.window_handles) try: view_summary.click() except Exception: self.driver.execute_script("arguments[0].click();", view_summary) print("[UnitedSCO PreAuthCheck step2] Clicked View Summary") time.sleep(1) new_windows = [w for w in self.driver.window_handles if w not in windows_before] if new_windows: self.driver.switch_to.window(new_windows[0]) print("[UnitedSCO PreAuthCheck step2] Summary opened in a new tab") # 3) Wait for "Authorization Summary" with the authorization number try: WebDriverWait(self.driver, 30).until(EC.presence_of_element_located((By.XPATH, f"//*[contains(normalize-space(.),'Authorization Number')][contains(normalize-space(.),'{number}')]" ))) WebDriverWait(self.driver, 15).until(EC.presence_of_element_located((By.XPATH, "//*[contains(normalize-space(.),'Determination Information')]" ))) except TimeoutException: print(f"[UnitedSCO PreAuthCheck step2] Summary page not found. URL: {self.driver.current_url}") return {"status": "error", "message": f"Authorization Summary for #{number} did not load."} print(f"[UnitedSCO PreAuthCheck step2] Summary page: {self.driver.current_url}") # Heading status ("Authorization Summary Processed") if the table had none if not status: try: heading = self.driver.find_element(By.XPATH, "//*[self::h1 or self::h2][contains(normalize-space(.),'Authorization Summary')]").text status = heading.replace("Authorization Summary", "").strip() except Exception: pass time.sleep(2) # let the procedure section finish rendering # 4) Save the page as a PDF (the Print button opens Chrome's dialog, which Selenium can't drive) 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, }) status_slug = re.sub(r"[^a-z0-9]+", "_", status.lower()).strip("_") or "summary" pdf_path = os.path.join( self.download_dir, f"unitedsco_preauth_{status_slug}_{number}_{int(time.time())}.pdf" ) with open(pdf_path, "wb") as f: f.write(base64.b64decode(pdf.get("data", ""))) print(f"[UnitedSCO PreAuthCheck step2] PDF saved: {pdf_path}") # Leave the browser idle so the session stays logged in for the next run try: if new_windows: self.driver.close() self.driver.switch_to.window(next(iter(windows_before))) self.driver.get("about:blank") self.driver.minimize_window() except Exception: pass return { "status": "success", "message": f"United SCO authorization #{number}" + (f": {status}." if status else "."), "preAuthNumber": number, "preAuthStatus": status, "approval_pdf_path": pdf_path, } except TimeoutException: return {"status": "error", "message": f"Options / View Summary not found for authorization #{number}."} except Exception as e: print(f"[UnitedSCO PreAuthCheck step2] Failed: {e}") return {"status": "error", "message": f"United SCO pre-auth check failed: {e}"}