Extend shift reporting and downtime analytics
This commit is contained in:
1 parent
41a5ae7a63
commit
6e8eb6f50f
74 files changed
+5397
-238
No files matched your search
@@ -62,6 +62,7 @@ class MaterialCalculationConfig:
|
||||
specific_discharge_kg_per_signal_unit_m: float | None = None
|
||||
erp_workplace: str = ""
|
||||
production_order_format: str = ""
|
||||
fallback_nominal_width_m: float | None = None
|
||||
process_application_calculation_id: str | None = None
|
||||
|
||||
|
||||
@@ -149,9 +150,14 @@ def load_material_calculation(
|
||||
except ValueError as exc:
|
||||
raise CalculationConfigError("Invalid production_order_format") from exc
|
||||
entry[refs_name] = tuple(refs)
|
||||
if "fallback_nominal_width_m" in entry:
|
||||
entry["fallback_nominal_width_m"] = finite_number(
|
||||
entry["fallback_nominal_width_m"],
|
||||
f"{prefix}.fallback_nominal_width_m", positive=True,
|
||||
)
|
||||
elif any(name in entry for name in (
|
||||
"application_signal_refs", "rotational_speed_signal_refs",
|
||||
"erp_workplace", "production_order_format",
|
||||
"erp_workplace", "production_order_format", "fallback_nominal_width_m",
|
||||
)):
|
||||
raise CalculationConfigError("Width context fields require a width-based source mode")
|
||||
if "calibration_ref" in entry:
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Allocate measured fiber mass using order-specific ERP booking weights."""
|
||||
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass, replace
|
||||
from math import fsum, isfinite
|
||||
|
||||
from production_analytics.calculations.shift_material import ShiftMaterialItem
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class FiberBooking:
|
||||
production_order: str
|
||||
material_number: str | None
|
||||
material_name: str | None
|
||||
quantity_kg: float | None
|
||||
|
||||
|
||||
def allocate_fiber_materials(
|
||||
item: ShiftMaterialItem, bookings: Iterable[FiberBooking], *, erp_order: str
|
||||
) -> tuple[ShiftMaterialItem, ...]:
|
||||
"""ERP quantities are weights only; the supplied measured mass is authoritative."""
|
||||
weights = defaultdict(list)
|
||||
for booking in bookings:
|
||||
quantity = booking.quantity_kg
|
||||
number = (booking.material_number or "").strip()
|
||||
if (
|
||||
booking.production_order != erp_order
|
||||
or not number
|
||||
or quantity is None
|
||||
or not isfinite(quantity)
|
||||
or quantity <= 0
|
||||
):
|
||||
continue
|
||||
name = (booking.material_name or "").strip() or None
|
||||
weights[(number, name)].append(quantity)
|
||||
totals = [
|
||||
(number, name, fsum(values))
|
||||
for (number, name), values in sorted(
|
||||
weights.items(), key=lambda entry: (entry[0][0], entry[0][1] or "")
|
||||
)
|
||||
]
|
||||
total = fsum(quantity for _, _, quantity in totals)
|
||||
if total <= 0:
|
||||
return (item,)
|
||||
return tuple(
|
||||
replace(
|
||||
item,
|
||||
consumption_kg=item.consumption_kg * (quantity / total),
|
||||
material_number=number,
|
||||
material_name=name,
|
||||
material_mapping_status="ERP_BOOKING_ESTIMATE",
|
||||
erp_booking_share=quantity / total,
|
||||
)
|
||||
for number, name, quantity in totals
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Machine-independent shift downtime from raw source intervals."""
|
||||
"""Machine-independent shift downtime from effective attribution intervals."""
|
||||
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterable
|
||||
@@ -18,6 +18,8 @@ class ShiftDowntimeEvent:
|
||||
reason_group: str | None
|
||||
category: str | None
|
||||
comment: str | None
|
||||
attributed_start: datetime | None = None
|
||||
attributed_end: datetime | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
for name in ("external_id", "machine_id"):
|
||||
@@ -25,6 +27,10 @@ class ShiftDowntimeEvent:
|
||||
if not isinstance(value, str) or not value.strip() or "\x00" in value:
|
||||
raise ValueError(f"{name} must be a non-empty string without NUL bytes")
|
||||
_aware(self.source_start, "source_start")
|
||||
for name in ("attributed_start", "attributed_end"):
|
||||
value = getattr(self, name)
|
||||
if value is not None:
|
||||
_aware(value, name)
|
||||
if self.source_end is not None:
|
||||
_aware(self.source_end, "source_end")
|
||||
if self.source_end.astimezone(UTC) < self.source_start.astimezone(UTC):
|
||||
@@ -85,12 +91,12 @@ def validate_downtime_window(*, machine_id: str, start: datetime, end: datetime)
|
||||
def aggregate_shift_downtime(
|
||||
events: Iterable[ShiftDowntimeEvent], *, machine_id: str, start: datetime, end: datetime
|
||||
) -> ShiftDowntimeSummary:
|
||||
"""Clip source intervals to [start, end); open events end at the shift end.
|
||||
"""Clip effective intervals to [start, end); open events end at the shift end.
|
||||
|
||||
Total downtime is the union of intervals. Each reason also uses a union within
|
||||
its full metadata group. Different reasons may overlap, so their durations need
|
||||
not sum to total downtime. Non-downtime is a time complement, not measured output.
|
||||
No production-order attribution fields participate in this calculation.
|
||||
Attribution timestamps take precedence, falling back to raw source timestamps.
|
||||
"""
|
||||
validate_downtime_window(machine_id=machine_id, start=start, end=end)
|
||||
lower, upper = start.astimezone(UTC), end.astimezone(UTC)
|
||||
@@ -98,12 +104,16 @@ def aggregate_shift_downtime(
|
||||
for event in events:
|
||||
if event.machine_id != machine_id:
|
||||
continue
|
||||
event_start = event.source_start.astimezone(UTC)
|
||||
event_end = upper if event.source_end is None else event.source_end.astimezone(UTC)
|
||||
effective_start = event.attributed_start or event.source_start
|
||||
effective_end = (
|
||||
event.attributed_end if event.attributed_end is not None else event.source_end
|
||||
)
|
||||
event_start = effective_start.astimezone(UTC)
|
||||
event_end = upper if effective_end is None else effective_end.astimezone(UTC)
|
||||
if event_start >= upper or event_end <= lower:
|
||||
continue
|
||||
clipped_start = start if event_start < lower else event.source_start
|
||||
clipped_end = end if event.source_end is None or event_end > upper else event.source_end
|
||||
clipped_start = start if event_start < lower else effective_start
|
||||
clipped_end = end if effective_end is None or event_end > upper else effective_end
|
||||
duration = (clipped_end.astimezone(UTC) - clipped_start.astimezone(UTC)).total_seconds()
|
||||
if duration > 0:
|
||||
clipped.append(ClippedShiftDowntimeEvent(event, clipped_start, clipped_end, duration))
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
"""Shift deltas from cumulative counters; no material identity is inferred."""
|
||||
"""Shift counter deltas with bounded, matching-identity channel gap bridging."""
|
||||
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from dataclasses import dataclass, replace
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from math import fsum, isfinite
|
||||
|
||||
MATERIAL_IDENTITY_GAP_LIMIT = timedelta(minutes=10)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftMaterialSnapshot:
|
||||
@@ -50,6 +52,7 @@ class ShiftMaterialItem:
|
||||
material_name: str | None = None
|
||||
material_mapping_status: str | None = None
|
||||
percentage_sum_valid: bool | None = None
|
||||
erp_booking_share: float | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -103,6 +106,7 @@ def aggregate_shift_material(
|
||||
makes no claim about source freshness or completeness.
|
||||
There is no interpolation or extrapolation at either boundary. Any within-run
|
||||
decrease raises ValueError, even if the final counter exceeds the baseline.
|
||||
Each delta belongs to the ending sample's order, consolidated by run/order.
|
||||
"""
|
||||
validate_material_window(
|
||||
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||
@@ -115,21 +119,24 @@ def aggregate_shift_material(
|
||||
items = []
|
||||
for rows in streams.values():
|
||||
for run in _runs(rows, start, channel=False):
|
||||
first, last = run[0], run[-1]
|
||||
_check_deltas(run, channel=False)
|
||||
items.append(
|
||||
ShiftMaterialItem(
|
||||
source="material_consumption_snapshots",
|
||||
calculation_id=first.calculation_id,
|
||||
machine_id=machine_id,
|
||||
production_order=first.production_order,
|
||||
run_id=first.run_id,
|
||||
consumption_kg=last.consumption_kg - first.consumption_kg,
|
||||
baseline_timestamp=first.timestamp,
|
||||
end_timestamp=last.timestamp,
|
||||
baseline_missing=_instant(first.timestamp) > _instant(start),
|
||||
missing = _instant(run[0].timestamp) > _instant(start)
|
||||
segment_items = []
|
||||
for previous, current in list(zip(run, run[1:])) or [(run[0], run[0])]:
|
||||
segment_items.append(
|
||||
ShiftMaterialItem(
|
||||
source="material_consumption_snapshots",
|
||||
calculation_id=current.calculation_id,
|
||||
machine_id=machine_id,
|
||||
production_order=current.production_order,
|
||||
run_id=current.run_id,
|
||||
consumption_kg=current.consumption_kg - previous.consumption_kg,
|
||||
baseline_timestamp=previous.timestamp,
|
||||
end_timestamp=current.timestamp,
|
||||
baseline_missing=missing,
|
||||
)
|
||||
)
|
||||
)
|
||||
items.extend(_consolidate_items(segment_items))
|
||||
return _summary(items, machine_id, start, end, include_zero)
|
||||
|
||||
|
||||
@@ -144,9 +151,9 @@ def aggregate_shift_channel_material(
|
||||
) -> ShiftMaterialSummary:
|
||||
"""For A -> B, attribute B.counter - A.counter to B's stored material identity.
|
||||
|
||||
Null/blank names remain null: no last-known carry-forward. Consecutive intervals
|
||||
with the same number/name/status form one material segment. A -> null -> A
|
||||
remains three segments. Counters and run boundaries follow the generic rules.
|
||||
After differencing, bridge unknown intervals only between identical known
|
||||
identities at most ten minutes apart in the same stream/run/order. Consolidate
|
||||
by final identity afterwards. Counters and run boundaries follow the generic rules.
|
||||
"""
|
||||
validate_material_window(
|
||||
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||
@@ -166,26 +173,22 @@ def aggregate_shift_channel_material(
|
||||
for previous, current in intervals:
|
||||
identity = _identity(current)
|
||||
delta = current.cumulative_consumption_kg - previous.cumulative_consumption_kg
|
||||
if segments and segments[-1].identity == identity:
|
||||
segment = segments[-1]
|
||||
segment.last = current
|
||||
segment.deltas.append(delta)
|
||||
segment.quality = segment.quality and current.percentage_sum_valid
|
||||
else:
|
||||
segments.append(
|
||||
_ChannelSegment(
|
||||
identity, previous, current, [delta], current.percentage_sum_valid
|
||||
)
|
||||
segments.append(
|
||||
_ChannelSegment(
|
||||
identity, previous, current, [delta], current.percentage_sum_valid
|
||||
)
|
||||
)
|
||||
_bridge_channel_identity_gaps(segments)
|
||||
segment_items = []
|
||||
for segment in segments:
|
||||
number, name, status = segment.identity
|
||||
first, last = segment.first, segment.last
|
||||
items.append(
|
||||
segment_items.append(
|
||||
ShiftMaterialItem(
|
||||
source="channel_material_consumption_snapshots",
|
||||
calculation_id=first.calculation_id,
|
||||
machine_id=machine_id,
|
||||
production_order=first.production_order,
|
||||
production_order=last.production_order,
|
||||
run_id=first.run_id,
|
||||
consumption_kg=fsum(segment.deltas),
|
||||
baseline_timestamp=first.timestamp,
|
||||
@@ -199,9 +202,84 @@ def aggregate_shift_channel_material(
|
||||
percentage_sum_valid=segment.quality,
|
||||
)
|
||||
)
|
||||
items.extend(_consolidate_items(segment_items))
|
||||
return _summary(items, machine_id, start, end, include_zero)
|
||||
|
||||
|
||||
def _bridge_channel_identity_gaps(intervals: list[_ChannelSegment]) -> None:
|
||||
"""Reassign already-differenced unknown intervals inside a bounded A/unknown/A gap.
|
||||
|
||||
The full enclosing sample span is used, including the return-to-known interval,
|
||||
so sparse sampling cannot turn a long outage into an apparently short gap.
|
||||
Enclosing samples must share an order within this physical stream/run.
|
||||
"""
|
||||
index = 0
|
||||
while index < len(intervals):
|
||||
if intervals[index].identity[:2] != (None, None):
|
||||
index += 1
|
||||
continue
|
||||
first = index
|
||||
while index < len(intervals) and intervals[index].identity[:2] == (None, None):
|
||||
index += 1
|
||||
if index == len(intervals):
|
||||
continue # No known identity after the gap.
|
||||
before = _identity(intervals[first].first)
|
||||
after = intervals[index].identity
|
||||
duration = _instant(intervals[index].last.timestamp) - _instant(
|
||||
intervals[first].first.timestamp
|
||||
)
|
||||
if (
|
||||
before[:2] != (None, None)
|
||||
and before == after
|
||||
and all(
|
||||
interval.first.production_order == intervals[first].first.production_order
|
||||
and interval.last.production_order == intervals[first].first.production_order
|
||||
for interval in intervals[first:index + 1]
|
||||
)
|
||||
and duration <= MATERIAL_IDENTITY_GAP_LIMIT
|
||||
):
|
||||
for interval in intervals[first:index]:
|
||||
interval.identity = before
|
||||
|
||||
|
||||
def _consolidate_items(items: list[ShiftMaterialItem]) -> list[ShiftMaterialItem]:
|
||||
groups = defaultdict(list)
|
||||
for item in items:
|
||||
key = (
|
||||
item.calculation_id,
|
||||
item.machine_id,
|
||||
item.production_order,
|
||||
item.run_id,
|
||||
item.extruder,
|
||||
item.doser_channel,
|
||||
item.material_number,
|
||||
item.material_name,
|
||||
item.material_mapping_status,
|
||||
)
|
||||
groups[key].append(item)
|
||||
consolidated = []
|
||||
# Explicit identity ordering also resolves any ties in the summary's time ordering.
|
||||
for key in sorted(
|
||||
groups, key=lambda key: tuple((part is not None, part or "") for part in key)
|
||||
):
|
||||
contributions = groups[key]
|
||||
consolidated.append(
|
||||
replace(
|
||||
contributions[0],
|
||||
consumption_kg=fsum(item.consumption_kg for item in contributions),
|
||||
baseline_timestamp=min(
|
||||
(item.baseline_timestamp for item in contributions), key=_instant
|
||||
),
|
||||
end_timestamp=max((item.end_timestamp for item in contributions), key=_instant),
|
||||
percentage_sum_valid=(
|
||||
None if contributions[0].percentage_sum_valid is None
|
||||
else all(item.percentage_sum_valid for item in contributions)
|
||||
),
|
||||
)
|
||||
)
|
||||
return consolidated
|
||||
|
||||
|
||||
def _runs(rows, start, *, channel):
|
||||
ordered = sorted(rows, key=lambda row: _instant(row.timestamp))
|
||||
if any(_instant(a.timestamp) == _instant(b.timestamp) for a, b in zip(ordered, ordered[1:])):
|
||||
@@ -214,21 +292,16 @@ def _runs(rows, start, *, channel):
|
||||
active -= 1
|
||||
selected = ordered[active:]
|
||||
runs = []
|
||||
seen = set()
|
||||
for row in selected:
|
||||
_identifier(row.run_id, "run_id")
|
||||
_identifier(row.production_order, "production_order")
|
||||
if not runs or runs[-1][-1].run_id != row.run_id:
|
||||
if row.run_id in seen:
|
||||
raise ValueError("Run reappeared after a different run in the same stream")
|
||||
seen.add(row.run_id)
|
||||
runs.append([])
|
||||
if runs[-1] and runs[-1][-1].production_order != row.production_order:
|
||||
raise ValueError("Production order changed within a run")
|
||||
runs[-1].append(row)
|
||||
for run in runs:
|
||||
valid = [
|
||||
row for row in run
|
||||
row
|
||||
for row in run
|
||||
if _valid_counter(row.cumulative_consumption_kg if channel else row.consumption_kg)
|
||||
]
|
||||
baseline = [row for row in valid if _instant(row.timestamp) <= _instant(start)]
|
||||
|
||||
@@ -13,8 +13,6 @@ from production_analytics.calculations.shift_material import ShiftMaterialSummar
|
||||
from production_analytics.calculations.shift_production import ShiftProductionSummary
|
||||
from production_analytics.calculations.shift_speed import ShiftSpeedSummary
|
||||
|
||||
SHIFT_TIMEZONE = ZoneInfo("Europe/Berlin")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftReportDowntimeReason:
|
||||
@@ -25,17 +23,20 @@ class ShiftReportDowntimeReason:
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftReport:
|
||||
machine_name: str
|
||||
machine_id: str
|
||||
machine_id: str | None
|
||||
start: datetime
|
||||
end: datetime
|
||||
production: ShiftProductionSummary
|
||||
downtime: ShiftDowntimeSummary
|
||||
materials: ShiftMaterialSummary
|
||||
speed: ShiftSpeedSummary
|
||||
production: ShiftProductionSummary | None
|
||||
downtime: ShiftDowntimeSummary | None
|
||||
materials: ShiftMaterialSummary | None
|
||||
speed: ShiftSpeedSummary | None
|
||||
timezone: ZoneInfo
|
||||
display_name: str | None = None
|
||||
site: str | None = None
|
||||
|
||||
@property
|
||||
def downtime_event_count(self) -> int:
|
||||
return len(self.downtime.events)
|
||||
return len(self.downtime.events) if self.downtime is not None else 0
|
||||
|
||||
@property
|
||||
def downtime_reasons(self) -> tuple[ShiftReportDowntimeReason, ...]:
|
||||
@@ -46,7 +47,7 @@ class ShiftReport:
|
||||
if reason.reason_name and reason.reason_name.strip()
|
||||
else "Ohne Stillstandsgrund",
|
||||
)
|
||||
for reason in self.downtime.reasons
|
||||
for reason in (self.downtime.reasons if self.downtime is not None else ())
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -56,21 +57,42 @@ class ShiftReport:
|
||||
|
||||
|
||||
def shift_report_window(
|
||||
day: date, shift: Literal["early", "late", "night"],
|
||||
day: date, shift: Literal["early", "late", "night"], timezone: ZoneInfo,
|
||||
) -> tuple[datetime, datetime]:
|
||||
"""Berlin wall-clock shifts; day denotes the shift's start date.
|
||||
"""Site-local wall-clock shifts; day denotes the shift's start date.
|
||||
|
||||
A night shift ends on the following calendar day, so elapsed duration may
|
||||
be seven or nine hours across DST. No fixed-duration arithmetic is used.
|
||||
"""
|
||||
if not isinstance(day, date) or isinstance(day, datetime):
|
||||
raise ValueError("day must be a calendar date")
|
||||
if not isinstance(timezone, ZoneInfo):
|
||||
raise ValueError("timezone must be a ZoneInfo")
|
||||
hours = {"early": (6, 14), "late": (14, 22), "night": (22, 6)}
|
||||
if shift not in hours:
|
||||
raise ValueError("shift must be early, late, or night")
|
||||
start_hour, end_hour = hours[shift]
|
||||
end_day = day + timedelta(days=1) if shift == "night" else day
|
||||
return (
|
||||
datetime.combine(day, time(start_hour), tzinfo=SHIFT_TIMEZONE),
|
||||
datetime.combine(end_day, time(end_hour), tzinfo=SHIFT_TIMEZONE),
|
||||
datetime.combine(day, time(start_hour), tzinfo=timezone),
|
||||
datetime.combine(end_day, time(end_hour), tzinfo=timezone),
|
||||
)
|
||||
|
||||
|
||||
def most_recent_completed_shift(
|
||||
now: datetime, timezone: ZoneInfo,
|
||||
) -> tuple[date, Literal["early", "late", "night"]]:
|
||||
"""Return start date and name of the last completed site-local shift."""
|
||||
if now.tzinfo is None or now.utcoffset() is None:
|
||||
raise ValueError("now must include a timezone")
|
||||
if not isinstance(timezone, ZoneInfo):
|
||||
raise ValueError("timezone must be a ZoneInfo")
|
||||
local = now.astimezone(timezone)
|
||||
day = local.date()
|
||||
if local.hour < 6:
|
||||
return day - timedelta(days=1), "late"
|
||||
if local.hour < 14:
|
||||
return day - timedelta(days=1), "night"
|
||||
if local.hour < 22:
|
||||
return day, "early"
|
||||
return day, "late"
|
||||
@@ -7,22 +7,68 @@ from math import isfinite
|
||||
from statistics import mean
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class NumericDwellGate:
|
||||
signal_ref: str
|
||||
threshold: float
|
||||
comparison: str
|
||||
minimum_duration_seconds: int
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if (not isinstance(self.signal_ref, str) or not self.signal_ref.strip()
|
||||
or "\x00" in self.signal_ref):
|
||||
raise ValueError("numeric_dwell_gate.signal_ref must be a non-empty string")
|
||||
if finite_speed(self.threshold) is None:
|
||||
raise ValueError("numeric_dwell_gate.threshold must be finite")
|
||||
if self.comparison not in ("below", "above"):
|
||||
raise ValueError("numeric_dwell_gate.comparison must be below or above")
|
||||
if (type(self.minimum_duration_seconds) is not int
|
||||
or self.minimum_duration_seconds <= 0):
|
||||
raise ValueError("numeric_dwell_gate.minimum_duration_seconds must be positive")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftSpeedConfig:
|
||||
machine_id: str
|
||||
speed_signal_ref: str
|
||||
production_gate_m_min: float
|
||||
production_gate_m_min: float | None = None
|
||||
unit: str = "m/min"
|
||||
signal: str = ""
|
||||
running_signal_ref: str | None = None
|
||||
running_when: bool = True
|
||||
numeric_dwell_gate: NumericDwellGate | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
for name in ("machine_id", "speed_signal_ref"):
|
||||
value = getattr(self, name)
|
||||
if not isinstance(value, str) or not value.strip() or "\x00" in value:
|
||||
raise ValueError(f"{name} must be a non-empty string without NUL bytes")
|
||||
if self.running_signal_ref is not None:
|
||||
value = self.running_signal_ref
|
||||
if not isinstance(value, str) or not value.strip() or "\x00" in value:
|
||||
raise ValueError("running_signal_ref must be a non-empty string without NUL bytes")
|
||||
if value == self.speed_signal_ref:
|
||||
raise ValueError("running_signal_ref must differ from speed_signal_ref")
|
||||
if type(self.running_when) is not bool:
|
||||
raise ValueError("running_when must be a boolean")
|
||||
if self.running_signal_ref is None and self.running_when is not True:
|
||||
raise ValueError("running_when requires running_signal_ref")
|
||||
if self.numeric_dwell_gate is not None:
|
||||
if not isinstance(self.numeric_dwell_gate, NumericDwellGate):
|
||||
raise ValueError("numeric_dwell_gate must be a NumericDwellGate")
|
||||
if self.numeric_dwell_gate.signal_ref == self.speed_signal_ref:
|
||||
raise ValueError("numeric dwell signal must differ from speed signal")
|
||||
if self.running_signal_ref is not None:
|
||||
raise ValueError("Boolean and numeric dwell gates are mutually exclusive")
|
||||
gate = finite_speed(self.production_gate_m_min)
|
||||
if gate is None or gate < 0:
|
||||
if (self.production_gate_m_min is not None and (gate is None or gate < 0)) or (
|
||||
self.running_signal_ref is None and self.numeric_dwell_gate is None and gate is None
|
||||
):
|
||||
raise ValueError("production_gate_m_min must be finite and non-negative")
|
||||
if self.numeric_dwell_gate is not None and self.production_gate_m_min is not None:
|
||||
raise ValueError("numeric dwell gate cannot use production_gate_m_min")
|
||||
if self.running_signal_ref is not None and self.production_gate_m_min is not None:
|
||||
raise ValueError("Boolean gate cannot use production_gate_m_min")
|
||||
if self.unit != "m/min":
|
||||
raise ValueError("Shift speed requires unit m/min")
|
||||
if not isinstance(self.signal, str):
|
||||
@@ -33,6 +79,8 @@ class ShiftSpeedConfig:
|
||||
class ShiftSpeedSample:
|
||||
timestamp: datetime | None
|
||||
value: object
|
||||
running: object = None
|
||||
gate_value: object = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -42,7 +90,7 @@ class ShiftSpeedSummary:
|
||||
end: datetime
|
||||
speed_signal_ref: str
|
||||
unit: str
|
||||
production_gate_m_min: float
|
||||
production_gate_m_min: float | None
|
||||
sample_count: int
|
||||
active_sample_count: int
|
||||
inactive_sample_count: int
|
||||
@@ -61,7 +109,7 @@ def aggregate_shift_speed(
|
||||
samples: Iterable[ShiftSpeedSample], *, config: ShiftSpeedConfig,
|
||||
start: datetime, end: datetime,
|
||||
) -> ShiftSpeedSummary:
|
||||
"""Count finite in-window samples; active iff value is strictly above gate.
|
||||
"""Count finite in-window samples; select activity by configured gate.
|
||||
|
||||
sample_count = active_sample_count + inactive_sample_count. Invalid values
|
||||
are counted separately, never converted to zero. Out-of-window samples are
|
||||
@@ -70,6 +118,9 @@ def aggregate_shift_speed(
|
||||
"""
|
||||
validate_speed_window(start, end)
|
||||
first, last = _instant(start), _instant(end)
|
||||
samples = list(samples)
|
||||
dwell_states = _dwell_states(samples, config.numeric_dwell_gate) if (
|
||||
config.numeric_dwell_gate is not None) else {}
|
||||
active = []
|
||||
count = invalid = 0
|
||||
for sample in samples:
|
||||
@@ -84,8 +135,20 @@ def aggregate_shift_speed(
|
||||
if value is None:
|
||||
invalid += 1
|
||||
continue
|
||||
if config.running_signal_ref is not None and type(sample.running) is not bool:
|
||||
invalid += 1
|
||||
continue
|
||||
if config.numeric_dwell_gate is not None and dwell_states.get(id(sample)) is None:
|
||||
invalid += 1
|
||||
continue
|
||||
count += 1
|
||||
if value > config.production_gate_m_min:
|
||||
if config.numeric_dwell_gate is not None:
|
||||
is_active = dwell_states[id(sample)]
|
||||
elif config.running_signal_ref is not None:
|
||||
is_active = sample.running is config.running_when
|
||||
else:
|
||||
is_active = value > config.production_gate_m_min
|
||||
if is_active:
|
||||
active.append(value)
|
||||
return ShiftSpeedSummary(
|
||||
machine_id=config.machine_id, start=start, end=end,
|
||||
@@ -100,6 +163,47 @@ def aggregate_shift_speed(
|
||||
)
|
||||
|
||||
|
||||
def _dwell_states(
|
||||
samples: list[ShiftSpeedSample], gate: NumericDwellGate,
|
||||
) -> dict[int, bool | None]:
|
||||
"""Classify each row from timestamped gate runs; None means unknown."""
|
||||
ordered = []
|
||||
for sample in samples:
|
||||
try:
|
||||
stamp = _instant(sample.timestamp)
|
||||
except ValueError:
|
||||
continue
|
||||
number = finite_speed(sample.gate_value)
|
||||
below = (number < gate.threshold if gate.comparison == "below"
|
||||
else number > gate.threshold) if number is not None else None
|
||||
ordered.append((stamp, sample, below))
|
||||
ordered.sort(key=lambda item: item[0])
|
||||
states: dict[int, bool | None] = {}
|
||||
cursor = 0
|
||||
while cursor < len(ordered):
|
||||
stamp, sample, condition = ordered[cursor]
|
||||
if condition is not True:
|
||||
states[id(sample)] = True if condition is False else None
|
||||
cursor += 1
|
||||
continue
|
||||
run_start = cursor
|
||||
while cursor < len(ordered) and ordered[cursor][2] is True:
|
||||
cursor += 1
|
||||
last_below = ordered[cursor - 1][0]
|
||||
closed = cursor < len(ordered) and ordered[cursor][2] is False
|
||||
finish = ordered[cursor][0] if closed else last_below
|
||||
duration = (finish - stamp).total_seconds()
|
||||
if duration >= gate.minimum_duration_seconds:
|
||||
state = False
|
||||
elif closed and run_start > 0 and ordered[run_start - 1][2] is False:
|
||||
state = True
|
||||
else:
|
||||
state = None
|
||||
for _, member, _ in ordered[run_start:cursor]:
|
||||
states[id(member)] = state
|
||||
return states
|
||||
|
||||
|
||||
def finite_speed(value: object) -> float | None:
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
return None
|
||||
|
||||
@@ -104,6 +104,18 @@ def _parser() -> argparse.ArgumentParser:
|
||||
default=Path("secrets/enlyze.env"),
|
||||
help="Local dotenv-style secret file (default: secrets/enlyze.env)",
|
||||
)
|
||||
historical = namespaces.add_parser("historical-reconcile", help="Repair historical attribution")
|
||||
historical.add_argument("--lookback-days", type=int, default=3)
|
||||
historical.add_argument("--dry-run", action="store_true")
|
||||
historical.add_argument("--verbose", action="store_true",
|
||||
help="Show individual record diagnostics as well as summaries")
|
||||
historical.add_argument("--config", type=Path,
|
||||
default=Path("config/shift-report-machines.yaml"))
|
||||
historical.add_argument("--order-formats", type=Path,
|
||||
default=Path("config/historical-order-formats.yaml"))
|
||||
historical.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env"))
|
||||
historical.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env"))
|
||||
historical.add_argument("--db-secrets-file", type=Path, default=Path("secrets/postgres.env"))
|
||||
run = namespaces.add_parser("run", help="Foreground production runners")
|
||||
runners = run.add_subparsers(dest="command", required=True)
|
||||
material = runners.add_parser("material-poll", help="Continuously poll material consumption")
|
||||
@@ -113,7 +125,9 @@ def _parser() -> argparse.ArgumentParser:
|
||||
material.add_argument("--state-directory", type=Path, default=Path("data/state/material"))
|
||||
material.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env"))
|
||||
material.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env"))
|
||||
power = runners.add_parser("power-meter", help="Collect configured ENLYZE power-meter telemetry")
|
||||
power = runners.add_parser(
|
||||
"power-meter", help="Collect configured ENLYZE power-meter telemetry",
|
||||
)
|
||||
power.add_argument("--config", type=Path, required=True)
|
||||
power.add_argument("--meter")
|
||||
power.add_argument("--start", help="ISO timestamp; defaults to one polling window ago")
|
||||
@@ -129,6 +143,16 @@ def _parser() -> argparse.ArgumentParser:
|
||||
monthly.add_argument("--month", required=True, help="YYYY-MM")
|
||||
monthly.add_argument("--db-secrets-file", type=Path, default=Path("secrets/postgres.env"))
|
||||
|
||||
shift = report_commands.add_parser("shift", help="Render one explicit shift report PDF")
|
||||
shift.add_argument("--config", type=Path, default=Path("config/shift-report-machines.yaml"))
|
||||
shift.add_argument("--machine", required=True)
|
||||
shift.add_argument("--start", required=True, help="ISO 8601 datetime with timezone")
|
||||
shift.add_argument("--end", required=True, help="ISO 8601 datetime with timezone")
|
||||
shift.add_argument("--output", type=Path, required=True)
|
||||
shift.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env"))
|
||||
shift.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env"))
|
||||
shift.add_argument("--db-secrets-file", type=Path, default=Path("secrets/postgres.env"))
|
||||
|
||||
channel_material = runners.add_parser(
|
||||
"channel-material-poll", help="Continuously poll channel-level material consumption"
|
||||
)
|
||||
@@ -258,8 +282,9 @@ def _parse_cli_timestamp(value: str) -> object:
|
||||
|
||||
|
||||
def _run_power_meter(args: argparse.Namespace) -> int:
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import time
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from production_analytics.calculations.config import CalculationConfigError
|
||||
from production_analytics.enlyze.exploration import ConfigurationError
|
||||
from production_analytics.power_meter.config import load_power_meter_config
|
||||
@@ -292,6 +317,7 @@ def _run_power_meter(args: argparse.Namespace) -> int:
|
||||
|
||||
|
||||
def _run_monthly_report(args: argparse.Namespace) -> int:
|
||||
from production_analytics.calculations.config import CalculationConfigError
|
||||
from production_analytics.enlyze.exploration import ConfigurationError
|
||||
from production_analytics.power_meter.config import load_power_meter_config
|
||||
from production_analytics.power_meter.repository import PostgresPowerMeterRepository
|
||||
@@ -300,7 +326,8 @@ def _run_monthly_report(args: argparse.Namespace) -> int:
|
||||
config = load_power_meter_config(args.config, args.meter)
|
||||
environment = _runtime_environment(args.db_secrets_file)
|
||||
from production_analytics.service.postgres_material import PostgresSettings
|
||||
path = monthly_report(config, PostgresPowerMeterRepository(PostgresSettings.from_environment(environment)), args.month)
|
||||
repository = PostgresPowerMeterRepository(PostgresSettings.from_environment(environment))
|
||||
path = monthly_report(config, repository, args.month)
|
||||
print(path)
|
||||
return 0
|
||||
except (CalculationConfigError, ConfigurationError, ValueError, RuntimeError) as exc:
|
||||
@@ -308,6 +335,36 @@ def _run_monthly_report(args: argparse.Namespace) -> int:
|
||||
return 2
|
||||
|
||||
|
||||
def _run_shift_report(args: argparse.Namespace) -> int:
|
||||
from production_analytics.calculations.shift_speed import validate_speed_window
|
||||
from production_analytics.enlyze.exploration import ConfigurationError
|
||||
from production_analytics.presentation.shift_report import write_pdf
|
||||
from production_analytics.service.shift_report_config import load_shift_report_machines
|
||||
from production_analytics.service.shift_report_runtime import build_shift_report_service
|
||||
|
||||
try:
|
||||
start = _parse_cli_timestamp(args.start)
|
||||
end = _parse_cli_timestamp(args.end)
|
||||
validate_speed_window(start, end)
|
||||
machines = load_shift_report_machines(args.config)
|
||||
if args.machine not in machines:
|
||||
raise ValueError(f"Unknown shift-report machine: {args.machine}")
|
||||
environment = _runtime_environment(
|
||||
args.secrets_file, args.erp_secrets_file, args.db_secrets_file,
|
||||
)
|
||||
service = build_shift_report_service(machines, environment)
|
||||
report = service.build(machine_name=args.machine, start=start, end=end)
|
||||
write_pdf(report, args.output)
|
||||
except (ValueError, ConfigurationError, ExplorationError) as exc:
|
||||
print(f"Report error: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
except Exception as exc:
|
||||
print(f"Report failed: {type(exc).__name__}", file=sys.stderr)
|
||||
return 1
|
||||
print(args.output)
|
||||
return 0
|
||||
|
||||
|
||||
def _run_downtime(args: argparse.Namespace) -> int:
|
||||
from production_analytics.service.downtime_runtime import build_downtime_runner
|
||||
|
||||
@@ -325,6 +382,17 @@ def _run_downtime(args: argparse.Namespace) -> int:
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
args = _parser().parse_args(argv)
|
||||
if args.namespace == "historical-reconcile":
|
||||
from production_analytics.service.historical_runtime import run
|
||||
|
||||
try:
|
||||
return run(args, _runtime_environment(
|
||||
args.secrets_file, args.erp_secrets_file, args.db_secrets_file,
|
||||
))
|
||||
except Exception as exc:
|
||||
print(f"Historical reconciliation failed: {type(exc).__name__}: {exc}",
|
||||
file=sys.stderr)
|
||||
return 1
|
||||
if args.namespace == "run":
|
||||
if args.command == "channel-material-poll":
|
||||
return _run_channel_material(args)
|
||||
@@ -336,6 +404,8 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
return _run_downtime(args)
|
||||
return _run_material(args)
|
||||
if args.namespace == "report":
|
||||
if args.command == "shift":
|
||||
return _run_shift_report(args)
|
||||
return _run_monthly_report(args)
|
||||
if args.namespace != "enlyze" or args.command not in {"raw", "timeseries"}:
|
||||
return 2
|
||||
|
||||
@@ -156,8 +156,10 @@ class EnlyzeApiGateway:
|
||||
|
||||
def get_speed_samples(
|
||||
self, *, machine_id: str, speed_signal_ref: str, start: datetime, end: datetime,
|
||||
running_signal_ref: str | None = None,
|
||||
numeric_gate_signal_ref: str | None = None,
|
||||
) -> list[ShiftSpeedSample]:
|
||||
"""Retrieve one bounded signal using the existing timeseries cursor contract.
|
||||
"""Retrieve bounded speed and optional status in one timeseries request.
|
||||
|
||||
Invalid/missing sample values remain unavailable for domain aggregation.
|
||||
Malformed timestamps/rows become invalid samples, while structural response
|
||||
@@ -167,11 +169,25 @@ class EnlyzeApiGateway:
|
||||
for name, value in (("machine_id", machine_id), ("speed_signal_ref", speed_signal_ref)):
|
||||
if not isinstance(value, str) or not value.strip() or "\x00" in value:
|
||||
raise ValueError(f"{name} must be a non-empty string without NUL bytes")
|
||||
if running_signal_ref is not None and numeric_gate_signal_ref is not None:
|
||||
raise ValueError("Speed activity gates are mutually exclusive")
|
||||
for name, signal_ref in (("running_signal_ref", running_signal_ref),
|
||||
("numeric_gate_signal_ref", numeric_gate_signal_ref)):
|
||||
if signal_ref is not None and (
|
||||
not isinstance(signal_ref, str) or not signal_ref.strip()
|
||||
or "\x00" in signal_ref or signal_ref == speed_signal_ref
|
||||
):
|
||||
raise ValueError(f"{name} must be a distinct non-empty string")
|
||||
variables = [{"uuid": speed_signal_ref}]
|
||||
if running_signal_ref is not None:
|
||||
variables.append({"uuid": running_signal_ref})
|
||||
if numeric_gate_signal_ref is not None:
|
||||
variables.append({"uuid": numeric_gate_signal_ref})
|
||||
body = {
|
||||
"machine": machine_id,
|
||||
"start": start.astimezone(UTC).isoformat(),
|
||||
"end": end.astimezone(UTC).isoformat(),
|
||||
"variables": [{"uuid": speed_signal_ref}],
|
||||
"variables": variables,
|
||||
}
|
||||
samples = []
|
||||
cursors: set[str] = set()
|
||||
@@ -181,14 +197,22 @@ class EnlyzeApiGateway:
|
||||
try:
|
||||
data = response.body["data"]
|
||||
columns = data["columns"]
|
||||
required = ["time", speed_signal_ref]
|
||||
if running_signal_ref is not None:
|
||||
required.append(running_signal_ref)
|
||||
if numeric_gate_signal_ref is not None:
|
||||
required.append(numeric_gate_signal_ref)
|
||||
if not isinstance(columns, list) or any(
|
||||
columns.count(column) != 1 for column in ("time", speed_signal_ref)
|
||||
columns.count(column) != 1 for column in required
|
||||
):
|
||||
raise ValueError("required columns must occur exactly once")
|
||||
records = data["records"]
|
||||
if not isinstance(records, list):
|
||||
raise ValueError("records must be a list")
|
||||
time_index, speed_index = columns.index("time"), columns.index(speed_signal_ref)
|
||||
running_index = columns.index(running_signal_ref) if running_signal_ref else None
|
||||
numeric_index = (columns.index(numeric_gate_signal_ref)
|
||||
if numeric_gate_signal_ref else None)
|
||||
for record in records:
|
||||
if not isinstance(record, list) or len(record) != len(columns):
|
||||
samples.append(ShiftSpeedSample(None, None))
|
||||
@@ -197,7 +221,11 @@ class EnlyzeApiGateway:
|
||||
timestamp = _parse_timestamp(record[time_index])
|
||||
except (TypeError, ValueError):
|
||||
timestamp = None
|
||||
samples.append(ShiftSpeedSample(timestamp, record[speed_index]))
|
||||
samples.append(ShiftSpeedSample(
|
||||
timestamp, record[speed_index],
|
||||
record[running_index] if running_index is not None else None,
|
||||
record[numeric_index] if numeric_index is not None else None,
|
||||
))
|
||||
cursor = _next_cursor(response.body)
|
||||
if cursor is None:
|
||||
return samples
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from production_analytics.erp.gateway import (
|
||||
CurrentWorkplaceStatus,
|
||||
ErpFiberBookingGateway,
|
||||
ErpProductionConfirmationGateway,
|
||||
ErpReadError,
|
||||
ErpSettings,
|
||||
@@ -11,6 +12,7 @@ from production_analytics.erp.gateway import (
|
||||
|
||||
__all__ = [
|
||||
"CurrentWorkplaceStatus",
|
||||
"ErpFiberBookingGateway",
|
||||
"ErpProductionConfirmationGateway",
|
||||
"ErpReadError",
|
||||
"ErpSettings",
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1 @@
|
||||
"""Output presenters independent of report composition and source access."""
|
||||
@@ -0,0 +1,315 @@
|
||||
"""German operational shift slips with deterministic A4 PDF output."""
|
||||
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from io import BytesIO
|
||||
from math import fsum
|
||||
from pathlib import Path
|
||||
from xml.sax.saxutils import escape
|
||||
|
||||
from production_analytics.calculations.shift_report import ShiftReport
|
||||
|
||||
|
||||
def _number(value: float) -> str:
|
||||
return f"{value:,.2f}".translate(str.maketrans({",": ".", ".": ","}))
|
||||
|
||||
|
||||
def _duration(seconds: float) -> str:
|
||||
hours, remainder = divmod(round(seconds, 1), 3600)
|
||||
minutes, seconds = divmod(remainder, 60)
|
||||
return f"{int(hours)} h {int(minutes):02d} min {seconds:04.1f} s".replace(".", ",")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class TextBlock:
|
||||
text: str
|
||||
style: str = "Normal"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class TableBlock:
|
||||
headers: tuple[str, ...]
|
||||
rows: tuple[tuple[str, ...], ...]
|
||||
widths_mm: tuple[float, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class MaterialPieBlock:
|
||||
labels: tuple[str, ...]
|
||||
consumption_kg: tuple[float, ...]
|
||||
|
||||
|
||||
def present_report(
|
||||
report: ShiftReport,
|
||||
*,
|
||||
include_single_material_chart: bool = False,
|
||||
) -> tuple[TextBlock | TableBlock | MaterialPieBlock, ...]:
|
||||
"""Format supplied values and material totals without source access or a clock."""
|
||||
story = []
|
||||
|
||||
def text(value: str, style: str = "Normal") -> None:
|
||||
story.append(TextBlock(value, style))
|
||||
|
||||
def table(headers: tuple[str, ...], rows: list[tuple], widths: list[float]) -> None:
|
||||
story.append(TableBlock(headers, tuple(rows), tuple(widths)))
|
||||
|
||||
text("Schichtbericht", "Title")
|
||||
text(f"Maschine: {report.display_name or report.machine_name}", "Heading2")
|
||||
for label, timestamp in (("Schichtbeginn", report.start), ("Schichtende", report.end)):
|
||||
text(f"{label}: {timestamp.astimezone(report.timezone):%d.%m.%Y %H:%M:%S %Z (%z)}")
|
||||
text(f"Zeitzone: {report.timezone.key}")
|
||||
text("Produktion", "Heading2")
|
||||
if report.production is None:
|
||||
text("Für diese Maschine nicht verfügbar.")
|
||||
elif report.production.items:
|
||||
table(
|
||||
("Produktionsauftrag", "Artikelnummer", "Artikelbeschreibung", "Menge", "Rollen"),
|
||||
[
|
||||
(
|
||||
item.production_order,
|
||||
item.article_number or "Nicht verfügbar",
|
||||
item.article_description or "Nicht verfügbar",
|
||||
f"{_number(item.produced_m2)} m²",
|
||||
str(item.roll_count),
|
||||
)
|
||||
for item in report.production.items
|
||||
],
|
||||
[36, 30, 62, 30, 20],
|
||||
)
|
||||
elif report.production is not None:
|
||||
text("Keine Produktionsdaten vorhanden.")
|
||||
if report.production is not None:
|
||||
text(
|
||||
f"Gesamtmenge: {_number(report.production.total_produced_m2)} m² | "
|
||||
f"Rollen gesamt: {report.production.total_roll_count}"
|
||||
)
|
||||
text("Stillstand", "Heading2")
|
||||
if report.downtime is None:
|
||||
text("Für diese Maschine nicht verfügbar.")
|
||||
else:
|
||||
text(f"Stillstand gesamt: {_duration(report.downtime.total_downtime_seconds)}")
|
||||
text("Zeit ohne erfassten Stillstand: " + _duration(report.downtime.non_downtime_seconds))
|
||||
text("Top 3 Stillstandsgründe", "Heading3")
|
||||
if report.top_downtime_reasons:
|
||||
table(
|
||||
("Stillstandsgrund", "Dauer"),
|
||||
[
|
||||
(view.display_name, _duration(view.reason.duration_seconds))
|
||||
for view in report.top_downtime_reasons
|
||||
],
|
||||
[125, 53],
|
||||
)
|
||||
else:
|
||||
text("Keine Stillstandsgründe vorhanden.")
|
||||
if not report.downtime.events:
|
||||
text("Keine Stillstandsereignisse vorhanden.")
|
||||
text("Materialverbrauch", "Heading2")
|
||||
if report.materials is None:
|
||||
text("Für diese Maschine nicht verfügbar.")
|
||||
else:
|
||||
material_totals = defaultdict(list)
|
||||
for item in report.materials.items:
|
||||
material_totals[(item.material_number, item.material_name)].append(item.consumption_kg)
|
||||
materials = [
|
||||
(number, name, fsum(quantities))
|
||||
for (number, name), quantities in sorted(
|
||||
material_totals.items(),
|
||||
key=lambda entry: (entry[0][1] or "", entry[0][0] or ""),
|
||||
)
|
||||
if fsum(quantities) != 0
|
||||
]
|
||||
if any(item.erp_booking_share is not None for item in report.materials.items):
|
||||
allocation_totals = defaultdict(list)
|
||||
for item in report.materials.items:
|
||||
allocation_totals[
|
||||
(
|
||||
item.production_order,
|
||||
item.material_number,
|
||||
item.material_name,
|
||||
item.erp_booking_share,
|
||||
)
|
||||
].append(item.consumption_kg)
|
||||
rows = []
|
||||
for (order, number, name, share), quantities in sorted(
|
||||
allocation_totals.items(),
|
||||
key=lambda entry: (
|
||||
entry[0][0],
|
||||
entry[0][2] or "",
|
||||
entry[0][1] or "",
|
||||
-1 if entry[0][3] is None else entry[0][3],
|
||||
),
|
||||
):
|
||||
quantity = fsum(quantities)
|
||||
if quantity != 0:
|
||||
rows.append(
|
||||
(
|
||||
order,
|
||||
name or number or "Materialzuordnung fehlt",
|
||||
number or "–",
|
||||
f"{_number(quantity)} kg",
|
||||
f"{share * 100:.0f}%" if share is not None else "–",
|
||||
)
|
||||
)
|
||||
if rows:
|
||||
table(
|
||||
("Produktionsauftrag", "Materialname", "Materialnummer", "Verbrauch",
|
||||
"ERP-Anteil"),
|
||||
rows,
|
||||
[32, 66, 28, 30, 22],
|
||||
)
|
||||
else:
|
||||
text("Keine Materialverbrauchsdaten vorhanden.")
|
||||
text(
|
||||
"Verbrauchsaufteilung geschätzt nach ERP-Buchungsverhältnis; "
|
||||
"Gesamtverbrauch aus ENLYZE."
|
||||
)
|
||||
elif materials:
|
||||
table(
|
||||
("Materialname", "Materialnummer", "Verbrauch"),
|
||||
[
|
||||
(
|
||||
name or number or "Materialzuordnung fehlt",
|
||||
number or "–",
|
||||
f"{_number(quantity)} kg",
|
||||
)
|
||||
for number, name, quantity in materials
|
||||
],
|
||||
[110, 38, 30],
|
||||
)
|
||||
else:
|
||||
text("Keine Materialverbrauchsdaten vorhanden.")
|
||||
text(f"Materialverbrauch gesamt: {_number(report.materials.total_consumption_kg)} kg")
|
||||
positive_materials = [
|
||||
(number, name, quantity) for number, name, quantity in materials if quantity > 0
|
||||
]
|
||||
if len(positive_materials) >= (1 if include_single_material_chart else 2):
|
||||
base_labels = [
|
||||
name or number or "Materialzuordnung fehlt"
|
||||
for number, name, _ in positive_materials
|
||||
]
|
||||
labels = tuple(
|
||||
f"{label} ({number or 'ohne Materialnummer'})"
|
||||
if base_labels.count(label) > 1
|
||||
else label
|
||||
for label, (number, _, _) in zip(base_labels, positive_materials)
|
||||
)
|
||||
story.append(
|
||||
MaterialPieBlock(labels, tuple(quantity for _, _, quantity in positive_materials))
|
||||
)
|
||||
text("Liniengeschwindigkeit", "Heading2")
|
||||
if report.speed is None:
|
||||
text("Für diese Maschine nicht verfügbar.")
|
||||
else:
|
||||
speed = report.speed.average_line_speed_m_min
|
||||
text(
|
||||
"Durchschnittliche Liniengeschwindigkeit im Lauf: "
|
||||
+ (f"{_number(speed)} m/min" if speed is not None
|
||||
else "Nicht verfügbar (keine Laufdaten).")
|
||||
)
|
||||
|
||||
return tuple(story)
|
||||
|
||||
|
||||
def render_pdf(report: ShiftReport) -> bytes:
|
||||
"""Repeatable bytes with the same ReportLab version and invariant metadata."""
|
||||
from reportlab.graphics.charts.piecharts import Pie
|
||||
from reportlab.graphics.shapes import Drawing, Rect
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.pagesizes import A4
|
||||
from reportlab.lib.styles import getSampleStyleSheet
|
||||
from reportlab.lib.units import mm
|
||||
from reportlab.pdfgen.canvas import Canvas
|
||||
from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle
|
||||
|
||||
styles = getSampleStyleSheet()
|
||||
styles["Normal"].fontSize = 9
|
||||
styles["Normal"].leading = 12
|
||||
|
||||
def paragraph(value: str, style: str = "Normal") -> Paragraph:
|
||||
return Paragraph(escape(value).replace("\n", "<br/>"), styles[style])
|
||||
|
||||
story = []
|
||||
for block in present_report(report):
|
||||
if isinstance(block, TextBlock):
|
||||
story.extend([paragraph(block.text, block.style), Spacer(1, 3 * mm)])
|
||||
elif isinstance(block, MaterialPieBlock):
|
||||
palette = tuple(
|
||||
colors.HexColor(value)
|
||||
for value in ("#496a81", "#8aa399", "#c4ad7a", "#9a869f", "#8399b0", "#b78e7c")
|
||||
)
|
||||
drawing = Drawing(65 * mm, 60 * mm)
|
||||
pie = Pie()
|
||||
pie.x, pie.y = 5 * mm, 2 * mm
|
||||
pie.width = pie.height = 55 * mm
|
||||
pie.data = list(block.consumption_kg)
|
||||
pie.labels = []
|
||||
pie.slices.strokeColor = colors.white
|
||||
pie.slices.strokeWidth = 0.5
|
||||
legend_rows = []
|
||||
for index, label in enumerate(block.labels):
|
||||
color = palette[index % len(palette)]
|
||||
pie.slices[index].fillColor = color
|
||||
swatch = Drawing(4 * mm, 4 * mm)
|
||||
swatch.add(Rect(0, 0, 4 * mm, 4 * mm, fillColor=color, strokeColor=None))
|
||||
legend_rows.append([swatch, paragraph(label)])
|
||||
drawing.add(pie)
|
||||
legend = Table(legend_rows, colWidths=[8 * mm, 101 * mm])
|
||||
legend.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP")]))
|
||||
chart = Table([[drawing, legend]], colWidths=[65 * mm, 113 * mm], splitInRow=1)
|
||||
chart.setStyle(
|
||||
TableStyle(
|
||||
[
|
||||
("VALIGN", (0, 0), (-1, -1), "TOP"),
|
||||
("LEFTPADDING", (0, 0), (-1, -1), 0),
|
||||
("RIGHTPADDING", (0, 0), (-1, -1), 0),
|
||||
]
|
||||
)
|
||||
)
|
||||
story.extend([chart, Spacer(1, 4 * mm)])
|
||||
else:
|
||||
cells = [[paragraph(value) for value in row] for row in [block.headers, *block.rows]]
|
||||
result = Table(cells, colWidths=[width * mm for width in block.widths_mm], repeatRows=1)
|
||||
result.setStyle(
|
||||
TableStyle(
|
||||
[
|
||||
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#e8eef3")),
|
||||
("VALIGN", (0, 0), (-1, -1), "TOP"),
|
||||
("LINEBELOW", (0, 0), (-1, -1), 0.3, colors.HexColor("#c9d1d8")),
|
||||
("TOPPADDING", (0, 0), (-1, -1), 6),
|
||||
("BOTTOMPADDING", (0, 0), (-1, -1), 6),
|
||||
]
|
||||
)
|
||||
)
|
||||
story.extend([result, Spacer(1, 4 * mm)])
|
||||
|
||||
buffer = BytesIO()
|
||||
document = SimpleDocTemplate(
|
||||
buffer,
|
||||
pagesize=A4,
|
||||
leftMargin=16 * mm,
|
||||
rightMargin=16 * mm,
|
||||
topMargin=16 * mm,
|
||||
bottomMargin=16 * mm,
|
||||
title="Schichtbericht",
|
||||
author="Production Analytics",
|
||||
pageCompression=0,
|
||||
)
|
||||
|
||||
def canvas(*args, **kwargs):
|
||||
kwargs["invariant"] = 1
|
||||
return Canvas(*args, **kwargs)
|
||||
|
||||
def footer(canvas, document):
|
||||
canvas.saveState()
|
||||
canvas.setFont("Helvetica", 8)
|
||||
canvas.drawRightString(A4[0] - 16 * mm, 10 * mm, f"Seite {document.page}")
|
||||
canvas.restoreState()
|
||||
|
||||
document.build(story, canvasmaker=canvas, onFirstPage=footer, onLaterPages=footer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def write_pdf(report: ShiftReport, output: Path) -> None:
|
||||
payload = render_pdf(report)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_bytes(payload)
|
||||
@@ -0,0 +1,130 @@
|
||||
"""HTML formatting of the shared report presentation; no data-source access."""
|
||||
|
||||
from html import escape
|
||||
from math import fsum
|
||||
|
||||
from production_analytics.presentation.shift_report import (
|
||||
MaterialPieBlock,
|
||||
TableBlock,
|
||||
TextBlock,
|
||||
_number,
|
||||
present_report,
|
||||
)
|
||||
|
||||
|
||||
def _material_chart(block: MaterialPieBlock) -> str:
|
||||
"""Draw supplied material slices; percentages are presentation geometry only.
|
||||
|
||||
No scripts or external assets: source labels are escaped HTML/SVG text.
|
||||
The adjacent shared material table remains the textual source of truth.
|
||||
"""
|
||||
palette = ("#496a81", "#8aa399", "#c4ad7a", "#9a869f", "#8399b0", "#b78e7c")
|
||||
total = fsum(block.consumption_kg)
|
||||
slices, legend = [], []
|
||||
offset = 0.0
|
||||
for index, (label, kg) in enumerate(zip(block.labels, block.consumption_kg)):
|
||||
percent = kg / total * 100
|
||||
color = palette[index % len(palette)]
|
||||
description = f"{label}: {_number(kg)} kg ({_number(percent)} %)"
|
||||
slices.append(
|
||||
f'<circle cx="60" cy="60" r="44" pathLength="100" fill="none" '
|
||||
f'stroke="{color}" stroke-width="22" '
|
||||
f'stroke-dasharray="{percent:.8f} {100 - percent:.8f}" '
|
||||
f'stroke-dashoffset="{-offset:.8f}" transform="rotate(-90 60 60)">'
|
||||
f"<title>{escape(description)}</title></circle>"
|
||||
)
|
||||
legend.append(
|
||||
f'<li><span class="material-swatch" style="background:{color}" '
|
||||
f'aria-hidden="true"></span><span>{escape(description)}</span></li>'
|
||||
)
|
||||
offset += percent
|
||||
return (
|
||||
'<figure class="material-chart"><figcaption>Verbrauchsanteile nach Material</figcaption>'
|
||||
'<svg viewBox="0 0 120 120" role="img" aria-label="Materialverbrauch in kg">'
|
||||
"<title>Verbrauchsanteile nach Material; Werte in der Legende</title>"
|
||||
+ "".join(slices)
|
||||
+ '</svg><ul class="material-legend">'
|
||||
+ "".join(legend)
|
||||
+ '</ul><p class="metadata">Anteile der positiven Verbrauchsmengen.</p></figure>'
|
||||
)
|
||||
|
||||
|
||||
def render_page(*, machines, labels, day, shift, machine, report, generated_at, error,
|
||||
sites=None):
|
||||
machine_labels = ((key, getattr(config, "display_name", key))
|
||||
for key, config in machines.items())
|
||||
def options(values, selected):
|
||||
return "".join(
|
||||
f'<option value="{escape(key, quote=True)}"'
|
||||
+ (" selected" if key == selected else "")
|
||||
+ f">{escape(label)}</option>"
|
||||
for key, label in values
|
||||
)
|
||||
|
||||
body = ""
|
||||
if error:
|
||||
body = f'<p class="error" role="alert">{escape(error)}</p>'
|
||||
if report is not None:
|
||||
body += (
|
||||
f'<p class="metadata">Datenstand: {generated_at:%d.%m.%Y %H:%M:%S %Z} '
|
||||
f"({report.timezone.key}). Quellen können nachträglich korrigiert werden.</p>"
|
||||
)
|
||||
material_open = False
|
||||
details_open = False
|
||||
for block in present_report(report, include_single_material_chart=True):
|
||||
if isinstance(block, TextBlock):
|
||||
if material_open and block.style == "Heading2":
|
||||
body += ("</div>" if details_open else "") + "</div></section>"
|
||||
material_open = details_open = False
|
||||
if block.text == "Materialverbrauch" and block.style == "Heading2":
|
||||
body += (
|
||||
'<section class="material-section"><h2>Materialverbrauch</h2>'
|
||||
'<div class="material-layout"><div class="material-details">'
|
||||
)
|
||||
material_open = details_open = True
|
||||
continue
|
||||
tag = {"Title": "h1", "Heading2": "h2", "Heading3": "h3"}.get(block.style, "p")
|
||||
body += f"<{tag}>{escape(block.text)}</{tag}>"
|
||||
elif isinstance(block, TableBlock):
|
||||
body += '<div class="table-scroll"><table><thead><tr>'
|
||||
body += "".join(f'<th scope="col">{escape(cell)}</th>' for cell in block.headers)
|
||||
body += "</tr></thead><tbody>"
|
||||
for row in block.rows:
|
||||
body += "<tr>" + "".join(f"<td>{escape(cell)}</td>" for cell in row) + "</tr>"
|
||||
body += "</tbody></table></div>"
|
||||
elif isinstance(block, MaterialPieBlock):
|
||||
body += "</div>" + _material_chart(block)
|
||||
details_open = False
|
||||
if material_open:
|
||||
body += ("</div>" if details_open else "") + "</div></section>"
|
||||
return f'''<!doctype html>
|
||||
<html lang="de"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Live-Schichtberichte</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:1rem; align-items:end; padding:1rem;
|
||||
background:#e8eef3}} label {{display:grid; gap:.4rem}}
|
||||
input,select,button {{font:inherit; padding:.55rem}} button {{cursor:pointer}}
|
||||
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}}
|
||||
.material-layout {{display:grid; grid-template-columns:minmax(0, 1fr) 300px; gap:1.5rem}}
|
||||
.material-chart {{margin:0; min-width:0}} .material-chart svg {{display:block;
|
||||
width:220px; max-width:100%; margin:.75rem auto}}
|
||||
.material-chart figcaption {{font-weight:600}} .material-legend {{list-style:none; padding:0}}
|
||||
.material-legend li {{display:flex; gap:.5rem; margin:.6rem 0; overflow-wrap:anywhere}}
|
||||
.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>
|
||||
<form method="get" action="/">
|
||||
<label>Datum (Schichtbeginn)<input type="date" name="date" required
|
||||
value="{day.isoformat()}"></label>
|
||||
<label>Schicht<select name="shift">{options(labels.items(), shift)}</select></label>
|
||||
<label>Maschine<select name="machine">{options(machine_labels, machine)}
|
||||
</select></label>
|
||||
<button type="submit">Bericht anzeigen</button>
|
||||
<button type="submit" name="format" value="pdf">Als PDF exportieren</button>
|
||||
</form><p class="metadata">Nachtschicht: 22:00 Uhr am gewählten Datum bis 06:00 Uhr
|
||||
am Folgetag. Jeder Aufruf liest die aktuellen Quelldaten.</p>{body}</main></body></html>'''
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Explicit K7 order adapter; generic measured material calculation stays ERP-free."""
|
||||
|
||||
import re
|
||||
from dataclasses import replace
|
||||
from typing import Protocol
|
||||
|
||||
from production_analytics.calculations.fiber_allocation import (
|
||||
FiberBooking,
|
||||
allocate_fiber_materials,
|
||||
)
|
||||
from production_analytics.calculations.shift_material import ShiftMaterialSummary
|
||||
|
||||
|
||||
class FiberBookingReader(Protocol):
|
||||
def get_fiber_bookings(self, production_order: str) -> list[FiberBooking]: ...
|
||||
|
||||
|
||||
class K7FiberAllocationService:
|
||||
def __init__(self, reader: FiberBookingReader) -> None:
|
||||
self.reader = reader
|
||||
|
||||
def allocate(self, measured: ShiftMaterialSummary) -> ShiftMaterialSummary:
|
||||
bookings = {}
|
||||
items = []
|
||||
for item in measured.items:
|
||||
match = re.fullmatch(r"(?:K 7-)?([0-9]+)", item.production_order.strip())
|
||||
if match is None:
|
||||
items.append(item)
|
||||
continue
|
||||
order = match[1]
|
||||
if order not in bookings:
|
||||
bookings[order] = self.reader.get_fiber_bookings(order)
|
||||
items.extend(allocate_fiber_materials(item, bookings[order], erp_order=order))
|
||||
# Keep the measured shift total, rather than replacing it with an ERP total.
|
||||
return replace(measured, items=tuple(items))
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Conservative historical attribution decisions and orchestration, without SQL."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, time, timedelta
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from production_analytics.context import build_enlyze_production_order
|
||||
|
||||
BERLIN = ZoneInfo("Europe/Berlin")
|
||||
|
||||
|
||||
def reconciliation_window(now: datetime, lookback_days: int = 3):
|
||||
"""Previous N complete Berlin calendar days, as a half-open interval."""
|
||||
if now.utcoffset() is None or isinstance(lookback_days, bool) or lookback_days < 1:
|
||||
raise ValueError("An aware clock and positive lookback-days are required")
|
||||
end = datetime.combine(now.astimezone(BERLIN).date(), time(), BERLIN)
|
||||
return end - timedelta(days=lookback_days), end
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HistoricalRecord:
|
||||
table: str
|
||||
identity: tuple
|
||||
machine_id: str
|
||||
timestamp: datetime
|
||||
production_order: str
|
||||
run_id: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Decision:
|
||||
record: HistoricalRecord
|
||||
order: str | None
|
||||
reason: str
|
||||
desired_run_id: str | None = None
|
||||
|
||||
|
||||
def decide(record, runs, confirmations, workplace, format_template):
|
||||
"""Keep physical counter/run identities; never infer boundaries from ERP points."""
|
||||
candidates = [r for r in runs if r.machine_id == record.machine_id
|
||||
and r.start.timestamp() <= record.timestamp.timestamp()
|
||||
and (r.end is None or record.timestamp.timestamp() < r.end.timestamp())]
|
||||
if len(candidates) != 1 or candidates[0].end is None:
|
||||
return Decision(record, None, "unresolved: missing or overlapping closed ENLYZE runs")
|
||||
run = candidates[0]
|
||||
orders = {build_enlyze_production_order(c.production_order, format_template)
|
||||
for c in confirmations if c.workplace == workplace and c.is_finished_goods
|
||||
and run.start.timestamp() < c.timestamp.timestamp() < run.end.timestamp()}
|
||||
if orders != {run.production_order}:
|
||||
return Decision(record, None, "unresolved: ERP evidence missing or conflicts with ENLYZE")
|
||||
return Decision(record, run.production_order,
|
||||
f"closed ENLYZE run {run.uuid} [{run.start.isoformat()}, "
|
||||
f"{run.end.isoformat()}) corroborated by ERP order {run.production_order}",
|
||||
run.uuid)
|
||||
|
||||
|
||||
def reconcile_machine(repository, source, erp, config, template, start, end, dry_run=False):
|
||||
records = repository.read(config.machine_id, start, end)
|
||||
runs = source.get_production_runs(config.machine_id)
|
||||
# Query complete overlapping runs so partial-window evidence cannot conceal conflicts.
|
||||
relevant = [r for r in runs if r.end is not None
|
||||
and r.start.timestamp() < end.timestamp() and r.end.timestamp() > start.timestamp()]
|
||||
evidence_start = min([start, *(r.start for r in relevant)], key=datetime.timestamp)
|
||||
evidence_end = max([end, *(r.end for r in relevant)], key=datetime.timestamp)
|
||||
confirmations = erp.get_confirmations(
|
||||
workplace=config.erp_workplace, start=evidence_start, end=evidence_end,
|
||||
)
|
||||
decisions = [decide(r, runs, confirmations, config.erp_workplace, template) for r in records]
|
||||
# Require complete, unambiguous evidence, allowing orders within a physical run.
|
||||
decisions = repository.guard_runs(decisions)
|
||||
applied = repository.apply(decisions) if not dry_run else 0
|
||||
return decisions, applied
|
||||
|
||||
|
||||
def grouped_counts(decisions):
|
||||
"""Count physical identities and contiguous attribution segments, not snapshot rows."""
|
||||
groups = {}
|
||||
for d in decisions:
|
||||
r = d.record
|
||||
key = (r.table, r.machine_id, r.identity[0], r.run_id)
|
||||
groups.setdefault(key, []).append(d)
|
||||
proposed_runs = unresolved_runs = corrected_segments = unresolved_segments = 0
|
||||
for peers in groups.values():
|
||||
proposed_runs += any(d.order is not None and d.order != d.record.production_order
|
||||
for d in peers)
|
||||
unresolved_runs += any(d.order is None for d in peers)
|
||||
streams = {}
|
||||
for d in peers:
|
||||
streams.setdefault(d.record.identity[3:], []).append(d)
|
||||
for stream in streams.values():
|
||||
previous = object()
|
||||
for d in sorted(stream, key=lambda d: d.record.timestamp.timestamp()):
|
||||
state = (d.order, d.order is not None and d.order != d.record.production_order)
|
||||
if state != previous:
|
||||
unresolved_segments += d.order is None
|
||||
corrected_segments += state[1]
|
||||
previous = state
|
||||
return (len(groups), proposed_runs, corrected_segments, unresolved_runs, unresolved_segments)
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Nightly reconciliation composition and operator output."""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import yaml
|
||||
|
||||
from production_analytics.context import build_enlyze_production_order
|
||||
from production_analytics.enlyze.exploration import ExplorationClient, ExplorationSettings
|
||||
from production_analytics.enlyze.gateway import EnlyzeApiGateway
|
||||
from production_analytics.erp import ErpProductionConfirmationGateway, ErpSettings
|
||||
from production_analytics.service.historical_reconcile import (
|
||||
BERLIN,
|
||||
grouped_counts,
|
||||
reconcile_machine,
|
||||
reconciliation_window,
|
||||
)
|
||||
from production_analytics.service.postgres_historical_reconcile import PostgresHistoricalRepository
|
||||
from production_analytics.service.postgres_material import PostgresSettings
|
||||
from production_analytics.service.shift_report_config import (
|
||||
_StrictLoader,
|
||||
load_shift_report_machines,
|
||||
)
|
||||
|
||||
|
||||
def _summarize_decisions(name, decisions, dry_run, verbose):
|
||||
"""Print run and source stream summaries from existing decisions."""
|
||||
corrections = {}
|
||||
unresolved = {}
|
||||
for decision in decisions:
|
||||
record = decision.record
|
||||
if decision.order is None:
|
||||
if verbose:
|
||||
print(f"Unresolved {name} {record.identity}: {decision.reason}")
|
||||
# Keep distinct physical runs and source streams separate, even when
|
||||
# they share the same unresolved reason.
|
||||
key = (decision.reason, record.table, record.identity[0], record.run_id,
|
||||
record.identity[3:])
|
||||
groups = unresolved
|
||||
elif decision.order != record.production_order:
|
||||
if verbose:
|
||||
print(f"{'Proposed' if dry_run else 'Corrected'} {name} "
|
||||
f"{record.table} {record.identity}: "
|
||||
f"{record.production_order} -> {decision.order}; {decision.reason}")
|
||||
prefix = "closed ENLYZE run "
|
||||
run_uuid = (decision.reason[len(prefix):].split(" [", 1)[0]
|
||||
if decision.reason.startswith(prefix) else "unknown")
|
||||
key = (record.production_order, decision.order, run_uuid)
|
||||
groups = corrections
|
||||
else:
|
||||
continue
|
||||
if key not in groups:
|
||||
groups[key] = [0, record.timestamp, record.timestamp]
|
||||
group = groups[key]
|
||||
group[0] += 1
|
||||
group[1] = min(group[1], record.timestamp)
|
||||
group[2] = max(group[2], record.timestamp)
|
||||
|
||||
action = "proposed" if dry_run else "corrected"
|
||||
for (old, new, run_uuid), (count, _first, _last) in corrections.items():
|
||||
print(f"{name} | {action}: {old} -> {new} | ENLYZE run {run_uuid} | "
|
||||
f"{count} records")
|
||||
for (reason, table, calculation, run_id, stream), (count, first, last) in unresolved.items():
|
||||
source = f"{table}/{calculation}"
|
||||
if stream:
|
||||
source += "/" + "/".join(map(str, stream))
|
||||
print(f"{name} | {reason} | physical run {run_id} | source {source} | "
|
||||
f"{count} records | {first.isoformat()} -> {last.isoformat()}")
|
||||
|
||||
|
||||
def run(args, environment):
|
||||
start, end = reconciliation_window(datetime.now(BERLIN), args.lookback_days)
|
||||
machines = {name: config for name, config in load_shift_report_machines(args.config).items()
|
||||
if config.capabilities.material}
|
||||
with args.order_formats.open(encoding="utf-8") as stream:
|
||||
formats = yaml.load(stream, Loader=_StrictLoader)
|
||||
if not isinstance(formats, dict) or set(formats) != set(machines):
|
||||
raise ValueError("Order formats must map every material machine name exactly once")
|
||||
for template in formats.values():
|
||||
if not isinstance(template, str):
|
||||
raise ValueError("Order formats must be strings")
|
||||
build_enlyze_production_order("1", template)
|
||||
repository = PostgresHistoricalRepository(PostgresSettings.from_environment(environment))
|
||||
source = EnlyzeApiGateway(ExplorationClient(ExplorationSettings.from_environment(environment)))
|
||||
erp = ErpProductionConfirmationGateway(ErpSettings.from_environment(environment))
|
||||
print("Historical reconciliation" + (" (DRY RUN)" if args.dry_run else ""))
|
||||
print(f"Window: {start.isoformat()} to {end.isoformat()} (exclusive)")
|
||||
grouped = [0] * 5
|
||||
inspected = corrections = unresolved = unchanged = failures = 0
|
||||
for name, config in machines.items():
|
||||
try:
|
||||
decisions, applied = reconcile_machine(
|
||||
repository, source, erp, config, formats[name], start, end, args.dry_run,
|
||||
)
|
||||
grouped = [a + b for a, b in zip(grouped, grouped_counts(decisions))]
|
||||
inspected += len(decisions)
|
||||
proposed = 0
|
||||
for d in decisions:
|
||||
if d.order is None:
|
||||
unresolved += 1
|
||||
elif d.order == d.record.production_order:
|
||||
unchanged += 1
|
||||
else:
|
||||
proposed += 1
|
||||
_summarize_decisions(name, decisions, args.dry_run, getattr(args, "verbose", False))
|
||||
corrections += proposed if args.dry_run else applied
|
||||
except Exception as exc:
|
||||
failures += 1
|
||||
print(f"FAILED {name}: {type(exc).__name__}: {exc}; machine transaction rolled back")
|
||||
print(f"Machines checked: {len(machines)}\nRecords inspected: {inspected}")
|
||||
print(f"Corrections {'proposed' if args.dry_run else 'applied'}: {corrections}")
|
||||
print(f"Ambiguous/unresolved: {unresolved}\nUnchanged: {unchanged}\nFailures: {failures}")
|
||||
print(f"Physical runs inspected: {grouped[0]}\nRuns with proposed corrections: {grouped[1]}")
|
||||
label = "proposed" if args.dry_run else "corrected"
|
||||
print(f"Order segments {label}: {grouped[2]}")
|
||||
print(f"Unresolved runs: {grouped[3]}\nUnresolved segments: {grouped[4]}")
|
||||
return 1 if failures else 0
|
||||
@@ -1,18 +1,45 @@
|
||||
"""ERP nominal-width resolution for an explicitly matched production order."""
|
||||
|
||||
import logging
|
||||
|
||||
from production_analytics.calculations.config import finite_number
|
||||
from production_analytics.context import build_enlyze_production_order, extract_nominal_width_m
|
||||
from production_analytics.erp import ErpWorkplaceStatusGateway
|
||||
from production_analytics.erp import ErpReadError, ErpWorkplaceStatusGateway
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ErpNominalWidthProvider:
|
||||
def __init__(
|
||||
self, gateway: ErpWorkplaceStatusGateway, *, workplace: str, format_template: str,
|
||||
fallback_nominal_width_m: float | None = None,
|
||||
) -> None:
|
||||
self.gateway = gateway
|
||||
self.workplace = workplace
|
||||
self.format_template = format_template
|
||||
self.fallback_nominal_width_m = (
|
||||
None if fallback_nominal_width_m is None else finite_number(
|
||||
fallback_nominal_width_m, "fallback_nominal_width_m", positive=True,
|
||||
)
|
||||
)
|
||||
self._warned_fallback_orders: set[str] = set()
|
||||
|
||||
def __call__(self, production_order: str) -> float:
|
||||
try:
|
||||
return self._resolve_erp_width(production_order)
|
||||
except (ValueError, ErpReadError) as exc:
|
||||
if self.fallback_nominal_width_m is None:
|
||||
raise
|
||||
if production_order not in self._warned_fallback_orders:
|
||||
logger.warning(
|
||||
"ERP nominal-width resolution failed for ENLYZE production order %r: %s; "
|
||||
"using fallback nominal width %s m",
|
||||
production_order, exc, self.fallback_nominal_width_m,
|
||||
)
|
||||
self._warned_fallback_orders.add(production_order)
|
||||
return self.fallback_nominal_width_m
|
||||
|
||||
def _resolve_erp_width(self, production_order: str) -> float:
|
||||
status = self.gateway.get_current_workplace_status(self.workplace)
|
||||
if (status is None
|
||||
or status.workplace.strip().casefold() != self.workplace.strip().casefold()
|
||||
|
||||
@@ -86,6 +86,7 @@ def build_material_runner(
|
||||
ErpWorkplaceStatusGateway(ErpSettings.from_secret_file(erp_secrets_file)),
|
||||
workplace=calculation.erp_workplace,
|
||||
format_template=calculation.production_order_format,
|
||||
fallback_nominal_width_m=calculation.fallback_nominal_width_m,
|
||||
),
|
||||
)
|
||||
if calculation.source_mode == "linear_signal_discharge":
|
||||
|
||||
@@ -34,18 +34,19 @@ class PostgresDowntimeRepository:
|
||||
def get_events(
|
||||
self, *, machine_id: str, start: datetime, end: datetime
|
||||
) -> list[ShiftDowntimeEvent]:
|
||||
"""Read raw machine intervals intersecting [start, end), independent of orders."""
|
||||
"""Read effective machine intervals intersecting [start, end)."""
|
||||
validate_downtime_window(machine_id=machine_id, start=start, end=end)
|
||||
try:
|
||||
with self._connect() as connection:
|
||||
rows = connection.execute(
|
||||
"""SELECT external_id, machine_id, source_start, source_end,
|
||||
reason_id, reason_name, reason_description, reason_group,
|
||||
category, comment
|
||||
category, comment, attributed_start, attributed_end
|
||||
FROM production_downtime_events
|
||||
WHERE machine_id = %s AND source_start < %s
|
||||
AND (source_end IS NULL OR source_end > %s)
|
||||
ORDER BY source_start, external_id""",
|
||||
WHERE machine_id = %s AND COALESCE(attributed_start, source_start) < %s
|
||||
AND (COALESCE(attributed_end, source_end) IS NULL
|
||||
OR COALESCE(attributed_end, source_end) > %s)
|
||||
ORDER BY COALESCE(attributed_start, source_start), external_id""",
|
||||
(machine_id, end, start),
|
||||
).fetchall()
|
||||
except Exception:
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Transactional attribution-only updates with an atomic audit trail."""
|
||||
|
||||
from contextlib import nullcontext
|
||||
from dataclasses import replace
|
||||
|
||||
import psycopg
|
||||
from psycopg import sql
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from production_analytics.service.historical_reconcile import HistoricalRecord
|
||||
|
||||
TABLES = {
|
||||
"material_consumption_snapshots": ("calculation_id", "machine_id", "timestamp"),
|
||||
"material_application_snapshots": ("calculation_id", "machine_id", "timestamp"),
|
||||
"channel_material_consumption_snapshots": (
|
||||
"calculation_id", "machine_id", "timestamp", "extruder", "doser_channel",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
class PostgresHistoricalRepository:
|
||||
def __init__(self, settings):
|
||||
self.settings = settings
|
||||
|
||||
def connect(self):
|
||||
s = self.settings
|
||||
return psycopg.connect(host=s.host, port=s.port, dbname=s.dbname, user=s.user,
|
||||
password=s.password, connect_timeout=10,
|
||||
options="-c statement_timeout=30000")
|
||||
|
||||
def read(self, machine_id, start, end):
|
||||
result = []
|
||||
with self.connect() as connection:
|
||||
for table, keys in TABLES.items():
|
||||
rows = connection.execute(sql.SQL(
|
||||
"SELECT {}, production_order, run_id FROM {} "
|
||||
"WHERE machine_id = %s AND timestamp >= %s AND timestamp < %s"
|
||||
).format(sql.SQL(', ').join(map(sql.Identifier, keys)), sql.Identifier(table)),
|
||||
(machine_id, start, end)).fetchall()
|
||||
result.extend(HistoricalRecord(table, tuple(row[:-2]), machine_id, row[2],
|
||||
row[-2], row[-1]) for row in rows)
|
||||
return result
|
||||
|
||||
def guard_runs(self, decisions, connection=None):
|
||||
"""Reject partial run repairs, including historical rows outside the window."""
|
||||
groups = {}
|
||||
for d in decisions:
|
||||
r = d.record
|
||||
groups.setdefault((r.table, r.machine_id, r.identity[0], r.run_id), []).append(d)
|
||||
blocked = set()
|
||||
context = self.connect() if connection is None else nullcontext(connection)
|
||||
with context as connection:
|
||||
for key, peers in groups.items():
|
||||
corrections = [d for d in peers if d.order is not None
|
||||
and d.order != d.record.production_order]
|
||||
if not corrections:
|
||||
continue
|
||||
table, machine, calculation, run = key
|
||||
count = connection.execute(sql.SQL(
|
||||
"SELECT count(*) FROM {} WHERE machine_id = %s "
|
||||
"AND calculation_id = %s AND run_id = %s"
|
||||
).format(sql.Identifier(table)), (machine, calculation, run)).fetchone()[0]
|
||||
if count != len(peers) or any(d.order is None for d in peers):
|
||||
blocked.add(key)
|
||||
return [replace(d, order=None,
|
||||
reason="unresolved: partial or unresolved cumulative run")
|
||||
if (d.record.table, d.record.machine_id, d.record.identity[0],
|
||||
d.record.run_id) in blocked else d for d in decisions]
|
||||
|
||||
def apply(self, decisions):
|
||||
count = 0
|
||||
with self.connect() as connection:
|
||||
# Serialize this job; concurrent changes fail rather than silently overwrite.
|
||||
connection.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
|
||||
connection.execute("SELECT pg_advisory_xact_lock(704301)")
|
||||
if self.guard_runs(decisions, connection) != decisions:
|
||||
raise RuntimeError("Historical run changed concurrently; retry reconciliation")
|
||||
for d in decisions:
|
||||
r = d.record
|
||||
if d.order is None or d.order == r.production_order:
|
||||
continue
|
||||
keys = TABLES[r.table]
|
||||
predicate = sql.SQL(' AND ').join(
|
||||
sql.SQL('{} = %s').format(sql.Identifier(k)) for k in keys)
|
||||
action = "updated"
|
||||
retained_run_id = None
|
||||
if r.table == "material_application_snapshots":
|
||||
source = connection.execute(sql.SQL(
|
||||
"SELECT application_g_m2 FROM {} WHERE {} "
|
||||
"AND production_order = %s AND run_id = %s FOR UPDATE"
|
||||
).format(sql.Identifier(r.table), predicate),
|
||||
(*r.identity, r.production_order, r.run_id)).fetchone()
|
||||
if source is None:
|
||||
raise RuntimeError(
|
||||
"Historical record changed concurrently; retry reconciliation"
|
||||
)
|
||||
target = connection.execute(
|
||||
"""SELECT run_id, application_g_m2 IS NOT DISTINCT FROM %s
|
||||
FROM material_application_snapshots
|
||||
WHERE calculation_id = %s AND machine_id = %s
|
||||
AND timestamp = %s AND production_order = %s FOR UPDATE""",
|
||||
(source[0], *r.identity, d.order)).fetchone()
|
||||
if target is not None:
|
||||
if (not target[1] or d.desired_run_id is None
|
||||
or target[0] != d.desired_run_id):
|
||||
raise RuntimeError(
|
||||
"Historical application collision has conflicting measurement "
|
||||
"or unexpected target run; machine transaction rolled back"
|
||||
)
|
||||
deleted = connection.execute(sql.SQL(
|
||||
"DELETE FROM {} WHERE {} AND production_order = %s "
|
||||
"AND run_id = %s RETURNING timestamp"
|
||||
).format(sql.Identifier(r.table), predicate),
|
||||
(*r.identity, r.production_order, r.run_id)).fetchone()
|
||||
if deleted is None:
|
||||
raise RuntimeError(
|
||||
"Historical record changed concurrently; retry reconciliation"
|
||||
)
|
||||
action = "deduplicated"
|
||||
retained_run_id = target[0]
|
||||
if action == "updated":
|
||||
changed = connection.execute(sql.SQL(
|
||||
"UPDATE {} SET production_order = %s WHERE {} "
|
||||
"AND production_order = %s AND run_id = %s RETURNING timestamp"
|
||||
).format(sql.Identifier(r.table), predicate),
|
||||
(d.order, *r.identity, r.production_order, r.run_id)).fetchone()
|
||||
if changed is None:
|
||||
raise RuntimeError(
|
||||
"Historical record changed concurrently; retry reconciliation"
|
||||
)
|
||||
connection.execute(
|
||||
"""INSERT INTO historical_assignment_audit
|
||||
(machine_id, source_table, record_identity, previous_order, new_order,
|
||||
run_id, reason, action, retained_run_id)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)""",
|
||||
(r.machine_id, r.table, Jsonb(dict(zip(keys, map(str, r.identity)))),
|
||||
r.production_order, d.order, r.run_id, d.reason, action, retained_run_id))
|
||||
count += 1
|
||||
return count
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Protocol
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from production_analytics.calculations.shift_production import (
|
||||
ShiftProductionSummary,
|
||||
@@ -13,7 +14,8 @@ from production_analytics.erp import ProductionConfirmation
|
||||
|
||||
class ProductionConfirmationReader(Protocol):
|
||||
def get_confirmations(
|
||||
self, *, workplace: str, start: datetime, end: datetime
|
||||
self, *, workplace: str, start: datetime, end: datetime,
|
||||
timezone: ZoneInfo | None = None,
|
||||
) -> list[ProductionConfirmation]: ...
|
||||
|
||||
|
||||
@@ -22,8 +24,12 @@ class ShiftProductionService:
|
||||
self.gateway = gateway
|
||||
|
||||
def summarize(
|
||||
self, *, workplace: str, start: datetime, end: datetime
|
||||
self, *, workplace: str, start: datetime, end: datetime,
|
||||
timezone: ZoneInfo | None = None,
|
||||
) -> ShiftProductionSummary:
|
||||
workplace = validate_shift_window(workplace=workplace, start=start, end=end)
|
||||
confirmations = self.gateway.get_confirmations(workplace=workplace, start=start, end=end)
|
||||
kwargs = {"workplace": workplace, "start": start, "end": end}
|
||||
if timezone is not None:
|
||||
kwargs["timezone"] = timezone
|
||||
confirmations = self.gateway.get_confirmations(**kwargs)
|
||||
return aggregate_shift_production(confirmations, workplace=workplace, start=start, end=end)
|
||||
@@ -3,8 +3,10 @@
|
||||
from collections.abc import Mapping
|
||||
from datetime import datetime
|
||||
from types import MappingProxyType
|
||||
from typing import Protocol
|
||||
|
||||
from production_analytics.calculations.shift_report import SHIFT_TIMEZONE, ShiftReport
|
||||
from production_analytics.calculations.shift_material import ShiftMaterialSummary
|
||||
from production_analytics.calculations.shift_report import ShiftReport
|
||||
from production_analytics.calculations.shift_speed import validate_speed_window
|
||||
from production_analytics.service.shift_downtime import ShiftDowntimeService
|
||||
from production_analytics.service.shift_material import (
|
||||
@@ -16,12 +18,21 @@ from production_analytics.service.shift_report_config import ShiftReportMachineC
|
||||
from production_analytics.service.shift_speed import ShiftSpeedService
|
||||
|
||||
|
||||
class ShiftMaterialAllocator(Protocol):
|
||||
def allocate(self, measured: ShiftMaterialSummary) -> ShiftMaterialSummary: ...
|
||||
|
||||
|
||||
class ShiftReportService:
|
||||
def __init__(
|
||||
self, *, machines: Mapping[str, ShiftReportMachineConfig],
|
||||
production: ShiftProductionService, downtime: ShiftDowntimeService,
|
||||
materials: ShiftMaterialService, channel_materials: ShiftChannelMaterialService,
|
||||
self,
|
||||
*,
|
||||
machines: Mapping[str, ShiftReportMachineConfig],
|
||||
production: ShiftProductionService,
|
||||
downtime: ShiftDowntimeService,
|
||||
materials: ShiftMaterialService,
|
||||
channel_materials: ShiftChannelMaterialService,
|
||||
speed: ShiftSpeedService,
|
||||
material_allocators: Mapping[str, ShiftMaterialAllocator] | None = None,
|
||||
) -> None:
|
||||
self.machines = MappingProxyType(dict(machines))
|
||||
self.production = production
|
||||
@@ -29,26 +40,47 @@ class ShiftReportService:
|
||||
self.materials = materials
|
||||
self.channel_materials = channel_materials
|
||||
self.speed = speed
|
||||
self.material_allocators = MappingProxyType(dict(material_allocators or {}))
|
||||
|
||||
def build(self, *, machine_name: str, start: datetime, end: datetime) -> ShiftReport:
|
||||
validate_speed_window(start, end)
|
||||
if not isinstance(machine_name, str) or machine_name not in self.machines:
|
||||
raise ValueError("Unknown shift-report machine")
|
||||
config = self.machines[machine_name]
|
||||
start, end = start.astimezone(SHIFT_TIMEZONE), end.astimezone(SHIFT_TIMEZONE)
|
||||
start, end = start.astimezone(config.timezone), end.astimezone(config.timezone)
|
||||
production = self.production.summarize(
|
||||
workplace=config.erp_workplace, start=start, end=end,
|
||||
)
|
||||
downtime = self.downtime.summarize(machine_id=config.machine_id, start=start, end=end)
|
||||
material_service = (
|
||||
self.channel_materials if config.material.mode == "channel" else self.materials
|
||||
)
|
||||
materials = material_service.summarize(
|
||||
machine_id=config.machine_id, calculation_ids=config.material.calculation_ids,
|
||||
start=start, end=end,
|
||||
)
|
||||
speed = self.speed.summarize(config=config.speed, start=start, end=end)
|
||||
workplace=config.erp_workplace,
|
||||
start=start,
|
||||
end=end,
|
||||
timezone=config.timezone,
|
||||
) if config.capabilities.production else None
|
||||
downtime = (self.downtime.summarize(machine_id=config.machine_id, start=start, end=end)
|
||||
if config.capabilities.downtime else None)
|
||||
materials = None
|
||||
if config.material is not None:
|
||||
material_service = (
|
||||
self.channel_materials if config.material.mode == "channel" else self.materials
|
||||
)
|
||||
materials = material_service.summarize(
|
||||
machine_id=config.machine_id,
|
||||
calculation_ids=config.material.calculation_ids,
|
||||
start=start,
|
||||
end=end,
|
||||
)
|
||||
if machine_name in self.material_allocators:
|
||||
materials = self.material_allocators[machine_name].allocate(materials)
|
||||
speed = (self.speed.summarize(config=config.speed, start=start, end=end)
|
||||
if config.speed is not None else None)
|
||||
return ShiftReport(
|
||||
machine_name=machine_name, machine_id=config.machine_id, start=start, end=end,
|
||||
production=production, downtime=downtime, materials=materials, speed=speed,
|
||||
machine_name=machine_name,
|
||||
machine_id=config.machine_id,
|
||||
display_name=config.display_name,
|
||||
site=config.site,
|
||||
timezone=config.timezone,
|
||||
start=start,
|
||||
end=end,
|
||||
production=production,
|
||||
downtime=downtime,
|
||||
materials=materials,
|
||||
speed=speed,
|
||||
)
|
||||
@@ -1,22 +1,55 @@
|
||||
"""Strict, self-contained configuration for shift-report composition."""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from types import MappingProxyType
|
||||
from typing import Literal
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
import yaml
|
||||
|
||||
from production_analytics.calculations.shift_speed import ShiftSpeedConfig
|
||||
from production_analytics.calculations.shift_speed import NumericDwellGate, ShiftSpeedConfig
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftReportSiteConfig:
|
||||
display_name: str
|
||||
timezone: ZoneInfo
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
_text(self.display_name, "site.display_name")
|
||||
if not isinstance(self.timezone, ZoneInfo):
|
||||
raise ValueError("site.timezone must be a valid IANA timezone")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftReportCapabilities:
|
||||
production: bool
|
||||
downtime: bool
|
||||
material: bool
|
||||
speed: bool
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if any(type(value) is not bool for value in (
|
||||
self.production, self.downtime, self.material, self.speed,
|
||||
)):
|
||||
raise ValueError("capabilities must contain booleans")
|
||||
if not any((self.production, self.downtime, self.material, self.speed)):
|
||||
raise ValueError("at least one capability must be enabled")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftReportMaterialConfig:
|
||||
mode: Literal["cumulative", "channel"]
|
||||
calculation_ids: tuple[str, ...]
|
||||
allocation: Literal["none", "erp_fiber_share"] = "none"
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.mode not in ("cumulative", "channel"):
|
||||
raise ValueError("material.mode must be cumulative or channel")
|
||||
if self.allocation not in ("none", "erp_fiber_share"):
|
||||
raise ValueError("material.allocation must be none or erp_fiber_share")
|
||||
if not isinstance(self.calculation_ids, tuple) or not self.calculation_ids:
|
||||
raise ValueError("material.calculation_ids must be a non-empty tuple")
|
||||
for calculation_id in self.calculation_ids:
|
||||
@@ -27,19 +60,48 @@ class ShiftReportMaterialConfig:
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftReportMachineConfig:
|
||||
machine_id: str
|
||||
display_name: str
|
||||
site: str
|
||||
machine_id: str | None
|
||||
erp_workplace: str
|
||||
material: ShiftReportMaterialConfig
|
||||
speed: ShiftSpeedConfig
|
||||
capabilities: ShiftReportCapabilities
|
||||
timezone: ZoneInfo
|
||||
material: ShiftReportMaterialConfig | None = None
|
||||
speed: ShiftSpeedConfig | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
_text(self.machine_id, "machine_id")
|
||||
_text(self.erp_workplace, "erp_workplace")
|
||||
if not isinstance(self.material, ShiftReportMaterialConfig):
|
||||
for name in ("display_name", "site", "erp_workplace"):
|
||||
_text(getattr(self, name), name)
|
||||
if not isinstance(self.timezone, ZoneInfo):
|
||||
raise ValueError("machine timezone must be a valid IANA timezone")
|
||||
if not isinstance(self.capabilities, ShiftReportCapabilities):
|
||||
raise ValueError("capabilities must be a ShiftReportCapabilities")
|
||||
if self.machine_id is not None:
|
||||
_text(self.machine_id, "machine_id")
|
||||
elif any((self.capabilities.downtime, self.capabilities.material,
|
||||
self.capabilities.speed)):
|
||||
raise ValueError("machine_id is required for downtime, material, or speed")
|
||||
if self.capabilities.material != (self.material is not None):
|
||||
raise ValueError("material configuration must match material capability")
|
||||
if self.capabilities.speed != (self.speed is not None):
|
||||
raise ValueError("speed configuration must match speed capability")
|
||||
if self.material is not None and not isinstance(self.material, ShiftReportMaterialConfig):
|
||||
raise ValueError("material must be a ShiftReportMaterialConfig")
|
||||
if not isinstance(self.speed, ShiftSpeedConfig) or self.speed.machine_id != self.machine_id:
|
||||
raise ValueError("speed configuration must refer to the report machine")
|
||||
_text(self.speed.signal, "speed.signal")
|
||||
if self.speed is not None:
|
||||
if (not isinstance(self.speed, ShiftSpeedConfig)
|
||||
or self.speed.machine_id != self.machine_id):
|
||||
raise ValueError("speed configuration must refer to the report machine")
|
||||
_text(self.speed.signal, "speed.signal")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftReportConfig:
|
||||
sites: Mapping[str, ShiftReportSiteConfig]
|
||||
machines: Mapping[str, ShiftReportMachineConfig]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "sites", MappingProxyType(dict(self.sites)))
|
||||
object.__setattr__(self, "machines", MappingProxyType(dict(self.machines)))
|
||||
|
||||
|
||||
class _StrictLoader(yaml.SafeLoader):
|
||||
@@ -70,36 +132,100 @@ def _fields(value: object, expected: set[str], name: str) -> dict:
|
||||
return value
|
||||
|
||||
|
||||
def load_shift_report_machines(path: str | Path) -> dict[str, ShiftReportMachineConfig]:
|
||||
def load_shift_report_config(path: str | Path) -> ShiftReportConfig:
|
||||
try:
|
||||
with Path(path).open(encoding="utf-8") as stream:
|
||||
document = yaml.load(stream, Loader=_StrictLoader)
|
||||
except (OSError, UnicodeError, yaml.YAMLError) as exc:
|
||||
raise ValueError("Cannot read shift-report machine configuration") from exc
|
||||
document = _fields(document, {"machines"}, "Shift-report configuration")
|
||||
document = _fields(document, {"sites", "machines"}, "Shift-report configuration")
|
||||
raw_sites = document["sites"]
|
||||
if not isinstance(raw_sites, dict) or not raw_sites:
|
||||
raise ValueError("sites must be a non-empty mapping")
|
||||
sites = {}
|
||||
for key, entry in raw_sites.items():
|
||||
_text(key, "site key")
|
||||
entry = _fields(entry, {"display_name", "timezone"}, f"site {key}")
|
||||
_text(entry["timezone"], "site.timezone")
|
||||
try:
|
||||
timezone = ZoneInfo(entry["timezone"])
|
||||
except (ZoneInfoNotFoundError, ValueError, TypeError) as exc:
|
||||
raise ValueError("site.timezone must be a valid IANA timezone") from exc
|
||||
sites[key] = ShiftReportSiteConfig(entry["display_name"], timezone)
|
||||
machines = document["machines"]
|
||||
if not isinstance(machines, dict) or not machines:
|
||||
raise ValueError("machines must be a non-empty mapping")
|
||||
result = {}
|
||||
for name, entry in machines.items():
|
||||
_text(name, "machine name")
|
||||
entry = _fields(entry, {"machine_id", "erp_workplace", "material", "speed"}, name)
|
||||
material = _fields(entry["material"], {"mode", "calculation_ids"}, "material")
|
||||
ids = material["calculation_ids"]
|
||||
if not isinstance(ids, list):
|
||||
raise ValueError("material.calculation_ids must be a list")
|
||||
speed = _fields(
|
||||
entry["speed"], {"signal_ref", "signal", "unit", "production_gate_m_min"}, "speed",
|
||||
)
|
||||
required = {"display_name", "site", "erp_workplace", "capabilities"}
|
||||
if not isinstance(entry, dict) or not required <= set(entry) or set(entry) - (
|
||||
required | {"machine_id", "material", "speed"}
|
||||
):
|
||||
raise ValueError(f"{name} has missing or unknown fields")
|
||||
capabilities = _fields(entry["capabilities"],
|
||||
{"production", "downtime", "material", "speed"},
|
||||
"capabilities")
|
||||
capabilities = ShiftReportCapabilities(**capabilities)
|
||||
_text(entry["site"], "site")
|
||||
if entry["site"] not in sites:
|
||||
raise ValueError(f"{name} references an unknown site")
|
||||
if capabilities.material != ("material" in entry):
|
||||
raise ValueError("material configuration must match material capability")
|
||||
if capabilities.speed != ("speed" in entry):
|
||||
raise ValueError("speed configuration must match speed capability")
|
||||
material = None
|
||||
if capabilities.material:
|
||||
material_entry = entry["material"]
|
||||
if not isinstance(material_entry, dict) or not {"mode", "calculation_ids"} <= set(
|
||||
material_entry
|
||||
) or set(material_entry) - {"mode", "calculation_ids", "allocation"}:
|
||||
raise ValueError("material has missing or unknown fields")
|
||||
ids = material_entry["calculation_ids"]
|
||||
if not isinstance(ids, list):
|
||||
raise ValueError("material.calculation_ids must be a list")
|
||||
material = ShiftReportMaterialConfig(
|
||||
material_entry["mode"], tuple(ids), material_entry.get("allocation", "none")
|
||||
)
|
||||
speed = None
|
||||
if capabilities.speed:
|
||||
speed_entry = entry["speed"]
|
||||
required_speed = {"signal_ref", "signal", "unit"}
|
||||
optional_speed = {"production_gate_m_min", "running_signal_ref", "running_when",
|
||||
"numeric_dwell_gate"}
|
||||
if (not isinstance(speed_entry, dict) or not required_speed <= set(speed_entry)
|
||||
or set(speed_entry) - (required_speed | optional_speed)):
|
||||
raise ValueError("speed has missing or unknown fields")
|
||||
if "running_when" in speed_entry and not speed_entry.get("running_signal_ref"):
|
||||
raise ValueError("speed.running_when requires running_signal_ref")
|
||||
dwell = None
|
||||
if "numeric_dwell_gate" in speed_entry:
|
||||
dwell_entry = _fields(
|
||||
speed_entry["numeric_dwell_gate"],
|
||||
{"signal_ref", "threshold", "comparison", "minimum_duration_seconds"},
|
||||
"numeric_dwell_gate",
|
||||
)
|
||||
dwell = NumericDwellGate(**dwell_entry)
|
||||
speed = ShiftSpeedConfig(
|
||||
machine_id=entry.get("machine_id"), speed_signal_ref=speed_entry["signal_ref"],
|
||||
signal=speed_entry["signal"], unit=speed_entry["unit"],
|
||||
production_gate_m_min=speed_entry.get("production_gate_m_min"),
|
||||
running_signal_ref=speed_entry.get("running_signal_ref"),
|
||||
running_when=speed_entry.get("running_when", True),
|
||||
numeric_dwell_gate=dwell,
|
||||
)
|
||||
result[name] = ShiftReportMachineConfig(
|
||||
machine_id=entry["machine_id"], erp_workplace=entry["erp_workplace"],
|
||||
material=ShiftReportMaterialConfig(material["mode"], tuple(ids)),
|
||||
speed=ShiftSpeedConfig(
|
||||
machine_id=entry["machine_id"], speed_signal_ref=speed["signal_ref"],
|
||||
signal=speed["signal"], unit=speed["unit"],
|
||||
production_gate_m_min=speed["production_gate_m_min"],
|
||||
),
|
||||
display_name=entry["display_name"], site=entry["site"],
|
||||
machine_id=entry.get("machine_id"), erp_workplace=entry["erp_workplace"],
|
||||
capabilities=capabilities, timezone=sites[entry["site"]].timezone,
|
||||
material=material, speed=speed,
|
||||
)
|
||||
if len({config.machine_id for config in result.values()}) != len(result):
|
||||
ids = [config.machine_id for config in result.values() if config.machine_id is not None]
|
||||
if len(set(ids)) != len(ids):
|
||||
raise ValueError("Shift-report machine IDs must be unique")
|
||||
return result
|
||||
return ShiftReportConfig(sites, result)
|
||||
|
||||
|
||||
def load_shift_report_machines(path: str | Path) -> dict[str, ShiftReportMachineConfig]:
|
||||
"""Compatibility view used by report entry points and historical reconciliation."""
|
||||
return dict(load_shift_report_config(path).machines)
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Construct read-only sources for one explicit shift report."""
|
||||
|
||||
from collections.abc import Mapping
|
||||
|
||||
from production_analytics.enlyze.exploration import ExplorationClient, ExplorationSettings
|
||||
from production_analytics.enlyze.gateway import EnlyzeApiGateway
|
||||
from production_analytics.erp import (
|
||||
ErpFiberBookingGateway,
|
||||
ErpProductionConfirmationGateway,
|
||||
ErpSettings,
|
||||
)
|
||||
from production_analytics.service.fiber_allocation import K7FiberAllocationService
|
||||
from production_analytics.service.postgres_downtime import PostgresDowntimeRepository
|
||||
from production_analytics.service.postgres_material import PostgresSettings
|
||||
from production_analytics.service.postgres_shift_material import (
|
||||
PostgresShiftChannelMaterialRepository,
|
||||
PostgresShiftMaterialRepository,
|
||||
)
|
||||
from production_analytics.service.shift_downtime import ShiftDowntimeService
|
||||
from production_analytics.service.shift_material import (
|
||||
ShiftChannelMaterialService,
|
||||
ShiftMaterialService,
|
||||
)
|
||||
from production_analytics.service.shift_production import ShiftProductionService
|
||||
from production_analytics.service.shift_report import ShiftReportService
|
||||
from production_analytics.service.shift_report_config import ShiftReportMachineConfig
|
||||
from production_analytics.service.shift_speed import ShiftSpeedService
|
||||
|
||||
|
||||
def build_shift_report_service(
|
||||
machines: Mapping[str, ShiftReportMachineConfig],
|
||||
environment: Mapping[str, str],
|
||||
) -> ShiftReportService:
|
||||
postgres = PostgresSettings.from_environment(environment)
|
||||
erp = ErpSettings.from_environment(environment)
|
||||
enlyze = ExplorationSettings.from_environment(environment)
|
||||
allocators = {
|
||||
name: K7FiberAllocationService(ErpFiberBookingGateway(erp))
|
||||
for name, config in machines.items()
|
||||
if config.material is not None and config.material.allocation == "erp_fiber_share"
|
||||
}
|
||||
return ShiftReportService(
|
||||
machines=machines,
|
||||
material_allocators=allocators,
|
||||
production=ShiftProductionService(ErpProductionConfirmationGateway(erp)),
|
||||
downtime=ShiftDowntimeService(PostgresDowntimeRepository(postgres)),
|
||||
materials=ShiftMaterialService(PostgresShiftMaterialRepository(postgres)),
|
||||
channel_materials=ShiftChannelMaterialService(
|
||||
PostgresShiftChannelMaterialRepository(postgres)
|
||||
),
|
||||
speed=ShiftSpeedService(EnlyzeApiGateway(ExplorationClient(enlyze))),
|
||||
)
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Compose bounded ENLYZE speed reads with the pure running-speed KPI."""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Protocol
|
||||
|
||||
from production_analytics.calculations.shift_speed import (
|
||||
@@ -15,6 +15,8 @@ from production_analytics.calculations.shift_speed import (
|
||||
class ShiftSpeedReader(Protocol):
|
||||
def get_speed_samples(
|
||||
self, *, machine_id: str, speed_signal_ref: str, start: datetime, end: datetime,
|
||||
running_signal_ref: str | None = None,
|
||||
numeric_gate_signal_ref: str | None = None,
|
||||
) -> list[ShiftSpeedSample]: ...
|
||||
|
||||
|
||||
@@ -26,8 +28,14 @@ class ShiftSpeedService:
|
||||
self, *, config: ShiftSpeedConfig, start: datetime, end: datetime,
|
||||
) -> ShiftSpeedSummary:
|
||||
validate_speed_window(start, end)
|
||||
samples = self.gateway.get_speed_samples(
|
||||
machine_id=config.machine_id, speed_signal_ref=config.speed_signal_ref,
|
||||
start=start, end=end,
|
||||
)
|
||||
kwargs = {"machine_id": config.machine_id, "speed_signal_ref": config.speed_signal_ref,
|
||||
"start": start, "end": end}
|
||||
if config.running_signal_ref is not None:
|
||||
kwargs["running_signal_ref"] = config.running_signal_ref
|
||||
if config.numeric_dwell_gate is not None:
|
||||
kwargs["numeric_gate_signal_ref"] = config.numeric_dwell_gate.signal_ref
|
||||
dwell = timedelta(seconds=config.numeric_dwell_gate.minimum_duration_seconds)
|
||||
kwargs["start"] = start.astimezone(UTC) - dwell
|
||||
kwargs["end"] = end.astimezone(UTC) + dwell
|
||||
samples = self.gateway.get_speed_samples(**kwargs)
|
||||
return aggregate_shift_speed(samples, config=config, start=start, end=end)
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Read-only live shift-report WSGI interface; no report cache or persistence."""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
from collections.abc import Callable, Mapping
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs
|
||||
from wsgiref.simple_server import make_server
|
||||
|
||||
from production_analytics.calculations.shift_report import (
|
||||
most_recent_completed_shift,
|
||||
shift_report_window,
|
||||
)
|
||||
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
|
||||
from production_analytics.service.shift_report_runtime import build_shift_report_service
|
||||
|
||||
SHIFT_LABELS = {"early": "Frühschicht", "late": "Spätschicht", "night": "Nachtschicht"}
|
||||
|
||||
|
||||
def create_app(machines: Mapping, service_factory: Callable, *, sites: Mapping | None = None,
|
||||
clock=None):
|
||||
"""Inject the configured service factory and clock without connecting at startup."""
|
||||
clock = clock or (lambda: datetime.now(UTC))
|
||||
|
||||
def app(environ, start_response):
|
||||
headers = [("Cache-Control", "no-store"), ("X-Content-Type-Options", "nosniff")]
|
||||
status = "200 OK"
|
||||
content_type = "text/html; charset=utf-8"
|
||||
now = clock()
|
||||
machine = next(iter(machines))
|
||||
timezone = machines[machine].timezone
|
||||
day, shift = most_recent_completed_shift(now, timezone)
|
||||
error = None
|
||||
report = None
|
||||
generated_at = None
|
||||
if environ.get("PATH_INFO", "/") != "/":
|
||||
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."
|
||||
headers.append(("Allow", "GET"))
|
||||
else:
|
||||
try:
|
||||
params = parse_qs(
|
||||
environ.get("QUERY_STRING", ""), keep_blank_values=True, max_num_fields=10
|
||||
)
|
||||
if any(len(values) != 1 for values in params.values()):
|
||||
raise ValueError
|
||||
from datetime import date
|
||||
|
||||
machine = params.get("machine", [machine])[0]
|
||||
if machine not in machines:
|
||||
raise ValueError
|
||||
timezone = machines[machine].timezone
|
||||
default_day, default_shift = most_recent_completed_shift(now, timezone)
|
||||
day = date.fromisoformat(params.get("date", [default_day.isoformat()])[0])
|
||||
shift = params.get("shift", [default_shift])[0]
|
||||
output = params.get("format", ["html"])[0]
|
||||
if shift not in SHIFT_LABELS:
|
||||
raise ValueError
|
||||
if output not in ("html", "pdf"):
|
||||
raise ValueError
|
||||
start, end = shift_report_window(day, shift, timezone)
|
||||
except (ValueError, OverflowError):
|
||||
status = "400 Bad Request"
|
||||
error = "Ungültige Auswahl. Bitte Datum, Schicht und Maschine prüfen."
|
||||
else:
|
||||
try:
|
||||
report = service_factory().build(machine_name=machine, start=start, end=end)
|
||||
generated_at = clock().astimezone(timezone)
|
||||
if output == "pdf":
|
||||
payload = render_pdf(report)
|
||||
content_type = "application/pdf"
|
||||
# Filename excludes externally configured machine names.
|
||||
headers.append(
|
||||
(
|
||||
"Content-Disposition",
|
||||
f'attachment; filename="Schichtbericht-{day}-{shift}.pdf"',
|
||||
)
|
||||
)
|
||||
else:
|
||||
payload = None
|
||||
except Exception:
|
||||
status = "503 Service Unavailable"
|
||||
error = (
|
||||
"Schichtbericht konnte nicht erstellt werden. "
|
||||
"Bitte später erneut versuchen oder die Datenquellen prüfen lassen."
|
||||
)
|
||||
report = None
|
||||
if error or content_type != "application/pdf":
|
||||
payload = render_page(
|
||||
machines=machines,
|
||||
sites=sites,
|
||||
labels=SHIFT_LABELS,
|
||||
day=day,
|
||||
shift=shift,
|
||||
machine=machine,
|
||||
report=report,
|
||||
generated_at=generated_at,
|
||||
error=error,
|
||||
).encode("utf-8")
|
||||
headers.extend([("Content-Type", content_type), ("Content-Length", str(len(payload)))])
|
||||
start_response(status, headers)
|
||||
return [payload]
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
from production_analytics.enlyze.exploration import load_secret_file
|
||||
|
||||
parser = argparse.ArgumentParser(description="Live-Schichtberichte")
|
||||
parser.add_argument("--host", default="127.0.0.1")
|
||||
parser.add_argument(
|
||||
"--port", type=int, default=int(os.environ.get("SHIFT_REPORT_PORT", "8087"))
|
||||
)
|
||||
parser.add_argument("--config", type=Path, default=Path("config/shift-report-machines.yaml"))
|
||||
parser.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env"))
|
||||
parser.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env"))
|
||||
parser.add_argument("--db-secrets-file", type=Path, default=Path("secrets/postgres.env"))
|
||||
args = parser.parse_args(argv)
|
||||
config = load_shift_report_config(args.config)
|
||||
machines = config.machines
|
||||
|
||||
def service():
|
||||
environment = dict(os.environ)
|
||||
for path in (args.secrets_file, args.erp_secrets_file, args.db_secrets_file):
|
||||
environment.update(load_secret_file(path))
|
||||
return build_shift_report_service(machines, environment)
|
||||
|
||||
app = create_app(machines, service, sites=config.sites)
|
||||
with make_server(args.host, args.port, app) as server:
|
||||
print(f"Schichtberichte: http://{args.host}:{args.port}/", flush=True)
|
||||
server.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user