-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataflow.py
More file actions
3413 lines (2924 loc) · 149 KB
/
dataflow.py
File metadata and controls
3413 lines (2924 loc) · 149 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
# RIGHE 1-2 (Importazioni necessarie per il DPI)
import sys
if sys.platform == 'win32':
from ctypes import windll
else:
windll = None
# ---------------------------------------------
# RIGHE 3-20: BLOCCO DPI AWARENESS (DEVE ESSERE QUI)
# ---------------------------------------------
if sys.platform == 'win32':
try:
# Importiamo windll direttamente se non è già stata importata
# Imposta PerMonitorV2
DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = -4
if hasattr(windll.shcore, 'SetProcessDpiAwarenessContext'):
windll.shcore.SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)
elif hasattr(windll.user32, 'SetProcessDPIAware'):
windll.user32.SetProcessDPIAware()
except Exception as e:
# Ignora errori se le librerie non sono presenti o la funzione non è supportata
# BUG #21 FIX: Log warning invece di pass silenzioso per diagnostica
import logging
logging.getLogger(__name__).debug(f"DPI awareness non disponibile: {e}")
import tkinter as tk
from tkinter import ttk, filedialog, simpledialog
from tksheet import Sheet, natural_sort_key
import os
from database_manager import DatabaseManager, DatabaseError
import tempfile
from tkcalendar import DateEntry
from datetime import datetime, date
import openpyxl
from openpyxl.styles import Border, Side, Font, Alignment, PatternFill
from copy import copy
import shutil
import configparser
import re
from PIL import Image, ImageTk
import time
import math
import glob
import ast # Aggiunto per la gestione sicura delle note formattate
import json # Aggiunto per parsing sicuro delle note
import logging
from logging.handlers import RotatingFileHandler
import atexit
import gettext
import subprocess
import threading
import unicodedata
from collections import defaultdict, deque
# Importa costanti UI/layout
from constants import (
TASKBAR_BUFFER,
BASE_ARTICLE_WIDTH,
CONTO_LAVORO_WIDTH,
SUPPLIER_COLUMN_WIDTH,
PADDING,
BUTTONS_MIN_WIDTH,
MIN_WINDOW_WIDTH,
SCREEN_WIDTH_PERCENTAGE,
SCREEN_HEIGHT_PERCENTAGE
)
# Importa utility stringhe e formattazione
from utils.string_utils import generate_username
from utils.format_utils import (
parse_float_from_comma_string,
format_quantity_display,
format_currency_display,
get_currency_code,
get_currency_excel_number_format,
)
from utils.window_utils import calculate_center_position, calculate_optimal_window_size, center_window
from utils.user_utils import get_app_data_dir, get_config_file, load_user_identity, save_user_identity
from utils.resource_utils import resource_path, set_window_icon
from utils.i18n_utils import (
tr,
init_i18n,
get_current_language,
get_pos_column_text,
get_qty_column_text,
normalize_rfq_type,
translate_rfq_type,
translate_derisking_status,
translate_vsm_action,
)
from utils.validation_utils import sanitize_filename, format_date_for_db, format_price_display
# !!!!! IMPORTANTE: Inizializza le traduzioni PRIMA di importare moduli UI !!!!!
# I moduli UI usano tr() durante l'import, quindi init_i18n() DEVE essere chiamato prima
init_i18n()
# Importa UI components (DOPO init_i18n per avere tr() disponibile)
from ui.kpi_window import KpiWindow
from ui.window_launchers import open_help_window, on_kpi_click, open_license_window
from ui.windows.view_request_window import ViewRequestWindow
from ui.components.main_dashboard_toolbar import MainDashboardToolbar
from ui.components.collapsible_filters import CollapsibleFilters
from ui.main_dashboard_builder import build_main_dashboard
from ui.sheet_factories import (
create_request_sheet,
create_vsm_event_sheet,
create_supplier_sheet,
create_cell_select_handler as factory_create_cell_select_handler,
create_row_select_handler as factory_create_row_select_handler,
)
from services.dashboard_controller import DashboardController
# REFACTORING: Import moduli estratti
from services.app_paths import (
get_user_documents_dataflow_dir,
get_fixed_db_dir,
get_fixed_attachments_dir,
get_db_path,
reset_db_cache
)
from services.startup_service import (
cleanup_temp_on_startup,
setup_logging,
initialize_dataflow_directory_structure
)
from services.excel_export_service import (
export_rfq_requests_excel,
export_vsm_events_excel,
export_derisking_suppliers_excel,
)
from services.dashboard_selection_policy import (
get_selected_row_indices as policy_get_selected_row_indices,
check_all_selected_are_mine as policy_check_all_selected_are_mine,
)
from services.dashboard_actions_policy import (
compute_actions_capabilities,
build_actions_menu_spec,
)
from services.vsm_dashboard_service import (
get_vsm_dataset as service_get_vsm_dataset,
apply_vsm_filters as service_apply_vsm_filters,
)
from services.derisking_dashboard_service import (
get_derisking_dataset as service_get_derisking_dataset,
build_supplier_rows_and_metadata,
auto_size_supplier_sheet as service_auto_size_supplier_sheet,
populate_supplier_sheet as service_populate_supplier_sheet,
)
from services.vsm_command_service import (
status_to_event_type,
delete_vsm_events_by_ids,
delete_suppliers_by_ids,
duplicate_vsm_event_by_id,
)
from services.rfq_dashboard_service import (
load_requests_by_status as service_load_requests_by_status,
build_rfq_sheet_payload,
)
from services.rfq_command_service import (
update_request_status,
delete_requests_with_attachments,
duplicate_request_full,
create_request_shell,
)
from services.dashboard_search_service import (
has_active_search_filters,
filter_derisking_suppliers_by_query,
split_vsm_events_by_type,
filter_vsm_events_by_query,
)
from services.settings_preferences_service import (
ALLOWED_CURRENCIES,
load_settings_snapshot,
save_language_preference,
save_currency_preference,
save_autobackup_preferences,
)
from services.settings_maintenance_service import (
read_autobackup_config,
read_last_autobackup_date,
save_last_autobackup_date,
copy_manual_backup_bundle,
perform_autobackup_copy,
)
from services.dataflow_location_service import (
normalize_parent_directory,
ensure_parent_directory_writable,
detect_username_conflict,
)
from services.restart_lifecycle_service import (
resolve_restart_script_path,
build_restart_command,
launch_post_mainloop_restart,
)
from database.db_helpers import crea_database_v4
from ui.dialogs.common_dialogs import (
LanguagePrompt,
NewRdOTypeDialog,
UserIdentityDialog,
CopyProgressWindow,
SplashScreen,
SimpleYesNoDialog,
SimpleMessageDialog,
LicenseAcceptanceDialog,
show_error
)
# Esegui pulizia all'avvio
cleanup_temp_on_startup()
# REFACTORING: Setup logging estratto in services.startup_service
logger = setup_logging()
# REFACTORING: Funzioni path management estratte in services.app_paths
# - get_user_documents_dataflow_dir()
# - get_fixed_db_dir()
# - get_fixed_attachments_dir()
# - initialize_dataflow_directory_structure()
# - get_db_path()
# - reset_db_cache()
# REFACTORING: Database helpers estratti in database.db_helpers
# - crea_database_v4()
# FINESTRA IMPOSTAZIONI
# ------------------------------------------------------------------------------------
class SettingsWindow(tk.Toplevel):
def __init__(self, parent, main_app):
try:
super().__init__(parent)
self.withdraw()
set_window_icon(self)
self.main_app = main_app
try:
self.title(tr("Settings and Maintenance"))
except Exception as e:
logger.error(f"Errore nel settare il titolo: {e}")
self.title(tr("Settings and Maintenance"))
self.transient(parent)
self.grab_set()
self.autobackup_enabled = tk.BooleanVar()
self.autobackup_hour = tk.StringVar()
self.autobackup_path = tk.StringVar()
self.language_var = tk.StringVar()
self.currency_var = tk.StringVar(value=tr("None"))
# Imposta un valore di default per la lingua (verrà aggiornato da load_settings)
self.language_var.set("English")
# Le impostazioni di visualizzazione sono ora gestite automaticamente da Windows DPI
main_frame = ttk.Frame(self, padding="20")
main_frame.pack(fill="both", expand=True)
# --- Sezione Posizione DataFlow Standard ---
dataflow_frame = ttk.LabelFrame(main_frame, text=tr("Standard DataFlow Location"), padding=10)
dataflow_frame.pack(fill="x", pady=(0, 15), padx=5)
dataflow_label = ttk.Label(
dataflow_frame,
text=tr("Choose where to save the DataFlow folder (requires restart)."),
font=(None, 10),
wraplength=480,
justify="left"
)
dataflow_label.pack(anchor="w", pady=(0, 10))
ttk.Button(
dataflow_frame,
text=tr("📁 Change DataFlow Location..."),
command=self.select_standard_dataflow_location
).pack()
try:
current_dataflow = get_user_documents_dataflow_dir()
ttk.Label(
dataflow_frame,
text=tr("Current DataFlow folder: {}").format(current_dataflow),
font=(None, 9),
foreground="gray",
wraplength=480,
justify="left"
).pack(anchor="w", pady=(10, 0))
except Exception as e:
logger.error(f"Errore visualizzazione posizione DataFlow corrente: {e}")
# --- Sezione Backup Manuale ---
backup_frame = ttk.LabelFrame(main_frame, text=tr("Manual Backup"), padding="10")
backup_frame.pack(fill="x", pady=(0, 15), padx=5)
ttk.Label(backup_frame, text=tr("Create an immediate backup of the database."), font=(None, 10), wraplength=500).pack(anchor="w", pady=(0, 10))
ttk.Button(backup_frame, text=tr("💾 Manual Backup..."), command=self.backup_database).pack()
# --- Sezione Backup Automatico ---
autobackup_frame = ttk.LabelFrame(main_frame, text=tr("Daily Automatic Backup"), padding="10")
autobackup_frame.pack(fill="x", pady=(0, 15), padx=5)
ttk.Checkbutton(autobackup_frame, text=tr("Enable daily automatic backup (max 3 copies)"), variable=self.autobackup_enabled).pack(anchor="w", pady=(0, 10))
hour_frame = ttk.Frame(autobackup_frame)
hour_frame.pack(fill="x", pady=5)
ttk.Label(hour_frame, text=tr("Time:")).pack(side="left", padx=(0, 5))
ttk.Combobox(hour_frame, textvariable=self.autobackup_hour, values=[f"{h:02}" for h in range(24)], width=5, state="readonly").pack(side="left")
path_frame = ttk.Frame(autobackup_frame)
path_frame.pack(fill="x", pady=5)
ttk.Label(path_frame, text=tr("Save to:")).pack(anchor="w")
path_entry_frame = ttk.Frame(autobackup_frame)
path_entry_frame.pack(fill="x")
ttk.Entry(path_entry_frame, textvariable=self.autobackup_path, state="readonly", width=50).pack(side="left", fill="x", expand=True, pady=(0, 5))
ttk.Button(path_entry_frame, text=tr("📁 Choose..."), command=self.select_autobackup_path).pack(side="left", padx=(5,0), pady=(0,5))
ttk.Button(autobackup_frame, text=tr("💾 Save Backup Settings"), command=self.save_autobackup_settings).pack(pady=(10,0))
# --- Sezione Lingua e Valuta ---
language_frame = ttk.LabelFrame(main_frame, text=tr("Lingua e Valuta"), padding="10")
language_frame.pack(fill="x", pady=(0, 15), padx=5)
ttk.Label(language_frame, text=tr("Select the interface language. The change requires restarting the application."), font=(None, 10), wraplength=500).pack(anchor="w", pady=(0, 15))
# Riga per il controllo della lingua
lang_row = ttk.Frame(language_frame)
lang_row.pack(fill="x", pady=(0, 5))
ttk.Label(lang_row, text=tr("Language:")).pack(side="left", padx=(0, 10))
language_combo = ttk.Combobox(lang_row, textvariable=self.language_var, values=["English", "Italiano"], state="readonly", width=20)
language_combo.pack(side="left", padx=(0, 10))
self.language_combo = language_combo # Salva riferimento per aggiornamento successivo
# Riga per preferenza valuta globale
currency_row = ttk.Frame(language_frame)
currency_row.pack(fill="x", pady=(8, 0))
ttk.Label(currency_row, text=tr("Currency")).pack(side="left", padx=(0, 10))
self.currency_combo = ttk.Combobox(
currency_row,
textvariable=self.currency_var,
values=[tr("None"), "EUR", "USD", "GBP", "CHF"],
state="readonly",
width=20,
)
self.currency_combo.pack(side="left", padx=(0, 10))
ttk.Button(
language_frame,
text=tr("💾 Save Settings"),
command=self.save_language_currency_settings,
).pack(pady=(12, 0))
# Assicura che il valore nel combobox corrisponda al codice lingua
def on_language_change(event):
selected = self.language_var.get()
# Il valore viene già impostato correttamente dal combobox
pass
language_combo.bind("<<ComboboxSelected>>", on_language_change)
try:
self.load_settings()
# Aggiorna il combobox dopo aver caricato le impostazioni
if hasattr(self, 'language_combo'):
current_val = self.language_var.get()
if current_val == "English":
self.language_combo.current(0)
elif current_val == "Italiano":
self.language_combo.current(1)
except Exception as e:
logger.error(f"Errore nel caricare impostazioni all'avvio di SettingsWindow: {e}", exc_info=True)
# Continua comunque con valori di default
try:
center_window(self)
except Exception as e:
logger.error(f"Errore nel centrare la finestra SettingsWindow: {e}", exc_info=True)
# Mostra comunque la finestra anche se il centraggio fallisce
self.deiconify()
self.geometry("800x600")
except Exception as e:
logger.error(f"Errore critico nell'inizializzazione di SettingsWindow: {e}", exc_info=True)
# Mostra la finestra anche in caso di errore critico
try:
self.deiconify()
self.geometry("800x600")
except:
pass
def load_settings(self):
"""Carica le impostazioni dal file config.ini."""
try:
snapshot = load_settings_snapshot(get_config_file())
self.autobackup_enabled.set(snapshot["autobackup_enabled"])
self.autobackup_hour.set(snapshot["autobackup_hour"])
self.autobackup_path.set(snapshot["autobackup_path"])
self.language_var.set("English" if snapshot["language_code"] == "en" else "Italiano")
self.currency_var.set(tr("None") if snapshot["currency_code"] == "NONE" else snapshot["currency_code"])
except Exception as e:
logger.error(f"Errore critico nel caricare impostazioni: {e}", exc_info=True)
# Imposta valori di default in caso di errore
self.autobackup_enabled.set(False)
self.autobackup_hour.set("12")
self.autobackup_path.set("")
self.language_var.set("English")
self.currency_var.set(tr("None"))
# La funzione save_display_settings() è stata rimossa perché le impostazioni
# di visualizzazione sono ora gestite automaticamente da Windows DPI
def save_language_settings(self):
"""Salva la lingua selezionata nel config.ini."""
try:
selected_lang = self.language_var.get()
if not selected_lang:
SimpleMessageDialog(self, tr("Warning"), tr("Select a language."), "warning")
return
save_language_preference(get_config_file(), selected_lang)
dialog = SimpleYesNoDialog(
self,
tr("Success"),
tr("Language setting saved.\nRestart the application now to apply the changes?")
)
if dialog.result:
# Riavvia l'applicazione
self.main_app.restart_program()
except Exception as e:
logger.error(f"Errore nel salvare la lingua: {e}", exc_info=True)
SimpleMessageDialog(self, tr("Error"), tr("Unable to save language setting: {}").format(e), "error")
def save_currency_settings(self):
"""Salva la preferenza valuta globale nel config.ini."""
try:
save_currency_preference(
get_config_file(),
self.currency_var.get(),
tr("None"),
)
dialog = SimpleYesNoDialog(
self,
tr("Success"),
tr("Currency setting saved.")
+ "\n"
+ tr("The change requires restarting the application.")
+ "\n"
+ tr("Restart the application now to apply the changes?")
)
if dialog.result:
self.main_app.restart_program()
except Exception as e:
logger.error(f"Errore nel salvare valuta: {e}", exc_info=True)
SimpleMessageDialog(self, tr("Error"), tr("Unable to save currency setting: {}").format(e), "error")
def save_language_currency_settings(self):
"""Salva lingua/valuta con un solo feedback finale e un solo prompt di restart."""
try:
selected_lang = self.language_var.get()
if not selected_lang:
SimpleMessageDialog(self, tr("Warning"), tr("Select a language."), "warning")
return
snapshot = load_settings_snapshot(get_config_file())
selected_lang_code = "en" if selected_lang == "English" else "it"
selected_currency_ui = (self.currency_var.get() or "").strip()
selected_currency_code = (
"NONE"
if selected_currency_ui in {tr("None"), "NONE"}
else selected_currency_ui.upper()
)
if selected_currency_code not in ALLOWED_CURRENCIES:
selected_currency_code = "NONE"
language_changed = selected_lang_code != snapshot["language_code"]
currency_changed = selected_currency_code != snapshot["currency_code"]
if not language_changed and not currency_changed:
SimpleMessageDialog(self, tr("Info"), tr("No changes to save."), "info")
return
if language_changed:
save_language_preference(get_config_file(), selected_lang)
if currency_changed:
save_currency_preference(
get_config_file(),
self.currency_var.get(),
tr("None"),
)
dialog = SimpleYesNoDialog(
self,
tr("Success"),
tr("The change requires restarting the application.")
+ "\n"
+ tr("Restart the application now to apply the changes?"),
)
if dialog.result:
self.main_app.restart_program()
except Exception as e:
logger.error(f"Errore nel salvare lingua/valuta: {e}", exc_info=True)
SimpleMessageDialog(self, tr("Error"), tr("Unable to save: {}").format(e), "error")
def select_autobackup_path(self):
path = filedialog.askdirectory(title=tr("Select folder for automatic backups"), parent=self)
if path: self.autobackup_path.set(path)
def save_autobackup_settings(self):
try:
save_autobackup_preferences(
get_config_file(),
enabled=self.autobackup_enabled.get(),
hour=self.autobackup_hour.get(),
path=self.autobackup_path.get(),
)
SimpleMessageDialog(self, tr("Success"), tr("Backup settings saved."), "info")
except ValueError:
SimpleMessageDialog(self, tr("Warning"), tr("To enable automatic backup, specify a path."), "warning")
except Exception as e:
SimpleMessageDialog(self, tr("Error"), tr("Unable to save: {}").format(e), "error")
def backup_database(self):
"""Crea backup manuale copiando i file del database (db, wal, shm)."""
db_file = get_db_path()
if not os.path.exists(db_file):
SimpleMessageDialog(self, tr("Error"), tr("Database file '{}' not found!").format(db_file), "error")
return
dest = filedialog.asksaveasfilename(
title=tr("Save backup as..."),
initialfile=f"backup_manuale_{datetime.now().strftime('%Y%m%d_%H%M%S')}.db",
defaultextension=".db",
filetypes=[(tr("Database SQLite"), "*.db"), (tr("All files"), "*.*")],
parent=self
)
if not dest:
return # Utente ha annullato
# Normalizza l'estensione del file di destinazione
if not dest.endswith('.db'):
dest = dest.rsplit('.', 1)[0] + '.db'
# Chiudi temporaneamente la connessione della MainWindow per permettere il backup
main_window_was_open = False
try:
if hasattr(self.main_app, 'db_manager') and self.main_app.db_manager:
logger.info("Chiusura connessione MainWindow per backup...")
self.main_app.db_manager.close()
main_window_was_open = True
# Piccolo delay per assicurarsi che la connessione sia completamente chiusa
import time
time.sleep(0.2)
except Exception as e:
logger.warning(f"Impossibile chiudere connessione MainWindow: {e}")
try:
copy_result = copy_manual_backup_bundle(
db_file=db_file,
dest=dest,
logger=logger,
)
original_size = copy_result["original_size"]
backup_size = copy_result["backup_size"]
copied_paths = copy_result["copied_files"]
if backup_size < original_size * 0.5:
logger.warning(f"Backup manuale potenzialmente incompleto: {backup_size} vs {original_size} bytes")
dialog = SimpleYesNoDialog(
self,
tr("Size Warning"),
tr("The created backup is significantly smaller than the original database.\n\nOriginal: {:.2f} MB\nBackup: {:.2f} MB\n\nDo you want to keep it anyway?").format(original_size / (1024*1024), backup_size / (1024*1024))
)
if not dialog.result:
try:
for file_path in copied_paths:
if os.path.exists(file_path):
os.remove(file_path)
except:
pass
return
# Messaggio di successo con info sui file copiati
files_copied = [os.path.basename(path) for path in copied_paths if os.path.exists(path)]
SimpleMessageDialog(
self,
tr("Success"),
tr("Backup created successfully:\n\nFiles copied:\n{}\n\nTotal size: {:.2f} MB").format(
'\n'.join(f' • {f}' for f in files_copied),
copy_result["total_size"] / (1024 * 1024)
),
"info"
)
logger.info(f"Backup manuale completato: {len(files_copied)} file copiati")
except Exception as e:
logger.error(f"Errore backup manuale: {e}", exc_info=True)
SimpleMessageDialog(
self,
tr("Error"),
tr("Unable to create backup:\n{}").format(e),
"error"
)
# Rimuovi backup parziale/corrotto
if os.path.exists(dest):
try:
for file_path in [dest, dest.replace('.db', '.db-wal'), dest.replace('.db', '.db-shm')]:
if os.path.exists(file_path):
os.remove(file_path)
except:
pass
finally:
# Riapri la connessione della MainWindow se era aperta
if main_window_was_open:
try:
logger.info("Riapertura connessione MainWindow dopo backup...")
self.main_app.db_manager = DatabaseManager(get_db_path())
logger.info("Connessione MainWindow riaperta con successo")
except Exception as e:
logger.error(f"Errore nella riapertura connessione MainWindow: {e}")
SimpleMessageDialog(
self,
tr("Warning"),
tr("The backup has been completed, but it was not possible to reopen the main connection.\nIt is recommended to restart the application."),
"warning"
)
def select_standard_dataflow_location(self):
"""
Permette all'utente di scegliere una nuova posizione per la cartella DataFlow.
Passaggi:
1. Avviso esplicativo con conferma
2. Selezione cartella
3. Validazioni (permessi, rete, lunghezza path, unità)
4. Salvataggio config
5. Istruzioni per spostare manualmente la cartella
6. Riavvio applicazione
"""
logger.info("Avvio procedura cambio posizione cartella DataFlow")
current_dataflow_dir = get_user_documents_dataflow_dir()
warning_text = tr(
"⚠️ WARNING: you are about to change the DataFlow folder location.\n\nThe current folder will be automatically copied to the new selected location, including the database and attachments. This operation may take a moment.\n\nThe application will restart when it is complete.\n\nCurrent location:\n{}\n\nDo you want to proceed?"
).format(current_dataflow_dir)
dialog = SimpleYesNoDialog(
self,
tr("Confirm Location Change"),
warning_text,
icon='warning'
)
if not dialog.result:
logger.info("Utente ha annullato il cambio posizione DataFlow")
return
if sys.platform == 'win32':
initial_dir = os.path.dirname(current_dataflow_dir) or os.path.join(os.path.expanduser('~'), 'Documents')
else:
initial_dir = os.path.dirname(current_dataflow_dir) or os.path.expanduser('~')
try:
selected_dir = filedialog.askdirectory(
title=tr("Select the new DataFlow folder location"),
initialdir=initial_dir,
parent=self
)
except Exception as e:
logger.error(f"Errore apertura dialog selezione cartella: {e}")
SimpleMessageDialog(
self,
tr("Error"),
tr("Error selecting folder: {}").format(e),
"error"
)
return
if not selected_dir:
logger.info("Utente ha annullato la selezione della nuova posizione")
return
normalized_dir = normalize_parent_directory(selected_dir)
if not normalized_dir:
SimpleMessageDialog(self, tr("Error"), tr("Invalid path."), "error")
return
# ✅ CORREZIONE: NON aggiungere "DataFlow" - useremo DataFlow_{username}
# Il percorso selezionato dall'utente è la directory PARENT dove verrà creata DataFlow_{username}
logger.info(f"Cartella parent selezionata per DataFlow: {normalized_dir}")
try:
ensure_parent_directory_writable(normalized_dir)
logger.info(f"Permessi verifica OK per {normalized_dir}")
except (OSError, PermissionError) as e:
logger.error(f"Test permessi fallito per {normalized_dir}: {e}")
SimpleMessageDialog(
self,
tr("Permission Error"),
tr("Cannot write to the selected folder:\n{}\n\nDetails: {}").format(normalized_dir, e),
"error"
)
return
# Controllo lunghezza
if len(normalized_dir) > 240:
logger.warning(f"Percorso DataFlow troppo lungo ({len(normalized_dir)} caratteri)")
length_warning = tr(
"The selected path is very long ({} characters).\nWindows may have issues accessing files.\nDo you want to continue anyway?"
).format(len(normalized_dir))
dialog = SimpleYesNoDialog(
self,
tr("Path Too Long"),
length_warning
)
if not dialog.result:
logger.info("Utente ha annullato dopo avviso percorso lungo")
return
# Controllo unità rimovibile
try:
drive_letter = os.path.splitdrive(normalized_dir)[0]
if drive_letter and drive_letter.upper() not in ['C:', 'D:', 'E:']:
logger.warning(f"Unità potenzialmente rimovibile: {drive_letter}")
removable_warning = tr(
"⚠️ The selected drive ({}) might be removable.\nIf disconnected, DataFlow will not be able to access the data."
).format(drive_letter)
SimpleMessageDialog(self, tr("Removable Drive?"), removable_warning, "warning")
except Exception as e:
logger.error(f"Errore durante controllo unità rimovibile: {e}")
# === INIZIO LOGICA CONTROLLO CONFLITTO USERNAME ===
# Carica identità utente corrente
identity = load_user_identity()
current_username = identity.get('username', '').strip().lower()
if not current_username:
logger.error("Username corrente non trovato nel config")
SimpleMessageDialog(
self,
tr("Error"),
tr("Unable to determine the current user. Restart DataFlow."),
"error"
)
return
# Variabili per gestione cambio username
final_username = current_username
username_changed = False
# Loop controllo conflitto username
while True:
# Controlla se esiste già un database con questo username nella destinazione
conflict_info = detect_username_conflict(
parent_dir=normalized_dir,
username=final_username,
logger=logger,
)
folder_exists = conflict_info["folder_exists"]
db_exists = conflict_info["db_exists"]
logger.info(f"Controllo conflitto per username '{final_username}': folder={folder_exists}, db={db_exists}")
# ✅ CORREZIONE LOGICA: Se ESISTE cartella O database, è un CONFLITTO
if folder_exists or db_exists:
# Conflitto rilevato: chiedi se vuole cambiare username
conflict_message = tr(
"⚠️ USER CONFLICT DETECTED\n\nA database associated with user '{}' already exists \nin the selected destination folder.\n\nTo avoid conflicts and data loss, you need to change \nyour username before proceeding.\n\nDo you want to proceed with the username change?"
).format(final_username)
dialog = SimpleYesNoDialog(
self,
tr("Username Conflict"),
conflict_message,
icon='warning'
)
if not dialog.result:
# Utente ha rifiutato, annulla tutto
logger.info("Utente ha rifiutato il cambio username, operazione annullata")
return
# Mostra dialogo cambio identità
self.withdraw() # Nascondi finestra settings temporaneamente
new_identity_dialog = UserIdentityDialog(self)
self.wait_window(new_identity_dialog)
self.deiconify() # Mostra di nuovo
new_identity = getattr(new_identity_dialog, 'result', None)
if not new_identity:
# Utente ha annullato il dialogo identità
logger.info("Utente ha annullato il dialogo identità, operazione annullata")
return
# Aggiorna username e continua il loop per ricontrollare
final_username = new_identity['username']
username_changed = True
logger.info(f"Nuovo username proposto: {final_username}, rientro nel loop controllo")
else:
# ✅ NESSUN CONFLITTO: Username libero, prosegui
logger.info(f"Username '{final_username}' disponibile nella destinazione (nessun conflitto rilevato)")
break
# === FINE LOGICA CONTROLLO CONFLITTO USERNAME ===
# A questo punto final_username è libero, procedi con la copia
source_folder = current_dataflow_dir
dest_parent = normalized_dir # Directory parent dove creare DataFlow_{username}
dest_folder = os.path.join(dest_parent, f"DataFlow_{final_username}") # Percorso completo destinazione
# Verifica che la cartella sorgente esista
if not os.path.exists(source_folder):
logger.error(f"Cartella sorgente non esiste: {source_folder}")
SimpleMessageDialog(
self,
tr("Error"),
tr("Source DataFlow folder not found:\n{}").format(source_folder),
"error"
)
return
# ✅ CHIUDI DATABASE PRIMA DELLA COPIA (evita WinError 32)
logger.info("Chiusura database prima della copia...")
try:
# Chiudi il DatabaseManager globale se esiste
if hasattr(self.main_app, 'db_manager') and self.main_app.db_manager:
self.main_app.db_manager.close()
logger.info("DatabaseManager principale chiuso")
except Exception as e:
logger.warning(f"Errore chiusura DatabaseManager: {e}")
# Mostra finestra progresso copia
progress_win = CopyProgressWindow(self, title=tr("Copying DataFlow..."))
progress_win.update_progress(0, tr("Preparing copy..."))
# Backup config originale (per rollback)
config_backup = None
try:
config_file = get_config_file()
if os.path.exists(config_file):
with open(config_file, 'r', encoding='utf-8') as f:
config_backup = f.read()
except Exception as e:
logger.error(f"Impossibile fare backup config: {e}")
try:
# === COPIA FISICA COMPLETA CON PROGRESSIONE ===
logger.info(f"Inizio copia da '{source_folder}' a '{dest_folder}'")
# Conta file totali per barra progresso
progress_win.update_progress(5, tr("Analyzing files to copy..."))
total_files = 0
for root, dirs, files in os.walk(source_folder):
total_files += len(files)
logger.info(f"File totali da copiare: {total_files}")
if total_files == 0:
raise Exception(tr("No files to copy in source folder"))
# Copia ricorsiva con aggiornamento progressione
files_copied = 0
def copy_with_progress(src, dst):
nonlocal files_copied
os.makedirs(dst, exist_ok=True)
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
copy_with_progress(s, d)
else:
# Copia file
shutil.copy2(s, d)
files_copied += 1
# Aggiorna progressione (da 10% a 80%)
progress_pct = 10 + int((files_copied / total_files) * 70)
file_name = os.path.basename(s)
progress_win.update_progress(
progress_pct,
tr("Copying file {}/{}: {}").format(files_copied, total_files, file_name[:40])
)
copy_with_progress(source_folder, dest_folder)
logger.info(f"Copia file completata: {files_copied} file copiati")
progress_win.update_progress(85, tr("Copy completed, updating configuration..."))
# === AGGIORNA USERNAME NEL DATABASE (SOLO SE CAMBIATO) ===
if username_changed:
logger.info(f"Username cambiato da '{current_username}' a '{final_username}', aggiorno database")
progress_win.update_progress(90, tr("Updating username in database..."))
# Percorso nuovo database
new_db_path = os.path.join(dest_folder, 'Database', f'dataflow_db_{final_username}.db')
# Rinomina anche il file database se necessario
old_db_name = f'dataflow_db_{current_username}.db'
old_db_path = os.path.join(dest_folder, 'Database', old_db_name)
if os.path.exists(old_db_path) and old_db_path != new_db_path:
logger.info(f"Rinomino database da '{old_db_name}' a 'dataflow_db_{final_username}.db'")
shutil.move(old_db_path, new_db_path)
# Aggiorna username in tutte le RdO
try:
# BUG #47 FIX: Usa context manager per garantire chiusura DB anche su eccezione
with DatabaseManager(new_db_path) as db_manager:
rows_updated = db_manager.update_all_usernames(final_username)
logger.info(f"Username aggiornato in {rows_updated} RdO")
except Exception as db_error:
logger.error(f"Errore aggiornamento username in DB: {db_error}", exc_info=True)
raise
# === AGGIORNA CONFIG.INI ===
progress_win.update_progress(95, tr("Saving configuration..."))
config = configparser.ConfigParser(interpolation=None)
config_file = get_config_file()
if os.path.exists(config_file):
config.read(config_file)
if 'Settings' not in config:
config['Settings'] = {}
if 'User' not in config:
config['User'] = {}
# Salva nuovo percorso base
config['Settings']['dataflow_base_dir'] = dest_parent
# Rimuovi legacy custom_db_path se presente
if config.has_option('Settings', 'custom_db_path'):
config.remove_option('Settings', 'custom_db_path')
# Se username è cambiato, aggiorna anche sezione User
if username_changed:
config['User']['first_name'] = new_identity['first_name']
config['User']['last_name'] = new_identity['last_name']
config['User']['username'] = final_username
with open(config_file, 'w', encoding='utf-8') as f:
config.write(f)
logger.info(f"Config aggiornato con nuovo percorso: {dest_parent}")
progress_win.update_progress(100, tr("Operation completed!"))
time.sleep(0.5)
progress_win.destroy()
# === MESSAGGIO SUCCESSO ===
username_info = ""
if username_changed:
username_info = tr("\n\n✓ Username updated from '{}' to '{}'").format(current_username, final_username)
success_msg = tr(
"✓ OPERATION COMPLETED SUCCESSFULLY\n\nThe DataFlow folder has been successfully copied to:\n{dest}\n\nFiles copied: {count}{username_change}\n\n⚠️ IMPORTANT:\n- The ORIGINAL folder in '{src}' has NOT been deleted.\n- Before deleting it manually, TEST the correct operation \n of the copied database.\n- DataFlow will restart automatically."
).format(
dest=dest_folder,
count=files_copied,
username_change=username_info,
src=source_folder
)
SimpleMessageDialog(self, tr("Operation Completed"), success_msg, "info")
# ✅ SALVA ESPLICITAMENTE LA NUOVA IDENTITÀ (se cambiata)
if username_changed:
save_user_identity(new_identity['first_name'], new_identity['last_name'], final_username)
logger.info(f"Identità salvata nel config: {final_username}")
# Invalida cache e riavvia
reset_db_cache()
logger.info("Cache DB invalidata, riavvio applicazione")
self.destroy()
self.main_app.restart_program()
except Exception as e:
# === GESTIONE ERRORE CON ROLLBACK ===
logger.error(f"Errore durante copia DataFlow: {e}", exc_info=True)
try:
progress_win.destroy()
except:
pass
# Ripristina config backup se disponibile
if config_backup:
try:
with open(get_config_file(), 'w', encoding='utf-8') as f:
f.write(config_backup)
logger.info("Config.ini ripristinato da backup")
except Exception as restore_err:
logger.error(f"Impossibile ripristinare config: {restore_err}")
# Tenta di eliminare cartella parziale (se creata)