Add per-order speed and material KPIs

This commit is contained in:
admin committed 2026-10-20 16:07:57 +02:00
1 parent 211fb45d52
commit f6ebd78a4a
15 files changed
+773 -30

No files matched your search

@@ -18,6 +18,8 @@ class ShiftProductionItem:
roll_count: int
first_confirmation_at: datetime
last_confirmation_at: datetime
average_speed_m_min: float | None = None
material_consumption_kg: float | None = None
@dataclass(frozen=True, slots=True)
@@ -7,6 +7,7 @@ from production_analytics.presentation.mode_navigation import (
MODE_NAV_CSS,
render_mode_navigation,
)
from production_analytics.presentation.shift_report import _number
from production_analytics.service.production_order import (
ProductionOrderDetail,
ProductionOrderSearchResult,
@@ -83,7 +84,8 @@ def render_detail(*, detail: ProductionOrderDetail | None,
return _page("Fertigungsauftrag", "<p>Fertigungsauftrag nicht gefunden.</p>")
body = f"<h1>Fertigungsauftrag {escape(detail.production_order)}</h1>"
body += '<p class="metadata">Zeiten sind ERP-Rückmeldezeitpunkte, keine durchgehenden '
body += 'Maschinenlaufzeiten. Mengen sind positive Rückmeldemengen in m².</p>'
body += 'Maschinenlaufzeiten. Mengen sind positive Rückmeldemengen in m². '
body += 'Geschwindigkeit und Material beziehen sich auf angenäherte FA-Zeitfenster.</p>'
body += '<h2>Artikel und Arbeitsplätze</h2><div class="table-scroll"><table><thead><tr>'
body += '<th>Artikel</th><th>Artikelbezeichnung</th><th>Arbeitsplatz / Maschine</th>'
body += '<th>Erste Rückmeldung</th><th>Letzte Rückmeldung</th></tr></thead><tbody>'
@@ -101,6 +103,7 @@ def render_detail(*, detail: ProductionOrderDetail | None,
else:
body += '<div class="table-scroll"><table><thead><tr><th>Standort</th><th>Maschine</th>'
body += '<th>Datum</th><th>Schicht</th><th>Produzierte Menge</th>'
body += '<th>Ø Geschwindigkeit</th><th>Materialverbrauch</th>'
body += '<th>Erste Rückmeldung</th><th>Letzte Rückmeldung</th><th>Bericht</th>'
body += '</tr></thead><tbody>'
for item in detail.shifts:
@@ -110,6 +113,10 @@ def render_detail(*, detail: ProductionOrderDetail | None,
escape(item.site.title()), escape(item.machine_name),
item.date.strftime("%d.%m.%Y"),
SHIFT_LABELS[item.shift], f"{item.produced_m2:,.2f} m²",
(f"{_number(item.average_speed_m_min)} m/min"
if item.average_speed_m_min is not None else "—"),
(f"{_number(item.material_consumption_kg)} kg"
if item.material_consumption_kg is not None else "—"),
escape(item.first_confirmation.strftime("%d.%m.%Y %H:%M %Z")),
escape(item.last_confirmation.strftime("%d.%m.%Y %H:%M %Z")),
f'<a href="{escape(href, quote=True)}">Schichtbericht</a>',
@@ -63,7 +63,8 @@ def present_report(
text("Für diese Maschine nicht verfügbar.")
elif report.production.items:
table(
("Produktionsauftrag", "Artikelnummer", "Artikelbeschreibung", "Menge", "Rollen"),
("Produktionsauftrag", "Artikelnummer", "Artikelbeschreibung", "Menge", "Rollen",
"Ø Geschwindigkeit", "Materialverbrauch"),
[
(
item.production_order,
@@ -71,10 +72,14 @@ def present_report(
item.article_description or "Nicht verfügbar",
f"{_number(item.produced_m2)} m²",
str(item.roll_count),
(f"{_number(item.average_speed_m_min)} m/min"
if item.average_speed_m_min is not None else "—"),
(f"{_number(item.material_consumption_kg)} kg"
if item.material_consumption_kg is not None else "—"),
)
for item in report.production.items
],
[36, 30, 62, 30, 20],
[28, 22, 44, 23, 13, 23, 25],
)
elif report.production is not None:
text("Keine Produktionsdaten vorhanden.")
@@ -2,6 +2,7 @@
from html import escape
from math import fsum
from urllib.parse import urlencode
from production_analytics.presentation.mode_navigation import (
MODE_NAV_CSS,
@@ -93,8 +94,19 @@ def render_page(*, machines, labels, day, shift, machine, report, generated_at,
body += '<div class="table-scroll"><table><thead><tr>'
body += "".join(f'<th scope="col">{escape(cell)}</th>' for cell in block.headers)
body += "</tr></thead><tbody>"
production_table = block.headers[:2] == ("Produktionsauftrag", "Artikelnummer")
for row in block.rows:
body += "<tr>" + "".join(f"<td>{escape(cell)}</td>" for cell in row) + "</tr>"
cells = []
for index, cell in enumerate(row):
if production_table and index == 0:
href = "/order?" + urlencode({"production_order": cell})
cells.append(
f'<td><a class="fa-link" href="{escape(href, quote=True)}">'
f"{escape(cell)}</a></td>"
)
else:
cells.append(f"<td>{escape(cell)}</td>")
body += "<tr>" + "".join(cells) + "</tr>"
body += "</tbody></table></div>"
elif isinstance(block, MaterialPieBlock):
body += "</div>" + _material_chart(block)
@@ -113,6 +125,8 @@ input,select,button {{font:inherit; padding:.55rem}} button {{cursor:pointer}}
table {{width:100%; border-collapse:collapse}} th,td {{text-align:left; padding:.7rem;
border-bottom:1px solid #c9d1d8}} th {{background:#e8eef3}}
.table-scroll {{overflow-x:auto}} .metadata {{color:#526473; font-size:.9rem}}
.fa-link {{color:#17547a; font-weight:600; text-decoration:underline;
text-underline-offset:2px}} .fa-link:hover,.fa-link:focus-visible {{color:#0b3653}}
.material-layout {{display:grid; grid-template-columns:minmax(0, 1fr) 300px; gap:1.5rem}}
.material-chart {{margin:0; min-width:0}} .material-chart svg {{display:block;
width:220px; max-width:100%; margin:.75rem auto}}
@@ -1,7 +1,9 @@
"""Explicit K7 order adapter; generic measured material calculation stays ERP-free."""
import re
from collections import defaultdict
from dataclasses import replace
from math import fsum
from typing import Protocol
from production_analytics.calculations.fiber_allocation import (
@@ -33,3 +35,12 @@ class K7FiberAllocationService:
items.extend(allocate_fiber_materials(item, bookings[order], erp_order=order))
# Keep the measured shift total, rather than replacing it with an ERP total.
return replace(measured, items=tuple(items))
def totals_by_order(self, allocated: ShiftMaterialSummary) -> dict[str, float]:
"""Sum the same allocated items shown in the shift material table by ERP FA."""
quantities = defaultdict(list)
for item in allocated.items:
match = re.fullmatch(r"(?:K 7-)?([0-9]+)", item.production_order.strip())
if match is not None:
quantities[match[1]].append(item.consumption_kg)
return {order: fsum(values) for order, values in quantities.items()}
@@ -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:
@@ -1,6 +1,7 @@
"""Sequential composition of validated services; mandatory failures propagate."""
from collections.abc import Mapping
from dataclasses import replace
from datetime import datetime
from types import MappingProxyType
from typing import Protocol
@@ -8,6 +9,7 @@ from typing import Protocol
from production_analytics.calculations.shift_material import ShiftMaterialSummary
from production_analytics.calculations.shift_report import ShiftReport
from production_analytics.calculations.shift_speed import validate_speed_window
from production_analytics.service.production_order import ProductionOrderService
from production_analytics.service.shift_downtime import ShiftDowntimeService
from production_analytics.service.shift_material import (
ShiftChannelMaterialService,
@@ -33,6 +35,7 @@ class ShiftReportService:
channel_materials: ShiftChannelMaterialService,
speed: ShiftSpeedService,
material_allocators: Mapping[str, ShiftMaterialAllocator] | None = None,
order_kpis: ProductionOrderService | None = None,
) -> None:
self.machines = MappingProxyType(dict(machines))
self.production = production
@@ -41,6 +44,7 @@ class ShiftReportService:
self.channel_materials = channel_materials
self.speed = speed
self.material_allocators = MappingProxyType(dict(material_allocators or {}))
self.order_kpis = order_kpis
def build(self, *, machine_name: str, start: datetime, end: datetime) -> ShiftReport:
validate_speed_window(start, end)
@@ -71,6 +75,20 @@ class ShiftReportService:
materials = self.material_allocators[machine_name].allocate(materials)
speed = (self.speed.summarize(config=config.speed, start=start, end=end)
if config.speed is not None else None)
if (production is not None and production.items and self.order_kpis is not None
and (config.speed is not None or config.material is not None)):
kpis = self.order_kpis.for_shift(
machine_name=machine_name, start=start, end=end,
orders=tuple(item.production_order for item in production.items),
allocated_shift_materials=(materials if machine_name in self.material_allocators
else None),
)
production = replace(production, items=tuple(
replace(item,
average_speed_m_min=kpis[item.production_order].average_speed_m_min,
material_consumption_kg=kpis[item.production_order].material_consumption_kg)
for item in production.items
))
return ShiftReport(
machine_name=machine_name,
machine_id=config.machine_id,
@@ -16,6 +16,7 @@ from production_analytics.service.postgres_shift_material import (
PostgresShiftChannelMaterialRepository,
PostgresShiftMaterialRepository,
)
from production_analytics.service.production_order import ProductionOrderService
from production_analytics.service.shift_downtime import ShiftDowntimeService
from production_analytics.service.shift_material import (
ShiftChannelMaterialService,
@@ -39,14 +40,21 @@ def build_shift_report_service(
for name, config in machines.items()
if config.material is not None and config.material.allocation == "erp_fiber_share"
}
confirmation_gateway = ErpProductionConfirmationGateway(erp)
materials = ShiftMaterialService(PostgresShiftMaterialRepository(postgres))
channel_materials = ShiftChannelMaterialService(
PostgresShiftChannelMaterialRepository(postgres))
speed = ShiftSpeedService(EnlyzeApiGateway(ExplorationClient(enlyze)))
order_kpis = ProductionOrderService(
confirmation_gateway, machines, speed=speed, materials=materials,
channel_materials=channel_materials, material_allocators=allocators)
return ShiftReportService(
machines=machines,
material_allocators=allocators,
production=ShiftProductionService(ErpProductionConfirmationGateway(erp)),
order_kpis=order_kpis,
production=ShiftProductionService(confirmation_gateway),
downtime=ShiftDowntimeService(PostgresDowntimeRepository(postgres)),
materials=ShiftMaterialService(PostgresShiftMaterialRepository(postgres)),
channel_materials=ShiftChannelMaterialService(
PostgresShiftChannelMaterialRepository(postgres)
),
speed=ShiftSpeedService(EnlyzeApiGateway(ExplorationClient(enlyze))),
materials=materials,
channel_materials=channel_materials,
speed=speed,
)
+5 -6
View File
@@ -176,12 +176,11 @@ def main(argv=None):
return build_shift_report_service(machines, environment)
def order_service():
from production_analytics.erp import ErpProductionConfirmationGateway, ErpSettings
from production_analytics.service.production_order import ProductionOrderService
environment = {**os.environ, **load_secret_file(args.erp_secrets_file)}
gateway = ErpProductionConfirmationGateway(ErpSettings.from_environment(environment))
return ProductionOrderService(gateway, machines)
environment = dict(os.environ)
for path in (args.secrets_file, args.erp_secrets_file, args.db_secrets_file):
environment.update(load_secret_file(path))
sources = build_shift_report_service(machines, environment)
return sources.order_kpis
app = create_app(machines, service, sites=config.sites,
order_service_factory=order_service)