Compare commits
4 Commits
e4b227e82c
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 1553427c21 | |||
| 9d87b07648 | |||
| fc43cbb7ec | |||
| 106ea49f64 |
154
aggiorna_monolista.bat
Normal file
154
aggiorna_monolista.bat
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
@echo off
|
||||||
|
setlocal EnableExtensions DisableDelayedExpansion
|
||||||
|
rem Run a temporary copy: Git may replace this file during the update.
|
||||||
|
if /I "%~1"=="--worker" goto worker
|
||||||
|
set "INSTALL_DIR=%~1"
|
||||||
|
if not defined INSTALL_DIR set "INSTALL_DIR=C:\flywms"
|
||||||
|
set "PYTHON_EXE=%~2"
|
||||||
|
set "WORKER=%TEMP%\warehouse-update-%RANDOM%-%RANDOM%.bat"
|
||||||
|
copy /Y "%~f0" "%WORKER%" >nul
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
call "%WORKER%" --worker "%INSTALL_DIR%" "%PYTHON_EXE%"
|
||||||
|
exit /b %errorlevel%
|
||||||
|
|
||||||
|
:worker
|
||||||
|
set "INSTALL_DIR=%~2"
|
||||||
|
set "PYTHON_EXE=%~3"
|
||||||
|
set "RESULT=1"
|
||||||
|
echo.
|
||||||
|
echo === Aggiornamento Warehouse MONOLISTA - ramo main ===
|
||||||
|
echo Cartella: "%INSTALL_DIR%"
|
||||||
|
echo Chiudere Warehouse e il barcode, anche nelle altre sessioni del server.
|
||||||
|
echo Non vengono eseguite patch SQL o cancellazioni di file locali.
|
||||||
|
choice /C SN /N /M "Le applicazioni sono chiuse e vuoi continuare? [S/N]: "
|
||||||
|
if errorlevel 2 goto cancelled
|
||||||
|
if errorlevel 1 goto checks
|
||||||
|
goto failed
|
||||||
|
|
||||||
|
:checks
|
||||||
|
where git >nul 2>&1
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo ERRORE: Git non e' installato o non e' nel PATH.
|
||||||
|
goto failed
|
||||||
|
)
|
||||||
|
cd /d "%INSTALL_DIR%"
|
||||||
|
if errorlevel 1 goto failed
|
||||||
|
if not exist ".git" (
|
||||||
|
echo ERRORE: questa cartella non e' la radice di un clone Git.
|
||||||
|
echo Lo script aggiorna installazioni esistenti, non cartelle copiate da ZIP.
|
||||||
|
goto failed
|
||||||
|
)
|
||||||
|
git rev-parse --verify HEAD >nul 2>&1
|
||||||
|
if errorlevel 1 goto failed
|
||||||
|
set "REMOTE_URL="
|
||||||
|
for /f "delims=" %%G in ('git remote get-url origin') do set "REMOTE_URL=%%G"
|
||||||
|
if /I not "%REMOTE_URL%"=="https://gitea.alessandrobonvicini.it/administrator/ware_house.git" (
|
||||||
|
echo ERRORE: origin non corrisponde al repository Warehouse previsto.
|
||||||
|
echo Verificare il clone prima di proseguire. Nessun URL viene modificato.
|
||||||
|
goto failed
|
||||||
|
)
|
||||||
|
git status --porcelain --untracked-files=no >nul
|
||||||
|
if errorlevel 1 goto failed
|
||||||
|
set "DIRTY="
|
||||||
|
for /f "delims=" %%G in ('git status --porcelain --untracked-files^=no') do set "DIRTY=1"
|
||||||
|
if defined DIRTY (
|
||||||
|
echo ERRORE: esistono modifiche locali a file tracciati.
|
||||||
|
git status --short --untracked-files=no
|
||||||
|
echo Nessun reset o stash automatico. Conservare e verificare le modifiche.
|
||||||
|
goto failed
|
||||||
|
)
|
||||||
|
if not defined PYTHON_EXE if exist ".venv\Scripts\python.exe" set "PYTHON_EXE=%CD%\.venv\Scripts\python.exe"
|
||||||
|
if not defined PYTHON_EXE set "PYTHON_EXE=python"
|
||||||
|
"%PYTHON_EXE%" --version
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo ERRORE: Python non disponibile. Indicare il percorso come secondo argomento.
|
||||||
|
goto failed
|
||||||
|
)
|
||||||
|
"%PYTHON_EXE%" -m pip --version
|
||||||
|
if errorlevel 1 goto failed
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo Scaricamento di main da Gitea...
|
||||||
|
rem Avoid repacking/deleting old pack indexes during deployment on Windows.
|
||||||
|
rem These settings apply only to this command, not to the repository config.
|
||||||
|
git -c maintenance.auto=false -c gc.auto=0 fetch origin refs/heads/main
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo ERRORE: scaricamento fallito. Verificare rete, credenziali e accesso ai file .git.
|
||||||
|
goto failed
|
||||||
|
)
|
||||||
|
set "TARGET="
|
||||||
|
for /f %%G in ('git rev-parse FETCH_HEAD') do set "TARGET=%%G"
|
||||||
|
if not defined TARGET goto failed
|
||||||
|
set "DB_TRACKED="
|
||||||
|
for /f "delims=" %%G in ('git ls-tree --name-only %TARGET% -- db_connection.json') do set "DB_TRACKED=1"
|
||||||
|
if defined DB_TRACKED (
|
||||||
|
echo ERRORE: il ramo remoto contiene db_connection.json. Aggiornamento bloccato per proteggerlo.
|
||||||
|
goto failed
|
||||||
|
)
|
||||||
|
rem Refuse to silently replace a different development branch or local commits.
|
||||||
|
git merge-base --is-ancestor HEAD %TARGET%
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo ERRORE: la versione locale non e' un antenato del main remoto.
|
||||||
|
echo Possibile ramo bilista o commit locali: occorre una verifica manuale.
|
||||||
|
goto failed
|
||||||
|
)
|
||||||
|
git show-ref --verify --quiet refs/heads/main
|
||||||
|
if errorlevel 1 goto backup
|
||||||
|
git merge-base --is-ancestor main %TARGET%
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo ERRORE: anche il main locale contiene commit non presenti sul remoto.
|
||||||
|
goto failed
|
||||||
|
)
|
||||||
|
|
||||||
|
:backup
|
||||||
|
set "STAMP="
|
||||||
|
for /f %%G in ('powershell -NoProfile -Command "Get-Date -Format yyyyMMdd-HHmmss-fff"') do set "STAMP=%%G"
|
||||||
|
if not defined STAMP goto failed
|
||||||
|
set "BACKUP_REF=refs/warehouse-backups/pre-update-%STAMP%"
|
||||||
|
git update-ref "%BACKUP_REF%" HEAD
|
||||||
|
if errorlevel 1 goto failed
|
||||||
|
echo.
|
||||||
|
echo Riferimento di recupero: %BACKUP_REF%
|
||||||
|
echo Per tornare ai sorgenti precedenti, con applicazioni chiuse:
|
||||||
|
echo git switch --detach %BACKUP_REF%
|
||||||
|
echo Il ripristino Git NON ripristina database o dipendenze Python.
|
||||||
|
echo.
|
||||||
|
git show-ref --verify --quiet refs/heads/main
|
||||||
|
if errorlevel 1 (
|
||||||
|
git switch -c main %TARGET%
|
||||||
|
) else (
|
||||||
|
git switch main
|
||||||
|
)
|
||||||
|
if errorlevel 1 goto failed
|
||||||
|
git -c maintenance.auto=false -c gc.auto=0 merge --ff-only %TARGET%
|
||||||
|
if errorlevel 1 goto failed
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo Installazione dipendenze con "%PYTHON_EXE%"...
|
||||||
|
"%PYTHON_EXE%" -m pip install -r requirements.txt
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo ERRORE: file Git aggiornati, ma installazione dipendenze NON completata.
|
||||||
|
echo Non riavviare l'applicazione finche' il problema pip non e' risolto.
|
||||||
|
goto failed
|
||||||
|
)
|
||||||
|
echo.
|
||||||
|
echo AGGIORNAMENTO COMPLETATO.
|
||||||
|
git log -1 --format="Commit installato: %%h %%s"
|
||||||
|
echo Ora puoi riaprire Warehouse e il barcode dai collegamenti abituali.
|
||||||
|
echo Se il push dal PC di sviluppo non e' riuscito, il remoto puo' essere ancora vecchio.
|
||||||
|
set "RESULT=0"
|
||||||
|
goto finish
|
||||||
|
|
||||||
|
:cancelled
|
||||||
|
echo Aggiornamento annullato.
|
||||||
|
set "RESULT=2"
|
||||||
|
goto finish
|
||||||
|
|
||||||
|
:failed
|
||||||
|
echo.
|
||||||
|
echo AGGIORNAMENTO NON COMPLETATO. Leggere l'errore riportato sopra.
|
||||||
|
|
||||||
|
:finish
|
||||||
|
echo.
|
||||||
|
pause
|
||||||
|
exit /b %RESULT%
|
||||||
21
apply_monolista_sam_date_patch.sql
Normal file
21
apply_monolista_sam_date_patch.sql
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
-- SSMS: select the monolista WMS database (not SAMA1).
|
||||||
|
-- Change only the known 30-day predicate of the installed Python view.
|
||||||
|
SET ANSI_NULLS ON;
|
||||||
|
SET QUOTED_IDENTIFIER ON;
|
||||||
|
DECLARE @ddl nvarchar(max) = OBJECT_DEFINITION(OBJECT_ID(N'dbo.py_XMag_ViewPackingList', N'V'));
|
||||||
|
DECLARE @old nvarchar(150) = N'DATDOC > CAST((GETDATE() - 30) AS int)';
|
||||||
|
DECLARE @new nvarchar(150) = N'DATDOC >= DATEDIFF(day, CONVERT(date, ''18991230'', 112), GETDATE()) - 29';
|
||||||
|
IF @ddl IS NULL
|
||||||
|
THROW 51000, 'Vista Python monolista assente o definizione non leggibile.', 1;
|
||||||
|
IF CHARINDEX(@new, @ddl) > 0 AND CHARINDEX(@old, @ddl) = 0
|
||||||
|
BEGIN
|
||||||
|
PRINT 'Soglia SAM gia aggiornata.';
|
||||||
|
RETURN;
|
||||||
|
END;
|
||||||
|
DECLARE @pos int = CHARINDEX(@old, @ddl);
|
||||||
|
DECLARE @view int = CHARINDEX(N'VIEW dbo.py_XMag_ViewPackingList', @ddl);
|
||||||
|
IF @pos = 0 OR @view = 0 OR CHARINDEX(@old, @ddl, @pos + 1) > 0
|
||||||
|
THROW 51001, 'Definizione diversa dalle versioni previste: nessuna modifica.', 1;
|
||||||
|
SET @ddl = STUFF(REPLACE(@ddl, @old, @new), 1, @view - 1, N'ALTER ');
|
||||||
|
EXEC sys.sp_executesql @ddl;
|
||||||
|
PRINT 'Soglia SAM aggiornata nella sola dbo.py_XMag_ViewPackingList.';
|
||||||
@@ -586,7 +586,7 @@ LEFT JOIN dbo.PyPickingListReservation AS pr
|
|||||||
ON pr.ID = 1
|
ON pr.ID = 1
|
||||||
AND NULLIF(LTRIM(RTRIM(pr.Documento)), '') IS NOT NULL
|
AND NULLIF(LTRIM(RTRIM(pr.Documento)), '') IS NOT NULL
|
||||||
WHERE prep.StatoDocumento = 'P'
|
WHERE prep.StatoDocumento = 'P'
|
||||||
AND prep.DATDOC > CAST((GETDATE() - 30) AS int)
|
AND prep.DATDOC >= DATEDIFF(day, CONVERT(date, '18991230', 112), GETDATE()) - 29
|
||||||
GROUP BY
|
GROUP BY
|
||||||
prep.Expr1,
|
prep.Expr1,
|
||||||
prep.NAZIONE,
|
prep.NAZIONE,
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ WITH PreparaPackingList AS (
|
|||||||
ON SAMA1.dbo.BAMTES.IDMTRASP = SAMA1.dbo.MTRASP.ID
|
ON SAMA1.dbo.BAMTES.IDMTRASP = SAMA1.dbo.MTRASP.ID
|
||||||
WHERE SAMA1.dbo.BAMTES.ANNDOC >= YEAR(GETDATE())
|
WHERE SAMA1.dbo.BAMTES.ANNDOC >= YEAR(GETDATE())
|
||||||
AND SAMA1.dbo.BAMTES.STATO = 'P'
|
AND SAMA1.dbo.BAMTES.STATO = 'P'
|
||||||
AND SAMA1.dbo.BAMTES.DATDOC > CAST((GETDATE() - 30) AS int)
|
AND SAMA1.dbo.BAMTES.DATDOC >= DATEDIFF(day, CONVERT(date, '18991230', 112), GETDATE()) - 29
|
||||||
AND SAMA1.dbo.LOTSER.NUMLOT <> '00000000000'
|
AND SAMA1.dbo.LOTSER.NUMLOT <> '00000000000'
|
||||||
GROUP BY
|
GROUP BY
|
||||||
SAMA1.dbo.LOTSER.NUMLOT,
|
SAMA1.dbo.LOTSER.NUMLOT,
|
||||||
|
|||||||
@@ -107,7 +107,7 @@ WITH PreparaPackingList AS (
|
|||||||
ON n.ID = bt.IDNAZDEST
|
ON n.ID = bt.IDNAZDEST
|
||||||
WHERE bt.ANNDOC >= YEAR(GETDATE())
|
WHERE bt.ANNDOC >= YEAR(GETDATE())
|
||||||
AND bt.STATO = 'P'
|
AND bt.STATO = 'P'
|
||||||
AND bt.DATDOC > CAST((GETDATE() - 30) AS int)
|
AND bt.DATDOC >= DATEDIFF(day, CONVERT(date, '18991230', 112), GETDATE()) - 29
|
||||||
AND ls.NUMLOT <> '00000000000'
|
AND ls.NUMLOT <> '00000000000'
|
||||||
GROUP BY
|
GROUP BY
|
||||||
ls.NUMLOT,
|
ls.NUMLOT,
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ import asyncio
|
|||||||
import sys
|
import sys
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from concurrent.futures import Future
|
from concurrent.futures import Future
|
||||||
from tkinter import messagebox, ttk
|
import error_dialog as messagebox
|
||||||
|
from tkinter import ttk
|
||||||
from typing import Callable
|
from typing import Callable
|
||||||
|
|
||||||
from runtime_support import configure_exception_logging, ensure_stdio, log_exception, run_with_fatal_log
|
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):
|
elif isinstance(result, BarcodeViewState):
|
||||||
self._apply_state(result)
|
self._apply_state(result)
|
||||||
|
|
||||||
def _show_transaction_error(self) -> None:
|
def _show_transaction_error(self, exception: Exception) -> None:
|
||||||
messagebox.showerror(
|
messagebox.showerror(
|
||||||
"Barcode WMS",
|
"Barcode WMS",
|
||||||
"Operazione non completata.\n\n"
|
"Operazione non completata.\n\n"
|
||||||
"Ripeti la lettura o avvisa il responsabile.\n"
|
"Ripeti la lettura o avvisa il responsabile.\n"
|
||||||
"Il dettaglio tecnico e' stato scritto nel log.",
|
"Il dettaglio tecnico e' stato scritto nel log.",
|
||||||
parent=self.root,
|
parent=self.root,
|
||||||
|
exception=exception,
|
||||||
)
|
)
|
||||||
|
|
||||||
def _poll_recovery_future(self, original_exception: Exception) -> None:
|
def _poll_recovery_future(self, original_exception: Exception) -> None:
|
||||||
if self._pending is None:
|
if self._pending is None:
|
||||||
self._set_busy(False)
|
self._set_busy(False)
|
||||||
self._show_transaction_error()
|
self._show_transaction_error(original_exception)
|
||||||
return
|
return
|
||||||
if not self._pending.done():
|
if not self._pending.done():
|
||||||
self.root.after(40, lambda err=original_exception: self._poll_recovery_future(err))
|
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_text = "Transazione non completata, ripeti l'operazione."
|
||||||
current.status_color = "#f4cccc"
|
current.status_color = "#f4cccc"
|
||||||
self._apply_state(current)
|
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
|
return
|
||||||
|
|
||||||
if isinstance(result, BarcodeActionResult):
|
if isinstance(result, BarcodeActionResult):
|
||||||
self._apply_state(result.state)
|
self._apply_state(result.state)
|
||||||
if not result.ok:
|
if not result.ok:
|
||||||
self.root.bell()
|
self.root.bell()
|
||||||
self._show_transaction_error()
|
self._show_transaction_error(original_exception)
|
||||||
elif isinstance(result, BarcodeViewState):
|
elif isinstance(result, BarcodeViewState):
|
||||||
self._apply_state(result)
|
self._apply_state(result)
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ import asyncio
|
|||||||
import json
|
import json
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from tkinter import messagebox, ttk
|
import error_dialog as messagebox
|
||||||
|
from tkinter import ttk
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from async_msssql_query import AsyncMSSQLClient, make_mssql_dsn
|
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.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),
|
loc_text("dbconfig.msg.test_error", catalog=self._locale_catalog, default="Connessione fallita:\n{error}").format(error=ex),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=ex,
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
messagebox.showinfo(
|
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.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),
|
loc_text("dbconfig.msg.save_error", catalog=self._locale_catalog, default="Salvataggio fallito:\n{error}").format(error=ex),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=ex,
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
self.result_config = config
|
self.result_config = config
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from tkinter import filedialog, messagebox, ttk
|
import error_dialog as messagebox
|
||||||
|
from tkinter import filedialog, ttk
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import customtkinter as ctk
|
import customtkinter as ctk
|
||||||
@@ -399,6 +400,7 @@ class DiagnosticaWindow(ctk.CTkToplevel):
|
|||||||
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
|
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
|
||||||
str(exc),
|
str(exc),
|
||||||
parent=self if self._is_alive() else None,
|
parent=self if self._is_alive() else None,
|
||||||
|
exception=exc,
|
||||||
)
|
)
|
||||||
|
|
||||||
def _on_loaded(self, res: dict[str, Any] | None) -> None:
|
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"),
|
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
|
||||||
str(exc),
|
str(exc),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=exc,
|
||||||
)
|
)
|
||||||
|
|
||||||
def _on_error(self, exc: BaseException) -> None:
|
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"),
|
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
|
||||||
str(exc),
|
str(exc),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=exc,
|
||||||
)
|
)
|
||||||
|
|
||||||
def _export_xlsx(self) -> None:
|
def _export_xlsx(self) -> None:
|
||||||
@@ -477,6 +481,7 @@ class DiagnosticaWindow(ctk.CTkToplevel):
|
|||||||
default="Per l'esportazione serve 'openpyxl' (pip install openpyxl).",
|
default="Per l'esportazione serve 'openpyxl' (pip install openpyxl).",
|
||||||
).format(error=exc),
|
).format(error=exc),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=exc,
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -531,6 +536,7 @@ class DiagnosticaWindow(ctk.CTkToplevel):
|
|||||||
default="Errore durante l'esportazione:\n{error}",
|
default="Errore durante l'esportazione:\n{error}",
|
||||||
).format(error=exc),
|
).format(error=exc),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=exc,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
107
docs/aggiornamento_monolista_bat.md
Normal file
107
docs/aggiornamento_monolista_bat.md
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
# Aggiornare un desktop di reparto con il file BAT
|
||||||
|
|
||||||
|
Il file `aggiorna_monolista.bat` si esegue SUL COMPUTER DA AGGIORNARE, anche da
|
||||||
|
una sessione Desktop Remoto. Non e' un comando che aggiorna tutti i PC da solo.
|
||||||
|
Prima deve essere riuscito il push del PC di sviluppo su Gitea: lo script puo'
|
||||||
|
scaricare solo cio' che e' effettivamente online.
|
||||||
|
|
||||||
|
## Avvio
|
||||||
|
|
||||||
|
Chiudere applicazione desktop e barcode in tutte le sessioni che usano la stessa
|
||||||
|
cartella. Non e' normalmente necessario eseguire come amministratore: l'utente
|
||||||
|
deve avere i permessi sulla cartella e sull'ambiente Python utilizzato.
|
||||||
|
|
||||||
|
Per la cartella standard `C:\flywms`, doppio clic sul BAT, oppure dal prompt CMD:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
aggiorna_monolista.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
Per scegliere cartella e interprete (lo stesso usato dal collegamento dell'app):
|
||||||
|
|
||||||
|
```bat
|
||||||
|
aggiorna_monolista.bat "C:\flywms" "C:\Python314\python.exe"
|
||||||
|
```
|
||||||
|
|
||||||
|
Se non si indica l'interprete, cerca prima `.venv\Scripts\python.exe` nella
|
||||||
|
cartella dell'applicazione, poi `python` nel PATH. Usare python.exe, non pythonw.exe,
|
||||||
|
per vedere gli errori di installazione. Lo script mostra la versione Python e pip.
|
||||||
|
|
||||||
|
## Comportamento
|
||||||
|
|
||||||
|
1. Chiede conferma che le applicazioni siano chiuse; non uccide processi.
|
||||||
|
2. Controlla clone Git, URL origin, Python/pip e assenza di modifiche ai file tracciati.
|
||||||
|
3. Scarica main da Gitea e verifica che non contenga db_connection.json.
|
||||||
|
4. Si ferma se HEAD o il main locale hanno commit non contenuti nel main remoto.
|
||||||
|
5. Salva un riferimento locale alla versione precedente, passa a main e aggiorna
|
||||||
|
con fast-forward, senza merge automatici di codice o reset distruttivi.
|
||||||
|
6. Esegue `python -m pip install -r requirements.txt` nell'interprete selezionato.
|
||||||
|
7. Mostra il commit installato; solo in caso di successo si puo' riaprire l'app.
|
||||||
|
|
||||||
|
Il BAT gira da una copia in TEMP per non essere interrotto se Git aggiorna il BAT
|
||||||
|
stesso. Non cancella log, ZIP, configurazioni o altri file non tracciati. Se un file
|
||||||
|
non tracciato impedisce il checkout, Git interrompe l'operazione anziche' sovrascriverlo.
|
||||||
|
Non esegue alcuna patch SQL. Le modifiche del 22 ottobre (svuotamento corsie e
|
||||||
|
ricerca UDC nello storico) non richiedono nuove patch SQL.
|
||||||
|
|
||||||
|
## Errori e ripristino
|
||||||
|
|
||||||
|
- Autenticazione: servono credenziali/token Git validi sul PC di reparto; il BAT
|
||||||
|
non contiene password e non modifica le credenziali memorizzate.
|
||||||
|
- Modifiche locali: il BAT si ferma. Non usare reset/clean alla cieca.
|
||||||
|
- Installazione da ZIP: occorre prima predisporre un clone Git, separatamente.
|
||||||
|
- Pip fallito: i sorgenti possono essere gia' aggiornati; risolvere l'errore prima
|
||||||
|
di riavviare. Il BAT non promette un rollback automatico dell'ambiente Python.
|
||||||
|
|
||||||
|
La finestra mostra il comando per recuperare i sorgenti precedenti:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
git switch --detach refs/warehouse-backups/pre-update-DATA-ORA
|
||||||
|
```
|
||||||
|
|
||||||
|
Usare il riferimento esatto stampato dal BAT. Per ritrovarlo:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
git for-each-ref --sort=-refname --format="%(refname) %(objectname:short)" refs/warehouse-backups/
|
||||||
|
```
|
||||||
|
|
||||||
|
Il ripristino riguarda esclusivamente i file Git: non annulla movimenti sul DB,
|
||||||
|
patch SQL, configurazioni locali o aggiornamenti dei pacchetti Python. La copia
|
||||||
|
locale db_connection.json non viene caricata da Gitea e rimane quella del reparto.
|
||||||
|
|
||||||
|
Il codice di uscita e' 0 per successo, 1 per errore, 2 per annullamento.
|
||||||
|
|
||||||
|
## Errore Unlink su .git/objects/pack/*.idx
|
||||||
|
|
||||||
|
Durante fetch Git puo' lanciare automaticamente manutenzione/ricompattazione.
|
||||||
|
Su Windows questa puo' fallire quando un vecchio indice pack e' bloccato da un
|
||||||
|
processo o non puo' essere eliminato per motivi di permessi. Il messaggio da solo
|
||||||
|
non identifica chi blocca il file. Non cancellare manualmente file .idx o .pack.
|
||||||
|
|
||||||
|
Il BAT disabilita la manutenzione automatica SOLO per fetch e merge, tramite
|
||||||
|
`git -c maintenance.auto=false -c gc.auto=0 ...`. Non modifica la configurazione
|
||||||
|
permanente di Git e non arresta eventuali manutenzioni gia' in corso o pianificate.
|
||||||
|
Non risolve permessi mancanti o blocchi che impediscono la normale scrittura Git.
|
||||||
|
|
||||||
|
Per recuperare il nuovo BAT mentre si dispone ancora di quello precedente, dopo
|
||||||
|
aver terminato l'operazione Git precedente, dal prompt CMD:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
cd /d C:\flywms
|
||||||
|
git -c maintenance.auto=false -c gc.auto=0 fetch origin refs/heads/main
|
||||||
|
```
|
||||||
|
|
||||||
|
Solo se fetch ha successo, estrarre il BAT in una cartella esterna gia' esistente:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
git show FETCH_HEAD:aggiorna_monolista.bat > C:\tmp\aggiorna_monolista_nuovo.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
Solo se anche questo comando ha successo:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
C:\tmp\aggiorna_monolista_nuovo.bat C:\flywms C:\Python314\python.exe
|
||||||
|
```
|
||||||
|
|
||||||
|
Questa procedura non modifica singolarmente il BAT tracciato nella cartella
|
||||||
|
installata (che altrimenti risulterebbe modificato e bloccherebbe i controlli).
|
||||||
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 logging
|
||||||
import sys
|
import sys
|
||||||
import tkinter as tk
|
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
|
import customtkinter as ctk
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
@@ -750,7 +751,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
|||||||
target=target_barcode_cella,
|
target=target_barcode_cella,
|
||||||
details={"barcode_pallet": barcode_pallet, "error": str(ex)},
|
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(
|
self._async.run(
|
||||||
move_pallet_async(
|
move_pallet_async(
|
||||||
@@ -838,7 +839,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
|||||||
target=self._cell_label(r, c),
|
target=self._cell_label(r, c),
|
||||||
details={"idcella": idcella, "stato": int(stato), "error": str(ex)},
|
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._async.run(
|
||||||
self.db.exec(SQL_SET_CELL_PRENOTAZIONE, params, commit=True),
|
self.db.exec(SQL_SET_CELL_PRENOTAZIONE, params, commit=True),
|
||||||
@@ -899,7 +900,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
|||||||
target=self._cell_label(r, c),
|
target=self._cell_label(r, c),
|
||||||
details={"idcella": idcella, "stato": int(stato), "error": str(ex)},
|
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._async.run(
|
||||||
self.db.exec(SQL_SET_CELL_PRENOTAZIONE, params, commit=True),
|
self.db.exec(SQL_SET_CELL_PRENOTAZIONE, params, commit=True),
|
||||||
@@ -1000,7 +1001,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
|||||||
return
|
return
|
||||||
self._busy.hide()
|
self._busy.hide()
|
||||||
_MODULE_LOGGER.exception(f"Errore caricamento corsie: {ex}")
|
_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…")
|
self._async.run(self.db.query_json(sql, {}), _ok, _err, busy=self._busy, message="Carico corsie…")
|
||||||
|
|
||||||
@_log_call()
|
@_log_call()
|
||||||
@@ -1179,7 +1180,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
|||||||
return
|
return
|
||||||
self._busy.hide()
|
self._busy.hide()
|
||||||
_MODULE_LOGGER.exception(f"Errore caricamento matrice corsia={corsia}: {ex}")
|
_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}…")
|
self._async.run(self.db.query_json(sql, {"corsia": corsia}), _ok, _err, busy=self._busy, message=f"Carico corsia {corsia}…")
|
||||||
|
|
||||||
# ---------------- SEARCH ----------------
|
# ---------------- SEARCH ----------------
|
||||||
@@ -1233,7 +1234,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
|||||||
if search_req_id < self._last_req:
|
if search_req_id < self._last_req:
|
||||||
return
|
return
|
||||||
_MODULE_LOGGER.exception(f"Errore ricerca UDC barcode={barcode}: {ex}")
|
_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…")
|
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 import Workbook
|
||||||
from openpyxl.styles import PatternFill, Alignment, Font
|
from openpyxl.styles import PatternFill, Alignment, Font
|
||||||
except Exception as ex:
|
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
|
return
|
||||||
rows = len(self.matrix_state)
|
rows = len(self.matrix_state)
|
||||||
cols = len(self.matrix_state[0]) if self.matrix_state else 0
|
cols = len(self.matrix_state[0]) if self.matrix_state else 0
|
||||||
@@ -1317,7 +1318,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
|||||||
wb.save(path)
|
wb.save(path)
|
||||||
self._toast(f"Esportato: {path}")
|
self._toast(f"Esportato: {path}")
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
messagebox.showerror("Export", f"Salvataggio fallito:\n{ex}")
|
messagebox.showerror("Export", f"Salvataggio fallito:\n{ex}", exception=ex)
|
||||||
|
|
||||||
# ---------------- STATS ----------------
|
# ---------------- STATS ----------------
|
||||||
def _refresh_stats(self):
|
def _refresh_stats(self):
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import json
|
|||||||
import sys
|
import sys
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
import customtkinter as ctk
|
import customtkinter as ctk
|
||||||
from tkinter import messagebox
|
import error_dialog as messagebox
|
||||||
from typing import Optional, Any, Dict, List, Callable
|
from typing import Optional, Any, Dict, List, Callable
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
@@ -213,7 +213,9 @@ if _MODULE_LOG_ENABLED:
|
|||||||
# Operational picking-list management uses the Python-only residual view.
|
# Operational picking-list management uses the Python-only residual view.
|
||||||
# Unlike the historical view, this dataset intentionally contains only UDCs
|
# Unlike the historical view, this dataset intentionally contains only UDCs
|
||||||
# that still have to be exhausted by the warehouse workflow.
|
# that still have to be exhausted by the warehouse workflow.
|
||||||
SQL_PL = """
|
# Include today and the preceding days - 1 civil dates, regardless of time.
|
||||||
|
_SAM_FIRST_DAY = "DATEDIFF(day, CONVERT(date, '18991230', 112), GETDATE()) + 1 - :days"
|
||||||
|
SQL_PL = f"""
|
||||||
SELECT
|
SELECT
|
||||||
COUNT(DISTINCT NULLIF(LTRIM(RTRIM(CAST(Pallet AS varchar(32)))), '')) AS Pallet,
|
COUNT(DISTINCT NULLIF(LTRIM(RTRIM(CAST(Pallet AS varchar(32)))), '')) AS Pallet,
|
||||||
COUNT(DISTINCT Lotto) AS Lotto,
|
COUNT(DISTINCT Lotto) AS Lotto,
|
||||||
@@ -232,16 +234,16 @@ SELECT
|
|||||||
MIN(Ordinamento) AS Ordinamento,
|
MIN(Ordinamento) AS Ordinamento,
|
||||||
MAX(IDStato) AS IDStato
|
MAX(IDStato) AS IDStato
|
||||||
FROM dbo.py_ViewPackingListPrelievo
|
FROM dbo.py_ViewPackingListPrelievo
|
||||||
WHERE DataDocumento > CAST((GETDATE() - :days) AS int)
|
WHERE DataDocumento >= {_SAM_FIRST_DAY}
|
||||||
GROUP BY Documento, CodNazione, NAZIONE, Stato
|
GROUP BY Documento, CodNazione, NAZIONE, Stato
|
||||||
ORDER BY MIN(OrdinePrelievoGruppo), MIN(Ordinamento), Documento, NAZIONE, Stato;
|
ORDER BY MIN(OrdinePrelievoGruppo), MIN(Ordinamento), Documento, NAZIONE, Stato;
|
||||||
"""
|
"""
|
||||||
|
|
||||||
SQL_PL_DETAILS = """
|
SQL_PL_DETAILS = f"""
|
||||||
SELECT *
|
SELECT *
|
||||||
FROM dbo.py_ViewPackingListPrelievo
|
FROM dbo.py_ViewPackingListPrelievo
|
||||||
WHERE Documento = :Documento
|
WHERE Documento = :Documento
|
||||||
AND DataDocumento > CAST((GETDATE() - :days) AS int)
|
AND DataDocumento >= {_SAM_FIRST_DAY}
|
||||||
ORDER BY OrdinePrelievoGruppo, Ordinamento, Pallet;
|
ORDER BY OrdinePrelievoGruppo, Ordinamento, Pallet;
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -1061,7 +1063,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
_MODULE_LOGGER.exception(f"Errore durante il caricamento dettagli del documento {self.detail_doc}: {ex}")
|
_MODULE_LOGGER.exception(f"Errore durante il caricamento dettagli del documento {self.detail_doc}: {ex}")
|
||||||
self.spinner.stop()
|
self.spinner.stop()
|
||||||
self.busy.hide() # Chiudi l'overlay in caso di errore
|
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(
|
self.runner.run(
|
||||||
_job(),
|
_job(),
|
||||||
@@ -1127,7 +1129,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
self._first_loading = False
|
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(
|
self.runner.run(
|
||||||
_job(),
|
_job(),
|
||||||
@@ -1296,7 +1298,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
target=documento,
|
target=documento,
|
||||||
details={"error": str(ex)},
|
details={"error": str(ex)},
|
||||||
)
|
)
|
||||||
messagebox.showerror("Prenota", f"Errore:\n{ex}")
|
messagebox.showerror("Prenota", f"Errore:\n{ex}", exception=ex)
|
||||||
|
|
||||||
self.runner.run(
|
self.runner.run(
|
||||||
_job(),
|
_job(),
|
||||||
@@ -1374,7 +1376,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
target=documento,
|
target=documento,
|
||||||
details={"error": str(ex)},
|
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(
|
self.runner.run(
|
||||||
_job(),
|
_job(),
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ from pathlib import Path
|
|||||||
from typing import Any, Callable
|
from typing import Any, Callable
|
||||||
|
|
||||||
import customtkinter as ctk
|
import customtkinter as ctk
|
||||||
from tkinter import messagebox, ttk
|
import error_dialog as messagebox
|
||||||
|
from tkinter import ttk
|
||||||
|
|
||||||
from gestione_aree import AsyncRunner
|
from gestione_aree import AsyncRunner
|
||||||
from audit_log import log_user_action
|
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.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),
|
loc_text("scarico.msg.load_error", catalog=self._locale_catalog, default="Caricamento UDC fallito:\n{error}").format(error=ex),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=ex,
|
||||||
)
|
)
|
||||||
self._close()
|
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.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),
|
loc_text("scarico.msg.exec_error", catalog=self._locale_catalog, default="Scarico fallito:\n{error}").format(error=ex),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=ex,
|
||||||
)
|
)
|
||||||
|
|
||||||
self._async.run(
|
self._async.run(
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ import asyncio
|
|||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from datetime import date
|
from datetime import date
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from tkinter import filedialog, messagebox, ttk
|
import error_dialog as messagebox
|
||||||
|
from tkinter import filedialog, ttk
|
||||||
|
|
||||||
import customtkinter as ctk
|
import customtkinter as ctk
|
||||||
|
|
||||||
@@ -234,7 +235,7 @@ class InventarioWindow(ctk.CTkToplevel):
|
|||||||
self._set_loading(False)
|
self._set_loading(False)
|
||||||
log_exception(__name__, error, context="inventory report/export")
|
log_exception(__name__, error, context="inventory report/export")
|
||||||
self.var_status.set(self._t("inventory.failed"))
|
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):
|
def _export(self):
|
||||||
if self._loading or not self._report or not self._rows:
|
if self._loading or not self._report or not self._rows:
|
||||||
|
|||||||
20
locale.json
20
locale.json
@@ -1,6 +1,16 @@
|
|||||||
{
|
{
|
||||||
"default_language": "IT",
|
"default_language": "IT",
|
||||||
"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.title": "Inventario",
|
||||||
"inventory.date": "Data (gg/mm/aaaa):",
|
"inventory.date": "Data (gg/mm/aaaa):",
|
||||||
"inventory.load": "Calcola inventario",
|
"inventory.load": "Calcola inventario",
|
||||||
@@ -235,6 +245,16 @@
|
|||||||
"scarico.msg.exec_error": "Scarico fallito:\n{error}"
|
"scarico.msg.exec_error": "Scarico fallito:\n{error}"
|
||||||
},
|
},
|
||||||
"ENG": {
|
"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.title": "Inventory",
|
||||||
"inventory.date": "Date (dd/mm/yyyy):",
|
"inventory.date": "Date (dd/mm/yyyy):",
|
||||||
"inventory.load": "Calculate inventory",
|
"inventory.load": "Calculate inventory",
|
||||||
|
|||||||
@@ -3,7 +3,8 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from tkinter import messagebox, ttk
|
import error_dialog as messagebox
|
||||||
|
from tkinter import ttk
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from audit_log import log_session_event
|
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.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),
|
loc_text("login.msg.error", catalog=self._locale_catalog, default="Verifica credenziali fallita:\n{error}").format(error=ex),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=ex,
|
||||||
)
|
)
|
||||||
|
|
||||||
self._async.run(
|
self._async.run(
|
||||||
|
|||||||
2
main.py
2
main.py
@@ -17,7 +17,7 @@ ensure_stdio("warehouse_main")
|
|||||||
|
|
||||||
import customtkinter as ctk
|
import customtkinter as ctk
|
||||||
from PIL import Image, ImageDraw
|
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_loop_singleton import get_global_loop, stop_global_loop
|
||||||
from async_msssql_query import AsyncMSSQLClient
|
from async_msssql_query import AsyncMSSQLClient
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Any, Callable
|
from typing import Any, Callable
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from tkinter import messagebox
|
import error_dialog as messagebox
|
||||||
|
|
||||||
import customtkinter as ctk
|
import customtkinter as ctk
|
||||||
|
|
||||||
@@ -285,6 +285,7 @@ class PickingListSequenceWindow(ctk.CTkToplevel):
|
|||||||
self._t("picking.sequence.title", "Sequenza di prelievo"),
|
self._t("picking.sequence.title", "Sequenza di prelievo"),
|
||||||
self._t("picking.sequence.msg.load_error", "Errore durante il caricamento:\n{error}", error=exc),
|
self._t("picking.sequence.msg.load_error", "Errore durante il caricamento:\n{error}", error=exc),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=exc,
|
||||||
)
|
)
|
||||||
|
|
||||||
self.runner.run(
|
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.title", "Sequenza di prelievo"),
|
||||||
self._t("picking.sequence.msg.save_error", "Errore durante il salvataggio:\n{error}", error=exc),
|
self._t("picking.sequence.msg.save_error", "Errore durante il salvataggio:\n{error}", error=exc),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=exc,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ import sys
|
|||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from tkinter import messagebox, simpledialog, ttk
|
import error_dialog as messagebox
|
||||||
|
from tkinter import simpledialog, ttk
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import customtkinter as ctk
|
import customtkinter as ctk
|
||||||
@@ -466,7 +467,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
|||||||
|
|
||||||
def _err(ex):
|
def _err(ex):
|
||||||
_MODULE_LOGGER.exception(f"Errore caricamento corsie reset corsie: {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...")
|
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,))
|
self.tree.insert("", "end", values=(ubi, n), tags=(tag,))
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
_MODULE_LOGGER.exception(f"Errore UI refresh reset corsie corsia={corsia}: {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):
|
def _err(ex):
|
||||||
_MODULE_LOGGER.exception(f"Errore refresh reset corsie corsia={corsia}: {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}...")
|
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):
|
def _err_count(ex):
|
||||||
_MODULE_LOGGER.exception(f"Errore conteggio reset corsie corsia={corsia}: {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...")
|
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):
|
def _err_del(ex):
|
||||||
_MODULE_LOGGER.exception(f"Errore reset logico corsie corsia={corsia}: {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}...")
|
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):
|
def _tk_exception(exc_type, exc, tb):
|
||||||
log_exception(app_name, exc, context="tkinter callback")
|
log_exception(app_name, exc, context="tkinter callback")
|
||||||
try:
|
try:
|
||||||
import tkinter.messagebox as messagebox
|
import error_dialog as messagebox
|
||||||
|
|
||||||
messagebox.showerror(
|
messagebox.showerror(
|
||||||
app_name,
|
app_name,
|
||||||
"Errore applicativo registrato nei log.\n\n"
|
"Errore applicativo registrato nei log.\n\n"
|
||||||
"Se l'operazione era in corso, ripeterla o avvisare il responsabile.",
|
"Se l'operazione era in corso, ripeterla o avvisare il responsabile.",
|
||||||
parent=root,
|
parent=root,
|
||||||
|
exception=exc,
|
||||||
|
context="tkinter callback",
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
@@ -150,7 +152,7 @@ def show_fatal_message(app_name: str, exc: BaseException) -> None:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from tkinter import messagebox
|
import error_dialog as messagebox
|
||||||
|
|
||||||
root = tk.Tk()
|
root = tk.Tk()
|
||||||
root.withdraw()
|
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"Se non ci sono, controlla anche:\n{TEMP_DIR}\n\n"
|
||||||
f"{exc}",
|
f"{exc}",
|
||||||
parent=root,
|
parent=root,
|
||||||
|
exception=exc,
|
||||||
)
|
)
|
||||||
root.destroy()
|
root.destroy()
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|||||||
@@ -3,7 +3,8 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from tkinter import filedialog, messagebox, ttk
|
import error_dialog as messagebox
|
||||||
|
from tkinter import filedialog, ttk
|
||||||
|
|
||||||
import customtkinter as ctk
|
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_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),
|
loc_text("search.msg.export_error", catalog=self._locale_catalog, default="Errore durante l'esportazione:{error}").format(error=ex),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=ex,
|
||||||
)
|
)
|
||||||
|
|
||||||
def _on_dclick(self, evt):
|
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"),
|
loc_text("search.msg.error_title", catalog=self._locale_catalog, default="Errore ricerca"),
|
||||||
str(ex),
|
str(ex),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=ex,
|
||||||
)
|
)
|
||||||
|
|
||||||
self._async.run(
|
self._async.run(
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ BEGIN TRY
|
|||||||
IF (SELECT COUNT(*) FROM SAMA1.dbo.BAMTES b WITH (UPDLOCK,HOLDLOCK)
|
IF (SELECT COUNT(*) FROM SAMA1.dbo.BAMTES b WITH (UPDLOCK,HOLDLOCK)
|
||||||
JOIN @Targets t ON b.ID=t.ID AND b.NUMDOC=t.Documento
|
JOIN @Targets t ON b.ID=t.ID AND b.NUMDOC=t.Documento
|
||||||
WHERE b.ANNDOC=2026 AND b.STATO='D'
|
WHERE b.ANNDOC=2026 AND b.STATO='D'
|
||||||
AND b.DATDOC>CAST(GETDATE()-30 AS int)) <> 4
|
AND b.DATDOC >= DATEDIFF(day, CONVERT(date, '18991230', 112), GETDATE()) - 29) <> 4
|
||||||
THROW 51002, 'Le quattro testate non corrispondono allo scenario atteso.', 1;
|
THROW 51002, 'Le quattro testate non corrispondono allo scenario atteso.', 1;
|
||||||
|
|
||||||
IF EXISTS (
|
IF EXISTS (
|
||||||
@@ -66,7 +66,7 @@ BEGIN TRY
|
|||||||
|
|
||||||
IF (SELECT COUNT(DISTINCT Documento) FROM dbo.py_ViewPackingListPrelievo
|
IF (SELECT COUNT(DISTINCT Documento) FROM dbo.py_ViewPackingListPrelievo
|
||||||
WHERE Documento IN (233,234,240,241,244)
|
WHERE Documento IN (233,234,240,241,244)
|
||||||
AND DataDocumento>CAST(GETDATE()-30 AS int))<>5
|
AND DataDocumento >= DATEDIFF(day, CONVERT(date, '18991230', 112), GETDATE()) - 29)<>5
|
||||||
THROW 51007, 'Le cinque liste non risultano tutte visibili. Rollback.', 1;
|
THROW 51007, 'Le cinque liste non risultano tutte visibili. Rollback.', 1;
|
||||||
|
|
||||||
COMMIT TRANSACTION;
|
COMMIT TRANSACTION;
|
||||||
|
|||||||
@@ -11,7 +11,8 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from datetime import date, datetime, timedelta
|
from datetime import date, datetime, timedelta
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from tkinter import messagebox, ttk
|
import error_dialog as messagebox
|
||||||
|
from tkinter import ttk
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import customtkinter as ctk
|
import customtkinter as ctk
|
||||||
@@ -146,8 +147,8 @@ def _format_date(value: Any) -> str:
|
|||||||
return value.strftime("%d/%m/%Y")
|
return value.strftime("%d/%m/%Y")
|
||||||
if isinstance(value, (int, float)):
|
if isinstance(value, (int, float)):
|
||||||
try:
|
try:
|
||||||
# SQL Server numeric datetime: CAST(datetime AS int), day 0 = 1900-01-01.
|
# DATDOC is a SAM day serial; its fractional part is not a new day.
|
||||||
return (datetime(1900, 1, 1) + timedelta(days=int(value))).strftime("%d/%m/%Y")
|
return (date(1899, 12, 30) + timedelta(days=int(value))).strftime("%d/%m/%Y")
|
||||||
except Exception:
|
except Exception:
|
||||||
return str(value)
|
return str(value)
|
||||||
text = str(value).strip()
|
text = str(value).strip()
|
||||||
@@ -351,6 +352,7 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
|||||||
default="Errore caricamento:\n{error}",
|
default="Errore caricamento:\n{error}",
|
||||||
).format(error=ex),
|
).format(error=ex),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=ex,
|
||||||
)
|
)
|
||||||
|
|
||||||
self._async.run(
|
self._async.run(
|
||||||
@@ -453,6 +455,7 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
|||||||
default="Errore dettaglio:\n{error}",
|
default="Errore dettaglio:\n{error}",
|
||||||
).format(error=ex),
|
).format(error=ex),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=ex,
|
||||||
)
|
)
|
||||||
|
|
||||||
self._async.run(
|
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"),
|
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
|
||||||
f"Versamento residui fallito:\n{ex}",
|
f"Versamento residui fallito:\n{ex}",
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=ex,
|
||||||
)
|
)
|
||||||
|
|
||||||
self._async.run(
|
self._async.run(
|
||||||
|
|||||||
@@ -3,7 +3,8 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from tkinter import messagebox, ttk
|
import error_dialog as messagebox
|
||||||
|
from tkinter import ttk
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import customtkinter as ctk
|
import customtkinter as ctk
|
||||||
@@ -269,6 +270,7 @@ class StoricoUDCWindow(ctk.CTkToplevel):
|
|||||||
default="Errore ricerca:\n{error}",
|
default="Errore ricerca:\n{error}",
|
||||||
).format(error=ex),
|
).format(error=ex),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=ex,
|
||||||
)
|
)
|
||||||
|
|
||||||
self._async.run(
|
self._async.run(
|
||||||
|
|||||||
93
tests/test_deploy_bat.py
Normal file
93
tests/test_deploy_bat.py
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
"""Run the deployment BAT against disposable local Git repositories, never production."""
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(os.name == "nt" and shutil.which("git"), "Windows/Git required")
|
||||||
|
class DeployBatTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory(prefix="warehouse deploy test ")
|
||||||
|
self.addCleanup(self.tmp.cleanup)
|
||||||
|
self.base = Path(self.tmp.name)
|
||||||
|
self.remote = self.base / "remote.git"
|
||||||
|
self.seed = self.base / "seed"
|
||||||
|
self.deploy = self.base / "deploy"
|
||||||
|
self.git("init", "--bare", str(self.remote), cwd=self.base)
|
||||||
|
self.git("init", "-b", "main", str(self.seed), cwd=self.base)
|
||||||
|
self.git("config", "user.email", "test@example.invalid", cwd=self.seed)
|
||||||
|
self.git("config", "user.name", "Deployment Test", cwd=self.seed)
|
||||||
|
(self.seed / "requirements.txt").write_text("", encoding="ascii")
|
||||||
|
(self.seed / "sample.txt").write_text("before", encoding="ascii")
|
||||||
|
self.git("add", ".", cwd=self.seed)
|
||||||
|
self.git("commit", "-m", "initial", cwd=self.seed)
|
||||||
|
self.git("remote", "add", "origin", self.remote.as_posix(), cwd=self.seed)
|
||||||
|
self.git("push", "origin", "main", cwd=self.seed)
|
||||||
|
self.git("clone", "--branch", "main", self.remote.as_posix(), str(self.deploy), cwd=self.base)
|
||||||
|
self.before = self.git("rev-parse", "HEAD", cwd=self.deploy).strip()
|
||||||
|
(self.deploy / "db_connection.json").write_text('LOCAL CONFIG', encoding="ascii")
|
||||||
|
(self.seed / "sample.txt").write_text("after", encoding="ascii")
|
||||||
|
self.git("commit", "-am", "update", cwd=self.seed)
|
||||||
|
self.git("push", "origin", "main", cwd=self.seed)
|
||||||
|
self.target = self.git("rev-parse", "HEAD", cwd=self.seed).strip()
|
||||||
|
# Only the test copy accepts the disposable local remote.
|
||||||
|
source = (Path(__file__).resolve().parents[1] / "aggiorna_monolista.bat").read_text(encoding="ascii")
|
||||||
|
source = source.replace("https://gitea.alessandrobonvicini.it/administrator/ware_house.git", self.remote.as_posix())
|
||||||
|
self.script = self.base / "update test.bat"
|
||||||
|
self.script.write_text(source, encoding="ascii")
|
||||||
|
|
||||||
|
def git(self, *args, cwd):
|
||||||
|
return subprocess.check_output(["git", *args], cwd=cwd, stderr=subprocess.STDOUT, text=True)
|
||||||
|
|
||||||
|
def run_script(self, confirmation="S"):
|
||||||
|
env = os.environ.copy()
|
||||||
|
env.update(TEMP=str(self.base), TMP=str(self.base), PIP_NO_INDEX="1", PIP_DISABLE_PIP_VERSION_CHECK="1",
|
||||||
|
GIT_TRACE2_EVENT=str(self.base / "git-trace.jsonl"))
|
||||||
|
command = f'""{self.script}" "{self.deploy}" "{sys.executable}""'
|
||||||
|
return subprocess.run("cmd.exe /d /s /c " + command,
|
||||||
|
input=confirmation + "\n\n", text=True, capture_output=True, env=env, timeout=60)
|
||||||
|
|
||||||
|
def test_success_preserves_config_and_saves_previous_commit(self):
|
||||||
|
self.git("config", "maintenance.auto", "true", cwd=self.deploy)
|
||||||
|
self.git("config", "gc.auto", "1", cwd=self.deploy)
|
||||||
|
result = self.run_script()
|
||||||
|
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||||
|
self.assertIn("AGGIORNAMENTO COMPLETATO", result.stdout)
|
||||||
|
self.assertEqual(self.git("rev-parse", "HEAD", cwd=self.deploy).strip(), self.target)
|
||||||
|
self.assertEqual((self.deploy / "db_connection.json").read_text(), "LOCAL CONFIG")
|
||||||
|
refs = self.git("for-each-ref", "--format=%(objectname)", "refs/warehouse-backups/", cwd=self.deploy)
|
||||||
|
self.assertIn(self.before, refs)
|
||||||
|
import json
|
||||||
|
trace = [json.loads(line) for line in (self.base / "git-trace.jsonl").read_text(encoding="utf-8").splitlines()]
|
||||||
|
children = [event.get("argv", []) for event in trace if event.get("event") == "child_start"]
|
||||||
|
self.assertFalse(any("maintenance" in args or "gc" in args for args in children), children)
|
||||||
|
self.assertEqual(self.git("config", "maintenance.auto", cwd=self.deploy).strip(), "true")
|
||||||
|
self.assertEqual(self.git("config", "gc.auto", cwd=self.deploy).strip(), "1")
|
||||||
|
|
||||||
|
def test_dirty_checkout_is_not_overwritten(self):
|
||||||
|
(self.deploy / "sample.txt").write_text("local", encoding="ascii")
|
||||||
|
result = self.run_script()
|
||||||
|
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
|
||||||
|
self.assertIn("modifiche locali", result.stdout)
|
||||||
|
self.assertEqual((self.deploy / "sample.txt").read_text(), "local")
|
||||||
|
self.assertEqual(self.git("rev-parse", "HEAD", cwd=self.deploy).strip(), self.before)
|
||||||
|
|
||||||
|
def test_cancel_does_not_update(self):
|
||||||
|
result = self.run_script("N")
|
||||||
|
self.assertEqual(result.returncode, 2, result.stdout + result.stderr)
|
||||||
|
self.assertEqual(self.git("rev-parse", "HEAD", cwd=self.deploy).strip(), self.before)
|
||||||
|
|
||||||
|
def test_remote_database_config_blocks_update(self):
|
||||||
|
(self.seed / "db_connection.json").write_text("REMOTE CONFIG", encoding="ascii")
|
||||||
|
self.git("add", "db_connection.json", cwd=self.seed)
|
||||||
|
self.git("commit", "-m", "bad config", cwd=self.seed)
|
||||||
|
self.git("push", "origin", "main", cwd=self.seed)
|
||||||
|
result = self.run_script()
|
||||||
|
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
|
||||||
|
self.assertIn("il ramo remoto contiene db_connection.json", result.stdout)
|
||||||
|
self.assertEqual((self.deploy / "db_connection.json").read_text(), "LOCAL CONFIG")
|
||||||
|
self.assertEqual(self.git("rev-parse", "HEAD", cwd=self.deploy).strip(), self.before)
|
||||||
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.assertNotEqual(self.win.var_status.get(), self.win._t("inventory.scope"))
|
||||||
self.win._loaded(self.sample())
|
self.win._loaded(self.sample())
|
||||||
self.assertEqual([label.cget("text") for label in self.win.legend_descriptions], descriptions)
|
self.assertEqual([label.cget("text") for label in self.win.legend_descriptions], descriptions)
|
||||||
with patch("inventario.messagebox.showerror"), patch("inventario.log_exception"):
|
error = RuntimeError("Synthetic failure")
|
||||||
self.win._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)
|
self.assertEqual([label.cget("text") for label in self.win.legend_descriptions], descriptions)
|
||||||
|
|
||||||
def test_legend_wraps_to_window_width(self):
|
def test_legend_wraps_to_window_width(self):
|
||||||
|
|||||||
62
tests/test_sam_date_origin.py
Normal file
62
tests/test_sam_date_origin.py
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
"""Diagnostic anchor from the SAM print: serial 43570 means 15 April 2019."""
|
||||||
|
import os
|
||||||
|
import unittest
|
||||||
|
from datetime import date, datetime
|
||||||
|
|
||||||
|
from inventory_service import inventory_cutoff
|
||||||
|
from storico_pickinglist import _format_date
|
||||||
|
|
||||||
|
|
||||||
|
class SamDateOriginTest(unittest.TestCase):
|
||||||
|
def test_inventory_exclusive_midnight_matches_sam_anchor(self):
|
||||||
|
_, cutoff, serial = inventory_cutoff("15/04/2019", today=date(2026, 11, 6))
|
||||||
|
self.assertEqual(cutoff, datetime(2019, 4, 16))
|
||||||
|
self.assertEqual(serial, 43571)
|
||||||
|
|
||||||
|
def test_native_datetime_preserved(self):
|
||||||
|
self.assertEqual(_format_date(datetime(2019, 4, 15, 18)), "15/04/2019")
|
||||||
|
|
||||||
|
def test_history_formats_sam_numeric_anchor(self):
|
||||||
|
self.assertEqual(_format_date(43570.0), "15/04/2019")
|
||||||
|
|
||||||
|
def test_document_244_changes_day_at_midnight_not_noon(self):
|
||||||
|
for fraction in (0, 0.49999, 0.5, 0.99999):
|
||||||
|
with self.subTest(fraction=fraction):
|
||||||
|
self.assertEqual(_format_date(46289 + fraction), "24/09/2026")
|
||||||
|
self.assertEqual(_format_date(46290), "25/09/2026")
|
||||||
|
|
||||||
|
def test_non_serial_inputs_are_not_shifted(self):
|
||||||
|
for value, expected in ((None, ""), (date(2024, 2, 29), "29/02/2024"),
|
||||||
|
("20260924", "24/09/2026"),
|
||||||
|
("2026-09-24T23:59:59", "24/09/2026")):
|
||||||
|
with self.subTest(value=value):
|
||||||
|
self.assertEqual(_format_date(value), expected)
|
||||||
|
|
||||||
|
@unittest.skipUnless(os.getenv("SAM_DATE_TEST_LOCAL") == "1", "opt-in local SQL Server test")
|
||||||
|
def test_actual_master_and_detail_filters_on_local_sql_server(self):
|
||||||
|
import pyodbc
|
||||||
|
from gestione_pickinglist import SQL_PL, SQL_PL_DETAILS
|
||||||
|
|
||||||
|
cn = pyodbc.connect("DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;"
|
||||||
|
"DATABASE=tempdb;Trusted_Connection=yes;", timeout=5)
|
||||||
|
self.addCleanup(cn.close)
|
||||||
|
# No warehouse objects: replace only the source and clock of each real query.
|
||||||
|
source = """(SELECT n AS Documento, n AS DataDocumento, 'x' AS Pallet,
|
||||||
|
1 AS Lotto, 1 AS Articolo, 1 AS Descrizione, 1 AS Qta, 1 AS CodNazione,
|
||||||
|
1 AS NAZIONE, 1 AS Stato, 1 AS PalletCella, 1 AS Magazzino, 1 AS Area,
|
||||||
|
1 AS Cella, 1 AS OrdinePrelievoGruppo, 1 AS Ordinamento, 0 AS IDStato
|
||||||
|
FROM (VALUES (CAST(? AS float))) v(n)) sample"""
|
||||||
|
for days in (10, 15, 20, 30):
|
||||||
|
first = 46289 - days + 1 # 24 September is the final included day.
|
||||||
|
for clock in ("00:00:00", "11:59:59", "12:00:00", "23:59:59"):
|
||||||
|
for serial, inside in ((first - 0.001, False), (first, True), (46289.99, True)):
|
||||||
|
for query in (SQL_PL, SQL_PL_DETAILS):
|
||||||
|
sql = query.replace("dbo.py_ViewPackingListPrelievo", source)
|
||||||
|
sql = sql.replace("GETDATE()", "CONVERT(datetime2, ?, 126)")
|
||||||
|
sql = sql.replace(":days", "?").replace(":Documento", "?")
|
||||||
|
params = [serial]
|
||||||
|
if query == SQL_PL_DETAILS:
|
||||||
|
params.append(serial)
|
||||||
|
params.extend(["2026-09-24T" + clock, days])
|
||||||
|
with self.subTest(days=days, clock=clock, serial=serial, detail=query==SQL_PL_DETAILS):
|
||||||
|
self.assertEqual(bool(cn.execute(sql, *params).fetchall()), inside)
|
||||||
@@ -3,7 +3,8 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from tkinter import messagebox, ttk
|
import error_dialog as messagebox
|
||||||
|
from tkinter import ttk
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import customtkinter as ctk
|
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"),
|
loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"),
|
||||||
str(exc),
|
str(exc),
|
||||||
parent=self if self._is_alive() else None,
|
parent=self if self._is_alive() else None,
|
||||||
|
exception=exc,
|
||||||
)
|
)
|
||||||
|
|
||||||
def _on_loaded(self, res: dict[str, Any] | None) -> None:
|
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"),
|
loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"),
|
||||||
str(exc),
|
str(exc),
|
||||||
parent=self,
|
parent=self,
|
||||||
|
exception=exc,
|
||||||
)
|
)
|
||||||
|
|
||||||
def _on_error(self, exc: BaseException) -> None:
|
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"),
|
loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"),
|
||||||
str(exc),
|
str(exc),
|
||||||
parent=self,
|
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": {
|
"inventory_window": {
|
||||||
"legend_fg_color": ["#f8fafb", "#262b30"],
|
"legend_fg_color": ["#f8fafb", "#262b30"],
|
||||||
"legend_text_color": ["#202830", "#f1f3f5"],
|
"legend_text_color": ["#202830", "#f1f3f5"],
|
||||||
|
|||||||
@@ -9,38 +9,39 @@ APP_VERSION = "1.0.0"
|
|||||||
|
|
||||||
MODULE_VERSIONS: dict[str, str] = {
|
MODULE_VERSIONS: dict[str, str] = {
|
||||||
"app": APP_VERSION,
|
"app": APP_VERSION,
|
||||||
|
"error_dialog": "1.0.0",
|
||||||
"async_loop_singleton": "1.0.0",
|
"async_loop_singleton": "1.0.0",
|
||||||
"async_msssql_query": "1.0.1",
|
"async_msssql_query": "1.0.1",
|
||||||
"audit_log": "1.0.0",
|
"audit_log": "1.0.0",
|
||||||
"main": "1.0.4",
|
"main": "1.0.5",
|
||||||
"inventario": "1.1.1",
|
"inventario": "1.1.2",
|
||||||
"inventory_service": "1.1.0",
|
"inventory_service": "1.1.0",
|
||||||
"barcode_client": "1.0.27",
|
"barcode_client": "1.0.28",
|
||||||
"barcode_repository": "1.0.14",
|
"barcode_repository": "1.0.14",
|
||||||
"barcode_service": "1.0.25",
|
"barcode_service": "1.0.25",
|
||||||
"busy_overlay": "1.0.0",
|
"busy_overlay": "1.0.0",
|
||||||
"db_config": "1.0.0",
|
"db_config": "1.0.1",
|
||||||
"diagnostica": "1.0.4",
|
"diagnostica": "1.0.5",
|
||||||
"gestione_aree": "1.0.1",
|
"gestione_aree": "1.0.1",
|
||||||
"gestione_layout": "1.0.2",
|
"gestione_layout": "1.0.3",
|
||||||
"gestione_pickinglist": "1.0.6",
|
"gestione_pickinglist": "1.0.8",
|
||||||
"gestione_scarico": "1.0.8",
|
"gestione_scarico": "1.0.9",
|
||||||
"locale_text": "1.0.0",
|
"locale_text": "1.0.0",
|
||||||
"login_window": "1.0.0",
|
"login_window": "1.0.1",
|
||||||
"prenota_sprenota_sql": "1.0.1",
|
"prenota_sprenota_sql": "1.0.1",
|
||||||
"pickinglist_sequence": "1.0.0",
|
"pickinglist_sequence": "1.0.1",
|
||||||
"reset_corsie": "1.0.1",
|
"reset_corsie": "1.0.2",
|
||||||
"reset_corsie_service": "1.0.0",
|
"reset_corsie_service": "1.0.0",
|
||||||
"runtime_support": "1.0.1",
|
"runtime_support": "1.0.2",
|
||||||
"search_pallets": "1.0.0",
|
"search_pallets": "1.0.1",
|
||||||
"storico_pickinglist": "1.0.5",
|
"storico_pickinglist": "1.0.7",
|
||||||
"pickinglist_history_search": "1.0.0",
|
"pickinglist_history_search": "1.0.0",
|
||||||
"storico_udc": "1.0.0",
|
"storico_udc": "1.0.1",
|
||||||
"tooltips": "1.0.0",
|
"tooltips": "1.0.0",
|
||||||
"udc_non_scaffalate": "1.0.1",
|
"udc_non_scaffalate": "1.0.2",
|
||||||
"ui_theme": "1.0.0",
|
"ui_theme": "1.0.0",
|
||||||
"user_session": "1.0.3",
|
"user_session": "1.0.3",
|
||||||
"view_celle_multi_udc": "1.0.0",
|
"view_celle_multi_udc": "1.0.1",
|
||||||
"window_placement": "1.0.0",
|
"window_placement": "1.0.0",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ import tkinter as tk
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from tkinter import filedialog, messagebox, ttk
|
import error_dialog as messagebox
|
||||||
|
from tkinter import filedialog, ttk
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import customtkinter as ctk
|
import customtkinter as ctk
|
||||||
@@ -651,7 +652,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
|||||||
|
|
||||||
def _err(ex):
|
def _err(ex):
|
||||||
_MODULE_LOGGER.exception(f"Errore caricamento corsie UDC fantasma: {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(
|
self.runner.run(
|
||||||
_q(self.db),
|
_q(self.db),
|
||||||
@@ -712,7 +713,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
|||||||
|
|
||||||
def _err(ex):
|
def _err(ex):
|
||||||
_MODULE_LOGGER.exception(f"Errore caricamento celle duplicate corsia={corsia}: {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(
|
self.runner.run(
|
||||||
_q(self.db),
|
_q(self.db),
|
||||||
@@ -762,7 +763,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
|||||||
|
|
||||||
def _err(ex):
|
def _err(ex):
|
||||||
_MODULE_LOGGER.exception(f"Errore caricamento pallet cella idcella={idcella}: {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(
|
self.runner.run(
|
||||||
_q(self.db),
|
_q(self.db),
|
||||||
@@ -889,7 +890,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
|||||||
def _err(ex):
|
def _err(ex):
|
||||||
self._busy.hide()
|
self._busy.hide()
|
||||||
_MODULE_LOGGER.exception(f"Errore preselezione fantasmi corsia={corsia}: {ex}")
|
_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(
|
self.runner.run(
|
||||||
_q(self.db),
|
_q(self.db),
|
||||||
@@ -962,7 +963,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
|||||||
def _err(ex):
|
def _err(ex):
|
||||||
self._busy.hide()
|
self._busy.hide()
|
||||||
_MODULE_LOGGER.exception(f"Errore bonifica fantasmi corsia={corsia}: {ex}")
|
_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(
|
self.runner.run(
|
||||||
_q(self.db),
|
_q(self.db),
|
||||||
@@ -982,7 +983,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
|||||||
|
|
||||||
def _err(ex):
|
def _err(ex):
|
||||||
_MODULE_LOGGER.exception(f"Errore caricamento riepilogo UDC fantasma: {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(
|
self.runner.run(
|
||||||
_q(self.db),
|
_q(self.db),
|
||||||
@@ -1095,7 +1096,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
|||||||
messagebox.showinfo("Esportazione completata", f"File creato:\n{fname}", parent=self)
|
messagebox.showinfo("Esportazione completata", f"File creato:\n{fname}", parent=self)
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
_MODULE_LOGGER.exception(f"Errore esportazione UDC fantasma: {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(
|
def open_celle_multiple_window(
|
||||||
|
|||||||
Reference in New Issue
Block a user