Extend shift reporting and downtime analytics

This commit is contained in:
admin committed 2026-10-20 14:16:58 +02:00
1 parent 41a5ae7a63
commit 6e8eb6f50f
74 files changed
+5397 -238

No files matched your search

+257 -9
View File
@@ -1,7 +1,8 @@
from copy import deepcopy
from dataclasses import FrozenInstanceError
from datetime import UTC, date, timedelta
from datetime import UTC, date, datetime, timedelta
from pathlib import Path
from zoneinfo import ZoneInfo
import pytest
import yaml
@@ -17,13 +18,20 @@ from production_analytics.calculations.shift_production import (
ShiftProductionItem,
ShiftProductionSummary,
)
from production_analytics.calculations.shift_report import shift_report_window
from production_analytics.calculations.shift_report import (
most_recent_completed_shift,
shift_report_window,
)
from production_analytics.calculations.shift_speed import aggregate_shift_speed
from production_analytics.service.shift_report import ShiftReportService
from production_analytics.service.shift_report_config import load_shift_report_machines
from production_analytics.service.shift_report_config import (
load_shift_report_config,
load_shift_report_machines,
)
CONFIG_PATH = Path(__file__).resolve().parents[1] / "config/shift-report-machines.yaml"
START, END = shift_report_window(date(2026, 10, 7), "early")
SHIFT_TIMEZONE = ZoneInfo("Europe/Berlin")
START, END = shift_report_window(date(2026, 10, 7), "early", SHIFT_TIMEZONE)
class Stub:
@@ -58,11 +66,12 @@ def composition(name="B1"):
event = ClippedShiftDowntimeEvent(source, START, source.source_end, 100)
downtime = ShiftDowntimeSummary(config.machine_id, START, END, 28800, 100, 28700,
(event,), reasons)
channel = config.material.mode == "channel"
channel = config.material is not None and config.material.mode == "channel"
item = ShiftMaterialItem(
source="channel_material_consumption_snapshots" if channel
else "material_consumption_snapshots",
calculation_id=config.material.calculation_ids[0], machine_id=config.machine_id,
calculation_id=config.material.calculation_ids[0] if config.material else "unused",
machine_id=config.machine_id,
production_order="order", run_id="run", consumption_kg=42,
baseline_timestamp=START, end_timestamp=END - timedelta(seconds=1),
baseline_missing=False, extruder="Ex1" if channel else None,
@@ -89,7 +98,8 @@ def test_machine_composition(name, workplace, mode, ids):
service, stubs, calls, config = composition(name)
report = service.build(machine_name=name, start=START, end=END)
assert calls == [
("production", {"workplace": workplace, "start": START, "end": END}),
("production", {"workplace": workplace, "start": START, "end": END,
"timezone": SHIFT_TIMEZONE}),
("downtime", {"machine_id": config.machine_id, "start": START, "end": END}),
(mode, {"machine_id": config.machine_id, "calculation_ids": ids,
"start": START, "end": END}),
@@ -113,6 +123,172 @@ def test_machine_composition(name, workplace, mode, ids):
report.machine_name = "other"
@pytest.mark.parametrize("name", ["Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", "K5"])
def test_boolean_speed_machines_appear_in_report_without_material(name):
service, stubs, calls, config = composition(name)
report = service.build(machine_name=name, start=START, end=END)
assert [stage for stage, _ in calls] == ["production", "downtime", "speed"]
assert calls[-1][1]["config"] is config.speed
assert report.speed is stubs["speed"].result
assert report.materials is None
def test_sites_and_existing_machine_capabilities():
config = load_shift_report_config(CONFIG_PATH)
assert {key: site.display_name for key, site in config.sites.items()} == {
"espelkamp": "Espelkamp", "adorf": "Adorf", "malaysia": "Malaysia",
}
assert set(config.machines) == {
"B1", "E1", "K7", "K3/4", "E4", "Gitter 1", "Gitter 2",
"Gitter 3", "Gitter 4", "K5", "Secumat 1/2", "Secumat 3",
"Bento 2", "K1", "K6",
}
assert all(config.machines[name].site == "espelkamp" for name in ("B1", "E1", "K7"))
assert all(vars_for_capabilities(machine) == (True, True, True, True)
for name, machine in config.machines.items() if name in ("B1", "E1", "K7"))
assert config.machines["K7"].material.allocation == "erp_fiber_share"
assert config.machines["B1"].material.allocation == "none"
assert config.sites["espelkamp"].timezone is SHIFT_TIMEZONE
assert config.sites["adorf"].timezone is SHIFT_TIMEZONE
assert config.sites["malaysia"].timezone.key == "Asia/Kuala_Lumpur"
assert all(config.machines[name].timezone is SHIFT_TIMEZONE
for name in ("B1", "E1", "K7"))
with pytest.raises(TypeError):
config.sites["new"] = config.sites["adorf"]
def vars_for_capabilities(machine):
value = machine.capabilities
return value.production, value.downtime, value.material, value.speed
def test_new_production_machines_have_valid_sites_and_capabilities():
machines = load_shift_report_config(CONFIG_PATH).machines
expected = {
"K3/4": ("espelkamp", "K3/4", None),
"E4": ("espelkamp", "1568700", "646ebfa0-e97d-4970-b9f4-da94492aecc3"),
"Gitter 1": ("adorf", "GITTERANL", "35612735-03cc-4496-a72e-3c3e2216c720"),
"Gitter 2": ("adorf", "GITTER II", "5e89db10-ef0e-4224-866c-eee12bc3d27c"),
"Gitter 3": ("adorf", "GITTERIII", "ec3baac3-ccc1-4d1e-9b57-3f5ab2daa567"),
"Gitter 4": ("adorf", "GITTER IV", "ffa5de99-66a2-44bd-b039-9b4275bc5f9e"),
"K5": ("adorf", "K5", "8c094b9d-32d2-4ddf-b56a-2cd11a09eebf"),
"Secumat 1/2": ("adorf", "SECEXTRU", "16c0a111-3049-41d5-9e19-42ee0e047757"),
"Secumat 3": ("adorf", "SEC3", "0c207a7c-7813-4cff-90ba-6a0148919d38"),
"Bento 2": ("malaysia", "BENTO 2", "6201f3de-b940-45d7-930c-1481c5ae9e1d"),
"K1": ("malaysia", "K1", "40f1f58b-21fc-490a-8343-d1888938f11b"),
"K6": ("malaysia", "K6", "5e778f87-2d0f-47ac-a3ce-0c0dd9957918"),
}
assert len(machines) == 15
assert set(machines) - {"B1", "E1", "K7"} == set(expected)
downtime_enabled = {
"E4", "Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4",
"K5", "Secumat 1/2", "Secumat 3",
}
for name, (site, workplace, machine_id) in expected.items():
machine = machines[name]
assert (machine.display_name, machine.site, machine.erp_workplace,
machine.machine_id) == (name, site, workplace, machine_id)
speed_enabled = name in {"Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", "K5"}
assert vars_for_capabilities(machine) == (True, name in downtime_enabled, False,
speed_enabled)
assert machine.material is None
assert (machine.speed is not None) == speed_enabled
assert machine.timezone.key == ("Asia/Kuala_Lumpur" if site == "malaysia"
else "Europe/Berlin")
ids = [machine.machine_id for machine in machines.values() if machine.machine_id]
assert len(ids) == len(set(ids)) == 14
@pytest.mark.parametrize("downtime", [False, True])
def test_partial_capabilities_skip_disabled_sources_and_render_unavailable(
downtime,
):
from dataclasses import replace
from production_analytics.presentation.shift_report import TextBlock, present_report
from production_analytics.service.shift_report_config import ShiftReportCapabilities
service, stubs, calls, config = composition()
partial = replace(config,
capabilities=ShiftReportCapabilities(True, downtime, False, False),
material=None, speed=None)
service.machines = {"Synthetic": partial}
report = service.build(machine_name="Synthetic", start=START, end=END)
expected = ["production", "downtime"] if downtime else ["production"]
assert [name for name, _ in calls] == expected
assert report.production is stubs["production"].result
assert report.downtime is (stubs["downtime"].result if downtime else None)
assert report.materials is None and report.speed is None
assert report.downtime_event_count == (1 if downtime else 0)
blocks = present_report(report)
unavailable = [b for b in blocks if isinstance(b, TextBlock)
and b.text == "Für diese Maschine nicht verfügbar."]
assert len(unavailable) == (2 if downtime else 3)
def test_downtime_only_machine_does_not_query_production():
from dataclasses import replace
from production_analytics.service.shift_report_config import ShiftReportCapabilities
service, stubs, calls, config = composition()
service.machines = {"DowntimeOnly": replace(
config, capabilities=ShiftReportCapabilities(False, True, False, False),
material=None, speed=None,
)}
report = service.build(machine_name="DowntimeOnly", start=START, end=END)
assert [name for name, _ in calls] == ["downtime"]
assert report.production is None and report.downtime is stubs["downtime"].result
@pytest.mark.parametrize("explicit_null", [False, True])
def test_production_only_machine_without_enlyze_id_loads_and_builds(tmp_path, explicit_null):
document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text()))
document["machines"] = {"K3/4": {
"display_name": "K3/4", "site": "espelkamp", "erp_workplace": "K3/4",
"capabilities": {"production": True, "downtime": False,
"material": False, "speed": False},
}}
if explicit_null:
document["machines"]["K3/4"]["machine_id"] = None
path = tmp_path / "machines.yaml"
path.write_text(yaml.safe_dump(document))
machine = load_shift_report_config(path).machines["K3/4"]
assert machine.machine_id is None and machine.timezone is SHIFT_TIMEZONE
service, stubs, calls, _ = composition()
service.machines = {"K3/4": machine}
report = service.build(machine_name="K3/4", start=START, end=END)
assert report.machine_id is None and report.timezone is SHIFT_TIMEZONE
assert report.production is stubs["production"].result
assert report.downtime is report.materials is report.speed is None
assert [name for name, _ in calls] == ["production"]
def test_malaysia_report_carries_site_timezone_to_production_and_presentation():
from dataclasses import replace
from production_analytics.presentation.shift_report import TextBlock, present_report
from production_analytics.service.shift_report_config import ShiftReportCapabilities
malaysia = ZoneInfo("Asia/Kuala_Lumpur")
service, _, calls, config = composition()
service.machines = {"Synthetic": replace(
config, site="malaysia", timezone=malaysia, machine_id=None,
capabilities=ShiftReportCapabilities(True, False, False, False),
material=None, speed=None,
)}
start, end = shift_report_window(date(2026, 10, 19), "late", malaysia)
report = service.build(machine_name="Synthetic", start=start.astimezone(UTC),
end=end.astimezone(UTC))
assert report.timezone is malaysia
assert report.start == start and report.end == end
assert calls == [("production", {"workplace": config.erp_workplace,
"start": start, "end": end, "timezone": malaysia})]
texts = [block.text for block in present_report(report) if isinstance(block, TextBlock)]
assert "Zeitzone: Asia/Kuala_Lumpur" in texts
assert any("Schichtbeginn: 19.10.2026 14:00:00" in value for value in texts)
def test_top_three_and_fallback_preserve_reason_metadata_and_order():
service, stubs, _, _ = composition()
report = service.build(machine_name="B1", start=START, end=END)
@@ -191,7 +367,7 @@ def test_utc_input_is_normalized_to_berlin_without_changing_instants():
("early", (6, 14)), ("late", (14, 22)), ("night", (22, 6)),
])
def test_shift_windows(shift, hours):
start, end = shift_report_window(date(2026, 10, 7), shift)
start, end = shift_report_window(date(2026, 10, 7), shift, SHIFT_TIMEZONE)
assert (start.hour, end.hour) == hours
expected_end_day = date(2026, 10, 8) if shift == "night" else start.date()
assert end.date() == expected_end_day
@@ -200,10 +376,28 @@ def test_shift_windows(shift, hours):
@pytest.mark.parametrize("day,hours", [(date(2026, 3, 28), 7), (date(2026, 10, 24), 9)])
def test_night_shift_dst_elapsed_duration(day, hours):
start, end = shift_report_window(day, "night")
start, end = shift_report_window(day, "night", SHIFT_TIMEZONE)
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == hours * 3600
@pytest.mark.parametrize("shift,start_hour,end_hour", [
("early", 6, 14), ("late", 14, 22), ("night", 22, 6),
])
def test_malaysia_shift_windows_use_local_wall_clock(shift, start_hour, end_hour):
malaysia = ZoneInfo("Asia/Kuala_Lumpur")
start, end = shift_report_window(date(2026, 10, 19), shift, malaysia)
assert start.tzinfo is end.tzinfo is malaysia
assert (start.hour, end.hour) == (start_hour, end_hour)
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == 28800
def test_same_instant_has_different_site_completed_shifts():
now = datetime(2026, 10, 19, 11, tzinfo=UTC)
assert most_recent_completed_shift(now, SHIFT_TIMEZONE) == (date(2026, 10, 18), "night")
assert most_recent_completed_shift(now, ZoneInfo("Asia/Kuala_Lumpur")) == (
date(2026, 10, 19), "early")
@pytest.mark.parametrize("mutation", [
lambda d: d["machines"]["B1"].pop("erp_workplace"),
lambda d: d["machines"]["B1"].update(unknown=True),
@@ -221,6 +415,25 @@ def test_night_shift_dst_elapsed_duration(day, hours):
lambda d: d["machines"]["E1"].update(machine_id=d["machines"]["B1"]["machine_id"]),
lambda d: d["machines"]["B1"].update(erp_workplace=1568705),
lambda d: d.update(extra=True),
lambda d: d["machines"]["B1"].update(site="unknown"),
lambda d: d["machines"]["B1"].update(site=[]),
lambda d: d["machines"]["B1"].pop("capabilities"),
lambda d: d["machines"]["B1"]["capabilities"].update(material=False),
lambda d: d["machines"]["B1"].pop("material"),
lambda d: d["machines"]["B1"]["capabilities"].update(speed=False),
lambda d: d["machines"]["B1"].pop("speed"),
lambda d: d["machines"]["B1"]["capabilities"].update(production="true"),
lambda d: d["machines"]["B1"].update(display_name=" "),
lambda d: d["sites"]["espelkamp"].update(display_name=""),
lambda d: d["sites"]["espelkamp"].update(extra=True),
lambda d: d["machines"]["B1"]["material"].update(allocation="unknown"),
lambda d: d["sites"]["malaysia"].update(timezone="Mars/Base"),
lambda d: d["sites"]["malaysia"].update(timezone=""),
lambda d: d["sites"]["malaysia"].pop("timezone"),
lambda d: d["machines"]["B1"].pop("machine_id"),
lambda d: d["machines"]["B1"].update(machine_id=None),
lambda d: d["machines"]["B1"]["capabilities"].update(
production=False, downtime=False, material=False, speed=False),
])
def test_strict_configuration(tmp_path, mutation):
document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text()))
@@ -236,3 +449,38 @@ def test_duplicate_yaml_keys_rejected(tmp_path):
path.write_text("machines: {}\nmachines: {}\n")
with pytest.raises(ValueError, match="unique"):
load_shift_report_machines(path)
def test_duplicate_site_key_rejected(tmp_path):
document = CONFIG_PATH.read_text().replace(
" adorf:\n display_name: Adorf", " espelkamp:\n display_name: Adorf"
)
path = tmp_path / "machines.yaml"
path.write_text(document)
with pytest.raises(ValueError, match="unique"):
load_shift_report_config(path)
def test_duplicate_machine_key_rejected(tmp_path):
document = CONFIG_PATH.read_text().replace(" E1:\n", " B1:\n")
path = tmp_path / "machines.yaml"
path.write_text(document)
with pytest.raises(ValueError, match="unique"):
load_shift_report_config(path)
@pytest.mark.parametrize("capability", ["downtime", "material", "speed"])
def test_machine_id_required_for_nonproduction_capabilities(tmp_path, capability):
document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text()))
machine = document["machines"]["B1"]
machine["capabilities"] = {name: name == capability
for name in ("production", "downtime", "material", "speed")}
machine.pop("machine_id")
if capability != "material":
machine.pop("material")
if capability != "speed":
machine.pop("speed")
path = tmp_path / "machines.yaml"
path.write_text(yaml.safe_dump(document))
with pytest.raises(ValueError):
load_shift_report_config(path)