Compare commits

...

9 Commits

15 changed files with 927 additions and 39 deletions

View File

@@ -72,7 +72,7 @@ LEFT OUTER JOIN SAMA1.sam.EXTUC
LEFT OUTER JOIN SAMA1.dbo.MTRASP
ON SAMA1.dbo.BAMTES.IDMTRASP = SAMA1.dbo.MTRASP.ID
WHERE
SAMA1.dbo.BAMTES.ANNDOC >= YEAR(GETDATE()) - 1
SAMA1.dbo.BAMTES.ANNDOC >= YEAR(GETDATE())
AND SAMA1.dbo.BAMTES.STATO IN ('P', 'D')
AND SAMA1.dbo.LOTSER.NUMLOT <> '00000000000'
GROUP BY

View File

@@ -18,8 +18,8 @@ Include:
- dbo.py_BarcodePickingListSkip
Nota storico:
dbo.py_vPreparaPackingListSAMA1 usa ANNDOC >= YEAR(GETDATE()) - 1
per mantenere visibili anche le picking list dell'anno precedente.
dbo.py_vPreparaPackingListSAMA1 usa ANNDOC >= YEAR(GETDATE())
per mantenere visibili solo le picking list dall'inizio dell'anno corrente.
*/
SET ANSI_NULLS ON;
@@ -378,7 +378,7 @@ LEFT OUTER JOIN SAMA1.sam.EXTUC
LEFT OUTER JOIN SAMA1.dbo.MTRASP
ON SAMA1.dbo.BAMTES.IDMTRASP = SAMA1.dbo.MTRASP.ID
WHERE
SAMA1.dbo.BAMTES.ANNDOC >= YEAR(GETDATE()) - 1
SAMA1.dbo.BAMTES.ANNDOC >= YEAR(GETDATE())
AND SAMA1.dbo.BAMTES.STATO IN ('P', 'D')
AND SAMA1.dbo.LOTSER.NUMLOT <> '00000000000'
GROUP BY

View File

@@ -48,7 +48,7 @@ LEFT OUTER JOIN SAMA1.sam.EXTUC
LEFT OUTER JOIN SAMA1.dbo.MTRASP
ON SAMA1.dbo.BAMTES.IDMTRASP = SAMA1.dbo.MTRASP.ID
WHERE
SAMA1.dbo.BAMTES.ANNDOC >= YEAR(GETDATE()) - 1
SAMA1.dbo.BAMTES.ANNDOC >= YEAR(GETDATE())
AND SAMA1.dbo.BAMTES.STATO IN ('P', 'D')
AND SAMA1.dbo.LOTSER.NUMLOT <> '00000000000'
GROUP BY

View File

@@ -10,9 +10,13 @@ cross-loop errors.
from __future__ import annotations
import asyncio
import inspect
import json
import logging
import os
import time
import urllib.parse
from pathlib import Path
from typing import Any, Dict, Optional
from sqlalchemy import text
@@ -22,6 +26,59 @@ from version_info import module_version
__version__ = module_version(__name__)
QUERY_PROFILER_LOG = Path(__file__).with_name("warehouse_query_profiler.log")
QUERY_PROFILER_CONFIG_PATH = Path(__file__).with_name("db_connection.json")
def _load_query_profiler_config() -> dict[str, Any]:
"""Read profiler settings from db_connection.json, with env overrides."""
config: dict[str, Any] = {
"enabled": False,
"slow_ms": 0,
"sql_limit": 4000,
}
try:
data = json.loads(QUERY_PROFILER_CONFIG_PATH.read_text(encoding="utf-8"))
section = data.get("query_profiler") if isinstance(data, dict) else None
if isinstance(section, dict):
config.update(section)
except Exception:
pass
if "WAREHOUSE_QUERY_PROFILER" in os.environ:
config["enabled"] = os.environ.get("WAREHOUSE_QUERY_PROFILER", "1").strip().lower() not in {
"0",
"false",
"no",
"off",
}
if "WAREHOUSE_QUERY_PROFILER_SLOW_MS" in os.environ:
config["slow_ms"] = os.environ.get("WAREHOUSE_QUERY_PROFILER_SLOW_MS", "0")
if "WAREHOUSE_QUERY_PROFILER_SQL_LIMIT" in os.environ:
config["sql_limit"] = os.environ.get("WAREHOUSE_QUERY_PROFILER_SQL_LIMIT", "4000")
return config
def _query_profiler_enabled() -> bool:
value = _load_query_profiler_config().get("enabled", False)
if isinstance(value, str):
return value.strip().lower() not in {"0", "false", "no", "off"}
return bool(value)
def _query_profiler_slow_ms() -> float:
try:
return float(_load_query_profiler_config().get("slow_ms", 0) or 0)
except Exception:
return 0.0
def _query_profiler_sql_limit() -> int:
try:
return int(_load_query_profiler_config().get("sql_limit", 4000) or 4000)
except Exception:
return 4000
try:
import pyodbc
@@ -76,6 +133,83 @@ def make_mssql_dsn(
return f"mssql+aioodbc:///?odbc_connect={urllib.parse.quote_plus(odbc)}"
def _compact_sql(sql: str, *, limit: int | None = None) -> str:
"""Collapse SQL whitespace so profiler entries stay readable."""
if limit is None:
limit = _query_profiler_sql_limit()
text_value = " ".join(str(sql or "").split())
if limit > 0 and len(text_value) > limit:
return text_value[:limit] + "...<truncated>"
return text_value
def _profile_params(params: Optional[Dict[str, Any]]) -> str:
"""Serialize SQL parameters for diagnostics."""
if not params:
return "{}"
try:
return _dumps(params)
except Exception:
return repr(params)
def _query_caller() -> str:
"""Return the first external Python frame that triggered the DB call."""
current_file = Path(__file__).resolve()
for frame in inspect.stack(context=0)[2:]:
try:
frame_file = Path(frame.filename).resolve()
except Exception:
continue
if frame_file == current_file:
continue
return f"{frame_file.name}:{frame.lineno}:{frame.function}"
return "unknown"
def _append_query_profile(
*,
method: str,
elapsed_ms: float,
rows: int | None,
rowcount: int | None,
commit: bool,
ok: bool,
sql: str,
params: Optional[Dict[str, Any]],
caller: str,
error: str = "",
) -> None:
"""Append one query timing line to the local profiler log."""
if not _query_profiler_enabled():
return
slow_ms = _query_profiler_slow_ms()
if ok and slow_ms > 0 and elapsed_ms < slow_ms:
return
try:
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
row_info = f"rows={rows}" if rows is not None else f"rowcount={rowcount}"
lines = [
(
f"{timestamp} | {elapsed_ms:.3f} ms | {method} | "
f"{row_info} | commit={int(commit)} | ok={int(ok)} | caller={caller}"
),
f"PARAMS: {_profile_params(params)}",
f"SQL: {_compact_sql(sql)}",
]
if error:
lines.append(f"ERROR: {error}")
with QUERY_PROFILER_LOG.open("a", encoding="utf-8") as handle:
handle.write("\n".join(lines) + "\n---\n")
except Exception:
# Profiling must never interfere with warehouse operations.
pass
class AsyncMSSQLClient:
"""Thin async query client for SQL Server.
@@ -152,23 +286,83 @@ class AsyncMSSQLClient:
"""
await self._ensure_engine()
t0 = time.perf_counter()
caller = _query_caller()
try:
async with (self._engine.begin() if commit else self._engine.connect()) as conn:
res = await conn.execute(text(sql), params or {})
rows = res.fetchall()
cols = list(res.keys())
except Exception as exc:
elapsed_ms = round((time.perf_counter() - t0) * 1000, 3)
_append_query_profile(
method="query_json",
elapsed_ms=elapsed_ms,
rows=None,
rowcount=None,
commit=commit,
ok=False,
sql=sql,
params=params,
caller=caller,
error=repr(exc),
)
raise
if as_dict_rows:
rows_out = [dict(zip(cols, row)) for row in rows]
else:
rows_out = [list(row) for row in rows]
elapsed_ms = round((time.perf_counter() - t0) * 1000, 3)
_append_query_profile(
method="query_json",
elapsed_ms=elapsed_ms,
rows=len(rows_out),
rowcount=None,
commit=commit,
ok=True,
sql=sql,
params=params,
caller=caller,
)
return {
"columns": cols,
"rows": rows_out,
"elapsed_ms": round((time.perf_counter() - t0) * 1000, 3),
"elapsed_ms": elapsed_ms,
}
async def exec(self, sql: str, params: Optional[Dict[str, Any]] = None, *, commit: bool = False) -> int:
"""Execute a DML statement and return its row count."""
await self._ensure_engine()
t0 = time.perf_counter()
caller = _query_caller()
try:
async with (self._engine.begin() if commit else self._engine.connect()) as conn:
res = await conn.execute(text(sql), params or {})
return res.rowcount or 0
rowcount = res.rowcount or 0
except Exception as exc:
elapsed_ms = round((time.perf_counter() - t0) * 1000, 3)
_append_query_profile(
method="exec",
elapsed_ms=elapsed_ms,
rows=None,
rowcount=None,
commit=commit,
ok=False,
sql=sql,
params=params,
caller=caller,
error=repr(exc),
)
raise
elapsed_ms = round((time.perf_counter() - t0) * 1000, 3)
_append_query_profile(
method="exec",
elapsed_ms=elapsed_ms,
rows=None,
rowcount=rowcount,
commit=commit,
ok=True,
sql=sql,
params=params,
caller=caller,
)
return rowcount

View File

@@ -68,6 +68,7 @@ class BarcodeClientApp:
self._auto_advance_id: str | None = None
self._pallet_auto_focus_id: str | None = None
self._paused_queue_id: int | None = None
self._paused_priority_state: BarcodeViewState | None = None
self._pallet_user_input_serial = 0
self._priority_loaded_input_serial = 0
self._priority_expected_pallet = ""
@@ -518,11 +519,12 @@ class BarcodeClientApp:
def _on_destination_enter(self, _event=None) -> str:
pallet = str(self.scanned_var.get() or "").strip()
destination = str(self.destination_var.get() or "").strip()
if pallet and destination:
self._submit()
else:
if not pallet:
self._focus_primary_input()
else:
self.info1_var.set("F3 per associare, F4 per disassociare")
self.status_band.configure(bg=self._status_colors["yellow"])
self._focus_destination_input()
return "break"
def _on_unload_key(self, _event=None) -> str:
@@ -531,6 +533,12 @@ class BarcodeClientApp:
def _on_escape_key(self, _event=None) -> str:
if self._is_priority_pause() and self._paused_queue_id is not None:
if self._paused_priority_state is not None:
state = self.service.resume_priority_state(self._paused_priority_state)
self._paused_priority_state = None
self._paused_queue_id = None
self._apply_state(state)
return "break"
self._start_queue(self._paused_queue_id, allow_during_pause=True)
return "break"
@@ -542,15 +550,18 @@ class BarcodeClientApp:
mode = getattr(self.service.state, "mode", "")
if mode == "priority_high":
self._paused_queue_id = 1
self._paused_priority_state = self.service.state
self._apply_state(self.service.begin_priority_pause(1))
return
if mode == "priority_low":
self._paused_queue_id = 0
self._paused_priority_state = self.service.state
self._apply_state(self.service.begin_priority_pause(0))
return
resumable_queue = self._resumable_queue_from_state(self.service.state)
if resumable_queue is not None:
self._paused_queue_id = resumable_queue
self._paused_priority_state = None
self._apply_state(self.service.begin_priority_pause(resumable_queue))
return
self._submit()

View File

@@ -107,15 +107,30 @@ ORDER BY g.BarcodePallet;
SQL_CLOSED_PICKING_BY_PALLET = """
SELECT TOP (1)
BarcodePallet,
NumeroPallet,
IDMagazzino,
IDArea,
IDCella,
IDStato
FROM dbo.XMag_GiacenzaPalletPlistChiuse
WHERE BarcodePallet COLLATE Latin1_General_CI_AS = :pallet COLLATE Latin1_General_CI_AS
ORDER BY IDCella DESC;
g.BarcodePallet,
g.NumeroPallet,
g.IDMagazzino,
g.IDArea,
g.IDCella,
g.IDStato
FROM dbo.XMag_GiacenzaPallet AS g
WHERE g.IDCella <> 9999
AND g.BarcodePallet COLLATE Latin1_General_CI_AS = :pallet COLLATE Latin1_General_CI_AS
AND EXISTS (
SELECT 1
FROM SAMA1.dbo.LOTSER AS ls
INNER JOIN SAMA1.dbo.LOTTIBF AS lb
ON lb.IDLOTSER = ls.ID
INNER JOIN SAMA1.dbo.FATRIG AS fr
ON lb.IDFATRIG = fr.ID
INNER JOIN SAMA1.dbo.BAMTES AS bt
ON bt.ID = fr.IDBAM
WHERE bt.ANNDOC >= 2011
AND bt.STATO = 'D'
AND LEFT(ls.NUMSER, 6) COLLATE Latin1_General_CI_AS =
:pallet COLLATE Latin1_General_CI_AS
)
ORDER BY g.IDCella DESC;
"""
SQL_RESOLVE_PHYSICAL_CELL = """
@@ -142,6 +157,7 @@ SQL_LEGACY_MOVE = """
SET NOCOUNT ON;
SET XACT_ABORT ON;
DECLARE @RC int = 0;
DECLARE @RefreshPickingReservation bit = :refresh_picking_reservation;
EXEC dbo.sp_xMagGestioneMagazziniPallet
@IDOperatore = :id_operatore,
@@ -150,7 +166,10 @@ EXEC dbo.sp_xMagGestioneMagazziniPallet
@NumeroCella = :numero_cella,
@RC = @RC OUTPUT;
EXEC dbo.py_sp_ControllaPrenotazionePackingListPalletNew;
IF @RefreshPickingReservation = 1
BEGIN
EXEC dbo.py_sp_ControllaPrenotazionePackingListPalletNew;
END;
SELECT
@RC AS RC,
@@ -408,6 +427,7 @@ class BarcodeRepository:
barcode_cella: str,
barcode_pallet: str,
numero_cella: int,
refresh_picking_reservation: bool = True,
) -> LegacyMoveResult:
"""Execute the same stored procedure used by the C# barcode form."""
@@ -416,6 +436,7 @@ class BarcodeRepository:
"barcode_cella": str(barcode_cella or "").strip(),
"barcode_pallet": str(barcode_pallet or "").strip(),
"numero_cella": int(numero_cella),
"refresh_picking_reservation": 1 if refresh_picking_reservation else 0,
}
log_runtime_event(
"Barcode WMS",
@@ -423,7 +444,8 @@ class BarcodeRepository:
"MOVE START "
f"operator={params['id_operatore']} "
f"cell={params['barcode_cella']} "
f"pallet={params['barcode_pallet']}"
f"pallet={params['barcode_pallet']} "
f"refresh_pl={params['refresh_picking_reservation']}"
),
)
try:

View File

@@ -2,7 +2,7 @@
from __future__ import annotations
from dataclasses import dataclass
from dataclasses import dataclass, replace
from typing import Literal
from barcode_repository import BarcodeRepository, LegacyMoveResult
@@ -115,6 +115,15 @@ class BarcodeService:
)
return self._state
def resume_priority_state(self, state: BarcodeViewState) -> BarcodeViewState:
"""Restore the exact picking pallet that was visible before a local pause."""
if state.mode not in ("priority_high", "priority_low"):
return self._state
self._current_priority_state = 1 if state.mode == "priority_high" else 0
self._state = replace(state, scanned_pallet="", auto_advance_delay_ms=0)
return self._state
async def skip_current_picking_pallet(self) -> BarcodeActionResult:
"""Mark the currently proposed picking pallet as skipped and advance."""
@@ -277,7 +286,11 @@ class BarcodeService:
target_display = resolved_cell.ubicazione or destination
current_location = await self.repository.fetch_current_location_by_pallet(pallet)
picking_before_move = await self.repository.fetch_picking_by_pallet(pallet)
picking_before_move = (
None
if current_location
else await self.repository.fetch_picking_by_pallet(pallet)
)
if not current_location and not picking_before_move:
if is_direct_load:
trace_row = await self.repository.fetch_trace_by_pallet(pallet)
@@ -297,6 +310,7 @@ class BarcodeService:
barcode_cella=self.NON_SCAFFALATA_BARCODE,
barcode_pallet=pallet,
numero_cella=int(self.NON_SCAFFALATA_BARCODE),
refresh_picking_reservation=False,
)
current_location = await self.repository.fetch_current_location_by_pallet(pallet)
try:
@@ -354,6 +368,7 @@ class BarcodeService:
barcode_cella=target_barcode,
barcode_pallet=pallet,
numero_cella=target_numero_cella,
refresh_picking_reservation=is_picking_unload,
)
final_location = await self.repository.fetch_current_location_by_pallet(pallet)
@@ -476,7 +491,45 @@ class BarcodeService:
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
return await self.submit(scanned_pallet=pallet, destination_barcode=self.NON_SCAFFALATA_BARCODE)
await self.repository.execute_legacy_move(
operator_id=self.operator_id,
barcode_cella=self.NON_SCAFFALATA_BARCODE,
barcode_pallet=pallet,
numero_cella=int(self.NON_SCAFFALATA_BARCODE),
refresh_picking_reservation=False,
)
final_location = await self.repository.fetch_current_location_by_pallet(pallet)
try:
final_cell = int((final_location or {}).get("IDCella") or 0)
except Exception:
final_cell = 0
if final_cell != 1000:
self._state.scanned_pallet = pallet
self._state.destination_barcode = source
self._state.status_text = "Movimento non confermato: la UDC non risulta non scaffalata."
self._state.status_color = self.RED
return BarcodeActionResult(False, self._state, self._state.status_text)
try:
self._state = await self._build_post_move_state(
barcode_pallet=pallet,
destination_barcode=self.NON_SCAFFALATA_BARCODE,
destination_display=self.CONVENTIONAL_LOCATION_BY_CELL[1000],
last_priority_state=self._current_priority_state,
auto_advance_delay_ms=0,
)
except Exception as exc:
log_exception("Barcode WMS", exc, context=f"post source-check unload pallet={pallet} source={source}")
self._state = BarcodeViewState(
mode="confirm",
queue_label="Conferma movimento",
status_text="Movimento eseguito. Dettagli non aggiornati.",
status_color=self.GREEN_YELLOW,
destination_barcode=self.NON_SCAFFALATA_BARCODE,
scanned_pallet=pallet,
)
return BarcodeActionResult(True, self._state, self._state.status_text)
async def _block_closed_picking_free_move(
self,

View File

@@ -26,6 +26,11 @@ DEFAULT_DB_CONFIG: dict[str, Any] = {
"driver": "ODBC Driver 17 for SQL Server",
"trust_server_certificate": True,
"encrypt": "",
"query_profiler": {
"enabled": False,
"slow_ms": 0,
"sql_limit": 4000,
},
}

543
diagnostica.py Normal file
View File

@@ -0,0 +1,543 @@
"""Operational diagnostic checks for warehouse data quadrature."""
from __future__ import annotations
import tkinter as tk
from datetime import datetime
from tkinter import filedialog, messagebox, ttk
from typing import Any
import customtkinter as ctk
from busy_overlay import InlineBusyOverlay
from gestione_aree import AsyncRunner
from locale_text import load_locale_catalog, text as loc_text
from runtime_support import log_exception
from ui_tables import style_treeview, zebra_tag
from ui_theme import theme_color, theme_font, theme_section, theme_value
from version_info import module_version, versioned_title
from window_placement import place_window_fullsize_below_parent_later
__version__ = module_version(__name__)
SQL_SHIPPED_NOT_DISASSOCIATED = """
SELECT DISTINCT
LTRIM(RTRIM(g.BarcodePallet)) AS UDC,
CAST('Spedita ma non disassociata' AS varchar(64)) AS Diagnostica,
CONCAT(
RTRIM(c.Corsia),
' - ',
RTRIM(CAST(c.Colonna AS varchar(32))),
' - ',
RTRIM(CAST(c.Fila AS varchar(32)))
) AS NomeSimbolicoCella
FROM dbo.XMag_GiacenzaPallet AS g
INNER JOIN dbo.Celle AS c
ON c.ID = g.IDCella
INNER JOIN dbo.py_XMag_ViewPackingListStorico AS chiuse
ON LTRIM(RTRIM(chiuse.Pallet)) COLLATE Latin1_General_CI_AS =
LTRIM(RTRIM(g.BarcodePallet)) COLLATE Latin1_General_CI_AS
WHERE chiuse.StatoDocumento = 'D'
AND g.IDCella <> 9999
ORDER BY NomeSimbolicoCella, UDC;
"""
SQL_MULTIPLE_UDC_BY_CELL = """
WITH celle_multiple AS (
SELECT
g.IDCella
FROM dbo.XMag_GiacenzaPallet AS g
WHERE g.IDCella NOT IN (1000, 9999)
GROUP BY g.IDCella
HAVING COUNT(DISTINCT LTRIM(RTRIM(g.BarcodePallet))) > 1
)
SELECT
CONCAT(
RTRIM(c.Corsia),
' - ',
RTRIM(CAST(c.Colonna AS varchar(32))),
' - ',
RTRIM(CAST(c.Fila AS varchar(32)))
) AS CELLA,
LTRIM(RTRIM(g.BarcodePallet)) AS UDC
FROM dbo.XMag_GiacenzaPallet AS g
INNER JOIN celle_multiple AS cm
ON cm.IDCella = g.IDCella
INNER JOIN dbo.Celle AS c
ON c.ID = g.IDCella
ORDER BY CELLA, UDC;
"""
SQL_SAM_UDC_NOT_IN_WMS = """
WITH recent_lotser AS (
SELECT TOP (5000)
ls.ID,
LEFT(ls.NUMSER, 6) AS UDC,
ls.NUMLOT AS Lotto,
ls.IDARTICO
FROM SAMA1.dbo.LOTSER AS ls
WHERE NULLIF(LTRIM(RTRIM(LEFT(ls.NUMSER, 6))), '') IS NOT NULL
AND TRY_CONVERT(int, LTRIM(RTRIM(LEFT(ls.NUMSER, 6)))) > 0
AND LEN(LTRIM(RTRIM(LEFT(ls.NUMSER, 6)))) = 6
AND ls.NUMLOT LIKE CONCAT('P', RIGHT(CONVERT(varchar(4), YEAR(GETDATE())), 2), '%')
ORDER BY ls.ID DESC
), sam_udc AS (
SELECT
LTRIM(RTRIM(r.UDC)) AS UDC,
MIN(r.Lotto) AS Lotto,
MIN(a.CODICE) AS Prodotto,
MIN(a.DESCR) AS Descrizione,
MAX(r.ID) AS UltimoIDLotSer
FROM recent_lotser AS r
INNER JOIN SAMA1.dbo.ARTICO AS a
ON a.ID = r.IDARTICO
GROUP BY LTRIM(RTRIM(r.UDC))
)
SELECT TOP (100)
s.UDC,
s.Lotto,
s.Prodotto,
s.Descrizione
FROM sam_udc AS s
WHERE NOT EXISTS (
SELECT 1
FROM dbo.MagazziniPallet AS mp
WHERE LTRIM(RTRIM(mp.Attributo)) COLLATE Latin1_General_CI_AS =
s.UDC COLLATE Latin1_General_CI_AS
)
ORDER BY s.UltimoIDLotSer DESC;
"""
SHIPPED_NOT_DISASSOCIATED_COLUMNS = (
("UDC", "diagnostics.col.udc", "UDC", 130, "w"),
(
"Diagnostica",
"diagnostics.col.shipped_not_disassociated",
"Spedita ma non disassociata",
280,
"w",
),
("NomeSimbolicoCella", "diagnostics.col.symbolic_cell", "Nome simbolico cella", 240, "w"),
)
MULTIPLE_UDC_COLUMNS = (
("CELLA", "diagnostics.col.cell", "CELLA", 220, "w"),
("UDC", "diagnostics.col.udc", "UDC", 160, "w"),
)
SAM_UDC_NOT_IN_WMS_COLUMNS = (
("UDC", "diagnostics.col.udc", "UDC", 130, "w"),
("Lotto", "diagnostics.col.lot", "Lotto", 160, "w"),
("Prodotto", "diagnostics.col.product", "Prodotto", 150, "w"),
("Descrizione", "diagnostics.col.description", "Descrizione", 360, "w"),
)
def _rows_to_dicts(res: dict[str, Any] | None) -> list[dict[str, Any]]:
if not isinstance(res, dict):
return []
rows = res.get("rows") or []
cols = res.get("columns") or []
if rows and isinstance(rows[0], dict):
return [row for row in rows if isinstance(row, dict)]
out: list[dict[str, Any]] = []
for row in rows:
if isinstance(row, (list, tuple)) and cols:
out.append({str(cols[i]): row[i] for i in range(min(len(cols), len(row)))})
return out
class DiagnosticaWindow(ctk.CTkToplevel):
"""Window collecting read-only diagnostic queries."""
def __init__(self, parent: tk.Widget, db_client, session=None):
super().__init__(parent)
self.db_client = db_client
self.session = session
self._theme = theme_section("diagnostics_window", theme_section("search_window", {}))
self._locale_catalog = load_locale_catalog()
self._async = AsyncRunner(self)
self._busy = InlineBusyOverlay(self, self._theme)
self._load_in_progress = False
self._current_check = ""
self.var_status = tk.StringVar(value="")
self._last_export_slug = "diagnostica"
self._current_columns = SHIPPED_NOT_DISASSOCIATED_COLUMNS
self._column_titles: dict[str, str] = {}
self._sort_column = ""
self._sort_descending = False
self.title(
versioned_title(
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
__name__,
)
)
self.geometry(str(theme_value(self._theme, "window_geometry", "1100x680")))
minsize = theme_value(self._theme, "window_minsize", [900, 560])
self.minsize(int(minsize[0]), int(minsize[1]))
try:
self.configure(fg_color=theme_color(self._theme, "window_fg_color", ("#efefef", "#2f2f2f")))
except Exception:
pass
self._build_ui()
def _is_alive(self) -> bool:
try:
return bool(self.winfo_exists())
except tk.TclError:
return False
def _hide_busy_safe(self) -> None:
try:
self._busy.hide()
except Exception as exc:
log_exception(__name__, exc, context="hide busy diagnostica")
def _build_ui(self) -> None:
self.grid_rowconfigure(2, weight=1)
self.grid_columnconfigure(0, weight=1)
top = ctk.CTkFrame(
self,
fg_color=theme_color(self._theme, "toolbar_frame_fg_color", ("#d7d7d7", "#3b3b3b")),
)
top.grid(row=0, column=0, sticky="ew", padx=8, pady=8)
top.grid_columnconfigure(3, weight=1)
button_font = theme_font(self._theme, "toolbar_button_font", ("Segoe UI", 10, "bold"))
ctk.CTkButton(
top,
text=loc_text(
"diagnostics.button.shipped_not_disassociated",
catalog=self._locale_catalog,
default="UDC spedite non disassociate",
),
command=self._load_shipped_not_disassociated,
font=button_font,
).grid(row=0, column=0, sticky="w", padx=(0, 8))
ctk.CTkButton(
top,
text=loc_text(
"diagnostics.button.multiple_udc_by_cell",
catalog=self._locale_catalog,
default="Celle con multiple UDC",
),
command=self._load_multiple_udc_by_cell,
font=button_font,
).grid(row=0, column=1, sticky="w", padx=(0, 8))
ctk.CTkButton(
top,
text=loc_text(
"diagnostics.button.sam_udc_not_in_wms",
catalog=self._locale_catalog,
default="Ultime UDC SAM non in WMS",
),
command=self._load_sam_udc_not_in_wms,
font=button_font,
).grid(row=0, column=2, sticky="w", padx=(0, 8))
self.btn_export = ctk.CTkButton(
top,
text=loc_text("diagnostics.button.export", catalog=self._locale_catalog, default="Esporta XLSX"),
command=self._export_xlsx,
font=button_font,
state="disabled",
)
self.btn_export.grid(row=0, column=4, sticky="e")
ctk.CTkLabel(
self,
textvariable=self.var_status,
anchor="w",
font=theme_font(self._theme, "status_font", ("Segoe UI", 10, "bold")),
).grid(row=1, column=0, sticky="ew", padx=10, pady=(0, 6))
wrap = ctk.CTkFrame(self)
wrap.grid(row=2, column=0, sticky="nsew", padx=8, pady=(0, 8))
wrap.grid_rowconfigure(0, weight=1)
wrap.grid_columnconfigure(0, weight=1)
self.tree = ttk.Treeview(wrap, show="headings")
self._configure_tree_columns(self._current_columns)
style_treeview(
self.tree,
style_name="Diagnostics.Treeview",
rowheight=22,
font=("", 9),
heading_font=("", 9, "bold"),
)
sy = ttk.Scrollbar(wrap, orient="vertical", command=self.tree.yview)
sx = ttk.Scrollbar(wrap, orient="horizontal", command=self.tree.xview)
self.tree.configure(yscrollcommand=sy.set, xscrollcommand=sx.set)
self.tree.grid(row=0, column=0, sticky="nsew")
sy.grid(row=0, column=1, sticky="ns")
sx.grid(row=1, column=0, sticky="ew")
def _set_status(self, text: str) -> None:
self.var_status.set(text)
def _configure_tree_columns(self, columns) -> None:
self.tree.delete(*self.tree.get_children(""))
keys = tuple(str(col[0]) for col in columns)
self.tree.configure(columns=keys, show="headings")
self._sort_column = ""
self._sort_descending = False
self._column_titles = {}
for key, locale_key, default, width, anchor in columns:
title = loc_text(str(locale_key), catalog=self._locale_catalog, default=str(default))
self._column_titles[str(key)] = title
self.tree.heading(
key,
text=title,
command=lambda col=str(key): self._sort_by_column(col),
)
self.tree.column(key, width=int(width), anchor=str(anchor), stretch=True)
def _refresh_sort_headings(self) -> None:
for key, title in self._column_titles.items():
suffix = ""
if key == self._sort_column:
suffix = " v" if self._sort_descending else " ^"
self.tree.heading(key, text=f"{title}{suffix}", command=lambda col=key: self._sort_by_column(col))
def _sort_key(self, value: Any) -> tuple[int, Any]:
text = str(value or "").strip()
if not text:
return (2, "")
normalized = text.replace(".", "").replace(",", ".")
try:
return (0, float(normalized))
except ValueError:
return (1, text.casefold())
def _sort_by_column(self, column: str) -> None:
columns = list(self.tree["columns"])
if column not in columns:
return
descending = not self._sort_descending if self._sort_column == column else False
col_index = columns.index(column)
rows = []
for iid in self.tree.get_children(""):
values = self.tree.item(iid, "values")
value = values[col_index] if col_index < len(values) else ""
rows.append((self._sort_key(value), iid))
rows.sort(key=lambda item: item[0], reverse=descending)
for index, (_key, iid) in enumerate(rows):
self.tree.move(iid, "", index)
self.tree.item(iid, tags=(zebra_tag(index),))
self._sort_column = column
self._sort_descending = descending
self._refresh_sort_headings()
def _load_shipped_not_disassociated(self) -> None:
self._run_check(
key="shipped_not_disassociated",
sql=SQL_SHIPPED_NOT_DISASSOCIATED,
columns=SHIPPED_NOT_DISASSOCIATED_COLUMNS,
busy_text=loc_text(
"diagnostics.busy.shipped_not_disassociated",
catalog=self._locale_catalog,
default="Cerco UDC spedite ma ancora in cella...",
),
)
def _load_multiple_udc_by_cell(self) -> None:
self._run_check(
key="multiple_udc_by_cell",
sql=SQL_MULTIPLE_UDC_BY_CELL,
columns=MULTIPLE_UDC_COLUMNS,
busy_text=loc_text(
"diagnostics.busy.multiple_udc_by_cell",
catalog=self._locale_catalog,
default="Cerco celle con multiple UDC...",
),
)
def _load_sam_udc_not_in_wms(self) -> None:
self._run_check(
key="sam_udc_not_in_wms",
sql=SQL_SAM_UDC_NOT_IN_WMS,
columns=SAM_UDC_NOT_IN_WMS_COLUMNS,
busy_text=loc_text(
"diagnostics.busy.sam_udc_not_in_wms",
catalog=self._locale_catalog,
default="Cerco le ultime UDC presenti in SAM ma non ancora in WMS...",
),
)
def _run_check(self, *, key: str, sql: str, columns, busy_text: str) -> None:
if self._load_in_progress or not self._is_alive():
return
async def job():
return await self.db_client.query_json(sql, as_dict_rows=True)
self._load_in_progress = True
self._current_check = key
self._last_export_slug = key
self._current_columns = columns
self._configure_tree_columns(columns)
try:
self.btn_export.configure(state="disabled")
except Exception:
pass
try:
self._busy.show(busy_text)
self._async.run(job(), self._on_loaded, self._on_error)
except Exception as exc:
self._load_in_progress = False
self._hide_busy_safe()
log_exception(__name__, exc, context=f"avvio diagnostica {key}")
messagebox.showerror(
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
str(exc),
parent=self if self._is_alive() else None,
)
def _on_loaded(self, res: dict[str, Any] | None) -> None:
self._load_in_progress = False
self._hide_busy_safe()
if not self._is_alive():
return
try:
rows = _rows_to_dicts(res)
self.tree.delete(*self.tree.get_children(""))
keys = [str(col[0]) for col in self._current_columns]
for index, row in enumerate(rows):
self.tree.insert(
"",
"end",
values=tuple(row.get(key) or "" for key in keys),
tags=(zebra_tag(index),),
)
try:
self.btn_export.configure(state="normal" if rows else "disabled")
except Exception:
pass
self._set_status(
loc_text(
"diagnostics.status.rows",
catalog=self._locale_catalog,
default="Righe trovate: {count}",
).format(count=len(rows))
)
except Exception as exc:
log_exception(__name__, exc, context="render diagnostica")
messagebox.showerror(
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
str(exc),
parent=self,
)
def _on_error(self, exc: BaseException) -> None:
self._load_in_progress = False
self._hide_busy_safe()
log_exception(__name__, exc, context=f"query diagnostica {self._current_check}")
if not self._is_alive():
return
messagebox.showerror(
loc_text("diagnostics.title", catalog=self._locale_catalog, default="Diagnostica"),
str(exc),
parent=self,
)
def _export_xlsx(self) -> None:
"""Export the currently visible diagnostic grid to an Excel file."""
rows = [self.tree.item(iid, "values") for iid in self.tree.get_children("")]
if not rows:
messagebox.showinfo(
loc_text("diagnostics.export.title", catalog=self._locale_catalog, default="Esporta"),
loc_text(
"diagnostics.export.empty",
catalog=self._locale_catalog,
default="Non ci sono righe da esportare.",
),
parent=self,
)
return
try:
from openpyxl import Workbook
from openpyxl.styles import Alignment, Font
from openpyxl.utils import get_column_letter
except Exception as exc:
messagebox.showerror(
loc_text("diagnostics.export.title", catalog=self._locale_catalog, default="Esporta"),
loc_text(
"diagnostics.export.dep",
catalog=self._locale_catalog,
default="Per l'esportazione serve 'openpyxl' (pip install openpyxl).",
).format(error=exc),
parent=self,
)
return
ts = datetime.now().strftime("%Y%m%d_%H%M")
default_name = f"{self._last_export_slug}_{ts}.xlsx"
path = filedialog.asksaveasfilename(
parent=self,
title=loc_text("diagnostics.export.title", catalog=self._locale_catalog, default="Esporta"),
defaultextension=".xlsx",
filetypes=[("Excel Workbook", "*.xlsx")],
initialfile=default_name,
)
if not path:
return
try:
wb = Workbook()
ws = wb.active
ws.title = "Diagnostica"
columns = list(self.tree["columns"])
headers = [str(self.tree.heading(col, "text") or col) for col in columns]
for col_index, header in enumerate(headers, start=1):
cell = ws.cell(row=1, column=col_index, value=header)
cell.font = Font(bold=True)
cell.alignment = Alignment(horizontal="center", vertical="center")
for row_index, row in enumerate(rows, start=2):
for col_index, value in enumerate(row, start=1):
ws.cell(row=row_index, column=col_index, value=value)
widths: dict[int, int] = {}
for row in ws.iter_rows(values_only=True):
for col_index, value in enumerate(row, start=1):
widths[col_index] = max(widths.get(col_index, 0), len("" if value is None else str(value)))
for col_index, width in widths.items():
ws.column_dimensions[get_column_letter(col_index)].width = min(max(width + 2, 12), 70)
wb.save(path)
messagebox.showinfo(
loc_text("diagnostics.export.title", catalog=self._locale_catalog, default="Esporta"),
loc_text("diagnostics.export.ok", catalog=self._locale_catalog, default="File creato:\n{path}").format(path=path),
parent=self,
)
except Exception as exc:
log_exception(__name__, exc, context="export diagnostica xlsx")
messagebox.showerror(
loc_text("diagnostics.export.title", catalog=self._locale_catalog, default="Esporta"),
loc_text(
"diagnostics.export.error",
catalog=self._locale_catalog,
default="Errore durante l'esportazione:\n{error}",
).format(error=exc),
parent=self,
)
def open_diagnostica_window(parent: tk.Misc, db_client, session=None) -> tk.Misc:
"""Open the diagnostics window."""
win = DiagnosticaWindow(parent, db_client, session=session)
place_window_fullsize_below_parent_later(parent, win)
win.bind("<Escape>", lambda _e: win.destroy())
return win

View File

@@ -10,6 +10,7 @@
"launcher.history_udc": "Storico movimenti UDC",
"launcher.pickinglist": "Gestione Picking List",
"launcher.history_pickinglist": "Storico Picking List",
"launcher.diagnostics": "Diagnostica",
"launcher.arrange": "Ridisponi finestre",
"launcher.exit": "Esci",
"launcher.already_running_title": "Warehouse",
@@ -75,6 +76,27 @@
"history.picking.msg.title": "Storico Picking List",
"history.picking.msg.load_error": "Errore caricamento:\n{error}",
"history.picking.msg.detail_error": "Errore dettaglio:\n{error}",
"diagnostics.title": "Diagnostica",
"diagnostics.button.shipped_not_disassociated": "UDC spedite non disassociate",
"diagnostics.button.multiple_udc_by_cell": "Celle con multiple UDC",
"diagnostics.button.sam_udc_not_in_wms": "Ultime UDC SAM non in WMS",
"diagnostics.button.export": "Esporta XLSX",
"diagnostics.busy.shipped_not_disassociated": "Cerco UDC spedite ma ancora in cella...",
"diagnostics.busy.multiple_udc_by_cell": "Cerco celle con multiple UDC...",
"diagnostics.busy.sam_udc_not_in_wms": "Cerco le ultime UDC presenti in SAM ma non ancora in WMS...",
"diagnostics.status.rows": "Righe trovate: {count}",
"diagnostics.col.udc": "UDC",
"diagnostics.col.cell": "CELLA",
"diagnostics.col.lot": "Lotto",
"diagnostics.col.product": "Prodotto",
"diagnostics.col.description": "Descrizione",
"diagnostics.col.shipped_not_disassociated": "Spedita ma non disassociata",
"diagnostics.col.symbolic_cell": "Nome simbolico cella",
"diagnostics.export.title": "Esporta",
"diagnostics.export.empty": "Non ci sono righe da esportare.",
"diagnostics.export.dep": "Per l'esportazione serve 'openpyxl' (pip install openpyxl).",
"diagnostics.export.ok": "File creato:\n{path}",
"diagnostics.export.error": "Errore durante l'esportazione:\n{error}",
"reset.title": "Gestione Corsie - svuotamento celle per corsia",
"reset.label.aisle": "Corsia:",
"reset.button.refresh": "Carica",
@@ -125,6 +147,7 @@
"launcher.history_udc": "UDC Movement History",
"launcher.pickinglist": "Picking List Management",
"launcher.history_pickinglist": "Picking List History",
"launcher.diagnostics": "Diagnostics",
"launcher.arrange": "Arrange windows",
"launcher.exit": "Exit",
"launcher.already_running_title": "Warehouse",
@@ -190,6 +213,27 @@
"history.picking.msg.title": "Picking List History",
"history.picking.msg.load_error": "Load failed:\n{error}",
"history.picking.msg.detail_error": "Detail load failed:\n{error}",
"diagnostics.title": "Diagnostics",
"diagnostics.button.shipped_not_disassociated": "Shipped UDC not disassociated",
"diagnostics.button.multiple_udc_by_cell": "Cells with multiple UDC",
"diagnostics.button.sam_udc_not_in_wms": "Latest UDC in SAM not in WMS",
"diagnostics.button.export": "Export XLSX",
"diagnostics.busy.shipped_not_disassociated": "Searching shipped UDC still assigned to cells...",
"diagnostics.busy.multiple_udc_by_cell": "Searching cells with multiple UDC...",
"diagnostics.busy.sam_udc_not_in_wms": "Searching latest UDC present in SAM but not yet in WMS...",
"diagnostics.status.rows": "Rows found: {count}",
"diagnostics.col.udc": "UDC",
"diagnostics.col.cell": "CELL",
"diagnostics.col.lot": "Lot",
"diagnostics.col.product": "Product",
"diagnostics.col.description": "Description",
"diagnostics.col.shipped_not_disassociated": "Shipped but not disassociated",
"diagnostics.col.symbolic_cell": "Symbolic cell name",
"diagnostics.export.title": "Export",
"diagnostics.export.empty": "There are no rows to export.",
"diagnostics.export.dep": "Export requires 'openpyxl' (pip install openpyxl).",
"diagnostics.export.ok": "File created:\n{path}",
"diagnostics.export.error": "Export failed:\n{error}",
"reset.title": "Aisle Management - empty cells by aisle",
"reset.label.aisle": "Aisle:",
"reset.button.refresh": "Load",

11
main.py
View File

@@ -22,6 +22,7 @@ from async_loop_singleton import get_global_loop, stop_global_loop
from async_msssql_query import AsyncMSSQLClient
from audit_log import log_session_event
from db_config import build_dsn_from_config, ensure_db_config
from diagnostica import open_diagnostica_window
from gestione_layout import open_layout_window
from gestione_pickinglist import open_pickinglist_window
from login_window import prompt_login
@@ -161,6 +162,7 @@ class Launcher(ctk.CTk):
"storico_udc",
"pickinglist",
"storico_pickinglist",
"diagnostica",
]
def __init__(self, session: UserSession, db_client: AsyncMSSQLClient):
@@ -268,6 +270,15 @@ class Launcher(ctk.CTk):
lambda: open_storico_pickinglist_window(self, self.db_client, session=self.session),
),
),
(
"diagnostica",
loc_text("launcher.diagnostics", catalog=self._locale_catalog, default="Diagnostica"),
"launcher.open_diagnostics",
lambda: self._open_or_focus_child_window(
"diagnostica",
lambda: open_diagnostica_window(self, self.db_client, session=self.session),
),
),
(
"arrange",
loc_text("launcher.arrange", catalog=self._locale_catalog, default="Ridisponi finestre"),

View File

@@ -93,7 +93,7 @@ SELECT
FROM meta m
LEFT JOIN agg a ON a.Documento = m.Documento
WHERE (:documento IS NULL OR CAST(m.Documento AS varchar(32)) LIKE CONCAT('%', :documento, '%'))
ORDER BY m.Documento DESC;
ORDER BY m.DataDocumento DESC, m.Documento DESC;
"""
# Detail query:

View File

@@ -8,6 +8,7 @@
"launcher.open_history_udc": "Apre lo storico movimenti UDC per ricostruire carichi, scarichi, celle e utenti coinvolti.",
"launcher.open_pickinglist": "Apre la gestione delle picking list per prenotare, controllare e aggiornare le liste di prelievo.",
"launcher.open_history_pickinglist": "Apre lo storico picking list per consultare liste, stato operativo e dettaglio UDC.",
"launcher.open_diagnostics": "Apre la diagnostica operativa con quadrature e controlli di coerenza sui dati di magazzino.",
"launcher.arrange_windows": "Dispone in cascata le finestre aperte seguendo l'ordine dei pulsanti del launcher.",
"launcher.exit": "Chiude l'applicazione in modo pulito terminando la sessione utente e rilasciando la connessione condivisa al database.",
"dbconfig.heading": "Spiega che qui si inseriscono i dati minimi per permettere al programma di collegarsi al database del magazzino al primo avvio.",
@@ -42,6 +43,7 @@
"launcher.open_history_udc": "Open UDC movement history to review loads, unloads, cells and users involved.",
"launcher.open_pickinglist": "Open picking list management to reserve, inspect and update picking lists.",
"launcher.open_history_pickinglist": "Open picking-list history to inspect lists, operational status and UDC detail.",
"launcher.open_diagnostics": "Open operational diagnostics with data consistency checks and warehouse quadratures.",
"launcher.arrange_windows": "Arrange open windows in cascade order following the launcher buttons.",
"launcher.exit": "Close the application cleanly by ending the user session and releasing the shared database connection.",
"dbconfig.heading": "Explain that this form collects the minimum data needed to connect the program to the warehouse database on first startup.",

View File

@@ -20,6 +20,7 @@ ALL_ACTIONS: FrozenSet[str] = frozenset(
"launcher.open_history_udc",
"launcher.open_pickinglist",
"launcher.open_history_pickinglist",
"launcher.open_diagnostics",
"launcher.arrange_windows",
"launcher.exit",
"reset_corsie.view",
@@ -27,6 +28,7 @@ ALL_ACTIONS: FrozenSet[str] = frozenset(
"non_shelved.view",
"history_udc.view",
"history_pickinglist.view",
"diagnostics.view",
"multi_udc.view",
"layout.view",
"layout.carico",

View File

@@ -10,14 +10,15 @@ APP_VERSION = "1.0.0"
MODULE_VERSIONS: dict[str, str] = {
"app": APP_VERSION,
"async_loop_singleton": "1.0.0",
"async_msssql_query": "1.0.0",
"async_msssql_query": "1.0.1",
"audit_log": "1.0.0",
"main": "1.0.1",
"barcode_client": "1.0.24",
"barcode_repository": "1.0.10",
"barcode_service": "1.0.22",
"main": "1.0.2",
"barcode_client": "1.0.26",
"barcode_repository": "1.0.12",
"barcode_service": "1.0.24",
"busy_overlay": "1.0.0",
"db_config": "1.0.0",
"diagnostica": "1.0.4",
"gestione_aree": "1.0.1",
"gestione_layout": "1.0.2",
"gestione_pickinglist": "1.0.4",
@@ -28,12 +29,12 @@ MODULE_VERSIONS: dict[str, str] = {
"reset_corsie": "1.0.0",
"runtime_support": "1.0.1",
"search_pallets": "1.0.0",
"storico_pickinglist": "1.0.3",
"storico_pickinglist": "1.0.4",
"storico_udc": "1.0.0",
"tooltips": "1.0.0",
"udc_non_scaffalate": "1.0.1",
"ui_theme": "1.0.0",
"user_session": "1.0.0",
"user_session": "1.0.1",
"view_celle_multi_udc": "1.0.0",
"window_placement": "1.0.0",
}