Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9d87b07648 | |||
| fc43cbb7ec | |||
| 106ea49f64 | |||
| e4b227e82c | |||
| 85b11834b6 | |||
| 588bf6ce73 | |||
| d3941e88cc | |||
| 04406e840d | |||
| a60610c03e | |||
| 3a2893dc3d | |||
| 5dc26b21b1 | |||
| 0ae052e55b | |||
| 7dc068b1b0 | |||
| 1ea37eb49d | |||
| 7f3ce9d3af | |||
| 8e9294f80b | |||
| fa9d0be09a | |||
| 44cd82352b | |||
| eb12af3b9a | |||
| 77da8d9bad | |||
| 5dd7139b19 | |||
| d4cfe0be54 | |||
| f4e73bd5b9 | |||
| e575c748cc | |||
| 7ecc906d59 | |||
| 29687c8094 | |||
| bd844ce056 | |||
| 466778ae5f | |||
| cc9680c49a | |||
| be7ce700d1 | |||
| 29900b8b09 | |||
| 8f9957a2db |
70
FREEZE_2.0_WAREHOUSE_MONOLISTA.md
Normal file
70
FREEZE_2.0_WAREHOUSE_MONOLISTA.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# Warehouse monolista - freeze 2.0
|
||||
|
||||
Data: 02/10/2026.
|
||||
Titolo release: warehouse monolista.
|
||||
Tag Git: `warehouse-monolista-2.0`.
|
||||
|
||||
## Scopo e contenuto
|
||||
|
||||
Punto di ripristino prima dello sviluppo del prelievo guidato di due liste.
|
||||
La versione conserva la prenotazione singola e i cicli F1/F2 separati.
|
||||
Include i sorgenti e gli script SQL gia' versionati, oltre alla correzione
|
||||
del documento fisso F1/F2, ai suoi test e alla relativa documentazione.
|
||||
|
||||
La denominazione 2.0 identifica questo freeze, non una rinumerazione di tutti
|
||||
i moduli. Il barcode conserva la versione visibile 1.0.27; repository 1.0.14,
|
||||
servizio 1.0.25. Il registro delle versioni resta `version_info.py`.
|
||||
|
||||
La specifica `specifica_prelievo_due_pickinglist.md` descrive lo sviluppo
|
||||
successivo, NON una funzionalita' gia' implementata in questa release.
|
||||
Comprende il vincolo di due liste nella stessa area operativa (5 oppure 6).
|
||||
|
||||
## Verifiche del freeze
|
||||
|
||||
Gli 11 test di `tests/test_barcode_document_binding.py` sono passati con:
|
||||
|
||||
```bat
|
||||
python -B -m unittest discover -s tests -v
|
||||
```
|
||||
|
||||
Si tratta di test automatici con repository simulato, non di un collaudo
|
||||
completo della GUI o del terminalino fisico. Non eseguono movimenti sul DB.
|
||||
|
||||
## Database e file locali
|
||||
|
||||
La correzione F1/F2 non richiede nuovi oggetti SQL. Le patch gia' necessarie
|
||||
alla versione precedente restano nel repository, inclusa
|
||||
`apply_online_python_wms_full_patch.sql`. Questo freeze non esegue patch SQL
|
||||
e non costituisce un backup dei database Mediseawall e SAM.
|
||||
|
||||
Gli script in `sql_tests/` servono soltanto alla preparazione locale dei test:
|
||||
NON lanciarli in produzione. Il ripristino delle sole testate non annulla
|
||||
eventuali movimenti successivi; leggere `sql_tests/README.md`.
|
||||
|
||||
Configurazione locale `db_connection.json`, log, cache, impostazioni IDE,
|
||||
registrazioni e vecchi ZIP locali non vengono aggiunti a questo commit.
|
||||
Conservare separatamente configurazione e backup coerenti dei database
|
||||
prima di modificare schema o dati per il futuro prelievo abbinato.
|
||||
|
||||
## Recuperare esattamente il freeze
|
||||
|
||||
Chiudere l'applicazione. Nella cartella del repository, con working tree pulito:
|
||||
|
||||
```bat
|
||||
git fetch origin --tags
|
||||
git switch --detach warehouse-monolista-2.0
|
||||
git describe --tags --exact-match
|
||||
python -m pip install -r requirements.txt
|
||||
```
|
||||
|
||||
Se Git segnala modifiche locali, fermarsi e salvarle prima: non forzare la
|
||||
sovrascrittura della configurazione o dei sorgenti. Per una prima installazione:
|
||||
|
||||
```bat
|
||||
git clone --branch warehouse-monolista-2.0 --single-branch https://gitea.alessandrobonvicini.it/administrator/ware_house.git C:\flywms-monolista-2.0
|
||||
```
|
||||
|
||||
Il checkout di un tag e' intenzionalmente in detached HEAD: identifica una
|
||||
versione fissa. `git pull origin main` non e' il comando per restare su questo
|
||||
freeze. Il ritorno al codice precedente non ripristina il database: eventuali
|
||||
future patch richiederanno il rispettivo rollback compatibile o un backup.
|
||||
235
GUIDA_INVENTARIO.md
Normal file
235
GUIDA_INVENTARIO.md
Normal file
@@ -0,0 +1,235 @@
|
||||
# Inventario WMS / SAM: guida alla schermata
|
||||
|
||||
Versione della schermata: **1.1.1**, monolista. Aggiornamento: 21/10/2026.
|
||||
|
||||
## 1. A cosa serve
|
||||
|
||||
La schermata confronta i pezzi ricostruiti dalle registrazioni del WMS e dei
|
||||
contenitori con i pezzi risultanti nel **Magazzino Principale di SAM**, alla
|
||||
fine del giorno scelto. Non movimenta materiale e non corregge automaticamente
|
||||
le differenze: serve a individuarle e a capire dove cercare.
|
||||
|
||||
**Attenzione al perimetro:** per ora e' il WMS a guidare la ricerca.
|
||||
Si parte dalle coppie prodotto/lotto presenti nelle UDC del WMS, nelle aree
|
||||
5 e 6 oppure non scaffalate, alla data scelta. Per quelle coppie si cercano
|
||||
anche i contenitori in SAM. Un lotto presente soltanto in confezionamento,
|
||||
senza alcuna UDC nel WMS, non entra nel report. Quindi non e' ancora un
|
||||
inventario completo di tutto SAM.
|
||||
|
||||
Una UDC puo' contenere piu' bag e piu' lotti. Una bag o una vasca e' un
|
||||
contenitore identificato in LOTSER: **contenitore, UDC e pezzi sono tre
|
||||
misure diverse**.
|
||||
|
||||
## 2. Come iniziare
|
||||
|
||||
1. Apri **Inventario** dal menu principale.
|
||||
2. Inserisci una data nel formato **gg/mm/aaaa**.
|
||||
3. Premi **Calcola inventario** e attendi la fine dell'overlay.
|
||||
4. Guarda **Esito / anomalie** e **Residuo SAM-(A+B+C)** nella griglia alta.
|
||||
5. Seleziona un prodotto: sotto compaiono le schede **Lotti** e **Contenitori**.
|
||||
6. Esamina prima il lotto che presenta la differenza, poi i relativi contenitori.
|
||||
7. Usa **Esporta XLSX** per conservare il risultato o proseguire la verifica.
|
||||
|
||||
Le colonne sono numerose: usa la barra orizzontale in fondo alla griglia.
|
||||
Cliccando un'intestazione della griglia prodotti puoi ordinare i risultati;
|
||||
un secondo clic inverte l'ordine. L'ordinamento puo' azzerare la selezione:
|
||||
riseleziona il prodotto per visualizzarne il dettaglio.
|
||||
|
||||
## 3. Legenda A, B, C e X
|
||||
|
||||
**A: materiale registrato nel WMS.**
|
||||
Sono i pezzi nelle UDC scaffalate nelle aree 5/6 oppure registrate come
|
||||
non scaffalate. Nella griglia, A corrisponde alla colonna **Pezzi WMS**.
|
||||
La quantita' nominale e' ricavata dai carichi produzione dei contenitori:
|
||||
va validata rispetto alle etichette, non e' una lettura fisica dei pezzi.
|
||||
|
||||
**B: materiale assegnato a UDC ma fuori dal WMS.**
|
||||
Sono contenitori con un numero UDC assegnato, giacenza SAM positiva alla data
|
||||
e nessuna posizione WMS che li collochi gia' in A o presenti anomalie.
|
||||
La collocazione in confezionamento e' **dedotta**, non rilevata fisicamente.
|
||||
Le UDC possono essere piene oppure ancora in riempimento: il report non
|
||||
determina quale dei due casi si verifichi.
|
||||
|
||||
**C: materiale non ancora assegnato a UDC.**
|
||||
Sono bag o vasche con seriale del tipo **000000/123456** e giacenza SAM
|
||||
positiva alla data. Possono essere parzialmente piene: si usano i pezzi
|
||||
registrati, non una capacita' teorica moltiplicata per il numero di bag.
|
||||
|
||||
**X: materiale con una classificazione anomala.**
|
||||
E' esposto nel dettaglio ma non viene aggiunto artificialmente ad A, B o C.
|
||||
Il suo saldo SAM contribuisce al confronto. Esempio: una UDC risulta spedita
|
||||
nel WMS ma ha ancora giacenza SAM. Il residuo deve far emergere il problema,
|
||||
non nasconderlo assegnandolo a B.
|
||||
|
||||
Una UDC non scaffalata gia' compresa in A **non viene contata anche in B**.
|
||||
Le UDC effettivamente spedite alla data non appartengono al normale stock A.
|
||||
La sola chiusura di un documento non sostituisce un movimento WMS mancante.
|
||||
|
||||
## 4. Comandi e messaggi in alto
|
||||
|
||||
| Campo o comando | Significato |
|
||||
| --- | --- |
|
||||
| Data (gg/mm/aaaa) | Giorno di riferimento, dalla fine del quale si ricostruisce l'inventario. Sono accettate date dal 01/01/2010 a oggi; cio' non garantisce che lo storico sia completo per ogni data. |
|
||||
| Calcola inventario | Avvia una nuova interrogazione. Aprire la finestra non avvia automaticamente il calcolo. Anche Invio nel campo data lo avvia. |
|
||||
| Esporta XLSX | Esporta l'ultimo risultato calcolato: prodotti, lotti e contenitori. Non esegue un nuovo calcolo. E' disabilitato prima del risultato, durante le operazioni o in assenza di righe. |
|
||||
| Legenda A/B/C/X | Definizioni fisse, separate dal messaggio di avanzamento: restano visibili dopo il calcolo. |
|
||||
| Inventario al ... (fine giornata) | Data effettiva del risultato, da controllare soprattutto se hai modificato il campo data senza premere Calcola. |
|
||||
| Prodotti | Numero di righe prodotto presenti nel report, non numero di UDC. |
|
||||
| Da verificare | Numero di prodotti con anomalie di ricostruzione. **Non e' il conteggio di tutte le differenze numeriche**: una differenza senza anomalie si legge nel residuo e nell'esito. |
|
||||
| Ultimo movimento WMS / SAM | Date massime dei movimenti rilevate nelle fonti. Non certificano quando e' stato effettuato il backup e non sono la data di ogni riga. |
|
||||
| Giornata corrente non ancora conclusa | Per oggi sono disponibili solo le operazioni gia' registrate: non e' possibile conoscere in anticipo lo stock di questa sera. |
|
||||
|
||||
Il limite temporale e' la mezzanotte successiva, esclusa. Ad esempio,
|
||||
per il 20/10 si considerano le operazioni precedenti alle 00:00 del 21/10.
|
||||
Non e' una funzionalita' riservata al 31 dicembre.
|
||||
|
||||
Se cambi solo la data nel campo, le righe gia' visualizzate e l'eventuale
|
||||
export rimangono riferiti all'ultimo calcolo. Premi Calcola per aggiornarli.
|
||||
In caso di errore del nuovo calcolo il risultato precedente viene svuotato,
|
||||
per evitare di scambiarlo per quello della nuova data.
|
||||
|
||||
## 5. Griglia principale: una riga per prodotto
|
||||
|
||||
I conteggi con **N.** contano identificativi distinti; gli altri valori
|
||||
quantitativi sono **pezzi**, non pallet.
|
||||
|
||||
| Colonna | Come leggerla |
|
||||
| --- | --- |
|
||||
| Prodotto | Codice articolo SAM. E' la chiave per raggruppare i lotti del prodotto inclusi nel perimetro. |
|
||||
| Descrizione | Descrizione dell'articolo. |
|
||||
| UM | Unita' di misura. Il calcolo accetta NR, PZ o PCS come pezzi; altre unita' richiedono verifica. |
|
||||
| N. UDC WMS | Numero di UDC distinte del prodotto comprese in A, scaffalate o non scaffalate. Una UDC con due lotti dello stesso prodotto conta una volta. |
|
||||
| Pezzi scaffalati | Pezzi di A nelle celle fisiche delle aree 5/6 alla data. |
|
||||
| Pezzi non scaffalati | Pezzi di A nella locazione virtuale non scaffalata, IDCella 1000. Non sono tutte le UDC presenti in SAM fuori WMS. |
|
||||
| Pezzi WMS | **A = Pezzi scaffalati + Pezzi non scaffalati**. E' il contenuto nominale delle UDC WMS ricostruito dai carichi produzione. |
|
||||
| N. UDC fuori WMS | Numero di UDC distinte nella componente B. Non e' il numero delle bag al loro interno. |
|
||||
| Pezzi B - UDC fuori WMS | Pezzi dei contenitori assegnati alle UDC B, usando la loro giacenza SAM alla data. |
|
||||
| N. contenitori senza UDC | Numero di identificativi LOTSER distinti in C: bag o vasche senza UDC. |
|
||||
| Pezzi C - Senza UDC | Pezzi presenti in quei contenitori C secondo il saldo SAM alla data. |
|
||||
| Totale A+B+C | Quantita' complessiva spiegata dalle tre componenti. Non include X. |
|
||||
| Pezzi SAM | Giacenza del Magazzino Principale per i soli prodotti/lotti compresi nel perimetro. Puo' includere saldi di contenitori classificati X. |
|
||||
| Differenza SAM-A | Differenza iniziale: **Pezzi SAM meno Pezzi WMS**. Serve a capire quanta parte potrebbe trovarsi fuori dal WMS. |
|
||||
| Residuo SAM-(A+B+C) | Differenza che rimane dopo aver aggiunto anche B e C. E' il principale valore da indagare. |
|
||||
| Esito / anomalie | Esito del confronto o motivi per cui il dato non e' determinabile/affidabile. Un saldo zero con anomalie non va considerato automaticamente corretto. |
|
||||
|
||||
**Non sommare indiscriminatamente N. UDC WMS tra prodotti:** una UDC
|
||||
multicomponente puo' essere contata una volta in ciascun prodotto.
|
||||
Analogamente non si sommano i conteggi UDC dei lotti per ottenere il
|
||||
conteggio distinto del prodotto.
|
||||
|
||||
## 6. Scheda Lotti
|
||||
|
||||
Mostra solo i lotti del prodotto selezionato nella griglia alta.
|
||||
|
||||
La colonna **Lotto** identifica NUMLOT. **Prodotto**, **UM**, i conteggi,
|
||||
le componenti A/B/C, le differenze e l'esito hanno lo stesso significato
|
||||
della griglia principale, ma sono limitati alla coppia prodotto/lotto.
|
||||
Non e' ripetuta la descrizione del prodotto.
|
||||
|
||||
Controllare sempre questa scheda: un lotto con +100 pezzi e un altro con
|
||||
-100 producono zero sul prodotto, ma non sono due lotti corretti.
|
||||
Il programma segnala questa compensazione nell'esito del prodotto.
|
||||
|
||||
## 7. Scheda Contenitori
|
||||
|
||||
Mostra tutti i contenitori del prodotto selezionato, anche su piu' lotti.
|
||||
La selezione di una riga nella scheda Lotti non filtra ulteriormente questa
|
||||
scheda. Per isolare un lotto puoi usare i filtri del foglio XLSX.
|
||||
|
||||
| Colonna | Significato |
|
||||
| --- | --- |
|
||||
| Componente | A - WMS, B - UDC fuori WMS, C - Senza UDC oppure X - Anomalia / fuori perimetro. |
|
||||
| Prodotto | Codice del prodotto contenuto nella bag/vasca. |
|
||||
| Lotto | Lotto del contenitore, NUMLOT. |
|
||||
| UDC | Numero dell'UDC cui il contenitore risulta assegnato alla data. Vuoto per il prefisso 000000. |
|
||||
| ID LOTSER | Identificativo tecnico del record contenitore in SAM. Utile per una verifica puntuale; non e' il numero UDC. |
|
||||
| Seriale contenitore | NUMSER ricostruito alla data: ad esempio 554321/123245 oppure 000000/123456. |
|
||||
| Cella alla data | Ubicazione WMS ricostruita. Per B/C senza cella compare Confezionamento (dedotto): non e' una cella fisica verificata. |
|
||||
| Pezzi della componente | Per A: pezzi nominali da carichi produzione. Per B/C: saldo SAM alla data. Per X: quantita' diagnostica, non inclusa in A+B+C. Un dato non determinabile compare come ?. |
|
||||
| Giacenza SAM contenitore | Saldo di quel singolo record LOTSER nel Magazzino Principale alla data. Puo' differire dal nominale di A. |
|
||||
| Esito / anomalie | Problemi specifici del contenitore. Una cella vuota in questa colonna significa nessuna anomalia specifica rilevata, non una certificazione fisica del contenuto. |
|
||||
|
||||
Il dettaglio serve alla diagnosi, non a una somma manuale indiscriminata:
|
||||
in caso di posizioni WMS anomale puo' comparire lo stesso contenitore piu'
|
||||
volte. Nel riepilogo il saldo SAM viene deduplicato e l'anomalia segnalata.
|
||||
|
||||
## 8. Esempio completo
|
||||
|
||||
Per un prodotto e i suoi lotti inclusi nel perimetro:
|
||||
|
||||
| Voce | Pezzi |
|
||||
| --- | ---: |
|
||||
| Scaffalati in WMS | 9.000 |
|
||||
| Non scaffalati in WMS | 1.000 |
|
||||
| A: Pezzi WMS | 10.000 |
|
||||
| B: in UDC fuori WMS | 400 |
|
||||
| C: bag/vasche senza UDC | 200 |
|
||||
| Totale A+B+C | 10.600 |
|
||||
| Pezzi SAM | 10.600 |
|
||||
| Differenza SAM-A | 600 |
|
||||
| Residuo SAM-(A+B+C) | 0 |
|
||||
|
||||
I 600 pezzi di differenza iniziale sono spiegati da B e C.
|
||||
Se SAM fosse 10.700 con le altre componenti invariate, rimarrebbero **+100**
|
||||
pezzi da spiegare. Se SAM fosse 10.500, il residuo sarebbe **-100**:
|
||||
la ricostruzione supererebbe SAM di 100 pezzi.
|
||||
|
||||
B e C derivano da SAM stesso: il pareggio indica coerenza documentale,
|
||||
non dimostra da solo che il materiale sia fisicamente in confezionamento.
|
||||
|
||||
## 9. Zero, punto interrogativo, colori ed esiti
|
||||
|
||||
- **0**: valore numerico noto pari a zero.
|
||||
- **?**: quantita' non determinabile. Non va sostituita con zero.
|
||||
- **Saldo coerente (nominale)**: residuo zero e nessuna anomalia rilevata dal calcolo.
|
||||
- **Differenza da verificare**: residuo diverso da zero senza ulteriori anomalie diagnostiche.
|
||||
- **Testo arancione/marrone**, nel tema attuale: riga con differenza numerica.
|
||||
- **Testo rosso**, nel tema attuale: riga con anomalie; controllare l'esito anche se alcuni valori sono numerici.
|
||||
|
||||
| Anomalia | Cosa controllare |
|
||||
| --- | --- |
|
||||
| Contenuto UDC non determinabile | Carichi produzione mancanti, non positivi o altre entrate che rendono ambiguo il contenuto nominale. |
|
||||
| UDC in piu' locazioni | Associazioni WMS multiple alla data scelta. |
|
||||
| Saldo movimenti UDC anomalo | Coerenza dei prelievi e versamenti WMS, presenza unitaria ed eventuali saldi negativi. |
|
||||
| Unita' di misura da verificare | UM diversa dai pezzi supportati, oppure incoerente nello stesso aggregato. |
|
||||
| Movimenti WMS privi di data | Movimenti senza una data utilizzabile: ricostruzione temporale non affidabile. |
|
||||
| Assegnazione storica non determinabile | Storico NUMSER assente, troppo recente rispetto alla data richiesta o ambiguo. |
|
||||
| Movimenti o saldo SAM non determinabili | Saldo o dati dei movimenti SAM insufficienti per la ricostruzione. |
|
||||
| Giacenza SAM negativa | Saldo negativo del contenitore. |
|
||||
| Seriale contenitore mancante o non valido | NUMSER non interpretabile nel formato atteso. |
|
||||
| Spedita WMS ma presenza residua da verificare | Incongruenza tra spedizione WMS e presenza/saldo residuo. |
|
||||
| Presenza fuori perimetro / classificazione anomala | Posizione non appartenente alle categorie ammesse o materiale non classificabile. |
|
||||
| Contenitore duplicato con dati incompatibili | Stesso contenitore restituito con attributi o quantita' contrastanti. |
|
||||
| Differenze tra lotti si compensano | Totale prodotto apparentemente corretto, ma differenze nei singoli lotti. |
|
||||
|
||||
Un'anomalia puo' rendere ignota solo una parte del risultato: le parti note
|
||||
restano consultabili. I totali dipendenti da un dato ignoto diventano ?.
|
||||
|
||||
## 10. Export e precauzioni
|
||||
|
||||
L'XLSX contiene tre fogli: **Inventario**, **Lotti** e **Contenitori**.
|
||||
Riporta data del calcolo, perimetro e avvertenze. Il foglio prodotti segue
|
||||
l'ordinamento scelto a video. I dettagli esportati comprendono tutti i
|
||||
prodotti del report, non solo quello selezionato. Le quantita' ignote sono
|
||||
celle vuote, mentre gli zeri reali restano numeri zero.
|
||||
|
||||
Eseguire la quadratura a movimentazioni ferme e con fonti WMS/SAM coerenti.
|
||||
Una copia WMS di ieri e una copia SAM di oggi possono generare differenze
|
||||
che non sono errori fisici. Il report non crea una fotografia atomica dei
|
||||
due database mentre altri operatori li stanno modificando.
|
||||
|
||||
Per una data storica il calcolo usa i movimenti e lo storico delle variazioni
|
||||
NUMSER disponibile. Uno storico incompleto o modifiche non tracciate
|
||||
possono impedire una ricostruzione attendibile. Prima dell'uso ufficiale
|
||||
confrontare alcuni lotti con etichette e inventario SAM alla medesima data.
|
||||
|
||||
## 11. Perche' alcune versioni non mostravano A/B/C
|
||||
|
||||
Il prototipo Inventario **1.0.0** presente nella cartella di sviluppo bilista
|
||||
non coincideva con la monolista **1.1.0** pubblicata. Il prototipo non aveva
|
||||
la stessa legenda e lo stesso dettaglio A/B/C della versione aggiornata.
|
||||
Non era un cambiamento provocato dai dati o dall'esecuzione del calcolo.
|
||||
|
||||
La revisione **1.1.1** presenta A/B/C/X su righe distinte, lettere in grassetto,
|
||||
contrasto dedicato e testo adattato alla larghezza della finestra. Elimina
|
||||
la ripetizione iniziale del perimetro. I calcoli e la query non cambiano.
|
||||
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.
|
||||
61
INSTALL_PRODUZIONE_20260610.md
Normal file
61
INSTALL_PRODUZIONE_20260610.md
Normal file
@@ -0,0 +1,61 @@
|
||||
# Installazione produzione - Warehouse/FlyWMS bridge
|
||||
|
||||
## Ordine consigliato
|
||||
|
||||
1. Fare backup del database `Mediseawall`.
|
||||
2. Copiare il contenuto dello zip in una cartella locale, ad esempio `C:\flywms`.
|
||||
3. Installare le dipendenze Python:
|
||||
|
||||
```bat
|
||||
python -m pip install -r requirements.txt
|
||||
```
|
||||
|
||||
4. In SSMS, sul database `Mediseawall`, lanciare:
|
||||
|
||||
```text
|
||||
apply_python_parallel_pickinglist_patch.sql
|
||||
apply_online_history_forms_patch.sql
|
||||
```
|
||||
|
||||
## Cosa fanno gli script
|
||||
|
||||
- `apply_python_parallel_pickinglist_patch.sql` crea il ramo SQL Python per gestione picking list, senza modificare le stored procedure C# legacy.
|
||||
- `apply_online_history_forms_patch.sql` crea le viste Python-only per "Storico Picking List".
|
||||
- "Storico movimenti UDC" non richiede script dedicati: legge in sola lettura `MagazziniPallet`, `Celle` e `XMag_GiacenzaPalletPlistChiuse`.
|
||||
|
||||
## Rollback SQL
|
||||
|
||||
Se serve tornare indietro sugli oggetti Python, usare:
|
||||
|
||||
```text
|
||||
rollback_online_history_forms_patch.sql
|
||||
rollback_python_parallel_pickinglist_patch.sql
|
||||
```
|
||||
|
||||
La tabella `dbo.PyPickingListReservation`, se creata, puo' rimanere anche in caso di rollback perche' il C# legacy non la usa.
|
||||
|
||||
## Avvio
|
||||
|
||||
Backoffice con console:
|
||||
|
||||
```bat
|
||||
python main.py
|
||||
```
|
||||
|
||||
Backoffice senza console:
|
||||
|
||||
```bat
|
||||
pythonw warehouse.pyw
|
||||
```
|
||||
|
||||
Barcode senza console:
|
||||
|
||||
```bat
|
||||
pythonw barcode.pyw
|
||||
```
|
||||
|
||||
Se si usa un collegamento Windows, impostare anche la cartella "Da" alla cartella dell'applicazione, ad esempio `C:\flywms`.
|
||||
|
||||
## File esclusi dal pacchetto
|
||||
|
||||
Il pacchetto non include `db_connection.json`, log, cache Python e vecchi zip locali. Alla prima apertura il programma chiedera' la configurazione DB se `db_connection.json` non esiste.
|
||||
154
aggiorna_monolista.bat
Normal file
154
aggiorna_monolista.bat
Normal file
@@ -0,0 +1,154 @@
|
||||
@echo off
|
||||
setlocal EnableExtensions DisableDelayedExpansion
|
||||
rem Run a temporary copy: Git may replace this file during the update.
|
||||
if /I "%~1"=="--worker" goto worker
|
||||
set "INSTALL_DIR=%~1"
|
||||
if not defined INSTALL_DIR set "INSTALL_DIR=C:\flywms"
|
||||
set "PYTHON_EXE=%~2"
|
||||
set "WORKER=%TEMP%\warehouse-update-%RANDOM%-%RANDOM%.bat"
|
||||
copy /Y "%~f0" "%WORKER%" >nul
|
||||
if errorlevel 1 exit /b 1
|
||||
call "%WORKER%" --worker "%INSTALL_DIR%" "%PYTHON_EXE%"
|
||||
exit /b %errorlevel%
|
||||
|
||||
:worker
|
||||
set "INSTALL_DIR=%~2"
|
||||
set "PYTHON_EXE=%~3"
|
||||
set "RESULT=1"
|
||||
echo.
|
||||
echo === Aggiornamento Warehouse MONOLISTA - ramo main ===
|
||||
echo Cartella: "%INSTALL_DIR%"
|
||||
echo Chiudere Warehouse e il barcode, anche nelle altre sessioni del server.
|
||||
echo Non vengono eseguite patch SQL o cancellazioni di file locali.
|
||||
choice /C SN /N /M "Le applicazioni sono chiuse e vuoi continuare? [S/N]: "
|
||||
if errorlevel 2 goto cancelled
|
||||
if errorlevel 1 goto checks
|
||||
goto failed
|
||||
|
||||
:checks
|
||||
where git >nul 2>&1
|
||||
if errorlevel 1 (
|
||||
echo ERRORE: Git non e' installato o non e' nel PATH.
|
||||
goto failed
|
||||
)
|
||||
cd /d "%INSTALL_DIR%"
|
||||
if errorlevel 1 goto failed
|
||||
if not exist ".git" (
|
||||
echo ERRORE: questa cartella non e' la radice di un clone Git.
|
||||
echo Lo script aggiorna installazioni esistenti, non cartelle copiate da ZIP.
|
||||
goto failed
|
||||
)
|
||||
git rev-parse --verify HEAD >nul 2>&1
|
||||
if errorlevel 1 goto failed
|
||||
set "REMOTE_URL="
|
||||
for /f "delims=" %%G in ('git remote get-url origin') do set "REMOTE_URL=%%G"
|
||||
if /I not "%REMOTE_URL%"=="https://gitea.alessandrobonvicini.it/administrator/ware_house.git" (
|
||||
echo ERRORE: origin non corrisponde al repository Warehouse previsto.
|
||||
echo Verificare il clone prima di proseguire. Nessun URL viene modificato.
|
||||
goto failed
|
||||
)
|
||||
git status --porcelain --untracked-files=no >nul
|
||||
if errorlevel 1 goto failed
|
||||
set "DIRTY="
|
||||
for /f "delims=" %%G in ('git status --porcelain --untracked-files^=no') do set "DIRTY=1"
|
||||
if defined DIRTY (
|
||||
echo ERRORE: esistono modifiche locali a file tracciati.
|
||||
git status --short --untracked-files=no
|
||||
echo Nessun reset o stash automatico. Conservare e verificare le modifiche.
|
||||
goto failed
|
||||
)
|
||||
if not defined PYTHON_EXE if exist ".venv\Scripts\python.exe" set "PYTHON_EXE=%CD%\.venv\Scripts\python.exe"
|
||||
if not defined PYTHON_EXE set "PYTHON_EXE=python"
|
||||
"%PYTHON_EXE%" --version
|
||||
if errorlevel 1 (
|
||||
echo ERRORE: Python non disponibile. Indicare il percorso come secondo argomento.
|
||||
goto failed
|
||||
)
|
||||
"%PYTHON_EXE%" -m pip --version
|
||||
if errorlevel 1 goto failed
|
||||
|
||||
echo.
|
||||
echo Scaricamento di main da Gitea...
|
||||
rem Avoid repacking/deleting old pack indexes during deployment on Windows.
|
||||
rem These settings apply only to this command, not to the repository config.
|
||||
git -c maintenance.auto=false -c gc.auto=0 fetch origin refs/heads/main
|
||||
if errorlevel 1 (
|
||||
echo ERRORE: scaricamento fallito. Verificare rete, credenziali e accesso ai file .git.
|
||||
goto failed
|
||||
)
|
||||
set "TARGET="
|
||||
for /f %%G in ('git rev-parse FETCH_HEAD') do set "TARGET=%%G"
|
||||
if not defined TARGET goto failed
|
||||
set "DB_TRACKED="
|
||||
for /f "delims=" %%G in ('git ls-tree --name-only %TARGET% -- db_connection.json') do set "DB_TRACKED=1"
|
||||
if defined DB_TRACKED (
|
||||
echo ERRORE: il ramo remoto contiene db_connection.json. Aggiornamento bloccato per proteggerlo.
|
||||
goto failed
|
||||
)
|
||||
rem Refuse to silently replace a different development branch or local commits.
|
||||
git merge-base --is-ancestor HEAD %TARGET%
|
||||
if errorlevel 1 (
|
||||
echo ERRORE: la versione locale non e' un antenato del main remoto.
|
||||
echo Possibile ramo bilista o commit locali: occorre una verifica manuale.
|
||||
goto failed
|
||||
)
|
||||
git show-ref --verify --quiet refs/heads/main
|
||||
if errorlevel 1 goto backup
|
||||
git merge-base --is-ancestor main %TARGET%
|
||||
if errorlevel 1 (
|
||||
echo ERRORE: anche il main locale contiene commit non presenti sul remoto.
|
||||
goto failed
|
||||
)
|
||||
|
||||
:backup
|
||||
set "STAMP="
|
||||
for /f %%G in ('powershell -NoProfile -Command "Get-Date -Format yyyyMMdd-HHmmss-fff"') do set "STAMP=%%G"
|
||||
if not defined STAMP goto failed
|
||||
set "BACKUP_REF=refs/warehouse-backups/pre-update-%STAMP%"
|
||||
git update-ref "%BACKUP_REF%" HEAD
|
||||
if errorlevel 1 goto failed
|
||||
echo.
|
||||
echo Riferimento di recupero: %BACKUP_REF%
|
||||
echo Per tornare ai sorgenti precedenti, con applicazioni chiuse:
|
||||
echo git switch --detach %BACKUP_REF%
|
||||
echo Il ripristino Git NON ripristina database o dipendenze Python.
|
||||
echo.
|
||||
git show-ref --verify --quiet refs/heads/main
|
||||
if errorlevel 1 (
|
||||
git switch -c main %TARGET%
|
||||
) else (
|
||||
git switch main
|
||||
)
|
||||
if errorlevel 1 goto failed
|
||||
git -c maintenance.auto=false -c gc.auto=0 merge --ff-only %TARGET%
|
||||
if errorlevel 1 goto failed
|
||||
|
||||
echo.
|
||||
echo Installazione dipendenze con "%PYTHON_EXE%"...
|
||||
"%PYTHON_EXE%" -m pip install -r requirements.txt
|
||||
if errorlevel 1 (
|
||||
echo ERRORE: file Git aggiornati, ma installazione dipendenze NON completata.
|
||||
echo Non riavviare l'applicazione finche' il problema pip non e' risolto.
|
||||
goto failed
|
||||
)
|
||||
echo.
|
||||
echo AGGIORNAMENTO COMPLETATO.
|
||||
git log -1 --format="Commit installato: %%h %%s"
|
||||
echo Ora puoi riaprire Warehouse e il barcode dai collegamenti abituali.
|
||||
echo Se il push dal PC di sviluppo non e' riuscito, il remoto puo' essere ancora vecchio.
|
||||
set "RESULT=0"
|
||||
goto finish
|
||||
|
||||
:cancelled
|
||||
echo Aggiornamento annullato.
|
||||
set "RESULT=2"
|
||||
goto finish
|
||||
|
||||
:failed
|
||||
echo.
|
||||
echo AGGIORNAMENTO NON COMPLETATO. Leggere l'errore riportato sopra.
|
||||
|
||||
:finish
|
||||
echo.
|
||||
pause
|
||||
exit /b %RESULT%
|
||||
247
analisi_fix_pickinglist_nazione_destinazione.md
Normal file
247
analisi_fix_pickinglist_nazione_destinazione.md
Normal file
@@ -0,0 +1,247 @@
|
||||
# Picking list con nazione di destinazione mancante
|
||||
|
||||
## Scopo
|
||||
|
||||
Questo documento descrive il difetto che rendeva invisibile una picking list
|
||||
quando il documento SAM utilizzava un indirizzo di destinazione alternativo
|
||||
senza nazione valorizzata. Descrive inoltre la correzione applicata al solo
|
||||
ramo dati Python del WMS, le conseguenze funzionali e le verifiche da eseguire.
|
||||
|
||||
La correzione non modifica tabelle o viste legacy utilizzate dal programma C#
|
||||
e non aggiorna dati anagrafici o documentali in SAM.
|
||||
|
||||
## Caso che ha evidenziato il difetto
|
||||
|
||||
Il problema e' stato rilevato sulla picking list `244/2026`:
|
||||
|
||||
| Dato | Valore |
|
||||
|---|---|
|
||||
| `BAMTES.ID` | `11896` |
|
||||
| `BAMTES.NUMDOC` | `244` |
|
||||
| `BAMTES.ANNDOC` | `2026` |
|
||||
| Data documento | `24/09/2026` |
|
||||
| `BAMTES.STATO` | `P` |
|
||||
| `BAMTES.IDINDDEST` | `274` |
|
||||
| Destinazione | `c/o UNITRANS Magazzino 4 Mirandola` |
|
||||
| `BAMTES.IDNAZDEST` | `NULL` |
|
||||
|
||||
L'indirizzo alternativo `SAMA1.dbo.INDANA.ID = 274` esiste, ma anche il suo
|
||||
campo `IDNAZIONI` e' `NULL`. L'indirizzo abituale della stessa controparte ha
|
||||
invece `IDNAZIONI = 21`, corrispondente all'Italia.
|
||||
|
||||
Il documento non aveva altri problemi:
|
||||
|
||||
- anno corrente valido;
|
||||
- stato `P` valido;
|
||||
- data compresa nell'intervallo operativo;
|
||||
- 4 righe documento;
|
||||
- 494 righe lotto valide;
|
||||
- 26 UDC distinte;
|
||||
- trasportatore esistente.
|
||||
|
||||
## Causa tecnica
|
||||
|
||||
La preparazione delle picking list collegava la testata del documento alla
|
||||
tabella delle nazioni con un collegamento obbligatorio:
|
||||
|
||||
```sql
|
||||
FROM SAMA1.dbo.NAZIONI
|
||||
INNER JOIN SAMA1.dbo.BAMTES
|
||||
ON SAMA1.dbo.NAZIONI.ID = SAMA1.dbo.BAMTES.IDNAZDEST
|
||||
```
|
||||
|
||||
Un `INNER JOIN` conserva soltanto le testate per le quali esiste una nazione
|
||||
compatibile. Quando `BAMTES.IDNAZDEST` e' `NULL`, il confronto non puo' trovare
|
||||
alcuna riga e l'intero documento scompare prima che vengano elaborate righe,
|
||||
lotti e UDC.
|
||||
|
||||
Nel caso 244 la diagnosi ha prodotto:
|
||||
|
||||
```text
|
||||
Righe valide senza join obbligatorio a NAZIONI: 494
|
||||
Righe valide con join obbligatorio a NAZIONI: 0
|
||||
```
|
||||
|
||||
Il filtro della GUI a 10 giorni, la prenotazione e la sequenza di prelievo non
|
||||
erano quindi responsabili del problema.
|
||||
|
||||
## Flusso dati interessato
|
||||
|
||||
La pagina Gestione Picking List usa questa catena:
|
||||
|
||||
```text
|
||||
SAMA1.dbo.BAMTES / FATRIG / LOTTIBF / LOTSER
|
||||
|
|
||||
v
|
||||
dbo.py_XMag_ViewPackingList
|
||||
|
|
||||
v
|
||||
dbo.py_ViewPackingListRestante
|
||||
|
|
||||
v
|
||||
dbo.py_ViewPackingListPrelievo
|
||||
|
|
||||
v
|
||||
Gestione Picking List e barcode Python
|
||||
```
|
||||
|
||||
Lo storico Python utilizza inoltre:
|
||||
|
||||
```text
|
||||
SAMA1
|
||||
-> dbo.py_vPreparaPackingListSAMA1
|
||||
-> dbo.py_vPreparaPackingList
|
||||
-> dbo.py_XMag_ViewPackingListStorico
|
||||
```
|
||||
|
||||
Per evitare comportamenti diversi fra operativita' e storico, la correzione e'
|
||||
stata applicata sia alla preparazione operativa sia alla preparazione storica.
|
||||
|
||||
## Correzione applicata
|
||||
|
||||
Il collegamento e' stato reso opzionale:
|
||||
|
||||
```sql
|
||||
FROM SAMA1.dbo.BAMTES AS bt
|
||||
LEFT OUTER JOIN SAMA1.dbo.NAZIONI AS n
|
||||
ON n.ID = bt.IDNAZDEST
|
||||
```
|
||||
|
||||
Con il `LEFT OUTER JOIN` la testata BAMTES viene conservata anche quando la
|
||||
nazione e' assente. Gli altri collegamenti essenziali verso righe, lotti e
|
||||
seriali restano obbligatori.
|
||||
|
||||
Sono state modificate soltanto queste viste Python:
|
||||
|
||||
- `dbo.py_vPreparaPackingListSAMA1`;
|
||||
- `dbo.py_XMag_ViewPackingList`.
|
||||
|
||||
Le viste dipendenti ricevono automaticamente i dati corretti:
|
||||
|
||||
- `dbo.py_vPreparaPackingList`;
|
||||
- `dbo.py_XMag_ViewPackingListStorico`;
|
||||
- `dbo.py_ViewPackingListRestante`;
|
||||
- `dbo.py_ViewPackingListPrelievo`.
|
||||
|
||||
## Gestione dei valori mancanti
|
||||
|
||||
La patch non assegna automaticamente una nazione. Questo evita di trasformare
|
||||
un'anagrafica incompleta in un dato apparentemente certo.
|
||||
|
||||
Quando la nazione manca:
|
||||
|
||||
- `CodNazione` resta `NULL`;
|
||||
- `NAZIONE` resta `NULL`;
|
||||
- il documento e le sue UDC restano visibili;
|
||||
- il `CASE` applicativo gia' esistente usa il ramo generico `Stato = 4`;
|
||||
- prenotazione, dettaglio UDC e sequenza di prelievo continuano a funzionare.
|
||||
|
||||
La correzione dell'anagrafica SAM rimane comunque consigliata. La robustezza
|
||||
della vista impedisce pero' che un campo descrittivo incompleto blocchi un
|
||||
processo operativo di magazzino.
|
||||
|
||||
## Script di installazione
|
||||
|
||||
La patch autonoma e' contenuta in:
|
||||
|
||||
```text
|
||||
apply_pickinglist_optional_destination_country_patch.sql
|
||||
```
|
||||
|
||||
Lo stesso cambiamento e' stato integrato anche negli script cumulativi:
|
||||
|
||||
- `apply_pickinglist_days_filter_patch.sql`;
|
||||
- `apply_online_python_wms_full_patch.sql`.
|
||||
|
||||
Per aggiornare un database che possiede gia' le viste Python e' sufficiente
|
||||
eseguire una sola volta in SSMS la patch autonoma. Gli script usano
|
||||
`CREATE OR ALTER VIEW`, quindi possono essere rieseguiti senza duplicare dati.
|
||||
|
||||
## Verifica post-patch
|
||||
|
||||
Controllo della vista operativa:
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
Documento,
|
||||
DataDocumento,
|
||||
CodNazione,
|
||||
NAZIONE,
|
||||
Stato,
|
||||
IDStato,
|
||||
COUNT(DISTINCT Pallet) AS NumeroUDC
|
||||
FROM dbo.py_ViewPackingListPrelievo
|
||||
WHERE Documento = 244
|
||||
GROUP BY
|
||||
Documento,
|
||||
DataDocumento,
|
||||
CodNazione,
|
||||
NAZIONE,
|
||||
Stato,
|
||||
IDStato;
|
||||
```
|
||||
|
||||
Risultato ottenuto dopo la correzione:
|
||||
|
||||
```text
|
||||
Documento: 244
|
||||
CodNazione: NULL
|
||||
NAZIONE: NULL
|
||||
Stato: 4
|
||||
IDStato: 0
|
||||
Numero UDC: 26
|
||||
```
|
||||
|
||||
Controllo dei quattro livelli principali:
|
||||
|
||||
```sql
|
||||
SELECT COUNT(DISTINCT UDC) AS UDC
|
||||
FROM dbo.py_vPreparaPackingListSAMA1
|
||||
WHERE NUMDOC = 244 AND StatoDocumento = 'P';
|
||||
|
||||
SELECT COUNT(DISTINCT Pallet) AS UDC
|
||||
FROM dbo.py_XMag_ViewPackingList
|
||||
WHERE Documento = 244;
|
||||
|
||||
SELECT COUNT(DISTINCT Pallet) AS UDC
|
||||
FROM dbo.py_ViewPackingListRestante
|
||||
WHERE Documento = 244;
|
||||
|
||||
SELECT COUNT(DISTINCT Pallet) AS UDC
|
||||
FROM dbo.py_ViewPackingListPrelievo
|
||||
WHERE Documento = 244;
|
||||
```
|
||||
|
||||
Tutte e quattro le query devono restituire `26` per il caso analizzato.
|
||||
|
||||
## Impatto e compatibilita'
|
||||
|
||||
- Nessuna riga SAM viene inserita, aggiornata o cancellata.
|
||||
- Nessuna prenotazione viene modificata.
|
||||
- Nessuna stored procedure di movimentazione viene modificata.
|
||||
- Le picking list con nazione valida mantengono lo stesso risultato.
|
||||
- Le picking list prima invisibili per nazione nulla diventano visibili.
|
||||
- Gli oggetti legacy senza prefisso `py_` non vengono modificati.
|
||||
|
||||
## Ripristino concettuale
|
||||
|
||||
Per ripristinare il comportamento precedente occorrerebbe riportare il
|
||||
collegamento `BAMTES -> NAZIONI` da `LEFT OUTER JOIN` a `INNER JOIN` nelle due
|
||||
viste Python modificate. Tale rollback farebbe nuovamente scomparire tutti i
|
||||
documenti con `IDNAZDEST` nullo e non e' quindi raccomandato come soluzione
|
||||
operativa.
|
||||
|
||||
## Miglioramento futuro consigliato
|
||||
|
||||
Una diagnostica separata potrebbe mostrare le picking list con dati anagrafici
|
||||
incompleti, senza impedirne l'uso:
|
||||
|
||||
```sql
|
||||
SELECT ID, ANNDOC, NUMDOC, IDINDDEST, DESCRDEST
|
||||
FROM SAMA1.dbo.BAMTES
|
||||
WHERE STATO = 'P'
|
||||
AND IDNAZDEST IS NULL;
|
||||
```
|
||||
|
||||
In questo modo il WMS rimane operativo e l'amministratore puo' correggere
|
||||
l'anagrafica SAM in un secondo momento.
|
||||
43
apply_barcode_picking_skip_patch.sql
Normal file
43
apply_barcode_picking_skip_patch.sql
Normal file
@@ -0,0 +1,43 @@
|
||||
SET XACT_ABORT ON;
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
IF OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.py_BarcodePickingListSkip (
|
||||
ID int IDENTITY(1,1) NOT NULL CONSTRAINT PK_py_BarcodePickingListSkip PRIMARY KEY,
|
||||
Documento varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
|
||||
Pallet varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
|
||||
IDStato int NOT NULL,
|
||||
IDOperatore int NOT NULL,
|
||||
DataOra datetime2(0) NOT NULL CONSTRAINT DF_py_BarcodePickingListSkip_DataOra DEFAULT SYSDATETIME(),
|
||||
Motivo nvarchar(200) NULL,
|
||||
Risolto bit NOT NULL CONSTRAINT DF_py_BarcodePickingListSkip_Risolto DEFAULT 0,
|
||||
RisoltoDa int NULL,
|
||||
RisoltoDataOra datetime2(0) NULL
|
||||
);
|
||||
END;
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM sys.indexes
|
||||
WHERE name = N'UX_py_BarcodePickingListSkip_Open'
|
||||
AND object_id = OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U')
|
||||
)
|
||||
BEGIN
|
||||
CREATE UNIQUE INDEX UX_py_BarcodePickingListSkip_Open
|
||||
ON dbo.py_BarcodePickingListSkip (Documento, Pallet, IDStato)
|
||||
WHERE Risolto = 0;
|
||||
END;
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM sys.indexes
|
||||
WHERE name = N'IX_py_BarcodePickingListSkip_Queue'
|
||||
AND object_id = OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U')
|
||||
)
|
||||
BEGIN
|
||||
CREATE INDEX IX_py_BarcodePickingListSkip_Queue
|
||||
ON dbo.py_BarcodePickingListSkip (IDStato, Documento, Pallet, Risolto);
|
||||
END;
|
||||
|
||||
COMMIT TRANSACTION;
|
||||
725
apply_online_python_wms_full_patch.sql
Normal file
725
apply_online_python_wms_full_patch.sql
Normal file
@@ -0,0 +1,725 @@
|
||||
/*
|
||||
Patch cumulativa DB online - ramo Python WMS
|
||||
|
||||
Da eseguire una sola volta in SSMS sul database Mediseawall.
|
||||
|
||||
Questa patch NON modifica gli oggetti legacy usati dal programma C#.
|
||||
|
||||
Include:
|
||||
- dbo.PyPickingListReservation
|
||||
- dbo.py_XMag_ViewPackingList
|
||||
- dbo.py_ViewPackingListRestante
|
||||
- dbo.py_sp_xExePackingListPallet
|
||||
- dbo.py_sp_xExePackingListPalletPrenota
|
||||
- dbo.py_sp_ControllaPrenotazionePackingListPalletNew
|
||||
- dbo.py_vPreparaPackingListSAMA1
|
||||
- dbo.py_vPreparaPackingList
|
||||
- dbo.py_XMag_ViewPackingListStorico
|
||||
- dbo.py_BarcodePickingListSkip
|
||||
- dbo.py_PickingListPrelievoSequenza
|
||||
- dbo.py_ViewPackingListPrelievo
|
||||
|
||||
Include inoltre:
|
||||
- intervallo operativo massimo di 30 giorni, filtrato dalla UI a 10/15/20/30;
|
||||
- destinazione senza nazione ammessa nel ramo Python mediante LEFT JOIN;
|
||||
- ordine predefinito con UDC Non scaff. prima degli scaffali;
|
||||
- ordine personalizzabile per singolo Documento.
|
||||
|
||||
Nota storico:
|
||||
dbo.py_vPreparaPackingListSAMA1 usa ANNDOC >= YEAR(GETDATE())
|
||||
per mantenere visibili solo le picking list dall'inizio dell'anno corrente.
|
||||
*/
|
||||
|
||||
SET ANSI_NULLS ON;
|
||||
GO
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
|
||||
/* ============================================================
|
||||
1. Stato prenotazione picking list ramo Python
|
||||
============================================================ */
|
||||
|
||||
IF OBJECT_ID(N'dbo.PyPickingListReservation', N'U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE [dbo].[PyPickingListReservation](
|
||||
[ID] [tinyint] NOT NULL,
|
||||
[Documento] [varchar](8) NULL,
|
||||
[IDOperatore] [int] NULL,
|
||||
[ModUtente] [varchar](50) NULL,
|
||||
[ModDataOra] [datetime] NULL,
|
||||
CONSTRAINT [PK_PyPickingListReservation] PRIMARY KEY CLUSTERED ([ID] ASC),
|
||||
CONSTRAINT [CK_PyPickingListReservation_Singleton] CHECK ([ID] = 1)
|
||||
) ON [PRIMARY];
|
||||
END
|
||||
GO
|
||||
|
||||
IF NOT EXISTS (SELECT 1 FROM dbo.PyPickingListReservation WHERE ID = 1)
|
||||
BEGIN
|
||||
INSERT INTO dbo.PyPickingListReservation (ID, Documento, IDOperatore, ModUtente, ModDataOra)
|
||||
VALUES (1, NULL, NULL, NULL, GETDATE());
|
||||
END
|
||||
GO
|
||||
|
||||
/* ============================================================
|
||||
2. Viste operative picking list ramo Python
|
||||
============================================================ */
|
||||
|
||||
CREATE OR ALTER VIEW [dbo].[py_XMag_ViewPackingList]
|
||||
AS
|
||||
SELECT TOP 10000
|
||||
legacy.Pallet,
|
||||
legacy.Lotto,
|
||||
legacy.Articolo,
|
||||
legacy.Descrizione,
|
||||
legacy.Qta,
|
||||
legacy.Documento,
|
||||
legacy.CodNazione,
|
||||
legacy.NAZIONE,
|
||||
legacy.Stato,
|
||||
legacy.PalletCella,
|
||||
legacy.Magazzino,
|
||||
legacy.Area,
|
||||
legacy.Cella,
|
||||
legacy.Ordinamento,
|
||||
legacy.Ubicazione,
|
||||
legacy.DEST,
|
||||
CASE
|
||||
WHEN pr.Documento IS NOT NULL
|
||||
AND pr.Documento = CAST(legacy.Documento AS varchar(8))
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END AS IDStato
|
||||
FROM dbo.XMag_ViewPackingList legacy
|
||||
LEFT JOIN dbo.PyPickingListReservation pr
|
||||
ON pr.ID = 1
|
||||
AND NULLIF(LTRIM(RTRIM(pr.Documento)), '') IS NOT NULL
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN pr.Documento IS NOT NULL
|
||||
AND pr.Documento = CAST(legacy.Documento AS varchar(8))
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END DESC,
|
||||
legacy.Documento,
|
||||
legacy.Ordinamento;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER VIEW [dbo].[py_ViewPackingListRestante]
|
||||
AS
|
||||
SELECT
|
||||
Pallet,
|
||||
Lotto,
|
||||
Articolo,
|
||||
Descrizione,
|
||||
Qta,
|
||||
Documento,
|
||||
CodNazione,
|
||||
NAZIONE,
|
||||
Stato,
|
||||
PalletCella,
|
||||
Magazzino,
|
||||
Area,
|
||||
Cella,
|
||||
Ordinamento,
|
||||
Ubicazione,
|
||||
DEST,
|
||||
IDStato
|
||||
FROM dbo.py_XMag_ViewPackingList
|
||||
WHERE Cella <> 9999;
|
||||
GO
|
||||
|
||||
/* ============================================================
|
||||
3. Stored procedure operative ramo Python
|
||||
============================================================ */
|
||||
|
||||
CREATE OR ALTER PROCEDURE [dbo].[py_sp_xExePackingListPallet]
|
||||
@IDOperatore int,
|
||||
@Documento varchar(8),
|
||||
@Azione char(1) = 'P',
|
||||
@RC int OUTPUT
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
SET @RC = 0;
|
||||
|
||||
DECLARE @Nominativo varchar(50) = '';
|
||||
DECLARE @DocumentoAttivo varchar(8) = NULL;
|
||||
DECLARE @Description varchar(255) = '';
|
||||
DECLARE @Message varchar(255) = '';
|
||||
DECLARE @IDResult int = 0;
|
||||
DECLARE @ID int = 0;
|
||||
|
||||
SELECT @Nominativo = [Login]
|
||||
FROM dbo.Operatori
|
||||
WHERE ID = @IDOperatore;
|
||||
|
||||
IF @Nominativo IS NULL
|
||||
SET @Nominativo = 'SYSTEM';
|
||||
|
||||
IF @Azione NOT IN ('P', 'S')
|
||||
BEGIN
|
||||
SET @RC = -10;
|
||||
RETURN;
|
||||
END;
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM dbo.py_XMag_ViewPackingList
|
||||
WHERE CAST(Documento AS varchar(8)) = @Documento
|
||||
)
|
||||
BEGIN
|
||||
SET @RC = -20;
|
||||
RETURN;
|
||||
END;
|
||||
|
||||
IF NOT EXISTS (SELECT 1 FROM dbo.PyPickingListReservation WHERE ID = 1)
|
||||
BEGIN
|
||||
INSERT INTO dbo.PyPickingListReservation (ID, Documento, IDOperatore, ModUtente, ModDataOra)
|
||||
VALUES (1, NULL, NULL, NULL, GETDATE());
|
||||
END;
|
||||
|
||||
SELECT @DocumentoAttivo = NULLIF(LTRIM(RTRIM(Documento)), '')
|
||||
FROM dbo.PyPickingListReservation
|
||||
WHERE ID = 1;
|
||||
|
||||
DECLARE @TargetCelle TABLE (
|
||||
IDCella int PRIMARY KEY
|
||||
);
|
||||
|
||||
INSERT INTO @TargetCelle (IDCella)
|
||||
SELECT DISTINCT Cella
|
||||
FROM dbo.py_XMag_ViewPackingList
|
||||
WHERE CAST(Documento AS varchar(8)) = @Documento
|
||||
AND Cella IS NOT NULL;
|
||||
|
||||
IF @Azione = 'P'
|
||||
BEGIN
|
||||
IF @DocumentoAttivo = @Documento
|
||||
RETURN;
|
||||
|
||||
UPDATE c
|
||||
SET c.IDStato = 0,
|
||||
c.ModUtente = @Nominativo,
|
||||
c.ModDataOra = GETDATE()
|
||||
FROM dbo.Celle c
|
||||
WHERE ISNULL(c.IDStato, 0) <> 0;
|
||||
|
||||
UPDATE c
|
||||
SET c.IDStato = 1,
|
||||
c.ModUtente = @Nominativo,
|
||||
c.ModDataOra = GETDATE()
|
||||
FROM dbo.Celle c
|
||||
INNER JOIN @TargetCelle t ON t.IDCella = c.ID;
|
||||
|
||||
UPDATE dbo.PyPickingListReservation
|
||||
SET Documento = @Documento,
|
||||
IDOperatore = @IDOperatore,
|
||||
ModUtente = @Nominativo,
|
||||
ModDataOra = GETDATE()
|
||||
WHERE ID = 1;
|
||||
|
||||
SELECT TOP 1 @Description = NAZIONE
|
||||
FROM dbo.py_XMag_ViewPackingList
|
||||
WHERE CAST(Documento AS varchar(8)) = @Documento;
|
||||
|
||||
EXEC dbo.sp_LogPackingList
|
||||
@ID = @ID,
|
||||
@Code = @Documento,
|
||||
@Description = @Description,
|
||||
@Message = @Message OUTPUT,
|
||||
@IDResult = @IDResult OUTPUT;
|
||||
|
||||
RETURN;
|
||||
END;
|
||||
|
||||
IF @Azione = 'S'
|
||||
BEGIN
|
||||
IF ISNULL(@DocumentoAttivo, '') <> @Documento
|
||||
RETURN;
|
||||
|
||||
UPDATE c
|
||||
SET c.IDStato = 0,
|
||||
c.ModUtente = @Nominativo,
|
||||
c.ModDataOra = GETDATE()
|
||||
FROM dbo.Celle c
|
||||
INNER JOIN @TargetCelle t ON t.IDCella = c.ID;
|
||||
|
||||
UPDATE dbo.PyPickingListReservation
|
||||
SET Documento = NULL,
|
||||
IDOperatore = @IDOperatore,
|
||||
ModUtente = @Nominativo,
|
||||
ModDataOra = GETDATE()
|
||||
WHERE ID = 1;
|
||||
|
||||
RETURN;
|
||||
END;
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE [dbo].[py_sp_xExePackingListPalletPrenota]
|
||||
@IDOperatore int,
|
||||
@Documento varchar(8),
|
||||
@RC int OUTPUT
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
SET @RC = 0;
|
||||
|
||||
DECLARE @Nominativo varchar(50) = '';
|
||||
|
||||
SELECT @Nominativo = LOGIN
|
||||
FROM dbo.Operatori
|
||||
WHERE ID = @IDOperatore;
|
||||
|
||||
IF @Nominativo IS NULL
|
||||
SET @Nominativo = 'SYSTEM';
|
||||
|
||||
UPDATE c
|
||||
SET c.IDStato = 1,
|
||||
c.ModUtente = @Nominativo,
|
||||
c.ModDataOra = GETDATE()
|
||||
FROM dbo.Celle c
|
||||
WHERE c.ID IN (
|
||||
SELECT DISTINCT Cella
|
||||
FROM dbo.py_ViewPackingListRestante
|
||||
WHERE CAST(Documento AS varchar(8)) = @Documento
|
||||
AND Cella IS NOT NULL
|
||||
);
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE [dbo].[py_sp_ControllaPrenotazionePackingListPalletNew]
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
|
||||
DECLARE @Documento varchar(8) = NULL;
|
||||
DECLARE @IDOperatore int = 0;
|
||||
DECLARE @Nominativo varchar(50) = 'SYSTEM';
|
||||
DECLARE @RC int = 0;
|
||||
|
||||
SELECT
|
||||
@Documento = NULLIF(LTRIM(RTRIM(Documento)), ''),
|
||||
@IDOperatore = ISNULL(IDOperatore, 0),
|
||||
@Nominativo = ISNULL(NULLIF(LTRIM(RTRIM(ModUtente)), ''), 'SYSTEM')
|
||||
FROM dbo.PyPickingListReservation
|
||||
WHERE ID = 1;
|
||||
|
||||
IF ISNULL(@Documento, '') = ''
|
||||
RETURN;
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM dbo.py_ViewPackingListRestante
|
||||
WHERE CAST(Documento AS varchar(8)) = @Documento
|
||||
)
|
||||
BEGIN
|
||||
UPDATE dbo.Celle
|
||||
SET IDStato = 0,
|
||||
ModUtente = @Nominativo,
|
||||
ModDataOra = GETDATE()
|
||||
WHERE ISNULL(IDStato, 0) <> 0;
|
||||
|
||||
UPDATE dbo.PyPickingListReservation
|
||||
SET Documento = NULL,
|
||||
IDOperatore = @IDOperatore,
|
||||
ModUtente = @Nominativo,
|
||||
ModDataOra = GETDATE()
|
||||
WHERE ID = 1;
|
||||
|
||||
RETURN;
|
||||
END;
|
||||
|
||||
UPDATE dbo.Celle
|
||||
SET IDStato = 0,
|
||||
ModUtente = @Nominativo,
|
||||
ModDataOra = GETDATE()
|
||||
WHERE ISNULL(IDStato, 0) <> 0;
|
||||
|
||||
IF @IDOperatore <= 0
|
||||
BEGIN
|
||||
SELECT TOP 1 @IDOperatore = ID
|
||||
FROM dbo.Operatori
|
||||
WHERE LOGIN = @Nominativo;
|
||||
END;
|
||||
|
||||
EXEC dbo.py_sp_xExePackingListPalletPrenota
|
||||
@IDOperatore = @IDOperatore,
|
||||
@Documento = @Documento,
|
||||
@RC = @RC OUTPUT;
|
||||
END;
|
||||
GO
|
||||
|
||||
/* ============================================================
|
||||
4. Viste storico picking list ramo Python
|
||||
============================================================ */
|
||||
|
||||
CREATE OR ALTER VIEW [dbo].[py_vPreparaPackingListSAMA1]
|
||||
AS
|
||||
SELECT
|
||||
SAMA1.dbo.LOTSER.NUMLOT,
|
||||
SAMA1.dbo.ARTICO.CODICE,
|
||||
SAMA1.dbo.FATRIG.DESCR,
|
||||
LEFT(SAMA1.dbo.LOTSER.NUMSER, 6) AS UDC,
|
||||
SUM(SAMA1.dbo.LOTSER.QTTGIAI) AS Qta,
|
||||
SAMA1.dbo.BAMTES.NUMDOC,
|
||||
SAMA1.dbo.BAMTES.DATDOC,
|
||||
SAMA1.dbo.BAMTES.ID,
|
||||
SAMA1.dbo.BAMTES.DESCRDEST,
|
||||
SAMA1.dbo.BAMTES.STATO AS StatoDocumento,
|
||||
SAMA1.dbo.NAZIONI.CODICE AS Expr1,
|
||||
SAMA1.dbo.MTRASP.CODICE + ' ' + SAMA1.dbo.NAZIONI.DESCR AS NAZIONE,
|
||||
SAMA1.dbo.BAMTES.IDMTRASP
|
||||
FROM SAMA1.dbo.BAMTES
|
||||
LEFT OUTER JOIN SAMA1.dbo.NAZIONI
|
||||
ON SAMA1.dbo.NAZIONI.ID = SAMA1.dbo.BAMTES.IDNAZDEST
|
||||
RIGHT OUTER JOIN SAMA1.dbo.LOTTIBF
|
||||
LEFT OUTER JOIN SAMA1.dbo.LOTSER
|
||||
ON SAMA1.dbo.LOTTIBF.IDLOTSER = SAMA1.dbo.LOTSER.ID
|
||||
LEFT OUTER JOIN SAMA1.dbo.ARTICO
|
||||
ON SAMA1.dbo.LOTSER.IDARTICO = SAMA1.dbo.ARTICO.ID
|
||||
LEFT OUTER JOIN SAMA1.dbo.FATRIG
|
||||
ON SAMA1.dbo.LOTTIBF.IDFATRIG = SAMA1.dbo.FATRIG.ID
|
||||
ON SAMA1.dbo.BAMTES.ID = SAMA1.dbo.FATRIG.IDBAM
|
||||
LEFT OUTER JOIN SAMA1.sam.EXTUC
|
||||
ON LEFT(SAMA1.dbo.LOTSER.NUMSER, 6) = SAMA1.sam.EXTUC.CODICE
|
||||
LEFT OUTER JOIN SAMA1.dbo.MTRASP
|
||||
ON SAMA1.dbo.BAMTES.IDMTRASP = SAMA1.dbo.MTRASP.ID
|
||||
WHERE
|
||||
SAMA1.dbo.BAMTES.ANNDOC >= YEAR(GETDATE())
|
||||
AND SAMA1.dbo.BAMTES.STATO IN ('P', 'D')
|
||||
AND SAMA1.dbo.LOTSER.NUMLOT <> '00000000000'
|
||||
GROUP BY
|
||||
SAMA1.dbo.LOTSER.NUMLOT,
|
||||
SAMA1.dbo.ARTICO.CODICE,
|
||||
SAMA1.dbo.FATRIG.DESCR,
|
||||
LEFT(SAMA1.dbo.LOTSER.NUMSER, 6),
|
||||
SAMA1.dbo.BAMTES.NUMDOC,
|
||||
SAMA1.dbo.BAMTES.DATDOC,
|
||||
SAMA1.dbo.BAMTES.ID,
|
||||
SAMA1.dbo.BAMTES.DESCRDEST,
|
||||
SAMA1.dbo.BAMTES.STATO,
|
||||
SAMA1.dbo.NAZIONI.CODICE,
|
||||
SAMA1.dbo.NAZIONI.DESCR,
|
||||
SAMA1.dbo.BAMTES.IDMTRASP,
|
||||
SAMA1.dbo.MTRASP.CODICE;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER VIEW [dbo].[py_vPreparaPackingList]
|
||||
AS
|
||||
SELECT
|
||||
NUMLOT,
|
||||
CODICE,
|
||||
DESCR,
|
||||
UDC,
|
||||
Qta,
|
||||
NUMDOC,
|
||||
DATDOC,
|
||||
ID,
|
||||
DESCRDEST,
|
||||
StatoDocumento,
|
||||
Expr1,
|
||||
NAZIONE
|
||||
FROM dbo.py_vPreparaPackingListSAMA1
|
||||
WHERE NUMLOT <> '';
|
||||
GO
|
||||
|
||||
CREATE OR ALTER VIEW [dbo].[py_XMag_ViewPackingListStorico]
|
||||
AS
|
||||
SELECT TOP (100000)
|
||||
prep.UDC AS Pallet,
|
||||
prep.NUMLOT AS Lotto,
|
||||
prep.CODICE AS Articolo,
|
||||
prep.DESCR AS Descrizione,
|
||||
prep.Qta,
|
||||
prep.NUMDOC AS Documento,
|
||||
prep.DATDOC AS DataDocumento,
|
||||
prep.StatoDocumento,
|
||||
prep.Expr1 AS CodNazione,
|
||||
prep.NAZIONE,
|
||||
CASE
|
||||
WHEN prep.Expr1 = 'DE' THEN 10
|
||||
WHEN prep.Expr1 = 'TH' THEN
|
||||
CASE WHEN SUBSTRING(prep.DESCRDEST, 1, 2) = 'NA' THEN 11 ELSE 13 END
|
||||
WHEN prep.Expr1 = 'MEX' THEN 12
|
||||
ELSE 4
|
||||
END AS Stato,
|
||||
ISNULL(g.NumeroPallet, 0) AS PalletCella,
|
||||
ISNULL(g.IDMagazzino, 1) AS Magazzino,
|
||||
ISNULL(g.IDArea, 5) AS Area,
|
||||
ISNULL(g.IDCella, 1000) AS Cella,
|
||||
ISNULL(c.Ordinamento, 99999) AS Ordinamento,
|
||||
ISNULL(c.Corsia + ' - ' + c.Colonna + ' - ' + c.Fila, 'Non scaff.') AS Ubicazione,
|
||||
SUBSTRING(prep.DESCRDEST, 1, 2) AS DEST,
|
||||
CASE
|
||||
WHEN MAX(CASE
|
||||
WHEN pr.Documento IS NOT NULL
|
||||
AND pr.Documento = CAST(prep.NUMDOC AS varchar(8))
|
||||
THEN 1 ELSE 0 END) = 1
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END AS IDStato
|
||||
FROM dbo.Celle c
|
||||
INNER JOIN dbo.XMag_GiacenzaPallet g
|
||||
ON c.ID = g.IDCella
|
||||
RIGHT OUTER JOIN dbo.py_vPreparaPackingList prep
|
||||
ON g.BarcodePallet COLLATE SQL_Latin1_General_CP1_CI_AS = prep.UDC
|
||||
LEFT JOIN dbo.PyPickingListReservation pr
|
||||
ON pr.ID = 1
|
||||
AND NULLIF(LTRIM(RTRIM(pr.Documento)), '') IS NOT NULL
|
||||
GROUP BY
|
||||
prep.Expr1,
|
||||
prep.NAZIONE,
|
||||
prep.UDC,
|
||||
prep.NUMDOC,
|
||||
prep.DATDOC,
|
||||
prep.StatoDocumento,
|
||||
prep.NUMLOT,
|
||||
prep.CODICE,
|
||||
prep.DESCR,
|
||||
prep.Qta,
|
||||
g.NumeroPallet,
|
||||
g.IDMagazzino,
|
||||
g.IDArea,
|
||||
g.IDCella,
|
||||
c.Ordinamento,
|
||||
c.Corsia,
|
||||
c.Colonna,
|
||||
c.Fila,
|
||||
prep.DESCRDEST;
|
||||
GO
|
||||
|
||||
/* ============================================================
|
||||
5. Tabella salta UDC barcode picking list
|
||||
============================================================ */
|
||||
|
||||
IF OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.py_BarcodePickingListSkip (
|
||||
ID int IDENTITY(1,1) NOT NULL CONSTRAINT PK_py_BarcodePickingListSkip PRIMARY KEY,
|
||||
Documento varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
|
||||
Pallet varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
|
||||
IDStato int NOT NULL,
|
||||
IDOperatore int NOT NULL,
|
||||
DataOra datetime2(0) NOT NULL CONSTRAINT DF_py_BarcodePickingListSkip_DataOra DEFAULT SYSDATETIME(),
|
||||
Motivo nvarchar(200) NULL,
|
||||
Risolto bit NOT NULL CONSTRAINT DF_py_BarcodePickingListSkip_Risolto DEFAULT 0,
|
||||
RisoltoDa int NULL,
|
||||
RisoltoDataOra datetime2(0) NULL
|
||||
);
|
||||
END;
|
||||
GO
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM sys.indexes
|
||||
WHERE name = N'UX_py_BarcodePickingListSkip_Open'
|
||||
AND object_id = OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U')
|
||||
)
|
||||
BEGIN
|
||||
CREATE UNIQUE INDEX UX_py_BarcodePickingListSkip_Open
|
||||
ON dbo.py_BarcodePickingListSkip (Documento, Pallet, IDStato)
|
||||
WHERE Risolto = 0;
|
||||
END;
|
||||
GO
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM sys.indexes
|
||||
WHERE name = N'IX_py_BarcodePickingListSkip_Queue'
|
||||
AND object_id = OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U')
|
||||
)
|
||||
BEGIN
|
||||
CREATE INDEX IX_py_BarcodePickingListSkip_Queue
|
||||
ON dbo.py_BarcodePickingListSkip (IDStato, Documento, Pallet, Risolto);
|
||||
END;
|
||||
GO
|
||||
|
||||
/* ============================================================
|
||||
6. Intervallo operativo 30 giorni e sequenza di prelievo
|
||||
|
||||
La vista di preparazione Python creata al punto 4 contiene sia P sia D.
|
||||
Qui il ramo operativo viene ristretto alle sole liste P degli ultimi 30
|
||||
giorni; la UI applica successivamente il valore scelto (10/15/20/30).
|
||||
============================================================ */
|
||||
|
||||
CREATE OR ALTER VIEW dbo.py_XMag_ViewPackingList
|
||||
AS
|
||||
SELECT TOP (10000)
|
||||
prep.UDC AS Pallet,
|
||||
prep.NUMLOT AS Lotto,
|
||||
prep.CODICE AS Articolo,
|
||||
prep.DESCR AS Descrizione,
|
||||
prep.Qta,
|
||||
prep.NUMDOC AS Documento,
|
||||
prep.DATDOC AS DataDocumento,
|
||||
prep.Expr1 AS CodNazione,
|
||||
prep.NAZIONE,
|
||||
CASE
|
||||
WHEN prep.Expr1 = 'DE' THEN 10
|
||||
WHEN prep.Expr1 = 'TH' THEN
|
||||
CASE WHEN SUBSTRING(prep.DESCRDEST, 1, 2) = 'NA' THEN 11 ELSE 13 END
|
||||
WHEN prep.Expr1 = 'MEX' THEN 12
|
||||
ELSE 4
|
||||
END AS Stato,
|
||||
ISNULL(g.NumeroPallet, 0) AS PalletCella,
|
||||
ISNULL(g.IDMagazzino, 1) AS Magazzino,
|
||||
ISNULL(g.IDArea, 5) AS Area,
|
||||
ISNULL(g.IDCella, 1000) AS Cella,
|
||||
ISNULL(c.Ordinamento, 99999) AS Ordinamento,
|
||||
ISNULL(c.Corsia + ' - ' + c.Colonna + ' - ' + c.Fila, 'Non scaff.') AS Ubicazione,
|
||||
SUBSTRING(prep.DESCRDEST, 1, 2) AS DEST,
|
||||
CASE
|
||||
WHEN MAX(CASE
|
||||
WHEN pr.Documento IS NOT NULL
|
||||
AND pr.Documento = CAST(prep.NUMDOC AS varchar(8))
|
||||
THEN 1 ELSE 0 END) = 1
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END AS IDStato
|
||||
FROM dbo.Celle AS c
|
||||
INNER JOIN dbo.XMag_GiacenzaPallet AS g
|
||||
ON c.ID = g.IDCella
|
||||
RIGHT OUTER JOIN dbo.py_vPreparaPackingList AS prep
|
||||
ON g.BarcodePallet COLLATE SQL_Latin1_General_CP1_CI_AS = prep.UDC
|
||||
LEFT JOIN dbo.PyPickingListReservation AS pr
|
||||
ON pr.ID = 1
|
||||
AND NULLIF(LTRIM(RTRIM(pr.Documento)), '') IS NOT NULL
|
||||
WHERE prep.StatoDocumento = 'P'
|
||||
AND prep.DATDOC > CAST((GETDATE() - 30) AS int)
|
||||
GROUP BY
|
||||
prep.Expr1,
|
||||
prep.NAZIONE,
|
||||
prep.UDC,
|
||||
prep.NUMDOC,
|
||||
prep.DATDOC,
|
||||
prep.NUMLOT,
|
||||
prep.CODICE,
|
||||
prep.DESCR,
|
||||
prep.Qta,
|
||||
g.NumeroPallet,
|
||||
g.IDMagazzino,
|
||||
g.IDArea,
|
||||
g.IDCella,
|
||||
c.Ordinamento,
|
||||
c.Corsia,
|
||||
c.Colonna,
|
||||
c.Fila,
|
||||
prep.DESCRDEST;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER VIEW dbo.py_ViewPackingListRestante
|
||||
AS
|
||||
SELECT
|
||||
Pallet, Lotto, Articolo, Descrizione, Qta, Documento, DataDocumento,
|
||||
CodNazione, NAZIONE, Stato, PalletCella, Magazzino, Area, Cella,
|
||||
Ordinamento, Ubicazione, DEST, IDStato
|
||||
FROM dbo.py_XMag_ViewPackingList
|
||||
WHERE Cella <> 9999;
|
||||
GO
|
||||
|
||||
IF OBJECT_ID(N'dbo.py_PickingListPrelievoSequenza', N'U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.py_PickingListPrelievoSequenza (
|
||||
ID bigint IDENTITY(1,1) NOT NULL
|
||||
CONSTRAINT PK_py_PickingListPrelievoSequenza PRIMARY KEY,
|
||||
Documento varchar(50) NOT NULL,
|
||||
GruppoChiave varchar(160) NOT NULL,
|
||||
GruppoEtichetta varchar(100) NOT NULL,
|
||||
Ordine int NOT NULL,
|
||||
InsUtente varchar(50) NULL,
|
||||
InsDataOra datetime2(0) NOT NULL
|
||||
CONSTRAINT DF_py_PickingListPrelievoSequenza_InsDataOra DEFAULT SYSDATETIME(),
|
||||
ModUtente varchar(50) NULL,
|
||||
ModDataOra datetime2(0) NULL,
|
||||
DelUtente varchar(50) NULL,
|
||||
DelDataOra datetime2(0) NULL,
|
||||
CONSTRAINT CK_py_PickingListPrelievoSequenza_Ordine CHECK (Ordine >= 0)
|
||||
);
|
||||
END;
|
||||
GO
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM sys.indexes
|
||||
WHERE object_id = OBJECT_ID(N'dbo.py_PickingListPrelievoSequenza', N'U')
|
||||
AND name = N'UX_py_PickingListPrelievoSequenza_DocGruppo'
|
||||
)
|
||||
BEGIN
|
||||
CREATE UNIQUE INDEX UX_py_PickingListPrelievoSequenza_DocGruppo
|
||||
ON dbo.py_PickingListPrelievoSequenza (Documento, GruppoChiave)
|
||||
WHERE DelDataOra IS NULL;
|
||||
END;
|
||||
GO
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM sys.indexes
|
||||
WHERE object_id = OBJECT_ID(N'dbo.py_PickingListPrelievoSequenza', N'U')
|
||||
AND name = N'UX_py_PickingListPrelievoSequenza_DocOrdine'
|
||||
)
|
||||
BEGIN
|
||||
CREATE UNIQUE INDEX UX_py_PickingListPrelievoSequenza_DocOrdine
|
||||
ON dbo.py_PickingListPrelievoSequenza (Documento, Ordine)
|
||||
WHERE DelDataOra IS NULL;
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER VIEW dbo.py_ViewPackingListPrelievo
|
||||
AS
|
||||
WITH Gruppi AS (
|
||||
SELECT
|
||||
pl.*,
|
||||
CASE
|
||||
WHEN pl.Cella = 1000 THEN 'NON_SCAFF'
|
||||
ELSE CONCAT(
|
||||
'M:', pl.Magazzino, '|A:', pl.Area, '|C:',
|
||||
LTRIM(RTRIM(CASE
|
||||
WHEN CHARINDEX(' - ', pl.Ubicazione) > 0
|
||||
THEN LEFT(pl.Ubicazione, CHARINDEX(' - ', pl.Ubicazione) - 1)
|
||||
ELSE pl.Ubicazione
|
||||
END))
|
||||
)
|
||||
END AS GruppoPrelievoChiave,
|
||||
CASE
|
||||
WHEN pl.Cella = 1000 THEN 'Non scaff.'
|
||||
ELSE LTRIM(RTRIM(CASE
|
||||
WHEN CHARINDEX(' - ', pl.Ubicazione) > 0
|
||||
THEN LEFT(pl.Ubicazione, CHARINDEX(' - ', pl.Ubicazione) - 1)
|
||||
ELSE pl.Ubicazione
|
||||
END))
|
||||
END AS GruppoPrelievo,
|
||||
CASE
|
||||
WHEN pl.Cella = 1000 THEN 0
|
||||
ELSE 1000 + ISNULL(pl.Ordinamento, 99999)
|
||||
END AS OrdineGruppoDefault
|
||||
FROM dbo.py_ViewPackingListRestante AS pl
|
||||
), Sequenza AS (
|
||||
SELECT
|
||||
g.*,
|
||||
s.Ordine AS OrdineGruppoConfigurato,
|
||||
CASE WHEN EXISTS (
|
||||
SELECT 1
|
||||
FROM dbo.py_PickingListPrelievoSequenza AS any_s
|
||||
WHERE any_s.Documento COLLATE Latin1_General_CI_AS =
|
||||
CAST(g.Documento AS varchar(50)) COLLATE Latin1_General_CI_AS
|
||||
AND any_s.DelDataOra IS NULL
|
||||
) THEN 1 ELSE 0 END AS HaSequenzaPersonalizzata
|
||||
FROM Gruppi AS g
|
||||
LEFT JOIN dbo.py_PickingListPrelievoSequenza AS s
|
||||
ON s.Documento COLLATE Latin1_General_CI_AS =
|
||||
CAST(g.Documento AS varchar(50)) COLLATE Latin1_General_CI_AS
|
||||
AND s.GruppoChiave COLLATE Latin1_General_CI_AS =
|
||||
g.GruppoPrelievoChiave COLLATE Latin1_General_CI_AS
|
||||
AND s.DelDataOra IS NULL
|
||||
)
|
||||
SELECT
|
||||
Sequenza.*,
|
||||
CASE
|
||||
WHEN OrdineGruppoConfigurato IS NOT NULL THEN OrdineGruppoConfigurato
|
||||
WHEN HaSequenzaPersonalizzata = 1 THEN 100000 + OrdineGruppoDefault
|
||||
ELSE OrdineGruppoDefault
|
||||
END AS OrdinePrelievoGruppo
|
||||
FROM Sequenza;
|
||||
GO
|
||||
|
||||
PRINT 'Patch cumulativa Python WMS completata.';
|
||||
GO
|
||||
190
apply_pickinglist_days_filter_patch.sql
Normal file
190
apply_pickinglist_days_filter_patch.sql
Normal file
@@ -0,0 +1,190 @@
|
||||
/*
|
||||
Patch: intervallo giorni selezionabile in Gestione Picking List Python
|
||||
|
||||
Scopo:
|
||||
- permettere alla UI Python di caricare picking list operative degli ultimi
|
||||
10, 15, 20 o 30 giorni;
|
||||
- mantenere 10 giorni come default applicativo;
|
||||
- non escludere documenti validi con nazione di destinazione non valorizzata;
|
||||
- non modificare gli oggetti legacy usati dal programma C#.
|
||||
|
||||
Oggetti modificati:
|
||||
- dbo.py_XMag_ViewPackingList
|
||||
- dbo.py_ViewPackingListRestante
|
||||
|
||||
Nota:
|
||||
La vista legacy dbo.XMag_ViewPackingList dipende da dbo.vPreparaPackingListSAMA1,
|
||||
che contiene il filtro fisso GETDATE()-10. Per questo la vista Python viene
|
||||
ricalcolata direttamente dalle tabelle SAM con un orizzonte massimo di 30 giorni.
|
||||
La UI applica poi il filtro effettivo scelto dall'operatore.
|
||||
Il collegamento a NAZIONI e' intenzionalmente LEFT OUTER JOIN: un indirizzo
|
||||
alternativo incompleto non deve rendere invisibile l'intera picking list.
|
||||
*/
|
||||
|
||||
SET ANSI_NULLS ON;
|
||||
GO
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER VIEW [dbo].[py_XMag_ViewPackingList]
|
||||
AS
|
||||
WITH PreparaPackingList AS (
|
||||
SELECT
|
||||
SAMA1.dbo.LOTSER.NUMLOT,
|
||||
SAMA1.dbo.ARTICO.CODICE,
|
||||
SAMA1.dbo.FATRIG.DESCR,
|
||||
LEFT(SAMA1.dbo.LOTSER.NUMSER, 6) AS UDC,
|
||||
SUM(SAMA1.dbo.LOTSER.QTTGIAI) AS Qta,
|
||||
SAMA1.dbo.BAMTES.NUMDOC,
|
||||
SAMA1.dbo.BAMTES.DATDOC,
|
||||
SAMA1.dbo.BAMTES.ID,
|
||||
SAMA1.dbo.BAMTES.DESCRDEST,
|
||||
SAMA1.dbo.NAZIONI.CODICE AS Expr1,
|
||||
SAMA1.dbo.MTRASP.CODICE + ' ' + SAMA1.dbo.NAZIONI.DESCR AS NAZIONE,
|
||||
SAMA1.dbo.BAMTES.IDMTRASP
|
||||
FROM SAMA1.dbo.BAMTES
|
||||
LEFT OUTER JOIN SAMA1.dbo.NAZIONI
|
||||
ON SAMA1.dbo.NAZIONI.ID = SAMA1.dbo.BAMTES.IDNAZDEST
|
||||
RIGHT OUTER JOIN SAMA1.dbo.LOTTIBF
|
||||
LEFT OUTER JOIN SAMA1.dbo.LOTSER
|
||||
ON SAMA1.dbo.LOTTIBF.IDLOTSER = SAMA1.dbo.LOTSER.ID
|
||||
LEFT OUTER JOIN SAMA1.dbo.ARTICO
|
||||
ON SAMA1.dbo.LOTSER.IDARTICO = SAMA1.dbo.ARTICO.ID
|
||||
LEFT OUTER JOIN SAMA1.dbo.FATRIG
|
||||
ON SAMA1.dbo.LOTTIBF.IDFATRIG = SAMA1.dbo.FATRIG.ID
|
||||
ON SAMA1.dbo.BAMTES.ID = SAMA1.dbo.FATRIG.IDBAM
|
||||
LEFT OUTER JOIN SAMA1.sam.EXTUC
|
||||
ON LEFT(SAMA1.dbo.LOTSER.NUMSER, 6) = SAMA1.sam.EXTUC.CODICE
|
||||
LEFT OUTER JOIN SAMA1.dbo.MTRASP
|
||||
ON SAMA1.dbo.BAMTES.IDMTRASP = SAMA1.dbo.MTRASP.ID
|
||||
WHERE SAMA1.dbo.BAMTES.ANNDOC >= YEAR(GETDATE())
|
||||
AND SAMA1.dbo.BAMTES.STATO = 'P'
|
||||
AND SAMA1.dbo.BAMTES.DATDOC > CAST((GETDATE() - 30) AS int)
|
||||
AND SAMA1.dbo.LOTSER.NUMLOT <> '00000000000'
|
||||
GROUP BY
|
||||
SAMA1.dbo.LOTSER.NUMLOT,
|
||||
SAMA1.dbo.ARTICO.CODICE,
|
||||
SAMA1.dbo.FATRIG.DESCR,
|
||||
LEFT(SAMA1.dbo.LOTSER.NUMSER, 6),
|
||||
SAMA1.dbo.BAMTES.NUMDOC,
|
||||
SAMA1.dbo.BAMTES.DATDOC,
|
||||
SAMA1.dbo.BAMTES.ID,
|
||||
SAMA1.dbo.BAMTES.DESCRDEST,
|
||||
SAMA1.dbo.NAZIONI.CODICE,
|
||||
SAMA1.dbo.NAZIONI.DESCR,
|
||||
SAMA1.dbo.BAMTES.IDMTRASP,
|
||||
SAMA1.dbo.MTRASP.CODICE
|
||||
),
|
||||
Base AS (
|
||||
SELECT
|
||||
prep.UDC AS Pallet,
|
||||
prep.NUMLOT AS Lotto,
|
||||
prep.CODICE AS Articolo,
|
||||
prep.DESCR AS Descrizione,
|
||||
prep.Qta,
|
||||
prep.NUMDOC AS Documento,
|
||||
prep.DATDOC AS DataDocumento,
|
||||
prep.Expr1 AS CodNazione,
|
||||
prep.NAZIONE,
|
||||
CASE
|
||||
WHEN prep.Expr1 = 'DE' THEN 10
|
||||
WHEN prep.Expr1 = 'TH' THEN CASE WHEN SUBSTRING(prep.DESCRDEST, 1, 2) = 'NA' THEN 11 ELSE 13 END
|
||||
WHEN prep.Expr1 = 'MEX' THEN 12
|
||||
ELSE 4
|
||||
END AS Stato,
|
||||
ISNULL(g.NumeroPallet, 0) AS PalletCella,
|
||||
ISNULL(g.IDMagazzino, 1) AS Magazzino,
|
||||
ISNULL(g.IDArea, 5) AS Area,
|
||||
ISNULL(g.IDCella, 1000) AS Cella,
|
||||
ISNULL(c.Ordinamento, 99999) AS Ordinamento,
|
||||
ISNULL(c.Corsia + ' - ' + c.Colonna + ' - ' + c.Fila, 'Non scaff.') AS Ubicazione,
|
||||
SUBSTRING(prep.DESCRDEST, 1, 2) AS DEST
|
||||
FROM dbo.Celle AS c
|
||||
INNER JOIN dbo.XMag_GiacenzaPallet AS g
|
||||
ON c.ID = g.IDCella
|
||||
RIGHT OUTER JOIN PreparaPackingList AS prep
|
||||
ON g.BarcodePallet COLLATE SQL_Latin1_General_CP1_CI_AS = prep.UDC
|
||||
WHERE prep.NUMLOT <> ''
|
||||
GROUP BY
|
||||
prep.Expr1,
|
||||
prep.NAZIONE,
|
||||
prep.UDC,
|
||||
prep.NUMDOC,
|
||||
prep.DATDOC,
|
||||
prep.NUMLOT,
|
||||
prep.CODICE,
|
||||
prep.DESCR,
|
||||
prep.Qta,
|
||||
g.NumeroPallet,
|
||||
g.IDMagazzino,
|
||||
g.IDArea,
|
||||
g.IDCella,
|
||||
c.Ordinamento,
|
||||
c.Corsia,
|
||||
c.Colonna,
|
||||
c.Fila,
|
||||
prep.DESCRDEST
|
||||
)
|
||||
SELECT TOP 10000
|
||||
Base.Pallet,
|
||||
Base.Lotto,
|
||||
Base.Articolo,
|
||||
Base.Descrizione,
|
||||
Base.Qta,
|
||||
Base.Documento,
|
||||
Base.DataDocumento,
|
||||
Base.CodNazione,
|
||||
Base.NAZIONE,
|
||||
Base.Stato,
|
||||
Base.PalletCella,
|
||||
Base.Magazzino,
|
||||
Base.Area,
|
||||
Base.Cella,
|
||||
Base.Ordinamento,
|
||||
Base.Ubicazione,
|
||||
Base.DEST,
|
||||
CASE
|
||||
WHEN pr.Documento IS NOT NULL
|
||||
AND pr.Documento = CAST(Base.Documento AS varchar(8))
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END AS IDStato
|
||||
FROM Base
|
||||
LEFT JOIN dbo.PyPickingListReservation AS pr
|
||||
ON pr.ID = 1
|
||||
AND NULLIF(LTRIM(RTRIM(pr.Documento)), '') IS NOT NULL
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN pr.Documento IS NOT NULL
|
||||
AND pr.Documento = CAST(Base.Documento AS varchar(8))
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END DESC,
|
||||
Base.Documento,
|
||||
Base.Ordinamento;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER VIEW [dbo].[py_ViewPackingListRestante]
|
||||
AS
|
||||
SELECT
|
||||
Pallet,
|
||||
Lotto,
|
||||
Articolo,
|
||||
Descrizione,
|
||||
Qta,
|
||||
Documento,
|
||||
DataDocumento,
|
||||
CodNazione,
|
||||
NAZIONE,
|
||||
Stato,
|
||||
PalletCella,
|
||||
Magazzino,
|
||||
Area,
|
||||
Cella,
|
||||
Ordinamento,
|
||||
Ubicazione,
|
||||
DEST,
|
||||
IDStato
|
||||
FROM dbo.py_XMag_ViewPackingList
|
||||
WHERE Cella <> 9999;
|
||||
GO
|
||||
217
apply_pickinglist_optional_destination_country_patch.sql
Normal file
217
apply_pickinglist_optional_destination_country_patch.sql
Normal file
@@ -0,0 +1,217 @@
|
||||
/*
|
||||
Patch Python WMS: picking list con nazione di destinazione non valorizzata
|
||||
|
||||
Problema risolto:
|
||||
- una testata BAMTES valida puo' avere IDNAZDEST NULL, in particolare quando
|
||||
viene scelto un indirizzo di destinazione alternativo privo di nazione;
|
||||
- l'INNER JOIN a SAMA1.dbo.NAZIONI eliminava l'intero documento;
|
||||
- la picking list non compariva quindi in Gestione Picking List ne' nello
|
||||
storico Python, anche se stato, data, righe, lotti e UDC erano validi.
|
||||
|
||||
Strategia:
|
||||
- il collegamento BAMTES -> NAZIONI diventa LEFT OUTER JOIN;
|
||||
- non viene inventato alcun codice nazione: Expr1 e NAZIONE restano NULL;
|
||||
- il CASE gia' esistente assegna in questo caso lo Stato generico 4;
|
||||
- nessun oggetto legacy usato dal programma C# viene modificato.
|
||||
|
||||
Oggetti Python modificati:
|
||||
- dbo.py_vPreparaPackingListSAMA1 (storico e base condivisa);
|
||||
- dbo.py_XMag_ViewPackingList (gestione operativa).
|
||||
*/
|
||||
|
||||
SET XACT_ABORT ON;
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER VIEW dbo.py_vPreparaPackingListSAMA1
|
||||
AS
|
||||
SELECT
|
||||
ls.NUMLOT,
|
||||
a.CODICE,
|
||||
fr.DESCR,
|
||||
LEFT(ls.NUMSER, 6) AS UDC,
|
||||
SUM(ls.QTTGIAI) AS Qta,
|
||||
bt.NUMDOC,
|
||||
bt.DATDOC,
|
||||
bt.ID,
|
||||
bt.DESCRDEST,
|
||||
bt.STATO AS StatoDocumento,
|
||||
n.CODICE AS Expr1,
|
||||
mt.CODICE + ' ' + n.DESCR AS NAZIONE,
|
||||
bt.IDMTRASP
|
||||
FROM SAMA1.dbo.BAMTES AS bt
|
||||
INNER JOIN SAMA1.dbo.FATRIG AS fr
|
||||
ON fr.IDBAM = bt.ID
|
||||
INNER JOIN SAMA1.dbo.LOTTIBF AS lb
|
||||
ON lb.IDFATRIG = fr.ID
|
||||
INNER JOIN SAMA1.dbo.LOTSER AS ls
|
||||
ON ls.ID = lb.IDLOTSER
|
||||
LEFT OUTER JOIN SAMA1.dbo.ARTICO AS a
|
||||
ON a.ID = ls.IDARTICO
|
||||
LEFT OUTER JOIN SAMA1.sam.EXTUC AS uc
|
||||
ON uc.CODICE = LEFT(ls.NUMSER, 6)
|
||||
LEFT OUTER JOIN SAMA1.dbo.MTRASP AS mt
|
||||
ON mt.ID = bt.IDMTRASP
|
||||
LEFT OUTER JOIN SAMA1.dbo.NAZIONI AS n
|
||||
ON n.ID = bt.IDNAZDEST
|
||||
WHERE bt.ANNDOC >= YEAR(GETDATE())
|
||||
AND bt.STATO IN ('P', 'D')
|
||||
AND ls.NUMLOT <> '00000000000'
|
||||
GROUP BY
|
||||
ls.NUMLOT,
|
||||
a.CODICE,
|
||||
fr.DESCR,
|
||||
LEFT(ls.NUMSER, 6),
|
||||
bt.NUMDOC,
|
||||
bt.DATDOC,
|
||||
bt.ID,
|
||||
bt.DESCRDEST,
|
||||
bt.STATO,
|
||||
n.CODICE,
|
||||
n.DESCR,
|
||||
bt.IDMTRASP,
|
||||
mt.CODICE;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER VIEW dbo.py_XMag_ViewPackingList
|
||||
AS
|
||||
WITH PreparaPackingList AS (
|
||||
SELECT
|
||||
ls.NUMLOT,
|
||||
a.CODICE,
|
||||
fr.DESCR,
|
||||
LEFT(ls.NUMSER, 6) AS UDC,
|
||||
SUM(ls.QTTGIAI) AS Qta,
|
||||
bt.NUMDOC,
|
||||
bt.DATDOC,
|
||||
bt.ID,
|
||||
bt.DESCRDEST,
|
||||
n.CODICE AS Expr1,
|
||||
mt.CODICE + ' ' + n.DESCR AS NAZIONE,
|
||||
bt.IDMTRASP
|
||||
FROM SAMA1.dbo.BAMTES AS bt
|
||||
INNER JOIN SAMA1.dbo.FATRIG AS fr
|
||||
ON fr.IDBAM = bt.ID
|
||||
INNER JOIN SAMA1.dbo.LOTTIBF AS lb
|
||||
ON lb.IDFATRIG = fr.ID
|
||||
INNER JOIN SAMA1.dbo.LOTSER AS ls
|
||||
ON ls.ID = lb.IDLOTSER
|
||||
LEFT OUTER JOIN SAMA1.dbo.ARTICO AS a
|
||||
ON a.ID = ls.IDARTICO
|
||||
LEFT OUTER JOIN SAMA1.sam.EXTUC AS uc
|
||||
ON uc.CODICE = LEFT(ls.NUMSER, 6)
|
||||
LEFT OUTER JOIN SAMA1.dbo.MTRASP AS mt
|
||||
ON mt.ID = bt.IDMTRASP
|
||||
LEFT OUTER JOIN SAMA1.dbo.NAZIONI AS n
|
||||
ON n.ID = bt.IDNAZDEST
|
||||
WHERE bt.ANNDOC >= YEAR(GETDATE())
|
||||
AND bt.STATO = 'P'
|
||||
AND bt.DATDOC > CAST((GETDATE() - 30) AS int)
|
||||
AND ls.NUMLOT <> '00000000000'
|
||||
GROUP BY
|
||||
ls.NUMLOT,
|
||||
a.CODICE,
|
||||
fr.DESCR,
|
||||
LEFT(ls.NUMSER, 6),
|
||||
bt.NUMDOC,
|
||||
bt.DATDOC,
|
||||
bt.ID,
|
||||
bt.DESCRDEST,
|
||||
n.CODICE,
|
||||
n.DESCR,
|
||||
bt.IDMTRASP,
|
||||
mt.CODICE
|
||||
),
|
||||
Base AS (
|
||||
SELECT
|
||||
prep.UDC AS Pallet,
|
||||
prep.NUMLOT AS Lotto,
|
||||
prep.CODICE AS Articolo,
|
||||
prep.DESCR AS Descrizione,
|
||||
prep.Qta,
|
||||
prep.NUMDOC AS Documento,
|
||||
prep.DATDOC AS DataDocumento,
|
||||
prep.Expr1 AS CodNazione,
|
||||
prep.NAZIONE,
|
||||
CASE
|
||||
WHEN prep.Expr1 = 'DE' THEN 10
|
||||
WHEN prep.Expr1 = 'TH' THEN
|
||||
CASE WHEN SUBSTRING(prep.DESCRDEST, 1, 2) = 'NA' THEN 11 ELSE 13 END
|
||||
WHEN prep.Expr1 = 'MEX' THEN 12
|
||||
ELSE 4
|
||||
END AS Stato,
|
||||
ISNULL(g.NumeroPallet, 0) AS PalletCella,
|
||||
ISNULL(g.IDMagazzino, 1) AS Magazzino,
|
||||
ISNULL(g.IDArea, 5) AS Area,
|
||||
ISNULL(g.IDCella, 1000) AS Cella,
|
||||
ISNULL(c.Ordinamento, 99999) AS Ordinamento,
|
||||
ISNULL(c.Corsia + ' - ' + c.Colonna + ' - ' + c.Fila, 'Non scaff.') AS Ubicazione,
|
||||
SUBSTRING(prep.DESCRDEST, 1, 2) AS DEST
|
||||
FROM dbo.Celle AS c
|
||||
INNER JOIN dbo.XMag_GiacenzaPallet AS g
|
||||
ON c.ID = g.IDCella
|
||||
RIGHT OUTER JOIN PreparaPackingList AS prep
|
||||
ON g.BarcodePallet COLLATE SQL_Latin1_General_CP1_CI_AS = prep.UDC
|
||||
WHERE prep.NUMLOT <> ''
|
||||
GROUP BY
|
||||
prep.Expr1,
|
||||
prep.NAZIONE,
|
||||
prep.UDC,
|
||||
prep.NUMDOC,
|
||||
prep.DATDOC,
|
||||
prep.NUMLOT,
|
||||
prep.CODICE,
|
||||
prep.DESCR,
|
||||
prep.Qta,
|
||||
g.NumeroPallet,
|
||||
g.IDMagazzino,
|
||||
g.IDArea,
|
||||
g.IDCella,
|
||||
c.Ordinamento,
|
||||
c.Corsia,
|
||||
c.Colonna,
|
||||
c.Fila,
|
||||
prep.DESCRDEST
|
||||
)
|
||||
SELECT TOP (10000)
|
||||
Base.Pallet,
|
||||
Base.Lotto,
|
||||
Base.Articolo,
|
||||
Base.Descrizione,
|
||||
Base.Qta,
|
||||
Base.Documento,
|
||||
Base.DataDocumento,
|
||||
Base.CodNazione,
|
||||
Base.NAZIONE,
|
||||
Base.Stato,
|
||||
Base.PalletCella,
|
||||
Base.Magazzino,
|
||||
Base.Area,
|
||||
Base.Cella,
|
||||
Base.Ordinamento,
|
||||
Base.Ubicazione,
|
||||
Base.DEST,
|
||||
CASE
|
||||
WHEN pr.Documento IS NOT NULL
|
||||
AND pr.Documento = CAST(Base.Documento AS varchar(8))
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END AS IDStato
|
||||
FROM Base
|
||||
LEFT JOIN dbo.PyPickingListReservation AS pr
|
||||
ON pr.ID = 1
|
||||
AND NULLIF(LTRIM(RTRIM(pr.Documento)), '') IS NOT NULL
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN pr.Documento IS NOT NULL
|
||||
AND pr.Documento = CAST(Base.Documento AS varchar(8))
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END DESC,
|
||||
Base.Documento,
|
||||
Base.Ordinamento;
|
||||
GO
|
||||
|
||||
PRINT 'Patch nazione destinazione opzionale applicata alle viste Python.';
|
||||
GO
|
||||
136
apply_pickinglist_sequence_patch.sql
Normal file
136
apply_pickinglist_sequence_patch.sql
Normal file
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
Patch Python WMS: ordine di prelievo per singola picking list
|
||||
|
||||
Prerequisito:
|
||||
- eseguire prima apply_pickinglist_days_filter_patch.sql, che espone
|
||||
DataDocumento nelle viste operative Python.
|
||||
|
||||
Effetti:
|
||||
- crea una tabella Python-only con la sequenza personalizzata per Documento;
|
||||
- crea una vista Python-only con l'ordine effettivo condiviso da backoffice e barcode;
|
||||
- senza configurazione applica il default: Non scaff. prima degli scaffali;
|
||||
- con configurazione applica i gruppi scelti e accoda in modo sicuro quelli mancanti;
|
||||
- non modifica tabelle, viste o stored procedure legacy usate dal programma C#.
|
||||
*/
|
||||
|
||||
SET ANSI_NULLS ON;
|
||||
GO
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
|
||||
IF OBJECT_ID(N'dbo.py_PickingListPrelievoSequenza', N'U') IS NULL
|
||||
BEGIN
|
||||
CREATE TABLE dbo.py_PickingListPrelievoSequenza (
|
||||
ID bigint IDENTITY(1,1) NOT NULL
|
||||
CONSTRAINT PK_py_PickingListPrelievoSequenza PRIMARY KEY,
|
||||
Documento varchar(50) NOT NULL,
|
||||
GruppoChiave varchar(160) NOT NULL,
|
||||
GruppoEtichetta varchar(100) NOT NULL,
|
||||
Ordine int NOT NULL,
|
||||
InsUtente varchar(50) NULL,
|
||||
InsDataOra datetime2(0) NOT NULL
|
||||
CONSTRAINT DF_py_PickingListPrelievoSequenza_InsDataOra DEFAULT SYSDATETIME(),
|
||||
ModUtente varchar(50) NULL,
|
||||
ModDataOra datetime2(0) NULL,
|
||||
DelUtente varchar(50) NULL,
|
||||
DelDataOra datetime2(0) NULL,
|
||||
CONSTRAINT CK_py_PickingListPrelievoSequenza_Ordine CHECK (Ordine >= 0)
|
||||
);
|
||||
END
|
||||
GO
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM sys.indexes
|
||||
WHERE object_id = OBJECT_ID(N'dbo.py_PickingListPrelievoSequenza', N'U')
|
||||
AND name = N'UX_py_PickingListPrelievoSequenza_DocGruppo'
|
||||
)
|
||||
BEGIN
|
||||
CREATE UNIQUE INDEX UX_py_PickingListPrelievoSequenza_DocGruppo
|
||||
ON dbo.py_PickingListPrelievoSequenza (Documento, GruppoChiave)
|
||||
WHERE DelDataOra IS NULL;
|
||||
END
|
||||
GO
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM sys.indexes
|
||||
WHERE object_id = OBJECT_ID(N'dbo.py_PickingListPrelievoSequenza', N'U')
|
||||
AND name = N'UX_py_PickingListPrelievoSequenza_DocOrdine'
|
||||
)
|
||||
BEGIN
|
||||
CREATE UNIQUE INDEX UX_py_PickingListPrelievoSequenza_DocOrdine
|
||||
ON dbo.py_PickingListPrelievoSequenza (Documento, Ordine)
|
||||
WHERE DelDataOra IS NULL;
|
||||
END
|
||||
GO
|
||||
|
||||
CREATE OR ALTER VIEW dbo.py_ViewPackingListPrelievo
|
||||
AS
|
||||
WITH Gruppi AS (
|
||||
SELECT
|
||||
pl.*,
|
||||
CASE
|
||||
WHEN pl.Cella = 1000 THEN 'NON_SCAFF'
|
||||
ELSE CONCAT(
|
||||
'M:', pl.Magazzino,
|
||||
'|A:', pl.Area,
|
||||
'|C:',
|
||||
LTRIM(RTRIM(
|
||||
CASE
|
||||
WHEN CHARINDEX(' - ', pl.Ubicazione) > 0
|
||||
THEN LEFT(pl.Ubicazione, CHARINDEX(' - ', pl.Ubicazione) - 1)
|
||||
ELSE pl.Ubicazione
|
||||
END
|
||||
))
|
||||
)
|
||||
END AS GruppoPrelievoChiave,
|
||||
CASE
|
||||
WHEN pl.Cella = 1000 THEN 'Non scaff.'
|
||||
ELSE LTRIM(RTRIM(
|
||||
CASE
|
||||
WHEN CHARINDEX(' - ', pl.Ubicazione) > 0
|
||||
THEN LEFT(pl.Ubicazione, CHARINDEX(' - ', pl.Ubicazione) - 1)
|
||||
ELSE pl.Ubicazione
|
||||
END
|
||||
))
|
||||
END AS GruppoPrelievo,
|
||||
CASE
|
||||
WHEN pl.Cella = 1000 THEN 0
|
||||
ELSE 1000 + ISNULL(pl.Ordinamento, 99999)
|
||||
END AS OrdineGruppoDefault
|
||||
FROM dbo.py_ViewPackingListRestante AS pl
|
||||
), Sequenza AS (
|
||||
SELECT
|
||||
g.*,
|
||||
s.Ordine AS OrdineGruppoConfigurato,
|
||||
CASE
|
||||
WHEN EXISTS (
|
||||
SELECT 1
|
||||
FROM dbo.py_PickingListPrelievoSequenza AS any_s
|
||||
WHERE any_s.Documento COLLATE Latin1_General_CI_AS =
|
||||
CAST(g.Documento AS varchar(50)) COLLATE Latin1_General_CI_AS
|
||||
AND any_s.DelDataOra IS NULL
|
||||
) THEN 1
|
||||
ELSE 0
|
||||
END AS HaSequenzaPersonalizzata
|
||||
FROM Gruppi AS g
|
||||
LEFT JOIN dbo.py_PickingListPrelievoSequenza AS s
|
||||
ON s.Documento COLLATE Latin1_General_CI_AS =
|
||||
CAST(g.Documento AS varchar(50)) COLLATE Latin1_General_CI_AS
|
||||
AND s.GruppoChiave COLLATE Latin1_General_CI_AS =
|
||||
g.GruppoPrelievoChiave COLLATE Latin1_General_CI_AS
|
||||
AND s.DelDataOra IS NULL
|
||||
)
|
||||
SELECT
|
||||
Sequenza.*,
|
||||
CASE
|
||||
WHEN OrdineGruppoConfigurato IS NOT NULL THEN OrdineGruppoConfigurato
|
||||
WHEN HaSequenzaPersonalizzata = 1 THEN 100000 + OrdineGruppoDefault
|
||||
ELSE OrdineGruppoDefault
|
||||
END AS OrdinePrelievoGruppo
|
||||
FROM Sequenza;
|
||||
GO
|
||||
|
||||
PRINT 'Patch sequenza prelievo Python applicata.';
|
||||
GO
|
||||
@@ -9,6 +9,10 @@ import asyncio
|
||||
import threading
|
||||
import contextlib
|
||||
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
|
||||
class _LoopHolder:
|
||||
"""Store the global loop instance and its worker thread."""
|
||||
|
||||
@@ -10,14 +10,74 @@ cross-loop errors.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import inspect
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
from sqlalchemy.pool import NullPool
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
QUERY_PROFILER_LOG = Path(__file__).with_name("warehouse_query_profiler.log")
|
||||
QUERY_PROFILER_CONFIG_PATH = Path(__file__).with_name("db_connection.json")
|
||||
|
||||
|
||||
def _load_query_profiler_config() -> dict[str, Any]:
|
||||
"""Read profiler settings from db_connection.json, with env overrides."""
|
||||
|
||||
config: dict[str, Any] = {
|
||||
"enabled": False,
|
||||
"slow_ms": 0,
|
||||
"sql_limit": 4000,
|
||||
}
|
||||
try:
|
||||
data = json.loads(QUERY_PROFILER_CONFIG_PATH.read_text(encoding="utf-8"))
|
||||
section = data.get("query_profiler") if isinstance(data, dict) else None
|
||||
if isinstance(section, dict):
|
||||
config.update(section)
|
||||
except Exception:
|
||||
pass
|
||||
if "WAREHOUSE_QUERY_PROFILER" in os.environ:
|
||||
config["enabled"] = os.environ.get("WAREHOUSE_QUERY_PROFILER", "1").strip().lower() not in {
|
||||
"0",
|
||||
"false",
|
||||
"no",
|
||||
"off",
|
||||
}
|
||||
if "WAREHOUSE_QUERY_PROFILER_SLOW_MS" in os.environ:
|
||||
config["slow_ms"] = os.environ.get("WAREHOUSE_QUERY_PROFILER_SLOW_MS", "0")
|
||||
if "WAREHOUSE_QUERY_PROFILER_SQL_LIMIT" in os.environ:
|
||||
config["sql_limit"] = os.environ.get("WAREHOUSE_QUERY_PROFILER_SQL_LIMIT", "4000")
|
||||
return config
|
||||
|
||||
|
||||
def _query_profiler_enabled() -> bool:
|
||||
value = _load_query_profiler_config().get("enabled", False)
|
||||
if isinstance(value, str):
|
||||
return value.strip().lower() not in {"0", "false", "no", "off"}
|
||||
return bool(value)
|
||||
|
||||
|
||||
def _query_profiler_slow_ms() -> float:
|
||||
try:
|
||||
return float(_load_query_profiler_config().get("slow_ms", 0) or 0)
|
||||
except Exception:
|
||||
return 0.0
|
||||
|
||||
|
||||
def _query_profiler_sql_limit() -> int:
|
||||
try:
|
||||
return int(_load_query_profiler_config().get("sql_limit", 4000) or 4000)
|
||||
except Exception:
|
||||
return 4000
|
||||
|
||||
try:
|
||||
import pyodbc
|
||||
@@ -73,6 +133,83 @@ def make_mssql_dsn(
|
||||
return f"mssql+aioodbc:///?odbc_connect={urllib.parse.quote_plus(odbc)}"
|
||||
|
||||
|
||||
def _compact_sql(sql: str, *, limit: int | None = None) -> str:
|
||||
"""Collapse SQL whitespace so profiler entries stay readable."""
|
||||
|
||||
if limit is None:
|
||||
limit = _query_profiler_sql_limit()
|
||||
text_value = " ".join(str(sql or "").split())
|
||||
if limit > 0 and len(text_value) > limit:
|
||||
return text_value[:limit] + "...<truncated>"
|
||||
return text_value
|
||||
|
||||
|
||||
def _profile_params(params: Optional[Dict[str, Any]]) -> str:
|
||||
"""Serialize SQL parameters for diagnostics."""
|
||||
|
||||
if not params:
|
||||
return "{}"
|
||||
try:
|
||||
return _dumps(params)
|
||||
except Exception:
|
||||
return repr(params)
|
||||
|
||||
|
||||
def _query_caller() -> str:
|
||||
"""Return the first external Python frame that triggered the DB call."""
|
||||
|
||||
current_file = Path(__file__).resolve()
|
||||
for frame in inspect.stack(context=0)[2:]:
|
||||
try:
|
||||
frame_file = Path(frame.filename).resolve()
|
||||
except Exception:
|
||||
continue
|
||||
if frame_file == current_file:
|
||||
continue
|
||||
return f"{frame_file.name}:{frame.lineno}:{frame.function}"
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _append_query_profile(
|
||||
*,
|
||||
method: str,
|
||||
elapsed_ms: float,
|
||||
rows: int | None,
|
||||
rowcount: int | None,
|
||||
commit: bool,
|
||||
ok: bool,
|
||||
sql: str,
|
||||
params: Optional[Dict[str, Any]],
|
||||
caller: str,
|
||||
error: str = "",
|
||||
) -> None:
|
||||
"""Append one query timing line to the local profiler log."""
|
||||
|
||||
if not _query_profiler_enabled():
|
||||
return
|
||||
slow_ms = _query_profiler_slow_ms()
|
||||
if ok and slow_ms > 0 and elapsed_ms < slow_ms:
|
||||
return
|
||||
try:
|
||||
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
row_info = f"rows={rows}" if rows is not None else f"rowcount={rowcount}"
|
||||
lines = [
|
||||
(
|
||||
f"{timestamp} | {elapsed_ms:.3f} ms | {method} | "
|
||||
f"{row_info} | commit={int(commit)} | ok={int(ok)} | caller={caller}"
|
||||
),
|
||||
f"PARAMS: {_profile_params(params)}",
|
||||
f"SQL: {_compact_sql(sql)}",
|
||||
]
|
||||
if error:
|
||||
lines.append(f"ERROR: {error}")
|
||||
with QUERY_PROFILER_LOG.open("a", encoding="utf-8") as handle:
|
||||
handle.write("\n".join(lines) + "\n---\n")
|
||||
except Exception:
|
||||
# Profiling must never interfere with warehouse operations.
|
||||
pass
|
||||
|
||||
|
||||
class AsyncMSSQLClient:
|
||||
"""Thin async query client for SQL Server.
|
||||
|
||||
@@ -149,23 +286,83 @@ class AsyncMSSQLClient:
|
||||
"""
|
||||
await self._ensure_engine()
|
||||
t0 = time.perf_counter()
|
||||
async with (self._engine.begin() if commit else self._engine.connect()) as conn:
|
||||
res = await conn.execute(text(sql), params or {})
|
||||
rows = res.fetchall()
|
||||
cols = list(res.keys())
|
||||
caller = _query_caller()
|
||||
try:
|
||||
async with (self._engine.begin() if commit else self._engine.connect()) as conn:
|
||||
res = await conn.execute(text(sql), params or {})
|
||||
rows = res.fetchall()
|
||||
cols = list(res.keys())
|
||||
except Exception as exc:
|
||||
elapsed_ms = round((time.perf_counter() - t0) * 1000, 3)
|
||||
_append_query_profile(
|
||||
method="query_json",
|
||||
elapsed_ms=elapsed_ms,
|
||||
rows=None,
|
||||
rowcount=None,
|
||||
commit=commit,
|
||||
ok=False,
|
||||
sql=sql,
|
||||
params=params,
|
||||
caller=caller,
|
||||
error=repr(exc),
|
||||
)
|
||||
raise
|
||||
if as_dict_rows:
|
||||
rows_out = [dict(zip(cols, row)) for row in rows]
|
||||
else:
|
||||
rows_out = [list(row) for row in rows]
|
||||
elapsed_ms = round((time.perf_counter() - t0) * 1000, 3)
|
||||
_append_query_profile(
|
||||
method="query_json",
|
||||
elapsed_ms=elapsed_ms,
|
||||
rows=len(rows_out),
|
||||
rowcount=None,
|
||||
commit=commit,
|
||||
ok=True,
|
||||
sql=sql,
|
||||
params=params,
|
||||
caller=caller,
|
||||
)
|
||||
return {
|
||||
"columns": cols,
|
||||
"rows": rows_out,
|
||||
"elapsed_ms": round((time.perf_counter() - t0) * 1000, 3),
|
||||
"elapsed_ms": elapsed_ms,
|
||||
}
|
||||
|
||||
async def exec(self, sql: str, params: Optional[Dict[str, Any]] = None, *, commit: bool = False) -> int:
|
||||
"""Execute a DML statement and return its row count."""
|
||||
await self._ensure_engine()
|
||||
async with (self._engine.begin() if commit else self._engine.connect()) as conn:
|
||||
res = await conn.execute(text(sql), params or {})
|
||||
return res.rowcount or 0
|
||||
t0 = time.perf_counter()
|
||||
caller = _query_caller()
|
||||
try:
|
||||
async with (self._engine.begin() if commit else self._engine.connect()) as conn:
|
||||
res = await conn.execute(text(sql), params or {})
|
||||
rowcount = res.rowcount or 0
|
||||
except Exception as exc:
|
||||
elapsed_ms = round((time.perf_counter() - t0) * 1000, 3)
|
||||
_append_query_profile(
|
||||
method="exec",
|
||||
elapsed_ms=elapsed_ms,
|
||||
rows=None,
|
||||
rowcount=None,
|
||||
commit=commit,
|
||||
ok=False,
|
||||
sql=sql,
|
||||
params=params,
|
||||
caller=caller,
|
||||
error=repr(exc),
|
||||
)
|
||||
raise
|
||||
elapsed_ms = round((time.perf_counter() - t0) * 1000, 3)
|
||||
_append_query_profile(
|
||||
method="exec",
|
||||
elapsed_ms=elapsed_ms,
|
||||
rows=None,
|
||||
rowcount=rowcount,
|
||||
commit=commit,
|
||||
ok=True,
|
||||
sql=sql,
|
||||
params=params,
|
||||
caller=caller,
|
||||
)
|
||||
return rowcount
|
||||
|
||||
@@ -8,7 +8,9 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from user_session import UserSession
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
AUDIT_LOG_PATH = Path(__file__).with_name("warehouse_audit.log")
|
||||
_LOGGER = logging.getLogger("warehouse_audit")
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
|
||||
|
||||
os.chdir(Path(__file__).resolve().parent)
|
||||
|
||||
from runtime_support import ensure_stdio, run_with_fatal_log
|
||||
|
||||
ensure_stdio("warehouse_barcode")
|
||||
|
||||
@@ -6,10 +6,11 @@ import asyncio
|
||||
import sys
|
||||
import tkinter as tk
|
||||
from concurrent.futures import Future
|
||||
from tkinter import messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import ttk
|
||||
from typing import Callable
|
||||
|
||||
from runtime_support import ensure_stdio, run_with_fatal_log
|
||||
from runtime_support import configure_exception_logging, ensure_stdio, log_exception, run_with_fatal_log
|
||||
|
||||
ensure_stdio("warehouse_barcode")
|
||||
|
||||
@@ -19,18 +20,44 @@ from barcode_repository import BarcodeRepository
|
||||
from barcode_service import BarcodeActionResult, BarcodeService, BarcodeViewState
|
||||
from db_config import build_dsn_from_config, ensure_db_config
|
||||
from login_window import prompt_login_compact
|
||||
from user_session import create_user_session
|
||||
from version_info import module_version, versioned_title
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
BYPASS_LOGIN = True
|
||||
BYPASS_LOGIN_USER = {
|
||||
"operator_id": 4,
|
||||
"login": "MAG1",
|
||||
"nominativo": "MAG1",
|
||||
"privilegio": 3,
|
||||
"codice_unita": "U1",
|
||||
}
|
||||
|
||||
|
||||
def _build_bypass_session():
|
||||
"""Create the temporary MAG1 session used while field testing the barcode."""
|
||||
|
||||
return create_user_session(
|
||||
operator_id=int(BYPASS_LOGIN_USER["operator_id"]),
|
||||
login=str(BYPASS_LOGIN_USER["login"]),
|
||||
nominativo=str(BYPASS_LOGIN_USER["nominativo"]),
|
||||
privilegio=int(BYPASS_LOGIN_USER["privilegio"]),
|
||||
codice_unita=str(BYPASS_LOGIN_USER["codice_unita"]),
|
||||
)
|
||||
|
||||
|
||||
class BarcodeClientApp:
|
||||
"""Single-window Tk barcode client modeled after the C# legacy form."""
|
||||
|
||||
PALLET_BARCODE_LENGTH = 6
|
||||
NON_SCAFFALATA_BARCODE = "9001000"
|
||||
SHIPPED_BARCODE = "9000000"
|
||||
BARCODE_MAX_WIDTH = 320
|
||||
BARCODE_MAX_HEIGHT = 400
|
||||
DESKTOP_THRESHOLD_WIDTH = 1024
|
||||
DESKTOP_THRESHOLD_HEIGHT = 768
|
||||
DESKTOP_WINDOW_WIDTH = 465
|
||||
DESKTOP_WINDOW_HEIGHT = 531
|
||||
|
||||
def __init__(self, root: tk.Tk, db_client: AsyncMSSQLClient, session, loop: asyncio.AbstractEventLoop):
|
||||
self.root = root
|
||||
self.db_client = db_client
|
||||
@@ -40,6 +67,12 @@ class BarcodeClientApp:
|
||||
self.service = BarcodeService(self.repository, session.operator_id)
|
||||
self._pending: Future | None = None
|
||||
self._auto_advance_id: str | None = None
|
||||
self._pallet_auto_focus_id: str | None = None
|
||||
self._paused_queue_id: int | None = None
|
||||
self._paused_priority_state: BarcodeViewState | None = None
|
||||
self._pallet_user_input_serial = 0
|
||||
self._priority_loaded_input_serial = 0
|
||||
self._priority_expected_pallet = ""
|
||||
self._status_colors = {
|
||||
"red": "#f4cccc",
|
||||
"green": "#d9ead3",
|
||||
@@ -59,9 +92,11 @@ class BarcodeClientApp:
|
||||
self._apply_state(self.service.state)
|
||||
self._bind_keys()
|
||||
self.root.protocol("WM_DELETE_WINDOW", self._shutdown)
|
||||
self.root.after(80, self._finalize_window_placement)
|
||||
self.root.after(250, self._finalize_window_placement)
|
||||
|
||||
def _build_ui(self) -> None:
|
||||
self.root.title("WMS")
|
||||
self.root.title(versioned_title("WMS", __name__))
|
||||
self.root.configure(bg="#f1f1f1")
|
||||
self._apply_responsive_geometry()
|
||||
|
||||
@@ -169,11 +204,11 @@ class BarcodeClientApp:
|
||||
|
||||
self.btn_f1 = ttk.Button(buttons, text="[F1] H Priority", command=lambda: self._start_queue(1))
|
||||
self.btn_f1.grid(row=0, column=0, padx=(0, 4), pady=(0, button_pad_y), sticky="ew")
|
||||
self.btn_submit = ttk.Button(buttons, text="[Ent] Salva", command=self._submit)
|
||||
self.btn_submit = ttk.Button(buttons, text="[F3] Carica", command=self._on_f3)
|
||||
self.btn_submit.grid(row=0, column=1, padx=(4, 0), pady=(0, button_pad_y), sticky="ew")
|
||||
self.btn_f2 = ttk.Button(buttons, text="[F2] L Priority", command=lambda: self._start_queue(0))
|
||||
self.btn_f2.grid(row=1, column=0, padx=(0, 4), sticky="ew")
|
||||
self.btn_unload = ttk.Button(buttons, text="[F4] Elimina", command=self._begin_manual_unload)
|
||||
self.btn_unload = ttk.Button(buttons, text="[F4] Scarica", command=self._begin_manual_unload)
|
||||
self.btn_unload.grid(row=1, column=1, padx=(4, 0), sticky="ew")
|
||||
|
||||
self.busy_cover = tk.Frame(self.root, bg="#d9d9d9")
|
||||
@@ -207,16 +242,55 @@ class BarcodeClientApp:
|
||||
parent.columnconfigure(1, weight=1)
|
||||
if scanned:
|
||||
self.pallet_entry = entry
|
||||
self.scanned_var.trace_add("write", lambda *_: self._limit_var(self.scanned_var, 8))
|
||||
self.pallet_entry.bind("<KeyPress>", self._on_pallet_keypress, add="+")
|
||||
self.scanned_var.trace_add("write", lambda *_: self._on_scanned_var_changed())
|
||||
else:
|
||||
self.destination_entry = entry
|
||||
self.destination_var.trace_add("write", lambda *_: self._limit_var(self.destination_var, 8))
|
||||
self.destination_var.trace_add("write", lambda *_: self._on_destination_var_changed())
|
||||
|
||||
def _limit_var(self, variable: tk.StringVar, max_len: int) -> None:
|
||||
value = str(variable.get() or "")
|
||||
if len(value) > max_len:
|
||||
variable.set(value[:max_len])
|
||||
|
||||
def _on_pallet_keypress(self, _event=None) -> None:
|
||||
self._pallet_user_input_serial += 1
|
||||
|
||||
def _on_scanned_var_changed(self) -> None:
|
||||
self._limit_var(self.scanned_var, 8)
|
||||
if self._pallet_auto_focus_id is not None:
|
||||
try:
|
||||
self.root.after_cancel(self._pallet_auto_focus_id)
|
||||
except Exception:
|
||||
pass
|
||||
self._pallet_auto_focus_id = None
|
||||
pallet = str(self.scanned_var.get() or "").strip()
|
||||
if len(pallet) < self.PALLET_BARCODE_LENGTH:
|
||||
return
|
||||
self._pallet_auto_focus_id = self.root.after(80, self._auto_focus_destination_after_scan)
|
||||
|
||||
def _on_destination_var_changed(self) -> None:
|
||||
self._limit_var(self.destination_var, 8)
|
||||
self._refresh_action_labels()
|
||||
|
||||
def _auto_focus_destination_after_scan(self) -> None:
|
||||
self._pallet_auto_focus_id = None
|
||||
pallet = str(self.scanned_var.get() or "").strip()
|
||||
if not pallet:
|
||||
return
|
||||
if self._pending is not None and not self._pending.done():
|
||||
return
|
||||
if getattr(self.service.state, "mode", "") == "confirm":
|
||||
return
|
||||
if getattr(self.service.state, "mode", "") in ("priority_high", "priority_low"):
|
||||
expected = str(getattr(self.service.state, "expected_pallet", "") or "").strip()
|
||||
if expected and pallet == expected and self._is_fresh_priority_scan(expected):
|
||||
self._submit()
|
||||
return
|
||||
if bool(getattr(self.service.state, "destination_readonly", False)):
|
||||
return
|
||||
self._focus_destination_input()
|
||||
|
||||
def _apply_responsive_geometry(self) -> None:
|
||||
"""Adapt the window size to barcode-sized or desktop-sized screens."""
|
||||
|
||||
@@ -254,10 +328,24 @@ class BarcodeClientApp:
|
||||
|
||||
self.root.geometry(f"{width}x{height}+{x}+{y}")
|
||||
|
||||
def _finalize_window_placement(self) -> None:
|
||||
"""Let Windows finish frame sizing, then snap the barcode window in place."""
|
||||
|
||||
try:
|
||||
if self._is_barcode_desktop:
|
||||
self.root.state("zoomed")
|
||||
else:
|
||||
self.root.geometry("+0+0")
|
||||
self.root.update_idletasks()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _bind_keys(self) -> None:
|
||||
self.root.bind("<F1>", lambda _e: self._start_queue(1))
|
||||
self.root.bind("<F2>", lambda _e: self._start_queue(0))
|
||||
self.root.bind("<F4>", lambda _e: self._begin_manual_unload())
|
||||
self.root.bind("<F3>", self._on_f3_key)
|
||||
self.root.bind("<F4>", self._on_unload_key)
|
||||
self.root.bind("<Escape>", self._on_escape_key)
|
||||
self.pallet_entry.bind("<Return>", self._on_pallet_enter)
|
||||
self.destination_entry.bind("<Return>", self._on_destination_enter)
|
||||
|
||||
@@ -285,6 +373,9 @@ class BarcodeClientApp:
|
||||
self.busy_bar.stop()
|
||||
self.busy_cover.place_forget()
|
||||
|
||||
def _is_priority_pause(self) -> bool:
|
||||
return str(self.queue_var.get() or "") == "Pausa PL"
|
||||
|
||||
def _apply_state(self, state: BarcodeViewState) -> None:
|
||||
if self._auto_advance_id is not None:
|
||||
try:
|
||||
@@ -292,16 +383,45 @@ class BarcodeClientApp:
|
||||
except Exception:
|
||||
pass
|
||||
self._auto_advance_id = None
|
||||
self.queue_var.set(state.queue_label)
|
||||
if self._pallet_auto_focus_id is not None:
|
||||
try:
|
||||
self.root.after_cancel(self._pallet_auto_focus_id)
|
||||
except Exception:
|
||||
pass
|
||||
self._pallet_auto_focus_id = None
|
||||
pause_context = self._paused_queue_id is not None and state.mode not in ("priority_high", "priority_low")
|
||||
effective_queue_label = "Pausa PL" if pause_context else state.queue_label
|
||||
self.queue_var.set(effective_queue_label)
|
||||
self.destination_var.set(state.destination_barcode)
|
||||
self.scanned_var.set(state.scanned_pallet)
|
||||
self.info1_var.set(state.status_text)
|
||||
self.info1_var.set(self._status_text_with_wait_hint(state))
|
||||
self.info2_var.set(state.document)
|
||||
self.info3_var.set(state.customer)
|
||||
self.info4_var.set(state.expected_pallet)
|
||||
self.status_band.configure(bg=state.status_color or self._status_colors["red"])
|
||||
|
||||
destination_readonly = state.mode in ("priority_high", "priority_low", "manual_unload")
|
||||
if state.mode in ("priority_high", "priority_low"):
|
||||
self._priority_loaded_input_serial = self._pallet_user_input_serial
|
||||
self._priority_expected_pallet = str(state.expected_pallet or "").strip()
|
||||
else:
|
||||
self._priority_expected_pallet = ""
|
||||
|
||||
try:
|
||||
if str(effective_queue_label or "") != "Pausa PL":
|
||||
self._paused_queue_id = None
|
||||
resumable_queue = self._resumable_queue_from_state(state)
|
||||
if state.mode in ("priority_high", "priority_low") or resumable_queue is not None:
|
||||
self.btn_submit.configure(text="[F3] Pausa PL")
|
||||
else:
|
||||
self.btn_submit.configure(text="[F3] Carica")
|
||||
self._refresh_action_labels(state)
|
||||
queue_buttons_state = "disabled" if str(effective_queue_label or "") == "Pausa PL" else "normal"
|
||||
self.btn_f1.configure(state=queue_buttons_state)
|
||||
self.btn_f2.configure(state=queue_buttons_state)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
destination_readonly = False if pause_context else bool(getattr(state, "destination_readonly", False))
|
||||
try:
|
||||
self.destination_entry.configure(state="normal")
|
||||
if destination_readonly:
|
||||
@@ -309,12 +429,34 @@ class BarcodeClientApp:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if state.mode == "confirm" and state.status_text == "Ok Scarico":
|
||||
next_queue = self._queue_id_from_label(state.queue_label)
|
||||
if state.mode == "confirm":
|
||||
next_queue = self._resumable_queue_from_state(state)
|
||||
if next_queue is not None:
|
||||
self._auto_advance_id = self.root.after(1200, lambda q=next_queue: self._start_queue(q))
|
||||
self._auto_advance_id = self.root.after(
|
||||
int(getattr(state, "auto_advance_delay_ms", 0) or 0),
|
||||
lambda q=next_queue: self._start_queue(q),
|
||||
)
|
||||
|
||||
self.root.after(20, self._focus_primary_input)
|
||||
if bool(getattr(state, "focus_destination", False)):
|
||||
self.root.after(20, self._focus_destination_input)
|
||||
else:
|
||||
self.root.after(20, self._focus_primary_input)
|
||||
|
||||
def _refresh_action_labels(self, state: BarcodeViewState | None = None) -> None:
|
||||
current_state = state or self.service.state
|
||||
try:
|
||||
if current_state.mode in ("priority_high", "priority_low"):
|
||||
self.btn_unload.configure(text="[F4] Salta UDC")
|
||||
return
|
||||
destination = str(self.destination_var.get() or "").strip()
|
||||
if destination == self.NON_SCAFFALATA_BARCODE:
|
||||
self.btn_unload.configure(text="[F4] Non scaff.")
|
||||
elif destination:
|
||||
self.btn_unload.configure(text="[F4] Dissocia")
|
||||
else:
|
||||
self.btn_unload.configure(text="[F4] Scarica")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _focus_primary_input(self) -> None:
|
||||
try:
|
||||
@@ -323,6 +465,17 @@ class BarcodeClientApp:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _status_text_with_wait_hint(self, state: BarcodeViewState) -> str:
|
||||
text = str(getattr(state, "status_text", "") or "")
|
||||
delay_ms = int(getattr(state, "auto_advance_delay_ms", 0) or 0)
|
||||
if delay_ms <= 0:
|
||||
return text
|
||||
seconds = max(1, round(delay_ms / 1000))
|
||||
hint = f"Attendi {seconds} secondi..."
|
||||
if hint.lower() in text.lower():
|
||||
return text
|
||||
return f"{text} - {hint}" if text else hint
|
||||
|
||||
def _focus_destination_input(self) -> None:
|
||||
try:
|
||||
self.destination_entry.configure(state="normal")
|
||||
@@ -334,13 +487,32 @@ class BarcodeClientApp:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _is_fresh_priority_scan(self, expected: str) -> bool:
|
||||
mode = str(getattr(self.service.state, "mode", "") or "")
|
||||
if mode not in ("priority_high", "priority_low"):
|
||||
return False
|
||||
if str(expected or "").strip() != self._priority_expected_pallet:
|
||||
return False
|
||||
return self._pallet_user_input_serial > self._priority_loaded_input_serial
|
||||
|
||||
def _on_pallet_enter(self, _event=None) -> str:
|
||||
pallet = str(self.scanned_var.get() or "").strip()
|
||||
destination = str(self.destination_var.get() or "").strip()
|
||||
if not pallet:
|
||||
return "break"
|
||||
if destination == "9000000":
|
||||
self._submit()
|
||||
if destination in (self.NON_SCAFFALATA_BARCODE, self.SHIPPED_BARCODE):
|
||||
if bool(getattr(self.service.state, "destination_readonly", False)):
|
||||
mode = str(getattr(self.service.state, "mode", "") or "")
|
||||
if mode in ("priority_high", "priority_low"):
|
||||
expected = str(getattr(self.service.state, "expected_pallet", "") or "").strip()
|
||||
if expected and pallet == expected and self._is_fresh_priority_scan(expected):
|
||||
self._submit()
|
||||
else:
|
||||
self._focus_primary_input()
|
||||
else:
|
||||
self._submit()
|
||||
else:
|
||||
self._focus_destination_input()
|
||||
return "break"
|
||||
self.destination_var.set("")
|
||||
self._focus_destination_input()
|
||||
@@ -348,20 +520,76 @@ class BarcodeClientApp:
|
||||
|
||||
def _on_destination_enter(self, _event=None) -> str:
|
||||
pallet = str(self.scanned_var.get() or "").strip()
|
||||
destination = str(self.destination_var.get() or "").strip()
|
||||
if pallet and destination:
|
||||
self._submit()
|
||||
else:
|
||||
if not pallet:
|
||||
self._focus_primary_input()
|
||||
else:
|
||||
self.info1_var.set("F3 per associare, F4 per disassociare")
|
||||
self.status_band.configure(bg=self._status_colors["yellow"])
|
||||
self._focus_destination_input()
|
||||
return "break"
|
||||
|
||||
def _on_unload_key(self, _event=None) -> str:
|
||||
self._begin_manual_unload()
|
||||
return "break"
|
||||
|
||||
def _on_escape_key(self, _event=None) -> str:
|
||||
if self._is_priority_pause() and self._paused_queue_id is not None:
|
||||
if self._paused_priority_state is not None:
|
||||
state = self.service.resume_priority_state(self._paused_priority_state)
|
||||
self._paused_priority_state = None
|
||||
self._paused_queue_id = None
|
||||
self._apply_state(state)
|
||||
return "break"
|
||||
self._start_queue(self._paused_queue_id, allow_during_pause=True)
|
||||
return "break"
|
||||
|
||||
def _on_f3_key(self, _event=None) -> str:
|
||||
self._on_f3()
|
||||
return "break"
|
||||
|
||||
def _on_f3(self) -> None:
|
||||
mode = getattr(self.service.state, "mode", "")
|
||||
if mode == "priority_high":
|
||||
self._paused_queue_id = 1
|
||||
self._paused_priority_state = self.service.state
|
||||
self._apply_state(self.service.begin_priority_pause(1))
|
||||
return
|
||||
if mode == "priority_low":
|
||||
self._paused_queue_id = 0
|
||||
self._paused_priority_state = self.service.state
|
||||
self._apply_state(self.service.begin_priority_pause(0))
|
||||
return
|
||||
resumable_queue = self._resumable_queue_from_state(self.service.state)
|
||||
if resumable_queue is not None:
|
||||
self._paused_queue_id = resumable_queue
|
||||
self._paused_priority_state = None
|
||||
self._apply_state(self.service.begin_priority_pause(resumable_queue))
|
||||
return
|
||||
self._submit()
|
||||
|
||||
def _begin_manual_unload(self) -> None:
|
||||
pallet = str(self.scanned_var.get() or "").strip()
|
||||
destination = str(self.destination_var.get() or "").strip()
|
||||
mode = getattr(self.service.state, "mode", "")
|
||||
if mode in ("priority_high", "priority_low"):
|
||||
self._skip_current_picking_pallet()
|
||||
return
|
||||
if pallet:
|
||||
if destination == self.NON_SCAFFALATA_BARCODE:
|
||||
self._submit()
|
||||
else:
|
||||
self._submit_unload_with_source_check()
|
||||
return
|
||||
if self._is_priority_pause():
|
||||
return
|
||||
self._apply_state(self.service.begin_manual_unload())
|
||||
|
||||
def _start_queue(self, id_stato: int) -> None:
|
||||
def _start_queue(self, id_stato: int, *, allow_during_pause: bool = False) -> None:
|
||||
if self._is_priority_pause() and not allow_during_pause:
|
||||
return
|
||||
self._run_async(
|
||||
lambda: self.service.start_priority_queue(id_stato),
|
||||
busy_message="Carico la coda selezionata...",
|
||||
busy_message="In preparazione...",
|
||||
)
|
||||
|
||||
def _submit(self) -> None:
|
||||
@@ -370,7 +598,22 @@ class BarcodeClientApp:
|
||||
scanned_pallet=self.scanned_var.get(),
|
||||
destination_barcode=self.destination_var.get(),
|
||||
),
|
||||
busy_message="Eseguo il movimento...",
|
||||
busy_message="In esecuzione...",
|
||||
)
|
||||
|
||||
def _submit_unload_with_source_check(self) -> None:
|
||||
self._run_async(
|
||||
lambda: self.service.submit_unload_with_source_check(
|
||||
scanned_pallet=self.scanned_var.get(),
|
||||
source_barcode=self.destination_var.get(),
|
||||
),
|
||||
busy_message="In esecuzione...",
|
||||
)
|
||||
|
||||
def _skip_current_picking_pallet(self) -> None:
|
||||
self._run_async(
|
||||
lambda: self.service.skip_current_picking_pallet(),
|
||||
busy_message="Registro salto UDC...",
|
||||
)
|
||||
|
||||
def _run_async(self, coro_factory: Callable[[], object], busy_message: str) -> None:
|
||||
@@ -394,6 +637,12 @@ class BarcodeClientApp:
|
||||
return 0
|
||||
return None
|
||||
|
||||
def _resumable_queue_from_state(self, state: BarcodeViewState) -> int | None:
|
||||
delay_ms = int(getattr(state, "auto_advance_delay_ms", 0) or 0)
|
||||
if delay_ms <= 0:
|
||||
return None
|
||||
return self._queue_id_from_label(str(getattr(state, "queue_label", "") or ""))
|
||||
|
||||
def _poll_future(self) -> None:
|
||||
if self._pending is None:
|
||||
self._set_busy(False)
|
||||
@@ -408,11 +657,16 @@ class BarcodeClientApp:
|
||||
try:
|
||||
result = future.result()
|
||||
except Exception as exc:
|
||||
current = self.service.state
|
||||
current.status_text = f"Errore operativo: {exc}"
|
||||
current.status_color = "#f4cccc"
|
||||
self._apply_state(current)
|
||||
messagebox.showerror("Barcode WMS", f"Operazione fallita:\n{exc}", parent=self.root)
|
||||
log_exception("Barcode WMS", exc, context="barcode async operation")
|
||||
self._set_busy(True, "Verifico esito...")
|
||||
self._pending = asyncio.run_coroutine_threadsafe(
|
||||
self.service.reconcile_after_submit_exception(
|
||||
scanned_pallet=self.scanned_var.get(),
|
||||
destination_barcode=self.destination_var.get(),
|
||||
),
|
||||
self.loop,
|
||||
)
|
||||
self.root.after(40, lambda err=exc: self._poll_recovery_future(err))
|
||||
return
|
||||
|
||||
if isinstance(result, BarcodeActionResult):
|
||||
@@ -422,6 +676,49 @@ class BarcodeClientApp:
|
||||
elif isinstance(result, BarcodeViewState):
|
||||
self._apply_state(result)
|
||||
|
||||
def _show_transaction_error(self, exception: Exception) -> None:
|
||||
messagebox.showerror(
|
||||
"Barcode WMS",
|
||||
"Operazione non completata.\n\n"
|
||||
"Ripeti la lettura o avvisa il responsabile.\n"
|
||||
"Il dettaglio tecnico e' stato scritto nel log.",
|
||||
parent=self.root,
|
||||
exception=exception,
|
||||
)
|
||||
|
||||
def _poll_recovery_future(self, original_exception: Exception) -> None:
|
||||
if self._pending is None:
|
||||
self._set_busy(False)
|
||||
self._show_transaction_error(original_exception)
|
||||
return
|
||||
if not self._pending.done():
|
||||
self.root.after(40, lambda err=original_exception: self._poll_recovery_future(err))
|
||||
return
|
||||
|
||||
future = self._pending
|
||||
self._pending = None
|
||||
self._set_busy(False)
|
||||
try:
|
||||
result = future.result()
|
||||
except Exception as exc:
|
||||
log_exception("Barcode WMS", exc, context=f"barcode recovery after {original_exception!r}")
|
||||
current = self.service.state
|
||||
current.status_text = "Transazione non completata, ripeti l'operazione."
|
||||
current.status_color = "#f4cccc"
|
||||
self._apply_state(current)
|
||||
# Keep both failures when reconciliation also fails asynchronously.
|
||||
self._show_transaction_error(ExceptionGroup(
|
||||
"Barcode operation and recovery failed", [original_exception, exc]))
|
||||
return
|
||||
|
||||
if isinstance(result, BarcodeActionResult):
|
||||
self._apply_state(result.state)
|
||||
if not result.ok:
|
||||
self.root.bell()
|
||||
self._show_transaction_error(original_exception)
|
||||
elif isinstance(result, BarcodeViewState):
|
||||
self._apply_state(result)
|
||||
|
||||
def _shutdown(self) -> None:
|
||||
try:
|
||||
if self._pending is not None and not self._pending.done():
|
||||
@@ -446,6 +743,7 @@ def main() -> int:
|
||||
loop = get_global_loop()
|
||||
bootstrap = tk.Tk()
|
||||
bootstrap.withdraw()
|
||||
configure_exception_logging("Barcode WMS", root=bootstrap, loop=loop)
|
||||
|
||||
config = ensure_db_config(loop, parent=bootstrap)
|
||||
if not config:
|
||||
@@ -454,7 +752,7 @@ def main() -> int:
|
||||
return 1
|
||||
|
||||
db_client = AsyncMSSQLClient(build_dsn_from_config(config))
|
||||
session = prompt_login_compact(bootstrap, db_client)
|
||||
session = _build_bypass_session() if BYPASS_LOGIN else prompt_login_compact(bootstrap, db_client)
|
||||
if session is None:
|
||||
try:
|
||||
fut = asyncio.run_coroutine_threadsafe(db_client.dispose(), loop)
|
||||
|
||||
@@ -7,8 +7,13 @@ possible while keeping SQL isolated from the UI.
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from runtime_support import log_exception, log_runtime_event
|
||||
from typing import Any
|
||||
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
|
||||
SQL_NEXT_PICKING = """
|
||||
SELECT TOP (1)
|
||||
@@ -21,10 +26,21 @@ SELECT TOP (1)
|
||||
Ubicazione,
|
||||
Ordinamento,
|
||||
IDStato
|
||||
FROM dbo.py_XMag_ViewPackingList
|
||||
FROM dbo.py_ViewPackingListPrelievo AS pl
|
||||
WHERE Ordinamento > 0
|
||||
AND IDStato = :id_stato
|
||||
ORDER BY Ordinamento;
|
||||
AND (:documento IS NULL OR pl.Documento = TRY_CONVERT(int, :documento))
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM dbo.py_BarcodePickingListSkip AS s
|
||||
WHERE s.Documento COLLATE Latin1_General_CI_AS =
|
||||
CAST(pl.Documento AS varchar(50)) COLLATE Latin1_General_CI_AS
|
||||
AND s.Pallet COLLATE Latin1_General_CI_AS =
|
||||
CAST(pl.Pallet AS varchar(50)) COLLATE Latin1_General_CI_AS
|
||||
AND s.IDStato = pl.IDStato
|
||||
AND s.Risolto = 0
|
||||
)
|
||||
ORDER BY OrdinePrelievoGruppo, Ordinamento, Pallet, Documento;
|
||||
"""
|
||||
|
||||
SQL_PICKING_BY_PALLET = """
|
||||
@@ -38,9 +54,10 @@ SELECT TOP (1)
|
||||
Ubicazione,
|
||||
Ordinamento,
|
||||
IDStato
|
||||
FROM dbo.py_XMag_ViewPackingList
|
||||
WHERE Pallet = :pallet
|
||||
ORDER BY Ordinamento;
|
||||
FROM dbo.py_ViewPackingListPrelievo
|
||||
WHERE Pallet COLLATE Latin1_General_CI_AS = :pallet COLLATE Latin1_General_CI_AS
|
||||
AND (:documento IS NULL OR Documento = TRY_CONVERT(int, :documento))
|
||||
ORDER BY OrdinePrelievoGruppo, Ordinamento, Pallet;
|
||||
"""
|
||||
|
||||
SQL_TRACE_BY_PALLET = """
|
||||
@@ -50,13 +67,99 @@ SELECT TOP (1)
|
||||
Prodotto,
|
||||
Descrizione
|
||||
FROM dbo.vXTracciaProdotti
|
||||
WHERE Pallet = :pallet
|
||||
WHERE Pallet COLLATE Latin1_General_CI_AS = :pallet COLLATE Latin1_General_CI_AS
|
||||
ORDER BY Lotto;
|
||||
"""
|
||||
|
||||
SQL_CURRENT_LOCATION_BY_PALLET = """
|
||||
SELECT TOP (1)
|
||||
g.BarcodePallet,
|
||||
g.IDCella,
|
||||
RTRIM(c.Corsia) AS Corsia,
|
||||
RTRIM(CAST(c.Colonna AS varchar(32))) AS Colonna,
|
||||
RTRIM(CAST(c.Fila AS varchar(32))) AS Fila
|
||||
FROM dbo.XMag_GiacenzaPallet AS g
|
||||
LEFT JOIN dbo.Celle AS c
|
||||
ON c.ID = g.IDCella
|
||||
WHERE g.BarcodePallet COLLATE Latin1_General_CI_AS = :pallet COLLATE Latin1_General_CI_AS;
|
||||
"""
|
||||
|
||||
SQL_OPEN_LOCATIONS_BY_PALLET = """
|
||||
SELECT
|
||||
g.BarcodePallet,
|
||||
g.IDCella,
|
||||
RTRIM(c.Corsia) AS Corsia,
|
||||
RTRIM(CAST(c.Colonna AS varchar(32))) AS Colonna,
|
||||
RTRIM(CAST(c.Fila AS varchar(32))) AS Fila
|
||||
FROM dbo.XMag_GiacenzaPallet AS g
|
||||
LEFT JOIN dbo.Celle AS c
|
||||
ON c.ID = g.IDCella
|
||||
WHERE g.BarcodePallet COLLATE Latin1_General_CI_AS = :pallet COLLATE Latin1_General_CI_AS
|
||||
ORDER BY g.IDCella;
|
||||
"""
|
||||
|
||||
SQL_OPEN_PALLETS_BY_CELL = """
|
||||
SELECT
|
||||
g.BarcodePallet,
|
||||
g.IDCella
|
||||
FROM dbo.XMag_GiacenzaPallet AS g
|
||||
WHERE g.IDCella = :id_cella
|
||||
ORDER BY g.BarcodePallet;
|
||||
"""
|
||||
|
||||
SQL_CLOSED_PICKING_BY_PALLET = """
|
||||
SELECT TOP (1)
|
||||
g.BarcodePallet,
|
||||
g.NumeroPallet,
|
||||
g.IDMagazzino,
|
||||
g.IDArea,
|
||||
g.IDCella,
|
||||
g.IDStato
|
||||
FROM dbo.XMag_GiacenzaPallet AS g
|
||||
WHERE g.IDCella <> 9999
|
||||
AND g.BarcodePallet COLLATE Latin1_General_CI_AS = :pallet COLLATE Latin1_General_CI_AS
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM SAMA1.dbo.LOTSER AS ls
|
||||
INNER JOIN SAMA1.dbo.LOTTIBF AS lb
|
||||
ON lb.IDLOTSER = ls.ID
|
||||
INNER JOIN SAMA1.dbo.FATRIG AS fr
|
||||
ON lb.IDFATRIG = fr.ID
|
||||
INNER JOIN SAMA1.dbo.BAMTES AS bt
|
||||
ON bt.ID = fr.IDBAM
|
||||
WHERE bt.ANNDOC >= 2011
|
||||
AND bt.STATO = 'D'
|
||||
AND LEFT(ls.NUMSER, 6) COLLATE Latin1_General_CI_AS =
|
||||
:pallet COLLATE Latin1_General_CI_AS
|
||||
)
|
||||
ORDER BY g.IDCella DESC;
|
||||
"""
|
||||
|
||||
SQL_RESOLVE_PHYSICAL_CELL = """
|
||||
DECLARE @raw int = TRY_CONVERT(int, :destination);
|
||||
DECLARE @cell_id int =
|
||||
CASE
|
||||
WHEN @raw IS NULL THEN NULL
|
||||
WHEN @raw >= 9000000 THEN @raw - 9000000
|
||||
ELSE @raw
|
||||
END;
|
||||
|
||||
SELECT TOP (1)
|
||||
c.ID AS IDCella,
|
||||
CAST(9000000 + c.ID AS varchar(8)) AS BarcodeCella,
|
||||
9000000 + c.ID AS NumeroCella,
|
||||
CONCAT(RTRIM(c.Corsia), '.', RTRIM(CAST(c.Colonna AS varchar(32))), '.', RTRIM(CAST(c.Fila AS varchar(32)))) AS Ubicazione
|
||||
FROM dbo.Celle AS c
|
||||
WHERE c.ID = @cell_id
|
||||
AND c.ID <> 9999
|
||||
AND c.DelDataOra IS NULL;
|
||||
"""
|
||||
|
||||
SQL_LEGACY_MOVE = """
|
||||
SET NOCOUNT ON;
|
||||
SET XACT_ABORT ON;
|
||||
DECLARE @RC int = 0;
|
||||
DECLARE @RefreshPickingReservation bit = :refresh_picking_reservation;
|
||||
|
||||
EXEC dbo.sp_xMagGestioneMagazziniPallet
|
||||
@IDOperatore = :id_operatore,
|
||||
@@ -65,7 +168,10 @@ EXEC dbo.sp_xMagGestioneMagazziniPallet
|
||||
@NumeroCella = :numero_cella,
|
||||
@RC = @RC OUTPUT;
|
||||
|
||||
EXEC dbo.py_sp_ControllaPrenotazionePackingListPalletNew;
|
||||
IF @RefreshPickingReservation = 1
|
||||
BEGIN
|
||||
EXEC dbo.py_sp_ControllaPrenotazionePackingListPalletNew;
|
||||
END;
|
||||
|
||||
SELECT
|
||||
@RC AS RC,
|
||||
@@ -74,6 +180,85 @@ SELECT
|
||||
:numero_cella AS NumeroCella;
|
||||
"""
|
||||
|
||||
SQL_SKIP_PICKING_PALLET = """
|
||||
SET NOCOUNT ON;
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM dbo.py_BarcodePickingListSkip
|
||||
WHERE Documento = :documento
|
||||
AND Pallet COLLATE Latin1_General_CI_AS = :pallet COLLATE Latin1_General_CI_AS
|
||||
AND IDStato = :id_stato
|
||||
AND Risolto = 0
|
||||
)
|
||||
BEGIN
|
||||
INSERT INTO dbo.py_BarcodePickingListSkip (
|
||||
Documento,
|
||||
Pallet,
|
||||
IDStato,
|
||||
IDOperatore,
|
||||
DataOra,
|
||||
Motivo,
|
||||
Risolto
|
||||
)
|
||||
VALUES (
|
||||
:documento,
|
||||
:pallet,
|
||||
:id_stato,
|
||||
:id_operatore,
|
||||
SYSDATETIME(),
|
||||
:motivo,
|
||||
0
|
||||
);
|
||||
END;
|
||||
|
||||
SELECT
|
||||
:documento AS Documento,
|
||||
:pallet AS Pallet,
|
||||
:id_stato AS IDStato;
|
||||
"""
|
||||
|
||||
SQL_ACTIVE_SKIPPED_DOCUMENT = """
|
||||
SELECT TOP (1)
|
||||
s.Documento,
|
||||
COUNT(*) AS SkippedCount
|
||||
FROM dbo.py_BarcodePickingListSkip AS s
|
||||
WHERE s.IDStato = :id_stato
|
||||
AND (:documento IS NULL OR s.Documento = :documento)
|
||||
AND s.Risolto = 0
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM dbo.py_ViewPackingListRestante AS pl
|
||||
WHERE CAST(pl.Documento AS varchar(50)) COLLATE Latin1_General_CI_AS =
|
||||
s.Documento COLLATE Latin1_General_CI_AS
|
||||
AND pl.IDStato = :id_stato
|
||||
AND CAST(pl.Pallet AS varchar(50)) COLLATE Latin1_General_CI_AS =
|
||||
s.Pallet COLLATE Latin1_General_CI_AS
|
||||
)
|
||||
GROUP BY s.Documento
|
||||
ORDER BY MIN(s.DataOra);
|
||||
"""
|
||||
|
||||
SQL_PICKING_DOCUMENT_REMAINING = """
|
||||
SELECT COUNT(DISTINCT Pallet) AS RemainingCount
|
||||
FROM dbo.py_XMag_ViewPackingListStorico
|
||||
WHERE Documento = TRY_CONVERT(int, :documento)
|
||||
AND Cella <> 9999;
|
||||
"""
|
||||
|
||||
SQL_RELEASE_PICKING_DOCUMENT = """
|
||||
SET NOCOUNT ON;
|
||||
DECLARE @RC int = 0;
|
||||
|
||||
EXEC dbo.py_sp_xExePackingListPallet
|
||||
@IDOperatore = :id_operatore,
|
||||
@Documento = :documento,
|
||||
@Azione = 'S',
|
||||
@RC = @RC OUTPUT;
|
||||
|
||||
SELECT CAST(@RC AS int) AS RC;
|
||||
"""
|
||||
|
||||
|
||||
def _rows_to_dicts(res: dict[str, Any] | None) -> list[dict[str, Any]]:
|
||||
"""Convert ``query_json`` payloads to a list of row dictionaries."""
|
||||
@@ -101,23 +286,37 @@ class LegacyMoveResult:
|
||||
numero_cella: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class DestinationCell:
|
||||
"""Resolved warehouse cell accepted by the legacy movement procedure."""
|
||||
|
||||
barcode_cella: str
|
||||
numero_cella: int
|
||||
id_cella: int
|
||||
ubicazione: str
|
||||
|
||||
|
||||
class BarcodeRepository:
|
||||
"""Thin async repository used by the lightweight barcode client."""
|
||||
|
||||
def __init__(self, db_client):
|
||||
self.db_client = db_client
|
||||
|
||||
async def fetch_next_picking(self, id_stato: int) -> dict[str, Any] | None:
|
||||
"""Return the next pallet proposed by the legacy F1/F2 queue logic."""
|
||||
async def fetch_next_picking(self, id_stato: int, documento: str | None = None) -> dict[str, Any] | None:
|
||||
"""Select a document initially, then fetch only within that document."""
|
||||
|
||||
res = await self.db_client.query_json(SQL_NEXT_PICKING, {"id_stato": int(id_stato)})
|
||||
res = await self.db_client.query_json(SQL_NEXT_PICKING, {
|
||||
"id_stato": int(id_stato), "documento": documento,
|
||||
})
|
||||
rows = _rows_to_dicts(res)
|
||||
return rows[0] if rows else None
|
||||
|
||||
async def fetch_picking_by_pallet(self, pallet: str) -> dict[str, Any] | None:
|
||||
async def fetch_picking_by_pallet(self, pallet: str, documento: str | None = None) -> dict[str, Any] | None:
|
||||
"""Return one picking row for the given pallet, if still present in the queue."""
|
||||
|
||||
res = await self.db_client.query_json(SQL_PICKING_BY_PALLET, {"pallet": str(pallet or "").strip()})
|
||||
res = await self.db_client.query_json(SQL_PICKING_BY_PALLET, {
|
||||
"pallet": str(pallet or "").strip(), "documento": documento,
|
||||
})
|
||||
rows = _rows_to_dicts(res)
|
||||
return rows[0] if rows else None
|
||||
|
||||
@@ -128,6 +327,123 @@ class BarcodeRepository:
|
||||
rows = _rows_to_dicts(res)
|
||||
return rows[0] if rows else None
|
||||
|
||||
async def fetch_current_location_by_pallet(self, pallet: str) -> dict[str, Any] | None:
|
||||
"""Return the current stock location for a pallet, if it exists in giacenza."""
|
||||
|
||||
res = await self.db_client.query_json(SQL_CURRENT_LOCATION_BY_PALLET, {"pallet": str(pallet or "").strip()})
|
||||
rows = _rows_to_dicts(res)
|
||||
return rows[0] if rows else None
|
||||
|
||||
async def fetch_open_locations_by_pallet(self, pallet: str) -> list[dict[str, Any]]:
|
||||
"""Return all positive stock locations currently open for a pallet."""
|
||||
|
||||
res = await self.db_client.query_json(SQL_OPEN_LOCATIONS_BY_PALLET, {"pallet": str(pallet or "").strip()})
|
||||
return _rows_to_dicts(res)
|
||||
|
||||
async def fetch_open_pallets_by_cell(self, id_cella: int) -> list[dict[str, Any]]:
|
||||
"""Return pallets currently present in a physical cell."""
|
||||
|
||||
res = await self.db_client.query_json(SQL_OPEN_PALLETS_BY_CELL, {"id_cella": int(id_cella)})
|
||||
return _rows_to_dicts(res)
|
||||
|
||||
async def fetch_closed_picking_by_pallet(self, pallet: str) -> dict[str, Any] | None:
|
||||
"""Return a closed picking-list row for a pallet already considered shipped."""
|
||||
|
||||
res = await self.db_client.query_json(SQL_CLOSED_PICKING_BY_PALLET, {"pallet": str(pallet or "").strip()})
|
||||
rows = _rows_to_dicts(res)
|
||||
return rows[0] if rows else None
|
||||
|
||||
async def skip_picking_pallet(
|
||||
self,
|
||||
*,
|
||||
documento: str,
|
||||
pallet: str,
|
||||
id_stato: int,
|
||||
operator_id: int,
|
||||
motivo: str = "UDC non trovata dal magazziniere",
|
||||
) -> None:
|
||||
"""Persist one skipped picking-list pallet so the queue can advance."""
|
||||
|
||||
params = {
|
||||
"documento": str(documento or "").strip(),
|
||||
"pallet": str(pallet or "").strip(),
|
||||
"id_stato": int(id_stato),
|
||||
"id_operatore": int(operator_id),
|
||||
"motivo": str(motivo or "").strip(),
|
||||
}
|
||||
log_runtime_event(
|
||||
"Barcode WMS",
|
||||
(
|
||||
"PICKING SKIP START "
|
||||
f"documento={params['documento']} "
|
||||
f"pallet={params['pallet']} "
|
||||
f"id_stato={params['id_stato']} "
|
||||
f"operator={params['id_operatore']}"
|
||||
),
|
||||
)
|
||||
await self.db_client.query_json(SQL_SKIP_PICKING_PALLET, params, commit=True)
|
||||
log_runtime_event(
|
||||
"Barcode WMS",
|
||||
(
|
||||
"PICKING SKIP OK "
|
||||
f"documento={params['documento']} "
|
||||
f"pallet={params['pallet']} "
|
||||
f"id_stato={params['id_stato']}"
|
||||
),
|
||||
)
|
||||
|
||||
async def fetch_active_skipped_document(self, id_stato: int, documento: str | None = None) -> dict[str, Any] | None:
|
||||
"""Find skipped residuals, restricted to the active document when set."""
|
||||
|
||||
res = await self.db_client.query_json(SQL_ACTIVE_SKIPPED_DOCUMENT, {
|
||||
"id_stato": int(id_stato), "documento": documento,
|
||||
})
|
||||
rows = _rows_to_dicts(res)
|
||||
return rows[0] if rows else None
|
||||
|
||||
async def count_picking_document_remaining(self, documento: str) -> int:
|
||||
"""Check residuals independently of priority before declaring completion."""
|
||||
res = await self.db_client.query_json(SQL_PICKING_DOCUMENT_REMAINING, {"documento": documento})
|
||||
rows = _rows_to_dicts(res)
|
||||
return int(rows[0]["RemainingCount"]) if rows else 0
|
||||
|
||||
async def release_picking_document(self, *, documento: str, operator_id: int) -> int:
|
||||
"""Release a reserved picking-list document without closing its residual rows."""
|
||||
|
||||
params = {
|
||||
"documento": str(documento or "").strip(),
|
||||
"id_operatore": int(operator_id),
|
||||
}
|
||||
log_runtime_event(
|
||||
"Barcode WMS",
|
||||
f"PICKING AUTO RELEASE START documento={params['documento']} operator={params['id_operatore']}",
|
||||
)
|
||||
res = await self.db_client.query_json(SQL_RELEASE_PICKING_DOCUMENT, params, as_dict_rows=True, commit=True)
|
||||
rows = _rows_to_dicts(res)
|
||||
rc = 0
|
||||
if rows:
|
||||
try:
|
||||
rc = int(rows[0].get("RC") or 0)
|
||||
except Exception:
|
||||
rc = 0
|
||||
log_runtime_event("Barcode WMS", f"PICKING AUTO RELEASE END documento={params['documento']} rc={rc}")
|
||||
return rc
|
||||
|
||||
async def resolve_physical_cell(self, destination: str) -> DestinationCell | None:
|
||||
"""Accept either an internal cell ID or the scanned legacy cell barcode."""
|
||||
|
||||
res = await self.db_client.query_json(SQL_RESOLVE_PHYSICAL_CELL, {"destination": str(destination or "").strip()})
|
||||
rows = _rows_to_dicts(res)
|
||||
if not rows:
|
||||
return None
|
||||
row = rows[0]
|
||||
return DestinationCell(
|
||||
barcode_cella=str(row.get("BarcodeCella") or ""),
|
||||
numero_cella=int(row.get("NumeroCella") or 0),
|
||||
id_cella=int(row.get("IDCella") or 0),
|
||||
ubicazione=str(row.get("Ubicazione") or ""),
|
||||
)
|
||||
|
||||
async def execute_legacy_move(
|
||||
self,
|
||||
*,
|
||||
@@ -135,6 +451,7 @@ class BarcodeRepository:
|
||||
barcode_cella: str,
|
||||
barcode_pallet: str,
|
||||
numero_cella: int,
|
||||
refresh_picking_reservation: bool = True,
|
||||
) -> LegacyMoveResult:
|
||||
"""Execute the same stored procedure used by the C# barcode form."""
|
||||
|
||||
@@ -143,13 +460,47 @@ class BarcodeRepository:
|
||||
"barcode_cella": str(barcode_cella or "").strip(),
|
||||
"barcode_pallet": str(barcode_pallet or "").strip(),
|
||||
"numero_cella": int(numero_cella),
|
||||
"refresh_picking_reservation": 1 if refresh_picking_reservation else 0,
|
||||
}
|
||||
res = await self.db_client.query_json(SQL_LEGACY_MOVE, params, commit=True)
|
||||
log_runtime_event(
|
||||
"Barcode WMS",
|
||||
(
|
||||
"MOVE START "
|
||||
f"operator={params['id_operatore']} "
|
||||
f"cell={params['barcode_cella']} "
|
||||
f"pallet={params['barcode_pallet']} "
|
||||
f"refresh_pl={params['refresh_picking_reservation']}"
|
||||
),
|
||||
)
|
||||
try:
|
||||
res = await self.db_client.query_json(SQL_LEGACY_MOVE, params, commit=True)
|
||||
except Exception as exc:
|
||||
log_exception(
|
||||
"Barcode WMS",
|
||||
exc,
|
||||
context=(
|
||||
"execute_legacy_move "
|
||||
f"operator={params['id_operatore']} "
|
||||
f"cell={params['barcode_cella']} "
|
||||
f"pallet={params['barcode_pallet']}"
|
||||
),
|
||||
)
|
||||
raise
|
||||
rows = _rows_to_dicts(res)
|
||||
row = rows[0] if rows else {}
|
||||
return LegacyMoveResult(
|
||||
result = LegacyMoveResult(
|
||||
rc=int(row.get("RC") or 0),
|
||||
barcode_cella=str(row.get("BarcodeCella") or params["barcode_cella"]),
|
||||
barcode_pallet=str(row.get("BarcodePallet") or params["barcode_pallet"]),
|
||||
numero_cella=int(row.get("NumeroCella") or params["numero_cella"]),
|
||||
)
|
||||
log_runtime_event(
|
||||
"Barcode WMS",
|
||||
(
|
||||
"MOVE OK "
|
||||
f"rc={result.rc} "
|
||||
f"cell={result.barcode_cella} "
|
||||
f"pallet={result.barcode_pallet}"
|
||||
),
|
||||
)
|
||||
return result
|
||||
|
||||
@@ -2,11 +2,14 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import Literal
|
||||
|
||||
from barcode_repository import BarcodeRepository, LegacyMoveResult
|
||||
from runtime_support import log_exception, log_runtime_event
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
ModeName = Literal["idle", "priority_high", "priority_low", "manual_load", "manual_unload", "confirm"]
|
||||
|
||||
@@ -25,6 +28,9 @@ class BarcodeViewState:
|
||||
expected_pallet: str = ""
|
||||
destination_barcode: str = ""
|
||||
scanned_pallet: str = ""
|
||||
auto_advance_delay_ms: int = 0
|
||||
destination_readonly: bool = False
|
||||
focus_destination: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -39,19 +45,23 @@ class BarcodeActionResult:
|
||||
class BarcodeService:
|
||||
"""Faithful, but cleaner, port of the legacy barcode form logic."""
|
||||
|
||||
NON_SCAFFALATA_BARCODE = "9001000"
|
||||
SHIPPED_BARCODE = "9000000"
|
||||
GRAY = "#d9d9d9"
|
||||
RED = "#f4cccc"
|
||||
LIGHT_GREEN = "#d9ead3"
|
||||
GREEN_YELLOW = "#e2f0cb"
|
||||
CONVENTIONAL_LOCATION_BY_CELL = {
|
||||
1000: "5E1.1",
|
||||
9999: "7G.1.1",
|
||||
1000: "5E.1.1 - Non scaffalata",
|
||||
9999: "7G.1.1 - Spedita",
|
||||
}
|
||||
|
||||
def __init__(self, repository: BarcodeRepository, operator_id: int):
|
||||
self.repository = repository
|
||||
self.operator_id = int(operator_id)
|
||||
self._current_priority_state = 0
|
||||
self._current_priority_state = -1
|
||||
# Independent document identities survive confirmations, F1/F2 and pause.
|
||||
self._priority_documents: dict[int, str] = {}
|
||||
self._state = BarcodeViewState()
|
||||
|
||||
@property
|
||||
@@ -63,14 +73,15 @@ class BarcodeService:
|
||||
def reset(self) -> BarcodeViewState:
|
||||
"""Return the client to its neutral state."""
|
||||
|
||||
self._current_priority_state = 0
|
||||
self._current_priority_state = -1
|
||||
self._priority_documents.clear()
|
||||
self._state = BarcodeViewState()
|
||||
return self._state
|
||||
|
||||
def begin_manual_load(self) -> BarcodeViewState:
|
||||
"""Prepare a real versamento into a physical warehouse cell."""
|
||||
|
||||
self._current_priority_state = 0
|
||||
self._current_priority_state = -1
|
||||
self._state = BarcodeViewState(
|
||||
mode="manual_load",
|
||||
queue_label="Versamento",
|
||||
@@ -80,34 +91,141 @@ class BarcodeService:
|
||||
return self._state
|
||||
|
||||
def begin_manual_unload(self) -> BarcodeViewState:
|
||||
"""Prepare a direct unload toward the virtual outbound cell 9000000."""
|
||||
"""Prepare a direct unload toward the conventional non-shelved cell."""
|
||||
|
||||
self._current_priority_state = 0
|
||||
self._current_priority_state = -1
|
||||
self._state = BarcodeViewState(
|
||||
mode="manual_unload",
|
||||
queue_label="Prelievo diretto",
|
||||
status_text="OP Scarico",
|
||||
status_color=self.GRAY,
|
||||
destination_barcode="9000000",
|
||||
destination_barcode=self.NON_SCAFFALATA_BARCODE,
|
||||
destination_readonly=True,
|
||||
)
|
||||
return self._state
|
||||
|
||||
async def start_priority_queue(self, id_stato: int) -> BarcodeActionResult:
|
||||
"""Load the next item of the selected legacy priority queue."""
|
||||
def begin_priority_pause(self, id_stato: int) -> BarcodeViewState:
|
||||
"""Pause the active picking queue locally for exactly one free movement."""
|
||||
|
||||
row = await self.repository.fetch_next_picking(id_stato)
|
||||
self._current_priority_state = int(id_stato)
|
||||
self._state = BarcodeViewState(
|
||||
mode="manual_unload",
|
||||
queue_label="Pausa PL",
|
||||
status_text="Premi ESC per uscire dalla pausa",
|
||||
status_color=self.GRAY,
|
||||
destination_barcode=self.NON_SCAFFALATA_BARCODE,
|
||||
destination_readonly=False,
|
||||
)
|
||||
return self._state
|
||||
|
||||
def resume_priority_state(self, state: BarcodeViewState) -> BarcodeViewState:
|
||||
"""Restore the exact picking pallet that was visible before a local pause."""
|
||||
|
||||
if state.mode not in ("priority_high", "priority_low"):
|
||||
return self._state
|
||||
self._current_priority_state = 1 if state.mode == "priority_high" else 0
|
||||
self._priority_documents[self._current_priority_state] = state.document
|
||||
self._state = replace(state, scanned_pallet="", auto_advance_delay_ms=0)
|
||||
return self._state
|
||||
|
||||
async def skip_current_picking_pallet(self) -> BarcodeActionResult:
|
||||
"""Mark the currently proposed picking pallet as skipped and advance."""
|
||||
|
||||
mode = str(self._state.mode or "")
|
||||
if mode not in ("priority_high", "priority_low"):
|
||||
return BarcodeActionResult(False, self._state, "Nessuna picking list attiva.")
|
||||
|
||||
id_stato = 1 if mode == "priority_high" else 0
|
||||
documento = str(self._state.document or "").strip()
|
||||
pallet = str(self._state.expected_pallet or "").strip()
|
||||
if not documento or not pallet:
|
||||
self._state.status_text = "Nessuna UDC da saltare."
|
||||
self._state.status_color = self.RED
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
|
||||
await self.repository.skip_picking_pallet(
|
||||
documento=documento,
|
||||
pallet=pallet,
|
||||
id_stato=id_stato,
|
||||
operator_id=self.operator_id,
|
||||
)
|
||||
queue_label = "Alta priorita' (F1)" if id_stato == 1 else "Bassa priorita' (F2)"
|
||||
self._current_priority_state = id_stato
|
||||
self._state = BarcodeViewState(
|
||||
mode="confirm",
|
||||
queue_label=queue_label,
|
||||
status_text="UDC saltata - chiusura manuale richiesta",
|
||||
status_color=self.RED,
|
||||
source_location=self._state.source_location,
|
||||
document=documento,
|
||||
customer="UDC non trovata",
|
||||
expected_pallet=pallet,
|
||||
destination_barcode=self.SHIPPED_BARCODE,
|
||||
auto_advance_delay_ms=1500,
|
||||
destination_readonly=True,
|
||||
)
|
||||
return BarcodeActionResult(True, self._state, self._state.status_text)
|
||||
|
||||
async def start_priority_queue(self, id_stato: int) -> BarcodeActionResult:
|
||||
"""Keep each F1/F2 cycle bound to its document until the cycle stops."""
|
||||
|
||||
id_stato = int(id_stato)
|
||||
active_document = self._priority_documents.get(id_stato)
|
||||
row = await self.repository.fetch_next_picking(id_stato, documento=active_document)
|
||||
self._current_priority_state = id_stato
|
||||
queue_label = "Alta priorita' (F1)" if int(id_stato) == 1 else "Bassa priorita' (F2)"
|
||||
if not row:
|
||||
skipped_doc = await self.repository.fetch_active_skipped_document(id_stato, documento=active_document)
|
||||
if skipped_doc:
|
||||
documento = str(skipped_doc.get("Documento") or "").strip()
|
||||
skipped_count = int(skipped_doc.get("SkippedCount") or 0)
|
||||
rc = await self.repository.release_picking_document(
|
||||
documento=documento,
|
||||
operator_id=self.operator_id,
|
||||
)
|
||||
if rc != 0:
|
||||
raise RuntimeError(f"Impossibile sospendere PL {documento}: RC={rc}")
|
||||
self._priority_documents.pop(id_stato, None)
|
||||
self._current_priority_state = -1
|
||||
self._state = BarcodeViewState(
|
||||
mode="manual_unload",
|
||||
queue_label=queue_label,
|
||||
status_text=f"PL {documento} sospesa: {skipped_count} UDC saltate. Riprenota per completare.",
|
||||
status_color=self.RED,
|
||||
destination_barcode=self.NON_SCAFFALATA_BARCODE,
|
||||
destination_readonly=False,
|
||||
)
|
||||
return BarcodeActionResult(True, self._state)
|
||||
status_text = "Pronto."
|
||||
remaining = 0
|
||||
if active_document:
|
||||
remaining = await self.repository.count_picking_document_remaining(active_document)
|
||||
status_text = (
|
||||
f"PL {active_document}: {remaining} UDC residue, coda non disponibile. Verifica la prenotazione."
|
||||
if remaining else f"PL {active_document} terminata. Premi F1 o F2 per iniziare."
|
||||
)
|
||||
log_runtime_event("Barcode WMS", f"PICKING CYCLE STOP documento={active_document} priority={id_stato} remaining={remaining}")
|
||||
# A changed reservation or visibility filter must not silently
|
||||
# replace an unfinished document on the next press of F1/F2.
|
||||
if not remaining:
|
||||
self._priority_documents.pop(id_stato, None)
|
||||
self._current_priority_state = -1
|
||||
self._state = BarcodeViewState(
|
||||
mode="priority_high" if int(id_stato) == 1 else "priority_low",
|
||||
mode="manual_unload",
|
||||
queue_label=queue_label,
|
||||
status_text="Pronto.",
|
||||
status_text=status_text,
|
||||
status_color=self.RED,
|
||||
destination_barcode="9000000",
|
||||
destination_barcode=self.NON_SCAFFALATA_BARCODE,
|
||||
destination_readonly=False,
|
||||
)
|
||||
return BarcodeActionResult(True, self._state)
|
||||
|
||||
document = str(row.get("Documento") or "").strip()
|
||||
if not document or (active_document is not None and document != active_document):
|
||||
raise RuntimeError(f"Cambio inatteso documento picking: atteso={active_document}, ricevuto={document}")
|
||||
self._priority_documents[id_stato] = document
|
||||
if active_document is None:
|
||||
log_runtime_event("Barcode WMS", f"PICKING CYCLE START documento={document} priority={id_stato}")
|
||||
customer = f"{row.get('CodNazione') or ''} - {row.get('NAZIONE') or ''}".strip(" -")
|
||||
source_location = self._display_location(
|
||||
cella=row.get("Cella"),
|
||||
@@ -122,7 +240,8 @@ class BarcodeService:
|
||||
document=str(row.get("Documento") or ""),
|
||||
customer=customer,
|
||||
expected_pallet=str(row.get("Pallet") or ""),
|
||||
destination_barcode="9000000",
|
||||
destination_barcode=self.SHIPPED_BARCODE,
|
||||
destination_readonly=True,
|
||||
)
|
||||
return BarcodeActionResult(True, self._state)
|
||||
|
||||
@@ -138,30 +257,412 @@ class BarcodeService:
|
||||
if not destination.isdigit():
|
||||
return BarcodeActionResult(False, self._state, "La destinazione deve essere numerica.")
|
||||
|
||||
if self._state.mode in ("priority_high", "priority_low") and destination == "9000000":
|
||||
expected = str(self._state.expected_pallet or "").strip()
|
||||
if expected and expected != pallet:
|
||||
is_priority_mode = self._state.mode in ("priority_high", "priority_low")
|
||||
expected_before_move = str(self._state.expected_pallet or "").strip()
|
||||
is_picking_unload = bool(is_priority_mode and expected_before_move and destination == self.SHIPPED_BARCODE)
|
||||
is_direct_unload = bool(destination == self.NON_SCAFFALATA_BARCODE and not is_picking_unload)
|
||||
is_direct_load = bool(destination not in (self.NON_SCAFFALATA_BARCODE, self.SHIPPED_BARCODE) and not is_picking_unload)
|
||||
|
||||
if is_priority_mode and destination == self.SHIPPED_BARCODE:
|
||||
if expected_before_move and expected_before_move != pallet:
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.status_text = "Errata lettura: il pallet letto non coincide con quello atteso."
|
||||
self._state.status_color = self.RED
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
|
||||
move = await self.repository.execute_legacy_move(
|
||||
operator_id=self.operator_id,
|
||||
barcode_cella=destination,
|
||||
barcode_pallet=pallet,
|
||||
numero_cella=int(destination),
|
||||
if not is_picking_unload:
|
||||
blocked = await self._block_closed_picking_free_move(pallet, destination)
|
||||
if blocked is not None:
|
||||
return blocked
|
||||
|
||||
target_barcode = destination
|
||||
target_numero_cella = int(destination)
|
||||
target_id_cella = 9999 if destination == self.SHIPPED_BARCODE else (1000 if destination == self.NON_SCAFFALATA_BARCODE else None)
|
||||
target_display = destination
|
||||
if is_direct_load:
|
||||
resolved_cell = await self.repository.resolve_physical_cell(destination)
|
||||
if not resolved_cell:
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.destination_barcode = destination
|
||||
self._state.status_text = f"Cella non valida: {destination}."
|
||||
self._state.status_color = self.RED
|
||||
self._state.focus_destination = True
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
|
||||
occupants = await self.repository.fetch_open_pallets_by_cell(resolved_cell.id_cella)
|
||||
if occupants:
|
||||
log_runtime_event(
|
||||
"Barcode WMS",
|
||||
(
|
||||
"MOVE BLOCKED DESTINATION_OCCUPIED "
|
||||
f"pallet={pallet} "
|
||||
f"cell={resolved_cell.id_cella} "
|
||||
f"occupants={','.join(str(row.get('BarcodePallet') or '') for row in occupants)}"
|
||||
),
|
||||
)
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.destination_barcode = destination
|
||||
self._state.status_text = "Errore: cella scelta occupata, cambiare cella di destinazione."
|
||||
self._state.status_color = self.RED
|
||||
self._state.destination_readonly = False
|
||||
self._state.focus_destination = True
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
|
||||
target_barcode = resolved_cell.barcode_cella
|
||||
target_numero_cella = resolved_cell.numero_cella
|
||||
target_id_cella = resolved_cell.id_cella
|
||||
target_display = resolved_cell.ubicazione or destination
|
||||
|
||||
current_location = await self.repository.fetch_current_location_by_pallet(pallet)
|
||||
picking_before_move = (
|
||||
None
|
||||
if current_location
|
||||
else await self.repository.fetch_picking_by_pallet(
|
||||
pallet,
|
||||
documento=self._priority_documents.get(self._current_priority_state) if is_picking_unload else None,
|
||||
)
|
||||
)
|
||||
if move.rc != 0:
|
||||
if not current_location and not picking_before_move:
|
||||
if is_direct_load:
|
||||
trace_row = await self.repository.fetch_trace_by_pallet(pallet)
|
||||
if not trace_row:
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.destination_barcode = destination
|
||||
self._state.status_text = "Errore: UDC non riconosciuta in ERP/SAM."
|
||||
self._state.status_color = self.RED
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
|
||||
log_runtime_event(
|
||||
"Barcode WMS",
|
||||
f"AUTO INTAKE NON_SHELVED pallet={pallet} before_cell={target_id_cella}",
|
||||
)
|
||||
await self.repository.execute_legacy_move(
|
||||
operator_id=self.operator_id,
|
||||
barcode_cella=self.NON_SCAFFALATA_BARCODE,
|
||||
barcode_pallet=pallet,
|
||||
numero_cella=int(self.NON_SCAFFALATA_BARCODE),
|
||||
refresh_picking_reservation=False,
|
||||
)
|
||||
current_location = await self.repository.fetch_current_location_by_pallet(pallet)
|
||||
try:
|
||||
current_id_cella = int((current_location or {}).get("IDCella") or 0)
|
||||
except Exception:
|
||||
current_id_cella = 0
|
||||
if current_id_cella != 1000:
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.destination_barcode = destination
|
||||
self._state.status_text = "Movimento non confermato: ingresso UDC non scaffalata non riuscito."
|
||||
self._state.status_color = self.RED
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
else:
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.status_text = "UDC non presente a magazzino."
|
||||
self._state.status_color = self.RED
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
|
||||
open_locations = await self.repository.fetch_open_locations_by_pallet(pallet)
|
||||
distinct_cells = sorted({
|
||||
int(row.get("IDCella") or 0)
|
||||
for row in open_locations
|
||||
if row.get("IDCella") is not None
|
||||
})
|
||||
if len(distinct_cells) > 1:
|
||||
log_runtime_event(
|
||||
"Barcode WMS",
|
||||
(
|
||||
"MOVE BLOCKED MULTI_LOCATION "
|
||||
f"pallet={pallet} "
|
||||
f"cells={','.join(str(cell) for cell in distinct_cells)}"
|
||||
),
|
||||
)
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.status_text = f"Operazione non riuscita (RC={move.rc})."
|
||||
self._state.destination_barcode = destination
|
||||
self._state.status_text = "UDC presente in piu' celle. Movimento bloccato."
|
||||
self._state.status_color = self.RED
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
|
||||
self._state = await self._build_post_move_state(
|
||||
if not is_direct_load and destination not in (self.NON_SCAFFALATA_BARCODE, self.SHIPPED_BARCODE):
|
||||
resolved_cell = await self.repository.resolve_physical_cell(destination)
|
||||
if not resolved_cell:
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.status_text = f"Cella non valida: {destination}."
|
||||
self._state.status_color = self.RED
|
||||
self._state.focus_destination = True
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
target_barcode = resolved_cell.barcode_cella
|
||||
target_numero_cella = resolved_cell.numero_cella
|
||||
target_id_cella = resolved_cell.id_cella
|
||||
target_display = resolved_cell.ubicazione or destination
|
||||
|
||||
move = await self.repository.execute_legacy_move(
|
||||
operator_id=self.operator_id,
|
||||
barcode_cella=target_barcode,
|
||||
barcode_pallet=pallet,
|
||||
numero_cella=target_numero_cella,
|
||||
refresh_picking_reservation=is_picking_unload,
|
||||
)
|
||||
|
||||
final_location = await self.repository.fetch_current_location_by_pallet(pallet)
|
||||
try:
|
||||
final_cell = int((final_location or {}).get("IDCella") or 0)
|
||||
except Exception:
|
||||
final_cell = 0
|
||||
if target_id_cella is not None and final_cell != target_id_cella:
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.destination_barcode = destination
|
||||
self._state.status_text = "Movimento non confermato: la UDC non risulta nella cella attesa."
|
||||
self._state.status_color = self.RED
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
|
||||
try:
|
||||
self._state = await self._build_post_move_state(
|
||||
barcode_pallet=pallet,
|
||||
destination_barcode=destination,
|
||||
destination_display=target_display,
|
||||
last_priority_state=self._current_priority_state,
|
||||
auto_advance_delay_ms=3000 if is_picking_unload else 0,
|
||||
)
|
||||
except Exception as exc:
|
||||
log_exception("Barcode WMS", exc, context=f"post move state pallet={pallet} destination={destination}")
|
||||
self._state = BarcodeViewState(
|
||||
mode="confirm",
|
||||
queue_label="Conferma movimento",
|
||||
status_text="Movimento eseguito. Dettagli non aggiornati.",
|
||||
status_color=self.GREEN_YELLOW,
|
||||
destination_barcode=destination,
|
||||
scanned_pallet=pallet,
|
||||
)
|
||||
return BarcodeActionResult(True, self._state, self._state.status_text)
|
||||
|
||||
async def submit_unload_with_source_check(self, *, scanned_pallet: str, source_barcode: str) -> BarcodeActionResult:
|
||||
"""Unload to the non-shelved cell only if the scanned source cell matches DB."""
|
||||
|
||||
pallet = str(scanned_pallet or "").strip()
|
||||
source = str(source_barcode or "").strip()
|
||||
if not pallet:
|
||||
return BarcodeActionResult(False, self._state, "Inserisci o leggi il pallet.")
|
||||
if not source:
|
||||
return BarcodeActionResult(False, self._state, "Leggi il codice della cella da scaricare.")
|
||||
if not source.isdigit():
|
||||
return BarcodeActionResult(False, self._state, "La cella da scaricare deve essere numerica.")
|
||||
|
||||
blocked = await self._block_closed_picking_free_move(pallet, source)
|
||||
if blocked is not None:
|
||||
return blocked
|
||||
|
||||
current_location = await self.repository.fetch_current_location_by_pallet(pallet)
|
||||
if not current_location:
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.status_text = "UDC non presente a magazzino."
|
||||
self._state.status_color = self.RED
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
|
||||
open_locations = await self.repository.fetch_open_locations_by_pallet(pallet)
|
||||
distinct_cells = sorted({
|
||||
int(row.get("IDCella") or 0)
|
||||
for row in open_locations
|
||||
if row.get("IDCella") is not None
|
||||
})
|
||||
if len(distinct_cells) > 1:
|
||||
log_runtime_event(
|
||||
"Barcode WMS",
|
||||
(
|
||||
"MOVE BLOCKED MULTI_LOCATION "
|
||||
f"pallet={pallet} "
|
||||
f"cells={','.join(str(cell) for cell in distinct_cells)}"
|
||||
),
|
||||
)
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.destination_barcode = source
|
||||
self._state.status_text = "UDC presente in piu' celle. Movimento bloccato."
|
||||
self._state.status_color = self.RED
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
|
||||
if source == self.NON_SCAFFALATA_BARCODE:
|
||||
source_id_cella = 1000
|
||||
else:
|
||||
resolved_source = await self.repository.resolve_physical_cell(source)
|
||||
if not resolved_source:
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.destination_barcode = source
|
||||
self._state.status_text = f"Cella non valida: {source}."
|
||||
self._state.status_color = self.RED
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
source_id_cella = int(resolved_source.id_cella)
|
||||
|
||||
current_id_cella = int((current_location or {}).get("IDCella") or 0)
|
||||
if current_id_cella != source_id_cella:
|
||||
if source == self.NON_SCAFFALATA_BARCODE and current_id_cella != 1000:
|
||||
log_runtime_event(
|
||||
"Barcode WMS",
|
||||
(
|
||||
"MOVE BLOCKED SOURCE_REQUIRED "
|
||||
f"pallet={pallet} "
|
||||
f"db_cell={current_id_cella} "
|
||||
f"default_cell={source_id_cella}"
|
||||
),
|
||||
)
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.destination_barcode = source
|
||||
self._state.status_text = "Errore: leggi la cella da scaricare."
|
||||
self._state.status_color = self.RED
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
log_runtime_event(
|
||||
"Barcode WMS",
|
||||
(
|
||||
"MOVE BLOCKED SOURCE_MISMATCH "
|
||||
f"pallet={pallet} "
|
||||
f"db_cell={current_id_cella} "
|
||||
f"scanned_cell={source_id_cella}"
|
||||
),
|
||||
)
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.destination_barcode = source
|
||||
self._state.status_text = "Errore: UDC in cella diversa, rileggi il codice della cella da scaricare."
|
||||
self._state.status_color = self.RED
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
|
||||
await self.repository.execute_legacy_move(
|
||||
operator_id=self.operator_id,
|
||||
barcode_cella=self.NON_SCAFFALATA_BARCODE,
|
||||
barcode_pallet=pallet,
|
||||
numero_cella=int(self.NON_SCAFFALATA_BARCODE),
|
||||
refresh_picking_reservation=False,
|
||||
)
|
||||
|
||||
final_location = await self.repository.fetch_current_location_by_pallet(pallet)
|
||||
try:
|
||||
final_cell = int((final_location or {}).get("IDCella") or 0)
|
||||
except Exception:
|
||||
final_cell = 0
|
||||
if final_cell != 1000:
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.destination_barcode = source
|
||||
self._state.status_text = "Movimento non confermato: la UDC non risulta non scaffalata."
|
||||
self._state.status_color = self.RED
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
|
||||
try:
|
||||
self._state = await self._build_post_move_state(
|
||||
barcode_pallet=pallet,
|
||||
destination_barcode=self.NON_SCAFFALATA_BARCODE,
|
||||
destination_display=self.CONVENTIONAL_LOCATION_BY_CELL[1000],
|
||||
last_priority_state=self._current_priority_state,
|
||||
auto_advance_delay_ms=0,
|
||||
)
|
||||
except Exception as exc:
|
||||
log_exception("Barcode WMS", exc, context=f"post source-check unload pallet={pallet} source={source}")
|
||||
self._state = BarcodeViewState(
|
||||
mode="confirm",
|
||||
queue_label="Conferma movimento",
|
||||
status_text="Movimento eseguito. Dettagli non aggiornati.",
|
||||
status_color=self.GREEN_YELLOW,
|
||||
destination_barcode=self.NON_SCAFFALATA_BARCODE,
|
||||
scanned_pallet=pallet,
|
||||
)
|
||||
return BarcodeActionResult(True, self._state, self._state.status_text)
|
||||
|
||||
async def _block_closed_picking_free_move(
|
||||
self,
|
||||
pallet: str,
|
||||
destination_barcode: str,
|
||||
) -> BarcodeActionResult | None:
|
||||
closed_row = await self.repository.fetch_closed_picking_by_pallet(pallet)
|
||||
if not closed_row:
|
||||
return None
|
||||
log_runtime_event(
|
||||
"Barcode WMS",
|
||||
(
|
||||
"MOVE BLOCKED CLOSED_PICKING "
|
||||
f"pallet={pallet} "
|
||||
f"destination={destination_barcode} "
|
||||
f"id_cella={closed_row.get('IDCella')} "
|
||||
f"id_stato={closed_row.get('IDStato')}"
|
||||
),
|
||||
)
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.destination_barcode = destination_barcode
|
||||
self._state.status_text = "Errore: UDC gia' spedita, problema nella locazione o nella UDC."
|
||||
self._state.status_color = self.RED
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
|
||||
async def reconcile_after_submit_exception(
|
||||
self,
|
||||
*,
|
||||
scanned_pallet: str,
|
||||
destination_barcode: str,
|
||||
) -> BarcodeActionResult:
|
||||
"""Check whether a failed client round-trip actually committed on SQL Server."""
|
||||
|
||||
pallet = str(scanned_pallet or "").strip()
|
||||
destination = str(destination_barcode or "").strip()
|
||||
if not pallet or not destination or not destination.isdigit():
|
||||
self._state.status_text = "Transazione non completata, ripeti l'operazione."
|
||||
self._state.status_color = self.RED
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
|
||||
target_id_cella = 9999 if destination == self.SHIPPED_BARCODE else (1000 if destination == self.NON_SCAFFALATA_BARCODE else None)
|
||||
target_display = destination
|
||||
if target_id_cella is None:
|
||||
resolved_cell = await self.repository.resolve_physical_cell(destination)
|
||||
if not resolved_cell:
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.destination_barcode = destination
|
||||
self._state.status_text = "Transazione non completata, ripeti l'operazione."
|
||||
self._state.status_color = self.RED
|
||||
self._state.focus_destination = True
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
target_id_cella = int(resolved_cell.id_cella)
|
||||
target_display = resolved_cell.ubicazione or destination
|
||||
|
||||
current_location = await self.repository.fetch_current_location_by_pallet(pallet)
|
||||
try:
|
||||
current_id_cella = int((current_location or {}).get("IDCella") or 0)
|
||||
except Exception:
|
||||
current_id_cella = 0
|
||||
|
||||
if current_id_cella != target_id_cella:
|
||||
log_runtime_event(
|
||||
"Barcode WMS",
|
||||
(
|
||||
"MOVE RECOVERY NOT_CONFIRMED "
|
||||
f"pallet={pallet} "
|
||||
f"destination={destination} "
|
||||
f"expected_cell={target_id_cella} "
|
||||
f"actual_cell={current_id_cella}"
|
||||
),
|
||||
)
|
||||
self._state.scanned_pallet = pallet
|
||||
self._state.destination_barcode = destination
|
||||
self._state.status_text = "Transazione non completata, ripeti l'operazione."
|
||||
self._state.status_color = self.RED
|
||||
return BarcodeActionResult(False, self._state, self._state.status_text)
|
||||
|
||||
last_priority_state = self._current_priority_state
|
||||
is_recovered_picking = bool(destination == self.SHIPPED_BARCODE and last_priority_state in (0, 1))
|
||||
auto_advance_delay_ms = 3000 if is_recovered_picking else 0
|
||||
state = await self._build_post_move_state(
|
||||
barcode_pallet=pallet,
|
||||
destination_barcode=destination,
|
||||
last_priority_state=self._current_priority_state,
|
||||
destination_display=target_display,
|
||||
last_priority_state=last_priority_state,
|
||||
auto_advance_delay_ms=auto_advance_delay_ms,
|
||||
)
|
||||
state.status_text = (
|
||||
"Ok Scarico - risposta persa recuperata"
|
||||
if is_recovered_picking
|
||||
else "Movimento completato - risposta persa recuperata"
|
||||
)
|
||||
state.status_color = self.GREEN_YELLOW
|
||||
self._state = state
|
||||
log_runtime_event(
|
||||
"Barcode WMS",
|
||||
(
|
||||
"MOVE RECOVERY CONFIRMED "
|
||||
f"pallet={pallet} "
|
||||
f"destination={destination} "
|
||||
f"cell={target_id_cella}"
|
||||
),
|
||||
)
|
||||
return BarcodeActionResult(True, self._state, self._state.status_text)
|
||||
|
||||
@@ -170,11 +671,23 @@ class BarcodeService:
|
||||
*,
|
||||
barcode_pallet: str,
|
||||
destination_barcode: str,
|
||||
destination_display: str,
|
||||
last_priority_state: int,
|
||||
auto_advance_delay_ms: int,
|
||||
) -> BarcodeViewState:
|
||||
"""Mirror the legacy confirmation flow after one stored-procedure move."""
|
||||
|
||||
picking_row = await self.repository.fetch_picking_by_pallet(barcode_pallet)
|
||||
is_priority_shipping_confirmation = (
|
||||
destination_barcode == self.SHIPPED_BARCODE
|
||||
and last_priority_state in (0, 1)
|
||||
)
|
||||
picking_row = (
|
||||
await self.repository.fetch_picking_by_pallet(
|
||||
barcode_pallet, documento=self._priority_documents.get(last_priority_state),
|
||||
)
|
||||
if is_priority_shipping_confirmation
|
||||
else None
|
||||
)
|
||||
if picking_row:
|
||||
customer = f"{picking_row.get('CodNazione') or ''} - {picking_row.get('NAZIONE') or ''}".strip(" -")
|
||||
source_location = self._display_location(
|
||||
@@ -191,6 +704,8 @@ class BarcodeService:
|
||||
customer=customer,
|
||||
expected_pallet=str(picking_row.get("Pallet") or ""),
|
||||
destination_barcode=destination_barcode,
|
||||
auto_advance_delay_ms=auto_advance_delay_ms,
|
||||
destination_readonly=True,
|
||||
)
|
||||
|
||||
trace_row = await self.repository.fetch_trace_by_pallet(barcode_pallet)
|
||||
@@ -199,31 +714,39 @@ class BarcodeService:
|
||||
prodotto = str(trace_row.get("Prodotto") or "")
|
||||
descrizione = str(trace_row.get("Descrizione") or "")
|
||||
queue_label = "Alta priorita' (F1)" if last_priority_state == 1 else ("Bassa priorita' (F2)" if last_priority_state == 0 else "Conferma movimento")
|
||||
destination_label = self._display_destination_location(
|
||||
destination_barcode=destination_barcode,
|
||||
destination_display=destination_display,
|
||||
)
|
||||
return BarcodeViewState(
|
||||
mode="confirm",
|
||||
queue_label=queue_label,
|
||||
status_text=(
|
||||
"Ok Scarico" if destination_barcode == "9000000" else f"Ok Carico - {destination_barcode}"
|
||||
f"Ok Scarico - {destination_label}"
|
||||
if destination_barcode in (self.NON_SCAFFALATA_BARCODE, self.SHIPPED_BARCODE)
|
||||
else f"Ok Carico - {destination_label}"
|
||||
),
|
||||
status_color=self.GREEN_YELLOW,
|
||||
source_location=str(destination_barcode or ""),
|
||||
source_location=destination_label,
|
||||
document=(
|
||||
self.CONVENTIONAL_LOCATION_BY_CELL[9999]
|
||||
if destination_barcode == "9000000" and last_priority_state in (0, 1)
|
||||
self.CONVENTIONAL_LOCATION_BY_CELL[9999 if destination_barcode == self.SHIPPED_BARCODE else 1000]
|
||||
if destination_barcode in (self.NON_SCAFFALATA_BARCODE, self.SHIPPED_BARCODE) and last_priority_state in (0, 1)
|
||||
else lotto
|
||||
),
|
||||
customer=(
|
||||
lotto
|
||||
if destination_barcode == "9000000" and last_priority_state in (0, 1)
|
||||
if destination_barcode in (self.NON_SCAFFALATA_BARCODE, self.SHIPPED_BARCODE) and last_priority_state in (0, 1)
|
||||
else prodotto
|
||||
),
|
||||
expected_pallet=(
|
||||
" - ".join(part for part in (prodotto, descrizione) if part)
|
||||
if destination_barcode == "9000000" and last_priority_state in (0, 1)
|
||||
if destination_barcode in (self.NON_SCAFFALATA_BARCODE, self.SHIPPED_BARCODE) and last_priority_state in (0, 1)
|
||||
else descrizione
|
||||
),
|
||||
destination_barcode=destination_barcode,
|
||||
scanned_pallet=barcode_pallet,
|
||||
auto_advance_delay_ms=auto_advance_delay_ms,
|
||||
destination_readonly=destination_barcode in (self.NON_SCAFFALATA_BARCODE, self.SHIPPED_BARCODE),
|
||||
)
|
||||
|
||||
return BarcodeViewState(
|
||||
@@ -235,6 +758,15 @@ class BarcodeService:
|
||||
scanned_pallet=barcode_pallet,
|
||||
)
|
||||
|
||||
def _display_destination_location(self, *, destination_barcode: str, destination_display: str) -> str:
|
||||
"""Return the confirmation label for a movement destination."""
|
||||
|
||||
if destination_barcode == self.NON_SCAFFALATA_BARCODE:
|
||||
return self.CONVENTIONAL_LOCATION_BY_CELL[1000]
|
||||
if destination_barcode == self.SHIPPED_BARCODE:
|
||||
return self.CONVENTIONAL_LOCATION_BY_CELL[9999]
|
||||
return str(destination_display or destination_barcode or "")
|
||||
|
||||
def _display_location(self, *, cella: object, ubicazione: object) -> str:
|
||||
"""Return the operator-facing location, honoring legacy conventional cells."""
|
||||
|
||||
|
||||
@@ -6,6 +6,9 @@ import tkinter as tk
|
||||
import customtkinter as ctk
|
||||
|
||||
from ui_theme import theme_color, theme_font, theme_padding, theme_value
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
|
||||
class InlineBusyOverlay:
|
||||
|
||||
256
comandi_git_per_installare.txt
Normal file
256
comandi_git_per_installare.txt
Normal file
@@ -0,0 +1,256 @@
|
||||
# Prontuario Git per installare/aggiornare Warehouse da remoto
|
||||
|
||||
Repository Gitea:
|
||||
|
||||
https://gitea.alessandrobonvicini.it/administrator/ware_house.git
|
||||
|
||||
Cartella consigliata sul PC di produzione:
|
||||
|
||||
C:\flywms
|
||||
|
||||
Ramo principale da usare in produzione:
|
||||
|
||||
main
|
||||
|
||||
Ultimo tag stabile al momento della stesura:
|
||||
|
||||
alpha7-stabilizzazione-non-scaffalate
|
||||
|
||||
|
||||
1. Prima installazione su PC nuovo
|
||||
----------------------------------
|
||||
|
||||
Aprire PowerShell nella macchina di produzione ed eseguire:
|
||||
|
||||
cd C:\
|
||||
git clone https://gitea.alessandrobonvicini.it/administrator/ware_house.git C:\flywms
|
||||
cd C:\flywms
|
||||
git switch main
|
||||
git pull origin main
|
||||
|
||||
Installare le dipendenze Python:
|
||||
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install -r requirements.txt
|
||||
|
||||
Avvio applicazione desktop:
|
||||
|
||||
python main.py
|
||||
|
||||
Oppure senza finestra console:
|
||||
|
||||
pythonw warehouse.pyw
|
||||
|
||||
Avvio applicazione barcode:
|
||||
|
||||
python barcode_client.py
|
||||
|
||||
Oppure senza finestra console:
|
||||
|
||||
pythonw barcode.pyw
|
||||
|
||||
|
||||
2. Aggiornare un'installazione gia' esistente
|
||||
--------------------------------------------
|
||||
|
||||
Sul PC di produzione:
|
||||
|
||||
cd C:\flywms
|
||||
git fetch --all --tags
|
||||
git switch main
|
||||
git pull origin main
|
||||
python -m pip install -r requirements.txt
|
||||
|
||||
Poi rilanciare l'applicazione.
|
||||
|
||||
|
||||
2.bis Aggiornare produzione dopo merge su main gia' fatto
|
||||
---------------------------------------------------------
|
||||
|
||||
Questo e' il caso piu' normale:
|
||||
|
||||
- sul PC di sviluppo hai gia' fatto merge del ramo di lavoro dentro main;
|
||||
- hai gia' fatto push su Gitea;
|
||||
- sul PC di produzione devi solo scaricare l'ultima versione ufficiale.
|
||||
|
||||
Sul PC di produzione eseguire:
|
||||
|
||||
cd C:\flywms
|
||||
git fetch --all --tags
|
||||
git switch main
|
||||
git pull origin main
|
||||
python -m pip install -r requirements.txt
|
||||
|
||||
Poi chiudere e riaprire l'applicazione.
|
||||
|
||||
Controllo consigliato dopo l'aggiornamento:
|
||||
|
||||
git log --oneline --decorate -3
|
||||
git describe --tags --abbrev=0 main
|
||||
|
||||
|
||||
3. Controllare che versione/tag si sta usando
|
||||
---------------------------------------------
|
||||
|
||||
Dentro C:\flywms:
|
||||
|
||||
git status
|
||||
git log --oneline --decorate -5
|
||||
|
||||
Vedere l'ultimo tag raggiungibile da main:
|
||||
|
||||
git describe --tags --abbrev=0 main
|
||||
|
||||
Vedere tutti i tag, dal piu' recente:
|
||||
|
||||
git tag --sort=-creatordate
|
||||
|
||||
Vedere graficamente branch, commit e tag:
|
||||
|
||||
git log --oneline --decorate --graph --all -20
|
||||
|
||||
|
||||
4. Installare esattamente una versione taggata
|
||||
---------------------------------------------
|
||||
|
||||
Usare questa modalita' quando si vuole installare una fotografia precisa e non
|
||||
necessariamente l'ultima versione di main.
|
||||
|
||||
Esempio:
|
||||
|
||||
cd C:\
|
||||
git clone --branch alpha7-stabilizzazione-non-scaffalate https://gitea.alessandrobonvicini.it/administrator/ware_house.git C:\flywms_alpha7
|
||||
|
||||
Nota:
|
||||
|
||||
Un tag e' una fotografia ferma. Non avanza con git pull come un branch.
|
||||
Per produzione ordinaria e' piu' comodo usare main.
|
||||
|
||||
|
||||
5. Portare l'ultimo sviluppo dentro main
|
||||
---------------------------------------
|
||||
|
||||
Da fare sulla macchina di sviluppo, non sul PC di produzione.
|
||||
|
||||
Se l'ultima versione buona e' su sviluppo3 e vuoi renderla ufficiale su main:
|
||||
|
||||
cd C:\devel\python\ware_house
|
||||
git fetch --all --tags
|
||||
git status
|
||||
git switch main
|
||||
git pull origin main
|
||||
git merge sviluppo3
|
||||
git push origin main
|
||||
|
||||
Se vuoi anche creare un tag stabile:
|
||||
|
||||
git tag nome-del-tag
|
||||
git push origin nome-del-tag
|
||||
|
||||
Esempio:
|
||||
|
||||
git tag alpha8-nome-breve-della-modifica
|
||||
git push origin alpha8-nome-breve-della-modifica
|
||||
|
||||
|
||||
6. Se il PC di produzione ha modifiche locali
|
||||
---------------------------------------------
|
||||
|
||||
Prima di aggiornare controllare:
|
||||
|
||||
cd C:\flywms
|
||||
git status
|
||||
|
||||
Se compaiono file modificati che non devono essere conservati, NON fare comandi
|
||||
distruttivi senza sapere cosa sono. Prima copiare o rinominare i file modificati.
|
||||
|
||||
File che normalmente NON devono essere messi nel repository:
|
||||
|
||||
db_connection.json
|
||||
*.log
|
||||
__pycache__
|
||||
*.pyc
|
||||
*.zip
|
||||
|
||||
|
||||
7. Script SQL
|
||||
-------------
|
||||
|
||||
Gli script SQL sono nel repository e vanno lanciati in SSMS solo quando serve
|
||||
preparare o aggiornare il database per le funzioni Python.
|
||||
|
||||
Patch principali:
|
||||
|
||||
apply_python_parallel_pickinglist_patch.sql
|
||||
apply_python_pickinglist_history_views.sql
|
||||
apply_online_history_forms_patch.sql
|
||||
|
||||
Rollback principali:
|
||||
|
||||
rollback_python_parallel_pickinglist_patch.sql
|
||||
rollback_python_pickinglist_history_views.sql
|
||||
rollback_online_history_forms_patch.sql
|
||||
|
||||
Nota:
|
||||
|
||||
Prima di lanciare patch SQL in produzione, fare sempre backup o snapshot del
|
||||
database, oppure verificare di avere una procedura di rollback sicura.
|
||||
|
||||
|
||||
8. Comando rapido piu' usato
|
||||
----------------------------
|
||||
|
||||
Aggiornamento standard del PC di produzione:
|
||||
|
||||
cd C:\flywms
|
||||
git fetch --all --tags
|
||||
git switch main
|
||||
git pull origin main
|
||||
python -m pip install -r requirements.txt
|
||||
|
||||
|
||||
9. Per vedere cosa ho installato
|
||||
------------------------------------------------------
|
||||
git log --oneline --decorate -3
|
||||
git describe --tags --abbrev=0 main
|
||||
|
||||
|
||||
10. Salvare questo prontuario su Gitea
|
||||
-------------------------------------
|
||||
|
||||
Da fare sul PC di sviluppo, dentro la cartella del repository:
|
||||
|
||||
cd C:\devel\python\ware_house
|
||||
git status
|
||||
git add comandi_git_per_installare.txt
|
||||
git commit -m "Aggiungi prontuario Git per installazione remota"
|
||||
git push origin main
|
||||
|
||||
Dopo il push, il file sara' disponibile anche sui PC di produzione al prossimo:
|
||||
|
||||
cd C:\flywms
|
||||
git pull origin main
|
||||
|
||||
|
||||
11. Aggiornare il prontuario se lo modifico in locale
|
||||
----------------------------------------------------
|
||||
|
||||
Se modifichi questo file sul PC di sviluppo e vuoi sincronizzarlo su Gitea:
|
||||
|
||||
cd C:\devel\python\ware_house
|
||||
git status
|
||||
git diff -- comandi_git_per_installare.txt
|
||||
git add comandi_git_per_installare.txt
|
||||
git commit -m "Aggiorna prontuario Git installazione"
|
||||
git push origin main
|
||||
|
||||
Se invece lo hai modificato su un PC di produzione e vuoi prima recuperare
|
||||
eventuali aggiornamenti online:
|
||||
|
||||
cd C:\flywms
|
||||
git status
|
||||
git pull origin main
|
||||
|
||||
Se Git segnala conflitti, fermarsi e risolverli prima di rilanciare
|
||||
l'applicazione. Per evitare confusione, e' meglio modificare questo prontuario
|
||||
solo sul PC di sviluppo e poi fare push su Gitea.
|
||||
15
db_config.py
15
db_config.py
@@ -6,13 +6,17 @@ import asyncio
|
||||
import json
|
||||
import tkinter as tk
|
||||
from pathlib import Path
|
||||
from tkinter import messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import ttk
|
||||
from typing import Any
|
||||
|
||||
from async_msssql_query import AsyncMSSQLClient, make_mssql_dsn
|
||||
from locale_text import load_locale_catalog, text as loc_text
|
||||
from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text
|
||||
from ui_theme import theme_section, theme_value
|
||||
from version_info import module_version, versioned_title
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
CONFIG_PATH = Path(__file__).with_name("db_connection.json")
|
||||
DEFAULT_DB_CONFIG: dict[str, Any] = {
|
||||
@@ -23,6 +27,11 @@ DEFAULT_DB_CONFIG: dict[str, Any] = {
|
||||
"driver": "ODBC Driver 17 for SQL Server",
|
||||
"trust_server_certificate": True,
|
||||
"encrypt": "",
|
||||
"query_profiler": {
|
||||
"enabled": False,
|
||||
"slow_ms": 0,
|
||||
"sql_limit": 4000,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -101,7 +110,7 @@ class DatabaseConfigWindow(tk.Toplevel):
|
||||
self.result_config: dict[str, Any] | None = None
|
||||
merged = {**DEFAULT_DB_CONFIG, **(initial or {})}
|
||||
|
||||
self.title(loc_text("dbconfig.title", catalog=self._locale_catalog, default="Configurazione Database"))
|
||||
self.title(versioned_title(loc_text("dbconfig.title", catalog=self._locale_catalog, default="Configurazione Database"), __name__))
|
||||
self.geometry(str(theme_value(self._theme, "window_geometry", "520x360")))
|
||||
self.resizable(False, False)
|
||||
try:
|
||||
@@ -365,6 +374,7 @@ class DatabaseConfigWindow(tk.Toplevel):
|
||||
loc_text("dbconfig.msg.title", catalog=self._locale_catalog, default="Configurazione Database"),
|
||||
loc_text("dbconfig.msg.test_error", catalog=self._locale_catalog, default="Connessione fallita:\n{error}").format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
return
|
||||
messagebox.showinfo(
|
||||
@@ -385,6 +395,7 @@ class DatabaseConfigWindow(tk.Toplevel):
|
||||
loc_text("dbconfig.msg.title", catalog=self._locale_catalog, default="Configurazione Database"),
|
||||
loc_text("dbconfig.msg.save_error", catalog=self._locale_catalog, default="Salvataggio fallito:\n{error}").format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
return
|
||||
self.result_config = config
|
||||
|
||||
549
diagnostica.py
Normal file
549
diagnostica.py
Normal file
@@ -0,0 +1,549 @@
|
||||
"""Operational diagnostic checks for warehouse data quadrature."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from datetime import datetime
|
||||
import error_dialog as messagebox
|
||||
from tkinter import filedialog, ttk
|
||||
from typing import Any
|
||||
|
||||
import customtkinter as ctk
|
||||
|
||||
from busy_overlay import InlineBusyOverlay
|
||||
from gestione_aree import AsyncRunner
|
||||
from locale_text import load_locale_catalog, text as loc_text
|
||||
from runtime_support import log_exception
|
||||
from ui_tables import style_treeview, zebra_tag
|
||||
from ui_theme import theme_color, theme_font, theme_section, theme_value
|
||||
from version_info import module_version, versioned_title
|
||||
from window_placement import place_window_fullsize_below_parent_later
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
|
||||
SQL_SHIPPED_NOT_DISASSOCIATED = """
|
||||
SELECT DISTINCT
|
||||
LTRIM(RTRIM(g.BarcodePallet)) AS UDC,
|
||||
CAST('Spedita ma non disassociata' AS varchar(64)) AS Diagnostica,
|
||||
CONCAT(
|
||||
RTRIM(c.Corsia),
|
||||
' - ',
|
||||
RTRIM(CAST(c.Colonna AS varchar(32))),
|
||||
' - ',
|
||||
RTRIM(CAST(c.Fila AS varchar(32)))
|
||||
) AS NomeSimbolicoCella
|
||||
FROM dbo.XMag_GiacenzaPallet AS g
|
||||
INNER JOIN dbo.Celle AS c
|
||||
ON c.ID = g.IDCella
|
||||
INNER JOIN dbo.py_XMag_ViewPackingListStorico AS chiuse
|
||||
ON LTRIM(RTRIM(chiuse.Pallet)) COLLATE Latin1_General_CI_AS =
|
||||
LTRIM(RTRIM(g.BarcodePallet)) COLLATE Latin1_General_CI_AS
|
||||
WHERE chiuse.StatoDocumento = 'D'
|
||||
AND g.IDCella <> 9999
|
||||
ORDER BY NomeSimbolicoCella, UDC;
|
||||
"""
|
||||
|
||||
SQL_MULTIPLE_UDC_BY_CELL = """
|
||||
WITH celle_multiple AS (
|
||||
SELECT
|
||||
g.IDCella
|
||||
FROM dbo.XMag_GiacenzaPallet AS g
|
||||
WHERE g.IDCella NOT IN (1000, 9999)
|
||||
GROUP BY g.IDCella
|
||||
HAVING COUNT(DISTINCT LTRIM(RTRIM(g.BarcodePallet))) > 1
|
||||
)
|
||||
SELECT
|
||||
CONCAT(
|
||||
RTRIM(c.Corsia),
|
||||
' - ',
|
||||
RTRIM(CAST(c.Colonna AS varchar(32))),
|
||||
' - ',
|
||||
RTRIM(CAST(c.Fila AS varchar(32)))
|
||||
) AS CELLA,
|
||||
LTRIM(RTRIM(g.BarcodePallet)) AS UDC
|
||||
FROM dbo.XMag_GiacenzaPallet AS g
|
||||
INNER JOIN celle_multiple AS cm
|
||||
ON cm.IDCella = g.IDCella
|
||||
INNER JOIN dbo.Celle AS c
|
||||
ON c.ID = g.IDCella
|
||||
ORDER BY CELLA, UDC;
|
||||
"""
|
||||
|
||||
SQL_SAM_UDC_NOT_IN_WMS = """
|
||||
WITH recent_lotser AS (
|
||||
SELECT TOP (5000)
|
||||
ls.ID,
|
||||
LEFT(ls.NUMSER, 6) AS UDC,
|
||||
ls.NUMLOT AS Lotto,
|
||||
ls.IDARTICO
|
||||
FROM SAMA1.dbo.LOTSER AS ls
|
||||
WHERE NULLIF(LTRIM(RTRIM(LEFT(ls.NUMSER, 6))), '') IS NOT NULL
|
||||
AND TRY_CONVERT(int, LTRIM(RTRIM(LEFT(ls.NUMSER, 6)))) > 0
|
||||
AND LEN(LTRIM(RTRIM(LEFT(ls.NUMSER, 6)))) = 6
|
||||
AND ls.NUMLOT LIKE CONCAT('P', RIGHT(CONVERT(varchar(4), YEAR(GETDATE())), 2), '%')
|
||||
ORDER BY ls.ID DESC
|
||||
), sam_udc AS (
|
||||
SELECT
|
||||
LTRIM(RTRIM(r.UDC)) AS UDC,
|
||||
MIN(r.Lotto) AS Lotto,
|
||||
MIN(a.CODICE) AS Prodotto,
|
||||
MIN(a.DESCR) AS Descrizione,
|
||||
MAX(r.ID) AS UltimoIDLotSer
|
||||
FROM recent_lotser AS r
|
||||
INNER JOIN SAMA1.dbo.ARTICO AS a
|
||||
ON a.ID = r.IDARTICO
|
||||
GROUP BY LTRIM(RTRIM(r.UDC))
|
||||
)
|
||||
SELECT TOP (100)
|
||||
s.UDC,
|
||||
s.Lotto,
|
||||
s.Prodotto,
|
||||
s.Descrizione
|
||||
FROM sam_udc AS s
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM dbo.MagazziniPallet AS mp
|
||||
WHERE LTRIM(RTRIM(mp.Attributo)) COLLATE Latin1_General_CI_AS =
|
||||
s.UDC COLLATE Latin1_General_CI_AS
|
||||
)
|
||||
ORDER BY s.UltimoIDLotSer DESC;
|
||||
"""
|
||||
|
||||
SHIPPED_NOT_DISASSOCIATED_COLUMNS = (
|
||||
("UDC", "diagnostics.col.udc", "UDC", 130, "w"),
|
||||
(
|
||||
"Diagnostica",
|
||||
"diagnostics.col.shipped_not_disassociated",
|
||||
"Spedita ma non disassociata",
|
||||
280,
|
||||
"w",
|
||||
),
|
||||
("NomeSimbolicoCella", "diagnostics.col.symbolic_cell", "Nome simbolico cella", 240, "w"),
|
||||
)
|
||||
|
||||
MULTIPLE_UDC_COLUMNS = (
|
||||
("CELLA", "diagnostics.col.cell", "CELLA", 220, "w"),
|
||||
("UDC", "diagnostics.col.udc", "UDC", 160, "w"),
|
||||
)
|
||||
|
||||
SAM_UDC_NOT_IN_WMS_COLUMNS = (
|
||||
("UDC", "diagnostics.col.udc", "UDC", 130, "w"),
|
||||
("Lotto", "diagnostics.col.lot", "Lotto", 160, "w"),
|
||||
("Prodotto", "diagnostics.col.product", "Prodotto", 150, "w"),
|
||||
("Descrizione", "diagnostics.col.description", "Descrizione", 360, "w"),
|
||||
)
|
||||
|
||||
|
||||
def _rows_to_dicts(res: dict[str, Any] | None) -> list[dict[str, Any]]:
|
||||
if not isinstance(res, dict):
|
||||
return []
|
||||
rows = res.get("rows") or []
|
||||
cols = res.get("columns") or []
|
||||
if rows and isinstance(rows[0], dict):
|
||||
return [row for row in rows if isinstance(row, dict)]
|
||||
|
||||
out: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
if isinstance(row, (list, tuple)) and cols:
|
||||
out.append({str(cols[i]): row[i] for i in range(min(len(cols), len(row)))})
|
||||
return out
|
||||
|
||||
|
||||
class DiagnosticaWindow(ctk.CTkToplevel):
|
||||
"""Window collecting read-only diagnostic queries."""
|
||||
|
||||
def __init__(self, parent: tk.Widget, db_client, session=None):
|
||||
super().__init__(parent)
|
||||
self.db_client = db_client
|
||||
self.session = session
|
||||
self._theme = theme_section("diagnostics_window", theme_section("search_window", {}))
|
||||
self._locale_catalog = load_locale_catalog()
|
||||
self._async = AsyncRunner(self)
|
||||
self._busy = InlineBusyOverlay(self, self._theme)
|
||||
self._load_in_progress = False
|
||||
self._current_check = ""
|
||||
self.var_status = tk.StringVar(value="")
|
||||
self._last_export_slug = "diagnostica"
|
||||
self._current_columns = SHIPPED_NOT_DISASSOCIATED_COLUMNS
|
||||
self._column_titles: dict[str, str] = {}
|
||||
self._sort_column = ""
|
||||
self._sort_descending = False
|
||||
|
||||
self.title(
|
||||
versioned_title(
|
||||
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
|
||||
__name__,
|
||||
)
|
||||
)
|
||||
self.geometry(str(theme_value(self._theme, "window_geometry", "1100x680")))
|
||||
minsize = theme_value(self._theme, "window_minsize", [900, 560])
|
||||
self.minsize(int(minsize[0]), int(minsize[1]))
|
||||
try:
|
||||
self.configure(fg_color=theme_color(self._theme, "window_fg_color", ("#efefef", "#2f2f2f")))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self._build_ui()
|
||||
|
||||
def _is_alive(self) -> bool:
|
||||
try:
|
||||
return bool(self.winfo_exists())
|
||||
except tk.TclError:
|
||||
return False
|
||||
|
||||
def _hide_busy_safe(self) -> None:
|
||||
try:
|
||||
self._busy.hide()
|
||||
except Exception as exc:
|
||||
log_exception(__name__, exc, context="hide busy diagnostica")
|
||||
|
||||
def _build_ui(self) -> None:
|
||||
self.grid_rowconfigure(2, weight=1)
|
||||
self.grid_columnconfigure(0, weight=1)
|
||||
|
||||
top = ctk.CTkFrame(
|
||||
self,
|
||||
fg_color=theme_color(self._theme, "toolbar_frame_fg_color", ("#d7d7d7", "#3b3b3b")),
|
||||
)
|
||||
top.grid(row=0, column=0, sticky="ew", padx=8, pady=8)
|
||||
top.grid_columnconfigure(3, weight=1)
|
||||
|
||||
button_font = theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold"))
|
||||
ctk.CTkButton(
|
||||
top,
|
||||
text=loc_text(
|
||||
"diagnostics.button.shipped_not_disassociated",
|
||||
catalog=self._locale_catalog,
|
||||
default="UDC spedite non disassociate",
|
||||
),
|
||||
command=self._load_shipped_not_disassociated,
|
||||
font=button_font,
|
||||
).grid(row=0, column=0, sticky="w", padx=(0, 8))
|
||||
|
||||
ctk.CTkButton(
|
||||
top,
|
||||
text=loc_text(
|
||||
"diagnostics.button.multiple_udc_by_cell",
|
||||
catalog=self._locale_catalog,
|
||||
default="Celle con multiple UDC",
|
||||
),
|
||||
command=self._load_multiple_udc_by_cell,
|
||||
font=button_font,
|
||||
).grid(row=0, column=1, sticky="w", padx=(0, 8))
|
||||
|
||||
ctk.CTkButton(
|
||||
top,
|
||||
text=loc_text(
|
||||
"diagnostics.button.sam_udc_not_in_wms",
|
||||
catalog=self._locale_catalog,
|
||||
default="Ultime UDC SAM non in WMS",
|
||||
),
|
||||
command=self._load_sam_udc_not_in_wms,
|
||||
font=button_font,
|
||||
).grid(row=0, column=2, sticky="w", padx=(0, 8))
|
||||
|
||||
self.btn_export = ctk.CTkButton(
|
||||
top,
|
||||
text=loc_text("diagnostics.button.export", catalog=self._locale_catalog, default="Esporta XLSX"),
|
||||
command=self._export_xlsx,
|
||||
font=button_font,
|
||||
state="disabled",
|
||||
)
|
||||
self.btn_export.grid(row=0, column=4, sticky="e")
|
||||
|
||||
ctk.CTkLabel(
|
||||
self,
|
||||
textvariable=self.var_status,
|
||||
anchor="w",
|
||||
font=theme_font(self._theme, "status_font", ("Segoe UI", 10, "bold")),
|
||||
).grid(row=1, column=0, sticky="ew", padx=10, pady=(0, 6))
|
||||
|
||||
wrap = ctk.CTkFrame(self)
|
||||
wrap.grid(row=2, column=0, sticky="nsew", padx=8, pady=(0, 8))
|
||||
wrap.grid_rowconfigure(0, weight=1)
|
||||
wrap.grid_columnconfigure(0, weight=1)
|
||||
|
||||
self.tree = ttk.Treeview(wrap, show="headings")
|
||||
self._configure_tree_columns(self._current_columns)
|
||||
style_treeview(
|
||||
self.tree,
|
||||
style_name="Diagnostics.Treeview",
|
||||
rowheight=22,
|
||||
font=("", 9),
|
||||
heading_font=("", 9, "bold"),
|
||||
)
|
||||
|
||||
sy = ttk.Scrollbar(wrap, orient="vertical", command=self.tree.yview)
|
||||
sx = ttk.Scrollbar(wrap, orient="horizontal", command=self.tree.xview)
|
||||
self.tree.configure(yscrollcommand=sy.set, xscrollcommand=sx.set)
|
||||
self.tree.grid(row=0, column=0, sticky="nsew")
|
||||
sy.grid(row=0, column=1, sticky="ns")
|
||||
sx.grid(row=1, column=0, sticky="ew")
|
||||
|
||||
def _set_status(self, text: str) -> None:
|
||||
self.var_status.set(text)
|
||||
|
||||
def _configure_tree_columns(self, columns) -> None:
|
||||
self.tree.delete(*self.tree.get_children(""))
|
||||
keys = tuple(str(col[0]) for col in columns)
|
||||
self.tree.configure(columns=keys, show="headings")
|
||||
self._sort_column = ""
|
||||
self._sort_descending = False
|
||||
self._column_titles = {}
|
||||
for key, locale_key, default, width, anchor in columns:
|
||||
title = loc_text(str(locale_key), catalog=self._locale_catalog, default=str(default))
|
||||
self._column_titles[str(key)] = title
|
||||
self.tree.heading(
|
||||
key,
|
||||
text=title,
|
||||
command=lambda col=str(key): self._sort_by_column(col),
|
||||
)
|
||||
self.tree.column(key, width=int(width), anchor=str(anchor), stretch=True)
|
||||
|
||||
def _refresh_sort_headings(self) -> None:
|
||||
for key, title in self._column_titles.items():
|
||||
suffix = ""
|
||||
if key == self._sort_column:
|
||||
suffix = " v" if self._sort_descending else " ^"
|
||||
self.tree.heading(key, text=f"{title}{suffix}", command=lambda col=key: self._sort_by_column(col))
|
||||
|
||||
def _sort_key(self, value: Any) -> tuple[int, Any]:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return (2, "")
|
||||
normalized = text.replace(".", "").replace(",", ".")
|
||||
try:
|
||||
return (0, float(normalized))
|
||||
except ValueError:
|
||||
return (1, text.casefold())
|
||||
|
||||
def _sort_by_column(self, column: str) -> None:
|
||||
columns = list(self.tree["columns"])
|
||||
if column not in columns:
|
||||
return
|
||||
descending = not self._sort_descending if self._sort_column == column else False
|
||||
col_index = columns.index(column)
|
||||
rows = []
|
||||
for iid in self.tree.get_children(""):
|
||||
values = self.tree.item(iid, "values")
|
||||
value = values[col_index] if col_index < len(values) else ""
|
||||
rows.append((self._sort_key(value), iid))
|
||||
rows.sort(key=lambda item: item[0], reverse=descending)
|
||||
for index, (_key, iid) in enumerate(rows):
|
||||
self.tree.move(iid, "", index)
|
||||
self.tree.item(iid, tags=(zebra_tag(index),))
|
||||
self._sort_column = column
|
||||
self._sort_descending = descending
|
||||
self._refresh_sort_headings()
|
||||
|
||||
def _load_shipped_not_disassociated(self) -> None:
|
||||
self._run_check(
|
||||
key="shipped_not_disassociated",
|
||||
sql=SQL_SHIPPED_NOT_DISASSOCIATED,
|
||||
columns=SHIPPED_NOT_DISASSOCIATED_COLUMNS,
|
||||
busy_text=loc_text(
|
||||
"diagnostics.busy.shipped_not_disassociated",
|
||||
catalog=self._locale_catalog,
|
||||
default="Cerco UDC spedite ma ancora in cella...",
|
||||
),
|
||||
)
|
||||
|
||||
def _load_multiple_udc_by_cell(self) -> None:
|
||||
self._run_check(
|
||||
key="multiple_udc_by_cell",
|
||||
sql=SQL_MULTIPLE_UDC_BY_CELL,
|
||||
columns=MULTIPLE_UDC_COLUMNS,
|
||||
busy_text=loc_text(
|
||||
"diagnostics.busy.multiple_udc_by_cell",
|
||||
catalog=self._locale_catalog,
|
||||
default="Cerco celle con multiple UDC...",
|
||||
),
|
||||
)
|
||||
|
||||
def _load_sam_udc_not_in_wms(self) -> None:
|
||||
self._run_check(
|
||||
key="sam_udc_not_in_wms",
|
||||
sql=SQL_SAM_UDC_NOT_IN_WMS,
|
||||
columns=SAM_UDC_NOT_IN_WMS_COLUMNS,
|
||||
busy_text=loc_text(
|
||||
"diagnostics.busy.sam_udc_not_in_wms",
|
||||
catalog=self._locale_catalog,
|
||||
default="Cerco le ultime UDC presenti in SAM ma non ancora in WMS...",
|
||||
),
|
||||
)
|
||||
|
||||
def _run_check(self, *, key: str, sql: str, columns, busy_text: str) -> None:
|
||||
if self._load_in_progress or not self._is_alive():
|
||||
return
|
||||
|
||||
async def job():
|
||||
return await self.db_client.query_json(sql, as_dict_rows=True)
|
||||
|
||||
self._load_in_progress = True
|
||||
self._current_check = key
|
||||
self._last_export_slug = key
|
||||
self._current_columns = columns
|
||||
self._configure_tree_columns(columns)
|
||||
try:
|
||||
self.btn_export.configure(state="disabled")
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self._busy.show(busy_text)
|
||||
self._async.run(job(), self._on_loaded, self._on_error)
|
||||
except Exception as exc:
|
||||
self._load_in_progress = False
|
||||
self._hide_busy_safe()
|
||||
log_exception(__name__, exc, context=f"avvio diagnostica {key}")
|
||||
messagebox.showerror(
|
||||
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
|
||||
str(exc),
|
||||
parent=self if self._is_alive() else None,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
def _on_loaded(self, res: dict[str, Any] | None) -> None:
|
||||
self._load_in_progress = False
|
||||
self._hide_busy_safe()
|
||||
if not self._is_alive():
|
||||
return
|
||||
try:
|
||||
rows = _rows_to_dicts(res)
|
||||
self.tree.delete(*self.tree.get_children(""))
|
||||
keys = [str(col[0]) for col in self._current_columns]
|
||||
for index, row in enumerate(rows):
|
||||
self.tree.insert(
|
||||
"",
|
||||
"end",
|
||||
values=tuple(row.get(key) or "" for key in keys),
|
||||
tags=(zebra_tag(index),),
|
||||
)
|
||||
try:
|
||||
self.btn_export.configure(state="normal" if rows else "disabled")
|
||||
except Exception:
|
||||
pass
|
||||
self._set_status(
|
||||
loc_text(
|
||||
"diagnostics.status.rows",
|
||||
catalog=self._locale_catalog,
|
||||
default="Righe trovate: {count}",
|
||||
).format(count=len(rows))
|
||||
)
|
||||
except Exception as exc:
|
||||
log_exception(__name__, exc, context="render diagnostica")
|
||||
messagebox.showerror(
|
||||
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
|
||||
str(exc),
|
||||
parent=self,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
def _on_error(self, exc: BaseException) -> None:
|
||||
self._load_in_progress = False
|
||||
self._hide_busy_safe()
|
||||
log_exception(__name__, exc, context=f"query diagnostica {self._current_check}")
|
||||
if not self._is_alive():
|
||||
return
|
||||
messagebox.showerror(
|
||||
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
|
||||
str(exc),
|
||||
parent=self,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
def _export_xlsx(self) -> None:
|
||||
"""Export the currently visible diagnostic grid to an Excel file."""
|
||||
|
||||
rows = [self.tree.item(iid, "values") for iid in self.tree.get_children("")]
|
||||
if not rows:
|
||||
messagebox.showinfo(
|
||||
loc_text("diagnostics.export.title", catalog=self._locale_catalog, default="Esporta"),
|
||||
loc_text(
|
||||
"diagnostics.export.empty",
|
||||
catalog=self._locale_catalog,
|
||||
default="Non ci sono righe da esportare.",
|
||||
),
|
||||
parent=self,
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Font
|
||||
from openpyxl.utils import get_column_letter
|
||||
except Exception as exc:
|
||||
messagebox.showerror(
|
||||
loc_text("diagnostics.export.title", catalog=self._locale_catalog, default="Esporta"),
|
||||
loc_text(
|
||||
"diagnostics.export.dep",
|
||||
catalog=self._locale_catalog,
|
||||
default="Per l'esportazione serve 'openpyxl' (pip install openpyxl).",
|
||||
).format(error=exc),
|
||||
parent=self,
|
||||
exception=exc,
|
||||
)
|
||||
return
|
||||
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M")
|
||||
default_name = f"{self._last_export_slug}_{ts}.xlsx"
|
||||
path = filedialog.asksaveasfilename(
|
||||
parent=self,
|
||||
title=loc_text("diagnostics.export.title", catalog=self._locale_catalog, default="Esporta"),
|
||||
defaultextension=".xlsx",
|
||||
filetypes=[("Excel Workbook", "*.xlsx")],
|
||||
initialfile=default_name,
|
||||
)
|
||||
if not path:
|
||||
return
|
||||
|
||||
try:
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Diagnostica"
|
||||
columns = list(self.tree["columns"])
|
||||
headers = [str(self.tree.heading(col, "text") or col) for col in columns]
|
||||
|
||||
for col_index, header in enumerate(headers, start=1):
|
||||
cell = ws.cell(row=1, column=col_index, value=header)
|
||||
cell.font = Font(bold=True)
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
|
||||
for row_index, row in enumerate(rows, start=2):
|
||||
for col_index, value in enumerate(row, start=1):
|
||||
ws.cell(row=row_index, column=col_index, value=value)
|
||||
|
||||
widths: dict[int, int] = {}
|
||||
for row in ws.iter_rows(values_only=True):
|
||||
for col_index, value in enumerate(row, start=1):
|
||||
widths[col_index] = max(widths.get(col_index, 0), len("" if value is None else str(value)))
|
||||
for col_index, width in widths.items():
|
||||
ws.column_dimensions[get_column_letter(col_index)].width = min(max(width + 2, 12), 70)
|
||||
|
||||
wb.save(path)
|
||||
messagebox.showinfo(
|
||||
loc_text("diagnostics.export.title", catalog=self._locale_catalog, default="Esporta"),
|
||||
loc_text("diagnostics.export.ok", catalog=self._locale_catalog, default="File creato:\n{path}").format(path=path),
|
||||
parent=self,
|
||||
)
|
||||
except Exception as exc:
|
||||
log_exception(__name__, exc, context="export diagnostica xlsx")
|
||||
messagebox.showerror(
|
||||
loc_text("diagnostics.export.title", catalog=self._locale_catalog, default="Esporta"),
|
||||
loc_text(
|
||||
"diagnostics.export.error",
|
||||
catalog=self._locale_catalog,
|
||||
default="Errore durante l'esportazione:\n{error}",
|
||||
).format(error=exc),
|
||||
parent=self,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
|
||||
def open_diagnostica_window(parent: tk.Misc, db_client, session=None) -> tk.Misc:
|
||||
"""Open the diagnostics window."""
|
||||
|
||||
win = DiagnosticaWindow(parent, db_client, session=session)
|
||||
place_window_fullsize_below_parent_later(parent, win)
|
||||
win.bind("<Escape>", lambda _e: win.destroy())
|
||||
return win
|
||||
235
diagnostica_scarico_celle_multiple.md
Normal file
235
diagnostica_scarico_celle_multiple.md
Normal file
@@ -0,0 +1,235 @@
|
||||
# Diagnostica Scarico Celle Multiple
|
||||
|
||||
## Contesto
|
||||
|
||||
La finestra `Scarico` aperta da `Gestione layout` serve a gestire celle fisiche che contengono piu' UDC.
|
||||
Nel database legacy non esisteva un vincolo rigido `una cella = una UDC`, quindi una cella rossa puo' contenere:
|
||||
|
||||
- UDC realmente compresenti nella stessa cella;
|
||||
- UDC rimaste in cella anche se appartenenti a picking list gia' chiuse/spedite.
|
||||
|
||||
L'obiettivo della diagnostica non e' ricostruire tutta la storia della UDC, ma aiutare l'operatore a capire quali righe scaricare come spedite.
|
||||
|
||||
## Fonti Dati
|
||||
|
||||
La griglia della dialog parte dalla giacenza corrente:
|
||||
|
||||
```sql
|
||||
dbo.XMag_GiacenzaPallet
|
||||
```
|
||||
|
||||
Questa vista indica quali UDC risultano presenti nella cella aperta dal layout.
|
||||
|
||||
La diagnostica controlla anche:
|
||||
|
||||
```sql
|
||||
dbo.XMag_GiacenzaPalletPlistChiuse
|
||||
```
|
||||
|
||||
Questa vista non e' uno storico documentale puro. E' una vista ibrida che incrocia la giacenza corrente con i documenti SAM chiusi.
|
||||
In pratica serve a individuare UDC ancora presenti in una cella fisica, ma appartenenti a una picking list/documento gia' chiuso.
|
||||
|
||||
## Conclusione Operativa
|
||||
|
||||
Per una cella fisica aperta da `Gestione layout`, i casi realmente utili sono solo due.
|
||||
|
||||
### 1. Nessuna Diagnostica
|
||||
|
||||
La UDC e' presente nella cella multipla e non compare in `XMag_GiacenzaPalletPlistChiuse`.
|
||||
|
||||
Significato:
|
||||
|
||||
```text
|
||||
UDC normalmente presente in cella.
|
||||
```
|
||||
|
||||
Non viene mostrato nessun messaggio nella colonna diagnostica.
|
||||
|
||||
### 2. Spedita Ma Non Scaricata Dalla Cella
|
||||
|
||||
La UDC e' presente nella cella fisica aperta, ma compare anche in `XMag_GiacenzaPalletPlistChiuse`.
|
||||
|
||||
Diagnostica mostrata:
|
||||
|
||||
```text
|
||||
Motivo: spedita ma non scaricata dalla cella
|
||||
```
|
||||
|
||||
Significato:
|
||||
|
||||
```text
|
||||
La UDC appartiene a una picking list chiusa, ma non e' stata scaricata dalla cella fisica.
|
||||
```
|
||||
|
||||
Operativamente questa UDC va selezionata e scaricata come spedita, quindi verso la cella virtuale:
|
||||
|
||||
```text
|
||||
7G.1.1 / IDCella 9999 / barcode cella 9000000
|
||||
```
|
||||
|
||||
## Casi Teorici Scartati Dalla Dialog
|
||||
|
||||
Durante l'analisi erano stati ipotizzati altri casi, ma sono stati esclusi dalla diagnostica della dialog per non confondere l'operatore.
|
||||
|
||||
### UDC Gia' In 7G.1.1
|
||||
|
||||
Se una UDC risulta davvero in `IDCella = 9999`, normalmente non dovrebbe comparire nella cella fisica aperta dal layout.
|
||||
Se accadesse, sarebbe un'incoerenza tra viste o dati non sincronizzati.
|
||||
|
||||
Per questo la dialog di scarico da layout fisico non mostra piu' il messaggio:
|
||||
|
||||
```text
|
||||
Motivo: spedita
|
||||
```
|
||||
|
||||
### UDC In Picking List Chiusa Ma Non Spedita
|
||||
|
||||
Questo caso e' teoricamente possibile ma raro e ambiguo nel modello dati attuale.
|
||||
Le viste disponibili non forniscono una distinzione documentale/storica abbastanza pulita da renderlo utile in questa dialog operativa.
|
||||
|
||||
Per questo la dialog non mostra piu':
|
||||
|
||||
```text
|
||||
Motivo: in plist chiusa, non spedita e non scaricata dalla cella
|
||||
```
|
||||
|
||||
Eventuali analisi piu' profonde vanno fatte nelle finestre di storico, non nella dialog rapida di scarico.
|
||||
|
||||
## Regola Finale Implementata
|
||||
|
||||
La diagnostica della dialog `Scarico` e' volutamente semplice:
|
||||
|
||||
```text
|
||||
se UDC in XMag_GiacenzaPalletPlistChiuse:
|
||||
"Motivo: spedita ma non scaricata dalla cella"
|
||||
altrimenti:
|
||||
diagnostica vuota
|
||||
```
|
||||
|
||||
Questa scelta riduce il rischio di falsi positivi e mantiene chiaro il comportamento per l'operatore.
|
||||
|
||||
## Aggiornamento 04/07/2026 - Barcode Picking List
|
||||
|
||||
Durante i test sul barcode sono state introdotte alcune modifiche operative collegate alla gestione delle picking list, agli skip UDC e alla ripresa del lavoro dopo movimenti liberi.
|
||||
|
||||
### Anti Autosubmit Su Cambio Lista
|
||||
|
||||
Problema osservato:
|
||||
|
||||
```text
|
||||
passando rapidamente da una picking list prenotata a una non prenotata,
|
||||
il barcode poteva considerare come lettura valida un valore gia' presente nel campo Pallet
|
||||
e scaricare automaticamente una UDC della nuova lista.
|
||||
```
|
||||
|
||||
Correzione implementata:
|
||||
|
||||
```text
|
||||
lo scarico automatico in picking list parte solo se il campo Pallet e' stato modificato
|
||||
dall'operatore dopo il caricamento della UDC proposta.
|
||||
```
|
||||
|
||||
In pratica, quando il programma carica una nuova UDC attesa, il valore visualizzato non puo' piu' generare da solo lo scarico. Serve una nuova lettura o digitazione effettiva.
|
||||
|
||||
### Skip UDC In Picking List
|
||||
|
||||
Durante l'evasione di una picking list, il tasto F4 assume il significato:
|
||||
|
||||
```text
|
||||
[F4] Salta UDC
|
||||
```
|
||||
|
||||
La UDC saltata viene registrata nella tabella:
|
||||
|
||||
```sql
|
||||
dbo.py_BarcodePickingListSkip
|
||||
```
|
||||
|
||||
Le righe aperte hanno:
|
||||
|
||||
```text
|
||||
Risolto = 0
|
||||
```
|
||||
|
||||
La query del barcode esclude le UDC saltate aperte, quindi la lista puo' proseguire sulle UDC successive senza chiudere definitivamente quelle non trovate.
|
||||
|
||||
### Fine Lista Con UDC Saltate
|
||||
|
||||
Quando una picking list non ha piu' UDC immediatamente lavorabili, ma contiene una o piu' UDC saltate, il barcode:
|
||||
|
||||
```text
|
||||
non chiude la picking list;
|
||||
rilascia la prenotazione;
|
||||
lascia la lista riprenotabile;
|
||||
mostra un messaggio di sospensione con numero UDC saltate.
|
||||
```
|
||||
|
||||
La lista resta quindi aperta e potra' essere ripresa in un secondo momento.
|
||||
|
||||
### Riprenotazione E Ripresa UDC Saltate
|
||||
|
||||
Quando la picking list viene riprenotata, gli skip aperti del documento vengono marcati come risolti:
|
||||
|
||||
```sql
|
||||
UPDATE dbo.py_BarcodePickingListSkip
|
||||
SET Risolto = 1,
|
||||
RisoltoDa = <operatore>,
|
||||
RisoltoDataOra = SYSDATETIME()
|
||||
WHERE Documento = <documento>
|
||||
AND Risolto = 0;
|
||||
```
|
||||
|
||||
Questo permette al barcode di riproporre le UDC saltate rimaste da evadere.
|
||||
|
||||
### Posizione UDC Dopo Movimenti Liberi
|
||||
|
||||
Una UDC saltata puo' essere movimentata in pausa tramite operazioni libere, ad esempio:
|
||||
|
||||
```text
|
||||
versamento in una nuova cella fisica;
|
||||
dissociazione verso 9001000 / Non scaffalata.
|
||||
```
|
||||
|
||||
Alla ripresa della picking list, la posizione mostrata dal barcode riflette la giacenza corrente, perche' la vista operativa deriva `Cella` e `Ubicazione` da:
|
||||
|
||||
```sql
|
||||
dbo.XMag_GiacenzaPallet
|
||||
```
|
||||
|
||||
Quindi una UDC prima saltata e poi spostata verra' proposta con la nuova cella, oppure come:
|
||||
|
||||
```text
|
||||
Non scaffalata
|
||||
```
|
||||
|
||||
se e' stata dissociata verso la locazione virtuale `9001000`.
|
||||
|
||||
### Regola Conservata
|
||||
|
||||
Resta confermata la regola operativa:
|
||||
|
||||
```text
|
||||
una UDC diventa Spedita / 7G.1.1 / 9000000 solo nel flusso picking list.
|
||||
```
|
||||
|
||||
Le operazioni libere non spediscono una UDC. Possono solo versarla in una cella fisica oppure metterla in `9001000 / Non scaffalata`.
|
||||
|
||||
### File Coinvolti
|
||||
|
||||
Le modifiche principali sono nei moduli:
|
||||
|
||||
```text
|
||||
barcode_client.py
|
||||
barcode_repository.py
|
||||
barcode_service.py
|
||||
prenota_sprenota_sql.py
|
||||
version_info.py
|
||||
```
|
||||
|
||||
La patch DB cumulativa da usare sul database online e':
|
||||
|
||||
```text
|
||||
apply_online_python_wms_full_patch.sql
|
||||
```
|
||||
|
||||
La patch contiene gli oggetti SQL necessari al ramo Python e puo' essere eseguita una sola volta da SSMS.
|
||||
107
docs/aggiornamento_monolista_bat.md
Normal file
107
docs/aggiornamento_monolista_bat.md
Normal file
@@ -0,0 +1,107 @@
|
||||
# Aggiornare un desktop di reparto con il file BAT
|
||||
|
||||
Il file `aggiorna_monolista.bat` si esegue SUL COMPUTER DA AGGIORNARE, anche da
|
||||
una sessione Desktop Remoto. Non e' un comando che aggiorna tutti i PC da solo.
|
||||
Prima deve essere riuscito il push del PC di sviluppo su Gitea: lo script puo'
|
||||
scaricare solo cio' che e' effettivamente online.
|
||||
|
||||
## Avvio
|
||||
|
||||
Chiudere applicazione desktop e barcode in tutte le sessioni che usano la stessa
|
||||
cartella. Non e' normalmente necessario eseguire come amministratore: l'utente
|
||||
deve avere i permessi sulla cartella e sull'ambiente Python utilizzato.
|
||||
|
||||
Per la cartella standard `C:\flywms`, doppio clic sul BAT, oppure dal prompt CMD:
|
||||
|
||||
```bat
|
||||
aggiorna_monolista.bat
|
||||
```
|
||||
|
||||
Per scegliere cartella e interprete (lo stesso usato dal collegamento dell'app):
|
||||
|
||||
```bat
|
||||
aggiorna_monolista.bat "C:\flywms" "C:\Python314\python.exe"
|
||||
```
|
||||
|
||||
Se non si indica l'interprete, cerca prima `.venv\Scripts\python.exe` nella
|
||||
cartella dell'applicazione, poi `python` nel PATH. Usare python.exe, non pythonw.exe,
|
||||
per vedere gli errori di installazione. Lo script mostra la versione Python e pip.
|
||||
|
||||
## Comportamento
|
||||
|
||||
1. Chiede conferma che le applicazioni siano chiuse; non uccide processi.
|
||||
2. Controlla clone Git, URL origin, Python/pip e assenza di modifiche ai file tracciati.
|
||||
3. Scarica main da Gitea e verifica che non contenga db_connection.json.
|
||||
4. Si ferma se HEAD o il main locale hanno commit non contenuti nel main remoto.
|
||||
5. Salva un riferimento locale alla versione precedente, passa a main e aggiorna
|
||||
con fast-forward, senza merge automatici di codice o reset distruttivi.
|
||||
6. Esegue `python -m pip install -r requirements.txt` nell'interprete selezionato.
|
||||
7. Mostra il commit installato; solo in caso di successo si puo' riaprire l'app.
|
||||
|
||||
Il BAT gira da una copia in TEMP per non essere interrotto se Git aggiorna il BAT
|
||||
stesso. Non cancella log, ZIP, configurazioni o altri file non tracciati. Se un file
|
||||
non tracciato impedisce il checkout, Git interrompe l'operazione anziche' sovrascriverlo.
|
||||
Non esegue alcuna patch SQL. Le modifiche del 22 ottobre (svuotamento corsie e
|
||||
ricerca UDC nello storico) non richiedono nuove patch SQL.
|
||||
|
||||
## Errori e ripristino
|
||||
|
||||
- Autenticazione: servono credenziali/token Git validi sul PC di reparto; il BAT
|
||||
non contiene password e non modifica le credenziali memorizzate.
|
||||
- Modifiche locali: il BAT si ferma. Non usare reset/clean alla cieca.
|
||||
- Installazione da ZIP: occorre prima predisporre un clone Git, separatamente.
|
||||
- Pip fallito: i sorgenti possono essere gia' aggiornati; risolvere l'errore prima
|
||||
di riavviare. Il BAT non promette un rollback automatico dell'ambiente Python.
|
||||
|
||||
La finestra mostra il comando per recuperare i sorgenti precedenti:
|
||||
|
||||
```bat
|
||||
git switch --detach refs/warehouse-backups/pre-update-DATA-ORA
|
||||
```
|
||||
|
||||
Usare il riferimento esatto stampato dal BAT. Per ritrovarlo:
|
||||
|
||||
```bat
|
||||
git for-each-ref --sort=-refname --format="%(refname) %(objectname:short)" refs/warehouse-backups/
|
||||
```
|
||||
|
||||
Il ripristino riguarda esclusivamente i file Git: non annulla movimenti sul DB,
|
||||
patch SQL, configurazioni locali o aggiornamenti dei pacchetti Python. La copia
|
||||
locale db_connection.json non viene caricata da Gitea e rimane quella del reparto.
|
||||
|
||||
Il codice di uscita e' 0 per successo, 1 per errore, 2 per annullamento.
|
||||
|
||||
## Errore Unlink su .git/objects/pack/*.idx
|
||||
|
||||
Durante fetch Git puo' lanciare automaticamente manutenzione/ricompattazione.
|
||||
Su Windows questa puo' fallire quando un vecchio indice pack e' bloccato da un
|
||||
processo o non puo' essere eliminato per motivi di permessi. Il messaggio da solo
|
||||
non identifica chi blocca il file. Non cancellare manualmente file .idx o .pack.
|
||||
|
||||
Il BAT disabilita la manutenzione automatica SOLO per fetch e merge, tramite
|
||||
`git -c maintenance.auto=false -c gc.auto=0 ...`. Non modifica la configurazione
|
||||
permanente di Git e non arresta eventuali manutenzioni gia' in corso o pianificate.
|
||||
Non risolve permessi mancanti o blocchi che impediscono la normale scrittura Git.
|
||||
|
||||
Per recuperare il nuovo BAT mentre si dispone ancora di quello precedente, dopo
|
||||
aver terminato l'operazione Git precedente, dal prompt CMD:
|
||||
|
||||
```bat
|
||||
cd /d C:\flywms
|
||||
git -c maintenance.auto=false -c gc.auto=0 fetch origin refs/heads/main
|
||||
```
|
||||
|
||||
Solo se fetch ha successo, estrarre il BAT in una cartella esterna gia' esistente:
|
||||
|
||||
```bat
|
||||
git show FETCH_HEAD:aggiorna_monolista.bat > C:\tmp\aggiorna_monolista_nuovo.bat
|
||||
```
|
||||
|
||||
Solo se anche questo comando ha successo:
|
||||
|
||||
```bat
|
||||
C:\tmp\aggiorna_monolista_nuovo.bat C:\flywms C:\Python314\python.exe
|
||||
```
|
||||
|
||||
Questa procedura non modifica singolarmente il BAT tracciato nella cartella
|
||||
installata (che altrimenti risulterebbe modificato e bloccherebbe i controlli).
|
||||
74
docs/finestre_errori.md
Normal file
74
docs/finestre_errori.md
Normal file
@@ -0,0 +1,74 @@
|
||||
# Finestre di errore unificate
|
||||
|
||||
## Modifica del 23 ottobre 2026
|
||||
|
||||
I dialoghi di errore del programma monolista, desktop e barcode, usano ora
|
||||
`error_dialog.py`, invece della messagebox nativa di Tkinter. Il testo non viene
|
||||
riassunto, accorciato o ridotto di dimensione per farlo entrare nello schermo.
|
||||
|
||||
La finestra offre:
|
||||
|
||||
- Ridimensionamento e scorrimento verticale e orizzontale.
|
||||
- Selezione del testo con il mouse, Ctrl+A e Ctrl+C.
|
||||
- Pulsante **Copia tutto**, per copiare l'intero report, anche fuori dalla vista.
|
||||
- Pulsante **Salva su file**, con scelta del percorso e formato TXT UTF-8.
|
||||
- Pulsante **Chiudi**, tasto Esc e chiusura dalla barra del titolo.
|
||||
|
||||
Su terminali piccoli i pulsanti vengono disposti in colonna. La dimensione
|
||||
iniziale tiene conto della risoluzione. Tema e testi sono definiti in
|
||||
`ui_theme.json` e `locale.json` (IT/ENG).
|
||||
|
||||
## Contenuto e integrazione
|
||||
|
||||
Il report conserva il messaggio originale, data/ora con fuso orario, versione
|
||||
applicativa e Python, e, quando fornita, l'eccezione originale con traceback e
|
||||
catena delle cause. Sono aggiunti gli attributi SQL `statement` e `params` per
|
||||
evitare le abbreviazioni della rappresentazione standard di SQLAlchemy.
|
||||
La finestra chiamante, quando indicata, contribuisce con il proprio titolo e
|
||||
la versione visibile. Una segnalazione di validazione senza eccezione conserva
|
||||
il messaggio, senza inventare uno stack di errore.
|
||||
|
||||
I callback asincroni passano esplicitamente `exception=exc`: convertire prima
|
||||
l'errore in stringa farebbe perdere il traceback. Nel barcode, se falliscono
|
||||
sia l'operazione sia la verifica del suo esito, il report contiene entrambe le
|
||||
eccezioni. La logica di verifica, le transazioni e i movimenti non cambiano.
|
||||
|
||||
Sono stati collegati inventario, diagnostica, layout, gestione e storico picking
|
||||
list, storico UDC, ricerca, UDC non scaffalate/multiple, scarico, reset corsie,
|
||||
sequenza di prelievo, autenticazione, configurazione DB, barcode, errori dei
|
||||
callback Tk e messaggi di avvio gestiti da `runtime_support`.
|
||||
|
||||
Informazioni, avvisi e conferme continuano a usare i dialoghi nativi: in
|
||||
particolare non cambiano le risposte Si/No delle operazioni di magazzino.
|
||||
Non viene applicata alcuna modifica globale alla libreria Tkinter: i moduli
|
||||
importano esplicitamente il componente condiviso.
|
||||
|
||||
Il dialogo e' modale come la precedente messagebox. Alla chiusura ripristina
|
||||
l'eventuale precedente finestra modale e il focus. Va chiamato sul thread Tk;
|
||||
non apre finestre direttamente dai thread di lavoro. Gli errori di background
|
||||
non destinati alla UI continuano a essere gestiti dai log esistenti.
|
||||
|
||||
Il salvataggio e' manuale, non sostituisce il logging gia' presente. Se viene
|
||||
annullato non scrive nulla; se fallisce, la finestra rimane aperta e indica
|
||||
l'errore. Copia e salvataggio usano lo stesso testo immutabile visualizzato.
|
||||
I report possono contenere parametri SQL e dati aziendali: conservarli e
|
||||
condividerli solo con personale autorizzato.
|
||||
|
||||
## Estensione email futura
|
||||
|
||||
Non viene inviata posta e non e' presente un pulsante non funzionante.
|
||||
Il report separato dalla visualizzazione potra' diventare l'allegato di un
|
||||
futuro pulsante **Invia al manutentore**, previa configurazione del destinatario,
|
||||
del servizio di invio e conferma dell'operatore. L'invio dovra' essere asincrono.
|
||||
|
||||
## Verifica e installazione
|
||||
|
||||
I test usano eccezioni sintetiche e widget Tk reali, senza operazioni sul DB:
|
||||
report lunghi, traceback e parametri, scroll, copia integrale/selezione,
|
||||
salvataggio UTF-8, annullamento/errori di salvataggio, schermi piccoli,
|
||||
ripristino della modalita' modale, errori asincroni e recupero barcode.
|
||||
|
||||
Non occorrono patch SQL o nuove dipendenze. Aggiornare anche il nuovo modulo,
|
||||
il catalogo delle lingue, il tema e `version_info.py`, non solo `inventario.py`.
|
||||
Questa modifica migliora la consultazione degli errori: non risolve da sola
|
||||
il lock timeout SQL 1222 rilevato nell'inventario.
|
||||
44
docs/review/README.md
Normal file
44
docs/review/README.md
Normal file
@@ -0,0 +1,44 @@
|
||||
# Documentazione review Warehouse / FlyWMS bridge
|
||||
|
||||
Questa cartella contiene la documentazione tecnica destinata alla review del codice Python e SQL.
|
||||
|
||||
## Obiettivi
|
||||
|
||||
- Descrivere il processo logico implementato da ogni modulo.
|
||||
- Documentare firme, parametri, ritorni e responsabilita' di funzioni e classi.
|
||||
- Documentare SQL, viste, stored procedure, tabelle coinvolte ed effetti collaterali.
|
||||
- Aggiungere commenti inline nel codice solo dove il comportamento non e' auto-evidente.
|
||||
|
||||
## Criterio di documentazione
|
||||
|
||||
La documentazione e' divisa in tre livelli.
|
||||
|
||||
1. Processo logico: flussi operativi, eventi UI, query, effetti sul database.
|
||||
2. API interna: classi, funzioni, parametri, valori di ritorno, errori, dipendenze.
|
||||
3. Dettaglio implementativo: strutture dati, cicli, dedupliche, transazioni, side effect.
|
||||
|
||||
## Ambito escluso
|
||||
|
||||
Questa review non considera:
|
||||
|
||||
- `__pycache__`
|
||||
- log applicativi
|
||||
- zip di distribuzione
|
||||
- cartelle `_package_*`
|
||||
- cartella `trash`
|
||||
- build HTML generata in `docs/_build`
|
||||
|
||||
## Primo lotto documentato
|
||||
|
||||
- [Modulo storico picking list](module_storico_pickinglist.md)
|
||||
- [SQL storico picking list](sql_storico_pickinglist.md)
|
||||
- [Modulo gestione picking list](module_gestione_pickinglist.md)
|
||||
- [Modulo prenota/sprenota SQL](module_prenota_sprenota_sql.md)
|
||||
- [SQL prenotazione picking list](sql_pickinglist_reservation.md)
|
||||
|
||||
## Prossimi lotti consigliati
|
||||
|
||||
1. `gestione_scarico.py`
|
||||
2. `barcode_service.py` e `barcode_repository.py`
|
||||
3. `main.py`, `login_window.py`, `db_config.py`
|
||||
4. Moduli di visualizzazione: `gestione_layout.py`, `reset_corsie.py`, `search_pallets.py`, `view_celle_multi_udc.py`
|
||||
68
docs/review/barcode_error_handling.md
Normal file
68
docs/review/barcode_error_handling.md
Normal file
@@ -0,0 +1,68 @@
|
||||
# Barcode: logging errori e transazioni
|
||||
|
||||
## Problema rilevato
|
||||
|
||||
Durante uno scarico picking list dal lettore barcode, l'operazione DB e' arrivata a buon fine ma il client ha mostrato un'eccezione. I file standard output/error erano vuoti.
|
||||
|
||||
Con `pythonw` non e' sufficiente affidarsi a stdout/stderr: eccezioni Tk, future asincrone o callback possono non arrivare al wrapper principale.
|
||||
|
||||
## Strategia adottata
|
||||
|
||||
Il client barcode ora registra errori in modo esplicito su `warehouse_fatal.log` e su `barcode_wms_launch.log`.
|
||||
|
||||
Canali coperti:
|
||||
|
||||
- `sys.excepthook`
|
||||
- `threading.excepthook`
|
||||
- `Tk.report_callback_exception`
|
||||
- exception handler del loop `asyncio`
|
||||
- eccezioni delle operazioni asincrone barcode
|
||||
- errori del repository durante movimento DB
|
||||
- errori post-movimento durante ricostruzione stato UI
|
||||
|
||||
## Transazione movimento DB
|
||||
|
||||
Il movimento barcode passa da `BarcodeRepository.execute_legacy_move`.
|
||||
|
||||
La batch SQL usa:
|
||||
|
||||
```sql
|
||||
SET XACT_ABORT ON;
|
||||
```
|
||||
|
||||
ed e' eseguita con:
|
||||
|
||||
```python
|
||||
query_json(..., commit=True)
|
||||
```
|
||||
|
||||
Questo significa:
|
||||
|
||||
- successo: commit;
|
||||
- eccezione SQL/Python: rollback automatico della transazione SQLAlchemy;
|
||||
- il valore `@RC` restituito dalla stored legacy non viene interpretato come errore.
|
||||
|
||||
Nota importante: in `sp_xMagGestioneMagazziniPallet`, quando il movimento va a buon fine, `@RC` viene valorizzato con `@@IDENTITY`, cioe' con l'identificativo del movimento inserito. Quindi un valore diverso da zero e' compatibile con un movimento riuscito e non deve causare rollback.
|
||||
|
||||
## Distinzione tra movimento e refresh UI
|
||||
|
||||
Dopo un movimento riuscito, il service ricostruisce il messaggio UI interrogando picking list e tracciabilita'.
|
||||
|
||||
Se questa fase post-movimento fallisce:
|
||||
|
||||
- il movimento resta valido;
|
||||
- l'errore viene loggato;
|
||||
- l'utente vede `Movimento eseguito. Dettagli non aggiornati.`;
|
||||
- non viene mostrato il messaggio "transazione non completata".
|
||||
|
||||
Se invece fallisce la transazione vera:
|
||||
|
||||
- l'utente vede `Transazione non completata, ripeti l'operazione.`;
|
||||
- il dettaglio tecnico viene scritto nel log.
|
||||
|
||||
## File principali
|
||||
|
||||
- `runtime_support.py`
|
||||
- `barcode_client.py`
|
||||
- `barcode_repository.py`
|
||||
- `barcode_service.py`
|
||||
119
docs/review/documentation_plan.md
Normal file
119
docs/review/documentation_plan.md
Normal file
@@ -0,0 +1,119 @@
|
||||
# Piano operativo documentazione review
|
||||
|
||||
## Strategia
|
||||
|
||||
La documentazione viene prodotta per lotti piccoli e verificabili. Ogni lotto deve contenere:
|
||||
|
||||
- descrizione del processo logico;
|
||||
- tabella firme funzioni/classi;
|
||||
- documentazione SQL collegata;
|
||||
- eventuali commenti inline mirati;
|
||||
- compilazione Python dei moduli modificati.
|
||||
|
||||
## Lotto 1 - Storico picking list
|
||||
|
||||
Stato: completato.
|
||||
|
||||
File documentati:
|
||||
|
||||
- `storico_pickinglist.py`
|
||||
- `apply_python_pickinglist_history_views.sql`
|
||||
- `apply_online_history_forms_patch.sql`
|
||||
- query runtime `SQL_STORICO_PL`
|
||||
- query runtime `SQL_STORICO_PL_DETAILS`
|
||||
- movimento collegato `move_pallet_async`
|
||||
|
||||
Motivo priorita:
|
||||
|
||||
- contiene una nuova funzione con effetti sul database;
|
||||
- gestisce casi critici `Chiusa ERP con residui`;
|
||||
- usa convenzioni operative `1000 / Non scaff.` e `9999 / 7G.1.1`.
|
||||
|
||||
## Lotto 2 - Gestione picking list
|
||||
|
||||
Stato: completato.
|
||||
|
||||
File target:
|
||||
|
||||
- `gestione_pickinglist.py`
|
||||
- `prenota_sprenota_sql.py`
|
||||
- `apply_python_parallel_pickinglist_patch.sql`
|
||||
- `rollback_python_parallel_pickinglist_patch.sql`
|
||||
|
||||
Aspetti da documentare:
|
||||
|
||||
- prenotazione/sprenotazione Python-only;
|
||||
- differenza tra vista residua e vista storica;
|
||||
- aggiornamento griglia alta/bassa;
|
||||
- stato `IDStato`;
|
||||
- separazione da C# legacy;
|
||||
- limiti concorrenza.
|
||||
|
||||
## Lotto 3 - Movimento UDC e scarico
|
||||
|
||||
File target:
|
||||
|
||||
- `gestione_scarico.py`
|
||||
- `storico_udc.py`
|
||||
|
||||
Aspetti da documentare:
|
||||
|
||||
- batch `SQL_SCARICA_UDC`;
|
||||
- movimento `P` e `V`;
|
||||
- audit utenti/date;
|
||||
- cella source e target;
|
||||
- fallback SPED in storico UDC.
|
||||
|
||||
## Lotto 4 - Barcode
|
||||
|
||||
File target:
|
||||
|
||||
- `barcode_client.py`
|
||||
- `barcode_service.py`
|
||||
- `barcode_repository.py`
|
||||
|
||||
Aspetti da documentare:
|
||||
|
||||
- stati operativi del barcode;
|
||||
- F1/F2 e priorita picking list;
|
||||
- gestione `9000000`;
|
||||
- mappatura 1:1 con comportamento C#;
|
||||
- stabilita di connessione DB.
|
||||
|
||||
## Lotto 5 - Avvio, autenticazione e configurazione
|
||||
|
||||
File target:
|
||||
|
||||
- `main.py`
|
||||
- `login_window.py`
|
||||
- `db_config.py`
|
||||
- `runtime_support.py`
|
||||
- `user_session.py`
|
||||
|
||||
Aspetti da documentare:
|
||||
|
||||
- single instance;
|
||||
- login operatore;
|
||||
- creazione configurazione DB;
|
||||
- gestione errori in `pythonw`;
|
||||
- shutdown ordinato.
|
||||
|
||||
## Lotto 6 - Visualizzazioni operative
|
||||
|
||||
File target:
|
||||
|
||||
- `gestione_layout.py`
|
||||
- `reset_corsie.py`
|
||||
- `search_pallets.py`
|
||||
- `view_celle_multi_udc.py`
|
||||
- `ui_tables.py`
|
||||
- `ui_theme.py`
|
||||
|
||||
Aspetti da documentare:
|
||||
|
||||
- griglie e layout;
|
||||
- query diagnostiche;
|
||||
- overlay async;
|
||||
- colori semantici;
|
||||
- export XLSX;
|
||||
- bonifica UDC fantasma.
|
||||
154
docs/review/module_gestione_pickinglist.md
Normal file
154
docs/review/module_gestione_pickinglist.md
Normal file
@@ -0,0 +1,154 @@
|
||||
# Modulo `gestione_pickinglist.py`
|
||||
|
||||
## Scopo
|
||||
|
||||
Il modulo implementa la finestra operativa "Gestione Picking List". La finestra serve al backoffice/magazzino per:
|
||||
|
||||
- visualizzare le picking list ancora lavorabili;
|
||||
- selezionare una sola lista alla volta;
|
||||
- visualizzare le UDC residue della lista selezionata;
|
||||
- prenotare una lista per darle priorita' alta sul barcode;
|
||||
- s-prenotare la lista correntemente prenotata;
|
||||
- mantenere UI reattiva tramite query asincrone, overlay e spinner.
|
||||
|
||||
La finestra lavora sulla vista residuale `dbo.py_ViewPackingListRestante`, quindi mostra cio' che resta da scaricare, non necessariamente il documento ERP completo. Il documento completo e' invece esposto dalla form "Storico Picking List".
|
||||
|
||||
## Processo logico
|
||||
|
||||
### Apertura finestra
|
||||
|
||||
1. `open_pickinglist_window` crea o riporta in primo piano una singola finestra.
|
||||
2. La finestra viene inizialmente nascosta con `withdraw` e alpha `0.0`.
|
||||
3. Viene creato `GestionePickingListFrame`.
|
||||
4. Dopo la stabilizzazione layout, `_first_show` avvia il primo caricamento.
|
||||
5. La finestra viene mostrata solo quando il layout e' pronto, riducendo flicker.
|
||||
|
||||
### Caricamento lista alta
|
||||
|
||||
1. `reload_from_db` esegue `SQL_PL`.
|
||||
2. `SQL_PL` legge da `dbo.py_ViewPackingListRestante`.
|
||||
3. Il risultato viene normalizzato con `_rows_to_dicts`.
|
||||
4. `_refresh_mid_rows` ricrea la tabella alta.
|
||||
5. Ogni riga e' rappresentata da un `PLRow`, che incapsula dizionario dati e checkbox.
|
||||
|
||||
### Selezione lista
|
||||
|
||||
1. Il click sul checkbox chiama `on_row_checked`.
|
||||
2. La selezione e' esclusiva: eventuali altre righe selezionate vengono deselezionate.
|
||||
3. Il documento selezionato viene salvato in `detail_doc`.
|
||||
4. Viene eseguita `SQL_PL_DETAILS`.
|
||||
5. Il dettaglio viene messo in cache in `_detail_cache`.
|
||||
6. `_refresh_details_incremental` ordina e renderizza il dettaglio con `tksheet`.
|
||||
|
||||
### Ricarica
|
||||
|
||||
`reload_from_db` preserva il documento selezionato quando possibile. Questo e' importante per il caso operativo in cui il barcode sta scaricando UDC mentre l'operatore aggiorna la finestra.
|
||||
|
||||
Flusso:
|
||||
|
||||
1. `_selected_documento_for_reload` determina il documento da mantenere.
|
||||
2. La griglia alta viene ricaricata.
|
||||
3. `_reselect_documento_after_reload` riseleziona la stessa lista se ancora presente.
|
||||
4. Il dettaglio viene ricaricato dalla vista residuale.
|
||||
|
||||
### Prenotazione
|
||||
|
||||
1. `on_prenota` verifica il permesso `pickinglist.prenota`.
|
||||
2. Richiede una riga selezionata.
|
||||
3. Se `IDStato == 1`, l'operazione e' no-op.
|
||||
4. Verifica sessione operatore valida.
|
||||
5. Chiama `sp_xExePackingListPallet_async(..., Azione="P")`.
|
||||
6. Se `rc == 0`, logga audit e ricarica la griglia mantenendo il documento.
|
||||
|
||||
### S-prenotazione
|
||||
|
||||
1. `on_sprenota` verifica il permesso `pickinglist.sprenota`.
|
||||
2. Richiede una riga selezionata.
|
||||
3. Se `IDStato == 0`, l'operazione e' no-op.
|
||||
4. Chiama `sp_xExePackingListPallet_async(..., Azione="S")`.
|
||||
5. Se `rc == 0`, logga audit e ricarica.
|
||||
|
||||
## Semantica operativa
|
||||
|
||||
La UI non implementa toggle implicito. I pulsanti hanno semantica esplicita:
|
||||
|
||||
| Pulsante | Effetto |
|
||||
| --- | --- |
|
||||
| `Prenota` | porta la lista selezionata a priorita' alta se non gia' prenotata |
|
||||
| `S-prenota` | libera la lista selezionata se e' la lista attiva |
|
||||
|
||||
Premere piu' volte `Prenota` sulla stessa lista gia' prenotata non la libera. Premere piu' volte `S-prenota` su lista non prenotata non la prenota.
|
||||
|
||||
## Strutture dati principali
|
||||
|
||||
| Nome | Tipo | Ruolo |
|
||||
| --- | --- | --- |
|
||||
| `rows_models` | `list[PLRow]` | modelli riga della griglia alta |
|
||||
| `_detail_cache` | `dict[Any, list]` | cache righe dettaglio per documento |
|
||||
| `detail_doc` | `Any` | documento correntemente selezionato |
|
||||
| `_detail_sort_key` | `str | None` | colonna dettaglio ordinata |
|
||||
| `_detail_sort_reverse` | `bool` | verso ordinamento dettaglio |
|
||||
| `pl_table` | `ScrollTable` | tabella custom griglia alta |
|
||||
| `detail_sheet` | `tksheet.Sheet` | griglia dettaglio ad alto volume |
|
||||
| `spinner` | `ToolbarSpinner` | feedback leggero toolbar |
|
||||
| `busy` | `InlineBusyOverlay` | overlay query/operazioni lente |
|
||||
|
||||
## Funzioni e classi principali
|
||||
|
||||
| Oggetto | Firma | Ruolo |
|
||||
| --- | --- | --- |
|
||||
| `_rows_to_dicts` | `_rows_to_dicts(res: Dict[str, Any]) -> List[Dict[str, Any]]` | normalizza payload DB |
|
||||
| `_s` | `_s(v) -> str` | converte `None` in stringa vuota |
|
||||
| `_first` | `_first(d: Dict[str, Any], keys: List[str], default: str = "")` | estrae il primo campo valorizzato |
|
||||
| `ColSpec` | `dataclass(title, key, width, anchor)` | descrive una colonna tabellare |
|
||||
| `ToolbarSpinner` | classe | animazione leggera toolbar |
|
||||
| `ScrollTable` | classe | tabella custom per griglia alta |
|
||||
| `PLRow` | classe | modello riga PL + checkbox |
|
||||
| `GestionePickingListFrame` | classe | frame principale |
|
||||
| `_build_detail_sheet` | `_build_detail_sheet(self)` | crea tksheet dettaglio |
|
||||
| `_detail_rows_to_sheet_data` | `_detail_rows_to_sheet_data(self, rows)` | converte righe DB in righe tksheet |
|
||||
| `_load_detail_sheet_data` | `_load_detail_sheet_data(self, data)` | applica headers, dati e zebra |
|
||||
| `_refresh_mid_rows` | `_refresh_mid_rows(self, rows)` | ricrea griglia alta |
|
||||
| `_get_selected_model` | `_get_selected_model(self) -> Optional[PLRow]` | ritorna riga selezionata |
|
||||
| `on_row_checked` | `on_row_checked(self, model: PLRow, is_checked: bool)` | carica dettaglio della lista |
|
||||
| `reload_from_db` | `reload_from_db(self, first=False, reselect_documento=None)` | aggiorna griglia alta |
|
||||
| `_refresh_details` | `_refresh_details(self)` | ridisegna dettaglio da cache |
|
||||
| `_refresh_details_incremental` | `_refresh_details_incremental(self, batch_size=25)` | render dettaglio con overlay |
|
||||
| `on_prenota` | `on_prenota(self)` | prenota lista selezionata |
|
||||
| `on_sprenota` | `on_sprenota(self)` | s-prenota lista selezionata |
|
||||
| `create_frame` | `create_frame(parent, *, db_client=None, conn_str=None, session=None)` | factory frame |
|
||||
| `open_pickinglist_window` | `open_pickinglist_window(parent, db_client, session=None) -> tk.Misc` | entry point finestra |
|
||||
|
||||
## Query runtime
|
||||
|
||||
### `SQL_PL`
|
||||
|
||||
Aggrega `dbo.py_ViewPackingListRestante` per documento. Conta UDC con:
|
||||
|
||||
```sql
|
||||
COUNT(DISTINCT NULLIF(LTRIM(RTRIM(CAST(Pallet AS varchar(32)))), '')) AS Pallet
|
||||
```
|
||||
|
||||
Questo evita il doppio conteggio di UDC multi-lotto.
|
||||
|
||||
### `SQL_PL_DETAILS`
|
||||
|
||||
Ritorna tutte le righe residuali della lista selezionata, ordinate per `Ordinamento`.
|
||||
|
||||
## Effetti sul database
|
||||
|
||||
Il modulo UI non aggiorna direttamente tabelle. Tutte le modifiche passano da `sp_xExePackingListPallet_async`, che esegue `dbo.py_sp_xExePackingListPallet`.
|
||||
|
||||
Effetti indiretti:
|
||||
|
||||
- aggiorna `dbo.PyPickingListReservation`;
|
||||
- aggiorna `dbo.Celle.IDStato`;
|
||||
- scrive audit applicativo con `log_user_action`;
|
||||
- la stored puo' scrivere log legacy tramite `sp_LogPackingList`.
|
||||
|
||||
## Rischi e note review
|
||||
|
||||
- La vista residuale cambia mentre il barcode scarica UDC: per questo `Ricarica` conserva la selezione e ricarica il dettaglio.
|
||||
- La tabella alta e il dettaglio possono non avere lo stesso numero di righe dello storico, perche' qui si vedono solo residui.
|
||||
- La convivenza C#/Python dipende dalla presenza degli oggetti `py_*`.
|
||||
- La selezione e' esclusiva lato UI, ma il secondo livello F2 barcode dipende dalla logica barcode/stato DB, non da una seconda prenotazione backoffice.
|
||||
97
docs/review/module_prenota_sprenota_sql.md
Normal file
97
docs/review/module_prenota_sprenota_sql.md
Normal file
@@ -0,0 +1,97 @@
|
||||
# Modulo `prenota_sprenota_sql.py`
|
||||
|
||||
## Scopo
|
||||
|
||||
Il modulo contiene il port asincrono della stored procedure di prenotazione picking list. E' il ponte tra la UI Python e la stored SQL Python-only `dbo.py_sp_xExePackingListPallet`.
|
||||
|
||||
La funzione pubblica principale e':
|
||||
|
||||
```python
|
||||
async def sp_xExePackingListPallet_async(db, IDOperatore: int, Documento: str, Azione: str = "P") -> SPResult
|
||||
```
|
||||
|
||||
## Motivazione
|
||||
|
||||
Durante la fase di test sul campo devono convivere:
|
||||
|
||||
- applicazione C# legacy;
|
||||
- applicazione Python.
|
||||
|
||||
Per evitare collisioni, il Python non chiama `dbo.sp_xExePackingListPallet` legacy ma `dbo.py_sp_xExePackingListPallet`.
|
||||
|
||||
## Semantica parametro `Azione`
|
||||
|
||||
| Azione | Significato |
|
||||
| --- | --- |
|
||||
| `P` | prenota il documento |
|
||||
| `S` | s-prenota il documento |
|
||||
|
||||
Ogni altra azione ritorna:
|
||||
|
||||
```python
|
||||
SPResult(rc=-10, message="Azione non valida: ...")
|
||||
```
|
||||
|
||||
## Classe `SPResult`
|
||||
|
||||
Firma:
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class SPResult:
|
||||
rc: int = 0
|
||||
message: Optional[str] = ""
|
||||
id_result: Optional[int] = None
|
||||
```
|
||||
|
||||
Campi:
|
||||
|
||||
| Campo | Ruolo |
|
||||
| --- | --- |
|
||||
| `rc` | codice ritorno della stored |
|
||||
| `message` | messaggio errore o vuoto |
|
||||
| `id_result` | predisposizione per ID risultato, non usato oggi |
|
||||
|
||||
## Funzioni helper
|
||||
|
||||
| Funzione | Firma | Ruolo |
|
||||
| --- | --- | --- |
|
||||
| `_query_one_value` | `_query_one_value(db, sql: str, params: Dict[str, Any]) -> Optional[Any]` | helper generico scalar, oggi non centrale nel flusso |
|
||||
| `_query_all` | `_query_all(db, sql: str, params: Dict[str, Any]) -> List[Dict[str, Any]]` | normalizza query multi-riga |
|
||||
| `_execute` | `_execute(db, sql: str, params: Dict[str, Any]) -> int` | helper generico DML |
|
||||
| `sp_xExePackingListPallet_async` | vedi sopra | esegue stored Python-only |
|
||||
|
||||
## Processo logico `sp_xExePackingListPallet_async`
|
||||
|
||||
1. Normalizza `Azione` a maiuscolo.
|
||||
2. Valida `Azione in ("P", "S")`.
|
||||
3. Costruisce una batch SQL con output parameter `@RC`.
|
||||
4. Esegue:
|
||||
|
||||
```sql
|
||||
EXEC dbo.py_sp_xExePackingListPallet
|
||||
@IDOperatore = :IDOperatore,
|
||||
@Documento = :Documento,
|
||||
@Azione = :Azione,
|
||||
@RC = @RC OUTPUT;
|
||||
```
|
||||
|
||||
5. Legge il valore `RC`.
|
||||
6. Ritorna `SPResult(rc=rc, message="", id_result=None)`.
|
||||
7. In caso di eccezione ritorna `SPResult(rc=-1, message=str(exc), id_result=None)`.
|
||||
|
||||
## Commit
|
||||
|
||||
La chiamata usa:
|
||||
|
||||
```python
|
||||
commit=True
|
||||
```
|
||||
|
||||
Motivo: la stored modifica `PyPickingListReservation` e `Celle.IDStato`.
|
||||
|
||||
## Rischi e note review
|
||||
|
||||
- Gli helper `_query_one_value`, `_query_all`, `_execute` sono generici e non tutti sono essenziali al percorso attuale.
|
||||
- La funzione cattura le eccezioni e ritorna `SPResult(rc=-1)`, quindi la UI deve controllare sempre `rc`.
|
||||
- La transazione reale dipende dal comportamento di `query_json(..., commit=True)` nel client DB.
|
||||
150
docs/review/module_storico_pickinglist.md
Normal file
150
docs/review/module_storico_pickinglist.md
Normal file
@@ -0,0 +1,150 @@
|
||||
# Modulo `storico_pickinglist.py`
|
||||
|
||||
## Scopo
|
||||
|
||||
Il modulo implementa la finestra "Storico Picking List". La finestra permette di:
|
||||
|
||||
- cercare picking list storiche per numero documento;
|
||||
- visualizzare lo stato operativo sintetico di ciascuna lista;
|
||||
- visualizzare il dettaglio UDC/lotto/articolo della lista selezionata;
|
||||
- evidenziare liste chiuse, liste attive e casi anomali;
|
||||
- versare in blocco in `7G.1.1` le UDC residue di una lista classificata come `Chiusa ERP con residui`.
|
||||
|
||||
Il modulo legge da viste SQL dedicate al ramo Python. Non usa le viste legacy C# per evitare collisioni durante il periodo in cui i due programmi convivono sullo stesso database.
|
||||
|
||||
## Dipendenze principali
|
||||
|
||||
- `customtkinter` e `tkinter.ttk`: UI e griglie.
|
||||
- `AsyncRunner`: esecuzione asincrona delle query senza bloccare la GUI.
|
||||
- `InlineBusyOverlay`: indicatore visivo durante query e movimenti.
|
||||
- `move_pallet_async`: funzione centrale per registrare un movimento UDC verso una cella.
|
||||
- `ui_tables`: stile comune delle griglie.
|
||||
- `version_info`: versione visibile nel titolo finestra.
|
||||
- `window_placement`: posizionamento della finestra rispetto al launcher.
|
||||
|
||||
## Processo logico
|
||||
|
||||
### Apertura finestra
|
||||
|
||||
1. `open_storico_pickinglist_window(parent, db_client, session)` crea `StoricoPickingListWindow`.
|
||||
2. La finestra viene posizionata sotto il launcher con `place_window_fullsize_below_parent_later`.
|
||||
3. Dopo 300 ms viene chiamato `_load_master`.
|
||||
|
||||
### Caricamento griglia alta
|
||||
|
||||
1. `_load_master` legge il filtro `Documento`.
|
||||
2. Viene eseguita `SQL_STORICO_PL`.
|
||||
3. `_rows_to_dicts` normalizza il payload del DB.
|
||||
4. `_fill_master` svuota griglia alta e dettaglio.
|
||||
5. Per ogni documento viene calcolato il tag visuale:
|
||||
- `warning` se lista aperta con UDC gia' spedite;
|
||||
- `done` se lista chiusa o esaurita;
|
||||
- `active` se lista prenotata;
|
||||
- zebra tag per alternanza righe.
|
||||
6. La riga viene inserita nella griglia alta.
|
||||
|
||||
### Selezione documento
|
||||
|
||||
1. `_on_master_select` legge la riga selezionata.
|
||||
2. Memorizza:
|
||||
- `_selected_documento`
|
||||
- `_selected_stato_operativo`
|
||||
- `_detail_rows`
|
||||
3. Abilita o disabilita il pulsante "Versa residui in 7G.1.1".
|
||||
4. Esegue `SQL_STORICO_PL_DETAILS`.
|
||||
5. `_fill_detail` carica la griglia bassa.
|
||||
|
||||
### Versamento residui in 7G.1.1
|
||||
|
||||
Il pulsante e' abilitato solo se `_selected_stato_operativo == "Chiusa ERP con residui"`.
|
||||
|
||||
Flusso:
|
||||
|
||||
1. `_ship_selected_residuals` verifica lo stato selezionato.
|
||||
2. Calcola una stima delle UDC residue gia' presenti nel dettaglio UI.
|
||||
3. Mostra una conferma all'operatore.
|
||||
4. Dentro il job asincrono rilegge il dettaglio dal DB, cosi' evita dati UI obsoleti.
|
||||
5. `_residual_pallets_from_rows` deduplica le UDC e scarta quelle gia' in `IDCella = 9999`.
|
||||
6. Per ogni UDC residua chiama `move_pallet_async` con:
|
||||
- `target_idcella = 9999`
|
||||
- `target_barcode_cella = "9000000"`
|
||||
- `utente = login sessione` oppure `warehouse_ui`
|
||||
7. Al termine mostra un riepilogo.
|
||||
8. Ricarica la griglia alta e tenta di ripristinare la selezione del documento.
|
||||
|
||||
## Stati operativi
|
||||
|
||||
La colonna `Stato` della griglia alta deriva da SQL:
|
||||
|
||||
| Stato operativo | Condizione |
|
||||
| --- | --- |
|
||||
| `Chiusa ERP con residui` | `StatoDocumento = 'D'` e almeno una UDC non e' in `9999` |
|
||||
| `Chiusa` | `StatoDocumento = 'D'` e nessuna UDC residua |
|
||||
| `Esaurita` | tutte le UDC risultano spedite |
|
||||
| `In corso` | almeno una UDC e' spedita e almeno una resta da lavorare |
|
||||
| `Da lavorare` | nessuna UDC ancora spedita |
|
||||
|
||||
## Strutture dati interne
|
||||
|
||||
| Nome | Tipo | Ruolo |
|
||||
| --- | --- | --- |
|
||||
| `var_documento` | `tk.StringVar` | filtro documento digitato dall'utente |
|
||||
| `_selected_documento` | `str | None` | documento correntemente selezionato |
|
||||
| `_selected_stato_operativo` | `str` | stato operativo della riga selezionata |
|
||||
| `_detail_rows` | `list[dict[str, Any]]` | ultimo dettaglio normalizzato caricato nella griglia bassa |
|
||||
| `master_tree` | `ttk.Treeview` | griglia alta documenti |
|
||||
| `detail_tree` | `ttk.Treeview` | griglia bassa righe UDC |
|
||||
| `btn_ship_residuals` | `ctk.CTkButton` | azione di versamento massivo residui |
|
||||
|
||||
## Funzioni e classi
|
||||
|
||||
| Oggetto | Firma | Ruolo |
|
||||
| --- | --- | --- |
|
||||
| `_rows_to_dicts` | `_rows_to_dicts(res: dict[str, Any] | None) -> list[dict[str, Any]]` | normalizza payload DB in lista di dizionari |
|
||||
| `_format_date` | `_format_date(value: Any) -> str` | converte date SQL/SAMA in `dd/mm/yyyy` |
|
||||
| `StoricoPickingListWindow.__init__` | `__init__(self, parent: tk.Widget, db_client, session=None)` | costruisce stato, tema, runner async e UI |
|
||||
| `_build_ui` | `_build_ui(self) -> None` | crea toolbar, griglia alta e griglia dettaglio |
|
||||
| `_make_tree` | `_make_tree(self, *, row: int, columns: tuple[str, ...], widths: dict[str, int]) -> ttk.Treeview` | factory griglia con stile comune |
|
||||
| `_load_master` | `_load_master(self) -> None` | lancia query master asincrona |
|
||||
| `_fill_master` | `_fill_master(self, rows: list[dict[str, Any]]) -> None` | popola griglia alta |
|
||||
| `_on_master_select` | `_on_master_select(self, _event=None) -> None` | gestisce selezione documento e carica dettaglio |
|
||||
| `_fill_detail` | `_fill_detail(self, rows: list[dict[str, Any]]) -> None` | popola griglia bassa |
|
||||
| `_update_residual_button` | `_update_residual_button(self) -> None` | abilita azione solo su `Chiusa ERP con residui` |
|
||||
| `_restore_master_selection` | `_restore_master_selection(self, documento: str) -> None` | riseleziona documento dopo reload |
|
||||
| `_residual_pallets_from_rows` | `_residual_pallets_from_rows(self, rows: list[dict[str, Any]]) -> list[str]` | deduplica UDC residue non gia' spedite |
|
||||
| `_operator_login` | `_operator_login(self) -> str` | determina utente per movimenti |
|
||||
| `_ship_selected_residuals` | `_ship_selected_residuals(self) -> None` | esegue versamento massivo verso `7G.1.1` |
|
||||
| `open_storico_pickinglist_window` | `open_storico_pickinglist_window(parent: tk.Misc, db_client, session=None) -> tk.Misc` | entry point chiamato dal launcher |
|
||||
|
||||
## Effetti sul database
|
||||
|
||||
Il modulo e' in sola lettura tranne `_ship_selected_residuals`.
|
||||
|
||||
`_ship_selected_residuals` non esegue SQL diretto di update. Delega ogni UDC a `move_pallet_async`, che:
|
||||
|
||||
- trova l'ultimo movimento `V` positivo della UDC;
|
||||
- aggiorna `ModUtente` e `ModDataOra` della riga sorgente;
|
||||
- inserisce un movimento `P` sulla cella sorgente;
|
||||
- libera `Celle.IDStato` della cella sorgente;
|
||||
- inserisce un movimento `V` sulla cella target `9999`;
|
||||
- esegue `dbo.py_sp_ControllaPrenotazionePackingListPalletNew`.
|
||||
|
||||
## Rischi e note review
|
||||
|
||||
- Il versamento massivo non e' atomico a livello di intera lista: ogni UDC viene movimentata con una chiamata separata. Se una UDC fallisce, quelle precedenti potrebbero essere gia' state registrate.
|
||||
- La rilettura del dettaglio riduce il rischio di dato UI obsoleto, ma non sostituisce un lock transazionale su documento.
|
||||
- Le UDC multi-lotto sono deduplicate per `Pallet`, per evitare doppio movimento fisico.
|
||||
- Le UDC gia' in `9999` vengono saltate.
|
||||
- Le UDC non scaffalate risultano `IDCella = 1000`; vengono considerate residue e quindi movimentate verso `9999`.
|
||||
|
||||
## Test consigliati
|
||||
|
||||
1. Selezionare una lista `Da lavorare`: il pulsante deve restare disabilitato.
|
||||
2. Selezionare una lista `Chiusa`: il pulsante deve restare disabilitato.
|
||||
3. Selezionare una lista `Chiusa ERP con residui`: il pulsante deve abilitarsi.
|
||||
4. Confermare il versamento su una lista con UDC non scaffalate.
|
||||
5. Verificare in `Storico movimenti UDC` che ogni UDC abbia:
|
||||
- ultimo passaggio sorgente;
|
||||
- movimento `P` sulla sorgente;
|
||||
- movimento `V` su `9999 / 7G.1.1`.
|
||||
6. Ricaricare lo storico picking list: la lista non deve piu' risultare con residui se tutte le UDC sono in `9999`.
|
||||
153
docs/review/sql_pickinglist_reservation.md
Normal file
153
docs/review/sql_pickinglist_reservation.md
Normal file
@@ -0,0 +1,153 @@
|
||||
# SQL prenotazione picking list Python-only
|
||||
|
||||
## Script
|
||||
|
||||
- `apply_python_parallel_pickinglist_patch.sql`
|
||||
- `rollback_python_parallel_pickinglist_patch.sql`
|
||||
|
||||
## Obiettivo
|
||||
|
||||
Permettere a Python e C# di lavorare sullo stesso database senza condividere le stesse stored procedure operative.
|
||||
|
||||
Il C# continua a usare gli oggetti legacy:
|
||||
|
||||
- `dbo.XMag_ViewPackingList`
|
||||
- `dbo.ViewPackingListRestante`
|
||||
- `dbo.sp_xExePackingListPallet`
|
||||
- `dbo.sp_xExePackingListPalletPrenota`
|
||||
- `dbo.sp_ControllaPrenotazionePackingListPalletNew`
|
||||
|
||||
Il Python usa oggetti separati:
|
||||
|
||||
- `dbo.py_XMag_ViewPackingList`
|
||||
- `dbo.py_ViewPackingListRestante`
|
||||
- `dbo.py_sp_xExePackingListPallet`
|
||||
- `dbo.py_sp_xExePackingListPalletPrenota`
|
||||
- `dbo.py_sp_ControllaPrenotazionePackingListPalletNew`
|
||||
- `dbo.PyPickingListReservation`
|
||||
|
||||
## Tabella `dbo.PyPickingListReservation`
|
||||
|
||||
### Scopo
|
||||
|
||||
Contiene la singola picking list prenotata dal programma Python.
|
||||
|
||||
### Schema
|
||||
|
||||
| Colonna | Tipo | Ruolo |
|
||||
| --- | --- | --- |
|
||||
| `ID` | `tinyint` | sempre `1`, enforced da check constraint |
|
||||
| `Documento` | `varchar(8)` | documento prenotato |
|
||||
| `IDOperatore` | `int` | operatore che ha fatto l'ultima azione |
|
||||
| `ModUtente` | `varchar(50)` | login operatore |
|
||||
| `ModDataOra` | `datetime` | timestamp modifica |
|
||||
|
||||
### Vincoli
|
||||
|
||||
- Primary key su `ID`.
|
||||
- Check `ID = 1`.
|
||||
|
||||
Questa scelta implementa un singleton DB: il Python puo' avere una sola lista prenotata dal backoffice.
|
||||
|
||||
## Vista `dbo.py_XMag_ViewPackingList`
|
||||
|
||||
### Scopo
|
||||
|
||||
Replica la vista legacy `dbo.XMag_ViewPackingList` ma calcola `IDStato` usando `PyPickingListReservation`, non `Celle.IDStato` legacy.
|
||||
|
||||
### Logica `IDStato`
|
||||
|
||||
```sql
|
||||
CASE
|
||||
WHEN pr.Documento IS NOT NULL
|
||||
AND pr.Documento = CAST(legacy.Documento AS varchar(8))
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END AS IDStato
|
||||
```
|
||||
|
||||
## Vista `dbo.py_ViewPackingListRestante`
|
||||
|
||||
### Scopo
|
||||
|
||||
Espone solo le UDC non ancora spedite:
|
||||
|
||||
```sql
|
||||
WHERE Cella <> 9999
|
||||
```
|
||||
|
||||
La UI "Gestione Picking List" usa questa vista sia per la griglia alta sia per il dettaglio.
|
||||
|
||||
## Stored `dbo.py_sp_xExePackingListPallet`
|
||||
|
||||
### Parametri
|
||||
|
||||
| Parametro | Tipo | Ruolo |
|
||||
| --- | --- | --- |
|
||||
| `@IDOperatore` | `int` | operatore corrente |
|
||||
| `@Documento` | `varchar(8)` | documento da prenotare/sprenotare |
|
||||
| `@Azione` | `char(1)` | `P` prenota, `S` s-prenota |
|
||||
| `@RC` | `int OUTPUT` | codice ritorno |
|
||||
|
||||
### Validazioni
|
||||
|
||||
- `@Azione` deve essere `P` o `S`, altrimenti `@RC = -10`.
|
||||
- Il documento deve esistere in `py_XMag_ViewPackingList`, altrimenti `@RC = -20`.
|
||||
- Se manca la riga singleton in `PyPickingListReservation`, viene creata.
|
||||
|
||||
### Prenotazione `P`
|
||||
|
||||
1. Se il documento e' gia' attivo, ritorna senza modifiche.
|
||||
2. Azzera `IDStato` su tutte le celle con stato diverso da zero.
|
||||
3. Mette `IDStato = 1` sulle celle del documento target.
|
||||
4. Aggiorna `PyPickingListReservation` con documento, operatore e timestamp.
|
||||
5. Scrive log tramite `sp_LogPackingList`.
|
||||
|
||||
### S-prenotazione `S`
|
||||
|
||||
1. Se il documento attivo non e' quello richiesto, ritorna senza modifiche.
|
||||
2. Azzera `IDStato` sulle celle target.
|
||||
3. Pulisce `PyPickingListReservation.Documento`.
|
||||
|
||||
## Stored `dbo.py_sp_xExePackingListPalletPrenota`
|
||||
|
||||
### Scopo
|
||||
|
||||
Mette `IDStato = 1` sulle celle ancora residue del documento. Viene usata dal controllo automatico prenotazione.
|
||||
|
||||
## Stored `dbo.py_sp_ControllaPrenotazionePackingListPalletNew`
|
||||
|
||||
### Scopo
|
||||
|
||||
Mantiene coerente la prenotazione mentre la picking list viene consumata dal barcode.
|
||||
|
||||
### Logica
|
||||
|
||||
1. Legge documento attivo da `PyPickingListReservation`.
|
||||
2. Se non c'e' documento attivo, termina.
|
||||
3. Se non esistono piu' righe residue in `py_ViewPackingListRestante`:
|
||||
- azzera `Celle.IDStato`;
|
||||
- svuota `PyPickingListReservation.Documento`;
|
||||
- termina.
|
||||
4. Se esistono ancora residui:
|
||||
- azzera tutti gli `IDStato`;
|
||||
- richiama `py_sp_xExePackingListPalletPrenota` per prenotare le celle residue.
|
||||
|
||||
## Rollback
|
||||
|
||||
`rollback_python_parallel_pickinglist_patch.sql` elimina:
|
||||
|
||||
- `py_sp_ControllaPrenotazionePackingListPalletNew`
|
||||
- `py_sp_xExePackingListPalletPrenota`
|
||||
- `py_sp_xExePackingListPallet`
|
||||
- `py_ViewPackingListRestante`
|
||||
- `py_XMag_ViewPackingList`
|
||||
- `PyPickingListReservation`
|
||||
|
||||
Non tocca gli oggetti legacy C#.
|
||||
|
||||
## Note review
|
||||
|
||||
- La stored Python usa una prenotazione singleton, quindi non gestisce due liste prenotate backoffice.
|
||||
- L'azzeramento globale di `Celle.IDStato` e' coerente con la semantica attuale, ma in futuro dovra' essere rivalutato se piu' operatori o magazzini lavorano in parallelo.
|
||||
- Le UDC non scaffalate condividono il fallback dati del modello legacy; questo e' noto e andra' riprogettato nel nuovo schema FlyWMS.
|
||||
236
docs/review/sql_storico_pickinglist.md
Normal file
236
docs/review/sql_storico_pickinglist.md
Normal file
@@ -0,0 +1,236 @@
|
||||
# SQL storico picking list
|
||||
|
||||
## Oggetti SQL coinvolti
|
||||
|
||||
La form "Storico Picking List" usa un ramo SQL Python-only:
|
||||
|
||||
- `dbo.py_vPreparaPackingListSAMA1`
|
||||
- `dbo.py_vPreparaPackingList`
|
||||
- `dbo.py_XMag_ViewPackingListStorico`
|
||||
- `dbo.PyPickingListReservation`
|
||||
|
||||
Gli script principali sono:
|
||||
|
||||
- `apply_python_pickinglist_history_views.sql`
|
||||
- `apply_online_history_forms_patch.sql`
|
||||
- `rollback_python_pickinglist_history_views.sql`
|
||||
- `rollback_online_history_forms_patch.sql`
|
||||
|
||||
## Motivazione del ramo Python-only
|
||||
|
||||
Il progetto deve convivere temporaneamente con l'applicazione C# legacy. Per questo lo storico Python non modifica:
|
||||
|
||||
- `dbo.vPreparaPackingListSAMA1`
|
||||
- `dbo.vPreparaPackingList`
|
||||
- `dbo.XMag_ViewPackingList`
|
||||
- stored procedure legacy C#
|
||||
|
||||
Le viste prefissate `py_` permettono di evolvere il comportamento Python senza cambiare la semantica legacy.
|
||||
|
||||
## Vista `dbo.py_vPreparaPackingListSAMA1`
|
||||
|
||||
### Scopo
|
||||
|
||||
Legge dal database ERP `SAMA1` le informazioni documentali e di riga necessarie a ricostruire la picking list.
|
||||
|
||||
### Tabelle ERP coinvolte
|
||||
|
||||
- `SAMA1.dbo.LOTSER`
|
||||
- `SAMA1.dbo.ARTICO`
|
||||
- `SAMA1.dbo.FATRIG`
|
||||
- `SAMA1.dbo.LOTTIBF`
|
||||
- `SAMA1.dbo.BAMTES`
|
||||
- `SAMA1.dbo.NAZIONI`
|
||||
- `SAMA1.sam.EXTUC`
|
||||
- `SAMA1.dbo.MTRASP`
|
||||
|
||||
### Campi principali
|
||||
|
||||
| Campo | Significato |
|
||||
| --- | --- |
|
||||
| `NUMLOT` | lotto |
|
||||
| `CODICE` | codice articolo |
|
||||
| `DESCR` | descrizione riga/articolo |
|
||||
| `UDC` | prime 6 cifre di `LOTSER.NUMSER` |
|
||||
| `Qta` | somma quantita giacente ERP |
|
||||
| `NUMDOC` | numero documento/picking list |
|
||||
| `DATDOC` | data documento ERP |
|
||||
| `StatoDocumento` | stato ERP, filtrato su `P` o `D` |
|
||||
| `NAZIONE` | trasporto + descrizione nazione |
|
||||
|
||||
### Filtri
|
||||
|
||||
- anno documento >= anno corrente;
|
||||
- stato documento in `P`, `D`;
|
||||
- lotto diverso da `00000000000`.
|
||||
|
||||
## Vista `dbo.py_vPreparaPackingList`
|
||||
|
||||
### Scopo
|
||||
|
||||
E' una vista di pulizia sopra `py_vPreparaPackingListSAMA1`.
|
||||
|
||||
### Filtro
|
||||
|
||||
Esclude righe con `NUMLOT = ''`.
|
||||
|
||||
## Vista `dbo.py_XMag_ViewPackingListStorico`
|
||||
|
||||
### Scopo
|
||||
|
||||
Unisce il contenuto ERP della picking list con la posizione WMS corrente della UDC.
|
||||
|
||||
### Tabelle WMS coinvolte
|
||||
|
||||
- `dbo.XMag_GiacenzaPallet`
|
||||
- `dbo.Celle`
|
||||
- `dbo.Aree`
|
||||
- `dbo.PyPickingListReservation`
|
||||
|
||||
### Join principale
|
||||
|
||||
La vista usa una `RIGHT OUTER JOIN` tra posizione WMS e preparazione ERP:
|
||||
|
||||
```sql
|
||||
RIGHT OUTER JOIN dbo.py_vPreparaPackingList prep
|
||||
ON g.BarcodePallet COLLATE SQL_Latin1_General_CP1_CI_AS = prep.UDC
|
||||
```
|
||||
|
||||
Questo garantisce che una UDC presente nella picking list ERP compaia anche se non e' scaffalata nel WMS.
|
||||
|
||||
### Convenzioni celle
|
||||
|
||||
| IDCella | Ubicazione | Significato |
|
||||
| --- | --- | --- |
|
||||
| `9999` | `7G - 1 - 1` | spedizione / UDC scaricata |
|
||||
| `1000` | `Non scaff.` | fallback per UDC non trovata in `XMag_GiacenzaPallet` |
|
||||
|
||||
La vista usa:
|
||||
|
||||
```sql
|
||||
ISNULL(g.IDCella, 1000) AS Cella
|
||||
ISNULL(c.Corsia + ' - ' + c.Colonna + ' - ' + c.Fila, 'Non scaff.') AS Ubicazione
|
||||
```
|
||||
|
||||
Quindi le UDC ERP non presenti in giacenza WMS sono rappresentate come non scaffalate.
|
||||
|
||||
## Query Python `SQL_STORICO_PL`
|
||||
|
||||
### Scopo
|
||||
|
||||
Costruisce la griglia alta della form.
|
||||
|
||||
### CTE
|
||||
|
||||
| CTE | Ruolo |
|
||||
| --- | --- |
|
||||
| `base` | normalizza `Pallet` in `PalletKey` |
|
||||
| `pallets` | aggrega righe multi-lotto per singola UDC |
|
||||
| `meta` | calcola metadati documento |
|
||||
| `agg` | calcola totale UDC, UDC spedite e UDC residue |
|
||||
|
||||
### Stato operativo
|
||||
|
||||
La query produce `StatoOperativo` con questa logica:
|
||||
|
||||
```sql
|
||||
CASE
|
||||
WHEN m.StatoDocumento = 'D' AND COALESCE(a.RigheResidue, 0) > 0 THEN 'Chiusa ERP con residui'
|
||||
WHEN m.StatoDocumento = 'D' THEN 'Chiusa'
|
||||
WHEN COALESCE(a.RigheResidue, 0) = 0 THEN 'Esaurita'
|
||||
WHEN COALESCE(a.RigheSpedite, 0) > 0 THEN 'In corso'
|
||||
ELSE 'Da lavorare'
|
||||
END
|
||||
```
|
||||
|
||||
### Deduplica UDC
|
||||
|
||||
La deduplica avviene su `PalletKey`, non sulle righe. Questo evita che una UDC con piu' lotti venga contata come piu' pallet.
|
||||
|
||||
## Query Python `SQL_STORICO_PL_DETAILS`
|
||||
|
||||
### Scopo
|
||||
|
||||
Costruisce la griglia bassa della form.
|
||||
|
||||
### Output
|
||||
|
||||
| Campo | Ruolo |
|
||||
| --- | --- |
|
||||
| `Documento` | numero picking list |
|
||||
| `Pallet` | UDC fisica |
|
||||
| `Lotto` | lotto |
|
||||
| `Articolo` | codice articolo |
|
||||
| `Descrizione` | descrizione articolo/riga |
|
||||
| `Qta` | quantita |
|
||||
| `DataDocumento` | data ERP |
|
||||
| `StatoDocumento` | stato ERP |
|
||||
| `Cella` | cella WMS corrente/fallback |
|
||||
| `Ubicazione` | descrizione cella |
|
||||
| `Ordinamento` | ordine operativo |
|
||||
| `IDStato` | prenotazione Python |
|
||||
|
||||
## Effetti SQL del versamento residui
|
||||
|
||||
La form non contiene direttamente update/insert SQL per il versamento residui. Chiama `move_pallet_async` in `gestione_scarico.py`.
|
||||
|
||||
La batch SQL associata e' `SQL_SCARICA_UDC` e produce:
|
||||
|
||||
1. ricerca dell'ultimo movimento `V` positivo della UDC;
|
||||
2. update audit della riga sorgente;
|
||||
3. insert movimento `P` sulla cella sorgente;
|
||||
4. update `Celle.IDStato = 0` sulla cella sorgente;
|
||||
5. insert movimento `V` sulla cella target;
|
||||
6. esecuzione `dbo.py_sp_ControllaPrenotazionePackingListPalletNew`.
|
||||
|
||||
Per la funzione storico picking list il target e':
|
||||
|
||||
- `target_idcella = 9999`
|
||||
- `target_barcode_cella = '9000000'`
|
||||
|
||||
## Note di consistenza dati
|
||||
|
||||
- Una UDC non scaffalata viene vista come `Cella = 1000`, quindi e' residua.
|
||||
- Una UDC in `9999` non e' residua e viene esclusa dal movimento massivo.
|
||||
- Una UDC multi-lotto puo' comparire piu' volte nel dettaglio ma deve generare un solo movimento fisico.
|
||||
- Lo stato `Chiusa ERP con residui` evidenzia disallineamento tra documento ERP chiuso e WMS non completamente versato in spedizione.
|
||||
|
||||
## Query diagnostiche utili
|
||||
|
||||
Verificare righe documento:
|
||||
|
||||
```sql
|
||||
SELECT *
|
||||
FROM dbo.py_XMag_ViewPackingListStorico
|
||||
WHERE Documento = 155
|
||||
ORDER BY Ordinamento, Pallet;
|
||||
```
|
||||
|
||||
Verificare UDC residue:
|
||||
|
||||
```sql
|
||||
SELECT DISTINCT Pallet, Cella, Ubicazione
|
||||
FROM dbo.py_XMag_ViewPackingListStorico
|
||||
WHERE Documento = 155
|
||||
AND ISNULL(Cella, 0) <> 9999
|
||||
ORDER BY Pallet;
|
||||
```
|
||||
|
||||
Verificare movimenti UDC dopo versamento:
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
ID,
|
||||
Tipo,
|
||||
IDRiferimento,
|
||||
Attributo,
|
||||
IDCella,
|
||||
DataMagazzino,
|
||||
InsUtente,
|
||||
InsDataOra,
|
||||
ModUtente,
|
||||
ModDataOra
|
||||
FROM dbo.MagazziniPallet
|
||||
WHERE Attributo = '655560'
|
||||
ORDER BY ID;
|
||||
```
|
||||
59
docs/ricerca_udc_storico_pickinglist.md
Normal file
59
docs/ricerca_udc_storico_pickinglist.md
Normal file
@@ -0,0 +1,59 @@
|
||||
# Ricerca UDC nello storico picking list
|
||||
|
||||
Modifica del 22 ottobre 2026. Storico Picking List versione 1.0.5, ramo monolista.
|
||||
|
||||
## Uso
|
||||
|
||||
- Campo UDC vuoto: rimane la consultazione annuale esistente, con il filtro
|
||||
facoltativo sul numero documento e ordinamento dalla data piu' recente.
|
||||
- Campo UDC compilato: premere Invio o Ricarica per trovare le picking list
|
||||
contenenti quella UDC nell'anno corrente e nel precedente. Nel 2026 sono
|
||||
2025 e 2026; nel 2027 saranno 2026 e 2027. L'anno e' quello documento SAM,
|
||||
rispetto alla data del server SQL, non l'anno di creazione della UDC.
|
||||
- Si cerca il codice UDC completo, non una sua parte; non inserire il suffisso
|
||||
della bag dopo lo slash. Sono ammessi codici numerici fino a sei cifre,
|
||||
conservando gli eventuali zeri iniziali.
|
||||
- Se sono compilati sia Documento sia UDC, i filtri si combinano (AND).
|
||||
Documento mantiene la ricerca parziale esistente.
|
||||
- L'anno compare accanto al documento nella griglia. Se ci sono piu' documenti
|
||||
contenenti la UDC vengono mostrati tutti, anche P e D, non solo l'ultimo.
|
||||
- Selezionando un risultato si vede il contenuto COMPLETO della lista.
|
||||
Anche i totali e i residui si riferiscono alla lista intera, non alla sola UDC
|
||||
cercata. Piu' lotti della stessa UDC non aumentano il numero pallet.
|
||||
- Per tornare all'elenco annuale, cancellare UDC e premere Ricarica.
|
||||
|
||||
## Dati e isolamento
|
||||
|
||||
La ricerca dedicata usa query parametrizzate in pickinglist_history_search.py,
|
||||
attraverso BAMTES, FATRIG, LOTTIBF e LOTSER di SAMA1. Usa LEFT(NUMSER,6) come
|
||||
identificativo UDC e seleziona documenti P o D, escludendo i lotti vuoti/fittizi
|
||||
come la vista storica. Le anagrafiche di destinazione sono facoltative: la loro
|
||||
assenza non nasconde il documento.
|
||||
|
||||
La vista annuale esistente non viene allargata. Nessuna tabella, vista o stored
|
||||
procedure e' creata o modificata; nessuna patch SQL aggiuntiva e' necessaria.
|
||||
Non cambiano il barcode, la prenotazione o gli oggetti legacy C#.
|
||||
|
||||
Il numero documento non e' univoco fra anni. La ricerca conserva BAMTES.ID per
|
||||
aggregazione, selezione, dettaglio e comando di versamento residui. Non vengono
|
||||
mescolate, per esempio, la lista 244 del 2025 e la lista 244 del 2026. Una
|
||||
prenotazione corrente non viene attribuita a una lista omonima dell'anno scorso.
|
||||
|
||||
Le ubicazioni e gli stati operativi sono quelli WMS correnti, come nello storico
|
||||
esistente, non una fotografia delle celle al momento della spedizione. Anche
|
||||
l'appartenenza della UDC dipende dalle associazioni LOTSER/documenti oggi presenti
|
||||
nel database, non da un nuovo archivio immutabile.
|
||||
|
||||
Le query mantengono esecuzione asincrona e overlay. Risposte tardive di una ricerca
|
||||
o selezione precedente non sostituiscono il risultato corrente. Il versamento
|
||||
residui rimane una distinta azione con conferma, mai un effetto della ricerca.
|
||||
|
||||
## Distribuzione e verifiche
|
||||
|
||||
Distribuire anche pickinglist_history_search.py insieme a storico_pickinglist.py,
|
||||
version_info.py e locale.json. Non occorre rilanciare full_patch per questa modifica.
|
||||
|
||||
tests/test_pickinglist_history_search.py include test con widget Tk reali e query
|
||||
SQL su sole fixture temporanee: finestra biennale, passaggio di anno, omonimia
|
||||
dei documenti, UDC multilotto, filtri combinati, dettagli e conteggi completi,
|
||||
assenza di ubicazione e protezione dalle risposte asincrone obsolete.
|
||||
81
docs/svuotamento_corsie.md
Normal file
81
docs/svuotamento_corsie.md
Normal file
@@ -0,0 +1,81 @@
|
||||
# Svuotamento scaffale/corsia con destinazione automatica
|
||||
|
||||
Modifica del 22 ottobre 2026, ramo monolista. Gestione Corsie: versione 1.0.1.
|
||||
|
||||
## Obiettivo e confini
|
||||
|
||||
Svuotare uno scaffale per rileggere le ubicazioni non equivale a spedire tutte
|
||||
le UDC. I movimenti eseguiti prima di questa modifica, incluso lo svuotamento
|
||||
del 21 ottobre, non vengono corretti o riscritti automaticamente.
|
||||
|
||||
La selezione continua a essere la corsia/scaffale della finestra Gestione Corsie.
|
||||
Non vengono coinvolte le altre corsie, le UDC assenti dal WMS o le locazioni
|
||||
virtuali. Le procedure del barcode e lo scarico manuale da layout non cambiano.
|
||||
|
||||
## Regola di destinazione
|
||||
|
||||
Per ogni UDC attualmente presente nella corsia si verifica la relazione
|
||||
`LOTSER -> LOTTIBF -> FATRIG -> BAMTES` in SAMA1. I primi sei caratteri di
|
||||
`LOTSER.NUMSER` identificano la UDC. Il criterio di definitivo e' `BAMTES.STATO = 'D'`,
|
||||
lo stesso stato ERP usato nello storico picking list; non e' la prenotazione WMS.
|
||||
|
||||
- Almeno un documento definitivo associato: destinazione ID 9999, 7G.1.1, spedita.
|
||||
- Nessun documento definitivo associato, anche con documento P o senza documento:
|
||||
destinazione ID 1000, non scaffalata (barcode 9001000).
|
||||
|
||||
La ricerca non dipende dall'anno visualizzato nello storico, dai giorni di
|
||||
visibilita' delle liste o dalla presenza della UDC nelle liste prenotabili.
|
||||
Piu' lotti/righe/documenti non moltiplicano il movimento: si usa EXISTS.
|
||||
Se una UDC compare sia in un documento D sia in uno P, prevale D, coerentemente
|
||||
con il controllo legacy sulle UDC gia' spedite. Il modello presuppone codici UDC
|
||||
non riutilizzati; eventuali riusi/resi richiedono analisi separata.
|
||||
|
||||
## Transazione, controlli e tracciamento
|
||||
|
||||
`reset_corsie_service.reset_pallet_async` esegue un singolo batch SQL con
|
||||
`query_json(commit=True)` e `XACT_ABORT ON`. Ogni UDC ha una propria transazione:
|
||||
|
||||
1. Blocca le righe di movimento della UDC durante il controllo e la scrittura.
|
||||
2. Verifica che la UDC sia ancora nella cella originariamente selezionata e non
|
||||
presenti altre ubicazioni attive. Le celle virtuali non sono sorgenti valide.
|
||||
3. Determina la destinazione dalla situazione ERP al momento del movimento.
|
||||
4. Verifica la presenza della cella virtuale e del versamento sorgente.
|
||||
5. Registra P dalla sorgente e V nella destinazione, con riferimenti, data e utente;
|
||||
azzera lo stato della cella sorgente secondo la logica di movimento esistente.
|
||||
6. Verifica che l'unica ubicazione attiva risultante sia la destinazione attesa.
|
||||
7. Richiama il controllo prenotazioni Python gia' esistente e conferma.
|
||||
|
||||
Un errore annulla la transazione della UDC corrente. Le altre UDC gia' confermate
|
||||
rimangono movimentate; lo svuotamento non e' una transazione unica di scaffale.
|
||||
La finestra riporta successi, spedite, non scaffalate ed eventuali errori. Nel log
|
||||
`reset_corsie.log` ogni successo indica UDC, cella sorgente, destinazione e utente;
|
||||
ogni errore include la UDC e il dettaglio tecnico. Un'interruzione di rete durante
|
||||
il commit richiede di ricaricare e verificare la situazione, non di presumere che
|
||||
il movimento sia certamente annullato. Eseguire lo svuotamento senza movimenti
|
||||
operativi concorrenti sulla corsia; i controlli non sostituiscono questa cautela.
|
||||
|
||||
## Effetto sullo storico picking list
|
||||
|
||||
Lo storico calcola i residui dalle ubicazioni correnti: ogni UDC con almeno una
|
||||
posizione diversa da 9999 e' residua; anche 1000 o l'assenza di un'associazione WMS
|
||||
sono rappresentati come residui dalla vista storica.
|
||||
|
||||
Un documento D passa da **Chiusa ERP con residui** a **Chiusa**, al successivo
|
||||
aggiornamento della finestra, solo quando TUTTE le sue UDC risultano spedite.
|
||||
Se lo scaffale svuotato contiene tutti gli ultimi residui, basta questa operazione.
|
||||
Se rimangono UDC in altri scaffali, non scaffalate o mai registrate nel WMS,
|
||||
la lista resta correttamente **Chiusa ERP con residui**. Non vengono modificate
|
||||
le intestazioni o le righe documento SAM. Per chiudere tutti i residui di un
|
||||
documento esiste gia' il comando dedicato nello storico, con conferma separata.
|
||||
|
||||
## Distribuzione e verifica
|
||||
|
||||
Non vengono create o alterate tabelle, viste o stored procedure: nessuna nuova
|
||||
patch SQL da lanciare. Il nuovo modulo Python deve essere distribuito insieme
|
||||
a reset_corsie.py, version_info.py, locale.json e tooltip.json. Restano necessarie
|
||||
le patch precedenti e la procedura Python di controllo prenotazioni gia' installata.
|
||||
|
||||
I test in tests/test_reset_corsie.py coprono la classificazione, le destinazioni,
|
||||
la registrazione P/V, i blocchi e il rollback. I test SQL sono attivabili con
|
||||
RESET_TEST_CONFIG: sostituiscono tutti gli oggetti reali con fixture temporanee
|
||||
locali alla connessione e non movimentano UDC reali.
|
||||
193
error_dialog.py
Normal file
193
error_dialog.py
Normal file
@@ -0,0 +1,193 @@
|
||||
"""Shared error dialogs; call on the Tk thread, like tkinter.messagebox.
|
||||
|
||||
Informational dialogs and confirmations retain their native implementations.
|
||||
Error reports are immutable text, shared by the viewer, clipboard and export.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import traceback
|
||||
import tkinter as tk
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from tkinter import filedialog, messagebox as native_messagebox, ttk
|
||||
|
||||
from locale_text import text
|
||||
from ui_theme import theme_font, theme_section
|
||||
from version_info import APP_VERSION, module_version, versioned_title
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
|
||||
def __getattr__(name):
|
||||
"""Delegate non-error dialogs without changing answers or confirmation flow."""
|
||||
return getattr(native_messagebox, name)
|
||||
|
||||
|
||||
def build_error_report(title, message, exception=None, *, context="") -> str:
|
||||
"""Keep the original message and chained traceback, with unabridged SQL data."""
|
||||
parts = [f"{datetime.now().astimezone().isoformat(timespec='seconds')} | {title}",
|
||||
f"Warehouse {APP_VERSION} | Python {sys.version}"]
|
||||
if context:
|
||||
parts.append(context)
|
||||
parts.append(str(message))
|
||||
if exception is not None:
|
||||
trace = traceback.TracebackException.from_exception(
|
||||
exception, max_group_width=sys.maxsize, max_group_depth=sys.maxsize)
|
||||
parts.append("".join(trace.format()))
|
||||
# SQLAlchemy's exception text may abbreviate parameter collections.
|
||||
seen = set()
|
||||
pending = [exception]
|
||||
while pending:
|
||||
current = pending.pop()
|
||||
if id(current) in seen:
|
||||
continue
|
||||
seen.add(id(current))
|
||||
for name in ("statement", "params"):
|
||||
value = getattr(current, name, None)
|
||||
if value is not None:
|
||||
parts.append(f"{type(current).__name__}.{name}:\n"
|
||||
+ (value if isinstance(value, str) else repr(value)))
|
||||
linked = current.__cause__ or (
|
||||
None if current.__suppress_context__ else current.__context__)
|
||||
if linked is not None:
|
||||
pending.append(linked)
|
||||
if isinstance(current, BaseExceptionGroup):
|
||||
pending.extend(reversed(current.exceptions))
|
||||
return "\n\n".join(parts)
|
||||
|
||||
|
||||
class ErrorDialog(tk.Toplevel):
|
||||
"""Resizable, selectable read-only report, also usable on small terminals."""
|
||||
|
||||
def __init__(self, parent, title, report):
|
||||
super().__init__(parent)
|
||||
self.withdraw()
|
||||
self.report = report
|
||||
self.title(versioned_title(title, __name__))
|
||||
self.resizable(True, True)
|
||||
theme = theme_section("error_dialog")
|
||||
width = min(int(theme.get("width", 900)), max(200, self.winfo_screenwidth() - 24))
|
||||
height = min(int(theme.get("height", 620)), max(200, self.winfo_screenheight() - 80))
|
||||
self.geometry(f"{width}x{height}+0+0")
|
||||
self.minsize(min(width, 420), min(height, 260))
|
||||
if parent.winfo_viewable():
|
||||
self.transient(parent.winfo_toplevel())
|
||||
self.grid_columnconfigure(0, weight=1)
|
||||
self.grid_rowconfigure(0, weight=1)
|
||||
|
||||
frame = ttk.Frame(self, padding=6)
|
||||
frame.grid(row=0, column=0, sticky="nsew")
|
||||
frame.grid_rowconfigure(0, weight=1)
|
||||
frame.grid_columnconfigure(0, weight=1)
|
||||
self.textbox = tk.Text(frame, wrap="none", width=1, height=1,
|
||||
font=theme_font(theme, "font", ("Consolas", 10)),
|
||||
background=theme.get("background", "#ffffff"),
|
||||
foreground=theme.get("foreground", "#202020"), exportselection=False)
|
||||
self.textbox.grid(row=0, column=0, sticky="nsew")
|
||||
self.vertical = ttk.Scrollbar(frame, orient="vertical", command=self.textbox.yview)
|
||||
self.vertical.grid(row=0, column=1, sticky="ns")
|
||||
self.horizontal = ttk.Scrollbar(frame, orient="horizontal", command=self.textbox.xview)
|
||||
self.horizontal.grid(row=1, column=0, sticky="ew")
|
||||
self.textbox.configure(yscrollcommand=self.vertical.set, xscrollcommand=self.horizontal.set)
|
||||
self.textbox.insert("1.0", report)
|
||||
self.textbox.configure(state="disabled")
|
||||
self.textbox.bind("<Control-a>", self.select_all)
|
||||
self.textbox.bind("<Control-c>", self.copy_selection)
|
||||
self.status = tk.StringVar(self, "")
|
||||
ttk.Label(self, textvariable=self.status, wraplength=max(150, width - 20)).grid(
|
||||
row=1, column=0, sticky="ew", padx=6)
|
||||
buttons = ttk.Frame(self, padding=6)
|
||||
buttons.grid(row=2, column=0, sticky="ew")
|
||||
self.buttons = []
|
||||
for i, (key, callback) in enumerate((("copy", self.copy_all),
|
||||
("save", self.save_report), ("close", self.destroy))):
|
||||
button = ttk.Button(buttons, text=text("errors." + key), command=callback)
|
||||
row, col = (i, 0) if width < 480 else (0, i)
|
||||
button.grid(row=row, column=col, sticky="ew", padx=2, pady=2)
|
||||
buttons.grid_columnconfigure(col, weight=1)
|
||||
self.buttons.append(button)
|
||||
self.bind("<Escape>", lambda _: self.destroy())
|
||||
self.deiconify()
|
||||
|
||||
def select_all(self, event=None):
|
||||
self.textbox.tag_add("sel", "1.0", "end-1c")
|
||||
return "break"
|
||||
|
||||
def _copy(self, value):
|
||||
try:
|
||||
self.clipboard_clear()
|
||||
self.clipboard_append(value)
|
||||
self.status.set(text("errors.copied"))
|
||||
except tk.TclError as exc:
|
||||
self.status.set(text("errors.copy_failed").format(error=exc))
|
||||
|
||||
def copy_selection(self, event=None):
|
||||
if self.textbox.tag_ranges("sel"):
|
||||
self._copy(self.textbox.get("sel.first", "sel.last"))
|
||||
return "break"
|
||||
|
||||
def copy_all(self):
|
||||
self._copy(self.report)
|
||||
|
||||
def save_report(self):
|
||||
"""Save UTF-8 without truncation; a failed save leaves the report open."""
|
||||
path = filedialog.asksaveasfilename(parent=self, title=text("errors.save"),
|
||||
defaultextension=".txt", initialfile=f"warehouse_error_{datetime.now():%Y%m%d_%H%M%S}.txt",
|
||||
filetypes=[(text("errors.text_file"), "*.txt"), (text("errors.all_files"), "*.*")])
|
||||
if not path:
|
||||
return
|
||||
try:
|
||||
Path(path).write_text(self.report, encoding="utf-8")
|
||||
except OSError as exc:
|
||||
self.status.set(text("errors.save_failed").format(error=exc))
|
||||
else:
|
||||
self.status.set(text("errors.saved").format(path=path))
|
||||
|
||||
|
||||
def showerror(title=None, message=None, *, parent=None, exception=None, context="", **options):
|
||||
"""Messagebox-compatible modal error; confirmations are never rerouted here.
|
||||
|
||||
Async callbacks must pass ``exception`` explicitly to retain their traceback.
|
||||
Within an except block the active exception is captured automatically.
|
||||
"""
|
||||
if exception is None:
|
||||
exception = message if isinstance(message, BaseException) else sys.exc_info()[1]
|
||||
title = title or text("errors.title")
|
||||
if not context and parent is not None:
|
||||
context = parent.winfo_toplevel().title()
|
||||
report = build_error_report(title, "" if message is None else message, exception, context=context)
|
||||
if options.get("detail"):
|
||||
report += "\n\n" + str(options["detail"])
|
||||
owned_root = None
|
||||
parent = parent if parent is not None else tk._default_root
|
||||
if parent is None:
|
||||
owned_root = parent = tk.Tk()
|
||||
parent.withdraw()
|
||||
previous_grab = parent.grab_current()
|
||||
previous_grab_status = previous_grab.grab_status() if previous_grab else None
|
||||
previous_focus = parent.focus_get()
|
||||
dialog = None
|
||||
try:
|
||||
dialog = ErrorDialog(parent, title, report)
|
||||
dialog.wait_visibility()
|
||||
dialog.grab_set()
|
||||
dialog.textbox.focus_set()
|
||||
dialog.wait_window()
|
||||
finally:
|
||||
if dialog is not None and dialog.winfo_exists():
|
||||
dialog.destroy()
|
||||
try:
|
||||
if previous_grab is not None and previous_grab.winfo_exists():
|
||||
if previous_grab_status == "global":
|
||||
previous_grab.grab_set_global()
|
||||
else:
|
||||
previous_grab.grab_set()
|
||||
if previous_focus is not None and previous_focus.winfo_exists():
|
||||
previous_focus.focus_set()
|
||||
except tk.TclError:
|
||||
pass
|
||||
if owned_root is not None:
|
||||
owned_root.destroy()
|
||||
return "ok"
|
||||
65
fix_barcode_documento_fisso_f1_f2.md
Normal file
65
fix_barcode_documento_fisso_f1_f2.md
Normal file
@@ -0,0 +1,65 @@
|
||||
# Documento fisso durante il ciclo barcode F1/F2
|
||||
|
||||
## Difetto e requisito
|
||||
|
||||
Prima della correzione ogni avanzamento interrogava tutte le UDC con IDStato
|
||||
uguale alla priorita' richiesta. Per F2, che include tutte le liste non
|
||||
prenotate, il documento poteva quindi cambiare senza intervento dell'operatore.
|
||||
|
||||
Una volta proposta una lista, ogni successiva UDC del ciclo deve appartenere
|
||||
a quel documento. F1 e F2 ricordano ciascuno la propria lista: F2 -> F1 -> F2
|
||||
deve riportare al documento inizialmente assegnato a F2, anche se cambia
|
||||
l'ordine globale delle UDC disponibili.
|
||||
|
||||
## Implementazione locale
|
||||
|
||||
- BarcodeService conserva un documento per priorita', separato dallo stato
|
||||
visuale temporaneo di conferma o pausa.
|
||||
- La prima richiesta senza documento usa il criterio di ordinamento vigente.
|
||||
Non viene introdotta una selezione per data del documento.
|
||||
- Le successive richieste applicano il filtro Documento nelle query di
|
||||
avanzamento, ricerca skip e ricerca della UDC per conferma del movimento.
|
||||
- Un documento differente ricevuto dal repository causa un errore esplicito.
|
||||
- La pausa per movimenti liberi e il passaggio tra F1/F2 conservano i documenti.
|
||||
- Quando termina il documento, il ciclo si ferma e mostra il relativo messaggio.
|
||||
Una successiva pressione esplicita di un tasto priorita' puo' avviare un nuovo
|
||||
ciclo; la fine del precedente non attiva automaticamente un altro documento.
|
||||
- Quando rimangono soltanto UDC saltate, viene gestita la sospensione della
|
||||
lista corrente senza passare a un'altra lista disponibile nella coda.
|
||||
- Se cambiano prenotazione o visibilita' e ci sono ancora residui nello storico,
|
||||
compare un messaggio di verifica e il documento viene mantenuto in memoria.
|
||||
- Un errore della query non cancella il documento memorizzato.
|
||||
|
||||
Gli skip sono conteggiati soltanto se la relativa UDC e' ancora residua.
|
||||
Le movimentazioni libere mantengono la loro logica; il filtro Documento e'
|
||||
applicato soltanto alle ricerche nel contesto del picking.
|
||||
|
||||
## Limiti e installazione
|
||||
|
||||
Questa correzione riguarda la sessione del terminalino. La memoria dei documenti
|
||||
viene azzerata con reset del servizio o riavvio del programma. Non introduce
|
||||
ancora due prenotazioni persistenti o un percorso automatico comune per colonna:
|
||||
questi appartengono alla successiva modifica funzionale da specificare.
|
||||
|
||||
Non serve una patch SQL: cambiano le SELECT eseguite dal codice Python, non gli
|
||||
oggetti del database. Versioni: barcode_client 1.0.27 (titolo visibile),
|
||||
barcode_repository 1.0.14, barcode_service 1.0.25.
|
||||
|
||||
## Verifiche
|
||||
|
||||
Esecuzione senza GUI e senza movimentazioni reali:
|
||||
|
||||
```bat
|
||||
python -m unittest discover -s tests -p test_barcode_document_binding.py -v
|
||||
```
|
||||
|
||||
Gli 11 test coprono avanzamento con documenti intercalati, passaggi ripetuti
|
||||
F2/F1/F2, pausa con movimento libero, salto UDC, sospensione con soli skip,
|
||||
fine lista, cambio prenotazione, errore query, rifiuto di documento inatteso,
|
||||
isolamento della conferma e passaggio del parametro al repository.
|
||||
|
||||
Ulteriori 5 verifiche SELECT su SQL Server, con righe sintetiche in CTE,
|
||||
hanno controllato selezione iniziale, filtro documento, assenza di fallback,
|
||||
skip effettivamente residui e isolamento della conferma. Nessun dato reale
|
||||
e' stato aggiornato per questi test. Il collaudo fisico sul terminalino resta
|
||||
da effettuare.
|
||||
@@ -19,8 +19,10 @@ from typing import Any, Callable, Optional
|
||||
import customtkinter as ctk
|
||||
|
||||
from async_loop_singleton import get_global_loop
|
||||
from runtime_support import log_exception
|
||||
from version_info import module_version
|
||||
|
||||
__VERSION__ = "GestioneAreeFrame v3.3.0-singleloop"
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
try:
|
||||
from async_msssql_query import AsyncMSSQLClient # noqa: F401
|
||||
@@ -127,21 +129,53 @@ class AsyncRunner:
|
||||
busy.show(message)
|
||||
fut = asyncio.run_coroutine_threadsafe(awaitable, self.loop)
|
||||
|
||||
def _widget_alive() -> bool:
|
||||
try:
|
||||
return bool(self.widget.winfo_exists())
|
||||
except tk.TclError:
|
||||
return False
|
||||
|
||||
def _dispatch_success(res: Any) -> None:
|
||||
try:
|
||||
on_success(res)
|
||||
except BaseException as ex:
|
||||
log_exception(__name__, ex, context="AsyncRunner on_success")
|
||||
|
||||
def _dispatch_error(ex: BaseException) -> None:
|
||||
if on_error:
|
||||
try:
|
||||
on_error(ex)
|
||||
except BaseException as callback_ex:
|
||||
log_exception(__name__, callback_ex, context="AsyncRunner on_error")
|
||||
else:
|
||||
log_exception(__name__, ex, context="AsyncRunner unhandled error")
|
||||
|
||||
def _poll():
|
||||
if not _widget_alive():
|
||||
return
|
||||
if fut.done():
|
||||
if busy:
|
||||
busy.hide()
|
||||
try:
|
||||
busy.hide()
|
||||
except Exception as ex:
|
||||
log_exception(__name__, ex, context="AsyncRunner hide busy")
|
||||
try:
|
||||
res = fut.result()
|
||||
except BaseException as ex:
|
||||
if on_error:
|
||||
self.widget.after(0, lambda e=ex: on_error(e))
|
||||
else:
|
||||
print("[AsyncRunner] Unhandled error:", repr(ex))
|
||||
try:
|
||||
self.widget.after(0, lambda e=ex: _dispatch_error(e))
|
||||
except tk.TclError:
|
||||
log_exception(__name__, ex, context="AsyncRunner error after destroyed")
|
||||
else:
|
||||
self.widget.after(0, lambda r=res: on_success(r))
|
||||
try:
|
||||
self.widget.after(0, lambda r=res: _dispatch_success(r))
|
||||
except tk.TclError as ex:
|
||||
log_exception(__name__, ex, context="AsyncRunner success after destroyed")
|
||||
else:
|
||||
self.widget.after(60, _poll)
|
||||
try:
|
||||
self.widget.after(60, _poll)
|
||||
except tk.TclError:
|
||||
return
|
||||
|
||||
_poll()
|
||||
|
||||
|
||||
@@ -10,7 +10,8 @@ import json
|
||||
import logging
|
||||
import sys
|
||||
import tkinter as tk
|
||||
from tkinter import Menu, messagebox, filedialog, simpledialog
|
||||
import error_dialog as messagebox
|
||||
from tkinter import Menu, filedialog, simpledialog
|
||||
import customtkinter as ctk
|
||||
from datetime import datetime
|
||||
from functools import wraps
|
||||
@@ -26,8 +27,11 @@ from tksheet import Sheet, natural_sort_key
|
||||
from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text
|
||||
from ui_theme import theme_color, theme_font, theme_section, theme_value
|
||||
from user_session import UserSession
|
||||
from version_info import module_version, versioned_title
|
||||
from window_placement import place_window_fullsize_below_parent_later
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
try:
|
||||
from loguru import logger
|
||||
except Exception: # pragma: no cover - fallback used only when Loguru is not available
|
||||
@@ -212,7 +216,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
self._theme = theme_section("layout_window", {})
|
||||
self._locale_catalog = load_locale_catalog()
|
||||
self._tooltip_catalog = load_tooltip_catalog()
|
||||
self.title(loc_text("layout.title", catalog=self._locale_catalog, default="Layout corsie"))
|
||||
self.title(versioned_title(loc_text("layout.title", catalog=self._locale_catalog, default="Layout corsie"), __name__))
|
||||
self.geometry(str(theme_value(self._theme, "window_geometry", "1200x740")))
|
||||
minsize = theme_value(self._theme, "window_minsize", [980, 560])
|
||||
self.minsize(int(minsize[0]), int(minsize[1]))
|
||||
@@ -604,6 +608,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
)
|
||||
m.add_separator()
|
||||
m.add_command(label="Copia ubicazione", command=lambda: self._copy(label))
|
||||
m.add_command(label="Codice cella", command=lambda: self._show_cell_code(r, c))
|
||||
x = self.winfo_pointerx() if event is None else event.x_root
|
||||
y = self.winfo_pointery() if event is None else event.y_root
|
||||
m.tk_popup(x, y)
|
||||
@@ -645,6 +650,25 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
def _show_cell_code(self, r: int, c: int) -> None:
|
||||
"""Show the internal cell code for the selected layout cell."""
|
||||
|
||||
idcella = self._cell_id(r, c)
|
||||
ubicazione = self._cell_label(r, c)
|
||||
barcode_cella = self._cell_barcode(r, c)
|
||||
if idcella <= 0:
|
||||
messagebox.showwarning(
|
||||
"Codice cella",
|
||||
f"Codice cella non disponibile per {ubicazione}.",
|
||||
parent=self,
|
||||
)
|
||||
return
|
||||
messagebox.showinfo(
|
||||
"Codice cella",
|
||||
f"Ubicazione: {ubicazione}\nCodice cella: {idcella}\nBarcode cella: {barcode_cella or idcella}",
|
||||
parent=self,
|
||||
)
|
||||
|
||||
@_log_call()
|
||||
def _prompt_carico(self, r: int, c: int):
|
||||
"""Prompt the operator for a pallet barcode and move it to the selected cell."""
|
||||
@@ -678,27 +702,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
if stato <= 0:
|
||||
self._toast("La cella selezionata non contiene alcuna UDC da scaricare.")
|
||||
return
|
||||
if stato >= 2:
|
||||
self._open_scarico_dialog(r, c)
|
||||
return
|
||||
|
||||
barcode = str(self.udc1[r][c] or "").strip()
|
||||
if not barcode:
|
||||
self._toast("UDC non disponibile per lo scarico.")
|
||||
return
|
||||
if not messagebox.askyesno(
|
||||
"Scarico",
|
||||
f"Scaricare l'UDC {barcode} da {self._cell_label(r, c)}?",
|
||||
parent=self,
|
||||
):
|
||||
return
|
||||
self._run_pallet_move(
|
||||
barcode_pallet=barcode,
|
||||
target_idcella=9999,
|
||||
target_barcode_cella="9000000",
|
||||
success_message=f"Scarico completato per {barcode}.",
|
||||
busy_message=f"Scarico {barcode}...",
|
||||
)
|
||||
self._open_scarico_dialog(r, c)
|
||||
|
||||
@_log_call()
|
||||
def _run_pallet_move(
|
||||
@@ -747,7 +751,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
target=target_barcode_cella,
|
||||
details={"barcode_pallet": barcode_pallet, "error": str(ex)},
|
||||
)
|
||||
messagebox.showerror("Movimento UDC", f"Operazione fallita:\n{ex}", parent=self)
|
||||
messagebox.showerror("Movimento UDC", f"Operazione fallita:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
self._async.run(
|
||||
move_pallet_async(
|
||||
@@ -835,7 +839,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
target=self._cell_label(r, c),
|
||||
details={"idcella": idcella, "stato": int(stato), "error": str(ex)},
|
||||
)
|
||||
messagebox.showerror("Prenotazione", f"Aggiornamento fallito:\n{ex}", parent=self)
|
||||
messagebox.showerror("Prenotazione", f"Aggiornamento fallito:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
self._async.run(
|
||||
self.db.exec(SQL_SET_CELL_PRENOTAZIONE, params, commit=True),
|
||||
@@ -896,7 +900,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
target=self._cell_label(r, c),
|
||||
details={"idcella": idcella, "stato": int(stato), "error": str(ex)},
|
||||
)
|
||||
messagebox.showerror("Stato cella", f"Aggiornamento fallito:\n{ex}", parent=self)
|
||||
messagebox.showerror("Stato cella", f"Aggiornamento fallito:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
self._async.run(
|
||||
self.db.exec(SQL_SET_CELL_PRENOTAZIONE, params, commit=True),
|
||||
@@ -997,7 +1001,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
return
|
||||
self._busy.hide()
|
||||
_MODULE_LOGGER.exception(f"Errore caricamento corsie: {ex}")
|
||||
messagebox.showerror("Errore", f"Caricamento corsie fallito:\n{ex}")
|
||||
messagebox.showerror("Errore", f"Caricamento corsie fallito:\n{ex}", exception=ex)
|
||||
self._async.run(self.db.query_json(sql, {}), _ok, _err, busy=self._busy, message="Carico corsie…")
|
||||
|
||||
@_log_call()
|
||||
@@ -1176,7 +1180,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
return
|
||||
self._busy.hide()
|
||||
_MODULE_LOGGER.exception(f"Errore caricamento matrice corsia={corsia}: {ex}")
|
||||
messagebox.showerror("Errore", f"Caricamento matrice {corsia} fallito:\n{ex}")
|
||||
messagebox.showerror("Errore", f"Caricamento matrice {corsia} fallito:\n{ex}", exception=ex)
|
||||
self._async.run(self.db.query_json(sql, {"corsia": corsia}), _ok, _err, busy=self._busy, message=f"Carico corsia {corsia}…")
|
||||
|
||||
# ---------------- SEARCH ----------------
|
||||
@@ -1230,7 +1234,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
if search_req_id < self._last_req:
|
||||
return
|
||||
_MODULE_LOGGER.exception(f"Errore ricerca UDC barcode={barcode}: {ex}")
|
||||
messagebox.showerror("Ricerca", f"Errore ricerca UDC:\n{ex}", parent=self)
|
||||
messagebox.showerror("Ricerca", f"Errore ricerca UDC:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
self._async.run(self.db.query_json(sql, {"barcode": barcode}), _ok, _err, busy=self._busy, message="Cerco UDC…")
|
||||
|
||||
@@ -1280,7 +1284,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import PatternFill, Alignment, Font
|
||||
except Exception as ex:
|
||||
messagebox.showerror("Export", f"Manca openpyxl: {ex}\nInstalla con: pip install openpyxl")
|
||||
messagebox.showerror("Export", f"Manca openpyxl: {ex}\nInstalla con: pip install openpyxl", exception=ex)
|
||||
return
|
||||
rows = len(self.matrix_state)
|
||||
cols = len(self.matrix_state[0]) if self.matrix_state else 0
|
||||
@@ -1314,7 +1318,7 @@ class LayoutWindow(ctk.CTkToplevel):
|
||||
wb.save(path)
|
||||
self._toast(f"Esportato: {path}")
|
||||
except Exception as ex:
|
||||
messagebox.showerror("Export", f"Salvataggio fallito:\n{ex}")
|
||||
messagebox.showerror("Export", f"Salvataggio fallito:\n{ex}", exception=ex)
|
||||
|
||||
# ---------------- STATS ----------------
|
||||
def _refresh_stats(self):
|
||||
|
||||
@@ -10,7 +10,7 @@ import json
|
||||
import sys
|
||||
import tkinter as tk
|
||||
import customtkinter as ctk
|
||||
from tkinter import messagebox
|
||||
import error_dialog as messagebox
|
||||
from typing import Optional, Any, Dict, List, Callable
|
||||
from dataclasses import dataclass
|
||||
from functools import wraps
|
||||
@@ -70,8 +70,20 @@ from busy_overlay import InlineBusyOverlay
|
||||
from gestione_aree import AsyncRunner
|
||||
from locale_text import load_locale_catalog, text as loc_text
|
||||
from ui_theme import theme_color, theme_font, theme_section, theme_value
|
||||
from ui_tables import (
|
||||
TABLE_HEADER_BG,
|
||||
TABLE_HEADER_FG,
|
||||
TABLE_ROW_EVEN,
|
||||
TABLE_ROW_ODD,
|
||||
apply_tksheet_visual_style,
|
||||
apply_tksheet_zebra,
|
||||
)
|
||||
from user_session import UserSession
|
||||
from version_info import module_version, versioned_title
|
||||
from window_placement import place_window_fullsize_below_parent_later
|
||||
from pickinglist_sequence import open_pickinglist_sequence_window
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
# === IMPORT procedura async prenota/s-prenota (no pyodbc qui) ===
|
||||
import asyncio
|
||||
@@ -198,9 +210,12 @@ if _MODULE_LOG_ENABLED:
|
||||
|
||||
|
||||
# -------------------- SQL --------------------
|
||||
# Operational picking-list management uses the Python-only residual view.
|
||||
# Unlike the historical view, this dataset intentionally contains only UDCs
|
||||
# that still have to be exhausted by the warehouse workflow.
|
||||
SQL_PL = """
|
||||
SELECT
|
||||
COUNT(DISTINCT Pallet) AS Pallet,
|
||||
COUNT(DISTINCT NULLIF(LTRIM(RTRIM(CAST(Pallet AS varchar(32)))), '')) AS Pallet,
|
||||
COUNT(DISTINCT Lotto) AS Lotto,
|
||||
COUNT(DISTINCT Articolo) AS Articolo,
|
||||
COUNT(DISTINCT Descrizione) AS Descrizione,
|
||||
@@ -213,18 +228,21 @@ SELECT
|
||||
MAX(Magazzino) AS Magazzino,
|
||||
MAX(Area) AS Area,
|
||||
MAX(Cella) AS Cella,
|
||||
MIN(OrdinePrelievoGruppo) AS OrdinePrelievoGruppo,
|
||||
MIN(Ordinamento) AS Ordinamento,
|
||||
MAX(IDStato) AS IDStato
|
||||
FROM dbo.py_ViewPackingListRestante
|
||||
FROM dbo.py_ViewPackingListPrelievo
|
||||
WHERE DataDocumento > CAST((GETDATE() - :days) AS int)
|
||||
GROUP BY Documento, CodNazione, NAZIONE, Stato
|
||||
ORDER BY MIN(Ordinamento), Documento, NAZIONE, Stato;
|
||||
ORDER BY MIN(OrdinePrelievoGruppo), MIN(Ordinamento), Documento, NAZIONE, Stato;
|
||||
"""
|
||||
|
||||
SQL_PL_DETAILS = """
|
||||
SELECT *
|
||||
FROM dbo.py_ViewPackingListRestante
|
||||
FROM dbo.py_ViewPackingListPrelievo
|
||||
WHERE Documento = :Documento
|
||||
ORDER BY Ordinamento;
|
||||
AND DataDocumento > CAST((GETDATE() - :days) AS int)
|
||||
ORDER BY OrdinePrelievoGruppo, Ordinamento, Pallet;
|
||||
"""
|
||||
|
||||
# -------------------- helpers --------------------
|
||||
@@ -314,6 +332,8 @@ DET_COLS: List[ColSpec] = [
|
||||
]
|
||||
|
||||
ROW_H = 28
|
||||
RESERVED_IDSTATO_BG = "#dc2626"
|
||||
RESERVED_IDSTATO_FG = "#ffffff"
|
||||
|
||||
|
||||
# -------------------- Micro spinner (toolbar) --------------------
|
||||
@@ -388,13 +408,14 @@ class ScrollTable(ctk.CTkFrame):
|
||||
self._sort_key: Optional[str] = None
|
||||
self._sort_reverse = False
|
||||
self.total_w = sum(c.width for c in self.columns)
|
||||
self._vbar_visible = False
|
||||
|
||||
self.grid_rowconfigure(1, weight=1)
|
||||
self.grid_columnconfigure(0, weight=1)
|
||||
|
||||
# header
|
||||
self.h_canvas = tk.Canvas(self, height=ROW_H, highlightthickness=0, bd=0)
|
||||
self.h_inner = ctk.CTkFrame(self.h_canvas, fg_color="#f3f3f3",
|
||||
self.h_canvas = tk.Canvas(self, height=ROW_H, highlightthickness=0, bd=0, bg=TABLE_HEADER_BG)
|
||||
self.h_inner = ctk.CTkFrame(self.h_canvas, fg_color=TABLE_HEADER_BG,
|
||||
height=ROW_H, width=self.total_w)
|
||||
self.h_canvas.create_window((0,0), window=self.h_inner, anchor="nw",
|
||||
width=self.total_w, height=ROW_H)
|
||||
@@ -411,7 +432,6 @@ class ScrollTable(ctk.CTkFrame):
|
||||
# scrollbars
|
||||
self.vbar = tk.Scrollbar(self, orient="vertical", command=self.b_canvas.yview)
|
||||
self.xbar = tk.Scrollbar(self, orient="horizontal", command=self._xscroll_both)
|
||||
self.vbar.grid(row=1, column=1, sticky="ns")
|
||||
self.xbar.grid(row=2, column=0, sticky="ew")
|
||||
|
||||
# link scroll
|
||||
@@ -433,14 +453,14 @@ class ScrollTable(ctk.CTkFrame):
|
||||
for w in self.h_inner.winfo_children():
|
||||
w.destroy()
|
||||
|
||||
row = ctk.CTkFrame(self.h_inner, fg_color="#f3f3f3",
|
||||
row = ctk.CTkFrame(self.h_inner, fg_color=TABLE_HEADER_BG,
|
||||
height=ROW_H, width=self.total_w)
|
||||
row.pack(fill="x", expand=False)
|
||||
row.pack_propagate(False)
|
||||
|
||||
for col in self.columns:
|
||||
holder = ctk.CTkFrame(
|
||||
row, fg_color="#f3f3f3",
|
||||
row, fg_color=TABLE_HEADER_BG,
|
||||
width=col.width, height=ROW_H,
|
||||
border_width=1, border_color=self.GRID_COLOR
|
||||
)
|
||||
@@ -451,7 +471,7 @@ class ScrollTable(ctk.CTkFrame):
|
||||
if col.key == self._sort_key:
|
||||
header_text = f"{col.title} {'↓' if self._sort_reverse else '↑'}"
|
||||
|
||||
lbl = ctk.CTkLabel(holder, text=header_text, anchor="w")
|
||||
lbl = ctk.CTkLabel(holder, text=header_text, anchor="w", text_color=TABLE_HEADER_FG)
|
||||
lbl.pack(fill="both", padx=(self.PADX_L, self.PADX_R), pady=self.PADY)
|
||||
|
||||
if self.on_header_click and col.key != "__check__":
|
||||
@@ -472,10 +492,27 @@ class ScrollTable(ctk.CTkFrame):
|
||||
"""Keep the scroll region aligned with the current body content width."""
|
||||
self.b_canvas.itemconfigure(self.body_window, width=self.total_w)
|
||||
sr = self.b_canvas.bbox("all")
|
||||
content_height = int(sr[3]) if sr else 0
|
||||
if sr:
|
||||
self.b_canvas.configure(scrollregion=(0,0,max(self.total_w, sr[2]), sr[3]))
|
||||
else:
|
||||
self.b_canvas.configure(scrollregion=(0,0,self.total_w,0))
|
||||
self._update_vertical_scrollbar(content_height)
|
||||
|
||||
def _update_vertical_scrollbar(self, content_height: int):
|
||||
"""Show the vertical scrollbar only when body rows exceed the visible area."""
|
||||
try:
|
||||
visible_height = max(1, int(self.b_canvas.winfo_height()))
|
||||
except Exception:
|
||||
visible_height = 1
|
||||
needs_scroll = content_height > visible_height + 2
|
||||
if needs_scroll and not self._vbar_visible:
|
||||
self.vbar.grid(row=1, column=1, sticky="ns")
|
||||
self._vbar_visible = True
|
||||
elif not needs_scroll and self._vbar_visible:
|
||||
self.vbar.grid_remove()
|
||||
self._vbar_visible = False
|
||||
self.b_canvas.yview_moveto(0)
|
||||
|
||||
def _on_body_configure(self):
|
||||
"""React to body resize events by syncing dimensions and header scroll."""
|
||||
@@ -510,8 +547,11 @@ class ScrollTable(ctk.CTkFrame):
|
||||
delta = getattr(event, "delta", 0)
|
||||
if delta == 0:
|
||||
return
|
||||
if not self._vbar_visible:
|
||||
return "break"
|
||||
step = -1 if delta > 0 else 1
|
||||
self.b_canvas.yview_scroll(step, "units")
|
||||
return "break"
|
||||
|
||||
def clear_rows(self):
|
||||
"""Remove all rendered body rows."""
|
||||
@@ -525,16 +565,20 @@ class ScrollTable(ctk.CTkFrame):
|
||||
row_index: int,
|
||||
anchors: Optional[List[str]] = None,
|
||||
checkbox_builder: Optional[Callable[[tk.Widget], ctk.CTkCheckBox]] = None,
|
||||
cell_bg: Optional[Dict[str, str]] = None,
|
||||
cell_fg: Optional[Dict[str, str]] = None,
|
||||
):
|
||||
"""Append one row to the table body."""
|
||||
row = ctk.CTkFrame(self.b_inner, fg_color="transparent",
|
||||
row_bg = TABLE_ROW_EVEN if row_index % 2 == 0 else TABLE_ROW_ODD
|
||||
row = ctk.CTkFrame(self.b_inner, fg_color=row_bg,
|
||||
height=ROW_H, width=self.total_w)
|
||||
row.pack(fill="x", expand=False)
|
||||
row.pack_propagate(False)
|
||||
|
||||
for i, col in enumerate(self.columns):
|
||||
holder_bg = (cell_bg or {}).get(col.key, row_bg)
|
||||
holder = ctk.CTkFrame(
|
||||
row, fg_color="transparent",
|
||||
row, fg_color=holder_bg,
|
||||
width=col.width, height=ROW_H,
|
||||
border_width=1, border_color=self.GRID_COLOR
|
||||
)
|
||||
@@ -546,10 +590,17 @@ class ScrollTable(ctk.CTkFrame):
|
||||
cb = checkbox_builder(holder)
|
||||
cb.pack(padx=(self.PADX_L, self.PADX_R), pady=self.PADY, anchor="w")
|
||||
else:
|
||||
ctk.CTkLabel(holder, text="").pack(fill="both")
|
||||
ctk.CTkLabel(holder, text="", fg_color=holder_bg).pack(fill="both")
|
||||
else:
|
||||
anchor = (anchors[i] if anchors else col.anchor)
|
||||
ctk.CTkLabel(holder, text=values[i], anchor=anchor).pack(
|
||||
ctk.CTkLabel(
|
||||
holder,
|
||||
text=values[i],
|
||||
anchor=anchor,
|
||||
fg_color=holder_bg,
|
||||
text_color=(cell_fg or {}).get(col.key, "#111827"),
|
||||
font=("Segoe UI", 10, "bold") if col.key == "IDStato" and col.key in (cell_bg or {}) else None,
|
||||
).pack(
|
||||
fill="both", padx=(self.PADX_L, self.PADX_R), pady=self.PADY
|
||||
)
|
||||
|
||||
@@ -602,6 +653,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
self.rows_models: list[PLRow] = []
|
||||
self._detail_cache: Dict[Any, list] = {}
|
||||
self.detail_doc = None
|
||||
self.days_var = tk.StringVar(value="10")
|
||||
self._detail_sort_key: Optional[str] = None
|
||||
self._detail_sort_reverse = False
|
||||
self._detail_sorting = False
|
||||
@@ -652,6 +704,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
(loc_text("picking.button.reload", catalog=self._locale_catalog, default="Ricarica"), self.reload_from_db),
|
||||
(loc_text("picking.button.prenota", catalog=self._locale_catalog, default="Prenota"), self.on_prenota),
|
||||
(loc_text("picking.button.sprenota", catalog=self._locale_catalog, default="S-prenota"), self.on_sprenota),
|
||||
(loc_text("picking.button.sequence", catalog=self._locale_catalog, default="Sequenza di prelievo"), self.on_sequence),
|
||||
(loc_text("picking.button.export", catalog=self._locale_catalog, default="Esporta XLSX"), self.on_export)
|
||||
]):
|
||||
ctk.CTkButton(
|
||||
@@ -661,6 +714,20 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
font=theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold")),
|
||||
).grid(row=0, column=i, padx=6)
|
||||
|
||||
ctk.CTkLabel(
|
||||
top,
|
||||
text=loc_text("picking.label.days", catalog=self._locale_catalog, default="Giorni:"),
|
||||
font=theme_font(self._theme, "toolbar_label_font", ("Segoe UI", 10)),
|
||||
).grid(row=0, column=5, padx=(18, 4), sticky="e")
|
||||
ctk.CTkOptionMenu(
|
||||
top,
|
||||
values=["10", "15", "20", "30"],
|
||||
variable=self.days_var,
|
||||
width=82,
|
||||
command=lambda _value: self.reload_from_db(),
|
||||
font=theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold")),
|
||||
).grid(row=0, column=6, padx=(0, 6), sticky="w")
|
||||
|
||||
# --- micro spinner a destra della toolbar ---
|
||||
self.spinner = ToolbarSpinner(top)
|
||||
self.spinner.widget().grid(row=0, column=10, padx=(8,0)) # largo spazio a destra
|
||||
@@ -693,6 +760,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
self.detail_sheet.change_theme("light green")
|
||||
self.detail_sheet.enable_bindings("all")
|
||||
self.detail_sheet.headers(self._detail_headers(), redraw=False)
|
||||
apply_tksheet_visual_style(self.detail_sheet)
|
||||
self.detail_sheet.bind("<ButtonRelease-1>", self._on_detail_sheet_left_click, add="+")
|
||||
self.detail_sheet.grid(row=0, column=0, sticky="nsew")
|
||||
|
||||
@@ -733,8 +801,10 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
data,
|
||||
reset_col_positions=True,
|
||||
reset_row_positions=True,
|
||||
redraw=True,
|
||||
redraw=False,
|
||||
)
|
||||
apply_tksheet_visual_style(self.detail_sheet)
|
||||
apply_tksheet_zebra(self.detail_sheet, len(data))
|
||||
self.detail_sheet.set_all_column_widths()
|
||||
|
||||
def _detail_sort_value(self, row: Dict[str, Any], key: str):
|
||||
@@ -838,10 +908,22 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
try:
|
||||
for idx, d in enumerate(rows):
|
||||
row_widget = self.pl_table.b_inner.winfo_children()[idx]
|
||||
if int(d.get("IDStato") or 0) == 1:
|
||||
row_widget.configure(fg_color="#ffe6f2") # rosa tenue
|
||||
else:
|
||||
row_widget.configure(fg_color="transparent")
|
||||
row_bg = TABLE_ROW_EVEN if idx % 2 == 0 else TABLE_ROW_ODD
|
||||
row_widget.configure(fg_color=row_bg)
|
||||
row_children = row_widget.winfo_children()
|
||||
if len(row_children) >= 5:
|
||||
holder = row_children[4]
|
||||
is_reserved = int(d.get("IDStato") or 0) == 1
|
||||
holder_bg = RESERVED_IDSTATO_BG if is_reserved else row_bg
|
||||
holder.configure(fg_color=holder_bg)
|
||||
if holder.winfo_children():
|
||||
lbl = holder.winfo_children()[0]
|
||||
if hasattr(lbl, "configure"):
|
||||
lbl.configure(
|
||||
fg_color=holder_bg,
|
||||
text_color=RESERVED_IDSTATO_FG if is_reserved else "#111827",
|
||||
font=("Segoe UI", 10, "bold") if is_reserved else ("Segoe UI", 10),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -868,7 +950,9 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
values=values,
|
||||
row_index=r,
|
||||
anchors=[c.anchor for c in PL_COLS],
|
||||
checkbox_builder=model.build_checkbox
|
||||
checkbox_builder=model.build_checkbox,
|
||||
cell_bg={"IDStato": RESERVED_IDSTATO_BG} if int(d.get("IDStato") or 0) == 1 else None,
|
||||
cell_fg={"IDStato": RESERVED_IDSTATO_FG} if int(d.get("IDStato") or 0) == 1 else None,
|
||||
)
|
||||
|
||||
# 🎯 Colora dopo che la UI è resa → no balzi visivi
|
||||
@@ -894,29 +978,62 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
row_children = row_widget.winfo_children()
|
||||
if len(row_children) >= 5:
|
||||
holder = row_children[4]
|
||||
holder.configure(fg_color=RESERVED_IDSTATO_BG if idstato == 1 else (
|
||||
TABLE_ROW_EVEN if idx % 2 == 0 else TABLE_ROW_ODD
|
||||
))
|
||||
if holder.winfo_children():
|
||||
lbl = holder.winfo_children()[0]
|
||||
if hasattr(lbl, "configure"):
|
||||
lbl.configure(text=str(idstato))
|
||||
lbl.configure(
|
||||
text=str(idstato),
|
||||
fg_color=RESERVED_IDSTATO_BG if idstato == 1 else (
|
||||
TABLE_ROW_EVEN if idx % 2 == 0 else TABLE_ROW_ODD
|
||||
),
|
||||
text_color=RESERVED_IDSTATO_FG if idstato == 1 else "#111827",
|
||||
font=("Segoe UI", 10, "bold") if idstato == 1 else ("Segoe UI", 10),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# differisci la colorazione (smooth)
|
||||
self.after_idle(_paint)
|
||||
break
|
||||
|
||||
def _reselect_documento_after_reload(self, documento: str):
|
||||
"""(Opzionale) Dopo un reload DB, riseleziona la PL con lo stesso Documento."""
|
||||
def _reselect_documento_after_reload(self, documento: str) -> bool:
|
||||
"""After a reload, reselect the same document and reload its details."""
|
||||
for m in self.rows_models:
|
||||
if _s(m.pl.get("Documento")) == _s(documento):
|
||||
self._detail_cache.pop(documento, None)
|
||||
m.set_checked(True)
|
||||
self.on_row_checked(m, True)
|
||||
break
|
||||
return True
|
||||
return False
|
||||
|
||||
def _selected_documento_for_reload(self) -> str | None:
|
||||
"""Return the document that should survive a toolbar reload."""
|
||||
|
||||
selected = self._get_selected_model()
|
||||
if selected is not None:
|
||||
documento = _s(selected.pl.get("Documento"))
|
||||
return documento or None
|
||||
documento = _s(self.detail_doc)
|
||||
return documento or None
|
||||
|
||||
def _selected_days(self) -> int:
|
||||
"""Return the selected look-back interval for operational picking lists."""
|
||||
|
||||
try:
|
||||
days = int(str(self.days_var.get()).strip())
|
||||
except Exception:
|
||||
days = 10
|
||||
return days if days in (10, 15, 20, 30) else 10
|
||||
|
||||
# ----- eventi -----
|
||||
@_log_call()
|
||||
def on_row_checked(self, model: PLRow, is_checked: bool):
|
||||
"""Handle row selection changes and refresh the detail section."""
|
||||
# selezione esclusiva
|
||||
# Only one backoffice picking list can be selected at a time. Barcode
|
||||
# F1/F2 priority behavior is derived downstream; this UI controls only
|
||||
# the explicit Python reservation slot.
|
||||
if is_checked:
|
||||
for m in self.rows_models:
|
||||
if m is not model and m.is_checked():
|
||||
@@ -925,10 +1042,12 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
self.detail_doc = model.pl.get("Documento")
|
||||
_MODULE_LOGGER.info(f"Documento selezionato per il dettaglio: {self.detail_doc}")
|
||||
self.spinner.start(" Carico dettagli…") # spinner ON
|
||||
days = self._selected_days()
|
||||
|
||||
async def _job():
|
||||
_log_sql("SQL_PL_DETAILS", SQL_PL_DETAILS, {"Documento": self.detail_doc})
|
||||
return await self.db_client.query_json(SQL_PL_DETAILS, {"Documento": self.detail_doc})
|
||||
params = {"Documento": self.detail_doc, "days": days}
|
||||
_log_sql("SQL_PL_DETAILS", SQL_PL_DETAILS, params)
|
||||
return await self.db_client.query_json(SQL_PL_DETAILS, params)
|
||||
|
||||
def _ok(res):
|
||||
# NON fermare lo spinner subito: lo farà _refresh_details_incremental
|
||||
@@ -942,7 +1061,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
_MODULE_LOGGER.exception(f"Errore durante il caricamento dettagli del documento {self.detail_doc}: {ex}")
|
||||
self.spinner.stop()
|
||||
self.busy.hide() # Chiudi l'overlay in caso di errore
|
||||
messagebox.showerror("DB", f"Errore nel caricamento dettagli:\n{ex}")
|
||||
messagebox.showerror("DB", f"Errore nel caricamento dettagli:\n{ex}", exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_job(),
|
||||
@@ -964,17 +1083,34 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
@_log_call()
|
||||
def reload_from_db(self, first: bool = False, reselect_documento: str | None = None):
|
||||
"""Load or reload the picking list summary table from the database."""
|
||||
if reselect_documento is None and not first:
|
||||
# Preserve the operator context while the barcode may be consuming
|
||||
# rows: Ricarica refreshes master and detail but keeps the selected
|
||||
# document selected when it is still visible.
|
||||
reselect_documento = self._selected_documento_for_reload()
|
||||
self.spinner.start(" Carico…") # spinner ON
|
||||
days = self._selected_days()
|
||||
async def _job():
|
||||
_log_sql("SQL_PL", SQL_PL, {})
|
||||
return await self.db_client.query_json(SQL_PL, {})
|
||||
params = {"days": days}
|
||||
_log_sql("SQL_PL", SQL_PL, params)
|
||||
return await self.db_client.query_json(SQL_PL, params)
|
||||
def _on_success(res):
|
||||
rows = _rows_to_dicts(res)
|
||||
_log_dataset("SQL_PL", rows)
|
||||
self._refresh_mid_rows(rows)
|
||||
if reselect_documento:
|
||||
self.after_idle(lambda doc=reselect_documento: self._reselect_documento_after_reload(doc))
|
||||
self.spinner.stop() # spinner OFF
|
||||
def _reselect_or_clear(doc=reselect_documento):
|
||||
found = self._reselect_documento_after_reload(doc)
|
||||
if not found:
|
||||
self.detail_doc = None
|
||||
self._draw_details_hint()
|
||||
self.spinner.stop()
|
||||
self.busy.hide()
|
||||
self.after_idle(_reselect_or_clear)
|
||||
else:
|
||||
self.detail_doc = None
|
||||
self._draw_details_hint()
|
||||
self.spinner.stop() # spinner OFF
|
||||
# se era il primo load, ripristina il cursore standard
|
||||
if self._first_loading:
|
||||
try:
|
||||
@@ -991,7 +1127,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
except Exception:
|
||||
pass
|
||||
self._first_loading = False
|
||||
messagebox.showerror("DB", f"Errore nel caricamento:\n{ex}")
|
||||
messagebox.showerror("DB", f"Errore nel caricamento:\n{ex}", exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_job(),
|
||||
@@ -1053,6 +1189,45 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
self._load_detail_sheet_data(self._detail_rows_to_sheet_data(rows))
|
||||
|
||||
# ----- azioni -----
|
||||
@_log_call()
|
||||
def on_sequence(self):
|
||||
"""Open the pickup-sequence editor for the selected picking list."""
|
||||
|
||||
if not self._can("pickinglist.sequence"):
|
||||
messagebox.showwarning(
|
||||
loc_text("picking.sequence.title", catalog=self._locale_catalog, default="Sequenza di prelievo"),
|
||||
loc_text("picking.sequence.msg.denied", catalog=self._locale_catalog, default="Permesso negato."),
|
||||
parent=self,
|
||||
)
|
||||
return
|
||||
|
||||
model = self._get_selected_model()
|
||||
if not model:
|
||||
messagebox.showinfo(
|
||||
loc_text("picking.sequence.title", catalog=self._locale_catalog, default="Sequenza di prelievo"),
|
||||
loc_text(
|
||||
"picking.sequence.msg.select",
|
||||
catalog=self._locale_catalog,
|
||||
default="Seleziona una Picking List prima di definire la sequenza.",
|
||||
),
|
||||
parent=self,
|
||||
)
|
||||
return
|
||||
|
||||
documento = _s(model.pl.get("Documento"))
|
||||
|
||||
def _on_saved():
|
||||
self._detail_cache.pop(documento, None)
|
||||
self.reload_from_db(reselect_documento=documento)
|
||||
|
||||
open_pickinglist_sequence_window(
|
||||
self.winfo_toplevel(),
|
||||
self.db_client,
|
||||
documento=documento,
|
||||
session=self.session,
|
||||
on_saved=_on_saved,
|
||||
)
|
||||
|
||||
@_log_call()
|
||||
def on_prenota(self):
|
||||
"""Reserve the selected picking list."""
|
||||
@@ -1067,6 +1242,8 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
documento = _s(model.pl.get("Documento"))
|
||||
current = int(model.pl.get("IDStato") or 0)
|
||||
desired = 1
|
||||
# Idempotent semantics: Prenota never toggles a list off. If the list
|
||||
# is already reserved, S-prenota remains the only explicit release path.
|
||||
if current == desired:
|
||||
messagebox.showinfo("Prenota", f"La Picking List {documento} è già prenotata.")
|
||||
return
|
||||
@@ -1079,6 +1256,8 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
self.spinner.start(" Prenoto…")
|
||||
|
||||
async def _job():
|
||||
# Use the Python-specific py_* stored procedure so C# legacy
|
||||
# procedures can coexist unchanged on the same database.
|
||||
return await sp_xExePackingListPallet_async(self.db_client, id_operatore, documento, "P")
|
||||
|
||||
def _ok(res: SPResult):
|
||||
@@ -1117,7 +1296,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
target=documento,
|
||||
details={"error": str(ex)},
|
||||
)
|
||||
messagebox.showerror("Prenota", f"Errore:\n{ex}")
|
||||
messagebox.showerror("Prenota", f"Errore:\n{ex}", exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_job(),
|
||||
@@ -1141,6 +1320,8 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
documento = _s(model.pl.get("Documento"))
|
||||
current = int(model.pl.get("IDStato") or 0)
|
||||
desired = 0
|
||||
# Idempotent semantics: S-prenota never reserves a list; if the list is
|
||||
# already free, the operation is a no-op rather than an implicit toggle.
|
||||
if current == desired:
|
||||
messagebox.showinfo("S-prenota", f"La Picking List {documento} è già NON prenotata.")
|
||||
return
|
||||
@@ -1153,6 +1334,8 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
self.spinner.start(" S-prenoto…")
|
||||
|
||||
async def _job():
|
||||
# Same Python-only procedure as Prenota, with action S to release
|
||||
# the singleton reservation and clear affected cell states.
|
||||
return await sp_xExePackingListPallet_async(self.db_client, id_operatore, documento, "S")
|
||||
|
||||
def _ok(res: SPResult):
|
||||
@@ -1191,7 +1374,7 @@ class GestionePickingListFrame(ctk.CTkFrame):
|
||||
target=documento,
|
||||
details={"error": str(ex)},
|
||||
)
|
||||
messagebox.showerror("S-prenota", f"Errore:\n{ex}")
|
||||
messagebox.showerror("S-prenota", f"Errore:\n{ex}", exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_job(),
|
||||
@@ -1240,7 +1423,7 @@ def open_pickinglist_window(parent: tk.Misc, db_client, session: UserSession | N
|
||||
|
||||
win = ctk.CTkToplevel(parent)
|
||||
locale_catalog = load_locale_catalog()
|
||||
win.title(loc_text("picking.title", catalog=locale_catalog, default="Gestione Picking List"))
|
||||
win.title(versioned_title(loc_text("picking.title", catalog=locale_catalog, default="Gestione Picking List"), __name__))
|
||||
theme = theme_section("pickinglist_window", {})
|
||||
win.geometry(str(theme_value(theme, "window_geometry", "1200x700")))
|
||||
minsize = theme_value(theme, "window_minsize", [1000, 560])
|
||||
|
||||
@@ -13,14 +13,19 @@ from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
import customtkinter as ctk
|
||||
from tkinter import messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import ttk
|
||||
|
||||
from gestione_aree import AsyncRunner
|
||||
from audit_log import log_user_action
|
||||
from busy_overlay import InlineBusyOverlay
|
||||
from locale_text import load_locale_catalog, text as loc_text
|
||||
from ui_theme import theme_color, theme_font, theme_section, theme_value
|
||||
from ui_tables import style_treeview, zebra_tag
|
||||
from user_session import UserSession
|
||||
from version_info import module_version, versioned_title
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
try:
|
||||
from loguru import logger
|
||||
@@ -72,6 +77,12 @@ _MODULE_LOG_LEVEL = "DEBUG" if SCARICO_LOG_MODE.upper() == "DEBUG" else "INFO"
|
||||
_MODULE_LOGGER = logger.bind(warehouse_module=MODULE_LOG_NAME)
|
||||
_MODULE_LOGGING_CONFIGURED = False
|
||||
DEFAULT_SCARICO_USER = "warehouse_ui"
|
||||
SHIPPED_IDCELLA = 9999
|
||||
SHIPPED_BARCODE = "9000000"
|
||||
SHIPPED_LABEL = "7G.1.1"
|
||||
NON_SCAFF_IDCELLA = 1000
|
||||
NON_SCAFF_BARCODE = "9001000"
|
||||
NON_SCAFF_LABEL = "5E1.1"
|
||||
|
||||
|
||||
def _session_login(session: UserSession | None, fallback: str | None = None) -> str:
|
||||
@@ -194,28 +205,7 @@ last_move AS (
|
||||
FROM dbo.MagazziniPallet mp
|
||||
JOIN last_in_cell lic ON lic.LastID = mp.ID
|
||||
),
|
||||
latest_any AS (
|
||||
SELECT
|
||||
ranked.BarcodePallet,
|
||||
ranked.IDCella
|
||||
FROM (
|
||||
SELECT
|
||||
mp.Attributo AS BarcodePallet,
|
||||
mp.IDCella,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY mp.Attributo
|
||||
ORDER BY mp.ID DESC
|
||||
) AS rn
|
||||
FROM dbo.MagazziniPallet mp
|
||||
JOIN cell_pallets cp
|
||||
ON cp.BarcodePallet COLLATE Latin1_General_CI_AS =
|
||||
mp.Attributo COLLATE Latin1_General_CI_AS
|
||||
WHERE mp.Tipo = 'V'
|
||||
AND mp.PesoUnitario > 0
|
||||
) ranked
|
||||
WHERE ranked.rn = 1
|
||||
),
|
||||
shipped AS (
|
||||
closed_plist AS (
|
||||
SELECT DISTINCT
|
||||
shipped.BarcodePallet
|
||||
FROM dbo.XMag_GiacenzaPalletPlistChiuse shipped
|
||||
@@ -227,25 +217,19 @@ SELECT
|
||||
cp.BarcodePallet AS UDC,
|
||||
lm.ID AS SourceID,
|
||||
lm.DataMagazzino AS LastEventAt,
|
||||
:idcella AS CurrentIDCella,
|
||||
CASE
|
||||
WHEN shipped.BarcodePallet IS NOT NULL THEN CAST(1 AS int)
|
||||
ELSE CAST(0 AS int)
|
||||
END AS IsShippedGhost,
|
||||
CASE
|
||||
WHEN la.IDCella IS NOT NULL
|
||||
AND la.IDCella <> :idcella
|
||||
WHEN :idcella <> 9999
|
||||
AND closed_plist.BarcodePallet IS NOT NULL
|
||||
THEN CAST(1 AS int)
|
||||
ELSE CAST(0 AS int)
|
||||
END AS IsMovedGhost
|
||||
END AS IsMissingUnload
|
||||
FROM cell_pallets cp
|
||||
LEFT JOIN last_move lm
|
||||
ON lm.BarcodePallet COLLATE Latin1_General_CI_AS =
|
||||
cp.BarcodePallet COLLATE Latin1_General_CI_AS
|
||||
LEFT JOIN latest_any la
|
||||
ON la.BarcodePallet COLLATE Latin1_General_CI_AS =
|
||||
cp.BarcodePallet COLLATE Latin1_General_CI_AS
|
||||
LEFT JOIN shipped
|
||||
ON shipped.BarcodePallet COLLATE Latin1_General_CI_AS =
|
||||
LEFT JOIN closed_plist
|
||||
ON closed_plist.BarcodePallet COLLATE Latin1_General_CI_AS =
|
||||
cp.BarcodePallet COLLATE Latin1_General_CI_AS
|
||||
ORDER BY
|
||||
lm.ID DESC,
|
||||
@@ -409,19 +393,23 @@ class ScaricoRow:
|
||||
udc: str
|
||||
source_id: int | None
|
||||
last_event_at: str
|
||||
current_idcella: int
|
||||
diagnostic_note: str
|
||||
selected: tk.BooleanVar
|
||||
|
||||
|
||||
def _build_diagnostic_note(is_shipped: int | bool, is_moved: int | bool) -> str:
|
||||
def _build_diagnostic_note(is_missing_unload: int | bool = False) -> str:
|
||||
"""Translate low-level anomaly flags into one operator-facing note."""
|
||||
|
||||
notes: list[str] = []
|
||||
if bool(is_shipped):
|
||||
notes.append("Mancato scarico: spedita")
|
||||
if bool(is_moved):
|
||||
notes.append("Mancato scarico: spostata")
|
||||
return " | ".join(notes)
|
||||
if bool(is_missing_unload):
|
||||
return "Motivo: spedita ma non scaricata dalla cella"
|
||||
return ""
|
||||
|
||||
|
||||
def _is_missing_unload_row(row: ScaricoRow) -> bool:
|
||||
"""Return True when the row must be corrected only with shipped unload."""
|
||||
|
||||
return "spedita ma non scaricata dalla cella" in str(row.diagnostic_note or "").lower()
|
||||
|
||||
|
||||
class ScaricoDialog(ctk.CTkToplevel):
|
||||
@@ -457,7 +445,7 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
self._async = AsyncRunner(self)
|
||||
self.rows_tree: ttk.Treeview | None = None
|
||||
|
||||
self.title(loc_text("scarico.title", catalog=self._locale_catalog, default="Scarica {ubicazione}").format(ubicazione=ubicazione))
|
||||
self.title(versioned_title(loc_text("scarico.title", catalog=self._locale_catalog, default="Scarica {ubicazione}").format(ubicazione=ubicazione), __name__))
|
||||
self.resizable(False, False)
|
||||
self.transient(parent)
|
||||
self.protocol("WM_DELETE_WINDOW", self._close)
|
||||
@@ -474,8 +462,9 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
self.wait_visibility()
|
||||
except Exception:
|
||||
pass
|
||||
self.lift()
|
||||
self.focus_force()
|
||||
if self.winfo_exists():
|
||||
self.lift()
|
||||
self.focus_force()
|
||||
|
||||
def _build_ui(self):
|
||||
"""Build the compact modal layout."""
|
||||
@@ -508,10 +497,6 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
tree_host.grid_rowconfigure(0, weight=1)
|
||||
tree_host.grid_columnconfigure(0, weight=1)
|
||||
|
||||
style = ttk.Style(self)
|
||||
style.configure("Scarico.Treeview", rowheight=28, font=theme_font(self._theme, "tree_body_font", ("Segoe UI", 10)))
|
||||
style.configure("Scarico.Treeview.Heading", font=theme_font(self._theme, "tree_heading_font", ("Segoe UI", 10, "bold")))
|
||||
|
||||
self.rows_tree = ttk.Treeview(
|
||||
tree_host,
|
||||
columns=("sel", "udc", "last", "diag"),
|
||||
@@ -519,6 +504,13 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
style="Scarico.Treeview",
|
||||
selectmode="none",
|
||||
)
|
||||
style_treeview(
|
||||
self.rows_tree,
|
||||
style_name="Scarico.Treeview",
|
||||
rowheight=28,
|
||||
font=theme_font(self._theme, "tree_body_font", ("Segoe UI", 10)),
|
||||
heading_font=theme_font(self._theme, "tree_heading_font", ("Segoe UI", 10, "bold")),
|
||||
)
|
||||
self.rows_tree.heading("sel", text="Sel")
|
||||
self.rows_tree.heading("udc", text=loc_text("scarico.col.udc", catalog=self._locale_catalog, default="UDC"))
|
||||
self.rows_tree.heading("last", text=loc_text("scarico.col.last_insert", catalog=self._locale_catalog, default="Ultimo inserimento"))
|
||||
@@ -539,19 +531,27 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
actions.grid_columnconfigure(0, weight=1)
|
||||
ctk.CTkButton(
|
||||
actions,
|
||||
text=loc_text("scarico.button.submit", catalog=self._locale_catalog, default="Scarica"),
|
||||
command=self._on_scarica,
|
||||
text=loc_text("scarico.button.shipped", catalog=self._locale_catalog, default="Scarico come spedita"),
|
||||
command=self._on_scarica_spedita,
|
||||
font=theme_font(self._theme, "button_font", ("Segoe UI", 10, "bold")),
|
||||
).grid(
|
||||
row=0, column=1, padx=(8, 0), pady=8
|
||||
)
|
||||
ctk.CTkButton(
|
||||
actions,
|
||||
text=loc_text("scarico.button.non_shelved", catalog=self._locale_catalog, default="Scarico come non scaff."),
|
||||
command=self._on_scarica_non_scaff,
|
||||
font=theme_font(self._theme, "button_font", ("Segoe UI", 10, "bold")),
|
||||
).grid(
|
||||
row=0, column=2, padx=(8, 0), pady=8
|
||||
)
|
||||
ctk.CTkButton(
|
||||
actions,
|
||||
text=loc_text("scarico.button.close", catalog=self._locale_catalog, default="Chiudi"),
|
||||
command=self._close,
|
||||
font=theme_font(self._theme, "button_font", ("Segoe UI", 10, "bold")),
|
||||
).grid(
|
||||
row=0, column=2, padx=(8, 8), pady=8
|
||||
row=0, column=3, padx=(8, 8), pady=8
|
||||
)
|
||||
|
||||
def _render_rows(self):
|
||||
@@ -572,6 +572,7 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
row.last_event_at,
|
||||
row.diagnostic_note or "",
|
||||
),
|
||||
tags=(zebra_tag(idx),),
|
||||
)
|
||||
|
||||
self.update_idletasks()
|
||||
@@ -609,7 +610,13 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
rows = res.get("rows", []) if isinstance(res, dict) else []
|
||||
_log_dataset("scarico_load_rows", rows)
|
||||
self.rows = []
|
||||
for udc, source_id, last_event_at, is_shipped, is_moved in rows:
|
||||
for (
|
||||
udc,
|
||||
source_id,
|
||||
last_event_at,
|
||||
current_idcella,
|
||||
is_missing_unload,
|
||||
) in rows:
|
||||
if isinstance(last_event_at, datetime):
|
||||
last_event = last_event_at.strftime("%d/%m/%Y %H:%M:%S")
|
||||
else:
|
||||
@@ -619,7 +626,8 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
udc=str(udc or ""),
|
||||
source_id=int(source_id) if source_id is not None else None,
|
||||
last_event_at=last_event,
|
||||
diagnostic_note=_build_diagnostic_note(is_shipped, is_moved),
|
||||
current_idcella=int(current_idcella or 0),
|
||||
diagnostic_note=_build_diagnostic_note(is_missing_unload),
|
||||
selected=tk.BooleanVar(value=False),
|
||||
)
|
||||
)
|
||||
@@ -633,6 +641,7 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
loc_text("scarico.msg.title", catalog=self._locale_catalog, default="Scarica"),
|
||||
loc_text("scarico.msg.load_error", catalog=self._locale_catalog, default="Caricamento UDC fallito:\n{error}").format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
self._close()
|
||||
|
||||
@@ -645,8 +654,9 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
)
|
||||
|
||||
@_log_call()
|
||||
def _on_scarica(self):
|
||||
"""Unload the UDCs selected by the user from the current cell."""
|
||||
def _selected_rows_or_warn(self) -> list[ScaricoRow] | None:
|
||||
"""Return selected rows or show the standard selection warning."""
|
||||
|
||||
selected = [row for row in self.rows if row.selected.get()]
|
||||
if not selected:
|
||||
messagebox.showinfo(
|
||||
@@ -654,23 +664,97 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
loc_text("scarico.msg.select_one", catalog=self._locale_catalog, default="Seleziona almeno una UDC da scaricare."),
|
||||
parent=self,
|
||||
)
|
||||
return selected
|
||||
|
||||
@_log_call()
|
||||
def _on_scarica_spedita(self):
|
||||
"""Unload selected UDCs to the shipped conventional location."""
|
||||
|
||||
self._scarica_selected_to_target(
|
||||
target_idcella=SHIPPED_IDCELLA,
|
||||
target_barcode_cella=SHIPPED_BARCODE,
|
||||
target_label=SHIPPED_LABEL,
|
||||
title="Scarico come spedita",
|
||||
confirm_text="Scaricare come spedite {count} UDC da {ubicazione}?",
|
||||
busy_message="Scarico UDC come spedite...",
|
||||
block_shipped_for_non_scaff=False,
|
||||
)
|
||||
|
||||
@_log_call()
|
||||
def _on_scarica_non_scaff(self):
|
||||
"""Unload selected UDCs to the non-shelved conventional location."""
|
||||
|
||||
self._scarica_selected_to_target(
|
||||
target_idcella=NON_SCAFF_IDCELLA,
|
||||
target_barcode_cella=NON_SCAFF_BARCODE,
|
||||
target_label=NON_SCAFF_LABEL,
|
||||
title="Scarico come non scaff.",
|
||||
confirm_text="Scaricare come non scaffalate {count} UDC da {ubicazione}?",
|
||||
busy_message="Scarico UDC come non scaffalate...",
|
||||
block_shipped_for_non_scaff=True,
|
||||
)
|
||||
|
||||
def _scarica_selected_to_target(
|
||||
self,
|
||||
*,
|
||||
target_idcella: int,
|
||||
target_barcode_cella: str,
|
||||
target_label: str,
|
||||
title: str,
|
||||
confirm_text: str,
|
||||
busy_message: str,
|
||||
block_shipped_for_non_scaff: bool,
|
||||
):
|
||||
"""Move selected UDCs to one conventional unload location."""
|
||||
|
||||
selected = self._selected_rows_or_warn()
|
||||
if not selected:
|
||||
return
|
||||
|
||||
shipped_rows: list[ScaricoRow] = []
|
||||
missing_unload_rows: list[ScaricoRow] = []
|
||||
movable_rows = list(selected)
|
||||
if block_shipped_for_non_scaff:
|
||||
shipped_rows = [
|
||||
row for row in selected
|
||||
if int(row.current_idcella or 0) == SHIPPED_IDCELLA
|
||||
]
|
||||
missing_unload_rows = [row for row in selected if _is_missing_unload_row(row)]
|
||||
blocked_udcs = {row.udc for row in shipped_rows + missing_unload_rows}
|
||||
movable_rows = [row for row in selected if row.udc not in blocked_udcs]
|
||||
|
||||
if (shipped_rows or missing_unload_rows) and not movable_rows:
|
||||
message_lines = ["Nessuna UDC movimentata."]
|
||||
if shipped_rows:
|
||||
message_lines.append(f"UDC gia' in {SHIPPED_LABEL}: " + ", ".join(row.udc for row in shipped_rows))
|
||||
if missing_unload_rows:
|
||||
message_lines.append(
|
||||
"UDC spedite ma non scaricate: "
|
||||
+ ", ".join(row.udc for row in missing_unload_rows)
|
||||
)
|
||||
message_lines.append("Usare 'Scarico come spedita'.")
|
||||
messagebox.showwarning(
|
||||
title,
|
||||
"\n".join(message_lines),
|
||||
parent=self,
|
||||
)
|
||||
return
|
||||
|
||||
if not messagebox.askyesno(
|
||||
"Conferma scarico",
|
||||
f"Scaricare {len(selected)} UDC da {self.ubicazione}?",
|
||||
title,
|
||||
confirm_text.format(count=len(movable_rows), ubicazione=self.ubicazione),
|
||||
parent=self,
|
||||
):
|
||||
return
|
||||
|
||||
async def _job():
|
||||
results: list[dict[str, Any]] = []
|
||||
for row in selected:
|
||||
for row in movable_rows:
|
||||
result = await move_pallet_async(
|
||||
self.db_client,
|
||||
barcode_pallet=row.udc,
|
||||
target_idcella=9999,
|
||||
target_barcode_cella="9000000",
|
||||
target_idcella=target_idcella,
|
||||
target_barcode_cella=target_barcode_cella,
|
||||
utente=_session_login(self.session),
|
||||
)
|
||||
results.append({"udc": row.udc, "affected": int(result.get("ok") or 0)})
|
||||
@@ -682,33 +766,65 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
skipped = [item["udc"] for item in results if int(item.get("affected") or 0) <= 0]
|
||||
if not done:
|
||||
messagebox.showwarning(
|
||||
"Scarica",
|
||||
title,
|
||||
"Nessuna UDC e' stata scaricata. Verifica che le unita' siano ancora presenti in cella.",
|
||||
parent=self,
|
||||
)
|
||||
return
|
||||
if skipped:
|
||||
shipped_note = (
|
||||
f"\nGia' in {SHIPPED_LABEL} non toccate: " + ", ".join(row.udc for row in shipped_rows)
|
||||
if shipped_rows
|
||||
else ""
|
||||
)
|
||||
missing_unload_note = (
|
||||
"\nSpedite ma non scaricate, usare 'Scarico come spedita': "
|
||||
+ ", ".join(row.udc for row in missing_unload_rows)
|
||||
if missing_unload_rows
|
||||
else ""
|
||||
)
|
||||
target_note = (
|
||||
f"\nUDC in {target_label}: " + ", ".join(done)
|
||||
if done
|
||||
else ""
|
||||
)
|
||||
messagebox.showwarning(
|
||||
"Scarica",
|
||||
title,
|
||||
"Scarico parziale.\nCompletate: "
|
||||
+ ", ".join(done)
|
||||
+ "\nNon scaricate: "
|
||||
+ ", ".join(skipped),
|
||||
+ ", ".join(skipped)
|
||||
+ shipped_note
|
||||
+ missing_unload_note
|
||||
+ target_note,
|
||||
parent=self,
|
||||
)
|
||||
else:
|
||||
messagebox.showinfo(
|
||||
"Scarica",
|
||||
"Scarico completato per:\n" + "\n".join(done),
|
||||
parent=self,
|
||||
)
|
||||
msg = f"Scarico completato verso {target_label} per:\n" + "\n".join(done)
|
||||
if shipped_rows:
|
||||
msg += f"\n\nUDC gia' in {SHIPPED_LABEL} non toccate:\n" + "\n".join(row.udc for row in shipped_rows)
|
||||
msg += f"\n\nUDC in {target_label}: " + ", ".join(done)
|
||||
if missing_unload_rows:
|
||||
msg += (
|
||||
"\n\nUDC spedite ma non scaricate non toccate:\n"
|
||||
+ "\n".join(row.udc for row in missing_unload_rows)
|
||||
+ "\nUsare 'Scarico come spedita'."
|
||||
)
|
||||
messagebox.showinfo(title, msg, parent=self)
|
||||
log_user_action(
|
||||
self.session,
|
||||
module=MODULE_LOG_NAME,
|
||||
action="layout.scarico",
|
||||
action="layout.scarico.spedita" if int(target_idcella) == SHIPPED_IDCELLA else "layout.scarico.non_scaff",
|
||||
outcome="ok",
|
||||
target=self.ubicazione,
|
||||
details={"scaricate": done, "saltate": skipped},
|
||||
details={
|
||||
"scaricate": done,
|
||||
"saltate": skipped,
|
||||
"target_idcella": target_idcella,
|
||||
"target_barcode_cella": target_barcode_cella,
|
||||
"gia_spedite": [row.udc for row in shipped_rows],
|
||||
"spedite_non_scaricate": [row.udc for row in missing_unload_rows],
|
||||
},
|
||||
)
|
||||
if self.on_completed:
|
||||
self.on_completed()
|
||||
@@ -719,7 +835,7 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
log_user_action(
|
||||
self.session,
|
||||
module=MODULE_LOG_NAME,
|
||||
action="layout.scarico",
|
||||
action="layout.scarico.spedita" if int(target_idcella) == SHIPPED_IDCELLA else "layout.scarico.non_scaff",
|
||||
outcome="error",
|
||||
target=self.ubicazione,
|
||||
details={"error": str(ex)},
|
||||
@@ -728,6 +844,7 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
loc_text("scarico.msg.title", catalog=self._locale_catalog, default="Scarica"),
|
||||
loc_text("scarico.msg.exec_error", catalog=self._locale_catalog, default="Scarico fallito:\n{error}").format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
|
||||
self._async.run(
|
||||
@@ -735,7 +852,7 @@ class ScaricoDialog(ctk.CTkToplevel):
|
||||
_ok,
|
||||
_err,
|
||||
busy=self._busy,
|
||||
message="Scarico UDC...",
|
||||
message=busy_message,
|
||||
)
|
||||
|
||||
@_log_call()
|
||||
|
||||
269
inventario.py
Normal file
269
inventario.py
Normal file
@@ -0,0 +1,269 @@
|
||||
"""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
|
||||
import error_dialog as messagebox
|
||||
from tkinter import filedialog, 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.ready"))
|
||||
self.title(versioned_title(self._t("inventory.title"), __name__))
|
||||
self.geometry(str(theme_value(self._theme, "window_geometry", "1200x720")))
|
||||
self.minsize(*theme_value(self._theme, "window_minsize", [900, 560]))
|
||||
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, minsize=120)
|
||||
self.grid_rowconfigure(5, weight=1, minsize=150)
|
||||
top = ctk.CTkFrame(self, fg_color=theme_color(self._theme, "toolbar_frame_fg_color", "#d7d7d7"))
|
||||
top.grid(row=0, column=0, sticky="ew", padx=8, pady=8)
|
||||
top.grid_columnconfigure(3, weight=1)
|
||||
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)
|
||||
self._build_legend()
|
||||
ctk.CTkLabel(self, textvariable=self.var_status, anchor="w", justify="left",
|
||||
wraplength=1000).grid(row=2, column=0, sticky="ew", padx=10, pady=5)
|
||||
self.tree = self._make_tree(3, KEYS)
|
||||
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 _build_legend(self):
|
||||
"""Keep component definitions visible independently of calculation status."""
|
||||
self.legend = ctk.CTkFrame(self, fg_color=theme_color(
|
||||
self._theme, "legend_fg_color", ["#f8fafb", "#262b30"]))
|
||||
self.legend.grid(row=1, column=0, sticky="ew", padx=8, pady=(0, 4))
|
||||
self.legend.grid_columnconfigure(1, weight=1)
|
||||
normal = theme_font(self._theme, "legend_font", ("Segoe UI", 13))
|
||||
bold = theme_font(self._theme, "legend_heading_font", ("Segoe UI", 13, "bold"))
|
||||
color = theme_color(self._theme, "legend_text_color", ["#202830", "#f1f3f5"])
|
||||
self.legend_labels = {}
|
||||
self.legend_descriptions = []
|
||||
for row, component in enumerate(("A", "B", "C", "X")):
|
||||
label = ctk.CTkLabel(self.legend, text=component + ":", font=bold,
|
||||
text_color=color, anchor="nw", height=20)
|
||||
label.grid(row=row, column=0, sticky="nw", padx=(10, 8), pady=1)
|
||||
self.legend_labels[component] = label
|
||||
description = ctk.CTkLabel(self.legend, text=self._t("inventory.legend." + component),
|
||||
font=normal, text_color=color, anchor="w", justify="left", wraplength=800, height=20)
|
||||
description.grid(row=row, column=1, sticky="ew", padx=(0, 10), pady=1)
|
||||
self.legend_descriptions.append(description)
|
||||
self.legend_notes = []
|
||||
for row, key in enumerate(("formula", "scope", "history_notice"), start=4):
|
||||
label = ctk.CTkLabel(self.legend, text=self._t("inventory." + key),
|
||||
font=bold if key == "formula" else normal, text_color=color,
|
||||
anchor="w", justify="left", wraplength=850, height=20)
|
||||
label.grid(row=row, column=0, columnspan=2, sticky="ew", padx=10, pady=1)
|
||||
self.legend_notes.append(label)
|
||||
self.legend.bind("<Configure>", self._resize_legend, add="+")
|
||||
|
||||
def _resize_legend(self, event):
|
||||
"""Wrap to the actual window width, including on smaller desktops."""
|
||||
for label in self.legend_descriptions:
|
||||
label.configure(wraplength=max(200, event.width - 65))
|
||||
for label in self.legend_notes:
|
||||
label.configure(wraplength=max(200, event.width - 24))
|
||||
|
||||
def _make_tree(self, row, keys, parent=None):
|
||||
wrap = ctk.CTkFrame(parent if parent is not None else self)
|
||||
wrap.grid(row=row, column=0, sticky="nsew", padx=8, pady=(0, 8))
|
||||
wrap.grid_columnconfigure(0, weight=1)
|
||||
wrap.grid_rowconfigure(0, weight=1)
|
||||
tree = ttk.Treeview(wrap, columns=keys, show="headings", selectmode="browse", height=5)
|
||||
style_treeview(tree, style_name="Inventory.Treeview", rowheight=24)
|
||||
tree.tag_configure("difference", foreground=theme_value(self._theme, "difference_color", "#9b3900"))
|
||||
tree.tag_configure("unknown", foreground=theme_value(self._theme, "unknown_color", "#aa0000"))
|
||||
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, exception=error)
|
||||
|
||||
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()
|
||||
262
locale.json
262
locale.json
@@ -1,6 +1,84 @@
|
||||
{
|
||||
"default_language": "IT",
|
||||
"IT": {
|
||||
"errors.title": "Dettaglio errore",
|
||||
"errors.copy": "Copia tutto",
|
||||
"errors.save": "Salva su file",
|
||||
"errors.close": "Chiudi",
|
||||
"errors.copied": "Testo copiato negli appunti.",
|
||||
"errors.copy_failed": "Copia non riuscita: {error}",
|
||||
"errors.saved": "Report salvato: {path}",
|
||||
"errors.save_failed": "Salvataggio non riuscito: {error}",
|
||||
"errors.text_file": "File di testo UTF-8",
|
||||
"errors.all_files": "Tutti i file",
|
||||
"inventory.title": "Inventario",
|
||||
"inventory.date": "Data (gg/mm/aaaa):",
|
||||
"inventory.load": "Calcola inventario",
|
||||
"inventory.export": "Esporta XLSX",
|
||||
"inventory.ready": "Scegli la data e premi Calcola inventario. Seleziona poi un prodotto per vedere lotti e contenitori.",
|
||||
"inventory.legend.A": "Pezzi nelle UDC presenti in WMS: scaffalate nelle aree 5/6 oppure non scaffalate.",
|
||||
"inventory.legend.B": "Pezzi in UDC assegnate ma fuori WMS: confezionamento dedotto, UDC piene o parziali.",
|
||||
"inventory.legend.C": "Pezzi in bag/vasche senza UDC: seriale 000000/..., con giacenza SAM positiva.",
|
||||
"inventory.legend.X": "Anomalie nel dettaglio: saldo SAM non classificabile in A/B/C; escluso dal totale ricostruito.",
|
||||
"inventory.formula": "Totale = A + B + C. Residuo = SAM - Totale. '?' = quantita' non determinabile, non zero.",
|
||||
"inventory.notice": "A: UDC WMS. B: UDC fuori WMS, confezionamento presunto. C: bag/vasche senza UDC. Residuo = SAM - (A+B+C). '?' indica dati non determinabili.",
|
||||
"inventory.scope": "Perimetro provvisorio: solo prodotti/lotti delle UDC in aree 5 e 6 o non scaffalate alla data. Non e' l'inventario completo SAM.",
|
||||
"inventory.history_notice": "Ricostruzione da movimenti e storico NUMSER disponibile, non inventario fisico certificato. Validare le etichette e la completezza dello storico.",
|
||||
"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.operator": "Operatore: {display_name} ({login})",
|
||||
"launcher.reset_corsie": "Gestione Corsie",
|
||||
@@ -10,6 +88,7 @@
|
||||
"launcher.history_udc": "Storico movimenti UDC",
|
||||
"launcher.pickinglist": "Gestione Picking List",
|
||||
"launcher.history_pickinglist": "Storico Picking List",
|
||||
"launcher.diagnostics": "Diagnostica",
|
||||
"launcher.arrange": "Ridisponi finestre",
|
||||
"launcher.exit": "Esci",
|
||||
"launcher.already_running_title": "Warehouse",
|
||||
@@ -68,6 +147,10 @@
|
||||
"history.udc.msg.empty": "Nessun movimento trovato.",
|
||||
"history.udc.msg.error": "Errore ricerca:\n{error}",
|
||||
"history.picking.title": "Storico Picking List",
|
||||
"history.picking.document": "Documento:",
|
||||
"history.picking.year": "Anno",
|
||||
"history.picking.udc_hint": "UDC vuota: anno corrente. Ricerca UDC: anno corrente e precedente. Se compilati, entrambi i filtri si applicano.",
|
||||
"history.picking.udc_invalid": "Inserire il codice UDC completo, numerico, di massimo 6 cifre.",
|
||||
"history.picking.button.reload": "Ricarica",
|
||||
"history.picking.detail_title": "Dettaglio contenuto",
|
||||
"history.picking.busy.master": "Carico storico picking list...",
|
||||
@@ -75,11 +158,34 @@
|
||||
"history.picking.msg.title": "Storico Picking List",
|
||||
"history.picking.msg.load_error": "Errore caricamento:\n{error}",
|
||||
"history.picking.msg.detail_error": "Errore dettaglio:\n{error}",
|
||||
"diagnostics.title": "Diagnostica",
|
||||
"diagnostics.button.shipped_not_disassociated": "UDC spedite non disassociate",
|
||||
"diagnostics.button.multiple_udc_by_cell": "Celle con multiple UDC",
|
||||
"diagnostics.button.sam_udc_not_in_wms": "Ultime UDC SAM non in WMS",
|
||||
"diagnostics.button.export": "Esporta XLSX",
|
||||
"diagnostics.busy.shipped_not_disassociated": "Cerco UDC spedite ma ancora in cella...",
|
||||
"diagnostics.busy.multiple_udc_by_cell": "Cerco celle con multiple UDC...",
|
||||
"diagnostics.busy.sam_udc_not_in_wms": "Cerco le ultime UDC presenti in SAM ma non ancora in WMS...",
|
||||
"diagnostics.status.rows": "Righe trovate: {count}",
|
||||
"diagnostics.col.udc": "UDC",
|
||||
"diagnostics.col.cell": "CELLA",
|
||||
"diagnostics.col.lot": "Lotto",
|
||||
"diagnostics.col.product": "Prodotto",
|
||||
"diagnostics.col.description": "Descrizione",
|
||||
"diagnostics.col.shipped_not_disassociated": "Spedita ma non disassociata",
|
||||
"diagnostics.col.symbolic_cell": "Nome simbolico cella",
|
||||
"diagnostics.export.title": "Esporta",
|
||||
"diagnostics.export.empty": "Non ci sono righe da esportare.",
|
||||
"diagnostics.export.dep": "Per l'esportazione serve 'openpyxl' (pip install openpyxl).",
|
||||
"diagnostics.export.ok": "File creato:\n{path}",
|
||||
"diagnostics.export.error": "Errore durante l'esportazione:\n{error}",
|
||||
"reset.title": "Gestione Corsie - svuotamento celle per corsia",
|
||||
"reset.label.aisle": "Corsia:",
|
||||
"reset.button.refresh": "Carica",
|
||||
"reset.button.empty": "Svuota corsia...",
|
||||
"reset.summary": "Riepilogo",
|
||||
"reset.confirm": "Verranno movimentate {udc} UDC da {cells} celle della corsia {aisle}.\nUDC associate a documenti di spedizione definitivi (stato D): spedite in 9999 / 7G.1.1.\nTutte le altre: non scaffalate in 1000 (barcode 9001000).\nSaranno registrati prelievo e versamento, senza cancellazioni.\nLa verifica viene effettuata al momento di ogni movimento.\nDigitare il nome della corsia per confermare:",
|
||||
"reset.result": "Corsia {aisle}: movimentate {success} UDC su {total}.\nSpedite in 9999 / 7G.1.1: {shipped}.\nNon scaffalate in 1000: {non_shelved}.\nAggiornare lo storico picking list per ricalcolare i residui.",
|
||||
"layout.title": "Layout corsie",
|
||||
"layout.button.search": "Cerca per barcode UDC",
|
||||
"layout.button.refresh": "Aggiorna",
|
||||
@@ -99,7 +205,30 @@
|
||||
"picking.button.reload": "Ricarica",
|
||||
"picking.button.prenota": "Prenota",
|
||||
"picking.button.sprenota": "S-prenota",
|
||||
"picking.button.sequence": "Sequenza di prelievo",
|
||||
"picking.button.export": "Esporta XLSX",
|
||||
"picking.label.days": "Giorni:",
|
||||
"picking.sequence.title": "Sequenza di prelievo",
|
||||
"picking.sequence.document": "Picking List {documento}",
|
||||
"picking.sequence.available": "Scaffali disponibili",
|
||||
"picking.sequence.selected": "Ordine personalizzato",
|
||||
"picking.sequence.hint": "Trascina gli scaffali a destra. Quelli non inseriti saranno accodati secondo l'ordine predefinito.",
|
||||
"picking.sequence.default_hint": "Default: prima Non scaff., poi gli scaffali secondo l'ordine WMS.",
|
||||
"picking.sequence.button.add": "Aggiungi >",
|
||||
"picking.sequence.button.remove": "< Rimuovi",
|
||||
"picking.sequence.button.up": "Su",
|
||||
"picking.sequence.button.down": "Giu'",
|
||||
"picking.sequence.button.save": "Salva",
|
||||
"picking.sequence.button.reset": "Ripristina default",
|
||||
"picking.sequence.button.close": "Chiudi",
|
||||
"picking.sequence.busy.load": "Carico gli scaffali...",
|
||||
"picking.sequence.busy.save": "Salvo la sequenza...",
|
||||
"picking.sequence.msg.select": "Seleziona una Picking List prima di definire la sequenza.",
|
||||
"picking.sequence.msg.denied": "Permesso negato.",
|
||||
"picking.sequence.msg.saved": "Sequenza salvata.",
|
||||
"picking.sequence.msg.reset": "Sequenza personalizzata rimossa. E' attivo l'ordine predefinito.",
|
||||
"picking.sequence.msg.load_error": "Errore durante il caricamento:\n{error}",
|
||||
"picking.sequence.msg.save_error": "Errore durante il salvataggio:\n{error}",
|
||||
"scarico.title": "Scarica {ubicazione}",
|
||||
"scarico.label.location": "Ubicazione: {ubicazione}",
|
||||
"scarico.label.select": "Seleziona le UDC da scaricare",
|
||||
@@ -107,6 +236,8 @@
|
||||
"scarico.col.last_insert": "Ultimo inserimento",
|
||||
"scarico.col.diagnostic": "Diagnostica",
|
||||
"scarico.button.submit": "Scarica",
|
||||
"scarico.button.shipped": "Scarico come spedita",
|
||||
"scarico.button.non_shelved": "Scarico come non scaff.",
|
||||
"scarico.button.close": "Chiudi",
|
||||
"scarico.msg.title": "Scarica",
|
||||
"scarico.msg.select_one": "Seleziona almeno una UDC da scaricare.",
|
||||
@@ -114,6 +245,84 @@
|
||||
"scarico.msg.exec_error": "Scarico fallito:\n{error}"
|
||||
},
|
||||
"ENG": {
|
||||
"errors.title": "Error details",
|
||||
"errors.copy": "Copy all",
|
||||
"errors.save": "Save to file",
|
||||
"errors.close": "Close",
|
||||
"errors.copied": "Text copied to clipboard.",
|
||||
"errors.copy_failed": "Copy failed: {error}",
|
||||
"errors.saved": "Report saved: {path}",
|
||||
"errors.save_failed": "Save failed: {error}",
|
||||
"errors.text_file": "UTF-8 text file",
|
||||
"errors.all_files": "All files",
|
||||
"inventory.title": "Inventory",
|
||||
"inventory.date": "Date (dd/mm/yyyy):",
|
||||
"inventory.load": "Calculate inventory",
|
||||
"inventory.export": "Export XLSX",
|
||||
"inventory.ready": "Choose a date and Calculate inventory. Then select a product to see lots and containers.",
|
||||
"inventory.legend.A": "Pieces in WMS UDCs: shelved in areas 5/6 or non-shelved.",
|
||||
"inventory.legend.B": "Pieces assigned to UDCs outside WMS: inferred packaging, full or partial UDCs.",
|
||||
"inventory.legend.C": "Pieces in bags/tubs without a UDC: serial 000000/..., with positive SAM stock.",
|
||||
"inventory.legend.X": "Detail anomalies: SAM stock not classifiable as A/B/C; excluded from the reconstructed total.",
|
||||
"inventory.formula": "Total = A + B + C. Residual = SAM - Total. '?' = undetermined quantity, not zero.",
|
||||
"inventory.notice": "A: WMS UDCs. B: UDCs outside WMS, inferred packaging location. C: bags/tubs without UDC. Residual = SAM - (A+B+C). '?' means undetermined data.",
|
||||
"inventory.scope": "Provisional scope: only products/lots of UDCs in areas 5/6 or non-shelved at date. Not the complete SAM inventory.",
|
||||
"inventory.history_notice": "Reconstruction from movements and available NUMSER history, not a certified physical inventory. Validate labels and history completeness.",
|
||||
"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.operator": "Operator: {display_name} ({login})",
|
||||
"launcher.reset_corsie": "Aisle Management",
|
||||
@@ -123,6 +332,7 @@
|
||||
"launcher.history_udc": "UDC Movement History",
|
||||
"launcher.pickinglist": "Picking List Management",
|
||||
"launcher.history_pickinglist": "Picking List History",
|
||||
"launcher.diagnostics": "Diagnostics",
|
||||
"launcher.arrange": "Arrange windows",
|
||||
"launcher.exit": "Exit",
|
||||
"launcher.already_running_title": "Warehouse",
|
||||
@@ -181,6 +391,10 @@
|
||||
"history.udc.msg.empty": "No movement found.",
|
||||
"history.udc.msg.error": "Search failed:\n{error}",
|
||||
"history.picking.title": "Picking List History",
|
||||
"history.picking.document": "Document:",
|
||||
"history.picking.year": "Year",
|
||||
"history.picking.udc_hint": "Empty UDC: current year. UDC search: current and previous year. Both filters apply when filled in.",
|
||||
"history.picking.udc_invalid": "Enter the complete numeric UDC code, up to 6 digits.",
|
||||
"history.picking.button.reload": "Reload",
|
||||
"history.picking.detail_title": "Content detail",
|
||||
"history.picking.busy.master": "Loading picking-list history...",
|
||||
@@ -188,11 +402,34 @@
|
||||
"history.picking.msg.title": "Picking List History",
|
||||
"history.picking.msg.load_error": "Load failed:\n{error}",
|
||||
"history.picking.msg.detail_error": "Detail load failed:\n{error}",
|
||||
"diagnostics.title": "Diagnostics",
|
||||
"diagnostics.button.shipped_not_disassociated": "Shipped UDC not disassociated",
|
||||
"diagnostics.button.multiple_udc_by_cell": "Cells with multiple UDC",
|
||||
"diagnostics.button.sam_udc_not_in_wms": "Latest UDC in SAM not in WMS",
|
||||
"diagnostics.button.export": "Export XLSX",
|
||||
"diagnostics.busy.shipped_not_disassociated": "Searching shipped UDC still assigned to cells...",
|
||||
"diagnostics.busy.multiple_udc_by_cell": "Searching cells with multiple UDC...",
|
||||
"diagnostics.busy.sam_udc_not_in_wms": "Searching latest UDC present in SAM but not yet in WMS...",
|
||||
"diagnostics.status.rows": "Rows found: {count}",
|
||||
"diagnostics.col.udc": "UDC",
|
||||
"diagnostics.col.cell": "CELL",
|
||||
"diagnostics.col.lot": "Lot",
|
||||
"diagnostics.col.product": "Product",
|
||||
"diagnostics.col.description": "Description",
|
||||
"diagnostics.col.shipped_not_disassociated": "Shipped but not disassociated",
|
||||
"diagnostics.col.symbolic_cell": "Symbolic cell name",
|
||||
"diagnostics.export.title": "Export",
|
||||
"diagnostics.export.empty": "There are no rows to export.",
|
||||
"diagnostics.export.dep": "Export requires 'openpyxl' (pip install openpyxl).",
|
||||
"diagnostics.export.ok": "File created:\n{path}",
|
||||
"diagnostics.export.error": "Export failed:\n{error}",
|
||||
"reset.title": "Aisle Management - empty cells by aisle",
|
||||
"reset.label.aisle": "Aisle:",
|
||||
"reset.button.refresh": "Load",
|
||||
"reset.button.empty": "Empty aisle...",
|
||||
"reset.summary": "Summary",
|
||||
"reset.confirm": "{udc} UDCs will be moved from {cells} cells in aisle {aisle}.\nUDCs associated with definitive shipping documents (state D): shipped to 9999 / 7G.1.1.\nAll others: non-shelved in 1000 (barcode 9001000).\nPick and put-away movements will be recorded, without deletions.\nThe check is performed when each UDC is moved.\nType the aisle name to confirm:",
|
||||
"reset.result": "Aisle {aisle}: moved {success} out of {total} UDCs.\nShipped to 9999 / 7G.1.1: {shipped}.\nNon-shelved in 1000: {non_shelved}.\nRefresh picking-list history to recalculate residuals.",
|
||||
"layout.title": "Aisle layout",
|
||||
"layout.button.search": "Search by UDC barcode",
|
||||
"layout.button.refresh": "Refresh",
|
||||
@@ -212,7 +449,30 @@
|
||||
"picking.button.reload": "Reload",
|
||||
"picking.button.prenota": "Reserve",
|
||||
"picking.button.sprenota": "Unreserve",
|
||||
"picking.button.sequence": "Pickup sequence",
|
||||
"picking.button.export": "Export XLSX",
|
||||
"picking.label.days": "Days:",
|
||||
"picking.sequence.title": "Pickup sequence",
|
||||
"picking.sequence.document": "Picking List {documento}",
|
||||
"picking.sequence.available": "Available racks",
|
||||
"picking.sequence.selected": "Custom order",
|
||||
"picking.sequence.hint": "Drag racks to the right. Missing racks are appended using the default order.",
|
||||
"picking.sequence.default_hint": "Default: non-shelved first, then racks in WMS order.",
|
||||
"picking.sequence.button.add": "Add >",
|
||||
"picking.sequence.button.remove": "< Remove",
|
||||
"picking.sequence.button.up": "Up",
|
||||
"picking.sequence.button.down": "Down",
|
||||
"picking.sequence.button.save": "Save",
|
||||
"picking.sequence.button.reset": "Restore default",
|
||||
"picking.sequence.button.close": "Close",
|
||||
"picking.sequence.busy.load": "Loading racks...",
|
||||
"picking.sequence.busy.save": "Saving sequence...",
|
||||
"picking.sequence.msg.select": "Select a Picking List before defining its sequence.",
|
||||
"picking.sequence.msg.denied": "Permission denied.",
|
||||
"picking.sequence.msg.saved": "Sequence saved.",
|
||||
"picking.sequence.msg.reset": "Custom sequence removed. The default order is active.",
|
||||
"picking.sequence.msg.load_error": "Load failed:\n{error}",
|
||||
"picking.sequence.msg.save_error": "Save failed:\n{error}",
|
||||
"scarico.title": "Unload {ubicazione}",
|
||||
"scarico.label.location": "Location: {ubicazione}",
|
||||
"scarico.label.select": "Select the UDCs to unload",
|
||||
@@ -220,6 +480,8 @@
|
||||
"scarico.col.last_insert": "Last insert",
|
||||
"scarico.col.diagnostic": "Diagnostics",
|
||||
"scarico.button.submit": "Unload",
|
||||
"scarico.button.shipped": "Unload as shipped",
|
||||
"scarico.button.non_shelved": "Unload as non-shelved",
|
||||
"scarico.button.close": "Close",
|
||||
"scarico.msg.title": "Unload",
|
||||
"scarico.msg.select_one": "Select at least one UDC to unload.",
|
||||
|
||||
@@ -6,6 +6,9 @@ import json
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
_LOCALE_FILE = Path(__file__).with_name("locale.json")
|
||||
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import ttk
|
||||
from typing import Any
|
||||
|
||||
from audit_log import log_session_event
|
||||
@@ -11,6 +12,9 @@ from gestione_aree import AsyncRunner
|
||||
from locale_text import load_locale_catalog, text as loc_text
|
||||
from ui_theme import theme_section, theme_value
|
||||
from user_session import UserSession, create_user_session
|
||||
from version_info import module_version, versioned_title
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
|
||||
SQL_LOGIN = """
|
||||
@@ -64,8 +68,8 @@ class LoginWindow(tk.Toplevel):
|
||||
self._show_ready_after_id: str | None = None
|
||||
self._clear_topmost_after_id: str | None = None
|
||||
|
||||
self.title(loc_text("login.msg.title", catalog=self._locale_catalog, default="Login"))
|
||||
self.geometry("170x145+0+0" if self.compact else str(theme_value(self._theme, "window_geometry", "165x155+0+0")))
|
||||
self.title(versioned_title(loc_text("login.msg.title", catalog=self._locale_catalog, default="Login"), __name__))
|
||||
self.geometry("170x148+0+0" if self.compact else str(theme_value(self._theme, "window_geometry", "165x170+0+0")))
|
||||
self.resizable(False, False)
|
||||
try:
|
||||
if parent is not None and parent.winfo_viewable():
|
||||
@@ -88,53 +92,59 @@ class LoginWindow(tk.Toplevel):
|
||||
def _build_ui(self) -> None:
|
||||
"""Build the compact operator login form."""
|
||||
|
||||
body = ttk.Frame(self, padding=8 if self.compact else 8)
|
||||
body = ttk.Frame(self, padding=6 if self.compact else 8)
|
||||
body.pack(fill="both", expand=True)
|
||||
body.columnconfigure(1, weight=0)
|
||||
|
||||
row_offset = 0
|
||||
|
||||
ttk.Label(body, text="User:").grid(row=row_offset, column=0, sticky="w", padx=(0, 4), pady=4)
|
||||
ttk.Label(body, text="User:").grid(row=row_offset, column=0, sticky="w", padx=(0, 4), pady=(2, 3))
|
||||
self.login_entry = ttk.Entry(body, textvariable=self.login_var, width=10, font=("Segoe UI", 10 if self.compact else 9))
|
||||
self.login_entry.grid(row=row_offset, column=1, sticky="w", pady=4)
|
||||
self.login_entry.grid(row=row_offset, column=1, sticky="w", pady=(2, 3))
|
||||
|
||||
ttk.Label(body, text="Pwd:").grid(row=row_offset + 1, column=0, sticky="w", padx=(0, 4), pady=4)
|
||||
ttk.Label(body, text="Pwd:").grid(row=row_offset + 1, column=0, sticky="w", padx=(0, 4), pady=(2, 2))
|
||||
self.password_entry = ttk.Entry(body, textvariable=self.password_var, width=10, show="*", font=("Segoe UI", 10 if self.compact else 9))
|
||||
self.password_entry.grid(row=row_offset + 1, column=1, sticky="w", pady=4)
|
||||
self.password_entry.grid(row=row_offset + 1, column=1, sticky="w", pady=(2, 2))
|
||||
|
||||
if self.compact:
|
||||
actions = ttk.Frame(body)
|
||||
actions.grid(row=row_offset + 2, column=0, columnspan=2, sticky="ew", pady=(6, 0))
|
||||
self._cancel_button = ttk.Button(
|
||||
actions,
|
||||
text="Annulla",
|
||||
command=self._on_cancel,
|
||||
)
|
||||
self._cancel_button.grid(row=1, column=0, sticky="ew", pady=(4, 0))
|
||||
actions.grid(row=row_offset + 2, column=0, columnspan=2, sticky="ew", pady=(3, 0))
|
||||
self._login_button = ttk.Button(
|
||||
actions,
|
||||
text="OK",
|
||||
command=self._on_login,
|
||||
)
|
||||
self._login_button.grid(row=0, column=0, sticky="ew")
|
||||
else:
|
||||
self.status_label = ttk.Label(body, textvariable=self._status_var, foreground="#555555")
|
||||
self.status_label.grid(row=2, column=0, columnspan=2, sticky="w", pady=(2, 2))
|
||||
|
||||
actions = ttk.Frame(body)
|
||||
actions.grid(row=3, column=0, columnspan=2, sticky="w", pady=(6, 0))
|
||||
self._cancel_button = ttk.Button(
|
||||
actions,
|
||||
text=loc_text("login.button.cancel", catalog=self._locale_catalog, default="Annulla"),
|
||||
text="Annulla",
|
||||
command=self._on_cancel,
|
||||
)
|
||||
self._cancel_button.grid(row=1, column=0, sticky="ew", pady=(4, 0))
|
||||
self._cancel_button.grid(row=1, column=0, sticky="ew", pady=(3, 0))
|
||||
else:
|
||||
self.status_label = ttk.Label(body, textvariable=self._status_var, foreground="#555555")
|
||||
self.status_label.grid(row=2, column=0, columnspan=2, sticky="w", pady=(1, 1))
|
||||
|
||||
actions = ttk.Frame(body)
|
||||
actions.grid(row=3, column=0, columnspan=2, sticky="w", pady=(3, 0))
|
||||
self._login_button = ttk.Button(
|
||||
actions,
|
||||
text=loc_text("login.button.submit", catalog=self._locale_catalog, default="OK"),
|
||||
command=self._on_login,
|
||||
)
|
||||
self._login_button.grid(row=0, column=0, sticky="ew")
|
||||
self._cancel_button = ttk.Button(
|
||||
actions,
|
||||
text=loc_text("login.button.cancel", catalog=self._locale_catalog, default="Annulla"),
|
||||
command=self._on_cancel,
|
||||
)
|
||||
self._cancel_button.grid(row=1, column=0, sticky="ew", pady=(3, 0))
|
||||
|
||||
for widget in (self.login_entry, self.password_entry, self._login_button, self._cancel_button):
|
||||
try:
|
||||
widget.configure(takefocus=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.bind("<Return>", lambda _e: self._on_login())
|
||||
self.bind("<Escape>", lambda _e: self._on_cancel())
|
||||
@@ -252,6 +262,7 @@ class LoginWindow(tk.Toplevel):
|
||||
loc_text("login.msg.title", catalog=self._locale_catalog, default="Login"),
|
||||
loc_text("login.msg.error", catalog=self._locale_catalog, default="Verifica credenziali fallita:\n{error}").format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
|
||||
self._async.run(
|
||||
|
||||
61
main.py
61
main.py
@@ -16,12 +16,15 @@ from runtime_support import ensure_stdio, run_with_fatal_log
|
||||
ensure_stdio("warehouse_main")
|
||||
|
||||
import customtkinter as ctk
|
||||
from tkinter import messagebox
|
||||
from PIL import Image, ImageDraw
|
||||
import error_dialog as messagebox
|
||||
|
||||
from async_loop_singleton import get_global_loop, stop_global_loop
|
||||
from async_msssql_query import AsyncMSSQLClient
|
||||
from audit_log import log_session_event
|
||||
from db_config import build_dsn_from_config, ensure_db_config
|
||||
from diagnostica import open_diagnostica_window
|
||||
from inventario import open_inventario_window
|
||||
from gestione_layout import open_layout_window
|
||||
from gestione_pickinglist import open_pickinglist_window
|
||||
from login_window import prompt_login
|
||||
@@ -31,8 +34,10 @@ from search_pallets import open_search_window
|
||||
from storico_pickinglist import open_storico_pickinglist_window
|
||||
from storico_udc import open_storico_udc_window
|
||||
from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text
|
||||
from udc_non_scaffalate import open_udc_non_scaffalate_window
|
||||
from ui_theme import theme_font, theme_section, theme_value
|
||||
from user_session import UserSession, create_user_session
|
||||
from version_info import module_version, versioned_title
|
||||
from view_celle_multi_udc import open_celle_multiple_window
|
||||
from window_placement import (
|
||||
cascade_children_below_parent,
|
||||
@@ -42,7 +47,8 @@ from window_placement import (
|
||||
|
||||
# Development shortcut: skip the login dialog and boot directly as MAG1.
|
||||
# Set to False when you want to restore normal authentication.
|
||||
BYPASS_LOGIN = False
|
||||
BYPASS_LOGIN = True
|
||||
__version__ = module_version(__name__)
|
||||
BYPASS_LOGIN_USER = {
|
||||
"operator_id": 4,
|
||||
"login": "MAG1",
|
||||
@@ -153,10 +159,13 @@ class Launcher(ctk.CTk):
|
||||
"reset_corsie",
|
||||
"layout",
|
||||
"multi_udc",
|
||||
"non_shelved",
|
||||
"search",
|
||||
"storico_udc",
|
||||
"pickinglist",
|
||||
"storico_pickinglist",
|
||||
"diagnostica",
|
||||
"inventario",
|
||||
]
|
||||
|
||||
def __init__(self, session: UserSession, db_client: AsyncMSSQLClient):
|
||||
@@ -176,7 +185,7 @@ class Launcher(ctk.CTk):
|
||||
color=str(theme_value(self._theme, "exit_icon_color", "#ca3d3d"))
|
||||
)
|
||||
self.title(
|
||||
f"{loc_text('launcher.window_title', catalog=self._locale_catalog, default='Warehouse 1.0.0')} - {self.session.display_name}"
|
||||
f"{versioned_title(loc_text('launcher.window_title', catalog=self._locale_catalog, default='Warehouse'), __name__)} - {self.session.display_name}"
|
||||
)
|
||||
self._apply_dynamic_geometry()
|
||||
|
||||
@@ -219,6 +228,15 @@ class Launcher(ctk.CTk):
|
||||
lambda: open_celle_multiple_window(self, self.db_client, session=self.session),
|
||||
),
|
||||
),
|
||||
(
|
||||
"non_shelved",
|
||||
loc_text("launcher.non_shelved", catalog=self._locale_catalog, default="UDC non scaffalate"),
|
||||
"launcher.open_non_shelved",
|
||||
lambda: self._open_or_focus_child_window(
|
||||
"non_shelved",
|
||||
lambda: open_udc_non_scaffalate_window(self, self.db_client, session=self.session),
|
||||
),
|
||||
),
|
||||
(
|
||||
"search",
|
||||
loc_text("launcher.search", catalog=self._locale_catalog, default="Ricerca UDC"),
|
||||
@@ -255,6 +273,24 @@ class Launcher(ctk.CTk):
|
||||
lambda: open_storico_pickinglist_window(self, self.db_client, session=self.session),
|
||||
),
|
||||
),
|
||||
(
|
||||
"diagnostica",
|
||||
loc_text("launcher.diagnostics", catalog=self._locale_catalog, default="Diagnostica"),
|
||||
"launcher.open_diagnostics",
|
||||
lambda: self._open_or_focus_child_window(
|
||||
"diagnostica",
|
||||
lambda: open_diagnostica_window(self, self.db_client, session=self.session),
|
||||
),
|
||||
),
|
||||
(
|
||||
"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",
|
||||
loc_text("launcher.arrange", catalog=self._locale_catalog, default="Ridisponi finestre"),
|
||||
@@ -322,17 +358,18 @@ class Launcher(ctk.CTk):
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _make_exit_icon(self, *, color: str) -> tk.PhotoImage:
|
||||
"""Create a small red X icon without adding image assets to the project."""
|
||||
def _make_exit_icon(self, *, color: str) -> ctk.CTkImage:
|
||||
"""Create a transparent X with extra resolution for HighDPI scaling."""
|
||||
|
||||
size = 14
|
||||
image = tk.PhotoImage(width=size, height=size)
|
||||
for offset in range(3, 11):
|
||||
image.put(color, (offset, offset))
|
||||
image.put(color, (offset + 1, offset))
|
||||
image.put(color, (offset, size - 1 - offset))
|
||||
image.put(color, (offset + 1, size - 1 - offset))
|
||||
return image
|
||||
scale = 3
|
||||
image = Image.new("RGBA", (size * scale, size * scale), (0, 0, 0, 0))
|
||||
draw = ImageDraw.Draw(image)
|
||||
draw.line((3 * scale, 3 * scale, 10 * scale, 10 * scale),
|
||||
fill=color, width=2 * scale)
|
||||
draw.line((3 * scale, 10 * scale, 10 * scale, 3 * scale),
|
||||
fill=color, width=2 * scale)
|
||||
return ctk.CTkImage(light_image=image, dark_image=image, size=(size, size))
|
||||
|
||||
def _apply_dynamic_geometry(self) -> None:
|
||||
"""Size the launcher around its current content and keep it docked at the top."""
|
||||
|
||||
414
ordinamento.md
Normal file
414
ordinamento.md
Normal file
@@ -0,0 +1,414 @@
|
||||
# Ordinamento di prelievo delle celle
|
||||
|
||||
## 1. Scopo del documento
|
||||
|
||||
Questo documento descrive il significato e l'origine del campo
|
||||
`dbo.Celle.Ordinamento`, il modo in cui viene utilizzato per proporre le UDC al
|
||||
barcode e le differenze riscontrate tra i due magazzini storici:
|
||||
|
||||
- Area 5, identificata nel database legacy come magazzino `MDE5`;
|
||||
- Area 6, identificata nel database legacy come magazzino `MDE6`.
|
||||
|
||||
Nel linguaggio operativo si parla di Area 5 e Area 6. Nel modello legacy,
|
||||
tuttavia, la tabella `Magazzini` contiene `MDE5` e `MDE6`, mentre la tabella
|
||||
`Aree` contiene le singole corsie o scaffali. Gli ID della tabella `Aree` non
|
||||
devono quindi essere confusi con i nomi operativi Area 5 e Area 6.
|
||||
|
||||
Le conclusioni riportate derivano da:
|
||||
|
||||
- struttura e dati correnti della tabella `dbo.Celle`;
|
||||
- stored procedure legacy contenute in `script.sql`;
|
||||
- viste usate dalle picking list;
|
||||
- codice Python del barcode e della gestione picking list;
|
||||
- confronto tra `ID`, ubicazione e `Ordinamento` delle celle reali.
|
||||
|
||||
## 2. Significato di `Celle.Ordinamento`
|
||||
|
||||
`Celle.Ordinamento` e' una priorita' numerica associata all'anagrafica della
|
||||
cella. Rappresenta la posizione della cella nel percorso predefinito di
|
||||
prelievo.
|
||||
|
||||
Il campo non indica:
|
||||
|
||||
- la quantita' di UDC presenti;
|
||||
- la priorita' della picking list;
|
||||
- lo stato libero o occupato della cella;
|
||||
- l'ordine cronologico di inserimento delle UDC;
|
||||
- l'ID della UDC;
|
||||
- la distanza calcolata dinamicamente dal barcode.
|
||||
|
||||
Il valore non viene ricalcolato durante un versamento o un prelievo. E' un dato
|
||||
statico dell'anagrafica della cella, salvo interventi amministrativi o
|
||||
procedure specifiche di rinumerazione.
|
||||
|
||||
Il tipo SQL storico e' `float`, ma nei dati analizzati viene usato come numero
|
||||
intero progressivo. Nella futura riprogettazione sarebbe preferibile un tipo
|
||||
intero o una struttura esplicita di percorso.
|
||||
|
||||
## 3. Dove viene assegnato
|
||||
|
||||
La stored procedure legacy `dbo.spt_SaveCelle` riceve il parametro
|
||||
`@Ordinamento` e lo salva direttamente:
|
||||
|
||||
```sql
|
||||
UPDATE Celle
|
||||
SET Ordinamento = @Ordinamento
|
||||
WHERE ID = @ID;
|
||||
```
|
||||
|
||||
Se la cella non esiste, la stessa stored procedure esegue una `INSERT` e
|
||||
inserisce il valore ricevuto. La procedura non contiene una formula per
|
||||
calcolarlo: chi crea o modifica la cella deve decidere il valore e passarlo.
|
||||
|
||||
Nel database non risultano trigger sulla tabella `Celle` che aggiornino
|
||||
automaticamente `Ordinamento`.
|
||||
|
||||
Sono state individuate anche procedure legacy di supporto:
|
||||
|
||||
- `CreaNuoveCelle`;
|
||||
- `CreaNuoveCelleMDE6`;
|
||||
- `CreaNuoveCelleMDE6_BIS`;
|
||||
- `sp_OrdinaCelle`;
|
||||
- `spt_SaveCelle`.
|
||||
|
||||
Le procedure di creazione MDE6 impostano normalmente:
|
||||
|
||||
```sql
|
||||
SET @Ordinamento = @ID;
|
||||
```
|
||||
|
||||
La procedura `sp_OrdinaCelle` dimostra invece che il campo puo' essere
|
||||
rinumerato in un secondo momento per rappresentare un percorso differente
|
||||
dall'ID della cella.
|
||||
|
||||
## 4. Uso durante una picking list
|
||||
|
||||
Le viste operative associano ogni UDC alla cella corrente e recuperano
|
||||
`Celle.Ordinamento`. Il barcode richiede la prima riga residua secondo l'ordine
|
||||
effettivo.
|
||||
|
||||
Prima dell'introduzione della sequenza personalizzata, il criterio principale
|
||||
era sostanzialmente:
|
||||
|
||||
```sql
|
||||
ORDER BY Ordinamento;
|
||||
```
|
||||
|
||||
Questo significa che il barcode non percorre tutte le celle del magazzino. La
|
||||
vista contiene soltanto le UDC ancora presenti nella picking list: le celle che
|
||||
non contengono una UDC richiesta vengono saltate automaticamente.
|
||||
|
||||
Esempio: se il percorso contiene le celle con ordine `1001`, `1002`, `1003` e
|
||||
`1004`, ma la picking list contiene UDC soltanto nelle celle `1001` e `1004`, il
|
||||
barcode propone direttamente la UDC di `1001` e poi quella di `1004`.
|
||||
|
||||
## 5. Ordinamento dell'Area 5 / MDE5
|
||||
|
||||
### 5.1 Caratteristica generale
|
||||
|
||||
Nell'Area 5 `Ordinamento` non coincide normalmente con l'ID della cella. Dai
|
||||
dati emerge un percorso fisico costruito intenzionalmente, verosimilmente
|
||||
hardcoded o rinumerato durante la configurazione iniziale del magazzino.
|
||||
|
||||
Le corsie principali coinvolte sono:
|
||||
|
||||
- `1A`;
|
||||
- `2B`;
|
||||
- `3C`;
|
||||
- `4D`.
|
||||
|
||||
Il percorso iniziale delle corsie `1A` e `2B` e' a serpentina. Le due corsie
|
||||
vengono trattate come lati o scaffali adiacenti di uno stesso tragitto fisico.
|
||||
|
||||
### 5.2 Esempio reale dell'inizio del percorso
|
||||
|
||||
```text
|
||||
Ordine Ubicazione ID cella
|
||||
1001 1A.1.e 1005
|
||||
1002 1A.1.d 1004
|
||||
1003 1A.1.c 1003
|
||||
1004 1A.1.b 1002
|
||||
1005 1A.1.a 1001
|
||||
|
||||
1007 2B.1.e 2005
|
||||
1008 2B.1.d 2004
|
||||
1009 2B.1.c 2003
|
||||
1010 2B.1.b 2002
|
||||
1011 2B.1.a 2001
|
||||
|
||||
1013 2B.2.e 2011
|
||||
1014 2B.2.d 2010
|
||||
1015 2B.2.c 2009
|
||||
1016 2B.2.b 2008
|
||||
1017 2B.2.a 2007
|
||||
|
||||
1019 1A.2.e 1011
|
||||
1020 1A.2.d 1010
|
||||
1021 1A.2.c 1009
|
||||
1022 1A.2.b 1008
|
||||
1023 1A.2.a 1007
|
||||
```
|
||||
|
||||
La sequenza prosegue con lo stesso principio:
|
||||
|
||||
```text
|
||||
1A campata 1
|
||||
2B campata 1
|
||||
2B campata 2
|
||||
1A campata 2
|
||||
1A campata 3
|
||||
2B campata 3
|
||||
2B campata 4
|
||||
1A campata 4
|
||||
...
|
||||
```
|
||||
|
||||
### 5.3 Movimento verticale nella campata
|
||||
|
||||
All'interno di ciascuna campata l'ordine verificato e':
|
||||
|
||||
```text
|
||||
e -> d -> c -> b -> a
|
||||
```
|
||||
|
||||
Il percorso procede quindi dal livello identificato con `e` verso il livello
|
||||
`a`. Non viene prelevata una sola UDC per campata per poi ricominciare il giro.
|
||||
Vengono considerate, in sequenza, tutte le celle richieste della campata
|
||||
corrente prima di passare alla campata successiva.
|
||||
|
||||
Se una campata contiene piu' UDC richieste in livelli diversi, il barcode le
|
||||
propone secondo `e, d, c, b, a`. Se alcuni livelli non contengono UDC della
|
||||
picking list, vengono semplicemente saltati.
|
||||
|
||||
### 5.4 Alternanza tra 1A e 2B
|
||||
|
||||
Il sistema non esaurisce tutto `1A` prima di iniziare `2B`. Alterna blocchi di
|
||||
campate tra le due corsie per seguire un tragitto a serpentina ed evitare
|
||||
ritorni inutili.
|
||||
|
||||
Il comportamento predefinito storico e' quindi:
|
||||
|
||||
- completare le UDC richieste nella campata corrente;
|
||||
- passare alla campata fisicamente successiva del percorso;
|
||||
- alternare `1A` e `2B` secondo la serpentina configurata;
|
||||
- non tornare all'inizio dopo ogni singola UDC.
|
||||
|
||||
### 5.5 Passaggio a 3C e 4D
|
||||
|
||||
Le corsie `3C` e `4D` hanno valori di ordinamento molto piu' alti. Nei dati
|
||||
analizzati:
|
||||
|
||||
```text
|
||||
1A: minimo 1001, massimo 1275
|
||||
2B: minimo 1007, massimo 1251
|
||||
3C: minimo 10019, massimo 10227
|
||||
4D: valori nell'intervallo 10055 - 10233 circa
|
||||
```
|
||||
|
||||
Di conseguenza il percorso storico esaurisce normalmente il blocco `1A/2B`
|
||||
prima di passare al blocco `3C/4D`.
|
||||
|
||||
La presenza di famiglie numeriche differenti indica che l'ordinamento
|
||||
dell'Area 5 e' stato costruito o modificato in piu' fasi storiche.
|
||||
|
||||
### 5.6 Significato dei numeri mancanti
|
||||
|
||||
La progressione contiene intervalli non utilizzati, per esempio `1005` seguito
|
||||
da `1007`. Il numero mancante non indica necessariamente una cella eliminata o
|
||||
un errore. Puo' essere stato lasciato come separatore tra campate o derivare
|
||||
dalla procedura di rinumerazione.
|
||||
|
||||
Il software deve usare il confronto numerico e non deve presumere che tutti i
|
||||
valori siano consecutivi.
|
||||
|
||||
## 6. Ordinamento dell'Area 6 / MDE6
|
||||
|
||||
### 6.1 Caratteristica generale
|
||||
|
||||
Nell'Area 6 il modello e' piu' semplice. La maggior parte delle celle e' stata
|
||||
generata con `Ordinamento` uguale all'ID della cella.
|
||||
|
||||
Le famiglie principali sono:
|
||||
|
||||
```text
|
||||
1M -> celle e ordinamenti 5001, 5002, 5003, ...
|
||||
2N -> celle e ordinamenti 6001, 6002, 6003, ...
|
||||
3O -> celle e ordinamenti 7001, 7002, 7003, ...
|
||||
4P -> celle e ordinamenti 8001, 8002, 8003, ...
|
||||
```
|
||||
|
||||
Le procedure `CreaNuoveCelleMDE6` e `CreaNuoveCelleMDE6_BIS` creano le celle
|
||||
con cicli annidati e assegnano esplicitamente:
|
||||
|
||||
```sql
|
||||
SET @Ordinamento = @ID;
|
||||
```
|
||||
|
||||
### 6.2 Ordine degli scaffali
|
||||
|
||||
Poiche' le famiglie numeriche sono separate, l'ordine globale predefinito e':
|
||||
|
||||
```text
|
||||
1M -> 2N -> 3O -> 4P
|
||||
```
|
||||
|
||||
Senza una sequenza personalizzata vengono quindi considerate prima tutte le
|
||||
UDC richieste in `1M`, poi quelle in `2N`, successivamente `3O` e infine `4P`.
|
||||
|
||||
### 6.3 Ordine interno dello scaffale
|
||||
|
||||
Durante la generazione delle celle, i cicli legacy incrementano prima la
|
||||
campata e, all'interno della campata, il piano. L'ordine risultante e':
|
||||
|
||||
```text
|
||||
1M.1.a -> 1M.1.b -> 1M.1.c -> 1M.1.d -> 1M.1.e
|
||||
1M.2.a -> 1M.2.b -> 1M.2.c -> 1M.2.d -> 1M.2.e
|
||||
...
|
||||
2N.1.a -> 2N.1.b -> ...
|
||||
```
|
||||
|
||||
Quindi l'Area 6 differisce dall'Area 5 in due aspetti principali:
|
||||
|
||||
- non presenta l'alternanza a serpentina tra due corsie adiacenti;
|
||||
- dentro la campata procede da `a` verso `e`, mentre nell'Area 5 verificata
|
||||
procede da `e` verso `a`.
|
||||
|
||||
### 6.4 Limiti della ricostruzione
|
||||
|
||||
Il comportamento descritto deriva dalla procedura di generazione e dai valori
|
||||
correnti. Eventuali celle aggiunte manualmente in tempi successivi possono
|
||||
avere eccezioni. L'applicazione deve sempre leggere il valore effettivo dal
|
||||
database e non ricostruirlo aritmeticamente dall'ubicazione.
|
||||
|
||||
## 7. Celle virtuali
|
||||
|
||||
Nel sistema legacy esistono due ubicazioni convenzionali:
|
||||
|
||||
```text
|
||||
ID 1000 -> 5E.1.1 -> Non scaff. -> Ordinamento 99999
|
||||
ID 9999 -> 7G.1.1 -> Spedita -> Ordinamento 0
|
||||
```
|
||||
|
||||
Questi valori non rappresentano un percorso fisico:
|
||||
|
||||
- `5E.1.1` identifica UDC presenti nel magazzino ma non allocate in uno
|
||||
scaffale fisico;
|
||||
- `7G.1.1` identifica UDC spedite.
|
||||
|
||||
Storicamente `Non scaff.` aveva ordinamento `99999`, quindi finiva in fondo
|
||||
alla picking list. Il nuovo requisito operativo stabilisce invece che le UDC
|
||||
non scaffalate devono essere proposte per prime.
|
||||
|
||||
La nuova vista Python non modifica `Celle.Ordinamento`: assegna a `Non scaff.`
|
||||
una precedenza logica di gruppo pari a zero. La cella `Spedita` non entra nella
|
||||
vista residuale e quindi non viene proposta dal barcode.
|
||||
|
||||
## 8. Nuovo ordinamento predefinito Python
|
||||
|
||||
In assenza di una configurazione specifica per il documento, il nuovo ordine
|
||||
effettivo e':
|
||||
|
||||
1. tutte le UDC `Non scaff.` ancora appartenenti alla picking list;
|
||||
2. tutte le UDC nelle celle fisiche secondo `Celle.Ordinamento`;
|
||||
3. codice pallet come criterio stabile in caso di parita'.
|
||||
|
||||
In forma semplificata:
|
||||
|
||||
```sql
|
||||
ORDER BY
|
||||
OrdinePrelievoGruppo,
|
||||
Ordinamento,
|
||||
Pallet;
|
||||
```
|
||||
|
||||
Per le celle fisiche, se non esiste una personalizzazione,
|
||||
`OrdinePrelievoGruppo` conserva la progressione storica. Il percorso dell'Area
|
||||
5 rimane quindi a serpentina e quello dell'Area 6 rimane progressivo.
|
||||
|
||||
## 9. Effetto della sequenza personalizzata
|
||||
|
||||
La sequenza personalizzata opera a livello di gruppo o scaffale, non a livello
|
||||
di singola cella.
|
||||
|
||||
Esempio di configurazione:
|
||||
|
||||
```text
|
||||
1. Non scaff.
|
||||
2. 3C
|
||||
3. 1A
|
||||
4. 2B
|
||||
5. 4D
|
||||
```
|
||||
|
||||
In questo caso il sistema esaurisce prima il gruppo `Non scaff.`, poi tutte le
|
||||
UDC di `3C`, quindi tutte quelle di `1A` e cosi' via.
|
||||
|
||||
All'interno di ciascun gruppo continua a usare `Celle.Ordinamento`. Per
|
||||
esempio, se `1A` viene posizionata prima di `2B`, non viene piu' conservata
|
||||
l'alternanza storica tra `1A` e `2B`: vengono esaurite prima tutte le UDC di
|
||||
`1A`, nel loro ordine interno, e successivamente quelle di `2B`.
|
||||
|
||||
Questa differenza e' intenzionale:
|
||||
|
||||
- ordine predefinito: conserva il percorso storico globale;
|
||||
- ordine personalizzato: impone la precedenza degli scaffali scelta
|
||||
dall'operatore e conserva l'ordine storico soltanto dentro ogni scaffale.
|
||||
|
||||
Se la sequenza personalizzata non include tutti i gruppi, quelli mancanti
|
||||
vengono accodati secondo il percorso predefinito. Nessuna UDC viene esclusa.
|
||||
|
||||
## 10. UDC multiple, lotti e parita' di ordine
|
||||
|
||||
Piu' righe della vista possono riferirsi alla stessa UDC quando contiene piu'
|
||||
lotti o articoli. Questo non significa che il magazziniere debba movimentare
|
||||
fisicamente la stessa UDC piu' volte: l'unita' di movimentazione rimane il
|
||||
pallet/UDC.
|
||||
|
||||
Piu' UDC possono inoltre risultare associate alla stessa cella nel modello
|
||||
legacy. In quel caso condividono lo stesso `Ordinamento`. Il nuovo codice usa
|
||||
anche `Pallet` come criterio finale per rendere stabile la sequenza, ma il
|
||||
percorso fisico resta quello della cella.
|
||||
|
||||
## 11. Considerazioni per la futura riprogettazione
|
||||
|
||||
Nel futuro FlyWMS Core e' consigliabile separare esplicitamente:
|
||||
|
||||
- ordine fisico della cella dentro lo scaffale;
|
||||
- ordine predefinito degli scaffali;
|
||||
- percorso o strategia di visita del magazzino;
|
||||
- ordine personalizzato per documento;
|
||||
- priorita' operativa della picking list;
|
||||
- eventuale ottimizzazione dinamica del percorso.
|
||||
|
||||
Il campo legacy `Celle.Ordinamento` incorpora piu' significati e dipende da
|
||||
decisioni storiche non completamente documentate. Non dovrebbe essere copiato
|
||||
alla lettera nel nuovo modello dati senza scomporne la semantica.
|
||||
|
||||
Una possibile struttura futura potrebbe prevedere:
|
||||
|
||||
- `Location.SequenceWithinRack` per l'ordine interno;
|
||||
- `Rack.DefaultSequence` per l'ordine tra scaffali;
|
||||
- `Route` e `RouteStep` per percorsi configurabili;
|
||||
- `PickingDocumentRoute` per la personalizzazione della singola lista.
|
||||
|
||||
## 12. Riferimenti tecnici nel progetto
|
||||
|
||||
- `script.sql`: definizioni di `spt_SaveCelle`, `CreaNuoveCelleMDE6`,
|
||||
`CreaNuoveCelleMDE6_BIS` e `sp_OrdinaCelle`;
|
||||
- `barcode_repository.py`: interrogazione della prossima UDC;
|
||||
- `gestione_pickinglist.py`: visualizzazione del dettaglio ordinato;
|
||||
- `pickinglist_sequence.py`: gestione della sequenza per documento;
|
||||
- `apply_pickinglist_sequence_patch.sql`: tabella e vista Python dedicate;
|
||||
- `specifica_sequenza_prelievo.md`: specifica funzionale della nuova
|
||||
configurazione.
|
||||
|
||||
## 13. Conclusione
|
||||
|
||||
L'Area 5 utilizza un percorso storico a serpentina, costruito per alternare
|
||||
corsie e campate secondo la disposizione fisica. L'Area 6 utilizza invece una
|
||||
progressione piu' semplice, sostanzialmente coincidente con gli ID creati in
|
||||
sequenza.
|
||||
|
||||
Il nuovo software conserva entrambi i comportamenti come default, anticipa le
|
||||
UDC non scaffalate e permette di sostituire l'ordine globale degli scaffali per
|
||||
una singola picking list senza modificare l'anagrafica delle celle.
|
||||
100
pickinglist_history_search.py
Normal file
100
pickinglist_history_search.py
Normal file
@@ -0,0 +1,100 @@
|
||||
"""Read-only UDC lookup across the current and previous ERP document years.
|
||||
|
||||
Unlike the default history view this query retains BAMTES.ID, so documents with
|
||||
the same display number in different years cannot share details or movements.
|
||||
The UDC selects documents, not detail rows: counts always describe whole lists.
|
||||
"""
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
_BASE = """
|
||||
DECLARE @UDC varchar(32) = :pallet;
|
||||
DECLARE @Document varchar(32) = :documento;
|
||||
DECLARE @DocumentID int = :id_documento;
|
||||
WITH documents AS (
|
||||
SELECT bt.*
|
||||
FROM SAMA1.dbo.BAMTES bt
|
||||
WHERE bt.ANNDOC BETWEEN YEAR(GETDATE()) - 1 AND YEAR(GETDATE())
|
||||
AND bt.STATO IN ('P', 'D')
|
||||
AND (@DocumentID IS NULL OR bt.ID = @DocumentID)
|
||||
AND (@Document IS NULL OR CAST(bt.NUMDOC AS varchar(32)) LIKE '%' + @Document + '%')
|
||||
AND (@UDC IS NULL OR EXISTS (
|
||||
SELECT 1 FROM SAMA1.dbo.FATRIG fr
|
||||
JOIN SAMA1.dbo.LOTTIBF lb ON lb.IDFATRIG = fr.ID
|
||||
JOIN SAMA1.dbo.LOTSER ls ON ls.ID = lb.IDLOTSER
|
||||
WHERE fr.IDBAM = bt.ID
|
||||
AND ls.NUMLOT NOT IN ('', '00000000000')
|
||||
AND LEFT(ls.NUMSER, 6) COLLATE Latin1_General_CI_AS = @UDC COLLATE Latin1_General_CI_AS
|
||||
))
|
||||
), prep AS (
|
||||
SELECT bt.ID AS IDDocumento, bt.ANNDOC AS AnnoDocumento,
|
||||
bt.NUMDOC AS Documento, bt.DATDOC AS DataDocumento, bt.STATO AS StatoDocumento,
|
||||
LEFT(ls.NUMSER, 6) AS Pallet, ls.NUMLOT AS Lotto, a.CODICE AS Articolo,
|
||||
fr.DESCR AS Descrizione, SUM(ls.QTTGIAI) AS Qta,
|
||||
n.CODICE AS CodNazione, mt.CODICE + ' ' + n.DESCR AS NAZIONE
|
||||
FROM documents bt
|
||||
JOIN SAMA1.dbo.FATRIG fr ON fr.IDBAM = bt.ID
|
||||
JOIN SAMA1.dbo.LOTTIBF lb ON lb.IDFATRIG = fr.ID
|
||||
JOIN SAMA1.dbo.LOTSER ls ON ls.ID = lb.IDLOTSER
|
||||
LEFT JOIN SAMA1.dbo.ARTICO a ON a.ID = ls.IDARTICO
|
||||
LEFT JOIN SAMA1.dbo.NAZIONI n ON n.ID = bt.IDNAZDEST
|
||||
LEFT JOIN SAMA1.dbo.MTRASP mt ON mt.ID = bt.IDMTRASP
|
||||
WHERE ls.NUMLOT NOT IN ('', '00000000000')
|
||||
GROUP BY bt.ID, bt.ANNDOC, bt.NUMDOC, bt.DATDOC, bt.STATO,
|
||||
LEFT(ls.NUMSER, 6), ls.NUMLOT, a.CODICE, fr.DESCR, n.CODICE, mt.CODICE, n.DESCR
|
||||
), locations AS (
|
||||
SELECT g.BarcodePallet, g.IDCella, c.Ordinamento,
|
||||
c.Corsia + ' - ' + c.Colonna + ' - ' + c.Fila AS Ubicazione
|
||||
FROM dbo.XMag_GiacenzaPallet g JOIN dbo.Celle c ON c.ID = g.IDCella
|
||||
), base AS (
|
||||
SELECT prep.*, ISNULL(g.IDCella, 1000) AS Cella,
|
||||
ISNULL(g.Ordinamento, 99999) AS Ordinamento,
|
||||
ISNULL(g.Ubicazione, 'Non scaff.') AS Ubicazione,
|
||||
CASE WHEN prep.AnnoDocumento = YEAR(GETDATE()) AND EXISTS (
|
||||
SELECT 1 FROM dbo.PyPickingListReservation pr
|
||||
WHERE pr.ID = 1 AND pr.Documento = CAST(prep.Documento AS varchar(8))
|
||||
) THEN 1 ELSE 0 END AS IDStato
|
||||
FROM prep LEFT JOIN locations g
|
||||
ON g.BarcodePallet COLLATE Latin1_General_CI_AS = prep.Pallet COLLATE Latin1_General_CI_AS
|
||||
)
|
||||
"""
|
||||
|
||||
SQL_UDC_HISTORY_DETAILS = _BASE + """
|
||||
SELECT * FROM base ORDER BY Ordinamento, Pallet, Lotto;
|
||||
"""
|
||||
|
||||
SQL_UDC_HISTORY = _BASE + """
|
||||
, pallets AS (
|
||||
SELECT IDDocumento, Pallet,
|
||||
MAX(CASE WHEN Cella <> 9999 THEN 1 ELSE 0 END) AS HasResiduo
|
||||
FROM base WHERE NULLIF(LTRIM(RTRIM(Pallet)), '') IS NOT NULL
|
||||
GROUP BY IDDocumento, Pallet
|
||||
), totals AS (
|
||||
SELECT IDDocumento, COUNT(*) AS TotUDC, SUM(HasResiduo) AS RigheResidue,
|
||||
SUM(1 - HasResiduo) AS RigheSpedite
|
||||
FROM pallets GROUP BY IDDocumento
|
||||
), meta AS (
|
||||
SELECT IDDocumento, MAX(AnnoDocumento) AS AnnoDocumento,
|
||||
MAX(Documento) AS Documento, MAX(DataDocumento) AS DataDocumento,
|
||||
MAX(StatoDocumento) AS StatoDocumento, MAX(NAZIONE) AS NAZIONE,
|
||||
MAX(CodNazione) AS CodNazione, MAX(IDStato) AS IDStato
|
||||
FROM base GROUP BY IDDocumento
|
||||
)
|
||||
SELECT m.*, ISNULL(t.TotUDC, 0) AS TotUDC, ISNULL(t.RigheResidue, 0) AS RigheResidue,
|
||||
ISNULL(t.RigheSpedite, 0) AS RigheSpedite,
|
||||
CASE WHEN m.StatoDocumento = 'D' AND ISNULL(t.RigheResidue, 0) > 0 THEN 'Chiusa ERP con residui'
|
||||
WHEN m.StatoDocumento = 'D' THEN 'Chiusa'
|
||||
WHEN ISNULL(t.RigheResidue, 0) = 0 THEN 'Esaurita'
|
||||
WHEN ISNULL(t.RigheSpedite, 0) > 0 THEN 'In corso'
|
||||
ELSE 'Da lavorare' END AS StatoOperativo
|
||||
FROM meta m LEFT JOIN totals t ON t.IDDocumento = m.IDDocumento
|
||||
ORDER BY m.DataDocumento DESC, m.Documento DESC, m.IDDocumento DESC;
|
||||
"""
|
||||
|
||||
|
||||
def detail_request(documento: str, document_id: int | None, default_sql: str):
|
||||
"""Return a bound detail query; never use a cross-year display number alone."""
|
||||
if document_id is not None:
|
||||
return SQL_UDC_HISTORY_DETAILS, {"pallet": None, "documento": None, "id_documento": document_id}
|
||||
return default_sql, {"documento": documento}
|
||||
586
pickinglist_sequence.py
Normal file
586
pickinglist_sequence.py
Normal file
@@ -0,0 +1,586 @@
|
||||
"""Editor for the per-document picking-list pickup sequence.
|
||||
|
||||
The barcode client remains unaware of the editor: it reads the effective order
|
||||
from ``dbo.py_ViewPackingListPrelievo``. This module only manages the Python-
|
||||
specific configuration rows used by that view.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable
|
||||
import tkinter as tk
|
||||
import error_dialog as messagebox
|
||||
|
||||
import customtkinter as ctk
|
||||
|
||||
from busy_overlay import InlineBusyOverlay
|
||||
from gestione_aree import AsyncRunner
|
||||
from locale_text import load_locale_catalog, text as loc_text
|
||||
from ui_theme import theme_color, theme_font, theme_section
|
||||
from user_session import UserSession
|
||||
from version_info import module_version, versioned_title
|
||||
from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
|
||||
SQL_LOAD_GROUPS = """
|
||||
SELECT
|
||||
GruppoPrelievoChiave,
|
||||
MAX(GruppoPrelievo) AS GruppoPrelievo,
|
||||
MIN(OrdineGruppoDefault) AS OrdineGruppoDefault,
|
||||
MIN(OrdineGruppoConfigurato) AS OrdineGruppoConfigurato
|
||||
FROM dbo.py_ViewPackingListPrelievo
|
||||
WHERE CAST(Documento AS varchar(50)) = :documento
|
||||
AND Cella <> 9999
|
||||
GROUP BY GruppoPrelievoChiave
|
||||
ORDER BY
|
||||
CASE WHEN MIN(OrdineGruppoConfigurato) IS NULL THEN 1 ELSE 0 END,
|
||||
MIN(OrdineGruppoConfigurato),
|
||||
MIN(OrdineGruppoDefault),
|
||||
MAX(GruppoPrelievo);
|
||||
"""
|
||||
|
||||
|
||||
SQL_RESET_SEQUENCE = """
|
||||
SET NOCOUNT ON;
|
||||
SET XACT_ABORT ON;
|
||||
UPDATE dbo.py_PickingListPrelievoSequenza
|
||||
SET DelUtente = :utente,
|
||||
DelDataOra = SYSDATETIME(),
|
||||
ModUtente = :utente,
|
||||
ModDataOra = SYSDATETIME()
|
||||
WHERE Documento = :documento
|
||||
AND DelDataOra IS NULL;
|
||||
SELECT CAST(0 AS int) AS ElementiSalvati;
|
||||
"""
|
||||
|
||||
|
||||
def _rows_to_dicts(result: dict[str, Any] | None) -> list[dict[str, Any]]:
|
||||
"""Convert the shared database payload to dictionaries."""
|
||||
|
||||
if not isinstance(result, dict):
|
||||
return []
|
||||
rows = result.get("rows") or []
|
||||
columns = result.get("columns") or []
|
||||
if rows and isinstance(rows[0], dict):
|
||||
return [dict(row) for row in rows]
|
||||
return [
|
||||
{str(columns[index]): row[index] for index in range(min(len(columns), len(row)))}
|
||||
for row in rows
|
||||
if isinstance(row, (list, tuple))
|
||||
]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PickupGroup:
|
||||
"""One rack group, or the conventional non-shelved group."""
|
||||
|
||||
key: str
|
||||
label: str
|
||||
default_order: int
|
||||
|
||||
|
||||
class PickingListSequenceWindow(ctk.CTkToplevel):
|
||||
"""Drag-and-drop editor for one picking-list pickup sequence."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent: tk.Misc,
|
||||
db_client,
|
||||
*,
|
||||
documento: str,
|
||||
session: UserSession | None,
|
||||
on_saved: Callable[[], None] | None = None,
|
||||
):
|
||||
super().__init__(parent)
|
||||
self.db_client = db_client
|
||||
self.documento = str(documento or "").strip()
|
||||
self.session = session
|
||||
self.on_saved = on_saved
|
||||
self._catalog = load_locale_catalog()
|
||||
self._tooltip_catalog = load_tooltip_catalog()
|
||||
self._theme = theme_section("picking_sequence_window", {})
|
||||
self.runner = AsyncRunner(self)
|
||||
self.busy = InlineBusyOverlay(self, self._theme)
|
||||
self.available: list[PickupGroup] = []
|
||||
self.selected: list[PickupGroup] = []
|
||||
self._selected_key: str | None = None
|
||||
self._selected_side: str | None = None
|
||||
self._drag_group: PickupGroup | None = None
|
||||
self._drag_side: str | None = None
|
||||
|
||||
self.title(versioned_title(self._t("picking.sequence.title", "Sequenza di prelievo"), __name__))
|
||||
self.geometry("780x560")
|
||||
self.minsize(680, 480)
|
||||
self.transient(parent)
|
||||
self.configure(fg_color=theme_color(self._theme, "window_fg_color", ("#efefef", "#2f2f2f")))
|
||||
self.protocol("WM_DELETE_WINDOW", self.destroy)
|
||||
self.bind("<Escape>", lambda _event: self.destroy())
|
||||
|
||||
self._build_layout()
|
||||
self.withdraw()
|
||||
self.after_idle(self._show_and_load)
|
||||
|
||||
def _t(self, key: str, default: str, **values: Any) -> str:
|
||||
"""Return one localized and formatted label."""
|
||||
|
||||
value = loc_text(key, catalog=self._catalog, default=default)
|
||||
try:
|
||||
return value.format(**values)
|
||||
except Exception:
|
||||
return value
|
||||
|
||||
def _build_layout(self) -> None:
|
||||
"""Build the two lists and the explicit keyboard-friendly controls."""
|
||||
|
||||
self.grid_columnconfigure(0, weight=1)
|
||||
self.grid_columnconfigure(2, weight=1)
|
||||
self.grid_rowconfigure(2, weight=1)
|
||||
|
||||
ctk.CTkLabel(
|
||||
self,
|
||||
text=self._t("picking.sequence.document", "Picking List {documento}", documento=self.documento),
|
||||
font=theme_font(self._theme, "title_font", ("Segoe UI", 16, "bold")),
|
||||
).grid(row=0, column=0, columnspan=3, padx=16, pady=(14, 4), sticky="w")
|
||||
|
||||
ctk.CTkLabel(
|
||||
self,
|
||||
text=self._t(
|
||||
"picking.sequence.hint",
|
||||
"Trascina gli scaffali a destra. Quelli non inseriti saranno accodati secondo l'ordine predefinito.",
|
||||
),
|
||||
anchor="w",
|
||||
justify="left",
|
||||
wraplength=720,
|
||||
).grid(row=1, column=0, columnspan=3, padx=16, pady=(0, 10), sticky="ew")
|
||||
|
||||
self.available_panel, self.available_list = self._build_list_panel(
|
||||
0, self._t("picking.sequence.available", "Scaffali disponibili")
|
||||
)
|
||||
controls = ctk.CTkFrame(self, fg_color="transparent")
|
||||
controls.grid(row=2, column=1, padx=10, pady=4)
|
||||
for label, command in (
|
||||
(self._t("picking.sequence.button.add", "Aggiungi >"), self._add_selected),
|
||||
(self._t("picking.sequence.button.remove", "< Rimuovi"), self._remove_selected),
|
||||
(self._t("picking.sequence.button.up", "Su"), lambda: self._move_selected(-1)),
|
||||
(self._t("picking.sequence.button.down", "Giu'"), lambda: self._move_selected(1)),
|
||||
):
|
||||
button = ctk.CTkButton(controls, text=label, width=120, command=command)
|
||||
button.pack(pady=5)
|
||||
tooltip_key = {
|
||||
self._t("picking.sequence.button.add", "Aggiungi >"): "picking.sequence.add",
|
||||
self._t("picking.sequence.button.remove", "< Rimuovi"): "picking.sequence.remove",
|
||||
self._t("picking.sequence.button.up", "Su"): "picking.sequence.up",
|
||||
self._t("picking.sequence.button.down", "Giu'"): "picking.sequence.down",
|
||||
}.get(label, "")
|
||||
self._attach_tooltip(button, tooltip_key)
|
||||
|
||||
self.selected_panel, self.selected_list = self._build_list_panel(
|
||||
2, self._t("picking.sequence.selected", "Ordine personalizzato")
|
||||
)
|
||||
|
||||
ctk.CTkLabel(
|
||||
self,
|
||||
text=self._t(
|
||||
"picking.sequence.default_hint",
|
||||
"Default: prima Non scaff., poi gli scaffali secondo l'ordine WMS.",
|
||||
),
|
||||
anchor="w",
|
||||
text_color=theme_color(self._theme, "secondary_text_color", "#4b5563"),
|
||||
).grid(row=3, column=0, columnspan=3, padx=16, pady=(8, 4), sticky="ew")
|
||||
|
||||
bottom = ctk.CTkFrame(self)
|
||||
bottom.grid(row=4, column=0, columnspan=3, padx=16, pady=(6, 14), sticky="ew")
|
||||
bottom.grid_columnconfigure(0, weight=1)
|
||||
reset_button = ctk.CTkButton(
|
||||
bottom,
|
||||
text=self._t("picking.sequence.button.reset", "Ripristina default"),
|
||||
command=self._reset_default,
|
||||
fg_color=theme_color(self._theme, "reset_button_fg_color", "#6b7280"),
|
||||
)
|
||||
reset_button.grid(row=0, column=1, padx=5, pady=8)
|
||||
self._attach_tooltip(reset_button, "picking.sequence.reset")
|
||||
save_button = ctk.CTkButton(
|
||||
bottom,
|
||||
text=self._t("picking.sequence.button.save", "Salva"),
|
||||
command=self._save,
|
||||
)
|
||||
save_button.grid(row=0, column=2, padx=5, pady=8)
|
||||
self._attach_tooltip(save_button, "picking.sequence.save")
|
||||
close_button = ctk.CTkButton(
|
||||
bottom,
|
||||
text=self._t("picking.sequence.button.close", "Chiudi"),
|
||||
command=self.destroy,
|
||||
)
|
||||
close_button.grid(row=0, column=3, padx=5, pady=8)
|
||||
self._attach_tooltip(close_button, "picking.sequence.close")
|
||||
|
||||
def _attach_tooltip(self, widget: tk.Misc, key: str) -> None:
|
||||
"""Attach a localized tooltip when the catalog contains one."""
|
||||
|
||||
value = tooltip_text(key, catalog=self._tooltip_catalog) if key else ""
|
||||
if value:
|
||||
WidgetToolTip(widget, value)
|
||||
|
||||
def _build_list_panel(self, column: int, title: str):
|
||||
"""Create one titled, scrollable group list."""
|
||||
|
||||
panel = ctk.CTkFrame(self)
|
||||
panel.grid(row=2, column=column, padx=(16 if column == 0 else 0, 16 if column == 2 else 0), pady=4, sticky="nsew")
|
||||
panel.grid_columnconfigure(0, weight=1)
|
||||
panel.grid_rowconfigure(1, weight=1)
|
||||
ctk.CTkLabel(panel, text=title, font=("Segoe UI", 12, "bold")).grid(
|
||||
row=0, column=0, padx=10, pady=(10, 6), sticky="w"
|
||||
)
|
||||
content = ctk.CTkScrollableFrame(panel, fg_color=theme_color(self._theme, "list_fg_color", "#f8fafc"))
|
||||
content.grid(row=1, column=0, padx=8, pady=(0, 8), sticky="nsew")
|
||||
content.grid_columnconfigure(0, weight=1)
|
||||
return panel, content
|
||||
|
||||
def _show_and_load(self) -> None:
|
||||
"""Center the ready window and start its asynchronous load."""
|
||||
|
||||
try:
|
||||
self.update_idletasks()
|
||||
parent = self.master
|
||||
x = max(0, parent.winfo_rootx() + (parent.winfo_width() - self.winfo_width()) // 2)
|
||||
y = max(0, parent.winfo_rooty() + (parent.winfo_height() - self.winfo_height()) // 2)
|
||||
self.geometry(f"+{x}+{y}")
|
||||
except Exception:
|
||||
pass
|
||||
self.deiconify()
|
||||
self.lift()
|
||||
self.focus_force()
|
||||
self._load()
|
||||
|
||||
def _load(self) -> None:
|
||||
"""Load available groups and the optional saved sequence."""
|
||||
|
||||
async def _job():
|
||||
return await self.db_client.query_json(SQL_LOAD_GROUPS, {"documento": self.documento})
|
||||
|
||||
def _ok(result):
|
||||
rows = _rows_to_dicts(result)
|
||||
configured: list[tuple[int, PickupGroup]] = []
|
||||
available: list[PickupGroup] = []
|
||||
for row in rows:
|
||||
group = PickupGroup(
|
||||
key=str(row.get("GruppoPrelievoChiave") or "").strip(),
|
||||
label=str(row.get("GruppoPrelievo") or "").strip(),
|
||||
default_order=int(row.get("OrdineGruppoDefault") or 0),
|
||||
)
|
||||
configured_order = row.get("OrdineGruppoConfigurato")
|
||||
if configured_order is None:
|
||||
available.append(group)
|
||||
else:
|
||||
configured.append((int(configured_order), group))
|
||||
self.available = sorted(available, key=lambda item: (item.default_order, item.label))
|
||||
self.selected = [item for _order, item in sorted(configured, key=lambda pair: pair[0])]
|
||||
self._render_lists()
|
||||
|
||||
def _error(exc):
|
||||
messagebox.showerror(
|
||||
self._t("picking.sequence.title", "Sequenza di prelievo"),
|
||||
self._t("picking.sequence.msg.load_error", "Errore durante il caricamento:\n{error}", error=exc),
|
||||
parent=self,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
self.runner.run(
|
||||
_job(),
|
||||
on_success=_ok,
|
||||
on_error=_error,
|
||||
busy=self.busy,
|
||||
message=self._t("picking.sequence.busy.load", "Carico gli scaffali..."),
|
||||
)
|
||||
|
||||
def _render_lists(self) -> None:
|
||||
"""Redraw list buttons after a move or a database load."""
|
||||
|
||||
for host in (self.available_list, self.selected_list):
|
||||
for child in host.winfo_children():
|
||||
child.destroy()
|
||||
for row, group in enumerate(self.available):
|
||||
self._render_group_button(self.available_list, group, "available", row)
|
||||
for row, group in enumerate(self.selected):
|
||||
self._render_group_button(self.selected_list, group, "selected", row)
|
||||
|
||||
def _render_group_button(self, host, group: PickupGroup, side: str, row: int) -> None:
|
||||
"""Render one selectable and draggable group button."""
|
||||
|
||||
is_selected = self._selected_key == group.key and self._selected_side == side
|
||||
prefix = f"{row + 1}. " if side == "selected" else ""
|
||||
button = ctk.CTkButton(
|
||||
host,
|
||||
text=f"{prefix}{group.label}",
|
||||
anchor="w",
|
||||
height=34,
|
||||
fg_color="#1976d2" if is_selected else theme_color(self._theme, "item_fg_color", "#2ebf74"),
|
||||
command=lambda g=group, s=side: self._select(g, s),
|
||||
)
|
||||
button.grid(row=row, column=0, padx=4, pady=4, sticky="ew")
|
||||
button.bind("<Double-Button-1>", lambda _event, g=group, s=side: self._toggle_group(g, s), add="+")
|
||||
drag_widgets = [button]
|
||||
for attr in ("_canvas", "_text_label", "_image_label"):
|
||||
widget = getattr(button, attr, None)
|
||||
if widget is not None:
|
||||
drag_widgets.append(widget)
|
||||
for widget in drag_widgets:
|
||||
widget.bind("<ButtonPress-1>", lambda _event, g=group, s=side: self._start_drag(g, s), add="+")
|
||||
widget.bind("<ButtonRelease-1>", self._finish_drag, add="+")
|
||||
self._attach_tooltip(button, "picking.sequence.item")
|
||||
|
||||
def _select(self, group: PickupGroup, side: str) -> None:
|
||||
"""Select one group for the explicit move controls."""
|
||||
|
||||
self._selected_key = group.key
|
||||
self._selected_side = side
|
||||
self._render_lists()
|
||||
|
||||
def _toggle_group(self, group: PickupGroup, side: str) -> None:
|
||||
"""Move a double-clicked group to the opposite side."""
|
||||
|
||||
self._selected_key = group.key
|
||||
self._selected_side = side
|
||||
self._add_selected() if side == "available" else self._remove_selected()
|
||||
|
||||
def _selected_group(self) -> PickupGroup | None:
|
||||
"""Return the group selected in the active side."""
|
||||
|
||||
source = self.available if self._selected_side == "available" else self.selected
|
||||
return next((item for item in source if item.key == self._selected_key), None)
|
||||
|
||||
def _add_selected(self) -> None:
|
||||
"""Append the selected available group to the custom sequence."""
|
||||
|
||||
if self._selected_side != "available":
|
||||
return
|
||||
group = self._selected_group()
|
||||
if group is None:
|
||||
return
|
||||
self.available = [item for item in self.available if item.key != group.key]
|
||||
self.selected.append(group)
|
||||
self._selected_side = "selected"
|
||||
self._render_lists()
|
||||
|
||||
def _remove_selected(self) -> None:
|
||||
"""Return the selected configured group to the available list."""
|
||||
|
||||
if self._selected_side != "selected":
|
||||
return
|
||||
group = self._selected_group()
|
||||
if group is None:
|
||||
return
|
||||
self.selected = [item for item in self.selected if item.key != group.key]
|
||||
self.available.append(group)
|
||||
self.available.sort(key=lambda item: (item.default_order, item.label))
|
||||
self._selected_side = "available"
|
||||
self._render_lists()
|
||||
|
||||
def _move_selected(self, offset: int) -> None:
|
||||
"""Move one configured group up or down."""
|
||||
|
||||
if self._selected_side != "selected":
|
||||
return
|
||||
index = next((i for i, item in enumerate(self.selected) if item.key == self._selected_key), -1)
|
||||
target = index + int(offset)
|
||||
if index < 0 or target < 0 or target >= len(self.selected):
|
||||
return
|
||||
self.selected[index], self.selected[target] = self.selected[target], self.selected[index]
|
||||
self._render_lists()
|
||||
|
||||
def _start_drag(self, group: PickupGroup, side: str) -> None:
|
||||
"""Remember the item being dragged."""
|
||||
|
||||
self._drag_group = group
|
||||
self._drag_side = side
|
||||
|
||||
@staticmethod
|
||||
def _is_descendant(widget: tk.Misc | None, ancestor: tk.Misc) -> bool:
|
||||
"""Return whether a widget belongs to one list panel."""
|
||||
|
||||
current = widget
|
||||
while current is not None:
|
||||
if current == ancestor:
|
||||
return True
|
||||
current = getattr(current, "master", None)
|
||||
return False
|
||||
|
||||
def _finish_drag(self, event) -> None:
|
||||
"""Drop the dragged group into a list and place it near the pointer."""
|
||||
|
||||
group = self._drag_group
|
||||
if group is None:
|
||||
return
|
||||
self._drag_group = None
|
||||
try:
|
||||
target_widget = self.winfo_containing(event.x_root, event.y_root)
|
||||
except Exception:
|
||||
return
|
||||
if self._is_descendant(target_widget, self.selected_panel):
|
||||
self.available = [item for item in self.available if item.key != group.key]
|
||||
self.selected = [item for item in self.selected if item.key != group.key]
|
||||
target_y = event.y_root - self.selected_list.winfo_rooty()
|
||||
row_height = 42
|
||||
target_index = max(0, min(len(self.selected), target_y // row_height))
|
||||
self.selected.insert(target_index, group)
|
||||
self._selected_side = "selected"
|
||||
elif self._is_descendant(target_widget, self.available_panel):
|
||||
self.selected = [item for item in self.selected if item.key != group.key]
|
||||
if not any(item.key == group.key for item in self.available):
|
||||
self.available.append(group)
|
||||
self.available.sort(key=lambda item: (item.default_order, item.label))
|
||||
self._selected_side = "available"
|
||||
else:
|
||||
return
|
||||
self._selected_key = group.key
|
||||
self._render_lists()
|
||||
|
||||
def _save_sql(self) -> tuple[str, dict[str, Any]]:
|
||||
"""Build one atomic soft-delete/insert batch using bound parameters."""
|
||||
|
||||
params: dict[str, Any] = {
|
||||
"documento": self.documento,
|
||||
"utente": self.session.login if self.session else "SYSTEM",
|
||||
}
|
||||
values: list[str] = []
|
||||
for index, group in enumerate(self.selected):
|
||||
params[f"key_{index}"] = group.key
|
||||
params[f"label_{index}"] = group.label
|
||||
params[f"order_{index}"] = index
|
||||
values.append(
|
||||
f"(:documento, :key_{index}, :label_{index}, :order_{index}, :utente, SYSDATETIME(), :utente, SYSDATETIME())"
|
||||
)
|
||||
insert = ""
|
||||
if values:
|
||||
insert = """
|
||||
INSERT INTO dbo.py_PickingListPrelievoSequenza (
|
||||
Documento, GruppoChiave, GruppoEtichetta, Ordine,
|
||||
InsUtente, InsDataOra, ModUtente, ModDataOra
|
||||
)
|
||||
VALUES
|
||||
""" + ",\n".join(values) + ";"
|
||||
sql = f"""
|
||||
SET NOCOUNT ON;
|
||||
SET XACT_ABORT ON;
|
||||
UPDATE dbo.py_PickingListPrelievoSequenza
|
||||
SET DelUtente = :utente,
|
||||
DelDataOra = SYSDATETIME(),
|
||||
ModUtente = :utente,
|
||||
ModDataOra = SYSDATETIME()
|
||||
WHERE Documento = :documento
|
||||
AND DelDataOra IS NULL;
|
||||
{insert}
|
||||
SELECT CAST({len(values)} AS int) AS ElementiSalvati;
|
||||
"""
|
||||
return sql, params
|
||||
|
||||
def _save(self) -> None:
|
||||
"""Persist the configured prefix atomically."""
|
||||
|
||||
sql, params = self._save_sql()
|
||||
|
||||
async def _job():
|
||||
return await self.db_client.query_json(sql, params, commit=True)
|
||||
|
||||
self.runner.run(
|
||||
_job(),
|
||||
on_success=lambda _result: self._save_completed("saved"),
|
||||
on_error=self._save_error,
|
||||
busy=self.busy,
|
||||
message=self._t("picking.sequence.busy.save", "Salvo la sequenza..."),
|
||||
)
|
||||
|
||||
def _reset_default(self) -> None:
|
||||
"""Delete the custom sequence so the shared default becomes active."""
|
||||
|
||||
async def _job():
|
||||
return await self.db_client.query_json(
|
||||
SQL_RESET_SEQUENCE,
|
||||
{
|
||||
"documento": self.documento,
|
||||
"utente": self.session.login if self.session else "SYSTEM",
|
||||
},
|
||||
commit=True,
|
||||
)
|
||||
|
||||
self.runner.run(
|
||||
_job(),
|
||||
on_success=lambda _result: self._save_completed("reset"),
|
||||
on_error=self._save_error,
|
||||
busy=self.busy,
|
||||
message=self._t("picking.sequence.busy.save", "Salvo la sequenza..."),
|
||||
)
|
||||
|
||||
def _save_completed(self, mode: str) -> None:
|
||||
"""Refresh the editor and notify the parent after a successful save."""
|
||||
|
||||
message_key = "picking.sequence.msg.reset" if mode == "reset" else "picking.sequence.msg.saved"
|
||||
default = (
|
||||
"Sequenza personalizzata rimossa. E' attivo l'ordine predefinito."
|
||||
if mode == "reset"
|
||||
else "Sequenza salvata."
|
||||
)
|
||||
messagebox.showinfo(self._t("picking.sequence.title", "Sequenza di prelievo"), self._t(message_key, default), parent=self)
|
||||
if self.on_saved:
|
||||
self.on_saved()
|
||||
self._selected_key = None
|
||||
self._selected_side = None
|
||||
self._load()
|
||||
|
||||
def _save_error(self, exc: BaseException) -> None:
|
||||
"""Show a localized save error."""
|
||||
|
||||
messagebox.showerror(
|
||||
self._t("picking.sequence.title", "Sequenza di prelievo"),
|
||||
self._t("picking.sequence.msg.save_error", "Errore durante il salvataggio:\n{error}", error=exc),
|
||||
parent=self,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
|
||||
def open_pickinglist_sequence_window(
|
||||
parent: tk.Misc,
|
||||
db_client,
|
||||
*,
|
||||
documento: str,
|
||||
session: UserSession | None,
|
||||
on_saved: Callable[[], None] | None = None,
|
||||
) -> PickingListSequenceWindow:
|
||||
"""Open at most one sequence editor for the picking-list window."""
|
||||
|
||||
key = "_pickinglist_sequence_window_singleton"
|
||||
existing = getattr(parent, key, None)
|
||||
if existing is not None:
|
||||
try:
|
||||
if existing.winfo_exists() and existing.documento == str(documento).strip():
|
||||
existing.on_saved = on_saved
|
||||
existing.deiconify()
|
||||
existing.lift()
|
||||
existing.focus_force()
|
||||
return existing
|
||||
if existing.winfo_exists():
|
||||
existing.destroy()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
window = PickingListSequenceWindow(
|
||||
parent,
|
||||
db_client,
|
||||
documento=documento,
|
||||
session=session,
|
||||
on_saved=on_saved,
|
||||
)
|
||||
setattr(parent, key, window)
|
||||
|
||||
def _clear_reference() -> None:
|
||||
try:
|
||||
if getattr(parent, key, None) is window:
|
||||
setattr(parent, key, None)
|
||||
finally:
|
||||
window.destroy()
|
||||
|
||||
window.protocol("WM_DELETE_WINDOW", _clear_reference)
|
||||
return window
|
||||
@@ -10,6 +10,10 @@ from functools import wraps
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
try:
|
||||
from loguru import logger
|
||||
except Exception: # pragma: no cover - safety fallback if dependency is missing locally
|
||||
@@ -258,6 +262,8 @@ async def sp_xExePackingListPallet_async(db, IDOperatore: int, Documento: str, A
|
||||
"""Execute the Python-specific picking-list reservation stored procedure."""
|
||||
try:
|
||||
azione = str(Azione or "P").strip().upper()
|
||||
# The toolbar uses two explicit commands rather than a toggle:
|
||||
# P = reserve the selected document, S = release it if it is active.
|
||||
if azione not in ("P", "S"):
|
||||
return SPResult(rc=-10, message=f"Azione non valida: {Azione}", id_result=None)
|
||||
_MODULE_LOGGER.log(
|
||||
@@ -279,6 +285,8 @@ async def sp_xExePackingListPallet_async(db, IDOperatore: int, Documento: str, A
|
||||
_log_sql("py_sp_xExePackingListPallet", sql, {"IDOperatore": IDOperatore, "Documento": Documento, "Azione": azione})
|
||||
if not hasattr(db, "query_json"):
|
||||
raise RuntimeError("Il client DB non espone query_json necessario per eseguire la stored procedure.")
|
||||
# commit=True is required because the stored procedure updates
|
||||
# PyPickingListReservation and Celle.IDStato.
|
||||
res = await db.query_json(
|
||||
sql,
|
||||
{"IDOperatore": IDOperatore, "Documento": Documento, "Azione": azione},
|
||||
@@ -295,6 +303,23 @@ async def sp_xExePackingListPallet_async(db, IDOperatore: int, Documento: str, A
|
||||
rc = int(rows[0].get("RC") or 0)
|
||||
except Exception:
|
||||
rc = 0
|
||||
if rc == 0 and azione == "P":
|
||||
resolve_sql = """
|
||||
UPDATE dbo.py_BarcodePickingListSkip
|
||||
SET Risolto = 1
|
||||
WHERE Documento COLLATE Latin1_General_CI_AS =
|
||||
CAST(:Documento AS varchar(50)) COLLATE Latin1_General_CI_AS
|
||||
AND Risolto = 0;
|
||||
"""
|
||||
_log_sql("resolve_skipped_pallets_on_prenota", resolve_sql, {"Documento": Documento})
|
||||
if hasattr(db, "exec"):
|
||||
await db.exec(resolve_sql, {"Documento": Documento}, commit=True)
|
||||
else:
|
||||
await db.query_json(
|
||||
resolve_sql + "\nSELECT 0 AS RC;",
|
||||
{"Documento": Documento},
|
||||
commit=True,
|
||||
)
|
||||
_MODULE_LOGGER.log(_MODULE_LOG_LEVEL, f"Stored procedure completata documento={Documento} azione={azione} rc={rc}")
|
||||
return SPResult(rc=rc, message="", id_result=None)
|
||||
except Exception as exc:
|
||||
|
||||
@@ -3,6 +3,7 @@ customtkinter==5.2.2
|
||||
loguru
|
||||
openpyxl==3.1.5
|
||||
orjson
|
||||
Pillow
|
||||
pyodbc==5.3.0
|
||||
SQLAlchemy==2.0.49
|
||||
tksheet==7.6.0
|
||||
|
||||
107
reset_corsie.py
107
reset_corsie.py
@@ -13,19 +13,24 @@ import sys
|
||||
import tkinter as tk
|
||||
from functools import wraps
|
||||
from pathlib import Path
|
||||
from tkinter import messagebox, simpledialog, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import simpledialog, ttk
|
||||
from typing import Any
|
||||
|
||||
import customtkinter as ctk
|
||||
|
||||
from busy_overlay import InlineBusyOverlay
|
||||
from gestione_aree import AsyncRunner
|
||||
from gestione_scarico import move_pallet_async
|
||||
from reset_corsie_service import reset_pallet_async
|
||||
from locale_text import load_locale_catalog, text as loc_text
|
||||
from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text
|
||||
from ui_theme import theme_color, theme_font, theme_padding, theme_section, theme_value
|
||||
from ui_theme import theme_color, theme_font, theme_section, theme_value
|
||||
from ui_tables import style_treeview, zebra_tag
|
||||
from version_info import module_version, versioned_title
|
||||
from window_placement import place_window_fullsize_below_parent_later
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
try:
|
||||
from loguru import logger
|
||||
except Exception: # pragma: no cover - fallback used only when Loguru is not available
|
||||
@@ -167,7 +172,7 @@ SQL_CORSIE = """
|
||||
WITH C AS (
|
||||
SELECT DISTINCT LTRIM(RTRIM(Corsia)) AS Corsia
|
||||
FROM dbo.Celle
|
||||
WHERE ID <> 9999 AND (DelDataOra IS NULL) AND LTRIM(RTRIM(Corsia)) <> '7G'
|
||||
WHERE ID NOT IN (1000, 9999) AND (DelDataOra IS NULL) AND LTRIM(RTRIM(Corsia)) <> '7G'
|
||||
)
|
||||
SELECT Corsia
|
||||
FROM C
|
||||
@@ -189,7 +194,7 @@ WITH C AS (
|
||||
LTRIM(RTRIM(Colonna)) AS Colonna,
|
||||
LTRIM(RTRIM(Fila)) AS Fila
|
||||
FROM dbo.Celle
|
||||
WHERE ID <> 9999 AND (DelDataOra IS NULL)
|
||||
WHERE ID NOT IN (1000, 9999) AND (DelDataOra IS NULL)
|
||||
AND LTRIM(RTRIM(Corsia)) = :corsia
|
||||
),
|
||||
S AS (
|
||||
@@ -211,7 +216,7 @@ WITH C AS (
|
||||
LTRIM(RTRIM(Colonna)) AS Colonna,
|
||||
LTRIM(RTRIM(Fila)) AS Fila
|
||||
FROM dbo.Celle
|
||||
WHERE ID <> 9999 AND (DelDataOra IS NULL)
|
||||
WHERE ID NOT IN (1000, 9999) AND (DelDataOra IS NULL)
|
||||
AND LTRIM(RTRIM(Corsia)) = :corsia
|
||||
),
|
||||
S AS (
|
||||
@@ -233,7 +238,7 @@ SELECT
|
||||
COUNT(DISTINCT g.IDCella) AS TotCelle
|
||||
FROM dbo.XMag_GiacenzaPallet g
|
||||
JOIN dbo.Celle c ON c.ID = g.IDCella
|
||||
WHERE c.ID <> 9999
|
||||
WHERE c.ID NOT IN (1000, 9999)
|
||||
AND LTRIM(RTRIM(c.Corsia)) = :corsia;
|
||||
"""
|
||||
|
||||
@@ -249,7 +254,7 @@ WITH U AS (
|
||||
LTRIM(RTRIM(c.Fila)) AS SortFilaTxt
|
||||
FROM dbo.XMag_GiacenzaPallet g
|
||||
JOIN dbo.Celle c ON c.ID = g.IDCella
|
||||
WHERE c.ID <> 9999
|
||||
WHERE c.ID NOT IN (1000, 9999)
|
||||
AND LTRIM(RTRIM(c.Corsia)) = :corsia
|
||||
)
|
||||
SELECT
|
||||
@@ -275,7 +280,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
super().__init__(parent)
|
||||
self._theme = theme_section("reset_corsie", {})
|
||||
self._locale_catalog = load_locale_catalog()
|
||||
self.title(loc_text("reset.title", catalog=self._locale_catalog, default="Gestione Corsie - svuotamento celle per corsia"))
|
||||
self.title(versioned_title(loc_text("reset.title", catalog=self._locale_catalog, default="Gestione Corsie - svuotamento celle per corsia"), __name__))
|
||||
self.geometry(str(theme_value(self._theme, "window_geometry", "1000x680")))
|
||||
minsize = theme_value(self._theme, "window_minsize", [880, 560])
|
||||
self.minsize(int(minsize[0]), int(minsize[1]))
|
||||
@@ -298,35 +303,6 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
def _setup_tree_style(self):
|
||||
"""Apply a denser, spreadsheet-like style to the main result grid."""
|
||||
|
||||
style = ttk.Style(self)
|
||||
style.configure(
|
||||
"ResetCorsie.Treeview.Heading",
|
||||
font=theme_font(self._theme, "tree_heading_font", ("Segoe UI", 10, "bold")),
|
||||
background=theme_value(self._theme, "tree_heading_bg", "#b8c7db"),
|
||||
foreground=theme_value(self._theme, "tree_heading_fg", "#10243e"),
|
||||
relief="flat",
|
||||
padding=theme_padding(self._theme, "tree_heading_padding", (8, 6)),
|
||||
)
|
||||
style.map(
|
||||
"ResetCorsie.Treeview.Heading",
|
||||
background=[("active", theme_value(self._theme, "tree_heading_bg_active", "#aebfd6"))],
|
||||
relief=[("pressed", "groove"), ("!pressed", "flat")],
|
||||
)
|
||||
style.configure(
|
||||
"ResetCorsie.Treeview",
|
||||
font=theme_font(self._theme, "tree_body_font", ("Segoe UI", 10)),
|
||||
rowheight=int(theme_value(self._theme, "tree_row_height", 30)),
|
||||
background=theme_value(self._theme, "tree_body_bg", "#ffffff"),
|
||||
fieldbackground=theme_value(self._theme, "tree_body_bg", "#ffffff"),
|
||||
foreground=theme_value(self._theme, "tree_body_fg", "#1f1f1f"),
|
||||
borderwidth=0,
|
||||
)
|
||||
style.map(
|
||||
"ResetCorsie.Treeview",
|
||||
background=[("selected", theme_value(self._theme, "tree_selected_bg", "#cfe4ff"))],
|
||||
foreground=[("selected", theme_value(self._theme, "tree_selected_fg", "#10243e"))],
|
||||
)
|
||||
|
||||
@_log_call()
|
||||
def _build_ui(self):
|
||||
"""Create selectors, summary widgets and the occupied-cell grid."""
|
||||
@@ -411,8 +387,13 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
width=int(theme_value(self._theme, "tree_col_num_udc_width", 160)),
|
||||
anchor=str(theme_value(self._theme, "tree_col_num_udc_anchor", "center")),
|
||||
)
|
||||
self.tree.tag_configure("odd", background=theme_value(self._theme, "tree_row_odd_bg", "#ffffff"))
|
||||
self.tree.tag_configure("even", background=theme_value(self._theme, "tree_row_even_bg", "#f3f6fb"))
|
||||
style_treeview(
|
||||
self.tree,
|
||||
style_name="ResetCorsie.Treeview",
|
||||
rowheight=int(theme_value(self._theme, "tree_row_height", 30)),
|
||||
font=theme_font(self._theme, "tree_body_font", ("Segoe UI", 10)),
|
||||
heading_font=theme_font(self._theme, "tree_heading_font", ("Segoe UI", 10, "bold")),
|
||||
)
|
||||
|
||||
sy = ttk.Scrollbar(mid, orient="vertical", command=self.tree.yview)
|
||||
sx = ttk.Scrollbar(mid, orient="horizontal", command=self.tree.xview)
|
||||
@@ -486,7 +467,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
|
||||
def _err(ex):
|
||||
_MODULE_LOGGER.exception(f"Errore caricamento corsie reset corsie: {ex}")
|
||||
messagebox.showerror("Errore", f"Caricamento corsie fallito:\n{ex}", parent=self)
|
||||
messagebox.showerror("Errore", f"Caricamento corsie fallito:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
self._async.run(self.db.query_json(SQL_CORSIE, {}), _ok, _err, busy=self._busy, message="Carico corsie...")
|
||||
|
||||
@@ -529,15 +510,15 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
for item in self.tree.get_children():
|
||||
self.tree.delete(item)
|
||||
for idx, (_idc, ubi, n) in enumerate(det_rows):
|
||||
tag = "even" if idx % 2 else "odd"
|
||||
tag = zebra_tag(idx)
|
||||
self.tree.insert("", "end", values=(ubi, n), tags=(tag,))
|
||||
except Exception as ex:
|
||||
_MODULE_LOGGER.exception(f"Errore UI refresh reset corsie corsia={corsia}: {ex}")
|
||||
messagebox.showerror("Errore", f"Aggiornamento interfaccia fallito:\n{ex}", parent=self)
|
||||
messagebox.showerror("Errore", f"Aggiornamento interfaccia fallito:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
def _err(ex):
|
||||
_MODULE_LOGGER.exception(f"Errore refresh reset corsie corsia={corsia}: {ex}")
|
||||
messagebox.showerror("Errore", f"Refresh fallito:\n{ex}", parent=self)
|
||||
messagebox.showerror("Errore", f"Refresh fallito:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
self._async.run(_q(), _ok, _err, busy=self._busy, message=f"Riepilogo {corsia}...")
|
||||
|
||||
@@ -557,12 +538,9 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
if tot_udc <= 0:
|
||||
messagebox.showinfo("Svuota corsia", f"Nessuna UDC attiva da scaricare per la corsia {corsia}.", parent=self)
|
||||
return
|
||||
msg = (
|
||||
f"Verranno scaricate logicamente {tot_udc} UDC attive distribuite su {tot_celle} celle della corsia {corsia}.",
|
||||
"L'operazione verra' eseguita come scarico verso 9000000 / 9999, senza cancellazioni fisiche dirette.",
|
||||
"Digitare il nome della corsia per confermare:",
|
||||
)
|
||||
confirm = simpledialog.askstring("Conferma", "\n".join(msg), parent=self)
|
||||
msg = loc_text("reset.confirm", catalog=self._locale_catalog).format(
|
||||
udc=tot_udc, cells=tot_celle, aisle=corsia)
|
||||
confirm = simpledialog.askstring("Conferma", msg, parent=self)
|
||||
if confirm is None:
|
||||
_MODULE_LOGGER.info(f"Reset corsia {corsia}: conferma annullata dall'utente")
|
||||
return
|
||||
@@ -574,7 +552,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
|
||||
def _err_count(ex):
|
||||
_MODULE_LOGGER.exception(f"Errore conteggio reset corsie corsia={corsia}: {ex}")
|
||||
messagebox.showerror("Errore", f"Conteggio UDC da scaricare fallito:\n{ex}", parent=self)
|
||||
messagebox.showerror("Errore", f"Conteggio UDC da scaricare fallito:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
self._async.run(self.db.query_json(SQL_COUNT_RESET, {"corsia": corsia}), _ok_count, _err_count, busy=self._busy, message="Verifico...")
|
||||
|
||||
@@ -589,20 +567,30 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
_log_dataset("reset_corsie_udc_reset", rows)
|
||||
|
||||
success = 0
|
||||
shipped = 0
|
||||
non_shelved = 0
|
||||
failed: list[dict[str, Any]] = []
|
||||
utente = str(getattr(self.session, "login", "") or "warehouse_ui").strip()
|
||||
|
||||
for barcode_pallet, idcella, ubicazione in rows:
|
||||
try:
|
||||
await move_pallet_async(
|
||||
target = await reset_pallet_async(
|
||||
self.db,
|
||||
barcode_pallet=str(barcode_pallet or "").strip(),
|
||||
target_idcella=9999,
|
||||
target_barcode_cella="9000000",
|
||||
source_idcella=int(idcella),
|
||||
utente=utente,
|
||||
)
|
||||
success += 1
|
||||
shipped += int(target == 9999)
|
||||
non_shelved += int(target == 1000)
|
||||
_MODULE_LOGGER.info(
|
||||
f"RESET MOVE corsia={corsia} pallet={barcode_pallet} "
|
||||
f"source={idcella} target={target} utente={utente}"
|
||||
)
|
||||
except Exception as ex:
|
||||
_MODULE_LOGGER.exception(
|
||||
f"RESET FAILED corsia={corsia} pallet={barcode_pallet} source={idcella}: {ex}"
|
||||
)
|
||||
failed.append(
|
||||
{
|
||||
"barcode_pallet": str(barcode_pallet or ""),
|
||||
@@ -615,6 +603,8 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
return {
|
||||
"total": len(rows),
|
||||
"success": success,
|
||||
"shipped": shipped,
|
||||
"non_shelved": non_shelved,
|
||||
"failed": failed,
|
||||
}
|
||||
|
||||
@@ -622,6 +612,9 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
total = int((result or {}).get("total", 0))
|
||||
success = int((result or {}).get("success", 0))
|
||||
failed = list((result or {}).get("failed", []))
|
||||
summary = loc_text("reset.result", catalog=self._locale_catalog).format(
|
||||
aisle=corsia, success=success, total=total,
|
||||
shipped=result.get("shipped", 0), non_shelved=result.get("non_shelved", 0))
|
||||
_MODULE_LOGGER.info(
|
||||
f"Reset corsia {corsia}: scarico logico completato success={success} total={total} failed={len(failed)}"
|
||||
)
|
||||
@@ -629,7 +622,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
messagebox.showwarning(
|
||||
"Completato con errori",
|
||||
(
|
||||
f"Corsia {corsia}: scaricate {success} UDC su {total}.\n"
|
||||
summary + "\n" +
|
||||
f"Errori su {len(failed)} UDC. Controllare {MODULE_LOG_PATH.name}."
|
||||
),
|
||||
parent=self,
|
||||
@@ -637,14 +630,14 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
else:
|
||||
messagebox.showinfo(
|
||||
"Completato",
|
||||
f"Corsia {corsia}: svuotamento logico completato su {success} UDC.",
|
||||
summary,
|
||||
parent=self,
|
||||
)
|
||||
self.refresh()
|
||||
|
||||
def _err_del(ex):
|
||||
_MODULE_LOGGER.exception(f"Errore reset logico corsie corsia={corsia}: {ex}")
|
||||
messagebox.showerror("Errore", f"Svuotamento fallito:\n{ex}", parent=self)
|
||||
messagebox.showerror("Errore", f"Svuotamento fallito:\n{ex}", parent=self, exception=ex)
|
||||
|
||||
self._async.run(_q(), _ok_del, _err_del, busy=self._busy, message=f"Svuoto {corsia}...")
|
||||
|
||||
|
||||
121
reset_corsie_service.py
Normal file
121
reset_corsie_service.py
Normal file
@@ -0,0 +1,121 @@
|
||||
"""Classify and move aisle-reset UDCs without changing barcode workflows.
|
||||
|
||||
Each call is one transaction: recheck the source, read the ERP document state,
|
||||
record P/V movements, refresh reservations and verify the resulting location.
|
||||
The caller must use query_json(commit=True), never execute this batch piecemeal.
|
||||
"""
|
||||
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
SQL_RESET_PALLET = """
|
||||
SET NOCOUNT ON;
|
||||
SET XACT_ABORT ON;
|
||||
DECLARE @Pallet varchar(32) = :barcode_pallet;
|
||||
DECLARE @ExpectedCell int = :source_idcella;
|
||||
DECLARE @User varchar(128) = :utente;
|
||||
DECLARE @Now datetime = GETDATE();
|
||||
DECLARE @LockedRows int;
|
||||
DECLARE @TargetCell int = 1000;
|
||||
DECLARE @SourceID int;
|
||||
|
||||
-- Keep other ledger writers away until this UDC transaction completes.
|
||||
SELECT @LockedRows = COUNT(*)
|
||||
FROM dbo.MagazziniPallet WITH (UPDLOCK, HOLDLOCK)
|
||||
WHERE Attributo = @Pallet;
|
||||
|
||||
IF @ExpectedCell IN (1000, 9999)
|
||||
THROW 51001, 'Reset: la sorgente deve essere una cella fisica.', 1;
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM dbo.XMag_GiacenzaPallet
|
||||
WHERE BarcodePallet = @Pallet AND IDCella = @ExpectedCell
|
||||
) OR EXISTS (
|
||||
SELECT 1 FROM dbo.XMag_GiacenzaPallet
|
||||
WHERE BarcodePallet = @Pallet AND (IDCella <> @ExpectedCell OR IDCella IS NULL)
|
||||
)
|
||||
THROW 51002, 'Reset: UDC spostata o presente in piu celle. Ricaricare e verificare.', 1;
|
||||
|
||||
-- Read the ERP association directly: history UI date filters must not decide
|
||||
-- whether an old, already shipped UDC is put back into available stock.
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM SAMA1.dbo.LOTSER AS ls
|
||||
JOIN SAMA1.dbo.LOTTIBF AS lb ON lb.IDLOTSER = ls.ID
|
||||
JOIN SAMA1.dbo.FATRIG AS fr ON fr.ID = lb.IDFATRIG
|
||||
JOIN SAMA1.dbo.BAMTES AS bt ON bt.ID = fr.IDBAM
|
||||
WHERE bt.STATO = 'D'
|
||||
AND LEFT(ls.NUMSER, 6) COLLATE Latin1_General_CI_AS =
|
||||
@Pallet COLLATE Latin1_General_CI_AS
|
||||
)
|
||||
SET @TargetCell = 9999;
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM dbo.Celle c JOIN dbo.Aree a ON a.ID = c.IDArea
|
||||
WHERE c.ID = @TargetCell AND c.DelDataOra IS NULL
|
||||
)
|
||||
THROW 51003, 'Reset: cella virtuale di destinazione non disponibile.', 1;
|
||||
|
||||
SELECT TOP (1) @SourceID = ID
|
||||
FROM dbo.MagazziniPallet
|
||||
WHERE Attributo = @Pallet AND IDCella = @ExpectedCell
|
||||
AND Tipo = 'V' AND PesoUnitario > 0
|
||||
ORDER BY ID DESC;
|
||||
IF @SourceID IS NULL
|
||||
THROW 51004, 'Reset: movimento sorgente non trovato.', 1;
|
||||
|
||||
UPDATE dbo.MagazziniPallet
|
||||
SET ModUtente = @User, ModDataOra = @Now
|
||||
WHERE ID = @SourceID;
|
||||
|
||||
INSERT INTO dbo.MagazziniPallet (
|
||||
Tipo, IDRiferimento, NumeroPallet, Attributo, IDMagazzino, IDArea,
|
||||
IDCella, DataMagazzino, PesoUnitario, Tara, InsUtente, InsDataOra
|
||||
)
|
||||
SELECT 'P', src.ID, ISNULL(src.NumeroPallet, 0), src.Attributo,
|
||||
src.IDMagazzino, src.IDArea, src.IDCella, @Now,
|
||||
src.PesoUnitario, ISNULL(src.Tara, 0), @User, @Now
|
||||
FROM dbo.MagazziniPallet src WHERE src.ID = @SourceID;
|
||||
|
||||
UPDATE dbo.Celle SET IDStato = 0, ModUtente = @User, ModDataOra = @Now
|
||||
WHERE ID = @ExpectedCell;
|
||||
|
||||
INSERT INTO dbo.MagazziniPallet (
|
||||
Tipo, IDRiferimento, NumeroPallet, Attributo, IDMagazzino, IDArea,
|
||||
IDCella, DataMagazzino, PesoUnitario, Tara, InsUtente, InsDataOra
|
||||
)
|
||||
SELECT 'V', src.ID, ISNULL(src.NumeroPallet, 0), src.Attributo,
|
||||
a.IDMagazzino, c.IDArea, c.ID, @Now,
|
||||
src.PesoUnitario, ISNULL(src.Tara, 0), @User, @Now
|
||||
FROM dbo.MagazziniPallet src
|
||||
JOIN dbo.Celle c ON c.ID = @TargetCell
|
||||
JOIN dbo.Aree a ON a.ID = c.IDArea
|
||||
WHERE src.ID = @SourceID;
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM dbo.XMag_GiacenzaPallet
|
||||
WHERE BarcodePallet = @Pallet AND IDCella = @TargetCell
|
||||
) OR EXISTS (
|
||||
SELECT 1 FROM dbo.XMag_GiacenzaPallet
|
||||
WHERE BarcodePallet = @Pallet AND (IDCella <> @TargetCell OR IDCella IS NULL)
|
||||
)
|
||||
THROW 51005, 'Reset: ubicazione finale incoerente. Movimento annullato.', 1;
|
||||
|
||||
EXEC dbo.py_sp_ControllaPrenotazionePackingListPalletNew;
|
||||
SELECT @TargetCell AS TargetIDCella;
|
||||
"""
|
||||
|
||||
|
||||
async def reset_pallet_async(db_client, *, barcode_pallet: str,
|
||||
source_idcella: int, utente: str) -> int:
|
||||
"""Move one UDC, returning 9999 (definitive document) or 1000 (otherwise).
|
||||
|
||||
source_idcella is the location shown in the reset selection, not a new
|
||||
destination. Any SQL failure rolls back this UDC through the DB client.
|
||||
"""
|
||||
result = await db_client.query_json(SQL_RESET_PALLET, {
|
||||
"barcode_pallet": str(barcode_pallet or "").strip(),
|
||||
"source_idcella": int(source_idcella),
|
||||
"utente": str(utente or "warehouse_ui").strip(),
|
||||
}, commit=True)
|
||||
return int(result["rows"][0][0])
|
||||
9
rollback_barcode_picking_skip_patch.sql
Normal file
9
rollback_barcode_picking_skip_patch.sql
Normal file
@@ -0,0 +1,9 @@
|
||||
SET XACT_ABORT ON;
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
IF OBJECT_ID(N'dbo.py_BarcodePickingListSkip', N'U') IS NOT NULL
|
||||
BEGIN
|
||||
DROP TABLE dbo.py_BarcodePickingListSkip;
|
||||
END;
|
||||
|
||||
COMMIT TRANSACTION;
|
||||
76
rollback_pickinglist_days_filter_patch.sql
Normal file
76
rollback_pickinglist_days_filter_patch.sql
Normal file
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
Rollback: intervallo giorni selezionabile in Gestione Picking List Python
|
||||
|
||||
Effetto:
|
||||
- ripristina le viste Python precedenti, appoggiate a dbo.XMag_ViewPackingList;
|
||||
- il filtro effettivo torna quindi a quello legacy fisso a 10 giorni.
|
||||
*/
|
||||
|
||||
SET ANSI_NULLS ON;
|
||||
GO
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER VIEW [dbo].[py_XMag_ViewPackingList]
|
||||
AS
|
||||
SELECT TOP 10000
|
||||
legacy.Pallet,
|
||||
legacy.Lotto,
|
||||
legacy.Articolo,
|
||||
legacy.Descrizione,
|
||||
legacy.Qta,
|
||||
legacy.Documento,
|
||||
legacy.CodNazione,
|
||||
legacy.NAZIONE,
|
||||
legacy.Stato,
|
||||
legacy.PalletCella,
|
||||
legacy.Magazzino,
|
||||
legacy.Area,
|
||||
legacy.Cella,
|
||||
legacy.Ordinamento,
|
||||
legacy.Ubicazione,
|
||||
legacy.DEST,
|
||||
CASE
|
||||
WHEN pr.Documento IS NOT NULL
|
||||
AND pr.Documento = CAST(legacy.Documento AS varchar(8))
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END AS IDStato
|
||||
FROM dbo.XMag_ViewPackingList AS legacy
|
||||
LEFT JOIN dbo.PyPickingListReservation AS pr
|
||||
ON pr.ID = 1
|
||||
AND NULLIF(LTRIM(RTRIM(pr.Documento)), '') IS NOT NULL
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN pr.Documento IS NOT NULL
|
||||
AND pr.Documento = CAST(legacy.Documento AS varchar(8))
|
||||
THEN 1
|
||||
ELSE 0
|
||||
END DESC,
|
||||
legacy.Documento,
|
||||
legacy.Ordinamento;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER VIEW [dbo].[py_ViewPackingListRestante]
|
||||
AS
|
||||
SELECT
|
||||
Pallet,
|
||||
Lotto,
|
||||
Articolo,
|
||||
Descrizione,
|
||||
Qta,
|
||||
Documento,
|
||||
CodNazione,
|
||||
NAZIONE,
|
||||
Stato,
|
||||
PalletCella,
|
||||
Magazzino,
|
||||
Area,
|
||||
Cella,
|
||||
Ordinamento,
|
||||
Ubicazione,
|
||||
DEST,
|
||||
IDStato
|
||||
FROM dbo.py_XMag_ViewPackingList
|
||||
WHERE Cella <> 9999;
|
||||
GO
|
||||
19
rollback_pickinglist_sequence_patch.sql
Normal file
19
rollback_pickinglist_sequence_patch.sql
Normal file
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
Rollback della sequenza personalizzata per picking list.
|
||||
|
||||
Attenzione:
|
||||
- elimina le configurazioni di sequenza salvate nel ramo Python;
|
||||
- non modifica gli oggetti legacy C#;
|
||||
- dopo il rollback occorre usare una versione Python precedente alla feature.
|
||||
*/
|
||||
|
||||
IF OBJECT_ID(N'dbo.py_ViewPackingListPrelievo', N'V') IS NOT NULL
|
||||
DROP VIEW dbo.py_ViewPackingListPrelievo;
|
||||
GO
|
||||
|
||||
IF OBJECT_ID(N'dbo.py_PickingListPrelievoSequenza', N'U') IS NOT NULL
|
||||
DROP TABLE dbo.py_PickingListPrelievoSequenza;
|
||||
GO
|
||||
|
||||
PRINT 'Rollback sequenza prelievo Python completato.';
|
||||
GO
|
||||
@@ -3,28 +3,47 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import threading
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
from typing import Callable, TypeVar
|
||||
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
FATAL_LOG = BASE_DIR / "warehouse_fatal.log"
|
||||
TEMP_DIR = Path(tempfile.gettempdir())
|
||||
_STDIO_HANDLES = []
|
||||
_EXCEPTION_LOGGING_CONFIGURED: set[str] = set()
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
def _open_log_file(path: Path):
|
||||
"""Open a log path, falling back to the user temp directory when needed."""
|
||||
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
return path.open("a", encoding="utf-8", buffering=1)
|
||||
except Exception:
|
||||
fallback = TEMP_DIR / path.name
|
||||
fallback.parent.mkdir(parents=True, exist_ok=True)
|
||||
return fallback.open("a", encoding="utf-8", buffering=1)
|
||||
|
||||
|
||||
def ensure_stdio(app_name: str) -> None:
|
||||
"""Give ``pythonw`` a real stdout/stderr target before loggers are imported."""
|
||||
|
||||
stamp = datetime.now().strftime("%Y%m%d")
|
||||
if sys.stdout is None:
|
||||
handle = (BASE_DIR / f"{app_name}_stdout_{stamp}.log").open("a", encoding="utf-8", buffering=1)
|
||||
handle = _open_log_file(BASE_DIR / f"{app_name}_stdout_{stamp}.log")
|
||||
_STDIO_HANDLES.append(handle)
|
||||
sys.stdout = handle
|
||||
if sys.stderr is None:
|
||||
handle = (BASE_DIR / f"{app_name}_stderr_{stamp}.log").open("a", encoding="utf-8", buffering=1)
|
||||
handle = _open_log_file(BASE_DIR / f"{app_name}_stderr_{stamp}.log")
|
||||
_STDIO_HANDLES.append(handle)
|
||||
sys.stderr = handle
|
||||
|
||||
@@ -32,25 +51,119 @@ def ensure_stdio(app_name: str) -> None:
|
||||
def log_fatal(app_name: str, exc: BaseException) -> None:
|
||||
"""Write one startup/runtime crash to a persistent log file."""
|
||||
|
||||
with FATAL_LOG.open("a", encoding="utf-8") as handle:
|
||||
with _open_log_file(FATAL_LOG) as handle:
|
||||
handle.write("\n" + "=" * 80 + "\n")
|
||||
handle.write(f"{datetime.now():%Y-%m-%d %H:%M:%S} | {app_name}\n")
|
||||
handle.write("".join(traceback.format_exception(type(exc), exc, exc.__traceback__)))
|
||||
|
||||
|
||||
def log_exception(app_name: str, exc: BaseException, *, context: str = "") -> None:
|
||||
"""Write a handled or callback exception to the persistent fatal log."""
|
||||
|
||||
with _open_log_file(FATAL_LOG) as handle:
|
||||
handle.write("\n" + "=" * 80 + "\n")
|
||||
handle.write(f"{datetime.now():%Y-%m-%d %H:%M:%S} | {app_name}")
|
||||
if context:
|
||||
handle.write(f" | {context}")
|
||||
handle.write("\n")
|
||||
handle.write("".join(traceback.format_exception(type(exc), exc, exc.__traceback__)))
|
||||
|
||||
|
||||
def configure_exception_logging(app_name: str, root=None, loop=None) -> None:
|
||||
"""Install process, Tk and asyncio exception hooks for console-less apps."""
|
||||
|
||||
if app_name in _EXCEPTION_LOGGING_CONFIGURED:
|
||||
return
|
||||
_EXCEPTION_LOGGING_CONFIGURED.add(app_name)
|
||||
|
||||
previous_excepthook = sys.excepthook
|
||||
|
||||
def _sys_excepthook(exc_type, exc, tb):
|
||||
log_exception(app_name, exc, context="sys.excepthook")
|
||||
if previous_excepthook:
|
||||
previous_excepthook(exc_type, exc, tb)
|
||||
|
||||
sys.excepthook = _sys_excepthook
|
||||
|
||||
if hasattr(threading, "excepthook"):
|
||||
previous_threading_excepthook = threading.excepthook
|
||||
|
||||
def _threading_excepthook(args):
|
||||
log_exception(app_name, args.exc_value, context=f"thread={getattr(args.thread, 'name', '')}")
|
||||
previous_threading_excepthook(args)
|
||||
|
||||
threading.excepthook = _threading_excepthook
|
||||
|
||||
if root is not None:
|
||||
def _tk_exception(exc_type, exc, tb):
|
||||
log_exception(app_name, exc, context="tkinter callback")
|
||||
try:
|
||||
import error_dialog as messagebox
|
||||
|
||||
messagebox.showerror(
|
||||
app_name,
|
||||
"Errore applicativo registrato nei log.\n\n"
|
||||
"Se l'operazione era in corso, ripeterla o avvisare il responsabile.",
|
||||
parent=root,
|
||||
exception=exc,
|
||||
context="tkinter callback",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
root.report_callback_exception = _tk_exception
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if loop is not None:
|
||||
previous_loop_handler = None
|
||||
try:
|
||||
previous_loop_handler = loop.get_exception_handler()
|
||||
except Exception:
|
||||
previous_loop_handler = None
|
||||
|
||||
def _loop_exception_handler(active_loop, context):
|
||||
exc = context.get("exception")
|
||||
if exc is not None:
|
||||
log_exception(app_name, exc, context=f"asyncio: {context.get('message', '')}")
|
||||
else:
|
||||
log_runtime_event(app_name, f"ASYNCIO {context!r}")
|
||||
if previous_loop_handler is not None:
|
||||
previous_loop_handler(active_loop, context)
|
||||
|
||||
try:
|
||||
loop.set_exception_handler(_loop_exception_handler)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def log_runtime_event(app_name: str, message: str) -> None:
|
||||
"""Write a lightweight launch/shutdown trace for console-less starts."""
|
||||
|
||||
safe_name = "".join(ch if ch.isalnum() or ch in ("_", "-") else "_" for ch in app_name.lower())
|
||||
path = BASE_DIR / f"{safe_name}_launch.log"
|
||||
with _open_log_file(path) as handle:
|
||||
handle.write(f"{datetime.now():%Y-%m-%d %H:%M:%S} | {message}\n")
|
||||
|
||||
|
||||
def show_fatal_message(app_name: str, exc: BaseException) -> None:
|
||||
"""Show a best-effort message box for console-less launches."""
|
||||
|
||||
try:
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox
|
||||
import error_dialog as messagebox
|
||||
|
||||
root = tk.Tk()
|
||||
root.withdraw()
|
||||
messagebox.showerror(
|
||||
app_name,
|
||||
f"Avvio non riuscito.\n\nDettaglio salvato in:\n{FATAL_LOG}\n\n{exc}",
|
||||
"Avvio non riuscito.\n\n"
|
||||
f"Controlla i log in:\n{BASE_DIR}\n\n"
|
||||
f"Se non ci sono, controlla anche:\n{TEMP_DIR}\n\n"
|
||||
f"{exc}",
|
||||
parent=root,
|
||||
exception=exc,
|
||||
)
|
||||
root.destroy()
|
||||
except Exception:
|
||||
@@ -61,8 +174,15 @@ def run_with_fatal_log(app_name: str, func: Callable[[], T]) -> T:
|
||||
"""Run an app entry point and persist otherwise invisible ``pythonw`` crashes."""
|
||||
|
||||
try:
|
||||
return func()
|
||||
log_runtime_event(
|
||||
app_name,
|
||||
f"START exe={sys.executable!r} version={sys.version.split()[0]} cwd={Path.cwd()} base={BASE_DIR} argv={sys.argv!r}",
|
||||
)
|
||||
result = func()
|
||||
log_runtime_event(app_name, f"RETURN result={result!r}")
|
||||
return result
|
||||
except BaseException as exc:
|
||||
log_runtime_event(app_name, f"EXCEPTION type={type(exc).__name__} value={exc!r}")
|
||||
log_fatal(app_name, exc)
|
||||
show_fatal_message(app_name, exc)
|
||||
raise
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import filedialog, messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import filedialog, ttk
|
||||
|
||||
import customtkinter as ctk
|
||||
|
||||
@@ -11,9 +12,19 @@ from busy_overlay import InlineBusyOverlay
|
||||
from gestione_aree import AsyncRunner
|
||||
from locale_text import load_locale_catalog, text as loc_text
|
||||
from ui_theme import theme_color, theme_font, theme_section, theme_value
|
||||
from ui_tables import (
|
||||
apply_tksheet_visual_style,
|
||||
apply_tksheet_zebra,
|
||||
merge_tags,
|
||||
style_treeview,
|
||||
zebra_tag,
|
||||
)
|
||||
from version_info import module_version, versioned_title
|
||||
from window_placement import place_window_fullsize_below_parent_later
|
||||
from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
try:
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Font
|
||||
@@ -85,7 +96,7 @@ class SearchWindow(ctk.CTkToplevel):
|
||||
self._theme = theme_section("search_window", {})
|
||||
self._locale_catalog = load_locale_catalog()
|
||||
self._tooltip_catalog = load_tooltip_catalog()
|
||||
self.title(loc_text("search.title", catalog=self._locale_catalog, default="Ricerca UDC/Lotto/Codice"))
|
||||
self.title(versioned_title(loc_text("search.title", catalog=self._locale_catalog, default="Ricerca UDC/Lotto/Codice"), __name__))
|
||||
self.geometry(str(theme_value(self._theme, "window_geometry", "1100x720")))
|
||||
minsize = theme_value(self._theme, "window_minsize", [900, 560])
|
||||
self.minsize(int(minsize[0]), int(minsize[1]))
|
||||
@@ -174,17 +185,25 @@ class SearchWindow(ctk.CTkToplevel):
|
||||
self.use_sheet = False
|
||||
cols = ("IDCella", "Ubicazione", "UDC", "Lotto", "Codice", "Descrizione")
|
||||
self.tree = ttk.Treeview(wrap, columns=cols, show="headings")
|
||||
self._style = ttk.Style(self)
|
||||
try:
|
||||
self._style.theme_use(self._style.theme_use())
|
||||
except Exception:
|
||||
pass
|
||||
self._style.configure("Search.Treeview", rowheight=22, font=("", 9))
|
||||
self._style.configure("Search.Treeview.Heading", font=("", 9, "bold"), background="#F3F4F6")
|
||||
self._style.map("Search.Treeview", background=[("selected", "#DCEBFF")])
|
||||
self.tree.configure(style="Search.Treeview")
|
||||
self.tree.tag_configure("even", background="#FFFFFF")
|
||||
self.tree.tag_configure("odd", background="#F7F9FC")
|
||||
headings = {
|
||||
"IDCella": ("IDCella", 90, "e"),
|
||||
"Ubicazione": ("Ubicazione", 150, "w"),
|
||||
"UDC": ("UDC / Barcode", 130, "w"),
|
||||
"Lotto": ("Lotto", 130, "w"),
|
||||
"Codice": ("Codice prodotto", 150, "w"),
|
||||
"Descrizione": ("Descrizione prodotto", 340, "w"),
|
||||
}
|
||||
for col in cols:
|
||||
text, width, anchor = headings[col]
|
||||
self.tree.heading(col, text=text)
|
||||
self.tree.column(col, width=width, anchor=anchor, stretch=True)
|
||||
self._style = style_treeview(
|
||||
self.tree,
|
||||
style_name="Search.Treeview",
|
||||
rowheight=22,
|
||||
font=("", 9),
|
||||
heading_font=("", 9, "bold"),
|
||||
)
|
||||
self.tree.tag_configure("id9999", background="#FFECEC", foreground="#B00020")
|
||||
|
||||
sy = ttk.Scrollbar(wrap, orient="vertical", command=self.tree.yview)
|
||||
@@ -209,7 +228,7 @@ class SearchWindow(ctk.CTkToplevel):
|
||||
is9999 = int(vals[0]) == 9999
|
||||
except Exception:
|
||||
is9999 = False
|
||||
tags = ("id9999", zebra) if is9999 else (zebra,)
|
||||
tags = merge_tags(zebra, "id9999" if is9999 else "")
|
||||
self.tree.item(iid, tags=tags)
|
||||
|
||||
def _export_xlsx(self):
|
||||
@@ -281,6 +300,7 @@ class SearchWindow(ctk.CTkToplevel):
|
||||
loc_text("search.msg.export_title", catalog=self._locale_catalog, default="Esporta"),
|
||||
loc_text("search.msg.export_error", catalog=self._locale_catalog, default="Errore durante l'esportazione:{error}").format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
|
||||
def _on_dclick(self, evt):
|
||||
@@ -414,6 +434,8 @@ class SearchWindow(ctk.CTkToplevel):
|
||||
hdrs = list(headers)
|
||||
hdrs[c] = hdrs[c] + arrow
|
||||
self.sheet.headers(hdrs)
|
||||
apply_tksheet_visual_style(self.sheet)
|
||||
apply_tksheet_zebra(self.sheet, len(data))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -449,7 +471,10 @@ class SearchWindow(ctk.CTkToplevel):
|
||||
for row in rows:
|
||||
idc, ubi, udc_v, lot_v, cod_v, desc_v = row
|
||||
data.append([idc, ubi, udc_v, lot_v, cod_v, desc_v])
|
||||
self.sheet.headers(["IDCella", "Ubicazione", "UDC", "Lotto", "Codice", "Descrizione"])
|
||||
apply_tksheet_visual_style(self.sheet)
|
||||
self.sheet.set_sheet_data(data)
|
||||
apply_tksheet_zebra(self.sheet, len(data))
|
||||
self.sheet.set_all_cell_sizes_to_text()
|
||||
except Exception:
|
||||
self.use_sheet = False
|
||||
@@ -458,12 +483,11 @@ class SearchWindow(ctk.CTkToplevel):
|
||||
self.tree.delete(iid)
|
||||
for idx, row in enumerate(rows):
|
||||
idc, ubi, udc_v, lot_v, cod_v, desc_v = row
|
||||
zebra = "even" if idx % 2 == 0 else "odd"
|
||||
try:
|
||||
is9999 = int(idc) == 9999
|
||||
except Exception:
|
||||
is9999 = False
|
||||
tags = ("id9999", zebra) if is9999 else (zebra,)
|
||||
tags = merge_tags(zebra_tag(idx), "id9999" if is9999 else "")
|
||||
self.tree.insert("", "end", values=(idc, ubi, udc_v, lot_v, cod_v, desc_v), tags=tags)
|
||||
|
||||
if not rows:
|
||||
@@ -488,6 +512,7 @@ class SearchWindow(ctk.CTkToplevel):
|
||||
loc_text("search.msg.error_title", catalog=self._locale_catalog, default="Errore ricerca"),
|
||||
str(ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
|
||||
self._async.run(
|
||||
|
||||
250
specifica_inventario.md
Normal file
250
specifica_inventario.md
Normal file
@@ -0,0 +1,250 @@
|
||||
# Inventario WMS - SAM per prodotto e lotto
|
||||
|
||||
## Revisione interfaccia 1.1.1
|
||||
|
||||
Guida operativa campo per campo: [GUIDA_INVENTARIO.md](GUIDA_INVENTARIO.md).
|
||||
Legenda permanente A/B/C/X su righe distinte, lettere in grassetto e colori/font
|
||||
configurabili nel tema JSON. Testi IT/ENG e ritorno a capo in base alla larghezza.
|
||||
Il messaggio iniziale spiega come calcolare, senza ripetere il perimetro.
|
||||
Non cambia il calcolo, il contenuto dell'export o la query SQL.
|
||||
|
||||
## Stato al 21/10/2026
|
||||
|
||||
Modulo Inventario 1.1.0 completato sul ramo `codex/inventario-monolista`,
|
||||
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.
|
||||
439
specifica_prelievo_due_pickinglist.md
Normal file
439
specifica_prelievo_due_pickinglist.md
Normal file
@@ -0,0 +1,439 @@
|
||||
# Prelievo guidato di due picking list sul terminalino
|
||||
|
||||
Data: 02/10/2026. Revisione: 0.3.
|
||||
|
||||
**Stato: specifica da rileggere e concordare prima dell'implementazione.**
|
||||
La funzione di prelievo abbinato descritta qui non e' ancora implementata.
|
||||
I punti indicati come aperti o proposti non sono decisioni gia' approvate.
|
||||
|
||||
## 1. Obiettivo operativo
|
||||
|
||||
Consentire al responsabile di prenotare una oppure due picking list dal
|
||||
programma desktop. Quando sono due, il terminalino deve guidare un unico
|
||||
percorso di prelievo che considera le UDC residue di entrambe.
|
||||
|
||||
L'operatore deve percorrere il magazzino seguendo l'ordine previsto, senza
|
||||
ritornare alle prime colonne perche' una lista non conteneva UDC in quelle
|
||||
posizioni. Il sistema sceglie di volta in volta il documento della prossima
|
||||
UDC; l'operatore riconosce il cambio dal numero del documento e dal colore.
|
||||
|
||||
Il prelievo abbinato riguarda un operatore che lavora due documenti nello
|
||||
stesso giro. La gestione di piu' operatori contemporanei richiede ulteriori
|
||||
decisioni e non e' definita da questa specifica.
|
||||
|
||||
## 2. Termini usati
|
||||
|
||||
| Termine | Significato |
|
||||
|---|---|
|
||||
| Lista 1 / F1 | Prima lista assegnata alla coppia, con identita' stabile |
|
||||
| Lista 2 / F2 | Seconda lista assegnata alla coppia, con identita' stabile |
|
||||
| Lista proposta | Documento della prossima UDC indicata dal sistema |
|
||||
| Colonna o campata | Colonna di uno specifico scaffale e magazzino |
|
||||
| Cella | Singola posizione dentro la colonna, a un determinato livello |
|
||||
| Percorso comune | Ordine delle posizioni applicato alle UDC di entrambe le liste |
|
||||
| UDC residua | UDC ancora da prelevare, non gia' nella locazione spedita |
|
||||
|
||||
Area 5 e Area 6 sono i nomi operativi dei magazzini MDE5 e MDE6.
|
||||
Non corrispondono necessariamente agli ID 5 e 6 della tabella legacy Aree.
|
||||
La colonna 1 dello scaffale A e la colonna 1 dello scaffale B sono distinte.
|
||||
|
||||
## 3. Situazione attuale e difetto da non reintrodurre
|
||||
|
||||
La prenotazione Python attuale prevede un unico documento. Storicamente F1
|
||||
interroga la priorita' prenotata e F2 quella non prenotata. Quest'ultima puo'
|
||||
contenere piu' documenti, quindi non identifica di per se' una seconda lista.
|
||||
|
||||
E' stata introdotta nel codice locale una correzione che fissa il documento
|
||||
del ciclo per ciascun tasto. Il passaggio F2 -> F1 -> F2 conserva il documento
|
||||
precedentemente avviato con F2. Il dettaglio e' in
|
||||
[fix_barcode_documento_fisso_f1_f2.md](fix_barcode_documento_fisso_f1_f2.md).
|
||||
|
||||
La nuova funzione estende il modello: entrambi i documenti devono essere
|
||||
esplicitamente assegnati alla coppia. Il cambio automatico sara' ammesso
|
||||
soltanto fra questi due documenti e per una ragione di percorso.
|
||||
Nessuna terza lista deve subentrare silenziosamente.
|
||||
|
||||
## 4. Selezione e prenotazione sul desktop
|
||||
|
||||
### R01. Una o due liste
|
||||
|
||||
Gestione Picking List deve permettere di prenotare al massimo due liste per
|
||||
il prelievo abbinato. Deve restare utilizzabile anche con una sola lista.
|
||||
Il semplice clic per consultare il dettaglio non deve modificare implicitamente
|
||||
una prenotazione: selezione per consultazione e assegnazione al giro devono
|
||||
avere un comportamento chiaramente distinguibile.
|
||||
|
||||
### R02. Identita' della coppia
|
||||
|
||||
Il desktop deve rendere riconoscibile quale documento e' Lista 1/F1 e quale
|
||||
e' Lista 2/F2. L'assegnazione non dipende dall'ordinamento momentaneo della
|
||||
griglia o dalla posizione della prossima UDC.
|
||||
|
||||
Il gesto per assegnare i ruoli e' ancora da definire: ad esempio due slot
|
||||
espliciti, oppure prima e seconda scelta rese chiaramente visibili.
|
||||
|
||||
### R02a. Le due liste devono appartenere alla stessa area
|
||||
|
||||
Il prelievo abbinato e' consentito esclusivamente fra due liste della stessa
|
||||
area operativa: entrambe Area 5/MDE5 oppure entrambe Area 6/MDE6.
|
||||
Non e' consentito abbinare una lista dell'Area 5 a una dell'Area 6.
|
||||
Il sistema deve rifiutare l'abbinamento con un messaggio comprensibile,
|
||||
senza salvare una coppia parziale o alterare le prenotazioni preesistenti.
|
||||
Il vincolo deve essere verificato anche lato servizio/database, non soltanto
|
||||
mediante la disponibilita' dei pulsanti nell'interfaccia desktop.
|
||||
|
||||
Prima dell'implementazione va definita la fonte autorevole dell'area della
|
||||
lista, specialmente se contiene UDC non scaffalate o senza giacenza WMS.
|
||||
La cella virtuale condivisa 1000 non dimostra da sola l'appartenenza all'area.
|
||||
Non dedurre il magazzino dal numero documento o dagli ID legacy delle Aree.
|
||||
Il trattamento delle liste internamente miste o con area indeterminata resta
|
||||
da concordare; non considerarle implicitamente compatibili con entrambe.
|
||||
|
||||
### R03. Un'unica sequenza personalizzata
|
||||
|
||||
Con due liste selezionate, il comando Sequenza di prelievo riguarda entrambe.
|
||||
L'editor deve presentare l'unione degli scaffali/gruppi presenti nelle due liste,
|
||||
includendo quelli presenti soltanto in una di esse e il gruppo Non scaff.
|
||||
|
||||
Non si devono eseguire due ordinamenti personalizzati incompatibili nello
|
||||
stesso giro. La sequenza della coppia deve costituire l'unico riferimento.
|
||||
|
||||
La scelta fra eventuali personalizzazioni gia' salvate sulle singole liste
|
||||
resta aperta. Non e' ammessa una fusione silenziosa che produca un ordine
|
||||
diverso da quello mostrato al responsabile.
|
||||
|
||||
## 5. Percorsi delle aree: conservare il comportamento esistente
|
||||
|
||||
### R04. Area 6 / MDE6
|
||||
|
||||
Conservare il percorso attuale: scaffali nell'ordine previsto, colonne in
|
||||
ordine crescente all'interno dello scaffale e livelli dal pavimento verso
|
||||
l'alto. Il documento [ordinamento.md](ordinamento.md) riporta per i dati
|
||||
analizzati la sequenza interna a -> b -> c -> d -> e.
|
||||
|
||||
La modifica non deve rinumerare Celle.Ordinamento ne' inventare nuovi percorsi
|
||||
per celle eventualmente configurate con eccezioni.
|
||||
|
||||
### R05. Area 5 / MDE5
|
||||
|
||||
Conservare l'ordinamento esistente delle celle. Nel default e' il percorso
|
||||
storico rappresentato da Celle.Ordinamento, con serpentina fra scaffali.
|
||||
|
||||
Esempio documentato del blocco 1A/2B:
|
||||
|
||||
```text
|
||||
1A.1 -> 2B.1 -> 2B.2 -> 1A.2 -> 1A.3 -> 2B.3 -> ...
|
||||
```
|
||||
|
||||
All'interno delle campate analizzate l'ordine e' e -> d -> c -> b -> a,
|
||||
quindi dall'alto verso il basso. E' confermato che anche la prima UDC
|
||||
proposta deve rispettare questo verso: non partire dal pavimento in area 5.
|
||||
Non sostituire questo percorso con un generico ordinamento numerico
|
||||
scaffale/colonna/livello dell'area 6.
|
||||
|
||||
### R06. Effetto della personalizzazione
|
||||
|
||||
La personalizzazione mantiene il significato attuale: cambia la precedenza
|
||||
dei gruppi/scaffali, mentre dentro ogni gruppo si conserva l'ordine delle celle.
|
||||
Con due liste, la stessa scelta si applica all'intero contenuto della coppia.
|
||||
|
||||
Per esempio, porre tutto 1A prima di tutto 2B elimina intenzionalmente
|
||||
l'alternanza fra quei due scaffali, come avviene gia' nella personalizzazione
|
||||
attuale. Non sarebbe corretto promettere contemporaneamente tale precedenza
|
||||
e il mantenimento della serpentina globale.
|
||||
|
||||
I gruppi omessi da una personalizzazione parziale devono essere accodati con
|
||||
il criterio attuale, senza perdere le relative UDC.
|
||||
|
||||
## 6. Scelta della prossima UDC
|
||||
|
||||
### R07. Confronto continuo delle due liste
|
||||
|
||||
A ogni passo confrontare le UDC ancora lavorabili di entrambe le liste e
|
||||
scegliere quella che viene prima nel percorso comune.
|
||||
Questa regola vale all'avvio, fra colonne consecutive, dopo un movimento e
|
||||
quando uno dei documenti non ha UDC nella colonna corrente.
|
||||
|
||||
Non si deve usare F1 come guida unica, cercando F2 soltanto nelle colonne
|
||||
incontrate da F1: questo lascerebbe indietro le colonne presenti solo in F2.
|
||||
|
||||
### R08. Il percorso prevale sull'identita' della lista
|
||||
|
||||
Non esiste una precedenza fissa F1-prima-di-F2 nella stessa colonna.
|
||||
Se nell'area 6 i livelli dal basso verso l'alto appartengono a F2, F1 e F2,
|
||||
il prelievo deve seguire F2 -> F1 -> F2.
|
||||
|
||||
La precedente ipotesi di esaurire tutte le UDC F1 della colonna e solo dopo
|
||||
quelle F2 e' superata: la scelta si compie sulla posizione a ogni passo.
|
||||
|
||||
### R09. Nessuna UDC persa e nessun documento estraneo
|
||||
|
||||
Il contenuto lavorato e' l'unione delle UDC residue delle due liste.
|
||||
Le UDC su piu' righe lotto devono essere considerate una sola volta come
|
||||
unita' fisica di prelievo. Ogni proposta deve mantenere l'identita' del
|
||||
documento a cui appartiene.
|
||||
|
||||
Non introdurre la scelta automatica di una terza lista, neanche al termine
|
||||
di una delle due. La gestione delle UDC saltate e' trattata al punto 10.
|
||||
|
||||
## 7. Avvio neutro e tasti F1/F2
|
||||
|
||||
### R10. Avvio scelto dal sistema
|
||||
|
||||
Quando il terminalino mostra Pronto per la coppia, il sistema deve avere gia'
|
||||
individuato la prima proposta. L'operatore non decide arbitrariamente da quale
|
||||
documento partire.
|
||||
|
||||
Se la prima UDC appartiene alla Lista 2, F2 e' abilitato e F1 disabilitato;
|
||||
se appartiene alla Lista 1, vale il contrario. Il blocco deve valere sia per
|
||||
i pulsanti sullo schermo sia per i tasti fisici.
|
||||
|
||||
### R11. Guida durante il giro
|
||||
|
||||
Nel prelievo abbinato deve essere selezionabile soltanto la lista proposta
|
||||
dal percorso. Il cambio automatico verso l'altro documento non richiede una
|
||||
nuova scelta dell'operatore.
|
||||
|
||||
La precedente modalita' manuale F1/F2 e il nuovo giro guidato non devono
|
||||
essere confusi: nel giro guidato i due tasti identificano documenti stabili,
|
||||
ma non autorizzano a scavalcare il percorso stabilito.
|
||||
|
||||
### Chiarimento confermato: la prima cella dipende dal percorso dell'area
|
||||
|
||||
Si parte dalla prima UDC secondo il percorso effettivo comune, rispettando
|
||||
anche all'avvio l'ordine dell'area e l'eventuale personalizzazione.
|
||||
La precedente espressione "cella piu' bassa" non e' una regola universale:
|
||||
|
||||
- Area 5: nella campata prevista dal percorso, prima la cella occupata
|
||||
richiesta piu' in alto, poi quelle inferiori (e -> d -> c -> b -> a).
|
||||
- Area 6: nella colonna prevista dal percorso, prima la cella occupata
|
||||
richiesta piu' vicina al pavimento, poi quelle superiori (a -> b -> c -> d -> e).
|
||||
|
||||
Il confronto comprende entrambe le liste: in area 5, se F1 ha una UDC al
|
||||
livello a e F2 ne ha una al livello d della stessa campata, si propone prima
|
||||
F2/d e poi F1/a. Non conta quale documento occupa il ruolo di Lista 1.
|
||||
Restano la serpentina del default area 5, l'ordine comune eventualmente
|
||||
personalizzato e la precedenza delle Non scaff. descritta in R14.
|
||||
|
||||
## 8. Identificazione visiva sul terminalino
|
||||
|
||||
### R12. Colori stabili
|
||||
|
||||
| Documento assegnato | Colore di contesto |
|
||||
|---|---|
|
||||
| Lista 1 / F1 | Rosellino |
|
||||
| Lista 2 / F2 | Giallino |
|
||||
|
||||
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
|
||||
nei successivi passaggi.
|
||||
|
||||
Il numero della picking list e il ruolo Lista 1/Lista 2 devono essere leggibili
|
||||
insieme all'UDC e alla cella proposta: il colore non deve essere l'unica
|
||||
informazione per capire quale documento si sta lavorando.
|
||||
|
||||
La barra esito mantiene il significato funzionale dei propri colori
|
||||
(successo, errore, attesa), distinguibile dallo sfondo di contesto.
|
||||
Il layout deve restare utilizzabile sul terminalino 240 x 320.
|
||||
|
||||
## 9. Ciclo di scansione e conferma
|
||||
|
||||
### R13. Sequenza ordinaria
|
||||
|
||||
1. Il sistema propone UDC, cella sorgente e documento; applica il colore relativo.
|
||||
2. L'operatore legge il barcode della UDC proposta.
|
||||
3. Rimangono i controlli attuali di corrispondenza e avvio automatico della lettura.
|
||||
4. Il movimento di picking porta la UDC in spedita, 7G.1.1, destinazione 9000000.
|
||||
5. Il terminalino mostra l'esito positivo per i tre secondi previsti.
|
||||
6. Il sistema propone la prossima UDC della coppia secondo il percorso comune.
|
||||
7. Se cambia documento, aggiorna insieme colore, riferimento lista e tasti abilitati.
|
||||
|
||||
L'esito dei tre secondi appartiene al movimento appena concluso, non al
|
||||
documento che verra' proposto dopo. Non deve comparire un contesto misto.
|
||||
|
||||
Un cambio programma della UDC visualizzata non deve simulare una scansione
|
||||
dell'operatore: va preservata la protezione contro gli auto-submit accidentali.
|
||||
Un errore o un esito incerto non deve avanzare il giro come se il movimento
|
||||
fosse riuscito; restano necessarie le verifiche e il recupero gia' esistenti.
|
||||
|
||||
## 10. Non scaffalate, salti, pausa e fine giro
|
||||
|
||||
### R14. Non scaffalate
|
||||
|
||||
Conservare il comportamento corrente: Non scaff. precede gli scaffali nel
|
||||
default, salvo diversa posizione assegnata nella sequenza personalizzata.
|
||||
La regola deve considerare le UDC di entrambe le liste.
|
||||
|
||||
La cella virtuale e' condivisibile e non ha un livello fisico da confrontare.
|
||||
Il criterio di parita' fra UDC non scaffalate delle due liste resta da
|
||||
concordare; proposta: ordine stabile per ruolo lista e codice UDC.
|
||||
|
||||
### R15. UDC saltate: approfondimento rinviato
|
||||
|
||||
Il comando Salta UDC esiste gia'. L'utente ha chiesto di analizzarne in seguito
|
||||
il comportamento nel nuovo giro abbinato, con l'intenzione di conservare
|
||||
quanto possibile il funzionamento attuale.
|
||||
|
||||
Restano da decidere il termine della singola lista con soli skip, la sua
|
||||
sprenotazione, la prosecuzione dell'altra lista e le modalita' di ripresa.
|
||||
Saltare una UDC non deve comunque equivalere a spedirla o cancellarla dalla lista.
|
||||
|
||||
### Pausa e ripresa: comportamento da completare
|
||||
|
||||
Oggi Pausa PL consente movimenti liberi e ESC riporta al picking.
|
||||
Nel nuovo giro occorre conservare identita' dei due documenti e percorso.
|
||||
Va deciso se al rientro mantenere la UDC gia' proposta o ricalcolare la
|
||||
prossima posizione quando nel frattempo cambiano le ubicazioni.
|
||||
I movimenti liberi devono mantenere le proprie regole di carico e scarico.
|
||||
|
||||
### Fine di una lista: proposta ancora da confermare
|
||||
|
||||
Quando una lista non ha piu' UDC residue, proseguire con l'altra mantenendone
|
||||
ruolo e colore originali. Non promuovere automaticamente F2 a F1 e non
|
||||
aggiungere un terzo documento. Distinguere esaurimento reale e soli skip.
|
||||
|
||||
## 11. Esempi di percorso atteso
|
||||
|
||||
### Esempio A: colonne presenti soltanto in F2
|
||||
|
||||
Area 6, stesso scaffale, default: colonne crescenti e livelli dal basso
|
||||
verso l'alto.
|
||||
|
||||
| Passo | Posizione | Lista proposta |
|
||||
|---|---|---|
|
||||
| 1 | Colonna 1, livello a | F2 |
|
||||
| 2 | Colonna 2, livello a | F2 |
|
||||
| 3 | Colonna 3, livello a | F1 |
|
||||
| 4 | Colonna 3, livello b | F2 |
|
||||
| 5 | Colonna 4, livello a | F2 |
|
||||
| 6 | Colonna 5, livello a | F2 |
|
||||
| 7 | Colonna 6, livello a | F1 |
|
||||
|
||||
F1 ha UDC solo ogni tre colonne. Le colonne intermedie di F2 vengono visitate
|
||||
al momento corretto, senza attendere il termine di F1.
|
||||
|
||||
### Esempio B: alternanza verticale nella stessa colonna
|
||||
|
||||
| Passo | Posizione | Lista proposta |
|
||||
|---|---|---|
|
||||
| 1 | Colonna 3, livello a | F2 |
|
||||
| 2 | Colonna 3, livello b | F1 |
|
||||
| 3 | Colonna 3, livello d | F2 |
|
||||
| 4 | Colonna 4, livello a | F1 |
|
||||
|
||||
Il passaggio F2 -> F1 -> F2 e' richiesto dal percorso; i documenti associati
|
||||
ai tasti restano gli stessi.
|
||||
|
||||
### Esempio C: area 5 con default storico
|
||||
|
||||
| Ordinamento cella | Ubicazione | Lista proposta |
|
||||
|---|---|---|
|
||||
| 1001 | 1A.1.e | F2 |
|
||||
| 1003 | 1A.1.c | F1 |
|
||||
| 1007 | 2B.1.e | F1 |
|
||||
| 1010 | 2B.1.b | F2 |
|
||||
| 1013 | 2B.2.e | F2 |
|
||||
| 1019 | 1A.2.e | F1 |
|
||||
|
||||
Si uniscono le due liste rispettando i valori del percorso storico; non si
|
||||
raggruppano automaticamente tutte le colonne 1A prima di quelle 2B.
|
||||
|
||||
### Esempio D: ordine personalizzato della coppia
|
||||
|
||||
Il responsabile imposta Non scaff. -> 4P -> 1M. Il terminalino lavora tutte
|
||||
le UDC richieste dalle due liste in Non scaff., poi quelle in 4P, poi quelle
|
||||
in 1M, applicando dentro ciascun gruppo l'ordine delle celle previsto.
|
||||
Gli eventuali gruppi non configurati vengono accodati, mai esclusi.
|
||||
|
||||
## 12. Garanzie e decisioni tecniche da tradurre in progetto
|
||||
|
||||
La prenotazione attuale a documento unico deve evolvere per rappresentare
|
||||
esplicitamente due documenti con ruoli stabili e una sequenza comune.
|
||||
Il formato delle nuove tabelle e le modifiche alle stored non sono ancora
|
||||
definiti da questo documento.
|
||||
|
||||
La nuova prenotazione dovra' essere salvata in modo atomico, evitando che il
|
||||
terminalino legga meta' coppia o una sequenza parzialmente aggiornata.
|
||||
Le modifiche SQL dovranno avere script di installazione e di ripristino e
|
||||
mantenere la separazione degli oggetti Python dagli oggetti legacy C#.
|
||||
|
||||
Sono ancora da specificare persistenza della ripresa dopo riavvio, modifiche
|
||||
alla coppia durante un giro, modifiche della sequenza a giro iniziato e
|
||||
comportamento con piu' terminalini. Non assumere che la memoria locale del
|
||||
singolo client sia una soluzione completa per questi casi.
|
||||
|
||||
## 13. Dati locali predisposti per il collaudo
|
||||
|
||||
Il 01/10/2026 sono state riattivate nella copia locale quattro testate SAM
|
||||
cambiando solo D in P, senza movimentare UDC. Con filtro 30 giorni:
|
||||
|
||||
| Lista | UDC residue | In celle fisiche | Non scaffalate nella vista |
|
||||
|---|---:|---:|---:|
|
||||
| 233 | 28 | 3 | 25 |
|
||||
| 234 | 28 | 2 | 26 |
|
||||
| 240 | 11 | 0 | 11 |
|
||||
| 241 | 28 | 0 | 28 |
|
||||
| 244, gia' attiva | 26 | 24 | 2 |
|
||||
|
||||
Le celle fisiche candidate sono risultate prive di altre UDC, anche esterne
|
||||
alle cinque liste. Le UDC residue non sono condivise fra questi documenti.
|
||||
La condivisione della locazione virtuale Non scaff. e' invece prevista.
|
||||
|
||||
Esempi utili in area 5: 234 in 1A.7.a e 244 in 1A.7.d; 233 in 1A.18.a e
|
||||
244 in 1A.18.c. Sono celle distinte della stessa colonna.
|
||||
|
||||
La voce Non scaff. puo' derivare anche dal fallback di una UDC senza giacenza
|
||||
WMS: non prova da sola l'esistenza di un versamento registrato nella cella 1000.
|
||||
|
||||
Questi dati non bastano a verificare tutte le alternanze verticali e le colonne
|
||||
intermedie in area 6: occorrera' predisporre ulteriori casi controllati prima
|
||||
del collaudo completo. Non creare documenti ERP fittizi o spostare UDC online
|
||||
per ottenere tali scenari.
|
||||
|
||||
Preparazione e ripristino sono descritti in [sql_tests/README.md](sql_tests/README.md).
|
||||
Il ripristino delle testate non annulla le movimentazioni fatte durante i test.
|
||||
|
||||
## 14. Criteri di accettazione
|
||||
|
||||
| Test | Risultato atteso |
|
||||
|---|---|
|
||||
| Una sola lista | Ordinamento attuale conservato |
|
||||
| Due liste entrambe Area 5 oppure entrambe Area 6 | Abbinamento consentito, applicando il percorso della relativa area |
|
||||
| Una lista Area 5 e una Area 6 | Abbinamento rifiutato senza modificare le prenotazioni esistenti |
|
||||
| F2 precede F1 nel percorso | All'avvio solo F2 utilizzabile |
|
||||
| F1 presente ogni tre colonne | Nessuna colonna intermedia F2 omessa |
|
||||
| Livelli alternati F2/F1/F2 | Tre proposte in ordine fisico, con documenti corretti |
|
||||
| Default area 5 | Serpentina attuale e livelli dall'alto verso il basso, anche all'avvio |
|
||||
| Area 5: F1 in 1A.7.a, F2 in 1A.7.d | Prima F2/d, poi F1/a, senza precedenza fissa a F1 |
|
||||
| Default area 6 | Percorso corrente per scaffale, colonne crescenti e livelli dal basso verso l'alto |
|
||||
| Personalizzazione della coppia | Stesso ordine applicato a entrambe |
|
||||
| Gruppo presente solo in F2 | Visibile nell'editor e incluso nel percorso |
|
||||
| Gruppo omesso dalla personalizzazione | Accodato secondo il comportamento attuale |
|
||||
| Tasto fisico della lista disabilitata | Nessun cambio documento e nessun movimento |
|
||||
| Cambio automatico | Numero lista, colore e UDC aggiornati coerentemente |
|
||||
| UDC con due lotti | Un solo prelievo fisico |
|
||||
| Terza lista disponibile | Mai inserita automaticamente nel giro |
|
||||
| Aggiornamento programma del campo UDC | Non interpretato come nuova lettura |
|
||||
| Movimento fallito o esito incerto | Nessun avanzamento ingiustificato |
|
||||
|
||||
I casi relativi a skip, fine parziale, pausa, riavvio e modifiche concorrenti
|
||||
andranno completati dopo la decisione delle relative regole.
|
||||
|
||||
## 15. Decisioni aperte per la revisione
|
||||
|
||||
L'avvio e' chiarito: si rispetta il percorso dell'area, dall'alto in area 5
|
||||
e dal basso in area 6. Restano aperti i punti seguenti.
|
||||
|
||||
1. Assegnazione esplicita dei ruoli Lista 1 e Lista 2 sul desktop.
|
||||
2. Gestione delle sequenze preesistenti quando si compone una nuova coppia.
|
||||
3. Ordine fra UDC non scaffalate o con identico valore di percorso.
|
||||
4. Salti, esaurimento con residui e riprenotazione della coppia o di una lista.
|
||||
5. Ripresa dalla pausa e da un riavvio, con ubicazioni eventualmente cambiate.
|
||||
6. Modifiche alla coppia/sequenza mentre il prelievo e' in corso.
|
||||
7. Fonte autorevole dell'area di una lista e gestione di liste internamente
|
||||
miste o con area indeterminata; le coppie Area 5/Area 6 sono vietate (R02a).
|
||||
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.
|
||||
|
||||
Le risposte possono essere annotate direttamente in questa sezione prima di
|
||||
passare al progetto tecnico e alle modifiche applicative.
|
||||
74
specifica_sequenza_prelievo.md
Normal file
74
specifica_sequenza_prelievo.md
Normal file
@@ -0,0 +1,74 @@
|
||||
# Sequenza di prelievo per picking list
|
||||
|
||||
## Obiettivo
|
||||
|
||||
Consentire al responsabile di definire, per una singola picking list, l'ordine
|
||||
dei gruppi di ubicazioni che il barcode deve seguire. Il barcode continua a
|
||||
presentare una sola UDC alla volta e non espone la configurazione all'operatore.
|
||||
|
||||
## Ordine predefinito
|
||||
|
||||
In assenza di una configurazione personalizzata il sistema propone:
|
||||
|
||||
1. UDC `Non scaff.` nella cella convenzionale `1000` / `5E.1.1`.
|
||||
2. UDC negli scaffali secondo il valore legacy `Celle.Ordinamento`.
|
||||
|
||||
L'ordinamento globale delle celle non viene modificato.
|
||||
|
||||
## Configurazione per documento
|
||||
|
||||
La finestra `Sequenza di prelievo` si apre dalla picking list selezionata in
|
||||
`Gestione Picking List`. I gruppi disponibili sono `Non scaff.` e le corsie
|
||||
effettivamente presenti nel contenuto residuo del documento.
|
||||
|
||||
L'utente puo' trascinare i gruppi nell'area destra, usare il doppio clic oppure
|
||||
i pulsanti `Aggiungi`, `Rimuovi`, `Su` e `Giu'`. L'ordine dall'alto verso il
|
||||
basso definisce la precedenza dei gruppi configurati.
|
||||
|
||||
Una sequenza puo' essere parziale: gli eventuali gruppi non inseriti vengono
|
||||
accodati secondo l'ordine predefinito. In questo modo una configurazione non
|
||||
puo' rendere invisibili UDC o scaffali aggiunti successivamente alla picking
|
||||
list.
|
||||
|
||||
`Ripristina default` elimina la configurazione del documento e riattiva
|
||||
immediatamente l'ordine standard.
|
||||
|
||||
## Persistenza e concorrenza
|
||||
|
||||
La tabella Python-only `dbo.py_PickingListPrelievoSequenza` memorizza una riga
|
||||
per documento e gruppo, con ordine e campi di audit. Il salvataggio marca come
|
||||
cancellata la configurazione precedente e inserisce quella nuova in una singola
|
||||
transazione con `XACT_ABORT ON`, conservando quindi anche lo storico delle
|
||||
variazioni.
|
||||
|
||||
Due picking list possono quindi avere sequenze diverse senza modificare le
|
||||
celle, le altre liste o gli oggetti usati dal programma C#.
|
||||
|
||||
## Consumo dal barcode
|
||||
|
||||
La vista Python-only `dbo.py_ViewPackingListPrelievo` deriva dalla vista
|
||||
residuale, esclude quindi le UDC gia' in `7G.1.1` e calcola
|
||||
`OrdinePrelievoGruppo`. Sia la griglia di dettaglio sia il repository barcode
|
||||
ordinano per:
|
||||
|
||||
1. `OrdinePrelievoGruppo`;
|
||||
2. `Ordinamento` legacy della cella;
|
||||
3. codice pallet come criterio stabile finale.
|
||||
|
||||
Pausa, ripresa, salto UDC, F1/F2 e prenotazione non vengono modificati. Quando
|
||||
una UDC viene movimentata, la richiesta successiva rilegge la vista e usa la
|
||||
sequenza corrente sul contenuto residuo.
|
||||
|
||||
## Installazione e rollback
|
||||
|
||||
Per un aggiornamento completo del database online usare
|
||||
`apply_online_python_wms_full_patch.sql`.
|
||||
|
||||
Per applicare solo questa evoluzione a un database gia' aggiornato:
|
||||
|
||||
1. eseguire `apply_pickinglist_days_filter_patch.sql`;
|
||||
2. eseguire `apply_pickinglist_sequence_patch.sql`.
|
||||
|
||||
Il rollback specifico e' `rollback_pickinglist_sequence_patch.sql`; dopo il
|
||||
rollback deve essere ripristinata anche una versione applicativa precedente,
|
||||
poiche' il nuovo codice interroga la vista di prelievo.
|
||||
38
sql_tests/README.md
Normal file
38
sql_tests/README.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# Dati per il collaudo a due picking list, 01/10/2026
|
||||
|
||||
Questi script riguardano esclusivamente la copia di test su HOMESERVER.
|
||||
Non includerli nella patch cumulativa per la produzione.
|
||||
|
||||
`riattiva_pickinglist_20261001.sql` cambia da D a P le testate SAM 233, 234,
|
||||
240 e 241 dell'anno 2026. Mantiene date, righe, lotti e posizioni delle UDC.
|
||||
Salva gli stati originali in Mediseawall.dbo.py_TestPickingListReactivation_20261001
|
||||
e controlla le precondizioni nella stessa transazione dell'aggiornamento.
|
||||
|
||||
In Gestione Picking List selezionare **30 giorni** per vedere tutte le liste:
|
||||
|
||||
| Lista | UDC residue | In celle fisiche | Non scaffalate nella vista |
|
||||
|---|---:|---:|---:|
|
||||
| 233 | 28 | 3 | 25 |
|
||||
| 234 | 28 | 2 | 26 |
|
||||
| 240 | 11 | 0 | 11 |
|
||||
| 241 | 28 | 0 | 28 |
|
||||
| 244 (gia attiva) | 26 | 24 | 2 |
|
||||
|
||||
La 240 conserva altre 33 UDC gia spedite, escluse dalla vista operativa.
|
||||
La qualifica non scaffalata deriva dalla vista: puo' comprendere UDC che non
|
||||
hanno una giacenza WMS, mostrate mediante il fallback convenzionale 1000.
|
||||
|
||||
Nessuna cella fisica candidata risulta contenere altre UDC. La condivisione
|
||||
della locazione virtuale non scaffalata e' ammessa. Le liste 233/234 e 244
|
||||
contengono celle distinte nelle stesse colonne, utili per il futuro test del
|
||||
cambio automatico fra documenti. Non sono stati creati movimenti di test.
|
||||
|
||||
`ripristina_testate_pickinglist_20261001.sql` ripristina solo gli stati SAM.
|
||||
Non ripristina UDC movimentate, skip o sequenze creati durante le prove.
|
||||
Per ripetere identicamente un test che modifica le giacenze occorre un backup
|
||||
coerente dei due database, oppure un ripristino specifico dei dati del test.
|
||||
La piccola tabella di backup degli stati non sostituisce tale backup completo.
|
||||
|
||||
Controllato anche il trigger SAM `StatoLottoRientrato`: il passaggio D -> P
|
||||
non soddisfa la sua condizione e non modifica i lotti. Il ripristino P -> D
|
||||
si ferma se esistono lotti marcati T, per evitare gli effetti di quel trigger.
|
||||
82
sql_tests/riattiva_pickinglist_20261001.sql
Normal file
82
sql_tests/riattiva_pickinglist_20261001.sql
Normal file
@@ -0,0 +1,82 @@
|
||||
/* Solo copia locale di test HOMESERVER. Non distribuire come patch produzione.
|
||||
Riattiva 233,234,240,241 conservando date, righe, UDC e posizioni attuali.
|
||||
Salva i valori di testata per un rollback mirato; non e' un backup dei DB.
|
||||
*/
|
||||
USE Mediseawall;
|
||||
SET NOCOUNT ON;
|
||||
SET XACT_ABORT ON;
|
||||
|
||||
IF CONVERT(nvarchar(128), SERVERPROPERTY('MachineName')) <> N'HOMESERVER'
|
||||
THROW 51000, 'Script riservato alla copia di test su HOMESERVER.', 1;
|
||||
|
||||
BEGIN TRY
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
IF OBJECT_ID('dbo.py_TestPickingListReactivation_20261001', 'U') IS NOT NULL
|
||||
THROW 51001, 'Preparazione gia eseguita: controllare il backup prima di ripetere.', 1;
|
||||
|
||||
DECLARE @Targets TABLE (ID int PRIMARY KEY, Documento int NOT NULL);
|
||||
INSERT INTO @Targets VALUES (11882,233),(11883,234),(11890,240),(11891,241);
|
||||
|
||||
IF (SELECT COUNT(*) FROM SAMA1.dbo.BAMTES b WITH (UPDLOCK,HOLDLOCK)
|
||||
JOIN @Targets t ON b.ID=t.ID AND b.NUMDOC=t.Documento
|
||||
WHERE b.ANNDOC=2026 AND b.STATO='D'
|
||||
AND b.DATDOC>CAST(GETDATE()-30 AS int)) <> 4
|
||||
THROW 51002, 'Le quattro testate non corrispondono allo scenario atteso.', 1;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM dbo.py_XMag_ViewPackingListStorico h
|
||||
JOIN dbo.XMag_GiacenzaPallet g ON g.IDCella=h.Cella
|
||||
WHERE h.Documento IN (233,234,240,241,244) AND h.Cella NOT IN (1000,9999)
|
||||
AND LTRIM(RTRIM(g.BarcodePallet)) COLLATE Latin1_General_CI_AS <>
|
||||
h.Pallet COLLATE Latin1_General_CI_AS
|
||||
) THROW 51003, 'Cella fisica con altre UDC: preparazione annullata.', 1;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT Pallet FROM dbo.py_XMag_ViewPackingListStorico
|
||||
WHERE Documento IN (233,234,240,241,244) AND Cella<>9999
|
||||
GROUP BY Pallet HAVING COUNT(DISTINCT Documento)>1
|
||||
) THROW 51004, 'Una UDC residua appartiene a piu liste candidate.', 1;
|
||||
|
||||
IF EXISTS (SELECT 1 FROM dbo.py_BarcodePickingListSkip
|
||||
WHERE Documento IN ('233','234','240','241') AND Risolto=0)
|
||||
OR EXISTS (SELECT 1 FROM dbo.py_PickingListPrelievoSequenza
|
||||
WHERE Documento IN ('233','234','240','241') AND DelDataOra IS NULL)
|
||||
OR EXISTS (SELECT 1 FROM dbo.PyPickingListReservation
|
||||
WHERE NULLIF(LTRIM(RTRIM(Documento)),'') IS NOT NULL)
|
||||
THROW 51005, 'Prenotazioni, skip o sequenze attive: verificare prima del test.', 1;
|
||||
|
||||
CREATE TABLE dbo.py_TestPickingListReactivation_20261001 (
|
||||
BamtesID int NOT NULL PRIMARY KEY,
|
||||
Anno smallint NOT NULL,
|
||||
Documento int NOT NULL,
|
||||
StatoOriginale char(1) NOT NULL,
|
||||
DataDocumentoOriginale float NOT NULL,
|
||||
ApplicataIl datetime2 NOT NULL,
|
||||
RipristinataIl datetime2 NULL
|
||||
);
|
||||
INSERT INTO dbo.py_TestPickingListReactivation_20261001
|
||||
(BamtesID,Anno,Documento,StatoOriginale,DataDocumentoOriginale,ApplicataIl)
|
||||
SELECT b.ID,b.ANNDOC,b.NUMDOC,b.STATO,b.DATDOC,SYSDATETIME()
|
||||
FROM SAMA1.dbo.BAMTES b JOIN @Targets t ON t.ID=b.ID;
|
||||
|
||||
UPDATE b SET STATO='P'
|
||||
FROM SAMA1.dbo.BAMTES b JOIN @Targets t ON t.ID=b.ID;
|
||||
IF @@ROWCOUNT<>4 THROW 51006, 'Numero di testate aggiornate inatteso.', 1;
|
||||
|
||||
IF (SELECT COUNT(DISTINCT Documento) FROM dbo.py_ViewPackingListPrelievo
|
||||
WHERE Documento IN (233,234,240,241,244)
|
||||
AND DataDocumento>CAST(GETDATE()-30 AS int))<>5
|
||||
THROW 51007, 'Le cinque liste non risultano tutte visibili. Rollback.', 1;
|
||||
|
||||
COMMIT TRANSACTION;
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
IF @@TRANCOUNT>0 ROLLBACK TRANSACTION;
|
||||
THROW;
|
||||
END CATCH;
|
||||
|
||||
SELECT Documento,COUNT(DISTINCT Pallet) AS UdcResidue
|
||||
FROM dbo.py_ViewPackingListPrelievo
|
||||
WHERE Documento IN (233,234,240,241,244)
|
||||
GROUP BY Documento ORDER BY Documento;
|
||||
54
sql_tests/ripristina_testate_pickinglist_20261001.sql
Normal file
54
sql_tests/ripristina_testate_pickinglist_20261001.sql
Normal file
@@ -0,0 +1,54 @@
|
||||
/* Ripristina SOLO lo stato delle quattro testate riattivate per i test.
|
||||
Non annulla movimentazioni effettuate durante il collaudo.
|
||||
Eseguire sullo stesso DB locale con applicazioni ferme e liste sprenotate.
|
||||
*/
|
||||
USE Mediseawall;
|
||||
SET NOCOUNT ON;
|
||||
SET XACT_ABORT ON;
|
||||
IF CONVERT(nvarchar(128),SERVERPROPERTY('MachineName'))<>N'HOMESERVER'
|
||||
THROW 51000, 'Script riservato alla copia di test su HOMESERVER.', 1;
|
||||
IF OBJECT_ID('dbo.py_TestPickingListReactivation_20261001','U') IS NULL
|
||||
THROW 51001, 'Backup delle testate non trovato.', 1;
|
||||
|
||||
BEGIN TRY
|
||||
BEGIN TRANSACTION;
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM dbo.PyPickingListReservation r
|
||||
JOIN dbo.py_TestPickingListReactivation_20261001 s
|
||||
ON r.Documento=CAST(s.Documento AS varchar(8))
|
||||
WHERE s.RipristinataIl IS NULL
|
||||
) THROW 51002, 'Sprenotare le liste di test prima del ripristino.', 1;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM dbo.py_TestPickingListReactivation_20261001 s
|
||||
LEFT JOIN SAMA1.dbo.BAMTES b WITH (UPDLOCK,HOLDLOCK) ON b.ID=s.BamtesID
|
||||
WHERE s.RipristinataIl IS NULL AND
|
||||
(b.ID IS NULL OR b.ANNDOC<>s.Anno OR b.NUMDOC<>s.Documento
|
||||
OR b.DATDOC<>s.DataDocumentoOriginale OR b.STATO IS NULL
|
||||
OR b.STATO NOT IN ('P','D'))
|
||||
) THROW 51003, 'Testate cambiate rispetto al backup: verificare manualmente.', 1;
|
||||
|
||||
-- Il trigger SAM StatoLottoRientrato modifica LOTSER.DESCR tornando in D.
|
||||
-- In presenza di lotti marcati T fermarsi prima di attivarlo.
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM dbo.py_TestPickingListReactivation_20261001 s
|
||||
JOIN SAMA1.dbo.BAMTES b ON b.ID=s.BamtesID
|
||||
JOIN SAMA1.dbo.FATRIG f ON f.IDBAM=b.ID
|
||||
JOIN SAMA1.dbo.LOTTIBF lb ON lb.IDFATRIG=f.ID
|
||||
JOIN SAMA1.dbo.LOTSER l ON l.ID=lb.IDLOTSER
|
||||
WHERE s.RipristinataIl IS NULL AND b.STATO<>'D' AND l.DESCR='T'
|
||||
) THROW 51004, 'Lotti rientrati marcati T: ripristino da valutare per il trigger SAM.', 1;
|
||||
|
||||
UPDATE b SET STATO=s.StatoOriginale
|
||||
FROM SAMA1.dbo.BAMTES b
|
||||
JOIN dbo.py_TestPickingListReactivation_20261001 s ON s.BamtesID=b.ID
|
||||
WHERE s.RipristinataIl IS NULL;
|
||||
|
||||
UPDATE dbo.py_TestPickingListReactivation_20261001
|
||||
SET RipristinataIl=SYSDATETIME() WHERE RipristinataIl IS NULL;
|
||||
COMMIT TRANSACTION;
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
IF @@TRANCOUNT>0 ROLLBACK TRANSACTION;
|
||||
THROW;
|
||||
END CATCH;
|
||||
@@ -1,65 +1,107 @@
|
||||
"""Read-only picking-list history window."""
|
||||
"""Picking-list history window and controlled residual-shipment workflow.
|
||||
|
||||
The window is mostly read-only: it summarizes historical picking lists and shows
|
||||
their UDC detail rows. The only write operation is the explicit, user-confirmed
|
||||
"Versa residui in 7G.1.1" action for lists classified as closed with residuals.
|
||||
That action delegates each UDC movement to ``move_pallet_async`` so the same
|
||||
MagazziniPallet trace used by the rest of the WMS is preserved.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timedelta
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import ttk
|
||||
from typing import Any
|
||||
|
||||
import customtkinter as ctk
|
||||
|
||||
from busy_overlay import InlineBusyOverlay
|
||||
from gestione_aree import AsyncRunner
|
||||
from gestione_scarico import move_pallet_async
|
||||
from locale_text import load_locale_catalog, text as loc_text
|
||||
from pickinglist_history_search import SQL_UDC_HISTORY, detail_request
|
||||
from ui_theme import theme_color, theme_font, theme_section, theme_value
|
||||
from ui_tables import merge_tags, style_treeview, zebra_tag
|
||||
from version_info import module_version, versioned_title
|
||||
from window_placement import place_window_fullsize_below_parent_later
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
|
||||
# Master query:
|
||||
# - reads the Python-only historical view, not the legacy C# views;
|
||||
# - groups repeated lot rows by distinct UDC/PalletKey;
|
||||
# - derives the operational status shown in the upper grid.
|
||||
SQL_STORICO_PL = """
|
||||
WITH base AS (
|
||||
SELECT *
|
||||
SELECT
|
||||
*,
|
||||
NULLIF(LTRIM(RTRIM(CAST(Pallet AS varchar(32)))), '') AS PalletKey
|
||||
FROM dbo.py_XMag_ViewPackingListStorico
|
||||
),
|
||||
agg AS (
|
||||
pallets AS (
|
||||
SELECT
|
||||
Documento,
|
||||
PalletKey,
|
||||
MAX(CASE WHEN Cella <> 9999 OR Cella IS NULL THEN 1 ELSE 0 END) AS HasResiduo,
|
||||
MAX(CASE WHEN Cella = 9999 THEN 1 ELSE 0 END) AS HasSpedito
|
||||
FROM base
|
||||
WHERE PalletKey IS NOT NULL
|
||||
GROUP BY Documento, PalletKey
|
||||
),
|
||||
meta AS (
|
||||
SELECT
|
||||
Documento,
|
||||
MAX(DataDocumento) AS DataDocumento,
|
||||
MAX(StatoDocumento) AS StatoDocumento,
|
||||
MAX(NAZIONE) AS NAZIONE,
|
||||
MAX(CodNazione) AS CodNazione,
|
||||
COUNT(DISTINCT Pallet) AS TotUDC,
|
||||
SUM(CASE WHEN Cella = 9999 THEN 1 ELSE 0 END) AS RigheSpedite,
|
||||
SUM(CASE WHEN Cella <> 9999 OR Cella IS NULL THEN 1 ELSE 0 END) AS RigheResidue,
|
||||
COUNT(*) AS RigheTotali,
|
||||
MIN(Ordinamento) AS PrimoOrdine,
|
||||
MAX(IDStato) AS IDStato
|
||||
FROM base
|
||||
GROUP BY Documento
|
||||
),
|
||||
agg AS (
|
||||
SELECT
|
||||
Documento,
|
||||
COUNT(*) AS TotUDC,
|
||||
SUM(CASE WHEN p.HasResiduo = 0 AND p.HasSpedito = 1 THEN 1 ELSE 0 END) AS RigheSpedite,
|
||||
SUM(CASE WHEN p.HasResiduo = 1 THEN 1 ELSE 0 END) AS RigheResidue
|
||||
FROM pallets p
|
||||
GROUP BY Documento
|
||||
)
|
||||
SELECT
|
||||
Documento,
|
||||
DataDocumento,
|
||||
StatoDocumento,
|
||||
NAZIONE,
|
||||
CodNazione,
|
||||
TotUDC,
|
||||
RigheResidue,
|
||||
RigheSpedite,
|
||||
RigheTotali,
|
||||
m.Documento,
|
||||
m.DataDocumento,
|
||||
m.StatoDocumento,
|
||||
m.NAZIONE,
|
||||
m.CodNazione,
|
||||
COALESCE(a.TotUDC, 0) AS TotUDC,
|
||||
COALESCE(a.RigheResidue, 0) AS RigheResidue,
|
||||
COALESCE(a.RigheSpedite, 0) AS RigheSpedite,
|
||||
m.RigheTotali,
|
||||
CASE
|
||||
WHEN StatoDocumento = 'D' THEN 'Chiusa'
|
||||
WHEN RigheResidue = 0 THEN 'Esaurita'
|
||||
WHEN RigheSpedite > 0 THEN 'In corso'
|
||||
WHEN m.StatoDocumento = 'D' AND COALESCE(a.RigheResidue, 0) > 0 THEN 'Chiusa ERP con residui'
|
||||
WHEN m.StatoDocumento = 'D' THEN 'Chiusa'
|
||||
WHEN COALESCE(a.RigheResidue, 0) = 0 THEN 'Esaurita'
|
||||
WHEN COALESCE(a.RigheSpedite, 0) > 0 THEN 'In corso'
|
||||
ELSE 'Da lavorare'
|
||||
END AS StatoOperativo,
|
||||
IDStato,
|
||||
PrimoOrdine
|
||||
FROM agg
|
||||
WHERE (:documento IS NULL OR CAST(Documento AS varchar(32)) LIKE CONCAT('%', :documento, '%'))
|
||||
ORDER BY Documento DESC;
|
||||
m.IDStato,
|
||||
m.PrimoOrdine
|
||||
FROM meta m
|
||||
LEFT JOIN agg a ON a.Documento = m.Documento
|
||||
WHERE (:documento IS NULL OR CAST(m.Documento AS varchar(32)) LIKE CONCAT('%', :documento, '%'))
|
||||
ORDER BY m.DataDocumento DESC, m.Documento DESC;
|
||||
"""
|
||||
|
||||
# Detail query:
|
||||
# - returns the ERP picking-list rows enriched with the current WMS cell;
|
||||
# - may contain multiple rows for the same UDC when the pallet contains more lots;
|
||||
# - is intentionally ordered by warehouse extraction order, then pallet.
|
||||
SQL_STORICO_PL_DETAILS = """
|
||||
SELECT
|
||||
Documento,
|
||||
@@ -135,8 +177,16 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
self._async = AsyncRunner(self)
|
||||
self._busy = InlineBusyOverlay(self, self._theme)
|
||||
self.var_documento = tk.StringVar()
|
||||
self.var_udc = tk.StringVar()
|
||||
self._master_rows: dict[str, dict[str, Any]] = {}
|
||||
self._selected_doc_id: int | None = None
|
||||
self._master_request = 0
|
||||
self._detail_request = 0
|
||||
self._selected_documento: str | None = None
|
||||
self._selected_stato_operativo: str = ""
|
||||
self._detail_rows: list[dict[str, Any]] = []
|
||||
|
||||
self.title(loc_text("history.picking.title", catalog=self._locale_catalog, default="Storico Picking List"))
|
||||
self.title(versioned_title(loc_text("history.picking.title", catalog=self._locale_catalog, default="Storico Picking List"), __name__))
|
||||
self.geometry(str(theme_value(self._theme, "window_geometry", "1200x720")))
|
||||
minsize = theme_value(self._theme, "window_minsize", [980, 560])
|
||||
self.minsize(int(minsize[0]), int(minsize[1]))
|
||||
@@ -158,28 +208,47 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
fg_color=theme_color(self._theme, "toolbar_frame_fg_color", ("#d7d7d7", "#3b3b3b")),
|
||||
)
|
||||
top.grid(row=0, column=0, sticky="ew", padx=8, pady=8)
|
||||
top.grid_columnconfigure(3, weight=1)
|
||||
top.grid_columnconfigure(6, weight=1)
|
||||
|
||||
label_font = theme_font(self._theme, "toolbar_label_font", ("Segoe UI", 10))
|
||||
entry_font = theme_font(self._theme, "entry_font", ("Segoe UI", 10))
|
||||
button_font = theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold"))
|
||||
|
||||
ctk.CTkLabel(top, text="Documento:", font=label_font).grid(row=0, column=0, sticky="w")
|
||||
ctk.CTkEntry(top, textvariable=self.var_documento, width=140, font=entry_font).grid(
|
||||
row=0, column=1, sticky="w", padx=(4, 12)
|
||||
)
|
||||
ctk.CTkLabel(top, text=loc_text("history.picking.document", catalog=self._locale_catalog),
|
||||
font=label_font).grid(row=0, column=0, sticky="w")
|
||||
self.entry_documento = ctk.CTkEntry(top, textvariable=self.var_documento, width=120, font=entry_font)
|
||||
self.entry_documento.grid(row=0, column=1, sticky="w", padx=(4, 12))
|
||||
self.entry_documento.bind("<Return>", lambda _e: self._load_master())
|
||||
ctk.CTkLabel(top, text="UDC:", font=label_font).grid(row=0, column=2, sticky="w")
|
||||
self.entry_udc = ctk.CTkEntry(top, textvariable=self.var_udc, width=110, font=entry_font)
|
||||
self.entry_udc.grid(row=0, column=3, sticky="w", padx=(4, 12))
|
||||
self.entry_udc.bind("<Return>", lambda _e: self._load_master())
|
||||
ctk.CTkButton(
|
||||
top,
|
||||
text=loc_text("history.picking.button.reload", catalog=self._locale_catalog, default="Ricarica"),
|
||||
command=self._load_master,
|
||||
font=button_font,
|
||||
).grid(
|
||||
row=0, column=2, sticky="w"
|
||||
row=0, column=4, sticky="w"
|
||||
)
|
||||
self.btn_ship_residuals = ctk.CTkButton(
|
||||
top,
|
||||
text=loc_text(
|
||||
"history.picking.button.ship_residuals",
|
||||
catalog=self._locale_catalog,
|
||||
default="Versa residui in 7G.1.1",
|
||||
),
|
||||
command=self._ship_selected_residuals,
|
||||
state="disabled",
|
||||
font=button_font,
|
||||
)
|
||||
self.btn_ship_residuals.grid(row=0, column=5, sticky="w", padx=(12, 0))
|
||||
ctk.CTkLabel(top, text=loc_text("history.picking.udc_hint", catalog=self._locale_catalog),
|
||||
font=label_font, anchor="w").grid(row=1, column=0, columnspan=7, sticky="ew", pady=(4, 0))
|
||||
|
||||
self.master_tree = self._make_tree(
|
||||
row=1,
|
||||
columns=("Documento", "Data", "StatoDoc", "NAZIONE", "TotUDC", "Residue", "Spedite", "Stato", "IDStato"),
|
||||
columns=("Documento", "Data", "StatoDoc", "NAZIONE", "TotUDC", "Residue", "Spedite", "Stato", "IDStato", "Anno"),
|
||||
widths={
|
||||
"Documento": 100,
|
||||
"Data": 110,
|
||||
@@ -190,9 +259,13 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
"Spedite": 90,
|
||||
"Stato": 120,
|
||||
"IDStato": 80,
|
||||
"Anno": 70,
|
||||
},
|
||||
)
|
||||
self.master_tree.bind("<<TreeviewSelect>>", self._on_master_select)
|
||||
self.master_tree.configure(displaycolumns=("Documento", "Anno", "Data", "StatoDoc", "NAZIONE",
|
||||
"TotUDC", "Residue", "Spedite", "Stato", "IDStato"))
|
||||
self.master_tree.heading("Anno", text=loc_text("history.picking.year", catalog=self._locale_catalog))
|
||||
|
||||
ctk.CTkLabel(
|
||||
self,
|
||||
@@ -228,8 +301,10 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
for col in columns:
|
||||
tree.heading(col, text=col)
|
||||
tree.column(col, width=widths.get(col, 100), anchor="w")
|
||||
style_treeview(tree, style_name="HistoryPicking.Treeview", rowheight=24)
|
||||
tree.tag_configure("done", background="#ECECEC")
|
||||
tree.tag_configure("active", background="#EAF7EA")
|
||||
tree.tag_configure("warning", background="#FFE3B3")
|
||||
sy = ttk.Scrollbar(wrap, orient="vertical", command=tree.yview)
|
||||
sx = ttk.Scrollbar(wrap, orient="horizontal", command=tree.xview)
|
||||
tree.configure(yscrollcommand=sy.set, xscrollcommand=sx.set)
|
||||
@@ -240,14 +315,35 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
|
||||
def _load_master(self) -> None:
|
||||
params = {"documento": str(self.var_documento.get() or "").strip() or None}
|
||||
udc = self.var_udc.get().strip()
|
||||
if udc and (not udc.isascii() or not udc.isdigit() or len(udc) > 6):
|
||||
messagebox.showwarning(loc_text("history.picking.msg.title", catalog=self._locale_catalog),
|
||||
loc_text("history.picking.udc_invalid", catalog=self._locale_catalog), parent=self)
|
||||
return
|
||||
sql = SQL_STORICO_PL
|
||||
if udc:
|
||||
sql = SQL_UDC_HISTORY
|
||||
params.update(pallet=udc, id_documento=None)
|
||||
previous_documento = self._selected_documento
|
||||
previous_id = self._selected_doc_id
|
||||
self._master_request += 1
|
||||
request = self._master_request
|
||||
self._detail_request += 1
|
||||
self._fill_master([])
|
||||
|
||||
async def _job():
|
||||
return await self.db_client.query_json(SQL_STORICO_PL, params)
|
||||
return await self.db_client.query_json(sql, params)
|
||||
|
||||
def _ok(res):
|
||||
if request != self._master_request:
|
||||
return
|
||||
self._fill_master(_rows_to_dicts(res))
|
||||
if previous_documento:
|
||||
self._restore_master_selection(previous_documento, previous_id)
|
||||
|
||||
def _err(ex):
|
||||
if request != self._master_request:
|
||||
return
|
||||
messagebox.showerror(
|
||||
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
|
||||
loc_text(
|
||||
@@ -256,6 +352,7 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
default="Errore caricamento:\n{error}",
|
||||
).format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
|
||||
self._async.run(
|
||||
@@ -273,13 +370,33 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
def _fill_master(self, rows: list[dict[str, Any]]) -> None:
|
||||
self.master_tree.delete(*self.master_tree.get_children(""))
|
||||
self.detail_tree.delete(*self.detail_tree.get_children(""))
|
||||
self._selected_documento = None
|
||||
self._selected_doc_id = None
|
||||
self._master_rows = {}
|
||||
self._selected_stato_operativo = ""
|
||||
self._detail_rows = []
|
||||
self._update_residual_button()
|
||||
for index, row in enumerate(rows):
|
||||
iid = f"doc_{row.get('Documento')}_{index}"
|
||||
self._master_rows[iid] = row
|
||||
stato = str(row.get("StatoOperativo") or "")
|
||||
tag = "done" if stato in {"Chiusa", "Esaurita"} else "active" if int(row.get("IDStato") or 0) == 1 else ""
|
||||
is_open_with_shipped = (
|
||||
str(row.get("StatoDocumento") or "") == "P"
|
||||
and int(row.get("RigheSpedite") or 0) > 0
|
||||
)
|
||||
tag = (
|
||||
"warning"
|
||||
if is_open_with_shipped
|
||||
else "done"
|
||||
if stato in {"Chiusa", "Esaurita"}
|
||||
else "active"
|
||||
if int(row.get("IDStato") or 0) == 1
|
||||
else ""
|
||||
)
|
||||
self.master_tree.insert(
|
||||
"",
|
||||
"end",
|
||||
iid=f"doc_{row.get('Documento')}_{index}",
|
||||
iid=iid,
|
||||
values=(
|
||||
row.get("Documento", ""),
|
||||
_format_date(row.get("DataDocumento", "")),
|
||||
@@ -290,26 +407,46 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
row.get("RigheSpedite", ""),
|
||||
stato,
|
||||
row.get("IDStato", ""),
|
||||
row.get("AnnoDocumento", datetime.now().year),
|
||||
),
|
||||
tags=(tag,) if tag else (),
|
||||
tags=merge_tags(zebra_tag(index), tag),
|
||||
)
|
||||
|
||||
def _on_master_select(self, _event=None) -> None:
|
||||
self._detail_request += 1
|
||||
request = self._detail_request
|
||||
selected = self.master_tree.selection()
|
||||
if not selected:
|
||||
self._selected_documento = None
|
||||
self._selected_doc_id = None
|
||||
self._selected_stato_operativo = ""
|
||||
self._detail_rows = []
|
||||
self._update_residual_button()
|
||||
return
|
||||
values = self.master_tree.item(selected[0], "values")
|
||||
if not values:
|
||||
return
|
||||
documento = values[0]
|
||||
self._selected_doc_id = self._master_rows.get(selected[0], {}).get("IDDocumento")
|
||||
self._selected_documento = str(documento)
|
||||
self._selected_stato_operativo = str(values[7] if len(values) > 7 else "")
|
||||
self._detail_rows = []
|
||||
self.detail_tree.delete(*self.detail_tree.get_children(""))
|
||||
self._update_residual_button()
|
||||
sql, params = detail_request(documento, self._selected_doc_id, SQL_STORICO_PL_DETAILS)
|
||||
|
||||
async def _job():
|
||||
return await self.db_client.query_json(SQL_STORICO_PL_DETAILS, {"documento": documento})
|
||||
return await self.db_client.query_json(sql, params)
|
||||
|
||||
def _ok(res):
|
||||
if request != self._detail_request:
|
||||
return
|
||||
self._fill_detail(_rows_to_dicts(res))
|
||||
self._update_residual_button()
|
||||
|
||||
def _err(ex):
|
||||
if request != self._detail_request:
|
||||
return
|
||||
messagebox.showerror(
|
||||
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
|
||||
loc_text(
|
||||
@@ -318,6 +455,7 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
default="Errore dettaglio:\n{error}",
|
||||
).format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
|
||||
self._async.run(
|
||||
@@ -334,8 +472,11 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
|
||||
def _fill_detail(self, rows: list[dict[str, Any]]) -> None:
|
||||
self.detail_tree.delete(*self.detail_tree.get_children(""))
|
||||
for row in rows:
|
||||
self._detail_rows = rows
|
||||
for index, row in enumerate(rows):
|
||||
is_open_shipped = str(row.get("StatoDocumento") or "") == "P" and int(row.get("Cella") or 0) == 9999
|
||||
done = str(row.get("StatoDocumento") or "") == "D" or int(row.get("Cella") or 0) == 9999
|
||||
tag = "warning" if is_open_shipped else "done" if done else ""
|
||||
self.detail_tree.insert(
|
||||
"",
|
||||
"end",
|
||||
@@ -351,9 +492,139 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
row.get("Ubicazione", ""),
|
||||
row.get("Ordinamento", ""),
|
||||
),
|
||||
tags=("done",) if done else (),
|
||||
tags=merge_tags(zebra_tag(index), tag),
|
||||
)
|
||||
|
||||
def _update_residual_button(self) -> None:
|
||||
"""Enable the bulk shipment button only for closed picking lists with residual UDCs."""
|
||||
|
||||
enabled = self._selected_stato_operativo == "Chiusa ERP con residui"
|
||||
try:
|
||||
self.btn_ship_residuals.configure(state="normal" if enabled else "disabled")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _restore_master_selection(self, documento: str, document_id: int | None = None) -> None:
|
||||
"""Re-select a document after a reload, when it is still visible."""
|
||||
|
||||
for iid in self.master_tree.get_children(""):
|
||||
values = self.master_tree.item(iid, "values")
|
||||
row = self._master_rows.get(iid, {})
|
||||
matches = (row.get("IDDocumento") == document_id if document_id is not None
|
||||
else row.get("IDDocumento") is None and values and str(values[0]) == str(documento))
|
||||
if matches:
|
||||
self.master_tree.selection_set(iid)
|
||||
self.master_tree.focus(iid)
|
||||
self.master_tree.see(iid)
|
||||
self._on_master_select()
|
||||
return
|
||||
|
||||
def _residual_pallets_from_rows(self, rows: list[dict[str, Any]]) -> list[str]:
|
||||
"""Return distinct residual UDCs that are not already in 7G.1.1."""
|
||||
|
||||
pallets: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for row in rows:
|
||||
pallet = str(row.get("Pallet") or "").strip()
|
||||
# One UDC can appear on multiple detail rows when it contains
|
||||
# multiple lots; movement must be executed once per physical UDC.
|
||||
if not pallet or pallet in seen:
|
||||
continue
|
||||
try:
|
||||
cella = int(row.get("Cella") or 0)
|
||||
except Exception:
|
||||
cella = 0
|
||||
# IDCella 9999 is the conventional 7G.1.1 shipment cell. Rows
|
||||
# already there are complete and must not receive another movement.
|
||||
if cella == 9999:
|
||||
continue
|
||||
seen.add(pallet)
|
||||
pallets.append(pallet)
|
||||
return pallets
|
||||
|
||||
def _operator_login(self) -> str:
|
||||
"""Return the user recorded on generated warehouse movements."""
|
||||
|
||||
login = str(getattr(self.session, "login", "") or "").strip()
|
||||
return login or "warehouse_ui"
|
||||
|
||||
def _ship_selected_residuals(self) -> None:
|
||||
"""Move all residual UDCs of the selected closed PL to the shipment cell 7G.1.1."""
|
||||
|
||||
if self._selected_stato_operativo != "Chiusa ERP con residui" or not self._selected_documento:
|
||||
return
|
||||
estimated = self._residual_pallets_from_rows(self._detail_rows)
|
||||
count_text = str(len(estimated)) if estimated else "le"
|
||||
if not messagebox.askyesno(
|
||||
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
|
||||
(
|
||||
f"Documento {self._selected_documento}\n\n"
|
||||
f"Verranno versate in 7G.1.1 {count_text} UDC residue della picking list chiusa.\n"
|
||||
"L'operazione registra i movimenti nello storico UDC.\n\n"
|
||||
"Procedere?"
|
||||
),
|
||||
parent=self,
|
||||
):
|
||||
return
|
||||
|
||||
documento = self._selected_documento
|
||||
document_id = self._selected_doc_id
|
||||
utente = self._operator_login()
|
||||
sql, params = detail_request(documento, document_id, SQL_STORICO_PL_DETAILS)
|
||||
|
||||
async def _job():
|
||||
# Re-read the detail inside the async job to avoid moving stale UI
|
||||
# rows if another operator or barcode client changed the list after
|
||||
# the user selected it.
|
||||
detail_res = await self.db_client.query_json(sql, params)
|
||||
detail_rows = _rows_to_dicts(detail_res)
|
||||
if document_id is not None and any(row.get("StatoDocumento") != "D" for row in detail_rows):
|
||||
raise RuntimeError("Documento non piu' definitivo. Ricaricare lo storico.")
|
||||
pallets = self._residual_pallets_from_rows(detail_rows)
|
||||
results: list[dict[str, Any]] = []
|
||||
for pallet in pallets:
|
||||
# Reuse the central movement primitive: it closes the current
|
||||
# source V row with a P movement and inserts a new V on 9999,
|
||||
# preserving the historical trail required by Storico UDC.
|
||||
result = await move_pallet_async(
|
||||
self.db_client,
|
||||
barcode_pallet=pallet,
|
||||
target_idcella=9999,
|
||||
target_barcode_cella="9000000",
|
||||
utente=utente,
|
||||
)
|
||||
results.append(result)
|
||||
return {"pallets": pallets, "results": results}
|
||||
|
||||
def _ok(res):
|
||||
pallets = res.get("pallets", []) if isinstance(res, dict) else []
|
||||
results = res.get("results", []) if isinstance(res, dict) else []
|
||||
moved = sum(1 for row in results if int(row.get("ok") or 0) == 1)
|
||||
messagebox.showinfo(
|
||||
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
|
||||
f"Documento {documento}\nUDC residue trovate: {len(pallets)}\nUDC versate in 7G.1.1: {moved}",
|
||||
parent=self,
|
||||
)
|
||||
self._selected_documento = str(documento)
|
||||
self._selected_doc_id = document_id
|
||||
self._load_master()
|
||||
|
||||
def _err(ex):
|
||||
messagebox.showerror(
|
||||
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
|
||||
f"Versamento residui fallito:\n{ex}",
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
|
||||
self._async.run(
|
||||
_job(),
|
||||
_ok,
|
||||
_err,
|
||||
busy=self._busy,
|
||||
message=f"Verso residui PL {documento} in 7G.1.1...",
|
||||
)
|
||||
|
||||
|
||||
def open_storico_pickinglist_window(parent: tk.Misc, db_client, session=None) -> tk.Misc:
|
||||
"""Open the picking-list history window."""
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import ttk
|
||||
from typing import Any
|
||||
|
||||
import customtkinter as ctk
|
||||
@@ -12,8 +13,12 @@ from busy_overlay import InlineBusyOverlay
|
||||
from gestione_aree import AsyncRunner
|
||||
from locale_text import load_locale_catalog, text as loc_text
|
||||
from ui_theme import theme_color, theme_font, theme_section, theme_value
|
||||
from ui_tables import merge_tags, style_treeview, zebra_tag
|
||||
from version_info import module_version, versioned_title
|
||||
from window_placement import place_window_fullsize_below_parent_later
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
|
||||
SQL_STORICO_UDC = """
|
||||
WITH direct AS (
|
||||
@@ -155,7 +160,7 @@ class StoricoUDCWindow(ctk.CTkToplevel):
|
||||
self._busy = InlineBusyOverlay(self, self._theme)
|
||||
self.var_udc = tk.StringVar(value=str(initial_udc or ""))
|
||||
|
||||
self.title(loc_text("history.udc.title", catalog=self._locale_catalog, default="Storico movimenti UDC"))
|
||||
self.title(versioned_title(loc_text("history.udc.title", catalog=self._locale_catalog, default="Storico movimenti UDC"), __name__))
|
||||
self.geometry(str(theme_value(self._theme, "window_geometry", "1100x720")))
|
||||
minsize = theme_value(self._theme, "window_minsize", [900, 560])
|
||||
self.minsize(int(minsize[0]), int(minsize[1]))
|
||||
@@ -218,6 +223,7 @@ class StoricoUDCWindow(ctk.CTkToplevel):
|
||||
for col in cols:
|
||||
self.tree.heading(col, text=col)
|
||||
self.tree.column(col, width=90, anchor="w")
|
||||
style_treeview(self.tree, style_name="HistoryUDC.Treeview", rowheight=24)
|
||||
self.tree.column("ID", width=70, anchor="e")
|
||||
self.tree.column("Tipo", width=55, anchor="center")
|
||||
self.tree.column("Rif", width=70, anchor="e")
|
||||
@@ -264,6 +270,7 @@ class StoricoUDCWindow(ctk.CTkToplevel):
|
||||
default="Errore ricerca:\n{error}",
|
||||
).format(error=ex),
|
||||
parent=self,
|
||||
exception=ex,
|
||||
)
|
||||
|
||||
self._async.run(
|
||||
@@ -280,7 +287,7 @@ class StoricoUDCWindow(ctk.CTkToplevel):
|
||||
value = row.get(name, "")
|
||||
return "" if value is None else value
|
||||
|
||||
for row in rows:
|
||||
for index, row in enumerate(rows):
|
||||
tipo = str(row.get("Tipo") or "")
|
||||
tag = "versamento" if tipo == "V" else "prelievo" if tipo == "P" else "spedita" if tipo == "SPED" else ""
|
||||
self.tree.insert(
|
||||
@@ -299,7 +306,7 @@ class StoricoUDCWindow(ctk.CTkToplevel):
|
||||
_value(row, "ModUtente"),
|
||||
_value(row, "ModDataOra"),
|
||||
),
|
||||
tags=(tag,) if tag else (),
|
||||
tags=merge_tags(zebra_tag(index), tag),
|
||||
)
|
||||
|
||||
|
||||
|
||||
194
tests/test_barcode_document_binding.py
Normal file
194
tests/test_barcode_document_binding.py
Normal file
@@ -0,0 +1,194 @@
|
||||
"""Document isolation regressions; no GUI, DB connection or real movements."""
|
||||
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from barcode_repository import BarcodeRepository, LegacyMoveResult
|
||||
from barcode_service import BarcodeService
|
||||
|
||||
|
||||
def row(doc, pallet, priority, order):
|
||||
return dict(Documento=doc, Pallet=pallet, IDStato=priority,
|
||||
Ordinamento=order, Cella=1101, Ubicazione="1A - 1 - a")
|
||||
|
||||
|
||||
class PickingRepositoryFake:
|
||||
def __init__(self):
|
||||
# Without a document filter the sequence would be 172, 171, 172.
|
||||
self.rows = [row("173", "600001", 1, 5), row("172", "600002", 0, 10),
|
||||
row("171", "600003", 0, 20), row("172", "600004", 0, 30)]
|
||||
self.skipped = set()
|
||||
self.locations = {r["Pallet"]: r["Cella"] for r in self.rows}
|
||||
self.released = []
|
||||
|
||||
async def fetch_next_picking(self, id_stato, documento=None):
|
||||
candidates = [r for r in self.rows if r["IDStato"] == id_stato
|
||||
and (documento is None or r["Documento"] == documento)
|
||||
and r["Pallet"] not in self.skipped]
|
||||
return min(candidates, key=lambda r: r["Ordinamento"]) if candidates else None
|
||||
|
||||
async def fetch_active_skipped_document(self, id_stato, documento=None):
|
||||
candidates = [r for r in self.rows if r["IDStato"] == id_stato
|
||||
and (documento is None or r["Documento"] == documento)
|
||||
and r["Pallet"] in self.skipped]
|
||||
return dict(Documento=candidates[0]["Documento"], SkippedCount=len(candidates)) if candidates else None
|
||||
|
||||
async def count_picking_document_remaining(self, documento):
|
||||
return len({r["Pallet"] for r in self.rows if r["Documento"] == documento})
|
||||
|
||||
async def release_picking_document(self, *, documento, operator_id):
|
||||
self.released.append(documento)
|
||||
return 0
|
||||
|
||||
async def skip_picking_pallet(self, *, documento, pallet, **kwargs):
|
||||
self.skipped.add(pallet)
|
||||
|
||||
async def fetch_picking_by_pallet(self, pallet, documento=None):
|
||||
return next((r for r in self.rows if r["Pallet"] == pallet
|
||||
and (documento is None or r["Documento"] == documento)), None)
|
||||
|
||||
async def fetch_trace_by_pallet(self, pallet):
|
||||
return dict(Lotto="LOT", Prodotto="ART", Descrizione="Test")
|
||||
|
||||
async def fetch_current_location_by_pallet(self, pallet):
|
||||
return dict(IDCella=self.locations[pallet])
|
||||
|
||||
async def fetch_open_locations_by_pallet(self, pallet):
|
||||
return [await self.fetch_current_location_by_pallet(pallet)]
|
||||
|
||||
async def fetch_closed_picking_by_pallet(self, pallet):
|
||||
return None
|
||||
|
||||
async def execute_legacy_move(self, *, barcode_pallet, barcode_cella, **kwargs):
|
||||
target = 9999 if barcode_cella == "9000000" else 1000
|
||||
self.locations[barcode_pallet] = target
|
||||
if target == 9999:
|
||||
self.rows = [r for r in self.rows if r["Pallet"] != barcode_pallet]
|
||||
return LegacyMoveResult(0, barcode_cella, barcode_pallet, int(barcode_cella))
|
||||
|
||||
|
||||
class DocumentBindingTests(unittest.IsolatedAsyncioTestCase):
|
||||
def setUp(self):
|
||||
logger = patch("barcode_service.log_runtime_event")
|
||||
logger.start()
|
||||
self.addCleanup(logger.stop)
|
||||
self.repo = PickingRepositoryFake()
|
||||
self.service = BarcodeService(self.repo, operator_id=1)
|
||||
|
||||
async def ship_current(self):
|
||||
result = await self.service.submit(
|
||||
scanned_pallet=self.service.state.expected_pallet, destination_barcode="9000000")
|
||||
self.assertTrue(result.ok)
|
||||
self.assertEqual(result.state.auto_advance_delay_ms, 3000)
|
||||
|
||||
async def test_auto_advance_never_interleaves_low_priority_documents(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
await self.ship_current()
|
||||
result = await self.service.start_priority_queue(0)
|
||||
self.assertEqual((result.state.document, result.state.expected_pallet), ("172", "600004"))
|
||||
|
||||
async def test_f2_f1_f2_stays_bound_even_if_global_order_changes(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
self.repo.rows[2]["Ordinamento"] = 1
|
||||
for _ in range(5):
|
||||
high = await self.service.start_priority_queue(1)
|
||||
self.assertEqual(high.state.document, "173")
|
||||
low = await self.service.start_priority_queue(0)
|
||||
self.assertEqual((low.state.document, low.state.expected_pallet), ("172", "600002"))
|
||||
|
||||
async def test_pause_free_move_resume_and_switch_preserve_document(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
paused = self.service.state
|
||||
self.service.begin_priority_pause(0)
|
||||
free = await self.service.submit(scanned_pallet="600003", destination_barcode="9001000")
|
||||
self.assertTrue(free.ok)
|
||||
self.service.resume_priority_state(paused)
|
||||
await self.service.start_priority_queue(1)
|
||||
low = await self.service.start_priority_queue(0)
|
||||
self.assertEqual(low.state.document, "172")
|
||||
self.assertEqual(low.state.expected_pallet, "600002")
|
||||
|
||||
async def test_skip_advances_only_within_active_document(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
await self.service.skip_current_picking_pallet()
|
||||
low = await self.service.start_priority_queue(0)
|
||||
self.assertEqual(low.state.expected_pallet, "600004")
|
||||
|
||||
async def test_only_skipped_residuals_stop_even_with_other_lists_available(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
await self.service.skip_current_picking_pallet()
|
||||
await self.service.start_priority_queue(0)
|
||||
await self.service.skip_current_picking_pallet()
|
||||
result = await self.service.start_priority_queue(0)
|
||||
self.assertEqual(result.state.mode, "manual_unload")
|
||||
self.assertIn("PL 172 sospesa", result.state.status_text)
|
||||
self.assertEqual(self.repo.released, ["172"])
|
||||
|
||||
async def test_completion_stops_before_next_document(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
await self.ship_current()
|
||||
await self.service.start_priority_queue(0)
|
||||
await self.ship_current()
|
||||
stopped = await self.service.start_priority_queue(0)
|
||||
self.assertEqual(stopped.state.mode, "manual_unload")
|
||||
self.assertIn("PL 172 terminata", stopped.state.status_text)
|
||||
self.assertEqual(stopped.state.auto_advance_delay_ms, 0)
|
||||
# A later explicit F2 can start another list, after the stop message.
|
||||
next_list = await self.service.start_priority_queue(0)
|
||||
self.assertEqual(next_list.state.document, "171")
|
||||
|
||||
async def test_priority_change_blocks_without_forgetting_previous_document(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
for r in self.repo.rows:
|
||||
if r["Documento"] == "172":
|
||||
r["IDStato"] = 1
|
||||
for _ in range(2):
|
||||
stopped = await self.service.start_priority_queue(0)
|
||||
self.assertIn("PL 172", stopped.state.status_text)
|
||||
self.assertIn("Verifica la prenotazione", stopped.state.status_text)
|
||||
for r in self.repo.rows:
|
||||
if r["Documento"] == "172":
|
||||
r["IDStato"] = 0
|
||||
resumed = await self.service.start_priority_queue(0)
|
||||
self.assertEqual(resumed.state.document, "172")
|
||||
|
||||
async def test_query_exception_keeps_document_for_retry(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
with patch.object(self.repo, "fetch_next_picking", side_effect=TimeoutError):
|
||||
with self.assertRaises(TimeoutError):
|
||||
await self.service.start_priority_queue(0)
|
||||
self.repo.rows[2]["Ordinamento"] = 1
|
||||
result = await self.service.start_priority_queue(0)
|
||||
self.assertEqual(result.state.document, "172")
|
||||
|
||||
async def test_wrong_document_from_repository_is_rejected(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
with patch.object(self.repo, "fetch_next_picking", return_value=self.repo.rows[2]):
|
||||
with self.assertRaisesRegex(RuntimeError, "Cambio inatteso documento"):
|
||||
await self.service.start_priority_queue(0)
|
||||
result = await self.service.start_priority_queue(0)
|
||||
self.assertEqual(result.state.document, "172")
|
||||
|
||||
async def test_confirmation_cannot_display_another_document_for_same_pallet(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
self.repo.rows.append(row("171", "600002", 0, 1))
|
||||
self.repo.fetch_picking_by_pallet = AsyncMock(wraps=self.repo.fetch_picking_by_pallet)
|
||||
state = await self.service._build_post_move_state(
|
||||
barcode_pallet="600002", destination_barcode="9000000",
|
||||
destination_display="7G.1.1", last_priority_state=0, auto_advance_delay_ms=3000)
|
||||
self.assertEqual(state.document, "172")
|
||||
self.repo.fetch_picking_by_pallet.assert_awaited_once_with("600002", documento="172")
|
||||
|
||||
async def test_repository_passes_document_to_all_related_queries(self):
|
||||
db = type("DB", (), {"query_json": AsyncMock(return_value={"rows": []})})()
|
||||
repo = BarcodeRepository(db)
|
||||
await repo.fetch_next_picking(0, documento="172")
|
||||
await repo.fetch_active_skipped_document(0, documento="172")
|
||||
await repo.fetch_picking_by_pallet("600002", documento="172")
|
||||
for call in db.query_json.await_args_list:
|
||||
self.assertEqual(call.args[1]["documento"], "172")
|
||||
self.assertIn(":documento", call.args[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
93
tests/test_deploy_bat.py
Normal file
93
tests/test_deploy_bat.py
Normal file
@@ -0,0 +1,93 @@
|
||||
"""Run the deployment BAT against disposable local Git repositories, never production."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
@unittest.skipUnless(os.name == "nt" and shutil.which("git"), "Windows/Git required")
|
||||
class DeployBatTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory(prefix="warehouse deploy test ")
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.base = Path(self.tmp.name)
|
||||
self.remote = self.base / "remote.git"
|
||||
self.seed = self.base / "seed"
|
||||
self.deploy = self.base / "deploy"
|
||||
self.git("init", "--bare", str(self.remote), cwd=self.base)
|
||||
self.git("init", "-b", "main", str(self.seed), cwd=self.base)
|
||||
self.git("config", "user.email", "test@example.invalid", cwd=self.seed)
|
||||
self.git("config", "user.name", "Deployment Test", cwd=self.seed)
|
||||
(self.seed / "requirements.txt").write_text("", encoding="ascii")
|
||||
(self.seed / "sample.txt").write_text("before", encoding="ascii")
|
||||
self.git("add", ".", cwd=self.seed)
|
||||
self.git("commit", "-m", "initial", cwd=self.seed)
|
||||
self.git("remote", "add", "origin", self.remote.as_posix(), cwd=self.seed)
|
||||
self.git("push", "origin", "main", cwd=self.seed)
|
||||
self.git("clone", "--branch", "main", self.remote.as_posix(), str(self.deploy), cwd=self.base)
|
||||
self.before = self.git("rev-parse", "HEAD", cwd=self.deploy).strip()
|
||||
(self.deploy / "db_connection.json").write_text('LOCAL CONFIG', encoding="ascii")
|
||||
(self.seed / "sample.txt").write_text("after", encoding="ascii")
|
||||
self.git("commit", "-am", "update", cwd=self.seed)
|
||||
self.git("push", "origin", "main", cwd=self.seed)
|
||||
self.target = self.git("rev-parse", "HEAD", cwd=self.seed).strip()
|
||||
# Only the test copy accepts the disposable local remote.
|
||||
source = (Path(__file__).resolve().parents[1] / "aggiorna_monolista.bat").read_text(encoding="ascii")
|
||||
source = source.replace("https://gitea.alessandrobonvicini.it/administrator/ware_house.git", self.remote.as_posix())
|
||||
self.script = self.base / "update test.bat"
|
||||
self.script.write_text(source, encoding="ascii")
|
||||
|
||||
def git(self, *args, cwd):
|
||||
return subprocess.check_output(["git", *args], cwd=cwd, stderr=subprocess.STDOUT, text=True)
|
||||
|
||||
def run_script(self, confirmation="S"):
|
||||
env = os.environ.copy()
|
||||
env.update(TEMP=str(self.base), TMP=str(self.base), PIP_NO_INDEX="1", PIP_DISABLE_PIP_VERSION_CHECK="1",
|
||||
GIT_TRACE2_EVENT=str(self.base / "git-trace.jsonl"))
|
||||
command = f'""{self.script}" "{self.deploy}" "{sys.executable}""'
|
||||
return subprocess.run("cmd.exe /d /s /c " + command,
|
||||
input=confirmation + "\n\n", text=True, capture_output=True, env=env, timeout=60)
|
||||
|
||||
def test_success_preserves_config_and_saves_previous_commit(self):
|
||||
self.git("config", "maintenance.auto", "true", cwd=self.deploy)
|
||||
self.git("config", "gc.auto", "1", cwd=self.deploy)
|
||||
result = self.run_script()
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn("AGGIORNAMENTO COMPLETATO", result.stdout)
|
||||
self.assertEqual(self.git("rev-parse", "HEAD", cwd=self.deploy).strip(), self.target)
|
||||
self.assertEqual((self.deploy / "db_connection.json").read_text(), "LOCAL CONFIG")
|
||||
refs = self.git("for-each-ref", "--format=%(objectname)", "refs/warehouse-backups/", cwd=self.deploy)
|
||||
self.assertIn(self.before, refs)
|
||||
import json
|
||||
trace = [json.loads(line) for line in (self.base / "git-trace.jsonl").read_text(encoding="utf-8").splitlines()]
|
||||
children = [event.get("argv", []) for event in trace if event.get("event") == "child_start"]
|
||||
self.assertFalse(any("maintenance" in args or "gc" in args for args in children), children)
|
||||
self.assertEqual(self.git("config", "maintenance.auto", cwd=self.deploy).strip(), "true")
|
||||
self.assertEqual(self.git("config", "gc.auto", cwd=self.deploy).strip(), "1")
|
||||
|
||||
def test_dirty_checkout_is_not_overwritten(self):
|
||||
(self.deploy / "sample.txt").write_text("local", encoding="ascii")
|
||||
result = self.run_script()
|
||||
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
|
||||
self.assertIn("modifiche locali", result.stdout)
|
||||
self.assertEqual((self.deploy / "sample.txt").read_text(), "local")
|
||||
self.assertEqual(self.git("rev-parse", "HEAD", cwd=self.deploy).strip(), self.before)
|
||||
|
||||
def test_cancel_does_not_update(self):
|
||||
result = self.run_script("N")
|
||||
self.assertEqual(result.returncode, 2, result.stdout + result.stderr)
|
||||
self.assertEqual(self.git("rev-parse", "HEAD", cwd=self.deploy).strip(), self.before)
|
||||
|
||||
def test_remote_database_config_blocks_update(self):
|
||||
(self.seed / "db_connection.json").write_text("REMOTE CONFIG", encoding="ascii")
|
||||
self.git("add", "db_connection.json", cwd=self.seed)
|
||||
self.git("commit", "-m", "bad config", cwd=self.seed)
|
||||
self.git("push", "origin", "main", cwd=self.seed)
|
||||
result = self.run_script()
|
||||
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
|
||||
self.assertIn("il ramo remoto contiene db_connection.json", result.stdout)
|
||||
self.assertEqual((self.deploy / "db_connection.json").read_text(), "LOCAL CONFIG")
|
||||
self.assertEqual(self.git("rev-parse", "HEAD", cwd=self.deploy).strip(), self.before)
|
||||
167
tests/test_error_dialog.py
Normal file
167
tests/test_error_dialog.py
Normal file
@@ -0,0 +1,167 @@
|
||||
"""Error report tests with real Tk widgets; no DB access or warehouse writes."""
|
||||
|
||||
import ast
|
||||
import tempfile
|
||||
import tkinter as tk
|
||||
import unittest
|
||||
from concurrent.futures import Future
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import error_dialog
|
||||
from error_dialog import ErrorDialog, build_error_report, showerror
|
||||
|
||||
|
||||
class ReportTests(unittest.TestCase):
|
||||
def test_chained_error_and_sql_are_complete(self):
|
||||
from sqlalchemy.exc import StatementError
|
||||
params = {"items": list(range(2000))}
|
||||
try:
|
||||
try:
|
||||
raise ValueError("original cause")
|
||||
except ValueError as cause:
|
||||
raise StatementError("query failed", "SELECT " + "x" * 20000, params, cause) from cause
|
||||
except StatementError as exc:
|
||||
report = build_error_report("Inventory", "User message", exc)
|
||||
self.assertIn("original cause", report)
|
||||
self.assertIn("Traceback", report)
|
||||
self.assertIn("SELECT " + "x" * 20000, report)
|
||||
self.assertIn(repr(params), report)
|
||||
self.assertIn("User message", report)
|
||||
|
||||
def test_group_has_every_exception_not_default_first_fifteen(self):
|
||||
exc = ExceptionGroup("errors", [ValueError(f"failure-{i}") for i in range(30)])
|
||||
report = build_error_report("Barcode", "Recovery", exc)
|
||||
for i in range(30):
|
||||
self.assertIn(f"failure-{i}", report)
|
||||
|
||||
def test_all_live_modules_use_shared_errors(self):
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
for path in root.glob("*.py"):
|
||||
if path.name == "error_dialog.py":
|
||||
continue
|
||||
tree = ast.parse(path.read_text(encoding="utf-8-sig"))
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.ImportFrom) and node.module in ("tkinter", "tkinter.messagebox"):
|
||||
self.assertFalse(any(n.name in ("messagebox", "showerror") for n in node.names), path.name)
|
||||
if isinstance(node, ast.Import):
|
||||
self.assertFalse(any(n.name == "tkinter.messagebox" for n in node.names), path.name)
|
||||
|
||||
def test_confirmations_and_information_remain_native(self):
|
||||
self.assertIs(error_dialog.askyesno, error_dialog.native_messagebox.askyesno)
|
||||
self.assertIs(error_dialog.showinfo, error_dialog.native_messagebox.showinfo)
|
||||
self.assertIs(error_dialog.showwarning, error_dialog.native_messagebox.showwarning)
|
||||
|
||||
def test_translations_exist(self):
|
||||
from locale_text import load_locale_catalog
|
||||
for lang in ("IT", "ENG"):
|
||||
for key in ("copy", "save", "close", "copy_failed", "save_failed", "saved"):
|
||||
self.assertTrue(load_locale_catalog()[lang]["errors." + key])
|
||||
|
||||
|
||||
class DialogTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.root = tk.Tk()
|
||||
self.root.withdraw()
|
||||
self.report = "Accento: \u00e8\n" + ("SQL " + "x" * 2000 + "\n") * 500 + "END OF REPORT"
|
||||
self.dialog = ErrorDialog(self.root, "Synthetic error", self.report)
|
||||
self.root.update()
|
||||
|
||||
def tearDown(self):
|
||||
self.root.destroy()
|
||||
|
||||
def test_full_text_read_only_and_both_scrollbars(self):
|
||||
box = self.dialog.textbox
|
||||
self.assertEqual(box.get("1.0", "end-1c"), self.report)
|
||||
self.assertEqual(box.cget("state"), "disabled")
|
||||
box.insert("end", "forbidden edit")
|
||||
self.assertEqual(box.get("1.0", "end-1c"), self.report)
|
||||
box.yview_moveto(1)
|
||||
box.xview_moveto(1)
|
||||
self.root.update()
|
||||
self.assertAlmostEqual(box.yview()[1], 1)
|
||||
self.assertGreater(box.xview()[0], 0)
|
||||
self.assertTrue(self.dialog.vertical.winfo_ismapped())
|
||||
self.assertTrue(self.dialog.horizontal.winfo_ismapped())
|
||||
|
||||
def test_copy_all_and_selection(self):
|
||||
self.dialog.copy_all()
|
||||
self.assertEqual(self.root.clipboard_get(), self.report)
|
||||
self.dialog.textbox.tag_add("sel", "1.0", "1.7")
|
||||
self.dialog.copy_selection()
|
||||
self.assertEqual(self.root.clipboard_get(), "Accento")
|
||||
self.dialog.select_all()
|
||||
self.dialog.copy_selection()
|
||||
self.assertEqual(self.root.clipboard_get(), self.report)
|
||||
|
||||
def test_save_utf8_exactly_matches_display_and_clipboard(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "error.txt"
|
||||
with patch("error_dialog.filedialog.asksaveasfilename", return_value=str(path)):
|
||||
self.dialog.save_report()
|
||||
self.assertEqual(path.read_text(encoding="utf-8"), self.report)
|
||||
|
||||
def test_save_cancel_does_nothing(self):
|
||||
with patch("error_dialog.filedialog.asksaveasfilename", return_value=""), \
|
||||
patch("error_dialog.Path.write_text") as write:
|
||||
self.dialog.save_report()
|
||||
write.assert_not_called()
|
||||
|
||||
def test_save_error_keeps_report_open(self):
|
||||
with patch("error_dialog.filedialog.asksaveasfilename", return_value="report.txt"), \
|
||||
patch("error_dialog.Path.write_text", side_effect=PermissionError("denied")):
|
||||
self.dialog.save_report()
|
||||
self.assertIn("denied", self.dialog.status.get())
|
||||
self.assertTrue(self.dialog.winfo_exists())
|
||||
self.assertEqual(self.dialog.textbox.get("1.0", "end-1c"), self.report)
|
||||
|
||||
def test_small_terminal_keeps_buttons_inside_window(self):
|
||||
self.dialog.destroy()
|
||||
with patch.object(ErrorDialog, "winfo_screenwidth", return_value=240), \
|
||||
patch.object(ErrorDialog, "winfo_screenheight", return_value=320):
|
||||
self.dialog = ErrorDialog(self.root, "Small", self.report)
|
||||
self.root.update()
|
||||
for button in self.dialog.buttons:
|
||||
self.assertLessEqual(button.winfo_rooty() + button.winfo_height(),
|
||||
self.dialog.winfo_rooty() + self.dialog.winfo_height())
|
||||
self.assertGreater(self.dialog.textbox.winfo_height(), 10)
|
||||
|
||||
def test_modal_returns_ok_and_restores_existing_grab(self):
|
||||
self.dialog.grab_set()
|
||||
captured = []
|
||||
def close_report():
|
||||
for child in self.dialog.winfo_children():
|
||||
if isinstance(child, ErrorDialog):
|
||||
captured.append(child.report)
|
||||
child.destroy()
|
||||
self.root.after(100, close_report)
|
||||
result = showerror("Test", "message", parent=self.dialog, exception=ValueError("async details"))
|
||||
self.assertEqual(result, "ok")
|
||||
self.assertIn("async details", captured[0])
|
||||
self.assertEqual(self.root.grab_current(), self.dialog)
|
||||
|
||||
|
||||
class BarcodeErrorTests(unittest.TestCase):
|
||||
def test_recovery_preserves_original_exception(self):
|
||||
from barcode_client import BarcodeClientApp
|
||||
app = Mock()
|
||||
app._pending = None
|
||||
original = RuntimeError("original SQL failure")
|
||||
BarcodeClientApp._poll_recovery_future(app, original)
|
||||
app._show_transaction_error.assert_called_once_with(original)
|
||||
|
||||
def test_failed_recovery_preserves_both_exceptions(self):
|
||||
from barcode_client import BarcodeClientApp
|
||||
app = Mock()
|
||||
app._pending = Future()
|
||||
app._pending.set_exception(ValueError("recovery failed"))
|
||||
original = RuntimeError("SQL failure")
|
||||
with patch("barcode_client.log_exception"):
|
||||
BarcodeClientApp._poll_recovery_future(app, original)
|
||||
group = app._show_transaction_error.call_args.args[0]
|
||||
self.assertIs(group.exceptions[0], original)
|
||||
self.assertEqual(str(group.exceptions[1]), "recovery failed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
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()
|
||||
176
tests/test_inventory_gui.py
Normal file
176
tests/test_inventory_gui.py
Normal file
@@ -0,0 +1,176 @@
|
||||
"""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_legend_is_bold_localized_and_independent_of_report(self):
|
||||
for component, label in self.win.legend_labels.items():
|
||||
self.assertEqual(label.cget("text"), component + ":")
|
||||
self.assertIn("bold", label.cget("font"))
|
||||
descriptions = [label.cget("text") for label in self.win.legend_descriptions]
|
||||
self.assertTrue(all(text and not text.startswith("inventory.") for text in descriptions))
|
||||
self.assertEqual(self.win.var_status.get(), self.win._t("inventory.ready"))
|
||||
self.assertNotEqual(self.win.var_status.get(), self.win._t("inventory.scope"))
|
||||
self.win._loaded(self.sample())
|
||||
self.assertEqual([label.cget("text") for label in self.win.legend_descriptions], descriptions)
|
||||
error = RuntimeError("Synthetic failure")
|
||||
with patch("inventario.messagebox.showerror") as show, patch("inventario.log_exception"):
|
||||
self.win._error(error)
|
||||
self.assertIs(show.call_args.kwargs["exception"], error)
|
||||
self.assertEqual([label.cget("text") for label in self.win.legend_descriptions], descriptions)
|
||||
|
||||
def test_legend_wraps_to_window_width(self):
|
||||
self.win._resize_legend(Mock(width=900))
|
||||
self.assertEqual(self.win.legend_descriptions[0].cget("wraplength"), 835)
|
||||
self.win._resize_legend(Mock(width=1200))
|
||||
self.assertEqual(self.win.legend_descriptions[0].cget("wraplength"), 1135)
|
||||
|
||||
def test_legend_has_both_translations(self):
|
||||
from locale_text import load_locale_catalog
|
||||
catalog = load_locale_catalog()
|
||||
for lang in ("IT", "ENG"):
|
||||
for suffix in ("ready", "formula", "legend.A", "legend.B", "legend.C", "legend.X"):
|
||||
self.assertTrue(catalog[lang]["inventory." + suffix])
|
||||
|
||||
def test_small_window_keeps_both_grids_visible(self):
|
||||
self.win.geometry("900x560+4000+0")
|
||||
self.win.deiconify()
|
||||
self.root.update_idletasks()
|
||||
self.assertGreaterEqual(self.win.tree.winfo_height(), 80)
|
||||
self.assertGreaterEqual(self.win.lot_tree.winfo_height(), 80)
|
||||
|
||||
def test_selection_populates_lot_and_container_details(self):
|
||||
self.win._loaded(self.sample())
|
||||
self.win.tree.selection_set("0")
|
||||
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()
|
||||
212
tests/test_pickinglist_history_search.py
Normal file
212
tests/test_pickinglist_history_search.py
Normal file
@@ -0,0 +1,212 @@
|
||||
"""History search regression tests. SQL tests use ONLY temporary fixtures."""
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import tkinter as tk
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
|
||||
import customtkinter as ctk
|
||||
from pickinglist_history_search import SQL_UDC_HISTORY, SQL_UDC_HISTORY_DETAILS, detail_request
|
||||
from storico_pickinglist import StoricoPickingListWindow, SQL_STORICO_PL, SQL_STORICO_PL_DETAILS
|
||||
|
||||
|
||||
class HistorySearchGuiTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.root = ctk.CTk()
|
||||
self.root.withdraw()
|
||||
self.runner = Mock()
|
||||
self.db = Mock(query_json=AsyncMock(return_value={"rows": []}))
|
||||
with patch("storico_pickinglist.AsyncRunner", return_value=self.runner):
|
||||
self.win = StoricoPickingListWindow(self.root, self.db)
|
||||
self.win.withdraw()
|
||||
self.root.update_idletasks()
|
||||
|
||||
def tearDown(self):
|
||||
for call in self.runner.run.call_args_list:
|
||||
call.args[0].close()
|
||||
for token in self.root.tk.call("after", "info"):
|
||||
try:
|
||||
self.root.tk.call("after", "cancel", token)
|
||||
except tk.TclError:
|
||||
pass
|
||||
self.win.destroy()
|
||||
self.root.destroy()
|
||||
|
||||
def rows(self):
|
||||
return [dict(Documento=244, AnnoDocumento=year, IDDocumento=identity,
|
||||
StatoDocumento="D", StatoOperativo="Chiusa ERP con residui", TotUDC=2,
|
||||
RigheResidue=1, RigheSpedite=1, IDStato=0)
|
||||
for year, identity in ((2026, 100), (2025, 200))]
|
||||
|
||||
def execute(self):
|
||||
coroutine, ok, err = self.runner.run.call_args.args
|
||||
result = asyncio.run(coroutine)
|
||||
ok(result)
|
||||
|
||||
def test_default_query_is_unchanged_and_clearing_udc_restores_it(self):
|
||||
self.win.var_udc.set("600001")
|
||||
self.win._load_master()
|
||||
self.execute()
|
||||
self.db.query_json.assert_awaited_with(SQL_UDC_HISTORY,
|
||||
{"documento": None, "pallet": "600001", "id_documento": None})
|
||||
self.win.var_udc.set("")
|
||||
self.win.var_documento.set("244")
|
||||
self.win._load_master()
|
||||
self.execute()
|
||||
self.db.query_json.assert_awaited_with(SQL_STORICO_PL, {"documento": "244"})
|
||||
|
||||
def test_both_filters_combined_and_leading_zero_preserved(self):
|
||||
self.win.var_udc.set(" 012345 ")
|
||||
self.win.var_documento.set("244")
|
||||
self.win._load_master()
|
||||
self.execute()
|
||||
self.assertEqual(self.db.query_json.await_args.args[1],
|
||||
dict(documento="244", pallet="012345", id_documento=None))
|
||||
|
||||
def test_invalid_udc_does_not_query(self):
|
||||
for value in ("ABC", "600001/123456", "6000017", "12%"):
|
||||
self.win.var_udc.set(value)
|
||||
with patch("storico_pickinglist.messagebox.showwarning") as warn:
|
||||
self.win._load_master()
|
||||
warn.assert_called_once()
|
||||
self.runner.run.assert_not_called()
|
||||
|
||||
def test_same_document_number_different_year_details_are_isolated(self):
|
||||
self.win._fill_master(self.rows())
|
||||
self.win.master_tree.selection_set("doc_244_1")
|
||||
self.win._on_master_select()
|
||||
self.execute()
|
||||
self.db.query_json.assert_awaited_with(SQL_UDC_HISTORY_DETAILS,
|
||||
dict(pallet=None, documento=None, id_documento=200))
|
||||
self.assertEqual(self.win._selected_doc_id, 200)
|
||||
self.assertEqual(self.win.master_tree.item("doc_244_1", "values")[-1], "2025")
|
||||
|
||||
def test_selection_restored_by_id_not_by_display_number(self):
|
||||
self.win._fill_master(self.rows())
|
||||
self.win._restore_master_selection("244", 200)
|
||||
self.assertEqual(self.win.master_tree.selection(), ("doc_244_1",))
|
||||
|
||||
def test_stale_detail_response_is_ignored(self):
|
||||
self.win._fill_master(self.rows())
|
||||
self.win.master_tree.selection_set("doc_244_0")
|
||||
self.win._on_master_select()
|
||||
stale = self.runner.run.call_args.args[1]
|
||||
self.win.master_tree.selection_set("doc_244_1")
|
||||
self.win._on_master_select()
|
||||
stale({"rows": [dict(Pallet="WRONG")]})
|
||||
self.assertEqual(self.win._detail_rows, [])
|
||||
|
||||
def test_residual_action_uses_exact_selected_id_and_whole_list(self):
|
||||
self.win._fill_master(self.rows())
|
||||
self.win.master_tree.selection_set("doc_244_1")
|
||||
self.win._on_master_select()
|
||||
self.db.query_json.return_value = {"rows": [dict(Pallet="600001", Cella=1000, StatoDocumento="D"),
|
||||
dict(Pallet="600002", Cella=1106, StatoDocumento="D")]}
|
||||
with patch("storico_pickinglist.messagebox.askyesno", return_value=True), \
|
||||
patch("storico_pickinglist.move_pallet_async", new_callable=AsyncMock) as move:
|
||||
move.return_value = {"ok": 1}
|
||||
self.win._ship_selected_residuals()
|
||||
asyncio.run(self.runner.run.call_args.args[0])
|
||||
self.db.query_json.assert_awaited_with(SQL_UDC_HISTORY_DETAILS,
|
||||
dict(pallet=None, documento=None, id_documento=200))
|
||||
self.assertEqual([c.kwargs["barcode_pallet"] for c in move.await_args_list], ["600001", "600002"])
|
||||
|
||||
def test_toolbar_fits_minimum_window(self):
|
||||
self.win.geometry("980x560+4000+0")
|
||||
self.win.deiconify()
|
||||
self.root.update_idletasks()
|
||||
self.assertLessEqual(self.win.btn_ship_residuals.winfo_rootx() + self.win.btn_ship_residuals.winfo_width(),
|
||||
self.win.winfo_rootx() + self.win.winfo_width())
|
||||
|
||||
def test_normal_detail_request_remains_unchanged(self):
|
||||
self.assertEqual(detail_request("244", None, SQL_STORICO_PL_DETAILS),
|
||||
(SQL_STORICO_PL_DETAILS, {"documento": "244"}))
|
||||
|
||||
|
||||
@unittest.skipUnless(os.environ.get("HISTORY_TEST_CONFIG"), "SQL fixture test is opt-in")
|
||||
class HistorySearchSQLTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
import pyodbc
|
||||
with open(os.environ["HISTORY_TEST_CONFIG"], encoding="utf-8") as handle:
|
||||
c = json.load(handle)
|
||||
self.cn = pyodbc.connect("DRIVER={" + c["driver"] + "};SERVER=" + c["server"]
|
||||
+ ";DATABASE=" + c["database"] + ";UID=" + c["user"] + ";PWD=" + c["password"]
|
||||
+ ";TrustServerCertificate=yes;", timeout=5)
|
||||
self.cn.timeout = 30
|
||||
self.addCleanup(self.cn.close)
|
||||
self.addCleanup(self.cn.rollback)
|
||||
self.cur = self.cn.cursor()
|
||||
self.definitions = {
|
||||
"BAMTES": "ID int, ANNDOC int, NUMDOC int, DATDOC int, STATO char(1), IDNAZDEST int, IDMTRASP int",
|
||||
"FATRIG": "ID int, IDBAM int, DESCR varchar(50)",
|
||||
"LOTTIBF": "IDFATRIG int, IDLOTSER int",
|
||||
"LOTSER": "ID int, NUMSER varchar(32), NUMLOT varchar(32), IDARTICO int, QTTGIAI float",
|
||||
"ARTICO": "ID int, CODICE varchar(32)",
|
||||
"NAZIONI": "ID int, CODICE varchar(8), DESCR varchar(50)",
|
||||
"MTRASP": "ID int, CODICE varchar(8)",
|
||||
"XMag_GiacenzaPallet": "BarcodePallet varchar(32), IDCella int",
|
||||
"Celle": "ID int, Ordinamento int, Corsia varchar(8), Colonna varchar(8), Fila varchar(8)",
|
||||
"PyPickingListReservation": "ID int, Documento varchar(8)",
|
||||
}
|
||||
for name, definition in self.definitions.items():
|
||||
self.cur.execute(f"CREATE TABLE #h_{name} ({definition})")
|
||||
self.cur.execute("INSERT INTO #h_Celle VALUES (1106,1,'1A','1','a'),(9999,2,'7G','1','1')")
|
||||
self.cur.execute("INSERT INTO #h_ARTICO VALUES (1,'PRODUCT')")
|
||||
self.cur.execute("INSERT INTO #h_PyPickingListReservation VALUES (1,'244')")
|
||||
for identity, year in ((100,2026),(200,2025),(300,2024),(400,2027)):
|
||||
self.cur.execute("INSERT INTO #h_BAMTES VALUES (?,?,244,?,'D',NULL,NULL)", identity, year, year*10)
|
||||
self.cur.execute("INSERT INTO #h_FATRIG VALUES (?,?,'Product')", identity, identity)
|
||||
self.cur.execute("INSERT INTO #h_LOTTIBF VALUES (?,?)", identity, 1)
|
||||
self.cur.execute("INSERT INTO #h_LOTSER VALUES (1,'600001/111111','LOT1',1,10),(2,'600002/222222','LOT2',1,20),(3,'600001/333333','LOT3',1,30)")
|
||||
self.cur.execute("INSERT INTO #h_LOTTIBF VALUES (100,2),(100,3)")
|
||||
self.cur.execute("INSERT INTO #h_XMag_GiacenzaPallet VALUES ('600001',9999),('600002',1106)")
|
||||
|
||||
def query(self, *, pallet="600001", doc=None, identity=None, details=False, year=2026):
|
||||
sql = SQL_UDC_HISTORY_DETAILS if details else SQL_UDC_HISTORY
|
||||
for name in self.definitions:
|
||||
sql = sql.replace("SAMA1.dbo." + name, "#h_" + name).replace("dbo." + name, "#h_" + name)
|
||||
self.assertNotIn("dbo.", sql)
|
||||
sql = sql.replace("YEAR(GETDATE())", str(year))
|
||||
params = dict(pallet=pallet, documento=doc, id_documento=identity)
|
||||
values = []
|
||||
def bind(match):
|
||||
values.append(params[match[1]])
|
||||
return "?"
|
||||
sql = re.sub(r":(pallet|documento|id_documento)\b", bind, sql)
|
||||
self.cur.execute(sql, values)
|
||||
names = [c[0] for c in self.cur.description]
|
||||
return [dict(zip(names, r)) for r in self.cur.fetchall()]
|
||||
|
||||
def test_two_years_exact_udc_whole_document_counts(self):
|
||||
rows = self.query()
|
||||
self.assertEqual([r["IDDocumento"] for r in rows], [100,200])
|
||||
self.assertEqual((rows[0]["TotUDC"], rows[0]["RigheResidue"], rows[0]["RigheSpedite"]), (2,1,1))
|
||||
self.assertEqual(rows[0]["StatoOperativo"], "Chiusa ERP con residui")
|
||||
self.assertEqual(rows[1]["StatoOperativo"], "Chiusa")
|
||||
self.assertEqual((rows[0]["IDStato"], rows[1]["IDStato"]), (1,0))
|
||||
|
||||
def test_detail_by_id_does_not_mix_same_number_or_filter_out_other_udcs(self):
|
||||
self.assertEqual(len(self.query(pallet=None, identity=200, details=True)), 1)
|
||||
current = self.query(pallet=None, identity=100, details=True)
|
||||
self.assertEqual(len(current), 3)
|
||||
self.assertEqual({r["Pallet"] for r in current}, {"600001", "600002"})
|
||||
|
||||
def test_exact_match_and_optional_document_filter(self):
|
||||
self.assertEqual(self.query(pallet="60000"), [])
|
||||
self.assertEqual(self.query(doc="999"), [])
|
||||
self.assertEqual(len(self.query(doc="24")), 2)
|
||||
|
||||
def test_year_window_rolls_forward(self):
|
||||
self.assertEqual([r["IDDocumento"] for r in self.query(year=2027)], [400,100])
|
||||
|
||||
def test_open_documents_and_missing_location_are_returned(self):
|
||||
self.cur.execute("UPDATE #h_BAMTES SET STATO='P' WHERE ID=200")
|
||||
self.cur.execute("DELETE FROM #h_XMag_GiacenzaPallet WHERE BarcodePallet='600001'")
|
||||
rows = self.query()
|
||||
self.assertEqual(rows[1]["StatoOperativo"], "Da lavorare")
|
||||
self.assertEqual(self.query(pallet=None, identity=200, details=True)[0]["Cella"], 1000)
|
||||
|
||||
def test_no_document_found(self):
|
||||
self.assertEqual(self.query(pallet="123456"), [])
|
||||
287
tests/test_reset_corsie.py
Normal file
287
tests/test_reset_corsie.py
Normal file
@@ -0,0 +1,287 @@
|
||||
"""Reset tests; optional SQL cases write exclusively to connection-local fixtures.
|
||||
|
||||
RESET_TEST_CONFIG=db_connection.json enables SQL Server execution. Every real
|
||||
object and the reservation procedure are replaced before the batch is run.
|
||||
"""
|
||||
import ast
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
from reset_corsie_service import SQL_RESET_PALLET, reset_pallet_async
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class ResetTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_classification_is_returned_by_transaction_not_ui(self):
|
||||
for target in (1000, 9999):
|
||||
db = unittest.mock.Mock()
|
||||
db.query_json = AsyncMock(return_value={"rows": [[target]]})
|
||||
self.assertEqual(await reset_pallet_async(db, barcode_pallet=" 600001 ",
|
||||
source_idcella=1106, utente="MAG1"), target)
|
||||
db.query_json.assert_awaited_once_with(SQL_RESET_PALLET,
|
||||
{"barcode_pallet": "600001", "source_idcella": 1106, "utente": "MAG1"},
|
||||
commit=True)
|
||||
|
||||
async def test_db_error_is_not_reported_as_success(self):
|
||||
db = unittest.mock.Mock()
|
||||
db.query_json = AsyncMock(side_effect=RuntimeError("rollback"))
|
||||
with self.assertRaisesRegex(RuntimeError, "rollback"):
|
||||
await reset_pallet_async(db, barcode_pallet="600001", source_idcella=1106, utente="MAG1")
|
||||
|
||||
def test_classification_has_no_history_date_filter(self):
|
||||
self.assertIn("bt.STATO = 'D'", SQL_RESET_PALLET)
|
||||
self.assertNotIn("ANNDOC", SQL_RESET_PALLET)
|
||||
self.assertNotIn("ViewPackingListStorico", SQL_RESET_PALLET)
|
||||
|
||||
def test_sqlalchemy_bind_parameters(self):
|
||||
from sqlalchemy import text
|
||||
self.assertEqual(set(text(SQL_RESET_PALLET).compile().params),
|
||||
{"barcode_pallet", "source_idcella", "utente"})
|
||||
|
||||
def test_confirmation_and_result_localized(self):
|
||||
catalog = json.loads((ROOT / "locale.json").read_text(encoding="utf-8"))
|
||||
for lang in ("IT", "ENG"):
|
||||
confirmation = catalog[lang]["reset.confirm"].format(udc=2, cells=1, aisle="1A")
|
||||
self.assertIn("9999", confirmation)
|
||||
self.assertIn("9001000", confirmation)
|
||||
result = catalog[lang]["reset.result"].format(aisle="1A", success=2, total=2,
|
||||
shipped=1, non_shelved=1)
|
||||
self.assertIn("1000", result)
|
||||
|
||||
def test_virtual_cells_not_resettable(self):
|
||||
module = ast.parse((ROOT / "reset_corsie.py").read_text(encoding="utf-8"))
|
||||
queries = {node.targets[0].id: ast.literal_eval(node.value) for node in module.body
|
||||
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant)
|
||||
and isinstance(node.targets[0], ast.Name) and node.targets[0].id.startswith("SQL_")}
|
||||
for query in ("SQL_CORSIE", "SQL_RIEPILOGO", "SQL_DETTAGLIO", "SQL_COUNT_RESET", "SQL_UDC_RESET"):
|
||||
self.assertIn("NOT IN (1000, 9999)", queries[query])
|
||||
|
||||
async def test_window_worker_reports_mixed_results_and_errors(self):
|
||||
# Execute the real callback body without opening a Tk window or DB.
|
||||
module = ast.parse((ROOT / "reset_corsie.py").read_text(encoding="utf-8"))
|
||||
cls = next(n for n in module.body if isinstance(n, ast.ClassDef) and n.name == "ResetCorsieWindow")
|
||||
method = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "_do_reset")
|
||||
method.decorator_list = []
|
||||
move = AsyncMock(side_effect=[9999, RuntimeError("failure"), 1000])
|
||||
messages = Mock()
|
||||
from locale_text import text
|
||||
namespace = dict(_log_sql=Mock(), _log_dataset=Mock(), _MODULE_LOGGER=Mock(),
|
||||
MODULE_LOG_PATH=Path("reset_corsie.log"), SQL_UDC_RESET="SELECT fixture",
|
||||
reset_pallet_async=move, messagebox=messages, loc_text=text, Any=object)
|
||||
exec(compile(ast.Module(body=[method], type_ignores=[]), "reset_corsie.py", "exec"), namespace)
|
||||
runner = Mock()
|
||||
fake = SimpleNamespace(_async=runner, _busy=object(),
|
||||
_locale_catalog=json.loads((ROOT / "locale.json").read_text(encoding="utf-8")),
|
||||
db=SimpleNamespace(query_json=AsyncMock(return_value={"rows": [
|
||||
["600001",1106,"1A.1.a"], ["600002",1106,"1A.1.a"], ["600003",1107,"1A.1.b"]]})),
|
||||
session=SimpleNamespace(login="MAG1"), refresh=Mock())
|
||||
namespace["_do_reset"](fake, "1A")
|
||||
coroutine, on_ok, on_error = runner.run.call_args.args
|
||||
result = await coroutine
|
||||
self.assertEqual((result["success"], result["shipped"], result["non_shelved"]), (2,1,1))
|
||||
self.assertEqual(result["failed"][0]["barcode_pallet"], "600002")
|
||||
self.assertEqual(move.await_count, 3)
|
||||
on_ok(result)
|
||||
messages.showwarning.assert_called_once()
|
||||
self.assertIn("Spedite in 9999 / 7G.1.1: 1", messages.showwarning.call_args.args[1])
|
||||
fake.refresh.assert_called_once()
|
||||
|
||||
|
||||
@unittest.skipUnless(os.environ.get("RESET_TEST_CONFIG"), "SQL fixture test is opt-in")
|
||||
class ResetSQLTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
import pyodbc
|
||||
with open(os.environ["RESET_TEST_CONFIG"], encoding="utf-8") as handle:
|
||||
c = json.load(handle)
|
||||
self.cn = pyodbc.connect("DRIVER={" + c["driver"] + "};SERVER=" + c["server"]
|
||||
+ ";DATABASE=" + c["database"] + ";UID=" + c["user"] + ";PWD=" + c["password"]
|
||||
+ ";TrustServerCertificate=yes;", timeout=5)
|
||||
self.cn.timeout = 30
|
||||
self.addCleanup(self.cn.close)
|
||||
self.addCleanup(self.cn.rollback)
|
||||
self.cur = self.cn.cursor()
|
||||
definitions = {
|
||||
"MagazziniPallet": "ID int IDENTITY PRIMARY KEY, Tipo char(1), IDRiferimento int, "
|
||||
"NumeroPallet int, Attributo varchar(32), IDMagazzino int, IDArea int, IDCella int, "
|
||||
"DataMagazzino datetime, PesoUnitario float, Tara float, InsUtente varchar(128), "
|
||||
"InsDataOra datetime, ModUtente varchar(128), ModDataOra datetime",
|
||||
"Celle": "ID int PRIMARY KEY, IDArea int, IDStato int, DelDataOra datetime, "
|
||||
"ModUtente varchar(128), ModDataOra datetime",
|
||||
"Aree": "ID int PRIMARY KEY, IDMagazzino int",
|
||||
"LOTSER": "ID int, NUMSER varchar(32)",
|
||||
"LOTTIBF": "IDLOTSER int, IDFATRIG int",
|
||||
"FATRIG": "ID int, IDBAM int",
|
||||
"BAMTES": "ID int, STATO char(1), ANNDOC int",
|
||||
}
|
||||
for name, definition in definitions.items():
|
||||
self.cur.execute(f"CREATE TABLE #reset_{name} ({definition})")
|
||||
self.cur.execute("CREATE TABLE #reset_refresh (Called int)")
|
||||
self.sql = SQL_RESET_PALLET
|
||||
for name in definitions:
|
||||
self.sql = self.sql.replace("SAMA1.dbo." + name, "#reset_" + name)
|
||||
self.sql = self.sql.replace("dbo." + name, "#reset_" + name)
|
||||
# Same V-minus-P balance and grouping as the real XMag views.
|
||||
self.stock = """SELECT mp.Attributo AS BarcodePallet, mp.IDCella
|
||||
FROM #reset_MagazziniPallet mp JOIN #reset_Celle c ON c.ID=mp.IDCella
|
||||
WHERE mp.Tipo IN ('V', 'P')
|
||||
GROUP BY mp.Attributo, mp.NumeroPallet, mp.IDMagazzino, mp.IDArea, mp.IDCella, c.IDStato
|
||||
HAVING SUM(CASE WHEN mp.Tipo='V' THEN mp.PesoUnitario ELSE -mp.PesoUnitario END)>0"""
|
||||
self.sql = self.sql.replace("dbo.XMag_GiacenzaPallet", "(" + self.stock + ") AS g")
|
||||
self.sql = self.sql.replace("EXEC dbo.py_sp_ControllaPrenotazionePackingListPalletNew;",
|
||||
"INSERT INTO #reset_refresh VALUES (1);")
|
||||
self.assertNotIn("dbo.", self.sql)
|
||||
self.cur.execute("INSERT INTO #reset_Aree VALUES (1,1)")
|
||||
self.cur.execute("INSERT INTO #reset_Celle (ID,IDArea,IDStato) VALUES (1106,1,1),(1107,1,0),(1000,1,0),(9999,1,0)")
|
||||
self.udc("600001", 1106)
|
||||
self.cn.commit()
|
||||
|
||||
def udc(self, pallet, cell):
|
||||
self.cur.execute("""INSERT INTO #reset_MagazziniPallet
|
||||
(Tipo, NumeroPallet, Attributo, IDMagazzino, IDArea, IDCella, PesoUnitario, Tara, InsUtente)
|
||||
VALUES ('V',?,?,1,1,?,1,0,'OLD')""", int(pallet), pallet, cell)
|
||||
|
||||
def document(self, state, *, pallet="600001", year=2026, identity=1):
|
||||
self.cur.execute("INSERT INTO #reset_BAMTES VALUES (?,?,?)", identity, state, year)
|
||||
self.cur.execute("INSERT INTO #reset_FATRIG VALUES (?,?)", identity, identity)
|
||||
self.cur.execute("INSERT INTO #reset_LOTTIBF VALUES (?,?)", identity, identity)
|
||||
self.cur.execute("INSERT INTO #reset_LOTSER VALUES (?,?)", identity, pallet + "/123456")
|
||||
|
||||
def run_move(self, pallet="600001", source=1106, sql=None):
|
||||
params = {"barcode_pallet": pallet, "source_idcella": source, "utente": "MAG1"}
|
||||
values = []
|
||||
def bind(match):
|
||||
values.append(params[match[1]])
|
||||
return "?"
|
||||
batch = re.sub(r":(barcode_pallet|source_idcella|utente)\b", bind, sql or self.sql)
|
||||
self.cur.execute(batch, values)
|
||||
return self.cur.fetchval()
|
||||
|
||||
def locations(self, pallet="600001"):
|
||||
return [r[0] for r in self.cur.execute("SELECT IDCella FROM (" + self.stock + ") g WHERE BarcodePallet=?", pallet)]
|
||||
|
||||
def test_definitive_document_ships_and_records_p_v(self):
|
||||
self.document("D")
|
||||
self.assertEqual(self.run_move(), 9999)
|
||||
self.assertEqual(self.locations(), [9999])
|
||||
rows = self.cur.execute("SELECT Tipo,IDCella,InsUtente,DataMagazzino FROM #reset_MagazziniPallet WHERE ID>1 ORDER BY ID").fetchall()
|
||||
self.assertEqual([(r[0], r[1], r[2]) for r in rows], [("P",1106,"MAG1"),("V",9999,"MAG1")])
|
||||
self.assertIsNotNone(rows[0][3])
|
||||
self.assertEqual(rows[0][3], rows[1][3])
|
||||
self.assertEqual(self.cur.execute("SELECT COUNT(*) FROM #reset_refresh").fetchval(), 1)
|
||||
|
||||
def test_old_definitive_document_is_not_lost_by_year_filter(self):
|
||||
self.document("D", year=2010)
|
||||
self.assertEqual(self.run_move(), 9999)
|
||||
|
||||
def test_open_document_becomes_non_shelved(self):
|
||||
self.document("P")
|
||||
self.assertEqual(self.run_move(), 1000)
|
||||
self.assertEqual(self.locations(), [1000])
|
||||
|
||||
def test_no_document_becomes_non_shelved(self):
|
||||
self.assertEqual(self.run_move(), 1000)
|
||||
|
||||
def test_closed_document_of_another_udc_does_not_ship_this_one(self):
|
||||
self.document("D", pallet="600002")
|
||||
self.assertEqual(self.run_move(), 1000)
|
||||
|
||||
def test_any_definitive_document_wins_and_multiple_lots_do_not_duplicate_move(self):
|
||||
self.document("P")
|
||||
self.document("D", identity=2)
|
||||
self.document("D", identity=3)
|
||||
self.assertEqual(self.run_move(), 9999)
|
||||
self.assertEqual(self.cur.execute("SELECT COUNT(*) FROM #reset_MagazziniPallet").fetchval(), 3)
|
||||
|
||||
def test_different_udcs_in_same_cell_have_independent_destinations(self):
|
||||
self.udc("600002", 1106)
|
||||
self.document("D")
|
||||
self.assertEqual(self.run_move(), 9999)
|
||||
self.assertEqual(self.run_move("600002"), 1000)
|
||||
self.assertEqual(self.locations(), [9999])
|
||||
self.assertEqual(self.locations("600002"), [1000])
|
||||
|
||||
def test_moved_udc_is_blocked(self):
|
||||
with self.assertRaisesRegex(Exception, "51002"):
|
||||
self.run_move(source=1107)
|
||||
self.cn.rollback()
|
||||
self.assertEqual(self.locations(), [1106])
|
||||
|
||||
def test_multiple_locations_are_blocked(self):
|
||||
self.udc("600001", 1107)
|
||||
self.cn.commit()
|
||||
with self.assertRaisesRegex(Exception, "51002"):
|
||||
self.run_move()
|
||||
self.cn.rollback()
|
||||
self.assertEqual(set(self.locations()), {1106, 1107})
|
||||
|
||||
def test_missing_target_rolls_back(self):
|
||||
self.cur.execute("DELETE FROM #reset_Celle WHERE ID=1000")
|
||||
self.cn.commit()
|
||||
with self.assertRaisesRegex(Exception, "51003"):
|
||||
self.run_move()
|
||||
self.cn.rollback()
|
||||
self.assertEqual(self.locations(), [1106])
|
||||
|
||||
def test_inconsistent_double_balance_rolls_back_instead_of_leaving_two_cells(self):
|
||||
self.udc("600001", 1106)
|
||||
self.cn.commit()
|
||||
with self.assertRaisesRegex(Exception, "51005"):
|
||||
self.run_move()
|
||||
self.cn.rollback()
|
||||
self.assertEqual(self.locations(), [1106])
|
||||
self.assertEqual(self.cur.execute("SELECT COUNT(*) FROM #reset_MagazziniPallet").fetchval(), 2)
|
||||
|
||||
def test_reservation_failure_rolls_back_both_movements(self):
|
||||
sql = self.sql.replace("INSERT INTO #reset_refresh VALUES (1);",
|
||||
"THROW 51009, 'Test refresh failure', 1;")
|
||||
with self.assertRaisesRegex(Exception, "51009"):
|
||||
self.run_move(sql=sql)
|
||||
self.cn.rollback()
|
||||
self.assertEqual(self.locations(), [1106])
|
||||
self.assertEqual(self.cur.execute("SELECT COUNT(*) FROM #reset_MagazziniPallet").fetchval(), 1)
|
||||
self.assertEqual(self.cur.execute("SELECT IDStato FROM #reset_Celle WHERE ID=1106").fetchval(), 1)
|
||||
|
||||
def test_residuals_outside_reset_aisle_are_not_changed(self):
|
||||
self.udc("600002", 1107)
|
||||
self.udc("600003", 1000)
|
||||
self.document("D")
|
||||
self.assertEqual(self.run_move(), 9999)
|
||||
self.assertEqual(self.locations("600002"), [1107])
|
||||
self.assertEqual(self.locations("600003"), [1000])
|
||||
|
||||
def test_real_history_query_closes_only_after_last_residual(self):
|
||||
# Feed the unmodified history summary SQL with connection-local rows.
|
||||
tree = ast.parse((ROOT / "storico_pickinglist.py").read_text(encoding="utf-8"))
|
||||
sql = next(ast.literal_eval(n.value) for n in tree.body if isinstance(n, ast.Assign)
|
||||
and isinstance(n.value, ast.Constant) and isinstance(n.value.value, str)
|
||||
and "AS StatoOperativo" in n.value.value)
|
||||
self.cur.execute("CREATE TABLE #reset_history (Pallet varchar(32))")
|
||||
self.cur.execute("INSERT INTO #reset_history VALUES ('600001'),('600002')")
|
||||
self.udc("600002", 1107)
|
||||
self.document("D")
|
||||
self.document("D", pallet="600002", identity=2)
|
||||
source = """(SELECT h.Pallet, 244 AS Documento, 46000 AS DataDocumento,
|
||||
'D' AS StatoDocumento, 'IT' AS NAZIONE, 'IT' AS CodNazione,
|
||||
1 AS Ordinamento, 0 AS IDStato, COALESCE(g.IDCella,1000) AS Cella
|
||||
FROM #reset_history h LEFT JOIN (""" + self.stock + """
|
||||
) g ON g.BarcodePallet=h.Pallet) AS fixture"""
|
||||
sql = sql.replace("dbo.py_XMag_ViewPackingListStorico", source).replace(":documento", "NULL")
|
||||
self.assertNotIn("dbo.", sql)
|
||||
def state():
|
||||
self.cur.execute(sql)
|
||||
return dict(zip([c[0] for c in self.cur.description], self.cur.fetchone()))["StatoOperativo"]
|
||||
self.assertEqual(state(), "Chiusa ERP con residui")
|
||||
self.run_move()
|
||||
self.assertEqual(state(), "Chiusa ERP con residui")
|
||||
self.run_move("600002", source=1107)
|
||||
self.assertEqual(state(), "Chiusa")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
28
tooltip.json
28
tooltip.json
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"default_language": "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_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.",
|
||||
@@ -8,6 +9,7 @@
|
||||
"launcher.open_history_udc": "Apre lo storico movimenti UDC per ricostruire carichi, scarichi, celle e utenti coinvolti.",
|
||||
"launcher.open_pickinglist": "Apre la gestione delle picking list per prenotare, controllare e aggiornare le liste di prelievo.",
|
||||
"launcher.open_history_pickinglist": "Apre lo storico picking list per consultare liste, stato operativo e dettaglio UDC.",
|
||||
"launcher.open_diagnostics": "Apre la diagnostica operativa con quadrature e controlli di coerenza sui dati di magazzino.",
|
||||
"launcher.arrange_windows": "Dispone in cascata le finestre aperte seguendo l'ordine dei pulsanti del launcher.",
|
||||
"launcher.exit": "Chiude l'applicazione in modo pulito terminando la sessione utente e rilasciando la connessione condivisa al database.",
|
||||
"dbconfig.heading": "Spiega che qui si inseriscono i dati minimi per permettere al programma di collegarsi al database del magazzino al primo avvio.",
|
||||
@@ -23,7 +25,7 @@
|
||||
"dbconfig.button.test": "Prova subito la connessione con i dati inseriti senza ancora salvarli definitivamente.",
|
||||
"dbconfig.button.save": "Verifica i dati, salva il file di configurazione e permette al programma di continuare l'avvio.",
|
||||
"reset_corsie.refresh": "Ricarica il riepilogo e l'elenco delle celle occupate per la corsia selezionata.",
|
||||
"reset_corsie.empty_aisle": "Scarica logicamente tutte le UDC attive della corsia selezionata verso l'ubicazione di uscita.",
|
||||
"reset_corsie.empty_aisle": "Svuota la corsia: UDC associate a documenti definitivi in 7G.1.1, tutte le altre non scaffalate. Registra prelievi e versamenti.",
|
||||
"layout.search_udc": "Cerca una UDC per barcode, cambia automaticamente corsia e porta in evidenza la cella trovata.",
|
||||
"layout.refresh": "Ricarica la corsia selezionata e aggiorna matrice, colori e statistiche.",
|
||||
"layout.export_xlsx": "Esporta la vista corrente del layout corsia in un file Excel.",
|
||||
@@ -32,9 +34,18 @@
|
||||
"multi_udc.collapse_all": "Comprime tutti i nodi dell'albero.",
|
||||
"multi_udc.preselect": "Espande la corsia selezionata e preseleziona automaticamente le UDC con causale fantasma.",
|
||||
"multi_udc.remove_ghosts": "Scarica logicamente le UDC selezionate della corsia attiva verso l'ubicazione di uscita.",
|
||||
"multi_udc.export_xlsx": "Esporta in Excel il contenuto corrente della vista UDC fantasma."
|
||||
"multi_udc.export_xlsx": "Esporta in Excel il contenuto corrente della vista UDC fantasma.",
|
||||
"picking.sequence.item": "Seleziona il gruppo. Puoi trascinarlo nell'altra area oppure usare doppio clic e pulsanti centrali.",
|
||||
"picking.sequence.add": "Aggiunge il gruppo selezionato alla fine della sequenza personalizzata.",
|
||||
"picking.sequence.remove": "Rimuove il gruppo dalla sequenza personalizzata e lo riporta tra quelli disponibili.",
|
||||
"picking.sequence.up": "Sposta il gruppo selezionato una posizione verso l'alto.",
|
||||
"picking.sequence.down": "Sposta il gruppo selezionato una posizione verso il basso.",
|
||||
"picking.sequence.save": "Salva in modo atomico la sequenza per la picking list corrente.",
|
||||
"picking.sequence.reset": "Elimina la personalizzazione e ripristina Non scaff. prima degli scaffali.",
|
||||
"picking.sequence.close": "Chiude la finestra senza effettuare altri salvataggi."
|
||||
},
|
||||
"ENG": {
|
||||
"launcher.open_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_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.",
|
||||
@@ -42,6 +53,7 @@
|
||||
"launcher.open_history_udc": "Open UDC movement history to review loads, unloads, cells and users involved.",
|
||||
"launcher.open_pickinglist": "Open picking list management to reserve, inspect and update picking lists.",
|
||||
"launcher.open_history_pickinglist": "Open picking-list history to inspect lists, operational status and UDC detail.",
|
||||
"launcher.open_diagnostics": "Open operational diagnostics with data consistency checks and warehouse quadratures.",
|
||||
"launcher.arrange_windows": "Arrange open windows in cascade order following the launcher buttons.",
|
||||
"launcher.exit": "Close the application cleanly by ending the user session and releasing the shared database connection.",
|
||||
"dbconfig.heading": "Explain that this form collects the minimum data needed to connect the program to the warehouse database on first startup.",
|
||||
@@ -57,7 +69,7 @@
|
||||
"dbconfig.button.test": "Try the connection immediately with the entered values without saving them yet.",
|
||||
"dbconfig.button.save": "Validate the connection, save the configuration file and let the program continue startup.",
|
||||
"reset_corsie.refresh": "Reload the summary and the list of occupied cells for the selected aisle.",
|
||||
"reset_corsie.empty_aisle": "Logically unload all active UDCs in the selected aisle to the outbound location.",
|
||||
"reset_corsie.empty_aisle": "Empty the aisle: UDCs associated with definitive documents go to 7G.1.1; all others become non-shelved. Records pick and put-away movements.",
|
||||
"layout.search_udc": "Search a UDC by barcode, switch aisle automatically and highlight the matching cell.",
|
||||
"layout.refresh": "Reload the selected aisle and refresh matrix, colors and statistics.",
|
||||
"layout.export_xlsx": "Export the current aisle layout view to an Excel file.",
|
||||
@@ -66,6 +78,14 @@
|
||||
"multi_udc.collapse_all": "Collapse all tree nodes.",
|
||||
"multi_udc.preselect": "Expand the selected aisle and automatically preselect UDCs classified as ghost candidates.",
|
||||
"multi_udc.remove_ghosts": "Logically unload the selected UDCs of the active aisle to the outbound location.",
|
||||
"multi_udc.export_xlsx": "Export the current ghost UDC view to Excel."
|
||||
"multi_udc.export_xlsx": "Export the current ghost UDC view to Excel.",
|
||||
"picking.sequence.item": "Select the group. You can drag it to the other area or use double-click and the center buttons.",
|
||||
"picking.sequence.add": "Append the selected group to the custom sequence.",
|
||||
"picking.sequence.remove": "Remove the group from the custom sequence and return it to the available list.",
|
||||
"picking.sequence.up": "Move the selected group one position up.",
|
||||
"picking.sequence.down": "Move the selected group one position down.",
|
||||
"picking.sequence.save": "Atomically save the sequence for the current picking list.",
|
||||
"picking.sequence.reset": "Remove the customization and restore non-shelved before racks.",
|
||||
"picking.sequence.close": "Close the window without further saves."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,9 @@ import json
|
||||
from pathlib import Path
|
||||
import tkinter as tk
|
||||
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
_TOOLTIP_FILE = Path(__file__).with_name("tooltip.json")
|
||||
|
||||
|
||||
234
udc_non_scaffalate.py
Normal file
234
udc_non_scaffalate.py
Normal file
@@ -0,0 +1,234 @@
|
||||
"""Read-only list of pallets currently parked in the non-shelved virtual cell."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import ttk
|
||||
from typing import Any
|
||||
|
||||
import customtkinter as ctk
|
||||
|
||||
from busy_overlay import InlineBusyOverlay
|
||||
from gestione_aree import AsyncRunner
|
||||
from locale_text import load_locale_catalog, text as loc_text
|
||||
from runtime_support import log_exception
|
||||
from ui_tables import style_treeview, zebra_tag
|
||||
from ui_theme import theme_color, theme_font, theme_section, theme_value
|
||||
from version_info import module_version, versioned_title
|
||||
from window_placement import place_window_fullsize_below_parent_later
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
|
||||
SQL_NON_SCAFFALATE = """
|
||||
WITH trace_rows AS (
|
||||
SELECT
|
||||
Pallet,
|
||||
MIN(Lotto) AS Lotto,
|
||||
MIN(Prodotto) AS Prodotto,
|
||||
MIN(Descrizione) AS Descrizione
|
||||
FROM dbo.vXTracciaProdotti
|
||||
GROUP BY Pallet
|
||||
)
|
||||
SELECT
|
||||
g.BarcodePallet AS UDC,
|
||||
g.IDCella,
|
||||
CONCAT(RTRIM(c.Corsia), '.', RTRIM(CAST(c.Colonna AS varchar(32))), '.', RTRIM(CAST(c.Fila AS varchar(32)))) AS Ubicazione,
|
||||
t.Lotto,
|
||||
t.Prodotto,
|
||||
t.Descrizione
|
||||
FROM dbo.XMag_GiacenzaPallet AS g
|
||||
LEFT JOIN dbo.Celle AS c
|
||||
ON c.ID = g.IDCella
|
||||
LEFT JOIN trace_rows AS t
|
||||
ON t.Pallet COLLATE Latin1_General_CI_AS =
|
||||
g.BarcodePallet COLLATE Latin1_General_CI_AS
|
||||
WHERE g.IDCella = 1000
|
||||
ORDER BY g.BarcodePallet;
|
||||
"""
|
||||
|
||||
|
||||
def _rows_to_dicts(res: dict[str, Any] | None) -> list[dict[str, Any]]:
|
||||
if not isinstance(res, dict):
|
||||
return []
|
||||
rows = res.get("rows") or []
|
||||
cols = res.get("columns") or []
|
||||
if rows and isinstance(rows[0], dict):
|
||||
return [row for row in rows if isinstance(row, dict)]
|
||||
out: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
if isinstance(row, (list, tuple)) and cols:
|
||||
out.append({str(cols[i]): row[i] for i in range(min(len(cols), len(row)))})
|
||||
return out
|
||||
|
||||
|
||||
class UDCNonScaffalateWindow(ctk.CTkToplevel):
|
||||
"""Window showing current UDCs in the conventional 5E1.1 non-shelved cell."""
|
||||
|
||||
def __init__(self, parent: tk.Widget, db_client, session=None):
|
||||
super().__init__(parent)
|
||||
self.db_client = db_client
|
||||
self.session = session
|
||||
self._theme = theme_section("non_shelved_window", theme_section("search_window", {}))
|
||||
self._locale_catalog = load_locale_catalog()
|
||||
self._async = AsyncRunner(self)
|
||||
self._busy = InlineBusyOverlay(self, self._theme)
|
||||
self._load_in_progress = False
|
||||
|
||||
self.title(versioned_title(loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"), __name__))
|
||||
self.geometry(str(theme_value(self._theme, "window_geometry", "1000x650")))
|
||||
minsize = theme_value(self._theme, "window_minsize", [820, 520])
|
||||
self.minsize(int(minsize[0]), int(minsize[1]))
|
||||
try:
|
||||
self.configure(fg_color=theme_color(self._theme, "window_fg_color", ("#efefef", "#2f2f2f")))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self._build_ui()
|
||||
self.after(250, self._load)
|
||||
|
||||
def _is_alive(self) -> bool:
|
||||
try:
|
||||
return bool(self.winfo_exists())
|
||||
except tk.TclError:
|
||||
return False
|
||||
|
||||
def _hide_busy_safe(self) -> None:
|
||||
try:
|
||||
self._busy.hide()
|
||||
except Exception as exc:
|
||||
log_exception(__name__, exc, context="hide busy UDC non scaffalate")
|
||||
|
||||
def _build_ui(self) -> None:
|
||||
self.grid_rowconfigure(1, weight=1)
|
||||
self.grid_columnconfigure(0, weight=1)
|
||||
|
||||
top = ctk.CTkFrame(
|
||||
self,
|
||||
fg_color=theme_color(self._theme, "toolbar_frame_fg_color", ("#d7d7d7", "#3b3b3b")),
|
||||
)
|
||||
top.grid(row=0, column=0, sticky="ew", padx=8, pady=8)
|
||||
top.grid_columnconfigure(2, weight=1)
|
||||
|
||||
label_font = theme_font(self._theme, "toolbar_label_font", ("Segoe UI", 10, "bold"))
|
||||
button_font = theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold"))
|
||||
ctk.CTkLabel(
|
||||
top,
|
||||
text=loc_text("non_shelved.subtitle", catalog=self._locale_catalog, default="Cella convenzionale: 5E1.1 (codice 1000 / barcode 9001000)"),
|
||||
font=label_font,
|
||||
).grid(row=0, column=0, sticky="w", padx=(0, 12))
|
||||
ctk.CTkButton(
|
||||
top,
|
||||
text=loc_text("non_shelved.refresh", catalog=self._locale_catalog, default="Aggiorna"),
|
||||
command=self._load,
|
||||
font=button_font,
|
||||
).grid(row=0, column=1, sticky="w")
|
||||
|
||||
wrap = ctk.CTkFrame(self)
|
||||
wrap.grid(row=1, column=0, sticky="nsew", padx=8, pady=(0, 8))
|
||||
wrap.grid_rowconfigure(0, weight=1)
|
||||
wrap.grid_columnconfigure(0, weight=1)
|
||||
|
||||
cols = ("UDC", "IDCella", "Ubicazione", "Lotto", "Prodotto", "Descrizione")
|
||||
self.tree = ttk.Treeview(wrap, columns=cols, show="headings")
|
||||
headings = {
|
||||
"UDC": ("UDC", 120, "w"),
|
||||
"IDCella": ("IDCella", 80, "e"),
|
||||
"Ubicazione": ("Ubicazione", 130, "w"),
|
||||
"Lotto": ("Lotto", 140, "w"),
|
||||
"Prodotto": ("Prodotto", 150, "w"),
|
||||
"Descrizione": ("Descrizione", 340, "w"),
|
||||
}
|
||||
for col in cols:
|
||||
text, width, anchor = headings[col]
|
||||
self.tree.heading(col, text=text)
|
||||
self.tree.column(col, width=width, anchor=anchor, stretch=True)
|
||||
style_treeview(
|
||||
self.tree,
|
||||
style_name="NonShelved.Treeview",
|
||||
rowheight=22,
|
||||
font=("", 9),
|
||||
heading_font=("", 9, "bold"),
|
||||
)
|
||||
|
||||
sy = ttk.Scrollbar(wrap, orient="vertical", command=self.tree.yview)
|
||||
sx = ttk.Scrollbar(wrap, orient="horizontal", command=self.tree.xview)
|
||||
self.tree.configure(yscrollcommand=sy.set, xscrollcommand=sx.set)
|
||||
self.tree.grid(row=0, column=0, sticky="nsew")
|
||||
sy.grid(row=0, column=1, sticky="ns")
|
||||
sx.grid(row=1, column=0, sticky="ew")
|
||||
|
||||
def _load(self) -> None:
|
||||
if self._load_in_progress or not self._is_alive():
|
||||
return
|
||||
|
||||
async def job():
|
||||
return await self.db_client.query_json(SQL_NON_SCAFFALATE, as_dict_rows=True)
|
||||
|
||||
self._load_in_progress = True
|
||||
try:
|
||||
self._busy.show(loc_text("non_shelved.busy", catalog=self._locale_catalog, default="Carico UDC non scaffalate..."))
|
||||
self._async.run(job(), self._on_loaded, self._on_error)
|
||||
except Exception as exc:
|
||||
self._load_in_progress = False
|
||||
self._hide_busy_safe()
|
||||
log_exception(__name__, exc, context="avvio caricamento UDC non scaffalate")
|
||||
messagebox.showerror(
|
||||
loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"),
|
||||
str(exc),
|
||||
parent=self if self._is_alive() else None,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
def _on_loaded(self, res: dict[str, Any] | None) -> None:
|
||||
self._load_in_progress = False
|
||||
self._hide_busy_safe()
|
||||
if not self._is_alive():
|
||||
return
|
||||
try:
|
||||
rows = _rows_to_dicts(res)
|
||||
self.tree.delete(*self.tree.get_children(""))
|
||||
for index, row in enumerate(rows):
|
||||
self.tree.insert(
|
||||
"",
|
||||
"end",
|
||||
values=(
|
||||
row.get("UDC") or "",
|
||||
row.get("IDCella") or "",
|
||||
row.get("Ubicazione") or "",
|
||||
row.get("Lotto") or "",
|
||||
row.get("Prodotto") or "",
|
||||
row.get("Descrizione") or "",
|
||||
),
|
||||
tags=(zebra_tag(index),),
|
||||
)
|
||||
except Exception as exc:
|
||||
log_exception(__name__, exc, context="render UDC non scaffalate")
|
||||
messagebox.showerror(
|
||||
loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"),
|
||||
str(exc),
|
||||
parent=self,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
def _on_error(self, exc: BaseException) -> None:
|
||||
self._load_in_progress = False
|
||||
self._hide_busy_safe()
|
||||
log_exception(__name__, exc, context="query UDC non scaffalate")
|
||||
if not self._is_alive():
|
||||
return
|
||||
messagebox.showerror(
|
||||
loc_text("non_shelved.title", catalog=self._locale_catalog, default="UDC non scaffalate"),
|
||||
str(exc),
|
||||
parent=self,
|
||||
exception=exc,
|
||||
)
|
||||
|
||||
|
||||
def open_udc_non_scaffalate_window(parent: tk.Misc, db_client, session=None) -> tk.Misc:
|
||||
"""Open the non-shelved UDC window."""
|
||||
|
||||
win = UDCNonScaffalateWindow(parent, db_client, session=session)
|
||||
place_window_fullsize_below_parent_later(parent, win)
|
||||
return win
|
||||
108
ui_tables.py
Normal file
108
ui_tables.py
Normal file
@@ -0,0 +1,108 @@
|
||||
"""Shared visual helpers for data grids."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tkinter import ttk
|
||||
from typing import Any
|
||||
|
||||
TABLE_ROW_EVEN = "#FFFFFF"
|
||||
TABLE_ROW_ODD = "#F4F6F8"
|
||||
TABLE_HEADER_BG = "#D1D5DB"
|
||||
TABLE_HEADER_FG = "#111827"
|
||||
TABLE_SELECTED_BG = "#DCEBFF"
|
||||
TABLE_SELECTED_FG = "#111827"
|
||||
|
||||
|
||||
def style_treeview(
|
||||
tree: ttk.Treeview,
|
||||
*,
|
||||
style_name: str,
|
||||
rowheight: int = 24,
|
||||
font: Any = ("Segoe UI", 9),
|
||||
heading_font: Any = ("Segoe UI", 9, "bold"),
|
||||
) -> ttk.Style:
|
||||
"""Apply a consistent high-contrast header and zebra-ready style."""
|
||||
|
||||
style = ttk.Style(tree)
|
||||
style.configure(style_name, rowheight=rowheight, font=font)
|
||||
style.configure(
|
||||
f"{style_name}.Heading",
|
||||
font=heading_font,
|
||||
background=TABLE_HEADER_BG,
|
||||
foreground=TABLE_HEADER_FG,
|
||||
relief="flat",
|
||||
)
|
||||
style.map(
|
||||
f"{style_name}.Heading",
|
||||
background=[("active", TABLE_HEADER_BG), ("pressed", TABLE_HEADER_BG)],
|
||||
foreground=[("active", TABLE_HEADER_FG), ("pressed", TABLE_HEADER_FG)],
|
||||
)
|
||||
style.map(
|
||||
style_name,
|
||||
background=[("selected", TABLE_SELECTED_BG)],
|
||||
foreground=[("selected", TABLE_SELECTED_FG)],
|
||||
)
|
||||
tree.configure(style=style_name)
|
||||
configure_treeview_zebra_tags(tree)
|
||||
return style
|
||||
|
||||
|
||||
def configure_treeview_zebra_tags(tree: ttk.Treeview) -> None:
|
||||
"""Register alternating row color tags on a Treeview."""
|
||||
|
||||
tree.tag_configure("even", background=TABLE_ROW_EVEN)
|
||||
tree.tag_configure("odd", background=TABLE_ROW_ODD)
|
||||
|
||||
|
||||
def zebra_tag(index: int) -> str:
|
||||
"""Return the alternating row tag for the given zero-based index."""
|
||||
|
||||
return "even" if index % 2 == 0 else "odd"
|
||||
|
||||
|
||||
def merge_tags(*tags: str) -> tuple[str, ...]:
|
||||
"""Return non-empty tags preserving order."""
|
||||
|
||||
return tuple(tag for tag in tags if tag)
|
||||
|
||||
|
||||
def apply_tksheet_visual_style(sheet: Any) -> None:
|
||||
"""Apply best-effort header contrast and zebra rows to a tksheet widget."""
|
||||
|
||||
try:
|
||||
sheet.set_options(
|
||||
header_bg=TABLE_HEADER_BG,
|
||||
header_fg=TABLE_HEADER_FG,
|
||||
header_selected_cells_bg=TABLE_HEADER_BG,
|
||||
header_selected_cells_fg=TABLE_HEADER_FG,
|
||||
table_bg=TABLE_ROW_EVEN,
|
||||
table_fg="#111827",
|
||||
selected_rows_bg=TABLE_SELECTED_BG,
|
||||
selected_rows_fg=TABLE_SELECTED_FG,
|
||||
selected_cells_bg=TABLE_SELECTED_BG,
|
||||
selected_cells_fg=TABLE_SELECTED_FG,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def apply_tksheet_zebra(sheet: Any, row_count: int) -> None:
|
||||
"""Apply alternating row colors to a tksheet widget when supported."""
|
||||
|
||||
try:
|
||||
sheet.dehighlight_rows(redraw=False)
|
||||
except Exception:
|
||||
pass
|
||||
for row_index in range(row_count):
|
||||
try:
|
||||
sheet.highlight_rows(
|
||||
rows=[row_index],
|
||||
bg=TABLE_ROW_EVEN if row_index % 2 == 0 else TABLE_ROW_ODD,
|
||||
redraw=False,
|
||||
)
|
||||
except Exception:
|
||||
break
|
||||
try:
|
||||
sheet.redraw()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -1,4 +1,24 @@
|
||||
{
|
||||
"error_dialog": {
|
||||
"width": 900,
|
||||
"height": 620,
|
||||
"background": "#ffffff",
|
||||
"foreground": "#202020",
|
||||
"font": {"family": "Consolas", "size": 10}
|
||||
},
|
||||
"inventory_window": {
|
||||
"legend_fg_color": ["#f8fafb", "#262b30"],
|
||||
"legend_text_color": ["#202830", "#f1f3f5"],
|
||||
"legend_font": {"family": "Segoe UI", "size": 13},
|
||||
"legend_heading_font": {"family": "Segoe UI", "size": 13, "weight": "bold"},
|
||||
"window_geometry": "1200x720",
|
||||
"window_minsize": [900, 560],
|
||||
"window_fg_color": ["#efefef", "#2f2f2f"],
|
||||
"toolbar_frame_fg_color": ["#d7d7d7", "#3b3b3b"],
|
||||
"toolbar_button_font": ["Segoe UI", 11, "bold"],
|
||||
"difference_color": "#9b3900",
|
||||
"unknown_color": "#aa0000"
|
||||
},
|
||||
"global": {
|
||||
"window_bg": ["#f1f1f1", "#2b2b2b"],
|
||||
"panel_bg": ["#d9d9d9", "#3a3a3a"],
|
||||
@@ -164,7 +184,7 @@
|
||||
}
|
||||
},
|
||||
"login_window": {
|
||||
"window_geometry": "165x155+0+0",
|
||||
"window_geometry": "165x170+0+0",
|
||||
"overlay_cover_fg_color": ["#d9d9d9", "#4a4a4a"],
|
||||
"overlay_panel_fg_color": ["#f2f2f2", "#353535"],
|
||||
"overlay_panel_corner_radius": 10,
|
||||
@@ -301,6 +321,29 @@
|
||||
"overlay_label_padding": [18, 14, 18, 8],
|
||||
"overlay_progress_padding": [18, 0, 18, 14]
|
||||
},
|
||||
"picking_sequence_window": {
|
||||
"window_fg_color": ["#eef2f3", "#2f2f2f"],
|
||||
"list_fg_color": ["#f8fafc", "#363636"],
|
||||
"item_fg_color": "#2ebf74",
|
||||
"secondary_text_color": "#4b5563",
|
||||
"reset_button_fg_color": "#6b7280",
|
||||
"title_font": {
|
||||
"family": "Segoe UI",
|
||||
"size": 16,
|
||||
"weight": "bold"
|
||||
},
|
||||
"overlay_cover_fg_color": ["#d9d9d9", "#4a4a4a"],
|
||||
"overlay_panel_fg_color": ["#f2f2f2", "#353535"],
|
||||
"overlay_panel_corner_radius": 10,
|
||||
"overlay_label_font": {
|
||||
"family": "Segoe UI",
|
||||
"size": 11,
|
||||
"weight": "bold"
|
||||
},
|
||||
"overlay_progress_width": 220,
|
||||
"overlay_label_padding": [18, 14, 18, 8],
|
||||
"overlay_progress_padding": [18, 0, 18, 14]
|
||||
},
|
||||
"history_picking_window": {
|
||||
"window_geometry": "1200x720",
|
||||
"window_minsize": [980, 560],
|
||||
|
||||
@@ -12,6 +12,10 @@ from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
THEME_PATH = Path(__file__).with_name("ui_theme.json")
|
||||
|
||||
|
||||
|
||||
@@ -6,6 +6,9 @@ from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from typing import FrozenSet
|
||||
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
ALL_ACTIONS: FrozenSet[str] = frozenset(
|
||||
{
|
||||
@@ -13,15 +16,21 @@ ALL_ACTIONS: FrozenSet[str] = frozenset(
|
||||
"launcher.open_layout",
|
||||
"launcher.open_multi_udc",
|
||||
"launcher.open_search",
|
||||
"launcher.open_non_shelved",
|
||||
"launcher.open_history_udc",
|
||||
"launcher.open_pickinglist",
|
||||
"launcher.open_history_pickinglist",
|
||||
"launcher.open_diagnostics",
|
||||
"launcher.open_inventory",
|
||||
"launcher.arrange_windows",
|
||||
"launcher.exit",
|
||||
"reset_corsie.view",
|
||||
"search.view",
|
||||
"non_shelved.view",
|
||||
"history_udc.view",
|
||||
"history_pickinglist.view",
|
||||
"diagnostics.view",
|
||||
"inventory.view",
|
||||
"multi_udc.view",
|
||||
"layout.view",
|
||||
"layout.carico",
|
||||
@@ -33,6 +42,7 @@ ALL_ACTIONS: FrozenSet[str] = frozenset(
|
||||
"pickinglist.view",
|
||||
"pickinglist.prenota",
|
||||
"pickinglist.sprenota",
|
||||
"pickinglist.sequence",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
80
version_info.py
Normal file
80
version_info.py
Normal file
@@ -0,0 +1,80 @@
|
||||
"""Application and module version registry for Warehouse/FlyWMS bridge."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
APP_VERSION = "1.0.0"
|
||||
|
||||
MODULE_VERSIONS: dict[str, str] = {
|
||||
"app": APP_VERSION,
|
||||
"error_dialog": "1.0.0",
|
||||
"async_loop_singleton": "1.0.0",
|
||||
"async_msssql_query": "1.0.1",
|
||||
"audit_log": "1.0.0",
|
||||
"main": "1.0.5",
|
||||
"inventario": "1.1.2",
|
||||
"inventory_service": "1.1.0",
|
||||
"barcode_client": "1.0.28",
|
||||
"barcode_repository": "1.0.14",
|
||||
"barcode_service": "1.0.25",
|
||||
"busy_overlay": "1.0.0",
|
||||
"db_config": "1.0.1",
|
||||
"diagnostica": "1.0.5",
|
||||
"gestione_aree": "1.0.1",
|
||||
"gestione_layout": "1.0.3",
|
||||
"gestione_pickinglist": "1.0.7",
|
||||
"gestione_scarico": "1.0.9",
|
||||
"locale_text": "1.0.0",
|
||||
"login_window": "1.0.1",
|
||||
"prenota_sprenota_sql": "1.0.1",
|
||||
"pickinglist_sequence": "1.0.1",
|
||||
"reset_corsie": "1.0.2",
|
||||
"reset_corsie_service": "1.0.0",
|
||||
"runtime_support": "1.0.2",
|
||||
"search_pallets": "1.0.1",
|
||||
"storico_pickinglist": "1.0.6",
|
||||
"pickinglist_history_search": "1.0.0",
|
||||
"storico_udc": "1.0.1",
|
||||
"tooltips": "1.0.0",
|
||||
"udc_non_scaffalate": "1.0.2",
|
||||
"ui_theme": "1.0.0",
|
||||
"user_session": "1.0.3",
|
||||
"view_celle_multi_udc": "1.0.1",
|
||||
"window_placement": "1.0.0",
|
||||
}
|
||||
|
||||
|
||||
def module_key(module_name: str) -> str:
|
||||
"""Return the stable registry key for a module name or path."""
|
||||
|
||||
name = str(module_name or "").replace("\\", "/")
|
||||
stem = Path(name).stem if "/" in name or "." not in name else name.rsplit(".", 1)[-1]
|
||||
return stem or "app"
|
||||
|
||||
|
||||
def module_version(module_name: str | None = None) -> str:
|
||||
"""Return the version for a module, falling back to the app version."""
|
||||
|
||||
if not module_name:
|
||||
return APP_VERSION
|
||||
return MODULE_VERSIONS.get(module_key(module_name), APP_VERSION)
|
||||
|
||||
|
||||
def version_label(module_name: str | None = None) -> str:
|
||||
"""Return the standard visual label used in window titles."""
|
||||
|
||||
return f"ver. {module_version(module_name)}"
|
||||
|
||||
|
||||
def versioned_title(title: str, module_name: str | None = None) -> str:
|
||||
"""Append the standard version label to a window title."""
|
||||
|
||||
clean_title = str(title or "").strip()
|
||||
label = version_label(module_name)
|
||||
if not clean_title:
|
||||
return label
|
||||
if label.lower() in clean_title.lower():
|
||||
return clean_title
|
||||
return f"{clean_title} - {label}"
|
||||
@@ -9,7 +9,8 @@ import tkinter as tk
|
||||
from datetime import datetime
|
||||
from functools import wraps
|
||||
from pathlib import Path
|
||||
from tkinter import filedialog, messagebox, ttk
|
||||
import error_dialog as messagebox
|
||||
from tkinter import filedialog, ttk
|
||||
from typing import Any
|
||||
|
||||
import customtkinter as ctk
|
||||
@@ -22,8 +23,12 @@ from gestione_scarico import move_pallet_async
|
||||
from locale_text import load_locale_catalog, text as loc_text
|
||||
from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text
|
||||
from ui_theme import theme_color, theme_font, theme_section, theme_value
|
||||
from ui_tables import merge_tags, style_treeview, zebra_tag
|
||||
from version_info import module_version, versioned_title
|
||||
from window_placement import place_window_fullsize_below_parent_later
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
try:
|
||||
from loguru import logger
|
||||
except Exception: # pragma: no cover - fallback used only when Loguru is not available
|
||||
@@ -436,7 +441,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
self._theme = theme_section("multi_udc", {})
|
||||
self._locale_catalog = load_locale_catalog()
|
||||
self._tooltip_catalog = load_tooltip_catalog()
|
||||
self.title(loc_text("multi.title", catalog=self._locale_catalog, default="Celle con piu' pallet"))
|
||||
self.title(versioned_title(loc_text("multi.title", catalog=self._locale_catalog, default="Celle con piu' pallet"), __name__))
|
||||
self.session = session
|
||||
self.geometry(str(theme_value(self._theme, "window_geometry", "1100x700")))
|
||||
minsize = theme_value(self._theme, "window_minsize", [900, 550])
|
||||
@@ -507,6 +512,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
self.tree.column("col2", width=250, anchor="w")
|
||||
self.tree.column("col3", width=120, anchor="w")
|
||||
self.tree.column("col4", width=260, anchor="w")
|
||||
style_treeview(self.tree, style_name="MultiUDC.Treeview", rowheight=24)
|
||||
y = ttk.Scrollbar(frame, orient="vertical", command=self.tree.yview)
|
||||
x = ttk.Scrollbar(frame, orient="horizontal", command=self.tree.xview)
|
||||
self.tree.configure(yscrollcommand=y.set, xscrollcommand=x.set)
|
||||
@@ -542,6 +548,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
):
|
||||
self.sum_tbl.heading(key, text=title)
|
||||
self.sum_tbl.column(key, width=width, anchor=anchor)
|
||||
style_treeview(self.sum_tbl, style_name="MultiUDCSummary.Treeview", rowheight=24)
|
||||
y2 = ttk.Scrollbar(inner, orient="vertical", command=self.sum_tbl.yview)
|
||||
x2 = ttk.Scrollbar(inner, orient="horizontal", command=self.sum_tbl.xview)
|
||||
self.sum_tbl.configure(yscrollcommand=y2.set, xscrollcommand=x2.set)
|
||||
@@ -645,7 +652,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
|
||||
def _err(ex):
|
||||
_MODULE_LOGGER.exception(f"Errore caricamento corsie UDC fantasma: {ex}")
|
||||
messagebox.showerror("Errore", str(ex), parent=self)
|
||||
messagebox.showerror("Errore", str(ex), parent=self, exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_q(self.db),
|
||||
@@ -660,7 +667,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
"""Populate root tree nodes after the aisle query completes."""
|
||||
rows = _json_obj(res).get("rows", [])
|
||||
_log_dataset("multi_udc_corsie", rows)
|
||||
for row in rows:
|
||||
for index, row in enumerate(rows):
|
||||
corsia = row.get("Corsia")
|
||||
if not corsia:
|
||||
continue
|
||||
@@ -672,7 +679,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
text=self._format_corsia_text(corsia),
|
||||
values=("", "", ""),
|
||||
open=False,
|
||||
tags=("corsia",),
|
||||
tags=merge_tags(zebra_tag(index), "corsia"),
|
||||
)
|
||||
self.tree.insert(node_id, "end", iid=f"{node_id}::lazy", text="...", values=("", "", ""))
|
||||
|
||||
@@ -706,7 +713,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
|
||||
def _err(ex):
|
||||
_MODULE_LOGGER.exception(f"Errore caricamento celle duplicate corsia={corsia}: {ex}")
|
||||
messagebox.showerror("Errore", str(ex), parent=self)
|
||||
messagebox.showerror("Errore", str(ex), parent=self, exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_q(self.db),
|
||||
@@ -724,7 +731,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
if not rows:
|
||||
self.tree.insert(parent_iid, "end", text="(nessuna cella con >1 UDC)", values=("", "", ""))
|
||||
return
|
||||
for row in rows:
|
||||
for index, row in enumerate(rows):
|
||||
idc = row["IDCella"]
|
||||
ubi = row["Ubicazione"]
|
||||
corsia = row.get("Corsia")
|
||||
@@ -741,7 +748,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
text=label,
|
||||
values=(f"IDCella {idc}", "", ""),
|
||||
open=False,
|
||||
tags=("cella", f"corsia:{corsia}"),
|
||||
tags=merge_tags(zebra_tag(index), "cella", f"corsia:{corsia}"),
|
||||
)
|
||||
if not any(child.endswith("::lazy") for child in self.tree.get_children(node_id)):
|
||||
self.tree.insert(node_id, "end", iid=f"{node_id}::lazy", text="...", values=("", "", ""))
|
||||
@@ -756,7 +763,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
|
||||
def _err(ex):
|
||||
_MODULE_LOGGER.exception(f"Errore caricamento pallet cella idcella={idcella}: {ex}")
|
||||
messagebox.showerror("Errore", str(ex), parent=self)
|
||||
messagebox.showerror("Errore", str(ex), parent=self, exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_q(self.db),
|
||||
@@ -781,7 +788,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
idcella_txt = self.tree.item(parent_iid, "values")[0]
|
||||
idcella_num = int(idcella_txt.split()[-1]) if idcella_txt else None
|
||||
|
||||
for row in rows:
|
||||
for index, row in enumerate(rows):
|
||||
pallet = row.get("Pallet", "")
|
||||
desc = row.get("Descrizione", "")
|
||||
lotto = row.get("Lotto", "")
|
||||
@@ -813,7 +820,13 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
iid=leaf_id,
|
||||
text=self._format_pallet_text(str(pallet), leaf_id in self.selected_udc_keys),
|
||||
values=(desc, lotto, causale),
|
||||
tags=("pallet", f"corsia:{corsia_val}", f"ubicazione:{cella_ubi}", f"idcella:{idcella_num}"),
|
||||
tags=merge_tags(
|
||||
zebra_tag(index),
|
||||
"pallet",
|
||||
f"corsia:{corsia_val}",
|
||||
f"ubicazione:{cella_ubi}",
|
||||
f"idcella:{idcella_num}",
|
||||
),
|
||||
)
|
||||
|
||||
@_log_call()
|
||||
@@ -877,7 +890,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
def _err(ex):
|
||||
self._busy.hide()
|
||||
_MODULE_LOGGER.exception(f"Errore preselezione fantasmi corsia={corsia}: {ex}")
|
||||
messagebox.showerror("Errore", str(ex), parent=self)
|
||||
messagebox.showerror("Errore", str(ex), parent=self, exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_q(self.db),
|
||||
@@ -950,7 +963,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
def _err(ex):
|
||||
self._busy.hide()
|
||||
_MODULE_LOGGER.exception(f"Errore bonifica fantasmi corsia={corsia}: {ex}")
|
||||
messagebox.showerror("Errore bonifica", str(ex), parent=self)
|
||||
messagebox.showerror("Errore bonifica", str(ex), parent=self, exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_q(self.db),
|
||||
@@ -970,7 +983,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
|
||||
def _err(ex):
|
||||
_MODULE_LOGGER.exception(f"Errore caricamento riepilogo UDC fantasma: {ex}")
|
||||
messagebox.showerror("Errore", str(ex), parent=self)
|
||||
messagebox.showerror("Errore", str(ex), parent=self, exception=ex)
|
||||
|
||||
self.runner.run(
|
||||
_q(self.db),
|
||||
@@ -987,11 +1000,12 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
_log_dataset("multi_udc_riepilogo", rows)
|
||||
for item in self.sum_tbl.get_children():
|
||||
self.sum_tbl.delete(item)
|
||||
for row in rows:
|
||||
for index, row in enumerate(rows):
|
||||
self.sum_tbl.insert(
|
||||
"",
|
||||
"end",
|
||||
values=(row.get("Corsia"), row.get("TotCelle", 0), row.get("CelleMultiple", 0), f"{row.get('Percentuale', 0):.2f}"),
|
||||
tags=(zebra_tag(index),),
|
||||
)
|
||||
|
||||
def expand_all(self):
|
||||
@@ -1082,7 +1096,7 @@ class CelleMultipleWindow(ctk.CTkToplevel):
|
||||
messagebox.showinfo("Esportazione completata", f"File creato:\n{fname}", parent=self)
|
||||
except Exception as ex:
|
||||
_MODULE_LOGGER.exception(f"Errore esportazione UDC fantasma: {ex}")
|
||||
messagebox.showerror("Errore esportazione", str(ex), parent=self)
|
||||
messagebox.showerror("Errore esportazione", str(ex), parent=self, exception=ex)
|
||||
|
||||
|
||||
def open_celle_multiple_window(
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
|
||||
|
||||
os.chdir(Path(__file__).resolve().parent)
|
||||
|
||||
from runtime_support import ensure_stdio, run_with_fatal_log
|
||||
|
||||
ensure_stdio("warehouse_main")
|
||||
|
||||
@@ -8,6 +8,9 @@ import math
|
||||
import tkinter as tk
|
||||
from pathlib import Path
|
||||
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
MODULE_LOG_NAME = "window_placement"
|
||||
MODULE_LOG_PATH = Path(__file__).with_name("window_placement.log")
|
||||
|
||||
Reference in New Issue
Block a user