diff --git a/docs/shift-report.md b/docs/shift-report.md index 8ee45fa..2ad3c0a 100644 --- a/docs/shift-report.md +++ b/docs/shift-report.md @@ -221,3 +221,30 @@ completeness claim. Sources are still read sequentially, not transactionally. Invalid selections return a German page-level error (HTTP 400). Source/settings or rendering failures return a generic German error (HTTP 503), retaining the selection controls without exposing exception text or credentials. + +## Fertigungsauftrag search + +The web UI links to `/orders?q=...` for a complete or partial FA number. Search +trims surrounding whitespace, rejects empty input, treats SQL wildcard characters +literally, and caps results at 25 distinct FAs. An exact match is listed first; +other results are ordered by FA. Repeated confirmation rows collapse into one FA +result, with separate workplace/article entries when needed. `/order?production_order=...` +shows the selected order and its affected shifts. Each shift links to the existing +live report URL with machine, shift start date and shift name. + +The order view reads positive `Rückmeldemenge` rows from +`dbo.GRAFANA_PRODUCTION_CONFIRMATION`, matching the finished-production quantity +semantics of the shift report. The view's `Zeitstempel` is an ERP confirmation +timestamp; first and last timestamps do not describe uninterrupted machine runtime. +Each row is assigned to a configured machine by its exact `erp_workplace`, then +interpreted in that machine's site timezone. Local 22:00–05:59 belongs to the +night shift whose start date may be the previous day. Multiple rows for the same +FA, machine and shift sum their positive feedback m². Unknown or ambiguous +workplaces remain visible but cannot be assigned a configured shift. + +The ERP gateway owns parameterized read-only SQL, the production-order service +owns mapping and shift grouping, and a dedicated presenter renders HTML. The +order/machine/shift model is the anchor for later order-specific KPI, roll/QS and +setup-sheet views; those data are not included yet. ERP timestamps are local +datetimes without offsets; autumn repeated-hour rows are interpreted as the +first occurrence, as in the existing confirmation gateway. diff --git a/src/production_analytics/calculations/shift_report.py b/src/production_analytics/calculations/shift_report.py index fd77cc6..b60f905 100644 --- a/src/production_analytics/calculations/shift_report.py +++ b/src/production_analytics/calculations/shift_report.py @@ -79,6 +79,28 @@ def shift_report_window( ) +def shift_containing( + timestamp: datetime, timezone: ZoneInfo, +) -> tuple[date, Literal["early", "late", "night"], datetime, datetime]: + """Return the site-local shift containing one confirmation instant.""" + if (not isinstance(timestamp, datetime) or timestamp.tzinfo is None + or timestamp.utcoffset() is None): + raise ValueError("timestamp must be timezone-aware") + if not isinstance(timezone, ZoneInfo): + raise ValueError("timezone must be a ZoneInfo") + local = timestamp.astimezone(timezone) + if local.hour < 6: + day, shift = local.date() - timedelta(days=1), "night" + elif local.hour < 14: + day, shift = local.date(), "early" + elif local.hour < 22: + day, shift = local.date(), "late" + else: + day, shift = local.date(), "night" + start, end = shift_report_window(day, shift, timezone) + return day, shift, start, end + + def most_recent_completed_shift( now: datetime, timezone: ZoneInfo, ) -> tuple[date, Literal["early", "late", "night"]]: diff --git a/src/production_analytics/erp/gateway.py b/src/production_analytics/erp/gateway.py index 9854279..723aade 100644 --- a/src/production_analytics/erp/gateway.py +++ b/src/production_analytics/erp/gateway.py @@ -255,6 +255,112 @@ class ErpProductionConfirmationGateway: except Exception: raise ErpReadError("ERP production confirmation returned an invalid row") from None + def search_orders(self, query: str, *, limit: int = 25) -> list["OrderConfirmationGroup"]: + query = _order_query(query) + if type(limit) is not int or not 1 <= limit <= 100: + raise ValueError("limit must be between 1 and 100") + pattern = "%" + query.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%" + rows = self._read_orders(_ORDER_SEARCH_SQL, (limit, pattern, query, query)) + try: + return [_order_group(row) for row in rows] + except Exception: + raise ErpReadError("ERP production-order search returned an invalid row") from None + + def get_order_confirmations(self, production_order: str) -> list["OrderConfirmationRow"]: + order = _order_query(production_order) + rows = self._read_orders(_ORDER_DETAIL_SQL, (order,)) + try: + return [_order_confirmation(row) for row in rows] + except Exception: + raise ErpReadError("ERP production-order detail returned an invalid row") from None + + def _read_orders(self, sql: str, parameters: tuple) -> list[tuple]: + try: + with pymssql.connect( + server=self._settings.host, port=self._settings.port, + database=self._settings.database, user=self._settings.user, + password=self._settings.password, login_timeout=10, timeout=10, + ) as connection: + with connection.cursor() as cursor: + cursor.execute(sql, parameters) + return cursor.fetchall() + except Exception: + raise ErpReadError("ERP production-order read failed") from None + + +@dataclass(frozen=True, slots=True) +class OrderConfirmationGroup: + production_order: str + workplace: str + article_number: str | None + article_description: str | None + first_confirmation_local: datetime + last_confirmation_local: datetime + + +@dataclass(frozen=True, slots=True) +class OrderConfirmationRow: + production_order: str + workplace: str + article_number: str | None + article_description: str | None + timestamp_local: datetime + feedback_quantity_m2: float + + +_ORDER_SEARCH_SQL = """WITH matching_orders AS ( + SELECT TOP (%s) [Fertigungsauftragsnummer] + FROM [dbo].[GRAFANA_PRODUCTION_CONFIRMATION] + WHERE [Fertigungsauftragsnummer] LIKE %s ESCAPE '\\' AND [Rückmeldemenge] > 0 + GROUP BY [Fertigungsauftragsnummer] + ORDER BY CASE WHEN [Fertigungsauftragsnummer] = %s THEN 0 ELSE 1 END, + [Fertigungsauftragsnummer] +) +SELECT c.[Fertigungsauftragsnummer], c.[Arbeitsplatz], c.[Artikelnummer], + c.[Artikelbezeichnung], MIN(c.[Zeitstempel]), MAX(c.[Zeitstempel]) +FROM [dbo].[GRAFANA_PRODUCTION_CONFIRMATION] AS c +JOIN matching_orders AS m ON m.[Fertigungsauftragsnummer] = c.[Fertigungsauftragsnummer] +WHERE c.[Rückmeldemenge] > 0 +GROUP BY c.[Fertigungsauftragsnummer], c.[Arbeitsplatz], c.[Artikelnummer], + c.[Artikelbezeichnung] +ORDER BY CASE WHEN c.[Fertigungsauftragsnummer] = %s THEN 0 ELSE 1 END, + c.[Fertigungsauftragsnummer], c.[Arbeitsplatz], c.[Artikelnummer], c.[Artikelbezeichnung]""" + + +_ORDER_DETAIL_SQL = """SELECT [Fertigungsauftragsnummer], [Arbeitsplatz], [Artikelnummer], + [Artikelbezeichnung], [Zeitstempel], [Rückmeldemenge] +FROM [dbo].[GRAFANA_PRODUCTION_CONFIRMATION] +WHERE [Fertigungsauftragsnummer] = %s AND [Rückmeldemenge] > 0 +ORDER BY [Zeitstempel], [Arbeitsplatz], [Artikelnummer], [Artikelbezeichnung], + [Rückmeldemenge]""" + + +def _order_query(value: str) -> str: + if (not isinstance(value, str) or not value.strip() or "\x00" in value + or len(value.strip()) > 80): + raise ValueError("production order query must be 1–80 non-NUL characters") + return value.strip() + + +def _order_group(row: tuple) -> OrderConfirmationGroup: + if len(row) != 6 or any(not isinstance(row[index], datetime) + or row[index].tzinfo is not None for index in (4, 5)): + raise ValueError + return OrderConfirmationGroup(_text(row[0]), _text(row[1]), + _text(row[2], nullable=True), _text(row[3], nullable=True), + row[4], row[5]) + + +def _order_confirmation(row: tuple) -> OrderConfirmationRow: + if len(row) != 6 or not isinstance(row[4], datetime) or row[4].tzinfo is not None: + raise ValueError + quantity = _number(row[5]) + if quantity is None or quantity <= 0: + raise ValueError + return OrderConfirmationRow(_text(row[0]), _text(row[1]), + _text(row[2], nullable=True), _text(row[3], nullable=True), + row[4], quantity) + def _production_confirmation(row: tuple[object, ...], timezone: ZoneInfo) -> ProductionConfirmation: if len(row) != 13 or not isinstance(row[2], datetime) or row[2].tzinfo is not None: diff --git a/src/production_analytics/presentation/production_order_html.py b/src/production_analytics/presentation/production_order_html.py new file mode 100644 index 0000000..08150f7 --- /dev/null +++ b/src/production_analytics/presentation/production_order_html.py @@ -0,0 +1,114 @@ +"""Server-rendered, escaped production-order search and detail pages.""" + +from html import escape +from urllib.parse import urlencode + +from production_analytics.service.production_order import ( + ProductionOrderDetail, + ProductionOrderSearchResult, +) + +SHIFT_LABELS = {"early": "Frühschicht", "late": "Spätschicht", "night": "Nachtschicht"} + + +def _page(title: str, body: str) -> str: + return f''' + +{escape(title)}
{body}
''' + + +def _form(query: str) -> str: + return ('
') + + +def _text(value: str | None) -> str: + return escape(value) if value else "–" + + +def _period(value, timezone) -> str: + label = value.strftime("%d.%m.%Y %H:%M") + return escape(f"{label} ({timezone.key})" if timezone else f"{label} (ERP-Lokalzeit)") + + +def render_search(*, query: str = "", results: tuple[ProductionOrderSearchResult, ...] = (), + error: str | None = None, searched: bool = False) -> str: + body = "

Fertigungsauftrag suchen

" + _form(query) + if error: + body += f'' + elif searched: + if not results: + body += "

Keine passenden Fertigungsaufträge gefunden.

" + else: + body += '
' + body += '' + body += '' + for result in results: + href = "/order?" + urlencode({"production_order": result.production_order}) + for placement in result.placements: + machine = placement.machine_name or "nicht zugeordnet" + link = (f'' + f'{escape(result.production_order)}') + body += "" + "".join(f"" for cell in ( + link, + _text(placement.article_number), _text(placement.article_description), + escape(f"{placement.workplace} / {machine}"), + _period(placement.first_confirmation_local, placement.timezone), + _period(placement.last_confirmation_local, placement.timezone), + )) + "" + body += "
FAArtikelArtikelbezeichnungArbeitsplatz / MaschineErste RückmeldungLetzte Rückmeldung
{cell}
" + return _page("Fertigungsauftrag suchen", body) + + +def render_detail(*, detail: ProductionOrderDetail | None, + error: str | None = None) -> str: + if error: + return _page("Fertigungsauftrag", f'') + if detail is None: + return _page("Fertigungsauftrag", "

Fertigungsauftrag nicht gefunden.

") + body = f"

Fertigungsauftrag {escape(detail.production_order)}

" + body += '

Zeiten sind ERP-Rückmeldezeitpunkte, keine durchgehenden ' + body += 'Maschinenlaufzeiten. Mengen sind positive Rückmeldemengen in m².

' + body += '

Artikel und Arbeitsplätze

' + body += '' + body += '' + for placement in detail.placements: + machine = placement.machine_name or f"nicht zugeordnet ({placement.mapping_status})" + body += "" + "".join(f"" for cell in ( + _text(placement.article_number), _text(placement.article_description), + escape(f"{placement.workplace} / {machine}"), + _period(placement.first_confirmation_local, placement.timezone), + _period(placement.last_confirmation_local, placement.timezone), + )) + "" + body += '
ArtikelArtikelbezeichnungArbeitsplatz / MaschineErste RückmeldungLetzte Rückmeldung
{cell}

Schichten

' + if not detail.shifts: + body += "

Keine Schichtzuordnung für konfigurierte Maschinen verfügbar.

" + else: + body += '
' + body += '' + body += '' + body += '' + for item in detail.shifts: + href = "/?" + urlencode({"date": item.date.isoformat(), "shift": item.shift, + "machine": item.machine_name}) + body += "" + "".join(f"" for cell in ( + escape(item.site.title()), escape(item.machine_name), + item.date.strftime("%d.%m.%Y"), + SHIFT_LABELS[item.shift], f"{item.produced_m2:,.2f} m²", + escape(item.first_confirmation.strftime("%d.%m.%Y %H:%M %Z")), + escape(item.last_confirmation.strftime("%d.%m.%Y %H:%M %Z")), + f'Schichtbericht', + )) + "" + body += "
StandortMaschineDatumSchichtProduzierte MengeErste RückmeldungLetzte RückmeldungBericht
{cell}
" + return _page(f"Fertigungsauftrag {detail.production_order}", body) diff --git a/src/production_analytics/presentation/shift_report_html.py b/src/production_analytics/presentation/shift_report_html.py index 88601a6..49012e9 100644 --- a/src/production_analytics/presentation/shift_report_html.py +++ b/src/production_analytics/presentation/shift_report_html.py @@ -117,7 +117,8 @@ width:220px; max-width:100%; margin:.75rem auto}} .material-swatch {{width:.9rem; height:.9rem; flex-shrink:0; margin-top:.2rem}} @media(max-width:850px) {{.material-layout {{grid-template-columns:minmax(0, 1fr)}}}} .error {{padding:1rem; background:#ffe8e5; border-left:4px solid #a32920}} -

Live-Schichtberichte

+
+

Live-Schichtberichte

diff --git a/src/production_analytics/service/production_order.py b/src/production_analytics/service/production_order.py new file mode 100644 index 0000000..61a868c --- /dev/null +++ b/src/production_analytics/service/production_order.py @@ -0,0 +1,155 @@ +"""Order-oriented view of positive ERP production confirmations.""" + +from collections import defaultdict +from collections.abc import Mapping +from dataclasses import dataclass +from datetime import UTC, date, datetime +from math import fsum +from typing import Literal, Protocol +from zoneinfo import ZoneInfo + +from production_analytics.calculations.shift_report import shift_containing +from production_analytics.erp.gateway import OrderConfirmationGroup, OrderConfirmationRow +from production_analytics.service.shift_report_config import ShiftReportMachineConfig + + +class ProductionOrderReader(Protocol): + def search_orders(self, query: str, *, limit: int = 25) -> list[OrderConfirmationGroup]: ... + def get_order_confirmations(self, production_order: str) -> list[OrderConfirmationRow]: ... + + +@dataclass(frozen=True, slots=True) +class ProductionOrderPlacement: + workplace: str + machine_name: str | None + site: str | None + timezone: ZoneInfo | None + article_number: str | None + article_description: str | None + first_confirmation_local: datetime + last_confirmation_local: datetime + mapping_status: Literal["configured", "unknown", "ambiguous"] + + +@dataclass(frozen=True, slots=True) +class ProductionOrderSearchResult: + production_order: str + placements: tuple[ProductionOrderPlacement, ...] + + +@dataclass(frozen=True, slots=True) +class ProductionOrderShift: + production_order: str + machine_name: str + workplace: str + site: str + timezone: ZoneInfo + date: date + shift: Literal["early", "late", "night"] + shift_start: datetime + shift_end: datetime + first_confirmation: datetime + last_confirmation: datetime + produced_m2: float + + +@dataclass(frozen=True, slots=True) +class ProductionOrderDetail: + production_order: str + placements: tuple[ProductionOrderPlacement, ...] + shifts: tuple[ProductionOrderShift, ...] + + +class ProductionOrderService: + """Resolve workplace and site timezone before assigning confirmation timestamps.""" + + def __init__(self, gateway: ProductionOrderReader, + machines: Mapping[str, ShiftReportMachineConfig]) -> None: + self.gateway = gateway + workplace_map = defaultdict(list) + for name, config in machines.items(): + workplace_map[config.erp_workplace].append((name, config)) + self._workplaces = dict(workplace_map) + + def _machine(self, workplace: str): + matches = self._workplaces.get(workplace, ()) + return matches[0] if len(matches) == 1 else None + + def _placement(self, workplace: str, article_number: str | None, + article_description: str | None, first: datetime, + last: datetime) -> ProductionOrderPlacement: + resolved = self._machine(workplace) + status = ("ambiguous" if len(self._workplaces.get(workplace, ())) > 1 else "unknown") + return ProductionOrderPlacement( + workplace=workplace, machine_name=resolved[0] if resolved else None, + site=resolved[1].site if resolved else None, + timezone=resolved[1].timezone if resolved else None, + article_number=article_number, article_description=article_description, + first_confirmation_local=first, last_confirmation_local=last, + mapping_status="configured" if resolved else status, + ) + + def search(self, query: str, *, limit: int = 25) -> tuple[ProductionOrderSearchResult, ...]: + query = _order_input(query) + if type(limit) is not int or not 1 <= limit <= 100: + raise ValueError("limit must be between 1 and 100") + groups = self.gateway.search_orders(query, limit=limit) + by_order = defaultdict(list) + for group in groups: + by_order[group.production_order].append(self._placement( + group.workplace, group.article_number, group.article_description, + group.first_confirmation_local, group.last_confirmation_local)) + orders = sorted(by_order, key=lambda order: (order != query, order))[:limit] + return tuple(ProductionOrderSearchResult( + order, tuple(sorted(by_order[order], key=lambda placement: ( + placement.workplace, placement.article_number or "", + placement.article_description or "")))) for order in orders) + + def detail(self, production_order: str) -> ProductionOrderDetail | None: + order = _order_input(production_order) + rows = self.gateway.get_order_confirmations(order) + if not rows: + return None + placements = defaultdict(list) + shifts = defaultdict(list) + for row in rows: + if row.production_order != order: + raise ValueError("ERP returned a different production order") + placements[(row.workplace, row.article_number, + row.article_description)].append(row) + resolved = self._machine(row.workplace) + if resolved is None: + continue + name, config = resolved + timestamp = row.timestamp_local.replace(tzinfo=config.timezone, fold=0) + day, shift, start, end = shift_containing(timestamp, config.timezone) + shifts[(name, day, shift, start, end)].append(row) + place_models = tuple(self._placement(workplace, article, description, + min(row.timestamp_local for row in grouped), + max(row.timestamp_local for row in grouped)) + for (workplace, article, description), grouped in sorted( + placements.items(), key=lambda item: tuple( + value or "" for value in item[0]))) + shift_models = [] + for (name, day, shift, start, end), grouped in shifts.items(): + config = self._machine(grouped[0].workplace)[1] + stamps = [row.timestamp_local.replace(tzinfo=config.timezone, fold=0) + for row in grouped] + shift_models.append(ProductionOrderShift( + production_order=order, machine_name=name, workplace=config.erp_workplace, + site=config.site, timezone=config.timezone, date=day, shift=shift, + shift_start=start, shift_end=end, + first_confirmation=min(stamps, key=lambda value: value.astimezone(UTC)), + last_confirmation=max(stamps, key=lambda value: value.astimezone(UTC)), + produced_m2=fsum(row.feedback_quantity_m2 for row in grouped), + )) + shift_models.sort(key=lambda item: (item.shift_start.astimezone(UTC), + item.machine_name)) + return ProductionOrderDetail(order, place_models, tuple(shift_models)) + + +def _order_input(value: str) -> str: + if (not isinstance(value, str) or not value.strip() or "\x00" in value + or len(value.strip()) > 80): + raise ValueError("production order must be 1–80 non-NUL characters") + return value.strip() diff --git a/src/production_analytics/web.py b/src/production_analytics/web.py index 6604d19..1be789c 100644 --- a/src/production_analytics/web.py +++ b/src/production_analytics/web.py @@ -12,6 +12,7 @@ from production_analytics.calculations.shift_report import ( most_recent_completed_shift, shift_report_window, ) +from production_analytics.presentation.production_order_html import render_detail, render_search from production_analytics.presentation.shift_report import render_pdf from production_analytics.presentation.shift_report_html import render_page from production_analytics.service.shift_report_config import load_shift_report_config @@ -21,7 +22,7 @@ SHIFT_LABELS = {"early": "Frühschicht", "late": "Spätschicht", "night": "Nacht def create_app(machines: Mapping, service_factory: Callable, *, sites: Mapping | None = None, - clock=None): + clock=None, order_service_factory: Callable | None = None): """Inject the configured service factory and clock without connecting at startup.""" clock = clock or (lambda: datetime.now(UTC)) @@ -29,6 +30,15 @@ def create_app(machines: Mapping, service_factory: Callable, *, sites: Mapping | headers = [("Cache-Control", "no-store"), ("X-Content-Type-Options", "nosniff")] status = "200 OK" content_type = "text/html; charset=utf-8" + path = environ.get("PATH_INFO", "/") + if path in ("/orders", "/order"): + status, payload = _order_response(environ, path, order_service_factory) + if status == "405 Method Not Allowed": + headers.append(("Allow", "GET")) + payload = payload.encode("utf-8") + headers.extend([("Content-Type", content_type), ("Content-Length", str(len(payload)))]) + start_response(status, headers) + return [payload] now = clock() machine = next(iter(machines)) timezone = machines[machine].timezone @@ -36,7 +46,7 @@ def create_app(machines: Mapping, service_factory: Callable, *, sites: Mapping | error = None report = None generated_at = None - if environ.get("PATH_INFO", "/") != "/": + if path != "/": status, error = "404 Not Found", "Seite nicht gefunden." elif environ.get("REQUEST_METHOD", "GET") != "GET": status, error = "405 Method Not Allowed", "Diese Anfrage wird nicht unterstützt." @@ -108,6 +118,41 @@ def create_app(machines: Mapping, service_factory: Callable, *, sites: Mapping | return app +def _order_response(environ, path: str, service_factory: Callable | None) -> tuple[str, str]: + if environ.get("REQUEST_METHOD", "GET") != "GET": + return "405 Method Not Allowed", render_search(error="Nur GET-Anfragen sind erlaubt.") + try: + params = parse_qs(environ.get("QUERY_STRING", ""), keep_blank_values=True, + max_num_fields=10) + key = "q" if path == "/orders" else "production_order" + if set(params) - {key} or any(len(values) != 1 for values in params.values()): + raise ValueError + if path == "/orders" and key not in params: + return "200 OK", render_search() + value = params[key][0].strip() + if not value or "\x00" in value or len(value) > 80: + raise ValueError + except (ValueError, KeyError): + message = "Bitte eine gültige Fertigungsauftragsnummer eingeben." + if path == "/orders": + return "400 Bad Request", render_search(error=message) + return "400 Bad Request", render_detail(detail=None, error=message) + try: + if service_factory is None: + raise RuntimeError("Order service unavailable") + service = service_factory() + if path == "/orders": + return "200 OK", render_search(query=value, results=service.search(value), + searched=True) + detail = service.detail(value) + return ("200 OK" if detail is not None else "404 Not Found"), render_detail(detail=detail) + except Exception: + message = "Fertigungsauftrag konnte nicht geladen werden. Bitte später erneut versuchen." + if path == "/orders": + return "503 Service Unavailable", render_search(query=value, error=message) + return "503 Service Unavailable", render_detail(detail=None, error=message) + + def main(argv=None): from production_analytics.enlyze.exploration import load_secret_file @@ -130,7 +175,16 @@ def main(argv=None): environment.update(load_secret_file(path)) return build_shift_report_service(machines, environment) - app = create_app(machines, service, sites=config.sites) + def order_service(): + from production_analytics.erp import ErpProductionConfirmationGateway, ErpSettings + from production_analytics.service.production_order import ProductionOrderService + + environment = {**os.environ, **load_secret_file(args.erp_secrets_file)} + gateway = ErpProductionConfirmationGateway(ErpSettings.from_environment(environment)) + return ProductionOrderService(gateway, machines) + + app = create_app(machines, service, sites=config.sites, + order_service_factory=order_service) with make_server(args.host, args.port, app) as server: print(f"Schichtberichte: http://{args.host}:{args.port}/", flush=True) server.serve_forever() diff --git a/tests/test_production_order.py b/tests/test_production_order.py new file mode 100644 index 0000000..7ec3688 --- /dev/null +++ b/tests/test_production_order.py @@ -0,0 +1,259 @@ +"""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, +) +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=()): + self.rows = list(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 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 "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 + + +def test_order_pages_escape_erp_text(): + unsafe = "" + gateway = FakeGateway( + rows=[OrderConfirmationRow(ORDER, "GITTERIII", "A", unsafe, + datetime(2026, 10, 19, 7), 1)], + groups=[OrderConfirmationGroup(ORDER, "GITTERIII", "A", unsafe, + datetime(2026, 10, 19, 7), + datetime(2026, 10, 19, 7))], + ) + app = web.create_app(MACHINES, lambda: None, + order_service_factory=lambda: ProductionOrderService(gateway, MACHINES)) + for path, query in (("/orders", "q=820264"), ("/order", f"production_order={ORDER}")): + assert "