from copy import deepcopy from dataclasses import FrozenInstanceError from datetime import UTC, date, timedelta from pathlib import Path 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 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 CONFIG_PATH = Path(__file__).resolve().parents[1] / "config/shift-report-machines.yaml" START, END = shift_report_window(date(2026, 10, 7), "early") 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.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, 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}), ("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_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) 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") assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == hours * 3600 @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), ]) 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)