From bd73fe5edb50e51e430fc03dc521244f75a8636b Mon Sep 17 00:00:00 2001 From: allebonvi Date: Tue, 13 Oct 2026 17:11:23 +0200 Subject: [PATCH] Implementa picking bilista 2.1.0 con test, patch SQL e rollback --- INSTALLAZIONE_BILISTA_2.1.md | 97 ++++++ apply_online_python_wms_full_patch.sql | 245 +++++++++++++++ apply_pickinglist_pair_patch.sql | 240 +++++++++++++++ barcode_client.py | 68 +++- barcode_pair_service.py | 155 ++++++++++ barcode_repository.py | 30 +- barcode_service.py | 5 + gestione_pickinglist.py | 150 ++++++--- locale.json | 10 +- pickinglist_pair.py | 139 +++++++++ pickinglist_pair_repository.py | 116 +++++++ pickinglist_sequence.py | 13 +- rollback_pickinglist_pair_patch.sql | 16 + specifica_prelievo_due_pickinglist.md | 410 ++++++++++++++++++++----- tests/test_barcode_pair_service.py | 143 +++++++++ tests/test_pair_gui.py | 154 ++++++++++ tests/test_pickinglist_pair.py | 161 ++++++++++ tests/validate_picking_pair_sql.py | 133 ++++++++ version_info.py | 13 +- 19 files changed, 2168 insertions(+), 130 deletions(-) create mode 100644 INSTALLAZIONE_BILISTA_2.1.md create mode 100644 apply_pickinglist_pair_patch.sql create mode 100644 barcode_pair_service.py create mode 100644 pickinglist_pair.py create mode 100644 pickinglist_pair_repository.py create mode 100644 rollback_pickinglist_pair_patch.sql create mode 100644 tests/test_barcode_pair_service.py create mode 100644 tests/test_pair_gui.py create mode 100644 tests/test_pickinglist_pair.py create mode 100644 tests/validate_picking_pair_sql.py diff --git a/INSTALLAZIONE_BILISTA_2.1.md b/INSTALLAZIONE_BILISTA_2.1.md new file mode 100644 index 0000000..66de6f4 --- /dev/null +++ b/INSTALLAZIONE_BILISTA_2.1.md @@ -0,0 +1,97 @@ +# Bilista 2.1.0: installazione e collaudo + +Stato: versione di collaudo sul branch Gitea `codex/doppia-pickinglist`. +Pubblicazione del 13/10/2026; non promossa a `main` o in produzione. +Base di ritorno: tag `warehouse-monolista-2.0` su Gitea. + +## Scaricare i sorgenti in WSL + +Dal terminale Ubuntu, se la cartella `flywms` non esiste o e' vuota: + +```bash +cd /home/administrator +git clone --branch codex/doppia-pickinglist https://gitea.alessandrobonvicini.it/administrator/ware_house.git flywms +cd flywms +git status -sb +git log -1 --oneline +``` + +Per aggiornare successivamente lo stesso branch: + +```bash +cd /home/administrator/flywms +git pull --ff-only +``` + +Il clone non installa dipendenze, non copia `db_connection.json` locale e non +esegue patch SQL. L'ambiente Python, il driver Linux e la connessione ai soli +database di test vanno predisposti separatamente. Il funzionamento completo +del client in WSL resta da verificare: i 52 test rieseguiti il 13/10/2026 +sono stati eseguiti su Windows, senza movimenti DB. + +## SQL + +1. Chiudere tutti i client Python. Eseguire un backup verificato del DB WMS + prima dell'aggiornamento, mantenendo una copia coerente di SAM per i test. +2. Su un DB gia' aggiornato al freeze monolista, eseguire in SSMS, database + Mediseawall, `apply_pickinglist_pair_patch.sql`. +3. In alternativa, per aggiornare anche gli oggetti Python precedenti, + eseguire `apply_online_python_wms_full_patch.sql`: include la stessa patch. + Non serve eseguire anche il file del punto 2. +4. Controllare l'assenza di errori SQL prima di avviare i nuovi client. + +Il nuovo script crea tre tabelle, una vista e una stored `py_*`. Non cambia +definizioni legacy C#, non modifica SAM e non effettua scarichi in installazione. +Rieseguirlo conserva giri, sequenze e skip. Non usare i file `sql_tests` online: +sono dedicati ai dati di collaudo locali e modificano testate SAM. + +## Prima prova locale + +1. Riavviare desktop e barcode per caricare i moduli 2.1.0. La versione e' + visibile nei titoli di Gestione Picking List e del barcode. +2. In Gestione Picking List scegliere 30 giorni. Nel dataset ripristinato + usare, ad esempio, 233 e 244: selezionare 233, poi 244, quindi Prenota. +3. Verificare IDStato 1 rosa e 2 giallo. Il dettaglio e' quello dell'ultima + lista cliccata; entrambi i checkbox devono restare selezionati al Ricarica. +4. Sul barcode premere F1: prima tutte le Non scaff. lavorabili di Lista 1, + poi di Lista 2, poi celle fisiche lungo il percorso comune. F2 disabilitato. +5. Leggere la UDC proposta: conferma 7G.1.1 / Spedita per 3 secondi, poi nuova + proposta. Il colore segue la lista, non il numero di scansioni. +6. F3 Pausa PL: fare piu' operazioni libere; ESC riprende la stessa proposta + con posizione aggiornata. Non deve comparire uno scarico spontaneo. +7. Saltare qualche UDC di entrambe con F4. Terminato il giro, Ricarica sul + desktop: liste con residui presenti ma non prenotate. Riprenotarle deve + riproporre gli skip ancora residui; nessuna terza lista si aggiunge da sola. +8. Verificare anche una sola lista e i movimenti liberi senza prenotazioni. + +Il test operatore modifica realmente le giacenze. Per ripeterlo da zero serve +un ripristino coerente dei dati, non basta cambiare tag Git. + +## Test ripetibili per sviluppo + +```powershell +python -m unittest discover -s tests -v +python tests/validate_picking_pair_sql.py +``` + +Il primo comando non apre connessioni DB: usa simulazioni e widget reali. +Il secondo e' vincolato a HOMESERVER/Mediseawall, richiede le liste 233/244 +di test e nessun giro aperto. Fa un movimento effettivo entro una transazione +poi annullata; non deve girare mentre un operatore usa la copia di sviluppo. +I log Python possono riportare quel movimento di collaudo anche se il DB e' +stato successivamente ripristinato dal rollback. + +## Tornare al monolista + +1. Con il nuovo desktop sprenotare le eventuali liste ancora attive. +2. Chiudere tutti i client. +3. Eseguire `rollback_pickinglist_pair_patch.sql` su Mediseawall: rifiuta il + rollback se trova ancora un giro aperto. Rimuove solo vista e stored nuove; + conserva le tre tabelle come audit. Non annulla movimenti effettuati. +4. Ripristinare i sorgenti del tag `warehouse-monolista-2.0` in una cartella + separata oppure con il consueto checkout, dopo avere salvato modifiche locali + e configurazione. Non usare reset distruttivi senza un backup. +5. Riavviare e prenotare la lista desiderata con il programma monolista. + +Il rollback specifico non disinstalla eventuali altre patch Python eseguite +tramite lo script cumulativo. Il freeze Git non e' un backup del database. diff --git a/apply_online_python_wms_full_patch.sql b/apply_online_python_wms_full_patch.sql index 590e6c1..468ee42 100644 --- a/apply_online_python_wms_full_patch.sql +++ b/apply_online_python_wms_full_patch.sql @@ -18,12 +18,15 @@ Include: - dbo.py_BarcodePickingListSkip - dbo.py_PickingListPrelievoSequenza - dbo.py_ViewPackingListPrelievo +- dbo.py_PickingPair, dbo.py_PickingPairSequence, dbo.py_PickingPairSkip +- dbo.py_ViewPickingPairRows, dbo.py_sp_PickingPair 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. +- prenotazione bilista e snapshot della sequenza della prima selezionata. Nota storico: dbo.py_vPreparaPackingListSAMA1 usa ANNDOC >= YEAR(GETDATE()) @@ -721,5 +724,247 @@ SELECT FROM Sequenza; GO +/* Bilista 2.1.0: generated from apply_pickinglist_pair_patch.sql. */ +/* Warehouse bilista. Eseguire su Mediseawall, dopo la patch cumulativa. + Solo nuovi oggetti py_*; nessuna modifica a oggetti C# o a dati SAM. + Idempotente: non azzera giri, skip o sequenze esistenti. + Fermare tutti i client Python prima di installare o ripristinare. +*/ +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +GO +IF OBJECT_ID('dbo.py_ViewPackingListPrelievo','V') IS NULL + OR OBJECT_ID('dbo.py_XMag_ViewPackingListStorico','V') IS NULL + THROW 51100, 'Applicare prima le patch Python esistenti.', 1; +GO +IF OBJECT_ID('dbo.py_PickingPair','U') IS NULL +BEGIN + CREATE TABLE dbo.py_PickingPair ( + RunId uniqueidentifier NOT NULL PRIMARY KEY, + Documento1 varchar(8) NOT NULL, + Documento2 varchar(8) NOT NULL, + Active1 bit NOT NULL, + Active2 bit NOT NULL, + IsOpen bit NOT NULL, + InsUtente int NOT NULL, + InsDataOra datetime2 NOT NULL DEFAULT SYSDATETIME(), + ModUtente int NOT NULL, + ModDataOra datetime2 NOT NULL DEFAULT SYSDATETIME(), + ClosedAt1 datetime2 NULL, + ClosedAt2 datetime2 NULL, + CONSTRAINT CK_py_PickingPair_Doc CHECK (Documento1 <> Documento2), + CONSTRAINT CK_py_PickingPair_Open CHECK + ((IsOpen=1 AND (Active1=1 OR Active2=1)) OR (IsOpen=0 AND Active1=0 AND Active2=0)) + ); + CREATE UNIQUE INDEX UX_py_PickingPair_Open ON dbo.py_PickingPair(IsOpen) WHERE IsOpen=1; +END; +IF OBJECT_ID('dbo.py_PickingPairSequence','U') IS NULL +BEGIN + CREATE TABLE dbo.py_PickingPairSequence ( + RunId uniqueidentifier NOT NULL REFERENCES dbo.py_PickingPair(RunId), + GruppoChiave varchar(160) NOT NULL, + Ordine int NOT NULL, + PRIMARY KEY(RunId,GruppoChiave), + UNIQUE(RunId,Ordine) + ); +END; +IF OBJECT_ID('dbo.py_PickingPairSkip','U') IS NULL +BEGIN + CREATE TABLE dbo.py_PickingPairSkip ( + RunId uniqueidentifier NOT NULL REFERENCES dbo.py_PickingPair(RunId), + Documento varchar(8) NOT NULL, + Pallet varchar(50) NOT NULL, + InsUtente int NOT NULL, + InsDataOra datetime2 NOT NULL DEFAULT SYSDATETIME(), + PRIMARY KEY(RunId,Documento,Pallet) + ); +END; +GO +CREATE OR ALTER VIEW dbo.py_ViewPickingPairRows +AS +WITH Residue AS ( + SELECT h.*, + CASE WHEN h.Cella=1000 THEN NULL + WHEN RTRIM(m.Descrizione)='MDE5' THEN 5 + WHEN RTRIM(m.Descrizione)='MDE6' THEN 6 END AS OperationalArea, + CASE WHEN h.Cella=1000 THEN 'NON_SCAFF' + ELSE CONCAT('M:',h.Magazzino,'|A:',h.Area,'|C:',LTRIM(RTRIM( + CASE WHEN CHARINDEX(' - ',h.Ubicazione)>0 + THEN LEFT(h.Ubicazione,CHARINDEX(' - ',h.Ubicazione)-1) + ELSE h.Ubicazione END))) END AS GroupKey + FROM dbo.py_XMag_ViewPackingListStorico h + LEFT JOIN dbo.Celle c ON c.ID=h.Cella + LEFT JOIN dbo.Aree a ON a.ID=c.IDArea + LEFT JOIN dbo.Magazzini m ON m.ID=a.IDMagazzino + WHERE h.Cella<>9999 +) +SELECT r.RunId, r.Documento1, r.Documento2, r.Active1, r.Active2, + d.Slot, d.Documento AS SlotDocument, d.IsActive, + h.Pallet, h.Cella, h.Ubicazione, h.Ordinamento, h.OperationalArea, + h.GroupKey, h.StatoDocumento, h.CodNazione, h.NAZIONE, + s.Ordine AS SequenceOrder, + CONVERT(bit,CASE WHEN k.Pallet IS NULL THEN 0 ELSE 1 END) AS IsSkipped +FROM dbo.py_PickingPair r +CROSS APPLY (VALUES (1,r.Documento1,r.Active1),(2,r.Documento2,r.Active2)) d(Slot,Documento,IsActive) +LEFT JOIN Residue h ON h.Documento=TRY_CONVERT(int,d.Documento) +LEFT JOIN dbo.py_PickingPairSequence s ON s.RunId=r.RunId + AND s.GruppoChiave COLLATE Latin1_General_CI_AS=h.GroupKey COLLATE Latin1_General_CI_AS +LEFT JOIN dbo.py_PickingPairSkip k ON k.RunId=r.RunId AND k.Documento=d.Documento + AND k.Pallet COLLATE Latin1_General_CI_AS=CAST(h.Pallet AS varchar(50)) COLLATE Latin1_General_CI_AS +WHERE r.IsOpen=1; +GO +CREATE OR ALTER PROCEDURE dbo.py_sp_PickingPair + @Action char(1), + @IDOperatore int, + @Documento1 varchar(8)=NULL, + @Documento2 varchar(8)=NULL, + @RunId uniqueidentifier=NULL, + @Documento varchar(8)=NULL, + @Pallet varchar(50)=NULL, + @Silent bit=0 +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + BEGIN TRY + BEGIN TRANSACTION; + DECLARE @LockResult int; + EXEC @LockResult=sys.sp_getapplock @Resource='py_PickingPair', + @LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000; + IF @LockResult<0 THROW 51101, 'Prenotazione occupata. Riprovare.', 1; + IF @IDOperatore<=0 THROW 51102, 'Operatore non valido.', 1; + + IF @Action='R' + BEGIN + IF @Documento1 IS NULL OR @Documento2 IS NULL OR @Documento1=@Documento2 + THROW 51103, 'Selezionare due liste diverse.', 1; + DECLARE @Existing uniqueidentifier; + SELECT @Existing=RunId FROM dbo.py_PickingPair WITH (UPDLOCK,HOLDLOCK) WHERE IsOpen=1; + IF @Existing IS NOT NULL + BEGIN + IF NOT EXISTS(SELECT 1 FROM dbo.py_PickingPair WHERE RunId=@Existing + AND Documento1=@Documento1 AND Documento2=@Documento2 AND Active1=1 AND Active2=1) + THROW 51104, 'Un giro bilista e gia prenotato. Sprenotarlo prima di cambiarlo.', 1; + SET @RunId=@Existing; + END + ELSE + BEGIN + IF (SELECT COUNT(DISTINCT Documento) FROM dbo.py_ViewPackingListRestante + WHERE Documento IN (TRY_CONVERT(int,@Documento1),TRY_CONVERT(int,@Documento2)))<>2 + THROW 51105, 'Una lista non e piu prenotabile o non ha residue.', 1; + IF EXISTS(SELECT Pallet FROM dbo.py_ViewPackingListRestante + WHERE Documento IN (TRY_CONVERT(int,@Documento1),TRY_CONVERT(int,@Documento2)) + GROUP BY Pallet HAVING COUNT(DISTINCT Documento)>1 OR COUNT(DISTINCT Cella)>1) + THROW 51106, 'UDC condivisa tra liste o presente in piu celle.', 1; + IF EXISTS(SELECT 1 FROM dbo.py_ViewPackingListRestante h + LEFT JOIN dbo.Celle c ON c.ID=h.Cella + LEFT JOIN dbo.Aree a ON a.ID=c.IDArea + LEFT JOIN dbo.Magazzini m ON m.ID=a.IDMagazzino + WHERE h.Documento IN (TRY_CONVERT(int,@Documento1),TRY_CONVERT(int,@Documento2)) + AND h.Cella<>1000 AND (m.ID IS NULL OR RTRIM(m.Descrizione) NOT IN ('MDE5','MDE6'))) + THROW 51107, 'Area fisica non riconosciuta.', 1; + IF (SELECT COUNT(DISTINCT m.ID) FROM dbo.py_ViewPackingListRestante h + JOIN dbo.Celle c ON c.ID=h.Cella JOIN dbo.Aree a ON a.ID=c.IDArea + JOIN dbo.Magazzini m ON m.ID=a.IDMagazzino + WHERE h.Documento IN (TRY_CONVERT(int,@Documento1),TRY_CONVERT(int,@Documento2)) + AND h.Cella<>1000)>1 + THROW 51108, 'Le liste contengono UDC in aree diverse.', 1; + + DECLARE @Single varchar(8), @RC int=0; + SELECT @Single=Documento FROM dbo.PyPickingListReservation WITH (UPDLOCK,HOLDLOCK) WHERE ID=1; + IF NULLIF(@Single,'') IS NOT NULL + BEGIN + EXEC dbo.py_sp_xExePackingListPallet @IDOperatore=@IDOperatore, + @Documento=@Single,@Azione='S',@RC=@RC OUTPUT; + IF @RC<>0 THROW 51109, 'Impossibile rilasciare la prenotazione monolista.', 1; + END; + SET @RunId=NEWID(); + INSERT dbo.py_PickingPair(RunId,Documento1,Documento2,Active1,Active2,IsOpen,InsUtente,ModUtente) + VALUES(@RunId,@Documento1,@Documento2,1,1,1,@IDOperatore,@IDOperatore); + INSERT dbo.py_PickingPairSequence(RunId,GruppoChiave,Ordine) + SELECT @RunId,GruppoChiave,Ordine FROM dbo.py_PickingListPrelievoSequenza + WHERE Documento=@Documento1 AND DelDataOra IS NULL AND GruppoChiave<>'NON_SCAFF'; + END; + END + ELSE IF @Action IN ('K','G','F','U') + BEGIN + IF NOT EXISTS(SELECT 1 FROM dbo.py_PickingPair WITH (UPDLOCK,HOLDLOCK) + WHERE RunId=@RunId AND IsOpen=1) + THROW 51110, 'Il giro bilista e terminato o e cambiato. Ricaricare.', 1; + -- The inherited historical view is scoped to the current year. + -- Never mistake the annual cutoff for a fully shipped pair. + IF @Action<>'U' AND EXISTS(SELECT 1 FROM dbo.py_PickingPair + WHERE RunId=@RunId AND YEAR(InsDataOra)<>YEAR(GETDATE())) + THROW 51116, 'Giro di un anno precedente: verificare e sprenotare dal desktop.', 1; + IF @Action IN ('K','G') + BEGIN + IF NOT EXISTS(SELECT 1 FROM dbo.py_ViewPickingPairRows + WHERE RunId=@RunId AND SlotDocument=@Documento AND IsActive=1 + AND CAST(Pallet AS varchar(50)) COLLATE Latin1_General_CI_AS=@Pallet COLLATE Latin1_General_CI_AS + AND StatoDocumento='P' AND IsSkipped=0) + THROW 51111, 'UDC non piu disponibile nella lista corrente.', 1; + IF EXISTS(SELECT 1 FROM dbo.py_ViewPickingPairRows WHERE RunId=@RunId + AND IsActive=1 AND Cella<>1000 AND Pallet IS NOT NULL AND OperationalArea IS NULL) + OR (SELECT COUNT(DISTINCT OperationalArea) FROM dbo.py_ViewPickingPairRows + WHERE RunId=@RunId AND IsActive=1 AND Cella<>1000)>1 + THROW 51108, 'Le liste contengono UDC in aree diverse o non riconosciute.', 1; + IF @Action='K' + BEGIN + INSERT dbo.py_PickingPairSkip(RunId,Documento,Pallet,InsUtente) + VALUES(@RunId,@Documento,@Pallet,@IDOperatore); + -- Preserve the monolist F2 rule after this pair is released: + -- skipped UDCs require an explicit new reservation. + IF NOT EXISTS(SELECT 1 FROM dbo.py_BarcodePickingListSkip + WHERE Documento=@Documento AND Pallet=@Pallet AND IDStato=0 AND Risolto=0) + INSERT dbo.py_BarcodePickingListSkip + (Documento,Pallet,IDStato,IDOperatore,DataOra,Motivo,Risolto) + VALUES(@Documento,@Pallet,0,@IDOperatore,SYSDATETIME(),'Salto bilista',0); + END; + END; + IF @Action='U' + BEGIN + IF @Documento IS NULL OR @Documento NOT IN (SELECT Documento1 FROM dbo.py_PickingPair WHERE RunId=@RunId + UNION ALL SELECT Documento2 FROM dbo.py_PickingPair WHERE RunId=@RunId) + THROW 51112, 'Documento estraneo al giro.', 1; + UPDATE dbo.py_PickingPair SET + Active1=CASE WHEN Documento1=@Documento THEN 0 ELSE Active1 END, + Active2=CASE WHEN Documento2=@Documento THEN 0 ELSE Active2 END, + ClosedAt1=CASE WHEN Documento1=@Documento THEN SYSDATETIME() ELSE ClosedAt1 END, + ClosedAt2=CASE WHEN Documento2=@Documento THEN SYSDATETIME() ELSE ClosedAt2 END, + IsOpen=CASE WHEN (Documento1=@Documento OR Active1=0) + AND (Documento2=@Documento OR Active2=0) THEN 0 ELSE 1 END, + ModUtente=@IDOperatore,ModDataOra=SYSDATETIME() + WHERE RunId=@RunId; + END; + IF @Action='F' + BEGIN + DECLARE @Work1 bit=0,@Work2 bit=0; + SELECT @Work1=MAX(CASE WHEN Slot=1 THEN 1 ELSE 0 END), + @Work2=MAX(CASE WHEN Slot=2 THEN 1 ELSE 0 END) + FROM dbo.py_ViewPickingPairRows WHERE RunId=@RunId AND IsActive=1 + AND Pallet IS NOT NULL AND IsSkipped=0; + UPDATE dbo.py_PickingPair SET + Active1=ISNULL(@Work1,0),Active2=ISNULL(@Work2,0), + IsOpen=CASE WHEN ISNULL(@Work1,0)=1 OR ISNULL(@Work2,0)=1 THEN 1 ELSE 0 END, + ClosedAt1=CASE WHEN ISNULL(@Work1,0)=0 THEN COALESCE(ClosedAt1,SYSDATETIME()) ELSE ClosedAt1 END, + ClosedAt2=CASE WHEN ISNULL(@Work2,0)=0 THEN COALESCE(ClosedAt2,SYSDATETIME()) ELSE ClosedAt2 END, + ModUtente=@IDOperatore,ModDataOra=SYSDATETIME() + WHERE RunId=@RunId; + END; + END + ELSE THROW 51113, 'Azione bilista non valida.', 1; + COMMIT TRANSACTION; + IF @Silent=0 SELECT CAST(@RunId AS varchar(36)) AS RunId,0 AS RC; + END TRY + BEGIN CATCH + IF XACT_STATE()<>0 ROLLBACK TRANSACTION; + THROW; + END CATCH; +END; +GO +PRINT 'Patch bilista installata. Nessun giro creato e nessuna UDC movimentata.'; +GO + PRINT 'Patch cumulativa Python WMS completata.'; GO diff --git a/apply_pickinglist_pair_patch.sql b/apply_pickinglist_pair_patch.sql new file mode 100644 index 0000000..4321de4 --- /dev/null +++ b/apply_pickinglist_pair_patch.sql @@ -0,0 +1,240 @@ +/* Warehouse bilista. Eseguire su Mediseawall, dopo la patch cumulativa. + Solo nuovi oggetti py_*; nessuna modifica a oggetti C# o a dati SAM. + Idempotente: non azzera giri, skip o sequenze esistenti. + Fermare tutti i client Python prima di installare o ripristinare. +*/ +SET ANSI_NULLS ON; +GO +SET QUOTED_IDENTIFIER ON; +GO +IF OBJECT_ID('dbo.py_ViewPackingListPrelievo','V') IS NULL + OR OBJECT_ID('dbo.py_XMag_ViewPackingListStorico','V') IS NULL + THROW 51100, 'Applicare prima le patch Python esistenti.', 1; +GO +IF OBJECT_ID('dbo.py_PickingPair','U') IS NULL +BEGIN + CREATE TABLE dbo.py_PickingPair ( + RunId uniqueidentifier NOT NULL PRIMARY KEY, + Documento1 varchar(8) NOT NULL, + Documento2 varchar(8) NOT NULL, + Active1 bit NOT NULL, + Active2 bit NOT NULL, + IsOpen bit NOT NULL, + InsUtente int NOT NULL, + InsDataOra datetime2 NOT NULL DEFAULT SYSDATETIME(), + ModUtente int NOT NULL, + ModDataOra datetime2 NOT NULL DEFAULT SYSDATETIME(), + ClosedAt1 datetime2 NULL, + ClosedAt2 datetime2 NULL, + CONSTRAINT CK_py_PickingPair_Doc CHECK (Documento1 <> Documento2), + CONSTRAINT CK_py_PickingPair_Open CHECK + ((IsOpen=1 AND (Active1=1 OR Active2=1)) OR (IsOpen=0 AND Active1=0 AND Active2=0)) + ); + CREATE UNIQUE INDEX UX_py_PickingPair_Open ON dbo.py_PickingPair(IsOpen) WHERE IsOpen=1; +END; +IF OBJECT_ID('dbo.py_PickingPairSequence','U') IS NULL +BEGIN + CREATE TABLE dbo.py_PickingPairSequence ( + RunId uniqueidentifier NOT NULL REFERENCES dbo.py_PickingPair(RunId), + GruppoChiave varchar(160) NOT NULL, + Ordine int NOT NULL, + PRIMARY KEY(RunId,GruppoChiave), + UNIQUE(RunId,Ordine) + ); +END; +IF OBJECT_ID('dbo.py_PickingPairSkip','U') IS NULL +BEGIN + CREATE TABLE dbo.py_PickingPairSkip ( + RunId uniqueidentifier NOT NULL REFERENCES dbo.py_PickingPair(RunId), + Documento varchar(8) NOT NULL, + Pallet varchar(50) NOT NULL, + InsUtente int NOT NULL, + InsDataOra datetime2 NOT NULL DEFAULT SYSDATETIME(), + PRIMARY KEY(RunId,Documento,Pallet) + ); +END; +GO +CREATE OR ALTER VIEW dbo.py_ViewPickingPairRows +AS +WITH Residue AS ( + SELECT h.*, + CASE WHEN h.Cella=1000 THEN NULL + WHEN RTRIM(m.Descrizione)='MDE5' THEN 5 + WHEN RTRIM(m.Descrizione)='MDE6' THEN 6 END AS OperationalArea, + CASE WHEN h.Cella=1000 THEN 'NON_SCAFF' + ELSE CONCAT('M:',h.Magazzino,'|A:',h.Area,'|C:',LTRIM(RTRIM( + CASE WHEN CHARINDEX(' - ',h.Ubicazione)>0 + THEN LEFT(h.Ubicazione,CHARINDEX(' - ',h.Ubicazione)-1) + ELSE h.Ubicazione END))) END AS GroupKey + FROM dbo.py_XMag_ViewPackingListStorico h + LEFT JOIN dbo.Celle c ON c.ID=h.Cella + LEFT JOIN dbo.Aree a ON a.ID=c.IDArea + LEFT JOIN dbo.Magazzini m ON m.ID=a.IDMagazzino + WHERE h.Cella<>9999 +) +SELECT r.RunId, r.Documento1, r.Documento2, r.Active1, r.Active2, + d.Slot, d.Documento AS SlotDocument, d.IsActive, + h.Pallet, h.Cella, h.Ubicazione, h.Ordinamento, h.OperationalArea, + h.GroupKey, h.StatoDocumento, h.CodNazione, h.NAZIONE, + s.Ordine AS SequenceOrder, + CONVERT(bit,CASE WHEN k.Pallet IS NULL THEN 0 ELSE 1 END) AS IsSkipped +FROM dbo.py_PickingPair r +CROSS APPLY (VALUES (1,r.Documento1,r.Active1),(2,r.Documento2,r.Active2)) d(Slot,Documento,IsActive) +LEFT JOIN Residue h ON h.Documento=TRY_CONVERT(int,d.Documento) +LEFT JOIN dbo.py_PickingPairSequence s ON s.RunId=r.RunId + AND s.GruppoChiave COLLATE Latin1_General_CI_AS=h.GroupKey COLLATE Latin1_General_CI_AS +LEFT JOIN dbo.py_PickingPairSkip k ON k.RunId=r.RunId AND k.Documento=d.Documento + AND k.Pallet COLLATE Latin1_General_CI_AS=CAST(h.Pallet AS varchar(50)) COLLATE Latin1_General_CI_AS +WHERE r.IsOpen=1; +GO +CREATE OR ALTER PROCEDURE dbo.py_sp_PickingPair + @Action char(1), + @IDOperatore int, + @Documento1 varchar(8)=NULL, + @Documento2 varchar(8)=NULL, + @RunId uniqueidentifier=NULL, + @Documento varchar(8)=NULL, + @Pallet varchar(50)=NULL, + @Silent bit=0 +AS +BEGIN + SET NOCOUNT ON; + SET XACT_ABORT ON; + BEGIN TRY + BEGIN TRANSACTION; + DECLARE @LockResult int; + EXEC @LockResult=sys.sp_getapplock @Resource='py_PickingPair', + @LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000; + IF @LockResult<0 THROW 51101, 'Prenotazione occupata. Riprovare.', 1; + IF @IDOperatore<=0 THROW 51102, 'Operatore non valido.', 1; + + IF @Action='R' + BEGIN + IF @Documento1 IS NULL OR @Documento2 IS NULL OR @Documento1=@Documento2 + THROW 51103, 'Selezionare due liste diverse.', 1; + DECLARE @Existing uniqueidentifier; + SELECT @Existing=RunId FROM dbo.py_PickingPair WITH (UPDLOCK,HOLDLOCK) WHERE IsOpen=1; + IF @Existing IS NOT NULL + BEGIN + IF NOT EXISTS(SELECT 1 FROM dbo.py_PickingPair WHERE RunId=@Existing + AND Documento1=@Documento1 AND Documento2=@Documento2 AND Active1=1 AND Active2=1) + THROW 51104, 'Un giro bilista e gia prenotato. Sprenotarlo prima di cambiarlo.', 1; + SET @RunId=@Existing; + END + ELSE + BEGIN + IF (SELECT COUNT(DISTINCT Documento) FROM dbo.py_ViewPackingListRestante + WHERE Documento IN (TRY_CONVERT(int,@Documento1),TRY_CONVERT(int,@Documento2)))<>2 + THROW 51105, 'Una lista non e piu prenotabile o non ha residue.', 1; + IF EXISTS(SELECT Pallet FROM dbo.py_ViewPackingListRestante + WHERE Documento IN (TRY_CONVERT(int,@Documento1),TRY_CONVERT(int,@Documento2)) + GROUP BY Pallet HAVING COUNT(DISTINCT Documento)>1 OR COUNT(DISTINCT Cella)>1) + THROW 51106, 'UDC condivisa tra liste o presente in piu celle.', 1; + IF EXISTS(SELECT 1 FROM dbo.py_ViewPackingListRestante h + LEFT JOIN dbo.Celle c ON c.ID=h.Cella + LEFT JOIN dbo.Aree a ON a.ID=c.IDArea + LEFT JOIN dbo.Magazzini m ON m.ID=a.IDMagazzino + WHERE h.Documento IN (TRY_CONVERT(int,@Documento1),TRY_CONVERT(int,@Documento2)) + AND h.Cella<>1000 AND (m.ID IS NULL OR RTRIM(m.Descrizione) NOT IN ('MDE5','MDE6'))) + THROW 51107, 'Area fisica non riconosciuta.', 1; + IF (SELECT COUNT(DISTINCT m.ID) FROM dbo.py_ViewPackingListRestante h + JOIN dbo.Celle c ON c.ID=h.Cella JOIN dbo.Aree a ON a.ID=c.IDArea + JOIN dbo.Magazzini m ON m.ID=a.IDMagazzino + WHERE h.Documento IN (TRY_CONVERT(int,@Documento1),TRY_CONVERT(int,@Documento2)) + AND h.Cella<>1000)>1 + THROW 51108, 'Le liste contengono UDC in aree diverse.', 1; + + DECLARE @Single varchar(8), @RC int=0; + SELECT @Single=Documento FROM dbo.PyPickingListReservation WITH (UPDLOCK,HOLDLOCK) WHERE ID=1; + IF NULLIF(@Single,'') IS NOT NULL + BEGIN + EXEC dbo.py_sp_xExePackingListPallet @IDOperatore=@IDOperatore, + @Documento=@Single,@Azione='S',@RC=@RC OUTPUT; + IF @RC<>0 THROW 51109, 'Impossibile rilasciare la prenotazione monolista.', 1; + END; + SET @RunId=NEWID(); + INSERT dbo.py_PickingPair(RunId,Documento1,Documento2,Active1,Active2,IsOpen,InsUtente,ModUtente) + VALUES(@RunId,@Documento1,@Documento2,1,1,1,@IDOperatore,@IDOperatore); + INSERT dbo.py_PickingPairSequence(RunId,GruppoChiave,Ordine) + SELECT @RunId,GruppoChiave,Ordine FROM dbo.py_PickingListPrelievoSequenza + WHERE Documento=@Documento1 AND DelDataOra IS NULL AND GruppoChiave<>'NON_SCAFF'; + END; + END + ELSE IF @Action IN ('K','G','F','U') + BEGIN + IF NOT EXISTS(SELECT 1 FROM dbo.py_PickingPair WITH (UPDLOCK,HOLDLOCK) + WHERE RunId=@RunId AND IsOpen=1) + THROW 51110, 'Il giro bilista e terminato o e cambiato. Ricaricare.', 1; + -- The inherited historical view is scoped to the current year. + -- Never mistake the annual cutoff for a fully shipped pair. + IF @Action<>'U' AND EXISTS(SELECT 1 FROM dbo.py_PickingPair + WHERE RunId=@RunId AND YEAR(InsDataOra)<>YEAR(GETDATE())) + THROW 51116, 'Giro di un anno precedente: verificare e sprenotare dal desktop.', 1; + IF @Action IN ('K','G') + BEGIN + IF NOT EXISTS(SELECT 1 FROM dbo.py_ViewPickingPairRows + WHERE RunId=@RunId AND SlotDocument=@Documento AND IsActive=1 + AND CAST(Pallet AS varchar(50)) COLLATE Latin1_General_CI_AS=@Pallet COLLATE Latin1_General_CI_AS + AND StatoDocumento='P' AND IsSkipped=0) + THROW 51111, 'UDC non piu disponibile nella lista corrente.', 1; + IF EXISTS(SELECT 1 FROM dbo.py_ViewPickingPairRows WHERE RunId=@RunId + AND IsActive=1 AND Cella<>1000 AND Pallet IS NOT NULL AND OperationalArea IS NULL) + OR (SELECT COUNT(DISTINCT OperationalArea) FROM dbo.py_ViewPickingPairRows + WHERE RunId=@RunId AND IsActive=1 AND Cella<>1000)>1 + THROW 51108, 'Le liste contengono UDC in aree diverse o non riconosciute.', 1; + IF @Action='K' + BEGIN + INSERT dbo.py_PickingPairSkip(RunId,Documento,Pallet,InsUtente) + VALUES(@RunId,@Documento,@Pallet,@IDOperatore); + -- Preserve the monolist F2 rule after this pair is released: + -- skipped UDCs require an explicit new reservation. + IF NOT EXISTS(SELECT 1 FROM dbo.py_BarcodePickingListSkip + WHERE Documento=@Documento AND Pallet=@Pallet AND IDStato=0 AND Risolto=0) + INSERT dbo.py_BarcodePickingListSkip + (Documento,Pallet,IDStato,IDOperatore,DataOra,Motivo,Risolto) + VALUES(@Documento,@Pallet,0,@IDOperatore,SYSDATETIME(),'Salto bilista',0); + END; + END; + IF @Action='U' + BEGIN + IF @Documento IS NULL OR @Documento NOT IN (SELECT Documento1 FROM dbo.py_PickingPair WHERE RunId=@RunId + UNION ALL SELECT Documento2 FROM dbo.py_PickingPair WHERE RunId=@RunId) + THROW 51112, 'Documento estraneo al giro.', 1; + UPDATE dbo.py_PickingPair SET + Active1=CASE WHEN Documento1=@Documento THEN 0 ELSE Active1 END, + Active2=CASE WHEN Documento2=@Documento THEN 0 ELSE Active2 END, + ClosedAt1=CASE WHEN Documento1=@Documento THEN SYSDATETIME() ELSE ClosedAt1 END, + ClosedAt2=CASE WHEN Documento2=@Documento THEN SYSDATETIME() ELSE ClosedAt2 END, + IsOpen=CASE WHEN (Documento1=@Documento OR Active1=0) + AND (Documento2=@Documento OR Active2=0) THEN 0 ELSE 1 END, + ModUtente=@IDOperatore,ModDataOra=SYSDATETIME() + WHERE RunId=@RunId; + END; + IF @Action='F' + BEGIN + DECLARE @Work1 bit=0,@Work2 bit=0; + SELECT @Work1=MAX(CASE WHEN Slot=1 THEN 1 ELSE 0 END), + @Work2=MAX(CASE WHEN Slot=2 THEN 1 ELSE 0 END) + FROM dbo.py_ViewPickingPairRows WHERE RunId=@RunId AND IsActive=1 + AND Pallet IS NOT NULL AND IsSkipped=0; + UPDATE dbo.py_PickingPair SET + Active1=ISNULL(@Work1,0),Active2=ISNULL(@Work2,0), + IsOpen=CASE WHEN ISNULL(@Work1,0)=1 OR ISNULL(@Work2,0)=1 THEN 1 ELSE 0 END, + ClosedAt1=CASE WHEN ISNULL(@Work1,0)=0 THEN COALESCE(ClosedAt1,SYSDATETIME()) ELSE ClosedAt1 END, + ClosedAt2=CASE WHEN ISNULL(@Work2,0)=0 THEN COALESCE(ClosedAt2,SYSDATETIME()) ELSE ClosedAt2 END, + ModUtente=@IDOperatore,ModDataOra=SYSDATETIME() + WHERE RunId=@RunId; + END; + END + ELSE THROW 51113, 'Azione bilista non valida.', 1; + COMMIT TRANSACTION; + IF @Silent=0 SELECT CAST(@RunId AS varchar(36)) AS RunId,0 AS RC; + END TRY + BEGIN CATCH + IF XACT_STATE()<>0 ROLLBACK TRANSACTION; + THROW; + END CATCH; +END; +GO +PRINT 'Patch bilista installata. Nessun giro creato e nessuna UDC movimentata.'; +GO diff --git a/barcode_client.py b/barcode_client.py index 799ac46..a5ee73f 100644 --- a/barcode_client.py +++ b/barcode_client.py @@ -17,6 +17,8 @@ from async_loop_singleton import get_global_loop, stop_global_loop from async_msssql_query import AsyncMSSQLClient from barcode_repository import BarcodeRepository from barcode_service import BarcodeActionResult, BarcodeService, BarcodeViewState +from barcode_pair_service import BarcodePairService +from pickinglist_pair import PAIR_SLOT_COLORS 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 @@ -63,7 +65,8 @@ class BarcodeClientApp: self.session = session self.loop = loop self.repository = BarcodeRepository(db_client) - self.service = BarcodeService(self.repository, session.operator_id) + self.service = BarcodePairService(self.repository, session.operator_id) + self._pending_movement = False self._pending: Future | None = None self._auto_advance_id: str | None = None self._pallet_auto_focus_id: str | None = None @@ -93,6 +96,7 @@ class BarcodeClientApp: self.root.protocol("WM_DELETE_WINDOW", self._shutdown) self.root.after(80, self._finalize_window_placement) self.root.after(250, self._finalize_window_placement) + self.root.after(300, lambda: self._run_async(self.service.prepare_pair, "In preparazione...")) def _build_ui(self) -> None: self.root.title(versioned_title("WMS", __name__)) @@ -371,11 +375,14 @@ class BarcodeClientApp: else: self.busy_bar.stop() self.busy_cover.place_forget() + if self.service.pair_active: + self.btn_f2.configure(state="disabled") def _is_priority_pause(self) -> bool: return str(self.queue_var.get() or "") == "Pausa PL" def _apply_state(self, state: BarcodeViewState) -> None: + self._apply_pair_color(state) if self._auto_advance_id is not None: try: self.root.after_cancel(self._auto_advance_id) @@ -408,6 +415,7 @@ class BarcodeClientApp: try: if str(effective_queue_label or "") != "Pausa PL": self._paused_queue_id = None + self._paused_priority_state = 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") @@ -415,8 +423,8 @@ class BarcodeClientApp: 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) + self.btn_f1.configure(state=queue_buttons_state, text="[F1] Inizia lista") + self.btn_f2.configure(state="disabled" if self.service.pair_active else queue_buttons_state) except Exception: pass @@ -441,6 +449,20 @@ class BarcodeClientApp: else: self.root.after(20, self._focus_primary_input) + def _apply_pair_color(self, state: BarcodeViewState) -> None: + slot = state.pair_slot or (1 if state.mode == "priority_high" else 0) + color = PAIR_SLOT_COLORS.get(slot, "#f1f1f1") if state.queue_label != "Pausa PL" else "#f1f1f1" + + def paint(widget): + if widget in (self.status_band, self.busy_cover): + return + if isinstance(widget, (tk.Tk, tk.Frame, tk.Label)): + widget.configure(bg=color) + for child in widget.winfo_children(): + paint(child) + + paint(self.root) + def _refresh_action_labels(self, state: BarcodeViewState | None = None) -> None: current_state = state or self.service.state try: @@ -532,7 +554,13 @@ class BarcodeClientApp: return "break" def _on_escape_key(self, _event=None) -> str: + if self._pending is not None: + return "break" if self._is_priority_pause() and self._paused_queue_id is not None: + if self.service.pair_active: + saved = self._paused_priority_state + self._run_async(lambda: self.service.resume_pair(saved), "In preparazione...") + return "break" if self._paused_priority_state is not None: state = self.service.resume_priority_state(self._paused_priority_state) self._paused_priority_state = None @@ -547,6 +575,8 @@ class BarcodeClientApp: return "break" def _on_f3(self) -> None: + if self._pending is not None: + return mode = getattr(self.service.state, "mode", "") if mode == "priority_high": self._paused_queue_id = 1 @@ -567,6 +597,10 @@ class BarcodeClientApp: self._submit() def _begin_manual_unload(self) -> None: + if self._pending is not None: + return + if self.service.pair_active and not self._is_priority_pause() and self.service.state.mode == "confirm": + return pallet = str(self.scanned_var.get() or "").strip() destination = str(self.destination_var.get() or "").strip() mode = getattr(self.service.state, "mode", "") @@ -584,6 +618,8 @@ class BarcodeClientApp: self._apply_state(self.service.begin_manual_unload()) def _start_queue(self, id_stato: int, *, allow_during_pause: bool = False) -> None: + if id_stato == 0 and self.service.pair_active: + return if self._is_priority_pause() and not allow_during_pause: return self._run_async( @@ -592,12 +628,15 @@ class BarcodeClientApp: ) def _submit(self) -> None: + if self.service.pair_active and not self._is_priority_pause() and self.service.state.mode != "priority_high": + return self._run_async( lambda: self.service.submit( scanned_pallet=self.scanned_var.get(), destination_barcode=self.destination_var.get(), ), busy_message="In esecuzione...", + movement=True, ) def _submit_unload_with_source_check(self) -> None: @@ -607,6 +646,8 @@ class BarcodeClientApp: source_barcode=self.destination_var.get(), ), busy_message="In esecuzione...", + movement=True, + recovery_destination=self.NON_SCAFFALATA_BARCODE, ) def _skip_current_picking_pallet(self) -> None: @@ -615,8 +656,9 @@ class BarcodeClientApp: busy_message="Registro salto UDC...", ) - def _run_async(self, coro_factory: Callable[[], object], busy_message: str) -> None: - if self._pending is not None and not self._pending.done(): + def _run_async(self, coro_factory: Callable[[], object], busy_message: str, *, movement: bool = False, + recovery_destination: str | None = None) -> None: + if self._pending is not None: return if self._auto_advance_id is not None: try: @@ -625,6 +667,8 @@ class BarcodeClientApp: pass self._auto_advance_id = None self._set_busy(True, busy_message) + self._pending_movement = movement + self._pending_scan = (self.scanned_var.get(), recovery_destination or self.destination_var.get()) self._pending = asyncio.run_coroutine_threadsafe(coro_factory(), self.loop) self.root.after(40, self._poll_future) @@ -640,6 +684,8 @@ class BarcodeClientApp: delay_ms = int(getattr(state, "auto_advance_delay_ms", 0) or 0) if delay_ms <= 0: return None + if state.pair_run_id: + return 1 return self._queue_id_from_label(str(getattr(state, "queue_label", "") or "")) def _poll_future(self) -> None: @@ -657,11 +703,19 @@ class BarcodeClientApp: result = future.result() except Exception as exc: log_exception("Barcode WMS", exc, context="barcode async operation") + if not self._pending_movement: + current = self.service.state + current.auto_advance_delay_ms = 0 + current.status_text = "Operazione non completata: verificare prenotazione e connessione." + current.status_color = self._status_colors["red"] + self._apply_state(current) + self._show_transaction_error() + return 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(), + scanned_pallet=self._pending_scan[0], + destination_barcode=self._pending_scan[1], ), self.loop, ) diff --git a/barcode_pair_service.py b/barcode_pair_service.py new file mode 100644 index 0000000..37416b0 --- /dev/null +++ b/barcode_pair_service.py @@ -0,0 +1,155 @@ +"""Paired picking coordinator. Free movements still use BarcodeService unchanged.""" + +from dataclasses import replace + +from barcode_service import BarcodeService, BarcodeViewState, BarcodeActionResult +from pickinglist_pair_repository import PickingPairRepository, PairSnapshot +from version_info import module_version + +__version__ = module_version(__name__) + + +class BarcodePairService(BarcodeService): + def __init__(self, repository, operator_id, pair_repository=None): + super().__init__(repository, operator_id) + self.pairs = pair_repository or PickingPairRepository(repository.db_client) + self._pair: PairSnapshot | None = None + self._pair_paused = False + + @property + def pair_active(self) -> bool: + return self._pair is not None + + async def prepare_pair(self): + """Identify an existing pair without advancing or simulating a scan.""" + self._pair = await self.pairs.snapshot() + return self._state + + def _decorate(self, state, document, *, paused=False): + slot = self._pair.documents.index(document) + 1 + if paused: + confirmed = state.mode == "confirm" + state = replace(state, mode="manual_unload", destination_readonly=False, + auto_advance_delay_ms=0, + scanned_pallet="" if confirmed else state.scanned_pallet, + destination_barcode=self.NON_SCAFFALATA_BARCODE if confirmed else state.destination_barcode) + return replace(state, pair_run_id=self._pair.run_id, pair_slot=slot, + pair_document=document, + queue_label="Pausa PL" if paused else f"Lista {slot} - PL {document}") + + def _proposal(self, snapshot, candidate): + row = snapshot.display_row(candidate.document, candidate.pallet) + self._current_priority_state = 1 + self._priority_documents[1] = candidate.document + self._pair = snapshot + location = self._display_location(cella=candidate.cell_id, ubicazione=row["Ubicazione"]) + self._state = self._decorate(BarcodeViewState( + mode="priority_high", status_text=f"Ok Cella - {location}", + status_color=self.LIGHT_GREEN, source_location=location, + document=candidate.document, expected_pallet=candidate.pallet, + customer=" - ".join(str(row.get(k) or "") for k in ("CodNazione", "NAZIONE")).strip(" -"), + destination_barcode=self.SHIPPED_BARCODE, destination_readonly=True, + ), candidate.document) + self._pair_paused = False + return BarcodeActionResult(True, self._state) + + async def start_priority_queue(self, id_stato): + if self._pair_paused: + return BarcodeActionResult(False, self._state, "Premi ESC per uscire dalla pausa.") + snapshot = await self.pairs.snapshot() + if self._pair and snapshot and snapshot.run_id != self._pair.run_id: + raise RuntimeError("Prenotazione cambiata durante il giro. Riavviare il terminalino.") + if snapshot: + self._pair = snapshot + if id_stato != 1: + return BarcodeActionResult(False, self._state, "Giro bilista: usa F1.") + snapshot.route() # Validate before releasing anything. + await self.pairs.command("F", self.operator_id, run_id=snapshot.run_id) + refreshed = await self.pairs.snapshot() + if refreshed and refreshed.run_id != snapshot.run_id: + raise RuntimeError("Il giro e cambiato. Ricaricare il terminalino.") + if refreshed: + route = refreshed.route() + if not route.pending: + raise RuntimeError("Residui cambiati durante il caricamento. Riprovare.") + return self._proposal(refreshed, route.pending[0]) + if self._pair: + self._pair = None + self._priority_documents.clear() + self._current_priority_state = -1 + self._state = BarcodeViewState(mode="manual_unload", status_text="Giro terminato. Riprenota le eventuali UDC saltate.", + destination_barcode=self.NON_SCAFFALATA_BARCODE) + return BarcodeActionResult(True, self._state) + return await super().start_priority_queue(id_stato) + + async def skip_current_picking_pallet(self): + if not self._pair: + return await super().skip_current_picking_pallet() + state = self._state + if state.mode != "priority_high" or self._pair_paused: + return BarcodeActionResult(False, state, "Nessuna UDC proposta da saltare.") + await self.pairs.command("K", self.operator_id, run_id=self._pair.run_id, + document=state.pair_document, pallet=state.expected_pallet) + self._state = replace(state, mode="confirm", status_text="UDC saltata, resta da prelevare", + status_color=self.RED, auto_advance_delay_ms=1500, scanned_pallet="") + return BarcodeActionResult(True, self._state) + + def begin_priority_pause(self, id_stato): + if not self._pair: + return super().begin_priority_pause(id_stato) + document = self._state.pair_document + self._pair_paused = True + state = super().begin_priority_pause(1) + self._state = self._decorate(state, document, paused=True) + return self._state + + async def resume_pair(self, saved): + snapshot = await self.pairs.snapshot() + if not snapshot or not self._pair or snapshot.run_id != self._pair.run_id: + raise RuntimeError("La coppia in pausa non e piu disponibile. Verificare la prenotazione.") + route = snapshot.route() + if saved is not None: + candidate = next((c for c in route.pending if c.document == saved.pair_document + and c.pallet == saved.expected_pallet), None) + if candidate: + return self._proposal(snapshot, candidate) + # Only advance if the paused UDC is no longer pending. + self._pair_paused = False + try: + return await self.start_priority_queue(1) + except Exception: + self._pair_paused = True + raise + + async def submit(self, **kwargs): + before = self._state + if self._pair and not self._pair_paused and before.mode != "priority_high": + return BarcodeActionResult(False, before, "Attendi la prossima UDC.") + result = await super().submit(**kwargs) + if self._pair and before.pair_document: + state = self._decorate(result.state, before.pair_document, paused=self._pair_paused) + if result.ok and not self._pair_paused and before.mode == "priority_high": + state = replace(state, auto_advance_delay_ms=3000, destination_readonly=True) + self._state = state + return BarcodeActionResult(result.ok, state, result.message) + return result + + async def submit_unload_with_source_check(self, **kwargs): + if self._pair and not self._pair_paused: + return BarcodeActionResult(False, self._state, "Metti in pausa la lista per un movimento libero.") + document = self._state.pair_document + result = await super().submit_unload_with_source_check(**kwargs) + if self._pair and document: + self._state = self._decorate(result.state, document, paused=self._pair_paused) + return BarcodeActionResult(result.ok, self._state, result.message) + return result + + async def reconcile_after_submit_exception(self, **kwargs): + before = self._state + result = await super().reconcile_after_submit_exception(**kwargs) + if self._pair and before.pair_document: + self._state = self._decorate(result.state, before.pair_document, paused=self._pair_paused) + if self._pair_paused: + self._state = replace(self._state, auto_advance_delay_ms=0, destination_readonly=False) + return BarcodeActionResult(result.ok, self._state, result.message) + return result diff --git a/barcode_repository.py b/barcode_repository.py index cf0cfa6..55ce1cd 100644 --- a/barcode_repository.py +++ b/barcode_repository.py @@ -40,7 +40,8 @@ WHERE Ordinamento > 0 AND s.IDStato = pl.IDStato AND s.Risolto = 0 ) -ORDER BY OrdinePrelievoGruppo, Ordinamento, Pallet, Documento; +ORDER BY CASE WHEN Cella=1000 THEN 0 ELSE 1 END, + OrdinePrelievoGruppo, Ordinamento, Pallet, Documento; """ SQL_PICKING_BY_PALLET = """ @@ -452,6 +453,8 @@ class BarcodeRepository: barcode_pallet: str, numero_cella: int, refresh_picking_reservation: bool = True, + pair_run_id: str | None = None, + pair_document: str | None = None, ) -> LegacyMoveResult: """Execute the same stored procedure used by the C# barcode form.""" @@ -473,7 +476,30 @@ class BarcodeRepository: ), ) try: - res = await self.db_client.query_json(SQL_LEGACY_MOVE, params, commit=True) + sql = SQL_LEGACY_MOVE + if pair_run_id: + # Guard and movement share the caller's transaction and app lock. + # No extra SQL is added to free or monolist movements. + params.update(pair_run_id=pair_run_id, pair_document=pair_document) + sql = """ +SET NOCOUNT ON; SET XACT_ABORT ON; +EXEC dbo.py_sp_PickingPair @Action='G',@IDOperatore=:id_operatore, + @RunId=:pair_run_id,@Documento=:pair_document,@Pallet=:barcode_pallet,@Silent=1; +""" + SQL_LEGACY_MOVE + sql = sql.replace("SELECT\n @RC AS RC,", """ +-- Legacy @RC is the inserted movement identity, not a zero-success code. +IF NOT EXISTS(SELECT 1 FROM dbo.XMag_GiacenzaPallet + WHERE BarcodePallet COLLATE Latin1_General_CI_AS=:barcode_pallet COLLATE Latin1_General_CI_AS AND IDCella=9999) + OR EXISTS(SELECT 1 FROM dbo.XMag_GiacenzaPallet + WHERE BarcodePallet COLLATE Latin1_General_CI_AS=:barcode_pallet COLLATE Latin1_General_CI_AS AND IDCella<>9999) + THROW 51115, 'Movimento bilista non confermato nella cella spedita.', 1; +EXEC dbo.py_sp_PickingPair @Action='F',@IDOperatore=:id_operatore, + @RunId=:pair_run_id,@Silent=1; +SELECT + @RC AS RC,""") + # Pair reservations are independent of the legacy singleton. + params["refresh_picking_reservation"] = 0 + res = await self.db_client.query_json(sql, params, commit=True) except Exception as exc: log_exception( "Barcode WMS", diff --git a/barcode_service.py b/barcode_service.py index a7eed7b..a8cd3b9 100644 --- a/barcode_service.py +++ b/barcode_service.py @@ -31,6 +31,9 @@ class BarcodeViewState: auto_advance_delay_ms: int = 0 destination_readonly: bool = False focus_destination: bool = False + pair_run_id: str = "" + pair_slot: int = 0 + pair_document: str = "" @dataclass @@ -400,6 +403,8 @@ class BarcodeService: barcode_pallet=pallet, numero_cella=target_numero_cella, refresh_picking_reservation=is_picking_unload, + **({"pair_run_id": self._state.pair_run_id, "pair_document": self._state.pair_document} + if is_picking_unload and self._state.pair_run_id else {}), ) final_location = await self.repository.fetch_current_location_by_pallet(pallet) diff --git a/gestione_pickinglist.py b/gestione_pickinglist.py index eb00cf7..ff1ba04 100644 --- a/gestione_pickinglist.py +++ b/gestione_pickinglist.py @@ -332,8 +332,11 @@ DET_COLS: List[ColSpec] = [ ] ROW_H = 28 -RESERVED_IDSTATO_BG = "#dc2626" -RESERVED_IDSTATO_FG = "#ffffff" +from pickinglist_pair import PAIR_SLOT_COLORS +from pickinglist_pair_repository import PickingPairRepository + +RESERVED_IDSTATO_BG = PAIR_SLOT_COLORS[1] +RESERVED_IDSTATO_FG = "#111827" # -------------------- Micro spinner (toolbar) -------------------- @@ -651,6 +654,8 @@ class GestionePickingListFrame(ctk.CTkFrame): pass self.rows_models: list[PLRow] = [] + self._selection_order: list[str] = [] + self._reserved_pair_documents: set[str] = set() self._detail_cache: Dict[Any, list] = {} self.detail_doc = None self.days_var = tk.StringVar(value="10") @@ -707,12 +712,15 @@ class GestionePickingListFrame(ctk.CTkFrame): (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( + button = ctk.CTkButton( top, text=text, command=cmd, font=theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold")), - ).grid(row=0, column=i, padx=6) + ) + button.grid(row=0, column=i, padx=6) + if cmd == self.on_sequence: + self.sequence_button = button ctk.CTkLabel( top, @@ -728,6 +736,10 @@ class GestionePickingListFrame(ctk.CTkFrame): font=theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold")), ).grid(row=0, column=6, padx=(0, 6), sticky="w") + self.selection_hint = ctk.CTkLabel(top, text="", anchor="w") + self.selection_hint.grid(row=1, column=0, columnspan=7, padx=6, pady=(4, 2), sticky="w") + self._update_sequence_button() + # --- 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 @@ -913,8 +925,9 @@ class GestionePickingListFrame(ctk.CTkFrame): 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 + slot = int(d.get("IDStato") or 0) + is_reserved = slot in PAIR_SLOT_COLORS + holder_bg = PAIR_SLOT_COLORS.get(slot, row_bg) holder.configure(fg_color=holder_bg) if holder.winfo_children(): lbl = holder.winfo_children()[0] @@ -951,8 +964,8 @@ class GestionePickingListFrame(ctk.CTkFrame): row_index=r, anchors=[c.anchor for c in PL_COLS], 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, + cell_bg={"IDStato": PAIR_SLOT_COLORS[int(d["IDStato"])]} if int(d.get("IDStato") or 0) in PAIR_SLOT_COLORS else None, + cell_fg={"IDStato": RESERVED_IDSTATO_FG} if int(d.get("IDStato") or 0) in PAIR_SLOT_COLORS else None, ) # 🎯 Colora dopo che la UI è resa → no balzi visivi @@ -961,11 +974,25 @@ class GestionePickingListFrame(ctk.CTkFrame): # ----- helpers ----- def _get_selected_model(self) -> Optional[PLRow]: """Return the currently checked picking list row, if any.""" - for m in self.rows_models: - if m.is_checked(): - return m + selected = self._selected_models() + if selected: + return next((m for m in selected if _s(m.pl.get("Documento")) == _s(self.detail_doc)), selected[0]) return None + def _selected_models(self) -> list[PLRow]: + by_doc = {_s(m.pl.get("Documento")): m for m in self.rows_models if m.is_checked()} + return [by_doc[d] for d in self._selection_order if d in by_doc] + + def _update_sequence_button(self): + selected = self._selected_models() + blocked = len(selected) != 1 or any(_s(m.pl.get("Documento")) in self._reserved_pair_documents for m in selected) + self.sequence_button.configure(state="disabled" if blocked else "normal") + docs = [_s(m.pl.get("Documento")) for m in selected] + hint = loc_text("picking.pair.selection_hint", catalog=self._locale_catalog, + default="Ordine di selezione: {documents}. Conferma con Prenota.") + self.selection_hint.configure(text=hint.format(documents=" / ".join( + f"{i}: PL {doc}" for i, doc in enumerate(docs, 1))) if docs else "") + def _recolor_row_by_documento(self, documento: str, idstato: int): """Aggiorna colore riga e cella IDStato per il Documento indicato.""" for idx, m in enumerate(self.rows_models): @@ -1031,21 +1058,24 @@ class GestionePickingListFrame(ctk.CTkFrame): @_log_call() def on_row_checked(self, model: PLRow, is_checked: bool): """Handle row selection changes and refresh the detail section.""" - # 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. + document = _s(model.pl.get("Documento")) if is_checked: - for m in self.rows_models: - if m is not model and m.is_checked(): - m.set_checked(False) + if document not in self._selection_order: + if len(self._selection_order) >= 2: + model.set_checked(False) + messagebox.showinfo("Picking List", loc_text("picking.pair.max_two", catalog=self._locale_catalog, + default="Seleziona al massimo due liste."), parent=self) + return + self._selection_order.append(document) + self._update_sequence_button() - self.detail_doc = model.pl.get("Documento") + self.detail_doc = document _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(): - params = {"Documento": self.detail_doc, "days": days} + params = {"Documento": document, "days": days} _log_sql("SQL_PL_DETAILS", SQL_PL_DETAILS, params) return await self.db_client.query_json(SQL_PL_DETAILS, params) @@ -1053,7 +1083,9 @@ class GestionePickingListFrame(ctk.CTkFrame): # NON fermare lo spinner subito: lo farà _refresh_details_incremental rows = _expand_detail_rows_for_test(_rows_to_dicts(res)) _log_dataset("SQL_PL_DETAILS", rows) - self._detail_cache[self.detail_doc] = rows + self._detail_cache[document] = rows + if _s(self.detail_doc) != document: + return # Avvia il rendering incrementale che mantiene l'overlay attivo self._refresh_details_incremental() @@ -1074,6 +1106,12 @@ class GestionePickingListFrame(ctk.CTkFrame): self.busy.show(f"Carico UDC per Documento {self.detail_doc}…") else: + self._selection_order = [d for d in self._selection_order if d != document] + self._update_sequence_button() + remaining = self._selected_models() + if remaining: + self.on_row_checked(remaining[-1], True) + return if not any(m.is_checked() for m in self.rows_models): self.detail_doc = None _MODULE_LOGGER.info("Nessun documento selezionato: ripristino placeholder del dettaglio.") @@ -1093,14 +1131,36 @@ class GestionePickingListFrame(ctk.CTkFrame): async def _job(): params = {"days": days} _log_sql("SQL_PL", SQL_PL, params) - return await self.db_client.query_json(SQL_PL, params) + result = await self.db_client.query_json(SQL_PL, params) + pair_result = await self.db_client.query_json( + "SELECT Documento1,Documento2,Active1,Active2 FROM dbo.py_PickingPair WHERE IsOpen=1;") + pair_rows = _rows_to_dicts(pair_result) + pair_docs, slots = [], {} + if pair_rows: + pair = pair_rows[0] + pair_docs = [_s(pair["Documento1"]), _s(pair["Documento2"])] + slots = {pair_docs[i - 1]: i if pair[f"Active{i}"] else 0 for i in (1, 2)} + rows = _rows_to_dicts(result) + for row in rows: + doc = _s(row["Documento"]) + if doc in slots: + row["IDStato"] = slots[doc] + return {"rows": rows, "pair_documents": pair_docs} def _on_success(res): rows = _rows_to_dicts(res) _log_dataset("SQL_PL", rows) self._refresh_mid_rows(rows) + self._reserved_pair_documents = set(res.get("pair_documents", [])) + visible = {_s(m.pl.get("Documento")) for m in self.rows_models} + self._selection_order = [d for d in self._selection_order if d in visible] + for m in self.rows_models: + m.set_checked(_s(m.pl.get("Documento")) in self._selection_order) + self._update_sequence_button() if reselect_documento: def _reselect_or_clear(doc=reselect_documento): found = self._reselect_documento_after_reload(doc) + if not found and self._selection_order: + found = self._reselect_documento_after_reload(self._selection_order[-1]) if not found: self.detail_doc = None self._draw_details_hint() @@ -1193,6 +1253,13 @@ class GestionePickingListFrame(ctk.CTkFrame): def on_sequence(self): """Open the pickup-sequence editor for the selected picking list.""" + if len(self._selected_models()) != 1 or any( + _s(m.pl.get("Documento")) in self._reserved_pair_documents for m in self._selected_models() + ): + messagebox.showinfo("Sequenza di prelievo", loc_text("picking.pair.sequence_blocked", catalog=self._locale_catalog, + default="Personalizzazione disponibile solo per una lista non abbinata."), parent=self) + return + if not self._can("pickinglist.sequence"): messagebox.showwarning( loc_text("picking.sequence.title", catalog=self._locale_catalog, default="Sequenza di prelievo"), @@ -1234,17 +1301,18 @@ class GestionePickingListFrame(ctk.CTkFrame): if not self._can("pickinglist.prenota"): messagebox.showwarning("Permesso negato", "L'operatore corrente non puo' prenotare picking list.", parent=self) return - model = self._get_selected_model() - if not model: + selected = self._selected_models() + if not selected: messagebox.showinfo("Prenota", "Seleziona una Picking List (checkbox) prima di prenotare.") return - documento = _s(model.pl.get("Documento")) - current = int(model.pl.get("IDStato") or 0) + documents = [_s(m.pl.get("Documento")) for m in selected] + documento = documents[0] + current = int(selected[0].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: + if len(documents) == 1 and current in (1, 2): messagebox.showinfo("Prenota", f"La Picking List {documento} è già prenotata.") return @@ -1256,9 +1324,12 @@ 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") + pairs = PickingPairRepository(self.db_client) + if len(documents) == 2: + await pairs.command("R", id_operatore, documents=tuple(documents)) + else: + await pairs.reserve_single(documento, id_operatore) + return SPResult(rc=0, message="", id_result=None) def _ok(res: SPResult): _MODULE_LOGGER.log(_MODULE_LOG_LEVEL, f"Esito prenotazione documento={documento} rc={getattr(res, 'rc', None)} message={getattr(res, 'message', None)}") @@ -1270,6 +1341,7 @@ class GestionePickingListFrame(ctk.CTkFrame): action="pickinglist.prenota", outcome="ok", target=documento, + details={"documents": documents}, ) self._detail_cache.pop(documento, None) self.reload_from_db(reselect_documento=documento) @@ -1303,7 +1375,7 @@ class GestionePickingListFrame(ctk.CTkFrame): on_success=_ok, on_error=_err, busy=self.busy, - message=f"Prenoto la Picking List {documento}…" + message=f"Prenoto PL {', '.join(documents)}..." ) @_log_call() @@ -1312,13 +1384,14 @@ class GestionePickingListFrame(ctk.CTkFrame): if not self._can("pickinglist.sprenota"): messagebox.showwarning("Permesso negato", "L'operatore corrente non puo' s-prenotare picking list.", parent=self) return - model = self._get_selected_model() - if not model: + selected = self._selected_models() + if not selected: messagebox.showinfo("S-prenota", "Seleziona una Picking List (checkbox) prima di s-prenotare.") return - documento = _s(model.pl.get("Documento")) - current = int(model.pl.get("IDStato") or 0) + documents = [_s(m.pl.get("Documento")) for m in selected] + documento = documents[0] + current = max(int(m.pl.get("IDStato") or 0) for m in selected) 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. @@ -1334,9 +1407,9 @@ 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") + # Release selected slots atomically, without changing the other role. + await PickingPairRepository(self.db_client).release_selected(documents, id_operatore) + return SPResult(rc=0, message="", id_result=None) def _ok(res: SPResult): _MODULE_LOGGER.log(_MODULE_LOG_LEVEL, f"Esito s-prenotazione documento={documento} rc={getattr(res, 'rc', None)} message={getattr(res, 'message', None)}") @@ -1348,6 +1421,7 @@ class GestionePickingListFrame(ctk.CTkFrame): action="pickinglist.sprenota", outcome="ok", target=documento, + details={"documents": documents}, ) self._detail_cache.pop(documento, None) self.reload_from_db(reselect_documento=documento) @@ -1381,7 +1455,7 @@ class GestionePickingListFrame(ctk.CTkFrame): on_success=_ok, on_error=_err, busy=self.busy, - message=f"S-prenoto la Picking List {documento}…" + message=f"S-prenoto PL {', '.join(documents)}..." ) def on_export(self): diff --git a/locale.json b/locale.json index 51ad915..e09af9d 100644 --- a/locale.json +++ b/locale.json @@ -1,6 +1,9 @@ { "default_language": "IT", "IT": { + "picking.pair.selection_hint": "Ordine di selezione: {documents}. Conferma con Prenota.", + "picking.pair.max_two": "Seleziona al massimo due liste.", + "picking.pair.sequence_blocked": "Personalizzazione disponibile solo per una lista non abbinata.", "launcher.window_title": "Warehouse 1.0.0", "launcher.operator": "Operatore: {display_name} ({login})", "launcher.reset_corsie": "Gestione Corsie", @@ -129,7 +132,7 @@ "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.default_hint": "Non scaff. sempre per prime; l'ordine personalizzato riguarda solo gli scaffali.", "picking.sequence.button.add": "Aggiungi >", "picking.sequence.button.remove": "< Rimuovi", "picking.sequence.button.up": "Su", @@ -161,6 +164,9 @@ "scarico.msg.exec_error": "Scarico fallito:\n{error}" }, "ENG": { + "picking.pair.selection_hint": "Selection order: {documents}. Confirm with Reserve.", + "picking.pair.max_two": "Select at most two lists.", + "picking.pair.sequence_blocked": "Custom ordering is available only for one unpaired list.", "launcher.window_title": "Warehouse 1.0.0", "launcher.operator": "Operator: {display_name} ({login})", "launcher.reset_corsie": "Aisle Management", @@ -289,7 +295,7 @@ "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.default_hint": "Non-shelved always first; custom ordering applies only to racks.", "picking.sequence.button.add": "Add >", "picking.sequence.button.remove": "< Remove", "picking.sequence.button.up": "Up", diff --git a/pickinglist_pair.py b/pickinglist_pair.py new file mode 100644 index 0000000..58dd81c --- /dev/null +++ b/pickinglist_pair.py @@ -0,0 +1,139 @@ +"""Pure routing rules for paired picking. + +The caller supplies a fresh residual snapshot and per-document rack sequences. +No database writes, Tk calls, movement execution or reservation changes occur +here. Keeping this calculation independent allows deterministic regression +tests without moving stock. SQL access and UI integration live in separate modules. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Iterable, Mapping + +from version_info import module_version + +__version__ = module_version(__name__) + +NON_SHELVED_CELL = 1000 +SHIPPED_CELL = 9999 +PAIR_SLOT_COLORS = {1: "#ffe6f2", 2: "#fff2cc"} + + +class PairRoutingError(ValueError): + """Reject an inconsistent snapshot rather than silently omitting stock.""" + + +@dataclass(frozen=True) +class PickingCandidate: + """One physical UDC, possibly repeated across lot rows of the same document. + + ``area`` is the operational area 5/6, NOT the legacy Aree primary key. + It is ignored for virtual locations. ``cell_order`` is Celle.Ordinamento; + it preserves both the Area 5 serpentine and the Area 6 upward route. + ``group_key`` identifies the rack for a shared custom sequence. + """ + + document: str + pallet: str + cell_id: int + area: int | None + cell_order: int + group_key: str + + +@dataclass(frozen=True) +class PairRoute: + """Read-only result; skipped candidates remain residual, never shipped.""" + + documents: tuple[str, str] + area: int | None + pending: tuple[PickingCandidate, ...] + skipped: tuple[PickingCandidate, ...] + + def slot_for(self, document: str) -> int: + """Return the stable desktop IDStato 1/2, independent of route position.""" + if document not in self.documents: + raise PairRoutingError("Documento estraneo alla coppia.") + return self.documents.index(document) + 1 + + +def build_pair_route( + candidates: Iterable[PickingCandidate], + *, + documents: tuple[str, str], + document_sequences: Mapping[str, Iterable[str]] | None = None, + skipped: Iterable[tuple[str, str]] = (), +) -> PairRoute: + """Build a route from a residual snapshot without changing any input. + + ``documents`` defines the reservation roles, not which document starts. + ``document_sequences`` contains saved per-document sequences. Only the + first selected document's sequence governs the pair, even if the second + document starts the route. The second sequence is never merged or changed. + An empty/missing first sequence uses the legacy global order for both. + Non-shelved UDCs always precede racks, even if NON_SCAFF appears last in + an older sequence. Unconfigured racks follow configured racks in legacy + cell order. Non-shelved UDCs are ordered by slot 1 then slot 2, and by + pallet code within each slot, before any physical cell is proposed. + + ``skipped`` contains (document, pallet) identities from the active cycle. + Area consistency is checked before separating skips from workable UDCs. + Duplicate lot rows collapse only when their route metadata agrees. + """ + if len(documents) != 2 or any(not d or d != d.strip() for d in documents): + raise PairRoutingError("Servono due documenti non vuoti.") + if documents[0] == documents[1]: + raise PairRoutingError("La coppia deve contenere due documenti diversi.") + first_sequence = (document_sequences or {}).get(documents[0], ()) + groups = tuple(key for key in first_sequence if key != "NON_SCAFF") + if any(not key for key in groups) or len(groups) != len(set(groups)): + raise PairRoutingError("Sequenza scaffali non valida.") + rank = {key: index for index, key in enumerate(groups)} + slots = {document: index + 1 for index, document in enumerate(documents)} + unique: dict[tuple[str, str], PickingCandidate] = {} + owners: dict[str, str] = {} + areas: set[int] = set() + + for row in candidates: + if row.document not in slots: + raise PairRoutingError("Documento estraneo alla coppia.") + if row.cell_id == SHIPPED_CELL: + continue + if not row.pallet or row.pallet != row.pallet.strip(): + raise PairRoutingError("Codice UDC mancante o non normalizzato.") + if row.cell_id != NON_SHELVED_CELL: + if row.cell_id <= 0 or row.area not in (5, 6): + raise PairRoutingError("Area della cella fisica non riconosciuta.") + if row.cell_order <= 0 or not row.group_key: + raise PairRoutingError("Ordinamento della cella fisica non valido.") + areas.add(row.area) + owner = owners.setdefault(row.pallet, row.document) + if owner != row.document: + raise PairRoutingError(f"UDC {row.pallet} presente in entrambe le liste.") + identity = (row.document, row.pallet) + previous = unique.get(identity) + if previous is not None and previous != row: + raise PairRoutingError(f"Posizione o percorso discordante per UDC {row.pallet}.") + unique[identity] = row + + if len(areas) > 1: + raise PairRoutingError("Le UDC scaffalate devono appartenere alla stessa area.") + + def route_key(row: PickingCandidate) -> tuple: + slot = slots[row.document] + if row.cell_id == NON_SHELVED_CELL: + return (0, slot, row.pallet) + if row.group_key in rank: + return (1, 0, rank[row.group_key], row.cell_order, row.pallet, slot) + # Do not group racks in the default: that would destroy Area 5's serpentine. + return (1, 1, 0, row.cell_order, row.pallet, slot) + + ordered = sorted(unique.values(), key=route_key) + skip_ids = set(skipped) + return PairRoute( + documents=documents, + area=next(iter(areas)) if areas else None, + pending=tuple(row for row in ordered if (row.document, row.pallet) not in skip_ids), + skipped=tuple(row for row in ordered if (row.document, row.pallet) in skip_ids), + ) diff --git a/pickinglist_pair_repository.py b/pickinglist_pair_repository.py new file mode 100644 index 0000000..9749d1b --- /dev/null +++ b/pickinglist_pair_repository.py @@ -0,0 +1,116 @@ +"""SQL access for paired reservations, isolated from legacy movement rules.""" + +from dataclasses import dataclass +from typing import Any + +from barcode_repository import _rows_to_dicts +from pickinglist_pair import PickingCandidate, PairRoute, build_pair_route +from version_info import module_version + +__version__ = module_version(__name__) + +PAIR_LOCK_SQL = """ +DECLARE @PairLock int; +EXEC @PairLock=sys.sp_getapplock @Resource='py_PickingPair', + @LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000; +IF @PairLock<0 THROW 51101, 'Prenotazione occupata. Riprovare.', 1; +""" + +PAIR_COMMAND_SQL = """ +EXEC dbo.py_sp_PickingPair @Action=:action, @IDOperatore=:operator, + @Documento1=:document1, @Documento2=:document2, @RunId=:run_id, + @Documento=:document, @Pallet=:pallet; +""" + + +@dataclass(frozen=True) +class PairSnapshot: + run_id: str + documents: tuple[str, str] + active: frozenset[str] + rows: tuple[dict[str, Any], ...] + + def route(self) -> PairRoute: + candidates = [] + skipped = set() + sequence = {} + for row in self.rows: + if row.get("SequenceOrder") is not None: + sequence[str(row["GroupKey"])] = int(row["SequenceOrder"]) + document = str(row["SlotDocument"]) + if document not in self.active or row.get("Pallet") is None: + continue + if str(row["StatoDocumento"]).strip() != "P": + raise ValueError(f"PL {document}: stato ERP cambiato. Verificare la lista.") + pallet = str(row["Pallet"]).strip() + candidates.append(PickingCandidate(document, pallet, int(row["Cella"]), + int(row["OperationalArea"]) if row.get("OperationalArea") is not None else None, + int(row["Ordinamento"]), str(row["GroupKey"]))) + if row["IsSkipped"]: + skipped.add((document, pallet)) + return build_pair_route(candidates, documents=self.documents, + document_sequences={self.documents[0]: sorted(sequence, key=sequence.get)}, skipped=skipped) + + def display_row(self, document: str, pallet: str) -> dict: + return next(row for row in self.rows + if str(row["SlotDocument"]) == document and str(row.get("Pallet", "")).strip() == pallet) + + +class PickingPairRepository: + def __init__(self, db_client): + self.db_client = db_client + + async def snapshot(self) -> PairSnapshot | None: + result = await self.db_client.query_json("SELECT * FROM dbo.py_ViewPickingPairRows;") + rows = _rows_to_dicts(result) + if not rows: + return None + head = rows[0] + documents = (str(head["Documento1"]), str(head["Documento2"])) + active = frozenset(d for d, yes in zip(documents, (head["Active1"], head["Active2"])) if yes) + return PairSnapshot(str(head["RunId"]), documents, active, tuple(rows)) + + async def command(self, action: str, operator: int, *, documents=(None, None), + run_id=None, document=None, pallet=None) -> None: + await self.db_client.query_json(PAIR_COMMAND_SQL, { + "action": action, "operator": operator, "document1": documents[0], + "document2": documents[1], "run_id": run_id, "document": document, + "pallet": pallet, + }, commit=True) + + async def reserve_single(self, document: str, operator: int) -> None: + # Hold the same lock as pair reservation until this transaction commits. + sql = "SET NOCOUNT ON; SET XACT_ABORT ON;\n" + PAIR_LOCK_SQL + """ +IF EXISTS(SELECT 1 FROM dbo.py_PickingPair WHERE IsOpen=1) + THROW 51104, 'Sprenotare il giro bilista prima di cambiarlo.', 1; +DECLARE @RC int=0; +EXEC dbo.py_sp_xExePackingListPallet @IDOperatore=:operator, + @Documento=:document,@Azione='P',@RC=@RC OUTPUT; +IF @RC<>0 THROW 51109, 'Prenotazione non completata.', 1; +UPDATE dbo.py_BarcodePickingListSkip SET Risolto=1 + WHERE Documento=:document AND Risolto=0; +SELECT @RC AS RC; +""" + await self.db_client.query_json(sql, {"operator": operator, "document": document}, commit=True) + + async def release_selected(self, documents: list[str], operator: int) -> None: + # One transaction for the whole desktop selection, no partial release. + sql = "SET NOCOUNT ON; SET XACT_ABORT ON;\n" + PAIR_LOCK_SQL + params = {"operator": operator} + for index, doc in enumerate(documents): + params[f"doc{index}"] = doc + sql += f""" +DECLARE @Run{index} uniqueidentifier=(SELECT RunId FROM dbo.py_PickingPair + WHERE IsOpen=1 AND (Documento1=:doc{index} OR Documento2=:doc{index})); +IF @Run{index} IS NOT NULL + EXEC dbo.py_sp_PickingPair @Action='U',@IDOperatore=:operator, + @RunId=@Run{index},@Documento=:doc{index},@Silent=1; +ELSE +BEGIN + DECLARE @RC{index} int=0; + EXEC dbo.py_sp_xExePackingListPallet @IDOperatore=:operator, + @Documento=:doc{index},@Azione='S',@RC=@RC{index} OUTPUT; + IF @RC{index}<>0 THROW 51109, 'Sprenotazione non completata.', 1; +END; +""" + await self.db_client.query_json(sql + "\nSELECT 0 AS RC;", params, commit=True) diff --git a/pickinglist_sequence.py b/pickinglist_sequence.py index 75a71bb..2a2c3c8 100644 --- a/pickinglist_sequence.py +++ b/pickinglist_sequence.py @@ -20,6 +20,7 @@ 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 pickinglist_pair_repository import PAIR_LOCK_SQL from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text __version__ = module_version(__name__) @@ -43,7 +44,13 @@ ORDER BY """ -SQL_RESET_SEQUENCE = """ +SEQUENCE_GUARD_SQL = PAIR_LOCK_SQL + """ +IF EXISTS(SELECT 1 FROM dbo.py_PickingPair WHERE IsOpen=1 + AND (Documento1=:documento OR Documento2=:documento)) + THROW 51114, 'Sequenza bloccata durante il giro bilista.', 1; +""" + +SQL_RESET_SEQUENCE = SEQUENCE_GUARD_SQL + """ SET NOCOUNT ON; SET XACT_ABORT ON; UPDATE dbo.py_PickingListPrelievoSequenza @@ -266,6 +273,8 @@ class PickingListSequenceWindow(ctk.CTkToplevel): configured: list[tuple[int, PickupGroup]] = [] available: list[PickupGroup] = [] for row in rows: + if str(row.get("GruppoPrelievoChiave") or "").strip() == "NON_SCAFF": + continue # Non-shelved UDCs always precede the configurable racks. group = PickupGroup( key=str(row.get("GruppoPrelievoChiave") or "").strip(), label=str(row.get("GruppoPrelievo") or "").strip(), @@ -474,7 +483,7 @@ WHERE Documento = :documento {insert} SELECT CAST({len(values)} AS int) AS ElementiSalvati; """ - return sql, params + return SEQUENCE_GUARD_SQL + sql, params def _save(self) -> None: """Persist the configured prefix atomically.""" diff --git a/rollback_pickinglist_pair_patch.sql b/rollback_pickinglist_pair_patch.sql new file mode 100644 index 0000000..afda258 --- /dev/null +++ b/rollback_pickinglist_pair_patch.sql @@ -0,0 +1,16 @@ +/* Fermare i client. Ripristinare anche il codice warehouse-monolista-2.0. + Non annulla movimentazioni o prenotazioni storiche; non modifica SAM. + I dati dei giri/skip vengono conservati per audit e reinstallazione. +*/ +SET XACT_ABORT ON; +BEGIN TRANSACTION; +IF OBJECT_ID('dbo.py_PickingPair','U') IS NOT NULL + AND EXISTS(SELECT 1 FROM dbo.py_PickingPair WHERE IsOpen=1) +BEGIN + ROLLBACK; + THROW 51120, 'Sprenotare il giro bilista prima del rollback.', 1; +END; +DROP PROCEDURE IF EXISTS dbo.py_sp_PickingPair; +DROP VIEW IF EXISTS dbo.py_ViewPickingPairRows; +COMMIT; +PRINT 'Oggetti eseguibili bilista rimossi; tabelle di audit conservate.'; diff --git a/specifica_prelievo_due_pickinglist.md b/specifica_prelievo_due_pickinglist.md index 10bf497..b0365e5 100644 --- a/specifica_prelievo_due_pickinglist.md +++ b/specifica_prelievo_due_pickinglist.md @@ -1,10 +1,11 @@ # Prelievo guidato di due picking list sul terminalino -Data: 02/10/2026. Revisione: 0.3. +Data: 02/10/2026. Revisione: 1.0. -**Stato: specifica da rileggere e concordare prima dell'implementazione.** -La funzione di prelievo abbinato descritta qui non e' ancora implementata. -I punti indicati come aperti o proposti non sono decisioni gia' approvate. +**Stato: implementazione bilista 2.1.0 collegata a desktop, barcode e SQL; +collaudo locale automatizzato eseguito, collaudo operatore da completare.** +La sezione 17 descrive l'implementazione e le protezioni conservative adottate. +Le sezioni precedenti conservano anche la storia delle decisioni. ## 1. Obiettivo operativo @@ -25,8 +26,8 @@ decisioni e non e' definita da questa specifica. | Termine | Significato | |---|---| -| Lista 1 / F1 | Prima lista assegnata alla coppia, con identita' stabile | -| Lista 2 / F2 | Seconda lista assegnata alla coppia, con identita' stabile | +| Lista 1 / IDStato 1 | Prima lista assegnata alla coppia, con identita' stabile | +| Lista 2 / IDStato 2 | Seconda lista assegnata alla coppia, con identita' stabile | | Lista proposta | Documento della prossima UDC indicata dal sistema | | Colonna o campata | Colonna di uno specifico scaffale e magazzino | | Cella | Singola posizione dentro la colonna, a un determinato livello | @@ -37,6 +38,11 @@ Area 5 e Area 6 sono i nomi operativi dei magazzini MDE5 e MDE6. Non corrispondono necessariamente agli ID 5 e 6 della tabella legacy Aree. La colonna 1 dello scaffale A e la colonna 1 dello scaffale B sono distinte. +Chiarimento del 02/10: con due liste F1 e' il comando di avvio del giro, +non la scelta obbligatoria della Lista 1. Le sigle F1/F2 usate negli esempi +storici di questo documento indicano rispettivamente Lista 1 e Lista 2, +non tasti che l'operatore debba premere per cambiare documento. + ## 3. Situazione attuale e difetto da non reintrodurre La prenotazione Python attuale prevede un unico documento. Storicamente F1 @@ -65,12 +71,19 @@ avere un comportamento chiaramente distinguibile. ### R02. Identita' della coppia -Il desktop deve rendere riconoscibile quale documento e' Lista 1/F1 e quale -e' Lista 2/F2. L'assegnazione non dipende dall'ordinamento momentaneo della +Il desktop deve rendere riconoscibile quale documento e' Lista 1/IDStato 1 e quale +e' Lista 2/IDStato 2. L'assegnazione non dipende dall'ordinamento momentaneo della griglia o dalla posizione della prossima UDC. -Il gesto per assegnare i ruoli e' ancora da definire: ad esempio due slot -espliciti, oppure prima e seconda scelta rese chiaramente visibili. +Le liste non prenotate mantengono IDStato 0. Lo sfondo della cella IDStato +deve essere lo stesso colore di contesto usato sul terminalino: rosa per +Lista 1 e giallo per Lista 2. Lo stato 2 non e' un nuovo stato delle celle +fisiche: rappresenta il ruolo del documento nella prenotazione Python. + +Confermato il 02/10: si selezionano fino a due checkbox e poi si preme +Prenota. La prima lista selezionata assume IDStato 1, la seconda IDStato 2. +Il solo checkbox non modifica la prenotazione. L'ordine di selezione deve +essere conservato anche se cambia l'ordinamento visuale della griglia. ### R02a. Le due liste devono appartenere alla stessa area @@ -82,25 +95,42 @@ senza salvare una coppia parziale o alterare le prenotazioni preesistenti. Il vincolo deve essere verificato anche lato servizio/database, non soltanto mediante la disponibilita' dei pulsanti nell'interfaccia desktop. -Prima dell'implementazione va definita la fonte autorevole dell'area della -lista, specialmente se contiene UDC non scaffalate o senza giacenza WMS. -La cella virtuale condivisa 1000 non dimostra da sola l'appartenenza all'area. +Chiarimento confermato: le UDC non scaffalate possono trovarsi ovunque e non +appartengono ad alcuna area. Restano Non scaff. e non richiedono una scelta +artificiale fra Area 5 e Area 6. Anche l'eventuale magazzino associato nel +legacy alla cella virtuale 1000 non deve essere usato per attribuire loro +un'area. + +Il controllo di compatibilita' riguarda quindi le UDC nelle celle fisiche: +la loro presenza nelle due liste non deve imporre un giro misto Area 5/Area 6. Non dedurre il magazzino dal numero documento o dagli ID legacy delle Aree. -Il trattamento delle liste internamente miste o con area indeterminata resta -da concordare; non considerarle implicitamente compatibili con entrambe. +Una lista composta solo da Non scaff. non introduce un conflitto di area; +se entrambe sono composte solo da Non scaff., non c'e' un percorso scaffali +da scegliere. Celle fisiche con magazzino non riconoscibile restano invece +un'anomalia da gestire, non equivalgono a UDC non scaffalate. -### R03. Un'unica sequenza personalizzata +### R03. Nel bilista governa la sequenza della prima lista selezionata -Con due liste selezionate, il comando Sequenza di prelievo riguarda entrambe. -L'editor deve presentare l'unione degli scaffali/gruppi presenti nelle due liste, -includendo quelli presenti soltanto in una di esse e il gruppo Non scaff. +CONFERMATO: quando sono selezionate due liste, il pulsante Sequenza di prelievo +deve essere disabilitato. Non si apre un editor della coppia e non si chiede +all'operatore di risolvere un conflitto fra personalizzazioni preesistenti. -Non si devono eseguire due ordinamenti personalizzati incompatibili nello -stesso giro. La sequenza della coppia deve costituire l'unico riferimento. +Il giro abbinato segue la sequenza gia' salvata sulla prima lista selezionata, +ossia quella assegnata a IDStato 1. Non si intende la lista che il terminalino +propone per prima: quella puo' essere la Lista 2. L'ordinamento della griglia +non cambia quale documento e' il riferimento. -La scelta fra eventuali personalizzazioni gia' salvate sulle singole liste -resta aperta. Non e' ammessa una fusione silenziosa che produca un ordine -diverso da quello mostrato al responsabile. +Se la prima lista non ha personalizzazione, entrambe seguono l'ordine standard. +L'eventuale personalizzazione della seconda lista viene ignorata per il giro +abbinato, senza cancellarla o sovrascriverla. Non si fondono le due sequenze. + +Gli scaffali della seconda lista non presenti nella sequenza della prima +vengono accodati secondo il criterio standard gia' previsto per i gruppi +mancanti, senza escluderne le UDC. Non scaff. precede SEMPRE tutti gli scaffali, +anche se una personalizzazione precedente l'aveva collocato diversamente. + +La personalizzazione individuale rimane disponibile nel contesto monolista. +Questa regola sostituisce la precedente proposta di un editor comune della coppia. ## 5. Percorsi delle aree: conservare il comportamento esistente @@ -133,9 +163,10 @@ scaffale/colonna/livello dell'area 6. ### R06. Effetto della personalizzazione -La personalizzazione mantiene il significato attuale: cambia la precedenza -dei gruppi/scaffali, mentre dentro ogni gruppo si conserva l'ordine delle celle. -Con due liste, la stessa scelta si applica all'intero contenuto della coppia. +La personalizzazione cambia la precedenza degli scaffali, mentre dentro +ogni scaffale si conserva l'ordine delle celle. Non scaff. resta sempre primo. +Con due liste, la scelta gia' salvata sulla prima selezionata si applica +all'intero contenuto della coppia, senza modificarla durante la selezione doppia. Per esempio, porre tutto 1A prima di tutto 2B elimina intenzionalmente l'alternanza fra quei due scaffali, come avviene gia' nella personalizzazione @@ -176,27 +207,42 @@ documento a cui appartiene. Non introdurre la scelta automatica di una terza lista, neanche al termine di una delle due. La gestione delle UDC saltate e' trattata al punto 10. -## 7. Avvio neutro e tasti F1/F2 +## 7. Avvio con F1 e gestione dei tasti ### R10. Avvio scelto dal sistema -Quando il terminalino mostra Pronto per la coppia, il sistema deve avere gia' -individuato la prima proposta. L'operatore non decide arbitrariamente da quale -documento partire. +L'operatore preme sempre F1 per avviare il lavoro. Il sistema legge la +prenotazione e distingue tre casi: -Se la prima UDC appartiene alla Lista 2, F2 e' abilitato e F1 disabilitato; -se appartiene alla Lista 1, vale il contrario. Il blocco deve valere sia per -i pulsanti sullo schermo sia per i tasti fisici. +1. Nessuna lista prenotata: mantenere l'accesso attuale ai movimenti liberi. +2. Una lista prenotata: mantenere il comportamento monolista attuale. +3. Due liste prenotate: avviare il giro comune, scegliendo automaticamente + la prima UDC secondo il percorso dell'area e la personalizzazione. + +Nel terzo caso F1 puo' quindi proporre subito la Lista 2, con IDStato 2 e +sfondo giallo. Non occorre premere F2 per iniziare da questa lista. +Numero documento, UDC, cella e colore devono riferirsi alla stessa proposta. + +Questa decisione sostituisce la bozza precedente che abilitava all'avvio +soltanto F1 oppure F2 in base alla lista iniziale. CONFERMATO: con due liste +F2 e' disabilitato sia come pulsante sia come tasto fisico. Fra i comandi +di avvio l'operatore dispone soltanto di F1; durante il giro conserva Salta +UDC e Pausa PL, non la scelta manuale del documento. + +Per ora resta invariato il comportamento di F2 fuori dal giro abbinato. +L'eventuale futura eliminazione di F2 o conversione in "Interrompi lista" +e' rinviata: non fa parte di questa modifica. ### R11. Guida durante il giro -Nel prelievo abbinato deve essere selezionabile soltanto la lista proposta -dal percorso. Il cambio automatico verso l'altro documento non richiede una -nuova scelta dell'operatore. +Nel prelievo abbinato il documento da lavorare e' quello proposto dal percorso. +Il cambio automatico verso l'altro documento non richiede una nuova scelta +dell'operatore. La precedente modalita' manuale F1/F2 e il nuovo giro guidato non devono -essere confusi: nel giro guidato i due tasti identificano documenti stabili, -ma non autorizzano a scavalcare il percorso stabilito. +essere confusi: nel giro guidato sono i ruoli IDStato 1/2 a identificare +documenti stabili. La pressione di F1 non deve forzare la Lista 1 quando +il percorso richiede prima una UDC della Lista 2. ### Chiarimento confermato: la prima cella dipende dal percorso dell'area @@ -221,10 +267,10 @@ personalizzato e la precedenza delle Non scaff. descritta in R14. | Documento assegnato | Colore di contesto | |---|---| -| Lista 1 / F1 | Rosellino | -| Lista 2 / F2 | Giallino | +| Lista 1 / IDStato 1 | Rosellino | +| Lista 2 / IDStato 2 | Giallino | -Il colore segue il documento e non la sua posizione nel giro: se inizia F2, +Il colore segue il documento e non la sua posizione nel giro: se inizia Lista 2, lo sfondo iniziale e' giallino. La stessa lista conserva il proprio colore nei successivi passaggi. @@ -260,37 +306,72 @@ fosse riuscito; restano necessarie le verifiche e il recupero gia' esistenti. ### R14. Non scaffalate -Conservare il comportamento corrente: Non scaff. precede gli scaffali nel -default, salvo diversa posizione assegnata nella sequenza personalizzata. -La regola deve considerare le UDC di entrambe le liste. +Requisito confermato e obbligatorio: il prelievo parte SEMPRE dalle UDC +non scaffalate. Con due liste si considerano prima le Non scaff. di ENTRAMBE, +non soltanto quelle del documento dal quale parte il terminalino. +Solo esaurita questa fase si passa alle celle fisiche secondo il percorso +definito per l'area, oppure secondo la sequenza personalizzata degli scaffali. + +Questa precedenza non puo' essere cambiata dalla personalizzazione: supera +la precedente bozza che consentiva di spostare Non scaff. dopo uno scaffale. +Anche eventuali sequenze gia' salvate devono rispettare questa priorita'. +Le Non scaff. saltate restano residue ma vengono escluse dalle proposte del +ciclo corrente, come gli altri skip (R15). Esaurite le Non scaff. lavorabili +si passa alle scaffalate; nessuno skip viene considerato una spedizione. La cella virtuale e' condivisibile e non ha un livello fisico da confrontare. -Il criterio di parita' fra UDC non scaffalate delle due liste resta da -concordare; proposta: ordine stabile per ruolo lista e codice UDC. +CONFERMATO: prima le Non scaff. della Lista 1, poi quelle della Lista 2; +in ciascuna lista si mantiene l'ordine per codice UDC. Solo dopo questa fase +si inizia il prelievo dalle celle fisiche di entrambe. -### R15. UDC saltate: approfondimento rinviato +### R15. UDC saltate: comando conservato -Il comando Salta UDC esiste gia'. L'utente ha chiesto di analizzarne in seguito -il comportamento nel nuovo giro abbinato, con l'intenzione di conservare -quanto possibile il funzionamento attuale. +CONFERMATO: F4 conserva il comando Salta UDC anche nel giro abbinato. +Il salto riguarda il documento e la UDC correntemente proposti, non un +documento scelto manualmente mediante F2. Si passa alla prossima UDC lavorabile +del percorso comune senza registrare alcuno scarico per quella saltata. -Restano da decidere il termine della singola lista con soli skip, la sua -sprenotazione, la prosecuzione dell'altra lista e le modalita' di ripresa. -Saltare una UDC non deve comunque equivalere a spedirla o cancellarla dalla lista. +CONFERMATO: per ogni documento, quando non restano UDC lavorabili nel ciclo +attuale, la prenotazione viene portata automaticamente a 0. Se rimangono UDC +saltate, la lista continua a comparire fra le prenotabili con le sole residue. +Il salto non spedisce la UDC, non la cancella dalla lista e non chiude la lista +come completamente evasa. -### Pausa e ripresa: comportamento da completare +Per prelevare le residue, l'operatore seleziona e prenota nuovamente la lista. +Gli skip del ciclo precedente non devono impedire che tali UDC vengano proposte +nel nuovo ciclo; la traccia storica dei salti puo' essere conservata separatamente. +Si rilegge la posizione attuale di ogni UDC, senza riutilizzare una coda vecchia. -Oggi Pausa PL consente movimenti liberi e ESC riporta al picking. +La regola vale indipendentemente per entrambi i documenti: se sono state saltate +UDC in entrambe le liste, entrambe tornano prenotabili. Possono essere riprese +singolarmente o insieme, applicando alle code residue le stesse regole di +prelievo monolista/bilista. Non si ripropongono UDC gia' correttamente scaricate. + +### Pausa e ripresa: comando conservato + +CONFERMATO: Pausa PL consente di uscire temporaneamente dall'evasione abbinata +per effettuare movimenti liberi e poi rientrare con ESC, come nel monolista. +L'esito di un movimento libero non deve far perdere la coppia o causare +un rientro automatico indesiderato. F2 non e' necessario per questa funzione. Nel nuovo giro occorre conservare identita' dei due documenti e percorso. Va deciso se al rientro mantenere la UDC gia' proposta o ricalcolare la prossima posizione quando nel frattempo cambiano le ubicazioni. I movimenti liberi devono mantenere le proprie regole di carico e scarico. -### Fine di una lista: proposta ancora da confermare +### Fine di una lista: comportamento confermato -Quando una lista non ha piu' UDC residue, proseguire con l'altra mantenendone -ruolo e colore originali. Non promuovere automaticamente F2 a F1 e non -aggiungere un terzo documento. Distinguere esaurimento reale e soli skip. +Quando una lista non ha piu' UDC residue, viene sprenotata automaticamente, +scompare dall'elenco operativo delle prenotabili e rimane consultabile nello +storico, come nel comportamento attuale. Questo non richiede di inventare un +nuovo cambio di stato della testata ERP: si conserva la logica attuale di +visibilita' e conclusione del prelievo. + +Quando finisce il ciclo di una lista, con esaurimento reale oppure soli skip, +si continua sull'altra mantenendone ruolo e colore. Non promuovere la Lista 2 +a Lista 1, non cambiare il riferimento di percorso della coppia e non aggiungere +un terzo documento. Il ruolo del giro resta distinto dalla prenotazione ormai +azzerata del documento terminato. Quando entrambe hanno concluso il ciclo, +il giro termina; le eventuali residue richiedono una nuova prenotazione esplicita. ## 11. Esempi di percorso atteso @@ -340,7 +421,10 @@ raggruppano automaticamente tutte le colonne 1A prima di quelle 2B. ### Esempio D: ordine personalizzato della coppia -Il responsabile imposta Non scaff. -> 4P -> 1M. Il terminalino lavora tutte +La prima lista selezionata ha gia' salvato l'ordine 4P -> 1M, mentre la seconda +ha 1M -> 4P. Con due liste il pulsante di personalizzazione e' disabilitato. +Si usa 4P -> 1M per entrambe; Non scaff. rimane fisso in testa. +Il terminalino lavora tutte le UDC richieste dalle due liste in Non scaff., poi quelle in 4P, poi quelle in 1M, applicando dentro ciascun gruppo l'ordine delle celle previsto. Gli eventuali gruppi non configurati vengono accodati, mai esclusi. @@ -400,40 +484,218 @@ Il ripristino delle testate non annulla le movimentazioni fatte durante i test. | Una sola lista | Ordinamento attuale conservato | | Due liste entrambe Area 5 oppure entrambe Area 6 | Abbinamento consentito, applicando il percorso della relativa area | | Una lista Area 5 e una Area 6 | Abbinamento rifiutato senza modificare le prenotazioni esistenti | -| F2 precede F1 nel percorso | All'avvio solo F2 utilizzabile | +| Lista 2 precede Lista 1 nel percorso | F1 avvia direttamente Lista 2, con sfondo giallo | +| Nessuna lista prenotata | F1 mantiene l'accesso ai movimenti liberi | +| Una lista prenotata | F1 mantiene il comportamento monolista | +| Colori IDStato desktop | Stato 1 rosa e stato 2 giallo, uguali al contesto barcode | +| Non scaff. presenti in entrambe le liste | Tutte proposte nella fase iniziale, prima delle celle fisiche | +| Solo Lista 2 contiene Non scaff. | F1 avvia Lista 2 gialla prima delle UDC scaffalate di Lista 1 | +| Personalizzazione con scaffali prioritari | Non scaff. resta comunque in testa, anche con vecchie sequenze salvate | +| Liste con sole Non scaff. | Nessuna attribuzione artificiale di area e nessun conflitto di area | | F1 presente ogni tre colonne | Nessuna colonna intermedia F2 omessa | | Livelli alternati F2/F1/F2 | Tre proposte in ordine fisico, con documenti corretti | | Default area 5 | Serpentina attuale e livelli dall'alto verso il basso, anche all'avvio | | Area 5: F1 in 1A.7.a, F2 in 1A.7.d | Prima F2/d, poi F1/a, senza precedenza fissa a F1 | | Default area 6 | Percorso corrente per scaffale, colonne crescenti e livelli dal basso verso l'alto | | Personalizzazione della coppia | Stesso ordine applicato a entrambe | -| Gruppo presente solo in F2 | Visibile nell'editor e incluso nel percorso | +| Due checkbox selezionati | Pulsante Sequenza di prelievo disabilitato | +| Sequenze salvate diverse | Vale quella della prima selezionata; la seconda non viene modificata | +| Prima lista senza sequenza, seconda personalizzata | Percorso standard per entrambe | +| Il giro inizia dalla Lista 2 | Il riferimento resta la sequenza della Lista 1 | +| Gruppo presente solo in Lista 2 | Incluso nel percorso, accodato se assente dalla sequenza della Lista 1 | | Gruppo omesso dalla personalizzazione | Accodato secondo il comportamento attuale | -| Tasto fisico della lista disabilitata | Nessun cambio documento e nessun movimento | +| F2 durante il giro abbinato | Disabilitato: nessun cambio documento e nessun movimento, anche da tastiera | +| F4 durante il giro abbinato | Salta la UDC corrente senza scaricarla e prosegue nel percorso comune | +| Lista senza piu' residue | IDStato 0, assente dalle prenotabili e consultabile nello storico | +| Lista con sole residue saltate | IDStato 0, ancora visibile e riprenotabile con quelle UDC | +| Skip in entrambe le liste | Entrambe si sprenotano a fine ciclo e restano riprenotabili | +| Nuova prenotazione di liste con skip precedenti | Residue nuovamente proposte, con ubicazioni attuali e percorso previsto | +| Una lista finisce prima dell'altra | Continua l'altra, con ruolo, colore e percorso del giro invariati | +| Non scaff. saltate nel ciclo corrente | Restano residue; esaurite le altre Non scaff. si passa alle scaffalate | +| Pausa PL e successivo ESC | Movimenti liberi separati e rientro nella stessa coppia | | Cambio automatico | Numero lista, colore e UDC aggiornati coerentemente | | UDC con due lotti | Un solo prelievo fisico | | Terza lista disponibile | Mai inserita automaticamente nel giro | | Aggiornamento programma del campo UDC | Non interpretato come nuova lettura | | Movimento fallito o esito incerto | Nessun avanzamento ingiustificato | -I casi relativi a skip, fine parziale, pausa, riavvio e modifiche concorrenti -andranno completati dopo la decisione delle relative regole. +I casi relativi a pausa, riavvio e modifiche concorrenti andranno completati +dopo la decisione delle relative regole. Skip, fine parziale e riprenotazione +devono rispettare i casi confermati sopra. ## 15. Decisioni aperte per la revisione -L'avvio e' chiarito: si rispetta il percorso dell'area, dall'alto in area 5 -e dal basso in area 6. Restano aperti i punti seguenti. +L'avvio e' chiarito: prima tutte le Non scaff., poi il percorso dell'area, +dall'alto in area 5 e dal basso in area 6. Restano aperti i punti seguenti. -1. Assegnazione esplicita dei ruoli Lista 1 e Lista 2 sul desktop. -2. Gestione delle sequenze preesistenti quando si compone una nuova coppia. -3. Ordine fra UDC non scaffalate o con identico valore di percorso. -4. Salti, esaurimento con residui e riprenotazione della coppia o di una lista. +1. Gestione di successive modifiche a una coppia gia' prenotata; l'assegnazione + iniziale e' confermata: ordine dei checkbox e conferma con Prenota. +2. Blocco delle modifiche individuali alla sequenza mentre una coppia e' gia' + in lavorazione, anche tramite un'altra finestra o un altro PC. +3. Criterio di parita' per celle fisiche con identico valore di percorso; + per Non scaff. e' confermato Lista 1, poi Lista 2, ciascuna per codice UDC. +4. Salti, esaurimento con residui e riprenotazione sono confermati in R15; + resta da realizzarne l'integrazione SQL e barcode, non una nuova regola utente. 5. Ripresa dalla pausa e da un riavvio, con ubicazioni eventualmente cambiate. 6. Modifiche alla coppia/sequenza mentre il prelievo e' in corso. -7. Fonte autorevole dell'area di una lista e gestione di liste internamente - miste o con area indeterminata; le coppie Area 5/Area 6 sono vietate (R02a). +7. Gestione delle anomalie di mappatura delle celle fisiche al magazzino; + le Non scaff. sono prive di area, le coppie fisicamente miste 5/6 vietate. 8. Condotta su dati anomali: stessa UDC in due liste o cella fisica con piu' UDC. Il dataset di collaudo evita questi casi; la regola generale resta da definire. +9. Nessuna nuova funzione di interruzione assegnata a F2 in questa fase; + disabilitazione nel giro abbinato confermata. + +### Domande preliminari all'implementazione, 02/10/2026 + +- CONFERMATO: fino a due checkbox seguiti da Prenota, con ruoli assegnati + nell'ordine di selezione. Il solo checkbox consulta, non prenota. +- CONFERMATO: le Non scaff. non appartengono ad alcuna area e precedono sempre + tutte le UDC scaffalate, anche in presenza di personalizzazione. +- CONFERMATO: F2 disabilitato con due liste, conservando F4 Salta UDC e Pausa + PL/ESC. Un futuro F2 Interrompi lista e' fuori ambito. +- CONFERMATO: Non scaff. prima della Lista 1, poi della Lista 2. +- CONFERMATO: con due liste la personalizzazione e' disabilitata e governa + la sequenza della prima selezionata, senza alterare quella della seconda. +- CONFERMATO: ogni lista si sprenota a fine ciclo; solo quelle con residue + saltate restano fra le prenotabili. Una nuova prenotazione riabilita il + prelievo delle residue, singolarmente o in coppia, come nel monolista. + +Le proposte non marcate CONFERMATO restano da approvare e non vanno assunte +come regole definitive nella patch SQL o nel comportamento applicativo. + +## 16. Prima fase: motore isolato (superata dall'integrazione seguente) + +Branch di sviluppo: `codex/doppia-pickinglist`, successivo al freeze +`warehouse-monolista-2.0`. Il tag di ripristino resta invariato. + +Il primo modulo `pickinglist_pair.py` calcola un percorso da un insieme di +UDC residue senza collegarsi al DB, modificare prenotazioni o eseguire movimenti. +Nella prima fase non era collegato alla GUI o al barcode. Il collegamento +e' ora realizzato dai moduli descritti nella sezione 17. +L'ordine fra le Non scaff. e' Lista 1, poi Lista 2, ciascuna per codice UDC. +Fra le sequenze individuali fornite al modulo si usa esclusivamente quella +della prima lista selezionata; in sua assenza si usa il default, anche se +la seconda lista dispone di una personalizzazione. La disabilitazione del +pulsante e' ora integrata nella GUI desktop e protetta anche lato SQL. + +I test in `tests/test_pickinglist_pair.py` verificano precedenza assoluta delle +Non scaff., serpentina area 5, percorso area 6, gruppi comuni, ruoli stabili, +deduplicazione dei lotti, isolamento degli skip e rifiuto di dati incoerenti. +Queste verifiche sono ora affiancate dai test SQL e dei widget. Le risposte possono essere annotate direttamente in questa sezione prima di passare al progetto tecnico e alle modifiche applicative. + +## 17. Integrazione applicativa 2.1.0 + +### Desktop e prenotazione + +Si selezionano fino a due checkbox e si preme Prenota. Una dicitura mostra +l'ordine della selezione: questo ordine, non la data o l'ordinamento della +griglia, determina Lista 1 e Lista 2. Il dettaglio mostra l'ultima selezionata; +una risposta asincrona tardiva dell'altra non deve sostituirlo. +Ricarica conserva entrambi i checkbox ancora presenti e aggiorna i residui. + +Gli IDStato visualizzati sono 1 (rosa #ffe6f2) e 2 (giallo #fff2cc). +Per la coppia sono una proiezione dei ruoli e dei flag Active1/Active2 della +nuova prenotazione, NON un nuovo significato assegnato a Celle.IDStato. +La prenotazione monolista continua a usare PyPickingListReservation. +L'apertura di una coppia rilascia prima l'eventuale prenotazione monolista +Python, nella stessa transazione. Non crea una terza lista implicita. + +Prenota ripetuto sulla stessa coppia non azzera gli skip. Per cambiare coppia +si deve prima sprenotare il giro esistente; non si sostituisce una lista +silenziosamente mentre il terminalino sta lavorando. S-prenota agisce sulle +liste selezionate. La seconda eventualmente ancora attiva resta Lista 2. + +### Percorso, pausa e completamento + +F1 avvia la coppia e propone la prima UDC del percorso comune. F2 e' bloccato +sia sul bottone sia da tastiera. F3 mette in pausa, F4 registra uno skip. +La lettura valida della UDC attesa avvia lo scarico; la conferma resta per +3 secondi e poi viene caricata la successiva. Durante la conferma un secondo +invio non puo' trasformarsi in un movimento libero. + +Le Non scaff. precedono sempre le scaffalate, anche con personalizzazione: +prima Lista 1, poi Lista 2, ciascuna per codice UDC. Nel singolo documento +la stessa precedenza assoluta e' ora applicata anche alla query del barcode. +L'editor permette di riordinare gli scaffali, non la posizione di Non scaff. + +In pausa sono possibili piu' movimenti liberi; non si rientra automaticamente +dopo il primo. ESC rilegge le posizioni dal DB e ripropone la stessa UDC +lasciata, anche se ora e' in altra cella o Non scaff. Solo se quella UDC non +e' piu' pendente passa alla successiva. I controlli e le procedure dei movimenti +liberi restano quelli preesistenti e non ricevono i parametri di movimento bilista. + +Ogni slot senza altre UDC lavorabili viene disattivato. I residui saltati +rimangono nei dati e nella griglia operativa; non sono spediti artificialmente. +Una nuova prenotazione apre un nuovo giro e ripropone quei residui. Gli skip +del vecchio giro restano tracciati ma non vengono applicati al nuovo. +Lo skip viene registrato anche nella tabella Python monolista con priorita' +0: terminata la coppia, F2 non deve aggirare la riprenotazione delle residue. +Prenotare nuovamente una lista singola risolve questi skip, come gia' previsto. +La lista senza alcun residuo scompare dalla gestione e resta consultabile +nello storico. Non viene cambiato lo stato del documento ERP da P a D. + +### Moduli e oggetti SQL + +- pickinglist_pair.py: calcolo puro del percorso e deduplicazione per UDC. +- pickinglist_pair_repository.py: snapshot, prenotazione e rilascio transazionale. +- barcode_pair_service.py: coordinatore bilista sopra il servizio monolista. +- barcode_client.py: proiezione grafica, tasti, timer e protezione anti-autosubmit. +- gestione_pickinglist.py: selezione doppia, ruoli, colori, prenotazione esplicita. +- py_PickingPair: identita' del giro, documenti, slot attivi e audit temporale. +- py_PickingPairSequence: copia della sequenza della prima lista al momento della prenotazione. +- py_PickingPairSkip: UDC saltate per giro/documento, operatore e data. +- py_ViewPickingPairRows: residui aggiornati con ruolo, area, sequenza e skip. +- py_sp_PickingPair: R prenota, K salta, G verifica movimento, F conclude slot, U rilascia. + +La sequenza della seconda lista non viene modificata. Lo snapshot della prima +rimane valido quando la prima termina. Il salvataggio di una sequenza individuale +appartenente a un giro aperto viene bloccato anche da un editor gia' aperto. + +Prenotazioni, rilasci, skip e movimenti bilista condividono un application lock +SQL di transazione. La verifica G, il movimento legacy, il controllo della +posizione finale 9999 e la chiusura F sono nella stessa transazione del client. +Un errore propaga al rollback. @RC del movimento legacy e' l'identita' del +movimento inserito, non un codice zero-successo: la verifica usa la giacenza. +Il caricamento della coda non attiva il recupero degli errori di scrittura. + +Il ramo bilista non modifica definizioni C# ne' scrive documenti SAM. +I movimenti WMS restano necessariamente sugli stessi dati condivisi: non +usare il C# per lavorare contemporaneamente le medesime UDC del giro di prova. + +### Protezioni e limiti di questa fase + +Area fisica ricavata da Celle -> Aree -> Magazzini, MDE5/MDE6. Non scaff. +non ha area. Area sconosciuta, aree miste, stessa UDC in due documenti o +posizioni discordanti bloccano il giro invece di omettere righe. +Piu' lotti della stessa UDC nella stessa posizione contano come una UDC. +A parita' di ordinamento fisico si usa il codice UDC e poi il ruolo. + +Un altro giro non viene adottato silenziosamente da un terminalino ancora +legato al precedente. In tal caso verificare la prenotazione e riavviare il +terminalino. Dopo un riavvio si ricalcola il percorso dai residui e dagli skip +persistiti; la proposta lasciata in pausa e' mantenuta solo nella sessione +in memoria, non come cursore durevole. + +Il ramo storico sorgente conserva il filtro all'anno corrente. Un giro aperto +nell'anno precedente e' bloccato esplicitamente: non si considera concluso +solo perche' i documenti sono usciti dal filtro annuale. Va verificato e +sprenotato dal desktop. Il superamento di questo limite richiede un intervento +separato sul modello temporale dei documenti, non incluso qui. + +### Installazione, rollback e prove + +Vedere INSTALLAZIONE_BILISTA_2.1.md. La patch specifica e' incorporata anche +in apply_online_python_wms_full_patch.sql. Non e' necessario eseguirle entrambe. +Il freeze warehouse-monolista-2.0 resta intatto; non e' stato pubblicato un +nuovo tag di produzione per questa versione in collaudo. + +Eseguiti test automatici del motore, del servizio e dei widget Tk, compresi +regressioni monolista, sei caratteri, colori, tasti, conferma e risposta tardiva +del dettaglio. Il test SQL esplicito usa le liste locali 233/244, verifica +prenotazione ripetuta, pausa, un movimento reale, skip, completamento parziale, +rilascio e riprenotazione. Tutti i suoi cambiamenti sono annullati con rollback. +Compilata anche la patch cumulativa completa (30 batch) in rollback. +Queste prove non sostituiscono il test con scanner reale e operatore. diff --git a/tests/test_barcode_pair_service.py b/tests/test_barcode_pair_service.py new file mode 100644 index 0000000..30d3efa --- /dev/null +++ b/tests/test_barcode_pair_service.py @@ -0,0 +1,143 @@ +"""Paired workflow regressions, without a database or real movements.""" + +import unittest +from unittest.mock import AsyncMock, patch + +from barcode_pair_service import BarcodePairService +from barcode_service import BarcodeActionResult, BarcodeService, BarcodeViewState +from pickinglist_pair_repository import PairSnapshot +from test_barcode_document_binding import PickingRepositoryFake + + +def snapshot(rows=None, *, active=("173", "172"), run="run-1"): + rows = rows if rows is not None else [ + dict(SlotDocument="173", Pallet="600001", Cella=1101, Ordinamento=20), + dict(SlotDocument="172", Pallet="600002", Cella=1102, Ordinamento=10), + ] + return PairSnapshot(run, ("173", "172"), frozenset(active), tuple( + dict(OperationalArea=5, GroupKey="A", StatoDocumento="P", IsSkipped=False, + SequenceOrder=None, Ubicazione=f"A - {r['Cella']}", **r) for r in rows)) + + +class PairServiceTests(unittest.IsolatedAsyncioTestCase): + def setUp(self): + self.repo = PickingRepositoryFake() + self.pairs = AsyncMock() + self.pairs.snapshot.return_value = snapshot() + self.service = BarcodePairService(self.repo, 1, self.pairs) + logger = patch("barcode_service.log_runtime_event") + logger.start() + self.addCleanup(logger.stop) + + async def test_f1_can_start_second_slot_and_f2_never_advances(self): + result = await self.service.start_priority_queue(1) + self.assertEqual((result.state.pair_slot, result.state.pair_document), (2, "172")) + self.assertEqual(result.state.expected_pallet, "600002") + self.pairs.command.reset_mock() + blocked = await self.service.start_priority_queue(0) + self.assertFalse(blocked.ok) + self.pairs.command.assert_not_awaited() + self.assertIs(blocked.state, result.state) + + async def test_success_keeps_slot_and_three_second_timer(self): + await self.service.start_priority_queue(1) + self.repo.execute_legacy_move = AsyncMock(wraps=self.repo.execute_legacy_move) + result = await self.service.submit(scanned_pallet="600002", destination_barcode="9000000") + self.assertTrue(result.ok) + self.assertEqual(result.state.pair_document, "172") + self.assertEqual(result.state.pair_slot, 2) + self.assertEqual(result.state.auto_advance_delay_ms, 3000) + self.assertTrue(result.state.destination_readonly) + kwargs = self.repo.execute_legacy_move.call_args.kwargs + self.assertEqual((kwargs["pair_run_id"], kwargs["pair_document"]), ("run-1", "172")) + + async def test_wrong_scan_does_not_move_or_advance(self): + await self.service.start_priority_queue(1) + self.repo.execute_legacy_move = AsyncMock() + result = await self.service.submit(scanned_pallet="600001", destination_barcode="9000000") + self.assertFalse(result.ok) + self.repo.execute_legacy_move.assert_not_awaited() + self.assertEqual(result.state.auto_advance_delay_ms, 0) + + async def test_duplicate_submit_during_confirmation_cannot_become_free_move(self): + await self.service.start_priority_queue(1) + self.repo.execute_legacy_move = AsyncMock(wraps=self.repo.execute_legacy_move) + await self.service.submit(scanned_pallet="600002", destination_barcode="9000000") + again = await self.service.submit(scanned_pallet="600002", destination_barcode="9000000") + self.assertFalse(again.ok) + self.assertEqual(self.repo.execute_legacy_move.await_count, 1) + + async def test_pause_multiple_free_moves_and_resume_same_pallet_with_new_location(self): + await self.service.start_priority_queue(1) + saved = self.service.state + self.service.begin_priority_pause(1) + self.repo.execute_legacy_move = AsyncMock(wraps=self.repo.execute_legacy_move) + for _ in range(2): + result = await self.service.submit(scanned_pallet="600003", destination_barcode="9001000") + self.assertTrue(result.ok) + self.assertEqual(result.state.queue_label, "Pausa PL") + self.assertEqual(result.state.auto_advance_delay_ms, 0) + self.assertEqual(result.state.mode, "manual_unload") + self.assertFalse(result.state.destination_readonly) + self.assertEqual(result.state.scanned_pallet, "") + self.assertNotIn("pair_run_id", self.repo.execute_legacy_move.call_args.kwargs) + self.pairs.snapshot.return_value = snapshot([ + dict(SlotDocument="173", Pallet="600001", Cella=1101, Ordinamento=1), + dict(SlotDocument="172", Pallet="600002", Cella=4004, Ordinamento=100), + ]) + result = await self.service.resume_pair(saved) + self.assertEqual(result.state.expected_pallet, "600002") + self.assertIn("4004", result.state.source_location) + self.assertEqual(result.state.pair_slot, 2) + + async def test_free_f4_keeps_pause_context(self): + await self.service.start_priority_queue(1) + self.service.begin_priority_pause(1) + result = BarcodeActionResult(True, BarcodeViewState(mode="confirm")) + with patch.object(BarcodeService, "submit_unload_with_source_check", new=AsyncMock(return_value=result)): + done = await self.service.submit_unload_with_source_check(scanned_pallet="600001", source_barcode="9001101") + self.assertEqual(done.state.queue_label, "Pausa PL") + self.assertEqual(done.state.pair_document, "172") + + async def test_skip_uses_run_and_document_without_moving(self): + await self.service.start_priority_queue(1) + self.repo.execute_legacy_move = AsyncMock() + await self.service.skip_current_picking_pallet() + self.pairs.command.assert_awaited_with("K", 1, run_id="run-1", document="172", pallet="600002") + self.repo.execute_legacy_move.assert_not_awaited() + + async def test_finished_first_slot_never_renumbers_second(self): + self.pairs.snapshot.return_value = snapshot(active=("172",)) + result = await self.service.start_priority_queue(1) + self.assertEqual(result.state.pair_slot, 2) + + async def test_pair_end_never_loads_a_third_document(self): + await self.service.start_priority_queue(1) + self.pairs.snapshot.return_value = None + self.repo.fetch_next_picking = AsyncMock() + result = await self.service.start_priority_queue(1) + self.assertEqual(result.state.mode, "manual_unload") + self.assertFalse(self.service.pair_active) + self.repo.fetch_next_picking.assert_not_awaited() + + async def test_external_replacement_is_rejected(self): + await self.service.start_priority_queue(1) + self.pairs.snapshot.return_value = snapshot(run="another-run") + with self.assertRaisesRegex(RuntimeError, "Prenotazione cambiata"): + await self.service.start_priority_queue(1) + + async def test_query_failure_on_resume_preserves_pause(self): + await self.service.start_priority_queue(1) + saved = self.service.state + self.service.begin_priority_pause(1) + self.pairs.snapshot.side_effect = TimeoutError + with self.assertRaises(TimeoutError): + await self.service.resume_pair(saved) + self.assertTrue(self.service._pair_paused) + self.assertEqual(self.service.state.queue_label, "Pausa PL") + + async def test_no_pair_delegates_to_unchanged_monolist(self): + self.pairs.snapshot.return_value = None + result = await self.service.start_priority_queue(1) + self.assertEqual(result.state.document, "173") + self.assertFalse(result.state.pair_run_id) diff --git a/tests/test_pair_gui.py b/tests/test_pair_gui.py new file mode 100644 index 0000000..795a705 --- /dev/null +++ b/tests/test_pair_gui.py @@ -0,0 +1,154 @@ +"""Widget-level regressions. No database connection and no actual movement.""" + +import asyncio +from types import SimpleNamespace +import tkinter as tk +import unittest +from unittest.mock import AsyncMock, Mock, patch + +import customtkinter as ctk +from barcode_client import BarcodeClientApp +from barcode_service import BarcodeViewState +from gestione_pickinglist import GestionePickingListFrame +from pickinglist_pair import PAIR_SLOT_COLORS + + +class BarcodePairGuiTests(unittest.TestCase): + def setUp(self): + self.root = tk.Tk() + self.root.withdraw() + self.loop = asyncio.new_event_loop() + self.app = BarcodeClientApp(self.root, Mock(), SimpleNamespace(operator_id=1), self.loop) + self.app.service._pair = Mock() + + def tearDown(self): + for timer in self.root.tk.call("after", "info"): + self.root.after_cancel(timer) + self.root.destroy() + self.loop.close() + + def proposal(self, slot=2): + state = BarcodeViewState(mode="priority_high", pair_slot=slot, pair_run_id="run", + pair_document=str(slot), queue_label=f"Lista {slot}", expected_pallet="600001", + destination_barcode="9000000", destination_readonly=True) + self.app.service._state = state + self.app._apply_state(state) + return state + + def test_colors_and_disabled_f2(self): + for slot in (1, 2): + self.proposal(slot) + self.assertEqual(self.root.cget("bg"), PAIR_SLOT_COLORS[slot]) + self.assertEqual(str(self.app.btn_f2.cget("state")), "disabled") + self.assertEqual(str(self.app.destination_entry.cget("state")), "readonly") + with patch.object(self.app, "_run_async") as run: + self.app._start_queue(0) + run.assert_not_called() + + def test_programmatic_scan_never_submits_but_six_user_characters_do(self): + self.proposal() + with patch.object(self.app, "_submit") as submit: + self.app.scanned_var.set("600001") + self.app._auto_focus_destination_after_scan() + submit.assert_not_called() + self.app.scanned_var.set("") + for value in ("6", "60", "600", "6000", "60000", "600001"): + self.app._on_pallet_keypress() + self.app.scanned_var.set(value) + self.app._auto_focus_destination_after_scan() + submit.assert_called_once() + + def test_confirmation_has_timer_and_no_second_movement(self): + state = self.proposal() + state.mode = "confirm" + state.auto_advance_delay_ms = 3000 + self.app._apply_state(state) + self.assertIsNotNone(self.app._auto_advance_id) + self.assertIn("3 secondi", self.app.info1_var.get()) + with patch.object(self.app, "_run_async") as run: + self.app._submit() + self.app._begin_manual_unload() + run.assert_not_called() + + def test_pause_keeps_destination_editable_until_escape(self): + self.proposal() + self.app.service._pair.documents = ("1", "2") + self.app.service._pair.run_id = "run" + self.app._on_f3() + self.assertEqual(str(self.app.destination_entry.cget("state")), "normal") + self.assertEqual(str(self.app.btn_f1.cget("state")), "disabled") + state = BarcodeViewState(mode="confirm", queue_label="Pausa PL", destination_barcode="9001000") + self.app._apply_state(state) + self.assertEqual(str(self.app.destination_entry.cget("state")), "normal") + self.assertIsNone(self.app._auto_advance_id) + with patch.object(self.app, "_run_async") as run: + self.app._on_escape_key() + run.assert_called_once() + + +class DeferredRunner: + def __init__(self, *_args): + self.jobs = [] + + def run(self, coroutine, **callbacks): + coroutine.close() + self.jobs.append(callbacks) + + +class DesktopPairGuiTests(unittest.TestCase): + def setUp(self): + self.root = ctk.CTk() + self.root.withdraw() + self.runner_patch = patch("gestione_pickinglist.AsyncRunner", DeferredRunner) + self.runner_patch.start() + self.frame = GestionePickingListFrame(self.root, db_client=Mock()) + self.rows = [dict(Documento=d, IDStato=0) for d in (233, 244, 240)] + self.frame._refresh_mid_rows(self.rows) + + def tearDown(self): + self.frame.destroy() + for timer in self.root.tk.call("after", "info"): + self.root.after_cancel(timer) + self.root.destroy() + self.runner_patch.stop() + + def select(self, index): + row = self.frame.rows_models[index] + row.set_checked(True) + self.frame.on_row_checked(row, True) + + def test_two_checkboxes_keep_click_order_and_disable_sequence(self): + self.select(1) + self.select(0) + self.assertEqual(self.frame._selection_order, ["244", "233"]) + self.assertEqual(self.frame.sequence_button.cget("state"), "disabled") + with patch("gestione_pickinglist.messagebox.showinfo"): + self.select(2) + self.assertFalse(self.frame.rows_models[2].is_checked()) + self.assertEqual(self.frame._selection_order, ["244", "233"]) + + def test_late_detail_result_does_not_replace_current_document(self): + self.select(0) + first_job = self.frame.runner.jobs[-1] + self.select(1) + second_job = self.frame.runner.jobs[-1] + with patch.object(self.frame, "_refresh_details_incremental") as render: + first_job["on_success"]({"rows": [{"Pallet": "600001"}]}) + render.assert_not_called() + second_job["on_success"]({"rows": [{"Pallet": "600002"}]}) + render.assert_called_once() + self.assertEqual(self.frame.detail_doc, "244") + self.assertEqual(self.frame._detail_cache[self.frame.detail_doc][0]["Pallet"], "600002") + + def test_reload_keeps_both_checkboxes_and_roles(self): + self.select(1) + self.select(0) + self.frame.reload_from_db() + reload_job = self.frame.runner.jobs[-1] + reload_job["on_success"]({"rows": [dict(Documento=233, IDStato=2), dict(Documento=244, IDStato=1)], + "pair_documents": ["244", "233"]}) + self.root.update_idletasks() + self.assertEqual(self.frame._selection_order, ["244", "233"]) + self.assertTrue(all(r.is_checked() for r in self.frame.rows_models)) + self.assertEqual(self.frame.detail_doc, "233") + self.assertEqual(self.frame.sequence_button.cget("state"), "disabled") diff --git a/tests/test_pickinglist_pair.py b/tests/test_pickinglist_pair.py new file mode 100644 index 0000000..d77cc14 --- /dev/null +++ b/tests/test_pickinglist_pair.py @@ -0,0 +1,161 @@ +"""Paired-route requirements, without a GUI or database connection.""" + +from dataclasses import replace +import unittest + +from pickinglist_pair import PickingCandidate, PairRoutingError, build_pair_route + + +def udc(doc, pallet, order, *, cell=1101, area=5, group="1A"): + return PickingCandidate(doc, pallet, cell, area, order, group) + + +class PairRouteTests(unittest.TestCase): + def route(self, rows, **kwargs): + return build_pair_route(rows, documents=("173", "172"), + **kwargs) + + def test_non_shelved_from_both_documents_precede_every_rack(self): + rows = [udc("173", "600001", 1001), + udc("172", "600002", 99999, cell=1000, area=6), + udc("173", "600003", 99999, cell=1000, area=None)] + route = self.route(rows, document_sequences={"173": ("1A", "NON_SCAFF")}) + self.assertEqual([r.pallet for r in route.pending], ["600003", "600002", "600001"]) + self.assertEqual(route.area, 5) + + def test_only_non_shelved_has_no_area(self): + route = self.route([udc("172", "600001", 99999, cell=1000, area=None)]) + self.assertIsNone(route.area) + self.assertEqual(route.slot_for(route.pending[0].document), 2) + + def test_second_slot_can_start_and_keeps_its_identity(self): + route = self.route([udc("173", "600001", 1005), udc("172", "600002", 1001, cell=1105)]) + self.assertEqual(route.pending[0].document, "172") + self.assertEqual(route.slot_for("172"), 2) + self.assertEqual(route.slot_for("173"), 1) + + def test_area5_serpentine_and_top_down_are_not_replaced_by_slot_order(self): + # Legacy order: 1A.1.e, 1A.1.a, 2B.1.e, 2B.2.e, 1A.2.e. + rows = [udc("173", "600005", 1019), udc("172", "600004", 1013, group="2B"), + udc("173", "600003", 1007, group="2B"), + udc("173", "600002", 1005), udc("172", "600001", 1001)] + route = self.route(rows) + self.assertEqual([r.cell_order for r in route.pending], [1001, 1005, 1007, 1013, 1019]) + + def test_area6_visits_columns_missing_from_first_list(self): + rows = [udc("173", "600006", 5026, area=6, group="1M"), + udc("172", "600002", 5006, area=6, group="1M"), + udc("173", "600003", 5011, area=6, group="1M"), + udc("172", "600001", 5001, area=6, group="1M"), + udc("172", "600004", 5012, area=6, group="1M"), + udc("172", "600005", 5021, area=6, group="1M")] + self.assertEqual([r.pallet for r in self.route(rows).pending], + ["600001", "600002", "600003", "600004", "600005", "600006"]) + + def test_custom_rack_order_is_common_and_unconfigured_racks_remain(self): + rows = [udc("173", "600001", 1001), udc("172", "600002", 1007, group="2B"), + udc("173", "600003", 1008, group="2B"), + udc("172", "600004", 2001, group="3C")] + self.assertEqual([r.pallet for r in self.route(rows, document_sequences={"173": ("2B",)}).pending], + ["600002", "600003", "600001", "600004"]) + + def test_lot_duplicates_are_one_udc(self): + row = udc("173", "600001", 1001) + self.assertEqual(self.route([row, row]).pending, (row,)) + + def test_skip_remains_residual_and_does_not_modify_input(self): + first = udc("173", "600001", 1001) + second = udc("172", "600002", 1002) + rows = [first, second] + route = self.route(rows, skipped=(("173", "600001"),)) + self.assertEqual(route.pending, (second,)) + self.assertEqual(route.skipped, (first,)) + self.assertEqual(rows, [first, second]) + self.assertEqual(self.route(rows).pending, (first, second)) + + def test_all_skipped_is_not_an_empty_residual_list(self): + row = udc("173", "600001", 1001) + route = self.route([row], skipped=(("173", "600001"),)) + self.assertEqual(route.pending, ()) + self.assertEqual(route.skipped, (row,)) + + def test_mixed_areas_rejected_even_if_conflicting_udc_is_skipped(self): + rows = [udc("173", "600001", 1001), udc("172", "600002", 5001, area=6)] + with self.assertRaisesRegex(PairRoutingError, "stessa area"): + self.route(rows, skipped=(("172", "600002"),)) + + def test_physical_unknown_area_is_not_treated_as_non_shelved(self): + with self.assertRaisesRegex(PairRoutingError, "non riconosciuta"): + self.route([udc("173", "600001", 1001, area=None)]) + + def test_shipped_rows_are_not_proposed_or_used_for_area_check(self): + self.assertEqual(self.route([udc("173", "600001", 0, cell=9999, area=None)]).pending, ()) + + def test_third_document_is_rejected(self): + with self.assertRaisesRegex(PairRoutingError, "estraneo"): + self.route([udc("171", "600001", 1001)]) + + def test_udc_in_two_documents_is_rejected(self): + row = udc("173", "600001", 1001) + with self.assertRaisesRegex(PairRoutingError, "entrambe"): + self.route([row, replace(row, document="172")]) + + def test_conflicting_locations_are_rejected(self): + row = udc("173", "600001", 1001) + with self.assertRaisesRegex(PairRoutingError, "discordante"): + self.route([row, replace(row, cell_id=1102)]) + + def test_duplicate_documents_or_groups_are_rejected(self): + with self.assertRaises(PairRoutingError): + build_pair_route([], documents=("173", "173")) + with self.assertRaises(PairRoutingError): + self.route([], document_sequences={"173": ("1A", "1A")}) + + def test_updated_snapshot_uses_updated_position_without_retaining_old_cursor(self): + first = udc("173", "600001", 1001) + second = udc("172", "600002", 1002) + self.assertEqual(self.route([first, second]).pending[0], first) + moved = replace(second, cell_id=1000, area=None, cell_order=99999) + self.assertEqual(self.route([first, moved]).pending[0], moved) + + def test_non_shelved_first_slot_then_second_and_pallet_order_within_slot(self): + rows = [udc("173", "600002", 99999, cell=1000), udc("172", "600001", 99999, cell=1000)] + rows.append(udc("173", "600003", 99999, cell=1000)) + self.assertEqual([r.pallet for r in self.route(reversed(rows)).pending], + ["600002", "600003", "600001"]) + + def test_first_selected_sequence_wins_even_when_second_document_starts(self): + sequences = {"173": ("2B", "1A"), "172": ("1A", "2B")} + rows = [udc("173", "600001", 1001), + udc("172", "600002", 1007, group="2B")] + route = self.route(rows, document_sequences=sequences) + self.assertEqual([r.pallet for r in route.pending], ["600002", "600001"]) + self.assertEqual(route.slot_for(route.pending[0].document), 2) + self.assertEqual(sequences, {"173": ("2B", "1A"), "172": ("1A", "2B")}) + + def test_missing_first_custom_sequence_means_default_not_second_sequence(self): + rows = [udc("173", "600001", 1001), + udc("172", "600002", 1007, group="2B")] + for first in ({}, {"173": ()}): + with self.subTest(first=first): + route = self.route(rows, document_sequences={**first, "172": ("2B", "1A")}) + self.assertEqual([r.pallet for r in route.pending], ["600001", "600002"]) + + def test_first_sequence_still_governs_when_only_second_has_residuals(self): + rows = [udc("172", "600001", 1001), + udc("172", "600002", 1007, group="2B")] + route = self.route(rows, document_sequences={"173": ("2B", "1A"), "172": ("1A", "2B")}) + self.assertEqual([r.pallet for r in route.pending], ["600002", "600001"]) + self.assertEqual(route.slot_for("172"), 2) + + def test_selection_order_not_document_number_chooses_sequence(self): + rows = [udc("173", "600001", 1001), + udc("172", "600002", 1007, group="2B")] + route = build_pair_route(rows, documents=("172", "173"), + document_sequences={"173": ("2B", "1A"), "172": ("1A", "2B")}) + self.assertEqual([r.pallet for r in route.pending], ["600001", "600002"]) + self.assertEqual(route.slot_for("173"), 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/validate_picking_pair_sql.py b/tests/validate_picking_pair_sql.py new file mode 100644 index 0000000..20e1177 --- /dev/null +++ b/tests/validate_picking_pair_sql.py @@ -0,0 +1,133 @@ +"""Explicit LOCAL integration test. Installs patch and exercises SQL, then rolls back. + +Run from the repository root: python tests/validate_picking_pair_sql.py +Requires the restored test lists 233 and 244 on HOMESERVER/Mediseawall. +Never commits: reservations, skips and one real legacy movement are rolled back. +Do not run concurrently with operators on this development database. +""" + +import asyncio +from pathlib import Path +import re +import sys + +import pyodbc + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +from db_config import load_db_config +from barcode_repository import BarcodeRepository +from barcode_pair_service import BarcodePairService +from pickinglist_pair_repository import PickingPairRepository + + +class TransactionClient: + """Same SQL and parameters as production, but all calls share one rollback.""" + + def __init__(self, connection): + self.connection = connection + + async def query_json(self, sql, params=None, *, commit=False): + params = params or {} + args = [] + + def parameter(match): + args.append(params[match.group(1)]) + return "?" + + sql = re.sub(r":([a-zA-Z_]\w*)", parameter, sql) + cursor = self.connection.cursor() + try: + cursor.execute(sql, *args) + rows = [] + columns = [] + while True: + if cursor.description: + columns = [c[0] for c in cursor.description] + rows = [list(r) for r in cursor.fetchall()] + if not cursor.nextset(): + break + return {"columns": columns, "rows": rows} + finally: + cursor.close() + + +async def exercise(connection): + client = TransactionClient(connection) + pair_repo = PickingPairRepository(client) + assert await pair_repo.snapshot() is None, "Un giro e gia aperto: test annullato." + await pair_repo.command("R", 1, documents=("233", "244")) + initial = await pair_repo.snapshot() + route = initial.route() + print("Route:", len(route.pending), "UDC; area", route.area) + assert route.pending and route.pending[0].cell_id == 1000 + await pair_repo.command("R", 1, documents=("233", "244")) + assert (await pair_repo.snapshot()).run_id == initial.run_id + + service = BarcodePairService(BarcodeRepository(client), 1, pair_repo) + proposed = await service.start_priority_queue(1) + saved = proposed.state + service.begin_priority_pause(1) + resumed = await service.resume_pair(saved) + assert resumed.state.expected_pallet == saved.expected_pallet + shipped_pallet = resumed.state.expected_pallet + shipped = await service.submit(scanned_pallet=shipped_pallet, destination_barcode="9000000") + assert shipped.ok, shipped.message + assert shipped.state.auto_advance_delay_ms == 3000 + current = await service.repository.fetch_current_location_by_pallet(shipped_pallet) + assert int(current["IDCella"]) == 9999 + print("Movement verified inside rollback:", shipped_pallet) + after_move = await pair_repo.snapshot() + assert shipped_pallet not in {c.pallet for c in after_move.route().pending} + + # Skip all residuals of role 1. Role 2 must retain its identity and route. + first_residuals = [c for c in after_move.route().pending if c.document == "233"] + for candidate in first_residuals: + await pair_repo.command("K", 1, run_id=initial.run_id, document="233", pallet=candidate.pallet) + await pair_repo.command("F", 1, run_id=initial.run_id) + one_left = await pair_repo.snapshot() + assert one_left.active == frozenset({"244"}) + assert len(one_left.route().pending) > 0 + next_item = await service.start_priority_queue(1) + assert next_item.state.pair_slot == 2 + # Residuals are still in the operative view, not marked shipped. + count = await client.query_json("SELECT COUNT(DISTINCT Pallet) AS N FROM dbo.py_ViewPackingListRestante WHERE Documento=233") + assert count["rows"][0][0] == len(first_residuals) + await pair_repo.release_selected(["244"], 1) + assert await pair_repo.snapshot() is None + assert await service.repository.fetch_next_picking(0, documento="233") is None + await pair_repo.command("R", 1, documents=("233", "244")) + restarted = await pair_repo.snapshot() + assert restarted.run_id != initial.run_id + assert any(c.document == "233" for c in restarted.route().pending) + assert not restarted.route().skipped + await pair_repo.release_selected(["233", "244"], 1) + await pair_repo.reserve_single("233", 1) + assert await pair_repo.snapshot() is None + await pair_repo.release_selected(["233"], 1) + print("SQL integration passed: reserve, idempotence, pause, move, skip, release, re-reserve, monolist") + + +def main(): + c = load_db_config() + connection = pyodbc.connect( + "DRIVER={" + c["driver"] + "};SERVER=" + c["server"] + ";DATABASE=" + c["database"] + + ";UID=" + c["user"] + ";PWD=" + c["password"] + ";TrustServerCertificate=yes;", timeout=10) + try: + cursor = connection.cursor() + identity = cursor.execute("SELECT @@SERVERNAME,DB_NAME()").fetchone() + assert tuple(identity) == ("HOMESERVER", "Mediseawall"), "Database non autorizzato per questo test" + for batch in re.split(r"^\s*GO\s*$", (ROOT / "apply_pickinglist_pair_patch.sql").read_text(), flags=re.M | re.I): + if batch.strip(): + cursor.execute(batch) + while cursor.nextset(): + pass + asyncio.run(exercise(connection)) + finally: + connection.rollback() + connection.close() + print("ROLLBACK completed: no persistent movement or reservation") + + +if __name__ == "__main__": + main() diff --git a/version_info.py b/version_info.py index 43e4b3b..cc48157 100644 --- a/version_info.py +++ b/version_info.py @@ -13,20 +13,23 @@ MODULE_VERSIONS: dict[str, str] = { "async_msssql_query": "1.0.1", "audit_log": "1.0.0", "main": "1.0.2", - "barcode_client": "1.0.27", - "barcode_repository": "1.0.14", - "barcode_service": "1.0.25", + "barcode_client": "2.1.0", + "barcode_repository": "2.1.0", + "barcode_service": "2.1.0", + "barcode_pair_service": "2.1.0", "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_pickinglist": "2.1.0", "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", + "pickinglist_sequence": "2.1.0", + "pickinglist_pair": "2.1.0", + "pickinglist_pair_repository": "2.1.0", "reset_corsie": "1.0.0", "runtime_support": "1.0.1", "search_pallets": "1.0.0",