diff --git a/apps/Backend/src/routes/patients.ts b/apps/Backend/src/routes/patients.ts index 44a86bcd..274b29e6 100755 --- a/apps/Backend/src/routes/patients.ts +++ b/apps/Backend/src/routes/patients.ts @@ -380,6 +380,32 @@ router.delete( } } ); +// POST /api/patients/merge +// Body: { keepId, mergeIds } — moves the mergeIds records' appointments, claims, payments, +// documents and Cloud Storage folders onto keepId, then deletes them. +router.post("/merge", async (req: Request, res: Response): Promise => { + // Merging deletes records, so like delete it's admin-only + if (req.user!.username !== "admin") { + return res.status(403).json({ message: "Forbidden: Only admin users can merge patients." }); + } + + const keepId = Number(req.body?.keepId); + const mergeIds: number[] = Array.isArray(req.body?.mergeIds) + ? req.body.mergeIds.map(Number).filter((id: number) => Number.isInteger(id) && id > 0 && id !== keepId) + : []; + if (!Number.isInteger(keepId) || keepId <= 0 || mergeIds.length === 0) { + return res.status(400).json({ message: "Choose the record to keep and at least one other record to merge." }); + } + + try { + const patient = await storage.mergePatients(keepId, [...new Set(mergeIds)]); + return res.json(patient); + } catch (error: any) { + console.error("Merge patients error:", error); + return res.status(500).json({ message: error?.message || "Failed to merge patients" }); + } +}); + // Get appointments for a specific patient router.get( "/:patientId/appointments", diff --git a/apps/Backend/src/storage/cloudStorage-storage.ts b/apps/Backend/src/storage/cloudStorage-storage.ts index 005e11d1..eb5973b6 100755 --- a/apps/Backend/src/storage/cloudStorage-storage.ts +++ b/apps/Backend/src/storage/cloudStorage-storage.ts @@ -165,7 +165,7 @@ export interface IStorage { listRecentAttachmentFiles(limit?: number): Promise; listPatientAllCloudFiles( patientId: number - ): Promise<(CloudFile & { folderName: string })[]>; + ): Promise<(CloudFile & { folderName: string; recordLabel: string })[]>; } /* ------------------------------- Implementation ------------------------------- */ @@ -679,17 +679,55 @@ export const cloudStorageStorage: IStorage = { // Every file in the patient's folder and its subfolders (Approval, Eligibility, ...), // each tagged with the name of the folder it's in. async listPatientAllCloudFiles(patientId: number) { - const patientFolder = await db.cloudFolder.findFirst({ where: { patientId } }); - if (!patientFolder) return []; + // The same person may have several patient records (e.g. one per insurance, MassHealth + // then CCA): include every record with the same first + last name. + const patient = await db.patient.findUnique({ + where: { id: patientId }, + select: { firstName: true, lastName: true }, + }); + if (!patient) return []; + const records = await db.patient.findMany({ + where: { + firstName: { equals: patient.firstName.trim(), mode: "insensitive" }, + lastName: { equals: patient.lastName.trim(), mode: "insensitive" }, + }, + select: { id: true, insuranceProvider: true }, + }); + if (!records.some((r: { id: number }) => r.id === patientId)) { + records.push({ id: patientId, insuranceProvider: null }); + } - const folderNames = new Map([[patientFolder.id, patientFolder.name]]); - let frontier = [patientFolder.id]; + // A record can own more than one patient folder, so take all of them + const patientFolders = await db.cloudFolder.findMany({ + where: { patientId: { in: records.map((r: { id: number }) => r.id) } }, + select: { id: true, name: true, patientId: true }, + }); + if (patientFolders.length === 0) return []; + + // With several records, label each file with the record it belongs to + const multipleRecords = new Set(patientFolders.map((f: { patientId: number | null }) => f.patientId)).size > 1; + const recordLabel = (id: number | null) => { + if (!multipleRecords || id == null) return ""; + const r = records.find((x: { id: number }) => x.id === id); + return `${r?.insuranceProvider || "No insurance"} (#${id})`; + }; + + const folderNames = new Map(); + const folderRecords = new Map(); + patientFolders.forEach((f: { id: number; name: string; patientId: number | null }) => { + folderNames.set(f.id, f.name); + folderRecords.set(f.id, recordLabel(f.patientId)); + }); + let frontier = patientFolders.map((f: { id: number }) => f.id); while (frontier.length > 0) { const children = await db.cloudFolder.findMany({ where: { parentId: { in: frontier } }, - select: { id: true, name: true }, + select: { id: true, name: true, parentId: true }, + }); + children.forEach((c: { id: number; name: string; parentId: number | null }) => { + folderNames.set(c.id, c.name); + folderRecords.set(c.id, folderRecords.get(c.parentId as number) ?? ""); }); - children.forEach((c: { id: number; name: string }) => folderNames.set(c.id, c.name)); frontier = children.map((c: { id: number }) => c.id); } @@ -710,7 +748,8 @@ export const cloudStorageStorage: IStorage = { return files.map((f: any) => ({ ...serializeFile(f), folderName: folderNames.get(f.folderId as number) ?? "", - })) as unknown as (CloudFile & { folderName: string })[]; + recordLabel: folderRecords.get(f.folderId as number) ?? "", + })) as unknown as (CloudFile & { folderName: string; recordLabel: string })[]; }, async listRecentAttachmentFiles(limit: number = 20) { diff --git a/apps/Backend/src/storage/patients-storage.ts b/apps/Backend/src/storage/patients-storage.ts index e830d40b..f2e8c206 100755 --- a/apps/Backend/src/storage/patients-storage.ts +++ b/apps/Backend/src/storage/patients-storage.ts @@ -28,6 +28,7 @@ export interface IStorage { updatePatient(id: number, patient: UpdatePatient): Promise; touchPatient(id: number): Promise; deletePatient(id: number): Promise; + mergePatients(keepId: number, mergeIds: number[]): Promise; searchPatients(args: { filters: any; limit: number; @@ -203,6 +204,114 @@ export const patientsStorage: IStorage = { } }, + // Moves everything belonging to the mergeIds records onto keepId, fills keepId's blank fields + // from them, then deletes them. All in one transaction: a failure leaves every record as it was. + async mergePatients(keepId: number, mergeIds: number[]): Promise { + const ids = mergeIds.filter((id) => id !== keepId); + if (ids.length === 0) throw new Error("Choose at least one other record to merge"); + + return db.$transaction( + async (tx) => { + const keep = await tx.patient.findUnique({ where: { id: keepId } }); + if (!keep) throw new Error(`Patient ${keepId} not found`); + const others = await tx.patient.findMany({ where: { id: { in: ids } }, orderBy: { id: "desc" } }); + if (others.length !== ids.length) throw new Error("One of the records to merge was not found"); + + // 1) Fill the kept record's blank fields from the merged records (newest record first) + const isBlank = (v: unknown) => + v === null || v === undefined || (typeof v === "string" && v.trim() === ""); + const fillable = [ + "gender", "phone", "email", "address", "city", "state", "zipCode", "insuranceProvider", + "insuranceId", "groupNumber", "policyHolder", "policyHolderPatientId", + "policyHolderRelationship", "allergies", "medicalConditions", "remainingBenefit", + "thirdPartyInsurance", + ] as const; + const fill: Record = {}; + for (const field of fillable) { + if (!isBlank((keep as any)[field])) continue; + const source = others.find((o) => !isBlank((o as any)[field])); + if (source) fill[field] = (source as any)[field]; + } + // 1900-01-01 is the placeholder DOB for records created without one + const hasRealDob = (d: Date | null) => !!d && d.getUTCFullYear() > 1900; + if (!hasRealDob(keep.dateOfBirth)) { + const source = others.find((o) => hasRealDob(o.dateOfBirth)); + if (source) fill.dateOfBirth = source.dateOfBirth; + } + if (fill.policyHolderPatientId !== undefined && ids.includes(fill.policyHolderPatientId as number)) { + fill.policyHolderPatientId = keepId; + } + + // 2) Re-point everything that belongs to the merged records + const move = { where: { patientId: { in: ids } }, data: { patientId: keepId } }; + await tx.appointment.updateMany(move); + await tx.appointmentProcedure.updateMany(move); + await tx.claim.updateMany(move); + await tx.payment.updateMany(move); + await tx.pdfGroup.updateMany(move); + await tx.communication.updateMany(move); + await tx.patientDocument.updateMany(move); + await tx.patient.updateMany({ + where: { policyHolderPatientId: { in: ids } }, + data: { policyHolderPatientId: keepId }, + }); + // One-per-patient data: keep the kept record's own when it has one + if (!(await tx.patientConversation.findUnique({ where: { patientId: keepId } }))) { + const conv = await tx.patientConversation.findFirst({ where: { patientId: { in: ids } } }); + if (conv) await tx.patientConversation.update({ where: { id: conv.id }, data: { patientId: keepId } }); + } + // Service history is a snapshot from the last MassHealth check, not something to combine + if ((await tx.patientServiceHistory.count({ where: { patientId: keepId } })) === 0) { + const latest = await tx.patientServiceHistory.findFirst({ + where: { patientId: { in: ids } }, + orderBy: { createdAt: "desc" }, + }); + if (latest) { + await tx.patientServiceHistory.updateMany({ + where: { patientId: latest.patientId }, + data: { patientId: keepId }, + }); + } + } + + // 3) Cloud Storage: fold every patient folder of these records into one, + // merging same-name subfolders (Approval, Claims, ...) rather than duplicating them + const roots = await tx.cloudFolder.findMany({ + where: { patientId: { in: [keepId, ...ids] } }, + orderBy: { id: "asc" }, + }); + const target = roots.find((r) => r.patientId === keepId) ?? roots[0]; + const mergeFolderInto = async (srcId: number, dstId: number) => { + const children = await tx.cloudFolder.findMany({ where: { parentId: srcId } }); + for (const child of children) { + const same = await tx.cloudFolder.findFirst({ where: { parentId: dstId, name: child.name } }); + if (same) { + await mergeFolderInto(child.id, same.id); + await tx.cloudFolder.delete({ where: { id: child.id } }); + } else { + await tx.cloudFolder.update({ where: { id: child.id }, data: { parentId: dstId } }); + } + } + await tx.cloudFile.updateMany({ where: { folderId: srcId }, data: { folderId: dstId } }); + }; + if (target) { + for (const root of roots) { + if (root.id === target.id) continue; + await mergeFolderInto(root.id, target.id); + await tx.cloudFolder.delete({ where: { id: root.id } }); + } + await tx.cloudFolder.update({ where: { id: target.id }, data: { patientId: keepId } }); + } + + // 4) Remove the merged records (anything left on them is only data the kept record replaces) + await tx.patient.deleteMany({ where: { id: { in: ids } } }); + const merged = await tx.patient.update({ where: { id: keepId }, data: fill as any }); + return merged as unknown as Patient; + }, + { timeout: 60_000 } + ); + }, + async searchPatients({ filters, limit, diff --git a/apps/Frontend/src/components/file-upload/server-attachments-picker-modal.tsx b/apps/Frontend/src/components/file-upload/server-attachments-picker-modal.tsx index 9c49c38e..039d9956 100644 --- a/apps/Frontend/src/components/file-upload/server-attachments-picker-modal.tsx +++ b/apps/Frontend/src/components/file-upload/server-attachments-picker-modal.tsx @@ -18,7 +18,8 @@ interface ServerAttachmentsPickerModalProps { onFilesSelected: (files: File[]) => void; } -type PickerFile = CloudFile & { folderName?: string }; +// recordLabel: which of the patient's records (e.g. "CCA (#269)") the file is from, when there are several +type PickerFile = CloudFile & { folderName?: string; recordLabel?: string }; function fileIcon(mime: string | undefined | null) { if (mime?.startsWith("image/")) return ImageIcon; @@ -159,12 +160,12 @@ export function ServerAttachmentsPickerModal({

{showAllFolders - ? "Files saved in any of this patient's folders (Approval, Eligibility, Attachments, ...)." + ? "Files saved in any of this patient's folders (Approval, Eligibility, Attachments, ...), including the patient's other records." : patientId ? "Previously saved screenshots and files for this patient." : "Recently saved screenshots and files across all patients."}

- {folderNames.length > 1 && ( + {folderNames.length > 0 && (
{[null, ...folderNames].map((name) => (
{isSelected && (
diff --git a/apps/Frontend/src/components/patients/merge-patients-modal.tsx b/apps/Frontend/src/components/patients/merge-patients-modal.tsx new file mode 100644 index 00000000..d8363106 --- /dev/null +++ b/apps/Frontend/src/components/patients/merge-patients-modal.tsx @@ -0,0 +1,146 @@ +import { useEffect, useState } from "react"; +import { useMutation } from "@tanstack/react-query"; +import { Loader2 } from "lucide-react"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { Checkbox } from "@/components/ui/checkbox"; +import { apiRequest, queryClient } from "@/lib/queryClient"; +import { useToast } from "@/hooks/use-toast"; +import { formatDateToHumanReadable } from "@/utils/dateUtils"; +import { Patient } from "@repo/db/types"; +import { QK_PATIENTS_BASE } from "./patient-table"; + +interface MergePatientsModalProps { + open: boolean; + onClose: () => void; + // Records to choose from: the patients currently listed by the search + patients: Patient[]; +} + +export function MergePatientsModal({ open, onClose, patients }: MergePatientsModalProps) { + const { toast } = useToast(); + const [selectedIds, setSelectedIds] = useState>(new Set()); + const [keepId, setKeepId] = useState(null); + + // Start with every listed record ticked (a search like "shah" usually lists just the duplicates) + useEffect(() => { + if (!open) return; + const ids = patients.map((p) => Number(p.id)); + setSelectedIds(new Set(ids)); + setKeepId(ids[0] ?? null); + }, [open, patients]); + + const mergeMutation = useMutation({ + mutationFn: async () => { + const mergeIds = [...selectedIds].filter((id) => id !== keepId); + const res = await apiRequest("POST", "/api/patients/merge", { keepId, mergeIds }); + const json = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(json.message || "Failed to merge patients"); + return json as Patient; + }, + onSuccess: (patient) => { + queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE }); + toast({ + title: "Patients merged", + description: `All records are now PID-${String(patient.id).padStart(4, "0")} ${patient.firstName} ${patient.lastName}.`, + }); + onClose(); + }, + onError: (err: any) => { + toast({ title: "Merge failed", description: err?.message, variant: "destructive" }); + }, + }); + + const toggle = (id: number) => { + setSelectedIds((prev) => { + const next = new Set(prev); + if (next.has(id)) { + next.delete(id); + if (keepId === id) setKeepId([...next][0] ?? null); + } else { + next.add(id); + if (keepId === null) setKeepId(id); + } + return next; + }); + }; + + const mergeCount = [...selectedIds].filter((id) => id !== keepId).length; + const canMerge = keepId !== null && selectedIds.has(keepId) && mergeCount > 0; + + return ( + !o && !mergeMutation.isPending && onClose()}> + + + Merge Patients + + Tick the records that are the same patient and choose the one to keep. Appointments, + claims, payments, documents and files from the other records move to it, its blank + fields are filled from them, and the other records are deleted. This can't be undone. + + + + {patients.length < 2 ? ( +

+ Search for the patient first so their records are listed (e.g. "shah"), then click Merge. +

+ ) : ( +
+ {patients.map((p) => { + const id = Number(p.id); + const selected = selectedIds.has(id); + return ( +
+ toggle(id)} /> +
+
+ {p.firstName} {p.lastName}{" "} + PID-{String(id).padStart(4, "0")} +
+
+ DOB {formatDateToHumanReadable(p.dateOfBirth ?? undefined)} · {p.insuranceProvider || "No insurance"} + {p.insuranceId ? ` · ${p.insuranceId}` : ""} +
+
+ +
+ ); + })} +
+ )} + + + + + +
+
+ ); +} diff --git a/apps/Frontend/src/components/patients/patient-table.tsx b/apps/Frontend/src/components/patients/patient-table.tsx index a5a75663..3fa8754b 100755 --- a/apps/Frontend/src/components/patients/patient-table.tsx +++ b/apps/Frontend/src/components/patients/patient-table.tsx @@ -8,7 +8,7 @@ import { TableRow, } from "@/components/ui/table"; import { Button } from "@/components/ui/button"; -import { Delete, Edit, Eye, FileCheck, Scan, Upload, X, FileText, Download, Trash2, Camera, RefreshCw } from "lucide-react"; +import { Delete, Edit, Eye, FileCheck, Scan, Upload, X, FileText, Download, Trash2, Camera, RefreshCw, Merge } from "lucide-react"; import { Avatar, AvatarFallback } from "@/components/ui/avatar"; import { Pagination, @@ -39,6 +39,7 @@ import { Checkbox } from "@/components/ui/checkbox"; import { formatDateToHumanReadable } from "@/utils/dateUtils"; import { Patient, UpdatePatient } from "@repo/db/types"; import { PatientFinancialsModal } from "./patient-financial-modal"; +import { MergePatientsModal } from "./merge-patients-modal"; import { getPageNumbers } from "@/utils/pageNumberGenerator"; import { uploadDocument, @@ -72,6 +73,8 @@ interface PatientTableProps { allowCheckbox?: boolean; allowNewClaim?: boolean; allowFinancial?: boolean; + // Merge Patients button above the search (admin only, since merging deletes records) + allowMerge?: boolean; showEligibilityColumns?: boolean; onNewClaim?: (patientId: number) => void; onSelectPatient?: (patient: Patient | null) => void; @@ -92,6 +95,7 @@ export function PatientTable({ allowCheckbox, allowNewClaim, allowFinancial, + allowMerge, showEligibilityColumns, onNewClaim, onSelectPatient, @@ -110,6 +114,7 @@ export function PatientTable({ const [isViewPatientOpen, setIsViewPatientOpen] = useState(false); const [isDeletePatientOpen, setIsDeletePatientOpen] = useState(false); const [isFinancialsOpen, setIsFinancialsOpen] = useState(false); + const [isMergeOpen, setIsMergeOpen] = useState(false); const [modalPatientId, setModalPatientId] = useState(null); const [currentPage, setCurrentPage] = useState(1); @@ -975,6 +980,28 @@ export function PatientTable({ )}
+ {allowMerge && isAdmin && ( +
+ +
+ )} + { + setIsMergeOpen(false); + handleClearSelection(); + }} + patients={patientsData?.patients ?? []} + /> { setSearchCriteria(criteria); diff --git a/apps/Frontend/src/pages/insurance-status-page.tsx b/apps/Frontend/src/pages/insurance-status-page.tsx index 91a429c0..725a694d 100755 --- a/apps/Frontend/src/pages/insurance-status-page.tsx +++ b/apps/Frontend/src/pages/insurance-status-page.tsx @@ -1512,6 +1512,7 @@ export default function InsuranceStatusPage() { allowDelete={true} allowCheckbox={true} allowEdit={true} + allowMerge={true} showEligibilityColumns={true} onSelectPatient={setSelectedPatient} /> diff --git a/apps/SeleniumService/selenium_CCA_preAuthCheckWorker.py b/apps/SeleniumService/selenium_CCA_preAuthCheckWorker.py index fd5c0d18..d201df32 100644 --- a/apps/SeleniumService/selenium_CCA_preAuthCheckWorker.py +++ b/apps/SeleniumService/selenium_CCA_preAuthCheckWorker.py @@ -1,11 +1,275 @@ +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. - Starts with the same steps as the eligibility check: login, step1, step2. - Reuses the eligibility check's persistent browser session (same Chrome profile and cookies). - Override a step here when the preauth check needs to do something different. + 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}"}