diff --git a/docs/ricerca_udc_storico_pickinglist.md b/docs/ricerca_udc_storico_pickinglist.md new file mode 100644 index 0000000..844abf1 --- /dev/null +++ b/docs/ricerca_udc_storico_pickinglist.md @@ -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. diff --git a/docs/svuotamento_corsie.md b/docs/svuotamento_corsie.md new file mode 100644 index 0000000..a37ed55 --- /dev/null +++ b/docs/svuotamento_corsie.md @@ -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. diff --git a/locale.json b/locale.json index 8acc56e..80a3786 100644 --- a/locale.json +++ b/locale.json @@ -137,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...", @@ -170,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", @@ -365,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...", @@ -398,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", diff --git a/pickinglist_history_search.py b/pickinglist_history_search.py new file mode 100644 index 0000000..bb2c251 --- /dev/null +++ b/pickinglist_history_search.py @@ -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} diff --git a/reset_corsie.py b/reset_corsie.py index ed1ea89..820d7ee 100644 --- a/reset_corsie.py +++ b/reset_corsie.py @@ -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() diff --git a/reset_corsie_service.py b/reset_corsie_service.py new file mode 100644 index 0000000..3bd2091 --- /dev/null +++ b/reset_corsie_service.py @@ -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]) diff --git a/storico_pickinglist.py b/storico_pickinglist.py index 9149ab0..f718504 100644 --- a/storico_pickinglist.py +++ b/storico_pickinglist.py @@ -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("", 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("", 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("<>", 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): diff --git a/tests/test_pickinglist_history_search.py b/tests/test_pickinglist_history_search.py new file mode 100644 index 0000000..9518e53 --- /dev/null +++ b/tests/test_pickinglist_history_search.py @@ -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"), []) diff --git a/tests/test_reset_corsie.py b/tests/test_reset_corsie.py new file mode 100644 index 0000000..21e396b --- /dev/null +++ b/tests/test_reset_corsie.py @@ -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() diff --git a/tooltip.json b/tooltip.json index a5f4430..816c648 100644 --- a/tooltip.json +++ b/tooltip.json @@ -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.", diff --git a/version_info.py b/version_info.py index e76e78d..f6890b0 100644 --- a/version_info.py +++ b/version_info.py @@ -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",