Compare commits
5 Commits
codex/dopp
...
e4b227e82c
| Author | SHA1 | Date | |
|---|---|---|---|
| e4b227e82c | |||
| 85b11834b6 | |||
| 588bf6ce73 | |||
| d3941e88cc | |||
| 04406e840d |
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.
|
||||||
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.
|
||||||
268
inventario.py
Normal file
268
inventario.py
Normal file
@@ -0,0 +1,268 @@
|
|||||||
|
"""Dated inventory reconciliation window, using the shared desktop UI lifecycle."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import tkinter as tk
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from tkinter import filedialog, messagebox, ttk
|
||||||
|
|
||||||
|
import customtkinter as ctk
|
||||||
|
|
||||||
|
from busy_overlay import InlineBusyOverlay
|
||||||
|
from gestione_aree import AsyncRunner
|
||||||
|
from inventory_service import (DETAIL_KEYS, LOT_KEYS, SUMMARY_KEYS, detail_values,
|
||||||
|
export_inventory, inventory_cutoff, load_inventory, status_text)
|
||||||
|
from locale_text import load_locale_catalog, text as loc_text
|
||||||
|
from runtime_support import log_exception
|
||||||
|
from ui_tables import style_treeview, zebra_tag
|
||||||
|
from ui_theme import theme_color, theme_font, theme_section, theme_value
|
||||||
|
from version_info import module_version, versioned_title
|
||||||
|
from window_placement import place_window_fullsize_below_parent_later
|
||||||
|
|
||||||
|
__version__ = module_version(__name__)
|
||||||
|
KEYS = SUMMARY_KEYS
|
||||||
|
|
||||||
|
|
||||||
|
def display_number(value) -> str:
|
||||||
|
"""Keep zeros visible and unknown values distinct from numeric stock."""
|
||||||
|
if value is None:
|
||||||
|
return "?"
|
||||||
|
if isinstance(value, Decimal):
|
||||||
|
return format(value, "f").rstrip("0").rstrip(".") if value.as_tuple().exponent < 0 else str(value)
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
|
||||||
|
class InventarioWindow(ctk.CTkToplevel):
|
||||||
|
"""Read-only, single-instance launcher child; DB and XLSX work are asynchronous."""
|
||||||
|
|
||||||
|
def __init__(self, parent, db_client, session=None):
|
||||||
|
super().__init__(parent)
|
||||||
|
self.db_client = db_client
|
||||||
|
self.session = session
|
||||||
|
self._catalog = load_locale_catalog()
|
||||||
|
self._theme = theme_section("inventory_window", theme_section("search_window", {}))
|
||||||
|
self._async = AsyncRunner(self)
|
||||||
|
self._busy = InlineBusyOverlay(self, self._theme)
|
||||||
|
self._loading = False
|
||||||
|
self._report = None
|
||||||
|
self._sort_column = "Product"
|
||||||
|
self._descending = False
|
||||||
|
self._rows = []
|
||||||
|
self.var_date = tk.StringVar(value=date.today().strftime("%d/%m/%Y"))
|
||||||
|
self.var_status = tk.StringVar(value=self._t("inventory.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)
|
||||||
|
|
||||||
|
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()
|
||||||
148
locale.json
148
locale.json
@@ -1,6 +1,74 @@
|
|||||||
{
|
{
|
||||||
"default_language": "IT",
|
"default_language": "IT",
|
||||||
"IT": {
|
"IT": {
|
||||||
|
"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.window_title": "Warehouse 1.0.0",
|
||||||
"launcher.operator": "Operatore: {display_name} ({login})",
|
"launcher.operator": "Operatore: {display_name} ({login})",
|
||||||
"launcher.reset_corsie": "Gestione Corsie",
|
"launcher.reset_corsie": "Gestione Corsie",
|
||||||
@@ -69,6 +137,10 @@
|
|||||||
"history.udc.msg.empty": "Nessun movimento trovato.",
|
"history.udc.msg.empty": "Nessun movimento trovato.",
|
||||||
"history.udc.msg.error": "Errore ricerca:\n{error}",
|
"history.udc.msg.error": "Errore ricerca:\n{error}",
|
||||||
"history.picking.title": "Storico Picking List",
|
"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.button.reload": "Ricarica",
|
||||||
"history.picking.detail_title": "Dettaglio contenuto",
|
"history.picking.detail_title": "Dettaglio contenuto",
|
||||||
"history.picking.busy.master": "Carico storico picking list...",
|
"history.picking.busy.master": "Carico storico picking list...",
|
||||||
@@ -102,6 +174,8 @@
|
|||||||
"reset.button.refresh": "Carica",
|
"reset.button.refresh": "Carica",
|
||||||
"reset.button.empty": "Svuota corsia...",
|
"reset.button.empty": "Svuota corsia...",
|
||||||
"reset.summary": "Riepilogo",
|
"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.title": "Layout corsie",
|
||||||
"layout.button.search": "Cerca per barcode UDC",
|
"layout.button.search": "Cerca per barcode UDC",
|
||||||
"layout.button.refresh": "Aggiorna",
|
"layout.button.refresh": "Aggiorna",
|
||||||
@@ -161,6 +235,74 @@
|
|||||||
"scarico.msg.exec_error": "Scarico fallito:\n{error}"
|
"scarico.msg.exec_error": "Scarico fallito:\n{error}"
|
||||||
},
|
},
|
||||||
"ENG": {
|
"ENG": {
|
||||||
|
"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.window_title": "Warehouse 1.0.0",
|
||||||
"launcher.operator": "Operator: {display_name} ({login})",
|
"launcher.operator": "Operator: {display_name} ({login})",
|
||||||
"launcher.reset_corsie": "Aisle Management",
|
"launcher.reset_corsie": "Aisle Management",
|
||||||
@@ -229,6 +371,10 @@
|
|||||||
"history.udc.msg.empty": "No movement found.",
|
"history.udc.msg.empty": "No movement found.",
|
||||||
"history.udc.msg.error": "Search failed:\n{error}",
|
"history.udc.msg.error": "Search failed:\n{error}",
|
||||||
"history.picking.title": "Picking List History",
|
"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.button.reload": "Reload",
|
||||||
"history.picking.detail_title": "Content detail",
|
"history.picking.detail_title": "Content detail",
|
||||||
"history.picking.busy.master": "Loading picking-list history...",
|
"history.picking.busy.master": "Loading picking-list history...",
|
||||||
@@ -262,6 +408,8 @@
|
|||||||
"reset.button.refresh": "Load",
|
"reset.button.refresh": "Load",
|
||||||
"reset.button.empty": "Empty aisle...",
|
"reset.button.empty": "Empty aisle...",
|
||||||
"reset.summary": "Summary",
|
"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.title": "Aisle layout",
|
||||||
"layout.button.search": "Search by UDC barcode",
|
"layout.button.search": "Search by UDC barcode",
|
||||||
"layout.button.refresh": "Refresh",
|
"layout.button.refresh": "Refresh",
|
||||||
|
|||||||
31
main.py
31
main.py
@@ -16,6 +16,7 @@ from runtime_support import ensure_stdio, run_with_fatal_log
|
|||||||
ensure_stdio("warehouse_main")
|
ensure_stdio("warehouse_main")
|
||||||
|
|
||||||
import customtkinter as ctk
|
import customtkinter as ctk
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
from tkinter import messagebox
|
from tkinter import messagebox
|
||||||
|
|
||||||
from async_loop_singleton import get_global_loop, stop_global_loop
|
from async_loop_singleton import get_global_loop, stop_global_loop
|
||||||
@@ -23,6 +24,7 @@ from async_msssql_query import AsyncMSSQLClient
|
|||||||
from audit_log import log_session_event
|
from audit_log import log_session_event
|
||||||
from db_config import build_dsn_from_config, ensure_db_config
|
from db_config import build_dsn_from_config, ensure_db_config
|
||||||
from diagnostica import open_diagnostica_window
|
from diagnostica import open_diagnostica_window
|
||||||
|
from inventario import open_inventario_window
|
||||||
from gestione_layout import open_layout_window
|
from gestione_layout import open_layout_window
|
||||||
from gestione_pickinglist import open_pickinglist_window
|
from gestione_pickinglist import open_pickinglist_window
|
||||||
from login_window import prompt_login
|
from login_window import prompt_login
|
||||||
@@ -163,6 +165,7 @@ class Launcher(ctk.CTk):
|
|||||||
"pickinglist",
|
"pickinglist",
|
||||||
"storico_pickinglist",
|
"storico_pickinglist",
|
||||||
"diagnostica",
|
"diagnostica",
|
||||||
|
"inventario",
|
||||||
]
|
]
|
||||||
|
|
||||||
def __init__(self, session: UserSession, db_client: AsyncMSSQLClient):
|
def __init__(self, session: UserSession, db_client: AsyncMSSQLClient):
|
||||||
@@ -279,6 +282,15 @@ class Launcher(ctk.CTk):
|
|||||||
lambda: open_diagnostica_window(self, self.db_client, session=self.session),
|
lambda: open_diagnostica_window(self, self.db_client, session=self.session),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
(
|
||||||
|
"inventario",
|
||||||
|
loc_text("inventory.title", catalog=self._locale_catalog, default="Inventario"),
|
||||||
|
"launcher.open_inventory",
|
||||||
|
lambda: self._open_or_focus_child_window(
|
||||||
|
"inventario",
|
||||||
|
lambda: open_inventario_window(self, self.db_client, session=self.session),
|
||||||
|
),
|
||||||
|
),
|
||||||
(
|
(
|
||||||
"arrange",
|
"arrange",
|
||||||
loc_text("launcher.arrange", catalog=self._locale_catalog, default="Ridisponi finestre"),
|
loc_text("launcher.arrange", catalog=self._locale_catalog, default="Ridisponi finestre"),
|
||||||
@@ -346,17 +358,18 @@ class Launcher(ctk.CTk):
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def _make_exit_icon(self, *, color: str) -> tk.PhotoImage:
|
def _make_exit_icon(self, *, color: str) -> ctk.CTkImage:
|
||||||
"""Create a small red X icon without adding image assets to the project."""
|
"""Create a transparent X with extra resolution for HighDPI scaling."""
|
||||||
|
|
||||||
size = 14
|
size = 14
|
||||||
image = tk.PhotoImage(width=size, height=size)
|
scale = 3
|
||||||
for offset in range(3, 11):
|
image = Image.new("RGBA", (size * scale, size * scale), (0, 0, 0, 0))
|
||||||
image.put(color, (offset, offset))
|
draw = ImageDraw.Draw(image)
|
||||||
image.put(color, (offset + 1, offset))
|
draw.line((3 * scale, 3 * scale, 10 * scale, 10 * scale),
|
||||||
image.put(color, (offset, size - 1 - offset))
|
fill=color, width=2 * scale)
|
||||||
image.put(color, (offset + 1, size - 1 - offset))
|
draw.line((3 * scale, 10 * scale, 10 * scale, 3 * scale),
|
||||||
return image
|
fill=color, width=2 * scale)
|
||||||
|
return ctk.CTkImage(light_image=image, dark_image=image, size=(size, size))
|
||||||
|
|
||||||
def _apply_dynamic_geometry(self) -> None:
|
def _apply_dynamic_geometry(self) -> None:
|
||||||
"""Size the launcher around its current content and keep it docked at the top."""
|
"""Size the launcher around its current content and keep it docked at the top."""
|
||||||
|
|||||||
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}
|
||||||
@@ -3,6 +3,7 @@ customtkinter==5.2.2
|
|||||||
loguru
|
loguru
|
||||||
openpyxl==3.1.5
|
openpyxl==3.1.5
|
||||||
orjson
|
orjson
|
||||||
|
Pillow
|
||||||
pyodbc==5.3.0
|
pyodbc==5.3.0
|
||||||
SQLAlchemy==2.0.49
|
SQLAlchemy==2.0.49
|
||||||
tksheet==7.6.0
|
tksheet==7.6.0
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ import customtkinter as ctk
|
|||||||
|
|
||||||
from busy_overlay import InlineBusyOverlay
|
from busy_overlay import InlineBusyOverlay
|
||||||
from gestione_aree import AsyncRunner
|
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 locale_text import load_locale_catalog, text as loc_text
|
||||||
from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text
|
from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text
|
||||||
from ui_theme import theme_color, theme_font, theme_section, theme_value
|
from ui_theme import theme_color, theme_font, theme_section, theme_value
|
||||||
@@ -171,7 +171,7 @@ SQL_CORSIE = """
|
|||||||
WITH C AS (
|
WITH C AS (
|
||||||
SELECT DISTINCT LTRIM(RTRIM(Corsia)) AS Corsia
|
SELECT DISTINCT LTRIM(RTRIM(Corsia)) AS Corsia
|
||||||
FROM dbo.Celle
|
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
|
SELECT Corsia
|
||||||
FROM C
|
FROM C
|
||||||
@@ -193,7 +193,7 @@ WITH C AS (
|
|||||||
LTRIM(RTRIM(Colonna)) AS Colonna,
|
LTRIM(RTRIM(Colonna)) AS Colonna,
|
||||||
LTRIM(RTRIM(Fila)) AS Fila
|
LTRIM(RTRIM(Fila)) AS Fila
|
||||||
FROM dbo.Celle
|
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
|
AND LTRIM(RTRIM(Corsia)) = :corsia
|
||||||
),
|
),
|
||||||
S AS (
|
S AS (
|
||||||
@@ -215,7 +215,7 @@ WITH C AS (
|
|||||||
LTRIM(RTRIM(Colonna)) AS Colonna,
|
LTRIM(RTRIM(Colonna)) AS Colonna,
|
||||||
LTRIM(RTRIM(Fila)) AS Fila
|
LTRIM(RTRIM(Fila)) AS Fila
|
||||||
FROM dbo.Celle
|
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
|
AND LTRIM(RTRIM(Corsia)) = :corsia
|
||||||
),
|
),
|
||||||
S AS (
|
S AS (
|
||||||
@@ -237,7 +237,7 @@ SELECT
|
|||||||
COUNT(DISTINCT g.IDCella) AS TotCelle
|
COUNT(DISTINCT g.IDCella) AS TotCelle
|
||||||
FROM dbo.XMag_GiacenzaPallet g
|
FROM dbo.XMag_GiacenzaPallet g
|
||||||
JOIN dbo.Celle c ON c.ID = g.IDCella
|
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;
|
AND LTRIM(RTRIM(c.Corsia)) = :corsia;
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -253,7 +253,7 @@ WITH U AS (
|
|||||||
LTRIM(RTRIM(c.Fila)) AS SortFilaTxt
|
LTRIM(RTRIM(c.Fila)) AS SortFilaTxt
|
||||||
FROM dbo.XMag_GiacenzaPallet g
|
FROM dbo.XMag_GiacenzaPallet g
|
||||||
JOIN dbo.Celle c ON c.ID = g.IDCella
|
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
|
AND LTRIM(RTRIM(c.Corsia)) = :corsia
|
||||||
)
|
)
|
||||||
SELECT
|
SELECT
|
||||||
@@ -537,12 +537,9 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
|||||||
if tot_udc <= 0:
|
if tot_udc <= 0:
|
||||||
messagebox.showinfo("Svuota corsia", f"Nessuna UDC attiva da scaricare per la corsia {corsia}.", parent=self)
|
messagebox.showinfo("Svuota corsia", f"Nessuna UDC attiva da scaricare per la corsia {corsia}.", parent=self)
|
||||||
return
|
return
|
||||||
msg = (
|
msg = loc_text("reset.confirm", catalog=self._locale_catalog).format(
|
||||||
f"Verranno scaricate logicamente {tot_udc} UDC attive distribuite su {tot_celle} celle della corsia {corsia}.",
|
udc=tot_udc, cells=tot_celle, aisle=corsia)
|
||||||
"L'operazione verra' eseguita come scarico verso 9000000 / 9999, senza cancellazioni fisiche dirette.",
|
confirm = simpledialog.askstring("Conferma", msg, parent=self)
|
||||||
"Digitare il nome della corsia per confermare:",
|
|
||||||
)
|
|
||||||
confirm = simpledialog.askstring("Conferma", "\n".join(msg), parent=self)
|
|
||||||
if confirm is None:
|
if confirm is None:
|
||||||
_MODULE_LOGGER.info(f"Reset corsia {corsia}: conferma annullata dall'utente")
|
_MODULE_LOGGER.info(f"Reset corsia {corsia}: conferma annullata dall'utente")
|
||||||
return
|
return
|
||||||
@@ -569,20 +566,30 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
|||||||
_log_dataset("reset_corsie_udc_reset", rows)
|
_log_dataset("reset_corsie_udc_reset", rows)
|
||||||
|
|
||||||
success = 0
|
success = 0
|
||||||
|
shipped = 0
|
||||||
|
non_shelved = 0
|
||||||
failed: list[dict[str, Any]] = []
|
failed: list[dict[str, Any]] = []
|
||||||
utente = str(getattr(self.session, "login", "") or "warehouse_ui").strip()
|
utente = str(getattr(self.session, "login", "") or "warehouse_ui").strip()
|
||||||
|
|
||||||
for barcode_pallet, idcella, ubicazione in rows:
|
for barcode_pallet, idcella, ubicazione in rows:
|
||||||
try:
|
try:
|
||||||
await move_pallet_async(
|
target = await reset_pallet_async(
|
||||||
self.db,
|
self.db,
|
||||||
barcode_pallet=str(barcode_pallet or "").strip(),
|
barcode_pallet=str(barcode_pallet or "").strip(),
|
||||||
target_idcella=9999,
|
source_idcella=int(idcella),
|
||||||
target_barcode_cella="9000000",
|
|
||||||
utente=utente,
|
utente=utente,
|
||||||
)
|
)
|
||||||
success += 1
|
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:
|
except Exception as ex:
|
||||||
|
_MODULE_LOGGER.exception(
|
||||||
|
f"RESET FAILED corsia={corsia} pallet={barcode_pallet} source={idcella}: {ex}"
|
||||||
|
)
|
||||||
failed.append(
|
failed.append(
|
||||||
{
|
{
|
||||||
"barcode_pallet": str(barcode_pallet or ""),
|
"barcode_pallet": str(barcode_pallet or ""),
|
||||||
@@ -595,6 +602,8 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
|||||||
return {
|
return {
|
||||||
"total": len(rows),
|
"total": len(rows),
|
||||||
"success": success,
|
"success": success,
|
||||||
|
"shipped": shipped,
|
||||||
|
"non_shelved": non_shelved,
|
||||||
"failed": failed,
|
"failed": failed,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -602,6 +611,9 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
|||||||
total = int((result or {}).get("total", 0))
|
total = int((result or {}).get("total", 0))
|
||||||
success = int((result or {}).get("success", 0))
|
success = int((result or {}).get("success", 0))
|
||||||
failed = list((result or {}).get("failed", []))
|
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(
|
_MODULE_LOGGER.info(
|
||||||
f"Reset corsia {corsia}: scarico logico completato success={success} total={total} failed={len(failed)}"
|
f"Reset corsia {corsia}: scarico logico completato success={success} total={total} failed={len(failed)}"
|
||||||
)
|
)
|
||||||
@@ -609,7 +621,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
|||||||
messagebox.showwarning(
|
messagebox.showwarning(
|
||||||
"Completato con errori",
|
"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}."
|
f"Errori su {len(failed)} UDC. Controllare {MODULE_LOG_PATH.name}."
|
||||||
),
|
),
|
||||||
parent=self,
|
parent=self,
|
||||||
@@ -617,7 +629,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
|||||||
else:
|
else:
|
||||||
messagebox.showinfo(
|
messagebox.showinfo(
|
||||||
"Completato",
|
"Completato",
|
||||||
f"Corsia {corsia}: svuotamento logico completato su {success} UDC.",
|
summary,
|
||||||
parent=self,
|
parent=self,
|
||||||
)
|
)
|
||||||
self.refresh()
|
self.refresh()
|
||||||
|
|||||||
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])
|
||||||
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.
|
||||||
@@ -20,6 +20,7 @@ from busy_overlay import InlineBusyOverlay
|
|||||||
from gestione_aree import AsyncRunner
|
from gestione_aree import AsyncRunner
|
||||||
from gestione_scarico import move_pallet_async
|
from gestione_scarico import move_pallet_async
|
||||||
from locale_text import load_locale_catalog, text as loc_text
|
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_theme import theme_color, theme_font, theme_section, theme_value
|
||||||
from ui_tables import merge_tags, style_treeview, zebra_tag
|
from ui_tables import merge_tags, style_treeview, zebra_tag
|
||||||
from version_info import module_version, versioned_title
|
from version_info import module_version, versioned_title
|
||||||
@@ -175,6 +176,11 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
|||||||
self._async = AsyncRunner(self)
|
self._async = AsyncRunner(self)
|
||||||
self._busy = InlineBusyOverlay(self, self._theme)
|
self._busy = InlineBusyOverlay(self, self._theme)
|
||||||
self.var_documento = tk.StringVar()
|
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_documento: str | None = None
|
||||||
self._selected_stato_operativo: str = ""
|
self._selected_stato_operativo: str = ""
|
||||||
self._detail_rows: list[dict[str, Any]] = []
|
self._detail_rows: list[dict[str, Any]] = []
|
||||||
@@ -201,23 +207,28 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
|||||||
fg_color=theme_color(self._theme, "toolbar_frame_fg_color", ("#d7d7d7", "#3b3b3b")),
|
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(row=0, column=0, sticky="ew", padx=8, pady=8)
|
||||||
top.grid_columnconfigure(4, weight=1)
|
top.grid_columnconfigure(6, weight=1)
|
||||||
|
|
||||||
label_font = theme_font(self._theme, "toolbar_label_font", ("Segoe UI", 10))
|
label_font = theme_font(self._theme, "toolbar_label_font", ("Segoe UI", 10))
|
||||||
entry_font = theme_font(self._theme, "entry_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"))
|
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.CTkLabel(top, text=loc_text("history.picking.document", catalog=self._locale_catalog),
|
||||||
ctk.CTkEntry(top, textvariable=self.var_documento, width=140, font=entry_font).grid(
|
font=label_font).grid(row=0, column=0, sticky="w")
|
||||||
row=0, column=1, sticky="w", padx=(4, 12)
|
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(
|
ctk.CTkButton(
|
||||||
top,
|
top,
|
||||||
text=loc_text("history.picking.button.reload", catalog=self._locale_catalog, default="Ricarica"),
|
text=loc_text("history.picking.button.reload", catalog=self._locale_catalog, default="Ricarica"),
|
||||||
command=self._load_master,
|
command=self._load_master,
|
||||||
font=button_font,
|
font=button_font,
|
||||||
).grid(
|
).grid(
|
||||||
row=0, column=2, sticky="w"
|
row=0, column=4, sticky="w"
|
||||||
)
|
)
|
||||||
self.btn_ship_residuals = ctk.CTkButton(
|
self.btn_ship_residuals = ctk.CTkButton(
|
||||||
top,
|
top,
|
||||||
@@ -230,11 +241,13 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
|||||||
state="disabled",
|
state="disabled",
|
||||||
font=button_font,
|
font=button_font,
|
||||||
)
|
)
|
||||||
self.btn_ship_residuals.grid(row=0, column=3, sticky="w", padx=(12, 0))
|
self.btn_ship_residuals.grid(row=0, column=5, sticky="w", padx=(12, 0))
|
||||||
|
ctk.CTkLabel(top, text=loc_text("history.picking.udc_hint", catalog=self._locale_catalog),
|
||||||
|
font=label_font, anchor="w").grid(row=1, column=0, columnspan=7, sticky="ew", pady=(4, 0))
|
||||||
|
|
||||||
self.master_tree = self._make_tree(
|
self.master_tree = self._make_tree(
|
||||||
row=1,
|
row=1,
|
||||||
columns=("Documento", "Data", "StatoDoc", "NAZIONE", "TotUDC", "Residue", "Spedite", "Stato", "IDStato"),
|
columns=("Documento", "Data", "StatoDoc", "NAZIONE", "TotUDC", "Residue", "Spedite", "Stato", "IDStato", "Anno"),
|
||||||
widths={
|
widths={
|
||||||
"Documento": 100,
|
"Documento": 100,
|
||||||
"Data": 110,
|
"Data": 110,
|
||||||
@@ -245,9 +258,13 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
|||||||
"Spedite": 90,
|
"Spedite": 90,
|
||||||
"Stato": 120,
|
"Stato": 120,
|
||||||
"IDStato": 80,
|
"IDStato": 80,
|
||||||
|
"Anno": 70,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
self.master_tree.bind("<<TreeviewSelect>>", self._on_master_select)
|
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(
|
ctk.CTkLabel(
|
||||||
self,
|
self,
|
||||||
@@ -297,17 +314,35 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
|||||||
|
|
||||||
def _load_master(self) -> None:
|
def _load_master(self) -> None:
|
||||||
params = {"documento": str(self.var_documento.get() or "").strip() or 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_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():
|
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):
|
def _ok(res):
|
||||||
|
if request != self._master_request:
|
||||||
|
return
|
||||||
self._fill_master(_rows_to_dicts(res))
|
self._fill_master(_rows_to_dicts(res))
|
||||||
if previous_documento:
|
if previous_documento:
|
||||||
self._restore_master_selection(previous_documento)
|
self._restore_master_selection(previous_documento, previous_id)
|
||||||
|
|
||||||
def _err(ex):
|
def _err(ex):
|
||||||
|
if request != self._master_request:
|
||||||
|
return
|
||||||
messagebox.showerror(
|
messagebox.showerror(
|
||||||
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
|
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
|
||||||
loc_text(
|
loc_text(
|
||||||
@@ -334,10 +369,14 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
|||||||
self.master_tree.delete(*self.master_tree.get_children(""))
|
self.master_tree.delete(*self.master_tree.get_children(""))
|
||||||
self.detail_tree.delete(*self.detail_tree.get_children(""))
|
self.detail_tree.delete(*self.detail_tree.get_children(""))
|
||||||
self._selected_documento = None
|
self._selected_documento = None
|
||||||
|
self._selected_doc_id = None
|
||||||
|
self._master_rows = {}
|
||||||
self._selected_stato_operativo = ""
|
self._selected_stato_operativo = ""
|
||||||
self._detail_rows = []
|
self._detail_rows = []
|
||||||
self._update_residual_button()
|
self._update_residual_button()
|
||||||
for index, row in enumerate(rows):
|
for index, row in enumerate(rows):
|
||||||
|
iid = f"doc_{row.get('Documento')}_{index}"
|
||||||
|
self._master_rows[iid] = row
|
||||||
stato = str(row.get("StatoOperativo") or "")
|
stato = str(row.get("StatoOperativo") or "")
|
||||||
is_open_with_shipped = (
|
is_open_with_shipped = (
|
||||||
str(row.get("StatoDocumento") or "") == "P"
|
str(row.get("StatoDocumento") or "") == "P"
|
||||||
@@ -355,7 +394,7 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
|||||||
self.master_tree.insert(
|
self.master_tree.insert(
|
||||||
"",
|
"",
|
||||||
"end",
|
"end",
|
||||||
iid=f"doc_{row.get('Documento')}_{index}",
|
iid=iid,
|
||||||
values=(
|
values=(
|
||||||
row.get("Documento", ""),
|
row.get("Documento", ""),
|
||||||
_format_date(row.get("DataDocumento", "")),
|
_format_date(row.get("DataDocumento", "")),
|
||||||
@@ -366,14 +405,18 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
|||||||
row.get("RigheSpedite", ""),
|
row.get("RigheSpedite", ""),
|
||||||
stato,
|
stato,
|
||||||
row.get("IDStato", ""),
|
row.get("IDStato", ""),
|
||||||
|
row.get("AnnoDocumento", datetime.now().year),
|
||||||
),
|
),
|
||||||
tags=merge_tags(zebra_tag(index), tag),
|
tags=merge_tags(zebra_tag(index), tag),
|
||||||
)
|
)
|
||||||
|
|
||||||
def _on_master_select(self, _event=None) -> None:
|
def _on_master_select(self, _event=None) -> None:
|
||||||
|
self._detail_request += 1
|
||||||
|
request = self._detail_request
|
||||||
selected = self.master_tree.selection()
|
selected = self.master_tree.selection()
|
||||||
if not selected:
|
if not selected:
|
||||||
self._selected_documento = None
|
self._selected_documento = None
|
||||||
|
self._selected_doc_id = None
|
||||||
self._selected_stato_operativo = ""
|
self._selected_stato_operativo = ""
|
||||||
self._detail_rows = []
|
self._detail_rows = []
|
||||||
self._update_residual_button()
|
self._update_residual_button()
|
||||||
@@ -382,19 +425,26 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
|||||||
if not values:
|
if not values:
|
||||||
return
|
return
|
||||||
documento = values[0]
|
documento = values[0]
|
||||||
|
self._selected_doc_id = self._master_rows.get(selected[0], {}).get("IDDocumento")
|
||||||
self._selected_documento = str(documento)
|
self._selected_documento = str(documento)
|
||||||
self._selected_stato_operativo = str(values[7] if len(values) > 7 else "")
|
self._selected_stato_operativo = str(values[7] if len(values) > 7 else "")
|
||||||
self._detail_rows = []
|
self._detail_rows = []
|
||||||
|
self.detail_tree.delete(*self.detail_tree.get_children(""))
|
||||||
self._update_residual_button()
|
self._update_residual_button()
|
||||||
|
sql, params = detail_request(documento, self._selected_doc_id, SQL_STORICO_PL_DETAILS)
|
||||||
|
|
||||||
async def _job():
|
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):
|
def _ok(res):
|
||||||
|
if request != self._detail_request:
|
||||||
|
return
|
||||||
self._fill_detail(_rows_to_dicts(res))
|
self._fill_detail(_rows_to_dicts(res))
|
||||||
self._update_residual_button()
|
self._update_residual_button()
|
||||||
|
|
||||||
def _err(ex):
|
def _err(ex):
|
||||||
|
if request != self._detail_request:
|
||||||
|
return
|
||||||
messagebox.showerror(
|
messagebox.showerror(
|
||||||
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
|
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
|
||||||
loc_text(
|
loc_text(
|
||||||
@@ -451,12 +501,15 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def _restore_master_selection(self, documento: str) -> None:
|
def _restore_master_selection(self, documento: str, document_id: int | None = None) -> None:
|
||||||
"""Re-select a document after a reload, when it is still visible."""
|
"""Re-select a document after a reload, when it is still visible."""
|
||||||
|
|
||||||
for iid in self.master_tree.get_children(""):
|
for iid in self.master_tree.get_children(""):
|
||||||
values = self.master_tree.item(iid, "values")
|
values = self.master_tree.item(iid, "values")
|
||||||
if values and str(values[0]) == str(documento):
|
row = self._master_rows.get(iid, {})
|
||||||
|
matches = (row.get("IDDocumento") == document_id if document_id is not None
|
||||||
|
else row.get("IDDocumento") is None and values and str(values[0]) == str(documento))
|
||||||
|
if matches:
|
||||||
self.master_tree.selection_set(iid)
|
self.master_tree.selection_set(iid)
|
||||||
self.master_tree.focus(iid)
|
self.master_tree.focus(iid)
|
||||||
self.master_tree.see(iid)
|
self.master_tree.see(iid)
|
||||||
@@ -512,14 +565,18 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
|||||||
return
|
return
|
||||||
|
|
||||||
documento = self._selected_documento
|
documento = self._selected_documento
|
||||||
|
document_id = self._selected_doc_id
|
||||||
utente = self._operator_login()
|
utente = self._operator_login()
|
||||||
|
sql, params = detail_request(documento, document_id, SQL_STORICO_PL_DETAILS)
|
||||||
|
|
||||||
async def _job():
|
async def _job():
|
||||||
# Re-read the detail inside the async job to avoid moving stale UI
|
# Re-read the detail inside the async job to avoid moving stale UI
|
||||||
# rows if another operator or barcode client changed the list after
|
# rows if another operator or barcode client changed the list after
|
||||||
# the user selected it.
|
# the user selected it.
|
||||||
detail_res = await self.db_client.query_json(SQL_STORICO_PL_DETAILS, {"documento": documento})
|
detail_res = await self.db_client.query_json(sql, params)
|
||||||
detail_rows = _rows_to_dicts(detail_res)
|
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)
|
pallets = self._residual_pallets_from_rows(detail_rows)
|
||||||
results: list[dict[str, Any]] = []
|
results: list[dict[str, Any]] = []
|
||||||
for pallet in pallets:
|
for pallet in pallets:
|
||||||
@@ -546,6 +603,7 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
|||||||
parent=self,
|
parent=self,
|
||||||
)
|
)
|
||||||
self._selected_documento = str(documento)
|
self._selected_documento = str(documento)
|
||||||
|
self._selected_doc_id = document_id
|
||||||
self._load_master()
|
self._load_master()
|
||||||
|
|
||||||
def _err(ex):
|
def _err(ex):
|
||||||
|
|||||||
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()
|
||||||
174
tests/test_inventory_gui.py
Normal file
174
tests/test_inventory_gui.py
Normal file
@@ -0,0 +1,174 @@
|
|||||||
|
"""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)
|
||||||
|
with patch("inventario.messagebox.showerror"), patch("inventario.log_exception"):
|
||||||
|
self.win._error(RuntimeError("Synthetic failure"))
|
||||||
|
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()
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
{
|
{
|
||||||
"default_language": "IT",
|
"default_language": "IT",
|
||||||
"IT": {
|
"IT": {
|
||||||
|
"launcher.open_inventory": "Confronta WMS e Magazzino Principale SAM a fine giornata, con dettaglio UDC, anomalie ed esportazione XLSX. Ricostruzione da validare.",
|
||||||
"launcher.open_reset_corsie": "Apre la finestra di gestione corsie per visualizzare il contenuto di una corsia e svuotarla in modo controllato.",
|
"launcher.open_reset_corsie": "Apre la finestra di gestione corsie per visualizzare il contenuto di una corsia e svuotarla in modo controllato.",
|
||||||
"launcher.open_layout": "Apre la vista layout delle corsie con celle, UDC presenti e menu operativo contestuale.",
|
"launcher.open_layout": "Apre la vista layout delle corsie con celle, UDC presenti e menu operativo contestuale.",
|
||||||
"launcher.open_multi_udc": "Apre la vista UDC fantasma per analizzare celle con piu' pallet e bonificare i candidati fantasma.",
|
"launcher.open_multi_udc": "Apre la vista UDC fantasma per analizzare celle con piu' pallet e bonificare i candidati fantasma.",
|
||||||
@@ -24,7 +25,7 @@
|
|||||||
"dbconfig.button.test": "Prova subito la connessione con i dati inseriti senza ancora salvarli definitivamente.",
|
"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.",
|
"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.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.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.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.",
|
"layout.export_xlsx": "Esporta la vista corrente del layout corsia in un file Excel.",
|
||||||
@@ -44,6 +45,7 @@
|
|||||||
"picking.sequence.close": "Chiude la finestra senza effettuare altri salvataggi."
|
"picking.sequence.close": "Chiude la finestra senza effettuare altri salvataggi."
|
||||||
},
|
},
|
||||||
"ENG": {
|
"ENG": {
|
||||||
|
"launcher.open_inventory": "Compare WMS and SAM main warehouse at end of day, with UDC details, data-quality warnings and XLSX export. Reconstruction requires validation.",
|
||||||
"launcher.open_reset_corsie": "Open the aisle management window to inspect an aisle and empty it in a controlled way.",
|
"launcher.open_reset_corsie": "Open the aisle management window to inspect an aisle and empty it in a controlled way.",
|
||||||
"launcher.open_layout": "Open the aisle layout view with cells, present UDCs and the operational context menu.",
|
"launcher.open_layout": "Open the aisle layout view with cells, present UDCs and the operational context menu.",
|
||||||
"launcher.open_multi_udc": "Open the ghost UDC view to inspect cells with multiple pallets and clean ghost candidates.",
|
"launcher.open_multi_udc": "Open the ghost UDC view to inspect cells with multiple pallets and clean ghost candidates.",
|
||||||
@@ -67,7 +69,7 @@
|
|||||||
"dbconfig.button.test": "Try the connection immediately with the entered values without saving them yet.",
|
"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.",
|
"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.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.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.refresh": "Reload the selected aisle and refresh matrix, colors and statistics.",
|
||||||
"layout.export_xlsx": "Export the current aisle layout view to an Excel file.",
|
"layout.export_xlsx": "Export the current aisle layout view to an Excel file.",
|
||||||
|
|||||||
@@ -1,4 +1,17 @@
|
|||||||
{
|
{
|
||||||
|
"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": {
|
"global": {
|
||||||
"window_bg": ["#f1f1f1", "#2b2b2b"],
|
"window_bg": ["#f1f1f1", "#2b2b2b"],
|
||||||
"panel_bg": ["#d9d9d9", "#3a3a3a"],
|
"panel_bg": ["#d9d9d9", "#3a3a3a"],
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ ALL_ACTIONS: FrozenSet[str] = frozenset(
|
|||||||
"launcher.open_pickinglist",
|
"launcher.open_pickinglist",
|
||||||
"launcher.open_history_pickinglist",
|
"launcher.open_history_pickinglist",
|
||||||
"launcher.open_diagnostics",
|
"launcher.open_diagnostics",
|
||||||
|
"launcher.open_inventory",
|
||||||
"launcher.arrange_windows",
|
"launcher.arrange_windows",
|
||||||
"launcher.exit",
|
"launcher.exit",
|
||||||
"reset_corsie.view",
|
"reset_corsie.view",
|
||||||
@@ -29,6 +30,7 @@ ALL_ACTIONS: FrozenSet[str] = frozenset(
|
|||||||
"history_udc.view",
|
"history_udc.view",
|
||||||
"history_pickinglist.view",
|
"history_pickinglist.view",
|
||||||
"diagnostics.view",
|
"diagnostics.view",
|
||||||
|
"inventory.view",
|
||||||
"multi_udc.view",
|
"multi_udc.view",
|
||||||
"layout.view",
|
"layout.view",
|
||||||
"layout.carico",
|
"layout.carico",
|
||||||
|
|||||||
@@ -12,7 +12,9 @@ MODULE_VERSIONS: dict[str, str] = {
|
|||||||
"async_loop_singleton": "1.0.0",
|
"async_loop_singleton": "1.0.0",
|
||||||
"async_msssql_query": "1.0.1",
|
"async_msssql_query": "1.0.1",
|
||||||
"audit_log": "1.0.0",
|
"audit_log": "1.0.0",
|
||||||
"main": "1.0.2",
|
"main": "1.0.4",
|
||||||
|
"inventario": "1.1.1",
|
||||||
|
"inventory_service": "1.1.0",
|
||||||
"barcode_client": "1.0.27",
|
"barcode_client": "1.0.27",
|
||||||
"barcode_repository": "1.0.14",
|
"barcode_repository": "1.0.14",
|
||||||
"barcode_service": "1.0.25",
|
"barcode_service": "1.0.25",
|
||||||
@@ -27,15 +29,17 @@ MODULE_VERSIONS: dict[str, str] = {
|
|||||||
"login_window": "1.0.0",
|
"login_window": "1.0.0",
|
||||||
"prenota_sprenota_sql": "1.0.1",
|
"prenota_sprenota_sql": "1.0.1",
|
||||||
"pickinglist_sequence": "1.0.0",
|
"pickinglist_sequence": "1.0.0",
|
||||||
"reset_corsie": "1.0.0",
|
"reset_corsie": "1.0.1",
|
||||||
|
"reset_corsie_service": "1.0.0",
|
||||||
"runtime_support": "1.0.1",
|
"runtime_support": "1.0.1",
|
||||||
"search_pallets": "1.0.0",
|
"search_pallets": "1.0.0",
|
||||||
"storico_pickinglist": "1.0.4",
|
"storico_pickinglist": "1.0.5",
|
||||||
|
"pickinglist_history_search": "1.0.0",
|
||||||
"storico_udc": "1.0.0",
|
"storico_udc": "1.0.0",
|
||||||
"tooltips": "1.0.0",
|
"tooltips": "1.0.0",
|
||||||
"udc_non_scaffalate": "1.0.1",
|
"udc_non_scaffalate": "1.0.1",
|
||||||
"ui_theme": "1.0.0",
|
"ui_theme": "1.0.0",
|
||||||
"user_session": "1.0.2",
|
"user_session": "1.0.3",
|
||||||
"view_celle_multi_udc": "1.0.0",
|
"view_celle_multi_udc": "1.0.0",
|
||||||
"window_placement": "1.0.0",
|
"window_placement": "1.0.0",
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user