Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e4b227e82c | |||
| 85b11834b6 | |||
| 588bf6ce73 | |||
| d3941e88cc |
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.
|
||||
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.
|
||||
@@ -51,7 +51,7 @@ class InventarioWindow(ctk.CTkToplevel):
|
||||
self._descending = False
|
||||
self._rows = []
|
||||
self.var_date = tk.StringVar(value=date.today().strftime("%d/%m/%Y"))
|
||||
self.var_status = tk.StringVar(value=self._t("inventory.scope"))
|
||||
self.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]))
|
||||
@@ -63,8 +63,8 @@ class InventarioWindow(ctk.CTkToplevel):
|
||||
|
||||
def _build_ui(self):
|
||||
self.grid_columnconfigure(0, weight=1)
|
||||
self.grid_rowconfigure(3, weight=3)
|
||||
self.grid_rowconfigure(5, 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)
|
||||
@@ -78,9 +78,7 @@ class InventarioWindow(ctk.CTkToplevel):
|
||||
self.btn_export = ctk.CTkButton(top, text=self._t("inventory.export"), command=self._export,
|
||||
font=font, state="disabled")
|
||||
self.btn_export.grid(row=0, column=4, padx=6)
|
||||
ctk.CTkLabel(self, text=self._t("inventory.notice") + "\n" + self._t("inventory.scope")
|
||||
+ "\n" + self._t("inventory.history_notice"), anchor="w", justify="left",
|
||||
wraplength=1000).grid(row=1, column=0, sticky="ew", padx=10)
|
||||
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)
|
||||
@@ -97,12 +95,48 @@ class InventarioWindow(ctk.CTkToplevel):
|
||||
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")
|
||||
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"))
|
||||
|
||||
24
locale.json
24
locale.json
@@ -5,6 +5,12 @@
|
||||
"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.",
|
||||
@@ -131,6 +137,10 @@
|
||||
"history.udc.msg.empty": "Nessun movimento trovato.",
|
||||
"history.udc.msg.error": "Errore ricerca:\n{error}",
|
||||
"history.picking.title": "Storico Picking List",
|
||||
"history.picking.document": "Documento:",
|
||||
"history.picking.year": "Anno",
|
||||
"history.picking.udc_hint": "UDC vuota: anno corrente. Ricerca UDC: anno corrente e precedente. Se compilati, entrambi i filtri si applicano.",
|
||||
"history.picking.udc_invalid": "Inserire il codice UDC completo, numerico, di massimo 6 cifre.",
|
||||
"history.picking.button.reload": "Ricarica",
|
||||
"history.picking.detail_title": "Dettaglio contenuto",
|
||||
"history.picking.busy.master": "Carico storico picking list...",
|
||||
@@ -164,6 +174,8 @@
|
||||
"reset.button.refresh": "Carica",
|
||||
"reset.button.empty": "Svuota corsia...",
|
||||
"reset.summary": "Riepilogo",
|
||||
"reset.confirm": "Verranno movimentate {udc} UDC da {cells} celle della corsia {aisle}.\nUDC associate a documenti di spedizione definitivi (stato D): spedite in 9999 / 7G.1.1.\nTutte le altre: non scaffalate in 1000 (barcode 9001000).\nSaranno registrati prelievo e versamento, senza cancellazioni.\nLa verifica viene effettuata al momento di ogni movimento.\nDigitare il nome della corsia per confermare:",
|
||||
"reset.result": "Corsia {aisle}: movimentate {success} UDC su {total}.\nSpedite in 9999 / 7G.1.1: {shipped}.\nNon scaffalate in 1000: {non_shelved}.\nAggiornare lo storico picking list per ricalcolare i residui.",
|
||||
"layout.title": "Layout corsie",
|
||||
"layout.button.search": "Cerca per barcode UDC",
|
||||
"layout.button.refresh": "Aggiorna",
|
||||
@@ -227,6 +239,12 @@
|
||||
"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.",
|
||||
@@ -353,6 +371,10 @@
|
||||
"history.udc.msg.empty": "No movement found.",
|
||||
"history.udc.msg.error": "Search failed:\n{error}",
|
||||
"history.picking.title": "Picking List History",
|
||||
"history.picking.document": "Document:",
|
||||
"history.picking.year": "Year",
|
||||
"history.picking.udc_hint": "Empty UDC: current year. UDC search: current and previous year. Both filters apply when filled in.",
|
||||
"history.picking.udc_invalid": "Enter the complete numeric UDC code, up to 6 digits.",
|
||||
"history.picking.button.reload": "Reload",
|
||||
"history.picking.detail_title": "Content detail",
|
||||
"history.picking.busy.master": "Loading picking-list history...",
|
||||
@@ -386,6 +408,8 @@
|
||||
"reset.button.refresh": "Load",
|
||||
"reset.button.empty": "Empty aisle...",
|
||||
"reset.summary": "Summary",
|
||||
"reset.confirm": "{udc} UDCs will be moved from {cells} cells in aisle {aisle}.\nUDCs associated with definitive shipping documents (state D): shipped to 9999 / 7G.1.1.\nAll others: non-shelved in 1000 (barcode 9001000).\nPick and put-away movements will be recorded, without deletions.\nThe check is performed when each UDC is moved.\nType the aisle name to confirm:",
|
||||
"reset.result": "Aisle {aisle}: moved {success} out of {total} UDCs.\nShipped to 9999 / 7G.1.1: {shipped}.\nNon-shelved in 1000: {non_shelved}.\nRefresh picking-list history to recalculate residuals.",
|
||||
"layout.title": "Aisle layout",
|
||||
"layout.button.search": "Search by UDC barcode",
|
||||
"layout.button.refresh": "Refresh",
|
||||
|
||||
20
main.py
20
main.py
@@ -16,6 +16,7 @@ from runtime_support import ensure_stdio, run_with_fatal_log
|
||||
ensure_stdio("warehouse_main")
|
||||
|
||||
import customtkinter as ctk
|
||||
from PIL import Image, ImageDraw
|
||||
from tkinter import messagebox
|
||||
|
||||
from async_loop_singleton import get_global_loop, stop_global_loop
|
||||
@@ -357,17 +358,18 @@ class Launcher(ctk.CTk):
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _make_exit_icon(self, *, color: str) -> tk.PhotoImage:
|
||||
"""Create a small red X icon without adding image assets to the project."""
|
||||
def _make_exit_icon(self, *, color: str) -> ctk.CTkImage:
|
||||
"""Create a transparent X with extra resolution for HighDPI scaling."""
|
||||
|
||||
size = 14
|
||||
image = tk.PhotoImage(width=size, height=size)
|
||||
for offset in range(3, 11):
|
||||
image.put(color, (offset, offset))
|
||||
image.put(color, (offset + 1, offset))
|
||||
image.put(color, (offset, size - 1 - offset))
|
||||
image.put(color, (offset + 1, size - 1 - offset))
|
||||
return image
|
||||
scale = 3
|
||||
image = Image.new("RGBA", (size * scale, size * scale), (0, 0, 0, 0))
|
||||
draw = ImageDraw.Draw(image)
|
||||
draw.line((3 * scale, 3 * scale, 10 * scale, 10 * scale),
|
||||
fill=color, width=2 * scale)
|
||||
draw.line((3 * scale, 10 * scale, 10 * scale, 3 * scale),
|
||||
fill=color, width=2 * scale)
|
||||
return ctk.CTkImage(light_image=image, dark_image=image, size=(size, size))
|
||||
|
||||
def _apply_dynamic_geometry(self) -> None:
|
||||
"""Size the launcher around its current content and keep it docked at the top."""
|
||||
|
||||
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
|
||||
openpyxl==3.1.5
|
||||
orjson
|
||||
Pillow
|
||||
pyodbc==5.3.0
|
||||
SQLAlchemy==2.0.49
|
||||
tksheet==7.6.0
|
||||
|
||||
@@ -20,7 +20,7 @@ import customtkinter as ctk
|
||||
|
||||
from busy_overlay import InlineBusyOverlay
|
||||
from gestione_aree import AsyncRunner
|
||||
from gestione_scarico import move_pallet_async
|
||||
from reset_corsie_service import reset_pallet_async
|
||||
from locale_text import load_locale_catalog, text as loc_text
|
||||
from tooltips import WidgetToolTip, load_tooltip_catalog, tooltip_text
|
||||
from ui_theme import theme_color, theme_font, theme_section, theme_value
|
||||
@@ -171,7 +171,7 @@ SQL_CORSIE = """
|
||||
WITH C AS (
|
||||
SELECT DISTINCT LTRIM(RTRIM(Corsia)) AS Corsia
|
||||
FROM dbo.Celle
|
||||
WHERE ID <> 9999 AND (DelDataOra IS NULL) AND LTRIM(RTRIM(Corsia)) <> '7G'
|
||||
WHERE ID NOT IN (1000, 9999) AND (DelDataOra IS NULL) AND LTRIM(RTRIM(Corsia)) <> '7G'
|
||||
)
|
||||
SELECT Corsia
|
||||
FROM C
|
||||
@@ -193,7 +193,7 @@ WITH C AS (
|
||||
LTRIM(RTRIM(Colonna)) AS Colonna,
|
||||
LTRIM(RTRIM(Fila)) AS Fila
|
||||
FROM dbo.Celle
|
||||
WHERE ID <> 9999 AND (DelDataOra IS NULL)
|
||||
WHERE ID NOT IN (1000, 9999) AND (DelDataOra IS NULL)
|
||||
AND LTRIM(RTRIM(Corsia)) = :corsia
|
||||
),
|
||||
S AS (
|
||||
@@ -215,7 +215,7 @@ WITH C AS (
|
||||
LTRIM(RTRIM(Colonna)) AS Colonna,
|
||||
LTRIM(RTRIM(Fila)) AS Fila
|
||||
FROM dbo.Celle
|
||||
WHERE ID <> 9999 AND (DelDataOra IS NULL)
|
||||
WHERE ID NOT IN (1000, 9999) AND (DelDataOra IS NULL)
|
||||
AND LTRIM(RTRIM(Corsia)) = :corsia
|
||||
),
|
||||
S AS (
|
||||
@@ -237,7 +237,7 @@ SELECT
|
||||
COUNT(DISTINCT g.IDCella) AS TotCelle
|
||||
FROM dbo.XMag_GiacenzaPallet g
|
||||
JOIN dbo.Celle c ON c.ID = g.IDCella
|
||||
WHERE c.ID <> 9999
|
||||
WHERE c.ID NOT IN (1000, 9999)
|
||||
AND LTRIM(RTRIM(c.Corsia)) = :corsia;
|
||||
"""
|
||||
|
||||
@@ -253,7 +253,7 @@ WITH U AS (
|
||||
LTRIM(RTRIM(c.Fila)) AS SortFilaTxt
|
||||
FROM dbo.XMag_GiacenzaPallet g
|
||||
JOIN dbo.Celle c ON c.ID = g.IDCella
|
||||
WHERE c.ID <> 9999
|
||||
WHERE c.ID NOT IN (1000, 9999)
|
||||
AND LTRIM(RTRIM(c.Corsia)) = :corsia
|
||||
)
|
||||
SELECT
|
||||
@@ -537,12 +537,9 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
if tot_udc <= 0:
|
||||
messagebox.showinfo("Svuota corsia", f"Nessuna UDC attiva da scaricare per la corsia {corsia}.", parent=self)
|
||||
return
|
||||
msg = (
|
||||
f"Verranno scaricate logicamente {tot_udc} UDC attive distribuite su {tot_celle} celle della corsia {corsia}.",
|
||||
"L'operazione verra' eseguita come scarico verso 9000000 / 9999, senza cancellazioni fisiche dirette.",
|
||||
"Digitare il nome della corsia per confermare:",
|
||||
)
|
||||
confirm = simpledialog.askstring("Conferma", "\n".join(msg), parent=self)
|
||||
msg = loc_text("reset.confirm", catalog=self._locale_catalog).format(
|
||||
udc=tot_udc, cells=tot_celle, aisle=corsia)
|
||||
confirm = simpledialog.askstring("Conferma", msg, parent=self)
|
||||
if confirm is None:
|
||||
_MODULE_LOGGER.info(f"Reset corsia {corsia}: conferma annullata dall'utente")
|
||||
return
|
||||
@@ -569,20 +566,30 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
_log_dataset("reset_corsie_udc_reset", rows)
|
||||
|
||||
success = 0
|
||||
shipped = 0
|
||||
non_shelved = 0
|
||||
failed: list[dict[str, Any]] = []
|
||||
utente = str(getattr(self.session, "login", "") or "warehouse_ui").strip()
|
||||
|
||||
for barcode_pallet, idcella, ubicazione in rows:
|
||||
try:
|
||||
await move_pallet_async(
|
||||
target = await reset_pallet_async(
|
||||
self.db,
|
||||
barcode_pallet=str(barcode_pallet or "").strip(),
|
||||
target_idcella=9999,
|
||||
target_barcode_cella="9000000",
|
||||
source_idcella=int(idcella),
|
||||
utente=utente,
|
||||
)
|
||||
success += 1
|
||||
shipped += int(target == 9999)
|
||||
non_shelved += int(target == 1000)
|
||||
_MODULE_LOGGER.info(
|
||||
f"RESET MOVE corsia={corsia} pallet={barcode_pallet} "
|
||||
f"source={idcella} target={target} utente={utente}"
|
||||
)
|
||||
except Exception as ex:
|
||||
_MODULE_LOGGER.exception(
|
||||
f"RESET FAILED corsia={corsia} pallet={barcode_pallet} source={idcella}: {ex}"
|
||||
)
|
||||
failed.append(
|
||||
{
|
||||
"barcode_pallet": str(barcode_pallet or ""),
|
||||
@@ -595,6 +602,8 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
return {
|
||||
"total": len(rows),
|
||||
"success": success,
|
||||
"shipped": shipped,
|
||||
"non_shelved": non_shelved,
|
||||
"failed": failed,
|
||||
}
|
||||
|
||||
@@ -602,6 +611,9 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
total = int((result or {}).get("total", 0))
|
||||
success = int((result or {}).get("success", 0))
|
||||
failed = list((result or {}).get("failed", []))
|
||||
summary = loc_text("reset.result", catalog=self._locale_catalog).format(
|
||||
aisle=corsia, success=success, total=total,
|
||||
shipped=result.get("shipped", 0), non_shelved=result.get("non_shelved", 0))
|
||||
_MODULE_LOGGER.info(
|
||||
f"Reset corsia {corsia}: scarico logico completato success={success} total={total} failed={len(failed)}"
|
||||
)
|
||||
@@ -609,7 +621,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
messagebox.showwarning(
|
||||
"Completato con errori",
|
||||
(
|
||||
f"Corsia {corsia}: scaricate {success} UDC su {total}.\n"
|
||||
summary + "\n" +
|
||||
f"Errori su {len(failed)} UDC. Controllare {MODULE_LOG_PATH.name}."
|
||||
),
|
||||
parent=self,
|
||||
@@ -617,7 +629,7 @@ class ResetCorsieWindow(ctk.CTkToplevel):
|
||||
else:
|
||||
messagebox.showinfo(
|
||||
"Completato",
|
||||
f"Corsia {corsia}: svuotamento logico completato su {success} UDC.",
|
||||
summary,
|
||||
parent=self,
|
||||
)
|
||||
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])
|
||||
@@ -1,5 +1,13 @@
|
||||
# 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`,
|
||||
|
||||
@@ -20,6 +20,7 @@ from busy_overlay import InlineBusyOverlay
|
||||
from gestione_aree import AsyncRunner
|
||||
from gestione_scarico import move_pallet_async
|
||||
from locale_text import load_locale_catalog, text as loc_text
|
||||
from pickinglist_history_search import SQL_UDC_HISTORY, detail_request
|
||||
from ui_theme import theme_color, theme_font, theme_section, theme_value
|
||||
from ui_tables import merge_tags, style_treeview, zebra_tag
|
||||
from version_info import module_version, versioned_title
|
||||
@@ -175,6 +176,11 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
self._async = AsyncRunner(self)
|
||||
self._busy = InlineBusyOverlay(self, self._theme)
|
||||
self.var_documento = tk.StringVar()
|
||||
self.var_udc = tk.StringVar()
|
||||
self._master_rows: dict[str, dict[str, Any]] = {}
|
||||
self._selected_doc_id: int | None = None
|
||||
self._master_request = 0
|
||||
self._detail_request = 0
|
||||
self._selected_documento: str | None = None
|
||||
self._selected_stato_operativo: str = ""
|
||||
self._detail_rows: list[dict[str, Any]] = []
|
||||
@@ -201,23 +207,28 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
fg_color=theme_color(self._theme, "toolbar_frame_fg_color", ("#d7d7d7", "#3b3b3b")),
|
||||
)
|
||||
top.grid(row=0, column=0, sticky="ew", padx=8, pady=8)
|
||||
top.grid_columnconfigure(4, weight=1)
|
||||
top.grid_columnconfigure(6, weight=1)
|
||||
|
||||
label_font = theme_font(self._theme, "toolbar_label_font", ("Segoe UI", 10))
|
||||
entry_font = theme_font(self._theme, "entry_font", ("Segoe UI", 10))
|
||||
button_font = theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold"))
|
||||
|
||||
ctk.CTkLabel(top, text="Documento:", font=label_font).grid(row=0, column=0, sticky="w")
|
||||
ctk.CTkEntry(top, textvariable=self.var_documento, width=140, font=entry_font).grid(
|
||||
row=0, column=1, sticky="w", padx=(4, 12)
|
||||
)
|
||||
ctk.CTkLabel(top, text=loc_text("history.picking.document", catalog=self._locale_catalog),
|
||||
font=label_font).grid(row=0, column=0, sticky="w")
|
||||
self.entry_documento = ctk.CTkEntry(top, textvariable=self.var_documento, width=120, font=entry_font)
|
||||
self.entry_documento.grid(row=0, column=1, sticky="w", padx=(4, 12))
|
||||
self.entry_documento.bind("<Return>", lambda _e: self._load_master())
|
||||
ctk.CTkLabel(top, text="UDC:", font=label_font).grid(row=0, column=2, sticky="w")
|
||||
self.entry_udc = ctk.CTkEntry(top, textvariable=self.var_udc, width=110, font=entry_font)
|
||||
self.entry_udc.grid(row=0, column=3, sticky="w", padx=(4, 12))
|
||||
self.entry_udc.bind("<Return>", lambda _e: self._load_master())
|
||||
ctk.CTkButton(
|
||||
top,
|
||||
text=loc_text("history.picking.button.reload", catalog=self._locale_catalog, default="Ricarica"),
|
||||
command=self._load_master,
|
||||
font=button_font,
|
||||
).grid(
|
||||
row=0, column=2, sticky="w"
|
||||
row=0, column=4, sticky="w"
|
||||
)
|
||||
self.btn_ship_residuals = ctk.CTkButton(
|
||||
top,
|
||||
@@ -230,11 +241,13 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
state="disabled",
|
||||
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(
|
||||
row=1,
|
||||
columns=("Documento", "Data", "StatoDoc", "NAZIONE", "TotUDC", "Residue", "Spedite", "Stato", "IDStato"),
|
||||
columns=("Documento", "Data", "StatoDoc", "NAZIONE", "TotUDC", "Residue", "Spedite", "Stato", "IDStato", "Anno"),
|
||||
widths={
|
||||
"Documento": 100,
|
||||
"Data": 110,
|
||||
@@ -245,9 +258,13 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
"Spedite": 90,
|
||||
"Stato": 120,
|
||||
"IDStato": 80,
|
||||
"Anno": 70,
|
||||
},
|
||||
)
|
||||
self.master_tree.bind("<<TreeviewSelect>>", self._on_master_select)
|
||||
self.master_tree.configure(displaycolumns=("Documento", "Anno", "Data", "StatoDoc", "NAZIONE",
|
||||
"TotUDC", "Residue", "Spedite", "Stato", "IDStato"))
|
||||
self.master_tree.heading("Anno", text=loc_text("history.picking.year", catalog=self._locale_catalog))
|
||||
|
||||
ctk.CTkLabel(
|
||||
self,
|
||||
@@ -297,17 +314,35 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
|
||||
def _load_master(self) -> None:
|
||||
params = {"documento": str(self.var_documento.get() or "").strip() or None}
|
||||
udc = self.var_udc.get().strip()
|
||||
if udc and (not udc.isascii() or not udc.isdigit() or len(udc) > 6):
|
||||
messagebox.showwarning(loc_text("history.picking.msg.title", catalog=self._locale_catalog),
|
||||
loc_text("history.picking.udc_invalid", catalog=self._locale_catalog), parent=self)
|
||||
return
|
||||
sql = SQL_STORICO_PL
|
||||
if udc:
|
||||
sql = SQL_UDC_HISTORY
|
||||
params.update(pallet=udc, id_documento=None)
|
||||
previous_documento = self._selected_documento
|
||||
previous_id = self._selected_doc_id
|
||||
self._master_request += 1
|
||||
request = self._master_request
|
||||
self._detail_request += 1
|
||||
self._fill_master([])
|
||||
|
||||
async def _job():
|
||||
return await self.db_client.query_json(SQL_STORICO_PL, params)
|
||||
return await self.db_client.query_json(sql, params)
|
||||
|
||||
def _ok(res):
|
||||
if request != self._master_request:
|
||||
return
|
||||
self._fill_master(_rows_to_dicts(res))
|
||||
if previous_documento:
|
||||
self._restore_master_selection(previous_documento)
|
||||
self._restore_master_selection(previous_documento, previous_id)
|
||||
|
||||
def _err(ex):
|
||||
if request != self._master_request:
|
||||
return
|
||||
messagebox.showerror(
|
||||
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
|
||||
loc_text(
|
||||
@@ -334,10 +369,14 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
self.master_tree.delete(*self.master_tree.get_children(""))
|
||||
self.detail_tree.delete(*self.detail_tree.get_children(""))
|
||||
self._selected_documento = None
|
||||
self._selected_doc_id = None
|
||||
self._master_rows = {}
|
||||
self._selected_stato_operativo = ""
|
||||
self._detail_rows = []
|
||||
self._update_residual_button()
|
||||
for index, row in enumerate(rows):
|
||||
iid = f"doc_{row.get('Documento')}_{index}"
|
||||
self._master_rows[iid] = row
|
||||
stato = str(row.get("StatoOperativo") or "")
|
||||
is_open_with_shipped = (
|
||||
str(row.get("StatoDocumento") or "") == "P"
|
||||
@@ -355,7 +394,7 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
self.master_tree.insert(
|
||||
"",
|
||||
"end",
|
||||
iid=f"doc_{row.get('Documento')}_{index}",
|
||||
iid=iid,
|
||||
values=(
|
||||
row.get("Documento", ""),
|
||||
_format_date(row.get("DataDocumento", "")),
|
||||
@@ -366,14 +405,18 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
row.get("RigheSpedite", ""),
|
||||
stato,
|
||||
row.get("IDStato", ""),
|
||||
row.get("AnnoDocumento", datetime.now().year),
|
||||
),
|
||||
tags=merge_tags(zebra_tag(index), tag),
|
||||
)
|
||||
|
||||
def _on_master_select(self, _event=None) -> None:
|
||||
self._detail_request += 1
|
||||
request = self._detail_request
|
||||
selected = self.master_tree.selection()
|
||||
if not selected:
|
||||
self._selected_documento = None
|
||||
self._selected_doc_id = None
|
||||
self._selected_stato_operativo = ""
|
||||
self._detail_rows = []
|
||||
self._update_residual_button()
|
||||
@@ -382,19 +425,26 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
if not values:
|
||||
return
|
||||
documento = values[0]
|
||||
self._selected_doc_id = self._master_rows.get(selected[0], {}).get("IDDocumento")
|
||||
self._selected_documento = str(documento)
|
||||
self._selected_stato_operativo = str(values[7] if len(values) > 7 else "")
|
||||
self._detail_rows = []
|
||||
self.detail_tree.delete(*self.detail_tree.get_children(""))
|
||||
self._update_residual_button()
|
||||
sql, params = detail_request(documento, self._selected_doc_id, SQL_STORICO_PL_DETAILS)
|
||||
|
||||
async def _job():
|
||||
return await self.db_client.query_json(SQL_STORICO_PL_DETAILS, {"documento": documento})
|
||||
return await self.db_client.query_json(sql, params)
|
||||
|
||||
def _ok(res):
|
||||
if request != self._detail_request:
|
||||
return
|
||||
self._fill_detail(_rows_to_dicts(res))
|
||||
self._update_residual_button()
|
||||
|
||||
def _err(ex):
|
||||
if request != self._detail_request:
|
||||
return
|
||||
messagebox.showerror(
|
||||
loc_text("history.picking.msg.title", catalog=self._locale_catalog, default="Storico Picking List"),
|
||||
loc_text(
|
||||
@@ -451,12 +501,15 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
except Exception:
|
||||
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."""
|
||||
|
||||
for iid in self.master_tree.get_children(""):
|
||||
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.focus(iid)
|
||||
self.master_tree.see(iid)
|
||||
@@ -512,14 +565,18 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
return
|
||||
|
||||
documento = self._selected_documento
|
||||
document_id = self._selected_doc_id
|
||||
utente = self._operator_login()
|
||||
sql, params = detail_request(documento, document_id, SQL_STORICO_PL_DETAILS)
|
||||
|
||||
async def _job():
|
||||
# Re-read the detail inside the async job to avoid moving stale UI
|
||||
# rows if another operator or barcode client changed the list after
|
||||
# the user selected it.
|
||||
detail_res = await self.db_client.query_json(SQL_STORICO_PL_DETAILS, {"documento": documento})
|
||||
detail_res = await self.db_client.query_json(sql, params)
|
||||
detail_rows = _rows_to_dicts(detail_res)
|
||||
if document_id is not None and any(row.get("StatoDocumento") != "D" for row in detail_rows):
|
||||
raise RuntimeError("Documento non piu' definitivo. Ricaricare lo storico.")
|
||||
pallets = self._residual_pallets_from_rows(detail_rows)
|
||||
results: list[dict[str, Any]] = []
|
||||
for pallet in pallets:
|
||||
@@ -546,6 +603,7 @@ class StoricoPickingListWindow(ctk.CTkToplevel):
|
||||
parent=self,
|
||||
)
|
||||
self._selected_documento = str(documento)
|
||||
self._selected_doc_id = document_id
|
||||
self._load_master()
|
||||
|
||||
def _err(ex):
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import tkinter as tk
|
||||
import unittest
|
||||
import warnings
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from unittest.mock import Mock, patch
|
||||
@@ -46,6 +47,40 @@ class InventoryGuiTests(unittest.TestCase):
|
||||
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")
|
||||
@@ -98,11 +133,18 @@ class InventoryLauncherTests(unittest.TestCase):
|
||||
from main import Launcher
|
||||
from user_session import UserSession
|
||||
session = UserSession(1, "TEST", "Test operator")
|
||||
with patch.object(Launcher, "_apply_dynamic_geometry"), patch.object(Launcher, "lift"), \
|
||||
patch.object(Launcher, "focus_force"), patch.object(Launcher, "_make_exit_icon", return_value=None):
|
||||
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
|
||||
|
||||
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()
|
||||
@@ -25,7 +25,7 @@
|
||||
"dbconfig.button.test": "Prova subito la connessione con i dati inseriti senza ancora salvarli definitivamente.",
|
||||
"dbconfig.button.save": "Verifica i dati, salva il file di configurazione e permette al programma di continuare l'avvio.",
|
||||
"reset_corsie.refresh": "Ricarica il riepilogo e l'elenco delle celle occupate per la corsia selezionata.",
|
||||
"reset_corsie.empty_aisle": "Scarica logicamente tutte le UDC attive della corsia selezionata verso l'ubicazione di uscita.",
|
||||
"reset_corsie.empty_aisle": "Svuota la corsia: UDC associate a documenti definitivi in 7G.1.1, tutte le altre non scaffalate. Registra prelievi e versamenti.",
|
||||
"layout.search_udc": "Cerca una UDC per barcode, cambia automaticamente corsia e porta in evidenza la cella trovata.",
|
||||
"layout.refresh": "Ricarica la corsia selezionata e aggiorna matrice, colori e statistiche.",
|
||||
"layout.export_xlsx": "Esporta la vista corrente del layout corsia in un file Excel.",
|
||||
@@ -69,7 +69,7 @@
|
||||
"dbconfig.button.test": "Try the connection immediately with the entered values without saving them yet.",
|
||||
"dbconfig.button.save": "Validate the connection, save the configuration file and let the program continue startup.",
|
||||
"reset_corsie.refresh": "Reload the summary and the list of occupied cells for the selected aisle.",
|
||||
"reset_corsie.empty_aisle": "Logically unload all active UDCs in the selected aisle to the outbound location.",
|
||||
"reset_corsie.empty_aisle": "Empty the aisle: UDCs associated with definitive documents go to 7G.1.1; all others become non-shelved. Records pick and put-away movements.",
|
||||
"layout.search_udc": "Search a UDC by barcode, switch aisle automatically and highlight the matching cell.",
|
||||
"layout.refresh": "Reload the selected aisle and refresh matrix, colors and statistics.",
|
||||
"layout.export_xlsx": "Export the current aisle layout view to an Excel file.",
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
{
|
||||
"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"],
|
||||
|
||||
@@ -12,8 +12,8 @@ MODULE_VERSIONS: dict[str, str] = {
|
||||
"async_loop_singleton": "1.0.0",
|
||||
"async_msssql_query": "1.0.1",
|
||||
"audit_log": "1.0.0",
|
||||
"main": "1.0.3",
|
||||
"inventario": "1.1.0",
|
||||
"main": "1.0.4",
|
||||
"inventario": "1.1.1",
|
||||
"inventory_service": "1.1.0",
|
||||
"barcode_client": "1.0.27",
|
||||
"barcode_repository": "1.0.14",
|
||||
@@ -29,10 +29,12 @@ MODULE_VERSIONS: dict[str, str] = {
|
||||
"login_window": "1.0.0",
|
||||
"prenota_sprenota_sql": "1.0.1",
|
||||
"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",
|
||||
"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",
|
||||
"tooltips": "1.0.0",
|
||||
"udc_non_scaffalate": "1.0.1",
|
||||
|
||||
Reference in New Issue
Block a user