From 04406e840dd720dba9134222a13896197865305d Mon Sep 17 00:00:00 2001 From: allebonvi Date: Wed, 21 Oct 2026 11:13:23 +0200 Subject: [PATCH] Integra inventario WMS-SAM nella versione monolista con test e guida deploy --- INSTALLAZIONE_MONOLISTA_INVENTARIO.md | 104 ++++++++++ inventario.py | 234 ++++++++++++++++++++++ inventory_report.sql | 155 +++++++++++++++ inventory_service.py | 271 ++++++++++++++++++++++++++ locale.json | 124 ++++++++++++ main.py | 11 ++ specifica_inventario.md | 242 +++++++++++++++++++++++ tests/test_inventory.py | 202 +++++++++++++++++++ tests/test_inventory_gui.py | 132 +++++++++++++ tests/test_inventory_sql.py | 139 +++++++++++++ tooltip.json | 2 + ui_theme.json | 9 + user_session.py | 2 + version_info.py | 6 +- 14 files changed, 1631 insertions(+), 2 deletions(-) create mode 100644 INSTALLAZIONE_MONOLISTA_INVENTARIO.md create mode 100644 inventario.py create mode 100644 inventory_report.sql create mode 100644 inventory_service.py create mode 100644 specifica_inventario.md create mode 100644 tests/test_inventory.py create mode 100644 tests/test_inventory_gui.py create mode 100644 tests/test_inventory_sql.py diff --git a/INSTALLAZIONE_MONOLISTA_INVENTARIO.md b/INSTALLAZIONE_MONOLISTA_INVENTARIO.md new file mode 100644 index 0000000..ec7221e --- /dev/null +++ b/INSTALLAZIONE_MONOLISTA_INVENTARIO.md @@ -0,0 +1,104 @@ +# Aggiornamento reparto: monolista con Inventario + +Release: `warehouse-monolista-2.0.1-inventario`, ramo di distribuzione `main`. +La bilista rimane separata su `codex/doppia-pickinglist` e non e' inclusa. +Modulo Inventario 1.1.0, launcher 1.0.3. Barcode e logica picking monolista +invariati rispetto al freeze `warehouse-monolista-2.0`. + +## Prima dell'aggiornamento + +Chiudere backoffice e terminalini Python che usano il database. +Conservare una copia della cartella installata, in particolare dei file locali +di configurazione e dei log utili. Non pubblicare db_connection.json su Git. +Se si aggiorna il DB, eseguire prima un backup e conservarne il ripristino. + +## Aggiornare il programma con Git + +Dal prompt nella cartella di installazione (esempio C:\flywms): + +```bat +cd /d C:\flywms +git status --short +git rev-parse HEAD +git fetch origin --tags +git switch main +git pull --ff-only origin main +python -m pip install -r requirements.txt +git log -1 --oneline +git describe --tags --exact-match HEAD +``` + +Annotare il vecchio commit prima dell'aggiornamento. Se Git segnala modifiche +locali o una divergenza, fermarsi: NON usare reset --hard, clean o push --force. +I file locali non tracciati, come la configurazione DB, non devono essere eliminati. +Verificare che la connessione rimanga quella del reparto, non del PC di sviluppo. + +Il tag identifica questa pubblicazione; se in futuro main avanza, il comando +describe potra' mostrare un'altra release. Per scegliere esattamente questa: + +```bat +git switch --detach warehouse-monolista-2.0.1-inventario +``` + +Per riprendere in seguito gli aggiornamenti normali: git switch main, poi +git pull --ff-only origin main. + +## Script SQL da usare + +Il cumulativo MONOLISTA e' `apply_online_python_wms_full_patch.sql`, ottenuto +dal ramo main/tag di questa release. Aprirlo in SSMS, selezionare esplicitamente +il database Mediseawall e lanciarlo dopo backup, con client Python chiusi. +Controllare tutti i messaggi di errore: lo script usa piu' batch GO e non e' +una singola transazione atomica; il solo PRINT finale non certifica il successo. + +Sono gia' inclusi: +- oggetti Python di prenotazione e viste picking residue; +- oggetti per storico picking e salti UDC; +- filtro operativo massimo 30 giorni, selezionabile nella UI a 10/15/20/30; +- LEFT JOIN per le destinazioni senza nazione; +- tabella py_PickingListPrelievoSequenza e vista py_ViewPackingListPrelievo; +- ordine di default con non scaffalate prima degli scaffali e sequenza + personalizzata per documento, che nella monolista prevale sul default. + +Se si applica il cumulativo non occorre ripetere separatamente le patch +days_filter, optional_destination_country e sequence. I singoli script e i +rollback gia' presenti rimangono nel repository per interventi mirati: +non eseguirli tutti indiscriminatamente e non usarli come rollback cumulativo. + +ATTENZIONE: nel ramo BILISTA il file cumulativo ha lo stesso nome ma comprende +anche oggetti py_PickingPair. Non prelevarlo da quella cartella/ramo per questa +installazione. Questa pubblicazione non esegue alcuno script sul DB online. + +## Inventario: nessuna nuova patch DB + +Se il DB ha gia' tutte le patch monolista sopra elencate, per aggiungere +l'inventario non serve rilanciare il cumulativo: gli script SQL sono invariati +rispetto al freeze monolista 2.0. + +`inventory_report.sql` DEVE rimanere accanto a inventory_service.py, ma NON va +incollato in SSMS: e' la query parametrizzata eseguita dal programma. +L'utente DB deve poter leggere le sorgenti WMS e SAMA1, incluso EXTTACLOTSER. +Non vengono create tabelle persistenti per l'inventario. + +Avviare il programma come di consueto, aprire Inventario, scegliere la data, +eseguire il calcolo e provare l'export. Una seconda pressione di Inventario +deve riportare la stessa finestra in primo piano. Nessuna query parte +automaticamente all'apertura della finestra. + +Prima dell'inventario ufficiale validare etichette e stampa SAM su un campione, +con movimentazioni ferme e dati ERP/WMS coerenti. Il perimetro provvisorio e' +guidato dai prodotti/lotti WMS; le limitazioni sono in specifica_inventario.md. + +## Ritorno alla precedente monolista + +Con programmi chiusi e senza modifiche locali ai sorgenti: + +```bat +git switch --detach warehouse-monolista-2.0 +``` + +Oppure usare il commit precedente annotato, se il PC partiva da un'altra +versione. Il nuovo inventario non modifica lo schema o i dati persistenti, +quindi il suo solo aggiornamento non richiede rollback SQL. Se sono state +applicate anche patch mancanti di versioni precedenti, valutarne separatamente +il ripristino usando il backup: tornare al vecchio codice non annulla il DB. diff --git a/inventario.py b/inventario.py new file mode 100644 index 0000000..9614876 --- /dev/null +++ b/inventario.py @@ -0,0 +1,234 @@ +"""Dated inventory reconciliation window, using the shared desktop UI lifecycle.""" + +from __future__ import annotations + +import asyncio +import tkinter as tk +from datetime import date +from decimal import Decimal +from tkinter import filedialog, messagebox, ttk + +import customtkinter as ctk + +from busy_overlay import InlineBusyOverlay +from gestione_aree import AsyncRunner +from inventory_service import (DETAIL_KEYS, LOT_KEYS, SUMMARY_KEYS, detail_values, + export_inventory, inventory_cutoff, load_inventory, status_text) +from locale_text import load_locale_catalog, text as loc_text +from runtime_support import log_exception +from ui_tables import style_treeview, zebra_tag +from ui_theme import theme_color, theme_font, theme_section, theme_value +from version_info import module_version, versioned_title +from window_placement import place_window_fullsize_below_parent_later + +__version__ = module_version(__name__) +KEYS = SUMMARY_KEYS + + +def display_number(value) -> str: + """Keep zeros visible and unknown values distinct from numeric stock.""" + if value is None: + return "?" + if isinstance(value, Decimal): + return format(value, "f").rstrip("0").rstrip(".") if value.as_tuple().exponent < 0 else str(value) + return str(value) + + +class InventarioWindow(ctk.CTkToplevel): + """Read-only, single-instance launcher child; DB and XLSX work are asynchronous.""" + + def __init__(self, parent, db_client, session=None): + super().__init__(parent) + self.db_client = db_client + self.session = session + self._catalog = load_locale_catalog() + self._theme = theme_section("inventory_window", theme_section("search_window", {})) + self._async = AsyncRunner(self) + self._busy = InlineBusyOverlay(self, self._theme) + self._loading = False + self._report = None + self._sort_column = "Product" + self._descending = False + self._rows = [] + self.var_date = tk.StringVar(value=date.today().strftime("%d/%m/%Y")) + self.var_status = tk.StringVar(value=self._t("inventory.scope")) + self.title(versioned_title(self._t("inventory.title"), __name__)) + self.geometry(str(theme_value(self._theme, "window_geometry", "1200x720"))) + self.minsize(*theme_value(self._theme, "window_minsize", [900, 560])) + self.configure(fg_color=theme_color(self._theme, "window_fg_color", ["#efefef", "#2f2f2f"])) + self._build_ui() + + def _t(self, key: str) -> str: + return loc_text(key, catalog=self._catalog, default=key) + + def _build_ui(self): + self.grid_columnconfigure(0, weight=1) + self.grid_rowconfigure(3, weight=3) + self.grid_rowconfigure(5, weight=1) + top = ctk.CTkFrame(self, fg_color=theme_color(self._theme, "toolbar_frame_fg_color", "#d7d7d7")) + top.grid(row=0, column=0, sticky="ew", padx=8, pady=8) + top.grid_columnconfigure(3, weight=1) + font = theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 11, "bold")) + ctk.CTkLabel(top, text=self._t("inventory.date"), font=font).grid(row=0, column=0, padx=6) + self.date_entry = ctk.CTkEntry(top, textvariable=self.var_date, width=130) + self.date_entry.grid(row=0, column=1, padx=6) + self.date_entry.bind("", lambda _: self._load()) + self.btn_load = ctk.CTkButton(top, text=self._t("inventory.load"), command=self._load, font=font) + self.btn_load.grid(row=0, column=2, padx=6) + self.btn_export = ctk.CTkButton(top, text=self._t("inventory.export"), command=self._export, + font=font, state="disabled") + self.btn_export.grid(row=0, column=4, padx=6) + ctk.CTkLabel(self, text=self._t("inventory.notice") + "\n" + self._t("inventory.scope") + + "\n" + self._t("inventory.history_notice"), anchor="w", justify="left", + wraplength=1000).grid(row=1, column=0, sticky="ew", padx=10) + ctk.CTkLabel(self, textvariable=self.var_status, anchor="w", justify="left", + wraplength=1000).grid(row=2, column=0, sticky="ew", padx=10, pady=5) + self.tree = self._make_tree(3, KEYS) + self.tree.bind("<>", self._select) + ctk.CTkLabel(self, text=self._t("inventory.detail"), anchor="w").grid(row=4, column=0, sticky="ew", padx=10) + tabs = ttk.Notebook(self) + tabs.grid(row=5, column=0, sticky="nsew", padx=8, pady=(0, 8)) + lot_page, detail_page = ttk.Frame(tabs), ttk.Frame(tabs) + for page in (lot_page, detail_page): + page.grid_rowconfigure(0, weight=1) + page.grid_columnconfigure(0, weight=1) + tabs.add(lot_page, text=self._t("inventory.lot_sheet")) + tabs.add(detail_page, text=self._t("inventory.detail_sheet")) + self.lot_tree = self._make_tree(0, LOT_KEYS, lot_page) + self.detail_tree = self._make_tree(0, DETAIL_KEYS, detail_page) + + def _make_tree(self, row, keys, parent=None): + wrap = ctk.CTkFrame(parent if parent is not None else self) + wrap.grid(row=row, column=0, sticky="nsew", padx=8, pady=(0, 8)) + wrap.grid_columnconfigure(0, weight=1) + wrap.grid_rowconfigure(0, weight=1) + tree = ttk.Treeview(wrap, columns=keys, show="headings", selectmode="browse") + style_treeview(tree, style_name="Inventory.Treeview", rowheight=24) + tree.tag_configure("difference", foreground=theme_value(self._theme, "difference_color", "#9b3900")) + tree.tag_configure("unknown", foreground=theme_value(self._theme, "unknown_color", "#aa0000")) + for key in keys: + tree.heading(key, text=self._t("inventory.col." + key)) + tree.column(key, width=250 if key in ("Description", "Status") else 120, + anchor="e" if key in KEYS[3:-1] or key in ("Quantity", "SamQuantity") else "w") + if keys == KEYS: + tree.heading(key, command=lambda k=key: self._sort(k)) + sy = ttk.Scrollbar(wrap, orient="vertical", command=tree.yview) + sx = ttk.Scrollbar(wrap, orient="horizontal", command=tree.xview) + tree.configure(yscrollcommand=sy.set, xscrollcommand=sx.set) + tree.grid(row=0, column=0, sticky="nsew") + sy.grid(row=0, column=1, sticky="ns") + sx.grid(row=1, column=0, sticky="ew") + return tree + + def _set_loading(self, value): + self._loading = value + state = "disabled" if value else "normal" + self.btn_load.configure(state=state) + self.date_entry.configure(state=state) + self.btn_export.configure(state="normal" if not value and self._report and self._rows else "disabled") + + def _load(self): + if self._loading: + return + value = self.var_date.get() + try: + inventory_cutoff(value) + except ValueError: + messagebox.showerror(self._t("inventory.title"), self._t("inventory.bad_date"), parent=self) + return + self._report = None + self._rows = [] + self.tree.delete(*self.tree.get_children()) + self.detail_tree.delete(*self.detail_tree.get_children()) + self.lot_tree.delete(*self.lot_tree.get_children()) + self.var_status.set(self._t("inventory.busy")) + self._set_loading(True) + self._async.run(load_inventory(self.db_client, value), self._loaded, self._error, + busy=self._busy, message=self._t("inventory.busy")) + + def _loaded(self, report): + self._report = report + self._rows = list(report.rows) + self._set_loading(False) + self._render() + source = lambda key: str(report.metadata.get(key) or "?")[:10] + self.var_status.set(self._t("inventory.loaded").format( + date=report.selected_date.strftime("%d/%m/%Y"), count=len(report.rows), + unknown=sum(bool(r["Issues"]) for r in report.rows), + wms=source("WMS_MAX"), sam=source("SAM_MAX"))) + if report.selected_date == date.today(): + self.var_status.set(self.var_status.get() + "\n" + self._t("inventory.today")) + + def _render(self): + self.tree.delete(*self.tree.get_children()) + self.detail_tree.delete(*self.detail_tree.get_children()) + self.lot_tree.delete(*self.lot_tree.get_children()) + for index, row in enumerate(self._rows): + tag = "unknown" if row["Issues"] else ("difference" if row["Difference"] else "") + self.tree.insert("", "end", iid=str(index), + values=[display_number(row[k]) for k in KEYS[:-1]] + [status_text(row, self._t)], + tags=(zebra_tag(index), tag)) + + def _sort(self, key): + if self._loading: + return + self._descending = not self._descending if self._sort_column == key else False + self._sort_column = key + def sort_value(row): + value = status_text(row, self._t) if key == "Status" else row[key] + return (value is None, value.casefold() if isinstance(value, str) else value if value is not None else ZERO_SORT) + self._rows.sort(key=sort_value, reverse=self._descending) + self._render() + + def _select(self, _event=None): + self.detail_tree.delete(*self.detail_tree.get_children()) + self.lot_tree.delete(*self.lot_tree.get_children()) + selected = self.tree.selection() + if not selected or self._report is None: + return + product = self._rows[int(selected[0])]["Product"] + for i, row in enumerate(r for r in self._report.lots if r["Product"] == product): + self.lot_tree.insert("", "end", + values=[display_number(row[k]) for k in LOT_KEYS[:-1]] + [status_text(row, self._t)], + tags=(zebra_tag(i), "unknown" if row["Issues"] else "difference" if row["Difference"] else "")) + details = [r for r in self._report.details if r["Product"] == product] + for i, row in enumerate(details): + self.detail_tree.insert("", "end", values=[display_number(v) for v in detail_values(row, self._t)], + tags=(zebra_tag(i),)) + + def _error(self, error): + self._set_loading(False) + log_exception(__name__, error, context="inventory report/export") + self.var_status.set(self._t("inventory.failed")) + messagebox.showerror(self._t("inventory.title"), str(error), parent=self) + + def _export(self): + if self._loading or not self._report or not self._rows: + return + report = self._report + path = filedialog.asksaveasfilename(parent=self, defaultextension=".xlsx", + filetypes=[("Excel", "*.xlsx")], initialfile=f"inventario_{report.selected_date:%Y%m%d}.xlsx") + if not path: + return + self._set_loading(True) + self._async.run(asyncio.to_thread(export_inventory, report, path, + headers=[self._t("inventory.col." + k) for k in KEYS], + detail_headers=[self._t("inventory.col." + k) for k in DETAIL_KEYS], + translate=self._t, ordered_rows=list(self._rows)), + lambda _: self._exported(path), self._error, + busy=self._busy, message=self._t("inventory.export_busy")) + + def _exported(self, path): + self._set_loading(False) + messagebox.showinfo(self._t("inventory.title"), self._t("inventory.exported").format(path=path), parent=self) + + +ZERO_SORT = Decimal(0) + + +def open_inventario_window(parent, db_client, session=None): + """Create the launcher-managed window with the same placement as other forms.""" + win = InventarioWindow(parent, db_client, session=session) + place_window_fullsize_below_parent_later(parent, win) + win.bind("", lambda _: win.destroy()) + return win diff --git a/inventory_report.sql b/inventory_report.sql new file mode 100644 index 0000000..ac1b7ff --- /dev/null +++ b/inventory_report.sql @@ -0,0 +1,155 @@ +-- Read-only runtime query: cutoff and sam_cutoff are exclusive next-day bounds. +-- Writes only session-local temp tables; never alters SAM/WMS objects or stock. +SET NOCOUNT ON; +SET XACT_ABORT ON; +SET LOCK_TIMEOUT 15000; +DECLARE @cutoff datetime2 = :cutoff, @sam_cutoff float = :sam_cutoff; +DECLARE @warehouse int; +IF (SELECT COUNT(*) FROM SAMA1.dbo.ANAMAG + WHERE LTRIM(RTRIM(DESCR))='Magazzino Principale')<>1 + THROW 51200, 'Magazzino Principale SAM assente o ambiguo.', 1; +SELECT @warehouse=ID FROM SAMA1.dbo.ANAMAG +WHERE LTRIM(RTRIM(DESCR))='Magazzino Principale'; +SELECT ID INTO #inv_slots FROM SAMA1.dbo.ALLMAG WHERE IDANAMAG=@warehouse; +CREATE UNIQUE CLUSTERED INDEX ix_slots ON #inv_slots(ID); + +SELECT LTRIM(RTRIM(Attributo)) COLLATE DATABASE_DEFAULT AS Pallet, IDCella, + SUM(CASE Tipo WHEN 'V' THEN CAST(PesoUnitario AS decimal(28,6)) + WHEN 'P' THEN -CAST(PesoUnitario AS decimal(28,6)) END) AS Balance +INTO #inv_balance FROM dbo.MagazziniPallet +WHERE DataMagazzino<@cutoff AND Tipo IN ('P','V') +GROUP BY LTRIM(RTRIM(Attributo)),IDCella; +CREATE INDEX ix_balance ON #inv_balance(Pallet); +SELECT Pallet, COUNT(CASE WHEN Balance>0 THEN 1 END) AS Locations, + COUNT(CASE WHEN Balance<0 THEN 1 END) AS NegativeBalances, + MAX(CASE WHEN IDCella=9999 AND Balance>0 THEN 1 ELSE 0 END) AS Shipped +INTO #inv_position FROM #inv_balance GROUP BY Pallet; +CREATE UNIQUE CLUSTERED INDEX ix_position ON #inv_position(Pallet); +SELECT b.*,CONCAT(RTRIM(c.Corsia),'.',RTRIM(c.Colonna),'.',RTRIM(c.Fila)) AS Location +INTO #inv_stock FROM #inv_balance b +JOIN dbo.Celle c ON c.ID=b.IDCella +JOIN dbo.Aree a ON a.ID=c.IDArea +JOIN dbo.Magazzini w ON w.ID=a.IDMagazzino +WHERE b.Balance>0 AND (b.IDCella=1000 OR + (b.IDCella<>9999 AND UPPER(RTRIM(w.Descrizione)) IN ('MDE5','MDE6'))); +CREATE INDEX ix_stock ON #inv_stock(Pallet); + +-- First change AFTER cutoff supplies the OLD serial valid at cutoff. +-- Same-timestamp ties have no ordering key: flag them instead of certifying them. +SELECT IDLOTSER,MIN(AGGIORNAMENTO) AS FirstAfter +INTO #inv_change_time FROM SAMA1.dbo.EXTTACLOTSER +WHERE AGGIORNAMENTO>=@cutoff GROUP BY IDLOTSER; +CREATE UNIQUE CLUSTERED INDEX ix_time ON #inv_change_time(IDLOTSER); +SELECT h.IDLOTSER,MIN(RTRIM(h.EXNUMSER)) COLLATE DATABASE_DEFAULT AS Serial, + CASE WHEN COUNT(*)>1 THEN 1 ELSE 0 END AS AssignmentIssue +INTO #inv_old FROM SAMA1.dbo.EXTTACLOTSER h +JOIN #inv_change_time t ON t.IDLOTSER=h.IDLOTSER AND t.FirstAfter=h.AGGIORNAMENTO +GROUP BY h.IDLOTSER; +CREATE UNIQUE CLUSTERED INDEX ix_old ON #inv_old(IDLOTSER); + +SELECT ls.ID,ls.IDARTICO,RTRIM(ls.NUMLOT) COLLATE DATABASE_DEFAULT AS Lot, + COALESCE(o.Serial,RTRIM(ls.NUMSER) COLLATE DATABASE_DEFAULT) AS Serial, + ISNULL(o.AssignmentIssue,0) AS AssignmentIssue +INTO #inv_wms_labels FROM SAMA1.dbo.LOTSER ls +LEFT JOIN #inv_old o ON o.IDLOTSER=ls.ID +WHERE EXISTS(SELECT 1 FROM #inv_stock s WHERE s.Pallet= + LEFT(COALESCE(o.Serial,RTRIM(ls.NUMSER) COLLATE DATABASE_DEFAULT),6)); + +-- Scope by PRODUCT + LOT in WMS, not all products and not a P% convention. +SELECT DISTINCT IDARTICO,Lot INTO #inv_scope FROM #inv_wms_labels; +CREATE UNIQUE CLUSTERED INDEX ix_scope ON #inv_scope(IDARTICO,Lot); +SELECT ls.ID,ls.IDARTICO,RTRIM(ls.NUMLOT) COLLATE DATABASE_DEFAULT AS Lot, + COALESCE(o.Serial,RTRIM(ls.NUMSER) COLLATE DATABASE_DEFAULT) AS Serial, + ISNULL(o.AssignmentIssue,0) AS AssignmentIssue +INTO #inv_labels FROM SAMA1.dbo.LOTSER ls +JOIN #inv_scope sc ON sc.IDARTICO=ls.IDARTICO + AND sc.Lot=RTRIM(ls.NUMLOT) COLLATE DATABASE_DEFAULT +LEFT JOIN #inv_old o ON o.IDLOTSER=ls.ID; +CREATE UNIQUE CLUSTERED INDEX ix_labels ON #inv_labels(ID); + +-- SAM balance per CONTAINER; B/C are never fabricated as SAM minus A. +SELECT l.ID,SUM(CAST(g.QTTGIAI AS decimal(28,6))) AS Quantity +INTO #inv_now FROM #inv_labels l +JOIN SAMA1.dbo.GIAMAG g ON g.IDARTICO=l.ID +JOIN #inv_slots s ON s.ID=g.IDMAG GROUP BY l.ID; + +SELECT m.IDARTICO AS ID,m.DATMOV,CAST(m.QTAINV AS decimal(28,6)) AS Quantity, + RTRIM(c.CODICE) AS Cause, + CASE WHEN sp.ID IS NOT NULL THEN + CASE c.QTGIUP WHEN '+' THEN 1 WHEN '-' THEN -1 ELSE 0 END ELSE 0 END + + CASE WHEN sa.ID IS NOT NULL THEN + CASE c.QTGIUA WHEN '+' THEN 1 WHEN '-' THEN -1 ELSE 0 END ELSE 0 END AS Sign, + CASE WHEN sa.ID IS NOT NULL AND c.QTGIUA='+' THEN 1 ELSE 0 END AS Receipt, + CASE WHEN c.ID IS NULL OR + (sp.ID IS NOT NULL AND ISNULL(RTRIM(c.QTGIUP),'') NOT IN ('','+','-')) OR + (sa.ID IS NOT NULL AND ISNULL(RTRIM(c.QTGIUA),'') NOT IN ('','+','-')) + THEN 1 ELSE 0 END AS CauseIssue +INTO #inv_moves FROM #inv_labels l +JOIN SAMA1.dbo.MOVMAG m ON m.IDARTICO=l.ID +LEFT JOIN SAMA1.dbo.CAUMOV c ON c.ID=m.IDCAUMOV +LEFT JOIN #inv_slots sp ON sp.ID=m.IDMAGPAR +LEFT JOIN #inv_slots sa ON sa.ID=m.IDMAGARR +WHERE sp.ID IS NOT NULL OR sa.ID IS NOT NULL; +CREATE INDEX ix_moves ON #inv_moves(ID); +SELECT ID, + SUM(CASE WHEN DATMOV>=@sam_cutoff THEN Quantity*Sign ELSE 0 END) AS AfterQuantity, + SUM(CASE WHEN DATMOV<@sam_cutoff AND Cause='CP' THEN Quantity*Sign END) AS Nominal, + SUM(CASE WHEN DATMOV IS NULL OR Quantity IS NULL OR CauseIssue=1 THEN 1 ELSE 0 END) AS MovementIssues, + SUM(CASE WHEN DATMOV<@sam_cutoff AND Receipt=1 AND Cause<>'CP' THEN 1 ELSE 0 END) AS OtherReceipts +INTO #inv_quantities FROM #inv_moves GROUP BY ID; + +CREATE TABLE #inv_result ( + Kind varchar(8) NULL, Component varchar(8) NULL, + Product nvarchar(255) NULL, Description nvarchar(1000) NULL, Unit nvarchar(32) NULL, + ContainerId int NULL, Lot nvarchar(255) NULL, Serial nvarchar(255) NULL, + Pallet nvarchar(64) NULL, Cell int NULL, Location nvarchar(255) NULL, + Balance decimal(38,6) NULL, Quantity decimal(38,6) NULL, SamQuantity decimal(38,6) NULL, + Locations int NULL, NegativeBalances int NULL, Shipped int NULL, + AssignmentIssue int NULL, MovementIssues int NULL, OtherReceipts int NULL, + SourceDate datetime2 NULL +); +INSERT INTO #inv_result +SELECT CAST('ROW' AS varchar(8)) AS Kind, + CAST(CASE WHEN s.Pallet IS NOT NULL THEN 'A' + WHEN LEFT(l.Serial,6)='000000' THEN 'C' + WHEN ISNULL(p.Locations,0)>0 OR ISNULL(p.NegativeBalances,0)>0 THEN 'X' + WHEN LEN(l.Serial)<8 OR SUBSTRING(l.Serial,7,1)<>'/' THEN 'X' + ELSE 'B' END AS varchar(8)) AS Component, + RTRIM(a.CODICE) AS Product,RTRIM(a.DESCR) AS Description,RTRIM(a.UMI) AS Unit, + l.ID AS ContainerId,l.Lot,l.Serial, + LEFT(l.Serial,6) AS Pallet,s.IDCella AS Cell,s.Location,s.Balance, + CASE WHEN s.Pallet IS NOT NULL THEN q.Nominal + ELSE ISNULL(n.Quantity,0)-ISNULL(q.AfterQuantity,0) END AS Quantity, + ISNULL(n.Quantity,0)-ISNULL(q.AfterQuantity,0) AS SamQuantity, + ISNULL(p.Locations,0) AS Locations,ISNULL(p.NegativeBalances,0) AS NegativeBalances, + ISNULL(p.Shipped,0) AS Shipped,l.AssignmentIssue, + ISNULL(q.MovementIssues,0) AS MovementIssues,ISNULL(q.OtherReceipts,0) AS OtherReceipts, + CAST(NULL AS datetime2) AS SourceDate +FROM #inv_labels l +LEFT JOIN SAMA1.dbo.ARTICO a ON a.ID=l.IDARTICO +LEFT JOIN #inv_now n ON n.ID=l.ID +LEFT JOIN #inv_quantities q ON q.ID=l.ID +LEFT JOIN #inv_position p ON p.Pallet=LEFT(l.Serial,6) +LEFT JOIN #inv_stock s ON s.Pallet=LEFT(l.Serial,6) +WHERE s.Pallet IS NOT NULL OR ISNULL(n.Quantity,0)-ISNULL(q.AfterQuantity,0)<>0 + OR ISNULL(q.MovementIssues,0)>0; + +-- WMS presence with no recognizable label must remain visible. +INSERT INTO #inv_result(Kind,Component,Pallet,Cell,Location,Balance,Locations, + NegativeBalances,Shipped,AssignmentIssue,MovementIssues,OtherReceipts) +SELECT 'ROW','A',s.Pallet,s.IDCella,s.Location,s.Balance,p.Locations, + p.NegativeBalances,p.Shipped,0,0,0 +FROM #inv_stock s JOIN #inv_position p ON p.Pallet=s.Pallet +WHERE NOT EXISTS(SELECT 1 FROM #inv_wms_labels l WHERE LEFT(l.Serial,6)=s.Pallet); + +-- One result set, as required by the shared async SQL client. +INSERT INTO #inv_result(Kind,Component,SourceDate) +SELECT 'META','WMS_MAX',MAX(DataMagazzino) FROM dbo.MagazziniPallet; +INSERT INTO #inv_result(Kind,Component,SourceDate) +SELECT 'META','SAM_MAX',DATEADD(day,CAST(MAX(DATMOV) AS int),CAST('1899-12-30' AS datetime2)) +FROM SAMA1.dbo.MOVMAG; +INSERT INTO #inv_result(Kind,Component,SourceDate) +SELECT 'META','HIST_MIN',MIN(AGGIORNAMENTO) FROM SAMA1.dbo.EXTTACLOTSER; +INSERT INTO #inv_result(Kind,Component,Quantity) +SELECT 'META','UNDATED',COUNT(*) FROM dbo.MagazziniPallet WHERE DataMagazzino IS NULL; +SELECT * FROM #inv_result; diff --git a/inventory_service.py b/inventory_service.py new file mode 100644 index 0000000..b4c8cdc --- /dev/null +++ b/inventory_service.py @@ -0,0 +1,271 @@ +"""Read-only WMS/SAM reconciliation by product and lot; see specifica_inventario.md.""" +from __future__ import annotations + +from dataclasses import dataclass +from datetime import date, datetime, time, timedelta +from decimal import Decimal +from pathlib import Path +from typing import Any + +from version_info import module_version + +__version__ = module_version(__name__) +SQL_PATH = Path(__file__).with_name("inventory_report.sql") +ZERO = Decimal("0") +SUMMARY_KEYS = ("Product", "Description", "Unit", "UDCs", "Shelved", "NonShelved", + "WMS", "PackingUDCs", "Packing", "LooseContainers", "Loose", + "Reconstructed", "SAM", "InitialDifference", "Difference", "Status") +DETAIL_KEYS = ("Component", "Product", "Lot", "Pallet", "ContainerId", "Serial", + "Location", "Quantity", "SamQuantity", "Status") +LOT_KEYS = ("Product", "Lot") + SUMMARY_KEYS[2:] + + +def inventory_cutoff(value: str, *, today: date | None = None) -> tuple[date, datetime, int]: + """Parse a day, not an instant; use the exclusive following midnight.""" + selected = datetime.strptime(value.strip(), "%d/%m/%Y").date() + if selected > (today or date.today()) or selected < date(2010, 1, 1): + raise ValueError("date_range") + cutoff = datetime.combine(selected + timedelta(days=1), time.min) + return selected, cutoff, (cutoff - datetime(1899, 12, 30)).days + + +def number(value: Any) -> Decimal: + """Convert SQL decimals without introducing floating-point summation.""" + return Decimal(str(value)) if value is not None else ZERO + + +@dataclass +class InventoryReport: + selected_date: date + rows: list[dict[str, Any]] + details: list[dict[str, Any]] + metadata: dict[str, Any] + lots: list[dict[str, Any]] + + +def _bucket(product, description, unit, lot=""): + return dict(Product=product, Description=description, Unit=unit, Lot=lot, + UDCs=set(), PackingUDCs=set(), LooseContainers=set(), + Shelved=ZERO, NonShelved=ZERO, Packing=ZERO, Loose=ZERO, SAM=ZERO, + Issues=set(), Invalid=set()) + + +def build_report(selected_date: date, records: list[dict[str, Any]]) -> InventoryReport: + """Count each container once; retain anomalies instead of manufacturing balance. + + A uses production receipt quantities, independently of current SAM balance. + B/C use the dated container balance. X is unclassified/conflicting SAM stock; + it contributes to SAM, never silently to B. Aggregation begins at product/lot. + """ + metadata = {r["Component"]: (r.get("Quantity") if r["Component"] == "UNDATED" + else r.get("SourceDate")) + for r in records if r["Kind"] == "META"} + history_start = metadata.get("HIST_MIN") + history_unknown = not history_start or selected_date < history_start.date() + products, lots, details, seen = {}, {}, [], {} + for record in records: + if record["Kind"] == "META": + continue + r = dict(record) + pallet = str(r.get("Pallet") or "").strip() + product = str(r.get("Product") or "").strip() or f"? UDC {pallet}" + lot = str(r.get("Lot") or "").strip() + unit = str(r.get("Unit") or "").strip().upper() + component = r["Component"] + quantity = None if r.get("Quantity") is None else number(r["Quantity"]) + sam_quantity = None if r.get("SamQuantity") is None else number(r["SamQuantity"]) + issues, invalid = set(), set() + if unit not in {"NR", "PZ", "PCS"}: + issues.add("unit") + invalid.update(("A", "B", "C", "SAM")) + if r.get("AssignmentIssue") or history_unknown: + issues.add("history") + invalid.update(("A", "B", "C")) + if metadata.get("UNDATED"): + issues.add("undated") + invalid.update(("A", "B", "C")) + if r.get("MovementIssues") or sam_quantity is None: + issues.add("movements") + invalid.update(("A", "B", "C", "SAM")) + if sam_quantity is not None and sam_quantity < 0: + issues.add("negative") + invalid.add("SAM") + serial = str(r.get("Serial") or "").strip() + if len(serial) < 8 or serial[6:7] != "/" or not serial[7:].strip(): + issues.add("serial") + invalid.add(component) + if component == "A": + if quantity is None or quantity <= 0 or r.get("OtherReceipts"): + issues.add("content") + invalid.add("A") + if r.get("Locations") != 1: + issues.add("locations") + invalid.add("A") + if number(r.get("Balance")) != 1 or r.get("NegativeBalances"): + issues.add("balance") + invalid.add("A") + if r.get("Shipped"): + issues.add("shipped") + invalid.add("A") + elif component in ("B", "C"): + if quantity is None or quantity <= 0: + issues.add("content") + invalid.add(component) + if r.get("Shipped") or r.get("Locations") or r.get("NegativeBalances"): + issues.add("shipped" if r.get("Shipped") else "outside") + invalid.add(component) + else: + issues.add("shipped" if r.get("Shipped") else "outside") + bucket = lots.setdefault((product, lot), _bucket(product, r.get("Description") or "", unit, lot)) + if bucket["Unit"] != unit: + issues.add("unit") + invalid.update(("A", "B", "C", "SAM")) + bucket["Issues"].update(issues) + bucket["Invalid"].update(invalid) + if component == "A": + bucket["UDCs"].add(pallet) + elif component == "B": + bucket["PackingUDCs"].add(pallet) + elif component == "C": + bucket["LooseContainers"].add(r.get("ContainerId")) + # Anomaly details can have several locations, but SAM must not be doubled. + identity = r.get("ContainerId") or ("missing", pallet) + key = (product, lot, identity) + fingerprint = (component, quantity, sam_quantity, pallet) + if key not in seen: + bucket["SAM"] += sam_quantity or ZERO + field = ("NonShelved" if r.get("Cell") == 1000 else "Shelved") if component == "A" else { + "B": "Packing", "C": "Loose"}.get(component) + if field and quantity is not None: + bucket[field] += quantity + seen[key] = fingerprint + elif seen[key] != fingerprint: + bucket["Issues"].add("duplicate") + bucket["Invalid"].update(("A", "B", "C", "SAM")) + issues.add("duplicate") + details.append(dict(Component=component, Product=product, Lot=lot, + Pallet="" if pallet == "000000" else pallet, + ContainerId=r.get("ContainerId"), Serial=serial, + Cell=r.get("Cell"), Location=r.get("Location") or "", + Quantity=None if component in invalid else quantity, + SamQuantity=None if "SAM" in invalid else sam_quantity, + Issues=tuple(sorted(issues)))) + # Aggregate lots without summing their distinct-UDC counts. + for bucket in lots.values(): + total = products.setdefault(bucket["Product"], _bucket( + bucket["Product"], bucket["Description"], bucket["Unit"])) + if total["Unit"] != bucket["Unit"]: + total["Issues"].add("unit") + total["Invalid"].update(("A", "B", "C", "SAM")) + for key in ("UDCs", "PackingUDCs", "LooseContainers", "Issues", "Invalid"): + total[key].update(bucket[key]) + for key in ("Shelved", "NonShelved", "Packing", "Loose", "SAM"): + total[key] += bucket[key] + def finish(row): + invalid = row.pop("Invalid") + for key in ("UDCs", "PackingUDCs", "LooseContainers"): + row[key] = len(row[key]) + if "A" in invalid: + row["Shelved"] = row["NonShelved"] = None + for component, field in (("B", "Packing"), ("C", "Loose"), ("SAM", "SAM")): + if component in invalid: + row[field] = None + row["WMS"] = add_known(row["Shelved"], row["NonShelved"]) + row["Reconstructed"] = add_known(row["WMS"], row["Packing"], row["Loose"]) + row["InitialDifference"] = subtract_known(row["SAM"], row["WMS"]) + row["Difference"] = subtract_known(row["SAM"], row["Reconstructed"]) + row["Issues"] = tuple(sorted(row["Issues"])) + return row + lot_rows = [finish(lots[k]) for k in sorted(lots)] + product_rows = [finish(products[k]) for k in sorted(products)] + for row in product_rows: + if row["Difference"] == 0 and any( + lot["Product"] == row["Product"] and lot["Difference"] not in (None, ZERO) + for lot in lot_rows): + row["Issues"] = tuple(sorted(set(row["Issues"]) | {"lot_offsets"})) + return InventoryReport(selected_date, + product_rows, + sorted(details, key=lambda r: (r["Product"], r["Lot"], r["Component"], + r["Pallet"], r["Serial"], str(r["Cell"]))), + metadata, lot_rows) + + +def add_known(*values): + return None if any(v is None for v in values) else sum(values, ZERO) + + +def subtract_known(left, right): + return None if left is None or right is None else left - right + + +async def load_inventory(db_client, value: str) -> InventoryReport: + """Use the existing asynchronous DB client; no commit or stock mutation.""" + selected, cutoff, sam_cutoff = inventory_cutoff(value) + result = await db_client.query_json(SQL_PATH.read_text(encoding="utf-8"), + {"cutoff": cutoff, "sam_cutoff": sam_cutoff}, as_dict_rows=True) + return build_report(selected, result["rows"]) + + +def status_text(row, translate): + if row["Issues"]: + return "; ".join(translate("inventory.issue." + issue) for issue in row["Issues"]) + return translate("inventory.match" if row["Difference"] == 0 else "inventory.mismatch") + + +def detail_values(row, translate): + """Use identical localized labels in GUI and exported container details.""" + values = dict(row) + values["Component"] = translate("inventory.component." + row["Component"]) + if not values["Location"] and row["Component"] in ("B", "C"): + values["Location"] = translate("inventory.inferred_location") + values["Status"] = "; ".join(translate("inventory.issue." + issue) for issue in row["Issues"]) + return [values[k] for k in DETAIL_KEYS] + + +def export_inventory(report: InventoryReport, path: str, *, headers=None, + detail_headers=None, translate, ordered_rows=None) -> None: + """Export product, lot and container views with typed cells and provenance.""" + from openpyxl import Workbook + from openpyxl.styles import Font, PatternFill + from openpyxl.utils import get_column_letter + + wb = Workbook() + ws = wb.active + ws.title = translate("inventory.title") + ws.append([translate("inventory.date"), report.selected_date]) + ws["B1"].number_format = "DD/MM/YYYY" + ws.append([translate("inventory.notice")]) + ws.append([translate("inventory.scope")]) + ws.append([translate("inventory.sources"), str(report.metadata)]) + ws.append([translate("inventory.history_notice")]) + ws.append(headers or [translate("inventory.col." + k) for k in SUMMARY_KEYS]) + for row in ordered_rows if ordered_rows is not None else report.rows: + ws.append([row[k] for k in SUMMARY_KEYS[:-1]] + [status_text(row, translate)]) + ls = wb.create_sheet(translate("inventory.lot_sheet")) + ls.append([translate("inventory.col." + k) for k in LOT_KEYS]) + for row in report.lots: + ls.append([row[k] for k in LOT_KEYS[:-1]] + [status_text(row, translate)]) + ds = wb.create_sheet(translate("inventory.detail_sheet")) + ds.append(detail_headers or [translate("inventory.col." + k) for k in DETAIL_KEYS]) + for row in report.details: + ds.append(detail_values(row, translate)) + for sheet, header_row in ((ws, 6), (ls, 1), (ds, 1)): + sheet.freeze_panes = f"A{header_row + 1}" + sheet.auto_filter.ref = f"A{header_row}:{get_column_letter(sheet.max_column)}{sheet.max_row}" + for cell in sheet[header_row]: + cell.font = Font(bold=True, color="000000") + cell.fill = PatternFill("solid", fgColor="BFC4CA") + for row in sheet.iter_rows(): + for cell in row: + if isinstance(cell.value, str): + cell.data_type = "s" + elif isinstance(cell.value, (Decimal, float, int)): + cell.number_format = '#,##0.######;[Red]-#,##0.######;0' + if cell.row > header_row and cell.row % 2 == 0: + cell.fill = PatternFill("solid", fgColor="F0F0F0") + for col in range(1, sheet.max_column + 1): + sheet.column_dimensions[get_column_letter(col)].width = 24 + try: + wb.save(path) + finally: + wb.close() diff --git a/locale.json b/locale.json index 51ad915..191be17 100644 --- a/locale.json +++ b/locale.json @@ -1,6 +1,68 @@ { "default_language": "IT", "IT": { + "inventory.title": "Inventario", + "inventory.date": "Data (gg/mm/aaaa):", + "inventory.load": "Calcola inventario", + "inventory.export": "Esporta XLSX", + "inventory.notice": "A: UDC WMS. B: UDC fuori WMS, confezionamento presunto. C: bag/vasche senza UDC. Residuo = SAM - (A+B+C). '?' indica dati non determinabili.", + "inventory.scope": "Perimetro provvisorio: solo prodotti/lotti delle UDC in aree 5 e 6 o non scaffalate alla data. Non e' l'inventario completo SAM.", + "inventory.history_notice": "Ricostruzione da movimenti e storico NUMSER disponibile, non inventario fisico certificato. Validare le etichette e la completezza dello storico.", + "inventory.sources": "Ultimi movimenti nelle fonti (non data di aggiornamento del backup)", + "inventory.detail": "Lotti e contenitori del prodotto selezionato", + "inventory.detail_sheet": "Contenitori", + "inventory.lot_sheet": "Lotti", + "inventory.inferred_location": "Confezionamento (dedotto)", + "inventory.component.A": "A - WMS", + "inventory.component.B": "B - UDC fuori WMS", + "inventory.component.C": "C - Senza UDC", + "inventory.component.X": "X - Anomalia / fuori perimetro", + "inventory.today": "Giornata corrente non ancora conclusa: il risultato comprende solo i movimenti gia' registrati.", + "inventory.bad_date": "Inserisci una data valida gg/mm/aaaa, dal 01/01/2010 a oggi.", + "inventory.busy": "Ricostruisco l'inventario alla data scelta...", + "inventory.loaded": "Inventario al {date} (fine giornata) | Prodotti: {count} | Da verificare: {unknown}\nUltimo movimento WMS: {wms} | Ultimo movimento SAM: {sam}. Eseguire a movimentazioni ferme; verificare che i backup siano coerenti.", + "inventory.failed": "Operazione non completata. Nessun dato del magazzino modificato.", + "inventory.export_busy": "Esporto inventario...", + "inventory.exported": "File creato:\n{path}", + "inventory.match": "Saldo coerente (nominale)", + "inventory.mismatch": "Differenza da verificare", + "inventory.issue.content": "Contenuto UDC non determinabile", + "inventory.issue.locations": "UDC in piu' locazioni", + "inventory.issue.balance": "Saldo movimenti UDC anomalo", + "inventory.issue.unit": "Unita' di misura da verificare", + "inventory.issue.undated": "Movimenti WMS privi di data", + "inventory.issue.history": "Assegnazione storica non determinabile", + "inventory.issue.movements": "Movimenti o saldo SAM non determinabili", + "inventory.issue.negative": "Giacenza SAM negativa", + "inventory.issue.serial": "Seriale contenitore mancante o non valido", + "inventory.issue.shipped": "Spedita WMS ma presenza residua da verificare", + "inventory.issue.outside": "Presenza fuori perimetro / classificazione anomala", + "inventory.issue.duplicate": "Contenitore duplicato con dati incompatibili", + "inventory.issue.lot_offsets": "Differenze tra lotti si compensano: verificare il dettaglio", + "inventory.col.Product": "Prodotto", + "inventory.col.Description": "Descrizione", + "inventory.col.Unit": "UM", + "inventory.col.UDCs": "N. UDC WMS", + "inventory.col.Shelved": "Pezzi scaffalati", + "inventory.col.NonShelved": "Pezzi non scaffalati", + "inventory.col.WMS": "Pezzi WMS", + "inventory.col.SAM": "Pezzi SAM", + "inventory.col.Difference": "Residuo SAM-(A+B+C)", + "inventory.col.InitialDifference": "Differenza SAM-A", + "inventory.col.PackingUDCs": "N. UDC fuori WMS", + "inventory.col.Packing": "Pezzi B - UDC fuori WMS", + "inventory.col.LooseContainers": "N. contenitori senza UDC", + "inventory.col.Loose": "Pezzi C - Senza UDC", + "inventory.col.Reconstructed": "Totale A+B+C", + "inventory.col.Component": "Componente", + "inventory.col.Lot": "Lotto", + "inventory.col.ContainerId": "ID LOTSER", + "inventory.col.Serial": "Seriale contenitore", + "inventory.col.SamQuantity": "Giacenza SAM contenitore", + "inventory.col.Status": "Esito / anomalie", + "inventory.col.Pallet": "UDC", + "inventory.col.Location": "Cella alla data", + "inventory.col.Quantity": "Pezzi della componente", "launcher.window_title": "Warehouse 1.0.0", "launcher.operator": "Operatore: {display_name} ({login})", "launcher.reset_corsie": "Gestione Corsie", @@ -161,6 +223,68 @@ "scarico.msg.exec_error": "Scarico fallito:\n{error}" }, "ENG": { + "inventory.title": "Inventory", + "inventory.date": "Date (dd/mm/yyyy):", + "inventory.load": "Calculate inventory", + "inventory.export": "Export XLSX", + "inventory.notice": "A: WMS UDCs. B: UDCs outside WMS, inferred packaging location. C: bags/tubs without UDC. Residual = SAM - (A+B+C). '?' means undetermined data.", + "inventory.scope": "Provisional scope: only products/lots of UDCs in areas 5/6 or non-shelved at date. Not the complete SAM inventory.", + "inventory.history_notice": "Reconstruction from movements and available NUMSER history, not a certified physical inventory. Validate labels and history completeness.", + "inventory.sources": "Latest source movements (not backup update dates)", + "inventory.detail": "Lots and containers for the selected product", + "inventory.detail_sheet": "Containers", + "inventory.lot_sheet": "Lots", + "inventory.inferred_location": "Packaging (inferred)", + "inventory.component.A": "A - WMS", + "inventory.component.B": "B - UDCs outside WMS", + "inventory.component.C": "C - Without UDC", + "inventory.component.X": "X - Conflict / out of scope", + "inventory.today": "Today is still in progress: the result includes only movements already recorded.", + "inventory.bad_date": "Enter a valid dd/mm/yyyy date between 01/01/2010 and today.", + "inventory.busy": "Reconstructing inventory at the selected date...", + "inventory.loaded": "Inventory at {date} (end of day) | Products: {count} | To verify: {unknown}\nLatest WMS movement: {wms} | Latest SAM movement: {sam}. Run while stock movements are stopped; verify backup consistency.", + "inventory.failed": "Operation failed. No warehouse data was changed.", + "inventory.export_busy": "Exporting inventory...", + "inventory.exported": "File created:\n{path}", + "inventory.match": "Matching balance (nominal)", + "inventory.mismatch": "Difference to verify", + "inventory.issue.content": "UDC content cannot be determined", + "inventory.issue.locations": "UDC in multiple locations", + "inventory.issue.balance": "Abnormal UDC movement balance", + "inventory.issue.unit": "Unit of measure to verify", + "inventory.issue.undated": "Undated WMS movements", + "inventory.issue.history": "Historical assignment cannot be determined", + "inventory.issue.movements": "SAM movements or balance cannot be determined", + "inventory.issue.negative": "Negative SAM balance", + "inventory.issue.serial": "Missing or invalid container serial", + "inventory.issue.shipped": "WMS shipped with residual presence to verify", + "inventory.issue.outside": "Out-of-scope presence / abnormal classification", + "inventory.issue.duplicate": "Duplicate container with conflicting data", + "inventory.issue.lot_offsets": "Lot differences offset each other: inspect lot details", + "inventory.col.Product": "Product", + "inventory.col.Description": "Description", + "inventory.col.Unit": "UOM", + "inventory.col.UDCs": "WMS UDC count", + "inventory.col.Shelved": "Shelved pieces", + "inventory.col.NonShelved": "Non-shelved pieces", + "inventory.col.WMS": "WMS pieces", + "inventory.col.SAM": "SAM pieces", + "inventory.col.Difference": "Residual SAM-(A+B+C)", + "inventory.col.InitialDifference": "SAM-A difference", + "inventory.col.PackingUDCs": "UDCs outside WMS count", + "inventory.col.Packing": "B pieces - UDCs outside WMS", + "inventory.col.LooseContainers": "Unassigned container count", + "inventory.col.Loose": "C pieces - Without UDC", + "inventory.col.Reconstructed": "Total A+B+C", + "inventory.col.Component": "Component", + "inventory.col.Lot": "Lot", + "inventory.col.ContainerId": "LOTSER ID", + "inventory.col.Serial": "Container serial", + "inventory.col.SamQuantity": "Container SAM balance", + "inventory.col.Status": "Result / issues", + "inventory.col.Pallet": "UDC", + "inventory.col.Location": "Location at date", + "inventory.col.Quantity": "Component pieces", "launcher.window_title": "Warehouse 1.0.0", "launcher.operator": "Operator: {display_name} ({login})", "launcher.reset_corsie": "Aisle Management", diff --git a/main.py b/main.py index 889d467..9af8c66 100644 --- a/main.py +++ b/main.py @@ -23,6 +23,7 @@ from async_msssql_query import AsyncMSSQLClient from audit_log import log_session_event from db_config import build_dsn_from_config, ensure_db_config from diagnostica import open_diagnostica_window +from inventario import open_inventario_window from gestione_layout import open_layout_window from gestione_pickinglist import open_pickinglist_window from login_window import prompt_login @@ -163,6 +164,7 @@ class Launcher(ctk.CTk): "pickinglist", "storico_pickinglist", "diagnostica", + "inventario", ] def __init__(self, session: UserSession, db_client: AsyncMSSQLClient): @@ -279,6 +281,15 @@ class Launcher(ctk.CTk): lambda: open_diagnostica_window(self, self.db_client, session=self.session), ), ), + ( + "inventario", + loc_text("inventory.title", catalog=self._locale_catalog, default="Inventario"), + "launcher.open_inventory", + lambda: self._open_or_focus_child_window( + "inventario", + lambda: open_inventario_window(self, self.db_client, session=self.session), + ), + ), ( "arrange", loc_text("launcher.arrange", catalog=self._locale_catalog, default="Ridisponi finestre"), diff --git a/specifica_inventario.md b/specifica_inventario.md new file mode 100644 index 0000000..25bd164 --- /dev/null +++ b/specifica_inventario.md @@ -0,0 +1,242 @@ +# Inventario WMS - SAM per prodotto e lotto + +## Stato al 21/10/2026 + +Modulo Inventario 1.1.0 completato sul ramo `codex/inventario-monolista`, +derivato da `main` al commit `a60610c` (freeze warehouse monolista 2.0). +Il lavoro bilista non viene importato: barcode, prenotazione e gestione delle +picking list restano quelli monolista. Il ramo bilista e la sua cartella originale +restano intatti. Su richiesta dell'utente, questa versione viene integrata in +`main` e identificata dal tag `warehouse-monolista-2.0.1-inventario`. +L'installazione sui PC e l'esecuzione delle patch sul server restano manuali; +vedere `INSTALLAZIONE_MONOLISTA_INVENTARIO.md`. + +Questa versione sostituisce il prototipo del 14/10 e attua i requisiti discussi +il 15/10. E' una quadratura delle registrazioni disponibili, NON una certificazione +dell'inventario fisico. Prima dell'uso ufficiale confrontare etichette e stampa SAM +su un campione. Eventuali limiti storici sono dichiarati e le ambiguita' note +invalidano i totali interessati, invece di trasformarsi in zeri. + +## Requisiti e perimetro provvisorio + +- Data qualsiasi scelta dall'operatore, riferita alla fine della giornata. + In SQL si usa il limite esclusivo della mezzanotte successiva. Il 31 dicembre + e' un esempio, non un vincolo. Oggi e' segnalato come giornata non conclusa. +- E' provvisoriamente il WMS a guidare la ricerca: coppie prodotto/lotto delle + UDC presenti nelle aree 5/MDE5 e 6/MDE6 oppure non scaffalate alla data. +- Per quelle stesse coppie prodotto/lotto si cercano i contenitori in SAM nel + Magazzino Principale. Non si estende la ricerca agli altri lotti del prodotto. +- Un lotto presente solo in confezionamento e in nessuna UDC WMS e' fuori dal + perimetro provvisorio. Questo limite compare in GUI e XLSX. L'utente potra' + rivedere in seguito la scelta del perimetro. +- Escludere le UDC effettivamente spedite alla data (IDCella 9999), non quelle + spedite dopo. Una picking list chiusa NON sostituisce un movimento mancante. +- Nessuna modifica automatica a giacenze, prenotazioni, movimenti o anagrafiche. + +## Contenitori, UDC e tre componenti + +Il materiale e' in bag o vasche etichettate, anche parzialmente piene. +LOTSER contiene ID, prodotto, NUMLOT e NUMSER. La chiave tecnica del contenitore +e' LOTSER.ID; nel dettaglio si conservano anche lotto e seriale completo. + +- `554321/123245`: contenitore assegnato alla UDC 554321. +- `000000/123456`: contenitore non assegnato a una UDC. +- Un prefisso diverso da zero NON certifica una UDC completa o entrata nel WMS. +- "Non scaffalata" descrive la collocazione; "parziale" descrive il riempimento. +- Una UDC puo' crescere durante il confezionamento. La precedente affermazione + "UDC intere" esclude prelievi parziali/riconfezionamenti nel processo regolare, + non il riempimento iniziale progressivo. +- Non si moltiplica il numero di contenitori per una capacita' standard. + +| Componente | Significato | Quantita' | +| --- | --- | --- | +| A | UDC presenti in WMS, allocate o non scaffalate | Pezzi da carichi produzione dei contenitori associati | +| B | Contenitori con UDC assegnata, giacenza SAM positiva e nessuna posizione WMS positiva/anomala | Pezzi SAM alla data; confezionamento dedotto, piena/parziale non determinato | +| C | Contenitori con prefisso 000000 e giacenza SAM positiva | Pezzi SAM alla data nei contenitori senza UDC | +| X | Materiale non classificabile come A/B/C senza contraddizioni | Visibile nel dettaglio e nel saldo SAM, non attribuito arbitrariamente a B | + +La proposta "UDC SAM meno UDC WMS" e' una differenza di insiemi di identificativi, +non una sottrazione di pezzi utilizzata per inventare B. Una UDC gia' in A come +non scaffalata non si conta anche in B. Il contenitore viene contato una sola volta. + +Per le UDC fuori WMS si controllano anche posizioni in altre aree, saldo negativo +e posizione spedita. Una UDC in 9999 con giacenza SAM residua diventa X, non B. +Una presenza WMS residua con saldo SAM zero resta A: la differenza va mostrata, +non cancellata per ottenere una quadratura apparente. + +## Fonti verificate e algoritmo SQL + +La query runtime e' `inventory_report.sql`, parametrizzata e invocata tramite +il client asincrono esistente. Crea solo tabelle temporanee di sessione. +Non modifica oggetti legacy, SAM, viste Python, indici persistenti o stored. + +### Magazzino SAM e relazioni + +Si cerca in ANAMAG il nome esatto `Magazzino Principale`, che deve essere univoco. +Le ubicazioni sono ALLMAG con IDANAMAG corrispondente. Nel DB locale sono +ANAMAG.ID=20 e ALLMAG.ID=4, ma non vengono codificati come costanti nella query. + +MOVMAG.IDARTICO e GIAMAG.IDARTICO indicano LOTSER.ID, NON ARTICO.ID. +Il prodotto e' LOTSER.IDARTICO -> ARTICO.ID. +Il database ERP resta SAMA1, come nell'integrazione legacy di questo progetto; +non si tratta ancora del futuro connettore ERP generalizzato FlyWMS. + +### Presenza WMS + +MagazziniPallet: somma PesoUnitario con segno positivo per V e negativo per P, +per Attributo/UDC e IDCella, prima del limite esclusivo. PesoUnitario e' un +indicatore di presenza, non il numero di pezzi. Le posizioni positive nelle +aree MDE5/MDE6 e nella cella 1000 sono A. Le posizioni in 9999 sono spedite. +Si conserva la diagnostica su posizioni multiple e saldi diversi da uno/negativi. + +La geometria Celle -> Aree -> Magazzini e' quella disponibile oggi: non esiste +qui uno storico di rinomina o spostamento fisico degli scaffali. + +### Assegnazione contenitore/UDC alla data + +E' stata verificata la presenza del trigger SAM `StoricizzaVariazioniSerie`, +che registra in EXTTACLOTSER il valore vecchio EXNUMSER, il nuovo NUMSER e +AGGIORNAMENTO per ogni modifica di seriale. + +Per ogni contenitore: +1. Se esiste una modifica dalla mezzanotte successiva in avanti, il valore + EXNUMSER della prima modifica e' il seriale valido alla data richiesta. +2. In assenza di modifiche successive si usa il NUMSER corrente. +3. Due modifiche al primo istante utile, senza chiave univoca di ordinamento, + sono considerate ambigue. Il totale ricostruito interessato diventa ignoto. + +Nel DB locale lo storico disponibile parte dal 10/01/2022. Per una data prima +del primo storico disponibile, o se lo storico e' vuoto, i totali ricostruiti +non vengono certificati numericamente: si mostra l'anomalia. + +Limite esplicito: l'assenza di una modifica nello storico non prova che il +trigger sia sempre stato attivo. La ricostruzione assume storico completo, +nessuna cancellazione di contenitori e nessuna modifica non tracciata a +prodotto/lotto. EXTTACLOTSER non e' una fotografia immutabile di tutte le +anagrafiche. Questa avvertenza resta visibile in GUI e XLSX. + +### Quantita' A e saldo SAM per contenitore + +A: somma algebrica dei carichi di produzione causale CP nel Magazzino +Principale prima del limite, usando MOVMAG.QTAINV e i segni della causale. +Si supportano piu' carichi CP e le loro quantita' effettive: non si presume +una bag piena e non si usa la giacenza corrente come contenuto nominale. +Un contenitore senza carico nominale positivo o con altri tipi di entrata +richiede verifica: A rimane ignoto per il prodotto/lotto interessato. +Sul campione locale esaminato CP e' il carico e VEN la vendita; l'equivalenza +del nominale all'etichetta va comunque validata sui dati reali dell'operatore. + +SAM: per ciascun LOTSER.ID si parte da GIAMAG.QTTGIAI nelle ubicazioni del +Magazzino Principale e si sottrae l'effetto dei MOVMAG dal limite in avanti. +I segni vengono da CAUMOV.QTGIUP/QTGIUA per sorgente/destinazione. Un movimento +interno allo stesso magazzino si compensa. Le date SAM usano origine 1899-12-30. + +B/C usano il saldo cosi' ricostruito per ciascun contenitore, non il numero +di contenitori e non il residuo del confronto con A. Vasche/bag parziali +sono quindi trattate con la quantita' registrata, non una capacita' teorica. +Essendo B/C ricavati da SAM, la loro presenza non prova la collocazione fisica +in confezionamento: e' una spiegazione documentale da verificare sul posto. + +## Calcolo ed esiti + +`Totale ricostruito = A + B + C` + +`Differenza iniziale = SAM - A` + +`Scostamento residuo = SAM - (A + B + C)` + +Esempio: SAM 10.600, A 10.000, B 400, C 200 -> residuo zero. +Un residuo positivo indica pezzi SAM non spiegati da A/B/C; uno negativo +indica quantita' ricostruita superiore a SAM. + +L'aggregazione parte dal prodotto/lotto, poi viene riepilogata per prodotto. +Se differenze di lotti opposte si annullano nel totale del prodotto, una +segnalazione impedisce di leggere quel totale come una quadratura corretta. +Le UDC multilotto sono contate una volta per prodotto. I conteggi UDC di +prodotti diversi non sono sommabili per ottenere le UDC globali. + +Quantita' ignote: `?` a video, celle vuote in XLSX. Zeri reali: numeri zero. +Calcoli Python con Decimal. Un'anomalia puo' invalidare A, B, C o SAM: +la parte nota resta consultabile, il totale dipendente dalla parte ignota no. + +Le righe X restano fuori dalla somma A+B+C ma dentro SAM, con avviso: +per esempio una spedita con saldo SAM residuo resta uno scostamento da indagare. + +## Interfaccia e integrazione monolista + +- Pulsante Inventario nella barra orizzontale desktop, permesso + `launcher.open_inventory`; una sola finestra e richiamo in primo piano. +- Finestra con posizionamento condiviso, tema JSON, stringhe IT/ENG, versione + visibile 1.1.0. Versione launcher aggiornata a 1.0.3. +- Data, Calcola, Esporta XLSX. Nessuna query all'apertura. Query e export + asincroni con overlay; durante il calcolo non si avviano richieste duplicate. +- Griglia prodotti ordinabile: UDC WMS, pezzi scaffalati/non scaffalati, A, + numero UDC B e pezzi B, numero contenitori C e pezzi C, totale, SAM, + differenza iniziale, residuo, anomalie. +- Selezionando un prodotto: schede Lotti e Contenitori. Per contenitore: + componente, prodotto, lotto, UDC, ID LOTSER, seriale, ubicazione, quantita' + della componente, saldo SAM, anomalie. +- Ubicazione di B/C etichettata "Confezionamento (dedotto)". +- XLSX con tre fogli (prodotti, lotti, contenitori), data del calcolo, + perimetro, avvertenze e date delle fonti. Numeri e codici restano del tipo + corretto, anche codici che iniziano con '='. +- Errore di calcolo: griglia precedente svuotata, export disabilitato. + Nessun risultato vecchio presentato come relativo alla nuova data. +- Barcode e procedure di movimentazione/prenotazione monolista invariati. + +## Collaudo eseguito + +Il 21/10/2026 sono stati eseguiti 50 test con esito positivo, comprendenti +test monolista preesistenti e nuove verifiche di dominio, GUI, menu, XLSX e SQL. + +I test SQL opt-in usano solo tabelle temporanee con dati fittizi: i nomi +delle tabelle sorgenti della query sono sostituiti con fixture prima +dell'esecuzione. Non vengono effettuati movimenti reali. + +Casi verificati: A/B/C, UDC multilotto, esclusione di lotti solo SAM, bag +parziale, saldo residuo di UDC spedita, cambio NUMSER successivo alla data, +spedizione successiva, due celle per la stessa UDC senza raddoppiare SAM, +piu' carichi CP, solo Magazzino Principale, limite della mezzanotte, +storico ambiguo, quantita' ignote, ordinamento numerico, export tipizzato, +errori senza risultati obsoleti, pulsante menu e finestra unica. + +Letture sul database locale tramite il vero client SQLAlchemy/aioodbc: +- 31/12/2025: 27 prodotti, 172 lotti, 19.859 righe dettaglio, circa 15 secondi. +- 28/09/2026: 21 prodotti, 68 lotti, 9.472 righe dettaglio, circa 6 secondi. + +Questi tempi e conteggi descrivono il backup locale disponibile, non sono +una certificazione quantitativa della produzione. Le anomalie reali restano +visibili; non sono state corrette nei dati. + +Comandi di verifica dalla cartella del ramo monolista: + +```powershell +python -B -m unittest discover -s tests -q +$env:INVENTORY_TEST_CONFIG = 'C:\devel\python\ware_house\db_connection.json' +python -B -m unittest discover -s tests -q +``` + +Senza variabile i cinque test SQL sono saltati esplicitamente. Con variabile +si collega SQL Server per creare esclusivamente fixture temporanee. +La configurazione contiene credenziali: non aggiungerla al repository. + +## Installazione e limiti residui + +Non serve una patch SQL per questo modulo. Distribuire il file +`inventory_report.sql` insieme ai sorgenti: NON e' uno script da eseguire +manualmente in SSMS. La query richiede lettura di SAMA1, incluso EXTTACLOTSER. + +Distribuire insieme inventario.py, inventory_service.py, inventory_report.sql +e le integrazioni main.py, user_session.py, version_info.py, locale.json, +tooltip.json, ui_theme.json. Nessuna dipendenza nuova: openpyxl e' gia' prevista. +Preferire la distribuzione completa della monolista dopo commit e collaudo, +non copiare indiscriminatamente dalla cartella del ramo bilista. + +Eseguire a movimentazioni ferme, con backup ERP/WMS coerenti. Le letture non +costituiscono una snapshot distribuita atomica; le date massime dei movimenti +NON certificano la data di backup. Nessun NOLOCK o lettura sporca viene usato. + +Prima della distribuzione ufficiale confrontare un campione con etichette e +inventario SAM alla medesima data, provare il menu sulla postazione del reparto +e verificare la completezza dello storico seriali. L'ambiente di simulazione +bilista rimane un'attivita' separata. diff --git a/tests/test_inventory.py b/tests/test_inventory.py new file mode 100644 index 0000000..4cabf56 --- /dev/null +++ b/tests/test_inventory.py @@ -0,0 +1,202 @@ +"""Domain and XLSX regression tests: no live stock is modified.""" +import json +import tempfile +import unittest +from datetime import date, datetime +from decimal import Decimal +from pathlib import Path +from unittest.mock import AsyncMock + +from inventory_service import (DETAIL_KEYS, SUMMARY_KEYS, build_report, export_inventory, + inventory_cutoff, load_inventory) +from locale_text import text + +DAY = date(2025, 12, 31) +HISTORY = dict(Kind="META", Component="HIST_MIN", SourceDate=datetime(2022, 1, 1)) + + +def stock(**changes): + r = dict(Kind="ROW", Component="A", Product="P1", Description="Product", + Unit="NR", ContainerId=1, Lot="L1", Serial="600001/000001", + Pallet="600001", Cell=1101, Location="1A.1.a", Balance=Decimal(1), + Quantity=Decimal(20), SamQuantity=Decimal(20), Locations=1, + NegativeBalances=0, Shipped=0, AssignmentIssue=0, + MovementIssues=0, OtherReceipts=0) + r.update(changes) + return r + + +def report(*records): + return build_report(DAY, [HISTORY, *records]) + + +def packing(**changes): + return stock(Component="B", ContainerId=2, Pallet="600002", Serial="600002/000002", + Cell=None, Location=None, Balance=None, Locations=0, **changes) + + +def loose(**changes): + return stock(Component="C", ContainerId=3, Pallet="000000", Serial="000000/000003", + Cell=None, Location=None, Balance=None, Locations=0, **changes) + + +class InventoryTests(unittest.TestCase): + def test_year_end_exclusive_cutoff(self): + self.assertEqual(inventory_cutoff("31/12/2025"), (DAY, datetime(2026, 1, 1), 46023)) + + def test_dates_invalid_future_and_leap(self): + for value in ("31/02/2025", "2025-12-31", "01/01/3000", "31/12/2009"): + with self.assertRaises(ValueError): + inventory_cutoff(value) + self.assertEqual(inventory_cutoff("29/02/2024")[1], datetime(2024, 3, 1)) + + def test_three_components_and_sign(self): + r = report(stock(), packing(Quantity=10, SamQuantity=10), loose(Quantity=5, SamQuantity=5)) + row = r.rows[0] + self.assertEqual([row[k] for k in ("WMS", "Packing", "Loose", "Reconstructed", "SAM", "Difference")], + [20, 10, 5, 35, 35, 0]) + self.assertEqual(row["InitialDifference"], 15) + self.assertEqual(row["LooseContainers"], 1) + + def test_non_shelved_is_a_not_b(self): + row = report(stock(Cell=1000)).rows[0] + self.assertEqual((row["NonShelved"], row["Packing"], row["UDCs"]), (20, 0, 1)) + + def test_multilot_counts_udc_once_and_keeps_lots(self): + r = report(stock(), stock(ContainerId=4, Lot="L2", Serial="600001/000004")) + self.assertEqual((r.rows[0]["UDCs"], r.rows[0]["WMS"]), (1, 40)) + self.assertEqual(len(r.lots), 2) + + def test_multi_product_udc(self): + r = report(stock(), stock(ContainerId=4, Product="P2")) + self.assertEqual([row["UDCs"] for row in r.rows], [1, 1]) + + def test_lot_offsets_do_not_look_like_a_match(self): + row = report(stock(SamQuantity=10), stock(ContainerId=2, Lot="L2", SamQuantity=30)).rows[0] + self.assertEqual(row["Difference"], 0) + self.assertIn("lot_offsets", row["Issues"]) + + def test_multilocation_does_not_double_sam(self): + r = report(stock(Locations=2), stock(Locations=2, Cell=8004)) + self.assertEqual((r.rows[0]["SAM"], r.rows[0]["UDCs"]), (20, 1)) + self.assertIsNone(r.rows[0]["WMS"]) + self.assertIn("locations", r.rows[0]["Issues"]) + + def test_duplicate_incompatible_data_invalidates(self): + row = report(stock(), stock(Quantity=50)).rows[0] + self.assertIn("duplicate", row["Issues"]) + self.assertIsNone(row["SAM"]) + + def test_missing_content_is_not_zero(self): + row = report(stock(Quantity=None)).rows[0] + self.assertIsNone(row["WMS"]) + self.assertIsNone(row["Difference"]) + self.assertEqual(row["SAM"], 20) + + def test_shipped_residual_is_not_packaging(self): + row = report( + stock(), stock(Component="X", ContainerId=9, Pallet="600009", + Cell=None, Locations=1, Shipped=1, Quantity=5, SamQuantity=5)).rows[0] + self.assertEqual((row["Packing"], row["SAM"], row["Difference"]), (0, 25, 5)) + self.assertIn("shipped", row["Issues"]) + + def test_sam_zero_does_not_hide_wms_presence(self): + row = report(stock(SamQuantity=0)).rows[0] + self.assertEqual((row["WMS"], row["Difference"]), (20, -20)) + + def test_partial_container_uses_actual_quantity(self): + row = report(loose(Quantity=Decimal("3.5"), SamQuantity=Decimal("3.5"))).rows[0] + self.assertEqual(row["Loose"], Decimal("3.5")) + + def test_history_missing_or_ambiguous_is_not_certified(self): + for r in (build_report(DAY, [stock()]), report(stock(AssignmentIssue=1)), + build_report(date(2020, 1, 1), [HISTORY, stock()])): + self.assertIn("history", r.rows[0]["Issues"]) + self.assertIsNone(r.rows[0]["Difference"]) + + def test_movements_missing_invalidates_sam(self): + row = report(stock(MovementIssues=1)).rows[0] + self.assertIsNone(row["SAM"]) + + def test_negative_balance_flagged(self): + row = report(loose(Quantity=-5, SamQuantity=-5)).rows[0] + self.assertIn("negative", row["Issues"]) + self.assertIsNone(row["Difference"]) + + def test_other_receipt_requires_validation(self): + row = report(stock(OtherReceipts=1)).rows[0] + self.assertIsNone(row["WMS"]) + + def test_unknown_unit(self): + row = report(stock(Unit="KG")).rows[0] + self.assertIn("unit", row["Issues"]) + self.assertIsNone(row["SAM"]) + + def test_undated_wms(self): + row = report(stock(), dict(Kind="META", Component="UNDATED", Quantity=1)).rows[0] + self.assertIsNone(row["Difference"]) + + def test_missing_label_remains_visible(self): + row = report(stock(Product=None, ContainerId=None, Quantity=None)).rows[0] + self.assertIn("600001", row["Product"]) + self.assertIsNone(row["WMS"]) + + def test_empty_report(self): + r = report() + self.assertEqual((r.rows, r.lots, r.details), ([], [], [])) + + def test_export_roundtrip(self): + from openpyxl import load_workbook + r = report(stock(Product="=CODE"), stock(Product="P2", ContainerId=2, Quantity=None)) + with tempfile.TemporaryDirectory() as folder: + path = str(Path(folder) / "inventory.xlsx") + export_inventory(r, path, translate=text) + wb = load_workbook(path) + ws = wb.active + self.assertEqual(len(wb.worksheets), 3) + self.assertEqual(ws["B1"].value.date(), DAY) + self.assertEqual((ws["A7"].value, ws["A7"].data_type), ("=CODE", "s")) + diff_col = SUMMARY_KEYS.index("Difference") + 1 + self.assertEqual(ws.cell(7, diff_col).value, 0) + self.assertIsNone(ws.cell(8, SUMMARY_KEYS.index("WMS")+1).value) + self.assertEqual(ws.freeze_panes, "A7") + self.assertEqual(wb.worksheets[2].cell(2, DETAIL_KEYS.index("Serial")+1).value, "600001/000001") + wb.close() + + def test_translations_complete(self): + catalog = json.loads(Path("locale.json").read_text(encoding="utf-8")) + for language in ("IT", "ENG"): + for key in SUMMARY_KEYS + DETAIL_KEYS: + self.assertIn("inventory.col." + key, catalog[language]) + for component in "ABCX": + self.assertIn("inventory.component." + component, catalog[language]) + self.assertEqual({k for k in catalog["IT"] if k.startswith("inventory.")}, + {k for k in catalog["ENG"] if k.startswith("inventory.")}) + + def test_sqlalchemy_has_only_two_actual_bind_markers(self): + from sqlalchemy import text as sql_text + from sqlalchemy.dialects.mssql.pyodbc import dialect + from inventory_service import SQL_PATH + compiled = sql_text(SQL_PATH.read_text(encoding="utf-8")).compile(dialect=dialect(paramstyle="qmark")) + self.assertEqual(compiled.positiontup, ["cutoff", "sam_cutoff"]) + + +class InventoryAsyncTests(unittest.IsolatedAsyncioTestCase): + async def test_bound_cutoffs_without_commit(self): + db = type("DB", (), {"query_json": AsyncMock(return_value={"rows": []})})() + r = await load_inventory(db, "31/12/2025") + args, kwargs = db.query_json.call_args + self.assertEqual(args[1]["cutoff"], datetime(2026, 1, 1)) + self.assertEqual(args[1]["sam_cutoff"], 46023) + self.assertNotIn("commit", kwargs) + self.assertEqual(r.selected_date, DAY) + + async def test_invalid_date_never_queries(self): + db = type("DB", (), {"query_json": AsyncMock()})() + with self.assertRaises(ValueError): + await load_inventory(db, "31/02/2025") + db.query_json.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_inventory_gui.py b/tests/test_inventory_gui.py new file mode 100644 index 0000000..00174ff --- /dev/null +++ b/tests/test_inventory_gui.py @@ -0,0 +1,132 @@ +"""Real Tk widget checks with synthetic report data; no database connection.""" + +import tkinter as tk +import unittest +from datetime import date +from decimal import Decimal +from unittest.mock import Mock, patch + +import customtkinter as ctk + +from inventario import InventarioWindow, display_number +from inventory_service import build_report +from test_inventory import stock, HISTORY + + +class InventoryGuiTests(unittest.TestCase): + def setUp(self): + self.root = ctk.CTk() + self.root.withdraw() + self.win = InventarioWindow(self.root, Mock()) + self.win.withdraw() + self.root.update_idletasks() + + def tearDown(self): + for token in self.root.tk.call("after", "info"): + try: + # Cancel the timer without deleting another widget's Tcl command. + self.root.tk.call("after", "cancel", token) + except tk.TclError: + pass + self.win.destroy() + self.root.destroy() + + def sample(self): + return build_report(date(2025, 12, 31), [ + HISTORY, + stock(Product="A", Quantity=Decimal(10), SamQuantity=Decimal(10)), + stock(Product="B", ContainerId=2, Quantity=Decimal(2), SamQuantity=Decimal(2)), + ]) + + def test_no_query_at_open_and_render_zeros(self): + self.win.db_client.query_json.assert_not_called() + self.win._loaded(self.sample()) + values = self.win.tree.item("0", "values") + self.assertEqual(values[3:9], ("1", "10", "0", "10", "0", "0")) + self.assertEqual(self.win.btn_export.cget("state"), "normal") + self.assertIn("31/12/2025", self.win.var_status.get()) + + def test_selection_populates_lot_and_container_details(self): + self.win._loaded(self.sample()) + self.win.tree.selection_set("0") + self.win._select() + self.assertEqual(len(self.win.lot_tree.get_children()), 1) + self.assertEqual(len(self.win.detail_tree.get_children()), 1) + + def test_sort_uses_numbers_not_formatted_strings(self): + self.win._loaded(self.sample()) + self.win._sort("SAM") + self.assertEqual([r["Product"] for r in self.win._rows], ["B", "A"]) + self.win._sort("SAM") + self.assertEqual([r["Product"] for r in self.win._rows], ["A", "B"]) + + def test_load_disables_export_and_repeated_requests(self): + self.win._loaded(self.sample()) + with patch.object(self.win._async, "run") as run: + self.win._load() + self.assertEqual(self.win.btn_export.cget("state"), "disabled") + self.win._load() + self.assertEqual(run.call_count, 1) + run.call_args.args[0].close() + + def test_export_uses_result_date_not_edited_entry(self): + self.win._loaded(self.sample()) + self.win.var_date.set("01/01/2026") + with patch("inventario.filedialog.asksaveasfilename", return_value="") as save: + self.win._export() + self.assertEqual(save.call_args.kwargs["initialfile"], "inventario_20251231.xlsx") + + def test_decimal_formatting(self): + self.assertEqual(display_number(Decimal("0.000000")), "0") + self.assertEqual(display_number(Decimal("1200.000000")), "1200") + self.assertEqual(display_number(None), "?") + + def test_failed_load_restores_controls_without_old_export(self): + self.win._loaded(self.sample()) + with patch.object(self.win._async, "run") as run: + self.win._load() + run.call_args.args[0].close() + with patch("inventario.messagebox.showerror"), patch("inventario.log_exception"): + self.win._error(RuntimeError("Synthetic failure")) + self.assertEqual(self.win.btn_load.cget("state"), "normal") + self.assertEqual(self.win.btn_export.cget("state"), "disabled") + self.assertEqual(self.win.tree.get_children(), ()) + + +class InventoryLauncherTests(unittest.TestCase): + def test_menu_opens_single_inventory_child(self): + from main import Launcher + from user_session import UserSession + session = UserSession(1, "TEST", "Test operator") + with patch.object(Launcher, "_apply_dynamic_geometry"), patch.object(Launcher, "lift"), \ + patch.object(Launcher, "focus_force"), patch.object(Launcher, "_make_exit_icon", return_value=None): + root = Launcher(session, Mock()) + root.withdraw() + try: + def widgets(widget): + for child in widget.winfo_children(): + yield child + yield from widgets(child) + buttons = [w for w in widgets(root) if isinstance(w, ctk.CTkButton) and w.cget("text") == "Inventario"] + self.assertEqual(len(buttons), 1) + def create(*args, **kwargs): + win = InventarioWindow(*args, **kwargs) + win.withdraw() + return win + with patch("main.open_inventario_window", side_effect=create) as factory, \ + patch("main.place_window_below_parent_later"), \ + patch.object(InventarioWindow, "lift"), patch.object(InventarioWindow, "focus_force"): + buttons[0].invoke() + first = root._child_windows_by_key["inventario"] + buttons[0].invoke() + self.assertIs(root._child_windows_by_key["inventario"], first) + self.assertEqual(factory.call_count, 1) + root.db_client.query_json.assert_not_called() + finally: + for token in root.tk.call("after", "info"): + root.tk.call("after", "cancel", token) + root.destroy() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_inventory_sql.py b/tests/test_inventory_sql.py new file mode 100644 index 0000000..34b487a --- /dev/null +++ b/tests/test_inventory_sql.py @@ -0,0 +1,139 @@ +"""Opt-in SQL Server integration tests using ONLY local #temporary fixtures. + +Set INVENTORY_TEST_CONFIG to a local db_connection.json. Source object names in +the production batch are replaced with #fixtures before execution: no warehouse +or ERP table is read or written by the test. Credentials are never printed. +""" +import json +import os +import unittest +from datetime import date, datetime + +from inventory_service import SQL_PATH, build_report + + +@unittest.skipUnless(os.environ.get("INVENTORY_TEST_CONFIG"), "SQL fixture test is opt-in") +class InventorySQLTests(unittest.TestCase): + def setUp(self): + import pyodbc + with open(os.environ["INVENTORY_TEST_CONFIG"], encoding="utf-8") as handle: + c = json.load(handle) + self.cn = pyodbc.connect("DRIVER={" + c["driver"] + "};SERVER=" + c["server"] + + ";DATABASE=" + c["database"] + ";UID=" + c["user"] + ";PWD=" + c["password"] + + ";TrustServerCertificate=yes;", timeout=5) + self.cn.timeout = 60 + self.addCleanup(self.cn.close) + self.addCleanup(self.cn.rollback) + self.cur = self.cn.cursor() + definitions = { + "ANAMAG": "ID int, DESCR varchar(100)", + "ALLMAG": "ID int, IDANAMAG int", + "MagazziniPallet": "Attributo varchar(20),IDCella int,Tipo char(1),PesoUnitario decimal(28,6),DataMagazzino datetime", + "Celle": "ID int,IDArea int,Corsia varchar(20),Colonna varchar(20),Fila varchar(20)", + "Aree": "ID int,IDMagazzino int", + "Magazzini": "ID int,Descrizione varchar(20)", + "LOTSER": "ID int,IDARTICO int,NUMLOT varchar(30),NUMSER varchar(30)", + "EXTTACLOTSER": "IDLOTSER float,EXNUMSER varchar(30),NUMSER varchar(30),AGGIORNAMENTO datetime", + "GIAMAG": "IDARTICO int,IDMAG int,QTTGIAI decimal(28,6)", + "MOVMAG": "IDARTICO int,IDCAUMOV int,IDMAGPAR int,IDMAGARR int,QTAINV decimal(28,6),DATMOV float", + "CAUMOV": "ID int,CODICE varchar(10),QTGIUP char(1),QTGIUA char(1)", + "ARTICO": "ID int,CODICE varchar(30),DESCR varchar(100),UMI varchar(8)", + } + for name, definition in definitions.items(): + self.cur.execute(f"CREATE TABLE #fixture_{name} ({definition})") + self.sql = SQL_PATH.read_text(encoding="utf-8") + for name in definitions: + self.sql = self.sql.replace("SAMA1.dbo." + name, "#fixture_" + name) + self.sql = self.sql.replace("dbo." + name, "#fixture_" + name) + self.assertNotIn("SAMA1.dbo.", self.sql) + self.assertNotIn("dbo.", self.sql) + self.sql = self.sql.replace(":sam_cutoff", "?").replace(":cutoff", "?") + self.insert("ANAMAG", (20, "Magazzino Principale")) + self.insert("ALLMAG", (4, 20), (6, 30)) + self.insert("Magazzini", (1, "MDE5"), (2, "MDE6"), (3, "OTHER")) + self.insert("Aree", (1, 1), (2, 2), (3, 3)) + self.insert("Celle", (1101, 1, "1A", "1", "a"), (8004, 2, "4P", "1", "d"), + (1000, 1, "5E", "1", "1"), (9999, 1, "7G", "1", "1"), + (9900, 3, "Z", "1", "1")) + self.insert("ARTICO", (1, "PROD", "Product", "NR")) + self.insert("CAUMOV", (1, "CP", None, "+"), (2, "VEN", "-", None)) + self.insert("EXTTACLOTSER", (999, "000000/000999", "600999/000999", datetime(2022, 1, 1))) + self.day = date(2026, 1, 1) + self.cutoff = datetime(2026, 1, 2) + self.serial_cutoff = (self.cutoff - datetime(1899, 12, 30)).days + for pallet, cell in (("600001", 1101), ("600002", 1000), ("600006", 9999), ("600007", 9999)): + self.insert("MagazziniPallet", (pallet, cell, "V", 1, datetime(2025, 12, 30))) + # Real WMS stock: 60 + 40 + 10 pieces. ID3 is another lot in the SAME UDC. + self.container(1, "L1", "600001/000001", 60, 0) + self.container(2, "L1", "600002/000002", 40, 40) + self.container(3, "L2", "600001/000003", 10, 10) + self.container(4, "L1", "600004/000004", 30, 30) # partial packing UDC + self.container(5, "L1", "000000/000005", 20, 20) + self.container(6, "L1", "600006/000006", 15, 15) # shipped with SAM residual + self.container(7, "L1", "600007/000007", 99, 0) # fully shipped + self.container(8, "EXCLUDED", "000000/000008", 777, 777) # same product, other lot + self.container(9, "L1", "600009/000009", 6, 6) # was unassigned at cutoff + self.insert("EXTTACLOTSER", (9, "000000/000009", "600009/000009", datetime(2026, 1, 3))) + # ID1 shipped AFTER inventory. Current GIAMAG=0 must be reversed to 60. + self.insert("MOVMAG", (1, 2, 4, None, 60, self.serial_cutoff + 1)) + self.insert("MagazziniPallet", ("600001", 1101, "P", 1, datetime(2026, 1, 3)), + ("600001", 9999, "V", 1, datetime(2026, 1, 3))) + + def insert(self, name, *rows): + for row in rows: + self.cur.execute(f"INSERT INTO #fixture_{name} VALUES ({','.join('?' for _ in row)})", row) + + def container(self, identity, lot, serial, receipt, current): + self.insert("LOTSER", (identity, 1, lot, serial)) + self.insert("GIAMAG", (identity, 4, current)) + self.insert("MOVMAG", (identity, 1, None, 4, receipt, self.serial_cutoff - 2)) + + def run_query(self): + self.cur.execute(self.sql, self.cutoff, self.serial_cutoff) + columns = [c[0] for c in self.cur.description] + records = [dict(zip(columns, row)) for row in self.cur.fetchall()] + return build_report(self.day, records) + + def test_scope_history_shipments_three_components(self): + r = self.run_query() + row = r.rows[0] + self.assertEqual((row["WMS"], row["Packing"], row["Loose"], row["SAM"], row["Difference"]), + (110, 30, 26, 181, 15)) + self.assertEqual((row["UDCs"], row["PackingUDCs"], row["LooseContainers"]), (2, 1, 2)) + self.assertEqual({x["Lot"] for x in r.lots}, {"L1", "L2"}) + by_id = {x["ContainerId"]: x for x in r.details} + self.assertEqual(by_id[9]["Component"], "C") + self.assertEqual(by_id[9]["Serial"], "000000/000009") + self.assertEqual(by_id[6]["Component"], "X") + self.assertNotIn(7, by_id) + self.assertNotIn(8, by_id) + self.assertEqual(by_id[1]["SamQuantity"], 60) + + def test_principal_only_and_incremental_receipts(self): + self.insert("GIAMAG", (4, 6, 10000)) + self.insert("MOVMAG", (1, 1, None, 4, 5, self.serial_cutoff - 1)) + row = self.run_query().rows[0] + self.assertEqual(row["WMS"], 115) + self.assertEqual(row["SAM"], 181) + + def test_multiple_locations_never_double_sam(self): + self.insert("MagazziniPallet", ("600001", 8004, "V", 1, datetime(2025, 12, 31))) + row = self.run_query().rows[0] + self.assertEqual(row["SAM"], 181) + self.assertIsNone(row["WMS"]) + self.assertIn("locations", row["Issues"]) + + def test_assignment_tie_is_unknown(self): + self.insert("EXTTACLOTSER", (9, "000000/000009", "600010/000009", datetime(2026, 1, 3))) + row = self.run_query().rows[0] + self.assertIn("history", row["Issues"]) + self.assertIsNone(row["Difference"]) + + def test_midnight_is_exclusive(self): + self.insert("MOVMAG", (2, 2, 4, None, 7, self.serial_cutoff)) + row = self.run_query().rows[0] + self.assertEqual(row["SAM"], 188) + + +if __name__ == "__main__": + unittest.main() diff --git a/tooltip.json b/tooltip.json index bf07cad..a5f4430 100644 --- a/tooltip.json +++ b/tooltip.json @@ -1,6 +1,7 @@ { "default_language": "IT", "IT": { + "launcher.open_inventory": "Confronta WMS e Magazzino Principale SAM a fine giornata, con dettaglio UDC, anomalie ed esportazione XLSX. Ricostruzione da validare.", "launcher.open_reset_corsie": "Apre la finestra di gestione corsie per visualizzare il contenuto di una corsia e svuotarla in modo controllato.", "launcher.open_layout": "Apre la vista layout delle corsie con celle, UDC presenti e menu operativo contestuale.", "launcher.open_multi_udc": "Apre la vista UDC fantasma per analizzare celle con piu' pallet e bonificare i candidati fantasma.", @@ -44,6 +45,7 @@ "picking.sequence.close": "Chiude la finestra senza effettuare altri salvataggi." }, "ENG": { + "launcher.open_inventory": "Compare WMS and SAM main warehouse at end of day, with UDC details, data-quality warnings and XLSX export. Reconstruction requires validation.", "launcher.open_reset_corsie": "Open the aisle management window to inspect an aisle and empty it in a controlled way.", "launcher.open_layout": "Open the aisle layout view with cells, present UDCs and the operational context menu.", "launcher.open_multi_udc": "Open the ghost UDC view to inspect cells with multiple pallets and clean ghost candidates.", diff --git a/ui_theme.json b/ui_theme.json index fdaf65f..b770b60 100644 --- a/ui_theme.json +++ b/ui_theme.json @@ -1,4 +1,13 @@ { + "inventory_window": { + "window_geometry": "1200x720", + "window_minsize": [900, 560], + "window_fg_color": ["#efefef", "#2f2f2f"], + "toolbar_frame_fg_color": ["#d7d7d7", "#3b3b3b"], + "toolbar_button_font": ["Segoe UI", 11, "bold"], + "difference_color": "#9b3900", + "unknown_color": "#aa0000" + }, "global": { "window_bg": ["#f1f1f1", "#2b2b2b"], "panel_bg": ["#d9d9d9", "#3a3a3a"], diff --git a/user_session.py b/user_session.py index fbfcb6c..b149c90 100644 --- a/user_session.py +++ b/user_session.py @@ -21,6 +21,7 @@ ALL_ACTIONS: FrozenSet[str] = frozenset( "launcher.open_pickinglist", "launcher.open_history_pickinglist", "launcher.open_diagnostics", + "launcher.open_inventory", "launcher.arrange_windows", "launcher.exit", "reset_corsie.view", @@ -29,6 +30,7 @@ ALL_ACTIONS: FrozenSet[str] = frozenset( "history_udc.view", "history_pickinglist.view", "diagnostics.view", + "inventory.view", "multi_udc.view", "layout.view", "layout.carico", diff --git a/version_info.py b/version_info.py index 43e4b3b..8e14705 100644 --- a/version_info.py +++ b/version_info.py @@ -12,7 +12,9 @@ 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.2", + "main": "1.0.3", + "inventario": "1.1.0", + "inventory_service": "1.1.0", "barcode_client": "1.0.27", "barcode_repository": "1.0.14", "barcode_service": "1.0.25", @@ -35,7 +37,7 @@ MODULE_VERSIONS: dict[str, str] = { "tooltips": "1.0.0", "udc_non_scaffalate": "1.0.1", "ui_theme": "1.0.0", - "user_session": "1.0.2", + "user_session": "1.0.3", "view_celle_multi_udc": "1.0.0", "window_placement": "1.0.0", }