Extend shift reporting and downtime analytics

This commit is contained in:
admin committed 2026-10-20 14:16:58 +02:00
1 parent 41a5ae7a63
commit 6e8eb6f50f
74 files changed
+5397 -238

No files matched your search

+92 -21
View File
@@ -10,6 +10,7 @@ from zoneinfo import ZoneInfo
import pymssql
from production_analytics.calculations.fiber_allocation import FiberBooking
from production_analytics.enlyze.exploration import ConfigurationError, load_secret_file
@@ -23,7 +24,10 @@ class ErpSettings:
def __post_init__(self) -> None:
for attribute, suffix in (
("host", "HOST"), ("database", "NAME"), ("user", "USER"), ("password", "PASSWORD"),
("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:
@@ -41,7 +45,8 @@ class ErpSettings:
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,
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", ""),
@@ -49,8 +54,10 @@ class ErpSettings:
@classmethod
def from_secret_file(
cls, path: str | os.PathLike[str] = "secrets/erp.env",
*, environment: Mapping[str, str] | None = None,
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:
@@ -98,9 +105,13 @@ class ErpWorkplaceStatusGateway:
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,
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,))
@@ -118,15 +129,17 @@ class ErpWorkplaceStatusGateway:
if len(row) != 10 or not isinstance(row[4], datetime):
raise ValueError
return CurrentWorkplaceStatus(
workplace=_text(row[0]), production_order=_text(row[1]),
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]
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]),
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:
@@ -203,8 +216,12 @@ class ErpProductionConfirmationGateway:
self._settings = settings
def get_confirmations(
self, *, workplace: str, start: datetime, end: datetime
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)):
@@ -212,15 +229,19 @@ class ErpProductionConfirmationGateway:
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(_PLANT_TIMEZONE).replace(tzinfo=None)
local_end = end.astimezone(_PLANT_TIMEZONE).replace(tzinfo=None)
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,
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(
@@ -230,18 +251,18 @@ class ErpProductionConfirmationGateway:
except Exception:
raise ErpReadError("ERP production confirmation read failed") from None
try:
return [_production_confirmation(row) for row in rows]
return [_production_confirmation(row, timezone) for row in rows]
except Exception:
raise ErpReadError("ERP production confirmation returned an invalid row") from None
def _production_confirmation(row: tuple[object, ...]) -> ProductionConfirmation:
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=_PLANT_TIMEZONE, fold=0),
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),
@@ -253,3 +274,53 @@ def _production_confirmation(row: tuple[object, ...]) -> ProductionConfirmation:
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