Compare commits

..

23 Commits

Author SHA1 Message Date
3a2893dc3d Aggiungi sequenza prelievo e gestisci destinazioni senza nazione 2026-09-29 11:52:33 +02:00
5dc26b21b1 Rendi ordinabili le griglie diagnostica 2026-07-06 18:42:07 +02:00
0ae052e55b Rendi operativa diagnostica UDC SAM recenti 2026-07-06 18:37:00 +02:00
7dc068b1b0 Aggiungi diagnostica UDC SAM non entrate in WMS 2026-07-06 18:23:01 +02:00
1ea37eb49d Aggiungi diagnostica celle con multiple UDC 2026-07-06 18:16:17 +02:00
7f3ce9d3af Aggiungi export XLSX diagnostica 2026-07-06 18:14:13 +02:00
8e9294f80b Aggiungi finestra diagnostica quadrature 2026-07-06 18:07:27 +02:00
fa9d0be09a Obbliga conferma movimenti barcode con tasti funzione 2026-07-06 17:56:44 +02:00
44cd82352b Ripristina storico picking list anno corrente 2026-07-06 09:45:42 +02:00
eb12af3b9a Ottimizza barcode e disattiva profiler query 2026-07-04 18:26:20 +02:00
77da8d9bad Stabilizza picking barcode e patch cumulativa online 2026-07-04 17:03:55 +02:00
5dd7139b19 Differenzia scarico layout spedita e non scaffalata 2026-07-04 09:27:52 +02:00
d4cfe0be54 Aggiungi salto UDC nel picking barcode 2026-07-04 09:13:25 +02:00
f4e73bd5b9 Recupera movimenti barcode dopo risposta persa 2026-07-04 09:05:14 +02:00
e575c748cc Rafforza controlli carico barcode 2026-07-03 15:40:06 +02:00
7ecc906d59 Aggiungi pausa picking list nel barcode 2026-07-03 10:13:49 +02:00
29687c8094 Aggiungi prontuario Git per installazione remota 2026-06-19 10:15:30 +02:00
bd844ce056 Stabilizza barcode e UDC non scaffalate 2026-06-18 18:19:00 +02:00
466778ae5f Alpha6 barcode non scaffalate e bypass login 2026-06-18 16:13:47 +02:00
cc9680c49a Aggiungi versamento residui 7G da storico pickinglist 2026-06-17 11:24:05 +02:00
be7ce700d1 Alpha4 polish griglie e login 2026-06-16 15:51:50 +02:00
29900b8b09 Freeze stato gestione picking e storico 2026-06-15 20:56:35 +02:00
8f9957a2db Introdotto versioning visibile ver 1.0 2026-06-05 11:33:47 +02:00
58 changed files with 7838 additions and 335 deletions

View File

@@ -0,0 +1,61 @@
# Installazione produzione - Warehouse/FlyWMS bridge
## Ordine consigliato
1. Fare backup del database `Mediseawall`.
2. Copiare il contenuto dello zip in una cartella locale, ad esempio `C:\flywms`.
3. Installare le dipendenze Python:
```bat
python -m pip install -r requirements.txt
```
4. In SSMS, sul database `Mediseawall`, lanciare:
```text
apply_python_parallel_pickinglist_patch.sql
apply_online_history_forms_patch.sql
```
## Cosa fanno gli script
- `apply_python_parallel_pickinglist_patch.sql` crea il ramo SQL Python per gestione picking list, senza modificare le stored procedure C# legacy.
- `apply_online_history_forms_patch.sql` crea le viste Python-only per "Storico Picking List".
- "Storico movimenti UDC" non richiede script dedicati: legge in sola lettura `MagazziniPallet`, `Celle` e `XMag_GiacenzaPalletPlistChiuse`.
## Rollback SQL
Se serve tornare indietro sugli oggetti Python, usare:
```text
rollback_online_history_forms_patch.sql
rollback_python_parallel_pickinglist_patch.sql
```
La tabella `dbo.PyPickingListReservation`, se creata, puo' rimanere anche in caso di rollback perche' il C# legacy non la usa.
## Avvio
Backoffice con console:
```bat
python main.py
```
Backoffice senza console:
```bat
pythonw warehouse.pyw
```
Barcode senza console:
```bat
pythonw barcode.pyw
```
Se si usa un collegamento Windows, impostare anche la cartella "Da" alla cartella dell'applicazione, ad esempio `C:\flywms`.
## File esclusi dal pacchetto
Il pacchetto non include `db_connection.json`, log, cache Python e vecchi zip locali. Alla prima apertura il programma chiedera' la configurazione DB se `db_connection.json` non esiste.

View File

@@ -0,0 +1,247 @@
# Picking list con nazione di destinazione mancante
## Scopo
Questo documento descrive il difetto che rendeva invisibile una picking list
quando il documento SAM utilizzava un indirizzo di destinazione alternativo
senza nazione valorizzata. Descrive inoltre la correzione applicata al solo
ramo dati Python del WMS, le conseguenze funzionali e le verifiche da eseguire.
La correzione non modifica tabelle o viste legacy utilizzate dal programma C#
e non aggiorna dati anagrafici o documentali in SAM.
## Caso che ha evidenziato il difetto
Il problema e' stato rilevato sulla picking list `244/2026`:
| Dato | Valore |
|---|---|
| `BAMTES.ID` | `11896` |
| `BAMTES.NUMDOC` | `244` |
| `BAMTES.ANNDOC` | `2026` |
| Data documento | `24/09/2026` |
| `BAMTES.STATO` | `P` |
| `BAMTES.IDINDDEST` | `274` |
| Destinazione | `c/o UNITRANS Magazzino 4 Mirandola` |
| `BAMTES.IDNAZDEST` | `NULL` |
L'indirizzo alternativo `SAMA1.dbo.INDANA.ID = 274` esiste, ma anche il suo
campo `IDNAZIONI` e' `NULL`. L'indirizzo abituale della stessa controparte ha
invece `IDNAZIONI = 21`, corrispondente all'Italia.
Il documento non aveva altri problemi:
- anno corrente valido;
- stato `P` valido;
- data compresa nell'intervallo operativo;
- 4 righe documento;
- 494 righe lotto valide;
- 26 UDC distinte;
- trasportatore esistente.
## Causa tecnica
La preparazione delle picking list collegava la testata del documento alla
tabella delle nazioni con un collegamento obbligatorio:
```sql
FROM SAMA1.dbo.NAZIONI
INNER JOIN SAMA1.dbo.BAMTES
ON SAMA1.dbo.NAZIONI.ID = SAMA1.dbo.BAMTES.IDNAZDEST
```
Un `INNER JOIN` conserva soltanto le testate per le quali esiste una nazione
compatibile. Quando `BAMTES.IDNAZDEST` e' `NULL`, il confronto non puo' trovare
alcuna riga e l'intero documento scompare prima che vengano elaborate righe,
lotti e UDC.
Nel caso 244 la diagnosi ha prodotto:
```text
Righe valide senza join obbligatorio a NAZIONI: 494
Righe valide con join obbligatorio a NAZIONI: 0
```
Il filtro della GUI a 10 giorni, la prenotazione e la sequenza di prelievo non
erano quindi responsabili del problema.
## Flusso dati interessato
La pagina Gestione Picking List usa questa catena:
```text
SAMA1.dbo.BAMTES / FATRIG / LOTTIBF / LOTSER
|
v
dbo.py_XMag_ViewPackingList
|
v
dbo.py_ViewPackingListRestante
|
v
dbo.py_ViewPackingListPrelievo
|
v
Gestione Picking List e barcode Python
```
Lo storico Python utilizza inoltre:
```text
SAMA1
-> dbo.py_vPreparaPackingListSAMA1
-> dbo.py_vPreparaPackingList
-> dbo.py_XMag_ViewPackingListStorico
```
Per evitare comportamenti diversi fra operativita' e storico, la correzione e'
stata applicata sia alla preparazione operativa sia alla preparazione storica.
## Correzione applicata
Il collegamento e' stato reso opzionale:
```sql
FROM SAMA1.dbo.BAMTES AS bt
LEFT OUTER JOIN SAMA1.dbo.NAZIONI AS n
ON n.ID = bt.IDNAZDEST
```
Con il `LEFT OUTER JOIN` la testata BAMTES viene conservata anche quando la
nazione e' assente. Gli altri collegamenti essenziali verso righe, lotti e
seriali restano obbligatori.
Sono state modificate soltanto queste viste Python:
- `dbo.py_vPreparaPackingListSAMA1`;
- `dbo.py_XMag_ViewPackingList`.
Le viste dipendenti ricevono automaticamente i dati corretti:
- `dbo.py_vPreparaPackingList`;
- `dbo.py_XMag_ViewPackingListStorico`;
- `dbo.py_ViewPackingListRestante`;
- `dbo.py_ViewPackingListPrelievo`.
## Gestione dei valori mancanti
La patch non assegna automaticamente una nazione. Questo evita di trasformare
un'anagrafica incompleta in un dato apparentemente certo.
Quando la nazione manca:
- `CodNazione` resta `NULL`;
- `NAZIONE` resta `NULL`;
- il documento e le sue UDC restano visibili;
- il `CASE` applicativo gia' esistente usa il ramo generico `Stato = 4`;
- prenotazione, dettaglio UDC e sequenza di prelievo continuano a funzionare.
La correzione dell'anagrafica SAM rimane comunque consigliata. La robustezza
della vista impedisce pero' che un campo descrittivo incompleto blocchi un
processo operativo di magazzino.
## Script di installazione
La patch autonoma e' contenuta in:
```text
apply_pickinglist_optional_destination_country_patch.sql
```
Lo stesso cambiamento e' stato integrato anche negli script cumulativi:
- `apply_pickinglist_days_filter_patch.sql`;
- `apply_online_python_wms_full_patch.sql`.
Per aggiornare un database che possiede gia' le viste Python e' sufficiente
eseguire una sola volta in SSMS la patch autonoma. Gli script usano
`CREATE OR ALTER VIEW`, quindi possono essere rieseguiti senza duplicare dati.
## Verifica post-patch
Controllo della vista operativa:
```sql
SELECT
Documento,
DataDocumento,
CodNazione,
NAZIONE,
Stato,
IDStato,
COUNT(DISTINCT Pallet) AS NumeroUDC
FROM dbo.py_ViewPackingListPrelievo
WHERE Documento = 244
GROUP BY
Documento,
DataDocumento,
CodNazione,
NAZIONE,
Stato,
IDStato;
```
Risultato ottenuto dopo la correzione:
```text
Documento: 244
CodNazione: NULL
NAZIONE: NULL
Stato: 4
IDStato: 0
Numero UDC: 26
```
Controllo dei quattro livelli principali:
```sql
SELECT COUNT(DISTINCT UDC) AS UDC
FROM dbo.py_vPreparaPackingListSAMA1
WHERE NUMDOC = 244 AND StatoDocumento = 'P';
SELECT COUNT(DISTINCT Pallet) AS UDC
FROM dbo.py_XMag_ViewPackingList
WHERE Documento = 244;
SELECT COUNT(DISTINCT Pallet) AS UDC
FROM dbo.py_ViewPackingListRestante
WHERE Documento = 244;
SELECT COUNT(DISTINCT Pallet) AS UDC
FROM dbo.py_ViewPackingListPrelievo
WHERE Documento = 244;
```
Tutte e quattro le query devono restituire `26` per il caso analizzato.
## Impatto e compatibilita'
- Nessuna riga SAM viene inserita, aggiornata o cancellata.
- Nessuna prenotazione viene modificata.
- Nessuna stored procedure di movimentazione viene modificata.
- Le picking list con nazione valida mantengono lo stesso risultato.
- Le picking list prima invisibili per nazione nulla diventano visibili.
- Gli oggetti legacy senza prefisso `py_` non vengono modificati.
## Ripristino concettuale
Per ripristinare il comportamento precedente occorrerebbe riportare il
collegamento `BAMTES -> NAZIONI` da `LEFT OUTER JOIN` a `INNER JOIN` nelle due
viste Python modificate. Tale rollback farebbe nuovamente scomparire tutti i
documenti con `IDNAZDEST` nullo e non e' quindi raccomandato come soluzione
operativa.
## Miglioramento futuro consigliato
Una diagnostica separata potrebbe mostrare le picking list con dati anagrafici
incompleti, senza impedirne l'uso:
```sql
SELECT ID, ANNDOC, NUMDOC, IDINDDEST, DESCRDEST
FROM SAMA1.dbo.BAMTES
WHERE STATO = 'P'
AND IDNAZDEST IS NULL;
```
In questo modo il WMS rimane operativo e l'amministratore puo' correggere
l'anagrafica SAM in un secondo momento.

View File

@@ -0,0 +1,43 @@
SET XACT_ABORT ON;
BEGIN TRANSACTION;
IF OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U') IS NULL
BEGIN
CREATE TABLE dbo.py_BarcodePickingListSkip (
ID int IDENTITY(1,1) NOT NULL CONSTRAINT PK_py_BarcodePickingListSkip PRIMARY KEY,
Documento varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
Pallet varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
IDStato int NOT NULL,
IDOperatore int NOT NULL,
DataOra datetime2(0) NOT NULL CONSTRAINT DF_py_BarcodePickingListSkip_DataOra DEFAULT SYSDATETIME(),
Motivo nvarchar(200) NULL,
Risolto bit NOT NULL CONSTRAINT DF_py_BarcodePickingListSkip_Risolto DEFAULT 0,
RisoltoDa int NULL,
RisoltoDataOra datetime2(0) NULL
);
END;
IF NOT EXISTS (
SELECT 1
FROM sys.indexes
WHERE name = N'UX_py_BarcodePickingListSkip_Open'
AND object_id = OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U')
)
BEGIN
CREATE UNIQUE INDEX UX_py_BarcodePickingListSkip_Open
ON dbo.py_BarcodePickingListSkip (Documento, Pallet, IDStato)
WHERE Risolto = 0;
END;
IF NOT EXISTS (
SELECT 1
FROM sys.indexes
WHERE name = N'IX_py_BarcodePickingListSkip_Queue'
AND object_id = OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U')
)
BEGIN
CREATE INDEX IX_py_BarcodePickingListSkip_Queue
ON dbo.py_BarcodePickingListSkip (IDStato, Documento, Pallet, Risolto);
END;
COMMIT TRANSACTION;

View File

@@ -0,0 +1,725 @@
/*
Patch cumulativa DB online - ramo Python WMS
Da eseguire una sola volta in SSMS sul database Mediseawall.
Questa patch NON modifica gli oggetti legacy usati dal programma C#.
Include:
- dbo.PyPickingListReservation
- dbo.py_XMag_ViewPackingList
- dbo.py_ViewPackingListRestante
- dbo.py_sp_xExePackingListPallet
- dbo.py_sp_xExePackingListPalletPrenota
- dbo.py_sp_ControllaPrenotazionePackingListPalletNew
- dbo.py_vPreparaPackingListSAMA1
- dbo.py_vPreparaPackingList
- dbo.py_XMag_ViewPackingListStorico
- dbo.py_BarcodePickingListSkip
- dbo.py_PickingListPrelievoSequenza
- dbo.py_ViewPackingListPrelievo
Include inoltre:
- intervallo operativo massimo di 30 giorni, filtrato dalla UI a 10/15/20/30;
- destinazione senza nazione ammessa nel ramo Python mediante LEFT JOIN;
- ordine predefinito con UDC Non scaff. prima degli scaffali;
- ordine personalizzabile per singolo Documento.
Nota storico:
dbo.py_vPreparaPackingListSAMA1 usa ANNDOC >= YEAR(GETDATE())
per mantenere visibili solo le picking list dall'inizio dell'anno corrente.
*/
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
/* ============================================================
1. Stato prenotazione picking list ramo Python
============================================================ */
IF OBJECT_ID(N'dbo.PyPickingListReservation', N'U') IS NULL
BEGIN
CREATE TABLE [dbo].[PyPickingListReservation](
[ID] [tinyint] NOT NULL,
[Documento] [varchar](8) NULL,
[IDOperatore] [int] NULL,
[ModUtente] [varchar](50) NULL,
[ModDataOra] [datetime] NULL,
CONSTRAINT [PK_PyPickingListReservation] PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [CK_PyPickingListReservation_Singleton] CHECK ([ID] = 1)
) ON [PRIMARY];
END
GO
IF NOT EXISTS (SELECT 1 FROM dbo.PyPickingListReservation WHERE ID = 1)
BEGIN
INSERT INTO dbo.PyPickingListReservation (ID, Documento, IDOperatore, ModUtente, ModDataOra)
VALUES (1, NULL, NULL, NULL, GETDATE());
END
GO
/* ============================================================
2. Viste operative picking list ramo Python
============================================================ */
CREATE OR ALTER VIEW [dbo].[py_XMag_ViewPackingList]
AS
SELECT TOP 10000
legacy.Pallet,
legacy.Lotto,
legacy.Articolo,
legacy.Descrizione,
legacy.Qta,
legacy.Documento,
legacy.CodNazione,
legacy.NAZIONE,
legacy.Stato,
legacy.PalletCella,
legacy.Magazzino,
legacy.Area,
legacy.Cella,
legacy.Ordinamento,
legacy.Ubicazione,
legacy.DEST,
CASE
WHEN pr.Documento IS NOT NULL
AND pr.Documento = CAST(legacy.Documento AS varchar(8))
THEN 1
ELSE 0
END AS IDStato
FROM dbo.XMag_ViewPackingList legacy
LEFT JOIN dbo.PyPickingListReservation pr
ON pr.ID = 1
AND NULLIF(LTRIM(RTRIM(pr.Documento)), '') IS NOT NULL
ORDER BY
CASE
WHEN pr.Documento IS NOT NULL
AND pr.Documento = CAST(legacy.Documento AS varchar(8))
THEN 1
ELSE 0
END DESC,
legacy.Documento,
legacy.Ordinamento;
GO
CREATE OR ALTER VIEW [dbo].[py_ViewPackingListRestante]
AS
SELECT
Pallet,
Lotto,
Articolo,
Descrizione,
Qta,
Documento,
CodNazione,
NAZIONE,
Stato,
PalletCella,
Magazzino,
Area,
Cella,
Ordinamento,
Ubicazione,
DEST,
IDStato
FROM dbo.py_XMag_ViewPackingList
WHERE Cella <> 9999;
GO
/* ============================================================
3. Stored procedure operative ramo Python
============================================================ */
CREATE OR ALTER PROCEDURE [dbo].[py_sp_xExePackingListPallet]
@IDOperatore int,
@Documento varchar(8),
@Azione char(1) = 'P',
@RC int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET @RC = 0;
DECLARE @Nominativo varchar(50) = '';
DECLARE @DocumentoAttivo varchar(8) = NULL;
DECLARE @Description varchar(255) = '';
DECLARE @Message varchar(255) = '';
DECLARE @IDResult int = 0;
DECLARE @ID int = 0;
SELECT @Nominativo = [Login]
FROM dbo.Operatori
WHERE ID = @IDOperatore;
IF @Nominativo IS NULL
SET @Nominativo = 'SYSTEM';
IF @Azione NOT IN ('P', 'S')
BEGIN
SET @RC = -10;
RETURN;
END;
IF NOT EXISTS (
SELECT 1
FROM dbo.py_XMag_ViewPackingList
WHERE CAST(Documento AS varchar(8)) = @Documento
)
BEGIN
SET @RC = -20;
RETURN;
END;
IF NOT EXISTS (SELECT 1 FROM dbo.PyPickingListReservation WHERE ID = 1)
BEGIN
INSERT INTO dbo.PyPickingListReservation (ID, Documento, IDOperatore, ModUtente, ModDataOra)
VALUES (1, NULL, NULL, NULL, GETDATE());
END;
SELECT @DocumentoAttivo = NULLIF(LTRIM(RTRIM(Documento)), '')
FROM dbo.PyPickingListReservation
WHERE ID = 1;
DECLARE @TargetCelle TABLE (
IDCella int PRIMARY KEY
);
INSERT INTO @TargetCelle (IDCella)
SELECT DISTINCT Cella
FROM dbo.py_XMag_ViewPackingList
WHERE CAST(Documento AS varchar(8)) = @Documento
AND Cella IS NOT NULL;
IF @Azione = 'P'
BEGIN
IF @DocumentoAttivo = @Documento
RETURN;
UPDATE c
SET c.IDStato = 0,
c.ModUtente = @Nominativo,
c.ModDataOra = GETDATE()
FROM dbo.Celle c
WHERE ISNULL(c.IDStato, 0) <> 0;
UPDATE c
SET c.IDStato = 1,
c.ModUtente = @Nominativo,
c.ModDataOra = GETDATE()
FROM dbo.Celle c
INNER JOIN @TargetCelle t ON t.IDCella = c.ID;
UPDATE dbo.PyPickingListReservation
SET Documento = @Documento,
IDOperatore = @IDOperatore,
ModUtente = @Nominativo,
ModDataOra = GETDATE()
WHERE ID = 1;
SELECT TOP 1 @Description = NAZIONE
FROM dbo.py_XMag_ViewPackingList
WHERE CAST(Documento AS varchar(8)) = @Documento;
EXEC dbo.sp_LogPackingList
@ID = @ID,
@Code = @Documento,
@Description = @Description,
@Message = @Message OUTPUT,
@IDResult = @IDResult OUTPUT;
RETURN;
END;
IF @Azione = 'S'
BEGIN
IF ISNULL(@DocumentoAttivo, '') <> @Documento
RETURN;
UPDATE c
SET c.IDStato = 0,
c.ModUtente = @Nominativo,
c.ModDataOra = GETDATE()
FROM dbo.Celle c
INNER JOIN @TargetCelle t ON t.IDCella = c.ID;
UPDATE dbo.PyPickingListReservation
SET Documento = NULL,
IDOperatore = @IDOperatore,
ModUtente = @Nominativo,
ModDataOra = GETDATE()
WHERE ID = 1;
RETURN;
END;
END;
GO
CREATE OR ALTER PROCEDURE [dbo].[py_sp_xExePackingListPalletPrenota]
@IDOperatore int,
@Documento varchar(8),
@RC int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET @RC = 0;
DECLARE @Nominativo varchar(50) = '';
SELECT @Nominativo = LOGIN
FROM dbo.Operatori
WHERE ID = @IDOperatore;
IF @Nominativo IS NULL
SET @Nominativo = 'SYSTEM';
UPDATE c
SET c.IDStato = 1,
c.ModUtente = @Nominativo,
c.ModDataOra = GETDATE()
FROM dbo.Celle c
WHERE c.ID IN (
SELECT DISTINCT Cella
FROM dbo.py_ViewPackingListRestante
WHERE CAST(Documento AS varchar(8)) = @Documento
AND Cella IS NOT NULL
);
END;
GO
CREATE OR ALTER PROCEDURE [dbo].[py_sp_ControllaPrenotazionePackingListPalletNew]
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Documento varchar(8) = NULL;
DECLARE @IDOperatore int = 0;
DECLARE @Nominativo varchar(50) = 'SYSTEM';
DECLARE @RC int = 0;
SELECT
@Documento = NULLIF(LTRIM(RTRIM(Documento)), ''),
@IDOperatore = ISNULL(IDOperatore, 0),
@Nominativo = ISNULL(NULLIF(LTRIM(RTRIM(ModUtente)), ''), 'SYSTEM')
FROM dbo.PyPickingListReservation
WHERE ID = 1;
IF ISNULL(@Documento, '') = ''
RETURN;
IF NOT EXISTS (
SELECT 1
FROM dbo.py_ViewPackingListRestante
WHERE CAST(Documento AS varchar(8)) = @Documento
)
BEGIN
UPDATE dbo.Celle
SET IDStato = 0,
ModUtente = @Nominativo,
ModDataOra = GETDATE()
WHERE ISNULL(IDStato, 0) <> 0;
UPDATE dbo.PyPickingListReservation
SET Documento = NULL,
IDOperatore = @IDOperatore,
ModUtente = @Nominativo,
ModDataOra = GETDATE()
WHERE ID = 1;
RETURN;
END;
UPDATE dbo.Celle
SET IDStato = 0,
ModUtente = @Nominativo,
ModDataOra = GETDATE()
WHERE ISNULL(IDStato, 0) <> 0;
IF @IDOperatore <= 0
BEGIN
SELECT TOP 1 @IDOperatore = ID
FROM dbo.Operatori
WHERE LOGIN = @Nominativo;
END;
EXEC dbo.py_sp_xExePackingListPalletPrenota
@IDOperatore = @IDOperatore,
@Documento = @Documento,
@RC = @RC OUTPUT;
END;
GO
/* ============================================================
4. Viste storico picking list ramo Python
============================================================ */
CREATE OR ALTER VIEW [dbo].[py_vPreparaPackingListSAMA1]
AS
SELECT
SAMA1.dbo.LOTSER.NUMLOT,
SAMA1.dbo.ARTICO.CODICE,
SAMA1.dbo.FATRIG.DESCR,
LEFT(SAMA1.dbo.LOTSER.NUMSER, 6) AS UDC,
SUM(SAMA1.dbo.LOTSER.QTTGIAI) AS Qta,
SAMA1.dbo.BAMTES.NUMDOC,
SAMA1.dbo.BAMTES.DATDOC,
SAMA1.dbo.BAMTES.ID,
SAMA1.dbo.BAMTES.DESCRDEST,
SAMA1.dbo.BAMTES.STATO AS StatoDocumento,
SAMA1.dbo.NAZIONI.CODICE AS Expr1,
SAMA1.dbo.MTRASP.CODICE + ' ' + SAMA1.dbo.NAZIONI.DESCR AS NAZIONE,
SAMA1.dbo.BAMTES.IDMTRASP
FROM SAMA1.dbo.BAMTES
LEFT OUTER JOIN SAMA1.dbo.NAZIONI
ON SAMA1.dbo.NAZIONI.ID = SAMA1.dbo.BAMTES.IDNAZDEST
RIGHT OUTER JOIN SAMA1.dbo.LOTTIBF
LEFT OUTER JOIN SAMA1.dbo.LOTSER
ON SAMA1.dbo.LOTTIBF.IDLOTSER = SAMA1.dbo.LOTSER.ID
LEFT OUTER JOIN SAMA1.dbo.ARTICO
ON SAMA1.dbo.LOTSER.IDARTICO = SAMA1.dbo.ARTICO.ID
LEFT OUTER JOIN SAMA1.dbo.FATRIG
ON SAMA1.dbo.LOTTIBF.IDFATRIG = SAMA1.dbo.FATRIG.ID
ON SAMA1.dbo.BAMTES.ID = SAMA1.dbo.FATRIG.IDBAM
LEFT OUTER JOIN SAMA1.sam.EXTUC
ON LEFT(SAMA1.dbo.LOTSER.NUMSER, 6) = SAMA1.sam.EXTUC.CODICE
LEFT OUTER JOIN SAMA1.dbo.MTRASP
ON SAMA1.dbo.BAMTES.IDMTRASP = SAMA1.dbo.MTRASP.ID
WHERE
SAMA1.dbo.BAMTES.ANNDOC >= YEAR(GETDATE())
AND SAMA1.dbo.BAMTES.STATO IN ('P', 'D')
AND SAMA1.dbo.LOTSER.NUMLOT <> '00000000000'
GROUP BY
SAMA1.dbo.LOTSER.NUMLOT,
SAMA1.dbo.ARTICO.CODICE,
SAMA1.dbo.FATRIG.DESCR,
LEFT(SAMA1.dbo.LOTSER.NUMSER, 6),
SAMA1.dbo.BAMTES.NUMDOC,
SAMA1.dbo.BAMTES.DATDOC,
SAMA1.dbo.BAMTES.ID,
SAMA1.dbo.BAMTES.DESCRDEST,
SAMA1.dbo.BAMTES.STATO,
SAMA1.dbo.NAZIONI.CODICE,
SAMA1.dbo.NAZIONI.DESCR,
SAMA1.dbo.BAMTES.IDMTRASP,
SAMA1.dbo.MTRASP.CODICE;
GO
CREATE OR ALTER VIEW [dbo].[py_vPreparaPackingList]
AS
SELECT
NUMLOT,
CODICE,
DESCR,
UDC,
Qta,
NUMDOC,
DATDOC,
ID,
DESCRDEST,
StatoDocumento,
Expr1,
NAZIONE
FROM dbo.py_vPreparaPackingListSAMA1
WHERE NUMLOT <> '';
GO
CREATE OR ALTER VIEW [dbo].[py_XMag_ViewPackingListStorico]
AS
SELECT TOP (100000)
prep.UDC AS Pallet,
prep.NUMLOT AS Lotto,
prep.CODICE AS Articolo,
prep.DESCR AS Descrizione,
prep.Qta,
prep.NUMDOC AS Documento,
prep.DATDOC AS DataDocumento,
prep.StatoDocumento,
prep.Expr1 AS CodNazione,
prep.NAZIONE,
CASE
WHEN prep.Expr1 = 'DE' THEN 10
WHEN prep.Expr1 = 'TH' THEN
CASE WHEN SUBSTRING(prep.DESCRDEST, 1, 2) = 'NA' THEN 11 ELSE 13 END
WHEN prep.Expr1 = 'MEX' THEN 12
ELSE 4
END AS Stato,
ISNULL(g.NumeroPallet, 0) AS PalletCella,
ISNULL(g.IDMagazzino, 1) AS Magazzino,
ISNULL(g.IDArea, 5) AS Area,
ISNULL(g.IDCella, 1000) AS Cella,
ISNULL(c.Ordinamento, 99999) AS Ordinamento,
ISNULL(c.Corsia + ' - ' + c.Colonna + ' - ' + c.Fila, 'Non scaff.') AS Ubicazione,
SUBSTRING(prep.DESCRDEST, 1, 2) AS DEST,
CASE
WHEN MAX(CASE
WHEN pr.Documento IS NOT NULL
AND pr.Documento = CAST(prep.NUMDOC AS varchar(8))
THEN 1 ELSE 0 END) = 1
THEN 1
ELSE 0
END AS IDStato
FROM dbo.Celle c
INNER JOIN dbo.XMag_GiacenzaPallet g
ON c.ID = g.IDCella
RIGHT OUTER JOIN dbo.py_vPreparaPackingList prep
ON g.BarcodePallet COLLATE SQL_Latin1_General_CP1_CI_AS = prep.UDC
LEFT JOIN dbo.PyPickingListReservation pr
ON pr.ID = 1
AND NULLIF(LTRIM(RTRIM(pr.Documento)), '') IS NOT NULL
GROUP BY
prep.Expr1,
prep.NAZIONE,
prep.UDC,
prep.NUMDOC,
prep.DATDOC,
prep.StatoDocumento,
prep.NUMLOT,
prep.CODICE,
prep.DESCR,
prep.Qta,
g.NumeroPallet,
g.IDMagazzino,
g.IDArea,
g.IDCella,
c.Ordinamento,
c.Corsia,
c.Colonna,
c.Fila,
prep.DESCRDEST;
GO
/* ============================================================
5. Tabella salta UDC barcode picking list
============================================================ */
IF OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U') IS NULL
BEGIN
CREATE TABLE dbo.py_BarcodePickingListSkip (
ID int IDENTITY(1,1) NOT NULL CONSTRAINT PK_py_BarcodePickingListSkip PRIMARY KEY,
Documento varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
Pallet varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
IDStato int NOT NULL,
IDOperatore int NOT NULL,
DataOra datetime2(0) NOT NULL CONSTRAINT DF_py_BarcodePickingListSkip_DataOra DEFAULT SYSDATETIME(),
Motivo nvarchar(200) NULL,
Risolto bit NOT NULL CONSTRAINT DF_py_BarcodePickingListSkip_Risolto DEFAULT 0,
RisoltoDa int NULL,
RisoltoDataOra datetime2(0) NULL
);
END;
GO
IF NOT EXISTS (
SELECT 1
FROM sys.indexes
WHERE name = N'UX_py_BarcodePickingListSkip_Open'
AND object_id = OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U')
)
BEGIN
CREATE UNIQUE INDEX UX_py_BarcodePickingListSkip_Open
ON dbo.py_BarcodePickingListSkip (Documento, Pallet, IDStato)
WHERE Risolto = 0;
END;
GO
IF NOT EXISTS (
SELECT 1
FROM sys.indexes
WHERE name = N'IX_py_BarcodePickingListSkip_Queue'
AND object_id = OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U')
)
BEGIN
CREATE INDEX IX_py_BarcodePickingListSkip_Queue
ON dbo.py_BarcodePickingListSkip (IDStato, Documento, Pallet, Risolto);
END;
GO
/* ============================================================
6. Intervallo operativo 30 giorni e sequenza di prelievo
La vista di preparazione Python creata al punto 4 contiene sia P sia D.
Qui il ramo operativo viene ristretto alle sole liste P degli ultimi 30
giorni; la UI applica successivamente il valore scelto (10/15/20/30).
============================================================ */
CREATE OR ALTER VIEW dbo.py_XMag_ViewPackingList
AS
SELECT TOP (10000)
prep.UDC AS Pallet,
prep.NUMLOT AS Lotto,
prep.CODICE AS Articolo,
prep.DESCR AS Descrizione,
prep.Qta,
prep.NUMDOC AS Documento,
prep.DATDOC AS DataDocumento,
prep.Expr1 AS CodNazione,
prep.NAZIONE,
CASE
WHEN prep.Expr1 = 'DE' THEN 10
WHEN prep.Expr1 = 'TH' THEN
CASE WHEN SUBSTRING(prep.DESCRDEST, 1, 2) = 'NA' THEN 11 ELSE 13 END
WHEN prep.Expr1 = 'MEX' THEN 12
ELSE 4
END AS Stato,
ISNULL(g.NumeroPallet, 0) AS PalletCella,
ISNULL(g.IDMagazzino, 1) AS Magazzino,
ISNULL(g.IDArea, 5) AS Area,
ISNULL(g.IDCella, 1000) AS Cella,
ISNULL(c.Ordinamento, 99999) AS Ordinamento,
ISNULL(c.Corsia + ' - ' + c.Colonna + ' - ' + c.Fila, 'Non scaff.') AS Ubicazione,
SUBSTRING(prep.DESCRDEST, 1, 2) AS DEST,
CASE
WHEN MAX(CASE
WHEN pr.Documento IS NOT NULL
AND pr.Documento = CAST(prep.NUMDOC AS varchar(8))
THEN 1 ELSE 0 END) = 1
THEN 1
ELSE 0
END AS IDStato
FROM dbo.Celle AS c
INNER JOIN dbo.XMag_GiacenzaPallet AS g
ON c.ID = g.IDCella
RIGHT OUTER JOIN dbo.py_vPreparaPackingList AS prep
ON g.BarcodePallet COLLATE SQL_Latin1_General_CP1_CI_AS = prep.UDC
LEFT JOIN dbo.PyPickingListReservation AS pr
ON pr.ID = 1
AND NULLIF(LTRIM(RTRIM(pr.Documento)), '') IS NOT NULL
WHERE prep.StatoDocumento = 'P'
AND prep.DATDOC > CAST((GETDATE() - 30) AS int)
GROUP BY
prep.Expr1,
prep.NAZIONE,
prep.UDC,
prep.NUMDOC,
prep.DATDOC,
prep.NUMLOT,
prep.CODICE,
prep.DESCR,
prep.Qta,
g.NumeroPallet,
g.IDMagazzino,
g.IDArea,
g.IDCella,
c.Ordinamento,
c.Corsia,
c.Colonna,
c.Fila,
prep.DESCRDEST;
GO
CREATE OR ALTER VIEW dbo.py_ViewPackingListRestante
AS
SELECT
Pallet, Lotto, Articolo, Descrizione, Qta, Documento, DataDocumento,
CodNazione, NAZIONE, Stato, PalletCella, Magazzino, Area, Cella,
Ordinamento, Ubicazione, DEST, IDStato
FROM dbo.py_XMag_ViewPackingList
WHERE Cella <> 9999;
GO
IF OBJECT_ID(N'dbo.py_PickingListPrelievoSequenza', N'U') IS NULL
BEGIN
CREATE TABLE dbo.py_PickingListPrelievoSequenza (
ID bigint IDENTITY(1,1) NOT NULL
CONSTRAINT PK_py_PickingListPrelievoSequenza PRIMARY KEY,
Documento varchar(50) NOT NULL,
GruppoChiave varchar(160) NOT NULL,
GruppoEtichetta varchar(100) NOT NULL,
Ordine int NOT NULL,
InsUtente varchar(50) NULL,
InsDataOra datetime2(0) NOT NULL
CONSTRAINT DF_py_PickingListPrelievoSequenza_InsDataOra DEFAULT SYSDATETIME(),
ModUtente varchar(50) NULL,
ModDataOra datetime2(0) NULL,
DelUtente varchar(50) NULL,
DelDataOra datetime2(0) NULL,
CONSTRAINT CK_py_PickingListPrelievoSequenza_Ordine CHECK (Ordine >= 0)
);
END;
GO
IF NOT EXISTS (
SELECT 1 FROM sys.indexes
WHERE object_id = OBJECT_ID(N'dbo.py_PickingListPrelievoSequenza', N'U')
AND name = N'UX_py_PickingListPrelievoSequenza_DocGruppo'
)
BEGIN
CREATE UNIQUE INDEX UX_py_PickingListPrelievoSequenza_DocGruppo
ON dbo.py_PickingListPrelievoSequenza (Documento, GruppoChiave)
WHERE DelDataOra IS NULL;
END;
GO
IF NOT EXISTS (
SELECT 1 FROM sys.indexes
WHERE object_id = OBJECT_ID(N'dbo.py_PickingListPrelievoSequenza', N'U')
AND name = N'UX_py_PickingListPrelievoSequenza_DocOrdine'
)
BEGIN
CREATE UNIQUE INDEX UX_py_PickingListPrelievoSequenza_DocOrdine
ON dbo.py_PickingListPrelievoSequenza (Documento, Ordine)
WHERE DelDataOra IS NULL;
END;
GO
CREATE OR ALTER VIEW dbo.py_ViewPackingListPrelievo
AS
WITH Gruppi AS (
SELECT
pl.*,
CASE
WHEN pl.Cella = 1000 THEN 'NON_SCAFF'
ELSE CONCAT(
'M:', pl.Magazzino, '|A:', pl.Area, '|C:',
LTRIM(RTRIM(CASE
WHEN CHARINDEX(' - ', pl.Ubicazione) > 0
THEN LEFT(pl.Ubicazione, CHARINDEX(' - ', pl.Ubicazione) - 1)
ELSE pl.Ubicazione
END))
)
END AS GruppoPrelievoChiave,
CASE
WHEN pl.Cella = 1000 THEN 'Non scaff.'
ELSE LTRIM(RTRIM(CASE
WHEN CHARINDEX(' - ', pl.Ubicazione) > 0
THEN LEFT(pl.Ubicazione, CHARINDEX(' - ', pl.Ubicazione) - 1)
ELSE pl.Ubicazione
END))
END AS GruppoPrelievo,
CASE
WHEN pl.Cella = 1000 THEN 0
ELSE 1000 + ISNULL(pl.Ordinamento, 99999)
END AS OrdineGruppoDefault
FROM dbo.py_ViewPackingListRestante AS pl
), Sequenza AS (
SELECT
g.*,
s.Ordine AS OrdineGruppoConfigurato,
CASE WHEN EXISTS (
SELECT 1
FROM dbo.py_PickingListPrelievoSequenza AS any_s
WHERE any_s.Documento COLLATE Latin1_General_CI_AS =
CAST(g.Documento AS varchar(50)) COLLATE Latin1_General_CI_AS
AND any_s.DelDataOra IS NULL
) THEN 1 ELSE 0 END AS HaSequenzaPersonalizzata
FROM Gruppi AS g
LEFT JOIN dbo.py_PickingListPrelievoSequenza AS s
ON s.Documento COLLATE Latin1_General_CI_AS =
CAST(g.Documento AS varchar(50)) COLLATE Latin1_General_CI_AS
AND s.GruppoChiave COLLATE Latin1_General_CI_AS =
g.GruppoPrelievoChiave COLLATE Latin1_General_CI_AS
AND s.DelDataOra IS NULL
)
SELECT
Sequenza.*,
CASE
WHEN OrdineGruppoConfigurato IS NOT NULL THEN OrdineGruppoConfigurato
WHEN HaSequenzaPersonalizzata = 1 THEN 100000 + OrdineGruppoDefault
ELSE OrdineGruppoDefault
END AS OrdinePrelievoGruppo
FROM Sequenza;
GO
PRINT 'Patch cumulativa Python WMS completata.';
GO

View File

@@ -0,0 +1,190 @@
/*
Patch: intervallo giorni selezionabile in Gestione Picking List Python
Scopo:
- permettere alla UI Python di caricare picking list operative degli ultimi
10, 15, 20 o 30 giorni;
- mantenere 10 giorni come default applicativo;
- non escludere documenti validi con nazione di destinazione non valorizzata;
- non modificare gli oggetti legacy usati dal programma C#.
Oggetti modificati:
- dbo.py_XMag_ViewPackingList
- dbo.py_ViewPackingListRestante
Nota:
La vista legacy dbo.XMag_ViewPackingList dipende da dbo.vPreparaPackingListSAMA1,
che contiene il filtro fisso GETDATE()-10. Per questo la vista Python viene
ricalcolata direttamente dalle tabelle SAM con un orizzonte massimo di 30 giorni.
La UI applica poi il filtro effettivo scelto dall'operatore.
Il collegamento a NAZIONI e' intenzionalmente LEFT OUTER JOIN: un indirizzo
alternativo incompleto non deve rendere invisibile l'intera picking list.
*/
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER VIEW [dbo].[py_XMag_ViewPackingList]
AS
WITH PreparaPackingList AS (
SELECT
SAMA1.dbo.LOTSER.NUMLOT,
SAMA1.dbo.ARTICO.CODICE,
SAMA1.dbo.FATRIG.DESCR,
LEFT(SAMA1.dbo.LOTSER.NUMSER, 6) AS UDC,
SUM(SAMA1.dbo.LOTSER.QTTGIAI) AS Qta,
SAMA1.dbo.BAMTES.NUMDOC,
SAMA1.dbo.BAMTES.DATDOC,
SAMA1.dbo.BAMTES.ID,
SAMA1.dbo.BAMTES.DESCRDEST,
SAMA1.dbo.NAZIONI.CODICE AS Expr1,
SAMA1.dbo.MTRASP.CODICE + ' ' + SAMA1.dbo.NAZIONI.DESCR AS NAZIONE,
SAMA1.dbo.BAMTES.IDMTRASP
FROM SAMA1.dbo.BAMTES
LEFT OUTER JOIN SAMA1.dbo.NAZIONI
ON SAMA1.dbo.NAZIONI.ID = SAMA1.dbo.BAMTES.IDNAZDEST
RIGHT OUTER JOIN SAMA1.dbo.LOTTIBF
LEFT OUTER JOIN SAMA1.dbo.LOTSER
ON SAMA1.dbo.LOTTIBF.IDLOTSER = SAMA1.dbo.LOTSER.ID
LEFT OUTER JOIN SAMA1.dbo.ARTICO
ON SAMA1.dbo.LOTSER.IDARTICO = SAMA1.dbo.ARTICO.ID
LEFT OUTER JOIN SAMA1.dbo.FATRIG
ON SAMA1.dbo.LOTTIBF.IDFATRIG = SAMA1.dbo.FATRIG.ID
ON SAMA1.dbo.BAMTES.ID = SAMA1.dbo.FATRIG.IDBAM
LEFT OUTER JOIN SAMA1.sam.EXTUC
ON LEFT(SAMA1.dbo.LOTSER.NUMSER, 6) = SAMA1.sam.EXTUC.CODICE
LEFT OUTER JOIN SAMA1.dbo.MTRASP
ON SAMA1.dbo.BAMTES.IDMTRASP = SAMA1.dbo.MTRASP.ID
WHERE SAMA1.dbo.BAMTES.ANNDOC >= YEAR(GETDATE())
AND SAMA1.dbo.BAMTES.STATO = 'P'
AND SAMA1.dbo.BAMTES.DATDOC > CAST((GETDATE() - 30) AS int)
AND SAMA1.dbo.LOTSER.NUMLOT <> '00000000000'
GROUP BY
SAMA1.dbo.LOTSER.NUMLOT,
SAMA1.dbo.ARTICO.CODICE,
SAMA1.dbo.FATRIG.DESCR,
LEFT(SAMA1.dbo.LOTSER.NUMSER, 6),
SAMA1.dbo.BAMTES.NUMDOC,
SAMA1.dbo.BAMTES.DATDOC,
SAMA1.dbo.BAMTES.ID,
SAMA1.dbo.BAMTES.DESCRDEST,
SAMA1.dbo.NAZIONI.CODICE,
SAMA1.dbo.NAZIONI.DESCR,
SAMA1.dbo.BAMTES.IDMTRASP,
SAMA1.dbo.MTRASP.CODICE
),
Base AS (
SELECT
prep.UDC AS Pallet,
prep.NUMLOT AS Lotto,
prep.CODICE AS Articolo,
prep.DESCR AS Descrizione,
prep.Qta,
prep.NUMDOC AS Documento,
prep.DATDOC AS DataDocumento,
prep.Expr1 AS CodNazione,
prep.NAZIONE,
CASE
WHEN prep.Expr1 = 'DE' THEN 10
WHEN prep.Expr1 = 'TH' THEN CASE WHEN SUBSTRING(prep.DESCRDEST, 1, 2) = 'NA' THEN 11 ELSE 13 END
WHEN prep.Expr1 = 'MEX' THEN 12
ELSE 4
END AS Stato,
ISNULL(g.NumeroPallet, 0) AS PalletCella,
ISNULL(g.IDMagazzino, 1) AS Magazzino,
ISNULL(g.IDArea, 5) AS Area,
ISNULL(g.IDCella, 1000) AS Cella,
ISNULL(c.Ordinamento, 99999) AS Ordinamento,
ISNULL(c.Corsia + ' - ' + c.Colonna + ' - ' + c.Fila, 'Non scaff.') AS Ubicazione,
SUBSTRING(prep.DESCRDEST, 1, 2) AS DEST
FROM dbo.Celle AS c
INNER JOIN dbo.XMag_GiacenzaPallet AS g
ON c.ID = g.IDCella
RIGHT OUTER JOIN PreparaPackingList AS prep
ON g.BarcodePallet COLLATE SQL_Latin1_General_CP1_CI_AS = prep.UDC
WHERE prep.NUMLOT <> ''
GROUP BY
prep.Expr1,
prep.NAZIONE,
prep.UDC,
prep.NUMDOC,
prep.DATDOC,
prep.NUMLOT,
prep.CODICE,
prep.DESCR,
prep.Qta,
g.NumeroPallet,
g.IDMagazzino,
g.IDArea,
g.IDCella,
c.Ordinamento,
c.Corsia,
c.Colonna,
c.Fila,
prep.DESCRDEST
)
SELECT TOP 10000
Base.Pallet,
Base.Lotto,
Base.Articolo,
Base.Descrizione,
Base.Qta,
Base.Documento,
Base.DataDocumento,
Base.CodNazione,
Base.NAZIONE,
Base.Stato,
Base.PalletCella,
Base.Magazzino,
Base.Area,
Base.Cella,
Base.Ordinamento,
Base.Ubicazione,
Base.DEST,
CASE
WHEN pr.Documento IS NOT NULL
AND pr.Documento = CAST(Base.Documento AS varchar(8))
THEN 1
ELSE 0
END AS IDStato
FROM Base
LEFT JOIN dbo.PyPickingListReservation AS pr
ON pr.ID = 1
AND NULLIF(LTRIM(RTRIM(pr.Documento)), '') IS NOT NULL
ORDER BY
CASE
WHEN pr.Documento IS NOT NULL
AND pr.Documento = CAST(Base.Documento AS varchar(8))
THEN 1
ELSE 0
END DESC,
Base.Documento,
Base.Ordinamento;
GO
CREATE OR ALTER VIEW [dbo].[py_ViewPackingListRestante]
AS
SELECT
Pallet,
Lotto,
Articolo,
Descrizione,
Qta,
Documento,
DataDocumento,
CodNazione,
NAZIONE,
Stato,
PalletCella,
Magazzino,
Area,
Cella,
Ordinamento,
Ubicazione,
DEST,
IDStato
FROM dbo.py_XMag_ViewPackingList
WHERE Cella <> 9999;
GO

View File

@@ -0,0 +1,217 @@
/*
Patch Python WMS: picking list con nazione di destinazione non valorizzata
Problema risolto:
- una testata BAMTES valida puo' avere IDNAZDEST NULL, in particolare quando
viene scelto un indirizzo di destinazione alternativo privo di nazione;
- l'INNER JOIN a SAMA1.dbo.NAZIONI eliminava l'intero documento;
- la picking list non compariva quindi in Gestione Picking List ne' nello
storico Python, anche se stato, data, righe, lotti e UDC erano validi.
Strategia:
- il collegamento BAMTES -> NAZIONI diventa LEFT OUTER JOIN;
- non viene inventato alcun codice nazione: Expr1 e NAZIONE restano NULL;
- il CASE gia' esistente assegna in questo caso lo Stato generico 4;
- nessun oggetto legacy usato dal programma C# viene modificato.
Oggetti Python modificati:
- dbo.py_vPreparaPackingListSAMA1 (storico e base condivisa);
- dbo.py_XMag_ViewPackingList (gestione operativa).
*/
SET XACT_ABORT ON;
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER VIEW dbo.py_vPreparaPackingListSAMA1
AS
SELECT
ls.NUMLOT,
a.CODICE,
fr.DESCR,
LEFT(ls.NUMSER, 6) AS UDC,
SUM(ls.QTTGIAI) AS Qta,
bt.NUMDOC,
bt.DATDOC,
bt.ID,
bt.DESCRDEST,
bt.STATO AS StatoDocumento,
n.CODICE AS Expr1,
mt.CODICE + ' ' + n.DESCR AS NAZIONE,
bt.IDMTRASP
FROM SAMA1.dbo.BAMTES AS bt
INNER JOIN SAMA1.dbo.FATRIG AS fr
ON fr.IDBAM = bt.ID
INNER JOIN SAMA1.dbo.LOTTIBF AS lb
ON lb.IDFATRIG = fr.ID
INNER JOIN SAMA1.dbo.LOTSER AS ls
ON ls.ID = lb.IDLOTSER
LEFT OUTER JOIN SAMA1.dbo.ARTICO AS a
ON a.ID = ls.IDARTICO
LEFT OUTER JOIN SAMA1.sam.EXTUC AS uc
ON uc.CODICE = LEFT(ls.NUMSER, 6)
LEFT OUTER JOIN SAMA1.dbo.MTRASP AS mt
ON mt.ID = bt.IDMTRASP
LEFT OUTER JOIN SAMA1.dbo.NAZIONI AS n
ON n.ID = bt.IDNAZDEST
WHERE bt.ANNDOC >= YEAR(GETDATE())
AND bt.STATO IN ('P', 'D')
AND ls.NUMLOT <> '00000000000'
GROUP BY
ls.NUMLOT,
a.CODICE,
fr.DESCR,
LEFT(ls.NUMSER, 6),
bt.NUMDOC,
bt.DATDOC,
bt.ID,
bt.DESCRDEST,
bt.STATO,
n.CODICE,
n.DESCR,
bt.IDMTRASP,
mt.CODICE;
GO
CREATE OR ALTER VIEW dbo.py_XMag_ViewPackingList
AS
WITH PreparaPackingList AS (
SELECT
ls.NUMLOT,
a.CODICE,
fr.DESCR,
LEFT(ls.NUMSER, 6) AS UDC,
SUM(ls.QTTGIAI) AS Qta,
bt.NUMDOC,
bt.DATDOC,
bt.ID,
bt.DESCRDEST,
n.CODICE AS Expr1,
mt.CODICE + ' ' + n.DESCR AS NAZIONE,
bt.IDMTRASP
FROM SAMA1.dbo.BAMTES AS bt
INNER JOIN SAMA1.dbo.FATRIG AS fr
ON fr.IDBAM = bt.ID
INNER JOIN SAMA1.dbo.LOTTIBF AS lb
ON lb.IDFATRIG = fr.ID
INNER JOIN SAMA1.dbo.LOTSER AS ls
ON ls.ID = lb.IDLOTSER
LEFT OUTER JOIN SAMA1.dbo.ARTICO AS a
ON a.ID = ls.IDARTICO
LEFT OUTER JOIN SAMA1.sam.EXTUC AS uc
ON uc.CODICE = LEFT(ls.NUMSER, 6)
LEFT OUTER JOIN SAMA1.dbo.MTRASP AS mt
ON mt.ID = bt.IDMTRASP
LEFT OUTER JOIN SAMA1.dbo.NAZIONI AS n
ON n.ID = bt.IDNAZDEST
WHERE bt.ANNDOC >= YEAR(GETDATE())
AND bt.STATO = 'P'
AND bt.DATDOC > CAST((GETDATE() - 30) AS int)
AND ls.NUMLOT <> '00000000000'
GROUP BY
ls.NUMLOT,
a.CODICE,
fr.DESCR,
LEFT(ls.NUMSER, 6),
bt.NUMDOC,
bt.DATDOC,
bt.ID,
bt.DESCRDEST,
n.CODICE,
n.DESCR,
bt.IDMTRASP,
mt.CODICE
),
Base AS (
SELECT
prep.UDC AS Pallet,
prep.NUMLOT AS Lotto,
prep.CODICE AS Articolo,
prep.DESCR AS Descrizione,
prep.Qta,
prep.NUMDOC AS Documento,
prep.DATDOC AS DataDocumento,
prep.Expr1 AS CodNazione,
prep.NAZIONE,
CASE
WHEN prep.Expr1 = 'DE' THEN 10
WHEN prep.Expr1 = 'TH' THEN
CASE WHEN SUBSTRING(prep.DESCRDEST, 1, 2) = 'NA' THEN 11 ELSE 13 END
WHEN prep.Expr1 = 'MEX' THEN 12
ELSE 4
END AS Stato,
ISNULL(g.NumeroPallet, 0) AS PalletCella,
ISNULL(g.IDMagazzino, 1) AS Magazzino,
ISNULL(g.IDArea, 5) AS Area,
ISNULL(g.IDCella, 1000) AS Cella,
ISNULL(c.Ordinamento, 99999) AS Ordinamento,
ISNULL(c.Corsia + ' - ' + c.Colonna + ' - ' + c.Fila, 'Non scaff.') AS Ubicazione,
SUBSTRING(prep.DESCRDEST, 1, 2) AS DEST
FROM dbo.Celle AS c
INNER JOIN dbo.XMag_GiacenzaPallet AS g
ON c.ID = g.IDCella
RIGHT OUTER JOIN PreparaPackingList AS prep
ON g.BarcodePallet COLLATE SQL_Latin1_General_CP1_CI_AS = prep.UDC
WHERE prep.NUMLOT <> ''
GROUP BY
prep.Expr1,
prep.NAZIONE,
prep.UDC,
prep.NUMDOC,
prep.DATDOC,
prep.NUMLOT,
prep.CODICE,
prep.DESCR,
prep.Qta,
g.NumeroPallet,
g.IDMagazzino,
g.IDArea,
g.IDCella,
c.Ordinamento,
c.Corsia,
c.Colonna,
c.Fila,
prep.DESCRDEST
)
SELECT TOP (10000)
Base.Pallet,
Base.Lotto,
Base.Articolo,
Base.Descrizione,
Base.Qta,
Base.Documento,
Base.DataDocumento,
Base.CodNazione,
Base.NAZIONE,
Base.Stato,
Base.PalletCella,
Base.Magazzino,
Base.Area,
Base.Cella,
Base.Ordinamento,
Base.Ubicazione,
Base.DEST,
CASE
WHEN pr.Documento IS NOT NULL
AND pr.Documento = CAST(Base.Documento AS varchar(8))
THEN 1
ELSE 0
END AS IDStato
FROM Base
LEFT JOIN dbo.PyPickingListReservation AS pr
ON pr.ID = 1
AND NULLIF(LTRIM(RTRIM(pr.Documento)), '') IS NOT NULL
ORDER BY
CASE
WHEN pr.Documento IS NOT NULL
AND pr.Documento = CAST(Base.Documento AS varchar(8))
THEN 1
ELSE 0
END DESC,
Base.Documento,
Base.Ordinamento;
GO
PRINT 'Patch nazione destinazione opzionale applicata alle viste Python.';
GO

View File

@@ -0,0 +1,136 @@
/*
Patch Python WMS: ordine di prelievo per singola picking list
Prerequisito:
- eseguire prima apply_pickinglist_days_filter_patch.sql, che espone
DataDocumento nelle viste operative Python.
Effetti:
- crea una tabella Python-only con la sequenza personalizzata per Documento;
- crea una vista Python-only con l'ordine effettivo condiviso da backoffice e barcode;
- senza configurazione applica il default: Non scaff. prima degli scaffali;
- con configurazione applica i gruppi scelti e accoda in modo sicuro quelli mancanti;
- non modifica tabelle, viste o stored procedure legacy usate dal programma C#.
*/
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
IF OBJECT_ID(N'dbo.py_PickingListPrelievoSequenza', N'U') IS NULL
BEGIN
CREATE TABLE dbo.py_PickingListPrelievoSequenza (
ID bigint IDENTITY(1,1) NOT NULL
CONSTRAINT PK_py_PickingListPrelievoSequenza PRIMARY KEY,
Documento varchar(50) NOT NULL,
GruppoChiave varchar(160) NOT NULL,
GruppoEtichetta varchar(100) NOT NULL,
Ordine int NOT NULL,
InsUtente varchar(50) NULL,
InsDataOra datetime2(0) NOT NULL
CONSTRAINT DF_py_PickingListPrelievoSequenza_InsDataOra DEFAULT SYSDATETIME(),
ModUtente varchar(50) NULL,
ModDataOra datetime2(0) NULL,
DelUtente varchar(50) NULL,
DelDataOra datetime2(0) NULL,
CONSTRAINT CK_py_PickingListPrelievoSequenza_Ordine CHECK (Ordine >= 0)
);
END
GO
IF NOT EXISTS (
SELECT 1
FROM sys.indexes
WHERE object_id = OBJECT_ID(N'dbo.py_PickingListPrelievoSequenza', N'U')
AND name = N'UX_py_PickingListPrelievoSequenza_DocGruppo'
)
BEGIN
CREATE UNIQUE INDEX UX_py_PickingListPrelievoSequenza_DocGruppo
ON dbo.py_PickingListPrelievoSequenza (Documento, GruppoChiave)
WHERE DelDataOra IS NULL;
END
GO
IF NOT EXISTS (
SELECT 1
FROM sys.indexes
WHERE object_id = OBJECT_ID(N'dbo.py_PickingListPrelievoSequenza', N'U')
AND name = N'UX_py_PickingListPrelievoSequenza_DocOrdine'
)
BEGIN
CREATE UNIQUE INDEX UX_py_PickingListPrelievoSequenza_DocOrdine
ON dbo.py_PickingListPrelievoSequenza (Documento, Ordine)
WHERE DelDataOra IS NULL;
END
GO
CREATE OR ALTER VIEW dbo.py_ViewPackingListPrelievo
AS
WITH Gruppi AS (
SELECT
pl.*,
CASE
WHEN pl.Cella = 1000 THEN 'NON_SCAFF'
ELSE CONCAT(
'M:', pl.Magazzino,
'|A:', pl.Area,
'|C:',
LTRIM(RTRIM(
CASE
WHEN CHARINDEX(' - ', pl.Ubicazione) > 0
THEN LEFT(pl.Ubicazione, CHARINDEX(' - ', pl.Ubicazione) - 1)
ELSE pl.Ubicazione
END
))
)
END AS GruppoPrelievoChiave,
CASE
WHEN pl.Cella = 1000 THEN 'Non scaff.'
ELSE LTRIM(RTRIM(
CASE
WHEN CHARINDEX(' - ', pl.Ubicazione) > 0
THEN LEFT(pl.Ubicazione, CHARINDEX(' - ', pl.Ubicazione) - 1)
ELSE pl.Ubicazione
END
))
END AS GruppoPrelievo,
CASE
WHEN pl.Cella = 1000 THEN 0
ELSE 1000 + ISNULL(pl.Ordinamento, 99999)
END AS OrdineGruppoDefault
FROM dbo.py_ViewPackingListRestante AS pl
), Sequenza AS (
SELECT
g.*,
s.Ordine AS OrdineGruppoConfigurato,
CASE
WHEN EXISTS (
SELECT 1
FROM dbo.py_PickingListPrelievoSequenza AS any_s
WHERE any_s.Documento COLLATE Latin1_General_CI_AS =
CAST(g.Documento AS varchar(50)) COLLATE Latin1_General_CI_AS
AND any_s.DelDataOra IS NULL
) THEN 1
ELSE 0
END AS HaSequenzaPersonalizzata
FROM Gruppi AS g
LEFT JOIN dbo.py_PickingListPrelievoSequenza AS s
ON s.Documento COLLATE Latin1_General_CI_AS =
CAST(g.Documento AS varchar(50)) COLLATE Latin1_General_CI_AS
AND s.GruppoChiave COLLATE Latin1_General_CI_AS =
g.GruppoPrelievoChiave COLLATE Latin1_General_CI_AS
AND s.DelDataOra IS NULL
)
SELECT
Sequenza.*,
CASE
WHEN OrdineGruppoConfigurato IS NOT NULL THEN OrdineGruppoConfigurato
WHEN HaSequenzaPersonalizzata = 1 THEN 100000 + OrdineGruppoDefault
ELSE OrdineGruppoDefault
END AS OrdinePrelievoGruppo
FROM Sequenza;
GO
PRINT 'Patch sequenza prelievo Python applicata.';
GO

View File

@@ -9,6 +9,10 @@ import asyncio
import threading
import contextlib
from version_info import module_version
__version__ = module_version(__name__)
class _LoopHolder:
"""Store the global loop instance and its worker thread."""

View File

@@ -10,14 +10,74 @@ cross-loop errors.
from __future__ import annotations
import asyncio
import inspect
import json
import logging
import os
import time
import urllib.parse
from pathlib import Path
from typing import Any, Dict, Optional
from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.pool import NullPool
from version_info import module_version
__version__ = module_version(__name__)
QUERY_PROFILER_LOG = Path(__file__).with_name("warehouse_query_profiler.log")
QUERY_PROFILER_CONFIG_PATH = Path(__file__).with_name("db_connection.json")
def _load_query_profiler_config() -> dict[str, Any]:
"""Read profiler settings from db_connection.json, with env overrides."""
config: dict[str, Any] = {
"enabled": False,
"slow_ms": 0,
"sql_limit": 4000,
}
try:
data = json.loads(QUERY_PROFILER_CONFIG_PATH.read_text(encoding="utf-8"))
section = data.get("query_profiler") if isinstance(data, dict) else None
if isinstance(section, dict):
config.update(section)
except Exception:
pass
if "WAREHOUSE_QUERY_PROFILER" in os.environ:
config["enabled"] = os.environ.get("WAREHOUSE_QUERY_PROFILER", "1").strip().lower() not in {
"0",
"false",
"no",
"off",
}
if "WAREHOUSE_QUERY_PROFILER_SLOW_MS" in os.environ:
config["slow_ms"] = os.environ.get("WAREHOUSE_QUERY_PROFILER_SLOW_MS", "0")
if "WAREHOUSE_QUERY_PROFILER_SQL_LIMIT" in os.environ:
config["sql_limit"] = os.environ.get("WAREHOUSE_QUERY_PROFILER_SQL_LIMIT", "4000")
return config
def _query_profiler_enabled() -> bool:
value = _load_query_profiler_config().get("enabled", False)
if isinstance(value, str):
return value.strip().lower() not in {"0", "false", "no", "off"}
return bool(value)
def _query_profiler_slow_ms() -> float:
try:
return float(_load_query_profiler_config().get("slow_ms", 0) or 0)
except Exception:
return 0.0
def _query_profiler_sql_limit() -> int:
try:
return int(_load_query_profiler_config().get("sql_limit", 4000) or 4000)
except Exception:
return 4000
try:
import pyodbc
@@ -73,6 +133,83 @@ def make_mssql_dsn(
return f"mssql+aioodbc:///?odbc_connect={urllib.parse.quote_plus(odbc)}"
def _compact_sql(sql: str, *, limit: int | None = None) -> str:
"""Collapse SQL whitespace so profiler entries stay readable."""
if limit is None:
limit = _query_profiler_sql_limit()
text_value = " ".join(str(sql or "").split())
if limit > 0 and len(text_value) > limit:
return text_value[:limit] + "...<truncated>"
return text_value
def _profile_params(params: Optional[Dict[str, Any]]) -> str:
"""Serialize SQL parameters for diagnostics."""
if not params:
return "{}"
try:
return _dumps(params)
except Exception:
return repr(params)
def _query_caller() -> str:
"""Return the first external Python frame that triggered the DB call."""
current_file = Path(__file__).resolve()
for frame in inspect.stack(context=0)[2:]:
try:
frame_file = Path(frame.filename).resolve()
except Exception:
continue
if frame_file == current_file:
continue
return f"{frame_file.name}:{frame.lineno}:{frame.function}"
return "unknown"
def _append_query_profile(
*,
method: str,
elapsed_ms: float,
rows: int | None,
rowcount: int | None,
commit: bool,
ok: bool,
sql: str,
params: Optional[Dict[str, Any]],
caller: str,
error: str = "",
) -> None:
"""Append one query timing line to the local profiler log."""
if not _query_profiler_enabled():
return
slow_ms = _query_profiler_slow_ms()
if ok and slow_ms > 0 and elapsed_ms < slow_ms:
return
try:
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
row_info = f"rows={rows}" if rows is not None else f"rowcount={rowcount}"
lines = [
(
f"{timestamp} | {elapsed_ms:.3f} ms | {method} | "
f"{row_info} | commit={int(commit)} | ok={int(ok)} | caller={caller}"
),
f"PARAMS: {_profile_params(params)}",
f"SQL: {_compact_sql(sql)}",
]
if error:
lines.append(f"ERROR: {error}")
with QUERY_PROFILER_LOG.open("a", encoding="utf-8") as handle:
handle.write("\n".join(lines) + "\n---\n")
except Exception:
# Profiling must never interfere with warehouse operations.
pass
class AsyncMSSQLClient:
"""Thin async query client for SQL Server.
@@ -149,23 +286,83 @@ class AsyncMSSQLClient:
"""
await self._ensure_engine()
t0 = time.perf_counter()
caller = _query_caller()
try:
async with (self._engine.begin() if commit else self._engine.connect()) as conn:
res = await conn.execute(text(sql), params or {})
rows = res.fetchall()
cols = list(res.keys())
except Exception as exc:
elapsed_ms = round((time.perf_counter() - t0) * 1000, 3)
_append_query_profile(
method="query_json",
elapsed_ms=elapsed_ms,
rows=None,
rowcount=None,
commit=commit,
ok=False,
sql=sql,
params=params,
caller=caller,
error=repr(exc),
)
raise
if as_dict_rows:
rows_out = [dict(zip(cols, row)) for row in rows]
else:
rows_out = [list(row) for row in rows]
elapsed_ms = round((time.perf_counter() - t0) * 1000, 3)
_append_query_profile(
method="query_json",
elapsed_ms=elapsed_ms,
rows=len(rows_out),
rowcount=None,
commit=commit,
ok=True,
sql=sql,
params=params,
caller=caller,
)
return {
"columns": cols,
"rows": rows_out,
"elapsed_ms": round((time.perf_counter() - t0) * 1000, 3),
"elapsed_ms": elapsed_ms,
}
async def exec(self, sql: str, params: Optional[Dict[str, Any]] = None, *, commit: bool = False) -> int:
"""Execute a DML statement and return its row count."""
await self._ensure_engine()
t0 = time.perf_counter()
caller = _query_caller()
try:
async with (self._engine.begin() if commit else self._engine.connect()) as conn:
res = await conn.execute(text(sql), params or {})
return res.rowcount or 0
rowcount = res.rowcount or 0
except Exception as exc:
elapsed_ms = round((time.perf_counter() - t0) * 1000, 3)
_append_query_profile(
method="exec",
elapsed_ms=elapsed_ms,
rows=None,
rowcount=None,
commit=commit,
ok=False,
sql=sql,
params=params,
caller=caller,
error=repr(exc),
)
raise
elapsed_ms = round((time.perf_counter() - t0) * 1000, 3)
_append_query_profile(
method="exec",
elapsed_ms=elapsed_ms,
rows=None,
rowcount=rowcount,
commit=commit,
ok=True,
sql=sql,
params=params,
caller=caller,
)
return rowcount

View File

@@ -8,7 +8,9 @@ from pathlib import Path
from typing import Any
from user_session import UserSession
from version_info import module_version
__version__ = module_version(__name__)
AUDIT_LOG_PATH = Path(__file__).with_name("warehouse_audit.log")
_LOGGER = logging.getLogger("warehouse_audit")

View File

@@ -1,3 +1,9 @@
from pathlib import Path
import os
os.chdir(Path(__file__).resolve().parent)
from runtime_support import ensure_stdio, run_with_fatal_log
ensure_stdio("warehouse_barcode")

View File

@@ -9,7 +9,7 @@ from concurrent.futures import Future
from tkinter import messagebox, ttk
from typing import Callable
from runtime_support import ensure_stdio, run_with_fatal_log
from runtime_support import configure_exception_logging, ensure_stdio, log_exception, run_with_fatal_log
ensure_stdio("warehouse_barcode")
@@ -19,18 +19,44 @@ from barcode_repository import BarcodeRepository
from barcode_service import BarcodeActionResult, BarcodeService, BarcodeViewState
from db_config import build_dsn_from_config, ensure_db_config
from login_window import prompt_login_compact
from user_session import create_user_session
from version_info import module_version, versioned_title
__version__ = module_version(__name__)
BYPASS_LOGIN = True
BYPASS_LOGIN_USER = {
"operator_id": 4,
"login": "MAG1",
"nominativo": "MAG1",
"privilegio": 3,
"codice_unita": "U1",
}
def _build_bypass_session():
"""Create the temporary MAG1 session used while field testing the barcode."""
return create_user_session(
operator_id=int(BYPASS_LOGIN_USER["operator_id"]),
login=str(BYPASS_LOGIN_USER["login"]),
nominativo=str(BYPASS_LOGIN_USER["nominativo"]),
privilegio=int(BYPASS_LOGIN_USER["privilegio"]),
codice_unita=str(BYPASS_LOGIN_USER["codice_unita"]),
)
class BarcodeClientApp:
"""Single-window Tk barcode client modeled after the C# legacy form."""
PALLET_BARCODE_LENGTH = 6
NON_SCAFFALATA_BARCODE = "9001000"
SHIPPED_BARCODE = "9000000"
BARCODE_MAX_WIDTH = 320
BARCODE_MAX_HEIGHT = 400
DESKTOP_THRESHOLD_WIDTH = 1024
DESKTOP_THRESHOLD_HEIGHT = 768
DESKTOP_WINDOW_WIDTH = 465
DESKTOP_WINDOW_HEIGHT = 531
def __init__(self, root: tk.Tk, db_client: AsyncMSSQLClient, session, loop: asyncio.AbstractEventLoop):
self.root = root
self.db_client = db_client
@@ -40,6 +66,12 @@ class BarcodeClientApp:
self.service = BarcodeService(self.repository, session.operator_id)
self._pending: Future | None = None
self._auto_advance_id: str | None = None
self._pallet_auto_focus_id: str | None = None
self._paused_queue_id: int | None = None
self._paused_priority_state: BarcodeViewState | None = None
self._pallet_user_input_serial = 0
self._priority_loaded_input_serial = 0
self._priority_expected_pallet = ""
self._status_colors = {
"red": "#f4cccc",
"green": "#d9ead3",
@@ -59,9 +91,11 @@ class BarcodeClientApp:
self._apply_state(self.service.state)
self._bind_keys()
self.root.protocol("WM_DELETE_WINDOW", self._shutdown)
self.root.after(80, self._finalize_window_placement)
self.root.after(250, self._finalize_window_placement)
def _build_ui(self) -> None:
self.root.title("WMS")
self.root.title(versioned_title("WMS", __name__))
self.root.configure(bg="#f1f1f1")
self._apply_responsive_geometry()
@@ -169,11 +203,11 @@ class BarcodeClientApp:
self.btn_f1 = ttk.Button(buttons, text="[F1] H Priority", command=lambda: self._start_queue(1))
self.btn_f1.grid(row=0, column=0, padx=(0, 4), pady=(0, button_pad_y), sticky="ew")
self.btn_submit = ttk.Button(buttons, text="[Ent] Salva", command=self._submit)
self.btn_submit = ttk.Button(buttons, text="[F3] Carica", command=self._on_f3)
self.btn_submit.grid(row=0, column=1, padx=(4, 0), pady=(0, button_pad_y), sticky="ew")
self.btn_f2 = ttk.Button(buttons, text="[F2] L Priority", command=lambda: self._start_queue(0))
self.btn_f2.grid(row=1, column=0, padx=(0, 4), sticky="ew")
self.btn_unload = ttk.Button(buttons, text="[F4] Elimina", command=self._begin_manual_unload)
self.btn_unload = ttk.Button(buttons, text="[F4] Scarica", command=self._begin_manual_unload)
self.btn_unload.grid(row=1, column=1, padx=(4, 0), sticky="ew")
self.busy_cover = tk.Frame(self.root, bg="#d9d9d9")
@@ -207,16 +241,55 @@ class BarcodeClientApp:
parent.columnconfigure(1, weight=1)
if scanned:
self.pallet_entry = entry
self.scanned_var.trace_add("write", lambda *_: self._limit_var(self.scanned_var, 8))
self.pallet_entry.bind("<KeyPress>", self._on_pallet_keypress, add="+")
self.scanned_var.trace_add("write", lambda *_: self._on_scanned_var_changed())
else:
self.destination_entry = entry
self.destination_var.trace_add("write", lambda *_: self._limit_var(self.destination_var, 8))
self.destination_var.trace_add("write", lambda *_: self._on_destination_var_changed())
def _limit_var(self, variable: tk.StringVar, max_len: int) -> None:
value = str(variable.get() or "")
if len(value) > max_len:
variable.set(value[:max_len])
def _on_pallet_keypress(self, _event=None) -> None:
self._pallet_user_input_serial += 1
def _on_scanned_var_changed(self) -> None:
self._limit_var(self.scanned_var, 8)
if self._pallet_auto_focus_id is not None:
try:
self.root.after_cancel(self._pallet_auto_focus_id)
except Exception:
pass
self._pallet_auto_focus_id = None
pallet = str(self.scanned_var.get() or "").strip()
if len(pallet) < self.PALLET_BARCODE_LENGTH:
return
self._pallet_auto_focus_id = self.root.after(80, self._auto_focus_destination_after_scan)
def _on_destination_var_changed(self) -> None:
self._limit_var(self.destination_var, 8)
self._refresh_action_labels()
def _auto_focus_destination_after_scan(self) -> None:
self._pallet_auto_focus_id = None
pallet = str(self.scanned_var.get() or "").strip()
if not pallet:
return
if self._pending is not None and not self._pending.done():
return
if getattr(self.service.state, "mode", "") == "confirm":
return
if getattr(self.service.state, "mode", "") in ("priority_high", "priority_low"):
expected = str(getattr(self.service.state, "expected_pallet", "") or "").strip()
if expected and pallet == expected and self._is_fresh_priority_scan(expected):
self._submit()
return
if bool(getattr(self.service.state, "destination_readonly", False)):
return
self._focus_destination_input()
def _apply_responsive_geometry(self) -> None:
"""Adapt the window size to barcode-sized or desktop-sized screens."""
@@ -254,10 +327,24 @@ class BarcodeClientApp:
self.root.geometry(f"{width}x{height}+{x}+{y}")
def _finalize_window_placement(self) -> None:
"""Let Windows finish frame sizing, then snap the barcode window in place."""
try:
if self._is_barcode_desktop:
self.root.state("zoomed")
else:
self.root.geometry("+0+0")
self.root.update_idletasks()
except Exception:
pass
def _bind_keys(self) -> None:
self.root.bind("<F1>", lambda _e: self._start_queue(1))
self.root.bind("<F2>", lambda _e: self._start_queue(0))
self.root.bind("<F4>", lambda _e: self._begin_manual_unload())
self.root.bind("<F3>", self._on_f3_key)
self.root.bind("<F4>", self._on_unload_key)
self.root.bind("<Escape>", self._on_escape_key)
self.pallet_entry.bind("<Return>", self._on_pallet_enter)
self.destination_entry.bind("<Return>", self._on_destination_enter)
@@ -285,6 +372,9 @@ class BarcodeClientApp:
self.busy_bar.stop()
self.busy_cover.place_forget()
def _is_priority_pause(self) -> bool:
return str(self.queue_var.get() or "") == "Pausa PL"
def _apply_state(self, state: BarcodeViewState) -> None:
if self._auto_advance_id is not None:
try:
@@ -292,16 +382,45 @@ class BarcodeClientApp:
except Exception:
pass
self._auto_advance_id = None
self.queue_var.set(state.queue_label)
if self._pallet_auto_focus_id is not None:
try:
self.root.after_cancel(self._pallet_auto_focus_id)
except Exception:
pass
self._pallet_auto_focus_id = None
pause_context = self._paused_queue_id is not None and state.mode not in ("priority_high", "priority_low")
effective_queue_label = "Pausa PL" if pause_context else state.queue_label
self.queue_var.set(effective_queue_label)
self.destination_var.set(state.destination_barcode)
self.scanned_var.set(state.scanned_pallet)
self.info1_var.set(state.status_text)
self.info1_var.set(self._status_text_with_wait_hint(state))
self.info2_var.set(state.document)
self.info3_var.set(state.customer)
self.info4_var.set(state.expected_pallet)
self.status_band.configure(bg=state.status_color or self._status_colors["red"])
destination_readonly = state.mode in ("priority_high", "priority_low", "manual_unload")
if state.mode in ("priority_high", "priority_low"):
self._priority_loaded_input_serial = self._pallet_user_input_serial
self._priority_expected_pallet = str(state.expected_pallet or "").strip()
else:
self._priority_expected_pallet = ""
try:
if str(effective_queue_label or "") != "Pausa PL":
self._paused_queue_id = None
resumable_queue = self._resumable_queue_from_state(state)
if state.mode in ("priority_high", "priority_low") or resumable_queue is not None:
self.btn_submit.configure(text="[F3] Pausa PL")
else:
self.btn_submit.configure(text="[F3] Carica")
self._refresh_action_labels(state)
queue_buttons_state = "disabled" if str(effective_queue_label or "") == "Pausa PL" else "normal"
self.btn_f1.configure(state=queue_buttons_state)
self.btn_f2.configure(state=queue_buttons_state)
except Exception:
pass
destination_readonly = False if pause_context else bool(getattr(state, "destination_readonly", False))
try:
self.destination_entry.configure(state="normal")
if destination_readonly:
@@ -309,13 +428,35 @@ class BarcodeClientApp:
except Exception:
pass
if state.mode == "confirm" and state.status_text == "Ok Scarico":
next_queue = self._queue_id_from_label(state.queue_label)
if state.mode == "confirm":
next_queue = self._resumable_queue_from_state(state)
if next_queue is not None:
self._auto_advance_id = self.root.after(1200, lambda q=next_queue: self._start_queue(q))
self._auto_advance_id = self.root.after(
int(getattr(state, "auto_advance_delay_ms", 0) or 0),
lambda q=next_queue: self._start_queue(q),
)
if bool(getattr(state, "focus_destination", False)):
self.root.after(20, self._focus_destination_input)
else:
self.root.after(20, self._focus_primary_input)
def _refresh_action_labels(self, state: BarcodeViewState | None = None) -> None:
current_state = state or self.service.state
try:
if current_state.mode in ("priority_high", "priority_low"):
self.btn_unload.configure(text="[F4] Salta UDC")
return
destination = str(self.destination_var.get() or "").strip()
if destination == self.NON_SCAFFALATA_BARCODE:
self.btn_unload.configure(text="[F4] Non scaff.")
elif destination:
self.btn_unload.configure(text="[F4] Dissocia")
else:
self.btn_unload.configure(text="[F4] Scarica")
except Exception:
pass
def _focus_primary_input(self) -> None:
try:
self.pallet_entry.focus_force()
@@ -323,6 +464,17 @@ class BarcodeClientApp:
except Exception:
pass
def _status_text_with_wait_hint(self, state: BarcodeViewState) -> str:
text = str(getattr(state, "status_text", "") or "")
delay_ms = int(getattr(state, "auto_advance_delay_ms", 0) or 0)
if delay_ms <= 0:
return text
seconds = max(1, round(delay_ms / 1000))
hint = f"Attendi {seconds} secondi..."
if hint.lower() in text.lower():
return text
return f"{text} - {hint}" if text else hint
def _focus_destination_input(self) -> None:
try:
self.destination_entry.configure(state="normal")
@@ -334,13 +486,32 @@ class BarcodeClientApp:
except Exception:
pass
def _is_fresh_priority_scan(self, expected: str) -> bool:
mode = str(getattr(self.service.state, "mode", "") or "")
if mode not in ("priority_high", "priority_low"):
return False
if str(expected or "").strip() != self._priority_expected_pallet:
return False
return self._pallet_user_input_serial > self._priority_loaded_input_serial
def _on_pallet_enter(self, _event=None) -> str:
pallet = str(self.scanned_var.get() or "").strip()
destination = str(self.destination_var.get() or "").strip()
if not pallet:
return "break"
if destination == "9000000":
if destination in (self.NON_SCAFFALATA_BARCODE, self.SHIPPED_BARCODE):
if bool(getattr(self.service.state, "destination_readonly", False)):
mode = str(getattr(self.service.state, "mode", "") or "")
if mode in ("priority_high", "priority_low"):
expected = str(getattr(self.service.state, "expected_pallet", "") or "").strip()
if expected and pallet == expected and self._is_fresh_priority_scan(expected):
self._submit()
else:
self._focus_primary_input()
else:
self._submit()
else:
self._focus_destination_input()
return "break"
self.destination_var.set("")
self._focus_destination_input()
@@ -348,20 +519,76 @@ class BarcodeClientApp:
def _on_destination_enter(self, _event=None) -> str:
pallet = str(self.scanned_var.get() or "").strip()
destination = str(self.destination_var.get() or "").strip()
if pallet and destination:
self._submit()
else:
if not pallet:
self._focus_primary_input()
else:
self.info1_var.set("F3 per associare, F4 per disassociare")
self.status_band.configure(bg=self._status_colors["yellow"])
self._focus_destination_input()
return "break"
def _on_unload_key(self, _event=None) -> str:
self._begin_manual_unload()
return "break"
def _on_escape_key(self, _event=None) -> str:
if self._is_priority_pause() and self._paused_queue_id is not None:
if self._paused_priority_state is not None:
state = self.service.resume_priority_state(self._paused_priority_state)
self._paused_priority_state = None
self._paused_queue_id = None
self._apply_state(state)
return "break"
self._start_queue(self._paused_queue_id, allow_during_pause=True)
return "break"
def _on_f3_key(self, _event=None) -> str:
self._on_f3()
return "break"
def _on_f3(self) -> None:
mode = getattr(self.service.state, "mode", "")
if mode == "priority_high":
self._paused_queue_id = 1
self._paused_priority_state = self.service.state
self._apply_state(self.service.begin_priority_pause(1))
return
if mode == "priority_low":
self._paused_queue_id = 0
self._paused_priority_state = self.service.state
self._apply_state(self.service.begin_priority_pause(0))
return
resumable_queue = self._resumable_queue_from_state(self.service.state)
if resumable_queue is not None:
self._paused_queue_id = resumable_queue
self._paused_priority_state = None
self._apply_state(self.service.begin_priority_pause(resumable_queue))
return
self._submit()
def _begin_manual_unload(self) -> None:
pallet = str(self.scanned_var.get() or "").strip()
destination = str(self.destination_var.get() or "").strip()
mode = getattr(self.service.state, "mode", "")
if mode in ("priority_high", "priority_low"):
self._skip_current_picking_pallet()
return
if pallet:
if destination == self.NON_SCAFFALATA_BARCODE:
self._submit()
else:
self._submit_unload_with_source_check()
return
if self._is_priority_pause():
return
self._apply_state(self.service.begin_manual_unload())
def _start_queue(self, id_stato: int) -> None:
def _start_queue(self, id_stato: int, *, allow_during_pause: bool = False) -> None:
if self._is_priority_pause() and not allow_during_pause:
return
self._run_async(
lambda: self.service.start_priority_queue(id_stato),
busy_message="Carico la coda selezionata...",
busy_message="In preparazione...",
)
def _submit(self) -> None:
@@ -370,7 +597,22 @@ class BarcodeClientApp:
scanned_pallet=self.scanned_var.get(),
destination_barcode=self.destination_var.get(),
),
busy_message="Eseguo il movimento...",
busy_message="In esecuzione...",
)
def _submit_unload_with_source_check(self) -> None:
self._run_async(
lambda: self.service.submit_unload_with_source_check(
scanned_pallet=self.scanned_var.get(),
source_barcode=self.destination_var.get(),
),
busy_message="In esecuzione...",
)
def _skip_current_picking_pallet(self) -> None:
self._run_async(
lambda: self.service.skip_current_picking_pallet(),
busy_message="Registro salto UDC...",
)
def _run_async(self, coro_factory: Callable[[], object], busy_message: str) -> None:
@@ -394,6 +636,12 @@ class BarcodeClientApp:
return 0
return None
def _resumable_queue_from_state(self, state: BarcodeViewState) -> int | None:
delay_ms = int(getattr(state, "auto_advance_delay_ms", 0) or 0)
if delay_ms <= 0:
return None
return self._queue_id_from_label(str(getattr(state, "queue_label", "") or ""))
def _poll_future(self) -> None:
if self._pending is None:
self._set_busy(False)
@@ -408,11 +656,16 @@ class BarcodeClientApp:
try:
result = future.result()
except Exception as exc:
current = self.service.state
current.status_text = f"Errore operativo: {exc}"
current.status_color = "#f4cccc"
self._apply_state(current)
messagebox.showerror("Barcode WMS", f"Operazione fallita:\n{exc}", parent=self.root)
log_exception("Barcode WMS", exc, context="barcode async operation")
self._set_busy(True, "Verifico esito...")
self._pending = asyncio.run_coroutine_threadsafe(
self.service.reconcile_after_submit_exception(
scanned_pallet=self.scanned_var.get(),
destination_barcode=self.destination_var.get(),
),
self.loop,
)
self.root.after(40, lambda err=exc: self._poll_recovery_future(err))
return
if isinstance(result, BarcodeActionResult):
@@ -422,6 +675,46 @@ class BarcodeClientApp:
elif isinstance(result, BarcodeViewState):
self._apply_state(result)
def _show_transaction_error(self) -> 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,
)
def _poll_recovery_future(self, original_exception: Exception) -> None:
if self._pending is None:
self._set_busy(False)
self._show_transaction_error()
return
if not self._pending.done():
self.root.after(40, lambda err=original_exception: self._poll_recovery_future(err))
return
future = self._pending
self._pending = None
self._set_busy(False)
try:
result = future.result()
except Exception as exc:
log_exception("Barcode WMS", exc, context=f"barcode recovery after {original_exception!r}")
current = self.service.state
current.status_text = "Transazione non completata, ripeti l'operazione."
current.status_color = "#f4cccc"
self._apply_state(current)
self._show_transaction_error()
return
if isinstance(result, BarcodeActionResult):
self._apply_state(result.state)
if not result.ok:
self.root.bell()
self._show_transaction_error()
elif isinstance(result, BarcodeViewState):
self._apply_state(result)
def _shutdown(self) -> None:
try:
if self._pending is not None and not self._pending.done():
@@ -446,6 +739,7 @@ def main() -> int:
loop = get_global_loop()
bootstrap = tk.Tk()
bootstrap.withdraw()
configure_exception_logging("Barcode WMS", root=bootstrap, loop=loop)
config = ensure_db_config(loop, parent=bootstrap)
if not config:
@@ -454,7 +748,7 @@ def main() -> int:
return 1
db_client = AsyncMSSQLClient(build_dsn_from_config(config))
session = prompt_login_compact(bootstrap, db_client)
session = _build_bypass_session() if BYPASS_LOGIN else prompt_login_compact(bootstrap, db_client)
if session is None:
try:
fut = asyncio.run_coroutine_threadsafe(db_client.dispose(), loop)

View File

@@ -7,8 +7,13 @@ possible while keeping SQL isolated from the UI.
from __future__ import annotations
from dataclasses import dataclass
from runtime_support import log_exception, log_runtime_event
from typing import Any
from version_info import module_version
__version__ = module_version(__name__)
SQL_NEXT_PICKING = """
SELECT TOP (1)
@@ -21,10 +26,20 @@ SELECT TOP (1)
Ubicazione,
Ordinamento,
IDStato
FROM dbo.py_XMag_ViewPackingList
FROM dbo.py_ViewPackingListPrelievo AS pl
WHERE Ordinamento > 0
AND IDStato = :id_stato
ORDER BY Ordinamento;
AND NOT EXISTS (
SELECT 1
FROM dbo.py_BarcodePickingListSkip AS s
WHERE s.Documento COLLATE Latin1_General_CI_AS =
CAST(pl.Documento AS varchar(50)) COLLATE Latin1_General_CI_AS
AND s.Pallet COLLATE Latin1_General_CI_AS =
CAST(pl.Pallet AS varchar(50)) COLLATE Latin1_General_CI_AS
AND s.IDStato = pl.IDStato
AND s.Risolto = 0
)
ORDER BY OrdinePrelievoGruppo, Ordinamento, Pallet;
"""
SQL_PICKING_BY_PALLET = """
@@ -38,9 +53,9 @@ SELECT TOP (1)
Ubicazione,
Ordinamento,
IDStato
FROM dbo.py_XMag_ViewPackingList
WHERE Pallet = :pallet
ORDER BY Ordinamento;
FROM dbo.py_ViewPackingListPrelievo
WHERE Pallet COLLATE Latin1_General_CI_AS = :pallet COLLATE Latin1_General_CI_AS
ORDER BY OrdinePrelievoGruppo, Ordinamento, Pallet;
"""
SQL_TRACE_BY_PALLET = """
@@ -50,13 +65,99 @@ SELECT TOP (1)
Prodotto,
Descrizione
FROM dbo.vXTracciaProdotti
WHERE Pallet = :pallet
WHERE Pallet COLLATE Latin1_General_CI_AS = :pallet COLLATE Latin1_General_CI_AS
ORDER BY Lotto;
"""
SQL_CURRENT_LOCATION_BY_PALLET = """
SELECT TOP (1)
g.BarcodePallet,
g.IDCella,
RTRIM(c.Corsia) AS Corsia,
RTRIM(CAST(c.Colonna AS varchar(32))) AS Colonna,
RTRIM(CAST(c.Fila AS varchar(32))) AS Fila
FROM dbo.XMag_GiacenzaPallet AS g
LEFT JOIN dbo.Celle AS c
ON c.ID = g.IDCella
WHERE g.BarcodePallet COLLATE Latin1_General_CI_AS = :pallet COLLATE Latin1_General_CI_AS;
"""
SQL_OPEN_LOCATIONS_BY_PALLET = """
SELECT
g.BarcodePallet,
g.IDCella,
RTRIM(c.Corsia) AS Corsia,
RTRIM(CAST(c.Colonna AS varchar(32))) AS Colonna,
RTRIM(CAST(c.Fila AS varchar(32))) AS Fila
FROM dbo.XMag_GiacenzaPallet AS g
LEFT JOIN dbo.Celle AS c
ON c.ID = g.IDCella
WHERE g.BarcodePallet COLLATE Latin1_General_CI_AS = :pallet COLLATE Latin1_General_CI_AS
ORDER BY g.IDCella;
"""
SQL_OPEN_PALLETS_BY_CELL = """
SELECT
g.BarcodePallet,
g.IDCella
FROM dbo.XMag_GiacenzaPallet AS g
WHERE g.IDCella = :id_cella
ORDER BY g.BarcodePallet;
"""
SQL_CLOSED_PICKING_BY_PALLET = """
SELECT TOP (1)
g.BarcodePallet,
g.NumeroPallet,
g.IDMagazzino,
g.IDArea,
g.IDCella,
g.IDStato
FROM dbo.XMag_GiacenzaPallet AS g
WHERE g.IDCella <> 9999
AND g.BarcodePallet COLLATE Latin1_General_CI_AS = :pallet COLLATE Latin1_General_CI_AS
AND EXISTS (
SELECT 1
FROM SAMA1.dbo.LOTSER AS ls
INNER JOIN SAMA1.dbo.LOTTIBF AS lb
ON lb.IDLOTSER = ls.ID
INNER JOIN SAMA1.dbo.FATRIG AS fr
ON lb.IDFATRIG = fr.ID
INNER JOIN SAMA1.dbo.BAMTES AS bt
ON bt.ID = fr.IDBAM
WHERE bt.ANNDOC >= 2011
AND bt.STATO = 'D'
AND LEFT(ls.NUMSER, 6) COLLATE Latin1_General_CI_AS =
:pallet COLLATE Latin1_General_CI_AS
)
ORDER BY g.IDCella DESC;
"""
SQL_RESOLVE_PHYSICAL_CELL = """
DECLARE @raw int = TRY_CONVERT(int, :destination);
DECLARE @cell_id int =
CASE
WHEN @raw IS NULL THEN NULL
WHEN @raw >= 9000000 THEN @raw - 9000000
ELSE @raw
END;
SELECT TOP (1)
c.ID AS IDCella,
CAST(9000000 + c.ID AS varchar(8)) AS BarcodeCella,
9000000 + c.ID AS NumeroCella,
CONCAT(RTRIM(c.Corsia), '.', RTRIM(CAST(c.Colonna AS varchar(32))), '.', RTRIM(CAST(c.Fila AS varchar(32)))) AS Ubicazione
FROM dbo.Celle AS c
WHERE c.ID = @cell_id
AND c.ID <> 9999
AND c.DelDataOra IS NULL;
"""
SQL_LEGACY_MOVE = """
SET NOCOUNT ON;
SET XACT_ABORT ON;
DECLARE @RC int = 0;
DECLARE @RefreshPickingReservation bit = :refresh_picking_reservation;
EXEC dbo.sp_xMagGestioneMagazziniPallet
@IDOperatore = :id_operatore,
@@ -65,7 +166,10 @@ EXEC dbo.sp_xMagGestioneMagazziniPallet
@NumeroCella = :numero_cella,
@RC = @RC OUTPUT;
EXEC dbo.py_sp_ControllaPrenotazionePackingListPalletNew;
IF @RefreshPickingReservation = 1
BEGIN
EXEC dbo.py_sp_ControllaPrenotazionePackingListPalletNew;
END;
SELECT
@RC AS RC,
@@ -74,6 +178,75 @@ SELECT
:numero_cella AS NumeroCella;
"""
SQL_SKIP_PICKING_PALLET = """
SET NOCOUNT ON;
IF NOT EXISTS (
SELECT 1
FROM dbo.py_BarcodePickingListSkip
WHERE Documento = :documento
AND Pallet COLLATE Latin1_General_CI_AS = :pallet COLLATE Latin1_General_CI_AS
AND IDStato = :id_stato
AND Risolto = 0
)
BEGIN
INSERT INTO dbo.py_BarcodePickingListSkip (
Documento,
Pallet,
IDStato,
IDOperatore,
DataOra,
Motivo,
Risolto
)
VALUES (
:documento,
:pallet,
:id_stato,
:id_operatore,
SYSDATETIME(),
:motivo,
0
);
END;
SELECT
:documento AS Documento,
:pallet AS Pallet,
:id_stato AS IDStato;
"""
SQL_ACTIVE_SKIPPED_DOCUMENT = """
SELECT TOP (1)
s.Documento,
COUNT(*) AS SkippedCount
FROM dbo.py_BarcodePickingListSkip AS s
WHERE s.IDStato = :id_stato
AND s.Risolto = 0
AND EXISTS (
SELECT 1
FROM dbo.py_ViewPackingListRestante AS pl
WHERE CAST(pl.Documento AS varchar(50)) COLLATE Latin1_General_CI_AS =
s.Documento COLLATE Latin1_General_CI_AS
AND pl.IDStato = :id_stato
)
GROUP BY s.Documento
ORDER BY MIN(s.DataOra);
"""
SQL_RELEASE_PICKING_DOCUMENT = """
SET NOCOUNT ON;
DECLARE @RC int = 0;
EXEC dbo.py_sp_xExePackingListPallet
@IDOperatore = :id_operatore,
@Documento = :documento,
@Azione = 'S',
@RC = @RC OUTPUT;
SELECT CAST(@RC AS int) AS RC;
"""
def _rows_to_dicts(res: dict[str, Any] | None) -> list[dict[str, Any]]:
"""Convert ``query_json`` payloads to a list of row dictionaries."""
@@ -101,6 +274,16 @@ class LegacyMoveResult:
numero_cella: int
@dataclass
class DestinationCell:
"""Resolved warehouse cell accepted by the legacy movement procedure."""
barcode_cella: str
numero_cella: int
id_cella: int
ubicazione: str
class BarcodeRepository:
"""Thin async repository used by the lightweight barcode client."""
@@ -128,6 +311,115 @@ class BarcodeRepository:
rows = _rows_to_dicts(res)
return rows[0] if rows else None
async def fetch_current_location_by_pallet(self, pallet: str) -> dict[str, Any] | None:
"""Return the current stock location for a pallet, if it exists in giacenza."""
res = await self.db_client.query_json(SQL_CURRENT_LOCATION_BY_PALLET, {"pallet": str(pallet or "").strip()})
rows = _rows_to_dicts(res)
return rows[0] if rows else None
async def fetch_open_locations_by_pallet(self, pallet: str) -> list[dict[str, Any]]:
"""Return all positive stock locations currently open for a pallet."""
res = await self.db_client.query_json(SQL_OPEN_LOCATIONS_BY_PALLET, {"pallet": str(pallet or "").strip()})
return _rows_to_dicts(res)
async def fetch_open_pallets_by_cell(self, id_cella: int) -> list[dict[str, Any]]:
"""Return pallets currently present in a physical cell."""
res = await self.db_client.query_json(SQL_OPEN_PALLETS_BY_CELL, {"id_cella": int(id_cella)})
return _rows_to_dicts(res)
async def fetch_closed_picking_by_pallet(self, pallet: str) -> dict[str, Any] | None:
"""Return a closed picking-list row for a pallet already considered shipped."""
res = await self.db_client.query_json(SQL_CLOSED_PICKING_BY_PALLET, {"pallet": str(pallet or "").strip()})
rows = _rows_to_dicts(res)
return rows[0] if rows else None
async def skip_picking_pallet(
self,
*,
documento: str,
pallet: str,
id_stato: int,
operator_id: int,
motivo: str = "UDC non trovata dal magazziniere",
) -> None:
"""Persist one skipped picking-list pallet so the queue can advance."""
params = {
"documento": str(documento or "").strip(),
"pallet": str(pallet or "").strip(),
"id_stato": int(id_stato),
"id_operatore": int(operator_id),
"motivo": str(motivo or "").strip(),
}
log_runtime_event(
"Barcode WMS",
(
"PICKING SKIP START "
f"documento={params['documento']} "
f"pallet={params['pallet']} "
f"id_stato={params['id_stato']} "
f"operator={params['id_operatore']}"
),
)
await self.db_client.query_json(SQL_SKIP_PICKING_PALLET, params, commit=True)
log_runtime_event(
"Barcode WMS",
(
"PICKING SKIP OK "
f"documento={params['documento']} "
f"pallet={params['pallet']} "
f"id_stato={params['id_stato']}"
),
)
async def fetch_active_skipped_document(self, id_stato: int) -> dict[str, Any] | None:
"""Return a reserved document whose remaining pallets were all skipped."""
res = await self.db_client.query_json(SQL_ACTIVE_SKIPPED_DOCUMENT, {"id_stato": int(id_stato)})
rows = _rows_to_dicts(res)
return rows[0] if rows else None
async def release_picking_document(self, *, documento: str, operator_id: int) -> int:
"""Release a reserved picking-list document without closing its residual rows."""
params = {
"documento": str(documento or "").strip(),
"id_operatore": int(operator_id),
}
log_runtime_event(
"Barcode WMS",
f"PICKING AUTO RELEASE START documento={params['documento']} operator={params['id_operatore']}",
)
res = await self.db_client.query_json(SQL_RELEASE_PICKING_DOCUMENT, params, as_dict_rows=True, commit=True)
rows = _rows_to_dicts(res)
rc = 0
if rows:
try:
rc = int(rows[0].get("RC") or 0)
except Exception:
rc = 0
log_runtime_event("Barcode WMS", f"PICKING AUTO RELEASE END documento={params['documento']} rc={rc}")
return rc
async def resolve_physical_cell(self, destination: str) -> DestinationCell | None:
"""Accept either an internal cell ID or the scanned legacy cell barcode."""
res = await self.db_client.query_json(SQL_RESOLVE_PHYSICAL_CELL, {"destination": str(destination or "").strip()})
rows = _rows_to_dicts(res)
if not rows:
return None
row = rows[0]
return DestinationCell(
barcode_cella=str(row.get("BarcodeCella") or ""),
numero_cella=int(row.get("NumeroCella") or 0),
id_cella=int(row.get("IDCella") or 0),
ubicazione=str(row.get("Ubicazione") or ""),
)
async def execute_legacy_move(
self,
*,
@@ -135,6 +427,7 @@ class BarcodeRepository:
barcode_cella: str,
barcode_pallet: str,
numero_cella: int,
refresh_picking_reservation: bool = True,
) -> LegacyMoveResult:
"""Execute the same stored procedure used by the C# barcode form."""
@@ -143,13 +436,47 @@ class BarcodeRepository:
"barcode_cella": str(barcode_cella or "").strip(),
"barcode_pallet": str(barcode_pallet or "").strip(),
"numero_cella": int(numero_cella),
"refresh_picking_reservation": 1 if refresh_picking_reservation else 0,
}
log_runtime_event(
"Barcode WMS",
(
"MOVE START "
f"operator={params['id_operatore']} "
f"cell={params['barcode_cella']} "
f"pallet={params['barcode_pallet']} "
f"refresh_pl={params['refresh_picking_reservation']}"
),
)
try:
res = await self.db_client.query_json(SQL_LEGACY_MOVE, params, commit=True)
except Exception as exc:
log_exception(
"Barcode WMS",
exc,
context=(
"execute_legacy_move "
f"operator={params['id_operatore']} "
f"cell={params['barcode_cella']} "
f"pallet={params['barcode_pallet']}"
),
)
raise
rows = _rows_to_dicts(res)
row = rows[0] if rows else {}
return LegacyMoveResult(
result = LegacyMoveResult(
rc=int(row.get("RC") or 0),
barcode_cella=str(row.get("BarcodeCella") or params["barcode_cella"]),
barcode_pallet=str(row.get("BarcodePallet") or params["barcode_pallet"]),
numero_cella=int(row.get("NumeroCella") or params["numero_cella"]),
)
log_runtime_event(
"Barcode WMS",
(
"MOVE OK "
f"rc={result.rc} "
f"cell={result.barcode_cella} "
f"pallet={result.barcode_pallet}"
),
)
return result

View File

@@ -2,11 +2,14 @@
from __future__ import annotations
from dataclasses import dataclass
from dataclasses import dataclass, replace
from typing import Literal
from barcode_repository import BarcodeRepository, LegacyMoveResult
from runtime_support import log_exception, log_runtime_event
from version_info import module_version
__version__ = module_version(__name__)
ModeName = Literal["idle", "priority_high", "priority_low", "manual_load", "manual_unload", "confirm"]
@@ -25,6 +28,9 @@ class BarcodeViewState:
expected_pallet: str = ""
destination_barcode: str = ""
scanned_pallet: str = ""
auto_advance_delay_ms: int = 0
destination_readonly: bool = False
focus_destination: bool = False
@dataclass
@@ -39,19 +45,21 @@ class BarcodeActionResult:
class BarcodeService:
"""Faithful, but cleaner, port of the legacy barcode form logic."""
NON_SCAFFALATA_BARCODE = "9001000"
SHIPPED_BARCODE = "9000000"
GRAY = "#d9d9d9"
RED = "#f4cccc"
LIGHT_GREEN = "#d9ead3"
GREEN_YELLOW = "#e2f0cb"
CONVENTIONAL_LOCATION_BY_CELL = {
1000: "5E1.1",
9999: "7G.1.1",
1000: "5E.1.1 - Non scaffalata",
9999: "7G.1.1 - Spedita",
}
def __init__(self, repository: BarcodeRepository, operator_id: int):
self.repository = repository
self.operator_id = int(operator_id)
self._current_priority_state = 0
self._current_priority_state = -1
self._state = BarcodeViewState()
@property
@@ -63,14 +71,14 @@ class BarcodeService:
def reset(self) -> BarcodeViewState:
"""Return the client to its neutral state."""
self._current_priority_state = 0
self._current_priority_state = -1
self._state = BarcodeViewState()
return self._state
def begin_manual_load(self) -> BarcodeViewState:
"""Prepare a real versamento into a physical warehouse cell."""
self._current_priority_state = 0
self._current_priority_state = -1
self._state = BarcodeViewState(
mode="manual_load",
queue_label="Versamento",
@@ -80,18 +88,80 @@ class BarcodeService:
return self._state
def begin_manual_unload(self) -> BarcodeViewState:
"""Prepare a direct unload toward the virtual outbound cell 9000000."""
"""Prepare a direct unload toward the conventional non-shelved cell."""
self._current_priority_state = 0
self._current_priority_state = -1
self._state = BarcodeViewState(
mode="manual_unload",
queue_label="Prelievo diretto",
status_text="OP Scarico",
status_color=self.GRAY,
destination_barcode="9000000",
destination_barcode=self.NON_SCAFFALATA_BARCODE,
destination_readonly=True,
)
return self._state
def begin_priority_pause(self, id_stato: int) -> BarcodeViewState:
"""Pause the active picking queue locally for exactly one free movement."""
self._current_priority_state = int(id_stato)
self._state = BarcodeViewState(
mode="manual_unload",
queue_label="Pausa PL",
status_text="Premi ESC per uscire dalla pausa",
status_color=self.GRAY,
destination_barcode=self.NON_SCAFFALATA_BARCODE,
destination_readonly=False,
)
return self._state
def resume_priority_state(self, state: BarcodeViewState) -> BarcodeViewState:
"""Restore the exact picking pallet that was visible before a local pause."""
if state.mode not in ("priority_high", "priority_low"):
return self._state
self._current_priority_state = 1 if state.mode == "priority_high" else 0
self._state = replace(state, scanned_pallet="", auto_advance_delay_ms=0)
return self._state
async def skip_current_picking_pallet(self) -> BarcodeActionResult:
"""Mark the currently proposed picking pallet as skipped and advance."""
mode = str(self._state.mode or "")
if mode not in ("priority_high", "priority_low"):
return BarcodeActionResult(False, self._state, "Nessuna picking list attiva.")
id_stato = 1 if mode == "priority_high" else 0
documento = str(self._state.document or "").strip()
pallet = str(self._state.expected_pallet or "").strip()
if not documento or not pallet:
self._state.status_text = "Nessuna UDC da saltare."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
await self.repository.skip_picking_pallet(
documento=documento,
pallet=pallet,
id_stato=id_stato,
operator_id=self.operator_id,
)
queue_label = "Alta priorita' (F1)" if id_stato == 1 else "Bassa priorita' (F2)"
self._current_priority_state = id_stato
self._state = BarcodeViewState(
mode="confirm",
queue_label=queue_label,
status_text="UDC saltata - chiusura manuale richiesta",
status_color=self.RED,
source_location=self._state.source_location,
document=documento,
customer="UDC non trovata",
expected_pallet=pallet,
destination_barcode=self.SHIPPED_BARCODE,
auto_advance_delay_ms=1500,
destination_readonly=True,
)
return BarcodeActionResult(True, self._state, self._state.status_text)
async def start_priority_queue(self, id_stato: int) -> BarcodeActionResult:
"""Load the next item of the selected legacy priority queue."""
@@ -99,12 +169,32 @@ class BarcodeService:
self._current_priority_state = int(id_stato)
queue_label = "Alta priorita' (F1)" if int(id_stato) == 1 else "Bassa priorita' (F2)"
if not row:
skipped_doc = await self.repository.fetch_active_skipped_document(int(id_stato))
if skipped_doc:
documento = str(skipped_doc.get("Documento") or "").strip()
skipped_count = int(skipped_doc.get("SkippedCount") or 0)
await self.repository.release_picking_document(
documento=documento,
operator_id=self.operator_id,
)
self._current_priority_state = -1
self._state = BarcodeViewState(
mode="priority_high" if int(id_stato) == 1 else "priority_low",
mode="manual_unload",
queue_label=queue_label,
status_text=f"PL {documento} sospesa: {skipped_count} UDC saltate. Riprenota per completare.",
status_color=self.RED,
destination_barcode=self.NON_SCAFFALATA_BARCODE,
destination_readonly=False,
)
return BarcodeActionResult(True, self._state)
self._current_priority_state = -1
self._state = BarcodeViewState(
mode="manual_unload",
queue_label=queue_label,
status_text="Pronto.",
status_color=self.RED,
destination_barcode="9000000",
destination_barcode=self.NON_SCAFFALATA_BARCODE,
destination_readonly=False,
)
return BarcodeActionResult(True, self._state)
@@ -122,7 +212,8 @@ class BarcodeService:
document=str(row.get("Documento") or ""),
customer=customer,
expected_pallet=str(row.get("Pallet") or ""),
destination_barcode="9000000",
destination_barcode=self.SHIPPED_BARCODE,
destination_readonly=True,
)
return BarcodeActionResult(True, self._state)
@@ -138,30 +229,409 @@ class BarcodeService:
if not destination.isdigit():
return BarcodeActionResult(False, self._state, "La destinazione deve essere numerica.")
if self._state.mode in ("priority_high", "priority_low") and destination == "9000000":
expected = str(self._state.expected_pallet or "").strip()
if expected and expected != pallet:
is_priority_mode = self._state.mode in ("priority_high", "priority_low")
expected_before_move = str(self._state.expected_pallet or "").strip()
is_picking_unload = bool(is_priority_mode and expected_before_move and destination == self.SHIPPED_BARCODE)
is_direct_unload = bool(destination == self.NON_SCAFFALATA_BARCODE and not is_picking_unload)
is_direct_load = bool(destination not in (self.NON_SCAFFALATA_BARCODE, self.SHIPPED_BARCODE) and not is_picking_unload)
if is_priority_mode and destination == self.SHIPPED_BARCODE:
if expected_before_move and expected_before_move != pallet:
self._state.scanned_pallet = pallet
self._state.status_text = "Errata lettura: il pallet letto non coincide con quello atteso."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
move = await self.repository.execute_legacy_move(
operator_id=self.operator_id,
barcode_cella=destination,
barcode_pallet=pallet,
numero_cella=int(destination),
)
if move.rc != 0:
if not is_picking_unload:
blocked = await self._block_closed_picking_free_move(pallet, destination)
if blocked is not None:
return blocked
target_barcode = destination
target_numero_cella = int(destination)
target_id_cella = 9999 if destination == self.SHIPPED_BARCODE else (1000 if destination == self.NON_SCAFFALATA_BARCODE else None)
target_display = destination
if is_direct_load:
resolved_cell = await self.repository.resolve_physical_cell(destination)
if not resolved_cell:
self._state.scanned_pallet = pallet
self._state.status_text = f"Operazione non riuscita (RC={move.rc})."
self._state.destination_barcode = destination
self._state.status_text = f"Cella non valida: {destination}."
self._state.status_color = self.RED
self._state.focus_destination = True
return BarcodeActionResult(False, self._state, self._state.status_text)
occupants = await self.repository.fetch_open_pallets_by_cell(resolved_cell.id_cella)
if occupants:
log_runtime_event(
"Barcode WMS",
(
"MOVE BLOCKED DESTINATION_OCCUPIED "
f"pallet={pallet} "
f"cell={resolved_cell.id_cella} "
f"occupants={','.join(str(row.get('BarcodePallet') or '') for row in occupants)}"
),
)
self._state.scanned_pallet = pallet
self._state.destination_barcode = destination
self._state.status_text = "Errore: cella scelta occupata, cambiare cella di destinazione."
self._state.status_color = self.RED
self._state.destination_readonly = False
self._state.focus_destination = True
return BarcodeActionResult(False, self._state, self._state.status_text)
target_barcode = resolved_cell.barcode_cella
target_numero_cella = resolved_cell.numero_cella
target_id_cella = resolved_cell.id_cella
target_display = resolved_cell.ubicazione or destination
current_location = await self.repository.fetch_current_location_by_pallet(pallet)
picking_before_move = (
None
if current_location
else await self.repository.fetch_picking_by_pallet(pallet)
)
if not current_location and not picking_before_move:
if is_direct_load:
trace_row = await self.repository.fetch_trace_by_pallet(pallet)
if not trace_row:
self._state.scanned_pallet = pallet
self._state.destination_barcode = destination
self._state.status_text = "Errore: UDC non riconosciuta in ERP/SAM."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
log_runtime_event(
"Barcode WMS",
f"AUTO INTAKE NON_SHELVED pallet={pallet} before_cell={target_id_cella}",
)
await self.repository.execute_legacy_move(
operator_id=self.operator_id,
barcode_cella=self.NON_SCAFFALATA_BARCODE,
barcode_pallet=pallet,
numero_cella=int(self.NON_SCAFFALATA_BARCODE),
refresh_picking_reservation=False,
)
current_location = await self.repository.fetch_current_location_by_pallet(pallet)
try:
current_id_cella = int((current_location or {}).get("IDCella") or 0)
except Exception:
current_id_cella = 0
if current_id_cella != 1000:
self._state.scanned_pallet = pallet
self._state.destination_barcode = destination
self._state.status_text = "Movimento non confermato: ingresso UDC non scaffalata non riuscito."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
else:
self._state.scanned_pallet = pallet
self._state.status_text = "UDC non presente a magazzino."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
open_locations = await self.repository.fetch_open_locations_by_pallet(pallet)
distinct_cells = sorted({
int(row.get("IDCella") or 0)
for row in open_locations
if row.get("IDCella") is not None
})
if len(distinct_cells) > 1:
log_runtime_event(
"Barcode WMS",
(
"MOVE BLOCKED MULTI_LOCATION "
f"pallet={pallet} "
f"cells={','.join(str(cell) for cell in distinct_cells)}"
),
)
self._state.scanned_pallet = pallet
self._state.destination_barcode = destination
self._state.status_text = "UDC presente in piu' celle. Movimento bloccato."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
if not is_direct_load and destination not in (self.NON_SCAFFALATA_BARCODE, self.SHIPPED_BARCODE):
resolved_cell = await self.repository.resolve_physical_cell(destination)
if not resolved_cell:
self._state.scanned_pallet = pallet
self._state.status_text = f"Cella non valida: {destination}."
self._state.status_color = self.RED
self._state.focus_destination = True
return BarcodeActionResult(False, self._state, self._state.status_text)
target_barcode = resolved_cell.barcode_cella
target_numero_cella = resolved_cell.numero_cella
target_id_cella = resolved_cell.id_cella
target_display = resolved_cell.ubicazione or destination
move = await self.repository.execute_legacy_move(
operator_id=self.operator_id,
barcode_cella=target_barcode,
barcode_pallet=pallet,
numero_cella=target_numero_cella,
refresh_picking_reservation=is_picking_unload,
)
final_location = await self.repository.fetch_current_location_by_pallet(pallet)
try:
final_cell = int((final_location or {}).get("IDCella") or 0)
except Exception:
final_cell = 0
if target_id_cella is not None and final_cell != target_id_cella:
self._state.scanned_pallet = pallet
self._state.destination_barcode = destination
self._state.status_text = "Movimento non confermato: la UDC non risulta nella cella attesa."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
try:
self._state = await self._build_post_move_state(
barcode_pallet=pallet,
destination_barcode=destination,
destination_display=target_display,
last_priority_state=self._current_priority_state,
auto_advance_delay_ms=3000 if is_picking_unload else 0,
)
except Exception as exc:
log_exception("Barcode WMS", exc, context=f"post move state pallet={pallet} destination={destination}")
self._state = BarcodeViewState(
mode="confirm",
queue_label="Conferma movimento",
status_text="Movimento eseguito. Dettagli non aggiornati.",
status_color=self.GREEN_YELLOW,
destination_barcode=destination,
scanned_pallet=pallet,
)
return BarcodeActionResult(True, self._state, self._state.status_text)
async def submit_unload_with_source_check(self, *, scanned_pallet: str, source_barcode: str) -> BarcodeActionResult:
"""Unload to the non-shelved cell only if the scanned source cell matches DB."""
pallet = str(scanned_pallet or "").strip()
source = str(source_barcode or "").strip()
if not pallet:
return BarcodeActionResult(False, self._state, "Inserisci o leggi il pallet.")
if not source:
return BarcodeActionResult(False, self._state, "Leggi il codice della cella da scaricare.")
if not source.isdigit():
return BarcodeActionResult(False, self._state, "La cella da scaricare deve essere numerica.")
blocked = await self._block_closed_picking_free_move(pallet, source)
if blocked is not None:
return blocked
current_location = await self.repository.fetch_current_location_by_pallet(pallet)
if not current_location:
self._state.scanned_pallet = pallet
self._state.status_text = "UDC non presente a magazzino."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
open_locations = await self.repository.fetch_open_locations_by_pallet(pallet)
distinct_cells = sorted({
int(row.get("IDCella") or 0)
for row in open_locations
if row.get("IDCella") is not None
})
if len(distinct_cells) > 1:
log_runtime_event(
"Barcode WMS",
(
"MOVE BLOCKED MULTI_LOCATION "
f"pallet={pallet} "
f"cells={','.join(str(cell) for cell in distinct_cells)}"
),
)
self._state.scanned_pallet = pallet
self._state.destination_barcode = source
self._state.status_text = "UDC presente in piu' celle. Movimento bloccato."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
if source == self.NON_SCAFFALATA_BARCODE:
source_id_cella = 1000
else:
resolved_source = await self.repository.resolve_physical_cell(source)
if not resolved_source:
self._state.scanned_pallet = pallet
self._state.destination_barcode = source
self._state.status_text = f"Cella non valida: {source}."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
source_id_cella = int(resolved_source.id_cella)
current_id_cella = int((current_location or {}).get("IDCella") or 0)
if current_id_cella != source_id_cella:
if source == self.NON_SCAFFALATA_BARCODE and current_id_cella != 1000:
log_runtime_event(
"Barcode WMS",
(
"MOVE BLOCKED SOURCE_REQUIRED "
f"pallet={pallet} "
f"db_cell={current_id_cella} "
f"default_cell={source_id_cella}"
),
)
self._state.scanned_pallet = pallet
self._state.destination_barcode = source
self._state.status_text = "Errore: leggi la cella da scaricare."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
log_runtime_event(
"Barcode WMS",
(
"MOVE BLOCKED SOURCE_MISMATCH "
f"pallet={pallet} "
f"db_cell={current_id_cella} "
f"scanned_cell={source_id_cella}"
),
)
self._state.scanned_pallet = pallet
self._state.destination_barcode = source
self._state.status_text = "Errore: UDC in cella diversa, rileggi il codice della cella da scaricare."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
await self.repository.execute_legacy_move(
operator_id=self.operator_id,
barcode_cella=self.NON_SCAFFALATA_BARCODE,
barcode_pallet=pallet,
numero_cella=int(self.NON_SCAFFALATA_BARCODE),
refresh_picking_reservation=False,
)
final_location = await self.repository.fetch_current_location_by_pallet(pallet)
try:
final_cell = int((final_location or {}).get("IDCella") or 0)
except Exception:
final_cell = 0
if final_cell != 1000:
self._state.scanned_pallet = pallet
self._state.destination_barcode = source
self._state.status_text = "Movimento non confermato: la UDC non risulta non scaffalata."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
try:
self._state = await self._build_post_move_state(
barcode_pallet=pallet,
destination_barcode=self.NON_SCAFFALATA_BARCODE,
destination_display=self.CONVENTIONAL_LOCATION_BY_CELL[1000],
last_priority_state=self._current_priority_state,
auto_advance_delay_ms=0,
)
except Exception as exc:
log_exception("Barcode WMS", exc, context=f"post source-check unload pallet={pallet} source={source}")
self._state = BarcodeViewState(
mode="confirm",
queue_label="Conferma movimento",
status_text="Movimento eseguito. Dettagli non aggiornati.",
status_color=self.GREEN_YELLOW,
destination_barcode=self.NON_SCAFFALATA_BARCODE,
scanned_pallet=pallet,
)
return BarcodeActionResult(True, self._state, self._state.status_text)
async def _block_closed_picking_free_move(
self,
pallet: str,
destination_barcode: str,
) -> BarcodeActionResult | None:
closed_row = await self.repository.fetch_closed_picking_by_pallet(pallet)
if not closed_row:
return None
log_runtime_event(
"Barcode WMS",
(
"MOVE BLOCKED CLOSED_PICKING "
f"pallet={pallet} "
f"destination={destination_barcode} "
f"id_cella={closed_row.get('IDCella')} "
f"id_stato={closed_row.get('IDStato')}"
),
)
self._state.scanned_pallet = pallet
self._state.destination_barcode = destination_barcode
self._state.status_text = "Errore: UDC gia' spedita, problema nella locazione o nella UDC."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
async def reconcile_after_submit_exception(
self,
*,
scanned_pallet: str,
destination_barcode: str,
) -> BarcodeActionResult:
"""Check whether a failed client round-trip actually committed on SQL Server."""
pallet = str(scanned_pallet or "").strip()
destination = str(destination_barcode or "").strip()
if not pallet or not destination or not destination.isdigit():
self._state.status_text = "Transazione non completata, ripeti l'operazione."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
target_id_cella = 9999 if destination == self.SHIPPED_BARCODE else (1000 if destination == self.NON_SCAFFALATA_BARCODE else None)
target_display = destination
if target_id_cella is None:
resolved_cell = await self.repository.resolve_physical_cell(destination)
if not resolved_cell:
self._state.scanned_pallet = pallet
self._state.destination_barcode = destination
self._state.status_text = "Transazione non completata, ripeti l'operazione."
self._state.status_color = self.RED
self._state.focus_destination = True
return BarcodeActionResult(False, self._state, self._state.status_text)
target_id_cella = int(resolved_cell.id_cella)
target_display = resolved_cell.ubicazione or destination
current_location = await self.repository.fetch_current_location_by_pallet(pallet)
try:
current_id_cella = int((current_location or {}).get("IDCella") or 0)
except Exception:
current_id_cella = 0
if current_id_cella != target_id_cella:
log_runtime_event(
"Barcode WMS",
(
"MOVE RECOVERY NOT_CONFIRMED "
f"pallet={pallet} "
f"destination={destination} "
f"expected_cell={target_id_cella} "
f"actual_cell={current_id_cella}"
),
)
self._state.scanned_pallet = pallet
self._state.destination_barcode = destination
self._state.status_text = "Transazione non completata, ripeti l'operazione."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
last_priority_state = self._current_priority_state
is_recovered_picking = bool(destination == self.SHIPPED_BARCODE and last_priority_state in (0, 1))
auto_advance_delay_ms = 3000 if is_recovered_picking else 0
state = await self._build_post_move_state(
barcode_pallet=pallet,
destination_barcode=destination,
destination_display=target_display,
last_priority_state=last_priority_state,
auto_advance_delay_ms=auto_advance_delay_ms,
)
state.status_text = (
"Ok Scarico - risposta persa recuperata"
if is_recovered_picking
else "Movimento completato - risposta persa recuperata"
)
state.status_color = self.GREEN_YELLOW
self._state = state
log_runtime_event(
"Barcode WMS",
(
"MOVE RECOVERY CONFIRMED "
f"pallet={pallet} "
f"destination={destination} "
f"cell={target_id_cella}"
),
)
return BarcodeActionResult(True, self._state, self._state.status_text)
@@ -170,11 +640,21 @@ class BarcodeService:
*,
barcode_pallet: str,
destination_barcode: str,
destination_display: str,
last_priority_state: int,
auto_advance_delay_ms: int,
) -> BarcodeViewState:
"""Mirror the legacy confirmation flow after one stored-procedure move."""
picking_row = await self.repository.fetch_picking_by_pallet(barcode_pallet)
is_priority_shipping_confirmation = (
destination_barcode == self.SHIPPED_BARCODE
and last_priority_state in (0, 1)
)
picking_row = (
await self.repository.fetch_picking_by_pallet(barcode_pallet)
if is_priority_shipping_confirmation
else None
)
if picking_row:
customer = f"{picking_row.get('CodNazione') or ''} - {picking_row.get('NAZIONE') or ''}".strip(" -")
source_location = self._display_location(
@@ -191,6 +671,8 @@ class BarcodeService:
customer=customer,
expected_pallet=str(picking_row.get("Pallet") or ""),
destination_barcode=destination_barcode,
auto_advance_delay_ms=auto_advance_delay_ms,
destination_readonly=True,
)
trace_row = await self.repository.fetch_trace_by_pallet(barcode_pallet)
@@ -199,31 +681,39 @@ class BarcodeService:
prodotto = str(trace_row.get("Prodotto") or "")
descrizione = str(trace_row.get("Descrizione") or "")
queue_label = "Alta priorita' (F1)" if last_priority_state == 1 else ("Bassa priorita' (F2)" if last_priority_state == 0 else "Conferma movimento")
destination_label = self._display_destination_location(
destination_barcode=destination_barcode,
destination_display=destination_display,
)
return BarcodeViewState(
mode="confirm",
queue_label=queue_label,
status_text=(
"Ok Scarico" if destination_barcode == "9000000" else f"Ok Carico - {destination_barcode}"
f"Ok Scarico - {destination_label}"
if destination_barcode in (self.NON_SCAFFALATA_BARCODE, self.SHIPPED_BARCODE)
else f"Ok Carico - {destination_label}"
),
status_color=self.GREEN_YELLOW,
source_location=str(destination_barcode or ""),
source_location=destination_label,
document=(
self.CONVENTIONAL_LOCATION_BY_CELL[9999]
if destination_barcode == "9000000" and last_priority_state in (0, 1)
self.CONVENTIONAL_LOCATION_BY_CELL[9999 if destination_barcode == self.SHIPPED_BARCODE else 1000]
if destination_barcode in (self.NON_SCAFFALATA_BARCODE, self.SHIPPED_BARCODE) and last_priority_state in (0, 1)
else lotto
),
customer=(
lotto
if destination_barcode == "9000000" and last_priority_state in (0, 1)
if destination_barcode in (self.NON_SCAFFALATA_BARCODE, self.SHIPPED_BARCODE) and last_priority_state in (0, 1)
else prodotto
),
expected_pallet=(
" - ".join(part for part in (prodotto, descrizione) if part)
if destination_barcode == "9000000" and last_priority_state in (0, 1)
if destination_barcode in (self.NON_SCAFFALATA_BARCODE, self.SHIPPED_BARCODE) and last_priority_state in (0, 1)
else descrizione
),
destination_barcode=destination_barcode,
scanned_pallet=barcode_pallet,
auto_advance_delay_ms=auto_advance_delay_ms,
destination_readonly=destination_barcode in (self.NON_SCAFFALATA_BARCODE, self.SHIPPED_BARCODE),
)
return BarcodeViewState(
@@ -235,6 +725,15 @@ class BarcodeService:
scanned_pallet=barcode_pallet,
)
def _display_destination_location(self, *, destination_barcode: str, destination_display: str) -> str:
"""Return the confirmation label for a movement destination."""
if destination_barcode == self.NON_SCAFFALATA_BARCODE:
return self.CONVENTIONAL_LOCATION_BY_CELL[1000]
if destination_barcode == self.SHIPPED_BARCODE:
return self.CONVENTIONAL_LOCATION_BY_CELL[9999]
return str(destination_display or destination_barcode or "")
def _display_location(self, *, cella: object, ubicazione: object) -> str:
"""Return the operator-facing location, honoring legacy conventional cells."""

View File

@@ -6,6 +6,9 @@ import tkinter as tk
import customtkinter as ctk
from ui_theme import theme_color, theme_font, theme_padding, theme_value
from version_info import module_version
__version__ = module_version(__name__)
class InlineBusyOverlay:

View File

@@ -0,0 +1,256 @@
# Prontuario Git per installare/aggiornare Warehouse da remoto
Repository Gitea:
https://gitea.alessandrobonvicini.it/administrator/ware_house.git
Cartella consigliata sul PC di produzione:
C:\flywms
Ramo principale da usare in produzione:
main
Ultimo tag stabile al momento della stesura:
alpha7-stabilizzazione-non-scaffalate
1. Prima installazione su PC nuovo
----------------------------------
Aprire PowerShell nella macchina di produzione ed eseguire:
cd C:\
git clone https://gitea.alessandrobonvicini.it/administrator/ware_house.git C:\flywms
cd C:\flywms
git switch main
git pull origin main
Installare le dipendenze Python:
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
Avvio applicazione desktop:
python main.py
Oppure senza finestra console:
pythonw warehouse.pyw
Avvio applicazione barcode:
python barcode_client.py
Oppure senza finestra console:
pythonw barcode.pyw
2. Aggiornare un'installazione gia' esistente
--------------------------------------------
Sul PC di produzione:
cd C:\flywms
git fetch --all --tags
git switch main
git pull origin main
python -m pip install -r requirements.txt
Poi rilanciare l'applicazione.
2.bis Aggiornare produzione dopo merge su main gia' fatto
---------------------------------------------------------
Questo e' il caso piu' normale:
- sul PC di sviluppo hai gia' fatto merge del ramo di lavoro dentro main;
- hai gia' fatto push su Gitea;
- sul PC di produzione devi solo scaricare l'ultima versione ufficiale.
Sul PC di produzione eseguire:
cd C:\flywms
git fetch --all --tags
git switch main
git pull origin main
python -m pip install -r requirements.txt
Poi chiudere e riaprire l'applicazione.
Controllo consigliato dopo l'aggiornamento:
git log --oneline --decorate -3
git describe --tags --abbrev=0 main
3. Controllare che versione/tag si sta usando
---------------------------------------------
Dentro C:\flywms:
git status
git log --oneline --decorate -5
Vedere l'ultimo tag raggiungibile da main:
git describe --tags --abbrev=0 main
Vedere tutti i tag, dal piu' recente:
git tag --sort=-creatordate
Vedere graficamente branch, commit e tag:
git log --oneline --decorate --graph --all -20
4. Installare esattamente una versione taggata
---------------------------------------------
Usare questa modalita' quando si vuole installare una fotografia precisa e non
necessariamente l'ultima versione di main.
Esempio:
cd C:\
git clone --branch alpha7-stabilizzazione-non-scaffalate https://gitea.alessandrobonvicini.it/administrator/ware_house.git C:\flywms_alpha7
Nota:
Un tag e' una fotografia ferma. Non avanza con git pull come un branch.
Per produzione ordinaria e' piu' comodo usare main.
5. Portare l'ultimo sviluppo dentro main
---------------------------------------
Da fare sulla macchina di sviluppo, non sul PC di produzione.
Se l'ultima versione buona e' su sviluppo3 e vuoi renderla ufficiale su main:
cd C:\devel\python\ware_house
git fetch --all --tags
git status
git switch main
git pull origin main
git merge sviluppo3
git push origin main
Se vuoi anche creare un tag stabile:
git tag nome-del-tag
git push origin nome-del-tag
Esempio:
git tag alpha8-nome-breve-della-modifica
git push origin alpha8-nome-breve-della-modifica
6. Se il PC di produzione ha modifiche locali
---------------------------------------------
Prima di aggiornare controllare:
cd C:\flywms
git status
Se compaiono file modificati che non devono essere conservati, NON fare comandi
distruttivi senza sapere cosa sono. Prima copiare o rinominare i file modificati.
File che normalmente NON devono essere messi nel repository:
db_connection.json
*.log
__pycache__
*.pyc
*.zip
7. Script SQL
-------------
Gli script SQL sono nel repository e vanno lanciati in SSMS solo quando serve
preparare o aggiornare il database per le funzioni Python.
Patch principali:
apply_python_parallel_pickinglist_patch.sql
apply_python_pickinglist_history_views.sql
apply_online_history_forms_patch.sql
Rollback principali:
rollback_python_parallel_pickinglist_patch.sql
rollback_python_pickinglist_history_views.sql
rollback_online_history_forms_patch.sql
Nota:
Prima di lanciare patch SQL in produzione, fare sempre backup o snapshot del
database, oppure verificare di avere una procedura di rollback sicura.
8. Comando rapido piu' usato
----------------------------
Aggiornamento standard del PC di produzione:
cd C:\flywms
git fetch --all --tags
git switch main
git pull origin main
python -m pip install -r requirements.txt
9. Per vedere cosa ho installato
------------------------------------------------------
git log --oneline --decorate -3
git describe --tags --abbrev=0 main
10. Salvare questo prontuario su Gitea
-------------------------------------
Da fare sul PC di sviluppo, dentro la cartella del repository:
cd C:\devel\python\ware_house
git status
git add comandi_git_per_installare.txt
git commit -m "Aggiungi prontuario Git per installazione remota"
git push origin main
Dopo il push, il file sara' disponibile anche sui PC di produzione al prossimo:
cd C:\flywms
git pull origin main
11. Aggiornare il prontuario se lo modifico in locale
----------------------------------------------------
Se modifichi questo file sul PC di sviluppo e vuoi sincronizzarlo su Gitea:
cd C:\devel\python\ware_house
git status
git diff -- comandi_git_per_installare.txt
git add comandi_git_per_installare.txt
git commit -m "Aggiorna prontuario Git installazione"
git push origin main
Se invece lo hai modificato su un PC di produzione e vuoi prima recuperare
eventuali aggiornamenti online:
cd C:\flywms
git status
git pull origin main
Se Git segnala conflitti, fermarsi e risolverli prima di rilanciare
l'applicazione. Per evitare confusione, e' meglio modificare questo prontuario
solo sul PC di sviluppo e poi fare push su Gitea.

View File

@@ -13,6 +13,9 @@ from async_msssql_query import AsyncMSSQLClient, make_mssql_dsn
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_section, theme_value
from version_info import module_version, versioned_title
__version__ = module_version(__name__)
CONFIG_PATH = Path(__file__).with_name("db_connection.json")
DEFAULT_DB_CONFIG: dict[str, Any] = {
@@ -23,6 +26,11 @@ DEFAULT_DB_CONFIG: dict[str, Any] = {
"driver": "ODBC Driver 17 for SQL Server",
"trust_server_certificate": True,
"encrypt": "",
"query_profiler": {
"enabled": False,
"slow_ms": 0,
"sql_limit": 4000,
},
}
@@ -101,7 +109,7 @@ class DatabaseConfigWindow(tk.Toplevel):
self.result_config: dict[str, Any] | None = None
merged = {**DEFAULT_DB_CONFIG, **(initial or {})}
self.title(loc_text("dbconfig.title", catalog=self._locale_catalog, default="Configurazione Database"))
self.title(versioned_title(loc_text("dbconfig.title", catalog=self._locale_catalog, default="Configurazione Database"), __name__))
self.geometry(str(theme_value(self._theme, "window_geometry", "520x360")))
self.resizable(False, False)
try:

543
diagnostica.py Normal file
View File

@@ -0,0 +1,543 @@
"""Operational diagnostic checks for warehouse data quadrature."""
from __future__ import annotations
import tkinter as tk
from datetime import datetime
from tkinter import filedialog, messagebox, ttk
from typing import Any
import customtkinter as ctk
from busy_overlay import InlineBusyOverlay
from gestione_aree import AsyncRunner
from locale_text import load_locale_catalog, text as loc_text
from runtime_support import log_exception
from ui_tables import style_treeview, zebra_tag
from ui_theme import theme_color, theme_font, theme_section, theme_value
from version_info import module_version, versioned_title
from window_placement import place_window_fullsize_below_parent_later
__version__ = module_version(__name__)
SQL_SHIPPED_NOT_DISASSOCIATED = """
SELECT DISTINCT
LTRIM(RTRIM(g.BarcodePallet)) AS UDC,
CAST('Spedita ma non disassociata' AS varchar(64)) AS Diagnostica,
CONCAT(
RTRIM(c.Corsia),
' - ',
RTRIM(CAST(c.Colonna AS varchar(32))),
' - ',
RTRIM(CAST(c.Fila AS varchar(32)))
) AS NomeSimbolicoCella
FROM dbo.XMag_GiacenzaPallet AS g
INNER JOIN dbo.Celle AS c
ON c.ID = g.IDCella
INNER JOIN dbo.py_XMag_ViewPackingListStorico AS chiuse
ON LTRIM(RTRIM(chiuse.Pallet)) COLLATE Latin1_General_CI_AS =
LTRIM(RTRIM(g.BarcodePallet)) COLLATE Latin1_General_CI_AS
WHERE chiuse.StatoDocumento = 'D'
AND g.IDCella <> 9999
ORDER BY NomeSimbolicoCella, UDC;
"""
SQL_MULTIPLE_UDC_BY_CELL = """
WITH celle_multiple AS (
SELECT
g.IDCella
FROM dbo.XMag_GiacenzaPallet AS g
WHERE g.IDCella NOT IN (1000, 9999)
GROUP BY g.IDCella
HAVING COUNT(DISTINCT LTRIM(RTRIM(g.BarcodePallet))) > 1
)
SELECT
CONCAT(
RTRIM(c.Corsia),
' - ',
RTRIM(CAST(c.Colonna AS varchar(32))),
' - ',
RTRIM(CAST(c.Fila AS varchar(32)))
) AS CELLA,
LTRIM(RTRIM(g.BarcodePallet)) AS UDC
FROM dbo.XMag_GiacenzaPallet AS g
INNER JOIN celle_multiple AS cm
ON cm.IDCella = g.IDCella
INNER JOIN dbo.Celle AS c
ON c.ID = g.IDCella
ORDER BY CELLA, UDC;
"""
SQL_SAM_UDC_NOT_IN_WMS = """
WITH recent_lotser AS (
SELECT TOP (5000)
ls.ID,
LEFT(ls.NUMSER, 6) AS UDC,
ls.NUMLOT AS Lotto,
ls.IDARTICO
FROM SAMA1.dbo.LOTSER AS ls
WHERE NULLIF(LTRIM(RTRIM(LEFT(ls.NUMSER, 6))), '') IS NOT NULL
AND TRY_CONVERT(int, LTRIM(RTRIM(LEFT(ls.NUMSER, 6)))) > 0
AND LEN(LTRIM(RTRIM(LEFT(ls.NUMSER, 6)))) = 6
AND ls.NUMLOT LIKE CONCAT('P', RIGHT(CONVERT(varchar(4), YEAR(GETDATE())), 2), '%')
ORDER BY ls.ID DESC
), sam_udc AS (
SELECT
LTRIM(RTRIM(r.UDC)) AS UDC,
MIN(r.Lotto) AS Lotto,
MIN(a.CODICE) AS Prodotto,
MIN(a.DESCR) AS Descrizione,
MAX(r.ID) AS UltimoIDLotSer
FROM recent_lotser AS r
INNER JOIN SAMA1.dbo.ARTICO AS a
ON a.ID = r.IDARTICO
GROUP BY LTRIM(RTRIM(r.UDC))
)
SELECT TOP (100)
s.UDC,
s.Lotto,
s.Prodotto,
s.Descrizione
FROM sam_udc AS s
WHERE NOT EXISTS (
SELECT 1
FROM dbo.MagazziniPallet AS mp
WHERE LTRIM(RTRIM(mp.Attributo)) COLLATE Latin1_General_CI_AS =
s.UDC COLLATE Latin1_General_CI_AS
)
ORDER BY s.UltimoIDLotSer DESC;
"""
SHIPPED_NOT_DISASSOCIATED_COLUMNS = (
("UDC", "diagnostics.col.udc", "UDC", 130, "w"),
(
"Diagnostica",
"diagnostics.col.shipped_not_disassociated",
"Spedita ma non disassociata",
280,
"w",
),
("NomeSimbolicoCella", "diagnostics.col.symbolic_cell", "Nome simbolico cella", 240, "w"),
)
MULTIPLE_UDC_COLUMNS = (
("CELLA", "diagnostics.col.cell", "CELLA", 220, "w"),
("UDC", "diagnostics.col.udc", "UDC", 160, "w"),
)
SAM_UDC_NOT_IN_WMS_COLUMNS = (
("UDC", "diagnostics.col.udc", "UDC", 130, "w"),
("Lotto", "diagnostics.col.lot", "Lotto", 160, "w"),
("Prodotto", "diagnostics.col.product", "Prodotto", 150, "w"),
("Descrizione", "diagnostics.col.description", "Descrizione", 360, "w"),
)
def _rows_to_dicts(res: dict[str, Any] | None) -> list[dict[str, Any]]:
if not isinstance(res, dict):
return []
rows = res.get("rows") or []
cols = res.get("columns") or []
if rows and isinstance(rows[0], dict):
return [row for row in rows if isinstance(row, dict)]
out: list[dict[str, Any]] = []
for row in rows:
if isinstance(row, (list, tuple)) and cols:
out.append({str(cols[i]): row[i] for i in range(min(len(cols), len(row)))})
return out
class DiagnosticaWindow(ctk.CTkToplevel):
"""Window collecting read-only diagnostic queries."""
def __init__(self, parent: tk.Widget, db_client, session=None):
super().__init__(parent)
self.db_client = db_client
self.session = session
self._theme = theme_section("diagnostics_window", theme_section("search_window", {}))
self._locale_catalog = load_locale_catalog()
self._async = AsyncRunner(self)
self._busy = InlineBusyOverlay(self, self._theme)
self._load_in_progress = False
self._current_check = ""
self.var_status = tk.StringVar(value="")
self._last_export_slug = "diagnostica"
self._current_columns = SHIPPED_NOT_DISASSOCIATED_COLUMNS
self._column_titles: dict[str, str] = {}
self._sort_column = ""
self._sort_descending = False
self.title(
versioned_title(
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
__name__,
)
)
self.geometry(str(theme_value(self._theme, "window_geometry", "1100x680")))
minsize = theme_value(self._theme, "window_minsize", [900, 560])
self.minsize(int(minsize[0]), int(minsize[1]))
try:
self.configure(fg_color=theme_color(self._theme, "window_fg_color", ("#efefef", "#2f2f2f")))
except Exception:
pass
self._build_ui()
def _is_alive(self) -> bool:
try:
return bool(self.winfo_exists())
except tk.TclError:
return False
def _hide_busy_safe(self) -> None:
try:
self._busy.hide()
except Exception as exc:
log_exception(__name__, exc, context="hide busy diagnostica")
def _build_ui(self) -> None:
self.grid_rowconfigure(2, weight=1)
self.grid_columnconfigure(0, weight=1)
top = ctk.CTkFrame(
self,
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(3, weight=1)
button_font = theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold"))
ctk.CTkButton(
top,
text=loc_text(
"diagnostics.button.shipped_not_disassociated",
catalog=self._locale_catalog,
default="UDC spedite non disassociate",
),
command=self._load_shipped_not_disassociated,
font=button_font,
).grid(row=0, column=0, sticky="w", padx=(0, 8))
ctk.CTkButton(
top,
text=loc_text(
"diagnostics.button.multiple_udc_by_cell",
catalog=self._locale_catalog,
default="Celle con multiple UDC",
),
command=self._load_multiple_udc_by_cell,
font=button_font,
).grid(row=0, column=1, sticky="w", padx=(0, 8))
ctk.CTkButton(
top,
text=loc_text(
"diagnostics.button.sam_udc_not_in_wms",
catalog=self._locale_catalog,
default="Ultime UDC SAM non in WMS",
),
command=self._load_sam_udc_not_in_wms,
font=button_font,
).grid(row=0, column=2, sticky="w", padx=(0, 8))
self.btn_export = ctk.CTkButton(
top,
text=loc_text("diagnostics.button.export", catalog=self._locale_catalog, default="Esporta XLSX"),
command=self._export_xlsx,
font=button_font,
state="disabled",
)
self.btn_export.grid(row=0, column=4, sticky="e")
ctk.CTkLabel(
self,
textvariable=self.var_status,
anchor="w",
font=theme_font(self._theme, "status_font", ("Segoe UI", 10, "bold")),
).grid(row=1, column=0, sticky="ew", padx=10, pady=(0, 6))
wrap = ctk.CTkFrame(self)
wrap.grid(row=2, column=0, sticky="nsew", padx=8, pady=(0, 8))
wrap.grid_rowconfigure(0, weight=1)
wrap.grid_columnconfigure(0, weight=1)
self.tree = ttk.Treeview(wrap, show="headings")
self._configure_tree_columns(self._current_columns)
style_treeview(
self.tree,
style_name="Diagnostics.Treeview",
rowheight=22,
font=("", 9),
heading_font=("", 9, "bold"),
)
sy = ttk.Scrollbar(wrap, orient="vertical", command=self.tree.yview)
sx = ttk.Scrollbar(wrap, orient="horizontal", command=self.tree.xview)
self.tree.configure(yscrollcommand=sy.set, xscrollcommand=sx.set)
self.tree.grid(row=0, column=0, sticky="nsew")
sy.grid(row=0, column=1, sticky="ns")
sx.grid(row=1, column=0, sticky="ew")
def _set_status(self, text: str) -> None:
self.var_status.set(text)
def _configure_tree_columns(self, columns) -> None:
self.tree.delete(*self.tree.get_children(""))
keys = tuple(str(col[0]) for col in columns)
self.tree.configure(columns=keys, show="headings")
self._sort_column = ""
self._sort_descending = False
self._column_titles = {}
for key, locale_key, default, width, anchor in columns:
title = loc_text(str(locale_key), catalog=self._locale_catalog, default=str(default))
self._column_titles[str(key)] = title
self.tree.heading(
key,
text=title,
command=lambda col=str(key): self._sort_by_column(col),
)
self.tree.column(key, width=int(width), anchor=str(anchor), stretch=True)
def _refresh_sort_headings(self) -> None:
for key, title in self._column_titles.items():
suffix = ""
if key == self._sort_column:
suffix = " v" if self._sort_descending else " ^"
self.tree.heading(key, text=f"{title}{suffix}", command=lambda col=key: self._sort_by_column(col))
def _sort_key(self, value: Any) -> tuple[int, Any]:
text = str(value or "").strip()
if not text:
return (2, "")
normalized = text.replace(".", "").replace(",", ".")
try:
return (0, float(normalized))
except ValueError:
return (1, text.casefold())
def _sort_by_column(self, column: str) -> None:
columns = list(self.tree["columns"])
if column not in columns:
return
descending = not self._sort_descending if self._sort_column == column else False
col_index = columns.index(column)
rows = []
for iid in self.tree.get_children(""):
values = self.tree.item(iid, "values")
value = values[col_index] if col_index < len(values) else ""
rows.append((self._sort_key(value), iid))
rows.sort(key=lambda item: item[0], reverse=descending)
for index, (_key, iid) in enumerate(rows):
self.tree.move(iid, "", index)
self.tree.item(iid, tags=(zebra_tag(index),))
self._sort_column = column
self._sort_descending = descending
self._refresh_sort_headings()
def _load_shipped_not_disassociated(self) -> None:
self._run_check(
key="shipped_not_disassociated",
sql=SQL_SHIPPED_NOT_DISASSOCIATED,
columns=SHIPPED_NOT_DISASSOCIATED_COLUMNS,
busy_text=loc_text(
"diagnostics.busy.shipped_not_disassociated",
catalog=self._locale_catalog,
default="Cerco UDC spedite ma ancora in cella...",
),
)
def _load_multiple_udc_by_cell(self) -> None:
self._run_check(
key="multiple_udc_by_cell",
sql=SQL_MULTIPLE_UDC_BY_CELL,
columns=MULTIPLE_UDC_COLUMNS,
busy_text=loc_text(
"diagnostics.busy.multiple_udc_by_cell",
catalog=self._locale_catalog,
default="Cerco celle con multiple UDC...",
),
)
def _load_sam_udc_not_in_wms(self) -> None:
self._run_check(
key="sam_udc_not_in_wms",
sql=SQL_SAM_UDC_NOT_IN_WMS,
columns=SAM_UDC_NOT_IN_WMS_COLUMNS,
busy_text=loc_text(
"diagnostics.busy.sam_udc_not_in_wms",
catalog=self._locale_catalog,
default="Cerco le ultime UDC presenti in SAM ma non ancora in WMS...",
),
)
def _run_check(self, *, key: str, sql: str, columns, busy_text: str) -> None:
if self._load_in_progress or not self._is_alive():
return
async def job():
return await self.db_client.query_json(sql, as_dict_rows=True)
self._load_in_progress = True
self._current_check = key
self._last_export_slug = key
self._current_columns = columns
self._configure_tree_columns(columns)
try:
self.btn_export.configure(state="disabled")
except Exception:
pass
try:
self._busy.show(busy_text)
self._async.run(job(), self._on_loaded, self._on_error)
except Exception as exc:
self._load_in_progress = False
self._hide_busy_safe()
log_exception(__name__, exc, context=f"avvio diagnostica {key}")
messagebox.showerror(
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
str(exc),
parent=self if self._is_alive() else None,
)
def _on_loaded(self, res: dict[str, Any] | None) -> None:
self._load_in_progress = False
self._hide_busy_safe()
if not self._is_alive():
return
try:
rows = _rows_to_dicts(res)
self.tree.delete(*self.tree.get_children(""))
keys = [str(col[0]) for col in self._current_columns]
for index, row in enumerate(rows):
self.tree.insert(
"",
"end",
values=tuple(row.get(key) or "" for key in keys),
tags=(zebra_tag(index),),
)
try:
self.btn_export.configure(state="normal" if rows else "disabled")
except Exception:
pass
self._set_status(
loc_text(
"diagnostics.status.rows",
catalog=self._locale_catalog,
default="Righe trovate: {count}",
).format(count=len(rows))
)
except Exception as exc:
log_exception(__name__, exc, context="render diagnostica")
messagebox.showerror(
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
str(exc),
parent=self,
)
def _on_error(self, exc: BaseException) -> None:
self._load_in_progress = False
self._hide_busy_safe()
log_exception(__name__, exc, context=f"query diagnostica {self._current_check}")
if not self._is_alive():
return
messagebox.showerror(
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
str(exc),
parent=self,
)
def _export_xlsx(self) -> None:
"""Export the currently visible diagnostic grid to an Excel file."""
rows = [self.tree.item(iid, "values") for iid in self.tree.get_children("")]
if not rows:
messagebox.showinfo(
loc_text("diagnostics.export.title", catalog=self._locale_catalog, default="Esporta"),
loc_text(
"diagnostics.export.empty",
catalog=self._locale_catalog,
default="Non ci sono righe da esportare.",
),
parent=self,
)
return
try:
from openpyxl import Workbook
from openpyxl.styles import Alignment, Font
from openpyxl.utils import get_column_letter
except Exception as exc:
messagebox.showerror(
loc_text("diagnostics.export.title", catalog=self._locale_catalog, default="Esporta"),
loc_text(
"diagnostics.export.dep",
catalog=self._locale_catalog,
default="Per l'esportazione serve 'openpyxl' (pip install openpyxl).",
).format(error=exc),
parent=self,
)
return
ts = datetime.now().strftime("%Y%m%d_%H%M")
default_name = f"{self._last_export_slug}_{ts}.xlsx"
path = filedialog.asksaveasfilename(
parent=self,
title=loc_text("diagnostics.export.title", catalog=self._locale_catalog, default="Esporta"),
defaultextension=".xlsx",
filetypes=[("Excel Workbook", "*.xlsx")],
initialfile=default_name,
)
if not path:
return
try:
wb = Workbook()
ws = wb.active
ws.title = "Diagnostica"
columns = list(self.tree["columns"])
headers = [str(self.tree.heading(col, "text") or col) for col in columns]
for col_index, header in enumerate(headers, start=1):
cell = ws.cell(row=1, column=col_index, value=header)
cell.font = Font(bold=True)
cell.alignment = Alignment(horizontal="center", vertical="center")
for row_index, row in enumerate(rows, start=2):
for col_index, value in enumerate(row, start=1):
ws.cell(row=row_index, column=col_index, value=value)
widths: dict[int, int] = {}
for row in ws.iter_rows(values_only=True):
for col_index, value in enumerate(row, start=1):
widths[col_index] = max(widths.get(col_index, 0), len("" if value is None else str(value)))
for col_index, width in widths.items():
ws.column_dimensions[get_column_letter(col_index)].width = min(max(width + 2, 12), 70)
wb.save(path)
messagebox.showinfo(
loc_text("diagnostics.export.title", catalog=self._locale_catalog, default="Esporta"),
loc_text("diagnostics.export.ok", catalog=self._locale_catalog, default="File creato:\n{path}").format(path=path),
parent=self,
)
except Exception as exc:
log_exception(__name__, exc, context="export diagnostica xlsx")
messagebox.showerror(
loc_text("diagnostics.export.title", catalog=self._locale_catalog, default="Esporta"),
loc_text(
"diagnostics.export.error",
catalog=self._locale_catalog,
default="Errore durante l'esportazione:\n{error}",
).format(error=exc),
parent=self,
)
def open_diagnostica_window(parent: tk.Misc, db_client, session=None) -> tk.Misc:
"""Open the diagnostics window."""
win = DiagnosticaWindow(parent, db_client, session=session)
place_window_fullsize_below_parent_later(parent, win)
win.bind("<Escape>", lambda _e: win.destroy())
return win

View File

@@ -0,0 +1,235 @@
# Diagnostica Scarico Celle Multiple
## Contesto
La finestra `Scarico` aperta da `Gestione layout` serve a gestire celle fisiche che contengono piu' UDC.
Nel database legacy non esisteva un vincolo rigido `una cella = una UDC`, quindi una cella rossa puo' contenere:
- UDC realmente compresenti nella stessa cella;
- UDC rimaste in cella anche se appartenenti a picking list gia' chiuse/spedite.
L'obiettivo della diagnostica non e' ricostruire tutta la storia della UDC, ma aiutare l'operatore a capire quali righe scaricare come spedite.
## Fonti Dati
La griglia della dialog parte dalla giacenza corrente:
```sql
dbo.XMag_GiacenzaPallet
```
Questa vista indica quali UDC risultano presenti nella cella aperta dal layout.
La diagnostica controlla anche:
```sql
dbo.XMag_GiacenzaPalletPlistChiuse
```
Questa vista non e' uno storico documentale puro. E' una vista ibrida che incrocia la giacenza corrente con i documenti SAM chiusi.
In pratica serve a individuare UDC ancora presenti in una cella fisica, ma appartenenti a una picking list/documento gia' chiuso.
## Conclusione Operativa
Per una cella fisica aperta da `Gestione layout`, i casi realmente utili sono solo due.
### 1. Nessuna Diagnostica
La UDC e' presente nella cella multipla e non compare in `XMag_GiacenzaPalletPlistChiuse`.
Significato:
```text
UDC normalmente presente in cella.
```
Non viene mostrato nessun messaggio nella colonna diagnostica.
### 2. Spedita Ma Non Scaricata Dalla Cella
La UDC e' presente nella cella fisica aperta, ma compare anche in `XMag_GiacenzaPalletPlistChiuse`.
Diagnostica mostrata:
```text
Motivo: spedita ma non scaricata dalla cella
```
Significato:
```text
La UDC appartiene a una picking list chiusa, ma non e' stata scaricata dalla cella fisica.
```
Operativamente questa UDC va selezionata e scaricata come spedita, quindi verso la cella virtuale:
```text
7G.1.1 / IDCella 9999 / barcode cella 9000000
```
## Casi Teorici Scartati Dalla Dialog
Durante l'analisi erano stati ipotizzati altri casi, ma sono stati esclusi dalla diagnostica della dialog per non confondere l'operatore.
### UDC Gia' In 7G.1.1
Se una UDC risulta davvero in `IDCella = 9999`, normalmente non dovrebbe comparire nella cella fisica aperta dal layout.
Se accadesse, sarebbe un'incoerenza tra viste o dati non sincronizzati.
Per questo la dialog di scarico da layout fisico non mostra piu' il messaggio:
```text
Motivo: spedita
```
### UDC In Picking List Chiusa Ma Non Spedita
Questo caso e' teoricamente possibile ma raro e ambiguo nel modello dati attuale.
Le viste disponibili non forniscono una distinzione documentale/storica abbastanza pulita da renderlo utile in questa dialog operativa.
Per questo la dialog non mostra piu':
```text
Motivo: in plist chiusa, non spedita e non scaricata dalla cella
```
Eventuali analisi piu' profonde vanno fatte nelle finestre di storico, non nella dialog rapida di scarico.
## Regola Finale Implementata
La diagnostica della dialog `Scarico` e' volutamente semplice:
```text
se UDC in XMag_GiacenzaPalletPlistChiuse:
"Motivo: spedita ma non scaricata dalla cella"
altrimenti:
diagnostica vuota
```
Questa scelta riduce il rischio di falsi positivi e mantiene chiaro il comportamento per l'operatore.
## Aggiornamento 04/07/2026 - Barcode Picking List
Durante i test sul barcode sono state introdotte alcune modifiche operative collegate alla gestione delle picking list, agli skip UDC e alla ripresa del lavoro dopo movimenti liberi.
### Anti Autosubmit Su Cambio Lista
Problema osservato:
```text
passando rapidamente da una picking list prenotata a una non prenotata,
il barcode poteva considerare come lettura valida un valore gia' presente nel campo Pallet
e scaricare automaticamente una UDC della nuova lista.
```
Correzione implementata:
```text
lo scarico automatico in picking list parte solo se il campo Pallet e' stato modificato
dall'operatore dopo il caricamento della UDC proposta.
```
In pratica, quando il programma carica una nuova UDC attesa, il valore visualizzato non puo' piu' generare da solo lo scarico. Serve una nuova lettura o digitazione effettiva.
### Skip UDC In Picking List
Durante l'evasione di una picking list, il tasto F4 assume il significato:
```text
[F4] Salta UDC
```
La UDC saltata viene registrata nella tabella:
```sql
dbo.py_BarcodePickingListSkip
```
Le righe aperte hanno:
```text
Risolto = 0
```
La query del barcode esclude le UDC saltate aperte, quindi la lista puo' proseguire sulle UDC successive senza chiudere definitivamente quelle non trovate.
### Fine Lista Con UDC Saltate
Quando una picking list non ha piu' UDC immediatamente lavorabili, ma contiene una o piu' UDC saltate, il barcode:
```text
non chiude la picking list;
rilascia la prenotazione;
lascia la lista riprenotabile;
mostra un messaggio di sospensione con numero UDC saltate.
```
La lista resta quindi aperta e potra' essere ripresa in un secondo momento.
### Riprenotazione E Ripresa UDC Saltate
Quando la picking list viene riprenotata, gli skip aperti del documento vengono marcati come risolti:
```sql
UPDATE dbo.py_BarcodePickingListSkip
SET Risolto = 1,
RisoltoDa = <operatore>,
RisoltoDataOra = SYSDATETIME()
WHERE Documento = <documento>
AND Risolto = 0;
```
Questo permette al barcode di riproporre le UDC saltate rimaste da evadere.
### Posizione UDC Dopo Movimenti Liberi
Una UDC saltata puo' essere movimentata in pausa tramite operazioni libere, ad esempio:
```text
versamento in una nuova cella fisica;
dissociazione verso 9001000 / Non scaffalata.
```
Alla ripresa della picking list, la posizione mostrata dal barcode riflette la giacenza corrente, perche' la vista operativa deriva `Cella` e `Ubicazione` da:
```sql
dbo.XMag_GiacenzaPallet
```
Quindi una UDC prima saltata e poi spostata verra' proposta con la nuova cella, oppure come:
```text
Non scaffalata
```
se e' stata dissociata verso la locazione virtuale `9001000`.
### Regola Conservata
Resta confermata la regola operativa:
```text
una UDC diventa Spedita / 7G.1.1 / 9000000 solo nel flusso picking list.
```
Le operazioni libere non spediscono una UDC. Possono solo versarla in una cella fisica oppure metterla in `9001000 / Non scaffalata`.
### File Coinvolti
Le modifiche principali sono nei moduli:
```text
barcode_client.py
barcode_repository.py
barcode_service.py
prenota_sprenota_sql.py
version_info.py
```
La patch DB cumulativa da usare sul database online e':
```text
apply_online_python_wms_full_patch.sql
```
La patch contiene gli oggetti SQL necessari al ramo Python e puo' essere eseguita una sola volta da SSMS.

44
docs/review/README.md Normal file
View File

@@ -0,0 +1,44 @@
# Documentazione review Warehouse / FlyWMS bridge
Questa cartella contiene la documentazione tecnica destinata alla review del codice Python e SQL.
## Obiettivi
- Descrivere il processo logico implementato da ogni modulo.
- Documentare firme, parametri, ritorni e responsabilita' di funzioni e classi.
- Documentare SQL, viste, stored procedure, tabelle coinvolte ed effetti collaterali.
- Aggiungere commenti inline nel codice solo dove il comportamento non e' auto-evidente.
## Criterio di documentazione
La documentazione e' divisa in tre livelli.
1. Processo logico: flussi operativi, eventi UI, query, effetti sul database.
2. API interna: classi, funzioni, parametri, valori di ritorno, errori, dipendenze.
3. Dettaglio implementativo: strutture dati, cicli, dedupliche, transazioni, side effect.
## Ambito escluso
Questa review non considera:
- `__pycache__`
- log applicativi
- zip di distribuzione
- cartelle `_package_*`
- cartella `trash`
- build HTML generata in `docs/_build`
## Primo lotto documentato
- [Modulo storico picking list](module_storico_pickinglist.md)
- [SQL storico picking list](sql_storico_pickinglist.md)
- [Modulo gestione picking list](module_gestione_pickinglist.md)
- [Modulo prenota/sprenota SQL](module_prenota_sprenota_sql.md)
- [SQL prenotazione picking list](sql_pickinglist_reservation.md)
## Prossimi lotti consigliati
1. `gestione_scarico.py`
2. `barcode_service.py` e `barcode_repository.py`
3. `main.py`, `login_window.py`, `db_config.py`
4. Moduli di visualizzazione: `gestione_layout.py`, `reset_corsie.py`, `search_pallets.py`, `view_celle_multi_udc.py`

View File

@@ -0,0 +1,68 @@
# Barcode: logging errori e transazioni
## Problema rilevato
Durante uno scarico picking list dal lettore barcode, l'operazione DB e' arrivata a buon fine ma il client ha mostrato un'eccezione. I file standard output/error erano vuoti.
Con `pythonw` non e' sufficiente affidarsi a stdout/stderr: eccezioni Tk, future asincrone o callback possono non arrivare al wrapper principale.
## Strategia adottata
Il client barcode ora registra errori in modo esplicito su `warehouse_fatal.log` e su `barcode_wms_launch.log`.
Canali coperti:
- `sys.excepthook`
- `threading.excepthook`
- `Tk.report_callback_exception`
- exception handler del loop `asyncio`
- eccezioni delle operazioni asincrone barcode
- errori del repository durante movimento DB
- errori post-movimento durante ricostruzione stato UI
## Transazione movimento DB
Il movimento barcode passa da `BarcodeRepository.execute_legacy_move`.
La batch SQL usa:
```sql
SET XACT_ABORT ON;
```
ed e' eseguita con:
```python
query_json(..., commit=True)
```
Questo significa:
- successo: commit;
- eccezione SQL/Python: rollback automatico della transazione SQLAlchemy;
- il valore `@RC` restituito dalla stored legacy non viene interpretato come errore.
Nota importante: in `sp_xMagGestioneMagazziniPallet`, quando il movimento va a buon fine, `@RC` viene valorizzato con `@@IDENTITY`, cioe' con l'identificativo del movimento inserito. Quindi un valore diverso da zero e' compatibile con un movimento riuscito e non deve causare rollback.
## Distinzione tra movimento e refresh UI
Dopo un movimento riuscito, il service ricostruisce il messaggio UI interrogando picking list e tracciabilita'.
Se questa fase post-movimento fallisce:
- il movimento resta valido;
- l'errore viene loggato;
- l'utente vede `Movimento eseguito. Dettagli non aggiornati.`;
- non viene mostrato il messaggio "transazione non completata".
Se invece fallisce la transazione vera:
- l'utente vede `Transazione non completata, ripeti l'operazione.`;
- il dettaglio tecnico viene scritto nel log.
## File principali
- `runtime_support.py`
- `barcode_client.py`
- `barcode_repository.py`
- `barcode_service.py`

View File

@@ -0,0 +1,119 @@
# Piano operativo documentazione review
## Strategia
La documentazione viene prodotta per lotti piccoli e verificabili. Ogni lotto deve contenere:
- descrizione del processo logico;
- tabella firme funzioni/classi;
- documentazione SQL collegata;
- eventuali commenti inline mirati;
- compilazione Python dei moduli modificati.
## Lotto 1 - Storico picking list
Stato: completato.
File documentati:
- `storico_pickinglist.py`
- `apply_python_pickinglist_history_views.sql`
- `apply_online_history_forms_patch.sql`
- query runtime `SQL_STORICO_PL`
- query runtime `SQL_STORICO_PL_DETAILS`
- movimento collegato `move_pallet_async`
Motivo priorita:
- contiene una nuova funzione con effetti sul database;
- gestisce casi critici `Chiusa ERP con residui`;
- usa convenzioni operative `1000 / Non scaff.` e `9999 / 7G.1.1`.
## Lotto 2 - Gestione picking list
Stato: completato.
File target:
- `gestione_pickinglist.py`
- `prenota_sprenota_sql.py`
- `apply_python_parallel_pickinglist_patch.sql`
- `rollback_python_parallel_pickinglist_patch.sql`
Aspetti da documentare:
- prenotazione/sprenotazione Python-only;
- differenza tra vista residua e vista storica;
- aggiornamento griglia alta/bassa;
- stato `IDStato`;
- separazione da C# legacy;
- limiti concorrenza.
## Lotto 3 - Movimento UDC e scarico
File target:
- `gestione_scarico.py`
- `storico_udc.py`
Aspetti da documentare:
- batch `SQL_SCARICA_UDC`;
- movimento `P` e `V`;
- audit utenti/date;
- cella source e target;
- fallback SPED in storico UDC.
## Lotto 4 - Barcode
File target:
- `barcode_client.py`
- `barcode_service.py`
- `barcode_repository.py`
Aspetti da documentare:
- stati operativi del barcode;
- F1/F2 e priorita picking list;
- gestione `9000000`;
- mappatura 1:1 con comportamento C#;
- stabilita di connessione DB.
## Lotto 5 - Avvio, autenticazione e configurazione
File target:
- `main.py`
- `login_window.py`
- `db_config.py`
- `runtime_support.py`
- `user_session.py`
Aspetti da documentare:
- single instance;
- login operatore;
- creazione configurazione DB;
- gestione errori in `pythonw`;
- shutdown ordinato.
## Lotto 6 - Visualizzazioni operative
File target:
- `gestione_layout.py`
- `reset_corsie.py`
- `search_pallets.py`
- `view_celle_multi_udc.py`
- `ui_tables.py`
- `ui_theme.py`
Aspetti da documentare:
- griglie e layout;
- query diagnostiche;
- overlay async;
- colori semantici;
- export XLSX;
- bonifica UDC fantasma.

View File

@@ -0,0 +1,154 @@
# Modulo `gestione_pickinglist.py`
## Scopo
Il modulo implementa la finestra operativa "Gestione Picking List". La finestra serve al backoffice/magazzino per:
- visualizzare le picking list ancora lavorabili;
- selezionare una sola lista alla volta;
- visualizzare le UDC residue della lista selezionata;
- prenotare una lista per darle priorita' alta sul barcode;
- s-prenotare la lista correntemente prenotata;
- mantenere UI reattiva tramite query asincrone, overlay e spinner.
La finestra lavora sulla vista residuale `dbo.py_ViewPackingListRestante`, quindi mostra cio' che resta da scaricare, non necessariamente il documento ERP completo. Il documento completo e' invece esposto dalla form "Storico Picking List".
## Processo logico
### Apertura finestra
1. `open_pickinglist_window` crea o riporta in primo piano una singola finestra.
2. La finestra viene inizialmente nascosta con `withdraw` e alpha `0.0`.
3. Viene creato `GestionePickingListFrame`.
4. Dopo la stabilizzazione layout, `_first_show` avvia il primo caricamento.
5. La finestra viene mostrata solo quando il layout e' pronto, riducendo flicker.
### Caricamento lista alta
1. `reload_from_db` esegue `SQL_PL`.
2. `SQL_PL` legge da `dbo.py_ViewPackingListRestante`.
3. Il risultato viene normalizzato con `_rows_to_dicts`.
4. `_refresh_mid_rows` ricrea la tabella alta.
5. Ogni riga e' rappresentata da un `PLRow`, che incapsula dizionario dati e checkbox.
### Selezione lista
1. Il click sul checkbox chiama `on_row_checked`.
2. La selezione e' esclusiva: eventuali altre righe selezionate vengono deselezionate.
3. Il documento selezionato viene salvato in `detail_doc`.
4. Viene eseguita `SQL_PL_DETAILS`.
5. Il dettaglio viene messo in cache in `_detail_cache`.
6. `_refresh_details_incremental` ordina e renderizza il dettaglio con `tksheet`.
### Ricarica
`reload_from_db` preserva il documento selezionato quando possibile. Questo e' importante per il caso operativo in cui il barcode sta scaricando UDC mentre l'operatore aggiorna la finestra.
Flusso:
1. `_selected_documento_for_reload` determina il documento da mantenere.
2. La griglia alta viene ricaricata.
3. `_reselect_documento_after_reload` riseleziona la stessa lista se ancora presente.
4. Il dettaglio viene ricaricato dalla vista residuale.
### Prenotazione
1. `on_prenota` verifica il permesso `pickinglist.prenota`.
2. Richiede una riga selezionata.
3. Se `IDStato == 1`, l'operazione e' no-op.
4. Verifica sessione operatore valida.
5. Chiama `sp_xExePackingListPallet_async(..., Azione="P")`.
6. Se `rc == 0`, logga audit e ricarica la griglia mantenendo il documento.
### S-prenotazione
1. `on_sprenota` verifica il permesso `pickinglist.sprenota`.
2. Richiede una riga selezionata.
3. Se `IDStato == 0`, l'operazione e' no-op.
4. Chiama `sp_xExePackingListPallet_async(..., Azione="S")`.
5. Se `rc == 0`, logga audit e ricarica.
## Semantica operativa
La UI non implementa toggle implicito. I pulsanti hanno semantica esplicita:
| Pulsante | Effetto |
| --- | --- |
| `Prenota` | porta la lista selezionata a priorita' alta se non gia' prenotata |
| `S-prenota` | libera la lista selezionata se e' la lista attiva |
Premere piu' volte `Prenota` sulla stessa lista gia' prenotata non la libera. Premere piu' volte `S-prenota` su lista non prenotata non la prenota.
## Strutture dati principali
| Nome | Tipo | Ruolo |
| --- | --- | --- |
| `rows_models` | `list[PLRow]` | modelli riga della griglia alta |
| `_detail_cache` | `dict[Any, list]` | cache righe dettaglio per documento |
| `detail_doc` | `Any` | documento correntemente selezionato |
| `_detail_sort_key` | `str | None` | colonna dettaglio ordinata |
| `_detail_sort_reverse` | `bool` | verso ordinamento dettaglio |
| `pl_table` | `ScrollTable` | tabella custom griglia alta |
| `detail_sheet` | `tksheet.Sheet` | griglia dettaglio ad alto volume |
| `spinner` | `ToolbarSpinner` | feedback leggero toolbar |
| `busy` | `InlineBusyOverlay` | overlay query/operazioni lente |
## Funzioni e classi principali
| Oggetto | Firma | Ruolo |
| --- | --- | --- |
| `_rows_to_dicts` | `_rows_to_dicts(res: Dict[str, Any]) -> List[Dict[str, Any]]` | normalizza payload DB |
| `_s` | `_s(v) -> str` | converte `None` in stringa vuota |
| `_first` | `_first(d: Dict[str, Any], keys: List[str], default: str = "")` | estrae il primo campo valorizzato |
| `ColSpec` | `dataclass(title, key, width, anchor)` | descrive una colonna tabellare |
| `ToolbarSpinner` | classe | animazione leggera toolbar |
| `ScrollTable` | classe | tabella custom per griglia alta |
| `PLRow` | classe | modello riga PL + checkbox |
| `GestionePickingListFrame` | classe | frame principale |
| `_build_detail_sheet` | `_build_detail_sheet(self)` | crea tksheet dettaglio |
| `_detail_rows_to_sheet_data` | `_detail_rows_to_sheet_data(self, rows)` | converte righe DB in righe tksheet |
| `_load_detail_sheet_data` | `_load_detail_sheet_data(self, data)` | applica headers, dati e zebra |
| `_refresh_mid_rows` | `_refresh_mid_rows(self, rows)` | ricrea griglia alta |
| `_get_selected_model` | `_get_selected_model(self) -> Optional[PLRow]` | ritorna riga selezionata |
| `on_row_checked` | `on_row_checked(self, model: PLRow, is_checked: bool)` | carica dettaglio della lista |
| `reload_from_db` | `reload_from_db(self, first=False, reselect_documento=None)` | aggiorna griglia alta |
| `_refresh_details` | `_refresh_details(self)` | ridisegna dettaglio da cache |
| `_refresh_details_incremental` | `_refresh_details_incremental(self, batch_size=25)` | render dettaglio con overlay |
| `on_prenota` | `on_prenota(self)` | prenota lista selezionata |
| `on_sprenota` | `on_sprenota(self)` | s-prenota lista selezionata |
| `create_frame` | `create_frame(parent, *, db_client=None, conn_str=None, session=None)` | factory frame |
| `open_pickinglist_window` | `open_pickinglist_window(parent, db_client, session=None) -> tk.Misc` | entry point finestra |
## Query runtime
### `SQL_PL`
Aggrega `dbo.py_ViewPackingListRestante` per documento. Conta UDC con:
```sql
COUNT(DISTINCT NULLIF(LTRIM(RTRIM(CAST(Pallet AS varchar(32)))), '')) AS Pallet
```
Questo evita il doppio conteggio di UDC multi-lotto.
### `SQL_PL_DETAILS`
Ritorna tutte le righe residuali della lista selezionata, ordinate per `Ordinamento`.
## Effetti sul database
Il modulo UI non aggiorna direttamente tabelle. Tutte le modifiche passano da `sp_xExePackingListPallet_async`, che esegue `dbo.py_sp_xExePackingListPallet`.
Effetti indiretti:
- aggiorna `dbo.PyPickingListReservation`;
- aggiorna `dbo.Celle.IDStato`;
- scrive audit applicativo con `log_user_action`;
- la stored puo' scrivere log legacy tramite `sp_LogPackingList`.
## Rischi e note review
- La vista residuale cambia mentre il barcode scarica UDC: per questo `Ricarica` conserva la selezione e ricarica il dettaglio.
- La tabella alta e il dettaglio possono non avere lo stesso numero di righe dello storico, perche' qui si vedono solo residui.
- La convivenza C#/Python dipende dalla presenza degli oggetti `py_*`.
- La selezione e' esclusiva lato UI, ma il secondo livello F2 barcode dipende dalla logica barcode/stato DB, non da una seconda prenotazione backoffice.

View File

@@ -0,0 +1,97 @@
# Modulo `prenota_sprenota_sql.py`
## Scopo
Il modulo contiene il port asincrono della stored procedure di prenotazione picking list. E' il ponte tra la UI Python e la stored SQL Python-only `dbo.py_sp_xExePackingListPallet`.
La funzione pubblica principale e':
```python
async def sp_xExePackingListPallet_async(db, IDOperatore: int, Documento: str, Azione: str = "P") -> SPResult
```
## Motivazione
Durante la fase di test sul campo devono convivere:
- applicazione C# legacy;
- applicazione Python.
Per evitare collisioni, il Python non chiama `dbo.sp_xExePackingListPallet` legacy ma `dbo.py_sp_xExePackingListPallet`.
## Semantica parametro `Azione`
| Azione | Significato |
| --- | --- |
| `P` | prenota il documento |
| `S` | s-prenota il documento |
Ogni altra azione ritorna:
```python
SPResult(rc=-10, message="Azione non valida: ...")
```
## Classe `SPResult`
Firma:
```python
@dataclass
class SPResult:
rc: int = 0
message: Optional[str] = ""
id_result: Optional[int] = None
```
Campi:
| Campo | Ruolo |
| --- | --- |
| `rc` | codice ritorno della stored |
| `message` | messaggio errore o vuoto |
| `id_result` | predisposizione per ID risultato, non usato oggi |
## Funzioni helper
| Funzione | Firma | Ruolo |
| --- | --- | --- |
| `_query_one_value` | `_query_one_value(db, sql: str, params: Dict[str, Any]) -> Optional[Any]` | helper generico scalar, oggi non centrale nel flusso |
| `_query_all` | `_query_all(db, sql: str, params: Dict[str, Any]) -> List[Dict[str, Any]]` | normalizza query multi-riga |
| `_execute` | `_execute(db, sql: str, params: Dict[str, Any]) -> int` | helper generico DML |
| `sp_xExePackingListPallet_async` | vedi sopra | esegue stored Python-only |
## Processo logico `sp_xExePackingListPallet_async`
1. Normalizza `Azione` a maiuscolo.
2. Valida `Azione in ("P", "S")`.
3. Costruisce una batch SQL con output parameter `@RC`.
4. Esegue:
```sql
EXEC dbo.py_sp_xExePackingListPallet
@IDOperatore = :IDOperatore,
@Documento = :Documento,
@Azione = :Azione,
@RC = @RC OUTPUT;
```
5. Legge il valore `RC`.
6. Ritorna `SPResult(rc=rc, message="", id_result=None)`.
7. In caso di eccezione ritorna `SPResult(rc=-1, message=str(exc), id_result=None)`.
## Commit
La chiamata usa:
```python
commit=True
```
Motivo: la stored modifica `PyPickingListReservation` e `Celle.IDStato`.
## Rischi e note review
- Gli helper `_query_one_value`, `_query_all`, `_execute` sono generici e non tutti sono essenziali al percorso attuale.
- La funzione cattura le eccezioni e ritorna `SPResult(rc=-1)`, quindi la UI deve controllare sempre `rc`.
- La transazione reale dipende dal comportamento di `query_json(..., commit=True)` nel client DB.

View File

@@ -0,0 +1,150 @@
# Modulo `storico_pickinglist.py`
## Scopo
Il modulo implementa la finestra "Storico Picking List". La finestra permette di:
- cercare picking list storiche per numero documento;
- visualizzare lo stato operativo sintetico di ciascuna lista;
- visualizzare il dettaglio UDC/lotto/articolo della lista selezionata;
- evidenziare liste chiuse, liste attive e casi anomali;
- versare in blocco in `7G.1.1` le UDC residue di una lista classificata come `Chiusa ERP con residui`.
Il modulo legge da viste SQL dedicate al ramo Python. Non usa le viste legacy C# per evitare collisioni durante il periodo in cui i due programmi convivono sullo stesso database.
## Dipendenze principali
- `customtkinter` e `tkinter.ttk`: UI e griglie.
- `AsyncRunner`: esecuzione asincrona delle query senza bloccare la GUI.
- `InlineBusyOverlay`: indicatore visivo durante query e movimenti.
- `move_pallet_async`: funzione centrale per registrare un movimento UDC verso una cella.
- `ui_tables`: stile comune delle griglie.
- `version_info`: versione visibile nel titolo finestra.
- `window_placement`: posizionamento della finestra rispetto al launcher.
## Processo logico
### Apertura finestra
1. `open_storico_pickinglist_window(parent, db_client, session)` crea `StoricoPickingListWindow`.
2. La finestra viene posizionata sotto il launcher con `place_window_fullsize_below_parent_later`.
3. Dopo 300 ms viene chiamato `_load_master`.
### Caricamento griglia alta
1. `_load_master` legge il filtro `Documento`.
2. Viene eseguita `SQL_STORICO_PL`.
3. `_rows_to_dicts` normalizza il payload del DB.
4. `_fill_master` svuota griglia alta e dettaglio.
5. Per ogni documento viene calcolato il tag visuale:
- `warning` se lista aperta con UDC gia' spedite;
- `done` se lista chiusa o esaurita;
- `active` se lista prenotata;
- zebra tag per alternanza righe.
6. La riga viene inserita nella griglia alta.
### Selezione documento
1. `_on_master_select` legge la riga selezionata.
2. Memorizza:
- `_selected_documento`
- `_selected_stato_operativo`
- `_detail_rows`
3. Abilita o disabilita il pulsante "Versa residui in 7G.1.1".
4. Esegue `SQL_STORICO_PL_DETAILS`.
5. `_fill_detail` carica la griglia bassa.
### Versamento residui in 7G.1.1
Il pulsante e' abilitato solo se `_selected_stato_operativo == "Chiusa ERP con residui"`.
Flusso:
1. `_ship_selected_residuals` verifica lo stato selezionato.
2. Calcola una stima delle UDC residue gia' presenti nel dettaglio UI.
3. Mostra una conferma all'operatore.
4. Dentro il job asincrono rilegge il dettaglio dal DB, cosi' evita dati UI obsoleti.
5. `_residual_pallets_from_rows` deduplica le UDC e scarta quelle gia' in `IDCella = 9999`.
6. Per ogni UDC residua chiama `move_pallet_async` con:
- `target_idcella = 9999`
- `target_barcode_cella = "9000000"`
- `utente = login sessione` oppure `warehouse_ui`
7. Al termine mostra un riepilogo.
8. Ricarica la griglia alta e tenta di ripristinare la selezione del documento.
## Stati operativi
La colonna `Stato` della griglia alta deriva da SQL:
| Stato operativo | Condizione |
| --- | --- |
| `Chiusa ERP con residui` | `StatoDocumento = 'D'` e almeno una UDC non e' in `9999` |
| `Chiusa` | `StatoDocumento = 'D'` e nessuna UDC residua |
| `Esaurita` | tutte le UDC risultano spedite |
| `In corso` | almeno una UDC e' spedita e almeno una resta da lavorare |
| `Da lavorare` | nessuna UDC ancora spedita |
## Strutture dati interne
| Nome | Tipo | Ruolo |
| --- | --- | --- |
| `var_documento` | `tk.StringVar` | filtro documento digitato dall'utente |
| `_selected_documento` | `str | None` | documento correntemente selezionato |
| `_selected_stato_operativo` | `str` | stato operativo della riga selezionata |
| `_detail_rows` | `list[dict[str, Any]]` | ultimo dettaglio normalizzato caricato nella griglia bassa |
| `master_tree` | `ttk.Treeview` | griglia alta documenti |
| `detail_tree` | `ttk.Treeview` | griglia bassa righe UDC |
| `btn_ship_residuals` | `ctk.CTkButton` | azione di versamento massivo residui |
## Funzioni e classi
| Oggetto | Firma | Ruolo |
| --- | --- | --- |
| `_rows_to_dicts` | `_rows_to_dicts(res: dict[str, Any] | None) -> list[dict[str, Any]]` | normalizza payload DB in lista di dizionari |
| `_format_date` | `_format_date(value: Any) -> str` | converte date SQL/SAMA in `dd/mm/yyyy` |
| `StoricoPickingListWindow.__init__` | `__init__(self, parent: tk.Widget, db_client, session=None)` | costruisce stato, tema, runner async e UI |
| `_build_ui` | `_build_ui(self) -> None` | crea toolbar, griglia alta e griglia dettaglio |
| `_make_tree` | `_make_tree(self, *, row: int, columns: tuple[str, ...], widths: dict[str, int]) -> ttk.Treeview` | factory griglia con stile comune |
| `_load_master` | `_load_master(self) -> None` | lancia query master asincrona |
| `_fill_master` | `_fill_master(self, rows: list[dict[str, Any]]) -> None` | popola griglia alta |
| `_on_master_select` | `_on_master_select(self, _event=None) -> None` | gestisce selezione documento e carica dettaglio |
| `_fill_detail` | `_fill_detail(self, rows: list[dict[str, Any]]) -> None` | popola griglia bassa |
| `_update_residual_button` | `_update_residual_button(self) -> None` | abilita azione solo su `Chiusa ERP con residui` |
| `_restore_master_selection` | `_restore_master_selection(self, documento: str) -> None` | riseleziona documento dopo reload |
| `_residual_pallets_from_rows` | `_residual_pallets_from_rows(self, rows: list[dict[str, Any]]) -> list[str]` | deduplica UDC residue non gia' spedite |
| `_operator_login` | `_operator_login(self) -> str` | determina utente per movimenti |
| `_ship_selected_residuals` | `_ship_selected_residuals(self) -> None` | esegue versamento massivo verso `7G.1.1` |
| `open_storico_pickinglist_window` | `open_storico_pickinglist_window(parent: tk.Misc, db_client, session=None) -> tk.Misc` | entry point chiamato dal launcher |
## Effetti sul database
Il modulo e' in sola lettura tranne `_ship_selected_residuals`.
`_ship_selected_residuals` non esegue SQL diretto di update. Delega ogni UDC a `move_pallet_async`, che:
- trova l'ultimo movimento `V` positivo della UDC;
- aggiorna `ModUtente` e `ModDataOra` della riga sorgente;
- inserisce un movimento `P` sulla cella sorgente;
- libera `Celle.IDStato` della cella sorgente;
- inserisce un movimento `V` sulla cella target `9999`;
- esegue `dbo.py_sp_ControllaPrenotazionePackingListPalletNew`.
## Rischi e note review
- Il versamento massivo non e' atomico a livello di intera lista: ogni UDC viene movimentata con una chiamata separata. Se una UDC fallisce, quelle precedenti potrebbero essere gia' state registrate.
- La rilettura del dettaglio riduce il rischio di dato UI obsoleto, ma non sostituisce un lock transazionale su documento.
- Le UDC multi-lotto sono deduplicate per `Pallet`, per evitare doppio movimento fisico.
- Le UDC gia' in `9999` vengono saltate.
- Le UDC non scaffalate risultano `IDCella = 1000`; vengono considerate residue e quindi movimentate verso `9999`.
## Test consigliati
1. Selezionare una lista `Da lavorare`: il pulsante deve restare disabilitato.
2. Selezionare una lista `Chiusa`: il pulsante deve restare disabilitato.
3. Selezionare una lista `Chiusa ERP con residui`: il pulsante deve abilitarsi.
4. Confermare il versamento su una lista con UDC non scaffalate.
5. Verificare in `Storico movimenti UDC` che ogni UDC abbia:
- ultimo passaggio sorgente;
- movimento `P` sulla sorgente;
- movimento `V` su `9999 / 7G.1.1`.
6. Ricaricare lo storico picking list: la lista non deve piu' risultare con residui se tutte le UDC sono in `9999`.

View File

@@ -0,0 +1,153 @@
# SQL prenotazione picking list Python-only
## Script
- `apply_python_parallel_pickinglist_patch.sql`
- `rollback_python_parallel_pickinglist_patch.sql`
## Obiettivo
Permettere a Python e C# di lavorare sullo stesso database senza condividere le stesse stored procedure operative.
Il C# continua a usare gli oggetti legacy:
- `dbo.XMag_ViewPackingList`
- `dbo.ViewPackingListRestante`
- `dbo.sp_xExePackingListPallet`
- `dbo.sp_xExePackingListPalletPrenota`
- `dbo.sp_ControllaPrenotazionePackingListPalletNew`
Il Python usa oggetti separati:
- `dbo.py_XMag_ViewPackingList`
- `dbo.py_ViewPackingListRestante`
- `dbo.py_sp_xExePackingListPallet`
- `dbo.py_sp_xExePackingListPalletPrenota`
- `dbo.py_sp_ControllaPrenotazionePackingListPalletNew`
- `dbo.PyPickingListReservation`
## Tabella `dbo.PyPickingListReservation`
### Scopo
Contiene la singola picking list prenotata dal programma Python.
### Schema
| Colonna | Tipo | Ruolo |
| --- | --- | --- |
| `ID` | `tinyint` | sempre `1`, enforced da check constraint |
| `Documento` | `varchar(8)` | documento prenotato |
| `IDOperatore` | `int` | operatore che ha fatto l'ultima azione |
| `ModUtente` | `varchar(50)` | login operatore |
| `ModDataOra` | `datetime` | timestamp modifica |
### Vincoli
- Primary key su `ID`.
- Check `ID = 1`.
Questa scelta implementa un singleton DB: il Python puo' avere una sola lista prenotata dal backoffice.
## Vista `dbo.py_XMag_ViewPackingList`
### Scopo
Replica la vista legacy `dbo.XMag_ViewPackingList` ma calcola `IDStato` usando `PyPickingListReservation`, non `Celle.IDStato` legacy.
### Logica `IDStato`
```sql
CASE
WHEN pr.Documento IS NOT NULL
AND pr.Documento = CAST(legacy.Documento AS varchar(8))
THEN 1
ELSE 0
END AS IDStato
```
## Vista `dbo.py_ViewPackingListRestante`
### Scopo
Espone solo le UDC non ancora spedite:
```sql
WHERE Cella <> 9999
```
La UI "Gestione Picking List" usa questa vista sia per la griglia alta sia per il dettaglio.
## Stored `dbo.py_sp_xExePackingListPallet`
### Parametri
| Parametro | Tipo | Ruolo |
| --- | --- | --- |
| `@IDOperatore` | `int` | operatore corrente |
| `@Documento` | `varchar(8)` | documento da prenotare/sprenotare |
| `@Azione` | `char(1)` | `P` prenota, `S` s-prenota |
| `@RC` | `int OUTPUT` | codice ritorno |
### Validazioni
- `@Azione` deve essere `P` o `S`, altrimenti `@RC = -10`.
- Il documento deve esistere in `py_XMag_ViewPackingList`, altrimenti `@RC = -20`.
- Se manca la riga singleton in `PyPickingListReservation`, viene creata.
### Prenotazione `P`
1. Se il documento e' gia' attivo, ritorna senza modifiche.
2. Azzera `IDStato` su tutte le celle con stato diverso da zero.
3. Mette `IDStato = 1` sulle celle del documento target.
4. Aggiorna `PyPickingListReservation` con documento, operatore e timestamp.
5. Scrive log tramite `sp_LogPackingList`.
### S-prenotazione `S`
1. Se il documento attivo non e' quello richiesto, ritorna senza modifiche.
2. Azzera `IDStato` sulle celle target.
3. Pulisce `PyPickingListReservation.Documento`.
## Stored `dbo.py_sp_xExePackingListPalletPrenota`
### Scopo
Mette `IDStato = 1` sulle celle ancora residue del documento. Viene usata dal controllo automatico prenotazione.
## Stored `dbo.py_sp_ControllaPrenotazionePackingListPalletNew`
### Scopo
Mantiene coerente la prenotazione mentre la picking list viene consumata dal barcode.
### Logica
1. Legge documento attivo da `PyPickingListReservation`.
2. Se non c'e' documento attivo, termina.
3. Se non esistono piu' righe residue in `py_ViewPackingListRestante`:
- azzera `Celle.IDStato`;
- svuota `PyPickingListReservation.Documento`;
- termina.
4. Se esistono ancora residui:
- azzera tutti gli `IDStato`;
- richiama `py_sp_xExePackingListPalletPrenota` per prenotare le celle residue.
## Rollback
`rollback_python_parallel_pickinglist_patch.sql` elimina:
- `py_sp_ControllaPrenotazionePackingListPalletNew`
- `py_sp_xExePackingListPalletPrenota`
- `py_sp_xExePackingListPallet`
- `py_ViewPackingListRestante`
- `py_XMag_ViewPackingList`
- `PyPickingListReservation`
Non tocca gli oggetti legacy C#.
## Note review
- La stored Python usa una prenotazione singleton, quindi non gestisce due liste prenotate backoffice.
- L'azzeramento globale di `Celle.IDStato` e' coerente con la semantica attuale, ma in futuro dovra' essere rivalutato se piu' operatori o magazzini lavorano in parallelo.
- Le UDC non scaffalate condividono il fallback dati del modello legacy; questo e' noto e andra' riprogettato nel nuovo schema FlyWMS.

View File

@@ -0,0 +1,236 @@
# SQL storico picking list
## Oggetti SQL coinvolti
La form "Storico Picking List" usa un ramo SQL Python-only:
- `dbo.py_vPreparaPackingListSAMA1`
- `dbo.py_vPreparaPackingList`
- `dbo.py_XMag_ViewPackingListStorico`
- `dbo.PyPickingListReservation`
Gli script principali sono:
- `apply_python_pickinglist_history_views.sql`
- `apply_online_history_forms_patch.sql`
- `rollback_python_pickinglist_history_views.sql`
- `rollback_online_history_forms_patch.sql`
## Motivazione del ramo Python-only
Il progetto deve convivere temporaneamente con l'applicazione C# legacy. Per questo lo storico Python non modifica:
- `dbo.vPreparaPackingListSAMA1`
- `dbo.vPreparaPackingList`
- `dbo.XMag_ViewPackingList`
- stored procedure legacy C#
Le viste prefissate `py_` permettono di evolvere il comportamento Python senza cambiare la semantica legacy.
## Vista `dbo.py_vPreparaPackingListSAMA1`
### Scopo
Legge dal database ERP `SAMA1` le informazioni documentali e di riga necessarie a ricostruire la picking list.
### Tabelle ERP coinvolte
- `SAMA1.dbo.LOTSER`
- `SAMA1.dbo.ARTICO`
- `SAMA1.dbo.FATRIG`
- `SAMA1.dbo.LOTTIBF`
- `SAMA1.dbo.BAMTES`
- `SAMA1.dbo.NAZIONI`
- `SAMA1.sam.EXTUC`
- `SAMA1.dbo.MTRASP`
### Campi principali
| Campo | Significato |
| --- | --- |
| `NUMLOT` | lotto |
| `CODICE` | codice articolo |
| `DESCR` | descrizione riga/articolo |
| `UDC` | prime 6 cifre di `LOTSER.NUMSER` |
| `Qta` | somma quantita giacente ERP |
| `NUMDOC` | numero documento/picking list |
| `DATDOC` | data documento ERP |
| `StatoDocumento` | stato ERP, filtrato su `P` o `D` |
| `NAZIONE` | trasporto + descrizione nazione |
### Filtri
- anno documento >= anno corrente;
- stato documento in `P`, `D`;
- lotto diverso da `00000000000`.
## Vista `dbo.py_vPreparaPackingList`
### Scopo
E' una vista di pulizia sopra `py_vPreparaPackingListSAMA1`.
### Filtro
Esclude righe con `NUMLOT = ''`.
## Vista `dbo.py_XMag_ViewPackingListStorico`
### Scopo
Unisce il contenuto ERP della picking list con la posizione WMS corrente della UDC.
### Tabelle WMS coinvolte
- `dbo.XMag_GiacenzaPallet`
- `dbo.Celle`
- `dbo.Aree`
- `dbo.PyPickingListReservation`
### Join principale
La vista usa una `RIGHT OUTER JOIN` tra posizione WMS e preparazione ERP:
```sql
RIGHT OUTER JOIN dbo.py_vPreparaPackingList prep
ON g.BarcodePallet COLLATE SQL_Latin1_General_CP1_CI_AS = prep.UDC
```
Questo garantisce che una UDC presente nella picking list ERP compaia anche se non e' scaffalata nel WMS.
### Convenzioni celle
| IDCella | Ubicazione | Significato |
| --- | --- | --- |
| `9999` | `7G - 1 - 1` | spedizione / UDC scaricata |
| `1000` | `Non scaff.` | fallback per UDC non trovata in `XMag_GiacenzaPallet` |
La vista usa:
```sql
ISNULL(g.IDCella, 1000) AS Cella
ISNULL(c.Corsia + ' - ' + c.Colonna + ' - ' + c.Fila, 'Non scaff.') AS Ubicazione
```
Quindi le UDC ERP non presenti in giacenza WMS sono rappresentate come non scaffalate.
## Query Python `SQL_STORICO_PL`
### Scopo
Costruisce la griglia alta della form.
### CTE
| CTE | Ruolo |
| --- | --- |
| `base` | normalizza `Pallet` in `PalletKey` |
| `pallets` | aggrega righe multi-lotto per singola UDC |
| `meta` | calcola metadati documento |
| `agg` | calcola totale UDC, UDC spedite e UDC residue |
### Stato operativo
La query produce `StatoOperativo` con questa logica:
```sql
CASE
WHEN m.StatoDocumento = 'D' AND COALESCE(a.RigheResidue, 0) > 0 THEN 'Chiusa ERP con residui'
WHEN m.StatoDocumento = 'D' THEN 'Chiusa'
WHEN COALESCE(a.RigheResidue, 0) = 0 THEN 'Esaurita'
WHEN COALESCE(a.RigheSpedite, 0) > 0 THEN 'In corso'
ELSE 'Da lavorare'
END
```
### Deduplica UDC
La deduplica avviene su `PalletKey`, non sulle righe. Questo evita che una UDC con piu' lotti venga contata come piu' pallet.
## Query Python `SQL_STORICO_PL_DETAILS`
### Scopo
Costruisce la griglia bassa della form.
### Output
| Campo | Ruolo |
| --- | --- |
| `Documento` | numero picking list |
| `Pallet` | UDC fisica |
| `Lotto` | lotto |
| `Articolo` | codice articolo |
| `Descrizione` | descrizione articolo/riga |
| `Qta` | quantita |
| `DataDocumento` | data ERP |
| `StatoDocumento` | stato ERP |
| `Cella` | cella WMS corrente/fallback |
| `Ubicazione` | descrizione cella |
| `Ordinamento` | ordine operativo |
| `IDStato` | prenotazione Python |
## Effetti SQL del versamento residui
La form non contiene direttamente update/insert SQL per il versamento residui. Chiama `move_pallet_async` in `gestione_scarico.py`.
La batch SQL associata e' `SQL_SCARICA_UDC` e produce:
1. ricerca dell'ultimo movimento `V` positivo della UDC;
2. update audit della riga sorgente;
3. insert movimento `P` sulla cella sorgente;
4. update `Celle.IDStato = 0` sulla cella sorgente;
5. insert movimento `V` sulla cella target;
6. esecuzione `dbo.py_sp_ControllaPrenotazionePackingListPalletNew`.
Per la funzione storico picking list il target e':
- `target_idcella = 9999`
- `target_barcode_cella = '9000000'`
## Note di consistenza dati
- Una UDC non scaffalata viene vista come `Cella = 1000`, quindi e' residua.
- Una UDC in `9999` non e' residua e viene esclusa dal movimento massivo.
- Una UDC multi-lotto puo' comparire piu' volte nel dettaglio ma deve generare un solo movimento fisico.
- Lo stato `Chiusa ERP con residui` evidenzia disallineamento tra documento ERP chiuso e WMS non completamente versato in spedizione.
## Query diagnostiche utili
Verificare righe documento:
```sql
SELECT *
FROM dbo.py_XMag_ViewPackingListStorico
WHERE Documento = 155
ORDER BY Ordinamento, Pallet;
```
Verificare UDC residue:
```sql
SELECT DISTINCT Pallet, Cella, Ubicazione
FROM dbo.py_XMag_ViewPackingListStorico
WHERE Documento = 155
AND ISNULL(Cella, 0) <> 9999
ORDER BY Pallet;
```
Verificare movimenti UDC dopo versamento:
```sql
SELECT
ID,
Tipo,
IDRiferimento,
Attributo,
IDCella,
DataMagazzino,
InsUtente,
InsDataOra,
ModUtente,
ModDataOra
FROM dbo.MagazziniPallet
WHERE Attributo = '655560'
ORDER BY ID;
```

View File

@@ -19,8 +19,10 @@ from typing import Any, Callable, Optional
import customtkinter as ctk
from async_loop_singleton import get_global_loop
from runtime_support import log_exception
from version_info import module_version
__VERSION__ = "GestioneAreeFrame v3.3.0-singleloop"
__version__ = module_version(__name__)
try:
from async_msssql_query import AsyncMSSQLClient # noqa: F401
@@ -127,21 +129,53 @@ class AsyncRunner:
busy.show(message)
fut = asyncio.run_coroutine_threadsafe(awaitable, self.loop)
def _widget_alive() -> bool:
try:
return bool(self.widget.winfo_exists())
except tk.TclError:
return False
def _dispatch_success(res: Any) -> None:
try:
on_success(res)
except BaseException as ex:
log_exception(__name__, ex, context="AsyncRunner on_success")
def _dispatch_error(ex: BaseException) -> None:
if on_error:
try:
on_error(ex)
except BaseException as callback_ex:
log_exception(__name__, callback_ex, context="AsyncRunner on_error")
else:
log_exception(__name__, ex, context="AsyncRunner unhandled error")
def _poll():
if not _widget_alive():
return
if fut.done():
if busy:
try:
busy.hide()
except Exception as ex:
log_exception(__name__, ex, context="AsyncRunner hide busy")
try:
res = fut.result()
except BaseException as ex:
if on_error:
self.widget.after(0, lambda e=ex: on_error(e))
try:
self.widget.after(0, lambda e=ex: _dispatch_error(e))
except tk.TclError:
log_exception(__name__, ex, context="AsyncRunner error after destroyed")
else:
print("[AsyncRunner] Unhandled error:", repr(ex))
else:
self.widget.after(0, lambda r=res: on_success(r))
try:
self.widget.after(0, lambda r=res: _dispatch_success(r))
except tk.TclError as ex:
log_exception(__name__, ex, context="AsyncRunner success after destroyed")
else:
try:
self.widget.after(60, _poll)
except tk.TclError:
return
_poll()

View File

@@ -26,8 +26,11 @@ from tksheet import Sheet, natural_sort_key
from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text
from ui_theme import theme_color, theme_font, theme_section, theme_value
from user_session import UserSession
from version_info import module_version, versioned_title
from window_placement import place_window_fullsize_below_parent_later
__version__ = module_version(__name__)
try:
from loguru import logger
except Exception: # pragma: no cover - fallback used only when Loguru is not available
@@ -212,7 +215,7 @@ class LayoutWindow(ctk.CTkToplevel):
self._theme = theme_section("layout_window", {})
self._locale_catalog = load_locale_catalog()
self._tooltip_catalog = load_tooltip_catalog()
self.title(loc_text("layout.title", catalog=self._locale_catalog, default="Layout corsie"))
self.title(versioned_title(loc_text("layout.title", catalog=self._locale_catalog, default="Layout corsie"), __name__))
self.geometry(str(theme_value(self._theme, "window_geometry", "1200x740")))
minsize = theme_value(self._theme, "window_minsize", [980, 560])
self.minsize(int(minsize[0]), int(minsize[1]))
@@ -604,6 +607,7 @@ class LayoutWindow(ctk.CTkToplevel):
)
m.add_separator()
m.add_command(label="Copia ubicazione", command=lambda: self._copy(label))
m.add_command(label="Codice cella", command=lambda: self._show_cell_code(r, c))
x = self.winfo_pointerx() if event is None else event.x_root
y = self.winfo_pointery() if event is None else event.y_root
m.tk_popup(x, y)
@@ -645,6 +649,25 @@ class LayoutWindow(ctk.CTkToplevel):
except Exception:
return 0
def _show_cell_code(self, r: int, c: int) -> None:
"""Show the internal cell code for the selected layout cell."""
idcella = self._cell_id(r, c)
ubicazione = self._cell_label(r, c)
barcode_cella = self._cell_barcode(r, c)
if idcella <= 0:
messagebox.showwarning(
"Codice cella",
f"Codice cella non disponibile per {ubicazione}.",
parent=self,
)
return
messagebox.showinfo(
"Codice cella",
f"Ubicazione: {ubicazione}\nCodice cella: {idcella}\nBarcode cella: {barcode_cella or idcella}",
parent=self,
)
@_log_call()
def _prompt_carico(self, r: int, c: int):
"""Prompt the operator for a pallet barcode and move it to the selected cell."""
@@ -678,27 +701,7 @@ class LayoutWindow(ctk.CTkToplevel):
if stato <= 0:
self._toast("La cella selezionata non contiene alcuna UDC da scaricare.")
return
if stato >= 2:
self._open_scarico_dialog(r, c)
return
barcode = str(self.udc1[r][c] or "").strip()
if not barcode:
self._toast("UDC non disponibile per lo scarico.")
return
if not messagebox.askyesno(
"Scarico",
f"Scaricare l'UDC {barcode} da {self._cell_label(r, c)}?",
parent=self,
):
return
self._run_pallet_move(
barcode_pallet=barcode,
target_idcella=9999,
target_barcode_cella="9000000",
success_message=f"Scarico completato per {barcode}.",
busy_message=f"Scarico {barcode}...",
)
@_log_call()
def _run_pallet_move(

View File

@@ -70,8 +70,20 @@ from busy_overlay import InlineBusyOverlay
from gestione_aree import AsyncRunner
from locale_text import load_locale_catalog, text as loc_text
from ui_theme import theme_color, theme_font, theme_section, theme_value
from ui_tables import (
TABLE_HEADER_BG,
TABLE_HEADER_FG,
TABLE_ROW_EVEN,
TABLE_ROW_ODD,
apply_tksheet_visual_style,
apply_tksheet_zebra,
)
from user_session import UserSession
from version_info import module_version, versioned_title
from window_placement import place_window_fullsize_below_parent_later
from pickinglist_sequence import open_pickinglist_sequence_window
__version__ = module_version(__name__)
# === IMPORT procedura async prenota/s-prenota (no pyodbc qui) ===
import asyncio
@@ -198,9 +210,12 @@ if _MODULE_LOG_ENABLED:
# -------------------- SQL --------------------
# Operational picking-list management uses the Python-only residual view.
# Unlike the historical view, this dataset intentionally contains only UDCs
# that still have to be exhausted by the warehouse workflow.
SQL_PL = """
SELECT
COUNT(DISTINCT Pallet) AS Pallet,
COUNT(DISTINCT NULLIF(LTRIM(RTRIM(CAST(Pallet AS varchar(32)))), '')) AS Pallet,
COUNT(DISTINCT Lotto) AS Lotto,
COUNT(DISTINCT Articolo) AS Articolo,
COUNT(DISTINCT Descrizione) AS Descrizione,
@@ -213,18 +228,21 @@ SELECT
MAX(Magazzino) AS Magazzino,
MAX(Area) AS Area,
MAX(Cella) AS Cella,
MIN(OrdinePrelievoGruppo) AS OrdinePrelievoGruppo,
MIN(Ordinamento) AS Ordinamento,
MAX(IDStato) AS IDStato
FROM dbo.py_ViewPackingListRestante
FROM dbo.py_ViewPackingListPrelievo
WHERE DataDocumento > CAST((GETDATE() - :days) AS int)
GROUP BY Documento, CodNazione, NAZIONE, Stato
ORDER BY MIN(Ordinamento), Documento, NAZIONE, Stato;
ORDER BY MIN(OrdinePrelievoGruppo), MIN(Ordinamento), Documento, NAZIONE, Stato;
"""
SQL_PL_DETAILS = """
SELECT *
FROM dbo.py_ViewPackingListRestante
FROM dbo.py_ViewPackingListPrelievo
WHERE Documento = :Documento
ORDER BY Ordinamento;
AND DataDocumento > CAST((GETDATE() - :days) AS int)
ORDER BY OrdinePrelievoGruppo, Ordinamento, Pallet;
"""
# -------------------- helpers --------------------
@@ -314,6 +332,8 @@ DET_COLS: List[ColSpec] = [
]
ROW_H = 28
RESERVED_IDSTATO_BG = "#dc2626"
RESERVED_IDSTATO_FG = "#ffffff"
# -------------------- Micro spinner (toolbar) --------------------
@@ -388,13 +408,14 @@ class ScrollTable(ctk.CTkFrame):
self._sort_key: Optional[str] = None
self._sort_reverse = False
self.total_w = sum(c.width for c in self.columns)
self._vbar_visible = False
self.grid_rowconfigure(1, weight=1)
self.grid_columnconfigure(0, weight=1)
# header
self.h_canvas = tk.Canvas(self, height=ROW_H, highlightthickness=0, bd=0)
self.h_inner = ctk.CTkFrame(self.h_canvas, fg_color="#f3f3f3",
self.h_canvas = tk.Canvas(self, height=ROW_H, highlightthickness=0, bd=0, bg=TABLE_HEADER_BG)
self.h_inner = ctk.CTkFrame(self.h_canvas, fg_color=TABLE_HEADER_BG,
height=ROW_H, width=self.total_w)
self.h_canvas.create_window((0,0), window=self.h_inner, anchor="nw",
width=self.total_w, height=ROW_H)
@@ -411,7 +432,6 @@ class ScrollTable(ctk.CTkFrame):
# scrollbars
self.vbar = tk.Scrollbar(self, orient="vertical", command=self.b_canvas.yview)
self.xbar = tk.Scrollbar(self, orient="horizontal", command=self._xscroll_both)
self.vbar.grid(row=1, column=1, sticky="ns")
self.xbar.grid(row=2, column=0, sticky="ew")
# link scroll
@@ -433,14 +453,14 @@ class ScrollTable(ctk.CTkFrame):
for w in self.h_inner.winfo_children():
w.destroy()
row = ctk.CTkFrame(self.h_inner, fg_color="#f3f3f3",
row = ctk.CTkFrame(self.h_inner, fg_color=TABLE_HEADER_BG,
height=ROW_H, width=self.total_w)
row.pack(fill="x", expand=False)
row.pack_propagate(False)
for col in self.columns:
holder = ctk.CTkFrame(
row, fg_color="#f3f3f3",
row, fg_color=TABLE_HEADER_BG,
width=col.width, height=ROW_H,
border_width=1, border_color=self.GRID_COLOR
)
@@ -451,7 +471,7 @@ class ScrollTable(ctk.CTkFrame):
if col.key == self._sort_key:
header_text = f"{col.title} {'↓' if self._sort_reverse else '↑'}"
lbl = ctk.CTkLabel(holder, text=header_text, anchor="w")
lbl = ctk.CTkLabel(holder, text=header_text, anchor="w", text_color=TABLE_HEADER_FG)
lbl.pack(fill="both", padx=(self.PADX_L, self.PADX_R), pady=self.PADY)
if self.on_header_click and col.key != "__check__":
@@ -472,10 +492,27 @@ class ScrollTable(ctk.CTkFrame):
"""Keep the scroll region aligned with the current body content width."""
self.b_canvas.itemconfigure(self.body_window, width=self.total_w)
sr = self.b_canvas.bbox("all")
content_height = int(sr[3]) if sr else 0
if sr:
self.b_canvas.configure(scrollregion=(0,0,max(self.total_w, sr[2]), sr[3]))
else:
self.b_canvas.configure(scrollregion=(0,0,self.total_w,0))
self._update_vertical_scrollbar(content_height)
def _update_vertical_scrollbar(self, content_height: int):
"""Show the vertical scrollbar only when body rows exceed the visible area."""
try:
visible_height = max(1, int(self.b_canvas.winfo_height()))
except Exception:
visible_height = 1
needs_scroll = content_height > visible_height + 2
if needs_scroll and not self._vbar_visible:
self.vbar.grid(row=1, column=1, sticky="ns")
self._vbar_visible = True
elif not needs_scroll and self._vbar_visible:
self.vbar.grid_remove()
self._vbar_visible = False
self.b_canvas.yview_moveto(0)
def _on_body_configure(self):
"""React to body resize events by syncing dimensions and header scroll."""
@@ -510,8 +547,11 @@ class ScrollTable(ctk.CTkFrame):
delta = getattr(event, "delta", 0)
if delta == 0:
return
if not self._vbar_visible:
return "break"
step = -1 if delta > 0 else 1
self.b_canvas.yview_scroll(step, "units")
return "break"
def clear_rows(self):
"""Remove all rendered body rows."""
@@ -525,16 +565,20 @@ class ScrollTable(ctk.CTkFrame):
row_index: int,
anchors: Optional[List[str]] = None,
checkbox_builder: Optional[Callable[[tk.Widget], ctk.CTkCheckBox]] = None,
cell_bg: Optional[Dict[str, str]] = None,
cell_fg: Optional[Dict[str, str]] = None,
):
"""Append one row to the table body."""
row = ctk.CTkFrame(self.b_inner, fg_color="transparent",
row_bg = TABLE_ROW_EVEN if row_index % 2 == 0 else TABLE_ROW_ODD
row = ctk.CTkFrame(self.b_inner, fg_color=row_bg,
height=ROW_H, width=self.total_w)
row.pack(fill="x", expand=False)
row.pack_propagate(False)
for i, col in enumerate(self.columns):
holder_bg = (cell_bg or {}).get(col.key, row_bg)
holder = ctk.CTkFrame(
row, fg_color="transparent",
row, fg_color=holder_bg,
width=col.width, height=ROW_H,
border_width=1, border_color=self.GRID_COLOR
)
@@ -546,10 +590,17 @@ class ScrollTable(ctk.CTkFrame):
cb = checkbox_builder(holder)
cb.pack(padx=(self.PADX_L, self.PADX_R), pady=self.PADY, anchor="w")
else:
ctk.CTkLabel(holder, text="").pack(fill="both")
ctk.CTkLabel(holder, text="", fg_color=holder_bg).pack(fill="both")
else:
anchor = (anchors[i] if anchors else col.anchor)
ctk.CTkLabel(holder, text=values[i], anchor=anchor).pack(
ctk.CTkLabel(
holder,
text=values[i],
anchor=anchor,
fg_color=holder_bg,
text_color=(cell_fg or {}).get(col.key, "#111827"),
font=("Segoe UI", 10, "bold") if col.key == "IDStato" and col.key in (cell_bg or {}) else None,
).pack(
fill="both", padx=(self.PADX_L, self.PADX_R), pady=self.PADY
)
@@ -602,6 +653,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
self.rows_models: list[PLRow] = []
self._detail_cache: Dict[Any, list] = {}
self.detail_doc = None
self.days_var = tk.StringVar(value="10")
self._detail_sort_key: Optional[str] = None
self._detail_sort_reverse = False
self._detail_sorting = False
@@ -652,6 +704,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
(loc_text("picking.button.reload", catalog=self._locale_catalog, default="Ricarica"), self.reload_from_db),
(loc_text("picking.button.prenota", catalog=self._locale_catalog, default="Prenota"), self.on_prenota),
(loc_text("picking.button.sprenota", catalog=self._locale_catalog, default="S-prenota"), self.on_sprenota),
(loc_text("picking.button.sequence", catalog=self._locale_catalog, default="Sequenza di prelievo"), self.on_sequence),
(loc_text("picking.button.export", catalog=self._locale_catalog, default="Esporta XLSX"), self.on_export)
]):
ctk.CTkButton(
@@ -661,6 +714,20 @@ class GestionePickingListFrame(ctk.CTkFrame):
font=theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold")),
).grid(row=0, column=i, padx=6)
ctk.CTkLabel(
top,
text=loc_text("picking.label.days", catalog=self._locale_catalog, default="Giorni:"),
font=theme_font(self._theme, "toolbar_label_font", ("Segoe UI", 10)),
).grid(row=0, column=5, padx=(18, 4), sticky="e")
ctk.CTkOptionMenu(
top,
values=["10", "15", "20", "30"],
variable=self.days_var,
width=82,
command=lambda _value: self.reload_from_db(),
font=theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold")),
).grid(row=0, column=6, padx=(0, 6), sticky="w")
# --- micro spinner a destra della toolbar ---
self.spinner = ToolbarSpinner(top)
self.spinner.widget().grid(row=0, column=10, padx=(8,0)) # largo spazio a destra
@@ -693,6 +760,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
self.detail_sheet.change_theme("light green")
self.detail_sheet.enable_bindings("all")
self.detail_sheet.headers(self._detail_headers(), redraw=False)
apply_tksheet_visual_style(self.detail_sheet)
self.detail_sheet.bind("<ButtonRelease-1>", self._on_detail_sheet_left_click, add="+")
self.detail_sheet.grid(row=0, column=0, sticky="nsew")
@@ -733,8 +801,10 @@ class GestionePickingListFrame(ctk.CTkFrame):
data,
reset_col_positions=True,
reset_row_positions=True,
redraw=True,
redraw=False,
)
apply_tksheet_visual_style(self.detail_sheet)
apply_tksheet_zebra(self.detail_sheet, len(data))
self.detail_sheet.set_all_column_widths()
def _detail_sort_value(self, row: Dict[str, Any], key: str):
@@ -838,10 +908,22 @@ class GestionePickingListFrame(ctk.CTkFrame):
try:
for idx, d in enumerate(rows):
row_widget = self.pl_table.b_inner.winfo_children()[idx]
if int(d.get("IDStato") or 0) == 1:
row_widget.configure(fg_color="#ffe6f2") # rosa tenue
else:
row_widget.configure(fg_color="transparent")
row_bg = TABLE_ROW_EVEN if idx % 2 == 0 else TABLE_ROW_ODD
row_widget.configure(fg_color=row_bg)
row_children = row_widget.winfo_children()
if len(row_children) >= 5:
holder = row_children[4]
is_reserved = int(d.get("IDStato") or 0) == 1
holder_bg = RESERVED_IDSTATO_BG if is_reserved else row_bg
holder.configure(fg_color=holder_bg)
if holder.winfo_children():
lbl = holder.winfo_children()[0]
if hasattr(lbl, "configure"):
lbl.configure(
fg_color=holder_bg,
text_color=RESERVED_IDSTATO_FG if is_reserved else "#111827",
font=("Segoe UI", 10, "bold") if is_reserved else ("Segoe UI", 10),
)
except Exception:
pass
@@ -868,7 +950,9 @@ class GestionePickingListFrame(ctk.CTkFrame):
values=values,
row_index=r,
anchors=[c.anchor for c in PL_COLS],
checkbox_builder=model.build_checkbox
checkbox_builder=model.build_checkbox,
cell_bg={"IDStato": RESERVED_IDSTATO_BG} if int(d.get("IDStato") or 0) == 1 else None,
cell_fg={"IDStato": RESERVED_IDSTATO_FG} if int(d.get("IDStato") or 0) == 1 else None,
)
# 🎯 Colora dopo che la UI è resa → no balzi visivi
@@ -894,29 +978,62 @@ class GestionePickingListFrame(ctk.CTkFrame):
row_children = row_widget.winfo_children()
if len(row_children) >= 5:
holder = row_children[4]
holder.configure(fg_color=RESERVED_IDSTATO_BG if idstato == 1 else (
TABLE_ROW_EVEN if idx % 2 == 0 else TABLE_ROW_ODD
))
if holder.winfo_children():
lbl = holder.winfo_children()[0]
if hasattr(lbl, "configure"):
lbl.configure(text=str(idstato))
lbl.configure(
text=str(idstato),
fg_color=RESERVED_IDSTATO_BG if idstato == 1 else (
TABLE_ROW_EVEN if idx % 2 == 0 else TABLE_ROW_ODD
),
text_color=RESERVED_IDSTATO_FG if idstato == 1 else "#111827",
font=("Segoe UI", 10, "bold") if idstato == 1 else ("Segoe UI", 10),
)
except Exception:
pass
# differisci la colorazione (smooth)
self.after_idle(_paint)
break
def _reselect_documento_after_reload(self, documento: str):
"""(Opzionale) Dopo un reload DB, riseleziona la PL con lo stesso Documento."""
def _reselect_documento_after_reload(self, documento: str) -> bool:
"""After a reload, reselect the same document and reload its details."""
for m in self.rows_models:
if _s(m.pl.get("Documento")) == _s(documento):
self._detail_cache.pop(documento, None)
m.set_checked(True)
self.on_row_checked(m, True)
break
return True
return False
def _selected_documento_for_reload(self) -> str | None:
"""Return the document that should survive a toolbar reload."""
selected = self._get_selected_model()
if selected is not None:
documento = _s(selected.pl.get("Documento"))
return documento or None
documento = _s(self.detail_doc)
return documento or None
def _selected_days(self) -> int:
"""Return the selected look-back interval for operational picking lists."""
try:
days = int(str(self.days_var.get()).strip())
except Exception:
days = 10
return days if days in (10, 15, 20, 30) else 10
# ----- eventi -----
@_log_call()
def on_row_checked(self, model: PLRow, is_checked: bool):
"""Handle row selection changes and refresh the detail section."""
# selezione esclusiva
# Only one backoffice picking list can be selected at a time. Barcode
# F1/F2 priority behavior is derived downstream; this UI controls only
# the explicit Python reservation slot.
if is_checked:
for m in self.rows_models:
if m is not model and m.is_checked():
@@ -925,10 +1042,12 @@ class GestionePickingListFrame(ctk.CTkFrame):
self.detail_doc = model.pl.get("Documento")
_MODULE_LOGGER.info(f"Documento selezionato per il dettaglio: {self.detail_doc}")
self.spinner.start(" Carico dettagli…") # spinner ON
days = self._selected_days()
async def _job():
_log_sql("SQL_PL_DETAILS", SQL_PL_DETAILS, {"Documento": self.detail_doc})
return await self.db_client.query_json(SQL_PL_DETAILS, {"Documento": self.detail_doc})
params = {"Documento": self.detail_doc, "days": days}
_log_sql("SQL_PL_DETAILS", SQL_PL_DETAILS, params)
return await self.db_client.query_json(SQL_PL_DETAILS, params)
def _ok(res):
# NON fermare lo spinner subito: lo farà _refresh_details_incremental
@@ -964,16 +1083,33 @@ class GestionePickingListFrame(ctk.CTkFrame):
@_log_call()
def reload_from_db(self, first: bool = False, reselect_documento: str | None = None):
"""Load or reload the picking list summary table from the database."""
if reselect_documento is None and not first:
# Preserve the operator context while the barcode may be consuming
# rows: Ricarica refreshes master and detail but keeps the selected
# document selected when it is still visible.
reselect_documento = self._selected_documento_for_reload()
self.spinner.start(" Carico…") # spinner ON
days = self._selected_days()
async def _job():
_log_sql("SQL_PL", SQL_PL, {})
return await self.db_client.query_json(SQL_PL, {})
params = {"days": days}
_log_sql("SQL_PL", SQL_PL, params)
return await self.db_client.query_json(SQL_PL, params)
def _on_success(res):
rows = _rows_to_dicts(res)
_log_dataset("SQL_PL", rows)
self._refresh_mid_rows(rows)
if reselect_documento:
self.after_idle(lambda doc=reselect_documento: self._reselect_documento_after_reload(doc))
def _reselect_or_clear(doc=reselect_documento):
found = self._reselect_documento_after_reload(doc)
if not found:
self.detail_doc = None
self._draw_details_hint()
self.spinner.stop()
self.busy.hide()
self.after_idle(_reselect_or_clear)
else:
self.detail_doc = None
self._draw_details_hint()
self.spinner.stop() # spinner OFF
# se era il primo load, ripristina il cursore standard
if self._first_loading:
@@ -1053,6 +1189,45 @@ class GestionePickingListFrame(ctk.CTkFrame):
self._load_detail_sheet_data(self._detail_rows_to_sheet_data(rows))
# ----- azioni -----
@_log_call()
def on_sequence(self):
"""Open the pickup-sequence editor for the selected picking list."""
if not self._can("pickinglist.sequence"):
messagebox.showwarning(
loc_text("picking.sequence.title", catalog=self._locale_catalog, default="Sequenza di prelievo"),
loc_text("picking.sequence.msg.denied", catalog=self._locale_catalog, default="Permesso negato."),
parent=self,
)
return
model = self._get_selected_model()
if not model:
messagebox.showinfo(
loc_text("picking.sequence.title", catalog=self._locale_catalog, default="Sequenza di prelievo"),
loc_text(
"picking.sequence.msg.select",
catalog=self._locale_catalog,
default="Seleziona una Picking List prima di definire la sequenza.",
),
parent=self,
)
return
documento = _s(model.pl.get("Documento"))
def _on_saved():
self._detail_cache.pop(documento, None)
self.reload_from_db(reselect_documento=documento)
open_pickinglist_sequence_window(
self.winfo_toplevel(),
self.db_client,
documento=documento,
session=self.session,
on_saved=_on_saved,
)
@_log_call()
def on_prenota(self):
"""Reserve the selected picking list."""
@@ -1067,6 +1242,8 @@ class GestionePickingListFrame(ctk.CTkFrame):
documento = _s(model.pl.get("Documento"))
current = int(model.pl.get("IDStato") or 0)
desired = 1
# Idempotent semantics: Prenota never toggles a list off. If the list
# is already reserved, S-prenota remains the only explicit release path.
if current == desired:
messagebox.showinfo("Prenota", f"La Picking List {documento} è già prenotata.")
return
@@ -1079,6 +1256,8 @@ class GestionePickingListFrame(ctk.CTkFrame):
self.spinner.start(" Prenoto…")
async def _job():
# Use the Python-specific py_* stored procedure so C# legacy
# procedures can coexist unchanged on the same database.
return await sp_xExePackingListPallet_async(self.db_client, id_operatore, documento, "P")
def _ok(res: SPResult):
@@ -1141,6 +1320,8 @@ class GestionePickingListFrame(ctk.CTkFrame):
documento = _s(model.pl.get("Documento"))
current = int(model.pl.get("IDStato") or 0)
desired = 0
# Idempotent semantics: S-prenota never reserves a list; if the list is
# already free, the operation is a no-op rather than an implicit toggle.
if current == desired:
messagebox.showinfo("S-prenota", f"La Picking List {documento} è già NON prenotata.")
return
@@ -1153,6 +1334,8 @@ class GestionePickingListFrame(ctk.CTkFrame):
self.spinner.start(" S-prenoto…")
async def _job():
# Same Python-only procedure as Prenota, with action S to release
# the singleton reservation and clear affected cell states.
return await sp_xExePackingListPallet_async(self.db_client, id_operatore, documento, "S")
def _ok(res: SPResult):
@@ -1240,7 +1423,7 @@ def open_pickinglist_window(parent: tk.Misc, db_client, session: UserSession | N
win = ctk.CTkToplevel(parent)
locale_catalog = load_locale_catalog()
win.title(loc_text("picking.title", catalog=locale_catalog, default="Gestione Picking List"))
win.title(versioned_title(loc_text("picking.title", catalog=locale_catalog, default="Gestione Picking List"), __name__))
theme = theme_section("pickinglist_window", {})
win.geometry(str(theme_value(theme, "window_geometry", "1200x700")))
minsize = theme_value(theme, "window_minsize", [1000, 560])

View File

@@ -20,7 +20,11 @@ from audit_log import log_user_action
from busy_overlay import InlineBusyOverlay
from locale_text import load_locale_catalog, text as loc_text
from ui_theme import theme_color, theme_font, theme_section, theme_value
from ui_tables import style_treeview, zebra_tag
from user_session import UserSession
from version_info import module_version, versioned_title
__version__ = module_version(__name__)
try:
from loguru import logger
@@ -72,6 +76,12 @@ _MODULE_LOG_LEVEL = "DEBUG" if SCARICO_LOG_MODE.upper() == "DEBUG" else "INFO"
_MODULE_LOGGER = logger.bind(warehouse_module=MODULE_LOG_NAME)
_MODULE_LOGGING_CONFIGURED = False
DEFAULT_SCARICO_USER = "warehouse_ui"
SHIPPED_IDCELLA = 9999
SHIPPED_BARCODE = "9000000"
SHIPPED_LABEL = "7G.1.1"
NON_SCAFF_IDCELLA = 1000
NON_SCAFF_BARCODE = "9001000"
NON_SCAFF_LABEL = "5E1.1"
def _session_login(session: UserSession | None, fallback: str | None = None) -> str:
@@ -194,28 +204,7 @@ last_move AS (
FROM dbo.MagazziniPallet mp
JOIN last_in_cell lic ON lic.LastID = mp.ID
),
latest_any AS (
SELECT
ranked.BarcodePallet,
ranked.IDCella
FROM (
SELECT
mp.Attributo AS BarcodePallet,
mp.IDCella,
ROW_NUMBER() OVER (
PARTITION BY mp.Attributo
ORDER BY mp.ID DESC
) AS rn
FROM dbo.MagazziniPallet mp
JOIN cell_pallets cp
ON cp.BarcodePallet COLLATE Latin1_General_CI_AS =
mp.Attributo COLLATE Latin1_General_CI_AS
WHERE mp.Tipo = 'V'
AND mp.PesoUnitario > 0
) ranked
WHERE ranked.rn = 1
),
shipped AS (
closed_plist AS (
SELECT DISTINCT
shipped.BarcodePallet
FROM dbo.XMag_GiacenzaPalletPlistChiuse shipped
@@ -227,25 +216,19 @@ SELECT
cp.BarcodePallet AS UDC,
lm.ID AS SourceID,
lm.DataMagazzino AS LastEventAt,
:idcella AS CurrentIDCella,
CASE
WHEN shipped.BarcodePallet IS NOT NULL THEN CAST(1 AS int)
ELSE CAST(0 AS int)
END AS IsShippedGhost,
CASE
WHEN la.IDCella IS NOT NULL
AND la.IDCella <> :idcella
WHEN :idcella <> 9999
AND closed_plist.BarcodePallet IS NOT NULL
THEN CAST(1 AS int)
ELSE CAST(0 AS int)
END AS IsMovedGhost
END AS IsMissingUnload
FROM cell_pallets cp
LEFT JOIN last_move lm
ON lm.BarcodePallet COLLATE Latin1_General_CI_AS =
cp.BarcodePallet COLLATE Latin1_General_CI_AS
LEFT JOIN latest_any la
ON la.BarcodePallet COLLATE Latin1_General_CI_AS =
cp.BarcodePallet COLLATE Latin1_General_CI_AS
LEFT JOIN shipped
ON shipped.BarcodePallet COLLATE Latin1_General_CI_AS =
LEFT JOIN closed_plist
ON closed_plist.BarcodePallet COLLATE Latin1_General_CI_AS =
cp.BarcodePallet COLLATE Latin1_General_CI_AS
ORDER BY
lm.ID DESC,
@@ -409,19 +392,23 @@ class ScaricoRow:
udc: str
source_id: int | None
last_event_at: str
current_idcella: int
diagnostic_note: str
selected: tk.BooleanVar
def _build_diagnostic_note(is_shipped: int | bool, is_moved: int | bool) -> str:
def _build_diagnostic_note(is_missing_unload: int | bool = False) -> str:
"""Translate low-level anomaly flags into one operator-facing note."""
notes: list[str] = []
if bool(is_shipped):
notes.append("Mancato scarico: spedita")
if bool(is_moved):
notes.append("Mancato scarico: spostata")
return " | ".join(notes)
if bool(is_missing_unload):
return "Motivo: spedita ma non scaricata dalla cella"
return ""
def _is_missing_unload_row(row: ScaricoRow) -> bool:
"""Return True when the row must be corrected only with shipped unload."""
return "spedita ma non scaricata dalla cella" in str(row.diagnostic_note or "").lower()
class ScaricoDialog(ctk.CTkToplevel):
@@ -457,7 +444,7 @@ class ScaricoDialog(ctk.CTkToplevel):
self._async = AsyncRunner(self)
self.rows_tree: ttk.Treeview | None = None
self.title(loc_text("scarico.title", catalog=self._locale_catalog, default="Scarica {ubicazione}").format(ubicazione=ubicazione))
self.title(versioned_title(loc_text("scarico.title", catalog=self._locale_catalog, default="Scarica {ubicazione}").format(ubicazione=ubicazione), __name__))
self.resizable(False, False)
self.transient(parent)
self.protocol("WM_DELETE_WINDOW", self._close)
@@ -474,6 +461,7 @@ class ScaricoDialog(ctk.CTkToplevel):
self.wait_visibility()
except Exception:
pass
if self.winfo_exists():
self.lift()
self.focus_force()
@@ -508,10 +496,6 @@ class ScaricoDialog(ctk.CTkToplevel):
tree_host.grid_rowconfigure(0, weight=1)
tree_host.grid_columnconfigure(0, weight=1)
style = ttk.Style(self)
style.configure("Scarico.Treeview", rowheight=28, font=theme_font(self._theme, "tree_body_font", ("Segoe UI", 10)))
style.configure("Scarico.Treeview.Heading", font=theme_font(self._theme, "tree_heading_font", ("Segoe UI", 10, "bold")))
self.rows_tree = ttk.Treeview(
tree_host,
columns=("sel", "udc", "last", "diag"),
@@ -519,6 +503,13 @@ class ScaricoDialog(ctk.CTkToplevel):
style="Scarico.Treeview",
selectmode="none",
)
style_treeview(
self.rows_tree,
style_name="Scarico.Treeview",
rowheight=28,
font=theme_font(self._theme, "tree_body_font", ("Segoe UI", 10)),
heading_font=theme_font(self._theme, "tree_heading_font", ("Segoe UI", 10, "bold")),
)
self.rows_tree.heading("sel", text="Sel")
self.rows_tree.heading("udc", text=loc_text("scarico.col.udc", catalog=self._locale_catalog, default="UDC"))
self.rows_tree.heading("last", text=loc_text("scarico.col.last_insert", catalog=self._locale_catalog, default="Ultimo inserimento"))
@@ -539,19 +530,27 @@ class ScaricoDialog(ctk.CTkToplevel):
actions.grid_columnconfigure(0, weight=1)
ctk.CTkButton(
actions,
text=loc_text("scarico.button.submit", catalog=self._locale_catalog, default="Scarica"),
command=self._on_scarica,
text=loc_text("scarico.button.shipped", catalog=self._locale_catalog, default="Scarico come spedita"),
command=self._on_scarica_spedita,
font=theme_font(self._theme, "button_font", ("Segoe UI", 10, "bold")),
).grid(
row=0, column=1, padx=(8, 0), pady=8
)
ctk.CTkButton(
actions,
text=loc_text("scarico.button.non_shelved", catalog=self._locale_catalog, default="Scarico come non scaff."),
command=self._on_scarica_non_scaff,
font=theme_font(self._theme, "button_font", ("Segoe UI", 10, "bold")),
).grid(
row=0, column=2, padx=(8, 0), pady=8
)
ctk.CTkButton(
actions,
text=loc_text("scarico.button.close", catalog=self._locale_catalog, default="Chiudi"),
command=self._close,
font=theme_font(self._theme, "button_font", ("Segoe UI", 10, "bold")),
).grid(
row=0, column=2, padx=(8, 8), pady=8
row=0, column=3, padx=(8, 8), pady=8
)
def _render_rows(self):
@@ -572,6 +571,7 @@ class ScaricoDialog(ctk.CTkToplevel):
row.last_event_at,
row.diagnostic_note or "",
),
tags=(zebra_tag(idx),),
)
self.update_idletasks()
@@ -609,7 +609,13 @@ class ScaricoDialog(ctk.CTkToplevel):
rows = res.get("rows", []) if isinstance(res, dict) else []
_log_dataset("scarico_load_rows", rows)
self.rows = []
for udc, source_id, last_event_at, is_shipped, is_moved in rows:
for (
udc,
source_id,
last_event_at,
current_idcella,
is_missing_unload,
) in rows:
if isinstance(last_event_at, datetime):
last_event = last_event_at.strftime("%d/%m/%Y %H:%M:%S")
else:
@@ -619,7 +625,8 @@ class ScaricoDialog(ctk.CTkToplevel):
udc=str(udc or ""),
source_id=int(source_id) if source_id is not None else None,
last_event_at=last_event,
diagnostic_note=_build_diagnostic_note(is_shipped, is_moved),
current_idcella=int(current_idcella or 0),
diagnostic_note=_build_diagnostic_note(is_missing_unload),
selected=tk.BooleanVar(value=False),
)
)
@@ -645,8 +652,9 @@ class ScaricoDialog(ctk.CTkToplevel):
)
@_log_call()
def _on_scarica(self):
"""Unload the UDCs selected by the user from the current cell."""
def _selected_rows_or_warn(self) -> list[ScaricoRow] | None:
"""Return selected rows or show the standard selection warning."""
selected = [row for row in self.rows if row.selected.get()]
if not selected:
messagebox.showinfo(
@@ -654,23 +662,97 @@ class ScaricoDialog(ctk.CTkToplevel):
loc_text("scarico.msg.select_one", catalog=self._locale_catalog, default="Seleziona almeno una UDC da scaricare."),
parent=self,
)
return selected
@_log_call()
def _on_scarica_spedita(self):
"""Unload selected UDCs to the shipped conventional location."""
self._scarica_selected_to_target(
target_idcella=SHIPPED_IDCELLA,
target_barcode_cella=SHIPPED_BARCODE,
target_label=SHIPPED_LABEL,
title="Scarico come spedita",
confirm_text="Scaricare come spedite {count} UDC da {ubicazione}?",
busy_message="Scarico UDC come spedite...",
block_shipped_for_non_scaff=False,
)
@_log_call()
def _on_scarica_non_scaff(self):
"""Unload selected UDCs to the non-shelved conventional location."""
self._scarica_selected_to_target(
target_idcella=NON_SCAFF_IDCELLA,
target_barcode_cella=NON_SCAFF_BARCODE,
target_label=NON_SCAFF_LABEL,
title="Scarico come non scaff.",
confirm_text="Scaricare come non scaffalate {count} UDC da {ubicazione}?",
busy_message="Scarico UDC come non scaffalate...",
block_shipped_for_non_scaff=True,
)
def _scarica_selected_to_target(
self,
*,
target_idcella: int,
target_barcode_cella: str,
target_label: str,
title: str,
confirm_text: str,
busy_message: str,
block_shipped_for_non_scaff: bool,
):
"""Move selected UDCs to one conventional unload location."""
selected = self._selected_rows_or_warn()
if not selected:
return
shipped_rows: list[ScaricoRow] = []
missing_unload_rows: list[ScaricoRow] = []
movable_rows = list(selected)
if block_shipped_for_non_scaff:
shipped_rows = [
row for row in selected
if int(row.current_idcella or 0) == SHIPPED_IDCELLA
]
missing_unload_rows = [row for row in selected if _is_missing_unload_row(row)]
blocked_udcs = {row.udc for row in shipped_rows + missing_unload_rows}
movable_rows = [row for row in selected if row.udc not in blocked_udcs]
if (shipped_rows or missing_unload_rows) and not movable_rows:
message_lines = ["Nessuna UDC movimentata."]
if shipped_rows:
message_lines.append(f"UDC gia' in {SHIPPED_LABEL}: " + ", ".join(row.udc for row in shipped_rows))
if missing_unload_rows:
message_lines.append(
"UDC spedite ma non scaricate: "
+ ", ".join(row.udc for row in missing_unload_rows)
)
message_lines.append("Usare 'Scarico come spedita'.")
messagebox.showwarning(
title,
"\n".join(message_lines),
parent=self,
)
return
if not messagebox.askyesno(
"Conferma scarico",
f"Scaricare {len(selected)} UDC da {self.ubicazione}?",
title,
confirm_text.format(count=len(movable_rows), ubicazione=self.ubicazione),
parent=self,
):
return
async def _job():
results: list[dict[str, Any]] = []
for row in selected:
for row in movable_rows:
result = await move_pallet_async(
self.db_client,
barcode_pallet=row.udc,
target_idcella=9999,
target_barcode_cella="9000000",
target_idcella=target_idcella,
target_barcode_cella=target_barcode_cella,
utente=_session_login(self.session),
)
results.append({"udc": row.udc, "affected": int(result.get("ok") or 0)})
@@ -682,33 +764,65 @@ class ScaricoDialog(ctk.CTkToplevel):
skipped = [item["udc"] for item in results if int(item.get("affected") or 0) <= 0]
if not done:
messagebox.showwarning(
"Scarica",
title,
"Nessuna UDC e' stata scaricata. Verifica che le unita' siano ancora presenti in cella.",
parent=self,
)
return
if skipped:
shipped_note = (
f"\nGia' in {SHIPPED_LABEL} non toccate: " + ", ".join(row.udc for row in shipped_rows)
if shipped_rows
else ""
)
missing_unload_note = (
"\nSpedite ma non scaricate, usare 'Scarico come spedita': "
+ ", ".join(row.udc for row in missing_unload_rows)
if missing_unload_rows
else ""
)
target_note = (
f"\nUDC in {target_label}: " + ", ".join(done)
if done
else ""
)
messagebox.showwarning(
"Scarica",
title,
"Scarico parziale.\nCompletate: "
+ ", ".join(done)
+ "\nNon scaricate: "
+ ", ".join(skipped),
+ ", ".join(skipped)
+ shipped_note
+ missing_unload_note
+ target_note,
parent=self,
)
else:
messagebox.showinfo(
"Scarica",
"Scarico completato per:\n" + "\n".join(done),
parent=self,
msg = f"Scarico completato verso {target_label} per:\n" + "\n".join(done)
if shipped_rows:
msg += f"\n\nUDC gia' in {SHIPPED_LABEL} non toccate:\n" + "\n".join(row.udc for row in shipped_rows)
msg += f"\n\nUDC in {target_label}: " + ", ".join(done)
if missing_unload_rows:
msg += (
"\n\nUDC spedite ma non scaricate non toccate:\n"
+ "\n".join(row.udc for row in missing_unload_rows)
+ "\nUsare 'Scarico come spedita'."
)
messagebox.showinfo(title, msg, parent=self)
log_user_action(
self.session,
module=MODULE_LOG_NAME,
action="layout.scarico",
action="layout.scarico.spedita" if int(target_idcella) == SHIPPED_IDCELLA else "layout.scarico.non_scaff",
outcome="ok",
target=self.ubicazione,
details={"scaricate": done, "saltate": skipped},
details={
"scaricate": done,
"saltate": skipped,
"target_idcella": target_idcella,
"target_barcode_cella": target_barcode_cella,
"gia_spedite": [row.udc for row in shipped_rows],
"spedite_non_scaricate": [row.udc for row in missing_unload_rows],
},
)
if self.on_completed:
self.on_completed()
@@ -719,7 +833,7 @@ class ScaricoDialog(ctk.CTkToplevel):
log_user_action(
self.session,
module=MODULE_LOG_NAME,
action="layout.scarico",
action="layout.scarico.spedita" if int(target_idcella) == SHIPPED_IDCELLA else "layout.scarico.non_scaff",
outcome="error",
target=self.ubicazione,
details={"error": str(ex)},
@@ -735,7 +849,7 @@ class ScaricoDialog(ctk.CTkToplevel):
_ok,
_err,
busy=self._busy,
message="Scarico UDC...",
message=busy_message,
)
@_log_call()

View File

@@ -10,6 +10,7 @@
"launcher.history_udc": "Storico movimenti UDC",
"launcher.pickinglist": "Gestione Picking List",
"launcher.history_pickinglist": "Storico Picking List",
"launcher.diagnostics": "Diagnostica",
"launcher.arrange": "Ridisponi finestre",
"launcher.exit": "Esci",
"launcher.already_running_title": "Warehouse",
@@ -75,6 +76,27 @@
"history.picking.msg.title": "Storico Picking List",
"history.picking.msg.load_error": "Errore caricamento:\n{error}",
"history.picking.msg.detail_error": "Errore dettaglio:\n{error}",
"diagnostics.title": "Diagnostica",
"diagnostics.button.shipped_not_disassociated": "UDC spedite non disassociate",
"diagnostics.button.multiple_udc_by_cell": "Celle con multiple UDC",
"diagnostics.button.sam_udc_not_in_wms": "Ultime UDC SAM non in WMS",
"diagnostics.button.export": "Esporta XLSX",
"diagnostics.busy.shipped_not_disassociated": "Cerco UDC spedite ma ancora in cella...",
"diagnostics.busy.multiple_udc_by_cell": "Cerco celle con multiple UDC...",
"diagnostics.busy.sam_udc_not_in_wms": "Cerco le ultime UDC presenti in SAM ma non ancora in WMS...",
"diagnostics.status.rows": "Righe trovate: {count}",
"diagnostics.col.udc": "UDC",
"diagnostics.col.cell": "CELLA",
"diagnostics.col.lot": "Lotto",
"diagnostics.col.product": "Prodotto",
"diagnostics.col.description": "Descrizione",
"diagnostics.col.shipped_not_disassociated": "Spedita ma non disassociata",
"diagnostics.col.symbolic_cell": "Nome simbolico cella",
"diagnostics.export.title": "Esporta",
"diagnostics.export.empty": "Non ci sono righe da esportare.",
"diagnostics.export.dep": "Per l'esportazione serve 'openpyxl' (pip install openpyxl).",
"diagnostics.export.ok": "File creato:\n{path}",
"diagnostics.export.error": "Errore durante l'esportazione:\n{error}",
"reset.title": "Gestione Corsie - svuotamento celle per corsia",
"reset.label.aisle": "Corsia:",
"reset.button.refresh": "Carica",
@@ -99,7 +121,30 @@
"picking.button.reload": "Ricarica",
"picking.button.prenota": "Prenota",
"picking.button.sprenota": "S-prenota",
"picking.button.sequence": "Sequenza di prelievo",
"picking.button.export": "Esporta XLSX",
"picking.label.days": "Giorni:",
"picking.sequence.title": "Sequenza di prelievo",
"picking.sequence.document": "Picking List {documento}",
"picking.sequence.available": "Scaffali disponibili",
"picking.sequence.selected": "Ordine personalizzato",
"picking.sequence.hint": "Trascina gli scaffali a destra. Quelli non inseriti saranno accodati secondo l'ordine predefinito.",
"picking.sequence.default_hint": "Default: prima Non scaff., poi gli scaffali secondo l'ordine WMS.",
"picking.sequence.button.add": "Aggiungi >",
"picking.sequence.button.remove": "< Rimuovi",
"picking.sequence.button.up": "Su",
"picking.sequence.button.down": "Giu'",
"picking.sequence.button.save": "Salva",
"picking.sequence.button.reset": "Ripristina default",
"picking.sequence.button.close": "Chiudi",
"picking.sequence.busy.load": "Carico gli scaffali...",
"picking.sequence.busy.save": "Salvo la sequenza...",
"picking.sequence.msg.select": "Seleziona una Picking List prima di definire la sequenza.",
"picking.sequence.msg.denied": "Permesso negato.",
"picking.sequence.msg.saved": "Sequenza salvata.",
"picking.sequence.msg.reset": "Sequenza personalizzata rimossa. E' attivo l'ordine predefinito.",
"picking.sequence.msg.load_error": "Errore durante il caricamento:\n{error}",
"picking.sequence.msg.save_error": "Errore durante il salvataggio:\n{error}",
"scarico.title": "Scarica {ubicazione}",
"scarico.label.location": "Ubicazione: {ubicazione}",
"scarico.label.select": "Seleziona le UDC da scaricare",
@@ -107,6 +152,8 @@
"scarico.col.last_insert": "Ultimo inserimento",
"scarico.col.diagnostic": "Diagnostica",
"scarico.button.submit": "Scarica",
"scarico.button.shipped": "Scarico come spedita",
"scarico.button.non_shelved": "Scarico come non scaff.",
"scarico.button.close": "Chiudi",
"scarico.msg.title": "Scarica",
"scarico.msg.select_one": "Seleziona almeno una UDC da scaricare.",
@@ -123,6 +170,7 @@
"launcher.history_udc": "UDC Movement History",
"launcher.pickinglist": "Picking List Management",
"launcher.history_pickinglist": "Picking List History",
"launcher.diagnostics": "Diagnostics",
"launcher.arrange": "Arrange windows",
"launcher.exit": "Exit",
"launcher.already_running_title": "Warehouse",
@@ -188,6 +236,27 @@
"history.picking.msg.title": "Picking List History",
"history.picking.msg.load_error": "Load failed:\n{error}",
"history.picking.msg.detail_error": "Detail load failed:\n{error}",
"diagnostics.title": "Diagnostics",
"diagnostics.button.shipped_not_disassociated": "Shipped UDC not disassociated",
"diagnostics.button.multiple_udc_by_cell": "Cells with multiple UDC",
"diagnostics.button.sam_udc_not_in_wms": "Latest UDC in SAM not in WMS",
"diagnostics.button.export": "Export XLSX",
"diagnostics.busy.shipped_not_disassociated": "Searching shipped UDC still assigned to cells...",
"diagnostics.busy.multiple_udc_by_cell": "Searching cells with multiple UDC...",
"diagnostics.busy.sam_udc_not_in_wms": "Searching latest UDC present in SAM but not yet in WMS...",
"diagnostics.status.rows": "Rows found: {count}",
"diagnostics.col.udc": "UDC",
"diagnostics.col.cell": "CELL",
"diagnostics.col.lot": "Lot",
"diagnostics.col.product": "Product",
"diagnostics.col.description": "Description",
"diagnostics.col.shipped_not_disassociated": "Shipped but not disassociated",
"diagnostics.col.symbolic_cell": "Symbolic cell name",
"diagnostics.export.title": "Export",
"diagnostics.export.empty": "There are no rows to export.",
"diagnostics.export.dep": "Export requires 'openpyxl' (pip install openpyxl).",
"diagnostics.export.ok": "File created:\n{path}",
"diagnostics.export.error": "Export failed:\n{error}",
"reset.title": "Aisle Management - empty cells by aisle",
"reset.label.aisle": "Aisle:",
"reset.button.refresh": "Load",
@@ -212,7 +281,30 @@
"picking.button.reload": "Reload",
"picking.button.prenota": "Reserve",
"picking.button.sprenota": "Unreserve",
"picking.button.sequence": "Pickup sequence",
"picking.button.export": "Export XLSX",
"picking.label.days": "Days:",
"picking.sequence.title": "Pickup sequence",
"picking.sequence.document": "Picking List {documento}",
"picking.sequence.available": "Available racks",
"picking.sequence.selected": "Custom order",
"picking.sequence.hint": "Drag racks to the right. Missing racks are appended using the default order.",
"picking.sequence.default_hint": "Default: non-shelved first, then racks in WMS order.",
"picking.sequence.button.add": "Add >",
"picking.sequence.button.remove": "< Remove",
"picking.sequence.button.up": "Up",
"picking.sequence.button.down": "Down",
"picking.sequence.button.save": "Save",
"picking.sequence.button.reset": "Restore default",
"picking.sequence.button.close": "Close",
"picking.sequence.busy.load": "Loading racks...",
"picking.sequence.busy.save": "Saving sequence...",
"picking.sequence.msg.select": "Select a Picking List before defining its sequence.",
"picking.sequence.msg.denied": "Permission denied.",
"picking.sequence.msg.saved": "Sequence saved.",
"picking.sequence.msg.reset": "Custom sequence removed. The default order is active.",
"picking.sequence.msg.load_error": "Load failed:\n{error}",
"picking.sequence.msg.save_error": "Save failed:\n{error}",
"scarico.title": "Unload {ubicazione}",
"scarico.label.location": "Location: {ubicazione}",
"scarico.label.select": "Select the UDCs to unload",
@@ -220,6 +312,8 @@
"scarico.col.last_insert": "Last insert",
"scarico.col.diagnostic": "Diagnostics",
"scarico.button.submit": "Unload",
"scarico.button.shipped": "Unload as shipped",
"scarico.button.non_shelved": "Unload as non-shelved",
"scarico.button.close": "Close",
"scarico.msg.title": "Unload",
"scarico.msg.select_one": "Select at least one UDC to unload.",

View File

@@ -6,6 +6,9 @@ import json
from functools import lru_cache
from pathlib import Path
from version_info import module_version
__version__ = module_version(__name__)
_LOCALE_FILE = Path(__file__).with_name("locale.json")

View File

@@ -11,6 +11,9 @@ from gestione_aree import AsyncRunner
from locale_text import load_locale_catalog, text as loc_text
from ui_theme import theme_section, theme_value
from user_session import UserSession, create_user_session
from version_info import module_version, versioned_title
__version__ = module_version(__name__)
SQL_LOGIN = """
@@ -64,8 +67,8 @@ class LoginWindow(tk.Toplevel):
self._show_ready_after_id: str | None = None
self._clear_topmost_after_id: str | None = None
self.title(loc_text("login.msg.title", catalog=self._locale_catalog, default="Login"))
self.geometry("170x145+0+0" if self.compact else str(theme_value(self._theme, "window_geometry", "165x155+0+0")))
self.title(versioned_title(loc_text("login.msg.title", catalog=self._locale_catalog, default="Login"), __name__))
self.geometry("170x148+0+0" if self.compact else str(theme_value(self._theme, "window_geometry", "165x170+0+0")))
self.resizable(False, False)
try:
if parent is not None and parent.winfo_viewable():
@@ -88,53 +91,59 @@ class LoginWindow(tk.Toplevel):
def _build_ui(self) -> None:
"""Build the compact operator login form."""
body = ttk.Frame(self, padding=8 if self.compact else 8)
body = ttk.Frame(self, padding=6 if self.compact else 8)
body.pack(fill="both", expand=True)
body.columnconfigure(1, weight=0)
row_offset = 0
ttk.Label(body, text="User:").grid(row=row_offset, column=0, sticky="w", padx=(0, 4), pady=4)
ttk.Label(body, text="User:").grid(row=row_offset, column=0, sticky="w", padx=(0, 4), pady=(2, 3))
self.login_entry = ttk.Entry(body, textvariable=self.login_var, width=10, font=("Segoe UI", 10 if self.compact else 9))
self.login_entry.grid(row=row_offset, column=1, sticky="w", pady=4)
self.login_entry.grid(row=row_offset, column=1, sticky="w", pady=(2, 3))
ttk.Label(body, text="Pwd:").grid(row=row_offset + 1, column=0, sticky="w", padx=(0, 4), pady=4)
ttk.Label(body, text="Pwd:").grid(row=row_offset + 1, column=0, sticky="w", padx=(0, 4), pady=(2, 2))
self.password_entry = ttk.Entry(body, textvariable=self.password_var, width=10, show="*", font=("Segoe UI", 10 if self.compact else 9))
self.password_entry.grid(row=row_offset + 1, column=1, sticky="w", pady=4)
self.password_entry.grid(row=row_offset + 1, column=1, sticky="w", pady=(2, 2))
if self.compact:
actions = ttk.Frame(body)
actions.grid(row=row_offset + 2, column=0, columnspan=2, sticky="ew", pady=(6, 0))
self._cancel_button = ttk.Button(
actions,
text="Annulla",
command=self._on_cancel,
)
self._cancel_button.grid(row=1, column=0, sticky="ew", pady=(4, 0))
actions.grid(row=row_offset + 2, column=0, columnspan=2, sticky="ew", pady=(3, 0))
self._login_button = ttk.Button(
actions,
text="OK",
command=self._on_login,
)
self._login_button.grid(row=0, column=0, sticky="ew")
else:
self.status_label = ttk.Label(body, textvariable=self._status_var, foreground="#555555")
self.status_label.grid(row=2, column=0, columnspan=2, sticky="w", pady=(2, 2))
actions = ttk.Frame(body)
actions.grid(row=3, column=0, columnspan=2, sticky="w", pady=(6, 0))
self._cancel_button = ttk.Button(
actions,
text=loc_text("login.button.cancel", catalog=self._locale_catalog, default="Annulla"),
text="Annulla",
command=self._on_cancel,
)
self._cancel_button.grid(row=1, column=0, sticky="ew", pady=(4, 0))
self._cancel_button.grid(row=1, column=0, sticky="ew", pady=(3, 0))
else:
self.status_label = ttk.Label(body, textvariable=self._status_var, foreground="#555555")
self.status_label.grid(row=2, column=0, columnspan=2, sticky="w", pady=(1, 1))
actions = ttk.Frame(body)
actions.grid(row=3, column=0, columnspan=2, sticky="w", pady=(3, 0))
self._login_button = ttk.Button(
actions,
text=loc_text("login.button.submit", catalog=self._locale_catalog, default="OK"),
command=self._on_login,
)
self._login_button.grid(row=0, column=0, sticky="ew")
self._cancel_button = ttk.Button(
actions,
text=loc_text("login.button.cancel", catalog=self._locale_catalog, default="Annulla"),
command=self._on_cancel,
)
self._cancel_button.grid(row=1, column=0, sticky="ew", pady=(3, 0))
for widget in (self.login_entry, self.password_entry, self._login_button, self._cancel_button):
try:
widget.configure(takefocus=True)
except Exception:
pass
self.bind("<Return>", lambda _e: self._on_login())
self.bind("<Escape>", lambda _e: self._on_cancel())

28
main.py
View File

@@ -22,6 +22,7 @@ from async_loop_singleton import get_global_loop, stop_global_loop
from async_msssql_query import AsyncMSSQLClient
from audit_log import log_session_event
from db_config import build_dsn_from_config, ensure_db_config
from diagnostica import open_diagnostica_window
from gestione_layout import open_layout_window
from gestione_pickinglist import open_pickinglist_window
from login_window import prompt_login
@@ -31,8 +32,10 @@ from search_pallets import open_search_window
from storico_pickinglist import open_storico_pickinglist_window
from storico_udc import open_storico_udc_window
from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text
from udc_non_scaffalate import open_udc_non_scaffalate_window
from ui_theme import theme_font, theme_section, theme_value
from user_session import UserSession, create_user_session
from version_info import module_version, versioned_title
from view_celle_multi_udc import open_celle_multiple_window
from window_placement import (
cascade_children_below_parent,
@@ -42,7 +45,8 @@ from window_placement import (
# Development shortcut: skip the login dialog and boot directly as MAG1.
# Set to False when you want to restore normal authentication.
BYPASS_LOGIN = False
BYPASS_LOGIN = True
__version__ = module_version(__name__)
BYPASS_LOGIN_USER = {
"operator_id": 4,
"login": "MAG1",
@@ -153,10 +157,12 @@ class Launcher(ctk.CTk):
"reset_corsie",
"layout",
"multi_udc",
"non_shelved",
"search",
"storico_udc",
"pickinglist",
"storico_pickinglist",
"diagnostica",
]
def __init__(self, session: UserSession, db_client: AsyncMSSQLClient):
@@ -176,7 +182,7 @@ class Launcher(ctk.CTk):
color=str(theme_value(self._theme, "exit_icon_color", "#ca3d3d"))
)
self.title(
f"{loc_text('launcher.window_title', catalog=self._locale_catalog, default='Warehouse 1.0.0')} - {self.session.display_name}"
f"{versioned_title(loc_text('launcher.window_title', catalog=self._locale_catalog, default='Warehouse'), __name__)} - {self.session.display_name}"
)
self._apply_dynamic_geometry()
@@ -219,6 +225,15 @@ class Launcher(ctk.CTk):
lambda: open_celle_multiple_window(self, self.db_client, session=self.session),
),
),
(
"non_shelved",
loc_text("launcher.non_shelved", catalog=self._locale_catalog, default="UDC non scaffalate"),
"launcher.open_non_shelved",
lambda: self._open_or_focus_child_window(
"non_shelved",
lambda: open_udc_non_scaffalate_window(self, self.db_client, session=self.session),
),
),
(
"search",
loc_text("launcher.search", catalog=self._locale_catalog, default="Ricerca UDC"),
@@ -255,6 +270,15 @@ class Launcher(ctk.CTk):
lambda: open_storico_pickinglist_window(self, self.db_client, session=self.session),
),
),
(
"diagnostica",
loc_text("launcher.diagnostics", catalog=self._locale_catalog, default="Diagnostica"),
"launcher.open_diagnostics",
lambda: self._open_or_focus_child_window(
"diagnostica",
lambda: open_diagnostica_window(self, self.db_client, session=self.session),
),
),
(
"arrange",
loc_text("launcher.arrange", catalog=self._locale_catalog, default="Ridisponi finestre"),

414
ordinamento.md Normal file
View File

@@ -0,0 +1,414 @@
# Ordinamento di prelievo delle celle
## 1. Scopo del documento
Questo documento descrive il significato e l'origine del campo
`dbo.Celle.Ordinamento`, il modo in cui viene utilizzato per proporre le UDC al
barcode e le differenze riscontrate tra i due magazzini storici:
- Area 5, identificata nel database legacy come magazzino `MDE5`;
- Area 6, identificata nel database legacy come magazzino `MDE6`.
Nel linguaggio operativo si parla di Area 5 e Area 6. Nel modello legacy,
tuttavia, la tabella `Magazzini` contiene `MDE5` e `MDE6`, mentre la tabella
`Aree` contiene le singole corsie o scaffali. Gli ID della tabella `Aree` non
devono quindi essere confusi con i nomi operativi Area 5 e Area 6.
Le conclusioni riportate derivano da:
- struttura e dati correnti della tabella `dbo.Celle`;
- stored procedure legacy contenute in `script.sql`;
- viste usate dalle picking list;
- codice Python del barcode e della gestione picking list;
- confronto tra `ID`, ubicazione e `Ordinamento` delle celle reali.
## 2. Significato di `Celle.Ordinamento`
`Celle.Ordinamento` e' una priorita' numerica associata all'anagrafica della
cella. Rappresenta la posizione della cella nel percorso predefinito di
prelievo.
Il campo non indica:
- la quantita' di UDC presenti;
- la priorita' della picking list;
- lo stato libero o occupato della cella;
- l'ordine cronologico di inserimento delle UDC;
- l'ID della UDC;
- la distanza calcolata dinamicamente dal barcode.
Il valore non viene ricalcolato durante un versamento o un prelievo. E' un dato
statico dell'anagrafica della cella, salvo interventi amministrativi o
procedure specifiche di rinumerazione.
Il tipo SQL storico e' `float`, ma nei dati analizzati viene usato come numero
intero progressivo. Nella futura riprogettazione sarebbe preferibile un tipo
intero o una struttura esplicita di percorso.
## 3. Dove viene assegnato
La stored procedure legacy `dbo.spt_SaveCelle` riceve il parametro
`@Ordinamento` e lo salva direttamente:
```sql
UPDATE Celle
SET Ordinamento = @Ordinamento
WHERE ID = @ID;
```
Se la cella non esiste, la stessa stored procedure esegue una `INSERT` e
inserisce il valore ricevuto. La procedura non contiene una formula per
calcolarlo: chi crea o modifica la cella deve decidere il valore e passarlo.
Nel database non risultano trigger sulla tabella `Celle` che aggiornino
automaticamente `Ordinamento`.
Sono state individuate anche procedure legacy di supporto:
- `CreaNuoveCelle`;
- `CreaNuoveCelleMDE6`;
- `CreaNuoveCelleMDE6_BIS`;
- `sp_OrdinaCelle`;
- `spt_SaveCelle`.
Le procedure di creazione MDE6 impostano normalmente:
```sql
SET @Ordinamento = @ID;
```
La procedura `sp_OrdinaCelle` dimostra invece che il campo puo' essere
rinumerato in un secondo momento per rappresentare un percorso differente
dall'ID della cella.
## 4. Uso durante una picking list
Le viste operative associano ogni UDC alla cella corrente e recuperano
`Celle.Ordinamento`. Il barcode richiede la prima riga residua secondo l'ordine
effettivo.
Prima dell'introduzione della sequenza personalizzata, il criterio principale
era sostanzialmente:
```sql
ORDER BY Ordinamento;
```
Questo significa che il barcode non percorre tutte le celle del magazzino. La
vista contiene soltanto le UDC ancora presenti nella picking list: le celle che
non contengono una UDC richiesta vengono saltate automaticamente.
Esempio: se il percorso contiene le celle con ordine `1001`, `1002`, `1003` e
`1004`, ma la picking list contiene UDC soltanto nelle celle `1001` e `1004`, il
barcode propone direttamente la UDC di `1001` e poi quella di `1004`.
## 5. Ordinamento dell'Area 5 / MDE5
### 5.1 Caratteristica generale
Nell'Area 5 `Ordinamento` non coincide normalmente con l'ID della cella. Dai
dati emerge un percorso fisico costruito intenzionalmente, verosimilmente
hardcoded o rinumerato durante la configurazione iniziale del magazzino.
Le corsie principali coinvolte sono:
- `1A`;
- `2B`;
- `3C`;
- `4D`.
Il percorso iniziale delle corsie `1A` e `2B` e' a serpentina. Le due corsie
vengono trattate come lati o scaffali adiacenti di uno stesso tragitto fisico.
### 5.2 Esempio reale dell'inizio del percorso
```text
Ordine Ubicazione ID cella
1001 1A.1.e 1005
1002 1A.1.d 1004
1003 1A.1.c 1003
1004 1A.1.b 1002
1005 1A.1.a 1001
1007 2B.1.e 2005
1008 2B.1.d 2004
1009 2B.1.c 2003
1010 2B.1.b 2002
1011 2B.1.a 2001
1013 2B.2.e 2011
1014 2B.2.d 2010
1015 2B.2.c 2009
1016 2B.2.b 2008
1017 2B.2.a 2007
1019 1A.2.e 1011
1020 1A.2.d 1010
1021 1A.2.c 1009
1022 1A.2.b 1008
1023 1A.2.a 1007
```
La sequenza prosegue con lo stesso principio:
```text
1A campata 1
2B campata 1
2B campata 2
1A campata 2
1A campata 3
2B campata 3
2B campata 4
1A campata 4
...
```
### 5.3 Movimento verticale nella campata
All'interno di ciascuna campata l'ordine verificato e':
```text
e -> d -> c -> b -> a
```
Il percorso procede quindi dal livello identificato con `e` verso il livello
`a`. Non viene prelevata una sola UDC per campata per poi ricominciare il giro.
Vengono considerate, in sequenza, tutte le celle richieste della campata
corrente prima di passare alla campata successiva.
Se una campata contiene piu' UDC richieste in livelli diversi, il barcode le
propone secondo `e, d, c, b, a`. Se alcuni livelli non contengono UDC della
picking list, vengono semplicemente saltati.
### 5.4 Alternanza tra 1A e 2B
Il sistema non esaurisce tutto `1A` prima di iniziare `2B`. Alterna blocchi di
campate tra le due corsie per seguire un tragitto a serpentina ed evitare
ritorni inutili.
Il comportamento predefinito storico e' quindi:
- completare le UDC richieste nella campata corrente;
- passare alla campata fisicamente successiva del percorso;
- alternare `1A` e `2B` secondo la serpentina configurata;
- non tornare all'inizio dopo ogni singola UDC.
### 5.5 Passaggio a 3C e 4D
Le corsie `3C` e `4D` hanno valori di ordinamento molto piu' alti. Nei dati
analizzati:
```text
1A: minimo 1001, massimo 1275
2B: minimo 1007, massimo 1251
3C: minimo 10019, massimo 10227
4D: valori nell'intervallo 10055 - 10233 circa
```
Di conseguenza il percorso storico esaurisce normalmente il blocco `1A/2B`
prima di passare al blocco `3C/4D`.
La presenza di famiglie numeriche differenti indica che l'ordinamento
dell'Area 5 e' stato costruito o modificato in piu' fasi storiche.
### 5.6 Significato dei numeri mancanti
La progressione contiene intervalli non utilizzati, per esempio `1005` seguito
da `1007`. Il numero mancante non indica necessariamente una cella eliminata o
un errore. Puo' essere stato lasciato come separatore tra campate o derivare
dalla procedura di rinumerazione.
Il software deve usare il confronto numerico e non deve presumere che tutti i
valori siano consecutivi.
## 6. Ordinamento dell'Area 6 / MDE6
### 6.1 Caratteristica generale
Nell'Area 6 il modello e' piu' semplice. La maggior parte delle celle e' stata
generata con `Ordinamento` uguale all'ID della cella.
Le famiglie principali sono:
```text
1M -> celle e ordinamenti 5001, 5002, 5003, ...
2N -> celle e ordinamenti 6001, 6002, 6003, ...
3O -> celle e ordinamenti 7001, 7002, 7003, ...
4P -> celle e ordinamenti 8001, 8002, 8003, ...
```
Le procedure `CreaNuoveCelleMDE6` e `CreaNuoveCelleMDE6_BIS` creano le celle
con cicli annidati e assegnano esplicitamente:
```sql
SET @Ordinamento = @ID;
```
### 6.2 Ordine degli scaffali
Poiche' le famiglie numeriche sono separate, l'ordine globale predefinito e':
```text
1M -> 2N -> 3O -> 4P
```
Senza una sequenza personalizzata vengono quindi considerate prima tutte le
UDC richieste in `1M`, poi quelle in `2N`, successivamente `3O` e infine `4P`.
### 6.3 Ordine interno dello scaffale
Durante la generazione delle celle, i cicli legacy incrementano prima la
campata e, all'interno della campata, il piano. L'ordine risultante e':
```text
1M.1.a -> 1M.1.b -> 1M.1.c -> 1M.1.d -> 1M.1.e
1M.2.a -> 1M.2.b -> 1M.2.c -> 1M.2.d -> 1M.2.e
...
2N.1.a -> 2N.1.b -> ...
```
Quindi l'Area 6 differisce dall'Area 5 in due aspetti principali:
- non presenta l'alternanza a serpentina tra due corsie adiacenti;
- dentro la campata procede da `a` verso `e`, mentre nell'Area 5 verificata
procede da `e` verso `a`.
### 6.4 Limiti della ricostruzione
Il comportamento descritto deriva dalla procedura di generazione e dai valori
correnti. Eventuali celle aggiunte manualmente in tempi successivi possono
avere eccezioni. L'applicazione deve sempre leggere il valore effettivo dal
database e non ricostruirlo aritmeticamente dall'ubicazione.
## 7. Celle virtuali
Nel sistema legacy esistono due ubicazioni convenzionali:
```text
ID 1000 -> 5E.1.1 -> Non scaff. -> Ordinamento 99999
ID 9999 -> 7G.1.1 -> Spedita -> Ordinamento 0
```
Questi valori non rappresentano un percorso fisico:
- `5E.1.1` identifica UDC presenti nel magazzino ma non allocate in uno
scaffale fisico;
- `7G.1.1` identifica UDC spedite.
Storicamente `Non scaff.` aveva ordinamento `99999`, quindi finiva in fondo
alla picking list. Il nuovo requisito operativo stabilisce invece che le UDC
non scaffalate devono essere proposte per prime.
La nuova vista Python non modifica `Celle.Ordinamento`: assegna a `Non scaff.`
una precedenza logica di gruppo pari a zero. La cella `Spedita` non entra nella
vista residuale e quindi non viene proposta dal barcode.
## 8. Nuovo ordinamento predefinito Python
In assenza di una configurazione specifica per il documento, il nuovo ordine
effettivo e':
1. tutte le UDC `Non scaff.` ancora appartenenti alla picking list;
2. tutte le UDC nelle celle fisiche secondo `Celle.Ordinamento`;
3. codice pallet come criterio stabile in caso di parita'.
In forma semplificata:
```sql
ORDER BY
OrdinePrelievoGruppo,
Ordinamento,
Pallet;
```
Per le celle fisiche, se non esiste una personalizzazione,
`OrdinePrelievoGruppo` conserva la progressione storica. Il percorso dell'Area
5 rimane quindi a serpentina e quello dell'Area 6 rimane progressivo.
## 9. Effetto della sequenza personalizzata
La sequenza personalizzata opera a livello di gruppo o scaffale, non a livello
di singola cella.
Esempio di configurazione:
```text
1. Non scaff.
2. 3C
3. 1A
4. 2B
5. 4D
```
In questo caso il sistema esaurisce prima il gruppo `Non scaff.`, poi tutte le
UDC di `3C`, quindi tutte quelle di `1A` e cosi' via.
All'interno di ciascun gruppo continua a usare `Celle.Ordinamento`. Per
esempio, se `1A` viene posizionata prima di `2B`, non viene piu' conservata
l'alternanza storica tra `1A` e `2B`: vengono esaurite prima tutte le UDC di
`1A`, nel loro ordine interno, e successivamente quelle di `2B`.
Questa differenza e' intenzionale:
- ordine predefinito: conserva il percorso storico globale;
- ordine personalizzato: impone la precedenza degli scaffali scelta
dall'operatore e conserva l'ordine storico soltanto dentro ogni scaffale.
Se la sequenza personalizzata non include tutti i gruppi, quelli mancanti
vengono accodati secondo il percorso predefinito. Nessuna UDC viene esclusa.
## 10. UDC multiple, lotti e parita' di ordine
Piu' righe della vista possono riferirsi alla stessa UDC quando contiene piu'
lotti o articoli. Questo non significa che il magazziniere debba movimentare
fisicamente la stessa UDC piu' volte: l'unita' di movimentazione rimane il
pallet/UDC.
Piu' UDC possono inoltre risultare associate alla stessa cella nel modello
legacy. In quel caso condividono lo stesso `Ordinamento`. Il nuovo codice usa
anche `Pallet` come criterio finale per rendere stabile la sequenza, ma il
percorso fisico resta quello della cella.
## 11. Considerazioni per la futura riprogettazione
Nel futuro FlyWMS Core e' consigliabile separare esplicitamente:
- ordine fisico della cella dentro lo scaffale;
- ordine predefinito degli scaffali;
- percorso o strategia di visita del magazzino;
- ordine personalizzato per documento;
- priorita' operativa della picking list;
- eventuale ottimizzazione dinamica del percorso.
Il campo legacy `Celle.Ordinamento` incorpora piu' significati e dipende da
decisioni storiche non completamente documentate. Non dovrebbe essere copiato
alla lettera nel nuovo modello dati senza scomporne la semantica.
Una possibile struttura futura potrebbe prevedere:
- `Location.SequenceWithinRack` per l'ordine interno;
- `Rack.DefaultSequence` per l'ordine tra scaffali;
- `Route` e `RouteStep` per percorsi configurabili;
- `PickingDocumentRoute` per la personalizzazione della singola lista.
## 12. Riferimenti tecnici nel progetto
- `script.sql`: definizioni di `spt_SaveCelle`, `CreaNuoveCelleMDE6`,
`CreaNuoveCelleMDE6_BIS` e `sp_OrdinaCelle`;
- `barcode_repository.py`: interrogazione della prossima UDC;
- `gestione_pickinglist.py`: visualizzazione del dettaglio ordinato;
- `pickinglist_sequence.py`: gestione della sequenza per documento;
- `apply_pickinglist_sequence_patch.sql`: tabella e vista Python dedicate;
- `specifica_sequenza_prelievo.md`: specifica funzionale della nuova
configurazione.
## 13. Conclusione
L'Area 5 utilizza un percorso storico a serpentina, costruito per alternare
corsie e campate secondo la disposizione fisica. L'Area 6 utilizza invece una
progressione piu' semplice, sostanzialmente coincidente con gli ID creati in
sequenza.
Il nuovo software conserva entrambi i comportamenti come default, anticipa le
UDC non scaffalate e permette di sostituire l'ordine globale degli scaffali per
una singola picking list senza modificare l'anagrafica delle celle.

584
pickinglist_sequence.py Normal file
View File

@@ -0,0 +1,584 @@
"""Editor for the per-document picking-list pickup sequence.
The barcode client remains unaware of the editor: it reads the effective order
from ``dbo.py_ViewPackingListPrelievo``. This module only manages the Python-
specific configuration rows used by that view.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable
import tkinter as tk
from tkinter import messagebox
import customtkinter as ctk
from busy_overlay import InlineBusyOverlay
from gestione_aree import AsyncRunner
from locale_text import load_locale_catalog, text as loc_text
from ui_theme import theme_color, theme_font, theme_section
from user_session import UserSession
from version_info import module_version, versioned_title
from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text
__version__ = module_version(__name__)
SQL_LOAD_GROUPS = """
SELECT
GruppoPrelievoChiave,
MAX(GruppoPrelievo) AS GruppoPrelievo,
MIN(OrdineGruppoDefault) AS OrdineGruppoDefault,
MIN(OrdineGruppoConfigurato) AS OrdineGruppoConfigurato
FROM dbo.py_ViewPackingListPrelievo
WHERE CAST(Documento AS varchar(50)) = :documento
AND Cella <> 9999
GROUP BY GruppoPrelievoChiave
ORDER BY
CASE WHEN MIN(OrdineGruppoConfigurato) IS NULL THEN 1 ELSE 0 END,
MIN(OrdineGruppoConfigurato),
MIN(OrdineGruppoDefault),
MAX(GruppoPrelievo);
"""
SQL_RESET_SEQUENCE = """
SET NOCOUNT ON;
SET XACT_ABORT ON;
UPDATE dbo.py_PickingListPrelievoSequenza
SET DelUtente = :utente,
DelDataOra = SYSDATETIME(),
ModUtente = :utente,
ModDataOra = SYSDATETIME()
WHERE Documento = :documento
AND DelDataOra IS NULL;
SELECT CAST(0 AS int) AS ElementiSalvati;
"""
def _rows_to_dicts(result: dict[str, Any] | None) -> list[dict[str, Any]]:
"""Convert the shared database payload to dictionaries."""
if not isinstance(result, dict):
return []
rows = result.get("rows") or []
columns = result.get("columns") or []
if rows and isinstance(rows[0], dict):
return [dict(row) for row in rows]
return [
{str(columns[index]): row[index] for index in range(min(len(columns), len(row)))}
for row in rows
if isinstance(row, (list, tuple))
]
@dataclass(frozen=True)
class PickupGroup:
"""One rack group, or the conventional non-shelved group."""
key: str
label: str
default_order: int
class PickingListSequenceWindow(ctk.CTkToplevel):
"""Drag-and-drop editor for one picking-list pickup sequence."""
def __init__(
self,
parent: tk.Misc,
db_client,
*,
documento: str,
session: UserSession | None,
on_saved: Callable[[], None] | None = None,
):
super().__init__(parent)
self.db_client = db_client
self.documento = str(documento or "").strip()
self.session = session
self.on_saved = on_saved
self._catalog = load_locale_catalog()
self._tooltip_catalog = load_tooltip_catalog()
self._theme = theme_section("picking_sequence_window", {})
self.runner = AsyncRunner(self)
self.busy = InlineBusyOverlay(self, self._theme)
self.available: list[PickupGroup] = []
self.selected: list[PickupGroup] = []
self._selected_key: str | None = None
self._selected_side: str | None = None
self._drag_group: PickupGroup | None = None
self._drag_side: str | None = None
self.title(versioned_title(self._t("picking.sequence.title", "Sequenza di prelievo"), __name__))
self.geometry("780x560")
self.minsize(680, 480)
self.transient(parent)
self.configure(fg_color=theme_color(self._theme, "window_fg_color", ("#efefef", "#2f2f2f")))
self.protocol("WM_DELETE_WINDOW", self.destroy)
self.bind("<Escape>", lambda _event: self.destroy())
self._build_layout()
self.withdraw()
self.after_idle(self._show_and_load)
def _t(self, key: str, default: str, **values: Any) -> str:
"""Return one localized and formatted label."""
value = loc_text(key, catalog=self._catalog, default=default)
try:
return value.format(**values)
except Exception:
return value
def _build_layout(self) -> None:
"""Build the two lists and the explicit keyboard-friendly controls."""
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(2, weight=1)
self.grid_rowconfigure(2, weight=1)
ctk.CTkLabel(
self,
text=self._t("picking.sequence.document", "Picking List {documento}", documento=self.documento),
font=theme_font(self._theme, "title_font", ("Segoe UI", 16, "bold")),
).grid(row=0, column=0, columnspan=3, padx=16, pady=(14, 4), sticky="w")
ctk.CTkLabel(
self,
text=self._t(
"picking.sequence.hint",
"Trascina gli scaffali a destra. Quelli non inseriti saranno accodati secondo l'ordine predefinito.",
),
anchor="w",
justify="left",
wraplength=720,
).grid(row=1, column=0, columnspan=3, padx=16, pady=(0, 10), sticky="ew")
self.available_panel, self.available_list = self._build_list_panel(
0, self._t("picking.sequence.available", "Scaffali disponibili")
)
controls = ctk.CTkFrame(self, fg_color="transparent")
controls.grid(row=2, column=1, padx=10, pady=4)
for label, command in (
(self._t("picking.sequence.button.add", "Aggiungi >"), self._add_selected),
(self._t("picking.sequence.button.remove", "< Rimuovi"), self._remove_selected),
(self._t("picking.sequence.button.up", "Su"), lambda: self._move_selected(-1)),
(self._t("picking.sequence.button.down", "Giu'"), lambda: self._move_selected(1)),
):
button = ctk.CTkButton(controls, text=label, width=120, command=command)
button.pack(pady=5)
tooltip_key = {
self._t("picking.sequence.button.add", "Aggiungi >"): "picking.sequence.add",
self._t("picking.sequence.button.remove", "< Rimuovi"): "picking.sequence.remove",
self._t("picking.sequence.button.up", "Su"): "picking.sequence.up",
self._t("picking.sequence.button.down", "Giu'"): "picking.sequence.down",
}.get(label, "")
self._attach_tooltip(button, tooltip_key)
self.selected_panel, self.selected_list = self._build_list_panel(
2, self._t("picking.sequence.selected", "Ordine personalizzato")
)
ctk.CTkLabel(
self,
text=self._t(
"picking.sequence.default_hint",
"Default: prima Non scaff., poi gli scaffali secondo l'ordine WMS.",
),
anchor="w",
text_color=theme_color(self._theme, "secondary_text_color", "#4b5563"),
).grid(row=3, column=0, columnspan=3, padx=16, pady=(8, 4), sticky="ew")
bottom = ctk.CTkFrame(self)
bottom.grid(row=4, column=0, columnspan=3, padx=16, pady=(6, 14), sticky="ew")
bottom.grid_columnconfigure(0, weight=1)
reset_button = ctk.CTkButton(
bottom,
text=self._t("picking.sequence.button.reset", "Ripristina default"),
command=self._reset_default,
fg_color=theme_color(self._theme, "reset_button_fg_color", "#6b7280"),
)
reset_button.grid(row=0, column=1, padx=5, pady=8)
self._attach_tooltip(reset_button, "picking.sequence.reset")
save_button = ctk.CTkButton(
bottom,
text=self._t("picking.sequence.button.save", "Salva"),
command=self._save,
)
save_button.grid(row=0, column=2, padx=5, pady=8)
self._attach_tooltip(save_button, "picking.sequence.save")
close_button = ctk.CTkButton(
bottom,
text=self._t("picking.sequence.button.close", "Chiudi"),
command=self.destroy,
)
close_button.grid(row=0, column=3, padx=5, pady=8)
self._attach_tooltip(close_button, "picking.sequence.close")
def _attach_tooltip(self, widget: tk.Misc, key: str) -> None:
"""Attach a localized tooltip when the catalog contains one."""
value = tooltip_text(key, catalog=self._tooltip_catalog) if key else ""
if value:
WidgetToolTip(widget, value)
def _build_list_panel(self, column: int, title: str):
"""Create one titled, scrollable group list."""
panel = ctk.CTkFrame(self)
panel.grid(row=2, column=column, padx=(16 if column == 0 else 0, 16 if column == 2 else 0), pady=4, sticky="nsew")
panel.grid_columnconfigure(0, weight=1)
panel.grid_rowconfigure(1, weight=1)
ctk.CTkLabel(panel, text=title, font=("Segoe UI", 12, "bold")).grid(
row=0, column=0, padx=10, pady=(10, 6), sticky="w"
)
content = ctk.CTkScrollableFrame(panel, fg_color=theme_color(self._theme, "list_fg_color", "#f8fafc"))
content.grid(row=1, column=0, padx=8, pady=(0, 8), sticky="nsew")
content.grid_columnconfigure(0, weight=1)
return panel, content
def _show_and_load(self) -> None:
"""Center the ready window and start its asynchronous load."""
try:
self.update_idletasks()
parent = self.master
x = max(0, parent.winfo_rootx() + (parent.winfo_width() - self.winfo_width()) // 2)
y = max(0, parent.winfo_rooty() + (parent.winfo_height() - self.winfo_height()) // 2)
self.geometry(f"+{x}+{y}")
except Exception:
pass
self.deiconify()
self.lift()
self.focus_force()
self._load()
def _load(self) -> None:
"""Load available groups and the optional saved sequence."""
async def _job():
return await self.db_client.query_json(SQL_LOAD_GROUPS, {"documento": self.documento})
def _ok(result):
rows = _rows_to_dicts(result)
configured: list[tuple[int, PickupGroup]] = []
available: list[PickupGroup] = []
for row in rows:
group = PickupGroup(
key=str(row.get("GruppoPrelievoChiave") or "").strip(),
label=str(row.get("GruppoPrelievo") or "").strip(),
default_order=int(row.get("OrdineGruppoDefault") or 0),
)
configured_order = row.get("OrdineGruppoConfigurato")
if configured_order is None:
available.append(group)
else:
configured.append((int(configured_order), group))
self.available = sorted(available, key=lambda item: (item.default_order, item.label))
self.selected = [item for _order, item in sorted(configured, key=lambda pair: pair[0])]
self._render_lists()
def _error(exc):
messagebox.showerror(
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,
)
self.runner.run(
_job(),
on_success=_ok,
on_error=_error,
busy=self.busy,
message=self._t("picking.sequence.busy.load", "Carico gli scaffali..."),
)
def _render_lists(self) -> None:
"""Redraw list buttons after a move or a database load."""
for host in (self.available_list, self.selected_list):
for child in host.winfo_children():
child.destroy()
for row, group in enumerate(self.available):
self._render_group_button(self.available_list, group, "available", row)
for row, group in enumerate(self.selected):
self._render_group_button(self.selected_list, group, "selected", row)
def _render_group_button(self, host, group: PickupGroup, side: str, row: int) -> None:
"""Render one selectable and draggable group button."""
is_selected = self._selected_key == group.key and self._selected_side == side
prefix = f"{row + 1}. " if side == "selected" else ""
button = ctk.CTkButton(
host,
text=f"{prefix}{group.label}",
anchor="w",
height=34,
fg_color="#1976d2" if is_selected else theme_color(self._theme, "item_fg_color", "#2ebf74"),
command=lambda g=group, s=side: self._select(g, s),
)
button.grid(row=row, column=0, padx=4, pady=4, sticky="ew")
button.bind("<Double-Button-1>", lambda _event, g=group, s=side: self._toggle_group(g, s), add="+")
drag_widgets = [button]
for attr in ("_canvas", "_text_label", "_image_label"):
widget = getattr(button, attr, None)
if widget is not None:
drag_widgets.append(widget)
for widget in drag_widgets:
widget.bind("<ButtonPress-1>", lambda _event, g=group, s=side: self._start_drag(g, s), add="+")
widget.bind("<ButtonRelease-1>", self._finish_drag, add="+")
self._attach_tooltip(button, "picking.sequence.item")
def _select(self, group: PickupGroup, side: str) -> None:
"""Select one group for the explicit move controls."""
self._selected_key = group.key
self._selected_side = side
self._render_lists()
def _toggle_group(self, group: PickupGroup, side: str) -> None:
"""Move a double-clicked group to the opposite side."""
self._selected_key = group.key
self._selected_side = side
self._add_selected() if side == "available" else self._remove_selected()
def _selected_group(self) -> PickupGroup | None:
"""Return the group selected in the active side."""
source = self.available if self._selected_side == "available" else self.selected
return next((item for item in source if item.key == self._selected_key), None)
def _add_selected(self) -> None:
"""Append the selected available group to the custom sequence."""
if self._selected_side != "available":
return
group = self._selected_group()
if group is None:
return
self.available = [item for item in self.available if item.key != group.key]
self.selected.append(group)
self._selected_side = "selected"
self._render_lists()
def _remove_selected(self) -> None:
"""Return the selected configured group to the available list."""
if self._selected_side != "selected":
return
group = self._selected_group()
if group is None:
return
self.selected = [item for item in self.selected if item.key != group.key]
self.available.append(group)
self.available.sort(key=lambda item: (item.default_order, item.label))
self._selected_side = "available"
self._render_lists()
def _move_selected(self, offset: int) -> None:
"""Move one configured group up or down."""
if self._selected_side != "selected":
return
index = next((i for i, item in enumerate(self.selected) if item.key == self._selected_key), -1)
target = index + int(offset)
if index < 0 or target < 0 or target >= len(self.selected):
return
self.selected[index], self.selected[target] = self.selected[target], self.selected[index]
self._render_lists()
def _start_drag(self, group: PickupGroup, side: str) -> None:
"""Remember the item being dragged."""
self._drag_group = group
self._drag_side = side
@staticmethod
def _is_descendant(widget: tk.Misc | None, ancestor: tk.Misc) -> bool:
"""Return whether a widget belongs to one list panel."""
current = widget
while current is not None:
if current == ancestor:
return True
current = getattr(current, "master", None)
return False
def _finish_drag(self, event) -> None:
"""Drop the dragged group into a list and place it near the pointer."""
group = self._drag_group
if group is None:
return
self._drag_group = None
try:
target_widget = self.winfo_containing(event.x_root, event.y_root)
except Exception:
return
if self._is_descendant(target_widget, self.selected_panel):
self.available = [item for item in self.available if item.key != group.key]
self.selected = [item for item in self.selected if item.key != group.key]
target_y = event.y_root - self.selected_list.winfo_rooty()
row_height = 42
target_index = max(0, min(len(self.selected), target_y // row_height))
self.selected.insert(target_index, group)
self._selected_side = "selected"
elif self._is_descendant(target_widget, self.available_panel):
self.selected = [item for item in self.selected if item.key != group.key]
if not any(item.key == group.key for item in self.available):
self.available.append(group)
self.available.sort(key=lambda item: (item.default_order, item.label))
self._selected_side = "available"
else:
return
self._selected_key = group.key
self._render_lists()
def _save_sql(self) -> tuple[str, dict[str, Any]]:
"""Build one atomic soft-delete/insert batch using bound parameters."""
params: dict[str, Any] = {
"documento": self.documento,
"utente": self.session.login if self.session else "SYSTEM",
}
values: list[str] = []
for index, group in enumerate(self.selected):
params[f"key_{index}"] = group.key
params[f"label_{index}"] = group.label
params[f"order_{index}"] = index
values.append(
f"(:documento, :key_{index}, :label_{index}, :order_{index}, :utente, SYSDATETIME(), :utente, SYSDATETIME())"
)
insert = ""
if values:
insert = """
INSERT INTO dbo.py_PickingListPrelievoSequenza (
Documento, GruppoChiave, GruppoEtichetta, Ordine,
InsUtente, InsDataOra, ModUtente, ModDataOra
)
VALUES
""" + ",\n".join(values) + ";"
sql = f"""
SET NOCOUNT ON;
SET XACT_ABORT ON;
UPDATE dbo.py_PickingListPrelievoSequenza
SET DelUtente = :utente,
DelDataOra = SYSDATETIME(),
ModUtente = :utente,
ModDataOra = SYSDATETIME()
WHERE Documento = :documento
AND DelDataOra IS NULL;
{insert}
SELECT CAST({len(values)} AS int) AS ElementiSalvati;
"""
return sql, params
def _save(self) -> None:
"""Persist the configured prefix atomically."""
sql, params = self._save_sql()
async def _job():
return await self.db_client.query_json(sql, params, commit=True)
self.runner.run(
_job(),
on_success=lambda _result: self._save_completed("saved"),
on_error=self._save_error,
busy=self.busy,
message=self._t("picking.sequence.busy.save", "Salvo la sequenza..."),
)
def _reset_default(self) -> None:
"""Delete the custom sequence so the shared default becomes active."""
async def _job():
return await self.db_client.query_json(
SQL_RESET_SEQUENCE,
{
"documento": self.documento,
"utente": self.session.login if self.session else "SYSTEM",
},
commit=True,
)
self.runner.run(
_job(),
on_success=lambda _result: self._save_completed("reset"),
on_error=self._save_error,
busy=self.busy,
message=self._t("picking.sequence.busy.save", "Salvo la sequenza..."),
)
def _save_completed(self, mode: str) -> None:
"""Refresh the editor and notify the parent after a successful save."""
message_key = "picking.sequence.msg.reset" if mode == "reset" else "picking.sequence.msg.saved"
default = (
"Sequenza personalizzata rimossa. E' attivo l'ordine predefinito."
if mode == "reset"
else "Sequenza salvata."
)
messagebox.showinfo(self._t("picking.sequence.title", "Sequenza di prelievo"), self._t(message_key, default), parent=self)
if self.on_saved:
self.on_saved()
self._selected_key = None
self._selected_side = None
self._load()
def _save_error(self, exc: BaseException) -> None:
"""Show a localized save error."""
messagebox.showerror(
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,
)
def open_pickinglist_sequence_window(
parent: tk.Misc,
db_client,
*,
documento: str,
session: UserSession | None,
on_saved: Callable[[], None] | None = None,
) -> PickingListSequenceWindow:
"""Open at most one sequence editor for the picking-list window."""
key = "_pickinglist_sequence_window_singleton"
existing = getattr(parent, key, None)
if existing is not None:
try:
if existing.winfo_exists() and existing.documento == str(documento).strip():
existing.on_saved = on_saved
existing.deiconify()
existing.lift()
existing.focus_force()
return existing
if existing.winfo_exists():
existing.destroy()
except Exception:
pass
window = PickingListSequenceWindow(
parent,
db_client,
documento=documento,
session=session,
on_saved=on_saved,
)
setattr(parent, key, window)
def _clear_reference() -> None:
try:
if getattr(parent, key, None) is window:
setattr(parent, key, None)
finally:
window.destroy()
window.protocol("WM_DELETE_WINDOW", _clear_reference)
return window

View File

@@ -10,6 +10,10 @@ from functools import wraps
from pathlib import Path
from typing import Any, Dict, List, Optional
from version_info import module_version
__version__ = module_version(__name__)
try:
from loguru import logger
except Exception: # pragma: no cover - safety fallback if dependency is missing locally
@@ -258,6 +262,8 @@ async def sp_xExePackingListPallet_async(db, IDOperatore: int, Documento: str, A
"""Execute the Python-specific picking-list reservation stored procedure."""
try:
azione = str(Azione or "P").strip().upper()
# The toolbar uses two explicit commands rather than a toggle:
# P = reserve the selected document, S = release it if it is active.
if azione not in ("P", "S"):
return SPResult(rc=-10, message=f"Azione non valida: {Azione}", id_result=None)
_MODULE_LOGGER.log(
@@ -279,6 +285,8 @@ async def sp_xExePackingListPallet_async(db, IDOperatore: int, Documento: str, A
_log_sql("py_sp_xExePackingListPallet", sql, {"IDOperatore": IDOperatore, "Documento": Documento, "Azione": azione})
if not hasattr(db, "query_json"):
raise RuntimeError("Il client DB non espone query_json necessario per eseguire la stored procedure.")
# commit=True is required because the stored procedure updates
# PyPickingListReservation and Celle.IDStato.
res = await db.query_json(
sql,
{"IDOperatore": IDOperatore, "Documento": Documento, "Azione": azione},
@@ -295,6 +303,23 @@ async def sp_xExePackingListPallet_async(db, IDOperatore: int, Documento: str, A
rc = int(rows[0].get("RC") or 0)
except Exception:
rc = 0
if rc == 0 and azione == "P":
resolve_sql = """
UPDATE dbo.py_BarcodePickingListSkip
SET Risolto = 1
WHERE Documento COLLATE Latin1_General_CI_AS =
CAST(:Documento AS varchar(50)) COLLATE Latin1_General_CI_AS
AND Risolto = 0;
"""
_log_sql("resolve_skipped_pallets_on_prenota", resolve_sql, {"Documento": Documento})
if hasattr(db, "exec"):
await db.exec(resolve_sql, {"Documento": Documento}, commit=True)
else:
await db.query_json(
resolve_sql + "\nSELECT 0 AS RC;",
{"Documento": Documento},
commit=True,
)
_MODULE_LOGGER.log(_MODULE_LOG_LEVEL, f"Stored procedure completata documento={Documento} azione={azione} rc={rc}")
return SPResult(rc=rc, message="", id_result=None)
except Exception as exc:

View File

@@ -23,9 +23,13 @@ from gestione_aree import AsyncRunner
from gestione_scarico import move_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_padding, theme_section, theme_value
from ui_theme import theme_color, theme_font, theme_section, theme_value
from ui_tables import style_treeview, zebra_tag
from version_info import module_version, versioned_title
from window_placement import place_window_fullsize_below_parent_later
__version__ = module_version(__name__)
try:
from loguru import logger
except Exception: # pragma: no cover - fallback used only when Loguru is not available
@@ -275,7 +279,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
super().__init__(parent)
self._theme = theme_section("reset_corsie", {})
self._locale_catalog = load_locale_catalog()
self.title(loc_text("reset.title", catalog=self._locale_catalog, default="Gestione Corsie - svuotamento celle per corsia"))
self.title(versioned_title(loc_text("reset.title", catalog=self._locale_catalog, default="Gestione Corsie - svuotamento celle per corsia"), __name__))
self.geometry(str(theme_value(self._theme, "window_geometry", "1000x680")))
minsize = theme_value(self._theme, "window_minsize", [880, 560])
self.minsize(int(minsize[0]), int(minsize[1]))
@@ -298,35 +302,6 @@ class ResetCorsieWindow(ctk.CTkToplevel):
def _setup_tree_style(self):
"""Apply a denser, spreadsheet-like style to the main result grid."""
style = ttk.Style(self)
style.configure(
"ResetCorsie.Treeview.Heading",
font=theme_font(self._theme, "tree_heading_font", ("Segoe UI", 10, "bold")),
background=theme_value(self._theme, "tree_heading_bg", "#b8c7db"),
foreground=theme_value(self._theme, "tree_heading_fg", "#10243e"),
relief="flat",
padding=theme_padding(self._theme, "tree_heading_padding", (8, 6)),
)
style.map(
"ResetCorsie.Treeview.Heading",
background=[("active", theme_value(self._theme, "tree_heading_bg_active", "#aebfd6"))],
relief=[("pressed", "groove"), ("!pressed", "flat")],
)
style.configure(
"ResetCorsie.Treeview",
font=theme_font(self._theme, "tree_body_font", ("Segoe UI", 10)),
rowheight=int(theme_value(self._theme, "tree_row_height", 30)),
background=theme_value(self._theme, "tree_body_bg", "#ffffff"),
fieldbackground=theme_value(self._theme, "tree_body_bg", "#ffffff"),
foreground=theme_value(self._theme, "tree_body_fg", "#1f1f1f"),
borderwidth=0,
)
style.map(
"ResetCorsie.Treeview",
background=[("selected", theme_value(self._theme, "tree_selected_bg", "#cfe4ff"))],
foreground=[("selected", theme_value(self._theme, "tree_selected_fg", "#10243e"))],
)
@_log_call()
def _build_ui(self):
"""Create selectors, summary widgets and the occupied-cell grid."""
@@ -411,8 +386,13 @@ class ResetCorsieWindow(ctk.CTkToplevel):
width=int(theme_value(self._theme, "tree_col_num_udc_width", 160)),
anchor=str(theme_value(self._theme, "tree_col_num_udc_anchor", "center")),
)
self.tree.tag_configure("odd", background=theme_value(self._theme, "tree_row_odd_bg", "#ffffff"))
self.tree.tag_configure("even", background=theme_value(self._theme, "tree_row_even_bg", "#f3f6fb"))
style_treeview(
self.tree,
style_name="ResetCorsie.Treeview",
rowheight=int(theme_value(self._theme, "tree_row_height", 30)),
font=theme_font(self._theme, "tree_body_font", ("Segoe UI", 10)),
heading_font=theme_font(self._theme, "tree_heading_font", ("Segoe UI", 10, "bold")),
)
sy = ttk.Scrollbar(mid, orient="vertical", command=self.tree.yview)
sx = ttk.Scrollbar(mid, orient="horizontal", command=self.tree.xview)
@@ -529,7 +509,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
for item in self.tree.get_children():
self.tree.delete(item)
for idx, (_idc, ubi, n) in enumerate(det_rows):
tag = "even" if idx % 2 else "odd"
tag = zebra_tag(idx)
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}")

View File

@@ -0,0 +1,9 @@
SET XACT_ABORT ON;
BEGIN TRANSACTION;
IF OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U') IS NOT NULL
BEGIN
DROP TABLE dbo.py_BarcodePickingListSkip;
END;
COMMIT TRANSACTION;

View File

@@ -0,0 +1,76 @@
/*
Rollback: intervallo giorni selezionabile in Gestione Picking List Python
Effetto:
- ripristina le viste Python precedenti, appoggiate a dbo.XMag_ViewPackingList;
- il filtro effettivo torna quindi a quello legacy fisso a 10 giorni.
*/
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER VIEW [dbo].[py_XMag_ViewPackingList]
AS
SELECT TOP 10000
legacy.Pallet,
legacy.Lotto,
legacy.Articolo,
legacy.Descrizione,
legacy.Qta,
legacy.Documento,
legacy.CodNazione,
legacy.NAZIONE,
legacy.Stato,
legacy.PalletCella,
legacy.Magazzino,
legacy.Area,
legacy.Cella,
legacy.Ordinamento,
legacy.Ubicazione,
legacy.DEST,
CASE
WHEN pr.Documento IS NOT NULL
AND pr.Documento = CAST(legacy.Documento AS varchar(8))
THEN 1
ELSE 0
END AS IDStato
FROM dbo.XMag_ViewPackingList AS legacy
LEFT JOIN dbo.PyPickingListReservation AS pr
ON pr.ID = 1
AND NULLIF(LTRIM(RTRIM(pr.Documento)), '') IS NOT NULL
ORDER BY
CASE
WHEN pr.Documento IS NOT NULL
AND pr.Documento = CAST(legacy.Documento AS varchar(8))
THEN 1
ELSE 0
END DESC,
legacy.Documento,
legacy.Ordinamento;
GO
CREATE OR ALTER VIEW [dbo].[py_ViewPackingListRestante]
AS
SELECT
Pallet,
Lotto,
Articolo,
Descrizione,
Qta,
Documento,
CodNazione,
NAZIONE,
Stato,
PalletCella,
Magazzino,
Area,
Cella,
Ordinamento,
Ubicazione,
DEST,
IDStato
FROM dbo.py_XMag_ViewPackingList
WHERE Cella <> 9999;
GO

View File

@@ -0,0 +1,19 @@
/*
Rollback della sequenza personalizzata per picking list.
Attenzione:
- elimina le configurazioni di sequenza salvate nel ramo Python;
- non modifica gli oggetti legacy C#;
- dopo il rollback occorre usare una versione Python precedente alla feature.
*/
IF OBJECT_ID(N'dbo.py_ViewPackingListPrelievo', N'V') IS NOT NULL
DROP VIEW dbo.py_ViewPackingListPrelievo;
GO
IF OBJECT_ID(N'dbo.py_PickingListPrelievoSequenza', N'U') IS NOT NULL
DROP TABLE dbo.py_PickingListPrelievoSequenza;
GO
PRINT 'Rollback sequenza prelievo Python completato.';
GO

View File

@@ -3,28 +3,47 @@
from __future__ import annotations
import sys
import threading
import traceback
from datetime import datetime
from pathlib import Path
import tempfile
from typing import Callable, TypeVar
from version_info import module_version
__version__ = module_version(__name__)
BASE_DIR = Path(__file__).resolve().parent
FATAL_LOG = BASE_DIR / "warehouse_fatal.log"
TEMP_DIR = Path(tempfile.gettempdir())
_STDIO_HANDLES = []
_EXCEPTION_LOGGING_CONFIGURED: set[str] = set()
T = TypeVar("T")
def _open_log_file(path: Path):
"""Open a log path, falling back to the user temp directory when needed."""
try:
path.parent.mkdir(parents=True, exist_ok=True)
return path.open("a", encoding="utf-8", buffering=1)
except Exception:
fallback = TEMP_DIR / path.name
fallback.parent.mkdir(parents=True, exist_ok=True)
return fallback.open("a", encoding="utf-8", buffering=1)
def ensure_stdio(app_name: str) -> None:
"""Give ``pythonw`` a real stdout/stderr target before loggers are imported."""
stamp = datetime.now().strftime("%Y%m%d")
if sys.stdout is None:
handle = (BASE_DIR / f"{app_name}_stdout_{stamp}.log").open("a", encoding="utf-8", buffering=1)
handle = _open_log_file(BASE_DIR / f"{app_name}_stdout_{stamp}.log")
_STDIO_HANDLES.append(handle)
sys.stdout = handle
if sys.stderr is None:
handle = (BASE_DIR / f"{app_name}_stderr_{stamp}.log").open("a", encoding="utf-8", buffering=1)
handle = _open_log_file(BASE_DIR / f"{app_name}_stderr_{stamp}.log")
_STDIO_HANDLES.append(handle)
sys.stderr = handle
@@ -32,12 +51,100 @@ def ensure_stdio(app_name: str) -> None:
def log_fatal(app_name: str, exc: BaseException) -> None:
"""Write one startup/runtime crash to a persistent log file."""
with FATAL_LOG.open("a", encoding="utf-8") as handle:
with _open_log_file(FATAL_LOG) as handle:
handle.write("\n" + "=" * 80 + "\n")
handle.write(f"{datetime.now():%Y-%m-%d %H:%M:%S} | {app_name}\n")
handle.write("".join(traceback.format_exception(type(exc), exc, exc.__traceback__)))
def log_exception(app_name: str, exc: BaseException, *, context: str = "") -> None:
"""Write a handled or callback exception to the persistent fatal log."""
with _open_log_file(FATAL_LOG) as handle:
handle.write("\n" + "=" * 80 + "\n")
handle.write(f"{datetime.now():%Y-%m-%d %H:%M:%S} | {app_name}")
if context:
handle.write(f" | {context}")
handle.write("\n")
handle.write("".join(traceback.format_exception(type(exc), exc, exc.__traceback__)))
def configure_exception_logging(app_name: str, root=None, loop=None) -> None:
"""Install process, Tk and asyncio exception hooks for console-less apps."""
if app_name in _EXCEPTION_LOGGING_CONFIGURED:
return
_EXCEPTION_LOGGING_CONFIGURED.add(app_name)
previous_excepthook = sys.excepthook
def _sys_excepthook(exc_type, exc, tb):
log_exception(app_name, exc, context="sys.excepthook")
if previous_excepthook:
previous_excepthook(exc_type, exc, tb)
sys.excepthook = _sys_excepthook
if hasattr(threading, "excepthook"):
previous_threading_excepthook = threading.excepthook
def _threading_excepthook(args):
log_exception(app_name, args.exc_value, context=f"thread={getattr(args.thread, 'name', '')}")
previous_threading_excepthook(args)
threading.excepthook = _threading_excepthook
if root is not None:
def _tk_exception(exc_type, exc, tb):
log_exception(app_name, exc, context="tkinter callback")
try:
import tkinter.messagebox 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,
)
except Exception:
pass
try:
root.report_callback_exception = _tk_exception
except Exception:
pass
if loop is not None:
previous_loop_handler = None
try:
previous_loop_handler = loop.get_exception_handler()
except Exception:
previous_loop_handler = None
def _loop_exception_handler(active_loop, context):
exc = context.get("exception")
if exc is not None:
log_exception(app_name, exc, context=f"asyncio: {context.get('message', '')}")
else:
log_runtime_event(app_name, f"ASYNCIO {context!r}")
if previous_loop_handler is not None:
previous_loop_handler(active_loop, context)
try:
loop.set_exception_handler(_loop_exception_handler)
except Exception:
pass
def log_runtime_event(app_name: str, message: str) -> None:
"""Write a lightweight launch/shutdown trace for console-less starts."""
safe_name = "".join(ch if ch.isalnum() or ch in ("_", "-") else "_" for ch in app_name.lower())
path = BASE_DIR / f"{safe_name}_launch.log"
with _open_log_file(path) as handle:
handle.write(f"{datetime.now():%Y-%m-%d %H:%M:%S} | {message}\n")
def show_fatal_message(app_name: str, exc: BaseException) -> None:
"""Show a best-effort message box for console-less launches."""
@@ -49,7 +156,10 @@ def show_fatal_message(app_name: str, exc: BaseException) -> None:
root.withdraw()
messagebox.showerror(
app_name,
f"Avvio non riuscito.\n\nDettaglio salvato in:\n{FATAL_LOG}\n\n{exc}",
"Avvio non riuscito.\n\n"
f"Controlla i log in:\n{BASE_DIR}\n\n"
f"Se non ci sono, controlla anche:\n{TEMP_DIR}\n\n"
f"{exc}",
parent=root,
)
root.destroy()
@@ -61,8 +171,15 @@ def run_with_fatal_log(app_name: str, func: Callable[[], T]) -> T:
"""Run an app entry point and persist otherwise invisible ``pythonw`` crashes."""
try:
return func()
log_runtime_event(
app_name,
f"START exe={sys.executable!r} version={sys.version.split()[0]} cwd={Path.cwd()} base={BASE_DIR} argv={sys.argv!r}",
)
result = func()
log_runtime_event(app_name, f"RETURN result={result!r}")
return result
except BaseException as exc:
log_runtime_event(app_name, f"EXCEPTION type={type(exc).__name__} value={exc!r}")
log_fatal(app_name, exc)
show_fatal_message(app_name, exc)
raise

View File

@@ -11,9 +11,19 @@ from busy_overlay import InlineBusyOverlay
from gestione_aree import AsyncRunner
from locale_text import load_locale_catalog, text as loc_text
from ui_theme import theme_color, theme_font, theme_section, theme_value
from ui_tables import (
apply_tksheet_visual_style,
apply_tksheet_zebra,
merge_tags,
style_treeview,
zebra_tag,
)
from version_info import module_version, versioned_title
from window_placement import place_window_fullsize_below_parent_later
from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text
__version__ = module_version(__name__)
try:
from openpyxl import Workbook
from openpyxl.styles import Alignment, Font
@@ -85,7 +95,7 @@ class SearchWindow(ctk.CTkToplevel):
self._theme = theme_section("search_window", {})
self._locale_catalog = load_locale_catalog()
self._tooltip_catalog = load_tooltip_catalog()
self.title(loc_text("search.title", catalog=self._locale_catalog, default="Ricerca UDC/Lotto/Codice"))
self.title(versioned_title(loc_text("search.title", catalog=self._locale_catalog, default="Ricerca UDC/Lotto/Codice"), __name__))
self.geometry(str(theme_value(self._theme, "window_geometry", "1100x720")))
minsize = theme_value(self._theme, "window_minsize", [900, 560])
self.minsize(int(minsize[0]), int(minsize[1]))
@@ -174,17 +184,25 @@ class SearchWindow(ctk.CTkToplevel):
self.use_sheet = False
cols = ("IDCella", "Ubicazione", "UDC", "Lotto", "Codice", "Descrizione")
self.tree = ttk.Treeview(wrap, columns=cols, show="headings")
self._style = ttk.Style(self)
try:
self._style.theme_use(self._style.theme_use())
except Exception:
pass
self._style.configure("Search.Treeview", rowheight=22, font=("", 9))
self._style.configure("Search.Treeview.Heading", font=("", 9, "bold"), background="#F3F4F6")
self._style.map("Search.Treeview", background=[("selected", "#DCEBFF")])
self.tree.configure(style="Search.Treeview")
self.tree.tag_configure("even", background="#FFFFFF")
self.tree.tag_configure("odd", background="#F7F9FC")
headings = {
"IDCella": ("IDCella", 90, "e"),
"Ubicazione": ("Ubicazione", 150, "w"),
"UDC": ("UDC / Barcode", 130, "w"),
"Lotto": ("Lotto", 130, "w"),
"Codice": ("Codice prodotto", 150, "w"),
"Descrizione": ("Descrizione prodotto", 340, "w"),
}
for col in cols:
text, width, anchor = headings[col]
self.tree.heading(col, text=text)
self.tree.column(col, width=width, anchor=anchor, stretch=True)
self._style = style_treeview(
self.tree,
style_name="Search.Treeview",
rowheight=22,
font=("", 9),
heading_font=("", 9, "bold"),
)
self.tree.tag_configure("id9999", background="#FFECEC", foreground="#B00020")
sy = ttk.Scrollbar(wrap, orient="vertical", command=self.tree.yview)
@@ -209,7 +227,7 @@ class SearchWindow(ctk.CTkToplevel):
is9999 = int(vals[0]) == 9999
except Exception:
is9999 = False
tags = ("id9999", zebra) if is9999 else (zebra,)
tags = merge_tags(zebra, "id9999" if is9999 else "")
self.tree.item(iid, tags=tags)
def _export_xlsx(self):
@@ -414,6 +432,8 @@ class SearchWindow(ctk.CTkToplevel):
hdrs = list(headers)
hdrs[c] = hdrs[c] + arrow
self.sheet.headers(hdrs)
apply_tksheet_visual_style(self.sheet)
apply_tksheet_zebra(self.sheet, len(data))
except Exception:
pass
@@ -449,7 +469,10 @@ class SearchWindow(ctk.CTkToplevel):
for row in rows:
idc, ubi, udc_v, lot_v, cod_v, desc_v = row
data.append([idc, ubi, udc_v, lot_v, cod_v, desc_v])
self.sheet.headers(["IDCella", "Ubicazione", "UDC", "Lotto", "Codice", "Descrizione"])
apply_tksheet_visual_style(self.sheet)
self.sheet.set_sheet_data(data)
apply_tksheet_zebra(self.sheet, len(data))
self.sheet.set_all_cell_sizes_to_text()
except Exception:
self.use_sheet = False
@@ -458,12 +481,11 @@ class SearchWindow(ctk.CTkToplevel):
self.tree.delete(iid)
for idx, row in enumerate(rows):
idc, ubi, udc_v, lot_v, cod_v, desc_v = row
zebra = "even" if idx % 2 == 0 else "odd"
try:
is9999 = int(idc) == 9999
except Exception:
is9999 = False
tags = ("id9999", zebra) if is9999 else (zebra,)
tags = merge_tags(zebra_tag(idx), "id9999" if is9999 else "")
self.tree.insert("", "end", values=(idc, ubi, udc_v, lot_v, cod_v, desc_v), tags=tags)
if not rows:

View File

@@ -0,0 +1,74 @@
# Sequenza di prelievo per picking list
## Obiettivo
Consentire al responsabile di definire, per una singola picking list, l'ordine
dei gruppi di ubicazioni che il barcode deve seguire. Il barcode continua a
presentare una sola UDC alla volta e non espone la configurazione all'operatore.
## Ordine predefinito
In assenza di una configurazione personalizzata il sistema propone:
1. UDC `Non scaff.` nella cella convenzionale `1000` / `5E.1.1`.
2. UDC negli scaffali secondo il valore legacy `Celle.Ordinamento`.
L'ordinamento globale delle celle non viene modificato.
## Configurazione per documento
La finestra `Sequenza di prelievo` si apre dalla picking list selezionata in
`Gestione Picking List`. I gruppi disponibili sono `Non scaff.` e le corsie
effettivamente presenti nel contenuto residuo del documento.
L'utente puo' trascinare i gruppi nell'area destra, usare il doppio clic oppure
i pulsanti `Aggiungi`, `Rimuovi`, `Su` e `Giu'`. L'ordine dall'alto verso il
basso definisce la precedenza dei gruppi configurati.
Una sequenza puo' essere parziale: gli eventuali gruppi non inseriti vengono
accodati secondo l'ordine predefinito. In questo modo una configurazione non
puo' rendere invisibili UDC o scaffali aggiunti successivamente alla picking
list.
`Ripristina default` elimina la configurazione del documento e riattiva
immediatamente l'ordine standard.
## Persistenza e concorrenza
La tabella Python-only `dbo.py_PickingListPrelievoSequenza` memorizza una riga
per documento e gruppo, con ordine e campi di audit. Il salvataggio marca come
cancellata la configurazione precedente e inserisce quella nuova in una singola
transazione con `XACT_ABORT ON`, conservando quindi anche lo storico delle
variazioni.
Due picking list possono quindi avere sequenze diverse senza modificare le
celle, le altre liste o gli oggetti usati dal programma C#.
## Consumo dal barcode
La vista Python-only `dbo.py_ViewPackingListPrelievo` deriva dalla vista
residuale, esclude quindi le UDC gia' in `7G.1.1` e calcola
`OrdinePrelievoGruppo`. Sia la griglia di dettaglio sia il repository barcode
ordinano per:
1. `OrdinePrelievoGruppo`;
2. `Ordinamento` legacy della cella;
3. codice pallet come criterio stabile finale.
Pausa, ripresa, salto UDC, F1/F2 e prenotazione non vengono modificati. Quando
una UDC viene movimentata, la richiesta successiva rilegge la vista e usa la
sequenza corrente sul contenuto residuo.
## Installazione e rollback
Per un aggiornamento completo del database online usare
`apply_online_python_wms_full_patch.sql`.
Per applicare solo questa evoluzione a un database gia' aggiornato:
1. eseguire `apply_pickinglist_days_filter_patch.sql`;
2. eseguire `apply_pickinglist_sequence_patch.sql`.
Il rollback specifico e' `rollback_pickinglist_sequence_patch.sql`; dopo il
rollback deve essere ripristinata anche una versione applicativa precedente,
poiche' il nuovo codice interroga la vista di prelievo.

View File

@@ -1,4 +1,11 @@
"""Read-only picking-list history window."""
"""Picking-list history window and controlled residual-shipment workflow.
The window is mostly read-only: it summarizes historical picking lists and shows
their UDC detail rows. The only write operation is the explicit, user-confirmed
"Versa residui in 7G.1.1" action for lists classified as closed with residuals.
That action delegates each UDC movement to ``move_pallet_async`` so the same
MagazziniPallet trace used by the rest of the WMS is preserved.
"""
from __future__ import annotations
@@ -11,55 +18,88 @@ import customtkinter as ctk
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 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
from window_placement import place_window_fullsize_below_parent_later
__version__ = module_version(__name__)
# Master query:
# - reads the Python-only historical view, not the legacy C# views;
# - groups repeated lot rows by distinct UDC/PalletKey;
# - derives the operational status shown in the upper grid.
SQL_STORICO_PL = """
WITH base AS (
SELECT *
SELECT
*,
NULLIF(LTRIM(RTRIM(CAST(Pallet AS varchar(32)))), '') AS PalletKey
FROM dbo.py_XMag_ViewPackingListStorico
),
agg AS (
pallets AS (
SELECT
Documento,
PalletKey,
MAX(CASE WHEN Cella <> 9999 OR Cella IS NULL THEN 1 ELSE 0 END) AS HasResiduo,
MAX(CASE WHEN Cella = 9999 THEN 1 ELSE 0 END) AS HasSpedito
FROM base
WHERE PalletKey IS NOT NULL
GROUP BY Documento, PalletKey
),
meta AS (
SELECT
Documento,
MAX(DataDocumento) AS DataDocumento,
MAX(StatoDocumento) AS StatoDocumento,
MAX(NAZIONE) AS NAZIONE,
MAX(CodNazione) AS CodNazione,
COUNT(DISTINCT Pallet) AS TotUDC,
SUM(CASE WHEN Cella = 9999 THEN 1 ELSE 0 END) AS RigheSpedite,
SUM(CASE WHEN Cella <> 9999 OR Cella IS NULL THEN 1 ELSE 0 END) AS RigheResidue,
COUNT(*) AS RigheTotali,
MIN(Ordinamento) AS PrimoOrdine,
MAX(IDStato) AS IDStato
FROM base
GROUP BY Documento
),
agg AS (
SELECT
Documento,
COUNT(*) AS TotUDC,
SUM(CASE WHEN p.HasResiduo = 0 AND p.HasSpedito = 1 THEN 1 ELSE 0 END) AS RigheSpedite,
SUM(CASE WHEN p.HasResiduo = 1 THEN 1 ELSE 0 END) AS RigheResidue
FROM pallets p
GROUP BY Documento
)
SELECT
Documento,
DataDocumento,
StatoDocumento,
NAZIONE,
CodNazione,
TotUDC,
RigheResidue,
RigheSpedite,
RigheTotali,
m.Documento,
m.DataDocumento,
m.StatoDocumento,
m.NAZIONE,
m.CodNazione,
COALESCE(a.TotUDC, 0) AS TotUDC,
COALESCE(a.RigheResidue, 0) AS RigheResidue,
COALESCE(a.RigheSpedite, 0) AS RigheSpedite,
m.RigheTotali,
CASE
WHEN StatoDocumento = 'D' THEN 'Chiusa'
WHEN RigheResidue = 0 THEN 'Esaurita'
WHEN RigheSpedite > 0 THEN 'In corso'
WHEN m.StatoDocumento = 'D' AND COALESCE(a.RigheResidue, 0) > 0 THEN 'Chiusa ERP con residui'
WHEN m.StatoDocumento = 'D' THEN 'Chiusa'
WHEN COALESCE(a.RigheResidue, 0) = 0 THEN 'Esaurita'
WHEN COALESCE(a.RigheSpedite, 0) > 0 THEN 'In corso'
ELSE 'Da lavorare'
END AS StatoOperativo,
IDStato,
PrimoOrdine
FROM agg
WHERE (:documento IS NULL OR CAST(Documento AS varchar(32)) LIKE CONCAT('%', :documento, '%'))
ORDER BY Documento DESC;
m.IDStato,
m.PrimoOrdine
FROM meta m
LEFT JOIN agg a ON a.Documento = m.Documento
WHERE (:documento IS NULL OR CAST(m.Documento AS varchar(32)) LIKE CONCAT('%', :documento, '%'))
ORDER BY m.DataDocumento DESC, m.Documento DESC;
"""
# Detail query:
# - returns the ERP picking-list rows enriched with the current WMS cell;
# - may contain multiple rows for the same UDC when the pallet contains more lots;
# - is intentionally ordered by warehouse extraction order, then pallet.
SQL_STORICO_PL_DETAILS = """
SELECT
Documento,
@@ -135,8 +175,11 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
self._async = AsyncRunner(self)
self._busy = InlineBusyOverlay(self, self._theme)
self.var_documento = tk.StringVar()
self._selected_documento: str | None = None
self._selected_stato_operativo: str = ""
self._detail_rows: list[dict[str, Any]] = []
self.title(loc_text("history.picking.title", catalog=self._locale_catalog, default="Storico Picking List"))
self.title(versioned_title(loc_text("history.picking.title", catalog=self._locale_catalog, default="Storico Picking List"), __name__))
self.geometry(str(theme_value(self._theme, "window_geometry", "1200x720")))
minsize = theme_value(self._theme, "window_minsize", [980, 560])
self.minsize(int(minsize[0]), int(minsize[1]))
@@ -158,7 +201,7 @@ 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(3, weight=1)
top.grid_columnconfigure(4, 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))
@@ -176,6 +219,18 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
).grid(
row=0, column=2, sticky="w"
)
self.btn_ship_residuals = ctk.CTkButton(
top,
text=loc_text(
"history.picking.button.ship_residuals",
catalog=self._locale_catalog,
default="Versa residui in 7G.1.1",
),
command=self._ship_selected_residuals,
state="disabled",
font=button_font,
)
self.btn_ship_residuals.grid(row=0, column=3, sticky="w", padx=(12, 0))
self.master_tree = self._make_tree(
row=1,
@@ -228,8 +283,10 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
for col in columns:
tree.heading(col, text=col)
tree.column(col, width=widths.get(col, 100), anchor="w")
style_treeview(tree, style_name="HistoryPicking.Treeview", rowheight=24)
tree.tag_configure("done", background="#ECECEC")
tree.tag_configure("active", background="#EAF7EA")
tree.tag_configure("warning", background="#FFE3B3")
sy = ttk.Scrollbar(wrap, orient="vertical", command=tree.yview)
sx = ttk.Scrollbar(wrap, orient="horizontal", command=tree.xview)
tree.configure(yscrollcommand=sy.set, xscrollcommand=sx.set)
@@ -240,12 +297,15 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
def _load_master(self) -> None:
params = {"documento": str(self.var_documento.get() or "").strip() or None}
previous_documento = self._selected_documento
async def _job():
return await self.db_client.query_json(SQL_STORICO_PL, params)
def _ok(res):
self._fill_master(_rows_to_dicts(res))
if previous_documento:
self._restore_master_selection(previous_documento)
def _err(ex):
messagebox.showerror(
@@ -273,9 +333,25 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
def _fill_master(self, rows: list[dict[str, Any]]) -> None:
self.master_tree.delete(*self.master_tree.get_children(""))
self.detail_tree.delete(*self.detail_tree.get_children(""))
self._selected_documento = None
self._selected_stato_operativo = ""
self._detail_rows = []
self._update_residual_button()
for index, row in enumerate(rows):
stato = str(row.get("StatoOperativo") or "")
tag = "done" if stato in {"Chiusa", "Esaurita"} else "active" if int(row.get("IDStato") or 0) == 1 else ""
is_open_with_shipped = (
str(row.get("StatoDocumento") or "") == "P"
and int(row.get("RigheSpedite") or 0) > 0
)
tag = (
"warning"
if is_open_with_shipped
else "done"
if stato in {"Chiusa", "Esaurita"}
else "active"
if int(row.get("IDStato") or 0) == 1
else ""
)
self.master_tree.insert(
"",
"end",
@@ -291,23 +367,32 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
stato,
row.get("IDStato", ""),
),
tags=(tag,) if tag else (),
tags=merge_tags(zebra_tag(index), tag),
)
def _on_master_select(self, _event=None) -> None:
selected = self.master_tree.selection()
if not selected:
self._selected_documento = None
self._selected_stato_operativo = ""
self._detail_rows = []
self._update_residual_button()
return
values = self.master_tree.item(selected[0], "values")
if not values:
return
documento = values[0]
self._selected_documento = str(documento)
self._selected_stato_operativo = str(values[7] if len(values) > 7 else "")
self._detail_rows = []
self._update_residual_button()
async def _job():
return await self.db_client.query_json(SQL_STORICO_PL_DETAILS, {"documento": documento})
def _ok(res):
self._fill_detail(_rows_to_dicts(res))
self._update_residual_button()
def _err(ex):
messagebox.showerror(
@@ -334,8 +419,11 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
def _fill_detail(self, rows: list[dict[str, Any]]) -> None:
self.detail_tree.delete(*self.detail_tree.get_children(""))
for row in rows:
self._detail_rows = rows
for index, row in enumerate(rows):
is_open_shipped = str(row.get("StatoDocumento") or "") == "P" and int(row.get("Cella") or 0) == 9999
done = str(row.get("StatoDocumento") or "") == "D" or int(row.get("Cella") or 0) == 9999
tag = "warning" if is_open_shipped else "done" if done else ""
self.detail_tree.insert(
"",
"end",
@@ -351,7 +439,128 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
row.get("Ubicazione", ""),
row.get("Ordinamento", ""),
),
tags=("done",) if done else (),
tags=merge_tags(zebra_tag(index), tag),
)
def _update_residual_button(self) -> None:
"""Enable the bulk shipment button only for closed picking lists with residual UDCs."""
enabled = self._selected_stato_operativo == "Chiusa ERP con residui"
try:
self.btn_ship_residuals.configure(state="normal" if enabled else "disabled")
except Exception:
pass
def _restore_master_selection(self, documento: str) -> 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):
self.master_tree.selection_set(iid)
self.master_tree.focus(iid)
self.master_tree.see(iid)
self._on_master_select()
return
def _residual_pallets_from_rows(self, rows: list[dict[str, Any]]) -> list[str]:
"""Return distinct residual UDCs that are not already in 7G.1.1."""
pallets: list[str] = []
seen: set[str] = set()
for row in rows:
pallet = str(row.get("Pallet") or "").strip()
# One UDC can appear on multiple detail rows when it contains
# multiple lots; movement must be executed once per physical UDC.
if not pallet or pallet in seen:
continue
try:
cella = int(row.get("Cella") or 0)
except Exception:
cella = 0
# IDCella 9999 is the conventional 7G.1.1 shipment cell. Rows
# already there are complete and must not receive another movement.
if cella == 9999:
continue
seen.add(pallet)
pallets.append(pallet)
return pallets
def _operator_login(self) -> str:
"""Return the user recorded on generated warehouse movements."""
login = str(getattr(self.session, "login", "") or "").strip()
return login or "warehouse_ui"
def _ship_selected_residuals(self) -> None:
"""Move all residual UDCs of the selected closed PL to the shipment cell 7G.1.1."""
if self._selected_stato_operativo != "Chiusa ERP con residui" or not self._selected_documento:
return
estimated = self._residual_pallets_from_rows(self._detail_rows)
count_text = str(len(estimated)) if estimated else "le"
if not messagebox.askyesno(
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
(
f"Documento {self._selected_documento}\n\n"
f"Verranno versate in 7G.1.1 {count_text} UDC residue della picking list chiusa.\n"
"L'operazione registra i movimenti nello storico UDC.\n\n"
"Procedere?"
),
parent=self,
):
return
documento = self._selected_documento
utente = self._operator_login()
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_rows = _rows_to_dicts(detail_res)
pallets = self._residual_pallets_from_rows(detail_rows)
results: list[dict[str, Any]] = []
for pallet in pallets:
# Reuse the central movement primitive: it closes the current
# source V row with a P movement and inserts a new V on 9999,
# preserving the historical trail required by Storico UDC.
result = await move_pallet_async(
self.db_client,
barcode_pallet=pallet,
target_idcella=9999,
target_barcode_cella="9000000",
utente=utente,
)
results.append(result)
return {"pallets": pallets, "results": results}
def _ok(res):
pallets = res.get("pallets", []) if isinstance(res, dict) else []
results = res.get("results", []) if isinstance(res, dict) else []
moved = sum(1 for row in results if int(row.get("ok") or 0) == 1)
messagebox.showinfo(
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
f"Documento {documento}\nUDC residue trovate: {len(pallets)}\nUDC versate in 7G.1.1: {moved}",
parent=self,
)
self._selected_documento = str(documento)
self._load_master()
def _err(ex):
messagebox.showerror(
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
f"Versamento residui fallito:\n{ex}",
parent=self,
)
self._async.run(
_job(),
_ok,
_err,
busy=self._busy,
message=f"Verso residui PL {documento} in 7G.1.1...",
)

View File

@@ -12,8 +12,12 @@ from busy_overlay import InlineBusyOverlay
from gestione_aree import AsyncRunner
from locale_text import load_locale_catalog, text as loc_text
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
from window_placement import place_window_fullsize_below_parent_later
__version__ = module_version(__name__)
SQL_STORICO_UDC = """
WITH direct AS (
@@ -155,7 +159,7 @@ class StoricoUDCWindow(ctk.CTkToplevel):
self._busy = InlineBusyOverlay(self, self._theme)
self.var_udc = tk.StringVar(value=str(initial_udc or ""))
self.title(loc_text("history.udc.title", catalog=self._locale_catalog, default="Storico movimenti UDC"))
self.title(versioned_title(loc_text("history.udc.title", catalog=self._locale_catalog, default="Storico movimenti UDC"), __name__))
self.geometry(str(theme_value(self._theme, "window_geometry", "1100x720")))
minsize = theme_value(self._theme, "window_minsize", [900, 560])
self.minsize(int(minsize[0]), int(minsize[1]))
@@ -218,6 +222,7 @@ class StoricoUDCWindow(ctk.CTkToplevel):
for col in cols:
self.tree.heading(col, text=col)
self.tree.column(col, width=90, anchor="w")
style_treeview(self.tree, style_name="HistoryUDC.Treeview", rowheight=24)
self.tree.column("ID", width=70, anchor="e")
self.tree.column("Tipo", width=55, anchor="center")
self.tree.column("Rif", width=70, anchor="e")
@@ -280,7 +285,7 @@ class StoricoUDCWindow(ctk.CTkToplevel):
value = row.get(name, "")
return "" if value is None else value
for row in rows:
for index, row in enumerate(rows):
tipo = str(row.get("Tipo") or "")
tag = "versamento" if tipo == "V" else "prelievo" if tipo == "P" else "spedita" if tipo == "SPED" else ""
self.tree.insert(
@@ -299,7 +304,7 @@ class StoricoUDCWindow(ctk.CTkToplevel):
_value(row, "ModUtente"),
_value(row, "ModDataOra"),
),
tags=(tag,) if tag else (),
tags=merge_tags(zebra_tag(index), tag),
)

View File

@@ -8,6 +8,7 @@
"launcher.open_history_udc": "Apre lo storico movimenti UDC per ricostruire carichi, scarichi, celle e utenti coinvolti.",
"launcher.open_pickinglist": "Apre la gestione delle picking list per prenotare, controllare e aggiornare le liste di prelievo.",
"launcher.open_history_pickinglist": "Apre lo storico picking list per consultare liste, stato operativo e dettaglio UDC.",
"launcher.open_diagnostics": "Apre la diagnostica operativa con quadrature e controlli di coerenza sui dati di magazzino.",
"launcher.arrange_windows": "Dispone in cascata le finestre aperte seguendo l'ordine dei pulsanti del launcher.",
"launcher.exit": "Chiude l'applicazione in modo pulito terminando la sessione utente e rilasciando la connessione condivisa al database.",
"dbconfig.heading": "Spiega che qui si inseriscono i dati minimi per permettere al programma di collegarsi al database del magazzino al primo avvio.",
@@ -32,7 +33,15 @@
"multi_udc.collapse_all": "Comprime tutti i nodi dell'albero.",
"multi_udc.preselect": "Espande la corsia selezionata e preseleziona automaticamente le UDC con causale fantasma.",
"multi_udc.remove_ghosts": "Scarica logicamente le UDC selezionate della corsia attiva verso l'ubicazione di uscita.",
"multi_udc.export_xlsx": "Esporta in Excel il contenuto corrente della vista UDC fantasma."
"multi_udc.export_xlsx": "Esporta in Excel il contenuto corrente della vista UDC fantasma.",
"picking.sequence.item": "Seleziona il gruppo. Puoi trascinarlo nell'altra area oppure usare doppio clic e pulsanti centrali.",
"picking.sequence.add": "Aggiunge il gruppo selezionato alla fine della sequenza personalizzata.",
"picking.sequence.remove": "Rimuove il gruppo dalla sequenza personalizzata e lo riporta tra quelli disponibili.",
"picking.sequence.up": "Sposta il gruppo selezionato una posizione verso l'alto.",
"picking.sequence.down": "Sposta il gruppo selezionato una posizione verso il basso.",
"picking.sequence.save": "Salva in modo atomico la sequenza per la picking list corrente.",
"picking.sequence.reset": "Elimina la personalizzazione e ripristina Non scaff. prima degli scaffali.",
"picking.sequence.close": "Chiude la finestra senza effettuare altri salvataggi."
},
"ENG": {
"launcher.open_reset_corsie": "Open the aisle management window to inspect an aisle and empty it in a controlled way.",
@@ -42,6 +51,7 @@
"launcher.open_history_udc": "Open UDC movement history to review loads, unloads, cells and users involved.",
"launcher.open_pickinglist": "Open picking list management to reserve, inspect and update picking lists.",
"launcher.open_history_pickinglist": "Open picking-list history to inspect lists, operational status and UDC detail.",
"launcher.open_diagnostics": "Open operational diagnostics with data consistency checks and warehouse quadratures.",
"launcher.arrange_windows": "Arrange open windows in cascade order following the launcher buttons.",
"launcher.exit": "Close the application cleanly by ending the user session and releasing the shared database connection.",
"dbconfig.heading": "Explain that this form collects the minimum data needed to connect the program to the warehouse database on first startup.",
@@ -66,6 +76,14 @@
"multi_udc.collapse_all": "Collapse all tree nodes.",
"multi_udc.preselect": "Expand the selected aisle and automatically preselect UDCs classified as ghost candidates.",
"multi_udc.remove_ghosts": "Logically unload the selected UDCs of the active aisle to the outbound location.",
"multi_udc.export_xlsx": "Export the current ghost UDC view to Excel."
"multi_udc.export_xlsx": "Export the current ghost UDC view to Excel.",
"picking.sequence.item": "Select the group. You can drag it to the other area or use double-click and the center buttons.",
"picking.sequence.add": "Append the selected group to the custom sequence.",
"picking.sequence.remove": "Remove the group from the custom sequence and return it to the available list.",
"picking.sequence.up": "Move the selected group one position up.",
"picking.sequence.down": "Move the selected group one position down.",
"picking.sequence.save": "Atomically save the sequence for the current picking list.",
"picking.sequence.reset": "Remove the customization and restore non-shelved before racks.",
"picking.sequence.close": "Close the window without further saves."
}
}

View File

@@ -6,6 +6,9 @@ import json
from pathlib import Path
import tkinter as tk
from version_info import module_version
__version__ = module_version(__name__)
_TOOLTIP_FILE = Path(__file__).with_name("tooltip.json")

230
udc_non_scaffalate.py Normal file
View File

@@ -0,0 +1,230 @@
"""Read-only list of pallets currently parked in the non-shelved virtual cell."""
from __future__ import annotations
import tkinter as tk
from tkinter import messagebox, ttk
from typing import Any
import customtkinter as ctk
from busy_overlay import InlineBusyOverlay
from gestione_aree import AsyncRunner
from locale_text import load_locale_catalog, text as loc_text
from runtime_support import log_exception
from ui_tables import style_treeview, zebra_tag
from ui_theme import theme_color, theme_font, theme_section, theme_value
from version_info import module_version, versioned_title
from window_placement import place_window_fullsize_below_parent_later
__version__ = module_version(__name__)
SQL_NON_SCAFFALATE = """
WITH trace_rows AS (
SELECT
Pallet,
MIN(Lotto) AS Lotto,
MIN(Prodotto) AS Prodotto,
MIN(Descrizione) AS Descrizione
FROM dbo.vXTracciaProdotti
GROUP BY Pallet
)
SELECT
g.BarcodePallet AS UDC,
g.IDCella,
CONCAT(RTRIM(c.Corsia), '.', RTRIM(CAST(c.Colonna AS varchar(32))), '.', RTRIM(CAST(c.Fila AS varchar(32)))) AS Ubicazione,
t.Lotto,
t.Prodotto,
t.Descrizione
FROM dbo.XMag_GiacenzaPallet AS g
LEFT JOIN dbo.Celle AS c
ON c.ID = g.IDCella
LEFT JOIN trace_rows AS t
ON t.Pallet COLLATE Latin1_General_CI_AS =
g.BarcodePallet COLLATE Latin1_General_CI_AS
WHERE g.IDCella = 1000
ORDER BY g.BarcodePallet;
"""
def _rows_to_dicts(res: dict[str, Any] | None) -> list[dict[str, Any]]:
if not isinstance(res, dict):
return []
rows = res.get("rows") or []
cols = res.get("columns") or []
if rows and isinstance(rows[0], dict):
return [row for row in rows if isinstance(row, dict)]
out: list[dict[str, Any]] = []
for row in rows:
if isinstance(row, (list, tuple)) and cols:
out.append({str(cols[i]): row[i] for i in range(min(len(cols), len(row)))})
return out
class UDCNonScaffalateWindow(ctk.CTkToplevel):
"""Window showing current UDCs in the conventional 5E1.1 non-shelved cell."""
def __init__(self, parent: tk.Widget, db_client, session=None):
super().__init__(parent)
self.db_client = db_client
self.session = session
self._theme = theme_section("non_shelved_window", theme_section("search_window", {}))
self._locale_catalog = load_locale_catalog()
self._async = AsyncRunner(self)
self._busy = InlineBusyOverlay(self, self._theme)
self._load_in_progress = False
self.title(versioned_title(loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"), __name__))
self.geometry(str(theme_value(self._theme, "window_geometry", "1000x650")))
minsize = theme_value(self._theme, "window_minsize", [820, 520])
self.minsize(int(minsize[0]), int(minsize[1]))
try:
self.configure(fg_color=theme_color(self._theme, "window_fg_color", ("#efefef", "#2f2f2f")))
except Exception:
pass
self._build_ui()
self.after(250, self._load)
def _is_alive(self) -> bool:
try:
return bool(self.winfo_exists())
except tk.TclError:
return False
def _hide_busy_safe(self) -> None:
try:
self._busy.hide()
except Exception as exc:
log_exception(__name__, exc, context="hide busy UDC non scaffalate")
def _build_ui(self) -> None:
self.grid_rowconfigure(1, weight=1)
self.grid_columnconfigure(0, weight=1)
top = ctk.CTkFrame(
self,
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(2, weight=1)
label_font = theme_font(self._theme, "toolbar_label_font", ("Segoe UI", 10, "bold"))
button_font = theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold"))
ctk.CTkLabel(
top,
text=loc_text("non_shelved.subtitle", catalog=self._locale_catalog, default="Cella convenzionale: 5E1.1 (codice 1000 / barcode 9001000)"),
font=label_font,
).grid(row=0, column=0, sticky="w", padx=(0, 12))
ctk.CTkButton(
top,
text=loc_text("non_shelved.refresh", catalog=self._locale_catalog, default="Aggiorna"),
command=self._load,
font=button_font,
).grid(row=0, column=1, sticky="w")
wrap = ctk.CTkFrame(self)
wrap.grid(row=1, column=0, sticky="nsew", padx=8, pady=(0, 8))
wrap.grid_rowconfigure(0, weight=1)
wrap.grid_columnconfigure(0, weight=1)
cols = ("UDC", "IDCella", "Ubicazione", "Lotto", "Prodotto", "Descrizione")
self.tree = ttk.Treeview(wrap, columns=cols, show="headings")
headings = {
"UDC": ("UDC", 120, "w"),
"IDCella": ("IDCella", 80, "e"),
"Ubicazione": ("Ubicazione", 130, "w"),
"Lotto": ("Lotto", 140, "w"),
"Prodotto": ("Prodotto", 150, "w"),
"Descrizione": ("Descrizione", 340, "w"),
}
for col in cols:
text, width, anchor = headings[col]
self.tree.heading(col, text=text)
self.tree.column(col, width=width, anchor=anchor, stretch=True)
style_treeview(
self.tree,
style_name="NonShelved.Treeview",
rowheight=22,
font=("", 9),
heading_font=("", 9, "bold"),
)
sy = ttk.Scrollbar(wrap, orient="vertical", command=self.tree.yview)
sx = ttk.Scrollbar(wrap, orient="horizontal", command=self.tree.xview)
self.tree.configure(yscrollcommand=sy.set, xscrollcommand=sx.set)
self.tree.grid(row=0, column=0, sticky="nsew")
sy.grid(row=0, column=1, sticky="ns")
sx.grid(row=1, column=0, sticky="ew")
def _load(self) -> None:
if self._load_in_progress or not self._is_alive():
return
async def job():
return await self.db_client.query_json(SQL_NON_SCAFFALATE, as_dict_rows=True)
self._load_in_progress = True
try:
self._busy.show(loc_text("non_shelved.busy", catalog=self._locale_catalog, default="Carico UDC non scaffalate..."))
self._async.run(job(), self._on_loaded, self._on_error)
except Exception as exc:
self._load_in_progress = False
self._hide_busy_safe()
log_exception(__name__, exc, context="avvio caricamento UDC non scaffalate")
messagebox.showerror(
loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"),
str(exc),
parent=self if self._is_alive() else None,
)
def _on_loaded(self, res: dict[str, Any] | None) -> None:
self._load_in_progress = False
self._hide_busy_safe()
if not self._is_alive():
return
try:
rows = _rows_to_dicts(res)
self.tree.delete(*self.tree.get_children(""))
for index, row in enumerate(rows):
self.tree.insert(
"",
"end",
values=(
row.get("UDC") or "",
row.get("IDCella") or "",
row.get("Ubicazione") or "",
row.get("Lotto") or "",
row.get("Prodotto") or "",
row.get("Descrizione") or "",
),
tags=(zebra_tag(index),),
)
except Exception as exc:
log_exception(__name__, exc, context="render UDC non scaffalate")
messagebox.showerror(
loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"),
str(exc),
parent=self,
)
def _on_error(self, exc: BaseException) -> None:
self._load_in_progress = False
self._hide_busy_safe()
log_exception(__name__, exc, context="query UDC non scaffalate")
if not self._is_alive():
return
messagebox.showerror(
loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"),
str(exc),
parent=self,
)
def open_udc_non_scaffalate_window(parent: tk.Misc, db_client, session=None) -> tk.Misc:
"""Open the non-shelved UDC window."""
win = UDCNonScaffalateWindow(parent, db_client, session=session)
place_window_fullsize_below_parent_later(parent, win)
return win

108
ui_tables.py Normal file
View File

@@ -0,0 +1,108 @@
"""Shared visual helpers for data grids."""
from __future__ import annotations
from tkinter import ttk
from typing import Any
TABLE_ROW_EVEN = "#FFFFFF"
TABLE_ROW_ODD = "#F4F6F8"
TABLE_HEADER_BG = "#D1D5DB"
TABLE_HEADER_FG = "#111827"
TABLE_SELECTED_BG = "#DCEBFF"
TABLE_SELECTED_FG = "#111827"
def style_treeview(
tree: ttk.Treeview,
*,
style_name: str,
rowheight: int = 24,
font: Any = ("Segoe UI", 9),
heading_font: Any = ("Segoe UI", 9, "bold"),
) -> ttk.Style:
"""Apply a consistent high-contrast header and zebra-ready style."""
style = ttk.Style(tree)
style.configure(style_name, rowheight=rowheight, font=font)
style.configure(
f"{style_name}.Heading",
font=heading_font,
background=TABLE_HEADER_BG,
foreground=TABLE_HEADER_FG,
relief="flat",
)
style.map(
f"{style_name}.Heading",
background=[("active", TABLE_HEADER_BG), ("pressed", TABLE_HEADER_BG)],
foreground=[("active", TABLE_HEADER_FG), ("pressed", TABLE_HEADER_FG)],
)
style.map(
style_name,
background=[("selected", TABLE_SELECTED_BG)],
foreground=[("selected", TABLE_SELECTED_FG)],
)
tree.configure(style=style_name)
configure_treeview_zebra_tags(tree)
return style
def configure_treeview_zebra_tags(tree: ttk.Treeview) -> None:
"""Register alternating row color tags on a Treeview."""
tree.tag_configure("even", background=TABLE_ROW_EVEN)
tree.tag_configure("odd", background=TABLE_ROW_ODD)
def zebra_tag(index: int) -> str:
"""Return the alternating row tag for the given zero-based index."""
return "even" if index % 2 == 0 else "odd"
def merge_tags(*tags: str) -> tuple[str, ...]:
"""Return non-empty tags preserving order."""
return tuple(tag for tag in tags if tag)
def apply_tksheet_visual_style(sheet: Any) -> None:
"""Apply best-effort header contrast and zebra rows to a tksheet widget."""
try:
sheet.set_options(
header_bg=TABLE_HEADER_BG,
header_fg=TABLE_HEADER_FG,
header_selected_cells_bg=TABLE_HEADER_BG,
header_selected_cells_fg=TABLE_HEADER_FG,
table_bg=TABLE_ROW_EVEN,
table_fg="#111827",
selected_rows_bg=TABLE_SELECTED_BG,
selected_rows_fg=TABLE_SELECTED_FG,
selected_cells_bg=TABLE_SELECTED_BG,
selected_cells_fg=TABLE_SELECTED_FG,
)
except Exception:
pass
def apply_tksheet_zebra(sheet: Any, row_count: int) -> None:
"""Apply alternating row colors to a tksheet widget when supported."""
try:
sheet.dehighlight_rows(redraw=False)
except Exception:
pass
for row_index in range(row_count):
try:
sheet.highlight_rows(
rows=[row_index],
bg=TABLE_ROW_EVEN if row_index % 2 == 0 else TABLE_ROW_ODD,
redraw=False,
)
except Exception:
break
try:
sheet.redraw()
except Exception:
pass

View File

@@ -164,7 +164,7 @@
}
},
"login_window": {
"window_geometry": "165x155+0+0",
"window_geometry": "165x170+0+0",
"overlay_cover_fg_color": ["#d9d9d9", "#4a4a4a"],
"overlay_panel_fg_color": ["#f2f2f2", "#353535"],
"overlay_panel_corner_radius": 10,
@@ -301,6 +301,29 @@
"overlay_label_padding": [18, 14, 18, 8],
"overlay_progress_padding": [18, 0, 18, 14]
},
"picking_sequence_window": {
"window_fg_color": ["#eef2f3", "#2f2f2f"],
"list_fg_color": ["#f8fafc", "#363636"],
"item_fg_color": "#2ebf74",
"secondary_text_color": "#4b5563",
"reset_button_fg_color": "#6b7280",
"title_font": {
"family": "Segoe UI",
"size": 16,
"weight": "bold"
},
"overlay_cover_fg_color": ["#d9d9d9", "#4a4a4a"],
"overlay_panel_fg_color": ["#f2f2f2", "#353535"],
"overlay_panel_corner_radius": 10,
"overlay_label_font": {
"family": "Segoe UI",
"size": 11,
"weight": "bold"
},
"overlay_progress_width": 220,
"overlay_label_padding": [18, 14, 18, 8],
"overlay_progress_padding": [18, 0, 18, 14]
},
"history_picking_window": {
"window_geometry": "1200x720",
"window_minsize": [980, 560],

View File

@@ -12,6 +12,10 @@ from functools import lru_cache
from pathlib import Path
from typing import Any
from version_info import module_version
__version__ = module_version(__name__)
THEME_PATH = Path(__file__).with_name("ui_theme.json")

View File

@@ -6,6 +6,9 @@ from dataclasses import dataclass, field
from datetime import datetime
from typing import FrozenSet
from version_info import module_version
__version__ = module_version(__name__)
ALL_ACTIONS: FrozenSet[str] = frozenset(
{
@@ -13,15 +16,19 @@ ALL_ACTIONS: FrozenSet[str] = frozenset(
"launcher.open_layout",
"launcher.open_multi_udc",
"launcher.open_search",
"launcher.open_non_shelved",
"launcher.open_history_udc",
"launcher.open_pickinglist",
"launcher.open_history_pickinglist",
"launcher.open_diagnostics",
"launcher.arrange_windows",
"launcher.exit",
"reset_corsie.view",
"search.view",
"non_shelved.view",
"history_udc.view",
"history_pickinglist.view",
"diagnostics.view",
"multi_udc.view",
"layout.view",
"layout.carico",
@@ -33,6 +40,7 @@ ALL_ACTIONS: FrozenSet[str] = frozenset(
"pickinglist.view",
"pickinglist.prenota",
"pickinglist.sprenota",
"pickinglist.sequence",
}
)

75
version_info.py Normal file
View File

@@ -0,0 +1,75 @@
"""Application and module version registry for Warehouse/FlyWMS bridge."""
from __future__ import annotations
from pathlib import Path
APP_VERSION = "1.0.0"
MODULE_VERSIONS: dict[str, str] = {
"app": APP_VERSION,
"async_loop_singleton": "1.0.0",
"async_msssql_query": "1.0.1",
"audit_log": "1.0.0",
"main": "1.0.2",
"barcode_client": "1.0.26",
"barcode_repository": "1.0.13",
"barcode_service": "1.0.24",
"busy_overlay": "1.0.0",
"db_config": "1.0.0",
"diagnostica": "1.0.4",
"gestione_aree": "1.0.1",
"gestione_layout": "1.0.2",
"gestione_pickinglist": "1.0.6",
"gestione_scarico": "1.0.8",
"locale_text": "1.0.0",
"login_window": "1.0.0",
"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",
"tooltips": "1.0.0",
"udc_non_scaffalate": "1.0.1",
"ui_theme": "1.0.0",
"user_session": "1.0.2",
"view_celle_multi_udc": "1.0.0",
"window_placement": "1.0.0",
}
def module_key(module_name: str) -> str:
"""Return the stable registry key for a module name or path."""
name = str(module_name or "").replace("\\", "/")
stem = Path(name).stem if "/" in name or "." not in name else name.rsplit(".", 1)[-1]
return stem or "app"
def module_version(module_name: str | None = None) -> str:
"""Return the version for a module, falling back to the app version."""
if not module_name:
return APP_VERSION
return MODULE_VERSIONS.get(module_key(module_name), APP_VERSION)
def version_label(module_name: str | None = None) -> str:
"""Return the standard visual label used in window titles."""
return f"ver. {module_version(module_name)}"
def versioned_title(title: str, module_name: str | None = None) -> str:
"""Append the standard version label to a window title."""
clean_title = str(title or "").strip()
label = version_label(module_name)
if not clean_title:
return label
if label.lower() in clean_title.lower():
return clean_title
return f"{clean_title} - {label}"

View File

@@ -22,8 +22,12 @@ from gestione_scarico import move_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
from ui_tables import merge_tags, style_treeview, zebra_tag
from version_info import module_version, versioned_title
from window_placement import place_window_fullsize_below_parent_later
__version__ = module_version(__name__)
try:
from loguru import logger
except Exception: # pragma: no cover - fallback used only when Loguru is not available
@@ -436,7 +440,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
self._theme = theme_section("multi_udc", {})
self._locale_catalog = load_locale_catalog()
self._tooltip_catalog = load_tooltip_catalog()
self.title(loc_text("multi.title", catalog=self._locale_catalog, default="Celle con piu' pallet"))
self.title(versioned_title(loc_text("multi.title", catalog=self._locale_catalog, default="Celle con piu' pallet"), __name__))
self.session = session
self.geometry(str(theme_value(self._theme, "window_geometry", "1100x700")))
minsize = theme_value(self._theme, "window_minsize", [900, 550])
@@ -507,6 +511,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
self.tree.column("col2", width=250, anchor="w")
self.tree.column("col3", width=120, anchor="w")
self.tree.column("col4", width=260, anchor="w")
style_treeview(self.tree, style_name="MultiUDC.Treeview", rowheight=24)
y = ttk.Scrollbar(frame, orient="vertical", command=self.tree.yview)
x = ttk.Scrollbar(frame, orient="horizontal", command=self.tree.xview)
self.tree.configure(yscrollcommand=y.set, xscrollcommand=x.set)
@@ -542,6 +547,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
):
self.sum_tbl.heading(key, text=title)
self.sum_tbl.column(key, width=width, anchor=anchor)
style_treeview(self.sum_tbl, style_name="MultiUDCSummary.Treeview", rowheight=24)
y2 = ttk.Scrollbar(inner, orient="vertical", command=self.sum_tbl.yview)
x2 = ttk.Scrollbar(inner, orient="horizontal", command=self.sum_tbl.xview)
self.sum_tbl.configure(yscrollcommand=y2.set, xscrollcommand=x2.set)
@@ -660,7 +666,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
"""Populate root tree nodes after the aisle query completes."""
rows = _json_obj(res).get("rows", [])
_log_dataset("multi_udc_corsie", rows)
for row in rows:
for index, row in enumerate(rows):
corsia = row.get("Corsia")
if not corsia:
continue
@@ -672,7 +678,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
text=self._format_corsia_text(corsia),
values=("", "", ""),
open=False,
tags=("corsia",),
tags=merge_tags(zebra_tag(index), "corsia"),
)
self.tree.insert(node_id, "end", iid=f"{node_id}::lazy", text="...", values=("", "", ""))
@@ -724,7 +730,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
if not rows:
self.tree.insert(parent_iid, "end", text="(nessuna cella con >1 UDC)", values=("", "", ""))
return
for row in rows:
for index, row in enumerate(rows):
idc = row["IDCella"]
ubi = row["Ubicazione"]
corsia = row.get("Corsia")
@@ -741,7 +747,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
text=label,
values=(f"IDCella {idc}", "", ""),
open=False,
tags=("cella", f"corsia:{corsia}"),
tags=merge_tags(zebra_tag(index), "cella", f"corsia:{corsia}"),
)
if not any(child.endswith("::lazy") for child in self.tree.get_children(node_id)):
self.tree.insert(node_id, "end", iid=f"{node_id}::lazy", text="...", values=("", "", ""))
@@ -781,7 +787,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
idcella_txt = self.tree.item(parent_iid, "values")[0]
idcella_num = int(idcella_txt.split()[-1]) if idcella_txt else None
for row in rows:
for index, row in enumerate(rows):
pallet = row.get("Pallet", "")
desc = row.get("Descrizione", "")
lotto = row.get("Lotto", "")
@@ -813,7 +819,13 @@ class CelleMultipleWindow(ctk.CTkToplevel):
iid=leaf_id,
text=self._format_pallet_text(str(pallet), leaf_id in self.selected_udc_keys),
values=(desc, lotto, causale),
tags=("pallet", f"corsia:{corsia_val}", f"ubicazione:{cella_ubi}", f"idcella:{idcella_num}"),
tags=merge_tags(
zebra_tag(index),
"pallet",
f"corsia:{corsia_val}",
f"ubicazione:{cella_ubi}",
f"idcella:{idcella_num}",
),
)
@_log_call()
@@ -987,11 +999,12 @@ class CelleMultipleWindow(ctk.CTkToplevel):
_log_dataset("multi_udc_riepilogo", rows)
for item in self.sum_tbl.get_children():
self.sum_tbl.delete(item)
for row in rows:
for index, row in enumerate(rows):
self.sum_tbl.insert(
"",
"end",
values=(row.get("Corsia"), row.get("TotCelle", 0), row.get("CelleMultiple", 0), f"{row.get('Percentuale', 0):.2f}"),
tags=(zebra_tag(index),),
)
def expand_all(self):

View File

@@ -1,3 +1,9 @@
from pathlib import Path
import os
os.chdir(Path(__file__).resolve().parent)
from runtime_support import ensure_stdio, run_with_fatal_log
ensure_stdio("warehouse_main")

View File

@@ -8,6 +8,9 @@ import math
import tkinter as tk
from pathlib import Path
from version_info import module_version
__version__ = module_version(__name__)
MODULE_LOG_NAME = "window_placement"
MODULE_LOG_PATH = Path(__file__).with_name("window_placement.log")