-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2759 lines (2223 loc) · 121 KB
/
app.py
File metadata and controls
2759 lines (2223 loc) · 121 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import time
import json
import logging
from datetime import datetime
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.service import Service
import requests
from pathlib import Path
import zipfile #Create a zip file for PDF and XML
import atexit
import tempfile
import threading
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('invoice_service.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
app = Flask(__name__)
CORS(app)
# Thread-safe tracking
DOWNLOADS_DIR = Path.home() / 'Downloads'
pending_cleanup = set()
cleanup_lock = threading.Lock()
def clean_downloads_dir():
"""Safely clean the entire Downloads directory"""
with cleanup_lock:
try:
logger.info(f"Starting cleanup of {DOWNLOADS_DIR}")
deleted_count = 0
for item in DOWNLOADS_DIR.iterdir():
try:
if item.is_file():
item.unlink()
deleted_count += 1
elif item.is_dir():
shutil.rmtree(item)
deleted_count += 1
except Exception as e:
logger.warning(f"Could not delete {item.name}: {str(e)}")
logger.info(f"Cleaned {deleted_count} items from Downloads")
return True
except Exception as e:
logger.error(f"Downloads cleanup failed: {str(e)}")
return False
def background_cleanup(file_path):
"""Guaranteed cleanup in a background thread"""
def cleanup():
time.sleep(2) # Extended safety delay
with cleanup_lock:
try:
if Path(file_path).exists():
Path(file_path).unlink()
logger.info(f"Deleted {file_path}")
pending_cleanup.discard(file_path)
clean_downloads_dir() # Full cleanup
except Exception as e:
logger.error(f"Cleanup error: {str(e)}")
threading.Thread(target=cleanup, daemon=True).start()
class ServiceStore:
#def __init__(self, download_directory="~/Downloads"):
def __init__(self, download_directory=DOWNLOADS_DIR):
self.download_directory = os.path.abspath(download_directory)
Path(self.download_directory).mkdir(parents=True, exist_ok=True)
self.driver = None
def setup_stealth_driver():
chrome_options = Options()
# Anti-detection options
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option('useAutomationExtension', False)
chrome_options.add_argument("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36")
# Performance options
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--disable-gpu")
# Block tracking
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-plugins")
# Railway provides chromedriver at this path
service = Service('/usr/bin/chromedriver')
driver = webdriver.Chrome(service=service, options=chrome_options)
#driver = webdriver.Chrome(options=chrome_options)
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
return driver
def setup_driver(self):
"""Setup Chrome WebDriver with download preferences"""
# chrome_options = Options()
# Configure download directory
prefs = {
"download.default_directory": self.download_directory,
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True,
"plugins.always_open_pdf_externally": True
}
self.driver = ServiceStore.setup_stealth_driver()
def close_driver(self):
"""Close the WebDriver"""
if self.driver:
self.driver.quit()
def debug_page_elements(self):
"""Debug method to find all buttons and their attributes"""
try:
buttons = self.driver.find_elements(By.TAG_NAME, "button")
inputs = self.driver.find_elements(By.XPATH, "//input[@type='submit' or @type='button']")
logger.info("=== DEBUG: Found buttons ===")
for i, button in enumerate(buttons):
text = button.text.strip()
button_id = button.get_attribute("id")
button_class = button.get_attribute("class")
button_type = button.get_attribute("type")
logger.info(f"Button {i}: text='{text}', id='{button_id}', class='{button_class}', type='{button_type}'")
logger.info("=== DEBUG: Found input buttons ===")
for i, input_elem in enumerate(inputs):
value = input_elem.get_attribute("value")
input_id = input_elem.get_attribute("id")
input_class = input_elem.get_attribute("class")
input_type = input_elem.get_attribute("type")
logger.info(f"Input {i}: value='{value}', id='{input_id}', class='{input_class}', type='{input_type}'")
except Exception as e:
logger.error(f"Debug error: {str(e)}")
def wait_for_element(self, by, value, timeout=10):
"""Wait for element to be present and return it"""
return WebDriverWait(self.driver, timeout).until(
EC.presence_of_element_located((by, value))
)
def wait_for_element_enabled(self, by, value, timeout=10):
"""Wait for element to be present and enabled"""
def element_is_enabled(driver):
try:
element = driver.find_element(by, value)
return element and element.is_enabled() and not element.get_attribute("disabled")
except:
return False
WebDriverWait(self.driver, timeout).until(element_is_enabled)
return self.driver.find_element(by, value)
def wait_for_clickable(self, by, value, timeout=10):
"""Wait for element to be clickable and return it"""
return WebDriverWait(self.driver, timeout).until(
EC.element_to_be_clickable((by, value))
)
def fill_form_guadalajara(self, data):
"""Main method to fill the form with provided data"""
try:
# Navigate to the website
logger.info("Navigating to the website...")
self.driver.get("https://www.movil.farmaciasguadalajara.com/facturacion/")
# Wait for page to load completely
time.sleep(3)
# Debug: Print page elements if in debug mode
if logger.level == logging.DEBUG:
self.debug_page_elements()
# Fill first section of the form
logger.info("Filling first section of the form...")
self._fill_first_section_guadalajara(data)
# Handle popup and click accept
#logger.info("Handling popup...")
self._handle_popup()
# Fill second section of the form
logger.info("Filling second section of the form...")
self._fill_second_section_guadalajara(data)
# Handle email if required
if data.get('send_email', False):
logger.info("Setting up email delivery...")
self._setup_email(data)
# Submit form
logger.info("Submitting form...")
return self._submit_form_guadalajara()
except Exception as e:
logger.error(f"Error filling form: {str(e)}")
# Debug: Print current page source snippet if error occurs
try:
page_title = self.driver.title
current_url = self.driver.current_url
logger.error(f"Current page: {page_title} - {current_url}")
# Print any error messages on the page
error_elements = self.driver.find_elements(By.CLASS_NAME, "error")
for error in error_elements:
if error.text.strip():
logger.error(f"Page error: {error.text}")
except Exception as debug_error:
logger.error(f"Debug error: {str(debug_error)}")
raise
def fill_form_ahorro(self, data):
"""Main method to fill the form with provided data"""
try:
# Navigate to the website
logger.info("Navigating to the website...")
self.driver.get("https://fahorro.masfacturaweb.com.mx/creafactura")
# Wait for page to load completely
time.sleep(3)
# Debug: Print page elements if in debug mode
if logger.level == logging.DEBUG:
self.debug_page_elements()
# Fill first section of the form
logger.info("Filling first section of the form...")
self._fill_first_section_ahorro(data)
# Handle popup and click accept
#logger.info("Handling popup...")
#self._handle_popup()
# Fill second section of the form
logger.info("Filling second section of the form...")
self._fill_second_section_ahorro(data)
# Handle email if required
#if data.get('send_email', False):
# logger.info("Setting up email delivery...")
# self._setup_email(data)
# Submit form
logger.info("Submitting form...")
return self._submit_form_ahorro()
except Exception as e:
logger.error(f"Error filling form: {str(e)}")
# Debug: Print current page source snippet if error occurs
try:
page_title = self.driver.title
current_url = self.driver.current_url
logger.error(f"Current page: {page_title} - {current_url}")
# Print any error messages on the page
error_elements = self.driver.find_elements(By.CLASS_NAME, "error")
for error in error_elements:
if error.text.strip():
logger.error(f"Page error: {error.text}")
except Exception as debug_error:
logger.error(f"Debug error: {str(debug_error)}")
raise
def fill_form_ahorro_descargar(self, data):
"""Main method to fill the form with provided data"""
try:
# Navigate to the website
logger.info("Navigating to the website...")
self.driver.get("https://fahorro.masfacturaweb.com.mx/creafactura")
# Wait for page to load completely
time.sleep(3)
# Debug: Print page elements if in debug mode
if logger.level == logging.DEBUG:
self.debug_page_elements()
# Fill first section of the form
logger.info("Filling first section of the form...")
self._fill_first_section_ahorro(data)
# Submit form
logger.info("Submitting form...")
return self._submit_form_ahorro_descargar()
except Exception as e:
logger.error(f"Error filling form: {str(e)}")
# Debug: Print current page source snippet if error occurs
try:
page_title = self.driver.title
current_url = self.driver.current_url
logger.error(f"Current page: {page_title} - {current_url}")
# Print any error messages on the page
error_elements = self.driver.find_elements(By.CLASS_NAME, "error")
for error in error_elements:
if error.text.strip():
logger.error(f"Page error: {error.text}")
except Exception as debug_error:
logger.error(f"Debug error: {str(debug_error)}")
raise
def _fill_first_section_guadalajara(self, data):
"""Fill the first section of the form"""
try:
# Fill Folio Factura
logger.info("Filling Folio Factura...")
folio_element = self.wait_for_element(By.ID, "folioFactura")
folio_element.clear()
folio_element.send_keys(data['folio_factura'])
time.sleep(0.5) # Brief pause for any JavaScript validation
# Fill Caja
logger.info("Filling Caja...")
caja_element = self.wait_for_element(By.ID, "caja")
caja_element.clear()
caja_element.send_keys(data['caja'])
time.sleep(0.5)
# Fill Fecha de Compra
logger.info("Filling Fecha de Compra...")
fecha_element = self.wait_for_element(By.ID, "fechaCompra")
fecha_element.clear()
fecha_element.send_keys(data['fecha_compra'])
time.sleep(0.5)
# Fill No. Ticket
logger.info("Filling No. Ticket...")
ticket_element = self.wait_for_element(By.ID, "ticket")
ticket_element.clear()
ticket_element.send_keys(data['ticket'])
# Trigger any change events that might enable the button
self.driver.execute_script("arguments[0].dispatchEvent(new Event('change', {bubbles: true}));", ticket_element)
self.driver.execute_script("arguments[0].dispatchEvent(new Event('input', {bubbles: true}));", ticket_element)
# Wait for any JavaScript to process
time.sleep(2)
# Now try to find and click "Validar Folio" button
logger.info("Looking for 'Validar Folio' button...")
self._click_validar_folio_button()
except Exception as e:
logger.error(f"Error in _fill_first_section_guadalajara: {str(e)}")
raise
def _fill_first_section_ahorro(self, data):
"""Fill the first section of the form"""
try:
# Fill Folio RFC
logger.info("Filling RFC...")
folio_element = self.wait_for_element(By.ID, "TextRfc")
folio_element.clear()
folio_element.send_keys(data['rfc'])
time.sleep(0.5) # Brief pause for any JavaScript validation
# Fill ITU
logger.info("Filling ITU...")
caja_element = self.wait_for_element(By.ID, "inputAddress")
caja_element.clear()
caja_element.send_keys(data['ticket'])
time.sleep(2)
# Now try to find and click "Continuar" button
logger.info("Looking for 'Continuar' button...")
#self._click_validar_folio_button()
button = self.wait_for_element_enabled(By.ID, 'btnContinuar')
button.send_keys(Keys.PAGE_DOWN);
button.click()
except Exception as e:
logger.error(f"Error in _fill_first_section: {str(e)}")
raise
def _click_validar_folio_button(self):
"""Click the Angular Material Validar Folio button with improved targeting"""
button_found = False
logger.info("Looking for Angular Material 'Validar Folio' button...")
# Wait for Angular to fully load and button to be ready
time.sleep(2)
# More precise selectors based on the actual HTML structure
targeted_selectors = [
# Most specific - target the exact button structure from your HTML
(By.XPATH, "//button[@mat-fab='' and @extended='' and @type='submit' and contains(@class, 'primary')]"),
# Target by the combination of classes that are always present
(By.XPATH, "//button[contains(@class, 'mdc-fab') and contains(@class, 'mat-mdc-fab') and contains(@class, 'mdc-fab--extended') and @type='submit']"),
# Target by the inner span with "Validar Folio" text
(By.XPATH, "//span[@class='mdc-button__label' and normalize-space(text())='Validar Folio']/parent::button"),
# Target by mat-accent class and submit type
(By.XPATH, "//button[contains(@class, 'mat-accent') and @type='submit' and contains(@class, 'mdc-fab--extended')]"),
# CSS selector approach
(By.CSS_SELECTOR, "button.mdc-fab.mat-mdc-fab.mdc-fab--extended[type='submit']"),
# Fallback - any submit button with primary class
(By.XPATH, "//button[@type='submit' and contains(@class, 'primary')]"),
]
for by_method, selector in targeted_selectors:
try:
logger.info(f"Trying selector: {selector}")
# Wait for element to be present in DOM
element = WebDriverWait(self.driver, 15).until(
EC.presence_of_element_located((by_method, selector))
)
if element:
# Log element details for verification
element_text = element.text.strip()
element_classes = element.get_attribute('class')
element_type = element.get_attribute('type')
is_enabled = element.is_enabled()
is_displayed = element.is_displayed()
logger.info(f"Found element - Text: '{element_text}', Classes: '{element_classes}', Type: '{element_type}', Enabled: {is_enabled}, Displayed: {is_displayed}")
if not is_enabled:
logger.warning("Button found but not enabled. Waiting for it to become enabled...")
# Wait longer for button to become enabled after form validation
try:
WebDriverWait(self.driver, 20).until(
lambda driver: driver.find_element(by_method, selector).is_enabled()
)
logger.info("Button is now enabled")
except TimeoutException:
logger.error("Button never became enabled")
continue
# Scroll element into view smoothly
self.driver.execute_script(
"arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});"
"window.scrollBy(0, -100);", # Offset for any fixed headers
element
)
time.sleep(1)
# Wait for any animations to complete
time.sleep(2)
# Method 1: Try ActionChains click (best for Angular Material)
try:
from selenium.webdriver.common.action_chains import ActionChains
# Move to element and click
actions = ActionChains(self.driver)
actions.move_to_element(element).pause(0.5).click().perform()
logger.info("✓ Successfully clicked 'Validar Folio' button using ActionChains")
button_found = True
except Exception as action_error:
logger.warning(f"ActionChains click failed: {str(action_error)}")
# Method 2: Try clicking the inner span with the text
try:
inner_span = element.find_element(By.CLASS_NAME, "mdc-button__label")
inner_span.click()
logger.info("✓ Successfully clicked 'Validar Folio' button by clicking inner span")
button_found = True
except Exception as span_error:
logger.warning(f"Inner span click failed: {str(span_error)}")
# Method 3: JavaScript click with proper event dispatching for Angular
try:
# Dispatch both click and Angular-specific events
self.driver.execute_script("""
var element = arguments[0];
// Dispatch multiple events that Angular Material expects
var events = ['mousedown', 'mouseup', 'click'];
events.forEach(function(eventType) {
var event = new MouseEvent(eventType, {
bubbles: true,
cancelable: true,
view: window
});
element.dispatchEvent(event);
});
// Also trigger form submission if it's a submit button
if (element.type === 'submit') {
var form = element.closest('form');
if (form) {
var submitEvent = new Event('submit', {
bubbles: true,
cancelable: true
});
form.dispatchEvent(submitEvent);
}
}
""", element)
logger.info("✓ Successfully clicked 'Validar Folio' button using JavaScript with events")
button_found = True
except Exception as js_error:
logger.warning(f"JavaScript click failed: {str(js_error)}")
# Method 4: Last resort - direct JavaScript click
try:
self.driver.execute_script("arguments[0].click();", element)
logger.info("✓ Successfully clicked 'Validar Folio' button using direct JavaScript click")
button_found = True
except Exception as direct_js_error:
logger.error(f"All click methods failed: {str(direct_js_error)}")
continue
if button_found:
# Wait for any loading, validation, or state changes
#logger.info("Waiting for validation to complete...")
#time.sleep(5) # Increased wait time for server response
# Check for any immediate validation feedback
#self._check_validation_feedback()
break
except TimeoutException:
logger.debug(f"Selector timed out: {selector}")
continue
except Exception as e:
logger.debug(f"Selector failed {selector}: {str(e)}")
continue
if not button_found:
logger.error("❌ Could not find or click the Angular Material 'Validar Folio' button")
# Enhanced debug info
self._enhanced_debug_info()
raise Exception("Failed to click Validar Folio button")
return button_found
def _enhanced_debug_info(self):
"""Enhanced debug information for troubleshooting"""
try:
logger.info("=== ENHANCED DEBUG INFO ===")
# Check if page is still loading
ready_state = self.driver.execute_script("return document.readyState")
logger.info(f"Page ready state: {ready_state}")
# Check for Angular
angular_loaded = self.driver.execute_script("""
return typeof angular !== 'undefined' ||
typeof ng !== 'undefined' ||
window.getAllAngularTestabilities !== undefined ||
document.querySelector('[ng-version]') !== null;
""")
logger.info(f"Angular detected: {angular_loaded}")
# Find all submit buttons
submit_buttons = self.driver.find_elements(By.XPATH, "//button[@type='submit']")
logger.info(f"Found {len(submit_buttons)} submit buttons")
for i, btn in enumerate(submit_buttons):
try:
text = btn.text.strip()
classes = btn.get_attribute("class")
enabled = btn.is_enabled()
displayed = btn.is_displayed()
logger.info(f"Submit button {i}: text='{text}', enabled={enabled}, displayed={displayed}, classes='{classes}'")
except Exception as e:
logger.info(f"Submit button {i}: Error getting info - {str(e)}")
# Look for buttons containing "validar" or "folio"
validar_buttons = self.driver.find_elements(By.XPATH, "//button[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'validar') or contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'folio')]")
logger.info(f"Found {len(validar_buttons)} buttons with 'validar' or 'folio'")
# Check current URL and title
logger.info(f"Current URL: {self.driver.current_url}")
logger.info(f"Page title: {self.driver.title}")
# Check for any error messages
error_elements = self.driver.find_elements(By.XPATH, "//*[contains(@class, 'error') or contains(@class, 'alert') or contains(@class, 'warning')]")
for error in error_elements:
if error.is_displayed() and error.text.strip():
logger.warning(f"Page error/warning: {error.text.strip()}")
except Exception as e:
logger.error(f"Error in enhanced debug: {str(e)}")
def _wait_for_angular_ready(self):
"""Wait for Angular application to be fully loaded and ready"""
try:
logger.info("Waiting for Angular to be ready...")
WebDriverWait(self.driver, 30).until(
lambda driver: driver.execute_script("""
// Check if Angular is present and ready
if (typeof angular !== 'undefined') {
// AngularJS
var element = document.querySelector('[ng-app]') || document.body;
var scope = angular.element(element).scope();
return scope && !scope.$$phase;
}
// Angular 2+ (check for zone.js stability)
if (window.getAllAngularTestabilities) {
var testabilities = window.getAllAngularTestabilities();
return testabilities.every(function(testability) {
return testability.isStable();
});
}
// Fallback - check if page is loaded
return document.readyState === 'complete';
""")
)
logger.info("Angular appears to be ready")
return True
except TimeoutException:
logger.warning("Timeout waiting for Angular to be ready, proceeding anyway")
return False
except Exception as e:
logger.warning(f"Error checking Angular readiness: {str(e)}")
return False
def _check_validation_feedback(self):
"""Check for validation feedback after clicking Validar Folio"""
try:
# Look for common validation feedback elements
feedback_selectors = [
".mat-error",
".validation-message",
".error-message",
".alert",
".snack-bar",
".mat-snack-bar-container",
"[role='alert']",
".toast",
".notification"
]
for selector in feedback_selectors:
try:
elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
for element in elements:
if element.is_displayed() and element.text.strip():
feedback_text = element.text.strip()
logger.info(f"Validation feedback: {feedback_text}")
# Check if it's an error
if any(word in feedback_text.lower() for word in ['error', 'invalid', 'incorrect', 'failed']):
logger.error(f"Validation error detected: {feedback_text}")
raise Exception(f"Form validation failed: {feedback_text}")
else:
logger.info(f"Validation feedback (likely success): {feedback_text}")
except Exception as e:
continue
# Also check if the politicas button is now enabled (good sign)
try:
politicas_button = self.driver.find_element(By.ID, "politicasPr-input")
if politicas_button.is_enabled():
logger.info("✓ Politicas button is now enabled - validation likely successful")
else:
logger.warning("⚠ Politicas button is still disabled - validation may have failed")
except:
logger.debug("Could not check politicas button status")
except Exception as e:
logger.debug(f"Error checking validation feedback: {str(e)}")
def _print_all_buttons_debug(self):
"""Print all buttons and inputs for debugging purposes"""
try:
logger.info("=== DEBUG: All buttons and inputs on page ===")
# Find all buttons
buttons = self.driver.find_elements(By.TAG_NAME, "button")
for i, btn in enumerate(buttons):
text = btn.text.strip()
btn_id = btn.get_attribute("id")
btn_class = btn.get_attribute("class")
onclick = btn.get_attribute("onclick")
disabled = btn.get_attribute("disabled")
logger.info(f"Button {i}: text='{text}', id='{btn_id}', class='{btn_class}', onclick='{onclick}', disabled='{disabled}'")
# Find all input buttons
inputs = self.driver.find_elements(By.XPATH, "//input[@type='submit' or @type='button']")
for i, inp in enumerate(inputs):
value = inp.get_attribute("value")
inp_id = inp.get_attribute("id")
inp_class = inp.get_attribute("class")
onclick = inp.get_attribute("onclick")
disabled = inp.get_attribute("disabled")
logger.info(f"Input {i}: value='{value}', id='{inp_id}', class='{inp_class}', onclick='{onclick}', disabled='{disabled}'")
except Exception as e:
logger.error(f"Error in debug print: {str(e)}")
def _handle_popup(self):
"""Click the politicas button and handle the popup"""
try:
# First, make sure the validar folio step was successful
# Look for any validation messages or enabled fields
self._wait_for_validation_success()
# Click the politicas button
#logger.info("Looking for politicas button...")
#politicas_button = self.wait_for_clickable(By.ID, "politicasPr-input", timeout=15)
# Scroll to button and click
#self.driver.execute_script("arguments[0].scrollIntoView(true);", politicas_button)
#time.sleep(0.5)
#politicas_button.click()
#logger.info("Politicas button clicked")
# Wait for popup and click confirm
logger.info("Waiting for popup to appear...")
try:
confirm_button = self.wait_for_clickable(
By.CLASS_NAME, "swal2-confirm", timeout=15
)
confirm_button.click()
logger.info("Popup confirmed successfully")
# Wait for popup to disappear and form to be enabled
time.sleep(10)
except TimeoutException:
logger.error("Popup confirm button not found within timeout")
# Try alternative selectors for the confirm button
alt_selectors = [
"swal2-styled",
"swal2-default-outline",
"btn-confirm",
"btn-ok"
]
for selector in alt_selectors:
try:
confirm_button = self.wait_for_clickable(By.CLASS_NAME, selector, timeout=5)
confirm_button.click()
logger.info(f"Popup confirmed with alternative selector: {selector}")
time.sleep(3)
break
except:
continue
else:
raise TimeoutException("Could not find popup confirm button")
except Exception as e:
logger.error(f"Error in _handle_popup: {str(e)}")
raise
def _wait_for_validation_success(self):
"""Wait for validation to complete successfully"""
try:
# Wait a bit for any validation to process
time.sleep(2)
# Check for validation error messages
error_selectors = [
".error",
".alert-danger",
".validation-error",
".text-danger",
"[class*='error']"
]
for selector in error_selectors:
try:
error_elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
for error in error_elements:
error_text = error.text.strip()
if error_text and error.is_displayed():
logger.warning(f"Validation error found: {error_text}")
raise Exception(f"Form validation failed: {error_text}")
except:
continue
# Check if politicas button is now enabled (sign of successful validation)
try:
politicas_button = self.driver.find_element(By.ID, "politicasPr-input")
if politicas_button.get_attribute("disabled"):
logger.warning("Politicas button is still disabled - validation may have failed")
else:
logger.info("Politicas button is enabled - validation appears successful")
except:
logger.warning("Could not check politicas button status")
except Exception as e:
logger.warning(f"Error checking validation status: {str(e)}")
# Continue anyway
def _fill_second_section_guadalajara(self, data):
"""Fill the second section of the form after popup is handled - Simple version"""
try:
# Wait a bit for the form to be fully enabled
time.sleep(2)
# Fill RFC
logger.info("Filling RFC...")
rfc_element = self.wait_for_element(By.ID, "rfc")
self._simple_clear_and_fill(rfc_element, data['rfc'])
# Fill Código Postal
logger.info("Filling Código Postal...")
codigo_postal_element = self.wait_for_element(By.ID, "codigoPostal")
self._simple_clear_and_fill(codigo_postal_element, data['codigo_postal'])
# Fill Razón Social (the problematfield)
logger.info("Filling Razón Social...")
razon_social_element = self.wait_for_element(By.ID, "razonSocial")
self._simple_clear_and_fill(razon_social_element, data['razon_social'])
# Select Régimen Fiscal
logger.info("Selecting Régimen Fiscal...")
regimen_fiscal_select = Select(self.wait_for_element(By.ID, "regimenFiscal"))
regimen_fiscal_select.select_by_value(data['regimen_fiscal'])
time.sleep(0.5)
# Select Uso de CFDI
logger.info("Selecting Uso de CFDI...")
uso_cfdi_select = Select(self.wait_for_element(By.ID, "usoCfdi"))
uso_cfdi_select.select_by_value(data['uso_cfdi'])
time.sleep(0.5)
logger.info("Second section filled successfully")
except Exception as e:
logger.error(f"Error in _fill_second_section_guadalajara: {str(e)}")
raise
def _fill_second_section_ahorro(self, data):
"""Fill the second section of the form after popup is handled - Simple version"""
try:
# Wait a bit for the form to be fully enabled
time.sleep(2)
# Fill Email
logger.info("Filling Email...")
rfc_element = self.wait_for_element(By.ID, "ConfirmarCorreo")
self._simple_clear_and_fill(rfc_element, data['email'])
# Select Régimen Fiscal
logger.info("Selecting Régimen Fiscal...")
regimen_fiscal_select = Select(self.wait_for_element(By.ID, "inputRF"))
regimen_fiscal_select.select_by_value(data['regimen_fiscal'])
time.sleep(0.5)
# Select Uso de CFDI
logger.info("Selecting Uso de CFDI...")
uso_cfdi_select = Select(self.wait_for_element(By.ID, "inputState"))
uso_cfdi_select.select_by_value(data['uso_cfdi'])
time.sleep(0.5)
logger.info("Second section filled successfully")
except Exception as e:
logger.error(f"Error in _fill_second_section_ahorro: {str(e)}")
raise
def _simple_clear_and_fill(self, element, value):
"""Simple method to clear and fill without duplication"""
try:
logger.info(f"Clearing and filling field with: '{value}'")
# Method 1: Standard clear
element.clear()
time.sleep(0.1)
# Method 2: Select all and delete (cross-platform)
try:
element.send_keys(Keys.CONTROL + "a") # Ctrl+A on Windows/Linux
element.send_keys(Keys.DELETE)
except:
try:
element.send_keys(Keys.COMMAND + "a") # Cmd+A on Mac
element.send_keys(Keys.DELETE)
except:
pass # If both fail, continue with other methods
time.sleep(0.1)
# Method 3: JavaScript clear (most reliable)
self.driver.execute_script("arguments[0].value = '';", element)
self.driver.execute_script("arguments[0].setAttribute('value', '');", element)
time.sleep(0.1)
# Verify field is empty
current_value = element.get_attribute('value')
if current_value:
logger.warning(f"Field still contains '{current_value}' after clearing attempts")
# Force clear with focus and selection
element.click()
self.driver.execute_script("""
arguments[0].focus();
arguments[0].select();
arguments[0].value = '';
""", element)
# Now fill with the value
element.send_keys(value)
time.sleep(0.2)
# Verify the value and check for duplication
final_value = element.get_attribute('value')
logger.info(f"Field value after filling: '{final_value}'")
if final_value != value:
if value in final_value and len(final_value) > len(value):
logger.warning(f"Duplication detected! Expected: '{value}', Got: '{final_value}'")
# Fix duplication by setting value directly
self.driver.execute_script("arguments[0].value = arguments[1];", element, value)
logger.info("Duplication fixed with JavaScript")
else:
logger.warning(f"Unexpected value. Expected: '{value}', Got: '{final_value}'")
# Trigger Angular change events
self.driver.execute_script("""
var element = arguments[0];
var events = ['input', 'change', 'blur'];
events.forEach(function(eventType) {
var event = new Event(eventType, {bubbles: true});
element.dispatchEvent(event);
});
""", element)
logger.info(f"Successfully filled field with: '{value}'")
except Exception as e:
logger.error(f"Error in _simple_clear_and_fill: {str(e)}")
raise
def _safe_clear_and_fill(self, element, value):
"""Safely clear and fill an input field to prevent duplication"""
try:
logger.info(f"Filling field with value: '{value}'")
# Method 1: Multiple clearing attempts
for attempt in range(3):
# Clear the field multiple ways
element.clear()
# Select all and delete (works better with some Angular inputs)
element.send_keys(Keys.CTRL + "a")
element.send_keys(Keys.DELETE)
# Check if field is actually empty
current_value = element.get_attribute('value')
if not current_value:
break
logger.warning(f"Field still contains '{current_value}' after clearing attempt {attempt + 1}")
time.sleep(0.2)
# Verify field is empty before filling
final_value = element.get_attribute('value')
if final_value:
logger.warning(f"Field not completely cleared, contains: '{final_value}'")
# Force clear with JavaScript