Unifica finestre errori con testo completo, copia ed esportazione
This commit is contained in:
@@ -6,7 +6,8 @@ import asyncio
|
||||
import sys
|
||||
import tkinter as tk
|
||||
from concurrent.futures import Future
|
||||
from tkinter import messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import ttk
|
||||
from typing import Callable
|
||||
|
||||
from runtime_support import configure_exception_logging, ensure_stdio, log_exception, run_with_fatal_log
|
||||
@@ -675,19 +676,20 @@ class BarcodeClientApp:
|
||||
elif isinstance(result, BarcodeViewState):
|
||||
self._apply_state(result)
|
||||
|
||||
def _show_transaction_error(self) -> None:
|
||||
def _show_transaction_error(self, exception: Exception) -> None:
|
||||
messagebox.showerror(
|
||||
"Barcode WMS",
|
||||
"Operazione non completata.\n\n"
|
||||
"Ripeti la lettura o avvisa il responsabile.\n"
|
||||
"Il dettaglio tecnico e' stato scritto nel log.",
|
||||
parent=self.root,
|
||||
exception=exception,
|
||||
)
|
||||
|
||||
def _poll_recovery_future(self, original_exception: Exception) -> None:
|
||||
if self._pending is None:
|
||||
self._set_busy(False)
|
||||
self._show_transaction_error()
|
||||
self._show_transaction_error(original_exception)
|
||||
return
|
||||
if not self._pending.done():
|
||||
self.root.after(40, lambda err=original_exception: self._poll_recovery_future(err))
|
||||
@@ -704,14 +706,16 @@ class BarcodeClientApp:
|
||||
current.status_text = "Transazione non completata, ripeti l'operazione."
|
||||
current.status_color = "#f4cccc"
|
||||
self._apply_state(current)
|
||||
self._show_transaction_error()
|
||||
# Keep both failures when reconciliation also fails asynchronously.
|
||||
self._show_transaction_error(ExceptionGroup(
|
||||
"Barcode operation and recovery failed", [original_exception, exc]))
|
||||
return
|
||||
|
||||
if isinstance(result, BarcodeActionResult):
|
||||
self._apply_state(result.state)
|
||||
if not result.ok:
|
||||
self.root.bell()
|
||||
self._show_transaction_error()
|
||||
self._show_transaction_error(original_exception)
|
||||
elif isinstance(result, BarcodeViewState):
|
||||
self._apply_state(result)
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@ import asyncio
|
||||
import json
|
||||
import tkinter as tk
|
||||
from pathlib import Path
|
||||
from tkinter import messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import ttk
|
||||
from typing import Any
|
||||
|
||||
from async_msssql_query import AsyncMSSQLClient, make_mssql_dsn
|
||||
@@ -373,6 +374,7 @@ class DatabaseConfigWindow(tk.Toplevel):
|
||||
loc_text("dbconfig.msg.title", catalog=self._locale_catalog, default="Configurazione Database"),
|
||||
loc_text("dbconfig.msg.test_error", catalog=self._locale_catalog, default="Connessione fallita:\n{error}").format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
return
|
||||
messagebox.showinfo(
|
||||
@@ -393,6 +395,7 @@ class DatabaseConfigWindow(tk.Toplevel):
|
||||
loc_text("dbconfig.msg.title", catalog=self._locale_catalog, default="Configurazione Database"),
|
||||
loc_text("dbconfig.msg.save_error", catalog=self._locale_catalog, default="Salvataggio fallito:\n{error}").format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
return
|
||||
self.result_config = config
|
||||
|
||||
@@ -4,7 +4,8 @@ from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from datetime import datetime
|
||||
from tkinter import filedialog, messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import filedialog, ttk
|
||||
from typing import Any
|
||||
|
||||
import customtkinter as ctk
|
||||
@@ -399,6 +400,7 @@ class DiagnosticaWindow(ctk.CTkToplevel):
|
||||
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
|
||||
str(exc),
|
||||
parent=self if self._is_alive() else None,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
def _on_loaded(self, res: dict[str, Any] | None) -> None:
|
||||
@@ -434,6 +436,7 @@ class DiagnosticaWindow(ctk.CTkToplevel):
|
||||
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
|
||||
str(exc),
|
||||
parent=self,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
def _on_error(self, exc: BaseException) -> None:
|
||||
@@ -446,6 +449,7 @@ class DiagnosticaWindow(ctk.CTkToplevel):
|
||||
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
|
||||
str(exc),
|
||||
parent=self,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
def _export_xlsx(self) -> None:
|
||||
@@ -477,6 +481,7 @@ class DiagnosticaWindow(ctk.CTkToplevel):
|
||||
default="Per l'esportazione serve 'openpyxl' (pip install openpyxl).",
|
||||
).format(error=exc),
|
||||
parent=self,
|
||||
exception=exc,
|
||||
)
|
||||
return
|
||||
|
||||
@@ -531,6 +536,7 @@ class DiagnosticaWindow(ctk.CTkToplevel):
|
||||
default="Errore durante l'esportazione:\n{error}",
|
||||
).format(error=exc),
|
||||
parent=self,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
|
||||
|
||||
74
docs/finestre_errori.md
Normal file
74
docs/finestre_errori.md
Normal file
@@ -0,0 +1,74 @@
|
||||
# Finestre di errore unificate
|
||||
|
||||
## Modifica del 23 ottobre 2026
|
||||
|
||||
I dialoghi di errore del programma monolista, desktop e barcode, usano ora
|
||||
`error_dialog.py`, invece della messagebox nativa di Tkinter. Il testo non viene
|
||||
riassunto, accorciato o ridotto di dimensione per farlo entrare nello schermo.
|
||||
|
||||
La finestra offre:
|
||||
|
||||
- Ridimensionamento e scorrimento verticale e orizzontale.
|
||||
- Selezione del testo con il mouse, Ctrl+A e Ctrl+C.
|
||||
- Pulsante **Copia tutto**, per copiare l'intero report, anche fuori dalla vista.
|
||||
- Pulsante **Salva su file**, con scelta del percorso e formato TXT UTF-8.
|
||||
- Pulsante **Chiudi**, tasto Esc e chiusura dalla barra del titolo.
|
||||
|
||||
Su terminali piccoli i pulsanti vengono disposti in colonna. La dimensione
|
||||
iniziale tiene conto della risoluzione. Tema e testi sono definiti in
|
||||
`ui_theme.json` e `locale.json` (IT/ENG).
|
||||
|
||||
## Contenuto e integrazione
|
||||
|
||||
Il report conserva il messaggio originale, data/ora con fuso orario, versione
|
||||
applicativa e Python, e, quando fornita, l'eccezione originale con traceback e
|
||||
catena delle cause. Sono aggiunti gli attributi SQL `statement` e `params` per
|
||||
evitare le abbreviazioni della rappresentazione standard di SQLAlchemy.
|
||||
La finestra chiamante, quando indicata, contribuisce con il proprio titolo e
|
||||
la versione visibile. Una segnalazione di validazione senza eccezione conserva
|
||||
il messaggio, senza inventare uno stack di errore.
|
||||
|
||||
I callback asincroni passano esplicitamente `exception=exc`: convertire prima
|
||||
l'errore in stringa farebbe perdere il traceback. Nel barcode, se falliscono
|
||||
sia l'operazione sia la verifica del suo esito, il report contiene entrambe le
|
||||
eccezioni. La logica di verifica, le transazioni e i movimenti non cambiano.
|
||||
|
||||
Sono stati collegati inventario, diagnostica, layout, gestione e storico picking
|
||||
list, storico UDC, ricerca, UDC non scaffalate/multiple, scarico, reset corsie,
|
||||
sequenza di prelievo, autenticazione, configurazione DB, barcode, errori dei
|
||||
callback Tk e messaggi di avvio gestiti da `runtime_support`.
|
||||
|
||||
Informazioni, avvisi e conferme continuano a usare i dialoghi nativi: in
|
||||
particolare non cambiano le risposte Si/No delle operazioni di magazzino.
|
||||
Non viene applicata alcuna modifica globale alla libreria Tkinter: i moduli
|
||||
importano esplicitamente il componente condiviso.
|
||||
|
||||
Il dialogo e' modale come la precedente messagebox. Alla chiusura ripristina
|
||||
l'eventuale precedente finestra modale e il focus. Va chiamato sul thread Tk;
|
||||
non apre finestre direttamente dai thread di lavoro. Gli errori di background
|
||||
non destinati alla UI continuano a essere gestiti dai log esistenti.
|
||||
|
||||
Il salvataggio e' manuale, non sostituisce il logging gia' presente. Se viene
|
||||
annullato non scrive nulla; se fallisce, la finestra rimane aperta e indica
|
||||
l'errore. Copia e salvataggio usano lo stesso testo immutabile visualizzato.
|
||||
I report possono contenere parametri SQL e dati aziendali: conservarli e
|
||||
condividerli solo con personale autorizzato.
|
||||
|
||||
## Estensione email futura
|
||||
|
||||
Non viene inviata posta e non e' presente un pulsante non funzionante.
|
||||
Il report separato dalla visualizzazione potra' diventare l'allegato di un
|
||||
futuro pulsante **Invia al manutentore**, previa configurazione del destinatario,
|
||||
del servizio di invio e conferma dell'operatore. L'invio dovra' essere asincrono.
|
||||
|
||||
## Verifica e installazione
|
||||
|
||||
I test usano eccezioni sintetiche e widget Tk reali, senza operazioni sul DB:
|
||||
report lunghi, traceback e parametri, scroll, copia integrale/selezione,
|
||||
salvataggio UTF-8, annullamento/errori di salvataggio, schermi piccoli,
|
||||
ripristino della modalita' modale, errori asincroni e recupero barcode.
|
||||
|
||||
Non occorrono patch SQL o nuove dipendenze. Aggiornare anche il nuovo modulo,
|
||||
il catalogo delle lingue, il tema e `version_info.py`, non solo `inventario.py`.
|
||||
Questa modifica migliora la consultazione degli errori: non risolve da sola
|
||||
il lock timeout SQL 1222 rilevato nell'inventario.
|
||||
193
error_dialog.py
Normal file
193
error_dialog.py
Normal file
@@ -0,0 +1,193 @@
|
||||
"""Shared error dialogs; call on the Tk thread, like tkinter.messagebox.
|
||||
|
||||
Informational dialogs and confirmations retain their native implementations.
|
||||
Error reports are immutable text, shared by the viewer, clipboard and export.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import traceback
|
||||
import tkinter as tk
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from tkinter import filedialog, messagebox as native_messagebox, ttk
|
||||
|
||||
from locale_text import text
|
||||
from ui_theme import theme_font, theme_section
|
||||
from version_info import APP_VERSION, module_version, versioned_title
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
|
||||
def __getattr__(name):
|
||||
"""Delegate non-error dialogs without changing answers or confirmation flow."""
|
||||
return getattr(native_messagebox, name)
|
||||
|
||||
|
||||
def build_error_report(title, message, exception=None, *, context="") -> str:
|
||||
"""Keep the original message and chained traceback, with unabridged SQL data."""
|
||||
parts = [f"{datetime.now().astimezone().isoformat(timespec='seconds')} | {title}",
|
||||
f"Warehouse {APP_VERSION} | Python {sys.version}"]
|
||||
if context:
|
||||
parts.append(context)
|
||||
parts.append(str(message))
|
||||
if exception is not None:
|
||||
trace = traceback.TracebackException.from_exception(
|
||||
exception, max_group_width=sys.maxsize, max_group_depth=sys.maxsize)
|
||||
parts.append("".join(trace.format()))
|
||||
# SQLAlchemy's exception text may abbreviate parameter collections.
|
||||
seen = set()
|
||||
pending = [exception]
|
||||
while pending:
|
||||
current = pending.pop()
|
||||
if id(current) in seen:
|
||||
continue
|
||||
seen.add(id(current))
|
||||
for name in ("statement", "params"):
|
||||
value = getattr(current, name, None)
|
||||
if value is not None:
|
||||
parts.append(f"{type(current).__name__}.{name}:\n"
|
||||
+ (value if isinstance(value, str) else repr(value)))
|
||||
linked = current.__cause__ or (
|
||||
None if current.__suppress_context__ else current.__context__)
|
||||
if linked is not None:
|
||||
pending.append(linked)
|
||||
if isinstance(current, BaseExceptionGroup):
|
||||
pending.extend(reversed(current.exceptions))
|
||||
return "\n\n".join(parts)
|
||||
|
||||
|
||||
class ErrorDialog(tk.Toplevel):
|
||||
"""Resizable, selectable read-only report, also usable on small terminals."""
|
||||
|
||||
def __init__(self, parent, title, report):
|
||||
super().__init__(parent)
|
||||
self.withdraw()
|
||||
self.report = report
|
||||
self.title(versioned_title(title, __name__))
|
||||
self.resizable(True, True)
|
||||
theme = theme_section("error_dialog")
|
||||
width = min(int(theme.get("width", 900)), max(200, self.winfo_screenwidth() - 24))
|
||||
height = min(int(theme.get("height", 620)), max(200, self.winfo_screenheight() - 80))
|
||||
self.geometry(f"{width}x{height}+0+0")
|
||||
self.minsize(min(width, 420), min(height, 260))
|
||||
if parent.winfo_viewable():
|
||||
self.transient(parent.winfo_toplevel())
|
||||
self.grid_columnconfigure(0, weight=1)
|
||||
self.grid_rowconfigure(0, weight=1)
|
||||
|
||||
frame = ttk.Frame(self, padding=6)
|
||||
frame.grid(row=0, column=0, sticky="nsew")
|
||||
frame.grid_rowconfigure(0, weight=1)
|
||||
frame.grid_columnconfigure(0, weight=1)
|
||||
self.textbox = tk.Text(frame, wrap="none", width=1, height=1,
|
||||
font=theme_font(theme, "font", ("Consolas", 10)),
|
||||
background=theme.get("background", "#ffffff"),
|
||||
foreground=theme.get("foreground", "#202020"), exportselection=False)
|
||||
self.textbox.grid(row=0, column=0, sticky="nsew")
|
||||
self.vertical = ttk.Scrollbar(frame, orient="vertical", command=self.textbox.yview)
|
||||
self.vertical.grid(row=0, column=1, sticky="ns")
|
||||
self.horizontal = ttk.Scrollbar(frame, orient="horizontal", command=self.textbox.xview)
|
||||
self.horizontal.grid(row=1, column=0, sticky="ew")
|
||||
self.textbox.configure(yscrollcommand=self.vertical.set, xscrollcommand=self.horizontal.set)
|
||||
self.textbox.insert("1.0", report)
|
||||
self.textbox.configure(state="disabled")
|
||||
self.textbox.bind("<Control-a>", self.select_all)
|
||||
self.textbox.bind("<Control-c>", self.copy_selection)
|
||||
self.status = tk.StringVar(self, "")
|
||||
ttk.Label(self, textvariable=self.status, wraplength=max(150, width - 20)).grid(
|
||||
row=1, column=0, sticky="ew", padx=6)
|
||||
buttons = ttk.Frame(self, padding=6)
|
||||
buttons.grid(row=2, column=0, sticky="ew")
|
||||
self.buttons = []
|
||||
for i, (key, callback) in enumerate((("copy", self.copy_all),
|
||||
("save", self.save_report), ("close", self.destroy))):
|
||||
button = ttk.Button(buttons, text=text("errors." + key), command=callback)
|
||||
row, col = (i, 0) if width < 480 else (0, i)
|
||||
button.grid(row=row, column=col, sticky="ew", padx=2, pady=2)
|
||||
buttons.grid_columnconfigure(col, weight=1)
|
||||
self.buttons.append(button)
|
||||
self.bind("<Escape>", lambda _: self.destroy())
|
||||
self.deiconify()
|
||||
|
||||
def select_all(self, event=None):
|
||||
self.textbox.tag_add("sel", "1.0", "end-1c")
|
||||
return "break"
|
||||
|
||||
def _copy(self, value):
|
||||
try:
|
||||
self.clipboard_clear()
|
||||
self.clipboard_append(value)
|
||||
self.status.set(text("errors.copied"))
|
||||
except tk.TclError as exc:
|
||||
self.status.set(text("errors.copy_failed").format(error=exc))
|
||||
|
||||
def copy_selection(self, event=None):
|
||||
if self.textbox.tag_ranges("sel"):
|
||||
self._copy(self.textbox.get("sel.first", "sel.last"))
|
||||
return "break"
|
||||
|
||||
def copy_all(self):
|
||||
self._copy(self.report)
|
||||
|
||||
def save_report(self):
|
||||
"""Save UTF-8 without truncation; a failed save leaves the report open."""
|
||||
path = filedialog.asksaveasfilename(parent=self, title=text("errors.save"),
|
||||
defaultextension=".txt", initialfile=f"warehouse_error_{datetime.now():%Y%m%d_%H%M%S}.txt",
|
||||
filetypes=[(text("errors.text_file"), "*.txt"), (text("errors.all_files"), "*.*")])
|
||||
if not path:
|
||||
return
|
||||
try:
|
||||
Path(path).write_text(self.report, encoding="utf-8")
|
||||
except OSError as exc:
|
||||
self.status.set(text("errors.save_failed").format(error=exc))
|
||||
else:
|
||||
self.status.set(text("errors.saved").format(path=path))
|
||||
|
||||
|
||||
def showerror(title=None, message=None, *, parent=None, exception=None, context="", **options):
|
||||
"""Messagebox-compatible modal error; confirmations are never rerouted here.
|
||||
|
||||
Async callbacks must pass ``exception`` explicitly to retain their traceback.
|
||||
Within an except block the active exception is captured automatically.
|
||||
"""
|
||||
if exception is None:
|
||||
exception = message if isinstance(message, BaseException) else sys.exc_info()[1]
|
||||
title = title or text("errors.title")
|
||||
if not context and parent is not None:
|
||||
context = parent.winfo_toplevel().title()
|
||||
report = build_error_report(title, "" if message is None else message, exception, context=context)
|
||||
if options.get("detail"):
|
||||
report += "\n\n" + str(options["detail"])
|
||||
owned_root = None
|
||||
parent = parent if parent is not None else tk._default_root
|
||||
if parent is None:
|
||||
owned_root = parent = tk.Tk()
|
||||
parent.withdraw()
|
||||
previous_grab = parent.grab_current()
|
||||
previous_grab_status = previous_grab.grab_status() if previous_grab else None
|
||||
previous_focus = parent.focus_get()
|
||||
dialog = None
|
||||
try:
|
||||
dialog = ErrorDialog(parent, title, report)
|
||||
dialog.wait_visibility()
|
||||
dialog.grab_set()
|
||||
dialog.textbox.focus_set()
|
||||
dialog.wait_window()
|
||||
finally:
|
||||
if dialog is not None and dialog.winfo_exists():
|
||||
dialog.destroy()
|
||||
try:
|
||||
if previous_grab is not None and previous_grab.winfo_exists():
|
||||
if previous_grab_status == "global":
|
||||
previous_grab.grab_set_global()
|
||||
else:
|
||||
previous_grab.grab_set()
|
||||
if previous_focus is not None and previous_focus.winfo_exists():
|
||||
previous_focus.focus_set()
|
||||
except tk.TclError:
|
||||
pass
|
||||
if owned_root is not None:
|
||||
owned_root.destroy()
|
||||
return "ok"
|
||||
@@ -10,7 +10,8 @@ import json
|
||||
import logging
|
||||
import sys
|
||||
import tkinter as tk
|
||||
from tkinter import Menu, messagebox, filedialog, simpledialog
|
||||
import error_dialog as messagebox
|
||||
from tkinter import Menu, filedialog, simpledialog
|
||||
import customtkinter as ctk
|
||||
from datetime import datetime
|
||||
from functools import wraps
|
||||
@@ -750,7 +751,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
target=target_barcode_cella,
|
||||
details={"barcode_pallet": barcode_pallet, "error": str(ex)},
|
||||
)
|
||||
messagebox.showerror("Movimento UDC", f"Operazione fallita:\n{ex}", parent=self)
|
||||
messagebox.showerror("Movimento UDC", f"Operazione fallita:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
self._async.run(
|
||||
move_pallet_async(
|
||||
@@ -838,7 +839,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
target=self._cell_label(r, c),
|
||||
details={"idcella": idcella, "stato": int(stato), "error": str(ex)},
|
||||
)
|
||||
messagebox.showerror("Prenotazione", f"Aggiornamento fallito:\n{ex}", parent=self)
|
||||
messagebox.showerror("Prenotazione", f"Aggiornamento fallito:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
self._async.run(
|
||||
self.db.exec(SQL_SET_CELL_PRENOTAZIONE, params, commit=True),
|
||||
@@ -899,7 +900,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
target=self._cell_label(r, c),
|
||||
details={"idcella": idcella, "stato": int(stato), "error": str(ex)},
|
||||
)
|
||||
messagebox.showerror("Stato cella", f"Aggiornamento fallito:\n{ex}", parent=self)
|
||||
messagebox.showerror("Stato cella", f"Aggiornamento fallito:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
self._async.run(
|
||||
self.db.exec(SQL_SET_CELL_PRENOTAZIONE, params, commit=True),
|
||||
@@ -1000,7 +1001,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
return
|
||||
self._busy.hide()
|
||||
_MODULE_LOGGER.exception(f"Errore caricamento corsie: {ex}")
|
||||
messagebox.showerror("Errore", f"Caricamento corsie fallito:\n{ex}")
|
||||
messagebox.showerror("Errore", f"Caricamento corsie fallito:\n{ex}", exception=ex)
|
||||
self._async.run(self.db.query_json(sql, {}), _ok, _err, busy=self._busy, message="Carico corsie…")
|
||||
|
||||
@_log_call()
|
||||
@@ -1179,7 +1180,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
return
|
||||
self._busy.hide()
|
||||
_MODULE_LOGGER.exception(f"Errore caricamento matrice corsia={corsia}: {ex}")
|
||||
messagebox.showerror("Errore", f"Caricamento matrice {corsia} fallito:\n{ex}")
|
||||
messagebox.showerror("Errore", f"Caricamento matrice {corsia} fallito:\n{ex}", exception=ex)
|
||||
self._async.run(self.db.query_json(sql, {"corsia": corsia}), _ok, _err, busy=self._busy, message=f"Carico corsia {corsia}…")
|
||||
|
||||
# ---------------- SEARCH ----------------
|
||||
@@ -1233,7 +1234,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
if search_req_id < self._last_req:
|
||||
return
|
||||
_MODULE_LOGGER.exception(f"Errore ricerca UDC barcode={barcode}: {ex}")
|
||||
messagebox.showerror("Ricerca", f"Errore ricerca UDC:\n{ex}", parent=self)
|
||||
messagebox.showerror("Ricerca", f"Errore ricerca UDC:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
self._async.run(self.db.query_json(sql, {"barcode": barcode}), _ok, _err, busy=self._busy, message="Cerco UDC…")
|
||||
|
||||
@@ -1283,7 +1284,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import PatternFill, Alignment, Font
|
||||
except Exception as ex:
|
||||
messagebox.showerror("Export", f"Manca openpyxl: {ex}\nInstalla con: pip install openpyxl")
|
||||
messagebox.showerror("Export", f"Manca openpyxl: {ex}\nInstalla con: pip install openpyxl", exception=ex)
|
||||
return
|
||||
rows = len(self.matrix_state)
|
||||
cols = len(self.matrix_state[0]) if self.matrix_state else 0
|
||||
@@ -1317,7 +1318,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
wb.save(path)
|
||||
self._toast(f"Esportato: {path}")
|
||||
except Exception as ex:
|
||||
messagebox.showerror("Export", f"Salvataggio fallito:\n{ex}")
|
||||
messagebox.showerror("Export", f"Salvataggio fallito:\n{ex}", exception=ex)
|
||||
|
||||
# ---------------- STATS ----------------
|
||||
def _refresh_stats(self):
|
||||
|
||||
@@ -10,7 +10,7 @@ import json
|
||||
import sys
|
||||
import tkinter as tk
|
||||
import customtkinter as ctk
|
||||
from tkinter import messagebox
|
||||
import error_dialog as messagebox
|
||||
from typing import Optional, Any, Dict, List, Callable
|
||||
from dataclasses import dataclass
|
||||
from functools import wraps
|
||||
@@ -1061,7 +1061,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
_MODULE_LOGGER.exception(f"Errore durante il caricamento dettagli del documento {self.detail_doc}: {ex}")
|
||||
self.spinner.stop()
|
||||
self.busy.hide() # Chiudi l'overlay in caso di errore
|
||||
messagebox.showerror("DB", f"Errore nel caricamento dettagli:\n{ex}")
|
||||
messagebox.showerror("DB", f"Errore nel caricamento dettagli:\n{ex}", exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_job(),
|
||||
@@ -1127,7 +1127,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
except Exception:
|
||||
pass
|
||||
self._first_loading = False
|
||||
messagebox.showerror("DB", f"Errore nel caricamento:\n{ex}")
|
||||
messagebox.showerror("DB", f"Errore nel caricamento:\n{ex}", exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_job(),
|
||||
@@ -1296,7 +1296,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
target=documento,
|
||||
details={"error": str(ex)},
|
||||
)
|
||||
messagebox.showerror("Prenota", f"Errore:\n{ex}")
|
||||
messagebox.showerror("Prenota", f"Errore:\n{ex}", exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_job(),
|
||||
@@ -1374,7 +1374,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
target=documento,
|
||||
details={"error": str(ex)},
|
||||
)
|
||||
messagebox.showerror("S-prenota", f"Errore:\n{ex}")
|
||||
messagebox.showerror("S-prenota", f"Errore:\n{ex}", exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_job(),
|
||||
|
||||
@@ -13,7 +13,8 @@ from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
import customtkinter as ctk
|
||||
from tkinter import messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import ttk
|
||||
|
||||
from gestione_aree import AsyncRunner
|
||||
from audit_log import log_user_action
|
||||
@@ -640,6 +641,7 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
loc_text("scarico.msg.title", catalog=self._locale_catalog, default="Scarica"),
|
||||
loc_text("scarico.msg.load_error", catalog=self._locale_catalog, default="Caricamento UDC fallito:\n{error}").format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
self._close()
|
||||
|
||||
@@ -842,6 +844,7 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
loc_text("scarico.msg.title", catalog=self._locale_catalog, default="Scarica"),
|
||||
loc_text("scarico.msg.exec_error", catalog=self._locale_catalog, default="Scarico fallito:\n{error}").format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
|
||||
self._async.run(
|
||||
|
||||
@@ -6,7 +6,8 @@ import asyncio
|
||||
import tkinter as tk
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from tkinter import filedialog, messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import filedialog, ttk
|
||||
|
||||
import customtkinter as ctk
|
||||
|
||||
@@ -234,7 +235,7 @@ class InventarioWindow(ctk.CTkToplevel):
|
||||
self._set_loading(False)
|
||||
log_exception(__name__, error, context="inventory report/export")
|
||||
self.var_status.set(self._t("inventory.failed"))
|
||||
messagebox.showerror(self._t("inventory.title"), str(error), parent=self)
|
||||
messagebox.showerror(self._t("inventory.title"), str(error), parent=self, exception=error)
|
||||
|
||||
def _export(self):
|
||||
if self._loading or not self._report or not self._rows:
|
||||
|
||||
20
locale.json
20
locale.json
@@ -1,6 +1,16 @@
|
||||
{
|
||||
"default_language": "IT",
|
||||
"IT": {
|
||||
"errors.title": "Dettaglio errore",
|
||||
"errors.copy": "Copia tutto",
|
||||
"errors.save": "Salva su file",
|
||||
"errors.close": "Chiudi",
|
||||
"errors.copied": "Testo copiato negli appunti.",
|
||||
"errors.copy_failed": "Copia non riuscita: {error}",
|
||||
"errors.saved": "Report salvato: {path}",
|
||||
"errors.save_failed": "Salvataggio non riuscito: {error}",
|
||||
"errors.text_file": "File di testo UTF-8",
|
||||
"errors.all_files": "Tutti i file",
|
||||
"inventory.title": "Inventario",
|
||||
"inventory.date": "Data (gg/mm/aaaa):",
|
||||
"inventory.load": "Calcola inventario",
|
||||
@@ -235,6 +245,16 @@
|
||||
"scarico.msg.exec_error": "Scarico fallito:\n{error}"
|
||||
},
|
||||
"ENG": {
|
||||
"errors.title": "Error details",
|
||||
"errors.copy": "Copy all",
|
||||
"errors.save": "Save to file",
|
||||
"errors.close": "Close",
|
||||
"errors.copied": "Text copied to clipboard.",
|
||||
"errors.copy_failed": "Copy failed: {error}",
|
||||
"errors.saved": "Report saved: {path}",
|
||||
"errors.save_failed": "Save failed: {error}",
|
||||
"errors.text_file": "UTF-8 text file",
|
||||
"errors.all_files": "All files",
|
||||
"inventory.title": "Inventory",
|
||||
"inventory.date": "Date (dd/mm/yyyy):",
|
||||
"inventory.load": "Calculate inventory",
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import ttk
|
||||
from typing import Any
|
||||
|
||||
from audit_log import log_session_event
|
||||
@@ -261,6 +262,7 @@ class LoginWindow(tk.Toplevel):
|
||||
loc_text("login.msg.title", catalog=self._locale_catalog, default="Login"),
|
||||
loc_text("login.msg.error", catalog=self._locale_catalog, default="Verifica credenziali fallita:\n{error}").format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
|
||||
self._async.run(
|
||||
|
||||
2
main.py
2
main.py
@@ -17,7 +17,7 @@ ensure_stdio("warehouse_main")
|
||||
|
||||
import customtkinter as ctk
|
||||
from PIL import Image, ImageDraw
|
||||
from tkinter import messagebox
|
||||
import error_dialog as messagebox
|
||||
|
||||
from async_loop_singleton import get_global_loop, stop_global_loop
|
||||
from async_msssql_query import AsyncMSSQLClient
|
||||
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox
|
||||
import error_dialog as messagebox
|
||||
|
||||
import customtkinter as ctk
|
||||
|
||||
@@ -285,6 +285,7 @@ class PickingListSequenceWindow(ctk.CTkToplevel):
|
||||
self._t("picking.sequence.title", "Sequenza di prelievo"),
|
||||
self._t("picking.sequence.msg.load_error", "Errore durante il caricamento:\n{error}", error=exc),
|
||||
parent=self,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
self.runner.run(
|
||||
@@ -536,6 +537,7 @@ SELECT CAST({len(values)} AS int) AS ElementiSalvati;
|
||||
self._t("picking.sequence.title", "Sequenza di prelievo"),
|
||||
self._t("picking.sequence.msg.save_error", "Errore durante il salvataggio:\n{error}", error=exc),
|
||||
parent=self,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -13,7 +13,8 @@ import sys
|
||||
import tkinter as tk
|
||||
from functools import wraps
|
||||
from pathlib import Path
|
||||
from tkinter import messagebox, simpledialog, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import simpledialog, ttk
|
||||
from typing import Any
|
||||
|
||||
import customtkinter as ctk
|
||||
@@ -466,7 +467,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
|
||||
def _err(ex):
|
||||
_MODULE_LOGGER.exception(f"Errore caricamento corsie reset corsie: {ex}")
|
||||
messagebox.showerror("Errore", f"Caricamento corsie fallito:\n{ex}", parent=self)
|
||||
messagebox.showerror("Errore", f"Caricamento corsie fallito:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
self._async.run(self.db.query_json(SQL_CORSIE, {}), _ok, _err, busy=self._busy, message="Carico corsie...")
|
||||
|
||||
@@ -513,11 +514,11 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
self.tree.insert("", "end", values=(ubi, n), tags=(tag,))
|
||||
except Exception as ex:
|
||||
_MODULE_LOGGER.exception(f"Errore UI refresh reset corsie corsia={corsia}: {ex}")
|
||||
messagebox.showerror("Errore", f"Aggiornamento interfaccia fallito:\n{ex}", parent=self)
|
||||
messagebox.showerror("Errore", f"Aggiornamento interfaccia fallito:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
def _err(ex):
|
||||
_MODULE_LOGGER.exception(f"Errore refresh reset corsie corsia={corsia}: {ex}")
|
||||
messagebox.showerror("Errore", f"Refresh fallito:\n{ex}", parent=self)
|
||||
messagebox.showerror("Errore", f"Refresh fallito:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
self._async.run(_q(), _ok, _err, busy=self._busy, message=f"Riepilogo {corsia}...")
|
||||
|
||||
@@ -551,7 +552,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
|
||||
def _err_count(ex):
|
||||
_MODULE_LOGGER.exception(f"Errore conteggio reset corsie corsia={corsia}: {ex}")
|
||||
messagebox.showerror("Errore", f"Conteggio UDC da scaricare fallito:\n{ex}", parent=self)
|
||||
messagebox.showerror("Errore", f"Conteggio UDC da scaricare fallito:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
self._async.run(self.db.query_json(SQL_COUNT_RESET, {"corsia": corsia}), _ok_count, _err_count, busy=self._busy, message="Verifico...")
|
||||
|
||||
@@ -636,7 +637,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
|
||||
def _err_del(ex):
|
||||
_MODULE_LOGGER.exception(f"Errore reset logico corsie corsia={corsia}: {ex}")
|
||||
messagebox.showerror("Errore", f"Svuotamento fallito:\n{ex}", parent=self)
|
||||
messagebox.showerror("Errore", f"Svuotamento fallito:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
self._async.run(_q(), _ok_del, _err_del, busy=self._busy, message=f"Svuoto {corsia}...")
|
||||
|
||||
|
||||
@@ -98,13 +98,15 @@ def configure_exception_logging(app_name: str, root=None, loop=None) -> None:
|
||||
def _tk_exception(exc_type, exc, tb):
|
||||
log_exception(app_name, exc, context="tkinter callback")
|
||||
try:
|
||||
import tkinter.messagebox as messagebox
|
||||
import error_dialog as messagebox
|
||||
|
||||
messagebox.showerror(
|
||||
app_name,
|
||||
"Errore applicativo registrato nei log.\n\n"
|
||||
"Se l'operazione era in corso, ripeterla o avvisare il responsabile.",
|
||||
parent=root,
|
||||
exception=exc,
|
||||
context="tkinter callback",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -150,7 +152,7 @@ def show_fatal_message(app_name: str, exc: BaseException) -> None:
|
||||
|
||||
try:
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox
|
||||
import error_dialog as messagebox
|
||||
|
||||
root = tk.Tk()
|
||||
root.withdraw()
|
||||
@@ -161,6 +163,7 @@ def show_fatal_message(app_name: str, exc: BaseException) -> None:
|
||||
f"Se non ci sono, controlla anche:\n{TEMP_DIR}\n\n"
|
||||
f"{exc}",
|
||||
parent=root,
|
||||
exception=exc,
|
||||
)
|
||||
root.destroy()
|
||||
except Exception:
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import filedialog, messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import filedialog, ttk
|
||||
|
||||
import customtkinter as ctk
|
||||
|
||||
@@ -299,6 +300,7 @@ class SearchWindow(ctk.CTkToplevel):
|
||||
loc_text("search.msg.export_title", catalog=self._locale_catalog, default="Esporta"),
|
||||
loc_text("search.msg.export_error", catalog=self._locale_catalog, default="Errore durante l'esportazione:{error}").format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
|
||||
def _on_dclick(self, evt):
|
||||
@@ -510,6 +512,7 @@ class SearchWindow(ctk.CTkToplevel):
|
||||
loc_text("search.msg.error_title", catalog=self._locale_catalog, default="Errore ricerca"),
|
||||
str(ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
|
||||
self._async.run(
|
||||
|
||||
@@ -11,7 +11,8 @@ from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timedelta
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import ttk
|
||||
from typing import Any
|
||||
|
||||
import customtkinter as ctk
|
||||
@@ -351,6 +352,7 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
default="Errore caricamento:\n{error}",
|
||||
).format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
|
||||
self._async.run(
|
||||
@@ -453,6 +455,7 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
default="Errore dettaglio:\n{error}",
|
||||
).format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
|
||||
self._async.run(
|
||||
@@ -611,6 +614,7 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
|
||||
f"Versamento residui fallito:\n{ex}",
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
|
||||
self._async.run(
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import ttk
|
||||
from typing import Any
|
||||
|
||||
import customtkinter as ctk
|
||||
@@ -269,6 +270,7 @@ class StoricoUDCWindow(ctk.CTkToplevel):
|
||||
default="Errore ricerca:\n{error}",
|
||||
).format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
|
||||
self._async.run(
|
||||
|
||||
167
tests/test_error_dialog.py
Normal file
167
tests/test_error_dialog.py
Normal file
@@ -0,0 +1,167 @@
|
||||
"""Error report tests with real Tk widgets; no DB access or warehouse writes."""
|
||||
|
||||
import ast
|
||||
import tempfile
|
||||
import tkinter as tk
|
||||
import unittest
|
||||
from concurrent.futures import Future
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import error_dialog
|
||||
from error_dialog import ErrorDialog, build_error_report, showerror
|
||||
|
||||
|
||||
class ReportTests(unittest.TestCase):
|
||||
def test_chained_error_and_sql_are_complete(self):
|
||||
from sqlalchemy.exc import StatementError
|
||||
params = {"items": list(range(2000))}
|
||||
try:
|
||||
try:
|
||||
raise ValueError("original cause")
|
||||
except ValueError as cause:
|
||||
raise StatementError("query failed", "SELECT " + "x" * 20000, params, cause) from cause
|
||||
except StatementError as exc:
|
||||
report = build_error_report("Inventory", "User message", exc)
|
||||
self.assertIn("original cause", report)
|
||||
self.assertIn("Traceback", report)
|
||||
self.assertIn("SELECT " + "x" * 20000, report)
|
||||
self.assertIn(repr(params), report)
|
||||
self.assertIn("User message", report)
|
||||
|
||||
def test_group_has_every_exception_not_default_first_fifteen(self):
|
||||
exc = ExceptionGroup("errors", [ValueError(f"failure-{i}") for i in range(30)])
|
||||
report = build_error_report("Barcode", "Recovery", exc)
|
||||
for i in range(30):
|
||||
self.assertIn(f"failure-{i}", report)
|
||||
|
||||
def test_all_live_modules_use_shared_errors(self):
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
for path in root.glob("*.py"):
|
||||
if path.name == "error_dialog.py":
|
||||
continue
|
||||
tree = ast.parse(path.read_text(encoding="utf-8-sig"))
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.ImportFrom) and node.module in ("tkinter", "tkinter.messagebox"):
|
||||
self.assertFalse(any(n.name in ("messagebox", "showerror") for n in node.names), path.name)
|
||||
if isinstance(node, ast.Import):
|
||||
self.assertFalse(any(n.name == "tkinter.messagebox" for n in node.names), path.name)
|
||||
|
||||
def test_confirmations_and_information_remain_native(self):
|
||||
self.assertIs(error_dialog.askyesno, error_dialog.native_messagebox.askyesno)
|
||||
self.assertIs(error_dialog.showinfo, error_dialog.native_messagebox.showinfo)
|
||||
self.assertIs(error_dialog.showwarning, error_dialog.native_messagebox.showwarning)
|
||||
|
||||
def test_translations_exist(self):
|
||||
from locale_text import load_locale_catalog
|
||||
for lang in ("IT", "ENG"):
|
||||
for key in ("copy", "save", "close", "copy_failed", "save_failed", "saved"):
|
||||
self.assertTrue(load_locale_catalog()[lang]["errors." + key])
|
||||
|
||||
|
||||
class DialogTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.root = tk.Tk()
|
||||
self.root.withdraw()
|
||||
self.report = "Accento: \u00e8\n" + ("SQL " + "x" * 2000 + "\n") * 500 + "END OF REPORT"
|
||||
self.dialog = ErrorDialog(self.root, "Synthetic error", self.report)
|
||||
self.root.update()
|
||||
|
||||
def tearDown(self):
|
||||
self.root.destroy()
|
||||
|
||||
def test_full_text_read_only_and_both_scrollbars(self):
|
||||
box = self.dialog.textbox
|
||||
self.assertEqual(box.get("1.0", "end-1c"), self.report)
|
||||
self.assertEqual(box.cget("state"), "disabled")
|
||||
box.insert("end", "forbidden edit")
|
||||
self.assertEqual(box.get("1.0", "end-1c"), self.report)
|
||||
box.yview_moveto(1)
|
||||
box.xview_moveto(1)
|
||||
self.root.update()
|
||||
self.assertAlmostEqual(box.yview()[1], 1)
|
||||
self.assertGreater(box.xview()[0], 0)
|
||||
self.assertTrue(self.dialog.vertical.winfo_ismapped())
|
||||
self.assertTrue(self.dialog.horizontal.winfo_ismapped())
|
||||
|
||||
def test_copy_all_and_selection(self):
|
||||
self.dialog.copy_all()
|
||||
self.assertEqual(self.root.clipboard_get(), self.report)
|
||||
self.dialog.textbox.tag_add("sel", "1.0", "1.7")
|
||||
self.dialog.copy_selection()
|
||||
self.assertEqual(self.root.clipboard_get(), "Accento")
|
||||
self.dialog.select_all()
|
||||
self.dialog.copy_selection()
|
||||
self.assertEqual(self.root.clipboard_get(), self.report)
|
||||
|
||||
def test_save_utf8_exactly_matches_display_and_clipboard(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "error.txt"
|
||||
with patch("error_dialog.filedialog.asksaveasfilename", return_value=str(path)):
|
||||
self.dialog.save_report()
|
||||
self.assertEqual(path.read_text(encoding="utf-8"), self.report)
|
||||
|
||||
def test_save_cancel_does_nothing(self):
|
||||
with patch("error_dialog.filedialog.asksaveasfilename", return_value=""), \
|
||||
patch("error_dialog.Path.write_text") as write:
|
||||
self.dialog.save_report()
|
||||
write.assert_not_called()
|
||||
|
||||
def test_save_error_keeps_report_open(self):
|
||||
with patch("error_dialog.filedialog.asksaveasfilename", return_value="report.txt"), \
|
||||
patch("error_dialog.Path.write_text", side_effect=PermissionError("denied")):
|
||||
self.dialog.save_report()
|
||||
self.assertIn("denied", self.dialog.status.get())
|
||||
self.assertTrue(self.dialog.winfo_exists())
|
||||
self.assertEqual(self.dialog.textbox.get("1.0", "end-1c"), self.report)
|
||||
|
||||
def test_small_terminal_keeps_buttons_inside_window(self):
|
||||
self.dialog.destroy()
|
||||
with patch.object(ErrorDialog, "winfo_screenwidth", return_value=240), \
|
||||
patch.object(ErrorDialog, "winfo_screenheight", return_value=320):
|
||||
self.dialog = ErrorDialog(self.root, "Small", self.report)
|
||||
self.root.update()
|
||||
for button in self.dialog.buttons:
|
||||
self.assertLessEqual(button.winfo_rooty() + button.winfo_height(),
|
||||
self.dialog.winfo_rooty() + self.dialog.winfo_height())
|
||||
self.assertGreater(self.dialog.textbox.winfo_height(), 10)
|
||||
|
||||
def test_modal_returns_ok_and_restores_existing_grab(self):
|
||||
self.dialog.grab_set()
|
||||
captured = []
|
||||
def close_report():
|
||||
for child in self.dialog.winfo_children():
|
||||
if isinstance(child, ErrorDialog):
|
||||
captured.append(child.report)
|
||||
child.destroy()
|
||||
self.root.after(100, close_report)
|
||||
result = showerror("Test", "message", parent=self.dialog, exception=ValueError("async details"))
|
||||
self.assertEqual(result, "ok")
|
||||
self.assertIn("async details", captured[0])
|
||||
self.assertEqual(self.root.grab_current(), self.dialog)
|
||||
|
||||
|
||||
class BarcodeErrorTests(unittest.TestCase):
|
||||
def test_recovery_preserves_original_exception(self):
|
||||
from barcode_client import BarcodeClientApp
|
||||
app = Mock()
|
||||
app._pending = None
|
||||
original = RuntimeError("original SQL failure")
|
||||
BarcodeClientApp._poll_recovery_future(app, original)
|
||||
app._show_transaction_error.assert_called_once_with(original)
|
||||
|
||||
def test_failed_recovery_preserves_both_exceptions(self):
|
||||
from barcode_client import BarcodeClientApp
|
||||
app = Mock()
|
||||
app._pending = Future()
|
||||
app._pending.set_exception(ValueError("recovery failed"))
|
||||
original = RuntimeError("SQL failure")
|
||||
with patch("barcode_client.log_exception"):
|
||||
BarcodeClientApp._poll_recovery_future(app, original)
|
||||
group = app._show_transaction_error.call_args.args[0]
|
||||
self.assertIs(group.exceptions[0], original)
|
||||
self.assertEqual(str(group.exceptions[1]), "recovery failed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -57,8 +57,10 @@ class InventoryGuiTests(unittest.TestCase):
|
||||
self.assertNotEqual(self.win.var_status.get(), self.win._t("inventory.scope"))
|
||||
self.win._loaded(self.sample())
|
||||
self.assertEqual([label.cget("text") for label in self.win.legend_descriptions], descriptions)
|
||||
with patch("inventario.messagebox.showerror"), patch("inventario.log_exception"):
|
||||
self.win._error(RuntimeError("Synthetic failure"))
|
||||
error = RuntimeError("Synthetic failure")
|
||||
with patch("inventario.messagebox.showerror") as show, patch("inventario.log_exception"):
|
||||
self.win._error(error)
|
||||
self.assertIs(show.call_args.kwargs["exception"], error)
|
||||
self.assertEqual([label.cget("text") for label in self.win.legend_descriptions], descriptions)
|
||||
|
||||
def test_legend_wraps_to_window_width(self):
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import ttk
|
||||
from typing import Any
|
||||
|
||||
import customtkinter as ctk
|
||||
@@ -177,6 +178,7 @@ class UDCNonScaffalateWindow(ctk.CTkToplevel):
|
||||
loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"),
|
||||
str(exc),
|
||||
parent=self if self._is_alive() else None,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
def _on_loaded(self, res: dict[str, Any] | None) -> None:
|
||||
@@ -207,6 +209,7 @@ class UDCNonScaffalateWindow(ctk.CTkToplevel):
|
||||
loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"),
|
||||
str(exc),
|
||||
parent=self,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
def _on_error(self, exc: BaseException) -> None:
|
||||
@@ -219,6 +222,7 @@ class UDCNonScaffalateWindow(ctk.CTkToplevel):
|
||||
loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"),
|
||||
str(exc),
|
||||
parent=self,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
{
|
||||
"error_dialog": {
|
||||
"width": 900,
|
||||
"height": 620,
|
||||
"background": "#ffffff",
|
||||
"foreground": "#202020",
|
||||
"font": {"family": "Consolas", "size": 10}
|
||||
},
|
||||
"inventory_window": {
|
||||
"legend_fg_color": ["#f8fafb", "#262b30"],
|
||||
"legend_text_color": ["#202830", "#f1f3f5"],
|
||||
|
||||
@@ -9,38 +9,39 @@ APP_VERSION = "1.0.0"
|
||||
|
||||
MODULE_VERSIONS: dict[str, str] = {
|
||||
"app": APP_VERSION,
|
||||
"error_dialog": "1.0.0",
|
||||
"async_loop_singleton": "1.0.0",
|
||||
"async_msssql_query": "1.0.1",
|
||||
"audit_log": "1.0.0",
|
||||
"main": "1.0.4",
|
||||
"inventario": "1.1.1",
|
||||
"main": "1.0.5",
|
||||
"inventario": "1.1.2",
|
||||
"inventory_service": "1.1.0",
|
||||
"barcode_client": "1.0.27",
|
||||
"barcode_client": "1.0.28",
|
||||
"barcode_repository": "1.0.14",
|
||||
"barcode_service": "1.0.25",
|
||||
"busy_overlay": "1.0.0",
|
||||
"db_config": "1.0.0",
|
||||
"diagnostica": "1.0.4",
|
||||
"db_config": "1.0.1",
|
||||
"diagnostica": "1.0.5",
|
||||
"gestione_aree": "1.0.1",
|
||||
"gestione_layout": "1.0.2",
|
||||
"gestione_pickinglist": "1.0.6",
|
||||
"gestione_scarico": "1.0.8",
|
||||
"gestione_layout": "1.0.3",
|
||||
"gestione_pickinglist": "1.0.7",
|
||||
"gestione_scarico": "1.0.9",
|
||||
"locale_text": "1.0.0",
|
||||
"login_window": "1.0.0",
|
||||
"login_window": "1.0.1",
|
||||
"prenota_sprenota_sql": "1.0.1",
|
||||
"pickinglist_sequence": "1.0.0",
|
||||
"reset_corsie": "1.0.1",
|
||||
"pickinglist_sequence": "1.0.1",
|
||||
"reset_corsie": "1.0.2",
|
||||
"reset_corsie_service": "1.0.0",
|
||||
"runtime_support": "1.0.1",
|
||||
"search_pallets": "1.0.0",
|
||||
"storico_pickinglist": "1.0.5",
|
||||
"runtime_support": "1.0.2",
|
||||
"search_pallets": "1.0.1",
|
||||
"storico_pickinglist": "1.0.6",
|
||||
"pickinglist_history_search": "1.0.0",
|
||||
"storico_udc": "1.0.0",
|
||||
"storico_udc": "1.0.1",
|
||||
"tooltips": "1.0.0",
|
||||
"udc_non_scaffalate": "1.0.1",
|
||||
"udc_non_scaffalate": "1.0.2",
|
||||
"ui_theme": "1.0.0",
|
||||
"user_session": "1.0.3",
|
||||
"view_celle_multi_udc": "1.0.0",
|
||||
"view_celle_multi_udc": "1.0.1",
|
||||
"window_placement": "1.0.0",
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,8 @@ import tkinter as tk
|
||||
from datetime import datetime
|
||||
from functools import wraps
|
||||
from pathlib import Path
|
||||
from tkinter import filedialog, messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import filedialog, ttk
|
||||
from typing import Any
|
||||
|
||||
import customtkinter as ctk
|
||||
@@ -651,7 +652,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
|
||||
def _err(ex):
|
||||
_MODULE_LOGGER.exception(f"Errore caricamento corsie UDC fantasma: {ex}")
|
||||
messagebox.showerror("Errore", str(ex), parent=self)
|
||||
messagebox.showerror("Errore", str(ex), parent=self, exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_q(self.db),
|
||||
@@ -712,7 +713,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
|
||||
def _err(ex):
|
||||
_MODULE_LOGGER.exception(f"Errore caricamento celle duplicate corsia={corsia}: {ex}")
|
||||
messagebox.showerror("Errore", str(ex), parent=self)
|
||||
messagebox.showerror("Errore", str(ex), parent=self, exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_q(self.db),
|
||||
@@ -762,7 +763,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
|
||||
def _err(ex):
|
||||
_MODULE_LOGGER.exception(f"Errore caricamento pallet cella idcella={idcella}: {ex}")
|
||||
messagebox.showerror("Errore", str(ex), parent=self)
|
||||
messagebox.showerror("Errore", str(ex), parent=self, exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_q(self.db),
|
||||
@@ -889,7 +890,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
def _err(ex):
|
||||
self._busy.hide()
|
||||
_MODULE_LOGGER.exception(f"Errore preselezione fantasmi corsia={corsia}: {ex}")
|
||||
messagebox.showerror("Errore", str(ex), parent=self)
|
||||
messagebox.showerror("Errore", str(ex), parent=self, exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_q(self.db),
|
||||
@@ -962,7 +963,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
def _err(ex):
|
||||
self._busy.hide()
|
||||
_MODULE_LOGGER.exception(f"Errore bonifica fantasmi corsia={corsia}: {ex}")
|
||||
messagebox.showerror("Errore bonifica", str(ex), parent=self)
|
||||
messagebox.showerror("Errore bonifica", str(ex), parent=self, exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_q(self.db),
|
||||
@@ -982,7 +983,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
|
||||
def _err(ex):
|
||||
_MODULE_LOGGER.exception(f"Errore caricamento riepilogo UDC fantasma: {ex}")
|
||||
messagebox.showerror("Errore", str(ex), parent=self)
|
||||
messagebox.showerror("Errore", str(ex), parent=self, exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_q(self.db),
|
||||
@@ -1095,7 +1096,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
messagebox.showinfo("Esportazione completata", f"File creato:\n{fname}", parent=self)
|
||||
except Exception as ex:
|
||||
_MODULE_LOGGER.exception(f"Errore esportazione UDC fantasma: {ex}")
|
||||
messagebox.showerror("Errore esportazione", str(ex), parent=self)
|
||||
messagebox.showerror("Errore esportazione", str(ex), parent=self, exception=ex)
|
||||
|
||||
|
||||
def open_celle_multiple_window(
|
||||
|
||||
Reference in New Issue
Block a user