Compare commits
2 Commits
codex/dopp
...
d3941e88cc
| Author | SHA1 | Date | |
|---|---|---|---|
| d3941e88cc | |||
| 04406e840d |
@@ -1,97 +0,0 @@
|
|||||||
# 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.
|
|
||||||
104
INSTALLAZIONE_MONOLISTA_INVENTARIO.md
Normal file
104
INSTALLAZIONE_MONOLISTA_INVENTARIO.md
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
# Aggiornamento reparto: monolista con Inventario
|
||||||
|
|
||||||
|
Release: `warehouse-monolista-2.0.1-inventario`, ramo di distribuzione `main`.
|
||||||
|
La bilista rimane separata su `codex/doppia-pickinglist` e non e' inclusa.
|
||||||
|
Modulo Inventario 1.1.0, launcher 1.0.3. Barcode e logica picking monolista
|
||||||
|
invariati rispetto al freeze `warehouse-monolista-2.0`.
|
||||||
|
|
||||||
|
## Prima dell'aggiornamento
|
||||||
|
|
||||||
|
Chiudere backoffice e terminalini Python che usano il database.
|
||||||
|
Conservare una copia della cartella installata, in particolare dei file locali
|
||||||
|
di configurazione e dei log utili. Non pubblicare db_connection.json su Git.
|
||||||
|
Se si aggiorna il DB, eseguire prima un backup e conservarne il ripristino.
|
||||||
|
|
||||||
|
## Aggiornare il programma con Git
|
||||||
|
|
||||||
|
Dal prompt nella cartella di installazione (esempio C:\flywms):
|
||||||
|
|
||||||
|
```bat
|
||||||
|
cd /d C:\flywms
|
||||||
|
git status --short
|
||||||
|
git rev-parse HEAD
|
||||||
|
git fetch origin --tags
|
||||||
|
git switch main
|
||||||
|
git pull --ff-only origin main
|
||||||
|
python -m pip install -r requirements.txt
|
||||||
|
git log -1 --oneline
|
||||||
|
git describe --tags --exact-match HEAD
|
||||||
|
```
|
||||||
|
|
||||||
|
Annotare il vecchio commit prima dell'aggiornamento. Se Git segnala modifiche
|
||||||
|
locali o una divergenza, fermarsi: NON usare reset --hard, clean o push --force.
|
||||||
|
I file locali non tracciati, come la configurazione DB, non devono essere eliminati.
|
||||||
|
Verificare che la connessione rimanga quella del reparto, non del PC di sviluppo.
|
||||||
|
|
||||||
|
Il tag identifica questa pubblicazione; se in futuro main avanza, il comando
|
||||||
|
describe potra' mostrare un'altra release. Per scegliere esattamente questa:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
git switch --detach warehouse-monolista-2.0.1-inventario
|
||||||
|
```
|
||||||
|
|
||||||
|
Per riprendere in seguito gli aggiornamenti normali: git switch main, poi
|
||||||
|
git pull --ff-only origin main.
|
||||||
|
|
||||||
|
## Script SQL da usare
|
||||||
|
|
||||||
|
Il cumulativo MONOLISTA e' `apply_online_python_wms_full_patch.sql`, ottenuto
|
||||||
|
dal ramo main/tag di questa release. Aprirlo in SSMS, selezionare esplicitamente
|
||||||
|
il database Mediseawall e lanciarlo dopo backup, con client Python chiusi.
|
||||||
|
Controllare tutti i messaggi di errore: lo script usa piu' batch GO e non e'
|
||||||
|
una singola transazione atomica; il solo PRINT finale non certifica il successo.
|
||||||
|
|
||||||
|
Sono gia' inclusi:
|
||||||
|
- oggetti Python di prenotazione e viste picking residue;
|
||||||
|
- oggetti per storico picking e salti UDC;
|
||||||
|
- filtro operativo massimo 30 giorni, selezionabile nella UI a 10/15/20/30;
|
||||||
|
- LEFT JOIN per le destinazioni senza nazione;
|
||||||
|
- tabella py_PickingListPrelievoSequenza e vista py_ViewPackingListPrelievo;
|
||||||
|
- ordine di default con non scaffalate prima degli scaffali e sequenza
|
||||||
|
personalizzata per documento, che nella monolista prevale sul default.
|
||||||
|
|
||||||
|
Se si applica il cumulativo non occorre ripetere separatamente le patch
|
||||||
|
days_filter, optional_destination_country e sequence. I singoli script e i
|
||||||
|
rollback gia' presenti rimangono nel repository per interventi mirati:
|
||||||
|
non eseguirli tutti indiscriminatamente e non usarli come rollback cumulativo.
|
||||||
|
|
||||||
|
ATTENZIONE: nel ramo BILISTA il file cumulativo ha lo stesso nome ma comprende
|
||||||
|
anche oggetti py_PickingPair. Non prelevarlo da quella cartella/ramo per questa
|
||||||
|
installazione. Questa pubblicazione non esegue alcuno script sul DB online.
|
||||||
|
|
||||||
|
## Inventario: nessuna nuova patch DB
|
||||||
|
|
||||||
|
Se il DB ha gia' tutte le patch monolista sopra elencate, per aggiungere
|
||||||
|
l'inventario non serve rilanciare il cumulativo: gli script SQL sono invariati
|
||||||
|
rispetto al freeze monolista 2.0.
|
||||||
|
|
||||||
|
`inventory_report.sql` DEVE rimanere accanto a inventory_service.py, ma NON va
|
||||||
|
incollato in SSMS: e' la query parametrizzata eseguita dal programma.
|
||||||
|
L'utente DB deve poter leggere le sorgenti WMS e SAMA1, incluso EXTTACLOTSER.
|
||||||
|
Non vengono create tabelle persistenti per l'inventario.
|
||||||
|
|
||||||
|
Avviare il programma come di consueto, aprire Inventario, scegliere la data,
|
||||||
|
eseguire il calcolo e provare l'export. Una seconda pressione di Inventario
|
||||||
|
deve riportare la stessa finestra in primo piano. Nessuna query parte
|
||||||
|
automaticamente all'apertura della finestra.
|
||||||
|
|
||||||
|
Prima dell'inventario ufficiale validare etichette e stampa SAM su un campione,
|
||||||
|
con movimentazioni ferme e dati ERP/WMS coerenti. Il perimetro provvisorio e'
|
||||||
|
guidato dai prodotti/lotti WMS; le limitazioni sono in specifica_inventario.md.
|
||||||
|
|
||||||
|
## Ritorno alla precedente monolista
|
||||||
|
|
||||||
|
Con programmi chiusi e senza modifiche locali ai sorgenti:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
git switch --detach warehouse-monolista-2.0
|
||||||
|
```
|
||||||
|
|
||||||
|
Oppure usare il commit precedente annotato, se il PC partiva da un'altra
|
||||||
|
versione. Il nuovo inventario non modifica lo schema o i dati persistenti,
|
||||||
|
quindi il suo solo aggiornamento non richiede rollback SQL. Se sono state
|
||||||
|
applicate anche patch mancanti di versioni precedenti, valutarne separatamente
|
||||||
|
il ripristino usando il backup: tornare al vecchio codice non annulla il DB.
|
||||||
@@ -18,15 +18,12 @@ Include:
|
|||||||
- dbo.py_BarcodePickingListSkip
|
- dbo.py_BarcodePickingListSkip
|
||||||
- dbo.py_PickingListPrelievoSequenza
|
- dbo.py_PickingListPrelievoSequenza
|
||||||
- dbo.py_ViewPackingListPrelievo
|
- dbo.py_ViewPackingListPrelievo
|
||||||
- dbo.py_PickingPair, dbo.py_PickingPairSequence, dbo.py_PickingPairSkip
|
|
||||||
- dbo.py_ViewPickingPairRows, dbo.py_sp_PickingPair
|
|
||||||
|
|
||||||
Include inoltre:
|
Include inoltre:
|
||||||
- intervallo operativo massimo di 30 giorni, filtrato dalla UI a 10/15/20/30;
|
- intervallo operativo massimo di 30 giorni, filtrato dalla UI a 10/15/20/30;
|
||||||
- destinazione senza nazione ammessa nel ramo Python mediante LEFT JOIN;
|
- destinazione senza nazione ammessa nel ramo Python mediante LEFT JOIN;
|
||||||
- ordine predefinito con UDC Non scaff. prima degli scaffali;
|
- ordine predefinito con UDC Non scaff. prima degli scaffali;
|
||||||
- ordine personalizzabile per singolo Documento.
|
- ordine personalizzabile per singolo Documento.
|
||||||
- prenotazione bilista e snapshot della sequenza della prima selezionata.
|
|
||||||
|
|
||||||
Nota storico:
|
Nota storico:
|
||||||
dbo.py_vPreparaPackingListSAMA1 usa ANNDOC >= YEAR(GETDATE())
|
dbo.py_vPreparaPackingListSAMA1 usa ANNDOC >= YEAR(GETDATE())
|
||||||
@@ -724,247 +721,5 @@ SELECT
|
|||||||
FROM Sequenza;
|
FROM Sequenza;
|
||||||
GO
|
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.';
|
PRINT 'Patch cumulativa Python WMS completata.';
|
||||||
GO
|
GO
|
||||||
|
|||||||
@@ -1,240 +0,0 @@
|
|||||||
/* 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
|
|
||||||
@@ -17,8 +17,6 @@ from async_loop_singleton import get_global_loop, stop_global_loop
|
|||||||
from async_msssql_query import AsyncMSSQLClient
|
from async_msssql_query import AsyncMSSQLClient
|
||||||
from barcode_repository import BarcodeRepository
|
from barcode_repository import BarcodeRepository
|
||||||
from barcode_service import BarcodeActionResult, BarcodeService, BarcodeViewState
|
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 db_config import build_dsn_from_config, ensure_db_config
|
||||||
from login_window import prompt_login_compact
|
from login_window import prompt_login_compact
|
||||||
from user_session import create_user_session
|
from user_session import create_user_session
|
||||||
@@ -65,8 +63,7 @@ class BarcodeClientApp:
|
|||||||
self.session = session
|
self.session = session
|
||||||
self.loop = loop
|
self.loop = loop
|
||||||
self.repository = BarcodeRepository(db_client)
|
self.repository = BarcodeRepository(db_client)
|
||||||
self.service = BarcodePairService(self.repository, session.operator_id)
|
self.service = BarcodeService(self.repository, session.operator_id)
|
||||||
self._pending_movement = False
|
|
||||||
self._pending: Future | None = None
|
self._pending: Future | None = None
|
||||||
self._auto_advance_id: str | None = None
|
self._auto_advance_id: str | None = None
|
||||||
self._pallet_auto_focus_id: str | None = None
|
self._pallet_auto_focus_id: str | None = None
|
||||||
@@ -96,7 +93,6 @@ class BarcodeClientApp:
|
|||||||
self.root.protocol("WM_DELETE_WINDOW", self._shutdown)
|
self.root.protocol("WM_DELETE_WINDOW", self._shutdown)
|
||||||
self.root.after(80, self._finalize_window_placement)
|
self.root.after(80, self._finalize_window_placement)
|
||||||
self.root.after(250, 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:
|
def _build_ui(self) -> None:
|
||||||
self.root.title(versioned_title("WMS", __name__))
|
self.root.title(versioned_title("WMS", __name__))
|
||||||
@@ -375,14 +371,11 @@ class BarcodeClientApp:
|
|||||||
else:
|
else:
|
||||||
self.busy_bar.stop()
|
self.busy_bar.stop()
|
||||||
self.busy_cover.place_forget()
|
self.busy_cover.place_forget()
|
||||||
if self.service.pair_active:
|
|
||||||
self.btn_f2.configure(state="disabled")
|
|
||||||
|
|
||||||
def _is_priority_pause(self) -> bool:
|
def _is_priority_pause(self) -> bool:
|
||||||
return str(self.queue_var.get() or "") == "Pausa PL"
|
return str(self.queue_var.get() or "") == "Pausa PL"
|
||||||
|
|
||||||
def _apply_state(self, state: BarcodeViewState) -> None:
|
def _apply_state(self, state: BarcodeViewState) -> None:
|
||||||
self._apply_pair_color(state)
|
|
||||||
if self._auto_advance_id is not None:
|
if self._auto_advance_id is not None:
|
||||||
try:
|
try:
|
||||||
self.root.after_cancel(self._auto_advance_id)
|
self.root.after_cancel(self._auto_advance_id)
|
||||||
@@ -415,7 +408,6 @@ class BarcodeClientApp:
|
|||||||
try:
|
try:
|
||||||
if str(effective_queue_label or "") != "Pausa PL":
|
if str(effective_queue_label or "") != "Pausa PL":
|
||||||
self._paused_queue_id = None
|
self._paused_queue_id = None
|
||||||
self._paused_priority_state = None
|
|
||||||
resumable_queue = self._resumable_queue_from_state(state)
|
resumable_queue = self._resumable_queue_from_state(state)
|
||||||
if state.mode in ("priority_high", "priority_low") or resumable_queue is not None:
|
if state.mode in ("priority_high", "priority_low") or resumable_queue is not None:
|
||||||
self.btn_submit.configure(text="[F3] Pausa PL")
|
self.btn_submit.configure(text="[F3] Pausa PL")
|
||||||
@@ -423,8 +415,8 @@ class BarcodeClientApp:
|
|||||||
self.btn_submit.configure(text="[F3] Carica")
|
self.btn_submit.configure(text="[F3] Carica")
|
||||||
self._refresh_action_labels(state)
|
self._refresh_action_labels(state)
|
||||||
queue_buttons_state = "disabled" if str(effective_queue_label or "") == "Pausa PL" else "normal"
|
queue_buttons_state = "disabled" if str(effective_queue_label or "") == "Pausa PL" else "normal"
|
||||||
self.btn_f1.configure(state=queue_buttons_state, text="[F1] Inizia lista")
|
self.btn_f1.configure(state=queue_buttons_state)
|
||||||
self.btn_f2.configure(state="disabled" if self.service.pair_active else queue_buttons_state)
|
self.btn_f2.configure(state=queue_buttons_state)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -449,20 +441,6 @@ class BarcodeClientApp:
|
|||||||
else:
|
else:
|
||||||
self.root.after(20, self._focus_primary_input)
|
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:
|
def _refresh_action_labels(self, state: BarcodeViewState | None = None) -> None:
|
||||||
current_state = state or self.service.state
|
current_state = state or self.service.state
|
||||||
try:
|
try:
|
||||||
@@ -554,13 +532,7 @@ class BarcodeClientApp:
|
|||||||
return "break"
|
return "break"
|
||||||
|
|
||||||
def _on_escape_key(self, _event=None) -> str:
|
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._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:
|
if self._paused_priority_state is not None:
|
||||||
state = self.service.resume_priority_state(self._paused_priority_state)
|
state = self.service.resume_priority_state(self._paused_priority_state)
|
||||||
self._paused_priority_state = None
|
self._paused_priority_state = None
|
||||||
@@ -575,8 +547,6 @@ class BarcodeClientApp:
|
|||||||
return "break"
|
return "break"
|
||||||
|
|
||||||
def _on_f3(self) -> None:
|
def _on_f3(self) -> None:
|
||||||
if self._pending is not None:
|
|
||||||
return
|
|
||||||
mode = getattr(self.service.state, "mode", "")
|
mode = getattr(self.service.state, "mode", "")
|
||||||
if mode == "priority_high":
|
if mode == "priority_high":
|
||||||
self._paused_queue_id = 1
|
self._paused_queue_id = 1
|
||||||
@@ -597,10 +567,6 @@ class BarcodeClientApp:
|
|||||||
self._submit()
|
self._submit()
|
||||||
|
|
||||||
def _begin_manual_unload(self) -> None:
|
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()
|
pallet = str(self.scanned_var.get() or "").strip()
|
||||||
destination = str(self.destination_var.get() or "").strip()
|
destination = str(self.destination_var.get() or "").strip()
|
||||||
mode = getattr(self.service.state, "mode", "")
|
mode = getattr(self.service.state, "mode", "")
|
||||||
@@ -618,8 +584,6 @@ class BarcodeClientApp:
|
|||||||
self._apply_state(self.service.begin_manual_unload())
|
self._apply_state(self.service.begin_manual_unload())
|
||||||
|
|
||||||
def _start_queue(self, id_stato: int, *, allow_during_pause: bool = False) -> None:
|
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:
|
if self._is_priority_pause() and not allow_during_pause:
|
||||||
return
|
return
|
||||||
self._run_async(
|
self._run_async(
|
||||||
@@ -628,15 +592,12 @@ class BarcodeClientApp:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def _submit(self) -> None:
|
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(
|
self._run_async(
|
||||||
lambda: self.service.submit(
|
lambda: self.service.submit(
|
||||||
scanned_pallet=self.scanned_var.get(),
|
scanned_pallet=self.scanned_var.get(),
|
||||||
destination_barcode=self.destination_var.get(),
|
destination_barcode=self.destination_var.get(),
|
||||||
),
|
),
|
||||||
busy_message="In esecuzione...",
|
busy_message="In esecuzione...",
|
||||||
movement=True,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def _submit_unload_with_source_check(self) -> None:
|
def _submit_unload_with_source_check(self) -> None:
|
||||||
@@ -646,8 +607,6 @@ class BarcodeClientApp:
|
|||||||
source_barcode=self.destination_var.get(),
|
source_barcode=self.destination_var.get(),
|
||||||
),
|
),
|
||||||
busy_message="In esecuzione...",
|
busy_message="In esecuzione...",
|
||||||
movement=True,
|
|
||||||
recovery_destination=self.NON_SCAFFALATA_BARCODE,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def _skip_current_picking_pallet(self) -> None:
|
def _skip_current_picking_pallet(self) -> None:
|
||||||
@@ -656,9 +615,8 @@ class BarcodeClientApp:
|
|||||||
busy_message="Registro salto UDC...",
|
busy_message="Registro salto UDC...",
|
||||||
)
|
)
|
||||||
|
|
||||||
def _run_async(self, coro_factory: Callable[[], object], busy_message: str, *, movement: bool = False,
|
def _run_async(self, coro_factory: Callable[[], object], busy_message: str) -> None:
|
||||||
recovery_destination: str | None = None) -> None:
|
if self._pending is not None and not self._pending.done():
|
||||||
if self._pending is not None:
|
|
||||||
return
|
return
|
||||||
if self._auto_advance_id is not None:
|
if self._auto_advance_id is not None:
|
||||||
try:
|
try:
|
||||||
@@ -667,8 +625,6 @@ class BarcodeClientApp:
|
|||||||
pass
|
pass
|
||||||
self._auto_advance_id = None
|
self._auto_advance_id = None
|
||||||
self._set_busy(True, busy_message)
|
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._pending = asyncio.run_coroutine_threadsafe(coro_factory(), self.loop)
|
||||||
self.root.after(40, self._poll_future)
|
self.root.after(40, self._poll_future)
|
||||||
|
|
||||||
@@ -684,8 +640,6 @@ class BarcodeClientApp:
|
|||||||
delay_ms = int(getattr(state, "auto_advance_delay_ms", 0) or 0)
|
delay_ms = int(getattr(state, "auto_advance_delay_ms", 0) or 0)
|
||||||
if delay_ms <= 0:
|
if delay_ms <= 0:
|
||||||
return None
|
return None
|
||||||
if state.pair_run_id:
|
|
||||||
return 1
|
|
||||||
return self._queue_id_from_label(str(getattr(state, "queue_label", "") or ""))
|
return self._queue_id_from_label(str(getattr(state, "queue_label", "") or ""))
|
||||||
|
|
||||||
def _poll_future(self) -> None:
|
def _poll_future(self) -> None:
|
||||||
@@ -703,19 +657,11 @@ class BarcodeClientApp:
|
|||||||
result = future.result()
|
result = future.result()
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
log_exception("Barcode WMS", exc, context="barcode async operation")
|
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._set_busy(True, "Verifico esito...")
|
||||||
self._pending = asyncio.run_coroutine_threadsafe(
|
self._pending = asyncio.run_coroutine_threadsafe(
|
||||||
self.service.reconcile_after_submit_exception(
|
self.service.reconcile_after_submit_exception(
|
||||||
scanned_pallet=self._pending_scan[0],
|
scanned_pallet=self.scanned_var.get(),
|
||||||
destination_barcode=self._pending_scan[1],
|
destination_barcode=self.destination_var.get(),
|
||||||
),
|
),
|
||||||
self.loop,
|
self.loop,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,155 +0,0 @@
|
|||||||
"""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
|
|
||||||
@@ -40,8 +40,7 @@ WHERE Ordinamento > 0
|
|||||||
AND s.IDStato = pl.IDStato
|
AND s.IDStato = pl.IDStato
|
||||||
AND s.Risolto = 0
|
AND s.Risolto = 0
|
||||||
)
|
)
|
||||||
ORDER BY CASE WHEN Cella=1000 THEN 0 ELSE 1 END,
|
ORDER BY OrdinePrelievoGruppo, Ordinamento, Pallet, Documento;
|
||||||
OrdinePrelievoGruppo, Ordinamento, Pallet, Documento;
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
SQL_PICKING_BY_PALLET = """
|
SQL_PICKING_BY_PALLET = """
|
||||||
@@ -453,8 +452,6 @@ class BarcodeRepository:
|
|||||||
barcode_pallet: str,
|
barcode_pallet: str,
|
||||||
numero_cella: int,
|
numero_cella: int,
|
||||||
refresh_picking_reservation: bool = True,
|
refresh_picking_reservation: bool = True,
|
||||||
pair_run_id: str | None = None,
|
|
||||||
pair_document: str | None = None,
|
|
||||||
) -> LegacyMoveResult:
|
) -> LegacyMoveResult:
|
||||||
"""Execute the same stored procedure used by the C# barcode form."""
|
"""Execute the same stored procedure used by the C# barcode form."""
|
||||||
|
|
||||||
@@ -476,30 +473,7 @@ class BarcodeRepository:
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
sql = SQL_LEGACY_MOVE
|
res = await self.db_client.query_json(SQL_LEGACY_MOVE, params, commit=True)
|
||||||
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:
|
except Exception as exc:
|
||||||
log_exception(
|
log_exception(
|
||||||
"Barcode WMS",
|
"Barcode WMS",
|
||||||
|
|||||||
@@ -31,9 +31,6 @@ class BarcodeViewState:
|
|||||||
auto_advance_delay_ms: int = 0
|
auto_advance_delay_ms: int = 0
|
||||||
destination_readonly: bool = False
|
destination_readonly: bool = False
|
||||||
focus_destination: bool = False
|
focus_destination: bool = False
|
||||||
pair_run_id: str = ""
|
|
||||||
pair_slot: int = 0
|
|
||||||
pair_document: str = ""
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -403,8 +400,6 @@ class BarcodeService:
|
|||||||
barcode_pallet=pallet,
|
barcode_pallet=pallet,
|
||||||
numero_cella=target_numero_cella,
|
numero_cella=target_numero_cella,
|
||||||
refresh_picking_reservation=is_picking_unload,
|
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)
|
final_location = await self.repository.fetch_current_location_by_pallet(pallet)
|
||||||
|
|||||||
@@ -332,11 +332,8 @@ DET_COLS: List[ColSpec] = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
ROW_H = 28
|
ROW_H = 28
|
||||||
from pickinglist_pair import PAIR_SLOT_COLORS
|
RESERVED_IDSTATO_BG = "#dc2626"
|
||||||
from pickinglist_pair_repository import PickingPairRepository
|
RESERVED_IDSTATO_FG = "#ffffff"
|
||||||
|
|
||||||
RESERVED_IDSTATO_BG = PAIR_SLOT_COLORS[1]
|
|
||||||
RESERVED_IDSTATO_FG = "#111827"
|
|
||||||
|
|
||||||
|
|
||||||
# -------------------- Micro spinner (toolbar) --------------------
|
# -------------------- Micro spinner (toolbar) --------------------
|
||||||
@@ -654,8 +651,6 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
self.rows_models: list[PLRow] = []
|
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_cache: Dict[Any, list] = {}
|
||||||
self.detail_doc = None
|
self.detail_doc = None
|
||||||
self.days_var = tk.StringVar(value="10")
|
self.days_var = tk.StringVar(value="10")
|
||||||
@@ -712,15 +707,12 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
(loc_text("picking.button.sequence", catalog=self._locale_catalog, default="Sequenza di prelievo"), self.on_sequence),
|
(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)
|
(loc_text("picking.button.export", catalog=self._locale_catalog, default="Esporta XLSX"), self.on_export)
|
||||||
]):
|
]):
|
||||||
button = ctk.CTkButton(
|
ctk.CTkButton(
|
||||||
top,
|
top,
|
||||||
text=text,
|
text=text,
|
||||||
command=cmd,
|
command=cmd,
|
||||||
font=theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold")),
|
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(
|
ctk.CTkLabel(
|
||||||
top,
|
top,
|
||||||
@@ -736,10 +728,6 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
font=theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold")),
|
font=theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold")),
|
||||||
).grid(row=0, column=6, padx=(0, 6), sticky="w")
|
).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 ---
|
# --- micro spinner a destra della toolbar ---
|
||||||
self.spinner = ToolbarSpinner(top)
|
self.spinner = ToolbarSpinner(top)
|
||||||
self.spinner.widget().grid(row=0, column=10, padx=(8,0)) # largo spazio a destra
|
self.spinner.widget().grid(row=0, column=10, padx=(8,0)) # largo spazio a destra
|
||||||
@@ -925,9 +913,8 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
row_children = row_widget.winfo_children()
|
row_children = row_widget.winfo_children()
|
||||||
if len(row_children) >= 5:
|
if len(row_children) >= 5:
|
||||||
holder = row_children[4]
|
holder = row_children[4]
|
||||||
slot = int(d.get("IDStato") or 0)
|
is_reserved = int(d.get("IDStato") or 0) == 1
|
||||||
is_reserved = slot in PAIR_SLOT_COLORS
|
holder_bg = RESERVED_IDSTATO_BG if is_reserved else row_bg
|
||||||
holder_bg = PAIR_SLOT_COLORS.get(slot, row_bg)
|
|
||||||
holder.configure(fg_color=holder_bg)
|
holder.configure(fg_color=holder_bg)
|
||||||
if holder.winfo_children():
|
if holder.winfo_children():
|
||||||
lbl = holder.winfo_children()[0]
|
lbl = holder.winfo_children()[0]
|
||||||
@@ -964,8 +951,8 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
row_index=r,
|
row_index=r,
|
||||||
anchors=[c.anchor for c in PL_COLS],
|
anchors=[c.anchor for c in PL_COLS],
|
||||||
checkbox_builder=model.build_checkbox,
|
checkbox_builder=model.build_checkbox,
|
||||||
cell_bg={"IDStato": PAIR_SLOT_COLORS[int(d["IDStato"])]} if int(d.get("IDStato") or 0) in PAIR_SLOT_COLORS else None,
|
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) in PAIR_SLOT_COLORS else None,
|
cell_fg={"IDStato": RESERVED_IDSTATO_FG} if int(d.get("IDStato") or 0) == 1 else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
# 🎯 Colora dopo che la UI è resa → no balzi visivi
|
# 🎯 Colora dopo che la UI è resa → no balzi visivi
|
||||||
@@ -974,25 +961,11 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
# ----- helpers -----
|
# ----- helpers -----
|
||||||
def _get_selected_model(self) -> Optional[PLRow]:
|
def _get_selected_model(self) -> Optional[PLRow]:
|
||||||
"""Return the currently checked picking list row, if any."""
|
"""Return the currently checked picking list row, if any."""
|
||||||
selected = self._selected_models()
|
for m in self.rows_models:
|
||||||
if selected:
|
if m.is_checked():
|
||||||
return next((m for m in selected if _s(m.pl.get("Documento")) == _s(self.detail_doc)), selected[0])
|
return m
|
||||||
return None
|
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):
|
def _recolor_row_by_documento(self, documento: str, idstato: int):
|
||||||
"""Aggiorna colore riga e cella IDStato per il Documento indicato."""
|
"""Aggiorna colore riga e cella IDStato per il Documento indicato."""
|
||||||
for idx, m in enumerate(self.rows_models):
|
for idx, m in enumerate(self.rows_models):
|
||||||
@@ -1058,24 +1031,21 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
@_log_call()
|
@_log_call()
|
||||||
def on_row_checked(self, model: PLRow, is_checked: bool):
|
def on_row_checked(self, model: PLRow, is_checked: bool):
|
||||||
"""Handle row selection changes and refresh the detail section."""
|
"""Handle row selection changes and refresh the detail section."""
|
||||||
document = _s(model.pl.get("Documento"))
|
# Only one backoffice picking list can be selected at a time. Barcode
|
||||||
|
# F1/F2 priority behavior is derived downstream; this UI controls only
|
||||||
|
# the explicit Python reservation slot.
|
||||||
if is_checked:
|
if is_checked:
|
||||||
if document not in self._selection_order:
|
for m in self.rows_models:
|
||||||
if len(self._selection_order) >= 2:
|
if m is not model and m.is_checked():
|
||||||
model.set_checked(False)
|
m.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 = document
|
self.detail_doc = model.pl.get("Documento")
|
||||||
_MODULE_LOGGER.info(f"Documento selezionato per il dettaglio: {self.detail_doc}")
|
_MODULE_LOGGER.info(f"Documento selezionato per il dettaglio: {self.detail_doc}")
|
||||||
self.spinner.start(" Carico dettagli…") # spinner ON
|
self.spinner.start(" Carico dettagli…") # spinner ON
|
||||||
days = self._selected_days()
|
days = self._selected_days()
|
||||||
|
|
||||||
async def _job():
|
async def _job():
|
||||||
params = {"Documento": document, "days": days}
|
params = {"Documento": self.detail_doc, "days": days}
|
||||||
_log_sql("SQL_PL_DETAILS", SQL_PL_DETAILS, params)
|
_log_sql("SQL_PL_DETAILS", SQL_PL_DETAILS, params)
|
||||||
return await self.db_client.query_json(SQL_PL_DETAILS, params)
|
return await self.db_client.query_json(SQL_PL_DETAILS, params)
|
||||||
|
|
||||||
@@ -1083,9 +1053,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
# NON fermare lo spinner subito: lo farà _refresh_details_incremental
|
# NON fermare lo spinner subito: lo farà _refresh_details_incremental
|
||||||
rows = _expand_detail_rows_for_test(_rows_to_dicts(res))
|
rows = _expand_detail_rows_for_test(_rows_to_dicts(res))
|
||||||
_log_dataset("SQL_PL_DETAILS", rows)
|
_log_dataset("SQL_PL_DETAILS", rows)
|
||||||
self._detail_cache[document] = rows
|
self._detail_cache[self.detail_doc] = rows
|
||||||
if _s(self.detail_doc) != document:
|
|
||||||
return
|
|
||||||
# Avvia il rendering incrementale che mantiene l'overlay attivo
|
# Avvia il rendering incrementale che mantiene l'overlay attivo
|
||||||
self._refresh_details_incremental()
|
self._refresh_details_incremental()
|
||||||
|
|
||||||
@@ -1106,12 +1074,6 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
self.busy.show(f"Carico UDC per Documento {self.detail_doc}…")
|
self.busy.show(f"Carico UDC per Documento {self.detail_doc}…")
|
||||||
|
|
||||||
else:
|
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):
|
if not any(m.is_checked() for m in self.rows_models):
|
||||||
self.detail_doc = None
|
self.detail_doc = None
|
||||||
_MODULE_LOGGER.info("Nessun documento selezionato: ripristino placeholder del dettaglio.")
|
_MODULE_LOGGER.info("Nessun documento selezionato: ripristino placeholder del dettaglio.")
|
||||||
@@ -1131,36 +1093,14 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
async def _job():
|
async def _job():
|
||||||
params = {"days": days}
|
params = {"days": days}
|
||||||
_log_sql("SQL_PL", SQL_PL, params)
|
_log_sql("SQL_PL", SQL_PL, params)
|
||||||
result = await self.db_client.query_json(SQL_PL, params)
|
return 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):
|
def _on_success(res):
|
||||||
rows = _rows_to_dicts(res)
|
rows = _rows_to_dicts(res)
|
||||||
_log_dataset("SQL_PL", rows)
|
_log_dataset("SQL_PL", rows)
|
||||||
self._refresh_mid_rows(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:
|
if reselect_documento:
|
||||||
def _reselect_or_clear(doc=reselect_documento):
|
def _reselect_or_clear(doc=reselect_documento):
|
||||||
found = self._reselect_documento_after_reload(doc)
|
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:
|
if not found:
|
||||||
self.detail_doc = None
|
self.detail_doc = None
|
||||||
self._draw_details_hint()
|
self._draw_details_hint()
|
||||||
@@ -1253,13 +1193,6 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
def on_sequence(self):
|
def on_sequence(self):
|
||||||
"""Open the pickup-sequence editor for the selected picking list."""
|
"""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"):
|
if not self._can("pickinglist.sequence"):
|
||||||
messagebox.showwarning(
|
messagebox.showwarning(
|
||||||
loc_text("picking.sequence.title", catalog=self._locale_catalog, default="Sequenza di prelievo"),
|
loc_text("picking.sequence.title", catalog=self._locale_catalog, default="Sequenza di prelievo"),
|
||||||
@@ -1301,18 +1234,17 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
if not self._can("pickinglist.prenota"):
|
if not self._can("pickinglist.prenota"):
|
||||||
messagebox.showwarning("Permesso negato", "L'operatore corrente non puo' prenotare picking list.", parent=self)
|
messagebox.showwarning("Permesso negato", "L'operatore corrente non puo' prenotare picking list.", parent=self)
|
||||||
return
|
return
|
||||||
selected = self._selected_models()
|
model = self._get_selected_model()
|
||||||
if not selected:
|
if not model:
|
||||||
messagebox.showinfo("Prenota", "Seleziona una Picking List (checkbox) prima di prenotare.")
|
messagebox.showinfo("Prenota", "Seleziona una Picking List (checkbox) prima di prenotare.")
|
||||||
return
|
return
|
||||||
|
|
||||||
documents = [_s(m.pl.get("Documento")) for m in selected]
|
documento = _s(model.pl.get("Documento"))
|
||||||
documento = documents[0]
|
current = int(model.pl.get("IDStato") or 0)
|
||||||
current = int(selected[0].pl.get("IDStato") or 0)
|
|
||||||
desired = 1
|
desired = 1
|
||||||
# Idempotent semantics: Prenota never toggles a list off. If the list
|
# Idempotent semantics: Prenota never toggles a list off. If the list
|
||||||
# is already reserved, S-prenota remains the only explicit release path.
|
# is already reserved, S-prenota remains the only explicit release path.
|
||||||
if len(documents) == 1 and current in (1, 2):
|
if current == desired:
|
||||||
messagebox.showinfo("Prenota", f"La Picking List {documento} è già prenotata.")
|
messagebox.showinfo("Prenota", f"La Picking List {documento} è già prenotata.")
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -1324,12 +1256,9 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
self.spinner.start(" Prenoto…")
|
self.spinner.start(" Prenoto…")
|
||||||
|
|
||||||
async def _job():
|
async def _job():
|
||||||
pairs = PickingPairRepository(self.db_client)
|
# Use the Python-specific py_* stored procedure so C# legacy
|
||||||
if len(documents) == 2:
|
# procedures can coexist unchanged on the same database.
|
||||||
await pairs.command("R", id_operatore, documents=tuple(documents))
|
return await sp_xExePackingListPallet_async(self.db_client, id_operatore, documento, "P")
|
||||||
else:
|
|
||||||
await pairs.reserve_single(documento, id_operatore)
|
|
||||||
return SPResult(rc=0, message="", id_result=None)
|
|
||||||
|
|
||||||
def _ok(res: SPResult):
|
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)}")
|
_MODULE_LOGGER.log(_MODULE_LOG_LEVEL, f"Esito prenotazione documento={documento} rc={getattr(res, 'rc', None)} message={getattr(res, 'message', None)}")
|
||||||
@@ -1341,7 +1270,6 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
action="pickinglist.prenota",
|
action="pickinglist.prenota",
|
||||||
outcome="ok",
|
outcome="ok",
|
||||||
target=documento,
|
target=documento,
|
||||||
details={"documents": documents},
|
|
||||||
)
|
)
|
||||||
self._detail_cache.pop(documento, None)
|
self._detail_cache.pop(documento, None)
|
||||||
self.reload_from_db(reselect_documento=documento)
|
self.reload_from_db(reselect_documento=documento)
|
||||||
@@ -1375,7 +1303,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
on_success=_ok,
|
on_success=_ok,
|
||||||
on_error=_err,
|
on_error=_err,
|
||||||
busy=self.busy,
|
busy=self.busy,
|
||||||
message=f"Prenoto PL {', '.join(documents)}..."
|
message=f"Prenoto la Picking List {documento}…"
|
||||||
)
|
)
|
||||||
|
|
||||||
@_log_call()
|
@_log_call()
|
||||||
@@ -1384,14 +1312,13 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
if not self._can("pickinglist.sprenota"):
|
if not self._can("pickinglist.sprenota"):
|
||||||
messagebox.showwarning("Permesso negato", "L'operatore corrente non puo' s-prenotare picking list.", parent=self)
|
messagebox.showwarning("Permesso negato", "L'operatore corrente non puo' s-prenotare picking list.", parent=self)
|
||||||
return
|
return
|
||||||
selected = self._selected_models()
|
model = self._get_selected_model()
|
||||||
if not selected:
|
if not model:
|
||||||
messagebox.showinfo("S-prenota", "Seleziona una Picking List (checkbox) prima di s-prenotare.")
|
messagebox.showinfo("S-prenota", "Seleziona una Picking List (checkbox) prima di s-prenotare.")
|
||||||
return
|
return
|
||||||
|
|
||||||
documents = [_s(m.pl.get("Documento")) for m in selected]
|
documento = _s(model.pl.get("Documento"))
|
||||||
documento = documents[0]
|
current = int(model.pl.get("IDStato") or 0)
|
||||||
current = max(int(m.pl.get("IDStato") or 0) for m in selected)
|
|
||||||
desired = 0
|
desired = 0
|
||||||
# Idempotent semantics: S-prenota never reserves a list; if the list is
|
# 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.
|
# already free, the operation is a no-op rather than an implicit toggle.
|
||||||
@@ -1407,9 +1334,9 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
self.spinner.start(" S-prenoto…")
|
self.spinner.start(" S-prenoto…")
|
||||||
|
|
||||||
async def _job():
|
async def _job():
|
||||||
# Release selected slots atomically, without changing the other role.
|
# Same Python-only procedure as Prenota, with action S to release
|
||||||
await PickingPairRepository(self.db_client).release_selected(documents, id_operatore)
|
# the singleton reservation and clear affected cell states.
|
||||||
return SPResult(rc=0, message="", id_result=None)
|
return await sp_xExePackingListPallet_async(self.db_client, id_operatore, documento, "S")
|
||||||
|
|
||||||
def _ok(res: SPResult):
|
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)}")
|
_MODULE_LOGGER.log(_MODULE_LOG_LEVEL, f"Esito s-prenotazione documento={documento} rc={getattr(res, 'rc', None)} message={getattr(res, 'message', None)}")
|
||||||
@@ -1421,7 +1348,6 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
action="pickinglist.sprenota",
|
action="pickinglist.sprenota",
|
||||||
outcome="ok",
|
outcome="ok",
|
||||||
target=documento,
|
target=documento,
|
||||||
details={"documents": documents},
|
|
||||||
)
|
)
|
||||||
self._detail_cache.pop(documento, None)
|
self._detail_cache.pop(documento, None)
|
||||||
self.reload_from_db(reselect_documento=documento)
|
self.reload_from_db(reselect_documento=documento)
|
||||||
@@ -1455,7 +1381,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
|||||||
on_success=_ok,
|
on_success=_ok,
|
||||||
on_error=_err,
|
on_error=_err,
|
||||||
busy=self.busy,
|
busy=self.busy,
|
||||||
message=f"S-prenoto PL {', '.join(documents)}..."
|
message=f"S-prenoto la Picking List {documento}…"
|
||||||
)
|
)
|
||||||
|
|
||||||
def on_export(self):
|
def on_export(self):
|
||||||
|
|||||||
234
inventario.py
Normal file
234
inventario.py
Normal file
@@ -0,0 +1,234 @@
|
|||||||
|
"""Dated inventory reconciliation window, using the shared desktop UI lifecycle."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import tkinter as tk
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from tkinter import filedialog, messagebox, ttk
|
||||||
|
|
||||||
|
import customtkinter as ctk
|
||||||
|
|
||||||
|
from busy_overlay import InlineBusyOverlay
|
||||||
|
from gestione_aree import AsyncRunner
|
||||||
|
from inventory_service import (DETAIL_KEYS, LOT_KEYS, SUMMARY_KEYS, detail_values,
|
||||||
|
export_inventory, inventory_cutoff, load_inventory, status_text)
|
||||||
|
from locale_text import load_locale_catalog, text as loc_text
|
||||||
|
from runtime_support import log_exception
|
||||||
|
from ui_tables import style_treeview, zebra_tag
|
||||||
|
from ui_theme import theme_color, theme_font, theme_section, theme_value
|
||||||
|
from version_info import module_version, versioned_title
|
||||||
|
from window_placement import place_window_fullsize_below_parent_later
|
||||||
|
|
||||||
|
__version__ = module_version(__name__)
|
||||||
|
KEYS = SUMMARY_KEYS
|
||||||
|
|
||||||
|
|
||||||
|
def display_number(value) -> str:
|
||||||
|
"""Keep zeros visible and unknown values distinct from numeric stock."""
|
||||||
|
if value is None:
|
||||||
|
return "?"
|
||||||
|
if isinstance(value, Decimal):
|
||||||
|
return format(value, "f").rstrip("0").rstrip(".") if value.as_tuple().exponent < 0 else str(value)
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
|
||||||
|
class InventarioWindow(ctk.CTkToplevel):
|
||||||
|
"""Read-only, single-instance launcher child; DB and XLSX work are asynchronous."""
|
||||||
|
|
||||||
|
def __init__(self, parent, db_client, session=None):
|
||||||
|
super().__init__(parent)
|
||||||
|
self.db_client = db_client
|
||||||
|
self.session = session
|
||||||
|
self._catalog = load_locale_catalog()
|
||||||
|
self._theme = theme_section("inventory_window", theme_section("search_window", {}))
|
||||||
|
self._async = AsyncRunner(self)
|
||||||
|
self._busy = InlineBusyOverlay(self, self._theme)
|
||||||
|
self._loading = False
|
||||||
|
self._report = None
|
||||||
|
self._sort_column = "Product"
|
||||||
|
self._descending = False
|
||||||
|
self._rows = []
|
||||||
|
self.var_date = tk.StringVar(value=date.today().strftime("%d/%m/%Y"))
|
||||||
|
self.var_status = tk.StringVar(value=self._t("inventory.scope"))
|
||||||
|
self.title(versioned_title(self._t("inventory.title"), __name__))
|
||||||
|
self.geometry(str(theme_value(self._theme, "window_geometry", "1200x720")))
|
||||||
|
self.minsize(*theme_value(self._theme, "window_minsize", [900, 560]))
|
||||||
|
self.configure(fg_color=theme_color(self._theme, "window_fg_color", ["#efefef", "#2f2f2f"]))
|
||||||
|
self._build_ui()
|
||||||
|
|
||||||
|
def _t(self, key: str) -> str:
|
||||||
|
return loc_text(key, catalog=self._catalog, default=key)
|
||||||
|
|
||||||
|
def _build_ui(self):
|
||||||
|
self.grid_columnconfigure(0, weight=1)
|
||||||
|
self.grid_rowconfigure(3, weight=3)
|
||||||
|
self.grid_rowconfigure(5, weight=1)
|
||||||
|
top = ctk.CTkFrame(self, fg_color=theme_color(self._theme, "toolbar_frame_fg_color", "#d7d7d7"))
|
||||||
|
top.grid(row=0, column=0, sticky="ew", padx=8, pady=8)
|
||||||
|
top.grid_columnconfigure(3, weight=1)
|
||||||
|
font = theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 11, "bold"))
|
||||||
|
ctk.CTkLabel(top, text=self._t("inventory.date"), font=font).grid(row=0, column=0, padx=6)
|
||||||
|
self.date_entry = ctk.CTkEntry(top, textvariable=self.var_date, width=130)
|
||||||
|
self.date_entry.grid(row=0, column=1, padx=6)
|
||||||
|
self.date_entry.bind("<Return>", lambda _: self._load())
|
||||||
|
self.btn_load = ctk.CTkButton(top, text=self._t("inventory.load"), command=self._load, font=font)
|
||||||
|
self.btn_load.grid(row=0, column=2, padx=6)
|
||||||
|
self.btn_export = ctk.CTkButton(top, text=self._t("inventory.export"), command=self._export,
|
||||||
|
font=font, state="disabled")
|
||||||
|
self.btn_export.grid(row=0, column=4, padx=6)
|
||||||
|
ctk.CTkLabel(self, text=self._t("inventory.notice") + "\n" + self._t("inventory.scope")
|
||||||
|
+ "\n" + self._t("inventory.history_notice"), anchor="w", justify="left",
|
||||||
|
wraplength=1000).grid(row=1, column=0, sticky="ew", padx=10)
|
||||||
|
ctk.CTkLabel(self, textvariable=self.var_status, anchor="w", justify="left",
|
||||||
|
wraplength=1000).grid(row=2, column=0, sticky="ew", padx=10, pady=5)
|
||||||
|
self.tree = self._make_tree(3, KEYS)
|
||||||
|
self.tree.bind("<<TreeviewSelect>>", self._select)
|
||||||
|
ctk.CTkLabel(self, text=self._t("inventory.detail"), anchor="w").grid(row=4, column=0, sticky="ew", padx=10)
|
||||||
|
tabs = ttk.Notebook(self)
|
||||||
|
tabs.grid(row=5, column=0, sticky="nsew", padx=8, pady=(0, 8))
|
||||||
|
lot_page, detail_page = ttk.Frame(tabs), ttk.Frame(tabs)
|
||||||
|
for page in (lot_page, detail_page):
|
||||||
|
page.grid_rowconfigure(0, weight=1)
|
||||||
|
page.grid_columnconfigure(0, weight=1)
|
||||||
|
tabs.add(lot_page, text=self._t("inventory.lot_sheet"))
|
||||||
|
tabs.add(detail_page, text=self._t("inventory.detail_sheet"))
|
||||||
|
self.lot_tree = self._make_tree(0, LOT_KEYS, lot_page)
|
||||||
|
self.detail_tree = self._make_tree(0, DETAIL_KEYS, detail_page)
|
||||||
|
|
||||||
|
def _make_tree(self, row, keys, parent=None):
|
||||||
|
wrap = ctk.CTkFrame(parent if parent is not None else self)
|
||||||
|
wrap.grid(row=row, column=0, sticky="nsew", padx=8, pady=(0, 8))
|
||||||
|
wrap.grid_columnconfigure(0, weight=1)
|
||||||
|
wrap.grid_rowconfigure(0, weight=1)
|
||||||
|
tree = ttk.Treeview(wrap, columns=keys, show="headings", selectmode="browse")
|
||||||
|
style_treeview(tree, style_name="Inventory.Treeview", rowheight=24)
|
||||||
|
tree.tag_configure("difference", foreground=theme_value(self._theme, "difference_color", "#9b3900"))
|
||||||
|
tree.tag_configure("unknown", foreground=theme_value(self._theme, "unknown_color", "#aa0000"))
|
||||||
|
for key in keys:
|
||||||
|
tree.heading(key, text=self._t("inventory.col." + key))
|
||||||
|
tree.column(key, width=250 if key in ("Description", "Status") else 120,
|
||||||
|
anchor="e" if key in KEYS[3:-1] or key in ("Quantity", "SamQuantity") else "w")
|
||||||
|
if keys == KEYS:
|
||||||
|
tree.heading(key, command=lambda k=key: self._sort(k))
|
||||||
|
sy = ttk.Scrollbar(wrap, orient="vertical", command=tree.yview)
|
||||||
|
sx = ttk.Scrollbar(wrap, orient="horizontal", command=tree.xview)
|
||||||
|
tree.configure(yscrollcommand=sy.set, xscrollcommand=sx.set)
|
||||||
|
tree.grid(row=0, column=0, sticky="nsew")
|
||||||
|
sy.grid(row=0, column=1, sticky="ns")
|
||||||
|
sx.grid(row=1, column=0, sticky="ew")
|
||||||
|
return tree
|
||||||
|
|
||||||
|
def _set_loading(self, value):
|
||||||
|
self._loading = value
|
||||||
|
state = "disabled" if value else "normal"
|
||||||
|
self.btn_load.configure(state=state)
|
||||||
|
self.date_entry.configure(state=state)
|
||||||
|
self.btn_export.configure(state="normal" if not value and self._report and self._rows else "disabled")
|
||||||
|
|
||||||
|
def _load(self):
|
||||||
|
if self._loading:
|
||||||
|
return
|
||||||
|
value = self.var_date.get()
|
||||||
|
try:
|
||||||
|
inventory_cutoff(value)
|
||||||
|
except ValueError:
|
||||||
|
messagebox.showerror(self._t("inventory.title"), self._t("inventory.bad_date"), parent=self)
|
||||||
|
return
|
||||||
|
self._report = None
|
||||||
|
self._rows = []
|
||||||
|
self.tree.delete(*self.tree.get_children())
|
||||||
|
self.detail_tree.delete(*self.detail_tree.get_children())
|
||||||
|
self.lot_tree.delete(*self.lot_tree.get_children())
|
||||||
|
self.var_status.set(self._t("inventory.busy"))
|
||||||
|
self._set_loading(True)
|
||||||
|
self._async.run(load_inventory(self.db_client, value), self._loaded, self._error,
|
||||||
|
busy=self._busy, message=self._t("inventory.busy"))
|
||||||
|
|
||||||
|
def _loaded(self, report):
|
||||||
|
self._report = report
|
||||||
|
self._rows = list(report.rows)
|
||||||
|
self._set_loading(False)
|
||||||
|
self._render()
|
||||||
|
source = lambda key: str(report.metadata.get(key) or "?")[:10]
|
||||||
|
self.var_status.set(self._t("inventory.loaded").format(
|
||||||
|
date=report.selected_date.strftime("%d/%m/%Y"), count=len(report.rows),
|
||||||
|
unknown=sum(bool(r["Issues"]) for r in report.rows),
|
||||||
|
wms=source("WMS_MAX"), sam=source("SAM_MAX")))
|
||||||
|
if report.selected_date == date.today():
|
||||||
|
self.var_status.set(self.var_status.get() + "\n" + self._t("inventory.today"))
|
||||||
|
|
||||||
|
def _render(self):
|
||||||
|
self.tree.delete(*self.tree.get_children())
|
||||||
|
self.detail_tree.delete(*self.detail_tree.get_children())
|
||||||
|
self.lot_tree.delete(*self.lot_tree.get_children())
|
||||||
|
for index, row in enumerate(self._rows):
|
||||||
|
tag = "unknown" if row["Issues"] else ("difference" if row["Difference"] else "")
|
||||||
|
self.tree.insert("", "end", iid=str(index),
|
||||||
|
values=[display_number(row[k]) for k in KEYS[:-1]] + [status_text(row, self._t)],
|
||||||
|
tags=(zebra_tag(index), tag))
|
||||||
|
|
||||||
|
def _sort(self, key):
|
||||||
|
if self._loading:
|
||||||
|
return
|
||||||
|
self._descending = not self._descending if self._sort_column == key else False
|
||||||
|
self._sort_column = key
|
||||||
|
def sort_value(row):
|
||||||
|
value = status_text(row, self._t) if key == "Status" else row[key]
|
||||||
|
return (value is None, value.casefold() if isinstance(value, str) else value if value is not None else ZERO_SORT)
|
||||||
|
self._rows.sort(key=sort_value, reverse=self._descending)
|
||||||
|
self._render()
|
||||||
|
|
||||||
|
def _select(self, _event=None):
|
||||||
|
self.detail_tree.delete(*self.detail_tree.get_children())
|
||||||
|
self.lot_tree.delete(*self.lot_tree.get_children())
|
||||||
|
selected = self.tree.selection()
|
||||||
|
if not selected or self._report is None:
|
||||||
|
return
|
||||||
|
product = self._rows[int(selected[0])]["Product"]
|
||||||
|
for i, row in enumerate(r for r in self._report.lots if r["Product"] == product):
|
||||||
|
self.lot_tree.insert("", "end",
|
||||||
|
values=[display_number(row[k]) for k in LOT_KEYS[:-1]] + [status_text(row, self._t)],
|
||||||
|
tags=(zebra_tag(i), "unknown" if row["Issues"] else "difference" if row["Difference"] else ""))
|
||||||
|
details = [r for r in self._report.details if r["Product"] == product]
|
||||||
|
for i, row in enumerate(details):
|
||||||
|
self.detail_tree.insert("", "end", values=[display_number(v) for v in detail_values(row, self._t)],
|
||||||
|
tags=(zebra_tag(i),))
|
||||||
|
|
||||||
|
def _error(self, error):
|
||||||
|
self._set_loading(False)
|
||||||
|
log_exception(__name__, error, context="inventory report/export")
|
||||||
|
self.var_status.set(self._t("inventory.failed"))
|
||||||
|
messagebox.showerror(self._t("inventory.title"), str(error), parent=self)
|
||||||
|
|
||||||
|
def _export(self):
|
||||||
|
if self._loading or not self._report or not self._rows:
|
||||||
|
return
|
||||||
|
report = self._report
|
||||||
|
path = filedialog.asksaveasfilename(parent=self, defaultextension=".xlsx",
|
||||||
|
filetypes=[("Excel", "*.xlsx")], initialfile=f"inventario_{report.selected_date:%Y%m%d}.xlsx")
|
||||||
|
if not path:
|
||||||
|
return
|
||||||
|
self._set_loading(True)
|
||||||
|
self._async.run(asyncio.to_thread(export_inventory, report, path,
|
||||||
|
headers=[self._t("inventory.col." + k) for k in KEYS],
|
||||||
|
detail_headers=[self._t("inventory.col." + k) for k in DETAIL_KEYS],
|
||||||
|
translate=self._t, ordered_rows=list(self._rows)),
|
||||||
|
lambda _: self._exported(path), self._error,
|
||||||
|
busy=self._busy, message=self._t("inventory.export_busy"))
|
||||||
|
|
||||||
|
def _exported(self, path):
|
||||||
|
self._set_loading(False)
|
||||||
|
messagebox.showinfo(self._t("inventory.title"), self._t("inventory.exported").format(path=path), parent=self)
|
||||||
|
|
||||||
|
|
||||||
|
ZERO_SORT = Decimal(0)
|
||||||
|
|
||||||
|
|
||||||
|
def open_inventario_window(parent, db_client, session=None):
|
||||||
|
"""Create the launcher-managed window with the same placement as other forms."""
|
||||||
|
win = InventarioWindow(parent, db_client, session=session)
|
||||||
|
place_window_fullsize_below_parent_later(parent, win)
|
||||||
|
win.bind("<Escape>", lambda _: win.destroy())
|
||||||
|
return win
|
||||||
155
inventory_report.sql
Normal file
155
inventory_report.sql
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
-- Read-only runtime query: cutoff and sam_cutoff are exclusive next-day bounds.
|
||||||
|
-- Writes only session-local temp tables; never alters SAM/WMS objects or stock.
|
||||||
|
SET NOCOUNT ON;
|
||||||
|
SET XACT_ABORT ON;
|
||||||
|
SET LOCK_TIMEOUT 15000;
|
||||||
|
DECLARE @cutoff datetime2 = :cutoff, @sam_cutoff float = :sam_cutoff;
|
||||||
|
DECLARE @warehouse int;
|
||||||
|
IF (SELECT COUNT(*) FROM SAMA1.dbo.ANAMAG
|
||||||
|
WHERE LTRIM(RTRIM(DESCR))='Magazzino Principale')<>1
|
||||||
|
THROW 51200, 'Magazzino Principale SAM assente o ambiguo.', 1;
|
||||||
|
SELECT @warehouse=ID FROM SAMA1.dbo.ANAMAG
|
||||||
|
WHERE LTRIM(RTRIM(DESCR))='Magazzino Principale';
|
||||||
|
SELECT ID INTO #inv_slots FROM SAMA1.dbo.ALLMAG WHERE IDANAMAG=@warehouse;
|
||||||
|
CREATE UNIQUE CLUSTERED INDEX ix_slots ON #inv_slots(ID);
|
||||||
|
|
||||||
|
SELECT LTRIM(RTRIM(Attributo)) COLLATE DATABASE_DEFAULT AS Pallet, IDCella,
|
||||||
|
SUM(CASE Tipo WHEN 'V' THEN CAST(PesoUnitario AS decimal(28,6))
|
||||||
|
WHEN 'P' THEN -CAST(PesoUnitario AS decimal(28,6)) END) AS Balance
|
||||||
|
INTO #inv_balance FROM dbo.MagazziniPallet
|
||||||
|
WHERE DataMagazzino<@cutoff AND Tipo IN ('P','V')
|
||||||
|
GROUP BY LTRIM(RTRIM(Attributo)),IDCella;
|
||||||
|
CREATE INDEX ix_balance ON #inv_balance(Pallet);
|
||||||
|
SELECT Pallet, COUNT(CASE WHEN Balance>0 THEN 1 END) AS Locations,
|
||||||
|
COUNT(CASE WHEN Balance<0 THEN 1 END) AS NegativeBalances,
|
||||||
|
MAX(CASE WHEN IDCella=9999 AND Balance>0 THEN 1 ELSE 0 END) AS Shipped
|
||||||
|
INTO #inv_position FROM #inv_balance GROUP BY Pallet;
|
||||||
|
CREATE UNIQUE CLUSTERED INDEX ix_position ON #inv_position(Pallet);
|
||||||
|
SELECT b.*,CONCAT(RTRIM(c.Corsia),'.',RTRIM(c.Colonna),'.',RTRIM(c.Fila)) AS Location
|
||||||
|
INTO #inv_stock FROM #inv_balance b
|
||||||
|
JOIN dbo.Celle c ON c.ID=b.IDCella
|
||||||
|
JOIN dbo.Aree a ON a.ID=c.IDArea
|
||||||
|
JOIN dbo.Magazzini w ON w.ID=a.IDMagazzino
|
||||||
|
WHERE b.Balance>0 AND (b.IDCella=1000 OR
|
||||||
|
(b.IDCella<>9999 AND UPPER(RTRIM(w.Descrizione)) IN ('MDE5','MDE6')));
|
||||||
|
CREATE INDEX ix_stock ON #inv_stock(Pallet);
|
||||||
|
|
||||||
|
-- First change AFTER cutoff supplies the OLD serial valid at cutoff.
|
||||||
|
-- Same-timestamp ties have no ordering key: flag them instead of certifying them.
|
||||||
|
SELECT IDLOTSER,MIN(AGGIORNAMENTO) AS FirstAfter
|
||||||
|
INTO #inv_change_time FROM SAMA1.dbo.EXTTACLOTSER
|
||||||
|
WHERE AGGIORNAMENTO>=@cutoff GROUP BY IDLOTSER;
|
||||||
|
CREATE UNIQUE CLUSTERED INDEX ix_time ON #inv_change_time(IDLOTSER);
|
||||||
|
SELECT h.IDLOTSER,MIN(RTRIM(h.EXNUMSER)) COLLATE DATABASE_DEFAULT AS Serial,
|
||||||
|
CASE WHEN COUNT(*)>1 THEN 1 ELSE 0 END AS AssignmentIssue
|
||||||
|
INTO #inv_old FROM SAMA1.dbo.EXTTACLOTSER h
|
||||||
|
JOIN #inv_change_time t ON t.IDLOTSER=h.IDLOTSER AND t.FirstAfter=h.AGGIORNAMENTO
|
||||||
|
GROUP BY h.IDLOTSER;
|
||||||
|
CREATE UNIQUE CLUSTERED INDEX ix_old ON #inv_old(IDLOTSER);
|
||||||
|
|
||||||
|
SELECT ls.ID,ls.IDARTICO,RTRIM(ls.NUMLOT) COLLATE DATABASE_DEFAULT AS Lot,
|
||||||
|
COALESCE(o.Serial,RTRIM(ls.NUMSER) COLLATE DATABASE_DEFAULT) AS Serial,
|
||||||
|
ISNULL(o.AssignmentIssue,0) AS AssignmentIssue
|
||||||
|
INTO #inv_wms_labels FROM SAMA1.dbo.LOTSER ls
|
||||||
|
LEFT JOIN #inv_old o ON o.IDLOTSER=ls.ID
|
||||||
|
WHERE EXISTS(SELECT 1 FROM #inv_stock s WHERE s.Pallet=
|
||||||
|
LEFT(COALESCE(o.Serial,RTRIM(ls.NUMSER) COLLATE DATABASE_DEFAULT),6));
|
||||||
|
|
||||||
|
-- Scope by PRODUCT + LOT in WMS, not all products and not a P% convention.
|
||||||
|
SELECT DISTINCT IDARTICO,Lot INTO #inv_scope FROM #inv_wms_labels;
|
||||||
|
CREATE UNIQUE CLUSTERED INDEX ix_scope ON #inv_scope(IDARTICO,Lot);
|
||||||
|
SELECT ls.ID,ls.IDARTICO,RTRIM(ls.NUMLOT) COLLATE DATABASE_DEFAULT AS Lot,
|
||||||
|
COALESCE(o.Serial,RTRIM(ls.NUMSER) COLLATE DATABASE_DEFAULT) AS Serial,
|
||||||
|
ISNULL(o.AssignmentIssue,0) AS AssignmentIssue
|
||||||
|
INTO #inv_labels FROM SAMA1.dbo.LOTSER ls
|
||||||
|
JOIN #inv_scope sc ON sc.IDARTICO=ls.IDARTICO
|
||||||
|
AND sc.Lot=RTRIM(ls.NUMLOT) COLLATE DATABASE_DEFAULT
|
||||||
|
LEFT JOIN #inv_old o ON o.IDLOTSER=ls.ID;
|
||||||
|
CREATE UNIQUE CLUSTERED INDEX ix_labels ON #inv_labels(ID);
|
||||||
|
|
||||||
|
-- SAM balance per CONTAINER; B/C are never fabricated as SAM minus A.
|
||||||
|
SELECT l.ID,SUM(CAST(g.QTTGIAI AS decimal(28,6))) AS Quantity
|
||||||
|
INTO #inv_now FROM #inv_labels l
|
||||||
|
JOIN SAMA1.dbo.GIAMAG g ON g.IDARTICO=l.ID
|
||||||
|
JOIN #inv_slots s ON s.ID=g.IDMAG GROUP BY l.ID;
|
||||||
|
|
||||||
|
SELECT m.IDARTICO AS ID,m.DATMOV,CAST(m.QTAINV AS decimal(28,6)) AS Quantity,
|
||||||
|
RTRIM(c.CODICE) AS Cause,
|
||||||
|
CASE WHEN sp.ID IS NOT NULL THEN
|
||||||
|
CASE c.QTGIUP WHEN '+' THEN 1 WHEN '-' THEN -1 ELSE 0 END ELSE 0 END
|
||||||
|
+ CASE WHEN sa.ID IS NOT NULL THEN
|
||||||
|
CASE c.QTGIUA WHEN '+' THEN 1 WHEN '-' THEN -1 ELSE 0 END ELSE 0 END AS Sign,
|
||||||
|
CASE WHEN sa.ID IS NOT NULL AND c.QTGIUA='+' THEN 1 ELSE 0 END AS Receipt,
|
||||||
|
CASE WHEN c.ID IS NULL OR
|
||||||
|
(sp.ID IS NOT NULL AND ISNULL(RTRIM(c.QTGIUP),'') NOT IN ('','+','-')) OR
|
||||||
|
(sa.ID IS NOT NULL AND ISNULL(RTRIM(c.QTGIUA),'') NOT IN ('','+','-'))
|
||||||
|
THEN 1 ELSE 0 END AS CauseIssue
|
||||||
|
INTO #inv_moves FROM #inv_labels l
|
||||||
|
JOIN SAMA1.dbo.MOVMAG m ON m.IDARTICO=l.ID
|
||||||
|
LEFT JOIN SAMA1.dbo.CAUMOV c ON c.ID=m.IDCAUMOV
|
||||||
|
LEFT JOIN #inv_slots sp ON sp.ID=m.IDMAGPAR
|
||||||
|
LEFT JOIN #inv_slots sa ON sa.ID=m.IDMAGARR
|
||||||
|
WHERE sp.ID IS NOT NULL OR sa.ID IS NOT NULL;
|
||||||
|
CREATE INDEX ix_moves ON #inv_moves(ID);
|
||||||
|
SELECT ID,
|
||||||
|
SUM(CASE WHEN DATMOV>=@sam_cutoff THEN Quantity*Sign ELSE 0 END) AS AfterQuantity,
|
||||||
|
SUM(CASE WHEN DATMOV<@sam_cutoff AND Cause='CP' THEN Quantity*Sign END) AS Nominal,
|
||||||
|
SUM(CASE WHEN DATMOV IS NULL OR Quantity IS NULL OR CauseIssue=1 THEN 1 ELSE 0 END) AS MovementIssues,
|
||||||
|
SUM(CASE WHEN DATMOV<@sam_cutoff AND Receipt=1 AND Cause<>'CP' THEN 1 ELSE 0 END) AS OtherReceipts
|
||||||
|
INTO #inv_quantities FROM #inv_moves GROUP BY ID;
|
||||||
|
|
||||||
|
CREATE TABLE #inv_result (
|
||||||
|
Kind varchar(8) NULL, Component varchar(8) NULL,
|
||||||
|
Product nvarchar(255) NULL, Description nvarchar(1000) NULL, Unit nvarchar(32) NULL,
|
||||||
|
ContainerId int NULL, Lot nvarchar(255) NULL, Serial nvarchar(255) NULL,
|
||||||
|
Pallet nvarchar(64) NULL, Cell int NULL, Location nvarchar(255) NULL,
|
||||||
|
Balance decimal(38,6) NULL, Quantity decimal(38,6) NULL, SamQuantity decimal(38,6) NULL,
|
||||||
|
Locations int NULL, NegativeBalances int NULL, Shipped int NULL,
|
||||||
|
AssignmentIssue int NULL, MovementIssues int NULL, OtherReceipts int NULL,
|
||||||
|
SourceDate datetime2 NULL
|
||||||
|
);
|
||||||
|
INSERT INTO #inv_result
|
||||||
|
SELECT CAST('ROW' AS varchar(8)) AS Kind,
|
||||||
|
CAST(CASE WHEN s.Pallet IS NOT NULL THEN 'A'
|
||||||
|
WHEN LEFT(l.Serial,6)='000000' THEN 'C'
|
||||||
|
WHEN ISNULL(p.Locations,0)>0 OR ISNULL(p.NegativeBalances,0)>0 THEN 'X'
|
||||||
|
WHEN LEN(l.Serial)<8 OR SUBSTRING(l.Serial,7,1)<>'/' THEN 'X'
|
||||||
|
ELSE 'B' END AS varchar(8)) AS Component,
|
||||||
|
RTRIM(a.CODICE) AS Product,RTRIM(a.DESCR) AS Description,RTRIM(a.UMI) AS Unit,
|
||||||
|
l.ID AS ContainerId,l.Lot,l.Serial,
|
||||||
|
LEFT(l.Serial,6) AS Pallet,s.IDCella AS Cell,s.Location,s.Balance,
|
||||||
|
CASE WHEN s.Pallet IS NOT NULL THEN q.Nominal
|
||||||
|
ELSE ISNULL(n.Quantity,0)-ISNULL(q.AfterQuantity,0) END AS Quantity,
|
||||||
|
ISNULL(n.Quantity,0)-ISNULL(q.AfterQuantity,0) AS SamQuantity,
|
||||||
|
ISNULL(p.Locations,0) AS Locations,ISNULL(p.NegativeBalances,0) AS NegativeBalances,
|
||||||
|
ISNULL(p.Shipped,0) AS Shipped,l.AssignmentIssue,
|
||||||
|
ISNULL(q.MovementIssues,0) AS MovementIssues,ISNULL(q.OtherReceipts,0) AS OtherReceipts,
|
||||||
|
CAST(NULL AS datetime2) AS SourceDate
|
||||||
|
FROM #inv_labels l
|
||||||
|
LEFT JOIN SAMA1.dbo.ARTICO a ON a.ID=l.IDARTICO
|
||||||
|
LEFT JOIN #inv_now n ON n.ID=l.ID
|
||||||
|
LEFT JOIN #inv_quantities q ON q.ID=l.ID
|
||||||
|
LEFT JOIN #inv_position p ON p.Pallet=LEFT(l.Serial,6)
|
||||||
|
LEFT JOIN #inv_stock s ON s.Pallet=LEFT(l.Serial,6)
|
||||||
|
WHERE s.Pallet IS NOT NULL OR ISNULL(n.Quantity,0)-ISNULL(q.AfterQuantity,0)<>0
|
||||||
|
OR ISNULL(q.MovementIssues,0)>0;
|
||||||
|
|
||||||
|
-- WMS presence with no recognizable label must remain visible.
|
||||||
|
INSERT INTO #inv_result(Kind,Component,Pallet,Cell,Location,Balance,Locations,
|
||||||
|
NegativeBalances,Shipped,AssignmentIssue,MovementIssues,OtherReceipts)
|
||||||
|
SELECT 'ROW','A',s.Pallet,s.IDCella,s.Location,s.Balance,p.Locations,
|
||||||
|
p.NegativeBalances,p.Shipped,0,0,0
|
||||||
|
FROM #inv_stock s JOIN #inv_position p ON p.Pallet=s.Pallet
|
||||||
|
WHERE NOT EXISTS(SELECT 1 FROM #inv_wms_labels l WHERE LEFT(l.Serial,6)=s.Pallet);
|
||||||
|
|
||||||
|
-- One result set, as required by the shared async SQL client.
|
||||||
|
INSERT INTO #inv_result(Kind,Component,SourceDate)
|
||||||
|
SELECT 'META','WMS_MAX',MAX(DataMagazzino) FROM dbo.MagazziniPallet;
|
||||||
|
INSERT INTO #inv_result(Kind,Component,SourceDate)
|
||||||
|
SELECT 'META','SAM_MAX',DATEADD(day,CAST(MAX(DATMOV) AS int),CAST('1899-12-30' AS datetime2))
|
||||||
|
FROM SAMA1.dbo.MOVMAG;
|
||||||
|
INSERT INTO #inv_result(Kind,Component,SourceDate)
|
||||||
|
SELECT 'META','HIST_MIN',MIN(AGGIORNAMENTO) FROM SAMA1.dbo.EXTTACLOTSER;
|
||||||
|
INSERT INTO #inv_result(Kind,Component,Quantity)
|
||||||
|
SELECT 'META','UNDATED',COUNT(*) FROM dbo.MagazziniPallet WHERE DataMagazzino IS NULL;
|
||||||
|
SELECT * FROM #inv_result;
|
||||||
271
inventory_service.py
Normal file
271
inventory_service.py
Normal file
@@ -0,0 +1,271 @@
|
|||||||
|
"""Read-only WMS/SAM reconciliation by product and lot; see specifica_inventario.md."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import date, datetime, time, timedelta
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from version_info import module_version
|
||||||
|
|
||||||
|
__version__ = module_version(__name__)
|
||||||
|
SQL_PATH = Path(__file__).with_name("inventory_report.sql")
|
||||||
|
ZERO = Decimal("0")
|
||||||
|
SUMMARY_KEYS = ("Product", "Description", "Unit", "UDCs", "Shelved", "NonShelved",
|
||||||
|
"WMS", "PackingUDCs", "Packing", "LooseContainers", "Loose",
|
||||||
|
"Reconstructed", "SAM", "InitialDifference", "Difference", "Status")
|
||||||
|
DETAIL_KEYS = ("Component", "Product", "Lot", "Pallet", "ContainerId", "Serial",
|
||||||
|
"Location", "Quantity", "SamQuantity", "Status")
|
||||||
|
LOT_KEYS = ("Product", "Lot") + SUMMARY_KEYS[2:]
|
||||||
|
|
||||||
|
|
||||||
|
def inventory_cutoff(value: str, *, today: date | None = None) -> tuple[date, datetime, int]:
|
||||||
|
"""Parse a day, not an instant; use the exclusive following midnight."""
|
||||||
|
selected = datetime.strptime(value.strip(), "%d/%m/%Y").date()
|
||||||
|
if selected > (today or date.today()) or selected < date(2010, 1, 1):
|
||||||
|
raise ValueError("date_range")
|
||||||
|
cutoff = datetime.combine(selected + timedelta(days=1), time.min)
|
||||||
|
return selected, cutoff, (cutoff - datetime(1899, 12, 30)).days
|
||||||
|
|
||||||
|
|
||||||
|
def number(value: Any) -> Decimal:
|
||||||
|
"""Convert SQL decimals without introducing floating-point summation."""
|
||||||
|
return Decimal(str(value)) if value is not None else ZERO
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class InventoryReport:
|
||||||
|
selected_date: date
|
||||||
|
rows: list[dict[str, Any]]
|
||||||
|
details: list[dict[str, Any]]
|
||||||
|
metadata: dict[str, Any]
|
||||||
|
lots: list[dict[str, Any]]
|
||||||
|
|
||||||
|
|
||||||
|
def _bucket(product, description, unit, lot=""):
|
||||||
|
return dict(Product=product, Description=description, Unit=unit, Lot=lot,
|
||||||
|
UDCs=set(), PackingUDCs=set(), LooseContainers=set(),
|
||||||
|
Shelved=ZERO, NonShelved=ZERO, Packing=ZERO, Loose=ZERO, SAM=ZERO,
|
||||||
|
Issues=set(), Invalid=set())
|
||||||
|
|
||||||
|
|
||||||
|
def build_report(selected_date: date, records: list[dict[str, Any]]) -> InventoryReport:
|
||||||
|
"""Count each container once; retain anomalies instead of manufacturing balance.
|
||||||
|
|
||||||
|
A uses production receipt quantities, independently of current SAM balance.
|
||||||
|
B/C use the dated container balance. X is unclassified/conflicting SAM stock;
|
||||||
|
it contributes to SAM, never silently to B. Aggregation begins at product/lot.
|
||||||
|
"""
|
||||||
|
metadata = {r["Component"]: (r.get("Quantity") if r["Component"] == "UNDATED"
|
||||||
|
else r.get("SourceDate"))
|
||||||
|
for r in records if r["Kind"] == "META"}
|
||||||
|
history_start = metadata.get("HIST_MIN")
|
||||||
|
history_unknown = not history_start or selected_date < history_start.date()
|
||||||
|
products, lots, details, seen = {}, {}, [], {}
|
||||||
|
for record in records:
|
||||||
|
if record["Kind"] == "META":
|
||||||
|
continue
|
||||||
|
r = dict(record)
|
||||||
|
pallet = str(r.get("Pallet") or "").strip()
|
||||||
|
product = str(r.get("Product") or "").strip() or f"? UDC {pallet}"
|
||||||
|
lot = str(r.get("Lot") or "").strip()
|
||||||
|
unit = str(r.get("Unit") or "").strip().upper()
|
||||||
|
component = r["Component"]
|
||||||
|
quantity = None if r.get("Quantity") is None else number(r["Quantity"])
|
||||||
|
sam_quantity = None if r.get("SamQuantity") is None else number(r["SamQuantity"])
|
||||||
|
issues, invalid = set(), set()
|
||||||
|
if unit not in {"NR", "PZ", "PCS"}:
|
||||||
|
issues.add("unit")
|
||||||
|
invalid.update(("A", "B", "C", "SAM"))
|
||||||
|
if r.get("AssignmentIssue") or history_unknown:
|
||||||
|
issues.add("history")
|
||||||
|
invalid.update(("A", "B", "C"))
|
||||||
|
if metadata.get("UNDATED"):
|
||||||
|
issues.add("undated")
|
||||||
|
invalid.update(("A", "B", "C"))
|
||||||
|
if r.get("MovementIssues") or sam_quantity is None:
|
||||||
|
issues.add("movements")
|
||||||
|
invalid.update(("A", "B", "C", "SAM"))
|
||||||
|
if sam_quantity is not None and sam_quantity < 0:
|
||||||
|
issues.add("negative")
|
||||||
|
invalid.add("SAM")
|
||||||
|
serial = str(r.get("Serial") or "").strip()
|
||||||
|
if len(serial) < 8 or serial[6:7] != "/" or not serial[7:].strip():
|
||||||
|
issues.add("serial")
|
||||||
|
invalid.add(component)
|
||||||
|
if component == "A":
|
||||||
|
if quantity is None or quantity <= 0 or r.get("OtherReceipts"):
|
||||||
|
issues.add("content")
|
||||||
|
invalid.add("A")
|
||||||
|
if r.get("Locations") != 1:
|
||||||
|
issues.add("locations")
|
||||||
|
invalid.add("A")
|
||||||
|
if number(r.get("Balance")) != 1 or r.get("NegativeBalances"):
|
||||||
|
issues.add("balance")
|
||||||
|
invalid.add("A")
|
||||||
|
if r.get("Shipped"):
|
||||||
|
issues.add("shipped")
|
||||||
|
invalid.add("A")
|
||||||
|
elif component in ("B", "C"):
|
||||||
|
if quantity is None or quantity <= 0:
|
||||||
|
issues.add("content")
|
||||||
|
invalid.add(component)
|
||||||
|
if r.get("Shipped") or r.get("Locations") or r.get("NegativeBalances"):
|
||||||
|
issues.add("shipped" if r.get("Shipped") else "outside")
|
||||||
|
invalid.add(component)
|
||||||
|
else:
|
||||||
|
issues.add("shipped" if r.get("Shipped") else "outside")
|
||||||
|
bucket = lots.setdefault((product, lot), _bucket(product, r.get("Description") or "", unit, lot))
|
||||||
|
if bucket["Unit"] != unit:
|
||||||
|
issues.add("unit")
|
||||||
|
invalid.update(("A", "B", "C", "SAM"))
|
||||||
|
bucket["Issues"].update(issues)
|
||||||
|
bucket["Invalid"].update(invalid)
|
||||||
|
if component == "A":
|
||||||
|
bucket["UDCs"].add(pallet)
|
||||||
|
elif component == "B":
|
||||||
|
bucket["PackingUDCs"].add(pallet)
|
||||||
|
elif component == "C":
|
||||||
|
bucket["LooseContainers"].add(r.get("ContainerId"))
|
||||||
|
# Anomaly details can have several locations, but SAM must not be doubled.
|
||||||
|
identity = r.get("ContainerId") or ("missing", pallet)
|
||||||
|
key = (product, lot, identity)
|
||||||
|
fingerprint = (component, quantity, sam_quantity, pallet)
|
||||||
|
if key not in seen:
|
||||||
|
bucket["SAM"] += sam_quantity or ZERO
|
||||||
|
field = ("NonShelved" if r.get("Cell") == 1000 else "Shelved") if component == "A" else {
|
||||||
|
"B": "Packing", "C": "Loose"}.get(component)
|
||||||
|
if field and quantity is not None:
|
||||||
|
bucket[field] += quantity
|
||||||
|
seen[key] = fingerprint
|
||||||
|
elif seen[key] != fingerprint:
|
||||||
|
bucket["Issues"].add("duplicate")
|
||||||
|
bucket["Invalid"].update(("A", "B", "C", "SAM"))
|
||||||
|
issues.add("duplicate")
|
||||||
|
details.append(dict(Component=component, Product=product, Lot=lot,
|
||||||
|
Pallet="" if pallet == "000000" else pallet,
|
||||||
|
ContainerId=r.get("ContainerId"), Serial=serial,
|
||||||
|
Cell=r.get("Cell"), Location=r.get("Location") or "",
|
||||||
|
Quantity=None if component in invalid else quantity,
|
||||||
|
SamQuantity=None if "SAM" in invalid else sam_quantity,
|
||||||
|
Issues=tuple(sorted(issues))))
|
||||||
|
# Aggregate lots without summing their distinct-UDC counts.
|
||||||
|
for bucket in lots.values():
|
||||||
|
total = products.setdefault(bucket["Product"], _bucket(
|
||||||
|
bucket["Product"], bucket["Description"], bucket["Unit"]))
|
||||||
|
if total["Unit"] != bucket["Unit"]:
|
||||||
|
total["Issues"].add("unit")
|
||||||
|
total["Invalid"].update(("A", "B", "C", "SAM"))
|
||||||
|
for key in ("UDCs", "PackingUDCs", "LooseContainers", "Issues", "Invalid"):
|
||||||
|
total[key].update(bucket[key])
|
||||||
|
for key in ("Shelved", "NonShelved", "Packing", "Loose", "SAM"):
|
||||||
|
total[key] += bucket[key]
|
||||||
|
def finish(row):
|
||||||
|
invalid = row.pop("Invalid")
|
||||||
|
for key in ("UDCs", "PackingUDCs", "LooseContainers"):
|
||||||
|
row[key] = len(row[key])
|
||||||
|
if "A" in invalid:
|
||||||
|
row["Shelved"] = row["NonShelved"] = None
|
||||||
|
for component, field in (("B", "Packing"), ("C", "Loose"), ("SAM", "SAM")):
|
||||||
|
if component in invalid:
|
||||||
|
row[field] = None
|
||||||
|
row["WMS"] = add_known(row["Shelved"], row["NonShelved"])
|
||||||
|
row["Reconstructed"] = add_known(row["WMS"], row["Packing"], row["Loose"])
|
||||||
|
row["InitialDifference"] = subtract_known(row["SAM"], row["WMS"])
|
||||||
|
row["Difference"] = subtract_known(row["SAM"], row["Reconstructed"])
|
||||||
|
row["Issues"] = tuple(sorted(row["Issues"]))
|
||||||
|
return row
|
||||||
|
lot_rows = [finish(lots[k]) for k in sorted(lots)]
|
||||||
|
product_rows = [finish(products[k]) for k in sorted(products)]
|
||||||
|
for row in product_rows:
|
||||||
|
if row["Difference"] == 0 and any(
|
||||||
|
lot["Product"] == row["Product"] and lot["Difference"] not in (None, ZERO)
|
||||||
|
for lot in lot_rows):
|
||||||
|
row["Issues"] = tuple(sorted(set(row["Issues"]) | {"lot_offsets"}))
|
||||||
|
return InventoryReport(selected_date,
|
||||||
|
product_rows,
|
||||||
|
sorted(details, key=lambda r: (r["Product"], r["Lot"], r["Component"],
|
||||||
|
r["Pallet"], r["Serial"], str(r["Cell"]))),
|
||||||
|
metadata, lot_rows)
|
||||||
|
|
||||||
|
|
||||||
|
def add_known(*values):
|
||||||
|
return None if any(v is None for v in values) else sum(values, ZERO)
|
||||||
|
|
||||||
|
|
||||||
|
def subtract_known(left, right):
|
||||||
|
return None if left is None or right is None else left - right
|
||||||
|
|
||||||
|
|
||||||
|
async def load_inventory(db_client, value: str) -> InventoryReport:
|
||||||
|
"""Use the existing asynchronous DB client; no commit or stock mutation."""
|
||||||
|
selected, cutoff, sam_cutoff = inventory_cutoff(value)
|
||||||
|
result = await db_client.query_json(SQL_PATH.read_text(encoding="utf-8"),
|
||||||
|
{"cutoff": cutoff, "sam_cutoff": sam_cutoff}, as_dict_rows=True)
|
||||||
|
return build_report(selected, result["rows"])
|
||||||
|
|
||||||
|
|
||||||
|
def status_text(row, translate):
|
||||||
|
if row["Issues"]:
|
||||||
|
return "; ".join(translate("inventory.issue." + issue) for issue in row["Issues"])
|
||||||
|
return translate("inventory.match" if row["Difference"] == 0 else "inventory.mismatch")
|
||||||
|
|
||||||
|
|
||||||
|
def detail_values(row, translate):
|
||||||
|
"""Use identical localized labels in GUI and exported container details."""
|
||||||
|
values = dict(row)
|
||||||
|
values["Component"] = translate("inventory.component." + row["Component"])
|
||||||
|
if not values["Location"] and row["Component"] in ("B", "C"):
|
||||||
|
values["Location"] = translate("inventory.inferred_location")
|
||||||
|
values["Status"] = "; ".join(translate("inventory.issue." + issue) for issue in row["Issues"])
|
||||||
|
return [values[k] for k in DETAIL_KEYS]
|
||||||
|
|
||||||
|
|
||||||
|
def export_inventory(report: InventoryReport, path: str, *, headers=None,
|
||||||
|
detail_headers=None, translate, ordered_rows=None) -> None:
|
||||||
|
"""Export product, lot and container views with typed cells and provenance."""
|
||||||
|
from openpyxl import Workbook
|
||||||
|
from openpyxl.styles import Font, PatternFill
|
||||||
|
from openpyxl.utils import get_column_letter
|
||||||
|
|
||||||
|
wb = Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = translate("inventory.title")
|
||||||
|
ws.append([translate("inventory.date"), report.selected_date])
|
||||||
|
ws["B1"].number_format = "DD/MM/YYYY"
|
||||||
|
ws.append([translate("inventory.notice")])
|
||||||
|
ws.append([translate("inventory.scope")])
|
||||||
|
ws.append([translate("inventory.sources"), str(report.metadata)])
|
||||||
|
ws.append([translate("inventory.history_notice")])
|
||||||
|
ws.append(headers or [translate("inventory.col." + k) for k in SUMMARY_KEYS])
|
||||||
|
for row in ordered_rows if ordered_rows is not None else report.rows:
|
||||||
|
ws.append([row[k] for k in SUMMARY_KEYS[:-1]] + [status_text(row, translate)])
|
||||||
|
ls = wb.create_sheet(translate("inventory.lot_sheet"))
|
||||||
|
ls.append([translate("inventory.col." + k) for k in LOT_KEYS])
|
||||||
|
for row in report.lots:
|
||||||
|
ls.append([row[k] for k in LOT_KEYS[:-1]] + [status_text(row, translate)])
|
||||||
|
ds = wb.create_sheet(translate("inventory.detail_sheet"))
|
||||||
|
ds.append(detail_headers or [translate("inventory.col." + k) for k in DETAIL_KEYS])
|
||||||
|
for row in report.details:
|
||||||
|
ds.append(detail_values(row, translate))
|
||||||
|
for sheet, header_row in ((ws, 6), (ls, 1), (ds, 1)):
|
||||||
|
sheet.freeze_panes = f"A{header_row + 1}"
|
||||||
|
sheet.auto_filter.ref = f"A{header_row}:{get_column_letter(sheet.max_column)}{sheet.max_row}"
|
||||||
|
for cell in sheet[header_row]:
|
||||||
|
cell.font = Font(bold=True, color="000000")
|
||||||
|
cell.fill = PatternFill("solid", fgColor="BFC4CA")
|
||||||
|
for row in sheet.iter_rows():
|
||||||
|
for cell in row:
|
||||||
|
if isinstance(cell.value, str):
|
||||||
|
cell.data_type = "s"
|
||||||
|
elif isinstance(cell.value, (Decimal, float, int)):
|
||||||
|
cell.number_format = '#,##0.######;[Red]-#,##0.######;0'
|
||||||
|
if cell.row > header_row and cell.row % 2 == 0:
|
||||||
|
cell.fill = PatternFill("solid", fgColor="F0F0F0")
|
||||||
|
for col in range(1, sheet.max_column + 1):
|
||||||
|
sheet.column_dimensions[get_column_letter(col)].width = 24
|
||||||
|
try:
|
||||||
|
wb.save(path)
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
134
locale.json
134
locale.json
@@ -1,9 +1,68 @@
|
|||||||
{
|
{
|
||||||
"default_language": "IT",
|
"default_language": "IT",
|
||||||
"IT": {
|
"IT": {
|
||||||
"picking.pair.selection_hint": "Ordine di selezione: {documents}. Conferma con Prenota.",
|
"inventory.title": "Inventario",
|
||||||
"picking.pair.max_two": "Seleziona al massimo due liste.",
|
"inventory.date": "Data (gg/mm/aaaa):",
|
||||||
"picking.pair.sequence_blocked": "Personalizzazione disponibile solo per una lista non abbinata.",
|
"inventory.load": "Calcola inventario",
|
||||||
|
"inventory.export": "Esporta XLSX",
|
||||||
|
"inventory.notice": "A: UDC WMS. B: UDC fuori WMS, confezionamento presunto. C: bag/vasche senza UDC. Residuo = SAM - (A+B+C). '?' indica dati non determinabili.",
|
||||||
|
"inventory.scope": "Perimetro provvisorio: solo prodotti/lotti delle UDC in aree 5 e 6 o non scaffalate alla data. Non e' l'inventario completo SAM.",
|
||||||
|
"inventory.history_notice": "Ricostruzione da movimenti e storico NUMSER disponibile, non inventario fisico certificato. Validare le etichette e la completezza dello storico.",
|
||||||
|
"inventory.sources": "Ultimi movimenti nelle fonti (non data di aggiornamento del backup)",
|
||||||
|
"inventory.detail": "Lotti e contenitori del prodotto selezionato",
|
||||||
|
"inventory.detail_sheet": "Contenitori",
|
||||||
|
"inventory.lot_sheet": "Lotti",
|
||||||
|
"inventory.inferred_location": "Confezionamento (dedotto)",
|
||||||
|
"inventory.component.A": "A - WMS",
|
||||||
|
"inventory.component.B": "B - UDC fuori WMS",
|
||||||
|
"inventory.component.C": "C - Senza UDC",
|
||||||
|
"inventory.component.X": "X - Anomalia / fuori perimetro",
|
||||||
|
"inventory.today": "Giornata corrente non ancora conclusa: il risultato comprende solo i movimenti gia' registrati.",
|
||||||
|
"inventory.bad_date": "Inserisci una data valida gg/mm/aaaa, dal 01/01/2010 a oggi.",
|
||||||
|
"inventory.busy": "Ricostruisco l'inventario alla data scelta...",
|
||||||
|
"inventory.loaded": "Inventario al {date} (fine giornata) | Prodotti: {count} | Da verificare: {unknown}\nUltimo movimento WMS: {wms} | Ultimo movimento SAM: {sam}. Eseguire a movimentazioni ferme; verificare che i backup siano coerenti.",
|
||||||
|
"inventory.failed": "Operazione non completata. Nessun dato del magazzino modificato.",
|
||||||
|
"inventory.export_busy": "Esporto inventario...",
|
||||||
|
"inventory.exported": "File creato:\n{path}",
|
||||||
|
"inventory.match": "Saldo coerente (nominale)",
|
||||||
|
"inventory.mismatch": "Differenza da verificare",
|
||||||
|
"inventory.issue.content": "Contenuto UDC non determinabile",
|
||||||
|
"inventory.issue.locations": "UDC in piu' locazioni",
|
||||||
|
"inventory.issue.balance": "Saldo movimenti UDC anomalo",
|
||||||
|
"inventory.issue.unit": "Unita' di misura da verificare",
|
||||||
|
"inventory.issue.undated": "Movimenti WMS privi di data",
|
||||||
|
"inventory.issue.history": "Assegnazione storica non determinabile",
|
||||||
|
"inventory.issue.movements": "Movimenti o saldo SAM non determinabili",
|
||||||
|
"inventory.issue.negative": "Giacenza SAM negativa",
|
||||||
|
"inventory.issue.serial": "Seriale contenitore mancante o non valido",
|
||||||
|
"inventory.issue.shipped": "Spedita WMS ma presenza residua da verificare",
|
||||||
|
"inventory.issue.outside": "Presenza fuori perimetro / classificazione anomala",
|
||||||
|
"inventory.issue.duplicate": "Contenitore duplicato con dati incompatibili",
|
||||||
|
"inventory.issue.lot_offsets": "Differenze tra lotti si compensano: verificare il dettaglio",
|
||||||
|
"inventory.col.Product": "Prodotto",
|
||||||
|
"inventory.col.Description": "Descrizione",
|
||||||
|
"inventory.col.Unit": "UM",
|
||||||
|
"inventory.col.UDCs": "N. UDC WMS",
|
||||||
|
"inventory.col.Shelved": "Pezzi scaffalati",
|
||||||
|
"inventory.col.NonShelved": "Pezzi non scaffalati",
|
||||||
|
"inventory.col.WMS": "Pezzi WMS",
|
||||||
|
"inventory.col.SAM": "Pezzi SAM",
|
||||||
|
"inventory.col.Difference": "Residuo SAM-(A+B+C)",
|
||||||
|
"inventory.col.InitialDifference": "Differenza SAM-A",
|
||||||
|
"inventory.col.PackingUDCs": "N. UDC fuori WMS",
|
||||||
|
"inventory.col.Packing": "Pezzi B - UDC fuori WMS",
|
||||||
|
"inventory.col.LooseContainers": "N. contenitori senza UDC",
|
||||||
|
"inventory.col.Loose": "Pezzi C - Senza UDC",
|
||||||
|
"inventory.col.Reconstructed": "Totale A+B+C",
|
||||||
|
"inventory.col.Component": "Componente",
|
||||||
|
"inventory.col.Lot": "Lotto",
|
||||||
|
"inventory.col.ContainerId": "ID LOTSER",
|
||||||
|
"inventory.col.Serial": "Seriale contenitore",
|
||||||
|
"inventory.col.SamQuantity": "Giacenza SAM contenitore",
|
||||||
|
"inventory.col.Status": "Esito / anomalie",
|
||||||
|
"inventory.col.Pallet": "UDC",
|
||||||
|
"inventory.col.Location": "Cella alla data",
|
||||||
|
"inventory.col.Quantity": "Pezzi della componente",
|
||||||
"launcher.window_title": "Warehouse 1.0.0",
|
"launcher.window_title": "Warehouse 1.0.0",
|
||||||
"launcher.operator": "Operatore: {display_name} ({login})",
|
"launcher.operator": "Operatore: {display_name} ({login})",
|
||||||
"launcher.reset_corsie": "Gestione Corsie",
|
"launcher.reset_corsie": "Gestione Corsie",
|
||||||
@@ -132,7 +191,7 @@
|
|||||||
"picking.sequence.available": "Scaffali disponibili",
|
"picking.sequence.available": "Scaffali disponibili",
|
||||||
"picking.sequence.selected": "Ordine personalizzato",
|
"picking.sequence.selected": "Ordine personalizzato",
|
||||||
"picking.sequence.hint": "Trascina gli scaffali a destra. Quelli non inseriti saranno accodati secondo l'ordine predefinito.",
|
"picking.sequence.hint": "Trascina gli scaffali a destra. Quelli non inseriti saranno accodati secondo l'ordine predefinito.",
|
||||||
"picking.sequence.default_hint": "Non scaff. sempre per prime; l'ordine personalizzato riguarda solo gli scaffali.",
|
"picking.sequence.default_hint": "Default: prima Non scaff., poi gli scaffali secondo l'ordine WMS.",
|
||||||
"picking.sequence.button.add": "Aggiungi >",
|
"picking.sequence.button.add": "Aggiungi >",
|
||||||
"picking.sequence.button.remove": "< Rimuovi",
|
"picking.sequence.button.remove": "< Rimuovi",
|
||||||
"picking.sequence.button.up": "Su",
|
"picking.sequence.button.up": "Su",
|
||||||
@@ -164,9 +223,68 @@
|
|||||||
"scarico.msg.exec_error": "Scarico fallito:\n{error}"
|
"scarico.msg.exec_error": "Scarico fallito:\n{error}"
|
||||||
},
|
},
|
||||||
"ENG": {
|
"ENG": {
|
||||||
"picking.pair.selection_hint": "Selection order: {documents}. Confirm with Reserve.",
|
"inventory.title": "Inventory",
|
||||||
"picking.pair.max_two": "Select at most two lists.",
|
"inventory.date": "Date (dd/mm/yyyy):",
|
||||||
"picking.pair.sequence_blocked": "Custom ordering is available only for one unpaired list.",
|
"inventory.load": "Calculate inventory",
|
||||||
|
"inventory.export": "Export XLSX",
|
||||||
|
"inventory.notice": "A: WMS UDCs. B: UDCs outside WMS, inferred packaging location. C: bags/tubs without UDC. Residual = SAM - (A+B+C). '?' means undetermined data.",
|
||||||
|
"inventory.scope": "Provisional scope: only products/lots of UDCs in areas 5/6 or non-shelved at date. Not the complete SAM inventory.",
|
||||||
|
"inventory.history_notice": "Reconstruction from movements and available NUMSER history, not a certified physical inventory. Validate labels and history completeness.",
|
||||||
|
"inventory.sources": "Latest source movements (not backup update dates)",
|
||||||
|
"inventory.detail": "Lots and containers for the selected product",
|
||||||
|
"inventory.detail_sheet": "Containers",
|
||||||
|
"inventory.lot_sheet": "Lots",
|
||||||
|
"inventory.inferred_location": "Packaging (inferred)",
|
||||||
|
"inventory.component.A": "A - WMS",
|
||||||
|
"inventory.component.B": "B - UDCs outside WMS",
|
||||||
|
"inventory.component.C": "C - Without UDC",
|
||||||
|
"inventory.component.X": "X - Conflict / out of scope",
|
||||||
|
"inventory.today": "Today is still in progress: the result includes only movements already recorded.",
|
||||||
|
"inventory.bad_date": "Enter a valid dd/mm/yyyy date between 01/01/2010 and today.",
|
||||||
|
"inventory.busy": "Reconstructing inventory at the selected date...",
|
||||||
|
"inventory.loaded": "Inventory at {date} (end of day) | Products: {count} | To verify: {unknown}\nLatest WMS movement: {wms} | Latest SAM movement: {sam}. Run while stock movements are stopped; verify backup consistency.",
|
||||||
|
"inventory.failed": "Operation failed. No warehouse data was changed.",
|
||||||
|
"inventory.export_busy": "Exporting inventory...",
|
||||||
|
"inventory.exported": "File created:\n{path}",
|
||||||
|
"inventory.match": "Matching balance (nominal)",
|
||||||
|
"inventory.mismatch": "Difference to verify",
|
||||||
|
"inventory.issue.content": "UDC content cannot be determined",
|
||||||
|
"inventory.issue.locations": "UDC in multiple locations",
|
||||||
|
"inventory.issue.balance": "Abnormal UDC movement balance",
|
||||||
|
"inventory.issue.unit": "Unit of measure to verify",
|
||||||
|
"inventory.issue.undated": "Undated WMS movements",
|
||||||
|
"inventory.issue.history": "Historical assignment cannot be determined",
|
||||||
|
"inventory.issue.movements": "SAM movements or balance cannot be determined",
|
||||||
|
"inventory.issue.negative": "Negative SAM balance",
|
||||||
|
"inventory.issue.serial": "Missing or invalid container serial",
|
||||||
|
"inventory.issue.shipped": "WMS shipped with residual presence to verify",
|
||||||
|
"inventory.issue.outside": "Out-of-scope presence / abnormal classification",
|
||||||
|
"inventory.issue.duplicate": "Duplicate container with conflicting data",
|
||||||
|
"inventory.issue.lot_offsets": "Lot differences offset each other: inspect lot details",
|
||||||
|
"inventory.col.Product": "Product",
|
||||||
|
"inventory.col.Description": "Description",
|
||||||
|
"inventory.col.Unit": "UOM",
|
||||||
|
"inventory.col.UDCs": "WMS UDC count",
|
||||||
|
"inventory.col.Shelved": "Shelved pieces",
|
||||||
|
"inventory.col.NonShelved": "Non-shelved pieces",
|
||||||
|
"inventory.col.WMS": "WMS pieces",
|
||||||
|
"inventory.col.SAM": "SAM pieces",
|
||||||
|
"inventory.col.Difference": "Residual SAM-(A+B+C)",
|
||||||
|
"inventory.col.InitialDifference": "SAM-A difference",
|
||||||
|
"inventory.col.PackingUDCs": "UDCs outside WMS count",
|
||||||
|
"inventory.col.Packing": "B pieces - UDCs outside WMS",
|
||||||
|
"inventory.col.LooseContainers": "Unassigned container count",
|
||||||
|
"inventory.col.Loose": "C pieces - Without UDC",
|
||||||
|
"inventory.col.Reconstructed": "Total A+B+C",
|
||||||
|
"inventory.col.Component": "Component",
|
||||||
|
"inventory.col.Lot": "Lot",
|
||||||
|
"inventory.col.ContainerId": "LOTSER ID",
|
||||||
|
"inventory.col.Serial": "Container serial",
|
||||||
|
"inventory.col.SamQuantity": "Container SAM balance",
|
||||||
|
"inventory.col.Status": "Result / issues",
|
||||||
|
"inventory.col.Pallet": "UDC",
|
||||||
|
"inventory.col.Location": "Location at date",
|
||||||
|
"inventory.col.Quantity": "Component pieces",
|
||||||
"launcher.window_title": "Warehouse 1.0.0",
|
"launcher.window_title": "Warehouse 1.0.0",
|
||||||
"launcher.operator": "Operator: {display_name} ({login})",
|
"launcher.operator": "Operator: {display_name} ({login})",
|
||||||
"launcher.reset_corsie": "Aisle Management",
|
"launcher.reset_corsie": "Aisle Management",
|
||||||
@@ -295,7 +413,7 @@
|
|||||||
"picking.sequence.available": "Available racks",
|
"picking.sequence.available": "Available racks",
|
||||||
"picking.sequence.selected": "Custom order",
|
"picking.sequence.selected": "Custom order",
|
||||||
"picking.sequence.hint": "Drag racks to the right. Missing racks are appended using the default order.",
|
"picking.sequence.hint": "Drag racks to the right. Missing racks are appended using the default order.",
|
||||||
"picking.sequence.default_hint": "Non-shelved always first; custom ordering applies only to racks.",
|
"picking.sequence.default_hint": "Default: non-shelved first, then racks in WMS order.",
|
||||||
"picking.sequence.button.add": "Add >",
|
"picking.sequence.button.add": "Add >",
|
||||||
"picking.sequence.button.remove": "< Remove",
|
"picking.sequence.button.remove": "< Remove",
|
||||||
"picking.sequence.button.up": "Up",
|
"picking.sequence.button.up": "Up",
|
||||||
|
|||||||
31
main.py
31
main.py
@@ -16,6 +16,7 @@ from runtime_support import ensure_stdio, run_with_fatal_log
|
|||||||
ensure_stdio("warehouse_main")
|
ensure_stdio("warehouse_main")
|
||||||
|
|
||||||
import customtkinter as ctk
|
import customtkinter as ctk
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
from tkinter import messagebox
|
from tkinter import messagebox
|
||||||
|
|
||||||
from async_loop_singleton import get_global_loop, stop_global_loop
|
from async_loop_singleton import get_global_loop, stop_global_loop
|
||||||
@@ -23,6 +24,7 @@ from async_msssql_query import AsyncMSSQLClient
|
|||||||
from audit_log import log_session_event
|
from audit_log import log_session_event
|
||||||
from db_config import build_dsn_from_config, ensure_db_config
|
from db_config import build_dsn_from_config, ensure_db_config
|
||||||
from diagnostica import open_diagnostica_window
|
from diagnostica import open_diagnostica_window
|
||||||
|
from inventario import open_inventario_window
|
||||||
from gestione_layout import open_layout_window
|
from gestione_layout import open_layout_window
|
||||||
from gestione_pickinglist import open_pickinglist_window
|
from gestione_pickinglist import open_pickinglist_window
|
||||||
from login_window import prompt_login
|
from login_window import prompt_login
|
||||||
@@ -163,6 +165,7 @@ class Launcher(ctk.CTk):
|
|||||||
"pickinglist",
|
"pickinglist",
|
||||||
"storico_pickinglist",
|
"storico_pickinglist",
|
||||||
"diagnostica",
|
"diagnostica",
|
||||||
|
"inventario",
|
||||||
]
|
]
|
||||||
|
|
||||||
def __init__(self, session: UserSession, db_client: AsyncMSSQLClient):
|
def __init__(self, session: UserSession, db_client: AsyncMSSQLClient):
|
||||||
@@ -279,6 +282,15 @@ class Launcher(ctk.CTk):
|
|||||||
lambda: open_diagnostica_window(self, self.db_client, session=self.session),
|
lambda: open_diagnostica_window(self, self.db_client, session=self.session),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
(
|
||||||
|
"inventario",
|
||||||
|
loc_text("inventory.title", catalog=self._locale_catalog, default="Inventario"),
|
||||||
|
"launcher.open_inventory",
|
||||||
|
lambda: self._open_or_focus_child_window(
|
||||||
|
"inventario",
|
||||||
|
lambda: open_inventario_window(self, self.db_client, session=self.session),
|
||||||
|
),
|
||||||
|
),
|
||||||
(
|
(
|
||||||
"arrange",
|
"arrange",
|
||||||
loc_text("launcher.arrange", catalog=self._locale_catalog, default="Ridisponi finestre"),
|
loc_text("launcher.arrange", catalog=self._locale_catalog, default="Ridisponi finestre"),
|
||||||
@@ -346,17 +358,18 @@ class Launcher(ctk.CTk):
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def _make_exit_icon(self, *, color: str) -> tk.PhotoImage:
|
def _make_exit_icon(self, *, color: str) -> ctk.CTkImage:
|
||||||
"""Create a small red X icon without adding image assets to the project."""
|
"""Create a transparent X with extra resolution for HighDPI scaling."""
|
||||||
|
|
||||||
size = 14
|
size = 14
|
||||||
image = tk.PhotoImage(width=size, height=size)
|
scale = 3
|
||||||
for offset in range(3, 11):
|
image = Image.new("RGBA", (size * scale, size * scale), (0, 0, 0, 0))
|
||||||
image.put(color, (offset, offset))
|
draw = ImageDraw.Draw(image)
|
||||||
image.put(color, (offset + 1, offset))
|
draw.line((3 * scale, 3 * scale, 10 * scale, 10 * scale),
|
||||||
image.put(color, (offset, size - 1 - offset))
|
fill=color, width=2 * scale)
|
||||||
image.put(color, (offset + 1, size - 1 - offset))
|
draw.line((3 * scale, 10 * scale, 10 * scale, 3 * scale),
|
||||||
return image
|
fill=color, width=2 * scale)
|
||||||
|
return ctk.CTkImage(light_image=image, dark_image=image, size=(size, size))
|
||||||
|
|
||||||
def _apply_dynamic_geometry(self) -> None:
|
def _apply_dynamic_geometry(self) -> None:
|
||||||
"""Size the launcher around its current content and keep it docked at the top."""
|
"""Size the launcher around its current content and keep it docked at the top."""
|
||||||
|
|||||||
@@ -1,139 +0,0 @@
|
|||||||
"""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),
|
|
||||||
)
|
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
"""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)
|
|
||||||
@@ -20,7 +20,6 @@ from locale_text import load_locale_catalog, text as loc_text
|
|||||||
from ui_theme import theme_color, theme_font, theme_section
|
from ui_theme import theme_color, theme_font, theme_section
|
||||||
from user_session import UserSession
|
from user_session import UserSession
|
||||||
from version_info import module_version, versioned_title
|
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
|
from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text
|
||||||
|
|
||||||
__version__ = module_version(__name__)
|
__version__ = module_version(__name__)
|
||||||
@@ -44,13 +43,7 @@ ORDER BY
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
SEQUENCE_GUARD_SQL = PAIR_LOCK_SQL + """
|
SQL_RESET_SEQUENCE = """
|
||||||
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 NOCOUNT ON;
|
||||||
SET XACT_ABORT ON;
|
SET XACT_ABORT ON;
|
||||||
UPDATE dbo.py_PickingListPrelievoSequenza
|
UPDATE dbo.py_PickingListPrelievoSequenza
|
||||||
@@ -273,8 +266,6 @@ class PickingListSequenceWindow(ctk.CTkToplevel):
|
|||||||
configured: list[tuple[int, PickupGroup]] = []
|
configured: list[tuple[int, PickupGroup]] = []
|
||||||
available: list[PickupGroup] = []
|
available: list[PickupGroup] = []
|
||||||
for row in rows:
|
for row in rows:
|
||||||
if str(row.get("GruppoPrelievoChiave") or "").strip() == "NON_SCAFF":
|
|
||||||
continue # Non-shelved UDCs always precede the configurable racks.
|
|
||||||
group = PickupGroup(
|
group = PickupGroup(
|
||||||
key=str(row.get("GruppoPrelievoChiave") or "").strip(),
|
key=str(row.get("GruppoPrelievoChiave") or "").strip(),
|
||||||
label=str(row.get("GruppoPrelievo") or "").strip(),
|
label=str(row.get("GruppoPrelievo") or "").strip(),
|
||||||
@@ -483,7 +474,7 @@ WHERE Documento = :documento
|
|||||||
{insert}
|
{insert}
|
||||||
SELECT CAST({len(values)} AS int) AS ElementiSalvati;
|
SELECT CAST({len(values)} AS int) AS ElementiSalvati;
|
||||||
"""
|
"""
|
||||||
return SEQUENCE_GUARD_SQL + sql, params
|
return sql, params
|
||||||
|
|
||||||
def _save(self) -> None:
|
def _save(self) -> None:
|
||||||
"""Persist the configured prefix atomically."""
|
"""Persist the configured prefix atomically."""
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ customtkinter==5.2.2
|
|||||||
loguru
|
loguru
|
||||||
openpyxl==3.1.5
|
openpyxl==3.1.5
|
||||||
orjson
|
orjson
|
||||||
|
Pillow
|
||||||
pyodbc==5.3.0
|
pyodbc==5.3.0
|
||||||
SQLAlchemy==2.0.49
|
SQLAlchemy==2.0.49
|
||||||
tksheet==7.6.0
|
tksheet==7.6.0
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
/* 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.';
|
|
||||||
242
specifica_inventario.md
Normal file
242
specifica_inventario.md
Normal file
@@ -0,0 +1,242 @@
|
|||||||
|
# Inventario WMS - SAM per prodotto e lotto
|
||||||
|
|
||||||
|
## Stato al 21/10/2026
|
||||||
|
|
||||||
|
Modulo Inventario 1.1.0 completato sul ramo `codex/inventario-monolista`,
|
||||||
|
derivato da `main` al commit `a60610c` (freeze warehouse monolista 2.0).
|
||||||
|
Il lavoro bilista non viene importato: barcode, prenotazione e gestione delle
|
||||||
|
picking list restano quelli monolista. Il ramo bilista e la sua cartella originale
|
||||||
|
restano intatti. Su richiesta dell'utente, questa versione viene integrata in
|
||||||
|
`main` e identificata dal tag `warehouse-monolista-2.0.1-inventario`.
|
||||||
|
L'installazione sui PC e l'esecuzione delle patch sul server restano manuali;
|
||||||
|
vedere `INSTALLAZIONE_MONOLISTA_INVENTARIO.md`.
|
||||||
|
|
||||||
|
Questa versione sostituisce il prototipo del 14/10 e attua i requisiti discussi
|
||||||
|
il 15/10. E' una quadratura delle registrazioni disponibili, NON una certificazione
|
||||||
|
dell'inventario fisico. Prima dell'uso ufficiale confrontare etichette e stampa SAM
|
||||||
|
su un campione. Eventuali limiti storici sono dichiarati e le ambiguita' note
|
||||||
|
invalidano i totali interessati, invece di trasformarsi in zeri.
|
||||||
|
|
||||||
|
## Requisiti e perimetro provvisorio
|
||||||
|
|
||||||
|
- Data qualsiasi scelta dall'operatore, riferita alla fine della giornata.
|
||||||
|
In SQL si usa il limite esclusivo della mezzanotte successiva. Il 31 dicembre
|
||||||
|
e' un esempio, non un vincolo. Oggi e' segnalato come giornata non conclusa.
|
||||||
|
- E' provvisoriamente il WMS a guidare la ricerca: coppie prodotto/lotto delle
|
||||||
|
UDC presenti nelle aree 5/MDE5 e 6/MDE6 oppure non scaffalate alla data.
|
||||||
|
- Per quelle stesse coppie prodotto/lotto si cercano i contenitori in SAM nel
|
||||||
|
Magazzino Principale. Non si estende la ricerca agli altri lotti del prodotto.
|
||||||
|
- Un lotto presente solo in confezionamento e in nessuna UDC WMS e' fuori dal
|
||||||
|
perimetro provvisorio. Questo limite compare in GUI e XLSX. L'utente potra'
|
||||||
|
rivedere in seguito la scelta del perimetro.
|
||||||
|
- Escludere le UDC effettivamente spedite alla data (IDCella 9999), non quelle
|
||||||
|
spedite dopo. Una picking list chiusa NON sostituisce un movimento mancante.
|
||||||
|
- Nessuna modifica automatica a giacenze, prenotazioni, movimenti o anagrafiche.
|
||||||
|
|
||||||
|
## Contenitori, UDC e tre componenti
|
||||||
|
|
||||||
|
Il materiale e' in bag o vasche etichettate, anche parzialmente piene.
|
||||||
|
LOTSER contiene ID, prodotto, NUMLOT e NUMSER. La chiave tecnica del contenitore
|
||||||
|
e' LOTSER.ID; nel dettaglio si conservano anche lotto e seriale completo.
|
||||||
|
|
||||||
|
- `554321/123245`: contenitore assegnato alla UDC 554321.
|
||||||
|
- `000000/123456`: contenitore non assegnato a una UDC.
|
||||||
|
- Un prefisso diverso da zero NON certifica una UDC completa o entrata nel WMS.
|
||||||
|
- "Non scaffalata" descrive la collocazione; "parziale" descrive il riempimento.
|
||||||
|
- Una UDC puo' crescere durante il confezionamento. La precedente affermazione
|
||||||
|
"UDC intere" esclude prelievi parziali/riconfezionamenti nel processo regolare,
|
||||||
|
non il riempimento iniziale progressivo.
|
||||||
|
- Non si moltiplica il numero di contenitori per una capacita' standard.
|
||||||
|
|
||||||
|
| Componente | Significato | Quantita' |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| A | UDC presenti in WMS, allocate o non scaffalate | Pezzi da carichi produzione dei contenitori associati |
|
||||||
|
| B | Contenitori con UDC assegnata, giacenza SAM positiva e nessuna posizione WMS positiva/anomala | Pezzi SAM alla data; confezionamento dedotto, piena/parziale non determinato |
|
||||||
|
| C | Contenitori con prefisso 000000 e giacenza SAM positiva | Pezzi SAM alla data nei contenitori senza UDC |
|
||||||
|
| X | Materiale non classificabile come A/B/C senza contraddizioni | Visibile nel dettaglio e nel saldo SAM, non attribuito arbitrariamente a B |
|
||||||
|
|
||||||
|
La proposta "UDC SAM meno UDC WMS" e' una differenza di insiemi di identificativi,
|
||||||
|
non una sottrazione di pezzi utilizzata per inventare B. Una UDC gia' in A come
|
||||||
|
non scaffalata non si conta anche in B. Il contenitore viene contato una sola volta.
|
||||||
|
|
||||||
|
Per le UDC fuori WMS si controllano anche posizioni in altre aree, saldo negativo
|
||||||
|
e posizione spedita. Una UDC in 9999 con giacenza SAM residua diventa X, non B.
|
||||||
|
Una presenza WMS residua con saldo SAM zero resta A: la differenza va mostrata,
|
||||||
|
non cancellata per ottenere una quadratura apparente.
|
||||||
|
|
||||||
|
## Fonti verificate e algoritmo SQL
|
||||||
|
|
||||||
|
La query runtime e' `inventory_report.sql`, parametrizzata e invocata tramite
|
||||||
|
il client asincrono esistente. Crea solo tabelle temporanee di sessione.
|
||||||
|
Non modifica oggetti legacy, SAM, viste Python, indici persistenti o stored.
|
||||||
|
|
||||||
|
### Magazzino SAM e relazioni
|
||||||
|
|
||||||
|
Si cerca in ANAMAG il nome esatto `Magazzino Principale`, che deve essere univoco.
|
||||||
|
Le ubicazioni sono ALLMAG con IDANAMAG corrispondente. Nel DB locale sono
|
||||||
|
ANAMAG.ID=20 e ALLMAG.ID=4, ma non vengono codificati come costanti nella query.
|
||||||
|
|
||||||
|
MOVMAG.IDARTICO e GIAMAG.IDARTICO indicano LOTSER.ID, NON ARTICO.ID.
|
||||||
|
Il prodotto e' LOTSER.IDARTICO -> ARTICO.ID.
|
||||||
|
Il database ERP resta SAMA1, come nell'integrazione legacy di questo progetto;
|
||||||
|
non si tratta ancora del futuro connettore ERP generalizzato FlyWMS.
|
||||||
|
|
||||||
|
### Presenza WMS
|
||||||
|
|
||||||
|
MagazziniPallet: somma PesoUnitario con segno positivo per V e negativo per P,
|
||||||
|
per Attributo/UDC e IDCella, prima del limite esclusivo. PesoUnitario e' un
|
||||||
|
indicatore di presenza, non il numero di pezzi. Le posizioni positive nelle
|
||||||
|
aree MDE5/MDE6 e nella cella 1000 sono A. Le posizioni in 9999 sono spedite.
|
||||||
|
Si conserva la diagnostica su posizioni multiple e saldi diversi da uno/negativi.
|
||||||
|
|
||||||
|
La geometria Celle -> Aree -> Magazzini e' quella disponibile oggi: non esiste
|
||||||
|
qui uno storico di rinomina o spostamento fisico degli scaffali.
|
||||||
|
|
||||||
|
### Assegnazione contenitore/UDC alla data
|
||||||
|
|
||||||
|
E' stata verificata la presenza del trigger SAM `StoricizzaVariazioniSerie`,
|
||||||
|
che registra in EXTTACLOTSER il valore vecchio EXNUMSER, il nuovo NUMSER e
|
||||||
|
AGGIORNAMENTO per ogni modifica di seriale.
|
||||||
|
|
||||||
|
Per ogni contenitore:
|
||||||
|
1. Se esiste una modifica dalla mezzanotte successiva in avanti, il valore
|
||||||
|
EXNUMSER della prima modifica e' il seriale valido alla data richiesta.
|
||||||
|
2. In assenza di modifiche successive si usa il NUMSER corrente.
|
||||||
|
3. Due modifiche al primo istante utile, senza chiave univoca di ordinamento,
|
||||||
|
sono considerate ambigue. Il totale ricostruito interessato diventa ignoto.
|
||||||
|
|
||||||
|
Nel DB locale lo storico disponibile parte dal 10/01/2022. Per una data prima
|
||||||
|
del primo storico disponibile, o se lo storico e' vuoto, i totali ricostruiti
|
||||||
|
non vengono certificati numericamente: si mostra l'anomalia.
|
||||||
|
|
||||||
|
Limite esplicito: l'assenza di una modifica nello storico non prova che il
|
||||||
|
trigger sia sempre stato attivo. La ricostruzione assume storico completo,
|
||||||
|
nessuna cancellazione di contenitori e nessuna modifica non tracciata a
|
||||||
|
prodotto/lotto. EXTTACLOTSER non e' una fotografia immutabile di tutte le
|
||||||
|
anagrafiche. Questa avvertenza resta visibile in GUI e XLSX.
|
||||||
|
|
||||||
|
### Quantita' A e saldo SAM per contenitore
|
||||||
|
|
||||||
|
A: somma algebrica dei carichi di produzione causale CP nel Magazzino
|
||||||
|
Principale prima del limite, usando MOVMAG.QTAINV e i segni della causale.
|
||||||
|
Si supportano piu' carichi CP e le loro quantita' effettive: non si presume
|
||||||
|
una bag piena e non si usa la giacenza corrente come contenuto nominale.
|
||||||
|
Un contenitore senza carico nominale positivo o con altri tipi di entrata
|
||||||
|
richiede verifica: A rimane ignoto per il prodotto/lotto interessato.
|
||||||
|
Sul campione locale esaminato CP e' il carico e VEN la vendita; l'equivalenza
|
||||||
|
del nominale all'etichetta va comunque validata sui dati reali dell'operatore.
|
||||||
|
|
||||||
|
SAM: per ciascun LOTSER.ID si parte da GIAMAG.QTTGIAI nelle ubicazioni del
|
||||||
|
Magazzino Principale e si sottrae l'effetto dei MOVMAG dal limite in avanti.
|
||||||
|
I segni vengono da CAUMOV.QTGIUP/QTGIUA per sorgente/destinazione. Un movimento
|
||||||
|
interno allo stesso magazzino si compensa. Le date SAM usano origine 1899-12-30.
|
||||||
|
|
||||||
|
B/C usano il saldo cosi' ricostruito per ciascun contenitore, non il numero
|
||||||
|
di contenitori e non il residuo del confronto con A. Vasche/bag parziali
|
||||||
|
sono quindi trattate con la quantita' registrata, non una capacita' teorica.
|
||||||
|
Essendo B/C ricavati da SAM, la loro presenza non prova la collocazione fisica
|
||||||
|
in confezionamento: e' una spiegazione documentale da verificare sul posto.
|
||||||
|
|
||||||
|
## Calcolo ed esiti
|
||||||
|
|
||||||
|
`Totale ricostruito = A + B + C`
|
||||||
|
|
||||||
|
`Differenza iniziale = SAM - A`
|
||||||
|
|
||||||
|
`Scostamento residuo = SAM - (A + B + C)`
|
||||||
|
|
||||||
|
Esempio: SAM 10.600, A 10.000, B 400, C 200 -> residuo zero.
|
||||||
|
Un residuo positivo indica pezzi SAM non spiegati da A/B/C; uno negativo
|
||||||
|
indica quantita' ricostruita superiore a SAM.
|
||||||
|
|
||||||
|
L'aggregazione parte dal prodotto/lotto, poi viene riepilogata per prodotto.
|
||||||
|
Se differenze di lotti opposte si annullano nel totale del prodotto, una
|
||||||
|
segnalazione impedisce di leggere quel totale come una quadratura corretta.
|
||||||
|
Le UDC multilotto sono contate una volta per prodotto. I conteggi UDC di
|
||||||
|
prodotti diversi non sono sommabili per ottenere le UDC globali.
|
||||||
|
|
||||||
|
Quantita' ignote: `?` a video, celle vuote in XLSX. Zeri reali: numeri zero.
|
||||||
|
Calcoli Python con Decimal. Un'anomalia puo' invalidare A, B, C o SAM:
|
||||||
|
la parte nota resta consultabile, il totale dipendente dalla parte ignota no.
|
||||||
|
|
||||||
|
Le righe X restano fuori dalla somma A+B+C ma dentro SAM, con avviso:
|
||||||
|
per esempio una spedita con saldo SAM residuo resta uno scostamento da indagare.
|
||||||
|
|
||||||
|
## Interfaccia e integrazione monolista
|
||||||
|
|
||||||
|
- Pulsante Inventario nella barra orizzontale desktop, permesso
|
||||||
|
`launcher.open_inventory`; una sola finestra e richiamo in primo piano.
|
||||||
|
- Finestra con posizionamento condiviso, tema JSON, stringhe IT/ENG, versione
|
||||||
|
visibile 1.1.0. Versione launcher aggiornata a 1.0.3.
|
||||||
|
- Data, Calcola, Esporta XLSX. Nessuna query all'apertura. Query e export
|
||||||
|
asincroni con overlay; durante il calcolo non si avviano richieste duplicate.
|
||||||
|
- Griglia prodotti ordinabile: UDC WMS, pezzi scaffalati/non scaffalati, A,
|
||||||
|
numero UDC B e pezzi B, numero contenitori C e pezzi C, totale, SAM,
|
||||||
|
differenza iniziale, residuo, anomalie.
|
||||||
|
- Selezionando un prodotto: schede Lotti e Contenitori. Per contenitore:
|
||||||
|
componente, prodotto, lotto, UDC, ID LOTSER, seriale, ubicazione, quantita'
|
||||||
|
della componente, saldo SAM, anomalie.
|
||||||
|
- Ubicazione di B/C etichettata "Confezionamento (dedotto)".
|
||||||
|
- XLSX con tre fogli (prodotti, lotti, contenitori), data del calcolo,
|
||||||
|
perimetro, avvertenze e date delle fonti. Numeri e codici restano del tipo
|
||||||
|
corretto, anche codici che iniziano con '='.
|
||||||
|
- Errore di calcolo: griglia precedente svuotata, export disabilitato.
|
||||||
|
Nessun risultato vecchio presentato come relativo alla nuova data.
|
||||||
|
- Barcode e procedure di movimentazione/prenotazione monolista invariati.
|
||||||
|
|
||||||
|
## Collaudo eseguito
|
||||||
|
|
||||||
|
Il 21/10/2026 sono stati eseguiti 50 test con esito positivo, comprendenti
|
||||||
|
test monolista preesistenti e nuove verifiche di dominio, GUI, menu, XLSX e SQL.
|
||||||
|
|
||||||
|
I test SQL opt-in usano solo tabelle temporanee con dati fittizi: i nomi
|
||||||
|
delle tabelle sorgenti della query sono sostituiti con fixture prima
|
||||||
|
dell'esecuzione. Non vengono effettuati movimenti reali.
|
||||||
|
|
||||||
|
Casi verificati: A/B/C, UDC multilotto, esclusione di lotti solo SAM, bag
|
||||||
|
parziale, saldo residuo di UDC spedita, cambio NUMSER successivo alla data,
|
||||||
|
spedizione successiva, due celle per la stessa UDC senza raddoppiare SAM,
|
||||||
|
piu' carichi CP, solo Magazzino Principale, limite della mezzanotte,
|
||||||
|
storico ambiguo, quantita' ignote, ordinamento numerico, export tipizzato,
|
||||||
|
errori senza risultati obsoleti, pulsante menu e finestra unica.
|
||||||
|
|
||||||
|
Letture sul database locale tramite il vero client SQLAlchemy/aioodbc:
|
||||||
|
- 31/12/2025: 27 prodotti, 172 lotti, 19.859 righe dettaglio, circa 15 secondi.
|
||||||
|
- 28/09/2026: 21 prodotti, 68 lotti, 9.472 righe dettaglio, circa 6 secondi.
|
||||||
|
|
||||||
|
Questi tempi e conteggi descrivono il backup locale disponibile, non sono
|
||||||
|
una certificazione quantitativa della produzione. Le anomalie reali restano
|
||||||
|
visibili; non sono state corrette nei dati.
|
||||||
|
|
||||||
|
Comandi di verifica dalla cartella del ramo monolista:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -B -m unittest discover -s tests -q
|
||||||
|
$env:INVENTORY_TEST_CONFIG = 'C:\devel\python\ware_house\db_connection.json'
|
||||||
|
python -B -m unittest discover -s tests -q
|
||||||
|
```
|
||||||
|
|
||||||
|
Senza variabile i cinque test SQL sono saltati esplicitamente. Con variabile
|
||||||
|
si collega SQL Server per creare esclusivamente fixture temporanee.
|
||||||
|
La configurazione contiene credenziali: non aggiungerla al repository.
|
||||||
|
|
||||||
|
## Installazione e limiti residui
|
||||||
|
|
||||||
|
Non serve una patch SQL per questo modulo. Distribuire il file
|
||||||
|
`inventory_report.sql` insieme ai sorgenti: NON e' uno script da eseguire
|
||||||
|
manualmente in SSMS. La query richiede lettura di SAMA1, incluso EXTTACLOTSER.
|
||||||
|
|
||||||
|
Distribuire insieme inventario.py, inventory_service.py, inventory_report.sql
|
||||||
|
e le integrazioni main.py, user_session.py, version_info.py, locale.json,
|
||||||
|
tooltip.json, ui_theme.json. Nessuna dipendenza nuova: openpyxl e' gia' prevista.
|
||||||
|
Preferire la distribuzione completa della monolista dopo commit e collaudo,
|
||||||
|
non copiare indiscriminatamente dalla cartella del ramo bilista.
|
||||||
|
|
||||||
|
Eseguire a movimentazioni ferme, con backup ERP/WMS coerenti. Le letture non
|
||||||
|
costituiscono una snapshot distribuita atomica; le date massime dei movimenti
|
||||||
|
NON certificano la data di backup. Nessun NOLOCK o lettura sporca viene usato.
|
||||||
|
|
||||||
|
Prima della distribuzione ufficiale confrontare un campione con etichette e
|
||||||
|
inventario SAM alla medesima data, provare il menu sulla postazione del reparto
|
||||||
|
e verificare la completezza dello storico seriali. L'ambiente di simulazione
|
||||||
|
bilista rimane un'attivita' separata.
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
# Prelievo guidato di due picking list sul terminalino
|
# Prelievo guidato di due picking list sul terminalino
|
||||||
|
|
||||||
Data: 02/10/2026. Revisione: 1.0.
|
Data: 02/10/2026. Revisione: 0.3.
|
||||||
|
|
||||||
**Stato: implementazione bilista 2.1.0 collegata a desktop, barcode e SQL;
|
**Stato: specifica da rileggere e concordare prima dell'implementazione.**
|
||||||
collaudo locale automatizzato eseguito, collaudo operatore da completare.**
|
La funzione di prelievo abbinato descritta qui non e' ancora implementata.
|
||||||
La sezione 17 descrive l'implementazione e le protezioni conservative adottate.
|
I punti indicati come aperti o proposti non sono decisioni gia' approvate.
|
||||||
Le sezioni precedenti conservano anche la storia delle decisioni.
|
|
||||||
|
|
||||||
## 1. Obiettivo operativo
|
## 1. Obiettivo operativo
|
||||||
|
|
||||||
@@ -26,8 +25,8 @@ decisioni e non e' definita da questa specifica.
|
|||||||
|
|
||||||
| Termine | Significato |
|
| Termine | Significato |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Lista 1 / IDStato 1 | Prima lista assegnata alla coppia, con identita' stabile |
|
| Lista 1 / F1 | Prima lista assegnata alla coppia, con identita' stabile |
|
||||||
| Lista 2 / IDStato 2 | Seconda lista assegnata alla coppia, con identita' stabile |
|
| Lista 2 / F2 | Seconda lista assegnata alla coppia, con identita' stabile |
|
||||||
| Lista proposta | Documento della prossima UDC indicata dal sistema |
|
| Lista proposta | Documento della prossima UDC indicata dal sistema |
|
||||||
| Colonna o campata | Colonna di uno specifico scaffale e magazzino |
|
| Colonna o campata | Colonna di uno specifico scaffale e magazzino |
|
||||||
| Cella | Singola posizione dentro la colonna, a un determinato livello |
|
| Cella | Singola posizione dentro la colonna, a un determinato livello |
|
||||||
@@ -38,11 +37,6 @@ 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.
|
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.
|
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
|
## 3. Situazione attuale e difetto da non reintrodurre
|
||||||
|
|
||||||
La prenotazione Python attuale prevede un unico documento. Storicamente F1
|
La prenotazione Python attuale prevede un unico documento. Storicamente F1
|
||||||
@@ -71,19 +65,12 @@ avere un comportamento chiaramente distinguibile.
|
|||||||
|
|
||||||
### R02. Identita' della coppia
|
### R02. Identita' della coppia
|
||||||
|
|
||||||
Il desktop deve rendere riconoscibile quale documento e' Lista 1/IDStato 1 e quale
|
Il desktop deve rendere riconoscibile quale documento e' Lista 1/F1 e quale
|
||||||
e' Lista 2/IDStato 2. L'assegnazione non dipende dall'ordinamento momentaneo della
|
e' Lista 2/F2. L'assegnazione non dipende dall'ordinamento momentaneo della
|
||||||
griglia o dalla posizione della prossima UDC.
|
griglia o dalla posizione della prossima UDC.
|
||||||
|
|
||||||
Le liste non prenotate mantengono IDStato 0. Lo sfondo della cella IDStato
|
Il gesto per assegnare i ruoli e' ancora da definire: ad esempio due slot
|
||||||
deve essere lo stesso colore di contesto usato sul terminalino: rosa per
|
espliciti, oppure prima e seconda scelta rese chiaramente visibili.
|
||||||
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
|
### R02a. Le due liste devono appartenere alla stessa area
|
||||||
|
|
||||||
@@ -95,42 +82,25 @@ senza salvare una coppia parziale o alterare le prenotazioni preesistenti.
|
|||||||
Il vincolo deve essere verificato anche lato servizio/database, non soltanto
|
Il vincolo deve essere verificato anche lato servizio/database, non soltanto
|
||||||
mediante la disponibilita' dei pulsanti nell'interfaccia desktop.
|
mediante la disponibilita' dei pulsanti nell'interfaccia desktop.
|
||||||
|
|
||||||
Chiarimento confermato: le UDC non scaffalate possono trovarsi ovunque e non
|
Prima dell'implementazione va definita la fonte autorevole dell'area della
|
||||||
appartengono ad alcuna area. Restano Non scaff. e non richiedono una scelta
|
lista, specialmente se contiene UDC non scaffalate o senza giacenza WMS.
|
||||||
artificiale fra Area 5 e Area 6. Anche l'eventuale magazzino associato nel
|
La cella virtuale condivisa 1000 non dimostra da sola l'appartenenza all'area.
|
||||||
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.
|
Non dedurre il magazzino dal numero documento o dagli ID legacy delle Aree.
|
||||||
Una lista composta solo da Non scaff. non introduce un conflitto di area;
|
Il trattamento delle liste internamente miste o con area indeterminata resta
|
||||||
se entrambe sono composte solo da Non scaff., non c'e' un percorso scaffali
|
da concordare; non considerarle implicitamente compatibili con entrambe.
|
||||||
da scegliere. Celle fisiche con magazzino non riconoscibile restano invece
|
|
||||||
un'anomalia da gestire, non equivalgono a UDC non scaffalate.
|
|
||||||
|
|
||||||
### R03. Nel bilista governa la sequenza della prima lista selezionata
|
### R03. Un'unica sequenza personalizzata
|
||||||
|
|
||||||
CONFERMATO: quando sono selezionate due liste, il pulsante Sequenza di prelievo
|
Con due liste selezionate, il comando Sequenza di prelievo riguarda entrambe.
|
||||||
deve essere disabilitato. Non si apre un editor della coppia e non si chiede
|
L'editor deve presentare l'unione degli scaffali/gruppi presenti nelle due liste,
|
||||||
all'operatore di risolvere un conflitto fra personalizzazioni preesistenti.
|
includendo quelli presenti soltanto in una di esse e il gruppo Non scaff.
|
||||||
|
|
||||||
Il giro abbinato segue la sequenza gia' salvata sulla prima lista selezionata,
|
Non si devono eseguire due ordinamenti personalizzati incompatibili nello
|
||||||
ossia quella assegnata a IDStato 1. Non si intende la lista che il terminalino
|
stesso giro. La sequenza della coppia deve costituire l'unico riferimento.
|
||||||
propone per prima: quella puo' essere la Lista 2. L'ordinamento della griglia
|
|
||||||
non cambia quale documento e' il riferimento.
|
|
||||||
|
|
||||||
Se la prima lista non ha personalizzazione, entrambe seguono l'ordine standard.
|
La scelta fra eventuali personalizzazioni gia' salvate sulle singole liste
|
||||||
L'eventuale personalizzazione della seconda lista viene ignorata per il giro
|
resta aperta. Non e' ammessa una fusione silenziosa che produca un ordine
|
||||||
abbinato, senza cancellarla o sovrascriverla. Non si fondono le due sequenze.
|
diverso da quello mostrato al responsabile.
|
||||||
|
|
||||||
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
|
## 5. Percorsi delle aree: conservare il comportamento esistente
|
||||||
|
|
||||||
@@ -163,10 +133,9 @@ scaffale/colonna/livello dell'area 6.
|
|||||||
|
|
||||||
### R06. Effetto della personalizzazione
|
### R06. Effetto della personalizzazione
|
||||||
|
|
||||||
La personalizzazione cambia la precedenza degli scaffali, mentre dentro
|
La personalizzazione mantiene il significato attuale: cambia la precedenza
|
||||||
ogni scaffale si conserva l'ordine delle celle. Non scaff. resta sempre primo.
|
dei gruppi/scaffali, mentre dentro ogni gruppo si conserva l'ordine delle celle.
|
||||||
Con due liste, la scelta gia' salvata sulla prima selezionata si applica
|
Con due liste, la stessa scelta si applica all'intero contenuto della coppia.
|
||||||
all'intero contenuto della coppia, senza modificarla durante la selezione doppia.
|
|
||||||
|
|
||||||
Per esempio, porre tutto 1A prima di tutto 2B elimina intenzionalmente
|
Per esempio, porre tutto 1A prima di tutto 2B elimina intenzionalmente
|
||||||
l'alternanza fra quei due scaffali, come avviene gia' nella personalizzazione
|
l'alternanza fra quei due scaffali, come avviene gia' nella personalizzazione
|
||||||
@@ -207,42 +176,27 @@ documento a cui appartiene.
|
|||||||
Non introdurre la scelta automatica di una terza lista, neanche al termine
|
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.
|
di una delle due. La gestione delle UDC saltate e' trattata al punto 10.
|
||||||
|
|
||||||
## 7. Avvio con F1 e gestione dei tasti
|
## 7. Avvio neutro e tasti F1/F2
|
||||||
|
|
||||||
### R10. Avvio scelto dal sistema
|
### R10. Avvio scelto dal sistema
|
||||||
|
|
||||||
L'operatore preme sempre F1 per avviare il lavoro. Il sistema legge la
|
Quando il terminalino mostra Pronto per la coppia, il sistema deve avere gia'
|
||||||
prenotazione e distingue tre casi:
|
individuato la prima proposta. L'operatore non decide arbitrariamente da quale
|
||||||
|
documento partire.
|
||||||
|
|
||||||
1. Nessuna lista prenotata: mantenere l'accesso attuale ai movimenti liberi.
|
Se la prima UDC appartiene alla Lista 2, F2 e' abilitato e F1 disabilitato;
|
||||||
2. Una lista prenotata: mantenere il comportamento monolista attuale.
|
se appartiene alla Lista 1, vale il contrario. Il blocco deve valere sia per
|
||||||
3. Due liste prenotate: avviare il giro comune, scegliendo automaticamente
|
i pulsanti sullo schermo sia per i tasti fisici.
|
||||||
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
|
### R11. Guida durante il giro
|
||||||
|
|
||||||
Nel prelievo abbinato il documento da lavorare e' quello proposto dal percorso.
|
Nel prelievo abbinato deve essere selezionabile soltanto la lista proposta
|
||||||
Il cambio automatico verso l'altro documento non richiede una nuova scelta
|
dal percorso. Il cambio automatico verso l'altro documento non richiede una
|
||||||
dell'operatore.
|
nuova scelta dell'operatore.
|
||||||
|
|
||||||
La precedente modalita' manuale F1/F2 e il nuovo giro guidato non devono
|
La precedente modalita' manuale F1/F2 e il nuovo giro guidato non devono
|
||||||
essere confusi: nel giro guidato sono i ruoli IDStato 1/2 a identificare
|
essere confusi: nel giro guidato i due tasti identificano documenti stabili,
|
||||||
documenti stabili. La pressione di F1 non deve forzare la Lista 1 quando
|
ma non autorizzano a scavalcare il percorso stabilito.
|
||||||
il percorso richiede prima una UDC della Lista 2.
|
|
||||||
|
|
||||||
### Chiarimento confermato: la prima cella dipende dal percorso dell'area
|
### Chiarimento confermato: la prima cella dipende dal percorso dell'area
|
||||||
|
|
||||||
@@ -267,10 +221,10 @@ personalizzato e la precedenza delle Non scaff. descritta in R14.
|
|||||||
|
|
||||||
| Documento assegnato | Colore di contesto |
|
| Documento assegnato | Colore di contesto |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Lista 1 / IDStato 1 | Rosellino |
|
| Lista 1 / F1 | Rosellino |
|
||||||
| Lista 2 / IDStato 2 | Giallino |
|
| Lista 2 / F2 | Giallino |
|
||||||
|
|
||||||
Il colore segue il documento e non la sua posizione nel giro: se inizia Lista 2,
|
Il colore segue il documento e non la sua posizione nel giro: se inizia F2,
|
||||||
lo sfondo iniziale e' giallino. La stessa lista conserva il proprio colore
|
lo sfondo iniziale e' giallino. La stessa lista conserva il proprio colore
|
||||||
nei successivi passaggi.
|
nei successivi passaggi.
|
||||||
|
|
||||||
@@ -306,72 +260,37 @@ fosse riuscito; restano necessarie le verifiche e il recupero gia' esistenti.
|
|||||||
|
|
||||||
### R14. Non scaffalate
|
### R14. Non scaffalate
|
||||||
|
|
||||||
Requisito confermato e obbligatorio: il prelievo parte SEMPRE dalle UDC
|
Conservare il comportamento corrente: Non scaff. precede gli scaffali nel
|
||||||
non scaffalate. Con due liste si considerano prima le Non scaff. di ENTRAMBE,
|
default, salvo diversa posizione assegnata nella sequenza personalizzata.
|
||||||
non soltanto quelle del documento dal quale parte il terminalino.
|
La regola deve considerare le UDC di entrambe le liste.
|
||||||
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.
|
La cella virtuale e' condivisibile e non ha un livello fisico da confrontare.
|
||||||
CONFERMATO: prima le Non scaff. della Lista 1, poi quelle della Lista 2;
|
Il criterio di parita' fra UDC non scaffalate delle due liste resta da
|
||||||
in ciascuna lista si mantiene l'ordine per codice UDC. Solo dopo questa fase
|
concordare; proposta: ordine stabile per ruolo lista e codice UDC.
|
||||||
si inizia il prelievo dalle celle fisiche di entrambe.
|
|
||||||
|
|
||||||
### R15. UDC saltate: comando conservato
|
### R15. UDC saltate: approfondimento rinviato
|
||||||
|
|
||||||
CONFERMATO: F4 conserva il comando Salta UDC anche nel giro abbinato.
|
Il comando Salta UDC esiste gia'. L'utente ha chiesto di analizzarne in seguito
|
||||||
Il salto riguarda il documento e la UDC correntemente proposti, non un
|
il comportamento nel nuovo giro abbinato, con l'intenzione di conservare
|
||||||
documento scelto manualmente mediante F2. Si passa alla prossima UDC lavorabile
|
quanto possibile il funzionamento attuale.
|
||||||
del percorso comune senza registrare alcuno scarico per quella saltata.
|
|
||||||
|
|
||||||
CONFERMATO: per ogni documento, quando non restano UDC lavorabili nel ciclo
|
Restano da decidere il termine della singola lista con soli skip, la sua
|
||||||
attuale, la prenotazione viene portata automaticamente a 0. Se rimangono UDC
|
sprenotazione, la prosecuzione dell'altra lista e le modalita' di ripresa.
|
||||||
saltate, la lista continua a comparire fra le prenotabili con le sole residue.
|
Saltare una UDC non deve comunque equivalere a spedirla o cancellarla dalla lista.
|
||||||
Il salto non spedisce la UDC, non la cancella dalla lista e non chiude la lista
|
|
||||||
come completamente evasa.
|
|
||||||
|
|
||||||
Per prelevare le residue, l'operatore seleziona e prenota nuovamente la lista.
|
### Pausa e ripresa: comportamento da completare
|
||||||
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.
|
|
||||||
|
|
||||||
La regola vale indipendentemente per entrambi i documenti: se sono state saltate
|
Oggi Pausa PL consente movimenti liberi e ESC riporta al picking.
|
||||||
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.
|
Nel nuovo giro occorre conservare identita' dei due documenti e percorso.
|
||||||
Va deciso se al rientro mantenere la UDC gia' proposta o ricalcolare la
|
Va deciso se al rientro mantenere la UDC gia' proposta o ricalcolare la
|
||||||
prossima posizione quando nel frattempo cambiano le ubicazioni.
|
prossima posizione quando nel frattempo cambiano le ubicazioni.
|
||||||
I movimenti liberi devono mantenere le proprie regole di carico e scarico.
|
I movimenti liberi devono mantenere le proprie regole di carico e scarico.
|
||||||
|
|
||||||
### Fine di una lista: comportamento confermato
|
### Fine di una lista: proposta ancora da confermare
|
||||||
|
|
||||||
Quando una lista non ha piu' UDC residue, viene sprenotata automaticamente,
|
Quando una lista non ha piu' UDC residue, proseguire con l'altra mantenendone
|
||||||
scompare dall'elenco operativo delle prenotabili e rimane consultabile nello
|
ruolo e colore originali. Non promuovere automaticamente F2 a F1 e non
|
||||||
storico, come nel comportamento attuale. Questo non richiede di inventare un
|
aggiungere un terzo documento. Distinguere esaurimento reale e soli skip.
|
||||||
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
|
## 11. Esempi di percorso atteso
|
||||||
|
|
||||||
@@ -421,10 +340,7 @@ raggruppano automaticamente tutte le colonne 1A prima di quelle 2B.
|
|||||||
|
|
||||||
### Esempio D: ordine personalizzato della coppia
|
### Esempio D: ordine personalizzato della coppia
|
||||||
|
|
||||||
La prima lista selezionata ha gia' salvato l'ordine 4P -> 1M, mentre la seconda
|
Il responsabile imposta Non scaff. -> 4P -> 1M. Il terminalino lavora tutte
|
||||||
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
|
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.
|
in 1M, applicando dentro ciascun gruppo l'ordine delle celle previsto.
|
||||||
Gli eventuali gruppi non configurati vengono accodati, mai esclusi.
|
Gli eventuali gruppi non configurati vengono accodati, mai esclusi.
|
||||||
@@ -484,218 +400,40 @@ Il ripristino delle testate non annulla le movimentazioni fatte durante i test.
|
|||||||
| Una sola lista | Ordinamento attuale conservato |
|
| Una sola lista | Ordinamento attuale conservato |
|
||||||
| Due liste entrambe Area 5 oppure entrambe Area 6 | Abbinamento consentito, applicando il percorso della relativa area |
|
| 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 |
|
| Una lista Area 5 e una Area 6 | Abbinamento rifiutato senza modificare le prenotazioni esistenti |
|
||||||
| Lista 2 precede Lista 1 nel percorso | F1 avvia direttamente Lista 2, con sfondo giallo |
|
| F2 precede F1 nel percorso | All'avvio solo F2 utilizzabile |
|
||||||
| 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 |
|
| F1 presente ogni tre colonne | Nessuna colonna intermedia F2 omessa |
|
||||||
| Livelli alternati F2/F1/F2 | Tre proposte in ordine fisico, con documenti corretti |
|
| 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 |
|
| 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 |
|
| 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 |
|
| Default area 6 | Percorso corrente per scaffale, colonne crescenti e livelli dal basso verso l'alto |
|
||||||
| Personalizzazione della coppia | Stesso ordine applicato a entrambe |
|
| Personalizzazione della coppia | Stesso ordine applicato a entrambe |
|
||||||
| Due checkbox selezionati | Pulsante Sequenza di prelievo disabilitato |
|
| Gruppo presente solo in F2 | Visibile nell'editor e incluso nel percorso |
|
||||||
| 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 |
|
| Gruppo omesso dalla personalizzazione | Accodato secondo il comportamento attuale |
|
||||||
| F2 durante il giro abbinato | Disabilitato: nessun cambio documento e nessun movimento, anche da tastiera |
|
| Tasto fisico della lista disabilitata | Nessun cambio documento e nessun movimento |
|
||||||
| 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 |
|
| Cambio automatico | Numero lista, colore e UDC aggiornati coerentemente |
|
||||||
| UDC con due lotti | Un solo prelievo fisico |
|
| UDC con due lotti | Un solo prelievo fisico |
|
||||||
| Terza lista disponibile | Mai inserita automaticamente nel giro |
|
| Terza lista disponibile | Mai inserita automaticamente nel giro |
|
||||||
| Aggiornamento programma del campo UDC | Non interpretato come nuova lettura |
|
| Aggiornamento programma del campo UDC | Non interpretato come nuova lettura |
|
||||||
| Movimento fallito o esito incerto | Nessun avanzamento ingiustificato |
|
| Movimento fallito o esito incerto | Nessun avanzamento ingiustificato |
|
||||||
|
|
||||||
I casi relativi a pausa, riavvio e modifiche concorrenti andranno completati
|
I casi relativi a skip, fine parziale, pausa, riavvio e modifiche concorrenti
|
||||||
dopo la decisione delle relative regole. Skip, fine parziale e riprenotazione
|
andranno completati dopo la decisione delle relative regole.
|
||||||
devono rispettare i casi confermati sopra.
|
|
||||||
|
|
||||||
## 15. Decisioni aperte per la revisione
|
## 15. Decisioni aperte per la revisione
|
||||||
|
|
||||||
L'avvio e' chiarito: prima tutte le Non scaff., poi il percorso dell'area,
|
L'avvio e' chiarito: si rispetta il percorso dell'area, dall'alto in area 5
|
||||||
dall'alto in area 5 e dal basso in area 6. Restano aperti i punti seguenti.
|
e dal basso in area 6. Restano aperti i punti seguenti.
|
||||||
|
|
||||||
1. Gestione di successive modifiche a una coppia gia' prenotata; l'assegnazione
|
1. Assegnazione esplicita dei ruoli Lista 1 e Lista 2 sul desktop.
|
||||||
iniziale e' confermata: ordine dei checkbox e conferma con Prenota.
|
2. Gestione delle sequenze preesistenti quando si compone una nuova coppia.
|
||||||
2. Blocco delle modifiche individuali alla sequenza mentre una coppia e' gia'
|
3. Ordine fra UDC non scaffalate o con identico valore di percorso.
|
||||||
in lavorazione, anche tramite un'altra finestra o un altro PC.
|
4. Salti, esaurimento con residui e riprenotazione della coppia o di una lista.
|
||||||
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.
|
5. Ripresa dalla pausa e da un riavvio, con ubicazioni eventualmente cambiate.
|
||||||
6. Modifiche alla coppia/sequenza mentre il prelievo e' in corso.
|
6. Modifiche alla coppia/sequenza mentre il prelievo e' in corso.
|
||||||
7. Gestione delle anomalie di mappatura delle celle fisiche al magazzino;
|
7. Fonte autorevole dell'area di una lista e gestione di liste internamente
|
||||||
le Non scaff. sono prive di area, le coppie fisicamente miste 5/6 vietate.
|
miste o con area indeterminata; le coppie Area 5/Area 6 sono vietate (R02a).
|
||||||
8. Condotta su dati anomali: stessa UDC in due liste o cella fisica con piu' UDC.
|
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.
|
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
|
Le risposte possono essere annotate direttamente in questa sezione prima di
|
||||||
passare al progetto tecnico e alle modifiche applicative.
|
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.
|
|
||||||
|
|||||||
@@ -1,143 +0,0 @@
|
|||||||
"""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)
|
|
||||||
202
tests/test_inventory.py
Normal file
202
tests/test_inventory.py
Normal file
@@ -0,0 +1,202 @@
|
|||||||
|
"""Domain and XLSX regression tests: no live stock is modified."""
|
||||||
|
import json
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from datetime import date, datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import AsyncMock
|
||||||
|
|
||||||
|
from inventory_service import (DETAIL_KEYS, SUMMARY_KEYS, build_report, export_inventory,
|
||||||
|
inventory_cutoff, load_inventory)
|
||||||
|
from locale_text import text
|
||||||
|
|
||||||
|
DAY = date(2025, 12, 31)
|
||||||
|
HISTORY = dict(Kind="META", Component="HIST_MIN", SourceDate=datetime(2022, 1, 1))
|
||||||
|
|
||||||
|
|
||||||
|
def stock(**changes):
|
||||||
|
r = dict(Kind="ROW", Component="A", Product="P1", Description="Product",
|
||||||
|
Unit="NR", ContainerId=1, Lot="L1", Serial="600001/000001",
|
||||||
|
Pallet="600001", Cell=1101, Location="1A.1.a", Balance=Decimal(1),
|
||||||
|
Quantity=Decimal(20), SamQuantity=Decimal(20), Locations=1,
|
||||||
|
NegativeBalances=0, Shipped=0, AssignmentIssue=0,
|
||||||
|
MovementIssues=0, OtherReceipts=0)
|
||||||
|
r.update(changes)
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
def report(*records):
|
||||||
|
return build_report(DAY, [HISTORY, *records])
|
||||||
|
|
||||||
|
|
||||||
|
def packing(**changes):
|
||||||
|
return stock(Component="B", ContainerId=2, Pallet="600002", Serial="600002/000002",
|
||||||
|
Cell=None, Location=None, Balance=None, Locations=0, **changes)
|
||||||
|
|
||||||
|
|
||||||
|
def loose(**changes):
|
||||||
|
return stock(Component="C", ContainerId=3, Pallet="000000", Serial="000000/000003",
|
||||||
|
Cell=None, Location=None, Balance=None, Locations=0, **changes)
|
||||||
|
|
||||||
|
|
||||||
|
class InventoryTests(unittest.TestCase):
|
||||||
|
def test_year_end_exclusive_cutoff(self):
|
||||||
|
self.assertEqual(inventory_cutoff("31/12/2025"), (DAY, datetime(2026, 1, 1), 46023))
|
||||||
|
|
||||||
|
def test_dates_invalid_future_and_leap(self):
|
||||||
|
for value in ("31/02/2025", "2025-12-31", "01/01/3000", "31/12/2009"):
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
inventory_cutoff(value)
|
||||||
|
self.assertEqual(inventory_cutoff("29/02/2024")[1], datetime(2024, 3, 1))
|
||||||
|
|
||||||
|
def test_three_components_and_sign(self):
|
||||||
|
r = report(stock(), packing(Quantity=10, SamQuantity=10), loose(Quantity=5, SamQuantity=5))
|
||||||
|
row = r.rows[0]
|
||||||
|
self.assertEqual([row[k] for k in ("WMS", "Packing", "Loose", "Reconstructed", "SAM", "Difference")],
|
||||||
|
[20, 10, 5, 35, 35, 0])
|
||||||
|
self.assertEqual(row["InitialDifference"], 15)
|
||||||
|
self.assertEqual(row["LooseContainers"], 1)
|
||||||
|
|
||||||
|
def test_non_shelved_is_a_not_b(self):
|
||||||
|
row = report(stock(Cell=1000)).rows[0]
|
||||||
|
self.assertEqual((row["NonShelved"], row["Packing"], row["UDCs"]), (20, 0, 1))
|
||||||
|
|
||||||
|
def test_multilot_counts_udc_once_and_keeps_lots(self):
|
||||||
|
r = report(stock(), stock(ContainerId=4, Lot="L2", Serial="600001/000004"))
|
||||||
|
self.assertEqual((r.rows[0]["UDCs"], r.rows[0]["WMS"]), (1, 40))
|
||||||
|
self.assertEqual(len(r.lots), 2)
|
||||||
|
|
||||||
|
def test_multi_product_udc(self):
|
||||||
|
r = report(stock(), stock(ContainerId=4, Product="P2"))
|
||||||
|
self.assertEqual([row["UDCs"] for row in r.rows], [1, 1])
|
||||||
|
|
||||||
|
def test_lot_offsets_do_not_look_like_a_match(self):
|
||||||
|
row = report(stock(SamQuantity=10), stock(ContainerId=2, Lot="L2", SamQuantity=30)).rows[0]
|
||||||
|
self.assertEqual(row["Difference"], 0)
|
||||||
|
self.assertIn("lot_offsets", row["Issues"])
|
||||||
|
|
||||||
|
def test_multilocation_does_not_double_sam(self):
|
||||||
|
r = report(stock(Locations=2), stock(Locations=2, Cell=8004))
|
||||||
|
self.assertEqual((r.rows[0]["SAM"], r.rows[0]["UDCs"]), (20, 1))
|
||||||
|
self.assertIsNone(r.rows[0]["WMS"])
|
||||||
|
self.assertIn("locations", r.rows[0]["Issues"])
|
||||||
|
|
||||||
|
def test_duplicate_incompatible_data_invalidates(self):
|
||||||
|
row = report(stock(), stock(Quantity=50)).rows[0]
|
||||||
|
self.assertIn("duplicate", row["Issues"])
|
||||||
|
self.assertIsNone(row["SAM"])
|
||||||
|
|
||||||
|
def test_missing_content_is_not_zero(self):
|
||||||
|
row = report(stock(Quantity=None)).rows[0]
|
||||||
|
self.assertIsNone(row["WMS"])
|
||||||
|
self.assertIsNone(row["Difference"])
|
||||||
|
self.assertEqual(row["SAM"], 20)
|
||||||
|
|
||||||
|
def test_shipped_residual_is_not_packaging(self):
|
||||||
|
row = report(
|
||||||
|
stock(), stock(Component="X", ContainerId=9, Pallet="600009",
|
||||||
|
Cell=None, Locations=1, Shipped=1, Quantity=5, SamQuantity=5)).rows[0]
|
||||||
|
self.assertEqual((row["Packing"], row["SAM"], row["Difference"]), (0, 25, 5))
|
||||||
|
self.assertIn("shipped", row["Issues"])
|
||||||
|
|
||||||
|
def test_sam_zero_does_not_hide_wms_presence(self):
|
||||||
|
row = report(stock(SamQuantity=0)).rows[0]
|
||||||
|
self.assertEqual((row["WMS"], row["Difference"]), (20, -20))
|
||||||
|
|
||||||
|
def test_partial_container_uses_actual_quantity(self):
|
||||||
|
row = report(loose(Quantity=Decimal("3.5"), SamQuantity=Decimal("3.5"))).rows[0]
|
||||||
|
self.assertEqual(row["Loose"], Decimal("3.5"))
|
||||||
|
|
||||||
|
def test_history_missing_or_ambiguous_is_not_certified(self):
|
||||||
|
for r in (build_report(DAY, [stock()]), report(stock(AssignmentIssue=1)),
|
||||||
|
build_report(date(2020, 1, 1), [HISTORY, stock()])):
|
||||||
|
self.assertIn("history", r.rows[0]["Issues"])
|
||||||
|
self.assertIsNone(r.rows[0]["Difference"])
|
||||||
|
|
||||||
|
def test_movements_missing_invalidates_sam(self):
|
||||||
|
row = report(stock(MovementIssues=1)).rows[0]
|
||||||
|
self.assertIsNone(row["SAM"])
|
||||||
|
|
||||||
|
def test_negative_balance_flagged(self):
|
||||||
|
row = report(loose(Quantity=-5, SamQuantity=-5)).rows[0]
|
||||||
|
self.assertIn("negative", row["Issues"])
|
||||||
|
self.assertIsNone(row["Difference"])
|
||||||
|
|
||||||
|
def test_other_receipt_requires_validation(self):
|
||||||
|
row = report(stock(OtherReceipts=1)).rows[0]
|
||||||
|
self.assertIsNone(row["WMS"])
|
||||||
|
|
||||||
|
def test_unknown_unit(self):
|
||||||
|
row = report(stock(Unit="KG")).rows[0]
|
||||||
|
self.assertIn("unit", row["Issues"])
|
||||||
|
self.assertIsNone(row["SAM"])
|
||||||
|
|
||||||
|
def test_undated_wms(self):
|
||||||
|
row = report(stock(), dict(Kind="META", Component="UNDATED", Quantity=1)).rows[0]
|
||||||
|
self.assertIsNone(row["Difference"])
|
||||||
|
|
||||||
|
def test_missing_label_remains_visible(self):
|
||||||
|
row = report(stock(Product=None, ContainerId=None, Quantity=None)).rows[0]
|
||||||
|
self.assertIn("600001", row["Product"])
|
||||||
|
self.assertIsNone(row["WMS"])
|
||||||
|
|
||||||
|
def test_empty_report(self):
|
||||||
|
r = report()
|
||||||
|
self.assertEqual((r.rows, r.lots, r.details), ([], [], []))
|
||||||
|
|
||||||
|
def test_export_roundtrip(self):
|
||||||
|
from openpyxl import load_workbook
|
||||||
|
r = report(stock(Product="=CODE"), stock(Product="P2", ContainerId=2, Quantity=None))
|
||||||
|
with tempfile.TemporaryDirectory() as folder:
|
||||||
|
path = str(Path(folder) / "inventory.xlsx")
|
||||||
|
export_inventory(r, path, translate=text)
|
||||||
|
wb = load_workbook(path)
|
||||||
|
ws = wb.active
|
||||||
|
self.assertEqual(len(wb.worksheets), 3)
|
||||||
|
self.assertEqual(ws["B1"].value.date(), DAY)
|
||||||
|
self.assertEqual((ws["A7"].value, ws["A7"].data_type), ("=CODE", "s"))
|
||||||
|
diff_col = SUMMARY_KEYS.index("Difference") + 1
|
||||||
|
self.assertEqual(ws.cell(7, diff_col).value, 0)
|
||||||
|
self.assertIsNone(ws.cell(8, SUMMARY_KEYS.index("WMS")+1).value)
|
||||||
|
self.assertEqual(ws.freeze_panes, "A7")
|
||||||
|
self.assertEqual(wb.worksheets[2].cell(2, DETAIL_KEYS.index("Serial")+1).value, "600001/000001")
|
||||||
|
wb.close()
|
||||||
|
|
||||||
|
def test_translations_complete(self):
|
||||||
|
catalog = json.loads(Path("locale.json").read_text(encoding="utf-8"))
|
||||||
|
for language in ("IT", "ENG"):
|
||||||
|
for key in SUMMARY_KEYS + DETAIL_KEYS:
|
||||||
|
self.assertIn("inventory.col." + key, catalog[language])
|
||||||
|
for component in "ABCX":
|
||||||
|
self.assertIn("inventory.component." + component, catalog[language])
|
||||||
|
self.assertEqual({k for k in catalog["IT"] if k.startswith("inventory.")},
|
||||||
|
{k for k in catalog["ENG"] if k.startswith("inventory.")})
|
||||||
|
|
||||||
|
def test_sqlalchemy_has_only_two_actual_bind_markers(self):
|
||||||
|
from sqlalchemy import text as sql_text
|
||||||
|
from sqlalchemy.dialects.mssql.pyodbc import dialect
|
||||||
|
from inventory_service import SQL_PATH
|
||||||
|
compiled = sql_text(SQL_PATH.read_text(encoding="utf-8")).compile(dialect=dialect(paramstyle="qmark"))
|
||||||
|
self.assertEqual(compiled.positiontup, ["cutoff", "sam_cutoff"])
|
||||||
|
|
||||||
|
|
||||||
|
class InventoryAsyncTests(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def test_bound_cutoffs_without_commit(self):
|
||||||
|
db = type("DB", (), {"query_json": AsyncMock(return_value={"rows": []})})()
|
||||||
|
r = await load_inventory(db, "31/12/2025")
|
||||||
|
args, kwargs = db.query_json.call_args
|
||||||
|
self.assertEqual(args[1]["cutoff"], datetime(2026, 1, 1))
|
||||||
|
self.assertEqual(args[1]["sam_cutoff"], 46023)
|
||||||
|
self.assertNotIn("commit", kwargs)
|
||||||
|
self.assertEqual(r.selected_date, DAY)
|
||||||
|
|
||||||
|
async def test_invalid_date_never_queries(self):
|
||||||
|
db = type("DB", (), {"query_json": AsyncMock()})()
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
await load_inventory(db, "31/02/2025")
|
||||||
|
db.query_json.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
140
tests/test_inventory_gui.py
Normal file
140
tests/test_inventory_gui.py
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
"""Real Tk widget checks with synthetic report data; no database connection."""
|
||||||
|
|
||||||
|
import tkinter as tk
|
||||||
|
import unittest
|
||||||
|
import warnings
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
import customtkinter as ctk
|
||||||
|
|
||||||
|
from inventario import InventarioWindow, display_number
|
||||||
|
from inventory_service import build_report
|
||||||
|
from test_inventory import stock, HISTORY
|
||||||
|
|
||||||
|
|
||||||
|
class InventoryGuiTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.root = ctk.CTk()
|
||||||
|
self.root.withdraw()
|
||||||
|
self.win = InventarioWindow(self.root, Mock())
|
||||||
|
self.win.withdraw()
|
||||||
|
self.root.update_idletasks()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
for token in self.root.tk.call("after", "info"):
|
||||||
|
try:
|
||||||
|
# Cancel the timer without deleting another widget's Tcl command.
|
||||||
|
self.root.tk.call("after", "cancel", token)
|
||||||
|
except tk.TclError:
|
||||||
|
pass
|
||||||
|
self.win.destroy()
|
||||||
|
self.root.destroy()
|
||||||
|
|
||||||
|
def sample(self):
|
||||||
|
return build_report(date(2025, 12, 31), [
|
||||||
|
HISTORY,
|
||||||
|
stock(Product="A", Quantity=Decimal(10), SamQuantity=Decimal(10)),
|
||||||
|
stock(Product="B", ContainerId=2, Quantity=Decimal(2), SamQuantity=Decimal(2)),
|
||||||
|
])
|
||||||
|
|
||||||
|
def test_no_query_at_open_and_render_zeros(self):
|
||||||
|
self.win.db_client.query_json.assert_not_called()
|
||||||
|
self.win._loaded(self.sample())
|
||||||
|
values = self.win.tree.item("0", "values")
|
||||||
|
self.assertEqual(values[3:9], ("1", "10", "0", "10", "0", "0"))
|
||||||
|
self.assertEqual(self.win.btn_export.cget("state"), "normal")
|
||||||
|
self.assertIn("31/12/2025", self.win.var_status.get())
|
||||||
|
|
||||||
|
def test_selection_populates_lot_and_container_details(self):
|
||||||
|
self.win._loaded(self.sample())
|
||||||
|
self.win.tree.selection_set("0")
|
||||||
|
self.win._select()
|
||||||
|
self.assertEqual(len(self.win.lot_tree.get_children()), 1)
|
||||||
|
self.assertEqual(len(self.win.detail_tree.get_children()), 1)
|
||||||
|
|
||||||
|
def test_sort_uses_numbers_not_formatted_strings(self):
|
||||||
|
self.win._loaded(self.sample())
|
||||||
|
self.win._sort("SAM")
|
||||||
|
self.assertEqual([r["Product"] for r in self.win._rows], ["B", "A"])
|
||||||
|
self.win._sort("SAM")
|
||||||
|
self.assertEqual([r["Product"] for r in self.win._rows], ["A", "B"])
|
||||||
|
|
||||||
|
def test_load_disables_export_and_repeated_requests(self):
|
||||||
|
self.win._loaded(self.sample())
|
||||||
|
with patch.object(self.win._async, "run") as run:
|
||||||
|
self.win._load()
|
||||||
|
self.assertEqual(self.win.btn_export.cget("state"), "disabled")
|
||||||
|
self.win._load()
|
||||||
|
self.assertEqual(run.call_count, 1)
|
||||||
|
run.call_args.args[0].close()
|
||||||
|
|
||||||
|
def test_export_uses_result_date_not_edited_entry(self):
|
||||||
|
self.win._loaded(self.sample())
|
||||||
|
self.win.var_date.set("01/01/2026")
|
||||||
|
with patch("inventario.filedialog.asksaveasfilename", return_value="") as save:
|
||||||
|
self.win._export()
|
||||||
|
self.assertEqual(save.call_args.kwargs["initialfile"], "inventario_20251231.xlsx")
|
||||||
|
|
||||||
|
def test_decimal_formatting(self):
|
||||||
|
self.assertEqual(display_number(Decimal("0.000000")), "0")
|
||||||
|
self.assertEqual(display_number(Decimal("1200.000000")), "1200")
|
||||||
|
self.assertEqual(display_number(None), "?")
|
||||||
|
|
||||||
|
def test_failed_load_restores_controls_without_old_export(self):
|
||||||
|
self.win._loaded(self.sample())
|
||||||
|
with patch.object(self.win._async, "run") as run:
|
||||||
|
self.win._load()
|
||||||
|
run.call_args.args[0].close()
|
||||||
|
with patch("inventario.messagebox.showerror"), patch("inventario.log_exception"):
|
||||||
|
self.win._error(RuntimeError("Synthetic failure"))
|
||||||
|
self.assertEqual(self.win.btn_load.cget("state"), "normal")
|
||||||
|
self.assertEqual(self.win.btn_export.cget("state"), "disabled")
|
||||||
|
self.assertEqual(self.win.tree.get_children(), ())
|
||||||
|
|
||||||
|
|
||||||
|
class InventoryLauncherTests(unittest.TestCase):
|
||||||
|
def test_menu_opens_single_inventory_child(self):
|
||||||
|
from main import Launcher
|
||||||
|
from user_session import UserSession
|
||||||
|
session = UserSession(1, "TEST", "Test operator")
|
||||||
|
with warnings.catch_warnings(), patch.object(Launcher, "_apply_dynamic_geometry"), \
|
||||||
|
patch.object(Launcher, "lift"), patch.object(Launcher, "focus_force"):
|
||||||
|
warnings.simplefilter("error", UserWarning)
|
||||||
|
root = Launcher(session, Mock())
|
||||||
|
root.withdraw()
|
||||||
|
try:
|
||||||
|
self.assertIsInstance(root._exit_icon, ctk.CTkImage)
|
||||||
|
self.assertEqual(root._exit_icon.cget("size"), (14, 14))
|
||||||
|
for mode in ("light", "dark"):
|
||||||
|
for scale in (1, 2):
|
||||||
|
photo = root._exit_icon.create_scaled_photo_image(scale, mode)
|
||||||
|
self.assertEqual((photo.width(), photo.height()), (14 * scale, 14 * scale))
|
||||||
|
def widgets(widget):
|
||||||
|
for child in widget.winfo_children():
|
||||||
|
yield child
|
||||||
|
yield from widgets(child)
|
||||||
|
buttons = [w for w in widgets(root) if isinstance(w, ctk.CTkButton) and w.cget("text") == "Inventario"]
|
||||||
|
self.assertEqual(len(buttons), 1)
|
||||||
|
def create(*args, **kwargs):
|
||||||
|
win = InventarioWindow(*args, **kwargs)
|
||||||
|
win.withdraw()
|
||||||
|
return win
|
||||||
|
with patch("main.open_inventario_window", side_effect=create) as factory, \
|
||||||
|
patch("main.place_window_below_parent_later"), \
|
||||||
|
patch.object(InventarioWindow, "lift"), patch.object(InventarioWindow, "focus_force"):
|
||||||
|
buttons[0].invoke()
|
||||||
|
first = root._child_windows_by_key["inventario"]
|
||||||
|
buttons[0].invoke()
|
||||||
|
self.assertIs(root._child_windows_by_key["inventario"], first)
|
||||||
|
self.assertEqual(factory.call_count, 1)
|
||||||
|
root.db_client.query_json.assert_not_called()
|
||||||
|
finally:
|
||||||
|
for token in root.tk.call("after", "info"):
|
||||||
|
root.tk.call("after", "cancel", token)
|
||||||
|
root.destroy()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
139
tests/test_inventory_sql.py
Normal file
139
tests/test_inventory_sql.py
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
"""Opt-in SQL Server integration tests using ONLY local #temporary fixtures.
|
||||||
|
|
||||||
|
Set INVENTORY_TEST_CONFIG to a local db_connection.json. Source object names in
|
||||||
|
the production batch are replaced with #fixtures before execution: no warehouse
|
||||||
|
or ERP table is read or written by the test. Credentials are never printed.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import unittest
|
||||||
|
from datetime import date, datetime
|
||||||
|
|
||||||
|
from inventory_service import SQL_PATH, build_report
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(os.environ.get("INVENTORY_TEST_CONFIG"), "SQL fixture test is opt-in")
|
||||||
|
class InventorySQLTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
import pyodbc
|
||||||
|
with open(os.environ["INVENTORY_TEST_CONFIG"], encoding="utf-8") as handle:
|
||||||
|
c = json.load(handle)
|
||||||
|
self.cn = pyodbc.connect("DRIVER={" + c["driver"] + "};SERVER=" + c["server"]
|
||||||
|
+ ";DATABASE=" + c["database"] + ";UID=" + c["user"] + ";PWD=" + c["password"]
|
||||||
|
+ ";TrustServerCertificate=yes;", timeout=5)
|
||||||
|
self.cn.timeout = 60
|
||||||
|
self.addCleanup(self.cn.close)
|
||||||
|
self.addCleanup(self.cn.rollback)
|
||||||
|
self.cur = self.cn.cursor()
|
||||||
|
definitions = {
|
||||||
|
"ANAMAG": "ID int, DESCR varchar(100)",
|
||||||
|
"ALLMAG": "ID int, IDANAMAG int",
|
||||||
|
"MagazziniPallet": "Attributo varchar(20),IDCella int,Tipo char(1),PesoUnitario decimal(28,6),DataMagazzino datetime",
|
||||||
|
"Celle": "ID int,IDArea int,Corsia varchar(20),Colonna varchar(20),Fila varchar(20)",
|
||||||
|
"Aree": "ID int,IDMagazzino int",
|
||||||
|
"Magazzini": "ID int,Descrizione varchar(20)",
|
||||||
|
"LOTSER": "ID int,IDARTICO int,NUMLOT varchar(30),NUMSER varchar(30)",
|
||||||
|
"EXTTACLOTSER": "IDLOTSER float,EXNUMSER varchar(30),NUMSER varchar(30),AGGIORNAMENTO datetime",
|
||||||
|
"GIAMAG": "IDARTICO int,IDMAG int,QTTGIAI decimal(28,6)",
|
||||||
|
"MOVMAG": "IDARTICO int,IDCAUMOV int,IDMAGPAR int,IDMAGARR int,QTAINV decimal(28,6),DATMOV float",
|
||||||
|
"CAUMOV": "ID int,CODICE varchar(10),QTGIUP char(1),QTGIUA char(1)",
|
||||||
|
"ARTICO": "ID int,CODICE varchar(30),DESCR varchar(100),UMI varchar(8)",
|
||||||
|
}
|
||||||
|
for name, definition in definitions.items():
|
||||||
|
self.cur.execute(f"CREATE TABLE #fixture_{name} ({definition})")
|
||||||
|
self.sql = SQL_PATH.read_text(encoding="utf-8")
|
||||||
|
for name in definitions:
|
||||||
|
self.sql = self.sql.replace("SAMA1.dbo." + name, "#fixture_" + name)
|
||||||
|
self.sql = self.sql.replace("dbo." + name, "#fixture_" + name)
|
||||||
|
self.assertNotIn("SAMA1.dbo.", self.sql)
|
||||||
|
self.assertNotIn("dbo.", self.sql)
|
||||||
|
self.sql = self.sql.replace(":sam_cutoff", "?").replace(":cutoff", "?")
|
||||||
|
self.insert("ANAMAG", (20, "Magazzino Principale"))
|
||||||
|
self.insert("ALLMAG", (4, 20), (6, 30))
|
||||||
|
self.insert("Magazzini", (1, "MDE5"), (2, "MDE6"), (3, "OTHER"))
|
||||||
|
self.insert("Aree", (1, 1), (2, 2), (3, 3))
|
||||||
|
self.insert("Celle", (1101, 1, "1A", "1", "a"), (8004, 2, "4P", "1", "d"),
|
||||||
|
(1000, 1, "5E", "1", "1"), (9999, 1, "7G", "1", "1"),
|
||||||
|
(9900, 3, "Z", "1", "1"))
|
||||||
|
self.insert("ARTICO", (1, "PROD", "Product", "NR"))
|
||||||
|
self.insert("CAUMOV", (1, "CP", None, "+"), (2, "VEN", "-", None))
|
||||||
|
self.insert("EXTTACLOTSER", (999, "000000/000999", "600999/000999", datetime(2022, 1, 1)))
|
||||||
|
self.day = date(2026, 1, 1)
|
||||||
|
self.cutoff = datetime(2026, 1, 2)
|
||||||
|
self.serial_cutoff = (self.cutoff - datetime(1899, 12, 30)).days
|
||||||
|
for pallet, cell in (("600001", 1101), ("600002", 1000), ("600006", 9999), ("600007", 9999)):
|
||||||
|
self.insert("MagazziniPallet", (pallet, cell, "V", 1, datetime(2025, 12, 30)))
|
||||||
|
# Real WMS stock: 60 + 40 + 10 pieces. ID3 is another lot in the SAME UDC.
|
||||||
|
self.container(1, "L1", "600001/000001", 60, 0)
|
||||||
|
self.container(2, "L1", "600002/000002", 40, 40)
|
||||||
|
self.container(3, "L2", "600001/000003", 10, 10)
|
||||||
|
self.container(4, "L1", "600004/000004", 30, 30) # partial packing UDC
|
||||||
|
self.container(5, "L1", "000000/000005", 20, 20)
|
||||||
|
self.container(6, "L1", "600006/000006", 15, 15) # shipped with SAM residual
|
||||||
|
self.container(7, "L1", "600007/000007", 99, 0) # fully shipped
|
||||||
|
self.container(8, "EXCLUDED", "000000/000008", 777, 777) # same product, other lot
|
||||||
|
self.container(9, "L1", "600009/000009", 6, 6) # was unassigned at cutoff
|
||||||
|
self.insert("EXTTACLOTSER", (9, "000000/000009", "600009/000009", datetime(2026, 1, 3)))
|
||||||
|
# ID1 shipped AFTER inventory. Current GIAMAG=0 must be reversed to 60.
|
||||||
|
self.insert("MOVMAG", (1, 2, 4, None, 60, self.serial_cutoff + 1))
|
||||||
|
self.insert("MagazziniPallet", ("600001", 1101, "P", 1, datetime(2026, 1, 3)),
|
||||||
|
("600001", 9999, "V", 1, datetime(2026, 1, 3)))
|
||||||
|
|
||||||
|
def insert(self, name, *rows):
|
||||||
|
for row in rows:
|
||||||
|
self.cur.execute(f"INSERT INTO #fixture_{name} VALUES ({','.join('?' for _ in row)})", row)
|
||||||
|
|
||||||
|
def container(self, identity, lot, serial, receipt, current):
|
||||||
|
self.insert("LOTSER", (identity, 1, lot, serial))
|
||||||
|
self.insert("GIAMAG", (identity, 4, current))
|
||||||
|
self.insert("MOVMAG", (identity, 1, None, 4, receipt, self.serial_cutoff - 2))
|
||||||
|
|
||||||
|
def run_query(self):
|
||||||
|
self.cur.execute(self.sql, self.cutoff, self.serial_cutoff)
|
||||||
|
columns = [c[0] for c in self.cur.description]
|
||||||
|
records = [dict(zip(columns, row)) for row in self.cur.fetchall()]
|
||||||
|
return build_report(self.day, records)
|
||||||
|
|
||||||
|
def test_scope_history_shipments_three_components(self):
|
||||||
|
r = self.run_query()
|
||||||
|
row = r.rows[0]
|
||||||
|
self.assertEqual((row["WMS"], row["Packing"], row["Loose"], row["SAM"], row["Difference"]),
|
||||||
|
(110, 30, 26, 181, 15))
|
||||||
|
self.assertEqual((row["UDCs"], row["PackingUDCs"], row["LooseContainers"]), (2, 1, 2))
|
||||||
|
self.assertEqual({x["Lot"] for x in r.lots}, {"L1", "L2"})
|
||||||
|
by_id = {x["ContainerId"]: x for x in r.details}
|
||||||
|
self.assertEqual(by_id[9]["Component"], "C")
|
||||||
|
self.assertEqual(by_id[9]["Serial"], "000000/000009")
|
||||||
|
self.assertEqual(by_id[6]["Component"], "X")
|
||||||
|
self.assertNotIn(7, by_id)
|
||||||
|
self.assertNotIn(8, by_id)
|
||||||
|
self.assertEqual(by_id[1]["SamQuantity"], 60)
|
||||||
|
|
||||||
|
def test_principal_only_and_incremental_receipts(self):
|
||||||
|
self.insert("GIAMAG", (4, 6, 10000))
|
||||||
|
self.insert("MOVMAG", (1, 1, None, 4, 5, self.serial_cutoff - 1))
|
||||||
|
row = self.run_query().rows[0]
|
||||||
|
self.assertEqual(row["WMS"], 115)
|
||||||
|
self.assertEqual(row["SAM"], 181)
|
||||||
|
|
||||||
|
def test_multiple_locations_never_double_sam(self):
|
||||||
|
self.insert("MagazziniPallet", ("600001", 8004, "V", 1, datetime(2025, 12, 31)))
|
||||||
|
row = self.run_query().rows[0]
|
||||||
|
self.assertEqual(row["SAM"], 181)
|
||||||
|
self.assertIsNone(row["WMS"])
|
||||||
|
self.assertIn("locations", row["Issues"])
|
||||||
|
|
||||||
|
def test_assignment_tie_is_unknown(self):
|
||||||
|
self.insert("EXTTACLOTSER", (9, "000000/000009", "600010/000009", datetime(2026, 1, 3)))
|
||||||
|
row = self.run_query().rows[0]
|
||||||
|
self.assertIn("history", row["Issues"])
|
||||||
|
self.assertIsNone(row["Difference"])
|
||||||
|
|
||||||
|
def test_midnight_is_exclusive(self):
|
||||||
|
self.insert("MOVMAG", (2, 2, 4, None, 7, self.serial_cutoff))
|
||||||
|
row = self.run_query().rows[0]
|
||||||
|
self.assertEqual(row["SAM"], 188)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -1,154 +0,0 @@
|
|||||||
"""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")
|
|
||||||
@@ -1,161 +0,0 @@
|
|||||||
"""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()
|
|
||||||
@@ -1,133 +0,0 @@
|
|||||||
"""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()
|
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
{
|
{
|
||||||
"default_language": "IT",
|
"default_language": "IT",
|
||||||
"IT": {
|
"IT": {
|
||||||
|
"launcher.open_inventory": "Confronta WMS e Magazzino Principale SAM a fine giornata, con dettaglio UDC, anomalie ed esportazione XLSX. Ricostruzione da validare.",
|
||||||
"launcher.open_reset_corsie": "Apre la finestra di gestione corsie per visualizzare il contenuto di una corsia e svuotarla in modo controllato.",
|
"launcher.open_reset_corsie": "Apre la finestra di gestione corsie per visualizzare il contenuto di una corsia e svuotarla in modo controllato.",
|
||||||
"launcher.open_layout": "Apre la vista layout delle corsie con celle, UDC presenti e menu operativo contestuale.",
|
"launcher.open_layout": "Apre la vista layout delle corsie con celle, UDC presenti e menu operativo contestuale.",
|
||||||
"launcher.open_multi_udc": "Apre la vista UDC fantasma per analizzare celle con piu' pallet e bonificare i candidati fantasma.",
|
"launcher.open_multi_udc": "Apre la vista UDC fantasma per analizzare celle con piu' pallet e bonificare i candidati fantasma.",
|
||||||
@@ -44,6 +45,7 @@
|
|||||||
"picking.sequence.close": "Chiude la finestra senza effettuare altri salvataggi."
|
"picking.sequence.close": "Chiude la finestra senza effettuare altri salvataggi."
|
||||||
},
|
},
|
||||||
"ENG": {
|
"ENG": {
|
||||||
|
"launcher.open_inventory": "Compare WMS and SAM main warehouse at end of day, with UDC details, data-quality warnings and XLSX export. Reconstruction requires validation.",
|
||||||
"launcher.open_reset_corsie": "Open the aisle management window to inspect an aisle and empty it in a controlled way.",
|
"launcher.open_reset_corsie": "Open the aisle management window to inspect an aisle and empty it in a controlled way.",
|
||||||
"launcher.open_layout": "Open the aisle layout view with cells, present UDCs and the operational context menu.",
|
"launcher.open_layout": "Open the aisle layout view with cells, present UDCs and the operational context menu.",
|
||||||
"launcher.open_multi_udc": "Open the ghost UDC view to inspect cells with multiple pallets and clean ghost candidates.",
|
"launcher.open_multi_udc": "Open the ghost UDC view to inspect cells with multiple pallets and clean ghost candidates.",
|
||||||
|
|||||||
@@ -1,4 +1,13 @@
|
|||||||
{
|
{
|
||||||
|
"inventory_window": {
|
||||||
|
"window_geometry": "1200x720",
|
||||||
|
"window_minsize": [900, 560],
|
||||||
|
"window_fg_color": ["#efefef", "#2f2f2f"],
|
||||||
|
"toolbar_frame_fg_color": ["#d7d7d7", "#3b3b3b"],
|
||||||
|
"toolbar_button_font": ["Segoe UI", 11, "bold"],
|
||||||
|
"difference_color": "#9b3900",
|
||||||
|
"unknown_color": "#aa0000"
|
||||||
|
},
|
||||||
"global": {
|
"global": {
|
||||||
"window_bg": ["#f1f1f1", "#2b2b2b"],
|
"window_bg": ["#f1f1f1", "#2b2b2b"],
|
||||||
"panel_bg": ["#d9d9d9", "#3a3a3a"],
|
"panel_bg": ["#d9d9d9", "#3a3a3a"],
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ ALL_ACTIONS: FrozenSet[str] = frozenset(
|
|||||||
"launcher.open_pickinglist",
|
"launcher.open_pickinglist",
|
||||||
"launcher.open_history_pickinglist",
|
"launcher.open_history_pickinglist",
|
||||||
"launcher.open_diagnostics",
|
"launcher.open_diagnostics",
|
||||||
|
"launcher.open_inventory",
|
||||||
"launcher.arrange_windows",
|
"launcher.arrange_windows",
|
||||||
"launcher.exit",
|
"launcher.exit",
|
||||||
"reset_corsie.view",
|
"reset_corsie.view",
|
||||||
@@ -29,6 +30,7 @@ ALL_ACTIONS: FrozenSet[str] = frozenset(
|
|||||||
"history_udc.view",
|
"history_udc.view",
|
||||||
"history_pickinglist.view",
|
"history_pickinglist.view",
|
||||||
"diagnostics.view",
|
"diagnostics.view",
|
||||||
|
"inventory.view",
|
||||||
"multi_udc.view",
|
"multi_udc.view",
|
||||||
"layout.view",
|
"layout.view",
|
||||||
"layout.carico",
|
"layout.carico",
|
||||||
|
|||||||
@@ -12,24 +12,23 @@ MODULE_VERSIONS: dict[str, str] = {
|
|||||||
"async_loop_singleton": "1.0.0",
|
"async_loop_singleton": "1.0.0",
|
||||||
"async_msssql_query": "1.0.1",
|
"async_msssql_query": "1.0.1",
|
||||||
"audit_log": "1.0.0",
|
"audit_log": "1.0.0",
|
||||||
"main": "1.0.2",
|
"main": "1.0.4",
|
||||||
"barcode_client": "2.1.0",
|
"inventario": "1.1.0",
|
||||||
"barcode_repository": "2.1.0",
|
"inventory_service": "1.1.0",
|
||||||
"barcode_service": "2.1.0",
|
"barcode_client": "1.0.27",
|
||||||
"barcode_pair_service": "2.1.0",
|
"barcode_repository": "1.0.14",
|
||||||
|
"barcode_service": "1.0.25",
|
||||||
"busy_overlay": "1.0.0",
|
"busy_overlay": "1.0.0",
|
||||||
"db_config": "1.0.0",
|
"db_config": "1.0.0",
|
||||||
"diagnostica": "1.0.4",
|
"diagnostica": "1.0.4",
|
||||||
"gestione_aree": "1.0.1",
|
"gestione_aree": "1.0.1",
|
||||||
"gestione_layout": "1.0.2",
|
"gestione_layout": "1.0.2",
|
||||||
"gestione_pickinglist": "2.1.0",
|
"gestione_pickinglist": "1.0.6",
|
||||||
"gestione_scarico": "1.0.8",
|
"gestione_scarico": "1.0.8",
|
||||||
"locale_text": "1.0.0",
|
"locale_text": "1.0.0",
|
||||||
"login_window": "1.0.0",
|
"login_window": "1.0.0",
|
||||||
"prenota_sprenota_sql": "1.0.1",
|
"prenota_sprenota_sql": "1.0.1",
|
||||||
"pickinglist_sequence": "2.1.0",
|
"pickinglist_sequence": "1.0.0",
|
||||||
"pickinglist_pair": "2.1.0",
|
|
||||||
"pickinglist_pair_repository": "2.1.0",
|
|
||||||
"reset_corsie": "1.0.0",
|
"reset_corsie": "1.0.0",
|
||||||
"runtime_support": "1.0.1",
|
"runtime_support": "1.0.1",
|
||||||
"search_pallets": "1.0.0",
|
"search_pallets": "1.0.0",
|
||||||
@@ -38,7 +37,7 @@ MODULE_VERSIONS: dict[str, str] = {
|
|||||||
"tooltips": "1.0.0",
|
"tooltips": "1.0.0",
|
||||||
"udc_non_scaffalate": "1.0.1",
|
"udc_non_scaffalate": "1.0.1",
|
||||||
"ui_theme": "1.0.0",
|
"ui_theme": "1.0.0",
|
||||||
"user_session": "1.0.2",
|
"user_session": "1.0.3",
|
||||||
"view_celle_multi_udc": "1.0.0",
|
"view_celle_multi_udc": "1.0.0",
|
||||||
"window_placement": "1.0.0",
|
"window_placement": "1.0.0",
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user