-
Notifications
You must be signed in to change notification settings - Fork 1
/
napmodule.py
2969 lines (2249 loc) · 129 KB
/
napmodule.py
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 csv
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementNotInteractableException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
import time
import datetime
import re
from decimal import Decimal, InvalidOperation, DecimalException, ROUND_HALF_UP
from napcountrysearch import get_country
bad_request_errors_global=0
bad_request_errors_global_previous=0
slow_global=False
# Подпрограма за проверка дали даден елемент със зададено ID съществува.
# Подпрограмата чака time секунди да види дали този елемент ще се появи.
def check_if_element_with_ID_exists(driver, element_id, time=3):
try:
WebDriverWait(driver, time).until(EC.presence_of_element_located((By.ID, element_id)))
return True
except:
return False
# Подпрограма за проверка дали има <h1>Bad Request</h1>
def bad_request_is_appearing(driver):
global bad_request_errors_global
# Wait for up to 1 second for the "Bad Request" to appear
for _ in range(10):
try:
bad_request_h1 = driver.find_elements(By.XPATH,"//h1[contains(text(), 'Bad Request')")
except:
time.sleep(0.1) # Wait for 0.1 second before checking again
continue
if bad_request_h1:
bad_request_errors_global += 1
return True
time.sleep(0.1) # Wait for 0.1 second before checking again
# If the button is not found after 1 second, print a message and return False
else:
print("This is good - tag h1 with text Bad Request not found within 1 second.")
return False
# Подпрограма за проверка дали има диалог за избор на задължено лице
def dialog_selection_of_taxable_person_is_appearing(driver):
try:
WebDriverWait(driver, 1).until(EC.presence_of_element_located((By.XPATH, "//span[contains(@class, 'ag-cell-value')]")))
except: # catch any exceptions
pass
ag_cell_value_spans = driver.find_elements(By.XPATH, "//span[contains(@class, 'ag-cell-value')]")
if len(ag_cell_value_spans) > 0:
return True
else:
return False
# Подпрограма за проверка дали съобщението за добре дошли се вижда.
def welcome_message_is_appearing(driver):
# Wait for up to 1 second for the dialog and button to appear
for _ in range(10):
try:
close_button = driver.find_elements(By.XPATH,"//button[@id='skip']")
except:
time.sleep(0.1) # Wait for 0.1 second before checking again
continue
if close_button:
return True # Return True if the button exists
time.sleep(0.1) # Wait for 0.1 second before checking again
# If the button is not found after 1 second, print a message and return False
else:
print("Button (welcome message) not found within 1 second.")
return False
# Връща брой на ЕГН-та. Ако върне 0 броя значи в списъка няма нито едно ЕГН.
# Ако върне None значи няма изобщо списък.
# def .... / още не съм измислил как ще се казва.
# Проверява дали има списък с ЕГН-та и ако има само едно ЕГН в списъка го клика
# Ако има повече от едно ЕГН зацикля и чака потербителят да кликне за да избере ЕГН.
# При успешно кликане с изчезване на ЕГН-то връща True.
# А какво става при други обстоятелства не е много ясно, дано не се случват.
# Логиката не е много смислена, за пренаписване е.
# Но ако се ползва за потребители с права за едно ЕГН и се ползва само за избор на ЕГН-то
# с цел да се затвори диалога и да може да се продължи - върши работа.
# За потребители, които попълват декларация за физически лица с някакъв друг номер (не ЕГН)
# тази подпрограма няма да работи! Трябва да се види какво точно излиза като текст,
# за да се добави и търсене на друго име на идентификатор, примерно ЛНЧ, служебен номер (не знам как излиза).
# Трябва да има версия на автопилота, която да изчаква потребителят да се заеме с този диалог.
# Тази функция да се ползва само за версията автопилот "може би работи".
def check_and_click_egn_spans(driver):
while True:
try:
# wait for the element to be present, up to 5 seconds
WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.XPATH, "//span[contains(text(), 'ЕГН') and contains(@class, 'ag-cell-value')]")))
except Exception as e: # catch any exceptions
pass
#print(f"Error: {e}") # print the error message
#return False # exit the function
print("check_and_click_egn_spans debug")
egn_spans = driver.find_elements(By.XPATH, "//span[contains(text(), 'ЕГН') and contains(@class, 'ag-cell-value')]")
if len(egn_spans) == 1:
egn_span = egn_spans[0]
egn_span.click()
try:
WebDriverWait(driver, 10).until_not(EC.visibility_of(egn_span))
return True
except:
return True
elif len(egn_spans) > 0:
print("Error: Too many lines with 'ЕГН' are present. Please click the appropriate line.")
break
else:
print("Error: No lines with 'ЕГН' are present.")
return False
print("Waiting indefinitely for 'ЕГН' spans to disappear. Press Ctrl+C to interrupt.")
while True:
egn_spans = driver.find_elements(By.XPATH, "//span[contains(text(), 'ЕГН') and contains(@class, 'ag-cell-value')]")
if not egn_spans:
print("All 'ЕГН' lines have disappeared.")
break
def how_many_EGN_spans_appear(driver):
egn_count = 0
try:
egn_spans = WebDriverWait(driver, 5).until(EC.presence_of_all_elements_located((By.XPATH, "//span[contains(text(), 'ЕГН') and contains(@class, 'ag-cell-value')]")))
# Count the number of elements found
egn_count = len(egn_spans)
except TimeoutException:
print("Timed out waiting for ЕГН spans to appear.")
except Exception as e:
print(f"Error: {e}")
# Additional error handling if needed
return egn_count
def get_supplement_id(supplement_number):
"""
Returns the corresponding supplement_id based on the given supplement_number.
Args:
supplement_number: The supplement number (integer or Roman numeral).
Returns:
The corresponding supplement_id (string).
Raises:
ValueError: If the supplement_number is out of range (not an integer between 1 and 13, or not a valid Roman numeral between "III" and "V").
TypeError: If the supplement_number is not an integer or string.
"""
if isinstance(supplement_number, int):
if 1 <= supplement_number <= 13:
return f"part_{1159 + supplement_number}"
else:
raise ValueError(f"Integer supplement number {supplement_number} is out of range (must be between 1 and 13)")
elif isinstance(supplement_number, str):
if supplement_number.upper() in ["III", "IV", "V"]:
roman_to_int = {"III": 3, "IV": 4, "V": 5}
return f"part_{1154 + roman_to_int[supplement_number.upper()]}"
else:
raise ValueError(f"Roman numeral supplement number '{supplement_number}' is invalid (must be one of 'III', 'IV', or 'V')")
else:
raise TypeError("Invalid supplement number type: must be integer or string")
def go_to_supplement(driver, supplement_number):
try:
supplement_id = get_supplement_id(supplement_number)
print(f"Supplement number: {supplement_number}, Supplement ID: {supplement_id}")
except (ValueError, TypeError) as e:
print(f"Error: {e}")
return False
try:
link = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, f"//li[@id='{supplement_id}']/a"))
)
print("Element found! Sleeping for 1 second before clicking it..")
time.sleep(1)
# Scroll into view if needed
driver.execute_script("arguments[0].scrollIntoView(true);", link)
# Attempt to click using actions chain
actions = ActionChains(driver)
actions.move_to_element(link).click().perform()
print("Link clicked!")
if bad_request_is_appearing(driver):
print("WARNING: Bad Request message is appearing.")
time.sleep(2)
return True
except TimeoutException:
print("Timed out waiting for element to be clickable.")
return False
except Exception as e:
print("Error:", e)
return False
def click_submit_part_button(driver):
try:
confirm_button_xpath = "//form[@name='submitFrm']//input[@type='button' and contains(@onclick, 'SubmitPart')]"
time.sleep(0.5) # in case JS did not finished updating the yellow fields
# Click the confirm button
confirm_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, confirm_button_xpath))
)
confirm_button.click()
return True # Success
except NoSuchElementException:
print("Error: SubmitPart button not found.")
return False
def enable_supplement(driver, supplement_number):
if not 1 <= supplement_number <= 13:
raise SystemExit("Error: Supplement number is out of range.")
go_to_supplement(driver, "III")
checkbox_name = f"dec50_part3_issetapp{supplement_number}"
checkbox_xpath = f"//input[@name='{checkbox_name}']"
try:
# Check if the checkbox is already checked
checkbox = driver.find_element(By.XPATH, checkbox_xpath)
if checkbox.is_selected():
print(f"Error: Supplement {supplement_number} is already checked.")
return True # Already checked, return True
# Check the checkbox
checkbox.click()
# Click the SubmitPart button
if not click_submit_part_button(driver):
print("Error: Failed to click SubmitPart button.")
return False
if bad_request_is_appearing(driver):
print("WARNING: Bad Request message is appearing.")
time.sleep(2)
return True # Success
except NoSuchElementException:
print(f"Error: Checkbox for supplement {supplement_number} not found.")
return False
def check_if_row_exists(driver, row_id):
# Function to check if a row exists
try:
driver.find_element(By.ID, row_id)
return True
except NoSuchElementException:
return False
def check_if_row_full_owned(driver, row_id):
# Function to check if a row is already filled with non-zero data
try:
# Find the input fields in the row
count_input = driver.find_element(By.ID, f"{row_id}_count")
price_input = driver.find_element(By.ID, f"{row_id}_price")
price_in_currency_input = driver.find_element(By.ID, f"{row_id}_priceincurrency")
acquiredate_input = driver.find_element(By.ID, f"{row_id}_acquiredate_display")
# Get the values from the input fields
count_value = count_input.get_attribute("value")
price_value = price_input.get_attribute("value")
price_in_currency_value = price_in_currency_input.get_attribute("value")
acquiredate_value = acquiredate_input.get_attribute("value")
# Check if any of the input fields contain non-zero values
if count_value.strip() and float(count_value) != 0 or \
price_value.strip() and float(price_value) != 0 or \
price_in_currency_value.strip() and float(price_in_currency_value) != 0 or \
acquiredate_value.strip() and acquiredate_value != "0":
return True
else:
return False
except NoSuchElementException:
# If any of the input fields are not found we don't want to touch it, so we consider the row as full
return True
except ValueError:
# If any of the input fields cannot be converted to float we don't want to touch it, so we consider the row as full
return True
def check_if_row_full_dividends(driver, row_id):
# Function to check if a row is already filled with meaningful data for dividends table
try:
sum_input = driver.find_element(By.ID, f"{row_id}_sum")
name_input = driver.find_element(By.ID, f"{row_id}_name")
paidtax_input = driver.find_element(By.ID, f"{row_id}_paidtax")
# Get the values from the input fields
sum_value = sum_input.get_attribute("value")
name_value = name_input.get_attribute("value")
paidtax_value = paidtax_input.get_attribute("value")
# Check if any of the input fields contain meaningful non-zero data
if (sum_value.strip() and sum_value != "0.00") or \
name_value.strip() or \
(paidtax_value.strip() and paidtax_value != "0.00"):
return True
else:
return False
except NoSuchElementException:
# If any of the input fields are not found, consider the row as full
return True
def check_if_row_full_sales(driver, row_id):
# Function to check if a row is already filled with meaningful data for the sales table
try:
sellvalue_input = driver.find_element(By.ID, f"{row_id}_sellvalue")
buyvalue_input = driver.find_element(By.ID, f"{row_id}_buyvalue")
profit_input = driver.find_element(By.ID, f"{row_id}_profit")
loss_input = driver.find_element(By.ID, f"{row_id}_loss")
# Get the values from the input fields
sellvalue_value = sellvalue_input.get_attribute("value")
buyvalue_value = buyvalue_input.get_attribute("value")
profit_value = profit_input.get_attribute("value")
loss_value = loss_input.get_attribute("value")
# Check if any of the input fields contain meaningful non-zero data
if any(float(value.strip() or 0) != 0 for value in [sellvalue_value, buyvalue_value, profit_value, loss_value]):
return True
else:
return False
except NoSuchElementException:
# If any of the input fields are not found, consider the row as full
return True
def fill_income_code_v1(driver, row_id, income_code):
# Function to select the income code from the dropdown menu
try:
income_code_select = Select(driver.find_element(By.ID, f"{row_id}_incomecode"))
income_code_select.select_by_value(income_code)
#print(f"Income code '{income_code}' selected.")
except NoSuchElementException:
print("Error: Income code field not found.")
except:
print("Error: Failed to select income code.")
def fill_dropdown_menu(driver, field_id, value, retry_attempts=10):
attempt=0
while True:
attempt += 1
print(f"DEBUG: fill_dropdown_menu: attempt: \"{attempt}\", field_id: \"{field_id}\", value: \"{value}\"")
try:
# Wait for the dropdown element to be clickable
dropdown_element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, field_id)))
try:
if dropdown_element.get_attribute("value") == str(value):
print(f"fill_dropdown_menu: The field_id \"{field_id}\" is already with the same string value \"{value}\", we don't touch it.")
return True
except Exception as e:
print(f"Error in fill_dropdown_menu while trying to check if the field_id \"{field_id}\" is already selected: {e}")
time.sleep(1)
if attempt > retry_attempts:
print("")
print(" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *")
print(f"fill_dropdown_menu: All attempts failed. DEBUG: retry_attempts: {retry_attempts} attempt: {attempt}")
print("This is unusual. So we requre user confirmation to continue.")
print("Това е необичайно. Потвърждение за продължаването на скрипта се изисква.")
print(f"We tried to enter in \"{field_id}\" the value \"{value}\".")
print(f"Опитахме се да въведем в \"{field_id}\" стойността \"{value}\".")
print("Type \"stop\" and press Enter to stop the program. Напишете \"стоп\" и натиснете Enter за да спрете скрипта.")
print("Or to continue trying again: Или за следващ опит:")
while True:
user_input = input("Press Enter to try again. Натиснете Enter за да опитаме пак.")
if user_input == "":
break
if user_input == "стоп":
raise SystemExit("Скриптът спря, защото потребителят потвърди, че иска да спре.")
if user_input == "stop":
raise SystemExit("Script stopped because of user confirmation to stop.")
#time.sleep(1)
# Scroll the element into view, aligning it to the center of the viewport
driver.execute_script("arguments[0].scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });", dropdown_element)
#time.sleep(1)
#print("Click!")
# Open the dropdown menu
#dropdown_element.click()
#time.sleep(1)
#driver.execute_script("arguments[0].scrollIntoView(true);", dropdown_element)
time.sleep(0.1)
if slow_global:
time.sleep(1)
if attempt > 3:
time.sleep(0.5)
# Wait for the dropdown options to become visible
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, field_id)))
#input("DEBUG: fill_dropdobwn_menu - press ENTER to continiue. Checkpoint 2.")
if attempt > 3:
time.sleep(0.5)
# Select the value from the dropdown
select = Select(driver.find_element(By.ID, field_id))
select.select_by_value(value)
if attempt > 3:
time.sleep(0.5)
#driver.execute_script("arguments[0].blur();", select)
#select_element = driver.find_element(By.ID, field_id)
# select_element.send_keys(Keys.TAB)
#actions = ActionChains(driver)
#actions.move_to_element(select_element).send_keys(Keys.TAB).perform()
#print("Blur element...")
#driver.execute_script("arguments[0].blur();", select_element)
#select_element.click()
#select_element.send_keys(Keys.ESCAPE)
print(f"Value '{value}' selected in dropdown '{field_id}'.")
time.sleep(0.1)
if attempt > 3:
time.sleep(0.5)
if slow_global:
time.sleep(0.5)
# Check if the selected value matches the expected value
if select.first_selected_option.get_attribute("value") == value:
return True
else:
print(f"Error: Selected value '{select.first_selected_option.get_attribute('value')}' doesn't match the expected value '{value}'.")
continue
except TimeoutException:
print(f"Error: Timeout while waiting for the dropdown options in '{field_id}' to appear.")
except NoSuchElementException:
print(f"Error: Dropdown element or option not found in '{field_id}'.")
except Exception as e:
print(f"Error: {e}")
return False
def fill_income_code_v2(driver, row_id, income_code, retry_attempts=10):
field_id = f"{row_id}_incomecode"
for attempt in range(retry_attempts + 1):
if attempt > 0:
print(f"fill_income_code: Retry attempt {attempt}...")
time.sleep(2)
if fill_dropdown_menu(driver, field_id, income_code):
print(f"fill_income_code: Income code '{income_code}' successfully selected for row '{row_id}'.")
return True
print(f"fill_income_code: All {retry_attempts + 1} attempts failed to select income code '{income_code}' for row '{row_id}'.")
return False
def fill_income_code(driver, row_id, income_code, retry_attempts=10):
field_id = f"{row_id}_incomecode"
if fill_dropdown_menu(driver, field_id, income_code, retry_attempts):
print(f"fill_income_code: Income code '{income_code}' successfully selected for row '{row_id}'.")
return True
print(f"fill_income_code: fill_dropdown_menu failed to select income code '{income_code}' for row '{row_id}' in field_id '{field_id}'.")
return False
# Затваря прозореца с инструкции за попълване, който излиза при попълване на кода на дохода
# Предишна версия, не се ползва, пази се за всеки случай (за справка).
def click_the_close_button_v1(driver):
# Wait for up to 1 second for the dialog and button to appear
for _ in range(10):
try:
close_button = driver.find_elements(By.CLASS_NAME, "ui-dialog-titlebar-close")
except:
time.sleep(0.1) # Wait for 0.1 second before checking again
continue
if close_button:
try:
close_button[0].click() # Click the first close button found
#print("Button clicked successfully.")
return True # Return True if the button is clicked successfully
except Exception as e:
print(f"Error clicking button: {e}")
break # Exit the loop once the button is found and clicked
time.sleep(0.1) # Wait for 0.1 second before checking again
# If the button is not found after 1 second, print a message and return False
else:
print("Button not found within 1 second.")
return False
# Затваря прозореца с инструкции за попълване, който излиза при попълване на кода на дохода
def click_the_close_button(driver,timeout=1):
# Wait for up to 1 second for the dialog and button to appear
try:
close_button = WebDriverWait(driver, timeout).until(EC.element_to_be_clickable((By.CLASS_NAME, "ui-dialog-titlebar-close")))
# driver.execute_script("arguments[0].scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });", close_button)
# time.sleep(1) # ако не се изчака не зацепва
time.sleep(0.1) # за всеки случай, има WebDriverWait отдолу, който трябва да чака
# вместо sleep за всеки случай
wait = WebDriverWait(driver, timeout)
wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "ui-dialog-titlebar-close")))
close_button.click() # Click the first close button found
print("click_the_close_button: Button clicked successfully.")
return True # Return True if the button is clicked successfully
except TimeoutException:
print(f"click_the_close_button: TimeoutException")
return False
except Exception as e:
print(f"Error in click_the_close_button: {e}")
return False
def click_the_close_skip_button_from_welcome_message(driver):
# Wait for up to 1 second for the dialog and button to appear
for _ in range(10):
try:
#close_button = driver.find_elements_by_xpath("//button[@id='skip']")
#close_buttons = driver.find_elements(By.XPATH,"//button[@id='skip']")
#close_button = close_buttons[0]
close_button = driver.find_element(By.XPATH, "//button[@id='skip']")
except:
time.sleep(0.1) # Wait for 0.1 second before checking again
continue
if close_button:
try:
driver.execute_script("arguments[0].scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });", close_button)
time.sleep(1)
except Exception as e:
print(f"Error scrollIntoView button: {e}")
if close_button:
try:
close_button.click() # Click the first close button found
#print("Button clicked successfully.")
return True # Return True if the button is clicked successfully
except Exception as e:
print(f"Error clicking button: {e}")
break # Exit the loop once the button is found and clicked
time.sleep(0.1) # Wait for 0.1 second before checking again
# If the button is not found after 1 second, print a message and return False
else:
print("Button not found within 1 second.")
return False
def check_messenger_status(driver):
try:
#messenger_div = driver.find_element_by_id("messenger")
messenger_div = driver.find_element(By.ID, "messenger")
content = messenger_div.text
print("Messenger div content:", content)
# Check if the content is not only whitespace
if content and not content.isspace():
try:
# Check if there is a span with id="msgr_title" and text "Вие потвърдихте успешно тази част"
#msgr_title_span = messenger_div.find_element_by_id("msgr_title")
msgr_title_span = messenger_div.find_element(By.ID, "msgr_title")
if "Вие потвърдихте успешно тази част" in msgr_title_span.text:
return "green"
print("The content of msgr_title_span.text is: ", msgr_title_span.text)
except:
print("Error while trying msgr_title_span = messenger_div.find_element(By.ID, \"msgr_title\").")
try:
# Check if any child div has class="error"
#error_divs = messenger_div.find_elements_by_css_selector("div.error")
error_divs = messenger_div.find_elements(By.CSS_SELECTOR, "div.error")
if error_divs:
print("Error content:", [error_div.text for error_div in error_divs])
return "error"
except:
print("Error while trying error_divs = messenger_div.find_element(By.CSS_SELECTOR, \"div.error\").")
try:
# Check if there is a span with id="msgr_title" and text "Грешки при потвърждаване на частта"
#msgr_title_span = messenger_div.find_element_by_id("msgr_title")
msgr_title_span = messenger_div.find_element(By.ID, "msgr_title")
if "Грешки при потвърждаване на частта" in msgr_title_span.text:
return "error"
print("The content of msgr_title_span.text is: ", msgr_title_span.text)
except:
print("Error while trying msgr_title_span = messenger_div.find_element(By.ID, \"msgr_title\").")
# If there is a div with id="messenger" but no error and no success message, return "unexpected"
return "unexpected"
else:
if not content:
print("It's an empty string")
elif content.isspace():
print("It's whitespace")
else:
print("The content is:", content)
return "none"
except NoSuchElementException:
# If there is no div with id="messenger", return "none"
print("check_messenger_status: NoSuchElementException")
return "none"
except Exception as e:
print(f"check_messenger_status: Error: {e}")
return "exception"
def click_and_check_messenger_hide(driver):
try:
# Find the div with id="messenger"
messenger_div = driver.find_element(By.ID, "messenger")
# Check if the messenger_div exists
if messenger_div:
# Search for an img with onclick="msgr.hide()"
hide_img = messenger_div.find_element(By.XPATH, ".//img[contains(@onclick, 'msgr.hide()')]")
# Check if the hide_img exists
if hide_img:
try:
driver.execute_script("arguments[0].scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });", hide_img)
time.sleep(0.1)
except Exception as e:
print(f"Error scrollIntoView hide_img in click_and_check_messenger_hide: {e}")
# Click on the hide_img
hide_img.click()
# Wait for the hide_img to disappear
start_time = time.time()
while hide_img.is_displayed():
time.sleep(0.1)
if time.time() - start_time >= 2:
return False
except ElementNotInteractableException as e:
print(f"Element is not interactable: {e}")
return True # no need to click, it's already clicked?
except Exception as e:
print(f"Error in click_and_check_messenger_hide:: {e}")
return False
return True
def fill_sales_code_v1(driver, row_id):
# Function to select the income code from the dropdown menu
try:
code_select = Select(driver.find_element(By.ID, f"{row_id}_code"))
code_select.select_by_value("508")
if row_id.endswith(":1"):
time.sleep(0.2)
click_the_close_button(driver)
except NoSuchElementException:
print("Error: Sales code field not found.")
except:
print("Error: Failed to select sales code.")
def fill_sales_code_v2(driver, row_id):
# Function to select the income code from the dropdown menu
code_id = f"{row_id}_code"
print(f"DEBUG: fill_sales_code_v2 is invoked. code_id is \"{code_id}\"")
try:
code_element = driver.find_element(By.ID, code_id)
if row_id.endswith(":1"):
print("DEBUG: row_id.endswith LINE 1")
click_the_close_button(driver,0.1)
# Scroll the element into view, aligning it to the center of the viewport
try:
print("Scroll more precisely...")
driver.execute_script("arguments[0].scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });", code_element)
except Exception as e:
print(f"Error scrollIntoView code_element in fill_sales_code: {e}")
time.sleep(0.1)
# code_select.click() # НЕ МОЖЕ ДА СЕ КЛИКА: AttributeError: 'Select' object has no attribute 'click'
# time.sleep(1) # трябва да се изчака скролирането да завръши преди кликането
# code_element.click() # може
wait = WebDriverWait(driver, 5)
# code_element = wait.until(EC.element_to_be_clickable((By.ID, f"{row_id}_code")))
# code_element = wait.until(EC.element_to_be_clickable(code_element))
# wait.until(EC.element_to_be_clickable(code_element))
wait.until(EC.element_to_be_clickable((By.ID, code_id)))
code_select = Select(code_element)
code_element.click()
time.sleep(0.1)
if row_id.endswith(":1"):
print("DEBUG: row_id.endswith LINE 2")
click_the_close_button(driver,1)
# Scroll the element into view, aligning it to the center of the viewport
try:
print("Scroll more precisely...")
driver.execute_script("arguments[0].scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });", code_element)
except Exception as e:
print(f"Error scrollIntoView code_element in fill_sales_code: {e}")
code_select.select_by_value("508")
if row_id.endswith(":1"):
print("DEBUG: row_id.endswith LINE 2")
click_the_close_button(driver,0.1)
code_element.send_keys(Keys.TAB)
except NoSuchElementException:
print("Error in fill_sales_code: Sales code field not found.")
except Exception as e:
print(f"Error in fill_sales_code:: {e}")
def fill_sales_code(driver, row_id):
# Function to select the income code from the dropdown menu
code_id = f"{row_id}_code"
print(f"DEBUG: fill_sales_code is invoked. code_id is \"{code_id}\"")
try:
code_element = driver.find_element(By.ID, code_id)
if row_id.endswith(":1"):
print("DEBUG: row_id.endswith LINE 1")
click_the_close_button(driver,0.1)
# Scroll the element into view, aligning it to the center of the viewport
try:
print("Scroll...")
driver.execute_script("arguments[0].scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });", code_element)
except Exception as e:
print(f"Error scrollIntoView code_element in fill_sales_code: {e}")
time.sleep(0.1)
wait = WebDriverWait(driver, 5)
wait.until(EC.element_to_be_clickable((By.ID, code_id)))
code_select = Select(code_element)
if row_id.endswith(":1"):
#code_element.click()
# Create an instance of ActionChains
actions = ActionChains(driver)
# Click on the code_element
actions.click(code_element)
time.sleep(0.5) # CRITICAL It does not work without this delay
# Perform the action to click
actions.perform()
time.sleep(0.1)
if row_id.endswith(":1"):
print("DEBUG: row_id.endswith LINE 2")
# click_the_close_button(driver,1)
if click_the_close_button(driver,1):
time.sleep(5)
# Scroll the element into view, aligning it to the center of the viewport
try:
print("Scroll...")
driver.execute_script("arguments[0].scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });", code_element)
except Exception as e:
print(f"Error scrollIntoView code_element in fill_sales_code: {e}")
# code_select.select_by_value("508")
fill_dropdown_menu(driver, code_id, "508")
if row_id.endswith(":1"):
print("DEBUG: row_id.endswith LINE 3")
click_the_close_button(driver,0.1)
except NoSuchElementException:
print("Error in fill_sales_code: Sales code field not found.")
except Exception as e:
print(f"Error in fill_sales_code:: {e}")
# Keep for reference
def sales_code_message_provoke_and_close_BROKEN(driver):
field_id = "A5D2:1_code"
code_select = Select(driver.find_element(By.ID, field_id))
# Scroll into view if needed
driver.execute_script("arguments[0].scrollIntoView(true);", code_select)
time.sleep(5)
# Attempt to click using actions chain
actions = ActionChains(driver)
actions.move_to_element(code_select).click().perform()
time.sleep(5)
click_the_close_button(driver)
# Keep for reference
def sales_code_message_provoke_and_close(driver):
field_id = "A5D2:1_code"
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select
# Find the <select> element
select_element = driver.find_element(By.ID, field_id)
# Create a Select object
code_select = Select(select_element)
# Scroll into view if needed
# driver.execute_script("arguments[0].scrollIntoView(true);", select_element)
# Scroll just in case
try:
print("Scroll...")
driver.execute_script("arguments[0].scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });", select_element)
except Exception as e:
print(f"Error scrollIntoView code_element in sales_code_message_provoke_and_close: {e}")
time.sleep(0.1)
# Attempt to click the <select> element using actions chain
# actions = ActionChains(driver)
# actions.move_to_element(select_element).click().perform()
# Create an instance of ActionChains
actions = ActionChains(driver)
# Click
actions.click(select_element)
time.sleep(0.5) # It does not work without this delay
# Perform the action to click
actions.perform()
#time.sleep(0.1)
return click_the_close_button(driver)
def fill_sales_code_new_do_not_work(driver, row_id, retry_attempts=4):
field_id = f"{row_id}_code"
sales_code="508"
for attempt in range(retry_attempts + 1):
if attempt > 0:
print(f"Retry attempt {attempt}...")
time.sleep(0.5)
if fill_dropdown_menu(driver, field_id, sales_code):
print(f"Sales code '{sales_code}' successfully selected for row '{row_id}'.")
if row_id.endswith(":1"):
time.sleep(0.2)
click_the_close_button(driver)
return True
print(f"All {retry_attempts + 1} attempts failed to select sales code '{sales_code}' for row '{row_id}'.")
if row_id.endswith(":1"):
time.sleep(0.2)
click_the_close_button(driver)
return False
def fill_method_code(driver, row_id, method_code):
# Function to select the method code from the dropdown menu
try:
method_code_select = Select(driver.find_element(By.ID, f"{row_id}_methodcode"))
method_code_select.select_by_value(method_code)
#print(f"Method code '{method_code}' selected.")
except NoSuchElementException:
print("Error: Method code field not found.")
except:
print("Error: Failed to select method code.")
def create_row(driver, table_type):
# Function to create a new row in the table
try:
if table_type == "stocks":
add_button_id = "A8D1"
elif table_type == "shares":
add_button_id = "A8D2"
elif table_type == "dividends":
add_button_id = "A8D5"