-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase_manager.py
More file actions
3090 lines (2710 loc) · 141 KB
/
database_manager.py
File metadata and controls
3090 lines (2710 loc) · 141 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 sqlite3
import os
import glob
from datetime import datetime
# Eccezione personalizzata per isolare dipendenze dal database
class DatabaseError(Exception):
"""Eccezione generica per errori del database.
Questa classe isola il file principale dall'implementazione specifica
del database (duckdb), permettendo di gestire errori DB in modo generico.
"""
pass
class DatabaseManager:
def __init__(self, db_name="dataflow_db.db", read_only=False):
"""
Inizializza il gestore del database SQLite + WAL.
Accetta il nome del file del database.
Args:
db_name: Percorso al file database (estensione .db)
read_only: Se True, apre il database in modalità sola lettura (per concorrenza multi-utente WAL)
"""
self.db_name = db_name
self.read_only = read_only
self.conn = None
self.cursor = None
self.connect()
# BUG #44 FIX: Aggiunti metodi __enter__ e __exit__ per supportare context manager
def __enter__(self):
"""Context manager entry - ritorna se stesso per usare con 'with' statement"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit - garantisce chiusura connessione anche in caso di eccezioni"""
self.close()
# Ritorna False per propagare eventuali eccezioni
return False
def connect(self):
"""
Apre la connessione al database SQLite con WAL mode.
Configurazione ottimale per concorrenza multi-utente su rete.
"""
try:
# Apri connessione con URI mode per read-only se richiesto
if self.read_only:
# URI mode read-only per WAL concurrent access
uri = f"file:{self.db_name}?mode=ro"
self.conn = sqlite3.connect(uri, uri=True, timeout=10.0, check_same_thread=False)
else:
# Modalità read-write normale
self.conn = sqlite3.connect(self.db_name, timeout=10.0, check_same_thread=False, isolation_level=None)
# Configura WAL mode e ottimizzazioni (solo per read-write)
self.conn.execute("PRAGMA journal_mode=WAL")
self.conn.execute("PRAGMA synchronous=NORMAL")
self.conn.execute("PRAGMA wal_autocheckpoint=1000")
self.conn.execute("PRAGMA cache_size=-64000") # 64MB cache
self.conn.execute("PRAGMA temp_store=MEMORY")
# Busy timeout per gestire lock temporanei su rete
self.conn.execute("PRAGMA busy_timeout=10000") # 10 secondi
self.cursor = self.conn.cursor()
# SQLite row_factory per accesso dict-like
self.conn.row_factory = sqlite3.Row
except Exception as e:
raise DatabaseError(f"Errore di connessione al database: {e}") from e
def close(self):
"""
Chiude la connessione al database in modo sicuro.
"""
if self.conn:
self.conn.commit() # Salva eventuali modifiche pendenti
self.conn.close()
def get_connection(self):
"""
Restituisce l'oggetto connessione (utile per casi particolari)
"""
return self.conn
def _get_last_insert_id(self):
"""
Helper per ottenere l'ultimo ID inserito da SQLite.
SQLite supporta nativamente lastrowid.
"""
try:
if hasattr(self.cursor, 'lastrowid') and self.cursor.lastrowid is not None:
return self.cursor.lastrowid
return None
except Exception:
return None
def create_tables(self):
"""
Crea tutte le tabelle necessarie per l'applicazione DataFlow.
Include anche le migrazioni delle colonne esistenti.
"""
try:
# SQLite usa AUTOINCREMENT al posto delle sequenze DuckDB
# Non serve più creare sequenze separate
# Migrazione colonne per richieste_offerta
try:
self.cursor.execute("ALTER TABLE richieste_offerta ADD COLUMN stato VARCHAR NOT NULL DEFAULT 'attiva'")
except Exception:
pass
try:
self.cursor.execute("ALTER TABLE richieste_offerta ADD COLUMN numeri_ordine VARCHAR")
except Exception:
pass
try:
self.cursor.execute("ALTER TABLE richieste_offerta ADD COLUMN tipo_rdo VARCHAR NOT NULL DEFAULT 'Fornitura piena'")
except Exception:
pass
try:
self.cursor.execute("ALTER TABLE richieste_offerta ADD COLUMN note_formattate VARCHAR")
except Exception:
pass
try:
self.cursor.execute("ALTER TABLE richieste_offerta ADD COLUMN username VARCHAR")
except Exception:
pass
# Migrazione colonne per dettagli_richiesta
try:
self.cursor.execute("ALTER TABLE dettagli_richiesta ADD COLUMN disegno VARCHAR")
except Exception:
pass
try:
self.cursor.execute("ALTER TABLE dettagli_richiesta ADD COLUMN codice_grezzo VARCHAR")
except Exception:
pass
try:
self.cursor.execute("ALTER TABLE dettagli_richiesta ADD COLUMN disegno_grezzo VARCHAR")
except Exception:
pass
try:
self.cursor.execute("ALTER TABLE dettagli_richiesta ADD COLUMN materiale_conto_lavoro VARCHAR")
except Exception:
pass
# Creazione tabelle principali
# SQLite usa INTEGER PRIMARY KEY AUTOINCREMENT per auto-increment
self.cursor.execute('CREATE TABLE IF NOT EXISTS fornitori (id_fornitore INTEGER PRIMARY KEY AUTOINCREMENT, nome_fornitore VARCHAR NOT NULL UNIQUE)')
self.cursor.execute(''' CREATE TABLE IF NOT EXISTS richieste_offerta (id_richiesta INTEGER PRIMARY KEY AUTOINCREMENT, data_emissione VARCHAR, data_scadenza VARCHAR, riferimento VARCHAR, note_generali VARCHAR, stato VARCHAR NOT NULL DEFAULT 'attiva', numeri_ordine VARCHAR, tipo_rdo VARCHAR NOT NULL DEFAULT 'Fornitura piena', note_formattate VARCHAR, username VARCHAR) ''')
self.cursor.execute('''CREATE TABLE IF NOT EXISTS dettagli_richiesta (id_dettaglio INTEGER PRIMARY KEY AUTOINCREMENT, id_richiesta INTEGER, codice_materiale VARCHAR, descrizione_materiale VARCHAR, quantita VARCHAR, disegno VARCHAR, data_consegna_richiesta VARCHAR, codice_grezzo VARCHAR, disegno_grezzo VARCHAR, materiale_conto_lavoro VARCHAR, FOREIGN KEY (id_richiesta) REFERENCES richieste_offerta (id_richiesta))''')
self.cursor.execute('''CREATE TABLE IF NOT EXISTS richiesta_fornitori (id_richiesta INTEGER, nome_fornitore VARCHAR, PRIMARY KEY (id_richiesta, nome_fornitore), FOREIGN KEY (id_richiesta) REFERENCES richieste_offerta (id_richiesta))''')
# Migrazione e creazione tabella offerte_ricevute con prezzo_unitario VARCHAR
try:
# SQLite usa PRAGMA table_info invece di DESCRIBE
self.cursor.execute("PRAGMA table_info(offerte_ricevute)")
cols = self.cursor.fetchall()
# In SQLite, PRAGMA table_info ritorna: (cid, name, type, notnull, dflt_value, pk)
prezzo_col_info = next((c for c in cols if c[1] == 'prezzo_unitario'), None)
if prezzo_col_info and ('DOUBLE' in str(prezzo_col_info[2]).upper() or 'REAL' in str(prezzo_col_info[2]).upper()):
print("Avvio migrazione tabella 'offerte_ricevute' per prezzi testuali...")
self.cursor.execute("ALTER TABLE offerte_ricevute RENAME TO _offerte_ricevute_old;")
self.cursor.execute('''CREATE TABLE offerte_ricevute (id_dettaglio INTEGER, nome_fornitore VARCHAR, prezzo_unitario VARCHAR, PRIMARY KEY (id_dettaglio, nome_fornitore), FOREIGN KEY (id_dettaglio) REFERENCES dettagli_richiesta (id_dettaglio))''')
self.cursor.execute("INSERT INTO offerte_ricevute (id_dettaglio, nome_fornitore, prezzo_unitario) SELECT id_dettaglio, nome_fornitore, prezzo_unitario FROM _offerte_ricevute_old;")
self.cursor.execute("DROP TABLE _offerte_ricevute_old;")
self.conn.commit()
print("Migrazione completata.")
except Exception as e:
if "Table" not in str(e) or "does not exist" not in str(e):
print(f"Nota: impossibile eseguire la migrazione della tabella offerte_ricevute. Errore: {e}")
self.cursor.execute('''CREATE TABLE IF NOT EXISTS offerte_ricevute (id_dettaglio INTEGER, nome_fornitore VARCHAR, prezzo_unitario VARCHAR, PRIMARY KEY (id_dettaglio, nome_fornitore), FOREIGN KEY (id_dettaglio) REFERENCES dettagli_richiesta (id_dettaglio))''')
self.cursor.execute('''CREATE TABLE IF NOT EXISTS allegati_richiesta (id_allegato INTEGER PRIMARY KEY AUTOINCREMENT, id_richiesta INTEGER, nome_file VARCHAR, dati_file BLOB, tipo_allegato VARCHAR, nome_fornitore VARCHAR, percorso_esterno VARCHAR, data_inserimento VARCHAR DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (id_richiesta) REFERENCES richieste_offerta (id_richiesta))''')
# Migrazione colonna percorso_esterno
try:
self.cursor.execute("ALTER TABLE allegati_richiesta ADD COLUMN percorso_esterno VARCHAR")
except Exception:
pass
# Migrazione colonna data_inserimento con controllo
try:
# SQLite usa PRAGMA table_info invece di DESCRIBE
self.cursor.execute("PRAGMA table_info(allegati_richiesta)")
columns = [column[1] for column in self.cursor.fetchall()] # column[1] è il nome in SQLite
if 'data_inserimento' not in columns:
self.cursor.execute("ALTER TABLE allegati_richiesta ADD COLUMN data_inserimento VARCHAR DEFAULT CURRENT_TIMESTAMP")
# Aggiorna i record esistenti con la data corrente
self.cursor.execute("UPDATE allegati_richiesta SET data_inserimento = CURRENT_TIMESTAMP WHERE data_inserimento IS NULL")
except Exception:
pass # Colonna già esistente
# ========== TABELLE VSM (Value Stream Mapping) ==========
# Tabella eventi VSM
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS vsm_events (
event_id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
event_date TEXT,
buyer TEXT,
event_type TEXT,
action TEXT,
description TEXT,
reference TEXT,
importo_bdg REAL,
importo_negoziato REAL,
importo_richiesto_iniziale REAL,
quantita_annua REAL,
percent_realizzo REAL,
driver TEXT,
giorni_pagamento_attuali INTEGER,
giorni_pagamento_negoziati INTEGER,
spending_annuo REAL,
opex_ripetitivo INTEGER NOT NULL DEFAULT 0,
note TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (username) REFERENCES utenti(username)
)
''')
# Tabella impatti mensili VSM
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS vsm_impacts (
impact_id INTEGER PRIMARY KEY AUTOINCREMENT,
event_id INTEGER NOT NULL,
username TEXT NOT NULL,
anno INTEGER NOT NULL,
mese INTEGER NOT NULL,
tipo_valore TEXT NOT NULL,
valore_teorico REAL NOT NULL,
valore_effettivo REAL NOT NULL,
FOREIGN KEY (event_id) REFERENCES vsm_events(event_id),
FOREIGN KEY (username) REFERENCES utenti(username)
)
''')
# Migrazione colonna payments_rate per vsm_events
try:
self.cursor.execute("ALTER TABLE vsm_events ADD COLUMN payments_rate REAL")
except Exception:
pass
# Migrazione colonna new_supplier per vsm_events
try:
self.cursor.execute("ALTER TABLE vsm_events ADD COLUMN new_supplier TEXT DEFAULT ''")
except Exception:
pass
# Indici per performance VSM
self.cursor.execute('CREATE INDEX IF NOT EXISTS idx_vsm_impacts_event_id ON vsm_impacts(event_id)')
self.cursor.execute('CREATE INDEX IF NOT EXISTS idx_vsm_impacts_period ON vsm_impacts(anno, mese)')
self.cursor.execute('CREATE INDEX IF NOT EXISTS idx_vsm_impacts_username ON vsm_impacts(username)')
self.cursor.execute('CREATE INDEX IF NOT EXISTS idx_vsm_events_username ON vsm_events(username)')
# ========== TABELLA FORNITORI POTENZIALI (Derisking anagrafica) ==========
# Entità separata da vsm_events: nessun legame con il flusso VSM.
# Migrazione conservativa: CREATE TABLE IF NOT EXISTS + ALTER TABLE IF NOT EXISTS.
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS potential_suppliers (
supplier_id INTEGER PRIMARY KEY AUTOINCREMENT,
supplier_name TEXT NOT NULL,
macrocategory TEXT NOT NULL DEFAULT '',
merchandise_class TEXT NOT NULL DEFAULT '',
supplier_status TEXT NOT NULL DEFAULT 'Prospect',
contact_name TEXT NOT NULL DEFAULT '',
email TEXT NOT NULL DEFAULT '',
phone TEXT NOT NULL DEFAULT '',
website TEXT NOT NULL DEFAULT '',
notes TEXT NOT NULL DEFAULT '',
username TEXT NOT NULL DEFAULT '',
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
)
''')
# Indici per performance fornitori potenziali
self.cursor.execute(
'CREATE INDEX IF NOT EXISTS idx_ps_username ON potential_suppliers(username)'
)
self.cursor.execute(
'CREATE INDEX IF NOT EXISTS idx_ps_macrocategory ON potential_suppliers(macrocategory)'
)
self.cursor.execute(
'CREATE INDEX IF NOT EXISTS idx_ps_status ON potential_suppliers(supplier_status)'
)
# Migrazione conservativa: aggiunge colonna category (idempotente)
self.cursor.execute("PRAGMA table_info(potential_suppliers)")
existing_cols = {row[1] for row in self.cursor.fetchall()}
if 'category' not in existing_cols:
self.cursor.execute(
"ALTER TABLE potential_suppliers ADD COLUMN category TEXT NOT NULL DEFAULT ''"
)
self.cursor.execute(
"UPDATE potential_suppliers SET category = macrocategory "
"WHERE category = '' OR category IS NULL"
)
self.cursor.execute(
'CREATE INDEX IF NOT EXISTS idx_ps_category ON potential_suppliers(category)'
)
# Migrazione conservativa: aggiunge colonna created_at se non esiste.
# I record preesistenti restano con created_at = NULL (comportamento voluto):
# non vengono falsificate date storiche. I nuovi record ricevono la data
# corrente esplicitamente in insert_potential_supplier.
if 'created_at' not in existing_cols:
self.cursor.execute(
"ALTER TABLE potential_suppliers ADD COLUMN created_at TEXT DEFAULT NULL"
)
self.cursor.execute(
'CREATE INDEX IF NOT EXISTS idx_ps_created_at ON potential_suppliers(created_at)'
)
# ========== TABELLA CATEGORIE FORNITORI POTENZIALI ==========
# Anagrafica centrale delle categorie. supplier_categories.name è il catalogo
# ufficiale. potential_suppliers.category resta TEXT (nessun FK).
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS supplier_categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE
)
''')
# Migrazione idempotente: importa categorie già presenti nei supplier
self.cursor.execute(
"""
INSERT OR IGNORE INTO supplier_categories (name)
SELECT DISTINCT TRIM(category)
FROM potential_suppliers
WHERE category IS NOT NULL AND TRIM(category) != ''
"""
)
# Commit finale
self.conn.commit()
except Exception as e:
raise DatabaseError(f"Errore durante la creazione delle tabelle: {e}") from e
# ========== METODI INSERT ==========
def insert_allegato_richiesta_link(self, id_richiesta, nome_file, tipo_allegato, nome_fornitore, percorso_esterno):
"""Inserisce un allegato salvato come link esterno."""
try:
# SQLite usa lastrowid invece di RETURNING
self.cursor.execute(
"INSERT INTO allegati_richiesta (id_richiesta, nome_file, dati_file, tipo_allegato, nome_fornitore, percorso_esterno) VALUES (?, ?, NULL, ?, ?, ?)",
(id_richiesta, nome_file, tipo_allegato, nome_fornitore, percorso_esterno)
)
self.conn.commit()
return self._get_last_insert_id()
except Exception as e:
print(f"[DB Manager] Errore insert_allegato_richiesta_link: {e}")
raise DatabaseError(str(e)) from e
def insert_allegato_richiesta_blob(self, id_richiesta, nome_file, dati_file, tipo_allegato, nome_fornitore):
"""Inserisce un allegato salvato come BLOB nel database."""
try:
# SQLite usa lastrowid invece di RETURNING
self.cursor.execute(
"INSERT INTO allegati_richiesta (id_richiesta, nome_file, dati_file, tipo_allegato, nome_fornitore) VALUES (?, ?, ?, ?, ?)",
(id_richiesta, nome_file, dati_file, tipo_allegato, nome_fornitore)
)
self.conn.commit()
return self._get_last_insert_id()
except Exception as e:
print(f"[DB Manager] Errore insert_allegato_richiesta_blob: {e}")
raise DatabaseError(str(e)) from e
def insert_richiesta_fornitore(self, id_richiesta, nome_fornitore):
"""Inserisce un fornitore associato a una richiesta."""
try:
self.cursor.execute(
"INSERT INTO richiesta_fornitori (id_richiesta, nome_fornitore) VALUES (?, ?)",
(id_richiesta, nome_fornitore)
)
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore insert_richiesta_fornitore: {e}")
raise DatabaseError(str(e)) from e
def insert_dettaglio_richiesta(self, id_richiesta, codice_materiale='', disegno='', descrizione_materiale='',
quantita='', codice_grezzo='', disegno_grezzo='', materiale_conto_lavoro=''):
"""Inserisce un nuovo dettaglio/articolo in una richiesta."""
try:
# SQLite usa lastrowid invece di RETURNING
self.cursor.execute("""
INSERT INTO dettagli_richiesta
(id_richiesta, codice_materiale, disegno, descrizione_materiale, quantita,
codice_grezzo, disegno_grezzo, materiale_conto_lavoro)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", (id_richiesta, codice_materiale, disegno, descrizione_materiale, quantita,
codice_grezzo, disegno_grezzo, materiale_conto_lavoro))
self.conn.commit()
return self._get_last_insert_id()
except Exception as e:
print(f"[DB Manager] Errore insert_dettaglio_richiesta: {e}")
raise DatabaseError(str(e)) from e
def insert_richiesta_offerta(self, tipo_rdo, stato, data_emissione, username=None):
"""Inserisce una nuova richiesta d'offerta calcolando l'ID basato sull'anno."""
try:
username_value = username.strip().lower() if isinstance(username, str) and username.strip() else None
# --- LOGICA YEAR-DRIVEN ID ---
# 1. Calcola la base per l'anno corrente (es. 2025 -> 2500000)
yy = int(datetime.now().strftime('%y'))
min_id_for_year = yy * 100000
# 2. Trova il max ID attuale nel database
# Usa conn.execute per DuckDB
res = self.conn.execute("SELECT MAX(id_richiesta) FROM richieste_offerta").fetchone()
max_id_esistente = res[0] if res and res[0] is not None else 0
# 3. Il nuovo ID è il maggiore tra (Base Anno) e (Max Esistente + 1)
# Se siamo nel nuovo anno, min_id_for_year vincerà su un vecchio ID basso.
# Se siamo nello stesso anno, max_id + 1 vincerà.
next_id = max(min_id_for_year, max_id_esistente + 1)
# 4. Insert Esplicito passando l'ID calcolato
query = """
INSERT INTO richieste_offerta
(id_richiesta, tipo_rdo, stato, data_emissione, username)
VALUES (?, ?, ?, ?, ?)
"""
self.cursor.execute(query, (next_id, tipo_rdo, stato, data_emissione, username_value))
self.conn.commit()
print(f"[DB Manager] Nuova RdO creata con ID Year-Driven: {next_id}")
return next_id
except Exception as e:
print(f"[DB Manager] Errore insert_richiesta_offerta: {e}")
raise DatabaseError(str(e)) from e
def insert_richiesta_offerta_completa(self, columns, values):
"""Inserisce una richiesta d'offerta con colonne personalizzate (per duplicazione)."""
try:
placeholders = ', '.join(['?'] * len(columns))
# SQLite usa lastrowid invece di RETURNING
sql = f"INSERT INTO richieste_offerta ({', '.join(columns)}) VALUES ({placeholders})"
self.cursor.execute(sql, values)
self.conn.commit()
return self._get_last_insert_id()
except Exception as e:
print(f"[DB Manager] Errore insert_richiesta_offerta_completa: {e}")
raise DatabaseError(str(e)) from e
def insert_dettaglio_richiesta_completo(self, id_richiesta, columns, values):
"""Inserisce un dettaglio richiesta con colonne personalizzate (per duplicazione)."""
try:
placeholders = ', '.join(['?'] * (len(columns) + 1))
sql = f"INSERT INTO dettagli_richiesta (id_richiesta, {', '.join(columns)}) VALUES ({placeholders})"
self.cursor.execute(sql, [id_richiesta, *values])
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore insert_dettaglio_richiesta_completo: {e}")
raise DatabaseError(str(e)) from e
# ========== METODI UPDATE ==========
def update_numeri_ordine(self, id_richiesta, numeri_ordine_json):
"""Aggiorna i numeri ordine di una richiesta (salvati come JSON)."""
try:
self.cursor.execute(
"UPDATE richieste_offerta SET numeri_ordine = ? WHERE id_richiesta = ?",
(numeri_ordine_json, id_richiesta)
)
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore update_numeri_ordine: {e}")
raise DatabaseError(str(e)) from e
def update_riferimento(self, id_richiesta, riferimento):
"""Aggiorna il riferimento di una richiesta."""
try:
self.cursor.execute(
"UPDATE richieste_offerta SET riferimento = ? WHERE id_richiesta = ?",
(riferimento, id_richiesta)
)
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore update_riferimento: {e}")
raise DatabaseError(str(e)) from e
def update_note_formattate(self, id_richiesta, note_formattate):
"""Aggiorna le note formattate di una richiesta."""
try:
self.cursor.execute(
"UPDATE richieste_offerta SET note_formattate = ? WHERE id_richiesta = ?",
(note_formattate, id_richiesta)
)
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore update_note_formattate: {e}")
raise DatabaseError(str(e)) from e
def update_request_username(self, id_richiesta, username):
"""Aggiorna lo username associato a una RdO."""
try:
username_value = username.strip().lower() if isinstance(username, str) and username.strip() else None
self.cursor.execute(
"UPDATE richieste_offerta SET username = ? WHERE id_richiesta = ?",
(username_value, id_richiesta)
)
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore update_request_username: {e}")
raise DatabaseError(str(e)) from e
def update_all_usernames(self, new_username):
"""Aggiorna lo username in TUTTE le RdO del database.
Usato quando si cambia identità utente durante spostamento cartella.
Args:
new_username: Nuovo username da impostare
Returns:
int: Numero di righe aggiornate
"""
try:
username_value = new_username.strip().lower() if isinstance(new_username, str) and new_username.strip() else None
# Prima conta le righe totali
count_result = self.cursor.execute("SELECT COUNT(*) FROM richieste_offerta").fetchone()
total_rows = count_result[0] if count_result else 0
# Aggiorna tutte le righe
self.cursor.execute(
"UPDATE richieste_offerta SET username = ?",
(username_value,)
)
self.conn.commit()
print(f"[DB Manager] Aggiornate {total_rows} RdO con nuovo username: {username_value}")
return total_rows
except Exception as e:
print(f"[DB Manager] Errore update_all_usernames: {e}")
raise DatabaseError(str(e)) from e
def update_allegato_blob(self, id_allegato, dati_file):
"""Aggiorna i dati BLOB di un allegato esistente."""
try:
self.cursor.execute(
"UPDATE allegati_richiesta SET dati_file = ? WHERE id_allegato = ?",
(dati_file, id_allegato)
)
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore update_allegato_blob: {e}")
raise DatabaseError(str(e)) from e
def update_date_richiesta(self, id_richiesta, data_emissione, data_scadenza):
"""Aggiorna le date di emissione e scadenza di una richiesta."""
try:
self.cursor.execute(
"UPDATE richieste_offerta SET data_emissione = ?, data_scadenza = ? WHERE id_richiesta = ?",
(data_emissione, data_scadenza, id_richiesta)
)
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore update_date_richiesta: {e}")
raise DatabaseError(str(e)) from e
def update_dettaglio_field(self, id_dettaglio, field_name, value):
"""Aggiorna un campo specifico di un dettaglio richiesta."""
try:
sql = f"UPDATE dettagli_richiesta SET {field_name} = ? WHERE id_dettaglio = ?"
self.cursor.execute(sql, (value, id_dettaglio))
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore update_dettaglio_field: {e}")
raise DatabaseError(str(e)) from e
def update_allegato_to_link(self, id_allegato, percorso_esterno):
"""Converte un allegato da BLOB a link esterno."""
try:
self.cursor.execute(
"UPDATE allegati_richiesta SET dati_file = NULL, percorso_esterno = ? WHERE id_allegato = ?",
(percorso_esterno, id_allegato)
)
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore update_allegato_to_link: {e}")
raise DatabaseError(str(e)) from e
def update_stato_richieste(self, params_list):
"""Aggiorna lo stato di multiple richieste in batch."""
try:
self.cursor.executemany(
"UPDATE richieste_offerta SET stato = ? WHERE id_richiesta = ?",
params_list
)
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore update_stato_richieste: {e}")
raise DatabaseError(str(e)) from e
def renumber_richieste(self, old_ids, offset):
"""Rinumera tutte le richieste aggiungendo un offset agli ID."""
try:
# DuckDB gestisce automaticamente le foreign keys, non serve PRAGMA
self.cursor.execute("BEGIN TRANSACTION")
for old_id in old_ids:
new_id = old_id + offset
self.cursor.execute("UPDATE richieste_offerta SET id_richiesta = ? WHERE id_richiesta = ?", (new_id, old_id))
self.cursor.execute("UPDATE dettagli_richiesta SET id_richiesta = ? WHERE id_richiesta = ?", (new_id, old_id))
self.cursor.execute("UPDATE richiesta_fornitori SET id_richiesta = ? WHERE id_richiesta = ?", (new_id, old_id))
self.cursor.execute("UPDATE allegati_richiesta SET id_richiesta = ? WHERE id_richiesta = ?", (new_id, old_id))
# DuckDB non ha sqlite_sequence, gli auto-increment sono gestiti automaticamente
self.conn.commit()
except Exception as e:
self.conn.rollback()
print(f"[DB Manager] Errore renumber_richieste: {e}")
raise DatabaseError(str(e)) from e
# ========== METODI DELETE ==========
def delete_allegato(self, id_allegato):
"""Elimina un allegato."""
try:
self.cursor.execute("DELETE FROM allegati_richiesta WHERE id_allegato = ?", (id_allegato,))
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore delete_allegato: {e}")
raise DatabaseError(str(e)) from e
def delete_offerta_by_dettaglio_fornitore(self, id_dettaglio, nome_fornitore):
"""Elimina un'offerta ricevuta per un dettaglio e fornitore specifici."""
try:
self.cursor.execute(
"DELETE FROM offerte_ricevute WHERE id_dettaglio = ? AND nome_fornitore = ?",
(id_dettaglio, nome_fornitore)
)
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore delete_offerta_by_dettaglio_fornitore: {e}")
raise DatabaseError(str(e)) from e
def delete_fornitori_by_richiesta(self, id_richiesta):
"""Elimina tutti i fornitori associati a una richiesta."""
try:
self.cursor.execute("DELETE FROM richiesta_fornitori WHERE id_richiesta = ?", (id_richiesta,))
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore delete_fornitori_by_richiesta: {e}")
raise DatabaseError(str(e)) from e
def delete_offerte_by_dettaglio(self, id_dettaglio):
"""Elimina tutte le offerte associate a un dettaglio."""
try:
self.cursor.execute("DELETE FROM offerte_ricevute WHERE id_dettaglio = ?", (id_dettaglio,))
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore delete_offerte_by_dettaglio: {e}")
raise DatabaseError(str(e)) from e
def delete_dettaglio(self, id_dettaglio):
"""Elimina un dettaglio richiesta."""
try:
self.cursor.execute("DELETE FROM dettagli_richiesta WHERE id_dettaglio = ?", (id_dettaglio,))
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore delete_dettaglio: {e}")
raise DatabaseError(str(e)) from e
def delete_richiesta_completa(self, id_richiesta):
"""Elimina una richiesta e tutti i dati correlati (offerte, allegati, fornitori, dettagli)."""
try:
self.cursor.execute("BEGIN TRANSACTION")
self.cursor.execute("DELETE FROM offerte_ricevute WHERE id_dettaglio IN (SELECT id_dettaglio FROM dettagli_richiesta WHERE id_richiesta = ?)", (id_richiesta,))
self.cursor.execute("DELETE FROM allegati_richiesta WHERE id_richiesta = ?", (id_richiesta,))
self.cursor.execute("DELETE FROM richiesta_fornitori WHERE id_richiesta = ?", (id_richiesta,))
self.cursor.execute("DELETE FROM dettagli_richiesta WHERE id_richiesta = ?", (id_richiesta,))
self.cursor.execute("DELETE FROM richieste_offerta WHERE id_richiesta = ?", (id_richiesta,))
self.conn.commit()
except Exception as e:
self.conn.rollback()
print(f"[DB Manager] Errore delete_richiesta_completa: {e}")
raise DatabaseError(str(e)) from e
# ========== METODI TRANSAZIONALI COMPLESSI ==========
def update_fornitori_richiesta(self, id_richiesta, new_suppliers, detail_ids):
"""
Aggiorna l'elenco fornitori di una richiesta.
Elimina offerte dei fornitori rimossi e ricrea la lista fornitori.
"""
try:
self.cursor.execute("BEGIN TRANSACTION")
# Ottieni fornitori attuali
self.cursor.execute("SELECT nome_fornitore FROM richiesta_fornitori WHERE id_richiesta = ?", (id_richiesta,))
old_suppliers = {row[0] for row in self.cursor.fetchall()}
removed_suppliers = old_suppliers - set(new_suppliers)
# Elimina offerte dei fornitori rimossi
for supplier in removed_suppliers:
for detail_id in detail_ids:
self.cursor.execute(
"DELETE FROM offerte_ricevute WHERE id_dettaglio = ? AND nome_fornitore = ?",
(detail_id, supplier)
)
# Elimina TUTTI i fornitori esistenti
self.cursor.execute("DELETE FROM richiesta_fornitori WHERE id_richiesta = ?", (id_richiesta,))
# Inserisci solo i nuovi fornitori
for s in new_suppliers:
self.cursor.execute(
"INSERT INTO richiesta_fornitori (id_richiesta, nome_fornitore) VALUES (?, ?)",
(id_richiesta, s)
)
self.conn.commit()
except Exception as e:
self.conn.rollback()
print(f"[DB Manager] Errore update_fornitori_richiesta: {e}")
raise DatabaseError(str(e)) from e
def insert_or_update_allegato_sqdc(self, id_richiesta, sqdc_filename, percorso_esterno):
"""Inserisce o aggiorna un allegato SQDC (Documento Interno) con link esterno.
Args:
id_richiesta: ID della richiesta
sqdc_filename: Nome visualizzato del file (es. SQDC_RdO_123.xlsx)
percorso_esterno: Nome del file fisico nella cartella Attachments (es. RDO123_Interno_ID456.xlsx)
"""
try:
# BUG FIX: Controlla se esiste già un SQDC specifico (non qualsiasi Documento Interno)
# Identifica gli SQDC dal nome file che inizia con "SQDC_"
self.cursor.execute(
"SELECT id_allegato FROM allegati_richiesta WHERE id_richiesta = ? AND tipo_allegato = 'Documento Interno' AND nome_file LIKE 'SQDC_%'",
(id_richiesta,)
)
existing = self.cursor.fetchone()
if existing:
# Aggiorna esistente con nuovo link esterno
self.cursor.execute(
"UPDATE allegati_richiesta SET nome_file = ?, percorso_esterno = ?, dati_file = NULL WHERE id_allegato = ?",
(sqdc_filename, percorso_esterno, existing[0])
)
else:
# Inserisci nuovo con link esterno (come tutti gli altri allegati)
self.cursor.execute(
"INSERT INTO allegati_richiesta (id_richiesta, nome_file, dati_file, tipo_allegato, nome_fornitore, percorso_esterno) VALUES (?, ?, NULL, ?, ?, ?)",
(id_richiesta, sqdc_filename, "Documento Interno", "Interno", percorso_esterno)
)
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore insert_or_update_allegato_sqdc: {e}")
raise DatabaseError(str(e)) from e
def delete_dettagli_batch(self, detail_ids):
"""Elimina multiple righe di dettaglio e le relative offerte in batch."""
try:
# DuckDB: NON usiamo BEGIN TRANSACTION esplicito
# Lasciamo che DuckDB gestisca automaticamente le transazioni
# Usa conn.execute() invece di cursor.execute() per garantire persistenza
# Elimina prima i prezzi associati
for detail_id in detail_ids:
self.conn.execute("DELETE FROM offerte_ricevute WHERE id_dettaglio = ?", (detail_id,))
# Poi elimina gli articoli
for detail_id in detail_ids:
self.conn.execute("DELETE FROM dettagli_richiesta WHERE id_dettaglio = ?", (detail_id,))
# Forza commit esplicito per garantire persistenza
self.conn.commit()
print(f"[DB Manager] COMMIT eseguito per eliminazione di {len(detail_ids)} dettagli")
return len(detail_ids)
except Exception as e:
# Se c'è un errore, prova a fare rollback
try:
self.conn.rollback()
except Exception as rollback_error:
# Se il rollback fallisce, non è critico
print(f"[DB Manager] Nota: Impossibile eseguire rollback: {rollback_error}")
print(f"[DB Manager] Errore delete_dettagli_batch: {e}")
raise DatabaseError(str(e)) from e
def import_dettagli_from_list(self, id_richiesta, items_list):
"""Importa una lista di dettagli da Excel in batch."""
try:
# DuckDB: NON usiamo BEGIN TRANSACTION esplicito
# Lasciamo che DuckDB gestisca automaticamente le transazioni
# Questo dovrebbe garantire che il commit sia persistente
inserted_count = 0
for cod, allegato, desc, qta, cod_grezzo, dis_grezzo, mat_cl in items_list:
# Usa conn.execute() invece di cursor.execute() per garantire persistenza
self.conn.execute("""
INSERT INTO dettagli_richiesta
(id_richiesta, codice_materiale, disegno, descrizione_materiale, quantita,
codice_grezzo, disegno_grezzo, materiale_conto_lavoro)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", (id_richiesta, cod, allegato, desc, qta, cod_grezzo, dis_grezzo, mat_cl))
inserted_count += 1
# Forza commit esplicito per garantire persistenza
self.conn.commit()
print(f"[DB Manager] COMMIT eseguito per importazione richiesta {id_richiesta}")
# Verifica che i dati siano stati effettivamente salvati nella stessa connessione
result = self.conn.execute(
"SELECT COUNT(*) FROM dettagli_richiesta WHERE id_richiesta = ?",
(id_richiesta,)
).fetchone()
total_count = result[0] if result else 0
print(f"[DB Manager] import_dettagli_from_list: Inseriti {inserted_count} articoli per richiesta {id_richiesta}. Totale articoli nella richiesta: {total_count}")
# IMPORTANTE: Non chiudere la connessione qui - lasciala aperta
# DuckDB dovrebbe persistere i dati automaticamente dopo il commit
# Chiudere la connessione qui potrebbe causare problemi di persistenza
return inserted_count
except Exception as e:
# Se c'è un errore, prova a fare rollback
try:
self.conn.rollback()
except Exception as rollback_error:
# Se il rollback fallisce, non è critico
print(f"[DB Manager] Nota: Impossibile eseguire rollback: {rollback_error}")
print(f"[DB Manager] Errore import_dettagli_from_list: {e}")
raise DatabaseError(str(e)) from e
def delete_richieste_batch(self, request_ids):
"""Elimina multiple richieste in batch con tutti i dati correlati."""
try:
# DuckDB: NON usiamo BEGIN TRANSACTION esplicito
# Lasciamo che DuckDB gestisca automaticamente le transazioni
# Usa conn.execute() invece di cursor.execute() per garantire persistenza
print(f"[DB Manager] delete_richieste_batch: Eliminazione di {len(request_ids)} richieste: {request_ids}")
for req_id in request_ids:
# Elimina prima i dati correlati (offerte, allegati, fornitori, dettagli)
self.conn.execute("DELETE FROM offerte_ricevute WHERE id_dettaglio IN (SELECT id_dettaglio FROM dettagli_richiesta WHERE id_richiesta = ?)", (req_id,))
self.conn.execute("DELETE FROM allegati_richiesta WHERE id_richiesta = ?", (req_id,))
self.conn.execute("DELETE FROM richiesta_fornitori WHERE id_richiesta = ?", (req_id,))
self.conn.execute("DELETE FROM dettagli_richiesta WHERE id_richiesta = ?", (req_id,))
# Elimina infine la richiesta principale
self.conn.execute("DELETE FROM richieste_offerta WHERE id_richiesta = ?", (req_id,))
print(f"[DB Manager] Eliminata richiesta {req_id}")
# Forza commit esplicito per garantire persistenza
self.conn.commit()
print(f"[DB Manager] COMMIT eseguito per eliminazione di {len(request_ids)} richieste")
# Verifica che le richieste siano state effettivamente eliminate
for req_id in request_ids:
result = self.conn.execute("SELECT COUNT(*) FROM richieste_offerta WHERE id_richiesta = ?", (req_id,)).fetchone()
count = result[0] if result else 0
if count > 0:
print(f"[DB Manager] WARNING: Richiesta {req_id} non è stata eliminata (ancora presente nel database)")
else:
print(f"[DB Manager] Verificato: Richiesta {req_id} eliminata correttamente")
return len(request_ids)
except Exception as e:
# Se c'è un errore, prova a fare rollback solo se c'è una transazione attiva
try:
self.conn.rollback()
except Exception as rollback_error:
# Se il rollback fallisce, non è critico - potrebbe non esserci transazione attiva
print(f"[DB Manager] Nota: Impossibile eseguire rollback: {rollback_error}")
print(f"[DB Manager] Errore delete_richieste_batch: {e}")
raise DatabaseError(str(e)) from e
# ========== METODI PER GESTIONE PREZZI/OFFERTE ==========
def insert_or_replace_offerta(self, id_dettaglio, nome_fornitore, prezzo_unitario):
"""Inserisce o sostituisce un'offerta ricevuta (prezzo)."""
try:
# SQLite: ON CONFLICT gestisce i duplicati
self.cursor.execute(
"INSERT INTO offerte_ricevute (id_dettaglio, nome_fornitore, prezzo_unitario) VALUES (?, ?, ?) ON CONFLICT (id_dettaglio, nome_fornitore) DO UPDATE SET prezzo_unitario = excluded.prezzo_unitario",
(id_dettaglio, nome_fornitore, prezzo_unitario)
)
self.conn.commit()
except Exception as e:
print(f"[DB Manager] Errore insert_or_replace_offerta: {e}")
raise DatabaseError(str(e)) from e
# ========== METODI PER ARCHIVIAZIONE ALLEGATI ==========
def get_allegati_to_archive(self):
"""Recupera tutti gli allegati con dati BLOB da archiviare."""
try:
self.cursor.execute(
"SELECT id_allegato, id_richiesta, nome_fornitore, nome_file, dati_file FROM allegati_richiesta WHERE dati_file IS NOT NULL AND LENGTH(dati_file) > 0"
)
return self.cursor.fetchall()
except Exception as e:
print(f"[DB Manager] Errore get_allegati_to_archive: {e}")
raise DatabaseError(str(e)) from e
def archive_allegati_batch(self, allegati_updates):
"""
Archivia un batch di allegati convertendoli da BLOB a link.
allegati_updates: lista di tuple (percorso_esterno, id_allegato)
"""
try:
self.cursor.execute("BEGIN TRANSACTION")
for percorso_esterno, id_allegato in allegati_updates:
self.cursor.execute(
"UPDATE allegati_richiesta SET dati_file = NULL, percorso_esterno = ? WHERE id_allegato = ?",
(percorso_esterno, id_allegato)
)
self.conn.commit()
return len(allegati_updates)
except Exception as e:
self.conn.rollback()
print(f"[DB Manager] Errore archive_allegati_batch: {e}")
raise DatabaseError(str(e)) from e
# ========== METODI PER DUPLICAZIONE ==========
def duplicate_richiesta_dettagli(self, original_id, new_request_id, detail_columns, detail_rows):
"""Duplica i dettagli di una richiesta."""
try:
# SQLite: conn.execute è equivalente a cursor.execute, entrambi funzionano
placeholders = ', '.join(['?'] * (len(detail_columns) + 1))
insert_sql = f"INSERT INTO dettagli_richiesta (id_richiesta, {', '.join(detail_columns)}) VALUES ({placeholders})"
for detail in detail_rows:
self.conn.execute(insert_sql, [new_request_id, *detail])
# Il commit sarà fatto dal metodo chiamante (duplicate_richiesta_full)
# Non facciamo commit qui per evitare commit multipli
print(f"[DB Manager] Duplicati {len(detail_rows)} dettagli per richiesta {new_request_id}")
except Exception as e:
print(f"[DB Manager] Errore duplicate_richiesta_dettagli: {e}")
raise DatabaseError(str(e)) from e
# ========== METODI SELECT (LETTURA) ==========
def get_allegati_by_richiesta(self, id_richiesta, tipo_allegato, has_date_column=True):
"""Recupera allegati per richiesta e tipo."""
try:
if has_date_column:
self.cursor.execute(
"SELECT id_allegato, nome_fornitore, nome_file, data_inserimento FROM allegati_richiesta WHERE id_richiesta = ? AND tipo_allegato = ?",
(id_richiesta, tipo_allegato)
)
else:
self.cursor.execute(
"SELECT id_allegato, nome_fornitore, nome_file FROM allegati_richiesta WHERE id_richiesta = ? AND tipo_allegato = ?",
(id_richiesta, tipo_allegato)