sonuprasad23 commited on
Commit
2d2ac3e
·
1 Parent(s): b48d5cc

Updated Logic for Refund

Browse files
Files changed (2) hide show
  1. server.py +109 -22
  2. worker.py +72 -24
server.py CHANGED
@@ -31,12 +31,63 @@ bot_instance = None
31
  session_data = {}
32
 
33
  class GmailApiService:
34
- # This class remains unchanged
35
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  class GoogleDriveService:
38
- # This class remains unchanged
39
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
  email_service = GmailApiService()
42
  drive_service = GoogleDriveService()
@@ -66,13 +117,50 @@ def run_automation_process(session_id):
66
  if session_id in session_data: del session_data[session_id]
67
 
68
  def generate_and_send_reports(session_id, results, is_crash_report=False, is_terminated=False):
69
- # This function remains unchanged
70
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
  @app.route('/')
73
  def status_page():
74
- # This function remains unchanged
75
- pass
76
 
77
  def extract_patient_name(raw_name):
78
  if not isinstance(raw_name, str): return ""
@@ -83,18 +171,7 @@ def extract_patient_name(raw_name):
83
  def handle_file_processing_and_init():
84
  session_id = 'user_session'
85
  try:
86
- # --- Definitive Fix: Get all data from FormData ---
87
- emails = request.form.getlist('emails[]')
88
- filename = request.form.get('filename')
89
- mode = request.form.get('mode')
90
- start_date = request.form.get('start_date')
91
- end_date = request.form.get('end_date')
92
-
93
- session_data[session_id] = {
94
- 'emails': emails, 'filename': filename, 'mode': mode,
95
- 'start_date': start_date, 'end_date': end_date
96
- }
97
-
98
  if 'app_data' not in request.files or 'quantum_data' not in request.files:
99
  return jsonify({"error": "Both files are required."}), 400
100
 
@@ -112,8 +189,10 @@ def handle_file_processing_and_init():
112
  master_df = df_quantum.copy()
113
  master_df['Status'] = ''
114
 
115
- session_data[session_id]['patient_data_for_report'] = master_df
116
- session_data[session_id]['patient_data'] = master_df.to_dict('records')
 
 
117
 
118
  socketio.emit('data_processed')
119
  return jsonify({"message": "Data processed successfully."})
@@ -126,6 +205,14 @@ def handle_connect():
126
  print(f'Frontend connected.')
127
  emit('email_list', {'emails': get_email_list()})
128
 
 
 
 
 
 
 
 
 
129
  @socketio.on('start_login')
130
  def handle_login(credentials):
131
  global bot_instance
 
31
  session_data = {}
32
 
33
  class GmailApiService:
34
+ def __init__(self):
35
+ self.sender_email = os.getenv('EMAIL_SENDER'); self.service = None
36
+ try:
37
+ from google.oauth2 import service_account; from googleapiclient.discovery import build
38
+ base64_creds = os.getenv('GDRIVE_SA_KEY_BASE64')
39
+ if not base64_creds: print("[Server Log] WARNING: GDRIVE_SA_KEY_BASE64 not found."); return
40
+ creds_json = base64.b64decode(base64_creds).decode('utf-8'); creds_dict = json.loads(creds_json)
41
+ credentials = service_account.Credentials.from_service_account_info(creds_dict, scopes=['https://www.googleapis.com/auth/gmail.send'])
42
+ if self.sender_email: credentials = credentials.with_subject(self.sender_email)
43
+ self.service = build('gmail', 'v1', credentials=credentials)
44
+ print("[Server Log] Gmail API Service initialized successfully")
45
+ except Exception as e: print(f"[Server Log] Gmail API Error: {e}")
46
+
47
+ def create_professional_email_template(self, subject, status_text, stats, custom_name, process_type):
48
+ status_color = "#28a745" if "completed" in status_text else "#ffc107" if "terminated" in status_text else "#dc3545"
49
+ current_date = datetime.now().strftime("%B %d, %Y at %I:%M %p")
50
+ html_template = f"""<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{subject}</title><style> * {{ margin: 0; padding: 0; box-sizing: border-box; }} body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #2c2c2c; background-color: #f8f8f8; }} .email-container {{ max-width: 700px; margin: 20px auto; background-color: #ffffff; box-shadow: 0 8px 32px rgba(139, 0, 0, 0.15); border-radius: 12px; overflow: hidden; }} .header {{ background: linear-gradient(135deg, #8A0303 0%, #4c00ff 100%); color: white; padding: 40px 30px; text-align: center; }} .header h1 {{ font-size: 32px; font-weight: 700; margin-bottom: 8px; text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3); }} .header p {{ font-size: 18px; opacity: 0.95; font-weight: 300; letter-spacing: 1px; }} .status-banner {{ background: {status_color}; color: white; text-align: center; padding: 18px; font-size: 16px; font-weight: 600; text-transform: uppercase; letter-spacing: 1.5px; }} .content {{ padding: 40px 30px; }} .report-info {{ background: #fdfdff; border-left: 6px solid #4c00ff; padding: 25px; margin-bottom: 35px; border-radius: 8px; box-shadow: 0 4px 12px rgba(76, 0, 255, 0.1); }} .info-grid {{ display: grid; grid-template-columns: 1fr 1fr; gap: 15px 25px; }} .info-item {{ display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid #f0f0f0; }} .stats-grid {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 20px; margin: 35px 0; }} .stat-card {{ background: #f8f9fa; border: 1px solid #e0e0e0; border-radius: 12px; padding: 25px 15px; text-align: center; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05); }} .stat-number {{ font-size: 36px; font-weight: 700; color: #4c00ff; margin-bottom: 10px; }} .attachments-section {{ background: #f8f5ff; border: 1px solid #e0e0e0; border-radius: 12px; padding: 25px; margin: 35px 0; }} .footer {{ background: #2c2c2c; color: white; padding: 35px 30px; text-align: center; }} h3 {{ color: #8A0303; margin-bottom: 20px; font-size: 20px; font-weight: 600; }} </style></head><body> <div class="email-container"> <div class="header"><h1>Hillside's Quantum Automation</h1><p>Patient Processing Report</p></div> <div class="status-banner">Process {status_text}</div> <div class="content"> <div class="report-info"> <h3>Report Summary</h3> <div class="info-grid"> <div class="info-item"><span><b>Report Name</b></span><span>{custom_name}</span></div> <div class="info-item"><span><b>Process Type</b></span><span>{process_type}</span></div> <div class="info-item"><span><b>Generated</b></span><span>{current_date}</span></div> <div class="info-item"><span><b>Status</b></span><span style="font-weight: bold; color: {status_color};">{status_text}</span></div> </div> </div> <h3>Processing Results</h3> <div class="stats-grid"> <div class="stat-card"><div class="stat-number">{stats['total']}</div><div>Total in File</div></div> <div class="stat-card"><div class="stat-number">{stats['processed']}</div><div>Attempted</div></div> <div class="stat-card"><div class="stat-number">{stats['successful']}</div><div>Done</div></div> <div class="stat-card"><div class="stat-number">{stats['bad']}</div><div>Bad State</div></div> <div class="stat-card"><div class="stat-number">{stats['skipped']}</div><div>Skipped</div></div> </div> <div class="attachments-section"> <h3>Attached Reports</h3> <p style="margin-bottom: 1rem;">The following files are attached and have been uploaded to Google Drive:</p> <ul style="list-style-position: inside; padding-left: 0;"> <li><b>{custom_name}_Full.csv:</b> The complete report with the final status for every patient.</li> <li><b>{custom_name}_Bad.csv:</b> A filtered list of patients that resulted in a "Bad" state.</li> <li><b>{custom_name}_Skipped.csv:</b> A filtered list of patients that were skipped.</li> </ul> </div> </div> <div class="footer"><h4>Hillside Automation</h4><p>This is an automated report. Please do not reply.</p></div> </div> </body></html>"""
51
+ return html_template
52
+
53
+ def send_report(self, recipients, subject, body, attachments=None):
54
+ if not self.service or not recipients: return False
55
+ try:
56
+ from googleapiclient.errors import HttpError
57
+ message = MIMEMultipart(); message['From'] = self.sender_email; message['To'] = ', '.join(recipients); message['Subject'] = subject
58
+ message.attach(MIMEText(body, 'html'))
59
+ if attachments:
60
+ for filename, content in attachments.items():
61
+ part = MIMEBase('application', 'octet-stream'); part.set_payload(content.encode('utf-8'))
62
+ encoders.encode_base64(part); part.add_header('Content-Disposition', f'attachment; filename="{filename}"')
63
+ message.attach(part)
64
+ raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode('utf-8')
65
+ sent_message = self.service.users().messages().send(userId='me', body={'raw': raw_message}).execute()
66
+ print(f"[Server Log] Email sent successfully! Message ID: {sent_message['id']}"); return True
67
+ except Exception as e: print(f"[Server Log] Failed to send email: {e}"); return False
68
 
69
  class GoogleDriveService:
70
+ def __init__(self):
71
+ self.creds = None; self.service = None; self.folder_id = os.getenv('GOOGLE_DRIVE_FOLDER_ID')
72
+ try:
73
+ from google.oauth2 import service_account; from googleapiclient.discovery import build
74
+ base64_creds = os.getenv('GDRIVE_SA_KEY_BASE64')
75
+ if not base64_creds or not self.folder_id: raise ValueError("Google Drive secrets not found.")
76
+ creds_json = base64.b64decode(base64_creds).decode('utf-8'); creds_dict = json.loads(creds_json)
77
+ self.creds = service_account.Credentials.from_service_account_info(creds_dict, scopes=['https://www.googleapis.com/auth/drive'])
78
+ self.service = build('drive', 'v3', credentials=self.creds)
79
+ print("[Server Log] Google Drive Service initialized successfully.")
80
+ except Exception as e: print(f"[Server Log] G-Drive ERROR: Could not initialize service: {e}")
81
+
82
+ def upload_file(self, filename, file_content):
83
+ if not self.service: return False
84
+ try:
85
+ from googleapiclient.http import MediaIoBaseUpload
86
+ file_metadata = {'name': filename, 'parents': [self.folder_id]}
87
+ media = MediaIoBaseUpload(io.BytesIO(file_content.encode('utf-8')), mimetype='text/csv', resumable=True)
88
+ self.service.files().create(body=file_metadata, media_body=media, fields='id').execute()
89
+ print(f"[Server Log] File '{filename}' uploaded to Google Drive."); return True
90
+ except Exception as e: print(f"[Server Log] G-Drive ERROR: File upload failed: {e}"); return False
91
 
92
  email_service = GmailApiService()
93
  drive_service = GoogleDriveService()
 
117
  if session_id in session_data: del session_data[session_id]
118
 
119
  def generate_and_send_reports(session_id, results, is_crash_report=False, is_terminated=False):
120
+ data = session_data.get(session_id, {});
121
+ if not data: print("[Server Log] Session data not found for reporting."); return
122
+
123
+ full_df = pd.DataFrame(data.get('patient_data_for_report'))
124
+ if results:
125
+ result_df = pd.DataFrame(results).set_index('Name')
126
+ full_df.set_index('Name', inplace=True)
127
+ full_df.update(result_df); full_df.reset_index(inplace=True)
128
+
129
+ full_df['Status'] = full_df['Status'].fillna('Not Processed')
130
+
131
+ final_report_df = full_df[['Name', 'PRN', 'Status']]
132
+ bad_df = final_report_df[final_report_df['Status'] == 'Bad']
133
+ skipped_df = final_report_df[final_report_df['Status'] == 'Skipped - No PRN']
134
+
135
+ timestamp = datetime.now().strftime("%d_%b_%Y"); custom_name = data.get('filename') or timestamp
136
+ full_report_name = f"{custom_name}_Full.csv"; bad_report_name = f"{custom_name}_Bad.csv"; skipped_report_name = f"{custom_name}_Skipped.csv"
137
+ full_report_content = final_report_df.to_csv(index=False)
138
+ drive_service.upload_file(full_report_name, full_report_content)
139
+
140
+ attachments = {
141
+ full_report_name: full_report_content,
142
+ bad_report_name: bad_df.to_csv(index=False),
143
+ skipped_report_name: skipped_df.to_csv(index=False)
144
+ }
145
+ status_text = "Terminated by User" if is_terminated else "Crashed" if is_crash_report else "Completed Successfully"
146
+
147
+ stats = {
148
+ 'total': len(full_df), 'processed': len(results),
149
+ 'successful': len(full_df[full_df['Status'] == 'Done']),
150
+ 'bad': len(bad_df), 'skipped': len(skipped_df)
151
+ }
152
+ process_type_str = data.get('mode', 'Unknown').title()
153
+ subject = f"{process_type_str} Automation Report [{status_text.upper()}]: {custom_name}"
154
+
155
+ professional_body = email_service.create_professional_email_template(subject, status_text, stats, custom_name, process_type_str)
156
+
157
+ email_service.send_report(data.get('emails'), subject, professional_body, attachments)
158
+ socketio.emit('process_complete', {'message': f'Process {status_text}. Report sent.'})
159
 
160
  @app.route('/')
161
  def status_page():
162
+ APP_STATUS_HTML = """<!DOCTYPE html><html lang="en"><head><title>API Status</title><style>body{font-family:sans-serif;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;background:#f0f2f5;}.status-box{text-align:center;padding:40px 60px;background:white;border-radius:12px;box-shadow:0 8px 30px rgba(0,0,0,0.1);}h1{font-size:24px;color:#333;margin-bottom:10px;} .indicator{font-size:18px;font-weight:600;padding:8px 16px;border-radius:20px;}.active{color:#28a745;background-color:#e9f7ea;}</style></head><body><div class="status-box"><h1>Hillside Automation API</h1><div class="indicator active">● Active</div></div></body></html>"""
163
+ return Response(APP_STATUS_HTML)
164
 
165
  def extract_patient_name(raw_name):
166
  if not isinstance(raw_name, str): return ""
 
171
  def handle_file_processing_and_init():
172
  session_id = 'user_session'
173
  try:
174
+ data = session_data.get(session_id, {})
 
 
 
 
 
 
 
 
 
 
 
175
  if 'app_data' not in request.files or 'quantum_data' not in request.files:
176
  return jsonify({"error": "Both files are required."}), 400
177
 
 
189
  master_df = df_quantum.copy()
190
  master_df['Status'] = ''
191
 
192
+ data['patient_data_for_report'] = master_df
193
+ data['patient_data'] = master_df.to_dict('records')
194
+ data['start_date'] = request.form.get('start_date')
195
+ data['end_date'] = request.form.get('end_date')
196
 
197
  socketio.emit('data_processed')
198
  return jsonify({"message": "Data processed successfully."})
 
205
  print(f'Frontend connected.')
206
  emit('email_list', {'emails': get_email_list()})
207
 
208
+ @socketio.on('initialize_session')
209
+ def handle_init(data):
210
+ session_id = 'user_session'
211
+ session_data[session_id] = {
212
+ 'emails': data['emails'], 'filename': data['filename'], 'mode': data.get('mode'),
213
+ 'start_date': data.get('start_date'), 'end_date': data.get('end_date')
214
+ }
215
+
216
  @socketio.on('start_login')
217
  def handle_login(credentials):
218
  global bot_instance
worker.py CHANGED
@@ -121,26 +121,48 @@ class QuantumBot:
121
  time.sleep(1)
122
  self._select_date_in_calendar(end_date)
123
  self.driver.find_element(By.TAG_NAME, "body").click()
124
- self.micro_status("Date range set. Waiting up to 1 minute for data to filter...")
125
- WebDriverWait(self.driver, 60).until(EC.invisibility_of_element_located((By.XPATH, "//div[contains(@class, 'is-loading')]")))
126
- self.micro_status("Data has finished loading.")
127
  return True
128
  except Exception as e:
129
  self.micro_status(f"Error setting date range: {e}"); return False
130
 
131
  def process_void_list(self, patient_data):
132
- # This method remains unchanged as it is stable
133
- pass
134
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  def process_refund_list(self, patient_data, start_date, end_date):
136
  results = []
 
 
 
 
 
 
 
 
137
  for index, record in enumerate(patient_data):
138
  if self.termination_event.is_set(): print("[Bot Log] Termination detected."); break
139
  patient_name = record['Name']; patient_prn = record.get('PRN', '')
140
  status = 'Skipped - No PRN'
141
  if patient_prn and str(patient_prn).strip():
142
  self.micro_status(f"Processing REFUND for '{patient_name}' ({index + 1}/{len(patient_data)})...")
143
- status = self._process_single_refund(patient_name, patient_prn, start_date, end_date)
144
  else:
145
  self.micro_status(f"Skipping '{patient_name}' (No PRN).")
146
  time.sleep(0.5)
@@ -150,42 +172,37 @@ class QuantumBot:
150
  self.socketio.emit('stats_update', {'processed': index + 1, 'remaining': len(patient_data) - (index + 1), 'status': status})
151
  return results
152
 
153
- def _process_single_refund(self, patient_name, patient_prn):
154
  try:
155
- self.micro_status(f"Navigating to Refund page for '{patient_name}'")
156
- self.driver.get("https://gateway.quantumepay.com/credit-card/refund")
157
-
158
- # Date range must be set for each patient in a robust loop
159
- if not self._set_date_range(start_date, end_date):
160
- raise Exception("Date range could not be set.")
161
-
162
  search_successful = False
163
  for attempt in range(15):
164
  try:
165
  self.micro_status(f"Searching... (Attempt {attempt + 1})")
 
166
  search_box = WebDriverWait(self.driver, 2).until(EC.element_to_be_clickable((By.XPATH, "//input[@placeholder='Search']")))
167
  search_box.click(); time.sleep(0.5); search_box.clear(); time.sleep(0.5)
168
  search_box.send_keys(patient_name); search_successful = True; break
169
  except Exception: time.sleep(1)
170
- if not search_successful: raise Exception("Failed to search for patient in Refund.")
171
  time.sleep(3)
172
-
173
  self.micro_status("Opening transaction details...")
174
- WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, f"//tr[contains(., \"{patient_name}\")]//button"))).click()
175
- self.micro_status("Initiating Refund...")
176
- WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button/span[normalize-space()='Refund']"))).click()
177
-
 
178
  try:
179
  self.micro_status("Verifying success and saving...")
180
- # Assuming the fields are the same as the Void workflow
181
  company_input = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.NAME, "company_name")))
182
  company_input.click(); company_input.send_keys(Keys.CONTROL + "a"); company_input.send_keys(Keys.BACK_SPACE)
183
  company_input.send_keys(patient_name)
184
-
185
  contact_input = WebDriverWait(self.driver, 5).until(EC.element_to_be_clickable((By.NAME, "company_contact")))
 
186
  contact_input.click(); contact_input.send_keys(Keys.CONTROL + "a"); contact_input.send_keys(Keys.BACK_SPACE)
 
187
  contact_input.send_keys(str(patient_prn))
188
-
189
  WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button/span[normalize-space()='Save Changes']"))).click()
190
  WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button[.//span[normalize-space()='Confirm']]"))).click()
191
  time.sleep(5); return 'Done'
@@ -193,6 +210,37 @@ class QuantumBot:
193
  self.micro_status(f"'{patient_name}' is in a bad state, cancelling.")
194
  WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button[.//span[normalize-space()='Cancel']]"))).click()
195
  return 'Bad'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  except Exception as e:
197
  print(f"An error occurred during REFUND for {patient_name}: {e}"); return 'Error'
198
 
 
121
  time.sleep(1)
122
  self._select_date_in_calendar(end_date)
123
  self.driver.find_element(By.TAG_NAME, "body").click()
124
+ self.micro_status("Date range set. Waiting dynamically for up to 1 minute for data to filter...")
125
+ WebDriverWait(self.driver, 60).until_not(EC.presence_of_element_located((By.XPATH, "//*[contains(@class, 'is-loading')]")))
126
+ time.sleep(2) # Extra buffer
127
  return True
128
  except Exception as e:
129
  self.micro_status(f"Error setting date range: {e}"); return False
130
 
131
  def process_void_list(self, patient_data):
132
+ results = []
133
+ for index, record in enumerate(patient_data):
134
+ if self.termination_event.is_set(): print("[Bot Log] Termination detected."); break
135
+ patient_name = record['Name']; patient_prn = record.get('PRN', '')
136
+ status = 'Skipped - No PRN'
137
+ if patient_prn and str(patient_prn).strip():
138
+ self.micro_status(f"Processing VOID for '{patient_name}' ({index + 1}/{len(patient_data)})...")
139
+ status = self._process_single_void(patient_name, patient_prn)
140
+ else:
141
+ self.micro_status(f"Skipping '{patient_name}' (No PRN).")
142
+ time.sleep(0.5)
143
+ results.append({'Name': patient_name, 'PRN': patient_prn, 'Status': status})
144
+ with self.app.app_context():
145
+ self.socketio.emit('log_update', {'name': patient_name, 'prn': patient_prn, 'status': status})
146
+ self.socketio.emit('stats_update', {'processed': index + 1, 'remaining': len(patient_data) - (index + 1), 'status': status})
147
+ return results
148
+
149
  def process_refund_list(self, patient_data, start_date, end_date):
150
  results = []
151
+ # Set date range once at the beginning
152
+ self.driver.get("https://gateway.quantumepay.com/credit-card/refund")
153
+ if not self._set_date_range(start_date, end_date):
154
+ self.micro_status("FATAL: Could not set date range. Terminating process.")
155
+ for record in patient_data:
156
+ results.append({'Name': record['Name'], 'PRN': record.get('PRN',''), 'Status': 'Error'})
157
+ return results
158
+
159
  for index, record in enumerate(patient_data):
160
  if self.termination_event.is_set(): print("[Bot Log] Termination detected."); break
161
  patient_name = record['Name']; patient_prn = record.get('PRN', '')
162
  status = 'Skipped - No PRN'
163
  if patient_prn and str(patient_prn).strip():
164
  self.micro_status(f"Processing REFUND for '{patient_name}' ({index + 1}/{len(patient_data)})...")
165
+ status = self._process_single_refund(patient_name, patient_prn)
166
  else:
167
  self.micro_status(f"Skipping '{patient_name}' (No PRN).")
168
  time.sleep(0.5)
 
172
  self.socketio.emit('stats_update', {'processed': index + 1, 'remaining': len(patient_data) - (index + 1), 'status': status})
173
  return results
174
 
175
+ def _process_single_void(self, patient_name, patient_prn):
176
  try:
177
+ self.micro_status(f"Navigating to Void page for '{patient_name}'")
178
+ self.driver.get("https://gateway.quantumepay.com/credit-card/void")
 
 
 
 
 
179
  search_successful = False
180
  for attempt in range(15):
181
  try:
182
  self.micro_status(f"Searching... (Attempt {attempt + 1})")
183
+ WebDriverWait(self.driver, 2).until(EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'table-wrapper')]")))
184
  search_box = WebDriverWait(self.driver, 2).until(EC.element_to_be_clickable((By.XPATH, "//input[@placeholder='Search']")))
185
  search_box.click(); time.sleep(0.5); search_box.clear(); time.sleep(0.5)
186
  search_box.send_keys(patient_name); search_successful = True; break
187
  except Exception: time.sleep(1)
188
+ if not search_successful: raise Exception("Failed to search for patient.")
189
  time.sleep(3)
 
190
  self.micro_status("Opening transaction details...")
191
+ WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, f"//tr[contains(., \"{patient_name}\")]//button[@data-v-b6b33fa0]"))).click()
192
+ WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.LINK_TEXT, "Transaction Detail"))).click()
193
+ self.micro_status("Adding to Vault...")
194
+ WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button/span[normalize-space()='Add to Vault']"))).click()
195
+ WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='modal-footer']//button/span[normalize-space()='Confirm']"))).click()
196
  try:
197
  self.micro_status("Verifying success and saving...")
 
198
  company_input = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.NAME, "company_name")))
199
  company_input.click(); company_input.send_keys(Keys.CONTROL + "a"); company_input.send_keys(Keys.BACK_SPACE)
200
  company_input.send_keys(patient_name)
 
201
  contact_input = WebDriverWait(self.driver, 5).until(EC.element_to_be_clickable((By.NAME, "company_contact")))
202
+ self.micro_status("Clearing Contact Name field...")
203
  contact_input.click(); contact_input.send_keys(Keys.CONTROL + "a"); contact_input.send_keys(Keys.BACK_SPACE)
204
+ self.micro_status(f"Entering PRN: {patient_prn}...")
205
  contact_input.send_keys(str(patient_prn))
 
206
  WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button/span[normalize-space()='Save Changes']"))).click()
207
  WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button[.//span[normalize-space()='Confirm']]"))).click()
208
  time.sleep(5); return 'Done'
 
210
  self.micro_status(f"'{patient_name}' is in a bad state, cancelling.")
211
  WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button[.//span[normalize-space()='Cancel']]"))).click()
212
  return 'Bad'
213
+ except Exception as e:
214
+ print(f"An error occurred during VOID for {patient_name}: {e}"); return 'Error'
215
+
216
+ def _process_single_refund(self, patient_name, patient_prn):
217
+ # This is the new, robust Refund logic.
218
+ try:
219
+ # We are already on the correct page with the date range set
220
+ search_successful = False
221
+ for attempt in range(15):
222
+ try:
223
+ self.micro_status(f"Searching for '{patient_name}' in date range... (Attempt {attempt+1})")
224
+ search_box = WebDriverWait(self.driver, 2).until(EC.element_to_be_clickable((By.XPATH, "//input[@placeholder='Search']")))
225
+ search_box.click(); time.sleep(0.5); search_box.clear(); time.sleep(0.5)
226
+ search_box.send_keys(patient_name); search_successful = True; break
227
+ except Exception: time.sleep(1)
228
+ if not search_successful: raise Exception("Failed to search for patient in Refund.")
229
+ time.sleep(3)
230
+ self.micro_status("Opening transaction details...")
231
+ WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, f"//tr[contains(., \"{patient_name}\")]//button"))).click()
232
+ self.micro_status("Initiating Refund...")
233
+ WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button/span[normalize-space()='Refund']"))).click()
234
+ try:
235
+ self.micro_status("Verifying refund success...")
236
+ # We expect a confirmation modal or a success message.
237
+ # Here we will assume a final confirm button appears, similar to Void.
238
+ WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='modal-footer']//button/span[normalize-space()='Confirm']"))).click()
239
+ time.sleep(5); return 'Done'
240
+ except TimeoutException:
241
+ self.micro_status(f"'{patient_name}' is in a bad state for refund, cancelling.")
242
+ WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button[.//span[normalize-space()='Cancel']]"))).click()
243
+ return 'Bad'
244
  except Exception as e:
245
  print(f"An error occurred during REFUND for {patient_name}: {e}"); return 'Error'
246