Add per-order speed and material KPIs
This commit is contained in:
1 parent
211fb45d52
commit
f6ebd78a4a
15 files changed
+773
-30
No files matched your search
@@ -2,20 +2,40 @@
|
||||
|
||||
from collections import defaultdict
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
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.erp.gateway import OrderConfirmationGroup, OrderConfirmationRow
|
||||
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)
|
||||
@@ -37,6 +57,19 @@ class ProductionOrderSearchResult:
|
||||
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
|
||||
@@ -51,6 +84,9 @@ class ProductionOrderShift:
|
||||
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)
|
||||
@@ -64,8 +100,17 @@ class ProductionOrderService:
|
||||
"""Resolve workplace and site timezone before assigning confirmation timestamps."""
|
||||
|
||||
def __init__(self, gateway: ProductionOrderReader,
|
||||
machines: Mapping[str, ShiftReportMachineConfig]) -> None:
|
||||
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))
|
||||
@@ -145,7 +190,133 @@ class ProductionOrderService:
|
||||
))
|
||||
shift_models.sort(key=lambda item: (item.shift_start.astimezone(UTC),
|
||||
item.machine_name))
|
||||
return ProductionOrderDetail(order, place_models, tuple(shift_models))
|
||||
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:
|
||||
|
||||
Reference in new issue
Block a user