Add production order search and shift drill-down

This commit is contained in:
admin committed 2026-10-20 15:06:04 +02:00
1 parent 6e8eb6f50f
commit dcde029bc7
8 files changed
+742 -4

No files matched your search

@@ -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"]]:
+106
View File
@@ -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:
@@ -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'''<!doctype html><html lang="de"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{escape(title)}</title><style>
body {{font:16px system-ui,sans-serif;background:#f4f6f8;color:#182c3b;margin:0}}
main {{max-width:1100px;margin:2rem auto;padding:1.5rem;background:white}}
form {{display:flex;flex-wrap:wrap;gap:.7rem;align-items:end;padding:1rem;background:#e8eef3}}
label {{display:grid;gap:.4rem}} input,button {{font:inherit;padding:.55rem}}
table {{width:100%;border-collapse:collapse}} th,td {{text-align:left;padding:.7rem;
border-bottom:1px solid #c9d1d8}} th {{background:#e8eef3}}
.table-scroll {{overflow-x:auto}} .metadata {{color:#526473;font-size:.9rem}}
.error {{padding:1rem;background:#ffe8e5;border-left:4px solid #a32920}}
</style></head><body><main><nav><a href="/">Schichtberichte</a> ·
<a href="/orders">Fertigungsauftrag suchen</a></nav>{body}</main></body></html>'''
def _form(query: str) -> str:
return ('<form method="get" action="/orders"><label>Fertigungsauftrag (FA)'
f'<input type="search" name="q" value="{escape(query, quote=True)}"'
' maxlength="80" required></label><button type="submit">Suchen</button></form>')
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 = "<h1>Fertigungsauftrag suchen</h1>" + _form(query)
if error:
body += f'<p class="error" role="alert">{escape(error)}</p>'
elif searched:
if not results:
body += "<p>Keine passenden Fertigungsaufträge gefunden.</p>"
else:
body += '<div class="table-scroll"><table><thead><tr><th>FA</th><th>Artikel</th>'
body += '<th>Artikelbezeichnung</th><th>Arbeitsplatz / Maschine</th>'
body += '<th>Erste Rückmeldung</th><th>Letzte Rückmeldung</th></tr></thead><tbody>'
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'<a href="{escape(href, quote=True)}">'
f'{escape(result.production_order)}</a>')
body += "<tr>" + "".join(f"<td>{cell}</td>" 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),
)) + "</tr>"
body += "</tbody></table></div>"
return _page("Fertigungsauftrag suchen", body)
def render_detail(*, detail: ProductionOrderDetail | None,
error: str | None = None) -> str:
if error:
return _page("Fertigungsauftrag", f'<p class="error" role="alert">{escape(error)}</p>')
if detail is None:
return _page("Fertigungsauftrag", "<p>Fertigungsauftrag nicht gefunden.</p>")
body = f"<h1>Fertigungsauftrag {escape(detail.production_order)}</h1>"
body += '<p class="metadata">Zeiten sind ERP-Rückmeldezeitpunkte, keine durchgehenden '
body += 'Maschinenlaufzeiten. Mengen sind positive Rückmeldemengen in m².</p>'
body += '<h2>Artikel und Arbeitsplätze</h2><div class="table-scroll"><table><thead><tr>'
body += '<th>Artikel</th><th>Artikelbezeichnung</th><th>Arbeitsplatz / Maschine</th>'
body += '<th>Erste Rückmeldung</th><th>Letzte Rückmeldung</th></tr></thead><tbody>'
for placement in detail.placements:
machine = placement.machine_name or f"nicht zugeordnet ({placement.mapping_status})"
body += "<tr>" + "".join(f"<td>{cell}</td>" 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),
)) + "</tr>"
body += '</tbody></table></div><h2>Schichten</h2>'
if not detail.shifts:
body += "<p>Keine Schichtzuordnung für konfigurierte Maschinen verfügbar.</p>"
else:
body += '<div class="table-scroll"><table><thead><tr><th>Standort</th><th>Maschine</th>'
body += '<th>Datum</th><th>Schicht</th><th>Produzierte Menge</th>'
body += '<th>Erste Rückmeldung</th><th>Letzte Rückmeldung</th><th>Bericht</th>'
body += '</tr></thead><tbody>'
for item in detail.shifts:
href = "/?" + urlencode({"date": item.date.isoformat(), "shift": item.shift,
"machine": item.machine_name})
body += "<tr>" + "".join(f"<td>{cell}</td>" 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'<a href="{escape(href, quote=True)}">Schichtbericht</a>',
)) + "</tr>"
body += "</tbody></table></div>"
return _page(f"Fertigungsauftrag {detail.production_order}", body)
@@ -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}}
</style></head><body><main><h1>Live-Schichtberichte</h1>
</style></head><body><main><nav><a href="/orders">Fertigungsauftrag suchen</a></nav>
<h1>Live-Schichtberichte</h1>
<form method="get" action="/">
<label>Datum (Schichtbeginn)<input type="date" name="date" required
value="{day.isoformat()}"></label>
@@ -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()
+57 -3
View File
@@ -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()