Implementa picking bilista 2.1.0 con test, patch SQL e rollback
This commit is contained in:
116
pickinglist_pair_repository.py
Normal file
116
pickinglist_pair_repository.py
Normal file
@@ -0,0 +1,116 @@
|
||||
"""SQL access for paired reservations, isolated from legacy movement rules."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from barcode_repository import _rows_to_dicts
|
||||
from pickinglist_pair import PickingCandidate, PairRoute, build_pair_route
|
||||
from version_info import module_version
|
||||
|
||||
__version__ = module_version(__name__)
|
||||
|
||||
PAIR_LOCK_SQL = """
|
||||
DECLARE @PairLock int;
|
||||
EXEC @PairLock=sys.sp_getapplock @Resource='py_PickingPair',
|
||||
@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000;
|
||||
IF @PairLock<0 THROW 51101, 'Prenotazione occupata. Riprovare.', 1;
|
||||
"""
|
||||
|
||||
PAIR_COMMAND_SQL = """
|
||||
EXEC dbo.py_sp_PickingPair @Action=:action, @IDOperatore=:operator,
|
||||
@Documento1=:document1, @Documento2=:document2, @RunId=:run_id,
|
||||
@Documento=:document, @Pallet=:pallet;
|
||||
"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PairSnapshot:
|
||||
run_id: str
|
||||
documents: tuple[str, str]
|
||||
active: frozenset[str]
|
||||
rows: tuple[dict[str, Any], ...]
|
||||
|
||||
def route(self) -> PairRoute:
|
||||
candidates = []
|
||||
skipped = set()
|
||||
sequence = {}
|
||||
for row in self.rows:
|
||||
if row.get("SequenceOrder") is not None:
|
||||
sequence[str(row["GroupKey"])] = int(row["SequenceOrder"])
|
||||
document = str(row["SlotDocument"])
|
||||
if document not in self.active or row.get("Pallet") is None:
|
||||
continue
|
||||
if str(row["StatoDocumento"]).strip() != "P":
|
||||
raise ValueError(f"PL {document}: stato ERP cambiato. Verificare la lista.")
|
||||
pallet = str(row["Pallet"]).strip()
|
||||
candidates.append(PickingCandidate(document, pallet, int(row["Cella"]),
|
||||
int(row["OperationalArea"]) if row.get("OperationalArea") is not None else None,
|
||||
int(row["Ordinamento"]), str(row["GroupKey"])))
|
||||
if row["IsSkipped"]:
|
||||
skipped.add((document, pallet))
|
||||
return build_pair_route(candidates, documents=self.documents,
|
||||
document_sequences={self.documents[0]: sorted(sequence, key=sequence.get)}, skipped=skipped)
|
||||
|
||||
def display_row(self, document: str, pallet: str) -> dict:
|
||||
return next(row for row in self.rows
|
||||
if str(row["SlotDocument"]) == document and str(row.get("Pallet", "")).strip() == pallet)
|
||||
|
||||
|
||||
class PickingPairRepository:
|
||||
def __init__(self, db_client):
|
||||
self.db_client = db_client
|
||||
|
||||
async def snapshot(self) -> PairSnapshot | None:
|
||||
result = await self.db_client.query_json("SELECT * FROM dbo.py_ViewPickingPairRows;")
|
||||
rows = _rows_to_dicts(result)
|
||||
if not rows:
|
||||
return None
|
||||
head = rows[0]
|
||||
documents = (str(head["Documento1"]), str(head["Documento2"]))
|
||||
active = frozenset(d for d, yes in zip(documents, (head["Active1"], head["Active2"])) if yes)
|
||||
return PairSnapshot(str(head["RunId"]), documents, active, tuple(rows))
|
||||
|
||||
async def command(self, action: str, operator: int, *, documents=(None, None),
|
||||
run_id=None, document=None, pallet=None) -> None:
|
||||
await self.db_client.query_json(PAIR_COMMAND_SQL, {
|
||||
"action": action, "operator": operator, "document1": documents[0],
|
||||
"document2": documents[1], "run_id": run_id, "document": document,
|
||||
"pallet": pallet,
|
||||
}, commit=True)
|
||||
|
||||
async def reserve_single(self, document: str, operator: int) -> None:
|
||||
# Hold the same lock as pair reservation until this transaction commits.
|
||||
sql = "SET NOCOUNT ON; SET XACT_ABORT ON;\n" + PAIR_LOCK_SQL + """
|
||||
IF EXISTS(SELECT 1 FROM dbo.py_PickingPair WHERE IsOpen=1)
|
||||
THROW 51104, 'Sprenotare il giro bilista prima di cambiarlo.', 1;
|
||||
DECLARE @RC int=0;
|
||||
EXEC dbo.py_sp_xExePackingListPallet @IDOperatore=:operator,
|
||||
@Documento=:document,@Azione='P',@RC=@RC OUTPUT;
|
||||
IF @RC<>0 THROW 51109, 'Prenotazione non completata.', 1;
|
||||
UPDATE dbo.py_BarcodePickingListSkip SET Risolto=1
|
||||
WHERE Documento=:document AND Risolto=0;
|
||||
SELECT @RC AS RC;
|
||||
"""
|
||||
await self.db_client.query_json(sql, {"operator": operator, "document": document}, commit=True)
|
||||
|
||||
async def release_selected(self, documents: list[str], operator: int) -> None:
|
||||
# One transaction for the whole desktop selection, no partial release.
|
||||
sql = "SET NOCOUNT ON; SET XACT_ABORT ON;\n" + PAIR_LOCK_SQL
|
||||
params = {"operator": operator}
|
||||
for index, doc in enumerate(documents):
|
||||
params[f"doc{index}"] = doc
|
||||
sql += f"""
|
||||
DECLARE @Run{index} uniqueidentifier=(SELECT RunId FROM dbo.py_PickingPair
|
||||
WHERE IsOpen=1 AND (Documento1=:doc{index} OR Documento2=:doc{index}));
|
||||
IF @Run{index} IS NOT NULL
|
||||
EXEC dbo.py_sp_PickingPair @Action='U',@IDOperatore=:operator,
|
||||
@RunId=@Run{index},@Documento=:doc{index},@Silent=1;
|
||||
ELSE
|
||||
BEGIN
|
||||
DECLARE @RC{index} int=0;
|
||||
EXEC dbo.py_sp_xExePackingListPallet @IDOperatore=:operator,
|
||||
@Documento=:doc{index},@Azione='S',@RC=@RC{index} OUTPUT;
|
||||
IF @RC{index}<>0 THROW 51109, 'Sprenotazione non completata.', 1;
|
||||
END;
|
||||
"""
|
||||
await self.db_client.query_json(sql + "\nSELECT 0 AS RC;", params, commit=True)
|
||||
Reference in New Issue
Block a user