Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 04406e840d | |||
| a60610c03e |
70
FREEZE_2.0_WAREHOUSE_MONOLISTA.md
Normal file
70
FREEZE_2.0_WAREHOUSE_MONOLISTA.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# Warehouse monolista - freeze 2.0
|
||||
|
||||
Data: 02/10/2026.
|
||||
Titolo release: warehouse monolista.
|
||||
Tag Git: `warehouse-monolista-2.0`.
|
||||
|
||||
## Scopo e contenuto
|
||||
|
||||
Punto di ripristino prima dello sviluppo del prelievo guidato di due liste.
|
||||
La versione conserva la prenotazione singola e i cicli F1/F2 separati.
|
||||
Include i sorgenti e gli script SQL gia' versionati, oltre alla correzione
|
||||
del documento fisso F1/F2, ai suoi test e alla relativa documentazione.
|
||||
|
||||
La denominazione 2.0 identifica questo freeze, non una rinumerazione di tutti
|
||||
i moduli. Il barcode conserva la versione visibile 1.0.27; repository 1.0.14,
|
||||
servizio 1.0.25. Il registro delle versioni resta `version_info.py`.
|
||||
|
||||
La specifica `specifica_prelievo_due_pickinglist.md` descrive lo sviluppo
|
||||
successivo, NON una funzionalita' gia' implementata in questa release.
|
||||
Comprende il vincolo di due liste nella stessa area operativa (5 oppure 6).
|
||||
|
||||
## Verifiche del freeze
|
||||
|
||||
Gli 11 test di `tests/test_barcode_document_binding.py` sono passati con:
|
||||
|
||||
```bat
|
||||
python -B -m unittest discover -s tests -v
|
||||
```
|
||||
|
||||
Si tratta di test automatici con repository simulato, non di un collaudo
|
||||
completo della GUI o del terminalino fisico. Non eseguono movimenti sul DB.
|
||||
|
||||
## Database e file locali
|
||||
|
||||
La correzione F1/F2 non richiede nuovi oggetti SQL. Le patch gia' necessarie
|
||||
alla versione precedente restano nel repository, inclusa
|
||||
`apply_online_python_wms_full_patch.sql`. Questo freeze non esegue patch SQL
|
||||
e non costituisce un backup dei database Mediseawall e SAM.
|
||||
|
||||
Gli script in `sql_tests/` servono soltanto alla preparazione locale dei test:
|
||||
NON lanciarli in produzione. Il ripristino delle sole testate non annulla
|
||||
eventuali movimenti successivi; leggere `sql_tests/README.md`.
|
||||
|
||||
Configurazione locale `db_connection.json`, log, cache, impostazioni IDE,
|
||||
registrazioni e vecchi ZIP locali non vengono aggiunti a questo commit.
|
||||
Conservare separatamente configurazione e backup coerenti dei database
|
||||
prima di modificare schema o dati per il futuro prelievo abbinato.
|
||||
|
||||
## Recuperare esattamente il freeze
|
||||
|
||||
Chiudere l'applicazione. Nella cartella del repository, con working tree pulito:
|
||||
|
||||
```bat
|
||||
git fetch origin --tags
|
||||
git switch --detach warehouse-monolista-2.0
|
||||
git describe --tags --exact-match
|
||||
python -m pip install -r requirements.txt
|
||||
```
|
||||
|
||||
Se Git segnala modifiche locali, fermarsi e salvarle prima: non forzare la
|
||||
sovrascrittura della configurazione o dei sorgenti. Per una prima installazione:
|
||||
|
||||
```bat
|
||||
git clone --branch warehouse-monolista-2.0 --single-branch https://gitea.alessandrobonvicini.it/administrator/ware_house.git C:\flywms-monolista-2.0
|
||||
```
|
||||
|
||||
Il checkout di un tag e' intenzionalmente in detached HEAD: identifica una
|
||||
versione fissa. `git pull origin main` non e' il comando per restare su questo
|
||||
freeze. Il ritorno al codice precedente non ripristina il database: eventuali
|
||||
future patch richiederanno il rispettivo rollback compatibile o un backup.
|
||||
104
INSTALLAZIONE_MONOLISTA_INVENTARIO.md
Normal file
104
INSTALLAZIONE_MONOLISTA_INVENTARIO.md
Normal file
@@ -0,0 +1,104 @@
|
||||
# Aggiornamento reparto: monolista con Inventario
|
||||
|
||||
Release: `warehouse-monolista-2.0.1-inventario`, ramo di distribuzione `main`.
|
||||
La bilista rimane separata su `codex/doppia-pickinglist` e non e' inclusa.
|
||||
Modulo Inventario 1.1.0, launcher 1.0.3. Barcode e logica picking monolista
|
||||
invariati rispetto al freeze `warehouse-monolista-2.0`.
|
||||
|
||||
## Prima dell'aggiornamento
|
||||
|
||||
Chiudere backoffice e terminalini Python che usano il database.
|
||||
Conservare una copia della cartella installata, in particolare dei file locali
|
||||
di configurazione e dei log utili. Non pubblicare db_connection.json su Git.
|
||||
Se si aggiorna il DB, eseguire prima un backup e conservarne il ripristino.
|
||||
|
||||
## Aggiornare il programma con Git
|
||||
|
||||
Dal prompt nella cartella di installazione (esempio C:\flywms):
|
||||
|
||||
```bat
|
||||
cd /d C:\flywms
|
||||
git status --short
|
||||
git rev-parse HEAD
|
||||
git fetch origin --tags
|
||||
git switch main
|
||||
git pull --ff-only origin main
|
||||
python -m pip install -r requirements.txt
|
||||
git log -1 --oneline
|
||||
git describe --tags --exact-match HEAD
|
||||
```
|
||||
|
||||
Annotare il vecchio commit prima dell'aggiornamento. Se Git segnala modifiche
|
||||
locali o una divergenza, fermarsi: NON usare reset --hard, clean o push --force.
|
||||
I file locali non tracciati, come la configurazione DB, non devono essere eliminati.
|
||||
Verificare che la connessione rimanga quella del reparto, non del PC di sviluppo.
|
||||
|
||||
Il tag identifica questa pubblicazione; se in futuro main avanza, il comando
|
||||
describe potra' mostrare un'altra release. Per scegliere esattamente questa:
|
||||
|
||||
```bat
|
||||
git switch --detach warehouse-monolista-2.0.1-inventario
|
||||
```
|
||||
|
||||
Per riprendere in seguito gli aggiornamenti normali: git switch main, poi
|
||||
git pull --ff-only origin main.
|
||||
|
||||
## Script SQL da usare
|
||||
|
||||
Il cumulativo MONOLISTA e' `apply_online_python_wms_full_patch.sql`, ottenuto
|
||||
dal ramo main/tag di questa release. Aprirlo in SSMS, selezionare esplicitamente
|
||||
il database Mediseawall e lanciarlo dopo backup, con client Python chiusi.
|
||||
Controllare tutti i messaggi di errore: lo script usa piu' batch GO e non e'
|
||||
una singola transazione atomica; il solo PRINT finale non certifica il successo.
|
||||
|
||||
Sono gia' inclusi:
|
||||
- oggetti Python di prenotazione e viste picking residue;
|
||||
- oggetti per storico picking e salti UDC;
|
||||
- filtro operativo massimo 30 giorni, selezionabile nella UI a 10/15/20/30;
|
||||
- LEFT JOIN per le destinazioni senza nazione;
|
||||
- tabella py_PickingListPrelievoSequenza e vista py_ViewPackingListPrelievo;
|
||||
- ordine di default con non scaffalate prima degli scaffali e sequenza
|
||||
personalizzata per documento, che nella monolista prevale sul default.
|
||||
|
||||
Se si applica il cumulativo non occorre ripetere separatamente le patch
|
||||
days_filter, optional_destination_country e sequence. I singoli script e i
|
||||
rollback gia' presenti rimangono nel repository per interventi mirati:
|
||||
non eseguirli tutti indiscriminatamente e non usarli come rollback cumulativo.
|
||||
|
||||
ATTENZIONE: nel ramo BILISTA il file cumulativo ha lo stesso nome ma comprende
|
||||
anche oggetti py_PickingPair. Non prelevarlo da quella cartella/ramo per questa
|
||||
installazione. Questa pubblicazione non esegue alcuno script sul DB online.
|
||||
|
||||
## Inventario: nessuna nuova patch DB
|
||||
|
||||
Se il DB ha gia' tutte le patch monolista sopra elencate, per aggiungere
|
||||
l'inventario non serve rilanciare il cumulativo: gli script SQL sono invariati
|
||||
rispetto al freeze monolista 2.0.
|
||||
|
||||
`inventory_report.sql` DEVE rimanere accanto a inventory_service.py, ma NON va
|
||||
incollato in SSMS: e' la query parametrizzata eseguita dal programma.
|
||||
L'utente DB deve poter leggere le sorgenti WMS e SAMA1, incluso EXTTACLOTSER.
|
||||
Non vengono create tabelle persistenti per l'inventario.
|
||||
|
||||
Avviare il programma come di consueto, aprire Inventario, scegliere la data,
|
||||
eseguire il calcolo e provare l'export. Una seconda pressione di Inventario
|
||||
deve riportare la stessa finestra in primo piano. Nessuna query parte
|
||||
automaticamente all'apertura della finestra.
|
||||
|
||||
Prima dell'inventario ufficiale validare etichette e stampa SAM su un campione,
|
||||
con movimentazioni ferme e dati ERP/WMS coerenti. Il perimetro provvisorio e'
|
||||
guidato dai prodotti/lotti WMS; le limitazioni sono in specifica_inventario.md.
|
||||
|
||||
## Ritorno alla precedente monolista
|
||||
|
||||
Con programmi chiusi e senza modifiche locali ai sorgenti:
|
||||
|
||||
```bat
|
||||
git switch --detach warehouse-monolista-2.0
|
||||
```
|
||||
|
||||
Oppure usare il commit precedente annotato, se il PC partiva da un'altra
|
||||
versione. Il nuovo inventario non modifica lo schema o i dati persistenti,
|
||||
quindi il suo solo aggiornamento non richiede rollback SQL. Se sono state
|
||||
applicate anche patch mancanti di versioni precedenti, valutarne separatamente
|
||||
il ripristino usando il backup: tornare al vecchio codice non annulla il DB.
|
||||
@@ -29,6 +29,7 @@ SELECT TOP (1)
|
||||
FROM dbo.py_ViewPackingListPrelievo AS pl
|
||||
WHERE Ordinamento > 0
|
||||
AND IDStato = :id_stato
|
||||
AND (:documento IS NULL OR pl.Documento = TRY_CONVERT(int, :documento))
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM dbo.py_BarcodePickingListSkip AS s
|
||||
@@ -39,7 +40,7 @@ WHERE Ordinamento > 0
|
||||
AND s.IDStato = pl.IDStato
|
||||
AND s.Risolto = 0
|
||||
)
|
||||
ORDER BY OrdinePrelievoGruppo, Ordinamento, Pallet;
|
||||
ORDER BY OrdinePrelievoGruppo, Ordinamento, Pallet, Documento;
|
||||
"""
|
||||
|
||||
SQL_PICKING_BY_PALLET = """
|
||||
@@ -55,6 +56,7 @@ SELECT TOP (1)
|
||||
IDStato
|
||||
FROM dbo.py_ViewPackingListPrelievo
|
||||
WHERE Pallet COLLATE Latin1_General_CI_AS = :pallet COLLATE Latin1_General_CI_AS
|
||||
AND (:documento IS NULL OR Documento = TRY_CONVERT(int, :documento))
|
||||
ORDER BY OrdinePrelievoGruppo, Ordinamento, Pallet;
|
||||
"""
|
||||
|
||||
@@ -222,6 +224,7 @@ SELECT TOP (1)
|
||||
COUNT(*) AS SkippedCount
|
||||
FROM dbo.py_BarcodePickingListSkip AS s
|
||||
WHERE s.IDStato = :id_stato
|
||||
AND (:documento IS NULL OR s.Documento = :documento)
|
||||
AND s.Risolto = 0
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
@@ -229,11 +232,20 @@ WHERE s.IDStato = :id_stato
|
||||
WHERE CAST(pl.Documento AS varchar(50)) COLLATE Latin1_General_CI_AS =
|
||||
s.Documento COLLATE Latin1_General_CI_AS
|
||||
AND pl.IDStato = :id_stato
|
||||
AND CAST(pl.Pallet AS varchar(50)) COLLATE Latin1_General_CI_AS =
|
||||
s.Pallet COLLATE Latin1_General_CI_AS
|
||||
)
|
||||
GROUP BY s.Documento
|
||||
ORDER BY MIN(s.DataOra);
|
||||
"""
|
||||
|
||||
SQL_PICKING_DOCUMENT_REMAINING = """
|
||||
SELECT COUNT(DISTINCT Pallet) AS RemainingCount
|
||||
FROM dbo.py_XMag_ViewPackingListStorico
|
||||
WHERE Documento = TRY_CONVERT(int, :documento)
|
||||
AND Cella <> 9999;
|
||||
"""
|
||||
|
||||
SQL_RELEASE_PICKING_DOCUMENT = """
|
||||
SET NOCOUNT ON;
|
||||
DECLARE @RC int = 0;
|
||||
@@ -290,17 +302,21 @@ class BarcodeRepository:
|
||||
def __init__(self, db_client):
|
||||
self.db_client = db_client
|
||||
|
||||
async def fetch_next_picking(self, id_stato: int) -> dict[str, Any] | None:
|
||||
"""Return the next pallet proposed by the legacy F1/F2 queue logic."""
|
||||
async def fetch_next_picking(self, id_stato: int, documento: str | None = None) -> dict[str, Any] | None:
|
||||
"""Select a document initially, then fetch only within that document."""
|
||||
|
||||
res = await self.db_client.query_json(SQL_NEXT_PICKING, {"id_stato": int(id_stato)})
|
||||
res = await self.db_client.query_json(SQL_NEXT_PICKING, {
|
||||
"id_stato": int(id_stato), "documento": documento,
|
||||
})
|
||||
rows = _rows_to_dicts(res)
|
||||
return rows[0] if rows else None
|
||||
|
||||
async def fetch_picking_by_pallet(self, pallet: str) -> dict[str, Any] | None:
|
||||
async def fetch_picking_by_pallet(self, pallet: str, documento: str | None = None) -> dict[str, Any] | None:
|
||||
"""Return one picking row for the given pallet, if still present in the queue."""
|
||||
|
||||
res = await self.db_client.query_json(SQL_PICKING_BY_PALLET, {"pallet": str(pallet or "").strip()})
|
||||
res = await self.db_client.query_json(SQL_PICKING_BY_PALLET, {
|
||||
"pallet": str(pallet or "").strip(), "documento": documento,
|
||||
})
|
||||
rows = _rows_to_dicts(res)
|
||||
return rows[0] if rows else None
|
||||
|
||||
@@ -376,13 +392,21 @@ class BarcodeRepository:
|
||||
),
|
||||
)
|
||||
|
||||
async def fetch_active_skipped_document(self, id_stato: int) -> dict[str, Any] | None:
|
||||
"""Return a reserved document whose remaining pallets were all skipped."""
|
||||
async def fetch_active_skipped_document(self, id_stato: int, documento: str | None = None) -> dict[str, Any] | None:
|
||||
"""Find skipped residuals, restricted to the active document when set."""
|
||||
|
||||
res = await self.db_client.query_json(SQL_ACTIVE_SKIPPED_DOCUMENT, {"id_stato": int(id_stato)})
|
||||
res = await self.db_client.query_json(SQL_ACTIVE_SKIPPED_DOCUMENT, {
|
||||
"id_stato": int(id_stato), "documento": documento,
|
||||
})
|
||||
rows = _rows_to_dicts(res)
|
||||
return rows[0] if rows else None
|
||||
|
||||
async def count_picking_document_remaining(self, documento: str) -> int:
|
||||
"""Check residuals independently of priority before declaring completion."""
|
||||
res = await self.db_client.query_json(SQL_PICKING_DOCUMENT_REMAINING, {"documento": documento})
|
||||
rows = _rows_to_dicts(res)
|
||||
return int(rows[0]["RemainingCount"]) if rows else 0
|
||||
|
||||
async def release_picking_document(self, *, documento: str, operator_id: int) -> int:
|
||||
"""Release a reserved picking-list document without closing its residual rows."""
|
||||
|
||||
|
||||
@@ -60,6 +60,8 @@ class BarcodeService:
|
||||
self.repository = repository
|
||||
self.operator_id = int(operator_id)
|
||||
self._current_priority_state = -1
|
||||
# Independent document identities survive confirmations, F1/F2 and pause.
|
||||
self._priority_documents: dict[int, str] = {}
|
||||
self._state = BarcodeViewState()
|
||||
|
||||
@property
|
||||
@@ -72,6 +74,7 @@ class BarcodeService:
|
||||
"""Return the client to its neutral state."""
|
||||
|
||||
self._current_priority_state = -1
|
||||
self._priority_documents.clear()
|
||||
self._state = BarcodeViewState()
|
||||
return self._state
|
||||
|
||||
@@ -121,6 +124,7 @@ class BarcodeService:
|
||||
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._priority_documents[self._current_priority_state] = state.document
|
||||
self._state = replace(state, scanned_pallet="", auto_advance_delay_ms=0)
|
||||
return self._state
|
||||
|
||||
@@ -163,20 +167,25 @@ class BarcodeService:
|
||||
return BarcodeActionResult(True, self._state, self._state.status_text)
|
||||
|
||||
async def start_priority_queue(self, id_stato: int) -> BarcodeActionResult:
|
||||
"""Load the next item of the selected legacy priority queue."""
|
||||
"""Keep each F1/F2 cycle bound to its document until the cycle stops."""
|
||||
|
||||
row = await self.repository.fetch_next_picking(id_stato)
|
||||
self._current_priority_state = int(id_stato)
|
||||
id_stato = int(id_stato)
|
||||
active_document = self._priority_documents.get(id_stato)
|
||||
row = await self.repository.fetch_next_picking(id_stato, documento=active_document)
|
||||
self._current_priority_state = id_stato
|
||||
queue_label = "Alta priorita' (F1)" if int(id_stato) == 1 else "Bassa priorita' (F2)"
|
||||
if not row:
|
||||
skipped_doc = await self.repository.fetch_active_skipped_document(int(id_stato))
|
||||
skipped_doc = await self.repository.fetch_active_skipped_document(id_stato, documento=active_document)
|
||||
if skipped_doc:
|
||||
documento = str(skipped_doc.get("Documento") or "").strip()
|
||||
skipped_count = int(skipped_doc.get("SkippedCount") or 0)
|
||||
await self.repository.release_picking_document(
|
||||
rc = await self.repository.release_picking_document(
|
||||
documento=documento,
|
||||
operator_id=self.operator_id,
|
||||
)
|
||||
if rc != 0:
|
||||
raise RuntimeError(f"Impossibile sospendere PL {documento}: RC={rc}")
|
||||
self._priority_documents.pop(id_stato, None)
|
||||
self._current_priority_state = -1
|
||||
self._state = BarcodeViewState(
|
||||
mode="manual_unload",
|
||||
@@ -187,17 +196,36 @@ class BarcodeService:
|
||||
destination_readonly=False,
|
||||
)
|
||||
return BarcodeActionResult(True, self._state)
|
||||
status_text = "Pronto."
|
||||
remaining = 0
|
||||
if active_document:
|
||||
remaining = await self.repository.count_picking_document_remaining(active_document)
|
||||
status_text = (
|
||||
f"PL {active_document}: {remaining} UDC residue, coda non disponibile. Verifica la prenotazione."
|
||||
if remaining else f"PL {active_document} terminata. Premi F1 o F2 per iniziare."
|
||||
)
|
||||
log_runtime_event("Barcode WMS", f"PICKING CYCLE STOP documento={active_document} priority={id_stato} remaining={remaining}")
|
||||
# A changed reservation or visibility filter must not silently
|
||||
# replace an unfinished document on the next press of F1/F2.
|
||||
if not remaining:
|
||||
self._priority_documents.pop(id_stato, None)
|
||||
self._current_priority_state = -1
|
||||
self._state = BarcodeViewState(
|
||||
mode="manual_unload",
|
||||
queue_label=queue_label,
|
||||
status_text="Pronto.",
|
||||
status_text=status_text,
|
||||
status_color=self.RED,
|
||||
destination_barcode=self.NON_SCAFFALATA_BARCODE,
|
||||
destination_readonly=False,
|
||||
)
|
||||
return BarcodeActionResult(True, self._state)
|
||||
|
||||
document = str(row.get("Documento") or "").strip()
|
||||
if not document or (active_document is not None and document != active_document):
|
||||
raise RuntimeError(f"Cambio inatteso documento picking: atteso={active_document}, ricevuto={document}")
|
||||
self._priority_documents[id_stato] = document
|
||||
if active_document is None:
|
||||
log_runtime_event("Barcode WMS", f"PICKING CYCLE START documento={document} priority={id_stato}")
|
||||
customer = f"{row.get('CodNazione') or ''} - {row.get('NAZIONE') or ''}".strip(" -")
|
||||
source_location = self._display_location(
|
||||
cella=row.get("Cella"),
|
||||
@@ -289,7 +317,10 @@ class BarcodeService:
|
||||
picking_before_move = (
|
||||
None
|
||||
if current_location
|
||||
else await self.repository.fetch_picking_by_pallet(pallet)
|
||||
else await self.repository.fetch_picking_by_pallet(
|
||||
pallet,
|
||||
documento=self._priority_documents.get(self._current_priority_state) if is_picking_unload else None,
|
||||
)
|
||||
)
|
||||
if not current_location and not picking_before_move:
|
||||
if is_direct_load:
|
||||
@@ -651,7 +682,9 @@ class BarcodeService:
|
||||
and last_priority_state in (0, 1)
|
||||
)
|
||||
picking_row = (
|
||||
await self.repository.fetch_picking_by_pallet(barcode_pallet)
|
||||
await self.repository.fetch_picking_by_pallet(
|
||||
barcode_pallet, documento=self._priority_documents.get(last_priority_state),
|
||||
)
|
||||
if is_priority_shipping_confirmation
|
||||
else None
|
||||
)
|
||||
|
||||
65
fix_barcode_documento_fisso_f1_f2.md
Normal file
65
fix_barcode_documento_fisso_f1_f2.md
Normal file
@@ -0,0 +1,65 @@
|
||||
# Documento fisso durante il ciclo barcode F1/F2
|
||||
|
||||
## Difetto e requisito
|
||||
|
||||
Prima della correzione ogni avanzamento interrogava tutte le UDC con IDStato
|
||||
uguale alla priorita' richiesta. Per F2, che include tutte le liste non
|
||||
prenotate, il documento poteva quindi cambiare senza intervento dell'operatore.
|
||||
|
||||
Una volta proposta una lista, ogni successiva UDC del ciclo deve appartenere
|
||||
a quel documento. F1 e F2 ricordano ciascuno la propria lista: F2 -> F1 -> F2
|
||||
deve riportare al documento inizialmente assegnato a F2, anche se cambia
|
||||
l'ordine globale delle UDC disponibili.
|
||||
|
||||
## Implementazione locale
|
||||
|
||||
- BarcodeService conserva un documento per priorita', separato dallo stato
|
||||
visuale temporaneo di conferma o pausa.
|
||||
- La prima richiesta senza documento usa il criterio di ordinamento vigente.
|
||||
Non viene introdotta una selezione per data del documento.
|
||||
- Le successive richieste applicano il filtro Documento nelle query di
|
||||
avanzamento, ricerca skip e ricerca della UDC per conferma del movimento.
|
||||
- Un documento differente ricevuto dal repository causa un errore esplicito.
|
||||
- La pausa per movimenti liberi e il passaggio tra F1/F2 conservano i documenti.
|
||||
- Quando termina il documento, il ciclo si ferma e mostra il relativo messaggio.
|
||||
Una successiva pressione esplicita di un tasto priorita' puo' avviare un nuovo
|
||||
ciclo; la fine del precedente non attiva automaticamente un altro documento.
|
||||
- Quando rimangono soltanto UDC saltate, viene gestita la sospensione della
|
||||
lista corrente senza passare a un'altra lista disponibile nella coda.
|
||||
- Se cambiano prenotazione o visibilita' e ci sono ancora residui nello storico,
|
||||
compare un messaggio di verifica e il documento viene mantenuto in memoria.
|
||||
- Un errore della query non cancella il documento memorizzato.
|
||||
|
||||
Gli skip sono conteggiati soltanto se la relativa UDC e' ancora residua.
|
||||
Le movimentazioni libere mantengono la loro logica; il filtro Documento e'
|
||||
applicato soltanto alle ricerche nel contesto del picking.
|
||||
|
||||
## Limiti e installazione
|
||||
|
||||
Questa correzione riguarda la sessione del terminalino. La memoria dei documenti
|
||||
viene azzerata con reset del servizio o riavvio del programma. Non introduce
|
||||
ancora due prenotazioni persistenti o un percorso automatico comune per colonna:
|
||||
questi appartengono alla successiva modifica funzionale da specificare.
|
||||
|
||||
Non serve una patch SQL: cambiano le SELECT eseguite dal codice Python, non gli
|
||||
oggetti del database. Versioni: barcode_client 1.0.27 (titolo visibile),
|
||||
barcode_repository 1.0.14, barcode_service 1.0.25.
|
||||
|
||||
## Verifiche
|
||||
|
||||
Esecuzione senza GUI e senza movimentazioni reali:
|
||||
|
||||
```bat
|
||||
python -m unittest discover -s tests -p test_barcode_document_binding.py -v
|
||||
```
|
||||
|
||||
Gli 11 test coprono avanzamento con documenti intercalati, passaggi ripetuti
|
||||
F2/F1/F2, pausa con movimento libero, salto UDC, sospensione con soli skip,
|
||||
fine lista, cambio prenotazione, errore query, rifiuto di documento inatteso,
|
||||
isolamento della conferma e passaggio del parametro al repository.
|
||||
|
||||
Ulteriori 5 verifiche SELECT su SQL Server, con righe sintetiche in CTE,
|
||||
hanno controllato selezione iniziale, filtro documento, assenza di fallback,
|
||||
skip effettivamente residui e isolamento della conferma. Nessun dato reale
|
||||
e' stato aggiornato per questi test. Il collaudo fisico sul terminalino resta
|
||||
da effettuare.
|
||||
234
inventario.py
Normal file
234
inventario.py
Normal file
@@ -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("<Return>", lambda _: self._load())
|
||||
self.btn_load = ctk.CTkButton(top, text=self._t("inventory.load"), command=self._load, font=font)
|
||||
self.btn_load.grid(row=0, column=2, padx=6)
|
||||
self.btn_export = ctk.CTkButton(top, text=self._t("inventory.export"), command=self._export,
|
||||
font=font, state="disabled")
|
||||
self.btn_export.grid(row=0, column=4, padx=6)
|
||||
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("<<TreeviewSelect>>", self._select)
|
||||
ctk.CTkLabel(self, text=self._t("inventory.detail"), anchor="w").grid(row=4, column=0, sticky="ew", padx=10)
|
||||
tabs = ttk.Notebook(self)
|
||||
tabs.grid(row=5, column=0, sticky="nsew", padx=8, pady=(0, 8))
|
||||
lot_page, detail_page = ttk.Frame(tabs), ttk.Frame(tabs)
|
||||
for page in (lot_page, detail_page):
|
||||
page.grid_rowconfigure(0, weight=1)
|
||||
page.grid_columnconfigure(0, weight=1)
|
||||
tabs.add(lot_page, text=self._t("inventory.lot_sheet"))
|
||||
tabs.add(detail_page, text=self._t("inventory.detail_sheet"))
|
||||
self.lot_tree = self._make_tree(0, LOT_KEYS, lot_page)
|
||||
self.detail_tree = self._make_tree(0, DETAIL_KEYS, detail_page)
|
||||
|
||||
def _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("<Escape>", lambda _: win.destroy())
|
||||
return win
|
||||
155
inventory_report.sql
Normal file
155
inventory_report.sql
Normal file
@@ -0,0 +1,155 @@
|
||||
-- Read-only runtime query: cutoff and sam_cutoff are exclusive next-day bounds.
|
||||
-- Writes only session-local temp tables; never alters SAM/WMS objects or stock.
|
||||
SET NOCOUNT ON;
|
||||
SET XACT_ABORT ON;
|
||||
SET LOCK_TIMEOUT 15000;
|
||||
DECLARE @cutoff datetime2 = :cutoff, @sam_cutoff float = :sam_cutoff;
|
||||
DECLARE @warehouse int;
|
||||
IF (SELECT COUNT(*) FROM SAMA1.dbo.ANAMAG
|
||||
WHERE LTRIM(RTRIM(DESCR))='Magazzino Principale')<>1
|
||||
THROW 51200, 'Magazzino Principale SAM assente o ambiguo.', 1;
|
||||
SELECT @warehouse=ID FROM SAMA1.dbo.ANAMAG
|
||||
WHERE LTRIM(RTRIM(DESCR))='Magazzino Principale';
|
||||
SELECT ID INTO #inv_slots FROM SAMA1.dbo.ALLMAG WHERE IDANAMAG=@warehouse;
|
||||
CREATE UNIQUE CLUSTERED INDEX ix_slots ON #inv_slots(ID);
|
||||
|
||||
SELECT LTRIM(RTRIM(Attributo)) COLLATE DATABASE_DEFAULT AS Pallet, IDCella,
|
||||
SUM(CASE Tipo WHEN 'V' THEN CAST(PesoUnitario AS decimal(28,6))
|
||||
WHEN 'P' THEN -CAST(PesoUnitario AS decimal(28,6)) END) AS Balance
|
||||
INTO #inv_balance FROM dbo.MagazziniPallet
|
||||
WHERE DataMagazzino<@cutoff AND Tipo IN ('P','V')
|
||||
GROUP BY LTRIM(RTRIM(Attributo)),IDCella;
|
||||
CREATE INDEX ix_balance ON #inv_balance(Pallet);
|
||||
SELECT Pallet, COUNT(CASE WHEN Balance>0 THEN 1 END) AS Locations,
|
||||
COUNT(CASE WHEN Balance<0 THEN 1 END) AS NegativeBalances,
|
||||
MAX(CASE WHEN IDCella=9999 AND Balance>0 THEN 1 ELSE 0 END) AS Shipped
|
||||
INTO #inv_position FROM #inv_balance GROUP BY Pallet;
|
||||
CREATE UNIQUE CLUSTERED INDEX ix_position ON #inv_position(Pallet);
|
||||
SELECT b.*,CONCAT(RTRIM(c.Corsia),'.',RTRIM(c.Colonna),'.',RTRIM(c.Fila)) AS Location
|
||||
INTO #inv_stock FROM #inv_balance b
|
||||
JOIN dbo.Celle c ON c.ID=b.IDCella
|
||||
JOIN dbo.Aree a ON a.ID=c.IDArea
|
||||
JOIN dbo.Magazzini w ON w.ID=a.IDMagazzino
|
||||
WHERE b.Balance>0 AND (b.IDCella=1000 OR
|
||||
(b.IDCella<>9999 AND UPPER(RTRIM(w.Descrizione)) IN ('MDE5','MDE6')));
|
||||
CREATE INDEX ix_stock ON #inv_stock(Pallet);
|
||||
|
||||
-- First change AFTER cutoff supplies the OLD serial valid at cutoff.
|
||||
-- Same-timestamp ties have no ordering key: flag them instead of certifying them.
|
||||
SELECT IDLOTSER,MIN(AGGIORNAMENTO) AS FirstAfter
|
||||
INTO #inv_change_time FROM SAMA1.dbo.EXTTACLOTSER
|
||||
WHERE AGGIORNAMENTO>=@cutoff GROUP BY IDLOTSER;
|
||||
CREATE UNIQUE CLUSTERED INDEX ix_time ON #inv_change_time(IDLOTSER);
|
||||
SELECT h.IDLOTSER,MIN(RTRIM(h.EXNUMSER)) COLLATE DATABASE_DEFAULT AS Serial,
|
||||
CASE WHEN COUNT(*)>1 THEN 1 ELSE 0 END AS AssignmentIssue
|
||||
INTO #inv_old FROM SAMA1.dbo.EXTTACLOTSER h
|
||||
JOIN #inv_change_time t ON t.IDLOTSER=h.IDLOTSER AND t.FirstAfter=h.AGGIORNAMENTO
|
||||
GROUP BY h.IDLOTSER;
|
||||
CREATE UNIQUE CLUSTERED INDEX ix_old ON #inv_old(IDLOTSER);
|
||||
|
||||
SELECT ls.ID,ls.IDARTICO,RTRIM(ls.NUMLOT) COLLATE DATABASE_DEFAULT AS Lot,
|
||||
COALESCE(o.Serial,RTRIM(ls.NUMSER) COLLATE DATABASE_DEFAULT) AS Serial,
|
||||
ISNULL(o.AssignmentIssue,0) AS AssignmentIssue
|
||||
INTO #inv_wms_labels FROM SAMA1.dbo.LOTSER ls
|
||||
LEFT JOIN #inv_old o ON o.IDLOTSER=ls.ID
|
||||
WHERE EXISTS(SELECT 1 FROM #inv_stock s WHERE s.Pallet=
|
||||
LEFT(COALESCE(o.Serial,RTRIM(ls.NUMSER) COLLATE DATABASE_DEFAULT),6));
|
||||
|
||||
-- Scope by PRODUCT + LOT in WMS, not all products and not a P% convention.
|
||||
SELECT DISTINCT IDARTICO,Lot INTO #inv_scope FROM #inv_wms_labels;
|
||||
CREATE UNIQUE CLUSTERED INDEX ix_scope ON #inv_scope(IDARTICO,Lot);
|
||||
SELECT ls.ID,ls.IDARTICO,RTRIM(ls.NUMLOT) COLLATE DATABASE_DEFAULT AS Lot,
|
||||
COALESCE(o.Serial,RTRIM(ls.NUMSER) COLLATE DATABASE_DEFAULT) AS Serial,
|
||||
ISNULL(o.AssignmentIssue,0) AS AssignmentIssue
|
||||
INTO #inv_labels FROM SAMA1.dbo.LOTSER ls
|
||||
JOIN #inv_scope sc ON sc.IDARTICO=ls.IDARTICO
|
||||
AND sc.Lot=RTRIM(ls.NUMLOT) COLLATE DATABASE_DEFAULT
|
||||
LEFT JOIN #inv_old o ON o.IDLOTSER=ls.ID;
|
||||
CREATE UNIQUE CLUSTERED INDEX ix_labels ON #inv_labels(ID);
|
||||
|
||||
-- SAM balance per CONTAINER; B/C are never fabricated as SAM minus A.
|
||||
SELECT l.ID,SUM(CAST(g.QTTGIAI AS decimal(28,6))) AS Quantity
|
||||
INTO #inv_now FROM #inv_labels l
|
||||
JOIN SAMA1.dbo.GIAMAG g ON g.IDARTICO=l.ID
|
||||
JOIN #inv_slots s ON s.ID=g.IDMAG GROUP BY l.ID;
|
||||
|
||||
SELECT m.IDARTICO AS ID,m.DATMOV,CAST(m.QTAINV AS decimal(28,6)) AS Quantity,
|
||||
RTRIM(c.CODICE) AS Cause,
|
||||
CASE WHEN sp.ID IS NOT NULL THEN
|
||||
CASE c.QTGIUP WHEN '+' THEN 1 WHEN '-' THEN -1 ELSE 0 END ELSE 0 END
|
||||
+ CASE WHEN sa.ID IS NOT NULL THEN
|
||||
CASE c.QTGIUA WHEN '+' THEN 1 WHEN '-' THEN -1 ELSE 0 END ELSE 0 END AS Sign,
|
||||
CASE WHEN sa.ID IS NOT NULL AND c.QTGIUA='+' THEN 1 ELSE 0 END AS Receipt,
|
||||
CASE WHEN c.ID IS NULL OR
|
||||
(sp.ID IS NOT NULL AND ISNULL(RTRIM(c.QTGIUP),'') NOT IN ('','+','-')) OR
|
||||
(sa.ID IS NOT NULL AND ISNULL(RTRIM(c.QTGIUA),'') NOT IN ('','+','-'))
|
||||
THEN 1 ELSE 0 END AS CauseIssue
|
||||
INTO #inv_moves FROM #inv_labels l
|
||||
JOIN SAMA1.dbo.MOVMAG m ON m.IDARTICO=l.ID
|
||||
LEFT JOIN SAMA1.dbo.CAUMOV c ON c.ID=m.IDCAUMOV
|
||||
LEFT JOIN #inv_slots sp ON sp.ID=m.IDMAGPAR
|
||||
LEFT JOIN #inv_slots sa ON sa.ID=m.IDMAGARR
|
||||
WHERE sp.ID IS NOT NULL OR sa.ID IS NOT NULL;
|
||||
CREATE INDEX ix_moves ON #inv_moves(ID);
|
||||
SELECT ID,
|
||||
SUM(CASE WHEN DATMOV>=@sam_cutoff THEN Quantity*Sign ELSE 0 END) AS AfterQuantity,
|
||||
SUM(CASE WHEN DATMOV<@sam_cutoff AND Cause='CP' THEN Quantity*Sign END) AS Nominal,
|
||||
SUM(CASE WHEN DATMOV IS NULL OR Quantity IS NULL OR CauseIssue=1 THEN 1 ELSE 0 END) AS MovementIssues,
|
||||
SUM(CASE WHEN DATMOV<@sam_cutoff AND Receipt=1 AND Cause<>'CP' THEN 1 ELSE 0 END) AS OtherReceipts
|
||||
INTO #inv_quantities FROM #inv_moves GROUP BY ID;
|
||||
|
||||
CREATE TABLE #inv_result (
|
||||
Kind varchar(8) NULL, Component varchar(8) NULL,
|
||||
Product nvarchar(255) NULL, Description nvarchar(1000) NULL, Unit nvarchar(32) NULL,
|
||||
ContainerId int NULL, Lot nvarchar(255) NULL, Serial nvarchar(255) NULL,
|
||||
Pallet nvarchar(64) NULL, Cell int NULL, Location nvarchar(255) NULL,
|
||||
Balance decimal(38,6) NULL, Quantity decimal(38,6) NULL, SamQuantity decimal(38,6) NULL,
|
||||
Locations int NULL, NegativeBalances int NULL, Shipped int NULL,
|
||||
AssignmentIssue int NULL, MovementIssues int NULL, OtherReceipts int NULL,
|
||||
SourceDate datetime2 NULL
|
||||
);
|
||||
INSERT INTO #inv_result
|
||||
SELECT CAST('ROW' AS varchar(8)) AS Kind,
|
||||
CAST(CASE WHEN s.Pallet IS NOT NULL THEN 'A'
|
||||
WHEN LEFT(l.Serial,6)='000000' THEN 'C'
|
||||
WHEN ISNULL(p.Locations,0)>0 OR ISNULL(p.NegativeBalances,0)>0 THEN 'X'
|
||||
WHEN LEN(l.Serial)<8 OR SUBSTRING(l.Serial,7,1)<>'/' THEN 'X'
|
||||
ELSE 'B' END AS varchar(8)) AS Component,
|
||||
RTRIM(a.CODICE) AS Product,RTRIM(a.DESCR) AS Description,RTRIM(a.UMI) AS Unit,
|
||||
l.ID AS ContainerId,l.Lot,l.Serial,
|
||||
LEFT(l.Serial,6) AS Pallet,s.IDCella AS Cell,s.Location,s.Balance,
|
||||
CASE WHEN s.Pallet IS NOT NULL THEN q.Nominal
|
||||
ELSE ISNULL(n.Quantity,0)-ISNULL(q.AfterQuantity,0) END AS Quantity,
|
||||
ISNULL(n.Quantity,0)-ISNULL(q.AfterQuantity,0) AS SamQuantity,
|
||||
ISNULL(p.Locations,0) AS Locations,ISNULL(p.NegativeBalances,0) AS NegativeBalances,
|
||||
ISNULL(p.Shipped,0) AS Shipped,l.AssignmentIssue,
|
||||
ISNULL(q.MovementIssues,0) AS MovementIssues,ISNULL(q.OtherReceipts,0) AS OtherReceipts,
|
||||
CAST(NULL AS datetime2) AS SourceDate
|
||||
FROM #inv_labels l
|
||||
LEFT JOIN SAMA1.dbo.ARTICO a ON a.ID=l.IDARTICO
|
||||
LEFT JOIN #inv_now n ON n.ID=l.ID
|
||||
LEFT JOIN #inv_quantities q ON q.ID=l.ID
|
||||
LEFT JOIN #inv_position p ON p.Pallet=LEFT(l.Serial,6)
|
||||
LEFT JOIN #inv_stock s ON s.Pallet=LEFT(l.Serial,6)
|
||||
WHERE s.Pallet IS NOT NULL OR ISNULL(n.Quantity,0)-ISNULL(q.AfterQuantity,0)<>0
|
||||
OR ISNULL(q.MovementIssues,0)>0;
|
||||
|
||||
-- WMS presence with no recognizable label must remain visible.
|
||||
INSERT INTO #inv_result(Kind,Component,Pallet,Cell,Location,Balance,Locations,
|
||||
NegativeBalances,Shipped,AssignmentIssue,MovementIssues,OtherReceipts)
|
||||
SELECT 'ROW','A',s.Pallet,s.IDCella,s.Location,s.Balance,p.Locations,
|
||||
p.NegativeBalances,p.Shipped,0,0,0
|
||||
FROM #inv_stock s JOIN #inv_position p ON p.Pallet=s.Pallet
|
||||
WHERE NOT EXISTS(SELECT 1 FROM #inv_wms_labels l WHERE LEFT(l.Serial,6)=s.Pallet);
|
||||
|
||||
-- One result set, as required by the shared async SQL client.
|
||||
INSERT INTO #inv_result(Kind,Component,SourceDate)
|
||||
SELECT 'META','WMS_MAX',MAX(DataMagazzino) FROM dbo.MagazziniPallet;
|
||||
INSERT INTO #inv_result(Kind,Component,SourceDate)
|
||||
SELECT 'META','SAM_MAX',DATEADD(day,CAST(MAX(DATMOV) AS int),CAST('1899-12-30' AS datetime2))
|
||||
FROM SAMA1.dbo.MOVMAG;
|
||||
INSERT INTO #inv_result(Kind,Component,SourceDate)
|
||||
SELECT 'META','HIST_MIN',MIN(AGGIORNAMENTO) FROM SAMA1.dbo.EXTTACLOTSER;
|
||||
INSERT INTO #inv_result(Kind,Component,Quantity)
|
||||
SELECT 'META','UNDATED',COUNT(*) FROM dbo.MagazziniPallet WHERE DataMagazzino IS NULL;
|
||||
SELECT * FROM #inv_result;
|
||||
271
inventory_service.py
Normal file
271
inventory_service.py
Normal file
@@ -0,0 +1,271 @@
|
||||
"""Read-only WMS/SAM reconciliation by product and lot; see specifica_inventario.md."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
SQL_PATH = Path(__file__).with_name("inventory_report.sql")
|
||||
ZERO = Decimal("0")
|
||||
SUMMARY_KEYS = ("Product", "Description", "Unit", "UDCs", "Shelved", "NonShelved",
|
||||
"WMS", "PackingUDCs", "Packing", "LooseContainers", "Loose",
|
||||
"Reconstructed", "SAM", "InitialDifference", "Difference", "Status")
|
||||
DETAIL_KEYS = ("Component", "Product", "Lot", "Pallet", "ContainerId", "Serial",
|
||||
"Location", "Quantity", "SamQuantity", "Status")
|
||||
LOT_KEYS = ("Product", "Lot") + SUMMARY_KEYS[2:]
|
||||
|
||||
|
||||
def inventory_cutoff(value: str, *, today: date | None = None) -> tuple[date, datetime, int]:
|
||||
"""Parse a day, not an instant; use the exclusive following midnight."""
|
||||
selected = datetime.strptime(value.strip(), "%d/%m/%Y").date()
|
||||
if selected > (today or date.today()) or selected < date(2010, 1, 1):
|
||||
raise ValueError("date_range")
|
||||
cutoff = datetime.combine(selected + timedelta(days=1), time.min)
|
||||
return selected, cutoff, (cutoff - datetime(1899, 12, 30)).days
|
||||
|
||||
|
||||
def number(value: Any) -> Decimal:
|
||||
"""Convert SQL decimals without introducing floating-point summation."""
|
||||
return Decimal(str(value)) if value is not None else ZERO
|
||||
|
||||
|
||||
@dataclass
|
||||
class InventoryReport:
|
||||
selected_date: date
|
||||
rows: list[dict[str, Any]]
|
||||
details: list[dict[str, Any]]
|
||||
metadata: dict[str, Any]
|
||||
lots: list[dict[str, Any]]
|
||||
|
||||
|
||||
def _bucket(product, description, unit, lot=""):
|
||||
return dict(Product=product, Description=description, Unit=unit, Lot=lot,
|
||||
UDCs=set(), PackingUDCs=set(), LooseContainers=set(),
|
||||
Shelved=ZERO, NonShelved=ZERO, Packing=ZERO, Loose=ZERO, SAM=ZERO,
|
||||
Issues=set(), Invalid=set())
|
||||
|
||||
|
||||
def build_report(selected_date: date, records: list[dict[str, Any]]) -> InventoryReport:
|
||||
"""Count each container once; retain anomalies instead of manufacturing balance.
|
||||
|
||||
A uses production receipt quantities, independently of current SAM balance.
|
||||
B/C use the dated container balance. X is unclassified/conflicting SAM stock;
|
||||
it contributes to SAM, never silently to B. Aggregation begins at product/lot.
|
||||
"""
|
||||
metadata = {r["Component"]: (r.get("Quantity") if r["Component"] == "UNDATED"
|
||||
else r.get("SourceDate"))
|
||||
for r in records if r["Kind"] == "META"}
|
||||
history_start = metadata.get("HIST_MIN")
|
||||
history_unknown = not history_start or selected_date < history_start.date()
|
||||
products, lots, details, seen = {}, {}, [], {}
|
||||
for record in records:
|
||||
if record["Kind"] == "META":
|
||||
continue
|
||||
r = dict(record)
|
||||
pallet = str(r.get("Pallet") or "").strip()
|
||||
product = str(r.get("Product") or "").strip() or f"? UDC {pallet}"
|
||||
lot = str(r.get("Lot") or "").strip()
|
||||
unit = str(r.get("Unit") or "").strip().upper()
|
||||
component = r["Component"]
|
||||
quantity = None if r.get("Quantity") is None else number(r["Quantity"])
|
||||
sam_quantity = None if r.get("SamQuantity") is None else number(r["SamQuantity"])
|
||||
issues, invalid = set(), set()
|
||||
if unit not in {"NR", "PZ", "PCS"}:
|
||||
issues.add("unit")
|
||||
invalid.update(("A", "B", "C", "SAM"))
|
||||
if r.get("AssignmentIssue") or history_unknown:
|
||||
issues.add("history")
|
||||
invalid.update(("A", "B", "C"))
|
||||
if metadata.get("UNDATED"):
|
||||
issues.add("undated")
|
||||
invalid.update(("A", "B", "C"))
|
||||
if r.get("MovementIssues") or sam_quantity is None:
|
||||
issues.add("movements")
|
||||
invalid.update(("A", "B", "C", "SAM"))
|
||||
if sam_quantity is not None and sam_quantity < 0:
|
||||
issues.add("negative")
|
||||
invalid.add("SAM")
|
||||
serial = str(r.get("Serial") or "").strip()
|
||||
if len(serial) < 8 or serial[6:7] != "/" or not serial[7:].strip():
|
||||
issues.add("serial")
|
||||
invalid.add(component)
|
||||
if component == "A":
|
||||
if quantity is None or quantity <= 0 or r.get("OtherReceipts"):
|
||||
issues.add("content")
|
||||
invalid.add("A")
|
||||
if r.get("Locations") != 1:
|
||||
issues.add("locations")
|
||||
invalid.add("A")
|
||||
if number(r.get("Balance")) != 1 or r.get("NegativeBalances"):
|
||||
issues.add("balance")
|
||||
invalid.add("A")
|
||||
if r.get("Shipped"):
|
||||
issues.add("shipped")
|
||||
invalid.add("A")
|
||||
elif component in ("B", "C"):
|
||||
if quantity is None or quantity <= 0:
|
||||
issues.add("content")
|
||||
invalid.add(component)
|
||||
if r.get("Shipped") or r.get("Locations") or r.get("NegativeBalances"):
|
||||
issues.add("shipped" if r.get("Shipped") else "outside")
|
||||
invalid.add(component)
|
||||
else:
|
||||
issues.add("shipped" if r.get("Shipped") else "outside")
|
||||
bucket = lots.setdefault((product, lot), _bucket(product, r.get("Description") or "", unit, lot))
|
||||
if bucket["Unit"] != unit:
|
||||
issues.add("unit")
|
||||
invalid.update(("A", "B", "C", "SAM"))
|
||||
bucket["Issues"].update(issues)
|
||||
bucket["Invalid"].update(invalid)
|
||||
if component == "A":
|
||||
bucket["UDCs"].add(pallet)
|
||||
elif component == "B":
|
||||
bucket["PackingUDCs"].add(pallet)
|
||||
elif component == "C":
|
||||
bucket["LooseContainers"].add(r.get("ContainerId"))
|
||||
# Anomaly details can have several locations, but SAM must not be doubled.
|
||||
identity = r.get("ContainerId") or ("missing", pallet)
|
||||
key = (product, lot, identity)
|
||||
fingerprint = (component, quantity, sam_quantity, pallet)
|
||||
if key not in seen:
|
||||
bucket["SAM"] += sam_quantity or ZERO
|
||||
field = ("NonShelved" if r.get("Cell") == 1000 else "Shelved") if component == "A" else {
|
||||
"B": "Packing", "C": "Loose"}.get(component)
|
||||
if field and quantity is not None:
|
||||
bucket[field] += quantity
|
||||
seen[key] = fingerprint
|
||||
elif seen[key] != fingerprint:
|
||||
bucket["Issues"].add("duplicate")
|
||||
bucket["Invalid"].update(("A", "B", "C", "SAM"))
|
||||
issues.add("duplicate")
|
||||
details.append(dict(Component=component, Product=product, Lot=lot,
|
||||
Pallet="" if pallet == "000000" else pallet,
|
||||
ContainerId=r.get("ContainerId"), Serial=serial,
|
||||
Cell=r.get("Cell"), Location=r.get("Location") or "",
|
||||
Quantity=None if component in invalid else quantity,
|
||||
SamQuantity=None if "SAM" in invalid else sam_quantity,
|
||||
Issues=tuple(sorted(issues))))
|
||||
# Aggregate lots without summing their distinct-UDC counts.
|
||||
for bucket in lots.values():
|
||||
total = products.setdefault(bucket["Product"], _bucket(
|
||||
bucket["Product"], bucket["Description"], bucket["Unit"]))
|
||||
if total["Unit"] != bucket["Unit"]:
|
||||
total["Issues"].add("unit")
|
||||
total["Invalid"].update(("A", "B", "C", "SAM"))
|
||||
for key in ("UDCs", "PackingUDCs", "LooseContainers", "Issues", "Invalid"):
|
||||
total[key].update(bucket[key])
|
||||
for key in ("Shelved", "NonShelved", "Packing", "Loose", "SAM"):
|
||||
total[key] += bucket[key]
|
||||
def finish(row):
|
||||
invalid = row.pop("Invalid")
|
||||
for key in ("UDCs", "PackingUDCs", "LooseContainers"):
|
||||
row[key] = len(row[key])
|
||||
if "A" in invalid:
|
||||
row["Shelved"] = row["NonShelved"] = None
|
||||
for component, field in (("B", "Packing"), ("C", "Loose"), ("SAM", "SAM")):
|
||||
if component in invalid:
|
||||
row[field] = None
|
||||
row["WMS"] = add_known(row["Shelved"], row["NonShelved"])
|
||||
row["Reconstructed"] = add_known(row["WMS"], row["Packing"], row["Loose"])
|
||||
row["InitialDifference"] = subtract_known(row["SAM"], row["WMS"])
|
||||
row["Difference"] = subtract_known(row["SAM"], row["Reconstructed"])
|
||||
row["Issues"] = tuple(sorted(row["Issues"]))
|
||||
return row
|
||||
lot_rows = [finish(lots[k]) for k in sorted(lots)]
|
||||
product_rows = [finish(products[k]) for k in sorted(products)]
|
||||
for row in product_rows:
|
||||
if row["Difference"] == 0 and any(
|
||||
lot["Product"] == row["Product"] and lot["Difference"] not in (None, ZERO)
|
||||
for lot in lot_rows):
|
||||
row["Issues"] = tuple(sorted(set(row["Issues"]) | {"lot_offsets"}))
|
||||
return InventoryReport(selected_date,
|
||||
product_rows,
|
||||
sorted(details, key=lambda r: (r["Product"], r["Lot"], r["Component"],
|
||||
r["Pallet"], r["Serial"], str(r["Cell"]))),
|
||||
metadata, lot_rows)
|
||||
|
||||
|
||||
def add_known(*values):
|
||||
return None if any(v is None for v in values) else sum(values, ZERO)
|
||||
|
||||
|
||||
def subtract_known(left, right):
|
||||
return None if left is None or right is None else left - right
|
||||
|
||||
|
||||
async def load_inventory(db_client, value: str) -> InventoryReport:
|
||||
"""Use the existing asynchronous DB client; no commit or stock mutation."""
|
||||
selected, cutoff, sam_cutoff = inventory_cutoff(value)
|
||||
result = await db_client.query_json(SQL_PATH.read_text(encoding="utf-8"),
|
||||
{"cutoff": cutoff, "sam_cutoff": sam_cutoff}, as_dict_rows=True)
|
||||
return build_report(selected, result["rows"])
|
||||
|
||||
|
||||
def status_text(row, translate):
|
||||
if row["Issues"]:
|
||||
return "; ".join(translate("inventory.issue." + issue) for issue in row["Issues"])
|
||||
return translate("inventory.match" if row["Difference"] == 0 else "inventory.mismatch")
|
||||
|
||||
|
||||
def detail_values(row, translate):
|
||||
"""Use identical localized labels in GUI and exported container details."""
|
||||
values = dict(row)
|
||||
values["Component"] = translate("inventory.component." + row["Component"])
|
||||
if not values["Location"] and row["Component"] in ("B", "C"):
|
||||
values["Location"] = translate("inventory.inferred_location")
|
||||
values["Status"] = "; ".join(translate("inventory.issue." + issue) for issue in row["Issues"])
|
||||
return [values[k] for k in DETAIL_KEYS]
|
||||
|
||||
|
||||
def export_inventory(report: InventoryReport, path: str, *, headers=None,
|
||||
detail_headers=None, translate, ordered_rows=None) -> None:
|
||||
"""Export product, lot and container views with typed cells and provenance."""
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, PatternFill
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = translate("inventory.title")
|
||||
ws.append([translate("inventory.date"), report.selected_date])
|
||||
ws["B1"].number_format = "DD/MM/YYYY"
|
||||
ws.append([translate("inventory.notice")])
|
||||
ws.append([translate("inventory.scope")])
|
||||
ws.append([translate("inventory.sources"), str(report.metadata)])
|
||||
ws.append([translate("inventory.history_notice")])
|
||||
ws.append(headers or [translate("inventory.col." + k) for k in SUMMARY_KEYS])
|
||||
for row in ordered_rows if ordered_rows is not None else report.rows:
|
||||
ws.append([row[k] for k in SUMMARY_KEYS[:-1]] + [status_text(row, translate)])
|
||||
ls = wb.create_sheet(translate("inventory.lot_sheet"))
|
||||
ls.append([translate("inventory.col." + k) for k in LOT_KEYS])
|
||||
for row in report.lots:
|
||||
ls.append([row[k] for k in LOT_KEYS[:-1]] + [status_text(row, translate)])
|
||||
ds = wb.create_sheet(translate("inventory.detail_sheet"))
|
||||
ds.append(detail_headers or [translate("inventory.col." + k) for k in DETAIL_KEYS])
|
||||
for row in report.details:
|
||||
ds.append(detail_values(row, translate))
|
||||
for sheet, header_row in ((ws, 6), (ls, 1), (ds, 1)):
|
||||
sheet.freeze_panes = f"A{header_row + 1}"
|
||||
sheet.auto_filter.ref = f"A{header_row}:{get_column_letter(sheet.max_column)}{sheet.max_row}"
|
||||
for cell in sheet[header_row]:
|
||||
cell.font = Font(bold=True, color="000000")
|
||||
cell.fill = PatternFill("solid", fgColor="BFC4CA")
|
||||
for row in sheet.iter_rows():
|
||||
for cell in row:
|
||||
if isinstance(cell.value, str):
|
||||
cell.data_type = "s"
|
||||
elif isinstance(cell.value, (Decimal, float, int)):
|
||||
cell.number_format = '#,##0.######;[Red]-#,##0.######;0'
|
||||
if cell.row > header_row and cell.row % 2 == 0:
|
||||
cell.fill = PatternFill("solid", fgColor="F0F0F0")
|
||||
for col in range(1, sheet.max_column + 1):
|
||||
sheet.column_dimensions[get_column_letter(col)].width = 24
|
||||
try:
|
||||
wb.save(path)
|
||||
finally:
|
||||
wb.close()
|
||||
124
locale.json
124
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",
|
||||
|
||||
11
main.py
11
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"),
|
||||
|
||||
242
specifica_inventario.md
Normal file
242
specifica_inventario.md
Normal file
@@ -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.
|
||||
439
specifica_prelievo_due_pickinglist.md
Normal file
439
specifica_prelievo_due_pickinglist.md
Normal file
@@ -0,0 +1,439 @@
|
||||
# Prelievo guidato di due picking list sul terminalino
|
||||
|
||||
Data: 02/10/2026. Revisione: 0.3.
|
||||
|
||||
**Stato: specifica da rileggere e concordare prima dell'implementazione.**
|
||||
La funzione di prelievo abbinato descritta qui non e' ancora implementata.
|
||||
I punti indicati come aperti o proposti non sono decisioni gia' approvate.
|
||||
|
||||
## 1. Obiettivo operativo
|
||||
|
||||
Consentire al responsabile di prenotare una oppure due picking list dal
|
||||
programma desktop. Quando sono due, il terminalino deve guidare un unico
|
||||
percorso di prelievo che considera le UDC residue di entrambe.
|
||||
|
||||
L'operatore deve percorrere il magazzino seguendo l'ordine previsto, senza
|
||||
ritornare alle prime colonne perche' una lista non conteneva UDC in quelle
|
||||
posizioni. Il sistema sceglie di volta in volta il documento della prossima
|
||||
UDC; l'operatore riconosce il cambio dal numero del documento e dal colore.
|
||||
|
||||
Il prelievo abbinato riguarda un operatore che lavora due documenti nello
|
||||
stesso giro. La gestione di piu' operatori contemporanei richiede ulteriori
|
||||
decisioni e non e' definita da questa specifica.
|
||||
|
||||
## 2. Termini usati
|
||||
|
||||
| Termine | Significato |
|
||||
|---|---|
|
||||
| Lista 1 / F1 | Prima lista assegnata alla coppia, con identita' stabile |
|
||||
| Lista 2 / F2 | Seconda lista assegnata alla coppia, con identita' stabile |
|
||||
| Lista proposta | Documento della prossima UDC indicata dal sistema |
|
||||
| Colonna o campata | Colonna di uno specifico scaffale e magazzino |
|
||||
| Cella | Singola posizione dentro la colonna, a un determinato livello |
|
||||
| Percorso comune | Ordine delle posizioni applicato alle UDC di entrambe le liste |
|
||||
| UDC residua | UDC ancora da prelevare, non gia' nella locazione spedita |
|
||||
|
||||
Area 5 e Area 6 sono i nomi operativi dei magazzini MDE5 e MDE6.
|
||||
Non corrispondono necessariamente agli ID 5 e 6 della tabella legacy Aree.
|
||||
La colonna 1 dello scaffale A e la colonna 1 dello scaffale B sono distinte.
|
||||
|
||||
## 3. Situazione attuale e difetto da non reintrodurre
|
||||
|
||||
La prenotazione Python attuale prevede un unico documento. Storicamente F1
|
||||
interroga la priorita' prenotata e F2 quella non prenotata. Quest'ultima puo'
|
||||
contenere piu' documenti, quindi non identifica di per se' una seconda lista.
|
||||
|
||||
E' stata introdotta nel codice locale una correzione che fissa il documento
|
||||
del ciclo per ciascun tasto. Il passaggio F2 -> F1 -> F2 conserva il documento
|
||||
precedentemente avviato con F2. Il dettaglio e' in
|
||||
[fix_barcode_documento_fisso_f1_f2.md](fix_barcode_documento_fisso_f1_f2.md).
|
||||
|
||||
La nuova funzione estende il modello: entrambi i documenti devono essere
|
||||
esplicitamente assegnati alla coppia. Il cambio automatico sara' ammesso
|
||||
soltanto fra questi due documenti e per una ragione di percorso.
|
||||
Nessuna terza lista deve subentrare silenziosamente.
|
||||
|
||||
## 4. Selezione e prenotazione sul desktop
|
||||
|
||||
### R01. Una o due liste
|
||||
|
||||
Gestione Picking List deve permettere di prenotare al massimo due liste per
|
||||
il prelievo abbinato. Deve restare utilizzabile anche con una sola lista.
|
||||
Il semplice clic per consultare il dettaglio non deve modificare implicitamente
|
||||
una prenotazione: selezione per consultazione e assegnazione al giro devono
|
||||
avere un comportamento chiaramente distinguibile.
|
||||
|
||||
### R02. Identita' della coppia
|
||||
|
||||
Il desktop deve rendere riconoscibile quale documento e' Lista 1/F1 e quale
|
||||
e' Lista 2/F2. L'assegnazione non dipende dall'ordinamento momentaneo della
|
||||
griglia o dalla posizione della prossima UDC.
|
||||
|
||||
Il gesto per assegnare i ruoli e' ancora da definire: ad esempio due slot
|
||||
espliciti, oppure prima e seconda scelta rese chiaramente visibili.
|
||||
|
||||
### R02a. Le due liste devono appartenere alla stessa area
|
||||
|
||||
Il prelievo abbinato e' consentito esclusivamente fra due liste della stessa
|
||||
area operativa: entrambe Area 5/MDE5 oppure entrambe Area 6/MDE6.
|
||||
Non e' consentito abbinare una lista dell'Area 5 a una dell'Area 6.
|
||||
Il sistema deve rifiutare l'abbinamento con un messaggio comprensibile,
|
||||
senza salvare una coppia parziale o alterare le prenotazioni preesistenti.
|
||||
Il vincolo deve essere verificato anche lato servizio/database, non soltanto
|
||||
mediante la disponibilita' dei pulsanti nell'interfaccia desktop.
|
||||
|
||||
Prima dell'implementazione va definita la fonte autorevole dell'area della
|
||||
lista, specialmente se contiene UDC non scaffalate o senza giacenza WMS.
|
||||
La cella virtuale condivisa 1000 non dimostra da sola l'appartenenza all'area.
|
||||
Non dedurre il magazzino dal numero documento o dagli ID legacy delle Aree.
|
||||
Il trattamento delle liste internamente miste o con area indeterminata resta
|
||||
da concordare; non considerarle implicitamente compatibili con entrambe.
|
||||
|
||||
### R03. Un'unica sequenza personalizzata
|
||||
|
||||
Con due liste selezionate, il comando Sequenza di prelievo riguarda entrambe.
|
||||
L'editor deve presentare l'unione degli scaffali/gruppi presenti nelle due liste,
|
||||
includendo quelli presenti soltanto in una di esse e il gruppo Non scaff.
|
||||
|
||||
Non si devono eseguire due ordinamenti personalizzati incompatibili nello
|
||||
stesso giro. La sequenza della coppia deve costituire l'unico riferimento.
|
||||
|
||||
La scelta fra eventuali personalizzazioni gia' salvate sulle singole liste
|
||||
resta aperta. Non e' ammessa una fusione silenziosa che produca un ordine
|
||||
diverso da quello mostrato al responsabile.
|
||||
|
||||
## 5. Percorsi delle aree: conservare il comportamento esistente
|
||||
|
||||
### R04. Area 6 / MDE6
|
||||
|
||||
Conservare il percorso attuale: scaffali nell'ordine previsto, colonne in
|
||||
ordine crescente all'interno dello scaffale e livelli dal pavimento verso
|
||||
l'alto. Il documento [ordinamento.md](ordinamento.md) riporta per i dati
|
||||
analizzati la sequenza interna a -> b -> c -> d -> e.
|
||||
|
||||
La modifica non deve rinumerare Celle.Ordinamento ne' inventare nuovi percorsi
|
||||
per celle eventualmente configurate con eccezioni.
|
||||
|
||||
### R05. Area 5 / MDE5
|
||||
|
||||
Conservare l'ordinamento esistente delle celle. Nel default e' il percorso
|
||||
storico rappresentato da Celle.Ordinamento, con serpentina fra scaffali.
|
||||
|
||||
Esempio documentato del blocco 1A/2B:
|
||||
|
||||
```text
|
||||
1A.1 -> 2B.1 -> 2B.2 -> 1A.2 -> 1A.3 -> 2B.3 -> ...
|
||||
```
|
||||
|
||||
All'interno delle campate analizzate l'ordine e' e -> d -> c -> b -> a,
|
||||
quindi dall'alto verso il basso. E' confermato che anche la prima UDC
|
||||
proposta deve rispettare questo verso: non partire dal pavimento in area 5.
|
||||
Non sostituire questo percorso con un generico ordinamento numerico
|
||||
scaffale/colonna/livello dell'area 6.
|
||||
|
||||
### R06. Effetto della personalizzazione
|
||||
|
||||
La personalizzazione mantiene il significato attuale: cambia la precedenza
|
||||
dei gruppi/scaffali, mentre dentro ogni gruppo si conserva l'ordine delle celle.
|
||||
Con due liste, la stessa scelta si applica all'intero contenuto della coppia.
|
||||
|
||||
Per esempio, porre tutto 1A prima di tutto 2B elimina intenzionalmente
|
||||
l'alternanza fra quei due scaffali, come avviene gia' nella personalizzazione
|
||||
attuale. Non sarebbe corretto promettere contemporaneamente tale precedenza
|
||||
e il mantenimento della serpentina globale.
|
||||
|
||||
I gruppi omessi da una personalizzazione parziale devono essere accodati con
|
||||
il criterio attuale, senza perdere le relative UDC.
|
||||
|
||||
## 6. Scelta della prossima UDC
|
||||
|
||||
### R07. Confronto continuo delle due liste
|
||||
|
||||
A ogni passo confrontare le UDC ancora lavorabili di entrambe le liste e
|
||||
scegliere quella che viene prima nel percorso comune.
|
||||
Questa regola vale all'avvio, fra colonne consecutive, dopo un movimento e
|
||||
quando uno dei documenti non ha UDC nella colonna corrente.
|
||||
|
||||
Non si deve usare F1 come guida unica, cercando F2 soltanto nelle colonne
|
||||
incontrate da F1: questo lascerebbe indietro le colonne presenti solo in F2.
|
||||
|
||||
### R08. Il percorso prevale sull'identita' della lista
|
||||
|
||||
Non esiste una precedenza fissa F1-prima-di-F2 nella stessa colonna.
|
||||
Se nell'area 6 i livelli dal basso verso l'alto appartengono a F2, F1 e F2,
|
||||
il prelievo deve seguire F2 -> F1 -> F2.
|
||||
|
||||
La precedente ipotesi di esaurire tutte le UDC F1 della colonna e solo dopo
|
||||
quelle F2 e' superata: la scelta si compie sulla posizione a ogni passo.
|
||||
|
||||
### R09. Nessuna UDC persa e nessun documento estraneo
|
||||
|
||||
Il contenuto lavorato e' l'unione delle UDC residue delle due liste.
|
||||
Le UDC su piu' righe lotto devono essere considerate una sola volta come
|
||||
unita' fisica di prelievo. Ogni proposta deve mantenere l'identita' del
|
||||
documento a cui appartiene.
|
||||
|
||||
Non introdurre la scelta automatica di una terza lista, neanche al termine
|
||||
di una delle due. La gestione delle UDC saltate e' trattata al punto 10.
|
||||
|
||||
## 7. Avvio neutro e tasti F1/F2
|
||||
|
||||
### R10. Avvio scelto dal sistema
|
||||
|
||||
Quando il terminalino mostra Pronto per la coppia, il sistema deve avere gia'
|
||||
individuato la prima proposta. L'operatore non decide arbitrariamente da quale
|
||||
documento partire.
|
||||
|
||||
Se la prima UDC appartiene alla Lista 2, F2 e' abilitato e F1 disabilitato;
|
||||
se appartiene alla Lista 1, vale il contrario. Il blocco deve valere sia per
|
||||
i pulsanti sullo schermo sia per i tasti fisici.
|
||||
|
||||
### R11. Guida durante il giro
|
||||
|
||||
Nel prelievo abbinato deve essere selezionabile soltanto la lista proposta
|
||||
dal percorso. Il cambio automatico verso l'altro documento non richiede una
|
||||
nuova scelta dell'operatore.
|
||||
|
||||
La precedente modalita' manuale F1/F2 e il nuovo giro guidato non devono
|
||||
essere confusi: nel giro guidato i due tasti identificano documenti stabili,
|
||||
ma non autorizzano a scavalcare il percorso stabilito.
|
||||
|
||||
### Chiarimento confermato: la prima cella dipende dal percorso dell'area
|
||||
|
||||
Si parte dalla prima UDC secondo il percorso effettivo comune, rispettando
|
||||
anche all'avvio l'ordine dell'area e l'eventuale personalizzazione.
|
||||
La precedente espressione "cella piu' bassa" non e' una regola universale:
|
||||
|
||||
- Area 5: nella campata prevista dal percorso, prima la cella occupata
|
||||
richiesta piu' in alto, poi quelle inferiori (e -> d -> c -> b -> a).
|
||||
- Area 6: nella colonna prevista dal percorso, prima la cella occupata
|
||||
richiesta piu' vicina al pavimento, poi quelle superiori (a -> b -> c -> d -> e).
|
||||
|
||||
Il confronto comprende entrambe le liste: in area 5, se F1 ha una UDC al
|
||||
livello a e F2 ne ha una al livello d della stessa campata, si propone prima
|
||||
F2/d e poi F1/a. Non conta quale documento occupa il ruolo di Lista 1.
|
||||
Restano la serpentina del default area 5, l'ordine comune eventualmente
|
||||
personalizzato e la precedenza delle Non scaff. descritta in R14.
|
||||
|
||||
## 8. Identificazione visiva sul terminalino
|
||||
|
||||
### R12. Colori stabili
|
||||
|
||||
| Documento assegnato | Colore di contesto |
|
||||
|---|---|
|
||||
| Lista 1 / F1 | Rosellino |
|
||||
| Lista 2 / F2 | Giallino |
|
||||
|
||||
Il colore segue il documento e non la sua posizione nel giro: se inizia F2,
|
||||
lo sfondo iniziale e' giallino. La stessa lista conserva il proprio colore
|
||||
nei successivi passaggi.
|
||||
|
||||
Il numero della picking list e il ruolo Lista 1/Lista 2 devono essere leggibili
|
||||
insieme all'UDC e alla cella proposta: il colore non deve essere l'unica
|
||||
informazione per capire quale documento si sta lavorando.
|
||||
|
||||
La barra esito mantiene il significato funzionale dei propri colori
|
||||
(successo, errore, attesa), distinguibile dallo sfondo di contesto.
|
||||
Il layout deve restare utilizzabile sul terminalino 240 x 320.
|
||||
|
||||
## 9. Ciclo di scansione e conferma
|
||||
|
||||
### R13. Sequenza ordinaria
|
||||
|
||||
1. Il sistema propone UDC, cella sorgente e documento; applica il colore relativo.
|
||||
2. L'operatore legge il barcode della UDC proposta.
|
||||
3. Rimangono i controlli attuali di corrispondenza e avvio automatico della lettura.
|
||||
4. Il movimento di picking porta la UDC in spedita, 7G.1.1, destinazione 9000000.
|
||||
5. Il terminalino mostra l'esito positivo per i tre secondi previsti.
|
||||
6. Il sistema propone la prossima UDC della coppia secondo il percorso comune.
|
||||
7. Se cambia documento, aggiorna insieme colore, riferimento lista e tasti abilitati.
|
||||
|
||||
L'esito dei tre secondi appartiene al movimento appena concluso, non al
|
||||
documento che verra' proposto dopo. Non deve comparire un contesto misto.
|
||||
|
||||
Un cambio programma della UDC visualizzata non deve simulare una scansione
|
||||
dell'operatore: va preservata la protezione contro gli auto-submit accidentali.
|
||||
Un errore o un esito incerto non deve avanzare il giro come se il movimento
|
||||
fosse riuscito; restano necessarie le verifiche e il recupero gia' esistenti.
|
||||
|
||||
## 10. Non scaffalate, salti, pausa e fine giro
|
||||
|
||||
### R14. Non scaffalate
|
||||
|
||||
Conservare il comportamento corrente: Non scaff. precede gli scaffali nel
|
||||
default, salvo diversa posizione assegnata nella sequenza personalizzata.
|
||||
La regola deve considerare le UDC di entrambe le liste.
|
||||
|
||||
La cella virtuale e' condivisibile e non ha un livello fisico da confrontare.
|
||||
Il criterio di parita' fra UDC non scaffalate delle due liste resta da
|
||||
concordare; proposta: ordine stabile per ruolo lista e codice UDC.
|
||||
|
||||
### R15. UDC saltate: approfondimento rinviato
|
||||
|
||||
Il comando Salta UDC esiste gia'. L'utente ha chiesto di analizzarne in seguito
|
||||
il comportamento nel nuovo giro abbinato, con l'intenzione di conservare
|
||||
quanto possibile il funzionamento attuale.
|
||||
|
||||
Restano da decidere il termine della singola lista con soli skip, la sua
|
||||
sprenotazione, la prosecuzione dell'altra lista e le modalita' di ripresa.
|
||||
Saltare una UDC non deve comunque equivalere a spedirla o cancellarla dalla lista.
|
||||
|
||||
### Pausa e ripresa: comportamento da completare
|
||||
|
||||
Oggi Pausa PL consente movimenti liberi e ESC riporta al picking.
|
||||
Nel nuovo giro occorre conservare identita' dei due documenti e percorso.
|
||||
Va deciso se al rientro mantenere la UDC gia' proposta o ricalcolare la
|
||||
prossima posizione quando nel frattempo cambiano le ubicazioni.
|
||||
I movimenti liberi devono mantenere le proprie regole di carico e scarico.
|
||||
|
||||
### Fine di una lista: proposta ancora da confermare
|
||||
|
||||
Quando una lista non ha piu' UDC residue, proseguire con l'altra mantenendone
|
||||
ruolo e colore originali. Non promuovere automaticamente F2 a F1 e non
|
||||
aggiungere un terzo documento. Distinguere esaurimento reale e soli skip.
|
||||
|
||||
## 11. Esempi di percorso atteso
|
||||
|
||||
### Esempio A: colonne presenti soltanto in F2
|
||||
|
||||
Area 6, stesso scaffale, default: colonne crescenti e livelli dal basso
|
||||
verso l'alto.
|
||||
|
||||
| Passo | Posizione | Lista proposta |
|
||||
|---|---|---|
|
||||
| 1 | Colonna 1, livello a | F2 |
|
||||
| 2 | Colonna 2, livello a | F2 |
|
||||
| 3 | Colonna 3, livello a | F1 |
|
||||
| 4 | Colonna 3, livello b | F2 |
|
||||
| 5 | Colonna 4, livello a | F2 |
|
||||
| 6 | Colonna 5, livello a | F2 |
|
||||
| 7 | Colonna 6, livello a | F1 |
|
||||
|
||||
F1 ha UDC solo ogni tre colonne. Le colonne intermedie di F2 vengono visitate
|
||||
al momento corretto, senza attendere il termine di F1.
|
||||
|
||||
### Esempio B: alternanza verticale nella stessa colonna
|
||||
|
||||
| Passo | Posizione | Lista proposta |
|
||||
|---|---|---|
|
||||
| 1 | Colonna 3, livello a | F2 |
|
||||
| 2 | Colonna 3, livello b | F1 |
|
||||
| 3 | Colonna 3, livello d | F2 |
|
||||
| 4 | Colonna 4, livello a | F1 |
|
||||
|
||||
Il passaggio F2 -> F1 -> F2 e' richiesto dal percorso; i documenti associati
|
||||
ai tasti restano gli stessi.
|
||||
|
||||
### Esempio C: area 5 con default storico
|
||||
|
||||
| Ordinamento cella | Ubicazione | Lista proposta |
|
||||
|---|---|---|
|
||||
| 1001 | 1A.1.e | F2 |
|
||||
| 1003 | 1A.1.c | F1 |
|
||||
| 1007 | 2B.1.e | F1 |
|
||||
| 1010 | 2B.1.b | F2 |
|
||||
| 1013 | 2B.2.e | F2 |
|
||||
| 1019 | 1A.2.e | F1 |
|
||||
|
||||
Si uniscono le due liste rispettando i valori del percorso storico; non si
|
||||
raggruppano automaticamente tutte le colonne 1A prima di quelle 2B.
|
||||
|
||||
### Esempio D: ordine personalizzato della coppia
|
||||
|
||||
Il responsabile imposta Non scaff. -> 4P -> 1M. Il terminalino lavora tutte
|
||||
le UDC richieste dalle due liste in Non scaff., poi quelle in 4P, poi quelle
|
||||
in 1M, applicando dentro ciascun gruppo l'ordine delle celle previsto.
|
||||
Gli eventuali gruppi non configurati vengono accodati, mai esclusi.
|
||||
|
||||
## 12. Garanzie e decisioni tecniche da tradurre in progetto
|
||||
|
||||
La prenotazione attuale a documento unico deve evolvere per rappresentare
|
||||
esplicitamente due documenti con ruoli stabili e una sequenza comune.
|
||||
Il formato delle nuove tabelle e le modifiche alle stored non sono ancora
|
||||
definiti da questo documento.
|
||||
|
||||
La nuova prenotazione dovra' essere salvata in modo atomico, evitando che il
|
||||
terminalino legga meta' coppia o una sequenza parzialmente aggiornata.
|
||||
Le modifiche SQL dovranno avere script di installazione e di ripristino e
|
||||
mantenere la separazione degli oggetti Python dagli oggetti legacy C#.
|
||||
|
||||
Sono ancora da specificare persistenza della ripresa dopo riavvio, modifiche
|
||||
alla coppia durante un giro, modifiche della sequenza a giro iniziato e
|
||||
comportamento con piu' terminalini. Non assumere che la memoria locale del
|
||||
singolo client sia una soluzione completa per questi casi.
|
||||
|
||||
## 13. Dati locali predisposti per il collaudo
|
||||
|
||||
Il 01/10/2026 sono state riattivate nella copia locale quattro testate SAM
|
||||
cambiando solo D in P, senza movimentare UDC. Con filtro 30 giorni:
|
||||
|
||||
| Lista | UDC residue | In celle fisiche | Non scaffalate nella vista |
|
||||
|---|---:|---:|---:|
|
||||
| 233 | 28 | 3 | 25 |
|
||||
| 234 | 28 | 2 | 26 |
|
||||
| 240 | 11 | 0 | 11 |
|
||||
| 241 | 28 | 0 | 28 |
|
||||
| 244, gia' attiva | 26 | 24 | 2 |
|
||||
|
||||
Le celle fisiche candidate sono risultate prive di altre UDC, anche esterne
|
||||
alle cinque liste. Le UDC residue non sono condivise fra questi documenti.
|
||||
La condivisione della locazione virtuale Non scaff. e' invece prevista.
|
||||
|
||||
Esempi utili in area 5: 234 in 1A.7.a e 244 in 1A.7.d; 233 in 1A.18.a e
|
||||
244 in 1A.18.c. Sono celle distinte della stessa colonna.
|
||||
|
||||
La voce Non scaff. puo' derivare anche dal fallback di una UDC senza giacenza
|
||||
WMS: non prova da sola l'esistenza di un versamento registrato nella cella 1000.
|
||||
|
||||
Questi dati non bastano a verificare tutte le alternanze verticali e le colonne
|
||||
intermedie in area 6: occorrera' predisporre ulteriori casi controllati prima
|
||||
del collaudo completo. Non creare documenti ERP fittizi o spostare UDC online
|
||||
per ottenere tali scenari.
|
||||
|
||||
Preparazione e ripristino sono descritti in [sql_tests/README.md](sql_tests/README.md).
|
||||
Il ripristino delle testate non annulla le movimentazioni fatte durante i test.
|
||||
|
||||
## 14. Criteri di accettazione
|
||||
|
||||
| Test | Risultato atteso |
|
||||
|---|---|
|
||||
| Una sola lista | Ordinamento attuale conservato |
|
||||
| Due liste entrambe Area 5 oppure entrambe Area 6 | Abbinamento consentito, applicando il percorso della relativa area |
|
||||
| Una lista Area 5 e una Area 6 | Abbinamento rifiutato senza modificare le prenotazioni esistenti |
|
||||
| F2 precede F1 nel percorso | All'avvio solo F2 utilizzabile |
|
||||
| F1 presente ogni tre colonne | Nessuna colonna intermedia F2 omessa |
|
||||
| Livelli alternati F2/F1/F2 | Tre proposte in ordine fisico, con documenti corretti |
|
||||
| Default area 5 | Serpentina attuale e livelli dall'alto verso il basso, anche all'avvio |
|
||||
| Area 5: F1 in 1A.7.a, F2 in 1A.7.d | Prima F2/d, poi F1/a, senza precedenza fissa a F1 |
|
||||
| Default area 6 | Percorso corrente per scaffale, colonne crescenti e livelli dal basso verso l'alto |
|
||||
| Personalizzazione della coppia | Stesso ordine applicato a entrambe |
|
||||
| Gruppo presente solo in F2 | Visibile nell'editor e incluso nel percorso |
|
||||
| Gruppo omesso dalla personalizzazione | Accodato secondo il comportamento attuale |
|
||||
| Tasto fisico della lista disabilitata | Nessun cambio documento e nessun movimento |
|
||||
| Cambio automatico | Numero lista, colore e UDC aggiornati coerentemente |
|
||||
| UDC con due lotti | Un solo prelievo fisico |
|
||||
| Terza lista disponibile | Mai inserita automaticamente nel giro |
|
||||
| Aggiornamento programma del campo UDC | Non interpretato come nuova lettura |
|
||||
| Movimento fallito o esito incerto | Nessun avanzamento ingiustificato |
|
||||
|
||||
I casi relativi a skip, fine parziale, pausa, riavvio e modifiche concorrenti
|
||||
andranno completati dopo la decisione delle relative regole.
|
||||
|
||||
## 15. Decisioni aperte per la revisione
|
||||
|
||||
L'avvio e' chiarito: si rispetta il percorso dell'area, dall'alto in area 5
|
||||
e dal basso in area 6. Restano aperti i punti seguenti.
|
||||
|
||||
1. Assegnazione esplicita dei ruoli Lista 1 e Lista 2 sul desktop.
|
||||
2. Gestione delle sequenze preesistenti quando si compone una nuova coppia.
|
||||
3. Ordine fra UDC non scaffalate o con identico valore di percorso.
|
||||
4. Salti, esaurimento con residui e riprenotazione della coppia o di una lista.
|
||||
5. Ripresa dalla pausa e da un riavvio, con ubicazioni eventualmente cambiate.
|
||||
6. Modifiche alla coppia/sequenza mentre il prelievo e' in corso.
|
||||
7. Fonte autorevole dell'area di una lista e gestione di liste internamente
|
||||
miste o con area indeterminata; le coppie Area 5/Area 6 sono vietate (R02a).
|
||||
8. Condotta su dati anomali: stessa UDC in due liste o cella fisica con piu' UDC.
|
||||
Il dataset di collaudo evita questi casi; la regola generale resta da definire.
|
||||
|
||||
Le risposte possono essere annotate direttamente in questa sezione prima di
|
||||
passare al progetto tecnico e alle modifiche applicative.
|
||||
38
sql_tests/README.md
Normal file
38
sql_tests/README.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# Dati per il collaudo a due picking list, 01/10/2026
|
||||
|
||||
Questi script riguardano esclusivamente la copia di test su HOMESERVER.
|
||||
Non includerli nella patch cumulativa per la produzione.
|
||||
|
||||
`riattiva_pickinglist_20261001.sql` cambia da D a P le testate SAM 233, 234,
|
||||
240 e 241 dell'anno 2026. Mantiene date, righe, lotti e posizioni delle UDC.
|
||||
Salva gli stati originali in Mediseawall.dbo.py_TestPickingListReactivation_20261001
|
||||
e controlla le precondizioni nella stessa transazione dell'aggiornamento.
|
||||
|
||||
In Gestione Picking List selezionare **30 giorni** per vedere tutte le liste:
|
||||
|
||||
| Lista | UDC residue | In celle fisiche | Non scaffalate nella vista |
|
||||
|---|---:|---:|---:|
|
||||
| 233 | 28 | 3 | 25 |
|
||||
| 234 | 28 | 2 | 26 |
|
||||
| 240 | 11 | 0 | 11 |
|
||||
| 241 | 28 | 0 | 28 |
|
||||
| 244 (gia attiva) | 26 | 24 | 2 |
|
||||
|
||||
La 240 conserva altre 33 UDC gia spedite, escluse dalla vista operativa.
|
||||
La qualifica non scaffalata deriva dalla vista: puo' comprendere UDC che non
|
||||
hanno una giacenza WMS, mostrate mediante il fallback convenzionale 1000.
|
||||
|
||||
Nessuna cella fisica candidata risulta contenere altre UDC. La condivisione
|
||||
della locazione virtuale non scaffalata e' ammessa. Le liste 233/234 e 244
|
||||
contengono celle distinte nelle stesse colonne, utili per il futuro test del
|
||||
cambio automatico fra documenti. Non sono stati creati movimenti di test.
|
||||
|
||||
`ripristina_testate_pickinglist_20261001.sql` ripristina solo gli stati SAM.
|
||||
Non ripristina UDC movimentate, skip o sequenze creati durante le prove.
|
||||
Per ripetere identicamente un test che modifica le giacenze occorre un backup
|
||||
coerente dei due database, oppure un ripristino specifico dei dati del test.
|
||||
La piccola tabella di backup degli stati non sostituisce tale backup completo.
|
||||
|
||||
Controllato anche il trigger SAM `StatoLottoRientrato`: il passaggio D -> P
|
||||
non soddisfa la sua condizione e non modifica i lotti. Il ripristino P -> D
|
||||
si ferma se esistono lotti marcati T, per evitare gli effetti di quel trigger.
|
||||
82
sql_tests/riattiva_pickinglist_20261001.sql
Normal file
82
sql_tests/riattiva_pickinglist_20261001.sql
Normal file
@@ -0,0 +1,82 @@
|
||||
/* Solo copia locale di test HOMESERVER. Non distribuire come patch produzione.
|
||||
Riattiva 233,234,240,241 conservando date, righe, UDC e posizioni attuali.
|
||||
Salva i valori di testata per un rollback mirato; non e' un backup dei DB.
|
||||
*/
|
||||
USE Mediseawall;
|
||||
SET NOCOUNT ON;
|
||||
SET XACT_ABORT ON;
|
||||
|
||||
IF CONVERT(nvarchar(128), SERVERPROPERTY('MachineName')) <> N'HOMESERVER'
|
||||
THROW 51000, 'Script riservato alla copia di test su HOMESERVER.', 1;
|
||||
|
||||
BEGIN TRY
|
||||
BEGIN TRANSACTION;
|
||||
|
||||
IF OBJECT_ID('dbo.py_TestPickingListReactivation_20261001', 'U') IS NOT NULL
|
||||
THROW 51001, 'Preparazione gia eseguita: controllare il backup prima di ripetere.', 1;
|
||||
|
||||
DECLARE @Targets TABLE (ID int PRIMARY KEY, Documento int NOT NULL);
|
||||
INSERT INTO @Targets VALUES (11882,233),(11883,234),(11890,240),(11891,241);
|
||||
|
||||
IF (SELECT COUNT(*) FROM SAMA1.dbo.BAMTES b WITH (UPDLOCK,HOLDLOCK)
|
||||
JOIN @Targets t ON b.ID=t.ID AND b.NUMDOC=t.Documento
|
||||
WHERE b.ANNDOC=2026 AND b.STATO='D'
|
||||
AND b.DATDOC>CAST(GETDATE()-30 AS int)) <> 4
|
||||
THROW 51002, 'Le quattro testate non corrispondono allo scenario atteso.', 1;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM dbo.py_XMag_ViewPackingListStorico h
|
||||
JOIN dbo.XMag_GiacenzaPallet g ON g.IDCella=h.Cella
|
||||
WHERE h.Documento IN (233,234,240,241,244) AND h.Cella NOT IN (1000,9999)
|
||||
AND LTRIM(RTRIM(g.BarcodePallet)) COLLATE Latin1_General_CI_AS <>
|
||||
h.Pallet COLLATE Latin1_General_CI_AS
|
||||
) THROW 51003, 'Cella fisica con altre UDC: preparazione annullata.', 1;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT Pallet FROM dbo.py_XMag_ViewPackingListStorico
|
||||
WHERE Documento IN (233,234,240,241,244) AND Cella<>9999
|
||||
GROUP BY Pallet HAVING COUNT(DISTINCT Documento)>1
|
||||
) THROW 51004, 'Una UDC residua appartiene a piu liste candidate.', 1;
|
||||
|
||||
IF EXISTS (SELECT 1 FROM dbo.py_BarcodePickingListSkip
|
||||
WHERE Documento IN ('233','234','240','241') AND Risolto=0)
|
||||
OR EXISTS (SELECT 1 FROM dbo.py_PickingListPrelievoSequenza
|
||||
WHERE Documento IN ('233','234','240','241') AND DelDataOra IS NULL)
|
||||
OR EXISTS (SELECT 1 FROM dbo.PyPickingListReservation
|
||||
WHERE NULLIF(LTRIM(RTRIM(Documento)),'') IS NOT NULL)
|
||||
THROW 51005, 'Prenotazioni, skip o sequenze attive: verificare prima del test.', 1;
|
||||
|
||||
CREATE TABLE dbo.py_TestPickingListReactivation_20261001 (
|
||||
BamtesID int NOT NULL PRIMARY KEY,
|
||||
Anno smallint NOT NULL,
|
||||
Documento int NOT NULL,
|
||||
StatoOriginale char(1) NOT NULL,
|
||||
DataDocumentoOriginale float NOT NULL,
|
||||
ApplicataIl datetime2 NOT NULL,
|
||||
RipristinataIl datetime2 NULL
|
||||
);
|
||||
INSERT INTO dbo.py_TestPickingListReactivation_20261001
|
||||
(BamtesID,Anno,Documento,StatoOriginale,DataDocumentoOriginale,ApplicataIl)
|
||||
SELECT b.ID,b.ANNDOC,b.NUMDOC,b.STATO,b.DATDOC,SYSDATETIME()
|
||||
FROM SAMA1.dbo.BAMTES b JOIN @Targets t ON t.ID=b.ID;
|
||||
|
||||
UPDATE b SET STATO='P'
|
||||
FROM SAMA1.dbo.BAMTES b JOIN @Targets t ON t.ID=b.ID;
|
||||
IF @@ROWCOUNT<>4 THROW 51006, 'Numero di testate aggiornate inatteso.', 1;
|
||||
|
||||
IF (SELECT COUNT(DISTINCT Documento) FROM dbo.py_ViewPackingListPrelievo
|
||||
WHERE Documento IN (233,234,240,241,244)
|
||||
AND DataDocumento>CAST(GETDATE()-30 AS int))<>5
|
||||
THROW 51007, 'Le cinque liste non risultano tutte visibili. Rollback.', 1;
|
||||
|
||||
COMMIT TRANSACTION;
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
IF @@TRANCOUNT>0 ROLLBACK TRANSACTION;
|
||||
THROW;
|
||||
END CATCH;
|
||||
|
||||
SELECT Documento,COUNT(DISTINCT Pallet) AS UdcResidue
|
||||
FROM dbo.py_ViewPackingListPrelievo
|
||||
WHERE Documento IN (233,234,240,241,244)
|
||||
GROUP BY Documento ORDER BY Documento;
|
||||
54
sql_tests/ripristina_testate_pickinglist_20261001.sql
Normal file
54
sql_tests/ripristina_testate_pickinglist_20261001.sql
Normal file
@@ -0,0 +1,54 @@
|
||||
/* Ripristina SOLO lo stato delle quattro testate riattivate per i test.
|
||||
Non annulla movimentazioni effettuate durante il collaudo.
|
||||
Eseguire sullo stesso DB locale con applicazioni ferme e liste sprenotate.
|
||||
*/
|
||||
USE Mediseawall;
|
||||
SET NOCOUNT ON;
|
||||
SET XACT_ABORT ON;
|
||||
IF CONVERT(nvarchar(128),SERVERPROPERTY('MachineName'))<>N'HOMESERVER'
|
||||
THROW 51000, 'Script riservato alla copia di test su HOMESERVER.', 1;
|
||||
IF OBJECT_ID('dbo.py_TestPickingListReactivation_20261001','U') IS NULL
|
||||
THROW 51001, 'Backup delle testate non trovato.', 1;
|
||||
|
||||
BEGIN TRY
|
||||
BEGIN TRANSACTION;
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM dbo.PyPickingListReservation r
|
||||
JOIN dbo.py_TestPickingListReactivation_20261001 s
|
||||
ON r.Documento=CAST(s.Documento AS varchar(8))
|
||||
WHERE s.RipristinataIl IS NULL
|
||||
) THROW 51002, 'Sprenotare le liste di test prima del ripristino.', 1;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM dbo.py_TestPickingListReactivation_20261001 s
|
||||
LEFT JOIN SAMA1.dbo.BAMTES b WITH (UPDLOCK,HOLDLOCK) ON b.ID=s.BamtesID
|
||||
WHERE s.RipristinataIl IS NULL AND
|
||||
(b.ID IS NULL OR b.ANNDOC<>s.Anno OR b.NUMDOC<>s.Documento
|
||||
OR b.DATDOC<>s.DataDocumentoOriginale OR b.STATO IS NULL
|
||||
OR b.STATO NOT IN ('P','D'))
|
||||
) THROW 51003, 'Testate cambiate rispetto al backup: verificare manualmente.', 1;
|
||||
|
||||
-- Il trigger SAM StatoLottoRientrato modifica LOTSER.DESCR tornando in D.
|
||||
-- In presenza di lotti marcati T fermarsi prima di attivarlo.
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM dbo.py_TestPickingListReactivation_20261001 s
|
||||
JOIN SAMA1.dbo.BAMTES b ON b.ID=s.BamtesID
|
||||
JOIN SAMA1.dbo.FATRIG f ON f.IDBAM=b.ID
|
||||
JOIN SAMA1.dbo.LOTTIBF lb ON lb.IDFATRIG=f.ID
|
||||
JOIN SAMA1.dbo.LOTSER l ON l.ID=lb.IDLOTSER
|
||||
WHERE s.RipristinataIl IS NULL AND b.STATO<>'D' AND l.DESCR='T'
|
||||
) THROW 51004, 'Lotti rientrati marcati T: ripristino da valutare per il trigger SAM.', 1;
|
||||
|
||||
UPDATE b SET STATO=s.StatoOriginale
|
||||
FROM SAMA1.dbo.BAMTES b
|
||||
JOIN dbo.py_TestPickingListReactivation_20261001 s ON s.BamtesID=b.ID
|
||||
WHERE s.RipristinataIl IS NULL;
|
||||
|
||||
UPDATE dbo.py_TestPickingListReactivation_20261001
|
||||
SET RipristinataIl=SYSDATETIME() WHERE RipristinataIl IS NULL;
|
||||
COMMIT TRANSACTION;
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
IF @@TRANCOUNT>0 ROLLBACK TRANSACTION;
|
||||
THROW;
|
||||
END CATCH;
|
||||
194
tests/test_barcode_document_binding.py
Normal file
194
tests/test_barcode_document_binding.py
Normal file
@@ -0,0 +1,194 @@
|
||||
"""Document isolation regressions; no GUI, DB connection or real movements."""
|
||||
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from barcode_repository import BarcodeRepository, LegacyMoveResult
|
||||
from barcode_service import BarcodeService
|
||||
|
||||
|
||||
def row(doc, pallet, priority, order):
|
||||
return dict(Documento=doc, Pallet=pallet, IDStato=priority,
|
||||
Ordinamento=order, Cella=1101, Ubicazione="1A - 1 - a")
|
||||
|
||||
|
||||
class PickingRepositoryFake:
|
||||
def __init__(self):
|
||||
# Without a document filter the sequence would be 172, 171, 172.
|
||||
self.rows = [row("173", "600001", 1, 5), row("172", "600002", 0, 10),
|
||||
row("171", "600003", 0, 20), row("172", "600004", 0, 30)]
|
||||
self.skipped = set()
|
||||
self.locations = {r["Pallet"]: r["Cella"] for r in self.rows}
|
||||
self.released = []
|
||||
|
||||
async def fetch_next_picking(self, id_stato, documento=None):
|
||||
candidates = [r for r in self.rows if r["IDStato"] == id_stato
|
||||
and (documento is None or r["Documento"] == documento)
|
||||
and r["Pallet"] not in self.skipped]
|
||||
return min(candidates, key=lambda r: r["Ordinamento"]) if candidates else None
|
||||
|
||||
async def fetch_active_skipped_document(self, id_stato, documento=None):
|
||||
candidates = [r for r in self.rows if r["IDStato"] == id_stato
|
||||
and (documento is None or r["Documento"] == documento)
|
||||
and r["Pallet"] in self.skipped]
|
||||
return dict(Documento=candidates[0]["Documento"], SkippedCount=len(candidates)) if candidates else None
|
||||
|
||||
async def count_picking_document_remaining(self, documento):
|
||||
return len({r["Pallet"] for r in self.rows if r["Documento"] == documento})
|
||||
|
||||
async def release_picking_document(self, *, documento, operator_id):
|
||||
self.released.append(documento)
|
||||
return 0
|
||||
|
||||
async def skip_picking_pallet(self, *, documento, pallet, **kwargs):
|
||||
self.skipped.add(pallet)
|
||||
|
||||
async def fetch_picking_by_pallet(self, pallet, documento=None):
|
||||
return next((r for r in self.rows if r["Pallet"] == pallet
|
||||
and (documento is None or r["Documento"] == documento)), None)
|
||||
|
||||
async def fetch_trace_by_pallet(self, pallet):
|
||||
return dict(Lotto="LOT", Prodotto="ART", Descrizione="Test")
|
||||
|
||||
async def fetch_current_location_by_pallet(self, pallet):
|
||||
return dict(IDCella=self.locations[pallet])
|
||||
|
||||
async def fetch_open_locations_by_pallet(self, pallet):
|
||||
return [await self.fetch_current_location_by_pallet(pallet)]
|
||||
|
||||
async def fetch_closed_picking_by_pallet(self, pallet):
|
||||
return None
|
||||
|
||||
async def execute_legacy_move(self, *, barcode_pallet, barcode_cella, **kwargs):
|
||||
target = 9999 if barcode_cella == "9000000" else 1000
|
||||
self.locations[barcode_pallet] = target
|
||||
if target == 9999:
|
||||
self.rows = [r for r in self.rows if r["Pallet"] != barcode_pallet]
|
||||
return LegacyMoveResult(0, barcode_cella, barcode_pallet, int(barcode_cella))
|
||||
|
||||
|
||||
class DocumentBindingTests(unittest.IsolatedAsyncioTestCase):
|
||||
def setUp(self):
|
||||
logger = patch("barcode_service.log_runtime_event")
|
||||
logger.start()
|
||||
self.addCleanup(logger.stop)
|
||||
self.repo = PickingRepositoryFake()
|
||||
self.service = BarcodeService(self.repo, operator_id=1)
|
||||
|
||||
async def ship_current(self):
|
||||
result = await self.service.submit(
|
||||
scanned_pallet=self.service.state.expected_pallet, destination_barcode="9000000")
|
||||
self.assertTrue(result.ok)
|
||||
self.assertEqual(result.state.auto_advance_delay_ms, 3000)
|
||||
|
||||
async def test_auto_advance_never_interleaves_low_priority_documents(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
await self.ship_current()
|
||||
result = await self.service.start_priority_queue(0)
|
||||
self.assertEqual((result.state.document, result.state.expected_pallet), ("172", "600004"))
|
||||
|
||||
async def test_f2_f1_f2_stays_bound_even_if_global_order_changes(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
self.repo.rows[2]["Ordinamento"] = 1
|
||||
for _ in range(5):
|
||||
high = await self.service.start_priority_queue(1)
|
||||
self.assertEqual(high.state.document, "173")
|
||||
low = await self.service.start_priority_queue(0)
|
||||
self.assertEqual((low.state.document, low.state.expected_pallet), ("172", "600002"))
|
||||
|
||||
async def test_pause_free_move_resume_and_switch_preserve_document(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
paused = self.service.state
|
||||
self.service.begin_priority_pause(0)
|
||||
free = await self.service.submit(scanned_pallet="600003", destination_barcode="9001000")
|
||||
self.assertTrue(free.ok)
|
||||
self.service.resume_priority_state(paused)
|
||||
await self.service.start_priority_queue(1)
|
||||
low = await self.service.start_priority_queue(0)
|
||||
self.assertEqual(low.state.document, "172")
|
||||
self.assertEqual(low.state.expected_pallet, "600002")
|
||||
|
||||
async def test_skip_advances_only_within_active_document(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
await self.service.skip_current_picking_pallet()
|
||||
low = await self.service.start_priority_queue(0)
|
||||
self.assertEqual(low.state.expected_pallet, "600004")
|
||||
|
||||
async def test_only_skipped_residuals_stop_even_with_other_lists_available(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
await self.service.skip_current_picking_pallet()
|
||||
await self.service.start_priority_queue(0)
|
||||
await self.service.skip_current_picking_pallet()
|
||||
result = await self.service.start_priority_queue(0)
|
||||
self.assertEqual(result.state.mode, "manual_unload")
|
||||
self.assertIn("PL 172 sospesa", result.state.status_text)
|
||||
self.assertEqual(self.repo.released, ["172"])
|
||||
|
||||
async def test_completion_stops_before_next_document(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
await self.ship_current()
|
||||
await self.service.start_priority_queue(0)
|
||||
await self.ship_current()
|
||||
stopped = await self.service.start_priority_queue(0)
|
||||
self.assertEqual(stopped.state.mode, "manual_unload")
|
||||
self.assertIn("PL 172 terminata", stopped.state.status_text)
|
||||
self.assertEqual(stopped.state.auto_advance_delay_ms, 0)
|
||||
# A later explicit F2 can start another list, after the stop message.
|
||||
next_list = await self.service.start_priority_queue(0)
|
||||
self.assertEqual(next_list.state.document, "171")
|
||||
|
||||
async def test_priority_change_blocks_without_forgetting_previous_document(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
for r in self.repo.rows:
|
||||
if r["Documento"] == "172":
|
||||
r["IDStato"] = 1
|
||||
for _ in range(2):
|
||||
stopped = await self.service.start_priority_queue(0)
|
||||
self.assertIn("PL 172", stopped.state.status_text)
|
||||
self.assertIn("Verifica la prenotazione", stopped.state.status_text)
|
||||
for r in self.repo.rows:
|
||||
if r["Documento"] == "172":
|
||||
r["IDStato"] = 0
|
||||
resumed = await self.service.start_priority_queue(0)
|
||||
self.assertEqual(resumed.state.document, "172")
|
||||
|
||||
async def test_query_exception_keeps_document_for_retry(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
with patch.object(self.repo, "fetch_next_picking", side_effect=TimeoutError):
|
||||
with self.assertRaises(TimeoutError):
|
||||
await self.service.start_priority_queue(0)
|
||||
self.repo.rows[2]["Ordinamento"] = 1
|
||||
result = await self.service.start_priority_queue(0)
|
||||
self.assertEqual(result.state.document, "172")
|
||||
|
||||
async def test_wrong_document_from_repository_is_rejected(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
with patch.object(self.repo, "fetch_next_picking", return_value=self.repo.rows[2]):
|
||||
with self.assertRaisesRegex(RuntimeError, "Cambio inatteso documento"):
|
||||
await self.service.start_priority_queue(0)
|
||||
result = await self.service.start_priority_queue(0)
|
||||
self.assertEqual(result.state.document, "172")
|
||||
|
||||
async def test_confirmation_cannot_display_another_document_for_same_pallet(self):
|
||||
await self.service.start_priority_queue(0)
|
||||
self.repo.rows.append(row("171", "600002", 0, 1))
|
||||
self.repo.fetch_picking_by_pallet = AsyncMock(wraps=self.repo.fetch_picking_by_pallet)
|
||||
state = await self.service._build_post_move_state(
|
||||
barcode_pallet="600002", destination_barcode="9000000",
|
||||
destination_display="7G.1.1", last_priority_state=0, auto_advance_delay_ms=3000)
|
||||
self.assertEqual(state.document, "172")
|
||||
self.repo.fetch_picking_by_pallet.assert_awaited_once_with("600002", documento="172")
|
||||
|
||||
async def test_repository_passes_document_to_all_related_queries(self):
|
||||
db = type("DB", (), {"query_json": AsyncMock(return_value={"rows": []})})()
|
||||
repo = BarcodeRepository(db)
|
||||
await repo.fetch_next_picking(0, documento="172")
|
||||
await repo.fetch_active_skipped_document(0, documento="172")
|
||||
await repo.fetch_picking_by_pallet("600002", documento="172")
|
||||
for call in db.query_json.await_args_list:
|
||||
self.assertEqual(call.args[1]["documento"], "172")
|
||||
self.assertIn(":documento", call.args[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
202
tests/test_inventory.py
Normal file
202
tests/test_inventory.py
Normal file
@@ -0,0 +1,202 @@
|
||||
"""Domain and XLSX regression tests: no live stock is modified."""
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from inventory_service import (DETAIL_KEYS, SUMMARY_KEYS, build_report, export_inventory,
|
||||
inventory_cutoff, load_inventory)
|
||||
from locale_text import text
|
||||
|
||||
DAY = date(2025, 12, 31)
|
||||
HISTORY = dict(Kind="META", Component="HIST_MIN", SourceDate=datetime(2022, 1, 1))
|
||||
|
||||
|
||||
def stock(**changes):
|
||||
r = dict(Kind="ROW", Component="A", Product="P1", Description="Product",
|
||||
Unit="NR", ContainerId=1, Lot="L1", Serial="600001/000001",
|
||||
Pallet="600001", Cell=1101, Location="1A.1.a", Balance=Decimal(1),
|
||||
Quantity=Decimal(20), SamQuantity=Decimal(20), Locations=1,
|
||||
NegativeBalances=0, Shipped=0, AssignmentIssue=0,
|
||||
MovementIssues=0, OtherReceipts=0)
|
||||
r.update(changes)
|
||||
return r
|
||||
|
||||
|
||||
def report(*records):
|
||||
return build_report(DAY, [HISTORY, *records])
|
||||
|
||||
|
||||
def packing(**changes):
|
||||
return stock(Component="B", ContainerId=2, Pallet="600002", Serial="600002/000002",
|
||||
Cell=None, Location=None, Balance=None, Locations=0, **changes)
|
||||
|
||||
|
||||
def loose(**changes):
|
||||
return stock(Component="C", ContainerId=3, Pallet="000000", Serial="000000/000003",
|
||||
Cell=None, Location=None, Balance=None, Locations=0, **changes)
|
||||
|
||||
|
||||
class InventoryTests(unittest.TestCase):
|
||||
def test_year_end_exclusive_cutoff(self):
|
||||
self.assertEqual(inventory_cutoff("31/12/2025"), (DAY, datetime(2026, 1, 1), 46023))
|
||||
|
||||
def test_dates_invalid_future_and_leap(self):
|
||||
for value in ("31/02/2025", "2025-12-31", "01/01/3000", "31/12/2009"):
|
||||
with self.assertRaises(ValueError):
|
||||
inventory_cutoff(value)
|
||||
self.assertEqual(inventory_cutoff("29/02/2024")[1], datetime(2024, 3, 1))
|
||||
|
||||
def test_three_components_and_sign(self):
|
||||
r = report(stock(), packing(Quantity=10, SamQuantity=10), loose(Quantity=5, SamQuantity=5))
|
||||
row = r.rows[0]
|
||||
self.assertEqual([row[k] for k in ("WMS", "Packing", "Loose", "Reconstructed", "SAM", "Difference")],
|
||||
[20, 10, 5, 35, 35, 0])
|
||||
self.assertEqual(row["InitialDifference"], 15)
|
||||
self.assertEqual(row["LooseContainers"], 1)
|
||||
|
||||
def test_non_shelved_is_a_not_b(self):
|
||||
row = report(stock(Cell=1000)).rows[0]
|
||||
self.assertEqual((row["NonShelved"], row["Packing"], row["UDCs"]), (20, 0, 1))
|
||||
|
||||
def test_multilot_counts_udc_once_and_keeps_lots(self):
|
||||
r = report(stock(), stock(ContainerId=4, Lot="L2", Serial="600001/000004"))
|
||||
self.assertEqual((r.rows[0]["UDCs"], r.rows[0]["WMS"]), (1, 40))
|
||||
self.assertEqual(len(r.lots), 2)
|
||||
|
||||
def test_multi_product_udc(self):
|
||||
r = report(stock(), stock(ContainerId=4, Product="P2"))
|
||||
self.assertEqual([row["UDCs"] for row in r.rows], [1, 1])
|
||||
|
||||
def test_lot_offsets_do_not_look_like_a_match(self):
|
||||
row = report(stock(SamQuantity=10), stock(ContainerId=2, Lot="L2", SamQuantity=30)).rows[0]
|
||||
self.assertEqual(row["Difference"], 0)
|
||||
self.assertIn("lot_offsets", row["Issues"])
|
||||
|
||||
def test_multilocation_does_not_double_sam(self):
|
||||
r = report(stock(Locations=2), stock(Locations=2, Cell=8004))
|
||||
self.assertEqual((r.rows[0]["SAM"], r.rows[0]["UDCs"]), (20, 1))
|
||||
self.assertIsNone(r.rows[0]["WMS"])
|
||||
self.assertIn("locations", r.rows[0]["Issues"])
|
||||
|
||||
def test_duplicate_incompatible_data_invalidates(self):
|
||||
row = report(stock(), stock(Quantity=50)).rows[0]
|
||||
self.assertIn("duplicate", row["Issues"])
|
||||
self.assertIsNone(row["SAM"])
|
||||
|
||||
def test_missing_content_is_not_zero(self):
|
||||
row = report(stock(Quantity=None)).rows[0]
|
||||
self.assertIsNone(row["WMS"])
|
||||
self.assertIsNone(row["Difference"])
|
||||
self.assertEqual(row["SAM"], 20)
|
||||
|
||||
def test_shipped_residual_is_not_packaging(self):
|
||||
row = report(
|
||||
stock(), stock(Component="X", ContainerId=9, Pallet="600009",
|
||||
Cell=None, Locations=1, Shipped=1, Quantity=5, SamQuantity=5)).rows[0]
|
||||
self.assertEqual((row["Packing"], row["SAM"], row["Difference"]), (0, 25, 5))
|
||||
self.assertIn("shipped", row["Issues"])
|
||||
|
||||
def test_sam_zero_does_not_hide_wms_presence(self):
|
||||
row = report(stock(SamQuantity=0)).rows[0]
|
||||
self.assertEqual((row["WMS"], row["Difference"]), (20, -20))
|
||||
|
||||
def test_partial_container_uses_actual_quantity(self):
|
||||
row = report(loose(Quantity=Decimal("3.5"), SamQuantity=Decimal("3.5"))).rows[0]
|
||||
self.assertEqual(row["Loose"], Decimal("3.5"))
|
||||
|
||||
def test_history_missing_or_ambiguous_is_not_certified(self):
|
||||
for r in (build_report(DAY, [stock()]), report(stock(AssignmentIssue=1)),
|
||||
build_report(date(2020, 1, 1), [HISTORY, stock()])):
|
||||
self.assertIn("history", r.rows[0]["Issues"])
|
||||
self.assertIsNone(r.rows[0]["Difference"])
|
||||
|
||||
def test_movements_missing_invalidates_sam(self):
|
||||
row = report(stock(MovementIssues=1)).rows[0]
|
||||
self.assertIsNone(row["SAM"])
|
||||
|
||||
def test_negative_balance_flagged(self):
|
||||
row = report(loose(Quantity=-5, SamQuantity=-5)).rows[0]
|
||||
self.assertIn("negative", row["Issues"])
|
||||
self.assertIsNone(row["Difference"])
|
||||
|
||||
def test_other_receipt_requires_validation(self):
|
||||
row = report(stock(OtherReceipts=1)).rows[0]
|
||||
self.assertIsNone(row["WMS"])
|
||||
|
||||
def test_unknown_unit(self):
|
||||
row = report(stock(Unit="KG")).rows[0]
|
||||
self.assertIn("unit", row["Issues"])
|
||||
self.assertIsNone(row["SAM"])
|
||||
|
||||
def test_undated_wms(self):
|
||||
row = report(stock(), dict(Kind="META", Component="UNDATED", Quantity=1)).rows[0]
|
||||
self.assertIsNone(row["Difference"])
|
||||
|
||||
def test_missing_label_remains_visible(self):
|
||||
row = report(stock(Product=None, ContainerId=None, Quantity=None)).rows[0]
|
||||
self.assertIn("600001", row["Product"])
|
||||
self.assertIsNone(row["WMS"])
|
||||
|
||||
def test_empty_report(self):
|
||||
r = report()
|
||||
self.assertEqual((r.rows, r.lots, r.details), ([], [], []))
|
||||
|
||||
def test_export_roundtrip(self):
|
||||
from openpyxl import load_workbook
|
||||
r = report(stock(Product="=CODE"), stock(Product="P2", ContainerId=2, Quantity=None))
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = str(Path(folder) / "inventory.xlsx")
|
||||
export_inventory(r, path, translate=text)
|
||||
wb = load_workbook(path)
|
||||
ws = wb.active
|
||||
self.assertEqual(len(wb.worksheets), 3)
|
||||
self.assertEqual(ws["B1"].value.date(), DAY)
|
||||
self.assertEqual((ws["A7"].value, ws["A7"].data_type), ("=CODE", "s"))
|
||||
diff_col = SUMMARY_KEYS.index("Difference") + 1
|
||||
self.assertEqual(ws.cell(7, diff_col).value, 0)
|
||||
self.assertIsNone(ws.cell(8, SUMMARY_KEYS.index("WMS")+1).value)
|
||||
self.assertEqual(ws.freeze_panes, "A7")
|
||||
self.assertEqual(wb.worksheets[2].cell(2, DETAIL_KEYS.index("Serial")+1).value, "600001/000001")
|
||||
wb.close()
|
||||
|
||||
def test_translations_complete(self):
|
||||
catalog = json.loads(Path("locale.json").read_text(encoding="utf-8"))
|
||||
for language in ("IT", "ENG"):
|
||||
for key in SUMMARY_KEYS + DETAIL_KEYS:
|
||||
self.assertIn("inventory.col." + key, catalog[language])
|
||||
for component in "ABCX":
|
||||
self.assertIn("inventory.component." + component, catalog[language])
|
||||
self.assertEqual({k for k in catalog["IT"] if k.startswith("inventory.")},
|
||||
{k for k in catalog["ENG"] if k.startswith("inventory.")})
|
||||
|
||||
def test_sqlalchemy_has_only_two_actual_bind_markers(self):
|
||||
from sqlalchemy import text as sql_text
|
||||
from sqlalchemy.dialects.mssql.pyodbc import dialect
|
||||
from inventory_service import SQL_PATH
|
||||
compiled = sql_text(SQL_PATH.read_text(encoding="utf-8")).compile(dialect=dialect(paramstyle="qmark"))
|
||||
self.assertEqual(compiled.positiontup, ["cutoff", "sam_cutoff"])
|
||||
|
||||
|
||||
class InventoryAsyncTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_bound_cutoffs_without_commit(self):
|
||||
db = type("DB", (), {"query_json": AsyncMock(return_value={"rows": []})})()
|
||||
r = await load_inventory(db, "31/12/2025")
|
||||
args, kwargs = db.query_json.call_args
|
||||
self.assertEqual(args[1]["cutoff"], datetime(2026, 1, 1))
|
||||
self.assertEqual(args[1]["sam_cutoff"], 46023)
|
||||
self.assertNotIn("commit", kwargs)
|
||||
self.assertEqual(r.selected_date, DAY)
|
||||
|
||||
async def test_invalid_date_never_queries(self):
|
||||
db = type("DB", (), {"query_json": AsyncMock()})()
|
||||
with self.assertRaises(ValueError):
|
||||
await load_inventory(db, "31/02/2025")
|
||||
db.query_json.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
132
tests/test_inventory_gui.py
Normal file
132
tests/test_inventory_gui.py
Normal file
@@ -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()
|
||||
139
tests/test_inventory_sql.py
Normal file
139
tests/test_inventory_sql.py
Normal file
@@ -0,0 +1,139 @@
|
||||
"""Opt-in SQL Server integration tests using ONLY local #temporary fixtures.
|
||||
|
||||
Set INVENTORY_TEST_CONFIG to a local db_connection.json. Source object names in
|
||||
the production batch are replaced with #fixtures before execution: no warehouse
|
||||
or ERP table is read or written by the test. Credentials are never printed.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import unittest
|
||||
from datetime import date, datetime
|
||||
|
||||
from inventory_service import SQL_PATH, build_report
|
||||
|
||||
|
||||
@unittest.skipUnless(os.environ.get("INVENTORY_TEST_CONFIG"), "SQL fixture test is opt-in")
|
||||
class InventorySQLTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
import pyodbc
|
||||
with open(os.environ["INVENTORY_TEST_CONFIG"], encoding="utf-8") as handle:
|
||||
c = json.load(handle)
|
||||
self.cn = pyodbc.connect("DRIVER={" + c["driver"] + "};SERVER=" + c["server"]
|
||||
+ ";DATABASE=" + c["database"] + ";UID=" + c["user"] + ";PWD=" + c["password"]
|
||||
+ ";TrustServerCertificate=yes;", timeout=5)
|
||||
self.cn.timeout = 60
|
||||
self.addCleanup(self.cn.close)
|
||||
self.addCleanup(self.cn.rollback)
|
||||
self.cur = self.cn.cursor()
|
||||
definitions = {
|
||||
"ANAMAG": "ID int, DESCR varchar(100)",
|
||||
"ALLMAG": "ID int, IDANAMAG int",
|
||||
"MagazziniPallet": "Attributo varchar(20),IDCella int,Tipo char(1),PesoUnitario decimal(28,6),DataMagazzino datetime",
|
||||
"Celle": "ID int,IDArea int,Corsia varchar(20),Colonna varchar(20),Fila varchar(20)",
|
||||
"Aree": "ID int,IDMagazzino int",
|
||||
"Magazzini": "ID int,Descrizione varchar(20)",
|
||||
"LOTSER": "ID int,IDARTICO int,NUMLOT varchar(30),NUMSER varchar(30)",
|
||||
"EXTTACLOTSER": "IDLOTSER float,EXNUMSER varchar(30),NUMSER varchar(30),AGGIORNAMENTO datetime",
|
||||
"GIAMAG": "IDARTICO int,IDMAG int,QTTGIAI decimal(28,6)",
|
||||
"MOVMAG": "IDARTICO int,IDCAUMOV int,IDMAGPAR int,IDMAGARR int,QTAINV decimal(28,6),DATMOV float",
|
||||
"CAUMOV": "ID int,CODICE varchar(10),QTGIUP char(1),QTGIUA char(1)",
|
||||
"ARTICO": "ID int,CODICE varchar(30),DESCR varchar(100),UMI varchar(8)",
|
||||
}
|
||||
for name, definition in definitions.items():
|
||||
self.cur.execute(f"CREATE TABLE #fixture_{name} ({definition})")
|
||||
self.sql = SQL_PATH.read_text(encoding="utf-8")
|
||||
for name in definitions:
|
||||
self.sql = self.sql.replace("SAMA1.dbo." + name, "#fixture_" + name)
|
||||
self.sql = self.sql.replace("dbo." + name, "#fixture_" + name)
|
||||
self.assertNotIn("SAMA1.dbo.", self.sql)
|
||||
self.assertNotIn("dbo.", self.sql)
|
||||
self.sql = self.sql.replace(":sam_cutoff", "?").replace(":cutoff", "?")
|
||||
self.insert("ANAMAG", (20, "Magazzino Principale"))
|
||||
self.insert("ALLMAG", (4, 20), (6, 30))
|
||||
self.insert("Magazzini", (1, "MDE5"), (2, "MDE6"), (3, "OTHER"))
|
||||
self.insert("Aree", (1, 1), (2, 2), (3, 3))
|
||||
self.insert("Celle", (1101, 1, "1A", "1", "a"), (8004, 2, "4P", "1", "d"),
|
||||
(1000, 1, "5E", "1", "1"), (9999, 1, "7G", "1", "1"),
|
||||
(9900, 3, "Z", "1", "1"))
|
||||
self.insert("ARTICO", (1, "PROD", "Product", "NR"))
|
||||
self.insert("CAUMOV", (1, "CP", None, "+"), (2, "VEN", "-", None))
|
||||
self.insert("EXTTACLOTSER", (999, "000000/000999", "600999/000999", datetime(2022, 1, 1)))
|
||||
self.day = date(2026, 1, 1)
|
||||
self.cutoff = datetime(2026, 1, 2)
|
||||
self.serial_cutoff = (self.cutoff - datetime(1899, 12, 30)).days
|
||||
for pallet, cell in (("600001", 1101), ("600002", 1000), ("600006", 9999), ("600007", 9999)):
|
||||
self.insert("MagazziniPallet", (pallet, cell, "V", 1, datetime(2025, 12, 30)))
|
||||
# Real WMS stock: 60 + 40 + 10 pieces. ID3 is another lot in the SAME UDC.
|
||||
self.container(1, "L1", "600001/000001", 60, 0)
|
||||
self.container(2, "L1", "600002/000002", 40, 40)
|
||||
self.container(3, "L2", "600001/000003", 10, 10)
|
||||
self.container(4, "L1", "600004/000004", 30, 30) # partial packing UDC
|
||||
self.container(5, "L1", "000000/000005", 20, 20)
|
||||
self.container(6, "L1", "600006/000006", 15, 15) # shipped with SAM residual
|
||||
self.container(7, "L1", "600007/000007", 99, 0) # fully shipped
|
||||
self.container(8, "EXCLUDED", "000000/000008", 777, 777) # same product, other lot
|
||||
self.container(9, "L1", "600009/000009", 6, 6) # was unassigned at cutoff
|
||||
self.insert("EXTTACLOTSER", (9, "000000/000009", "600009/000009", datetime(2026, 1, 3)))
|
||||
# ID1 shipped AFTER inventory. Current GIAMAG=0 must be reversed to 60.
|
||||
self.insert("MOVMAG", (1, 2, 4, None, 60, self.serial_cutoff + 1))
|
||||
self.insert("MagazziniPallet", ("600001", 1101, "P", 1, datetime(2026, 1, 3)),
|
||||
("600001", 9999, "V", 1, datetime(2026, 1, 3)))
|
||||
|
||||
def insert(self, name, *rows):
|
||||
for row in rows:
|
||||
self.cur.execute(f"INSERT INTO #fixture_{name} VALUES ({','.join('?' for _ in row)})", row)
|
||||
|
||||
def container(self, identity, lot, serial, receipt, current):
|
||||
self.insert("LOTSER", (identity, 1, lot, serial))
|
||||
self.insert("GIAMAG", (identity, 4, current))
|
||||
self.insert("MOVMAG", (identity, 1, None, 4, receipt, self.serial_cutoff - 2))
|
||||
|
||||
def run_query(self):
|
||||
self.cur.execute(self.sql, self.cutoff, self.serial_cutoff)
|
||||
columns = [c[0] for c in self.cur.description]
|
||||
records = [dict(zip(columns, row)) for row in self.cur.fetchall()]
|
||||
return build_report(self.day, records)
|
||||
|
||||
def test_scope_history_shipments_three_components(self):
|
||||
r = self.run_query()
|
||||
row = r.rows[0]
|
||||
self.assertEqual((row["WMS"], row["Packing"], row["Loose"], row["SAM"], row["Difference"]),
|
||||
(110, 30, 26, 181, 15))
|
||||
self.assertEqual((row["UDCs"], row["PackingUDCs"], row["LooseContainers"]), (2, 1, 2))
|
||||
self.assertEqual({x["Lot"] for x in r.lots}, {"L1", "L2"})
|
||||
by_id = {x["ContainerId"]: x for x in r.details}
|
||||
self.assertEqual(by_id[9]["Component"], "C")
|
||||
self.assertEqual(by_id[9]["Serial"], "000000/000009")
|
||||
self.assertEqual(by_id[6]["Component"], "X")
|
||||
self.assertNotIn(7, by_id)
|
||||
self.assertNotIn(8, by_id)
|
||||
self.assertEqual(by_id[1]["SamQuantity"], 60)
|
||||
|
||||
def test_principal_only_and_incremental_receipts(self):
|
||||
self.insert("GIAMAG", (4, 6, 10000))
|
||||
self.insert("MOVMAG", (1, 1, None, 4, 5, self.serial_cutoff - 1))
|
||||
row = self.run_query().rows[0]
|
||||
self.assertEqual(row["WMS"], 115)
|
||||
self.assertEqual(row["SAM"], 181)
|
||||
|
||||
def test_multiple_locations_never_double_sam(self):
|
||||
self.insert("MagazziniPallet", ("600001", 8004, "V", 1, datetime(2025, 12, 31)))
|
||||
row = self.run_query().rows[0]
|
||||
self.assertEqual(row["SAM"], 181)
|
||||
self.assertIsNone(row["WMS"])
|
||||
self.assertIn("locations", row["Issues"])
|
||||
|
||||
def test_assignment_tie_is_unknown(self):
|
||||
self.insert("EXTTACLOTSER", (9, "000000/000009", "600010/000009", datetime(2026, 1, 3)))
|
||||
row = self.run_query().rows[0]
|
||||
self.assertIn("history", row["Issues"])
|
||||
self.assertIsNone(row["Difference"])
|
||||
|
||||
def test_midnight_is_exclusive(self):
|
||||
self.insert("MOVMAG", (2, 2, 4, None, 7, self.serial_cutoff))
|
||||
row = self.run_query().rows[0]
|
||||
self.assertEqual(row["SAM"], 188)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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.",
|
||||
|
||||
@@ -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"],
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -12,10 +12,12 @@ 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",
|
||||
"barcode_client": "1.0.26",
|
||||
"barcode_repository": "1.0.13",
|
||||
"barcode_service": "1.0.24",
|
||||
"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",
|
||||
"busy_overlay": "1.0.0",
|
||||
"db_config": "1.0.0",
|
||||
"diagnostica": "1.0.4",
|
||||
@@ -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",
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user