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

+380
View File
@@ -0,0 +1,380 @@
"""Approximate FA windows feed existing speed and material services."""
from dataclasses import replace
from datetime import datetime
from math import fsum
from types import SimpleNamespace
import pytest
from test_production_order import BERLIN, MACHINES, FakeGateway, row
from test_shift_report import composition
from production_analytics.calculations.fiber_allocation import FiberBooking
from production_analytics.calculations.shift_material import (
ShiftMaterialItem,
ShiftMaterialSnapshot,
ShiftMaterialSummary,
)
from production_analytics.enlyze.exploration import ExplorationError
from production_analytics.presentation.production_order_html import render_detail
from production_analytics.presentation.shift_report import TableBlock, present_report
from production_analytics.service.fiber_allocation import K7FiberAllocationService
from production_analytics.service.postgres_shift_material import ShiftMaterialReadError
from production_analytics.service.production_order import ProductionOrderService
from production_analytics.service.shift_material import ShiftMaterialService
A, B, C = "FA-A", "FA-B", "FA-C"
class Speed:
def __init__(self, count=2, error=None):
self.calls = []
self.count = count
self.error = error
def summarize(self, *, config, start, end):
self.calls.append((config, start, end))
if self.error:
raise self.error
speed = float(start.hour + 1) if self.count else None
return SimpleNamespace(average_line_speed_m_min=speed,
active_sample_count=self.count)
class Material:
def __init__(self, value=0, error=None):
self.calls = []
self.value = value
self.error = error
def summarize(self, *, machine_id, calculation_ids, start, end):
self.calls.append((machine_id, calculation_ids, start, end))
if self.error:
raise self.error
value = self.value(start, end) if callable(self.value) else self.value
return SimpleNamespace(total_consumption_kg=value, items=())
def service(selected, all_rows, *, speed=None, materials=None, machines=MACHINES):
return ProductionOrderService(FakeGateway(rows=selected, shift_rows=all_rows), machines,
speed=speed, materials=materials)
def b1(hour, minute=0, *, order=A, day=19, amount=10):
return row(hour, minute, workplace="BENTO 1", order=order, day=day, amount=amount)
def windows(detail):
return [(part.start, part.end) for shift in detail.shifts for part in shift.segments]
def test_one_fa_occupies_full_shift_and_sources_receive_segment_window():
speed, material = Speed(), Material(12)
detail = service([b1(9)], [b1(9)], speed=speed, materials=material).detail(A)
shift = detail.shifts[0]
assert windows(detail) == [(datetime(2026, 10, 19, 6, tzinfo=BERLIN),
datetime(2026, 10, 19, 14, tzinfo=BERLIN))]
assert speed.calls[0][1:] == windows(detail)[0]
assert material.calls[0][2:] == windows(detail)[0]
assert (shift.average_speed_m_min, shift.material_consumption_kg) == (7, 12)
def test_two_fas_have_distinct_nonoverlapping_windows_and_kpis():
a, b = b1(7, order=A), b1(11, order=B)
speed, material = Speed(), Material(lambda start, end: 5 if start.hour == 6 else 12)
service_a = service([a], [a, b], speed=speed, materials=material)
service_b = service([b], [a, b], speed=speed, materials=material)
first, second = service_a.detail(A).shifts[0], service_b.detail(B).shifts[0]
assert first.segments[0].start.hour == 6
assert first.segments[0].end.hour == 9
assert second.segments[0].start == first.segments[0].end
assert second.segments[0].end.hour == 14
assert (first.average_speed_m_min, second.average_speed_m_min) == (7, 10)
assert (first.material_consumption_kg, second.material_consumption_kg) == (5, 12)
assert speed.calls[0][1:] == (first.segments[0].start, first.segments[0].end)
assert material.calls[1][2:] == (second.segments[0].start, second.segments[0].end)
def test_shift_report_and_order_detail_use_same_kpi_attribution():
a, b = b1(7, order=A), b1(11, order=B)
speed, material = Speed(), Material(lambda start, end: 5 if start.hour == 6 else 12)
order_service = service([a], [a, b], speed=speed, materials=material)
start = datetime(2026, 10, 19, 6, tzinfo=BERLIN)
end = datetime(2026, 10, 19, 14, tzinfo=BERLIN)
shift_kpis = order_service.for_shift(machine_name="B1", start=start, end=end,
orders=(A, B))
detail = order_service.detail(A).shifts[0]
assert shift_kpis[A].segments == detail.segments
assert shift_kpis[A].average_speed_m_min == detail.average_speed_m_min
assert shift_kpis[A].material_consumption_kg == detail.material_consumption_kg
assert shift_kpis[B].segments[0].start == shift_kpis[A].segments[0].end
assert shift_kpis[A].material_consumption_kg + shift_kpis[B].material_consumption_kg == 17
def test_three_sequential_fas_and_midpoints_are_clamped():
a, b, c = b1(6, order=A), b1(9, order=B), b1(13, order=C)
details = [service([selected], [a, b, c]).detail(selected.production_order)
for selected in (a, b, c)]
segments = [detail.shifts[0].segments[0] for detail in details]
assert [part.start.strftime("%H:%M") for part in segments] == ["06:00", "07:30", "11:00"]
assert [part.end.strftime("%H:%M") for part in segments] == ["07:30", "11:00", "14:00"]
assert all(left.end == right.start for left, right in zip(segments, segments[1:]))
def test_repeated_adjacent_fa_rows_keep_one_segment_and_sum_production():
a1, a2, b = b1(7, order=A, amount=3), b1(8, order=A, amount=4), b1(10, order=B)
detail = service([a1, a2], [a1, a2, b]).detail(A)
assert len(detail.shifts) == len(detail.shifts[0].segments) == 1
assert detail.shifts[0].produced_m2 == 7
assert detail.shifts[0].segments[0].end.hour == 9
def test_alternating_fa_confirmation_runs_remain_two_disjoint_segments():
a1, b, a2 = b1(7, order=A), b1(9, order=B), b1(11, order=A)
speed, material = Speed(), Material(4)
detail = service([a1, a2], [a1, b, a2], speed=speed, materials=material).detail(A)
parts = detail.shifts[0].segments
assert len(parts) == 2
assert parts[0].end.hour == 8 and parts[1].start.hour == 10
assert parts[0].end < parts[1].start
assert len(speed.calls) == len(material.calls) == 2
assert detail.shifts[0].material_consumption_kg == 8
assert detail.shifts[0].average_speed_m_min == 9
def test_simultaneous_three_fa_tie_gives_middle_order_unavailable_kpis():
a, b, c = (b1(9, order=order) for order in (A, B, C))
speed, material = Speed(), Material(4)
shift = service([b], [a, b, c], speed=speed, materials=material).detail(B).shifts[0]
assert shift.produced_m2 == 10
assert shift.segments == ()
assert shift.average_speed_m_min is shift.material_consumption_kg is None
assert speed.calls == material.calls == []
def test_cross_shift_and_night_keep_separate_kpis():
first = b1(21, order=A)
second = b1(1, order=A, day=20)
speed, material = Speed(), Material(3)
detail = service([first, second], [first, second], speed=speed, materials=material).detail(A)
assert [(item.date.day, item.shift) for item in detail.shifts] == [
(19, "late"), (19, "night")]
assert detail.shifts[0].segments[0].end.hour == 22
assert detail.shifts[1].segments[0].start.hour == 22
assert detail.shifts[1].segments[0].end == datetime(2026, 10, 20, 6, tzinfo=BERLIN)
assert [item.material_consumption_kg for item in detail.shifts] == [3, 3]
assert len(speed.calls) == len(material.calls) == 2
def test_disabled_capabilities_never_query_optional_sources():
k1 = row(7, 0, workplace="K1", order=A)
speed, material = Speed(), Material(10)
shift = service([k1], [k1], speed=speed, materials=material).detail(A).shifts[0]
assert shift.average_speed_m_min is shift.material_consumption_kg is None
assert speed.calls == material.calls == []
gitter = row(7, 0, workplace="GITTERIII", order=A)
service([gitter], [gitter], speed=speed, materials=material).detail(A)
assert len(speed.calls) == 1 and material.calls == []
@pytest.mark.parametrize("workplace,machine", [("GITTERIII", "Gitter 3"), ("K5", "K5")])
def test_machine_speed_gate_configuration_is_forwarded_unchanged(workplace, machine):
confirmation = row(7, 0, workplace=workplace, order=A)
speed = Speed()
shift = service([confirmation], [confirmation], speed=speed).detail(A).shifts[0]
assert speed.calls[0][0] is MACHINES[machine].speed
assert shift.average_speed_m_min == 7
def test_channel_material_uses_existing_channel_path():
e1 = row(7, 0, workplace="1568705", order=A)
cumulative, channel = Material(99), Material(6)
order_service = ProductionOrderService(
FakeGateway(rows=[e1]), MACHINES, materials=cumulative,
channel_materials=channel)
shift = order_service.detail(A).shifts[0]
assert shift.material_consumption_kg == 6
assert cumulative.calls == [] and len(channel.calls) == 1
def test_order_aware_allocator_uses_full_shift_summary():
k7 = row(7, 0, workplace="K7", order=A)
material = Material(9)
class Allocator:
def __init__(self):
self.calls = []
def allocate(self, measured):
self.calls.append(measured)
return measured
def totals_by_order(self, allocated):
return {A: allocated.total_consumption_kg}
allocator = Allocator()
order_service = ProductionOrderService(
FakeGateway(rows=[k7]), MACHINES, materials=material,
material_allocators={"K7": allocator})
shift = order_service.detail(A).shifts[0]
assert shift.material_consumption_kg == 9
assert len(allocator.calls) == 1
assert material.calls[0][2:] == (shift.shift_start, shift.shift_end)
def test_k7_compact_material_matches_allocated_shift_items_not_time_segments():
first_order, second_order = "12026001032", "12026001037"
start = datetime(2026, 10, 13, 14, tzinfo=BERLIN)
end = datetime(2026, 10, 13, 22, tzinfo=BERLIN)
config = MACHINES["K7"]
template = ShiftMaterialItem(
source="material_consumption_snapshots",
calculation_id=config.material.calculation_ids[0], machine_id=config.machine_id,
production_order=f"K 7-{first_order}", run_id="run", consumption_kg=3317.58,
baseline_timestamp=start, end_timestamp=end, baseline_missing=False,
)
measured = ShiftMaterialSummary(
config.machine_id, start, end, 5180.94,
(template, replace(template, production_order=f"K 7-{second_order}",
consumption_kg=1863.36)),
)
class Bookings:
def get_fiber_bookings(self, order):
amounts = ((2288.71, 1028.87) if order == first_order else (1312.62, 550.74))
return [FiberBooking(order, str(index), f"Fiber {index}", amount)
for index, amount in enumerate(amounts)]
allocator = K7FiberAllocationService(Bookings())
service, stubs, _, _ = composition("K7")
stubs["materials"].result = measured
first = row(15, 0, day=13, workplace="K7", order=first_order)
second = row(20, 0, day=13, workplace="K7", order=second_order)
order_service = ProductionOrderService(
FakeGateway(rows=[first], shift_rows=[first, second]), MACHINES,
speed=Speed(), materials=stubs["materials"],
material_allocators={"K7": allocator},
)
service.order_kpis = order_service
service.material_allocators = {"K7": allocator}
production = stubs["production"].result
production_items = tuple(
replace(production.items[0], production_order=order,
first_confirmation_at=start, last_confirmation_at=start)
for order in (first_order, second_order)
)
stubs["production"].result = replace(production, items=production_items)
report = service.build(machine_name="K7", start=start, end=end)
assert [item.material_consumption_kg for item in report.production.items] == pytest.approx(
[3317.58, 1863.36])
assert report.materials.total_consumption_kg == pytest.approx(5180.94)
assert fsum(item.consumption_kg for item in report.materials.items) == pytest.approx(5180.94)
assert len(report.materials.items) == 4
assert [item.consumption_kg for item in report.materials.items] == pytest.approx(
[2288.71, 1028.87, 1312.62, 550.74])
material_calls = [kwargs for name, kwargs in stubs["materials"].calls if name == "materials"]
assert material_calls == [{"machine_id": config.machine_id,
"calculation_ids": config.material.calculation_ids,
"start": start, "end": end}]
table = next(block for block in present_report(report)
if isinstance(block, TableBlock) and "Ø Geschwindigkeit" in block.headers)
assert [entry[-1] for entry in table.rows] == ["3.317,58 kg", "1.863,36 kg"]
material_table = next(block for block in present_report(report)
if isinstance(block, TableBlock) and "ERP-Anteil" in block.headers)
assert [entry[3] for entry in material_table.rows] == [
"2.288,71 kg", "1.028,87 kg", "1.312,62 kg", "550,74 kg"]
assert len(order_service.speed.calls) == 2
assert order_service.speed.calls[0][2] == order_service.speed.calls[1][1]
assert order_service.detail(first_order).shifts[0].material_consumption_kg == pytest.approx(
3317.58)
def test_k7_allocated_zero_remains_zero_and_absent_order_is_unavailable():
start = datetime(2026, 10, 13, 14, tzinfo=BERLIN)
end = datetime(2026, 10, 13, 22, tzinfo=BERLIN)
config = MACHINES["K7"]
item = ShiftMaterialItem(
source="material_consumption_snapshots",
calculation_id=config.material.calculation_ids[0], machine_id=config.machine_id,
production_order="K 7-12026001032", run_id="run", consumption_kg=0,
baseline_timestamp=start, end_timestamp=end, baseline_missing=False,
)
allocated = ShiftMaterialSummary(config.machine_id, start, end, 0, (item,))
allocator = K7FiberAllocationService(SimpleNamespace(get_fiber_bookings=lambda order: []))
first = row(15, 0, day=13, workplace="K7", order="12026001032")
second = row(20, 0, day=13, workplace="K7", order="12026001037")
order_service = ProductionOrderService(
FakeGateway(shift_rows=[first, second]), MACHINES,
material_allocators={"K7": allocator},
)
kpis = order_service.for_shift(
machine_name="K7", start=start, end=end,
orders=(first.production_order, second.production_order),
allocated_shift_materials=allocated,
)
assert kpis[first.production_order].material_consumption_kg == 0
assert kpis[second.production_order].material_consumption_kg is None
def test_no_active_speed_is_unavailable_and_material_zero_is_not():
speed, material = Speed(count=0), Material(0)
shift = service([b1(7)], [b1(7)], speed=speed, materials=material).detail(A).shifts[0]
assert shift.average_speed_m_min is None
assert shift.material_consumption_kg == 0
html = render_detail(detail=service([b1(7)], [b1(7)], speed=speed,
materials=material).detail(A))
assert "Ø Geschwindigkeit" in html and "Materialverbrauch" in html
assert "<td>—</td>" in html and "<td>0,00 kg</td>" in html
def test_order_html_formats_per_shift_kpis_in_german():
detail = service([b1(7)], [b1(7)]).detail(A)
enriched = replace(detail, shifts=(replace(detail.shifts[0],
average_speed_m_min=4.77,
material_consumption_kg=1234),))
html = render_detail(detail=enriched)
assert "<td>4,77 m/min</td>" in html
assert "<td>1.234,00 kg</td>" in html
def test_optional_source_failure_degrades_only_that_kpi():
speed = Speed(error=ExplorationError("unavailable"))
material = Material(2)
shift = service([b1(7)], [b1(7)], speed=speed, materials=material).detail(A).shifts[0]
assert shift.average_speed_m_min is None and shift.material_consumption_kg == 2
speed = Speed()
material = Material(error=ShiftMaterialReadError("unavailable"))
shift = service([b1(7)], [b1(7)], speed=speed, materials=material).detail(A).shifts[0]
assert shift.average_speed_m_min == 7 and shift.material_consumption_kg is None
def test_unexpected_programming_error_still_propagates():
with pytest.raises(ValueError, match="invalid configuration"):
service([b1(7)], [b1(7)], speed=Speed(error=ValueError("invalid configuration"))).detail(A)
def test_cumulative_material_segments_use_snapshot_deltas_without_double_counting():
a, b = b1(7, order=A), b1(12, order=B)
config = MACHINES["B1"]
stamps = [(6, 0), (8, 20), (10, 40), (13, 70)]
snapshots = [ShiftMaterialSnapshot(datetime(2026, 10, 19, hour, tzinfo=BERLIN),
config.material.calculation_ids[0], config.machine_id,
A, "run", value) for hour, value in stamps]
class Repository:
def get_snapshots(self, *, machine_id, calculation_ids, start, end):
earlier = [sample for sample in snapshots if sample.timestamp <= start]
inside = [sample for sample in snapshots if start < sample.timestamp < end]
return earlier[-1:] + inside
material = ShiftMaterialService(Repository())
first = service([a], [a, b], materials=material).detail(A).shifts[0]
second = service([b], [a, b], materials=material).detail(B).shifts[0]
whole = material.summarize(machine_id=config.machine_id,
calculation_ids=config.material.calculation_ids,
start=first.shift_start, end=first.shift_end)
assert first.segments[0].end == second.segments[0].start
assert (first.material_consumption_kg, second.material_consumption_kg) == (20, 50)
assert first.material_consumption_kg + second.material_consumption_kg == (
whole.total_consumption_kg)