Compare commits

..

7 Commits

37 changed files with 2256 additions and 116 deletions

235
GUIDA_INVENTARIO.md Normal file
View File

@@ -0,0 +1,235 @@
# Inventario WMS / SAM: guida alla schermata
Versione della schermata: **1.1.1**, monolista. Aggiornamento: 21/10/2026.
## 1. A cosa serve
La schermata confronta i pezzi ricostruiti dalle registrazioni del WMS e dei
contenitori con i pezzi risultanti nel **Magazzino Principale di SAM**, alla
fine del giorno scelto. Non movimenta materiale e non corregge automaticamente
le differenze: serve a individuarle e a capire dove cercare.
**Attenzione al perimetro:** per ora e' il WMS a guidare la ricerca.
Si parte dalle coppie prodotto/lotto presenti nelle UDC del WMS, nelle aree
5 e 6 oppure non scaffalate, alla data scelta. Per quelle coppie si cercano
anche i contenitori in SAM. Un lotto presente soltanto in confezionamento,
senza alcuna UDC nel WMS, non entra nel report. Quindi non e' ancora un
inventario completo di tutto SAM.
Una UDC puo' contenere piu' bag e piu' lotti. Una bag o una vasca e' un
contenitore identificato in LOTSER: **contenitore, UDC e pezzi sono tre
misure diverse**.
## 2. Come iniziare
1. Apri **Inventario** dal menu principale.
2. Inserisci una data nel formato **gg/mm/aaaa**.
3. Premi **Calcola inventario** e attendi la fine dell'overlay.
4. Guarda **Esito / anomalie** e **Residuo SAM-(A+B+C)** nella griglia alta.
5. Seleziona un prodotto: sotto compaiono le schede **Lotti** e **Contenitori**.
6. Esamina prima il lotto che presenta la differenza, poi i relativi contenitori.
7. Usa **Esporta XLSX** per conservare il risultato o proseguire la verifica.
Le colonne sono numerose: usa la barra orizzontale in fondo alla griglia.
Cliccando un'intestazione della griglia prodotti puoi ordinare i risultati;
un secondo clic inverte l'ordine. L'ordinamento puo' azzerare la selezione:
riseleziona il prodotto per visualizzarne il dettaglio.
## 3. Legenda A, B, C e X
**A: materiale registrato nel WMS.**
Sono i pezzi nelle UDC scaffalate nelle aree 5/6 oppure registrate come
non scaffalate. Nella griglia, A corrisponde alla colonna **Pezzi WMS**.
La quantita' nominale e' ricavata dai carichi produzione dei contenitori:
va validata rispetto alle etichette, non e' una lettura fisica dei pezzi.
**B: materiale assegnato a UDC ma fuori dal WMS.**
Sono contenitori con un numero UDC assegnato, giacenza SAM positiva alla data
e nessuna posizione WMS che li collochi gia' in A o presenti anomalie.
La collocazione in confezionamento e' **dedotta**, non rilevata fisicamente.
Le UDC possono essere piene oppure ancora in riempimento: il report non
determina quale dei due casi si verifichi.
**C: materiale non ancora assegnato a UDC.**
Sono bag o vasche con seriale del tipo **000000/123456** e giacenza SAM
positiva alla data. Possono essere parzialmente piene: si usano i pezzi
registrati, non una capacita' teorica moltiplicata per il numero di bag.
**X: materiale con una classificazione anomala.**
E' esposto nel dettaglio ma non viene aggiunto artificialmente ad A, B o C.
Il suo saldo SAM contribuisce al confronto. Esempio: una UDC risulta spedita
nel WMS ma ha ancora giacenza SAM. Il residuo deve far emergere il problema,
non nasconderlo assegnandolo a B.
Una UDC non scaffalata gia' compresa in A **non viene contata anche in B**.
Le UDC effettivamente spedite alla data non appartengono al normale stock A.
La sola chiusura di un documento non sostituisce un movimento WMS mancante.
## 4. Comandi e messaggi in alto
| Campo o comando | Significato |
| --- | --- |
| Data (gg/mm/aaaa) | Giorno di riferimento, dalla fine del quale si ricostruisce l'inventario. Sono accettate date dal 01/01/2010 a oggi; cio' non garantisce che lo storico sia completo per ogni data. |
| Calcola inventario | Avvia una nuova interrogazione. Aprire la finestra non avvia automaticamente il calcolo. Anche Invio nel campo data lo avvia. |
| Esporta XLSX | Esporta l'ultimo risultato calcolato: prodotti, lotti e contenitori. Non esegue un nuovo calcolo. E' disabilitato prima del risultato, durante le operazioni o in assenza di righe. |
| Legenda A/B/C/X | Definizioni fisse, separate dal messaggio di avanzamento: restano visibili dopo il calcolo. |
| Inventario al ... (fine giornata) | Data effettiva del risultato, da controllare soprattutto se hai modificato il campo data senza premere Calcola. |
| Prodotti | Numero di righe prodotto presenti nel report, non numero di UDC. |
| Da verificare | Numero di prodotti con anomalie di ricostruzione. **Non e' il conteggio di tutte le differenze numeriche**: una differenza senza anomalie si legge nel residuo e nell'esito. |
| Ultimo movimento WMS / SAM | Date massime dei movimenti rilevate nelle fonti. Non certificano quando e' stato effettuato il backup e non sono la data di ogni riga. |
| Giornata corrente non ancora conclusa | Per oggi sono disponibili solo le operazioni gia' registrate: non e' possibile conoscere in anticipo lo stock di questa sera. |
Il limite temporale e' la mezzanotte successiva, esclusa. Ad esempio,
per il 20/10 si considerano le operazioni precedenti alle 00:00 del 21/10.
Non e' una funzionalita' riservata al 31 dicembre.
Se cambi solo la data nel campo, le righe gia' visualizzate e l'eventuale
export rimangono riferiti all'ultimo calcolo. Premi Calcola per aggiornarli.
In caso di errore del nuovo calcolo il risultato precedente viene svuotato,
per evitare di scambiarlo per quello della nuova data.
## 5. Griglia principale: una riga per prodotto
I conteggi con **N.** contano identificativi distinti; gli altri valori
quantitativi sono **pezzi**, non pallet.
| Colonna | Come leggerla |
| --- | --- |
| Prodotto | Codice articolo SAM. E' la chiave per raggruppare i lotti del prodotto inclusi nel perimetro. |
| Descrizione | Descrizione dell'articolo. |
| UM | Unita' di misura. Il calcolo accetta NR, PZ o PCS come pezzi; altre unita' richiedono verifica. |
| N. UDC WMS | Numero di UDC distinte del prodotto comprese in A, scaffalate o non scaffalate. Una UDC con due lotti dello stesso prodotto conta una volta. |
| Pezzi scaffalati | Pezzi di A nelle celle fisiche delle aree 5/6 alla data. |
| Pezzi non scaffalati | Pezzi di A nella locazione virtuale non scaffalata, IDCella 1000. Non sono tutte le UDC presenti in SAM fuori WMS. |
| Pezzi WMS | **A = Pezzi scaffalati + Pezzi non scaffalati**. E' il contenuto nominale delle UDC WMS ricostruito dai carichi produzione. |
| N. UDC fuori WMS | Numero di UDC distinte nella componente B. Non e' il numero delle bag al loro interno. |
| Pezzi B - UDC fuori WMS | Pezzi dei contenitori assegnati alle UDC B, usando la loro giacenza SAM alla data. |
| N. contenitori senza UDC | Numero di identificativi LOTSER distinti in C: bag o vasche senza UDC. |
| Pezzi C - Senza UDC | Pezzi presenti in quei contenitori C secondo il saldo SAM alla data. |
| Totale A+B+C | Quantita' complessiva spiegata dalle tre componenti. Non include X. |
| Pezzi SAM | Giacenza del Magazzino Principale per i soli prodotti/lotti compresi nel perimetro. Puo' includere saldi di contenitori classificati X. |
| Differenza SAM-A | Differenza iniziale: **Pezzi SAM meno Pezzi WMS**. Serve a capire quanta parte potrebbe trovarsi fuori dal WMS. |
| Residuo SAM-(A+B+C) | Differenza che rimane dopo aver aggiunto anche B e C. E' il principale valore da indagare. |
| Esito / anomalie | Esito del confronto o motivi per cui il dato non e' determinabile/affidabile. Un saldo zero con anomalie non va considerato automaticamente corretto. |
**Non sommare indiscriminatamente N. UDC WMS tra prodotti:** una UDC
multicomponente puo' essere contata una volta in ciascun prodotto.
Analogamente non si sommano i conteggi UDC dei lotti per ottenere il
conteggio distinto del prodotto.
## 6. Scheda Lotti
Mostra solo i lotti del prodotto selezionato nella griglia alta.
La colonna **Lotto** identifica NUMLOT. **Prodotto**, **UM**, i conteggi,
le componenti A/B/C, le differenze e l'esito hanno lo stesso significato
della griglia principale, ma sono limitati alla coppia prodotto/lotto.
Non e' ripetuta la descrizione del prodotto.
Controllare sempre questa scheda: un lotto con +100 pezzi e un altro con
-100 producono zero sul prodotto, ma non sono due lotti corretti.
Il programma segnala questa compensazione nell'esito del prodotto.
## 7. Scheda Contenitori
Mostra tutti i contenitori del prodotto selezionato, anche su piu' lotti.
La selezione di una riga nella scheda Lotti non filtra ulteriormente questa
scheda. Per isolare un lotto puoi usare i filtri del foglio XLSX.
| Colonna | Significato |
| --- | --- |
| Componente | A - WMS, B - UDC fuori WMS, C - Senza UDC oppure X - Anomalia / fuori perimetro. |
| Prodotto | Codice del prodotto contenuto nella bag/vasca. |
| Lotto | Lotto del contenitore, NUMLOT. |
| UDC | Numero dell'UDC cui il contenitore risulta assegnato alla data. Vuoto per il prefisso 000000. |
| ID LOTSER | Identificativo tecnico del record contenitore in SAM. Utile per una verifica puntuale; non e' il numero UDC. |
| Seriale contenitore | NUMSER ricostruito alla data: ad esempio 554321/123245 oppure 000000/123456. |
| Cella alla data | Ubicazione WMS ricostruita. Per B/C senza cella compare Confezionamento (dedotto): non e' una cella fisica verificata. |
| Pezzi della componente | Per A: pezzi nominali da carichi produzione. Per B/C: saldo SAM alla data. Per X: quantita' diagnostica, non inclusa in A+B+C. Un dato non determinabile compare come ?. |
| Giacenza SAM contenitore | Saldo di quel singolo record LOTSER nel Magazzino Principale alla data. Puo' differire dal nominale di A. |
| Esito / anomalie | Problemi specifici del contenitore. Una cella vuota in questa colonna significa nessuna anomalia specifica rilevata, non una certificazione fisica del contenuto. |
Il dettaglio serve alla diagnosi, non a una somma manuale indiscriminata:
in caso di posizioni WMS anomale puo' comparire lo stesso contenitore piu'
volte. Nel riepilogo il saldo SAM viene deduplicato e l'anomalia segnalata.
## 8. Esempio completo
Per un prodotto e i suoi lotti inclusi nel perimetro:
| Voce | Pezzi |
| --- | ---: |
| Scaffalati in WMS | 9.000 |
| Non scaffalati in WMS | 1.000 |
| A: Pezzi WMS | 10.000 |
| B: in UDC fuori WMS | 400 |
| C: bag/vasche senza UDC | 200 |
| Totale A+B+C | 10.600 |
| Pezzi SAM | 10.600 |
| Differenza SAM-A | 600 |
| Residuo SAM-(A+B+C) | 0 |
I 600 pezzi di differenza iniziale sono spiegati da B e C.
Se SAM fosse 10.700 con le altre componenti invariate, rimarrebbero **+100**
pezzi da spiegare. Se SAM fosse 10.500, il residuo sarebbe **-100**:
la ricostruzione supererebbe SAM di 100 pezzi.
B e C derivano da SAM stesso: il pareggio indica coerenza documentale,
non dimostra da solo che il materiale sia fisicamente in confezionamento.
## 9. Zero, punto interrogativo, colori ed esiti
- **0**: valore numerico noto pari a zero.
- **?**: quantita' non determinabile. Non va sostituita con zero.
- **Saldo coerente (nominale)**: residuo zero e nessuna anomalia rilevata dal calcolo.
- **Differenza da verificare**: residuo diverso da zero senza ulteriori anomalie diagnostiche.
- **Testo arancione/marrone**, nel tema attuale: riga con differenza numerica.
- **Testo rosso**, nel tema attuale: riga con anomalie; controllare l'esito anche se alcuni valori sono numerici.
| Anomalia | Cosa controllare |
| --- | --- |
| Contenuto UDC non determinabile | Carichi produzione mancanti, non positivi o altre entrate che rendono ambiguo il contenuto nominale. |
| UDC in piu' locazioni | Associazioni WMS multiple alla data scelta. |
| Saldo movimenti UDC anomalo | Coerenza dei prelievi e versamenti WMS, presenza unitaria ed eventuali saldi negativi. |
| Unita' di misura da verificare | UM diversa dai pezzi supportati, oppure incoerente nello stesso aggregato. |
| Movimenti WMS privi di data | Movimenti senza una data utilizzabile: ricostruzione temporale non affidabile. |
| Assegnazione storica non determinabile | Storico NUMSER assente, troppo recente rispetto alla data richiesta o ambiguo. |
| Movimenti o saldo SAM non determinabili | Saldo o dati dei movimenti SAM insufficienti per la ricostruzione. |
| Giacenza SAM negativa | Saldo negativo del contenitore. |
| Seriale contenitore mancante o non valido | NUMSER non interpretabile nel formato atteso. |
| Spedita WMS ma presenza residua da verificare | Incongruenza tra spedizione WMS e presenza/saldo residuo. |
| Presenza fuori perimetro / classificazione anomala | Posizione non appartenente alle categorie ammesse o materiale non classificabile. |
| Contenitore duplicato con dati incompatibili | Stesso contenitore restituito con attributi o quantita' contrastanti. |
| Differenze tra lotti si compensano | Totale prodotto apparentemente corretto, ma differenze nei singoli lotti. |
Un'anomalia puo' rendere ignota solo una parte del risultato: le parti note
restano consultabili. I totali dipendenti da un dato ignoto diventano ?.
## 10. Export e precauzioni
L'XLSX contiene tre fogli: **Inventario**, **Lotti** e **Contenitori**.
Riporta data del calcolo, perimetro e avvertenze. Il foglio prodotti segue
l'ordinamento scelto a video. I dettagli esportati comprendono tutti i
prodotti del report, non solo quello selezionato. Le quantita' ignote sono
celle vuote, mentre gli zeri reali restano numeri zero.
Eseguire la quadratura a movimentazioni ferme e con fonti WMS/SAM coerenti.
Una copia WMS di ieri e una copia SAM di oggi possono generare differenze
che non sono errori fisici. Il report non crea una fotografia atomica dei
due database mentre altri operatori li stanno modificando.
Per una data storica il calcolo usa i movimenti e lo storico delle variazioni
NUMSER disponibile. Uno storico incompleto o modifiche non tracciate
possono impedire una ricostruzione attendibile. Prima dell'uso ufficiale
confrontare alcuni lotti con etichette e inventario SAM alla medesima data.
## 11. Perche' alcune versioni non mostravano A/B/C
Il prototipo Inventario **1.0.0** presente nella cartella di sviluppo bilista
non coincideva con la monolista **1.1.0** pubblicata. Il prototipo non aveva
la stessa legenda e lo stesso dettaglio A/B/C della versione aggiornata.
Non era un cambiamento provocato dai dati o dall'esecuzione del calcolo.
La revisione **1.1.1** presenta A/B/C/X su righe distinte, lettere in grassetto,
contrasto dedicato e testo adattato alla larghezza della finestra. Elimina
la ripetizione iniziale del perimetro. I calcoli e la query non cambiano.

154
aggiorna_monolista.bat Normal file
View 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%

View File

@@ -6,7 +6,8 @@ import asyncio
import sys
import tkinter as tk
from concurrent.futures import Future
from tkinter import messagebox, ttk
import error_dialog as messagebox
from tkinter import ttk
from typing import Callable
from runtime_support import configure_exception_logging, ensure_stdio, log_exception, run_with_fatal_log
@@ -675,19 +676,20 @@ class BarcodeClientApp:
elif isinstance(result, BarcodeViewState):
self._apply_state(result)
def _show_transaction_error(self) -> None:
def _show_transaction_error(self, exception: Exception) -> None:
messagebox.showerror(
"Barcode WMS",
"Operazione non completata.\n\n"
"Ripeti la lettura o avvisa il responsabile.\n"
"Il dettaglio tecnico e' stato scritto nel log.",
parent=self.root,
exception=exception,
)
def _poll_recovery_future(self, original_exception: Exception) -> None:
if self._pending is None:
self._set_busy(False)
self._show_transaction_error()
self._show_transaction_error(original_exception)
return
if not self._pending.done():
self.root.after(40, lambda err=original_exception: self._poll_recovery_future(err))
@@ -704,14 +706,16 @@ class BarcodeClientApp:
current.status_text = "Transazione non completata, ripeti l'operazione."
current.status_color = "#f4cccc"
self._apply_state(current)
self._show_transaction_error()
# Keep both failures when reconciliation also fails asynchronously.
self._show_transaction_error(ExceptionGroup(
"Barcode operation and recovery failed", [original_exception, exc]))
return
if isinstance(result, BarcodeActionResult):
self._apply_state(result.state)
if not result.ok:
self.root.bell()
self._show_transaction_error()
self._show_transaction_error(original_exception)
elif isinstance(result, BarcodeViewState):
self._apply_state(result)

View File

@@ -6,7 +6,8 @@ import asyncio
import json
import tkinter as tk
from pathlib import Path
from tkinter import messagebox, ttk
import error_dialog as messagebox
from tkinter import ttk
from typing import Any
from async_msssql_query import AsyncMSSQLClient, make_mssql_dsn
@@ -373,6 +374,7 @@ class DatabaseConfigWindow(tk.Toplevel):
loc_text("dbconfig.msg.title", catalog=self._locale_catalog, default="Configurazione Database"),
loc_text("dbconfig.msg.test_error", catalog=self._locale_catalog, default="Connessione fallita:\n{error}").format(error=ex),
parent=self,
exception=ex,
)
return
messagebox.showinfo(
@@ -393,6 +395,7 @@ class DatabaseConfigWindow(tk.Toplevel):
loc_text("dbconfig.msg.title", catalog=self._locale_catalog, default="Configurazione Database"),
loc_text("dbconfig.msg.save_error", catalog=self._locale_catalog, default="Salvataggio fallito:\n{error}").format(error=ex),
parent=self,
exception=ex,
)
return
self.result_config = config

View File

@@ -4,7 +4,8 @@ from __future__ import annotations
import tkinter as tk
from datetime import datetime
from tkinter import filedialog, messagebox, ttk
import error_dialog as messagebox
from tkinter import filedialog, ttk
from typing import Any
import customtkinter as ctk
@@ -399,6 +400,7 @@ class DiagnosticaWindow(ctk.CTkToplevel):
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
str(exc),
parent=self if self._is_alive() else None,
exception=exc,
)
def _on_loaded(self, res: dict[str, Any] | None) -> None:
@@ -434,6 +436,7 @@ class DiagnosticaWindow(ctk.CTkToplevel):
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
str(exc),
parent=self,
exception=exc,
)
def _on_error(self, exc: BaseException) -> None:
@@ -446,6 +449,7 @@ class DiagnosticaWindow(ctk.CTkToplevel):
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
str(exc),
parent=self,
exception=exc,
)
def _export_xlsx(self) -> None:
@@ -477,6 +481,7 @@ class DiagnosticaWindow(ctk.CTkToplevel):
default="Per l'esportazione serve 'openpyxl' (pip install openpyxl).",
).format(error=exc),
parent=self,
exception=exc,
)
return
@@ -531,6 +536,7 @@ class DiagnosticaWindow(ctk.CTkToplevel):
default="Errore durante l'esportazione:\n{error}",
).format(error=exc),
parent=self,
exception=exc,
)

View 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
View 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.

View File

@@ -0,0 +1,59 @@
# Ricerca UDC nello storico picking list
Modifica del 22 ottobre 2026. Storico Picking List versione 1.0.5, ramo monolista.
## Uso
- Campo UDC vuoto: rimane la consultazione annuale esistente, con il filtro
facoltativo sul numero documento e ordinamento dalla data piu' recente.
- Campo UDC compilato: premere Invio o Ricarica per trovare le picking list
contenenti quella UDC nell'anno corrente e nel precedente. Nel 2026 sono
2025 e 2026; nel 2027 saranno 2026 e 2027. L'anno e' quello documento SAM,
rispetto alla data del server SQL, non l'anno di creazione della UDC.
- Si cerca il codice UDC completo, non una sua parte; non inserire il suffisso
della bag dopo lo slash. Sono ammessi codici numerici fino a sei cifre,
conservando gli eventuali zeri iniziali.
- Se sono compilati sia Documento sia UDC, i filtri si combinano (AND).
Documento mantiene la ricerca parziale esistente.
- L'anno compare accanto al documento nella griglia. Se ci sono piu' documenti
contenenti la UDC vengono mostrati tutti, anche P e D, non solo l'ultimo.
- Selezionando un risultato si vede il contenuto COMPLETO della lista.
Anche i totali e i residui si riferiscono alla lista intera, non alla sola UDC
cercata. Piu' lotti della stessa UDC non aumentano il numero pallet.
- Per tornare all'elenco annuale, cancellare UDC e premere Ricarica.
## Dati e isolamento
La ricerca dedicata usa query parametrizzate in pickinglist_history_search.py,
attraverso BAMTES, FATRIG, LOTTIBF e LOTSER di SAMA1. Usa LEFT(NUMSER,6) come
identificativo UDC e seleziona documenti P o D, escludendo i lotti vuoti/fittizi
come la vista storica. Le anagrafiche di destinazione sono facoltative: la loro
assenza non nasconde il documento.
La vista annuale esistente non viene allargata. Nessuna tabella, vista o stored
procedure e' creata o modificata; nessuna patch SQL aggiuntiva e' necessaria.
Non cambiano il barcode, la prenotazione o gli oggetti legacy C#.
Il numero documento non e' univoco fra anni. La ricerca conserva BAMTES.ID per
aggregazione, selezione, dettaglio e comando di versamento residui. Non vengono
mescolate, per esempio, la lista 244 del 2025 e la lista 244 del 2026. Una
prenotazione corrente non viene attribuita a una lista omonima dell'anno scorso.
Le ubicazioni e gli stati operativi sono quelli WMS correnti, come nello storico
esistente, non una fotografia delle celle al momento della spedizione. Anche
l'appartenenza della UDC dipende dalle associazioni LOTSER/documenti oggi presenti
nel database, non da un nuovo archivio immutabile.
Le query mantengono esecuzione asincrona e overlay. Risposte tardive di una ricerca
o selezione precedente non sostituiscono il risultato corrente. Il versamento
residui rimane una distinta azione con conferma, mai un effetto della ricerca.
## Distribuzione e verifiche
Distribuire anche pickinglist_history_search.py insieme a storico_pickinglist.py,
version_info.py e locale.json. Non occorre rilanciare full_patch per questa modifica.
tests/test_pickinglist_history_search.py include test con widget Tk reali e query
SQL su sole fixture temporanee: finestra biennale, passaggio di anno, omonimia
dei documenti, UDC multilotto, filtri combinati, dettagli e conteggi completi,
assenza di ubicazione e protezione dalle risposte asincrone obsolete.

View File

@@ -0,0 +1,81 @@
# Svuotamento scaffale/corsia con destinazione automatica
Modifica del 22 ottobre 2026, ramo monolista. Gestione Corsie: versione 1.0.1.
## Obiettivo e confini
Svuotare uno scaffale per rileggere le ubicazioni non equivale a spedire tutte
le UDC. I movimenti eseguiti prima di questa modifica, incluso lo svuotamento
del 21 ottobre, non vengono corretti o riscritti automaticamente.
La selezione continua a essere la corsia/scaffale della finestra Gestione Corsie.
Non vengono coinvolte le altre corsie, le UDC assenti dal WMS o le locazioni
virtuali. Le procedure del barcode e lo scarico manuale da layout non cambiano.
## Regola di destinazione
Per ogni UDC attualmente presente nella corsia si verifica la relazione
`LOTSER -> LOTTIBF -> FATRIG -> BAMTES` in SAMA1. I primi sei caratteri di
`LOTSER.NUMSER` identificano la UDC. Il criterio di definitivo e' `BAMTES.STATO = 'D'`,
lo stesso stato ERP usato nello storico picking list; non e' la prenotazione WMS.
- Almeno un documento definitivo associato: destinazione ID 9999, 7G.1.1, spedita.
- Nessun documento definitivo associato, anche con documento P o senza documento:
destinazione ID 1000, non scaffalata (barcode 9001000).
La ricerca non dipende dall'anno visualizzato nello storico, dai giorni di
visibilita' delle liste o dalla presenza della UDC nelle liste prenotabili.
Piu' lotti/righe/documenti non moltiplicano il movimento: si usa EXISTS.
Se una UDC compare sia in un documento D sia in uno P, prevale D, coerentemente
con il controllo legacy sulle UDC gia' spedite. Il modello presuppone codici UDC
non riutilizzati; eventuali riusi/resi richiedono analisi separata.
## Transazione, controlli e tracciamento
`reset_corsie_service.reset_pallet_async` esegue un singolo batch SQL con
`query_json(commit=True)` e `XACT_ABORT ON`. Ogni UDC ha una propria transazione:
1. Blocca le righe di movimento della UDC durante il controllo e la scrittura.
2. Verifica che la UDC sia ancora nella cella originariamente selezionata e non
presenti altre ubicazioni attive. Le celle virtuali non sono sorgenti valide.
3. Determina la destinazione dalla situazione ERP al momento del movimento.
4. Verifica la presenza della cella virtuale e del versamento sorgente.
5. Registra P dalla sorgente e V nella destinazione, con riferimenti, data e utente;
azzera lo stato della cella sorgente secondo la logica di movimento esistente.
6. Verifica che l'unica ubicazione attiva risultante sia la destinazione attesa.
7. Richiama il controllo prenotazioni Python gia' esistente e conferma.
Un errore annulla la transazione della UDC corrente. Le altre UDC gia' confermate
rimangono movimentate; lo svuotamento non e' una transazione unica di scaffale.
La finestra riporta successi, spedite, non scaffalate ed eventuali errori. Nel log
`reset_corsie.log` ogni successo indica UDC, cella sorgente, destinazione e utente;
ogni errore include la UDC e il dettaglio tecnico. Un'interruzione di rete durante
il commit richiede di ricaricare e verificare la situazione, non di presumere che
il movimento sia certamente annullato. Eseguire lo svuotamento senza movimenti
operativi concorrenti sulla corsia; i controlli non sostituiscono questa cautela.
## Effetto sullo storico picking list
Lo storico calcola i residui dalle ubicazioni correnti: ogni UDC con almeno una
posizione diversa da 9999 e' residua; anche 1000 o l'assenza di un'associazione WMS
sono rappresentati come residui dalla vista storica.
Un documento D passa da **Chiusa ERP con residui** a **Chiusa**, al successivo
aggiornamento della finestra, solo quando TUTTE le sue UDC risultano spedite.
Se lo scaffale svuotato contiene tutti gli ultimi residui, basta questa operazione.
Se rimangono UDC in altri scaffali, non scaffalate o mai registrate nel WMS,
la lista resta correttamente **Chiusa ERP con residui**. Non vengono modificate
le intestazioni o le righe documento SAM. Per chiudere tutti i residui di un
documento esiste gia' il comando dedicato nello storico, con conferma separata.
## Distribuzione e verifica
Non vengono create o alterate tabelle, viste o stored procedure: nessuna nuova
patch SQL da lanciare. Il nuovo modulo Python deve essere distribuito insieme
a reset_corsie.py, version_info.py, locale.json e tooltip.json. Restano necessarie
le patch precedenti e la procedura Python di controllo prenotazioni gia' installata.
I test in tests/test_reset_corsie.py coprono la classificazione, le destinazioni,
la registrazione P/V, i blocchi e il rollback. I test SQL sono attivabili con
RESET_TEST_CONFIG: sostituiscono tutti gli oggetti reali con fixture temporanee
locali alla connessione e non movimentano UDC reali.

193
error_dialog.py Normal file
View 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"

View File

@@ -10,7 +10,8 @@ import json
import logging
import sys
import tkinter as tk
from tkinter import Menu, messagebox, filedialog, simpledialog
import error_dialog as messagebox
from tkinter import Menu, filedialog, simpledialog
import customtkinter as ctk
from datetime import datetime
from functools import wraps
@@ -750,7 +751,7 @@ class LayoutWindow(ctk.CTkToplevel):
target=target_barcode_cella,
details={"barcode_pallet": barcode_pallet, "error": str(ex)},
)
messagebox.showerror("Movimento UDC", f"Operazione fallita:\n{ex}", parent=self)
messagebox.showerror("Movimento UDC", f"Operazione fallita:\n{ex}", parent=self, exception=ex)
self._async.run(
move_pallet_async(
@@ -838,7 +839,7 @@ class LayoutWindow(ctk.CTkToplevel):
target=self._cell_label(r, c),
details={"idcella": idcella, "stato": int(stato), "error": str(ex)},
)
messagebox.showerror("Prenotazione", f"Aggiornamento fallito:\n{ex}", parent=self)
messagebox.showerror("Prenotazione", f"Aggiornamento fallito:\n{ex}", parent=self, exception=ex)
self._async.run(
self.db.exec(SQL_SET_CELL_PRENOTAZIONE, params, commit=True),
@@ -899,7 +900,7 @@ class LayoutWindow(ctk.CTkToplevel):
target=self._cell_label(r, c),
details={"idcella": idcella, "stato": int(stato), "error": str(ex)},
)
messagebox.showerror("Stato cella", f"Aggiornamento fallito:\n{ex}", parent=self)
messagebox.showerror("Stato cella", f"Aggiornamento fallito:\n{ex}", parent=self, exception=ex)
self._async.run(
self.db.exec(SQL_SET_CELL_PRENOTAZIONE, params, commit=True),
@@ -1000,7 +1001,7 @@ class LayoutWindow(ctk.CTkToplevel):
return
self._busy.hide()
_MODULE_LOGGER.exception(f"Errore caricamento corsie: {ex}")
messagebox.showerror("Errore", f"Caricamento corsie fallito:\n{ex}")
messagebox.showerror("Errore", f"Caricamento corsie fallito:\n{ex}", exception=ex)
self._async.run(self.db.query_json(sql, {}), _ok, _err, busy=self._busy, message="Carico corsie…")
@_log_call()
@@ -1179,7 +1180,7 @@ class LayoutWindow(ctk.CTkToplevel):
return
self._busy.hide()
_MODULE_LOGGER.exception(f"Errore caricamento matrice corsia={corsia}: {ex}")
messagebox.showerror("Errore", f"Caricamento matrice {corsia} fallito:\n{ex}")
messagebox.showerror("Errore", f"Caricamento matrice {corsia} fallito:\n{ex}", exception=ex)
self._async.run(self.db.query_json(sql, {"corsia": corsia}), _ok, _err, busy=self._busy, message=f"Carico corsia {corsia}…")
# ---------------- SEARCH ----------------
@@ -1233,7 +1234,7 @@ class LayoutWindow(ctk.CTkToplevel):
if search_req_id < self._last_req:
return
_MODULE_LOGGER.exception(f"Errore ricerca UDC barcode={barcode}: {ex}")
messagebox.showerror("Ricerca", f"Errore ricerca UDC:\n{ex}", parent=self)
messagebox.showerror("Ricerca", f"Errore ricerca UDC:\n{ex}", parent=self, exception=ex)
self._async.run(self.db.query_json(sql, {"barcode": barcode}), _ok, _err, busy=self._busy, message="Cerco UDC…")
@@ -1283,7 +1284,7 @@ class LayoutWindow(ctk.CTkToplevel):
from openpyxl import Workbook
from openpyxl.styles import PatternFill, Alignment, Font
except Exception as ex:
messagebox.showerror("Export", f"Manca openpyxl: {ex}\nInstalla con: pip install openpyxl")
messagebox.showerror("Export", f"Manca openpyxl: {ex}\nInstalla con: pip install openpyxl", exception=ex)
return
rows = len(self.matrix_state)
cols = len(self.matrix_state[0]) if self.matrix_state else 0
@@ -1317,7 +1318,7 @@ class LayoutWindow(ctk.CTkToplevel):
wb.save(path)
self._toast(f"Esportato: {path}")
except Exception as ex:
messagebox.showerror("Export", f"Salvataggio fallito:\n{ex}")
messagebox.showerror("Export", f"Salvataggio fallito:\n{ex}", exception=ex)
# ---------------- STATS ----------------
def _refresh_stats(self):

View File

@@ -10,7 +10,7 @@ import json
import sys
import tkinter as tk
import customtkinter as ctk
from tkinter import messagebox
import error_dialog as messagebox
from typing import Optional, Any, Dict, List, Callable
from dataclasses import dataclass
from functools import wraps
@@ -1061,7 +1061,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
_MODULE_LOGGER.exception(f"Errore durante il caricamento dettagli del documento {self.detail_doc}: {ex}")
self.spinner.stop()
self.busy.hide() # Chiudi l'overlay in caso di errore
messagebox.showerror("DB", f"Errore nel caricamento dettagli:\n{ex}")
messagebox.showerror("DB", f"Errore nel caricamento dettagli:\n{ex}", exception=ex)
self.runner.run(
_job(),
@@ -1127,7 +1127,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
except Exception:
pass
self._first_loading = False
messagebox.showerror("DB", f"Errore nel caricamento:\n{ex}")
messagebox.showerror("DB", f"Errore nel caricamento:\n{ex}", exception=ex)
self.runner.run(
_job(),
@@ -1296,7 +1296,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
target=documento,
details={"error": str(ex)},
)
messagebox.showerror("Prenota", f"Errore:\n{ex}")
messagebox.showerror("Prenota", f"Errore:\n{ex}", exception=ex)
self.runner.run(
_job(),
@@ -1374,7 +1374,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
target=documento,
details={"error": str(ex)},
)
messagebox.showerror("S-prenota", f"Errore:\n{ex}")
messagebox.showerror("S-prenota", f"Errore:\n{ex}", exception=ex)
self.runner.run(
_job(),

View File

@@ -13,7 +13,8 @@ from pathlib import Path
from typing import Any, Callable
import customtkinter as ctk
from tkinter import messagebox, ttk
import error_dialog as messagebox
from tkinter import ttk
from gestione_aree import AsyncRunner
from audit_log import log_user_action
@@ -640,6 +641,7 @@ class ScaricoDialog(ctk.CTkToplevel):
loc_text("scarico.msg.title", catalog=self._locale_catalog, default="Scarica"),
loc_text("scarico.msg.load_error", catalog=self._locale_catalog, default="Caricamento UDC fallito:\n{error}").format(error=ex),
parent=self,
exception=ex,
)
self._close()
@@ -842,6 +844,7 @@ class ScaricoDialog(ctk.CTkToplevel):
loc_text("scarico.msg.title", catalog=self._locale_catalog, default="Scarica"),
loc_text("scarico.msg.exec_error", catalog=self._locale_catalog, default="Scarico fallito:\n{error}").format(error=ex),
parent=self,
exception=ex,
)
self._async.run(

View File

@@ -6,7 +6,8 @@ import asyncio
import tkinter as tk
from datetime import date
from decimal import Decimal
from tkinter import filedialog, messagebox, ttk
import error_dialog as messagebox
from tkinter import filedialog, ttk
import customtkinter as ctk
@@ -51,7 +52,7 @@ class InventarioWindow(ctk.CTkToplevel):
self._descending = False
self._rows = []
self.var_date = tk.StringVar(value=date.today().strftime("%d/%m/%Y"))
self.var_status = tk.StringVar(value=self._t("inventory.scope"))
self.var_status = tk.StringVar(value=self._t("inventory.ready"))
self.title(versioned_title(self._t("inventory.title"), __name__))
self.geometry(str(theme_value(self._theme, "window_geometry", "1200x720")))
self.minsize(*theme_value(self._theme, "window_minsize", [900, 560]))
@@ -63,8 +64,8 @@ class InventarioWindow(ctk.CTkToplevel):
def _build_ui(self):
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(3, weight=3)
self.grid_rowconfigure(5, weight=1)
self.grid_rowconfigure(3, weight=3, minsize=120)
self.grid_rowconfigure(5, weight=1, minsize=150)
top = ctk.CTkFrame(self, fg_color=theme_color(self._theme, "toolbar_frame_fg_color", "#d7d7d7"))
top.grid(row=0, column=0, sticky="ew", padx=8, pady=8)
top.grid_columnconfigure(3, weight=1)
@@ -78,9 +79,7 @@ class InventarioWindow(ctk.CTkToplevel):
self.btn_export = ctk.CTkButton(top, text=self._t("inventory.export"), command=self._export,
font=font, state="disabled")
self.btn_export.grid(row=0, column=4, padx=6)
ctk.CTkLabel(self, text=self._t("inventory.notice") + "\n" + self._t("inventory.scope")
+ "\n" + self._t("inventory.history_notice"), anchor="w", justify="left",
wraplength=1000).grid(row=1, column=0, sticky="ew", padx=10)
self._build_legend()
ctk.CTkLabel(self, textvariable=self.var_status, anchor="w", justify="left",
wraplength=1000).grid(row=2, column=0, sticky="ew", padx=10, pady=5)
self.tree = self._make_tree(3, KEYS)
@@ -97,12 +96,48 @@ class InventarioWindow(ctk.CTkToplevel):
self.lot_tree = self._make_tree(0, LOT_KEYS, lot_page)
self.detail_tree = self._make_tree(0, DETAIL_KEYS, detail_page)
def _build_legend(self):
"""Keep component definitions visible independently of calculation status."""
self.legend = ctk.CTkFrame(self, fg_color=theme_color(
self._theme, "legend_fg_color", ["#f8fafb", "#262b30"]))
self.legend.grid(row=1, column=0, sticky="ew", padx=8, pady=(0, 4))
self.legend.grid_columnconfigure(1, weight=1)
normal = theme_font(self._theme, "legend_font", ("Segoe UI", 13))
bold = theme_font(self._theme, "legend_heading_font", ("Segoe UI", 13, "bold"))
color = theme_color(self._theme, "legend_text_color", ["#202830", "#f1f3f5"])
self.legend_labels = {}
self.legend_descriptions = []
for row, component in enumerate(("A", "B", "C", "X")):
label = ctk.CTkLabel(self.legend, text=component + ":", font=bold,
text_color=color, anchor="nw", height=20)
label.grid(row=row, column=0, sticky="nw", padx=(10, 8), pady=1)
self.legend_labels[component] = label
description = ctk.CTkLabel(self.legend, text=self._t("inventory.legend." + component),
font=normal, text_color=color, anchor="w", justify="left", wraplength=800, height=20)
description.grid(row=row, column=1, sticky="ew", padx=(0, 10), pady=1)
self.legend_descriptions.append(description)
self.legend_notes = []
for row, key in enumerate(("formula", "scope", "history_notice"), start=4):
label = ctk.CTkLabel(self.legend, text=self._t("inventory." + key),
font=bold if key == "formula" else normal, text_color=color,
anchor="w", justify="left", wraplength=850, height=20)
label.grid(row=row, column=0, columnspan=2, sticky="ew", padx=10, pady=1)
self.legend_notes.append(label)
self.legend.bind("<Configure>", self._resize_legend, add="+")
def _resize_legend(self, event):
"""Wrap to the actual window width, including on smaller desktops."""
for label in self.legend_descriptions:
label.configure(wraplength=max(200, event.width - 65))
for label in self.legend_notes:
label.configure(wraplength=max(200, event.width - 24))
def _make_tree(self, row, keys, parent=None):
wrap = ctk.CTkFrame(parent if parent is not None else self)
wrap.grid(row=row, column=0, sticky="nsew", padx=8, pady=(0, 8))
wrap.grid_columnconfigure(0, weight=1)
wrap.grid_rowconfigure(0, weight=1)
tree = ttk.Treeview(wrap, columns=keys, show="headings", selectmode="browse")
tree = ttk.Treeview(wrap, columns=keys, show="headings", selectmode="browse", height=5)
style_treeview(tree, style_name="Inventory.Treeview", rowheight=24)
tree.tag_configure("difference", foreground=theme_value(self._theme, "difference_color", "#9b3900"))
tree.tag_configure("unknown", foreground=theme_value(self._theme, "unknown_color", "#aa0000"))
@@ -200,7 +235,7 @@ class InventarioWindow(ctk.CTkToplevel):
self._set_loading(False)
log_exception(__name__, error, context="inventory report/export")
self.var_status.set(self._t("inventory.failed"))
messagebox.showerror(self._t("inventory.title"), str(error), parent=self)
messagebox.showerror(self._t("inventory.title"), str(error), parent=self, exception=error)
def _export(self):
if self._loading or not self._report or not self._rows:

View File

@@ -1,10 +1,26 @@
{
"default_language": "IT",
"IT": {
"errors.title": "Dettaglio errore",
"errors.copy": "Copia tutto",
"errors.save": "Salva su file",
"errors.close": "Chiudi",
"errors.copied": "Testo copiato negli appunti.",
"errors.copy_failed": "Copia non riuscita: {error}",
"errors.saved": "Report salvato: {path}",
"errors.save_failed": "Salvataggio non riuscito: {error}",
"errors.text_file": "File di testo UTF-8",
"errors.all_files": "Tutti i file",
"inventory.title": "Inventario",
"inventory.date": "Data (gg/mm/aaaa):",
"inventory.load": "Calcola inventario",
"inventory.export": "Esporta XLSX",
"inventory.ready": "Scegli la data e premi Calcola inventario. Seleziona poi un prodotto per vedere lotti e contenitori.",
"inventory.legend.A": "Pezzi nelle UDC presenti in WMS: scaffalate nelle aree 5/6 oppure non scaffalate.",
"inventory.legend.B": "Pezzi in UDC assegnate ma fuori WMS: confezionamento dedotto, UDC piene o parziali.",
"inventory.legend.C": "Pezzi in bag/vasche senza UDC: seriale 000000/..., con giacenza SAM positiva.",
"inventory.legend.X": "Anomalie nel dettaglio: saldo SAM non classificabile in A/B/C; escluso dal totale ricostruito.",
"inventory.formula": "Totale = A + B + C. Residuo = SAM - Totale. '?' = quantita' non determinabile, non zero.",
"inventory.notice": "A: UDC WMS. B: UDC fuori WMS, confezionamento presunto. C: bag/vasche senza UDC. Residuo = SAM - (A+B+C). '?' indica dati non determinabili.",
"inventory.scope": "Perimetro provvisorio: solo prodotti/lotti delle UDC in aree 5 e 6 o non scaffalate alla data. Non e' l'inventario completo SAM.",
"inventory.history_notice": "Ricostruzione da movimenti e storico NUMSER disponibile, non inventario fisico certificato. Validare le etichette e la completezza dello storico.",
@@ -131,6 +147,10 @@
"history.udc.msg.empty": "Nessun movimento trovato.",
"history.udc.msg.error": "Errore ricerca:\n{error}",
"history.picking.title": "Storico Picking List",
"history.picking.document": "Documento:",
"history.picking.year": "Anno",
"history.picking.udc_hint": "UDC vuota: anno corrente. Ricerca UDC: anno corrente e precedente. Se compilati, entrambi i filtri si applicano.",
"history.picking.udc_invalid": "Inserire il codice UDC completo, numerico, di massimo 6 cifre.",
"history.picking.button.reload": "Ricarica",
"history.picking.detail_title": "Dettaglio contenuto",
"history.picking.busy.master": "Carico storico picking list...",
@@ -164,6 +184,8 @@
"reset.button.refresh": "Carica",
"reset.button.empty": "Svuota corsia...",
"reset.summary": "Riepilogo",
"reset.confirm": "Verranno movimentate {udc} UDC da {cells} celle della corsia {aisle}.\nUDC associate a documenti di spedizione definitivi (stato D): spedite in 9999 / 7G.1.1.\nTutte le altre: non scaffalate in 1000 (barcode 9001000).\nSaranno registrati prelievo e versamento, senza cancellazioni.\nLa verifica viene effettuata al momento di ogni movimento.\nDigitare il nome della corsia per confermare:",
"reset.result": "Corsia {aisle}: movimentate {success} UDC su {total}.\nSpedite in 9999 / 7G.1.1: {shipped}.\nNon scaffalate in 1000: {non_shelved}.\nAggiornare lo storico picking list per ricalcolare i residui.",
"layout.title": "Layout corsie",
"layout.button.search": "Cerca per barcode UDC",
"layout.button.refresh": "Aggiorna",
@@ -223,10 +245,26 @@
"scarico.msg.exec_error": "Scarico fallito:\n{error}"
},
"ENG": {
"errors.title": "Error details",
"errors.copy": "Copy all",
"errors.save": "Save to file",
"errors.close": "Close",
"errors.copied": "Text copied to clipboard.",
"errors.copy_failed": "Copy failed: {error}",
"errors.saved": "Report saved: {path}",
"errors.save_failed": "Save failed: {error}",
"errors.text_file": "UTF-8 text file",
"errors.all_files": "All files",
"inventory.title": "Inventory",
"inventory.date": "Date (dd/mm/yyyy):",
"inventory.load": "Calculate inventory",
"inventory.export": "Export XLSX",
"inventory.ready": "Choose a date and Calculate inventory. Then select a product to see lots and containers.",
"inventory.legend.A": "Pieces in WMS UDCs: shelved in areas 5/6 or non-shelved.",
"inventory.legend.B": "Pieces assigned to UDCs outside WMS: inferred packaging, full or partial UDCs.",
"inventory.legend.C": "Pieces in bags/tubs without a UDC: serial 000000/..., with positive SAM stock.",
"inventory.legend.X": "Detail anomalies: SAM stock not classifiable as A/B/C; excluded from the reconstructed total.",
"inventory.formula": "Total = A + B + C. Residual = SAM - Total. '?' = undetermined quantity, not zero.",
"inventory.notice": "A: WMS UDCs. B: UDCs outside WMS, inferred packaging location. C: bags/tubs without UDC. Residual = SAM - (A+B+C). '?' means undetermined data.",
"inventory.scope": "Provisional scope: only products/lots of UDCs in areas 5/6 or non-shelved at date. Not the complete SAM inventory.",
"inventory.history_notice": "Reconstruction from movements and available NUMSER history, not a certified physical inventory. Validate labels and history completeness.",
@@ -353,6 +391,10 @@
"history.udc.msg.empty": "No movement found.",
"history.udc.msg.error": "Search failed:\n{error}",
"history.picking.title": "Picking List History",
"history.picking.document": "Document:",
"history.picking.year": "Year",
"history.picking.udc_hint": "Empty UDC: current year. UDC search: current and previous year. Both filters apply when filled in.",
"history.picking.udc_invalid": "Enter the complete numeric UDC code, up to 6 digits.",
"history.picking.button.reload": "Reload",
"history.picking.detail_title": "Content detail",
"history.picking.busy.master": "Loading picking-list history...",
@@ -386,6 +428,8 @@
"reset.button.refresh": "Load",
"reset.button.empty": "Empty aisle...",
"reset.summary": "Summary",
"reset.confirm": "{udc} UDCs will be moved from {cells} cells in aisle {aisle}.\nUDCs associated with definitive shipping documents (state D): shipped to 9999 / 7G.1.1.\nAll others: non-shelved in 1000 (barcode 9001000).\nPick and put-away movements will be recorded, without deletions.\nThe check is performed when each UDC is moved.\nType the aisle name to confirm:",
"reset.result": "Aisle {aisle}: moved {success} out of {total} UDCs.\nShipped to 9999 / 7G.1.1: {shipped}.\nNon-shelved in 1000: {non_shelved}.\nRefresh picking-list history to recalculate residuals.",
"layout.title": "Aisle layout",
"layout.button.search": "Search by UDC barcode",
"layout.button.refresh": "Refresh",

View File

@@ -3,7 +3,8 @@
from __future__ import annotations
import tkinter as tk
from tkinter import messagebox, ttk
import error_dialog as messagebox
from tkinter import ttk
from typing import Any
from audit_log import log_session_event
@@ -261,6 +262,7 @@ class LoginWindow(tk.Toplevel):
loc_text("login.msg.title", catalog=self._locale_catalog, default="Login"),
loc_text("login.msg.error", catalog=self._locale_catalog, default="Verifica credenziali fallita:\n{error}").format(error=ex),
parent=self,
exception=ex,
)
self._async.run(

22
main.py
View File

@@ -16,7 +16,8 @@ from runtime_support import ensure_stdio, run_with_fatal_log
ensure_stdio("warehouse_main")
import customtkinter as ctk
from tkinter import messagebox
from PIL import Image, ImageDraw
import error_dialog as messagebox
from async_loop_singleton import get_global_loop, stop_global_loop
from async_msssql_query import AsyncMSSQLClient
@@ -357,17 +358,18 @@ class Launcher(ctk.CTk):
except Exception:
pass
def _make_exit_icon(self, *, color: str) -> tk.PhotoImage:
"""Create a small red X icon without adding image assets to the project."""
def _make_exit_icon(self, *, color: str) -> ctk.CTkImage:
"""Create a transparent X with extra resolution for HighDPI scaling."""
size = 14
image = tk.PhotoImage(width=size, height=size)
for offset in range(3, 11):
image.put(color, (offset, offset))
image.put(color, (offset + 1, offset))
image.put(color, (offset, size - 1 - offset))
image.put(color, (offset + 1, size - 1 - offset))
return image
scale = 3
image = Image.new("RGBA", (size * scale, size * scale), (0, 0, 0, 0))
draw = ImageDraw.Draw(image)
draw.line((3 * scale, 3 * scale, 10 * scale, 10 * scale),
fill=color, width=2 * scale)
draw.line((3 * scale, 10 * scale, 10 * scale, 3 * scale),
fill=color, width=2 * scale)
return ctk.CTkImage(light_image=image, dark_image=image, size=(size, size))
def _apply_dynamic_geometry(self) -> None:
"""Size the launcher around its current content and keep it docked at the top."""

View File

@@ -0,0 +1,100 @@
"""Read-only UDC lookup across the current and previous ERP document years.
Unlike the default history view this query retains BAMTES.ID, so documents with
the same display number in different years cannot share details or movements.
The UDC selects documents, not detail rows: counts always describe whole lists.
"""
from version_info import module_version
__version__ = module_version(__name__)
_BASE = """
DECLARE @UDC varchar(32) = :pallet;
DECLARE @Document varchar(32) = :documento;
DECLARE @DocumentID int = :id_documento;
WITH documents AS (
SELECT bt.*
FROM SAMA1.dbo.BAMTES bt
WHERE bt.ANNDOC BETWEEN YEAR(GETDATE()) - 1 AND YEAR(GETDATE())
AND bt.STATO IN ('P', 'D')
AND (@DocumentID IS NULL OR bt.ID = @DocumentID)
AND (@Document IS NULL OR CAST(bt.NUMDOC AS varchar(32)) LIKE '%' + @Document + '%')
AND (@UDC IS NULL OR EXISTS (
SELECT 1 FROM SAMA1.dbo.FATRIG fr
JOIN SAMA1.dbo.LOTTIBF lb ON lb.IDFATRIG = fr.ID
JOIN SAMA1.dbo.LOTSER ls ON ls.ID = lb.IDLOTSER
WHERE fr.IDBAM = bt.ID
AND ls.NUMLOT NOT IN ('', '00000000000')
AND LEFT(ls.NUMSER, 6) COLLATE Latin1_General_CI_AS = @UDC COLLATE Latin1_General_CI_AS
))
), prep AS (
SELECT bt.ID AS IDDocumento, bt.ANNDOC AS AnnoDocumento,
bt.NUMDOC AS Documento, bt.DATDOC AS DataDocumento, bt.STATO AS StatoDocumento,
LEFT(ls.NUMSER, 6) AS Pallet, ls.NUMLOT AS Lotto, a.CODICE AS Articolo,
fr.DESCR AS Descrizione, SUM(ls.QTTGIAI) AS Qta,
n.CODICE AS CodNazione, mt.CODICE + ' ' + n.DESCR AS NAZIONE
FROM documents bt
JOIN SAMA1.dbo.FATRIG fr ON fr.IDBAM = bt.ID
JOIN SAMA1.dbo.LOTTIBF lb ON lb.IDFATRIG = fr.ID
JOIN SAMA1.dbo.LOTSER ls ON ls.ID = lb.IDLOTSER
LEFT JOIN SAMA1.dbo.ARTICO a ON a.ID = ls.IDARTICO
LEFT JOIN SAMA1.dbo.NAZIONI n ON n.ID = bt.IDNAZDEST
LEFT JOIN SAMA1.dbo.MTRASP mt ON mt.ID = bt.IDMTRASP
WHERE ls.NUMLOT NOT IN ('', '00000000000')
GROUP BY bt.ID, bt.ANNDOC, bt.NUMDOC, bt.DATDOC, bt.STATO,
LEFT(ls.NUMSER, 6), ls.NUMLOT, a.CODICE, fr.DESCR, n.CODICE, mt.CODICE, n.DESCR
), locations AS (
SELECT g.BarcodePallet, g.IDCella, c.Ordinamento,
c.Corsia + ' - ' + c.Colonna + ' - ' + c.Fila AS Ubicazione
FROM dbo.XMag_GiacenzaPallet g JOIN dbo.Celle c ON c.ID = g.IDCella
), base AS (
SELECT prep.*, ISNULL(g.IDCella, 1000) AS Cella,
ISNULL(g.Ordinamento, 99999) AS Ordinamento,
ISNULL(g.Ubicazione, 'Non scaff.') AS Ubicazione,
CASE WHEN prep.AnnoDocumento = YEAR(GETDATE()) AND EXISTS (
SELECT 1 FROM dbo.PyPickingListReservation pr
WHERE pr.ID = 1 AND pr.Documento = CAST(prep.Documento AS varchar(8))
) THEN 1 ELSE 0 END AS IDStato
FROM prep LEFT JOIN locations g
ON g.BarcodePallet COLLATE Latin1_General_CI_AS = prep.Pallet COLLATE Latin1_General_CI_AS
)
"""
SQL_UDC_HISTORY_DETAILS = _BASE + """
SELECT * FROM base ORDER BY Ordinamento, Pallet, Lotto;
"""
SQL_UDC_HISTORY = _BASE + """
, pallets AS (
SELECT IDDocumento, Pallet,
MAX(CASE WHEN Cella <> 9999 THEN 1 ELSE 0 END) AS HasResiduo
FROM base WHERE NULLIF(LTRIM(RTRIM(Pallet)), '') IS NOT NULL
GROUP BY IDDocumento, Pallet
), totals AS (
SELECT IDDocumento, COUNT(*) AS TotUDC, SUM(HasResiduo) AS RigheResidue,
SUM(1 - HasResiduo) AS RigheSpedite
FROM pallets GROUP BY IDDocumento
), meta AS (
SELECT IDDocumento, MAX(AnnoDocumento) AS AnnoDocumento,
MAX(Documento) AS Documento, MAX(DataDocumento) AS DataDocumento,
MAX(StatoDocumento) AS StatoDocumento, MAX(NAZIONE) AS NAZIONE,
MAX(CodNazione) AS CodNazione, MAX(IDStato) AS IDStato
FROM base GROUP BY IDDocumento
)
SELECT m.*, ISNULL(t.TotUDC, 0) AS TotUDC, ISNULL(t.RigheResidue, 0) AS RigheResidue,
ISNULL(t.RigheSpedite, 0) AS RigheSpedite,
CASE WHEN m.StatoDocumento = 'D' AND ISNULL(t.RigheResidue, 0) > 0 THEN 'Chiusa ERP con residui'
WHEN m.StatoDocumento = 'D' THEN 'Chiusa'
WHEN ISNULL(t.RigheResidue, 0) = 0 THEN 'Esaurita'
WHEN ISNULL(t.RigheSpedite, 0) > 0 THEN 'In corso'
ELSE 'Da lavorare' END AS StatoOperativo
FROM meta m LEFT JOIN totals t ON t.IDDocumento = m.IDDocumento
ORDER BY m.DataDocumento DESC, m.Documento DESC, m.IDDocumento DESC;
"""
def detail_request(documento: str, document_id: int | None, default_sql: str):
"""Return a bound detail query; never use a cross-year display number alone."""
if document_id is not None:
return SQL_UDC_HISTORY_DETAILS, {"pallet": None, "documento": None, "id_documento": document_id}
return default_sql, {"documento": documento}

View File

@@ -10,7 +10,7 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable
import tkinter as tk
from tkinter import messagebox
import error_dialog as messagebox
import customtkinter as ctk
@@ -285,6 +285,7 @@ class PickingListSequenceWindow(ctk.CTkToplevel):
self._t("picking.sequence.title", "Sequenza di prelievo"),
self._t("picking.sequence.msg.load_error", "Errore durante il caricamento:\n{error}", error=exc),
parent=self,
exception=exc,
)
self.runner.run(
@@ -536,6 +537,7 @@ SELECT CAST({len(values)} AS int) AS ElementiSalvati;
self._t("picking.sequence.title", "Sequenza di prelievo"),
self._t("picking.sequence.msg.save_error", "Errore durante il salvataggio:\n{error}", error=exc),
parent=self,
exception=exc,
)

View File

@@ -3,6 +3,7 @@ customtkinter==5.2.2
loguru
openpyxl==3.1.5
orjson
Pillow
pyodbc==5.3.0
SQLAlchemy==2.0.49
tksheet==7.6.0

View File

@@ -13,14 +13,15 @@ import sys
import tkinter as tk
from functools import wraps
from pathlib import Path
from tkinter import messagebox, simpledialog, ttk
import error_dialog as messagebox
from tkinter import simpledialog, ttk
from typing import Any
import customtkinter as ctk
from busy_overlay import InlineBusyOverlay
from gestione_aree import AsyncRunner
from gestione_scarico import move_pallet_async
from reset_corsie_service import reset_pallet_async
from locale_text import load_locale_catalog, text as loc_text
from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text
from ui_theme import theme_color, theme_font, theme_section, theme_value
@@ -171,7 +172,7 @@ SQL_CORSIE = """
WITH C AS (
SELECT DISTINCT LTRIM(RTRIM(Corsia)) AS Corsia
FROM dbo.Celle
WHERE ID <> 9999 AND (DelDataOra IS NULL) AND LTRIM(RTRIM(Corsia)) <> '7G'
WHERE ID NOT IN (1000, 9999) AND (DelDataOra IS NULL) AND LTRIM(RTRIM(Corsia)) <> '7G'
)
SELECT Corsia
FROM C
@@ -193,7 +194,7 @@ WITH C AS (
LTRIM(RTRIM(Colonna)) AS Colonna,
LTRIM(RTRIM(Fila)) AS Fila
FROM dbo.Celle
WHERE ID <> 9999 AND (DelDataOra IS NULL)
WHERE ID NOT IN (1000, 9999) AND (DelDataOra IS NULL)
AND LTRIM(RTRIM(Corsia)) = :corsia
),
S AS (
@@ -215,7 +216,7 @@ WITH C AS (
LTRIM(RTRIM(Colonna)) AS Colonna,
LTRIM(RTRIM(Fila)) AS Fila
FROM dbo.Celle
WHERE ID <> 9999 AND (DelDataOra IS NULL)
WHERE ID NOT IN (1000, 9999) AND (DelDataOra IS NULL)
AND LTRIM(RTRIM(Corsia)) = :corsia
),
S AS (
@@ -237,7 +238,7 @@ SELECT
COUNT(DISTINCT g.IDCella) AS TotCelle
FROM dbo.XMag_GiacenzaPallet g
JOIN dbo.Celle c ON c.ID = g.IDCella
WHERE c.ID <> 9999
WHERE c.ID NOT IN (1000, 9999)
AND LTRIM(RTRIM(c.Corsia)) = :corsia;
"""
@@ -253,7 +254,7 @@ WITH U AS (
LTRIM(RTRIM(c.Fila)) AS SortFilaTxt
FROM dbo.XMag_GiacenzaPallet g
JOIN dbo.Celle c ON c.ID = g.IDCella
WHERE c.ID <> 9999
WHERE c.ID NOT IN (1000, 9999)
AND LTRIM(RTRIM(c.Corsia)) = :corsia
)
SELECT
@@ -466,7 +467,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
def _err(ex):
_MODULE_LOGGER.exception(f"Errore caricamento corsie reset corsie: {ex}")
messagebox.showerror("Errore", f"Caricamento corsie fallito:\n{ex}", parent=self)
messagebox.showerror("Errore", f"Caricamento corsie fallito:\n{ex}", parent=self, exception=ex)
self._async.run(self.db.query_json(SQL_CORSIE, {}), _ok, _err, busy=self._busy, message="Carico corsie...")
@@ -513,11 +514,11 @@ class ResetCorsieWindow(ctk.CTkToplevel):
self.tree.insert("", "end", values=(ubi, n), tags=(tag,))
except Exception as ex:
_MODULE_LOGGER.exception(f"Errore UI refresh reset corsie corsia={corsia}: {ex}")
messagebox.showerror("Errore", f"Aggiornamento interfaccia fallito:\n{ex}", parent=self)
messagebox.showerror("Errore", f"Aggiornamento interfaccia fallito:\n{ex}", parent=self, exception=ex)
def _err(ex):
_MODULE_LOGGER.exception(f"Errore refresh reset corsie corsia={corsia}: {ex}")
messagebox.showerror("Errore", f"Refresh fallito:\n{ex}", parent=self)
messagebox.showerror("Errore", f"Refresh fallito:\n{ex}", parent=self, exception=ex)
self._async.run(_q(), _ok, _err, busy=self._busy, message=f"Riepilogo {corsia}...")
@@ -537,12 +538,9 @@ class ResetCorsieWindow(ctk.CTkToplevel):
if tot_udc <= 0:
messagebox.showinfo("Svuota corsia", f"Nessuna UDC attiva da scaricare per la corsia {corsia}.", parent=self)
return
msg = (
f"Verranno scaricate logicamente {tot_udc} UDC attive distribuite su {tot_celle} celle della corsia {corsia}.",
"L'operazione verra' eseguita come scarico verso 9000000 / 9999, senza cancellazioni fisiche dirette.",
"Digitare il nome della corsia per confermare:",
)
confirm = simpledialog.askstring("Conferma", "\n".join(msg), parent=self)
msg = loc_text("reset.confirm", catalog=self._locale_catalog).format(
udc=tot_udc, cells=tot_celle, aisle=corsia)
confirm = simpledialog.askstring("Conferma", msg, parent=self)
if confirm is None:
_MODULE_LOGGER.info(f"Reset corsia {corsia}: conferma annullata dall'utente")
return
@@ -554,7 +552,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
def _err_count(ex):
_MODULE_LOGGER.exception(f"Errore conteggio reset corsie corsia={corsia}: {ex}")
messagebox.showerror("Errore", f"Conteggio UDC da scaricare fallito:\n{ex}", parent=self)
messagebox.showerror("Errore", f"Conteggio UDC da scaricare fallito:\n{ex}", parent=self, exception=ex)
self._async.run(self.db.query_json(SQL_COUNT_RESET, {"corsia": corsia}), _ok_count, _err_count, busy=self._busy, message="Verifico...")
@@ -569,20 +567,30 @@ class ResetCorsieWindow(ctk.CTkToplevel):
_log_dataset("reset_corsie_udc_reset", rows)
success = 0
shipped = 0
non_shelved = 0
failed: list[dict[str, Any]] = []
utente = str(getattr(self.session, "login", "") or "warehouse_ui").strip()
for barcode_pallet, idcella, ubicazione in rows:
try:
await move_pallet_async(
target = await reset_pallet_async(
self.db,
barcode_pallet=str(barcode_pallet or "").strip(),
target_idcella=9999,
target_barcode_cella="9000000",
source_idcella=int(idcella),
utente=utente,
)
success += 1
shipped += int(target == 9999)
non_shelved += int(target == 1000)
_MODULE_LOGGER.info(
f"RESET MOVE corsia={corsia} pallet={barcode_pallet} "
f"source={idcella} target={target} utente={utente}"
)
except Exception as ex:
_MODULE_LOGGER.exception(
f"RESET FAILED corsia={corsia} pallet={barcode_pallet} source={idcella}: {ex}"
)
failed.append(
{
"barcode_pallet": str(barcode_pallet or ""),
@@ -595,6 +603,8 @@ class ResetCorsieWindow(ctk.CTkToplevel):
return {
"total": len(rows),
"success": success,
"shipped": shipped,
"non_shelved": non_shelved,
"failed": failed,
}
@@ -602,6 +612,9 @@ class ResetCorsieWindow(ctk.CTkToplevel):
total = int((result or {}).get("total", 0))
success = int((result or {}).get("success", 0))
failed = list((result or {}).get("failed", []))
summary = loc_text("reset.result", catalog=self._locale_catalog).format(
aisle=corsia, success=success, total=total,
shipped=result.get("shipped", 0), non_shelved=result.get("non_shelved", 0))
_MODULE_LOGGER.info(
f"Reset corsia {corsia}: scarico logico completato success={success} total={total} failed={len(failed)}"
)
@@ -609,7 +622,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
messagebox.showwarning(
"Completato con errori",
(
f"Corsia {corsia}: scaricate {success} UDC su {total}.\n"
summary + "\n" +
f"Errori su {len(failed)} UDC. Controllare {MODULE_LOG_PATH.name}."
),
parent=self,
@@ -617,14 +630,14 @@ class ResetCorsieWindow(ctk.CTkToplevel):
else:
messagebox.showinfo(
"Completato",
f"Corsia {corsia}: svuotamento logico completato su {success} UDC.",
summary,
parent=self,
)
self.refresh()
def _err_del(ex):
_MODULE_LOGGER.exception(f"Errore reset logico corsie corsia={corsia}: {ex}")
messagebox.showerror("Errore", f"Svuotamento fallito:\n{ex}", parent=self)
messagebox.showerror("Errore", f"Svuotamento fallito:\n{ex}", parent=self, exception=ex)
self._async.run(_q(), _ok_del, _err_del, busy=self._busy, message=f"Svuoto {corsia}...")

121
reset_corsie_service.py Normal file
View File

@@ -0,0 +1,121 @@
"""Classify and move aisle-reset UDCs without changing barcode workflows.
Each call is one transaction: recheck the source, read the ERP document state,
record P/V movements, refresh reservations and verify the resulting location.
The caller must use query_json(commit=True), never execute this batch piecemeal.
"""
from version_info import module_version
__version__ = module_version(__name__)
SQL_RESET_PALLET = """
SET NOCOUNT ON;
SET XACT_ABORT ON;
DECLARE @Pallet varchar(32) = :barcode_pallet;
DECLARE @ExpectedCell int = :source_idcella;
DECLARE @User varchar(128) = :utente;
DECLARE @Now datetime = GETDATE();
DECLARE @LockedRows int;
DECLARE @TargetCell int = 1000;
DECLARE @SourceID int;
-- Keep other ledger writers away until this UDC transaction completes.
SELECT @LockedRows = COUNT(*)
FROM dbo.MagazziniPallet WITH (UPDLOCK, HOLDLOCK)
WHERE Attributo = @Pallet;
IF @ExpectedCell IN (1000, 9999)
THROW 51001, 'Reset: la sorgente deve essere una cella fisica.', 1;
IF NOT EXISTS (
SELECT 1 FROM dbo.XMag_GiacenzaPallet
WHERE BarcodePallet = @Pallet AND IDCella = @ExpectedCell
) OR EXISTS (
SELECT 1 FROM dbo.XMag_GiacenzaPallet
WHERE BarcodePallet = @Pallet AND (IDCella <> @ExpectedCell OR IDCella IS NULL)
)
THROW 51002, 'Reset: UDC spostata o presente in piu celle. Ricaricare e verificare.', 1;
-- Read the ERP association directly: history UI date filters must not decide
-- whether an old, already shipped UDC is put back into available stock.
IF EXISTS (
SELECT 1
FROM SAMA1.dbo.LOTSER AS ls
JOIN SAMA1.dbo.LOTTIBF AS lb ON lb.IDLOTSER = ls.ID
JOIN SAMA1.dbo.FATRIG AS fr ON fr.ID = lb.IDFATRIG
JOIN SAMA1.dbo.BAMTES AS bt ON bt.ID = fr.IDBAM
WHERE bt.STATO = 'D'
AND LEFT(ls.NUMSER, 6) COLLATE Latin1_General_CI_AS =
@Pallet COLLATE Latin1_General_CI_AS
)
SET @TargetCell = 9999;
IF NOT EXISTS (
SELECT 1 FROM dbo.Celle c JOIN dbo.Aree a ON a.ID = c.IDArea
WHERE c.ID = @TargetCell AND c.DelDataOra IS NULL
)
THROW 51003, 'Reset: cella virtuale di destinazione non disponibile.', 1;
SELECT TOP (1) @SourceID = ID
FROM dbo.MagazziniPallet
WHERE Attributo = @Pallet AND IDCella = @ExpectedCell
AND Tipo = 'V' AND PesoUnitario > 0
ORDER BY ID DESC;
IF @SourceID IS NULL
THROW 51004, 'Reset: movimento sorgente non trovato.', 1;
UPDATE dbo.MagazziniPallet
SET ModUtente = @User, ModDataOra = @Now
WHERE ID = @SourceID;
INSERT INTO dbo.MagazziniPallet (
Tipo, IDRiferimento, NumeroPallet, Attributo, IDMagazzino, IDArea,
IDCella, DataMagazzino, PesoUnitario, Tara, InsUtente, InsDataOra
)
SELECT 'P', src.ID, ISNULL(src.NumeroPallet, 0), src.Attributo,
src.IDMagazzino, src.IDArea, src.IDCella, @Now,
src.PesoUnitario, ISNULL(src.Tara, 0), @User, @Now
FROM dbo.MagazziniPallet src WHERE src.ID = @SourceID;
UPDATE dbo.Celle SET IDStato = 0, ModUtente = @User, ModDataOra = @Now
WHERE ID = @ExpectedCell;
INSERT INTO dbo.MagazziniPallet (
Tipo, IDRiferimento, NumeroPallet, Attributo, IDMagazzino, IDArea,
IDCella, DataMagazzino, PesoUnitario, Tara, InsUtente, InsDataOra
)
SELECT 'V', src.ID, ISNULL(src.NumeroPallet, 0), src.Attributo,
a.IDMagazzino, c.IDArea, c.ID, @Now,
src.PesoUnitario, ISNULL(src.Tara, 0), @User, @Now
FROM dbo.MagazziniPallet src
JOIN dbo.Celle c ON c.ID = @TargetCell
JOIN dbo.Aree a ON a.ID = c.IDArea
WHERE src.ID = @SourceID;
IF NOT EXISTS (
SELECT 1 FROM dbo.XMag_GiacenzaPallet
WHERE BarcodePallet = @Pallet AND IDCella = @TargetCell
) OR EXISTS (
SELECT 1 FROM dbo.XMag_GiacenzaPallet
WHERE BarcodePallet = @Pallet AND (IDCella <> @TargetCell OR IDCella IS NULL)
)
THROW 51005, 'Reset: ubicazione finale incoerente. Movimento annullato.', 1;
EXEC dbo.py_sp_ControllaPrenotazionePackingListPalletNew;
SELECT @TargetCell AS TargetIDCella;
"""
async def reset_pallet_async(db_client, *, barcode_pallet: str,
source_idcella: int, utente: str) -> int:
"""Move one UDC, returning 9999 (definitive document) or 1000 (otherwise).
source_idcella is the location shown in the reset selection, not a new
destination. Any SQL failure rolls back this UDC through the DB client.
"""
result = await db_client.query_json(SQL_RESET_PALLET, {
"barcode_pallet": str(barcode_pallet or "").strip(),
"source_idcella": int(source_idcella),
"utente": str(utente or "warehouse_ui").strip(),
}, commit=True)
return int(result["rows"][0][0])

View File

@@ -98,13 +98,15 @@ def configure_exception_logging(app_name: str, root=None, loop=None) -> None:
def _tk_exception(exc_type, exc, tb):
log_exception(app_name, exc, context="tkinter callback")
try:
import tkinter.messagebox as messagebox
import error_dialog as messagebox
messagebox.showerror(
app_name,
"Errore applicativo registrato nei log.\n\n"
"Se l'operazione era in corso, ripeterla o avvisare il responsabile.",
parent=root,
exception=exc,
context="tkinter callback",
)
except Exception:
pass
@@ -150,7 +152,7 @@ def show_fatal_message(app_name: str, exc: BaseException) -> None:
try:
import tkinter as tk
from tkinter import messagebox
import error_dialog as messagebox
root = tk.Tk()
root.withdraw()
@@ -161,6 +163,7 @@ def show_fatal_message(app_name: str, exc: BaseException) -> None:
f"Se non ci sono, controlla anche:\n{TEMP_DIR}\n\n"
f"{exc}",
parent=root,
exception=exc,
)
root.destroy()
except Exception:

View File

@@ -3,7 +3,8 @@
from __future__ import annotations
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import error_dialog as messagebox
from tkinter import filedialog, ttk
import customtkinter as ctk
@@ -299,6 +300,7 @@ class SearchWindow(ctk.CTkToplevel):
loc_text("search.msg.export_title", catalog=self._locale_catalog, default="Esporta"),
loc_text("search.msg.export_error", catalog=self._locale_catalog, default="Errore durante l'esportazione:{error}").format(error=ex),
parent=self,
exception=ex,
)
def _on_dclick(self, evt):
@@ -510,6 +512,7 @@ class SearchWindow(ctk.CTkToplevel):
loc_text("search.msg.error_title", catalog=self._locale_catalog, default="Errore ricerca"),
str(ex),
parent=self,
exception=ex,
)
self._async.run(

View File

@@ -1,5 +1,13 @@
# Inventario WMS - SAM per prodotto e lotto
## Revisione interfaccia 1.1.1
Guida operativa campo per campo: [GUIDA_INVENTARIO.md](GUIDA_INVENTARIO.md).
Legenda permanente A/B/C/X su righe distinte, lettere in grassetto e colori/font
configurabili nel tema JSON. Testi IT/ENG e ritorno a capo in base alla larghezza.
Il messaggio iniziale spiega come calcolare, senza ripetere il perimetro.
Non cambia il calcolo, il contenuto dell'export o la query SQL.
## Stato al 21/10/2026
Modulo Inventario 1.1.0 completato sul ramo `codex/inventario-monolista`,

View File

@@ -11,7 +11,8 @@ from __future__ import annotations
from datetime import date, datetime, timedelta
import tkinter as tk
from tkinter import messagebox, ttk
import error_dialog as messagebox
from tkinter import ttk
from typing import Any
import customtkinter as ctk
@@ -20,6 +21,7 @@ from busy_overlay import InlineBusyOverlay
from gestione_aree import AsyncRunner
from gestione_scarico import move_pallet_async
from locale_text import load_locale_catalog, text as loc_text
from pickinglist_history_search import SQL_UDC_HISTORY, detail_request
from ui_theme import theme_color, theme_font, theme_section, theme_value
from ui_tables import merge_tags, style_treeview, zebra_tag
from version_info import module_version, versioned_title
@@ -175,6 +177,11 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
self._async = AsyncRunner(self)
self._busy = InlineBusyOverlay(self, self._theme)
self.var_documento = tk.StringVar()
self.var_udc = tk.StringVar()
self._master_rows: dict[str, dict[str, Any]] = {}
self._selected_doc_id: int | None = None
self._master_request = 0
self._detail_request = 0
self._selected_documento: str | None = None
self._selected_stato_operativo: str = ""
self._detail_rows: list[dict[str, Any]] = []
@@ -201,23 +208,28 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
fg_color=theme_color(self._theme, "toolbar_frame_fg_color", ("#d7d7d7", "#3b3b3b")),
)
top.grid(row=0, column=0, sticky="ew", padx=8, pady=8)
top.grid_columnconfigure(4, weight=1)
top.grid_columnconfigure(6, weight=1)
label_font = theme_font(self._theme, "toolbar_label_font", ("Segoe UI", 10))
entry_font = theme_font(self._theme, "entry_font", ("Segoe UI", 10))
button_font = theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold"))
ctk.CTkLabel(top, text="Documento:", font=label_font).grid(row=0, column=0, sticky="w")
ctk.CTkEntry(top, textvariable=self.var_documento, width=140, font=entry_font).grid(
row=0, column=1, sticky="w", padx=(4, 12)
)
ctk.CTkLabel(top, text=loc_text("history.picking.document", catalog=self._locale_catalog),
font=label_font).grid(row=0, column=0, sticky="w")
self.entry_documento = ctk.CTkEntry(top, textvariable=self.var_documento, width=120, font=entry_font)
self.entry_documento.grid(row=0, column=1, sticky="w", padx=(4, 12))
self.entry_documento.bind("<Return>", lambda _e: self._load_master())
ctk.CTkLabel(top, text="UDC:", font=label_font).grid(row=0, column=2, sticky="w")
self.entry_udc = ctk.CTkEntry(top, textvariable=self.var_udc, width=110, font=entry_font)
self.entry_udc.grid(row=0, column=3, sticky="w", padx=(4, 12))
self.entry_udc.bind("<Return>", lambda _e: self._load_master())
ctk.CTkButton(
top,
text=loc_text("history.picking.button.reload", catalog=self._locale_catalog, default="Ricarica"),
command=self._load_master,
font=button_font,
).grid(
row=0, column=2, sticky="w"
row=0, column=4, sticky="w"
)
self.btn_ship_residuals = ctk.CTkButton(
top,
@@ -230,11 +242,13 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
state="disabled",
font=button_font,
)
self.btn_ship_residuals.grid(row=0, column=3, sticky="w", padx=(12, 0))
self.btn_ship_residuals.grid(row=0, column=5, sticky="w", padx=(12, 0))
ctk.CTkLabel(top, text=loc_text("history.picking.udc_hint", catalog=self._locale_catalog),
font=label_font, anchor="w").grid(row=1, column=0, columnspan=7, sticky="ew", pady=(4, 0))
self.master_tree = self._make_tree(
row=1,
columns=("Documento", "Data", "StatoDoc", "NAZIONE", "TotUDC", "Residue", "Spedite", "Stato", "IDStato"),
columns=("Documento", "Data", "StatoDoc", "NAZIONE", "TotUDC", "Residue", "Spedite", "Stato", "IDStato", "Anno"),
widths={
"Documento": 100,
"Data": 110,
@@ -245,9 +259,13 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
"Spedite": 90,
"Stato": 120,
"IDStato": 80,
"Anno": 70,
},
)
self.master_tree.bind("<<TreeviewSelect>>", self._on_master_select)
self.master_tree.configure(displaycolumns=("Documento", "Anno", "Data", "StatoDoc", "NAZIONE",
"TotUDC", "Residue", "Spedite", "Stato", "IDStato"))
self.master_tree.heading("Anno", text=loc_text("history.picking.year", catalog=self._locale_catalog))
ctk.CTkLabel(
self,
@@ -297,17 +315,35 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
def _load_master(self) -> None:
params = {"documento": str(self.var_documento.get() or "").strip() or None}
udc = self.var_udc.get().strip()
if udc and (not udc.isascii() or not udc.isdigit() or len(udc) > 6):
messagebox.showwarning(loc_text("history.picking.msg.title", catalog=self._locale_catalog),
loc_text("history.picking.udc_invalid", catalog=self._locale_catalog), parent=self)
return
sql = SQL_STORICO_PL
if udc:
sql = SQL_UDC_HISTORY
params.update(pallet=udc, id_documento=None)
previous_documento = self._selected_documento
previous_id = self._selected_doc_id
self._master_request += 1
request = self._master_request
self._detail_request += 1
self._fill_master([])
async def _job():
return await self.db_client.query_json(SQL_STORICO_PL, params)
return await self.db_client.query_json(sql, params)
def _ok(res):
if request != self._master_request:
return
self._fill_master(_rows_to_dicts(res))
if previous_documento:
self._restore_master_selection(previous_documento)
self._restore_master_selection(previous_documento, previous_id)
def _err(ex):
if request != self._master_request:
return
messagebox.showerror(
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
loc_text(
@@ -316,6 +352,7 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
default="Errore caricamento:\n{error}",
).format(error=ex),
parent=self,
exception=ex,
)
self._async.run(
@@ -334,10 +371,14 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
self.master_tree.delete(*self.master_tree.get_children(""))
self.detail_tree.delete(*self.detail_tree.get_children(""))
self._selected_documento = None
self._selected_doc_id = None
self._master_rows = {}
self._selected_stato_operativo = ""
self._detail_rows = []
self._update_residual_button()
for index, row in enumerate(rows):
iid = f"doc_{row.get('Documento')}_{index}"
self._master_rows[iid] = row
stato = str(row.get("StatoOperativo") or "")
is_open_with_shipped = (
str(row.get("StatoDocumento") or "") == "P"
@@ -355,7 +396,7 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
self.master_tree.insert(
"",
"end",
iid=f"doc_{row.get('Documento')}_{index}",
iid=iid,
values=(
row.get("Documento", ""),
_format_date(row.get("DataDocumento", "")),
@@ -366,14 +407,18 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
row.get("RigheSpedite", ""),
stato,
row.get("IDStato", ""),
row.get("AnnoDocumento", datetime.now().year),
),
tags=merge_tags(zebra_tag(index), tag),
)
def _on_master_select(self, _event=None) -> None:
self._detail_request += 1
request = self._detail_request
selected = self.master_tree.selection()
if not selected:
self._selected_documento = None
self._selected_doc_id = None
self._selected_stato_operativo = ""
self._detail_rows = []
self._update_residual_button()
@@ -382,19 +427,26 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
if not values:
return
documento = values[0]
self._selected_doc_id = self._master_rows.get(selected[0], {}).get("IDDocumento")
self._selected_documento = str(documento)
self._selected_stato_operativo = str(values[7] if len(values) > 7 else "")
self._detail_rows = []
self.detail_tree.delete(*self.detail_tree.get_children(""))
self._update_residual_button()
sql, params = detail_request(documento, self._selected_doc_id, SQL_STORICO_PL_DETAILS)
async def _job():
return await self.db_client.query_json(SQL_STORICO_PL_DETAILS, {"documento": documento})
return await self.db_client.query_json(sql, params)
def _ok(res):
if request != self._detail_request:
return
self._fill_detail(_rows_to_dicts(res))
self._update_residual_button()
def _err(ex):
if request != self._detail_request:
return
messagebox.showerror(
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
loc_text(
@@ -403,6 +455,7 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
default="Errore dettaglio:\n{error}",
).format(error=ex),
parent=self,
exception=ex,
)
self._async.run(
@@ -451,12 +504,15 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
except Exception:
pass
def _restore_master_selection(self, documento: str) -> None:
def _restore_master_selection(self, documento: str, document_id: int | None = None) -> None:
"""Re-select a document after a reload, when it is still visible."""
for iid in self.master_tree.get_children(""):
values = self.master_tree.item(iid, "values")
if values and str(values[0]) == str(documento):
row = self._master_rows.get(iid, {})
matches = (row.get("IDDocumento") == document_id if document_id is not None
else row.get("IDDocumento") is None and values and str(values[0]) == str(documento))
if matches:
self.master_tree.selection_set(iid)
self.master_tree.focus(iid)
self.master_tree.see(iid)
@@ -512,14 +568,18 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
return
documento = self._selected_documento
document_id = self._selected_doc_id
utente = self._operator_login()
sql, params = detail_request(documento, document_id, SQL_STORICO_PL_DETAILS)
async def _job():
# Re-read the detail inside the async job to avoid moving stale UI
# rows if another operator or barcode client changed the list after
# the user selected it.
detail_res = await self.db_client.query_json(SQL_STORICO_PL_DETAILS, {"documento": documento})
detail_res = await self.db_client.query_json(sql, params)
detail_rows = _rows_to_dicts(detail_res)
if document_id is not None and any(row.get("StatoDocumento") != "D" for row in detail_rows):
raise RuntimeError("Documento non piu' definitivo. Ricaricare lo storico.")
pallets = self._residual_pallets_from_rows(detail_rows)
results: list[dict[str, Any]] = []
for pallet in pallets:
@@ -546,6 +606,7 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
parent=self,
)
self._selected_documento = str(documento)
self._selected_doc_id = document_id
self._load_master()
def _err(ex):
@@ -553,6 +614,7 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
f"Versamento residui fallito:\n{ex}",
parent=self,
exception=ex,
)
self._async.run(

View File

@@ -3,7 +3,8 @@
from __future__ import annotations
import tkinter as tk
from tkinter import messagebox, ttk
import error_dialog as messagebox
from tkinter import ttk
from typing import Any
import customtkinter as ctk
@@ -269,6 +270,7 @@ class StoricoUDCWindow(ctk.CTkToplevel):
default="Errore ricerca:\n{error}",
).format(error=ex),
parent=self,
exception=ex,
)
self._async.run(

93
tests/test_deploy_bat.py Normal file
View 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
View 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()

View File

@@ -2,6 +2,7 @@
import tkinter as tk
import unittest
import warnings
from datetime import date
from decimal import Decimal
from unittest.mock import Mock, patch
@@ -46,6 +47,42 @@ class InventoryGuiTests(unittest.TestCase):
self.assertEqual(self.win.btn_export.cget("state"), "normal")
self.assertIn("31/12/2025", self.win.var_status.get())
def test_legend_is_bold_localized_and_independent_of_report(self):
for component, label in self.win.legend_labels.items():
self.assertEqual(label.cget("text"), component + ":")
self.assertIn("bold", label.cget("font"))
descriptions = [label.cget("text") for label in self.win.legend_descriptions]
self.assertTrue(all(text and not text.startswith("inventory.") for text in descriptions))
self.assertEqual(self.win.var_status.get(), self.win._t("inventory.ready"))
self.assertNotEqual(self.win.var_status.get(), self.win._t("inventory.scope"))
self.win._loaded(self.sample())
self.assertEqual([label.cget("text") for label in self.win.legend_descriptions], descriptions)
error = RuntimeError("Synthetic failure")
with patch("inventario.messagebox.showerror") as show, patch("inventario.log_exception"):
self.win._error(error)
self.assertIs(show.call_args.kwargs["exception"], error)
self.assertEqual([label.cget("text") for label in self.win.legend_descriptions], descriptions)
def test_legend_wraps_to_window_width(self):
self.win._resize_legend(Mock(width=900))
self.assertEqual(self.win.legend_descriptions[0].cget("wraplength"), 835)
self.win._resize_legend(Mock(width=1200))
self.assertEqual(self.win.legend_descriptions[0].cget("wraplength"), 1135)
def test_legend_has_both_translations(self):
from locale_text import load_locale_catalog
catalog = load_locale_catalog()
for lang in ("IT", "ENG"):
for suffix in ("ready", "formula", "legend.A", "legend.B", "legend.C", "legend.X"):
self.assertTrue(catalog[lang]["inventory." + suffix])
def test_small_window_keeps_both_grids_visible(self):
self.win.geometry("900x560+4000+0")
self.win.deiconify()
self.root.update_idletasks()
self.assertGreaterEqual(self.win.tree.winfo_height(), 80)
self.assertGreaterEqual(self.win.lot_tree.winfo_height(), 80)
def test_selection_populates_lot_and_container_details(self):
self.win._loaded(self.sample())
self.win.tree.selection_set("0")
@@ -98,11 +135,18 @@ class InventoryLauncherTests(unittest.TestCase):
from main import Launcher
from user_session import UserSession
session = UserSession(1, "TEST", "Test operator")
with patch.object(Launcher, "_apply_dynamic_geometry"), patch.object(Launcher, "lift"), \
patch.object(Launcher, "focus_force"), patch.object(Launcher, "_make_exit_icon", return_value=None):
with warnings.catch_warnings(), patch.object(Launcher, "_apply_dynamic_geometry"), \
patch.object(Launcher, "lift"), patch.object(Launcher, "focus_force"):
warnings.simplefilter("error", UserWarning)
root = Launcher(session, Mock())
root.withdraw()
try:
self.assertIsInstance(root._exit_icon, ctk.CTkImage)
self.assertEqual(root._exit_icon.cget("size"), (14, 14))
for mode in ("light", "dark"):
for scale in (1, 2):
photo = root._exit_icon.create_scaled_photo_image(scale, mode)
self.assertEqual((photo.width(), photo.height()), (14 * scale, 14 * scale))
def widgets(widget):
for child in widget.winfo_children():
yield child

View File

@@ -0,0 +1,212 @@
"""History search regression tests. SQL tests use ONLY temporary fixtures."""
import asyncio
import json
import os
import re
import tkinter as tk
import unittest
from unittest.mock import AsyncMock, Mock, patch
import customtkinter as ctk
from pickinglist_history_search import SQL_UDC_HISTORY, SQL_UDC_HISTORY_DETAILS, detail_request
from storico_pickinglist import StoricoPickingListWindow, SQL_STORICO_PL, SQL_STORICO_PL_DETAILS
class HistorySearchGuiTests(unittest.TestCase):
def setUp(self):
self.root = ctk.CTk()
self.root.withdraw()
self.runner = Mock()
self.db = Mock(query_json=AsyncMock(return_value={"rows": []}))
with patch("storico_pickinglist.AsyncRunner", return_value=self.runner):
self.win = StoricoPickingListWindow(self.root, self.db)
self.win.withdraw()
self.root.update_idletasks()
def tearDown(self):
for call in self.runner.run.call_args_list:
call.args[0].close()
for token in self.root.tk.call("after", "info"):
try:
self.root.tk.call("after", "cancel", token)
except tk.TclError:
pass
self.win.destroy()
self.root.destroy()
def rows(self):
return [dict(Documento=244, AnnoDocumento=year, IDDocumento=identity,
StatoDocumento="D", StatoOperativo="Chiusa ERP con residui", TotUDC=2,
RigheResidue=1, RigheSpedite=1, IDStato=0)
for year, identity in ((2026, 100), (2025, 200))]
def execute(self):
coroutine, ok, err = self.runner.run.call_args.args
result = asyncio.run(coroutine)
ok(result)
def test_default_query_is_unchanged_and_clearing_udc_restores_it(self):
self.win.var_udc.set("600001")
self.win._load_master()
self.execute()
self.db.query_json.assert_awaited_with(SQL_UDC_HISTORY,
{"documento": None, "pallet": "600001", "id_documento": None})
self.win.var_udc.set("")
self.win.var_documento.set("244")
self.win._load_master()
self.execute()
self.db.query_json.assert_awaited_with(SQL_STORICO_PL, {"documento": "244"})
def test_both_filters_combined_and_leading_zero_preserved(self):
self.win.var_udc.set(" 012345 ")
self.win.var_documento.set("244")
self.win._load_master()
self.execute()
self.assertEqual(self.db.query_json.await_args.args[1],
dict(documento="244", pallet="012345", id_documento=None))
def test_invalid_udc_does_not_query(self):
for value in ("ABC", "600001/123456", "6000017", "12%"):
self.win.var_udc.set(value)
with patch("storico_pickinglist.messagebox.showwarning") as warn:
self.win._load_master()
warn.assert_called_once()
self.runner.run.assert_not_called()
def test_same_document_number_different_year_details_are_isolated(self):
self.win._fill_master(self.rows())
self.win.master_tree.selection_set("doc_244_1")
self.win._on_master_select()
self.execute()
self.db.query_json.assert_awaited_with(SQL_UDC_HISTORY_DETAILS,
dict(pallet=None, documento=None, id_documento=200))
self.assertEqual(self.win._selected_doc_id, 200)
self.assertEqual(self.win.master_tree.item("doc_244_1", "values")[-1], "2025")
def test_selection_restored_by_id_not_by_display_number(self):
self.win._fill_master(self.rows())
self.win._restore_master_selection("244", 200)
self.assertEqual(self.win.master_tree.selection(), ("doc_244_1",))
def test_stale_detail_response_is_ignored(self):
self.win._fill_master(self.rows())
self.win.master_tree.selection_set("doc_244_0")
self.win._on_master_select()
stale = self.runner.run.call_args.args[1]
self.win.master_tree.selection_set("doc_244_1")
self.win._on_master_select()
stale({"rows": [dict(Pallet="WRONG")]})
self.assertEqual(self.win._detail_rows, [])
def test_residual_action_uses_exact_selected_id_and_whole_list(self):
self.win._fill_master(self.rows())
self.win.master_tree.selection_set("doc_244_1")
self.win._on_master_select()
self.db.query_json.return_value = {"rows": [dict(Pallet="600001", Cella=1000, StatoDocumento="D"),
dict(Pallet="600002", Cella=1106, StatoDocumento="D")]}
with patch("storico_pickinglist.messagebox.askyesno", return_value=True), \
patch("storico_pickinglist.move_pallet_async", new_callable=AsyncMock) as move:
move.return_value = {"ok": 1}
self.win._ship_selected_residuals()
asyncio.run(self.runner.run.call_args.args[0])
self.db.query_json.assert_awaited_with(SQL_UDC_HISTORY_DETAILS,
dict(pallet=None, documento=None, id_documento=200))
self.assertEqual([c.kwargs["barcode_pallet"] for c in move.await_args_list], ["600001", "600002"])
def test_toolbar_fits_minimum_window(self):
self.win.geometry("980x560+4000+0")
self.win.deiconify()
self.root.update_idletasks()
self.assertLessEqual(self.win.btn_ship_residuals.winfo_rootx() + self.win.btn_ship_residuals.winfo_width(),
self.win.winfo_rootx() + self.win.winfo_width())
def test_normal_detail_request_remains_unchanged(self):
self.assertEqual(detail_request("244", None, SQL_STORICO_PL_DETAILS),
(SQL_STORICO_PL_DETAILS, {"documento": "244"}))
@unittest.skipUnless(os.environ.get("HISTORY_TEST_CONFIG"), "SQL fixture test is opt-in")
class HistorySearchSQLTests(unittest.TestCase):
def setUp(self):
import pyodbc
with open(os.environ["HISTORY_TEST_CONFIG"], encoding="utf-8") as handle:
c = json.load(handle)
self.cn = pyodbc.connect("DRIVER={" + c["driver"] + "};SERVER=" + c["server"]
+ ";DATABASE=" + c["database"] + ";UID=" + c["user"] + ";PWD=" + c["password"]
+ ";TrustServerCertificate=yes;", timeout=5)
self.cn.timeout = 30
self.addCleanup(self.cn.close)
self.addCleanup(self.cn.rollback)
self.cur = self.cn.cursor()
self.definitions = {
"BAMTES": "ID int, ANNDOC int, NUMDOC int, DATDOC int, STATO char(1), IDNAZDEST int, IDMTRASP int",
"FATRIG": "ID int, IDBAM int, DESCR varchar(50)",
"LOTTIBF": "IDFATRIG int, IDLOTSER int",
"LOTSER": "ID int, NUMSER varchar(32), NUMLOT varchar(32), IDARTICO int, QTTGIAI float",
"ARTICO": "ID int, CODICE varchar(32)",
"NAZIONI": "ID int, CODICE varchar(8), DESCR varchar(50)",
"MTRASP": "ID int, CODICE varchar(8)",
"XMag_GiacenzaPallet": "BarcodePallet varchar(32), IDCella int",
"Celle": "ID int, Ordinamento int, Corsia varchar(8), Colonna varchar(8), Fila varchar(8)",
"PyPickingListReservation": "ID int, Documento varchar(8)",
}
for name, definition in self.definitions.items():
self.cur.execute(f"CREATE TABLE #h_{name} ({definition})")
self.cur.execute("INSERT INTO #h_Celle VALUES (1106,1,'1A','1','a'),(9999,2,'7G','1','1')")
self.cur.execute("INSERT INTO #h_ARTICO VALUES (1,'PRODUCT')")
self.cur.execute("INSERT INTO #h_PyPickingListReservation VALUES (1,'244')")
for identity, year in ((100,2026),(200,2025),(300,2024),(400,2027)):
self.cur.execute("INSERT INTO #h_BAMTES VALUES (?,?,244,?,'D',NULL,NULL)", identity, year, year*10)
self.cur.execute("INSERT INTO #h_FATRIG VALUES (?,?,'Product')", identity, identity)
self.cur.execute("INSERT INTO #h_LOTTIBF VALUES (?,?)", identity, 1)
self.cur.execute("INSERT INTO #h_LOTSER VALUES (1,'600001/111111','LOT1',1,10),(2,'600002/222222','LOT2',1,20),(3,'600001/333333','LOT3',1,30)")
self.cur.execute("INSERT INTO #h_LOTTIBF VALUES (100,2),(100,3)")
self.cur.execute("INSERT INTO #h_XMag_GiacenzaPallet VALUES ('600001',9999),('600002',1106)")
def query(self, *, pallet="600001", doc=None, identity=None, details=False, year=2026):
sql = SQL_UDC_HISTORY_DETAILS if details else SQL_UDC_HISTORY
for name in self.definitions:
sql = sql.replace("SAMA1.dbo." + name, "#h_" + name).replace("dbo." + name, "#h_" + name)
self.assertNotIn("dbo.", sql)
sql = sql.replace("YEAR(GETDATE())", str(year))
params = dict(pallet=pallet, documento=doc, id_documento=identity)
values = []
def bind(match):
values.append(params[match[1]])
return "?"
sql = re.sub(r":(pallet|documento|id_documento)\b", bind, sql)
self.cur.execute(sql, values)
names = [c[0] for c in self.cur.description]
return [dict(zip(names, r)) for r in self.cur.fetchall()]
def test_two_years_exact_udc_whole_document_counts(self):
rows = self.query()
self.assertEqual([r["IDDocumento"] for r in rows], [100,200])
self.assertEqual((rows[0]["TotUDC"], rows[0]["RigheResidue"], rows[0]["RigheSpedite"]), (2,1,1))
self.assertEqual(rows[0]["StatoOperativo"], "Chiusa ERP con residui")
self.assertEqual(rows[1]["StatoOperativo"], "Chiusa")
self.assertEqual((rows[0]["IDStato"], rows[1]["IDStato"]), (1,0))
def test_detail_by_id_does_not_mix_same_number_or_filter_out_other_udcs(self):
self.assertEqual(len(self.query(pallet=None, identity=200, details=True)), 1)
current = self.query(pallet=None, identity=100, details=True)
self.assertEqual(len(current), 3)
self.assertEqual({r["Pallet"] for r in current}, {"600001", "600002"})
def test_exact_match_and_optional_document_filter(self):
self.assertEqual(self.query(pallet="60000"), [])
self.assertEqual(self.query(doc="999"), [])
self.assertEqual(len(self.query(doc="24")), 2)
def test_year_window_rolls_forward(self):
self.assertEqual([r["IDDocumento"] for r in self.query(year=2027)], [400,100])
def test_open_documents_and_missing_location_are_returned(self):
self.cur.execute("UPDATE #h_BAMTES SET STATO='P' WHERE ID=200")
self.cur.execute("DELETE FROM #h_XMag_GiacenzaPallet WHERE BarcodePallet='600001'")
rows = self.query()
self.assertEqual(rows[1]["StatoOperativo"], "Da lavorare")
self.assertEqual(self.query(pallet=None, identity=200, details=True)[0]["Cella"], 1000)
def test_no_document_found(self):
self.assertEqual(self.query(pallet="123456"), [])

287
tests/test_reset_corsie.py Normal file
View File

@@ -0,0 +1,287 @@
"""Reset tests; optional SQL cases write exclusively to connection-local fixtures.
RESET_TEST_CONFIG=db_connection.json enables SQL Server execution. Every real
object and the reservation procedure are replaced before the batch is run.
"""
import ast
import json
import os
from pathlib import Path
import re
import unittest
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
from reset_corsie_service import SQL_RESET_PALLET, reset_pallet_async
ROOT = Path(__file__).resolve().parents[1]
class ResetTests(unittest.IsolatedAsyncioTestCase):
async def test_classification_is_returned_by_transaction_not_ui(self):
for target in (1000, 9999):
db = unittest.mock.Mock()
db.query_json = AsyncMock(return_value={"rows": [[target]]})
self.assertEqual(await reset_pallet_async(db, barcode_pallet=" 600001 ",
source_idcella=1106, utente="MAG1"), target)
db.query_json.assert_awaited_once_with(SQL_RESET_PALLET,
{"barcode_pallet": "600001", "source_idcella": 1106, "utente": "MAG1"},
commit=True)
async def test_db_error_is_not_reported_as_success(self):
db = unittest.mock.Mock()
db.query_json = AsyncMock(side_effect=RuntimeError("rollback"))
with self.assertRaisesRegex(RuntimeError, "rollback"):
await reset_pallet_async(db, barcode_pallet="600001", source_idcella=1106, utente="MAG1")
def test_classification_has_no_history_date_filter(self):
self.assertIn("bt.STATO = 'D'", SQL_RESET_PALLET)
self.assertNotIn("ANNDOC", SQL_RESET_PALLET)
self.assertNotIn("ViewPackingListStorico", SQL_RESET_PALLET)
def test_sqlalchemy_bind_parameters(self):
from sqlalchemy import text
self.assertEqual(set(text(SQL_RESET_PALLET).compile().params),
{"barcode_pallet", "source_idcella", "utente"})
def test_confirmation_and_result_localized(self):
catalog = json.loads((ROOT / "locale.json").read_text(encoding="utf-8"))
for lang in ("IT", "ENG"):
confirmation = catalog[lang]["reset.confirm"].format(udc=2, cells=1, aisle="1A")
self.assertIn("9999", confirmation)
self.assertIn("9001000", confirmation)
result = catalog[lang]["reset.result"].format(aisle="1A", success=2, total=2,
shipped=1, non_shelved=1)
self.assertIn("1000", result)
def test_virtual_cells_not_resettable(self):
module = ast.parse((ROOT / "reset_corsie.py").read_text(encoding="utf-8"))
queries = {node.targets[0].id: ast.literal_eval(node.value) for node in module.body
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant)
and isinstance(node.targets[0], ast.Name) and node.targets[0].id.startswith("SQL_")}
for query in ("SQL_CORSIE", "SQL_RIEPILOGO", "SQL_DETTAGLIO", "SQL_COUNT_RESET", "SQL_UDC_RESET"):
self.assertIn("NOT IN (1000, 9999)", queries[query])
async def test_window_worker_reports_mixed_results_and_errors(self):
# Execute the real callback body without opening a Tk window or DB.
module = ast.parse((ROOT / "reset_corsie.py").read_text(encoding="utf-8"))
cls = next(n for n in module.body if isinstance(n, ast.ClassDef) and n.name == "ResetCorsieWindow")
method = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "_do_reset")
method.decorator_list = []
move = AsyncMock(side_effect=[9999, RuntimeError("failure"), 1000])
messages = Mock()
from locale_text import text
namespace = dict(_log_sql=Mock(), _log_dataset=Mock(), _MODULE_LOGGER=Mock(),
MODULE_LOG_PATH=Path("reset_corsie.log"), SQL_UDC_RESET="SELECT fixture",
reset_pallet_async=move, messagebox=messages, loc_text=text, Any=object)
exec(compile(ast.Module(body=[method], type_ignores=[]), "reset_corsie.py", "exec"), namespace)
runner = Mock()
fake = SimpleNamespace(_async=runner, _busy=object(),
_locale_catalog=json.loads((ROOT / "locale.json").read_text(encoding="utf-8")),
db=SimpleNamespace(query_json=AsyncMock(return_value={"rows": [
["600001",1106,"1A.1.a"], ["600002",1106,"1A.1.a"], ["600003",1107,"1A.1.b"]]})),
session=SimpleNamespace(login="MAG1"), refresh=Mock())
namespace["_do_reset"](fake, "1A")
coroutine, on_ok, on_error = runner.run.call_args.args
result = await coroutine
self.assertEqual((result["success"], result["shipped"], result["non_shelved"]), (2,1,1))
self.assertEqual(result["failed"][0]["barcode_pallet"], "600002")
self.assertEqual(move.await_count, 3)
on_ok(result)
messages.showwarning.assert_called_once()
self.assertIn("Spedite in 9999 / 7G.1.1: 1", messages.showwarning.call_args.args[1])
fake.refresh.assert_called_once()
@unittest.skipUnless(os.environ.get("RESET_TEST_CONFIG"), "SQL fixture test is opt-in")
class ResetSQLTests(unittest.TestCase):
def setUp(self):
import pyodbc
with open(os.environ["RESET_TEST_CONFIG"], encoding="utf-8") as handle:
c = json.load(handle)
self.cn = pyodbc.connect("DRIVER={" + c["driver"] + "};SERVER=" + c["server"]
+ ";DATABASE=" + c["database"] + ";UID=" + c["user"] + ";PWD=" + c["password"]
+ ";TrustServerCertificate=yes;", timeout=5)
self.cn.timeout = 30
self.addCleanup(self.cn.close)
self.addCleanup(self.cn.rollback)
self.cur = self.cn.cursor()
definitions = {
"MagazziniPallet": "ID int IDENTITY PRIMARY KEY, Tipo char(1), IDRiferimento int, "
"NumeroPallet int, Attributo varchar(32), IDMagazzino int, IDArea int, IDCella int, "
"DataMagazzino datetime, PesoUnitario float, Tara float, InsUtente varchar(128), "
"InsDataOra datetime, ModUtente varchar(128), ModDataOra datetime",
"Celle": "ID int PRIMARY KEY, IDArea int, IDStato int, DelDataOra datetime, "
"ModUtente varchar(128), ModDataOra datetime",
"Aree": "ID int PRIMARY KEY, IDMagazzino int",
"LOTSER": "ID int, NUMSER varchar(32)",
"LOTTIBF": "IDLOTSER int, IDFATRIG int",
"FATRIG": "ID int, IDBAM int",
"BAMTES": "ID int, STATO char(1), ANNDOC int",
}
for name, definition in definitions.items():
self.cur.execute(f"CREATE TABLE #reset_{name} ({definition})")
self.cur.execute("CREATE TABLE #reset_refresh (Called int)")
self.sql = SQL_RESET_PALLET
for name in definitions:
self.sql = self.sql.replace("SAMA1.dbo." + name, "#reset_" + name)
self.sql = self.sql.replace("dbo." + name, "#reset_" + name)
# Same V-minus-P balance and grouping as the real XMag views.
self.stock = """SELECT mp.Attributo AS BarcodePallet, mp.IDCella
FROM #reset_MagazziniPallet mp JOIN #reset_Celle c ON c.ID=mp.IDCella
WHERE mp.Tipo IN ('V', 'P')
GROUP BY mp.Attributo, mp.NumeroPallet, mp.IDMagazzino, mp.IDArea, mp.IDCella, c.IDStato
HAVING SUM(CASE WHEN mp.Tipo='V' THEN mp.PesoUnitario ELSE -mp.PesoUnitario END)>0"""
self.sql = self.sql.replace("dbo.XMag_GiacenzaPallet", "(" + self.stock + ") AS g")
self.sql = self.sql.replace("EXEC dbo.py_sp_ControllaPrenotazionePackingListPalletNew;",
"INSERT INTO #reset_refresh VALUES (1);")
self.assertNotIn("dbo.", self.sql)
self.cur.execute("INSERT INTO #reset_Aree VALUES (1,1)")
self.cur.execute("INSERT INTO #reset_Celle (ID,IDArea,IDStato) VALUES (1106,1,1),(1107,1,0),(1000,1,0),(9999,1,0)")
self.udc("600001", 1106)
self.cn.commit()
def udc(self, pallet, cell):
self.cur.execute("""INSERT INTO #reset_MagazziniPallet
(Tipo, NumeroPallet, Attributo, IDMagazzino, IDArea, IDCella, PesoUnitario, Tara, InsUtente)
VALUES ('V',?,?,1,1,?,1,0,'OLD')""", int(pallet), pallet, cell)
def document(self, state, *, pallet="600001", year=2026, identity=1):
self.cur.execute("INSERT INTO #reset_BAMTES VALUES (?,?,?)", identity, state, year)
self.cur.execute("INSERT INTO #reset_FATRIG VALUES (?,?)", identity, identity)
self.cur.execute("INSERT INTO #reset_LOTTIBF VALUES (?,?)", identity, identity)
self.cur.execute("INSERT INTO #reset_LOTSER VALUES (?,?)", identity, pallet + "/123456")
def run_move(self, pallet="600001", source=1106, sql=None):
params = {"barcode_pallet": pallet, "source_idcella": source, "utente": "MAG1"}
values = []
def bind(match):
values.append(params[match[1]])
return "?"
batch = re.sub(r":(barcode_pallet|source_idcella|utente)\b", bind, sql or self.sql)
self.cur.execute(batch, values)
return self.cur.fetchval()
def locations(self, pallet="600001"):
return [r[0] for r in self.cur.execute("SELECT IDCella FROM (" + self.stock + ") g WHERE BarcodePallet=?", pallet)]
def test_definitive_document_ships_and_records_p_v(self):
self.document("D")
self.assertEqual(self.run_move(), 9999)
self.assertEqual(self.locations(), [9999])
rows = self.cur.execute("SELECT Tipo,IDCella,InsUtente,DataMagazzino FROM #reset_MagazziniPallet WHERE ID>1 ORDER BY ID").fetchall()
self.assertEqual([(r[0], r[1], r[2]) for r in rows], [("P",1106,"MAG1"),("V",9999,"MAG1")])
self.assertIsNotNone(rows[0][3])
self.assertEqual(rows[0][3], rows[1][3])
self.assertEqual(self.cur.execute("SELECT COUNT(*) FROM #reset_refresh").fetchval(), 1)
def test_old_definitive_document_is_not_lost_by_year_filter(self):
self.document("D", year=2010)
self.assertEqual(self.run_move(), 9999)
def test_open_document_becomes_non_shelved(self):
self.document("P")
self.assertEqual(self.run_move(), 1000)
self.assertEqual(self.locations(), [1000])
def test_no_document_becomes_non_shelved(self):
self.assertEqual(self.run_move(), 1000)
def test_closed_document_of_another_udc_does_not_ship_this_one(self):
self.document("D", pallet="600002")
self.assertEqual(self.run_move(), 1000)
def test_any_definitive_document_wins_and_multiple_lots_do_not_duplicate_move(self):
self.document("P")
self.document("D", identity=2)
self.document("D", identity=3)
self.assertEqual(self.run_move(), 9999)
self.assertEqual(self.cur.execute("SELECT COUNT(*) FROM #reset_MagazziniPallet").fetchval(), 3)
def test_different_udcs_in_same_cell_have_independent_destinations(self):
self.udc("600002", 1106)
self.document("D")
self.assertEqual(self.run_move(), 9999)
self.assertEqual(self.run_move("600002"), 1000)
self.assertEqual(self.locations(), [9999])
self.assertEqual(self.locations("600002"), [1000])
def test_moved_udc_is_blocked(self):
with self.assertRaisesRegex(Exception, "51002"):
self.run_move(source=1107)
self.cn.rollback()
self.assertEqual(self.locations(), [1106])
def test_multiple_locations_are_blocked(self):
self.udc("600001", 1107)
self.cn.commit()
with self.assertRaisesRegex(Exception, "51002"):
self.run_move()
self.cn.rollback()
self.assertEqual(set(self.locations()), {1106, 1107})
def test_missing_target_rolls_back(self):
self.cur.execute("DELETE FROM #reset_Celle WHERE ID=1000")
self.cn.commit()
with self.assertRaisesRegex(Exception, "51003"):
self.run_move()
self.cn.rollback()
self.assertEqual(self.locations(), [1106])
def test_inconsistent_double_balance_rolls_back_instead_of_leaving_two_cells(self):
self.udc("600001", 1106)
self.cn.commit()
with self.assertRaisesRegex(Exception, "51005"):
self.run_move()
self.cn.rollback()
self.assertEqual(self.locations(), [1106])
self.assertEqual(self.cur.execute("SELECT COUNT(*) FROM #reset_MagazziniPallet").fetchval(), 2)
def test_reservation_failure_rolls_back_both_movements(self):
sql = self.sql.replace("INSERT INTO #reset_refresh VALUES (1);",
"THROW 51009, 'Test refresh failure', 1;")
with self.assertRaisesRegex(Exception, "51009"):
self.run_move(sql=sql)
self.cn.rollback()
self.assertEqual(self.locations(), [1106])
self.assertEqual(self.cur.execute("SELECT COUNT(*) FROM #reset_MagazziniPallet").fetchval(), 1)
self.assertEqual(self.cur.execute("SELECT IDStato FROM #reset_Celle WHERE ID=1106").fetchval(), 1)
def test_residuals_outside_reset_aisle_are_not_changed(self):
self.udc("600002", 1107)
self.udc("600003", 1000)
self.document("D")
self.assertEqual(self.run_move(), 9999)
self.assertEqual(self.locations("600002"), [1107])
self.assertEqual(self.locations("600003"), [1000])
def test_real_history_query_closes_only_after_last_residual(self):
# Feed the unmodified history summary SQL with connection-local rows.
tree = ast.parse((ROOT / "storico_pickinglist.py").read_text(encoding="utf-8"))
sql = next(ast.literal_eval(n.value) for n in tree.body if isinstance(n, ast.Assign)
and isinstance(n.value, ast.Constant) and isinstance(n.value.value, str)
and "AS StatoOperativo" in n.value.value)
self.cur.execute("CREATE TABLE #reset_history (Pallet varchar(32))")
self.cur.execute("INSERT INTO #reset_history VALUES ('600001'),('600002')")
self.udc("600002", 1107)
self.document("D")
self.document("D", pallet="600002", identity=2)
source = """(SELECT h.Pallet, 244 AS Documento, 46000 AS DataDocumento,
'D' AS StatoDocumento, 'IT' AS NAZIONE, 'IT' AS CodNazione,
1 AS Ordinamento, 0 AS IDStato, COALESCE(g.IDCella,1000) AS Cella
FROM #reset_history h LEFT JOIN (""" + self.stock + """
) g ON g.BarcodePallet=h.Pallet) AS fixture"""
sql = sql.replace("dbo.py_XMag_ViewPackingListStorico", source).replace(":documento", "NULL")
self.assertNotIn("dbo.", sql)
def state():
self.cur.execute(sql)
return dict(zip([c[0] for c in self.cur.description], self.cur.fetchone()))["StatoOperativo"]
self.assertEqual(state(), "Chiusa ERP con residui")
self.run_move()
self.assertEqual(state(), "Chiusa ERP con residui")
self.run_move("600002", source=1107)
self.assertEqual(state(), "Chiusa")
if __name__ == "__main__":
unittest.main()

View File

@@ -25,7 +25,7 @@
"dbconfig.button.test": "Prova subito la connessione con i dati inseriti senza ancora salvarli definitivamente.",
"dbconfig.button.save": "Verifica i dati, salva il file di configurazione e permette al programma di continuare l'avvio.",
"reset_corsie.refresh": "Ricarica il riepilogo e l'elenco delle celle occupate per la corsia selezionata.",
"reset_corsie.empty_aisle": "Scarica logicamente tutte le UDC attive della corsia selezionata verso l'ubicazione di uscita.",
"reset_corsie.empty_aisle": "Svuota la corsia: UDC associate a documenti definitivi in 7G.1.1, tutte le altre non scaffalate. Registra prelievi e versamenti.",
"layout.search_udc": "Cerca una UDC per barcode, cambia automaticamente corsia e porta in evidenza la cella trovata.",
"layout.refresh": "Ricarica la corsia selezionata e aggiorna matrice, colori e statistiche.",
"layout.export_xlsx": "Esporta la vista corrente del layout corsia in un file Excel.",
@@ -69,7 +69,7 @@
"dbconfig.button.test": "Try the connection immediately with the entered values without saving them yet.",
"dbconfig.button.save": "Validate the connection, save the configuration file and let the program continue startup.",
"reset_corsie.refresh": "Reload the summary and the list of occupied cells for the selected aisle.",
"reset_corsie.empty_aisle": "Logically unload all active UDCs in the selected aisle to the outbound location.",
"reset_corsie.empty_aisle": "Empty the aisle: UDCs associated with definitive documents go to 7G.1.1; all others become non-shelved. Records pick and put-away movements.",
"layout.search_udc": "Search a UDC by barcode, switch aisle automatically and highlight the matching cell.",
"layout.refresh": "Reload the selected aisle and refresh matrix, colors and statistics.",
"layout.export_xlsx": "Export the current aisle layout view to an Excel file.",

View File

@@ -3,7 +3,8 @@
from __future__ import annotations
import tkinter as tk
from tkinter import messagebox, ttk
import error_dialog as messagebox
from tkinter import ttk
from typing import Any
import customtkinter as ctk
@@ -177,6 +178,7 @@ class UDCNonScaffalateWindow(ctk.CTkToplevel):
loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"),
str(exc),
parent=self if self._is_alive() else None,
exception=exc,
)
def _on_loaded(self, res: dict[str, Any] | None) -> None:
@@ -207,6 +209,7 @@ class UDCNonScaffalateWindow(ctk.CTkToplevel):
loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"),
str(exc),
parent=self,
exception=exc,
)
def _on_error(self, exc: BaseException) -> None:
@@ -219,6 +222,7 @@ class UDCNonScaffalateWindow(ctk.CTkToplevel):
loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"),
str(exc),
parent=self,
exception=exc,
)

View File

@@ -1,5 +1,16 @@
{
"error_dialog": {
"width": 900,
"height": 620,
"background": "#ffffff",
"foreground": "#202020",
"font": {"family": "Consolas", "size": 10}
},
"inventory_window": {
"legend_fg_color": ["#f8fafb", "#262b30"],
"legend_text_color": ["#202830", "#f1f3f5"],
"legend_font": {"family": "Segoe UI", "size": 13},
"legend_heading_font": {"family": "Segoe UI", "size": 13, "weight": "bold"},
"window_geometry": "1200x720",
"window_minsize": [900, 560],
"window_fg_color": ["#efefef", "#2f2f2f"],

View File

@@ -9,36 +9,39 @@ APP_VERSION = "1.0.0"
MODULE_VERSIONS: dict[str, str] = {
"app": APP_VERSION,
"error_dialog": "1.0.0",
"async_loop_singleton": "1.0.0",
"async_msssql_query": "1.0.1",
"audit_log": "1.0.0",
"main": "1.0.3",
"inventario": "1.1.0",
"main": "1.0.5",
"inventario": "1.1.2",
"inventory_service": "1.1.0",
"barcode_client": "1.0.27",
"barcode_client": "1.0.28",
"barcode_repository": "1.0.14",
"barcode_service": "1.0.25",
"busy_overlay": "1.0.0",
"db_config": "1.0.0",
"diagnostica": "1.0.4",
"db_config": "1.0.1",
"diagnostica": "1.0.5",
"gestione_aree": "1.0.1",
"gestione_layout": "1.0.2",
"gestione_pickinglist": "1.0.6",
"gestione_scarico": "1.0.8",
"gestione_layout": "1.0.3",
"gestione_pickinglist": "1.0.7",
"gestione_scarico": "1.0.9",
"locale_text": "1.0.0",
"login_window": "1.0.0",
"login_window": "1.0.1",
"prenota_sprenota_sql": "1.0.1",
"pickinglist_sequence": "1.0.0",
"reset_corsie": "1.0.0",
"runtime_support": "1.0.1",
"search_pallets": "1.0.0",
"storico_pickinglist": "1.0.4",
"storico_udc": "1.0.0",
"pickinglist_sequence": "1.0.1",
"reset_corsie": "1.0.2",
"reset_corsie_service": "1.0.0",
"runtime_support": "1.0.2",
"search_pallets": "1.0.1",
"storico_pickinglist": "1.0.6",
"pickinglist_history_search": "1.0.0",
"storico_udc": "1.0.1",
"tooltips": "1.0.0",
"udc_non_scaffalate": "1.0.1",
"udc_non_scaffalate": "1.0.2",
"ui_theme": "1.0.0",
"user_session": "1.0.3",
"view_celle_multi_udc": "1.0.0",
"view_celle_multi_udc": "1.0.1",
"window_placement": "1.0.0",
}

View File

@@ -9,7 +9,8 @@ import tkinter as tk
from datetime import datetime
from functools import wraps
from pathlib import Path
from tkinter import filedialog, messagebox, ttk
import error_dialog as messagebox
from tkinter import filedialog, ttk
from typing import Any
import customtkinter as ctk
@@ -651,7 +652,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
def _err(ex):
_MODULE_LOGGER.exception(f"Errore caricamento corsie UDC fantasma: {ex}")
messagebox.showerror("Errore", str(ex), parent=self)
messagebox.showerror("Errore", str(ex), parent=self, exception=ex)
self.runner.run(
_q(self.db),
@@ -712,7 +713,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
def _err(ex):
_MODULE_LOGGER.exception(f"Errore caricamento celle duplicate corsia={corsia}: {ex}")
messagebox.showerror("Errore", str(ex), parent=self)
messagebox.showerror("Errore", str(ex), parent=self, exception=ex)
self.runner.run(
_q(self.db),
@@ -762,7 +763,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
def _err(ex):
_MODULE_LOGGER.exception(f"Errore caricamento pallet cella idcella={idcella}: {ex}")
messagebox.showerror("Errore", str(ex), parent=self)
messagebox.showerror("Errore", str(ex), parent=self, exception=ex)
self.runner.run(
_q(self.db),
@@ -889,7 +890,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
def _err(ex):
self._busy.hide()
_MODULE_LOGGER.exception(f"Errore preselezione fantasmi corsia={corsia}: {ex}")
messagebox.showerror("Errore", str(ex), parent=self)
messagebox.showerror("Errore", str(ex), parent=self, exception=ex)
self.runner.run(
_q(self.db),
@@ -962,7 +963,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
def _err(ex):
self._busy.hide()
_MODULE_LOGGER.exception(f"Errore bonifica fantasmi corsia={corsia}: {ex}")
messagebox.showerror("Errore bonifica", str(ex), parent=self)
messagebox.showerror("Errore bonifica", str(ex), parent=self, exception=ex)
self.runner.run(
_q(self.db),
@@ -982,7 +983,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
def _err(ex):
_MODULE_LOGGER.exception(f"Errore caricamento riepilogo UDC fantasma: {ex}")
messagebox.showerror("Errore", str(ex), parent=self)
messagebox.showerror("Errore", str(ex), parent=self, exception=ex)
self.runner.run(
_q(self.db),
@@ -1095,7 +1096,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
messagebox.showinfo("Esportazione completata", f"File creato:\n{fname}", parent=self)
except Exception as ex:
_MODULE_LOGGER.exception(f"Errore esportazione UDC fantasma: {ex}")
messagebox.showerror("Errore esportazione", str(ex), parent=self)
messagebox.showerror("Errore esportazione", str(ex), parent=self, exception=ex)
def open_celle_multiple_window(