"""Order search, shift assignment, and read-only web routes use fake ERP rows.""" from datetime import date, datetime from unittest.mock import MagicMock from urllib.parse import urlencode from wsgiref.util import setup_testing_defaults from zoneinfo import ZoneInfo import pytest from production_analytics import web from production_analytics.erp.gateway import ( ErpProductionConfirmationGateway, ErpSettings, OrderConfirmationGroup, OrderConfirmationRow, ProductionConfirmation, ) from production_analytics.presentation.production_order_html import render_detail, render_search from production_analytics.service.production_order import ProductionOrderService from production_analytics.service.shift_report_config import load_shift_report_machines ORDER = "82026400900" BERLIN = ZoneInfo("Europe/Berlin") MALAYSIA = ZoneInfo("Asia/Kuala_Lumpur") MACHINES = load_shift_report_machines("config/shift-report-machines.yaml") def row(hour, minute, *, workplace="GITTERIII", day=19, amount=10, order=ORDER, article="A"): return OrderConfirmationRow(order, workplace, article, "Article name", datetime(2026, 10, day, hour, minute), amount) class FakeGateway: def __init__(self, rows=(), groups=(), shift_rows=None): self.rows = list(rows) self.shift_rows = list(rows if shift_rows is None else shift_rows) self.groups = list(groups) self.calls = [] def search_orders(self, query, *, limit=25): self.calls.append(("search", query, limit)) return self.groups def get_order_confirmations(self, production_order): self.calls.append(("detail", production_order)) return self.rows def get_confirmations(self, *, workplace, start, end, timezone): self.calls.append(("shift", workplace, start, end, timezone)) return [ProductionConfirmation( workplace=value.workplace, production_order=value.production_order, timestamp=value.timestamp_local.replace(tzinfo=timezone), article_number=value.article_number, article_description=value.article_description, roll_number=None, production_quantity_m2=None, feedback_quantity_m2=value.feedback_quantity_m2, raw_material_number=None, raw_material_description=None, batch_number=None, raw_material_quantity=None, tenant=None, ) for value in self.shift_rows if value.workplace == workplace and start <= value.timestamp_local.replace(tzinfo=timezone) < end] def group(order=ORDER, workplace="GITTERIII", article="A"): return OrderConfirmationGroup(order, workplace, article, "Article name", datetime(2026, 10, 19, 6), datetime(2026, 10, 19, 14)) def test_search_trims_and_collapses_rows_by_fa_with_multiple_workplaces(): gateway = FakeGateway(groups=[group(workplace="BENTO 1"), group(), group("82026400901"), group(article="B")]) result = ProductionOrderService(gateway, MACHINES).search(" 82026400900 ") assert gateway.calls == [("search", ORDER, 25)] assert [entry.production_order for entry in result] == [ORDER, "82026400901"] assert len(result[0].placements) == 3 assert {place.machine_name for place in result[0].placements} == {"B1", "Gitter 3"} assert {place.timezone for place in result[0].placements} == {BERLIN} def test_search_limit_and_order_are_deterministic_even_with_unsorted_gateway(): groups = [group("8202642"), group("8202641"), group("8202643"), group("8202641")] service = ProductionOrderService(FakeGateway(groups=groups), MACHINES) assert [value.production_order for value in service.search("820264", limit=2)] == [ "8202641", "8202642"] assert [value.production_order for value in service.search("8202642", limit=2)] == [ "8202642", "8202641"] @pytest.mark.parametrize("query", ["", " ", "\x00", "x" * 81]) def test_blank_or_invalid_search_never_queries_gateway(query): gateway = FakeGateway() with pytest.raises(ValueError): ProductionOrderService(gateway, MACHINES).search(query) assert gateway.calls == [] def test_unknown_workplace_is_visible_without_shift_assignment(): gateway = FakeGateway(rows=[row(7, 0, workplace="UNCONFIGURED")], groups=[group(workplace="UNCONFIGURED")]) service = ProductionOrderService(gateway, MACHINES) placement = service.search(ORDER)[0].placements[0] assert placement.mapping_status == "unknown" assert placement.machine_name is placement.site is placement.timezone is None detail = service.detail(ORDER) assert detail.placements[0].mapping_status == "unknown" assert detail.shifts == () def test_ambiguous_workplace_is_visible_without_arbitrary_machine_choice(): from dataclasses import replace machines = {"B1": MACHINES["B1"], "Other": replace(MACHINES["B1"], display_name="Other")} service = ProductionOrderService(FakeGateway(rows=[row(7, 0, workplace="BENTO 1")], groups=[group(workplace="BENTO 1")]), machines) assert service.search(ORDER)[0].placements[0].mapping_status == "ambiguous" assert service.detail(ORDER).shifts == () def test_one_shift_aggregates_positive_feedback_and_confirmation_bounds(): service = ProductionOrderService(FakeGateway(rows=[row(6, 1, amount=2), row(13, 59, amount=3)]), MACHINES) detail = service.detail(ORDER) assert len(detail.shifts) == 1 item = detail.shifts[0] assert (item.machine_name, item.site, item.date, item.shift, item.produced_m2) == ( "Gitter 3", "adorf", date(2026, 10, 19), "early", 5) assert (item.first_confirmation.hour, item.last_confirmation.hour) == (6, 13) assert (item.shift_start.hour, item.shift_end.hour) == (6, 14) def test_two_shifts_and_night_across_midnight(): rows = [row(13, 59), row(14, 0), row(22, 0), row(5, 59, day=20), row(6, 0, day=20)] shifts = ProductionOrderService(FakeGateway(rows=rows), MACHINES).detail(ORDER).shifts assert [(item.date, item.shift, item.produced_m2) for item in shifts] == [ (date(2026, 10, 19), "early", 10), (date(2026, 10, 19), "late", 10), (date(2026, 10, 19), "night", 20), (date(2026, 10, 20), "early", 10), ] assert shifts[2].shift_end == datetime(2026, 10, 20, 6, tzinfo=BERLIN) def test_same_fa_on_multiple_machines_uses_each_site_timezone(): rows = [row(7, 0), row(7, 0, workplace="K1", amount=4)] shifts = ProductionOrderService(FakeGateway(rows=rows), MACHINES).detail(ORDER).shifts assert len(shifts) == 2 assert {(item.machine_name, item.timezone) for item in shifts} == { ("Gitter 3", BERLIN), ("K1", MALAYSIA)} assert shifts[0].shift_start.astimezone(ZoneInfo("UTC")) != ( shifts[1].shift_start.astimezone(ZoneInfo("UTC"))) def test_malaysia_before_six_belongs_to_previous_night_start_date(): shift = ProductionOrderService(FakeGateway(rows=[row(5, 45, workplace="K1", day=20)]), MACHINES).detail(ORDER).shifts[0] assert (shift.date, shift.shift, shift.timezone) == ( date(2026, 10, 19), "night", MALAYSIA) assert shift.shift_start == datetime(2026, 10, 19, 22, tzinfo=MALAYSIA) assert shift.shift_end == datetime(2026, 10, 20, 6, tzinfo=MALAYSIA) def web_request(app, path, query="", method="GET"): env = {} setup_testing_defaults(env) env.update(PATH_INFO=path, QUERY_STRING=query, REQUEST_METHOD=method) result = [] body = b"".join(app(env, lambda status, headers: result.append((status, headers)))) return result[0][0], body.decode() def test_search_and_detail_web_pages_and_encoded_report_link(): gateway = FakeGateway(rows=[row(7, 0)], groups=[group()]) service = ProductionOrderService(gateway, MACHINES) app = web.create_app(MACHINES, lambda: None, order_service_factory=lambda: service) status, text = web_request(app, "/orders") assert status == "200 OK" and "Fertigungsauftrag suchen" in text assert gateway.calls == [] status, text = web_request(app, "/orders", urlencode({"q": " 820264 "})) assert status == "200 OK" and ORDER in text and "/order?production_order=" in text status, text = web_request(app, "/order", urlencode({"production_order": ORDER})) assert status == "200 OK" assert 'Fertigungsauftrag' in text assert "Article name" in text and "10.00 m²" in text assert "Schichtbericht" in text assert "/?date=2026-10-19&shift=early&machine=Gitter+3" in text @pytest.mark.parametrize("html", [render_search(), render_detail(detail=None)], ids=["search", "detail"]) def test_order_pages_mark_order_mode_active(html): assert '