327 lines
15 KiB
Python
327 lines
15 KiB
Python
"""Order-oriented view of positive ERP production confirmations."""
|
||
|
||
from collections import defaultdict
|
||
from collections.abc import Mapping
|
||
from dataclasses import dataclass, replace
|
||
from datetime import UTC, date, datetime
|
||
from math import fsum
|
||
from typing import Literal, Protocol
|
||
from zoneinfo import ZoneInfo
|
||
|
||
from production_analytics.calculations.shift_material import ShiftMaterialSummary
|
||
from production_analytics.calculations.shift_report import shift_containing
|
||
from production_analytics.enlyze.exploration import ExplorationError
|
||
from production_analytics.erp.gateway import (
|
||
ErpReadError,
|
||
OrderConfirmationGroup,
|
||
OrderConfirmationRow,
|
||
ProductionConfirmation,
|
||
)
|
||
from production_analytics.service.postgres_shift_material import ShiftMaterialReadError
|
||
from production_analytics.service.shift_material import (
|
||
ShiftChannelMaterialService,
|
||
ShiftMaterialService,
|
||
)
|
||
from production_analytics.service.shift_report_config import ShiftReportMachineConfig
|
||
from production_analytics.service.shift_speed import ShiftSpeedService
|
||
|
||
|
||
class ProductionOrderReader(Protocol):
|
||
def search_orders(self, query: str, *, limit: int = 25) -> list[OrderConfirmationGroup]: ...
|
||
def get_order_confirmations(self, production_order: str) -> list[OrderConfirmationRow]: ...
|
||
def get_confirmations(self, *, workplace: str, start: datetime, end: datetime,
|
||
timezone: ZoneInfo) -> list[ProductionConfirmation]: ...
|
||
|
||
|
||
class MaterialAllocator(Protocol):
|
||
def allocate(self, measured: ShiftMaterialSummary) -> ShiftMaterialSummary: ...
|
||
def totals_by_order(self, allocated: ShiftMaterialSummary) -> dict[str, float]: ...
|
||
|
||
|
||
@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 ProductionOrderSegment:
|
||
start: datetime
|
||
end: datetime
|
||
|
||
|
||
@dataclass(frozen=True, slots=True)
|
||
class ProductionOrderShiftKpi:
|
||
segments: tuple[ProductionOrderSegment, ...]
|
||
average_speed_m_min: float | None
|
||
material_consumption_kg: float | None
|
||
|
||
|
||
@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
|
||
segments: tuple[ProductionOrderSegment, ...] = ()
|
||
average_speed_m_min: float | None = None
|
||
material_consumption_kg: float | None = None
|
||
|
||
|
||
@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], *,
|
||
speed: ShiftSpeedService | None = None,
|
||
materials: ShiftMaterialService | None = None,
|
||
channel_materials: ShiftChannelMaterialService | None = None,
|
||
material_allocators: Mapping[str, MaterialAllocator] | None = None) -> None:
|
||
self.gateway = gateway
|
||
self.speed = speed
|
||
self.materials = materials
|
||
self.channel_materials = channel_materials
|
||
self.material_allocators = dict(material_allocators or {})
|
||
self.machines = dict(machines)
|
||
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))
|
||
enriched = []
|
||
for item in shift_models:
|
||
kpi = self.for_shift(machine_name=item.machine_name, start=item.shift_start,
|
||
end=item.shift_end, orders=(item.production_order,))[
|
||
item.production_order]
|
||
enriched.append(replace(item, segments=kpi.segments,
|
||
average_speed_m_min=kpi.average_speed_m_min,
|
||
material_consumption_kg=kpi.material_consumption_kg))
|
||
return ProductionOrderDetail(order, place_models, tuple(enriched))
|
||
|
||
def for_shift(self, *, machine_name: str, start: datetime, end: datetime,
|
||
orders: tuple[str, ...],
|
||
allocated_shift_materials: ShiftMaterialSummary | None = None,
|
||
) -> dict[str, ProductionOrderShiftKpi]:
|
||
"""Attribute one machine shift to all requested FAs with shared segmentation."""
|
||
if machine_name not in self.machines:
|
||
raise ValueError("Unknown machine")
|
||
if not orders:
|
||
return {}
|
||
config = self.machines[machine_name]
|
||
confirmations = self.gateway.get_confirmations(
|
||
workplace=config.erp_workplace, start=start, end=end, timezone=config.timezone)
|
||
by_order = _segments_by_order(
|
||
confirmations, workplace=config.erp_workplace, timezone=config.timezone,
|
||
start=start, end=end)
|
||
allocator = self.material_allocators.get(machine_name)
|
||
allocated_totals = None
|
||
if allocator is not None and config.material is not None:
|
||
try:
|
||
if allocated_shift_materials is None:
|
||
service = (self.channel_materials if config.material.mode == "channel"
|
||
else self.materials)
|
||
if service is not None:
|
||
measured = service.summarize(
|
||
machine_id=config.machine_id,
|
||
calculation_ids=config.material.calculation_ids,
|
||
start=start, end=end,
|
||
)
|
||
allocated_shift_materials = allocator.allocate(measured)
|
||
if allocated_shift_materials is not None:
|
||
allocated_totals = allocator.totals_by_order(allocated_shift_materials)
|
||
except (ShiftMaterialReadError, ErpReadError):
|
||
allocated_totals = None
|
||
result = {}
|
||
for order in dict.fromkeys(orders):
|
||
segments = by_order.get(order, ())
|
||
if allocator is not None:
|
||
material = allocated_totals.get(order) if allocated_totals is not None else None
|
||
elif segments:
|
||
material = self._material_for_segments(config, segments)
|
||
else:
|
||
material = None
|
||
result[order] = ProductionOrderShiftKpi(
|
||
segments=segments,
|
||
average_speed_m_min=self._speed_for_segments(config, segments) if segments
|
||
else None,
|
||
material_consumption_kg=material,
|
||
)
|
||
return result
|
||
|
||
def _speed_for_segments(self, config: ShiftReportMachineConfig,
|
||
segments: tuple[ProductionOrderSegment, ...]) -> float | None:
|
||
if config.speed is None or self.speed is None:
|
||
return None
|
||
try:
|
||
summaries = [self.speed.summarize(config=config.speed, start=part.start,
|
||
end=part.end) for part in segments]
|
||
except ExplorationError:
|
||
return None
|
||
count = sum(summary.active_sample_count for summary in summaries)
|
||
if count == 0:
|
||
return None
|
||
return fsum(summary.average_line_speed_m_min * (summary.active_sample_count / count)
|
||
for summary in summaries if summary.active_sample_count)
|
||
|
||
def _material_for_segments(self, config: ShiftReportMachineConfig,
|
||
segments: tuple[ProductionOrderSegment, ...]) -> float | None:
|
||
if config.material is None:
|
||
return None
|
||
service = (self.channel_materials if config.material.mode == "channel"
|
||
else self.materials)
|
||
if service is None:
|
||
return None
|
||
try:
|
||
measured = [service.summarize(
|
||
machine_id=config.machine_id,
|
||
calculation_ids=config.material.calculation_ids,
|
||
start=part.start, end=part.end,
|
||
) for part in segments]
|
||
except (ShiftMaterialReadError, ErpReadError):
|
||
return None
|
||
return fsum(summary.total_consumption_kg for summary in measured)
|
||
|
||
|
||
def _segments_by_order(
|
||
confirmations: list[ProductionConfirmation], *, workplace: str, timezone: ZoneInfo,
|
||
start: datetime, end: datetime,
|
||
) -> dict[str, tuple[ProductionOrderSegment, ...]]:
|
||
"""Partition one shift at midpoints between adjacent FA confirmation runs."""
|
||
first = start.astimezone(UTC)
|
||
last = end.astimezone(UTC)
|
||
ordered = sorted(
|
||
((row.timestamp.astimezone(UTC), row.production_order) for row in confirmations
|
||
if row.workplace == workplace and row.is_finished_goods
|
||
and first <= row.timestamp.astimezone(UTC) < last),
|
||
key=lambda entry: (entry[0], entry[1]),
|
||
)
|
||
if not ordered:
|
||
return {}
|
||
runs = []
|
||
for stamp, order in ordered:
|
||
if not runs or runs[-1][0] != order:
|
||
runs.append([order, stamp, stamp])
|
||
else:
|
||
runs[-1][2] = stamp
|
||
boundaries = [first]
|
||
for before, after in zip(runs, runs[1:]):
|
||
midpoint = before[2] + (after[1] - before[2]) / 2
|
||
boundaries.append(max(first, min(midpoint, last)))
|
||
boundaries.append(last)
|
||
by_order = defaultdict(list)
|
||
for index, run in enumerate(runs):
|
||
if boundaries[index] < boundaries[index + 1]:
|
||
by_order[run[0]].append(ProductionOrderSegment(
|
||
boundaries[index].astimezone(timezone),
|
||
boundaries[index + 1].astimezone(timezone)))
|
||
return {order: tuple(segments) for order, segments in by_order.items()}
|
||
|
||
|
||
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()
|