Add production order search and shift drill-down

This commit is contained in:
admin committed 2026-10-20 15:06:04 +02:00
1 parent 6e8eb6f50f
commit dcde029bc7
8 files changed
+742 -4

No files matched your search

@@ -0,0 +1,155 @@
"""Order-oriented view of positive ERP production confirmations."""
from collections import defaultdict
from collections.abc import Mapping
from dataclasses import dataclass
from datetime import UTC, date, datetime
from math import fsum
from typing import Literal, Protocol
from zoneinfo import ZoneInfo
from production_analytics.calculations.shift_report import shift_containing
from production_analytics.erp.gateway import OrderConfirmationGroup, OrderConfirmationRow
from production_analytics.service.shift_report_config import ShiftReportMachineConfig
class ProductionOrderReader(Protocol):
def search_orders(self, query: str, *, limit: int = 25) -> list[OrderConfirmationGroup]: ...
def get_order_confirmations(self, production_order: str) -> list[OrderConfirmationRow]: ...
@dataclass(frozen=True, slots=True)
class ProductionOrderPlacement:
workplace: str
machine_name: str | None
site: str | None
timezone: ZoneInfo | None
article_number: str | None
article_description: str | None
first_confirmation_local: datetime
last_confirmation_local: datetime
mapping_status: Literal["configured", "unknown", "ambiguous"]
@dataclass(frozen=True, slots=True)
class ProductionOrderSearchResult:
production_order: str
placements: tuple[ProductionOrderPlacement, ...]
@dataclass(frozen=True, slots=True)
class ProductionOrderShift:
production_order: str
machine_name: str
workplace: str
site: str
timezone: ZoneInfo
date: date
shift: Literal["early", "late", "night"]
shift_start: datetime
shift_end: datetime
first_confirmation: datetime
last_confirmation: datetime
produced_m2: float
@dataclass(frozen=True, slots=True)
class ProductionOrderDetail:
production_order: str
placements: tuple[ProductionOrderPlacement, ...]
shifts: tuple[ProductionOrderShift, ...]
class ProductionOrderService:
"""Resolve workplace and site timezone before assigning confirmation timestamps."""
def __init__(self, gateway: ProductionOrderReader,
machines: Mapping[str, ShiftReportMachineConfig]) -> None:
self.gateway = gateway
workplace_map = defaultdict(list)
for name, config in machines.items():
workplace_map[config.erp_workplace].append((name, config))
self._workplaces = dict(workplace_map)
def _machine(self, workplace: str):
matches = self._workplaces.get(workplace, ())
return matches[0] if len(matches) == 1 else None
def _placement(self, workplace: str, article_number: str | None,
article_description: str | None, first: datetime,
last: datetime) -> ProductionOrderPlacement:
resolved = self._machine(workplace)
status = ("ambiguous" if len(self._workplaces.get(workplace, ())) > 1 else "unknown")
return ProductionOrderPlacement(
workplace=workplace, machine_name=resolved[0] if resolved else None,
site=resolved[1].site if resolved else None,
timezone=resolved[1].timezone if resolved else None,
article_number=article_number, article_description=article_description,
first_confirmation_local=first, last_confirmation_local=last,
mapping_status="configured" if resolved else status,
)
def search(self, query: str, *, limit: int = 25) -> tuple[ProductionOrderSearchResult, ...]:
query = _order_input(query)
if type(limit) is not int or not 1 <= limit <= 100:
raise ValueError("limit must be between 1 and 100")
groups = self.gateway.search_orders(query, limit=limit)
by_order = defaultdict(list)
for group in groups:
by_order[group.production_order].append(self._placement(
group.workplace, group.article_number, group.article_description,
group.first_confirmation_local, group.last_confirmation_local))
orders = sorted(by_order, key=lambda order: (order != query, order))[:limit]
return tuple(ProductionOrderSearchResult(
order, tuple(sorted(by_order[order], key=lambda placement: (
placement.workplace, placement.article_number or "",
placement.article_description or "")))) for order in orders)
def detail(self, production_order: str) -> ProductionOrderDetail | None:
order = _order_input(production_order)
rows = self.gateway.get_order_confirmations(order)
if not rows:
return None
placements = defaultdict(list)
shifts = defaultdict(list)
for row in rows:
if row.production_order != order:
raise ValueError("ERP returned a different production order")
placements[(row.workplace, row.article_number,
row.article_description)].append(row)
resolved = self._machine(row.workplace)
if resolved is None:
continue
name, config = resolved
timestamp = row.timestamp_local.replace(tzinfo=config.timezone, fold=0)
day, shift, start, end = shift_containing(timestamp, config.timezone)
shifts[(name, day, shift, start, end)].append(row)
place_models = tuple(self._placement(workplace, article, description,
min(row.timestamp_local for row in grouped),
max(row.timestamp_local for row in grouped))
for (workplace, article, description), grouped in sorted(
placements.items(), key=lambda item: tuple(
value or "" for value in item[0])))
shift_models = []
for (name, day, shift, start, end), grouped in shifts.items():
config = self._machine(grouped[0].workplace)[1]
stamps = [row.timestamp_local.replace(tzinfo=config.timezone, fold=0)
for row in grouped]
shift_models.append(ProductionOrderShift(
production_order=order, machine_name=name, workplace=config.erp_workplace,
site=config.site, timezone=config.timezone, date=day, shift=shift,
shift_start=start, shift_end=end,
first_confirmation=min(stamps, key=lambda value: value.astimezone(UTC)),
last_confirmation=max(stamps, key=lambda value: value.astimezone(UTC)),
produced_m2=fsum(row.feedback_quantity_m2 for row in grouped),
))
shift_models.sort(key=lambda item: (item.shift_start.astimezone(UTC),
item.machine_name))
return ProductionOrderDetail(order, place_models, tuple(shift_models))
def _order_input(value: str) -> str:
if (not isinstance(value, str) or not value.strip() or "\x00" in value
or len(value.strip()) > 80):
raise ValueError("production order must be 1–80 non-NUL characters")
return value.strip()