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(error)}
' + elif searched: + if not results: + body += "Keine passenden Fertigungsaufträge gefunden.
" + else: + body += '| FA | Artikel | ' + body += 'Artikelbezeichnung | Arbeitsplatz / Maschine | ' + body += 'Erste Rückmeldung | Letzte Rückmeldung |
|---|---|---|---|---|---|
| {cell} | " 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), + )) + "
{escape(error)}
') + if detail is None: + return _page("Fertigungsauftrag", "Fertigungsauftrag nicht gefunden.
") + body = f"| Artikel | Artikelbezeichnung | Arbeitsplatz / Maschine | ' + body += 'Erste Rückmeldung | Letzte Rückmeldung |
|---|---|---|---|---|
| {cell} | " 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), + )) + "
Keine Schichtzuordnung für konfigurierte Maschinen verfügbar.
" + else: + body += '| Standort | Maschine | ' + body += 'Datum | Schicht | Produzierte Menge | ' + body += 'Erste Rückmeldung | Letzte Rückmeldung | Bericht | ' + body += '
|---|---|---|---|---|---|---|---|
| {cell} | " 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', + )) + "