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_DentaQuest_eligibilityCheckWorker import AutomationDentaQuestEligibilityCheck from tuftssco_preauth_procedures import extract_preauth_procedures SUBMITTED_URL = "https://providers.dentaquest.com/pre-auth-claims/submitted/" class AutomationTuftsSCOPreAuthCheck(AutomationDentaQuestEligibilityCheck): """ Tufts SCO (DentaQuest) Check PreAuth. login: same as the eligibility check (persistent browser session, OTP if asked). step1: open Pre-authorizations and Claims > Submitted, clear the date range, search by pre-auth / claim number. step2: open the pre-auth from the result row and save its detail page as a PDF (filed under the patient's Approval folder by the backend), and read its procedure lines for the patient's Preauth History. """ 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 step1(self): number = self.preAuthNumber or self.claimNumber if not number: return "ERROR: This record has no pre-auth or claim number to search for." wait = WebDriverWait(self.driver, 30) try: print(f"[TuftsSCO PreAuthCheck step1] Opening {SUBMITTED_URL}") self.driver.get(SUBMITTED_URL) if self._is_maintenance_page(): return "ERROR: DentaQuest server is temporarily unavailable (maintenance). Please try again later." # Clear "Set date range" (defaults to the last 2 weeks) so older preauths are found try: clear_btn = WebDriverWait(self.driver, 15).until(EC.element_to_be_clickable( (By.XPATH, "//button[@aria-label='Clear date range']") )) clear_btn.click() print("[TuftsSCO PreAuthCheck step1] Cleared date range") time.sleep(0.5) except TimeoutException: print("[TuftsSCO PreAuthCheck step1] No date range to clear") number_input = wait.until(EC.element_to_be_clickable( (By.XPATH, "//input[@data-testid='claims-search_claim-number_input']") )) number_input.click() number_input.send_keys(Keys.CONTROL, "a") number_input.send_keys(Keys.DELETE) number_input.send_keys(number) print(f"[TuftsSCO PreAuthCheck step1] Entered number: {number}") search_btn = wait.until(EC.element_to_be_clickable( (By.XPATH, "//button[@data-testid='claims-search_submit-btn']") )) search_btn.click() print("[TuftsSCO PreAuthCheck step1] Clicked Search") return "SUCCESS" except TimeoutException: return "ERROR: Pre-auth/claim search form not found on the Submitted page." except Exception as e: return f"ERROR: Pre-auth search failed: {e}" def step2(self): number = self.preAuthNumber or self.claimNumber try: # 1) Wait for the result row and click the pre-auth number in its first column try: id_link = WebDriverWait(self.driver, 30).until(EC.element_to_be_clickable( (By.XPATH, f"//tbody//tr[1]/*[1]//*[self::a or self::button][contains(normalize-space(.), '{number}')]") )) except TimeoutException: body = self.driver.find_element(By.TAG_NAME, "body").text if "0 records found" in body or "no records" in body.lower() or "no results" in body.lower(): return {"status": "error", "message": f"Tufts SCO found no pre-auth/claim #{number}."} return {"status": "error", "message": f"Search result for #{number} did not load."} # Status column of the result row (e.g. "Approved"), read before leaving the page # (cells may be or , and header text may carry sort-icon text) status = "" try: headers = [h.text.strip().lower() for h in self.driver.find_elements(By.XPATH, "//thead//tr[1]/*")] cells = self.driver.find_elements(By.XPATH, "//tbody//tr[1]/*") idx = next((i for i, h in enumerate(headers) if h.startswith("status")), -1) if 0 <= idx < len(cells): status = cells[idx].text.strip() if not status: row_text = " ".join(c.text for c in cells).lower() for word in ("Partially approved", "Approved", "Denied","Pending", "In review", "Rejected"): if word.lower() in row_text: status = word break except Exception as e: print(f"[TuftsSCO PreAuthCheck step2] Reading status failed: {e}") print(f"[TuftsSCO PreAuthCheck step2] Status: {status!r}") # A plain click can be intercepted (banner over the row) or hit a re-rendered link link_xpath = f"//tbody//tr[1]/*[1]//*[self::a or self::button][contains(normalize-space(.), '{number}')]" windows_before = set(self.driver.window_handles) try: id_link = self.driver.find_element(By.XPATH, link_xpath) self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", id_link) id_link.click() except Exception as e: print(f"[TuftsSCO PreAuthCheck step2] Click failed ({type(e).__name__}), using JS click") self.driver.execute_script("arguments[0].click();", self.driver.find_element(By.XPATH, link_xpath)) # The detail page may open in a new tab 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("[TuftsSCO PreAuthCheck step2] Detail page opened in a new tab") print(f"[TuftsSCO PreAuthCheck step2] Opened #{number}: {self.driver.current_url}") # 2) Wait for the detail page ("Pre-authorization for ") try: WebDriverWait(self.driver, 30).until(EC.presence_of_element_located( (By.XPATH, f"//h1[contains(., '{number}')] | //*[self::h1 or self::h2][contains(., 'for ')][contains(., '{number}')]") )) except TimeoutException: print(f"[TuftsSCO PreAuthCheck step2] Detail page not found. URL: {self.driver.current_url}") return {"status": "error", "message": f"Detail page for #{number} did not load."} # Denied pre-auths may have no procedure section; still save the page as a PDF try: WebDriverWait(self.driver, 15).until(EC.presence_of_element_located( (By.XPATH, "//*[contains(normalize-space(.), 'Procedure information')]") )) except TimeoutException: print("[TuftsSCO PreAuthCheck step2] No 'Procedure information' section") time.sleep(2) # let the procedure table finish rendering # Procedure lines for the patient's Preauth History procedures = extract_preauth_procedures(self.driver) # 3) The page's Print button opens Chrome's print dialog, which Selenium can't drive; # printing to PDF through DevTools produces the same printable page. 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 "approval" pdf_path = os.path.join( self.download_dir, f"tuftssco_preauth_{status_slug}_{number}_{int(time.time())}.pdf" ) with open(pdf_path, "wb") as f: f.write(base64.b64decode(pdf.get("data", ""))) print(f"[TuftsSCO 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"Tufts SCO pre-auth #{number}" + (f": {status}." if status else "."), "preAuthNumber": number, "preAuthStatus": status, "procedures": procedures, "approval_pdf_path": pdf_path, } except Exception as e: print(f"[TuftsSCO PreAuthCheck step2] Failed: {e}") return {"status": "error", "message": f"Tufts SCO pre-auth check failed: {e}"}