"""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()