from copy import deepcopy from dataclasses import FrozenInstanceError from datetime import UTC, date, datetime, timedelta from pathlib import Path from zoneinfo import ZoneInfo import pytest import yaml from production_analytics.calculations.shift_downtime import ( ClippedShiftDowntimeEvent, ShiftDowntimeEvent, ShiftDowntimeReason, ShiftDowntimeSummary, ) from production_analytics.calculations.shift_material import ShiftMaterialItem, ShiftMaterialSummary from production_analytics.calculations.shift_production import ( ShiftProductionItem, ShiftProductionSummary, ) 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_config, load_shift_report_machines, ) CONFIG_PATH = Path(__file__).resolve().parents[1] / "config/shift-report-machines.yaml" SHIFT_TIMEZONE = ZoneInfo("Europe/Berlin") START, END = shift_report_window(date(2026, 10, 7), "early", SHIFT_TIMEZONE) class Stub: def __init__(self, name, result, calls): self.name, self.result, self.calls = name, result, calls self.error = None def summarize(self, **kwargs): self.calls.append((self.name, kwargs)) if self.error is not None: raise self.error return self.result def composition(name="B1"): machines = load_shift_report_machines(CONFIG_PATH) config = machines[name] calls = [] production = ShiftProductionSummary( START, END, config.erp_workplace, 123, 1, (ShiftProductionItem("order", "article", "description", 123, 1, START, START),), ) reasons = tuple( ShiftDowntimeReason(str(index), reason_name, "description", "group", "category", duration, 1) for index, (reason_name, duration) in enumerate( [(None, 100), ("Stop", 90), (" ", 80), ("Other", 70)] ) ) source = ShiftDowntimeEvent("event", config.machine_id, START, START + timedelta(seconds=100), None, None, None, None, None, None) event = ClippedShiftDowntimeEvent(source, START, source.source_end, 100) downtime = ShiftDowntimeSummary(config.machine_id, START, END, 28800, 100, 28700, (event,), reasons) 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] 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, doser_channel="C2" if channel else None, material_name=None, material_mapping_status="UNAVAILABLE" if channel else None, ) materials = ShiftMaterialSummary(config.machine_id, START, END, 42, (item,)) speed = aggregate_shift_speed([], config=config.speed, start=START, end=END) stubs = {key: Stub(key, value, calls) for key, value in [ ("production", production), ("downtime", downtime), ("materials", materials), ("channel_materials", materials), ("speed", speed), ]} service = ShiftReportService(machines=machines, **stubs) return service, stubs, calls, config @pytest.mark.parametrize("name,workplace,mode,ids", [ ("B1", "BENTO 1", "materials", ("bento1-fresh-bentonite-consumption", "bento1-spreader3-consumption")), ("E1", "1568705", "channel_materials", ("e1-channel-material-consumption",)), ("K7", "K7", "materials", ("k7-fiber-consumption",)), ]) 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, "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}), ("speed", {"config": config.speed, "start": START, "end": END}), ] assert report.machine_name == name and report.machine_id == config.machine_id assert report.production is stubs["production"].result assert report.downtime is stubs["downtime"].result assert report.materials is stubs[mode].result assert report.speed is stubs["speed"].result assert report.materials.items[0].consumption_kg == 42 assert report.materials.items[0].material_name is None if name == "E1": assert report.materials.items[0].extruder == "Ex1" assert report.materials.items[0].doser_channel == "C2" assert report.materials.items[0].material_mapping_status == "UNAVAILABLE" assert report.downtime.non_downtime_seconds == 28700 assert report.downtime_event_count == 1 assert report.production.items[0].article_description == "description" with pytest.raises(FrozenInstanceError): report.machine_name = "other" def test_order_kpis_enrich_each_production_row_without_changing_shift_totals(): from dataclasses import replace from production_analytics.service.production_order import ProductionOrderShiftKpi service, stubs, _, _ = composition("K7") first = stubs["production"].result.items[0] second = replace(first, production_order="other", produced_m2=24) stubs["production"].result = replace( stubs["production"].result, items=(first, second), total_produced_m2=147, total_roll_count=2, ) class OrderKpis: def __init__(self): self.calls = [] def for_shift(self, **kwargs): self.calls.append(kwargs) return { "order": ProductionOrderShiftKpi((), 10.24, 3317.58), "other": ProductionOrderShiftKpi((), 8.5, 1863.36), } order_kpis = OrderKpis() service.order_kpis = order_kpis report = service.build(machine_name="K7", start=START, end=END) assert order_kpis.calls == [{"machine_name": "K7", "start": START, "end": END, "orders": ("order", "other"), "allocated_shift_materials": None}] assert [(item.average_speed_m_min, item.material_consumption_kg) for item in report.production.items] == [(10.24, 3317.58), (8.5, 1863.36)] assert report.production.total_produced_m2 == 147 assert report.materials is stubs["materials"].result assert report.speed is stubs["speed"].result @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) assert len(report.downtime_reasons) == 4 assert len(report.top_downtime_reasons) == 3 assert [reason.display_name for reason in report.top_downtime_reasons] == [ "Ohne Stillstandsgrund", "Stop", "Ohne Stillstandsgrund", ] for index, view in enumerate(report.top_downtime_reasons): assert view.reason is stubs["downtime"].result.reasons[index] assert view.reason.duration_seconds == [100, 90, 80][index] assert view.reason.reason_description == "description" assert report.downtime.reasons[0].reason_name is None with pytest.raises(FrozenInstanceError): report.top_downtime_reasons[0].display_name = "changed" def test_legitimate_empty_sources_are_kept(): service, stubs, _, config = composition() stubs["production"].result = ShiftProductionSummary(START, END, config.erp_workplace, 0, 0, ()) stubs["downtime"].result = ShiftDowntimeSummary(config.machine_id, START, END, 28800, 0, 28800, (), ()) stubs["materials"].result = ShiftMaterialSummary(config.machine_id, START, END, 0, ()) report = service.build(machine_name="B1", start=START, end=END) assert report.production.items == () and report.production.total_produced_m2 == 0 assert report.materials.items == () and report.materials.total_consumption_kg == 0 assert report.speed.average_line_speed_m_min is None assert report.top_downtime_reasons == () assert report.downtime_event_count == 0 @pytest.mark.parametrize("name,stage", [ ("B1", "production"), ("B1", "downtime"), ("B1", "materials"), ("E1", "channel_materials"), ("K7", "speed"), ]) def test_mandatory_failures_propagate_without_reading_later_sources(name, stage): service, stubs, calls, _ = composition(name) error = RuntimeError("source failed") stubs[stage].error = error with pytest.raises(RuntimeError) as caught: service.build(machine_name=name, start=START, end=END) assert caught.value is error assert calls[-1][0] == stage sequence = ["production", "downtime", "channel_materials" if name == "E1" else "materials", "speed"] assert [call[0] for call in calls] == sequence[:sequence.index(stage) + 1] @pytest.mark.parametrize("start,end", [ (START.replace(tzinfo=None), END), (START, END.replace(tzinfo=None)), (START, START), (END, START), ]) def test_invalid_window_precedes_source_calls(start, end): service, _, calls, _ = composition() with pytest.raises(ValueError): service.build(machine_name="B1", start=start, end=end) assert calls == [] def test_unknown_machine_precedes_source_calls(): service, _, calls, _ = composition() with pytest.raises(ValueError, match="Unknown"): service.build(machine_name="unknown", start=START, end=END) assert calls == [] def test_utc_input_is_normalized_to_berlin_without_changing_instants(): service, _, calls, _ = composition() report = service.build(machine_name="B1", start=START.astimezone(UTC), end=END.astimezone(UTC)) assert report.start.tzinfo.key == "Europe/Berlin" assert report.start == START and report.end == END assert all(call[1]["start"].tzinfo.key == "Europe/Berlin" for call in calls) @pytest.mark.parametrize("shift,hours", [ ("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, 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 assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == 28800 @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", 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), lambda d: d["machines"]["B1"]["material"].update(mode="erp"), lambda d: d["machines"]["B1"]["material"].update(calculation_ids=[]), lambda d: d["machines"]["B1"]["material"].update(calculation_ids="calc"), lambda d: d["machines"]["B1"]["material"].update(calculation_ids=["calc", "calc"]), lambda d: d["machines"]["B1"]["material"].update(calculation_ids=[None]), lambda d: d["machines"]["B1"]["material"].update(extra=True), lambda d: d["machines"]["B1"]["speed"].pop("signal_ref"), lambda d: d["machines"]["B1"]["speed"].update(extra=True), lambda d: d["machines"]["B1"]["speed"].update(signal=" "), lambda d: d["machines"]["B1"]["speed"].update(unit="rpm"), lambda d: d["machines"]["B1"]["speed"].update(production_gate_m_min=float("nan")), 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())) mutation(document) path = tmp_path / "machines.yaml" path.write_text(yaml.safe_dump(document)) with pytest.raises(ValueError): load_shift_report_machines(path) def test_duplicate_yaml_keys_rejected(tmp_path): path = tmp_path / "machines.yaml" 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)