"""Focused read-only MSSQL boundaries for ERP status and confirmations.""" import os from collections.abc import Mapping from dataclasses import dataclass, field from datetime import UTC, datetime from decimal import Decimal from math import isfinite from zoneinfo import ZoneInfo import pymssql from production_analytics.calculations.fiber_allocation import FiberBooking from production_analytics.enlyze.exploration import ConfigurationError, load_secret_file @dataclass(frozen=True, slots=True) class ErpSettings: host: str port: int database: str user: str = field(repr=False) password: str = field(repr=False) def __post_init__(self) -> None: for attribute, suffix in ( ("host", "HOST"), ("database", "NAME"), ("user", "USER"), ("password", "PASSWORD"), ): value = getattr(self, attribute) if not isinstance(value, str) or not value.strip() or "\x00" in value: raise ConfigurationError(f"ERP_DB_{suffix} must be non-empty without NUL bytes") if type(self.port) is not int or not 1 <= self.port <= 65535: raise ConfigurationError("ERP_DB_PORT must be an integer from 1 to 65535") @classmethod def from_environment(cls, environment: Mapping[str, str]) -> "ErpSettings": raw_port = environment.get("ERP_DB_PORT", "") try: if not isinstance(raw_port, str): raise ValueError port = int(raw_port) except ValueError: raise ConfigurationError("ERP_DB_PORT must be an integer from 1 to 65535") from None return cls( host=environment.get("ERP_DB_HOST", ""), port=port, database=environment.get("ERP_DB_NAME", ""), user=environment.get("ERP_DB_USER", ""), password=environment.get("ERP_DB_PASSWORD", ""), ) @classmethod def from_secret_file( cls, path: str | os.PathLike[str] = "secrets/erp.env", *, environment: Mapping[str, str] | None = None, ) -> "ErpSettings": """Load dotenv values over the environment, following the existing convention.""" try: values = load_secret_file(path) except Exception: raise ConfigurationError("ERP secret file could not be loaded") from None base = os.environ if environment is None else environment return cls.from_environment({**base, **values}) @dataclass(frozen=True, slots=True) class CurrentWorkplaceStatus: """Latest ERP feedback with an aware timestamp; no freshness claim.""" workplace: str production_order: str article_number: str | None article_description: str | None feedback_timestamp: datetime order_quantity_m2: float | None good_quantity_m2: float | None remaining_quantity_m2: float | None remaining_time_hours: float | None remaining_rolls: float | None class ErpReadError(RuntimeError): """Safe operator-facing ERP read or result error.""" _CURRENT_STATUS_SQL = """SELECT [Arbeitsplatz], [Fertigungsauftragsnummer], [Artikelnummer], [Artikelbezeichnung], [Zeitstempel], [Auftragsmenge], [Gutmenge], [Restmenge], [Verbleibende Zeit], [Verbleibende Rollen] FROM [dbo].[GRAFANA_WORKPLACE_STATUS] WHERE [Arbeitsplatz] = %s""" class ErpWorkplaceStatusGateway: def __init__(self, settings: ErpSettings) -> None: self._settings = settings def get_current_workplace_status(self, workplace: str) -> CurrentWorkplaceStatus | None: if not isinstance(workplace, str) or not workplace.strip() or "\x00" in workplace: raise ValueError("workplace must be a non-empty string without NUL bytes") 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(_CURRENT_STATUS_SQL, (workplace,)) # Two rows suffice to detect a violation without selecting an arbitrary row. rows = cursor.fetchmany(2) except Exception: # Driver messages may include credentials; suppress their traceback chain too. raise ErpReadError("ERP current workplace status read failed") from None if not rows: return None if len(rows) > 1: raise ErpReadError("ERP current workplace status returned multiple rows") try: row = rows[0] if len(row) != 10 or not isinstance(row[4], datetime): raise ValueError return CurrentWorkplaceStatus( workplace=_text(row[0]), production_order=_text(row[1]), article_number=_text(row[2], nullable=True), article_description=_text(row[3], nullable=True), feedback_timestamp=( row[4].replace(tzinfo=_PLANT_TIMEZONE) if row[4].utcoffset() is None else row[4] ), order_quantity_m2=_number(row[5]), good_quantity_m2=_number(row[6]), remaining_quantity_m2=_number(row[7]), remaining_time_hours=_number(row[8]), remaining_rolls=_number(row[9]), ) except Exception: raise ErpReadError("ERP current workplace status returned an invalid row") from None def _text(value: object, *, nullable: bool = False) -> str | None: if value is None and nullable: return None if not isinstance(value, str): raise ValueError return value.rstrip() def _number(value: object) -> float | None: if value is None: return None if isinstance(value, bool) or not isinstance(value, (Decimal, int, float)): raise ValueError result = float(value) if not isfinite(result): raise ValueError return result _PLANT_TIMEZONE = ZoneInfo("Europe/Berlin") @dataclass(frozen=True, slots=True) class ProductionConfirmation: """Historical ERP view row; quantities follow the view's production semantics.""" workplace: str production_order: str timestamp: datetime article_number: str | None article_description: str | None roll_number: str | None production_quantity_m2: float | None feedback_quantity_m2: float | None raw_material_number: str | None raw_material_description: str | None batch_number: str | None raw_material_quantity: float | None tenant: str | None @property def is_finished_goods(self) -> bool: """Positive feedback identifies finished production, independently of workplace.""" return self.feedback_quantity_m2 is not None and self.feedback_quantity_m2 > 0 _PRODUCTION_CONFIRMATION_SQL = """SELECT [Mandant], [Fertigungsauftragsnummer], [Zeitstempel], [Arbeitsplatz], [Artikelnummer], [Artikelbezeichnung], [Rollennummer], [Fertigungsmenge], [Rohstoffnummer], [Rohstoffbezeichnung], [Chargennummer], [Rückmeldemenge], [Fasermenge] FROM [dbo].[GRAFANA_PRODUCTION_CONFIRMATION] WHERE [Arbeitsplatz] = %s AND [Zeitstempel] >= %s AND [Zeitstempel] < %s ORDER BY [Zeitstempel], [Mandant], [Fertigungsauftragsnummer], [Rollennummer], [Artikelnummer], [Rohstoffnummer], [Chargennummer], [Fertigungsmenge], [Rückmeldemenge], [Fasermenge], [Artikelbezeichnung], [Rohstoffbezeichnung]""" class ErpProductionConfirmationGateway: """Read complete view rows for an exact workplace and a plant-local [start, end). SQL datetime stores no offset or fold. Ambiguous autumn timestamps are attached with fold=0 (the first occurrence); the source cannot identify their actual fold. Windows whose local end does not follow their local start cannot be expressed by this SQL predicate and are rejected. Repeated hours cannot be queried separately. """ def __init__(self, settings: ErpSettings) -> None: self._settings = settings def get_confirmations( self, *, workplace: str, start: datetime, end: datetime, timezone: ZoneInfo | None = None, ) -> list[ProductionConfirmation]: timezone = _PLANT_TIMEZONE if timezone is None else timezone if not isinstance(timezone, ZoneInfo): raise ValueError("timezone must be a ZoneInfo") if not isinstance(workplace, str) or not workplace.strip() or "\x00" in workplace: raise ValueError("workplace must be a non-empty string without NUL bytes") for name, value in (("start", start), ("end", end)): if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None: raise ValueError(f"{name} must be a timezone-aware datetime") if end.astimezone(UTC) <= start.astimezone(UTC): raise ValueError("end must follow start") local_start = start.astimezone(timezone).replace(tzinfo=None) local_end = end.astimezone(timezone).replace(tzinfo=None) if local_end <= local_start: raise ValueError("end must follow start in plant-local SQL time") 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( _PRODUCTION_CONFIRMATION_SQL, (workplace.strip(), local_start, local_end) ) rows = cursor.fetchall() except Exception: raise ErpReadError("ERP production confirmation read failed") from None try: return [_production_confirmation(row, timezone) for row in rows] 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: raise ValueError return ProductionConfirmation( workplace=_text(row[3]), production_order=_text(row[1]), timestamp=row[2].replace(tzinfo=timezone, fold=0), article_number=_text(row[4], nullable=True), article_description=_text(row[5], nullable=True), roll_number=_text(row[6], nullable=True), production_quantity_m2=_number(row[7]), feedback_quantity_m2=_number(row[11]), raw_material_number=_text(row[8], nullable=True), raw_material_description=_text(row[9], nullable=True), batch_number=_text(row[10], nullable=True), raw_material_quantity=_number(row[12]), tenant=_text(row[0], nullable=True), ) _FIBER_BOOKING_SQL = """SELECT [Fertigungsauftragsnummer], [Rohstoffnummer], [Rohstoffbezeichnung], [Fasermenge] FROM [dbo].[GRAFANA_PRODUCTION_CONFIRMATION] WHERE [Fertigungsauftragsnummer] = %s AND [Fasermenge] > 0 AND NULLIF(LTRIM(RTRIM([Rohstoffnummer])), '') IS NOT NULL ORDER BY [Rohstoffnummer], [Rohstoffbezeichnung], [Fasermenge]""" class ErpFiberBookingGateway: """Order-wide positive raw-material bookings; never a measured shift quantity.""" def __init__(self, settings: ErpSettings) -> None: self._settings = settings def get_fiber_bookings(self, production_order: str) -> list[FiberBooking]: if ( not isinstance(production_order, str) or not production_order.strip() or "\x00" in production_order ): raise ValueError("production_order must be a non-empty string without NUL bytes") 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(_FIBER_BOOKING_SQL, (production_order.strip(),)) rows = cursor.fetchall() except Exception: raise ErpReadError("ERP fiber booking read failed") from None try: return [ FiberBooking( _text(row[0]), _text(row[1], nullable=True), _text(row[2], nullable=True), _number(row[3]), ) for row in rows ] except Exception: raise ErpReadError("ERP fiber booking returned an invalid row") from None