import os import re import time import base64 import asyncio from datetime import date, datetime from typing import Dict, Any 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 from selenium.common.exceptions import WebDriverException, TimeoutException # Reuse the DDMA eligibility worker for login (same persistent browser + device trust) from selenium_DDMA_eligibilityCheckWorker import AutomationDeltaDentalMAEligibilityCheck # In-memory session store sessions: Dict[str, Dict[str, Any]] = {} SESSION_OTP_TIMEOUT = int(os.getenv("SESSION_OTP_TIMEOUT", "120")) # seconds DDMA_DASHBOARD_URL = "https://www.deltadentalma.com/private/provider/dashboard" MEMBER_SEARCH_XPATH = "//a[contains(@href, 'check-patient-benefits-search')]" CLAIMS_STATUS_PATH = "/private/provider/claims-status-search" CLAIMS_STATUS_URL = "https://www.deltadentalma.com" + CLAIMS_STATUS_PATH MAX_CLAIM_PAGES = 100 # Same place the MH batch check saves its PDFs (Backend/uploads/MHVoucher) DDMA_PAYMENT_PDF_DIR = os.path.abspath( os.path.join(os.path.dirname(__file__), "..", "Backend", "uploads", "DDMAPayment") ) # ─── Claim status page helpers (sync — run via asyncio.to_thread) ──────────── def _parse_iso_date(value: str | None) -> date | None: if not value: return None try: return datetime.strptime(value[:10], "%Y-%m-%d").date() except ValueError: return None def _parse_portal_date(text: str) -> date | None: """Portal shows dates like 'Nov 25, 2026' (fallback: 11/25/2026).""" text = (text or "").strip() for fmt in ("%b %d, %Y", "%B %d, %Y", "%m/%d/%Y"): try: return datetime.strptime(text, fmt).date() except ValueError: continue return None def _parse_amount(text: str) -> float | None: cleaned = re.sub(r"[^0-9.\-]", "", text or "") if not cleaned: return None try: return round(float(cleaned), 2) except ValueError: return None def _click_claim_status_link(driver, timeout: int = 15) -> bool: """ Click the visible 'Check Claim Status' quick link. The page has several links to the same URL (some hidden in menus), so pick a displayed one, preferring the QuickLink button. """ xpaths = [ f"//a[contains(@class, 'QuickLink') and contains(@href, '{CLAIMS_STATUS_PATH}')]", "//a[normalize-space(.)='Check Claim Status']", f"//a[contains(@href, '{CLAIMS_STATUS_PATH}')]", ] deadline = time.time() + timeout while time.time() < deadline: for xp in xpaths: for link in driver.find_elements(By.XPATH, xp): try: if not link.is_displayed(): continue driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", link) time.sleep(0.3) driver.execute_script("arguments[0].click();", link) print(f"[DDMA Payment] Clicked 'Check Claim Status' ({xp})") return True except Exception as e: print(f"[DDMA Payment] Link click failed: {e}") time.sleep(0.5) return False def _wait_for_claims_table(driver, timeout: int = 30) -> bool: """ Wait until the claims table is readable. Checks the main page and any iframes; leaves the driver switched into whichever frame holds the table. """ deadline = time.time() + timeout while time.time() < deadline: try: driver.switch_to.default_content() if driver.execute_script(_READ_TABLE_JS): return True for i, _ in enumerate(driver.find_elements(By.TAG_NAME, "iframe")): try: driver.switch_to.default_content() driver.switch_to.frame(i) if driver.execute_script(_READ_TABLE_JS): print(f"[DDMA Payment] Claims table found inside iframe #{i}") return True except Exception: continue except Exception: pass time.sleep(1) driver.switch_to.default_content() return False def _save_debug_snapshot(driver, tag: str) -> None: """Save the current page HTML + screenshot so we can see what Selenium saw.""" try: debug_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "debug_ddma_payment") os.makedirs(debug_dir, exist_ok=True) stamp = datetime.now().strftime("%Y%m%d_%H%M%S") base = os.path.join(debug_dir, f"{tag}_{stamp}") try: driver.switch_to.default_content() except Exception: pass with open(base + ".html", "w", encoding="utf-8") as f: f.write(driver.page_source) driver.save_screenshot(base + ".png") print(f"[DDMA Payment] Saved debug snapshot: {base}.html / .png (URL: {driver.current_url})") except Exception as e: print(f"[DDMA Payment] Could not save debug snapshot: {e}") def _open_claim_status_page(driver): """Click the 'Check Claim Status' quick link on the dashboard (fallback: direct URL).""" driver.switch_to.default_content() if "dashboard" not in driver.current_url.lower(): driver.get(DDMA_DASHBOARD_URL) if not _click_claim_status_link(driver): print("[DDMA Payment] 'Check Claim Status' link not found; navigating directly") driver.get(CLAIMS_STATUS_URL) # Wait for the Service From Date box — the claims page is ready once it shows print(f"[DDMA Payment] Waiting for Service From Date box (URL: {driver.current_url})") try: WebDriverWait(driver, 30).until( EC.visibility_of_element_located((By.XPATH, "//input[@data-test-id='fromDate']")) ) except TimeoutException: _save_debug_snapshot(driver, "date_boxes_not_found") raise RuntimeError( f"Service date boxes not found on DDMA claim status page (URL: {driver.current_url})" ) time.sleep(1) _NO_RESULTS_JS = """ const live = document.getElementById('liveFilterMessage'); if (live && /^\\s*0 results/i.test(live.textContent || '')) return true; const t = (document.body.innerText || '').toLowerCase(); return /no (claims|results|records)|\\b0 results|nothing found/.test(t); """ def _fill_date_field(driver, test_id: str, d: date) -> bool: """ Fill the claims page date box (). It is a masked mm/dd/yyyy input with a jQuery UI datepicker. Returns True if filled. """ target = d.strftime("%m/%d/%Y") try: inp = WebDriverWait(driver, 10).until(EC.element_to_be_clickable( (By.XPATH, f"//input[@data-test-id='{test_id}']") )) except TimeoutException: print(f"[DDMA Payment] Could not find '{test_id}' input") return False try: driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", inp) inp.click() inp.send_keys(Keys.CONTROL, "a") inp.send_keys(Keys.BACKSPACE) # Masked input: type digits only, the mask inserts the slashes inp.send_keys(d.strftime("%m%d%Y")) time.sleep(0.3) # Close the datepicker popup inp.send_keys(Keys.ESCAPE) except Exception as e: print(f"[DDMA Payment] Typing into '{test_id}' failed: {e}") value = (inp.get_attribute("value") or "").strip() if value != target: # Fallback: set the value directly and fire the events the page listens to print(f"[DDMA Payment] '{test_id}' shows '{value}' after typing; setting via JS") driver.execute_script( """ const el = arguments[0], v = arguments[1]; el.value = v; el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); if (window.jQuery) { window.jQuery(el).val(v).trigger('change'); } """, inp, target, ) value = (inp.get_attribute("value") or "").strip() try: inp.send_keys(Keys.TAB) except Exception: pass print(f"[DDMA Payment] Filled '{test_id}' = {value} (wanted {target})") return value == target _READ_TABLE_JS = """ const text = el => (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim(); // Case 0: DDMA claims grid made of divs: // .grid-container > .tableHeader > .cell ... (headers) // .containerforResults > .rowResults > .cell (one row per claim) const gridHdrDiv = Array.from(document.querySelectorAll('.tableHeader')) .find(h => Array.from(h.children).some(c => /^claim\\s*number$/i.test(text(c)))); if (gridHdrDiv) { const container = gridHdrDiv.closest('.grid-container') || gridHdrDiv.parentElement; const headers = Array.from(gridHdrDiv.children).map(text); const rows = Array.from(container.querySelectorAll('.rowResults')) .filter(r => r.offsetParent !== null) // skip rows hidden by the live filter .map(r => Array.from(r.querySelectorAll(':scope > .cell')).map(text)) .filter(cells => cells.length > 1); if (rows.length) return { headers, rows }; } // Find the 'Claim number' header cell (th, td, or ARIA column header) const hdr = Array.from(document.querySelectorAll('th, td, [role=columnheader]')) .find(el => /^claim\\s*(number|no\\.?|#)\\b/i.test(text(el)) && text(el).length < 40); if (!hdr) return null; // Case 1: real const hdrRow = hdr.closest('tr'); const table = hdr.closest('table'); if (table && hdrRow) { const headers = Array.from(hdrRow.children).map(text); const rows = Array.from(table.querySelectorAll('tr')) .filter(tr => tr !== hdrRow && !tr.querySelector('th')) .map(tr => Array.from(tr.children).map(text)) .filter(cells => cells.length > 1); return { headers, rows }; } // Case 2: ARIA grid made of divs const grid = hdr.closest('[role=table], [role=grid]'); const gridHdrRow = hdr.closest('[role=row]'); if (grid && gridHdrRow) { const headers = Array.from(gridHdrRow.children).map(text); const rows = Array.from(grid.querySelectorAll('[role=row]')) .filter(r => r !== gridHdrRow) .map(r => Array.from(r.children).map(text)) .filter(cells => cells.length > 1); return { headers, rows }; } return null; """ def _read_claims_table(driver) -> list[dict]: data = driver.execute_script(_READ_TABLE_JS) if not data: return [] headers = [h.lower() for h in data.get("headers", [])] def idx(*names): for i, h in enumerate(headers): if any(n in h for n in names): return i return None i_dos = idx("date of service") i_provider = idx("provider") i_patient = idx("patient") i_claim = idx("claim number") i_pays = idx("plan pays") i_status = idx("status") def cell(cells, i): return cells[i] if i is not None and i < len(cells) else "" out = [] for cells in data.get("rows", []): claim_number = cell(cells, i_claim).strip() if not claim_number: continue dos_text = cell(cells, i_dos) dos = _parse_portal_date(dos_text) out.append({ "claimNumber": claim_number, "dateOfService": dos.isoformat() if dos else dos_text, "provider": cell(cells, i_provider), "patientName": cell(cells, i_patient), "planPays": _parse_amount(cell(cells, i_pays)), "planPaysText": cell(cells, i_pays), "status": cell(cells, i_status).replace("*", "").strip(), }) return out def _go_to_next_page(driver, current_page: int, first_claim_before: str | None) -> bool: """ Advance the claims table one page by clicking 'Next →'. Returns True if the table changed. The DDMA pager (.paginationWrapper) is hidden when there is only one page, and its Next link has class 'disabled' on the last page. """ next_xpaths = [ "//div[contains(@class,'paginationWrapper')]//span[contains(@class,'controlsRight')]//a[contains(@class,'nextLink')]", "//a[@aria-label='Next' or @aria-label='Next page' or @aria-label='Go to next page']", "//button[@aria-label='Next' or @aria-label='Next page' or @aria-label='Go to next page']", "//a[normalize-space(.)='Next' or normalize-space(.)='›' or normalize-space(.)='»' or normalize-space(.)='>']", "//button[normalize-space(.)='Next' or normalize-space(.)='›' or normalize-space(.)='»' or normalize-space(.)='>']", f"//a[normalize-space(.)='{current_page + 1}']", f"//button[normalize-space(.)='{current_page + 1}']", ] clicked = False for xp in next_xpaths: try: for el in driver.find_elements(By.XPATH, xp): if not el.is_displayed(): continue cls = (el.get_attribute("class") or "").lower() if el.get_attribute("disabled") or el.get_attribute("aria-disabled") == "true" or "disabled" in cls: continue driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", el) driver.execute_script("arguments[0].click();", el) clicked = True break except Exception: continue if clicked: break if not clicked: # No enabled Next link (single page, or last page reached) return False # Wait for the first row to change for _ in range(20): time.sleep(0.5) rows = _read_claims_table(driver) if not rows: return False if rows[0]["claimNumber"] != first_claim_before: return True return False def _print_page_pdf(driver) -> bytes | None: """Print the current page to PDF bytes (same settings as the MH results PDF).""" try: result = driver.execute_cdp_cmd("Page.printToPDF", { "landscape": True, "printBackground": True, "preferCSSPageSize": False, "paperWidth": 11, "paperHeight": 8.5, "marginTop": 0.3, "marginBottom": 0.3, "marginLeft": 0.3, "marginRight": 0.3, "scale": 0.8, }) return base64.b64decode(result.get("data", "")) except Exception as e: print(f"[DDMA Payment] Could not print page to PDF: {e}") return None def _save_results_pdf(pdf_pages: list[bytes], from_d: date | None, to_d: date | None) -> str | None: """Combine the printed result pages into one PDF in Backend/uploads/DDMAPayment.""" pdf_pages = [p for p in pdf_pages if p] if not pdf_pages: return None try: os.makedirs(DDMA_PAYMENT_PDF_DIR, exist_ok=True) safe_from = from_d.strftime("%Y%m%d") if from_d else "start" safe_to = to_d.strftime("%Y%m%d") if to_d else "end" stamp = datetime.now().strftime("%Y%m%d_%H%M%S") pdf_path = os.path.join( DDMA_PAYMENT_PDF_DIR, f"ddma_claims_{safe_from}_to_{safe_to}_{stamp}.pdf" ) if len(pdf_pages) == 1: with open(pdf_path, "wb") as f: f.write(pdf_pages[0]) else: import fitz # PyMuPDF merged = fitz.open() for page_bytes in pdf_pages: with fitz.open(stream=page_bytes, filetype="pdf") as part: merged.insert_pdf(part) merged.save(pdf_path) merged.close() print(f"[DDMA Payment] Saved results PDF: {pdf_path}") return pdf_path except Exception as e: print(f"[DDMA Payment] Error saving results PDF: {e}") return None def extract_claim_payments(driver, from_date_str: str | None, to_date_str: str | None) -> dict: """ Opens Check Claim Status, enters the service date range (the Patient box is left empty), and returns: { "claims": [{ claimNumber, dateOfService, patientName, provider, planPays, status }, ...], "pdfPath": "" | None } Only claims whose date of service is within the range are returned. """ from_d = _parse_iso_date(from_date_str) to_d = _parse_iso_date(to_date_str) _open_claim_status_page(driver) if from_d: _fill_date_field(driver, "fromDate", from_d) if to_d: _fill_date_field(driver, "toDate", to_d) # The page refreshes the claims list on its own once both dates are in time.sleep(3) print("[DDMA Payment] Waiting for claims list") if not _wait_for_claims_table(driver): if driver.execute_script(_NO_RESULTS_JS): print("[DDMA Payment] Page reports no claims for this date range") driver.switch_to.default_content() pdf_path = _save_results_pdf([_print_page_pdf(driver)], from_d, to_d) return {"claims": [], "pdfPath": pdf_path} _save_debug_snapshot(driver, "claims_table_not_found") raise RuntimeError( f"Claims list did not appear after entering the dates (URL: {driver.current_url})" ) time.sleep(1) results: dict[str, dict] = {} pdf_pages: list[bytes] = [] page = 1 while page <= MAX_CLAIM_PAGES: rows = _read_claims_table(driver) print(f"[DDMA Payment] Page {page}: {len(rows)} row(s)") if not rows: break # Save this results page for the PDF (print from the top-level page) try: driver.switch_to.default_content() pdf_pages.append(_print_page_pdf(driver)) finally: _wait_for_claims_table(driver, timeout=5) # re-enter the table's frame if any all_older = True for r in rows: dos = _parse_iso_date(r["dateOfService"]) if dos and from_d and dos < from_d: continue all_older = False if dos and to_d and dos > to_d: continue results.setdefault(r["claimNumber"], r) # Table is sorted newest first — stop once a whole page is before the range if all_older: print("[DDMA Payment] Page is entirely before From date — stopping") break if not _go_to_next_page(driver, page, rows[0]["claimNumber"]): break page += 1 claims = list(results.values()) print(f"[DDMA Payment] Extracted {len(claims)} claim(s) in range") driver.switch_to.default_content() pdf_path = _save_results_pdf(pdf_pages, from_d, to_d) return {"claims": claims, "pdfPath": pdf_path} def make_session_entry() -> str: """Create a new session entry and return its ID.""" import uuid sid = str(uuid.uuid4()) sessions[sid] = { "status": "created", # created → running → waiting_for_otp → completed / error "created_at": time.time(), "last_activity": time.time(), "bot": None, "driver": None, "otp_event": asyncio.Event(), "otp_value": None, "result": None, "message": None, "type": None, } return sid async def cleanup_session(sid: str, message: str | None = None): """ Wake any OTP waiter, set final state, and remove the session entry. NOTE: Does NOT quit the browser driver — the persistent browser stays alive. """ s = sessions.get(sid) if not s: return try: if s.get("status") not in ("completed", "error", "not_found"): s["status"] = "error" if message: s["message"] = message ev = s.get("otp_event") if ev and not ev.is_set(): ev.set() finally: sessions.pop(sid, None) print(f"[helpers_ddma_payment] cleaned session {sid}") async def _remove_session_later(sid: str, delay: int = 20): await asyncio.sleep(delay) await cleanup_session(sid) async def start_ddma_payment_run(sid: str, data: dict, url: str): """ DDMA payment check workflow for one session. Login + OTP handling mirrors helpers_ddma_eligibility.start_ddma_run. data: { massddmaUsername, massddmaPassword, fromDate, toDate, ... } """ s = sessions.get(sid) if not s: return {"status": "error", "message": "session not found"} s["status"] = "running" s["last_activity"] = time.time() from_date = data.get("fromDate") to_date = data.get("toDate") try: bot = AutomationDeltaDentalMAEligibilityCheck({"data": data}) bot.config_driver() s["bot"] = bot s["driver"] = bot.driver s["last_activity"] = time.time() # Navigate to login page try: if not url: raise ValueError("URL not provided for DDMA payment run") bot.driver.maximize_window() bot.driver.get(url) await asyncio.sleep(1) except Exception as e: s["status"] = "error" s["message"] = f"Navigation failed: {e}" await cleanup_session(sid) return {"status": "error", "message": s["message"]} # Login try: login_result = bot.login(url) except WebDriverException as wde: s["status"] = "error" s["message"] = f"Selenium driver error during login: {wde}" await cleanup_session(sid, s["message"]) return {"status": "error", "message": s["message"]} except Exception as e: s["status"] = "error" s["message"] = f"Unexpected error during login: {e}" await cleanup_session(sid, s["message"]) return {"status": "error", "message": s["message"]} # ── Path: already logged in (persistent session) ────────────────────── if isinstance(login_result, str) and login_result == "ALREADY_LOGGED_IN": print("[DDMA Payment] Session persisted - skipping OTP") s["status"] = "running" s["message"] = "Session persisted" # ── Path: OTP required ──────────────────────────────────────────────── elif isinstance(login_result, str) and login_result == "OTP_REQUIRED": s["status"] = "waiting_for_otp" s["message"] = "OTP required for login - please enter OTP" s["last_activity"] = time.time() driver = s["driver"] max_polls = SESSION_OTP_TIMEOUT login_success = False print(f"[DDMA Payment OTP] Polling for OTP completion (up to {SESSION_OTP_TIMEOUT}s)...") for poll in range(max_polls): await asyncio.sleep(1) s["last_activity"] = time.time() try: # a) App submitted OTP via /submit-otp endpoint otp_value = s.get("otp_value") if otp_value: print(f"[DDMA Payment OTP poll {poll+1}] OTP received from app, typing it in...") try: otp_input = driver.find_element(By.XPATH, "//input[@data-test-id='MfaCode']") otp_input.clear() otp_input.send_keys(otp_value) try: verify_btn = driver.find_element(By.XPATH, "//button[@data-test-id='ConfirmSubmitButton']") verify_btn.click() except Exception: otp_input.send_keys("\n") print("[DDMA Payment OTP] OTP typed and submitted via app") s["otp_value"] = None await asyncio.sleep(3) except Exception as type_err: print(f"[DDMA Payment OTP] Failed to type OTP from app: {type_err}") # b) Check URL — if we're past OTP page, login succeeded current_url = driver.current_url.lower() print(f"[DDMA Payment OTP poll {poll+1}/{max_polls}] URL: {current_url[:70]}...") if "member" in current_url or "dashboard" in current_url or "eligibility" in current_url: try: WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.XPATH, MEMBER_SEARCH_XPATH)) ) print("[DDMA Payment OTP] Dashboard found — login successful!") login_success = True break except TimeoutException: print("[DDMA Payment OTP] On member page but dashboard link not found, continuing...") # Check if OTP input is still visible (user hasn't finished) try: driver.find_element(By.XPATH, "//input[@data-test-id='MfaCode']") print(f"[DDMA Payment OTP poll {poll+1}] OTP input still visible - waiting...") except Exception: if "sign-in" in current_url: print("[DDMA Payment OTP] OTP input gone, trying to navigate to dashboard...") try: driver.get(DDMA_DASHBOARD_URL) await asyncio.sleep(2) except Exception: pass except Exception as poll_err: print(f"[DDMA Payment OTP poll {poll+1}] Error: {poll_err}") if not login_success: try: print("[DDMA Payment OTP] Final attempt - navigating to dashboard...") driver.get(DDMA_DASHBOARD_URL) await asyncio.sleep(3) WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH, MEMBER_SEARCH_XPATH)) ) print("[DDMA Payment OTP] Dashboard found — login successful!") login_success = True except TimeoutException: s["status"] = "error" s["message"] = "OTP timeout - login not completed" await cleanup_session(sid) return {"status": "error", "message": "OTP not completed in time"} except Exception as final_err: s["status"] = "error" s["message"] = f"OTP verification failed: {final_err}" await cleanup_session(sid) return {"status": "error", "message": s["message"]} if login_success: s["status"] = "running" s["message"] = "Login successful after OTP" # ── Path: login succeeded without OTP ───────────────────────────────── elif isinstance(login_result, str) and login_result == "SUCCESS": print("[DDMA Payment] Login succeeded without OTP") s["status"] = "running" s["message"] = "Login succeeded" # ── Path: login error ────────────────────────────────────────────────── elif isinstance(login_result, str) and login_result.startswith("ERROR"): s["status"] = "error" s["message"] = login_result await cleanup_session(sid) return {"status": "error", "message": login_result} print(f"[DDMA Payment] Logged in. Date range: {from_date} → {to_date}") s["message"] = "Logged in — reading claim status" s["last_activity"] = time.time() # ── Claim status page: extract Plan Pays per claim number ───────────── try: extracted = await asyncio.to_thread(extract_claim_payments, bot.driver, from_date, to_date) except Exception as e: s["status"] = "error" s["message"] = f"Failed to read DDMA claim status: {e}" await cleanup_session(sid) return {"status": "error", "message": s["message"]} claims = extracted.get("claims", []) pdf_path = extracted.get("pdfPath") result = { "status": "success", "message": f"Found {len(claims)} DDMA claim(s) between {from_date} and {to_date}", "fromDate": from_date, "toDate": to_date, "claims": claims, "pdfFilename": os.path.basename(pdf_path) if pdf_path else None, } s["status"] = "completed" s["result"] = result s["message"] = "completed" asyncio.create_task(_remove_session_later(sid, 30)) return result except Exception as e: s["status"] = "error" s["message"] = f"worker exception: {e}" await cleanup_session(sid) return {"status": "error", "message": s["message"]} def submit_otp(sid: str, otp: str) -> Dict[str, Any]: """Called when the app sends an OTP via POST /submit-otp.""" s = sessions.get(sid) if not s: return {"status": "error", "message": "session not found"} if s.get("status") != "waiting_for_otp": return {"status": "error", "message": f"session not waiting for OTP (state={s.get('status')})"} s["otp_value"] = otp s["last_activity"] = time.time() try: s["otp_event"].set() except Exception: pass return {"status": "ok", "message": "otp accepted"} def get_session_status(sid: str) -> Dict[str, Any]: s = sessions.get(sid) if not s: return {"status": "not_found"} return { "session_id": sid, "status": s.get("status"), "message": s.get("message"), "created_at": s.get("created_at"), "last_activity": s.get("last_activity"), "result": s.get("result") if s.get("status") == "completed" else None, }